[
  {
    "path": ".clang-format",
    "content": "---\n# This section defines defaults for all languages. Currently we derive ANTLR style from LLVM.\nBasedOnStyle: LLVM\n# Only use clang-format for C++ for now.\nDisableFormat: true\n\n---\n# This section configures C++ formatting.\nLanguage: Cpp\nDisableFormat: false\nStandard: c++17\n# Prevent clang-format from attempting to pick the alignment and always use right alignment.\nDerivePointerAlignment: false\n# ANTLR existing style is to right align pointers and references.\nPointerAlignment: Right\nReferenceAlignment: Right\n# Some of ANTLR existing code is longer than the default 80, so use 100 for now.\nColumnLimit: 100\n# Historically ANTLR has used indentation within namespaces, so replicate it.\nNamespaceIndentation: Inner\n"
  },
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\ntab_width = 4\n\n[*.{java,stg}]\ncharset = utf-8\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nindent_style = tab\nij_java_else_on_new_line = true\n\n[*.{h,cpp}]\ncharset = utf-8\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nindent_style = space\nindent_size = 2\n"
  },
  {
    "path": ".gitattributes",
    "content": "# This rule applies to all files which don't match another line below\n* text=auto"
  },
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "content": "<!--\nAll ANTLR contributors provide implementation, maintenance and support for free.\nWe therefore kindly ask that before submitting any issue to ANTLR, you please check off these boxes:\n\n- [ ] I have reproduced my issue using the latest version of ANTLR\n- [ ] I have asked at [stackoverflow](http://stackoverflow.com/questions/tagged/antlr4)\n- [ ] Responses from the above seem to indicate that my issue could be an ANTLR bug\n- [ ] I have done a search of the existing issues to make sure I'm not sending in a duplicate\n\nPlease include the following information:\n - target information (Java, C++ ...)\n - smallest possible grammar and code that reproduces the behavior\n - description of the expected behavior and actual behavior\nPointers to suspicious code regions are also very welcome.\n-->\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!--\nThank you for proposing a contribution to the ANTLR project!\n\n(Please make sure your PR is in a branch other than dev or master\n and also make sure that you derive this branch from dev.)\n\nAs of 4.10, ANTLR uses the Linux Foundation's Developer\nCertificate of Origin, DCO, version 1.1. See either\nhttps://developercertificate.org/ or file \ncontributors-cert-of-origin.txt in the main directory.\n\nEach commit requires a \"signature\", which is simple as\nusing `-s` (not `-S`) to the git commit command: \n\ngit commit -s -m 'This is my commit message'\n\nGithub's pull request process enforces the sig and gives\ninstructions on how to fix any commits that lack the sig.\nSee https://github.com/apps/dco for more info.\n\nNo signature is required in this file (unlike the\nprevious ANTLR contributor's certificate of origin.)\n-->\n"
  },
  {
    "path": ".github/workflows/hosted.yml",
    "content": "name: antlr4\n\nconcurrency:\n  group: ${{ github.repository }}-${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\non:\n  push:\n    branches: [ master, dev, hostedci ]\n  pull_request:\n    branches: [ master, dev ]\n\npermissions:\n  contents: read\n\njobs:\n  cpp-lib-build:\n    runs-on: ${{ matrix.os }}\n\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [\n          macos-15,\n          ubuntu-22.04,\n          windows-2022\n        ]\n        compiler: [ clang, gcc ]\n        unity_build: [ ON, OFF ]\n        exclude:\n          - os: windows-2022\n            compiler: gcc\n        include:\n          - os: windows-2022\n            compiler: cl\n\n    steps:\n    - name: Install dependencies (Ubuntu)\n      if: startswith(matrix.os, 'ubuntu')\n      run: |\n        sudo apt-get update -qq\n        sudo apt install -y ninja-build\n\n    - name: Install dependencies (MacOS)\n      if: startswith(matrix.os, 'macos')\n      run: brew install ninja\n\n    - name: Setup Clang\n      if: (matrix.compiler == 'clang') && !startswith(matrix.os, 'macos')\n      uses: egor-tensin/setup-clang@v1\n      with:\n        version: 13\n        platform: x64\n        cygwin: 0\n\n    - name: Check out code\n      uses: actions/checkout@v3\n\n    - name: Use ccache\n      if: startswith(matrix.os, 'macos') || startswith(matrix.os, 'ubuntu')\n      uses: hendrikmuhs/ccache-action@v1.2\n      with:\n        key: ${{ matrix.os }}-${{ matrix.compiler }}\n\n    - name: Configure shell (Ubuntu)\n      if: startswith(matrix.os, 'ubuntu')\n      run: echo 'PATH=/usr/lib/ccache:'\"$PATH\" >> $GITHUB_ENV\n\n    - name: Configure shell (MacOS)\n      if: startswith(matrix.os, 'macos')\n      run: echo \"PATH=$(brew --prefix)/opt/ccache/libexec:$PATH\" >> $GITHUB_ENV\n\n    - name: Build (Windows)\n      if: startswith(matrix.os, 'windows')\n      shell: cmd\n      run: |\n        call \"C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Auxiliary\\Build\\vcvars64.bat\"\n\n        if \"${{ matrix.compiler }}\" EQU \"cl\" (\n          set CC=cl\n          set CXX=cl\n          echo 'CC=cl' >> $GITHUB_ENV\n          echo 'CXX=cl' >> $GITHUB_ENV\n        ) else (\n          set CC=clang\n          set CXX=clang++\n          echo 'CC=clang' >> $GITHUB_ENV\n          echo 'CXX=clang++' >> $GITHUB_ENV\n        )\n\n        set\n        where cmake && cmake --version\n        where ninja && ninja --version\n        where %CC% && %CC% -version\n        where %CXX% && %CXX% -version\n\n        cd runtime/Cpp\n\n        cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug -DANTLR_BUILD_CPP_TESTS=OFF -DCMAKE_UNITY_BUILD=${{ matrix.unity_build }} -DCMAKE_UNITY_BUILD_BATCH_SIZE=20 -S . -B out/Debug\n        if %errorlevel% neq 0 exit /b %errorlevel%\n\n        cmake --build out/Debug -j %NUMBER_OF_PROCESSORS%\n        if %errorlevel% neq 0 exit /b %errorlevel%\n\n        cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DANTLR_BUILD_CPP_TESTS=OFF -S . -B out/Release\n        if %errorlevel% neq 0 exit /b %errorlevel%\n\n        cmake --build out/Release -j %NUMBER_OF_PROCESSORS%\n        if %errorlevel% neq 0 exit /b %errorlevel%\n\n    - name: Build (non-Windows)\n      if: startswith(matrix.os, 'macos') || startswith(matrix.os, 'ubuntu')\n      run: |\n        if [ \"${{matrix.compiler}}\" == \"clang\" ]; then\n          export CC=clang\n          export CXX=clang++\n          echo 'CC=clang' >> $GITHUB_ENV\n          echo 'CXX=clang++' >> $GITHUB_ENV\n        else\n          export CC=gcc\n          export CXX=g++\n          echo 'CC=gcc' >> $GITHUB_ENV\n          echo 'CXX=g++' >> $GITHUB_ENV\n        fi\n\n        env\n        which cmake && cmake --version\n        which ninja && ninja --version\n        which $CC && $CC --version\n        which $CXX && $CXX --version\n\n        cd runtime/Cpp\n\n        cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug -DANTLR_BUILD_CPP_TESTS=OFF -DCMAKE_UNITY_BUILD=${{ matrix.unity_build }} -DCMAKE_UNITY_BUILD_BATCH_SIZE=20 -S . -B out/Debug\n        cmake --build out/Debug --parallel\n\n        cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DANTLR_BUILD_CPP_TESTS=OFF -S . -B out/Release\n        cmake --build out/Release --parallel\n\n    - name: Prepare artifacts\n      if: always()\n      run: |\n        cd ${{ github.workspace }}/..\n        tar czfp antlr_${{ matrix.os }}_${{ matrix.compiler }}.tgz --exclude='.git' antlr4\n        mv antlr_${{ matrix.os }}_${{ matrix.compiler }}.tgz ${{ github.workspace }}/.\n\n    - name: Archive artifacts\n      if: always()\n      continue-on-error: true\n      uses: actions/upload-artifact@v4\n      with:\n        name: antlr_${{ matrix.os }}_${{ matrix.compiler }}\n        path: antlr_${{ matrix.os }}_${{ matrix.compiler }}.tgz\n\n\n  build:\n    runs-on: ${{ matrix.os }}\n\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [\n          macos-15,\n          ubuntu-22.04,\n          windows-2022\n        ]\n        target: [\n          tool,\n          cpp,\n          csharp,\n          dart,\n          go,\n          java,\n          javascript,\n          typescript,\n          php,\n          python3,\n          # swift,\n        ]\n        exclude:\n          - os: windows-2022\n            target: swift\n\n    steps:\n      # Check out the code before setting the environment since some\n      # of the actions actually parse the files to figure out the\n      # dependencies, for instance, the setup-java actually parses\n      # **/pom.xml files to decide what to cache.\n    - name: Check out code\n      uses: actions/checkout@v3\n\n    - name: Checkout antlr PHP runtime\n      if: matrix.target == 'php'\n      uses: actions/checkout@v3\n      with:\n        repository: antlr/antlr-php-runtime\n        path: runtime/PHP\n\n    - name: Setup PHP 8.2\n      if: matrix.target == 'php'\n      uses: shivammathur/setup-php@v2\n      with:\n        php-version: '8.3'\n        extensions: mbstring\n        tools: composer\n\n    - name: Install dependencies\n      env:\n        COMPOSER_CACHE_DIR: ${{ github.workspace }}/.cache\n      if: matrix.target == 'php'\n      run: |-\n        cd runtime/PHP\n        composer install --no-progress --no-interaction --prefer-dist --optimize-autoloader\n\n    - name: Install dependencies (Ubuntu)\n      if: startswith(matrix.os, 'ubuntu')\n      run: |\n        sudo apt-get update -qq\n        sudo apt install -y ninja-build\n\n    - name: Install dependencies (MacOS)\n      if: startswith(matrix.os, 'macos')\n      run: brew install ninja\n\n    - name: Set up JDK 11\n      id: setup-java\n      uses: actions/setup-java@v3\n      with:\n        distribution: 'zulu'\n        java-version: 11\n        cache: 'maven'\n\n    - name: Set up Maven\n      if: steps.setup-java.outputs.cache-hit != 'true'\n      uses: stCarolas/setup-maven@v4.5\n      with:\n        maven-version: 3.8.5\n\n    - name: Add msbuild to PATH\n      if: startswith(matrix.os, 'windows') && (matrix.target == 'cpp')\n      uses: microsoft/setup-msbuild@v1.1\n\n    - name: Set up Python 3\n      if: matrix.target == 'python3'\n      uses: actions/setup-python@v4\n      with:\n        python-version: '3.x'\n        architecture: 'x64'\n\n    - name: Set up Node 16\n      if: (matrix.target == 'javascript') || (matrix.target == 'typescript')\n      uses: actions/setup-node@v3.6.0\n      with:\n        node-version: '16'\n\n    - name: Setup Dotnet\n      if: matrix.target == 'csharp'\n      uses: actions/setup-dotnet@v3.0.3\n      with:\n        dotnet-version: '7.0.x'\n\n    - name: Setup Dart 2.12.1\n      if: matrix.target == 'dart'\n      uses: dart-lang/setup-dart@v1.3\n      with:\n        sdk: 2.12.1\n\n    - name: Setup Go 1.19\n      if: matrix.target == 'go'\n      uses: actions/setup-go@v3.3.1\n      with:\n        go-version: '^1.19'\n\n    - name: Setup Swift\n      if: matrix.target == 'swift'\n      uses: swift-actions/setup-swift@v1.19.0\n      with:\n        swift-version: '5.2'\n\n    - name: Use ccache\n      if: (startswith(matrix.os, 'macos') || startswith(matrix.os, 'ubuntu')) && (matrix.target == 'cpp')\n      uses: hendrikmuhs/ccache-action@v1.2\n      with:\n        key: ${{ matrix.os }}-${{ matrix.target }}\n\n    - name: Configure shell (Ubuntu)\n      if: startswith(matrix.os, 'ubuntu') && (matrix.target == 'cpp')\n      run: echo 'PATH=/usr/lib/ccache:'\"$PATH\" >> $GITHUB_ENV\n\n    - name: Configure shell (MacOS)\n      if: startswith(matrix.os, 'macos') && (matrix.target == 'cpp')\n      run: echo \"PATH=$(brew --prefix)/opt/ccache/libexec:$PATH\" >> $GITHUB_ENV\n\n    - name: Build ANTLR with Maven\n      run: mvn install -DskipTests=true -Darguments=\"-Dmaven.javadoc.skip=true\" -B -V\n\n    - name: Test tool\n      if: matrix.target == 'tool'\n      run: |\n        cd tool-testsuite\n        mvn test\n\n    - name: Test runtime (Windows)\n      if: startsWith(matrix.os, 'windows') && (matrix.target != 'tool')\n      run: |\n        gci env:* | sort-object name\n\n        cd runtime-testsuite\n        switch (\"${{ matrix.target }}\")\n        {\n          python3 { mvn -X '-Dantlr-python3-exec=\"${{ env.pythonLocation }}\\python.exe\"' '-Dtest=python3.**' test }\n          default { mvn -X '-Dtest=${{ matrix.target }}.**' test }\n        }\n\n      env:\n        CMAKE_GENERATOR: Ninja\n\n    - name: Test runtime (non-Windows)\n      if: (startsWith(matrix.os, 'ubuntu') || startsWith(matrix.os, 'macos'))  && (matrix.target != 'tool')\n      run: |\n        env\n\n        cd runtime-testsuite\n        case ${{ matrix.target }} in\n          python3) mvn -X '-Dantlr-python3-exec=${{ env.pythonLocation }}/bin/python' '-Dtest=python3.**' test ;;\n          *) mvn -X '-Dtest=${{ matrix.target }}.**' test ;;\n        esac\n\n    - name: Prepare artifacts\n      if: always()\n      run: |\n        cd ${{ github.workspace }}/..\n        tar czfp antlr_${{ matrix.os }}_${{ matrix.target }}.tgz --exclude='.git' antlr4\n        mv antlr_${{ matrix.os }}_${{ matrix.target }}.tgz ${{ github.workspace }}/.\n\n    - name: Archive artifacts\n      if: always()\n      continue-on-error: true\n      uses: actions/upload-artifact@v4\n      with:\n        name: antlr_${{ matrix.os }}_${{ matrix.target }}\n        path: antlr_${{ matrix.os }}_${{ matrix.target }}.tgz\n"
  },
  {
    "path": ".gitignore",
    "content": "# Nuget packages\n*.nupkg\n\n# Maven build folders\ntarget/\n# ... but not code generation targets\n!tool/src/org/antlr/v4/codegen/target/\n\n# Node.js (npm and typings) cached dependencies\nnode_modules/\ntypings/\n\n# Ant build folders\nbuild/\ndist/\nlib/\nuser.build.properties\n\n# MacOSX files\n.DS_Store\n\n## Python, selected lines from https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n# Build results\n*.egg-info/\n\n## CSharp and VisualStudio, selected lines from https://raw.githubusercontent.com/github/gitignore/master/VisualStudio.gitignore\n# User-specific files\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# User-specific files (MonoDevelop/Xamarin Studio/Visual Studio)\n*.userprefs\n.vs/\nproject.lock.json\n\n# Build results\n[Dd]ebug/\n[Dd]ebugPublic/\n[Rr]elease/\n[Rr]eleases/\nx64/\nx86/\nbld/\n[Bb]in/\n[Oo]bj/\n[Ll]og/\n\n# NetBeans user configuration files\nnbactions*.xml\n/nbproject/private/\n*/nbproject/private/\n\n# IntelliJ projects\n*.iws\n*.iml\n.idea/\n\n# Eclipse projects\n.classpath\n.project\n.settings/\n.metadata\n\n# Profiler results\n*.hprof\n\n# parrt's bash prompt data\n.fetch_time_cache\n\n# Playground\n#/tool/playground/\n\n# Generated files\n/out/\n/gen/\n/gen3/\n/gen4/\n/tool/playground/\ntmp/\n**/generatedCode/*.interp\n**/generatedCode/*.tokens\n**/generatedCode/*.bak\n\n# Configurable build files\nbilder.py\nbilder.pyc\nbild.log\n\nbild_output.txt\nruntime/Cpp/demo/generated\nxcuserdata\n*.jar\n.vscode\n\n# VSCode Java plugin temporary files\njavac-services.0.log\njavac-services.0.log.lck\n\n# Don't ignore python tests\n!runtime/Python3/test/\nAntlr4.sln\nruntime/PHP\n\n# Swift binaries\n.build/\n\n# Code coverage reports\ncoverage/\n\n# Cpp generated build files\nruntime/Cpp/CMakeCache.txt\nruntime/Cpp/CMakeFiles/\nruntime/Cpp/CPackConfig.cmake\nruntime/Cpp/CPackSourceConfig.cmake\nruntime/Cpp/CTestTestfile.cmake\nruntime/Cpp/Makefile\nruntime/Cpp/_deps/\nruntime/Cpp/cmake_install.cmake\nruntime/Cpp/runtime/CMakeFiles/\nruntime/Cpp/runtime/CTestTestfile.cmake\nruntime/Cpp/runtime/Makefile\nruntime/Cpp/runtime/antlr4_tests\nruntime/Cpp/runtime/antlr4_tests\\[1]_include.cmake\nruntime/Cpp/runtime/antlr4_tests\\[1]_tests.cmake\nruntime/Cpp/runtime/cmake_install.cmake\nruntime/Cpp/runtime/libantlr4-runtime.4.10.1.dylib\nruntime/Cpp/runtime/libantlr4-runtime.a\nruntime/Cpp/runtime/libantlr4-runtime.dylib\n/runtime/Cpp/runtime/libantlr4-runtime.4.12.0.dylib\n/runtime/Cpp/runtime/libantlr4-runtime.4.13.0.dylib\n\n# Go test and performance trace files\n**/*.pprof\n"
  },
  {
    "path": "ANTLR-HOUSE-RULES.md",
    "content": "# ANTLR HOUSE RULES\n\n*Last updated: Sept 10, 2022*\n\nThis brief document describes best practices for us to all get along and for the benefit of the project.  Collaborating on this project poses a number of difficulties:\n\n* different native languages\n* different time zones\n* lack of common company or other organization as social glue\n* we are just github userids without personal connection to most other contributors\n* those developers able to contribute to such a complex project typically have a lot of experience and, consequently, strong opinions\n\nEffective communication is difficult under the circumstances and civil discourse is a requirement to keep the project on track.  Over 35 years, in-fighting between contributors has made parrt's job as supreme dictator for life much more difficult.\n\nRules\n\n1. Assume good intentions of the other party.\n2. Try to be welcoming and respectful of differing viewpoints experiences.\n2. No personal attacks, meaning ideas can be bad in your comments but not people.  Replace \"You are ...\" with \"Your idea is ...\".\n3. Control your anger please. No hate speech, racism, sexism, or ethnocentrism. No trolling or insulting. See rule #1.\n2. Be tolerant and understanding of non-native English speakers' word choice and phrasing.  This is a huge source of misunderstandings; see rule #1. For example, to a native English speaker \"I cannot *approve* this\" makes it sound like the writer has control over the readers contribution. Instead, the writer likely meant \"I cannot *support* this.\" See rule #1.\n3. Soften word choice to use conditional tenses and helper words. For example, use phrases such as \"I'm not sure this is a good idea because ...\" or \"I wonder if you'd consider this other possibility: ...\" etc...\n\nSupreme dictator for life parrt has final say. His decisions will not always be correct nor to your liking, but he has a difficult cost-benefit equation to solve for every bug fix, feature, and PR.\n\nAny text contrary to these house rules will likely be edited and replaced with an admonishment by parrt.\n\nSend concerns to parrt@antlr.org."
  },
  {
    "path": "CHANGES.txt",
    "content": "****************************************************************************\nAs of ANTLR 4.2.1, March 25 2014, we are no longer updating this file. Instead,\nwe are using the github release mechanism. For example, here is\n4.2.1 release notes:\n\nhttps://github.com/antlr/antlr4/releases/tag/4.2.1\n****************************************************************************\n\nANTLR v4 Honey Badger\n\nJanuary 15, 2014\n\n* Unit tests for lexer actions from yesterday.\n* Refactored TreeView so we can refresh tree externally w/o creating new one.\n  Needed for intellij plugin.\n\nJanuary 14, 2014\n\n* Updated serialized ATN representation of lexer actions, allowing the lexer\n  interpreter to execute the majority of lexer commands (#408)\n\nJanuary 12, 2014\n\n* Support executing precedence predicates during the SLL phase of\n  adaptivePredict (#401). The result is a massive performance boost for grammars\n  containing direct left-recursion (improvements of 5% to 1000+% have been\n  observed, depending on the grammar and input).\n\nDecember 29, 2013\n\n* Internal change: Tool.loadGrammar() -> parseGrammar(). Tool.load()->parse()\n\n* Added Tool.loadGrammar(fileName) that completely parses, extracts implicit lexer,\n  and processes into Grammar object. Does not geneate code.  Use\n  Grammar.getImplicitLexer() to get the lexer created during processing of\n  combined grammar.\n\n* Added Grammar.load(fileName) that creates Tool object for you. loadGrammar()\n  lets you create your own Tool for setting error handlers etc...\n\n\tfinal Grammar g = Grammar.load(\"/tmp/MyGrammar.g4\");\n\nDecember 19, 2013\n\n* Sam:\n\tImproved documentation for tree patterns classes\n    Refactored parts of the tree patterns API to simplify classes and improve encapsulation\n    Move ATN serializer to runtime\n    Use ATNDeserializer methods instead of ATNSimulator methods which are now deprecated\n\n* parrt: fix null pointer bug with rule \"a : a;\"\n\nNovember 24, 2013\n\n* Ter adds tree pattern matching.  Preferred interface:\n\n\tParseTree t = parser.expr();\n\tParseTreePattern p = parser.compileParseTreePattern(\"<ID>+0\", MyParser.RULE_expr);\n\tParseTreeMatch m = p.match(t);\n\tString id = m.get(\"ID\");\n\n  or\n\n\tString xpath = \"//blockStatement/*\";\n\tString treePattern = \"int <Identifier> = <expression>;\";\n\tParseTreePattern p =\n\t\tparser.compileParseTreePattern(treePattern,\n\t\t\t\t\t\t\t\t\t   JavaParser.RULE_localVariableDeclarationStatement);\n\tList<ParseTreeMatch> matches = p.findAll(tree, xpath);\n\nNovember 20, 2013\n\n* Sam added method stuff like expr() that calls expr(0). Makes it possible\n  to call expr rule from TestRig (grun).\n\nNovember 14, 2013\n\n* Added Sam's ParserInterpreter implementation that uses ATN after\n  deserialization.\n\n\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n  \t\t\"A : 'a' ;\\n\" +\n  \t\t\"B : 'b' ;\\n\" +\n  \t\t\"C : 'c' ;\\n\");\n  \tGrammar g = new Grammar(\n  \t\t\"parser grammar T;\\n\" +\n  \t\t\"s : (A{;}|B)* C ;\\n\",\n  \t\tlg);\n\n\tLexerInterpreter lexEngine = lg.createLexerInterpreter(new ANTLRInputStream(input));\n\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\tParserInterpreter parser = g.createParserInterpreter(tokens);\n\tParseTree t = parser.parse(g.rules.get(startRule).index);\n\nNovember 13, 2013\n\n* move getChildren() from Tree into Trees (to avoid breaking change)\n* Notation:\n\t/prog/func,         -> all funcs under prog at root\n\t/prog/*,            -> all children of prog at root\n\t/*/func,            -> all func kids of any root node\n\tprog,               -> prog must be root node\n\t/prog,              -> prog must be root node\n\t/*,                 -> any root\n\t*,                  -> any root\n\t//ID,               -> any ID in tree\n\t//expr/primary/ID,  -> any ID child of a primary under any expr\n\t//body//ID,         -> any ID under a body\n\t//'return',         -> any 'return' literal in tree\n\t//primary/*,        -> all kids of any primary\n\t//func/*/stat,      -> all stat nodes grandkids of any func node\n\t/prog/func/'def',   -> all def literal kids of func kid of prog\n\t//stat/';',         -> all ';' under any stat node\n\t//expr/primary/!ID, -> anything but ID under primary under any expr node\n\t//expr/!primary,    -> anything but primary under any expr node\n\t//!*,               -> nothing anywhere\n\t/!*,                -> nothing at root\n\nSeptember 16, 2013\n\n* Updated build.xml to support v4 grammars in v4 itself; compiles XPathLexer.g4\n* Add to XPath:\n\tCollection<ParseTree> findAll(String xpath);\n\nSeptember 11, 2013\n\n* Add ! operator to XPath\n* Use ANTLR v4 XPathLexer.g4 not regex\n* Copy lots of find node stuff from v3 GrammarAST to Trees class in runtime.\n\nSeptember 10, 2013\n\n* Adding in XPath stuff.\n\nAugust 31, 2013\n\n* Lots of little fixes thanks to Coverity Scan\n\nAugust 7, 2013\n\n* [BREAKING CHANGE] Altered left-recursion elimination to be simpler. Now,\n  we use the following patterns:\n\n  * Binary expressions are expressions which contain a recursive invocation of\n    the rule as the first and last element of the alternative.\n\n  * Suffix expressions contain a recursive invocation of the rule as the first\n    element of the alternative, but not as the last element.\n\n  * Prefix expressions contain a recursive invocation of the rule as the last\n    element of the alternative, but not as the first element.\n\nThere is no such thing as a \"ternary\" expression--they are just binary\nexpressions in disguise.\n\nThe right associativity specifiers no longer on the individual tokens because\nit's done on alternative basis anyway. The option is now on the individual\nalternative; e.g.,\n\n  e : e '*' e\n    | e '+' e\n    |<assoc=right> e '?' e ':' e\n    |<assoc=right> e '=' e\n    | INT\n    ;\n\nIf your language uses a right-associative ternary operator, you will need\nto update your grammar to include <assoc=right> on the alternative operator.\n\nThis also fixes #245 and fixes #268:\n\nhttps://github.com/antlr/antlr4/issues/245\nhttps://github.com/antlr/antlr4/issues/268\n\nTo smooth the transition, <assoc=right> is still allowed on token references\nbut it is ignored.\n\nJune 30, 2013 -- 4.1 release\n\nJune 24, 2013\n\n* Resize ANTLRInputStream.data after reading a file with fewer characters than\n  bytes\n* Fix ATN created for non-greedy optional block with multiple alternatives\n* Support Unicode escape sequences with indirection in JavaUnicodeInputStream\n  (fixes #287)\n* Remove the ParserRuleContext.altNum field (fixes #288)\n* PredictionContext no longer implements Iterable<SingletonPredictionContext>\n* PredictionContext no longer implements Comparable<PredictionContext>\n* Add the EPSILON_CLOSURE error and EPSILON_OPTIONAL warning\n* Optimized usage of closureBusy set (fixes #282)\n\nJune 9, 2013\n\n* Add regression test for #239 (already passes)\n\nJune 8, 2013\n\n* Support list labels on a set of tokens (fixes #270)\n* Fix associativity of XOR in Java LR grammar (fixes #280)\n\nJune 1, 2013\n\n* DiagnosticErrorListener includes rule names for each decision in its reports\n* Document ANTLRErrorListener and DiagnosticErrorListener (fixes #265)\n* Support '\\uFFFF' (fixes #267)\n* Optimize serialized ATN\n\nMay 26, 2013\n\n* Report errors that occur while lexing a grammar (fixes #262)\n* Improved error message for unterminated string literals (fixes #243)\n\nMay 24, 2013\n\n* Significantly improve performance of JavaUnicodeInputStream.LA(1)\n\nMay 20, 2013\n\n* Generate Javadoc for generated visitor and listener interfaces and classes\n* Fix unit tests\n\nMay 18, 2013\n\n* Group terminals in Java grammars so ATN can collapse sets\n* Improved Java 7 support in Java grammars (numeric literals)\n* Updated error listener interfaces\n* Support detailed statistics in TestPerformance\n\nMay 17, 2013\n\n* Add JavaUnicodeInputStream to handle Unicode escapes in Java code\n* Proper Unicode identifier handling in Java grammars\n* Report file names with lexer errors in TestPerformance\n\nMay 14, 2013\n\n* Use a called rule stack to prevent stack overflow in LL1Analyzer\n* Use 0-based indexing for several arrays in the tool\n* Code simplification, assertions, documentation\n\nMay 13, 2013\n\n* Unit test updates to ensure exceptions are not hidden\n\nMay 12, 2013\n\n* Updates to TestPerformance\n\nMay 5, 2013\n\n* Updated several classes to use MurmurHash 3 hashing\n\nMay 1, 2013\n\n* Added parse tree JTree to TreeViewer (Bart Kiers)\n\nApril 30, 2013\n\n* Updated TestPerformance to support parallelization across passes\n\nApril 24, 2013\n\n* Remove unused stub class ParserATNPathFinder\n* Remove ParserInterpreter.predictATN\n* Remove DFA.getATNStatesAlongPath\n* Encapsulate implementation methods in LexerATNSimulator and ParserATNSimulator\n* Updated documentation\n* Simplify creation of new DFA edges\n* Fix handling of previously cached error edges\n* Fix DFA created during forced-SLL parsing (PredictionMode.SLL)\n* Extract methods ParserATNSimulator.getExistingTargetState and\n  ParserATNSimulator.computeTargetState.\n\nApril 22, 2013\n\n* Lazy initialization of ParserATNSimulator.mergeCache\n* Improved hash code for DFAState\n* Improved hash code with caching for ATNConfigSet\n* Add new configuration parameters to TestPerformance\n* Update Java LR and Java Std to support Java 7 syntax\n\nApril 21, 2013\n\n* Add new configuration parameters to TestPerformance\n\nApril 18, 2013\n\n* Must check rule transition follow states before eliminating states in\n  the ATN (fixes #224)\n* Simplify ParserATNSimulator and improve performance by combining execDFA and\n  execATN and using DFA edges even after edge computation is required\n\nApril 15, 2013\n\n* Fix code in TestPerformance that clears the DFA\n\nApril 12, 2013\n\n* Improved initialization and concurrency control in DFA updates\n* Fix EOF handling in edge case (fixes #218)\n\nApril 4, 2013\n\n* Improved testing of error reporting\n* Fix NPE revealed by updated testing method\n* Strict handling of redefined rules - prevents code generation (fixes #210)\n* Updated documentation in Tool\n\nMarch 27, 2013\n\n* Avoid creating empty action methods in lexer (fixes #202)\n* Split serialized ATN when it exceeds Java's 65535 byte limit (fixes #76)\n* Fix incorrect reports of label type conflicts across separated labeled outer\n  alternatives (fixes #195)\n* Update Maven plugin site documentation\n\nMarch 26, 2013\n\n* Fix bugs with the closureBusy set in ParserATNSimulator.closure\n* Fix handling of empty options{} block (fixes #194)\n* Add error 149 INVALID_LEXER_COMMAND (fixes #190)\n* Add error 150 MISSING_LEXER_COMMAND_ARGUMENT\n* Add error 151 UNWANTED_LEXER_COMMAND_ARGUMENT\n* Updated documentation in the Parser and RecognitionException classes\n* Refactored and extensively documented the ANTLRErrorStrategy interface and\n  DefaultErrorStrategy default implementation\n* Track the number of syntax errors in Parser.notifyErrorListeners instead of in\n  the error strategy\n* Move primary implementation of getExpectedTokens to ATN, fixes #191\n* Updated ATN documentation\n* Use UUID instead of incremented integer for serialized ATN versioning\n\nMarch 7, 2013\n\n* Added export to PNG feature to the parse tree viewer\n\nMarch 6, 2013\n\n* Allow direct calls to left-recursive rules (fixes #161)\n* Change error type 146 (EPSILON_TOKEN) to a warning (fixes #180)\n* Specify locale for all format operations (fixes #158)\n* Fix generation of invalid Unicode escape sequences in Java code (fixes #164)\n* Do not require escape for $ in action when not followed by an ID start char\n  (fixes #176)\n\nFebruary 23, 2013\n\n* Refactoring Target-related classes to improve support for additional language\n  targets\n\nFebruary 22, 2013\n\n* Do not allow raw newline characters in literals\n* Pair and Triple are immutable; Triple is not a Pair\n\nFebruary 5, 2013\n\n* Fix IntervalSet.add when multiple merges are required (fixes #153)\n\nJanuary 29, 2013\n\n* don't call process() if args aren't specified (Dave Parfitt)\n\nJanuary 21, 2013 -- Release 4.0\n\n* Updated PredictionContext Javadocs\n* Updated Maven site documentation\n* Minor tweaks in Java.stg\n\nJanuary 15, 2013\n\n* Tweak error messages\n* (Tool) Make TokenVocabParser fields `protected final`\n* Fix generated escape sequences for literals containing backslashes\n\nJanuary 14, 2013\n\n* Relax parser in favor of errors during semantic analysis\n* Add error 145: lexer mode must contain at least one non-fragment rule\n* Add error 146: non-fragment lexer rule can match the empty string\n\nJanuary 11, 2013\n\n* Updated error 72, 76; added 73-74 and 136-143: detailed errors about name\n  conflicts\n* Report exact location for parameter/retval/local name conflicts\n* Add error 144: multi-character literals are not allowed in lexer sets\n* Error 134 now only applies to rule references in lexer sets\n* Updated error messages (cleanup)\n* Reduce size of _serializedATN by adding 2 to each element: new representation\n  avoids embedded values 0 and 0xFFFF which are common and have multi-byte\n  representations in Java's modified UTF-8\n\nJanuary 10, 2013\n\n* Add error 135: cannot assign a value to list label: $label\n  (fixes antlr/antlr4#128)\n\nJanuary 2, 2013\n\n* Fix EOF handling (antlr/antlr4#110)\n* Remove TREE_PARSER reference\n* Additional validation checks in ATN deserialization\n* Fix potential NPE in parser predicate evaluation\n* Fix termination condition detection in full-context parsing\n\nJanuary 1, 2013\n\n* Updated documentation\n* Minor code cleanup\n* Added the `-XdbgSTWait` command line option for the Tool\n* Removed method override since bug was fixed in V3 runtime\n\nDecember 31, 2012\n\n* I altered Target.getTargetStringLiteralFromANTLRStringLiteral() so that\n  it converts \\uXXXX in an ANTLR string to \\\\uXXXX, thus, avoiding Java's\n  conversion to a single character before compilation.\n\nDecember 16, 2012\n\n* Encapsulate some fields in ANTLRMessage\n* Remove ErrorType.INVALID\n* Update error/warning messages, show all v3 compatibility messages\n\nDecember 12, 2012\n\n* Use arrays instead of HashSet to save memory in SemanticContext.AND/OR\n* Use arrays instead of HashSet to save memory in cached DFA\n* Reduce single-operand SemanticContext.and/or operations\n\nDecember 11, 2012\n\n* Add -long-messages option; only show exceptions with errors when set\n* \"warning treated as error\" is a one-off error\n* Listen for issues reported by StringTemplate, report them as warnings\n* Fix template issues\n* GrammarASTWithOptions.getOptions never returns null\n* Use EnumSet instead of HashSet\n* Use new STGroup.GROUP_FILE_EXTENSION value\n\nDecember 2, 2012\n\n* Remove -Xverbose-dfa option\n* Create the ParseTreeVisitor interface for all visitors, rename previous base\n  visitor class to AbstractParseTreeVisitor\n\nDecember 1, 2012\n\n* escape [\\n\\r\\t] in lexical error messages; e.g,:\n  line 2:3 token recognition error at: '\\t'\n  line 2:4 token recognition error at: '\\n'\n\n* added error for bad sets in lexer; e.g.:\n  lexer set element A is invalid (either rule ref or literal with > 1 char)\n  some tests in TestSets appeared to allow ~('a'|B) but it was randomly working.\n  ('a'|B) works, though doesn't collapse to a set.\n\n* label+='foo' wasn't generating good code. It was generating token type as\n  variable name. Now, I gen \"s<ttype>\" for implicit labels on string literals.\n\n* tokens now have token and char source to draw from.\n\n* remove -Xsave-lexer option; log file as implicit lexer AST.\n\nNovember 30, 2012\n\n* Maven updates (cleanup, unification, and specify Java 6 bootstrap classpath)\n\nNovember 28, 2012\n\n* Maven updates (uber-jar, manifest details)\n\nNovember 27, 2012\n\n* Maven updates (prepare for deploying to Sonatype OSS)\n* Use efficient bitset tests instead of long chains of operator ==\n\nNovember 26, 2012\n\n* Maven updates (include sources and javadocs, fix warnings)\n* Don't generate action methods for lexer rules not containing an action\n* Generated action and sempred methods are private\n* Remove unused / problematic methods:\n** (unused) TerminalNodeImpl.isErrorNode\n** (unused) RuleContext.conflictsWith, RuleContext.suffix.\n** (problematic) RuleContext.hashCode, RuleContext.equals.\n\nNovember 23, 2012\n\n* Updated Maven build (added master POM, cleaned up module POMs)\n\nNovember 22, 2012\n\n* make sure left-recur rule translation uses token stream from correct imported file.\n* actions like @after in imported rules caused inf loop.\n* This misidentified scope lexer/parser: @lexer::members { } @parser::members { }\n\nNovember 18, 2012\n\n* fixed: undefined rule refs caused exception\n* cleanup, rm dead etypes, add check for ids that cause code gen issues\n* added notion of one-off error\n* added check for v3 backward incompatibilities:\n** tree grammars\n** labels in lexer rules\n** tokens {A;B;} syntax\n** tokens {A='C';} syntax\n** {...}?=> gate semantic predicates\n** (...)=> syntactic predicates\n* Detect EOF in lexer rule\n\nNovember 17, 2012\n\n* .tokens files goes in output dir like parser file.\n* added check: action in lexer rules must be last element of outermost alt\n* properly check for grammar/filename difference\n* if labels, don't allow set collapse for\n  a : A # X | B ;\n* wasn't checking soon enough for rule redef; now it sets a dead flag in\n  AST so no more walking dup.\n  error(51): T.g:7:0: rule s redefinition (ignoring); previous at line 3\n\nNovember 11, 2012\n\n* Change version to 4.0b4 (btw, forgot to push 4.0b3 in build.properties when\n  I made git tag 4.0b3...ooops).\n\nNovember 4, 2012\n\n* Kill box in tree dialog box makes dialog dispose of itself\n\nOctober 29, 2012\n\n* Sam fixes nongreedy more.\n* -Werror added.\n* Sam made speed improvement re preds in lexer.\n\nOctober 20, 2012\n\n* Merged Sam's fix for nongreedy lexer/parser. lots of unit tests. A fix in\n  prediction ctx merge. https://github.com/parrt/antlr4/pull/99\n\nOctober 14, 2012\n\n* Rebuild how ANTLR detects SLL conflict and failover to full LL.  LL is\n  a bit slower but correct now.  Added ability to ask for exact ambiguity\n  detection.\n\nOctober 8, 2012\n\n* Fixed a bug where labeling the alternatives of the start rule caused\n  a null pointer exception.\n\nOctober 1, 2012 -- 4.0b2 release\n\nSeptember 30, 2012\n\n* Fixed the unbuffered streams, which actually buffered everything\n  up by mistake. tweaked a few comments.\n\n* Added a getter to IntStream for the token factory\n\n* Added -depend cmd-line option.\n\nSeptember 29, 2012\n\n* no nongreedy or wildcard in parser.\n\nSeptember 28, 2012\n\n* empty \"tokens {}\" is ok now.\n\nSeptember 22, 2012\n\n* Rule exception handlers weren't passed to the generated code\n* $ruleattribute.foo weren't handled properly\n* Added -package option\n\nSeptember 18, 2012 -- 4.0b1 release\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to ANTLR 4\n\n1. [Fork](https://help.github.com/articles/fork-a-repo) the [antlr/antlr4 repo](https://github.com/antlr/antlr4), which will give you both key branches, `master` and `dev`\n2. Make sure to `git checkout dev` in your fork so that you are working from the latest development branch\n3. Create and work from a branch derived from `dev` such as `git checkout -b your-branch-name`\n4. Install and configure [EditorConfig](http://editorconfig.org/) so your text editor or IDE uses the ANTLR 4 coding style\n5. [Build ANTLR 4](doc/building-antlr.md)\n6. [Run the ANTLR project unit tests](doc/antlr-project-testing.md)\n7. Create a [pull request](https://help.github.com/articles/using-pull-requests/) with your changes and make sure you're comparing your `dev`-derived branch in your fork to the `dev` branch from the `antlr/antlr4` repo:\n\n<img src=\"doc/images/PR-on-dev.png\" width=\"600\">\n\n**Note:** Each commit requires a \"signature\", which is simple as using `-s` (not \n`-S`) to the git commit command:\n\n```\ngit commit -s -m 'This is my commit message'\n```\n\nGithub's pull request process enforces the sig and gives instructions on how to \nfix any commits that lack the sig. See [Github DCO app](https://github.com/apps/dco) \nfor more info.\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and/or other materials provided with the distribution.\n\n3. Neither name of copyright holders nor the names of its contributors\nmay be used to endorse or promote products derived from this software\nwithout specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "Package.swift",
    "content": "// swift-tools-version:5.6\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Antlr4\",\n    products: [\n        .library(\n            name: \"Antlr4\",\n            targets: [\"Antlr4\"]),\n        .library(\n            name: \"Antlr4Static\",\n            type: .static,\n            targets: [\"Antlr4\"]),\n        .library(\n            name: \"Antlr4Dynamic\",\n            type: .dynamic,\n            targets: [\"Antlr4\"]),\n    ],\n    targets: [\n        .target(\n            name: \"Antlr4\",\n            dependencies: [],\n            path: \"./runtime/Swift/Sources/Antlr4\"),\n        .testTarget(\n            name: \"Antlr4Tests\",\n            dependencies: [\"Antlr4\"],\n            path: \"./runtime/Swift/Tests/Antlr4Tests\",\n            exclude: [\n                \"./runtime/Swift/Tests/VisitorBasic.g4\",\n                \"./runtime/Swift/Tests/VisitorCalc.g4\",\n                \"./runtime/Swift/Tests/LexerA.g4\",\n                \"./runtime/Swift/Tests/LexerB.g4\",\n                \"./runtime/Swift/Tests/Threading.g4\"\n            ]\n        )\n    ]\n)\n"
  },
  {
    "path": "README.md",
    "content": "# ANTLR v4\n\n[![Java 11+](https://img.shields.io/badge/java-11+-4c7e9f.svg)](http://java.oracle.com)\n[![License](https://img.shields.io/badge/license-BSD-blue.svg)](https://raw.githubusercontent.com/antlr/antlr4/master/LICENSE.txt)\n\n**ANTLR** (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files. It's widely used to build languages, tools, and frameworks. From a grammar, ANTLR generates a parser that can build parse trees and also generates a listener interface (or visitor) that makes it easy to respond to the recognition of phrases of interest.\n\n**Dev branch build status**\n\n[![MacOSX, Windows, Linux](https://github.com/antlr/antlr4/actions/workflows/hosted.yml/badge.svg)](https://github.com/antlr/antlr4/actions/workflows/hosted.yml) (github actions)\n\n<!--\n* [![Windows](https://github.com/antlr/antlr4/actions/workflows/windows.yml/badge.svg?branch=dev)](https://github.com/antlr/antlr4/actions/workflows/windows.yml) (github actions)\n\n* [![Circle CI Build Status (Linux)](https://img.shields.io/circleci/build/gh/antlr/antlr4/master?label=Linux)](https://app.circleci.com/pipelines/github/antlr/antlr4) (CircleCI)\n\n[![AppVeyor CI Build Status (Windows)](https://img.shields.io/appveyor/build/parrt/antlr4?label=Windows)](https://ci.appveyor.com/project/parrt/antlr4) \n[![Travis-CI Build Status (Swift-Linux)](https://img.shields.io/travis/antlr/antlr4.svg?label=Linux-Swift&branch=master)](https://travis-ci.com/github/antlr/antlr4)\n-->\n\n\n## Versioning\n\nANTLR 4 supports 10 target languages\n(Cpp, CSharp, Dart, Java, JavaScript, PHP, Python3, Swift, TypeScript, Go),\nand ensuring consistency across these targets is a unique and highly valuable feature.\nTo ensure proper support of this feature, each release of ANTLR is a complete release of the tool and the 10 runtimes, all with the same version.\nAs such, ANTLR versioning does not strictly follow semver semantics:\n\n* a component may be released with the latest version number even though nothing has changed within that component since the previous release\n* major version is bumped only when ANTLR is rewritten for a totally new \"generation\", such as ANTLR3 -> ANTLR4 (LL(\\*) -> ALL(\\*) parsing)\n* minor version updates may include minor breaking changes, the policy is to regenerate parsers with every release (4.11 -> 4.12)\n* backwards compatibility is only guaranteed for patch version bumps (4.11.1 -> 4.11.2)\n\nIf you use a semver verifier in your CI, you probably want to apply special rules for ANTLR, such as treating minor change as a major change.\n\n## Repo branch structure\n\nThe default branch for this repo is [`master`](https://github.com/antlr/antlr4/tree/master), which is the latest stable release and has tags for the various releases; e.g., see release tag [4.9.3](https://github.com/antlr/antlr4/tree/4.9.3).  Branch [`dev`](https://github.com/antlr/antlr4/tree/dev) is where development occurs between releases and all pull requests should be derived from that branch. The `dev` branch is merged back into `master` to cut a release and the release state is tagged (e.g., with `4.10-rc1` or `4.10`.) Visually our process looks roughly like this:\n\n<img src=\"doc/images/new-antlr-branches.png\" width=\"500\">\n\nThe Go target now has its own dedicated repo:\n\n```bash\n$ go get github.com/antlr4-go/antlr\n```\n**Note**\nThe dedicated Go repo is for `go get` and `import` only. Go runtime development is still performed in the main `antlr/antlr4` repo. \n\n## Authors and major contributors\n\n* [Terence Parr](http://www.cs.usfca.edu/~parrt/), parrt@cs.usfca.edu\nANTLR project lead and supreme dictator for life\n[University of San Francisco](http://www.usfca.edu/)\n* [Sam Harwell](http://tunnelvisionlabs.com/) (Tool co-author, Java and original C# target)\n* [Eric Vergnaud](https://github.com/ericvergnaud) (Javascript, TypeScript, Python2, Python3 targets and maintenance of C# target)\n* [Peter Boyer](https://github.com/pboyer) (Go target)\n* [Mike Lischke](http://www.soft-gems.net/) (C++ completed target)\n* Dan McLaughlin (C++ initial target)\n* David Sisson (C++ initial target and test)\n* [Janyou](https://github.com/janyou) (Swift target)\n* [Ewan Mellor](https://github.com/ewanmellor), [Hanzhou Shi](https://github.com/hanjoes) (Swift target merging)\n* [Ben Hamilton](https://github.com/bhamiltoncx) (Full Unicode support in serialized ATN and all languages' runtimes for code points > U+FFFF)\n* [Marcos Passos](https://github.com/marcospassos) (PHP target)\n* [Lingyu Li](https://github.com/lingyv-li) (Dart target)\n* [Ivan Kochurkin](https://github.com/KvanTTT) has made major contributions to overall quality, error handling, and Target performance.\n* [Justin King](https://github.com/jcking) has done a huge amount of work across multiple targets, but especially for C++.\n* [Ken Domino](https://github.com/kaby76) has a knack for finding bugs/issues and analysis; also a major contributor on the [grammars-v4 repo](https://github.com/antlr/grammars-v4).\n* [Jim Idle](https://github.com/jimidle) has contributed to previous versions of ANTLR and recently jumped back in to solve a major problem with the Go target.\n\n\n## Useful information\n\n* [Release notes](https://github.com/antlr/antlr4/releases)\n* [Getting started with v4](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md)\n* [Official site](http://www.antlr.org/)\n* [Documentation](https://github.com/antlr/antlr4/blob/master/doc/index.md)\n* [FAQ](https://github.com/antlr/antlr4/blob/master/doc/faq/index.md)\n* [ANTLR code generation targets](https://github.com/antlr/antlr4/blob/master/doc/targets.md)<br>(Currently: Java, C#, Python3, JavaScript, TypeScript, Go, C++, Swift, Dart, PHP)\n* _Note: As of version 4.14, we are dropping support for Python 2. We love the Python\ncommunity, but Python 2 support was officially halted in Jan 2020. More recently,\nGitHub also dropped support for Python 2, which has made it impossible for us to\nmaintain a consistent level of quality across targets (we use GitHub for our CI).\nLong live Python 3!_\n* [Java API](http://www.antlr.org/api/Java/index.html)\n* [ANTLR v3](http://www.antlr3.org/)\n* [v3 to v4 Migration, differences](https://github.com/antlr/antlr4/blob/master/doc/faq/general.md)\n\nYou might also find the following pages useful, particularly if you want to mess around with the various target languages.\n \n* [How to build ANTLR itself](https://github.com/antlr/antlr4/blob/master/doc/building-antlr.md)\n* [How we create and deploy an ANTLR release](https://github.com/antlr/antlr4/blob/master/doc/releasing-antlr.md)\n\n## The Definitive ANTLR 4 Reference\n\nProgrammers run into parsing problems all the time. Whether it’s a data format like JSON, a network protocol like SMTP, a server configuration file for Apache, a PostScript/PDF file, or a simple spreadsheet macro language—ANTLR v4 and this book will demystify the process. ANTLR v4 has been rewritten from scratch to make it easier than ever to build parsers and the language applications built on top. This completely rewritten new edition of the bestselling Definitive ANTLR Reference shows you how to take advantage of these new features.\n\nYou can buy the book [The Definitive ANTLR 4 Reference](http://amzn.com/dp/1934356999) at amazon or an [electronic version at the publisher's site](https://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference).\n\nYou will find the [Book source code](http://pragprog.com/titles/tpantlr2/source_code) useful.\n\n## Additional grammars\n[This repository](https://github.com/antlr/grammars-v4) is a collection of grammars without actions where the\nroot directory name is the all-lowercase name of the language parsed\nby the grammar. For example, java, cpp, csharp, c, etc...\n"
  },
  {
    "path": "antlr4-maven-plugin/nb-configuration.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project-shared-configuration>\n    <!--\nThis file contains additional configuration written by modules in the NetBeans IDE.\nThe configuration is intended to be shared among all the users of project and\ntherefore it is assumed to be part of version control checkout.\nWithout this configuration present, some functionality in the IDE may be limited or fail altogether.\n-->\n    <properties xmlns=\"http://www.netbeans.org/ns/maven-properties-data/1\">\n        <!--\nProperties that influence various parts of the IDE, especially code formatting and the like.\nYou can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.\nThat way multiple projects can share the same settings (useful for formatting rules for example).\nAny value defined here will override the pom.xml file value but is only applicable to the current project.\n-->\n        <org-netbeans-modules-editor-indent.CodeStyle.usedProfile>project</org-netbeans-modules-editor-indent.CodeStyle.usedProfile>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs>true</org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-line-wrap>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.continuationIndentSize>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.continuationIndentSize>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStarImport>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStarImport>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStaticStarImport>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStaticStarImport>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>*;java</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>\n        <netbeans.compile.on.save>test</netbeans.compile.on.save>\n    </properties>\n</project-shared-configuration>\n"
  },
  {
    "path": "antlr4-maven-plugin/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.antlr</groupId>\n    <artifactId>antlr4-master</artifactId>\n    <version>4.13.3-SNAPSHOT</version>\n  </parent>\n  <artifactId>antlr4-maven-plugin</artifactId>\n  <packaging>maven-plugin</packaging>\n  <name>ANTLR 4 Maven plugin</name>\n  <description>Maven plugin for ANTLR 4 grammars</description>\n\n  <!-- Ancillary information for completeness -->\n  <inceptionYear>2009</inceptionYear>\n\n  <properties>\n    <mavenVersion>3.8.5</mavenVersion>\n  </properties>\n\n  <!-- ============================================================================= -->\n\n  <!-- What are we depedent on for the Mojos to execute? We need the plugin\n    API itself and of course we need the ANTLR Tool and runtime and any of their\n    dependencies, which we inherit. The Tool itself provides us with all the\n    dependencies, so we need only name it here. -->\n  <dependencies>\n\n    <!-- The things we need to build the target language recognizer -->\n    <dependency>\n      <groupId>org.apache.maven</groupId>\n      <artifactId>maven-plugin-api</artifactId>\n      <version>${mavenVersion}</version>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.codehaus.plexus</groupId>\n      <artifactId>plexus-compiler-api</artifactId>\n      <version>2.12.1</version>\n    </dependency>\n    <dependency>\n      <groupId>org.sonatype.plexus</groupId>\n      <artifactId>plexus-build-api</artifactId>\n      <version>0.0.7</version>\n    </dependency>\n    <!-- The version of ANTLR tool that this version of the plugin controls.\n      We have decided that this should be in lockstep with ANTLR itself, other\n      than -1 -2 -3 etc patch releases. -->\n    <dependency>\n      <groupId>org.antlr</groupId>\n      <artifactId>antlr4</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <!-- Testing requirements... -->\n    <dependency>\n      <groupId>junit</groupId>\n      <artifactId>junit</artifactId>\n      <version>4.13.2</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.maven.plugin-tools</groupId>\n      <artifactId>maven-plugin-annotations</artifactId>\n      <version>3.6.4</version>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>io.takari.maven.plugins</groupId>\n        <artifactId>takari-plugin-testing</artifactId>\n        <version>3.0.0</version>\n        <scope>test</scope>\n    </dependency>\n    <dependency>\n        <groupId>org.apache.maven</groupId>\n        <artifactId>maven-core</artifactId>\n        <version>${mavenVersion}</version>\n        <scope>provided</scope>\n    </dependency>\n    <dependency>\n        <groupId>org.apache.maven</groupId>\n        <artifactId>maven-compat</artifactId>\n        <version>${mavenVersion}</version>\n        <scope>test</scope>\n    </dependency>\n    <dependency>\n        <groupId>org.codehaus.plexus</groupId>\n        <artifactId>plexus-utils</artifactId>\n        <version>3.4.2</version>\n        <scope>provided</scope>\n    </dependency>\n      <dependency>\n          <groupId>org.slf4j</groupId>\n          <artifactId>slf4j-api</artifactId>\n          <version>2.0.0</version>\n      </dependency>\n      <dependency>\n          <groupId>org.slf4j</groupId>\n          <artifactId>slf4j-simple</artifactId>\n          <version>2.0.0</version>\n      </dependency>\n  </dependencies>\n\n  <build>\n    <resources>\n      <resource>\n        <directory>resources</directory>\n      </resource>\n    </resources>\n    <testSourceDirectory>src/test</testSourceDirectory>\n    <testResources>\n      <testResource>\n        <directory>src/test/resources</directory>\n      </testResource>\n    </testResources>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-plugin-plugin</artifactId>\n        <version>3.6.2</version>\n        <configuration>\n          <!-- see http://jira.codehaus.org/browse/MNG-5346 -->\n          <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>\n        </configuration>\n        <executions>\n          <execution>\n            <id>mojo-descriptor</id>\n            <goals>\n              <goal>descriptor</goal>\n            </goals>\n          </execution>\n          <execution>\n            <id>help-goal</id>\n            <goals>\n              <goal>helpmojo</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n      <plugin>\n         <groupId>io.takari.maven.plugins</groupId>\n         <artifactId>takari-lifecycle-plugin</artifactId>\n         <version>2.0.7</version>         \n         <extensions>true</extensions>\n         <executions>\n           <execution>\n             <id>testProperties</id>\n             <phase>process-test-resources</phase>\n             <goals>\n               <goal>testProperties</goal>\n             </goals>\n           </execution>\n         </executions>\n       </plugin>\n        <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-compiler-plugin</artifactId>\n            <configuration>\n                <release>8</release>\n            </configuration>\n        </plugin>\n    </plugins>\n  </build>\n\n  <reporting>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-javadoc-plugin</artifactId>\n        <version>3.3.1</version>\n        <configuration>\n          <quiet>true</quiet>\n        </configuration>\n      </plugin>\n    </plugins>\n  </reporting>\n</project>\n"
  },
  {
    "path": "antlr4-maven-plugin/resources/META-INF/m2e/lifecycle-mapping-metadata.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<lifecycleMappingMetadata>\n    <pluginExecutions>\n        <pluginExecution>\n            <pluginExecutionFilter>\n                <goals>\n                    <goal>antlr4</goal>\n                </goals>\n            </pluginExecutionFilter>\n            <action>\n                <execute>\n                    <runOnIncremental>true</runOnIncremental>\n                    <runOnConfiguration>true</runOnConfiguration>\n                </execute>\n            </action>\n        </pluginExecution>\n    </pluginExecutions>\n</lifecycleMappingMetadata>\n"
  },
  {
    "path": "antlr4-maven-plugin/src/main/java/org/antlr/mojo/antlr4/Antlr4ErrorLog.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.mojo.antlr4;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.tool.ANTLRMessage;\nimport org.antlr.v4.tool.ANTLRToolListener;\nimport org.apache.maven.plugin.logging.Log;\nimport org.sonatype.plexus.build.incremental.BuildContext;\nimport org.stringtemplate.v4.ST;\n\nimport java.io.File;\n\n/**\n * This implementation of {@link ANTLRToolListener} reports messages to the\n * {@link Log} instance provided by Maven.\n *\n * @author Sam Harwell\n */\npublic class Antlr4ErrorLog implements ANTLRToolListener {\n\n    private final Tool tool;\n    private final BuildContext buildContext;\n    private final Log log;\n\n    /**\n     * Creates an instance of {@link Antlr4ErrorLog}.\n     *\n     * @param log The Maven log\n     */\n    public Antlr4ErrorLog(Tool tool, BuildContext buildContext, Log log) {\n        this.tool = tool;\n        this.buildContext = buildContext;\n        this.log = log;\n    }\n\n    /**\n     * {@inheritDoc}\n     * <p>\n     * This implementation passes the message to the Maven log.\n     * </p>\n     * @param message The message to send to Maven\n     */\n    @Override\n    public void info(String message) {\n        if (tool.errMgr.formatWantsSingleLineMessage()) {\n            message = message.replace('\\n', ' ');\n        }\n        log.info(message);\n    }\n\n    /**\n     * {@inheritDoc}\n     * <p>\n     * This implementation passes the message to the Maven log.\n     * </p>\n     * @param message The message to send to Maven.\n     */\n    @Override\n    public void error(ANTLRMessage message) {\n        ST msgST = tool.errMgr.getMessageTemplate(message);\n        String outputMsg = msgST.render();\n        if (tool.errMgr.formatWantsSingleLineMessage()) {\n            outputMsg = outputMsg.replace('\\n', ' ');\n        }\n\n        log.error(outputMsg);\n\n        if (message.fileName != null) {\n            String text = message.getMessageTemplate(false).render();\n            buildContext.addMessage(new File(message.fileName), message.line, message.charPosition, text, BuildContext.SEVERITY_ERROR, message.getCause());\n        }\n    }\n\n    /**\n     * {@inheritDoc}\n     * <p>\n     * This implementation passes the message to the Maven log.\n     * </p>\n     * @param message\n     */\n    @Override\n    public void warning(ANTLRMessage message) {\n        ST msgST = tool.errMgr.getMessageTemplate(message);\n        String outputMsg = msgST.render();\n        if (tool.errMgr.formatWantsSingleLineMessage()) {\n            outputMsg = outputMsg.replace('\\n', ' ');\n        }\n\n        log.warn(outputMsg);\n\n        if (message.fileName != null) {\n            String text = message.getMessageTemplate(false).render();\n            buildContext.addMessage(new File(message.fileName), message.line, message.charPosition, text, BuildContext.SEVERITY_WARNING, message.getCause());\n        }\n    }\n}\n"
  },
  {
    "path": "antlr4-maven-plugin/src/main/java/org/antlr/mojo/antlr4/Antlr4Mojo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.mojo.antlr4;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.runtime.misc.MultiMap;\nimport org.antlr.v4.runtime.misc.Utils;\nimport org.antlr.v4.tool.Grammar;\nimport org.apache.maven.plugin.AbstractMojo;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.plugin.MojoFailureException;\nimport org.apache.maven.plugin.logging.Log;\nimport org.apache.maven.plugins.annotations.Component;\nimport org.apache.maven.plugins.annotations.LifecyclePhase;\nimport org.apache.maven.plugins.annotations.Mojo;\nimport org.apache.maven.plugins.annotations.Parameter;\nimport org.apache.maven.plugins.annotations.ResolutionScope;\nimport org.apache.maven.project.MavenProject;\nimport org.codehaus.plexus.compiler.util.scan.InclusionScanException;\nimport org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner;\nimport org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner;\nimport org.codehaus.plexus.compiler.util.scan.mapping.SourceMapping;\nimport org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping;\nimport org.sonatype.plexus.build.incremental.BuildContext;\n\nimport java.io.BufferedWriter;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.net.URI;\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Parses ANTLR 4 grammar files {@code *.g4} and transforms them into Java\n * source files.\n *\n * @author Sam Harwell\n */\n@Mojo(\n\tname = \"antlr4\",\n\tdefaultPhase = LifecyclePhase.GENERATE_SOURCES,\n\trequiresDependencyResolution = ResolutionScope.COMPILE,\n\trequiresProject = true, threadSafe = true)\npublic class Antlr4Mojo extends AbstractMojo {\n\n    // First, let's deal with the options that the ANTLR tool itself\n    // can be configured by.\n    //\n\n    /**\n     * If set to true then the ANTLR tool will generate a description of the ATN\n     * for each rule in <a href=\"http://www.graphviz.org\">Dot format</a>.\n     */\n    @Parameter(property = \"antlr4.atn\", defaultValue = \"false\")\n    protected boolean atn;\n\n\t/**\n\t * specify grammar file encoding; e.g., euc-jp\n\t */\n\t@Parameter(property = \"project.build.sourceEncoding\")\n\tprotected String inputEncoding;\n\n\t/**\n\t * specify output file encoding; defaults to source encoding\n\t */\n\t@Parameter(property = \"project.build.sourceEncoding\")\n\tprotected String outputEncoding;\n\n\t/**\n\t * Generate parse tree listener interface and base class.\n\t */\n\t@Parameter(property = \"antlr4.listener\", defaultValue = \"true\")\n\tprotected boolean listener;\n\n\t/**\n\t * Generate parse tree visitor interface and base class.\n\t */\n\t@Parameter(property = \"antlr4.visitor\", defaultValue = \"false\")\n\tprotected boolean visitor;\n\n\t/**\n\t * Treat warnings as errors.\n\t */\n\t@Parameter(property = \"antlr4.treatWarningsAsErrors\", defaultValue = \"false\")\n\tprotected boolean treatWarningsAsErrors;\n\n\t/**\n\t * Use the ATN simulator for all predictions.\n\t */\n\t@Parameter(property = \"antlr4.forceATN\", defaultValue = \"false\")\n\tprotected boolean forceATN;\n\n\t/**\n\t * A list of grammar options to explicitly specify to the tool. These\n\t * options are passed to the tool using the\n\t * <code>-D&lt;option&gt;=&lt;value&gt;</code> syntax.\n\t */\n\t@Parameter\n\tprotected Map<String, String> options;\n\n\t/**\n\t * A list of additional command line arguments to pass to the ANTLR tool.\n\t */\n\t@Parameter\n\tprotected List<String> arguments;\n\n    /* --------------------------------------------------------------------\n     * The following are Maven specific parameters, rather than specific\n     * options that the ANTLR tool can use.\n     */\n\n\t/**\n\t * Provides an explicit list of all the grammars that should be included in\n\t * the generate phase of the plugin. Note that the plugin is smart enough to\n\t * realize that imported grammars should be included but not acted upon\n\t * directly by the ANTLR Tool.\n\t * <p>\n\t * A set of Ant-like inclusion patterns used to select files from the source\n\t * directory for processing. By default, the pattern\n\t * <code>**&#47;*.g4</code> is used to select grammar files.\n\t * </p>\n\t */\n    @Parameter\n    protected Set<String> includes = new HashSet<String>();\n    /**\n     * A set of Ant-like exclusion patterns used to prevent certain files from\n     * being processed. By default, this set is empty such that no files are\n     * excluded.\n     */\n    @Parameter\n    protected Set<String> excludes = new HashSet<String>();\n    /**\n     * The current Maven project.\n     */\n    @Parameter(property = \"project\", required = true, readonly = true)\n    protected MavenProject project;\n\n\t/**\n\t * Specifies whether sources are added to the {@code compile} or\n\t * {@code test} scope.\n\t */\n\t@Parameter(property = \"antlr4.generateTestSources\", defaultValue = \"false\")\n\tprivate boolean generateTestSources;\n\n    /**\n     * The directory where the ANTLR grammar files ({@code *.g4}) are located.\n     */\n\t@Parameter(defaultValue = \"${basedir}/src/main/antlr4\")\n    private File sourceDirectory;\n\n    /**\n     * Specify output directory where the Java files are generated.\n     */\n\t@Parameter(defaultValue = \"${project.build.directory}/generated-sources/antlr4\")\n    private File outputDirectory;\n\n    /**\n     * Specify location of imported grammars and tokens files.\n     */\n\t@Parameter(defaultValue = \"${basedir}/src/main/antlr4/imports\")\n    private File libDirectory;\n\n    /**\n     * The directory where build status information is located.\n     */\n    @Parameter(defaultValue = \"${project.build.directory}/maven-status/antlr4\", readonly=true)\n    private File statusDirectory;\n\n\t@Component\n\tprivate BuildContext buildContext;\n\n    public File getSourceDirectory() {\n        return sourceDirectory;\n    }\n\n    public File getOutputDirectory() {\n        return outputDirectory;\n    }\n\n    public File getLibDirectory() {\n        return libDirectory;\n    }\n\n    void addSourceRoot(File outputDir) {\n\t\tif (generateTestSources) {\n\t\t\tproject.addTestCompileSourceRoot(outputDir.getPath());\n\t\t}\n\t\telse {\n\t\t\tproject.addCompileSourceRoot(outputDir.getPath());\n\t\t}\n    }\n\n    /**\n     * An instance of the ANTLR tool build\n     */\n    protected Tool tool;\n\n    /**\n     * The main entry point for this Mojo, it is responsible for converting\n     * ANTLR 4.x grammars into the target language specified by the grammar.\n     *\n     * @exception MojoExecutionException if a configuration or grammar error causes\n     * the code generation process to fail\n     * @exception MojoFailureException if an instance of the ANTLR 4 {@link Tool}\n     * cannot be created\n     */\n    @Override\n    public void execute() throws MojoExecutionException, MojoFailureException {\n\n        Log log = getLog();\n\n\t\toutputEncoding = validateEncoding(outputEncoding);\n\n        if (log.isDebugEnabled()) {\n            for (String e : excludes) {\n                log.debug(\"ANTLR: Exclude: \" + e);\n            }\n\n            for (String e : includes) {\n                log.debug(\"ANTLR: Include: \" + e);\n            }\n\n            log.debug(\"ANTLR: Output: \" + outputDirectory);\n            log.debug(\"ANTLR: Library: \" + libDirectory);\n        }\n\n\t\tif (!sourceDirectory.isDirectory()) {\n\t\t\tlog.info(\"No ANTLR 4 grammars to compile in \" + sourceDirectory.getAbsolutePath());\n\t\t\treturn;\n\t\t}\n\n        // Ensure that the output directory path is all in tact so that\n        // ANTLR can just write into it.\n        //\n        File outputDir = getOutputDirectory();\n\n        if (!outputDir.exists()) {\n            outputDir.mkdirs();\n        }\n\n        GrammarDependencies dependencies = new GrammarDependencies(sourceDirectory, libDirectory, arguments, getDependenciesStatusFile(), getLog());\n\n\t\t// Now pick up all the files and process them with the Tool\n\t\t//\n\n\t\tList<List<String>> argumentSets;\n        Set<File> grammarFiles;\n        Set<File> importGrammarFiles;\n        try {\n\t\t\tList<String> args = getCommandArguments();\n            grammarFiles = getGrammarFiles(sourceDirectory);\n            importGrammarFiles = getImportFiles(sourceDirectory);\n            argumentSets = processGrammarFiles(args, grammarFiles, dependencies, sourceDirectory);\n        } catch (Exception e) {\n            log.error(e);\n            throw new MojoExecutionException(\"Fatal error occured while evaluating the names of the grammar files to analyze\", e);\n        }\n\n\t\tlog.debug(\"Output directory base will be \" + outputDirectory.getAbsolutePath());\n\t\tlog.info(\"ANTLR 4: Processing source directory \" + sourceDirectory.getAbsolutePath());\n\t\tfor (List<String> args : argumentSets) {\n\t\t\ttry {\n\t\t\t\t// Create an instance of the ANTLR 4 build tool\n\t\t\t\ttool = new CustomTool(args.toArray(new String[0]));\n\t\t\t} catch (Exception e) {\n\t\t\t\tlog.error(\"The attempt to create the ANTLR 4 build tool failed, see exception report for details\", e);\n\t\t\t\tthrow new MojoFailureException(\"Error creating an instanceof the ANTLR tool.\", e);\n\t\t\t}\n\n            try {\n                dependencies.analyze(grammarFiles, importGrammarFiles, tool);\n            } catch (Exception e) {\n                log.error(\"Dependency analysis failed, see exception report for details\",\n                    e);\n                throw new MojoFailureException(\"Dependency analysis failed.\", e);\n            }\n\n\t\t\t// Set working directory for ANTLR to be the base source directory\n\t\t\ttool.inputDirectory = sourceDirectory;\n\n\t\t\ttool.processGrammarsOnCommandLine();\n\n\t\t\t// If any of the grammar files caused errors but did nto throw exceptions\n\t\t\t// then we should have accumulated errors in the counts\n\t\t\tif (tool.getNumErrors() > 0) {\n\t\t\t\tthrow new MojoExecutionException(\"ANTLR 4 caught \" + tool.getNumErrors() + \" build errors.\");\n\t\t\t}\n\t\t}\n\n        if (project != null) {\n            // Tell Maven that there are some new source files underneath the output directory.\n            addSourceRoot(this.getOutputDirectory());\n        }\n\n        try {\n            dependencies.save();\n        } catch (IOException ex) {\n            log.warn(\"Could not save grammar dependency status\", ex);\n        }\n    }\n\n\tprivate List<String> getCommandArguments() {\n\t\tList<String> args = new ArrayList<String>();\n\n\t\tif (getOutputDirectory() != null) {\n\t\t\targs.add(\"-o\");\n\t\t\targs.add(outputDirectory.getAbsolutePath());\n\t\t}\n\n\t\t// Where do we want ANTLR to look for .tokens and import grammars?\n\t\tif (getLibDirectory() != null && getLibDirectory().isDirectory()) {\n\t\t\targs.add(\"-lib\");\n\t\t\targs.add(libDirectory.getAbsolutePath());\n\t\t}\n\n        // Next we need to set the options given to us in the pom into the\n        // tool instance we have created.\n\t\tif (atn) {\n\t\t\targs.add(\"-atn\");\n\t\t}\n\n\t\tif ( inputEncoding!=null && !inputEncoding.isEmpty()) {\n\t\t\targs.add(\"-encoding\");\n\t\t\toutputEncoding = inputEncoding;\n\t\t\targs.add(inputEncoding);\n\t\t}\n\n\t\tif (listener) {\n\t\t\targs.add(\"-listener\");\n\t\t}\n\t\telse {\n\t\t\targs.add(\"-no-listener\");\n\t\t}\n\n\t\tif (visitor) {\n\t\t\targs.add(\"-visitor\");\n\t\t}\n\t\telse {\n\t\t\targs.add(\"-no-visitor\");\n\t\t}\n\n\t\tif (treatWarningsAsErrors) {\n\t\t\targs.add(\"-Werror\");\n\t\t}\n\n\t\tif (forceATN) {\n\t\t\targs.add(\"-Xforce-atn\");\n\t\t}\n\n\t\tif (options != null) {\n\t\t\tfor (Map.Entry<String, String> option : options.entrySet()) {\n\t\t\t\targs.add(String.format(\"-D%s=%s\", option.getKey(), option.getValue()));\n\t\t\t}\n\t\t}\n\n\t\tif (arguments != null) {\n\t\t\targs.addAll(arguments);\n\t\t}\n\n\t\treturn args;\n\t}\n\n    /**\n     *\n     * @param sourceDirectory\n     * @exception InclusionScanException\n     */\n    private List<List<String>> processGrammarFiles(\n        List<String> args,\n        Set<File> grammarFiles,\n        GrammarDependencies dependencies,\n        File sourceDirectory) throws InclusionScanException, IOException {\n\n        // We don't want the plugin to run for every grammar, regardless of whether\n        // it's changed since the last compilation. Check the mtime of the tokens vs\n        // the grammar file mtime to determine whether we even need to execute.\n        Set<File> grammarFilesToProcess = new HashSet<File>();\n\n        for (File grammarFile : grammarFiles) {\n            String tokensFileName = grammarFile.getName().split(\"\\\\.\")[0] + \".tokens\";\n            File outputFile = new File(outputDirectory, tokensFileName);\n            if ( (! outputFile.exists()) ||\n                 outputFile.lastModified() <= grammarFile.lastModified() ||\n                 dependencies.isDependencyChanged(grammarFile)) {\n                grammarFilesToProcess.add(grammarFile);\n            }\n        }\n\n        grammarFiles = grammarFilesToProcess;\n\n        if (grammarFiles.isEmpty()) {\n            getLog().info(\"No grammars to process\");\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tMultiMap<String, File> grammarFileByFolder = new MultiMap<String, File>();\n\t\t// Iterate each grammar file we were given and add it into the tool's list of\n\t\t// grammars to process.\n\t\tfor (File grammarFile : grammarFiles) {\n\t\t\tbuildContext.refresh(grammarFile);\n\t\t\tbuildContext.removeMessages(grammarFile);\n\n\t\t\tgetLog().debug(\"Grammar file '\" + grammarFile.getPath() + \"' detected.\");\n\n\t\t\tString relPathBase = MojoUtils.findSourceSubdir(sourceDirectory, grammarFile);\n\t\t\tString relPath = relPathBase + grammarFile.getName();\n\t\t\tgetLog().debug(\"  ... relative path is: \" + relPath);\n\n\t\t\tgrammarFileByFolder.map(relPathBase, grammarFile);\n\t\t}\n\n\t\tList<List<String>> result = new ArrayList<List<String>>();\n\t\tfor (Map.Entry<String, List<File>> entry : grammarFileByFolder.entrySet()) {\n\t\t\tList<String> folderArgs = new ArrayList<String>(args);\n\t\t\tif (!folderArgs.contains(\"-package\") && !entry.getKey().isEmpty()) {\n\t\t\t\tfolderArgs.add(\"-package\");\n\t\t\t\tfolderArgs.add(getPackageName(entry.getKey()));\n\t\t\t}\n\n\t\t\tfor (File file : entry.getValue()) {\n\t\t\t\tfolderArgs.add(entry.getKey() + file.getName());\n\t\t\t}\n\n\t\t\tresult.add(folderArgs);\n\t\t}\n\n\t\treturn result;\n\t}\n\n    private Set<File> getImportFiles(File sourceDirectory) throws InclusionScanException {\n        if (!libDirectory.exists()) return Collections.emptySet();\n\n        Set<String> includes = new HashSet<String>();\n        includes.add(\"*.g4\");\n        includes.add(\"*.tokens\");\n\n        SourceInclusionScanner scan = new SimpleSourceInclusionScanner(includes,\n                Collections.<String>emptySet());\n        scan.addSourceMapping(new SuffixMapping(\"G4\", \"g4\"));\n\n        return scan.getIncludedSources(libDirectory, null);\n    }\n\n\tprivate Set<File> getGrammarFiles(File sourceDirectory) throws InclusionScanException\n\t{\n\t\t// Which files under the source set should we be looking for as grammar files\n\t\tSourceMapping mapping = new SuffixMapping(\"g4\", Collections.<String>emptySet());\n\n\t\t// What are the sets of includes (defaulted or otherwise).\n\t\tSet<String> includes = getIncludesPatterns();\n\n\t\t// Now, to the excludes, we need to add the imports directory\n\t\t// as this is autoscanned for imported grammars and so is auto-excluded from the\n\t\t// set of grammar fields we should be analyzing.\n\t\texcludes.add(\"imports/**\");\n\n\t\tSourceInclusionScanner scan = new SimpleSourceInclusionScanner(includes, excludes);\n\t\tscan.addSourceMapping(mapping);\n\n\t\treturn scan.getIncludedSources(sourceDirectory, null);\n\t}\n\n\tprivate static String getPackageName(String relativeFolderPath) {\n\t\tif (relativeFolderPath.contains(\"..\")) {\n\t\t\tthrow new UnsupportedOperationException(\"Cannot handle relative paths containing '..'\");\n\t\t}\n\n\t\tList<String> parts = new ArrayList<String>(Arrays.asList(relativeFolderPath.split(\"[/\\\\\\\\\\\\.]+\")));\n\t\twhile (parts.remove(\"\")) {\n\t\t\t// intentionally blank\n\t\t}\n\n\t\treturn Utils.join(parts.iterator(), \".\");\n\t}\n\n    public Set<String> getIncludesPatterns() {\n        if (includes == null || includes.isEmpty()) {\n            return Collections.singleton(\"**/*.g4\");\n        }\n        return includes;\n    }\n\n    private File getDependenciesStatusFile() {\n        File statusFile = new File(statusDirectory, \"dependencies.ser\");\n\n        if (!statusFile.getParentFile().exists()) {\n            statusFile.getParentFile().mkdirs();\n        }\n\n        return statusFile;\n    }\n\n\tprivate final class CustomTool extends Tool {\n\n\t\tpublic CustomTool(String[] args) {\n\t\t\tsuper(args);\n\t\t\taddListener(new Antlr4ErrorLog(this, buildContext, getLog()));\n\t\t}\n\n\t\t@Override\n\t\tpublic void process(Grammar g, boolean gencode) {\n\t\t\tgetLog().info(\"Processing grammar: \" + g.fileName);\n\t\t\tsuper.process(g, gencode);\n\t\t}\n\n\t\t@Override\n\t\tpublic Writer getOutputFileWriter(Grammar g, String fileName) throws IOException {\n\t\t\tif (outputDirectory == null) {\n\t\t\t\treturn new StringWriter();\n\t\t\t}\n\t\t\t// output directory is a function of where the grammar file lives\n\t\t\t// for subdir/T.g4, you get subdir here.  Well, depends on -o etc...\n\t\t\t// But, if this is a .tokens file, then we force the output to\n\t\t\t// be the base output directory (or current directory if there is not a -o)\n\t\t\t//\n\t\t\tFile outputDir;\n\t\t\tif ( fileName.endsWith(CodeGenerator.VOCAB_FILE_EXTENSION) ) {\n\t\t\t\toutputDir = new File(outputDirectory);\n\t\t\t}\n\t\t\telse {\n\t\t\t\toutputDir = getOutputDirectory(g.fileName);\n\t\t\t}\n\n\t\t\tFile outputFile = new File(outputDir, fileName);\n\t\t\tif (!outputDir.exists()) {\n\t\t\t\toutputDir.mkdirs();\n\t\t\t}\n\n\t\t\tURI relativePath = project.getBasedir().toURI().relativize(outputFile.toURI());\n\t\t\tgetLog().debug(\"  Writing file: \" + relativePath);\n\t\t\tOutputStream outputStream = buildContext.newFileOutputStream(outputFile);\n\t\t\tif ( outputEncoding!=null && !outputEncoding.isEmpty()) {\n\t\t\t\treturn new BufferedWriter(new OutputStreamWriter(outputStream, outputEncoding));\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn new BufferedWriter(new OutputStreamWriter(outputStream));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Validates the given encoding.\n\t *\n\t * @return  the validated encoding. If {@code null} was provided, returns the platform default encoding.\n\t */\n\tprivate String validateEncoding(String encoding) {\n\t\treturn (encoding == null) ? Charset.defaultCharset().name() : Charset.forName(encoding.trim()).name();\n\t}\n}\n"
  },
  {
    "path": "antlr4-maven-plugin/src/main/java/org/antlr/mojo/antlr4/GrammarDependencies.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.mojo.antlr4;\n\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.misc.Graph;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\nimport org.apache.maven.plugin.logging.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.util.AbstractMap;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n\nclass GrammarDependencies {\n    private final Graph<String> graph = new Graph<String>();\n    private final File sourceDirectory;\n    private final File libDirectory;\n    private final File statusFile;\n    private final String packageName;\n\n    /** Map grammars to their checksum and references. */\n    private final Map<File, Map.Entry<byte[], Collection<String>>> grammars;\n    private final Log log;\n\n    public GrammarDependencies(File sourceDirectory, File libDirectory,\n        List<String> arguments, File status, Log log) {\n        this.log = log;\n        this.sourceDirectory = sourceDirectory;\n        this.libDirectory = libDirectory;\n        this.statusFile = status;\n        this.grammars = loadStatus(status);\n        this.packageName = getPackage(arguments);\n    }\n\n    /**\n     * Determines the package to use.\n     *\n     * @param   arguments  the tool arguments.\n     *\n     * @return  the package. Returns {@code null} to indicate that no package should be\n     *          used.\n     */\n    private String getPackage(List<String> arguments) {\n        int index = (arguments != null) ? arguments.indexOf(\"-package\") : -1;\n\n        return (index > -1)\n            ? (arguments.get(index + 1).replace('.', File.separatorChar) +\n                File.separatorChar)\n            : null;\n    }\n\n    public void save() throws IOException {\n        if (!grammars.isEmpty()) {\n            log.debug(\"Persisting grammars dependency status: \" + statusFile);\n\n            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(\n                        statusFile));\n\n            try {\n                out.writeObject(grammars);\n            } finally {\n                out.close();\n            }\n        }\n    }\n\n    /**\n     * Performs dependency analysis for the given grammar files.\n     *\n     * @param   grammarFiles        the grammar files.\n     * @param   importGrammarFiles  the import grammar files.\n     * @param   tool                the tool to use.\n     *\n     * @return  self-reference.\n     */\n    public GrammarDependencies analyze(Set<File> grammarFiles,\n        Set<File> importGrammarFiles, Tool tool) throws IOException {\n        log.debug(\"Analysing grammar dependencies \" + sourceDirectory);\n\n        // for dependency analysis we require all grammars\n        Collection<File> grammarsAndTokens = new HashSet<File>();\n        grammarsAndTokens.addAll(importGrammarFiles);\n        grammarsAndTokens.addAll(grammarFiles);\n\n        for (File grammarFile : grammarsAndTokens) {\n            // .tokens files must not be parsed, they can just be referenced\n            if (!grammarFile.getName().endsWith(\".tokens\"))\n                analyse(grammarFile, grammarsAndTokens, tool);\n        }\n\n        for (File grammarFile : grammarFiles) {\n            Collection<String> usages = findUsages(getRelativePath(grammarFile));\n\n            if (!usages.isEmpty()) {\n                grammars.put(grammarFile,\n                    new AbstractMap.SimpleImmutableEntry<byte[], Collection<String>>(\n                        MojoUtils.checksum(grammarFile), usages));\n\n                log.debug(\"  \" + getRelativePath(grammarFile) + \" used by \" + usages);\n            }\n        }\n\n        for (File grammarFile : importGrammarFiles) {\n            // imported files are not allowed to be qualified\n            Collection<String> usages = findUsages(grammarFile.getName());\n\n            if (!usages.isEmpty()) {\n                grammars.put(grammarFile,\n                    new AbstractMap.SimpleImmutableEntry<byte[], Collection<String>>(\n                        MojoUtils.checksum(grammarFile), usages));\n\n                log.debug(\"  \" + grammarFile.getName() + \" imported by \" + usages);\n            }\n        }\n\n        return this;\n    }\n\n\n    /**\n     * Determines whether a grammar used by the given grammar was modified since the last\n     * build.\n     *\n     * @param   grammarFile  the grammar.\n     *\n     * @return  {@code true} if a grammar used by the given grammar has been modified.\n     */\n    public boolean isDependencyChanged(File grammarFile) throws IOException {\n        String grammarPath = getRelativePath(grammarFile);\n\n        for (Map.Entry<File, Map.Entry<byte[], Collection<String>>> e : grammars.entrySet()) {\n            File depGrammarFile = e.getKey();\n            byte[] checksum = e.getValue().getKey();\n            Collection<String> usages = e.getValue().getValue();\n\n            if (usages.contains(grammarPath)) {\n                if (!depGrammarFile.exists() || !Arrays.equals(MojoUtils.checksum(depGrammarFile), checksum)) {\n                    log.debug(\"  \" + grammarPath + \": dependency \" +\n                        depGrammarFile.getName() + \" changed\");\n\n                    return true;\n                }\n            }\n        }\n\n        return false;\n    }\n\n    /**\n     * Determines the relative target path of the given grammar file.\n     *\n     * @param   grammarFile  the grammar file.\n     *\n     * @return  the relative path.\n     */\n    private String getRelativePath(File grammarFile) {\n        // the library directory does not allow sub-directories\n        if (grammarFile.getPath().startsWith(libDirectory.getPath()))\n            return grammarFile.getName();\n\n        // if a package is given, we have to use it\n        if (packageName != null)\n            return packageName + grammarFile.getName();\n\n        // otherwise resolve the path relative to the source directory\n        String path = MojoUtils.findSourceSubdir(sourceDirectory, grammarFile);\n\n        return path + grammarFile.getName();\n    }\n\n    /**\n     * Returns the grammar file names that directly or indirectly use the given grammar.\n     *\n     * @param   grammarFileName  the grammar file name.\n     *\n     * @return  the grammar file names that use the given grammar file.\n     */\n    private Collection<String> findUsages(String grammarFileName) {\n        Collection<String> result = new ArrayList<String>();\n        explore(grammarFileName, result);\n\n        return result;\n    }\n\n    private void explore(String grammarName, Collection<String> result) {\n        for (Graph.Node<String> node : graph.getNode(grammarName).edges) {\n            result.add(node.payload);\n            explore(node.payload, result);\n        }\n    }\n\n    private void analyse(File grammarFile, Collection<File> grammarFiles, Tool tool) {\n        GrammarRootAST grammar = tool.parseGrammar(grammarFile.getAbsolutePath());\n\n        if (grammar == null)\n            return;\n\n        for (GrammarAST importDecl : grammar.getAllChildrenWithType(ANTLRParser.IMPORT)) {\n            for (Tree id: importDecl.getAllChildrenWithType(ANTLRParser.ID)) {\n                // missing id is not valid, but we don't want to prevent the root cause from\n                // being reported by the ANTLR tool\n                if (id != null) {\n                    String grammarPath = getRelativePath(grammarFile);\n\n                    graph.addEdge(id.getText() + \".g4\", grammarPath);\n                }\n            }\n        }\n\n        for (GrammarAST options : grammar.getAllChildrenWithType(ANTLRParser.OPTIONS)) {\n            for (int i = 0, count = options.getChildCount(); i < count; i++) {\n                Tree option = options.getChild(i);\n\n                if (option.getType() == ANTLRParser.ASSIGN) {\n                    String key = option.getChild(0).getText();\n                    String value = option.getChild(1).getText();\n\n                    if (\"tokenVocab\".equals(key)) {\n                        String name = stripQuotes(value);\n                        // the grammar name may be qualified, but we resolve the path anyway\n                        String grammarName = stripPath(name);\n                        String grammarPath = MojoUtils.findSourceSubdir(sourceDirectory,\n                                grammarFile);\n                        File depGrammarFile = resolve(grammarName, grammarPath);\n\n                        // if a package has been given, we use it instead of the file directory path\n                        // (files probably reside in the root directory anyway with such a configuration )\n                        if (packageName != null)\n                            grammarPath = packageName;\n\n                        graph.addEdge(getRelativePath(depGrammarFile),\n                            grammarPath + grammarFile.getName());\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Resolves the given grammar name.\n     *\n     * @param   name  the name.\n     * @param   path  the relative path.\n     *\n     * @return  the grammar file.\n     */\n    private File resolve(String name, String path) {\n        File file = new File(sourceDirectory, path + name + \".g4\");\n\n        if (file.exists())\n            return file;\n\n        file = new File(libDirectory, name + \".g4\");\n\n        if (file.exists())\n            return file;\n\n        return new File(libDirectory, name + \".tokens\");\n    }\n\n    private Map<File, Map.Entry<byte[], Collection<String>>> loadStatus(File statusFile) {\n        if (statusFile.exists()) {\n            log.debug(\"Load grammars dependency status: \" + statusFile);\n\n            try {\n                ObjectInputStream in = new ObjectInputStream(new FileInputStream(\n                            statusFile));\n\n                try {\n                    @SuppressWarnings(\"unchecked\")\n                    Map<File, Map.Entry<byte[], Collection<String>>> data =\n                        (Map<File, Map.Entry<byte[], Collection<String>>>)\n                        in.readObject();\n\n                    return data;\n                } finally {\n                    in.close();\n                }\n            } catch (Exception ex) {\n                log.warn(\"Could not load grammar dependency status information\", ex);\n            }\n        }\n\n        return new HashMap<File, Map.Entry<byte[], Collection<String>>>();\n    }\n\n    private String stripPath(String str) {\n        return str.replaceAll(\"^.*[/\\\\\\\\]\", \"\");\n    }\n\n    private String stripQuotes(String str) {\n        return str.replaceAll(\"\\\\A'|'\\\\Z\", \"\");\n    }\n}\n"
  },
  {
    "path": "antlr4-maven-plugin/src/main/java/org/antlr/mojo/antlr4/MojoUtils.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.mojo.antlr4;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\n\nclass MojoUtils {\n    /**\n     * Creates the MD5 checksum for the given file.\n     *\n     * @param   file  the file.\n     *\n     * @return  the checksum.\n     */\n    public static byte[] checksum(File file) throws IOException {\n        try {\n            InputStream in = new FileInputStream(file);\n            byte[] buffer = new byte[2048];\n            MessageDigest complete = MessageDigest.getInstance(\"MD5\");\n\n            try {\n                int n;\n\n                do {\n                    n = in.read(buffer);\n\n                    if (n > 0) {\n                        complete.update(buffer, 0, n);\n                    }\n                } while (n != -1);\n            } finally {\n                in.close();\n            }\n\n            return complete.digest();\n        } catch (NoSuchAlgorithmException ex) {\n            throw new IOException(\"Could not create checksum \" + file, ex);\n        }\n    }\n\n    /**\n     * Given the source directory File object and the full PATH to a grammar, produce the\n     * path to the named grammar file in relative terms to the {@code sourceDirectory}.\n     * This will then allow ANTLR to produce output relative to the base of the output\n     * directory and reflect the input organization of the grammar files.\n     *\n     * @param   sourceDirectory  The source directory {@link File} object\n     * @param   grammarFileName  The full path to the input grammar file\n     *\n     * @return  The path to the grammar file relative to the source directory\n     */\n    public static String findSourceSubdir(File sourceDirectory, File grammarFile) {\n        String srcPath = sourceDirectory.getPath() + File.separator;\n        String path = grammarFile.getPath();\n\n        if (!path.startsWith(srcPath)) {\n            throw new IllegalArgumentException(\"expected \" + path +\n                \" to be prefixed with \" + sourceDirectory);\n        }\n\n        File unprefixedGrammarFileName = new File(path.substring(srcPath.length()));\n\n        if (unprefixedGrammarFileName.getParent() == null) {\n            return \"\";\n        }\n\n        return unprefixedGrammarFileName.getParent() + File.separator;\n    }\n}\n"
  },
  {
    "path": "antlr4-maven-plugin/src/site/apt/examples/import.apt",
    "content": "Imported Grammar Files\n\n In order to have the ANTLR plugin automatically locate and use grammars used\n as imports in your main <<<.g4>>> files, you need to place the imported grammar\n files in the <<<imports>>> directory beneath the root directory of your grammar\n files (which is <<<src/main/antlr4>>> by default of course).\n\n For a default layout, place your import grammars in the directory: <<<src/main/antlr4/imports>>>\n"
  },
  {
    "path": "antlr4-maven-plugin/src/site/apt/examples/libraries.apt.vm",
    "content": "Libraries\n\n The introduction of the import directive in a grammar allows reuse of common grammar files\n as well as the ability to divide up functional components of large grammars. However it has\n caused some confusion in regard to the fact that generated vocabulary files (<<<*.tokens>>>) can also\n be searched for with the <<<<libDirectory>>>> directive.\n\n This has confused two separate functions and imposes a structure upon the layout of\n your grammar files in certain cases. If you have grammars that both use the import\n directive and also require the use of a vocabulary file then you will need to locate\n the grammar that generates the <<<.tokens>>> file alongside the grammar that uses it. This\n is because you will need to use the <<<<libDirectory>>>> directive to specify the\n location of your imported grammars and ANTLR will not find any vocabulary files in\n this directory.\n\n The <<<.tokens>>> files for any grammars are generated within the same output directory structure\n as the <<<.java>>> files. So, wherever the <<<.java>>> files are generated, you will also find the <<<.tokens>>>\n files. ANTLR looks for <<<.tokens>>> files in both the <<<<libDirectory>>>> and the output directory\n where it is placing the generated <<<.java>>> files. Hence when you locate the grammars that generate\n <<<.tokens>>> files in the same source directory as the ones that use the <<<.tokens>>> files, then\n the Maven plugin will find the expected <<<.tokens>>> files.\n\n The <<<<libDirectory>>>> is specified like any other directory parameter in Maven. Here is an\n example:\n\n+--\n<plugin>\n    <groupId>org.antlr</groupId>\n    <artifactId>antlr4-maven-plugin</artifactId>\n    <version>${project.version}</version>\n\n    <executions>\n        <execution>\n            <configuration>\n                <goals>\n                    <goal>antlr4</goal>\n                </goals>\n                <libDirectory>src/main/antlr4_imports</libDirectory>\n            </configuration>\n        </execution>\n    </executions>\n</plugin>\n+--\n\n\n\n"
  },
  {
    "path": "antlr4-maven-plugin/src/site/apt/examples/simple.apt.vm",
    "content": "Simple configuration\n\n If your grammar files are organized into the default locations as described in the {{{../index.html}introduction}},\n then configuring the <<<pom.xml>>> file for your project is as simple as adding this to it\n\n+--\n<plugins>\n<plugin>\n    <groupId>org.antlr</groupId>\n    <artifactId>antlr4-maven-plugin</artifactId>\n    <version>${project.version}</version>\n    <executions>\n        <execution>\n            <goals>\n                <goal>antlr4</goal>\n            </goals>\n        </execution>\n    </executions>\n</plugin>\n...\n</plugins>\n+--\n\n When the <<<mvn>>> command is executed all grammar files under <<<src/main/antlr4>>>, except any\n import grammars under <<<src/main/antlr4/imports>>> will be analyzed and converted to\n Java source code in the output directory <<<target/generated-sources/antlr4>>>.\n\n Your input files under <<<antlr4>>> should be stored in sub directories that\n reflect the package structure of your java parsers. If your grammar file <<<parser.g4>>> contains:\n\n+---\n@header {\npackage org.jimi.themuss;\n}\n+---\n\n Then the <<<.g4>>> file should be stored in: <<<src/main/antlr4/org/jimi/themuss/parser.g4>>>. This way\n the generated <<<.java>>> files will correctly reflect the package structure in which they will\n finally rest as classes.\n\n"
  },
  {
    "path": "antlr4-maven-plugin/src/site/apt/faq.apt.vm",
    "content": "FAQ\n"
  },
  {
    "path": "antlr4-maven-plugin/src/site/apt/index.apt",
    "content": "         -------------\n         ANTLR v4 Maven Plugin\n         -------------\n         Jim Idle\n         -------------\n         March 2009\n         -------------\n\nANTLR v4 Maven plugin\n\n The ANTLR v4 Maven plugin is completely re-written as of version 4.0; if you are familiar\n with prior versions, you should note that there are some behavioral differences that make\n it worthwhile reading this documentation. \n\n The job of the plugin is essentially to tell the standard ANTLR parser generator where the\n input grammar files are and where the output files should be generated. As with all Maven\n plugins, there are defaults, which you are advised to comply to, but are not forced to\n comply to.\n\n This version of the plugin allows full control over ANTLR and allows configuration of all\n options that are useful for a build system. The code required to calculate dependencies,\n check the build order, and otherwise work with your grammar files is built into the ANTLR\n tool as of version 4.0 of ANTLR and this plugin.\n\n* Plugin Versioning\n\n The plugin version tracks the version of the ANTLR tool that it controls. Hence if you\n use version 4.0 of the plugin, you will build your grammars using version 4.0 of the\n ANTLR tool, version 4.2 of the plugin will use version 4.2 of the ANTLR tool and so on.\n\n You may also find that there are patch versions of the plugin such as 4.0-1 4.0-2 and\n so on. Use the latest patch release of the plugin.\n\n The current version of the plugin is shown at the top of this page after the <<Last Deployed>> date.\n \n\n* Default directories\n\n As with all Maven plugins, this plugin will automatically default to standard locations\n for your grammar and import files. Organizing your source code to reflect this standard\n layout will greatly reduce the configuration effort required. The standard layout lookd\n like this:\n\n+--\n src/main/\n      |\n      +--- antlr4/... .g4 files organized in the required package structure\n             |\n             +--- imports/  .g4 files that are imported by other grammars.\n+--\n\n If your grammar is intended to be part of a package called <<<org.foo.bar>>> then you would\n place it in the directory <<<src/main/antlr4/org/foo/bar>>>. The plugin will then produce\n <<<.java>>> and <<<.tokens>>> files in the output directory <<<target/generated-sources/antlr4/org/foo/bar>>>\n When the Java files are compiled they will be in the correct location for the Javac\n compiler without any special configuration. The generated java files are automatically\n submitted for compilation by the plugin.\n\n The <<<src/main/antlr4/imports>>> directory is treated in a special way. It should contain\n any grammar files that are imported by other grammar files (do not make subdirectories here.)\n Such files are never built on their own, but the plugin will automatically tell the ANTLR\n tool to look in this directory for library files.\n"
  },
  {
    "path": "antlr4-maven-plugin/src/site/apt/usage.apt.vm",
    "content": "Usage\n\n The ANTLR 4 plugin for Maven can generate parsers for any number of grammars in\n your project.\n\n* Compiling Grammars into Parsers\n\n By default, the <<<{{{./antlr4-mojo.html}antlr4}}>>> goal will search for grammar\n files in the directory <<<$\\{basedir\\}/src/main/antlr4>>> and any additional\n <<<.tokens>>> files in the directory <<<$\\{basedir\\}/src/main/antlr4/imports>>>.\n This can be configured to search other directories using the plugin configuration\n parameters as described in the <<<{{{./antlr4-mojo.html}antlr4}}>>> goal\n documentation.\n\n The following figure shows the expected layout of files for the default\n configuration of this plugin.\n\n+--\n src/main/\n      |\n      +--- antlr4/...       .g4 files organized in the required package structure\n             |\n             +--- imports/  user-created .tokens files and .g4 files that are imported by other grammars\n+--\n\n The next step is to configure your POM to call the plugin. The goals will\n normally run during the generate-sources phase of the build. Examples of how to\n configure your POM can be found on the various examples pages, reachable via\n the page menu. If you stick with the default values, the snippet below will\n suffice:\n\n+--\n<project>\n  ...\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.antlr</groupId>\n        <artifactId>antlr4-maven-plugin</artifactId>\n        <version>${project.version}</version>\n        <executions>\n          <execution>\n            <id>antlr</id>\n            <goals>\n              <goal>antlr4</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n    ...\n  </build>\n  ...\n</project>\n+--\n\n Note that you can create multiple executions, and thus build some grammars with\n different options to others (such as setting the <<<debug>>> option for\n instance).\n"
  },
  {
    "path": "antlr4-maven-plugin/src/site/site.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project name=\"ANTLR v4 Maven plugin\">\n\n  <publishDate position=\"left\"/>\n  <version position=\"left\"/>\n\n  <poweredBy>\n    <logo name=\"ANTLR Web Site\" href=\"http://antlr.org/\"\n          img=\"http://www.antlr.org/images/antlr-logo.png\"/>\n  </poweredBy>\n\n  <body>\n    <links>\n      <item name=\"Antlr Web Site\" href=\"http://www.antlr.org/\"/>\n    </links>\n\n    <menu name=\"Overview\">\n      <item name=\"Introduction\" href=\"index.html\"/>\n      <item name=\"Goals\" href=\"plugin-info.html\"/>\n      <item name=\"Usage\" href=\"usage.html\"/>\n      <item name=\"FAQ\" href=\"faq.html\"/>\n    </menu>\n\n    <menu name=\"Examples\">\n      <item name=\"Simple configurations\" href=\"examples/simple.html\"/>\n      <item name=\"Using library directories\" href=\"examples/libraries.html\"/>\n      <item name=\"Using imported grammars\" href=\"examples/import.html\"/>\n    </menu>\n\n    <menu ref=\"reports\" />\n    <menu ref=\"modules\" />\n\n  </body>\n</project>\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/java/org/antlr/mojo/antlr4/Antlr4MojoTest.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.mojo.antlr4;\n\nimport io.takari.maven.testing.TestMavenRuntime;\nimport io.takari.maven.testing.TestResources;\nimport org.apache.maven.execution.MavenSession;\nimport org.apache.maven.plugin.MojoExecution;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.project.MavenProject;\nimport org.codehaus.plexus.util.xml.Xpp3Dom;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\n\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.Arrays;\n\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\n\npublic class Antlr4MojoTest {\n    @Rule\n    public ExpectedException thrown = ExpectedException.none();\n\n    @Rule\n    public final TestResources resources = new TestResources();\n\n    @Rule\n    public final TestMavenRuntime maven = new TestMavenRuntime();\n\n    @Test\n    public void importTokens() throws Exception {\n        Path baseDir = resources.getBasedir(\"importTokens\").toPath();\n        Path antlrDir = baseDir.resolve(\"src/main/antlr4\");\n        Path generatedSources = baseDir.resolve(\"target/generated-sources/antlr4\");\n\n        Path genParser = generatedSources.resolve(\"test/SimpleParser.java\");\n        Path tokens = antlrDir.resolve(\"imports/SimpleLexer.tokens\");\n\n        MavenProject project = maven.readMavenProject(baseDir.toFile());\n        MavenSession session = maven.newMavenSession(project);\n        MojoExecution exec = maven.newMojoExecution(\"antlr4\");\n\n        ////////////////////////////////////////////////////////////////////////\n        // 1st - all grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        assertFalse(Files.exists(genParser));\n\n        maven.executeMojo(session, project, exec);\n\n        assertTrue(Files.exists(genParser));\n\n        ////////////////////////////////////////////////////////////////////////\n        // 2nd - nothing has been modified, no grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        {\n            byte[] sum = checksum(genParser);\n\n            maven.executeMojo(session, project, exec);\n\n            assertTrue(Arrays.equals(sum, checksum(genParser)));\n        }\n\n        ////////////////////////////////////////////////////////////////////////\n        // 3rd - the imported grammar changed, every dependency has to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        try(Change change = Change.of(tokens, \"DOT=4\")) {\n            byte[] sum = checksum(genParser);\n\n            maven.executeMojo(session, project, exec);\n\n            assertFalse(Arrays.equals(sum, checksum(genParser)));\n        }\n    }\n\n    @Test\n    public void importsCustomLayout() throws Exception {\n        Path baseDir = resources.getBasedir(\"importsCustom\").toPath();\n        Path antlrDir = baseDir.resolve(\"src/main/antlr4\");\n        Path generatedSources = baseDir.resolve(\"src/main/java\");\n\n        Path genTestLexer = generatedSources.resolve(\"foo/TestLexer.java\");\n        Path genTestParser = generatedSources.resolve(\"foo/TestParser.java\");\n        Path genHello = generatedSources.resolve(\"foo/HelloParser.java\");\n\n        Path baseGrammar = antlrDir.resolve(\"imports/TestBaseLexer.g4\");\n        Path lexerGrammar = antlrDir.resolve(\"TestLexer.g4\");\n        Path parserGrammar = antlrDir.resolve(\"TestParser.g4\");\n\n        Xpp3Dom outputDirectory = TestMavenRuntime.newParameter(\"outputDirectory\",\n                \"src/main/java/foo\");\n        Xpp3Dom arguments = new Xpp3Dom(\"arguments\");\n        arguments.addChild(TestMavenRuntime.newParameter(\"argument\", \"-package\"));\n        arguments.addChild(TestMavenRuntime.newParameter(\"argument\", \"foo\"));\n\n        MavenProject project = maven.readMavenProject(baseDir.toFile());\n        MavenSession session = maven.newMavenSession(project);\n        MojoExecution exec = maven.newMojoExecution(\"antlr4\", outputDirectory, arguments);\n\n        ////////////////////////////////////////////////////////////////////////\n        // 1st - all grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        assertFalse(Files.exists(genHello));\n        assertFalse(Files.exists(genTestParser));\n        assertFalse(Files.exists(genTestLexer));\n\n        maven.executeMojo(session, project, exec);\n\n        assertTrue(Files.exists(genHello));\n        assertTrue(Files.exists(genTestParser));\n        assertTrue(Files.exists(genTestLexer));\n\n        ////////////////////////////////////////////////////////////////////////\n        // 2nd - nothing has been modified, no grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        {\n            byte[] testLexerSum = checksum(genTestLexer);\n            byte[] testParserSum = checksum(genTestParser);\n            byte[] helloSum = checksum(genHello);\n\n            maven.executeMojo(session, project, exec);\n\n            assertTrue(Arrays.equals(testLexerSum, checksum(genTestLexer)));\n            assertTrue(Arrays.equals(testParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(helloSum, checksum(genHello)));\n        }\n\n        ////////////////////////////////////////////////////////////////////////\n        // 3rd - the imported grammar changed, every dependency has to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        // modify the grammar to make checksum comparison detect a change\n        try(Change change = Change.of(baseGrammar, \"DOT: '.' ;\")) {\n            byte[] testLexerSum = checksum(genTestLexer);\n            byte[] testParserSum = checksum(genTestParser);\n            byte[] helloSum = checksum(genHello);\n\n            maven.executeMojo(session, project, exec);\n\n            assertFalse(Arrays.equals(testLexerSum, checksum(genTestLexer)));\n            assertFalse(Arrays.equals(testParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(helloSum, checksum(genHello)));\n        }\n\n        ////////////////////////////////////////////////////////////////////////\n        // 4th - the lexer grammar changed, the parser grammar has to be processed as well\n        ////////////////////////////////////////////////////////////////////////\n\n        // modify the grammar to make checksum comparison detect a change\n        try(Change change = Change.of(lexerGrammar, \"fragment DOT : '.';\")) {\n            byte[] testLexerSum = checksum(genTestLexer);\n            byte[] testParserSum = checksum(genTestParser);\n            byte[] helloSum = checksum(genHello);\n\n            maven.executeMojo(session, project, exec);\n\n            assertFalse(Arrays.equals(testLexerSum, checksum(genTestLexer)));\n            assertFalse(Arrays.equals(testParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(helloSum, checksum(genHello)));\n        }\n\n        ////////////////////////////////////////////////////////////////////////\n        // 5th - the parser grammar changed, no other grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        // modify the grammar to make checksum comparison detect a change\n        try(Change change = Change.of(parserGrammar, \" t : WS* ;\")) {\n            byte[] testLexerSum = checksum(genTestLexer);\n            byte[] testParserSum = checksum(genTestParser);\n            byte[] helloSum = checksum(genHello);\n\n            maven.executeMojo(session, project, exec);\n\n            assertTrue(Arrays.equals(testLexerSum, checksum(genTestLexer)));\n            assertFalse(Arrays.equals(testParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(helloSum, checksum(genHello)));\n        }\n    }\n\n    @Test\n    public void importsStandardLayout() throws Exception {\n        Path baseDir = resources.getBasedir(\"importsStandard\").toPath();\n        Path antlrDir = baseDir.resolve(\"src/main/antlr4\");\n        Path generatedSources = baseDir.resolve(\"target/generated-sources/antlr4\");\n\n        Path genTestLexer = generatedSources.resolve(\"test/TestLexer.java\");\n        Path genTestParser = generatedSources.resolve(\"test/TestParser.java\");\n        Path genHello = generatedSources.resolve(\"test/HelloParser.java\");\n\n        Path baseGrammar = antlrDir.resolve(\"imports/TestBaseLexer.g4\");\n        Path baseGrammar2 = antlrDir.resolve(\"imports/TestBaseLexer2.g4\");\n        Path lexerGrammar = antlrDir.resolve(\"test/TestLexer.g4\");\n        Path parserGrammar = antlrDir.resolve(\"test/TestParser.g4\");\n\n        MavenProject project = maven.readMavenProject(baseDir.toFile());\n        MavenSession session = maven.newMavenSession(project);\n        MojoExecution exec = maven.newMojoExecution(\"antlr4\");\n\n        ////////////////////////////////////////////////////////////////////////\n        // 1st - all grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        assertFalse(Files.exists(genHello));\n        assertFalse(Files.exists(genTestParser));\n        assertFalse(Files.exists(genTestLexer));\n\n        maven.executeMojo(session, project, exec);\n\n        assertTrue(Files.exists(genHello));\n        assertTrue(Files.exists(genTestParser));\n        assertTrue(Files.exists(genTestLexer));\n        byte[] origTestLexerSum = checksum(genTestLexer);\n        byte[] origTestParserSum = checksum(genTestParser);\n        byte[] origHelloSum = checksum(genHello);\n\n        ////////////////////////////////////////////////////////////////////////\n        // 2nd - nothing has been modified, no grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        {\n            maven.executeMojo(session, project, exec);\n\n            assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n            assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n        }\n\n        ////////////////////////////////////////////////////////////////////////\n        // 3rd - the imported grammar changed, every dependency has to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        // modify the grammar to make checksum comparison detect a change\n        try(Change change = Change.of(baseGrammar, \"DOT: '.' ;\")) {\n            maven.executeMojo(session, project, exec);\n\n            assertFalse(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n        }\n        // Restore file and confirm it was restored.\n        maven.executeMojo(session, project, exec);\n        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n\n        ////////////////////////////////////////////////////////////////////////\n        // 4th - the second imported grammar changed, every dependency has to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        // modify the grammar to make checksum comparison detect a change\n        try(Change change = Change.of(baseGrammar2, \"BANG: '!' ;\")) {\n            maven.executeMojo(session, project, exec);\n\n            assertFalse(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n        }\n        // Restore file and confirm it was restored.\n        maven.executeMojo(session, project, exec);\n        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n\n        ////////////////////////////////////////////////////////////////////////\n        // 5th - the lexer grammar changed, the parser grammar has to be processed as well\n        ////////////////////////////////////////////////////////////////////////\n\n        // modify the grammar to make checksum comparison detect a change\n        try(Change change = Change.of(lexerGrammar, \"FOO: 'foo' ;\")) {\n            maven.executeMojo(session, project, exec);\n\n            assertFalse(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n        }\n        // Restore file and confirm it was restored.\n        maven.executeMojo(session, project, exec);\n        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n\n        ////////////////////////////////////////////////////////////////////////\n        // 6th - the parser grammar changed, no other grammars have to be processed\n        ////////////////////////////////////////////////////////////////////////\n\n        // modify the grammar to make checksum comparison detect a change\n        try(Change change = Change.of(parserGrammar, \" t : WS* ;\")) {\n            maven.executeMojo(session, project, exec);\n\n            assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n            assertFalse(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n            assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n        }\n        // Restore file and confirm it was restored.\n        maven.executeMojo(session, project, exec);\n        assertTrue(Arrays.equals(origTestLexerSum, checksum(genTestLexer)));\n        assertTrue(Arrays.equals(origTestParserSum, checksum(genTestParser)));\n        assertTrue(Arrays.equals(origHelloSum, checksum(genHello)));\n    }\n\n    @Test\n    public void processWhenDependencyRemoved() throws Exception {\n        Path baseDir = resources.getBasedir(\"dependencyRemoved\").toPath();\n        Path antlrDir = baseDir.resolve(\"src/main/antlr4\");\n\n        Path baseGrammar = antlrDir.resolve(\"imports/HelloBase.g4\");\n\n        MavenProject project = maven.readMavenProject(baseDir.toFile());\n        MavenSession session = maven.newMavenSession(project);\n        MojoExecution exec = maven.newMojoExecution(\"antlr4\");\n\n        maven.executeMojo(session, project, exec);\n\n        try(Change temp = Change.of(baseGrammar)) {\n            // if the base grammar no longer exists, processing must be performed\n            Files.delete(baseGrammar);\n\n            thrown.expect(MojoExecutionException.class);\n            thrown.expectMessage(\"ANTLR 4 caught 1 build errors.\");\n\n            maven.executeMojo(session, project, exec);\n        }\n    }\n\n    private byte[] checksum(Path path) throws IOException {\n        return MojoUtils.checksum(path.toFile());\n    }\n\n    private static class Change implements AutoCloseable {\n        final Path file;\n        final byte[] original;\n\n        public Change(Path file, String change) {\n            this.file = file;\n\n            try {\n                original = Files.readAllBytes(file);\n            } catch (IOException ex) {\n                throw new RuntimeException(\"Could not read file \" + file);\n            }\n\n            String text = new String(original, StandardCharsets.UTF_8) + change;\n\n            write(file, text.getBytes(StandardCharsets.UTF_8));\n        }\n\n        private void write(Path file, byte[] data) {\n            try {\n                Files.write(file, data);\n            } catch (IOException ex) {\n                throw new RuntimeException(\"Could not write file \" + file);\n            }\n        }\n\n        public static Change of(Path file, String change) {\n            return new Change(file, change);\n        }\n\n        public static Change of(Path file) {\n            return new Change(file, \"\\n\");\n        }\n\n        @Override\n        public void close() {\n            write(file, original);\n        }\n    }\n}\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/dependencyRemoved/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>deps.removed</groupId>\n  <artifactId>depRemoved</artifactId>\n  <version>1.0-SNAPSHOT</version>\n  <packaging>jar</packaging>\n  <name>Test processing after dependency removed</name>\n  <dependencies>\n    <dependency>\n      <groupId>junit</groupId>\n      <artifactId>junit</artifactId>\n      <version>4.13.1</version>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n  <build>\n    <plugins>\n      <plugin>\n          <artifactId>antlr4-maven-plugin</artifactId>\n        <configuration>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/dependencyRemoved/src/main/antlr4/imports/HelloBase.g4",
    "content": "lexer grammar TestBaseLexer;\n\ntokens  { Name }\n\n// Default \"mode\": Everything OUTSIDE of a tag\nComment     :  '<!--' .*? '-->' ;\nCDSect      :  '<![CDATA[' .*? ']]>' ;\n\nfragment\nWhitespace  :  ' ' | '\\n' | '\\t' | '\\r' ;\n\nfragment\nHexdigit    :  [a-fA-F0-9] ;\n\nfragment\nDigit       :  [0-9] ;\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/dependencyRemoved/src/main/antlr4/test/Hello.g4",
    "content": "grammar Hello;\n\nimport HelloBase;\n\nr  : 'hello' ID ;\nID : [a-z]+ ;\nWS : [ \\r\\t\\n]+ -> skip ;\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importTokens/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>import.tokens</groupId>\n  <artifactId>importTokens</artifactId>\n  <version>1.0-SNAPSHOT</version>\n  <packaging>jar</packaging>\n  <name>Test importing tokens file</name>\n  <dependencies>\n    <dependency>\n      <groupId>junit</groupId>\n      <artifactId>junit</artifactId>\n      <version>4.13.1</version>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n  <build>\n    <plugins>\n      <plugin>\n          <artifactId>antlr4-maven-plugin</artifactId>\n        <configuration>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importTokens/src/main/antlr4/imports/SimpleLexer.tokens",
    "content": "ID=1\nINT=2\nSEMI=3\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importTokens/src/main/antlr4/test/SimpleParser.g4",
    "content": "parser grammar SimpleParser;\noptions {\n  // get token types from SimpleLexer.tokens; don't name it\n  // SimpleParser.tokens as ANTLR will overwrite!\n  tokenVocab=SimpleLexer; \n}\n\ns : ( ID | INT )* SEMI ;\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsCustom/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>imports.custom</groupId>\n  <artifactId>importsCustom</artifactId>\n  <version>1.0-SNAPSHOT</version>\n  <packaging>jar</packaging>\n  <name>Test importing, custom layout</name>\n  <dependencies>\n    <dependency>\n      <groupId>junit</groupId>\n      <artifactId>junit</artifactId>\n      <version>4.13.1</version>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n  <build>\n    <plugins>\n      <plugin>\n        <artifactId>antlr4-maven-plugin</artifactId>\n        <configuration>\n          <outputDirectory>${basedir}/src/main/java/com/foo</outputDirectory>\n\t\t\t\t\t<arguments>\n\t\t\t\t\t\t<argument>-visitor</argument>\n\t\t\t\t\t\t<argument>-no-listener</argument>\n\t\t\t\t\t\t<argument>-Xlog</argument>\n\t\t\t\t\t\t<argument>-package</argument>\n\t\t\t\t\t\t<argument>com.foo</argument>\n\t\t\t\t\t</arguments>\n        </configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>antlr4</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsCustom/src/main/antlr4/Hello.g4",
    "content": "grammar Hello;\nr  : 'hello' ID ;\nID : [a-z]+ ;\nWS : [ \\r\\t\\n]+ -> skip ;"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsCustom/src/main/antlr4/TestLexer.g4",
    "content": "lexer grammar TestLexer;\n\nimport TestBaseLexer;\n\nWS    :  Whitespace+              -> skip;\nTEXT  :  ~[<&]+ ; // match any 16 bit char other than < and &"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsCustom/src/main/antlr4/TestParser.g4",
    "content": "parser grammar TestParser;\n\noptions { tokenVocab=TestLexer; }\n\ndocument  :  (Comment | Name) EOF ;"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsCustom/src/main/antlr4/imports/TestBaseLexer.g4",
    "content": "lexer grammar TestBaseLexer;\n\ntokens  { Name }\n\n// Default \"mode\": Everything OUTSIDE of a tag\nComment     :  '<!--' .*? '-->' ;\nCDSect      :  '<![CDATA[' .*? ']]>' ;\n\nfragment\nWhitespace  :  ' ' | '\\n' | '\\t' | '\\r' ;\n\nfragment\nHexdigit    :  [a-fA-F0-9] ;\n\nfragment\nDigit       :  [0-9] ;\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsStandard/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>imports.standard</groupId>\n  <artifactId>importsStandard</artifactId>\n  <version>1.0-SNAPSHOT</version>\n  <packaging>jar</packaging>\n  <name>Test importing, standard layout</name>\n  <dependencies>\n    <dependency>\n      <groupId>junit</groupId>\n      <artifactId>junit</artifactId>\n      <version>4.13.1</version>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n  <build>\n    <plugins>\n      <plugin>\n          <artifactId>antlr4-maven-plugin</artifactId>\n        <configuration>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsStandard/src/main/antlr4/imports/TestBaseLexer.g4",
    "content": "lexer grammar TestBaseLexer;\n\ntokens  { Name }\n\n// Default \"mode\": Everything OUTSIDE of a tag\nComment     :  '<!--' .*? '-->' ;\nCDSect      :  '<![CDATA[' .*? ']]>' ;\n\nfragment\nWhitespace  :  ' ' | '\\n' | '\\t' | '\\r' ;\n\nfragment\nHexdigit    :  [a-fA-F0-9] ;"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsStandard/src/main/antlr4/imports/TestBaseLexer2.g4",
    "content": "lexer grammar TestBaseLexer2;\n\nfragment\nDigit       :  [0-9] ;\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsStandard/src/main/antlr4/test/Hello.g4",
    "content": "grammar Hello;\nr  : 'hello' ID ;\nID : [a-z]+ ;\nWS : [ \\r\\t\\n]+ -> skip ;"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsStandard/src/main/antlr4/test/TestLexer.g4",
    "content": "lexer grammar TestLexer;\n\nimport TestBaseLexer, TestBaseLexer2;\n\nWS    :  Whitespace+              -> skip;\nTEXT  :  ~[<&]+ ; // match any 16 bit char other than < and &\n"
  },
  {
    "path": "antlr4-maven-plugin/src/test/projects/importsStandard/src/main/antlr4/test/TestParser.g4",
    "content": "parser grammar TestParser;\n\noptions { tokenVocab=TestLexer; }\n\ndocument  :  (Comment | Name) EOF ;"
  },
  {
    "path": "developer-cert-of-origin.txt",
    "content": "As of 4.10, ANTLR uses the Linux Foundation's Developer\nCertificate of Origin, DCO, version 1.1. See either\nhttps://developercertificate.org/ or the text below.\n\nEach commit requires a \"signature\", which is simple as\nusing `-s` (not `-S`) to the git commit command: \n\ngit commit -s -m 'This is my commit message'\n\nGithub's pull request process enforces the sig and gives\ninstructions on how to fix any commits that lack the sig.\nSee https://github.com/apps/dco for more info.\n\nNo signature is required in this file (unlike the\nprevious ANTLR contributor's certificate of origin.)\n\n----- https://developercertificate.org/ ------\n\nDeveloper Certificate of Origin\nVersion 1.1\n\nCopyright (C) 2004, 2006 The Linux Foundation and its contributors.\n\nEveryone is permitted to copy and distribute verbatim copies of this\nlicense document, but changing it is not allowed.\n\n\nDeveloper's Certificate of Origin 1.1\n\nBy making a contribution to this project, I certify that:\n\n(a) The contribution was created in whole or in part by me and I\n    have the right to submit it under the open source license\n    indicated in the file; or\n\n(b) The contribution is based upon previous work that, to the best\n    of my knowledge, is covered under an appropriate open source\n    license and I have the right under that license to submit that\n    work with modifications, whether created in whole or in part\n    by me, under the same open source license (unless I am\n    permitted to submit under a different license), as indicated\n    in the file; or\n\n(c) The contribution was provided directly to me by some other\n    person who certified (a), (b) or (c) and I have not modified\n    it.\n\n(d) I understand and agree that this project and the contribution\n    are public and that a record of the contribution (including all\n    personal information I submit with it, including my sign-off) is\n    maintained indefinitely and may be redistributed consistent with\n    this project or the open source license(s) involved.\n"
  },
  {
    "path": "doc/IDEs.md",
    "content": "# Integrating ANTLR into Development Systems\n\nThe Java target is the reference implementation mirrored by other targets. The following pages help you integrate ANTLR into development environments and build systems appropriate for your target language.  As of December 2016, we have Java, C#, Python 3, JavaScript, Go, C++, and Swift targets.\n\nThe easiest thing is probably just to use an [ANTLR plug-in](http://www.antlr.org/tools.html) for your favorite development environment.\n"
  },
  {
    "path": "doc/ace-javascript-target.md",
    "content": "# Integrating ANTLR JavaScript parsers with ACE editor\n\nHaving the ability to parse code other than JavaScript is great, but nowadays users expect to be able to edit code with nice edit features such as keyword highlighting, indentation and brace matching, and advanced ones such as syntax checking.\n\nI have been through the process of integrating an ANTLR parser with ACE, the dominant code editor for web based code editing. Information about ACE can be found on their web site. \n\nThis page describes my experience, and humbly aims to help you get started. It is not however a reference guide, and no support is provided.\n\n## Architecture\n\nThe ACE editor is organized as follows\n\n1. The editor itself is a <div> which once initialized comprises a number of elements. This UI element is responsible for the display, and the generation of edit events.\n1. The editor relies on a Session, which manages events and configuration.\n1. The code itself is stored in a Document. Any insertion or deletion of text is reflected in the Document.\n1. Keyword highlighting, indentation and brace matching are delegated to a mode. There is no direct equivalent of an ACE mode in ANTLR. While keywords are the equivalent of ANTLR lexer tokens, indentation and brace matching are edit tasks, not parsing ones. A given ACE editor can only have one mode, which corresponds to the language being edited. There is no need for ANTLR integration to support keyword highlighting, indentation and brace matching.\n1. Syntax checking is delegated to a worker. This is where ANTLR integration is needed. If syntax checking is enabled, ACE asks the mode to create a worker. In JavaScript, workers run in complete isolation i.e. they don't share code or variables with other workers, or with the HTML page itself.\n1. The below diagram describes how the whole system works. In green are the components *you* need to provide. You'll notice that there is no need to load ANTLR in the HTML page itself. You'll also notice that ACE maintains a document in each thread. This is done through low level events sent by the ACE session to the worker which describe the delta. Once applied to the worker document, a high level event is triggered, which is easy to handle since at this point the worker document is a perfect copy of the UI document.  \n\n<img src=images/ACE-Architecture.001.png>\n\n## Step-by-step guide\n\nThe first thing to do is to create an editor in your html page. This is thoroughly described in the ACE documentation, so we'll just sum it up here:\n\n```xml\n<script src=\"../js/ace/ace.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n<script>\n    var editor = ace.edit(\"editor\");\n</script>\n```\n\nThis should give you a working editor. You may want to control its sizing using CSS. I personally load the editor in an iframe and set its style to position: absolute, top: 0, left: 0 etc... but I'm sure you know better than me how to achieve results. \n\nThe second thing to do is to configure the ACE editor to use your mode i.e. language configuration. A good place to start is to inherit from the built-in TextMode. The following is a very simple example, which only caters for comments, literals, and a limited subset of separators and keywords :\n\n```javascript\nace.define('ace/mode/my-mode',[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/mode/text\",\"ace/mode/text_highlight_rules\", \"ace/worker/worker_client\" ], function(require, exports, module) {\n    var oop = require(\"ace/lib/oop\");\n    var TextMode = require(\"ace/mode/text\").Mode;\n    var TextHighlightRules = require(\"ace/mode/text_highlight_rules\").TextHighlightRules;\n\n    var MyHighlightRules = function() {\n        var keywordMapper = this.createKeywordMapper({\n            \"keyword.control\": \"if|then|else\",\n            \"keyword.operator\": \"and|or|not\",\n            \"keyword.other\": \"class\",\n            \"storage.type\": \"int|float|text\",\n            \"storage.modifier\": \"private|public\",\n            \"support.function\": \"print|sort\",\n            \"constant.language\": \"true|false\"\n  }, \"identifier\");\n        this.$rules = {\n            \"start\": [\n                { token : \"comment\", regex : \"//\" },\n                { token : \"string\",  regex : '[\"](?:(?:\\\\\\\\.)|(?:[^\"\\\\\\\\]))*?[\"]' },\n                { token : \"constant.numeric\", regex : \"0[xX][0-9a-fA-F]+\\\\b\" },\n                { token : \"constant.numeric\", regex: \"[+-]?\\\\d+(?:(?:\\\\.\\\\d*)?(?:[eE][+-]?\\\\d+)?)?\\\\b\" },\n                { token : \"keyword.operator\", regex : \"!|%|\\\\\\\\|/|\\\\*|\\\\-|\\\\+|~=|==|<>|!=|<=|>=|=|<|>|&&|\\\\|\\\\|\" },\n                { token : \"punctuation.operator\", regex : \"\\\\?|\\\\:|\\\\,|\\\\;|\\\\.\" },\n                { token : \"paren.lparen\", regex : \"[[({]\" },\n                { token : \"paren.rparen\", regex : \"[\\\\])}]\" },\n                { token : \"text\", regex : \"\\\\s+\" },\n                { token: keywordMapper, regex: \"[a-zA-Z_$][a-zA-Z0-9_$]*\\\\b\" }\n            ]\n        };\n    };\n    oop.inherits(MyHighlightRules, TextHighlightRules);\n\n    var MyMode = function() {\n        this.HighlightRules = MyHighlightRules;\n    };\n    oop.inherits(MyMode, TextMode);\n\n    (function() {\n\n        this.$id = \"ace/mode/my-mode\";\n\n    }).call(MyMode.prototype);\n\n    exports.Mode = MyMode;\n});\n```\n\nNow if you store the above in a file called \"my-mode.js\", setting the ACE Editor becomes straightforward:\n\n```xml\n<script src=\"../js/ace/ace.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n<script src=\"../js/my-mode.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n<script>\n    var editor = ace.edit(\"editor\");\n    editor.getSession().setMode(\"ace/mode/my-mode\");\n</script>\n```\n\nAt this point you should have a working editor, able to highlight keywords. You may wonder why you need to set the tokens when you have already done so in your ANTLR lexer grammar. First, ACE expects a classification (control, operator, type...) which does not exist in ANTLR. Second, there is no need for ANTLR to achieve this, since ACE comes with its own lexer.\n\nOk, now that we have a working editor comes the time where we need syntax validation. This is where the worker comes in the picture.\n\nCreating the worker is the responsibility of the mode you provide. So you need to enhance it with something like the following:\n \n```javascript\nvar WorkerClient = require(\"ace/worker/worker_client\").WorkerClient;\nthis.createWorker = function(session) {\n    this.$worker = new WorkerClient([\"ace\"], \"ace/worker/my-worker\", \"MyWorker\", \"../js/my-worker.js\");\n    this.$worker.attachToDocument(session.getDocument());\n\n    this.$worker.on(\"errors\", function(e) {\n        session.setAnnotations(e.data);\n    });\n\n    this.$worker.on(\"annotate\", function(e) {\n        session.setAnnotations(e.data);\n    });\n\n    this.$worker.on(\"terminate\", function() {\n        session.clearAnnotations();\n    });\n\n    return this.$worker;\n\n};\n```\n\nThe above code needs to be placed in the existing worker, after: \n\n```javascript\nthis.$id = \"ace/mode/my-mode\";\n```\n\nPlease note that the mode code runs on the UI side, not the worker side. The event handlers here are for events sent by the worker, not to the worker.\n\nObviously the above won't work out of the box, because you need to provide the \"my-worker.js\" file.\n\nCreating a worker from scratch is not something I've tried. Simply put, your worker needs to handle all messages sent by ACE using the WorkerClient created by the mode. This is not a simple task, and is better delegated to existing ACE code, so we can focus on tasks specific to our language.\n\nWhat I did is I started from \"mode-json.js\", a rather simple worker which comes with ACE, stripped out all JSON validation related stuff out of it, and saved the remaining code in a file name \"worker-base.js\" which you can find [here](resources/worker-base.js). Once this done, I was able to create a simple worker, as follows:\n\n```javascript\nimportScripts(\"worker-base.js\");\nace.define('ace/worker/my-worker',[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\"], function(require, exports, module) {\n    \"use strict\";\n\n    var oop = require(\"ace/lib/oop\");\n    var Mirror = require(\"ace/worker/mirror\").Mirror;\n\n    var MyWorker = function(sender) {\n        Mirror.call(this, sender);\n        this.setTimeout(200);\n        this.$dialect = null;\n    };\n\n    oop.inherits(MyWorker, Mirror);\n\n    (function() {\n\n        this.onUpdate = function() {\n            var value = this.doc.getValue();\n            var annotations = validate(value);\n            this.sender.emit(\"annotate\", annotations);\n        };\n\n    }).call(MyWorker.prototype);\n\n    exports.MyWorker = MyWorker;\n});\n\nvar validate = function(input) {\n    return [ { row: 0, column: 0, text: \"MyMode says Hello!\", type: \"error\" } ];\n};\n```\n\nAt this point, you should have an editor which displays an error icon next to the first line. When you hover over the error icon, it should display: MyMode says Hello!. Is that not a friendly worker? Yum.\n\nWhat remains to be done is have our validate function actually validate the input. Finally ANTLR comes in the picture!\n\nTo start with, let's load ANTLR and your parser, listener etc.. \n\nThe preferred approach for loading parser code is to bundle your parser, [as described here](javascript-target.md).\nYou can then load it as part of the importScripts instruction at the start of your worker code.\n\nAnother approach is to load it using 'require'. Easy, since you could write:\n\n```js\nvar antlr4 = require('antlr4/index');\n```\n\nThis may work, but it's actually unreliable. The reason is that the 'require' function that comes with ACE uses a different syntax than the 'require' function used by ANTLR, which follows the NodeJS 'require' convention. \nSo we need to bring in a NodeJS compatible 'require' function that conforms to the NodeJS syntax. I personally use one that comes from Torben Haase's Honey project, which you can find in li/require.js. \nBut hey, now we're going to have 2 'require' functions not compatible with each other! Indeed, this is why you need to take special care, as follows:\n\n```js\n// load nodejs compatible require\nvar ace_require = require;\nrequire = undefined;\nvar Honey = { 'requirePath': ['..'] }; // walk up to js folder, see Honey docs\nimportScripts(\"../lib/require.js\");\nvar antlr4_require = require;\nrequire = ace_require;\n```\nNow it's safe to load antlr and the parsers generated for your language. \nAssuming that your language files (generated or hand-built) are in a folder with an index.js file that calls require for each file, your parser loading code can be as simple as follows:\n```js\n// load antlr4 and myLanguage\nvar antlr4, mylanguage;\ntry {\n    require = antlr4_require;\n    antlr4 = require('antlr4/index');\n    mylanguage = require('mylanguage/index');\n} finally {\n    require = ace_require;\n}\n```\nPlease note the try-finally construct. ANTLR uses 'require' synchronously so it's perfectly safe to ignore the ACE 'require' while running ANTLR code. ACE itself does not guarantee synchronous execution, so you are much safer always switching 'require' back to 'ace_require'.\n\nNow detecting deep syntax errors in your code is a task for your ANTLR listener or visitor or whatever piece of code you've delegated this to. We're not going to describe this here, since it would require some knowledge of your language. However, detecting grammar syntax errors is something ANTLR does beautifully (isn't that why you went for ANTLR in the first place?). So what we will illustrate here is how to report grammar syntax errors. I have no doubt that from there, you will be able to extend the validator to suit your specific needs.\nWhenever ANTLR encounters an unexpected token, it fires an error. By default, the error is routed to an error listener which simply writes to the console.\nWhat we need to do is replace this listener by our own listener, se we can route errors to the ACE editor. First, let's create such a listener:\n```js\n// class for gathering errors and posting them to ACE editor\nvar AnnotatingErrorListener = function(annotations) {\n    antlr4.error.ErrorListener.call(this);\n    this.annotations = annotations;\n    return this;\n};\n\nAnnotatingErrorListener.prototype = Object.create(antlr4.error.ErrorListener.prototype);\nAnnotatingErrorListener.prototype.constructor = AnnotatingErrorListener;\n\nAnnotatingErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {\n    this.annotations.push({\n        row: line - 1,\n        column: column,\n        text: msg,\n        type: \"error\"\n });\n};\n```\nWith this, all that remains to be done is plug the listener in when we parse the code. Here is how I do it:\n```js\nvar validate = function(input) {\n    var stream = CharStreams.fromString(input);\n    var lexer = new mylanguage.MyLexer(stream);\n    var tokens = new antlr4.CommonTokenStream(lexer);\n    var parser = new mylanguage.MyParser(tokens);\n    var annotations = [];\n    var listener = new AnnotatingErrorListener(annotations)\n    parser.removeErrorListeners();\n    parser.addErrorListener(listener);\n    parser.parseMyRule();\n    return annotations;\n};\n```\nYou know what? That's it! You now have an ACE editor that does syntax validation using ANTLR! I hope you find this useful, and simple enough to get started.\nNow wait, hey! How do you debug this? Well, as usual, using Chrome, since no other browser is able to debug worker code. What a shame...\n"
  },
  {
    "path": "doc/actions.md",
    "content": "# Actions and Attributes\n\nIn Chapter 10, Attributes and Actions, we learned how to embed actions within grammars and looked at the most common token and rule attributes. This section summarizes the important syntax and semantics from that chapter and provides a complete list of all available attributes. (You can learn more about actions in the grammar from the free excerpt on listeners and actions.)\n\nActions are blocks of text written in the target language and enclosed in curly braces. The recognizer triggers them according to their locations within the grammar. For example, the following rule emits \"found a decl\" after the parser has seen a valid declaration:\n\n```\ndecl: type ID ';' {System.out.println(\"found a decl\");} ;\ntype: 'int' | 'float' ;\n```\n\nMost often, actions access the attributes of tokens and rule references:\n\n```\ndecl: type ID ';'\n      {System.out.println(\"var \"+$ID.text+\":\"+$type.text+\";\");}\n    | t=ID id=ID ';'\n      {System.out.println(\"var \"+$id.text+\":\"+$t.text+\";\");}\n    ;\n```\n\n## Token Attributes\n\nAll tokens have a collection of predefined, read-only attributes. The attributes include useful token properties such as the token type and text matched for a token. Actions can access these attributes via `$label.attribute` where label labels a particular instance of a token reference (`a` and `b` in the example below are used in the action code as `$a` and `$b`). Often, a particular token is only referenced once in the rule, in which case the token name itself can be used unambiguously in the action code (token `INT` can be used as `$INT` in the action). The following example illustrates token attribute expression syntax:\n\n```\nr : INT {int x = $INT.line;}\n    ( ID {if ($INT.line == $ID.line) ...;} )?\n    a=FLOAT b=FLOAT {if ($a.line == $b.line) ...;}\n  ;\n```\n\nThe action within the `(...)?` subrule can see the `INT` token matched before it in the outer level.\n\nBecause there are two references to the `FLOAT` token, a reference to `$FLOAT` in an action is not unique; you must use labels to specify which token reference you’re interested in.\n\nToken references within different alternatives are unique because only one of them can be matched for any invocation of the rule. For example, in the following rule, actions in both alternatives can reference `$ID` directly without using a label:\n\n```\n \tr : ... ID {System.out.println($ID.text);}\n \t| ... ID {System.out.println($ID.text);}\n \t;\n```\n\nTo access the tokens matched for literals, you must use a label:\n\n```\n \tstat: r='return' expr ';' {System.out.println(\"line=\"+$r.line);} ;\n```\n\nMost of the time you access the attributes of the token, but sometimes it is useful to access the Token object itself because it aggregates all the attributes. Further, you can use it to test whether an optional subrule matched a token:\n\n```\n \tstat: 'if' expr 'then' stat (el='else' stat)?\n \t{if ( $el!=null ) System.out.println(\"found an else\");}\n \t| ...\n \t;\n```\n\n`$T` and `$L` evaluate to `Token` objects for token name `T` and token label `L`. `$ll` evaluates to `List<Token>` for list label `ll`. `$T.attr` evaluates to the type and value specified in the following table for attribute `attr`:\n\n\n|Attribute|Type|Description|\n|---------|----|-----------|\n|text|String|The text matched for the token; translates to a call to getText. Example: $ID.text.|\n|type|int|The token type (nonzero positive integer) of the token such as INT; translates to a call to getType. Example: $ID.type.|\n|line|int|The line number on which the token occurs, counting from 1; translates to a call to getLine. Example: $ID.line.|\n|pos|int|The character position within the line at which the token’s first character occurs counting from zero; translates to a call to getCharPositionInLine. Example: $ID.pos.|\n|index|int|The overall index of this token in the token stream, counting from zero; translates to a call to getTokenIndex. Example: $ID.index.|\n|channel|int|The token’s channel number. The parser tunes to only one channel, effectively ignoring off-channel tokens. The default channel is 0 (Token.DEFAULT_CHANNEL), and the default hidden channel is Token.HIDDEN_CHANNEL. Translates to a call to getChannel. Example: $ID.channel.|\n|int|int|The integer value of the text held by this token; it assumes that the text is a valid numeric string. Handy for building calculators and so on. Translates to Integer.valueOf(text-of-token). Example: $INT.int.|\n\n## Parser Rule Attributes\n\nANTLR predefines a number of read-only attributes associated with parser rule references that are available to actions. Actions can access rule attributes only for references that precede the action. The syntax is `$r.attr` for rule name `r` or a label assigned to a rule reference. For example, `$expr.text` returns the complete text matched by a preceding invocation of rule `expr`:\n\n```\nreturnStat : 'return' expr {System.out.println(\"matched \"+$expr.text);} ;\n```\n\nUsing a rule label looks like this:\n\n```\nreturnStat : 'return' e=expr {System.out.println(\"matched \"+$e.text);} ;\n```\n\nYou can also use `$` followed by the name of the attribute to access the value associated with the currently executing rule. For example, `$start` is the starting token of the current rule.\n\n```\nreturnStat : 'return' expr {System.out.println(\"first token \"+$start.getText());} ;\n```\n\n`$r` and `$rl` evaluate to `ParserRuleContext` objects of type `RContext` for rule name `r` and rule label `rl`. `$rll` evaluates to `List<RContext>` for rule list label `rll`. `$r.attr` evaluates to the type and value specified in the following table for attribute `attr`:\n\n|Attribute|Type|Description|\n|---------|----|-----------|\n|text|String|The text matched for a rule or the text matched from the start of the rule up until the point of the `$text` expression evaluation. Note that this includes the text for all tokens including those on hidden channels, which is what you want because usually that has all the whitespace and comments. When referring to the current rule, this attribute is available in any action including any exception actions.|\n|start|Token|The first token to be potentially matched by the rule that is on the main token channel; in other words, this attribute is never a hidden token. For rules that end up matching no tokens, this attribute points at the first token that could have been matched by this rule. When referring to the current rule, this attribute is available to any action within the rule.|\n|stop|Token|The last nonhidden channel token to be matched by the rule. When referring to the current rule, this attribute is available only to the after and finally actions.|\n|ctx|ParserRuleContext|The rule context object associated with a rule invocation. All of the other attributes are available through this attribute. For example, `$ctx.start` accesses the start field within the current rules context object. It’s the same as `$start`.|\n|parser|Parser|The parser itself.  This attribute can be used, for example, to invoke a method defined in the parser's `@members` section from a semantic predicate.|\n\n## Dynamically-Scoped Attributes\n\nYou can pass information to and from rules using parameters and return values, just like functions in a general-purpose programming language. Programming languages don’t allow functions to access the local variables or parameters of invoking functions, however. For example, the following reference to local variable `x` form a nested method call is illegal in Java:\n\n```java\nvoid f() {\n\tint x = 0;\n\tg();\n}\nvoid g() {\n\th();\n}\nvoid h() {\n\tint y = x; // INVALID reference to f's local variable x\n}\n```\n\nVariable `x` is available only within the scope of `f`, which is the text lexically delimited by curly brackets. For this reason, Java is said to use lexical scoping. Lexical scoping is the norm for most programming languages. Languages that allow methods further down in the call chain to access local variables defined earlier are said to use dynamic scoping. The term dynamic refers to the fact that a compiler cannot statically determine the set of visible variables. This is because the set of variables visible to a method changes depending on who calls that method.\n\nIt turns out that, in the grammar realm, distant rules sometimes need to communicate with each other, mostly to provide context information to rules matched below in the rule invocation chain. (Naturally, this assumes that you are using actions directly in the grammar instead of the parse-tree listener event mechanism.) ANTLR allows dynamic scoping in that actions can access attributes from invoking rules using syntax `$r::x` where `r` is a rule name and `x` is an attribute within that rule. It is up to the programmer to ensure that `r` is in fact an invoking rule of the current rule. A runtime exception occurs if `r` is not in the current call chain when you access `$r::x`.\n\nTo illustrate the use of dynamic scoping, consider the real problem of defining variables and ensuring that variables in expressions are defined. The following grammar defines the symbols attribute where it belongs in the block rule but adds variable names to it in rule `decl`. Rule `stat` then consults the list to see whether variables have been defined.\n\n```\ngrammar DynScope;\n \nprog: block ;\n \nblock\n\t/* List of symbols defined within this block */\n\tlocals [\n\tList<String> symbols = new ArrayList<String>()\n\t]\n\t: '{' decl* stat+ '}'\n\t// print out all symbols found in block\n\t// $block::symbols evaluates to a List as defined in scope\n\t{System.out.println(\"symbols=\"+$symbols);}\n\t;\n \n/** Match a declaration and add identifier name to list of symbols */\ndecl: 'int' ID {$block::symbols.add($ID.text);} ';' ;\n \n/** Match an assignment then test list of symbols to verify\n * that it contains the variable on the left side of the assignment.\n * Method contains() is List.contains() because $block::symbols\n * is a List.\n */\nstat: ID '=' INT ';'\n\t{\n\tif ( !$block::symbols.contains($ID.text) ) {\n\tSystem.err.println(\"undefined variable: \"+$ID.text);\n\t}\n\t}\n\t| block\n\t;\n \nID : [a-z]+ ;\nINT : [0-9]+ ;\nWS : [ \\t\\r\\n]+ -> skip ;\n```\n\nHere’s a simple build and test sequence:\n\n```bash\n$ antlr4 DynScope.g4\n$ javac DynScope*.java\n$ grun DynScope prog\n=> \t{\n=> \tint i;\n=> \ti = 0;\n=> \tj = 3;\n=> \t}\n=> \tEOF\n<= \tundefined variable: j\n \tsymbols=[i]\n```\n\nThere’s an important difference between a simple field declaration in a `@members` action and dynamic scoping. symbols is a local variable and so there is a copy for each invocation of rule `block`. That’s exactly what we want for nested blocks so that we can reuse the same input variable name in an inner block. For example, the following nested code block redefines `i` in the inner scope. This new definition must hide the definition in the outer scope.\n\n```\n{\n\tint i;\n\tint j;\n\ti = 0;\n\t{\n\t\tint i;\n\t\tint x;\n\t\tx = 5;\n\t}\n\tx = 3;\n}\n```\n\nHere’s the output generated for that input by DynScope:\n\n```bash\n$ grun DynScope prog nested-input\nsymbols=[i, x]\nundefined variable: x\nsymbols=[i, j]\n```\n\nReferencing `$block::symbols` accesses the `symbols` field of the most recently invoked `block`’s rule context object. If you need access to a symbols instance from a rule invocation farther up the call chain, you can walk backwards starting at the current context, `$ctx`. Use `getParent` to walk up the chain.\n"
  },
  {
    "path": "doc/antlr-project-testing.md",
    "content": "# ANTLR project unit tests\n\n## Introduction\n\nBecause ANTLR supports multiple target languages, the unit tests are broken into two groups:\nthe unit tests that test the tool itself (in `tool-testsuite`) and the unit tests that test the parser runtimes (in `antlr4/runtime-testsuite`).\nThe tool tests are straightforward because they are Java code testing Java code; see the section at the bottom of this file.\n\nThe runtime tests must be specified in a generic fashion to work across language targets.\nFurthermore, the various targets from Java must be tested.\n\nThis usually means Java launching processes to compile, say, C++ and run parsers.\n\nAs of 4.10, a Java descriptor file held as an [RuntimeTestDescriptor.java](../runtime-testsuite/test/org/antlr/v4/test/runtime/RuntimeTestDescriptor.java)\nis used to represent each runtime test.\n\nEach test is described with a text file with various sections and resides in a group directory;\nsee [directories under descriptors' dir](../runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors).\nHere is a sample test descriptor:\n\n```\n[notes]\nThis is a regression test for blah blah blah...\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na : ID* {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\na b c\n\n[output]\n\"\"\"abc\n\"\"\"\n```\n\nThe grammars are strings representing StringTemplates (`ST` objects) so `<writeln(\"$text\")>` will get replace when the unit test file is generated (`Test.java`, `Test.cs`, ...).\nThe `writeln` template must be defined per target.\nHere are all the \n[Target templates for runtime tests](../runtime-testsuite/resources/org/antlr/v4/test/runtime/templates).\nUse triple-quotes `\"\"\"` when whitespace matters (usually input/output sections).\n\n## Requirements\n\nIn order to perform the tests on all target languages, the following tools should be installed:\n\n* dotnet\n* Node.js\n* Python 3\n* Go\n* Swift\n* Clang (Linux, Mac) or MSBuild (Windows) for C++\n* Dart\n* PHP\n\nTo **install into local repository** `~/.m2/repository/org/antlr`, do this:\n\n```bash\n$ export MAVEN_OPTS=\"-Xmx1G\"  # don't forget this on linux\n$ mvn install -DskipTests     # make sure all artifacts are visible on this machine\n```\n\n## Running the runtime tests\n\nA single test rig is sufficient to test all targets against all descriptors using the [junit dynamic tests](https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests) mechanism.\nBut it's often convenient to test just a single target or perhaps even just a single test within a single group of a single target.\nIntelliJ automatically generates a bunch of\n[Target runtime test rigs](../runtime-testsuite/test/org/antlr/v4/test/runtime) that allows developers such flexibility.\nFor example, here are the Python3 test rigs in IntelliJ:\n\n![testrigs](images/testrigs.png)\n\nAnd the result of testing the entire subdirectory:\n\n![python3-tests](images/python3-tests.png)\n\nAll test are run in parallel both via maven and via IDE.\n\nIn IntelliJ, it's very easy to go to source by right-clicking on any test and pressing `Jump to source` (F4).\n\n## Running test subsets\n\nFrom the `runtime-testsuite` dir\n\n### Run all tests for a single target\n\n```bash\n$ cd runtime-testsuite\n$ export MAVEN_OPTS=\"-Xmx1G\"     # don't forget this on linux\n$ mvn -Dtest='java.**' test\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\n[INFO] Running org.antlr.v4.test.runtime.java.TestIntegerList\n[INFO] Running org.antlr.v4.test.runtime.java.JavaRuntimeTests\n...\n[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 s - in org.antlr.v4.test.runtime.java.TestIntegerList\n[INFO] Tests run: 348, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 19.269 s - in org.antlr.v4.test.runtime.java.JavaRuntimeTests\n...\n```\n\n## Adding a runtime test\n\nTo add a new runtime test, first determine which [group (dir) of tests](../runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors) it belongs to.\nThen, add a new descriptor file implementation by filling in one of these (omitting unused sections):\n\n```\n[notes]\n\n[type]\n\n[grammar]\n\n[slaveGrammar]\n\n[start]\n\n[input]\n\n[output]\n\n[errors]\n\n[flags]\n\n[skip]\n```\n\nYour best bet is to find a similar test in the appropriate group and then copy and paste the descriptor file, creating a new file within the test group dir.\nModify the sections to suit your new problem.\n \n### Ignoring tests\n\nIn order to turn off a test for a particular target, the `skip` section in the descriptor file should be used.\nFor example, the following skips PHP and Dart targets:\n\n```\n[skip]\nPHP\nDart\n```\n\n### Target API/library testing\n\nSome parts of the runtime API need to be tested with code written specifically in the target language.\nFor example, all the Java runtime API tests are placed here:\n\n[runtime-testsuite/test/org/antlr/v4/test/runtime/java/api](../runtime-testsuite/test/org/antlr/v4/test/runtime/java/api)\n\nNotice that it is under an `api` dir. The directory above is where all of the `*Test*` files go.\n\n### Cross-language actions embedded within grammars\n\nTo get:\n\n```\nSystem.out.println($set.stop);\n```\n\nUse instead the language-neutral:\n\n```\n<writeln(\"$set.stop\")>\n```\n\nTemplate file [Java.test.stg](../runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Java.test.stg) has templates like:\n\n```\nwriteln(s) ::= <<System.out.println(<s>);>>\n```\n\nthat translate generic operations to target-specific language statements or expressions.\n\n## Adding an ANTLR tool unit test\n\nJust go into the appropriate Java test class in dir [antlr4/tool-testsuite/test/org/antlr/v4/test/tool](../tool-testsuite/test/org/antlr/v4/test/tool) and add your unit test.\n\n\n"
  },
  {
    "path": "doc/building-antlr.md",
    "content": "# Building ANTLR\n\nMost programmers do not need the information on this page because they will simply download the appropriate jar(s) or use ANTLR through maven (via ANTLR's antlr4-maven-plugin). If you would like to fork the project and fix bugs or tweak the runtime code generation, then you will almost certainly need to build ANTLR itself. There are two components:\n\n 1. the tool that compiles grammars down into parsers and lexers in one of the target languages\n 1. the runtime used by those generated parsers and lexers.\n\nI will assume that the root directory is `/tmp` for the purposes of explaining how to build ANTLR in this document.\n\n*As of 4.6, ANTLR tool and Java-target runtime requires Java 7. As of 4.10, we have verified that the tool itself builds with Java 8 and 11.*\n\n# Get the source\n\nThe first step is to get the Java source code from the ANTLR 4 repository at github. You can download the repository from github, but the easiest thing to do is simply clone the repository on your local disk:\n\n```bash\n$ cd /tmp\n/tmp $ git clone https://github.com/antlr/antlr4.git\nCloning into 'antlr4'...\nremote: Counting objects: 61480, done.\nremote: Total 61480 (delta 0), reused 0 (delta 0), pack-reused 61480\nReceiving objects: 100% (61480/61480), 31.24 MiB | 7.18 MiB/s, done.\nResolving deltas: 100% (32970/32970), done.\nChecking connectivity... done.\nChecking out files: 100% (1427/1427), done.\n```\n\n# Check your environment\n\nIf you are starting from a clean, minimum Ubuntu OS, check your environment.\n\n\n```bash\n$ sudo apt-get update\n$ # Get Java\n$ java > /dev/null 2>&1\n$ if [[ \"$?\" != \"0\" ]]; then sudo apt install -y openjdk-11-jre-headless; fi\n$ # Get Mvn\n$ mvn > /dev/null 2>&1\n$ if [[ \"$?\" != \"0\" ]]; then sudo apt install -y maven; fi\n\n```\n\n# Compile\n\nThe current maven build seems complicated to me because there is a dependency of the project on itself. The runtime tests naturally depend on the current version being available but it won't compile without the current version.  Once you have the generated/installed jar, mvn builds but otherwise there's a dependency on what you are going to build.  You will get this error when you try to clean but you can ignore it:\n\n```\n[INFO] ANTLR 4 Runtime Tests (4th generation) ............. FAILURE [  0.073 s]\n...\n[ERROR] Plugin org.antlr:antlr4-maven-plugin:4.10-SNAPSHOT or one of its dependencies could not be resolved: Could not find artifact org.antlr:antlr4-maven-plugin:jar:4.10-SNAPSHOT -> [Help 1]\n```\n\nTo be super squeaky clean, you can wipe out the repository cache, then do the build:\n\n```\n$ export MAVEN_OPTS=\"-Xmx1G\"   # don't forget this on linux\ncd /tmp/antlr4 # or wherever you have the software\nrm -rf ~/.m2/repository/org/antlr*\nmvn clean\nmvn -DskipTests install\n```\n\n**NOTE:** We do `install` not `compile` as tool tests and such refer to modules that must be pulled from the maven install local cache.\n\nOnce you have completed this process once and there is a jar hanging around in the repository cache.\n\n# Installing libs to mvn cache locally\n\nTo skip the tests (which require all the target languages be installed) and **install into local repository** `~/.m2/repository/org/antlr`, do this:\n\n```bash\n$ export MAVEN_OPTS=\"-Xmx1G\"     # don't forget this on linux\n$ mvn install -DskipTests   # make sure all artifacts are visible on this machine\n```\n\nYou should see these jars (when building 4.6-SNAPSHOT):\n\n```bash\n/Users/parrt/.m2/repository/org/antlr $ find antlr4* -name '*.jar'\nantlr4-maven-plugin/4.6-SNAPSHOT/antlr4-maven-plugin-4.6-SNAPSHOT.jar\nantlr4-runtime-testsuite/4.6-SNAPSHOT/antlr4-runtime-testsuite-4.6-SNAPSHOT-tests.jar\nantlr4-runtime-testsuite/4.6-SNAPSHOT/antlr4-runtime-testsuite-4.6-SNAPSHOT.jar\nantlr4-runtime/4.6-SNAPSHOT/antlr4-runtime-4.6-SNAPSHOT.jar\nantlr4-tool-testsuite/4.6-SNAPSHOT/antlr4-tool-testsuite-4.6-SNAPSHOT.jar\nantlr4/4.6-SNAPSHOT/antlr4-4.6-SNAPSHOT-tests.jar\nantlr4/4.6-SNAPSHOT/antlr4-4.6-SNAPSHOT.jar\n```\n\nNote that ANTLR is written in itself, which is why maven downloads antlr4-4.5.jar for boostrapping 4.6-SNAPSHOT purposes.\n\n# Testing tool and targets\n\nSee [ANTLR project unit tests](antlr-project-testing.md).\n\n\n# Building without testing\n\nTo build without running the tests (saves a lot of time), do this:\n\n```bash\n$ mvn -DskipTests install\n```\n\n## Building ANTLR in Intellij IDE\n\nAfter download ANTLR source, just \"import project from existing sources\" and click on the \"Maven Projects\" tab in right gutter of IDE. It should build stuff in the background automatically and look like:\n\n<img src=images/intellij-maven.png width=200>\n"
  },
  {
    "path": "doc/cpp-target.md",
    "content": "# C++\n\nThe C++ target supports all platforms that can either run MS Visual Studio 2017 (or newer), XCode 7 (or newer) or CMake (C++17 required). All build tools can either create static or dynamic libraries, both as 64bit or 32bit arch. Additionally, XCode can create an iOS library. Also see [Antlr4 for C++ with CMake: A practical example](http://blorente.me/beyond-the-loop/Antlr-cpp-cmake/).\n\n## How to create a C++ lexer or parser?\nThis is pretty much the same as creating a Java lexer or parser, except you need to specify the language target, for example:\n\n```\n$ antlr4 -Dlanguage=Cpp MyGrammar.g4\n```\n\nYou will see that there are a whole bunch of files generated by this call. If visitor or listener are not suppressed (which is the default) you'll get:\n\n* MyGrammarLexer.h + MyGrammarLexer.cpp\n* MyGrammarParser.h + MyGrammarParser.cpp\n* MyGrammarVisitor.h + MyGrammarVisitor.cpp\n* MyGrammarBaseVisitor.h + MyGrammarBaseVisitor.cpp\n* MyGrammarListener.h + MyGrammarListener.cpp\n* MyGrammarBaseListener.h + MyGrammarBaseListener.cpp\n\n## Where can I get the runtime?\n\nOnce you've generated the lexer and/or parser code, you need to download or build the runtime. Prebuilt C++ runtime binaries for Windows (Visual Studio 2013/2015), OSX/macOS and iOS are available on the ANTLR web site:\n\n* http://www.antlr.org\n\nUse CMake to build a Linux library (works also on OSX, however not for the iOS library).\n\nInstead of downloading a prebuilt binary you can also easily build your own library on OSX or Windows. Just use the provided projects for XCode or Visual Studio and build it. Should work out of the box without any additional dependency.\n\n\n## How do I run the generated lexer and/or parser?\n\nPutting it all together to get a working parser is really easy. Look in the [runtime/Cpp/demo](../runtime/Cpp/demo) folder for a simple example. The [README](../runtime/Cpp/demo/README.md) there describes shortly how to build and run the demo on OSX, Windows or Linux.\n\n## How do I create and run a custom listener?\n\nThe generation step above created a listener and base listener class for you. The listener class is an abstract interface, which declares enter and exit methods for each of your parser rules. The base listener implements all those abstract methods with an empty body, so you don't have to do it yourself if you just want to implement a single function. Hence use this base listener as the base class for your custom listener:\n\n```c++\n#include <iostream>\n\n#include \"antlr4-runtime.h\"\n#include \"MyGrammarLexer.h\"\n#include \"MyGrammarParser.h\"\n#include \"MyGrammarBaseListener.h\"\n\nusing namespace antlr4;\n\nclass TreeShapeListener : public MyGrammarBaseListener {\npublic:\n  void enterKey(ParserRuleContext *ctx) override {\n\t// Do something when entering the key rule.\n  }\n};\n\n\nint main(int argc, const char* argv[]) {\n  std::ifstream stream;\n  stream.open(argv[1]);\n  ANTLRInputStream input(stream);\n  MyGrammarLexer lexer(&input);\n  CommonTokenStream tokens(&lexer);\n  MyGrammarParser parser(&tokens);\n\n  tree::ParseTree *tree = parser.key();\n  TreeShapeListener listener;\n  tree::ParseTreeWalker::DEFAULT.walk(&listener, tree);\n\n  return 0;\n}\n\n```\n \nThis example assumes your grammar contains a parser rule named `key` for which the `enterKey` function was generated.\n\n## Special cases for this ANTLR target\n\nThere are a couple of things that only the C++ ANTLR target has to deal with. They are described here.\n\n### Code Generation Aspects\nThe code generation (by running the ANTLR4 jar) allows to specify 2 values you might find useful for better integration of the generated files into your application (both are optional):\n\n* A **namespace**: use the **`-package`** parameter to specify the namespace you want.\n* An **export macro**: especially in VC++ extra work is required to export your classes from a DLL. This is usually accomplished by a macro that has different values depending on whether you are creating the DLL or import it. The ANTLR4 runtime itself also uses one for its classes:\n\n```c++\n  #ifdef ANTLR4CPP_EXPORTS\n    #define ANTLR4CPP_PUBLIC __declspec(dllexport)\n  #else\n    #ifdef ANTLR4CPP_STATIC\n      #define ANTLR4CPP_PUBLIC\n    #else\n      #define ANTLR4CPP_PUBLIC __declspec(dllimport)\n    #endif\n  #endif\n```\nJust like the `ANTLR4CPP_PUBLIC` macro here you can specify your own one for the generated classes using the **`-DexportMacro=...`** command-line parameter or\ngrammar option `options {exportMacro='...';}` in your grammar file.\n\nIn order to create a static lib in Visual Studio define the `ANTLR4CPP_STATIC` macro in addition to the project settings that must be set for a static library (if you compile the runtime yourself).\n\nFor gcc and clang it is possible to use the `-fvisibility=hidden` setting to hide all symbols except those that are made default-visible (which has been defined for all public classes in the runtime).\n\n### Compile Aspects\n\nWhen compiling generated files, you can configure a compile option according to your needs (also optional):\n\n* A **thread local DFA macro**: Add `-DANTLR4_USE_THREAD_LOCAL_CACHE=1` to the compilation options\nwill enable using thread local DFA cache (disabled by default), after that, each thread uses its own DFA.\nThis will increase memory usage to store thread local DFAs and redundant computation to build thread local DFAs (not too much).\nThe benefit is that it can improve the concurrent performance running with multiple threads.\nIn other words, when you find your concurent throughput is not high enough, you should consider turning on this option.\n\n### Memory Management\nSince C++ has no built-in memory management we need to take extra care. For that we rely mostly on smart pointers, which however might cause time penalties or memory side effects (like cyclic references) if not used with care. Currently however the memory household looks very stable. Generally, when you see a raw pointer in code consider this as being managed elsewhere. You should never try to manage such a pointer (delete, assign to smart pointer etc.).\n\nAccordingly a parse tree is only valid for the lifetime of its parser. The parser, in turn, is only valid for the lifetime of its token stream, and so on back to the original `ANTLRInputStream` (or equivalent). To retain a tree across function calls you'll need to create and store all of these and `delete` all but the tree when you no longer need it.\n\n### Unicode Support\nEncoding is mostly an input issue, i.e. when the lexer converts text input into lexer tokens. The parser is completely encoding unaware.\n\nThe C++ target always expects UTF-8 input (either in a string or stream) which is then converted to UTF-32 (a char32_t array) and fed to the lexer.\n\n### Named Actions\nIn order to help customizing the generated files there are a number of additional so-called **named actions**. These actions are tight to specific areas in the generated code and allow to add custom (target specific) code. All targets support these actions\n\n* @parser::header\n* @parser::members\n* @lexer::header\n* @lexer::members\n\n(and their scopeless alternatives `@header` and `@members`) where header doesn't mean a C/C++ header file, but the top of a code file. The content of the header action appears in all generated files at the first line. So it's good for things like license/copyright information.\n\nThe content of a *members* action is placed in the public section of lexer or parser class declarations. Hence it can be used for public variables or predicate functions used in a grammar predicate. Since all targets support *header* + *members* they are the best place for stuff that should be available also in generated files for other languages.\n\nIn addition to that the C++ target supports many more such named actions. Unfortunately, it's not possible to define new scopes (e.g. *listener* in addition to *parser*) so they had to be defined as part of the existing scopes (*lexer* or *parser*). The grammar in the demo application contains all of the named actions as well for reference. Here's the list:\n\n* **@lexer::preinclude** - Placed right before the first #include (e.g. good for headers that must appear first, for system headers etc.). Appears in both lexer h and cpp file.\n* **@lexer::postinclude** - Placed right after the last #include, but before any class code (e.g. for additional namespaces). Appears in both lexer h and cpp file.\n* **@lexer::context** - Placed right before the lexer class declaration. Use for e.g. additional types, aliases, forward declarations and the like. Appears in the lexer h file.\n* **@lexer::declarations** - Placed in the private section of the lexer declaration (generated sections in all classes strictly follow the pattern: public, protected, private, from top to bottom). Use this for private vars etc.\n* **@lexer::definitions** - Placed before other implementations in the cpp file (but after *@postinclude*). Use this to implement e.g. private types.\n\nFor the parser there are the same actions as shown above for the lexer. In addition to that there are even more actions for visitor and listener classes:\n\n* **@parser::listenerpreinclude**\n* **@parser::listenerpostinclude**\n* **@parser::listenerdeclarations**\n* **@parser::listenermembers**\n* **@parser::listenerdefinitions**\n* \n* **@parser::baselistenerpreinclude**\n* **@parser::baselistenerpostinclude**\n* **@parser::baselistenerdeclarations**\n* **@parser::baselistenermembers**\n* **@parser::baselistenerdefinitions**\n* \n* **@parser::visitorpreinclude**\n* **@parser::visitorpostinclude**\n* **@parser::visitordeclarations**\n* **@parser::visitormembers**\n* **@parser::visitordefinitions**\n* \n* **@parser::basevisitorpreinclude**\n* **@parser::basevisitorpostinclude**\n* **@parser::basevisitordeclarations**\n* **@parser::basevisitormembers**\n* **@parser::basevisitordefinitions**\n\nand should be self explanatory now. Note: there is no *context* action for listeners or visitors, simply because they would be even less used than the other actions and there are so many already.\n"
  },
  {
    "path": "doc/creating-a-language-target.md",
    "content": "# Creating an ANTLR Language Target\n\nThis document describes how to make ANTLR generate parsers in a new language, *X*.\n\n## Overview\n\nCreating a new target involves the following key elements:\n\n1. For the tool, create class *X*Target as a subclass of class `Target` in package `org.antlr.v4.codegen.target`.\n   This class describes language specific details about escape characters and strings and so on.\n   There is very little to do here typically.\n2. Create `*X*.stg` in directory `tool/resources/org/antlr/v4/tool/templates/codegen/*X*/*X*.stg`.\n   This is a [StringTemplate](http://www.stringtemplate.org/) group file (`.stg`) that tells ANTLR how to express\n   all the parsing elements needed to generate code.\n   You will see templates called `ParserFile`, `Parser`, `Lexer`, `CodeBlockForAlt`, `AltBlock`, etc...\n   Each of these must be described how to build the indicated chunk of code.\n   Your best bet is to find the closest existing target, copy that template file, and tweak to suit.\n3. Create a runtime library to support the parsers generated by ANTLR.\n   Under directory `runtime/*X*`, you are in complete control of the directory structure as dictated by common usage of that target language.\n   For example, Java has: `runtime/Java/lib` and `runtime/Java/src` directories.\n   Under `src`, you will find a directory structure for package `org.antlr.v4.runtime` and below.\n4. Create a template file for runtime tests.\n   All you have to do is provide a few templates that indicate how to print values and declare variables.\n   Our runtime test mechanism in dir `runtime-testsuite` will automatically generate code using these templates for each target and check the test results.\n   It needs to know how to define various class fields, compare members and so on.\n   You must create a `*X*.test.stg` file underneath [runtime-testsuite/resources/org/antlr/v4/test/runtime](../runtime-testsuite/resources/org/antlr/v4/test/runtime)\n   and `Test.*x*.stg` underneath [runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers](../runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers).\n   Again, your best bet is to copy the templates from the closest language to your target and tweak it to suit.\n6. Create test files under [/runtime-testsuite/test/org/antlr/v4/test/runtime](../runtime-testsuite/test/org/antlr/v4/test/runtime).\n   They will load defined test cases in each test descriptor.\n   Also add the `/runtime-testsuite/test/org/antlr/v4/test/runtime/X/BaseXTest.java` which defines how test cases will execute and output.\n7. Create/edit shell scripts in [/.github](../.github) to run tests in CI pipelines.\n\n## Getting started\n\n1. Fork the `antlr/antlr4` repository at GitHub to your own user so that you have repository `username/antlr4`.\n2. Clone `username/antlr4`, the forked repository, to your local disk.\n   Your remote `origin` will be the forked repository on GitHub.\n   Add a remote `upstream` to the original `antlr/antlr4` repository (URL `https://github.com/antlr/antlr4.git`).\n   Changes that you would like to contribute back to the project are done with [pull requests](https://help.github.com/articles/using-pull-requests/).\n3. Try to build it before doing anything\n\n```bash\n$ mvn compile\n```\n\nThat should proceed with success. See [Building ANTLR](building-antlr.md) for more details.\n\n## Comparing your target's parsing decisionmaking with Java's\n\nANTLR's power comes from it's dynamic parsing strategy, but that means each target\nmust implement that complicated algorithm. You should compare your target's debug\noutput for ParserATNSimulator with Java's.\n\nRun this so we get right jars before trying this script:\n\n```\ncd ANTLR-ROOT-DIR\nmvn install -DskipTests=true\ncd runtime-tests \nmvn install -DskipTests=true # yes do it again\n```\n\nRun the script from `runtime-tests` dir with\n\n```\n../scripts/traceatn.sh /tmp/JSON.g4 json -target Go /tmp/foo.json\n```\n\nor whatever your test grammar, start rule, target, test input are.\n\n### Debugging the PHP target\n\nBecause the PHP target is hosted in a separate repository, you will need to clone the [antlr/php-antlr-runtime](https://github.com/antlr/antlr-php-runtime)\nrepository into the `runtime/PHP` and install the dependencies with `composer install` before you can run the tests.\n\n```\ngit clone -b dev https://github.com/antlr/antlr-php-runtime.git runtime/PHP\ncd runtime/PHP\ncomposer install\n```\n"
  },
  {
    "path": "doc/csharp-target.md",
    "content": "# C&sharp;\n\n## Which frameworks are supported?\n\nThe C# runtime is CLS compliant, and only requires a corresponding 3.5 .Net framework.\n\nIn practice, the runtime has been extensively tested against:\n\n* Microsoft .Net 3.5 framework\n* Mono .Net 3.5 framework\n\nNo issue was found, so you should find that the runtime works pretty much against any recent .Net framework.\n\n## How do I get started?\n\nYou will find full instructions on the [Git repo page for ANTLR C# runtime](https://github.com/antlr/antlr4/tree/master/runtime/CSharp).\n \n## How do I use the runtime from my project?\n\n(i.e., How do I run the generated lexer and/or parser?)\n\nLet's suppose that your grammar is named `MyGrammar`. The tool will generate for you the following files:\n\n*   MyGrammarLexer.cs\n*   MyGrammarParser.cs\n*   MyGrammarListener.cs (if you have not activated the -no-listener option)\n*   MyGrammarBaseListener.cs (if you have not activated the -no-listener option)\n*   MyGrammarVisitor.cs (if you have activated the -visitor option)\n*   MyGrammarBaseVisitor.cs (if you have activated the -visitor option)\n\nNow a fully functioning code might look like the following for start rule `StartRule`:\n\n```csharp\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Tree;\n     \npublic void MyParseMethod() {\n      String input = \"your text to parse here\";\n      ICharStream stream = CharStreams.fromString(input);\n      ITokenSource lexer = new MyGrammarLexer(stream);\n      ITokenStream tokens = new CommonTokenStream(lexer);\n      MyGrammarParser parser = new MyGrammarParser(tokens);\n      IParseTree tree = parser.StartRule();\n}\n```\n\nThis program will work. But it won't be useful unless you do one of the following:\n\n* you visit the parse tree using a custom listener\n* you visit the parse tree using a custom visitor\n* your grammar comprises production code (like AntLR3)\n\n(please note that production code is target specific, so you can't have multi target grammars that include production code)\n \n## How do I create and run a custom listener?\n\nLet's suppose your MyGrammar grammar comprises 2 rules: \"key\" and \"value\".\n\nThe antlr4 tool will have generated the following listener (only partial code shown here): \n\n```csharp\ninterface IMyGrammarParserListener : IParseTreeListener {\n      void EnterKey (MyGrammarParser.KeyContext context);\n      void ExitKey (MyGrammarParser.KeyContext context);\n      void EnterValue (MyGrammarParser.ValueContext context);\n      void ExitValue (MyGrammarParser.ValueContext context);\n}\n```\n \nIn order to provide custom behavior, you might want to create the following class:\n \n```csharp\nclass KeyPrinter : MyGrammarBaseListener {\n    // override default listener behavior\n    void ExitKey (MyGrammarParser.KeyContext context) {\n        Console.WriteLine(\"Oh, a key!\");\n    }\n}\n```\n   \nIn order to execute this listener, you would simply add the following lines to the above code:\n \n \n```csharp\n...\nIParseTree tree = parser.StartRule() - only repeated here for reference\nKeyPrinter printer = new KeyPrinter();\nParseTreeWalker.Default.Walk(printer, tree);\n```\n        \nFurther information can be found from The Definitive ANTLR Reference book.\n\nThe C# implementation of ANTLR is as close as possible to the Java one, so you shouldn't find it difficult to adapt the examples for C#. See also [Sam Harwell's alternative C# target](https://github.com/tunnelvisionlabs/antlr4cs)\n\n"
  },
  {
    "path": "doc/dart-target.md",
    "content": "# ANTLR4 Runtime for Dart\n\nFrom version 4.9 onwards antlr's dart generated code is null sound safety compatible and sets the minimum dart sdk version to 2.12.0.\n\n### First steps\n\n#### 1. Install ANTLR4\n\n[The getting started guide](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md) \nshould get you started.\n\n#### 2. Install the Dart ANTLR runtime\n\nEach target language for ANTLR has a runtime package for running parser \ngenerated by ANTLR4. The runtime provides a common set of tools for using your parser.\n\nInstall the runtime with the same version as the main ANTLR tool:\n\nAdd this to your package's pubspec.yaml file:\n```yaml\n...\ndependencies:\n  antlr4: <ANTLR version>\n...\n```\n\n#### 3. Generate your parser\n\nYou use the ANTLR4 \"tool\" to generate a parser. These will reference the ANTLR \nruntime, installed above.\n\nSuppose you're using a UNIX system and have set up an alias for the ANTLR4 tool \nas described in [the getting started guide](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md). \nTo generate your Dart parser, run the following command:\n\n```shell script\nantlr4 -Dlanguage=Dart MyGrammar.g4\n```\n\nFor a full list of antlr4 tool options, please visit the \n[tool documentation page](https://github.com/antlr/antlr4/blob/master/doc/tool-options.md).\n\n### Complete example\n\nSuppose you're using the JSON grammar from https://github.com/antlr/grammars-v4/tree/master/json.\n\nThen, invoke `antlr4 -Dlanguage=Dart JSON.g4`. The result of this is a \ncollection of `.dart` including:\n\n* JsonLexer.dart\n* JsonParser.dart\n* JsonBaseListener.dart\n* JsonListener.dart (if you have not activated the -no-listener option)\n* JsonVisitor.dart (if you have activated the -visitor option)\n\nWe'll write a small main func to call the generated parser/lexer \n(assuming they are separate). This one writes out the encountered \n`ParseTreeContext`'s:\n\n```dart\nimport 'package:antlr4/antlr4.dart';\nimport 'package:my_project/JSONParser.dart';\nimport 'package:my_project/JSONLexer.dart';\n\nclass TreeShapeListener implements ParseTreeListener {\n  @override\n  void enterEveryRule(ParserRuleContext ctx) {\n    print(ctx.text);\n  }\n\n  @override\n  void exitEveryRule(ParserRuleContext node) {\n  }\n\n  @override\n  void visitErrorNode(ErrorNode node) {\n  }\n\n  @override\n  void visitTerminal(TerminalNode node) {\n  }\n}\n\nvoid main(List<String> args) async {\n  JSONLexer.checkVersion();\n  JSONParser.checkVersion();\n  final input = await InputStream.fromPath(args[0]);\n  final lexer = JSONLexer(input);\n  final tokens = CommonTokenStream(lexer);\n  final parser = JSONParser(tokens);\n  parser.addErrorListener(DiagnosticErrorListener());\n  final tree = parser.json();\n  ParseTreeWalker.DEFAULT.walk(TreeShapeListener(), tree);\n}\n```\n\nCreate a `example.json` file:\n```json\n{\"a\":1}\n```\n\nParse the input file:\n\n```shell script\ndart bin/main.dart example.json\n```\n\nThe expected output is:\n\n```\n{\"a\":1}\n{\"a\":1}\n{\"a\":1}\n\"a\":1\n1\n```\n\n### Debug\n\nWe have some logs in place that can ease the debugging process, in order to turn these logs on you can enable the following environment declarations:\n\n- ANTLR_LEXER_DEBUG\n- ANTLR_LEXER_DFA_DEBUG\n- ANTLR_PARSER_DEBUG\n- ANTLR_PARSER_LIST_ATN_DECISIONS_DEBUG\n- ANTLR_PARSER_DFA_DEBUG\n- ANTLR_PARSER_RETRY_DEBUG\n\nIf you're using flutter, you can define these variables by adding an `--dart-define` arguments, eg. `flutter run --dart-define LEXER_DEBUG=false`\n"
  },
  {
    "path": "doc/faq/actions-preds.md",
    "content": "# Actions and semantic predicates\n\n## How do I test if an optional rule was matched?\n\nFor optional rule references such as the initialization clause in the following\n\n```\ndecl : 'var' ID (EQUALS expr)? ;\n```\n\ntesting to see if that clause was matched can be done using `$EQUALS!=null` or `$expr.ctx!=null` where `$expr.ctx` points to the context or parse tree created for that reference to rule expr."
  },
  {
    "path": "doc/faq/error-handling.md",
    "content": "# Error handling\n\n## How do I perform semantic checking with ANTLR?\n\nSee [How to implement error handling in ANTLR4](http://stackoverflow.com/questions/21613421/how-to-implement-error-handling-in-antlr4/21615751#21615751).\n"
  },
  {
    "path": "doc/faq/general.md",
    "content": "# General\n\n## Why do we need ANTLR v4?\n\n*Oliver Zeigermann asked me some questions about v4. Here is our conversation.*\n\n*See the [preface from the book](http://media.pragprog.com/titles/tpantlr2/preface.pdf)*\n\n**Q: Why is the new version of ANTLR also called “honey badger”?**\n\nANTLR v4 is called the honey badger release after the fearless hero of the YouTube sensation, The Crazy Nastyass Honey Badger.\n\n**Q: Why did you create a new version of ANTLR?**\n\nWell, I start creating a new version because v3 had gotten very messy on the inside and also relied on grammars written in ANTLR v2. Unfortunately, v2's open-source license was unclear and so projects such as Eclipse could not include v3 because of its dependency on v2. In the end, Sam Harwell converted all of the v2 grammars into v3 so that v3 was written in itself. Because v3 has a very clean BSD license, the Eclipse project okayed for inclusion in that project in the summer of 2011.\n\nAs I was rewriting ANTLR, I wanted to experiment with a new variation of the LL(\\*) parsing algorithm. As luck would have it, I came up with a cool new version called adaptive LL(\\*) that pushes all of the grammar analysis effort to runtime. The parser warms up like Java does with its JIT on-the-fly compiler; the code gets faster and faster the longer it runs. The benefit is that the adaptive algorithm is much stronger than the static LL(\\*) grammar analysis algorithm in v3. Honey Badger takes any grammar that you give it; it just doesn't give a damn. (v4 accepts even left recursive grammars, except for indirectly left recursive grammars where x calls y which calls x).\n\nv4 is the culmination of 25 years of research into parsers and parser generators. I think I finally know what I want to build. :)\n\n**Q: What makes you excited about ANTLR4?**\n\nThe biggest thing is the new adaptive parsing strategy, which lets us accept any grammar we care to write. That gives us a huge productivity boost because we can now write much more natural expression rules (which occur in almost every grammar). For example, bottom-up parser generators such as yacc let you write very natural grammars like this:\n\n```\ne : e '*' e\n  | e '+' e\n  | INT\n  ;\n```\n\nANTLR v4 will also take that grammar now, translating it secretly to a non-left recursive version.\n\nAnother big thing with v4 is that my goal has shifted from performance to ease-of-use. For example, ANTLR automatically can build parse trees for you and generate listeners and visitors. This is not only a huge productivity win, but also an important step forward in building grammars that don't depend on embedded actions. Those embedded actions (raw Java code or whatever) locked the grammar into use with only one language. If we keep all of the actions out of the grammar and put them into external visitors, we can reuse the same grammar to generate code in any language for which we have an ANTLR target.\n\n**Q: What do you think are the things people had problems with in ANTLR3?**\n\nThe biggest problem was figuring out why ANTLR did not like their grammar. The static analysis often could not figure out how to generate a parser for the grammar. This problem totally goes away with the honey badger because it will take just about anything you give it without a whimper.\n\n**Q: And what with other compiler generator tools?**\n\nThe biggest problem for the average practitioner is that most parser generators do not produce code you can load into a debugger and step through. This immediately removes bottom-up parser generators and the really powerful GLR parser generators from consideration by the average programmer. There are a few other tools that generate source code like ANTLR does, but they don't have v4's adaptive LL(\\*) parsers. You will be stuck with contorting your grammar to fit the needs of the tool's weaker, say, LL(k) parsing strategy. PEG-based tools have a number of weaknesses, but to mention one, they have essentially no error recovery because they cannot report an error and until they have parsed the entire input.\n\n**Q: What are the main design decisions in ANTLR4?**\n\nEase-of-use over performance. I will worry about performance later. Simplicity over complexity. For example, I have taken out explicit/manual AST construction facilities and the tree grammar facilities. For 20 years I've been trying to get people to go that direction, but I've since decided that it was a mistake. It's much better to give people a parser generator that can automatically build trees and then let them use pure code to do whatever tree walking they want. People are extremely familiar and comfortable with visitors, for example.\n\n**Q: What do you think people will like most on ANTLR4?**\n\nThe lack of errors when you run your grammar through ANTLR. The automatic tree construction and listener/visitor generation.\n\n**What do you think are the problems people will try to solve with ANTLR4?**\n\nIn my experience, almost no one uses parser generators to build commercial compilers. So, people are using ANTLR for their everyday work, building everything from configuration files to little scripting languages.\n\nIn response to a question about this entry from stackoverflow.com: I believe that compiler developers are very concerned with parsing speed, error reporting, and error recovery. For that, they want absolute control over their parser. Also, some languages are so complicated, such as C++, that parser generators might build parsers slower than compiler developers want. The compiler developers also like the control of a recursive-descent parser for predicating the parse to handle context-sensitive constructs such as `T(i)` in C++.\n\nThere is also likely a sense that parsing is the easy part of building a compiler so they don't immediately jump automatically to parser generators. I think this is also a function of previous generation parser generators. McPeak's Elkhound GLR-based parser generator is powerful enough and fast enough, in the hands of someone that knows what they're doing, to be suitable for compilers. I can also attest to the fact that ANTLR v4 is now powerful enough and fast enough to compete well with handbuilt parsers. E.g., after warm-up, it's now taking just 1s to parse the entire JDK java/\\* library.\n\n## What is the difference between ANTLR 3 and 4?\n\nThe biggest difference between ANTLR 3 and 4 is that ANTLR 4 takes any grammar you give it unless the grammar had indirect left recursion. That means we don't need syntactic predicates or backtracking so ANTLR 4 does not support that syntax; you will get a warning for using it. ANTLR 4 allows direct left recursion so that expressing things like arithmetic expression syntax is very easy and natural:\n\n```\nexpr : expr '*' expr\n     | expr '+' expr\n     | INT\n     ;\n```\n\nANTLR 4 automatically constructs parse trees for you and abstract syntax tree (AST) construction is no longer an option. See also [What if I need ASTs not parse trees for a compiler, for example?](https://github.com/antlr/antlr4/blob/master/doc/faq/parse-trees.md#what-if-i-need-asts-not-parse-trees-for-a-compiler-for-example).\n\nAnother big difference is that we discourage the use of actions directly within the grammar because ANTLR 4 automatically generates [listeners and visitors](https://github.com/antlr/antlr4/blob/master/doc/listeners.md) for you to use that trigger method calls when some phrases of interest are recognized during a tree walk after parsing. See also [Parse Tree Matching and XPath](https://github.com/antlr/antlr4/blob/master/doc/tree-matching.md).\n\nSemantic predicates are still allowed in both the parser and lexer rules as our actions.  For efficiency sake keep semantic predicates to the right edge of lexical rules.\n\nThere are no tree grammars because we use listeners and visitors instead.\n\n## Why is my expression parser slow?\n\nMake sure to use two-stage parsing. See example in [bug report](https://github.com/antlr/antlr4/issues/374).\n\n```Java\n\nCharStream input = CharStreams.fromPath(Paths.get(args[0]));\nExprLexer lexer = new ExprLexer(input);\nCommonTokenStream tokens = new CommonTokenStream(lexer);\nExprParser parser = new ExprParser(tokens);\nparser.getInterpreter().setPredictionMode(PredictionMode.SLL);\ntry {\n    parser.stat();  // STAGE 1\n}\ncatch (Exception ex) {\n    tokens.reset(); // rewind input stream\n    parser.reset();\n    parser.getInterpreter().setPredictionMode(PredictionMode.LL);\n    parser.stat();  // STAGE 2\n    // if we parse ok, it's LL not SLL\n}\n```\n"
  },
  {
    "path": "doc/faq/getting-started.md",
    "content": "# Getting started\n\n## How to I install and run a simple grammar?\n\nSee [Getting Started with ANTLR v4](https://raw.githubusercontent.com/antlr/antlr4/master/doc/getting-started.md).\n\n## Why does my parser test program hang?\n\nYour test program is likely not hanging but simply waiting for you to type some input for standard input. Don't forget that you need to type the end of file character, generally on a line by itself, at the end of the input. On a Mac or Linux machine it is ctrl-D, as gawd intended, or ctrl-Z on a Windows machine.\n\nSee [Getting Started with ANTLR v4](https://raw.githubusercontent.com/antlr/antlr4/master/doc/getting-started.md)."
  },
  {
    "path": "doc/faq/index.md",
    "content": "# Frequently-Asked Questions (FAQ)\n\nThis is the main landing page for the ANTLR 4 FAQ. The links below will take you to the appropriate file containing all answers for that subcategory.\n\n*To add to or improve this FAQ, [fork](https://help.github.com/articles/fork-a-repo/) the [antlr/antlr4 repo](https://github.com/antlr/antlr4) then update this `doc/faq/index.md` or file(s) in that directory.  Submit a [pull request](https://help.github.com/articles/creating-a-pull-request/) to get your changes incorporated into the main repository. Do not mix code and FAQ updates in the sample pull request.* **You must sign the contributors.txt certificate of origin with your pull request if you've not done so before.**\n\n## Getting Started\n\n* [How to I install and run a simple grammar?](getting-started.md)\n* [Why does my parser test program hang?](getting-started.md)\n\n## Installation\n\n* [Why can't ANTLR (grun) find my lexer or parser?](installation.md)\n* [Why can't I run the ANTLR tool?](installation.md)\n* [Why doesn't my parser compile?](installation.md)\n\n## General\n\n* [Why do we need ANTLR v4?](general.md)\n* [What is the difference between ANTLR 3 and 4?](general.md)\n* [Why is my expression parser slow?](general.md)\n\n## Grammar syntax\n\n## Lexical analysis\n\n* [How can I parse non-ASCII text and use characters in token rules?](lexical.md)\n* [How do I replace escape characters in string tokens?](lexical.md)\n* [Why are my keywords treated as identifiers?](lexical.md)\n* [Why are there no whitespace tokens in the token stream?](lexical.md)\n\n## Parse Trees\n\n* [How do I get the input text for a parse-tree subtree?](parse-trees.md)\n* [What if I need ASTs not parse trees for a compiler, for example?](parse-trees.md)\n* [When do I use listener/visitor vs XPath vs Tree pattern matching?](parse-trees.md)\n\n## Translation\n\n* [ASTs vs parse trees](translation.md)\n* [Decoupling input walking from output generation](translation.md)\n\n## Actions and semantic predicates\n\n* [How do I test if an optional rule was matched?](actions-preds.md)\n\n## Error handling\n\n* [How do I perform semantic checking with ANTLR?](error-handling.md)\n"
  },
  {
    "path": "doc/faq/installation.md",
    "content": "# Installation\n\nPlease read carefully: [Getting Started with ANTLR v4](https://raw.githubusercontent.com/antlr/antlr4/master/doc/getting-started.md).\n\n## Why can't ANTLR (grun) find my lexer or parser?\n\nIf you see \"Can't load Hello as lexer or parser\", it's because you don't have '.' (current directory) in your CLASSPATH.\n\n```bash\n$ alias antlr4='java -jar /usr/local/lib/antlr-4.2.2-complete.jar'\n$ alias grun='java org.antlr.v4.runtime.misc.TestRig'\n$ export CLASSPATH=\"/usr/local/lib/antlr-4.2.2-complete.jar\"\n$ antlr4 Hello.g4\n$ javac Hello*.java\n$ grun Hello r -tree\nCan't load Hello as lexer or parser\n$\n```\n\nFor mac/linux, use:\n\n```bash\nexport CLASSPATH=\".:/usr/local/lib/antlr-4.2.2-complete.jar:$CLASSPATH\"\n```\n\nor for Windows:\n\n```\nSET CLASSPATH=.;C:\\Javalib\\antlr4-complete.jar;%CLASSPATH%\n```\n\n**See the dot at the beginning?** It's critical.\n\n## Why can't I run the ANTLR tool?\n\nIf you get a no class definition found error, you are missing the ANTLR jar in your `CLASSPATH` (or you might only have the runtime jar):\n\n```bash\n/tmp $ java org.antlr.v4.Tool Hello.g4\nException in thread \"main\" java.lang.NoClassDefFoundError: org/antlr/v4/Tool\nCaused by: java.lang.ClassNotFoundException: org.antlr.v4.Tool\n    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)\n    at java.security.AccessController.doPrivileged(Native Method)\n    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)\n    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)\n    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)\n    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)\n```\n\n## Why doesn't my parser compile?\n\nIf you see these kinds of errors, it's because you don't have the runtime or complete ANTLR library in your CLASSPATH.\n\n```bash\n/tmp $ javac Hello*.java\nHelloBaseListener.java:3: package org.antlr.v4.runtime does not exist\nimport org.antlr.v4.runtime.ParserRuleContext;\n                           ^\n...\n```\n"
  },
  {
    "path": "doc/faq/lexical.md",
    "content": "# Lexical analysis\n\n## How can I parse non-ASCII text and use characters in token rules?\n\nSee [Using non-ASCII characters in token rules](http://stackoverflow.com/questions/28126507/antlr4-using-non-ascii-characters-in-token-rules/28129510#28129510).\n\n## How do I replace escape characters in string tokens?\n\nUnfortunately, manipulating the text of the token matched by a lexical rule is cumbersome (as of 4.2).  You have to build up a buffer and then set the text at the end. Actions in the lexer execute at the associated position in the input just like they do in the parser. Here's an example that does escape character replacement in strings. It's not pretty but it works.\n\n```\ngrammar Foo;\n \n@members {\nStringBuilder buf = new StringBuilder(); // can't make locals in lexer rules\n}\n \nSTR :   '\"'\n        (   '\\\\'\n            (   'r'     {buf.append('\\r');}\n            |   'n'     {buf.append('\\n');}\n            |   't'     {buf.append('\\t');}\n            |   '\\\\'    {buf.append('\\\\');}\n            |   '\\\"'   {buf.append('\"');}\n            )\n        |   ~('\\\\'|'\"') {buf.append((char)_input.LA(-1));}\n        )*\n        '\"'\n        {setText(buf.toString()); buf.setLength(0); System.out.println(getText());}\n    ;\n```\n\nIt's easier and more efficient to return original input string and then use a small function to rewrite the string later during a parse tree walk or whatever. But, here's how to do it from within the lexer.\n\nLexer actions don't work in the interpreter, which includes xpath and tree patterns.\n\nFor more on the argument against doing complicated things in the lexer, see the [related lexer-action issue at github](https://github.com/antlr/antlr4/issues/483#issuecomment-37326067).\n\n## Why are my keywords treated as identifiers?\n\nKeywords such as `begin` are also valid identifiers lexically and so that input is ambiguous. To resolve ambiguities, ANTLR gives precedence to the lexical rules specified first. That implies that you must put the identifier rule after all of your keywords:\n\n```\ngrammar T;\n \ndecl : DEF 'int' ID ';'\n \nDEF : 'def' ;   // ambiguous with ID as is 'int'\nID  : [a-z]+ ;\n```\n\nNotice that literal `'int'` is also physically before the ID rule and will also get precedence.\n\n## Why are there no whitespace tokens in the token stream?\n\nThe lexer is not sending white space to the parser, which means that the rewrite stream doesn't have access to the tokens either. It is because of the skip lexer command:\n\n```\nWS : [ \\t\\r\\n\\u000C]+ -> skip\n   ;\n```\n\nYou have to change all those to `-> channel(HIDDEN)` which will send them to the parser on a different channel, making them available in the token stream, but invisible to the parser."
  },
  {
    "path": "doc/faq/parse-trees.md",
    "content": "# Parse Trees\n\n## How do I get the input text for a parse-tree subtree?\n\nIn ParseTree, you have this method:\n\n```java\n/** Return the combined text of all leaf nodes. Does not get any\n * off-channel tokens (if any) so won't return whitespace and\n * comments if they are sent to parser on hidden channel.\n */\nString getText();\n```\n\nBut, you probably want this method from TokenStream:\n\n```java\n/**\n * Return the text of all tokens in the source interval of the specified\n * context. This method behaves like the following code, including potential\n * exceptions from the call to {@link #getText(Interval)}, but may be\n * optimized by the specific implementation.\n *\n * <p>If {@code ctx.getSourceInterval()} does not return a valid interval of\n * tokens provided by this stream, the behavior is unspecified.</p>\n *\n * <pre>\n * TokenStream stream = ...;\n * String text = stream.getText(ctx.getSourceInterval());\n * </pre>\n *\n * @param ctx The context providing the source interval of tokens to get\n * text for.\n * @return The text of all tokens within the source interval of {@code ctx}.\n */\npublic String getText(RuleContext ctx);\n```\n\nThat is, do this:\n\n```\nmytokens.getText(mySubTree);\n```\n\n## What if I need ASTs not parse trees for a compiler, for example?\n\nFor writing a compiler, either generate [LLVM-type static-single-assignment](http://llvm.org/docs/LangRef.html) form or construct an AST from the parse tree using a listener or visitor. Or, use actions in grammar, turning off auto-parse-tree construction.\n\n## When do I use listener/visitor vs XPath vs Tree pattern matching?\n\n### XPath\n\nXPath works great when you need to find specific nodes, possibly in certain contexts. The context is limited to the parents on the way to the root of the tree. For example, if you want to find all ID nodes, use path `//ID`. If you want all variable declarations, you might use path `//vardecl`.  If you only want fields declarations, then you can use some context information via path `/classdef/vardecl`, which would only find vardecls that are children of class definitions. You can merge the results of multiple XPath `findAll()`s simulating a set union for XPath. The only caveat is that the order from the original tree is not preserved when you union multiple `findAll()` sets.\n\n### Tree pattern matching\n\nUse tree pattern matching when you want to find specific subtree structures such as all assignments to 0 using pattern `x = 0;`.  (Recall that these are very convenient because you specify the tree structure in the concrete syntax of the language described by the grammar.) If you want to find all assignments of any kind, you can use pattern `x = <expr>;` where `<expr>` will find any expression. This works great for matching particular substructures and therefore gives you a bit more ability to specify context. I.e., instead of just finding all identifiers, you can find all identifiers on the left hand side of an expression.\n\n### Listeners/Visitors\n\nUsing the listener or visitor interfaces give you the most power but require implementing more methods. It might be more challenging to discover the emergent behavior of the listener than a simple tree pattern matcher that says *go find me X under node Y*.\n\nListeners are great when you want to visit many nodes in a tree.\n\nListeners allow you to compute and save context information necessary for processing at various nodes. For example, when building a symbol table manager for a compiler or translator, you need to compute symbol scopes such as globals, class, function, and code block. When you enter a class or function, you push a new scope and then pop it when you exit that class or function. When you see a symbol, you need to define it or look it up in the proper scope. By having enter/exit listener functions push and pop scopes, listener functions for defining variables simply say something like:\n\n```java\nscopeStack.peek().define(new VariableSymbol(\"foo\"))\n```\n\nThat way each listener function does not have to compute its appropriate scope.\n\nExamples: [DefScopesAndSymbols.java](https://github.com/mantra/compiler/blob/master/src/java/mantra/semantics/DefScopesAndSymbols.java) and [SetScopeListener.java](https://github.com/mantra/compiler/blob/master/src/java/mantra/semantics/SetScopeListener.java) and [VerifyListener.java](https://github.com/mantra/compiler/blob/master/src/java/mantra/semantics/VerifyListener.java)\n"
  },
  {
    "path": "doc/faq/translation.md",
    "content": "# Translation\n\n## ASTs vs parse trees\n\nI used to do specialized AST (**abstract** syntax tree) nodes rather than (concrete) parse trees because I used to think more about compilation and generating bytecode/assembly code. When I started thinking more about translation, I started using parse trees. For v4, I realized that I did mostly translation.  I guess what I'm saying is that maybe parse trees are not as good as ASTs for generating bytecodes. Personally, I would rather see `(+ 3 4)` rather than `(expr 3 + 4)` for generating byte codes, but it's not the end of the world. (*Can someone fill this in?*)\n\n## Decoupling input walking from output generation\n\nI suggest creating an intermediate model that represents your output. You walk the parse tree to collect information and create your model. Then, you could almost certainly automatically walk this internal model to generate output based upon stringtemplates that match the class names of the internal model. In other words, define a special `IFStatement` object that has all of the fields you want and then create them as you walk the parse tree. This decoupling of the input from the output is very powerful. Just because we have a parse tree listener doesn't mean that the parse tree itself is necessarily the best data structure to hold all information necessary to generate code. Imagine a situation where the output is the exact reverse of the input. In that case, you really want to walk the input just to collect data. Generating output should be driven by the internal model not the way it was represented in the input."
  },
  {
    "path": "doc/getting-started.md",
    "content": "# Getting Started with ANTLR v4\n\nHi and welcome to the version 4 release of ANTLR! See [Why do we need ANTLR v4?](faq/general.md) and the [preface of the ANTLR v4 book](http://media.pragprog.com/titles/tpantlr2/preface.pdf).\n\n## Getting started the easy way using antlr4-tools\n\nTo play around with ANTLR without having to worry about installing it and the Java needed to execute it, use [antlr4-tools](https://github.com/antlr/antlr4-tools). The only requirement is Python3, which is typically installed on all developer machines on all operating systems. (See below for Windows issue.)\n\n```bash\n$ pip install antlr4-tools\n```\n\nThat command creates `antlr4` and `antlr4-parse` executables that, if necessary, will download and install Java 11 plus the latest ANTLR jar:\n\n```bash\n$ antlr4 \nDownloading antlr4-4.13.2-complete.jar\nANTLR tool needs Java to run; install Java JRE 11 yes/no (default yes)? y\nInstalled Java in /Users/parrt/.jre/jdk-11.0.15+10-jre; remove that dir to uninstall\nANTLR Parser Generator  Version 4.13.2\n -o ___              specify output directory where all output is generated\n -lib ___            specify location of grammars, tokens files\n...\n```\n\nLet's play with a simple grammar:\n\n```\ngrammar Expr;\t\t\nprog:\texpr EOF ;\nexpr:\texpr ('*'|'/') expr\n    |\texpr ('+'|'-') expr\n    |\tINT\n    |\t'(' expr ')'\n    ;\nNEWLINE : [\\r\\n]+ -> skip;\nINT     : [0-9]+ ;\n```\n\n### Windows-specific issues\n\nOn 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).\n\n\n1. Go to the Microsoft Store\n2. Search in Microsoft Store for Python\n3. Select the newest version of Python (3.11).\n4. 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.\n5. Open a \"cmd\" terminal.\n6. You can now type \"python\" and \"pip\", and \"pip install antlr4-tools\". 7. Unfortunately, it does not add that to the search path.\n7. 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.\n8. Or, you can set up an alias to antlr4.exe on that path.\n\nThe 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.\n\n### Try parsing with a sample grammar\n\nTo parse and get the parse tree in text form, use:\n\n```bash\n$ antlr4-parse Expr.g4 prog -tree\n10+20*30\n^D\n(prog:1 (expr:2 (expr:3 10) + (expr:1 (expr:3 20) * (expr:3 30))) <EOF>)\n```\n(Note: `^D` means control-D and indicates \"end of input\" on Unix; use `^Z` on Windows.)\n\nHere's how to get the tokens and trace through the parse:\n\n```bash\n$ antlr4-parse Expr.g4 prog -tokens -trace\n10+20*30\n^D\n[@0,0:1='10',<INT>,1:0]\n[@1,2:2='+',<'+'>,1:2]\n[@2,3:4='20',<INT>,1:3]\n[@3,5:5='*',<'*'>,1:5]\n[@4,6:7='30',<INT>,1:6]\n[@5,9:8='<EOF>',<EOF>,2:0]\nenter   prog, LT(1)=10\nenter   expr, LT(1)=10\nconsume [@0,0:1='10',<8>,1:0] rule expr\nenter   expr, LT(1)=+\nconsume [@1,2:2='+',<3>,1:2] rule expr\nenter   expr, LT(1)=20\nconsume [@2,3:4='20',<8>,1:3] rule expr\nenter   expr, LT(1)=*\nconsume [@3,5:5='*',<1>,1:5] rule expr\nenter   expr, LT(1)=30\nconsume [@4,6:7='30',<8>,1:6] rule expr\nexit    expr, LT(1)=<EOF>\nexit    expr, LT(1)=<EOF>\nexit    expr, LT(1)=<EOF>\nconsume [@5,9:8='<EOF>',<-1>,2:0] rule prog\nexit    prog, LT(1)=<EOF>\n```\n\nHere's how to get a visual tree view:\n\n```bash\n$ antlr4-parse Expr.g4 prog -gui\n10+20*30\n^D\n```\n\nThe following will pop up in a Java-based GUI window:\n\n<img src=\"https://github.com/antlr/antlr4-tools/blob/master/images/parse-tree.png?raw=true\" width=\"300\">\n\n### Generating parser code\n\nThe previous section used a built-in ANTLR interpreter but typically you will ask ANTLR to generate code in the language used by your project (there are about 10 languages to choose from as of 4.11).  Here's how to generate Java code from a grammar:\n\n```bash\n$ antlr4 Expr.g4\n$ ls Expr*.java\nExprBaseListener.java  ExprLexer.java         ExprListener.java      ExprParser.java\n```\n\nAnd, here's how to generate C++ code from the same grammar:\n\n```bash\n$ antlr4 -Dlanguage=Cpp Expr.g4\n$ ls Expr*.cpp Expr*.h\nExprBaseListener.cpp  ExprLexer.cpp         ExprListener.cpp      ExprParser.cpp\nExprBaseListener.h    ExprLexer.h           ExprListener.h        ExprParser.h\n```\n\n## Installation\n\nANTLR is really two things: a tool written in Java that translates your grammar to a parser/lexer in Java (or other target language) and the runtime library needed by the generated parsers/lexers. Even if you are using the ANTLR Intellij plug-in or ANTLRWorks to run the ANTLR tool, the generated code will still need the runtime library. \n\nThe first thing you should do is probably download and install a development tool plug-in. Even if you only use such tools for editing, they are great. Then, follow the instructions below to get the runtime environment available to your system to run generated parsers/lexers.  In what follows, I talk about antlr-4.13.2-complete.jar, which has the tool and the runtime and any other support libraries (e.g., ANTLR v4 is written in v3).\n\nIf you are going to integrate ANTLR into your existing build system using mvn, ant, or want to get ANTLR into your IDE such as eclipse or intellij, see [Integrating ANTLR into Development Systems](https://github.com/antlr/antlr4/blob/master/doc/IDEs.md).\n\n### UNIX\n\n0. Install Java (version 11 or higher)\n1. Download\n```\n$ cd /usr/local/lib\n$ curl -O https://www.antlr.org/download/antlr-4.13.2-complete.jar\n```\nOr just download in browser from website:\n    [https://www.antlr.org/download.html](https://www.antlr.org/download.html)\nand put it somewhere rational like `/usr/local/lib`.\n\nif you are using lower version jdk, just download from [website download](https://github.com/antlr/website-antlr4/tree/gh-pages/download) for previous version, and antlr version before 4.13.2 support jdk 1.8  \n\n2. Add `antlr-4.13.2-complete.jar` to your `CLASSPATH`:\n```\n$ export CLASSPATH=\".:/usr/local/lib/antlr-4.13.2-complete.jar:$CLASSPATH\"\n```\nIt's also a good idea to put this in your `.bash_profile` or whatever your startup script is.\n\n3. Create aliases for the ANTLR Tool, and `TestRig`.\n```\n$ alias antlr4='java -Xmx500M -cp \"/usr/local/lib/antlr-4.13.2-complete.jar:$CLASSPATH\" org.antlr.v4.Tool'\n$ alias grun='java -Xmx500M -cp \"/usr/local/lib/antlr-4.13.2-complete.jar:$CLASSPATH\" org.antlr.v4.gui.TestRig'\n```\n\n### WINDOWS\n\n(*Thanks to Graham Wideman*)\n\n0. Install Java (version 1.7 or higher)\n1. Download antlr-4.13.2-complete.jar (or whatever version) from [https://www.antlr.org/download.html](https://www.antlr.org/download.html)\nSave to your directory for 3rd party Java libraries, say `C:\\Javalib`\n2. Add `antlr-4.13.2-complete.jar` to CLASSPATH, either:\n  * Permanently: Using System Properties dialog > Environment variables > Create or append to `CLASSPATH` variable\n  * Temporarily, at command line:\n```\nSET CLASSPATH=.;C:\\Javalib\\antlr-4.13.2-complete.jar;%CLASSPATH%\n```\n3. Create short convenient commands for the ANTLR Tool, and TestRig, using batch files or doskey commands:\n  * Batch files (in directory in system PATH) antlr4.bat and grun.bat\n```\njava org.antlr.v4.Tool %*\n```\n```\n@ECHO OFF\nSET TEST_CURRENT_DIR=%CLASSPATH:.;=%\nif \"%TEST_CURRENT_DIR%\" == \"%CLASSPATH%\" ( SET CLASSPATH=.;%CLASSPATH% )\n@ECHO ON\njava org.antlr.v4.gui.TestRig %*\n```\n  * Or, use doskey commands:\n```\ndoskey antlr4=java org.antlr.v4.Tool $*\ndoskey grun =java org.antlr.v4.gui.TestRig $*\n```\n\n### Testing the installation\n\nEither launch org.antlr.v4.Tool directly:\n\n```\n$ java org.antlr.v4.Tool\nANTLR Parser Generator Version 4.13.2\n-o ___ specify output directory where all output is generated\n-lib ___ specify location of .tokens files\n...\n```\n\nor use -jar option on java:\n\n```\n$ java -jar /usr/local/lib/antlr-4.13.2-complete.jar\nANTLR Parser Generator Version 4.13.2\n-o ___ specify output directory where all output is generated\n-lib ___ specify location of .tokens files\n...\n```\n\n## A First Example\n\nIn a temporary directory, put the following grammar inside file Hello.g4:\nHello.g4\n\n```\n// Define a grammar called Hello\ngrammar Hello;\nr  : 'hello' ID ;         // match keyword hello followed by an identifier\nID : [a-z]+ ;             // match lower-case identifiers\nWS : [ \\t\\r\\n]+ -> skip ; // skip spaces, tabs, newlines\n```\n\nThen run ANTLR the tool on it:\n\n```\n$ cd /tmp\n$ antlr4 Hello.g4\n$ javac Hello*.java\n```\n\nNow test it:\n\n```\n$ grun Hello r -tree\n(Now enter something like the string below)\nhello parrt\n(now,do:)\n^D\n(The output:)\n(r hello parrt)\n(That ^D means EOF on unix; it's ^Z in Windows.) The -tree option prints the parse tree in LISP notation.\nIt's nicer to look at parse trees visually.\n$ grun Hello r -gui\nhello parrt\n^D\n```\n\nThat pops up a dialog box showing that rule `r` matched keyword `hello` followed by identifier `parrt`.\n\n![](images/hello-parrt.png)\n\n## Book source code\n\nThe book has lots and lots of examples that should be useful too. You can download them here for free:\n\n[ANTLR reference book examples in Java](https://media.pragprog.com/titles/tpantlr2/code/tpantlr2-code.zip)<br>\n[ANTLR reference book examples in C#](https://github.com/Philippe-Laval/tpantlr2)\n\n\n[Language implementation patterns book examples in Java](https://media.pragprog.com/titles/tpdsl/code/tpdsl-code.zip)<br>\n[Language implementation patterns book examples in C#](https://github.com/Philippe-Laval/tpdsl)\n\nAlso, there is a large collection of grammars for v4 at github:\n\n[https://github.com/antlr/grammars-v4](https://github.com/antlr/grammars-v4)\n"
  },
  {
    "path": "doc/go-changes.md",
    "content": "# Changes to the Go Runtime over time\n\n## v4.12.0 to v4.13.0\n\nStrictly speaking, if ANTLR was a go only project following [SemVer](https://semver.org/) release v4.13.0 would be\nat least a minor version change and arguably a bump to v5. However, we must follow the ANTLR conventions here or the\nrelease numbers would quickly become confusing. I apologize for being unable to follow the Go release rules absolutely \nto the letter.\n\nThere are a lot of changes and improvements in this release, but only the change of repo holding the runtime code,\nand possibly the removal of interfaces will cause any code changes. There are no breaking changes to the runtime\ninterfaces.\n\nANTLR Go Maintainer: [Jim Idle](https://github.com/jimidle) - Email:  [jimi@idle.ws](mailto:jimi@idle.ws)\n\n### Code Relocation\n\nFor complicated reasons, including not breaking the builds of some users who use a monorepo and eschew modules, as well\nas not making substantial changes to the internal test suite, the Go runtime code will continue to be maintained in\nthe main ANTLR4 repo `antlr/antlr4`. If you wish to contribute changes to the Go runtime code, please continue to submit \nPRs to this main repo, against the `dev` branch.\n\nThe code located in the main repo at about the depth of the Mariana Trench, means that the go tools cannot reconcile\nthe module correctly. After some debate, it was decided that we would create a dedicated release repo for the Go runtime\nso that it will behave exactly as the Go tooling expects. This repo is auto-maintained and keeps both the dev and master\nbranches up to date.\n\nHenceforth, all future projects using the ANTLR Go runtime, should import as follows:\n\n```go\nimport (\n    \"github.com/antlr4-go/antlr/v4\"\n    )\n```\n\nAnd use the command:\n\n```shell\ngo get github.com/antlr4-go/antlr\n```\n\nTo get the module - `go mod tidy` is probably the best way once imports have been changed. \n\nPlease note that there is no longer any source code kept in the ANTLR repo under `github.com/antlr/antlr4/runtime/Go/antlr`.\nIf you are using the code without modules, then sync the code from the new release repo.\n\n### Documentation\n\nPrior to this release, the godocs were essentially unusable as the go doc code was essentially copied without\nchange, from teh Java runtime. The godocs are now properly formatted for Go and pkg.dev.\n\nPlease feel free to raise an issue if you find any remaining mistakes. Or submit a PR (remember - not to the new repo).\nIt is expected that it might take a few iterations to get the docs 100% squeaky clean.\n\n### Removal of Unnecessary Interfaces\n\nThe Go runtime was originally produced as almost a copy of the Java runtime but with go syntax. This meant that everything \nhad an interface. There is no need to use interfaces in Go if there is only ever going to be one implementation of\nsome struct and its methods. Interfaces cause an extra deference at runtime and are detrimental to performance if you\nare trying to squeeze out every last nanosecond, which some users will be trying to do.\n\nThis is 99% an internal refactoring of the runtime with no outside effects to the user.\n\n### Generated Recognizers Return *struct and not Interfaces\n\nThe generated recognizer code generated an interface for the parsers and lexers. As they can only be implemented by the\ngenerated code, the interfaces were removed. This is possibly the only place you may need to make a code change to\nyour driver code.\n\nIf your code looked like this:\n\n```go\nvar lexer = parser.NewMySqlLexer(nil)\nvar p = parser.NewMySqlParser(nil)\n```\n\nOr this:\n\n```go\nlexer := parser.NewMySqlLexer(nil)\np := parser.NewMySqlParser(nil)\n```\n\nThen no changes need to be made. However, fi you predeclared the parser and lexer variables with there type, such as like\nthis:\n\n```go\nvar lexer parser.MySqlLexer\nvar p parser.MySqlParser\n// ...\nlexer = parser.NewMySqlLexer(nil)\np = parser.NewMySqlParser(nil)\n```\n\nYou will need to change your variable declarations to pointers (note the introduction of the `*` below. \n\n```go\nvar lexer *parser.MySqlLexer\nvar p *parser.MySqlParser\n// ...\nlexer = parser.NewMySqlLexer(nil)\np = parser.NewMySqlParser(nil)\n```\n\nThis is the only user facing change that I can see. This change though has a very beneficial side effect in that you\nno longer need to cast the interface into a struct so that you can access methods and data within it. Any code you\nhad that needed to do that, will be cleaner and faster.\n\nThe performance improvement is worth the change and there was no tidy way for me to avoid it.\n\n### Parser Error Recovery Does Not Use Panic\n\nTHe generated parser code was again essentially trying to be Java code in disguise. This meant that every parser rule\nexecuted a `defer {}` and a `recover()`, even if there wer no outstanding parser errors. Parser errors were issued by\nissuing a `panic()`! \n\nWhile some major work has been performed in the go compiler and runtime to make `defer {}` as fast as possible, \n`recover()` is (relatively) slow as it is not meant to be used as a general error mechanism, but to recover from say\nan internal library problem if that problem can be recovered to a known state. \n\nThe generated code now stores a recognition error and a flag in the main parser struct and use `goto` to exit the\nrule instead of a `panic()`. As might be imagined, this is significantly faster through the happy path. It is also \nfaster at generating errors.\n\nThe ANTLR runtime tests do check error raising and recovery, but if you find any differences in the error handling\nbehavior of your parsers, please raise an issue. \n\n### Reduction in use of Pointers\n\nCertain internal structs, such as interval sets are small and immutable, but were being passed around as pointers\nanyway. These have been change to use copies, and resulted in significant performance increases in some cases. \nThere is more work to come in this regard.\n\n### ATN Deserialization\n\nWhen the ATN and associated structures are deserialized for the first time, there was a bug that caused a needed\noptimization to fail to be executed. This could have a significant performance effect on recognizers that were written\nin a suboptimal way (as in poorly formed grammars). This is now fixed.\n\n### Prediction Context Caching was not Working\n\nThis has a massive effect when reusing a parser for a second and subsequent run. The PredictionContextCache merely\nused memory but did not speed up subsequent executions. This is now fixed, and you should see a big difference in \nperformance when reusing a parser. This single paragraph does not do this fix justice ;) \n\n### Cumulative Performance Improvements\n\nThough too numerous to mention, there are a lot of small performance improvements, that add up in accumulation. Everything\nfrom improvements in collection performance to slightly better algorithms or specific non-generic algorithms. \n\n### Cumulative Memory Improvements\n\nThe real improvements in memory usage, allocation and garbage collection are saved for the next major release. However,\nif your grammar is well-formed and does not require almost infinite passes using ALL(*), then both memory and performance\nwill be improved with this release.\n\n### Bug Fixes\n\nOther small bug fixes have been addressed, such as potential panics in funcs that did not check input parameters. There\nare a lot of bug fixes in this release that most people were probably not aware of. All known bugs are fixed at the \ntime of release preparation.\n\n### A Note on Poorly Constructed Grammars\n\nThough I have made some significant strides on improving the performance of poorly formed grammars, those that are\nparticularly bad will see much less of an incremental improvement compared to those that are fairly well-formed.\n\nThis is deliberately so in this release as I felt that those people who have put in effort to optimize the form of their\ngrammar are looking for performance, where those that have grammars that parser in seconds, tens of seconds or even\nminutes, are presumed to not care about performance. \n\nA particularly good (or bad) example is the MySQL grammar in the ANTLR grammar repository (apologies to the Author \nif you read this note - this isn't an attack). Although I have improved its runtime performance\ndrastically in the Go runtime, it still takes about a minute to parse complex select statements. As it is constructed, \nthere are no magic answers. I will look in more detail at improvements for such parsers, such as not freeing any\nmemory until the parse is finished (improved 100x in experiments).\n\nThe best advice I can give is to put some effort in to the actual grammar itself. well-formed grammars will potentially\nsee some huge improvements with this release. Badly formed grammars, not so much. \n"
  },
  {
    "path": "doc/go-target.md",
    "content": "# ANTLR4 Language Target, Runtime for Go\n\n### Changes from ANTLR 4.12.0\n\nPlease see [Changes in ANTLR Go runtimes](go-changes.md), but in summary:\n  - The Go runtime is now stored in the repo `antlr4-go/antlr` - change your import, remove the old location from\n    `go.mod` and use `go get github.com/antlr4-go/antlr`\n  - There are some new `@actions` for adding to the generated import statements and recognizer structure\n  - The recognizer rules are no longer called via an interface, for performance reasons\n  - Memory usage improvements\n  - Performance improvements\n  - Documentation in true Go format\n  - Git tags now work correctly with go tools\n\n### Removal of non v4 code\n\nPrior to the  release of the v4 tagged runtime, the source code for the Go runtime module existed at\n`runtime/Go/antlr`, which is the pre-v4 version of the code, and also under `runtime/Go/antlr/v4`. If your project\nwas not using modules, you could merely sync to the latest hash in the master branch and use the code. This has changed.\n\nAs of the current release, the source code for the Go runtime module has been moved to its own repo in its own\nGitHub organization. As of now, you can still use the code without modules, but you must use the code\nin the repo at https://github.com/antlr4-go/antlr instead of the code in the main ANTLR repo.\n\nThis is for historic reasons as the code was originally written before modules were a\nthing, and the go runtime source was - and the maintainer's version still is - a part of the monorepo \nthat is `antlr/antlr4/...`.\n\nNote that I am unable to properly deprecate the go.mod in the non-V4 directory, for hte same reason that I\ncannot use tag the v4 module at this depth in the source tree. \n\nWe strongly advise you to use modules, though it is not required. See below for more information.\n\nANTLR Go Maintainer: [Jim Idle](https://github.com/jimidle) - Email:  [jimi@idle.ws](mailto:jimi@idle.ws)\n\n### First steps\n\n#### 1. Install ANTLR4\n\nSee: [The getting started guide](getting-started.md).\n\n#### 2. Get the Go ANTLR runtime\n\nEach target language for ANTLR has a runtime package for running a recognizer generated by ANTLR4. \nThe runtime provides a common set of tools for using your parser/lexer. Note that if you have existing projects and have \nyet to replace the `v1.x.x` modules with the `v4` modules, then you can skip ahead to the section *Upgrading to v4\nfrom earlier versions*\n\nThe Go runtime uses modules and has a version path of `/v4` to stay in sync with the runtime versions of all the other \nruntimes and the tool itself. \n\nSetup is the same as any other module based project:\n\n```bash\n$ cd mymodproject\n$ go mod init mymodproject\n```\n\nAfter which, you can use go get, to get the latest release version of the ANTLR v4 runtime using:\n\n```bash\ngo get github.com/antlr4-go/antlr\n```\n\nIf your project was already using the v4 runtime from the main ANTLR repo, then you can upgrade to the latest release\nby removing the `github.com/antlr/antlr4/runtime/Go/antlr/v4` reference in your module, and changing the associated\nimport in your project code. The following script may be useful in changing your imports:\n\n```shell\nfind . -type f \\\n    -name '*.go' \\\n    -exec sed -i -e 's,github.com/antlr/antlr4/runtime/Go/antlr/v4,github.com/antlr4-go/antlr/v4,g' {} \\;\n```\nNote that the import package still imports with the final path as `antlr`, so only the import statement itself needs to\nchange.\n\nIf you are already using the repo and import `github.com/antlr4-go/antlr/v4` then you can upgrade to the latest version\nusing the standard.\n\n```shell\ngo get -u github.com/antlr4-go/antlr\n```\n\nIf you have not yet upgraded existing projects to the `/v4` module path, consult the section *Upgrading to v4\nfrom earlier versions*\n\nThe ANTLR runtime has only one external transient dependency, and that is part of the go system itself:\n\n```\ngolang.org/x/exp\n```\n\nA complete list of releases can be found on [the release page](https://github.com/antlr/antlr4/releases). The Go \nruntime will be tagged using standard Go tags, so release 4.13.2 in the `antlr4-go/antlr` repo, will be tagged with \n`v4.13.2` and go get will pick that up from the ANTLR repo.\n\n#### 3. Configuring `go generate` in your project\n\nIn order to promote the use of repeatable builds, it is often useful to add the latest tool jar to your project's\nrepo and configure a `generate.sh` and `generate.go` file. You can of course globally alias the java command required to run the\ntool. Your own CI and dev environment will guide you.\n\nHere is how you can configure `go generate` for your project, assuming that you follow the general recommendation to\nplace the ANTLR grammar files in their own package in your project structure. Here is a general template as a starting point:\n\n```\n\t.\n\t├── myproject\n\t├── parser\n\t│     ├── mygrammar.g4\n\t│     ├── antlr-4.13.2-complete.jar\n\t│     ├── generate.go\n\t│     └── generate.sh\n\t├── parsing  # Generated code goes here\n\t│     └── error_listeners.go\n\t├── go.mod\n\t├── go.sum\n\t├── main.go\n\t└── main_test.go\n```\n\nMake sure that the package statement in your grammar file(s) reflects the go package the go code will be generated in.\nThe `generate.go` file then looks like this:\n\n```golang\n\tpackage parser\n\n\t//go:generate ./generate.sh\n```\n\nAnd the `generate.sh` file will look similar to this:\n\n```shell\n\t#!/bin/sh\n\n\talias antlr4='java -Xmx500M -cp \"./antlr-4.13.2-complete.jar:$CLASSPATH\" org.antlr.v4.Tool'\n\tantlr4 -Dlanguage=Go -no-visitor -package parsing *.g4\n```\n\nFrom the command line at the root of your package - the location of the `go.mod` file -  you can then simply issue the command:\n\n```shell\n\tgo generate ./...\n```\n\nIf you have not yet run a `go get`, you can now run `go mod tidy` and update your \n\n#### 4. Generate your parser manually\n\nYou use the ANTLR4 \"tool\" to generate a parser. These will reference the ANTLR runtime, installed above.\n\nSuppose you're using a UNIX system and have set up an alias for the ANTLR4 tool as described in\n[the getting started guide](getting-started.md). \n\nTo generate your go parser, you'll need to invoke:\n\n```shell\n    antlr4 -Dlanguage=Go MyGrammar.g4\n```\n\nFor a full list of antlr4 tool options, please visit the [tool documentation page](tool-options.md).\n\n### Upgrading to `/v4` from the default path\n\n*NB: While switching to new module path would normally imply that the public interface for the runtime has changed, this is\nnot actually the case - you will not need to change your existing code to upgrade. The main point of the repo change is so\nthat git tagging works with the ANTLR Go runtime and the go tools.*\n\nPrior to release v4.11.0 the Go runtime shipped with a module but the module had no version path. This meant that\nthe tags in the ANTLR repo did not work, as any tag above `v1` must refer to a matching module path. \nSo the command `go get github.com/antlr/antlr4/runtime/Go/antlr` would just bring in\nwhatever was the `HEAD` of the master branch. While this *kind of* worked, it is obviously subject to problems and does\nnot fit properly with the idiomatic ways of Go.\n\nAs of v4.13.0 the runtime code exists in its own repo, `github.com/antlr4-go/antlr`, and is correctly tagged. \nHowever, this means you need to perform a few simple actions in order to upgrade to the `/v4` path. \n\n - Firstly, make sure that you are using an ANTLR tool jar with a version number of 4.13.0 or greater.\n - Next you replace any mention of the old (default) path to ANTLR in your go source files.\n - If using modules, remove any existing reference to the ANTLR Go runtime\n - Now regenerate your grammar files either manually or using `go generate ./...` (see above)\n - Consider whether you can move to using modules in your project\n\nA quick way to replace the original module path references is to use this script from your module's base directory:\n\n```shell\nfind . -type f \\\n    -name '*.go' \\\n    -exec sed -i -e 's,github.com/antlr/antlr4/runtime/Go/antlr,github.com/antlr4-go/antlr/v4,g' {} \\;\n```\n\nAfter performing the steps above, and you are using modules issuing:\n\n```shell\ngo mod tidy\n```\nShould fix up your `go.mod` file to reference only the `v4` version of the ANTLR Go runtime:\n\n```shell\nrequire github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.13.0\n```\n\nFrom this point on, your go mod commands will work correctly with the ANTLR repo and upgrades and downgrades will work\nas you expect. As will branch version such as @dev\n\n### Referencing the Go ANTLR runtime\n\nYou can reference the go ANTLR runtime package like this:\n\n```golang\nimport \"github.com/antlr4-go/antlr/v4\"\n```\n\n### Complete example\n\nSuppose you're using the JSON grammar from https://github.com/antlr/grammars-v4/tree/master/json placed in the parser\ndirectory and have initialized your `go mod` file.\n\nThen, invoke `antlr4 -Dlanguage=Go JSON.g4`. The result of this is a collection of .go files in the `parser` directory including:\n```\njson_parser.go\njson_base_listener.go\njson_lexer.go\njson_listener.go\n```\n\nAnother common option to the ANTLR tool is `-visitor`, which generates a parse tree visitor, but we won't be doing that here. \nFor a full list of antlr4 tool options, please visit the [tool documentation page](tool-options.md).\n\nWe'll write a small main func to call the generated parser/lexer (assuming they are separate). This one writes out the \nencountered `ParseTreeContext`'s. Assuming the generated parser code is in the `parser` directory relative to this code:\n\n```golang\npackage main\n\nimport (\n\t\"github.com/antlr4-go/antlr/v4\"\n\t\"./parser\"  // Note that with modules you may not be able to use a relative immport path\n\t\"os\"\n\t\"fmt\"\n)\n\ntype TreeShapeListener struct {\n\t*parser.BaseJSONListener\n}\n\nfunc NewTreeShapeListener() *TreeShapeListener {\n\treturn new(TreeShapeListener)\n}\n\nfunc (this *TreeShapeListener) EnterEveryRule(ctx antlr.ParserRuleContext) {\n\tfmt.Println(ctx.GetText())\n}\n\nfunc main() {\n\tinput, _ := antlr.NewFileStream(os.Args[1])\n\tlexer := parser.NewJSONLexer(input)\n\tstream := antlr.NewCommonTokenStream(lexer,0)\n\tp := parser.NewJSONParser(stream)\n\tp.AddErrorListener(antlr.NewDiagnosticErrorListener(true))\n\ttree := p.Json()\n\tantlr.ParseTreeWalkerDefault.Walk(NewTreeShapeListener(), tree)\n}\n```\n\nFix up your `go.mod` file:\n\n```shell\ngo mod tidy\n```\n\nThis one expects the input to be passed on the command line:\n\n```\ngo run test.go input\n```\n\nThe output is:\n\n```\n{\"a\":1}\n{\"a\":1}\n\"a\":1\n1\n```\n"
  },
  {
    "path": "doc/grammars.md",
    "content": "# Grammar Structure\n\nA grammar is essentially a grammar declaration followed by a list of rules, but has the general form:\n\n```\n/** Optional javadoc style comment */\ngrammar Name; ①\noptions {...}\nimport ... ;\n \t\ntokens {...}\nchannels {...} // lexer only\n@actionName {...}\n \t \nrule1 // parser and lexer rules, possibly intermingled\n...\nruleN\n```\n\nThe file name containing grammar `X` must be called `X.g4`. You can specify options, imports, token specifications, and actions in any order. There can be at most one each of options, imports, and token specifications. All of those elements are optional except for the header ① and at least one rule. Rules take the basic form:\n\n```\nruleName : alternative1 | ... | alternativeN ;\n```\n\nParser rule names must start with a lowercase letter and lexer rules must start with a capital letter.\n\nGrammars defined without a prefix on the `grammar` header are combined grammars that can contain both lexical and parser rules. To make a parser grammar that only allows parser rules, use the following header.\n\n```\nparser grammar Name;\n...\n```\n\nAnd, naturally, a pure lexer grammar looks like this:\n\n```\nlexer grammar Name;\n...\n```\n\nOnly lexer grammars can contain `mode` specifications.\n\nOnly lexer grammars can contain custom channels specifications\n\n```\nchannels {\n  WHITESPACE_CHANNEL,\n  COMMENTS_CHANNEL\n}\n```\n\nThose channels can then be used like enums within lexer rules:\n\n```\nWS : [ \\r\\t\\n]+ -> channel(WHITESPACE_CHANNEL) ;\n```\n\nSections 15.5, [Lexer Rules](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference) and Section 15.3, [Parser Rules](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference) contain details on rule syntax. Section 15.8, Options describes grammar options and Section 15.4, Actions and Attributes has information on grammar-level actions.\n\n## Grammar Imports\n\nGrammar `imports` let you break up a grammar into logical and reusable chunks, as we saw in [Importing Grammars](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference). ANTLR treats imported grammars very much like object-oriented programming languages treat superclasses. A grammar inherits all of the rules, tokens specifications, and named actions from the imported grammar. Rules in the “main grammar” override rules from imported grammars to implement inheritance.\n\nThink of `import` as more like a smart include statement (which does not include rules that are already defined). The result of all imports is a single combined grammar; the ANTLR code generator sees a complete grammar and has no idea there were imported grammars.\n\nTo process a main grammar, the ANTLR tool loads all of the imported grammars into subordinate grammar objects. It then merges the rules, token types, and named actions from the imported grammars into the main grammar. In the diagram below, the grammar on the right illustrates the effect of grammar `MyELang` importing grammar `ELang`.\n\n<img src=images/combined.png width=400>\n\n`MyELang` inherits rules `stat`, `WS`, and `ID`, but overrides rule `expr` and adds `INT`. Here’s a sample build and test run that shows `MyELang` can recognize integer expressions whereas the original `ELang` can’t. The third, erroneous input statement triggers an error message that also demonstrates the parser was looking for `MyELang`’s expr not `ELang`’s.\n\n```\n$ antlr4 MyELang.g4\n$ javac MyELang*.java\n$ grun MyELang stat\n=> \t34;\n=> \ta;\n=> \t;\n=> \tEOF\n<= \tline 3:0 extraneous input ';' expecting {INT, ID}\n```\n\nIf there are modes in the main grammar or any of the imported grammars then the import process will import those modes and merge their rules where they are not overridden. In the event any mode becomes empty as all its\nrules have been overridden by rules outside the mode this mode will be discarded.\n\nIf there were any `tokens` specifications, the main grammar would merge the token sets. If there were any `channel` specifications, the main grammar would merge the channel sets. Any named actions such as `@members` would be merged. In general, you should avoid named actions and actions within rules in imported grammars since that limits their reuse. ANTLR also ignores any options in imported grammars.\n\nImported grammars can also import other grammars. ANTLR pursues all imported grammars in a depth-first fashion. If two or more imported grammars define rule `r`, ANTLR chooses the first version of `r` it finds. In the following diagram, ANTLR examines grammars in the following order `Nested`, `G1`, `G3`, `G2`.\n\n<img src=images/nested.png width=350>\n\n`Nested` includes the `r` rule from `G3` because it sees that version before the `r` in `G2`.\n\nNot every kind of grammar can import every other kind of grammar:\n\n* Lexer grammars can import lexers, including lexers containing modes.\n* Parsers can import parsers.\n* Combined grammars can import parsers or lexers without modes.\n\nANTLR adds imported rules to the end of the rule list in a main lexer grammar. That means lexer rules in the main grammar get precedence over imported rules. For example, if a main grammar defines rule `IF : 'if' ;` and an imported grammar defines rule `ID : [a-z]+ ;` (which also recognizes `if`), the imported `ID` won’t hide the main grammar’s `IF` token definition.\n\n## Tokens Section\n\nThe purpose of the `tokens` section is to define token types needed by a grammar for which there is no associated lexical rule. The basic syntax is:\n\n```\ntokens { Token1, ..., TokenN }\n```\n\nMost of the time, the tokens section is used to define token types needed by actions in the grammar as shown in Section 10.3, [Recognizing Languages whose Keywords Aren’t Fixed](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference):\n\n```\n// explicitly define keyword token types to avoid implicit definition warnings\ntokens { BEGIN, END, IF, THEN, WHILE }\n \n@lexer::members { // keywords map used in lexer to assign token types\nMap<String,Integer> keywords = new HashMap<String,Integer>() {{\n\tput(\"begin\", KeywordsParser.BEGIN);\n\tput(\"end\", KeywordsParser.END);\n\t...\n}};\n}\n```\n\nThe `tokens` section really just defines a set of tokens to add to the overall set.\n\n```\n$ cat Tok.g4\ngrammar Tok;\ntokens { A, B, C }\na : X ;\n$ antlr4 Tok.g4\nwarning(125): Tok.g4:3:4: implicit definition of token X in parser\n$ cat Tok.tokens\nA=1\nB=2\nC=3\nX=4\n```\n\n## Actions at the Grammar Level\n\nCurrently there are only two defined named actions (for the Java target) used outside of grammar rules: `header` and `members`. The former injects code into the generated recognizer class file, before the recognizer class definition, and the latter injects code into the recognizer class definition, as fields and methods.\n\nFor combined grammars, ANTLR injects the actions into both the parser and the lexer. To restrict an action to the generated parser or lexer, use `@parser::name` or `@lexer::name`.\n\nHere’s an example where the grammar specifies a package for the generated code:\n\n```\ngrammar Count;\n \n@header {\npackage foo;\n}\n \n@members {\nint count = 0;\n}\n \nlist\n@after {System.out.println(count+\" ints\");}\n: INT {count++;} (',' INT {count++;} )*\n;\n \nINT : [0-9]+ ;\nWS : [ \\r\\t\\n]+ -> skip ;\n```\n\nThe grammar itself then should be in directory `foo` so that ANTLR generates code in that same `foo` directory (at least when not using the `-o` ANTLR tool option):\n\n```\n$ cd foo\n$ antlr4 Count.g4 # generates code in the current directory (foo)\n$ ls\nCount.g4\t\tCountLexer.java\tCountParser.java\nCount.tokens\tCountLexer.tokens\nCountBaseListener.java CountListener.java\n$ javac *.java\n$ cd ..\n$ grun foo.Count list\n=> \t9, 10, 11\n=> \tEOF\n<= \t3 ints\n```\n\nThe Java compiler expects classes in package `foo` to be in directory `foo`.\n"
  },
  {
    "path": "doc/index.md",
    "content": "# ANTLR 4 Documentation\n\nPlease check [Frequently asked questions (FAQ)](faq/index.md) before asking questions on stackoverflow or antlr-discussion list.\n\nNotes:\n<ul>\n<li>To add to or improve this documentation, <a href=https://help.github.com/articles/fork-a-repo>fork</a> the <a href=https://github.com/antlr/antlr4>antlr/antlr4 repo</a> then update this `doc/index.md` or file(s) in that directory.  Submit a <a href=https://help.github.com/articles/creating-a-pull-request>pull request</a> to get your changes incorporated into the main repository. Do not mix code and documentation updates in the sample pull request. <b>You must sign the contributors.txt certificate of origin with your pull request if you've not done so before.</b></li>\n\n<li>Copyright © 2012, The Pragmatic Bookshelf.  Pragmatic Bookshelf grants a nonexclusive, irrevocable, royalty-free, worldwide license to reproduce, distribute, prepare derivative works, and otherwise use this contribution as part of the ANTLR project and associated documentation.</li>\n\n<li>Much of this text was copied with permission from the <a href=http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference>The Definitive ANTLR 4 Reference</a>, though it is being morphed over time as the tool changes.</li>\n</ul>\n\nLinks in the documentation refer to various sections of the book but have been redirected to the general book page on the publisher's site. There are two excerpts on the publisher's website that might be useful to you without having to purchase the book: [Let's get Meta](http://media.pragprog.com/titles/tpantlr2/picture.pdf) and [Building a Translator with a Listener](http://media.pragprog.com/titles/tpantlr2/listener.pdf). You should also consider reading the following books (the vid describes the reference book):\n\n<a href=\"\"><img src=images/tpantlr2.png width=120></a>\n<a href=\"\"><img src=images/tpdsl.png width=120></a>\n<a href=\"https://www.youtube.com/watch?v=OAoA3E-cyug\"><img src=images/teronbook.png width=250></a>\n\nThis documentation is a reference and summarizes grammar syntax and the key semantics of ANTLR grammars. The source code for all examples in the book, not just this chapter, are free at the publisher's website. The following video is a general tour of ANTLR 4 and includes a description of how to use parse tree listeners to process Java files easily:\n\n<a href=\"https://vimeo.com/59285751\"><img src=images/tertalk.png width=200></a>\n\nFor those using Java, here's a great [set of ANTLR in Intellij notes](https://docs.google.com/document/d/1gQ2lsidvN2cDUUsHEkT05L-wGbX5mROB7d70Aaj3R64/edit#heading=h.xr0jj8vcdsgc) by Andreas Stefik.\n\n## Sections\n\n* [Getting Started with ANTLR v4](getting-started.md)\n\n* [Grammar Lexicon](lexicon.md)\n\n* [Grammar Structure](grammars.md)\n\n* [Parser Rules](parser-rules.md)\n\n* [Left-recursive rules](left-recursion.md)\n\n* [Actions and Attributes](actions.md)\n\n* [Lexer Rules](lexer-rules.md)\n\n* [Wildcard Operator and Nongreedy Subrules](wildcard.md)\n\n* [Parse Tree Listeners](listeners.md)\n\n* [Parse Tree Matching and XPath](tree-matching.md)\n\n* [Semantic Predicates](predicates.md)\n\n* [Options](options.md)\n\n* [ANTLR Tool Command Line Options](tool-options.md)\n\n* [Runtime Libraries and Code Generation Targets](targets.md)\n\n* [Unicode U+FFFF, U+10FFFF character streams](unicode.md)\n\n* [Parsing binary streams](parsing-binary-files.md)\n\n* [Parser and lexer interpreters](interpreters.md)\n\n* [Writing target-agnostic grammars](target-agnostic-grammars.md)\n\n* [Resources](resources.md)\n\n# Building / releasing ANTLR itself\n\n* [Building ANTLR itself](building-antlr.md)\n\n* [Contributing to ANTLR](/CONTRIBUTING.md)\n\n* [Cutting an ANTLR Release](releasing-antlr.md)\n\n* [ANTLR project unit tests](antlr-project-testing.md)\n\n* [Creating an ANTLR Language Target](creating-a-language-target.md)\n"
  },
  {
    "path": "doc/interpreters.md",
    "content": "# Parser and Lexer Interpreters\n\n*Since ANTLR 4.2*\n\nFor small parsing tasks it is sometimes convenient to use ANTLR in interpreted mode, rather than generating a parser in a particular target, compiling it and running it as part of your application. Here's some sample code that creates lexer and parser Grammar objects and then creates interpreters. Once we have a ParserInterpreter, we can use it to parse starting in any rule we like, given a rule index (which the grammar + the parser can provide).\n\n## Action Code\n\nSince interpreters don't use generated parsers + lexers they cannot execute any action code (including predicates). That means the interpreter runs as if there were no predicates at all. If your grammar requires action code in order to parse correctly you will not be able to test it using this approach.\n\n## Java Target Interpreter Setup\n\n```java\nLexerGrammar lg = new LexerGrammar(\n    \"lexer grammar L;\\n\" +\n    \"A : 'a' ;\\n\" +\n    \"B : 'b' ;\\n\" +\n    \"C : 'c' ;\\n\");\nGrammar g = new Grammar(\n    \"parser grammar T;\\n\" +\n    \"s : (A|B)* C ;\\n\",\n    lg);   \nLexerInterpreter lexEngine =\n    lg.createLexerInterpreter(new ANTLRInputStream(input));\nCommonTokenStream tokens = new CommonTokenStream(lexEngine);\nParserInterpreter parser = g.createParserInterpreter(tokens);\nParseTree t = parser.parse(g.rules.get(startRule).index);\n```\n\nYou can also load combined grammars from a file:\n\n```java\npublic static ParseTree parse(String fileName,\n                              String combinedGrammarFileName,\n                              String startRule)\n    throws IOException\n{\n    final Grammar g = Grammar.load(combinedGrammarFileName);\n    LexerInterpreter lexEngine = g.createLexerInterpreter(CharStreams.fromPath(Paths.get(fileName)));\n    CommonTokenStream tokens = new CommonTokenStream(lexEngine);\n    ParserInterpreter parser = g.createParserInterpreter(tokens);\n    ParseTree t = parser.parse(g.getRule(startRule).index);\n    System.out.println(\"parse tree: \"+t.toStringTree(parser));\n    return t;\n}\n```\n\nThen:\n\n```java\nParseTree t = parse(\"T.om\",\n                    MantraGrammar,\n                    \"compilationUnit\");\n```\n \nTo load separate lexer/parser grammars, do this:\n\n```java\npublic static ParseTree parse(String fileNameToParse,\n                              String lexerGrammarFileName,\n                              String parserGrammarFileName,\n                              String startRule)\n    throws IOException\n{\n    final LexerGrammar lg = (LexerGrammar) Grammar.load(lexerGrammarFileName);\n    final Grammar pg = Grammar.load(parserGrammarFileName, lg);\n    CharStream input = CharStreams.fromPath(Paths.get(fileNameToParse));\n    LexerInterpreter lexEngine = lg.createLexerInterpreter(input);\n    CommonTokenStream tokens = new CommonTokenStream(lexEngine);\n    ParserInterpreter parser = pg.createParserInterpreter(tokens);\n    ParseTree t = parser.parse(pg.getRule(startRule).index);\n    System.out.println(\"parse tree: \" + t.toStringTree(parser));\n    return t;\n}\n```\n\nThen:\n\n```java\nParseTree t = parse(fileName, XMLLexerGrammar, XMLParserGrammar, \"document\");\n```\n\nThis is also how we will integrate instantaneous parsing into ANTLRWorks2 and development environment plug-ins.\n\nSee [TestParserInterpreter.java](../tool-testsuite/test/org/antlr/v4/test/tool/TestParserInterpreter.java).\n\n## Non-Java Target Interpreter Setup\nThe ANTLR4 runtimes do not contain any grammar parsing classes (they are in the ANTLR4 tool  jar). Hence we cannot use `LexerGrammar` and `Grammar` to parse grammars for the interpreter. Instead we directly instantiate `LexerInterpreter` and `ParserInterpreter` objects. They require some data (namely symbol information and the ATNs) which only the ANTLR4 tool can give us. However, on each generation run ANTLR not only produces your parser + lexer files but also interpreter data files (*.interp) which contain all you need to feed the interpreters.\n\nA support class (`InterpreterDataReader`) is used to load the data for your convenience, which makes this very easy to use. Btw. even the Java target go this route instead of using the non-runtime classes `Grammar` and `LexerGrammar`. Sometimes it might not be feasible to use the tool jar for whatever reason.\n\nHere's how the setup looks like (C++ example):\n\n```cpp\n/**\n * sourceFileName - name of the file with content to parse\n * lexerName - the name of your lexer (arbitrary, that's what is used in error messages)\n * parserName - ditto for the parser\n * lexerDataFileName - the lexer interpeter data file name (e.g. `<path>/ExprLexer.interp`)\n * parserDataFileName - ditto for the parser (e.g. `<path>/Expr.interp`)\n * startRule - the name of the rule to start parsing at\n */\nvoid parse(std::string const& sourceFileName,\n  std::string const& lexerName, std::string const& parserName,\n  std::string const& lexerDataFileName, std::string const& parserDataFileName,\n  std::string const& startRule) {\n  \n    InterpreterData lexerData = InterpreterDataReader::parseFile(lexerDataFileName);\n    InterpreterData parserData = InterpreterDataReader::parseFile(parserDataFileName);\n\n    ANTLRFileStream input(sourceFileName);\n    LexerInterpreter lexEngine(lexerName, lexerData.vocabulary, lexerData.ruleNames,\n      lexerData.channels, lexerData.modes, lexerData.atn, &input);\n    CommonTokenStream tokens(&lexEngine);\n\n    /* Remove comment to print the tokens.\n    tokens.fill();\n    std::cout << \"INPUT:\" << std::endl;\n    for (auto token : tokens.getTokens()) {\n      std::cout << token->toString() << std::endl;\n    }\n    */\n\n    ParserInterpreter parser(parserName, parserData.vocabulary, parserData.ruleNames,\n      parserData.atn, &tokens);\n    tree::ParseTree *tree = parser.parse(parser.getRuleIndex(startRule));\n\n    std::cout << \"parse tree: \" << tree->toStringTree(&parser) << std::endl;\n}\n```\n"
  },
  {
    "path": "doc/java-target.md",
    "content": "# Java\n\n## Development environments\n\n### Intellij\n\nThere is a very complete and useful plug-in for intellij 12-14, you can grab at the [download page](https://plugins.jetbrains.com/plugin/7358?pr=). Check the [plugin readme](https://github.com/antlr/intellij-plugin-v4) for feature set. Just go to the preferences and click on the \"Install plug-in from disk...\" button from this dialog box:\n\n<img src=\"images/idea-prefs.png\">\n\nSelect the intellij-plugin-1.x.zip (or whatever version) file and hit okay or apply. It will ask you to restart the IDE. If you look at the plug-ins again, you will see:\n\n<img src=\"images/idea-prefs-after-install.png\">\n\nAlso, I have prepared a [video](https://youtu.be/eW4WFgRtFeY) that will help you generate grammars and so on using ANTLR v4 in Intellij (w/o the plugin).\n\n### Eclipse\n\nEdgar Espina has created an [eclipse plugin for ANTLR v4](https://marketplace.eclipse.org/content/antlr-ide). Features: Advanced Syntax Highlighting, Automatic Code Generation (on save), Manual Code Generation (through External Tools menu), Code Formatter (Ctrl+Shift+F), Syntax Diagrams, Advanced Rule Navigation between files (F3), Quick fixes.\n\n### NetBeans\n\nSam Harwell's [ANTLRWorks2](http://tunnelvisionlabs.com/products/demo/antlrworks) works also as a plug-in, not just a stand-alone tool built on top of NetBeans.\n\n## Build systems\n\n### ant\n\n### mvn\n\n*Maven Plugin Reference*\n\nThe reference pages for the latest version of the Maven plugin for ANTLR 4 can be found here:\n\n[http://www.antlr.org/api/maven-plugin/latest/index.html](http://www.antlr.org/api/maven-plugin/latest/index.html)\n\n*Walkthrough*\n\nThis section describes how to create a simple Antlr 4 project and build it using maven. We are going to use the ArrayInit.g4 example from chapter 3 of the book, and bring it under maven. We will need to rename files and modify them. We will conclude by building a portable stand alone application.\n\nGenerate the skeleton. To generate the maven skeleton, type these commands:\n\n```bash\nmkdir SimpleAntlrMavenProject\ncd SimpleAntlrMavenProject\nmvn archetype:generate -DgroupId=org.abcd.examples -DartifactId=array-example -Dpackage=org.abcd.examples.ArrayInit -Dversion=1.0\n# Accept all the default values\ncd array-example\n```\n\nMaven will ask a series of questions, simply accept the default answers by hitting enter.\n\nMove into the directory created by maven:\n\n```bash\ncd array-example\n```\n\nWe can use the find command to see the files created by maven:\n\n```bash\n$ find . -type f\n./pom.xml\n./src/test/java/org/abcd/examples/ArrayInit/AppTest.java\n./src/main/java/org/abcd/examples/ArrayInit/App.java\n```\n\nWe need to edit the pom.xml file extensively. The App.java will be renamed to ArrayInit.java and will contain the main ANTLR java program which we will download from the book examples. The AppTest.java file will be renamed ArrayInitTest.java but will remain the empty test as created by maven. We will also be adding the grammar file ArrayInit.g4 from the book examples in there.\n\nGet the examples for the book and put them in the Downloads folder. To obtain the ArrayInit.g4 grammar from the book, simply download it:\n\n```bash\npushd ~/Downloads\nwget http://media.pragprog.com/titles/tpantlr2/code/tpantlr2-code.tgz\ntar xvfz tpantlr2-code.tgz\npopd\n```\n\nCopy the grammar to the maven project. The grammar file goes into a special folder under the src/ directory. The folder name must match the maven package name org.abcd.examples.ArrayInit.\n\n```bash\nmkdir -p src/main/antlr4/org/abcd/examples/ArrayInit\ncp ~/Downloads/code/starter/ArrayInit.g4 src/main/antlr4/org/abcd/examples/ArrayInit\n```\n\nCopy the main program to the maven project. We replace the maven App.java file with the main java program from the book. In the book, that main program is called Test.java, we rename it to ArrayInit.java:\n\n```bash\n# Remove the maven file\nrm ./src/main/java/org/abcd/examples/ArrayInit/App.java\n# Copy and rename the example from the book\ncp ~/Downloads/code/starter/Test.java ./src/main/java/org/abcd/examples/ArrayInit/ArrayInit.java\n```\n\nSpend a few minutes to read the main program. Notice that it reads the standard input stream. We need to remember this when we run the application.\n\nEdit the ArrayInit.java file. We need to add a package declaration and to rename the class. Edit the file ./src/main/java/org/abcd/examples/ArrayInit/ArrayInit.java in your favorite editor. The head of the file should look like this when you are done:\n\n```java\npackage org.abcd.examples.ArrayInit;\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.tree.*;\n \npublic class ArrayInit {\n...\n```\n\nEdit the ArrayInitTest.java file. Maven creates a test file called AppTest.java, we need to rename it to match the name of our application:\n\n```bash\npushd src/test/java/org/abcd/examples/ArrayInit\nmv AppTest.java ArrayInitTest.java\nsed 's/App/ArrayInit/g' ArrayInitTest.java >ArrayInitTest.java.tmp\nmv ArrayInitTest.java.tmp ArrayInitTest.java\npopd\n```\n\nEdit the pom.xml file. Now we need to extensively modify the pom.xml file. The final product looks like this:\n\n```xml\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>org.abcd.examples</groupId>\n  <artifactId>array-init</artifactId>\n  <version>1.0</version>\n  <packaging>jar</packaging>\n  <name>array-init</name>\n  <url>http://maven.apache.org</url>\n  <properties>\n    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n  </properties>\n  <dependencies>\n    <dependency>\n      <groupId>org.antlr</groupId>\n      <artifactId>antlr4-runtime</artifactId>\n      <version>4.9.3</version>\n    </dependency>\n    <dependency>\n      <groupId>junit</groupId>\n      <artifactId>junit</artifactId>\n      <version>4.13.1</version>\n    </dependency>\n  </dependencies>\n  <build>\n    <plugins>\n      <!-- This plugin sets up maven to use Java 7 -->\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-compiler-plugin</artifactId>\n        <version>3.1</version>\n        <configuration>\n          <source>1.8</source>\n          <target>1.8</target>\n        </configuration>\n      </plugin>\n      <!-- Plugin to compile the g4 files ahead of the java files\n           See https://github.com/antlr/antlr4/blob/master/antlr4-maven-plugin/src/site/apt/examples/simple.apt.vm\n           Except that the grammar does not need to contain the package declaration as stated in the documentation (I do not know why)\n           To use this plugin, type:\n             mvn antlr4:antlr4\n           In any case, Maven will invoke this plugin before the Java source is compiled\n        -->\n      <plugin>\n        <groupId>org.antlr</groupId>\n        <artifactId>antlr4-maven-plugin</artifactId>\n        <version>4.9.3</version>\n        <executions>\n          <execution>\n            <goals>\n              <goal>antlr4</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n      <!-- plugin to create a self-contained portable package\n           This allows us to execute our application like this:\n           java -cp target/array-init-1.0-jar-with-dependencies.jar org.abcd.examples.ArrayInit.ArrayInit\n         -->\n      <plugin>\n        <artifactId>maven-assembly-plugin</artifactId>\n        <configuration>\n          <descriptorRefs>\n            <descriptorRef>jar-with-dependencies</descriptorRef>\n          </descriptorRefs>\n        </configuration>\n        <executions>\n          <execution>\n            <id>simple-command</id>\n            <phase>package</phase>\n            <goals>\n              <goal>attached</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n```\n\nThis concludes the changes we had to make. We can look at the list of files we have with the find command:\n\n```bash\n$ find . -type f\n./pom.xml\n./src/test/java/org/abcd/examples/ArrayInit/ArrayInitTest.java\n./src/main/antlr4/org/abcd/examples/ArrayInit/ArrayInit.g4\n./src/main/java/org/abcd/examples/ArrayInit/ArrayInit.java\n```\n\nBuilding a stand alone application. With all the files now in place, we can ask maven to create a standalone application. The following command does this:\n\n```bash\nmvn package\n```\n\nMaven creates a self-contained jar file called target/array-init-1.0-jar-with-dependencies.jar. We can execute the jar file, but remember that it expects some input on the command line, which means the command will hang on the command line until we feed it some input:\n\n```bash\njava -cp target/array-init-1.0-jar-with-dependencies.jar org.abcd.examples.ArrayInit.ArrayInit\n```\n\nAnd let's feed it the following input:\n\n```bash\n{1,2,3}\n^D\n```\n\nThe ^D signals the end of the input to the standard input stream and gets the rest of the application going. You should see the following output:\n\n```bash\n(init { (value 1) , (value 2) , (value 3) })\n```\n\nYou can also build a jar file without the dependencies, and execute it with a maven command instead:\n\n```bash\nmvn install\nmvn exec:java -Dexec.mainClass=org.abcd.examples.ArrayInit.ArrayInit\n{1,2,3}\n^D\n```\n"
  },
  {
    "path": "doc/javascript-target.md",
    "content": "# JavaScript\n\n## Which browsers are supported?\n\nIn theory, all browsers supporting ECMAScript 5.1.\n\nIn practice, this target has been extensively tested against:\n\n* Firefox 34.0.5\n* Safari 8.0.2\n* Chrome 39.0.2171\n* Explorer 11.0.3\n \nThe above tests were conducted using Selenium. No issue was found, so you should find that the runtime works pretty much against any recent JavaScript engine.\n\n## Is NodeJS supported?\n\nThe runtime has also been extensively tested against Node.js 14 LTS. No issue was found.\nNodeJS together with a packaging tool is now the preferred development path, developers are encouraged to follow it.\n\n## What about modules?\n\nStarting with version 8.1, Antlr4 JavaScript runtime follows esm semantics (see https://tc39.es/ecma262/#sec-modules for details)\nGenerated lexers, parsers, listeners and visitors also follow this new standard.\nIf you have used previous versions of the runtime, you will need to migrate and make your parser a module.\n\n## How to create a JavaScript lexer or parser?\n\nThis is pretty much the same as creating a Java lexer or parser, except you need to specify the language target, for example:\n\n```bash\n$ antlr4 -Dlanguage=JavaScript MyGrammar.g4\n```\n\nFor a full list of antlr4 tool options, please visit the [tool documentation page](tool-options.md).\n\n## Where can I get the runtime?\n\nOnce you've generated the lexer and/or parser code, you need to download the runtime.\n\nThe JavaScript runtime is [available from npm](https://www.npmjs.com/package/antlr4).\n\nWe will not document here how to refer to the runtime from your project, since this would differ a lot depending on your project type and IDE. \n\n## How do I get the runtime in my browser?\n\nThe runtime is quite big and is currently maintained in the form of around 50 scripts, which follow the same structure as the runtimes for other targets (Java, C#, Python...).\n\nThis structure is key in keeping code maintainable and consistent across targets.\n\nHowever, it would be a bit of a problem when it comes to get it into a browser. Nobody wants to write 50 times:\n\n```\n<script src='lib/myscript.js'>\n```\n\nTo avoid having doing this, the preferred approach is to bundle antlr4 with your parser code, using webpack.\n\nYou can get [information on webpack here](https://webpack.github.io).\n\nThe steps to create your parsing code are the following:\n - generate your lexer, parser, listener and visitor using the antlr tool\n - write your parse tree handling code by providing your custom listener or visitor, and associated code, using 'require' to load antlr.\n - create an index.js file with the entry point to your parsing code (or several if required).\n - test your parsing logic thoroughly using node.js\n \nYou are now ready to bundle your parsing code as follows:\n - following webpack specs, create a webpack.config file\n - For Webpack version 5,\n   - in the `webpack.config` file, exclude node.js only modules using: `resolve: { fallback: { fs: false } }`\n - For older versions of Webpack,\n   - in the `webpack.config` file, exclude node.js only modules using: `node: { module: \"empty\", net: \"empty\", fs: \"empty\" }`\n - from the cmd line, navigate to the directory containing webpack.config and type: webpack\n \nThis will produce a single js file containing all your parsing code. Easy to include in your web pages!\n\n## How do I run the generated lexer and/or parser?\n\nLet's suppose that your grammar is named, as above, \"MyGrammar\". Let's suppose this parser comprises a rule named \"MyStartRule\". The tool will have generated for you the following files:\n\n*   MyGrammarLexer.js\n*   MyGrammarParser.js\n*   MyGrammarListener.js (if you have not activated the -no-listener option)\n*   MyGrammarVisitor.js (if you have activated the -visitor option)\n   \n(Developers used to Java/C# ANTLR will notice that there is no base listener or visitor generated, this is because JavaScript having no support for interfaces, the generated listener and visitor are fully fledged classes)\n\nNow a fully functioning script might look like the following:\n\n```javascript\nimport antlr4 from 'antlr4';\nimport MyGrammarLexer from './MyGrammarLexer.js';\nimport MyGrammarParser from './MyGrammarParser.js';\nimport MyGrammarListener from './MyGrammarListener.js';\n\nconst input = \"your text to parse here\"\nconst chars = new antlr4.InputStream(input);\nconst lexer = new MyGrammarLexer(chars);\nconst tokens = new antlr4.CommonTokenStream(lexer);\nconst parser = new MyGrammarParser(tokens);\nconst tree = parser.MyStartRule();\n```\n\nThis program will work. But it won't be useful unless you do one of the following:\n\n* you visit the parse tree using a custom listener\n* you visit the parse tree using a custom visitor\n* your grammar comprises production code (like AntLR3)\n \n(please note that production code is target specific, so you can't have multi target grammars that include production code)\n \n## How do I create and run a visitor?\n\nSuppose your grammar is named \"Query\", the parser comprises a rule named \"MyQuery\", and the tool has generated the following files for you:\n\n*   QueryLexer.js\n*   QueryParser.js\n*   QueryListener.js (if you have not activated the -no-listener option)\n\n```javascript\n// test.js\nimport antlr4 from 'antlr4';\nimport MyGrammarLexer from './QueryLexer.js';\nimport MyGrammarParser from './QueryParser.js';\nimport MyGrammarListener from './QueryListener.js';\n\nconst input = \"field = 123 AND items in (1,2,3)\"\nconst chars = new antlr4.InputStream(input);\nconst lexer = new MyGrammarLexer(chars);\nconst tokens = new antlr4.CommonTokenStream(lexer);\nconst parser = new MyGrammarParser(tokens);\nconst tree = parser.MyQuery();\n\nclass Visitor {\n  visitChildren(ctx) {\n    if (!ctx) {\n      return;\n    }\n\n    if (ctx.children) {\n      return ctx.children.map(child => {\n        if (child.children && child.children.length != 0) {\n          return child.accept(this);\n        } else {\n          return child.getText();\n        }\n      });\n    }\n  }\n}\n\ntree.accept(new Visitor());\n````\n\n## How do I create and run a custom listener?\n\nLet's suppose your MyGrammar grammar comprises 2 rules: \"key\" and \"value\". The antlr4 tool will have generated the following listener: \n\n```javascript\nclass MyGrammarListener extends ParseTreeListener {\n    constructor() {\n        super();\n    }\n   \n    enterKey(ctx) {}\n    exitKey(ctx) {}\n    enterValue(ctx) {}\n    exitValue(ctx) {}\n}\n```\n\nIn order to provide custom behavior, you might want to create the following class:\n\n```javascript\nclass KeyPrinter extends MyGrammarListener {\n    // override default listener behavior\n    exitKey(ctx) {\n        console.log(\"Oh, a key!\");\n    }\n}\n```\n\nIn order to execute this listener, you would simply add the following lines to the above code:\n\n```javascript\n...\ntree = parser.MyStartRule() // assumes grammar \"MyGrammar\" has rule \"MyStartRule\"\nconst printer = new KeyPrinter();\nantlr4.tree.ParseTreeWalker.DEFAULT.walk(printer, tree);\n```\n\n## What about TypeScript?\n\nWe have a [TypeScript target](typescript-target.md), based on the JavaScript target.\n\n## How do I integrate my parser with ACE editor?\n\nThis specific task is described in this [dedicated page](ace-javascript-target.md).\n \n## How can I learn more about ANTLR?\n\nFurther information can be found from  \"The definitive ANTLR 4 reference\" book.\n\nThe JavaScript implementation of ANTLR is as close as possible to the Java one, so you shouldn't find it difficult to adapt the book's examples to JavaScript.\n"
  },
  {
    "path": "doc/left-recursion.md",
    "content": "# Left-recursive rules\n\nThe most natural expression of some common language constructs is left recursive. For example C declarators and arithmetic expressions. Unfortunately, left recursive specifications of arithmetic expressions are typically ambiguous but much easier to write out than the multiple levels required in a typical top-down grammar. Here is a sample ANTLR 4 grammar with a left recursive expression rule:\n\n```\nstat: expr '=' expr ';' // e.g., x=y; or x=f(x);\n    | expr ';'          // e.g., f(x); or f(g(x));\n    ;\nexpr: expr '*' expr\n    | expr '+' expr\n    | expr '(' expr ')' // f(x)\n    | id\n    ;\n```\n\nIn straight context free grammars, such a rule is ambiguous because `1+2*3` it can interpret either operator as occurring first, but ANTLR rewrites that to be non-left recursive and unambiguous using semantic predicates:\n\n```\nexpr[int pr] : id\n               ( {4 >= $pr}? '*' expr[5]\n               | {3 >= $pr}? '+' expr[4]\n               | {2 >= $pr}? '(' expr[0] ')'\n               )*\n             ;\n```\n\nThe predicates resolve ambiguities by comparing the precedence of the current operator against the precedence of the previous operator. An expansion of expr[pr] can match only those subexpressions whose precedence meets or exceeds pr.\n\n## Formal rules\n\nThe formal 4.0, 4.1 ANTLR left-recursion elimination rules were changed (simplified) for 4.2 and are laid out in the [ALL(*) tech report](http://www.antlr.org/papers/allstar-techreport.pdf):\n\n* Binary expressions are expressions which contain a recursive invocation of the rule as the first and last element of the alternative.\n* Suffix expressions contain a recursive invocation of the rule as the first element of the alternative, but not as the last element.\n* Prefix expressions contain a recursive invocation of the rule as the last element of the alternative, but not as the first element.\n\nThere is no such thing as a \"ternary\" expression--they are just binary expressions in disguise.\n\nThe right associativity specifiers used to be on the individual tokens but it's done on alternative basis anyway so the option is now on the individual alternative; e.g.,\n\n```\ne : e '*' e\n  | e '+' e\n  |<assoc=right> e '?' e ':' e\n  |<assoc=right> e '=' e\n  | INT\n  ;\n```\n\nIf your 4.0 or 4.1 grammar uses a right-associative ternary operator, you will need to update your grammar to include `<assoc=right>` on the alternative operator. To smooth the transition, `<assoc=right>` is still allowed on token references but it is ignored.\n"
  },
  {
    "path": "doc/lexer-rules.md",
    "content": "# Lexer Rules\n\nA lexer grammar is composed of lexer rules, optionally broken into multiple modes. Lexical modes allow us to split a single lexer grammar into multiple sublexers. The lexer can only return tokens matched by rules from the current mode.\n\nLexer rules specify token definitions and more or less follow the syntax of parser rules except that lexer rules cannot have arguments, return values, or local variables. Lexer rule names must begin with an uppercase letter, which distinguishes them from parser rule names:\n\n```\n/** Optional document comment */\nTokenName : alternative1 | ... | alternativeN ;\n```\n\nYou can also define rules that are not tokens but rather aid in the recognition of tokens. These fragment rules do not result in tokens visible to the parser:\n\n```\nfragment\nHelperTokenRule : alternative1 | ... | alternativeN ;\n```\n\nFor example, `DIGIT` is a pretty common fragment rule:\n\n```\nINT : DIGIT+ ; // references the DIGIT helper rule\nfragment DIGIT : [0-9] ; // not a token by itself\n```\n\n## Lexical Modes\n\nModes allow you to group lexical rules by context, such as inside and outside of XML tags. It’s like having multiple sublexers, one for each context. The lexer can only return tokens matched by entering a rule in the current mode. Lexers start out in the so-called default mode. All rules are considered to be within the default mode unless you specify a mode command. Modes are not allowed within combined grammars, just lexer grammars. (See grammar `XMLLexer` from [Tokenizing XML](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference).)\n\n```\nrules in default mode\n...\nmode MODE1;\nrules in MODE1\n...\nmode MODEN;\nrules in MODEN\n...\n```\n\n## Lexer Rule Elements\n\nLexer rules allow two constructs that are unavailable to parser rules: the .. range operator and the character set notation enclosed in square brackets, [characters]. Don’t confuse character sets with arguments to parser rules. [characters] only means character set in a lexer. Here’s a summary of all lexer rule elements:\n\n<table>\n<tr>\n<th>Syntax</th><th>Description</th>\n</tr>\n<tr>\n<td>T</td><td>\nMatch token T at the current input position. Tokens always begin with a capital letter.</td>\n</tr>\n\n<tr>\n<td>'literal'</td><td>\nMatch that character or sequence of characters. E.g., 'while' or '='.</td>\n</tr>\n\n<tr>\n<td>[char set]</td><td>\n<p>Match one of the characters specified in the character set. Interpret <tt>x-y</tt> as the set of characters between range <tt>x</tt> and <tt>y</tt>, inclusively. The following escaped characters are interpreted as single special characters: <tt>\\n</tt>, <tt>\\r</tt>, <tt>\\b</tt>, <tt>\\t</tt>, <tt>\\f</tt>, <tt>\\uXXXX</tt>, and <tt>\\u{XXXXXX}</tt>. To get <tt>]</tt> or <tt>\\</tt> you must escape them with <tt>\\</tt>. To get <tt>-</tt> you must escape it with <tt>\\</tt> too, except for the case when <tt>-</tt> is the first or last character in the set.</p>\n\n<p>You can also include all characters matching Unicode properties (general category, boolean, or enumerated including scripts and blocks) with <tt>\\p{PropertyName}</tt> or <tt>\\p{EnumProperty=Value}</tt>. (You can invert the test with <tt>\\P{PropertyName}</tt> or <tt>\\P{EnumProperty=Value}</tt>).</p>\n\n<p>For a list of valid Unicode property names, see <a href=\"http://unicode.org/reports/tr44/#Properties\">Unicode Standard Annex #44</a>. (ANTLR also supports <a href=\"http://unicode.org/reports/tr44/#General_Category_Values\">short and long Unicode general category names and values</a> like <tt>\\p{Lu}</tt>, <tt>\\p{Z}</tt>, <tt>\\p{Symbol}</tt>, <tt>\\p{Blk=Latin_1_Sup}</tt>, and <tt>\\p{Block=Latin_1_Supplement}</tt>.)</p>\n\n<p>As a shortcut for <tt>\\p{Block=Latin_1_Supplement}</tt>, you can refer to blocks using <a href=\"http://www.unicode.org/Public/UCD/latest/ucd/Blocks.txt\">Unicode block names</a> prefixed with <tt>In</tt> and with spaces changed to <tt>_</tt>. For example: <tt>\\p{InLatin_1_Supplement}</tt>, <tt>\\p{InYijing_Hexagram_Symbols}</tt>, and <tt>\\p{InAncient_Greek_Numbers}</tt>.</p>\n\n<p>A few extra properties are supported:</p>\n<ul>\n<li><tt>\\p{Extended_Pictographic}</tt> (see <a href=\"http://unicode.org/reports/tr35/\">UTS #35</a>)</li>\n<li><tt>\\p{EmojiPresentation=EmojiDefault}</tt> (code points which have colorful emoji-style presentation by default but which can also be displayed text-style)</li>\n<li><tt>\\p{EmojiPresentation=TextDefault}</tt> (code points which have black-and-white text-style presentation by default but which can also be displayed emoji-style)</li>\n<li><tt>\\p{EmojiPresentation=Text}</tt> (code points which have only black-and-white text-style and lack a colorful emoji-style presentation)</li>\n</ul>\n\n<p>Property names are <b>case-insensitive</b>, and <tt>_</tt> and <tt>-</tt> are treated identically</p>\n\n<p>Here are a few examples:</p>\n\n<pre>\nWS : [ \\n\\u000D] -> skip ; // same as [ \\n\\r]\n\nUNICODE_WS : [\\p{White_Space}] -> skip; // match all Unicode whitespace\n\nID : [a-zA-Z] [a-zA-Z0-9]* ; // match usual identifier spec\n\nUNICODE_ID : [\\p{Alpha}\\p{General_Category=Other_Letter}] [\\p{Alnum}\\p{General_Category=Other_Letter}]* ; // match full Unicode alphabetic ids\n\nEMOJI : [\\u{1F4A9}\\u{1F926}] ; // note Unicode code points > U+FFFF\n\nDASHBRACK : [\\-\\]]+ ; // match - or ] one or more times\n\nDASH : [---] ; // match a single -, i.e., \"any character\" between - and - (note first and last - not escaped)\n</pre>\n</td>\n</tr>\n\n<tr>\n<td>'x'..'y'</td><td>\nMatch any single character between range x and y, inclusively. E.g., 'a'..'z'. 'a'..'z' is identical to [a-z].</td>\n</tr>\n\n<tr>\n<td>T</td><td>\nInvoke lexer rule T; recursion is allowed in general, but not left recursion. T can be a regular token or fragment rule.\n \t\n<pre>\nID : LETTER (LETTER|'0'..'9')* ;\n \t\nfragment\nLETTER : [a-zA-Z\\u0080-\\u00FF_] ;\n</pre>\n</td>\n</tr>\n\n<tr>\n<td>.</td><td>\nThe dot is a single-character wildcard that matches any single character. Example:\n<pre>\nESC : '\\\\' . ; // match any escaped \\x character\n</pre>\n</td>\n</tr>\n\n<tr>\n<td>{«action»}</td><td>\nLexer actions can appear anywhere as of 4.2, not just at the end of the outermost alternative. The lexer executes the actions at the appropriate input position, according to the placement of the action within the rule. To execute a single action for a rule that has multiple alternatives, you can enclose the alts in parentheses and put the action afterwards:\n \t\n<pre>\nEND : ('endif'|'end') {System.out.println(\"found an end\");} ;\n</pre>\n\n<p>The action conforms to the syntax of the target language. ANTLR copies the action’s contents into the generated code verbatim; there is no translation of expressions like $x.y as there is in parser actions.</p>\n<p>\nOnly actions within the outermost token rule are executed. In other words, if STRING calls ESC_CHAR and ESC_CHAR has an action, that action is not executed when the lexer starts matching in STRING.</p></td>\n</tr>\n\n<tr>\n<td>{«p»}?</td><td>\nEvaluate semantic predicate «p». If «p» evaluates to false at runtime, the surrounding rule becomes “invisible” (nonviable). Expression «p» conforms to the target language syntax. While semantic predicates can appear anywhere within a lexer rule, it is most efficient to have them at the end of the rule. The one caveat is that semantic predicates must precede lexer actions. See Predicates in Lexer Rules.</td>\n</tr>\n\n<tr>\n<td>~x</td><td>\nMatch any single character not in the set described by x. Set x can be a single character literal, a range, or a subrule set like ~('x'|'y'|'z') or ~[xyz]. Here is a rule that uses ~ to match any character other than characters using ~[\\r\\n]*:\n<pre> \t\nCOMMENT : '#' ~[\\r\\n]* '\\r'? '\\n' -> skip ;\n</pre>\n</td>\n</tr>\n</table>\n\nJust as with parser rules, lexer rules allow subrules in parentheses and EBNF operators: `?`, `*`, `+`. The `COMMENT` rule illustrates the `*` and `?` operators. A common use of `+` is `[0-9]+` to match integers. Lexer subrules can also use the nongreedy `?` suffix on those EBNF operators.\n\n## Recursive Lexer Rules\n\nANTLR lexer rules can be recursive, unlike most lexical grammar tools. This comes in really handy when you want to match nested tokens like nested action blocks: `{...{...}...}`.\n\n```\nlexer grammar Recur;\n \nACTION : '{' ( ACTION | ~[{}] )* '}' ;\n \nWS : [ \\r\\t\\n]+ -> skip ;\n```\n\n## Redundant String Literals\n\nBe careful that you don’t specify the same string literal on the right-hand side of multiple lexer rules. Such literals are ambiguous and could match multiple token types. ANTLR makes this literal unavailable to the parser. The same is true for rules across modes. For example, the following lexer grammar defines two tokens with the same character sequence:\n\n```\nlexer grammar L;\nAND : '&' ;\nmode STR;\nMASK : '&' ;\n```\n\nA parser grammar cannot reference literal '&', but it can reference the name of the tokens:\n\n```\nparser grammar P;\noptions { tokenVocab=L; }\na : '&' // results in a tool error: no such token\n    AND // no problem\n    MASK // no problem\n  ;\n```\n\nHere’s a build and test sequence:\n\n```bash\n$ antlr4 L.g4 # yields L.tokens file needed by tokenVocab option in P.g4\n$ antlr4 P.g4\nerror(126): P.g4:3:4: cannot create implicit token for string literal '&' in non-combined grammar\n```\n\n## Lexer Rule Actions\n\nAn ANTLR lexer creates a Token object after matching a lexical rule. Each request for a token starts in `Lexer.nextToken`, which calls `emit` once it has identified a token. `emit` collects information from the current state of the lexer to build the token. It accesses fields `_type`, `_text`, `_channel`, `_tokenStartCharIndex`, `_tokenStartLine`, and `_tokenStartCharPositionInLine`. You can set the state of these with the various setter methods such as `setType`. For example, the following rule turns `enum` into an identifier if `enumIsKeyword` is false.\n\n```\nENUM : 'enum' {if (!enumIsKeyword) setType(Identifier);} ;\n```\n\nANTLR does no special `$x` attribute translations in lexer actions (unlike v3).\n\nThere can be at most a single action for a lexical rule, regardless of how many alternatives there are in that rule.\n\n## Lexer Commands\n\nTo avoid tying a grammar to a particular target language, ANTLR supports lexer commands. Unlike arbitrary embedded actions, these commands follow specific syntax and are limited to a few common commands. Lexer commands appear at the end of the outermost alternative of a lexer rule definition. Like arbitrary actions, there can only be one per token rule. A lexer command consists of the `->` operator followed by one or more command names that can optionally take parameters:\n\n```\nTokenName : «alternative» -> command-name\nTokenName : «alternative» -> command-name («identifier or integer»)\n```\n\nAn alternative can have more than one command separated by commas. Here are the valid command names:\n\n* skip\n* more\n* popMode\n* mode( x )\n* pushMode( x )\n* type( x )\n* channel( x )\n\nSee the book source code for usage, some examples of which are shown here:\n\n### skip\n\nA 'skip' command tells the lexer to get another token and throw out the current text.\n\n```\nID : [a-zA-Z]+ ; // match identifiers\nINT : [0-9]+ ; // match integers\nNEWLINE:'\\r'? '\\n' ; // return newlines to parser (is end-statement signal)\nWS : [ \\t]+ -> skip ; // toss out whitespace\n```\n\n### mode(), pushMode(), popMode, and more\n\nThe mode commands alter the mode stack and hence the mode of the lexer. The 'more' command forces the lexer to get another token but without throwing out the current text. The token type will be that of the \"final\" rule matched (i.e., the one without a more or skip command).\n\n```\n// Default \"mode\": Everything OUTSIDE of a tag\nCOMMENT : '<!--' .*? '-->' ;\nCDATA   : '<![CDATA[' .*? ']]>' ;\nOPEN : '<' -> pushMode(INSIDE) ;\n ...\nXMLDeclOpen : '<?xml' S -> pushMode(INSIDE) ;\nSPECIAL_OPEN: '<?' Name -> more, pushMode(PROC_INSTR) ;\n// ----------------- Everything INSIDE of a tag ---------------------\nmode INSIDE;\nCLOSE        : '>' -> popMode ;\nSPECIAL_CLOSE: '?>' -> popMode ; // close <?xml...?>\nSLASH_CLOSE  : '/>' -> popMode ;\n```\n\nAlso check out:\n\n```\nlexer grammar Strings;\nLQUOTE : '\"' -> more, mode(STR) ;\nWS : [ \\r\\t\\n]+ -> skip ;\nmode STR;\nSTRING : '\"' -> mode(DEFAULT_MODE) ; // token we want parser to see\nTEXT : . -> more ; // collect more text for string\n```\n\nPopping the bottom layer of a mode stack will result in an exception. Switching modes with `mode` changes the current stack top.  More than one `more` is the same as just one and the position does not matter.\n\n### type()\n\n```\nlexer grammar SetType;\ntokens { STRING }\nDOUBLE : '\"' .*? '\"'   -> type(STRING) ;\nSINGLE : '\\'' .*? '\\'' -> type(STRING) ;\nWS     : [ \\r\\t\\n]+    -> skip ;\n```\n\nFor multiple 'type()' commands, only the rightmost has an effect.\n\n### channel()\n\n```\nBLOCK_COMMENT\n\t: '/*' .*? '*/' -> channel(HIDDEN)\n\t;\nLINE_COMMENT\n\t: '//' ~[\\r\\n]* -> channel(HIDDEN)\n\t;\n... \n// ----------\n// Whitespace\n//\n// Characters and character constructs that are of no import\n// to the parser and are used to make the grammar easier to read\n// for humans.\n//\nWS : [ \\t\\r\\n\\f]+ -> channel(HIDDEN) ;\n```\n\nAs of 4.5, you can also define channel names like enumerations with the following construct above the lexer rules:\n\n```\nchannels { WSCHANNEL, MYHIDDEN }\n```\n\n## Lexer Rule Options\n\n### caseInsensitive\n\nDefines if the current lexer rule is case-insensitive.\nThe argument can be `true` or `false`.\nThe option rewrites `caseInsensitive` grammar option value if it's defined.\n\n```g4\noptions { caseInsensitive=true; }\nSTRING options { caseInsensitive=false; } : 'N'? '\\'' (~'\\'' | '\\'\\'')* '\\''; // lower n is not allowed\n```\n"
  },
  {
    "path": "doc/lexicon.md",
    "content": "# Grammar Lexicon\n\nThe lexicon of ANTLR is familiar to most programmers because it follows the syntax of C and its derivatives with some extensions for grammatical descriptions.\n\n## Comments\n\nThere are single-line, multiline, and Javadoc-style comments:\n\n```\n/** This grammar is an example illustrating the three kinds\n * of comments.\n */\ngrammar T;\n/* a multi-line\n  comment\n*/\n\n/** This rule matches a declarator for my language */\ndecl : ID ; // match a variable name\n```\n\nThe Javadoc comments are hidden from the parser and are ignored at the moment.  They are intended to be used only at the start of the grammar and any rule.\n\n## Identifiers\n\nToken names always start with a capital letter and so do lexer rules as defined by Java’s `Character.isUpperCase` method. Parser rule names always start with a lowercase letter (those that fail `Character.isUpperCase`). The initial character can be followed by uppercase and lowercase letters, digits, and underscores. Here are some sample names:\n\n```\nID, LPAREN, RIGHT_CURLY // token names/lexer rules\nexpr, simpleDeclarator, d2, header_file // parser rule names\n```\n\nLike Java, ANTLR accepts Unicode characters in ANTLR names:\n\n<img src=images/nonascii.png width=100>\n\nTo support Unicode parser and lexer rule names, ANTLR uses the following rule:\n\n```\nID : a=NameStartChar NameChar*\n     {  \n     if ( Character.isUpperCase(getText().charAt(0)) ) setType(TOKEN_REF);\n     else setType(RULE_REF);\n     }  \n   ;\n```\n\nRule `NameChar` identifies the valid identifier characters:\n\n```\nfragment\nNameChar\n   : NameStartChar\n   | '0'..'9'\n   | '_'\n   | '\\u00B7'\n   | '\\u0300'..'\\u036F'\n   | '\\u203F'..'\\u2040'\n   ;\nfragment\nNameStartChar\n   : 'A'..'Z' | 'a'..'z'\n   | '\\u00C0'..'\\u00D6'\n   | '\\u00D8'..'\\u00F6'\n   | '\\u00F8'..'\\u02FF'\n   | '\\u0370'..'\\u037D'\n   | '\\u037F'..'\\u1FFF'\n   | '\\u200C'..'\\u200D'\n   | '\\u2070'..'\\u218F'\n   | '\\u2C00'..'\\u2FEF'\n   | '\\u3001'..'\\uD7FF'\n   | '\\uF900'..'\\uFDCF'\n   | '\\uFDF0'..'\\uFFFD'\n   ;\n```\n\nRule `NameStartChar` is the list of characters that can start an identifier (rule, token, or label name):\nThese more or less correspond to `isJavaIdentifierPart` and `isJavaIdentifierStart` in Java’s Character class. Make sure to use the `-encoding` option on the ANTLR tool if your grammar file is not in UTF-8 format, so that ANTLR reads characters properly.\n\n## Literals\n\nANTLR does not distinguish between character and string literals as most languages do. All literal strings one or more characters in length are enclosed in single quotes such as `';'`, `'if'`, `'>='`, and `'\\''` (refers to the one-character string containing the single quote character). Literals never contain regular expressions.\n\nLiterals can contain Unicode escape sequences of the form `'\\uXXXX'` (for Unicode code points up to `'U+FFFF'`) or `'\\u{XXXXXX}'` (for all Unicode code points), where `'XXXX'` is the hexadecimal Unicode code point value.\n\nFor example, `'\\u00E8'` is the French letter with a grave accent: `'è'`, and `'\\u{1F4A9}'` is the famous emoji: `'💩'`.\n\nANTLR also understands the usual special escape sequences: `'\\n'` (newline), `'\\r'` (carriage return), `'\\t'` (tab), `'\\b'` (backspace), and `'\\f'` (form feed). You can use Unicode code points directly within literals or use the Unicode escape sequences:\n\n```\ngrammar Foreign;\na : '外' ;\n```\n\nThe recognizers that ANTLR generates assume a character vocabulary containing all Unicode characters. The input file encoding assumed by the runtime library depends on the target language. For the Java target, the runtime library assumes files are in UTF-8. Using the  factory methods in `CharStreams`, you can specify a different encoding.\n\n## Actions\n\nActions are code blocks written in the target language. You can use actions in a number of places within a grammar, but the syntax is always the same: arbitrary text surrounded by curly braces. You don’t need to escape a closing curly character if it’s in a string or comment: `\"}\"` or `/*}*/`. If the curlies are balanced, you also don’t need to escape }: `{...}`. Otherwise, escape extra curlies with a backslash: `\\{` or `\\}`. The action text should conform to the target language as specified with the language option.\n\nEmbedded code can appear in: `@header` and `@members` named actions, parser and lexer rules, exception catching specifications, attribute sections for parser rules (return values, arguments, and locals), and some rule element options (currently predicates).\n\nThe only interpretation ANTLR does inside actions relates to grammar attributes; see [Token Attributes](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference) and Chapter 10, [Attributes and Actions](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference). Actions embedded within lexer rules are emitted without any interpretation or translation into generated lexers.\n\n## Keywords\n\nHere’s a list of the reserved words in ANTLR grammars:\n\n```\nimport, fragment, lexer, parser, grammar, returns,\nlocals, throws, catch, finally, mode, options, tokens\n```\n  \nAlso, although it is not a keyword, do not use the word `rule` as a rule name. Further, do not use any keyword of the target language as a token, label, or rule name. For example, rule `if` would result in a generated function called `if`.  That would not compile obviously.\n"
  },
  {
    "path": "doc/listeners.md",
    "content": "# Parse Tree Listeners\n\n*Partially taken from publically visible [excerpt from ANTLR 4 book](http://media.pragprog.com/titles/tpantlr2/picture.pdf)*\n\nBy default, ANTLR-generated parsers build a data structure called a parse tree or syntax tree that records how the parser recognized the structure of the input sentence and component phrases.\n\n<img src=images/process.png>\n\nThe interior nodes of the parse tree are phrase names that group and identify their children. The root node is the most abstract phrase name, in this case `stat` (short for statement). The leaves of a parse tree are always the input tokens. Parse trees sit between a language recognizer and an interpreter or translator implementation. They are extremely effective data structures because they contain all of the input and complete knowledge of how the parser grouped the symbols into phrases. Better yet, they are easy to understand and the parser generates them automatically (unless you turn them off with `parser.setBuildParseTree(false)`).\n\nBecause we specify phrase structure with a set of rules, parse tree subtree roots correspond to grammar rule names. ANTLR has a ParseTreeWalker that knows how to walk these parse trees and trigger events in listener implementation objects that you can create. The ANTLR tool generates listener interfaces for you also, unless you turn that off with a commandline option. You can also have it generate visitors. For example from a Java.g4 grammar, ANTLR generates:\n\n```java\npublic interface JavaListener extends ParseTreeListener<Token> {\n  void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx);\n  void exitClassDeclaration(JavaParser.ClassDeclarationContext ctx);\n  void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx);\n ...\n}\n```\n\nwhere there is an enter and exit method for each rule in the parser grammar. ANTLR also generates a base listener with empty implementations of all listener interface methods, in this case called JavaBaseListener. You can build your listener by subclassing this base and overriding the methods of interest.\n\nAssuming you've created a listener object called `MyListener`, here is how to call the Java parser and walk the parse tree:\n\n```java\nJavaLexer lexer = new JavaLexer(input);\nCommonTokenStream tokens = new CommonTokenStream(lexer);\nJavaParser parser = new JavaParser(tokens);\nJavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse a compilationUnit\n\nMyListener extractor = new MyListener(parser);\nParseTreeWalker.DEFAULT.walk(extractor, tree); // initiate walk of tree with listener in use of default walker\n```\n\nListeners and visitors are great because they keep application-specific code out of grammars, making grammars easier to read and preventing them from getting entangled with a particular application.\n\nSee the book for more information on listeners and to learn how to use visitors. (The biggest difference between the listener and visitor mechanisms is that listener methods are called independently by an ANTLR-provided walker object, whereas visitor methods must walk their children with explicit visit calls.  Forgetting to invoke visitor methods on a node’s children, means those subtrees don’t get visited.)\n\n## Listening during the parse\n\nWe can also use listeners to execute code during the parse instead of waiting for a tree walker walks the resulting parse tree. Let's say we have the following simple expression grammar.\n\n```\ngrammar CalcNoLR;\n\ns : expr EOF ;\n\nexpr:\tadd ((MUL | DIV) add)* ;\n\nadd :   atom ((ADD | SUB) atom)* ;\n\natom : INT ;\n\nINT : [0-9]+;\nMUL : '*';\nDIV : '/';\nADD : '+';\nSUB : '-';\nWS : [ \\t]+ -> channel(HIDDEN);\n```\n\nWe can create a listener that executes during the parse by implementing the listener interface as before:\n\n\n```java\nclass CountListener extends CalcNoLRBaseListener {\n\tpublic int nums = 0;\n\tpublic boolean execExitS = false;\n\n\t@Override\n\tpublic void exitS(CalcNoLRParser.SContext ctx) {\n\t\texecExitS = true;\n\t}\n\n\t@Override\n\tpublic void exitAtom(CalcNoLRParser.AtomContext ctx) {\n\t\tnums++;\n\t}\n}\n```\n\nAnd then passing it to `addParseListener()`:\n\n```java\nString input = \"2 + 8 / 2\";\nCalcNoLRLexer lexer = new CalcNoLRLexer(new ANTLRInputStream(input));\nCalcNoLRParser parser = new CalcNoLRParser(new CommonTokenStream(lexer));\nCountListener counter = new CountListener();\nparser.addParseListener(counter);\n\n// Check that the purses valid first\nCalcNoLRParser.SContext context = parser.s();\nString parseTreeS = context.toStringTree(parser);\nassertEquals(\"(s (expr (add (atom 2) + (atom 8)) / (add (atom 2))) <EOF>)\", parseTreeS);\nassertEquals(3, counter.nums);\nassertEquals(true, counter.execExitS);\n```\n\nOne should not do very complicated work during the parse because the parser is throwing exception to handle syntax errors. If you're complicated code throws different kind of exception it will screw up the parsing and things will go nuts. If you want to catch and properly handle exceptions in your listener code during the parse, you should override this method from `Parser`:\n\n```java\nprotected boolean listenerExceptionOccurred = false;\n\n/**\n * Notify any parse listeners of an exit rule event.\n *\n * @see #addParseListener\n */\n@override\nprotected void triggerExitRuleEvent() {\n\tif ( listenerExceptionOccurred ) return;\n\ttry {\n\t\t// reverse order walk of listeners\n\t\tfor (int i = _parseListeners.size() - 1; i >= 0; i--) {\n\t\t\tParseTreeListener listener = _parseListeners.get(i);\n\t\t\t_ctx.exitRule(listener);\n\t\t\tlistener.exitEveryRule(_ctx);\n\t\t}\n\t}\n\tcatch (Throwable e) {\n\t\t// If an exception is thrown in the user's listener code, we need to bail out\n\t\t// completely out of the parser, without executing anymore user code. We\n\t\t// must also stop the parse otherwise other listener actions will attempt to execute\n\t\t// almost certainly with invalid results. So, record the fact an exception occurred\n\t\tlistenerExceptionOccurred = true;\n\t\tthrow e;\n\t}\n}\n```\n\nNow, if you throw an exception inside one of the listener methods:\n\n```java\n// Now throw an exception in the listener\nclass ErrorListener extends CalcNoLRBaseListener {\n\tpublic boolean execExitS = false;\n\tpublic boolean execExitAtom = false;\n\n\t@Override\n\tpublic void exitS(CalcNoLRParser.SContext ctx) {\n\t\texecExitS = true;\n\t}\n\n\t@Override\n\tpublic void exitAtom(CalcNoLRParser.AtomContext ctx) {\n\t\texecExitAtom = true;\n\t\tthrow new NullPointerException(\"bail out\");\n\t}\n}\n```\n\nthen the exception will properly cause the parser to bailout and the exception will not be thrown out:\n\n```\njava.lang.NullPointerException: bail out\n\n\tat org.antlr.v4.test.runtime.java.api.TestParseListener$2ErrorListener.exitAtom(TestParseListener.java:102)\n\tat org.antlr.v4.test.runtime.java.api.CalcNoLRParser$AtomContext.exitRule(CalcNoLRParser.java:311)\n\tat org.antlr.v4.runtime.Parser.triggerExitRuleEvent(Parser.java:412)\n\tat org.antlr.v4.runtime.Parser.exitRule(Parser.java:654)\n\tat org.antlr.v4.test.runtime.java.api.CalcNoLRParser.atom(CalcNoLRParser.java:336)\n\tat org.antlr.v4.test.runtime.java.api.CalcNoLRParser.add(CalcNoLRParser.java:261)\n\tat org.antlr.v4.test.runtime.java.api.CalcNoLRParser.expr(CalcNoLRParser.java:181)\n\tat org.antlr.v4.test.runtime.java.api.CalcNoLRParser.s(CalcNoLRParser.java:123)\n```\n"
  },
  {
    "path": "doc/options.md",
    "content": "# Options\n\nThere are a number of options that you can specify at the grammar and rule element level. (There are currently no rule options.) These change how ANTLR generates code from your grammar. The general syntax is:\n\n```\noptions { name1=value1; ... nameN=valueN; } // ANTLR not target language syntax\n```\n\nwhere a value can be an identifier, a qualified identifier (for example, a.b.c), a string, a multi-line string in curly braces `{...}`, and an integer.\n\n## Grammar Options\n\nAll grammars can use the following options. In combined grammars, all options except language pertain only to the generated parser. Options may be set either within the grammar file using the options syntax (described above) or when invoking ANTLR on the command line, using the `-D` option. (see Section 15.9, [ANTLR Tool Command Line Options](tool-options.md).) The following examples demonstrate both mechanisms; note that `-D` overrides options within the grammar.\n\n### `superClass`\n\nSet the superclass of the generated parser or lexer. For combined grammars, it sets the superclass of the parser.\n\n```\n$ cat Hi.g4\ngrammar Hi;\na : 'hi' ;\n$ antlr4 -DsuperClass=XX Hi.g4\n$ grep 'public class' HiParser.java\npublic class HiParser extends XX {\n$ grep 'public class' HiLexer.java\npublic class HiLexer extends Lexer {\n```\n\n### `language`\n\nGenerate code in the indicated language, if ANTLR is able to do so. Otherwise, you will see an error message like this:\n\n```\n$ antlr4 -Dlanguage=C MyGrammar.g4\nerror(31):  ANTLR cannot generate C code as of version 4.0\n```\n\n### `tokenVocab`\n\nANTLR assigns token type numbers to the tokens as it encounters them in a file. To use different token type values, such as with a separate lexer, use this option to have ANTLR pull in the <fileextension>tokens</fileextension> file. ANTLR generates a <fileextension>tokens</fileextension> file from each grammar.\n\n```\n$ cat SomeLexer.g4\nlexer grammar SomeLexer;\nID : [a-z]+ ;\n$ cat R.g4\nparser grammar R;\noptions {tokenVocab=SomeLexer;}\ntokens {A,B,C} // normally, these would be token types 1, 2, 3\na : ID ;\n$ antlr4 SomeLexer.g4\n$ cat SomeLexer.tokens \nID=1\n$ antlr4 R.g4\n$ cat R.tokens\nA=2\nB=3\nC=4\nID=1\n```\n\n### `TokenLabelType`\n\nANTLR normally uses type <class>Token</class> when it generates variables referencing tokens. If you have passed a <class>TokenFactory</class> to your parser and lexer so that they create custom tokens, you should set this option to your specific type. This ensures that the context objects know your type for fields and method return values.\n\n```\n$ cat T2.g4\ngrammar T2;\noptions {TokenLabelType=MyToken;}\na : x=ID ;\n$ antlr4 T2.g4\n$ grep MyToken T2Parser.java\n    public MyToken x;\n```\n\n### `contextSuperClass`\n\nSpecify the super class of parse tree internal nodes. Default is `ParserRuleContext`. Should derive from ultimately `RuleContext` at minimum.\nJava target can use `contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum` for convenience. It adds a backing field for `altNumber`, the alt matched for the associated rule node.\n\n### `caseInsensitive`\n\nAs of 4.10, ANTLR supports case-insensitive lexers using a grammar option. For example, the parser from the following grammar:\n\n```g4\nlexer grammar L;\noptions { caseInsensitive = true; }\nENGLISH_TOKEN:   [a-z]+;\nGERMAN_TOKEN:    [äéöüß]+;\nFRENCH_TOKEN:    [àâæ-ëîïôœùûüÿ]+;\nCROATIAN_TOKEN:  [ćčđšž]+;\nITALIAN_TOKEN:   [àèéìòù]+;\nSPANISH_TOKEN:   [áéíñóúü¡¿]+;\nGREEK_TOKEN:     [α-ω]+;\nRUSSIAN_TOKEN:   [а-я]+;\nWS:              [ ]+ -> skip;\n```\n\nmatches words such as the following:\n\n```\nabcXYZ äéöüßÄÉÖÜß àâæçÙÛÜŸ ćčđĐŠŽ àèéÌÒÙ áéÚÜ¡¿ αβγΧΨΩ абвЭЮЯ\n```\n\nANTLR considers only one-length chars in all cases. For instance, german lower `ß` is not treated as upper `ss` and vice versa.\n\nThe mechanism works by automatically transforming grammar references to characters to there upper/lower case equivalent; e.g., `a` to `[aA]`. This means that you do not need to convert your input characters to uppercase--token text will be as it appears in the input stream.\n\n## Rule Options\n\n### caseInsensitive\n\nThe tool support `caseInsensitive` lexer rule option that is described in [lexer-rules.md](lexer-rules.md#caseinsensitive).\n\n## Rule Element Options\n\nToken options have the form `T<name=value>` as we saw in Section 5.4, [Dealing with Precedence, Left Recursion, and Associativity](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference). The only token option is `assoc`, and it accepts values `left` and `right`. Here’s a sample grammar with a left-recursive expression rule that specifies a token option on the `^` exponent operator token:\n\n```\ngrammar ExprLR;\n \t \nexpr : expr '^'<assoc=right> expr\n \t| expr '*' expr // match subexpressions joined with '*' operator\n \t| expr '+' expr // match subexpressions joined with '+' operator\n \t| INT // matches simple integer atom\n \t;\n \t \nINT : '0'..'9'+ ;\nWS : [ \\n]+ -> skip ;\n```\n\nSemantic predicates also accept an option, per [Catching failed semantic predicates](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference). The only valid option is the `fail` option, which takes either a string literal in double-quotes or an action that evaluates to a string. The string literal or string result from the action should be the message to emit upon predicate failure.\n\n```\nints[int max]\n \tlocals [int i=1]\n \t: INT ( ',' {$i++;} {$i<=$max}?<fail={\"exceeded max \"+$max}> INT )*\n \t;\n```\n\nThe action can execute a function as well as compute a string when a predicate fails: `{...}?<fail={doSomethingAndReturnAString()}>`\n"
  },
  {
    "path": "doc/parser-rules.md",
    "content": "# Parser Rules\n\nParsers consist of a set of parser rules either in a parser or a combined grammar. A Java application launches a parser by invoking the rule function, generated by ANTLR, associated with the desired start rule. The most basic rule is just a rule name followed by a single alternative terminated with a semicolon:\n\n```\n \t/** Javadoc comment can precede rule */\n \tretstat : 'return' expr ';' ;\n```\n\nRules can also have alternatives separated by the | \n\n```\noperator:\n \tstat: retstat\n \t| 'break' ';'\n \t| 'continue' ';'\n \t;\n```\n\nAlternatives are either a list of rule elements or empty. For example, here’s a rule with an empty alternative that makes the entire rule optional:\n\n```\nsuperClass\n \t: 'extends' ID\n \t| // empty means other alternative(s) are optional\n \t;\n```\n\n## Alternative Labels\n\nAs we saw in Section 7.4, Labeling Rule Alternatives for Precise Event Methods, we can get more precise parse-tree listener events by labeling the outermost alternatives of a rule using the # operator. All alternatives within a rule must be labeled, or none of them. Here are two rules with labeled alternatives.\n\n```\ngrammar T;\nstat: 'return' e ';' # Return\n \t| 'break' ';' # Break\n \t;\ne   : e '*' e # Mult\n    | e '+' e # Add\n    | INT # Int\n    ;\n```\n\nAlternative labels do not have to be at the end of the line and there does not have to be a space after the # symbol.\nANTLR generates a rule context class definition for each label. For example, here is the listener that ANTLR generates:\n\n```java\npublic interface AListener extends ParseTreeListener {\n \tvoid enterReturn(AParser.ReturnContext ctx);\n \tvoid exitReturn(AParser.ReturnContext ctx);\n \tvoid enterBreak(AParser.BreakContext ctx);\n \tvoid exitBreak(AParser.BreakContext ctx);\n \tvoid enterMult(AParser.MultContext ctx);\n \tvoid exitMult(AParser.MultContext ctx);\n \tvoid enterAdd(AParser.AddContext ctx);\n \tvoid exitAdd(AParser.AddContext ctx);\n \tvoid enterInt(AParser.IntContext ctx);\n \tvoid exitInt(AParser.IntContext ctx);\n}\n```\n\nThere are enter and exit methods associated with each labeled alternative. The parameters to those methods are specific to alternatives.\n\nYou can reuse the same label on multiple alternatives to indicate that the parse tree walker should trigger the same event for those alternatives. For example, here’s a variation on rule e from grammar A above:\n\n```\n \te : e '*' e # BinaryOp\n \t| e '+' e # BinaryOp\n \t| INT # Int\n \t;\n```\n\nANTLR would generate the following listener methods for e:\n\n```java\n \tvoid enterBinaryOp(AParser.BinaryOpContext ctx);\n \tvoid exitBinaryOp(AParser.BinaryOpContext ctx);\n \tvoid enterInt(AParser.IntContext ctx);\n \tvoid exitInt(AParser.IntContext ctx);\n ```\n\nANTLR gives errors if an alternative name conflicts with a rule name. Here’s another rewrite of rule e where two \nalternative labels conflict with rule names:\n\n```\n \te : e '*' e # e\n \t| e '+' e # Stat\n \t| INT # Int\n \t;\n```\n\nThe context objects generated from rule names and labels get capitalized and so label Stat conflicts with rule stat:\n\n```bash\n \t$ antlr4 A.g4\n \terror(124): A.g4:5:23: rule alt label e conflicts with rule e\n \terror(124): A.g4:6:23: rule alt label Stat conflicts with rule stat\n \twarning(125): A.g4:2:13: implicit definition of token INT in parser\n```\n\n## Rule Context Objects\n\nANTLR generates methods to access the rule context objects (parse tree nodes) associated with each rule reference. For rules with a single rule reference, ANTLR generates a method with no arguments. Consider the following rule.\n\n```\n \tinc : e '++' ;\n```\n\nANTLR generates this context class:\n\n```java\npublic static class IncContext extends ParserRuleContext {\n \tpublic EContext e() { ... } // return context object associated with e\n \t...\n}\n```\n\nANTLR also provide support to access context objects when there is more than a single reference to a rule:\n\n```\nfield : e '.' e ;\n```\n\nANTLR generates a method with an index to access the ith element as well as a method to get context for all references to that rule:\n\n```java\npublic static class FieldContext extends ParserRuleContext {\n \tpublic EContext e(int i) { ... } // get ith e context\n \tpublic List<EContext> e() { ... } // return ALL e contexts\n \t...\n}\n```\n\nIf we had another rule, s, that references field, an embedded action could access the list of e rule matches performed by field:\n\n```\ns : field\n \t{\n \tList<EContext> x = $field.ctx.e();\n \t...\n \t}\n;\n```\n\nA listener or visitor could do the same thing. Given a pointer to a FieldContext object, f, f.e() would return List<EContext>.\n\n## Rule Element Labels\n\nYou can label rule elements using the = operator to add fields to the rule context objects:\n\n```\nstat: 'return' value=e ';' # Return\n \t| 'break' ';' # Break\n \t;\n```\n\nHere value is the label for the return value of rule e, which is defined elsewhere.\nLabels become fields in the appropriate parse tree node class. In this case, label value becomes a field in ReturnContext because of the Return alternative label:\n\n```java\npublic static class ReturnContext extends StatContext {\n \tpublic EContext value;\n \t...\n}\n```\n\nIt’s often handy to track a number of tokens, which you can do with the += “list label” operator. For example, the following rule creates a list of the Token objects matched for a simple array construct:\n\n```\n \tarray : '{' el+=INT (',' el+=INT)* '}' ;\n```\n\nANTLR generates a List field in the appropriate rule context class:\n\n```\n \tpublic static class ArrayContext extends ParserRuleContext {\n \tpublic List<Token> el = new ArrayList<Token>();\n \t...\n \t}\n```\n\nThese list labels also work for rule references:\n\n```\n \telist : exprs+=e (',' exprs+=e)* ;\n```\n\nANTLR generates a field holding the list of context objects:\n\n```\n \tpublic static class ElistContext extends ParserRuleContext {\n \tpublic List<EContext> exprs = new ArrayList<EContext>();\n \t...\n \t}\n```\n\n## Rule Elements\n\nRule elements specify what the parser should do at a given moment just like statements in a programming language. The elements can be rule, token, string literal like expression, ID, and 'return'. Here’s a complete list of the rule elements (we’ll look at actions and predicates in more detail later):\n\n<table>\n<tr>\n<th>Syntax</th><th>Description</th>\n</tr>\n<tr>\n<td>T</td><td>\nMatch token T at the current input position. Tokens always begin with a capital letter.</td>\n</tr>\n<tr>\n<td>'literal'</td><td>\nMatch the string literal at the current input position. A string literal is simply a token with a fixed string.</td>\n</tr>\n<tr>\n<td>r</td><td>\nMatch rule r at current input position, which amounts to invoking the rule just like a function call. Parser rule names always begin with a lowercase letter.</td>\n</tr>\n<tr>\n<td>r [«args»]</td><td>\nMatch rule r at current input position, passing in a list of arguments just like a function call. The arguments inside the square brackets are in the syntax of the target language and are usually a comma-separated list of expressions.</td>\n</tr>\n<tr>\n<td>{«action»}</td><td>\nExecute an action immediately after the preceding alternative element and immediately before the following alternative element. The action conforms to the syntax of the target language. ANTLR copies the action code to the generated class verbatim, except for substituting attribute and token references such as $x and $x.y.</td>\n</tr>\n<tr>\n<td>{«p»}?</td><td>\nEvaluate semantic predicate «p». Do not continue parsing past a predicate if «p» evaluates to false at runtime. Predicates encountered during prediction, when ANTLR distinguishes between alternatives, enable or disable the alternative(s) surrounding the predicate(s).</td>\n</tr>\n<tr>\n<td>.</td><td>\nMatch any single token except for the end of file token. The “dot” operator is called the wildcard.</td>\n</tr>\n</table>\n\nWhen you want to match everything but a particular token or set of tokens, use the `~` “not” operator. This operator is rarely used in the parser but is available. `~INT` matches any token except the `INT` token. `~','` matches any token except the comma. `~(INT|ID)` matches any token except an INT or an ID.\n\nToken, string literal, and semantic predicate rule elements can take options. See Rule Element Options.\n\n## Subrules\n\nA rule can contain alternative blocks called subrules (as allowed in Extended BNF Notation: EBNF). A subrule is like a rule that lacks a name and is enclosed in parentheses. Subrules can have one or more alternatives inside the parentheses. Subrules cannot define attributes with locals and returns like rules can. There are four kinds of subrules (x, y, and z represent grammar fragments):\n\n<table>\n<tr>\n<th>Syntax</th><th>Description</th>\n</tr>\n<tr>\n<td><img src=images/xyz.png></td><td>(x|y|z).\nMatch any alternative within the subrule exactly once. Example:\n<br>\n<tt>\nreturnType : (type | 'void') ;\n</tt>\n</td>\n</tr>\n<tr>\n<td><img src=images/xyz_opt.png></td><td>(x|y|z)?\nMatch nothing or any alternative within subrule. Example:\n<br>\n<tt>\t\nclassDeclaration\n    : 'class' ID (typeParameters)? ('extends' type)?\n      ('implements' typeList)?\n \t   classBody\n    ;\n</tt>\n<tr>\n<td><img src=images/xyz_star.png></td><td>(x|y|z)*\nMatch an alternative within subrule zero or more times. Example:\n<br>\n<tt>\nannotationName : ID ('.' ID)* ;\n</tt>\n</tr>\n<tr>\t\n<td><img src=images/xyz_plus.png></td><td>(x|y|z)+\nMatch an alternative within subrule one or more times. Example:\n<br>\n<tt>\nannotations : (annotation)+ ;\n</tt>\n</td>\n</tr>\n</table>\n\nYou can suffix the `?`, `*`, and `+` subrule operators with the nongreedy operator, which is also a question mark: `??`, `*?`, and `+?`. See Section 15.6, Wildcard Operator and Nongreedy Subrules.\n\nAs a shorthand, you can omit the parentheses for subrules composed of a single alternative with a single rule element reference. For example, `annotation+` is the same as `(annotation)+` and `ID+` is the same as `(ID)+`. Labels also work with the shorthand. `ids+=INT+` make a list of `INT` token objects.\n\n## Catching Exceptions\n\nWhen a syntax error occurs within a rule, ANTLR catches the exception, reports the error, attempts to recover (possibly by consuming more tokens), and then returns from the rule. Every rule is wrapped in a `try/catch/finally` statement:\n\n```\nvoid r() throws RecognitionException {\n \ttry {\n \t\trule-body\n \t}\n \tcatch (RecognitionException re) {\n\t \t_errHandler.reportError(this, re);\n\t \t_errHandler.recover(this, re);\n \t}\n \tfinally {\n\t\texitRule();\n \t}\n}\n```\n\nIn Section 9.5, Altering ANTLR’s Error Handling Strategy, we saw how to use a strategy object to alter ANTLR’s error handling. Replacing the strategy changes the strategy for all rules, however. To alter the exception handling for a single rule, specify an exception after the rule definition:\n\n```\nr : ...\n  ;\n  catch[RecognitionException e] { throw e; }\n```\n\nThat example shows how to avoid default error reporting and recovery. r rethrows the exception, which is useful when it makes more sense for a higher-level rule to report the error. Specifying any exception clause, prevents ANTLR from generating a clause to handle `RecognitionException`.\n\nYou can specify other exceptions as well:\n\n```\nr : ...\n  ;\n  catch[FailedPredicateException fpe] { ... }\n  catch[RecognitionException e] { ... }\n```\n\nThe code snippets inside curly braces and the exception “argument” actions must be written in the target language; Java, in this case.\nWhen you need to execute an action even if an exception occurs, put it into the `finally` clause:\n\n```\nr : ...\n  ;\n  // catch blocks go first\n  finally { System.out.println(\"exit rule r\"); }\n```\n\nThe finally clause executes right before the rule triggers `exitRule` before returning. If you want to execute an action after the rule finishes matching the alternatives but before it does its cleanup work, use an `after` action.\n\nHere’s a complete list of exceptions:\n\n<table>\n<tr>\n<th>Exception name</th><th>Description</th>\n</tr>\n<tr>\n<td>RecognitionException</td><td>\nThe superclass of all exceptions thrown by an ANTLR-generated recognizer. It’s a subclass of RuntimeException to avoid the hassles of checked exceptions. This exception records where the recognizer (lexer or parser) was in the input, where it was in the ATN (internal graph data structure representing the grammar), the rule invocation stack, and what kind of problem occurred.</td>\n</tr>\n<tr>\n<td>NoViableAltException</td><td>\nIndicates that the parser could not decide which of two or more paths to take by looking at the remaining input. This exception tracks the starting token of the offending input and also knows where the parser was in the various paths when the error occurred.</td>\n</tr>\n<tr>\n<td>LexerNoViableAltException</td><td>\nThe equivalent of NoViableAltException but for lexers only.</td>\n</tr>\n<tr>\n<td>InputMismatchException</td><td>\nThe current input Token does not match what the parser expected.</td>\n</tr>\n<tr>\n<td>FailedPredicateException</td><td>\nA semantic predicate that evaluates to false during prediction renders the surrounding alternative nonviable. Prediction occurs when a rule is predicting which alternative to take. If all viable paths disappear, parser will throw NoViableAltException. This predicate gets thrown by the parser when a semantic predicate evaluates to false outside of prediction, during the normal parsing process of matching tokens and calling rules.</td>\n</tr>\n</table>\n\n## Rule Attribute Definitions\n\nThere are a number of action-related syntax elements associated with rules to be aware of. Rules can have arguments, return values, and local variables just like functions in a programming language. (Rules can have actions embedded among the rule elements, as we’ll see in Section 15.4, Actions and Attributes.) ANTLR collects all of the variables you define and stores them in the rule context object. These variables are usually called attributes. Here’s the general syntax showing all possible attribute definition locations:\n\n```\nrulename[args] returns [retvals] locals [localvars] : ... ;\n```\n\nThe attributes defined within those [...] can be used like any other variable. Here is a sample rule that copies parameters to return values:\n\n```\n// Return the argument plus the integer value of the INT token\nadd[int x] returns [int result] : '+=' INT {$result = $x + $INT.int;} ;\n```\n\nThe args, locals, and return `[...]` are generally in the target language but with some constraints. The `[...]` string is a comma-separated list of declarations either with prefix or postfix type notation or no-type notation. The elements can have initializer such as `[int x = 32, float y]` but don't go too crazy as we are parsing this generic text manually in [ScopeParser](https://github.com/antlr/antlr4/blob/master/tool/src/org/antlr/v4/parse/ScopeParser.java).  \n\n* Java, CSharp, C++ use `int x` notation but C++ must use a slightly altered notation for array references, `int[] x`, to fit in the *type* *id* syntax.\n* Go and Swift give the type after the variable name, but Swift requires a `:` in between. Go `i int`, Swift `i:int`.  For Go target, you must either use `int i` or `i:int`.\n* Python and JavaScript don't specify static types so actions are just identifier lists such as `[i,j]`.\n\nTechnically any target could use either notation. For examples, see [TestScopeParsing](https://github.com/antlr/antlr4/blob/master/tool-testsuite/test/org/antlr/v4/test/tool/TestScopeParsing.java).\n\nAs with the grammar level, you can specify rule-level named actions. For rules, the valid names are `init` and `after`. As the names imply, parsers execute init actions immediately before trying to match the associated rule and execute after actions immediately after matching the rule. ANTLR after actions do not execute as part of the finally code block of the generated rule function. Use the ANTLR finally action to place code in the generated rule function finally code block.\n\nThe actions come after any argument, return value, or local attribute definition actions. The `row` rule preamble from Section 10.2, Accessing Token and Rule Attributes illustrates the syntax nicely:\nactions/CSV.g4\n\n```\n/** Derived from rule \"row : field (',' field)* '\\r'? '\\n' ;\" */\nrow[String[] columns]\n   returns [Map<String,String> values]\n   locals [int col=0]\n\t@init {\n\t$values = new HashMap<String,String>();\n\t}\n\t@after {\n\tif ($values!=null && $values.size()>0) {\n\tSystem.out.println(\"values = \"+$values);\n\t}\n\t}\n\t: ...\n\t;\n```\n\nRule row takes argument columns, returns values, and defines local variable col. The “actions” in square brackets are copied directly into the generated code:\n\n```java\npublic class CSVParser extends Parser {\n\t...\n\tpublic static class RowContext extends ParserRuleContext {\n\t\tpublic String [] columns;\n\t\tpublic Map<String,String> values;\n\t\tpublic int col=0;\n\t\t...\n\t}\n\t...\n}\n```\n\nThe generated rule functions also specify the rule arguments as function arguments, but they are quickly copied into the local RowContext object:\n\n```java\npublic class CSVParser extends Parser {\n \t...\n \tpublic final RowContext row(String [] columns) throws RecognitionException {\n\t \tRowContext _localctx = new RowContext(_ctx, 4, columns);\n\t \tenterRule(_localctx, RULE_row);\n\t \t...\n \t}\n \t...\n}\n```\n\nANTLR tracks nested `[...]` within the action so that `String[]` columns is parsed properly. It also tracks angle brackets so that commas within generic type parameters do not signify the start of another attribute. `Map<String,String>` values is one attribute definition.\n\nThere can be multiple attributes in each action, even for return values. Use a comma to separate attributes within the same action:\n\n```\na[Map<String,String> x, int y] : ... ;\n```\n\nANTLR interprets that action to define two arguments, x and y:\n\n```java\npublic final AContext a(Map<String,String> x, int y)\n\tthrows RecognitionException\n{\n\tAContext _localctx = new AContext(_ctx, 0, x, y);\n\tenterRule(_localctx, RULE_a);\n\t...\n}\n```\n\n## Start Rules and EOF\n\nA start rule is the rule engaged first by the parser; it’s the rule function called by the language application. For example, a language application that parsed to Java code might call `parser.compilationUnit()` for a `JavaParser` object called `parser`. Any rule in the grammar can act as a start rule.\n\nStart rules don’t necessarily consume all of the input. They consume only as much input as needed to match an alternative of the rule. For example, consider the following rule that matches one, two, or three tokens, depending on the input.\n\n```\ns : ID\n  | ID '+'\n  | ID '+' INT\n  ;\n```\n\nUpon `a+3`, rule `s` matches the third alternative. Upon `a+b`, it matches the second alternative and ignores the final `b` token. Upon `a b`, it matches the first alternative, ignoring the `b` token. The parser does not consume the complete input in the latter two cases because rule `s` doesn’t explicitly say that end of file must occur after matching an alternative of the rule.\n\nThis default functionality is very useful for building things like IDEs. Imagine the IDE wanting to parse a method somewhere in the middle of a big Java file. Calling rule `methodDeclaration` should try to match just a method and ignore whatever comes next.\n\nOn the other hand, rules that describe entire input files should reference special predefined-token `EOF`. If they don’t, you might scratch your head for a while wondering why the start rule doesn’t report errors for any input no matter what you give it. Here’s a rule that’s part of a grammar for reading configuration files:\n\n```\nconfig : element*; // can \"match\" even with invalid input.\n```\n\nInvalid input would cause `config` to return immediately without matching any input and without reporting an error. Here’s the proper specification:\n\n```\nfile : element* EOF; // don't stop early. must match all input\n```\n"
  },
  {
    "path": "doc/parsing-binary-files.md",
    "content": "# Parsing Binary Files\n\nParsing binary files is no different than parsing character-based files except that the \"characters\" are actually bytes not 16-bit unsigned short unicode characters.  From a lexer/parser point of view, there is no difference except that the characters are likely not printable.  If you want to match a special 2-byte marker 0xCA then 0xFE, the following rule is sufficient.\n\n```\nMARKER : '\\u00CA' '\\u00FE' ;\n```\n\nThe parser of course would refer to that token like any other token.\n\nHere is a sample grammar for use with the code snippets below.\n\n```\ngrammar IP;\n\nfile : ip+ (MARKER ip)* ;\n\nip : BYTE BYTE BYTE BYTE ;\n\nMARKER : '\\u00CA' '\\u00FE' ;\nBYTE : '\\u0000'..'\\u00FF' ;\n```\n\nNotice that `BYTE` is using a range operator to match anything between 0 and 255. We can't use character classes like `[a-z]` naturally because we are not parsing character codes.  All character specifiers must have `00` as their upper byte. E.g., `\\uCAFE` is not a valid character because that 16-bit value will never be created from the input stream (bytes only remember).\n\nIf there are actual characters like `$` or `!` encoded as bytes in the binary file, you can refer to them via literals like `'$'` as you normally would. See `'.'` in the grammar.\n \n## Binary streams\n\nThere are many targets now so I'm not sure exactly how they process text files but most targets will pull in text per the machine's locale. Much of the time this will mean UTF-8 encoding of text converted to 16-bit Unicode. ANTLR's lexers operate on `int` so we can handle any kind of character you want to send in that fits in `int`.\n\nOnce the lexer gets an input stream, it doesn't care whether the characters come from / represent bytes or actual Unicode characters.\n\nLet's get a binary file called `ips` and put it in our resources directory:\n\n```java\npublic class WriteBinaryFile {\n\tpublic static final byte[] bytes = {\n\t\t(byte)172, 0, 0, 1, (byte)0xCA, (byte)0xFE,\n\t\t(byte)10, 10, 10, 1, (byte)0xCA, (byte)0xFE,\n\t\t(byte)10, 10, 10, 99\n\t};\n\n\tpublic static void main(String[] args) throws IOException {\n\t\tFiles.write(new File(\"/tmp/ips\").toPath(), bytes);\n\t}\n}\n```\n\nNow we need to create a stream of bytes satisfactory to ANTLR, which is as simple as:\n\n```java\nCharStream bytesAsChar = CharStreams.fromFileName(\"/tmp/ips\", StandardCharsets.ISO_8859_1);\n```\n\nThe `ISO-8859-1` encoding is just the 8-bit char encoding for LATIN-1, which effectively tells the stream to treat each byte as a character. That's what we want. Then we have the usual test rig:\n\n\n```java\n//ANTLRFileStream bytesAsChar = new ANTLRFileStream(\"/tmp/ips\", \"ISO-8859-1\"); DEPRECATED in 4.7\nCharStream bytesAsChar = CharStreams.fromFileName(\"/tmp/ips\", StandardCharsets.ISO_8859_1);\nIPLexer lexer = new IPLexer(bytesAsChar);\nCommonTokenStream tokens = new CommonTokenStream(lexer);\nIPParser parser = new IPParser(tokens);\nParseTree tree = parser.file();\nIPBaseListener listener = new MyIPListener();\nParseTreeWalker.DEFAULT.walk(listener, tree);\n```\n\nHere is the listener:\n\n```java\nclass MyIPListener extends IPBaseListener {\n\t@Override\n\tpublic void exitIp(IPParser.IpContext ctx) {\n\t\tList<TerminalNode> octets = ctx.BYTE();\n\t\tshort[] ip = new short[4];\n\t\tfor (int i = 0; i<octets.size(); i++) {\n\t\t\tString oneCharStringHoldingOctet = octets.get(i).getText();\n\t\t\tip[i] = (short)oneCharStringHoldingOctet.charAt(0);\n\t\t}\n\t\tSystem.out.println(Arrays.toString(ip));\n\t}\n}\n```\n\nWe can't just print out the text because we are not reading in text. We need to emit each byte as a decimal value. The output should be the following when you run the test code:\n\n```\n[172, 0, 0, 1]\n[10, 10, 10, 1]\n[10, 10, 10, 99]\n```\n\n## Custom stream\n\n(*ANTLRFileStream was deprecated in 4.7*)\n\nIf you want to play around with the stream, you can. Here's an example that alters how \"text\" is computed from the byte stream (which changes how tokens print out their text as well):\n\n```java\n/** make a stream treating file as full of single unsigned byte characters */\nclass BinaryANTLRFileStream extends ANTLRFileStream {\n\tpublic BinaryANTLRFileStream(String fileName) throws IOException {\n\t\tsuper(fileName, \"ISO-8859-1\");\n\t}\n\n\t/** Print the decimal value rather than treat as char */\n\t@Override\n\tpublic String getText(Interval interval) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tint start = interval.a;\n\t\tint stop = interval.b;\n\t\tif(stop >= this.n) {\n\t\t\tstop = this.n - 1;\n\t\t}\n\n\t\tfor (int i = start; i<=stop; i++) {\n\t\t\tint v = data[i];\n\t\t\tbuf.append(v);\n\t\t}\n\t\treturn buf.toString();\n\t}\n}\n```\n\nThe new test code starts out like this:\n\n```java\nANTLRFileStream bytesAsChar = new BinaryANTLRFileStream(\"/tmp/ips\");\nIPLexer lexer = new IPLexer(bytesAsChar);\n...\n```\n\nThis simplifies our listener then:\n\n```java\nclass MyIPListenerCustomStream extends IPBaseListener {\n\t@Override\n\tpublic void exitIp(IPParser.IpContext ctx) {\n\t\tList<TerminalNode> octets = ctx.BYTE();\n\t\tSystem.out.println(octets);\n\t}\n}\n```\n\nYou should get this enhanced output:\n\n```\n[172(0xAC), 0(0x0), 0(0x0), 1(0x1)]\n[10(0xA), 10(0xA), 10(0xA), 1(0x1)]\n[10(0xA), 10(0xA), 10(0xA), 99(0x63)]\n```\n\n## Error handling in binary files\n\nError handling proceeds exactly like any other parser. For example, let's alter the binary file so that it is missing one of the 0's in the first IP address:\n\n```java\npublic static final byte[] bytes = {\n\t(byte)172, 0, 1, (byte)0xCA, (byte)0xFE, // OOOPS\n\t(byte)10, 10, 10, 1, (byte)0xCA, (byte)0xFE,\n\t(byte)10, 10, 10, 99\n};\n```\n\nRunning the original test case gives us:\n\n```\nline 1:4 extraneous input '.' expecting BYTE\nline 1:6 mismatched input 'Êþ' expecting '.'\n[172, 0, 1, 0]\n[10, 10, 10, 1]\n[10, 10, 10, 99]\n```\n\nThat `'Êþ'` is just to the character representation of two bytes 0xCA and 0xFE. Using the enhanced binary stream, we see:\n\n```\nline 1:4 extraneous input '46(0x2E)' expecting BYTE\nline 1:6 mismatched input '202(0xCA)254(0xFE)' expecting '.'\n[172(0xAC), 0(0x0), 1(0x1)]\n[10(0xA), 10(0xA), 10(0xA), 1(0x1)]\n[10(0xA), 10(0xA), 10(0xA), 99(0x63)]\n```"
  },
  {
    "path": "doc/php-target.md",
    "content": "# ANTLR4 Runtime for PHP\n\n### First steps\n\n#### 1. Install ANTLR4\n\n[The getting started guide](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md) \nshould get you started.\n\n#### 2. Install the PHP ANTLR runtime\n\nEach target language for ANTLR has a runtime package for running parser \ngenerated by ANTLR4. The runtime provides a common set of tools for using your parser.\n\nInstall the runtime with Composer:\n\n```bash\ncomposer require antlr/antlr4-php-runtime\n```\n\n#### 3. Generate your parser\n\nYou use the ANTLR4 \"tool\" to generate a parser. These will reference the ANTLR \nruntime, installed above.\n\nSuppose you're using a UNIX system and have set up an alias for the ANTLR4 tool \nas described in [the getting started guide](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md). \nTo generate your PHP parser, run the following command:\n\n```bash\nantlr4 -Dlanguage=PHP MyGrammar.g4\n```\n\nFor a full list of antlr4 tool options, please visit the \n[tool documentation page](https://github.com/antlr/antlr4/blob/master/doc/tool-options.md).\n\n### Complete example\n\nSuppose you're using the JSON grammar from https://github.com/antlr/grammars-v4/tree/master/json.\n\nThen, invoke `antlr4 -Dlanguage=PHP JSON.g4`. The result of this is a \ncollection of `.php` files in the `parser` directory including:\n```\nJsonParser.php\nJsonBaseListener.php\nJsonLexer.php\nJsonListener.php\n```\n\nAnother common option to the ANTLR tool is `-visitor`, which generates a parse \ntree visitor, but we won't be doing that here. For a full list of antlr4 tool \noptions, please visit the [tool documentation page](tool-options.md).\n\nWe'll write a small main func to call the generated parser/lexer \n(assuming they are separate). This one writes out the encountered \n`ParseTreeContext`'s:\n\n```php\n<?php\n\nnamespace JsonParser;\n\nuse Antlr\\Antlr4\\Runtime\\CommonTokenStream;\nuse Antlr\\Antlr4\\Runtime\\Error\\Listeners\\DiagnosticErrorListener;\nuse Antlr\\Antlr4\\Runtime\\InputStream;\nuse Antlr\\Antlr4\\Runtime\\ParserRuleContext;\nuse Antlr\\Antlr4\\Runtime\\Tree\\ErrorNode;\nuse Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeListener;\nuse Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeWalker;\nuse Antlr\\Antlr4\\Runtime\\Tree\\TerminalNode;\n\nfinal class TreeShapeListener implements ParseTreeListener {\n    public function visitTerminal(TerminalNode $node) : void {}\n    public function visitErrorNode(ErrorNode $node) : void {}\n    public function exitEveryRule(ParserRuleContext $ctx) : void {}\n\n    public function enterEveryRule(ParserRuleContext $ctx) : void {\n        echo $ctx->getText();\n    }\n}\n\n$input = InputStream::fromPath($argv[1]);\n$lexer = new JSONLexer($input);\n$tokens = new CommonTokenStream($lexer);\n$parser = new JSONParser($tokens);\n$parser->addErrorListener(new DiagnosticErrorListener());\n$tree = $parser->json();\n\nParseTreeWalker::default()->walk(new TreeShapeListener(), $tree);\n```\n\nCreate a `example.json` file:\n```json\n{\"a\":1}\n```\n\nParse the input file:\n\n```\nphp json.php example.json\n```\n\nThe expected output is:\n\n```\n{\"a\":1}\n{\"a\":1}\n\"a\":1\n1\n```\n"
  },
  {
    "path": "doc/predicates.md",
    "content": "# Semantic Predicates\n\nSemantic predicates, `{...}?`, are boolean expressions written in the target language that indicate the validity of continuing the parse along the path \"guarded\" by the predicate. Predicates can appear anywhere within a parser rule just like actions can, but only those appearing on the left edge of alternatives can affect prediction (choosing between alternatives).  This section provides all of the fine print regarding the use of semantic predicates in parser and lexer rules. Let's start out by digging deeper into how the parser incorporates predicates into parsing decisions.\n\n## Making Predicated Parsing Decisions\n\nANTLR's general decision-making strategy is to find all viable alternatives and then ignore the alternatives guarded with predicates that currently evaluate to false. (A viable alternative is one that matches the current input.) If more than one viable alternative remains, the parser chooses the alternative specified first in the decision.\n\nConsider a variant of C++ where array references also use parentheses instead of square brackets. If we only predicate one of the alternatives, we still have an ambiguous decision in expr:\n\n```\nexpr: ID '(' expr ')' // array reference (ANTLR picks this one)\n \t| {istype()}? ID '(' expr ')' // ctor-style typecast\n \t| ID '(' expr ')' // function call\n \t;\n```\n\nIn this case, all three alternatives are viable for input `x(i)`. When `x` is not a type name, the predicate evaluates to false, leaving only the first and third alternatives as possible matches for expr. ANTLR automatically chooses the first alternative matching the array reference to resolve the ambiguity. Leaving ANTLR with more than one viable alternative because of too few predicates is probably not a good idea. It's best to cover n viable alternatives with at least n-1 predicates. In other words, don't build rules like expr with too few predicates.\n\nSometimes, the parser finds multiple visible predicates associated with a single choice. No worries. ANTLR just combines the predicates with appropriate logical operators to conjure up a single meta-predicate on-the-fly.\n\nFor example, the decision in rule `stat` joins the predicates from both alternatives of expr with the `||` operator to guard the second stat alternative:\n\n```\nstat: decl | expr ;\ndecl: ID ID ;\nexpr: {istype()}? ID '(' expr ')' // ctor-style typecast\n \t| {isfunc()}? ID '(' expr ')' // function call\n \t;\n```\n\nThe parser will only predict an expr from stat when `istype()||isfunc()` evaluates to true. This makes sense because the parser should only choose to match an expression if the upcoming `ID` is a type name or function name. It wouldn't make sense to just test one of the predicates in this case. Note that, when the parser gets to `expr` itself, the parsing decision tests the predicates individually, one for each alternative.\n\nIf multiple predicates occur in a sequence, the parser joins them with the `&&` operator. For example, consider changing `stat` to include a predicate before the call `toexpr`:\n\n```\nstat: decl | {java5}? expr ;\n```\n\nNow, the parser would only predict the second alternative if `java5&&(istype()||isfunc())` evaluated to true.\n\nTurning to the code inside the predicates themselves now, keep in mind the following guidelines.\n\nEven when the parser isn't making decisions, predicates can deactivate alternatives, causing rules to fail. This happens when a rule only has a single alternative. There is no choice to make, but ANTLR evaluates the predicate as part of the normal parsing process, just like it does for actions. That means that the following rule always fails to match.\n\n```\nprog: {false}? 'return' INT ; // throws FailedPredicateException\n```\n\nANTLR converts `{false}?` in the grammar to a conditional in the generated parser:\n\n```\nif ( !false ) throw new FailedPredicateException(...);\n```\n\nSo far, all of the predicates we've seen have been visible and available to the prediction process, but that's not always the case.\n\n## Finding Visible Predicates\n\nThe parser will not evaluate predicates during prediction that occur after an action or token reference. Let's think about the relationship between actions and predicates first.\n\nANTLR has no idea what's inside the raw code of an action and so it must assume any predicate could depend on side effects of that action. Imagine an action that computed value `x` and a predicate that tested `x`. Evaluating that predicate before the action executed to create `x` would violate the implied order of operations within the grammar.\n\nMore importantly, the parser can't execute actions until it has decided which alternative to match. That's because actions have side effects and we can't undo things like print statements. For example, in the following rule, the parser can't execute the action in front of the `{java5}?` predicate before committing to that alternative.\n\n```\n@members {boolean allowgoto=false;}\nstat: {System.out.println(\"goto\"); allowgoto=true;} {java5}? 'goto' ID ';'\n \t| ...\n \t;\n```\n\nIf we can't execute the action during prediction, we shouldn't evaluate the `{java5}?` predicate because it depends on that action.\n\nThe prediction process also can't see through token references. Token references have the side effect of advancing the input one symbol. A predicate that tested the current input symbol would find itself out of sync if the parser shifted it over the token reference. For example, in the following grammar, the predicates expect `getCurrentToken` to return an `ID` token.\n\n```\nstat: '{' decl '}'\n \t| '{' stat '}'\n \t;\ndecl: {istype(getCurrentToken().getText())}? ID ID ';' ;\nexpr: {isvar(getCurrentToken().getText())}? ID ;\n```\n\nThe decision in stat can't test those predicates because, at the start of stat, the current token is a left curly. To preserve the semantics, ANTLR won't test the predicates in that decision.\n\nVisible predicates are those that prediction encounters before encountering an action or token. The prediction process ignores nonvisible predicates, treating them as if they don't exist.\n\nIn rare cases, the parser won't be able to use a predicate, even if it's visible to a particular decision. That brings us to our next fine print topic.\n\n## Using Context-Dependent Predicates\n\nA predicate that depends on a parameter or local variable of the surrounding rule, is considered a context-dependent predicate. Clearly, we can only evaluate such predicates within the rules in which they're defined. For example, it makes no sense for the decision in prog below to test context-dependent predicate `{$i<=5}?`. That `$i` local variable is not even defined in `prog`.\n\n```\nprog: vec5\n \t| ...\n \t;\nvec5\nlocals [int i=1]\n \t: ( {$i<=5}? INT {$i++;} )* // match 5 INTs\n \t;\n```\n\nANTLR ignores context-dependent predicates that it can't evaluate in the proper context. Normally the proper context is simply the rule defining the predicate, but sometimes the parser can't even evaluate a context-dependent predicate from within the same rule! Detecting these cases is done on-the-fly at runtime during adaptive LL(*) prediction.\n\nFor example, prediction for the optional branch of the else subrule in stat below \"falls off\" the end of stat and continues looking for symbols in the invoking prog rule.\n\n```\nprog: stat+ ; // stat can follow stat\nstat\nlocals [int i=0]\n \t: {$i==0}? 'if' expr 'then' stat {$i=5;} ('else' stat)?\n \t| 'break' ';'\n \t;\n```\n\nThe prediction process is trying to figure out what can follow an if statement other than an else clause. Since the input can have multiple stats in a row, the prediction for the optional branch of the else subrule reenters stat. This time, of course, it gets a new copy of `$i` with a value of 0, not 5. ANTLR ignores context-dependent predicate `{$i==0}?` because it knows that the parser isn't in the original stat call. The predicate would test a different version of `$i` so the parser can't evaluate it.\n\nThe fine print for predicates in the lexer more or less follow these same guidelines, except of course lexer rules can't have parameters and local variables. Let's look at all of the lexer-specific guidelines in the next section.\n\n## Predicates in Lexer Rules\n\nIn parser rules, predicates must appear on the left edge of alternatives to aid in alternative prediction. Lexers, on the other hand, prefer predicates on the right edge of lexer rules because they choose rules after seeing a token's entire text. Predicates in lexer rules can technically be anywhere within the rule. Some positions might be more or less efficient than others; ANTLR makes no guarantees about the optimal spot. A predicate in a lexer rule might be executed multiple times even during a single token match. You can embed multiple predicates per lexer rule and they are evaluated as the lexer reaches them during matching.\n\nLoosely speaking, the lexer's goal is to choose the rule that matches the most input characters. At each character, the lexer decides which rules are still viable. Eventually, only a single rule will be still viable. At that point, the lexer creates a token object according the rule's token type and matched text.\n\nSometimes the lexer is faced with more than a single viable matching rule. For example, input enum would match an `ENUM` rule and an `ID` rule. If the next character after enum is a space, neither rule can continue. The lexer resolves the ambiguity by choosing the viable rule specified first in the grammar. That's why we have to place keyword rules before an identifier rule like this:\n\n```\nENUM : 'enum' ;\nID : [a-z]+ ;\n```\n\nIf, on the other hand, the next character after input `enum` is a letter, then only `ID` is viable.\n\nPredicates come into play by pruning the set of viable lexer rules. When the lexer encounters a false predicate, it deactivates that rule just like parsers deactivate alternatives with false predicates.\n\nLike parser predicates, lexer predicates can't depend on side effects from lexer actions. That said, the predicate can depend on a side effect of an action that occured during the recognition of the previous token. That's because actions can only execute after the lexer positively identifies the rule to match. Since predicates are part of the rule selection process, they can't rely on action side effects created by actions in currently-prospective rules. Lexer actions must appear after predicates in lexer rules. As an example, here's another way to match enum as a keyword in the lexer:\n\n```\nENUM: [a-z]+ {getText().equals(\"enum\")}?\n\t   {System.out.println(\"enum!\");}\n    ;\nID  : [a-z]+ {System.out.println(\"ID \"+getText());} ;\n```\n\nThe print action in `ENUM` appears last and executes only if the current input matches `[a-z]+` and the predicate is true. Let's build and test `Enum3` to see if it distinguishes between enum and an identifier:\n\n```bash\n$ antlr4 Enum3.g4\n$ javac Enum3.java\n$ grun Enum3 tokens\n=> \tenum abc\n=> \tEOF\n<= \tenum!\n \tID abc\n```\n\nThat works great, but it's really just for instructional purposes. It's easier to understand and more efficient to match enum keywords with a simple rule like this:\n\n```\nENUM : 'enum' ;\n```\n\nHere's another example of a predicate.  It's important to note that the predicate is evaluated before the action because actions are only executed if the lexer rule matches. The actions are not executed in line; they are collected and executed en mass later.\n\n```\nINDENT : [ \\t]+ {System.out.println(\"INDENT\")>} {this.getCharPositionInLine()==0}? ;\n```\n\nFor more information on how actions and predicates operate in the lexer, see [Lexer actions and semantic predicates are executed out of order](https://github.com/antlr/antlr4/issues/3611) and [Lexer.getCharIndex() return value not behaving as expected](https://github.com/antlr/antlr4/issues/3606). The lexer rule that will not work as expected is:\n\n```\nStuff : ( 'a'+ {count++;} | 'b') 'c' 'd' {count == 3}? ;\n```\n\nThe `count++` code we'll not execute until after `Stuff` has been recognized (assuming count!=3)."
  },
  {
    "path": "doc/python-target.md",
    "content": "# Python 3\n\n## Requirements\n\nYou will need to install Python and Pip, version 3.6 or better.\nSee https://www.python.org/downloads/\nand https://www.geeksforgeeks.org/how-to-install-pip-on-windows/.\n\n## A simple example targeting Python3\n\nAn example of a parser for the Python3 target consists of the following files.\n* An Antlr4 grammar, e.g., Expr.g4:\n    ```antlr\n    grammar Expr;\n    start_ : expr (';' expr)* EOF;\n    expr : atom | ('+' | '-') expr | expr '**' expr | expr ('*' | '/') expr | expr ('+' | '-') expr | '(' expr ')' | atom ;\n    atom : INT ;\n    INT : [0-9]+ ;\n    WS : [ \\t\\n\\r]+ -> skip ;\n    ```\n* Driver.py:\nThe driver code opens a file, creates a lexer, token stream,\nand parser, then calls the parser.\n    ```python\n    import sys\n    from antlr4 import *\n    from ExprLexer import ExprLexer\n    from ExprParser import ExprParser\n    from VisitorInterp import VisitorInterp\n\n    def main(argv):\n        input_stream = FileStream(argv[1])\n        lexer = ExprLexer(input_stream)\n        stream = CommonTokenStream(lexer)\n        parser = ExprParser(stream)\n        tree = parser.start_()\n\n    if __name__ == '__main__':\n        main(sys.argv)\n    ```\n* requirements.txt:\nThis file contains a list of the\nrequired packages for the program. Required\npackages are downloaded by `pip`. The file\nmust include a reference to the Antlr Python3 runtime.\n    ```\n    antlr4-python3-runtime==4.13.0\n    ```\n* A build script, e.g., build.sh:\nYou should provide a script that builds the program.\n    ```\n    pip install -r requirements.txt\n    antlr4 -Dlanguage=Python3 Expr.g4\n    ```\n_It is vital that the versions for the\nAntlr tool used to generate the parser\nand the Antlr Python3 runtime match.\nE.g., 4.13.0. Using build files will help\neliminate common errors from happening._\n\n_For a list of antlr4 tool options, please visit [ANTLR Tool Command Line Options](https://github.com/antlr/antlr4/blob/master/doc/tool-options.md)._\n* Input, e.g., input.txt:\n    ```\n    -(1 + 2)/3;\n    1;\n    2+3;\n    8*9\n    ```\n* A run script, which runs your program.\n    ```\n    python Driver.py input.txt\n    ```\n\n## Parse tree traversal\n\nTree traversal is used to implement\n[static](https://en.wikipedia.org/wiki/Static_program_analysis) or [dynamic](https://en.wikipedia.org/wiki/Dynamic_program_analysis)\nprogram analysis.\nAntlr generates two types of tree traversals: visitors and listeners.\n\nUnderstanding when to choose a visitor versus a listener is a good idea.\nFor further information, see https://tomassetti.me/listeners-and-visitors/.\n\nA visitor is the best choice when computing only a single [synthesized attribute](https://en.wikipedia.org/wiki/Attribute_grammar#Synthesized_attributes)\nor when you want to control the order of parse tree nodes visited.\nAlternatively, a listener is the best choice when computing both synthesized\nand [inherited attributes](https://en.wikipedia.org/wiki/Attribute_grammar#Inherited_attributes).\n\nIn many situations, they are interchangeable.\n\n### Visitors\n\nAntlr visitors generally implement a post-order tree walk. If you write\n`visit...` methods, the method must contain code to visit the children\nin the order you want. For a post-order tree walk, visit the children first.\n\nTo implement a visitor, add the `-visitor` option to the `antlr4` command.\nCreate a class that inherits from the generated visitor,\nthen add `visit` methods that implement the analysis. Your driver code\nshould call the `visit()` method for the root of the parse tree.\n\nFor example, the following code implements an expression evaluator for the Expr.g4 grammar using a visitor.\n\n* Driver.py:\n    ```python\n    import sys\n    from antlr4 import *\n    from ExprLexer import ExprLexer\n    from ExprParser import ExprParser\n    from VisitorInterp import VisitorInterp\n\n    def main(argv):\n        input_stream = FileStream(argv[1])\n        lexer = ExprLexer(input_stream)\n        stream = CommonTokenStream(lexer)\n        parser = ExprParser(stream)\n        tree = parser.start_()\n        if parser.getNumberOfSyntaxErrors() > 0:\n            print(\"syntax errors\")\n        else:\n            vinterp = VisitorInterp()\n            vinterp.visit(tree)\n\n    if __name__ == '__main__':\n        main(sys.argv)\n    ```\n* VisitorInterp.py:\n    ```python\n    import sys\n    from antlr4 import *\n    from ExprParser import ExprParser\n    from ExprVisitor import ExprVisitor\n\n    class VisitorInterp(ExprVisitor):\n        def visitAtom(self, ctx:ExprParser.AtomContext):\n            return int(ctx.getText())\n\n        def visitExpr(self, ctx:ExprParser.ExprContext):\n            if ctx.getChildCount() == 3:\n                if ctx.getChild(0).getText() == \"(\":\n                    return self.visit(ctx.getChild(1))\n                op = ctx.getChild(1).getText()\n                v1 = self.visit(ctx.getChild(0))\n                v2 = self.visit(ctx.getChild(2))\n                if op == \"+\":\n                    return v1 + v2\n                if op == \"-\":\n                    return v1 - v2\n                if op == \"*\":\n                    return v1 * v2\n                if op == \"/\":\n                    return v1 / v2\n                return 0\n            if ctx.getChildCount() == 2:\n                opc = ctx.getChild(0).getText()\n                if opc == \"+\":\n                    return self.visit(ctx.getChild(1))\n                if opc == \"-\":\n                    return - self.visit(ctx.getChild(1))\n                return 0\n            if ctx.getChildCount() == 1:\n                return self.visit(ctx.getChild(0))\n            return 0\n\n        def visitStart_(self, ctx:ExprParser.Start_Context):\n            for i in range(0, ctx.getChildCount(), 2):\n                print(self.visit(ctx.getChild(i)))\n            return 0\n    ```\n\n### Listeners\n\nAntlr listeners perform an LR tree traversal. `enter` and `exit` methods are\ncalled during the tranversal. A parse tree node is visited twice, first for\nthe `enter` method, then the `exit` method after all children have been walked.\n\nTo implement a listener, add the `-listener` option to the `antlr4` command.\nAdd a class that inherits from the generated listener\nwith code that implements the analysis.\n\nThe following example implements an expression evaluator using a listener.\n\n* Driver.py:\n    ```python\n    import sys\n    from antlr4 import *\n    from ExprLexer import ExprLexer\n    from ExprParser import ExprParser\n    from ListenerInterp import ListenerInterp\n\n    def main(argv):\n        input_stream = FileStream(argv[1])\n        lexer = ExprLexer(input_stream)\n        stream = CommonTokenStream(lexer)\n        parser = ExprParser(stream)\n        tree = parser.start_()\n        if parser.getNumberOfSyntaxErrors() > 0:\n            print(\"syntax errors\")\n        else:\n            linterp = ListenerInterp()\n            walker = ParseTreeWalker()\n            walker.walk(linterp, tree)\n\n    if __name__ == '__main__':\n        main(sys.argv)\n    ```\n    * ListenerInterp.py:\n    ```python\n    import sys\n    from antlr4 import *\n    from ExprParser import ExprParser\n    from ExprListener import ExprListener\n\n    class ListenerInterp(ExprListener):\n        def __init__(self):\n            self.result = {}\n\n        def exitAtom(self, ctx:ExprParser.AtomContext):\n            self.result[ctx] = int(ctx.getText())\n\n        def exitExpr(self, ctx:ExprParser.ExprContext):\n            if ctx.getChildCount() == 3:\n                if ctx.getChild(0).getText() == \"(\":\n                    self.result[ctx] = self.result[ctx.getChild(1)]\n                else:\n                    opc = ctx.getChild(1).getText()\n                    v1 = self.result[ctx.getChild(0)]\n                    v2 = self.result[ctx.getChild(2)]\n                    if opc == \"+\":\n                        self.result[ctx] = v1 + v2\n                    elif opc == \"-\":\n                        self.result[ctx] = v1 - v2\n                    elif opc == \"*\":\n                        self.result[ctx] = v1 * v2\n                    elif opc == \"/\":\n                        self.result[ctx] = v1 / v2\n                    else:\n                        ctx.result[ctx] = 0\n            elif ctx.getChildCount() == 2:\n                opc = ctx.getChild(0).getText()\n                if opc == \"+\":\n                    v = self.result[ctx.getChild(1)]\n                    self.result[ctx] = v\n                elif opc == \"-\":\n                    v = self.result[ctx.getChild(1)]\n                    self.result[ctx] = - v\n            elif ctx.getChildCount() == 1:\n                self.result[ctx] = self.result[ctx.getChild(0)]\n\n        def exitStart_(self, ctx:ExprParser.Start_Context):\n            for i in range(0, ctx.getChildCount(), 2):\n                print(self.result[ctx.getChild(i)])\n    ```\n\nFurther information can be found from the ANTLR 4 definitive guide.\n\n## Examples\n\nThe examples from the ANTLR 4 book converted to Python are [here](https://github.com/jszheng/py3antlr4book).\n\nThere are many examples of grammars that target the Python3 target in the\n[grammars-v4 Github repository](https://github.com/antlr/grammars-v4).\n"
  },
  {
    "path": "doc/releasing-antlr.md",
    "content": "# Cutting an ANTLR Release\n\n## Github\n\n### Get dev merged into master\n\nDo this or make a PR:\n\n```bash\ncd ~/antlr/code/antlr4\ngit checkout master\ngit merge dev\n```\n\n### Turn on DCO Enforcement\n\nAs of 4.10.1, we will be using the Linux DCO not the previous contributors license agreement that required signing the file. Now, we use the DCO and contributors must use `-s` on each commit to the branch associated with a pull request.\n\nSee [GitHub App DCO](https://github.com/apps/dco).\n\nMake sure this feature is turned on for the `antlr4` repo upon release.\n\n### Delete existing release tag\n\nWack any existing tag as mvn will create one and it fails if already there.\n\n```\n$ git tag -d 4.13.2\n$ git push origin :refs/tags/4.13.2\n$ git push upstream :refs/tags/4.13.2\n```\n\n### Go release tags\n\n*I don't think this is necessary anymore as we have moved it release branch to https://github.com/antlr4-go/antlr*\n\nIt seems that [Go needs a `v` in the release git tag](https://go.dev/ref/mod#glos-version) so make sure that we double up with 4.13.2 and v4.13.2.\n\n```\n$ git tag -a runtime/Go/antlr/v4/v4.13.2 -m \"Go runtime module only\" \n$ git push upstream runtime/Go/antlr/v4/v4.13.2\n$ git push origin runtime/Go/antlr/v4/v4.13.2\n```\n\n\n## Bump version in code and other files\n\nThere are a number of files that require inversion number be updated.\n\n\nHere is a simple script to display any line from the critical files with, say, `4.11.1` in it.  Here's an example run of the script:\n\n```bash\n~/antlr/code/antlr4 $ python scripts/update_antlr_version.py 4.13.1 4.13.2\nUpdating ANTLR version from 4.13.1 to 4.13.2\nSet ANTLR repo root (default ~/antlr/code/antlr4): \nPerform antlr4 `mvn clean` and wipe build dirs Y/N? (default no): \nOk, not cleaning antlr4 dir\n4.13.1 appears on 2 lines so _not_ updating /tmp/antlr4/runtime/JavaScript/package-lock.json\n4.13.1 not in /tmp/antlr4/doc/releasing-antlr.md\n```\n\nMake sure this file doesn't have `-SNAPSHOT` when releasing!\n\n```\nruntime/Java/src/org/antlr/v4/runtime/RuntimeMetaData.java\n```\n\nIt's also worth doing a quick check to see if you find any other references to a version:\n\n```bash\nmvn clean\nfind . -type f -exec grep -l '4\\.12.0' {} \\; | grep -v -E '\\.o|\\.a|\\.jar|\\.dylib|node_modules/|\\.class|tests/|CHANGELOG|\\.zip|\\.gz|.iml|.svg'\n```\n\nCommit to repository.\n\n### PHP runtime\n\nWe only have to copy the PHP runtime into the ANTLR repository to run the unittests. But, we still need to bump the version to 4.13.2 in `~/antlr/code/antlr-php-runtime/src/RuntimeMetaData.php` in the separate repository, commit, and push.\n\n```\ncd ~/antlr/code/antlr-php-runtime/src\ngit checkout dev # Should be the default\ngit pull origin dev\n... vi RuntimeMetaData.php ...\ngit commit -a -m \"Update PHP Runtime to latest version\"\ngit push origin dev\ngit checkout master\ngit pull origin master\ngit merge dev\ngit push origin master\n```\n\n## Build XPath parsers\n\nThis section addresses a [circular dependency regarding XPath](https://github.com/antlr/antlr4/issues/3600). In the java target I avoided a circular dependency (gen 4.13.2 parser for XPath using 4.13.2 which needs it to build) by hand building the parser: runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPath.java.  Probably we won't have to rerun this for the patch releases, just major ones that alter the ATN serialization.\n\n```bash\ncd ~/antlr/code/antlr4/runtime/Cpp/runtime/src/tree/xpath\njava -cp \":/Users/parrt/.m2/repository/org/antlr/antlr4/4.13.2-SNAPSHOT/antlr4-4.13.2-SNAPSHOT-complete.jar:$CLASSPATH\" org.antlr.v4.Tool -Dlanguage=Cpp XPathLexer.g4\n\ncd ~/antlr/code/antlr4/runtime/CSharp/src/Tree/Xpath\njava -cp \":/Users/parrt/.m2/repository/org/antlr/antlr4/4.13.2-SNAPSHOT/antlr4-4.13.2-SNAPSHOT-complete.jar:$CLASSPATH\" org.antlr.v4.Tool -Dlanguage=CSharp XPathLexer.g4\n\ncd ~/antlr/code/antlr4/runtime/Python3/tests/expr\njava -cp \":/Users/parrt/.m2/repository/org/antlr/antlr4/4.13.2-SNAPSHOT/antlr4-4.13.2-SNAPSHOT-complete.jar:$CLASSPATH\" org.antlr.v4.Tool -Dlanguage=Python3 Expr.g4\ncd ~/antlr/code/antlr4/runtime/Python3/src/antlr4/xpath\njava -cp \":/Users/parrt/.m2/repository/org/antlr/antlr4/4.13.2-SNAPSHOT/antlr4-4.13.2-SNAPSHOT-complete.jar:$CLASSPATH\" org.antlr.v4.Tool -Dlanguage=Python3 XPathLexer.g4\n```\n\n## Maven Repository Settings\n\nFirst, make sure you have maven set up to communicate with staging servers etc...  Create file `~/.m2/settings.xml` with appropriate username/password for staging server and gpg.keyname/passphrase for signing. Make sure it has strict visibility privileges to just you. On unix, it looks like:\n\n```bash\nbeast:~/.m2 $ ls -l settings.xml \n-rw-------  1 parrt  staff  914 Jul 15 14:42 settings.xml\n```\n\nHere is the file template\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  User-specific configuration for maven. Includes things that should not\n  be distributed with the pom.xml file, such as developer identity, along with\n  local settings, like proxy information.\n-->\n<settings>\n   <servers>\n        <server>\n          <id>sonatype-nexus-staging</id>\n          <username>sonatype-username</username>\n          <password>XXX</password>\n        </server>\n        <server>\n          <id>sonatype-nexus-snapshots</id>\n          <username>sonatype-username</username>\n          <password>XXX</password>\n        </server>\n   </servers>\n    <profiles>\n            <profile>\n              <activation>\n                    <activeByDefault>false</activeByDefault>\n              </activation>\n              <properties>\n                    <gpg.keyname>UUU</gpg.keyname>\n                    <gpg.passphrase>XXX</gpg.passphrase>\n              </properties>\n            </profile>\n    </profiles>\n</settings>\n```\n\n## Maven deploy snapshot\n\nThe goal is to get a snapshot, such as `4.13.2-SNAPSHOT`, to the staging server: [antlr4 tool](https://oss.sonatype.org/content/repositories/snapshots/org/antlr/antlr4/4.13.2-SNAPSHOT/) and [antlr4 java runtime](https://oss.sonatype.org/content/repositories/snapshots/org/antlr/antlr4-runtime/4.13.2-SNAPSHOT/).\n\nDo this:\n\n```bash\n$ mvn install -DskipTests  # seems required to get the jar files visible to maven\n$ mvn deploy -DskipTests\n...\nUploading: https://oss.sonatype.org/content/repositories/snapshots/org/antlr/antlr4-tool-testsuite/maven-metadata.xml\nUploaded: https://oss.sonatype.org/content/repositories/snapshots/org/antlr/antlr4-tool-testsuite/maven-metadata.xml (388 B at 0.9 KB/sec)\n[INFO] ------------------------------------------------------------------------\n[INFO] Reactor Summary:\n[INFO] \n[INFO] ANTLR 4 ............................................ SUCCESS [  4.073 s]\n[INFO] ANTLR 4 Runtime .................................... SUCCESS [ 13.828 s]\n[INFO] ANTLR 4 Tool ....................................... SUCCESS [ 14.032 s]\n[INFO] ANTLR 4 Maven plugin ............................... SUCCESS [  6.547 s]\n[INFO] ANTLR 4 Runtime Test Annotations ................... SUCCESS [  2.519 s]\n[INFO] ANTLR 4 Runtime Test Processors .................... SUCCESS [  2.385 s]\n[INFO] ANTLR 4 Runtime Tests (4th generation) ............. SUCCESS [ 15.276 s]\n[INFO] ANTLR 4 Tool Tests ................................. SUCCESS [  2.233 s]\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 01:01 min\n[INFO] Finished at: 2016-12-11T09:37:54-08:00\n[INFO] Final Memory: 44M/470M\n[INFO] ------------------------------------------------------------------------\n```\n\n## Maven release\n\nThe maven deploy lifecycle phased deploys the artifacts and the poms for the ANTLR project to the [sonatype remote staging server](https://oss.sonatype.org/content/repositories/snapshots/).\n\n```bash\nmvn deploy -DskipTests\n```\n\nMake sure `gpg` is installed (`brew install gpg` on mac). Also must [create a key and publish it](https://blog.sonatype.com/2010/01/how-to-generate-pgp-signatures-with-maven/) then update `.m2/settings` to use that public key.\n\nThen:\n\n```bash\nmvn release:prepare -Darguments=\"-DskipTests\"\n```\n\nHmm...per https://github.com/keybase/keybase-issues/issues/1712 we need this to make gpg work:\n\n```bash\nexport GPG_TTY=$(tty)\n```\n\nYou should see 0x37 in generated .class files after 0xCAFEBABE; see [Java SE 11 = 55 (0x37 hex)](https://en.wikipedia.org/wiki/Java_class_file):\n\n```bash\n~/antlr/code/antlr4 $ od -h tool/target/classes/org/antlr/v4/Tool.class |head -1\n0000000      feca    beba    0000    3700    ed04    0207    0a9d    0100\n                                     ^^\n```\n\nAlso verify run time is 1.8:\n\n```bash\nod -h runtime/Java/target/classes/org/antlr/v4/runtime/Token.class | head -1\n0000000      feca    beba    0000    3400    2500    0007    0722    2300\n```\n\nIt will start out by asking you the version number:\n\n```\n...\nWhat is the release version for \"ANTLR 4\"? (org.antlr:antlr4-master) 4.13.2: : 4.13.2\nWhat is the release version for \"ANTLR 4 Runtime\"? (org.antlr:antlr4-runtime) 4.13.2: : \nWhat is the release version for \"ANTLR 4 Tool\"? (org.antlr:antlr4) 4.13.2: : \nWhat is the release version for \"ANTLR 4 Maven plugin\"? (org.antlr:antlr4-maven-plugin) 4.13.2: : \nWhat is the release version for \"ANTLR 4 Runtime Test Generator\"? (org.antlr:antlr4-runtime-testsuite) 4.13.2: : \nWhat is the release version for \"ANTLR 4 Tool Tests\"? (org.antlr:antlr4-tool-testsuite) 4.13.2: : \nWhat is SCM release tag or label for \"ANTLR 4\"? (org.antlr:antlr4-master) antlr4-master-4.13.2: : 4.13.2\nWhat is the new development version for \"ANTLR 4\"? (org.antlr:antlr4-master) 4.13.3-SNAPSHOT:\n...\n```\n\nMaven will go through your pom.xml files to update versions from 4.13.2-SNAPSHOT to 4.13.2 for release and then to 4.13.2-SNAPSHOT after release, which is done with:\n\n```bash\nmvn release:perform -Darguments=\"-DskipTests\"\n```\n\nMaven will use git to push pom.xml changes.\n\nNow, go here:\n\n&nbsp;&nbsp;&nbsp;&nbsp;[https://oss.sonatype.org/#welcome](https://oss.sonatype.org/#welcome)\n\nand on the left click \"Staging Repositories\". You click the staging repo and close it, then you refresh, click it and release it. It's done when you see it here:\n\n&nbsp;&nbsp;&nbsp;&nbsp;[https://oss.sonatype.org/service/local/repositories/releases/content/org/antlr/antlr4-runtime/4.13.2/antlr4-runtime-4.13.2.jar](https://oss.sonatype.org/service/local/repositories/releases/content/org/antlr/antlr4-runtime/4.13.2/antlr4-runtime-4.13.2.jar)\n\nAll releases should be here: [https://repo1.maven.org/maven2/org/antlr/antlr4-runtime](https://repo1.maven.org/maven2/org/antlr/antlr4-runtime).\n\n## Deploying Targets\n\n### JavaScript\n\n**Push to npm**\n\n(I think this has to be run before the unit test can run locally as it installs the global lib)\n\n```bash\ncd ~/antlr/code/antlr4/runtime/JavaScript\nrm -rf node_modules # seems we might need this later but try it here\nnpm update\nnpm install\nnpm run build \nnpm login     # asks for username/password/2FA (npmjs.com)\nnpm publish   # don't put antlr4 on there or it will try to push the old version for some reason\n```\n\nMove (and zip) target to website:\n\n```bash\ncd src\nzip -r ~/antlr/sites/website-antlr4/download/antlr-javascript-runtime-4.13.2.zip .\n```\n\n### CSharp\n\nAs of writing, you can only release from a Windows box, because Visual Studio for Mac can only build the netstandard2.0 version\n\n**Install the pre-requisites**\n\nYou need 'msbuild' and `nuget` to be installed. \n\n**Creating the signed assembly**\n\ncd ~/antlr/code/antlr4/runtime/CSharp/src\ndotnet build -c Release Antlr4.csproj\n\ncheck that the bin/Release folder contains both the netstandard2.0 and the net45 builds\nthe binaries are already signed, but it's worth double checking\n\nsn -v bin/Release/netstandard2.0/Antlr4.Runtime.Standard.dll\nsn -v bin/Release/net45/Antlr4.Runtime.Standard.dll\n\nboth should say the dll is valid\n\n**Publishing to NuGet**\n\nYou need to be a NuGet owner for \"ANTLR 4 Standard Runtime\"\nAs a registered NuGet user, you can then manually upload the package here: [https://www.nuget.org/packages/manage/upload](https://www.nuget.org/packages/manage/upload)\n\nAlternately, you can publish from the cmd line. You need to get your NuGet key from [https://www.nuget.org/account#](https://www.nuget.org/account#) and then from the cmd line, you can then type:\n\n```cmd\ncd bin/Release\nnuget push Antlr4.Runtime.Standard.<version>.nupkg <your-key> -Source https://www.nuget.org/api/v2/package\n```\n\n### Python\n\nThe Python target gets deployed with `twine` for Python 3.\n\nFirst, set up `~/.pypirc` with tight privileges:\n\n```bash\nbeast:~ $ ls -l ~/.pypirc\n-rw-------  1 parrt  staff  267 Jul 15 17:02 /Users/parrt/.pypirc\n```\n\n```\n[distutils] # this tells distutils what package indexes you can push to\nindex-servers =\n    pypi\n    pypitest\n\n[pypi]\nusername: parrt\npassword: xxx\n\n[pypitest]\nusername: parrt\npassword: xxx\n```\n\nThen run the python build and upload:\n\n```bash\ncd ~/antlr/code/antlr4/runtime/Python3\npython -m build\n# assume you have ~/.pypirc set up\ntwine upload dist/antlr4_python3_runtime-4.13.2.tar.gz dist/antlr4_python3_runtime-4.13.2-py3-none-any.whl\n```\n\nThere are links to the artifacts in [download.html](http://www.antlr.org/download.html) already.\n\n### C++\n\nThe C++ target is the most complex one, because it addresses multiple platforms, which require individual handling. We have 4 scenarios to cover:\n\n* **Windows**: static and dynamic libraries for the VC++ runtime 2017 or 2019 (corresponding to Visual Studio 2017 or 2019) + header files. All that in 32 and 64bit, debug + release.\n* **MacOS**: static and dynamic release libraries + header files.\n* **iOS**: no prebuilt binaries, but just a zip of the source, including the XCode project to build everything from source.\n* **Linux**: no prebuilt binaries, but just a zip of the source code, including the cmake file to build everything from source there.\n\nIn theory we could also create a library for iOS, but that requires to sign it, which depends on an active iOS developer account. So we leave this up to the ANTLR user to build the iOS lib, like we do for Linux builds.\n\nFor each platform there's a deployment script which generates zip archives and copies them to the target folder. The Windows deployment script must be run on a machine with VS 2013 + VS 2015 installed. The Mac script must be run on a machine with XCode 7+ installed. The source script can be executed on any Linux or Mac box.\n\nOn a Mac (with XCode 7+ installed):\n\n```bash\ncd ~/antlr/code/antlr4/runtime/Cpp\nrm CMakeCache.txt  # otherwise can't find some include files\n./deploy-macos.sh\ncp antlr4-cpp-runtime-macos.zip ~/antlr/sites/website-antlr4/download/antlr4-cpp-runtime-4.13.2-macos.zip\n```\n\nOn any Mac or Linux machine:\n\n```bash\ncd ~/antlr/code/antlr4/runtime/Cpp\n./deploy-source.sh\ncp antlr4-cpp-runtime-source.zip ~/antlr/sites/website-antlr4/download/antlr4-cpp-runtime-4.13.2-source.zip\n```\n\nOn a Windows machine the build scripts checks if VS 2017 and/or VS 2019 are installed and builds binaries for each, if found. This script requires 7z to be installed (http://7-zip.org then do `set PATH=%PATH%;C:\\Program Files\\7-Zip\\` from DOS not powershell).\n\n```bash\ncd ~/antlr/code/antlr4/runtime/Cpp\ndeploy-windows.cmd Community\ncp antlr4-cpp-runtime-vs2019.zip ~/antlr/sites/website-antlr4/download/antlr4-cpp-runtime-4.13.2-vs2019.zip\n```\n\nMove target to website (**_rename to a specific ANTLR version first if needed_**):\n\n```bash\npushd ~/antlr/sites/website-antlr4/download\ngit add antlr4-cpp-runtime-4.13.2-macos.zip\ngit add antlr4-cpp-runtime-4.13.2-windows.zip\ngit add antlr4-cpp-runtime-4.13.2-source.zip\ngit commit -a -m 'update C++ runtime'\ngit push origin gh-pages\npopd\n```\n\n### Dart\n\nInstall Dart SDK from https://dart.dev/get-dart\n\nPush to pub.dev\n\n```bash\ncd ~/antlr/code/antlr4/runtime/Dart\ndart pub publish\n```\n\nIt will warn that no change log found for the new version.\nOtherwise enter `N` to ignore the warning.\n\n## Update website\n\n### javadoc for runtime and tool\n\nJars are in:\n\n```\n~/.m2/repository/org/antlr/antlr4-runtime/4.13.2/antlr4-runtime-4.13.2\n```\n\n### Update version and copy jars / api\n\nCopy javadoc and java jars to website using this script:\n\n```bash\ncd ~/antlr/code/antlr4\npython scripts/deploy_to_website.py 4.13.1 4.13.2\n```\n\nOutput:\n\n```bash\nUpdating ANTLR version from 4.13.1 to 4.13.2\nSet ANTLR website root (default /Users/parrt/antlr/sites/website-antlr4): \nVersion string updated. Please commit/push:\nJavadoc copied:\n\tapi/Java updated from antlr4-runtime-4.13.2-javadoc.jar\n\tapi/JavaTool updated from antlr4-4.13.2-javadoc.jar\nJars copied:\n\tantlr-4.13.2-complete.jar\n\tantlr-runtime-4.13.2.jar\n\nPlease look for and add new api files!!\nThen MANUALLY commit/push:\n\ngit commit -a -m 'Update website, javadoc, jars to 4.13.2'\ngit push origin gh-pages\n```\n\n<!--\n```bash\ncp ~/.m2/repository/org/antlr/antlr4-runtime/4.13.2/antlr4-runtime-4.13.2.jar ~/antlr/sites/website-antlr4/download/antlr-runtime-4.13.2.jar\ncp ~/.m2/repository/org/antlr/antlr4/4.13.2/antlr4-4.13.2-complete.jar ~/antlr/sites/website-antlr4/download/antlr-4.13.2-complete.jar\ncd ~/antlr/sites/website-antlr4/download\ngit add antlr-4.13.2-complete.jar\ngit add antlr-runtime-4.13.2.jar \n```\n-->\n\nOnce it's done, you must do the following manually:\n\n```\ncd ~/antlr/sites/website-antlr4\ngit commit -a -m 'Update website, javadoc, jars to 4.13.2'\ngit push origin gh-pages\n```\n\n<!--\nThen copy to website:\n\n```bash\ncd ~/antlr/sites/website-antlr4/api\ngit checkout gh-pages\ngit pull origin gh-pages\ncd Java\njar xvf ~/.m2/repository/org/antlr/antlr4-runtime/4.13.2/antlr4-runtime-4.13.2-javadoc.jar\ncd ../JavaTool\njar xvf ~/.m2/repository/org/antlr/antlr4/4.13.2/antlr4-4.13.2-javadoc.jar\ngit commit -a -m 'freshen api doc'\ngit push origin gh-pages\n```\n-->\n\n## Get fresh dev branch\n\n```bash\ngit checkout master\ngit pull upstream master\ngit checkout dev\ngit pull upstream dev\ngit merge master\ngit push origin dev\ngit push upstream dev\n```\n\n## Other updates \n\n* Rebuild antlr Intellij plug-in with new antlr jar.\n* Cut release notes in github\n* Update lab.antlr.org\n"
  },
  {
    "path": "doc/resources.md",
    "content": "# Articles and Resources\n\n## Books\n\n<a href=\"\"><img src=images/tpantlr2.png width=120></a>\n<a href=\"\"><img src=images/tpdsl.png width=120></a>\n\n<a href=\"https://www.youtube.com/watch?v=OAoA3E-cyug\"><img src=images/teronbook.png width=250></a>\n\n## Articles\n\n* [Playing with ANTLR4, Primefaces extensions for Code Mirror and web-based DSLs](http://leonotepad.blogspot.com.br/2014/01/playing-with-antlr4-primefaces.html)\n* [A Tale of Two Grammars](https://dexvis.wordpress.com/2012/11/22/a-tale-of-two-grammars/)\n* [ANTLR 4: using the lexer, parser and listener with example grammar](http://www.theendian.com/blog/antlr-4-lexer-parser-and-listener-with-example-grammar/)\n* [Creating External DSLs using ANTLR and Java](http://java.dzone.com/articles/creating-external-dsls-using)\n\n## Presentations\n\n* [Introduction to ANTLR 4 by Oliver Zeigermann](https://docs.google.com/presentation/d/1XS_VIdicCQVonPK6AGYkWTp-3VeHfGuD2l8yNMpAfuQ/edit#slide=id.p)\n\n## Videos\n\n<a href=\"https://vimeo.com/59285751\"><img src=images/tertalk.png width=200></a>\n\n## Resources\n\n* [Stack overflow ANTLR4 tag](http://stackoverflow.com/questions/tagged/antlr4)\n* [Antlr 4 with C# and Visual Studio 2012](http://programming-pages.com/2013/12/14/antlr-4-with-c-and-visual-studio-2012/)\n* [ANTLR Language Support in VisualStudio](http://visualstudiogallery.msdn.microsoft.com/25b991db-befd-441b-b23b-bb5f8d07ee9f)\n* [Upgrading to ANTLR 4 with C#](http://andrevdm.blogspot.com/2013/08/upgrading-to-antlr-4-with-c.html)\n* [Generate parsers with Antlr4 via Maven](http://ljelonek.wordpress.com/2014/01/03/generate-parsers-with-antlr4-via-maven/)\n* [Exploring ANTLR v4](http://johnsquibb.like97.com/blog/read/exploring-antlr-v4)\n* [antlr4dart](http://pub.dartlang.org/packages/antlr4dart)"
  },
  {
    "path": "doc/swift-target.md",
    "content": "# ANTLR4 Language Target, Runtime for Swift\n\n## Performance Note\n\nTo use ANTLR4 Swift target in production environment, make sure to turn on compiler optimizations by following [these instructions](https://github.com/apple/swift-package-manager/blob/main/Documentation/Usage.md#setting-the-build-configuration) if you use SwiftPM to build your project. \n\nIf you are using Xcode to build your project, it's unlikely you will not use `release` build for production build.\n\nConclusion is, you need to turn on `release` mode (which will have all the optimization pre configured for you) so the ANTLR4 Swift target can have reasonable parsing speed.\n\n## Install ANTLR4\n\nMake sure you have the ANTLR\ninstalled. [The getting started guide](getting-started.md) should get\nyou started.\n\n## Create a Swift lexer or parser \nThis is pretty much the same as creating a Java lexer or parser, \nexcept you need to specify the language target, for example:\n\n``` \n$ antlr4 -Dlanguage=Swift MyGrammar.g4 \n``` \n\nIf you integrate this as a build step inside Xcode, then you should use the\n\"gnu\" message format to have any error messages parsed by Xcode.  You may\nalso want to use the `-o` option to put the autogenerated files in a\nseparate subdirectory.\n\n```\nantlr4 -Dlanguage=Swift -message-format gnu -o Autogen MyGrammar.g4\n```\n\nFor a full list of antlr4 tool options, please visit the\n[tool documentation page](tool-options.md).\n\n## Build your Swift project with ANTLR runtime\n\n### Note\n\nWe use __boot.py__ script located at the root of the Swift runtime folder\n`antlr4/runtime/Swift` to provide additional support for both Xcode-based\nprojects and SPM-based projects. Below sections are organized for both of\nthe flavors. If you want to quickly get started, try:\n\n```\npython boot.py --help\n```\n\nfor information about this script.\n\n### Xcode Projects\n\nNote that even if you are otherwise using ANTLR from a binary distribution,\nyou should compile the ANTLR Swift runtime from source, because the Swift\nlanguage does not yet have a stable ABI.\n\nANTLR uses Swift Package Manager to generate Xcode project files. \n\n#### Download source code for ANTLR\n\n```\ngit clone https://github.com/antlr/antlr4\n```\n\n#### Generate Xcode project for ANTLR runtime\n\nThe `boot.py` script includes a wrapper around `swift package\ngenerate-xcodeproj`. Use this to generate `Antlr4.xcodeproj` for the ANTLR\nSwift runtime. (using _swift package generate-xcodeproj_ is not recommended)\nsince the project is dependent on some parser files generated by _boot.py_.\n\n```\ncd antlr4/runtime/Swift\npython boot.py --gen-xcodeproj\n```\n\n#### Import ANTLR Swift runtime into your project\n\nOpen your own project in Xcode.\n\nOpen Finder in the `runtime/Swift` directory:\n\n```\n# From antlr4/runtime/Swift\nopen .\n```\n\nDrag `Antlr4.xcodeproj` into your project.\n\nAfter this is done, your Xcode project navigator will be something like the\nscreenshot below. In this example, your own project is \"Smalltalk\", and you\nwill be able to see `Antlr4.xcodeproj` shown as a contained project.\n\n<img src=images/xcodenav.png width=\"300\">\n\n#### Edit the build settings if necessary\n\nSwift Package Manager currently does not support iOS, watchOS, or tvOS.  If\nyou wish to build for those platforms, you will need to alter the project\nbuild settings manually.\n\n#### Add generated parser and lexer to project\n\nMake sure the parsers/lexers\ngenerated in __step 2__ are added to the project. To do this, you can\ndrag the generated files from Finder to the Xcode IDE. Remember to\ncheck __Copy items if needed__ to make sure the files are actually\nmoved into the project folder instead of symbolic links (see the\nscreenshot below). After moving you will be able to see your files in\nthe project navigator.  Make sure that the Target Membership settings\nare correct for your project.\n\n<img src=images/dragfile.png width=\"500\">\n\n#### Add the ANTLR Swift runtime as a dependency\n\nSelect your own project in Xcode and go to the Build Phases settings panel.\nAdd the ANTLR runtime under __Target Dependencies__ and __Link Binary With\nLibraries__.\n\n<img src=images/xcodedep.png width=\"800\">\n\n#### Build your project\n\nThe runtime and generated grammar should now build correctly.\n\n### Swift Package Manager Projects\n\nAdd Antlr4 as a dependency to your `Package.swift` file. For more information, please see the [Swift Package Manager documentation](https://github.com/apple/swift-package-manager/tree/master/Documentation).\n\n\n```swift\n.package(url: \"https://github.com/antlr/antlr4\", from: \"4.13.2\")\n```\n\n## Swift access levels\n\nYou may use the `accessLevel` option to control the access levels on generated\ncode.  This option can either be specified with `-DaccessLevel=value` on\nthe `antlr4` command line, or inside your `.g4` file like this:\n\n```\noptions {\n    accessLevel = 'value';\n}\n```\n\nBy default (with the `accessLevel` option unspecified) the generated code\nuses the following access levels:\n\n* `open` for anything that you can feasibly extend with subclassing:\nthe generated parser, lexer, and context classes, the the listener and\nvisitor base classes, and all their accessor and setter functions.\n* `public` for anything that should not be subclassed, but otherwise is\nuseful to client code: protocols, initializers, and static definitions such\nas the lexer tokens, symbol names, and so on.\n* `internal` or `private` for anything that should not be accessed directly.\n\nIf you specify `accessLevel = 'public'` then all items that are `open` by\ndefault will use `public` instead.  Otherwise, the behavior is the same as\nthe default.\n\nIf you specify `accessLevel = ''` or `accessLevel='internal'` then all items\nthat are `open` or `public` by default will use Swift's default (internal)\naccess level instead.\n\nThose are the only supported values for `accessLevel` when using the Swift\ncode-generator.\n\nWe recommend using `accessLevel = ''`.  Even if you are creating a parser\nas part of a library, you would usually want to wrap it in an API of your\nown and keep the ANTLR-generated parser internal to your module.  You\nonly need to use the less restrictive access levels if you need to expose\nthe parser directly as part of your own module's API.\n"
  },
  {
    "path": "doc/target-agnostic-grammars.md",
    "content": "# Writing target-agnostic grammars\n\nSome grammars require\n[semantic predicates](https://github.com/antlr/antlr4/blob/dev/doc/predicates.md)\nto add context-sensitive parsing to what would generally be a context-free grammar.\n\nFor example:\n* In Fortran90, [lines that begin with a 'C' in column 1\nare comments](https://github.com/antlr/grammars-v4/blob/43fbb16fec1d474d38a603cc6a6bcbe5edf07b1e/fortran/fortran90/slow/hw.f90#L1),\nwhich should be placed on a token stream other than the default.\nBut, if the 'C' does not begin in\ncolumn 1, then the input is invalid and should be flagged as so.\n\t```fortran\n\tc Hello World.\n\t   c This is a syntax error because 'c' does not start in column 1\n\tprogram hello\n\t\tprint *, 'Hello World!'\n\tend\n\t```\n\n* In CSharp, two [greater-than signs](https://util.unicode.org/UnicodeJsps/character.jsp?a=003E)\n`'>>'` can either mean\n[a right shift expression](https://github.com/antlr/grammars-v4/blob/43fbb16fec1d474d38a603cc6a6bcbe5edf07b1e/csharp/examples/AllInOneNoPreprocessor.cs#L657C15-L657C17)\nor [part of a type declaration with templates](https://github.com/antlr/grammars-v4/blob/master/csharp/examples/AllInOneNoPreprocessor.cs#L463C33-L463C35).\nSince lexers in Antlr are not parser aware,\nthe lexer must tokenize the two greater-than signs as two separate tokens.\nA semantic predicate should be added to disallow a space between the two greater-than signs in the context\nof an expression, but allowed in the context of a type declaration. \n\t```C#\n\tclass Foo {\n\t\tvoid Func()\n\t\t{\n\t\t\tint x = 1000 > > 2;               // syntax error if a space exists in the double greater-than sign\n\t\t}\n\t\tDictionary<int, List<int> > mapping;  // nested template declaration, valid\n\t}\n\t```\n\nAntlr does not have a general-purpose language for predicates. These must be\nwritten in the target language of the generated parser. The problem is that\na grammar would need to be forked for each target desired, which adds to the\nburden of maintenance.\n\nHowever, it is possible to write the grammar such that forking is not required,\nusing _target-agnostic format_.\n\n## Rules in writing target-agnostic grammars\n\n1) You will need to [split your grammar](https://github.com/antlr/antlr4/blob/dev/doc/grammars.md#grammar-structure)\ninto separate lexer and parser grammars. Then, add `options { tokenVocab=...; }` to the parser grammar.\n2) Create target-specific source code files that contain methods in a base class for\nthe parser or lexer grammar. In these source code files, write the code for the semantic\npredicate. For example, the files for the Cpp target would be `Python3LexerBase.{cpp,h}`, `Python3ParserBase.{cpp,h}`.\n3) In the grammar(s), add `options { superClass=... }`. This will\n[superclass the recognizer](https://github.com/antlr/antlr4/blob/dev/doc/options.md#superclass).\nFor example, `options { superclass=Python3ParserBase; }`.\n4) In the grammar(s), write code to make a single\ncall to the base-class method. The call should have a `this.` string\nbefore the name of the method, e.g., `OPEN_PAREN : '(' {this.openBrace();};`\nThe action code must not reference Antlr attributes,\nvariables, types, or have semi-colons as statement separators or\ncontrol-flow statements of any kind.\n5) For some targets like Cpp and PHP, you may need to add code to include source\ncode files so that the generated code compiles.\nFor these, add a comment\nsuch as `// Insert here @header for lexer include.` or `// Insert here @header for parser include.`\nto the grammar, before the first rule.\n5) Add a Python script called \"transformGrammar.py\" that rewrites the grammar(s) \nwith some target-specific code syntax.\n   a) For Cpp: replace `this.` strings with `this->`.\n   b) For PHP: replace `this.` strings with `$this->`.\n   c) For Python: replace `this.` strings with `self.`, `l.`, or `p.` depending on\nwhere the action or predicate is in the grammar.\n   d) For Cpp: replace `// Insert here @header for lexer include.` (or parser) with\n`@header::lexer {#include ...}`.\n   e) For PHP: replace `// Insert here @header for lexer include.` (or parser) with\n`@header::lexer {require ...}`.\n   e) Run `python transformGrammar.py *.g4` before generating the parser and lexer.\n\n## Examples of target-agnostic grammars\n* [fortran90](https://github.com/antlr/grammars-v4/tree/master/fortran/fortran90)\n* [csharp](https://github.com/antlr/grammars-v4/tree/master/csharp)\n"
  },
  {
    "path": "doc/targets.md",
    "content": "# Runtime Libraries and Code Generation Targets\n\nThis page lists the available and upcoming ANTLR runtimes. Please note that you won't find here language specific code generators. This is because there is only one tool, written in Java, which is able to generate lexer and parser code for all targets, through command line options. The tool can be invoked from the command line, or any integration plugin to popular IDEs and build systems: Eclipse, IntelliJ, Visual Studio, Maven. So whatever your environment and target is, you should be able to run the tool and produce the code in the targeted language. As of writing, the available targets are the following:\n\n* [Java](java-target.md). The [ANTLR v4 book](http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference) has a decent summary of the runtime library.  We have added a useful XPath feature since the book was printed that lets you select bits of parse trees. See [Runtime API](http://www.antlr.org/api/Java/index.html) and [Getting Started with ANTLR v4](getting-started.md)\n* [C#](csharp-target.md)\n* [Python](python-target.md) (3)\n* [JavaScript](javascript-target.md)\n* [TypeScript](typescript-target.md)\n* [Go](go-target.md)\n* [C++](cpp-target.md)\n* [Swift](swift-target.md)\n* [PHP](php-target.md)\n* [Dart](dart-target.md)\n\n## Target feature parity\n\nNew features generally appear in the Java target and then migrate to the other targets, but these other targets don't always get updated in the same overall tool release. This section tries to identify features added to Java that have not been added to the other targets.\n\n|Feature|Java|C&sharp;|Python3|JavaScript|Go|C++|Swift|PHP|Dart\n|---|---|---|---|---|---|---|---|---|---|\n|Ambiguous tree construction|4.5.1|-|-|-|-|-|-|-|-|\n\n"
  },
  {
    "path": "doc/tool-options.md",
    "content": "# ANTLR Tool Command Line Options\n\nIf you invoke the ANTLR tool without command line arguments, you’ll get a help message:\n\n```bash\n$ antlr4\nANTLR Parser Generator  Version 4.7.1\n -o ___              specify output directory where all output is generated\n -lib ___            specify location of grammars, tokens files\n -atn                generate rule augmented transition network diagrams\n -encoding ___       specify grammar file encoding; e.g., euc-jp\n -message-format ___ specify output style for messages in antlr, gnu, vs2005\n -long-messages      show exception details when available for errors and warnings\n -listener           generate parse tree listener (default)\n -no-listener        don't generate parse tree listener\n -visitor            generate parse tree visitor\n -no-visitor         don't generate parse tree visitor (default)\n -package ___        specify a package/namespace for the generated code\n -depend             generate file dependencies\n -D<option>=value    set/override a grammar-level option\n -Werror             treat warnings as errors\n -XdbgST             launch StringTemplate visualizer on generated code\n -XdbgSTWait         wait for STViz to close before continuing\n -Xforce-atn         use the ATN simulator for all predictions\n -Xlog               dump lots of logging info to antlr-timestamp.log\n -Xexact-output-dir  all output goes into -o dir regardless of paths/package\n```\n\nHere are more details on the options:\n\n## `-o outdir`\n\nANTLR generates output files in the current directory by default. This option specifies the output directory where ANTLR should generate parsers, listeners, visitors, and tokens files.\n \t\n```bash\n$ antlr4 -o /tmp T.g4\n$ ls /tmp/T*\n/tmp/T.tokens /tmp/TListener.java\n/tmp/TBaseListener.java /tmp/TParser.java\n```\n\n## `-lib libdir`\n\nWhen looking for tokens files and imported grammars, ANTLR normally looks in the current directory. This option specifies which directory to look in instead. It is only used for resolving grammar references for the import statement and the tokenVocab option. The path to the primary grammar must always be fully specified.\n \t\n$ cat /tmp/B.g4\n \t\nparser grammar B;\n \t\nx : ID ;\n \t\n$ cat A.g4\n \t\ngrammar A;\n \t\nimport B;\n \t\ns : x ;\n \t\nID : [a-z]+ ;\n \t\n$ antlr4 -lib /tmp A.g4\n\n## `-atn`\n\nGenerate DOT graph files that represent the internal ATN (augmented transition network) data structures that ANTLR uses to represent grammars. The files come out as Grammar.rule .dot. If the grammar is a combined grammar, the lexer rules are named Grammar Lexer.rule .dot.\n \t\n$ cat A.g4\n \t\ngrammar A;\n \t\ns : b ;\n \t\nb : ID ;\n \t\nID : [a-z]+ ;\n \t\n$ antlr4 -atn A.g4\n \t\n$ ls *.dot\n \t\nA.b.dot A.s.dot ALexer.ID.dot\n\n## `-encoding encodingname`\n\nBy default ANTLR loads grammar files using the UTF-8 encoding, which is a very common character file encoding that degenerates to ASCII for characters that fit in one byte. There are many character file encodings from around the world. If that grammar file is not the default encoding for your locale, you need this option so that ANTLR can properly interpret grammar files. This does not affect the input to the generated parsers, just the encoding of the grammars themselves.\n\n## `-message-format format`\n\nANTLR generates warning and error messages using templates from directory tool/resources/org/antlr/v4/tool/templates/messages/formats. By default, ANTLR uses the antlr.stg (StringTemplate group) file. You can change this to gnu or vs2005 to have ANTLR generate messages appropriate for Emacs or Visual Studio. To make your own called X, create resource org/antlr/v4/tool/templates/messages/formats/ X and place it in the CLASSPATH.\n\n## `-listener`\n\nThis option tells ANTLR to generate a parse tree listener and is the default.\n\n## `-no-listener`\n\nThis option tells ANTLR not to generate a parse tree listener.\n\n## `-visitor`\n\nANTLR does not generate parse tree visitors by default. This option turns that feature on. ANTLR can generate both parse tree listeners and visitors; this option and -listener aren’t mutually exclusive.\n\n## `-no-visitor`\n\nTell ANTLR not to generate a parse tree visitor; this is the default.\n\n## `-package`\n\nUse this option to specify a package or namespace for ANTLR-generated files. Alternatively, you can add a @header {...} action but that ties the grammar to a specific language. If you use this option and @header, make sure that the header action does not contain a package specification otherwise the generated code will have two of them.\n\n## `-depend`\n\nInstead of generating a parser and/or lexer, generate a list of file dependencies, one per line. The output shows what each grammar depends on and what it generates. This is useful for build tools that need to know ANTLR grammar dependencies. Here’s an example:\n \t\n```bash\n$ antlr4 -depend T.g\t\nT.g: A.tokens\nTParser.java : T.g\nT.tokens : T.g\nTLexer.java : T.g\nTListener.java : T.g\nTBaseListener.java : T.g\n```\n\nIf you use -lib libdir with -depend and grammar option tokenVocab=A, then the dependencies include the library path as well: T.g: libdir/A.tokens. The output is also sensitive to the -o outdir option: outdir/TParser.java : T.g.\n\n## `-D<option>=value`\n\nUse this option to override or set a grammar-level option in the specified grammar or grammars. This option is useful for generating parsers in different languages without altering the grammar itself. (I expect to have other targets in the near future.)\n \t\n```bash\n$ antlr4 -Dlanguage=Java T.g4 # default\n$ antlr4 -Dlanguage=C T.g4\nerror(31): ANTLR cannot generate C code as of version 4.0b3\n```\n\n## `-Werror`\n\nAs part of a large build, ANTLR warning messages could go unnoticed. Turn on this option to have warnings treated as errors, causing the ANTLR tool to report failure back to the invoking commandline shell.\nThere are also some extended options that are useful mainly for debugging ANTLR itself:\n\n## `-Xsave-lexer`\n\nANTLR generates both a parser and a lexer from a combined grammar. To create the lexer, ANTLR extracts a lexer grammar from the combined grammar. Sometimes it’s useful to see what that looks like if it’s not clear what token rules ANTLR is creating. This does not affect the generated parsers or lexers.\n\n## `-XdbgST`\n\nFor those building a code generation target, this option brings up a window showing the generated code and the templates used to generate that code. It invokes the StringTemplate inspector window.\n\n## `-Xforce-atn`\n\nANTLR normally builds traditional “switch on token type” decisions where possible (one token of lookahead is sufficient to distinguish between all alternatives in a decision). To force even these simple decisions into the adaptive LL(*) mechanism, use this option.\n\n## `-Xlog`\n\nThis option creates a log file containing lots of information messages from ANTLR as it processes your grammar. If you would like to see how ANTLR translates your left-recursive rules, turn on this option and look in the resulting log file.\n \t\n```bash\n$ antlr4 -Xlog T.g4 \t\nwrote ./antlr-2012-09-06-17.56.19.log\n```\n\n## `-Xexact-output-dir`\n\n(*See the [discussion](https://github.com/antlr/antlr4/pull/2065)*).\n\nAll output goes into `-o` dir regardless of paths/package.\n\n* Output `-o` directory specifier is the exact directory containing the output. Previously it would include the relative path specified on the grammar itself for the purposes of packages.\n\n**new**: `-o /tmp subdir/T.g4` => `/tmp/subdir/T.java`\n**old**: `-o /tmp subdir/T.g4` => `/tmp/T.java`\n\n*  Previously we looked for the tokens vocab file in the `-lib` dir or in the output dir. **New**: also look in the directory containing the grammar, particularly if it it is specified with a path.\n\n### Example for the output directory (4.7)\n\nHere is the existing 4.7 functionality.\n\n(For these examples, assume a4.7 and a4.7.1 are aliases to the right version of ANTLR's `org.antlr.v4.Tool`.)\n\n```bash\n$ cd /tmp/parrt\n$ tree\n.\n├── B.g4\n└── src\n    └── pkg\n        └── A.g4\n$ a4.7 -o /tmp/build src/pkg/A.g4\n$ tree /tmp/build\n/tmp/build/\n└── src\n    └── pkg\n        ├── A.tokens\n        ├── ABaseListener.java\n        ├── ALexer.java\n        ├── ALexer.tokens\n        ├── AListener.java\n        └── AParser.java\n```\n\nNow, let's build a grammar that sits in the current directory:\n\n```bash\n$ a4.7 -o /tmp/build B.g4\n$ tree /tmp/build\n/tmp/build\n├── B.tokens\n├── BBaseListener.java\n├── BLexer.java\n├── BLexer.tokens\n├── BListener.java\n├── BParser.java\n└── src\n    └── pkg\n        ├── A.tokens\n        ├── ABaseListener.java\n        ├── ALexer.java\n        ├── ALexer.tokens\n        ├── AListener.java\n        └── AParser.java\n```\n\nFinally, if we don't specify the output directory, it paid attention to the relative path specified on the input grammar:\n\n```bash\n$ a4.7 src/pkg/A.g4\n$ tree\n.\n├── B.g4\n└── src\n    └── pkg\n        ├── A.g4\n        ├── A.tokens\n        ├── ABaseListener.java\n        ├── ALexer.java\n        ├── ALexer.tokens\n        ├── AListener.java\n        └── AParser.java\n```\n\n### Example for the output directory (4.7.1 with -Xexact-output-dir)\n\nNow, the output directory is the exact directory where output is generated regardless of relative paths on the grammar\n\n```bash\n$ cd /tmp/parrt\n$ a4.7.1 -Xexact-output-dir  -o /tmp/build src/pkg/A.g4\n$ tree /tmp/build\n/tmp/build\n├── A.tokens\n├── ABaseListener.java\n├── ALexer.java\n├── ALexer.tokens\n├── AListener.java\n└── AParser.java\n```\n\nIf you use the package option, it still does not change where the output is generated if you use `-o`\n\n```bash\n$ a4.7.1 -Xexact-output-dir -package pkg -o /tmp/build src/pkg/A.g4\n$ tree /tmp/build\n/tmp/build\n├── A.tokens\n├── ABaseListener.java\n├── ALexer.java\n├── ALexer.tokens\n├── AListener.java\n└── AParser.java\n```\n\n4.7.1 does however add the package specification into the generated files:\n\n```bash\n$ grep package /tmp/build/A*.java\n/tmp/build/ABaseListener.java:package pkg;\n/tmp/build/ALexer.java:package pkg;\n/tmp/build/AListener.java:package pkg;\n/tmp/build/AParser.java:package pkg;\n```\n\nCompare this to 4.7:\n\n```bash\n$ a4.7 -package pkg -o /tmp/build src/pkg/A.g4\nbeast:/tmp/parrt $ tree /tmp/build\n/tmp/build\n└── src\n    └── pkg\n        ├── A.tokens\n        ├── ABaseListener.java\n        ├── ALexer.java\n        ├── ALexer.tokens\n        ├── AListener.java\n        └── AParser.java\n```\n\n### Example of where it looks for tokens vocab\n\nIn 4.7, we got an error for an obvious case that should work:\n\n```bash\n$ cd /tmp/parrt\n$ tree\n.\n└── src\n    └── pkg\n        ├── L.g4\n        └── P.g4\n$ a4.7 -o /tmp/build src/pkg/*.g4\nerror(160): P.g4:2:21: cannot find tokens file /tmp/build/L.tokens\nwarning(125): P.g4:3:4: implicit definition of token A in parser\n```\n\nIn 4.7.1 it looks in the directory containing the grammars as well:\n\n```bash\n$ a4.7.1 -o /tmp/build src/pkg/*.g4\n$ tree /tmp/build\n/tmp/build\n├── L.java\n├── L.tokens\n├── P.java\n├── P.tokens\n├── PBaseListener.java\n├── PListener.java\n└── src\n    └── pkg\n        ├── L.java\n        └── L.tokens\n```\n"
  },
  {
    "path": "doc/tree-matching.md",
    "content": "# Parse Tree Matching and XPath\n\n*Since ANTLR 4.2*\n\nANTLR 4 introduced a visitor and listener mechanism that lets you implement DOM visiting or SAX-analogous event processing of tree nodes. This works great. For example, if all you care about is looking at Java method declarations, grab the `Java.g4` file and then override methodDeclaration in `JavaBaseListener`. From there, a `ParseTreeWalker` can trigger calls to your overridden method as it walks the tree. Easy things are easy.\n\nThis mechanism works more or less on a node-level basis. In other words, for every method declaration subtree root, your `methodDeclaration()` would get called. There are many situations where we care more about subtrees not just nodes. We might want to:\n\n* Collect method declarations within a particular context (i.e., nested within another method) or methods with specific structure or specific types (e.g., `void <ID>() { }`). We'll combine `XPath` and tree pattern matching for this.\n* Group translation operations by patterns in the tree rather than spreading operations across listener event methods.\n* Get a list of all assignments anywhere in the tree. It's much easier to say *go find me all \"... = ... ;\" subtrees* rather than creating a class just to get a listener method for rule assignment and then passing the listener to the parse tree walker.\n\nThe other important idea here is that, since we're talking about parse trees not abstract syntax trees, we can use concrete patterns instead of tree syntax. For example, we can say `x = 0;` instead of AST `(= x 0)` where the `;` would probably stripped before it went into the AST.\n\n## Parse tree patterns\n\nTo test a subtree to see if it has a particular structure, we use a tree pattern. We also often want to extract descendents from the subtree based upon the structure. A very simple example is checking to see if a subtree matches an assignment statement. The pattern might look like the following in your language:\n\n```\n<ID> = <expr>;\n```\n\nwhere \"tags\" in angle brackets represent either token or rule references in the associated grammar. ANTLR converts that string to a parse tree with special nodes that represent any token `ID` and rule `expr` subtree. To create this parse tree, the pattern matching compiler needs to know which rule in the grammar the pattern conforms to. In this case it might be statement. Here is how we could test a tree, `t`, to see if it matches that pattern:\n\n```java\nParseTree t = ...; // assume t is a statement\nParseTreePattern p = parser.compileParseTreePattern(\"<ID> = <expr>;\", MyParser.RULE_statement);\nParseTreeMatch m = p.match(t);\nif ( m.succeeded() ) {...}\n```\n\nWe can also test for specific expressions or token values. For example, the following checks to see if `t` is an expression consisting of an identifier added to 0:\n\n```java\nParseTree t = ...; // assume t is an expression\nParseTreePattern p = parser.compileParseTreePattern(\"<ID>+0\", MyParser.RULE_expr);\nParseTreeMatch m = p.match(t);\n```\n\nWe can also ask the `ParseTreeMatch` result to pull out the token matched to the `<ID>` tag:\n\n```java\nString id = m.get(\"ID\");\n```\n\nYou can change the tag delimiters using a method on the pattern matcher:\n\n```java\nParseTreePatternMatcher m = new ParseTreePatternMatcher();\nm.setDelimiters(\"<<\", \">>\", \"$\"); // $ is the escape character\n```\n\nThis would allow pattern `<<ID>> = <<expr>> ;$<< ick $>>` to be interpreted as elements: `ID`, ` = `, `expr`, and ` ;<< ick >>`.\n\n### Pattern labels\n\nThe tree pattern matcher tracks the nodes in the tree at matches against the tags in a tree pattern. That way we can use the `get()` and `getAll()` methods to retrieve components of the matched subtree. For example, for pattern `<ID>`, `get(\"ID\")` returns the node matched for that `ID`. If more than one node matched the specified token or rule tag, only the first match is returned. If there is no node associated with the label, this returns null.\n\nYou can also label the tags with identifiers. If the label is the name of a parser rule or token in the grammar, the resulting list from `getAll()` (or node from `get()`) will contain both the parse trees matching rule or tags explicitly labeled with the label and the complete set of parse trees matching the labeled and unlabeled tags in the pattern for the parser rule or token. For example, if label is `foo`, the result will contain all of the following.\n\n* Parse tree nodes matching tags of the form `<foo:anyRuleName>` and `<foo:AnyTokenName>`.\n* Parse tree nodes matching tags of the form `<anyLabel:foo>`.\n* Parse tree nodes matching tags of the form `<foo>`.\n\n### Creating parse trees with the pattern matcher\n\nYou can use the parse tree pattern compiler to create parse trees for partial input fragments. Just use method `ParseTreePattern.getPatternTree()`.\n\nSee [TestParseTreeMatch.java](https://github.com/antlr/antlr4/blob/master/tool-testsuite/test/org/antlr/v4/test/tool/TestParseTreeMatcher.java).\n\n## Using XPath to identify parse tree node sets\n\nXPath paths are strings representing nodes or subtrees you would like to select within a parse tree. It's useful to collect subsets of the parse tree to process. For example you might want to know where all assignments are in a method or all variable declarations that are initialized.\n\nA path is a series of node names with the following separators.\n\n| Expression |Description|\n|---------|-----------|\n|nodename|\tNodes with the token or rule name nodename\n|/|\tThe root node but `/X` is the same as `X` since the tree you pass to xpath is assumed to be the root. Because it looks better, start all of your patterns with `/` (or `//` below).|\n|//|\tAll nodes in the tree that match the next element in the path. E.g., `//ID` finds all `ID` token nodes in the tree.|\n|!|\tAny node except for the next element in the path. E.g., `/classdef/!field` should find all children of `classdef` root node that are not `field` subtrees.|\n\nExamples:\n\n```\n/prog/func, -> all funcs under prog at root\n/prog/*, -> all children of prog at root\n/*/func, -> all func kids of any root node\nprog, -> prog must be root node\n/prog, -> prog must be root node\n/*, -> any root\n*, -> any root\n//ID, -> any ID in tree\n//expr/primary/ID, -> any ID child of a primary under any expr\n//body//ID, -> any ID under a body\n//'return', -> any 'return' literal in tree\n//primary/*, -> all kids of any primary\n//func/*/stat, -> all stat nodes grandkids of any func node\n/prog/func/'def', -> all def literal kids of func kid of prog\n//stat/';', -> all ';' under any stat node\n//expr/primary/!ID, -> anything but ID under primary under any expr node\n//expr/!primary, -> anything but primary under any expr node\n//!*, -> nothing anywhere\n/!*, -> nothing at root\n```\n\nGiven a parse tree, the typical mechanism for visiting those nodes is the following loop:\n\n```java\nfor (ParseTree t : XPath.findAll(tree, xpath, parser) ) {\n    ... process t ...\n}\n```\n\nE.g., here is a general formula for making a list of the text associated with every node identified by a path specification:\n\n```java\nList<String> nodes = new ArrayList<String>();\nfor (ParseTree t : XPath.findAll(tree, xpath, parser) ) {\n    if ( t instanceof RuleContext) {\n        RuleContext r = (RuleContext)t;\n        nodes.add(parser.getRuleNames()[r.getRuleIndex()]);    }      \n    else { \n        TerminalNode token = (TerminalNode)t;\n        nodes.add(token.getText());\n    }      \n}\n```\n\n## Combining XPath and tree pattern matching\n\nNaturally you can combine the use of XPath to find a set of root nodes and then use tree pattern matching to identify a certain subset of those and extract component nodes.\n\n```java\n// assume we are parsing Java\nParserRuleContext tree = parser.compilationUnit();\nString xpath = \"//blockStatement/*\"; // get children of blockStatement\nString treePattern = \"int <Identifier> = <expression>;\";\nParseTreePattern p =\n    parser.compileParseTreePattern(treePattern,   \n        ExprParser.RULE_localVariableDeclarationStatement);\nList<ParseTreeMatch> matches = p.findAll(tree, xpath);\nSystem.out.println(matches);\n```\n\nSee [TestXPath.java](https://github.com/antlr/antlr4/blob/master/tool-testsuite/test/org/antlr/v4/test/tool/TestXPath.java).\n"
  },
  {
    "path": "doc/typescript-target.md",
    "content": "# TypeScript\n\nAntlr4 TypeScript runtime uses the JavaScript runtime and adds type files to it.\nThis guarantees the same behaviour and performance across both target languages.\nGenerated lexers, parsers, listeners and visitors are generated in TypeScript.\n\nThe runtime is built using TypeScript v4.8.3, node 16.17 and webpack 5.66.\nIt may work with older versions but they have not been tested and they will not be supported.\n\n\n## How to create a TypeScript lexer or parser?\n\nThis is pretty much the same as creating a Java lexer or parser, except you need to specify the language target, for example:\n\n```bash\n$ antlr4 -Dlanguage=TypeScript MyGrammar.g4\n```\n\nFor a full list of antlr4 tool options, please visit the [tool documentation page](tool-options.md).\n\n## Where can I get the runtime?\n\nOnce you've generated the lexer and/or parser code, you need to download the runtime from [npm](https://www.npmjs.com/package/antlr4).\n\nWe will not document here how to refer to the runtime from your project, since this would differ a lot depending on your project type and IDE. \n\n## How do I get the runtime in my browser?\n\nThe runtime is webpacked and sits in the dist folder. A .map file is also provided.\n\n## How do I run the generated lexer and/or parser?\n\nLet's suppose that your grammar is named, as above, \"MyGrammar\". Let's suppose this parser comprises a rule named \"MyStartRule\". The tool will have generated for you the following files:\n\n*   MyGrammarLexer.ts\n*   MyGrammarParser.ts\n*   MyGrammarListener.ts (if you have not activated the -no-listener option)\n*   MyGrammarVisitor.ts (if you have activated the -visitor option)\n   \nThere is no listener or visitor interface generated, instead the generated listener and visitor class methods are implemented using lambdas.\n\nNow a fully functioning script might look like the following:\n\n```typescript\nimport { CharStream, CommonTokenStream }  from 'antlr4';\nimport MyGrammarLexer from './MyGrammarLexer';\nimport MyGrammarParser from './MyGrammarParser';\n\nconst input = \"your text to parse here\"\nconst chars = new CharStream(input); // replace this with a FileStream as required\nconst lexer = new MyGrammarLexer(chars);\nconst tokens = new CommonTokenStream(lexer);\nconst parser = new MyGrammarParser(tokens);\nconst tree = parser.MyStartRule();\n\n```\n\nTha above program will work. But it won't be useful unless you do one of the following:\n\n* you visit the parse tree using a custom listener\n* you visit the parse tree using a custom visitor\n* your grammar contains production code (like AntLR3)\n \n(please note that production code is target specific, so you can't have multi target grammars that include production code)\n \n## How do I create and run a visitor?\n\nYou need to create a custom visitor and use it to visit the parse tree, as follows:\n```typescript\n\nimport { ParserRuleContext } from 'antlr4';\nimport MyGrammarVisitor from './MyGrammarVisitor';\n\nclass CustomVisitor extends MyGrammarVisitor {\n\n  visitChildren(ctx: ParserRuleContext) {\n    if (!ctx) {\n      return;\n    }\n    if (ctx.children) {\n      return ctx.children.map(child => {\n        if (child.children && child.children.length != 0) {\n          return child.accept(this);\n        } else {\n          return child.getText();\n        }\n      });\n    }\n  }\n}\n\ntree.accept(new CustomVisitor());\n````\n\n## How do I create and run a custom listener?\n\nYou need to create a custom listener and use it to visit the parse tree, as follows:\n\n```typescript\n\nimport { ParseTreeWalker } from 'antlr4';\nimport MyGrammarListener from './MyGrammarListener';\n\nclass MyTreeWalker extends MyGrammarListener {\n\n    exitMyStartRule = (ctx: MyStartRuleContext) => {\n        console.log(\"In MyStartRule\");\n    };\n    \n}\n\nconst walker = new MyTreeWalker();\nParseTreeWalker.DEFAULT.walk(walker, tree);\n\n```\n\n## How do I integrate my parser with ACE editor?\n\nThis specific task is described in this [dedicated page](ace-javascript-target.md).\n \n## How can I learn more about ANTLR?\n\nFurther information can be found from  \"The definitive ANTLR 4 reference\" book.\n\nThe TypeScript implementation of ANTLR is based on the JavaScript implementation, which is as close as possible to the Java one, so you shouldn't find it difficult to adapt the book's examples to TypeScript.\n"
  },
  {
    "path": "doc/unicode.md",
    "content": "# Lexers and Unicode text\n\nPrior to ANTLR 4.7, generated lexers in most targets only supported part of the Unicode standard (code points up to `U+FFFF`). As of ANTLR 4.7, the lexers in all language runtimes support the full range of Unicode code points up to `U+10FFFF`. \n\nC++, Python, Go, and Swift APIs didn't need any API changes to support Unicode code points, so we decided to leave those class interfaces as-is. \n\nJava, C#, and JavaScript runtimes required changes and, rather than break the previous interface, we deprecated them. (The *Java-target* deprecated `ANTLRInputStream` and `ANTLRFileStream` APIs only support Unicode code points up to `U+FFFF`.) Now, those targets must create `CharStream`s from input using `CharStreams.fromPath()`, `CharStreams.fromFileName()`, etc... \n\nA big shout out to Ben Hamilton (github bhamiltoncx) for his superhuman\nefforts across all targets to get true support for U+10FFFF code points.\n\n## Example\n\nThe Java, C#, and JavaScript runtimes use the new factory style stream creation interface. For example, here is some sample Java code that uses `CharStreams.fromPath()`:\n\n```java\npublic static void main(String[] args) {\n  CharStream charStream = CharStreams.fromPath(Paths.get(args[0]));\n  Lexer lexer = new UnicodeLexer(charStream);\n  CommonTokenStream tokens = new CommonTokenStream(lexer);\n  tokens.fill();\n  for (Token token : tokens.getTokens()) {\n    System.out.println(\"Got token: \" + token.toString());\n  }\n}\n```\n\n# Unicode Code Points in Lexer Grammars\n\nTo refer to Unicode [code points](https://en.wikipedia.org/wiki/Code_point)\nin lexer grammars, use the `\\u` string escape plus up to 4 hex digits. For example, to create\na lexer rule for a single Cyrillic character by creating a range from\n`U+0400` to `U+04FF`:\n\n```ANTLR\nCYRILLIC : '\\u0400'..'\\u04FF' ; // or [\\u0400-\\u04FF] without quotes\n```\n\nUnicode literals larger than U+FFFF must use the extended `\\u{12345}` syntax. For example, to create a lexer rule for a selection of smiley faces\nfrom the [Emoticons Unicode block](http://www.unicode.org/charts/PDF/U1F600.pdf):\n\n```ANTLR\nEMOTICONS : ('\\u{1F600}' | '\\u{1F602}' | '\\u{1F615}') ; // or [\\u{1F600}\\u{1F602}\\u{1F615}]\n```\n\nFinally, lexer char sets can include Unicode properties. Each Unicode code point has at least one property that describes the type group to which it belongs (e.g. alpha, number, punctuation). Other properties can be the language script or special binary properties and Unicode code blocks. That means however, that a property specifies a group of code points, hence they are only allowed in lexer char sets.\n\n```ANTLR\nEMOJI : [\\p{Emoji}] ;\nJAPANESE : [\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Han}] ;\nNOT_CYRILLIC : [\\P{Script=Cyrillic}] ;\n```\n\nSee [lexer-rules.md](lexer-rules.md#lexer-rule-elements) for more detail on Unicode\nescapes in lexer rules.\n\n## Migration\n\n\nCode for **4.6** looked like this:\n\n\n```java\nCharStream input = new ANTLRFileStream(\"myinputfile\");\nJavaLexer lexer = new JavaLexer(input);\nCommonTokenStream tokens = new CommonTokenStream(lexer);\n```\n\n(It didn't use UTF-8 by default, despite the documentation saying so previously; it actually depended on the calling environments default.)\n\nCode for **4.7** assumes UTF-8 by default and looks like this:\n\n```java\nCharStream input = CharStreams.fromFileName(\"inputfile\");\nJavaLexer lexer = new JavaLexer(input);\nCommonTokenStream tokens = new CommonTokenStream(lexer);\n```\n\nOr, if you'd like to specify the file encoding:\n\n```java\nCharStream input = CharStreams.fromFileName(\"inputfile\", Charset.forName(\"windows-1252\"));\n```\n\n### Motivation\n\nAfter a [lively discussion](https://github.com/antlr/antlr4/pull/1771), I (parrt) decided not to simply gut the 4.6 `ANTLRFileStream` and `ANTLRInputStream` to incorporate the new U+10FFFF functionality. I decided to *deprecate* the old interface and recommend use of the new interface to prevent confusion. My reasoning is summarized as:\n\n* I didn't like the idea of breaking all 4.6 code. To get the previous streams to properly support > 16 bit Unicode would require a lot of changes to the method signatures.\n* Using `int` buffer element types would double the size of memory required to hold streams in memory, given that we buffer everything (and I didn't want to change that aspect of the streams).\n* The new factory-style interface supports creation of the smallest possible code point buffer element size according to the Unicode code points found in the input stream. This means using half as much memory\nas the old {@link ANTLRFileStream}, which assumed 16-bit characters, for ASCII text.\n* Through some [serious testing and performance tweaking](https://github.com/antlr/antlr4/pull/1781), the new streams perform as fast or faster than the 4.6 streams.\n\n**WARNING**. *You should avoid using both the deprecated and the new streams* in the same application because you will see \na nontrivial performance degradation. This speed hit is because the \n`Lexer`'s internal code goes from a monomorphic to megamorphic\ndynamic dispatch to get characters from the input stream. Java's\non-the-fly compiler (JIT) is unable to perform the same optimizations\nso stick with either the old or the new streams, if performance is\na primary concern. See the [extreme debugging and spelunking](https://github.com/antlr/antlr4/pull/1781) needed to identify this issue in our timing rig.\n\n### Legacy grammar using surrogate code units\n\nLegacy grammars that did their own UTF-16 surrogate code unit matching will need to continue to use `ANTLRInputStream` (Java target) until the parser-application code can upgrade to `CharStreams` interface. Then the surrogate code unit matching should be removed from the grammar in favor of letting the new streams do the decoding.  \n\nPrior to 4.7, application code could directly pass `Token.getStartIndex()` and `Token.getStopIndex()` to Java and C# String APIs (because both used UTF-16 code units as the fundamental unit of length).  With the new streams, clients will have to convert from code point indices to UTF-16 code unit indices. Here is some (Java) code to show you the necessary logic:\n\n```java\npublic final class CodePointCounter {\n  private final String input;\n  public int inputIndex = 0;\n  public int codePointIndex = 0;\n  \n  public int advanceToIndex(int newCodePointIndex) {\n    assert newCodePointIndex >= codePointIndex;\n    while (codePointIndex < newCodePointOffset) {\n        int codePoint = Character.codePointAt(input, inputIndex);\n        inputIndex += Character.charCount(codePoint);\n        codePointIndex++;\n    }\n    return inputIndex;\n  }\n}\n```\n\n### Character Buffering, Unbuffered streams\n\nThe ANTLR character streams still buffer all the input when you create\nthe stream, as they have done for ~20 years. \n\nIf you need unbuffered\naccess, please note that it becomes challenging to create\nparse trees. The parse tree has to point to tokens which will either\npoint into a stale location in an unbuffered stream or you have to copy\nthe characters out of the buffer into the token. That defeats the purpose\nof unbuffered input. See the [ANTLR 4 book](https://www.amazon.com/Definitive-ANTLR-4-Reference/dp/1934356999) \"13.8 Unbuffered Character and Token Streams\". Unbuffered streams are primarily\nuseful for processing infinite streams *during the parse* and require that you manually buffer characters. Use `UnbufferedCharStream` and `UnbufferedTokenStream`.\n\n```java\nCharStream input = new UnbufferedCharStream(is);\nCSVLexer lex = new CSVLexer(input); // copy text out of sliding buffer and store in tokens\nlex.setTokenFactory(new CommonTokenFactory(true));\nTokenStream tokens = new UnbufferedTokenStream<CommonToken>(lex);\nCSVParser parser = new CSVParser(tokens);\nparser.setBuildParseTree(false);\nparser.file();\n```\n\nYour grammar that needs to have embedded actions that access the tokens as they are created, but before they disappear and are garbage collected. For example,\n\n```\ndata : a=INT {int x = Integer.parseInt($a.text);} ;\n```\n\nFrom the code comments of `CommonTokenFactory`:\n\n> That `true` in `new CommonTokenFactory(true)` indicates whether `CommonToken.setText` should be called after \nconstructing tokens to explicitly set the text. This is useful for cases\nwhere the input stream might not be able to provide arbitrary substrings\nof text from the input after the lexer creates a token (e.g. the\nimplementation of `CharStream.getText` in\n`UnbufferedCharStream` throws an\n`UnsupportedOperationException`). Explicitly setting the token text\nallows `Token.getText` to be called at any time regardless of the\ninput stream implementation.\n\n*Currently, only Java, C++, and C# have these unbuffered streams implemented*.\n"
  },
  {
    "path": "doc/wildcard.md",
    "content": "# Wildcard Operator and Nongreedy Subrules\n\nEBNF subrules like `(...)?`, `(...)*` and `(...)+` are greedy—They consume as much input as possible, but sometimes that’s not what’s needed. Constructs like `.*` consume until the end of the input in the lexer and sometimes in the parser. We want that loop to be nongreedy so we need to use different syntax: `.*?` borrowed from regular expression notation. We can make any subrule that has a `?`, `*`, or `+` suffix nongreedy by adding another `?` suffix. Such nongreedy subrules are allowed in both the parser and the lexer, but they are used much more frequently in the lexer.\n\n## Nongreedy Lexer Subrules\n\nHere’s the very common C-style comment lexer rule that consumes any characters until it sees the trailing `*/`:\n\n```\nCOMMENT : '/*' .*? '*/' -> skip ; // .*? matches anything until the first */\n```\n\nHere’s another example that matches strings that allow \\\" as an escaped quote character:\n\n```\ngrammar Nongreedy;\ns : STRING+ ;\nSTRING : '\"' ( '\\\\\"' | . )*? '\"' ; // match \"foo\", \"\\\"\", \"x\\\"\\\"y\", ...\nWS : [ \\r\\t\\n]+ -> skip ;\n```\n\n```bash\n$ antlr4 Nongreedy.g4\n$ javac Nongreedy*.java\n$ grun Nongreedy s -tokens\n=> \t\"quote:\\\"\"\n=> \tEOF\n<= \t[@0,0:9='\"quote:\\\"\"',<1>,1:0]\n \t[@1,11:10='<EOF>',<-1>,2:0]\n```\n\nNongreedy subrules should be used sparingly because they complicate the recognition problem and sometimes make it tricky to decipher how the lexer will match text. Here is how the lexer chooses token rules:\n\n<ol>\n<li>The primary goal is to match the lexer rule that recognizes the most input characters.\n\n```\nINT : [0-9]+ ;\nDOT : '.' ; // match period\nFLOAT : [0-9]+ '.' ; // match FLOAT upon '34.' not INT then DOT\n```\n</li>\n<li>\nIf more than one lexer rule matches the same input sequence, the priority goes to the rule occurring first in the grammar file.\n\n```\nDOC : '/**' .*? '*/' ; // both rules match /** foo */, resolve to DOC\nCMT : '/*' .*? '*/' ;\n```\n</li>\n<li>\nNongreedy subrules match the fewest number of characters that still allows the surrounding lexical rule to match.\n\n```\n/** Match anything except \\n inside of double angle brackets */\nSTRING : '<<' ~'\\n'*? '>>' ; // Input '<<foo>>>>' matches STRING then END\nEND    : '>>' ;\n```\n</li>\n<li>\n<p>After crossing through a nongreedy subrule within a lexical rule, all decision-making from then on is \"first match wins.\"\n</p>\n<p>\nFor example, literal `ab` in rule right-hand side (grammar fragment) `.*? ('a'|'ab')` is dead code and can never be matched. If the input is ab, the first alternative, 'a', matches the first character and therefore succeeds. ('a'|'ab') by itself on the right-hand side of a rule properly matches the second alternative for input ab. This quirk arises from a nongreedy design decision that’s too complicated to go into here.</p>\n<li>\n</ol>\n\nTo illustrate the different ways to use loops within lexer rules, consider the following grammar, which has three different action-like tokens (using different delimiters so that they all fit within one example grammar).\n\n```\nACTION1 : '{' ( STRING | . )*? '}' ; // Allows {\"foo}\nACTION2 : '[' ( STRING | ~'\"' )*? ']' ; // Doesn't allow [\"foo]; nongreedy *?\nACTION3 : '<' ( STRING | ~[\">] )* '>' ; // Doesn't allow <\"foo>; greedy *\nSTRING : '\"' ( '\\\\\"' | . )*? '\"' ;\n```\n\nRule `ACTION1` allows unterminated strings, such as `\"foo`, because input `\"foo` matches to the wildcard part of the loop. It doesn’t have to go into rule `STRING` to match a quote. To fix that, rule `ACTION2` uses `~'\"'` to match any character but the quote. Expression `~'\"'` is still ambiguous with the `']'` that ends the rule, but the fact that the subrule is nongreedy means that the lexer will exit the loop upon a right square bracket. To avoid a nongreedy subrule, make the alternatives explicit. Expression `~[\">]` matches anything but the quote and right angle bracket. Here’s a sample run:\n\n```bash\n$ antlr4 Actions.g4\n$ javac Actions*.java\n$ grun Actions tokens -tokens\n=> \t{\"foo}\n=> \tEOF\n<= \t[@0,0:5='{\"foo}',<1>,1:0]\n \t[@1,7:6='<EOF>',<-1>,2:0]\n=> \t$ grun Actions tokens -tokens\n=> \t[\"foo]\n=> \tEOF\n<= \tline 1:0 token recognition error at: '[\"foo]\n \t'\n \t[@0,7:6='<EOF>',<-1>,2:0]\n=> \t$ grun Actions tokens -tokens\n=> \t<\"foo>\n=> \tEOF\n<= \tline 1:0 token recognition error at: '<\"foo>\n \t'\n \t[@0,7:6='<EOF>',<-1>,2:0]\n```\n\n## Nongreedy Parser Subrules\n\nNongreedy subrules and wildcard are also useful within parsers to do *fuzzy parsing* where the goal is to extract information from an input file without having to specify the full grammar. In contrast to nongreedy lexer decision-making, parsers always make globally correct decisions. A parser never makes a decision that will ultimately cause valid input to fail later on during the parse. Here is the central idea: Nongreedy parser subrules match the shortest sequence of tokens that preserves a successful parse for a valid input sentence.\n\nFor example, here are the key rules that demonstrate how to pull integer constants out of an arbitrary Java file:\n\n```\ngrammar FuzzyJava;\n \n/** Match anything in between constant rule matches */\nfile : .*? (constant .*?)+ ;\n \n/** Faster alternate version (Gets an ANTLR tool warning about\n * a subrule like .* in parser that you can ignore.)\n */\naltfile : (constant | .)* ; // match a constant or any token, 0-or-more times\n\n/** Match things like \"public static final SIZE\" followed by anything */\nconstant\n    :   'public' 'static' 'final' 'int' Identifier\n        {System.out.println(\"constant: \"+$Identifier.text);}\n    ;\n \nIdentifier : [a-zA-Z_$] [a-zA-Z_$0-9]* ; // simplified\n```\n\nThe grammar contains a greatly simplified set of lexer rules from a real Java lexer; the whole file about 60 lines. The recognizer still needs to handle string and character constants as well as comments so it doesn’t get out of sync, trying to match a constant inside of the string for example. The only unusual lexer rule performs “match any character not matched by another lexer rule” functionality:\n\n```\nOTHER : . -> skip ;\n```\n\nThis catchall lexer rule and the `.*?` subrule in the parser are the critical ingredients for fuzzy parsing.\n\nHere’s a sample file that we can run into the fuzzy parser:\n\n```java\nimport java.util.*;\npublic class C {\n    public static final int A = 1;\n    public static final int B = 1;\n    public void foo() { }\n    public static final int C = 1;\n}\n```\n\nAnd here’s the build and test sequence:\n\n```bash\n$ antlr4 FuzzyJava.g4\n$ javac FuzzyJava*.java\n$ grun FuzzyJava file C.java\nconstant: A\nconstant: B\nconstant: C\n```\n\nNotice that it totally ignores everything except for the `public static final int` declarations. This all happens with only two parser rules.\n\nNow let's try matching some simple class defs w/o having to build parser rules for the junk inside.  Here want to catch just `A` and `B`:\n\n```\nclass A {\n        String name = \"parrt\";\n}\n\nclass B {\n        int x;   \n        int getDubX() {\n                return 2*x;\n        }\n}\n```\n\nThis grammar does it.\n\n```\ngrammar Island;\nfile : clazz* ;\nclazz : 'class' ID '{' ignore '}' ;\nignore : (method|.)*? ;\nmethod : type ID '()' block ;\ntype : 'int' | 'void' ;\nblock : '{' (block | .)*? '}' ;\nID : [a-zA-Z] [a-zA-Z0-9]* ;\nWS : [ \\r\\t\\n]+ -> skip ;\nANY : . ;\n```\n\nYou get:\n\n<img src=images/nonnested-fuzzy.png width=450>\n\nNow let's try some nested classes\n\n```\nclass A {\n        String name = \"parrt\";\n        class Nested {\n            any filthy shite we want in here { }}}}}}\n        }\n}\n\nclass B {\n        int x;   \n        int getDubX() {\n                return 2*x;\n        }\n}\n\n```\n\n```\ngrammar Island;\nfile : clazz* ;\nclazz : 'class' ID '{' ignore '}' ;\nignore : (method|clazz|.)*? ; // <- only change is to add clazz alt here\nmethod : type ID '()' block ;\ntype : 'int' | 'void' ;\nblock : '{' (block | .)*? '}' ;\nID : [a-zA-Z] [a-zA-Z0-9]* ;\nWS : [ \\r\\t\\n]+ -> skip ;\nANY : . ;\n```\n\nYou get:\n\n<img src=images/nested-fuzzy.png width=600>\n"
  },
  {
    "path": "docker/.dockerignore",
    "content": "tool-testsuite\nruntime-testsuite\n.git*\nREADME.adoc\nREADME.md\ncache\ntests\n"
  },
  {
    "path": "docker/Dockerfile",
    "content": "FROM eclipse-temurin:21 AS builder\n\nWORKDIR /opt/antlr4\n\nARG ANTLR_VERSION=\"4.13.2\"\nARG MAVEN_OPTS=\"-Xmx1G\"\n\n\nRUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install maven git -y \\\n    && git clone https://github.com/antlr/antlr4.git \\\n    && cd antlr4 \\\n    && git checkout $ANTLR_VERSION \\\n    && mvn clean --projects tool --also-make \\\n    && mvn -DskipTests install --projects tool --also-make \\\n    && mv ./tool/target/antlr4-*-complete.jar antlr4-tool.jar\n\nFROM eclipse-temurin:21-jre\n\nCOPY --from=builder /opt/antlr4/antlr4/antlr4-tool.jar /usr/local/lib/\nWORKDIR /work\nENTRYPOINT [\"java\", \"-Xmx500M\", \"-cp\", \"/usr/local/lib/antlr4-tool.jar\", \"org.antlr.v4.Tool\"]\n"
  },
  {
    "path": "docker/README.md",
    "content": "# Docker Image for ANTLR4\n\nThis Docker image wraps current version of **ANTLR4** inclusive **Java runtime environment** so it can be executed as transparent command line tool even on machines without installed Java.\n\n## Docker Image\n\nThe image uses the official [eclipse-temurin:11](https://hub.docker.com/_/eclipse-temurin/tags?page=1&name=11&ordering=-name) image\nfor building a distribution of ANTLR4 and [eclipse-temurin:11-jre](https://hub.docker.com/_/eclipse-temurin/tags?page=1&name=11-jre&ordering=-name) for runtime.\n\n## Build\n\nYou can build docker image from source code locally. \n\n    git clone https://github.com/antlr/antlr4.git\n    cd antlr4/docker\n    docker build -t antlr/antlr4 --platform linux/amd64 .\n\n\n## Run\n\nFor security reasons is **ANTLR4 Docker image** designed to run in the current folder only, so a container doesn't have any access to any other folders on a host system. Since this is a transparent call of Docker image from command line, where new files are generated, it is also a good idea to execute code inside a Docker as a non root user and match it to the host caller.\n\nCalling a dockerized ANTLR4 image can look like this:\n\n```shell\nwget https://raw.githubusercontent.com/antlr/grammars-v4/master/json/JSON.g4\ndocker run --rm -u $(id -u ${USER}):$(id -g ${USER}) -v `pwd`:/work antlr/antlr4 -Dlanguage=Go JSON.g4\n```\n\n## Integration as alias\n\n      alias antlr4='docker run -it -u $(id -u ${USER}):$(id -g ${USER}) -v $(pwd):/work antlr/antlr4 $@'\n\n\n"
  },
  {
    "path": "historical-contributors-agreement.txt",
    "content": "ANTLR Project Contributors Certification of Origin and Rights\n\nAll contributors to ANTLR v4 must formally agree to abide by this\ncertificate of origin by signing on the bottom with their github\nuserid, full name, email address (you can obscure your e-mail, but it\nmust be computable by human), and date.\n\nBy signing this agreement, you are warranting and representing that\nyou have the right to release code contributions or other content free\nof any obligations to third parties and are granting Terence Parr and\nANTLR project contributors, henceforth referred to as The ANTLR\nProject, a license to incorporate it into The ANTLR Project tools\n(such as ANTLRWorks and StringTemplate) or related works under the BSD\nlicense. You understand that The ANTLR Project may or may not\nincorporate your contribution and you warrant and represent the\nfollowing:\n\n1. I am the creator of all my contributions. I am the author of all\n   contributed work submitted and further warrant and represent that\n   such work is my original creation and I have the right to license\n   it to The ANTLR Project for release under the 3-clause BSD\n   license. I hereby grant The ANTLR Project a nonexclusive,\n   irrevocable, royalty-free, worldwide license to reproduce,\n   distribute, prepare derivative works, and otherwise use this\n   contribution as part of the ANTLR project, associated\n   documentation, books, and tools at no cost to The ANTLR Project.\n\n2. I have the right to submit. This submission does not violate the\n   rights of any person or entity and that I have legal authority over\n   this submission and to make this certification.\n\n3. If I violate another's rights, liability lies with me. I agree to\n   defend, indemnify, and hold The ANTLR Project and ANTLR users\n   harmless from any claim or demand, including reasonable attorney\n   fees, made by any third party due to or arising out of my violation\n   of these terms and conditions or my violation of the rights of\n   another person or entity.\n\n4. I understand and agree that this project and the contribution are\n   public and that a record of the contribution (including all\n   personal information I submit with it, including my sign-off) is\n   maintained indefinitely and may be redistributed consistent with\n   this project or the open source license indicated in the file.\n\nI have read this agreement and do so certify by adding my signoff to\nthe end of the following contributors list.\n\nCONTRIBUTORS:\n\nYYYY/MM/DD, github id, Full name, email\n2012/07/12, parrt, Terence Parr, parrt@antlr.org\n2012/09/18, sharwell, Sam Harwell, sam@tunnelvisionlabs.com\n2012/10/10, stephengaito, Stephen Gaito, stephen@percepitsys.co.uk\n2012/11/23, maguro, Alan Cabrera, adc@toolazydogs.com\n2013/01/29, metadave, Dave Parfitt, diparfitt@gmail.com\n2013/03/06, bkiers, Bart Kiers, bkiers@gmail.com\n2013/08/20, cayhorstmann, Cay Horstmann, cay@horstmann.com\n2014/03/18, aphyr, Kyle Kingsbury, aphyr@aphyr.com\n2014/06/07, ericvergnaud, Eric Vergnaud, eric.vergnaud@wanadoo.fr\n2014/07/04, jimidle, Jim Idle, jimi@Idle.ws\n2014/01/01, danmclaughlin, Dan McLaughlin, dan.mclaughlin@gmail.com\n2014/09/04. jeduden, Jan-Eric Duden, jeduden@gmail.com\n2014/09/27, petrbel, Petr Bělohlávek, antlr@petrbel.cz\n2014/10/18, sergiusignacius, Sérgio Silva, serge.a.silva@gmail.com\n2014/10/26, bdkearns, Brian Kearns, bdkearns@gmail.com\n2014/10/27, michaelpj, Michael Peyton Jones, michaelpj@gmail.com\n2015/01/29, TomLottermann, Thomas Lottermann, tomlottermann@gmail.com\n2015/02/15, pavlo, Pavlo Lysov, pavlikus@gmail.com\n2015/03/07, RedTailedHawk, Lawrence Parker, larry@answerrocket.com\n2015/04/03, rljacobson, Robert Jacobson, rljacobson@gmail.com\n2015/04/06, ojakubcik, Ondrej Jakubcik, ojakubcik@gmail.com\n2015/04/29, jszheng, Jinshan Zheng, zheng_js@hotmail.com\n2015/05/08, ViceIce, Michael Kriese, michael.kriese@gmx.de\n2015/05/09, lkraz, Luke Krasnoff, luke.krasnoff@gmail.com\n2015/05/12, Pursuit92, Josh Chase, jcjoshuachase@gmail.com\n2015/05/20, peturingi, Pétur Ingi Egilsson, petur@petur.eu\n2015/05/27, jcbrinfo, Jean-Christophe Beaupré, jcbrinfo@users.noreply.github.com\n2015/06/29, jvanzyl, Jason van Zyl, jason@takari.io\n2015/08/18, krzkaczor, Krzysztof Kaczor, krzysztof@kaczor.io\n2015/09/18, worsht, Rajiv Subrahmanyam, rajiv.public@gmail.com\n2015/09/24, HSorensen, Henrik Sorensen, henrik.b.sorensen@gmail.com\n2015/10/06, brwml, Bryan Wilhelm, bryan.wilhelm@microsoft.com\n2015/10/08, fedotovalex, Alex Fedotov, me@alexfedotov.com\n2015/10/12, KvanTTT, Ivan Kochurkin, ivan.kochurkin@gmail.com\n2015/10/21, martin-probst, Martin Probst, martin-probst@web.de\n2015/10/21, hkff, Walid Benghabrit, walid.benghabrit@mines-nantes.fr\n2015/11/12, cooperra, Robbie Cooper, cooperra@users.noreply.github.com\n2015/11/25, abego, Udo Borkowski, ub@abego.org\n2015/12/17, sebadur, Sebastian Badur, sebadur@users.noreply.github.com\n2015/12/23, pboyer, Peter Boyer, peter.b.boyer@gmail.com\n2015/12/24, dtymon, David Tymon, david.tymon@gmail.com\n2016/02/18, reitzig, Raphael Reitzig, reitzig[at]cs.uni-kl.de\n2016/03/10, mike-lischke, Mike Lischke, mike@lischke-online.de\n2016/03/27, beardlybread, Bradley Steinbacher, bradley.j.steinbacher@gmail.com\n2016/03/29, msteiger, Martin Steiger, antlr@martin-steiger.de\n2016/03/28, gagern, Martin von Gagern, gagern@ma.tum.de\n2016/07/10, twz123, Tom Wieczorek, tom.wieczorek@zalando.de\n2016/07/20, chrisheller, Chris Heller, chris.heller.greyheller@gmail.com\n2016/07/20, nburles, Nathan Burles, nburles@gmail.com\n2016/07/20, kosl90, Li Liqiang, kos1990l@gmail.com\n2016/07/27, timoc, Tim O'Callaghan, timo@linux.com\n2016/07/26, nic30, Michal Orsák, michal.o.socials@gmail.com\n2016/07/18, willfaught, Will Faught, will.faught@gmail.com\n2016/08/08, wjkohnen, Wolfgang Johannes Kohnen, wjkohnen-go-antlr@ko-sys.com\n2016/08/11, BurtHarris, Ralph \"Burt\" Harris, Burt_Harris_antlr4@azxs.33mail.com\n2016/08/19, andjo403, Andreas Jonson, andjo403@hotmail.com\n2016/09/27, harriman, Kurt Harriman, harriman@acm.org\n2016/10/13, cgudrian, Christian Gudrian, christian.gudrian@gmx.de\n2016/10/13, nielsbasjes, Niels Basjes, niels@basjes.nl\n2016/10/21, FloorGoddijn, Floor Goddijn, floor.goddijn[at]aimms.com\n2016/11/01, RYDB3RG, Kai Stammerjohann, RYDB3RG@users.noreply.github.com\n2016/11/05, runner-mei, meifakun, runner.mei@gmail.com\n2016/11/15, hanjoes, Hanzhou Shi, hanzhou87@gmail.com\n2016/11/16, sridharxp, Sridharan S, aurosridhar@gmail.com\n2016/11/06, NoodleOfDeath, Thom Morgan, github@bytemeapp.com\n2016/11/01, sebkur, Sebastian Kürten, sebastian@topobyte.de\n2016/04/13, renatahodovan, Renata Hodovan, reni@inf.u-szeged.hu\n2016/11/05, ewanmellor, Ewan Mellor, github@ewanmellor.org\n2016/11/06, janyou, Janyou, janyou.antlr@outlook.com\n2016/11/20, marcohu, Marco Hunsicker, antlr@hunsicker.de\n2016/09/02, lygav, Vladimir (Vladi) Lyga, lyvladi@gmail.com\n2016/09/23, ghosthope, Dmitry Shakhtanov, sudstrike@gmail.com\n2016/11/25, MrSampson, Oliver Sampson, olsam@quickaudio.com\n2016/11/29, millergarym, Gary Miller, miller.garym@gmail.com\n2016/11/29, wxio, Gary Miller, gm@wx.io\n2016/11/29, Naios, Denis Blank, naios@users.noreply.github.com\n2016/12/01, samtatasurya, Samuel Tatasurya, xemradiant@gmail.com\n2016/12/03, redxdev, Samuel Bloomberg, sam@redxdev.com\n2016/12/11, Gaulouis, Gaulouis, gaulouis.com@gmail.com\n2016/12/22, akosthekiss, Akos Kiss, akiss@inf.u-szeged.hu\n2016/12/24, adrpo, Adrian Pop, adrian.pop@liu.se\n2017/01/11, robertbrignull, Robert Brignull, robertbrignull@gmail.com\n2017/01/13, marcelo-rocha, Marcelo Rocha, mcrocha@gmail.com\n2017/01/23, bhamiltoncx, Ben Hamilton, bhamiltoncx+antlr@gmail.com\n2017/01/18, mshockwave, Bekket McClane, yihshyng223@gmail.com\n2017/02/10, lionelplessis, Lionel Plessis, lionelplessis@users.noreply.github.com\n2017/02/14, lecode-official, David Neumann, david.neumann@lecode.de\n2017/02/14, xied75, Dong Xie, xied75@gmail.com\n2017/02/20, Thomasb81, Thomas Burg, thomasb81@gmail.com\n2017/02/26, jvasileff, John Vasileff, john@vasileff.com\n2017/03/08, harry-tallbelt, Igor Vysokopoyasny, harry.tallbelt@gmail.com\n2017/03/09, teverett, Tom Everett, tom@khubla.com\n2017/03/03, chund, Christian Hund, christian.hund@gmail.com\n2017/03/15, robertvanderhulst, Robert van der Hulst, robert@xsharp.eu\n2017/03/28, cmd-johnson, Jonas Auer, jonas.auer.94@gmail.com\n2017/04/12, lys0716, Yishuang Lu, luyscmu@gmail.com\n2017/04/30, shravanrn, Shravan Narayan, shravanrn@gmail.com\n2017/05/11, jimallman, Jim Allman, jim@ibang.com\n2017/05/26, waf, Will Fuqua, wafuqua@gmail.com\n2017/05/29, kosak, Corey Kosak, kosak@kosak.com\n2017/06/11, erikbra, Erik A. Brandstadmoen, erik@brandstadmoen.net\n2017/06/10, jm-mikkelsen, Jan Martin Mikkelsen, janm@transactionware.com\n2017/06/25, alimg, Alim Gökkaya, alim.gokkaya@gmail.com\n2017/06/28, jBugman, Sergey Parshukov, codedby@bugman.me\n2017/07/09, neatnerd, Mike Arshinskiy, neatnerd@users.noreply.github.com\n2017/07/11, dhalperi, Daniel Halperin, daniel@halper.in\n2017/07/17, vaibhavaingankar09, Vaibhav Vaingankar, vbhvvaingankar9@gmail.com\n2017/07/23, venkatperi, Venkat Peri, venkatperi@gmail.com\n2017/07/27, shirou, WAKAYAMA Shirou, shirou.faw@gmail.com\n2017/07/09, neatnerd, Mike Arshinskiy, neatnerd@users.noreply.github.com\n2017/07/27, matthauck, Matt Hauck, matthauck@gmail.com\n2017/07/27, shirou, WAKAYAMA Shirou, shirou.faw@gmail.com\n2017/08/20, tiagomazzutti, Tiago Mazzutti, tiagomzt@gmail.com\n2017/08/20, milanaleksic, Milan Aleksic, milanaleksic@gmail.com\n2017/08/29, Eddy Reyes, eddy@mindsight.io\n2017/09/09, brauliobz, Bráulio Bezerra, brauliobezerra@gmail.com\n2017/09/11, sachinjain024, Sachin Jain, sachinjain024@gmail.com\n2017/09/25, kaedvann, Rostislav Listerenko, r.listerenko@gmail.com\n2017/10/06, bramp, Andrew Brampton, brampton@gmail.com\n2017/10/15, simkimsia, Sim Kim Sia, kimcity@gmail.com\n2017/10/27, Griffon26, Maurice van der Pot, griffon26@kfk4ever.com\n2017/05/29, rlfnb, Ralf Neeb, rlfnb@rlfnb.de\n2017/10/29, gendalph, Максим Прохоренко, Maxim\\dotProhorenko@gm@il.com\n2017/11/02, jasonmoo, Jason Mooberry, jason.mooberry@gmail.com\n2017/11/05, ajaypanyala, Ajay Panyala, ajay.panyala@gmail.com\n2017/11/24, zqlu.cn, Zhiqiang Lu, zqlu.cn@gmail.com\n2017/11/28, niccroad, Nicolas Croad, nic.croad@gmail.com\n2017/12/01, DavidMoraisFerreira, David Morais Ferreira, david.moraisferreira@gmail.com\n2017/12/01, SebastianLng, Sebastian Lang, sebastian.lang@outlook.com\n2017/12/03, oranoran, Oran Epelbaum, oran / epelbaum me\n2017/12/12, janlinde, Jan Lindemann, jan@janware.com\n2017/12/13, enessoylu, Enes Soylu, enessoylutr@gmail.com\n2017/12/20, kbsletten, Kyle Sletten, kbsletten@gmail.com\n2017/12/27, jkmar, Jakub Marciniszyn, marciniszyn.jk@gmail.com\n2018/03/08, dannoc, Daniel Clifford, danno@google.com\n2018/03/10, uvguy, kangjoni76@gmail.com\n2018/01/06, kasbah, Kaspar Emanuel, kaspar@monostable.co.uk\n2018/01/15, xgcssch, Sönke Schau, xgcssch@users.noreply.github.com\n2018/02/08, razfriman, Raz Friman, raz@razfriman.com\n2018/02/11, io7m, Mark Raynsford, code@io7m.com\n2018/04/24, solussd, Joe Smith, joe@uwcreations.com\n2018/15/05, johnvanderholt, jan dillingh johnvanderholte@gmail.com\n2018/06/14, scadgek, Sergey Chupov, scadgek@live.com\n2018/06/16, EternalPhane, Zongyuan Zuo, eternalphane@gmail.com\n2018/06/27, wu-sheng, Wu Sheng, wu.sheng@foxmail.com\n2018/02/25, chaseoxide, Marcus Ong, taccs97[at]gmail[dot]com\n2018/05/15, johnvanderholt, jan dillingh johnvanderholte@gmail.com\n2018/06/16, EternalPhane, Zongyuan Zuo, eternalphane@gmail.com\n2018/05/15, johnvanderholt, jan dillingh johnvanderholte@gmail.com\n2018/05/17, sinopsysHK, Eric Bardes, sinofwd@gmail.com\n2018/05/23, srvance, Stephen Vance, steve@vance.com\n2018/06/14, alecont, Alessandro Contenti, alecontenti@hotmail.com\n2018/06/16, EternalPhane, Zongyuan Zuo, eternalphane@gmail.com\n2018/07/03, jgoppert, James Goppert, james.goppert@gmail.com\n2018/07/27, Maksim Novikov, mnovikov.work@gmail.com\n2018/08/03, ENDOH takanao, djmchl@gmail.com\n2018/10/08, xsIceman, Andreas Skaar, andreas.skaar@gmail.com\n2018/10/18, edirgarcia, Edir García Lazo, edirgl@hotmail.com\n2018/07/31, Lucas Henrqiue, lucashenrique580@gmail.com\n2018/08/03, ENDOH takanao, djmchl@gmail.com\n2018/10/29, chrisaycock, Christopher Aycock, chris[at]chrisaycock[dot]com\n2018/11/12, vinoski, Steve Vinoski, vinoski@ieee.org\n2018/11/14, nxtstep, Adriaan (Arjan) Duz, codewithadriaan[et]gmail[dot]com\n2018/11/15, amykyta3, Alex Mykyta, amykyta3@users.noreply.github.com\n2018/11/29, hannemann-tamas, Ralf Hannemann-Tamas, ralf.ht@gmail.com\n2018/12/20, WalterCouto, Walter Couto, WalterCouto@users.noreply.github.com\n2018/12/23, youkaichao, Kaichao You, youkaichao@gmail.com\n2019/01/01, khoroshilov, Alexey Khoroshilov, khoroshilov@ispras.ru\n2019/01/02, wkhemir, Wail Khemir, khemirwail@gmail.com\n2019/01/16, kuegi, Markus Zancolo, markus.zancolo@roomle.com\n2019/01/29, hc-codersatlas, Harry Chan, harry.chan@codersatlas.com\n2019/02/06, ralucado, Cristina Raluca Vijulie, ralucris.v[at]gmail[dot]com\n2019/02/23, gedimitr, Gerasimos Dimitriadis, gedimitr@gmail.com\n2019/03/13, base698, Justin Thomas, justin.thomas1@gmail.com\n2019/03/18, carlodri, Carlo Dri, carlo.dri@gmail.com\n2019/05/02, askingalot, Andy Collins, askingalot@gmail.com\n2019/05/13, mapio, Massimo Santini, massimo.santini@gmail.com\n2019/07/11, olowo726, Olof Wolgast, olof@baah.se\n2019/07/16, abhijithneilabraham, Abhijith Neil Abraham, abhijithneilabrahampk@gmail.com\n2019/07/26, Braavos96, Eric Hettiaratchi, erichettiaratchi@gmail.com\n2019/08/02, thron7, Thomas Herchenroeder, thron7[at]users[dot]sourceforge[dot]net\n2019/08/12, easonlin404, Eason Lin, easonlin404@gmail.com\n2019/08/23, akaJes, Oleksandr Mamchyts, akaJes@gmail.com\n2019/08/27, wurzelpeter, Markus Franke, markus[hyphen]franke[at]web[dot]de\n2019/09/10, ImanHosseini, Iman Hosseini, hosseini.iman@yahoo.com\n2019/09/03, João Henrique, johnnyonflame@hotmail.com\n2019/09/10, neko1235, Ihar Mokharau, igor.mohorev@gmail.com\n2019/09/10, yar3333, Yaroslav Sivakov, yar3333@gmail.com\n2019/09/10, marcospassos, Marcos Passos, marcospassos.com@gmail.com\n2019/09/10, amorimjuliana, Juliana Amorim, juu.amorim@gmail.com\n2019/09/15, sullis, Sean Sullivan, github@seansullivan.com\n2019/09/17, kaz, Kazuki Sawada, kazuki@6715.jp\n2019/09/28, lmy269, Mingyang Liu, lmy040758@gmail.com\n2019/10/29, tehbone, Tabari Alexander, tehbone@gmail.com\n2019/10/31, a-square, Alexei Averchenko, lex.aver@gmail.com\n2019/11/05, listba, Ben List, ben.list89@gmail.com\n2019/11/11, foxeverl, Liu Xinfeng, liuxf1986[at]gmail[dot]com\n2019/11/17, felixn, Felix Nieuwenhuizhen, felix@tdlrali.com\n2019/11/18, mlilback, Mark Lilback, mark@lilback.com\n2020/01/19, lingyv-li, Lingyu Li, lingyv.li@gmail.com\n2020/02/02, carocad, Camilo Roca, carocad@unal.edu.co\n2020/02/10, julibert, Julián Bermúdez Ortega, julibert.dev@gmail.com\n2020/02/17, quantumsheep, Nathanael Demacon, nathanael.dmc@outlook.fr\n2020/02/21, StochasticTinkr, Daniel Pitts, github@coloraura.com\n2020/03/17, XsongyangX, Song Yang, songyang1218@gmail.com\n2020/04/07, deniskyashif, Denis Kyashif, denis.kyashif@gmail.com\n2020/04/08, lwehmeier, Leon Wehmeier, wehmeier@st.ovgu.de\n2020/04/10, agrabski, Adam Grabski, adam.gr@outlook.com\n2020/04/23, martinvw, Martin van Wingerden, martin@martinvw.nl\n2020/04/23, kaczmarj, Jakub Kaczmarzyk, jakub.kaczmarzyk@stonybrookmedicine.edu\n2020/04/30, TristonianJones, Tristan Swadell, tswadell@google.com\n2020/05/06, iammosespaulr, Moses Paul R, iammosespaulr@gmail.com\n2020/05/10, gomerser, Erik Gomersbach, gomerser@gomersba.ch\n2020/05/22, keywan-ghadami-oxid, Keywan Ghadami, keywan.ghadami@oxid-esales.com\n2020/05/25, graknol, Sindre van der Linden, graknol@gmail.com\n2020/05/31, d-markey, David Markey, dmarkey@free.fr\n2020/06/02, cohomology, Kilian Kilger, kkilger AT gmail.com\n2020/06/04, IohannRabeson, Iohann Rabeson, iotaka6@gmail.com\n2020/06/04, sigmasoldi3r, Pablo Blanco, pablobc.1995@gmail.com\n2020/06/15, mattpaletta, Matthew Paletta, mattpaletta@gmail.com\n2020/07/01, sha-N, Shan M Mathews, admin@bluestarqatar.com\n2020/08/22, stevenjohnstone, Steven Johnstone, steven.james.johnstone@gmail.com\n2020/09/06, ArthurSonzogni, Sonzogni Arthur, arthursonzogni@gmail.com\n2020/09/10, Khailian, Arunav Sanyal, arunav.sanyal91@gmail.com\n2020/09/12, Clcanny, Charles Ruan, a837940593@gmail.com\n2020/09/15, rmcgregor1990, Robert McGregor, rmcgregor1990@gmail.com\n2020/09/16, trenki2, Markus Trenkwalder, trenki2[at]gmx[dot]net\n2020/10/08, Marti2203, Martin Mirchev, mirchevmartin2203@gmail.com\n2020/10/16, adarshbhat, Adarsh Bhat, adarshbhat@users.noreply.github.com\n2020/10/20, adamwojs, Adam Wójs, adam[at]wojs.pl\n2020/10/24, cliid, Jiwu Jang, jiwujang@naver.com\n2020/11/05, MichelHartmann, Michel Hartmann, MichelHartmann@users.noreply.github.com\n2020/11/26, mr-c, Michael R. Crusoe, 1330696+mr-c@users.noreply.github.com\n2020/12/01, maxence-lefebvre, Maxence Lefebvre, maxence-lefebvre@users.noreply.github.com\n2020/12/03, electrum, David Phillips, david@acz.org\n2021/01/03, niw, Yoshimasa Niwa, niw@niw.at\n2021/01/25, l215884529, Qiheng Liu, 13607681+l215884529@users.noreply.github.com\n2021/02/02, tsotnikov, Taras Sotnikov, taras.sotnikov@gmail.com\n2021/02/10, jirislaby, Jiri Slaby, jirislaby@gmail.com\n2021/02/21, namasikanam, Xingyu Xie, namasikanam@gmail.com\n2021/02/26, ahooper, Andrew Hooper, ahooper at kos dot net\n2021/02/27, khmarbaise, Karl Heinz Marbaise, github@soebes.com\n2021/02/28, Dante-Broggi, Dante Broggi, 34220985+Dante-Broggi@users.noreply.github.com\n2021/03/02, hackeris\n2021/03/03, xTachyon, Damian Andrei, xTachyon@users.noreply.github.com\n2021/03/22, 100mango, Fangqiu Fang, 100mango@gmail.com\n2021/04/07, b1f6c1c4, Jinzheng Tu, b1f6c1c4@gmail.com\n2021/04/17, jaggerjo, Josua Jäger, mail@jaggerjo.com\n2021/04/24, bigerl, Alexander Bigerl, alexander [äät] bigerl [pkt] eu\n2021/05/02, michalharakal, Michal Harakal, michal.harakal@users.noreply.github.com\n2021/05/03, redexp, Sergii Kliuchnyk, redexp@users.noreply.github.com\n2021/05/03, mitar, Mi Tar, mitar.git@tnode.com\n2021/05/04, joakker, Joaquín León, joaquinandresleon108@gmail.com\n2021/05/06, renancaraujo, Renan C. Araújo, renancaraujo@users.noreply.github.com\n2021/05/06, canastro, Ricardo Canastro, ricardocanastro@users.noreply.github.com\n2021/06/19, abe149, Abe Skolnik, abe 149 at gmail . com\n2021/07/01, appel1, Johan Appelgren, johan.appelgren@gmail.com\n2021/07/01, marcauberer, Marc Auberer, marc.auberer@chillibits.com\n2021/07/14, renzhentaxibaerde, Renzhentaxi Baerde, renzhentaxibaerde@gmail.com\n2021/07/21, skittlepox, Benjamin Spiegel, bspiegel@cs.brown.edu\n2021/07/29, ksyx, Qixing Xue, qixingxue@outlook.com\n2021/07/29, rachidlamouri, Rachid Lamouri, rachidlamouri@gmail.com\n2021/08/02, minjoosur, Minjoo Sur, msur@salesforce.com\n2021/08/05, jjeffcaii, Jeff Tsai, caiweiwei.cww@alibaba-inc.com\n2021/08/08, ansiemens, Yi-Hong Lin, ansiemens@gmail.com\n2021/08/25, XenoAmess, Jin Xu, xenoamess@gmail.com\n2021/09/08, jmcken8, Joel McKenzie, joel.b.mckenzie@gmail.com\n2021/09/23, skalt, Steven Kalt, kalt.steven@gmail.com\n2021/09/26, idraper, Isaac Draper, idraper@byu.edu\n2021/10/10, tools4origins, Erwan Guyomarc'h, contact@erwan-guyomarch.fr\n2021/10/19, jcking, Justin King, jcking@google.com\n2021/10/31, skef, Skef Iterum, github@skef.org\n2021/10/31, hlstwizard, h.l.s.t@163.com\n2021/11/30, bollwyvl, Nick Bollweg, bollwyvl@users.noreply.github.com\n2021/12/03, eneko, Eneko Alonso, eneko.alonso@gmail.com\n2021/12/16, Ketler13, Oleksandr Martyshchenko, oleksandr.martyshchenko@gmail.com\n2021/12/25, Tinker1024, Tinker1024, tinker@huawei.com\n2021/12/31, Biswa96, Biswapriyo Nath, nathbappai@gmail.com\n2022/03/07, chenquan, chenquan, chenquan.dev@gmail.com\n2022/03/15, hzeller, Henner Zeller, h.zeller@acm.org\n"
  },
  {
    "path": "pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<groupId>org.sonatype.oss</groupId>\n\t\t<artifactId>oss-parent</artifactId>\n\t\t<version>9</version>\n\t</parent>\n\t<groupId>org.antlr</groupId>\n\t<artifactId>antlr4-master</artifactId>\n\t<version>4.13.3-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>ANTLR 4</name>\n\t<description>ANTLR 4 Master Build POM</description>\n\t<url>https://www.antlr.org/</url>\n\t<inceptionYear>1992</inceptionYear>\n\t<organization>\n\t\t<name>ANTLR</name>\n\t\t<url>https://www.antlr.org/</url>\n\t</organization>\n\n    <prerequisites>\n        <maven>3.8</maven>\n    </prerequisites>\n\n    <licenses>\n\t\t<license>\n\t\t\t<name>BSD-3-Clause</name>\n\t\t\t<url>https://www.antlr.org/license.html</url>\n\t\t\t<distribution>repo</distribution>\n\t\t</license>\n\t</licenses>\n\n\t<developers>\n\t\t<developer>\n\t\t\t<name>Terence Parr</name>\n\t\t\t<url>https://github.com/parrt</url>\n\t\t\t<roles>\n\t\t\t\t<role>Project lead - ANTLR</role>\n\t\t\t</roles>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<name>Sam Harwell</name>\n\t\t\t<url>http://tunnelvisionlabs.com</url>\n\t\t\t<roles>\n\t\t\t\t<role>Developer</role>\n\t\t\t</roles>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<name>Eric Vergnaud</name>\n\t\t\t<roles>\n\t\t\t\t<role>Developer - JavaScript, C#, Python 2, Python 3</role>\n\t\t\t</roles>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<name>Peter Boyer</name>\n\t\t\t<roles>\n\t\t\t\t<role>Developer - Go</role>\n\t\t\t</roles>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<name>Jim Idle</name>\n\t\t\t<email>jimi@idle.ws</email>\n\t\t\t<url>https://www.linkedin.com/in/jimidle/</url>\n\t\t\t<roles>\n\t\t\t\t<role>Developer - Maven Plugin</role>\n\t\t\t\t<role>Developer - Go runtime</role>\n\t\t\t</roles>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<name>Mike Lischke</name>\n\t\t\t<roles>\n\t\t\t\t<role>Developer - C++ Target</role>\n\t\t\t</roles>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<name>Tom Everett</name>\n\t\t\t<roles>\n\t\t\t\t<role>Developer</role>\n\t\t\t</roles>\n\t\t</developer>\n\t</developers>\n\n\t<modules>\n\t\t<module>runtime/Java</module>\n\t\t<module>tool</module>\n\t\t<module>antlr4-maven-plugin</module>\n\t\t<module>tool-testsuite</module>\n\t\t<module>runtime-testsuite</module>\n\t</modules>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<project.build.outputTimestamp>1722710576</project.build.outputTimestamp>\n\t\t<antlr.testinprocess>true</antlr.testinprocess>\n\t\t<maven.compiler.source>11</maven.compiler.source>\n\t\t<maven.compiler.target>11</maven.compiler.target>\n\t</properties>\n\n\t<mailingLists>\n\t\t<mailingList>\n\t\t\t<name>antlr-discussion</name>\n\t\t\t<archive>https://groups.google.com/forum/?fromgroups#!forum/antlr-discussion</archive>\n\t\t</mailingList>\n\t</mailingLists>\n\n\t<issueManagement>\n\t\t<system>GitHub Issues</system>\n\t\t<url>https://github.com/antlr/antlr4/issues</url>\n\t</issueManagement>\n\n\t<scm>\n        <url>https://github.com/antlr/antlr4/tree/master</url>\n\t\t<connection>scm:git:git://github.com/antlr/antlr4.git</connection>\n\t\t<developerConnection>scm:git:git@github.com:antlr/antlr4.git</developerConnection>\n\t\t<tag>4.13.0</tag>\n\t</scm>\n\n\t<build>\n\t\t<resources>\n\t\t\t<resource>\n\t\t\t\t<directory>resources</directory>\n\t\t\t</resource>\n\t\t</resources>\n\t\t<testResources>\n\t\t\t<testResource>\n\t\t\t\t<directory>test</directory>\n\t\t\t</testResource>\n\t\t</testResources>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>3.1.0</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>runtime/Swift/.build</directory>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>runtime/Swift/Tests/Antlr4Tests/gen</directory>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t\t<pluginManagement>\n\t\t\t<plugins>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t\t<version>3.8.1</version>\n\t\t\t\t\t<configuration>\n\t\t\t\t\t\t<source>${maven.compiler.source}</source>\n\t\t\t\t\t\t<target>${maven.compiler.target}</target>\n\t\t\t\t\t</configuration>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t\t<version>3.2.2</version>\n\t\t\t\t</plugin>\n\t\t\t\t<plugin>\n\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t<artifactId>maven-release-plugin</artifactId>\n\t\t\t\t\t<version>3.0.0-M6</version>\n\t\t\t\t</plugin>\n\t\t\t</plugins>\n\t\t</pluginManagement>\n\t</build>\n</project>\n"
  },
  {
    "path": "runtime/CSharp/src/Antlr4.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Company>The ANTLR Organization</Company>\n    <Version>4.13.2</Version>\n    <NeutralLanguage>en-US</NeutralLanguage>\n    <TargetFramework Condition=\"'$(OS)' != 'Windows_NT'\">netstandard2.0</TargetFramework>\n    <TargetFrameworks Condition=\"'$(OS)' == 'Windows_NT'\">net45;netstandard2.0</TargetFrameworks>\n    <NoWarn>$(NoWarn);CS1591;CS1574;CS1580;CS1570;NU5048</NoWarn>\n    <GenerateDocumentationFile>true</GenerateDocumentationFile>\n    <AssemblyName>Antlr4.Runtime.Standard</AssemblyName>\n    <AssemblyOriginatorKeyFile>Antlr4.snk</AssemblyOriginatorKeyFile>\n    <SignAssembly>true</SignAssembly>\n    <PublicSign Condition=\" '$(OS)' != 'Windows_NT' \">true</PublicSign>\n    <PackageId>Antlr4.Runtime.Standard</PackageId>\n    <Title>ANTLR 4 .NET Standard Runtime</Title>\n    <Authors>Eric Vergnaud, Terence Parr, Sam Harwell</Authors>\n    <Description>The .NET Core C# ANTLR 4 runtime from the ANTLR Organization</Description>\n    <Summary>The runtime library for parsers generated by the C# target of the standard ANTLR 4 tool.</Summary>\n    <Copyright>Copyright (c) 2012-2020 The ANTLR Project. All rights reserved.</Copyright>\n    <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>\n    <PackageLicenseExpression>BSD-3-Clause</PackageLicenseExpression>\n    <PackageProjectUrl>https://github.com/antlr/antlr4</PackageProjectUrl>\n    <PackageIconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</PackageIconUrl>\n    <PackageReleaseNotes>https://github.com/antlr/antlr4/releases</PackageReleaseNotes>\n    <PackageTags>antlr parsing grammar</PackageTags>\n    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>\n    <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>\n    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>\n    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>\n    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>\n    <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>\n    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>\n    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>\n    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>\n    <RootNamespace>Antlr4.Runtime</RootNamespace>\n    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <Optimize>true</Optimize>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "runtime/CSharp/src/AntlrFileStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nusing Encoding = System.Text.Encoding;\nusing File = System.IO.File;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This is an\n    /// <see cref=\"AntlrInputStream\"/>\n    /// that is loaded from a file all at once\n    /// when you construct the object.\n    /// </summary>\n    public class AntlrFileStream : AntlrInputStream\n    {\n        protected internal string fileName;\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrFileStream(string fileName)\n            : this(fileName, null)\n        {\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrFileStream(string fileName, Encoding encoding)\n        {\n            this.fileName = fileName;\n            Load(fileName, encoding);\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public virtual void Load(string fileName, Encoding encoding)\n        {\n            if (fileName == null)\n            {\n                return;\n            }\n\n            string text;\n            if (encoding != null)\n                text = File.ReadAllText(fileName, encoding);\n            else\n                text = File.ReadAllText(fileName);\n\n            data = text.ToCharArray();\n            n = data.Length;\n        }\n\n        public override string SourceName\n        {\n            get\n            {\n                return fileName;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/AntlrInputStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.IO;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    public abstract class BaseInputCharStream : ICharStream\n    {\n        public const int ReadBufferSize = 1024;\n\n        public const int InitialBufferSize = 1024;\n\n        /// <summary>How many characters are actually in the buffer</summary>\n        protected internal int n;\n\n        /// <summary>0..n-1 index into string of next char</summary>\n        protected internal int p = 0;\n\n        /// <summary>What is name or source of this char stream?</summary>\n        public string name;\n\n        /// <summary>\n        /// Reset the stream so that it's in the same state it was\n        /// when the object was created *except* the data array is not\n        /// touched.\n        /// </summary>\n        /// <remarks>\n        /// Reset the stream so that it's in the same state it was\n        /// when the object was created *except* the data array is not\n        /// touched.\n        /// </remarks>\n        public virtual void Reset()\n        {\n            p = 0;\n        }\n\n        public virtual void Consume()\n        {\n            if (p >= n)\n            {\n                System.Diagnostics.Debug.Assert(LA(1) == IntStreamConstants.EOF);\n                throw new InvalidOperationException(\"cannot consume EOF\");\n            }\n            else\n            {\n                p++;\n            }\n        }\n\n        //System.out.println(\"p moves to \"+p+\" (c='\"+(char)data[p]+\"')\");\n        public virtual int LA(int i)\n        {\n            if (i == 0)\n            {\n                return 0;\n            }\n            // undefined\n            if (i < 0)\n            {\n                i++;\n                // e.g., translate LA(-1) to use offset i=0; then data[p+0-1]\n                if ((p + i - 1) < 0)\n                {\n                    return IntStreamConstants.EOF;\n                }\n            }\n            // invalid; no char before first char\n            if ((p + i - 1) >= n)\n            {\n                //System.out.println(\"char LA(\"+i+\")=EOF; p=\"+p);\n                return IntStreamConstants.EOF;\n            }\n            //System.out.println(\"char LA(\"+i+\")=\"+(char)data[p+i-1]+\"; p=\"+p);\n            //System.out.println(\"LA(\"+i+\"); p=\"+p+\" n=\"+n+\" data.length=\"+data.length);\n            return ValueAt(p + i - 1);\n        }\n\n        public virtual int Lt(int i)\n        {\n            return LA(i);\n        }\n\n        /// <summary>\n        /// Return the current input symbol index 0..n where n indicates the\n        /// last symbol has been read.\n        /// </summary>\n        /// <remarks>\n        /// Return the current input symbol index 0..n where n indicates the\n        /// last symbol has been read.  The index is the index of char to\n        /// be returned from LA(1).\n        /// </remarks>\n        public virtual int Index\n        {\n            get\n            {\n                return p;\n            }\n        }\n\n        public virtual int Size\n        {\n            get\n            {\n                return n;\n            }\n        }\n\n        /// <summary>mark/release do nothing; we have entire buffer</summary>\n        public virtual int Mark()\n        {\n            return -1;\n        }\n\n        public virtual void Release(int marker)\n        {\n        }\n\n        /// <summary>\n        /// consume() ahead until p==index; can't just set p=index as we must\n        /// update line and charPositionInLine.\n        /// </summary>\n        /// <remarks>\n        /// consume() ahead until p==index; can't just set p=index as we must\n        /// update line and charPositionInLine. If we seek backwards, just set p\n        /// </remarks>\n        public virtual void Seek(int index)\n        {\n            if (index <= p)\n            {\n                p = index;\n                // just jump; don't update stream state (line, ...)\n                return;\n            }\n            // seek forward, consume until p hits index or n (whichever comes first)\n            index = Math.Min(index, n);\n            while (p < index)\n            {\n                Consume();\n            }\n        }\n\n        public virtual string GetText(Interval interval)\n        {\n            int start = interval.a;\n            int stop = interval.b;\n            if (stop >= n)\n            {\n                stop = n - 1;\n            }\n            int count = stop - start + 1;\n            if (start >= n)\n            {\n                return string.Empty;\n            }\n            return ConvertDataToString(start, count);\n        }\n\n        protected abstract int ValueAt(int i);\n\n        protected abstract string ConvertDataToString(int start, int count);\n\n        public override sealed string ToString()\n        {\n            return ConvertDataToString(0, n);\n        }\n\n        public virtual string SourceName\n        {\n            get\n            {\n                if (string.IsNullOrEmpty(name))\n                {\n                    return IntStreamConstants.UnknownSourceName;\n                }\n                return name;\n            }\n        }\n    }\n\n    /// <summary>\n    /// Vacuum all input from a\n    /// <see cref=\"System.IO.TextReader\"/>\n    /// /\n    /// <see cref=\"System.IO.Stream\"/>\n    /// and then treat it\n    /// like a\n    /// <c>char[]</c>\n    /// buffer. Can also pass in a\n    /// <see cref=\"string\"/>\n    /// or\n    /// <c>char[]</c>\n    /// to use.\n    /// <p>If you need encoding, pass in stream/reader with correct encoding.</p>\n    /// </summary>\n    public class AntlrInputStream : BaseInputCharStream\n    {\n        /// <summary>The data being scanned</summary>\n        protected internal char[] data;\n\n        public AntlrInputStream()\n        {\n        }\n\n        /// <summary>Copy data in string to a local char array</summary>\n        public AntlrInputStream(string input)\n        {\n            this.data = input.ToCharArray();\n            this.n = input.Length;\n        }\n\n        /// <summary>This is the preferred constructor for strings as no data is copied</summary>\n        public AntlrInputStream(char[] data, int numberOfActualCharsInArray)\n        {\n            this.data = data;\n            this.n = numberOfActualCharsInArray;\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrInputStream(TextReader r)\n            : this(r, InitialBufferSize, ReadBufferSize)\n        {\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrInputStream(TextReader r, int initialSize)\n            : this(r, initialSize, ReadBufferSize)\n        {\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrInputStream(TextReader r, int initialSize, int readChunkSize)\n        {\n            Load(r, initialSize, readChunkSize);\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrInputStream(Stream input)\n            : this(new StreamReader(input), InitialBufferSize)\n        {\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrInputStream(Stream input, int initialSize)\n            : this(new StreamReader(input), initialSize)\n        {\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public AntlrInputStream(Stream input, int initialSize, int readChunkSize)\n            : this(new StreamReader(input), initialSize, readChunkSize)\n        {\n        }\n\n        /// <exception cref=\"System.IO.IOException\"/>\n        public virtual void Load(TextReader r, int size, int readChunkSize)\n        {\n            if (r == null)\n            {\n                return;\n            }\n\n            data = r.ReadToEnd().ToCharArray();\n            n = data.Length;\n        }\n\n        protected override int ValueAt(int i)\n        {\n            return data[i];\n        }\n\n        protected override string ConvertDataToString(int start, int count)\n        {\n            //\t\tSystem.err.println(\"data: \"+Arrays.toString(data)+\", n=\"+n+\n            //                                             \", start=\"+start+\n            //                                             \", stop=\"+stop);\n            return new string(data, start, count);\n        }\n    }\n\n    /// <summary>\n    /// Alternative to\n    /// <see cref=\"AntlrInputStream\"/>\n    /// which treats the input as a series of Unicode code points,\n    /// instead of a series of UTF-16 code units.\n    ///\n    /// Use this if you need to parse input which potentially contains\n    /// Unicode values > U+FFFF.\n    /// </summary>\n    public class CodePointCharStream : BaseInputCharStream\n    {\n        private int[] data;\n\n        public CodePointCharStream(string input)\n        {\n            this.data = new int[input.Length];\n            int dataIdx = 0;\n            for (int i = 0; i < input.Length; ) {\n                var codePoint = Char.ConvertToUtf32(input, i);\n                data[dataIdx++] = codePoint;\n                if (dataIdx > data.Length) {\n                    Array.Resize(ref data, data.Length * 2);\n                }\n                i += codePoint <= 0xFFFF ? 1 : 2;\n            }\n            this.n = dataIdx;\n        }\n\n        protected override int ValueAt(int i)\n        {\n            return data[i];\n        }\n\n        protected override string ConvertDataToString(int start, int count)\n        {\n            var sb = new StringBuilder(count);\n            for (int i = start; i < start + count; i++) {\n                sb.Append(Char.ConvertFromUtf32(data[i]));\n            }\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATN.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public class ATN\n    {\n        public const int INVALID_ALT_NUMBER = 0;\n\n        [NotNull]\n        public readonly IList<ATNState> states = new List<ATNState>();\n\n        /// <summary>\n        /// Each subrule/rule is a decision point and we must track them so we\n        /// can go back later and build DFA predictors for them.\n        /// </summary>\n        /// <remarks>\n        /// Each subrule/rule is a decision point and we must track them so we\n        /// can go back later and build DFA predictors for them.  This includes\n        /// all the rules, subrules, optional blocks, ()+, ()* etc...\n        /// </remarks>\n        [NotNull]\n        public readonly IList<DecisionState> decisionToState = new List<DecisionState>();\n\n        /// <summary>Maps from rule index to starting state number.</summary>\n        /// <remarks>Maps from rule index to starting state number.</remarks>\n        public RuleStartState[] ruleToStartState;\n\n        /// <summary>Maps from rule index to stop state number.</summary>\n        /// <remarks>Maps from rule index to stop state number.</remarks>\n        public RuleStopState[] ruleToStopState;\n\n        [NotNull]\n        public readonly IDictionary<string, TokensStartState> modeNameToStartState = new Dictionary<string, TokensStartState>();\n\n        /// <summary>The type of the ATN.</summary>\n        /// <remarks>The type of the ATN.</remarks>\n        public readonly ATNType grammarType;\n\n        /// <summary>The maximum value for any symbol recognized by a transition in the ATN.</summary>\n        /// <remarks>The maximum value for any symbol recognized by a transition in the ATN.</remarks>\n        public readonly int maxTokenType;\n\n        /// <summary>For lexer ATNs, this maps the rule index to the resulting token type.</summary>\n        /// <remarks>\n        /// For lexer ATNs, this maps the rule index to the resulting token type.\n        /// For parser ATNs, this maps the rule index to the generated bypass token\n        /// type if the\n        /// <see cref=\"ATNDeserializationOptions.GenerateRuleBypassTransitions()\"/>\n        /// deserialization option was specified; otherwise, this is\n        /// <see langword=\"null\"/>\n        /// .\n        /// </remarks>\n        public int[] ruleToTokenType;\n\n        /// <summary>\n        /// For lexer ATNs, this is an array of\n        /// <see cref=\"ILexerAction\"/>\n        /// objects which may\n        /// be referenced by action transitions in the ATN.\n        /// </summary>\n        public ILexerAction[] lexerActions;\n\n        [NotNull]\n        public readonly IList<TokensStartState> modeToStartState = new List<TokensStartState>();\n\n        private readonly PredictionContextCache contextCache = new PredictionContextCache();\n\n        [NotNull]\n\t\tpublic DFA[] decisionToDFA = Collections.EmptyList<DFA>();\n\n        [NotNull]\n\t\tpublic DFA[] modeToDFA = Collections.EmptyList<DFA>();\n\n        protected internal readonly ConcurrentDictionary<int, int> LL1Table = new ConcurrentDictionary<int, int>();\n\n        /// <summary>Used for runtime deserialization of ATNs from strings</summary>\n        public ATN(ATNType grammarType, int maxTokenType)\n        {\n            this.grammarType = grammarType;\n            this.maxTokenType = maxTokenType;\n        }\n\n\n        public virtual PredictionContext GetCachedContext(PredictionContext context)\n        {\n            return PredictionContext.GetCachedContext(context, contextCache, new PredictionContext.IdentityHashMap());\n        }\n\n        /// <summary>\n        /// Compute the set of valid tokens that can occur starting in state\n        /// <paramref name=\"s\"/>\n        /// .\n        /// If\n        /// <paramref name=\"ctx\"/>\n        /// is\n        /// <see cref=\"EmptyPredictionContext.Instance\"/>\n        /// , the set of tokens will not include what can follow\n        /// the rule surrounding\n        /// <paramref name=\"s\"/>\n        /// . In other words, the set will be\n        /// restricted to tokens reachable staying within\n        /// <paramref name=\"s\"/>\n        /// 's rule.\n        /// </summary>\n        [return: NotNull]\n        public virtual IntervalSet NextTokens(ATNState s, RuleContext ctx)\n        {\n            LL1Analyzer anal = new LL1Analyzer(this);\n            IntervalSet next = anal.Look(s, ctx);\n            return next;\n        }\n\n        /// <summary>\n        /// Compute the set of valid tokens that can occur starting in\n        /// <paramref name=\"s\"/>\n        /// and\n        /// staying in same rule.\n        /// <see cref=\"TokenConstants.EPSILON\"/>\n        /// is in set if we reach end of\n        /// rule.\n        /// </summary>\n        [return: NotNull]\n        public virtual IntervalSet NextTokens(ATNState s)\n        {\n            if (s.nextTokenWithinRule != null)\n            {\n                return s.nextTokenWithinRule;\n            }\n\t\t\ts.nextTokenWithinRule = NextTokens(s, null);\n            s.nextTokenWithinRule.SetReadonly(true);\n            return s.nextTokenWithinRule;\n        }\n\n        public virtual void AddState(ATNState state)\n        {\n            if (state != null)\n            {\n                state.atn = this;\n                state.stateNumber = states.Count;\n            }\n            states.Add(state);\n        }\n\n        public virtual void RemoveState(ATNState state)\n        {\n            states[state.stateNumber] = null;\n        }\n\n        // just free mem, don't shift states in list\n        public virtual void DefineMode(string name, TokensStartState s)\n        {\n            modeNameToStartState[name] = s;\n            modeToStartState.Add(s);\n            modeToDFA = Arrays.CopyOf(modeToDFA, modeToStartState.Count);\n            modeToDFA[modeToDFA.Length - 1] = new DFA(s);\n            DefineDecisionState(s);\n        }\n\n        public virtual int DefineDecisionState(DecisionState s)\n        {\n            decisionToState.Add(s);\n            s.decision = decisionToState.Count - 1;\n            decisionToDFA = Arrays.CopyOf(decisionToDFA, decisionToState.Count);\n            decisionToDFA[decisionToDFA.Length - 1] = new DFA(s, s.decision);\n            return s.decision;\n        }\n\n        public virtual DecisionState GetDecisionState(int decision)\n        {\n            if (decisionToState.Count != 0)\n            {\n                return decisionToState[decision];\n            }\n            return null;\n        }\n\n        public virtual int NumberOfDecisions\n        {\n            get\n            {\n                return decisionToState.Count;\n            }\n        }\n\n        /// <summary>\n        /// Computes the set of input symbols which could follow ATN state number\n        /// <paramref name=\"stateNumber\"/>\n        /// in the specified full\n        /// <paramref name=\"context\"/>\n        /// . This method\n        /// considers the complete parser context, but does not evaluate semantic\n        /// predicates (i.e. all predicates encountered during the calculation are\n        /// assumed true). If a path in the ATN exists from the starting state to the\n        /// <see cref=\"RuleStopState\"/>\n        /// of the outermost context without matching any\n        /// symbols,\n        /// <see cref=\"TokenConstants.EOF\"/>\n        /// is added to the returned set.\n        /// <p>If\n        /// <paramref name=\"context\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// , it is treated as\n        /// <see cref=\"ParserRuleContext.EmptyContext\"/>\n        /// .</p>\n        /// </summary>\n        /// <param name=\"stateNumber\">the ATN state number</param>\n        /// <param name=\"context\">the full parse context</param>\n        /// <returns>\n        /// The set of potentially valid input symbols which could follow the\n        /// specified state in the specified context.\n        /// </returns>\n        /// <exception cref=\"System.ArgumentException\">\n        /// if the ATN does not contain a state with\n        /// number\n        /// <paramref name=\"stateNumber\"/>\n        /// </exception>\n        [return: NotNull]\n        public virtual IntervalSet GetExpectedTokens(int stateNumber, RuleContext context)\n        {\n            if (stateNumber < 0 || stateNumber >= states.Count)\n            {\n                throw new ArgumentException(\"Invalid state number.\");\n            }\n            RuleContext ctx = context;\n            ATNState s = states[stateNumber];\n            IntervalSet following = NextTokens(s);\n            if (!following.Contains(TokenConstants.EPSILON))\n            {\n                return following;\n            }\n            IntervalSet expected = new IntervalSet();\n            expected.AddAll(following);\n            expected.Remove(TokenConstants.EPSILON);\n            while (ctx != null && ctx.invokingState >= 0 && following.Contains(TokenConstants.EPSILON))\n            {\n                ATNState invokingState = states[ctx.invokingState];\n                RuleTransition rt = (RuleTransition)invokingState.Transition(0);\n                following = NextTokens(rt.followState);\n                expected.AddAll(following);\n                expected.Remove(TokenConstants.EPSILON);\n                ctx = ctx.Parent;\n            }\n            if (following.Contains(TokenConstants.EPSILON))\n            {\n                expected.Add(TokenConstants.EOF);\n            }\n            return expected;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATNConfig.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\n\t/** A tuple: (ATN state, predicted alt, syntactic, semantic context).\n\t *  The syntactic context is a graph-structured stack node whose\n\t *  path(s) to the root is the rule invocation(s)\n\t *  chain used to arrive at the state.  The semantic context is\n\t *  the tree of semantic predicates encountered before reaching\n\t *  an ATN state.\n\t */\n\tpublic class ATNConfig\n\t{\n\t\t/**\n\t\t * This field stores the bit mask for implementing the\n\t\t * {@link #isPrecedenceFilterSuppressed} property as a bit within the\n\t\t * existing {@link #reachesIntoOuterContext} field.\n\t\t */\n\t\tprivate static readonly int SUPPRESS_PRECEDENCE_FILTER = 0x40000000;\n\n\t\t/** The ATN state associated with this configuration */\n\t\tpublic readonly ATNState state;\n\n\t\t/** What alt (or lexer rule) is predicted by this configuration */\n\t\tpublic readonly int alt;\n\n\t\t/** The stack of invoking states leading to the rule/states associated\n\t\t *  with this config.  We track only those contexts pushed during\n\t\t *  execution of the ATN simulator.\n\t\t */\n\t\tpublic PredictionContext context;\n\n\t\t/**\n\t\t * We cannot execute predicates dependent upon local context unless\n\t\t * we know for sure we are in the correct context. Because there is\n\t\t * no way to do this efficiently, we simply cannot evaluate\n\t\t * dependent predicates unless we are in the rule that initially\n\t\t * invokes the ATN simulator.\n\t\t *\n\t\t * <p>\n\t\t * closure() tracks the depth of how far we dip into the outer context:\n\t\t * depth &gt; 0.  Note that it may not be totally accurate depth since I\n\t\t * don't ever decrement. TODO: make it a boolean then</p>\n\t\t *\n\t\t * <p>\n\t\t * For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method\n\t\t * is also backed by this field. Since the field is publicly accessible, the\n\t\t * highest bit which would not cause the value to become negative is used to\n\t\t * store this field. This choice minimizes the risk that code which only\n\t\t * compares this value to 0 would be affected by the new purpose of the\n\t\t * flag. It also ensures the performance of the existing {@link ATNConfig}\n\t\t * constructors as well as certain operations like\n\t\t * {@link ATNConfigSet#add(ATNConfig, DoubleKeyMap)} method are\n\t\t * <em>completely</em> unaffected by the change.</p>\n\t\t */\n\t\tpublic int reachesIntoOuterContext;\n\n\n\t\tpublic readonly SemanticContext semanticContext;\n\n\t\tpublic ATNConfig(ATNConfig old)\n\t\t{ // dup\n\t\t\tthis.state = old.state;\n\t\t\tthis.alt = old.alt;\n\t\t\tthis.context = old.context;\n\t\t\tthis.semanticContext = old.semanticContext;\n\t\t\tthis.reachesIntoOuterContext = old.reachesIntoOuterContext;\n\t\t}\n\n\t\tpublic ATNConfig(ATNState state,\n\t\t\t\t\t\t int alt,\n\t\t\t\t\t\t PredictionContext context)\n\t\t\t: this(state, alt, context, SemanticContext.Empty.Instance)\n\t\t{\n\t\t}\n\n\t\tpublic ATNConfig(ATNState state,\n\t\t\t\t\t\t int alt,\n\t\t\t\t\t\t PredictionContext context,\n\t\t\t\t\t\t SemanticContext semanticContext)\n\t\t{\n\t\t\tthis.state = state;\n\t\t\tthis.alt = alt;\n\t\t\tthis.context = context;\n\t\t\tthis.semanticContext = semanticContext;\n\t\t}\n\n\t\tpublic ATNConfig(ATNConfig c, ATNState state)\n\t\t\t: this(c, state, c.context, c.semanticContext)\n\t\t{\n\t\t}\n\n\t\tpublic ATNConfig(ATNConfig c, ATNState state,\n\t\t\t SemanticContext semanticContext)\n\t\t\t: this(c, state, c.context, semanticContext)\n\t\t{\n\t\t}\n\n\t\tpublic ATNConfig(ATNConfig c,\n\t\t\t\t\t\t SemanticContext semanticContext)\n\t\t\t: this(c, c.state, c.context, semanticContext)\n\t\t{\n\t\t}\n\n\t\tpublic ATNConfig(ATNConfig c, ATNState state,\n\t\t\t\t\t\t PredictionContext context)\n\t\t\t: this(c, state, context, c.semanticContext)\n\t\t{\n\t\t}\n\n\t\tpublic ATNConfig(ATNConfig c, ATNState state,\n\t\t\t\t\t\t PredictionContext context,\n\t\t\t\t\t\t SemanticContext semanticContext)\n\t\t{\n\t\t\tthis.state = state;\n\t\t\tthis.alt = c.alt;\n\t\t\tthis.context = context;\n\t\t\tthis.semanticContext = semanticContext;\n\t\t\tthis.reachesIntoOuterContext = c.reachesIntoOuterContext;\n\t\t}\n\n\t\t/**\n\t\t * This method gets the value of the {@link #reachesIntoOuterContext} field\n\t\t * as it existed prior to the introduction of the\n\t\t * {@link #isPrecedenceFilterSuppressed} method.\n\t\t */\n\t\tpublic int OuterContextDepth\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool IsPrecedenceFilterSuppressed\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn (reachesIntoOuterContext & SUPPRESS_PRECEDENCE_FILTER) != 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic void SetPrecedenceFilterSuppressed(bool value)\n\t\t{\n\t\t\tif (value)\n\t\t\t{\n\t\t\t\tthis.reachesIntoOuterContext |= SUPPRESS_PRECEDENCE_FILTER;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.reachesIntoOuterContext &= ~SUPPRESS_PRECEDENCE_FILTER;\n\t\t\t}\n\t\t}\n\n\t\t/** An ATN configuration is equal to another if both have\n\t\t *  the same state, they predict the same alternative, and\n\t\t *  syntactic/semantic contexts are the same.\n\t\t */\n\t\tpublic override bool Equals(Object o)\n\t\t{\n\t\t\tif (!(o is ATNConfig)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn this.Equals((ATNConfig)o);\n\t\t}\n\n\t\tpublic virtual bool Equals(ATNConfig other)\n\t\t{\n\t\t\tif (this == other)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (other == null)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn this.state.stateNumber == other.state.stateNumber\n\t\t\t\t&& this.alt == other.alt\n\t\t\t\t&& (this.context == other.context || (this.context != null && this.context.Equals(other.context)))\n\t\t\t\t&& this.semanticContext.Equals(other.semanticContext)\n\t\t\t\t&& this.IsPrecedenceFilterSuppressed == other.IsPrecedenceFilterSuppressed;\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\tint hashCode = MurmurHash.Initialize(7);\n\t\t\thashCode = MurmurHash.Update(hashCode, state.stateNumber);\n\t\t\thashCode = MurmurHash.Update(hashCode, alt);\n\t\t\thashCode = MurmurHash.Update(hashCode, context);\n\t\t\thashCode = MurmurHash.Update(hashCode, semanticContext);\n\t\t\thashCode = MurmurHash.Finish(hashCode, 4);\n\t\t\treturn hashCode;\n\t\t}\n\n\t\tpublic override String ToString()\n\t\t{\n\t\t\treturn ToString(null, true);\n\t\t}\n\n\t\tpublic String ToString(IRecognizer recog, bool showAlt)\n\t\t{\n\t\t\tStringBuilder buf = new StringBuilder();\n\t\t\t//\t\tif ( state.ruleIndex>=0 ) {\n\t\t\t//\t\t\tif ( recog!=null ) buf.append(recog.getRuleNames()[state.ruleIndex]+\":\");\n\t\t\t//\t\t\telse buf.append(state.ruleIndex+\":\");\n\t\t\t//\t\t}\n\t\t\tbuf.Append('(');\n\t\t\tbuf.Append(state);\n\t\t\tif (showAlt)\n\t\t\t{\n\t\t\t\tbuf.Append(\",\");\n\t\t\t\tbuf.Append(alt);\n\t\t\t}\n\t\t\tif (context != null)\n\t\t\t{\n\t\t\t\tbuf.Append(\",[\");\n\t\t\t\tbuf.Append(context.ToString());\n\t\t\t\tbuf.Append(\"]\");\n\t\t\t}\n\t\t\tif (semanticContext != null && semanticContext != SemanticContext.Empty.Instance)\n\t\t\t{\n\t\t\t\tbuf.Append(\",\");\n\t\t\t\tbuf.Append(semanticContext);\n\t\t\t}\n\t\t\tif (OuterContextDepth > 0)\n\t\t\t{\n\t\t\t\tbuf.Append(\",up=\").Append(OuterContextDepth);\n\t\t\t}\n\t\t\tbuf.Append(')');\n\t\t\treturn buf.ToString();\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATNConfigSet.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\tpublic class ATNConfigSet\n\t{\n\n\n\t\t/** Indicates that the set of configurations is read-only. Do not\n\t\t *  allow any code to manipulate the set; DFA states will point at\n\t\t *  the sets and they must not change. This does not protect the other\n\t\t *  fields; in particular, conflictingAlts is set after\n\t\t *  we've made this readonly.\n\t\t */\n\t\tprotected bool readOnly = false;\n\n\t\t/**\n\t\t * All configs but hashed by (s, i, _, pi) not including context. Wiped out\n\t\t * when we go readonly as this set becomes a DFA state.\n\t\t */\n\t\tpublic ConfigHashSet configLookup;\n\n\t\t/** Track the elements as they are added to the set; supports get(i) */\n\t\tpublic ArrayList<ATNConfig> configs = new ArrayList<ATNConfig>(7);\n\n\t\t// TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation\n\t\t// TODO: can we track conflicts as they are added to save scanning configs later?\n\t\tpublic int uniqueAlt;\n\t\t/** Currently this is only used when we detect SLL conflict; this does\n\t\t *  not necessarily represent the ambiguous alternatives. In fact,\n\t\t *  I should also point out that this seems to include predicated alternatives\n\t\t *  that have predicates that evaluate to false. Computed in computeTargetState().\n\t\t */\n\t\tpublic BitSet conflictingAlts;\n\n\t\t// Used in parser and lexer. In lexer, it indicates we hit a pred\n\t\t// while computing a closure operation.  Don't make a DFA state from this.\n\t\tpublic bool hasSemanticContext;\n\t\tpublic bool dipsIntoOuterContext;\n\n\t\t/** Indicates that this configuration set is part of a full context\n\t\t *  LL prediction. It will be used to determine how to merge $. With SLL\n\t\t *  it's a wildcard whereas it is not for LL context merge.\n\t\t */\n\t\tpublic readonly bool fullCtx;\n\n\t\tprivate int cachedHashCode = -1;\n\n\t\tpublic ATNConfigSet(bool fullCtx)\n\t\t{\n\t\t\tconfigLookup = new ConfigHashSet();\n\t\t\tthis.fullCtx = fullCtx;\n\t\t}\n\n\t\tpublic ATNConfigSet()\n\t\t: this(true)\n\t\t{\n\t\t}\n\n\t\tpublic ATNConfigSet(ATNConfigSet old)\n\t\t\t: this(old.fullCtx)\n\t\t{\n\t\t\tAddAll(old.configs);\n\t\t\tthis.uniqueAlt = old.uniqueAlt;\n\t\t\tthis.conflictingAlts = old.conflictingAlts;\n\t\t\tthis.hasSemanticContext = old.hasSemanticContext;\n\t\t\tthis.dipsIntoOuterContext = old.dipsIntoOuterContext;\n\t\t}\n\n\t\tpublic bool Add(ATNConfig config)\n\t\t{\n\t\t\treturn Add(config, null);\n\t\t}\n\n\t\t/**\n\t\t * Adding a new config means merging contexts with existing configs for\n\t\t * {@code (s, i, pi, _)}, where {@code s} is the\n\t\t * {@link ATNConfig#state}, {@code i} is the {@link ATNConfig#alt}, and\n\t\t * {@code pi} is the {@link ATNConfig#semanticContext}. We use\n\t\t * {@code (s,i,pi)} as key.\n\t\t *\n\t\t * <p>This method updates {@link #dipsIntoOuterContext} and\n\t\t * {@link #hasSemanticContext} when necessary.</p>\n\t\t */\n\t\tpublic bool Add(ATNConfig config, MergeCache mergeCache)\n\t\t{\n\t\t\tif (readOnly)\n\t\t\t\tthrow new Exception(\"This set is readonly\");\n\t\t\tif (config.semanticContext != SemanticContext.Empty.Instance)\n\t\t\t{\n\t\t\t\thasSemanticContext = true;\n\t\t\t}\n\t\t\tif (config.OuterContextDepth > 0)\n\t\t\t{\n\t\t\t\tdipsIntoOuterContext = true;\n\t\t\t}\n\t\t\tATNConfig existing = configLookup.GetOrAdd(config);\n\t\t\tif (existing == config)\n\t\t\t{ // we added this new one\n\t\t\t\tcachedHashCode = -1;\n\t\t\t\tconfigs.Add(config);  // track order here\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t// a previous (s,i,pi,_), merge with it and save result\n\t\t\tbool rootIsWildcard = !fullCtx;\n\t\t\tPredictionContext merged = PredictionContext.Merge(existing.context, config.context, rootIsWildcard, mergeCache);\n\t\t\t // no need to check for existing.context, config.context in cache\n\t\t\t // since only way to create new graphs is \"call rule\" and here. We\n\t\t\t // cache at both places.\n\t\t\texisting.reachesIntoOuterContext = Math.Max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext);\n\n\t\t\t// make sure to preserve the precedence filter suppression during the merge\n\t\t\tif (config.IsPrecedenceFilterSuppressed)\n\t\t\t{\n\t\t\t\texisting.SetPrecedenceFilterSuppressed(true);\n\t\t\t}\n\n\t\t\texisting.context = merged; // replace context; no need to alt mapping\n\t\t\treturn true;\n\t\t}\n\n\t\t/** Return a List holding list of configs */\n\t\tpublic List<ATNConfig> Elements\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn configs;\n\t\t\t}\n\t\t}\n\n\t\tpublic HashSet<ATNState> GetStates()\n\t\t{\n\t\t\tHashSet<ATNState> states = new HashSet<ATNState>();\n\t\t\tforeach (ATNConfig c in configs)\n\t\t\t{\n\t\t\t\tstates.Add(c.state);\n\t\t\t}\n\t\t\treturn states;\n\t\t}\n\n\t\t/**\n\t\t * Gets the complete set of represented alternatives for the configuration\n\t\t * set.\n\t\t *\n\t\t * @return the set of represented alternatives in this configuration set\n\t\t *\n\t\t * @since 4.3\n\t\t */\n\n\t\tpublic BitSet GetAlts()\n\t\t{\n\t\t\tBitSet alts = new BitSet();\n\t\t\tforeach (ATNConfig config in configs)\n\t\t\t{\n\t\t\t\talts.Set(config.alt);\n\t\t\t}\n\t\t\treturn alts;\n\t\t}\n\n\t\tpublic List<SemanticContext> GetPredicates()\n\t\t{\n\t\t\tList<SemanticContext> preds = new List<SemanticContext>();\n\t\t\tforeach (ATNConfig c in configs)\n\t\t\t{\n\t\t\t\tif (c.semanticContext != SemanticContext.Empty.Instance)\n\t\t\t\t{\n\t\t\t\t\tpreds.Add(c.semanticContext);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn preds;\n\t\t}\n\n\t\tpublic ATNConfig Get(int i) { return configs[i]; }\n\n\t\tpublic void OptimizeConfigs(ATNSimulator interpreter)\n\t\t{\n\t\t\tif (readOnly)\n\t\t\t\tthrow new Exception(\"This set is readonly\");\n\t\t\tif (configLookup.Count == 0)\n\t\t\t\treturn;\n\n\t\t\tforeach (ATNConfig config in configs)\n\t\t\t{\n\t\t\t\t//\t\t\tint before = PredictionContext.getAllContextNodes(config.context).size();\n\t\t\t\tconfig.context = interpreter.getCachedContext(config.context);\n\t\t\t\t//\t\t\tint after = PredictionContext.getAllContextNodes(config.context).size();\n\t\t\t\t//\t\t\tSystem.out.println(\"configs \"+before+\"->\"+after);\n\t\t\t}\n\t\t}\n\n\t\tpublic bool AddAll(ICollection<ATNConfig> coll)\n\t\t{\n\t\t\tforeach (ATNConfig c in coll) Add(c);\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic override bool Equals(Object o)\n\t\t{\n\t\t\tif (o == this)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (!(o is ATNConfigSet))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t//\t\tSystem.out.print(\"equals \" + this + \", \" + o+\" = \");\n\t\t\tATNConfigSet other = (ATNConfigSet)o;\n\t\t\tbool same = configs != null &&\n\t\t\t\tconfigs.Equals(other.configs) &&  // includes stack context\n\t\t\t\tthis.fullCtx == other.fullCtx &&\n\t\t\t\tthis.uniqueAlt == other.uniqueAlt &&\n\t\t\t\tthis.conflictingAlts == other.conflictingAlts &&\n\t\t\t\tthis.hasSemanticContext == other.hasSemanticContext &&\n\t\t\t\tthis.dipsIntoOuterContext == other.dipsIntoOuterContext;\n\n\t\t\t//\t\tSystem.out.println(same);\n\t\t\treturn same;\n\t\t}\n\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\tif (IsReadOnly)\n\t\t\t{\n\t\t\t\tif (cachedHashCode == -1)\n\t\t\t\t{\n\t\t\t\t\tcachedHashCode = configs.GetHashCode();\n\t\t\t\t}\n\n\t\t\t\treturn cachedHashCode;\n\t\t\t}\n\n\t\t\treturn configs.GetHashCode();\n\t\t}\n\n\t\tpublic int Count\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn configs.Count;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool Empty\n\t\t{\n\t\t\tget\n\t\t\t{\n\n\t\t\t\treturn configs.Count == 0;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool Contains(Object o)\n\t\t{\n\t\t\tif (configLookup == null)\n\t\t\t{\n\t\t\t\tthrow new Exception(\"This method is not implemented for readonly sets.\");\n\t\t\t}\n\n\t\t\treturn configLookup.ContainsKey((ATNConfig)o);\n\t\t}\n\n\n\t\tpublic void Clear()\n\t\t{\n\t\t\tif (readOnly)\n\t\t\t\tthrow new Exception(\"This set is readonly\");\n\t\t\tconfigs.Clear();\n\t\t\tcachedHashCode = -1;\n\t\t\tconfigLookup.Clear();\n\t\t}\n\n\t\tpublic bool IsReadOnly\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn readOnly;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tthis.readOnly = value;\n\t\t\t\tconfigLookup = null; // can't mod, no need for lookup cache\n\t\t\t}\n\t\t}\n\n\t\tpublic override String ToString()\n\t\t{\n\t\t\tStringBuilder buf = new StringBuilder();\n\t\t\tbuf.Append('[');\n\t\t\tList<ATNConfig> cfgs = Elements;\n\t\t\tif (cfgs.Count > 0)\n\t\t\t{\n\t\t\t\tforeach (ATNConfig c in cfgs)\n\t\t\t\t{\n\t\t\t\t\tbuf.Append(c.ToString());\n\t\t\t\t\tbuf.Append(\", \");\n\t\t\t\t}\n\t\t\t\tbuf.Length = buf.Length - 2;\n\t\t\t}\n\t\t\tbuf.Append(']');\n\t\t\tif (hasSemanticContext)\n\t\t\t\tbuf.Append(\",hasSemanticContext=\")\n\t\t\t\t   .Append(hasSemanticContext.ToString().ToLower());\n\t\t\tif (uniqueAlt != ATN.INVALID_ALT_NUMBER)\n\t\t\t\tbuf.Append(\",uniqueAlt=\")\n\t\t\t\t   .Append(uniqueAlt);\n\t\t\tif (conflictingAlts != null)\n\t\t\t\tbuf.Append(\",conflictingAlts=\")\n\t\t\t\t   .Append(conflictingAlts);\n\t\t\tif (dipsIntoOuterContext)\n\t\t\t\tbuf.Append(\",dipsIntoOuterContext\");\n\t\t\treturn buf.ToString();\n\t\t}\n\n\n\t}\n\n\tpublic class OrderedATNConfigSet : ATNConfigSet\n\t{\n\n\t\tpublic OrderedATNConfigSet()\n\t\t{\n\t\t\tthis.configLookup = new LexerConfigHashSet();\n\t\t}\n\n\t\tpublic class LexerConfigHashSet : ConfigHashSet\n\t\t{\n\t\t\tpublic LexerConfigHashSet()\n\t\t\t\t: base(new ObjectEqualityComparator())\n\t\t\t{\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic class ObjectEqualityComparator : IEqualityComparer<ATNConfig>\n\t{\n\n\n\t\tpublic int GetHashCode(ATNConfig o)\n\t\t{\n\t\t\tif (o == null)\n\t\t\t\treturn 0;\n\t\t\telse\n\t\t\t\treturn o.GetHashCode();\n\t\t}\n\n\t\tpublic bool Equals(ATNConfig a, ATNConfig b)\n\t\t{\n\t\t\tif (a == b) return true;\n\t\t\tif (a == null || b == null) return false;\n\t\t\treturn a.Equals(b);\n\t\t}\n\t}\n\n\t/**\n\t* The reason that we need this is because we don't want the hash map to use\n\t* the standard hash code and equals. We need all configurations with the same\n\t* {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles\n\t* the number of objects associated with ATNConfigs. The other solution is to\n\t* use a hash table that lets us specify the equals/hashcode operation.\n\t*/\n\tpublic class ConfigHashSet : Dictionary<ATNConfig, ATNConfig>\n\t{\n\t\tpublic ConfigHashSet(IEqualityComparer<ATNConfig> comparer)\n\t\t\t: base(comparer)\n\t\t{\n\t\t}\n\n\n\t\tpublic ConfigHashSet()\n\t\t\t: base(new ConfigEqualityComparator())\n\t\t{\n\t\t}\n\n\t\tpublic ATNConfig GetOrAdd(ATNConfig config)\n\t\t{\n\t\t\tATNConfig existing;\n\t\t\tif (this.TryGetValue(config, out existing))\n\t\t\t\treturn existing;\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis.Put(config, config);\n\t\t\t\treturn config;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic class ConfigEqualityComparator : IEqualityComparer<ATNConfig>\n\t{\n\n\n\t\tpublic int GetHashCode(ATNConfig o)\n\t\t{\n\t\t\tint hashCode = 7;\n\t\t\thashCode = 31 * hashCode + o.state.stateNumber;\n\t\t\thashCode = 31 * hashCode + o.alt;\n\t\t\thashCode = 31 * hashCode + o.semanticContext.GetHashCode();\n\t\t\treturn hashCode;\n\t\t}\n\n\t\tpublic bool Equals(ATNConfig a, ATNConfig b)\n\t\t{\n\t\t\tif (a == b) return true;\n\t\t\tif (a == null || b == null) return false;\n\t\t\treturn a.state.stateNumber == b.state.stateNumber\n\t\t\t\t&& a.alt == b.alt\n\t\t\t\t&& a.semanticContext.Equals(b.semanticContext);\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATNDeserializationOptions.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    public class ATNDeserializationOptions\n    {\n        private static readonly Antlr4.Runtime.Atn.ATNDeserializationOptions defaultOptions;\n\n        static ATNDeserializationOptions()\n        {\n            defaultOptions = new Antlr4.Runtime.Atn.ATNDeserializationOptions();\n            defaultOptions.MakeReadOnly();\n        }\n\n        private bool readOnly;\n\n        private bool verifyATN;\n\n        private bool generateRuleBypassTransitions;\n\n        private bool optimize;\n\n        public ATNDeserializationOptions()\n        {\n            this.verifyATN = true;\n            this.generateRuleBypassTransitions = false;\n            this.optimize = true;\n        }\n\n        public ATNDeserializationOptions(Antlr4.Runtime.Atn.ATNDeserializationOptions options)\n        {\n            this.verifyATN = options.verifyATN;\n            this.generateRuleBypassTransitions = options.generateRuleBypassTransitions;\n            this.optimize = options.optimize;\n        }\n\n        [NotNull]\n        public static Antlr4.Runtime.Atn.ATNDeserializationOptions Default\n        {\n            get\n            {\n                return defaultOptions;\n            }\n        }\n\n        public bool IsReadOnly\n        {\n            get\n            {\n                return readOnly;\n            }\n        }\n\n        public void MakeReadOnly()\n        {\n            readOnly = true;\n        }\n\n        public bool VerifyAtn\n        {\n            get\n            {\n                return verifyATN;\n            }\n            set\n            {\n                bool verifyATN = value;\n                ThrowIfReadOnly();\n                this.verifyATN = verifyATN;\n            }\n        }\n\n        public bool GenerateRuleBypassTransitions\n        {\n            get\n            {\n                return generateRuleBypassTransitions;\n            }\n            set\n            {\n                bool generateRuleBypassTransitions = value;\n                ThrowIfReadOnly();\n                this.generateRuleBypassTransitions = generateRuleBypassTransitions;\n            }\n        }\n\n        public bool Optimize\n        {\n            get\n            {\n                return optimize;\n            }\n            set\n            {\n                bool optimize = value;\n                ThrowIfReadOnly();\n                this.optimize = optimize;\n            }\n        }\n\n        protected internal virtual void ThrowIfReadOnly()\n        {\n            if (IsReadOnly)\n            {\n                throw new InvalidOperationException(\"The object is read only.\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATNDeserializer.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    public class ATNDeserializer\n    {\n        public static readonly int SerializedVersion = 4;\n\n        [NotNull]\n        private readonly ATNDeserializationOptions deserializationOptions;\n\n        public ATNDeserializer()\n            : this(ATNDeserializationOptions.Default)\n        {\n        }\n\n        public ATNDeserializer(ATNDeserializationOptions deserializationOptions)\n        {\n            if (deserializationOptions == null)\n            {\n                deserializationOptions = ATNDeserializationOptions.Default;\n            }\n            this.deserializationOptions = deserializationOptions;\n        }\n\n\t\tint[] data;\n\t\tint p;\n\n        public virtual ATN Deserialize(int[] data)\n        {\n\t        this.data = data;\n\t\t\tCheckVersion ();\n\t\t\tATN atn = ReadATN ();\n\t\t\tReadStates (atn);\n\t\t\tReadRules (atn);\n\t\t\tReadModes (atn);\n\t\t\tIList<IntervalSet> sets = new List<IntervalSet>();\n\t\t\tReadSets (atn, sets);\n\t        ReadEdges (atn, sets);\n\t\t\tReadDecisions (atn);\n\t\t\tReadLexerActions (atn);\n            MarkPrecedenceDecisions(atn);\n\t\t\tif (deserializationOptions.VerifyAtn) {\n\t\t\t\tVerifyATN (atn);\n\t\t\t}\n\t\t\tif (deserializationOptions.GenerateRuleBypassTransitions && atn.grammarType == ATNType.Parser) {\n\t\t\t\tGenerateRuleBypassTransitions (atn);\n\t\t\t}\n            if (deserializationOptions.Optimize)\n            {\n\t\t\t\tOptimizeATN (atn);\n            }\n            IdentifyTailCalls(atn);\n            return atn;\n        }\n\n\t\tprotected internal virtual void OptimizeATN(ATN atn)\n\t\t{\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tint optimizationCount = 0;\n\t\t\t\toptimizationCount += InlineSetRules(atn);\n\t\t\t\toptimizationCount += CombineChainedEpsilons(atn);\n\t\t\t\tbool preserveOrder = atn.grammarType == ATNType.Lexer;\n\t\t\t\toptimizationCount += OptimizeSets(atn, preserveOrder);\n\t\t\t\tif (optimizationCount == 0)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (deserializationOptions.VerifyAtn)\n\t\t\t{\n\t\t\t\t// reverify after modification\n\t\t\t\tVerifyATN(atn);\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void GenerateRuleBypassTransitions(ATN atn)\n\t\t{\n\t\t\tatn.ruleToTokenType = new int[atn.ruleToStartState.Length];\n\t\t\tfor (int i_10 = 0; i_10 < atn.ruleToStartState.Length; i_10++)\n\t\t\t{\n\t\t\t\tatn.ruleToTokenType[i_10] = atn.maxTokenType + i_10 + 1;\n\t\t\t}\n\t\t\tfor (int i_13 = 0; i_13 < atn.ruleToStartState.Length; i_13++)\n\t\t\t{\n\t\t\t\tBasicBlockStartState bypassStart = new BasicBlockStartState();\n\t\t\t\tbypassStart.ruleIndex = i_13;\n\t\t\t\tatn.AddState(bypassStart);\n\t\t\t\tBlockEndState bypassStop = new BlockEndState();\n\t\t\t\tbypassStop.ruleIndex = i_13;\n\t\t\t\tatn.AddState(bypassStop);\n\t\t\t\tbypassStart.endState = bypassStop;\n\t\t\t\tatn.DefineDecisionState(bypassStart);\n\t\t\t\tbypassStop.startState = bypassStart;\n\t\t\t\tATNState endState;\n\t\t\t\tTransition excludeTransition = null;\n\t\t\t\tif (atn.ruleToStartState[i_13].isPrecedenceRule)\n\t\t\t\t{\n\t\t\t\t\t// wrap from the beginning of the rule to the StarLoopEntryState\n\t\t\t\t\tendState = null;\n\t\t\t\t\tforeach (ATNState state_3 in atn.states)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (state_3.ruleIndex != i_13)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(state_3 is StarLoopEntryState))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tATNState maybeLoopEndState = state_3.Transition(state_3.NumberOfTransitions - 1).target;\n\t\t\t\t\t\tif (!(maybeLoopEndState is LoopEndState))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.Transition(0).target is RuleStopState)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tendState = state_3;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (endState == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new NotSupportedException(\"Couldn't identify final state of the precedence rule prefix section.\");\n\t\t\t\t\t}\n\t\t\t\t\texcludeTransition = ((StarLoopEntryState)endState).loopBackState.Transition(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tendState = atn.ruleToStopState[i_13];\n\t\t\t\t}\n\t\t\t\t// all non-excluded transitions that currently target end state need to target blockEnd instead\n\t\t\t\tforeach (ATNState state_4 in atn.states)\n\t\t\t\t{\n\t\t\t\t\tforeach (Transition transition in state_4.transitions)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (transition == excludeTransition)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (transition.target == endState)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttransition.target = bypassStop;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// all transitions leaving the rule start state need to leave blockStart instead\n\t\t\t\twhile (atn.ruleToStartState[i_13].NumberOfTransitions > 0)\n\t\t\t\t{\n\t\t\t\t\tTransition transition = atn.ruleToStartState[i_13].Transition(atn.ruleToStartState[i_13].NumberOfTransitions - 1);\n\t\t\t\t\tatn.ruleToStartState[i_13].RemoveTransition(atn.ruleToStartState[i_13].NumberOfTransitions - 1);\n\t\t\t\t\tbypassStart.AddTransition(transition);\n\t\t\t\t}\n\t\t\t\t// link the new states\n\t\t\t\tatn.ruleToStartState[i_13].AddTransition(new EpsilonTransition(bypassStart));\n\t\t\t\tbypassStop.AddTransition(new EpsilonTransition(endState));\n\t\t\t\tATNState matchState = new BasicState();\n\t\t\t\tatn.AddState(matchState);\n\t\t\t\tmatchState.AddTransition(new AtomTransition(bypassStop, atn.ruleToTokenType[i_13]));\n\t\t\t\tbypassStart.AddTransition(new EpsilonTransition(matchState));\n\t\t\t}\n\t\t\tif (deserializationOptions.VerifyAtn)\n\t\t\t{\n\t\t\t\t// reverify after modification\n\t\t\t\tVerifyATN(atn);\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void ReadLexerActions(ATN atn)\n\t\t{\n\t\t\t//\n\t\t\t// LEXER ACTIONS\n\t\t\t//\n\t\t\tif (atn.grammarType == ATNType.Lexer)\n\t\t\t{\n\t\t\t\tatn.lexerActions = new ILexerAction[ReadInt()];\n\t\t\t\tfor (int i_10 = 0; i_10 < atn.lexerActions.Length; i_10++)\n\t\t\t\t{\n\t\t\t\t\tLexerActionType actionType = (LexerActionType)ReadInt();\n\t\t\t\t\tint data1 = ReadInt();\n\t\t\t\t\tint data2 = ReadInt();\n\t\t\t\t\tILexerAction lexerAction = LexerActionFactory(actionType, data1, data2);\n\t\t\t\t\tatn.lexerActions[i_10] = lexerAction;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void ReadDecisions(ATN atn)\n\t\t{\n\t\t\t//\n\t\t\t// DECISIONS\n\t\t\t//\n\t\t\tint ndecisions = ReadInt();\n\t\t\tfor (int i_11 = 0; i_11 < ndecisions; i_11++)\n\t\t\t{\n\t\t\t\tint s = ReadInt();\n\t\t\t\tDecisionState decState = (DecisionState)atn.states[s];\n\t\t\t\tatn.decisionToState.Add(decState);\n\t\t\t\tdecState.decision = i_11;\n\t\t\t}\n\t\t\tatn.decisionToDFA = new DFA[ndecisions];\n\t\t\tfor (int i_12 = 0; i_12 < ndecisions; i_12++)\n\t\t\t{\n\t\t\t\tatn.decisionToDFA[i_12] = new DFA(atn.decisionToState[i_12], i_12);\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void ReadEdges(ATN atn, IList<IntervalSet> sets)\n\t\t{\n\t\t\t//\n\t\t\t// EDGES\n\t\t\t//\n\t\t\tint nedges = ReadInt();\n\t\t\tfor (int i_9 = 0; i_9 < nedges; i_9++)\n\t\t\t{\n\t\t\t\tint src = ReadInt();\n\t\t\t\tint trg = ReadInt();\n\t\t\t\tTransitionType ttype = (TransitionType)ReadInt();\n\t\t\t\tint arg1 = ReadInt();\n\t\t\t\tint arg2 = ReadInt();\n\t\t\t\tint arg3 = ReadInt();\n\t\t\t\tTransition trans = EdgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);\n\t\t\t\tATNState srcState = atn.states[src];\n\t\t\t\tsrcState.AddTransition(trans);\n\t\t\t}\n\t\t\t// edges for rule stop states can be derived, so they aren't serialized\n\t\t\tforeach (ATNState state_1 in atn.states)\n\t\t\t{\n\t\t\t\tfor (int i_10 = 0; i_10 < state_1.NumberOfTransitions; i_10++)\n\t\t\t\t{\n\t\t\t\t\tTransition t = state_1.Transition(i_10);\n\t\t\t\t\tif (!(t is RuleTransition))\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tRuleTransition ruleTransition = (RuleTransition)t;\n\t\t\t\t\tint outermostPrecedenceReturn = -1;\n\t\t\t\t\tif (atn.ruleToStartState[ruleTransition.target.ruleIndex].isPrecedenceRule)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ruleTransition.precedence == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toutermostPrecedenceReturn = ruleTransition.target.ruleIndex;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tEpsilonTransition returnTransition = new EpsilonTransition(ruleTransition.followState, outermostPrecedenceReturn);\n\t\t\t\t\tatn.ruleToStopState[ruleTransition.target.ruleIndex].AddTransition(returnTransition);\n\t\t\t\t}\n\t\t\t}\n\t\t\tforeach (ATNState state_2 in atn.states)\n\t\t\t{\n\t\t\t\tif (state_2 is BlockStartState)\n\t\t\t\t{\n\t\t\t\t\t// we need to know the end state to set its start state\n\t\t\t\t\tif (((BlockStartState)state_2).endState == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new InvalidOperationException();\n\t\t\t\t\t}\n\t\t\t\t\t// block end states can only be associated to a single block start state\n\t\t\t\t\tif (((BlockStartState)state_2).endState.startState != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new InvalidOperationException();\n\t\t\t\t\t}\n\t\t\t\t\t((BlockStartState)state_2).endState.startState = (BlockStartState)state_2;\n\t\t\t\t}\n\t\t\t\telse if (state_2 is PlusLoopbackState)\n\t\t\t\t{\n\t\t\t\t\tPlusLoopbackState loopbackState = (PlusLoopbackState)state_2;\n\t\t\t\t\tfor (int i_10 = 0; i_10 < loopbackState.NumberOfTransitions; i_10++)\n\t\t\t\t\t{\n\t\t\t\t\t\tATNState target = loopbackState.Transition(i_10).target;\n\t\t\t\t\t\tif (target is PlusBlockStartState)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t((PlusBlockStartState)target).loopBackState = loopbackState;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (state_2 is StarLoopbackState)\n\t\t\t\t{\n\t\t\t\t\tStarLoopbackState loopbackState = (StarLoopbackState)state_2;\n\t\t\t\t\tfor (int i_10 = 0; i_10 < loopbackState.NumberOfTransitions; i_10++)\n\t\t\t\t\t{\n\t\t\t\t\t\tATNState target = loopbackState.Transition(i_10).target;\n\t\t\t\t\t\tif (target is StarLoopEntryState)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t((StarLoopEntryState)target).loopBackState = loopbackState;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void ReadSets(ATN atn, IList<IntervalSet> sets)\n\t\t{\n\t\t\t//\n\t\t\t// SETS\n\t\t\t//\n\t\t\tint nsets = ReadInt();\n\t\t\tfor (int i_8 = 0; i_8 < nsets; i_8++)\n\t\t\t{\n\t\t\t\tIntervalSet set = new IntervalSet();\n\t\t\t\tsets.Add(set);\n\t\t\t\tint nintervals = ReadInt();\n\t\t\t\tbool containsEof = ReadInt() != 0;\n\t\t\t\tif (containsEof)\n\t\t\t\t{\n\t\t\t\t\tset.Add(-1);\n\t\t\t\t}\n\t\t\t\tfor (int j = 0; j < nintervals; j++)\n\t\t\t\t{\n\t\t\t\t\tset.Add(ReadInt(), ReadInt());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void ReadModes(ATN atn)\n\t\t{\n\t\t\t//\n\t\t\t// MODES\n\t\t\t//\n\t\t\tint nmodes = ReadInt();\n\t\t\tfor (int i_6 = 0; i_6 < nmodes; i_6++)\n\t\t\t{\n\t\t\t\tint _i = ReadInt();\n\t\t\t\tatn.modeToStartState.Add((TokensStartState)atn.states[_i]);\n\t\t\t}\n\t\t\t// not in Java code\n\t\t\tatn.modeToDFA = new DFA[nmodes];\n\t\t\tfor (int i_7 = 0; i_7 < nmodes; i_7++)\n\t\t\t{\n\t\t\t\tatn.modeToDFA[i_7] = new DFA(atn.modeToStartState[i_7]);\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void ReadRules(ATN atn)\n\t\t{\n\t\t\t//\n\t\t\t// RULES\n\t\t\t//\n\t\t\tint nrules = ReadInt();\n\t\t\tif (atn.grammarType == ATNType.Lexer)\n\t\t\t{\n\t\t\t\tatn.ruleToTokenType = new int[nrules];\n\t\t\t}\n\t\t\tatn.ruleToStartState = new RuleStartState[nrules];\n\t\t\tfor (int i_5 = 0; i_5 < nrules; i_5++)\n\t\t\t{\n\t\t\t\tint s = ReadInt();\n\t\t\t\tRuleStartState startState = (RuleStartState)atn.states[s];\n\t\t\t\tatn.ruleToStartState[i_5] = startState;\n\t\t\t\tif (atn.grammarType == ATNType.Lexer) {\n\t\t\t\t\tint tokenType = ReadInt ();\n\t\t\t\t\tatn.ruleToTokenType [i_5] = tokenType;\n\t\t\t\t}\n\t\t\t}\n\t\t\tatn.ruleToStopState = new RuleStopState[nrules];\n\t\t\tforeach (ATNState state in atn.states)\n\t\t\t{\n\t\t\t\tif (!(state is RuleStopState))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tRuleStopState stopState = (RuleStopState)state;\n\t\t\t\tatn.ruleToStopState[state.ruleIndex] = stopState;\n\t\t\t\tatn.ruleToStartState[state.ruleIndex].stopState = stopState;\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual void ReadStates(ATN atn)\n\t\t{\n\t\t\t//\n\t\t\t// STATES\n\t\t\t//\n\t\t\tIList<Tuple<LoopEndState, int>> loopBackStateNumbers = new List<Tuple<LoopEndState, int>>();\n\t\t\tIList<Tuple<BlockStartState, int>> endStateNumbers = new List<Tuple<BlockStartState, int>>();\n\t\t\tint nstates = ReadInt();\n\t\t\tfor (int i_1 = 0; i_1 < nstates; i_1++)\n\t\t\t{\n\t\t\t\tStateType stype = (StateType)ReadInt();\n\t\t\t\t// ignore bad type of states\n\t\t\t\tif (stype == StateType.InvalidType)\n\t\t\t\t{\n\t\t\t\t\tatn.AddState(null);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint ruleIndex = ReadInt();\n\t\t\t\tif (ruleIndex == char.MaxValue)\n\t\t\t\t{\n\t\t\t\t\truleIndex = -1;\n\t\t\t\t}\n\t\t\t\tATNState s = StateFactory(stype, ruleIndex);\n\t\t\t\tif (stype == StateType.LoopEnd)\n\t\t\t\t{\n\t\t\t\t\t// special case\n\t\t\t\t\tint loopBackStateNumber = ReadInt();\n\t\t\t\t\tloopBackStateNumbers.Add(Tuple.Create((LoopEndState)s, loopBackStateNumber));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (s is BlockStartState)\n\t\t\t\t\t{\n\t\t\t\t\t\tint endStateNumber = ReadInt();\n\t\t\t\t\t\tendStateNumbers.Add(Tuple.Create((BlockStartState)s, endStateNumber));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tatn.AddState(s);\n\t\t\t}\n\t\t\t// delay the assignment of loop back and end states until we know all the state instances have been initialized\n\t\t\tforeach (Tuple<LoopEndState, int> pair in loopBackStateNumbers)\n\t\t\t{\n\t\t\t\tpair.Item1.loopBackState = atn.states[pair.Item2];\n\t\t\t}\n\t\t\tforeach (Tuple<BlockStartState, int> pair_1 in endStateNumbers)\n\t\t\t{\n\t\t\t\tpair_1.Item1.endState = (BlockEndState)atn.states[pair_1.Item2];\n\t\t\t}\n\t\t\tint numNonGreedyStates = ReadInt();\n\t\t\tfor (int i_2 = 0; i_2 < numNonGreedyStates; i_2++)\n\t\t\t{\n\t\t\t\tint stateNumber = ReadInt();\n\t\t\t\t((DecisionState)atn.states[stateNumber]).nonGreedy = true;\n\t\t\t}\n\t\t\tint numPrecedenceStates = ReadInt();\n\t\t\tfor (int i_4 = 0; i_4 < numPrecedenceStates; i_4++)\n\t\t\t{\n\t\t\t\tint stateNumber = ReadInt();\n\t\t\t\t((RuleStartState)atn.states[stateNumber]).isPrecedenceRule = true;\n\t\t\t}\n\t\t}\n\n\t\tprotected internal virtual ATN ReadATN()\n\t\t{\n\t\t\tATNType grammarType = (ATNType)ReadInt();\n\t\t\tint maxTokenType = ReadInt();\n\t\t\treturn new ATN(grammarType, maxTokenType);\n\t\t}\n\n\t\tprotected internal virtual void CheckVersion()\n\t\t{\n\t\t\tint version = ReadInt();\n\t\t\tif (version != SerializedVersion)\n\t\t\t{\n\t\t\t\tstring reason = string.Format(CultureInfo.CurrentCulture, \"Could not deserialize ATN with version {0} (expected {1}).\", version, SerializedVersion);\n\t\t\t\tthrow new NotSupportedException(reason);\n\t\t\t}\n\t\t}\n\n        /// <summary>\n        /// Analyze the\n        /// <see cref=\"StarLoopEntryState\"/>\n        /// states in the specified ATN to set\n        /// the\n        /// <see cref=\"StarLoopEntryState.isPrecedenceDecision\"/>\n        /// field to the\n        /// correct value.\n        /// </summary>\n        /// <param name=\"atn\">The ATN.</param>\n        protected internal virtual void MarkPrecedenceDecisions(ATN atn)\n        {\n            foreach (ATNState state in atn.states)\n            {\n                if (!(state is StarLoopEntryState))\n                {\n                    continue;\n                }\n                if (atn.ruleToStartState[state.ruleIndex].isPrecedenceRule)\n                {\n                    ATNState maybeLoopEndState = state.Transition(state.NumberOfTransitions - 1).target;\n                    if (maybeLoopEndState is LoopEndState)\n                    {\n                        if (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.Transition(0).target is RuleStopState)\n                        {\n\t\t\t\t\t\t\t((StarLoopEntryState)state).isPrecedenceDecision = true;\n                        }\n                    }\n                }\n            }\n        }\n\n        protected internal virtual void VerifyATN(ATN atn)\n        {\n            // verify assumptions\n            foreach (ATNState state in atn.states)\n            {\n                if (state == null)\n                {\n                    continue;\n                }\n                CheckCondition(state.OnlyHasEpsilonTransitions || state.NumberOfTransitions <= 1);\n                if (state is PlusBlockStartState)\n                {\n                    CheckCondition(((PlusBlockStartState)state).loopBackState != null);\n                }\n                if (state is StarLoopEntryState)\n                {\n                    StarLoopEntryState starLoopEntryState = (StarLoopEntryState)state;\n                    CheckCondition(starLoopEntryState.loopBackState != null);\n                    CheckCondition(starLoopEntryState.NumberOfTransitions == 2);\n                    if (starLoopEntryState.Transition(0).target is StarBlockStartState)\n                    {\n                        CheckCondition(starLoopEntryState.Transition(1).target is LoopEndState);\n                        CheckCondition(!starLoopEntryState.nonGreedy);\n                    }\n                    else\n                    {\n                        if (starLoopEntryState.Transition(0).target is LoopEndState)\n                        {\n                            CheckCondition(starLoopEntryState.Transition(1).target is StarBlockStartState);\n                            CheckCondition(starLoopEntryState.nonGreedy);\n                        }\n                        else\n                        {\n                            throw new InvalidOperationException();\n                        }\n                    }\n                }\n                if (state is StarLoopbackState)\n                {\n                    CheckCondition(state.NumberOfTransitions == 1);\n                    CheckCondition(state.Transition(0).target is StarLoopEntryState);\n                }\n                if (state is LoopEndState)\n                {\n                    CheckCondition(((LoopEndState)state).loopBackState != null);\n                }\n                if (state is RuleStartState)\n                {\n                    CheckCondition(((RuleStartState)state).stopState != null);\n                }\n                if (state is BlockStartState)\n                {\n                    CheckCondition(((BlockStartState)state).endState != null);\n                }\n                if (state is BlockEndState)\n                {\n                    CheckCondition(((BlockEndState)state).startState != null);\n                }\n                if (state is DecisionState)\n                {\n                    DecisionState decisionState = (DecisionState)state;\n                    CheckCondition(decisionState.NumberOfTransitions <= 1 || decisionState.decision >= 0);\n                }\n                else\n                {\n                    CheckCondition(state.NumberOfTransitions <= 1 || state is RuleStopState);\n                }\n            }\n        }\n\n        protected internal virtual void CheckCondition(bool condition)\n        {\n            CheckCondition(condition, null);\n        }\n\n        protected internal virtual void CheckCondition(bool condition, string message)\n        {\n            if (!condition)\n            {\n                throw new InvalidOperationException(message);\n            }\n        }\n\n        private static int InlineSetRules(ATN atn)\n        {\n            int inlinedCalls = 0;\n            Transition[] ruleToInlineTransition = new Transition[atn.ruleToStartState.Length];\n            for (int i = 0; i < atn.ruleToStartState.Length; i++)\n            {\n                RuleStartState startState = atn.ruleToStartState[i];\n                ATNState middleState = startState;\n                while (middleState.OnlyHasEpsilonTransitions && middleState.NumberOfOptimizedTransitions == 1 && middleState.GetOptimizedTransition(0).TransitionType == TransitionType.EPSILON)\n                {\n                    middleState = middleState.GetOptimizedTransition(0).target;\n                }\n                if (middleState.NumberOfOptimizedTransitions != 1)\n                {\n                    continue;\n                }\n                Transition matchTransition = middleState.GetOptimizedTransition(0);\n                ATNState matchTarget = matchTransition.target;\n                if (matchTransition.IsEpsilon || !matchTarget.OnlyHasEpsilonTransitions || matchTarget.NumberOfOptimizedTransitions != 1 || !(matchTarget.GetOptimizedTransition(0).target is RuleStopState))\n                {\n                    continue;\n                }\n                switch (matchTransition.TransitionType)\n                {\n                    case TransitionType.ATOM:\n                    case TransitionType.RANGE:\n                    case TransitionType.SET:\n                    {\n                        ruleToInlineTransition[i] = matchTransition;\n                        break;\n                    }\n\n                    case TransitionType.NOT_SET:\n                    case TransitionType.WILDCARD:\n                    {\n                        // not implemented yet\n                        continue;\n                    }\n\n                    default:\n                    {\n                        continue;\n                    }\n                }\n            }\n            for (int stateNumber = 0; stateNumber < atn.states.Count; stateNumber++)\n            {\n                ATNState state = atn.states[stateNumber];\n                if (state.ruleIndex < 0)\n                {\n                    continue;\n                }\n                IList<Transition> optimizedTransitions = null;\n                for (int i_1 = 0; i_1 < state.NumberOfOptimizedTransitions; i_1++)\n                {\n                    Transition transition = state.GetOptimizedTransition(i_1);\n                    if (!(transition is RuleTransition))\n                    {\n                        if (optimizedTransitions != null)\n                        {\n                            optimizedTransitions.Add(transition);\n                        }\n                        continue;\n                    }\n                    RuleTransition ruleTransition = (RuleTransition)transition;\n                    Transition effective = ruleToInlineTransition[ruleTransition.target.ruleIndex];\n                    if (effective == null)\n                    {\n                        if (optimizedTransitions != null)\n                        {\n                            optimizedTransitions.Add(transition);\n                        }\n                        continue;\n                    }\n                    if (optimizedTransitions == null)\n                    {\n                        optimizedTransitions = new List<Transition>();\n                        for (int j = 0; j < i_1; j++)\n                        {\n                            optimizedTransitions.Add(state.GetOptimizedTransition(i_1));\n                        }\n                    }\n                    inlinedCalls++;\n                    ATNState target = ruleTransition.followState;\n                    ATNState intermediateState = new BasicState();\n                    intermediateState.SetRuleIndex(target.ruleIndex);\n                    atn.AddState(intermediateState);\n                    optimizedTransitions.Add(new EpsilonTransition(intermediateState));\n                    switch (effective.TransitionType)\n                    {\n                        case TransitionType.ATOM:\n                        {\n\t\t\t\t\t\t\tintermediateState.AddTransition(new AtomTransition(target, ((AtomTransition)effective).token));\n                            break;\n                        }\n\n                        case TransitionType.RANGE:\n                        {\n                            intermediateState.AddTransition(new RangeTransition(target, ((RangeTransition)effective).from, ((RangeTransition)effective).to));\n                            break;\n                        }\n\n                        case TransitionType.SET:\n                        {\n                            intermediateState.AddTransition(new SetTransition(target, effective.Label));\n                            break;\n                        }\n\n                        default:\n                        {\n                            throw new NotSupportedException();\n                        }\n                    }\n                }\n                if (optimizedTransitions != null)\n                {\n                    if (state.IsOptimized)\n                    {\n                        while (state.NumberOfOptimizedTransitions > 0)\n                        {\n                            state.RemoveOptimizedTransition(state.NumberOfOptimizedTransitions - 1);\n                        }\n                    }\n                    foreach (Transition transition in optimizedTransitions)\n                    {\n                        state.AddOptimizedTransition(transition);\n                    }\n                }\n            }\n            return inlinedCalls;\n        }\n\n        private static int CombineChainedEpsilons(ATN atn)\n        {\n            int removedEdges = 0;\n            foreach (ATNState state in atn.states)\n            {\n                if (!state.OnlyHasEpsilonTransitions || state is RuleStopState)\n                {\n                    continue;\n                }\n                IList<Transition> optimizedTransitions = null;\n                for (int i = 0; i < state.NumberOfOptimizedTransitions; i++)\n                {\n                    Transition transition = state.GetOptimizedTransition(i);\n                    ATNState intermediate = transition.target;\n                    if (transition.TransitionType != TransitionType.EPSILON || ((EpsilonTransition)transition).OutermostPrecedenceReturn != -1 || intermediate.StateType != StateType.Basic || !intermediate.OnlyHasEpsilonTransitions)\n                    {\n                        if (optimizedTransitions != null)\n                        {\n                            optimizedTransitions.Add(transition);\n                        }\n                        goto nextTransition_continue;\n                    }\n                    for (int j = 0; j < intermediate.NumberOfOptimizedTransitions; j++)\n                    {\n                        if (intermediate.GetOptimizedTransition(j).TransitionType != TransitionType.EPSILON || ((EpsilonTransition)intermediate.GetOptimizedTransition(j)).OutermostPrecedenceReturn != -1)\n                        {\n                            if (optimizedTransitions != null)\n                            {\n                                optimizedTransitions.Add(transition);\n                            }\n                            goto nextTransition_continue;\n                        }\n                    }\n                    removedEdges++;\n                    if (optimizedTransitions == null)\n                    {\n                        optimizedTransitions = new List<Transition>();\n                        for (int j_1 = 0; j_1 < i; j_1++)\n                        {\n                            optimizedTransitions.Add(state.GetOptimizedTransition(j_1));\n                        }\n                    }\n                    for (int j_2 = 0; j_2 < intermediate.NumberOfOptimizedTransitions; j_2++)\n                    {\n                        ATNState target = intermediate.GetOptimizedTransition(j_2).target;\n                        optimizedTransitions.Add(new EpsilonTransition(target));\n                    }\nnextTransition_continue: ;\n                }\n\n                if (optimizedTransitions != null)\n                {\n                    if (state.IsOptimized)\n                    {\n                        while (state.NumberOfOptimizedTransitions > 0)\n                        {\n                            state.RemoveOptimizedTransition(state.NumberOfOptimizedTransitions - 1);\n                        }\n                    }\n                    foreach (Transition transition in optimizedTransitions)\n                    {\n                        state.AddOptimizedTransition(transition);\n                    }\n                }\n            }\n\n            return removedEdges;\n        }\n\n        private static int OptimizeSets(ATN atn, bool preserveOrder)\n        {\n            if (preserveOrder)\n            {\n                // this optimization currently doesn't preserve edge order.\n                return 0;\n            }\n            int removedPaths = 0;\n            IList<DecisionState> decisions = atn.decisionToState;\n            foreach (DecisionState decision in decisions)\n            {\n                IntervalSet setTransitions = new IntervalSet();\n                for (int i = 0; i < decision.NumberOfOptimizedTransitions; i++)\n                {\n                    Transition epsTransition = decision.GetOptimizedTransition(i);\n                    if (!(epsTransition is EpsilonTransition))\n                    {\n                        continue;\n                    }\n                    if (epsTransition.target.NumberOfOptimizedTransitions != 1)\n                    {\n                        continue;\n                    }\n                    Transition transition = epsTransition.target.GetOptimizedTransition(0);\n                    if (!(transition.target is BlockEndState))\n                    {\n                        continue;\n                    }\n                    if (transition is NotSetTransition)\n                    {\n                        // TODO: not yet implemented\n                        continue;\n                    }\n                    if (transition is AtomTransition || transition is RangeTransition || transition is SetTransition)\n                    {\n                        setTransitions.Add(i);\n                    }\n                }\n                if (setTransitions.Count <= 1)\n                {\n                    continue;\n                }\n                IList<Transition> optimizedTransitions = new List<Transition>();\n                for (int i_1 = 0; i_1 < decision.NumberOfOptimizedTransitions; i_1++)\n                {\n                    if (!setTransitions.Contains(i_1))\n                    {\n                        optimizedTransitions.Add(decision.GetOptimizedTransition(i_1));\n                    }\n                }\n                ATNState blockEndState = decision.GetOptimizedTransition(setTransitions.MinElement).target.GetOptimizedTransition(0).target;\n                IntervalSet matchSet = new IntervalSet();\n                for (int i_2 = 0; i_2 < setTransitions.GetIntervals().Count; i_2++)\n                {\n                    Interval interval = setTransitions.GetIntervals()[i_2];\n                    for (int j = interval.a; j <= interval.b; j++)\n                    {\n                        Transition matchTransition = decision.GetOptimizedTransition(j).target.GetOptimizedTransition(0);\n                        if (matchTransition is NotSetTransition)\n                        {\n                            throw new NotSupportedException(\"Not yet implemented.\");\n                        }\n                        else\n                        {\n                            matchSet.AddAll(matchTransition.Label);\n                        }\n                    }\n                }\n                Transition newTransition;\n                if (matchSet.GetIntervals().Count == 1)\n                {\n                    if (matchSet.Count == 1)\n                    {\n                        newTransition = new AtomTransition(blockEndState, matchSet.MinElement);\n                    }\n                    else\n                    {\n                        Interval matchInterval = matchSet.GetIntervals()[0];\n                        newTransition = new RangeTransition(blockEndState, matchInterval.a, matchInterval.b);\n                    }\n                }\n                else\n                {\n                    newTransition = new SetTransition(blockEndState, matchSet);\n                }\n                ATNState setOptimizedState = new BasicState();\n                setOptimizedState.SetRuleIndex(decision.ruleIndex);\n                atn.AddState(setOptimizedState);\n                setOptimizedState.AddTransition(newTransition);\n                optimizedTransitions.Add(new EpsilonTransition(setOptimizedState));\n                removedPaths += decision.NumberOfOptimizedTransitions - optimizedTransitions.Count;\n                if (decision.IsOptimized)\n                {\n                    while (decision.NumberOfOptimizedTransitions > 0)\n                    {\n                        decision.RemoveOptimizedTransition(decision.NumberOfOptimizedTransitions - 1);\n                    }\n                }\n                foreach (Transition transition_1 in optimizedTransitions)\n                {\n                    decision.AddOptimizedTransition(transition_1);\n                }\n            }\n            return removedPaths;\n        }\n\n        private static void IdentifyTailCalls(ATN atn)\n        {\n            foreach (ATNState state in atn.states)\n            {\n                foreach (Transition transition in state.transitions)\n                {\n                    if (!(transition is RuleTransition))\n                    {\n                        continue;\n                    }\n                    RuleTransition ruleTransition = (RuleTransition)transition;\n                    ruleTransition.tailCall = TestTailCall(atn, ruleTransition, false);\n                    ruleTransition.optimizedTailCall = TestTailCall(atn, ruleTransition, true);\n                }\n                if (!state.IsOptimized)\n                {\n                    continue;\n                }\n                foreach (Transition transition_1 in state.optimizedTransitions)\n                {\n                    if (!(transition_1 is RuleTransition))\n                    {\n                        continue;\n                    }\n                    RuleTransition ruleTransition = (RuleTransition)transition_1;\n                    ruleTransition.tailCall = TestTailCall(atn, ruleTransition, false);\n                    ruleTransition.optimizedTailCall = TestTailCall(atn, ruleTransition, true);\n                }\n            }\n        }\n\n        private static bool TestTailCall(ATN atn, RuleTransition transition, bool optimizedPath)\n        {\n            if (!optimizedPath && transition.tailCall)\n            {\n                return true;\n            }\n            if (optimizedPath && transition.optimizedTailCall)\n            {\n                return true;\n            }\n            BitSet reachable = new BitSet(atn.states.Count);\n            Stack<ATNState> worklist = new Stack<ATNState>();\n            worklist.Push(transition.followState);\n            while (worklist.Count > 0)\n            {\n                ATNState state = worklist.Pop();\n                if (reachable.Get(state.stateNumber))\n                {\n                    continue;\n                }\n                if (state is RuleStopState)\n                {\n                    continue;\n                }\n                if (!state.OnlyHasEpsilonTransitions)\n                {\n                    return false;\n                }\n                IList<Transition> transitions = optimizedPath ? state.optimizedTransitions : state.transitions;\n                foreach (Transition t in transitions)\n                {\n                    if (t.TransitionType != TransitionType.EPSILON)\n                    {\n                        return false;\n                    }\n                    worklist.Push(t.target);\n                }\n            }\n            return true;\n        }\n\n\n        protected internal int ReadInt()\n        {\n\t\t\treturn data[p++];\n        }\n\n        [return: NotNull]\n        protected internal virtual Transition EdgeFactory(ATN atn, TransitionType type, int src, int trg, int arg1, int arg2, int arg3, IList<IntervalSet> sets)\n        {\n            ATNState target = atn.states[trg];\n            switch (type)\n            {\n                case TransitionType.EPSILON:\n                {\n                    return new EpsilonTransition(target);\n                }\n\n                case TransitionType.RANGE:\n                {\n                    if (arg3 != 0)\n                    {\n                        return new RangeTransition(target, TokenConstants.EOF, arg2);\n                    }\n                    else\n                    {\n                        return new RangeTransition(target, arg1, arg2);\n                    }\n                }\n\n                case TransitionType.RULE:\n                {\n                    RuleTransition rt = new RuleTransition((RuleStartState)atn.states[arg1], arg2, arg3, target);\n                    return rt;\n                }\n\n                case TransitionType.PREDICATE:\n                {\n                    PredicateTransition pt = new PredicateTransition(target, arg1, arg2, arg3 != 0);\n                    return pt;\n                }\n\n                case TransitionType.PRECEDENCE:\n                {\n                    return new PrecedencePredicateTransition(target, arg1);\n                }\n\n                case TransitionType.ATOM:\n                {\n                    if (arg3 != 0)\n                    {\n                        return new AtomTransition(target, TokenConstants.EOF);\n                    }\n                    else\n                    {\n                        return new AtomTransition(target, arg1);\n                    }\n                }\n\n                case TransitionType.ACTION:\n                {\n                    ActionTransition a = new ActionTransition(target, arg1, arg2, arg3 != 0);\n                    return a;\n                }\n\n                case TransitionType.SET:\n                {\n                    return new SetTransition(target, sets[arg1]);\n                }\n\n                case TransitionType.NOT_SET:\n                {\n                    return new NotSetTransition(target, sets[arg1]);\n                }\n\n                case TransitionType.WILDCARD:\n                {\n                    return new WildcardTransition(target);\n                }\n            }\n            throw new ArgumentException(\"The specified transition type is not valid.\");\n        }\n\n        protected internal virtual ATNState StateFactory(StateType type, int ruleIndex)\n        {\n            ATNState s;\n            switch (type)\n            {\n                case StateType.InvalidType:\n                {\n                    return null;\n                }\n\n                case StateType.Basic:\n                {\n                    s = new BasicState();\n                    break;\n                }\n\n                case StateType.RuleStart:\n                {\n                    s = new RuleStartState();\n                    break;\n                }\n\n                case StateType.BlockStart:\n                {\n                    s = new BasicBlockStartState();\n                    break;\n                }\n\n                case StateType.PlusBlockStart:\n                {\n                    s = new PlusBlockStartState();\n                    break;\n                }\n\n                case StateType.StarBlockStart:\n                {\n                    s = new StarBlockStartState();\n                    break;\n                }\n\n                case StateType.TokenStart:\n                {\n                    s = new TokensStartState();\n                    break;\n                }\n\n                case StateType.RuleStop:\n                {\n                    s = new RuleStopState();\n                    break;\n                }\n\n                case StateType.BlockEnd:\n                {\n                    s = new BlockEndState();\n                    break;\n                }\n\n                case StateType.StarLoopBack:\n                {\n                    s = new StarLoopbackState();\n                    break;\n                }\n\n                case StateType.StarLoopEntry:\n                {\n                    s = new StarLoopEntryState();\n                    break;\n                }\n\n                case StateType.PlusLoopBack:\n                {\n                    s = new PlusLoopbackState();\n                    break;\n                }\n\n                case StateType.LoopEnd:\n                {\n                    s = new LoopEndState();\n                    break;\n                }\n\n                default:\n                {\n                    string message = string.Format(CultureInfo.CurrentCulture, \"The specified state type {0} is not valid.\", type);\n                    throw new ArgumentException(message);\n                }\n            }\n            s.ruleIndex = ruleIndex;\n            return s;\n        }\n\n        protected internal virtual ILexerAction LexerActionFactory(LexerActionType type, int data1, int data2)\n        {\n            switch (type)\n            {\n                case LexerActionType.Channel:\n                {\n                    return new LexerChannelAction(data1);\n                }\n\n                case LexerActionType.Custom:\n                {\n                    return new LexerCustomAction(data1, data2);\n                }\n\n                case LexerActionType.Mode:\n                {\n                    return new LexerModeAction(data1);\n                }\n\n                case LexerActionType.More:\n                {\n                    return LexerMoreAction.Instance;\n                }\n\n                case LexerActionType.PopMode:\n                {\n                    return LexerPopModeAction.Instance;\n                }\n\n                case LexerActionType.PushMode:\n                {\n                    return new LexerPushModeAction(data1);\n                }\n\n                case LexerActionType.Skip:\n                {\n                    return LexerSkipAction.Instance;\n                }\n\n                case LexerActionType.Type:\n                {\n                    return new LexerTypeAction(data1);\n                }\n\n                default:\n                {\n                    string message = string.Format(CultureInfo.CurrentCulture, \"The specified lexer action type {0} is not valid.\", type);\n                    throw new ArgumentException(message);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATNSimulator.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\tpublic abstract class ATNSimulator\n\t{\n\n\n\t\t/** Must distinguish between missing edge and edge we know leads nowhere */\n\n\t\tpublic static readonly DFAState ERROR = InitERROR();\n\n\t\tstatic DFAState InitERROR()\n\t\t{\n\t\t\tDFAState state = new DFAState(new ATNConfigSet());\n\t\t\tstate.stateNumber = Int32.MaxValue;\n\t\t\treturn state;\n\t\t}\n\n\t\tpublic readonly ATN atn;\n\n\t\t/** The context cache maps all PredictionContext objects that are equals()\n\t\t *  to a single cached copy. This cache is shared across all contexts\n\t\t *  in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet\n\t\t *  to use only cached nodes/graphs in addDFAState(). We don't want to\n\t\t *  fill this during closure() since there are lots of contexts that\n\t\t *  pop up but are not used ever again. It also greatly slows down closure().\n\t\t *\n\t\t *  <p>This cache makes a huge difference in memory and a little bit in speed.\n\t\t *  For the Java grammar on java.*, it dropped the memory requirements\n\t\t *  at the end from 25M to 16M. We don't store any of the full context\n\t\t *  graphs in the DFA because they are limited to local context only,\n\t\t *  but apparently there's a lot of repetition there as well. We optimize\n\t\t *  the config contexts before storing the config set in the DFA states\n\t\t *  by literally rebuilding them with cached subgraphs only.</p>\n\t\t *\n\t\t *  <p>I tried a cache for use during closure operations, that was\n\t\t *  whacked after each adaptivePredict(). It cost a little bit\n\t\t *  more time I think and doesn't save on the overall footprint\n\t\t *  so it's not worth the complexity.</p>\n\t\t */\n\t\tprotected readonly PredictionContextCache sharedContextCache;\n\n\n\t\tpublic ATNSimulator(ATN atn, PredictionContextCache sharedContextCache)\n\t\t{\n\t\t\tthis.atn = atn;\n\t\t\tthis.sharedContextCache = sharedContextCache;\n\t\t}\n\n\t\tpublic abstract void Reset();\n\n\t\t/**\n\t\t * Clear the DFA cache used by the current instance. Since the DFA cache may\n\t\t * be shared by multiple ATN simulators, this method may affect the\n\t\t * performance (but not accuracy) of other parsers which are being used\n\t\t * concurrently.\n\t\t *\n\t\t * @throws UnsupportedOperationException if the current instance does not\n\t\t * support clearing the DFA.\n\t\t *\n\t\t * @since 4.3\n\t\t */\n\t\tpublic virtual void ClearDFA()\n\t\t{\n\t\t\tthrow new Exception(\"This ATN simulator does not support clearing the DFA.\");\n\t\t}\n\n        public PredictionContextCache getSharedContextCache()\n\t\t{\n\t\t\treturn sharedContextCache;\n\t\t}\n\n\t\tpublic PredictionContext getCachedContext(PredictionContext context)\n\t\t{\n\t\t\tif (sharedContextCache == null) return context;\n\n\t\t\tlock (sharedContextCache)\n\t\t\t{\n\t\t\t\tPredictionContext.IdentityHashMap visited =\n\t\t\t\t\tnew PredictionContext.IdentityHashMap();\n\t\t\t\treturn PredictionContext.GetCachedContext(context,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  sharedContextCache,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  visited);\n\t\t\t}\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATNState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public abstract class ATNState\n    {\n        public const int InitialNumTransitions = 4;\n\n        public static readonly ReadOnlyCollection<string> serializationNames = new ReadOnlyCollection<string>(Arrays.AsList(\"INVALID\", \"BASIC\", \"RULE_START\", \"BLOCK_START\", \"PLUS_BLOCK_START\", \"STAR_BLOCK_START\", \"TOKEN_START\", \"RULE_STOP\", \"BLOCK_END\", \"STAR_LOOP_BACK\", \"STAR_LOOP_ENTRY\", \"PLUS_LOOP_BACK\", \"LOOP_END\"));\n\n        public const int InvalidStateNumber = -1;\n\n        public ATN atn = null;\n\n        public int stateNumber = InvalidStateNumber;\n\n        public int ruleIndex;\n\n        public bool epsilonOnlyTransitions = false;\n\n        protected internal readonly List<Transition> transitions = new List<Transition>(InitialNumTransitions);\n\n        protected internal List<Transition> optimizedTransitions;\n\n        public IntervalSet nextTokenWithinRule;\n\n        public virtual int NonStopStateNumber\n        {\n            get\n            {\n                return stateNumber;\n            }\n        }\n\n        public override int GetHashCode()\n        {\n            return stateNumber;\n        }\n\n        public override bool Equals(object o)\n        {\n            return o==this ||\n\t\t\t\t(o is ATNState && stateNumber == ((ATNState)o).stateNumber);\n        }\n\n        public virtual bool IsNonGreedyExitState\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public override string ToString()\n        {\n            return stateNumber.ToString();\n        }\n\n        public virtual Transition[] TransitionsArray\n        {\n            get\n            {\n                return transitions.ToArray();\n            }\n        }\n\n        public virtual int NumberOfTransitions\n        {\n            get\n            {\n                return transitions.Count;\n            }\n        }\n\n        public virtual void AddTransition(Antlr4.Runtime.Atn.Transition e)\n        {\n            AddTransition(transitions.Count, e);\n        }\n\n        public virtual void AddTransition(int index, Antlr4.Runtime.Atn.Transition e)\n        {\n            if (transitions.Count == 0)\n            {\n                epsilonOnlyTransitions = e.IsEpsilon;\n            }\n            else\n            {\n                if (epsilonOnlyTransitions != e.IsEpsilon)\n                {\n                    System.Console.Error.WriteLine(\"ATN state {0} has both epsilon and non-epsilon transitions.\", stateNumber);\n                    epsilonOnlyTransitions = false;\n                }\n            }\n            transitions.Insert(index, e);\n        }\n\n        public virtual Antlr4.Runtime.Atn.Transition Transition(int i)\n        {\n            return transitions[i];\n        }\n\n        public virtual void SetTransition(int i, Antlr4.Runtime.Atn.Transition e)\n        {\n            transitions[i] = e;\n        }\n\n        public virtual void RemoveTransition(int index)\n        {\n            transitions.RemoveAt(index);\n        }\n\n        public abstract Antlr4.Runtime.Atn.StateType StateType\n        {\n            get;\n        }\n\n        public bool OnlyHasEpsilonTransitions\n        {\n            get\n            {\n                return epsilonOnlyTransitions;\n            }\n        }\n\n        public virtual void SetRuleIndex(int ruleIndex)\n        {\n            this.ruleIndex = ruleIndex;\n        }\n\n        public virtual bool IsOptimized\n        {\n            get\n            {\n                return optimizedTransitions != transitions;\n            }\n        }\n\n        public virtual int NumberOfOptimizedTransitions\n        {\n            get\n            {\n                return optimizedTransitions.Count;\n            }\n        }\n\n        public virtual Antlr4.Runtime.Atn.Transition GetOptimizedTransition(int i)\n        {\n            return optimizedTransitions[i];\n        }\n\n        public virtual void AddOptimizedTransition(Antlr4.Runtime.Atn.Transition e)\n        {\n            if (!IsOptimized)\n            {\n                optimizedTransitions = new List<Antlr4.Runtime.Atn.Transition>();\n            }\n            optimizedTransitions.Add(e);\n        }\n\n        public virtual void SetOptimizedTransition(int i, Antlr4.Runtime.Atn.Transition e)\n        {\n            if (!IsOptimized)\n            {\n                throw new InvalidOperationException();\n            }\n            optimizedTransitions[i] = e;\n        }\n\n        public virtual void RemoveOptimizedTransition(int i)\n        {\n            if (!IsOptimized)\n            {\n                throw new InvalidOperationException();\n            }\n            optimizedTransitions.RemoveAt(i);\n        }\n\n        public ATNState()\n        {\n            optimizedTransitions = transitions;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ATNType.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>Represents the type of recognizer an ATN applies to.</summary>\n    /// <remarks>Represents the type of recognizer an ATN applies to.</remarks>\n    /// <author>Sam Harwell</author>\n    public enum ATNType\n    {\n        Lexer,\n        Parser\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/AbstractPredicateTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    public abstract class AbstractPredicateTransition : Transition\n    {\n        public AbstractPredicateTransition(ATNState target)\n            : base(target)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ActionTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class ActionTransition : Transition\n    {\n        public readonly int ruleIndex;\n\n        public readonly int actionIndex;\n\n        public readonly bool isCtxDependent;\n\n        public ActionTransition(ATNState target, int ruleIndex)\n            : this(target, ruleIndex, -1, false)\n        {\n        }\n\n        public ActionTransition(ATNState target, int ruleIndex, int actionIndex, bool isCtxDependent)\n            : base(target)\n        {\n            // e.g., $i ref in action\n            this.ruleIndex = ruleIndex;\n            this.actionIndex = actionIndex;\n            this.isCtxDependent = isCtxDependent;\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.ACTION;\n            }\n        }\n\n        public override bool IsEpsilon\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        // we are to be ignored by analysis 'cept for predicates\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return false;\n        }\n\n        public override string ToString()\n        {\n            return \"action_\" + ruleIndex + \":\" + actionIndex;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/AmbiguityInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>This class represents profiling event information for an ambiguity.</summary>\n    /// <remarks>\n    /// This class represents profiling event information for an ambiguity.\n    /// Ambiguities are decisions where a particular input resulted in an SLL\n    /// conflict, followed by LL prediction also reaching a conflict state\n    /// (indicating a true ambiguity in the grammar).\n    /// <p>\n    /// This event may be reported during SLL prediction in cases where the\n    /// conflicting SLL configuration set provides sufficient information to\n    /// determine that the SLL conflict is truly an ambiguity. For example, if none\n    /// of the ATN configurations in the conflicting SLL configuration set have\n    /// traversed a global follow transition (i.e.\n    /// <see cref=\"ATNConfig.reachesIntoOuterContext\"/>\n    /// is\n    /// <see langword=\"false\"/>\n    /// for all\n    /// configurations), then the result of SLL prediction for that input is known to\n    /// be equivalent to the result of LL prediction for that input.</p>\n    /// <p>\n    /// In some cases, the minimum represented alternative in the conflicting LL\n    /// configuration set is not equal to the minimum represented alternative in the\n    /// conflicting SLL configuration set. Grammars and inputs which result in this\n    /// scenario are unable to use\n    /// <see cref=\"PredictionMode.SLL\"/>\n    /// , which in turn means\n    /// they cannot use the two-stage parsing strategy to improve parsing performance\n    /// for that input.</p>\n    /// </remarks>\n    /// <seealso cref=\"ParserATNSimulator.ReportAmbiguity(Antlr4.Runtime.Dfa.DFA, Antlr4.Runtime.Dfa.DFAState, int, int, bool, Antlr4.Runtime.Sharpen.BitSet, ATNConfigSet)\"/>\n    /// <seealso cref=\"Antlr4.Runtime.IParserErrorListener.ReportAmbiguity(Antlr4.Runtime.Parser, Antlr4.Runtime.Dfa.DFA, int, int, bool, Antlr4.Runtime.Sharpen.BitSet, ATNConfigSet)\"/>\n    /// <since>4.3</since>\n    public class AmbiguityInfo : DecisionEventInfo\n    {\n        /** The set of alternative numbers for this decision event that lead to a valid parse. */\n        public BitSet ambigAlts;\n\n        /// <summary>\n        /// Constructs a new instance of the\n        /// <see cref=\"AmbiguityInfo\"/>\n        /// class with the\n        /// specified detailed ambiguity information.\n        /// </summary>\n        /// <param name=\"decision\">The decision number</param>\n        /// <param name=\"configs\">The final configuration set identifying the ambiguous\n        /// alternatives for the current input\n        /// </param>\n        /// <param name=\"ambigAlts\">The set of alternatives in the decision that lead to a valid parse.\n        /// The predicted alt is the min(ambigAlts)\n        /// </param>\n        /// <param name=\"input\">The input token stream</param>\n        /// <param name=\"startIndex\">The start index for the current prediction</param>\n        /// <param name=\"stopIndex\">\n        /// The index at which the ambiguity was identified during\n        /// prediction\n        /// </param>\n        /// <param name=\"fullCtx\">@code true} if the ambiguity was identified during LL\n        /// prediction; otherwise, {@code false} if the ambiguity was identified\n        /// during SLL prediction\n        /// </param>\n        public AmbiguityInfo(int decision,\n                 ATNConfigSet configs,\n                 BitSet ambigAlts,\n                 ITokenStream input, int startIndex, int stopIndex,\n                 bool fullCtx)\n        : base(decision, configs, input, startIndex, stopIndex, fullCtx)\n        {\n            this.ambigAlts = ambigAlts;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ArrayPredictionContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Text;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\n\n\t#pragma warning disable 0659 // 'class' overrides Object.Equals(object o) but does not override Object.GetHashCode()\n\tpublic class ArrayPredictionContext : PredictionContext\n\t{\n\t\t/** Parent can be null only if full ctx mode and we make an array\n\t\t *  from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and\n\t\t *  returnState == {@link #EMPTY_RETURN_STATE}.\n\t\t */\n\t\tpublic readonly PredictionContext[] parents;\n\n\t\t/** Sorted for merge, no duplicates; if present,\n\t\t *  {@link #EMPTY_RETURN_STATE} is always last.\n\t\t */\n\t\tpublic readonly int[] returnStates;\n\n\t\tpublic ArrayPredictionContext(SingletonPredictionContext a)\n\t\t\t: this(new PredictionContext[] { a.parent }, new int[] { a.returnState })\n\t\t{\n\t\t}\n\n\t\tpublic ArrayPredictionContext(PredictionContext[] parents, int[] returnStates)\n\t\t\t: base(CalculateHashCode(parents, returnStates))\n\t\t{\n\t\t\t//\t\tSystem.err.println(\"CREATE ARRAY: \"+Arrays.toString(parents)+\", \"+Arrays.toString(returnStates));\n\t\t\tthis.parents = parents;\n\t\t\tthis.returnStates = returnStates;\n\t\t}\n\n\t\tpublic override bool IsEmpty\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\t// since EMPTY_RETURN_STATE can only appear in the last position, we\n\t\t\t\t// don't need to verify that size==1\n\t\t\t\treturn returnStates[0] == EMPTY_RETURN_STATE;\n\t\t\t}\n\t\t}\n\n\t\tpublic override int Size\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn returnStates.Length;\n\t\t\t}\n\t\t}\n\n\t\tpublic override PredictionContext GetParent(int index)\n\t\t{\n\t\t\treturn parents[index];\n\t\t}\n\n\t\tpublic override int GetReturnState(int index)\n\t\t{\n\t\t\treturn returnStates[index];\n\t\t}\n\n\t\t//\t@Override\n\t\t//\tpublic int findReturnState(int returnState) {\n\t\t//\t\treturn Arrays.binarySearch(returnStates, returnState);\n\t\t//\t}\n\n\t\tpublic override bool Equals(Object o)\n\t\t{\n\t\t\tif (this == o)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (!(o is ArrayPredictionContext))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (this.GetHashCode() != o.GetHashCode())\n\t\t\t{\n\t\t\t\treturn false; // can't be same if hash is different\n\t\t\t}\n\n\t\t\tArrayPredictionContext a = (ArrayPredictionContext)o;\n\t\t\treturn Arrays.Equals(returnStates, a.returnStates) &&\n\t\t\t\t   Arrays.Equals(parents, a.parents);\n\t\t}\n\n\n\t\tpublic override String ToString()\n\t\t{\n\t\t\tif (IsEmpty)\n\t\t\t\treturn \"[]\";\n\t\t\tStringBuilder buf = new StringBuilder();\n\t\t\tbuf.Append(\"[\");\n\t\t\tfor (int i = 0; i < returnStates.Length; i++)\n\t\t\t{\n\t\t\t\tif (i > 0) buf.Append(\", \");\n\t\t\t\tif (returnStates[i] == EMPTY_RETURN_STATE)\n\t\t\t\t{\n\t\t\t\t\tbuf.Append(\"$\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbuf.Append(returnStates[i]);\n\t\t\t\tif (parents[i] != null)\n\t\t\t\t{\n\t\t\t\t\tbuf.Append(' ');\n\t\t\t\t\tbuf.Append(parents[i].ToString());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbuf.Append(\"null\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuf.Append(\"]\");\n\t\t\treturn buf.ToString();\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/AtomTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>TODO: make all transitions sets? no, should remove set edges</summary>\n    public sealed class AtomTransition : Transition\n    {\n        /// <summary>The token type or character value; or, signifies special label.</summary>\n        /// <remarks>The token type or character value; or, signifies special label.</remarks>\n        public readonly int token;\n\n\t\tpublic AtomTransition(ATNState target, int token)\n            : base(target)\n        {\n\t\t\tthis.token = token;\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.ATOM;\n            }\n        }\n\n        public override IntervalSet Label\n        {\n            get\n            {\n\t\t\t\treturn IntervalSet.Of(token);\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n\t\t\treturn token == symbol;\n        }\n\n        [return: NotNull]\n        public override string ToString()\n        {\n\t\t\treturn token.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/BasicBlockStartState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    public sealed class BasicBlockStartState : BlockStartState\n    {\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.BlockStart;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/BasicState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    public sealed class BasicState : ATNState\n    {\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.Basic;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/BlockEndState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Terminal node of a simple\n    /// <c>(a|b|c)</c>\n    /// block.\n    /// </summary>\n    public sealed class BlockEndState : ATNState\n    {\n        public BlockStartState startState;\n\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.BlockEnd;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/BlockStartState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// The start of a regular\n    /// <c>(...)</c>\n    /// block.\n    /// </summary>\n    public abstract class BlockStartState : DecisionState\n    {\n        public BlockEndState endState;\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ConflictInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>This class stores information about a configuration conflict.</summary>\n    /// <author>Sam Harwell</author>\n    public class ConflictInfo\n    {\n        private readonly BitSet conflictedAlts;\n\n        private readonly bool exact;\n\n        public ConflictInfo(BitSet conflictedAlts, bool exact)\n        {\n            this.conflictedAlts = conflictedAlts;\n            this.exact = exact;\n        }\n\n        /// <summary>Gets the set of conflicting alternatives for the configuration set.</summary>\n        /// <remarks>Gets the set of conflicting alternatives for the configuration set.</remarks>\n        public BitSet ConflictedAlts\n        {\n            get\n            {\n                return conflictedAlts;\n            }\n        }\n\n        /// <summary>Gets whether or not the configuration conflict is an exact conflict.</summary>\n        /// <remarks>\n        /// Gets whether or not the configuration conflict is an exact conflict.\n        /// An exact conflict occurs when the prediction algorithm determines that\n        /// the represented alternatives for a particular configuration set cannot be\n        /// further reduced by consuming additional input. After reaching an exact\n        /// conflict during an SLL prediction, only switch to full-context prediction\n        /// could reduce the set of viable alternatives. In LL prediction, an exact\n        /// conflict indicates a true ambiguity in the input.\n        /// <p>\n        /// For the\n        /// <see cref=\"PredictionMode.LL_EXACT_AMBIG_DETECTION\"/>\n        /// prediction mode,\n        /// accept states are conflicting but not exact are treated as non-accept\n        /// states.</p>\n        /// </remarks>\n        public bool IsExact\n        {\n            get\n            {\n                return exact;\n            }\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.ConflictInfo))\n                {\n                    return false;\n                }\n            }\n            Antlr4.Runtime.Atn.ConflictInfo other = (Antlr4.Runtime.Atn.ConflictInfo)obj;\n            return IsExact == other.IsExact && Utils.Equals(ConflictedAlts, other.ConflictedAlts);\n        }\n\n        public override int GetHashCode()\n        {\n            return ConflictedAlts.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ContextSensitivityInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>This class represents profiling event information for a context sensitivity.</summary>\n    /// <remarks>\n    /// This class represents profiling event information for a context sensitivity.\n    /// Context sensitivities are decisions where a particular input resulted in an\n    /// SLL conflict, but LL prediction produced a single unique alternative.\n    /// <p>\n    /// In some cases, the unique alternative identified by LL prediction is not\n    /// equal to the minimum represented alternative in the conflicting SLL\n    /// configuration set. Grammars and inputs which result in this scenario are\n    /// unable to use\n    /// <see cref=\"PredictionMode.SLL\"/>\n    /// , which in turn means they cannot use\n    /// the two-stage parsing strategy to improve parsing performance for that\n    /// input.</p>\n    /// </remarks>\n    /// <seealso cref=\"ParserATNSimulator.ReportContextSensitivity(Dfa.DFA, int, ATNConfigSet, int, int)\"/>\n    /// <seealso cref=\"Antlr4.Runtime.IParserErrorListener.ReportContextSensitivity(Antlr4.Runtime.Parser, Antlr4.Runtime.Dfa.DFA, int, int, int, SimulatorState)\"/>\n    /// <since>4.3</since>\n    public class ContextSensitivityInfo : DecisionEventInfo\n    {\n        /// <summary>\n        /// Constructs a new instance of the\n        /// <see cref=\"ContextSensitivityInfo\"/>\n        /// class\n        /// with the specified detailed context sensitivity information.\n        /// </summary>\n        /// <param name=\"decision\">The decision number</param>\n        /// <param name=\"configs\">The final configuration set identifying the ambiguous\n        /// alternatives for the current input\n        /// </param>\n        /// <param name=\"input\">The input token stream</param>\n        /// <param name=\"startIndex\">The start index for the current prediction</param>\n        /// <param name=\"stopIndex\">\n        /// The index at which the context sensitivity was\n        /// identified during full-context prediction\n        /// </param>\n        public ContextSensitivityInfo(int decision, ATNConfigSet configs, ITokenStream input, int startIndex, int stopIndex)\n            : base(decision, configs, input, startIndex, stopIndex, true)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/DecisionEventInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// This is the base class for gathering detailed information about prediction\n    /// events which occur during parsing.\n    /// </summary>\n    /// <remarks>\n    /// This is the base class for gathering detailed information about prediction\n    /// events which occur during parsing.\n    /// </remarks>\n    /// <since>4.3</since>\n    public class DecisionEventInfo\n    {\n        /// <summary>The invoked decision number which this event is related to.</summary>\n        /// <remarks>The invoked decision number which this event is related to.</remarks>\n        /// <seealso cref=\"ATN.decisionToState\"/>\n        public readonly int decision;\n\n        /// <summary>The configuration set containing additional information relevant to the\n        /// prediction state when the current event occurred, or {@code null} if no\n        /// additional information is relevant or available.</summary>\n        /// <remarks>The configuration set containing additional information relevant to the\n        /// prediction state when the current event occurred, or {@code null} if no\n        /// additional information is relevant or available.</remarks>\n        public readonly ATNConfigSet configs;\n\n        /// <summary>The input token stream which is being parsed.</summary>\n        /// <remarks>The input token stream which is being parsed.</remarks>\n        [NotNull]\n        public readonly ITokenStream input;\n\n        /// <summary>\n        /// The token index in the input stream at which the current prediction was\n        /// originally invoked.\n        /// </summary>\n        /// <remarks>\n        /// The token index in the input stream at which the current prediction was\n        /// originally invoked.\n        /// </remarks>\n        public readonly int startIndex;\n\n        /// <summary>The token index in the input stream at which the current event occurred.</summary>\n        /// <remarks>The token index in the input stream at which the current event occurred.</remarks>\n        public readonly int stopIndex;\n\n        /// <summary>\n        /// <see langword=\"true\"/>\n        /// if the current event occurred during LL prediction;\n        /// otherwise,\n        /// <see langword=\"false\"/>\n        /// if the input occurred during SLL prediction.\n        /// </summary>\n        public readonly bool fullCtx;\n\n        public DecisionEventInfo(int decision,\n            ATNConfigSet configs,\n            ITokenStream input, int startIndex, int stopIndex,\n            bool fullCtx)\n        {\n            this.decision = decision;\n            this.fullCtx = fullCtx;\n            this.stopIndex = stopIndex;\n            this.input = input;\n            this.startIndex = startIndex;\n            this.configs = configs;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/DecisionInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Sharpen;\n\n\nnamespace Antlr4.Runtime.Atn\n{\n\t/// <summary>This class contains profiling gathered for a particular decision.</summary>\n\t/// <remarks>\n\t/// This class contains profiling gathered for a particular decision.\n\t/// <p>\n\t/// Parsing performance in ANTLR 4 is heavily influenced by both static factors\n\t/// (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the\n\t/// choice of input and the state of the DFA cache at the time profiling\n\t/// operations are started). For best results, gather and use aggregate\n\t/// statistics from a large sample of inputs representing the inputs expected in\n\t/// production before using the results to make changes in the grammar.</p>\n\t/// </remarks>\n\t/// <since>4.3</since>\n\tpublic class DecisionInfo\n\t{\n\n\t\t/**\n\t\t * The decision number, which is an index into {@link ATN#decisionToState}.\n\t\t */\n\t\tpublic readonly int decision;\n\n\t\t/**\n\t\t * The total number of times {@link ParserATNSimulator#adaptivePredict} was\n\t\t * invoked for this decision.\n\t\t */\n\t\tpublic long invocations;\n\n\t\t/**\n\t\t * The total time spent in {@link ParserATNSimulator#adaptivePredict} for\n\t\t * this decision, in nanoseconds.\n\t\t *\n\t\t * <p>\n\t\t * The value of this field contains the sum of differential results obtained\n\t\t * by {@link System#nanoTime()}, and is not adjusted to compensate for JIT\n\t\t * and/or garbage collection overhead. For best accuracy, use a modern JVM\n\t\t * implementation that provides precise results from\n\t\t * {@link System#nanoTime()}, and perform profiling in a separate process\n\t\t * which is warmed up by parsing the input prior to profiling. If desired,\n\t\t * call {@link ATNSimulator#clearDFA} to reset the DFA cache to its initial\n\t\t * state before starting the profiling measurement pass.</p>\n\t\t */\n\t\tpublic long timeInPrediction;\n\n\t\t/**\n\t\t * The sum of the lookahead required for SLL prediction for this decision.\n\t\t * Note that SLL prediction is used before LL prediction for performance\n\t\t * reasons even when {@link PredictionMode#LL} or\n\t\t * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used.\n\t\t */\n\t\tpublic long SLL_TotalLook;\n\n\t\t/**\n\t\t * Gets the minimum lookahead required for any single SLL prediction to\n\t\t * complete for this decision, by reaching a unique prediction, reaching an\n\t\t * SLL conflict state, or encountering a syntax error.\n\t\t */\n\t\tpublic long SLL_MinLook;\n\n\t\t/**\n\t\t * Gets the maximum lookahead required for any single SLL prediction to\n\t\t * complete for this decision, by reaching a unique prediction, reaching an\n\t\t * SLL conflict state, or encountering a syntax error.\n\t\t */\n\t\tpublic long SLL_MaxLook;\n\n\t\t/**\n\t\t * Gets the {@link LookaheadEventInfo} associated with the event where the\n\t\t * {@link #SLL_MaxLook} value was set.\n\t\t */\n\t\tpublic LookaheadEventInfo SLL_MaxLookEvent;\n\n\t\t/**\n\t\t * The sum of the lookahead required for LL prediction for this decision.\n\t\t * Note that LL prediction is only used when SLL prediction reaches a\n\t\t * conflict state.\n\t\t */\n\t\tpublic long LL_TotalLook;\n\n\t\t/**\n\t\t * Gets the minimum lookahead required for any single LL prediction to\n\t\t * complete for this decision. An LL prediction completes when the algorithm\n\t\t * reaches a unique prediction, a conflict state (for\n\t\t * {@link PredictionMode#LL}, an ambiguity state (for\n\t\t * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error.\n\t\t */\n\t\tpublic long LL_MinLook;\n\n\t\t/**\n\t\t * Gets the maximum lookahead required for any single LL prediction to\n\t\t * complete for this decision. An LL prediction completes when the algorithm\n\t\t * reaches a unique prediction, a conflict state (for\n\t\t * {@link PredictionMode#LL}, an ambiguity state (for\n\t\t * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error.\n\t\t */\n\t\tpublic long LL_MaxLook;\n\n\t\t/**\n\t\t * Gets the {@link LookaheadEventInfo} associated with the event where the\n\t\t * {@link #LL_MaxLook} value was set.\n\t\t */\n\t\tpublic LookaheadEventInfo LL_MaxLookEvent;\n\n\t\t/**\n\t\t * A collection of {@link ContextSensitivityInfo} instances describing the\n\t\t * context sensitivities encountered during LL prediction for this decision.\n\t\t *\n\t\t * @see ContextSensitivityInfo\n\t\t */\n\t\tpublic readonly List<ContextSensitivityInfo> contextSensitivities = new List<ContextSensitivityInfo>();\n\n\t\t/**\n\t\t * A collection of {@link ErrorInfo} instances describing the parse errors\n\t\t * identified during calls to {@link ParserATNSimulator#adaptivePredict} for\n\t\t * this decision.\n\t\t *\n\t\t * @see ErrorInfo\n\t\t */\n\t\tpublic readonly List<ErrorInfo> errors = new List<ErrorInfo>();\n\n\t\t/**\n\t\t * A collection of {@link AmbiguityInfo} instances describing the\n\t\t * ambiguities encountered during LL prediction for this decision.\n\t\t *\n\t\t * @see AmbiguityInfo\n\t\t */\n\t\tpublic readonly List<AmbiguityInfo> ambiguities = new List<AmbiguityInfo>();\n\n\t\t/**\n\t\t * A collection of {@link PredicateEvalInfo} instances describing the\n\t\t * results of evaluating individual predicates during prediction for this\n\t\t * decision.\n\t\t *\n\t\t * @see PredicateEvalInfo\n\t\t */\n\t\tpublic readonly List<PredicateEvalInfo> predicateEvals = new List<PredicateEvalInfo>();\n\n\t\t/**\n\t\t * The total number of ATN transitions required during SLL prediction for\n\t\t * this decision. An ATN transition is determined by the number of times the\n\t\t * DFA does not contain an edge that is required for prediction, resulting\n\t\t * in on-the-fly computation of that edge.\n\t\t *\n\t\t * <p>\n\t\t * If DFA caching of SLL transitions is employed by the implementation, ATN\n\t\t * computation may cache the computed edge for efficient lookup during\n\t\t * future parsing of this decision. Otherwise, the SLL parsing algorithm\n\t\t * will use ATN transitions exclusively.</p>\n\t\t *\n\t\t * @see #SLL_ATNTransitions\n\t\t * @see ParserATNSimulator#computeTargetState\n\t\t * @see LexerATNSimulator#computeTargetState\n\t\t */\n\t\tpublic long SLL_ATNTransitions;\n\n\t\t/**\n\t\t * The total number of DFA transitions required during SLL prediction for\n\t\t * this decision.\n\t\t *\n\t\t * <p>If the ATN simulator implementation does not use DFA caching for SLL\n\t\t * transitions, this value will be 0.</p>\n\t\t *\n\t\t * @see ParserATNSimulator#getExistingTargetState\n\t\t * @see LexerATNSimulator#getExistingTargetState\n\t\t */\n\t\tpublic long SLL_DFATransitions;\n\n\t\t/**\n\t\t * Gets the total number of times SLL prediction completed in a conflict\n\t\t * state, resulting in fallback to LL prediction.\n\t\t *\n\t\t * <p>Note that this value is not related to whether or not\n\t\t * {@link PredictionMode#SLL} may be used successfully with a particular\n\t\t * grammar. If the ambiguity resolution algorithm applied to the SLL\n\t\t * conflicts for this decision produce the same result as LL prediction for\n\t\t * this decision, {@link PredictionMode#SLL} would produce the same overall\n\t\t * parsing result as {@link PredictionMode#LL}.</p>\n\t\t */\n\t\tpublic long LL_Fallback;\n\n\t\t/**\n\t\t * The total number of ATN transitions required during LL prediction for\n\t\t * this decision. An ATN transition is determined by the number of times the\n\t\t * DFA does not contain an edge that is required for prediction, resulting\n\t\t * in on-the-fly computation of that edge.\n\t\t *\n\t\t * <p>\n\t\t * If DFA caching of LL transitions is employed by the implementation, ATN\n\t\t * computation may cache the computed edge for efficient lookup during\n\t\t * future parsing of this decision. Otherwise, the LL parsing algorithm will\n\t\t * use ATN transitions exclusively.</p>\n\t\t *\n\t\t * @see #LL_DFATransitions\n\t\t * @see ParserATNSimulator#computeTargetState\n\t\t * @see LexerATNSimulator#computeTargetState\n\t\t */\n\t\tpublic long LL_ATNTransitions;\n\n\t\t/**\n\t\t * The total number of DFA transitions required during LL prediction for\n\t\t * this decision.\n\t\t *\n\t\t * <p>If the ATN simulator implementation does not use DFA caching for LL\n\t\t * transitions, this value will be 0.</p>\n\t\t *\n\t\t * @see ParserATNSimulator#getExistingTargetState\n\t\t * @see LexerATNSimulator#getExistingTargetState\n\t\t */\n\t\tpublic long LL_DFATransitions;\n\n\t\t/**\n\t\t * Constructs a new instance of the {@link DecisionInfo} class to contain\n\t\t * statistics for a particular decision.\n\t\t *\n\t\t * @param decision The decision number\n\t\t */\n\t\tpublic DecisionInfo(int decision)\n\t\t{\n\t\t\tthis.decision = decision;\n\t\t}\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\treturn \"{\" +\n\t\t\t\t   \"decision=\" + decision +\n\t\t\t\t\t\", contextSensitivities=\" + contextSensitivities.Count +\n\t\t\t\t   \", errors=\" + errors.Count +\n\t\t\t\t   \", ambiguities=\" + ambiguities.Count +\n\t\t\t\t   \", SLL_lookahead=\" + SLL_TotalLook +\n\t\t\t\t   \", SLL_ATNTransitions=\" + SLL_ATNTransitions +\n\t\t\t\t   \", SLL_DFATransitions=\" + SLL_DFATransitions +\n\t\t\t\t   \", LL_Fallback=\" + LL_Fallback +\n\t\t\t\t   \", LL_lookahead=\" + LL_TotalLook +\n\t\t\t\t   \", LL_ATNTransitions=\" + LL_ATNTransitions +\n\t\t\t\t   '}';\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/DecisionState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public abstract class DecisionState : ATNState\n    {\n        public int decision = -1;\n\n        public bool nonGreedy;\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/EmptyPredictionContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\t#pragma warning disable 0659 // 'class' overrides Object.Equals(object o) but does not override Object.GetHashCode()\n    public sealed class EmptyPredictionContext : SingletonPredictionContext\n    {\n        public static readonly EmptyPredictionContext Instance = new EmptyPredictionContext();\n\n        internal EmptyPredictionContext()\n            : base(null, EMPTY_RETURN_STATE)\n        {\n        }\n\n        public override PredictionContext GetParent(int index)\n        {\n            return null;\n        }\n\n        public override int GetReturnState(int index)\n        {\n            return returnState;\n        }\n\n\n        public override int Size\n        {\n            get\n            {\n                return 1;\n            }\n        }\n\n        public override bool IsEmpty\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public override bool Equals(object o)\n        {\n            return this == o;\n        }\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\treturn \"$\";\n\t\t}\n\n\t\tpublic override string[] ToStrings(IRecognizer recognizer, int currentState)\n        {\n            return new string[] { \"[]\" };\n        }\n\n        public override string[] ToStrings(IRecognizer recognizer, PredictionContext stop, int currentState)\n        {\n            return new string[] { \"[]\" };\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/EpsilonTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class EpsilonTransition : Transition\n    {\n        private readonly int outermostPrecedenceReturn;\n\n        public EpsilonTransition(ATNState target)\n            : this(target, -1)\n        {\n        }\n\n        public EpsilonTransition(ATNState target, int outermostPrecedenceReturn)\n            : base(target)\n        {\n            this.outermostPrecedenceReturn = outermostPrecedenceReturn;\n        }\n\n        /// <returns>\n        /// the rule index of a precedence rule for which this transition is\n        /// returning from, where the precedence value is 0; otherwise, -1.\n        /// </returns>\n        /// <seealso cref=\"ATNConfig.IsPrecedenceFilterSuppressed\"/>\n        /// <seealso cref=\"ParserATNSimulator.ApplyPrecedenceFilter(ATNConfigSet)\"/>\n        /// <since>4.4.1</since>\n        public int OutermostPrecedenceReturn\n        {\n            get\n            {\n                return outermostPrecedenceReturn;\n            }\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.EPSILON;\n            }\n        }\n\n        public override bool IsEpsilon\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return false;\n        }\n\n        [return: NotNull]\n        public override string ToString()\n        {\n            return \"epsilon\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ErrorInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// This class represents profiling event information for a syntax error\n    /// identified during prediction.\n    /// </summary>\n    /// <remarks>\n    /// This class represents profiling event information for a syntax error\n    /// identified during prediction. Syntax errors occur when the prediction\n    /// algorithm is unable to identify an alternative which would lead to a\n    /// successful parse.\n    /// </remarks>\n    /// <seealso cref=\"Parser.NotifyErrorListeners(IToken, string, RecognitionException)\"/>\n    /// <seealso cref=\"IAntlrErrorListener{TSymbol}.SyntaxError\"/>\n    /// <since>4.3</since>\n    public class ErrorInfo : DecisionEventInfo\n    {\n        /// <summary>\n        /// Constructs a new instance of the\n        /// <see cref=\"ErrorInfo\"/>\n        /// class with the\n        /// specified detailed syntax error information.\n        /// </summary>\n        /// <param name=\"decision\">The decision number</param>\n        /// <param name=\"configs\">The final configuration set reached during prediction\n        /// prior to reaching the {@link ATNSimulator#ERROR} state\n        /// </param>\n        /// <param name=\"input\">The input token stream</param>\n        /// <param name=\"startIndex\">The start index for the current prediction</param>\n        /// <param name=\"stopIndex\">The index at which the syntax error was identified</param>\n        /// <param name=\"fullCtx\">{@code true} if the syntax error was identified during LL\n        /// prediction; otherwise, {@code false} if the syntax error was identified\n        /// during SLL prediction\n        /// </param>\n        public ErrorInfo(int decision, ATNConfigSet configs, ITokenStream input, int startIndex, int stopIndex, bool fullCtx)\n            : base(decision, configs, input, startIndex, stopIndex, fullCtx)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ILexerAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Represents a single action which can be executed following the successful\n    /// match of a lexer rule.\n    /// </summary>\n    /// <remarks>\n    /// Represents a single action which can be executed following the successful\n    /// match of a lexer rule. Lexer actions are used for both embedded action syntax\n    /// and ANTLR 4's new lexer command syntax.\n    /// </remarks>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public interface ILexerAction\n    {\n        /// <summary>Gets the serialization type of the lexer action.</summary>\n        /// <remarks>Gets the serialization type of the lexer action.</remarks>\n        /// <returns>The serialization type of the lexer action.</returns>\n        [NotNull]\n        LexerActionType ActionType\n        {\n            get;\n        }\n\n        /// <summary>Gets whether the lexer action is position-dependent.</summary>\n        /// <remarks>\n        /// Gets whether the lexer action is position-dependent. Position-dependent\n        /// actions may have different semantics depending on the\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// index at the time the action is executed.\n        /// <p>Many lexer commands, including\n        /// <c>type</c>\n        /// ,\n        /// <c>skip</c>\n        /// , and\n        /// <c>more</c>\n        /// , do not check the input index during their execution.\n        /// Actions like this are position-independent, and may be stored more\n        /// efficiently as part of the\n        /// <see cref=\"LexerATNConfig.lexerActionExecutor\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if the lexer action semantics can be affected by the\n        /// position of the input\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// at the time it is executed;\n        /// otherwise,\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        bool IsPositionDependent\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Execute the lexer action in the context of the specified\n        /// <see cref=\"Antlr4.Runtime.Lexer\"/>\n        /// .\n        /// <p>For position-dependent actions, the input stream must already be\n        /// positioned correctly prior to calling this method.</p>\n        /// </summary>\n        /// <param name=\"lexer\">The lexer instance.</param>\n        void Execute(Lexer lexer);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LL1Analyzer.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public class LL1Analyzer\n    {\n        /** Special value added to the lookahead sets to indicate that we hit\n         *  a predicate during analysis if {@code seeThruPreds==false}.\n         */\n        public const int HitPred = TokenConstants.InvalidType;\n\n        [NotNull]\n        public readonly ATN atn;\n\n        public LL1Analyzer(ATN atn)\n        {\n            this.atn = atn;\n        }\n\n        /**\n      * Calculates the SLL(1) expected lookahead set for each outgoing transition\n      * of an {@link ATNState}. The returned array has one element for each\n      * outgoing transition in {@code s}. If the closure from transition\n      * <em>i</em> leads to a semantic predicate before matching a symbol, the\n      * element at index <em>i</em> of the result will be {@code null}.\n      *\n      * @param s the ATN state\n      * @return the expected symbols for each outgoing transition of {@code s}.\n      */\n        [return: Nullable]\n        public virtual IntervalSet[] GetDecisionLookahead(ATNState s)\n        {\n            //\t\tSystem.out.println(\"LOOK(\"+s.stateNumber+\")\");\n            if (s == null)\n            {\n                return null;\n            }\n            IntervalSet[] look = new IntervalSet[s.NumberOfTransitions];\n            for (int alt = 0; alt < s.NumberOfTransitions; alt++)\n            {\n                look[alt] = new IntervalSet();\n                HashSet<ATNConfig> lookBusy = new HashSet<ATNConfig>();\n                bool seeThruPreds = false;\n                // fail to get lookahead upon pred\n                Look_(s.Transition(alt).target, null, EmptyPredictionContext.Instance, look[alt], lookBusy, new BitSet(), seeThruPreds, false);\n                // Wipe out lookahead for this alternative if we found nothing\n                // or we had a predicate when we !seeThruPreds\n                if (look[alt].Count == 0 || look[alt].Contains(HitPred))\n                {\n                    look[alt] = null;\n                }\n            }\n            return look;\n        }\n\n        /**\n\t * Compute set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t *\n\t * <p>If {@code ctx} is {@code null} and the end of the rule containing\n\t * {@code s} is reached, {@link Token#EPSILON} is added to the result set.\n\t * If {@code ctx} is not {@code null} and the end of the outermost rule is\n\t * reached, {@link Token#EOF} is added to the result set.</p>\n\t *\n\t * @param s the ATN state\n\t * @param ctx the complete parser context, or {@code null} if the context\n\t * should be ignored\n\t *\n\t * @return The set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t */\n        [return: NotNull]\n        public virtual IntervalSet Look(ATNState s, RuleContext ctx)\n        {\n            return Look(s, null, ctx);\n        }\n\n        /**\n\t * Compute set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t *\n\t * <p>If {@code ctx} is {@code null} and the end of the rule containing\n\t * {@code s} is reached, {@link Token#EPSILON} is added to the result set.\n\t * If {@code ctx} is not {@code null} and the end of the outermost rule is\n\t * reached, {@link Token#EOF} is added to the result set.</p>\n\t *\n\t * @param s the ATN state\n\t * @param stopState the ATN state to stop at. This can be a\n\t * {@link BlockEndState} to detect epsilon paths through a closure.\n\t * @param ctx the complete parser context, or {@code null} if the context\n\t * should be ignored\n\t *\n\t * @return The set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t */\n        [return: NotNull]\n        public virtual IntervalSet Look(ATNState s, ATNState stopState, RuleContext ctx)\n        {\n            IntervalSet r = new IntervalSet();\n            bool seeThruPreds = true;\n            PredictionContext lookContext = ctx != null ? PredictionContext.FromRuleContext(s.atn, ctx) : null;\n            Look_(s, stopState, lookContext, r, new HashSet<ATNConfig>(), new BitSet(), seeThruPreds, true);\n            return r;\n        }\n\n        /**\n         * Compute set of tokens that can follow {@code s} in the ATN in the\n         * specified {@code ctx}.\n         *\n         * <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the\n         * rule containing {@code s} is reached, {@link Token#EPSILON} is added to\n         * the result set. If {@code ctx} is not {@code null} and {@code addEOF} is\n         * {@code true} and {@code stopState} or the end of the outermost rule is\n         * reached, {@link Token#EOF} is added to the result set.</p>\n         *\n         * @param s the ATN state.\n         * @param stopState the ATN state to stop at. This can be a\n         * {@link BlockEndState} to detect epsilon paths through a closure.\n         * @param ctx The outer context, or {@code null} if the outer context should\n         * not be used.\n         * @param look The result lookahead set.\n         * @param lookBusy A set used for preventing epsilon closures in the ATN\n         * from causing a stack overflow. Outside code should pass\n         * {@code new HashSet<ATNConfig>} for this argument.\n         * @param calledRuleStack A set used for preventing left recursion in the\n         * ATN from causing a stack overflow. Outside code should pass\n         * {@code new BitSet()} for this argument.\n         * @param seeThruPreds {@code true} to true semantic predicates as\n         * implicitly {@code true} and \"see through them\", otherwise {@code false}\n         * to treat semantic predicates as opaque and add {@link #HIT_PRED} to the\n         * result if one is encountered.\n         * @param addEOF Add {@link Token#EOF} to the result if the end of the\n         * outermost context is reached. This parameter has no effect if {@code ctx}\n         * is {@code null}.\n         */\n        protected internal virtual void Look_(ATNState s, ATNState stopState, PredictionContext ctx, IntervalSet look, HashSet<ATNConfig> lookBusy, BitSet calledRuleStack, bool seeThruPreds, bool addEOF)\n        {\n            ATNConfig c = new ATNConfig(s, 0, ctx);\n            if (!lookBusy.Add(c))\n            {\n                return;\n            }\n            if (s == stopState)\n            {\n                if (ctx == null)\n                {\n                    look.Add(TokenConstants.EPSILON);\n                    return;\n                }\n                else if (ctx.IsEmpty && addEOF)\n                {\n                    look.Add(TokenConstants.EOF);\n                    return;\n                }\n            }\n            if (s is RuleStopState)\n            {\n                if (ctx == null)\n                {\n                    look.Add(TokenConstants.EPSILON);\n                    return;\n                }\n                else if (ctx.IsEmpty && addEOF)\n                {\n                    look.Add(TokenConstants.EOF);\n                    return;\n                }\n                if (ctx != EmptyPredictionContext.Instance)\n                {\n                    bool removed = calledRuleStack.Get(s.ruleIndex);\n                    try\n                    {\n                        calledRuleStack.Clear(s.ruleIndex);\n                        for (int i = 0; i < ctx.Size; i++)\n                        {\n                            ATNState returnState = atn.states[ctx.GetReturnState(i)];\n                            Look_(returnState, stopState, ctx.GetParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n                        }\n                    }\n                    finally\n                    {\n                        if (removed)\n                        {\n                            calledRuleStack.Set(s.ruleIndex);\n                        }\n                    }\n                    return;\n                }\n            }\n            int n = s.NumberOfTransitions;\n            for (int i_1 = 0; i_1 < n; i_1++)\n            {\n                Transition t = s.Transition(i_1);\n                if (t.GetType() == typeof(RuleTransition))\n                {\n                    RuleTransition ruleTransition = (RuleTransition)t;\n                    if (calledRuleStack.Get(ruleTransition.ruleIndex))\n                    {\n                        continue;\n                    }\n                    PredictionContext newContext = SingletonPredictionContext.Create(ctx, ruleTransition.followState.stateNumber);\n                    try\n                    {\n                        calledRuleStack.Set(ruleTransition.target.ruleIndex);\n                        Look_(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n                    }\n                    finally\n                    {\n                        calledRuleStack.Clear(ruleTransition.target.ruleIndex);\n                    }\n                }\n                else if (t is AbstractPredicateTransition)\n                {\n                    if (seeThruPreds)\n                    {\n                        Look_(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n                    }\n                    else\n                    {\n                        look.Add(HitPred);\n                    }\n                }\n                else if (t.IsEpsilon)\n                {\n                    Look_(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n                }\n                else if (t.GetType() == typeof(WildcardTransition))\n                {\n                    look.AddAll(IntervalSet.Of(TokenConstants.MinUserTokenType, atn.maxTokenType));\n                }\n                else\n                {\n                    IntervalSet set = t.Label;\n                    if (set != null)\n                    {\n                        if (t is NotSetTransition)\n                        {\n                            set = set.Complement(IntervalSet.Of(TokenConstants.MinUserTokenType, atn.maxTokenType));\n                        }\n                        look.AddAll(set);\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerATNConfig.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Atn\n{\n\tpublic class LexerATNConfig : ATNConfig\n\t{\n\n\t\t/**\n\t\t * This is the backing field for {@link #getLexerActionExecutor}.\n\t\t */\n\t\tprivate readonly LexerActionExecutor lexerActionExecutor;\n\n\t\tprivate readonly bool passedThroughNonGreedyDecision;\n\n\t\tpublic LexerATNConfig(ATNState state,\n\t\t\t\t\t\t\t  int alt,\n\t\t\t\t\t\t\t  PredictionContext context)\n\t\t\t\t: base(state, alt, context/*, SemanticContext.Empty.Instance*/) // TODO\n\t\t{\n\t\t\tthis.passedThroughNonGreedyDecision = false;\n\t\t\tthis.lexerActionExecutor = null;\n\t\t}\n\n\t\tpublic LexerATNConfig(ATNState state,\n\t\t\t\t\t\t\t  int alt,\n\t\t\t\t\t\t\t  PredictionContext context,\n\t\t\t\t\t\t\t  LexerActionExecutor lexerActionExecutor)\n\t\t\t: base(state, alt, context, SemanticContext.Empty.Instance)\n\t\t{\n\t\t\tthis.lexerActionExecutor = lexerActionExecutor;\n\t\t\tthis.passedThroughNonGreedyDecision = false;\n\t\t}\n\n\t\tpublic LexerATNConfig(LexerATNConfig c, ATNState state)\n\t\t\t: base(c, state, c.context, c.semanticContext)\n\t\t{\n\t\t\tthis.lexerActionExecutor = c.lexerActionExecutor;\n\t\t\tthis.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state);\n\t\t}\n\n\t\tpublic LexerATNConfig(LexerATNConfig c, ATNState state,\n\t\t\t\t\t\t\t  LexerActionExecutor lexerActionExecutor)\n\t\t\t: base(c, state, c.context, c.semanticContext)\n\t\t{\n\t\t\tthis.lexerActionExecutor = lexerActionExecutor;\n\t\t\tthis.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state);\n\t\t}\n\n\t\tpublic LexerATNConfig(LexerATNConfig c, ATNState state,\n\t\t\t\t\t\t\t  PredictionContext context)\n\t\t\t: base(c, state, context, c.semanticContext)\n\t\t{\n\t\t\tthis.lexerActionExecutor = c.lexerActionExecutor;\n\t\t\tthis.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state);\n\t\t}\n\n\t\t/**\n\t\t * Gets the {@link LexerActionExecutor} capable of executing the embedded\n\t\t * action(s) for the current configuration.\n\t\t */\n\t\tpublic LexerActionExecutor getLexerActionExecutor()\n\t\t{\n\t\t\treturn lexerActionExecutor;\n\t\t}\n\n\t\tpublic bool hasPassedThroughNonGreedyDecision()\n\t\t{\n\t\t\treturn passedThroughNonGreedyDecision;\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\tint hashCode = MurmurHash.Initialize(7);\n\t\t\thashCode = MurmurHash.Update(hashCode, state.stateNumber);\n\t\t\thashCode = MurmurHash.Update(hashCode, alt);\n\t\t\thashCode = MurmurHash.Update(hashCode, context);\n\t\t\thashCode = MurmurHash.Update(hashCode, semanticContext);\n\t\t\thashCode = MurmurHash.Update(hashCode, passedThroughNonGreedyDecision ? 1 : 0);\n\t\t\thashCode = MurmurHash.Update(hashCode, lexerActionExecutor);\n\t\t\thashCode = MurmurHash.Finish(hashCode, 6);\n\t\t\treturn hashCode;\n\t\t}\n\n\t\tpublic override bool Equals(ATNConfig other)\n\t\t{\n\t\t\tif (this == other)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (!(other is LexerATNConfig))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tLexerATNConfig lexerOther = (LexerATNConfig)other;\n\t\t\tif (passedThroughNonGreedyDecision != lexerOther.passedThroughNonGreedyDecision)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!(lexerActionExecutor==null ? lexerOther.lexerActionExecutor==null : lexerActionExecutor.Equals(lexerOther.lexerActionExecutor)))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn base.Equals(other);\n\t\t}\n\n\t\tprivate static bool checkNonGreedyDecision(LexerATNConfig source, ATNState target)\n\t\t{\n\t\t\treturn source.passedThroughNonGreedyDecision\n\t\t\t\t|| target is DecisionState && ((DecisionState)target).nonGreedy;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerATNSimulator.cs",
    "content": "/*\n/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Atn\n{\n\t/// <summary>\"dup\" of ParserInterpreter</summary>\n\tpublic class LexerATNSimulator : ATNSimulator\n\t{\n\t\tpublic readonly bool debug = false;\n\n\t\tpublic readonly bool dfa_debug = false;\n\n\n\t\tpublic static readonly int MIN_DFA_EDGE = 0;\n\t\tpublic static readonly int MAX_DFA_EDGE = 127; // forces unicode to stay in ATN\n\n\n\n\t\tprotected readonly Lexer recog;\n\n\t\t/** The current token's starting index into the character stream.\n\t\t *  Shared across DFA to ATN simulation in case the ATN fails and the\n\t\t *  DFA did not have a previous accept state. In this case, we use the\n\t\t *  ATN-generated exception object.\n\t\t */\n\t\tprotected int startIndex = -1;\n\n\t\t/** line number 1..n within the input */\n\t\tprotected int thisLine = 1;\n\n\t\t/** The index of the character relative to the beginning of the line 0..n-1 */\n\t\tprotected int charPositionInLine = 0;\n\n\n\t\tpublic readonly DFA[] decisionToDFA;\n\t\tprotected int mode = Lexer.DEFAULT_MODE;\n\n\t\t/** Used during DFA/ATN exec to record the most recent accept configuration info */\n\n\t\treadonly SimState prevAccept = new SimState();\n\n\t\tpublic LexerATNSimulator(ATN atn, DFA[] decisionToDFA,\n\t\t\t\t\t\t\t\t PredictionContextCache sharedContextCache)\n\t\t\t: this(null, atn, decisionToDFA, sharedContextCache)\n\t\t{\n\t\t}\n\n\t\tpublic LexerATNSimulator(Lexer recog, ATN atn,\n\t\t\t\t\t\t\t\t DFA[] decisionToDFA,\n\t\t\t\t\t\t\t\t PredictionContextCache sharedContextCache)\n\t\t\t: base(atn, sharedContextCache)\n\t\t{\n\t\t\tthis.decisionToDFA = decisionToDFA;\n\t\t\tthis.recog = recog;\n\t\t}\n\n\n\n        public void CopyState(LexerATNSimulator simulator)\n\t\t{\n\t\t\tthis.charPositionInLine = simulator.charPositionInLine;\n\t\t\tthis.thisLine = simulator.thisLine;\n\t\t\tthis.mode = simulator.mode;\n\t\t\tthis.startIndex = simulator.startIndex;\n\t\t}\n\n\t\tpublic int Match(ICharStream input, int mode)\n\t\t{\n\t\t\tthis.mode = mode;\n\t\t\tint mark = input.Mark();\n\t\t\ttry\n\t\t\t{\n\t\t\t\tthis.startIndex = input.Index;\n\t\t\t\tthis.prevAccept.Reset();\n\t\t\t\tDFA dfa = decisionToDFA[mode];\n\t\t\t\tif (dfa.s0 == null)\n\t\t\t\t{\n\t\t\t\t\treturn MatchATN(input);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn ExecATN(input, dfa.s0);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tinput.Release(mark);\n\t\t\t}\n\t\t}\n\n\t\tpublic override void Reset()\n\t\t{\n\t\t\tprevAccept.Reset();\n\t\t\tstartIndex = -1;\n\t\t\tthisLine = 1;\n\t\t\tcharPositionInLine = 0;\n\t\t\tmode = Lexer.DEFAULT_MODE;\n\t\t}\n\n\t\tpublic override void ClearDFA()\n\t\t{\n\t\t\tfor (int d = 0; d < decisionToDFA.Length; d++)\n\t\t\t{\n\t\t\t\tdecisionToDFA[d] = new DFA(atn.GetDecisionState(d), d);\n\t\t\t}\n\t\t}\n\n\t\tprotected int MatchATN(ICharStream input)\n\t\t{\n\t\t\tATNState startState = atn.modeToStartState[mode];\n            if (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"matchATN mode \" + mode + \" start: \" + startState);\n\t\t\t}\n            int old_mode = mode;\n\n\t\t\tATNConfigSet s0_closure = ComputeStartState(input, startState);\n\t\t\tbool suppressEdge = s0_closure.hasSemanticContext;\n\t\t\ts0_closure.hasSemanticContext = false;\n\n\t\t\tDFAState next = AddDFAState(s0_closure);\n\t\t\tif (!suppressEdge)\n\t\t\t{\n\t\t\t\tdecisionToDFA[mode].s0 = next;\n\t\t\t}\n\n\t\t\tint predict = ExecATN(input, next);\n            if (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"DFA after matchATN: \" + decisionToDFA[old_mode].ToString());\n\t\t\t}\n            return predict;\n\t\t}\n\n\t\tprotected int ExecATN(ICharStream input, DFAState ds0)\n\t\t{\n            //System.out.println(\"enter exec index \"+input.index()+\" from \"+ds0.configs);\n            if (debug)\n            {\n                Console.WriteLine(\"start state closure=\" + ds0.configSet);\n\t\t\t}\n            if (ds0.isAcceptState)\n\t\t\t{\n\t\t\t\t// allow zero-length tokens\n\t\t\t\tCaptureSimState(prevAccept, input, ds0);\n\t\t\t}\n\n\t\t\tint t = input.LA(1);\n\n\t\t\tDFAState s = ds0; // s is current/from DFA state\n\n\t\t\twhile (true)\n\t\t\t{ // while more work\n                if (debug)\n                {\n                    Console.WriteLine(\"execATN loop starting closure: \" + s.configSet);\n\t\t\t\t}\n                // As we move src->trg, src->trg, we keep track of the previous trg to\n                // avoid looking up the DFA state again, which is expensive.\n                // If the previous target was already part of the DFA, we might\n                // be able to avoid doing a reach operation upon t. If s!=null,\n                // it means that semantic predicates didn't prevent us from\n                // creating a DFA state. Once we know s!=null, we check to see if\n                // the DFA state has an edge already for t. If so, we can just reuse\n                // it's configuration set; there's no point in re-computing it.\n                // This is kind of like doing DFA simulation within the ATN\n                // simulation because DFA simulation is really just a way to avoid\n                // computing reach/closure sets. Technically, once we know that\n                // we have a previously added DFA state, we could jump over to\n                // the DFA simulator. But, that would mean popping back and forth\n                // a lot and making things more complicated algorithmically.\n                // This optimization makes a lot of sense for loops within DFA.\n                // A character will take us back to an existing DFA state\n                // that already has lots of edges out of it. e.g., .* in comments.\n                DFAState target = GetExistingTargetState(s, t);\n\t\t\t\tif (target == null)\n\t\t\t\t{\n\t\t\t\t\ttarget = ComputeTargetState(input, s, t);\n\t\t\t\t}\n\n\t\t\t\tif (target == ERROR)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// If this is a consumable input element, make sure to consume before\n\t\t\t\t// capturing the accept state so the input index, line, and char\n\t\t\t\t// position accurately reflect the state of the interpreter at the\n\t\t\t\t// end of the token.\n\t\t\t\tif (t != IntStreamConstants.EOF)\n\t\t\t\t{\n\t\t\t\t\tConsume(input);\n\t\t\t\t}\n\n\t\t\t\tif (target.isAcceptState)\n\t\t\t\t{\n\t\t\t\t\tCaptureSimState(prevAccept, input, target);\n\t\t\t\t\tif (t == IntStreamConstants.EOF)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tt = input.LA(1);\n\t\t\t\ts = target; // flip; current DFA target becomes new src/from state\n\t\t\t}\n\n\t\t\treturn FailOrAccept(prevAccept, input, s.configSet, t);\n\t\t}\n\n\t\t/**\n\t\t * Get an existing target state for an edge in the DFA. If the target state\n\t\t * for the edge has not yet been computed or is otherwise not available,\n\t\t * this method returns {@code null}.\n\t\t *\n\t\t * @param s The current DFA state\n\t\t * @param t The next input symbol\n\t\t * @return The existing target DFA state for the given input symbol\n\t\t * {@code t}, or {@code null} if the target state for this edge is not\n\t\t * already cached\n\t\t */\n\n\t\tprotected DFAState GetExistingTargetState(DFAState s, int t)\n\t\t{\n\t\t\tif (s.edges == null || t < MIN_DFA_EDGE || t > MAX_DFA_EDGE)\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tDFAState target = s.edges[t - MIN_DFA_EDGE];\n\t\t\tif (debug && target != null)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"reuse state \" + s.stateNumber + \" edge to \" + target.stateNumber);\n\t\t\t}\n\n\t\t\treturn target;\n\t\t}\n\n\t\t/**\n\t\t * Compute a target state for an edge in the DFA, and attempt to add the\n\t\t * computed state and corresponding edge to the DFA.\n\t\t *\n\t\t * @param input The input stream\n\t\t * @param s The current DFA state\n\t\t * @param t The next input symbol\n\t\t *\n\t\t * @return The computed target DFA state for the given input symbol\n\t\t * {@code t}. If {@code t} does not lead to a valid DFA state, this method\n\t\t * returns {@link #ERROR}.\n\t\t */\n\n\t\tprotected DFAState ComputeTargetState(ICharStream input, DFAState s, int t)\n\t\t{\n\t\t\tATNConfigSet reach = new OrderedATNConfigSet();\n\n\t\t\t// if we don't find an existing DFA state\n\t\t\t// Fill reach starting from closure, following t transitions\n\t\t\tGetReachableConfigSet(input, s.configSet, reach, t);\n\n\t\t\tif (reach.Empty)\n\t\t\t{ // we got nowhere on t from s\n\t\t\t\tif (!reach.hasSemanticContext)\n\t\t\t\t{\n\t\t\t\t\t// we got nowhere on t, don't throw out this knowledge; it'd\n\t\t\t\t\t// cause a failover from DFA later.\n\t\t\t\t\tAddDFAEdge(s, t, ERROR);\n\t\t\t\t}\n\n\t\t\t\t// stop when we can't match any more char\n\t\t\t\treturn ERROR;\n\t\t\t}\n\n\t\t\t// Add an edge from s to target DFA found/created for reach\n\t\t\treturn AddDFAEdge(s, t, reach);\n\t\t}\n\n\t\tprotected int FailOrAccept(SimState prevAccept, ICharStream input,\n\t\t\t\t\t\t\t\t   ATNConfigSet reach, int t)\n\t\t{\n\t\t\tif (prevAccept.dfaState != null)\n\t\t\t{\n\t\t\t\tLexerActionExecutor lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor;\n\t\t\t\tAccept(input, lexerActionExecutor, startIndex,\n\t\t\t\t\tprevAccept.index, prevAccept.line, prevAccept.charPos);\n\t\t\t\treturn prevAccept.dfaState.prediction;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// if no accept and EOF is first char, return EOF\n\t\t\t\tif (t == IntStreamConstants.EOF && input.Index == startIndex)\n\t\t\t\t{\n\t\t\t\t\treturn TokenConstants.EOF;\n\t\t\t\t}\n\n\t\t\t\tthrow new LexerNoViableAltException(recog, input, startIndex, reach);\n\t\t\t}\n\t\t}\n\n\t\t/** Given a starting configuration set, figure out all ATN configurations\n\t\t *  we can reach upon input {@code t}. Parameter {@code reach} is a return\n\t\t *  parameter.\n\t\t */\n\t\tprotected void GetReachableConfigSet(ICharStream input, ATNConfigSet closure, ATNConfigSet reach, int t)\n\t\t{\n\t\t\t// this is used to skip processing for configs which have a lower priority\n\t\t\t// than a config that already reached an accept state for the same rule\n\t\t\tint skipAlt = ATN.INVALID_ALT_NUMBER;\n\t\t\tforeach (ATNConfig c in closure.configs)\n\t\t\t{\n\t\t\t\tbool currentAltReachedAcceptState = c.alt == skipAlt;\n\t\t\t\tif (currentAltReachedAcceptState && ((LexerATNConfig)c).hasPassedThroughNonGreedyDecision())\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (debug)\n\t\t\t\t{\n\t\t\t\t\tConsole.WriteLine(\"testing \" + GetTokenName(t) + \" at \" + c.ToString(recog, true));\n\t\t\t\t}\n\n\t\t\t\tint n = c.state.NumberOfTransitions;\n\t\t\t\tfor (int ti = 0; ti < n; ti++)\n\t\t\t\t{               // for each transition\n\t\t\t\t\tTransition trans = c.state.Transition(ti);\n\t\t\t\t\tATNState target = GetReachableTarget(trans, t);\n\t\t\t\t\tif (target != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tLexerActionExecutor lexerActionExecutor = ((LexerATNConfig)c).getLexerActionExecutor();\n\t\t\t\t\t\tif (lexerActionExecutor != null)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlexerActionExecutor = lexerActionExecutor.FixOffsetBeforeMatch(input.Index - startIndex);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbool treatEofAsEpsilon = t == IntStreamConstants.EOF;\n\t\t\t\t\t\tif (Closure(input, new LexerATNConfig((LexerATNConfig)c, target, lexerActionExecutor), reach, currentAltReachedAcceptState, true, treatEofAsEpsilon))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// any remaining configs for this alt have a lower priority than\n\t\t\t\t\t\t\t// the one that just reached an accept state.\n\t\t\t\t\t\t\tskipAlt = c.alt;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprotected void Accept(ICharStream input, LexerActionExecutor lexerActionExecutor,\n\t\t\t\t\t\t\t  int startIndex, int index, int line, int charPos)\n\t\t{\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"ACTION \" + lexerActionExecutor);\n\t\t\t}\n\n\t\t\t// seek to after last char in token\n\t\t\tinput.Seek(index);\n\t\t\tthis.thisLine = line;\n\t\t\tthis.charPositionInLine = charPos;\n\n\t\t\tif (lexerActionExecutor != null && recog != null)\n\t\t\t{\n\t\t\t\tlexerActionExecutor.Execute(recog, input, startIndex);\n\t\t\t}\n\t\t}\n\n\n\t\tprotected ATNState GetReachableTarget(Transition trans, int t)\n\t\t{\n\t\t\tif (trans.Matches(t, Lexer.MinCharValue, Lexer.MaxCharValue))\n\t\t\t{\n\t\t\t\treturn trans.target;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\n\t\tprotected ATNConfigSet ComputeStartState(ICharStream input,\n\t\t\t\t\t\t\t\t\t\t\t\t ATNState p)\n\t\t{\n\t\t\tPredictionContext initialContext = EmptyPredictionContext.Instance;\n\t\t\tATNConfigSet configs = new OrderedATNConfigSet();\n\t\t\tfor (int i = 0; i < p.NumberOfTransitions; i++)\n\t\t\t{\n\t\t\t\tATNState target = p.Transition(i).target;\n\t\t\t\tLexerATNConfig c = new LexerATNConfig(target, i + 1, initialContext);\n\t\t\t\tClosure(input, c, configs, false, false, false);\n\t\t\t}\n\t\t\treturn configs;\n\t\t}\n\n\t\t/**\n\t\t * Since the alternatives within any lexer decision are ordered by\n\t\t * preference, this method stops pursuing the closure as soon as an accept\n\t\t * state is reached. After the first accept state is reached by depth-first\n\t\t * search from {@code config}, all other (potentially reachable) states for\n\t\t * this rule would have a lower priority.\n\t\t *\n\t\t * @return {@code true} if an accept state is reached, otherwise\n\t\t * {@code false}.\n\t\t */\n\t\tprotected bool Closure(ICharStream input, LexerATNConfig config, ATNConfigSet configs, bool currentAltReachedAcceptState, bool speculative, bool treatEofAsEpsilon)\n\t\t{\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"closure(\" + config.ToString(recog, true) + \")\");\n\t\t\t}\n\n\t\t\tif (config.state is RuleStopState)\n\t\t\t{\n\t\t\t\tif (debug)\n\t\t\t\t{\n\t\t\t\t\tif (recog != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tConsole.WriteLine(\"closure at \" + recog.RuleNames[config.state.ruleIndex] + \" rule stop \" + config);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tConsole.WriteLine(\"closure at rule stop \" + config);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (config.context == null || config.context.HasEmptyPath)\n\t\t\t\t{\n\t\t\t\t\tif (config.context == null || config.context.IsEmpty)\n\t\t\t\t\t{\n\t\t\t\t\t\tconfigs.Add(config);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tconfigs.Add(new LexerATNConfig(config, config.state, EmptyPredictionContext.Instance));\n\t\t\t\t\t\tcurrentAltReachedAcceptState = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (config.context != null && !config.context.IsEmpty)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i < config.context.Size; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (config.context.GetReturnState(i) != PredictionContext.EMPTY_RETURN_STATE)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPredictionContext newContext = config.context.GetParent(i); // \"pop\" return state\n\t\t\t\t\t\t\tATNState returnState = atn.states[config.context.GetReturnState(i)];\n\t\t\t\t\t\t\tLexerATNConfig c = new LexerATNConfig(config, returnState, newContext);\n\t\t\t\t\t\t\tcurrentAltReachedAcceptState = Closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn currentAltReachedAcceptState;\n\t\t\t}\n\n\t\t\t// optimization\n\t\t\tif (!config.state.OnlyHasEpsilonTransitions)\n\t\t\t{\n\t\t\t\tif (!currentAltReachedAcceptState || !config.hasPassedThroughNonGreedyDecision())\n\t\t\t\t{\n\t\t\t\t\tconfigs.Add(config);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tATNState p = config.state;\n\t\t\tfor (int i = 0; i < p.NumberOfTransitions; i++)\n\t\t\t{\n\t\t\t\tTransition t = p.Transition(i);\n\t\t\t\tLexerATNConfig c = GetEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon);\n\t\t\t\tif (c != null)\n\t\t\t\t{\n\t\t\t\t\tcurrentAltReachedAcceptState = Closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn currentAltReachedAcceptState;\n\t\t}\n\n\t\t// side-effect: can alter configs.hasSemanticContext\n\n\t\tprotected LexerATNConfig GetEpsilonTarget(ICharStream input,\n\t\t\t\t\t\t\t\t\t\t\t   LexerATNConfig config,\n\t\t\t\t\t\t\t\t\t\t\t   Transition t,\n\t\t\t\t\t\t\t\t\t\t\t   ATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t\t   bool speculative,\n\t\t\t\t\t\t\t\t\t\t\t   bool treatEofAsEpsilon)\n\t\t{\n\t\t\tLexerATNConfig c = null;\n\t\t\tswitch (t.TransitionType)\n\t\t\t{\n\t\t\t\tcase TransitionType.RULE:\n\t\t\t\t\tRuleTransition ruleTransition = (RuleTransition)t;\n\t\t\t\t\tPredictionContext newContext = new SingletonPredictionContext(config.context, ruleTransition.followState.stateNumber);\n\t\t\t\t\tc = new LexerATNConfig(config, t.target, newContext);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TransitionType.PRECEDENCE:\n\t\t\t\t\tthrow new Exception(\"Precedence predicates are not supported in lexers.\");\n\n\t\t\t\tcase TransitionType.PREDICATE:\n\t\t\t\t\t/*  Track traversing semantic predicates. If we traverse,\n\t\t\t\t\t we cannot add a DFA state for this \"reach\" computation\n\t\t\t\t\t because the DFA would not test the predicate again in the\n\t\t\t\t\t future. Rather than creating collections of semantic predicates\n\t\t\t\t\t like v3 and testing them on prediction, v4 will test them on the\n\t\t\t\t\t fly all the time using the ATN not the DFA. This is slower but\n\t\t\t\t\t semantically it's not used that often. One of the key elements to\n\t\t\t\t\t this predicate mechanism is not adding DFA states that see\n\t\t\t\t\t predicates immediately afterwards in the ATN. For example,\n\n\t\t\t\t\t a : ID {p1}? | ID {p2}? ;\n\n\t\t\t\t\t should create the start state for rule 'a' (to save start state\n\t\t\t\t\t competition), but should not create target of ID state. The\n\t\t\t\t\t collection of ATN states the following ID references includes\n\t\t\t\t\t states reached by traversing predicates. Since this is when we\n\t\t\t\t\t test them, we cannot cash the DFA state target of ID.\n\t\t\t\t */\n\t\t\t\t\tPredicateTransition pt = (PredicateTransition)t;\n\t\t\t\t\tif (debug)\n\t\t\t\t\t{\n\t\t\t\t\t\tConsole.WriteLine(\"EVAL rule \" + pt.ruleIndex + \":\" + pt.predIndex);\n\t\t\t\t\t}\n\t\t\t\t\tconfigs.hasSemanticContext = true;\n\t\t\t\t\tif (EvaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative))\n\t\t\t\t\t{\n\t\t\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TransitionType.ACTION:\n\t\t\t\t\tif (config.context == null || config.context.HasEmptyPath)\n\t\t\t\t\t{\n\t\t\t\t\t\t// execute actions anywhere in the start rule for a token.\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// TODO: if the entry rule is invoked recursively, some\n\t\t\t\t\t\t// actions may be executed during the recursive call. The\n\t\t\t\t\t\t// problem can appear when hasEmptyPath() is true but\n\t\t\t\t\t\t// isEmpty() is false. In this case, the config needs to be\n\t\t\t\t\t\t// split into two contexts - one with just the empty path\n\t\t\t\t\t\t// and another with everything but the empty path.\n\t\t\t\t\t\t// Unfortunately, the current algorithm does not allow\n\t\t\t\t\t\t// getEpsilonTarget to return two configurations, so\n\t\t\t\t\t\t// additional modifications are needed before we can support\n\t\t\t\t\t\t// the split operation.\n\t\t\t\t\t\tLexerActionExecutor lexerActionExecutor = LexerActionExecutor.Append(config.getLexerActionExecutor(), atn.lexerActions[((ActionTransition)t).actionIndex]);\n\t\t\t\t\t\tc = new LexerATNConfig(config, t.target, lexerActionExecutor);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// ignore actions in referenced rules\n\t\t\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\tcase TransitionType.EPSILON:\n\t\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TransitionType.ATOM:\n\t\t\t\tcase TransitionType.RANGE:\n\t\t\t\tcase TransitionType.SET:\n\t\t\t\t\tif (treatEofAsEpsilon)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (t.Matches(IntStreamConstants.EOF, Lexer.MinCharValue, Lexer.MaxCharValue))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn c;\n\t\t}\n\n\t\t/**\n\t\t * Evaluate a predicate specified in the lexer.\n\t\t *\n\t\t * <p>If {@code speculative} is {@code true}, this method was called before\n\t\t * {@link #consume} for the matched character. This method should call\n\t\t * {@link #consume} before evaluating the predicate to ensure position\n\t\t * sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine},\n\t\t * and {@link Lexer#getCharPositionInLine}, properly reflect the current\n\t\t * lexer state. This method should restore {@code input} and the simulator\n\t\t * to the original state before returning (i.e. undo the actions made by the\n\t\t * call to {@link #consume}.</p>\n\t\t *\n\t\t * @param input The input stream.\n\t\t * @param ruleIndex The rule containing the predicate.\n\t\t * @param predIndex The index of the predicate within the rule.\n\t\t * @param speculative {@code true} if the current index in {@code input} is\n\t\t * one character before the predicate's location.\n\t\t *\n\t\t * @return {@code true} if the specified predicate evaluates to\n\t\t * {@code true}.\n\t\t */\n\t\tprotected bool EvaluatePredicate(ICharStream input, int ruleIndex, int predIndex, bool speculative)\n\t\t{\n\t\t\t// assume true if no recognizer was provided\n\t\t\tif (recog == null)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif (!speculative)\n\t\t\t{\n\t\t\t\treturn recog.Sempred(null, ruleIndex, predIndex);\n\t\t\t}\n\n\t\t\tint savedCharPositionInLine = charPositionInLine;\n\t\t\tint savedLine = thisLine;\n\t\t\tint index = input.Index;\n\t\t\tint marker = input.Mark();\n\t\t\ttry\n\t\t\t{\n\t\t\t\tConsume(input);\n\t\t\t\treturn recog.Sempred(null, ruleIndex, predIndex);\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tcharPositionInLine = savedCharPositionInLine;\n\t\t\t\tthisLine = savedLine;\n\t\t\t\tinput.Seek(index);\n\t\t\t\tinput.Release(marker);\n\t\t\t}\n\t\t}\n\n\t\tprotected void CaptureSimState(SimState settings,\n\t\t\t\t\t\t\t\t\t   ICharStream input,\n\t\t\t\t\t\t\t\t\t   DFAState dfaState)\n\t\t{\n\t\t\tsettings.index = input.Index;\n\t\t\tsettings.line = thisLine;\n\t\t\tsettings.charPos = charPositionInLine;\n\t\t\tsettings.dfaState = dfaState;\n\t\t}\n\n\n\t\tprotected DFAState AddDFAEdge(DFAState from,\n\t\t\t\t\t\t\t\t\t  int t,\n\t\t\t\t\t\t\t\t\t  ATNConfigSet q)\n\t\t{\n\t\t\t/* leading to this call, ATNConfigSet.hasSemanticContext is used as a\n\t\t\t * marker indicating dynamic predicate evaluation makes this edge\n\t\t\t * dependent on the specific input sequence, so the static edge in the\n\t\t\t * DFA should be omitted. The target DFAState is still created since\n\t\t\t * execATN has the ability to resynchronize with the DFA state cache\n\t\t\t * following the predicate evaluation step.\n\t\t\t *\n\t\t\t * TJP notes: next time through the DFA, we see a pred again and eval.\n\t\t\t * If that gets us to a previously created (but dangling) DFA\n\t\t\t * state, we can continue in pure DFA mode from there.\n\t\t\t */\n\t\t\tbool suppressEdge = q.hasSemanticContext;\n\t\t\tq.hasSemanticContext = false;\n\n\n\t\t\tDFAState to = AddDFAState(q);\n\n\t\t\tif (suppressEdge)\n\t\t\t{\n\t\t\t\treturn to;\n\t\t\t}\n\n\t\t\tAddDFAEdge(from, t, to);\n\t\t\treturn to;\n\t\t}\n\n\t\tprotected void AddDFAEdge(DFAState p, int t, DFAState q)\n\t\t{\n\t\t\tif (t < MIN_DFA_EDGE || t > MAX_DFA_EDGE)\n\t\t\t{\n\t\t\t\t// Only track edges within the DFA bounds\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"EDGE \" + p + \" -> \" + q + \" upon \" + ((char)t));\n\t\t\t}\n\n\t\t\tlock (p)\n\t\t\t{\n\t\t\t\tif (p.edges == null)\n\t\t\t\t{\n\t\t\t\t\t//  make room for tokens 1..n and -1 masquerading as index 0\n\t\t\t\t\tp.edges = new DFAState[MAX_DFA_EDGE - MIN_DFA_EDGE + 1];\n\t\t\t\t}\n\t\t\t\tp.edges[t - MIN_DFA_EDGE] = q; // connect\n\t\t\t}\n\t\t}\n\n\t\t/** Add a new DFA state if there isn't one with this set of\n\t\t\tconfigurations already. This method also detects the first\n\t\t\tconfiguration containing an ATN rule stop state. Later, when\n\t\t\ttraversing the DFA, we will know which rule to accept.\n\t\t */\n\n\t\tprotected DFAState AddDFAState(ATNConfigSet configSet)\n\t\t{\n\t\t\t/* the lexer evaluates predicates on-the-fly; by this point configs\n\t\t\t * should not contain any configurations with unevaluated predicates.\n\t\t\t */\n\t\t\tDFAState proposed = new DFAState(configSet);\n\t\t\tATNConfig firstConfigWithRuleStopState = null;\n\t\t\tforeach (ATNConfig c in configSet.configs)\n\t\t\t{\n\t\t\t\tif (c.state is RuleStopState)\n\t\t\t\t{\n\t\t\t\t\tfirstConfigWithRuleStopState = c;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (firstConfigWithRuleStopState != null)\n\t\t\t{\n\t\t\t\tproposed.isAcceptState = true;\n\t\t\t\tproposed.lexerActionExecutor = ((LexerATNConfig)firstConfigWithRuleStopState).getLexerActionExecutor();\n\t\t\t\tproposed.prediction = atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex];\n\t\t\t}\n\n\t\t\tDFA dfa = decisionToDFA[mode];\n\t\t\tlock (dfa.states)\n\t\t\t{\n\t\t\t\tDFAState existing;\n\t\t\t\tif(dfa.states.TryGetValue(proposed, out existing))\n\t\t\t\t\treturn existing;\n\n\t\t\t\tDFAState newState = proposed;\n\n\t\t\t\tnewState.stateNumber = dfa.states.Count;\n\t\t\t\tconfigSet.IsReadOnly = true;\n\t\t\t\tnewState.configSet = configSet;\n\t\t\t\tdfa.states[newState] = newState;\n\t\t\t\treturn newState;\n\t\t\t}\n\t\t}\n\n\n\t\tpublic DFA GetDFA(int mode)\n\t\t{\n\t\t\treturn decisionToDFA[mode];\n\t\t}\n\n\t\t/** Get the text matched so far for the current token.\n\t\t */\n\n\t\tpublic String GetText(ICharStream input)\n\t\t{\n\t\t\t// index is first lookahead char, don't include.\n\t\t\treturn input.GetText(Interval.Of(startIndex, input.Index - 1));\n\t\t}\n\n\t\tpublic int Line\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn thisLine;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tthis.thisLine = value;\n\t\t\t}\n\t\t}\n\n\t\tpublic int Column\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn charPositionInLine;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tthis.charPositionInLine = value;\n\t\t\t}\n\t\t}\n\n\n\t\tpublic virtual void Consume(ICharStream input)\n\t\t{\n\t\t\tint curChar = input.LA(1);\n\t\t\tif (curChar == '\\n')\n\t\t\t{\n\t\t\t\tthisLine++;\n\t\t\t\tcharPositionInLine = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcharPositionInLine++;\n\t\t\t}\n\t\t\tinput.Consume();\n\t\t}\n\n\n\t\tpublic String GetTokenName(int t)\n\t\t{\n\t\t\tif (t == -1) return \"EOF\";\n\t\t\t//if ( atn.g!=null ) return atn.g.getTokenDisplayName(t);\n\t\t\treturn \"'\" + (char)t + \"'\";\n\t\t}\n\t}\n\n\t/** When we hit an accept state in either the DFA or the ATN, we\n *  have to notify the character stream to start buffering characters\n *  via {@link IntStream#mark} and record the current state. The current sim state\n *  includes the current index into the input, the current line,\n *  and current character position in that line. Note that the Lexer is\n *  tracking the starting line and characterization of the token. These\n *  variables track the \"state\" of the simulator when it hits an accept state.\n *\n *  <p>We track these variables separately for the DFA and ATN simulation\n *  because the DFA simulation often has to fail over to the ATN\n *  simulation. If the ATN simulation fails, we need the DFA to fall\n *  back to its previously accepted state, if any. If the ATN succeeds,\n *  then the ATN does the accept and the DFA simulator that invoked it\n *  can simply return the predicted token type.</p>\n */\n\tpublic class SimState\n\t{\n\t\tpublic int index = -1;\n\t\tpublic int line = 0;\n\t\tpublic int charPos = -1;\n\t\tpublic DFAState dfaState;\n\n\t\tpublic void Reset()\n\t\t{\n\t\t\tindex = -1;\n\t\t\tline = 0;\n\t\t\tcharPos = -1;\n\t\t\tdfaState = null;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerActionExecutor.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Represents an executor for a sequence of lexer actions which traversed during\n    /// the matching operation of a lexer rule (token).\n    /// </summary>\n    /// <remarks>\n    /// Represents an executor for a sequence of lexer actions which traversed during\n    /// the matching operation of a lexer rule (token).\n    /// <p>The executor tracks position information for position-dependent lexer actions\n    /// efficiently, ensuring that actions appearing only at the end of the rule do\n    /// not cause bloating of the\n    /// <see cref=\"Antlr4.Runtime.Dfa.DFA\"/>\n    /// created for the lexer.</p>\n    /// </remarks>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public class LexerActionExecutor\n    {\n        [NotNull]\n        private readonly ILexerAction[] lexerActions;\n\n        /// <summary>\n        /// Caches the result of\n        /// <see cref=\"hashCode\"/>\n        /// since the hash code is an element\n        /// of the performance-critical\n        /// <see cref=\"ATNConfig.GetHashCode()\"/>\n        /// operation.\n        /// </summary>\n        private readonly int hashCode;\n\n        /// <summary>\n        /// Constructs an executor for a sequence of\n        /// <see cref=\"ILexerAction\"/>\n        /// actions.\n        /// </summary>\n        /// <param name=\"lexerActions\">The lexer actions to execute.</param>\n        public LexerActionExecutor(ILexerAction[] lexerActions)\n        {\n            this.lexerActions = lexerActions;\n            int hash = MurmurHash.Initialize();\n            foreach (ILexerAction lexerAction in lexerActions)\n            {\n                hash = MurmurHash.Update(hash, lexerAction);\n            }\n            this.hashCode = MurmurHash.Finish(hash, lexerActions.Length);\n        }\n\n        /// <summary>\n        /// Creates a\n        /// <see cref=\"LexerActionExecutor\"/>\n        /// which executes the actions for\n        /// the input\n        /// <paramref name=\"lexerActionExecutor\"/>\n        /// followed by a specified\n        /// <paramref name=\"lexerAction\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"lexerActionExecutor\">\n        /// The executor for actions already traversed by\n        /// the lexer while matching a token within a particular\n        /// <see cref=\"ATNConfig\"/>\n        /// . If this is\n        /// <see langword=\"null\"/>\n        /// , the method behaves as though\n        /// it were an empty executor.\n        /// </param>\n        /// <param name=\"lexerAction\">\n        /// The lexer action to execute after the actions\n        /// specified in\n        /// <paramref name=\"lexerActionExecutor\"/>\n        /// .\n        /// </param>\n        /// <returns>\n        /// A\n        /// <see cref=\"LexerActionExecutor\"/>\n        /// for executing the combine actions\n        /// of\n        /// <paramref name=\"lexerActionExecutor\"/>\n        /// and\n        /// <paramref name=\"lexerAction\"/>\n        /// .\n        /// </returns>\n        [return: NotNull]\n        public static Antlr4.Runtime.Atn.LexerActionExecutor Append(Antlr4.Runtime.Atn.LexerActionExecutor lexerActionExecutor, ILexerAction lexerAction)\n        {\n            if (lexerActionExecutor == null)\n            {\n                return new Antlr4.Runtime.Atn.LexerActionExecutor(new ILexerAction[] { lexerAction });\n            }\n            ILexerAction[] lexerActions = Arrays.CopyOf(lexerActionExecutor.lexerActions, lexerActionExecutor.lexerActions.Length + 1);\n            lexerActions[lexerActions.Length - 1] = lexerAction;\n            return new Antlr4.Runtime.Atn.LexerActionExecutor(lexerActions);\n        }\n\n        /// <summary>\n        /// Creates a\n        /// <see cref=\"LexerActionExecutor\"/>\n        /// which encodes the current offset\n        /// for position-dependent lexer actions.\n        /// <p>Normally, when the executor encounters lexer actions where\n        /// <see cref=\"ILexerAction.IsPositionDependent()\"/>\n        /// returns\n        /// <see langword=\"true\"/>\n        /// , it calls\n        /// <see cref=\"Antlr4.Runtime.IIntStream.Seek(int)\"/>\n        /// on the input\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// to set the input\n        /// position to the <em>end</em> of the current token. This behavior provides\n        /// for efficient DFA representation of lexer actions which appear at the end\n        /// of a lexer rule, even when the lexer rule matches a variable number of\n        /// characters.</p>\n        /// <p>Prior to traversing a match transition in the ATN, the current offset\n        /// from the token start index is assigned to all position-dependent lexer\n        /// actions which have not already been assigned a fixed offset. By storing\n        /// the offsets relative to the token start index, the DFA representation of\n        /// lexer actions which appear in the middle of tokens remains efficient due\n        /// to sharing among tokens of the same length, regardless of their absolute\n        /// position in the input stream.</p>\n        /// <p>If the current executor already has offsets assigned to all\n        /// position-dependent lexer actions, the method returns\n        /// <c>this</c>\n        /// .</p>\n        /// </summary>\n        /// <param name=\"offset\">\n        /// The current offset to assign to all position-dependent\n        /// lexer actions which do not already have offsets assigned.\n        /// </param>\n        /// <returns>\n        /// A\n        /// <see cref=\"LexerActionExecutor\"/>\n        /// which stores input stream offsets\n        /// for all position-dependent lexer actions.\n        /// </returns>\n        public virtual Antlr4.Runtime.Atn.LexerActionExecutor FixOffsetBeforeMatch(int offset)\n        {\n            ILexerAction[] updatedLexerActions = null;\n            for (int i = 0; i < lexerActions.Length; i++)\n            {\n                if (lexerActions[i].IsPositionDependent && !(lexerActions[i] is LexerIndexedCustomAction))\n                {\n                    if (updatedLexerActions == null)\n                    {\n                        updatedLexerActions = (ILexerAction[])lexerActions.Clone();\n                    }\n                    updatedLexerActions[i] = new LexerIndexedCustomAction(offset, lexerActions[i]);\n                }\n            }\n            if (updatedLexerActions == null)\n            {\n                return this;\n            }\n            return new Antlr4.Runtime.Atn.LexerActionExecutor(updatedLexerActions);\n        }\n\n        /// <summary>Gets the lexer actions to be executed by this executor.</summary>\n        /// <remarks>Gets the lexer actions to be executed by this executor.</remarks>\n        /// <returns>The lexer actions to be executed by this executor.</returns>\n        [NotNull]\n        public virtual ILexerAction[] LexerActions\n        {\n            get\n            {\n                return lexerActions;\n            }\n        }\n\n        /// <summary>\n        /// Execute the actions encapsulated by this executor within the context of a\n        /// particular\n        /// <see cref=\"Antlr4.Runtime.Lexer\"/>\n        /// .\n        /// <p>This method calls\n        /// <see cref=\"Antlr4.Runtime.IIntStream.Seek(int)\"/>\n        /// to set the position of the\n        /// <paramref name=\"input\"/>\n        ///\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// prior to calling\n        /// <see cref=\"ILexerAction.Execute(Antlr4.Runtime.Lexer)\"/>\n        /// on a position-dependent action. Before the\n        /// method returns, the input position will be restored to the same position\n        /// it was in when the method was invoked.</p>\n        /// </summary>\n        /// <param name=\"lexer\">The lexer instance.</param>\n        /// <param name=\"input\">\n        /// The input stream which is the source for the current token.\n        /// When this method is called, the current\n        /// <see cref=\"Antlr4.Runtime.IIntStream.Index()\"/>\n        /// for\n        /// <paramref name=\"input\"/>\n        /// should be the start of the following token, i.e. 1\n        /// character past the end of the current token.\n        /// </param>\n        /// <param name=\"startIndex\">\n        /// The token start index. This value may be passed to\n        /// <see cref=\"Antlr4.Runtime.IIntStream.Seek(int)\"/>\n        /// to set the\n        /// <paramref name=\"input\"/>\n        /// position to the beginning\n        /// of the token.\n        /// </param>\n        public virtual void Execute(Lexer lexer, ICharStream input, int startIndex)\n        {\n            bool requiresSeek = false;\n            int stopIndex = input.Index;\n            try\n            {\n                foreach (ILexerAction lexerAction in lexerActions)\n                {\n                    ILexerAction action = lexerAction;\n                    if (action is LexerIndexedCustomAction)\n                    {\n                        int offset = ((LexerIndexedCustomAction)action).Offset;\n                        input.Seek(startIndex + offset);\n                        action = ((LexerIndexedCustomAction)action).Action;\n                        requiresSeek = (startIndex + offset) != stopIndex;\n                    }\n                    else\n                    {\n                        if (action.IsPositionDependent)\n                        {\n                            input.Seek(stopIndex);\n                            requiresSeek = false;\n                        }\n                    }\n                    action.Execute(lexer);\n                }\n            }\n            finally\n            {\n                if (requiresSeek)\n                {\n                    input.Seek(stopIndex);\n                }\n            }\n        }\n\n        public override int GetHashCode()\n        {\n            return this.hashCode;\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.LexerActionExecutor))\n                {\n                    return false;\n                }\n            }\n            Antlr4.Runtime.Atn.LexerActionExecutor other = (Antlr4.Runtime.Atn.LexerActionExecutor)obj;\n            return hashCode == other.hashCode && Arrays.Equals(lexerActions, other.lexerActions);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerActionType.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public enum LexerActionType\n    {\n        Channel,\n        Custom,\n        Mode,\n        More,\n        PopMode,\n        PushMode,\n        Skip,\n        Type\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerChannelAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Implements the\n    /// <c>channel</c>\n    /// lexer action by calling\n    /// <see cref=\"Lexer.Channel\"/>\n    /// with the assigned channel.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerChannelAction : ILexerAction\n    {\n        private readonly int channel;\n\n        /// <summary>\n        /// Constructs a new\n        /// <paramref name=\"channel\"/>\n        /// action with the specified channel value.\n        /// </summary>\n        /// <param name=\"channel\">\n        /// The channel value to pass to\n        /// <see cref=\"Lexer.Channel\"/>\n        /// .\n        /// </param>\n        public LexerChannelAction(int channel)\n        {\n            this.channel = channel;\n        }\n\n        /// <summary>\n        /// Gets the channel to use for the\n        /// <see cref=\"Antlr4.Runtime.IToken\"/>\n        /// created by the lexer.\n        /// </summary>\n        /// <returns>\n        /// The channel to use for the\n        /// <see cref=\"Antlr4.Runtime.IToken\"/>\n        /// created by the lexer.\n        /// </returns>\n        public int Channel\n        {\n            get\n            {\n                return channel;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.Channel\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.Channel;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This action is implemented by calling\n        /// <see cref=\"Lexer.Channel\"/>\n        /// with the\n        /// value provided by\n        /// <see cref=\"Channel()\"/>\n        /// .</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            lexer.Channel = channel;\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            hash = MurmurHash.Update(hash, channel);\n            return MurmurHash.Finish(hash, 2);\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.LexerChannelAction))\n                {\n                    return false;\n                }\n            }\n            return channel == ((Antlr4.Runtime.Atn.LexerChannelAction)obj).channel;\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"channel({0})\", channel);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerCustomAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Executes a custom lexer action by calling\n    /// <see cref=\"Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)\"/>\n    /// with the\n    /// rule and action indexes assigned to the custom action. The implementation of\n    /// a custom action is added to the generated code for the lexer in an override\n    /// of\n    /// <see cref=\"Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)\"/>\n    /// when the grammar is compiled.\n    /// <p>This class may represent embedded actions created with the <code>{...}</code>\n    /// syntax in ANTLR 4, as well as actions created for lexer commands where the\n    /// command argument could not be evaluated when the grammar was compiled.</p>\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerCustomAction : ILexerAction\n    {\n        private readonly int ruleIndex;\n\n        private readonly int actionIndex;\n\n        /// <summary>\n        /// Constructs a custom lexer action with the specified rule and action\n        /// indexes.\n        /// </summary>\n        /// <remarks>\n        /// Constructs a custom lexer action with the specified rule and action\n        /// indexes.\n        /// </remarks>\n        /// <param name=\"ruleIndex\">\n        /// The rule index to use for calls to\n        /// <see cref=\"Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)\"/>\n        /// .\n        /// </param>\n        /// <param name=\"actionIndex\">\n        /// The action index to use for calls to\n        /// <see cref=\"Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)\"/>\n        /// .\n        /// </param>\n        public LexerCustomAction(int ruleIndex, int actionIndex)\n        {\n            this.ruleIndex = ruleIndex;\n            this.actionIndex = actionIndex;\n        }\n\n        /// <summary>\n        /// Gets the rule index to use for calls to\n        /// <see cref=\"Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)\"/>\n        /// .\n        /// </summary>\n        /// <returns>The rule index for the custom action.</returns>\n        public int RuleIndex\n        {\n            get\n            {\n                return ruleIndex;\n            }\n        }\n\n        /// <summary>\n        /// Gets the action index to use for calls to\n        /// <see cref=\"Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)\"/>\n        /// .\n        /// </summary>\n        /// <returns>The action index for the custom action.</returns>\n        public int ActionIndex\n        {\n            get\n            {\n                return actionIndex;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.Custom\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.Custom;\n            }\n        }\n\n        /// <summary>Gets whether the lexer action is position-dependent.</summary>\n        /// <remarks>\n        /// Gets whether the lexer action is position-dependent. Position-dependent\n        /// actions may have different semantics depending on the\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// index at the time the action is executed.\n        /// <p>Custom actions are position-dependent since they may represent a\n        /// user-defined embedded action which makes calls to methods like\n        /// <see cref=\"Antlr4.Runtime.Lexer.Text()\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"true\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>Custom actions are implemented by calling\n        /// <see cref=\"Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)\"/>\n        /// with the\n        /// appropriate rule and action indexes.</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            lexer.Action(null, ruleIndex, actionIndex);\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            hash = MurmurHash.Update(hash, ruleIndex);\n            hash = MurmurHash.Update(hash, actionIndex);\n            return MurmurHash.Finish(hash, 3);\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.LexerCustomAction))\n                {\n                    return false;\n                }\n            }\n            Antlr4.Runtime.Atn.LexerCustomAction other = (Antlr4.Runtime.Atn.LexerCustomAction)obj;\n            return ruleIndex == other.ruleIndex && actionIndex == other.actionIndex;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerIndexedCustomAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// This implementation of\n    /// <see cref=\"ILexerAction\"/>\n    /// is used for tracking input offsets\n    /// for position-dependent actions within a\n    /// <see cref=\"LexerActionExecutor\"/>\n    /// .\n    /// <p>This action is not serialized as part of the ATN, and is only required for\n    /// position-dependent lexer actions which appear at a location other than the\n    /// end of a rule. For more information about DFA optimizations employed for\n    /// lexer actions, see\n    /// <see cref=\"LexerActionExecutor.Append(LexerActionExecutor, ILexerAction)\"/>\n    /// and\n    /// <see cref=\"LexerActionExecutor.FixOffsetBeforeMatch(int)\"/>\n    /// .</p>\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerIndexedCustomAction : ILexerAction\n    {\n        private readonly int offset;\n\n        private readonly ILexerAction action;\n\n        /// <summary>\n        /// Constructs a new indexed custom action by associating a character offset\n        /// with a\n        /// <see cref=\"ILexerAction\"/>\n        /// .\n        /// <p>Note: This class is only required for lexer actions for which\n        /// <see cref=\"ILexerAction.IsPositionDependent()\"/>\n        /// returns\n        /// <see langword=\"true\"/>\n        /// .</p>\n        /// </summary>\n        /// <param name=\"offset\">\n        /// The offset into the input\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// , relative to\n        /// the token start index, at which the specified lexer action should be\n        /// executed.\n        /// </param>\n        /// <param name=\"action\">\n        /// The lexer action to execute at a particular offset in the\n        /// input\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// .\n        /// </param>\n        public LexerIndexedCustomAction(int offset, ILexerAction action)\n        {\n            this.offset = offset;\n            this.action = action;\n        }\n\n        /// <summary>\n        /// Gets the location in the input\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// at which the lexer\n        /// action should be executed. The value is interpreted as an offset relative\n        /// to the token start index.\n        /// </summary>\n        /// <returns>\n        /// The location in the input\n        /// <see cref=\"Antlr4.Runtime.ICharStream\"/>\n        /// at which the lexer\n        /// action should be executed.\n        /// </returns>\n        public int Offset\n        {\n            get\n            {\n                return offset;\n            }\n        }\n\n        /// <summary>Gets the lexer action to execute.</summary>\n        /// <remarks>Gets the lexer action to execute.</remarks>\n        /// <returns>\n        /// A\n        /// <see cref=\"ILexerAction\"/>\n        /// object which executes the lexer action.\n        /// </returns>\n        [NotNull]\n        public ILexerAction Action\n        {\n            get\n            {\n                return action;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns the result of calling\n        /// <see cref=\"ActionType()\"/>\n        /// on the\n        /// <see cref=\"ILexerAction\"/>\n        /// returned by\n        /// <see cref=\"Action()\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return action.ActionType;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"true\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This method calls\n        /// <see cref=\"Execute(Antlr4.Runtime.Lexer)\"/>\n        /// on the result of\n        /// <see cref=\"Action()\"/>\n        /// using the provided\n        /// <paramref name=\"lexer\"/>\n        /// .</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            // assume the input stream position was properly set by the calling code\n            action.Execute(lexer);\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, offset);\n            hash = MurmurHash.Update(hash, action);\n            return MurmurHash.Finish(hash, 2);\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.LexerIndexedCustomAction))\n                {\n                    return false;\n                }\n            }\n            Antlr4.Runtime.Atn.LexerIndexedCustomAction other = (Antlr4.Runtime.Atn.LexerIndexedCustomAction)obj;\n            return offset == other.offset && action.Equals(other.action);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerModeAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Implements the\n    /// <c>mode</c>\n    /// lexer action by calling\n    /// <see cref=\"Antlr4.Runtime.Lexer.Mode(int)\"/>\n    /// with\n    /// the assigned mode.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerModeAction : ILexerAction\n    {\n        private readonly int mode;\n\n        /// <summary>\n        /// Constructs a new\n        /// <paramref name=\"mode\"/>\n        /// action with the specified mode value.\n        /// </summary>\n        /// <param name=\"mode\">\n        /// The mode value to pass to\n        /// <see cref=\"Antlr4.Runtime.Lexer.Mode(int)\"/>\n        /// .\n        /// </param>\n        public LexerModeAction(int mode)\n        {\n            this.mode = mode;\n        }\n\n        /// <summary>Get the lexer mode this action should transition the lexer to.</summary>\n        /// <remarks>Get the lexer mode this action should transition the lexer to.</remarks>\n        /// <returns>\n        /// The lexer mode for this\n        /// <c>mode</c>\n        /// command.\n        /// </returns>\n        public int Mode\n        {\n            get\n            {\n                return mode;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.Mode\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.Mode;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This action is implemented by calling\n        /// <see cref=\"Antlr4.Runtime.Lexer.Mode(int)\"/>\n        /// with the\n        /// value provided by\n        /// <see cref=\"Mode()\"/>\n        /// .</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            lexer.Mode(mode);\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            hash = MurmurHash.Update(hash, mode);\n            return MurmurHash.Finish(hash, 2);\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.LexerModeAction))\n                {\n                    return false;\n                }\n            }\n            return mode == ((Antlr4.Runtime.Atn.LexerModeAction)obj).mode;\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"mode({0})\", mode);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerMoreAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Implements the\n    /// <c>more</c>\n    /// lexer action by calling\n    /// <see cref=\"Antlr4.Runtime.Lexer.More()\"/>\n    /// .\n    /// <p>The\n    /// <c>more</c>\n    /// command does not have any parameters, so this action is\n    /// implemented as a singleton instance exposed by\n    /// <see cref=\"Instance\"/>\n    /// .</p>\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerMoreAction : ILexerAction\n    {\n        /// <summary>Provides a singleton instance of this parameterless lexer action.</summary>\n        /// <remarks>Provides a singleton instance of this parameterless lexer action.</remarks>\n        public static readonly Antlr4.Runtime.Atn.LexerMoreAction Instance = new Antlr4.Runtime.Atn.LexerMoreAction();\n\n        /// <summary>\n        /// Constructs the singleton instance of the lexer\n        /// <c>more</c>\n        /// command.\n        /// </summary>\n        private LexerMoreAction()\n        {\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.More\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.More;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This action is implemented by calling\n        /// <see cref=\"Antlr4.Runtime.Lexer.More()\"/>\n        /// .</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            lexer.More();\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            return MurmurHash.Finish(hash, 1);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj == this;\n        }\n\n        public override string ToString()\n        {\n            return \"more\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerPopModeAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Implements the\n    /// <c>popMode</c>\n    /// lexer action by calling\n    /// <see cref=\"Antlr4.Runtime.Lexer.PopMode()\"/>\n    /// .\n    /// <p>The\n    /// <c>popMode</c>\n    /// command does not have any parameters, so this action is\n    /// implemented as a singleton instance exposed by\n    /// <see cref=\"Instance\"/>\n    /// .</p>\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerPopModeAction : ILexerAction\n    {\n        /// <summary>Provides a singleton instance of this parameterless lexer action.</summary>\n        /// <remarks>Provides a singleton instance of this parameterless lexer action.</remarks>\n        public static readonly Antlr4.Runtime.Atn.LexerPopModeAction Instance = new Antlr4.Runtime.Atn.LexerPopModeAction();\n\n        /// <summary>\n        /// Constructs the singleton instance of the lexer\n        /// <c>popMode</c>\n        /// command.\n        /// </summary>\n        private LexerPopModeAction()\n        {\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.PopMode\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.PopMode;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This action is implemented by calling\n        /// <see cref=\"Antlr4.Runtime.Lexer.PopMode()\"/>\n        /// .</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            lexer.PopMode();\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            return MurmurHash.Finish(hash, 1);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj == this;\n        }\n\n        public override string ToString()\n        {\n            return \"popMode\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerPushModeAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Implements the\n    /// <c>pushMode</c>\n    /// lexer action by calling\n    /// <see cref=\"Antlr4.Runtime.Lexer.PushMode(int)\"/>\n    /// with the assigned mode.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerPushModeAction : ILexerAction\n    {\n        private readonly int mode;\n\n        /// <summary>\n        /// Constructs a new\n        /// <c>pushMode</c>\n        /// action with the specified mode value.\n        /// </summary>\n        /// <param name=\"mode\">\n        /// The mode value to pass to\n        /// <see cref=\"Antlr4.Runtime.Lexer.PushMode(int)\"/>\n        /// .\n        /// </param>\n        public LexerPushModeAction(int mode)\n        {\n            this.mode = mode;\n        }\n\n        /// <summary>Get the lexer mode this action should transition the lexer to.</summary>\n        /// <remarks>Get the lexer mode this action should transition the lexer to.</remarks>\n        /// <returns>\n        /// The lexer mode for this\n        /// <c>pushMode</c>\n        /// command.\n        /// </returns>\n        public int Mode\n        {\n            get\n            {\n                return mode;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.PushMode\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.PushMode;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This action is implemented by calling\n        /// <see cref=\"Antlr4.Runtime.Lexer.PushMode(int)\"/>\n        /// with the\n        /// value provided by\n        /// <see cref=\"Mode()\"/>\n        /// .</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            lexer.PushMode(mode);\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            hash = MurmurHash.Update(hash, mode);\n            return MurmurHash.Finish(hash, 2);\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.LexerPushModeAction))\n                {\n                    return false;\n                }\n            }\n            return mode == ((Antlr4.Runtime.Atn.LexerPushModeAction)obj).mode;\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"pushMode({0})\", mode);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerSkipAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Implements the\n    /// <c>skip</c>\n    /// lexer action by calling\n    /// <see cref=\"Antlr4.Runtime.Lexer.Skip()\"/>\n    /// .\n    /// <p>The\n    /// <c>skip</c>\n    /// command does not have any parameters, so this action is\n    /// implemented as a singleton instance exposed by\n    /// <see cref=\"Instance\"/>\n    /// .</p>\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public sealed class LexerSkipAction : ILexerAction\n    {\n        /// <summary>Provides a singleton instance of this parameterless lexer action.</summary>\n        /// <remarks>Provides a singleton instance of this parameterless lexer action.</remarks>\n        public static readonly Antlr4.Runtime.Atn.LexerSkipAction Instance = new Antlr4.Runtime.Atn.LexerSkipAction();\n\n        /// <summary>\n        /// Constructs the singleton instance of the lexer\n        /// <c>skip</c>\n        /// command.\n        /// </summary>\n        private LexerSkipAction()\n        {\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.Skip\"/>\n        /// .\n        /// </returns>\n        public LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.Skip;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public bool IsPositionDependent\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This action is implemented by calling\n        /// <see cref=\"Antlr4.Runtime.Lexer.Skip()\"/>\n        /// .</p>\n        /// </summary>\n        public void Execute(Lexer lexer)\n        {\n            lexer.Skip();\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            return MurmurHash.Finish(hash, 1);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj == this;\n        }\n\n        public override string ToString()\n        {\n            return \"skip\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LexerTypeAction.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Implements the\n    /// <c>type</c>\n    /// lexer action by calling\n    /// <see cref=\"Lexer.Type\"/>\n    /// with the assigned type.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    /// <since>4.2</since>\n    public class LexerTypeAction : ILexerAction\n    {\n        private readonly int type;\n\n        /// <summary>\n        /// Constructs a new\n        /// <paramref name=\"type\"/>\n        /// action with the specified token type value.\n        /// </summary>\n        /// <param name=\"type\">\n        /// The type to assign to the token using\n        /// <see cref=\"Lexer.Type\"/>\n        /// .\n        /// </param>\n        public LexerTypeAction(int type)\n        {\n            this.type = type;\n        }\n\n        /// <summary>Gets the type to assign to a token created by the lexer.</summary>\n        /// <remarks>Gets the type to assign to a token created by the lexer.</remarks>\n        /// <returns>The type to assign to a token created by the lexer.</returns>\n        public virtual int Type\n        {\n            get\n            {\n                return type;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see cref=\"LexerActionType.Type\"/>\n        /// .\n        /// </returns>\n        public virtual LexerActionType ActionType\n        {\n            get\n            {\n                return LexerActionType.Type;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <returns>\n        /// This method returns\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public virtual bool IsPositionDependent\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This action is implemented by calling\n        /// <see cref=\"Lexer.Type\"/>\n        /// with the\n        /// value provided by\n        /// <see cref=\"Type()\"/>\n        /// .</p>\n        /// </summary>\n        public virtual void Execute(Lexer lexer)\n        {\n            lexer.Type = type;\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            hash = MurmurHash.Update(hash, (int)(ActionType));\n            hash = MurmurHash.Update(hash, type);\n            return MurmurHash.Finish(hash, 2);\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(obj is Antlr4.Runtime.Atn.LexerTypeAction))\n                {\n                    return false;\n                }\n            }\n            return type == ((Antlr4.Runtime.Atn.LexerTypeAction)obj).type;\n        }\n\n        public override string ToString()\n        {\n            return string.Format(\"type({0})\", type);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LookaheadEventInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// This class represents profiling event information for tracking the lookahead\n    /// depth required in order to make a prediction.\n    /// </summary>\n    /// <remarks>\n    /// This class represents profiling event information for tracking the lookahead\n    /// depth required in order to make a prediction.\n    /// </remarks>\n    /// <since>4.3</since>\n    public class LookaheadEventInfo : DecisionEventInfo\n    {\n        /// <summary>The alternative chosen by adaptivePredict(), not necessarily\n        ///  the outermost alt shown for a rule; left-recursive rules have\n        ///  user-level alts that differ from the rewritten rule with a (...) block\n        ///  and a (..)* loop.\n        /// </summary>\n        public int predictedAlt;\n\n        /// <summary>\n        /// Constructs a new instance of the\n        /// <see cref=\"LookaheadEventInfo\"/>\n        /// class with\n        /// the specified detailed lookahead information.\n        /// </summary>\n        /// <param name=\"decision\">The decision number</param>\n        /// <param name=\"configs\">The final configuration set containing the necessary\n        /// information to determine the result of a prediction, or {@code null} if\n        /// the final configuration set is not available\n        /// </param>\n        /// <param name=\"predictedAlt\"></param>\n        /// <param name=\"input\">The input token stream</param>\n        /// <param name=\"startIndex\">The start index for the current prediction</param>\n        /// <param name=\"stopIndex\">The index at which the prediction was finally made</param>\n        /// <param name=\"fullCtx\">\n        /// <see langword=\"true\"/>\n        /// if the current lookahead is part of an LL\n        /// prediction; otherwise,\n        /// <see langword=\"false\"/>\n        /// if the current lookahead is part of\n        /// an SLL prediction\n        /// </param>\n        public LookaheadEventInfo(int decision, ATNConfigSet configs, int predictedAlt, ITokenStream input, int startIndex, int stopIndex, bool fullCtx)\n            : base(decision, configs, input, startIndex, stopIndex, fullCtx)\n        {\n            this.predictedAlt = predictedAlt;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/LoopEndState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>Mark the end of a * or + loop.</summary>\n    /// <remarks>Mark the end of a * or + loop.</remarks>\n    public sealed class LoopEndState : ATNState\n    {\n        public ATNState loopBackState;\n\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.LoopEnd;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/MergeCache.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\n\nnamespace Antlr4.Runtime.Atn\n{\n\tpublic class MergeCache\n\t{\n\t\tDictionary<PredictionContext, Dictionary<PredictionContext, PredictionContext>> data = new Dictionary<PredictionContext, Dictionary<PredictionContext, PredictionContext>>();\n\n\t\tpublic PredictionContext Get(PredictionContext a, PredictionContext b)\n\t\t{\n\t\t\tDictionary<PredictionContext, PredictionContext> first;\n\t\t\tif (!data.TryGetValue(a, out first))\n\t\t\t\treturn null;\n\t\t\tPredictionContext value;\n\t\t\tif (first.TryGetValue(b, out value))\n\t\t\t\treturn value;\n\t\t\telse\n\t\t\t\treturn null;\n\n\t\t}\n\n\t\tpublic void Put(PredictionContext a, PredictionContext b, PredictionContext value)\n\t\t{\n\t\t\tDictionary<PredictionContext, PredictionContext> first;\n\t\t\tif (!data.TryGetValue(a, out first))\n\t\t\t{\n\t\t\t\tfirst = new Dictionary<PredictionContext, PredictionContext>();\n\t\t\t\tdata[a] = first;\n\t\t\t}\n\t\t\tfirst[b] = value;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/NotSetTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class NotSetTransition : SetTransition\n    {\n        public NotSetTransition(ATNState target, IntervalSet set)\n            : base(target, set)\n        {\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.NOT_SET;\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return symbol >= minVocabSymbol && symbol <= maxVocabSymbol && !base.Matches(symbol, minVocabSymbol, maxVocabSymbol);\n        }\n\n        public override string ToString()\n        {\n            return '~' + base.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ParseInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\n\t/**\n\t * This class provides access to specific and aggregate statistics gathered\n\t * during profiling of a parser.\n\t *\n\t * @since 4.3\n\t */\n\tpublic class ParseInfo\n\t{\n\t\tprotected readonly ProfilingATNSimulator atnSimulator;\n\n\tpublic ParseInfo(ProfilingATNSimulator atnSimulator)\n\t\t{\n\t\t\tthis.atnSimulator = atnSimulator;\n\t\t}\n\n\t\t/**\n\t\t * Gets an array of {@link DecisionInfo} instances containing the profiling\n\t\t * information gathered for each decision in the ATN.\n\t\t *\n\t\t * @return An array of {@link DecisionInfo} instances, indexed by decision\n\t\t * number.\n\t\t */\n\t\tpublic DecisionInfo[] getDecisionInfo()\n\t\t{\n\t\t\treturn atnSimulator.getDecisionInfo();\n\t\t}\n\n\t\t/**\n\t\t * Gets the decision numbers for decisions that required one or more\n\t\t * full-context predictions during parsing. These are decisions for which\n\t\t * {@link DecisionInfo#LL_Fallback} is non-zero.\n\t\t *\n\t\t * @return A list of decision numbers which required one or more\n\t\t * full-context predictions during parsing.\n\t\t */\n\t\tpublic List<int> getLLDecisions()\n\t\t{\n\t\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\t\tList<int> LL = new List<int>();\n\t\t\tfor (int i = 0; i < decisions.Length; i++)\n\t\t\t{\n\t\t\t\tlong fallBack = decisions[i].LL_Fallback;\n\t\t\t\tif (fallBack > 0) LL.Add(i);\n\t\t\t}\n\t\t\treturn LL;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total time spent during prediction across all decisions made\n\t\t * during parsing. This value is the sum of\n\t\t * {@link DecisionInfo#timeInPrediction} for all decisions.\n\t\t */\n\t\tpublic long getTotalTimeInPrediction()\n\t\t{\n\t\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\t\tlong t = 0;\n\t\t\tfor (int i = 0; i < decisions.Length; i++)\n\t\t\t{\n\t\t\t\tt += decisions[i].timeInPrediction;\n\t\t\t}\n\t\t\treturn t;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total number of SLL lookahead operations across all decisions\n\t\t * made during parsing. This value is the sum of\n\t\t * {@link DecisionInfo#SLL_TotalLook} for all decisions.\n\t\t */\n\t\tpublic long getTotalSLLLookaheadOps()\n\t\t{\n\t\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\t\tlong k = 0;\n\t\t\tfor (int i = 0; i < decisions.Length; i++)\n\t\t\t{\n\t\t\t\tk += decisions[i].SLL_TotalLook;\n\t\t\t}\n\t\t\treturn k;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total number of LL lookahead operations across all decisions\n\t\t * made during parsing. This value is the sum of\n\t\t * {@link DecisionInfo#LL_TotalLook} for all decisions.\n\t\t */\n\t\tpublic long getTotalLLLookaheadOps()\n\t\t{\n\t\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\t\tlong k = 0;\n\t\t\tfor (int i = 0; i < decisions.Length; i++)\n\t\t\t{\n\t\t\t\tk += decisions[i].LL_TotalLook;\n\t\t\t}\n\t\t\treturn k;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total number of ATN lookahead operations for SLL prediction\n\t\t * across all decisions made during parsing.\n\t\t */\n\t\tpublic long getTotalSLLATNLookaheadOps()\n\t\t{\n\t\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\t\tlong k = 0;\n\t\t\tfor (int i = 0; i < decisions.Length; i++)\n\t\t\t{\n\t\t\t\tk += decisions[i].SLL_ATNTransitions;\n\t\t\t}\n\t\t\treturn k;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total number of ATN lookahead operations for LL prediction\n\t\t * across all decisions made during parsing.\n\t\t */\n\t\tpublic long getTotalLLATNLookaheadOps()\n\t\t{\n\t\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\t\tlong k = 0;\n\t\t\tfor (int i = 0; i < decisions.Length; i++)\n\t\t\t{\n\t\t\t\tk += decisions[i].LL_ATNTransitions;\n\t\t\t}\n\t\t\treturn k;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total number of ATN lookahead operations for SLL and LL\n\t\t * prediction across all decisions made during parsing.\n\t\t *\n\t\t * <p>\n\t\t * This value is the sum of {@link #getTotalSLLATNLookaheadOps} and\n\t\t * {@link #getTotalLLATNLookaheadOps}.</p>\n\t\t */\n\t\tpublic long getTotalATNLookaheadOps()\n\t\t{\n\t\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\t\tlong k = 0;\n\t\t\tfor (int i = 0; i < decisions.Length; i++)\n\t\t\t{\n\t\t\t\tk += decisions[i].SLL_ATNTransitions;\n\t\t\t\tk += decisions[i].LL_ATNTransitions;\n\t\t\t}\n\t\t\treturn k;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total number of DFA states stored in the DFA cache for all\n\t\t * decisions in the ATN.\n\t\t */\n\t\tpublic int getDFASize()\n\t\t{\n\t\t\tint n = 0;\n\t\t\tDFA[] decisionToDFA = atnSimulator.decisionToDFA;\n\t\t\tfor (int i = 0; i < decisionToDFA.Length; i++)\n\t\t\t{\n\t\t\t\tn += getDFASize(i);\n\t\t\t}\n\t\t\treturn n;\n\t\t}\n\n\t\t/**\n\t\t * Gets the total number of DFA states stored in the DFA cache for a\n\t\t * particular decision.\n\t\t */\n\t\tpublic int getDFASize(int decision)\n\t\t{\n\t\t\tDFA decisionToDFA = atnSimulator.decisionToDFA[decision];\n\t\t\treturn decisionToDFA.states.Count;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ParserATNSimulator.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\n\t/**\n\t * The embodiment of the adaptive LL(*), ALL(*), parsing strategy.\n\t *\n\t * <p>\n\t * The basic complexity of the adaptive strategy makes it harder to understand.\n\t * We begin with ATN simulation to build paths in a DFA. Subsequent prediction\n\t * requests go through the DFA first. If they reach a state without an edge for\n\t * the current symbol, the algorithm fails over to the ATN simulation to\n\t * complete the DFA path for the current input (until it finds a conflict state\n\t * or uniquely predicting state).</p>\n\t *\n\t * <p>\n\t * All of that is done without using the outer context because we want to create\n\t * a DFA that is not dependent upon the rule invocation stack when we do a\n\t * prediction. One DFA works in all contexts. We avoid using context not\n\t * necessarily because it's slower, although it can be, but because of the DFA\n\t * caching problem. The closure routine only considers the rule invocation stack\n\t * created during prediction beginning in the decision rule. For example, if\n\t * prediction occurs without invoking another rule's ATN, there are no context\n\t * stacks in the configurations. When lack of context leads to a conflict, we\n\t * don't know if it's an ambiguity or a weakness in the strong LL(*) parsing\n\t * strategy (versus full LL(*)).</p>\n\t *\n\t * <p>\n\t * When SLL yields a configuration set with conflict, we rewind the input and\n\t * retry the ATN simulation, this time using full outer context without adding\n\t * to the DFA. Configuration context stacks will be the full invocation stacks\n\t * from the start rule. If we get a conflict using full context, then we can\n\t * definitively say we have a true ambiguity for that input sequence. If we\n\t * don't get a conflict, it implies that the decision is sensitive to the outer\n\t * context. (It is not context-sensitive in the sense of context-sensitive\n\t * grammars.)</p>\n\t *\n\t * <p>\n\t * The next time we reach this DFA state with an SLL conflict, through DFA\n\t * simulation, we will again retry the ATN simulation using full context mode.\n\t * This is slow because we can't save the results and have to \"interpret\" the\n\t * ATN each time we get that input.</p>\n\t *\n\t * <p>\n\t * <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>\n\t *\n\t * <p>\n\t * We could cache results from full context to predicted alternative easily and\n\t * that saves a lot of time but doesn't work in presence of predicates. The set\n\t * of visible predicates from the ATN start state changes depending on the\n\t * context, because closure can fall off the end of a rule. I tried to cache\n\t * tuples (stack context, semantic context, predicted alt) but it was slower\n\t * than interpreting and much more complicated. Also required a huge amount of\n\t * memory. The goal is not to create the world's fastest parser anyway. I'd like\n\t * to keep this algorithm simple. By launching multiple threads, we can improve\n\t * the speed of parsing across a large number of files.</p>\n\t *\n\t * <p>\n\t * There is no strict ordering between the amount of input used by SLL vs LL,\n\t * which makes it really hard to build a cache for full context. Let's say that\n\t * we have input A B C that leads to an SLL conflict with full context X. That\n\t * implies that using X we might only use A B but we could also use A B C D to\n\t * resolve conflict. Input A B C D could predict alternative 1 in one position\n\t * in the input and A B C E could predict alternative 2 in another position in\n\t * input. The conflicting SLL configurations could still be non-unique in the\n\t * full context prediction, which would lead us to requiring more input than the\n\t * original A B C.\tTo make a\tprediction cache work, we have to track\tthe exact\n\t * input\tused during the previous prediction. That amounts to a cache that maps\n\t * X to a specific DFA for that context.</p>\n\t *\n\t * <p>\n\t * Something should be done for left-recursive expression predictions. They are\n\t * likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry\n\t * with full LL thing Sam does.</p>\n\t *\n\t * <p>\n\t * <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>\n\t *\n\t * <p>\n\t * We avoid doing full context retry when the outer context is empty, we did not\n\t * dip into the outer context by falling off the end of the decision state rule,\n\t * or when we force SLL mode.</p>\n\t *\n\t * <p>\n\t * As an example of the not dip into outer context case, consider as super\n\t * constructor calls versus function calls. One grammar might look like\n\t * this:</p>\n\t *\n\t * <pre>\n\t * ctorBody\n\t *   : '{' superCall? stat* '}'\n\t *   ;\n\t * </pre>\n\t *\n\t * <p>\n\t * Or, you might see something like</p>\n\t *\n\t * <pre>\n\t * stat\n\t *   : superCall ';'\n\t *   | expression ';'\n\t *   | ...\n\t *   ;\n\t * </pre>\n\t *\n\t * <p>\n\t * In both cases I believe that no closure operations will dip into the outer\n\t * context. In the first case ctorBody in the worst case will stop at the '}'.\n\t * In the 2nd case it should stop at the ';'. Both cases should stay within the\n\t * entry rule and not dip into the outer context.</p>\n\t *\n\t * <p>\n\t * <strong>PREDICATES</strong></p>\n\t *\n\t * <p>\n\t * Predicates are always evaluated if present in either SLL or LL both. SLL and\n\t * LL simulation deals with predicates differently. SLL collects predicates as\n\t * it performs closure operations like ANTLR v3 did. It delays predicate\n\t * evaluation until it reaches and accept state. This allows us to cache the SLL\n\t * ATN simulation whereas, if we had evaluated predicates on-the-fly during\n\t * closure, the DFA state configuration sets would be different and we couldn't\n\t * build up a suitable DFA.</p>\n\t *\n\t * <p>\n\t * When building a DFA accept state during ATN simulation, we evaluate any\n\t * predicates and return the sole semantically valid alternative. If there is\n\t * more than 1 alternative, we report an ambiguity. If there are 0 alternatives,\n\t * we throw an exception. Alternatives without predicates act like they have\n\t * true predicates. The simple way to think about it is to strip away all\n\t * alternatives with false predicates and choose the minimum alternative that\n\t * remains.</p>\n\t *\n\t * <p>\n\t * When we start in the DFA and reach an accept state that's predicated, we test\n\t * those and return the minimum semantically viable alternative. If no\n\t * alternatives are viable, we throw an exception.</p>\n\t *\n\t * <p>\n\t * During full LL ATN simulation, closure always evaluates predicates and\n\t * on-the-fly. This is crucial to reducing the configuration set size during\n\t * closure. It hits a landmine when parsing with the Java grammar, for example,\n\t * without this on-the-fly evaluation.</p>\n\t *\n\t * <p>\n\t * <strong>SHARING DFA</strong></p>\n\t *\n\t * <p>\n\t * All instances of the same parser share the same decision DFAs through a\n\t * static field. Each instance gets its own ATN simulator but they share the\n\t * same {@link #decisionToDFA} field. They also share a\n\t * {@link PredictionContextCache} object that makes sure that all\n\t * {@link PredictionContext} objects are shared among the DFA states. This makes\n\t * a big size difference.</p>\n\t *\n\t * <p>\n\t * <strong>THREAD SAFETY</strong></p>\n\t *\n\t * <p>\n\t * The {@link ParserATNSimulator} locks on the {@link #decisionToDFA} field when\n\t * it adds a new DFA object to that array. {@link #addDFAEdge}\n\t * locks on the DFA for the current decision when setting the\n\t * {@link DFAState#edges} field. {@link #addDFAState} locks on\n\t * the DFA for the current decision when looking up a DFA state to see if it\n\t * already exists. We must make sure that all requests to add DFA states that\n\t * are equivalent result in the same shared DFA object. This is because lots of\n\t * threads will be trying to update the DFA at once. The\n\t * {@link #addDFAState} method also locks inside the DFA lock\n\t * but this time on the shared context cache when it rebuilds the\n\t * configurations' {@link PredictionContext} objects using cached\n\t * subgraphs/nodes. No other locking occurs, even during DFA simulation. This is\n\t * safe as long as we can guarantee that all threads referencing\n\t * {@code s.edge[t]} get the same physical target {@link DFAState}, or\n\t * {@code null}. Once into the DFA, the DFA simulation does not reference the\n\t * {@link DFA#states} map. It follows the {@link DFAState#edges} field to new\n\t * targets. The DFA simulator will either find {@link DFAState#edges} to be\n\t * {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or\n\t * {@code dfa.edges[t]} to be non-null. The\n\t * {@link #addDFAEdge} method could be racing to set the field\n\t * but in either case the DFA simulator works; if {@code null}, and requests ATN\n\t * simulation. It could also race trying to get {@code dfa.edges[t]}, but either\n\t * way it will work because it's not doing a test and set operation.</p>\n\t *\n\t * <p>\n\t * <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage\n\t * Parsing)</strong></p>\n\t *\n\t * <p>\n\t * Sam pointed out that if SLL does not give a syntax error, then there is no\n\t * point in doing full LL, which is slower. We only have to try LL if we get a\n\t * syntax error. For maximum speed, Sam starts the parser set to pure SLL\n\t * mode with the {@link BailErrorStrategy}:</p>\n\t *\n\t * <pre>\n\t * parser.{@link Parser#getInterpreter() getInterpreter()}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};\n\t * parser.{@link Parser#setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());\n\t * </pre>\n\t *\n\t * <p>\n\t * If it does not get a syntax error, then we're done. If it does get a syntax\n\t * error, we need to retry with the combined SLL/LL strategy.</p>\n\t *\n\t * <p>\n\t * The reason this works is as follows. If there are no SLL conflicts, then the\n\t * grammar is SLL (at least for that input set). If there is an SLL conflict,\n\t * the full LL analysis must yield a set of viable alternatives which is a\n\t * subset of the alternatives reported by SLL. If the LL set is a singleton,\n\t * then the grammar is LL but not SLL. If the LL set is the same size as the SLL\n\t * set, the decision is SLL. If the LL set has size &gt; 1, then that decision\n\t * is truly ambiguous on the current input. If the LL set is smaller, then the\n\t * SLL conflict resolution might choose an alternative that the full LL would\n\t * rule out as a possibility based upon better context information. If that's\n\t * the case, then the SLL parse will definitely get an error because the full LL\n\t * analysis says it's not viable. If SLL conflict resolution chooses an\n\t * alternative within the LL set, them both SLL and LL would choose the same\n\t * alternative because they both choose the minimum of multiple conflicting\n\t * alternatives.</p>\n\t *\n\t * <p>\n\t * Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and\n\t * a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL\n\t * parsing will get an error because SLL will pursue alternative 1. If\n\t * <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will\n\t * choose the same alternative because alternative one is the minimum of either\n\t * set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax\n\t * error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>\n\t *\n\t * <p>\n\t * Of course, if the input is invalid, then we will get an error for sure in\n\t * both SLL and LL parsing. Erroneous input will therefore require 2 passes over\n\t * the input.</p>\n\t */\n\tpublic class ParserATNSimulator : ATNSimulator\n\t{\n\t\tpublic static readonly bool debug = false;\n\t\tpublic static bool trace_atn_sim = false;\n\t\tpublic static readonly bool dfa_debug = false;\n\t\tpublic static readonly bool retry_debug = false;\n\n\t\tprotected readonly Parser parser;\n\n\t\tpublic readonly DFA[] decisionToDFA;\n\n\t\t/** SLL, LL, or LL + exact ambig detection? */\n\n\t\tprivate PredictionMode mode = PredictionMode.LL;\n\n\t\t/** Each prediction operation uses a cache for merge of prediction contexts.\n\t\t *  Don't keep around as it wastes huge amounts of memory. DoubleKeyMap\n\t\t *  isn't synchronized but we're ok since two threads shouldn't reuse same\n\t\t *  parser/atnsim object because it can only handle one input at a time.\n\t\t *  This maps graphs a and b to merged result c. (a,b)→c. We can avoid\n\t\t *  the merge if we ever see a and b again.  Note that (b,a)→c should\n\t\t *  also be examined during cache lookup.\n\t\t */\n\t\tprotected MergeCache mergeCache;\n\n\t\t// LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n\t\tprotected ITokenStream input;\n\t\tprotected int startIndex;\n\t\tprotected ParserRuleContext context;\n\t\tprotected DFA thisDfa;\n\n\t\t/** Testing only! */\n\t\tpublic ParserATNSimulator(ATN atn, DFA[] decisionToDFA,\n\t\t\t\t\t\t\t\t  PredictionContextCache sharedContextCache)\n\n\t\t: this(null, atn, decisionToDFA, sharedContextCache)\n\t\t{ }\n\n\t\tpublic ParserATNSimulator(Parser parser, ATN atn,\n\t\t\t\t\t\t\t\t  DFA[] decisionToDFA,\n\t\t\t\t\t\t\t\t  PredictionContextCache sharedContextCache)\n\t\t\t: base(atn, sharedContextCache)\n\t\t{\n\t\t\tthis.parser = parser;\n\t\t\tthis.decisionToDFA = decisionToDFA;\n\t\t\t//\t\tDOTGenerator dot = new DOTGenerator(null);\n\t\t\t//\t\tConsole.WriteLine(dot.getDOT(atn.rules.get(0), parser.getRuleNames()));\n\t\t\t//\t\tConsole.WriteLine(dot.getDOT(atn.rules.get(1), parser.getRuleNames()));\n\t\t}\n\n\t\tpublic override void Reset()\n\t\t{\n\t\t}\n\n\n\t\tpublic override void ClearDFA()\n\t\t{\n\t\t\tfor (int d = 0; d < decisionToDFA.Length; d++)\n\t\t\t{\n\t\t\t\tdecisionToDFA[d] = new DFA(atn.GetDecisionState(d), d);\n\t\t\t}\n\t\t}\n\n\t\tpublic virtual int AdaptivePredict(ITokenStream input, int decision,\n\t\t\t\t\t\t\t\t   ParserRuleContext outerContext)\n\t\t{\n\t\t\tif (debug || trace_atn_sim)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"adaptivePredict decision \" + decision +\n\t\t\t\t\t\t\t\t\t   \" exec LA(1)==\" + GetLookaheadName(input) +\n\t\t\t\t\t\t\t\t  \" line \" + input.LT(1).Line + \":\" + input.LT(1).Column);\n\t\t\t}\n\n\t\t\tthis.input = input;\n\t\t\tstartIndex = input.Index;\n\t\t\tcontext = outerContext;\n\t\t\tDFA dfa = decisionToDFA[decision];\n\t\t\tthisDfa = dfa;\n\n\t\t\tint m = input.Mark();\n\t\t\tint index = startIndex;\n\n\t\t\t// Now we are certain to have a specific decision's DFA\n\t\t\t// But, do we still need an initial state?\n\t\t\ttry\n\t\t\t{\n\t\t\t\tDFAState s0;\n\t\t\t\tif (dfa.IsPrecedenceDfa)\n\t\t\t\t{\n\t\t\t\t\t// the start state for a precedence DFA depends on the current\n\t\t\t\t\t// parser precedence, and is provided by a DFA method.\n\t\t\t\t\ts0 = dfa.GetPrecedenceStartState(parser.Precedence);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// the start state for a \"regular\" DFA is just s0\n\t\t\t\t\ts0 = dfa.s0;\n\t\t\t\t}\n\n\t\t\t\tif (s0 == null)\n\t\t\t\t{\n\t\t\t\t\tif (outerContext == null) outerContext = ParserRuleContext.EmptyContext;\n\t\t\t\t\tif (debug)\n\t\t\t\t\t{\n\t\t\t\t\t\tConsole.WriteLine(\"predictATN decision \" + dfa.decision +\n\t\t\t\t\t\t\t\t\t\t   \" exec LA(1)==\" + GetLookaheadName(input) +\n\t\t\t\t\t\t\t\t\t\t   \", outerContext=\" + outerContext.ToString(parser));\n\t\t\t\t\t}\n\n\t\t\t\t\tbool fullCtx = false;\n\t\t\t\t\tATNConfigSet s0_closure =\n\t\t\t\t\t\tComputeStartState(dfa.atnStartState,\n\t\t\t\t\t\t\t\t\t\t  ParserRuleContext.EmptyContext,\n\t\t\t\t\t\t\t\t\t\t  fullCtx);\n\n\t\t\t\t\tif (dfa.IsPrecedenceDfa)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* If this is a precedence DFA, we use applyPrecedenceFilter\n\t\t\t\t\t\t * to convert the computed start state to a precedence start\n\t\t\t\t\t\t * state. We then use DFA.setPrecedenceStartState to set the\n\t\t\t\t\t\t * appropriate start state for the precedence level rather\n\t\t\t\t\t\t * than simply setting DFA.s0.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tdfa.s0.configSet = s0_closure; // not used for prediction but useful to know start configs anyway\n\t\t\t\t\t\ts0_closure = ApplyPrecedenceFilter(s0_closure);\n\t\t\t\t\t\ts0 = AddDFAState(dfa, new DFAState(s0_closure));\n\t\t\t\t\t\tdfa.SetPrecedenceStartState(parser.Precedence, s0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\ts0 = AddDFAState(dfa, new DFAState(s0_closure));\n\t\t\t\t\t\tdfa.s0 = s0;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tint alt = ExecATN(dfa, s0, input, index, outerContext);\n\t\t\t\tif (debug)\n\t\t\t\t\tConsole.WriteLine(\"DFA after predictATN: \" + dfa.ToString(parser.Vocabulary));\n\t\t\t\treturn alt;\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tmergeCache = null; // wack cache after each prediction\n\t\t\t\tthisDfa = null;\n\t\t\t\tinput.Seek(index);\n\t\t\t\tinput.Release(m);\n\t\t\t}\n\t\t}\n\n\t\t/** Performs ATN simulation to compute a predicted alternative based\n\t\t *  upon the remaining input, but also updates the DFA cache to avoid\n\t\t *  having to traverse the ATN again for the same input sequence.\n\n\t\t There are some key conditions we're looking for after computing a new\n\t\t set of ATN configs (proposed DFA state):\n\t\t\t   * if the set is empty, there is no viable alternative for current symbol\n\t\t\t   * does the state uniquely predict an alternative?\n\t\t\t   * does the state have a conflict that would prevent us from\n\t\t\t\t putting it on the work list?\n\n\t\t We also have some key operations to do:\n\t\t\t   * add an edge from previous DFA state to potentially new DFA state, D,\n\t\t\t\t upon current symbol but only if adding to work list, which means in all\n\t\t\t\t cases except no viable alternative (and possibly non-greedy decisions?)\n\t\t\t   * collecting predicates and adding semantic context to DFA accept states\n\t\t\t   * adding rule context to context-sensitive DFA accept states\n\t\t\t   * consuming an input symbol\n\t\t\t   * reporting a conflict\n\t\t\t   * reporting an ambiguity\n\t\t\t   * reporting a context sensitivity\n\t\t\t   * reporting insufficient predicates\n\n\t\t cover these cases:\n\t\t\tdead end\n\t\t\tsingle alt\n\t\t\tsingle alt + preds\n\t\t\tconflict\n\t\t\tconflict + preds\n\t\t */\n\t\tprotected int ExecATN(DFA dfa, DFAState s0,\n\t\t\t\t\t\t   ITokenStream input, int startIndex,\n\t\t\t\t\t\t   ParserRuleContext outerContext)\n\t\t{\n\t\t\tif (debug || trace_atn_sim)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"execATN decision \" + dfa.decision +\n\t\t\t\t                  \", DFA state \" + s0 +\n\t\t\t\t\t\t\t\t  \", LA(1)==\" + GetLookaheadName(input) +\n\t\t\t\t\t\t\t\t  \" line \" + input.LT(1).Line + \":\" + input.LT(1).Column);\n\t\t\t}\n\n\t\t\tDFAState previousD = s0;\n\n\t\t\tif (debug) Console.WriteLine(\"s0 = \" + s0);\n\n\t\t\tint t = input.LA(1);\n\n\t\t\twhile (true)\n\t\t\t{ // while more work\n\t\t\t\tDFAState D = GetExistingTargetState(previousD, t);\n\t\t\t\tif (D == null)\n\t\t\t\t{\n\t\t\t\t\tD = ComputeTargetState(dfa, previousD, t);\n\t\t\t\t}\n\n\t\t\t\tif (D == ERROR)\n\t\t\t\t{\n\t\t\t\t\t// if any configs in previous dipped into outer context, that\n\t\t\t\t\t// means that input up to t actually finished entry rule\n\t\t\t\t\t// at least for SLL decision. Full LL doesn't dip into outer\n\t\t\t\t\t// so don't need special case.\n\t\t\t\t\t// We will get an error no matter what so delay until after\n\t\t\t\t\t// decision; better error message. Also, no reachable target\n\t\t\t\t\t// ATN states in SLL implies LL will also get nowhere.\n\t\t\t\t\t// If conflict in states that dip out, choose min since we\n\t\t\t\t\t// will get error no matter what.\n\t\t\t\t\tNoViableAltException e = NoViableAlt(input, outerContext, previousD.configSet, startIndex);\n\t\t\t\t\tinput.Seek(startIndex);\n\t\t\t\t\tint alt = GetSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configSet, outerContext);\n\t\t\t\t\tif (alt != ATN.INVALID_ALT_NUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn alt;\n\t\t\t\t\t}\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\n\t\t\t\tif (D.requiresFullContext && mode != PredictionMode.SLL)\n\t\t\t\t{\n\t\t\t\t\t// IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n\t\t\t\t\tBitSet conflictingAlts = D.configSet.conflictingAlts;\n\t\t\t\t\tif (D.predicates != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (debug) Console.WriteLine(\"DFA state has preds in DFA sim LL failover\");\n\t\t\t\t\t\tint conflictIndex = input.Index;\n\t\t\t\t\t\tif (conflictIndex != startIndex)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tinput.Seek(startIndex);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconflictingAlts = EvalSemanticContext(D.predicates, outerContext, true);\n\t\t\t\t\t\tif (conflictingAlts.Cardinality() == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (debug) Console.WriteLine(\"Full LL avoided\");\n\t\t\t\t\t\t\treturn conflictingAlts.NextSetBit(0);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (conflictIndex != startIndex)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// restore the index so reporting the fallback to full\n\t\t\t\t\t\t\t// context occurs with the index at the correct spot\n\t\t\t\t\t\t\tinput.Seek(conflictIndex);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (dfa_debug) Console.WriteLine(\"ctx sensitive state \" + outerContext + \" in \" + D);\n\t\t\t\t\tbool fullCtx = true;\n\t\t\t\t\tATNConfigSet s0_closure =\n\t\t\t\t\t\tComputeStartState(dfa.atnStartState, outerContext, fullCtx);\n\t\t\t\t\tReportAttemptingFullContext(dfa, conflictingAlts, D.configSet, startIndex, input.Index);\n\t\t\t\t\tint alt = ExecATNWithFullContext(dfa, D, s0_closure,\n\t\t\t\t\t\t\t\t\t\t\t\t\t input, startIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t outerContext);\n\t\t\t\t\treturn alt;\n\t\t\t\t}\n\n\t\t\t\tif (D.isAcceptState)\n\t\t\t\t{\n\t\t\t\t\tif (D.predicates == null)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn D.prediction;\n\t\t\t\t\t}\n\n\t\t\t\t\tint stopIndex = input.Index;\n\t\t\t\t\tinput.Seek(startIndex);\n\t\t\t\t\tBitSet alts = EvalSemanticContext(D.predicates, outerContext, true);\n\t\t\t\t\tswitch (alts.Cardinality())\n\t\t\t\t\t{\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tthrow NoViableAlt(input, outerContext, D.configSet, startIndex);\n\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\treturn alts.NextSetBit(0);\n\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// report ambiguity after predicate evaluation to make sure the correct\n\t\t\t\t\t\t\t// set of ambig alts is reported.\n\t\t\t\t\t\t\tReportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configSet);\n\t\t\t\t\t\t\treturn alts.NextSetBit(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpreviousD = D;\n\n\t\t\t\tif (t != IntStreamConstants.EOF)\n\t\t\t\t{\n\t\t\t\t\tinput.Consume();\n\t\t\t\t\tt = input.LA(1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Get an existing target state for an edge in the DFA. If the target state\n\t\t * for the edge has not yet been computed or is otherwise not available,\n\t\t * this method returns {@code null}.\n\t\t *\n\t\t * @param previousD The current DFA state\n\t\t * @param t The next input symbol\n\t\t * @return The existing target DFA state for the given input symbol\n\t\t * {@code t}, or {@code null} if the target state for this edge is not\n\t\t * already cached\n\t\t */\n\t\tprotected virtual DFAState GetExistingTargetState(DFAState previousD, int t)\n\t\t{\n\t\t\tDFAState[] edges = previousD.edges;\n\t\t\tif (edges == null || t + 1 < 0 || t + 1 >= edges.Length)\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn edges[t + 1];\n\t\t}\n\n\t\t/**\n\t\t * Compute a target state for an edge in the DFA, and attempt to add the\n\t\t * computed state and corresponding edge to the DFA.\n\t\t *\n\t\t * @param dfa The DFA\n\t\t * @param previousD The current DFA state\n\t\t * @param t The next input symbol\n\t\t *\n\t\t * @return The computed target DFA state for the given input symbol\n\t\t * {@code t}. If {@code t} does not lead to a valid DFA state, this method\n\t\t * returns {@link #ERROR}.\n\t\t */\n\t\tprotected virtual DFAState ComputeTargetState(DFA dfa, DFAState previousD, int t)\n\t\t{\n\t\t\tATNConfigSet reach = ComputeReachSet(previousD.configSet, t, false);\n\t\t\tif (reach == null)\n\t\t\t{\n\t\t\t\tAddDFAEdge(dfa, previousD, t, ERROR);\n\t\t\t\treturn ERROR;\n\t\t\t}\n\n\t\t\t// create new target state; we'll add to DFA after it's complete\n\t\t\tDFAState D = new DFAState(reach);\n\n\t\t\tint predictedAlt = GetUniqueAlt(reach);\n\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tICollection<BitSet> altSubSets = PredictionMode.GetConflictingAltSubsets(reach.configs);\n\t\t\t\tConsole.WriteLine(\"SLL altSubSets=\" + StaticUtils.ToString(altSubSets) +\n\t\t\t\t\t\t\t\t   \", configs=\" + reach +\n\t\t\t\t\t\t\t\t   \", predict=\" + predictedAlt + \", allSubsetsConflict=\" +\n\t\t\t\t\t\t\t\t\t   PredictionMode.AllSubsetsConflict(altSubSets) + \", conflictingAlts=\" +\n\t\t\t\t\t\t\t\t   GetConflictingAlts(reach));\n\t\t\t}\n\n\t\t\tif (predictedAlt != ATN.INVALID_ALT_NUMBER)\n\t\t\t{\n\t\t\t\t// NO CONFLICT, UNIQUELY PREDICTED ALT\n\t\t\t\tD.isAcceptState = true;\n\t\t\t\tD.configSet.uniqueAlt = predictedAlt;\n\t\t\t\tD.prediction = predictedAlt;\n\t\t\t}\n\t\t\telse if (PredictionMode.HasSLLConflictTerminatingPrediction(mode, reach))\n\t\t\t{\n\t\t\t\t// MORE THAN ONE VIABLE ALTERNATIVE\n\t\t\t\tD.configSet.conflictingAlts = GetConflictingAlts(reach);\n\t\t\t\tD.requiresFullContext = true;\n\t\t\t\t// in SLL-only mode, we will stop at this state and return the minimum alt\n\t\t\t\tD.isAcceptState = true;\n\t\t\t\tD.prediction = D.configSet.conflictingAlts.NextSetBit(0);\n\t\t\t}\n\n\t\t\tif (D.isAcceptState && D.configSet.hasSemanticContext)\n\t\t\t{\n\t\t\t\tPredicateDFAState(D, atn.GetDecisionState(dfa.decision));\n\t\t\t\tif (D.predicates != null)\n\t\t\t\t{\n\t\t\t\t\tD.prediction = ATN.INVALID_ALT_NUMBER;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// all adds to dfa are done after we've created full D state\n\t\t\tD = AddDFAEdge(dfa, previousD, t, D);\n\t\t\treturn D;\n\t\t}\n\n\t\tprotected void PredicateDFAState(DFAState dfaState, DecisionState decisionState)\n\t\t{\n\t\t\t// We need to test all predicates, even in DFA states that\n\t\t\t// uniquely predict alternative.\n\t\t\tint nalts = decisionState.NumberOfTransitions;\n\t\t\t// Update DFA so reach becomes accept state with (predicate,alt)\n\t\t\t// pairs if preds found for conflicting alts\n\t\t\tBitSet altsToCollectPredsFrom = GetConflictingAltsOrUniqueAlt(dfaState.configSet);\n\t\t\tSemanticContext[] altToPred = GetPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configSet, nalts);\n\t\t\tif (altToPred != null)\n\t\t\t{\n\t\t\t\tdfaState.predicates = GetPredicatePredictions(altsToCollectPredsFrom, altToPred);\n\t\t\t\tdfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// There are preds in configs but they might go away\n\t\t\t\t// when OR'd together like {p}? || NONE == NONE. If neither\n\t\t\t\t// alt has preds, resolve to min alt\n\t\t\t\tdfaState.prediction = altsToCollectPredsFrom.NextSetBit(0);\n\t\t\t}\n\t\t}\n\n\t\t// comes back with reach.UniqueAlt set to a valid alt\n\t\tprotected int ExecATNWithFullContext(DFA dfa,\n\t\t\t\t\t\t\t\t\t\t\t DFAState D, // how far we got in SLL DFA before failing over\n\t\t\t\t\t\t\t\t\t\t\t ATNConfigSet s0,\n\t\t\t\t\t\t\t\t\t\t\t ITokenStream input, int startIndex,\n\t\t\t\t\t\t\t\t\t\t\t ParserRuleContext outerContext)\n\t\t{\n\t\t\tif (debug || trace_atn_sim)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"execATNWithFullContext \" + s0);\n\t\t\t}\n\t\t\tbool fullCtx = true;\n\t\t\tbool foundExactAmbig = false;\n\t\t\tATNConfigSet reach = null;\n\t\t\tATNConfigSet previous = s0;\n\t\t\tinput.Seek(startIndex);\n\t\t\tint t = input.LA(1);\n\t\t\tint predictedAlt;\n\t\t\twhile (true)\n\t\t\t{ // while more work\n\t\t\t  //\t\t\tConsole.WriteLine(\"LL REACH \"+GetLookaheadName(input)+\n\t\t\t  //\t\t\t\t\t\t\t   \" from configs.size=\"+previous.size()+\n\t\t\t  //\t\t\t\t\t\t\t   \" line \"+input.LT(1)Line+\":\"+input.LT(1).Column);\n\t\t\t\treach = ComputeReachSet(previous, t, fullCtx);\n\t\t\t\tif (reach == null)\n\t\t\t\t{\n\t\t\t\t\t// if any configs in previous dipped into outer context, that\n\t\t\t\t\t// means that input up to t actually finished entry rule\n\t\t\t\t\t// at least for LL decision. Full LL doesn't dip into outer\n\t\t\t\t\t// so don't need special case.\n\t\t\t\t\t// We will get an error no matter what so delay until after\n\t\t\t\t\t// decision; better error message. Also, no reachable target\n\t\t\t\t\t// ATN states in SLL implies LL will also get nowhere.\n\t\t\t\t\t// If conflict in states that dip out, choose min since we\n\t\t\t\t\t// will get error no matter what.\n\t\t\t\t\tNoViableAltException e = NoViableAlt(input, outerContext, previous, startIndex);\n\t\t\t\t\tinput.Seek(startIndex);\n\t\t\t\t\tint alt = GetSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);\n\t\t\t\t\tif (alt != ATN.INVALID_ALT_NUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn alt;\n\t\t\t\t\t}\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\n\t\t\t\tICollection<BitSet> altSubSets = PredictionMode.GetConflictingAltSubsets(reach.configs);\n\t\t\t\tif (debug)\n\t\t\t\t{\n\t\t\t\t\tConsole.WriteLine(\"LL altSubSets=\" + altSubSets +\n\t\t\t\t\t\t\t\t\t   \", predict=\" + PredictionMode.GetUniqueAlt(altSubSets) +\n\t\t\t\t\t\t\t\t\t   \", ResolvesToJustOneViableAlt=\" +\n\t\t\t\t\t\t\t\t\t\t   PredictionMode.ResolvesToJustOneViableAlt(altSubSets));\n\t\t\t\t}\n\n\t\t\t\t//\t\t\tConsole.WriteLine(\"altSubSets: \"+altSubSets);\n\t\t\t\t//\t\t\tSystem.err.println(\"reach=\"+reach+\", \"+reach.conflictingAlts);\n\t\t\t\treach.uniqueAlt = GetUniqueAlt(reach);\n\t\t\t\t// unique prediction?\n\t\t\t\tif (reach.uniqueAlt != ATN.INVALID_ALT_NUMBER)\n\t\t\t\t{\n\t\t\t\t\tpredictedAlt = reach.uniqueAlt;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (mode != PredictionMode.LL_EXACT_AMBIG_DETECTION)\n\t\t\t\t{\n\t\t\t\t\tpredictedAlt = PredictionMode.ResolvesToJustOneViableAlt(altSubSets);\n\t\t\t\t\tif (predictedAlt != ATN.INVALID_ALT_NUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// In exact ambiguity mode, we never try to terminate early.\n\t\t\t\t\t// Just keeps scarfing until we know what the conflict is\n\t\t\t\t\tif (PredictionMode.AllSubsetsConflict(altSubSets) &&\n\t\t\t\t\t\t PredictionMode.AllSubsetsEqual(altSubSets))\n\t\t\t\t\t{\n\t\t\t\t\t\tfoundExactAmbig = true;\n\t\t\t\t\t\tpredictedAlt = PredictionMode.GetSingleViableAlt(altSubSets);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// else there are multiple non-conflicting subsets or\n\t\t\t\t\t// we're not sure what the ambiguity is yet.\n\t\t\t\t\t// So, keep going.\n\t\t\t\t}\n\n\t\t\t\tprevious = reach;\n\t\t\t\tif (t != IntStreamConstants.EOF)\n\t\t\t\t{\n\t\t\t\t\tinput.Consume();\n\t\t\t\t\tt = input.LA(1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the configuration set uniquely predicts an alternative,\n\t\t\t// without conflict, then we know that it's a full LL decision\n\t\t\t// not SLL.\n\t\t\tif (reach.uniqueAlt != ATN.INVALID_ALT_NUMBER)\n\t\t\t{\n\t\t\t\tReportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.Index);\n\t\t\t\treturn predictedAlt;\n\t\t\t}\n\n\t\t\t// We do not check predicates here because we have checked them\n\t\t\t// on-the-fly when doing full context prediction.\n\n\t\t\t/*\n\t\t\tIn non-exact ambiguity detection mode, we might\tactually be able to\n\t\t\tdetect an exact ambiguity, but I'm not going to spend the cycles\n\t\t\tneeded to check. We only emit ambiguity warnings in exact ambiguity\n\t\t\tmode.\n\n\t\t\tFor example, we might know that we have conflicting configurations.\n\t\t\tBut, that does not mean that there is no way forward without a\n\t\t\tconflict. It's possible to have nonconflicting alt subsets as in:\n\n\t\t\t   LL altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n\n\t\t\tfrom\n\n\t\t\t   [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n\t\t\t\t(13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n\n\t\t\tIn this case, (17,1,[5 $]) indicates there is some next sequence that\n\t\t\twould resolve this without conflict to alternative 1. Any other viable\n\t\t\tnext sequence, however, is associated with a conflict.  We stop\n\t\t\tlooking for input because no amount of further lookahead will alter\n\t\t\tthe fact that we should predict alternative 1.  We just can't say for\n\t\t\tsure that there is an ambiguity without looking further.\n\t\t\t*/\n\t\t\tReportAmbiguity(dfa, D, startIndex, input.Index, foundExactAmbig, reach.GetAlts(), reach);\n\n\t\t\treturn predictedAlt;\n\t\t}\n\n\t\tprotected virtual ATNConfigSet ComputeReachSet(ATNConfigSet closure, int t, bool fullCtx)\n\t\t{\n\t\t\tif (debug)\n\t\t\t\tConsole.WriteLine(\"in computeReachSet, starting closure: \" + closure);\n\n\t\t\tif (mergeCache == null)\n\t\t\t{\n\t\t\t\tmergeCache = new MergeCache();\n\t\t\t}\n\n\t\t\tATNConfigSet intermediate = new ATNConfigSet(fullCtx);\n\n\t\t\t/* Configurations already in a rule stop state indicate reaching the end\n\t\t\t * of the decision rule (local context) or end of the start rule (full\n\t\t\t * context). Once reached, these configurations are never updated by a\n\t\t\t * closure operation, so they are handled separately for the performance\n\t\t\t * advantage of having a smaller intermediate set when calling closure.\n\t\t\t *\n\t\t\t * For full-context reach operations, separate handling is required to\n\t\t\t * ensure that the alternative matching the longest overall sequence is\n\t\t\t * chosen when multiple such configurations can match the input.\n\t\t\t */\n\t\t\tList<ATNConfig> skippedStopStates = null;\n\n\t\t\t// First figure out where we can reach on input t\n\t\t\tforeach (ATNConfig c in closure.configs)\n\t\t\t{\n\t\t\t\tif (debug) Console.WriteLine(\"testing \" + GetTokenName(t) + \" at \" + c.ToString());\n\n\t\t\t\tif (c.state is RuleStopState)\n\t\t\t\t{\n\t\t\t\t\tif (fullCtx || t == IntStreamConstants.EOF)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (skippedStopStates == null)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tskippedStopStates = new List<ATNConfig>();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tskippedStopStates.Add(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tint n = c.state.NumberOfTransitions;\n\t\t\t\tfor (int ti = 0; ti < n; ti++)\n\t\t\t\t{               // for each transition\n\t\t\t\t\tTransition trans = c.state.Transition(ti);\n\t\t\t\t\tATNState target = GetReachableTarget(trans, t);\n\t\t\t\t\tif (target != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tintermediate.Add(new ATNConfig(c, target), mergeCache);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Now figure out where the reach operation can take us...\n\n\t\t\tATNConfigSet reach = null;\n\n\t\t\t/* This block optimizes the reach operation for intermediate sets which\n\t\t\t * trivially indicate a termination state for the overall\n\t\t\t * adaptivePredict operation.\n\t\t\t *\n\t\t\t * The conditions assume that intermediate\n\t\t\t * contains all configurations relevant to the reach set, but this\n\t\t\t * condition is not true when one or more configurations have been\n\t\t\t * withheld in skippedStopStates, or when the current symbol is EOF.\n\t\t\t */\n\t\t\tif (skippedStopStates == null && t != TokenConstants.EOF)\n\t\t\t{\n\t\t\t\tif (intermediate.Count == 1)\n\t\t\t\t{\n\t\t\t\t\t// Don't pursue the closure if there is just one state.\n\t\t\t\t\t// It can only have one alternative; just add to result\n\t\t\t\t\t// Also don't pursue the closure if there is unique alternative\n\t\t\t\t\t// among the configurations.\n\t\t\t\t\treach = intermediate;\n\t\t\t\t}\n\t\t\t\telse if (GetUniqueAlt(intermediate) != ATN.INVALID_ALT_NUMBER)\n\t\t\t\t{\n\t\t\t\t\t// Also don't pursue the closure if there is unique alternative\n\t\t\t\t\t// among the configurations.\n\t\t\t\t\treach = intermediate;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* If the reach set could not be trivially determined, perform a closure\n\t\t\t * operation on the intermediate set to compute its initial value.\n\t\t\t */\n\t\t\tif (reach == null)\n\t\t\t{\n\t\t\t\treach = new ATNConfigSet(fullCtx);\n\t\t\t\tHashSet<ATNConfig> closureBusy = new HashSet<ATNConfig>();\n\t\t\t\tbool treatEofAsEpsilon = t == TokenConstants.EOF;\n\t\t\t\tforeach (ATNConfig c in intermediate.configs)\n\t\t\t\t{\n\t\t\t\t\tClosure(c, reach, closureBusy, false, fullCtx, treatEofAsEpsilon);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (t == IntStreamConstants.EOF)\n\t\t\t{\n\t\t\t\t/* After consuming EOF no additional input is possible, so we are\n\t\t\t\t * only interested in configurations which reached the end of the\n\t\t\t\t * decision rule (local context) or end of the start rule (full\n\t\t\t\t * context). Update reach to contain only these configurations. This\n\t\t\t\t * handles both explicit EOF transitions in the grammar and implicit\n\t\t\t\t * EOF transitions following the end of the decision or start rule.\n\t\t\t\t *\n\t\t\t\t * When reach==intermediate, no closure operation was performed. In\n\t\t\t\t * this case, removeAllConfigsNotInRuleStopState needs to check for\n\t\t\t\t * reachable rule stop states as well as configurations already in\n\t\t\t\t * a rule stop state.\n\t\t\t\t *\n\t\t\t\t * This is handled before the configurations in skippedStopStates,\n\t\t\t\t * because any configurations potentially added from that list are\n\t\t\t\t * already guaranteed to meet this condition whether or not it's\n\t\t\t\t * required.\n\t\t\t\t */\n\t\t\t\treach = RemoveAllConfigsNotInRuleStopState(reach, reach == intermediate);\n\t\t\t}\n\n\t\t\t/* If skippedStopStates is not null, then it contains at least one\n\t\t\t * configuration. For full-context reach operations, these\n\t\t\t * configurations reached the end of the start rule, in which case we\n\t\t\t * only add them back to reach if no configuration during the current\n\t\t\t * closure operation reached such a state. This ensures adaptivePredict\n\t\t\t * chooses an alternative matching the longest overall sequence when\n\t\t\t * multiple alternatives are viable.\n\t\t\t */\n\t\t\tif (skippedStopStates != null && (!fullCtx || !PredictionMode.HasConfigInRuleStopState(reach.configs)))\n\t\t\t{\n\t\t\t\tforeach (ATNConfig c in skippedStopStates)\n\t\t\t\t{\n\t\t\t\t\treach.Add(c, mergeCache);\n\t\t\t\t}\n\t\t\t}\n\n            if ( trace_atn_sim ) {\n                Console.WriteLine(\"computeReachSet \"+closure+\" -> \"+reach);\n            }\n\n    \t\tif (reach.Empty)\n\t\t\t\treturn null;\n\t\t\treturn reach;\n\t\t}\n\n\t\t/**\n\t\t * Return a configuration set containing only the configurations from\n\t\t * {@code configs} which are in a {@link RuleStopState}. If all\n\t\t * configurations in {@code configs} are already in a rule stop state, this\n\t\t * method simply returns {@code configs}.\n\t\t *\n\t\t * <p>When {@code lookToEndOfRule} is true, this method uses\n\t\t * {@link ATN#nextTokens} for each configuration in {@code configs} which is\n\t\t * not already in a rule stop state to see if a rule stop state is reachable\n\t\t * from the configuration via epsilon-only transitions.</p>\n\t\t *\n\t\t * @param configs the configuration set to update\n\t\t * @param lookToEndOfRule when true, this method checks for rule stop states\n\t\t * reachable by epsilon-only transitions from each configuration in\n\t\t * {@code configs}.\n\t\t *\n\t\t * @return {@code configs} if all configurations in {@code configs} are in a\n\t\t * rule stop state, otherwise return a new configuration set containing only\n\t\t * the configurations from {@code configs} which are in a rule stop state\n\t\t */\n\t\tprotected ATNConfigSet RemoveAllConfigsNotInRuleStopState(ATNConfigSet configSet, bool lookToEndOfRule)\n\t\t{\n\t\t\tif (PredictionMode.AllConfigsInRuleStopStates(configSet.configs))\n\t\t\t{\n\t\t\t\treturn configSet;\n\t\t\t}\n\n\t\t\tATNConfigSet result = new ATNConfigSet(configSet.fullCtx);\n\t\t\tforeach (ATNConfig config in configSet.configs)\n\t\t\t{\n\t\t\t\tif (config.state is RuleStopState)\n\t\t\t\t{\n\t\t\t\t\tresult.Add(config, mergeCache);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (lookToEndOfRule && config.state.OnlyHasEpsilonTransitions)\n\t\t\t\t{\n\t\t\t\t\tIntervalSet nextTokens = atn.NextTokens(config.state);\n\t\t\t\t\tif (nextTokens.Contains(TokenConstants.EPSILON))\n\t\t\t\t\t{\n\t\t\t\t\t\tATNState endOfRuleState = atn.ruleToStopState[config.state.ruleIndex];\n\t\t\t\t\t\tresult.Add(new ATNConfig(config, endOfRuleState), mergeCache);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\n\t\tprotected ATNConfigSet ComputeStartState(ATNState p,\n\t\t\t\t\t\t\t\t\t\t\t  RuleContext ctx,\n\t\t\t\t\t\t\t\t\t\t\t  bool fullCtx)\n\t\t{\n\t\t\t// always at least the implicit call to start rule\n\t\t\tPredictionContext initialContext = PredictionContext.FromRuleContext(atn, ctx);\n\t\t\tATNConfigSet configs = new ATNConfigSet(fullCtx);\n\n            if ( trace_atn_sim )  {\n                Console.WriteLine(\"computeStartState from ATN state \"+p+\" initialContext=\"+initialContext);\n            }\n\n\n\t\t\tfor (int i = 0; i < p.NumberOfTransitions; i++)\n\t\t\t{\n\t\t\t\tATNState target = p.Transition(i).target;\n\t\t\t\tATNConfig c = new ATNConfig(target, i + 1, initialContext);\n\t\t\t\tHashSet<ATNConfig> closureBusy = new HashSet<ATNConfig>();\n\t\t\t\tClosure(c, configs, closureBusy, true, fullCtx, false);\n\t\t\t}\n\n\t\t\treturn configs;\n\t\t}\n\n\t\t/* parrt internal source braindump that doesn't mess up\n\t\t * external API spec.\n\t\t\tcontext-sensitive in that they can only be properly evaluated\n\t\t\tin the context of the proper prec argument. Without pruning,\n\t\t\tthese predicates are normal predicates evaluated when we reach\n\t\t\tconflict state (or unique prediction). As we cannot evaluate\n\t\t\tthese predicates out of context, the resulting conflict leads\n\t\t\tto full LL evaluation and nonlinear prediction which shows up\n\t\t\tvery clearly with fairly large expressions.\n\n\t\t\tExample grammar:\n\n\t\t\te : e '*' e\n\t\t\t  | e '+' e\n\t\t\t  | INT\n\t\t\t  ;\n\n\t\t\tWe convert that to the following:\n\n\t\t\te[int prec]\n\t\t\t\t:   INT\n\t\t\t\t\t( {3>=prec}? '*' e[4]\n\t\t\t\t\t| {2>=prec}? '+' e[3]\n\t\t\t\t\t)*\n\t\t\t\t;\n\n\t\t\tThe (..)* loop has a decision for the inner block as well as\n\t\t\tan enter or exit decision, which is what concerns us here. At\n\t\t\tthe 1st + of input 1+2+3, the loop entry sees both predicates\n\t\t\tand the loop exit also sees both predicates by falling off the\n\t\t\tedge of e.  This is because we have no stack information with\n\t\t\tSLL and find the follow of e, which will hit the return states\n\t\t\tinside the loop after e[4] and e[3], which brings it back to\n\t\t\tthe enter or exit decision. In this case, we know that we\n\t\t\tcannot evaluate those predicates because we have fallen off\n\t\t\tthe edge of the stack and will in general not know which prec\n\t\t\tparameter is the right one to use in the predicate.\n\n\t\t\tBecause we have special information, that these are precedence\n\t\t\tpredicates, we can resolve them without failing over to full\n\t\t\tLL despite their context sensitive nature. We make an\n\t\t\tassumption that prec[-1] <= prec[0], meaning that the current\n\t\t\tprecedence level is greater than or equal to the precedence\n\t\t\tlevel of recursive invocations above us in the stack. For\n\t\t\texample, if predicate {3>=prec}? is true of the current prec,\n\t\t\tthen one option is to enter the loop to match it now. The\n\t\t\tother option is to exit the loop and the left recursive rule\n\t\t\tto match the current operator in rule invocation further up\n\t\t\tthe stack. But, we know that all of those prec are lower or\n\t\t\tthe same value and so we can decide to enter the loop instead\n\t\t\tof matching it later. That means we can strip out the other\n\t\t\tconfiguration for the exit branch.\n\n\t\t\tSo imagine we have (14,1,$,{2>=prec}?) and then\n\t\t\t(14,2,$-dipsIntoOuterContext,{2>=prec}?). The optimization\n\t\t\tallows us to collapse these two configurations. We know that\n\t\t\tif {2>=prec}? is true for the current prec parameter, it will\n\t\t\talso be true for any prec from an invoking e call, indicated\n\t\t\tby dipsIntoOuterContext. As the predicates are both true, we\n\t\t\thave the option to evaluate them early in the decision start\n\t\t\tstate. We do this by stripping both predicates and choosing to\n\t\t\tenter the loop as it is consistent with the notion of operator\n\t\t\tprecedence. It's also how the full LL conflict resolution\n\t\t\twould work.\n\n\t\t\tThe solution requires a different DFA start state for each\n\t\t\tprecedence level.\n\n\t\t\tThe basic filter mechanism is to remove configurations of the\n\t\t\tform (p, 2, pi) if (p, 1, pi) exists for the same p and pi. In\n\t\t\tother words, for the same ATN state and predicate context,\n\t\t\tremove any configuration associated with an exit branch if\n\t\t\tthere is a configuration associated with the enter branch.\n\n\t\t\tIt's also the case that the filter evaluates precedence\n\t\t\tpredicates and resolves conflicts according to precedence\n\t\t\tlevels. For example, for input 1+2+3 at the first +, we see\n\t\t\tprediction filtering\n\n\t\t\t[(11,1,[$],{3>=prec}?), (14,1,[$],{2>=prec}?), (5,2,[$],up=1),\n\t\t\t (11,2,[$],up=1), (14,2,[$],up=1)],hasSemanticContext=true,dipsIntoOuterContext\n\n\t\t\tto\n\n\t\t\t[(11,1,[$]), (14,1,[$]), (5,2,[$],up=1)],dipsIntoOuterContext\n\n\t\t\tThis filters because {3>=prec}? evals to true and collapses\n\t\t\t(11,1,[$],{3>=prec}?) and (11,2,[$],up=1) since early conflict\n\t\t\tresolution based upon rules of operator precedence fits with\n\t\t\tour usual match first alt upon conflict.\n\n\t\t\tWe noticed a problem where a recursive call resets precedence\n\t\t\tto 0. Sam's fix: each config has flag indicating if it has\n\t\t\treturned from an expr[0] call. then just don't filter any\n\t\t\tconfig with that flag set. flag is carried along in\n\t\t\tclosure(). so to avoid adding field, set bit just under sign\n\t\t\tbit of dipsIntoOuterContext (SUPPRESS_PRECEDENCE_FILTER).\n\t\t\tWith the change you filter \"unless (p, 2, pi) was reached\n\t\t\tafter leaving the rule stop state of the LR rule containing\n\t\t\tstate p, corresponding to a rule invocation with precedence\n\t\t\tlevel 0\"\n\t\t */\n\n\t\t/**\n\t\t * This method transforms the start state computed by\n\t\t * {@link #computeStartState} to the special start state used by a\n\t\t * precedence DFA for a particular precedence value. The transformation\n\t\t * process applies the following changes to the start state's configuration\n\t\t * set.\n\t\t *\n\t\t * <ol>\n\t\t * <li>Evaluate the precedence predicates for each configuration using\n\t\t * {@link SemanticContext#evalPrecedence}.</li>\n\t\t * <li>When {@link ATNConfig#isPrecedenceFilterSuppressed} is {@code false},\n\t\t * remove all configurations which predict an alternative greater than 1,\n\t\t * for which another configuration that predicts alternative 1 is in the\n\t\t * same ATN state with the same prediction context. This transformation is\n\t\t * valid for the following reasons:\n\t\t * <ul>\n\t\t * <li>The closure block cannot contain any epsilon transitions which bypass\n\t\t * the body of the closure, so all states reachable via alternative 1 are\n\t\t * part of the precedence alternatives of the transformed left-recursive\n\t\t * rule.</li>\n\t\t * <li>The \"primary\" portion of a left recursive rule cannot contain an\n\t\t * epsilon transition, so the only way an alternative other than 1 can exist\n\t\t * in a state that is also reachable via alternative 1 is by nesting calls\n\t\t * to the left-recursive rule, with the outer calls not being at the\n\t\t * preferred precedence level. The\n\t\t * {@link ATNConfig#isPrecedenceFilterSuppressed} property marks ATN\n\t\t * configurations which do not meet this condition, and therefore are not\n\t\t * eligible for elimination during the filtering process.</li>\n\t\t * </ul>\n\t\t * </li>\n\t\t * </ol>\n\t\t *\n\t\t * <p>\n\t\t * The prediction context must be considered by this filter to address\n\t\t * situations like the following.\n\t\t * </p>\n\t\t * <code>\n\t\t * <pre>\n\t\t * grammar TA;\n\t\t * prog: statement* EOF;\n\t\t * statement: letterA | statement letterA 'b' ;\n\t\t * letterA: 'a';\n\t\t * </pre>\n\t\t * </code>\n\t\t * <p>\n\t\t * If the above grammar, the ATN state immediately before the token\n\t\t * reference {@code 'a'} in {@code letterA} is reachable from the left edge\n\t\t * of both the primary and closure blocks of the left-recursive rule\n\t\t * {@code statement}. The prediction context associated with each of these\n\t\t * configurations distinguishes between them, and prevents the alternative\n\t\t * which stepped out to {@code prog} (and then back in to {@code statement}\n\t\t * from being eliminated by the filter.\n\t\t * </p>\n\t\t *\n\t\t * @param configs The configuration set computed by\n\t\t * {@link #computeStartState} as the start state for the DFA.\n\t\t * @return The transformed configuration set representing the start state\n\t\t * for a precedence DFA at a particular precedence level (determined by\n\t\t * calling {@link Parser#getPrecedence}).\n\t\t */\n\n\t\tprotected ATNConfigSet ApplyPrecedenceFilter(ATNConfigSet configSet)\n\t\t{\n\t\t\tDictionary<int, PredictionContext> statesFromAlt1 = new Dictionary<int, PredictionContext>();\n\t\t\tATNConfigSet result = new ATNConfigSet(configSet.fullCtx);\n\t\t\tforeach (ATNConfig config in configSet.configs)\n\t\t\t{\n\t\t\t\t// handle alt 1 first\n\t\t\t\tif (config.alt != 1)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tSemanticContext updatedContext = config.semanticContext.EvalPrecedence(parser, context);\n\t\t\t\tif (updatedContext == null)\n\t\t\t\t{\n\t\t\t\t\t// the configuration was eliminated\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tstatesFromAlt1[config.state.stateNumber] = config.context;\n\t\t\t\tif (updatedContext != config.semanticContext)\n\t\t\t\t{\n\t\t\t\t\tresult.Add(new ATNConfig(config, updatedContext), mergeCache);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tresult.Add(config, mergeCache);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach (ATNConfig config in configSet.configs)\n\t\t\t{\n\t\t\t\tif (config.alt == 1)\n\t\t\t\t{\n\t\t\t\t\t// already handled\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!config.IsPrecedenceFilterSuppressed)\n\t\t\t\t{\n\t\t\t\t\t/* In the future, this elimination step could be updated to also\n\t\t\t\t\t * filter the prediction context for alternatives predicting alt>1\n\t\t\t\t\t * (basically a graph subtraction algorithm).\n\t\t\t\t\t */\n\t\t\t\t\tPredictionContext ctx;\n\t\t\t\t\tif (statesFromAlt1.TryGetValue(config.state.stateNumber, out ctx))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ctx != null && ctx.Equals(config.context))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// eliminated\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresult.Add(config, mergeCache);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\tprotected ATNState GetReachableTarget(Transition trans, int ttype)\n\t\t{\n\t\t\tif (trans.Matches(ttype, 0, atn.maxTokenType))\n\t\t\t{\n\t\t\t\treturn trans.target;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\tprotected SemanticContext[] GetPredsForAmbigAlts(BitSet ambigAlts,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ATNConfigSet configSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  int nalts)\n\t\t{\n\t\t\t// REACH=[1|1|[]|0:0, 1|2|[]|0:1]\n\t\t\t/* altToPred starts as an array of all null contexts. The entry at index i\n\t\t\t * corresponds to alternative i. altToPred[i] may have one of three values:\n\t\t\t *   1. null: no ATNConfig c is found such that c.alt==i\n\t\t\t *   2. SemanticContext.Empty.Instance: At least one ATNConfig c exists such that\n\t\t\t *      c.alt==i and c.semanticContext==SemanticContext.Empty.Instance. In other words,\n\t\t\t *      alt i has at least one unpredicated config.\n\t\t\t *   3. Non-NONE Semantic Context: There exists at least one, and for all\n\t\t\t *      ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.Empty.Instance.\n\t\t\t *\n\t\t\t * From this, it is clear that NONE||anything==NONE.\n\t\t\t */\n\t\t\tSemanticContext[] altToPred = new SemanticContext[nalts + 1];\n\t\t\tforeach (ATNConfig c in configSet.configs)\n\t\t\t{\n\t\t\t\tif (ambigAlts[c.alt])\n\t\t\t\t{\n\t\t\t\t\taltToPred[c.alt] = SemanticContext.OrOp(altToPred[c.alt], c.semanticContext);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint nPredAlts = 0;\n\t\t\tfor (int i = 1; i <= nalts; i++)\n\t\t\t{\n\t\t\t\tif (altToPred[i] == null)\n\t\t\t\t{\n\t\t\t\t\taltToPred[i] = SemanticContext.Empty.Instance;\n\t\t\t\t}\n\t\t\t\telse if (altToPred[i] != SemanticContext.Empty.Instance)\n\t\t\t\t{\n\t\t\t\t\tnPredAlts++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//\t\t// Optimize away p||p and p&&p TODO: optimize() was a no-op\n\t\t\t//\t\tfor (int i = 0; i < altToPred.length; i++) {\n\t\t\t//\t\t\taltToPred[i] = altToPred[i].optimize();\n\t\t\t//\t\t}\n\n\t\t\t// nonambig alts are null in altToPred\n\t\t\tif (nPredAlts == 0) altToPred = null;\n\t\t\tif (debug) Console.WriteLine(\"getPredsForAmbigAlts result \" + Arrays.ToString(altToPred));\n\t\t\treturn altToPred;\n\t\t}\n\n\t\tprotected PredPrediction[] GetPredicatePredictions(BitSet ambigAlts,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SemanticContext[] altToPred)\n\t\t{\n\t\t\tList<PredPrediction> pairs = new List<PredPrediction>();\n\t\t\tbool containsPredicate = false;\n\t\t\tfor (int i = 1; i < altToPred.Length; i++)\n\t\t\t{\n\t\t\t\tSemanticContext pred = altToPred[i];\n\n\t\t\t\t// unpredicated is indicated by SemanticContext.Empty.Instance\n\n\t\t\t\tif (ambigAlts != null && ambigAlts[i])\n\t\t\t\t{\n\t\t\t\t\tpairs.Add(new PredPrediction(pred, i));\n\t\t\t\t}\n\t\t\t\tif (pred != SemanticContext.Empty.Instance) containsPredicate = true;\n\t\t\t}\n\n\t\t\tif (!containsPredicate)\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t//\t\tConsole.WriteLine(Arrays.toString(altToPred)+\"->\"+pairs);\n\t\t\treturn pairs.ToArray();\n\t\t}\n\n\t\t/**\n\t\t * This method is used to improve the localization of error messages by\n\t\t * choosing an alternative rather than throwing a\n\t\t * {@link NoViableAltException} in particular prediction scenarios where the\n\t\t * {@link #ERROR} state was reached during ATN simulation.\n\t\t *\n\t\t * <p>\n\t\t * The default implementation of this method uses the following\n\t\t * algorithm to identify an ATN configuration which successfully parsed the\n\t\t * decision entry rule. Choosing such an alternative ensures that the\n\t\t * {@link ParserRuleContext} returned by the calling rule will be complete\n\t\t * and valid, and the syntax error will be reported later at a more\n\t\t * localized location.</p>\n\t\t *\n\t\t * <ul>\n\t\t * <li>If a syntactically valid path or paths reach the end of the decision rule and\n\t\t * they are semantically valid if predicated, return the min associated alt.</li>\n\t\t * <li>Else, if a semantically invalid but syntactically valid path exist\n\t\t * or paths exist, return the minimum associated alt.\n\t\t * </li>\n\t\t * <li>Otherwise, return {@link ATN#INVALID_ALT_NUMBER}.</li>\n\t\t * </ul>\n\t\t *\n\t\t * <p>\n\t\t * In some scenarios, the algorithm described above could predict an\n\t\t * alternative which will result in a {@link FailedPredicateException} in\n\t\t * the parser. Specifically, this could occur if the <em>only</em> configuration\n\t\t * capable of successfully parsing to the end of the decision rule is\n\t\t * blocked by a semantic predicate. By choosing this alternative within\n\t\t * {@link #adaptivePredict} instead of throwing a\n\t\t * {@link NoViableAltException}, the resulting\n\t\t * {@link FailedPredicateException} in the parser will identify the specific\n\t\t * predicate which is preventing the parser from successfully parsing the\n\t\t * decision rule, which helps developers identify and correct logic errors\n\t\t * in semantic predicates.\n\t\t * </p>\n\t\t *\n\t\t * @param configs The ATN configurations which were valid immediately before\n\t\t * the {@link #ERROR} state was reached\n\t\t * @param outerContext The is the \\gamma_0 initial parser context from the paper\n\t\t * or the parser stack at the instant before prediction commences.\n\t\t *\n\t\t * @return The value to return from {@link #adaptivePredict}, or\n\t\t * {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not\n\t\t * identified and {@link #adaptivePredict} should report an error instead.\n\t\t */\n\t\tprotected int GetSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(ATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  ParserRuleContext outerContext)\n\t\t{\n\t\t\tPair<ATNConfigSet, ATNConfigSet> sets =\n\t\t\t\tSplitAccordingToSemanticValidity(configs, outerContext);\n\t\t\tATNConfigSet semValidConfigs = sets.a;\n\t\t\tATNConfigSet semInvalidConfigs = sets.b;\n\t\t\tint alt = getAltThatFinishedDecisionEntryRule(semValidConfigs);\n\t\t\tif (alt != ATN.INVALID_ALT_NUMBER)\n\t\t\t{ // semantically/syntactically viable path exists\n\t\t\t\treturn alt;\n\t\t\t}\n\t\t\t// Is there a syntactically valid path with a failed pred?\n\t\t\tif (semInvalidConfigs.Count > 0)\n\t\t\t{\n\t\t\t\talt = getAltThatFinishedDecisionEntryRule(semInvalidConfigs);\n\t\t\t\tif (alt != ATN.INVALID_ALT_NUMBER)\n\t\t\t\t{ // syntactically viable path exists\n\t\t\t\t\treturn alt;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ATN.INVALID_ALT_NUMBER;\n\t\t}\n\n\t\tprotected int getAltThatFinishedDecisionEntryRule(ATNConfigSet configSet)\n\t\t{\n\t\t\tIntervalSet alts = new IntervalSet();\n\t\t\tforeach (ATNConfig c in configSet.configs)\n\t\t\t{\n\t\t\t\tif (c.OuterContextDepth > 0 || (c.state is RuleStopState && c.context.HasEmptyPath))\n\t\t\t\t{\n\t\t\t\t\talts.Add(c.alt);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (alts.Count == 0) return ATN.INVALID_ALT_NUMBER;\n\t\t\treturn alts.MinElement;\n\t\t}\n\n\t\t/** Walk the list of configurations and split them according to\n\t\t *  those that have preds evaluating to true/false.  If no pred, assume\n\t\t *  true pred and include in succeeded set.  Returns Pair of sets.\n\t\t *\n\t\t *  Create a new set so as not to alter the incoming parameter.\n\t\t *\n\t\t *  Assumption: the input stream has been restored to the starting point\n\t\t *  prediction, which is where predicates need to evaluate.\n\t\t */\n\t\tprotected Pair<ATNConfigSet, ATNConfigSet> SplitAccordingToSemanticValidity(\n\t\t\t\t\t\t\t\t\t\t\t\t  ATNConfigSet configSet,\n\t\t\tParserRuleContext outerContext)\n\t\t{\n\t\t\tATNConfigSet succeeded = new ATNConfigSet(configSet.fullCtx);\n\t\t\tATNConfigSet failed = new ATNConfigSet(configSet.fullCtx);\n\t\t\tforeach (ATNConfig c in configSet.configs)\n\t\t\t{\n\t\t\t\tif (c.semanticContext != SemanticContext.Empty.Instance)\n\t\t\t\t{\n\t\t\t\t\tbool predicateEvaluationResult = EvalSemanticContext(c.semanticContext, outerContext, c.alt, configSet.fullCtx);\n\t\t\t\t\tif (predicateEvaluationResult)\n\t\t\t\t\t{\n\t\t\t\t\t\tsucceeded.Add(c);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfailed.Add(c);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsucceeded.Add(c);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Pair<ATNConfigSet, ATNConfigSet>(succeeded, failed);\n\t\t}\n\n\t\t/** Look through a list of predicate/alt pairs, returning alts for the\n\t\t *  pairs that win. A {@code NONE} predicate indicates an alt containing an\n\t\t *  unpredicated config which behaves as \"always true.\" If !complete\n\t\t *  then we stop at the first predicate that evaluates to true. This\n\t\t *  includes pairs with null predicates.\n\t\t */\n\t\tprotected virtual BitSet EvalSemanticContext(PredPrediction[] predPredictions,\n\t\t\t\t\t\t\t\t\t\t  ParserRuleContext outerContext,\n\t\t\t\t\t\t\t\t\t\t  bool complete)\n\t\t{\n\t\t\tBitSet predictions = new BitSet();\n\t\t\tforeach (PredPrediction pair in predPredictions)\n\t\t\t{\n\t\t\t\tif (pair.pred == SemanticContext.Empty.Instance)\n\t\t\t\t{\n\t\t\t\t\tpredictions[pair.alt] = true;\n\t\t\t\t\tif (!complete)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbool fullCtx = false; // in dfa\n\t\t\t\tbool predicateEvaluationResult = EvalSemanticContext(pair.pred, outerContext, pair.alt, fullCtx);\n\t\t\t\tif (debug || dfa_debug)\n\t\t\t\t{\n\t\t\t\t\tConsole.WriteLine(\"eval pred \" + pair + \"=\" + predicateEvaluationResult);\n\t\t\t\t}\n\n\t\t\t\tif (predicateEvaluationResult)\n\t\t\t\t{\n\t\t\t\t\tif (debug || dfa_debug) Console.WriteLine(\"PREDICT \" + pair.alt);\n\t\t\t\t\tpredictions[pair.alt] = true;\n\t\t\t\t\tif (!complete)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn predictions;\n\t\t}\n\n\t\t/**\n\t\t * Evaluate a semantic context within a specific parser context.\n\t\t *\n\t\t * <p>\n\t\t * This method might not be called for every semantic context evaluated\n\t\t * during the prediction process. In particular, we currently do not\n\t\t * evaluate the following but it may change in the future:</p>\n\t\t *\n\t\t * <ul>\n\t\t * <li>Precedence predicates (represented by\n\t\t * {@link SemanticContext.PrecedencePredicate}) are not currently evaluated\n\t\t * through this method.</li>\n\t\t * <li>Operator predicates (represented by {@link SemanticContext.AND} and\n\t\t * {@link SemanticContext.OR}) are evaluated as a single semantic\n\t\t * context, rather than evaluating the operands individually.\n\t\t * Implementations which require evaluation results from individual\n\t\t * predicates should override this method to explicitly handle evaluation of\n\t\t * the operands within operator predicates.</li>\n\t\t * </ul>\n\t\t *\n\t\t * @param pred The semantic context to evaluate\n\t\t * @param parserCallStack The parser context in which to evaluate the\n\t\t * semantic context\n\t\t * @param alt The alternative which is guarded by {@code pred}\n\t\t * @param fullCtx {@code true} if the evaluation is occurring during LL\n\t\t * prediction; otherwise, {@code false} if the evaluation is occurring\n\t\t * during SLL prediction\n\t\t *\n\t\t * @since 4.3\n\t\t */\n\t\tprotected virtual bool EvalSemanticContext(SemanticContext pred, ParserRuleContext parserCallStack, int alt, bool fullCtx)\n\t\t{\n\t\t\treturn pred.Eval(parser, parserCallStack);\n\t\t}\n\n\t\t/* TODO: If we are doing predicates, there is no point in pursuing\n\t\t\t closure operations if we reach a DFA state that uniquely predicts\n\t\t\t alternative. We will not be caching that DFA state and it is a\n\t\t\t waste to pursue the closure. Might have to advance when we do\n\t\t\t ambig detection thought :(\n\t\t\t  */\n\n\t\tprotected void Closure(ATNConfig config,\n\t\t\t\t\t\t\t   ATNConfigSet configs,\n\t\t\t\t\t\t\t   HashSet<ATNConfig> closureBusy,\n\t\t\t\t\t\t\t   bool collectPredicates,\n\t\t\t\t\t\t\t   bool fullCtx,\n\t\t\t\t\t\t\t   bool treatEofAsEpsilon)\n\t\t{\n\t\t\tint initialDepth = 0;\n\t\t\tClosureCheckingStopState(config, configs, closureBusy, collectPredicates,\n\t\t\t\t\t\t\t\t\t fullCtx,\n\t\t\t\t\t\t\t\t\t initialDepth, treatEofAsEpsilon);\n\t\t}\n\n\t\tprotected void ClosureCheckingStopState(ATNConfig config,\n\t\t\t\t\t\t\t\t\t\t\t\tATNConfigSet configSet,\n\t\t\t\t\t\t\t\t\t\t\t\tHashSet<ATNConfig> closureBusy,\n\t\t\t\t\t\t\t\t\t\t\t\tbool collectPredicates,\n\t\t\t\t\t\t\t\t\t\t\t\tbool fullCtx,\n\t\t\t\t\t\t\t\t\t\t\t\tint depth,\n\t\t\t\t\t\t\t\t\t\t\t\tbool treatEofAsEpsilon)\n\t\t{\n\t\t\tif (trace_atn_sim)\n\t\t\t\tConsole.WriteLine(\"closure(\" + config.ToString(parser, true) + \")\");\n\n\t\t\tif (config.state is RuleStopState)\n\t\t\t{\n\t\t\t\t// We hit rule end. If we have context info, use it\n\t\t\t\t// run thru all possible stack tops in ctx\n\t\t\t\tif (!config.context.IsEmpty)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i < config.context.Size; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (config.context.GetReturnState(i) == PredictionContext.EMPTY_RETURN_STATE)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (fullCtx)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfigSet.Add(new ATNConfig(config, config.state, EmptyPredictionContext.Instance), mergeCache);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t// we have no context info, just chase follow links (if greedy)\n\t\t\t\t\t\t\t\tif (debug) Console.WriteLine(\"FALLING off rule \" +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  GetRuleName(config.state.ruleIndex));\n\t\t\t\t\t\t\t\tClosure_(config, configSet, closureBusy, collectPredicates,\n\t\t\t\t\t\t\t\t\t\t fullCtx, depth, treatEofAsEpsilon);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tATNState returnState = atn.states[config.context.GetReturnState(i)];\n\t\t\t\t\t\tPredictionContext newContext = config.context.GetParent(i); // \"pop\" return state\n\t\t\t\t\t\tATNConfig c = new ATNConfig(returnState, config.alt, newContext, config.semanticContext);\n\t\t\t\t\t\t// While we have context to pop back from, we may have\n\t\t\t\t\t\t// gotten that context AFTER having falling off a rule.\n\t\t\t\t\t\t// Make sure we track that we are now out of context.\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// This assignment also propagates the\n\t\t\t\t\t\t// isPrecedenceFilterSuppressed() value to the new\n\t\t\t\t\t\t// configuration.\n\t\t\t\t\t\tc.reachesIntoOuterContext = config.OuterContextDepth;\n\t\t\t\t\t\tClosureCheckingStopState(c, configSet, closureBusy, collectPredicates,\n\t\t\t\t\t\t\t\t\t\t\t\t fullCtx, depth - 1, treatEofAsEpsilon);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (fullCtx)\n\t\t\t\t{\n\t\t\t\t\t// reached end of start rule\n\t\t\t\t\tconfigSet.Add(config, mergeCache);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// else if we have no context info, just chase follow links (if greedy)\n\t\t\t\t\tif (debug) Console.WriteLine(\"FALLING off rule \" +\n\t\t\t\t\t\t\t\t\t\t\t\t  GetRuleName(config.state.ruleIndex));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tClosure_(config, configSet, closureBusy, collectPredicates,\n\t\t\t\t\t fullCtx, depth, treatEofAsEpsilon);\n\t\t}\n\n\t\t/** Do the actual work of walking epsilon edges */\n\t\tprotected void Closure_(ATNConfig config,\n\t\t\t\t\t\t\t\tATNConfigSet configs,\n\t\t\t\t\t\t\t\tHashSet<ATNConfig> closureBusy,\n\t\t\t\t\t\t\t\tbool collectPredicates,\n\t\t\t\t\t\t\t\tbool fullCtx,\n\t\t\t\t\t\t\t\tint depth,\n\t\t\t\t\t\t\t\tbool treatEofAsEpsilon)\n\t\t{\n\t\t\tATNState p = config.state;\n\t\t\t// optimization\n\t\t\tif (!p.OnlyHasEpsilonTransitions)\n\t\t\t{\n\t\t\t\tconfigs.Add(config, mergeCache);\n\t\t\t\t// make sure to not return here, because EOF transitions can act as\n\t\t\t\t// both epsilon transitions and non-epsilon transitions.\n\t\t\t\t//            if ( debug ) Console.WriteLine(\"added config \"+configs);\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < p.NumberOfTransitions; i++)\n\t\t\t{\n\t\t\t\tif (i == 0 && CanDropLoopEntryEdgeInLeftRecursiveRule(config)) continue;\n\n\t\t\t\tTransition t = p.Transition(i);\n\t\t\t\tbool continueCollecting =\n\t\t\t\t\t!(t is ActionTransition) && collectPredicates;\n\t\t\t\tATNConfig c = GetEpsilonTarget(config, t, continueCollecting,\n\t\t\t\t\t\t\t\t\t\t\t   depth == 0, fullCtx, treatEofAsEpsilon);\n\t\t\t\tif (c != null)\n\t\t\t\t{\n\t\t\t\t\tint newDepth = depth;\n\t\t\t\t\tif (config.state is RuleStopState)\n\t\t\t\t\t{\n\t\t\t\t\t\t// target fell off end of rule; mark resulting c as having dipped into outer context\n\t\t\t\t\t\t// We can't get here if incoming config was rule stop and we had context\n\t\t\t\t\t\t// track how far we dip into outer context.  Might\n\t\t\t\t\t\t// come in handy and we avoid evaluating context dependent\n\t\t\t\t\t\t// preds if this is > 0.\n\n\t\t\t\t\t\tif (thisDfa != null && thisDfa.IsPrecedenceDfa)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint outermostPrecedenceReturn = ((EpsilonTransition)t).OutermostPrecedenceReturn;\n\t\t\t\t\t\t\tif (outermostPrecedenceReturn == thisDfa.atnStartState.ruleIndex)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tc.SetPrecedenceFilterSuppressed(true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tc.reachesIntoOuterContext++;\n\t\t\t\t\t\tif (!closureBusy.Add(c))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// avoid infinite recursion for right-recursive rules\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconfigs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method\n\t\t\t\t\t\tnewDepth--;\n\t\t\t\t\t\tif (debug)\n\t\t\t\t\t\t\tConsole.WriteLine(\"dips into outer ctx: \" + c);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\n\t\t\t\t\t\tif (!t.IsEpsilon && !closureBusy.Add(c))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// avoid infinite recursion for EOF* and EOF+\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (t is RuleTransition)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// latch when newDepth goes negative - once we step out of the entry context we can't return\n\t\t\t\t\t\t\tif (newDepth >= 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnewDepth++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tClosureCheckingStopState(c, configs, closureBusy, continueCollecting,\n\t\t\t\t\t\t\t\t\t\t\t fullCtx, newDepth, treatEofAsEpsilon);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/** Implements first-edge (loop entry) elimination as an optimization\n\t\t *  during closure operations.  See antlr/antlr4#1398.\n\t\t *\n\t\t * The optimization is to avoid adding the loop entry config when\n\t\t * the exit path can only lead back to the same\n\t\t * StarLoopEntryState after popping context at the rule end state\n\t\t * (traversing only epsilon edges, so we're still in closure, in\n\t\t * this same rule).\n\t\t *\n\t\t * We need to detect any state that can reach loop entry on\n\t\t * epsilon w/o exiting rule. We don't have to look at FOLLOW\n\t\t * links, just ensure that all stack tops for config refer to key\n\t\t * states in LR rule.\n\t\t *\n\t\t * To verify we are in the right situation we must first check\n\t\t * closure is at a StarLoopEntryState generated during LR removal.\n\t\t * Then we check that each stack top of context is a return state\n\t\t * from one of these cases:\n\t\t *\n\t\t *   1. 'not' expr, '(' type ')' expr. The return state points at loop entry state\n\t\t *   2. expr op expr. The return state is the block end of internal block of (...)*\n\t\t *   3. 'between' expr 'and' expr. The return state of 2nd expr reference.\n\t\t *      That state points at block end of internal block of (...)*.\n\t\t *   4. expr '?' expr ':' expr. The return state points at block end,\n\t\t *      which points at loop entry state.\n\t\t *\n\t\t * If any is true for each stack top, then closure does not add a\n\t\t * config to the current config set for edge[0], the loop entry branch.\n\t\t *\n\t\t *  Conditions fail if any context for the current config is:\n\t\t *\n\t\t *   a. empty (we'd fall out of expr to do a global FOLLOW which could\n\t\t *      even be to some weird spot in expr) or,\n\t\t *   b. lies outside of expr or,\n\t\t *   c. lies within expr but at a state not the BlockEndState\n\t\t *   generated during LR removal\n\t\t *\n\t\t * Do we need to evaluate predicates ever in closure for this case?\n\t\t *\n\t\t * No. Predicates, including precedence predicates, are only\n\t\t * evaluated when computing a DFA start state. I.e., only before\n\t\t * the lookahead (but not parser) consumes a token.\n\t\t *\n\t\t * There are no epsilon edges allowed in LR rule alt blocks or in\n\t\t * the \"primary\" part (ID here). If closure is in\n\t\t * StarLoopEntryState any lookahead operation will have consumed a\n\t\t * token as there are no epsilon-paths that lead to\n\t\t * StarLoopEntryState. We do not have to evaluate predicates\n\t\t * therefore if we are in the generated StarLoopEntryState of a LR\n\t\t * rule. Note that when making a prediction starting at that\n\t\t * decision point, decision d=2, compute-start-state performs\n\t\t * closure starting at edges[0], edges[1] emanating from\n\t\t * StarLoopEntryState. That means it is not performing closure on\n\t\t * StarLoopEntryState during compute-start-state.\n\t\t *\n\t\t * How do we know this always gives same prediction answer?\n\t\t *\n\t\t * Without predicates, loop entry and exit paths are ambiguous\n\t\t * upon remaining input +b (in, say, a+b). Either paths lead to\n\t\t * valid parses. Closure can lead to consuming + immediately or by\n\t\t * falling out of this call to expr back into expr and loop back\n\t\t * again to StarLoopEntryState to match +b. In this special case,\n\t\t * we choose the more efficient path, which is to take the bypass\n\t\t * path.\n\t\t *\n\t\t * The lookahead language has not changed because closure chooses\n\t\t * one path over the other. Both paths lead to consuming the same\n\t\t * remaining input during a lookahead operation. If the next token\n\t\t * is an operator, lookahead will enter the choice block with\n\t\t * operators. If it is not, lookahead will exit expr. Same as if\n\t\t * closure had chosen to enter the choice block immediately.\n\t\t *\n\t\t * Closure is examining one config (some loopentrystate, some alt,\n\t\t * context) which means it is considering exactly one alt. Closure\n\t\t * always copies the same alt to any derived configs.\n\t\t *\n\t\t * How do we know this optimization doesn't mess up precedence in\n\t\t * our parse trees?\n\t\t *\n\t\t * Looking through expr from left edge of stat only has to confirm\n\t\t * that an input, say, a+b+c; begins with any valid interpretation\n\t\t * of an expression. The precedence actually doesn't matter when\n\t\t * making a decision in stat seeing through expr. It is only when\n\t\t * parsing rule expr that we must use the precedence to get the\n\t\t * right interpretation and, hence, parse tree.\n\t\t *\n\t\t * @since 4.6\n\t\t */\n\t\tprotected bool CanDropLoopEntryEdgeInLeftRecursiveRule(ATNConfig config)\n\t\t{\n\t\t\tATNState p = config.state;\n\t\t\t// First check to see if we are in StarLoopEntryState generated during\n\t\t\t// left-recursion elimination. For efficiency, also check if\n\t\t\t// the context has an empty stack case. If so, it would mean\n\t\t\t// global FOLLOW so we can't perform optimization\n\t\t\tif (p.StateType != StateType.StarLoopEntry ||\n\t\t\t    !((StarLoopEntryState)p).isPrecedenceDecision || // Are we the special loop entry/exit state?\n\t\t\t\t config.context.IsEmpty ||                      // If SLL wildcard\n\t\t\t\t config.context.HasEmptyPath)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Require all return states to return back to the same rule\n\t\t\t// that p is in.\n\t\t\tint numCtxs = config.context.Size;\n\t\t\tfor (int i = 0; i < numCtxs; i++)\n\t\t\t{ // for each stack context\n\t\t\t\tATNState returnState = atn.states[config.context.GetReturnState(i)];\n\t\t\t\tif (returnState.ruleIndex != p.ruleIndex) return false;\n\t\t\t}\n\n\t\t\tBlockStartState decisionStartState = (BlockStartState)p.Transition(0).target;\n\t\t\tint blockEndStateNum = decisionStartState.endState.stateNumber;\n\t\t\tBlockEndState blockEndState = (BlockEndState)atn.states[blockEndStateNum];\n\n\t\t\t// Verify that the top of each stack context leads to loop entry/exit\n\t\t\t// state through epsilon edges and w/o leaving rule.\n\t\t\tfor (int i = 0; i < numCtxs; i++)\n\t\t\t{                           // for each stack context\n\t\t\t\tint returnStateNumber = config.context.GetReturnState(i);\n\t\t\t\tATNState returnState = atn.states[returnStateNumber];\n\t\t\t\t// all states must have single outgoing epsilon edge\n\t\t\t\tif (returnState.NumberOfTransitions != 1 ||\n\t\t\t\t\t!returnState.Transition(0).IsEpsilon)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t// Look for prefix op case like 'not expr', (' type ')' expr\n\t\t\t\tATNState returnStateTarget = returnState.Transition(0).target;\n\t\t\t\tif (returnState.StateType == StateType.BlockEnd && returnStateTarget == p)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Look for 'expr op expr' or case where expr's return state is block end\n\t\t\t\t// of (...)* internal block; the block end points to loop back\n\t\t\t\t// which points to p but we don't need to check that\n\t\t\t\tif (returnState == blockEndState)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Look for ternary expr ? expr : expr. The return state points at block end,\n\t\t\t\t// which points at loop entry state\n\t\t\t\tif (returnStateTarget == blockEndState)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Look for complex prefix 'between expr and expr' case where 2nd expr's\n\t\t\t\t// return state points at block end state of (...)* internal block\n\t\t\t\tif (returnStateTarget.StateType == StateType.BlockEnd &&\n\t\t\t\t\t returnStateTarget.NumberOfTransitions == 1 &&\n\t\t\t\t\t returnStateTarget.Transition(0).IsEpsilon &&\n\t\t\t\t\t returnStateTarget.Transition(0).target == p)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// anything else ain't conforming\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\tpublic string GetRuleName(int index)\n\t\t{\n\t\t\tif (parser != null && index >= 0) return parser.RuleNames[index];\n\t\t\treturn \"<rule \" + index + \">\";\n\t\t}\n\n\n\t\tprotected ATNConfig GetEpsilonTarget(ATNConfig config,\n\t\t\t\t\t\t\t\t\t\t  Transition t,\n\t\t\t\t\t\t\t\t\t\t  bool collectPredicates,\n\t\t\t\t\t\t\t\t\t\t  bool inContext,\n\t\t\t\t\t\t\t\t\t\t  bool fullCtx,\n\t\t\t\t\t\t\t\t\t\t  bool treatEofAsEpsilon)\n\t\t{\n\t\t\tswitch (t.TransitionType)\n\t\t\t{\n\t\t\t\tcase TransitionType.RULE:\n\t\t\t\t\treturn RuleTransition(config, (RuleTransition)t);\n\n\t\t\t\tcase TransitionType.PRECEDENCE:\n\t\t\t\t\treturn PrecedenceTransition(config, (PrecedencePredicateTransition)t, collectPredicates, inContext, fullCtx);\n\n\t\t\t\tcase TransitionType.PREDICATE:\n\t\t\t\t\treturn PredTransition(config, (PredicateTransition)t,\n\t\t\t\t\t\t\t\t\t\t  collectPredicates,\n\t\t\t\t\t\t\t\t\t\t  inContext,\n\t\t\t\t\t\t\t\t\t\t  fullCtx);\n\n\t\t\t\tcase TransitionType.ACTION:\n\t\t\t\t\treturn ActionTransition(config, (ActionTransition)t);\n\n\t\t\t\tcase TransitionType.EPSILON:\n\t\t\t\t\treturn new ATNConfig(config, t.target);\n\n\t\t\t\tcase TransitionType.ATOM:\n\t\t\t\tcase TransitionType.RANGE:\n\t\t\t\tcase TransitionType.SET:\n\t\t\t\t\t// EOF transitions act like epsilon transitions after the first EOF\n\t\t\t\t\t// transition is traversed\n\t\t\t\t\tif (treatEofAsEpsilon)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (t.Matches(TokenConstants.EOF, 0, 1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn new ATNConfig(config, t.target);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn null;\n\n\t\t\t\tdefault:\n\t\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\n\t\tprotected ATNConfig ActionTransition(ATNConfig config, ActionTransition t)\n\t\t{\n\t\t\tif (debug) Console.WriteLine(\"ACTION edge \" + t.ruleIndex + \":\" + t.actionIndex);\n\t\t\treturn new ATNConfig(config, t.target);\n\t\t}\n\n\n\t\tpublic ATNConfig PrecedenceTransition(ATNConfig config,\n\t\t\t\t\t\t\t\t\t\tPrecedencePredicateTransition pt,\n\t\t\t\t\t\t\t\t\t\tbool collectPredicates,\n\t\t\t\t\t\t\t\t\t\tbool inContext,\n\t\t\t\t\t\t\t\t\t\tbool fullCtx)\n\t\t{\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"PRED (collectPredicates=\" + collectPredicates + \") \" +\n\t\t\t\t\t\tpt.precedence + \">=_p\" +\n\t\t\t\t\t\t\", ctx dependent=true\");\n\t\t\t\tif (parser != null)\n\t\t\t\t{\n\t\t\t\t\tConsole.WriteLine(\"context surrounding pred is \" +\n\t\t\t\t\t\t\t\t\t   StaticUtils.ToString(parser.GetRuleInvocationStack()));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tATNConfig c = null;\n\t\t\tif (collectPredicates && inContext)\n\t\t\t{\n\t\t\t\tif (fullCtx)\n\t\t\t\t{\n\t\t\t\t\t// In full context mode, we can evaluate predicates on-the-fly\n\t\t\t\t\t// during closure, which dramatically reduces the size of\n\t\t\t\t\t// the config sets. It also obviates the need to test predicates\n\t\t\t\t\t// later during conflict resolution.\n\t\t\t\t\tint currentPosition = input.Index;\n\t\t\t\t\tinput.Seek(startIndex);\n\t\t\t\t\tbool predSucceeds = EvalSemanticContext(pt.Predicate, context, config.alt, fullCtx);\n\t\t\t\t\tinput.Seek(currentPosition);\n\t\t\t\t\tif (predSucceeds)\n\t\t\t\t\t{\n\t\t\t\t\t\tc = new ATNConfig(config, pt.target); // no pred context\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSemanticContext newSemCtx = SemanticContext.AndOp(config.semanticContext, pt.Predicate);\n\t\t\t\t\tc = new ATNConfig(config, pt.target, newSemCtx);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tc = new ATNConfig(config, pt.target);\n\t\t\t}\n\n\t\t\tif (debug) Console.WriteLine(\"config from pred transition=\" + c);\n\t\t\treturn c;\n\t\t}\n\n\n\t\tprotected ATNConfig PredTransition(ATNConfig config,\n\t\t\t\t\t\t\t\t\t\tPredicateTransition pt,\n\t\t\t\t\t\t\t\t\t\tbool collectPredicates,\n\t\t\t\t\t\t\t\t\t\tbool inContext,\n\t\t\t\t\t\t\t\t\t\tbool fullCtx)\n\t\t{\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"PRED (collectPredicates=\" + collectPredicates + \") \" +\n\t\t\t\t\t\tpt.ruleIndex + \":\" + pt.predIndex +\n\t\t\t\t\t\t\", ctx dependent=\" + pt.isCtxDependent);\n\t\t\t\tif (parser != null)\n\t\t\t\t{\n\t\t\t\t\tConsole.WriteLine(\"context surrounding pred is \" +\n\t\t\t\t\t\t\t\t\t   StaticUtils.ToString(parser.GetRuleInvocationStack()));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tATNConfig c = null;\n\t\t\tif (collectPredicates &&\n\t\t\t\t (!pt.isCtxDependent || (pt.isCtxDependent && inContext)))\n\t\t\t{\n\t\t\t\tif (fullCtx)\n\t\t\t\t{\n\t\t\t\t\t// In full context mode, we can evaluate predicates on-the-fly\n\t\t\t\t\t// during closure, which dramatically reduces the size of\n\t\t\t\t\t// the config sets. It also obviates the need to test predicates\n\t\t\t\t\t// later during conflict resolution.\n\t\t\t\t\tint currentPosition = input.Index;\n\t\t\t\t\tinput.Seek(startIndex);\n\t\t\t\t\tbool predSucceeds = EvalSemanticContext(pt.Predicate, context, config.alt, fullCtx);\n\t\t\t\t\tinput.Seek(currentPosition);\n\t\t\t\t\tif (predSucceeds)\n\t\t\t\t\t{\n\t\t\t\t\t\tc = new ATNConfig(config, pt.target); // no pred context\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSemanticContext newSemCtx = SemanticContext.AndOp(config.semanticContext, pt.Predicate);\n\t\t\t\t\tc = new ATNConfig(config, pt.target, newSemCtx);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tc = new ATNConfig(config, pt.target);\n\t\t\t}\n\n\t\t\tif (debug) Console.WriteLine(\"config from pred transition=\" + c);\n\t\t\treturn c;\n\t\t}\n\n\n\t\tprotected ATNConfig RuleTransition(ATNConfig config, RuleTransition t)\n\t\t{\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"CALL rule \" + GetRuleName(t.target.ruleIndex) +\n\t\t\t\t\t\t\t\t   \", ctx=\" + config.context);\n\t\t\t}\n\n\t\t\tATNState returnState = t.followState;\n\t\t\tPredictionContext newContext =\n\t\t\t\tSingletonPredictionContext.Create(config.context, returnState.stateNumber);\n\t\t\treturn new ATNConfig(config, t.target, newContext);\n\t\t}\n\n\t\t/**\n\t\t * Gets a {@link BitSet} containing the alternatives in {@code configs}\n\t\t * which are part of one or more conflicting alternative subsets.\n\t\t *\n\t\t * @param configs The {@link ATNConfigSet} to analyze.\n\t\t * @return The alternatives in {@code configs} which are part of one or more\n\t\t * conflicting alternative subsets. If {@code configs} does not contain any\n\t\t * conflicting subsets, this method returns an empty {@link BitSet}.\n\t\t */\n\t\tprotected BitSet GetConflictingAlts(ATNConfigSet configSet)\n\t\t{\n\t\t\tICollection<BitSet> altsets = PredictionMode.GetConflictingAltSubsets(configSet.configs);\n\t\t\treturn PredictionMode.GetAlts(altsets);\n\t\t}\n\n\t\t/**\n\t\t Sam pointed out a problem with the previous definition, v3, of\n\t\t ambiguous states. If we have another state associated with conflicting\n\t\t alternatives, we should keep going. For example, the following grammar\n\n\t\t s : (ID | ID ID?) ';' ;\n\n\t\t When the ATN simulation reaches the state before ';', it has a DFA\n\t\t state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally\n\t\t 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node\n\t\t because alternative to has another way to continue, via [6|2|[]].\n\t\t The key is that we have a single state that has config's only associated\n\t\t with a single alternative, 2, and crucially the state transitions\n\t\t among the configurations are all non-epsilon transitions. That means\n\t\t we don't consider any conflicts that include alternative 2. So, we\n\t\t ignore the conflict between alts 1 and 2. We ignore a set of\n\t\t conflicting alts when there is an intersection with an alternative\n\t\t associated with a single alt state in the state→config-list map.\n\n\t\t It's also the case that we might have two conflicting configurations but\n\t\t also a 3rd nonconflicting configuration for a different alternative:\n\t\t [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:\n\n\t\t a : A | A | A B ;\n\n\t\t After matching input A, we reach the stop state for rule A, state 1.\n\t\t State 8 is the state right before B. Clearly alternatives 1 and 2\n\t\t conflict and no amount of further lookahead will separate the two.\n\t\t However, alternative 3 will be able to continue and so we do not\n\t\t stop working on this state. In the previous example, we're concerned\n\t\t with states associated with the conflicting alternatives. Here alt\n\t\t 3 is not associated with the conflicting configs, but since we can continue\n\t\t looking for input reasonably, I don't declare the state done. We\n\t\t ignore a set of conflicting alts when we have an alternative\n\t\t that we still need to pursue.\n\t\t */\n\t\tprotected BitSet GetConflictingAltsOrUniqueAlt(ATNConfigSet configSet)\n\t\t{\n\t\t\tBitSet conflictingAlts;\n\t\t\tif (configSet.uniqueAlt != ATN.INVALID_ALT_NUMBER)\n\t\t\t{\n\t\t\t\tconflictingAlts = new BitSet();\n\t\t\t\tconflictingAlts[configSet.uniqueAlt] = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconflictingAlts = configSet.conflictingAlts;\n\t\t\t}\n\t\t\treturn conflictingAlts;\n\t\t}\n\n\n\t\tpublic string GetTokenName(int t)\n\t\t{\n\t\t\tif (t == TokenConstants.EOF)\n\t\t\t{\n\t\t\t\treturn \"EOF\";\n\t\t\t}\n\n\t\t\tIVocabulary vocabulary = parser != null ? parser.Vocabulary : Vocabulary.EmptyVocabulary;\n\t\t\tString displayName = vocabulary.GetDisplayName(t);\n\t\t\tif (displayName.Equals(t.ToString()))\n\t\t\t{\n\t\t\t\treturn displayName;\n\t\t\t}\n\n\t\t\treturn displayName + \"<\" + t + \">\";\n\t\t}\n\n\t\tpublic string GetLookaheadName(ITokenStream input)\n\t\t{\n\t\t\treturn GetTokenName(input.LA(1));\n\t\t}\n\n\t\t/** Used for debugging in adaptivePredict around execATN but I cut\n\t\t *  it out for clarity now that alg. works well. We can leave this\n\t\t *  \"dead\" code for a bit.\n\t\t */\n\t\tpublic void DumpDeadEndConfigs(NoViableAltException nvae)\n\t\t{\n            System.Console.Error.WriteLine(\"dead end configs: \");\n            foreach (ATNConfig c in nvae.DeadEndConfigs.configs)\n\t\t\t{\n\t\t\t\tString trans = \"no edges\";\n\t\t\t\tif (c.state.NumberOfTransitions > 0)\n\t\t\t\t{\n\t\t\t\t\tTransition t = c.state.Transition(0);\n\t\t\t\t\tif (t is AtomTransition)\n\t\t\t\t\t{\n\t\t\t\t\t\tAtomTransition at = (AtomTransition)t;\n\t\t\t\t\t\ttrans = \"Atom \" + GetTokenName(at.token);\n\t\t\t\t\t}\n\t\t\t\t\telse if (t is SetTransition)\n\t\t\t\t\t{\n\t\t\t\t\t\tSetTransition st = (SetTransition)t;\n\t\t\t\t\t\tbool not = st is NotSetTransition;\n\t\t\t\t\t\ttrans = (not ? \"~\" : \"\") + \"Set \" + st.set.ToString();\n\t\t\t\t\t}\n\t\t\t\t}\n\n                System.Console.Error.WriteLine(c.ToString(parser, true) + \":\" + trans);\n\t\t\t}\n\t\t}\n\n\n\t\tprotected NoViableAltException NoViableAlt(ITokenStream input,\n\t\t\t\t\t\t\t\t\t\t\t\tParserRuleContext outerContext,\n\t\t\t\t\t\t\t\t\t\t\t\tATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t\t\tint startIndex)\n\t\t{\n\t\t\treturn new NoViableAltException(parser, input,\n\t\t\t\t\t\t\t\t\t\t\t\tinput.Get(startIndex),\n\t\t\t\t\t\t\t\t\t\t\t\tinput.LT(1),\n\t\t\t\t\t\t\t\t\t\t\t\tconfigs, outerContext);\n\t\t}\n\n\t\tprotected static int GetUniqueAlt(ATNConfigSet configSet)\n\t\t{\n\t\t\tint alt = ATN.INVALID_ALT_NUMBER;\n\t\t\tforeach (ATNConfig c in configSet.configs)\n\t\t\t{\n\t\t\t\tif (alt == ATN.INVALID_ALT_NUMBER)\n\t\t\t\t{\n\t\t\t\t\talt = c.alt; // found first alt\n\t\t\t\t}\n\t\t\t\telse if (c.alt != alt)\n\t\t\t\t{\n\t\t\t\t\treturn ATN.INVALID_ALT_NUMBER;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn alt;\n\t\t}\n\n\t\t/**\n\t\t * Add an edge to the DFA, if possible. This method calls\n\t\t * {@link #addDFAState} to ensure the {@code to} state is present in the\n\t\t * DFA. If {@code from} is {@code null}, or if {@code t} is outside the\n\t\t * range of edges that can be represented in the DFA tables, this method\n\t\t * returns without adding the edge to the DFA.\n\t\t *\n\t\t * <p>If {@code to} is {@code null}, this method returns {@code null}.\n\t\t * Otherwise, this method returns the {@link DFAState} returned by calling\n\t\t * {@link #addDFAState} for the {@code to} state.</p>\n\t\t *\n\t\t * @param dfa The DFA\n\t\t * @param from The source state for the edge\n\t\t * @param t The input symbol\n\t\t * @param to The target state for the edge\n\t\t *\n\t\t * @return If {@code to} is {@code null}, this method returns {@code null};\n\t\t * otherwise this method returns the result of calling {@link #addDFAState}\n\t\t * on {@code to}\n\t\t */\n\t\tprotected DFAState AddDFAEdge(DFA dfa,\n\t\t\t\t\t\t\t\t\t  DFAState from,\n\t\t\t\t\t\t\t\t\t  int t,\n\t\t\t\t\t\t\t\t\t  DFAState to)\n\t\t{\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"EDGE \" + from + \" -> \" + to + \" upon \" + GetTokenName(t));\n\t\t\t}\n\n\t\t\tif (to == null)\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tto = AddDFAState(dfa, to); // used existing if possible not incoming\n\t\t\tif (from == null || t < -1 || t > atn.maxTokenType)\n\t\t\t{\n\t\t\t\treturn to;\n\t\t\t}\n\n\t\t\tlock (from)\n\t\t\t{\n\t\t\t\tif (from.edges == null)\n\t\t\t\t{\n\t\t\t\t\tfrom.edges = new DFAState[atn.maxTokenType + 1 + 1];\n\t\t\t\t}\n\n\t\t\t\tfrom.edges[t + 1] = to; // connect\n\t\t\t}\n\n\t\t\tif (debug)\n\t\t\t{\n\t\t\t\tConsole.WriteLine(\"DFA=\\n\" + dfa.ToString(parser != null ? parser.Vocabulary : Vocabulary.EmptyVocabulary));\n\t\t\t}\n\n\t\t\treturn to;\n\t\t}\n\n\t\t/**\n\t\t * Add state {@code D} to the DFA if it is not already present, and return\n\t\t * the actual instance stored in the DFA. If a state equivalent to {@code D}\n\t\t * is already in the DFA, the existing state is returned. Otherwise this\n\t\t * method returns {@code D} after adding it to the DFA.\n\t\t *\n\t\t * <p>If {@code D} is {@link #ERROR}, this method returns {@link #ERROR} and\n\t\t * does not change the DFA.</p>\n\t\t *\n\t\t * @param dfa The dfa\n\t\t * @param D The DFA state to add\n\t\t * @return The state stored in the DFA. This will be either the existing\n\t\t * state if {@code D} is already in the DFA, or {@code D} itself if the\n\t\t * state was not already present.\n\t\t */\n\t\tprotected DFAState AddDFAState(DFA dfa, DFAState D)\n\t\t{\n\t\t\tif (D == ERROR)\n\t\t\t{\n\t\t\t\treturn D;\n\t\t\t}\n\n\t\t\tlock (dfa.states)\n\t\t\t{\n\t\t\t\tDFAState existing = dfa.states.Get(D);\n\t\t\t\tif (existing != null) {\n    \t\t\t\tif ( trace_atn_sim ) Console.WriteLine(\"addDFAState \" + D + \" exists\");\n    \t\t\t\treturn existing;\n\t\t\t\t}\n\n\t\t\t\tD.stateNumber = dfa.states.Count;\n\t\t\t\tif (!D.configSet.IsReadOnly)\n\t\t\t\t{\n\t\t\t\t\tD.configSet.OptimizeConfigs(this);\n\t\t\t\t\tD.configSet.IsReadOnly = true;\n\t\t\t\t}\n\t\t\t\tdfa.states.Put(D, D);\n\n  \t\t\t\tif ( trace_atn_sim ) Console.WriteLine(\"addDFAState new \" + D);\n\t\t\t\treturn D;\n\t\t\t}\n\t\t}\n\n\t\tprotected virtual void ReportAttemptingFullContext(DFA dfa, BitSet conflictingAlts, ATNConfigSet configs, int startIndex, int stopIndex)\n\t\t{\n\t\t\tif (debug || retry_debug)\n\t\t\t{\n\t\t\t\tInterval interval = Interval.Of(startIndex, stopIndex);\n\t\t\t\tConsole.WriteLine(\"reportAttemptingFullContext decision=\" + dfa.decision + \":\" + configs +\n\t\t\t\t\t\t\t\t   \", input=\" + parser.TokenStream.GetText(interval));\n\t\t\t}\n\t\t\tif (parser != null)\n\t\t\t\tparser.ErrorListenerDispatch.ReportAttemptingFullContext(parser, dfa, startIndex, stopIndex, conflictingAlts, configs);\n\t\t}\n\n\t\tprotected virtual void ReportContextSensitivity(DFA dfa, int prediction, ATNConfigSet configs, int startIndex, int stopIndex)\n\t\t{\n\t\t\tif (debug || retry_debug)\n\t\t\t{\n\t\t\t\tInterval interval = Interval.Of(startIndex, stopIndex);\n\t\t\t\tConsole.WriteLine(\"ReportContextSensitivity decision=\" + dfa.decision + \":\" + configs +\n\t\t\t\t\t\t\t\t   \", input=\" + parser.TokenStream.GetText(interval));\n\t\t\t}\n\t\t\tif (parser != null) parser.ErrorListenerDispatch.ReportContextSensitivity(parser, dfa, startIndex, stopIndex, prediction, configs);\n\t\t}\n\n\t\t/** If context sensitive parsing, we know it's ambiguity not conflict */\n\t\tprotected virtual void ReportAmbiguity(DFA dfa,\n\t\t\t\t\t\t\t\t\t   DFAState D, // the DFA state from execATN() that had SLL conflicts\n\t\t\t\t\t\t\t\t\t   int startIndex, int stopIndex,\n\t\t\t\t\t\t\t\t\t   bool exact,\n\t\t\t\t\t\t\t\t\t   BitSet ambigAlts,\n\t\t\t\t\t\t\t\t\t   ATNConfigSet configs) // configs that LL not SLL considered conflicting\n\t\t{\n\t\t\tif (debug || retry_debug)\n\t\t\t{\n\t\t\t\tInterval interval = Interval.Of(startIndex, stopIndex);\n\t\t\t\tConsole.WriteLine(\"ReportAmbiguity \" +\n\t\t\t\t\t\t\t\t   ambigAlts + \":\" + configs +\n\t\t\t\t\t\t\t\t   \", input=\" + parser.TokenStream.GetText(interval));\n\t\t\t}\n\t\t\tif (parser != null) parser.ErrorListenerDispatch.ReportAmbiguity(parser, dfa, startIndex, stopIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  exact, ambigAlts, configs);\n\t\t}\n\n\t\tpublic PredictionMode PredictionMode\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this.mode;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tthis.mode = value;\n\t\t\t}\n\t\t}\n\n\n\t\tpublic Parser getParser()\n\t\t{\n\t\t\treturn parser;\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PlusBlockStartState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Start of\n    /// <c>(A|B|...)+</c>\n    /// loop. Technically a decision state, but\n    /// we don't use for code generation; somebody might need it, so I'm defining\n    /// it for completeness. In reality, the\n    /// <see cref=\"PlusLoopbackState\"/>\n    /// node is the\n    /// real decision-making note for\n    /// <c>A+</c>\n    /// .\n    /// </summary>\n    public sealed class PlusBlockStartState : BlockStartState\n    {\n        public PlusLoopbackState loopBackState;\n\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.PlusBlockStart;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PlusLoopbackState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// Decision state for\n    /// <c>A+</c>\n    /// and\n    /// <c>(A|B)+</c>\n    /// .  It has two transitions:\n    /// one to the loop back to start of the block and one to exit.\n    /// </summary>\n    public sealed class PlusLoopbackState : DecisionState\n    {\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.PlusLoopBack;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PrecedencePredicateTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    public sealed class PrecedencePredicateTransition : AbstractPredicateTransition\n    {\n        public readonly int precedence;\n\n        public PrecedencePredicateTransition(ATNState target, int precedence)\n            : base(target)\n        {\n            this.precedence = precedence;\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.PRECEDENCE;\n            }\n        }\n\n        public override bool IsEpsilon\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return false;\n        }\n\n        public SemanticContext.PrecedencePredicate Predicate\n        {\n            get\n            {\n                return new SemanticContext.PrecedencePredicate(precedence);\n            }\n        }\n\n        public override string ToString()\n        {\n            return precedence + \" >= _p\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PredicateEvalInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// This class represents profiling event information for semantic predicate\n    /// evaluations which occur during prediction.\n    /// </summary>\n    /// <remarks>\n    /// This class represents profiling event information for semantic predicate\n    /// evaluations which occur during prediction.\n    /// </remarks>\n    /// <seealso cref=\"ParserATNSimulator.EvalSemanticContext(Dfa.PredPrediction[], ParserRuleContext, bool)\"/>\n    /// <since>4.3</since>\n    public class PredicateEvalInfo : DecisionEventInfo\n    {\n        /// <summary>The semantic context which was evaluated.</summary>\n        /// <remarks>The semantic context which was evaluated.</remarks>\n        public readonly SemanticContext semctx;\n\n        /// <summary>\n        /// The alternative number for the decision which is guarded by the semantic\n        /// context\n        /// <see cref=\"semctx\"/>\n        /// . Note that other ATN\n        /// configurations may predict the same alternative which are guarded by\n        /// other semantic contexts and/or\n        /// <see cref=\"SemanticContext.Empty.Instance\"/>\n        /// .\n        /// </summary>\n        public readonly int predictedAlt;\n\n        /// <summary>\n        /// The result of evaluating the semantic context\n        /// <see cref=\"semctx\"/>\n        /// .\n        /// </summary>\n        public readonly bool evalResult;\n\n        /// <summary>\n        /// Constructs a new instance of the\n        /// <see cref=\"PredicateEvalInfo\"/>\n        /// class with the\n        /// specified detailed predicate evaluation information.\n        /// </summary>\n        /// <param name=\"decision\">The decision number</param>\n        /// <param name=\"input\">The input token stream</param>\n        /// <param name=\"startIndex\">The start index for the current prediction</param>\n        /// <param name=\"stopIndex\">\n        /// The index at which the predicate evaluation was\n        /// triggered. Note that the input stream may be reset to other positions for\n        /// the actual evaluation of individual predicates.\n        /// </param>\n        /// <param name=\"semctx\">The semantic context which was evaluated</param>\n        /// <param name=\"evalResult\">The results of evaluating the semantic context</param>\n        /// <param name=\"predictedAlt\">\n        /// The alternative number for the decision which is\n        /// guarded by the semantic context\n        /// <paramref name=\"semctx\"/>\n        /// . See\n        /// <see cref=\"predictedAlt\"/>\n        /// for more information.\n        /// </param>\n        /// <param name=\"fullCtx\">{@code true} if the semantic context was\n        /// evaluated during LL prediction; otherwise, {@code false} if the semantic\n        /// context was evaluated during SLL prediction\n        /// </param>\n        ///\n        /// <seealso cref=\"ParserATNSimulator.EvalSemanticContext(SemanticContext, ParserRuleContext, int, bool)\"/>\n        /// <seealso cref=\"SemanticContext.Eval\"/>\n        public PredicateEvalInfo(int decision, ITokenStream input, int startIndex, int stopIndex, SemanticContext semctx, bool evalResult, int predictedAlt, bool fullCtx)\n            : base(decision, new ATNConfigSet(), input, startIndex, stopIndex, fullCtx)\n        {\n            this.semctx = semctx;\n            this.evalResult = evalResult;\n            this.predictedAlt = predictedAlt;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PredicateTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// TODO: this is old comment:\n    /// A tree of semantic predicates from the grammar AST if label==SEMPRED.\n    /// </summary>\n    /// <remarks>\n    /// TODO: this is old comment:\n    /// A tree of semantic predicates from the grammar AST if label==SEMPRED.\n    /// In the ATN, labels will always be exactly one predicate, but the DFA\n    /// may have to combine a bunch of them as it collects predicates from\n    /// multiple ATN configurations into a single DFA state.\n    /// </remarks>\n    public sealed class PredicateTransition : AbstractPredicateTransition\n    {\n        public readonly int ruleIndex;\n\n        public readonly int predIndex;\n\n        public readonly bool isCtxDependent;\n\n        public PredicateTransition(ATNState target, int ruleIndex, int predIndex, bool isCtxDependent)\n            : base(target)\n        {\n            // e.g., $i ref in pred\n            this.ruleIndex = ruleIndex;\n            this.predIndex = predIndex;\n            this.isCtxDependent = isCtxDependent;\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.PREDICATE;\n            }\n        }\n\n        public override bool IsEpsilon\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return false;\n        }\n\n        public SemanticContext.Predicate Predicate\n        {\n            get\n            {\n                return new SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent);\n            }\n        }\n\n        [return: NotNull]\n        public override string ToString()\n        {\n            return \"pred_\" + ruleIndex + \":\" + predIndex;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PredictionContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\tpublic abstract class PredictionContext\n\t{\n\t\tpublic static readonly int EMPTY_RETURN_STATE = int.MaxValue;\n\n\t\tprivate static readonly int INITIAL_HASH = 1;\n\n\t\tprotected internal static int CalculateEmptyHashCode()\n\t\t{\n\t\t\tint hash = MurmurHash.Initialize(INITIAL_HASH);\n\t\t\thash = MurmurHash.Finish(hash, 0);\n\t\t\treturn hash;\n\t\t}\n\n\t\tprotected internal static int CalculateHashCode(PredictionContext parent, int returnState)\n\t\t{\n\t\t\tint hash = MurmurHash.Initialize(INITIAL_HASH);\n\t\t\thash = MurmurHash.Update(hash, parent);\n\t\t\thash = MurmurHash.Update(hash, returnState);\n\t\t\thash = MurmurHash.Finish(hash, 2);\n\t\t\treturn hash;\n\t\t}\n\n\t\tprotected internal static int CalculateHashCode(PredictionContext[] parents, int[] returnStates)\n\t\t{\n\t\t\tint hash = MurmurHash.Initialize(INITIAL_HASH);\n\t\t\tforeach (PredictionContext parent in parents)\n\t\t\t{\n\t\t\t\thash = MurmurHash.Update(hash, parent);\n\t\t\t}\n\t\t\tforeach (int returnState in returnStates)\n\t\t\t{\n\t\t\t\thash = MurmurHash.Update(hash, returnState);\n\t\t\t}\n\t\t\thash = MurmurHash.Finish(hash, 2 * parents.Length);\n\t\t\treturn hash;\n\t\t}\n\n\t\tprivate readonly int cachedHashCode;\n\n\t\tprotected internal PredictionContext(int cachedHashCode)\n\t\t{\n\t\t\tthis.cachedHashCode = cachedHashCode;\n\t\t}\n\n\t\tpublic static PredictionContext FromRuleContext(ATN atn, RuleContext outerContext)\n\t\t{\n\t\t\tif (outerContext == null)\n\t\t\t\touterContext = ParserRuleContext.EMPTY;\n\t\t\tif (outerContext.Parent == null || outerContext == ParserRuleContext.EMPTY)\n\t\t\t\treturn EmptyPredictionContext.Instance;\n\t\t\tPredictionContext parent = PredictionContext.FromRuleContext(atn, outerContext.Parent);\n\t\t\tATNState state = atn.states[outerContext.invokingState];\n\t\t\tRuleTransition transition = (RuleTransition)state.Transition(0);\n\t\t\treturn parent.GetChild(transition.followState.stateNumber);\n\t\t}\n\n\t\tpublic abstract int Size\n\t\t{\n\t\t\tget;\n\t\t}\n\n\t\tpublic abstract PredictionContext GetParent(int index);\n\n\t\tpublic abstract int GetReturnState(int index);\n\n\t\tpublic virtual bool IsEmpty\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn this == EmptyPredictionContext.Instance;\n\t\t\t}\n\t\t}\n\n\t\tpublic virtual bool HasEmptyPath\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn GetReturnState(Size - 1) == EMPTY_RETURN_STATE;\n\t\t\t}\n\t\t}\n\n\t\tpublic sealed override int GetHashCode()\n\t\t{\n\t\t\treturn cachedHashCode;\n\t\t}\n\n\n\n\t\tinternal static PredictionContext Merge(PredictionContext a, PredictionContext b, bool rootIsWildcard, MergeCache mergeCache)\n\t\t{\n\t\t\tif (a == b || a.Equals(b))\n\t\t\t{\n\t\t\t\treturn a;\n\t\t\t}\n\t\t\tif (a is SingletonPredictionContext && b is SingletonPredictionContext)\n\t\t\t{\n\t\t\t\treturn MergeSingletons((SingletonPredictionContext)a,\n\t\t\t\t\t\t\t\t\t   (SingletonPredictionContext)b,\n\t\t\t\t\t\t\t\t\t   rootIsWildcard, mergeCache);\n\t\t\t}\n\n\t\t\t// At least one of a or b is array\n\t\t\t// If one is $ and rootIsWildcard, return $ as * wildcard\n\t\t\tif (rootIsWildcard)\n\t\t\t{\n\t\t\t\tif (a is EmptyPredictionContext)\n\t\t\t\t\treturn a;\n\t\t\t\tif (b is EmptyPredictionContext)\n\t\t\t\t\treturn b;\n\t\t\t}\n\n\t\t\t// convert singleton so both are arrays to normalize\n\t\t\tif (a is SingletonPredictionContext)\n\t\t\t{\n\t\t\t\ta = new ArrayPredictionContext((SingletonPredictionContext)a);\n\t\t\t}\n\t\t\tif (b is SingletonPredictionContext)\n\t\t\t{\n\t\t\t\tb = new ArrayPredictionContext((SingletonPredictionContext)b);\n\t\t\t}\n\t\t\treturn MergeArrays((ArrayPredictionContext)a, (ArrayPredictionContext)b,\n\t\t\t\t\t\t\t   rootIsWildcard, mergeCache);\n\t\t}\n\n\t\tpublic static PredictionContext MergeSingletons(\n\tSingletonPredictionContext a,\n\tSingletonPredictionContext b,\n\tbool rootIsWildcard,\n\tMergeCache mergeCache)\n\t\t{\n\t\t\tif (mergeCache != null)\n\t\t\t{\n\t\t\t\tPredictionContext previous = mergeCache.Get(a, b);\n\t\t\t\tif (previous != null) return previous;\n\t\t\t\tprevious = mergeCache.Get(b, a);\n\t\t\t\tif (previous != null) return previous;\n\t\t\t}\n\n\t\t\tPredictionContext rootMerge = MergeRoot(a, b, rootIsWildcard);\n\t\t\tif (rootMerge != null)\n\t\t\t{\n\t\t\t\tif (mergeCache != null) mergeCache.Put(a, b, rootMerge);\n\t\t\t\treturn rootMerge;\n\t\t\t}\n\n\t\t\tif (a.returnState == b.returnState)\n\t\t\t{ // a == b\n\t\t\t\tPredictionContext parent = Merge(a.parent, b.parent, rootIsWildcard, mergeCache);\n\t\t\t\t// if parent is same as existing a or b parent or reduced to a parent, return it\n\t\t\t\tif (parent == a.parent) return a; // ax + bx = ax, if a=b\n\t\t\t\tif (parent == b.parent) return b; // ax + bx = bx, if a=b\n\t\t\t\t\t\t\t\t\t\t\t\t  // else: ax + ay = a'[x,y]\n\t\t\t\t\t\t\t\t\t\t\t\t  // merge parents x and y, giving array node with x,y then remainders\n\t\t\t\t\t\t\t\t\t\t\t\t  // of those graphs.  dup a, a' points at merged array\n\t\t\t\t\t\t\t\t\t\t\t\t  // new joined parent so create new singleton pointing to it, a'\n\t\t\t\tPredictionContext a_ = SingletonPredictionContext.Create(parent, a.returnState);\n\t\t\t\tif (mergeCache != null) mergeCache.Put(a, b, a_);\n\t\t\t\treturn a_;\n\t\t\t}\n\t\t\telse { // a != b payloads differ\n\t\t\t\t   // see if we can collapse parents due to $+x parents if local ctx\n\t\t\t\tint[] payloads = new int[2];\n\t\t\t\tPredictionContext[] parents = new PredictionContext[2];\n\t\t\t\tPredictionContext pc;\n\t\t\t\tPredictionContext singleParent = null;\n\t\t\t\tif (a == b || (a.parent != null && a.parent.Equals(b.parent)))\n\t\t\t\t{ // ax + bx = [a,b]x\n\t\t\t\t\tsingleParent = a.parent;\n\t\t\t\t}\n\t\t\t\tif (singleParent != null)\n\t\t\t\t{   // parents are same\n\t\t\t\t\t// sort payloads and use same parent\n\t\t\t\t\tif (a.returnState > b.returnState)\n\t\t\t\t\t{\n\t\t\t\t\t\tpayloads[0] = b.returnState;\n\t\t\t\t\t\tpayloads[1] = a.returnState;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tpayloads[0] = a.returnState;\n\t\t\t\t\t\tpayloads[1] = b.returnState;\n\t\t\t\t\t}\n\t\t\t\t\tparents[0] = singleParent;\n\t\t\t\t\tparents[1] = singleParent;\n\t\t\t\t\tpc = new ArrayPredictionContext(parents, payloads);\n\t\t\t\t\tif (mergeCache != null)\n\t\t\t\t\t\tmergeCache.Put(a, b, pc);\n\t\t\t\t\treturn pc;\n\t\t\t\t}\n\t\t\t\t// parents differ and can't merge them. Just pack together\n\t\t\t\t// into array; can't merge.\n\t\t\t\t// ax + by = [ax,by]\n\t\t\t\t// sort by payload\n\t\t\t\tif (a.returnState > b.returnState)\n\t\t\t\t{\n\t\t\t\t\tpayloads[0] = b.returnState;\n\t\t\t\t\tpayloads[1] = a.returnState;\n\t\t\t\t\tparents[0] = b.parent;\n\t\t\t\t\tparents[1] = a.parent;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpayloads[0] = a.returnState;\n\t\t\t\t\tpayloads[1] = b.returnState;\n\t\t\t\t\tparents[0] = a.parent;\n\t\t\t\t\tparents[1] = b.parent;\n\t\t\t\t}\n\t\t\t\tpc = new ArrayPredictionContext(parents, payloads);\n\t\t\t\tif (mergeCache != null)\n\t\t\t\t\tmergeCache.Put(a, b, pc);\n\t\t\t\treturn pc;\n\t\t\t}\n\t\t}\n\n\t\tpublic static PredictionContext MergeArrays(\n            ArrayPredictionContext a,\n            ArrayPredictionContext b,\n            bool rootIsWildcard,\n            MergeCache mergeCache)\n\t\t{\n\t\t\tif (mergeCache != null)\n\t\t\t{\n\t\t\t\tPredictionContext previous = mergeCache.Get(a, b);\n\t\t\t\tif (previous != null) {\n    \t\t\t\tif ( ParserATNSimulator.trace_atn_sim ) Console.WriteLine(\"mergeArrays a=\"+a+\",b=\"+b+\" -> previous\");\n\t\t\t\t\treturn previous;\n\t\t\t\t}\n\t\t\t\tprevious = mergeCache.Get(b, a);\n\t\t\t\tif (previous != null) {\n    \t\t\t\tif ( ParserATNSimulator.trace_atn_sim ) Console.WriteLine(\"mergeArrays a=\"+a+\",b=\"+b+\" -> previous\");\n\t\t\t\t\treturn previous;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// merge sorted payloads a + b => M\n\t\t\tint i = 0; // walks a\n\t\t\tint j = 0; // walks b\n\t\t\tint k = 0; // walks target M array\n\n\t\t\tint[] mergedReturnStates =\n\t\t\t\tnew int[a.returnStates.Length + b.returnStates.Length];\n\t\t\tPredictionContext[] mergedParents =\n\t\t\t\tnew PredictionContext[a.returnStates.Length + b.returnStates.Length];\n\t\t\t// walk and merge to yield mergedParents, mergedReturnStates\n\t\t\twhile (i < a.returnStates.Length && j < b.returnStates.Length)\n\t\t\t{\n\t\t\t\tPredictionContext a_parent = a.parents[i];\n\t\t\t\tPredictionContext b_parent = b.parents[j];\n\t\t\t\tif (a.returnStates[i] == b.returnStates[j])\n\t\t\t\t{\n\t\t\t\t\t// same payload (stack tops are equal), must yield merged singleton\n\t\t\t\t\tint payload = a.returnStates[i];\n\t\t\t\t\t// $+$ = $\n\t\t\t\t\tbool both_dollar = payload == EMPTY_RETURN_STATE &&\n\t\t\t\t\t\t\t\t\ta_parent == null && b_parent == null;\n\t\t\t\t\tbool ax_ax = (a_parent != null && b_parent != null) &&\n\t\t\t\t\t\t\t\t\ta_parent.Equals(b_parent); // ax+ax -> ax\n\t\t\t\t\tif (both_dollar || ax_ax ) {\n\t\t\t\t\t\tmergedParents[k] = a_parent; // choose left\n\t\t\t\t\t\tmergedReturnStates[k] = payload;\n\t\t\t\t\t}\n\t\t\t\telse { // ax+ay -> a'[x,y]\n\t\t\t\t\t\tPredictionContext mergedParent =\n\t\t\t\t\t\t\tMerge(a_parent, b_parent, rootIsWildcard, mergeCache);\n\t\t\t\t\t\tmergedParents[k] = mergedParent;\n\t\t\t\t\t\tmergedReturnStates[k] = payload;\n\t\t\t\t\t}\n\t\t\t\t\ti++; // hop over left one as usual\n\t\t\t\t\tj++; // but also skip one in right side since we merge\n\t\t\t\t}\n\t\t\t\telse if (a.returnStates[i] < b.returnStates[j])\n\t\t\t\t{ // copy a[i] to M\n\t\t\t\t\tmergedParents[k] = a_parent;\n\t\t\t\t\tmergedReturnStates[k] = a.returnStates[i];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\telse { // b > a, copy b[j] to M\n\t\t\t\t\tmergedParents[k] = b_parent;\n\t\t\t\t\tmergedReturnStates[k] = b.returnStates[j];\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t\t// copy over any payloads remaining in either array\n\t\t\tif (i < a.returnStates.Length)\n\t\t\t{\n\t\t\t\tfor (int p = i; p < a.returnStates.Length; p++)\n\t\t\t\t{\n\t\t\t\t\tmergedParents[k] = a.parents[p];\n\t\t\t\t\tmergedReturnStates[k] = a.returnStates[p];\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (int p = j; p < b.returnStates.Length; p++)\n\t\t\t\t{\n\t\t\t\t\tmergedParents[k] = b.parents[p];\n\t\t\t\t\tmergedReturnStates[k] = b.returnStates[p];\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// trim merged if we combined a few that had same stack tops\n\t\t\tif (k < mergedParents.Length)\n\t\t\t{ // write index < last position; trim\n\t\t\t\tif (k == 1)\n\t\t\t\t{ // for just one merged element, return singleton top\n\t\t\t\t\tPredictionContext a_ = SingletonPredictionContext.Create(mergedParents[0], mergedReturnStates[0]);\n\t\t\t\t\tif (mergeCache != null) mergeCache.Put(a, b, a_);\n\t\t\t\t\treturn a_;\n\t\t\t\t}\n\t\t\t\tmergedParents = Arrays.CopyOf(mergedParents, k);\n\t\t\t\tmergedReturnStates = Arrays.CopyOf(mergedReturnStates, k);\n\t\t\t}\n\n\t\t\tPredictionContext M = new ArrayPredictionContext(mergedParents, mergedReturnStates);\n\n\t\t\t// if we created same array as a or b, return that instead\n\t\t\t// TODO: track whether this is possible above during merge sort for speed\n\t\t\tif (M.Equals(a))\n\t\t\t{\n\t\t\t\tif (mergeCache != null)\n\t\t\t\t\tmergeCache.Put(a, b, a);\n   \t\t\t\tif ( ParserATNSimulator.trace_atn_sim ) Console.WriteLine(\"mergeArrays a=\"+a+\",b=\"+b+\" -> a\");\n\t\t\t\treturn a;\n\t\t\t}\n\t\t\tif (M.Equals(b))\n\t\t\t{\n\t\t\t\tif (mergeCache != null)\n\t\t\t\t\tmergeCache.Put(a, b, b);\n   \t\t\t\tif ( ParserATNSimulator.trace_atn_sim ) Console.WriteLine(\"mergeArrays a=\"+a+\",b=\"+b+\" -> b\");\n\t\t\t\treturn b;\n\t\t\t}\n\n\t\t\tCombineCommonParents(mergedParents);\n\n\t\t\tif ( ParserATNSimulator.trace_atn_sim ) Console.WriteLine(\"mergeArrays a=\"+a+\",b=\"+b+\" -> \"+M);\n\n\t\t\tif (mergeCache != null)\n\t\t\t\tmergeCache.Put(a, b, M);\n\t\t\treturn M;\n\t\t}\n\n\t\tprotected static void CombineCommonParents(PredictionContext[] parents)\n\t\t{\n\t\t\tDictionary<PredictionContext, PredictionContext> uniqueParents = new Dictionary<PredictionContext, PredictionContext>();\n\n\t\t\tfor (int p = 0; p < parents.Length; p++)\n\t\t\t{\n\t\t\t\tPredictionContext parent = parents[p];\n\t\t\t\tif (parent!=null && !uniqueParents.ContainsKey(parent))\n\t\t\t\t{ // don't replace\n\t\t\t\t\tuniqueParents.Put(parent, parent);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int p = 0; p < parents.Length; p++)\n\t\t\t{\n\t\t\t\tPredictionContext parent = parents[p];\n\t\t\t\tif (parent!=null)\n\t\t\t\t\tparents[p] = uniqueParents.Get(parent);\n\t\t\t}\n\t\t}\n\n\t\tpublic static PredictionContext MergeRoot(SingletonPredictionContext a,\n\t\t\t\t\t\t\t\t\t\t\t  SingletonPredictionContext b,\n\t\t\t\t\t\t\t\t\t\t\t  bool rootIsWildcard)\n\t\t{\n\t\t\tif (rootIsWildcard)\n\t\t\t{\n\t\t\t\tif (a == EmptyPredictionContext.Instance)\n\t\t\t\t\treturn EmptyPredictionContext.Instance;  // * + b = *\n\t\t\t\tif (b == EmptyPredictionContext.Instance)\n\t\t\t\t\treturn EmptyPredictionContext.Instance;  // a + * = *\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (a == EmptyPredictionContext.Instance && b == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance; // $ + $ = $\n\t\t\t\tif (a == EmptyPredictionContext.Instance)\n\t\t\t\t{ // $ + x = [$,x]\n\t\t\t\t\tint[] payloads = { b.returnState, EMPTY_RETURN_STATE };\n\t\t\t\t\tPredictionContext[] parents = { b.parent, null };\n\t\t\t\t\tPredictionContext joined =\n\t\t\t\t\t\tnew ArrayPredictionContext(parents, payloads);\n\t\t\t\t\treturn joined;\n\t\t\t\t}\n\t\t\t\tif (b == EmptyPredictionContext.Instance)\n\t\t\t\t{ // x + $ = [$,x] ($ is always first if present)\n\t\t\t\t\tint[] payloads = { a.returnState, EMPTY_RETURN_STATE };\n\t\t\t\t\tPredictionContext[] parents = { a.parent, null };\n\t\t\t\t\tPredictionContext joined =\n\t\t\t\t\t\tnew ArrayPredictionContext(parents, payloads);\n\t\t\t\t\treturn joined;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\n\t\tpublic static PredictionContext GetCachedContext(PredictionContext context, PredictionContextCache contextCache, PredictionContext.IdentityHashMap visited)\n\t\t{\n\t\t\tif (context.IsEmpty)\n\t\t\t{\n\t\t\t\treturn context;\n\t\t\t}\n\n\t\t\tPredictionContext existing = visited.Get(context);\n\t\t\tif (existing != null)\n\t\t\t{\n\t\t\t\treturn existing;\n\t\t\t}\n\n\t\t\texisting = contextCache.Get(context);\n\t\t\tif (existing != null)\n\t\t\t{\n\t\t\t\tvisited.Put(context, existing);\n\t\t\t\treturn existing;\n\t\t\t}\n\n\t\t\tbool changed = false;\n\t\t\tPredictionContext[] parents = new PredictionContext[context.Size];\n\t\t\tfor (int i = 0; i < parents.Length; i++)\n\t\t\t{\n\t\t\t\tPredictionContext parent = GetCachedContext(context.GetParent(i), contextCache, visited);\n\t\t\t\tif (changed || parent != context.GetParent(i))\n\t\t\t\t{\n\t\t\t\t\tif (!changed)\n\t\t\t\t\t{\n\t\t\t\t\t\tparents = new PredictionContext[context.Size];\n\t\t\t\t\t\tfor (int j = 0; j < context.Size; j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tparents[j] = context.GetParent(j);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tparents[i] = parent;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!changed)\n\t\t\t{\n\t\t\t\tcontextCache.Add(context);\n\t\t\t\tvisited.Put(context, context);\n\t\t\t\treturn context;\n\t\t\t}\n\n\t\t\tPredictionContext updated;\n\t\t\tif (parents.Length == 0)\n\t\t\t{\n\t\t\t\tupdated = EmptyPredictionContext.Instance;\n\t\t\t}\n\t\t\telse if (parents.Length == 1)\n\t\t\t{\n\t\t\t\tupdated = SingletonPredictionContext.Create(parents[0], context.GetReturnState(0));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tArrayPredictionContext arrayPredictionContext = (ArrayPredictionContext)context;\n\t\t\t\tupdated = new ArrayPredictionContext(parents, arrayPredictionContext.returnStates);\n\t\t\t}\n\n\t\t\tcontextCache.Add(updated);\n\t\t\tvisited.Put(updated, updated);\n\t\t\tvisited.Put(context, updated);\n\n\t\t\treturn updated;\n\t\t}\n\n\t\tpublic virtual PredictionContext GetChild(int returnState)\n\t\t{\n\t\t\treturn new SingletonPredictionContext(this, returnState);\n\t\t}\n\n\n\t\tpublic virtual string[] ToStrings(IRecognizer recognizer, int currentState)\n\t\t{\n\t\t\treturn ToStrings(recognizer, EmptyPredictionContext.Instance, currentState);\n\t\t}\n\n\t\tpublic virtual string[] ToStrings(IRecognizer recognizer, PredictionContext stop, int currentState)\n\t\t{\n\t\t\tList<string> result = new List<string>();\n\t\t\tfor (int perm = 0; ; perm++)\n\t\t\t{\n\t\t\t\tint offset = 0;\n\t\t\t\tbool last = true;\n\t\t\t\tPredictionContext p = this;\n\t\t\t\tint stateNumber = currentState;\n\t\t\t\tStringBuilder localBuffer = new StringBuilder();\n\t\t\t\tlocalBuffer.Append(\"[\");\n\t\t\t\twhile (!p.IsEmpty && p != stop)\n\t\t\t\t{\n\t\t\t\t\tint index = 0;\n\t\t\t\t\tif (p.Size > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint bits = 1;\n\t\t\t\t\t\twhile ((1 << bits) < p.Size)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbits++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint mask = (1 << bits) - 1;\n\t\t\t\t\t\tindex = (perm >> offset) & mask;\n\t\t\t\t\t\tlast &= index >= p.Size - 1;\n\t\t\t\t\t\tif (index >= p.Size)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tgoto outer_continue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\toffset += bits;\n\t\t\t\t\t}\n\t\t\t\t\tif (recognizer != null)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (localBuffer.Length > 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// first char is '[', if more than that this isn't the first rule\n\t\t\t\t\t\t\tlocalBuffer.Append(' ');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tATN atn = recognizer.Atn;\n\t\t\t\t\t\tATNState s = atn.states[stateNumber];\n\t\t\t\t\t\tstring ruleName = recognizer.RuleNames[s.ruleIndex];\n\t\t\t\t\t\tlocalBuffer.Append(ruleName);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (p.GetReturnState(index) != EMPTY_RETURN_STATE)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!p.IsEmpty)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (localBuffer.Length > 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// first char is '[', if more than that this isn't the first rule\n\t\t\t\t\t\t\t\t\tlocalBuffer.Append(' ');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlocalBuffer.Append(p.GetReturnState(index));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tstateNumber = p.GetReturnState(index);\n\t\t\t\t\tp = p.GetParent(index);\n\t\t\t\t}\n\t\t\t\tlocalBuffer.Append(\"]\");\n\t\t\t\tresult.Add(localBuffer.ToString());\n\t\t\t\tif (last)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\touter_continue:;\n\t\t\t}\n\n\t\t\treturn result.ToArray();\n\t\t}\n\n\t\tpublic sealed class IdentityHashMap : Dictionary<PredictionContext, PredictionContext>\n\t\t{\n\t\t\tpublic IdentityHashMap()\n\t\t\t\t: base(PredictionContext.IdentityEqualityComparator.Instance)\n\t\t\t{\n\t\t\t}\n\t\t}\n\n\t\tpublic sealed class IdentityEqualityComparator : EqualityComparer<PredictionContext>\n\t\t{\n\t\t\tpublic static readonly PredictionContext.IdentityEqualityComparator Instance = new PredictionContext.IdentityEqualityComparator();\n\n\t\t\tprivate IdentityEqualityComparator()\n\t\t\t{\n\t\t\t}\n\n\t\t\tpublic override int GetHashCode(PredictionContext obj)\n\t\t\t{\n\t\t\t\treturn obj.GetHashCode();\n\t\t\t}\n\n\t\t\tpublic override bool Equals(PredictionContext a, PredictionContext b)\n\t\t\t{\n\t\t\t\treturn a == b;\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PredictionContextCache.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\tpublic class PredictionContextCache\n\t{\n\t\tprotected readonly Dictionary<PredictionContext, PredictionContext> cache =\n\t\t\tnew Dictionary<PredictionContext, PredictionContext>();\n\n\t\t/** Add a context to the cache and return it. If the context already exists,\n\t\t *  return that one instead and do not add a new context to the cache.\n\t\t *  Protect shared cache from unsafe thread access.\n\t\t */\n\t\tpublic PredictionContext Add(PredictionContext ctx)\n\t\t{\n\t\t\tif (ctx == EmptyPredictionContext.Instance)\n\t\t\t\treturn EmptyPredictionContext.Instance;\n\t\t\tPredictionContext existing = cache.Get(ctx);\n\t\t\tif (existing != null)\n\t\t\t{\n\t\t\t\treturn existing;\n\t\t\t}\n\t\t\tcache.Put(ctx, ctx);\n\t\t\treturn ctx;\n\t\t}\n\n\t\tpublic PredictionContext Get(PredictionContext ctx)\n\t\t{\n\t\t\treturn cache.Get(ctx);\n\t\t}\n\n\t\tpublic int Count\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn cache.Count;\n\t\t\t}\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/PredictionMode.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>\n    /// This enumeration defines the prediction modes available in ANTLR 4 along with\n    /// utility methods for analyzing configuration sets for conflicts and/or\n    /// ambiguities.\n    /// </summary>\n    /// <remarks>\n    /// This enumeration defines the prediction modes available in ANTLR 4 along with\n    /// utility methods for analyzing configuration sets for conflicts and/or\n    /// ambiguities.\n    /// </remarks>\n    [System.Serializable]\n    public sealed class PredictionMode\n    {\n        /// <summary>The SLL(*) prediction mode.</summary>\n        /// <remarks>\n        /// The SLL(*) prediction mode. This prediction mode ignores the current\n        /// parser context when making predictions. This is the fastest prediction\n        /// mode, and provides correct results for many grammars. This prediction\n        /// mode is more powerful than the prediction mode provided by ANTLR 3, but\n        /// may result in syntax errors for grammar and input combinations which are\n        /// not SLL.\n        /// <p>\n        /// When using this prediction mode, the parser will either return a correct\n        /// parse tree (i.e. the same parse tree that would be returned with the\n        /// <see cref=\"LL\"/>\n        /// prediction mode), or it will report a syntax error. If a\n        /// syntax error is encountered when using the\n        /// <see cref=\"SLL\"/>\n        /// prediction mode,\n        /// it may be due to either an actual syntax error in the input or indicate\n        /// that the particular combination of grammar and input requires the more\n        /// powerful\n        /// <see cref=\"LL\"/>\n        /// prediction abilities to complete successfully.</p>\n        /// <p>\n        /// This prediction mode does not provide any guarantees for prediction\n        /// behavior for syntactically-incorrect inputs.</p>\n        /// </remarks>\n        public static readonly PredictionMode SLL = new PredictionMode();\n\n        /// <summary>The LL(*) prediction mode.</summary>\n        /// <remarks>\n        /// The LL(*) prediction mode. This prediction mode allows the current parser\n        /// context to be used for resolving SLL conflicts that occur during\n        /// prediction. This is the fastest prediction mode that guarantees correct\n        /// parse results for all combinations of grammars with syntactically correct\n        /// inputs.\n        /// <p>\n        /// When using this prediction mode, the parser will make correct decisions\n        /// for all syntactically-correct grammar and input combinations. However, in\n        /// cases where the grammar is truly ambiguous this prediction mode might not\n        /// report a precise answer for <em>exactly which</em> alternatives are\n        /// ambiguous.</p>\n        /// <p>\n        /// This prediction mode does not provide any guarantees for prediction\n        /// behavior for syntactically-incorrect inputs.</p>\n        /// </remarks>\n        public static readonly PredictionMode LL = new PredictionMode();\n\n        /// <summary>The LL(*) prediction mode with exact ambiguity detection.</summary>\n        /// <remarks>\n        /// The LL(*) prediction mode with exact ambiguity detection. In addition to\n        /// the correctness guarantees provided by the\n        /// <see cref=\"LL\"/>\n        /// prediction mode,\n        /// this prediction mode instructs the prediction algorithm to determine the\n        /// complete and exact set of ambiguous alternatives for every ambiguous\n        /// decision encountered while parsing.\n        /// <p>\n        /// This prediction mode may be used for diagnosing ambiguities during\n        /// grammar development. Due to the performance overhead of calculating sets\n        /// of ambiguous alternatives, this prediction mode should be avoided when\n        /// the exact results are not necessary.</p>\n        /// <p>\n        /// This prediction mode does not provide any guarantees for prediction\n        /// behavior for syntactically-incorrect inputs.</p>\n        /// </remarks>\n        public static readonly PredictionMode LL_EXACT_AMBIG_DETECTION = new PredictionMode();\n\n        /// <summary>A Map that uses just the state and the stack context as the key.</summary>\n        /// <remarks>A Map that uses just the state and the stack context as the key.</remarks>\n        internal class AltAndContextMap : Dictionary<ATNConfig, BitSet>\n        {\n            public AltAndContextMap()\n                : base(PredictionMode.AltAndContextConfigEqualityComparator.Instance)\n            {\n            }\n        }\n\n        private sealed class AltAndContextConfigEqualityComparator : EqualityComparer<ATNConfig>\n        {\n            public static readonly PredictionMode.AltAndContextConfigEqualityComparator Instance = new PredictionMode.AltAndContextConfigEqualityComparator();\n\n            private AltAndContextConfigEqualityComparator()\n            {\n            }\n\n            /// <summary>\n            /// The hash code is only a function of the\n            /// <see cref=\"ATNState.stateNumber\"/>\n            /// and\n            /// <see cref=\"ATNConfig.context\"/>\n            /// .\n            /// </summary>\n            public override int GetHashCode(ATNConfig o)\n            {\n                int hashCode = MurmurHash.Initialize(7);\n                hashCode = MurmurHash.Update(hashCode, o.state.stateNumber);\n                hashCode = MurmurHash.Update(hashCode, o.context);\n                hashCode = MurmurHash.Finish(hashCode, 2);\n                return hashCode;\n            }\n\n            public override bool Equals(ATNConfig a, ATNConfig b)\n            {\n                if (a == b)\n                {\n                    return true;\n                }\n                if (a == null || b == null)\n                {\n                    return false;\n                }\n                return a.state.stateNumber == b.state.stateNumber && a.context.Equals(b.context);\n            }\n        }\n\n        /// <summary>Computes the SLL prediction termination condition.</summary>\n        /// <remarks>\n        /// Computes the SLL prediction termination condition.\n        /// <p>\n        /// This method computes the SLL prediction termination condition for both of\n        /// the following cases.</p>\n        /// <ul>\n        /// <li>The usual SLL+LL fallback upon SLL conflict</li>\n        /// <li>Pure SLL without LL fallback</li>\n        /// </ul>\n        /// <p><strong>COMBINED SLL+LL PARSING</strong></p>\n        /// <p>When LL-fallback is enabled upon SLL conflict, correct predictions are\n        /// ensured regardless of how the termination condition is computed by this\n        /// method. Due to the substantially higher cost of LL prediction, the\n        /// prediction should only fall back to LL when the additional lookahead\n        /// cannot lead to a unique SLL prediction.</p>\n        /// <p>Assuming combined SLL+LL parsing, an SLL configuration set with only\n        /// conflicting subsets should fall back to full LL, even if the\n        /// configuration sets don't resolve to the same alternative (e.g.\n        /// <c/>\n        ///\n        /// 1,2}} and\n        /// <c/>\n        ///\n        /// 3,4}}. If there is at least one non-conflicting\n        /// configuration, SLL could continue with the hopes that more lookahead will\n        /// resolve via one of those non-conflicting configurations.</p>\n        /// <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n        /// stops when it sees only conflicting configuration subsets. In contrast,\n        /// full LL keeps going when there is uncertainty.</p>\n        /// <p><strong>HEURISTIC</strong></p>\n        /// <p>As a heuristic, we stop prediction when we see any conflicting subset\n        /// unless we see a state that only has one alternative associated with it.\n        /// The single-alt-state thing lets prediction continue upon rules like\n        /// (otherwise, it would admit defeat too soon):</p>\n        /// <p>\n        /// <c>[12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;</c>\n        /// </p>\n        /// <p>When the ATN simulation reaches the state before\n        /// <c>';'</c>\n        /// , it has a\n        /// DFA state that looks like:\n        /// <c>[12|1|[], 6|2|[], 12|2|[]]</c>\n        /// . Naturally\n        /// <c>12|1|[]</c>\n        /// and\n        /// <c>12|2|[]</c>\n        /// conflict, but we cannot stop\n        /// processing this node because alternative to has another way to continue,\n        /// via\n        /// <c>[6|2|[]]</c>\n        /// .</p>\n        /// <p>It also let's us continue for this rule:</p>\n        /// <p>\n        /// <c>[1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;</c>\n        /// </p>\n        /// <p>After matching input A, we reach the stop state for rule A, state 1.\n        /// State 8 is the state right before B. Clearly alternatives 1 and 2\n        /// conflict and no amount of further lookahead will separate the two.\n        /// However, alternative 3 will be able to continue and so we do not stop\n        /// working on this state. In the previous example, we're concerned with\n        /// states associated with the conflicting alternatives. Here alt 3 is not\n        /// associated with the conflicting configs, but since we can continue\n        /// looking for input reasonably, don't declare the state done.</p>\n        /// <p><strong>PURE SLL PARSING</strong></p>\n        /// <p>To handle pure SLL parsing, all we have to do is make sure that we\n        /// combine stack contexts for configurations that differ only by semantic\n        /// predicate. From there, we can do the usual SLL termination heuristic.</p>\n        /// <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>\n        /// <p>SLL decisions don't evaluate predicates until after they reach DFA stop\n        /// states because they need to create the DFA cache that works in all\n        /// semantic situations. In contrast, full LL evaluates predicates collected\n        /// during start state computation so it can ignore predicates thereafter.\n        /// This means that SLL termination detection can totally ignore semantic\n        /// predicates.</p>\n        /// <p>Implementation-wise,\n        /// <see cref=\"ATNConfigSet\"/>\n        /// combines stack contexts but not\n        /// semantic predicate contexts so we might see two configurations like the\n        /// following.</p>\n        /// <p>\n        /// <c/>\n        /// (s, 1, x,\n        /// ), (s, 1, x', {p})}</p>\n        /// <p>Before testing these configurations against others, we have to merge\n        /// <c>x</c>\n        /// and\n        /// <c>x'</c>\n        /// (without modifying the existing configurations).\n        /// For example, we test\n        /// <c>(x+x')==x''</c>\n        /// when looking for conflicts in\n        /// the following configurations.</p>\n        /// <p>\n        /// <c/>\n        /// (s, 1, x,\n        /// ), (s, 1, x', {p}), (s, 2, x'', {})}</p>\n        /// <p>If the configuration set has predicates (as indicated by\n        /// <see cref=\"ATNConfigSet.hasSemanticContext\"/>\n        /// ), this algorithm makes a copy of\n        /// the configurations to strip out all of the predicates so that a standard\n        /// <see cref=\"ATNConfigSet\"/>\n        /// will merge everything ignoring predicates.</p>\n        /// </remarks>\n\t\tpublic static bool HasSLLConflictTerminatingPrediction(PredictionMode mode, ATNConfigSet configSet)\n        {\n\t\t\tif (AllConfigsInRuleStopStates(configSet.configs))\n            {\n                return true;\n            }\n            // pure SLL mode parsing\n            if (mode == PredictionMode.SLL)\n            {\n                // Don't bother with combining configs from different semantic\n                // contexts if we can fail over to full LL; costs more time\n                // since we'll often fail over anyway.\n                if (configSet.hasSemanticContext)\n                {\n                    // dup configs, tossing out semantic predicates\n                    ATNConfigSet dup = new ATNConfigSet();\n\t\t\t\t\tforeach (ATNConfig c in configSet.configs)\n                    {\n\t\t\t\t\t\tdup.Add(new ATNConfig(c, SemanticContext.Empty.Instance));\n                    }\n                    configSet = dup;\n                }\n            }\n            // now we have combined contexts for configs with dissimilar preds\n            // pure SLL or combined SLL+LL mode parsing\n\t\t\tICollection<BitSet> altsets = GetConflictingAltSubsets(configSet.configs);\n\t\t\tbool heuristic = HasConflictingAltSet(altsets) && !HasStateAssociatedWithOneAlt(configSet.configs);\n            return heuristic;\n        }\n\n        /// <summary>\n        /// Checks if any configuration in\n        /// <paramref name=\"configs\"/>\n        /// is in a\n        /// <see cref=\"RuleStopState\"/>\n        /// . Configurations meeting this condition have reached\n        /// the end of the decision rule (local context) or end of start rule (full\n        /// context).\n        /// </summary>\n        /// <param name=\"configs\">the configuration set to test</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if any configuration in\n        /// <paramref name=\"configs\"/>\n        /// is in a\n        /// <see cref=\"RuleStopState\"/>\n        /// , otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        public static bool HasConfigInRuleStopState(IEnumerable<ATNConfig> configs)\n        {\n            foreach (ATNConfig c in configs)\n            {\n                if (c.state is RuleStopState)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        /// <summary>\n        /// Checks if all configurations in\n        /// <paramref name=\"configs\"/>\n        /// are in a\n        /// <see cref=\"RuleStopState\"/>\n        /// . Configurations meeting this condition have reached\n        /// the end of the decision rule (local context) or end of start rule (full\n        /// context).\n        /// </summary>\n        /// <param name=\"configs\">the configuration set to test</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if all configurations in\n        /// <paramref name=\"configs\"/>\n        /// are in a\n        /// <see cref=\"RuleStopState\"/>\n        /// , otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        public static bool AllConfigsInRuleStopStates(IEnumerable<ATNConfig> configs)\n        {\n            foreach (ATNConfig config in configs)\n            {\n                if (!(config.state is RuleStopState))\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        /// <summary>Full LL prediction termination.</summary>\n        /// <remarks>\n        /// Full LL prediction termination.\n        /// <p>Can we stop looking ahead during ATN simulation or is there some\n        /// uncertainty as to which alternative we will ultimately pick, after\n        /// consuming more input? Even if there are partial conflicts, we might know\n        /// that everything is going to resolve to the same minimum alternative. That\n        /// means we can stop since no more lookahead will change that fact. On the\n        /// other hand, there might be multiple conflicts that resolve to different\n        /// minimums. That means we need more look ahead to decide which of those\n        /// alternatives we should predict.</p>\n        /// <p>The basic idea is to split the set of configurations\n        /// <c>C</c>\n        /// , into\n        /// conflicting subsets\n        /// <c>(s, _, ctx, _)</c>\n        /// and singleton subsets with\n        /// non-conflicting configurations. Two configurations conflict if they have\n        /// identical\n        /// <see cref=\"ATNConfig.state\"/>\n        /// and\n        /// <see cref=\"ATNConfig.context\"/>\n        /// values\n        /// but different\n        /// <see cref=\"ATNConfig.alt\"/>\n        /// value, e.g.\n        /// <c>(s, i, ctx, _)</c>\n        /// and\n        /// <c>(s, j, ctx, _)</c>\n        /// for\n        /// <c>i!=j</c>\n        /// .</p>\n        /// <p/>\n        /// Reduce these configuration subsets to the set of possible alternatives.\n        /// You can compute the alternative subsets in one pass as follows:\n        /// <p/>\n        /// <c/>\n        /// A_s,ctx =\n        /// i | (s, i, ctx, _)}} for each configuration in\n        /// <c>C</c>\n        /// holding\n        /// <c>s</c>\n        /// and\n        /// <c>ctx</c>\n        /// fixed.\n        /// <p/>\n        /// Or in pseudo-code, for each configuration\n        /// <c>c</c>\n        /// in\n        /// <c>C</c>\n        /// :\n        /// <pre>\n        /// map[c] U= c.\n        /// <see cref=\"ATNConfig.alt\">getAlt()</see>\n        /// # map hash/equals uses s and x, not\n        /// alt and not pred\n        /// </pre>\n        /// <p>The values in\n        /// <c>map</c>\n        /// are the set of\n        /// <c>A_s,ctx</c>\n        /// sets.</p>\n        /// <p>If\n        /// <c>|A_s,ctx|=1</c>\n        /// then there is no conflict associated with\n        /// <c>s</c>\n        /// and\n        /// <c>ctx</c>\n        /// .</p>\n        /// <p>Reduce the subsets to singletons by choosing a minimum of each subset. If\n        /// the union of these alternative subsets is a singleton, then no amount of\n        /// more lookahead will help us. We will always pick that alternative. If,\n        /// however, there is more than one alternative, then we are uncertain which\n        /// alternative to predict and must continue looking for resolution. We may\n        /// or may not discover an ambiguity in the future, even if there are no\n        /// conflicting subsets this round.</p>\n        /// <p>The biggest sin is to terminate early because it means we've made a\n        /// decision but were uncertain as to the eventual outcome. We haven't used\n        /// enough lookahead. On the other hand, announcing a conflict too late is no\n        /// big deal; you will still have the conflict. It's just inefficient. It\n        /// might even look until the end of file.</p>\n        /// <p>No special consideration for semantic predicates is required because\n        /// predicates are evaluated on-the-fly for full LL prediction, ensuring that\n        /// no configuration contains a semantic context during the termination\n        /// check.</p>\n        /// <p><strong>CONFLICTING CONFIGS</strong></p>\n        /// <p>Two configurations\n        /// <c>(s, i, x)</c>\n        /// and\n        /// <c>(s, j, x')</c>\n        /// , conflict\n        /// when\n        /// <c>i!=j</c>\n        /// but\n        /// <c>x=x'</c>\n        /// . Because we merge all\n        /// <c>(s, i, _)</c>\n        /// configurations together, that means that there are at\n        /// most\n        /// <c>n</c>\n        /// configurations associated with state\n        /// <c>s</c>\n        /// for\n        /// <c>n</c>\n        /// possible alternatives in the decision. The merged stacks\n        /// complicate the comparison of configuration contexts\n        /// <c>x</c>\n        /// and\n        /// <c>x'</c>\n        /// . Sam checks to see if one is a subset of the other by calling\n        /// merge and checking to see if the merged result is either\n        /// <c>x</c>\n        /// or\n        /// <c>x'</c>\n        /// . If the\n        /// <c>x</c>\n        /// associated with lowest alternative\n        /// <c>i</c>\n        /// is the superset, then\n        /// <c>i</c>\n        /// is the only possible prediction since the\n        /// others resolve to\n        /// <c>min(i)</c>\n        /// as well. However, if\n        /// <c>x</c>\n        /// is\n        /// associated with\n        /// <c>j&gt;i</c>\n        /// then at least one stack configuration for\n        /// <c>j</c>\n        /// is not in conflict with alternative\n        /// <c>i</c>\n        /// . The algorithm\n        /// should keep going, looking for more lookahead due to the uncertainty.</p>\n        /// <p>For simplicity, I'm doing a equality check between\n        /// <c>x</c>\n        /// and\n        /// <c>x'</c>\n        /// that lets the algorithm continue to consume lookahead longer\n        /// than necessary. The reason I like the equality is of course the\n        /// simplicity but also because that is the test you need to detect the\n        /// alternatives that are actually in conflict.</p>\n        /// <p><strong>CONTINUE/STOP RULE</strong></p>\n        /// <p>Continue if union of resolved alternative sets from non-conflicting and\n        /// conflicting alternative subsets has more than one alternative. We are\n        /// uncertain about which alternative to predict.</p>\n        /// <p>The complete set of alternatives,\n        /// <c>[i for (_,i,_)]</c>\n        /// , tells us which\n        /// alternatives are still in the running for the amount of input we've\n        /// consumed at this point. The conflicting sets let us to strip away\n        /// configurations that won't lead to more states because we resolve\n        /// conflicts to the configuration with a minimum alternate for the\n        /// conflicting set.</p>\n        /// <p><strong>CASES</strong></p>\n        /// <ul>\n        /// <li>no conflicts and more than 1 alternative in set =&gt; continue</li>\n        /// <li>\n        /// <c>(s, 1, x)</c>\n        /// ,\n        /// <c>(s, 2, x)</c>\n        /// ,\n        /// <c>(s, 3, z)</c>\n        /// ,\n        /// <c>(s', 1, y)</c>\n        /// ,\n        /// <c>(s', 2, y)</c>\n        /// yields non-conflicting set\n        /// <c/>\n        ///\n        /// 3}} U conflicting sets\n        /// <c/>\n        /// min(\n        /// 1,2})} U\n        /// <c/>\n        /// min(\n        /// 1,2})} =\n        /// <c/>\n        ///\n        /// 1,3}} =&gt; continue\n        /// </li>\n        /// <li>\n        /// <c>(s, 1, x)</c>\n        /// ,\n        /// <c>(s, 2, x)</c>\n        /// ,\n        /// <c>(s', 1, y)</c>\n        /// ,\n        /// <c>(s', 2, y)</c>\n        /// ,\n        /// <c>(s'', 1, z)</c>\n        /// yields non-conflicting set\n        /// <c/>\n        ///\n        /// 1}} U conflicting sets\n        /// <c/>\n        /// min(\n        /// 1,2})} U\n        /// <c/>\n        /// min(\n        /// 1,2})} =\n        /// <c/>\n        ///\n        /// 1}} =&gt; stop and predict 1</li>\n        /// <li>\n        /// <c>(s, 1, x)</c>\n        /// ,\n        /// <c>(s, 2, x)</c>\n        /// ,\n        /// <c>(s', 1, y)</c>\n        /// ,\n        /// <c>(s', 2, y)</c>\n        /// yields conflicting, reduced sets\n        /// <c/>\n        ///\n        /// 1}} U\n        /// <c/>\n        ///\n        /// 1}} =\n        /// <c/>\n        ///\n        /// 1}} =&gt; stop and predict 1, can announce\n        /// ambiguity\n        /// <c/>\n        ///\n        /// 1,2}}</li>\n        /// <li>\n        /// <c>(s, 1, x)</c>\n        /// ,\n        /// <c>(s, 2, x)</c>\n        /// ,\n        /// <c>(s', 2, y)</c>\n        /// ,\n        /// <c>(s', 3, y)</c>\n        /// yields conflicting, reduced sets\n        /// <c/>\n        ///\n        /// 1}} U\n        /// <c/>\n        ///\n        /// 2}} =\n        /// <c/>\n        ///\n        /// 1,2}} =&gt; continue</li>\n        /// <li>\n        /// <c>(s, 1, x)</c>\n        /// ,\n        /// <c>(s, 2, x)</c>\n        /// ,\n        /// <c>(s', 3, y)</c>\n        /// ,\n        /// <c>(s', 4, y)</c>\n        /// yields conflicting, reduced sets\n        /// <c/>\n        ///\n        /// 1}} U\n        /// <c/>\n        ///\n        /// 3}} =\n        /// <c/>\n        ///\n        /// 1,3}} =&gt; continue</li>\n        /// </ul>\n        /// <p><strong>EXACT AMBIGUITY DETECTION</strong></p>\n        /// <p>If all states report the same conflicting set of alternatives, then we\n        /// know we have the exact ambiguity set.</p>\n        /// <p><code>|A_<em>i</em>|&gt;1</code> and\n        /// <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>\n        /// <p>In other words, we continue examining lookahead until all\n        /// <c>A_i</c>\n        /// have more than one alternative and all\n        /// <c>A_i</c>\n        /// are the same. If\n        /// <c/>\n        /// A=\n        /// {1,2}, {1,3}}}, then regular LL prediction would terminate\n        /// because the resolved set is\n        /// <c/>\n        ///\n        /// 1}}. To determine what the real\n        /// ambiguity is, we have to know whether the ambiguity is between one and\n        /// two or one and three so we keep going. We can only stop prediction when\n        /// we need exact ambiguity detection when the sets look like\n        /// <c/>\n        /// A=\n        /// {1,2}}} or\n        /// <c/>\n        ///\n        /// {1,2},{1,2}}}, etc...</p>\n        /// </remarks>\n        public static int ResolvesToJustOneViableAlt(IEnumerable<BitSet> altsets)\n        {\n            return GetSingleViableAlt(altsets);\n        }\n\n        /// <summary>\n        /// Determines if every alternative subset in\n        /// <paramref name=\"altsets\"/>\n        /// contains more\n        /// than one alternative.\n        /// </summary>\n        /// <param name=\"altsets\">a collection of alternative subsets</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if every\n        /// <see cref=\"Antlr4.Runtime.Sharpen.BitSet\"/>\n        /// in\n        /// <paramref name=\"altsets\"/>\n        /// has\n        /// <see cref=\"Antlr4.Runtime.Sharpen.BitSet.Cardinality()\">cardinality</see>\n        /// &gt; 1, otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        public static bool AllSubsetsConflict(IEnumerable<BitSet> altsets)\n        {\n            return !HasNonConflictingAltSet(altsets);\n        }\n\n        /// <summary>\n        /// Determines if any single alternative subset in\n        /// <paramref name=\"altsets\"/>\n        /// contains\n        /// exactly one alternative.\n        /// </summary>\n        /// <param name=\"altsets\">a collection of alternative subsets</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if\n        /// <paramref name=\"altsets\"/>\n        /// contains a\n        /// <see cref=\"Antlr4.Runtime.Sharpen.BitSet\"/>\n        /// with\n        /// <see cref=\"Antlr4.Runtime.Sharpen.BitSet.Cardinality()\">cardinality</see>\n        /// 1, otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        public static bool HasNonConflictingAltSet(IEnumerable<BitSet> altsets)\n        {\n            foreach (BitSet alts in altsets)\n            {\n                if (alts.Cardinality() == 1)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        /// <summary>\n        /// Determines if any single alternative subset in\n        /// <paramref name=\"altsets\"/>\n        /// contains\n        /// more than one alternative.\n        /// </summary>\n        /// <param name=\"altsets\">a collection of alternative subsets</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if\n        /// <paramref name=\"altsets\"/>\n        /// contains a\n        /// <see cref=\"Antlr4.Runtime.Sharpen.BitSet\"/>\n        /// with\n        /// <see cref=\"Antlr4.Runtime.Sharpen.BitSet.Cardinality()\">cardinality</see>\n        /// &gt; 1, otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        public static bool HasConflictingAltSet(IEnumerable<BitSet> altsets)\n        {\n            foreach (BitSet alts in altsets)\n            {\n                if (alts.Cardinality() > 1)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        /// <summary>\n        /// Determines if every alternative subset in\n        /// <paramref name=\"altsets\"/>\n        /// is equivalent.\n        /// </summary>\n        /// <param name=\"altsets\">a collection of alternative subsets</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if every member of\n        /// <paramref name=\"altsets\"/>\n        /// is equal to the\n        /// others, otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        public static bool AllSubsetsEqual(IEnumerable<BitSet> altsets)\n        {\n            IEnumerator<BitSet> it = altsets.GetEnumerator();\n            it.MoveNext();\n            BitSet first = it.Current;\n            while (it.MoveNext())\n            {\n                BitSet next = it.Current;\n                if (!next.Equals(first))\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        /// <summary>\n        /// Returns the unique alternative predicted by all alternative subsets in\n        /// <paramref name=\"altsets\"/>\n        /// . If no such alternative exists, this method returns\n        /// <see cref=\"ATN.INVALID_ALT_NUMBER\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"altsets\">a collection of alternative subsets</param>\n        public static int GetUniqueAlt(IEnumerable<BitSet> altsets)\n        {\n            BitSet all = GetAlts(altsets);\n            if (all.Cardinality() == 1)\n            {\n                return all.NextSetBit(0);\n            }\n            return ATN.INVALID_ALT_NUMBER;\n        }\n\n        /// <summary>\n        /// Gets the complete set of represented alternatives for a collection of\n        /// alternative subsets.\n        /// </summary>\n        /// <remarks>\n        /// Gets the complete set of represented alternatives for a collection of\n        /// alternative subsets. This method returns the union of each\n        /// <see cref=\"Antlr4.Runtime.Sharpen.BitSet\"/>\n        /// in\n        /// <paramref name=\"altsets\"/>\n        /// .\n        /// </remarks>\n        /// <param name=\"altsets\">a collection of alternative subsets</param>\n        /// <returns>\n        /// the set of represented alternatives in\n        /// <paramref name=\"altsets\"/>\n        /// </returns>\n        public static BitSet GetAlts(IEnumerable<BitSet> altsets)\n        {\n            BitSet all = new BitSet();\n            foreach (BitSet alts in altsets)\n            {\n                all.Or(alts);\n            }\n            return all;\n        }\n\n        /// <summary>This function gets the conflicting alt subsets from a configuration set.</summary>\n        /// <remarks>\n        /// This function gets the conflicting alt subsets from a configuration set.\n        /// For each configuration\n        /// <c>c</c>\n        /// in\n        /// <paramref name=\"configs\"/>\n        /// :\n        /// <pre>\n        /// map[c] U= c.\n        /// <see cref=\"ATNConfig.alt\">getAlt()</see>\n        /// # map hash/equals uses s and x, not\n        /// alt and not pred\n        /// </pre>\n        /// </remarks>\n        [return: NotNull]\n        public static ICollection<BitSet> GetConflictingAltSubsets(IEnumerable<ATNConfig> configs)\n        {\n            PredictionMode.AltAndContextMap configToAlts = new PredictionMode.AltAndContextMap();\n            foreach (ATNConfig c in configs)\n            {\n                BitSet alts;\n                if (!configToAlts.TryGetValue(c, out alts))\n                {\n                    alts = new BitSet();\n                    configToAlts[c] = alts;\n                }\n                alts.Set(c.alt);\n            }\n            return configToAlts.Values;\n        }\n\n        /// <summary>Get a map from state to alt subset from a configuration set.</summary>\n        /// <remarks>\n        /// Get a map from state to alt subset from a configuration set. For each\n        /// configuration\n        /// <c>c</c>\n        /// in\n        /// <paramref name=\"configs\"/>\n        /// :\n        /// <pre>\n        /// map[c.\n        /// <see cref=\"ATNConfig.state\"/>\n        /// ] U= c.\n        /// <see cref=\"ATNConfig.alt\"/>\n        /// </pre>\n        /// </remarks>\n        [return: NotNull]\n        public static IDictionary<ATNState, BitSet> GetStateToAltMap(IEnumerable<ATNConfig> configs)\n        {\n            IDictionary<ATNState, BitSet> m = new Dictionary<ATNState, BitSet>();\n            foreach (ATNConfig c in configs)\n            {\n                BitSet alts;\n                if (!m.TryGetValue(c.state, out alts))\n                {\n                    alts = new BitSet();\n                    m[c.state] = alts;\n                }\n                alts.Set(c.alt);\n            }\n            return m;\n        }\n\n        public static bool HasStateAssociatedWithOneAlt(IEnumerable<ATNConfig> configs)\n        {\n            IDictionary<ATNState, BitSet> x = GetStateToAltMap(configs);\n            foreach (BitSet alts in x.Values)\n            {\n                if (alts.Cardinality() == 1)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public static int GetSingleViableAlt(IEnumerable<BitSet> altsets)\n        {\n            BitSet viableAlts = new BitSet();\n            foreach (BitSet alts in altsets)\n            {\n                int minAlt = alts.NextSetBit(0);\n                viableAlts.Set(minAlt);\n                if (viableAlts.Cardinality() > 1)\n                {\n                    // more than 1 viable alt\n                    return ATN.INVALID_ALT_NUMBER;\n                }\n            }\n            return viableAlts.NextSetBit(0);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/ProfilingATNSimulator.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n\n\t/**\n\t * @since 4.3\n\t */\n\tpublic class ProfilingATNSimulator : ParserATNSimulator\n\t{\n\tprotected readonly DecisionInfo[] decisions;\n\tprotected int numDecisions;\n\n\t\tprotected int sllStopIndex;\n\t\tprotected int llStopIndex;\n\n\tprotected int currentDecision;\n\tprotected DFAState currentState;\n\n\t/** At the point of LL failover, we record how SLL would resolve the conflict so that\n\t *  we can determine whether or not a decision / input pair is context-sensitive.\n\t *  If LL gives a different result than SLL's predicted alternative, we have a\n\t *  context sensitivity for sure. The converse is not necessarily true, however.\n\t *  It's possible that after conflict resolution chooses minimum alternatives,\n\t *  SLL could get the same answer as LL. Regardless of whether or not the result indicates\n\t *  an ambiguity, it is not treated as a context sensitivity because LL prediction\n\t *  was not required in order to produce a correct prediction for this decision and input sequence.\n\t *  It may in fact still be a context sensitivity but we don't know by looking at the\n\t *  minimum alternatives for the current input.\n \t */\n\tprotected int conflictingAltResolvedBySLL;\n\n\tpublic ProfilingATNSimulator(Parser parser)\n\n\t\t: base(parser,\n\t\t\t\tparser.Interpreter.atn,\n\t\t\t\tparser.Interpreter.decisionToDFA,\n\t\t\t   parser.Interpreter.getSharedContextCache())\n\t\t{\n\t\t\tnumDecisions = atn.decisionToState.Count;\n\t\tdecisions = new DecisionInfo[numDecisions];\n\t\tfor (int i = 0; i < numDecisions; i++)\n\t\t{\n\t\t\tdecisions[i] = new DecisionInfo(i);\n\t\t}\n\t}\n\n\tpublic override int AdaptivePredict(ITokenStream input, int decision, ParserRuleContext outerContext)\n\t{\n\t\ttry\n\t\t{\n\t\t\tthis.sllStopIndex = -1;\n\t\t\tthis.llStopIndex = -1;\n\t\t\tthis.currentDecision = decision;\n\t\t\t\tlong start = DateTime.Now.ToFileTime(); // expensive but useful info\n\t\t\tint alt = base.AdaptivePredict(input, decision, outerContext);\n\t\t\tlong stop = DateTime.Now.ToFileTime();\n\t\t\tdecisions[decision].timeInPrediction += (stop - start);\n\t\t\tdecisions[decision].invocations++;\n\n\t\t\tint SLL_k = sllStopIndex - startIndex + 1;\n\t\t\tdecisions[decision].SLL_TotalLook += SLL_k;\n\t\t\tdecisions[decision].SLL_MinLook = decisions[decision].SLL_MinLook == 0 ? SLL_k : Math.Min(decisions[decision].SLL_MinLook, SLL_k);\n\t\t\tif (SLL_k > decisions[decision].SLL_MaxLook)\n\t\t\t{\n\t\t\t\tdecisions[decision].SLL_MaxLook = SLL_k;\n\t\t\t\tdecisions[decision].SLL_MaxLookEvent =\n\t\t\t\t\t\tnew LookaheadEventInfo(decision, null, alt, input, startIndex, sllStopIndex, false);\n\t\t\t}\n\n\t\t\tif (llStopIndex >= 0)\n\t\t\t{\n\t\t\t\tint LL_k = llStopIndex - startIndex + 1;\n\t\t\t\tdecisions[decision].LL_TotalLook += LL_k;\n\t\t\t\tdecisions[decision].LL_MinLook = decisions[decision].LL_MinLook == 0 ? LL_k : Math.Min(decisions[decision].LL_MinLook, LL_k);\n\t\t\t\tif (LL_k > decisions[decision].LL_MaxLook)\n\t\t\t\t{\n\t\t\t\t\tdecisions[decision].LL_MaxLook = LL_k;\n\t\t\t\t\tdecisions[decision].LL_MaxLookEvent =\n\t\t\t\t\t\t\tnew LookaheadEventInfo(decision, null, alt, input, startIndex, llStopIndex, true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn alt;\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tthis.currentDecision = -1;\n\t\t}\n\t}\n\n\tprotected override DFAState GetExistingTargetState(DFAState previousD, int t)\n\t{\n\t\t// this method is called after each time the input position advances\n\t\t// during SLL prediction\n\t\tsllStopIndex = input.Index;\n\n\t\tDFAState existingTargetState = base.GetExistingTargetState(previousD, t);\n\t\tif (existingTargetState != null)\n\t\t{\n\t\t\tdecisions[currentDecision].SLL_DFATransitions++; // count only if we transition over a DFA state\n\t\t\tif (existingTargetState == ERROR)\n\t\t\t{\n\t\t\t\tdecisions[currentDecision].errors.Add(\n\t\t\t\t\t\tnew ErrorInfo(currentDecision, previousD.configSet, input, startIndex, sllStopIndex, false)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tcurrentState = existingTargetState;\n\t\treturn existingTargetState;\n\t}\n\n\tprotected override DFAState ComputeTargetState(DFA dfa, DFAState previousD, int t)\n\t{\n\t\tDFAState state = base.ComputeTargetState(dfa, previousD, t);\n\t\tcurrentState = state;\n\t\treturn state;\n\t}\n\n\tprotected override ATNConfigSet ComputeReachSet(ATNConfigSet closure, int t, bool fullCtx)\n\t{\n\t\tif (fullCtx)\n\t\t{\n\t\t\t// this method is called after each time the input position advances\n\t\t\t// during full context prediction\n\t\t\tllStopIndex = input.Index;\n\t\t}\n\n\t\tATNConfigSet reachConfigs = base.ComputeReachSet(closure, t, fullCtx);\n\t\tif (fullCtx)\n\t\t{\n\t\t\tdecisions[currentDecision].LL_ATNTransitions++; // count computation even if error\n\t\t\tif (reachConfigs != null)\n\t\t\t{\n\t\t\t}\n\t\t\telse { // no reach on current lookahead symbol. ERROR.\n\t\t\t\t   // TODO: does not handle delayed errors per getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule()\n\t\t\t\tdecisions[currentDecision].errors.Add(\n\t\t\t\t\tnew ErrorInfo(currentDecision, closure, input, startIndex, llStopIndex, true)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tdecisions[currentDecision].SLL_ATNTransitions++;\n\t\t\tif (reachConfigs != null)\n\t\t\t{\n\t\t\t}\n\t\t\telse { // no reach on current lookahead symbol. ERROR.\n\t\t\t\tdecisions[currentDecision].errors.Add(\n\t\t\t\t\tnew ErrorInfo(currentDecision, closure, input, startIndex, sllStopIndex, false)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn reachConfigs;\n\t}\n\n\tprotected override bool EvalSemanticContext(SemanticContext pred, ParserRuleContext parserCallStack, int alt, bool fullCtx)\n\t{\n\t\tbool result = base.EvalSemanticContext(pred, parserCallStack, alt, fullCtx);\n\t\tif (!(pred is SemanticContext.PrecedencePredicate)) {\n\t\t\tbool fullContext = llStopIndex >= 0;\n\t\t\tint stopIndex = fullContext ? llStopIndex : sllStopIndex;\n\t\t\tdecisions[currentDecision].predicateEvals.Add(\n\t\t\t\tnew PredicateEvalInfo(currentDecision, input, startIndex, stopIndex, pred, result, alt, fullCtx)\n\t\t\t);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprotected override void ReportAttemptingFullContext(DFA dfa, BitSet conflictingAlts, ATNConfigSet configs, int startIndex, int stopIndex)\n\t{\n\t\tif (conflictingAlts != null)\n\t\t{\n\t\t\tconflictingAltResolvedBySLL = conflictingAlts.NextSetBit(0);\n\t\t}\n\t\telse {\n\t\t\t\tconflictingAltResolvedBySLL = configs.GetAlts().NextSetBit(0);\n\t\t}\n\t\tdecisions[currentDecision].LL_Fallback++;\n\t\tbase.ReportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex);\n\t}\n\n\tprotected override void ReportContextSensitivity(DFA dfa, int prediction, ATNConfigSet configs, int startIndex, int stopIndex)\n\t{\n\t\tif (prediction != conflictingAltResolvedBySLL)\n\t\t{\n\t\t\tdecisions[currentDecision].contextSensitivities.Add(\n\t\t\t\t\tnew ContextSensitivityInfo(currentDecision, configs, input, startIndex, stopIndex)\n\t\t\t);\n\t\t}\n\t\t\tbase.ReportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex);\n\t}\n\n\tprotected override void ReportAmbiguity(DFA dfa, DFAState D, int startIndex, int stopIndex, bool exact,\n\t\t                                    BitSet ambigAlts, ATNConfigSet configs)\n\t{\n\t\tint prediction;\n\t\tif (ambigAlts != null)\n\t\t{\n\t\t\tprediction = ambigAlts.NextSetBit(0);\n\t\t}\n\t\telse {\n\t\t\t\tprediction = configs.GetAlts().NextSetBit(0);\n\t\t}\n\t\t\tif (configs.fullCtx && prediction != conflictingAltResolvedBySLL)\n\t\t{\n\t\t\t// Even though this is an ambiguity we are reporting, we can\n\t\t\t// still detect some context sensitivities.  Both SLL and LL\n\t\t\t// are showing a conflict, hence an ambiguity, but if they resolve\n\t\t\t// to different minimum alternatives we have also identified a\n\t\t\t// context sensitivity.\n\t\t\tdecisions[currentDecision].contextSensitivities.Add( new ContextSensitivityInfo(currentDecision, configs, input, startIndex, stopIndex) );\n\t\t}\n\t\tdecisions[currentDecision].ambiguities.Add(\n\t\t\tnew AmbiguityInfo(currentDecision, configs, ambigAlts,\n\t\t\t\t              input, startIndex, stopIndex, configs.fullCtx)\n\t\t);\n\t\tbase.ReportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts, configs);\n\t}\n\n\t// ---------------------------------------------------------------------\n\n\tpublic DecisionInfo[] getDecisionInfo()\n\t{\n\t\treturn decisions;\n\t}\n\n\tpublic DFAState getCurrentState()\n\t{\n\t\treturn currentState;\n\t}\n}\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/RangeTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class RangeTransition : Transition\n    {\n        public readonly int from;\n\n        public readonly int to;\n\n        public RangeTransition(ATNState target, int from, int to)\n            : base(target)\n        {\n            this.from = from;\n            this.to = to;\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.RANGE;\n            }\n        }\n\n        public override IntervalSet Label\n        {\n            get\n            {\n                return IntervalSet.Of(from, to);\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return symbol >= from && symbol <= to;\n        }\n\n        [return: NotNull]\n        public override string ToString()\n        {\n            return \"'\" + (char)from + \"'..'\" + (char)to + \"'\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/RuleStartState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class RuleStartState : ATNState\n    {\n        public RuleStopState stopState;\n\n        public bool isPrecedenceRule;\n\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.RuleStart;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/RuleStopState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>The last node in the ATN for a rule, unless that rule is the start symbol.</summary>\n    /// <remarks>\n    /// The last node in the ATN for a rule, unless that rule is the start symbol.\n    /// In that case, there is one transition to EOF. Later, we might encode\n    /// references to all calls to this rule to compute FOLLOW sets for\n    /// error handling.\n    /// </remarks>\n    public sealed class RuleStopState : ATNState\n    {\n        public override int NonStopStateNumber\n        {\n            get\n            {\n                return -1;\n            }\n        }\n\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.RuleStop;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/RuleTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class RuleTransition : Transition\n    {\n        /// <summary>Ptr to the rule definition object for this rule ref</summary>\n        public readonly int ruleIndex;\n\n        public readonly int precedence;\n\n        /// <summary>What node to begin computations following ref to rule</summary>\n        [NotNull]\n        public ATNState followState;\n\n        public bool tailCall;\n\n        public bool optimizedTailCall;\n\n        [Obsolete(@\"UseRuleTransition(RuleStartState, int, int, ATNState) instead.\")]\n        public RuleTransition(RuleStartState ruleStart, int ruleIndex, ATNState followState)\n            : this(ruleStart, ruleIndex, 0, followState)\n        {\n        }\n\n        public RuleTransition(RuleStartState ruleStart, int ruleIndex, int precedence, ATNState followState)\n            : base(ruleStart)\n        {\n            // no Rule object at runtime\n            this.ruleIndex = ruleIndex;\n            this.precedence = precedence;\n            this.followState = followState;\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.RULE;\n            }\n        }\n\n        public override bool IsEpsilon\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/SemanticContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public abstract class SemanticContext\n    {\n        public abstract bool Eval<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            where ATNInterpreter : ATNSimulator;\n\n\t\tpublic virtual SemanticContext EvalPrecedence<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            where ATNInterpreter : ATNSimulator\n        {\n            return this;\n        }\n\n        public class Empty : SemanticContext\n        {\n            public static readonly SemanticContext Instance = new Empty();\n\n            public override bool Eval<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                return false;\n            }\n        }\n\n        public class Predicate : SemanticContext\n        {\n            public readonly int ruleIndex;\n\n            public readonly int predIndex;\n\n            public readonly bool isCtxDependent;\n\n            protected internal Predicate()\n            {\n                // e.g., $i ref in pred\n                this.ruleIndex = -1;\n                this.predIndex = -1;\n                this.isCtxDependent = false;\n            }\n\n            public Predicate(int ruleIndex, int predIndex, bool isCtxDependent)\n            {\n                this.ruleIndex = ruleIndex;\n                this.predIndex = predIndex;\n                this.isCtxDependent = isCtxDependent;\n            }\n\n            public override bool Eval<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                RuleContext localctx = isCtxDependent ? parserCallStack : null;\n                return parser.Sempred(localctx, ruleIndex, predIndex);\n            }\n\n            public override int GetHashCode()\n            {\n                int hashCode = MurmurHash.Initialize();\n                hashCode = MurmurHash.Update(hashCode, ruleIndex);\n                hashCode = MurmurHash.Update(hashCode, predIndex);\n                hashCode = MurmurHash.Update(hashCode, isCtxDependent ? 1 : 0);\n                hashCode = MurmurHash.Finish(hashCode, 3);\n                return hashCode;\n            }\n\n            public override bool Equals(object obj)\n            {\n                if (!(obj is SemanticContext.Predicate))\n                {\n                    return false;\n                }\n                if (this == obj)\n                {\n                    return true;\n                }\n                SemanticContext.Predicate p = (SemanticContext.Predicate)obj;\n                return this.ruleIndex == p.ruleIndex && this.predIndex == p.predIndex && this.isCtxDependent == p.isCtxDependent;\n            }\n\n            public override string ToString()\n            {\n                return \"{\" + ruleIndex + \":\" + predIndex + \"}?\";\n            }\n        }\n\n        public class PrecedencePredicate : SemanticContext, IComparable<SemanticContext.PrecedencePredicate>\n        {\n            public readonly int precedence;\n\n            protected internal PrecedencePredicate()\n            {\n                this.precedence = 0;\n            }\n\n            public PrecedencePredicate(int precedence)\n            {\n                this.precedence = precedence;\n            }\n\n            public override bool Eval<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                return parser.Precpred(parserCallStack, precedence);\n            }\n\n            public override SemanticContext EvalPrecedence<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                if (parser.Precpred(parserCallStack, precedence))\n                {\n                    return SemanticContext.Empty.Instance;\n                }\n                else\n                {\n                    return null;\n                }\n            }\n\n            public virtual int CompareTo(SemanticContext.PrecedencePredicate o)\n            {\n                return precedence - o.precedence;\n            }\n\n            public override int GetHashCode()\n            {\n                int hashCode = 1;\n                hashCode = 31 * hashCode + precedence;\n                return hashCode;\n            }\n\n            public override bool Equals(object obj)\n            {\n                if (!(obj is SemanticContext.PrecedencePredicate))\n                {\n                    return false;\n                }\n                if (this == obj)\n                {\n                    return true;\n                }\n                SemanticContext.PrecedencePredicate other = (SemanticContext.PrecedencePredicate)obj;\n                return this.precedence == other.precedence;\n            }\n\n            public override string ToString()\n            {\n                // precedence >= _precedenceStack.peek()\n                return \"{\" + precedence + \">=prec}?\";\n            }\n        }\n\n        public abstract class Operator : SemanticContext\n        {\n            [NotNull]\n            public abstract ICollection<SemanticContext> Operands\n            {\n                get;\n            }\n        }\n\n        public class AND : SemanticContext.Operator\n        {\n            [NotNull]\n            public readonly SemanticContext[] opnds;\n\n            public AND(SemanticContext a, SemanticContext b)\n            {\n                HashSet<SemanticContext> operands = new HashSet<SemanticContext>();\n                if (a is SemanticContext.AND)\n                {\n                    operands.UnionWith(((AND)a).opnds);\n                }\n                else\n                {\n                    operands.Add(a);\n                }\n                if (b is SemanticContext.AND)\n                {\n                    operands.UnionWith(((AND)b).opnds);\n                }\n                else\n                {\n                    operands.Add(b);\n                }\n                IList<SemanticContext.PrecedencePredicate> precedencePredicates = FilterPrecedencePredicates(operands);\n                if (precedencePredicates.Count > 0)\n                {\n                    // interested in the transition with the lowest precedence\n                    SemanticContext.PrecedencePredicate reduced = precedencePredicates.Min();\n                    operands.Add(reduced);\n                }\n                opnds = operands.ToArray();\n            }\n\n            public override ICollection<SemanticContext> Operands\n            {\n                get\n                {\n                    return Arrays.AsList(opnds);\n                }\n            }\n\n            public override bool Equals(object obj)\n            {\n                if (this == obj)\n                {\n                    return true;\n                }\n                if (!(obj is SemanticContext.AND))\n                {\n                    return false;\n                }\n                SemanticContext.AND other = (SemanticContext.AND)obj;\n                return Arrays.Equals(this.opnds, other.opnds);\n            }\n\n            public override int GetHashCode()\n            {\n                return MurmurHash.HashCode(opnds, typeof(SemanticContext.AND).GetHashCode());\n            }\n\n            public override bool Eval<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                foreach (SemanticContext opnd in opnds)\n                {\n                    if (!opnd.Eval(parser, parserCallStack))\n                    {\n                        return false;\n                    }\n                }\n                return true;\n            }\n\n            public override SemanticContext EvalPrecedence<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                bool differs = false;\n                IList<SemanticContext> operands = new List<SemanticContext>();\n                foreach (SemanticContext context in opnds)\n                {\n                    SemanticContext evaluated = context.EvalPrecedence(parser, parserCallStack);\n                    differs |= (evaluated != context);\n                    if (evaluated == null)\n                    {\n                        // The AND context is false if any element is false\n                        return null;\n                    }\n                    else\n                    {\n                        if (evaluated != Empty.Instance)\n                        {\n                            // Reduce the result by skipping true elements\n                            operands.Add(evaluated);\n                        }\n                    }\n                }\n                if (!differs)\n                {\n                    return this;\n                }\n                if (operands.Count == 0)\n                {\n                    // all elements were true, so the AND context is true\n                    return Empty.Instance;\n                }\n                SemanticContext result = operands[0];\n                for (int i = 1; i < operands.Count; i++)\n                {\n                    result = SemanticContext.AndOp(result, operands[i]);\n                }\n                return result;\n            }\n\n            public override string ToString()\n            {\n                return Utils.Join(\"&&\", opnds);\n            }\n        }\n\n        public class OR : SemanticContext.Operator\n        {\n            [NotNull]\n            public readonly SemanticContext[] opnds;\n\n            public OR(SemanticContext a, SemanticContext b)\n            {\n                HashSet<SemanticContext> operands = new HashSet<SemanticContext>();\n                if (a is SemanticContext.OR)\n                {\n                    operands.UnionWith(((OR)a).opnds);\n                }\n                else\n                {\n                    operands.Add(a);\n                }\n                if (b is SemanticContext.OR)\n                {\n                    operands.UnionWith(((OR)b).opnds);\n                }\n                else\n                {\n                    operands.Add(b);\n                }\n                IList<SemanticContext.PrecedencePredicate> precedencePredicates = FilterPrecedencePredicates(operands);\n                if (precedencePredicates.Count > 0)\n                {\n                    // interested in the transition with the highest precedence\n                    SemanticContext.PrecedencePredicate reduced = precedencePredicates.Max();\n                    operands.Add(reduced);\n                }\n                this.opnds = operands.ToArray();\n            }\n\n            public override ICollection<SemanticContext> Operands\n            {\n                get\n                {\n                    return Arrays.AsList(opnds);\n                }\n            }\n\n            public override bool Equals(object obj)\n            {\n                if (this == obj)\n                {\n                    return true;\n                }\n                if (!(obj is SemanticContext.OR))\n                {\n                    return false;\n                }\n                SemanticContext.OR other = (SemanticContext.OR)obj;\n                return Arrays.Equals(this.opnds, other.opnds);\n            }\n\n            public override int GetHashCode()\n            {\n                return MurmurHash.HashCode(opnds, typeof(SemanticContext.OR).GetHashCode());\n            }\n\n            public override bool Eval<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                foreach (SemanticContext opnd in opnds)\n                {\n                    if (opnd.Eval(parser, parserCallStack))\n                    {\n                        return true;\n                    }\n                }\n                return false;\n            }\n\n            public override SemanticContext EvalPrecedence<Symbol, ATNInterpreter>(Recognizer<Symbol, ATNInterpreter> parser, RuleContext parserCallStack)\n            {\n                bool differs = false;\n                IList<SemanticContext> operands = new List<SemanticContext>();\n                foreach (SemanticContext context in opnds)\n                {\n                    SemanticContext evaluated = context.EvalPrecedence(parser, parserCallStack);\n                    differs |= (evaluated != context);\n                    if (evaluated == Empty.Instance)\n                    {\n                        // The OR context is true if any element is true\n                        return Empty.Instance;\n                    }\n                    else\n                    {\n                        if (evaluated != null)\n                        {\n                            // Reduce the result by skipping false elements\n                            operands.Add(evaluated);\n                        }\n                    }\n                }\n                if (!differs)\n                {\n                    return this;\n                }\n                if (operands.Count == 0)\n                {\n                    // all elements were false, so the OR context is false\n                    return null;\n                }\n                SemanticContext result = operands[0];\n                for (int i = 1; i < operands.Count; i++)\n                {\n                    result = SemanticContext.OrOp(result, operands[i]);\n                }\n                return result;\n            }\n\n            public override string ToString()\n            {\n                return Utils.Join(\"||\", opnds);\n            }\n        }\n\n        public static SemanticContext AndOp(SemanticContext a, SemanticContext b)\n        {\n            if (a == null || a == Empty.Instance)\n            {\n                return b;\n            }\n            if (b == null || b == Empty.Instance)\n            {\n                return a;\n            }\n            SemanticContext.AND result = new SemanticContext.AND(a, b);\n            if (result.opnds.Length == 1)\n            {\n                return result.opnds[0];\n            }\n            return result;\n        }\n\n        public static SemanticContext OrOp(SemanticContext a, SemanticContext b)\n        {\n            if (a == null)\n            {\n                return b;\n            }\n            if (b == null)\n            {\n                return a;\n            }\n            if (a == Empty.Instance || b == Empty.Instance)\n            {\n                return Empty.Instance;\n            }\n            SemanticContext.OR result = new SemanticContext.OR(a, b);\n            if (result.opnds.Length == 1)\n            {\n                return result.opnds[0];\n            }\n            return result;\n        }\n\n        private static IList<SemanticContext.PrecedencePredicate> FilterPrecedencePredicates(HashSet<SemanticContext> collection)\n        {\n            if (!collection.OfType<PrecedencePredicate>().Any())\n                Collections.EmptyList<PrecedencePredicate>();\n\n            List<PrecedencePredicate> result = collection.OfType<PrecedencePredicate>().ToList();\n            collection.ExceptWith(result);\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/SetTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>A transition containing a set of values.</summary>\n    /// <remarks>A transition containing a set of values.</remarks>\n    public class SetTransition : Transition\n    {\n        [NotNull]\n        public readonly IntervalSet set;\n\n        public SetTransition(ATNState target, IntervalSet set)\n            : base(target)\n        {\n            // TODO (sam): should we really allow null here?\n            if (set == null)\n            {\n                set = IntervalSet.Of(TokenConstants.InvalidType);\n            }\n            this.set = set;\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.SET;\n            }\n        }\n\n        public override IntervalSet Label\n        {\n            get\n            {\n                return set;\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return set.Contains(symbol);\n        }\n\n        [return: NotNull]\n        public override string ToString()\n        {\n            return set.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/SimulatorState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <author>Sam Harwell</author>\n    public class SimulatorState\n    {\n        public readonly ParserRuleContext outerContext;\n\n        public readonly DFAState s0;\n\n        public readonly bool useContext;\n\n        public readonly ParserRuleContext remainingOuterContext;\n\n        public SimulatorState(ParserRuleContext outerContext, DFAState s0, bool useContext, ParserRuleContext remainingOuterContext)\n        {\n            this.outerContext = outerContext != null ? outerContext : ParserRuleContext.EmptyContext;\n            this.s0 = s0;\n            this.useContext = useContext;\n            this.remainingOuterContext = remainingOuterContext;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/SingletonPredictionContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Atn\n{\n#pragma warning disable 0659 // 'class' overrides Object.Equals(object o) but does not override Object.GetHashCode()\n\n\tpublic class SingletonPredictionContext : PredictionContext\n    {\n\t\tpublic static PredictionContext Create(PredictionContext parent, int returnState)\n\t\t{\n\t\t\tif (returnState == EMPTY_RETURN_STATE && parent == null)\n\t\t\t{\n\t\t\t\t// someone can pass in the bits of an array ctx that mean $\n\t\t\t\treturn EmptyPredictionContext.Instance;\n\t\t\t}\n\t\t\treturn new SingletonPredictionContext(parent, returnState);\n\t\t}\n\n        [NotNull]\n        public readonly PredictionContext parent;\n\n        public readonly int returnState;\n\n        internal SingletonPredictionContext(PredictionContext parent, int returnState)\n            : base(CalculateHashCode(parent, returnState))\n        {\n            this.parent = parent;\n            this.returnState = returnState;\n        }\n\n        public override PredictionContext GetParent(int index)\n        {\n            System.Diagnostics.Debug.Assert(index == 0);\n            return parent;\n        }\n\n        public override int GetReturnState(int index)\n        {\n            System.Diagnostics.Debug.Assert(index == 0);\n            return returnState;\n        }\n\n\n        public override int Size\n        {\n            get\n            {\n                return 1;\n            }\n        }\n\n        public override bool IsEmpty\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public override bool Equals(object o)\n        {\n            if (o == this)\n            {\n                return true;\n            }\n            else\n            {\n                if (!(o is Antlr4.Runtime.Atn.SingletonPredictionContext))\n                {\n                    return false;\n                }\n            }\n            if (this.GetHashCode() != o.GetHashCode())\n            {\n                return false;\n            }\n\t\t\tAntlr4.Runtime.Atn.SingletonPredictionContext other = (Antlr4.Runtime.Atn.SingletonPredictionContext)o;\n            return returnState == other.returnState && (parent != null && parent.Equals(other.parent));\n        }\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\tstring up = parent != null ? parent.ToString() : \"\";\n\t\t\tif (up.Length == 0)\n\t\t\t{\n\t\t\t\tif (returnState == EMPTY_RETURN_STATE)\n\t\t\t\t{\n\t\t\t\t\treturn \"$\";\n\t\t\t\t}\n\t\t\t\treturn returnState.ToString();\n\t\t\t}\n\t\t\treturn returnState.ToString() + \" \" + up;\n\t\t}\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/StarBlockStartState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>The block that begins a closure loop.</summary>\n    /// <remarks>The block that begins a closure loop.</remarks>\n    public sealed class StarBlockStartState : BlockStartState\n    {\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.StarBlockStart;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/StarLoopEntryState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class StarLoopEntryState : DecisionState\n    {\n        public StarLoopbackState loopBackState;\n\n        /// <summary>\n        /// Indicates whether this state can benefit from a precedence DFA during SLL\n        /// decision making.\n        /// </summary>\n        /// <remarks>\n        /// Indicates whether this state can benefit from a precedence DFA during SLL\n        /// decision making.\n        /// <p>This is a computed property that is calculated during ATN deserialization\n        /// and stored for use in\n        /// <see cref=\"ParserATNSimulator\"/>\n        /// and\n        /// <see cref=\"Antlr4.Runtime.ParserInterpreter\"/>\n        /// .</p>\n        /// </remarks>\n        /// <seealso cref=\"Antlr4.Runtime.Dfa.DFA.IsPrecedenceDfa()\"/>\n        public bool isPrecedenceDecision;\n\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.StarLoopEntry;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/StarLoopbackState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class StarLoopbackState : ATNState\n    {\n        public StarLoopEntryState LoopEntryState\n        {\n            get\n            {\n                return (StarLoopEntryState)Transition(0).target;\n            }\n        }\n\n        public override Antlr4.Runtime.Atn.StateType StateType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.StateType.StarLoopBack;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/StateType.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Atn\n{\n    public enum StateType\n    {\n        InvalidType,\n        Basic,\n        RuleStart,\n        BlockStart,\n        PlusBlockStart,\n        StarBlockStart,\n        TokenStart,\n        RuleStop,\n        BlockEnd,\n        StarLoopBack,\n        StarLoopEntry,\n        PlusLoopBack,\n        LoopEnd\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/TokensStartState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>The Tokens rule start state linking to each lexer rule start state</summary>\n    public sealed class TokensStartState : DecisionState\n    {\n        public override StateType StateType\n        {\n            get\n            {\n                return StateType.TokenStart;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/Transition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.ObjectModel;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Atn\n{\n    /// <summary>An ATN transition between any two ATN states.</summary>\n    /// <remarks>\n    /// An ATN transition between any two ATN states.  Subclasses define\n    /// atom, set, epsilon, action, predicate, rule transitions.\n    /// <p>This is a one way link.  It emanates from a state (usually via a list of\n    /// transitions) and has a target state.</p>\n    /// <p>Since we never have to change the ATN transitions once we construct it,\n    /// we can fix these transitions as specific classes. The DFA transitions\n    /// on the other hand need to update the labels as it adds transitions to\n    /// the states. We'll use the term Edge for the DFA to distinguish them from\n    /// ATN transitions.</p>\n    /// </remarks>\n    public abstract class Transition\n    {\n        public static readonly ReadOnlyCollection<string> serializationNames = new ReadOnlyCollection<string>(Arrays.AsList(\"INVALID\", \"EPSILON\", \"RANGE\", \"RULE\", \"PREDICATE\", \"ATOM\", \"ACTION\", \"SET\", \"NOT_SET\", \"WILDCARD\", \"PRECEDENCE\"));\n\n        /// <summary>The target of this transition.</summary>\n        /// <remarks>The target of this transition.</remarks>\n        [NotNull]\n        public ATNState target;\n\n        protected internal Transition(ATNState target)\n        {\n            if (target == null)\n            {\n                throw new ArgumentNullException(\"target cannot be null.\");\n            }\n            this.target = target;\n        }\n\n        public abstract TransitionType TransitionType\n        {\n            get;\n        }\n\n        /// <summary>Determines if the transition is an \"epsilon\" transition.</summary>\n        /// <remarks>\n        /// Determines if the transition is an \"epsilon\" transition.\n        /// <p>The default implementation returns\n        /// <see langword=\"false\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if traversing this transition in the ATN does not\n        /// consume an input symbol; otherwise,\n        /// <see langword=\"false\"/>\n        /// if traversing this\n        /// transition consumes (matches) an input symbol.\n        /// </returns>\n        public virtual bool IsEpsilon\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public virtual IntervalSet Label\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        public abstract bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/TransitionType.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Atn\n{\n    public enum TransitionType\n    {\n\t\tINVALID,\n        EPSILON,\n        RANGE,\n        RULE,\n        PREDICATE,\n        ATOM,\n        ACTION,\n        SET,\n        NOT_SET,\n        WILDCARD,\n        PRECEDENCE\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Atn/WildcardTransition.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Atn\n{\n    public sealed class WildcardTransition : Transition\n    {\n        public WildcardTransition(ATNState target)\n            : base(target)\n        {\n        }\n\n        public override Antlr4.Runtime.Atn.TransitionType TransitionType\n        {\n            get\n            {\n                return Antlr4.Runtime.Atn.TransitionType.WILDCARD;\n            }\n        }\n\n        public override bool Matches(int symbol, int minVocabSymbol, int maxVocabSymbol)\n        {\n            return symbol >= minVocabSymbol && symbol <= maxVocabSymbol;\n        }\n\n        [return: NotNull]\n        public override string ToString()\n        {\n            return \".\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/BailErrorStrategy.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This implementation of\n    /// <see cref=\"IAntlrErrorStrategy\"/>\n    /// responds to syntax errors\n    /// by immediately canceling the parse operation with a\n    /// <see cref=\"ParseCanceledException\"/>\n    /// . The implementation ensures that the\n    /// <see cref=\"ParserRuleContext.exception\"/>\n    /// field is set for all parse tree nodes\n    /// that were not completed prior to encountering the error.\n    /// <p>\n    /// This error strategy is useful in the following scenarios.</p>\n    /// <ul>\n    /// <li><strong>Two-stage parsing:</strong> This error strategy allows the first\n    /// stage of two-stage parsing to immediately terminate if an error is\n    /// encountered, and immediately fall back to the second stage. In addition to\n    /// avoiding wasted work by attempting to recover from errors here, the empty\n    /// implementation of\n    /// <see cref=\"Sync(Parser)\"/>\n    /// improves the performance of\n    /// the first stage.</li>\n    /// <li><strong>Silent validation:</strong> When syntax errors are not being\n    /// reported or logged, and the parse result is simply ignored if errors occur,\n    /// the\n    /// <see cref=\"BailErrorStrategy\"/>\n    /// avoids wasting work on recovering from errors\n    /// when the result will be ignored either way.</li>\n    /// </ul>\n    /// <p>\n    /// <c>myparser.setErrorHandler(new BailErrorStrategy());</c>\n    /// </p>\n    /// </summary>\n    /// <seealso cref=\"Parser.ErrorHandler\"/>\n    public class BailErrorStrategy : DefaultErrorStrategy\n    {\n        /// <summary>\n        /// Instead of recovering from exception\n        /// <paramref name=\"e\"/>\n        /// , re-throw it wrapped\n        /// in a\n        /// <see cref=\"ParseCanceledException\"/>\n        /// so it is not caught by the\n        /// rule function catches.  Use\n        /// <see cref=\"System.Exception.InnerException()\"/>\n        /// to get the\n        /// original\n        /// <see cref=\"RecognitionException\"/>\n        /// .\n        /// </summary>\n        public override void Recover(Parser recognizer, RecognitionException e)\n        {\n            for (ParserRuleContext context = recognizer.Context; context != null; context = ((ParserRuleContext)context.Parent))\n            {\n                context.exception = e;\n            }\n            throw new ParseCanceledException(e);\n        }\n\n        /// <summary>\n        /// Make sure we don't attempt to recover inline; if the parser\n        /// successfully recovers, it won't throw an exception.\n        /// </summary>\n        /// <remarks>\n        /// Make sure we don't attempt to recover inline; if the parser\n        /// successfully recovers, it won't throw an exception.\n        /// </remarks>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        public override IToken RecoverInline(Parser recognizer)\n        {\n            InputMismatchException e = new InputMismatchException(recognizer);\n            for (ParserRuleContext context = recognizer.Context; context != null; context = ((ParserRuleContext)context.Parent))\n            {\n                context.exception = e;\n            }\n            throw new ParseCanceledException(e);\n        }\n\n        /// <summary>Make sure we don't attempt to recover from problems in subrules.</summary>\n        /// <remarks>Make sure we don't attempt to recover from problems in subrules.</remarks>\n        public override void Sync(Parser recognizer)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/BaseErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Sharpen;\nusing System.IO;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// Provides an empty default implementation of\n    /// <see cref=\"IAntlrErrorListener{Symbol}\"/>\n    /// . The\n    /// default implementation of each method does nothing, but can be overridden as\n    /// necessary.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    public class BaseErrorListener : IParserErrorListener\n    {\n        public virtual void SyntaxError(TextWriter output, IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)\n        {\n        }\n\n        public virtual void ReportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, bool exact, BitSet ambigAlts, ATNConfigSet configs)\n        {\n        }\n\n        public virtual void ReportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs)\n        {\n        }\n\n        public virtual void ReportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/BufferedTokenStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This implementation of\n    /// <see cref=\"ITokenStream\"/>\n    /// loads tokens from a\n    /// <see cref=\"ITokenSource\"/>\n    /// on-demand, and places the tokens in a buffer to provide\n    /// access to any previous token by index.\n    /// <p>\n    /// This token stream ignores the value of\n    /// <see cref=\"IToken.Channel()\"/>\n    /// . If your\n    /// parser requires the token stream filter tokens to only those on a particular\n    /// channel, such as\n    /// <see cref=\"TokenConstants.DefaultChannel\"/>\n    /// or\n    /// <see cref=\"TokenConstants.HiddenChannel\"/>\n    /// , use a filtering token stream such a\n    /// <see cref=\"CommonTokenStream\"/>\n    /// .</p>\n    /// </summary>\n    public class BufferedTokenStream : ITokenStream\n    {\n        /// <summary>\n        /// The\n        /// <see cref=\"ITokenSource\"/>\n        /// from which tokens for this stream are fetched.\n        /// </summary>\n        [NotNull]\n        private ITokenSource _tokenSource;\n\n        /// <summary>A collection of all tokens fetched from the token source.</summary>\n        /// <remarks>\n        /// A collection of all tokens fetched from the token source. The list is\n        /// considered a complete view of the input once\n        /// <see cref=\"fetchedEOF\"/>\n        /// is set\n        /// to\n        /// <see langword=\"true\"/>\n        /// .\n        /// </remarks>\n        protected internal IList<IToken> tokens = new List<IToken>(100);\n\n        /// <summary>\n        /// The index into\n        /// <see cref=\"tokens\"/>\n        /// of the current token (next token to\n        /// <see cref=\"Consume()\"/>\n        /// ).\n        /// <see cref=\"tokens\"/>\n        /// <c>[</c>\n        /// <see cref=\"p\"/>\n        /// <c>]</c>\n        /// should be\n        /// <see cref=\"LT(int)\">LT(1)</see>\n        /// .\n        /// <p>This field is set to -1 when the stream is first constructed or when\n        /// <see cref=\"SetTokenSource(ITokenSource)\"/>\n        /// is called, indicating that the first token has\n        /// not yet been fetched from the token source. For additional information,\n        /// see the documentation of\n        /// <see cref=\"IIntStream\"/>\n        /// for a description of\n        /// Initializing Methods.</p>\n        /// </summary>\n        protected internal int p = -1;\n\n        /// <summary>\n        /// Indicates whether the\n        /// <see cref=\"TokenConstants.EOF\"/>\n        /// token has been fetched from\n        /// <see cref=\"_tokenSource\"/>\n        /// and added to\n        /// <see cref=\"tokens\"/>\n        /// . This field improves\n        /// performance for the following cases:\n        /// <ul>\n        /// <li>\n        /// <see cref=\"Consume()\"/>\n        /// : The lookahead check in\n        /// <see cref=\"Consume()\"/>\n        /// to prevent\n        /// consuming the EOF symbol is optimized by checking the values of\n        /// <see cref=\"fetchedEOF\"/>\n        /// and\n        /// <see cref=\"p\"/>\n        /// instead of calling\n        /// <see cref=\"LA(int)\"/>\n        /// .</li>\n        /// <li>\n        /// <see cref=\"Fetch(int)\"/>\n        /// : The check to prevent adding multiple EOF symbols into\n        /// <see cref=\"tokens\"/>\n        /// is trivial with this field.</li>\n        /// </ul>\n        /// </summary>\n        protected internal bool fetchedEOF;\n\n        public BufferedTokenStream(ITokenSource tokenSource)\n        {\n            if (tokenSource == null)\n            {\n                throw new ArgumentNullException(\"tokenSource cannot be null\");\n            }\n            this._tokenSource = tokenSource;\n        }\n\n        public virtual ITokenSource TokenSource\n        {\n            get\n            {\n                return _tokenSource;\n            }\n        }\n\n        public virtual int Index\n        {\n            get\n            {\n                return p;\n            }\n        }\n\n        public virtual int Mark()\n        {\n            return 0;\n        }\n\n        public virtual void Release(int marker)\n        {\n        }\n\n        // no resources to release\n        public virtual void Reset()\n        {\n            Seek(0);\n        }\n\n        public virtual void Seek(int index)\n        {\n            LazyInit();\n            p = AdjustSeekIndex(index);\n        }\n\n        public virtual int Size\n        {\n            get\n            {\n                return tokens.Count;\n            }\n        }\n\n        public virtual void Consume()\n        {\n            bool skipEofCheck;\n            if (p >= 0)\n            {\n                if (fetchedEOF)\n                {\n                    // the last token in tokens is EOF. skip check if p indexes any\n                    // fetched token except the last.\n                    skipEofCheck = p < tokens.Count - 1;\n                }\n                else\n                {\n                    // no EOF token in tokens. skip check if p indexes a fetched token.\n                    skipEofCheck = p < tokens.Count;\n                }\n            }\n            else\n            {\n                // not yet initialized\n                skipEofCheck = false;\n            }\n            if (!skipEofCheck && LA(1) == IntStreamConstants.EOF)\n            {\n                throw new InvalidOperationException(\"cannot consume EOF\");\n            }\n            if (Sync(p + 1))\n            {\n                p = AdjustSeekIndex(p + 1);\n            }\n        }\n\n        /// <summary>\n        /// Make sure index\n        /// <paramref name=\"i\"/>\n        /// in tokens has a token.\n        /// </summary>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if a token is located at index\n        /// <paramref name=\"i\"/>\n        /// , otherwise\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        /// <seealso cref=\"Get(int)\"/>\n        protected internal virtual bool Sync(int i)\n        {\n            System.Diagnostics.Debug.Assert(i >= 0);\n            int n = i - tokens.Count + 1;\n            // how many more elements we need?\n            //System.out.println(\"sync(\"+i+\") needs \"+n);\n            if (n > 0)\n            {\n                int fetched = Fetch(n);\n                return fetched >= n;\n            }\n            return true;\n        }\n\n        /// <summary>\n        /// Add\n        /// <paramref name=\"n\"/>\n        /// elements to buffer.\n        /// </summary>\n        /// <returns>The actual number of elements added to the buffer.</returns>\n        protected internal virtual int Fetch(int n)\n        {\n            if (fetchedEOF)\n            {\n                return 0;\n            }\n            for (int i = 0; i < n; i++)\n            {\n                IToken t = _tokenSource.NextToken();\n                if (t is IWritableToken)\n                {\n                    ((IWritableToken)t).TokenIndex = tokens.Count;\n                }\n                tokens.Add(t);\n                if (t.Type == TokenConstants.EOF)\n                {\n                    fetchedEOF = true;\n                    return i + 1;\n                }\n            }\n            return n;\n        }\n\n        public virtual IToken Get(int i)\n        {\n            if (i < 0 || i >= tokens.Count)\n            {\n                throw new ArgumentOutOfRangeException(\"token index \" + i + \" out of range 0..\" + (tokens.Count - 1));\n            }\n            return tokens[i];\n        }\n\n        /// <summary>Get all tokens from start..stop inclusively.</summary>\n        /// <remarks>Get all tokens from start..stop inclusively.</remarks>\n        public virtual IList<IToken> Get(int start, int stop)\n        {\n            if (start < 0 || stop < 0)\n            {\n                return null;\n            }\n            LazyInit();\n            IList<IToken> subset = new List<IToken>();\n            if (stop >= tokens.Count)\n            {\n                stop = tokens.Count - 1;\n            }\n            for (int i = start; i <= stop; i++)\n            {\n                IToken t = tokens[i];\n                if (t.Type == TokenConstants.EOF)\n                {\n                    break;\n                }\n                subset.Add(t);\n            }\n            return subset;\n        }\n\n        public virtual int LA(int i)\n        {\n            return LT(i).Type;\n        }\n\n        protected internal virtual IToken Lb(int k)\n        {\n            if ((p - k) < 0)\n            {\n                return null;\n            }\n            return tokens[p - k];\n        }\n\n        [return: NotNull]\n        public virtual IToken LT(int k)\n        {\n            LazyInit();\n            if (k == 0)\n            {\n                return null;\n            }\n            if (k < 0)\n            {\n                return Lb(-k);\n            }\n            int i = p + k - 1;\n            Sync(i);\n            if (i >= tokens.Count)\n            {\n                // return EOF token\n                // EOF must be last token\n                return tokens[tokens.Count - 1];\n            }\n            //\t\tif ( i>range ) range = i;\n            return tokens[i];\n        }\n\n        /// <summary>\n        /// Allowed derived classes to modify the behavior of operations which change\n        /// the current stream position by adjusting the target token index of a seek\n        /// operation.\n        /// </summary>\n        /// <remarks>\n        /// Allowed derived classes to modify the behavior of operations which change\n        /// the current stream position by adjusting the target token index of a seek\n        /// operation. The default implementation simply returns\n        /// <paramref name=\"i\"/>\n        /// . If an\n        /// exception is thrown in this method, the current stream index should not be\n        /// changed.\n        /// <p>For example,\n        /// <see cref=\"CommonTokenStream\"/>\n        /// overrides this method to ensure that\n        /// the seek target is always an on-channel token.</p>\n        /// </remarks>\n        /// <param name=\"i\">The target token index.</param>\n        /// <returns>The adjusted target token index.</returns>\n        protected internal virtual int AdjustSeekIndex(int i)\n        {\n            return i;\n        }\n\n        protected internal void LazyInit()\n        {\n            if (p == -1)\n            {\n                Setup();\n            }\n        }\n\n        protected internal virtual void Setup()\n        {\n            Sync(0);\n            p = AdjustSeekIndex(0);\n        }\n\n        /// <summary>Reset this token stream by setting its token source.</summary>\n        /// <remarks>Reset this token stream by setting its token source.</remarks>\n        public virtual void SetTokenSource(ITokenSource tokenSource)\n        {\n            this._tokenSource = tokenSource;\n            tokens.Clear();\n            p = -1;\n\t\t\tthis.fetchedEOF = false;\n        }\n\n        public virtual IList<IToken> GetTokens()\n        {\n            return tokens;\n        }\n\n        public virtual IList<IToken> GetTokens(int start, int stop)\n        {\n            return GetTokens(start, stop, null);\n        }\n\n        /// <summary>\n        /// Given a start and stop index, return a\n        /// <c>List</c>\n        /// of all tokens in\n        /// the token type\n        /// <c>BitSet</c>\n        /// .  Return\n        /// <see langword=\"null\"/>\n        /// if no tokens were found.  This\n        /// method looks at both on and off channel tokens.\n        /// </summary>\n        public virtual IList<IToken> GetTokens(int start, int stop, BitSet types)\n        {\n            LazyInit();\n            if (start < 0 || stop >= tokens.Count || stop < 0 || start >= tokens.Count)\n            {\n                throw new ArgumentOutOfRangeException(\"start \" + start + \" or stop \" + stop + \" not in 0..\" + (tokens.Count - 1));\n            }\n            if (start > stop)\n            {\n                return null;\n            }\n            // list = tokens[start:stop]:{T t, t.getType() in types}\n            IList<IToken> filteredTokens = new List<IToken>();\n            for (int i = start; i <= stop; i++)\n            {\n                IToken t = tokens[i];\n                if (types == null || types.Get(t.Type))\n                {\n                    filteredTokens.Add(t);\n                }\n            }\n            if (filteredTokens.Count == 0)\n            {\n                filteredTokens = null;\n            }\n            return filteredTokens;\n        }\n\n        public virtual IList<IToken> GetTokens(int start, int stop, int ttype)\n        {\n            BitSet s = new BitSet(ttype);\n            s.Set(ttype);\n            return GetTokens(start, stop, s);\n        }\n\n        /// <summary>Given a starting index, return the index of the next token on channel.</summary>\n        /// <remarks>\n        /// Given a starting index, return the index of the next token on channel.\n        /// Return\n        /// <paramref name=\"i\"/>\n        /// if\n        /// <c>tokens[i]</c>\n        /// is on channel. Return the index of\n        /// the EOF token if there are no tokens on channel between\n        /// <paramref name=\"i\"/>\n        /// and\n        /// EOF.\n        /// </remarks>\n        protected internal virtual int NextTokenOnChannel(int i, int channel)\n        {\n            Sync(i);\n            if (i >= Size)\n            {\n                return Size - 1;\n            }\n            IToken token = tokens[i];\n            while (token.Channel != channel)\n            {\n                if (token.Type == TokenConstants.EOF)\n                {\n                    return i;\n                }\n                i++;\n                Sync(i);\n                token = tokens[i];\n            }\n            return i;\n        }\n\n        /// <summary>\n        /// Given a starting index, return the index of the previous token on\n        /// channel.\n        /// </summary>\n        /// <remarks>\n        /// Given a starting index, return the index of the previous token on\n        /// channel. Return\n        /// <paramref name=\"i\"/>\n        /// if\n        /// <c>tokens[i]</c>\n        /// is on channel. Return -1\n        /// if there are no tokens on channel between\n        /// <paramref name=\"i\"/>\n        /// and 0.\n        /// <p>\n        /// If\n        /// <paramref name=\"i\"/>\n        /// specifies an index at or after the EOF token, the EOF token\n        /// index is returned. This is due to the fact that the EOF token is treated\n        /// as though it were on every channel.</p>\n        /// </remarks>\n        protected internal virtual int PreviousTokenOnChannel(int i, int channel)\n        {\n            Sync(i);\n            if (i >= Size)\n            {\n                // the EOF token is on every channel\n                return Size - 1;\n            }\n            while (i >= 0)\n            {\n                IToken token = tokens[i];\n                if (token.Type == TokenConstants.EOF || token.Channel == channel)\n                {\n                    return i;\n                }\n                i--;\n            }\n            return i;\n        }\n\n        /// <summary>\n        /// Collect all tokens on specified channel to the right of\n        /// the current token up until we see a token on\n        /// <see cref=\"Lexer.DefaultTokenChannel\"/>\n        /// or\n        /// EOF. If\n        /// <paramref name=\"channel\"/>\n        /// is\n        /// <c>-1</c>\n        /// , find any non default channel token.\n        /// </summary>\n        public virtual IList<IToken> GetHiddenTokensToRight(int tokenIndex, int channel)\n        {\n            LazyInit();\n            if (tokenIndex < 0 || tokenIndex >= tokens.Count)\n            {\n                throw new ArgumentOutOfRangeException(tokenIndex + \" not in 0..\" + (tokens.Count - 1));\n            }\n            int nextOnChannel = NextTokenOnChannel(tokenIndex + 1, Lexer.DefaultTokenChannel);\n            int to;\n            int from = tokenIndex + 1;\n            // if none onchannel to right, nextOnChannel=-1 so set to = last token\n            if (nextOnChannel == -1)\n            {\n                to = Size - 1;\n            }\n            else\n            {\n                to = nextOnChannel;\n            }\n            return FilterForChannel(from, to, channel);\n        }\n\n        /// <summary>\n        /// Collect all hidden tokens (any off-default channel) to the right of\n        /// the current token up until we see a token on\n        /// <see cref=\"Lexer.DefaultTokenChannel\"/>\n        /// or EOF.\n        /// </summary>\n        public virtual IList<IToken> GetHiddenTokensToRight(int tokenIndex)\n        {\n            return GetHiddenTokensToRight(tokenIndex, -1);\n        }\n\n        /// <summary>\n        /// Collect all tokens on specified channel to the left of\n        /// the current token up until we see a token on\n        /// <see cref=\"Lexer.DefaultTokenChannel\"/>\n        /// .\n        /// If\n        /// <paramref name=\"channel\"/>\n        /// is\n        /// <c>-1</c>\n        /// , find any non default channel token.\n        /// </summary>\n        public virtual IList<IToken> GetHiddenTokensToLeft(int tokenIndex, int channel)\n        {\n            LazyInit();\n            if (tokenIndex < 0 || tokenIndex >= tokens.Count)\n            {\n                throw new ArgumentOutOfRangeException(tokenIndex + \" not in 0..\" + (tokens.Count - 1));\n            }\n            if (tokenIndex == 0)\n            {\n                // obviously no tokens can appear before the first token\n                return null;\n            }\n            int prevOnChannel = PreviousTokenOnChannel(tokenIndex - 1, Lexer.DefaultTokenChannel);\n            if (prevOnChannel == tokenIndex - 1)\n            {\n                return null;\n            }\n            // if none onchannel to left, prevOnChannel=-1 then from=0\n            int from = prevOnChannel + 1;\n            int to = tokenIndex - 1;\n            return FilterForChannel(from, to, channel);\n        }\n\n        /// <summary>\n        /// Collect all hidden tokens (any off-default channel) to the left of\n        /// the current token up until we see a token on\n        /// <see cref=\"Lexer.DefaultTokenChannel\"/>\n        /// .\n        /// </summary>\n        public virtual IList<IToken> GetHiddenTokensToLeft(int tokenIndex)\n        {\n            return GetHiddenTokensToLeft(tokenIndex, -1);\n        }\n\n        protected internal virtual IList<IToken> FilterForChannel(int from, int to, int channel)\n        {\n            IList<IToken> hidden = new List<IToken>();\n            for (int i = from; i <= to; i++)\n            {\n                IToken t = tokens[i];\n                if (channel == -1)\n                {\n                    if (t.Channel != Lexer.DefaultTokenChannel)\n                    {\n                        hidden.Add(t);\n                    }\n                }\n                else\n                {\n                    if (t.Channel == channel)\n                    {\n                        hidden.Add(t);\n                    }\n                }\n            }\n            if (hidden.Count == 0)\n            {\n                return null;\n            }\n            return hidden;\n        }\n\n        public virtual string SourceName\n        {\n            get\n            {\n                return _tokenSource.SourceName;\n            }\n        }\n\n        /// <summary>Get the text of all tokens in this buffer.</summary>\n        /// <remarks>Get the text of all tokens in this buffer.</remarks>\n        [return: NotNull]\n        public virtual string GetText()\n        {\n            Fill();\n            return GetText(Interval.Of(0, Size - 1));\n        }\n\n        [return: NotNull]\n        public virtual string GetText(Interval interval)\n        {\n            int start = interval.a;\n            int stop = interval.b;\n            if (start < 0 || stop < 0)\n            {\n                return string.Empty;\n            }\n            LazyInit();\n            if (stop >= tokens.Count)\n            {\n                stop = tokens.Count - 1;\n            }\n            StringBuilder buf = new StringBuilder();\n            for (int i = start; i <= stop; i++)\n            {\n                IToken t = tokens[i];\n                if (t.Type == TokenConstants.EOF)\n                {\n                    break;\n                }\n                buf.Append(t.Text);\n            }\n            return buf.ToString();\n        }\n\n        [return: NotNull]\n        public virtual string GetText(RuleContext ctx)\n        {\n            return GetText(ctx.SourceInterval);\n        }\n\n        [return: NotNull]\n        public virtual string GetText(IToken start, IToken stop)\n        {\n            if (start != null && stop != null)\n            {\n                return GetText(Interval.Of(start.TokenIndex, stop.TokenIndex));\n            }\n            return string.Empty;\n        }\n\n        /// <summary>Get all tokens from lexer until EOF.</summary>\n        /// <remarks>Get all tokens from lexer until EOF.</remarks>\n        public virtual void Fill()\n        {\n            LazyInit();\n            int blockSize = 1000;\n            while (true)\n            {\n                int fetched = Fetch(blockSize);\n                if (fetched < blockSize)\n                {\n                    return;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/CharStreams.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.IO;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>Utility class to create <see cref=\"ICharStream\"/>s from various sources of\n    /// string data.\n    ///\n    /// The methods in this utility class support the full range of\n    /// Unicode code points up to U+10FFFF, unlike <see cref=\"AntlrInputStream\"/>,\n    /// which is limited to 16-bit Unicode code units up to U+FFFF.\n    /// </summary>\n    public static class CharStreams\n    {\n        /// <summary>Creates an <see cref=\"ICharStream\"/> given a path to a UTF-8\n        /// encoded file on disk.\n        ///\n        /// Reads the entire contents of the file into the result before returning.\n        /// </summary>\n        public static ICharStream fromPath(string path)\n        {\n            return fromPath(path, Encoding.UTF8);\n        }\n\n        /// <summary>Creates an <see cref=\"ICharStream\"/> given a path to a\n        /// file on disk and the encoding of the bytes contained in the file.\n        ///\n        /// Reads the entire contents of the file into the result before returning.\n        /// </summary>\n        public static ICharStream fromPath(string path, Encoding encoding)\n        {\n            var pathContents = File.ReadAllText(path, encoding);\n            var result = new CodePointCharStream(pathContents);\n            result.name = path;\n            return result;\n        }\n\n        /// <summary>Creates an <see cref=\"ICharStream\"/> given an opened\n        /// <see cref=\"TextReader\"/>.\n        ///\n        /// Reads the entire contents of the TextReader then closes the reader before returning.\n        /// </summary>\n        public static ICharStream fromTextReader(TextReader textReader)\n        {\n            try {\n                var textReaderContents = textReader.ReadToEnd();\n                return new CodePointCharStream(textReaderContents);\n            } finally {\n                textReader.Dispose();\n            }\n        }\n\n        /// <summary>Creates an <see cref=\"ICharStream\"/> given an opened\n        /// <see cref=\"Stream\"/> from which UTF-8 encoded bytes can be read.\n        ///\n        /// Reads the entire contents of the stream into the result then\n        /// closes the stream before returning.\n        /// </summary>\n        public static ICharStream fromStream(Stream stream)\n        {\n            return fromStream(stream, Encoding.UTF8);\n        }\n\n        /// <summary>Creates an <see cref=\"ICharStream\"/> given an opened\n        /// <see cref=\"Stream\"/> as well as the encoding of the bytes\n        /// to be read from the stream.\n        ///\n        /// Reads the entire contents of the stream into the result then\n        /// closes the stream before returning.\n        /// </summary>\n        public static ICharStream fromStream(Stream stream, Encoding encoding)\n        {\n            using (StreamReader sr = new StreamReader(stream, encoding, false)) {\n                return fromTextReader(sr);\n            }\n        }\n\n        /// <summary>Creates an <see cref=\"ICharStream\"/> given a <see cref=\"string\"/>.\n        /// </summary>\n        public static ICharStream fromString(string s)\n        {\n            return new CodePointCharStream(s);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/CommonToken.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    [System.Serializable]\n    public class CommonToken : IWritableToken\n    {\n        private const long serialVersionUID = -6708843461296520577L;\n\n        /// <summary>\n        /// An empty\n        /// <see cref=\"Tuple{T1, T2}\"/>\n        /// which is used as the default value of\n        /// <see cref=\"source\"/>\n        /// for tokens that do not have a source.\n        /// </summary>\n        protected internal static readonly Tuple<ITokenSource, ICharStream> EmptySource = Tuple.Create<ITokenSource, ICharStream>(null, null);\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"Type\"/> property.\n        /// </summary>\n        private int _type;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"Line\"/> property.\n        /// </summary>\n        private int _line;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"Column\"/> property.\n        /// </summary>\n        protected internal int charPositionInLine = -1;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"Channel\"/> property.\n        /// </summary>\n        private int _channel = TokenConstants.DefaultChannel;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"TokenSource()\"/>\n        /// and\n        /// <see cref=\"InputStream()\"/>\n        /// .\n        /// <p>\n        /// These properties share a field to reduce the memory footprint of\n        /// <see cref=\"CommonToken\"/>\n        /// . Tokens created by a\n        /// <see cref=\"CommonTokenFactory\"/>\n        /// from\n        /// the same source and input stream share a reference to the same\n        /// <see cref=\"Tuple{T1, T2}\"/>\n        /// containing these values.</p>\n        /// </summary>\n        [NotNull]\n        protected internal Tuple<ITokenSource, ICharStream> source;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"Text\"/> property.\n        /// </summary>\n        /// <seealso cref=\"Text\"/>\n        private string _text;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"TokenIndex\"/> property.\n        /// </summary>\n        protected internal int index = -1;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"StartIndex\"/> property.\n        /// </summary>\n        protected internal int start;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"StopIndex\"/> property.\n        /// </summary>\n        protected internal int stop;\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"CommonToken\"/>\n        /// with the specified token type.\n        /// </summary>\n        /// <param name=\"type\">The token type.</param>\n        public CommonToken(int type)\n        {\n            // set to invalid position\n            this._type = type;\n            this.source = EmptySource;\n        }\n\n        public CommonToken(Tuple<ITokenSource, ICharStream> source, int type, int channel, int start, int stop)\n        {\n            this.source = source;\n            this._type = type;\n            this._channel = channel;\n            this.start = start;\n            this.stop = stop;\n            if (source.Item1 != null)\n            {\n                this._line = source.Item1.Line;\n                this.charPositionInLine = source.Item1.Column;\n            }\n        }\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"CommonToken\"/>\n        /// with the specified token type and\n        /// text.\n        /// </summary>\n        /// <param name=\"type\">The token type.</param>\n        /// <param name=\"text\">The text of the token.</param>\n        public CommonToken(int type, string text)\n        {\n            this._type = type;\n            this._channel = TokenConstants.DefaultChannel;\n            this._text = text;\n            this.source = EmptySource;\n        }\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"CommonToken\"/>\n        /// as a copy of another\n        /// <see cref=\"IToken\"/>\n        /// .\n        /// <p>\n        /// If\n        /// <paramref name=\"oldToken\"/>\n        /// is also a\n        /// <see cref=\"CommonToken\"/>\n        /// instance, the newly\n        /// constructed token will share a reference to the\n        /// <see cref=\"Text()\"/>\n        /// field and\n        /// the\n        /// <see cref=\"Tuple{T1, T2}\"/>\n        /// stored in\n        /// <see cref=\"source\"/>\n        /// . Otherwise,\n        /// <see cref=\"Text()\"/>\n        /// will\n        /// be assigned the result of calling\n        /// <see cref=\"Text()\"/>\n        /// , and\n        /// <see cref=\"source\"/>\n        /// will be constructed from the result of\n        /// <see cref=\"IToken.TokenSource()\"/>\n        /// and\n        /// <see cref=\"IToken.InputStream()\"/>\n        /// .</p>\n        /// </summary>\n        /// <param name=\"oldToken\">The token to copy.</param>\n        public CommonToken(IToken oldToken)\n        {\n            _type = oldToken.Type;\n            _line = oldToken.Line;\n            index = oldToken.TokenIndex;\n            charPositionInLine = oldToken.Column;\n            _channel = oldToken.Channel;\n            start = oldToken.StartIndex;\n            stop = oldToken.StopIndex;\n            if (oldToken is Antlr4.Runtime.CommonToken)\n            {\n                _text = ((Antlr4.Runtime.CommonToken)oldToken)._text;\n                source = ((Antlr4.Runtime.CommonToken)oldToken).source;\n            }\n            else\n            {\n                _text = oldToken.Text;\n                source = Tuple.Create(oldToken.TokenSource, oldToken.InputStream);\n            }\n        }\n\n        public virtual int Type\n        {\n            get\n            {\n                return _type;\n            }\n            set\n            {\n \t\t\t\tthis._type = value;\n            }\n        }\n\n        public virtual int Line\n        {\n            get\n            {\n                return _line;\n            }\n            set\n            {\n \t\t\t\tthis._line = value;\n            }\n        }\n\n        /// <summary>Explicitly set the text for this token.</summary>\n        /// <remarks>\n        /// Explicitly set the text for this token. If {code text} is not\n        /// <see langword=\"null\"/>\n        /// , then\n        /// <see cref=\"Text()\"/>\n        /// will return this value rather than\n        /// extracting the text from the input.\n        /// </remarks>\n        /// <value>\n        /// The explicit text of the token, or\n        /// <see langword=\"null\"/>\n        /// if the text\n        /// should be obtained from the input along with the start and stop indexes\n        /// of the token.\n        /// </value>\n        public virtual string Text\n        {\n            get\n            {\n                if (_text != null)\n                {\n                    return _text;\n                }\n                ICharStream input = InputStream;\n                if (input == null)\n                {\n                    return null;\n                }\n                int n = input.Size;\n                if (start < n && stop < n)\n                {\n                    return input.GetText(Interval.Of(start, stop));\n                }\n                else\n                {\n                    return \"<EOF>\";\n                }\n            }\n            set\n            {\n \t\t\t\tthis._text = value;\n            }\n        }\n\n        public virtual int Column\n        {\n            get\n            {\n                return charPositionInLine;\n            }\n            set\n            {\n                int charPositionInLine = value;\n                this.charPositionInLine = charPositionInLine;\n            }\n        }\n\n        public virtual int Channel\n        {\n            get\n            {\n                return _channel;\n            }\n            set\n            {\n                this._channel = value;\n            }\n        }\n\n        public virtual int StartIndex\n        {\n            get\n            {\n                return start;\n            }\n            set\n            {\n                int start = value;\n                this.start = start;\n            }\n        }\n\n        public virtual int StopIndex\n        {\n            get\n            {\n                return stop;\n            }\n            set\n            {\n                int stop = value;\n                this.stop = stop;\n            }\n        }\n\n        public virtual int TokenIndex\n        {\n            get\n            {\n                return index;\n            }\n            set\n            {\n                int index = value;\n                this.index = index;\n            }\n        }\n\n        public virtual ITokenSource TokenSource\n        {\n            get\n            {\n                return source.Item1;\n            }\n        }\n\n        public virtual ICharStream InputStream\n        {\n            get\n            {\n                return source.Item2;\n            }\n        }\n\n        public override string ToString()\n        {\n            string channelStr = string.Empty;\n            if (_channel > 0)\n            {\n                channelStr = \",channel=\" + _channel;\n            }\n            string txt = Text;\n            if (txt != null)\n            {\n                txt = txt.Replace(\"\\n\", \"\\\\n\");\n                txt = txt.Replace(\"\\r\", \"\\\\r\");\n                txt = txt.Replace(\"\\t\", \"\\\\t\");\n            }\n            else\n            {\n                txt = \"<no text>\";\n            }\n            return \"[@\" + TokenIndex + \",\" + start + \":\" + stop + \"='\" + txt + \"',<\" + _type + \">\" + channelStr + \",\" + _line + \":\" + Column + \"]\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/CommonTokenFactory.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This default implementation of\n    /// <see cref=\"ITokenFactory\"/>\n    /// creates\n    /// <see cref=\"CommonToken\"/>\n    /// objects.\n    /// </summary>\n    public class CommonTokenFactory : ITokenFactory\n    {\n        /// <summary>\n        /// The default\n        /// <see cref=\"CommonTokenFactory\"/>\n        /// instance.\n        /// <p>\n        /// This token factory does not explicitly copy token text when constructing\n        /// tokens.</p>\n        /// </summary>\n        public static readonly ITokenFactory Default = new Antlr4.Runtime.CommonTokenFactory();\n\n        /// <summary>\n        /// Indicates whether\n        /// <see cref=\"CommonToken.Text\"/>\n        /// should be called after\n        /// constructing tokens to explicitly set the text. This is useful for cases\n        /// where the input stream might not be able to provide arbitrary substrings\n        /// of text from the input after the lexer creates a token (e.g. the\n        /// implementation of\n        /// <see cref=\"ICharStream.GetText(Antlr4.Runtime.Misc.Interval)\"/>\n        /// in\n        /// <see cref=\"UnbufferedCharStream\"/>\n        /// throws an\n        /// <see cref=\"System.NotSupportedException\"/>\n        /// ). Explicitly setting the token text\n        /// allows\n        /// <see cref=\"IToken.Text()\"/>\n        /// to be called at any time regardless of the\n        /// input stream implementation.\n        /// <p>\n        /// The default value is\n        /// <see langword=\"false\"/>\n        /// to avoid the performance and memory\n        /// overhead of copying text for every token unless explicitly requested.</p>\n        /// </summary>\n        protected internal readonly bool copyText;\n\n        /// <summary>\n        /// Constructs a\n        /// <see cref=\"CommonTokenFactory\"/>\n        /// with the specified value for\n        /// <see cref=\"copyText\"/>\n        /// .\n        /// <p>\n        /// When\n        /// <paramref name=\"copyText\"/>\n        /// is\n        /// <see langword=\"false\"/>\n        /// , the\n        /// <see cref=\"Default\"/>\n        /// instance\n        /// should be used instead of constructing a new instance.</p>\n        /// </summary>\n        /// <param name=\"copyText\">\n        /// The value for\n        /// <see cref=\"copyText\"/>\n        /// .\n        /// </param>\n        public CommonTokenFactory(bool copyText)\n        {\n            this.copyText = copyText;\n        }\n\n        /// <summary>\n        /// Constructs a\n        /// <see cref=\"CommonTokenFactory\"/>\n        /// with\n        /// <see cref=\"copyText\"/>\n        /// set to\n        /// <see langword=\"false\"/>\n        /// .\n        /// <p>\n        /// The\n        /// <see cref=\"Default\"/>\n        /// instance should be used instead of calling this\n        /// directly.</p>\n        /// </summary>\n        public CommonTokenFactory()\n            : this(false)\n        {\n        }\n\n        public virtual CommonToken Create(Tuple<ITokenSource, ICharStream> source, int type, string text, int channel, int start, int stop, int line, int charPositionInLine)\n        {\n            CommonToken t = new CommonToken(source, type, channel, start, stop);\n            t.Line = line;\n            t.Column = charPositionInLine;\n            if (text != null)\n            {\n                t.Text = text;\n            }\n            else\n            {\n                if (copyText && source.Item2 != null)\n                {\n                    t.Text = source.Item2.GetText(Interval.Of(start, stop));\n                }\n            }\n            return t;\n        }\n\n        IToken ITokenFactory.Create(Tuple<ITokenSource, ICharStream> source, int type, string text, int channel, int start, int stop, int line, int charPositionInLine)\n        {\n            return Create(source, type, text, channel, start, stop, line, charPositionInLine);\n        }\n\n        public virtual CommonToken Create(int type, string text)\n        {\n            return new CommonToken(type, text);\n        }\n\n        IToken ITokenFactory.Create(int type, string text)\n        {\n            return Create(type, text);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/CommonTokenStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This class extends\n    /// <see cref=\"BufferedTokenStream\"/>\n    /// with functionality to filter\n    /// token streams to tokens on a particular channel (tokens where\n    /// <see cref=\"IToken.Channel()\"/>\n    /// returns a particular value).\n    /// <p>\n    /// This token stream provides access to all tokens by index or when calling\n    /// methods like\n    /// <see cref=\"BufferedTokenStream.GetText()\"/>\n    /// . The channel filtering is only used for code\n    /// accessing tokens via the lookahead methods\n    /// <see cref=\"BufferedTokenStream.LA(int)\"/>\n    /// ,\n    /// <see cref=\"LT(int)\"/>\n    /// , and\n    /// <see cref=\"Lb(int)\"/>\n    /// .</p>\n    /// <p>\n    /// By default, tokens are placed on the default channel\n    /// (\n    /// <see cref=\"TokenConstants.DefaultChannel\"/>\n    /// ), but may be reassigned by using the\n    /// <c>-&gt;channel(HIDDEN)</c>\n    /// lexer command, or by using an embedded action to\n    /// call\n    /// <see cref=\"Lexer.Channel\"/>\n    /// .\n    /// </p>\n    /// <p>\n    /// Note: lexer rules which use the\n    /// <c>-&gt;skip</c>\n    /// lexer command or call\n    /// <see cref=\"Lexer.Skip()\"/>\n    /// do not produce tokens at all, so input text matched by\n    /// such a rule will not be available as part of the token stream, regardless of\n    /// channel.</p>\n    /// </summary>\n    public class CommonTokenStream : BufferedTokenStream\n    {\n        /// <summary>Specifies the channel to use for filtering tokens.</summary>\n        /// <remarks>\n        /// Specifies the channel to use for filtering tokens.\n        /// <p>\n        /// The default value is\n        /// <see cref=\"TokenConstants.DefaultChannel\"/>\n        /// , which matches the\n        /// default channel assigned to tokens created by the lexer.</p>\n        /// </remarks>\n        protected internal int channel = TokenConstants.DefaultChannel;\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"CommonTokenStream\"/>\n        /// using the specified token\n        /// source and the default token channel (\n        /// <see cref=\"TokenConstants.DefaultChannel\"/>\n        /// ).\n        /// </summary>\n        /// <param name=\"tokenSource\">The token source.</param>\n        public CommonTokenStream(ITokenSource tokenSource)\n            : base(tokenSource)\n        {\n        }\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"CommonTokenStream\"/>\n        /// using the specified token\n        /// source and filtering tokens to the specified channel. Only tokens whose\n        /// <see cref=\"IToken.Channel()\"/>\n        /// matches\n        /// <paramref name=\"channel\"/>\n        /// or have the\n        /// <see cref=\"IToken.Type()\"/>\n        /// equal to\n        /// <see cref=\"TokenConstants.EOF\"/>\n        /// will be returned by the\n        /// token stream lookahead methods.\n        /// </summary>\n        /// <param name=\"tokenSource\">The token source.</param>\n        /// <param name=\"channel\">The channel to use for filtering tokens.</param>\n        public CommonTokenStream(ITokenSource tokenSource, int channel)\n            : this(tokenSource)\n        {\n            this.channel = channel;\n        }\n\n        protected internal override int AdjustSeekIndex(int i)\n        {\n            return NextTokenOnChannel(i, channel);\n        }\n\n        protected internal override IToken Lb(int k)\n        {\n            if (k == 0 || (p - k) < 0)\n            {\n                return null;\n            }\n            int i = p;\n            int n = 1;\n            // find k good tokens looking backwards\n            while (n <= k)\n            {\n                // skip off-channel tokens\n                i = PreviousTokenOnChannel(i - 1, channel);\n                n++;\n            }\n            if (i < 0)\n            {\n                return null;\n            }\n            return tokens[i];\n        }\n\n        public override IToken LT(int k)\n        {\n            //System.out.println(\"enter LT(\"+k+\")\");\n            LazyInit();\n            if (k == 0)\n            {\n                return null;\n            }\n            if (k < 0)\n            {\n                return Lb(-k);\n            }\n            int i = p;\n            int n = 1;\n            // we know tokens[p] is a good one\n            // find k good tokens\n            while (n < k)\n            {\n                // skip off-channel tokens, but make sure to not look past EOF\n                if (Sync(i + 1))\n                {\n                    i = NextTokenOnChannel(i + 1, channel);\n                }\n                n++;\n            }\n            //\t\tif ( i>range ) range = i;\n            return tokens[i];\n        }\n\n        /// <summary>Count EOF just once.</summary>\n        /// <remarks>Count EOF just once.</remarks>\n        public virtual int GetNumberOfOnChannelTokens()\n        {\n            int n = 0;\n            Fill();\n            for (int i = 0; i < tokens.Count; i++)\n            {\n                IToken t = tokens[i];\n                if (t.Channel == channel)\n                {\n                    n++;\n                }\n                if (t.Type == TokenConstants.EOF)\n                {\n                    break;\n                }\n            }\n            return n;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ConsoleErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nusing System.IO;\n\nnamespace Antlr4.Runtime\n{\n    /// <author>Sam Harwell</author>\n    public class ConsoleErrorListener<Symbol> : IAntlrErrorListener<Symbol>\n    {\n        /// <summary>\n        /// Provides a default instance of\n        /// <see cref=\"ConsoleErrorListener{Symbol}\"/>\n        /// .\n        /// </summary>\n        public static readonly ConsoleErrorListener<Symbol> Instance = new ConsoleErrorListener<Symbol>();\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>\n        /// This implementation prints messages to\n        /// <see cref=\"System.Console.Error\"/>\n        /// containing the\n        /// values of\n        /// <paramref name=\"line\"/>\n        /// ,\n        /// <paramref name=\"charPositionInLine\"/>\n        /// , and\n        /// <paramref name=\"msg\"/>\n        /// using\n        /// the following format.</p>\n        /// <pre>\n        /// line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>\n        /// </pre>\n        /// </summary>\n        public virtual void SyntaxError(TextWriter output, IRecognizer recognizer, Symbol offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)\n        {\n            output.WriteLine(\"line \" + line + \":\" + charPositionInLine + \" \" + msg);\n        }\n    }\n}"
  },
  {
    "path": "runtime/CSharp/src/DefaultErrorStrategy.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This is the default implementation of\n    /// <see cref=\"IAntlrErrorStrategy\"/>\n    /// used for\n    /// error reporting and recovery in ANTLR parsers.\n    /// </summary>\n    public class DefaultErrorStrategy : IAntlrErrorStrategy\n    {\n        /// <summary>\n        /// Indicates whether the error strategy is currently \"recovering from an\n        /// error\".\n        /// </summary>\n        /// <remarks>\n        /// Indicates whether the error strategy is currently \"recovering from an\n        /// error\". This is used to suppress reporting multiple error messages while\n        /// attempting to recover from a detected syntax error.\n        /// </remarks>\n        /// <seealso cref=\"InErrorRecoveryMode(Parser)\"/>\n        protected internal bool errorRecoveryMode = false;\n\n        /// <summary>The index into the input stream where the last error occurred.</summary>\n        /// <remarks>\n        /// The index into the input stream where the last error occurred.\n        /// This is used to prevent infinite loops where an error is found\n        /// but no token is consumed during recovery...another error is found,\n        /// ad nauseum.  This is a failsafe mechanism to guarantee that at least\n        /// one token/tree node is consumed for two errors.\n        /// </remarks>\n        protected internal int lastErrorIndex = -1;\n\n        protected internal IntervalSet lastErrorStates;\n\n        /**\n         * This field is used to propagate information about the lookahead following\n         * the previous match. Since prediction prefers completing the current rule\n         * to error recovery efforts, error reporting may occur later than the\n         * original point where it was discoverable. The original context is used to\n         * compute the true expected sets as though the reporting occurred as early\n         * as possible.\n         */\n        protected ParserRuleContext nextTokensContext;\n\n        /**\n         * @see #nextTokensContext\n         */\n        protected int nextTokensState;\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation simply calls\n        /// <see cref=\"EndErrorCondition(Parser)\"/>\n        /// to\n        /// ensure that the handler is not in error recovery mode.</p>\n        /// </summary>\n        public virtual void Reset(Parser recognizer)\n        {\n            EndErrorCondition(recognizer);\n        }\n\n        /// <summary>\n        /// This method is called to enter error recovery mode when a recognition\n        /// exception is reported.\n        /// </summary>\n        /// <remarks>\n        /// This method is called to enter error recovery mode when a recognition\n        /// exception is reported.\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        protected internal virtual void BeginErrorCondition(Parser recognizer)\n        {\n            errorRecoveryMode = true;\n        }\n\n        /// <summary><inheritDoc/></summary>\n        public virtual bool InErrorRecoveryMode(Parser recognizer)\n        {\n            return errorRecoveryMode;\n        }\n\n        /// <summary>\n        /// This method is called to leave error recovery mode after recovering from\n        /// a recognition exception.\n        /// </summary>\n        /// <remarks>\n        /// This method is called to leave error recovery mode after recovering from\n        /// a recognition exception.\n        /// </remarks>\n        /// <param name=\"recognizer\"/>\n        protected internal virtual void EndErrorCondition(Parser recognizer)\n        {\n            errorRecoveryMode = false;\n            lastErrorStates = null;\n            lastErrorIndex = -1;\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation simply calls\n        /// <see cref=\"EndErrorCondition(Parser)\"/>\n        /// .</p>\n        /// </summary>\n        public virtual void ReportMatch(Parser recognizer)\n        {\n            EndErrorCondition(recognizer);\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation returns immediately if the handler is already\n        /// in error recovery mode. Otherwise, it calls\n        /// <see cref=\"BeginErrorCondition(Parser)\"/>\n        /// and dispatches the reporting task based on the runtime type of\n        /// <paramref name=\"e\"/>\n        /// according to the following table.</p>\n        /// <ul>\n        /// <li>\n        /// <see cref=\"NoViableAltException\"/>\n        /// : Dispatches the call to\n        /// <see cref=\"ReportNoViableAlternative(Parser, NoViableAltException)\"/>\n        /// </li>\n        /// <li>\n        /// <see cref=\"InputMismatchException\"/>\n        /// : Dispatches the call to\n        /// <see cref=\"ReportInputMismatch(Parser, InputMismatchException)\"/>\n        /// </li>\n        /// <li>\n        /// <see cref=\"FailedPredicateException\"/>\n        /// : Dispatches the call to\n        /// <see cref=\"ReportFailedPredicate(Parser, FailedPredicateException)\"/>\n        /// </li>\n        /// <li>All other types: calls\n        /// <see cref=\"Parser.NotifyErrorListeners(string)\"/>\n        /// to report\n        /// the exception</li>\n        /// </ul>\n        /// </summary>\n        public virtual void ReportError(Parser recognizer, RecognitionException e)\n        {\n            // if we've already reported an error and have not matched a token\n            // yet successfully, don't report any errors.\n            if (InErrorRecoveryMode(recognizer))\n            {\n                //\t\t\tSystem.err.print(\"[SPURIOUS] \");\n                return;\n            }\n            // don't report spurious errors\n            BeginErrorCondition(recognizer);\n            if (e is NoViableAltException)\n            {\n                ReportNoViableAlternative(recognizer, (NoViableAltException)e);\n            }\n            else\n            {\n                if (e is InputMismatchException)\n                {\n                    ReportInputMismatch(recognizer, (InputMismatchException)e);\n                }\n                else\n                {\n                    if (e is FailedPredicateException)\n                    {\n                        ReportFailedPredicate(recognizer, (FailedPredicateException)e);\n                    }\n                    else\n                    {\n                        System.Console.Error.WriteLine(\"unknown recognition error type: \" + e.GetType().FullName);\n                        NotifyErrorListeners(recognizer, e.Message, e);\n                    }\n                }\n            }\n        }\n\n        protected internal virtual void NotifyErrorListeners(Parser recognizer, string message, RecognitionException e)\n        {\n            recognizer.NotifyErrorListeners(e.OffendingToken, message, e);\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation resynchronizes the parser by consuming tokens\n        /// until we find one in the resynchronization set--loosely the set of tokens\n        /// that can follow the current rule.</p>\n        /// </summary>\n        public virtual void Recover(Parser recognizer, RecognitionException e)\n        {\n            //\t\tSystem.out.println(\"recover in \"+recognizer.getRuleInvocationStack()+\n            //\t\t\t\t\t\t   \" index=\"+recognizer.getInputStream().index()+\n            //\t\t\t\t\t\t   \", lastErrorIndex=\"+\n            //\t\t\t\t\t\t   lastErrorIndex+\n            //\t\t\t\t\t\t   \", states=\"+lastErrorStates);\n            if (lastErrorIndex == ((ITokenStream)recognizer.InputStream).Index && lastErrorStates != null && lastErrorStates.Contains(recognizer.State))\n            {\n                // uh oh, another error at same token index and previously-visited\n                // state in ATN; must be a case where LT(1) is in the recovery\n                // token set so nothing got consumed. Consume a single token\n                // at least to prevent an infinite loop; this is a failsafe.\n                //\t\t\tSystem.err.println(\"seen error condition before index=\"+\n                //\t\t\t\t\t\t\t   lastErrorIndex+\", states=\"+lastErrorStates);\n                //\t\t\tSystem.err.println(\"FAILSAFE consumes \"+recognizer.getTokenNames()[recognizer.getInputStream().LA(1)]);\n                recognizer.Consume();\n            }\n            lastErrorIndex = ((ITokenStream)recognizer.InputStream).Index;\n            if (lastErrorStates == null)\n            {\n                lastErrorStates = new IntervalSet();\n            }\n            lastErrorStates.Add(recognizer.State);\n            IntervalSet followSet = GetErrorRecoverySet(recognizer);\n            ConsumeUntil(recognizer, followSet);\n        }\n\n        /// <summary>\n        /// The default implementation of\n        /// <see cref=\"IAntlrErrorStrategy.Sync(Parser)\"/>\n        /// makes sure\n        /// that the current lookahead symbol is consistent with what were expecting\n        /// at this point in the ATN. You can call this anytime but ANTLR only\n        /// generates code to check before subrules/loops and each iteration.\n        /// <p>Implements Jim Idle's magic sync mechanism in closures and optional\n        /// subrules. E.g.,</p>\n        /// <pre>\n        /// a : sync ( stuff sync )* ;\n        /// sync : {consume to what can follow sync} ;\n        /// </pre>\n        /// At the start of a sub rule upon error,\n        /// <see cref=\"Sync(Parser)\"/>\n        /// performs single\n        /// token deletion, if possible. If it can't do that, it bails on the current\n        /// rule and uses the default error recovery, which consumes until the\n        /// resynchronization set of the current rule.\n        /// <p>If the sub rule is optional (\n        /// <c>(...)?</c>\n        /// ,\n        /// <c>(...)*</c>\n        /// , or block\n        /// with an empty alternative), then the expected set includes what follows\n        /// the subrule.</p>\n        /// <p>During loop iteration, it consumes until it sees a token that can start a\n        /// sub rule or what follows loop. Yes, that is pretty aggressive. We opt to\n        /// stay in the loop as long as possible.</p>\n        /// <p><strong>ORIGINS</strong></p>\n        /// <p>Previous versions of ANTLR did a poor job of their recovery within loops.\n        /// A single mismatch token or missing token would force the parser to bail\n        /// out of the entire rules surrounding the loop. So, for rule</p>\n        /// <pre>\n        /// classDef : 'class' ID '{' member* '}'\n        /// </pre>\n        /// input with an extra token between members would force the parser to\n        /// consume until it found the next class definition rather than the next\n        /// member definition of the current class.\n        /// <p>This functionality cost a little bit of effort because the parser has to\n        /// compare token set at the start of the loop and at each iteration. If for\n        /// some reason speed is suffering for you, you can turn off this\n        /// functionality by simply overriding this method as a blank { }.</p>\n        /// </summary>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        public virtual void Sync(Parser recognizer)\n        {\n            ATNState s = recognizer.Interpreter.atn.states[recognizer.State];\n            //\t\tSystem.err.println(\"sync @ \"+s.stateNumber+\"=\"+s.getClass().getSimpleName());\n            // If already recovering, don't try to sync\n            if (InErrorRecoveryMode(recognizer))\n            {\n                return;\n            }\n            ITokenStream tokens = ((ITokenStream)recognizer.InputStream);\n            int la = tokens.LA(1);\n            // try cheaper subset first; might get lucky. seems to shave a wee bit off\n            var nextTokens = recognizer.Atn.NextTokens(s);\n            if (nextTokens.Contains(la))\n            {\n                nextTokensContext = null;\n                nextTokensState = ATNState.InvalidStateNumber;\n                return;\n            }\n\n            if (nextTokens.Contains(TokenConstants.EPSILON))\n            {\n                if (nextTokensContext == null)\n                {\n                    // It's possible the next token won't match; information tracked\n                    // by sync is restricted for performance.\n                    nextTokensContext = recognizer.Context;\n                    nextTokensState = recognizer.State;\n                }\n                return;\n            }\n            switch (s.StateType)\n            {\n                case StateType.BlockStart:\n                case StateType.StarBlockStart:\n                case StateType.PlusBlockStart:\n                case StateType.StarLoopEntry:\n                {\n                    // report error and recover if possible\n                    if (SingleTokenDeletion(recognizer) != null)\n                    {\n                        return;\n                    }\n                    throw new InputMismatchException(recognizer);\n                }\n\n                case StateType.PlusLoopBack:\n                case StateType.StarLoopBack:\n                {\n                    //\t\t\tSystem.err.println(\"at loop back: \"+s.getClass().getSimpleName());\n                    ReportUnwantedToken(recognizer);\n                    IntervalSet expecting = recognizer.GetExpectedTokens();\n                    IntervalSet whatFollowsLoopIterationOrRule = expecting.Or(GetErrorRecoverySet(recognizer));\n                    ConsumeUntil(recognizer, whatFollowsLoopIterationOrRule);\n                    break;\n                }\n\n                default:\n                {\n                    // do nothing if we can't identify the exact kind of ATN state\n                    break;\n                }\n            }\n        }\n\n        /// <summary>\n        /// This is called by\n        /// <see cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// when the exception is a\n        /// <see cref=\"NoViableAltException\"/>\n        /// .\n        /// </summary>\n        /// <seealso cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"e\">the recognition exception</param>\n        protected internal virtual void ReportNoViableAlternative(Parser recognizer, NoViableAltException e)\n        {\n            ITokenStream tokens = ((ITokenStream)recognizer.InputStream);\n            string input;\n            if (tokens != null)\n            {\n                if (e.StartToken.Type == TokenConstants.EOF)\n                {\n                    input = \"<EOF>\";\n                }\n                else\n                {\n                    input = tokens.GetText(e.StartToken, e.OffendingToken);\n                }\n            }\n            else\n            {\n                input = \"<unknown input>\";\n            }\n            string msg = \"no viable alternative at input \" + EscapeWSAndQuote(input);\n            NotifyErrorListeners(recognizer, msg, e);\n        }\n\n        /// <summary>\n        /// This is called by\n        /// <see cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// when the exception is an\n        /// <see cref=\"InputMismatchException\"/>\n        /// .\n        /// </summary>\n        /// <seealso cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"e\">the recognition exception</param>\n        protected internal virtual void ReportInputMismatch(Parser recognizer, InputMismatchException e)\n        {\n            string msg = \"mismatched input \" + GetTokenErrorDisplay(e.OffendingToken) + \" expecting \" + e.GetExpectedTokens().ToString(recognizer.Vocabulary);\n            NotifyErrorListeners(recognizer, msg, e);\n        }\n\n        /// <summary>\n        /// This is called by\n        /// <see cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// when the exception is a\n        /// <see cref=\"FailedPredicateException\"/>\n        /// .\n        /// </summary>\n        /// <seealso cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"e\">the recognition exception</param>\n        protected internal virtual void ReportFailedPredicate(Parser recognizer, FailedPredicateException e)\n        {\n\t\t\tstring ruleName = recognizer.RuleNames[recognizer.RuleContext.RuleIndex];\n            string msg = \"rule \" + ruleName + \" \" + e.Message;\n            NotifyErrorListeners(recognizer, msg, e);\n        }\n\n        /// <summary>\n        /// This method is called to report a syntax error which requires the removal\n        /// of a token from the input stream.\n        /// </summary>\n        /// <remarks>\n        /// This method is called to report a syntax error which requires the removal\n        /// of a token from the input stream. At the time this method is called, the\n        /// erroneous symbol is current\n        /// <c>LT(1)</c>\n        /// symbol and has not yet been\n        /// removed from the input stream. When this method returns,\n        /// <paramref name=\"recognizer\"/>\n        /// is in error recovery mode.\n        /// <p>This method is called when\n        /// <see cref=\"SingleTokenDeletion(Parser)\"/>\n        /// identifies\n        /// single-token deletion as a viable recovery strategy for a mismatched\n        /// input error.</p>\n        /// <p>The default implementation simply returns if the handler is already in\n        /// error recovery mode. Otherwise, it calls\n        /// <see cref=\"BeginErrorCondition(Parser)\"/>\n        /// to\n        /// enter error recovery mode, followed by calling\n        /// <see cref=\"Parser.NotifyErrorListeners(string)\"/>\n        /// .</p>\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        protected internal virtual void ReportUnwantedToken(Parser recognizer)\n        {\n            if (InErrorRecoveryMode(recognizer))\n            {\n                return;\n            }\n            BeginErrorCondition(recognizer);\n            IToken t = recognizer.CurrentToken;\n            string tokenName = GetTokenErrorDisplay(t);\n            IntervalSet expecting = GetExpectedTokens(recognizer);\n            string msg = \"extraneous input \" + tokenName + \" expecting \" + expecting.ToString(recognizer.Vocabulary);\n            recognizer.NotifyErrorListeners(t, msg, null);\n        }\n\n        /// <summary>\n        /// This method is called to report a syntax error which requires the\n        /// insertion of a missing token into the input stream.\n        /// </summary>\n        /// <remarks>\n        /// This method is called to report a syntax error which requires the\n        /// insertion of a missing token into the input stream. At the time this\n        /// method is called, the missing token has not yet been inserted. When this\n        /// method returns,\n        /// <paramref name=\"recognizer\"/>\n        /// is in error recovery mode.\n        /// <p>This method is called when\n        /// <see cref=\"SingleTokenInsertion(Parser)\"/>\n        /// identifies\n        /// single-token insertion as a viable recovery strategy for a mismatched\n        /// input error.</p>\n        /// <p>The default implementation simply returns if the handler is already in\n        /// error recovery mode. Otherwise, it calls\n        /// <see cref=\"BeginErrorCondition(Parser)\"/>\n        /// to\n        /// enter error recovery mode, followed by calling\n        /// <see cref=\"Parser.NotifyErrorListeners(string)\"/>\n        /// .</p>\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        protected internal virtual void ReportMissingToken(Parser recognizer)\n        {\n            if (InErrorRecoveryMode(recognizer))\n            {\n                return;\n            }\n            BeginErrorCondition(recognizer);\n            IToken t = recognizer.CurrentToken;\n            IntervalSet expecting = GetExpectedTokens(recognizer);\n            string msg = \"missing \" + expecting.ToString(recognizer.Vocabulary) + \" at \" + GetTokenErrorDisplay(t);\n            recognizer.NotifyErrorListeners(t, msg, null);\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation attempts to recover from the mismatched input\n        /// by using single token insertion and deletion as described below. If the\n        /// recovery attempt fails, this method throws an\n        /// <see cref=\"InputMismatchException\"/>\n        /// .</p>\n        /// <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>\n        /// <p>\n        /// <c>LA(1)</c>\n        /// is not what we are looking for. If\n        /// <c>LA(2)</c>\n        /// has the\n        /// right token, however, then assume\n        /// <c>LA(1)</c>\n        /// is some extra spurious\n        /// token and delete it. Then consume and return the next token (which was\n        /// the\n        /// <c>LA(2)</c>\n        /// token) as the successful result of the match operation.</p>\n        /// <p>This recovery strategy is implemented by\n        /// <see cref=\"SingleTokenDeletion(Parser)\"/>\n        /// .</p>\n        /// <p><strong>MISSING TOKEN</strong> (single token insertion)</p>\n        /// <p>If current token (at\n        /// <c>LA(1)</c>\n        /// ) is consistent with what could come\n        /// after the expected\n        /// <c>LA(1)</c>\n        /// token, then assume the token is missing\n        /// and use the parser's\n        /// <see cref=\"ITokenFactory\"/>\n        /// to create it on the fly. The\n        /// \"insertion\" is performed by returning the created token as the successful\n        /// result of the match operation.</p>\n        /// <p>This recovery strategy is implemented by\n        /// <see cref=\"SingleTokenInsertion(Parser)\"/>\n        /// .</p>\n        /// <p><strong>EXAMPLE</strong></p>\n        /// <p>For example, Input\n        /// <c>i=(3;</c>\n        /// is clearly missing the\n        /// <c>')'</c>\n        /// . When\n        /// the parser returns from the nested call to\n        /// <c>expr</c>\n        /// , it will have\n        /// call chain:</p>\n        /// <pre>\n        /// stat &#x2192; expr &#x2192; atom\n        /// </pre>\n        /// and it will be trying to match the\n        /// <c>')'</c>\n        /// at this point in the\n        /// derivation:\n        /// <pre>\n        /// =&gt; ID '=' '(' INT ')' ('+' atom)* ';'\n        /// ^\n        /// </pre>\n        /// The attempt to match\n        /// <c>')'</c>\n        /// will fail when it sees\n        /// <c>';'</c>\n        /// and\n        /// call\n        /// <see cref=\"RecoverInline(Parser)\"/>\n        /// . To recover, it sees that\n        /// <c>LA(1)==';'</c>\n        /// is in the set of tokens that can follow the\n        /// <c>')'</c>\n        /// token reference\n        /// in rule\n        /// <c>atom</c>\n        /// . It can assume that you forgot the\n        /// <c>')'</c>\n        /// .\n        /// </summary>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        public virtual IToken RecoverInline(Parser recognizer)\n        {\n            // SINGLE TOKEN DELETION\n            IToken matchedSymbol = SingleTokenDeletion(recognizer);\n            if (matchedSymbol != null)\n            {\n                // we have deleted the extra token.\n                // now, move past ttype token as if all were ok\n                recognizer.Consume();\n                return matchedSymbol;\n            }\n            // SINGLE TOKEN INSERTION\n            if (SingleTokenInsertion(recognizer))\n            {\n                return GetMissingSymbol(recognizer);\n            }\n            // even that didn't work; must throw the exception\n            throw new InputMismatchException(recognizer);\n        }\n\n        /// <summary>\n        /// This method implements the single-token insertion inline error recovery\n        /// strategy.\n        /// </summary>\n        /// <remarks>\n        /// This method implements the single-token insertion inline error recovery\n        /// strategy. It is called by\n        /// <see cref=\"RecoverInline(Parser)\"/>\n        /// if the single-token\n        /// deletion strategy fails to recover from the mismatched input. If this\n        /// method returns\n        /// <see langword=\"true\"/>\n        /// ,\n        /// <paramref name=\"recognizer\"/>\n        /// will be in error recovery\n        /// mode.\n        /// <p>This method determines whether or not single-token insertion is viable by\n        /// checking if the\n        /// <c>LA(1)</c>\n        /// input symbol could be successfully matched\n        /// if it were instead the\n        /// <c>LA(2)</c>\n        /// symbol. If this method returns\n        /// <see langword=\"true\"/>\n        /// , the caller is responsible for creating and inserting a\n        /// token with the correct type to produce this behavior.</p>\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if single-token insertion is a viable recovery\n        /// strategy for the current mismatched input, otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        protected internal virtual bool SingleTokenInsertion(Parser recognizer)\n        {\n            int currentSymbolType = ((ITokenStream)recognizer.InputStream).LA(1);\n            // if current token is consistent with what could come after current\n            // ATN state, then we know we're missing a token; error recovery\n            // is free to conjure up and insert the missing token\n            ATNState currentState = recognizer.Interpreter.atn.states[recognizer.State];\n            ATNState next = currentState.Transition(0).target;\n            ATN atn = recognizer.Interpreter.atn;\n\t\t\tIntervalSet expectingAtLL2 = atn.NextTokens(next, recognizer.RuleContext);\n            if (expectingAtLL2.Contains(currentSymbolType))\n            {\n                ReportMissingToken(recognizer);\n                return true;\n            }\n            return false;\n        }\n\n        /// <summary>\n        /// This method implements the single-token deletion inline error recovery\n        /// strategy.\n        /// </summary>\n        /// <remarks>\n        /// This method implements the single-token deletion inline error recovery\n        /// strategy. It is called by\n        /// <see cref=\"RecoverInline(Parser)\"/>\n        /// to attempt to recover\n        /// from mismatched input. If this method returns null, the parser and error\n        /// handler state will not have changed. If this method returns non-null,\n        /// <paramref name=\"recognizer\"/>\n        /// will <em>not</em> be in error recovery mode since the\n        /// returned token was a successful match.\n        /// <p>If the single-token deletion is successful, this method calls\n        /// <see cref=\"ReportUnwantedToken(Parser)\"/>\n        /// to report the error, followed by\n        /// <see cref=\"Parser.Consume()\"/>\n        /// to actually \"delete\" the extraneous token. Then,\n        /// before returning\n        /// <see cref=\"ReportMatch(Parser)\"/>\n        /// is called to signal a successful\n        /// match.</p>\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <returns>\n        /// the successfully matched\n        /// <see cref=\"IToken\"/>\n        /// instance if single-token\n        /// deletion successfully recovers from the mismatched input, otherwise\n        /// <see langword=\"null\"/>\n        /// </returns>\n        [return: Nullable]\n        protected internal virtual IToken SingleTokenDeletion(Parser recognizer)\n        {\n            int nextTokenType = ((ITokenStream)recognizer.InputStream).LA(2);\n            IntervalSet expecting = GetExpectedTokens(recognizer);\n            if (expecting.Contains(nextTokenType))\n            {\n                ReportUnwantedToken(recognizer);\n                recognizer.Consume();\n                // simply delete extra token\n                // we want to return the token we're actually matching\n                IToken matchedSymbol = recognizer.CurrentToken;\n                ReportMatch(recognizer);\n                // we know current token is correct\n                return matchedSymbol;\n            }\n            return null;\n        }\n\n        /// <summary>Conjure up a missing token during error recovery.</summary>\n        /// <remarks>\n        /// Conjure up a missing token during error recovery.\n        /// The recognizer attempts to recover from single missing\n        /// symbols. But, actions might refer to that missing symbol.\n        /// For example, x=ID {f($x);}. The action clearly assumes\n        /// that there has been an identifier matched previously and that\n        /// $x points at that token. If that token is missing, but\n        /// the next token in the stream is what we want we assume that\n        /// this token is missing and we keep going. Because we\n        /// have to return some token to replace the missing token,\n        /// we have to conjure one up. This method gives the user control\n        /// over the tokens returned for missing tokens. Mostly,\n        /// you will want to create something special for identifier\n        /// tokens. For literals such as '{' and ',', the default\n        /// action in the parser or tree parser works. It simply creates\n        /// a CommonToken of the appropriate type. The text will be the token.\n        /// If you change what tokens must be created by the lexer,\n        /// override this method to create the appropriate tokens.\n        /// </remarks>\n        [return: NotNull]\n        protected internal virtual IToken GetMissingSymbol(Parser recognizer)\n        {\n            IToken currentSymbol = recognizer.CurrentToken;\n            IntervalSet expecting = GetExpectedTokens(recognizer);\n            int expectedTokenType = expecting.MinElement;\n            // get any element\n            string tokenText;\n            if (expectedTokenType == TokenConstants.EOF)\n            {\n                tokenText = \"<missing EOF>\";\n            }\n            else\n            {\n                tokenText = \"<missing \" + recognizer.Vocabulary.GetDisplayName(expectedTokenType) + \">\";\n            }\n            IToken current = currentSymbol;\n            IToken lookback = ((ITokenStream)recognizer.InputStream).LT(-1);\n            if (current.Type == TokenConstants.EOF && lookback != null)\n            {\n                current = lookback;\n            }\n            return ConstructToken(((ITokenStream)recognizer.InputStream).TokenSource, expectedTokenType, tokenText, current);\n        }\n\n        protected internal virtual IToken ConstructToken(ITokenSource tokenSource, int expectedTokenType, string tokenText, IToken current)\n        {\n            ITokenFactory factory = tokenSource.TokenFactory;\n            return factory.Create(Tuple.Create(tokenSource, current.TokenSource.InputStream), expectedTokenType, tokenText, TokenConstants.DefaultChannel, -1, -1, current.Line, current.Column);\n        }\n\n        [return: NotNull]\n        protected internal virtual IntervalSet GetExpectedTokens(Parser recognizer)\n        {\n            return recognizer.GetExpectedTokens();\n        }\n\n        /// <summary>\n        /// How should a token be displayed in an error message? The default\n        /// is to display just the text, but during development you might\n        /// want to have a lot of information spit out.\n        /// </summary>\n        /// <remarks>\n        /// How should a token be displayed in an error message? The default\n        /// is to display just the text, but during development you might\n        /// want to have a lot of information spit out.  Override in that case\n        /// to use t.toString() (which, for CommonToken, dumps everything about\n        /// the token). This is better than forcing you to override a method in\n        /// your token objects because you don't have to go modify your lexer\n        /// so that it creates a new Java type.\n        /// </remarks>\n        protected internal virtual string GetTokenErrorDisplay(IToken t)\n        {\n            if (t == null)\n            {\n                return \"<no token>\";\n            }\n            string s = GetSymbolText(t);\n            if (s == null)\n            {\n                if (GetSymbolType(t) == TokenConstants.EOF)\n                {\n                    s = \"<EOF>\";\n                }\n                else\n                {\n                    s = \"<\" + GetSymbolType(t) + \">\";\n                }\n            }\n            return EscapeWSAndQuote(s);\n        }\n\n        protected internal virtual string GetSymbolText(IToken symbol)\n        {\n            return symbol.Text;\n        }\n\n        protected internal virtual int GetSymbolType(IToken symbol)\n        {\n            return symbol.Type;\n        }\n\n        [return: NotNull]\n        protected internal virtual string EscapeWSAndQuote(string s)\n        {\n            //\t\tif ( s==null ) return s;\n            s = s.Replace(\"\\n\", \"\\\\n\");\n            s = s.Replace(\"\\r\", \"\\\\r\");\n            s = s.Replace(\"\\t\", \"\\\\t\");\n            return \"'\" + s + \"'\";\n        }\n\n        [return: NotNull]\n        protected internal virtual IntervalSet GetErrorRecoverySet(Parser recognizer)\n        {\n            ATN atn = recognizer.Interpreter.atn;\n\t\t\tRuleContext ctx = recognizer.RuleContext;\n            IntervalSet recoverSet = new IntervalSet();\n            while (ctx != null && ctx.invokingState >= 0)\n            {\n                // compute what follows who invoked us\n                ATNState invokingState = atn.states[ctx.invokingState];\n                RuleTransition rt = (RuleTransition)invokingState.Transition(0);\n                IntervalSet follow = atn.NextTokens(rt.followState);\n                recoverSet.AddAll(follow);\n                ctx = ctx.Parent;\n            }\n            recoverSet.Remove(TokenConstants.EPSILON);\n            //\t\tSystem.out.println(\"recover set \"+recoverSet.toString(recognizer.getTokenNames()));\n            return recoverSet;\n        }\n\n        /// <summary>Consume tokens until one matches the given token set.</summary>\n        /// <remarks>Consume tokens until one matches the given token set.</remarks>\n        protected internal virtual void ConsumeUntil(Parser recognizer, IntervalSet set)\n        {\n            //\t\tSystem.err.println(\"consumeUntil(\"+set.toString(recognizer.getTokenNames())+\")\");\n            int ttype = ((ITokenStream)recognizer.InputStream).LA(1);\n            while (ttype != TokenConstants.EOF && !set.Contains(ttype))\n            {\n                //System.out.println(\"consume during recover LA(1)=\"+getTokenNames()[input.LA(1)]);\n                //\t\t\trecognizer.getInputStream().consume();\n                recognizer.Consume();\n                ttype = ((ITokenStream)recognizer.InputStream).LA(1);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dependents.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <author>Sam Harwell</author>\n    [Flags]\n    public enum Dependents\n    {\n        None = 0,\n        Self = 1 << 0,\n        Parents = 1 << 1,\n        Children = 1 << 2,\n        Ancestors = 1 << 3,\n        Descendants = 1 << 4,\n        Siblings = 1 << 5,\n        PreceedingSiblings = 1 << 6,\n        FollowingSiblings = 1 << 7,\n        Preceeding = 1 << 8,\n        Following = 1 << 9\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/AbstractEdgeMap.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <author>Sam Harwell</author>\n    public abstract class AbstractEdgeMap<T> : IEdgeMap<T>\n        where T : class\n    {\n        protected internal readonly int minIndex;\n\n        protected internal readonly int maxIndex;\n\n        protected AbstractEdgeMap(int minIndex, int maxIndex)\n        {\n            // the allowed range (with minIndex and maxIndex inclusive) should be less than 2^32\n            System.Diagnostics.Debug.Assert(maxIndex - minIndex + 1 >= 0);\n            this.minIndex = minIndex;\n            this.maxIndex = maxIndex;\n        }\n\n        public abstract Antlr4.Runtime.Dfa.AbstractEdgeMap<T> Put(int key, T value);\n\n        IEdgeMap<T> IEdgeMap<T>.Put(int key, T value)\n        {\n            return Put(key, value);\n        }\n\n        public virtual Antlr4.Runtime.Dfa.AbstractEdgeMap<T> PutAll(IEdgeMap<T> m)\n        {\n            Antlr4.Runtime.Dfa.AbstractEdgeMap<T> result = this;\n            foreach (KeyValuePair<int, T> entry in m)\n            {\n                result = result.Put(entry.Key, entry.Value);\n            }\n            return result;\n        }\n\n        IEdgeMap<T> IEdgeMap<T>.PutAll(IEdgeMap<T> m)\n        {\n            return PutAll(m);\n        }\n\n        public abstract Antlr4.Runtime.Dfa.AbstractEdgeMap<T> Clear();\n\n        IEdgeMap<T> IEdgeMap<T>.Clear()\n        {\n            return Clear();\n        }\n\n        public abstract Antlr4.Runtime.Dfa.AbstractEdgeMap<T> Remove(int key);\n\n        IEdgeMap<T> IEdgeMap<T>.Remove(int key)\n        {\n            return Remove(key);\n        }\n\n        public abstract bool ContainsKey(int arg1);\n\n        public abstract T this[int arg1]\n        {\n            get;\n        }\n\n        public abstract bool IsEmpty\n        {\n            get;\n        }\n\n        public abstract int Count\n        {\n            get;\n        }\n\n        public abstract IReadOnlyDictionary<int, T> ToMap();\n\n        public virtual IEnumerator<KeyValuePair<int, T>> GetEnumerator()\n        {\n            return ToMap().GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/AcceptStateInfo.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <summary>\n    /// Stores information about a\n    /// <see cref=\"DFAState\"/>\n    /// which is an accept state under\n    /// some condition. Certain settings, such as\n    /// <see cref=\"Antlr4.Runtime.Atn.ParserATNSimulator.PredictionMode()\"/>\n    /// , may be used in addition to\n    /// this information to determine whether or not a particular state is an accept\n    /// state.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    public class AcceptStateInfo\n    {\n        private readonly int prediction;\n\n        private readonly Antlr4.Runtime.Atn.LexerActionExecutor lexerActionExecutor;\n\n        public AcceptStateInfo(int prediction)\n        {\n            this.prediction = prediction;\n            this.lexerActionExecutor = null;\n        }\n\n        public AcceptStateInfo(int prediction, Antlr4.Runtime.Atn.LexerActionExecutor lexerActionExecutor)\n        {\n            this.prediction = prediction;\n            this.lexerActionExecutor = lexerActionExecutor;\n        }\n\n        /// <summary>Gets the prediction made by this accept state.</summary>\n        /// <remarks>\n        /// Gets the prediction made by this accept state. Note that this value\n        /// assumes the predicates, if any, in the\n        /// <see cref=\"DFAState\"/>\n        /// evaluate to\n        /// <see langword=\"true\"/>\n        /// . If predicate evaluation is enabled, the final prediction of\n        /// the accept state will be determined by the result of predicate\n        /// evaluation.\n        /// </remarks>\n        public virtual int Prediction\n        {\n            get\n            {\n                return prediction;\n            }\n        }\n\n        /// <summary>\n        /// Gets the\n        /// <see cref=\"Antlr4.Runtime.Atn.LexerActionExecutor\"/>\n        /// which can be used to execute actions\n        /// and/or commands after the lexer matches a token.\n        /// </summary>\n        public virtual Antlr4.Runtime.Atn.LexerActionExecutor LexerActionExecutor\n        {\n            get\n            {\n                return lexerActionExecutor;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/ArrayEdgeMap.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing Interlocked = System.Threading.Interlocked;\n\nusing Volatile = System.Threading.Volatile;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <author>Sam Harwell</author>\n    public sealed class ArrayEdgeMap<T> : AbstractEdgeMap<T>\n        where T : class\n    {\n        private readonly T[] arrayData;\n\n        private int size;\n\n        public ArrayEdgeMap(int minIndex, int maxIndex)\n            : base(minIndex, maxIndex)\n        {\n            arrayData = new T[maxIndex - minIndex + 1];\n        }\n\n        public override int Count\n        {\n            get\n            {\n                return Volatile.Read(ref size);\n            }\n        }\n\n        public override bool IsEmpty\n        {\n            get\n            {\n                return Count == 0;\n            }\n        }\n\n        public override bool ContainsKey(int key)\n        {\n            return this[key] != null;\n        }\n\n        public override T this[int key]\n        {\n            get\n            {\n                if (key < minIndex || key > maxIndex)\n                {\n                    return null;\n                }\n\n                return Volatile.Read(ref arrayData[key - minIndex]);\n            }\n        }\n\n        public override AbstractEdgeMap<T> Put(int key, T value)\n        {\n            if (key >= minIndex && key <= maxIndex)\n            {\n                T existing = Interlocked.Exchange(ref arrayData[key - minIndex], value);\n                if (existing == null && value != null)\n                {\n                    Interlocked.Increment(ref size);\n                }\n                else\n                {\n                    if (existing != null && value == null)\n                    {\n                        Interlocked.Decrement(ref size);\n                    }\n                }\n            }\n            return this;\n        }\n\n        public override AbstractEdgeMap<T> Remove(int key)\n        {\n            return Put(key, null);\n        }\n\n        public override AbstractEdgeMap<T> PutAll(IEdgeMap<T> m)\n        {\n            if (m.IsEmpty)\n            {\n                return this;\n            }\n            if (m is Antlr4.Runtime.Dfa.ArrayEdgeMap<T>)\n            {\n                Antlr4.Runtime.Dfa.ArrayEdgeMap<T> other = (Antlr4.Runtime.Dfa.ArrayEdgeMap<T>)m;\n                int minOverlap = Math.Max(minIndex, other.minIndex);\n                int maxOverlap = Math.Min(maxIndex, other.maxIndex);\n                Antlr4.Runtime.Dfa.ArrayEdgeMap<T> result = this;\n                for (int i = minOverlap; i <= maxOverlap; i++)\n                {\n                    result = ((Antlr4.Runtime.Dfa.ArrayEdgeMap<T>)result.Put(i, m[i]));\n                }\n                return result;\n            }\n            else\n            {\n                if (m is SingletonEdgeMap<T>)\n                {\n                    SingletonEdgeMap<T> other = (SingletonEdgeMap<T>)m;\n                    System.Diagnostics.Debug.Assert(!other.IsEmpty);\n                    return Put(other.Key, other.Value);\n                }\n                else\n                {\n                    if (m is SparseEdgeMap<T>)\n                    {\n                        SparseEdgeMap<T> other = (SparseEdgeMap<T>)m;\n                        lock (other)\n                        {\n                            int[] keys = other.Keys;\n                            IList<T> values = other.Values;\n                            Antlr4.Runtime.Dfa.ArrayEdgeMap<T> result = this;\n                            for (int i = 0; i < values.Count; i++)\n                            {\n                                result = ((Antlr4.Runtime.Dfa.ArrayEdgeMap<T>)result.Put(keys[i], values[i]));\n                            }\n                            return result;\n                        }\n                    }\n                    else\n                    {\n                        throw new NotSupportedException(string.Format(\"EdgeMap of type {0} is supported yet.\", m.GetType().FullName));\n                    }\n                }\n            }\n        }\n\n        public override AbstractEdgeMap<T> Clear()\n        {\n            return new EmptyEdgeMap<T>(minIndex, maxIndex);\n        }\n\n        public override IReadOnlyDictionary<int, T> ToMap()\n        {\n            if (IsEmpty)\n            {\n                return Sharpen.Collections.EmptyMap<int, T>();\n            }\n\n            IDictionary<int, T> result = new SortedDictionary<int, T>();\n\n            for (int i = 0; i < arrayData.Length; i++)\n            {\n                T element = arrayData[i];\n                if (element == null)\n                {\n                    continue;\n                }\n                result[i + minIndex] = element;\n            }\n\n            return new ReadOnlyDictionary<int, T>(result);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/DFA.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Dfa\n{\n\tpublic class DFA\n\t{\n\t\t/** A set of all DFA states. Use {@link Map} so we can get old state back\n\t *  ({@link Set} only allows you to see if it's there).\n     */\n\n\t\tpublic Dictionary<DFAState, DFAState> states = new Dictionary<DFAState, DFAState>();\n\n\t\tpublic DFAState s0;\n\n\t\tpublic int decision;\n\n\t\t/** From which ATN state did we create this DFA? */\n\n\t\tpublic DecisionState atnStartState;\n\n\t\t/**\n\t\t * {@code true} if this DFA is for a precedence decision; otherwise,\n\t\t * {@code false}. This is the backing field for {@link #isPrecedenceDfa}.\n\t\t */\n\t\tprivate bool precedenceDfa;\n\n\t\tpublic DFA(DecisionState atnStartState)\n\t\t\t: this(atnStartState, 0)\n\t\t{\n\t\t}\n\n\t\tpublic DFA(DecisionState atnStartState, int decision)\n\t\t{\n\t\t\tthis.atnStartState = atnStartState;\n\t\t\tthis.decision = decision;\n\n\t\t\tthis.precedenceDfa = false;\n\t\t\tif (atnStartState is StarLoopEntryState && ((StarLoopEntryState)atnStartState).isPrecedenceDecision)\n\t\t\t{\n\t\t\t\tthis.precedenceDfa = true;\n\t\t\t\tDFAState precedenceState = new DFAState(new ATNConfigSet());\n\t\t\t\tprecedenceState.edges = Collections.EmptyList<DFAState>();\n\t\t\t\tprecedenceState.isAcceptState = false;\n\t\t\t\tprecedenceState.requiresFullContext = false;\n\t\t\t\tthis.s0 = precedenceState;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Gets whether this DFA is a precedence DFA. Precedence DFAs use a special\n\t\t * start state {@link #s0} which is not stored in {@link #states}. The\n\t\t * {@link DFAState#edges} array for this start state contains outgoing edges\n\t\t * supplying individual start states corresponding to specific precedence\n\t\t * values.\n\t\t *\n\t\t * @return {@code true} if this is a precedence DFA; otherwise,\n\t\t * {@code false}.\n\t\t * @see Parser#getPrecedence()\n\t\t */\n\t\tpublic bool IsPrecedenceDfa\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn precedenceDfa;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Get the start state for a specific precedence value.\n\t\t *\n\t\t * @param precedence The current precedence.\n\t\t * @return The start state corresponding to the specified precedence, or\n\t\t * {@code null} if no start state exists for the specified precedence.\n\t\t *\n\t\t * @throws IllegalStateException if this is not a precedence DFA.\n\t\t * @see #isPrecedenceDfa()\n\t\t */\n\t\tpublic DFAState GetPrecedenceStartState(int precedence)\n\t\t{\n\t\t\tif (!IsPrecedenceDfa)\n\t\t\t{\n\t\t\t\tthrow new Exception(\"Only precedence DFAs may contain a precedence start state.\");\n\t\t\t}\n\n\t\t\t// s0.edges is never null for a precedence DFA\n\t\t\tif (precedence < 0 || precedence >= s0.edges.Length)\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn s0.edges[precedence];\n\t\t}\n\n\t\t/**\n\t\t * Set the start state for a specific precedence value.\n\t\t *\n\t\t * @param precedence The current precedence.\n\t\t * @param startState The start state corresponding to the specified\n\t\t * precedence.\n\t\t *\n\t\t * @throws IllegalStateException if this is not a precedence DFA.\n\t\t * @see #isPrecedenceDfa()\n\t\t */\n\t\tpublic void SetPrecedenceStartState(int precedence, DFAState startState)\n\t\t{\n\t\t\tif (!IsPrecedenceDfa)\n\t\t\t{\n\t\t\t\tthrow new Exception(\"Only precedence DFAs may contain a precedence start state.\");\n\t\t\t}\n\n\t\t\tif (precedence < 0)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// synchronization on s0 here is ok. when the DFA is turned into a\n\t\t\t// precedence DFA, s0 will be initialized once and not updated again\n\t\t\tlock (s0)\n\t\t\t{\n\t\t\t\t// s0.edges is never null for a precedence DFA\n\t\t\t\tif (precedence >= s0.edges.Length)\n\t\t\t\t{\n\t\t\t\t\ts0.edges = Arrays.CopyOf(s0.edges, precedence + 1);\n\t\t\t\t}\n\n\t\t\t\ts0.edges[precedence] = startState;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Return a list of all states in this DFA, ordered by state number.\n\t\t */\n\n\t\tpublic List<DFAState> GetStates()\n\t\t{\n\t\t\tList<DFAState> result = new List<DFAState>(states.Keys);\n\t\t\tresult.Sort((x, y) => x.stateNumber - y.stateNumber);\n\t\t\treturn result;\n\t\t}\n\n\t\tpublic override String ToString() { return ToString(Vocabulary.EmptyVocabulary); }\n\n\n\t\tpublic String ToString(IVocabulary vocabulary)\n\t\t{\n\t\t\tif (s0 == null)\n\t\t\t{\n\t\t\t\treturn \"\";\n\t\t\t}\n\n\t\t\tDFASerializer serializer = new DFASerializer(this, vocabulary);\n\t\t\treturn serializer.ToString();\n\t\t}\n\n\t\tpublic String ToLexerString()\n\t\t{\n\t\t\tif (s0 == null)\n\t\t\t\treturn \"\";\n\t\t\tDFASerializer serializer = new LexerDFASerializer(this);\n\t\t\treturn serializer.ToString();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/DFASerializer.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <summary>A DFA walker that knows how to dump them to serialized strings.</summary>\n    /// <remarks>A DFA walker that knows how to dump them to serialized strings.</remarks>\n    public class DFASerializer\n    {\n        [NotNull]\n        private readonly DFA dfa;\n\n        [NotNull]\n        private readonly IVocabulary vocabulary;\n\n        [Nullable]\n        internal readonly string[] ruleNames;\n\n        [Nullable]\n        internal readonly ATN atn;\n\n        public DFASerializer(DFA dfa, IVocabulary vocabulary)\n            : this(dfa, vocabulary, null, null)\n        {\n        }\n\n        public DFASerializer(DFA dfa, IRecognizer parser)\n            : this(dfa, parser != null ? parser.Vocabulary : Vocabulary.EmptyVocabulary, parser != null ? parser.RuleNames : null, parser != null ? parser.Atn : null)\n        {\n        }\n\n        public DFASerializer(DFA dfa, IVocabulary vocabulary, string[] ruleNames, ATN atn)\n        {\n            this.dfa = dfa;\n            this.vocabulary = vocabulary;\n            this.ruleNames = ruleNames;\n            this.atn = atn;\n        }\n\n        public override string ToString()\n        {\n            if (dfa.s0 == null)\n            {\n                return null;\n            }\n            StringBuilder buf = new StringBuilder();\n            if (dfa.states != null)\n            {\n                List<DFAState> states = new List<DFAState>(dfa.states.Values);\n\t\t\t\tstates.Sort((x,y)=>x.stateNumber - y.stateNumber);\n                foreach (DFAState s in states)\n                {\n\t\t\t\t\tint n = s.edges != null ? s.edges.Length : 0;\n\t\t\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tDFAState t = s.edges[i];\n\t\t\t\t\t\tif (t != null && t.stateNumber != int.MaxValue)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbuf.Append(GetStateString(s));\n\t\t\t\t\t\t\tString label = GetEdgeLabel(i);\n\t\t\t\t\t\t\tbuf.Append(\"-\");\n\t\t\t\t\t\t\tbuf.Append(label);\n\t\t\t\t\t\t\tbuf.Append(\"->\");\n\t\t\t\t\t\t\tbuf.Append(GetStateString(t));\n\t\t\t\t\t\t\tbuf.Append('\\n');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t            }\n            }\n            string output = buf.ToString();\n            if (output.Length == 0)\n            {\n                return null;\n            }\n            return output;\n        }\n\n\n\n        protected internal virtual string GetContextLabel(int i)\n        {\n\t\t\tif (i == PredictionContext.EMPTY_RETURN_STATE)\n            {\n                return \"ctx:EMPTY\";\n            }\n            if (atn != null && i > 0 && i <= atn.states.Count)\n            {\n                ATNState state = atn.states[i];\n                int ruleIndex = state.ruleIndex;\n                if (ruleNames != null && ruleIndex >= 0 && ruleIndex < ruleNames.Length)\n                {\n                    return \"ctx:\" + i.ToString() + \"(\" + ruleNames[ruleIndex] + \")\";\n                }\n            }\n            return \"ctx:\" + i.ToString();\n        }\n\n        protected internal virtual string GetEdgeLabel(int i)\n        {\n            return vocabulary.GetDisplayName(i - 1);\n        }\n\n        internal virtual string GetStateString(DFAState s)\n        {\n\t\t\tif (s == ATNSimulator.ERROR)\n            {\n                return \"ERROR\";\n            }\n\n\t\t\tint n = s.stateNumber;\n\t\t\tstring baseStateStr = (s.isAcceptState ? \":\" : \"\") + \"s\" + n + (s.requiresFullContext ? \"^\" : \"\");\n\t\t\tif ( s.isAcceptState ) {\n\t\t\t\tif ( s.predicates!=null ) {\n\t\t\t\t\treturn baseStateStr + \"=>\" + Arrays.ToString(s.predicates);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn baseStateStr + \"=>\" + s.prediction;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn baseStateStr;\n\t\t\t}\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/DFAState.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Dfa\n{\n\t/// <summary>A DFA state represents a set of possible ATN configurations.</summary>\n\t/// <remarks>\n\t/// A DFA state represents a set of possible ATN configurations.\n\t/// As Aho, Sethi, Ullman p. 117 says \"The DFA uses its state\n\t/// to keep track of all possible states the ATN can be in after\n\t/// reading each input symbol.  That is to say, after reading\n\t/// input a1a2..an, the DFA is in a state that represents the\n\t/// subset T of the states of the ATN that are reachable from the\n\t/// ATN's start state along some path labeled a1a2..an.\"\n\t/// In conventional NFA&#x2192;DFA conversion, therefore, the subset T\n\t/// would be a bitset representing the set of states the\n\t/// ATN could be in.  We need to track the alt predicted by each\n\t/// state as well, however.  More importantly, we need to maintain\n\t/// a stack of states, tracking the closure operations as they\n\t/// jump from rule to rule, emulating rule invocations (method calls).\n\t/// I have to add a stack to simulate the proper lookahead sequences for\n\t/// the underlying LL grammar from which the ATN was derived.\n\t/// <p>I use a set of ATNConfig objects not simple states.  An ATNConfig\n\t/// is both a state (ala normal conversion) and a RuleContext describing\n\t/// the chain of rules (if any) followed to arrive at that state.</p>\n\t/// <p>A DFA state may have multiple references to a particular state,\n\t/// but with different ATN contexts (with same or different alts)\n\t/// meaning that state was reached via a different set of rule invocations.</p>\n\t/// </remarks>\n\tpublic class DFAState\n\t{\n\t\tpublic int stateNumber = -1;\n\n\n\t\tpublic ATNConfigSet configSet = new ATNConfigSet();\n\n\t\t/** {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)\n\t\t *  {@link Token#EOF} maps to {@code edges[0]}.\n\t\t */\n\n\t\tpublic DFAState[] edges;\n\n\t\tpublic bool isAcceptState = false;\n\n\t\t/** if accept state, what ttype do we match or alt do we predict?\n\t\t *  This is set to {@link ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or\n\t\t *  {@link #requiresFullContext}.\n\t\t */\n\t\tpublic int prediction;\n\n\t\tpublic LexerActionExecutor lexerActionExecutor;\n\n\t\t/**\n\t\t * Indicates that this state was created during SLL prediction that\n\t\t * discovered a conflict between the configurations in the state. Future\n\t\t * {@link ParserATNSimulator#execATN} invocations immediately jumped doing\n\t\t * full context prediction if this field is true.\n\t\t */\n\t\tpublic bool requiresFullContext;\n\n\t\t/** During SLL parsing, this is a list of predicates associated with the\n\t\t *  ATN configurations of the DFA state. When we have predicates,\n\t\t *  {@link #requiresFullContext} is {@code false} since full context prediction evaluates predicates\n\t\t *  on-the-fly. If this is not null, then {@link #prediction} is\n\t\t *  {@link ATN#INVALID_ALT_NUMBER}.\n\t\t *\n\t\t *  <p>We only use these for non-{@link #requiresFullContext} but conflicting states. That\n\t\t *  means we know from the context (it's $ or we don't dip into outer\n\t\t *  context) that it's an ambiguity not a conflict.</p>\n\t\t *\n\t\t *  <p>This list is computed by {@link ParserATNSimulator#predicateDFAState}.</p>\n\t\t */\n\n\t\tpublic PredPrediction[] predicates;\n\n\n\n\t\tpublic DFAState() { }\n\n\t\tpublic DFAState(int stateNumber) { this.stateNumber = stateNumber; }\n\n\t\tpublic DFAState(ATNConfigSet configs) { this.configSet = configs; }\n\n\t\t/** Get the set of all alts mentioned by all ATN configurations in this\n\t\t *  DFA state.\n\t\t */\n\t\tpublic HashSet<int> getAltSet()\n\t\t{\n\t\t\tHashSet<int> alts = new HashSet<int>();\n\t\t\tif (configSet != null)\n\t\t\t{\n\t\t\t\tforeach (ATNConfig c in configSet.configs)\n\t\t\t\t{\n\t\t\t\t\talts.Add(c.alt);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (alts.Count==0)\n\t\t\t\treturn null;\n\t\t\treturn alts;\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\tint hash = MurmurHash.Initialize(7);\n\t\t\thash = MurmurHash.Update(hash, configSet.GetHashCode());\n\t\t\thash = MurmurHash.Finish(hash, 1);\n\t\t\treturn hash;\n\t\t}\n\n\t\t/**\n\t\t * Two {@link DFAState} instances are equal if their ATN configuration sets\n\t\t * are the same. This method is used to see if a state already exists.\n\t\t *\n\t\t * <p>Because the number of alternatives and number of ATN configurations are\n\t\t * finite, there is a finite number of DFA states that can be processed.\n\t\t * This is necessary to show that the algorithm terminates.</p>\n\t\t *\n\t\t * <p>Cannot test the DFA state numbers here because in\n\t\t * {@link ParserATNSimulator#addDFAState} we need to know if any other state\n\t\t * exists that has this exact set of ATN configurations. The\n\t\t * {@link #stateNumber} is irrelevant.</p>\n\t\t */\n\t\tpublic override bool Equals(Object o)\n\t\t{\n\t\t\t// compare set of ATN configurations in this set with other\n\t\t\tif (this == o) return true;\n\n\t\t\tif (!(o is DFAState))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tDFAState other = (DFAState)o;\n\t\t\t// TODO (sam): what to do when configs==null?\n\t\t\tbool sameSet = this.configSet.Equals(other.configSet);\n\t\t\t//\t\tSystem.out.println(\"DFAState.equals: \"+configs+(sameSet?\"==\":\"!=\")+other.configs);\n\t\t\treturn sameSet;\n\t\t}\n\n\t\tpublic override String ToString()\n\t\t{\n\t\t\tStringBuilder buf = new StringBuilder();\n\t\t\tbuf.Append(stateNumber).Append(\":\").Append(configSet);\n\t\t\tif (isAcceptState)\n\t\t\t{\n\t\t\t\tbuf.Append(\"=>\");\n\t\t\t\tif (predicates != null)\n\t\t\t\t{\n\t\t\t\t\tbuf.Append(Arrays.ToString(predicates));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbuf.Append(prediction);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn buf.ToString();\n\t\t}\n\t}\n\n\t/** Map a predicate to a predicted alternative. */\n\tpublic class PredPrediction\n\t{\n\n\t\tpublic SemanticContext pred; // never null; at least SemanticContext.Empty.Instance\n\t\tpublic int alt;\n\t\tpublic PredPrediction(SemanticContext pred, int alt)\n\t\t{\n\t\t\tthis.alt = alt;\n\t\t\tthis.pred = pred;\n\t\t}\n\n\t\tpublic override String ToString()\n\t\t{\n\t\t\treturn \"(\" + pred + \", \" + alt + \")\";\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/EmptyEdgeMap.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <summary>\n    /// This implementation of\n    /// <see cref=\"AbstractEdgeMap{T}\"/>\n    /// represents an empty edge map.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    public sealed class EmptyEdgeMap<T> : AbstractEdgeMap<T>\n        where T : class\n    {\n        public EmptyEdgeMap(int minIndex, int maxIndex)\n            : base(minIndex, maxIndex)\n        {\n        }\n\n        public override AbstractEdgeMap<T> Put(int key, T value)\n        {\n            if (value == null || key < minIndex || key > maxIndex)\n            {\n                // remains empty\n                return this;\n            }\n            return new SingletonEdgeMap<T>(minIndex, maxIndex, key, value);\n        }\n\n        public override AbstractEdgeMap<T> Clear()\n        {\n            return this;\n        }\n\n        public override AbstractEdgeMap<T> Remove(int key)\n        {\n            return this;\n        }\n\n        public override int Count\n        {\n            get\n            {\n                return 0;\n            }\n        }\n\n        public override bool IsEmpty\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public override bool ContainsKey(int key)\n        {\n            return false;\n        }\n\n        public override T this[int key]\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        public override IReadOnlyDictionary<int, T> ToMap()\n        {\n            return new ReadOnlyDictionary<int, T>(new Dictionary<int, T>());\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/IEdgeMap.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <author>Sam Harwell</author>\n    public interface IEdgeMap<T> : IEnumerable<KeyValuePair<int, T>>\n    {\n        int Count\n        {\n            get;\n        }\n\n        bool IsEmpty\n        {\n            get;\n        }\n\n        bool ContainsKey(int key);\n\n        T this[int key]\n        {\n            get;\n        }\n\n        [return: NotNull]\n        IEdgeMap<T> Put(int key, T value);\n\n        [return: NotNull]\n        IEdgeMap<T> Remove(int key);\n\n        [return: NotNull]\n        IEdgeMap<T> PutAll(IEdgeMap<T> m);\n\n        [return: NotNull]\n        IEdgeMap<T> Clear();\n\n        [return: NotNull]\n        IReadOnlyDictionary<int, T> ToMap();\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/LexerDFASerializer.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    public class LexerDFASerializer : DFASerializer\n    {\n        public LexerDFASerializer(DFA dfa)\n            : base(dfa, Vocabulary.EmptyVocabulary)\n        {\n        }\n\n        [return: NotNull]\n        protected internal override string GetEdgeLabel(int i)\n        {\n            return \"'\" + (char)i + \"'\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/SingletonEdgeMap.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <author>Sam Harwell</author>\n    public sealed class SingletonEdgeMap<T> : AbstractEdgeMap<T>\n        where T : class\n    {\n        private readonly int key;\n\n        private readonly T value;\n\n        public SingletonEdgeMap(int minIndex, int maxIndex, int key, T value)\n            : base(minIndex, maxIndex)\n        {\n            if (key >= minIndex && key <= maxIndex)\n            {\n                this.key = key;\n                this.value = value;\n            }\n            else\n            {\n                this.key = 0;\n                this.value = null;\n            }\n        }\n\n        public int Key\n        {\n            get\n            {\n                return key;\n            }\n        }\n\n        public T Value\n        {\n            get\n            {\n                return value;\n            }\n        }\n\n        public override int Count\n        {\n            get\n            {\n                return value != null ? 1 : 0;\n            }\n        }\n\n        public override bool IsEmpty\n        {\n            get\n            {\n                return value == null;\n            }\n        }\n\n        public override bool ContainsKey(int key)\n        {\n            return key == this.key && value != null;\n        }\n\n        public override T this[int key]\n        {\n            get\n            {\n                if (key == this.key)\n                {\n                    return value;\n                }\n                return null;\n            }\n        }\n\n        public override AbstractEdgeMap<T> Put(int key, T value)\n        {\n            if (key < minIndex || key > maxIndex)\n            {\n                return this;\n            }\n            if (key == this.key || this.value == null)\n            {\n                return new Antlr4.Runtime.Dfa.SingletonEdgeMap<T>(minIndex, maxIndex, key, value);\n            }\n            else\n            {\n                if (value != null)\n                {\n                    AbstractEdgeMap<T> result = new SparseEdgeMap<T>(minIndex, maxIndex);\n                    result = result.Put(this.key, this.value);\n                    result = result.Put(key, value);\n                    return result;\n                }\n                else\n                {\n                    return this;\n                }\n            }\n        }\n\n        public override AbstractEdgeMap<T> Remove(int key)\n        {\n            if (key == this.key && this.value != null)\n            {\n                return new EmptyEdgeMap<T>(minIndex, maxIndex);\n            }\n            return this;\n        }\n\n        public override AbstractEdgeMap<T> Clear()\n        {\n            if (this.value != null)\n            {\n                return new EmptyEdgeMap<T>(minIndex, maxIndex);\n            }\n            return this;\n        }\n\n        public override IReadOnlyDictionary<int, T> ToMap()\n        {\n            if (IsEmpty)\n            {\n                return Sharpen.Collections.EmptyMap<int, T>();\n            }\n            return Sharpen.Collections.SingletonMap(key, value);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Dfa/SparseEdgeMap.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Dfa\n{\n    /// <author>Sam Harwell</author>\n    public sealed class SparseEdgeMap<T> : AbstractEdgeMap<T>\n        where T : class\n    {\n        private const int DefaultMaxSize = 5;\n\n        private readonly int[] keys;\n\n        private readonly List<T> values;\n\n        public SparseEdgeMap(int minIndex, int maxIndex)\n            : this(minIndex, maxIndex, DefaultMaxSize)\n        {\n        }\n\n        public SparseEdgeMap(int minIndex, int maxIndex, int maxSparseSize)\n            : base(minIndex, maxIndex)\n        {\n            this.keys = new int[maxSparseSize];\n            this.values = new List<T>(maxSparseSize);\n        }\n\n        private SparseEdgeMap(Antlr4.Runtime.Dfa.SparseEdgeMap<T> map, int maxSparseSize)\n            : base(map.minIndex, map.maxIndex)\n        {\n            lock (map)\n            {\n                if (maxSparseSize < map.values.Count)\n                {\n                    throw new ArgumentException();\n                }\n                keys = Arrays.CopyOf(map.keys, maxSparseSize);\n                values = new List<T>(maxSparseSize);\n                values.AddRange(map.Values);\n            }\n        }\n\n        public int[] Keys\n        {\n            get\n            {\n                return keys;\n            }\n        }\n\n        public IList<T> Values\n        {\n            get\n            {\n                return values;\n            }\n        }\n\n        public int MaxSparseSize\n        {\n            get\n            {\n                return keys.Length;\n            }\n        }\n\n        public override int Count\n        {\n            get\n            {\n                return values.Count;\n            }\n        }\n\n        public override bool IsEmpty\n        {\n            get\n            {\n                return values.Count == 0;\n            }\n        }\n\n        public override bool ContainsKey(int key)\n        {\n            return this[key] != null;\n        }\n\n        public override T this[int key]\n        {\n            get\n            {\n                // Special property of this collection: values are only even added to\n                // the end, else a new object is returned from put(). Therefore no lock\n                // is required in this method.\n                int index = System.Array.BinarySearch(keys, 0, Count, key);\n                if (index < 0)\n                {\n                    return null;\n                }\n                return values[index];\n            }\n        }\n\n        public override AbstractEdgeMap<T> Put(int key, T value)\n        {\n            if (key < minIndex || key > maxIndex)\n            {\n                return this;\n            }\n            if (value == null)\n            {\n                return Remove(key);\n            }\n            lock (this)\n            {\n                int index = System.Array.BinarySearch(keys, 0, Count, key);\n                if (index >= 0)\n                {\n                    // replace existing entry\n                    values[index] = value;\n                    return this;\n                }\n                System.Diagnostics.Debug.Assert(index < 0 && value != null);\n                int insertIndex = -index - 1;\n                if (Count < MaxSparseSize && insertIndex == Count)\n                {\n                    // stay sparse and add new entry\n                    keys[insertIndex] = key;\n                    values.Add(value);\n                    return this;\n                }\n                int desiredSize = Count >= MaxSparseSize ? MaxSparseSize * 2 : MaxSparseSize;\n                int space = maxIndex - minIndex + 1;\n                // SparseEdgeMap only uses less memory than ArrayEdgeMap up to half the size of the symbol space\n                if (desiredSize >= space / 2)\n                {\n                    ArrayEdgeMap<T> arrayMap = new ArrayEdgeMap<T>(minIndex, maxIndex);\n                    arrayMap = ((ArrayEdgeMap<T>)arrayMap.PutAll(this));\n                    arrayMap.Put(key, value);\n                    return arrayMap;\n                }\n                else\n                {\n                    Antlr4.Runtime.Dfa.SparseEdgeMap<T> resized = new Antlr4.Runtime.Dfa.SparseEdgeMap<T>(this, desiredSize);\n                    System.Array.Copy(resized.keys, insertIndex, resized.keys, insertIndex + 1, Count - insertIndex);\n                    resized.keys[insertIndex] = key;\n                    resized.values.Insert(insertIndex, value);\n                    return resized;\n                }\n            }\n        }\n\n        public override AbstractEdgeMap<T> Remove(int key)\n        {\n            lock (this)\n            {\n                int index = System.Array.BinarySearch(keys, 0, Count, key);\n                if (index < 0)\n                {\n                    return this;\n                }\n                Antlr4.Runtime.Dfa.SparseEdgeMap<T> result = new Antlr4.Runtime.Dfa.SparseEdgeMap<T>(this, MaxSparseSize);\n                System.Array.Copy(result.keys, index + 1, result.keys, index, Count - index - 1);\n                result.values.RemoveAt(index);\n                return result;\n            }\n        }\n\n        public override AbstractEdgeMap<T> Clear()\n        {\n            if (IsEmpty)\n            {\n                return this;\n            }\n            return new EmptyEdgeMap<T>(minIndex, maxIndex);\n        }\n\n        public override IReadOnlyDictionary<int, T> ToMap()\n        {\n            if (IsEmpty)\n            {\n                return Sharpen.Collections.EmptyMap<int, T>();\n            }\n            lock (this)\n            {\n                IDictionary<int, T> result = new SortedDictionary<int, T>();\n\n                for (int i = 0; i < Count; i++)\n                {\n                    result[keys[i]] = values[i];\n                }\n\n                return new ReadOnlyDictionary<int, T>(result);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/DiagnosticErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This implementation of\n    /// <see cref=\"IAntlrErrorListener{Symbol}\"/>\n    /// can be used to identify\n    /// certain potential correctness and performance problems in grammars. \"Reports\"\n    /// are made by calling\n    /// <see cref=\"Parser.NotifyErrorListeners(string)\"/>\n    /// with the appropriate\n    /// message.\n    /// <ul>\n    /// <li><b>Ambiguities</b>: These are cases where more than one path through the\n    /// grammar can match the input.</li>\n    /// <li><b>Weak context sensitivity</b>: These are cases where full-context\n    /// prediction resolved an SLL conflict to a unique alternative which equaled the\n    /// minimum alternative of the SLL conflict.</li>\n    /// <li><b>Strong (forced) context sensitivity</b>: These are cases where the\n    /// full-context prediction resolved an SLL conflict to a unique alternative,\n    /// <em>and</em> the minimum alternative of the SLL conflict was found to not be\n    /// a truly viable alternative. Two-stage parsing cannot be used for inputs where\n    /// this situation occurs.</li>\n    /// </ul>\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    public class DiagnosticErrorListener : BaseErrorListener\n    {\n        /// <summary>\n        /// When\n        /// <see langword=\"true\"/>\n        /// , only exactly known ambiguities are reported.\n        /// </summary>\n        protected internal readonly bool exactOnly;\n\n        /// <summary>\n        /// Initializes a new instance of\n        /// <see cref=\"DiagnosticErrorListener\"/>\n        /// which only\n        /// reports exact ambiguities.\n        /// </summary>\n        public DiagnosticErrorListener()\n            : this(true)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of\n        /// <see cref=\"DiagnosticErrorListener\"/>\n        /// , specifying\n        /// whether all ambiguities or only exact ambiguities are reported.\n        /// </summary>\n        /// <param name=\"exactOnly\">\n        ///\n        /// <see langword=\"true\"/>\n        /// to report only exact ambiguities, otherwise\n        /// <see langword=\"false\"/>\n        /// to report all ambiguities.\n        /// </param>\n        public DiagnosticErrorListener(bool exactOnly)\n        {\n            this.exactOnly = exactOnly;\n        }\n\n        public override void ReportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, bool exact, BitSet ambigAlts, ATNConfigSet configs)\n        {\n            if (exactOnly && !exact)\n            {\n                return;\n            }\n            string format = \"reportAmbiguity d={0}: ambigAlts={1}, input='{2}'\";\n            string decision = GetDecisionDescription(recognizer, dfa);\n            BitSet conflictingAlts = GetConflictingAlts(ambigAlts, configs);\n            string text = ((ITokenStream)recognizer.InputStream).GetText(Interval.Of(startIndex, stopIndex));\n            string message = string.Format(format, decision, conflictingAlts, text);\n            recognizer.NotifyErrorListeners(message);\n        }\n\n        public override void ReportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs)\n        {\n            string format = \"reportAttemptingFullContext d={0}, input='{1}'\";\n            string decision = GetDecisionDescription(recognizer, dfa);\n            string text = ((ITokenStream)recognizer.InputStream).GetText(Interval.Of(startIndex, stopIndex));\n            string message = string.Format(format, decision, text);\n            recognizer.NotifyErrorListeners(message);\n        }\n\n        public override void ReportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs)\n        {\n            string format = \"reportContextSensitivity d={0}, input='{1}'\";\n            string decision = GetDecisionDescription(recognizer, dfa);\n            string text = ((ITokenStream)recognizer.InputStream).GetText(Interval.Of(startIndex, stopIndex));\n            string message = string.Format(format, decision, text);\n            recognizer.NotifyErrorListeners(message);\n        }\n\n        protected internal virtual string GetDecisionDescription(Parser recognizer, DFA dfa)\n        {\n            int decision = dfa.decision;\n            int ruleIndex = dfa.atnStartState.ruleIndex;\n            string[] ruleNames = recognizer.RuleNames;\n            if (ruleIndex < 0 || ruleIndex >= ruleNames.Length)\n            {\n                return decision.ToString();\n            }\n            string ruleName = ruleNames[ruleIndex];\n            if (string.IsNullOrEmpty(ruleName))\n            {\n                return decision.ToString();\n            }\n            return string.Format(\"{0} ({1})\", decision, ruleName);\n        }\n\n        /// <summary>\n        /// Computes the set of conflicting or ambiguous alternatives from a\n        /// configuration set, if that information was not already provided by the\n        /// parser.\n        /// </summary>\n        /// <remarks>\n        /// Computes the set of conflicting or ambiguous alternatives from a\n        /// configuration set, if that information was not already provided by the\n        /// parser.\n        /// </remarks>\n        /// <param name=\"reportedAlts\">\n        /// The set of conflicting or ambiguous alternatives, as\n        /// reported by the parser.\n        /// </param>\n        /// <param name=\"configSet\">The conflicting or ambiguous configuration set.</param>\n        /// <returns>\n        /// Returns\n        /// <paramref name=\"reportedAlts\"/>\n        /// if it is not\n        /// <see langword=\"null\"/>\n        /// , otherwise\n        /// returns the set of alternatives represented in\n        /// <paramref name=\"configSet\"/>\n        /// .\n        /// </returns>\n        [return: NotNull]\n\t\tprotected internal virtual BitSet GetConflictingAlts(BitSet reportedAlts, ATNConfigSet configSet)\n        {\n            if (reportedAlts != null)\n            {\n                return reportedAlts;\n            }\n            BitSet result = new BitSet();\n\t\t\tforeach (ATNConfig config in configSet.configs)\n            {\n                result.Set(config.alt);\n            }\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/FailedPredicateException.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Globalization;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>A semantic predicate failed during validation.</summary>\n    /// <remarks>\n    /// A semantic predicate failed during validation.  Validation of predicates\n    /// occurs when normally parsing the alternative just like matching a token.\n    /// Disambiguating predicate evaluation occurs when we test a predicate during\n    /// prediction.\n    /// </remarks>\n    [System.Serializable]\n    public class FailedPredicateException : RecognitionException\n    {\n        private const long serialVersionUID = 5379330841495778709L;\n\n        private readonly int ruleIndex;\n\n        private readonly int predicateIndex;\n\n        private readonly string predicate;\n\n        public FailedPredicateException(Parser recognizer)\n            : this(recognizer, null)\n        {\n        }\n\n        public FailedPredicateException(Parser recognizer, string predicate)\n            : this(recognizer, predicate, null)\n        {\n        }\n\n        public FailedPredicateException(Parser recognizer, string predicate, string message)\n\t\t\t: base(FormatMessage(predicate, message), recognizer, ((ITokenStream)recognizer.InputStream), recognizer.RuleContext)\n        {\n            ATNState s = recognizer.Interpreter.atn.states[recognizer.State];\n            AbstractPredicateTransition trans = (AbstractPredicateTransition)s.Transition(0);\n            if (trans is PredicateTransition)\n            {\n                this.ruleIndex = ((PredicateTransition)trans).ruleIndex;\n                this.predicateIndex = ((PredicateTransition)trans).predIndex;\n            }\n            else\n            {\n                this.ruleIndex = 0;\n                this.predicateIndex = 0;\n            }\n            this.predicate = predicate;\n            this.OffendingToken = recognizer.CurrentToken;\n        }\n\n        public virtual int RuleIndex\n        {\n            get\n            {\n                return ruleIndex;\n            }\n        }\n\n        public virtual int PredIndex\n        {\n            get\n            {\n                return predicateIndex;\n            }\n        }\n\n        [Nullable]\n        public virtual string Predicate\n        {\n            get\n            {\n                return predicate;\n            }\n        }\n\n        [return: NotNull]\n        private static string FormatMessage(string predicate, string message)\n        {\n            if (message != null)\n            {\n                return message;\n            }\n            return string.Format(CultureInfo.CurrentCulture, \"failed predicate: {{{0}}}?\", predicate);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IAntlrErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nusing System.IO;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>How to emit recognition errors.</summary>\n    /// <remarks>How to emit recognition errors.</remarks>\n    public interface IAntlrErrorListener<in TSymbol>\n    {\n        /// <summary>Upon syntax error, notify any interested parties.</summary>\n        /// <remarks>\n        /// Upon syntax error, notify any interested parties. This is not how to\n        /// recover from errors or compute error messages.\n        /// <see cref=\"IAntlrErrorStrategy\"/>\n        /// specifies how to recover from syntax errors and how to compute error\n        /// messages. This listener's job is simply to emit a computed message,\n        /// though it has enough information to create its own message in many cases.\n        /// <p>The\n        /// <see cref=\"RecognitionException\"/>\n        /// is non-null for all syntax errors except\n        /// when we discover mismatched token errors that we can recover from\n        /// in-line, without returning from the surrounding rule (via the single\n        /// token insertion and deletion mechanism).</p>\n        /// </remarks>\n        /// <param name=\"output\">\n        /// Where the error should be written.\n        /// </param>\n        /// <param name=\"recognizer\">\n        /// What parser got the error. From this\n        /// object, you can access the context as well\n        /// as the input stream.\n        /// </param>\n        /// <param name=\"offendingSymbol\">\n        /// The offending token in the input token\n        /// stream, unless recognizer is a lexer (then it's null). If\n        /// no viable alternative error,\n        /// <paramref name=\"e\"/>\n        /// has token at which we\n        /// started production for the decision.\n        /// </param>\n        /// <param name=\"line\">The line number in the input where the error occurred.</param>\n        /// <param name=\"charPositionInLine\">The character position within that line where the error occurred.</param>\n        /// <param name=\"msg\">The message to emit.</param>\n        /// <param name=\"e\">\n        /// The exception generated by the parser that led to\n        /// the reporting of an error. It is null in the case where\n        /// the parser was able to recover in line without exiting the\n        /// surrounding rule.\n        /// </param>\n        void SyntaxError(TextWriter output, IRecognizer recognizer, TSymbol offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IAntlrErrorStrategy.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing System.IO;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// The interface for defining strategies to deal with syntax errors encountered\n    /// during a parse by ANTLR-generated parsers.\n    /// </summary>\n    /// <remarks>\n    /// The interface for defining strategies to deal with syntax errors encountered\n    /// during a parse by ANTLR-generated parsers. We distinguish between three\n    /// different kinds of errors:\n    /// <ul>\n    /// <li>The parser could not figure out which path to take in the ATN (none of\n    /// the available alternatives could possibly match)</li>\n    /// <li>The current input does not match what we were looking for</li>\n    /// <li>A predicate evaluated to false</li>\n    /// </ul>\n    /// Implementations of this interface report syntax errors by calling\n    /// <see cref=\"Parser.NotifyErrorListeners(string)\"/>\n    /// .\n    /// <p>TODO: what to do about lexers</p>\n    /// </remarks>\n    public interface IAntlrErrorStrategy\n    {\n        /// <summary>\n        /// Reset the error handler state for the specified\n        /// <paramref name=\"recognizer\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"recognizer\">the parser instance</param>\n        void Reset(Parser recognizer);\n\n        /// <summary>\n        /// This method is called when an unexpected symbol is encountered during an\n        /// inline match operation, such as\n        /// <see cref=\"Parser.Match(int)\"/>\n        /// . If the error\n        /// strategy successfully recovers from the match failure, this method\n        /// returns the\n        /// <see cref=\"IToken\"/>\n        /// instance which should be treated as the\n        /// successful result of the match.\n        /// <p>Note that the calling code will not report an error if this method\n        /// returns successfully. The error strategy implementation is responsible\n        /// for calling\n        /// <see cref=\"Parser.NotifyErrorListeners(string)\"/>\n        /// as appropriate.</p>\n        /// </summary>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <exception cref=\"RecognitionException\">\n        /// if the error strategy was not able to\n        /// recover from the unexpected input symbol\n        /// </exception>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        [return: NotNull]\n        IToken RecoverInline(Parser recognizer);\n\n        /// <summary>\n        /// This method is called to recover from exception\n        /// <paramref name=\"e\"/>\n        /// . This method is\n        /// called after\n        /// <see cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// by the default exception handler\n        /// generated for a rule method.\n        /// </summary>\n        /// <seealso cref=\"ReportError(Parser, RecognitionException)\"/>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"e\">the recognition exception to recover from</param>\n        /// <exception cref=\"RecognitionException\">\n        /// if the error strategy could not recover from\n        /// the recognition exception\n        /// </exception>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        void Recover(Parser recognizer, RecognitionException e);\n\n        /// <summary>\n        /// This method provides the error handler with an opportunity to handle\n        /// syntactic or semantic errors in the input stream before they result in a\n        /// <see cref=\"RecognitionException\"/>\n        /// .\n        /// <p>The generated code currently contains calls to\n        /// <see cref=\"Sync(Parser)\"/>\n        /// after\n        /// entering the decision state of a closure block (\n        /// <c>(...)*</c>\n        /// or\n        /// <c>(...)+</c>\n        /// ).</p>\n        /// <p>For an implementation based on Jim Idle's \"magic sync\" mechanism, see\n        /// <see cref=\"DefaultErrorStrategy.Sync(Parser)\"/>\n        /// .</p>\n        /// </summary>\n        /// <seealso cref=\"DefaultErrorStrategy.Sync(Parser)\"/>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <exception cref=\"RecognitionException\">\n        /// if an error is detected by the error\n        /// strategy but cannot be automatically recovered at the current state in\n        /// the parsing process\n        /// </exception>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        void Sync(Parser recognizer);\n\n        /// <summary>\n        /// Tests whether or not\n        /// <paramref name=\"recognizer\"/>\n        /// is in the process of recovering\n        /// from an error. In error recovery mode,\n        /// <see cref=\"Parser.Consume()\"/>\n        /// adds\n        /// symbols to the parse tree by calling\n        /// <see cref=\"ParserRuleContext.AddErrorNode(IToken)\"/>\n        /// instead of\n        /// <see cref=\"ParserRuleContext.AddChild(IToken)\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if the parser is currently recovering from a parse\n        /// error, otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        bool InErrorRecoveryMode(Parser recognizer);\n\n        /// <summary>\n        /// This method is called by when the parser successfully matches an input\n        /// symbol.\n        /// </summary>\n        /// <remarks>\n        /// This method is called by when the parser successfully matches an input\n        /// symbol.\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        void ReportMatch(Parser recognizer);\n\n        /// <summary>\n        /// Report any kind of\n        /// <see cref=\"RecognitionException\"/>\n        /// . This method is called by\n        /// the default exception handler generated for a rule method.\n        /// </summary>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"e\">the recognition exception to report</param>\n        void ReportError(Parser recognizer, RecognitionException e);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ICharStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>A source of characters for an ANTLR lexer.</summary>\n    /// <remarks>A source of characters for an ANTLR lexer.</remarks>\n    public interface ICharStream : IIntStream\n    {\n        /// <summary>\n        /// This method returns the text for a range of characters within this input\n        /// stream.\n        /// </summary>\n        /// <remarks>\n        /// This method returns the text for a range of characters within this input\n        /// stream. This method is guaranteed to not throw an exception if the\n        /// specified\n        /// <paramref name=\"interval\"/>\n        /// lies entirely within a marked range. For more\n        /// information about marked ranges, see\n        /// <see cref=\"IIntStream.Mark()\"/>\n        /// .\n        /// </remarks>\n        /// <param name=\"interval\">an interval within the stream</param>\n        /// <returns>the text of the specified interval</returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// if\n        /// <paramref name=\"interval\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        /// <exception cref=\"System.ArgumentException\">\n        /// if\n        /// <c>interval.a &lt; 0</c>\n        /// , or if\n        /// <c>interval.b &lt; interval.a - 1</c>\n        /// , or if\n        /// <c>interval.b</c>\n        /// lies at or\n        /// past the end of the stream\n        /// </exception>\n        /// <exception cref=\"System.NotSupportedException\">\n        /// if the stream does not support\n        /// getting the text of the specified interval\n        /// </exception>\n        [return: NotNull]\n        string GetText(Interval interval);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IIntStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>A simple stream of symbols whose values are represented as integers.</summary>\n    /// <remarks>\n    /// A simple stream of symbols whose values are represented as integers. This\n    /// interface provides <em>marked ranges</em> with support for a minimum level\n    /// of buffering necessary to implement arbitrary lookahead during prediction.\n    /// For more information on marked ranges, see\n    /// <see cref=\"Mark()\"/>\n    /// .\n    /// <p><strong>Initializing Methods:</strong> Some methods in this interface have\n    /// unspecified behavior if no call to an initializing method has occurred after\n    /// the stream was constructed. The following is a list of initializing methods:</p>\n    /// <ul>\n    /// <li>\n    /// <see cref=\"LA(int)\"/>\n    /// </li>\n    /// <li>\n    /// <see cref=\"Consume()\"/>\n    /// </li>\n    /// <li>\n    /// <see cref=\"Size()\"/>\n    /// </li>\n    /// </ul>\n    /// </remarks>\n    public interface IIntStream\n    {\n        /// <summary>Consumes the current symbol in the stream.</summary>\n        /// <remarks>\n        /// Consumes the current symbol in the stream. This method has the following\n        /// effects:\n        /// <ul>\n        /// <li><strong>Forward movement:</strong> The value of\n        /// <see cref=\"Index()\">index()</see>\n        /// before calling this method is less than the value of\n        /// <c>index()</c>\n        /// after calling this method.</li>\n        /// <li><strong>Ordered lookahead:</strong> The value of\n        /// <c>LA(1)</c>\n        /// before\n        /// calling this method becomes the value of\n        /// <c>LA(-1)</c>\n        /// after calling\n        /// this method.</li>\n        /// </ul>\n        /// Note that calling this method does not guarantee that\n        /// <c>index()</c>\n        /// is\n        /// incremented by exactly 1, as that would preclude the ability to implement\n        /// filtering streams (e.g.\n        /// <see cref=\"CommonTokenStream\"/>\n        /// which distinguishes\n        /// between \"on-channel\" and \"off-channel\" tokens).\n        /// </remarks>\n        /// <exception cref=\"System.InvalidOperationException\">\n        /// if an attempt is made to consume the the\n        /// end of the stream (i.e. if\n        /// <c>LA(1)==</c>\n        /// <see cref=\"IntStreamConstants.EOF\">EOF</see>\n        /// before calling\n        /// <c>consume</c>\n        /// ).\n        /// </exception>\n        void Consume();\n\n        /// <summary>\n        /// Gets the value of the symbol at offset\n        /// <paramref name=\"i\"/>\n        /// from the current\n        /// position. When\n        /// <c>i==1</c>\n        /// , this method returns the value of the current\n        /// symbol in the stream (which is the next symbol to be consumed). When\n        /// <c>i==-1</c>\n        /// , this method returns the value of the previously read\n        /// symbol in the stream. It is not valid to call this method with\n        /// <c>i==0</c>\n        /// , but the specific behavior is unspecified because this\n        /// method is frequently called from performance-critical code.\n        /// <p>This method is guaranteed to succeed if any of the following are true:</p>\n        /// <ul>\n        /// <li>\n        /// <c>i&gt;0</c>\n        /// </li>\n        /// <li>\n        /// <c>i==-1</c>\n        /// and\n        /// <see cref=\"Index()\">index()</see>\n        /// returns a value greater\n        /// than the value of\n        /// <c>index()</c>\n        /// after the stream was constructed\n        /// and\n        /// <c>LA(1)</c>\n        /// was called in that order. Specifying the current\n        /// <c>index()</c>\n        /// relative to the index after the stream was created\n        /// allows for filtering implementations that do not return every symbol\n        /// from the underlying source. Specifying the call to\n        /// <c>LA(1)</c>\n        /// allows for lazily initialized streams.</li>\n        /// <li>\n        /// <c>LA(i)</c>\n        /// refers to a symbol consumed within a marked region\n        /// that has not yet been released.</li>\n        /// </ul>\n        /// <p>If\n        /// <paramref name=\"i\"/>\n        /// represents a position at or beyond the end of the stream,\n        /// this method returns\n        /// <see cref=\"IntStreamConstants.EOF\"/>\n        /// .</p>\n        /// <p>The return value is unspecified if\n        /// <c>i&lt;0</c>\n        /// and fewer than\n        /// <c>-i</c>\n        /// calls to\n        /// <see cref=\"Consume()\">consume()</see>\n        /// have occurred from the beginning of\n        /// the stream before calling this method.</p>\n        /// </summary>\n        /// <exception cref=\"System.NotSupportedException\">\n        /// if the stream does not support\n        /// retrieving the value of the specified symbol\n        /// </exception>\n        int LA(int i);\n\n        /// <summary>\n        /// A mark provides a guarantee that\n        /// <see cref=\"Seek(int)\">seek()</see>\n        /// operations will be\n        /// valid over a \"marked range\" extending from the index where\n        /// <c>mark()</c>\n        /// was called to the current\n        /// <see cref=\"Index()\">index()</see>\n        /// . This allows the use of\n        /// streaming input sources by specifying the minimum buffering requirements\n        /// to support arbitrary lookahead during prediction.\n        /// <p>The returned mark is an opaque handle (type\n        /// <c>int</c>\n        /// ) which is passed\n        /// to\n        /// <see cref=\"Release(int)\">release()</see>\n        /// when the guarantees provided by the marked\n        /// range are no longer necessary. When calls to\n        /// <c>mark()</c>\n        /// /\n        /// <c>release()</c>\n        /// are nested, the marks must be released\n        /// in reverse order of which they were obtained. Since marked regions are\n        /// used during performance-critical sections of prediction, the specific\n        /// behavior of invalid usage is unspecified (i.e. a mark is not released, or\n        /// a mark is released twice, or marks are not released in reverse order from\n        /// which they were created).</p>\n        /// <p>The behavior of this method is unspecified if no call to an\n        /// <see cref=\"IIntStream\">initializing method</see>\n        /// has occurred after this stream was\n        /// constructed.</p>\n        /// <p>This method does not change the current position in the input stream.</p>\n        /// <p>The following example shows the use of\n        /// <see cref=\"Mark()\">mark()</see>\n        /// ,\n        /// <see cref=\"Release(int)\">release(mark)</see>\n        /// ,\n        /// <see cref=\"Index()\">index()</see>\n        /// , and\n        /// <see cref=\"Seek(int)\">seek(index)</see>\n        /// as part of an operation to safely work within a\n        /// marked region, then restore the stream position to its original value and\n        /// release the mark.</p>\n        /// <pre>\n        /// IntStream stream = ...;\n        /// int index = -1;\n        /// int mark = stream.mark();\n        /// try {\n        /// index = stream.index();\n        /// // perform work here...\n        /// } finally {\n        /// if (index != -1) {\n        /// stream.seek(index);\n        /// }\n        /// stream.release(mark);\n        /// }\n        /// </pre>\n        /// </summary>\n        /// <returns>\n        /// An opaque marker which should be passed to\n        /// <see cref=\"Release(int)\">release()</see>\n        /// when the marked range is no longer required.\n        /// </returns>\n        int Mark();\n\n        /// <summary>\n        /// This method releases a marked range created by a call to\n        /// <see cref=\"Mark()\">mark()</see>\n        /// . Calls to\n        /// <c>release()</c>\n        /// must appear in the\n        /// reverse order of the corresponding calls to\n        /// <c>mark()</c>\n        /// . If a mark is\n        /// released twice, or if marks are not released in reverse order of the\n        /// corresponding calls to\n        /// <c>mark()</c>\n        /// , the behavior is unspecified.\n        /// <p>For more information and an example, see\n        /// <see cref=\"Mark()\"/>\n        /// .</p>\n        /// </summary>\n        /// <param name=\"marker\">\n        /// A marker returned by a call to\n        /// <c>mark()</c>\n        /// .\n        /// </param>\n        /// <seealso cref=\"Mark()\"/>\n        void Release(int marker);\n\n        /// <summary>\n        /// Return the index into the stream of the input symbol referred to by\n        /// <c>LA(1)</c>\n        /// .\n        /// <p>The behavior of this method is unspecified if no call to an\n        /// <see cref=\"IIntStream\">initializing method</see>\n        /// has occurred after this stream was\n        /// constructed.</p>\n        /// </summary>\n        int Index\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Set the input cursor to the position indicated by\n        /// <paramref name=\"index\"/>\n        /// . If the\n        /// specified index lies past the end of the stream, the operation behaves as\n        /// though\n        /// <paramref name=\"index\"/>\n        /// was the index of the EOF symbol. After this method\n        /// returns without throwing an exception, the at least one of the following\n        /// will be true.\n        /// <ul>\n        /// <li>\n        /// <see cref=\"Index()\">index()</see>\n        /// will return the index of the first symbol\n        /// appearing at or after the specified\n        /// <paramref name=\"index\"/>\n        /// . Specifically,\n        /// implementations which filter their sources should automatically\n        /// adjust\n        /// <paramref name=\"index\"/>\n        /// forward the minimum amount required for the\n        /// operation to target a non-ignored symbol.</li>\n        /// <li>\n        /// <c>LA(1)</c>\n        /// returns\n        /// <see cref=\"IntStreamConstants.EOF\"/>\n        /// </li>\n        /// </ul>\n        /// This operation is guaranteed to not throw an exception if\n        /// <paramref name=\"index\"/>\n        /// lies within a marked region. For more information on marked regions, see\n        /// <see cref=\"Mark()\"/>\n        /// . The behavior of this method is unspecified if no call to\n        /// an\n        /// <see cref=\"IIntStream\">initializing method</see>\n        /// has occurred after this stream\n        /// was constructed.\n        /// </summary>\n        /// <param name=\"index\">The absolute index to seek to.</param>\n        /// <exception cref=\"System.ArgumentException\">\n        /// if\n        /// <paramref name=\"index\"/>\n        /// is less than 0\n        /// </exception>\n        /// <exception cref=\"System.NotSupportedException\">\n        /// if the stream does not support\n        /// seeking to the specified index\n        /// </exception>\n        void Seek(int index);\n\n        /// <summary>\n        /// Returns the total number of symbols in the stream, including a single EOF\n        /// symbol.\n        /// </summary>\n        /// <remarks>\n        /// Returns the total number of symbols in the stream, including a single EOF\n        /// symbol.\n        /// </remarks>\n        /// <exception cref=\"System.NotSupportedException\">\n        /// if the size of the stream is\n        /// unknown.\n        /// </exception>\n        int Size\n        {\n            get;\n        }\n\n        /// <summary>Gets the name of the underlying symbol source.</summary>\n        /// <remarks>\n        /// Gets the name of the underlying symbol source. This method returns a\n        /// non-null, non-empty string. If such a name is not known, this method\n        /// returns\n        /// <see cref=\"IntStreamConstants.UnknownSourceName\"/>\n        /// .\n        /// </remarks>\n        string SourceName\n        {\n            get;\n        }\n    }\n\n    public static class IntStreamConstants\n    {\n        /// <summary>\n        /// The value returned by\n        /// <see cref=\"IIntStream.LA(int)\">LA()</see>\n        /// when the end of the stream is\n        /// reached.\n        /// </summary>\n        public const int EOF = -1;\n\n        /// <summary>\n        /// The value returned by\n        /// <see cref=\"IIntStream.SourceName\"/>\n        /// when the actual name of the\n        /// underlying source is not known.\n        /// </summary>\n        public const string UnknownSourceName = \"<unknown>\";\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IParserErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>How to emit recognition errors for parsers.</summary>\n    /// <remarks>How to emit recognition errors for parsers.</remarks>\n    public interface IParserErrorListener : IAntlrErrorListener<IToken>\n    {\n        /// <summary>\n        /// This method is called by the parser when a full-context prediction\n        /// results in an ambiguity.\n        /// </summary>\n        /// <remarks>\n        /// This method is called by the parser when a full-context prediction\n        /// results in an ambiguity.\n        /// <p>Each full-context prediction which does not result in a syntax error\n        /// will call either\n        /// <see cref=\"ReportContextSensitivity(Parser, Antlr4.Runtime.Dfa.DFA, int, int, int, Antlr4.Runtime.Atn.SimulatorState)\"/>\n        /// or\n        /// <see cref=\"ReportAmbiguity(Parser, Antlr4.Runtime.Dfa.DFA, int, int, bool, Antlr4.Runtime.Sharpen.BitSet, Antlr4.Runtime.Atn.ATNConfigSet)\"/>\n        /// .</p>\n        /// <p>\n        /// When\n        /// <paramref name=\"ambigAlts\"/>\n        /// is not null, it contains the set of potentially\n        /// viable alternatives identified by the prediction algorithm. When\n        /// <paramref name=\"ambigAlts\"/>\n        /// is null, use\n        /// <see cref=\"Antlr4.Runtime.Atn.ATNConfigSet.GetAlts()\"/>\n        /// to obtain the represented\n        /// alternatives from the\n        /// <paramref name=\"configs\"/>\n        /// argument.</p>\n        /// <p>When\n        /// <paramref name=\"exact\"/>\n        /// is\n        /// <see langword=\"true\"/>\n        /// , <em>all</em> of the potentially\n        /// viable alternatives are truly viable, i.e. this is reporting an exact\n        /// ambiguity. When\n        /// <paramref name=\"exact\"/>\n        /// is\n        /// <see langword=\"false\"/>\n        /// , <em>at least two</em> of\n        /// the potentially viable alternatives are viable for the current input, but\n        /// the prediction algorithm terminated as soon as it determined that at\n        /// least the <em>minimum</em> potentially viable alternative is truly\n        /// viable.</p>\n        /// <p>When the\n        /// <see cref=\"Antlr4.Runtime.Atn.PredictionMode.LL_EXACT_AMBIG_DETECTION\"/>\n        /// prediction\n        /// mode is used, the parser is required to identify exact ambiguities so\n        /// <paramref name=\"exact\"/>\n        /// will always be\n        /// <see langword=\"true\"/>\n        /// .</p>\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"dfa\">the DFA for the current decision</param>\n        /// <param name=\"startIndex\">the input index where the decision started</param>\n        /// <param name=\"stopIndex\">the input input where the ambiguity was identified</param>\n        /// <param name=\"exact\">\n        ///\n        /// <see langword=\"true\"/>\n        /// if the ambiguity is exactly known, otherwise\n        /// <see langword=\"false\"/>\n        /// . This is always\n        /// <see langword=\"true\"/>\n        /// when\n        /// <see cref=\"Antlr4.Runtime.Atn.PredictionMode.LL_EXACT_AMBIG_DETECTION\"/>\n        /// is used.\n        /// </param>\n        /// <param name=\"ambigAlts\">\n        /// the potentially ambiguous alternatives, or\n        /// <see langword=\"null\"/>\n        /// to indicate that the potentially ambiguous alternatives are the complete\n        /// set of represented alternatives in\n        /// <paramref name=\"configs\"/>\n        /// </param>\n        /// <param name=\"configs\">\n        /// the ATN configuration set where the ambiguity was\n        /// identified\n        /// </param>\n        void ReportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, bool exact, BitSet ambigAlts, ATNConfigSet configs);\n\n        /// <summary>\n        /// This method is called when an SLL conflict occurs and the parser is about\n        /// to use the full context information to make an LL decision.\n        /// </summary>\n        /// <remarks>\n        /// This method is called when an SLL conflict occurs and the parser is about\n        /// to use the full context information to make an LL decision.\n        /// <p>If one or more configurations in\n        /// <c>configs</c>\n        /// contains a semantic\n        /// predicate, the predicates are evaluated before this method is called. The\n        /// subset of alternatives which are still viable after predicates are\n        /// evaluated is reported in\n        /// <paramref name=\"conflictingAlts\"/>\n        /// .</p>\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"dfa\">the DFA for the current decision</param>\n        /// <param name=\"startIndex\">the input index where the decision started</param>\n        /// <param name=\"stopIndex\">the input index where the SLL conflict occurred</param>\n        /// <param name=\"conflictingAlts\">\n        /// The specific conflicting alternatives. If this is\n        /// <see langword=\"null\"/>\n        /// , the conflicting alternatives are all alternatives\n        /// represented in\n        /// <c>configs</c>\n        /// .\n        /// </param>\n        /// <param name=\"configs\">\n        /// the ATN configuration set where the ambiguity was\n        /// identified\n        /// </param>\n        void ReportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs);\n\n        /// <summary>\n        /// This method is called by the parser when a full-context prediction has a\n        /// unique result.\n        /// </summary>\n        /// <remarks>\n        /// This method is called by the parser when a full-context prediction has a\n        /// unique result.\n        /// <p>Each full-context prediction which does not result in a syntax error\n        /// will call either\n        /// <see cref=\"ReportContextSensitivity(Parser, Antlr4.Runtime.Dfa.DFA, int, int, int, Antlr4.Runtime.Atn.SimulatorState)\"/>\n        /// or\n        /// <see cref=\"ReportAmbiguity(Parser, Antlr4.Runtime.Dfa.DFA, int, int, bool, Antlr4.Runtime.Sharpen.BitSet, Antlr4.Runtime.Atn.ATNConfigSet)\"/>\n        /// .</p>\n        /// <p>For prediction implementations that only evaluate full-context\n        /// predictions when an SLL conflict is found (including the default\n        /// <see cref=\"Antlr4.Runtime.Atn.ParserATNSimulator\"/>\n        /// implementation), this method reports cases\n        /// where SLL conflicts were resolved to unique full-context predictions,\n        /// i.e. the decision was context-sensitive. This report does not necessarily\n        /// indicate a problem, and it may appear even in completely unambiguous\n        /// grammars.</p>\n        /// <p>\n        /// <c>configs</c>\n        /// may have more than one represented alternative if the\n        /// full-context prediction algorithm does not evaluate predicates before\n        /// beginning the full-context prediction. In all cases, the final prediction\n        /// is passed as the\n        /// <paramref name=\"prediction\"/>\n        /// argument.</p>\n        /// <p>Note that the definition of \"context sensitivity\" in this method\n        /// differs from the concept in\n        /// <see cref=\"Antlr4.Runtime.Atn.DecisionInfo.contextSensitivities\"/>\n        /// .\n        /// This method reports all instances where an SLL conflict occurred but LL\n        /// parsing produced a unique result, whether or not that unique result\n        /// matches the minimum alternative in the SLL conflicting set.</p>\n        /// </remarks>\n        /// <param name=\"recognizer\">the parser instance</param>\n        /// <param name=\"dfa\">the DFA for the current decision</param>\n        /// <param name=\"startIndex\">the input index where the decision started</param>\n        /// <param name=\"stopIndex\">\n        /// the input index where the context sensitivity was\n        /// finally determined\n        /// </param>\n        /// <param name=\"prediction\">the unambiguous result of the full-context prediction</param>\n        /// <param name=\"configs\">\n        /// the ATN configuration set where the unambiguous prediction\n        /// was determined\n        /// </param>\n        void ReportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IRecognizer.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime\n{\n    using System;\n    using Antlr4.Runtime.Atn;\n\n    public interface IRecognizer\n    {\n        IVocabulary Vocabulary\n        {\n            get;\n        }\n\n        string[] RuleNames\n        {\n            get;\n        }\n\n        string GrammarFileName\n        {\n            get;\n        }\n\n        ATN Atn\n        {\n            get;\n        }\n\n        int State\n        {\n            get;\n        }\n\n        IIntStream InputStream\n        {\n            get;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IToken.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// A token has properties: text, type, line, character position in the line\n    /// (so we can ignore tabs), token channel, index, and source from which\n    /// we obtained this token.\n    /// </summary>\n    /// <remarks>\n    /// A token has properties: text, type, line, character position in the line\n    /// (so we can ignore tabs), token channel, index, and source from which\n    /// we obtained this token.\n    /// </remarks>\n    public interface IToken\n    {\n        /// <summary>Get the text of the token.</summary>\n        /// <remarks>Get the text of the token.</remarks>\n        string Text\n        {\n            get;\n        }\n\n        /// <summary>Get the token type of the token.</summary>\n        /// <remarks>Get the token type of the token.</remarks>\n        int Type\n        {\n            get;\n        }\n\n        /// <summary>\n        /// The line number on which the 1st character of this token was matched,\n        /// line=1..n\n        /// </summary>\n        int Line\n        {\n            get;\n        }\n\n        /// <summary>\n        /// The index of the first character of this token relative to the\n        /// beginning of the line at which it occurs, 0..n-1\n        /// </summary>\n        int Column\n        {\n            get;\n        }\n\n        /// <summary>Return the channel this token.</summary>\n        /// <remarks>\n        /// Return the channel this token. Each token can arrive at the parser\n        /// on a different channel, but the parser only \"tunes\" to a single channel.\n        /// The parser ignores everything not on DEFAULT_CHANNEL.\n        /// </remarks>\n        int Channel\n        {\n            get;\n        }\n\n        /// <summary>An index from 0..n-1 of the token object in the input stream.</summary>\n        /// <remarks>\n        /// An index from 0..n-1 of the token object in the input stream.\n        /// This must be valid in order to print token streams and\n        /// use TokenRewriteStream.\n        /// Return -1 to indicate that this token was conjured up since\n        /// it doesn't have a valid index.\n        /// </remarks>\n        int TokenIndex\n        {\n            get;\n        }\n\n        /// <summary>\n        /// The starting character index of the token\n        /// This method is optional; return -1 if not implemented.\n        /// </summary>\n        /// <remarks>\n        /// The starting character index of the token\n        /// This method is optional; return -1 if not implemented.\n        /// </remarks>\n        int StartIndex\n        {\n            get;\n        }\n\n        /// <summary>The last character index of the token.</summary>\n        /// <remarks>\n        /// The last character index of the token.\n        /// This method is optional; return -1 if not implemented.\n        /// </remarks>\n        int StopIndex\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Gets the\n        /// <see cref=\"ITokenSource\"/>\n        /// which created this token.\n        /// </summary>\n        ITokenSource TokenSource\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Gets the\n        /// <see cref=\"ICharStream\"/>\n        /// from which this token was derived.\n        /// </summary>\n        ICharStream InputStream\n        {\n            get;\n        }\n    }\n\n    public static class TokenConstants\n    {\n        public const int InvalidType = 0;\n\n        /// <summary>\n        /// During lookahead operations, this \"token\" signifies we hit rule end ATN state\n        /// and did not follow it despite needing to.\n        /// </summary>\n        /// <remarks>\n        /// During lookahead operations, this \"token\" signifies we hit rule end ATN state\n        /// and did not follow it despite needing to.\n        /// </remarks>\n        public const int EPSILON = -2;\n\n        public const int MinUserTokenType = 1;\n\n        public const int EOF = IntStreamConstants.EOF;\n\n        /// <summary>\n        /// All tokens go to the parser (unless skip() is called in that rule)\n        /// on a particular \"channel\".\n        /// </summary>\n        /// <remarks>\n        /// All tokens go to the parser (unless skip() is called in that rule)\n        /// on a particular \"channel\".  The parser tunes to a particular channel\n        /// so that whitespace etc... can go to the parser on a \"hidden\" channel.\n        /// </remarks>\n        public const int DefaultChannel = 0;\n\n        /// <summary>\n        /// Anything on different channel than DEFAULT_CHANNEL is not parsed\n        /// by parser.\n        /// </summary>\n        /// <remarks>\n        /// Anything on different channel than DEFAULT_CHANNEL is not parsed\n        /// by parser.\n        /// </remarks>\n        public const int HiddenChannel = 1;\n\n        /// <summary>\n        /// This is the minimum constant value which can be assigned to a\n        /// user-defined token channel.\n        /// </summary>\n        /// <remarks>\n        /// This is the minimum constant value which can be assigned to a\n        /// user-defined token channel.\n        /// <p>\n        /// The non-negative numbers less than\n        /// <see cref=\"MinUserChannelValue\"/>\n        /// are\n        /// assigned to the predefined channels\n        /// <see cref=\"DefaultChannel\"/>\n        /// and\n        /// <see cref=\"HiddenChannel\"/>\n        /// .</p>\n        /// </remarks>\n        /// <seealso cref=\"IToken.Channel\"/>\n        public const int MinUserChannelValue = 2;\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ITokenFactory.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>The default mechanism for creating tokens.</summary>\n    /// <remarks>\n    /// The default mechanism for creating tokens. It's used by default in Lexer and\n    /// the error handling strategy (to create missing tokens).  Notifying the parser\n    /// of a new factory means that it notifies it's token source and error strategy.\n    /// </remarks>\n    public interface ITokenFactory\n    {\n        /// <summary>\n        /// This is the method used to create tokens in the lexer and in the\n        /// error handling strategy.\n        /// </summary>\n        /// <remarks>\n        /// This is the method used to create tokens in the lexer and in the\n        /// error handling strategy. If text!=null, than the start and stop positions\n        /// are wiped to -1 in the text override is set in the CommonToken.\n        /// </remarks>\n        [return: NotNull]\n        IToken Create(Tuple<ITokenSource, ICharStream> source, int type, string text, int channel, int start, int stop, int line, int charPositionInLine);\n\n        /// <summary>Generically useful</summary>\n        [return: NotNull]\n        IToken Create(int type, string text);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ITokenSource.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// A source of tokens must provide a sequence of tokens via\n    /// <see cref=\"NextToken()\"/>\n    /// and also must reveal it's source of characters;\n    /// <see cref=\"CommonToken\"/>\n    /// 's text is\n    /// computed from a\n    /// <see cref=\"ICharStream\"/>\n    /// ; it only store indices into the char\n    /// stream.\n    /// <p>Errors from the lexer are never passed to the parser. Either you want to keep\n    /// going or you do not upon token recognition error. If you do not want to\n    /// continue lexing then you do not want to continue parsing. Just throw an\n    /// exception not under\n    /// <see cref=\"RecognitionException\"/>\n    /// and Java will naturally toss\n    /// you all the way out of the recognizers. If you want to continue lexing then\n    /// you should not throw an exception to the parser--it has already requested a\n    /// token. Keep lexing until you get a valid one. Just report errors and keep\n    /// going, looking for a valid token.</p>\n    /// </summary>\n    public interface ITokenSource\n    {\n        /// <summary>\n        /// Return a\n        /// <see cref=\"IToken\"/>\n        /// object from your input stream (usually a\n        /// <see cref=\"ICharStream\"/>\n        /// ). Do not fail/return upon lexing error; keep chewing\n        /// on the characters until you get a good one; errors are not passed through\n        /// to the parser.\n        /// </summary>\n        [return: NotNull]\n        IToken NextToken();\n\n        /// <summary>Get the line number for the current position in the input stream.</summary>\n        /// <remarks>\n        /// Get the line number for the current position in the input stream. The\n        /// first line in the input is line 1.\n        /// </remarks>\n        /// <returns>\n        /// The line number for the current position in the input stream, or\n        /// 0 if the current token source does not track line numbers.\n        /// </returns>\n        int Line\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Get the index into the current line for the current position in the input\n        /// stream.\n        /// </summary>\n        /// <remarks>\n        /// Get the index into the current line for the current position in the input\n        /// stream. The first character on a line has position 0.\n        /// </remarks>\n        /// <returns>\n        /// The line number for the current position in the input stream, or\n        /// -1 if the current token source does not track character positions.\n        /// </returns>\n        int Column\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Get the\n        /// <see cref=\"ICharStream\"/>\n        /// from which this token source is currently\n        /// providing tokens.\n        /// </summary>\n        /// <returns>\n        /// The\n        /// <see cref=\"ICharStream\"/>\n        /// associated with the current position in\n        /// the input, or\n        /// <see langword=\"null\"/>\n        /// if no input stream is available for the token\n        /// source.\n        /// </returns>\n        ICharStream InputStream\n        {\n            get;\n        }\n\n        /// <summary>Gets the name of the underlying input source.</summary>\n        /// <remarks>\n        /// Gets the name of the underlying input source. This method returns a\n        /// non-null, non-empty string. If such a name is not known, this method\n        /// returns\n        /// <see cref=\"IntStreamConstants.UnknownSourceName\"/>\n        /// .\n        /// </remarks>\n        string SourceName\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Set the\n        /// <see cref=\"ITokenFactory\"/>\n        /// this token source should use for creating\n        /// <see cref=\"IToken\"/>\n        /// objects from the input.\n        /// </summary>\n        /// <value>\n        /// The\n        /// <see cref=\"ITokenFactory\"/>\n        /// to use for creating tokens.\n        /// </value>\n        /// <summary>\n        /// Gets the\n        /// <see cref=\"ITokenFactory\"/>\n        /// this token source is currently using for\n        /// creating\n        /// <see cref=\"IToken\"/>\n        /// objects from the input.\n        /// </summary>\n        /// <returns>\n        /// The\n        /// <see cref=\"ITokenFactory\"/>\n        /// currently used by this token source.\n        /// </returns>\n        ITokenFactory TokenFactory\n        {\n            get;\n            set;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ITokenStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// An\n    /// <see cref=\"IIntStream\"/>\n    /// whose symbols are\n    /// <see cref=\"IToken\"/>\n    /// instances.\n    /// </summary>\n    public interface ITokenStream : IIntStream\n    {\n        /// <summary>\n        /// Get the\n        /// <see cref=\"IToken\"/>\n        /// instance associated with the value returned by\n        /// <see cref=\"IIntStream.LA(int)\">LA(k)</see>\n        /// . This method has the same pre- and post-conditions as\n        /// <see cref=\"IIntStream.LA(int)\"/>\n        /// . In addition, when the preconditions of this method\n        /// are met, the return value is non-null and the value of\n        /// <c>LT(k).getType()==LA(k)</c>\n        /// .\n        /// </summary>\n        /// <seealso cref=\"IIntStream.LA(int)\"/>\n        [return: NotNull]\n        IToken LT(int k);\n\n        /// <summary>\n        /// Gets the\n        /// <see cref=\"IToken\"/>\n        /// at the specified\n        /// <c>index</c>\n        /// in the stream. When\n        /// the preconditions of this method are met, the return value is non-null.\n        /// <p>The preconditions for this method are the same as the preconditions of\n        /// <see cref=\"IIntStream.Seek(int)\"/>\n        /// . If the behavior of\n        /// <c>seek(index)</c>\n        /// is\n        /// unspecified for the current state and given\n        /// <c>index</c>\n        /// , then the\n        /// behavior of this method is also unspecified.</p>\n        /// <p>The symbol referred to by\n        /// <c>index</c>\n        /// differs from\n        /// <c>seek()</c>\n        /// only\n        /// in the case of filtering streams where\n        /// <c>index</c>\n        /// lies before the end\n        /// of the stream. Unlike\n        /// <c>seek()</c>\n        /// , this method does not adjust\n        /// <c>index</c>\n        /// to point to a non-ignored symbol.</p>\n        /// </summary>\n        /// <exception cref=\"System.ArgumentException\">if {code index} is less than 0</exception>\n        /// <exception cref=\"System.NotSupportedException\">\n        /// if the stream does not support\n        /// retrieving the token at the specified index\n        /// </exception>\n        [return: NotNull]\n        IToken Get(int i);\n\n        /// <summary>\n        /// Gets the underlying\n        /// <see cref=\"ITokenSource\"/>\n        /// which provides tokens for this\n        /// stream.\n        /// </summary>\n        ITokenSource TokenSource\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Return the text of all tokens within the specified\n        /// <paramref name=\"interval\"/>\n        /// . This\n        /// method behaves like the following code (including potential exceptions\n        /// for violating preconditions of\n        /// <see cref=\"Get(int)\"/>\n        /// , but may be optimized by the\n        /// specific implementation.\n        /// <pre>\n        /// TokenStream stream = ...;\n        /// String text = \"\";\n        /// for (int i = interval.a; i &lt;= interval.b; i++) {\n        /// text += stream.get(i).getText();\n        /// }\n        /// </pre>\n        /// </summary>\n        /// <param name=\"interval\">\n        /// The interval of tokens within this stream to get text\n        /// for.\n        /// </param>\n        /// <returns>\n        /// The text of all tokens within the specified interval in this\n        /// stream.\n        /// </returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// if\n        /// <paramref name=\"interval\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        [return: NotNull]\n        string GetText(Interval interval);\n\n        /// <summary>Return the text of all tokens in the stream.</summary>\n        /// <remarks>\n        /// Return the text of all tokens in the stream. This method behaves like the\n        /// following code, including potential exceptions from the calls to\n        /// <see cref=\"IIntStream.Size()\"/>\n        /// and\n        /// <see cref=\"GetText(Antlr4.Runtime.Misc.Interval)\"/>\n        /// , but may be\n        /// optimized by the specific implementation.\n        /// <pre>\n        /// TokenStream stream = ...;\n        /// String text = stream.getText(new Interval(0, stream.size()));\n        /// </pre>\n        /// </remarks>\n        /// <returns>The text of all tokens in the stream.</returns>\n        [return: NotNull]\n        string GetText();\n\n        /// <summary>\n        /// Return the text of all tokens in the source interval of the specified\n        /// context.\n        /// </summary>\n        /// <remarks>\n        /// Return the text of all tokens in the source interval of the specified\n        /// context. This method behaves like the following code, including potential\n        /// exceptions from the call to\n        /// <see cref=\"GetText(Antlr4.Runtime.Misc.Interval)\"/>\n        /// , but may be\n        /// optimized by the specific implementation.\n        /// <p>If\n        /// <c>ctx.getSourceInterval()</c>\n        /// does not return a valid interval of\n        /// tokens provided by this stream, the behavior is unspecified.</p>\n        /// <pre>\n        /// TokenStream stream = ...;\n        /// String text = stream.getText(ctx.getSourceInterval());\n        /// </pre>\n        /// </remarks>\n        /// <param name=\"ctx\">\n        /// The context providing the source interval of tokens to get\n        /// text for.\n        /// </param>\n        /// <returns>\n        /// The text of all tokens within the source interval of\n        /// <paramref name=\"ctx\"/>\n        /// .\n        /// </returns>\n        [return: NotNull]\n        string GetText(RuleContext ctx);\n\n        /// <summary>\n        /// Return the text of all tokens in this stream between\n        /// <paramref name=\"start\"/>\n        /// and\n        /// <paramref name=\"stop\"/>\n        /// (inclusive).\n        /// <p>If the specified\n        /// <paramref name=\"start\"/>\n        /// or\n        /// <paramref name=\"stop\"/>\n        /// token was not provided by\n        /// this stream, or if the\n        /// <paramref name=\"stop\"/>\n        /// occurred before the\n        /// <paramref name=\"start\"/>\n        /// token, the behavior is unspecified.</p>\n        /// <p>For streams which ensure that the\n        /// <see cref=\"IToken.TokenIndex()\"/>\n        /// method is\n        /// accurate for all of its provided tokens, this method behaves like the\n        /// following code. Other streams may implement this method in other ways\n        /// provided the behavior is consistent with this at a high level.</p>\n        /// <pre>\n        /// TokenStream stream = ...;\n        /// String text = \"\";\n        /// for (int i = start.getTokenIndex(); i &lt;= stop.getTokenIndex(); i++) {\n        /// text += stream.get(i).getText();\n        /// }\n        /// </pre>\n        /// </summary>\n        /// <param name=\"start\">The first token in the interval to get text for.</param>\n        /// <param name=\"stop\">The last token in the interval to get text for (inclusive).</param>\n        /// <returns>\n        /// The text of all tokens lying between the specified\n        /// <paramref name=\"start\"/>\n        /// and\n        /// <paramref name=\"stop\"/>\n        /// tokens.\n        /// </returns>\n        /// <exception cref=\"System.NotSupportedException\">\n        /// if this stream does not support\n        /// this method for the specified tokens\n        /// </exception>\n        [return: NotNull]\n        string GetText(IToken start, IToken stop);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IVocabulary.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This interface provides information about the vocabulary used by a\n    /// recognizer.\n    /// </summary>\n    /// <remarks>\n    /// This interface provides information about the vocabulary used by a\n    /// recognizer.\n    /// </remarks>\n    /// <seealso cref=\"Recognizer{Symbol, ATNInterpreter}.Vocabulary()\"/>\n    /// <author>Sam Harwell</author>\n    public interface IVocabulary\n    {\n\n\t\t/// <summary>\n\t\t/// Returns the highest token type value. It can be used to iterate from\n\t\t/// zero to that number, inclusively, thus querying all stored entries.\n\t\t/// </summary>\n\t\tint getMaxTokenType();\n\n\t\t/// <summary>Gets the string literal associated with a token type.</summary>\n\t\t/// <remarks>\n\t\t/// Gets the string literal associated with a token type. The string returned\n\t\t/// by this method, when not\n\t\t/// <see langword=\"null\"/>\n\t\t/// , can be used unaltered in a parser\n\t\t/// grammar to represent this token type.\n\t\t/// <p>The following table shows examples of lexer rules and the literal\n\t\t/// names assigned to the corresponding token types.</p>\n\t\t/// <table>\n\t\t/// <tr>\n\t\t/// <th>Rule</th>\n\t\t/// <th>Literal Name</th>\n\t\t/// <th>Java String Literal</th>\n\t\t/// </tr>\n\t\t/// <tr>\n\t\t/// <td>\n\t\t/// <c>THIS : 'this';</c>\n\t\t/// </td>\n\t\t/// <td>\n\t\t/// <c>'this'</c>\n\t\t/// </td>\n\t\t/// <td>\n\t\t/// <c>\"'this'\"</c>\n\t\t/// </td>\n\t\t/// </tr>\n\t\t/// <tr>\n\t\t/// <td>\n\t\t/// <c>SQUOTE : '\\'';</c>\n\t\t/// </td>\n\t\t/// <td>\n\t\t/// <c>'\\''</c>\n\t\t/// </td>\n\t\t/// <td>\n\t\t/// <c>\"'\\\\''\"</c>\n\t\t/// </td>\n\t\t/// </tr>\n\t\t/// <tr>\n\t\t/// <td>\n\t\t/// <c>ID : [A-Z]+;</c>\n\t\t/// </td>\n\t\t/// <td>n/a</td>\n\t\t/// <td>\n\t\t/// <see langword=\"null\"/>\n\t\t/// </td>\n\t\t/// </tr>\n\t\t/// </table>\n\t\t/// </remarks>\n\t\t/// <param name=\"tokenType\">The token type.</param>\n\t\t/// <returns>\n\t\t/// The string literal associated with the specified token type, or\n\t\t/// <see langword=\"null\"/>\n\t\t/// if no string literal is associated with the type.\n\t\t/// </returns>\n\t\t[return: Nullable]\n        string GetLiteralName(int tokenType);\n\n        /// <summary>Gets the symbolic name associated with a token type.</summary>\n        /// <remarks>\n        /// Gets the symbolic name associated with a token type. The string returned\n        /// by this method, when not\n        /// <see langword=\"null\"/>\n        /// , can be used unaltered in a parser\n        /// grammar to represent this token type.\n        /// <p>This method supports token types defined by any of the following\n        /// methods:</p>\n        /// <ul>\n        /// <li>Tokens created by lexer rules.</li>\n        /// <li>Tokens defined in a\n        /// <c/>\n        /// tokens\n        /// block in a lexer or parser\n        /// grammar.</li>\n        /// <li>The implicitly defined\n        /// <c>EOF</c>\n        /// token, which has the token type\n        /// <see cref=\"TokenConstants.EOF\"/>\n        /// .</li>\n        /// </ul>\n        /// <p>The following table shows examples of lexer rules and the literal\n        /// names assigned to the corresponding token types.</p>\n        /// <table>\n        /// <tr>\n        /// <th>Rule</th>\n        /// <th>Symbolic Name</th>\n        /// </tr>\n        /// <tr>\n        /// <td>\n        /// <c>THIS : 'this';</c>\n        /// </td>\n        /// <td>\n        /// <c>THIS</c>\n        /// </td>\n        /// </tr>\n        /// <tr>\n        /// <td>\n        /// <c>SQUOTE : '\\'';</c>\n        /// </td>\n        /// <td>\n        /// <c>SQUOTE</c>\n        /// </td>\n        /// </tr>\n        /// <tr>\n        /// <td>\n        /// <c>ID : [A-Z]+;</c>\n        /// </td>\n        /// <td>\n        /// <c>ID</c>\n        /// </td>\n        /// </tr>\n        /// </table>\n        /// </remarks>\n        /// <param name=\"tokenType\">The token type.</param>\n        /// <returns>\n        /// The symbolic name associated with the specified token type, or\n        /// <see langword=\"null\"/>\n        /// if no symbolic name is associated with the type.\n        /// </returns>\n        [return: Nullable]\n        string GetSymbolicName(int tokenType);\n\n        /// <summary>Gets the display name of a token type.</summary>\n        /// <remarks>\n        /// Gets the display name of a token type.\n        /// <p>ANTLR provides a default implementation of this method, but\n        /// applications are free to override the behavior in any manner which makes\n        /// sense for the application. The default implementation returns the first\n        /// result from the following list which produces a non-\n        /// <see langword=\"null\"/>\n        /// result.</p>\n        /// <ol>\n        /// <li>The result of\n        /// <see cref=\"GetLiteralName(int)\"/>\n        /// </li>\n        /// <li>The result of\n        /// <see cref=\"GetSymbolicName(int)\"/>\n        /// </li>\n        /// <li>The result of\n        /// <see cref=\"int.ToString()\"/>\n        /// </li>\n        /// </ol>\n        /// </remarks>\n        /// <param name=\"tokenType\">The token type.</param>\n        /// <returns>\n        /// The display name of the token type, for use in error reporting or\n        /// other user-visible messages which reference specific token types.\n        /// </returns>\n        [return: NotNull]\n        string GetDisplayName(int tokenType);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/IWritableToken.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    public interface IWritableToken : IToken\n    {\n        new string Text\n        {\n            set;\n        }\n\n        new int Type\n        {\n            set;\n        }\n\n        new int Line\n        {\n            set;\n        }\n\n        new int Column\n        {\n            set;\n        }\n\n        new int Channel\n        {\n            set;\n        }\n\n        new int TokenIndex\n        {\n            set;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/InputMismatchException.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This signifies any kind of mismatched input exceptions such as\n    /// when the current input does not match the expected token.\n    /// </summary>\n    /// <remarks>\n    /// This signifies any kind of mismatched input exceptions such as\n    /// when the current input does not match the expected token.\n    /// </remarks>\n    [System.Serializable]\n    public class InputMismatchException : RecognitionException\n    {\n        private const long serialVersionUID = 1532568338707443067L;\n\n        public InputMismatchException(Parser recognizer)\n\t\t\t: base(recognizer, ((ITokenStream)recognizer.InputStream), recognizer.RuleContext)\n        {\n            this.OffendingToken = recognizer.CurrentToken;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/InterpreterRuleContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This class extends\n    /// <see cref=\"ParserRuleContext\"/>\n    /// by allowing the value of\n    /// <see cref=\"RuleIndex()\"/>\n    /// to be explicitly set for the context.\n    /// <p>\n    /// <see cref=\"ParserRuleContext\"/>\n    /// does not include field storage for the rule index\n    /// since the context classes created by the code generator override the\n    /// <see cref=\"RuleIndex()\"/>\n    /// method to return the correct value for that context.\n    /// Since the parser interpreter does not use the context classes generated for a\n    /// parser, this class (with slightly more memory overhead per node) is used to\n    /// provide equivalent functionality.</p>\n    /// </summary>\n    public class InterpreterRuleContext : ParserRuleContext\n    {\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"RuleIndex()\"/>\n        /// .\n        /// </summary>\n        private readonly int ruleIndex;\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"InterpreterRuleContext\"/>\n        /// with the specified\n        /// parent, invoking state, and rule index.\n        /// </summary>\n        /// <param name=\"parent\">The parent context.</param>\n        /// <param name=\"invokingStateNumber\">The invoking state number.</param>\n        /// <param name=\"ruleIndex\">The rule index for the current context.</param>\n        public InterpreterRuleContext(ParserRuleContext parent, int invokingStateNumber, int ruleIndex)\n            : base(parent, invokingStateNumber)\n        {\n            this.ruleIndex = ruleIndex;\n        }\n\n        public override int RuleIndex\n        {\n            get\n            {\n                return ruleIndex;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Lexer.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.IO;\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>A lexer is recognizer that draws input symbols from a character stream.</summary>\n    /// <remarks>\n    /// A lexer is recognizer that draws input symbols from a character stream.\n    /// lexer grammars result in a subclass of this object. A Lexer object\n    /// uses simplified match() and error recovery mechanisms in the interest\n    /// of speed.\n    /// </remarks>\n    public abstract class Lexer : Recognizer<int, LexerATNSimulator>, ITokenSource\n    {\n        public const int DEFAULT_MODE = 0;\n\n        public const int DefaultTokenChannel = TokenConstants.DefaultChannel;\n\n        public const int Hidden = TokenConstants.HiddenChannel;\n\n        public const int MinCharValue = 0x0000;\n\n        public const int MaxCharValue = 0x10FFFF;\n\n        private ICharStream _input;\n\n        protected readonly TextWriter Output;\n\n        protected readonly TextWriter ErrorOutput;\n\n\t\tprivate Tuple<ITokenSource, ICharStream> _tokenFactorySourcePair;\n\n        /// <summary>How to create token objects</summary>\n\t\tprivate ITokenFactory _factory = CommonTokenFactory.Default;\n\n        /// <summary>The goal of all lexer rules/methods is to create a token object.</summary>\n        /// <remarks>\n        /// The goal of all lexer rules/methods is to create a token object.\n        /// This is an instance variable as multiple rules may collaborate to\n        /// create a single token.  nextToken will return this object after\n        /// matching lexer rule(s).  If you subclass to allow multiple token\n        /// emissions, then set this to the last token to be matched or\n        /// something nonnull so that the auto token emit mechanism will not\n        /// emit another token.\n        /// </remarks>\n        private IToken _token;\n\n        /// <summary>\n        /// What character index in the stream did the current token start at?\n        /// Needed, for example, to get the text for current token.\n        /// </summary>\n        /// <remarks>\n        /// What character index in the stream did the current token start at?\n        /// Needed, for example, to get the text for current token.  Set at\n        /// the start of nextToken.\n        /// </remarks>\n        private int _tokenStartCharIndex = -1;\n\n        /// <summary>The line on which the first character of the token resides</summary>\n\t\tprivate int _tokenStartLine;\n\n        /// <summary>The character position of first character within the line</summary>\n\t\tprivate int _tokenStartColumn;\n\n        /// <summary>Once we see EOF on char stream, next token will be EOF.</summary>\n        /// <remarks>\n        /// Once we see EOF on char stream, next token will be EOF.\n        /// If you have DONE : EOF ; then you see DONE EOF.\n        /// </remarks>\n\t\tprivate bool _hitEOF;\n\n        /// <summary>The channel number for the current token</summary>\n\t\tprivate int _channel;\n\n        /// <summary>The token type for the current token</summary>\n\t\tprivate int _type;\n\n        private readonly Stack<int> _modeStack = new Stack<int>();\n\n\t\tprivate int _mode = Antlr4.Runtime.Lexer.DEFAULT_MODE;\n\n        /// <summary>\n        /// You can set the text for the current token to override what is in\n        /// the input char buffer.\n        /// </summary>\n        /// <remarks>\n        /// You can set the text for the current token to override what is in\n        /// the input char buffer.  Use setText() or can set this instance var.\n        /// </remarks>\n\t\tprivate string _text;\n\n        public Lexer(ICharStream input) : this(input, Console.Out, Console.Error) { }\n\n        public Lexer(ICharStream input, TextWriter output, TextWriter errorOutput)\n        {\n            this._input = input;\n            this.Output = output;\n            this.ErrorOutput = errorOutput;\n            this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, input);\n        }\n\n        public virtual void Reset()\n        {\n            // wack Lexer state variables\n            if (_input != null)\n            {\n                _input.Seek(0);\n            }\n            // rewind the input\n            _token = null;\n            _type = TokenConstants.InvalidType;\n            _channel = TokenConstants.DefaultChannel;\n            _tokenStartCharIndex = -1;\n            _tokenStartColumn = -1;\n            _tokenStartLine = -1;\n            _text = null;\n            _hitEOF = false;\n            _mode = Antlr4.Runtime.Lexer.DEFAULT_MODE;\n            _modeStack.Clear();\n            Interpreter.Reset();\n        }\n\n        /// <summary>\n        /// Return a token from this source; i.e., match a token on the char\n        /// stream.\n        /// </summary>\n        /// <remarks>\n        /// Return a token from this source; i.e., match a token on the char\n        /// stream.\n        /// </remarks>\n        public virtual IToken NextToken()\n        {\n            if (_input == null)\n            {\n                throw new InvalidOperationException(\"nextToken requires a non-null input stream.\");\n            }\n            // Mark start location in char stream so unbuffered streams are\n            // guaranteed at least have text of current token\n            int tokenStartMarker = _input.Mark();\n            try\n            {\n                while (true)\n                {\n                    if (_hitEOF)\n                    {\n                        EmitEOF();\n                        return _token;\n                    }\n                    _token = null;\n                    _channel = TokenConstants.DefaultChannel;\n                    _tokenStartCharIndex = _input.Index;\n                    _tokenStartColumn = Interpreter.Column;\n                    _tokenStartLine = Interpreter.Line;\n                    _text = null;\n                    do\n                    {\n                        _type = TokenConstants.InvalidType;\n                        //\t\t\t\tSystem.out.println(\"nextToken line \"+tokenStartLine+\" at \"+((char)input.LA(1))+\n                        //\t\t\t\t\t\t\t\t   \" in mode \"+mode+\n                        //\t\t\t\t\t\t\t\t   \" at index \"+input.index());\n                        int ttype;\n                        try\n                        {\n                            ttype = Interpreter.Match(_input, _mode);\n                        }\n                        catch (LexerNoViableAltException e)\n                        {\n                            NotifyListeners(e);\n                            // report error\n                            Recover(e);\n                            ttype = TokenTypes.Skip;\n                        }\n                        if (_input.LA(1) == IntStreamConstants.EOF)\n                        {\n                            _hitEOF = true;\n                        }\n                        if (_type == TokenConstants.InvalidType)\n                        {\n                            _type = ttype;\n                        }\n                        if (_type == TokenTypes.Skip)\n                        {\n                            goto outer_continue;\n                        }\n                    }\n                    while (_type == TokenTypes.More);\n                    if (_token == null)\n                    {\n                        Emit();\n                    }\n                    return _token;\nouter_continue: ;\n                }\n            }\n            finally\n            {\n                // make sure we release marker after match or\n                // unbuffered char stream will keep buffering\n                _input.Release(tokenStartMarker);\n            }\n        }\n\n        /// <summary>\n        /// Instruct the lexer to skip creating a token for current lexer rule\n        /// and look for another token.\n        /// </summary>\n        /// <remarks>\n        /// Instruct the lexer to skip creating a token for current lexer rule\n        /// and look for another token.  nextToken() knows to keep looking when\n        /// a lexer rule finishes with token set to SKIP_TOKEN.  Recall that\n        /// if token==null at end of any token rule, it creates one for you\n        /// and emits it.\n        /// </remarks>\n        public virtual void Skip()\n        {\n            _type = TokenTypes.Skip;\n        }\n\n        public virtual void More()\n        {\n            _type = TokenTypes.More;\n        }\n\n        public virtual void Mode(int m)\n        {\n            _mode = m;\n        }\n\n        public virtual void PushMode(int m)\n        {\n            _modeStack.Push(_mode);\n            Mode(m);\n        }\n\n        public virtual int PopMode()\n        {\n            if (_modeStack.Count == 0)\n            {\n                throw new InvalidOperationException();\n            }\n\n            int mode = _modeStack.Pop();\n            Mode(mode);\n            return _mode;\n        }\n\n        public virtual ITokenFactory TokenFactory\n        {\n            get\n            {\n                return _factory;\n            }\n            set\n            {\n                ITokenFactory factory = value;\n                this._factory = factory;\n            }\n        }\n\n        /// <summary>Set the char stream and reset the lexer</summary>\n        public virtual void SetInputStream(ICharStream input)\n        {\n            this._input = null;\n            this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, _input);\n            Reset();\n            this._input = input;\n            this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, _input);\n        }\n\n        public virtual string SourceName\n        {\n            get\n            {\n                return _input.SourceName;\n            }\n        }\n\n        public override IIntStream InputStream\n        {\n            get\n            {\n                return _input;\n            }\n        }\n\n        ICharStream ITokenSource.InputStream\n        {\n            get\n            {\n\t\t\t\treturn _input;\n            }\n        }\n\n        /// <summary>\n        /// By default does not support multiple emits per nextToken invocation\n        /// for efficiency reasons.\n        /// </summary>\n        /// <remarks>\n        /// By default does not support multiple emits per nextToken invocation\n        /// for efficiency reasons.  Subclass and override this method, nextToken,\n        /// and getToken (to push tokens into a list and pull from that list\n        /// rather than a single variable as this implementation does).\n        /// </remarks>\n        public virtual void Emit(IToken token)\n        {\n            //System.err.println(\"emit \"+token);\n            this._token = token;\n        }\n\n        /// <summary>\n        /// The standard method called to automatically emit a token at the\n        /// outermost lexical rule.\n        /// </summary>\n        /// <remarks>\n        /// The standard method called to automatically emit a token at the\n        /// outermost lexical rule.  The token object should point into the\n        /// char buffer start..stop.  If there is a text override in 'text',\n        /// use that to set the token's text.  Override this method to emit\n        /// custom Token objects or provide a new factory.\n        /// </remarks>\n        public virtual IToken Emit()\n        {\n            IToken t = _factory.Create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, CharIndex - 1, _tokenStartLine, _tokenStartColumn);\n            Emit(t);\n            return t;\n        }\n\n        public virtual IToken EmitEOF()\n        {\n            int cpos = Column;\n\t\t\tint line = Line;\n            IToken eof = _factory.Create(_tokenFactorySourcePair, TokenConstants.EOF, null, TokenConstants.DefaultChannel, _input.Index, _input.Index - 1, line, cpos);\n            Emit(eof);\n            return eof;\n        }\n\n        public virtual int Line\n        {\n            get\n            {\n                return Interpreter.Line;\n            }\n            set\n            {\n                int line = value;\n                Interpreter.Line = line;\n            }\n        }\n\n        public virtual int Column\n        {\n            get\n            {\n                return Interpreter.Column;\n            }\n            set\n            {\n                int charPositionInLine = value;\n                Interpreter.Column = charPositionInLine;\n            }\n        }\n\n        /// <summary>What is the index of the current character of lookahead?</summary>\n        public virtual int CharIndex\n        {\n            get\n            {\n                return _input.Index;\n            }\n        }\n\n\t\tpublic virtual int TokenStartCharIndex\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _tokenStartCharIndex;\n\t\t\t}\n\t\t}\n\n\t\tpublic virtual int TokenStartLine\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _tokenStartLine;\n\t\t\t}\n\t\t}\n\n\t\tpublic virtual int TokenStartColumn\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _tokenStartColumn;\n\t\t\t}\n\t\t}\n\n        /// <summary>\n        /// Return the text matched so far for the current token or any text\n        /// override.\n        /// </summary>\n        /// <remarks>\n        /// Return the text matched so far for the current token or any text\n        /// override.\n        /// </remarks>\n        /// <summary>\n        /// Set the complete text of this token; it wipes any previous changes to the\n        /// text.\n        /// </summary>\n        /// <remarks>\n        /// Set the complete text of this token; it wipes any previous changes to the\n        /// text.\n        /// </remarks>\n        public virtual string Text\n        {\n            get\n            {\n                if (_text != null)\n                {\n                    return _text;\n                }\n                return Interpreter.GetText(_input);\n            }\n            set\n            {\n                string text = value;\n                this._text = text;\n            }\n        }\n\n        /// <summary>Override if emitting multiple tokens.</summary>\n        /// <remarks>Override if emitting multiple tokens.</remarks>\n        public virtual IToken Token\n        {\n            get\n            {\n                return _token;\n            }\n            set\n            {\n                IToken _token = value;\n                this._token = _token;\n            }\n        }\n\n        public virtual int Type\n        {\n            get\n            {\n                return _type;\n            }\n            set\n            {\n                int ttype = value;\n                _type = ttype;\n            }\n        }\n\n        public virtual int Channel\n        {\n            get\n            {\n                return _channel;\n            }\n            set\n            {\n                int channel = value;\n                _channel = channel;\n            }\n        }\n\n        public virtual Stack<int> ModeStack\n        {\n            get\n            {\n                return _modeStack;\n            }\n        }\n\n        public virtual int CurrentMode\n        {\n            get\n            {\n                return _mode;\n            }\n            set\n            {\n                int mode = value;\n                _mode = mode;\n            }\n        }\n\n        public virtual bool HitEOF\n        {\n            get\n            {\n                return _hitEOF;\n            }\n            set\n            {\n                bool hitEOF = value;\n                _hitEOF = hitEOF;\n            }\n        }\n\n        public virtual string[] ChannelNames\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        public virtual string[] ModeNames\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        /// <summary>Return a list of all Token objects in input char stream.</summary>\n        /// <remarks>\n        /// Return a list of all Token objects in input char stream.\n        /// Forces load of all tokens. Does not include EOF token.\n        /// </remarks>\n        public virtual IList<IToken> GetAllTokens()\n        {\n            IList<IToken> tokens = new List<IToken>();\n            IToken t = NextToken();\n            while (t.Type != TokenConstants.EOF)\n            {\n                tokens.Add(t);\n                t = NextToken();\n            }\n            return tokens;\n        }\n\n        public virtual void Recover(LexerNoViableAltException e)\n        {\n            if (_input.LA(1) != IntStreamConstants.EOF)\n            {\n                // skip a char and try again\n                Interpreter.Consume(_input);\n            }\n        }\n\n        public virtual void NotifyListeners(LexerNoViableAltException e)\n        {\n            string text = _input.GetText(Interval.Of(_tokenStartCharIndex, _input.Index));\n            string msg = \"token recognition error at: '\" + GetErrorDisplay(text) + \"'\";\n            IAntlrErrorListener<int> listener = ErrorListenerDispatch;\n            listener.SyntaxError(ErrorOutput, this, 0, _tokenStartLine, _tokenStartColumn, msg, e);\n        }\n\n        public virtual string GetErrorDisplay(string s)\n        {\n            StringBuilder buf = new StringBuilder();\n            for (var i = 0; i < s.Length; ) {\n                var codePoint = Char.ConvertToUtf32(s, i);\n                buf.Append(GetErrorDisplay(codePoint));\n                i += (codePoint > 0xFFFF) ? 2 : 1;\n            }\n            return buf.ToString();\n        }\n\n        public virtual string GetErrorDisplay(int c)\n        {\n            string s;\n            switch (c)\n            {\n                case TokenConstants.EOF:\n                {\n                    s = \"<EOF>\";\n                    break;\n                }\n\n                case '\\n':\n                {\n                    s = \"\\\\n\";\n                    break;\n                }\n\n                case '\\t':\n                {\n                    s = \"\\\\t\";\n                    break;\n                }\n\n                case '\\r':\n                {\n                    s = \"\\\\r\";\n                    break;\n                }\n\n                default:\n                {\n                    s = Char.ConvertFromUtf32(c);\n                    break;\n                }\n            }\n            return s;\n        }\n\n        public virtual string GetCharErrorDisplay(int c)\n        {\n            string s = GetErrorDisplay(c);\n            return \"'\" + s + \"'\";\n        }\n\n        /// <summary>\n        /// Lexers can normally match any char in it's vocabulary after matching\n        /// a token, so do the easy thing and just kill a character and hope\n        /// it all works out.\n        /// </summary>\n        /// <remarks>\n        /// Lexers can normally match any char in it's vocabulary after matching\n        /// a token, so do the easy thing and just kill a character and hope\n        /// it all works out.  You can instead use the rule invocation stack\n        /// to do sophisticated error recovery if you are in a fragment rule.\n        /// </remarks>\n        public virtual void Recover(RecognitionException re)\n        {\n            //System.out.println(\"consuming char \"+(char)input.LA(1)+\" during recovery\");\n            //re.printStackTrace();\n            // TODO: Do we lose character or line position information?\n            _input.Consume();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/LexerInterpreter.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    public class LexerInterpreter: Lexer\n    {\n        private readonly string grammarFileName;\n\n        private readonly ATN atn;\n\n        private readonly string[] ruleNames;\n\n        private readonly string[] channelNames;\n\n        private readonly string[] modeNames;\n\n        [NotNull]\n        private readonly IVocabulary vocabulary;\n\n        protected DFA[] decisionToDFA;\n        protected PredictionContextCache sharedContextCache = new PredictionContextCache();\n\n        [Obsolete(\"Use constructor with channelNames argument\")]\n        public LexerInterpreter(string grammarFileName, IVocabulary vocabulary, IEnumerable<string> ruleNames, IEnumerable<string> modeNames, ATN atn, ICharStream input)\n            : this(grammarFileName, vocabulary, ruleNames, Collections.EmptyList<string>(), modeNames, atn, input)\n        {\n        }\n\n        public LexerInterpreter(string grammarFileName, IVocabulary vocabulary, IEnumerable<string> ruleNames, IEnumerable<string> channelNames, IEnumerable<string> modeNames, ATN atn, ICharStream input)\n            : base(input)\n        {\n            if (atn.grammarType != ATNType.Lexer)\n            {\n                throw new ArgumentException(\"The ATN must be a lexer ATN.\");\n            }\n            this.grammarFileName = grammarFileName;\n            this.atn = atn;\n            this.ruleNames = ruleNames.ToArray();\n            this.channelNames = channelNames.ToArray();\n            this.modeNames = modeNames.ToArray();\n            this.vocabulary = vocabulary;\n            this.decisionToDFA = new DFA[atn.NumberOfDecisions];\n            for (int i = 0; i < decisionToDFA.Length; i++)\n            {\n                decisionToDFA[i] = new DFA(atn.GetDecisionState(i), i);\n            }\n            this.Interpreter = new LexerATNSimulator(this, atn, decisionToDFA, sharedContextCache);\n        }\n\n        public override ATN Atn\n        {\n            get\n            {\n                return atn;\n            }\n        }\n\n        public override string GrammarFileName\n        {\n            get\n            {\n                return grammarFileName;\n            }\n        }\n\n        public override string[] RuleNames\n        {\n            get\n            {\n                return ruleNames;\n            }\n        }\n\n        public override string[] ChannelNames\n        {\n            get\n            {\n                return channelNames;\n            }\n        }\n\n        public override string[] ModeNames\n        {\n            get\n            {\n                return modeNames;\n            }\n        }\n\n        public override IVocabulary Vocabulary\n        {\n            get\n            {\n                return vocabulary;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/LexerNoViableAltException.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Globalization;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    [System.Serializable]\n    public class LexerNoViableAltException : RecognitionException\n    {\n        private const long serialVersionUID = -730999203913001726L;\n\n        /// <summary>Matching attempted at what input index?</summary>\n        private readonly int startIndex;\n\n        /// <summary>Which configurations did we try at input.index() that couldn't match input.LA(1)?</summary>\n        [Nullable]\n        private readonly ATNConfigSet deadEndConfigs;\n\n        public LexerNoViableAltException(Lexer lexer, ICharStream input, int startIndex, ATNConfigSet deadEndConfigs)\n            : base(lexer, input)\n        {\n            this.startIndex = startIndex;\n            this.deadEndConfigs = deadEndConfigs;\n        }\n\n        public virtual int StartIndex\n        {\n            get\n            {\n                return startIndex;\n            }\n        }\n\n        [Nullable]\n        public virtual ATNConfigSet DeadEndConfigs\n        {\n            get\n            {\n                return deadEndConfigs;\n            }\n        }\n\n        public override IIntStream InputStream\n        {\n            get\n            {\n                return (ICharStream)base.InputStream;\n            }\n        }\n\n        public override string ToString()\n        {\n            string symbol = string.Empty;\n            if (startIndex >= 0 && startIndex < ((ICharStream)InputStream).Size)\n            {\n                symbol = ((ICharStream)InputStream).GetText(Interval.Of(startIndex, startIndex));\n                symbol = Utils.EscapeWhitespace(symbol, false);\n            }\n            return string.Format(CultureInfo.CurrentCulture, \"{0}('{1}')\", typeof(Antlr4.Runtime.LexerNoViableAltException).Name, symbol);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ListTokenSource.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// Provides an implementation of\n    /// <see cref=\"ITokenSource\"/>\n    /// as a wrapper around a list\n    /// of\n    /// <see cref=\"IToken\"/>\n    /// objects.\n    /// <p>If the final token in the list is an\n    /// <see cref=\"TokenConstants.EOF\"/>\n    /// token, it will be used\n    /// as the EOF token for every call to\n    /// <see cref=\"NextToken()\"/>\n    /// after the end of the\n    /// list is reached. Otherwise, an EOF token will be created.</p>\n    /// </summary>\n    public class ListTokenSource : ITokenSource\n    {\n        /// <summary>\n        /// The wrapped collection of\n        /// <see cref=\"IToken\"/>\n        /// objects to return.\n        /// </summary>\n        protected internal readonly IList<IToken> tokens;\n\n        /// <summary>The name of the input source.</summary>\n        /// <remarks>\n        /// The name of the input source. If this value is\n        /// <see langword=\"null\"/>\n        /// , a call to\n        /// <see cref=\"SourceName()\"/>\n        /// should return the source name used to create the\n        /// the next token in\n        /// <see cref=\"tokens\"/>\n        /// (or the previous token if the end of\n        /// the input has been reached).\n        /// </remarks>\n        private readonly string sourceName;\n\n        /// <summary>\n        /// The index into\n        /// <see cref=\"tokens\"/>\n        /// of token to return by the next call to\n        /// <see cref=\"NextToken()\"/>\n        /// . The end of the input is indicated by this value\n        /// being greater than or equal to the number of items in\n        /// <see cref=\"tokens\"/>\n        /// .\n        /// </summary>\n        protected internal int i;\n\n        /// <summary>This field caches the EOF token for the token source.</summary>\n        /// <remarks>This field caches the EOF token for the token source.</remarks>\n        protected internal IToken eofToken;\n\n        /// <summary>\n        /// This is the backing field for the <see cref=\"TokenFactory\"/> property.\n        /// </summary>\n        private ITokenFactory _factory = CommonTokenFactory.Default;\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"ListTokenSource\"/>\n        /// instance from the specified\n        /// collection of\n        /// <see cref=\"IToken\"/>\n        /// objects.\n        /// </summary>\n        /// <param name=\"tokens\">\n        /// The collection of\n        /// <see cref=\"IToken\"/>\n        /// objects to provide as a\n        /// <see cref=\"ITokenSource\"/>\n        /// .\n        /// </param>\n        /// <exception>\n        /// NullPointerException\n        /// if\n        /// <paramref name=\"tokens\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        public ListTokenSource(IList<IToken> tokens)\n            : this(tokens, null)\n        {\n        }\n\n        /// <summary>\n        /// Constructs a new\n        /// <see cref=\"ListTokenSource\"/>\n        /// instance from the specified\n        /// collection of\n        /// <see cref=\"IToken\"/>\n        /// objects and source name.\n        /// </summary>\n        /// <param name=\"tokens\">\n        /// The collection of\n        /// <see cref=\"IToken\"/>\n        /// objects to provide as a\n        /// <see cref=\"ITokenSource\"/>\n        /// .\n        /// </param>\n        /// <param name=\"sourceName\">\n        /// The name of the\n        /// <see cref=\"ITokenSource\"/>\n        /// . If this value is\n        /// <see langword=\"null\"/>\n        /// ,\n        /// <see cref=\"SourceName()\"/>\n        /// will attempt to infer the name from\n        /// the next\n        /// <see cref=\"IToken\"/>\n        /// (or the previous token if the end of the input has\n        /// been reached).\n        /// </param>\n        /// <exception>\n        /// NullPointerException\n        /// if\n        /// <paramref name=\"tokens\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        public ListTokenSource(IList<IToken> tokens, string sourceName)\n        {\n            if (tokens == null)\n            {\n                throw new ArgumentNullException(\"tokens cannot be null\");\n            }\n            this.tokens = tokens;\n            this.sourceName = sourceName;\n        }\n\n        /// <summary><inheritDoc/></summary>\n        public virtual int Column\n        {\n            get\n            {\n                if (i < tokens.Count)\n                {\n                    return tokens[i].Column;\n                }\n                else\n                {\n                    if (eofToken != null)\n                    {\n                        return eofToken.Column;\n                    }\n                    else\n                    {\n                        if (tokens.Count > 0)\n                        {\n                            // have to calculate the result from the line/column of the previous\n                            // token, along with the text of the token.\n                            IToken lastToken = tokens[tokens.Count - 1];\n                            string tokenText = lastToken.Text;\n                            if (tokenText != null)\n                            {\n                                int lastNewLine = tokenText.LastIndexOf('\\n');\n                                if (lastNewLine >= 0)\n                                {\n                                    return tokenText.Length - lastNewLine - 1;\n                                }\n                            }\n                            return lastToken.Column + lastToken.StopIndex - lastToken.StartIndex + 1;\n                        }\n                    }\n                }\n                // only reach this if tokens is empty, meaning EOF occurs at the first\n                // position in the input\n                return 0;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        public virtual IToken NextToken()\n        {\n            if (i >= tokens.Count)\n            {\n                if (eofToken == null)\n                {\n                    int start = -1;\n                    if (tokens.Count > 0)\n                    {\n                        int previousStop = tokens[tokens.Count - 1].StopIndex;\n                        if (previousStop != -1)\n                        {\n                            start = previousStop + 1;\n                        }\n                    }\n                    int stop = Math.Max(-1, start - 1);\n                    eofToken = _factory.Create(Tuple.Create((ITokenSource)this, InputStream), TokenConstants.EOF, \"EOF\", TokenConstants.DefaultChannel, start, stop, Line, Column);\n                }\n                return eofToken;\n            }\n            IToken t = tokens[i];\n            if (i == tokens.Count - 1 && t.Type == TokenConstants.EOF)\n            {\n                eofToken = t;\n            }\n            i++;\n            return t;\n        }\n\n        /// <summary><inheritDoc/></summary>\n        public virtual int Line\n        {\n            get\n            {\n                if (i < tokens.Count)\n                {\n                    return tokens[i].Line;\n                }\n                else\n                {\n                    if (eofToken != null)\n                    {\n                        return eofToken.Line;\n                    }\n                    else\n                    {\n                        if (tokens.Count > 0)\n                        {\n                            // have to calculate the result from the line/column of the previous\n                            // token, along with the text of the token.\n                            IToken lastToken = tokens[tokens.Count - 1];\n                            int line = lastToken.Line;\n                            string tokenText = lastToken.Text;\n                            if (tokenText != null)\n                            {\n                                for (int j = 0; j < tokenText.Length; j++)\n                                {\n                                    if (tokenText[j] == '\\n')\n                                    {\n                                        line++;\n                                    }\n                                }\n                            }\n                            // if no text is available, assume the token did not contain any newline characters.\n                            return line;\n                        }\n                    }\n                }\n                // only reach this if tokens is empty, meaning EOF occurs at the first\n                // position in the input\n                return 1;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        public virtual ICharStream InputStream\n        {\n            get\n            {\n                if (i < tokens.Count)\n                {\n                    return tokens[i].InputStream;\n                }\n                else\n                {\n                    if (eofToken != null)\n                    {\n                        return eofToken.InputStream;\n                    }\n                    else\n                    {\n                        if (tokens.Count > 0)\n                        {\n                            return tokens[tokens.Count - 1].InputStream;\n                        }\n                    }\n                }\n                // no input stream information is available\n                return null;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        public virtual string SourceName\n        {\n            get\n            {\n                if (sourceName != null)\n                {\n                    return sourceName;\n                }\n                ICharStream inputStream = InputStream;\n                if (inputStream != null)\n                {\n                    return inputStream.SourceName;\n                }\n                return \"List\";\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        /// <summary><inheritDoc/></summary>\n        public virtual ITokenFactory TokenFactory\n        {\n            get\n            {\n                return _factory;\n            }\n            set\n            {\n                ITokenFactory factory = value;\n                this._factory = factory;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/Args.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\n\nnamespace Antlr4.Runtime.Misc\n{\n    /// <author>Sam Harwell</author>\n    public static class Args\n    {\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// if\n        /// <paramref name=\"value\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// .\n        /// </exception>\n        public static void NotNull(string parameterName, object value)\n        {\n            if (value == null)\n            {\n                throw new ArgumentNullException(parameterName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/ArrayList.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nusing System.Collections.Generic;\n\nnamespace Antlr4.Runtime.Misc\n{\n\tpublic class ArrayList<T> : List<T>\n\t{\n\n\t\tpublic ArrayList()\n\t\t{\n\t\t}\n\n\t\tpublic ArrayList(int count)\n\t\t\t: base(count)\n\t\t{\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\tint hash = MurmurHash.Initialize(1);\n\t\t\tforeach (T t in this)\n\t\t\t\thash = MurmurHash.Update(hash, t.GetHashCode());\n\t\t\thash = MurmurHash.Finish(hash, this.Count);\n\t\t\treturn hash;\n\t\t}\n\n\t\tpublic override bool Equals(object o)\n\t\t{\n\t\t\treturn o == this\n\t\t\t\t|| (o is List<T> && this.Equals((List<T>)o));\n\t\t}\n\n\n\t\tpublic bool Equals(List<T> o)\n\t\t{\n\t\t\tif (this.Count != o.Count)\n\t\t\t\treturn false;\n\t\t\tIEnumerator<T> thisItems = this.GetEnumerator();\n\t\t\tIEnumerator<T> otherItems = o.GetEnumerator();\n\t\t\twhile (thisItems.MoveNext() && otherItems.MoveNext())\n\t\t\t{\n\t\t\t\tif (!thisItems.Current.Equals(otherItems.Current))\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/IIntSet.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\n\nnamespace Antlr4.Runtime.Misc\n{\n    /// <summary>A generic set of integers.</summary>\n    /// <remarks>A generic set of integers.</remarks>\n    /// <seealso cref=\"IntervalSet\"/>\n    public interface IIntSet\n    {\n        /// <summary>Adds the specified value to the current set.</summary>\n        /// <remarks>Adds the specified value to the current set.</remarks>\n        /// <param name=\"el\">the value to add</param>\n        /// <exception>\n        /// IllegalStateException\n        /// if the current set is read-only\n        /// </exception>\n        void Add(int el);\n\n        /// <summary>\n        /// Modify the current\n        /// <see cref=\"IIntSet\"/>\n        /// object to contain all elements that are\n        /// present in itself, the specified\n        /// <paramref name=\"set\"/>\n        /// , or both.\n        /// </summary>\n        /// <param name=\"set\">\n        /// The set to add to the current set. A\n        /// <see langword=\"null\"/>\n        /// argument is\n        /// treated as though it were an empty set.\n        /// </param>\n        /// <returns>\n        ///\n        /// <c>this</c>\n        /// (to support chained calls)\n        /// </returns>\n        /// <exception>\n        /// IllegalStateException\n        /// if the current set is read-only\n        /// </exception>\n        [return: NotNull]\n        IIntSet AddAll(IIntSet set);\n\n        /// <summary>\n        /// Return a new\n        /// <see cref=\"IIntSet\"/>\n        /// object containing all elements that are\n        /// present in both the current set and the specified set\n        /// <paramref name=\"a\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"a\">\n        /// The set to intersect with the current set. A\n        /// <see langword=\"null\"/>\n        /// argument is treated as though it were an empty set.\n        /// </param>\n        /// <returns>\n        /// A new\n        /// <see cref=\"IIntSet\"/>\n        /// instance containing the intersection of the\n        /// current set and\n        /// <paramref name=\"a\"/>\n        /// . The value\n        /// <see langword=\"null\"/>\n        /// may be returned in\n        /// place of an empty result set.\n        /// </returns>\n        [return: Nullable]\n        IIntSet And(IIntSet a);\n\n        /// <summary>\n        /// Return a new\n        /// <see cref=\"IIntSet\"/>\n        /// object containing all elements that are\n        /// present in\n        /// <paramref name=\"elements\"/>\n        /// but not present in the current set. The\n        /// following expressions are equivalent for input non-null\n        /// <see cref=\"IIntSet\"/>\n        /// instances\n        /// <c>x</c>\n        /// and\n        /// <c>y</c>\n        /// .\n        /// <ul>\n        /// <li>\n        /// <c>x.complement(y)</c>\n        /// </li>\n        /// <li>\n        /// <c>y.subtract(x)</c>\n        /// </li>\n        /// </ul>\n        /// </summary>\n        /// <param name=\"elements\">\n        /// The set to compare with the current set. A\n        /// <see langword=\"null\"/>\n        /// argument is treated as though it were an empty set.\n        /// </param>\n        /// <returns>\n        /// A new\n        /// <see cref=\"IIntSet\"/>\n        /// instance containing the elements present in\n        /// <paramref name=\"elements\"/>\n        /// but not present in the current set. The value\n        /// <see langword=\"null\"/>\n        /// may be returned in place of an empty result set.\n        /// </returns>\n        [return: Nullable]\n        IIntSet Complement(IIntSet elements);\n\n        /// <summary>\n        /// Return a new\n        /// <see cref=\"IIntSet\"/>\n        /// object containing all elements that are\n        /// present in the current set, the specified set\n        /// <paramref name=\"a\"/>\n        /// , or both.\n        /// <p>\n        /// This method is similar to\n        /// <see cref=\"AddAll(IIntSet)\"/>\n        /// , but returns a new\n        /// <see cref=\"IIntSet\"/>\n        /// instance instead of modifying the current set.</p>\n        /// </summary>\n        /// <param name=\"a\">\n        /// The set to union with the current set. A\n        /// <see langword=\"null\"/>\n        /// argument\n        /// is treated as though it were an empty set.\n        /// </param>\n        /// <returns>\n        /// A new\n        /// <see cref=\"IIntSet\"/>\n        /// instance containing the union of the current\n        /// set and\n        /// <paramref name=\"a\"/>\n        /// . The value\n        /// <see langword=\"null\"/>\n        /// may be returned in place of an\n        /// empty result set.\n        /// </returns>\n        [return: Nullable]\n        IIntSet Or(IIntSet a);\n\n        /// <summary>\n        /// Return a new\n        /// <see cref=\"IIntSet\"/>\n        /// object containing all elements that are\n        /// present in the current set but not present in the input set\n        /// <paramref name=\"a\"/>\n        /// .\n        /// The following expressions are equivalent for input non-null\n        /// <see cref=\"IIntSet\"/>\n        /// instances\n        /// <c>x</c>\n        /// and\n        /// <c>y</c>\n        /// .\n        /// <ul>\n        /// <li>\n        /// <c>y.subtract(x)</c>\n        /// </li>\n        /// <li>\n        /// <c>x.complement(y)</c>\n        /// </li>\n        /// </ul>\n        /// </summary>\n        /// <param name=\"a\">\n        /// The set to compare with the current set. A\n        /// <see langword=\"null\"/>\n        /// argument is treated as though it were an empty set.\n        /// </param>\n        /// <returns>\n        /// A new\n        /// <see cref=\"IIntSet\"/>\n        /// instance containing the elements present in\n        /// <c>elements</c>\n        /// but not present in the current set. The value\n        /// <see langword=\"null\"/>\n        /// may be returned in place of an empty result set.\n        /// </returns>\n        [return: Nullable]\n        IIntSet Subtract(IIntSet a);\n\n        /// <summary>Return the total number of elements represented by the current set.</summary>\n        /// <remarks>Return the total number of elements represented by the current set.</remarks>\n        /// <returns>\n        /// the total number of elements represented by the current set,\n        /// regardless of the manner in which the elements are stored.\n        /// </returns>\n        int Count\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Returns\n        /// <see langword=\"true\"/>\n        /// if this set contains no elements.\n        /// </summary>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if the current set contains no elements; otherwise,\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        bool IsNil\n        {\n            get;\n        }\n\n        /// <summary><inheritDoc/></summary>\n        bool Equals(object obj);\n\n        /// <summary>\n        /// Returns the single value contained in the set, if\n        /// <see cref=\"Count()\"/>\n        /// is 1;\n        /// otherwise, returns\n        /// <see cref=\"TokenConstants.InvalidType\"/>\n        /// .\n        /// </summary>\n        /// <returns>\n        /// the single value contained in the set, if\n        /// <see cref=\"Count()\"/>\n        /// is 1;\n        /// otherwise, returns\n        /// <see cref=\"TokenConstants.InvalidType\"/>\n        /// .\n        /// </returns>\n        int SingleElement\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Returns\n        /// <see langword=\"true\"/>\n        /// if the set contains the specified element.\n        /// </summary>\n        /// <param name=\"el\">The element to check for.</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if the set contains\n        /// <paramref name=\"el\"/>\n        /// ; otherwise\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        bool Contains(int el);\n\n        /// <summary>Removes the specified value from the current set.</summary>\n        /// <remarks>\n        /// Removes the specified value from the current set. If the current set does\n        /// not contain the element, no changes are made.\n        /// </remarks>\n        /// <param name=\"el\">the value to remove</param>\n        /// <exception>\n        /// IllegalStateException\n        /// if the current set is read-only\n        /// </exception>\n        void Remove(int el);\n\n        /// <summary>Return a list containing the elements represented by the current set.</summary>\n        /// <remarks>\n        /// Return a list containing the elements represented by the current set. The\n        /// list is returned in ascending numerical order.\n        /// </remarks>\n        /// <returns>\n        /// A list containing all element present in the current set, sorted\n        /// in ascending numerical order.\n        /// </returns>\n        [return: NotNull]\n        IList<int> ToList();\n\n        /// <summary><inheritDoc/></summary>\n        string ToString();\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/Interval.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\n\nnamespace Antlr4.Runtime.Misc\n{\n    /// <summary>An immutable inclusive interval a..b.</summary>\n    /// <remarks>An immutable inclusive interval a..b.</remarks>\n    public struct Interval\n    {\n        public static readonly Antlr4.Runtime.Misc.Interval Invalid = new Antlr4.Runtime.Misc.Interval(-1, -2);\n\n        /// <summary>The start of the interval.</summary>\n        /// <remarks>The start of the interval.</remarks>\n        public readonly int a;\n\n        /// <summary>The end of the interval (inclusive).</summary>\n        /// <remarks>The end of the interval (inclusive).</remarks>\n        public readonly int b;\n\n        public Interval(int a, int b)\n        {\n            this.a = a;\n            this.b = b;\n        }\n\n        /// <summary>\n        /// Interval objects are used readonly so share all with the\n        /// same single value a==b up to some max size.\n        /// </summary>\n        /// <remarks>\n        /// Interval objects are used readonly so share all with the\n        /// same single value a==b up to some max size.  Use an array as a perfect hash.\n        /// Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new\n        /// Interval object with a..a in it.  On Java.g4, 218623 IntervalSets\n        /// have a..a (set with 1 element).\n        /// </remarks>\n        public static Antlr4.Runtime.Misc.Interval Of(int a, int b)\n        {\n            return new Antlr4.Runtime.Misc.Interval(a, b);\n        }\n\n        /// <summary>return number of elements between a and b inclusively.</summary>\n        /// <remarks>\n        /// return number of elements between a and b inclusively. x..x is length 1.\n        /// if b &lt; a, then length is 0. 9..10 has length 2.\n        /// </remarks>\n        public int Length\n        {\n            get\n            {\n                if (b < a)\n                {\n                    return 0;\n                }\n                return b - a + 1;\n            }\n        }\n\n        public override bool Equals(object o)\n        {\n            if (!(o is Antlr4.Runtime.Misc.Interval))\n            {\n                return false;\n            }\n\n            Antlr4.Runtime.Misc.Interval other = (Antlr4.Runtime.Misc.Interval)o;\n            return this.a == other.a && this.b == other.b;\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = 23;\n            hash = hash * 31 + a;\n            hash = hash * 31 + b;\n            return hash;\n        }\n\n        /// <summary>Does this start completely before other? Disjoint</summary>\n        public bool StartsBeforeDisjoint(Antlr4.Runtime.Misc.Interval other)\n        {\n            return this.a < other.a && this.b < other.a;\n        }\n\n        /// <summary>Does this start at or before other? Nondisjoint</summary>\n        public bool StartsBeforeNonDisjoint(Antlr4.Runtime.Misc.Interval other)\n        {\n            return this.a <= other.a && this.b >= other.a;\n        }\n\n        /// <summary>Does this.a start after other.b? May or may not be disjoint</summary>\n        public bool StartsAfter(Antlr4.Runtime.Misc.Interval other)\n        {\n            return this.a > other.a;\n        }\n\n        /// <summary>Does this start completely after other? Disjoint</summary>\n        public bool StartsAfterDisjoint(Antlr4.Runtime.Misc.Interval other)\n        {\n            return this.a > other.b;\n        }\n\n        /// <summary>Does this start after other? NonDisjoint</summary>\n        public bool StartsAfterNonDisjoint(Antlr4.Runtime.Misc.Interval other)\n        {\n            return this.a > other.a && this.a <= other.b;\n        }\n\n        // this.b>=other.b implied\n        /// <summary>Are both ranges disjoint? I.e., no overlap?</summary>\n        public bool Disjoint(Antlr4.Runtime.Misc.Interval other)\n        {\n            return StartsBeforeDisjoint(other) || StartsAfterDisjoint(other);\n        }\n\n        /// <summary>Are two intervals adjacent such as 0..41 and 42..42?</summary>\n        public bool Adjacent(Antlr4.Runtime.Misc.Interval other)\n        {\n            return this.a == other.b + 1 || this.b == other.a - 1;\n        }\n\n        public bool ProperlyContains(Antlr4.Runtime.Misc.Interval other)\n        {\n            return other.a >= this.a && other.b <= this.b;\n        }\n\n        /// <summary>Return the interval computed from combining this and other</summary>\n        public Antlr4.Runtime.Misc.Interval Union(Antlr4.Runtime.Misc.Interval other)\n        {\n            return Antlr4.Runtime.Misc.Interval.Of(Math.Min(a, other.a), Math.Max(b, other.b));\n        }\n\n        /// <summary>Return the interval in common between this and o</summary>\n        public Antlr4.Runtime.Misc.Interval Intersection(Antlr4.Runtime.Misc.Interval other)\n        {\n            return Antlr4.Runtime.Misc.Interval.Of(Math.Max(a, other.a), Math.Min(b, other.b));\n        }\n\n        /// <summary>\n        /// Return the interval with elements from\n        /// <c>this</c>\n        /// not in\n        /// <paramref name=\"other\"/>\n        /// ;\n        /// <paramref name=\"other\"/>\n        /// must not be totally enclosed (properly contained)\n        /// within\n        /// <c>this</c>\n        /// , which would result in two disjoint intervals\n        /// instead of the single one returned by this method.\n        /// </summary>\n        public Antlr4.Runtime.Misc.Interval? DifferenceNotProperlyContained(Antlr4.Runtime.Misc.Interval other)\n        {\n            Antlr4.Runtime.Misc.Interval? diff = null;\n            // other.a to left of this.a (or same)\n            if (other.StartsBeforeNonDisjoint(this))\n            {\n                diff = Antlr4.Runtime.Misc.Interval.Of(Math.Max(this.a, other.b + 1), this.b);\n            }\n            else\n            {\n                // other.a to right of this.a\n                if (other.StartsAfterNonDisjoint(this))\n                {\n                    diff = Antlr4.Runtime.Misc.Interval.Of(this.a, other.a - 1);\n                }\n            }\n            return diff;\n        }\n\n        public override string ToString()\n        {\n            return a + \"..\" + b;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/IntervalSet.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Antlr4.Runtime.Misc\n{\n    /// <summary>\n    /// This class implements the\n    /// <see cref=\"IIntSet\"/>\n    /// backed by a sorted array of\n    /// non-overlapping intervals. It is particularly efficient for representing\n    /// large collections of numbers, where the majority of elements appear as part\n    /// of a sequential range of numbers that are all part of the set. For example,\n    /// the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }.\n    /// <p>\n    /// This class is able to represent sets containing any combination of values in\n    /// the range\n    /// <see cref=\"int.MinValue\"/>\n    /// to\n    /// <see cref=\"int.MaxValue\"/>\n    /// (inclusive).</p>\n    /// </summary>\n    public class IntervalSet : IIntSet\n    {\n        public static readonly Antlr4.Runtime.Misc.IntervalSet CompleteCharSet = Antlr4.Runtime.Misc.IntervalSet.Of(Lexer.MinCharValue, Lexer.MaxCharValue);\n\n        public static readonly Antlr4.Runtime.Misc.IntervalSet EmptySet = new Antlr4.Runtime.Misc.IntervalSet();\n\n        static IntervalSet()\n        {\n            CompleteCharSet.SetReadonly(true);\n            EmptySet.SetReadonly(true);\n        }\n\n        /// <summary>The list of sorted, disjoint intervals.</summary>\n        /// <remarks>The list of sorted, disjoint intervals.</remarks>\n        protected internal IList<Interval> intervals;\n\n        protected internal bool @readonly;\n\n        public IntervalSet(IList<Interval> intervals)\n        {\n            this.intervals = intervals;\n        }\n\n        public IntervalSet(Antlr4.Runtime.Misc.IntervalSet set)\n            : this()\n        {\n            AddAll(set);\n        }\n\n        public IntervalSet(params int[] els)\n        {\n            if (els == null)\n            {\n                intervals = new ArrayList<Interval>(2);\n            }\n            else\n            {\n                // most sets are 1 or 2 elements\n                intervals = new ArrayList<Interval>(els.Length);\n                foreach (int e in els)\n                {\n                    Add(e);\n                }\n            }\n        }\n\n        /// <summary>Create a set with a single element, el.</summary>\n        /// <remarks>Create a set with a single element, el.</remarks>\n        [return: NotNull]\n        public static Antlr4.Runtime.Misc.IntervalSet Of(int a)\n        {\n            Antlr4.Runtime.Misc.IntervalSet s = new Antlr4.Runtime.Misc.IntervalSet();\n            s.Add(a);\n            return s;\n        }\n\n        /// <summary>Create a set with all ints within range [a..b] (inclusive)</summary>\n        public static Antlr4.Runtime.Misc.IntervalSet Of(int a, int b)\n        {\n            Antlr4.Runtime.Misc.IntervalSet s = new Antlr4.Runtime.Misc.IntervalSet();\n            s.Add(a, b);\n            return s;\n        }\n\n        public virtual void Clear()\n        {\n            if (@readonly)\n            {\n                throw new InvalidOperationException(\"can't alter readonly IntervalSet\");\n            }\n            intervals.Clear();\n        }\n\n        /// <summary>Add a single element to the set.</summary>\n        /// <remarks>\n        /// Add a single element to the set.  An isolated element is stored\n        /// as a range el..el.\n        /// </remarks>\n        public virtual void Add(int el)\n        {\n            if (@readonly)\n            {\n                throw new InvalidOperationException(\"can't alter readonly IntervalSet\");\n            }\n            Add(el, el);\n        }\n\n        /// <summary>Add interval; i.e., add all integers from a to b to set.</summary>\n        /// <remarks>\n        /// Add interval; i.e., add all integers from a to b to set.\n        /// If b&lt;a, do nothing.\n        /// Keep list in sorted order (by left range value).\n        /// If overlap, combine ranges.  For example,\n        /// If this is {1..5, 10..20}, adding 6..7 yields\n        /// {1..5, 6..7, 10..20}.  Adding 4..8 yields {1..8, 10..20}.\n        /// </remarks>\n        public virtual void Add(int a, int b)\n        {\n            Add(Interval.Of(a, b));\n        }\n\n        // copy on write so we can cache a..a intervals and sets of that\n        protected internal virtual void Add(Interval addition)\n        {\n            if (@readonly)\n            {\n                throw new InvalidOperationException(\"can't alter readonly IntervalSet\");\n            }\n            //System.out.println(\"add \"+addition+\" to \"+intervals.toString());\n            if (addition.b < addition.a)\n            {\n                return;\n            }\n            // find position in list\n            // Use iterators as we modify list in place\n            for (int i = 0; i < intervals.Count; i++)\n            {\n                Interval r = intervals[i];\n                if (addition.Equals(r))\n                {\n                    return;\n                }\n                if (addition.Adjacent(r) || !addition.Disjoint(r))\n                {\n                    // next to each other, make a single larger interval\n                    Interval bigger = addition.Union(r);\n                    intervals[i] = bigger;\n                    // make sure we didn't just create an interval that\n                    // should be merged with next interval in list\n                    while (i < intervals.Count - 1)\n                    {\n                        i++;\n                        Interval next = intervals[i];\n                        if (!bigger.Adjacent(next) && bigger.Disjoint(next))\n                        {\n                            break;\n                        }\n                        // if we bump up against or overlap next, merge\n                        intervals.RemoveAt(i);\n                        // remove this one\n                        i--;\n                        // move backwards to what we just set\n                        intervals[i] = bigger.Union(next);\n                        // set to 3 merged ones\n                    }\n                    // first call to next after previous duplicates the result\n                    return;\n                }\n                if (addition.StartsBeforeDisjoint(r))\n                {\n                    // insert before r\n                    intervals.Insert(i, addition);\n                    return;\n                }\n            }\n            // if disjoint and after r, a future iteration will handle it\n            // ok, must be after last interval (and disjoint from last interval)\n            // just add it\n            intervals.Add(addition);\n        }\n\n        /// <summary>combine all sets in the array returned the or'd value</summary>\n        public static Antlr4.Runtime.Misc.IntervalSet Or(Antlr4.Runtime.Misc.IntervalSet[] sets)\n        {\n            Antlr4.Runtime.Misc.IntervalSet r = new Antlr4.Runtime.Misc.IntervalSet();\n            foreach (Antlr4.Runtime.Misc.IntervalSet s in sets)\n            {\n                r.AddAll(s);\n            }\n            return r;\n        }\n\n        public virtual Antlr4.Runtime.Misc.IntervalSet AddAll(IIntSet set)\n        {\n            if (set == null)\n            {\n                return this;\n            }\n            if (set is Antlr4.Runtime.Misc.IntervalSet)\n            {\n                Antlr4.Runtime.Misc.IntervalSet other = (Antlr4.Runtime.Misc.IntervalSet)set;\n                // walk set and add each interval\n                int n = other.intervals.Count;\n                for (int i = 0; i < n; i++)\n                {\n                    Interval I = other.intervals[i];\n                    this.Add(I.a, I.b);\n                }\n            }\n            else\n            {\n                foreach (int value in set.ToList())\n                {\n                    Add(value);\n                }\n            }\n            return this;\n        }\n\n        public virtual Antlr4.Runtime.Misc.IntervalSet Complement(int minElement, int maxElement)\n        {\n            return this.Complement(Antlr4.Runtime.Misc.IntervalSet.Of(minElement, maxElement));\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        ///\n        /// </summary>\n        public virtual Antlr4.Runtime.Misc.IntervalSet Complement(IIntSet vocabulary)\n        {\n            if (vocabulary == null || vocabulary.IsNil)\n            {\n                return null;\n            }\n            // nothing in common with null set\n            Antlr4.Runtime.Misc.IntervalSet vocabularyIS;\n            if (vocabulary is Antlr4.Runtime.Misc.IntervalSet)\n            {\n                vocabularyIS = (Antlr4.Runtime.Misc.IntervalSet)vocabulary;\n            }\n            else\n            {\n                vocabularyIS = new Antlr4.Runtime.Misc.IntervalSet();\n                vocabularyIS.AddAll(vocabulary);\n            }\n            return vocabularyIS.Subtract(this);\n        }\n\n        public virtual Antlr4.Runtime.Misc.IntervalSet Subtract(IIntSet a)\n        {\n            if (a == null || a.IsNil)\n            {\n                return new Antlr4.Runtime.Misc.IntervalSet(this);\n            }\n            if (a is Antlr4.Runtime.Misc.IntervalSet)\n            {\n                return Subtract(this, (Antlr4.Runtime.Misc.IntervalSet)a);\n            }\n            Antlr4.Runtime.Misc.IntervalSet other = new Antlr4.Runtime.Misc.IntervalSet();\n            other.AddAll(a);\n            return Subtract(this, other);\n        }\n\n        /// <summary>Compute the set difference between two interval sets.</summary>\n        /// <remarks>\n        /// Compute the set difference between two interval sets. The specific\n        /// operation is\n        /// <c>left - right</c>\n        /// . If either of the input sets is\n        /// <see langword=\"null\"/>\n        /// , it is treated as though it was an empty set.\n        /// </remarks>\n        [return: NotNull]\n        public static Antlr4.Runtime.Misc.IntervalSet Subtract(Antlr4.Runtime.Misc.IntervalSet left, Antlr4.Runtime.Misc.IntervalSet right)\n        {\n            if (left == null || left.IsNil)\n            {\n                return new Antlr4.Runtime.Misc.IntervalSet();\n            }\n            Antlr4.Runtime.Misc.IntervalSet result = new Antlr4.Runtime.Misc.IntervalSet(left);\n            if (right == null || right.IsNil)\n            {\n                // right set has no elements; just return the copy of the current set\n                return result;\n            }\n            int resultI = 0;\n            int rightI = 0;\n            while (resultI < result.intervals.Count && rightI < right.intervals.Count)\n            {\n                Interval resultInterval = result.intervals[resultI];\n                Interval rightInterval = right.intervals[rightI];\n                // operation: (resultInterval - rightInterval) and update indexes\n                if (rightInterval.b < resultInterval.a)\n                {\n                    rightI++;\n                    continue;\n                }\n                if (rightInterval.a > resultInterval.b)\n                {\n                    resultI++;\n                    continue;\n                }\n                Interval? beforeCurrent = null;\n                Interval? afterCurrent = null;\n                if (rightInterval.a > resultInterval.a)\n                {\n                    beforeCurrent = new Interval(resultInterval.a, rightInterval.a - 1);\n                }\n                if (rightInterval.b < resultInterval.b)\n                {\n                    afterCurrent = new Interval(rightInterval.b + 1, resultInterval.b);\n                }\n                if (beforeCurrent != null)\n                {\n                    if (afterCurrent != null)\n                    {\n                        // split the current interval into two\n                        result.intervals[resultI] = beforeCurrent.Value;\n                        result.intervals.Insert(resultI + 1, afterCurrent.Value);\n                        resultI++;\n                        rightI++;\n                        continue;\n                    }\n                    else\n                    {\n                        // replace the current interval\n                        result.intervals[resultI] = beforeCurrent.Value;\n                        resultI++;\n                        continue;\n                    }\n                }\n                else\n                {\n                    if (afterCurrent != null)\n                    {\n                        // replace the current interval\n                        result.intervals[resultI] = afterCurrent.Value;\n                        rightI++;\n                        continue;\n                    }\n                    else\n                    {\n                        // remove the current interval (thus no need to increment resultI)\n                        result.intervals.RemoveAt(resultI);\n                        continue;\n                    }\n                }\n            }\n            // If rightI reached right.intervals.size(), no more intervals to subtract from result.\n            // If resultI reached result.intervals.size(), we would be subtracting from an empty set.\n            // Either way, we are done.\n            return result;\n        }\n\n        public virtual Antlr4.Runtime.Misc.IntervalSet Or(IIntSet a)\n        {\n            Antlr4.Runtime.Misc.IntervalSet o = new Antlr4.Runtime.Misc.IntervalSet();\n            o.AddAll(this);\n            o.AddAll(a);\n            return o;\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        ///\n        /// </summary>\n        public virtual Antlr4.Runtime.Misc.IntervalSet And(IIntSet other)\n        {\n            if (other == null)\n            {\n                //|| !(other instanceof IntervalSet) ) {\n                return null;\n            }\n            // nothing in common with null set\n            IList<Interval> myIntervals = this.intervals;\n            IList<Interval> theirIntervals = ((Antlr4.Runtime.Misc.IntervalSet)other).intervals;\n            Antlr4.Runtime.Misc.IntervalSet intersection = null;\n            int mySize = myIntervals.Count;\n            int theirSize = theirIntervals.Count;\n            int i = 0;\n            int j = 0;\n            // iterate down both interval lists looking for nondisjoint intervals\n            while (i < mySize && j < theirSize)\n            {\n                Interval mine = myIntervals[i];\n                Interval theirs = theirIntervals[j];\n                //System.out.println(\"mine=\"+mine+\" and theirs=\"+theirs);\n                if (mine.StartsBeforeDisjoint(theirs))\n                {\n                    // move this iterator looking for interval that might overlap\n                    i++;\n                }\n                else\n                {\n                    if (theirs.StartsBeforeDisjoint(mine))\n                    {\n                        // move other iterator looking for interval that might overlap\n                        j++;\n                    }\n                    else\n                    {\n                        if (mine.ProperlyContains(theirs))\n                        {\n                            // overlap, add intersection, get next theirs\n                            if (intersection == null)\n                            {\n                                intersection = new Antlr4.Runtime.Misc.IntervalSet();\n                            }\n                            intersection.Add(mine.Intersection(theirs));\n                            j++;\n                        }\n                        else\n                        {\n                            if (theirs.ProperlyContains(mine))\n                            {\n                                // overlap, add intersection, get next mine\n                                if (intersection == null)\n                                {\n                                    intersection = new Antlr4.Runtime.Misc.IntervalSet();\n                                }\n                                intersection.Add(mine.Intersection(theirs));\n                                i++;\n                            }\n                            else\n                            {\n                                if (!mine.Disjoint(theirs))\n                                {\n                                    // overlap, add intersection\n                                    if (intersection == null)\n                                    {\n                                        intersection = new Antlr4.Runtime.Misc.IntervalSet();\n                                    }\n                                    intersection.Add(mine.Intersection(theirs));\n                                    // Move the iterator of lower range [a..b], but not\n                                    // the upper range as it may contain elements that will collide\n                                    // with the next iterator. So, if mine=[0..115] and\n                                    // theirs=[115..200], then intersection is 115 and move mine\n                                    // but not theirs as theirs may collide with the next range\n                                    // in thisIter.\n                                    // move both iterators to next ranges\n                                    if (mine.StartsAfterNonDisjoint(theirs))\n                                    {\n                                        j++;\n                                    }\n                                    else\n                                    {\n                                        if (theirs.StartsAfterNonDisjoint(mine))\n                                        {\n                                            i++;\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            if (intersection == null)\n            {\n                return new Antlr4.Runtime.Misc.IntervalSet();\n            }\n            return intersection;\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        ///\n        /// </summary>\n        public virtual bool Contains(int el)\n        {\n            int n = intervals.Count;\n            for (int i = 0; i < n; i++)\n            {\n                Interval I = intervals[i];\n                int a = I.a;\n                int b = I.b;\n                if (el < a)\n                {\n                    break;\n                }\n                // list is sorted and el is before this interval; not here\n                if (el >= a && el <= b)\n                {\n                    return true;\n                }\n            }\n            // found in this interval\n            return false;\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        ///\n        /// </summary>\n        public virtual bool IsNil\n        {\n            get\n            {\n                return intervals == null || intervals.Count == 0;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        ///\n        /// </summary>\n        public virtual int SingleElement\n        {\n            get\n            {\n                if (intervals != null && intervals.Count == 1)\n                {\n                    Interval I = intervals[0];\n                    if (I.a == I.b)\n                    {\n                        return I.a;\n                    }\n                }\n                return TokenConstants.InvalidType;\n            }\n        }\n\n        /// <summary>Returns the maximum value contained in the set.</summary>\n        /// <remarks>Returns the maximum value contained in the set.</remarks>\n        /// <returns>\n        /// the maximum value contained in the set. If the set is empty, this\n        /// method returns\n        /// <see cref=\"TokenConstants.InvalidType\"/>\n        /// .\n        /// </returns>\n        public virtual int MaxElement\n        {\n            get\n            {\n                if (IsNil)\n                {\n                    return TokenConstants.InvalidType;\n                }\n                Interval last = intervals[intervals.Count - 1];\n                return last.b;\n            }\n        }\n\n        /// <summary>Returns the minimum value contained in the set.</summary>\n        /// <remarks>Returns the minimum value contained in the set.</remarks>\n        /// <returns>\n        /// the minimum value contained in the set. If the set is empty, this\n        /// method returns\n        /// <see cref=\"TokenConstants.InvalidType\"/>\n        /// .\n        /// </returns>\n        public virtual int MinElement\n        {\n            get\n            {\n                if (IsNil)\n                {\n                    return TokenConstants.InvalidType;\n                }\n                return intervals[0].a;\n            }\n        }\n\n        /// <summary>Return a list of Interval objects.</summary>\n        /// <remarks>Return a list of Interval objects.</remarks>\n        public virtual IList<Interval> GetIntervals()\n        {\n            return intervals;\n        }\n\n        public override int GetHashCode()\n        {\n            int hash = MurmurHash.Initialize();\n            foreach (Interval I in intervals)\n            {\n                hash = MurmurHash.Update(hash, I.a);\n                hash = MurmurHash.Update(hash, I.b);\n            }\n            hash = MurmurHash.Finish(hash, intervals.Count * 2);\n            return hash;\n        }\n\n        /// <summary>\n        /// Are two IntervalSets equal?  Because all intervals are sorted\n        /// and disjoint, equals is a simple linear walk over both lists\n        /// to make sure they are the same.\n        /// </summary>\n        /// <remarks>\n        /// Are two IntervalSets equal?  Because all intervals are sorted\n        /// and disjoint, equals is a simple linear walk over both lists\n        /// to make sure they are the same.  Interval.equals() is used\n        /// by the List.equals() method to check the ranges.\n        /// </remarks>\n        public override bool Equals(object obj)\n        {\n            if (obj == null || !(obj is Antlr4.Runtime.Misc.IntervalSet))\n            {\n                return false;\n            }\n            Antlr4.Runtime.Misc.IntervalSet other = (Antlr4.Runtime.Misc.IntervalSet)obj;\n            return this.intervals.SequenceEqual(other.intervals);\n        }\n\n        public override string ToString()\n        {\n            return ToString(false);\n        }\n\n        public virtual string ToString(bool elemAreChar)\n        {\n            StringBuilder buf = new StringBuilder();\n            if (this.intervals == null || this.intervals.Count == 0)\n            {\n                return \"{}\";\n            }\n            if (this.Count > 1)\n            {\n                buf.Append(\"{\");\n            }\n\n            bool first = true;\n            foreach (Interval I in intervals)\n            {\n                if (!first)\n                    buf.Append(\", \");\n\n                first = false;\n                int a = I.a;\n                int b = I.b;\n                if (a == b)\n                {\n                    if (a == TokenConstants.EOF)\n                    {\n                        buf.Append(\"<EOF>\");\n                    }\n                    else\n                    {\n                        if (elemAreChar)\n                        {\n                            buf.Append(\"'\").Append((char)a).Append(\"'\");\n                        }\n                        else\n                        {\n                            buf.Append(a);\n                        }\n                    }\n                }\n                else\n                {\n                    if (elemAreChar)\n                    {\n                        buf.Append(\"'\").Append((char)a).Append(\"'..'\").Append((char)b).Append(\"'\");\n                    }\n                    else\n                    {\n                        buf.Append(a).Append(\"..\").Append(b);\n                    }\n                }\n            }\n            if (this.Count > 1)\n            {\n                buf.Append(\"}\");\n            }\n            return buf.ToString();\n        }\n\n        public virtual string ToString(IVocabulary vocabulary)\n        {\n            StringBuilder buf = new StringBuilder();\n            if (this.intervals == null || this.intervals.Count == 0)\n            {\n                return \"{}\";\n            }\n            if (this.Count > 1)\n            {\n                buf.Append(\"{\");\n            }\n\n            bool first = true;\n            foreach (Interval I in intervals)\n            {\n                if (!first)\n                    buf.Append(\", \");\n\n                first = false;\n                int a = I.a;\n                int b = I.b;\n                if (a == b)\n                {\n                    buf.Append(ElementName(vocabulary, a));\n                }\n                else\n                {\n                    for (int i = a; i <= b; i++)\n                    {\n                        if (i > a)\n                        {\n                            buf.Append(\", \");\n                        }\n                        buf.Append(ElementName(vocabulary, i));\n                    }\n                }\n            }\n            if (this.Count > 1)\n            {\n                buf.Append(\"}\");\n            }\n            return buf.ToString();\n        }\n\n        [return: NotNull]\n        protected internal virtual string ElementName(IVocabulary vocabulary, int a)\n        {\n            if (a == TokenConstants.EOF)\n            {\n                return \"<EOF>\";\n            }\n            else\n            {\n                if (a == TokenConstants.EPSILON)\n                {\n                    return \"<EPSILON>\";\n                }\n                else\n                {\n                    return vocabulary.GetDisplayName(a);\n                }\n            }\n        }\n\n        public virtual int Count\n        {\n            get\n            {\n                int n = 0;\n                int numIntervals = intervals.Count;\n                if (numIntervals == 1)\n                {\n                    Interval firstInterval = this.intervals[0];\n                    return firstInterval.b - firstInterval.a + 1;\n                }\n                for (int i = 0; i < numIntervals; i++)\n                {\n                    Interval I = intervals[i];\n                    n += (I.b - I.a + 1);\n                }\n                return n;\n            }\n        }\n\n        public virtual ArrayList<int> ToIntegerList()\n        {\n            ArrayList<int> values = new ArrayList<int>(Count);\n            int n = intervals.Count;\n            for (int i = 0; i < n; i++)\n            {\n                Interval I = intervals[i];\n                int a = I.a;\n                int b = I.b;\n                for (int v = a; v <= b; v++)\n                {\n                    values.Add(v);\n                }\n            }\n            return values;\n        }\n\n        public virtual IList<int> ToList()\n        {\n            IList<int> values = new ArrayList<int>();\n            int n = intervals.Count;\n            for (int i = 0; i < n; i++)\n            {\n                Interval I = intervals[i];\n                int a = I.a;\n                int b = I.b;\n                for (int v = a; v <= b; v++)\n                {\n                    values.Add(v);\n                }\n            }\n            return values;\n        }\n\n        public virtual HashSet<int> ToSet()\n        {\n            HashSet<int> s = new HashSet<int>();\n            foreach (Interval I in intervals)\n            {\n                int a = I.a;\n                int b = I.b;\n                for (int v = a; v <= b; v++)\n                {\n                    s.Add(v);\n                }\n            }\n            return s;\n        }\n\n        public virtual int[] ToArray()\n        {\n            return ToIntegerList().ToArray();\n        }\n\n        public virtual void Remove(int el)\n        {\n            if (@readonly)\n            {\n                throw new InvalidOperationException(\"can't alter readonly IntervalSet\");\n            }\n            int n = intervals.Count;\n            for (int i = 0; i < n; i++)\n            {\n                Interval I = intervals[i];\n                int a = I.a;\n                int b = I.b;\n                if (el < a)\n                {\n                    break;\n                }\n                // list is sorted and el is before this interval; not here\n                // if whole interval x..x, rm\n                if (el == a && el == b)\n                {\n                    intervals.RemoveAt(i);\n                    break;\n                }\n                // if on left edge x..b, adjust left\n                if (el == a)\n                {\n                    intervals[i] = Interval.Of(I.a + 1, I.b);\n                    break;\n                }\n                // if on right edge a..x, adjust right\n                if (el == b)\n                {\n                    intervals[i] = Interval.Of(I.a, I.b - 1);\n                    break;\n                }\n                // if in middle a..x..b, split interval\n                if (el > a && el < b)\n                {\n                    // found in this interval\n                    int oldb = I.b;\n                    intervals[i] = Interval.Of(I.a, el - 1);\n                    // [a..x-1]\n                    Add(el + 1, oldb);\n                }\n            }\n        }\n\n        public virtual bool IsReadOnly\n        {\n            get\n            {\n                // add [x+1..b]\n                return @readonly;\n            }\n        }\n\n        public virtual void SetReadonly(bool @readonly)\n        {\n            if (this.@readonly && !@readonly)\n            {\n                throw new InvalidOperationException(\"can't alter readonly IntervalSet\");\n            }\n            this.@readonly = @readonly;\n        }\n\n        IIntSet IIntSet.AddAll(IIntSet set)\n        {\n            return AddAll(set);\n        }\n\n        IIntSet IIntSet.And(IIntSet a)\n        {\n            return And(a);\n        }\n\n        IIntSet IIntSet.Complement(IIntSet elements)\n        {\n            return Complement(elements);\n        }\n\n        IIntSet IIntSet.Or(IIntSet a)\n        {\n            return Or(a);\n        }\n\n        IIntSet IIntSet.Subtract(IIntSet a)\n        {\n            return Subtract(a);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/MultiMap.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Misc\n{\n    [System.Serializable]\n    public class MultiMap<K, V> : Dictionary<K, IList<V>>\n    {\n        private const long serialVersionUID = -4956746660057462312L;\n\n        public virtual void Map(K key, V value)\n        {\n            IList<V> elementsForKey;\n            if (!TryGetValue(key, out elementsForKey))\n            {\n                elementsForKey = new ArrayList<V>();\n                this[key] = elementsForKey;\n            }\n            elementsForKey.Add(value);\n        }\n\n        public virtual IList<Tuple<K, V>> GetPairs()\n        {\n            IList<Tuple<K, V>> pairs = new ArrayList<Tuple<K, V>>();\n            foreach (KeyValuePair<K, IList<V>> pair in this)\n            {\n                foreach (V value in pair.Value)\n                {\n                    pairs.Add(Tuple.Create(pair.Key, value));\n                }\n            }\n\n            return pairs;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/MurmurHash.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Misc\n{\n    /// <author>Sam Harwell</author>\n    public sealed class MurmurHash\n    {\n        private const int DefaultSeed = 0;\n\n        /// <summary>Initialize the hash using the default seed value.</summary>\n        /// <remarks>Initialize the hash using the default seed value.</remarks>\n        /// <returns>the intermediate hash value</returns>\n        public static int Initialize()\n        {\n            return Initialize(DefaultSeed);\n        }\n\n        /// <summary>\n        /// Initialize the hash using the specified\n        /// <paramref name=\"seed\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"seed\">the seed</param>\n        /// <returns>the intermediate hash value</returns>\n        public static int Initialize(int seed)\n        {\n            return seed;\n        }\n\n        /// <summary>\n        /// Update the intermediate hash value for the next input\n        /// <paramref name=\"value\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"hash\">the intermediate hash value</param>\n        /// <param name=\"value\">the value to add to the current hash</param>\n        /// <returns>the updated intermediate hash value</returns>\n        public static int Update(int hash, int value)\n        {\n            int c1 = unchecked((int)(0xCC9E2D51));\n            int c2 = unchecked((int)(0x1B873593));\n            int r1 = 15;\n            int r2 = 13;\n            int m = 5;\n            int n = unchecked((int)(0xE6546B64));\n            int k = value;\n            k = k * c1;\n            k = (k << r1) | ((int)(((uint)k) >> (32 - r1)));\n            k = k * c2;\n            hash = hash ^ k;\n            hash = (hash << r2) | ((int)(((uint)hash) >> (32 - r2)));\n            hash = hash * m + n;\n            return hash;\n        }\n\n        /// <summary>\n        /// Update the intermediate hash value for the next input\n        /// <paramref name=\"value\"/>\n        /// .\n        /// </summary>\n        /// <param name=\"hash\">the intermediate hash value</param>\n        /// <param name=\"value\">the value to add to the current hash</param>\n        /// <returns>the updated intermediate hash value</returns>\n        public static int Update(int hash, object value)\n        {\n            return Update(hash, value != null ? value.GetHashCode() : 0);\n        }\n\n        /// <summary>\n        /// Apply the final computation steps to the intermediate value\n        /// <paramref name=\"hash\"/>\n        /// to form the final result of the MurmurHash 3 hash function.\n        /// </summary>\n        /// <param name=\"hash\">the intermediate hash value</param>\n        /// <param name=\"numberOfWords\">the number of integer values added to the hash</param>\n        /// <returns>the final hash result</returns>\n        public static int Finish(int hash, int numberOfWords)\n        {\n            hash = hash ^ (numberOfWords * 4);\n            hash = hash ^ ((int)(((uint)hash) >> 16));\n            hash = hash * unchecked((int)(0x85EBCA6B));\n            hash = hash ^ ((int)(((uint)hash) >> 13));\n            hash = hash * unchecked((int)(0xC2B2AE35));\n            hash = hash ^ ((int)(((uint)hash) >> 16));\n            return hash;\n        }\n\n        /// <summary>\n        /// Utility function to compute the hash code of an array using the\n        /// MurmurHash algorithm.\n        /// </summary>\n        /// <remarks>\n        /// Utility function to compute the hash code of an array using the\n        /// MurmurHash algorithm.\n        /// </remarks>\n        /// <param name=\"data\">the array data</param>\n        /// <param name=\"seed\">the seed for the MurmurHash algorithm</param>\n        /// <returns>the hash code of the data</returns>\n        public static int HashCode<T>(T[] data, int seed)\n        {\n            int hash = Initialize(seed);\n            foreach (T value in data)\n            {\n                hash = Update(hash, value);\n            }\n            hash = Finish(hash, data.Length);\n            return hash;\n        }\n\n        private MurmurHash()\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/NotNullAttribute.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Misc\n{\n    using System;\n\n    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]\n    public sealed class NotNullAttribute : Attribute\n    {\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/NullableAttribute.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Misc\n{\n    using System;\n\n    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]\n    public sealed class NullableAttribute : Attribute\n    {\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/Pair.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\n\nnamespace Antlr4.Runtime.Misc\n{\n\tpublic class Pair<A, B>\n\t{\n\t\tpublic readonly A a;\n\t\tpublic readonly B b;\n\n\t\tpublic Pair(A a, B b)\n\t\t{\n\t\t\tthis.a = a;\n\t\t\tthis.b = b;\n\t\t}\n\n\t\tpublic override bool Equals(Object obj)\n\t\t{\n\t\t\tif (obj == this)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (!(obj is Pair<A, B>))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tPair<A, B> other = (Pair<A, B>)obj;\n\t\t\treturn (a == null ? other.a == null : a.Equals(other.a)) &&\n\t\t\t\t   (b == null ? other.b == null : b.Equals(other.b));\n\t\t}\n\n\t\tpublic override int GetHashCode()\n\t\t{\n\t\t\tint hash = MurmurHash.Initialize();\n\t\t\thash = MurmurHash.Update(hash, a);\n\t\t\thash = MurmurHash.Update(hash, b);\n\t\t\treturn MurmurHash.Finish(hash, 2);\n\t\t}\n\n\t\tpublic override String ToString()\n\t\t{\n\t\t\treturn String.Format(\"({0}, {1})\", a, b);\n\t\t}\n\t}\n}"
  },
  {
    "path": "runtime/CSharp/src/Misc/ParseCanceledException.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\n\nnamespace Antlr4.Runtime.Misc\n{\n    /// <summary>This exception is thrown to cancel a parsing operation.</summary>\n    /// <remarks>\n    /// This exception is thrown to cancel a parsing operation. This exception does\n    /// not extend\n    /// <see cref=\"Antlr4.Runtime.RecognitionException\"/>\n    /// , allowing it to bypass the standard\n    /// error recovery mechanisms.\n    /// <see cref=\"Antlr4.Runtime.BailErrorStrategy\"/>\n    /// throws this exception in\n    /// response to a parse error.\n    /// </remarks>\n    /// <author>Sam Harwell</author>\n    [Serializable]\n    public class ParseCanceledException : OperationCanceledException\n    {\n        public ParseCanceledException()\n        {\n        }\n\n        public ParseCanceledException(string message)\n            : base(message)\n        {\n        }\n\n        public ParseCanceledException(Exception cause)\n            : base(\"The parse operation was cancelled.\", cause)\n        {\n        }\n\n        public ParseCanceledException(string message, Exception cause)\n            : base(message, cause)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/RuleDependencyChecker.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Misc\n{\n    /// <author>Sam Harwell</author>\n    public class RuleDependencyChecker\n    {\n        private static readonly HashSet<string> checkedAssemblies = new HashSet<string>();\n\n        public static void CheckDependencies(Assembly assembly)\n        {\n            if (IsChecked(assembly))\n            {\n                return;\n            }\n\n            IEnumerable<TypeInfo> typesToCheck = GetTypesToCheck(assembly);\n            List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();\n            foreach (TypeInfo clazz in typesToCheck)\n            {\n                dependencies.AddRange(GetDependencies(clazz));\n            }\n\n            if (dependencies.Count > 0)\n            {\n                IDictionary<TypeInfo, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> recognizerDependencies = new Dictionary<TypeInfo, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>>();\n                foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)\n                {\n                    TypeInfo recognizerType = dependency.Item1.Recognizer.GetTypeInfo();\n                    IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> list;\n                    if (!recognizerDependencies.TryGetValue(recognizerType, out list))\n                    {\n                        list = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();\n                        recognizerDependencies[recognizerType] = list;\n                    }\n                    list.Add(dependency);\n                }\n\n                foreach (KeyValuePair<TypeInfo, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> entry in recognizerDependencies)\n                {\n                    //processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, String.format(\"ANTLR 4: Validating {0} dependencies on rules in {1}.\", entry.getValue().size(), entry.getKey().toString()));\n                    CheckDependencies(entry.Value, entry.Key);\n                }\n            }\n\n            MarkChecked(assembly);\n        }\n\n        private static IEnumerable<TypeInfo> GetTypesToCheck(Assembly assembly)\n        {\n            return assembly.DefinedTypes;\n        }\n\n        private static bool IsChecked(Assembly assembly)\n        {\n            lock (checkedAssemblies)\n            {\n                return checkedAssemblies.Contains(assembly.FullName);\n            }\n        }\n\n        private static void MarkChecked(Assembly assembly)\n        {\n            lock (checkedAssemblies)\n            {\n                checkedAssemblies.Add(assembly.FullName);\n            }\n        }\n\n        private static void CheckDependencies(IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies, TypeInfo recognizerType)\n        {\n            string[] ruleNames = GetRuleNames(recognizerType);\n            int[] ruleVersions = GetRuleVersions(recognizerType, ruleNames);\n            RuleRelations relations = ExtractRuleRelations(recognizerType);\n            StringBuilder errors = new StringBuilder();\n            foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)\n            {\n                if (!dependency.Item1.Recognizer.GetTypeInfo().IsAssignableFrom(recognizerType))\n                {\n                    continue;\n                }\n                // this is the rule in the dependency set with the highest version number\n                int effectiveRule = dependency.Item1.Rule;\n                if (effectiveRule < 0 || effectiveRule >= ruleVersions.Length)\n                {\n                    string message = string.Format(\"Rule dependency on unknown rule {0}@{1} in {2}\", dependency.Item1.Rule, dependency.Item1.Version, dependency.Item1.Recognizer.ToString());\n                    errors.AppendLine(dependency.Item2.ToString());\n                    errors.AppendLine(message);\n                    continue;\n                }\n                Dependents dependents = Dependents.Self | dependency.Item1.Dependents;\n                ReportUnimplementedDependents(errors, dependency, dependents);\n                BitSet @checked = new BitSet();\n                int highestRequiredDependency = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, effectiveRule, null);\n                if ((dependents & Dependents.Parents) != 0)\n                {\n                    BitSet parents = relations.parents[dependency.Item1.Rule];\n                    for (int parent = parents.NextSetBit(0); parent >= 0; parent = parents.NextSetBit(parent + 1))\n                    {\n                        if (parent < 0 || parent >= ruleVersions.Length || @checked.Get(parent))\n                        {\n                            continue;\n                        }\n                        @checked.Set(parent);\n                        int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, parent, \"parent\");\n                        highestRequiredDependency = Math.Max(highestRequiredDependency, required);\n                    }\n                }\n                if ((dependents & Dependents.Children) != 0)\n                {\n                    BitSet children = relations.children[dependency.Item1.Rule];\n                    for (int child = children.NextSetBit(0); child >= 0; child = children.NextSetBit(child + 1))\n                    {\n                        if (child < 0 || child >= ruleVersions.Length || @checked.Get(child))\n                        {\n                            continue;\n                        }\n                        @checked.Set(child);\n                        int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, child, \"child\");\n                        highestRequiredDependency = Math.Max(highestRequiredDependency, required);\n                    }\n                }\n                if ((dependents & Dependents.Ancestors) != 0)\n                {\n                    BitSet ancestors = relations.GetAncestors(dependency.Item1.Rule);\n                    for (int ancestor = ancestors.NextSetBit(0); ancestor >= 0; ancestor = ancestors.NextSetBit(ancestor + 1))\n                    {\n                        if (ancestor < 0 || ancestor >= ruleVersions.Length || @checked.Get(ancestor))\n                        {\n                            continue;\n                        }\n                        @checked.Set(ancestor);\n                        int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, ancestor, \"ancestor\");\n                        highestRequiredDependency = Math.Max(highestRequiredDependency, required);\n                    }\n                }\n                if ((dependents & Dependents.Descendants) != 0)\n                {\n                    BitSet descendants = relations.GetDescendants(dependency.Item1.Rule);\n                    for (int descendant = descendants.NextSetBit(0); descendant >= 0; descendant = descendants.NextSetBit(descendant + 1))\n                    {\n                        if (descendant < 0 || descendant >= ruleVersions.Length || @checked.Get(descendant))\n                        {\n                            continue;\n                        }\n                        @checked.Set(descendant);\n                        int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, descendant, \"descendant\");\n                        highestRequiredDependency = Math.Max(highestRequiredDependency, required);\n                    }\n                }\n                int declaredVersion = dependency.Item1.Version;\n                if (declaredVersion > highestRequiredDependency)\n                {\n                    string message = string.Format(\"Rule dependency version mismatch: {0} has maximum dependency version {1} (expected {2}) in {3}\", ruleNames[dependency.Item1.Rule], highestRequiredDependency, declaredVersion, dependency.Item1.Recognizer.ToString());\n                    errors.AppendLine(dependency.Item2.ToString());\n                    errors.AppendLine(message);\n                }\n            }\n            if (errors.Length > 0)\n            {\n                throw new InvalidOperationException(errors.ToString());\n            }\n        }\n\n        private static readonly Dependents ImplementedDependents = Dependents.Self | Dependents.Parents | Dependents.Children | Dependents.Ancestors | Dependents.Descendants;\n\n        private static void ReportUnimplementedDependents(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, Dependents dependents)\n        {\n            Dependents unimplemented = dependents;\n            unimplemented &= ~ImplementedDependents;\n            if (unimplemented != Dependents.None)\n            {\n                string message = string.Format(\"Cannot validate the following dependents of rule {0}: {1}\", dependency.Item1.Rule, unimplemented);\n                errors.AppendLine(message);\n            }\n        }\n\n        private static int CheckDependencyVersion(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, string[] ruleNames, int[] ruleVersions, int relatedRule, string relation)\n        {\n            string ruleName = ruleNames[dependency.Item1.Rule];\n            string path;\n            if (relation == null)\n            {\n                path = ruleName;\n            }\n            else\n            {\n                string mismatchedRuleName = ruleNames[relatedRule];\n                path = string.Format(\"rule {0} ({1} of {2})\", mismatchedRuleName, relation, ruleName);\n            }\n            int declaredVersion = dependency.Item1.Version;\n            int actualVersion = ruleVersions[relatedRule];\n            if (actualVersion > declaredVersion)\n            {\n                string message = string.Format(\"Rule dependency version mismatch: {0} has version {1} (expected <= {2}) in {3}\", path, actualVersion, declaredVersion, dependency.Item1.Recognizer.ToString());\n                errors.AppendLine(dependency.Item2.ToString());\n                errors.AppendLine(message);\n            }\n            return actualVersion;\n        }\n\n        private static int[] GetRuleVersions(TypeInfo recognizerClass, string[] ruleNames)\n        {\n            int[] versions = new int[ruleNames.Length];\n            IEnumerable<FieldInfo> fields = recognizerClass.DeclaredFields;\n            foreach (FieldInfo field in fields)\n            {\n                bool isStatic = field.IsStatic;\n                bool isInteger = field.FieldType == typeof(int);\n                if (isStatic && isInteger && field.Name.StartsWith(\"RULE_\"))\n                {\n                    try\n                    {\n                        string name = field.Name.Substring(\"RULE_\".Length);\n                        if (name.Length == 0 || !System.Char.IsLower(name[0]))\n                        {\n                            continue;\n                        }\n                        int index = (int)field.GetValue(null);\n                        if (index < 0 || index >= versions.Length)\n                        {\n                            object[] @params = new object[] { index, field.Name, recognizerClass.Name };\n#if false\n                            Logger.Log(Level.Warning, \"Rule index {0} for rule ''{1}'' out of bounds for recognizer {2}.\", @params);\n#endif\n                            continue;\n                        }\n                        MethodInfo ruleMethod = GetRuleMethod(recognizerClass, name);\n                        if (ruleMethod == null)\n                        {\n                            object[] @params = new object[] { name, recognizerClass.Name };\n#if false\n                            Logger.Log(Level.Warning, \"Could not find rule method for rule ''{0}'' in recognizer {1}.\", @params);\n#endif\n                            continue;\n                        }\n                        RuleVersionAttribute ruleVersion = ruleMethod.GetCustomAttribute<RuleVersionAttribute>();\n                        int version = ruleVersion != null ? ruleVersion.Version : 0;\n                        versions[index] = version;\n                    }\n                    catch (ArgumentException)\n                    {\n#if false\n                        Logger.Log(Level.Warning, null, ex);\n#else\n                        throw;\n#endif\n                    }\n                    catch (MemberAccessException)\n                    {\n#if false\n                        Logger.Log(Level.Warning, null, ex);\n#else\n                        throw;\n#endif\n                    }\n                }\n            }\n            return versions;\n        }\n\n        private static MethodInfo GetRuleMethod(TypeInfo recognizerClass, string name)\n        {\n            IEnumerable<MethodInfo> declaredMethods = recognizerClass.DeclaredMethods;\n            foreach (MethodInfo method in declaredMethods)\n            {\n                if (method.Name.Equals(name) && method.GetCustomAttribute<RuleVersionAttribute>() != null)\n                {\n                    return method;\n                }\n            }\n            return null;\n        }\n\n        private static string[] GetRuleNames(TypeInfo recognizerClass)\n        {\n            FieldInfo ruleNames = recognizerClass.DeclaredFields.First(i => i.Name == \"ruleNames\");\n            return (string[])ruleNames.GetValue(null);\n        }\n\n        public static IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> GetDependencies(TypeInfo clazz)\n        {\n            IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();\n\n            GetElementDependencies(AsCustomAttributeProvider(clazz), result);\n            foreach (ConstructorInfo ctor in clazz.DeclaredConstructors)\n            {\n                GetElementDependencies(AsCustomAttributeProvider(ctor), result);\n                foreach (ParameterInfo parameter in ctor.GetParameters())\n                    GetElementDependencies(AsCustomAttributeProvider(parameter), result);\n            }\n\n            foreach (FieldInfo field in clazz.DeclaredFields)\n            {\n                GetElementDependencies(AsCustomAttributeProvider(field), result);\n            }\n\n            foreach (MethodInfo method in clazz.DeclaredMethods)\n            {\n                GetElementDependencies(AsCustomAttributeProvider(method), result);\n\n                if (method.ReturnParameter != null)\n                    GetElementDependencies(AsCustomAttributeProvider(method.ReturnParameter), result);\n\n                foreach (ParameterInfo parameter in method.GetParameters())\n                    GetElementDependencies(AsCustomAttributeProvider(parameter), result);\n            }\n\n            return result;\n        }\n\n        private static void GetElementDependencies(ICustomAttributeProvider annotatedElement, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result)\n        {\n            foreach (RuleDependencyAttribute dependency in annotatedElement.GetCustomAttributes(typeof(RuleDependencyAttribute), true))\n            {\n                result.Add(Tuple.Create(dependency, annotatedElement));\n            }\n        }\n\n        private static RuleDependencyChecker.RuleRelations ExtractRuleRelations(TypeInfo recognizer)\n        {\n            int[] serializedATN = GetSerializedATN(recognizer);\n            if (serializedATN == null)\n            {\n                return null;\n            }\n            ATN atn = new ATNDeserializer().Deserialize(serializedATN);\n            RuleDependencyChecker.RuleRelations relations = new RuleDependencyChecker.RuleRelations(atn.ruleToStartState.Length);\n            foreach (ATNState state in atn.states)\n            {\n                if (!state.epsilonOnlyTransitions)\n                {\n                    continue;\n                }\n                foreach (Transition transition in state.transitions)\n                {\n                    if (transition.TransitionType != TransitionType.RULE)\n                    {\n                        continue;\n                    }\n                    RuleTransition ruleTransition = (RuleTransition)transition;\n                    relations.AddRuleInvocation(state.ruleIndex, ruleTransition.target.ruleIndex);\n                }\n            }\n            return relations;\n        }\n\n        private static int[] GetSerializedATN(TypeInfo recognizerClass)\n        {\n            FieldInfo serializedAtnField = recognizerClass.DeclaredFields.First(i => i.Name == \"_serializedATN\");\n            if (serializedAtnField != null)\n                return (int[])serializedAtnField.GetValue(null);\n\n            if (recognizerClass.BaseType != null)\n                return GetSerializedATN(recognizerClass.BaseType.GetTypeInfo());\n\n            return null;\n        }\n\n        private sealed class RuleRelations\n        {\n            public readonly BitSet[] parents;\n\n            public readonly BitSet[] children;\n\n            public RuleRelations(int ruleCount)\n            {\n                parents = new BitSet[ruleCount];\n                for (int i = 0; i < ruleCount; i++)\n                {\n                    parents[i] = new BitSet();\n                }\n                children = new BitSet[ruleCount];\n                for (int i_1 = 0; i_1 < ruleCount; i_1++)\n                {\n                    children[i_1] = new BitSet();\n                }\n            }\n\n            public bool AddRuleInvocation(int caller, int callee)\n            {\n                if (caller < 0)\n                {\n                    // tokens rule\n                    return false;\n                }\n                if (children[caller].Get(callee))\n                {\n                    // already added\n                    return false;\n                }\n                children[caller].Set(callee);\n                parents[callee].Set(caller);\n                return true;\n            }\n\n            public BitSet GetAncestors(int rule)\n            {\n                BitSet ancestors = new BitSet();\n                ancestors.Or(parents[rule]);\n                while (true)\n                {\n                    int cardinality = ancestors.Cardinality();\n                    for (int i = ancestors.NextSetBit(0); i >= 0; i = ancestors.NextSetBit(i + 1))\n                    {\n                        ancestors.Or(parents[i]);\n                    }\n                    if (ancestors.Cardinality() == cardinality)\n                    {\n                        // nothing changed\n                        break;\n                    }\n                }\n                return ancestors;\n            }\n\n            public BitSet GetDescendants(int rule)\n            {\n                BitSet descendants = new BitSet();\n                descendants.Or(children[rule]);\n                while (true)\n                {\n                    int cardinality = descendants.Cardinality();\n                    for (int i = descendants.NextSetBit(0); i >= 0; i = descendants.NextSetBit(i + 1))\n                    {\n                        descendants.Or(children[i]);\n                    }\n                    if (descendants.Cardinality() == cardinality)\n                    {\n                        // nothing changed\n                        break;\n                    }\n                }\n                return descendants;\n            }\n        }\n\n        private RuleDependencyChecker()\n        {\n        }\n\n        public interface ICustomAttributeProvider\n        {\n            object[] GetCustomAttributes(Type attributeType, bool inherit);\n        }\n\n        protected static ICustomAttributeProvider AsCustomAttributeProvider(TypeInfo type)\n        {\n            return new TypeCustomAttributeProvider(type);\n        }\n\n        protected static ICustomAttributeProvider AsCustomAttributeProvider(MethodBase method)\n        {\n            return new MethodBaseCustomAttributeProvider(method);\n        }\n\n        protected static ICustomAttributeProvider AsCustomAttributeProvider(ParameterInfo parameter)\n        {\n            return new ParameterInfoCustomAttributeProvider(parameter);\n        }\n\n        protected static ICustomAttributeProvider AsCustomAttributeProvider(FieldInfo field)\n        {\n            return new FieldInfoCustomAttributeProvider(field);\n        }\n\n        protected sealed class TypeCustomAttributeProvider : ICustomAttributeProvider\n        {\n            private readonly TypeInfo _provider;\n\n            public TypeCustomAttributeProvider(TypeInfo provider)\n            {\n                _provider = provider;\n            }\n\n            public object[] GetCustomAttributes(Type attributeType, bool inherit)\n            {\n                return _provider.GetCustomAttributes(attributeType, inherit).ToArray();\n            }\n        }\n\n        protected sealed class MethodBaseCustomAttributeProvider : ICustomAttributeProvider\n        {\n            private readonly MethodBase _provider;\n\n            public MethodBaseCustomAttributeProvider(MethodBase provider)\n            {\n                _provider = provider;\n            }\n\n            public object[] GetCustomAttributes(Type attributeType, bool inherit)\n            {\n                return _provider.GetCustomAttributes(attributeType, inherit).ToArray();\n            }\n        }\n\n        protected sealed class ParameterInfoCustomAttributeProvider : ICustomAttributeProvider\n        {\n            private readonly ParameterInfo _provider;\n\n            public ParameterInfoCustomAttributeProvider(ParameterInfo provider)\n            {\n                _provider = provider;\n            }\n\n            public object[] GetCustomAttributes(Type attributeType, bool inherit)\n            {\n                return _provider.GetCustomAttributes(attributeType, inherit).ToArray();\n            }\n        }\n\n        protected sealed class FieldInfoCustomAttributeProvider : ICustomAttributeProvider\n        {\n            private readonly FieldInfo _provider;\n\n            public FieldInfoCustomAttributeProvider(FieldInfo provider)\n            {\n                _provider = provider;\n            }\n\n            public object[] GetCustomAttributes(Type attributeType, bool inherit)\n            {\n                return _provider.GetCustomAttributes(attributeType, inherit).ToArray();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Misc/Utils.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Antlr4.Runtime.Misc\n{\n    public static class StaticUtils\n    {\n        public static string ToString<T>(this IEnumerable<T> list)\n        {\n            return \"[\" + Utils.Join(\", \", list) + \"]\";\n        }\n    }\n\n    public class Utils\n    {\n        public static string Join<T>(string separator, IEnumerable<T> items)\n        {\n            return string.Join(separator, items);\n        }\n\n        public static int NumNonnull(object[] data)\n        {\n            int n = 0;\n            if (data == null)\n            {\n                return n;\n            }\n            foreach (object o in data)\n            {\n                if (o != null)\n                {\n                    n++;\n                }\n            }\n            return n;\n        }\n\n        public static void RemoveAllElements<T>(ICollection<T> data, T value)\n        {\n            if (data == null)\n            {\n                return;\n            }\n            while (data.Contains(value))\n            {\n                data.Remove(value);\n            }\n        }\n\n        public static string EscapeWhitespace(string s, bool escapeSpaces)\n        {\n            StringBuilder buf = new StringBuilder();\n            foreach (char c in s.ToCharArray())\n            {\n                if (c == ' ' && escapeSpaces)\n                {\n                    buf.Append('\\u00B7');\n                }\n                else\n                {\n                    if (c == '\\t')\n                    {\n                        buf.Append(\"\\\\t\");\n                    }\n                    else\n                    {\n                        if (c == '\\n')\n                        {\n                            buf.Append(\"\\\\n\");\n                        }\n                        else\n                        {\n                            if (c == '\\r')\n                            {\n                                buf.Append(\"\\\\r\");\n                            }\n                            else\n                            {\n                                buf.Append(c);\n                            }\n                        }\n                    }\n                }\n            }\n            return buf.ToString();\n        }\n\n        public static void RemoveAll<T>(IList<T> list, Predicate<T> predicate)\n        {\n            int j = 0;\n            for (int i = 0; i < list.Count; i++)\n            {\n                T item = list[i];\n                if (!predicate(item))\n                {\n                    if (j != i)\n                    {\n                        list[j] = item;\n                    }\n                    j++;\n                }\n            }\n            while (j < list.Count)\n            {\n                list.RemoveAt(list.Count - 1);\n            }\n        }\n\n        /// <summary>Convert array of strings to string&#x2192;index map.</summary>\n        /// <remarks>\n        /// Convert array of strings to string&#x2192;index map. Useful for\n        /// converting rulenames to name&#x2192;ruleindex map.\n        /// </remarks>\n        public static IDictionary<string, int> ToMap(string[] keys)\n        {\n            IDictionary<string, int> m = new Dictionary<string, int>();\n            for (int i = 0; i < keys.Length; i++)\n            {\n                m[keys[i]] = i;\n            }\n            return m;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/NoViableAltException.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// Indicates that the parser could not decide which of two or more paths\n    /// to take based upon the remaining input.\n    /// </summary>\n    /// <remarks>\n    /// Indicates that the parser could not decide which of two or more paths\n    /// to take based upon the remaining input. It tracks the starting token\n    /// of the offending input and also knows where the parser was\n    /// in the various paths when the error. Reported by reportNoViableAlternative()\n    /// </remarks>\n    [System.Serializable]\n    public class NoViableAltException : RecognitionException\n    {\n        private const long serialVersionUID = 5096000008992867052L;\n\n        /// <summary>Which configurations did we try at input.index() that couldn't match input.LT(1)?</summary>\n        [Nullable]\n        private readonly ATNConfigSet deadEndConfigs;\n\n        /// <summary>\n        /// The token object at the start index; the input stream might\n        /// not be buffering tokens so get a reference to it.\n        /// </summary>\n        /// <remarks>\n        /// The token object at the start index; the input stream might\n        /// not be buffering tokens so get a reference to it. (At the\n        /// time the error occurred, of course the stream needs to keep a\n        /// buffer all of the tokens but later we might not have access to those.)\n        /// </remarks>\n        [NotNull]\n        private readonly IToken startToken;\n\n        public NoViableAltException(Parser recognizer)\n\t\t\t: this(recognizer, ((ITokenStream)recognizer.InputStream), recognizer.CurrentToken, recognizer.CurrentToken, null, recognizer.RuleContext)\n        {\n        }\n\n        public NoViableAltException(IRecognizer recognizer, ITokenStream input, IToken startToken, IToken offendingToken, ATNConfigSet deadEndConfigs, ParserRuleContext ctx)\n            : base(recognizer, input, ctx)\n        {\n            // LL(1) error\n            this.deadEndConfigs = deadEndConfigs;\n            this.startToken = startToken;\n            this.OffendingToken = offendingToken;\n        }\n\n        public virtual IToken StartToken\n        {\n            get\n            {\n                return startToken;\n            }\n        }\n\n        [Nullable]\n        public virtual ATNConfigSet DeadEndConfigs\n        {\n            get\n            {\n                return deadEndConfigs;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Parser.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.IO;\nusing System.Text;\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Pattern;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>This is all the parsing support code essentially; most of it is error recovery stuff.</summary>\n    /// <remarks>This is all the parsing support code essentially; most of it is error recovery stuff.</remarks>\n    public abstract class Parser : Recognizer<IToken, ParserATNSimulator>\n    {\n        public class TraceListener : IParseTreeListener\n        {\n\n            public TraceListener(TextWriter output,Parser enclosing) {\n                _output = output;\n                _enclosing = enclosing;\n            }\n\n            public virtual void EnterEveryRule(ParserRuleContext ctx)\n            {\n                _output.WriteLine(\"enter   \" + this._enclosing.RuleNames[ctx.RuleIndex] + \", LT(1)=\" + this._enclosing._input.LT(1).Text);\n            }\n\n            public virtual void ExitEveryRule(ParserRuleContext ctx)\n            {\n                _output.WriteLine(\"exit    \" + this._enclosing.RuleNames[ctx.RuleIndex] + \", LT(1)=\" + this._enclosing._input.LT(1).Text);\n            }\n\n            public virtual void VisitErrorNode(IErrorNode node)\n            {\n            }\n\n            public virtual void VisitTerminal(ITerminalNode node)\n            {\n                ParserRuleContext parent = (ParserRuleContext)((IRuleNode)node.Parent).RuleContext;\n                IToken token = node.Symbol;\n                _output.WriteLine(\"consume \" + token + \" rule \" + this._enclosing.RuleNames[parent.RuleIndex]);\n            }\n\n            internal TraceListener(Parser _enclosing)\n            {\n                this._enclosing = _enclosing;\n                _output = Console.Out;\n            }\n\n            private readonly Parser _enclosing;\n            private readonly TextWriter _output;\n        }\n\n        public class TrimToSizeListener : IParseTreeListener\n        {\n            public static readonly Parser.TrimToSizeListener Instance = new Parser.TrimToSizeListener();\n\n            public virtual void VisitTerminal(ITerminalNode node)\n            {\n            }\n\n            public virtual void VisitErrorNode(IErrorNode node)\n            {\n            }\n\n            public virtual void EnterEveryRule(ParserRuleContext ctx)\n            {\n            }\n\n            public virtual void ExitEveryRule(ParserRuleContext ctx)\n            {\n                if (ctx.children is List<IParseTree>)\n                {\n                    ((List<IParseTree>)ctx.children).TrimExcess();\n                }\n            }\n        }\n\n        /// <summary>\n        /// This field maps from the serialized ATN string to the deserialized\n        /// <see cref=\"Antlr4.Runtime.Atn.ATN\"/>\n        /// with\n        /// bypass alternatives.\n        /// </summary>\n        /// <seealso cref=\"Antlr4.Runtime.Atn.ATNDeserializationOptions.GenerateRuleBypassTransitions()\"/>\n//        private static readonly IDictionary<string, ATN> bypassAltsAtnCache = new Dictionary<string, ATN>();\n        private ATN bypassAltsAtnCache;\n\n        /// <summary>The error handling strategy for the parser.</summary>\n        /// <remarks>\n        /// The error handling strategy for the parser. The default value is a new\n        /// instance of\n        /// <see cref=\"DefaultErrorStrategy\"/>\n        /// .\n        /// </remarks>\n        /// <seealso cref=\"ErrorHandler\"/>\n        [NotNull]\n\t\tprivate IAntlrErrorStrategy _errHandler = new DefaultErrorStrategy();\n\n        /// <summary>The input stream.</summary>\n        /// <remarks>The input stream.</remarks>\n        /// <seealso cref=\"InputStream()\"/>\n    \tprivate ITokenStream _input;\n\n\t\tprivate readonly List<int> _precedenceStack = new List<int> { 0 };\n\n        /// <summary>\n        /// The\n        /// <see cref=\"ParserRuleContext\"/>\n        /// object for the currently executing rule.\n        /// This is always non-null during the parsing process.\n        /// </summary>\n        private ParserRuleContext _ctx;\n\n        /// <summary>\n        /// Specifies whether or not the parser should construct a parse tree during\n        /// the parsing process.\n        /// </summary>\n        /// <remarks>\n        /// Specifies whether or not the parser should construct a parse tree during\n        /// the parsing process. The default value is\n        /// <see langword=\"true\"/>\n        /// .\n        /// </remarks>\n        /// <seealso cref=\"BuildParseTree\"/>\n        private bool _buildParseTrees = true;\n\n        /// <summary>\n        /// When\n        /// <see cref=\"Trace\"/>\n        /// <c>(true)</c>\n        /// is called, a reference to the\n        /// <see cref=\"TraceListener\"/>\n        /// is stored here so it can be easily removed in a\n        /// later call to\n        /// <see cref=\"Trace\"/>\n        /// <c>(false)</c>\n        /// . The listener itself is\n        /// implemented as a parser listener so this field is not directly used by\n        /// other parser methods.\n        /// </summary>\n        private Parser.TraceListener _tracer;\n\n        /// <summary>\n        /// The list of\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTreeListener\"/>\n        /// listeners registered to receive\n        /// events during the parse.\n        /// </summary>\n        /// <seealso cref=\"AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)\"/>\n        [Nullable]\n        private IList<IParseTreeListener> _parseListeners;\n\n        /// <summary>The number of syntax errors reported during parsing.</summary>\n        /// <remarks>\n        /// The number of syntax errors reported during parsing. This value is\n        /// incremented each time\n        /// <see cref=\"NotifyErrorListeners(string)\"/>\n        /// is called.\n        /// </remarks>\n        private int _syntaxErrors;\n\n        protected readonly TextWriter Output;\n        protected readonly TextWriter ErrorOutput;\n\n        public Parser(ITokenStream input) : this(input, Console.Out, Console.Error) { }\n\n        public Parser(ITokenStream input, TextWriter output, TextWriter errorOutput)\n        {\n            TokenStream = input;\n            Output = output;\n            ErrorOutput = errorOutput;\n        }\n\n        /// <summary>reset the parser's state</summary>\n        public virtual void Reset()\n        {\n            if (((ITokenStream)InputStream) != null)\n            {\n                ((ITokenStream)InputStream).Seek(0);\n            }\n            _errHandler.Reset(this);\n            _ctx = null;\n            _syntaxErrors = 0;\n            Trace = false;\n            _precedenceStack.Clear();\n            _precedenceStack.Add(0);\n            ATNSimulator interpreter = Interpreter;\n            if (interpreter != null)\n            {\n                interpreter.Reset();\n            }\n        }\n\n        /// <summary>\n        /// Match current input symbol against\n        /// <paramref name=\"ttype\"/>\n        /// . If the symbol type\n        /// matches,\n        /// <see cref=\"IAntlrErrorStrategy.ReportMatch(Parser)\"/>\n        /// and\n        /// <see cref=\"Consume()\"/>\n        /// are\n        /// called to complete the match process.\n        /// <p>If the symbol type does not match,\n        /// <see cref=\"IAntlrErrorStrategy.RecoverInline(Parser)\"/>\n        /// is called on the current error\n        /// strategy to attempt recovery. If\n        /// <see cref=\"BuildParseTree()\"/>\n        /// is\n        /// <see langword=\"true\"/>\n        /// and the token index of the symbol returned by\n        /// <see cref=\"IAntlrErrorStrategy.RecoverInline(Parser)\"/>\n        /// is -1, the symbol is added to\n        /// the parse tree by calling\n        /// <see cref=\"ParserRuleContext.AddErrorNode(IToken)\"/>\n        /// .</p>\n        /// </summary>\n        /// <param name=\"ttype\">the token type to match</param>\n        /// <returns>the matched symbol</returns>\n        /// <exception cref=\"RecognitionException\">\n        /// if the current input symbol did not match\n        /// <paramref name=\"ttype\"/>\n        /// and the error strategy could not recover from the\n        /// mismatched symbol\n        /// </exception>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        [return: NotNull]\n        public virtual IToken Match(int ttype)\n        {\n            IToken t = CurrentToken;\n            if (t.Type == ttype)\n            {\n                _errHandler.ReportMatch(this);\n                Consume();\n            }\n            else\n            {\n                t = _errHandler.RecoverInline(this);\n                if (_buildParseTrees && t.TokenIndex == -1)\n                {\n                    // we must have conjured up a new token during single token insertion\n                    // if it's not the current symbol\n                    _ctx.AddErrorNode(t);\n                }\n            }\n            return t;\n        }\n\n        /// <summary>Match current input symbol as a wildcard.</summary>\n        /// <remarks>\n        /// Match current input symbol as a wildcard. If the symbol type matches\n        /// (i.e. has a value greater than 0),\n        /// <see cref=\"IAntlrErrorStrategy.ReportMatch(Parser)\"/>\n        /// and\n        /// <see cref=\"Consume()\"/>\n        /// are called to complete the match process.\n        /// <p>If the symbol type does not match,\n        /// <see cref=\"IAntlrErrorStrategy.RecoverInline(Parser)\"/>\n        /// is called on the current error\n        /// strategy to attempt recovery. If\n        /// <see cref=\"BuildParseTree()\"/>\n        /// is\n        /// <see langword=\"true\"/>\n        /// and the token index of the symbol returned by\n        /// <see cref=\"IAntlrErrorStrategy.RecoverInline(Parser)\"/>\n        /// is -1, the symbol is added to\n        /// the parse tree by calling\n        /// <see cref=\"ParserRuleContext.AddErrorNode(IToken)\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>the matched symbol</returns>\n        /// <exception cref=\"RecognitionException\">\n        /// if the current input symbol did not match\n        /// a wildcard and the error strategy could not recover from the mismatched\n        /// symbol\n        /// </exception>\n        /// <exception cref=\"Antlr4.Runtime.RecognitionException\"/>\n        [return: NotNull]\n        public virtual IToken MatchWildcard()\n        {\n            IToken t = CurrentToken;\n            if (t.Type > 0)\n            {\n                _errHandler.ReportMatch(this);\n                Consume();\n            }\n            else\n            {\n                t = _errHandler.RecoverInline(this);\n                if (_buildParseTrees && t.TokenIndex == -1)\n                {\n                    // we must have conjured up a new token during single token insertion\n                    // if it's not the current symbol\n                    _ctx.AddErrorNode(t);\n                }\n            }\n            return t;\n        }\n\n        /// <summary>\n        /// Track the\n        /// <see cref=\"ParserRuleContext\"/>\n        /// objects during the parse and hook\n        /// them up using the\n        /// <see cref=\"ParserRuleContext.children\"/>\n        /// list so that it\n        /// forms a parse tree. The\n        /// <see cref=\"ParserRuleContext\"/>\n        /// returned from the start\n        /// rule represents the root of the parse tree.\n        /// <p>Note that if we are not building parse trees, rule contexts only point\n        /// upwards. When a rule exits, it returns the context but that gets garbage\n        /// collected if nobody holds a reference. It points upwards but nobody\n        /// points at it.</p>\n        /// <p>When we build parse trees, we are adding all of these contexts to\n        /// <see cref=\"ParserRuleContext.children\"/>\n        /// list. Contexts are then not candidates\n        /// for garbage collection.</p>\n        /// </summary>\n        /// <summary>\n        /// Gets whether or not a complete parse tree will be constructed while\n        /// parsing.\n        /// </summary>\n        /// <remarks>\n        /// Gets whether or not a complete parse tree will be constructed while\n        /// parsing. This property is\n        /// <see langword=\"true\"/>\n        /// for a newly constructed parser.\n        /// </remarks>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if a complete parse tree will be constructed while\n        /// parsing, otherwise\n        /// <see langword=\"false\"/>\n        /// </returns>\n        public virtual bool BuildParseTree\n        {\n            get\n            {\n                return _buildParseTrees;\n            }\n            set\n            {\n\t\t\t\tthis._buildParseTrees = value;\n            }\n        }\n\n        /// <summary>Trim the internal lists of the parse tree during parsing to conserve memory.</summary>\n        /// <remarks>\n        /// Trim the internal lists of the parse tree during parsing to conserve memory.\n        /// This property is set to\n        /// <see langword=\"false\"/>\n        /// by default for a newly constructed parser.\n        /// </remarks>\n        /// <value>\n        ///\n        /// <see langword=\"true\"/>\n        /// to trim the capacity of the\n        /// <see cref=\"ParserRuleContext.children\"/>\n        /// list to its size after a rule is parsed.\n        /// </value>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if the\n        /// <see cref=\"ParserRuleContext.children\"/>\n        /// list is trimmed\n        /// using the default\n        /// <see cref=\"TrimToSizeListener\"/>\n        /// during the parse process.\n        /// </returns>\n        public virtual bool TrimParseTree\n        {\n            get\n            {\n                return ParseListeners.Contains(Parser.TrimToSizeListener.Instance);\n            }\n            set\n            {\n                bool trimParseTrees = value;\n                if (trimParseTrees)\n                {\n                    if (TrimParseTree)\n                    {\n                        return;\n                    }\n                    AddParseListener(Parser.TrimToSizeListener.Instance);\n                }\n                else\n                {\n                    RemoveParseListener(Parser.TrimToSizeListener.Instance);\n                }\n            }\n        }\n\n        public virtual IList<IParseTreeListener> ParseListeners\n        {\n            get\n            {\n                IList<IParseTreeListener> listeners = _parseListeners;\n                if (listeners == null)\n                {\n                    return Sharpen.Collections.EmptyList<IParseTreeListener>();\n                }\n                return listeners;\n            }\n        }\n\n        /// <summary>\n        /// Registers\n        /// <paramref name=\"listener\"/>\n        /// to receive events during the parsing process.\n        /// <p>To support output-preserving grammar transformations (including but not\n        /// limited to left-recursion removal, automated left-factoring, and\n        /// optimized code generation), calls to listener methods during the parse\n        /// may differ substantially from calls made by\n        /// <see cref=\"Antlr4.Runtime.Tree.ParseTreeWalker.Default\"/>\n        /// used after the parse is complete. In\n        /// particular, rule entry and exit events may occur in a different order\n        /// during the parse than after the parser. In addition, calls to certain\n        /// rule entry methods may be omitted.</p>\n        /// <p>With the following specific exceptions, calls to listener events are\n        /// <em>deterministic</em>, i.e. for identical input the calls to listener\n        /// methods will be the same.</p>\n        /// <ul>\n        /// <li>Alterations to the grammar used to generate code may change the\n        /// behavior of the listener calls.</li>\n        /// <li>Alterations to the command line options passed to ANTLR 4 when\n        /// generating the parser may change the behavior of the listener calls.</li>\n        /// <li>Changing the version of the ANTLR Tool used to generate the parser\n        /// may change the behavior of the listener calls.</li>\n        /// </ul>\n        /// </summary>\n        /// <param name=\"listener\">the listener to add</param>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// if\n        /// <c/>\n        /// listener is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        public virtual void AddParseListener(IParseTreeListener listener)\n        {\n            if (listener == null)\n            {\n                throw new ArgumentNullException(\"listener\");\n            }\n            if (_parseListeners == null)\n            {\n                _parseListeners = new List<IParseTreeListener>();\n            }\n            this._parseListeners.Add(listener);\n        }\n\n        /// <summary>\n        /// Remove\n        /// <paramref name=\"listener\"/>\n        /// from the list of parse listeners.\n        /// <p>If\n        /// <paramref name=\"listener\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// or has not been added as a parse\n        /// listener, this method does nothing.</p>\n        /// </summary>\n        /// <seealso cref=\"AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)\"/>\n        /// <param name=\"listener\">the listener to remove</param>\n        public virtual void RemoveParseListener(IParseTreeListener listener)\n        {\n            if (_parseListeners != null)\n            {\n                if (_parseListeners.Remove(listener))\n                {\n                    if (_parseListeners.Count == 0)\n                    {\n                        _parseListeners = null;\n                    }\n                }\n            }\n        }\n\n        /// <summary>Remove all parse listeners.</summary>\n        /// <remarks>Remove all parse listeners.</remarks>\n        /// <seealso cref=\"AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)\"/>\n        public virtual void RemoveParseListeners()\n        {\n            _parseListeners = null;\n        }\n\n        /// <summary>Notify any parse listeners of an enter rule event.</summary>\n        /// <remarks>Notify any parse listeners of an enter rule event.</remarks>\n        /// <seealso cref=\"AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)\"/>\n        protected internal virtual void TriggerEnterRuleEvent()\n        {\n            foreach (IParseTreeListener listener in _parseListeners)\n            {\n                listener.EnterEveryRule(_ctx);\n                _ctx.EnterRule(listener);\n            }\n        }\n\n        /// <summary>Notify any parse listeners of an exit rule event.</summary>\n        /// <remarks>Notify any parse listeners of an exit rule event.</remarks>\n        /// <seealso cref=\"AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)\"/>\n        protected internal virtual void TriggerExitRuleEvent()\n        {\n            // reverse order walk of listeners\n\t\t\tif (_parseListeners != null) {\n\t\t\t\tfor (int i = _parseListeners.Count - 1; i >= 0; i--) {\n\t\t\t\t\tIParseTreeListener listener = _parseListeners [i];\n\t\t\t\t\t_ctx.ExitRule (listener);\n\t\t\t\t\tlistener.ExitEveryRule (_ctx);\n\t\t\t\t}\n\t\t\t}\n        }\n\n        /// <summary>Gets the number of syntax errors reported during parsing.</summary>\n        /// <remarks>\n        /// Gets the number of syntax errors reported during parsing. This value is\n        /// incremented each time\n        /// <see cref=\"NotifyErrorListeners(string)\"/>\n        /// is called.\n        /// </remarks>\n        /// <seealso cref=\"NotifyErrorListeners(string)\"/>\n        public virtual int NumberOfSyntaxErrors\n        {\n            get\n            {\n                return _syntaxErrors;\n            }\n        }\n\n        public virtual ITokenFactory TokenFactory\n        {\n            get\n            {\n                return _input.TokenSource.TokenFactory;\n            }\n        }\n\n        /// <summary>\n        /// The ATN with bypass alternatives is expensive to create so we create it\n        /// lazily.\n        /// </summary>\n        /// <remarks>\n        /// The ATN with bypass alternatives is expensive to create so we create it\n        /// lazily.\n        /// </remarks>\n        /// <exception cref=\"System.NotSupportedException\">\n        /// if the current parser does not\n        /// implement the\n        /// <see cref=\"Recognizer{Symbol, ATNInterpreter}.SerializedAtn()\"/>\n        /// method.\n        /// </exception>\n        [return: NotNull]\n        public virtual ATN GetATNWithBypassAlts()\n        {\n            int[] serializedAtn = SerializedAtn;\n            if (serializedAtn == null)\n            {\n                throw new NotSupportedException(\"The current parser does not support an ATN with bypass alternatives.\");\n            }\n            lock (this)\n            {\n                if ( bypassAltsAtnCache!=null ) {\n                    return bypassAltsAtnCache;\n                }\n                ATNDeserializationOptions deserializationOptions = new ATNDeserializationOptions();\n                deserializationOptions.GenerateRuleBypassTransitions = true;\n                bypassAltsAtnCache = new ATNDeserializer(deserializationOptions).Deserialize(serializedAtn);\n                return bypassAltsAtnCache;\n            }\n        }\n\n        /// <summary>The preferred method of getting a tree pattern.</summary>\n        /// <remarks>\n        /// The preferred method of getting a tree pattern. For example, here's a\n        /// sample use:\n        /// <pre>\n        /// ParseTree t = parser.expr();\n        /// ParseTreePattern p = parser.compileParseTreePattern(\"&lt;ID&gt;+0\", MyParser.RULE_expr);\n        /// ParseTreeMatch m = p.match(t);\n        /// String id = m.get(\"ID\");\n        /// </pre>\n        /// </remarks>\n        public virtual ParseTreePattern CompileParseTreePattern(string pattern, int patternRuleIndex)\n        {\n            if (((ITokenStream)InputStream) != null)\n            {\n                ITokenSource tokenSource = ((ITokenStream)InputStream).TokenSource;\n                if (tokenSource is Lexer)\n                {\n                    Lexer lexer = (Lexer)tokenSource;\n                    return CompileParseTreePattern(pattern, patternRuleIndex, lexer);\n                }\n            }\n            throw new NotSupportedException(\"Parser can't discover a lexer to use\");\n        }\n\n        /// <summary>\n        /// The same as\n        /// <see cref=\"CompileParseTreePattern(string, int)\"/>\n        /// but specify a\n        /// <see cref=\"Lexer\"/>\n        /// rather than trying to deduce it from this parser.\n        /// </summary>\n        public virtual ParseTreePattern CompileParseTreePattern(string pattern, int patternRuleIndex, Lexer lexer)\n        {\n            ParseTreePatternMatcher m = new ParseTreePatternMatcher(lexer, this);\n            return m.Compile(pattern, patternRuleIndex);\n        }\n\n        public virtual IAntlrErrorStrategy ErrorHandler\n        {\n            get\n            {\n                return _errHandler;\n            }\n            set\n            {\n                IAntlrErrorStrategy handler = value;\n                this._errHandler = handler;\n            }\n        }\n\n        public override IIntStream InputStream\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _input;\n\t\t\t}\n\t\t}\n\n\t\tpublic ITokenStream TokenStream\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _input;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tthis._input = null;\n\t\t\t\tReset ();\n\t\t\t\tthis._input = value;\n\t\t\t}\n\t\t}\n\n        /// <summary>\n        /// Match needs to return the current input symbol, which gets put\n        /// into the label for the associated token ref; e.g., x=ID.\n        /// </summary>\n        /// <remarks>\n        /// Match needs to return the current input symbol, which gets put\n        /// into the label for the associated token ref; e.g., x=ID.\n        /// </remarks>\n        public virtual IToken CurrentToken\n        {\n            get\n            {\n                return _input.LT(1);\n            }\n        }\n\n        public void NotifyErrorListeners(string msg)\n        {\n            NotifyErrorListeners(CurrentToken, msg, null);\n        }\n\n        public virtual void NotifyErrorListeners(IToken offendingToken, string msg, RecognitionException e)\n        {\n            _syntaxErrors++;\n            int line = -1;\n            int charPositionInLine = -1;\n            if (offendingToken != null)\n            {\n                line = offendingToken.Line;\n                charPositionInLine = offendingToken.Column;\n            }\n            IAntlrErrorListener<IToken> listener = ((IParserErrorListener)ErrorListenerDispatch);\n            listener.SyntaxError(ErrorOutput, this, offendingToken, line, charPositionInLine, msg, e);\n        }\n\n        /// <summary>\n        /// Consume and return the\n        /// <linkplain>\n        /// #getCurrentToken\n        /// current symbol\n        /// </linkplain>\n        /// .\n        /// <p>E.g., given the following input with\n        /// <c>A</c>\n        /// being the current\n        /// lookahead symbol, this function moves the cursor to\n        /// <c>B</c>\n        /// and returns\n        /// <c>A</c>\n        /// .</p>\n        /// <pre>\n        /// A B\n        /// ^\n        /// </pre>\n        /// If the parser is not in error recovery mode, the consumed symbol is added\n        /// to the parse tree using\n        /// <see cref=\"ParserRuleContext.AddChild(IToken)\"/>\n        /// , and\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTreeListener.VisitTerminal(Antlr4.Runtime.Tree.ITerminalNode)\"/>\n        /// is called on any parse listeners.\n        /// If the parser <em>is</em> in error recovery mode, the consumed symbol is\n        /// added to the parse tree using\n        /// <see cref=\"ParserRuleContext.AddErrorNode(IToken)\"/>\n        /// , and\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTreeListener.VisitErrorNode(Antlr4.Runtime.Tree.IErrorNode)\"/>\n        /// is called on any parse\n        /// listeners.\n        /// </summary>\n        public virtual IToken Consume()\n        {\n            IToken o = CurrentToken;\n            if (o.Type != Eof)\n            {\n                ((ITokenStream)InputStream).Consume();\n            }\n            bool hasListener = _parseListeners != null && _parseListeners.Count != 0;\n            if (_buildParseTrees || hasListener)\n            {\n                if (_errHandler.InErrorRecoveryMode(this))\n                {\n                    IErrorNode node = _ctx.AddErrorNode(o);\n                    if (_parseListeners != null)\n                    {\n                        foreach (IParseTreeListener listener in _parseListeners)\n                        {\n                            listener.VisitErrorNode(node);\n                        }\n                    }\n                }\n                else\n                {\n                    ITerminalNode node = _ctx.AddChild(o);\n                    if (_parseListeners != null)\n                    {\n                        foreach (IParseTreeListener listener in _parseListeners)\n                        {\n                            listener.VisitTerminal(node);\n                        }\n                    }\n                }\n            }\n            return o;\n        }\n\n        protected internal virtual void AddContextToParseTree()\n        {\n            ParserRuleContext parent = (ParserRuleContext)_ctx.Parent;\n            // add current context to parent if we have a parent\n            if (parent != null)\n            {\n                parent.AddChild(_ctx);\n            }\n        }\n\n        /// <summary>Always called by generated parsers upon entry to a rule.</summary>\n        /// <remarks>\n        /// Always called by generated parsers upon entry to a rule. Access field\n        /// <see cref=\"_ctx\"/>\n        /// get the current context.\n        /// </remarks>\n        public virtual void EnterRule(ParserRuleContext localctx, int state, int ruleIndex)\n        {\n            State = state;\n            _ctx = localctx;\n            _ctx.Start = _input.LT(1);\n            if (_buildParseTrees)\n            {\n                AddContextToParseTree();\n            }\n            if (_parseListeners != null)\n            {\n                TriggerEnterRuleEvent();\n            }\n        }\n\n        public virtual void EnterLeftFactoredRule(ParserRuleContext localctx, int state, int ruleIndex)\n        {\n            State = state;\n            if (_buildParseTrees)\n            {\n                ParserRuleContext factoredContext = (ParserRuleContext)_ctx.GetChild(_ctx.ChildCount - 1);\n                _ctx.RemoveLastChild();\n                factoredContext.Parent = localctx;\n                localctx.AddChild(factoredContext);\n            }\n            _ctx = localctx;\n            _ctx.Start = _input.LT(1);\n            if (_buildParseTrees)\n            {\n                AddContextToParseTree();\n            }\n            if (_parseListeners != null)\n            {\n                TriggerEnterRuleEvent();\n            }\n        }\n\n        public virtual void ExitRule()\n        {\n            _ctx.Stop = _input.LT(-1);\n            // trigger event on _ctx, before it reverts to parent\n            if (_parseListeners != null)\n            {\n                TriggerExitRuleEvent();\n            }\n            State = _ctx.invokingState;\n            _ctx = (ParserRuleContext)_ctx.Parent;\n        }\n\n        public virtual void EnterOuterAlt(ParserRuleContext localctx, int altNum)\n        {\n        \tlocalctx.setAltNumber(altNum);\n            // if we have new localctx, make sure we replace existing ctx\n            // that is previous child of parse tree\n            if (_buildParseTrees && _ctx != localctx)\n            {\n                ParserRuleContext parent = (ParserRuleContext)_ctx.Parent;\n                if (parent != null)\n                {\n                    parent.RemoveLastChild();\n                    parent.AddChild(localctx);\n                }\n            }\n            _ctx = localctx;\n        }\n\n        /// <summary>Get the precedence level for the top-most precedence rule.</summary>\n        /// <remarks>Get the precedence level for the top-most precedence rule.</remarks>\n        /// <returns>\n        /// The precedence level for the top-most precedence rule, or -1 if\n        /// the parser context is not nested within a precedence rule.\n        /// </returns>\n        public int Precedence\n        {\n            get\n            {\n                if (_precedenceStack.Count == 0)\n                {\n                    return -1;\n                }\n                return _precedenceStack[_precedenceStack.Count - 1];\n            }\n        }\n\n        [Obsolete(@\"UseEnterRecursionRule(ParserRuleContext, int, int, int) instead.\")]\n        public virtual void EnterRecursionRule(ParserRuleContext localctx, int ruleIndex)\n        {\n            EnterRecursionRule(localctx, Atn.ruleToStartState[ruleIndex].stateNumber, ruleIndex, 0);\n        }\n\n        public virtual void EnterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence)\n        {\n            State = state;\n            _precedenceStack.Add(precedence);\n            _ctx = localctx;\n            _ctx.Start = _input.LT(1);\n            if (_parseListeners != null)\n            {\n                TriggerEnterRuleEvent();\n            }\n        }\n\n        // simulates rule entry for left-recursive rules\n        /// <summary>\n        /// Like\n        /// <see cref=\"EnterRule(ParserRuleContext, int, int)\"/>\n        /// but for recursive rules.\n        /// </summary>\n        public virtual void PushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex)\n        {\n            ParserRuleContext previous = _ctx;\n            previous.Parent = localctx;\n            previous.invokingState = state;\n            previous.Stop = _input.LT(-1);\n            _ctx = localctx;\n            _ctx.Start = previous.Start;\n            if (_buildParseTrees)\n            {\n                _ctx.AddChild(previous);\n            }\n            if (_parseListeners != null)\n            {\n                TriggerEnterRuleEvent();\n            }\n        }\n\n        // simulates rule entry for left-recursive rules\n        public virtual void UnrollRecursionContexts(ParserRuleContext _parentctx)\n        {\n            _precedenceStack.RemoveAt(_precedenceStack.Count - 1);\n            _ctx.Stop = _input.LT(-1);\n            ParserRuleContext retctx = _ctx;\n            // save current ctx (return value)\n            // unroll so _ctx is as it was before call to recursive method\n            if (_parseListeners != null)\n            {\n                while (_ctx != _parentctx)\n                {\n                    TriggerExitRuleEvent();\n                    _ctx = (ParserRuleContext)_ctx.Parent;\n                }\n            }\n            else\n            {\n                _ctx = _parentctx;\n            }\n            // hook into tree\n            retctx.Parent = _parentctx;\n            if (_buildParseTrees && _parentctx != null)\n            {\n                // add return ctx into invoking rule's tree\n                _parentctx.AddChild(retctx);\n            }\n        }\n\n        public virtual ParserRuleContext GetInvokingContext(int ruleIndex)\n        {\n            ParserRuleContext p = _ctx;\n            while (p != null)\n            {\n                if (p.RuleIndex == ruleIndex)\n                {\n                    return p;\n                }\n                p = (ParserRuleContext)p.Parent;\n            }\n            return null;\n        }\n\n        public virtual ParserRuleContext Context\n        {\n            get\n            {\n                return _ctx;\n            }\n            set\n            {\n                ParserRuleContext ctx = value;\n                _ctx = ctx;\n            }\n        }\n\n        public override bool Precpred(RuleContext localctx, int precedence)\n        {\n            return precedence >= _precedenceStack[_precedenceStack.Count - 1];\n        }\n\n        public new IParserErrorListener ErrorListenerDispatch\n        {\n            get\n            {\n                return new ProxyParserErrorListener(ErrorListeners);\n            }\n        }\n\n        public virtual bool InContext(string context)\n        {\n            // TODO: useful in parser?\n            return false;\n        }\n\n        /// <summary>\n        /// Checks whether or not\n        /// <paramref name=\"symbol\"/>\n        /// can follow the current state in the\n        /// ATN. The behavior of this method is equivalent to the following, but is\n        /// implemented such that the complete context-sensitive follow set does not\n        /// need to be explicitly constructed.\n        /// <pre>\n        /// return getExpectedTokens().contains(symbol);\n        /// </pre>\n        /// </summary>\n        /// <param name=\"symbol\">the symbol type to check</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if\n        /// <paramref name=\"symbol\"/>\n        /// can follow the current state in\n        /// the ATN, otherwise\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public virtual bool IsExpectedToken(int symbol)\n        {\n            //   \t\treturn getInterpreter().atn.nextTokens(_ctx);\n            ATN atn = Interpreter.atn;\n            ParserRuleContext ctx = _ctx;\n            ATNState s = atn.states[State];\n            IntervalSet following = atn.NextTokens(s);\n            if (following.Contains(symbol))\n            {\n                return true;\n            }\n            //        System.out.println(\"following \"+s+\"=\"+following);\n            if (!following.Contains(TokenConstants.EPSILON))\n            {\n                return false;\n            }\n            while (ctx != null && ctx.invokingState >= 0 && following.Contains(TokenConstants.EPSILON))\n            {\n                ATNState invokingState = atn.states[ctx.invokingState];\n                RuleTransition rt = (RuleTransition)invokingState.Transition(0);\n                following = atn.NextTokens(rt.followState);\n                if (following.Contains(symbol))\n                {\n                    return true;\n                }\n                ctx = (ParserRuleContext)ctx.Parent;\n            }\n            if (following.Contains(TokenConstants.EPSILON) && symbol == TokenConstants.EOF)\n            {\n                return true;\n            }\n            return false;\n        }\n\n        /// <summary>\n        /// Computes the set of input symbols which could follow the current parser\n        /// state and context, as given by\n        /// <see cref=\"Recognizer{Symbol, ATNInterpreter}.State()\"/>\n        /// and\n        /// <see cref=\"Context()\"/>\n        /// ,\n        /// respectively.\n        /// </summary>\n        /// <seealso cref=\"Antlr4.Runtime.Atn.ATN.GetExpectedTokens(int, RuleContext)\"/>\n        [return: NotNull]\n        public virtual IntervalSet GetExpectedTokens()\n        {\n            return Atn.GetExpectedTokens(State, Context);\n        }\n\n        [return: NotNull]\n        public virtual IntervalSet GetExpectedTokensWithinCurrentRule()\n        {\n            ATN atn = Interpreter.atn;\n            ATNState s = atn.states[State];\n            return atn.NextTokens(s);\n        }\n\n        /// <summary>\n        /// Get a rule's index (i.e.,\n        /// <c>RULE_ruleName</c>\n        /// field) or -1 if not found.\n        /// </summary>\n        public virtual int GetRuleIndex(string ruleName)\n        {\n            int ruleIndex;\n            if (RuleIndexMap.TryGetValue(ruleName, out ruleIndex))\n            {\n                return ruleIndex;\n            }\n            return -1;\n        }\n\n        public virtual ParserRuleContext RuleContext\n        {\n            get\n            {\n                return _ctx;\n            }\n        }\n\n        /// <summary>\n        /// Return List&lt;String&gt; of the rule names in your parser instance\n        /// leading up to a call to the current rule.\n        /// </summary>\n        /// <remarks>\n        /// Return List&lt;String&gt; of the rule names in your parser instance\n        /// leading up to a call to the current rule.  You could override if\n        /// you want more details such as the file/line info of where\n        /// in the ATN a rule is invoked.\n        /// This is very useful for error messages.\n        /// </remarks>\n        public virtual IList<string> GetRuleInvocationStack()\n        {\n            return GetRuleInvocationStack(_ctx);\n        }\n\n\t\tpublic virtual string GetRuleInvocationStackAsString()\n\t\t{\n\t\t\tStringBuilder sb = new StringBuilder (\"[\");\n\t\t\tforeach (string s in GetRuleInvocationStack()) {\n\t\t\t\tsb.Append (s);\n\t\t\t\tsb.Append (\", \");\n\t\t\t}\n\t\t\tsb.Length = sb.Length - 2;\n\t\t\tsb.Append (\"]\");\n\t\t\treturn sb.ToString ();\n\t\t}\n\n        public virtual IList<string> GetRuleInvocationStack(RuleContext p)\n        {\n            string[] ruleNames = RuleNames;\n            IList<string> stack = new List<string>();\n            while (p != null)\n            {\n                // compute what follows who invoked us\n                int ruleIndex = p.RuleIndex;\n                if (ruleIndex < 0)\n                {\n                    stack.Add(\"n/a\");\n                }\n                else\n                {\n                    stack.Add(ruleNames[ruleIndex]);\n                }\n                p = p.Parent;\n            }\n            return stack;\n        }\n\n        /// <summary>For debugging and other purposes.</summary>\n        /// <remarks>For debugging and other purposes.</remarks>\n        public virtual IList<string> GetDFAStrings()\n        {\n            IList<string> s = new List<string>();\n            for (int d = 0; d < Interpreter.atn.decisionToDFA.Length; d++)\n            {\n\t\t\t\tDFA dfa = Interpreter.atn.decisionToDFA[d];\n                s.Add(dfa.ToString(Vocabulary));\n            }\n            return s;\n        }\n\n        /// <summary>For debugging and other purposes.</summary>\n        /// <remarks>For debugging and other purposes.</remarks>\n        public virtual void DumpDFA()\n        {\n            bool seenOne = false;\n\t\t\tfor (int d = 0; d < Interpreter.decisionToDFA.Length; d++)\n            {\n\t\t\t\tDFA dfa = Interpreter.decisionToDFA[d];\n\t\t\t\tif (dfa.states.Count>0)\n                {\n                    if (seenOne)\n                    {\n                        Output.WriteLine();\n                    }\n                    Output.WriteLine(\"Decision \" + dfa.decision + \":\");\n                    Output.Write(dfa.ToString(Vocabulary));\n                    seenOne = true;\n                }\n            }\n        }\n\n        public virtual string SourceName\n        {\n            get\n            {\n                return _input.SourceName;\n            }\n        }\n\n        public override ParseInfo ParseInfo\n        {\n            get\n            {\n                ParserATNSimulator interp = Interpreter;\n                if (interp is ProfilingATNSimulator)\n                {\n                    return new ParseInfo((ProfilingATNSimulator)interp);\n                }\n                return null;\n            }\n        }\n\n        /// <since>4.3</since>\n        public virtual bool Profile\n        {\n            set\n            {\n                bool profile = value;\n                ParserATNSimulator interp = Interpreter;\n                if (profile)\n                {\n                    if (!(interp is ProfilingATNSimulator))\n                    {\n                        Interpreter = new ProfilingATNSimulator(this);\n                    }\n                }\n                else\n                {\n                    if (interp is ProfilingATNSimulator)\n                    {\n                        Interpreter = new ParserATNSimulator(this, Atn, null, null);\n                    }\n                }\n            }\n        }\n\n        /// <summary>\n        /// During a parse is sometimes useful to listen in on the rule entry and exit\n        /// events as well as token matches.\n        /// </summary>\n        /// <remarks>\n        /// During a parse is sometimes useful to listen in on the rule entry and exit\n        /// events as well as token matches. This is for quick and dirty debugging.\n        /// </remarks>\n        public virtual bool Trace\n        {\n            get\n            {\n                foreach (object o in ParseListeners)\n                {\n                    if (o is Parser.TraceListener)\n                    {\n                        return true;\n                    }\n                }\n                return false;\n            }\n            set\n            {\n                bool trace = value;\n                if (!trace)\n                {\n                    RemoveParseListener(_tracer);\n                    _tracer = null;\n                }\n                else\n                {\n                    if (_tracer != null)\n                    {\n                        RemoveParseListener(_tracer);\n                    }\n                    else\n                    {\n                        _tracer = new Parser.TraceListener(this);\n                    }\n                    AddParseListener(_tracer);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ParserInterpreter.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// A parser simulator that mimics what ANTLR's generated\n    /// parser code does.\n    /// </summary>\n    /// <remarks>\n    /// A parser simulator that mimics what ANTLR's generated\n    /// parser code does. A ParserATNSimulator is used to make\n    /// predictions via adaptivePredict but this class moves a pointer through the\n    /// ATN to simulate parsing. ParserATNSimulator just\n    /// makes us efficient rather than having to backtrack, for example.\n    /// This properly creates parse trees even for left recursive rules.\n    /// We rely on the left recursive rule invocation and special predicate\n    /// transitions to make left recursive rules work.\n    /// See TestParserInterpreter for examples.\n    /// </remarks>\n    public class ParserInterpreter : Parser\n    {\n        private readonly string _grammarFileName;\n\n        private readonly ATN _atn;\n\t\t\n        private readonly Dfa.DFA[] _decisionToDFA;\n\n        protected internal readonly BitSet pushRecursionContextStates;\n\n\t\tprivate readonly string[] _ruleNames;\n\n        [NotNull]\n        private readonly IVocabulary vocabulary;\n\n        private readonly Stack<Tuple<ParserRuleContext, int>> _parentContextStack = new Stack<Tuple<ParserRuleContext, int>>();\n\n        public ParserInterpreter(string grammarFileName, IVocabulary vocabulary, IEnumerable<string> ruleNames, ATN atn, ITokenStream input)\n            : base(input)\n        {\n            this._grammarFileName = grammarFileName;\n            this._atn = atn;\n            this._ruleNames = ruleNames.ToArray();\n            this.vocabulary = vocabulary;\n            // identify the ATN states where pushNewRecursionContext must be called\n            this.pushRecursionContextStates = new BitSet(atn.states.Count);\n            foreach (ATNState state in atn.states)\n            {\n                if (!(state is StarLoopEntryState))\n                {\n                    continue;\n                }\n\t\t\t\tif (((StarLoopEntryState)state).isPrecedenceDecision)\n                {\n                    this.pushRecursionContextStates.Set(state.stateNumber);\n                }\n            }\n\t\t\t\n            //init decision DFA\n            int numberofDecisions = atn.NumberOfDecisions;\n            this._decisionToDFA = new Dfa.DFA[numberofDecisions];\n            for (int i = 0; i < numberofDecisions; i++)\n            {\n                DecisionState decisionState = atn.GetDecisionState(i);\n                _decisionToDFA[i] = new Dfa.DFA(decisionState, i);\n            }\n             // get atn simulator that knows how to do predictions\n            Interpreter = new ParserATNSimulator(this, atn, _decisionToDFA, null);\n        }\n\n        public override ATN Atn\n        {\n            get\n            {\n                return _atn;\n            }\n        }\n\n        public override IVocabulary Vocabulary\n        {\n            get\n            {\n                return vocabulary;\n            }\n        }\n\n        public override string[] RuleNames\n        {\n            get\n            {\n                return _ruleNames;\n            }\n        }\n\n        public override string GrammarFileName\n        {\n            get\n            {\n                return _grammarFileName;\n            }\n        }\n\n        /// <summary>Begin parsing at startRuleIndex</summary>\n        public virtual ParserRuleContext Parse(int startRuleIndex)\n        {\n            RuleStartState startRuleStartState = _atn.ruleToStartState[startRuleIndex];\n            InterpreterRuleContext rootContext = new InterpreterRuleContext(null, ATNState.InvalidStateNumber, startRuleIndex);\n            if (startRuleStartState.isPrecedenceRule)\n            {\n                EnterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0);\n            }\n            else\n            {\n                EnterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex);\n            }\n            while (true)\n            {\n                ATNState p = AtnState;\n                switch (p.StateType)\n                {\n                    case StateType.RuleStop:\n                    {\n                        // pop; return from rule\n\t\t\t\t\t\tif (RuleContext.IsEmpty)\n                        {\n                            if (startRuleStartState.isPrecedenceRule)\n                            {\n\t\t\t\t\t\t\t\tParserRuleContext result = RuleContext;\n                                Tuple<ParserRuleContext, int> parentContext = _parentContextStack.Pop();\n                                UnrollRecursionContexts(parentContext.Item1);\n                                return result;\n                            }\n                            else\n                            {\n                                ExitRule();\n                                return rootContext;\n                            }\n                        }\n                        VisitRuleStopState(p);\n                        break;\n                    }\n\n                    default:\n                    {\n                        try\n                        {\n                            VisitState(p);\n                        }\n                        catch (RecognitionException e)\n                        {\n                            State = _atn.ruleToStopState[p.ruleIndex].stateNumber;\n                            Context.exception = e;\n                            ErrorHandler.ReportError(this, e);\n                            ErrorHandler.Recover(this, e);\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n\n        public override void EnterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence)\n        {\n\t\t\t_parentContextStack.Push(Tuple.Create(RuleContext, localctx.invokingState));\n            base.EnterRecursionRule(localctx, state, ruleIndex, precedence);\n        }\n\n        protected internal virtual ATNState AtnState\n        {\n            get\n            {\n                return _atn.states[State];\n            }\n        }\n\n        protected internal virtual void VisitState(ATNState p)\n        {\n            int edge;\n            if (p.NumberOfTransitions > 1)\n            {\n                ErrorHandler.Sync(this);\n\t\t\t\tedge = Interpreter.AdaptivePredict(TokenStream, ((DecisionState)p).decision, RuleContext);\n            }\n            else\n            {\n                edge = 1;\n            }\n            Transition transition = p.Transition(edge - 1);\n            switch (transition.TransitionType)\n            {\n                case TransitionType.EPSILON:\n                {\n                    if (pushRecursionContextStates.Get(p.stateNumber) && !(transition.target is LoopEndState))\n                    {\n\t\t\t\t\t\tInterpreterRuleContext ctx = new InterpreterRuleContext(_parentContextStack.Peek().Item1, _parentContextStack.Peek().Item2, RuleContext.RuleIndex);\n\t\t\t\t\t\tPushNewRecursionContext(ctx, _atn.ruleToStartState[p.ruleIndex].stateNumber, RuleContext.RuleIndex);\n                    }\n                    break;\n                }\n\n                case TransitionType.ATOM:\n                {\n\t\t\t\t\tMatch(((AtomTransition)transition).token);\n                    break;\n                }\n\n                case TransitionType.RANGE:\n                case TransitionType.SET:\n                case TransitionType.NOT_SET:\n                {\n                    if (!transition.Matches(TokenStream.LA(1), TokenConstants.MinUserTokenType, 65535))\n                    {\n\t\t\t\t\t\tErrorHandler.RecoverInline(this);\n                    }\n                    MatchWildcard();\n                    break;\n                }\n\n                case TransitionType.WILDCARD:\n                {\n                    MatchWildcard();\n                    break;\n                }\n\n                case TransitionType.RULE:\n                {\n                    RuleStartState ruleStartState = (RuleStartState)transition.target;\n                    int ruleIndex = ruleStartState.ruleIndex;\n\t\t\t\t\tInterpreterRuleContext ctx_1 = new InterpreterRuleContext(RuleContext, p.stateNumber, ruleIndex);\n                    if (ruleStartState.isPrecedenceRule)\n                    {\n                        EnterRecursionRule(ctx_1, ruleStartState.stateNumber, ruleIndex, ((RuleTransition)transition).precedence);\n                    }\n                    else\n                    {\n                        EnterRule(ctx_1, transition.target.stateNumber, ruleIndex);\n                    }\n                    break;\n                }\n\n                case TransitionType.PREDICATE:\n                {\n                    PredicateTransition predicateTransition = (PredicateTransition)transition;\n\t\t\t\t\tif (!Sempred(RuleContext, predicateTransition.ruleIndex, predicateTransition.predIndex))\n                    {\n                        throw new FailedPredicateException(this);\n                    }\n                    break;\n                }\n\n                case TransitionType.ACTION:\n                {\n                    ActionTransition actionTransition = (ActionTransition)transition;\n\t\t\t\t\tAction(RuleContext, actionTransition.ruleIndex, actionTransition.actionIndex);\n                    break;\n                }\n\n                case TransitionType.PRECEDENCE:\n                {\n\t\t\t\t\tif (!Precpred(RuleContext, ((PrecedencePredicateTransition)transition).precedence))\n                    {\n                        throw new FailedPredicateException(this, string.Format(\"precpred(_ctx, {0})\", ((PrecedencePredicateTransition)transition).precedence));\n                    }\n                    break;\n                }\n\n                default:\n                {\n                    throw new NotSupportedException(\"Unrecognized ATN transition type.\");\n                }\n            }\n            State = transition.target.stateNumber;\n        }\n\n        protected internal virtual void VisitRuleStopState(ATNState p)\n        {\n            RuleStartState ruleStartState = _atn.ruleToStartState[p.ruleIndex];\n            if (ruleStartState.isPrecedenceRule)\n            {\n                Tuple<ParserRuleContext, int> parentContext = _parentContextStack.Pop();\n                UnrollRecursionContexts(parentContext.Item1);\n                State = parentContext.Item2;\n            }\n            else\n            {\n                ExitRule();\n            }\n            RuleTransition ruleTransition = (RuleTransition)_atn.states[State].Transition(0);\n            State = ruleTransition.followState.stateNumber;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ParserRuleContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>A rule invocation record for parsing.</summary>\n    /// <remarks>\n    /// A rule invocation record for parsing.\n    /// Contains all of the information about the current rule not stored in the\n    /// RuleContext. It handles parse tree children list, Any ATN state\n    /// tracing, and the default values available for rule indications:\n    /// start, stop, rule index, current alt number, current\n    /// ATN state.\n    /// Subclasses made for each rule and grammar track the parameters,\n    /// return values, locals, and labels specific to that rule. These\n    /// are the objects that are returned from rules.\n    /// Note text is not an actual field of a rule return value; it is computed\n    /// from start and stop using the input stream's toString() method.  I\n    /// could add a ctor to this so that we can pass in and store the input\n    /// stream, but I'm not sure we want to do that.  It would seem to be undefined\n    /// to get the .text property anyway if the rule matches tokens from multiple\n    /// input streams.\n    /// I do not use getters for fields of objects that are used simply to\n    /// group values such as this aggregate.  The getters/setters are there to\n    /// satisfy the superclass interface.\n    /// </remarks>\n    public class ParserRuleContext : RuleContext\n    {\n        public static readonly Antlr4.Runtime.ParserRuleContext EMPTY = new Antlr4.Runtime.ParserRuleContext();\n\n        /// <summary>\n        /// If we are debugging or building a parse tree for a visitor,\n        /// we need to track all of the tokens and rule invocations associated\n        /// with this rule's context.\n        /// </summary>\n        /// <remarks>\n        /// If we are debugging or building a parse tree for a visitor,\n        /// we need to track all of the tokens and rule invocations associated\n        /// with this rule's context. This is empty for parsing w/o tree constr.\n        /// operation because we don't the need to track the details about\n        /// how we parse this rule.\n        /// </remarks>\n        public IList<IParseTree> children;\n\n        /// <summary>\n        /// For debugging/tracing purposes, we want to track all of the nodes in\n        /// the ATN traversed by the parser for a particular rule.\n        /// </summary>\n        /// <remarks>\n        /// For debugging/tracing purposes, we want to track all of the nodes in\n        /// the ATN traversed by the parser for a particular rule.\n        /// This list indicates the sequence of ATN nodes used to match\n        /// the elements of the children list. This list does not include\n        /// ATN nodes and other rules used to match rule invocations. It\n        /// traces the rule invocation node itself but nothing inside that\n        /// other rule's ATN submachine.\n        /// There is NOT a one-to-one correspondence between the children and\n        /// states list. There are typically many nodes in the ATN traversed\n        /// for each element in the children list. For example, for a rule\n        /// invocation there is the invoking state and the following state.\n        /// The parser setState() method updates field s and adds it to this list\n        /// if we are debugging/tracing.\n        /// This does not trace states visited during prediction.\n        /// </remarks>\n        private IToken _start;\n\n        /// <summary>\n        /// For debugging/tracing purposes, we want to track all of the nodes in\n        /// the ATN traversed by the parser for a particular rule.\n        /// </summary>\n        /// <remarks>\n        /// For debugging/tracing purposes, we want to track all of the nodes in\n        /// the ATN traversed by the parser for a particular rule.\n        /// This list indicates the sequence of ATN nodes used to match\n        /// the elements of the children list. This list does not include\n        /// ATN nodes and other rules used to match rule invocations. It\n        /// traces the rule invocation node itself but nothing inside that\n        /// other rule's ATN submachine.\n        /// There is NOT a one-to-one correspondence between the children and\n        /// states list. There are typically many nodes in the ATN traversed\n        /// for each element in the children list. For example, for a rule\n        /// invocation there is the invoking state and the following state.\n        /// The parser setState() method updates field s and adds it to this list\n        /// if we are debugging/tracing.\n        /// This does not trace states visited during prediction.\n        /// </remarks>\n        private IToken _stop;\n\n        /// <summary>The exception that forced this rule to return.</summary>\n        /// <remarks>\n        /// The exception that forced this rule to return. If the rule successfully\n        /// completed, this is\n        /// <see langword=\"null\"/>\n        /// .\n        /// </remarks>\n        public RecognitionException exception;\n\n        public ParserRuleContext()\n        {\n        }\n\n        public static Antlr4.Runtime.ParserRuleContext EmptyContext\n        {\n            get\n            {\n                //\tpublic List<Integer> states;\n                return EMPTY;\n            }\n        }\n\n        /// <summary>\n        /// COPY a ctx (I'm deliberately not using copy constructor) to avoid\n        /// confusion with creating node with parent. Does not copy children.\n        ///\n        /// This is used in the generated parser code to flip a generic XContext\n        /// node for rule X to a YContext for alt label Y. In that sense, it is\n        /// not really a generic copy function.\n        ///\n        /// If we do an error sync() at start of a rule, we might add error nodes\n        /// to the generic XContext so this function must copy those nodes to\n        /// the YContext as well else they are lost!\n        /// </summary>\n        public virtual void CopyFrom(Antlr4.Runtime.ParserRuleContext ctx)\n        {\n            // from RuleContext\n            this.Parent = ctx.Parent;\n            this.invokingState = ctx.invokingState;\n            this._start = ctx._start;\n            this._stop = ctx._stop;\n\n            // copy any error nodes to alt label node\n            if (ctx.children != null)\n            {\n                children = new List<IParseTree>();\n                // reset parent pointer for any error nodes\n                foreach (var child in ctx.children)\n                {\n                    var errorChildNode = child as ErrorNodeImpl;\n                    if (errorChildNode != null)\n                    {\n                        children.Add(errorChildNode);\n                        errorChildNode.Parent = this;\n                    }\n                }\n            }\n        }\n\n        public ParserRuleContext(Antlr4.Runtime.ParserRuleContext parent, int invokingStateNumber)\n            : base(parent, invokingStateNumber)\n        {\n        }\n\n        // Double dispatch methods for listeners\n        public virtual void EnterRule(IParseTreeListener listener)\n        {\n        }\n\n        public virtual void ExitRule(IParseTreeListener listener)\n        {\n        }\n\n        /// <summary>Does not set parent link; other add methods do that</summary>\n        public virtual void AddChild(ITerminalNode t)\n        {\n            if (children == null)\n            {\n                children = new List<IParseTree>();\n            }\n\n            children.Add(t);\n        }\n\n        public virtual void AddChild(RuleContext ruleInvocation)\n        {\n            if (children == null)\n            {\n                children = new List<IParseTree>();\n            }\n\n            children.Add(ruleInvocation);\n        }\n\n        /// <summary>\n        /// Used by enterOuterAlt to toss out a RuleContext previously added as\n        /// we entered a rule.\n        /// </summary>\n        /// <remarks>\n        /// Used by enterOuterAlt to toss out a RuleContext previously added as\n        /// we entered a rule. If we have # label, we will need to remove\n        /// generic ruleContext object.\n        /// </remarks>\n        public virtual void RemoveLastChild()\n        {\n            if (children != null)\n            {\n                children.RemoveAt(children.Count - 1);\n            }\n        }\n\n        //\tpublic void trace(int s) {\n        //\t\tif ( states==null ) states = new ArrayList<Integer>();\n        //\t\tstates.add(s);\n        //\t}\n        public virtual ITerminalNode AddChild(IToken matchedToken)\n        {\n            TerminalNodeImpl t = new TerminalNodeImpl(matchedToken);\n            AddChild(t);\n            t.Parent = this;\n            return t;\n        }\n\n        public virtual IErrorNode AddErrorNode(IToken badToken)\n        {\n            ErrorNodeImpl t = new ErrorNodeImpl(badToken);\n            AddChild(t);\n            t.Parent = this;\n            return t;\n        }\n\n\n        public override IParseTree GetChild(int i)\n        {\n            return children != null && i >= 0 && i < children.Count ? children[i] : null;\n        }\n\n        public virtual T GetChild<T>(int i)\n            where T : IParseTree\n        {\n            if (children == null || i < 0 || i >= children.Count)\n            {\n                return default(T);\n            }\n\n            int j = -1;\n            // what element have we found with ctxType?\n            foreach (IParseTree o in children)\n            {\n                if (o is T)\n                {\n                    j++;\n                    if (j == i)\n                    {\n                        return (T) o;\n                    }\n                }\n            }\n\n            return default(T);\n        }\n\n        public virtual ITerminalNode GetToken(int ttype, int i)\n        {\n            if (children == null || i < 0 || i >= children.Count)\n            {\n                return null;\n            }\n\n            int j = -1;\n            // what token with ttype have we found?\n            foreach (IParseTree o in children)\n            {\n                if (o is ITerminalNode)\n                {\n                    ITerminalNode tnode = (ITerminalNode) o;\n                    IToken symbol = tnode.Symbol;\n                    if (symbol.Type == ttype)\n                    {\n                        j++;\n                        if (j == i)\n                        {\n                            return tnode;\n                        }\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        public virtual ITerminalNode[] GetTokens(int ttype)\n        {\n            if (children == null)\n            {\n                return Collections.EmptyList<ITerminalNode>();\n            }\n\n            List<ITerminalNode> tokens = null;\n            foreach (IParseTree o in children)\n            {\n                if (o is ITerminalNode)\n                {\n                    ITerminalNode tnode = (ITerminalNode) o;\n                    IToken symbol = tnode.Symbol;\n                    if (symbol.Type == ttype)\n                    {\n                        if (tokens == null)\n                        {\n                            tokens = new List<ITerminalNode>();\n                        }\n\n                        tokens.Add(tnode);\n                    }\n                }\n            }\n\n            if (tokens == null)\n            {\n                return Collections.EmptyList<ITerminalNode>();\n            }\n\n            return tokens.ToArray();\n        }\n\n        public virtual T GetRuleContext<T>(int i)\n            where T : Antlr4.Runtime.ParserRuleContext\n        {\n            return GetChild<T>(i);\n        }\n\n        public virtual T[] GetRuleContexts<T>()\n            where T : Antlr4.Runtime.ParserRuleContext\n        {\n            if (children == null)\n            {\n                return Collections.EmptyList<T>();\n            }\n\n            List<T> contexts = null;\n            foreach (IParseTree o in children)\n            {\n                if (o is T)\n                {\n                    if (contexts == null)\n                    {\n                        contexts = new List<T>();\n                    }\n\n                    contexts.Add((T) o);\n                }\n            }\n\n            if (contexts == null)\n            {\n                return Collections.EmptyList<T>();\n            }\n\n            return contexts.ToArray();\n        }\n\n        public override int ChildCount\n        {\n            get { return children != null ? children.Count : 0; }\n        }\n\n        public override Interval SourceInterval\n        {\n            get\n            {\n                if (_start == null || _stop == null)\n                {\n                    return Interval.Invalid;\n                }\n\n                return Interval.Of(_start.TokenIndex, _stop.TokenIndex);\n            }\n        }\n\n        public virtual IToken Start\n        {\n            get { return _start; }\n            set { _start = value; }\n        }\n\n        public virtual IToken Stop\n        {\n            get { return _stop; }\n            set { _stop = value; }\n        }\n\n        /// <summary>Used for rule context info debugging during parse-time, not so much for ATN debugging</summary>\n        public virtual string ToInfoString(Parser recognizer)\n        {\n            List<string> rules = new List<string>(recognizer.GetRuleInvocationStack(this));\n            rules.Reverse();\n            return \"ParserRuleContext\" + rules + \"{\" + \"start=\" + _start + \", stop=\" + _stop + '}';\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Properties/AssemblyInfo.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Reflection;\n\n[assembly: CLSCompliant(true)]\n[assembly: AssemblyVersion(\"4.13.2\")]\n"
  },
  {
    "path": "runtime/CSharp/src/ProxyErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This implementation of\n    /// <see cref=\"IAntlrErrorListener{Symbol}\"/>\n    /// dispatches all calls to a\n    /// collection of delegate listeners. This reduces the effort required to support multiple\n    /// listeners.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    public class ProxyErrorListener<Symbol> : IAntlrErrorListener<Symbol>\n    {\n        private readonly IEnumerable<IAntlrErrorListener<Symbol>> delegates;\n\n        public ProxyErrorListener(IEnumerable<IAntlrErrorListener<Symbol>> delegates)\n        {\n            if (delegates == null)\n            {\n                throw new ArgumentNullException(\"delegates\");\n            }\n            this.delegates = delegates;\n        }\n\n        protected internal virtual IEnumerable<IAntlrErrorListener<Symbol>> Delegates\n        {\n            get\n            {\n                return delegates;\n            }\n        }\n\n        public virtual void SyntaxError(TextWriter output, IRecognizer recognizer, Symbol offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)\n        {\n            foreach (IAntlrErrorListener<Symbol> listener in delegates)\n            {\n                listener.SyntaxError(output, recognizer, offendingSymbol, line, charPositionInLine, msg, e);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/ProxyParserErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Dfa;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <author>Sam Harwell</author>\n    public class ProxyParserErrorListener : ProxyErrorListener<IToken>, IParserErrorListener\n    {\n        public ProxyParserErrorListener(ICollection<IAntlrErrorListener<IToken>> delegates)\n            : base(delegates)\n        {\n        }\n\n        public virtual void ReportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, bool exact, BitSet ambigAlts, ATNConfigSet configs)\n        {\n            foreach (IAntlrErrorListener<IToken> listener in Delegates)\n            {\n                if (!(listener is IParserErrorListener))\n                {\n                    continue;\n                }\n                IParserErrorListener parserErrorListener = (IParserErrorListener)listener;\n                parserErrorListener.ReportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs);\n            }\n        }\n\n        public virtual void ReportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs)\n        {\n            foreach (IAntlrErrorListener<IToken> listener in Delegates)\n            {\n                if (!(listener is IParserErrorListener))\n                {\n                    continue;\n                }\n                IParserErrorListener parserErrorListener = (IParserErrorListener)listener;\n                parserErrorListener.ReportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs);\n            }\n        }\n\n        public virtual void ReportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs)\n        {\n            foreach (IAntlrErrorListener<IToken> listener in Delegates)\n            {\n                if (!(listener is IParserErrorListener))\n                {\n                    continue;\n                }\n                IParserErrorListener parserErrorListener = (IParserErrorListener)listener;\n                parserErrorListener.ReportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/README.md",
    "content": "# C# target for ANTLR 4\n\n### Note to historical users\n\nVersions of ANTLR 4.4.x and before managed the C#\ntarget as part of a [separate tool provided by Sam Harwell](https://github.com/tunnelvisionlabs/antlr4cs/releases/tag/v4.6.6).\nAs of 4.5, we our releasing a (mono-compatible) C# target together\nwith the main tool.\n\nThe current version is written using netstandard2.0 and netstandard2.1, it's possible\nto use it on different platforms (Windows, MacOS X, Linux, and other).\n\nReleasing the runtime with the tool ensures that you can get the exact same behavior across many languages: Java, C#, Python, JavaScript, Go, Swift and C++.\n\n## Getting Started\n\n### Step 1: Install Java\n\nThe C# target for ANTLR 4 requires Java for *generating* C# code (but the applications compiled from this C# code will not require Java to be installed).\nYou can install *any* of the following versions of Java to use this target.\n\nIf you already have one of the following installed, you should check to make sure the installation is up-to-date.\n\n* Java 8 runtime environment (x86 or x64)\n* Java 8 development kit (x86 or x64, provided that the JRE option is also installed during the development kit installation)\n* Java 7 runtime environment (x86 or x64)\n* Java 7 development kit (x86 or x64, provided that the JRE option is also installed during the development kit installation)\n\n### Step 2: Download the tool\n\nYou need to download the ANTLR tool from the ANTLR web site.\nThis is a Java archive (*.jar) used to generate the C# code from an ANTLR grammar.\n\n\n### Step 3: Add or create a grammar file (*.g4) in your project\n\nTo avoid confusing your IDE, we suggest setting the build action to None for this file.\nSee the docs and the book to learn about writing lexer and parser grammars.\n\n\n### Step 4: Generate the C# code\n\nThis can be done either from the cmd line, or by adding a custom pre-build command in your project.\nAt minimal, the cmd line should look as follows: ``java -jar antlr4-4.13.2.jar -Dlanguage=CSharp grammar.g4``\nThis will generate the files, which you can then integrate in your project.\nThis is just a quick start. The tool has many useful options to control generation, please refer to its documentation.\n\n### Step 5: Add a reference to the ANTLR runtime in your project\n\nThe Antlr 4 standard runtime for C# is now available from NuGet.\nWe trust that you know how to do add NuGet references to your project :-).\nThe package id is [Antlr4.Runtime.Standard](https://www.nuget.org/packages/Antlr4.Runtime.Standard/). We do not support other packages.\n\nUse the GUI or the following command in the Package Manager Console:\n\n```\nInstall-Package Antlr4.Runtime.Standard\n```\n\n### Step 6: You're done!\n\nOf course, the generated code is not going to meet your requirement by magic.\nThere are 3 ways to use the generated code:\n - by generating a parse tree, and traversing it using a listener. This is the most common method.\n - by generating a parse tree, and traversing it using a visitor. This requires the `-visitor` option, and is a bit more work.\n - by providing code within your grammar, which gets executed when your input files are parsed.\nWhile the latter works, it is no longer the recommended approach, because it is not portable, and harder to maintain. More importantly, it breaks the parsing when your code breaks.\n\nSee the web site for examples of using the generated code.\n\nTo learn more about ANTLR 4, read [the book](http://a.co/2n4rJlb).\n\n### Visual Studio integration\n\nIf you require tighter Visual Studio integration, you can use the tools from [Tunnel Vision Labs](http://tunnelvisionlabs.com/).\n(please note however that they use a different tool and runtime)\n\n"
  },
  {
    "path": "runtime/CSharp/src/RecognitionException.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>The root of the ANTLR exception hierarchy.</summary>\n    /// <remarks>\n    /// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n    /// 3 kinds of errors: prediction errors, failed predicate errors, and\n    /// mismatched input errors. In each case, the parser knows where it is\n    /// in the input, where it is in the ATN, the rule invocation stack,\n    /// and what kind of problem occurred.\n    /// </remarks>\n    [System.Serializable]\n    public class RecognitionException : Exception\n    {\n        private const long serialVersionUID = -3861826954750022374L;\n\n        /// <summary>\n        /// The\n        /// <see cref=\"IRecognizer\"/>\n        /// where this exception originated.\n        /// </summary>\n        [Nullable]\n        private readonly IRecognizer recognizer;\n\n        [Nullable]\n        private readonly RuleContext ctx;\n\n        [Nullable]\n        private readonly IIntStream input;\n\n        /// <summary>\n        /// The current\n        /// <see cref=\"IToken\"/>\n        /// when an error occurred. Since not all streams\n        /// support accessing symbols by index, we have to track the\n        /// <see cref=\"IToken\"/>\n        /// instance itself.\n        /// </summary>\n        private IToken offendingToken;\n\n        private int offendingState = -1;\n\n        public RecognitionException(Lexer lexer, ICharStream input)\n        {\n            this.recognizer = lexer;\n            this.input = input;\n            this.ctx = null;\n        }\n\n        public RecognitionException(IRecognizer recognizer, IIntStream input, ParserRuleContext ctx)\n        {\n            this.recognizer = recognizer;\n            this.input = input;\n            this.ctx = ctx;\n            if (recognizer != null)\n            {\n                this.offendingState = recognizer.State;\n            }\n        }\n\n        public RecognitionException(string message, IRecognizer recognizer, IIntStream input, ParserRuleContext ctx)\n            : base(message)\n        {\n            this.recognizer = recognizer;\n            this.input = input;\n            this.ctx = ctx;\n            if (recognizer != null)\n            {\n                this.offendingState = recognizer.State;\n            }\n        }\n\n        /// <summary>\n        /// Get the ATN state number the parser was in at the time the error\n        /// occurred.\n        /// </summary>\n        /// <remarks>\n        /// Get the ATN state number the parser was in at the time the error\n        /// occurred. For\n        /// <see cref=\"NoViableAltException\"/>\n        /// and\n        /// <see cref=\"LexerNoViableAltException\"/>\n        /// exceptions, this is the\n        /// <see cref=\"Antlr4.Runtime.Atn.DecisionState\"/>\n        /// number. For others, it is the state whose outgoing\n        /// edge we couldn't match.\n        /// <p>If the state number is not known, this method returns -1.</p>\n        /// </remarks>\n        public int OffendingState\n        {\n            get\n            {\n                return offendingState;\n            }\n            protected set\n            {\n                int offendingState = value;\n                this.offendingState = offendingState;\n            }\n        }\n\n        /// <summary>\n        /// Gets the set of input symbols which could potentially follow the\n        /// previously matched symbol at the time this exception was thrown.\n        /// </summary>\n        /// <remarks>\n        /// Gets the set of input symbols which could potentially follow the\n        /// previously matched symbol at the time this exception was thrown.\n        /// <p>If the set of expected tokens is not known and could not be computed,\n        /// this method returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>\n        /// The set of token types that could potentially follow the current\n        /// state in the ATN, or\n        /// <see langword=\"null\"/>\n        /// if the information is not available.\n        /// </returns>\n        [return: Nullable]\n        public virtual IntervalSet GetExpectedTokens()\n        {\n            if (recognizer != null)\n            {\n                return recognizer.Atn.GetExpectedTokens(offendingState, ctx);\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Gets the\n        /// <see cref=\"RuleContext\"/>\n        /// at the time this exception was thrown.\n        /// <p>If the context is not available, this method returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// </summary>\n        /// <returns>\n        /// The\n        /// <see cref=\"RuleContext\"/>\n        /// at the time this exception was thrown.\n        /// If the context is not available, this method returns\n        /// <see langword=\"null\"/>\n        /// .\n        /// </returns>\n        public virtual RuleContext Context\n        {\n            get\n            {\n                return ctx;\n            }\n        }\n\n        /// <summary>\n        /// Gets the input stream which is the symbol source for the recognizer where\n        /// this exception was thrown.\n        /// </summary>\n        /// <remarks>\n        /// Gets the input stream which is the symbol source for the recognizer where\n        /// this exception was thrown.\n        /// <p>If the input stream is not available, this method returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>\n        /// The input stream which is the symbol source for the recognizer\n        /// where this exception was thrown, or\n        /// <see langword=\"null\"/>\n        /// if the stream is not\n        /// available.\n        /// </returns>\n        public virtual IIntStream InputStream\n        {\n            get\n            {\n                return input;\n            }\n        }\n\n        public IToken OffendingToken\n        {\n            get\n            {\n                return offendingToken;\n            }\n            protected set\n            {\n                IToken offendingToken = value;\n                this.offendingToken = offendingToken;\n            }\n        }\n\n        /// <summary>\n        /// Gets the\n        /// <see cref=\"IRecognizer\"/>\n        /// where this exception occurred.\n        /// <p>If the recognizer is not available, this method returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// </summary>\n        /// <returns>\n        /// The recognizer where this exception occurred, or\n        /// <see langword=\"null\"/>\n        /// if\n        /// the recognizer is not available.\n        /// </returns>\n        public virtual IRecognizer Recognizer\n        {\n            get\n            {\n                return recognizer;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Recognizer.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    public abstract class Recognizer<Symbol, ATNInterpreter> : IRecognizer\n        where ATNInterpreter : ATNSimulator\n    {\n        public const int Eof = -1;\n\n        private static readonly ConditionalWeakTable<IVocabulary, IDictionary<string, int>> tokenTypeMapCache = new ConditionalWeakTable<IVocabulary, IDictionary<string, int>>();\n        private static readonly ConditionalWeakTable<string[], IDictionary<string, int>> ruleIndexMapCache = new ConditionalWeakTable<string[], IDictionary<string, int>>();\n\n        [NotNull]\n        private IAntlrErrorListener<Symbol>[] _listeners =\n        {\n            ConsoleErrorListener<Symbol>.Instance\n        };\n\n        private ATNInterpreter _interp;\n\n        private int _stateNumber = -1;\n\n        /// <summary>\n        /// Used to print out token names like ID during debugging and\n        /// error reporting.\n        /// </summary>\n        /// <remarks>\n        /// Used to print out token names like ID during debugging and\n        /// error reporting.  The generated parsers implement a method\n        /// that overrides this to point to their String[] tokenNames.\n        /// </remarks>\n\n        public abstract string[] RuleNames\n        {\n            get;\n        }\n\n\n        /// <summary>Get the vocabulary used by the recognizer.</summary>\n        /// <remarks>Get the vocabulary used by the recognizer.</remarks>\n        /// <returns>\n        /// A\n        /// <see cref=\"IVocabulary\"/>\n        /// instance providing information about the\n        /// vocabulary used by the grammar.\n        /// </returns>\n        public abstract IVocabulary Vocabulary\n        {\n\t\t\tget;\n       }\n\n        /// <summary>Get a map from token names to token types.</summary>\n        /// <remarks>\n        /// Get a map from token names to token types.\n        /// <p>Used for XPath and tree pattern compilation.</p>\n        /// </remarks>\n        [NotNull]\n        public virtual IDictionary<string, int> TokenTypeMap\n        {\n            get\n            {\n                return tokenTypeMapCache.GetValue(Vocabulary, CreateTokenTypeMap);\n            }\n        }\n\n        protected virtual IDictionary<string, int> CreateTokenTypeMap(IVocabulary vocabulary)\n        {\n            var result = new Dictionary<string, int>();\n            for (int i = 0; i <= Atn.maxTokenType; i++)\n            {\n                string literalName = vocabulary.GetLiteralName(i);\n                if (literalName != null)\n                {\n                    result[literalName] = i;\n                }\n                string symbolicName = vocabulary.GetSymbolicName(i);\n                if (symbolicName != null)\n                {\n                    result[symbolicName] = i;\n                }\n            }\n            result[\"EOF\"] = TokenConstants.EOF;\n            return result;\n        }\n\n        /// <summary>Get a map from rule names to rule indexes.</summary>\n        /// <remarks>\n        /// Get a map from rule names to rule indexes.\n        /// <p>Used for XPath and tree pattern compilation.</p>\n        /// </remarks>\n        [NotNull]\n        public virtual IDictionary<string, int> RuleIndexMap\n        {\n            get\n            {\n                string[] ruleNames = RuleNames;\n                if (ruleNames == null)\n                {\n                    throw new NotSupportedException(\"The current recognizer does not provide a list of rule names.\");\n                }\n\n                return ruleIndexMapCache.GetValue(ruleNames, Utils.ToMap);\n            }\n        }\n\n        public virtual int GetTokenType(string tokenName)\n        {\n            int ttype;\n            if (TokenTypeMap.TryGetValue(tokenName, out ttype))\n            {\n                return ttype;\n            }\n            return TokenConstants.InvalidType;\n        }\n\n        /// <summary>\n        /// If this recognizer was generated, it will have a serialized ATN\n        /// representation of the grammar.\n        /// </summary>\n        /// <remarks>\n        /// If this recognizer was generated, it will have a serialized ATN\n        /// representation of the grammar.\n        /// <p>For interpreters, we don't know their serialized ATN despite having\n        /// created the interpreter from it.</p>\n        /// </remarks>\n        public virtual int[] SerializedAtn\n        {\n            [return: NotNull]\n            get\n            {\n                throw new NotSupportedException(\"there is no serialized ATN\");\n            }\n        }\n\n        /// <summary>For debugging and other purposes, might want the grammar name.</summary>\n        /// <remarks>\n        /// For debugging and other purposes, might want the grammar name.\n        /// Have ANTLR generate an implementation for this method.\n        /// </remarks>\n        public abstract string GrammarFileName\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Get the\n        /// <see cref=\"Antlr4.Runtime.Atn.ATN\"/>\n        /// used by the recognizer for prediction.\n        /// </summary>\n        /// <returns>\n        /// The\n        /// <see cref=\"Antlr4.Runtime.Atn.ATN\"/>\n        /// used by the recognizer for prediction.\n        /// </returns>\n        public virtual ATN Atn\n        {\n            get\n            {\n                return _interp.atn;\n            }\n        }\n\n        /// <summary>Get the ATN interpreter used by the recognizer for prediction.</summary>\n        /// <remarks>Get the ATN interpreter used by the recognizer for prediction.</remarks>\n        /// <returns>The ATN interpreter used by the recognizer for prediction.</returns>\n        /// <summary>Set the ATN interpreter used by the recognizer for prediction.</summary>\n        /// <remarks>Set the ATN interpreter used by the recognizer for prediction.</remarks>\n        /// <value>\n        /// The ATN interpreter used by the recognizer for\n        /// prediction.\n        /// </value>\n        public virtual ATNInterpreter Interpreter\n        {\n            get\n            {\n                return _interp;\n            }\n            protected set\n            {\n\t\t\t\t_interp = value;\n            }\n        }\n\n        /// <summary>\n        /// If profiling during the parse/lex, this will return DecisionInfo records\n        /// for each decision in recognizer in a ParseInfo object.\n        /// </summary>\n        /// <remarks>\n        /// If profiling during the parse/lex, this will return DecisionInfo records\n        /// for each decision in recognizer in a ParseInfo object.\n        /// </remarks>\n        /// <since>4.3</since>\n        public virtual Antlr4.Runtime.Atn.ParseInfo ParseInfo\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        /// <summary>What is the error header, normally line/character position information?</summary>\n        [return: NotNull]\n        public virtual string GetErrorHeader(RecognitionException e)\n        {\n            int line = e.OffendingToken.Line;\n            int charPositionInLine = e.OffendingToken.Column;\n            return \"line \" + line + \":\" + charPositionInLine;\n        }\n\n        /// <summary>\n        /// How should a token be displayed in an error message? The default\n        /// is to display just the text, but during development you might\n        /// want to have a lot of information spit out.\n        /// </summary>\n        /// <remarks>\n        /// How should a token be displayed in an error message? The default\n        /// is to display just the text, but during development you might\n        /// want to have a lot of information spit out.  Override in that case\n        /// to use t.toString() (which, for CommonToken, dumps everything about\n        /// the token). This is better than forcing you to override a method in\n        /// your token objects because you don't have to go modify your lexer\n        /// so that it creates a new Java type.\n        /// </remarks>\n        [ObsoleteAttribute(@\"This method is not called by the ANTLR 4 Runtime. Specific implementations of IAntlrErrorStrategy may provide a similar feature when necessary. For example, see DefaultErrorStrategy.GetTokenErrorDisplay(IToken).\")]\n        public virtual string GetTokenErrorDisplay(IToken t)\n        {\n            if (t == null)\n            {\n                return \"<no token>\";\n            }\n            string s = t.Text;\n            if (s == null)\n            {\n                if (t.Type == TokenConstants.EOF)\n                {\n                    s = \"<EOF>\";\n                }\n                else\n                {\n                    s = \"<\" + t.Type + \">\";\n                }\n            }\n            s = s.Replace(\"\\n\", \"\\\\n\");\n            s = s.Replace(\"\\r\", \"\\\\r\");\n            s = s.Replace(\"\\t\", \"\\\\t\");\n            return \"'\" + s + \"'\";\n        }\n\n        /// <exception>\n        /// NullPointerException\n        /// if\n        /// <paramref name=\"listener\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// .\n        /// </exception>\n        public virtual void AddErrorListener(IAntlrErrorListener<Symbol> listener)\n        {\n            Args.NotNull(\"listener\", listener);\n\n            IAntlrErrorListener<Symbol>[] listeners = _listeners;\n            Array.Resize(ref listeners, listeners.Length + 1);\n            listeners[listeners.Length - 1] = listener;\n            _listeners = listeners;\n        }\n\n        public virtual void RemoveErrorListener(IAntlrErrorListener<Symbol> listener)\n        {\n            IAntlrErrorListener<Symbol>[] listeners = _listeners;\n            int removeIndex = Array.IndexOf(listeners, listener);\n            if (removeIndex < 0)\n                return;\n\n            Array.Copy(listeners, removeIndex + 1, listeners, removeIndex, listeners.Length - removeIndex - 1);\n            Array.Resize(ref listeners, listeners.Length - 1);\n            _listeners = listeners;\n        }\n\n        public virtual void RemoveErrorListeners()\n        {\n            _listeners = Collections.EmptyList<IAntlrErrorListener<Symbol>>();\n        }\n\n        [NotNull]\n        public virtual IList<IAntlrErrorListener<Symbol>> ErrorListeners\n        {\n            get\n            {\n                return new List<IAntlrErrorListener<Symbol>>(_listeners);\n            }\n        }\n\n        public virtual IAntlrErrorListener<Symbol> ErrorListenerDispatch\n        {\n            get\n            {\n                return new ProxyErrorListener<Symbol>(ErrorListeners);\n            }\n        }\n\n        // subclass needs to override these if there are sempreds or actions\n        // that the ATN interp needs to execute\n        public virtual bool Sempred(RuleContext _localctx, int ruleIndex, int actionIndex)\n        {\n            return true;\n        }\n\n        public virtual bool Precpred(RuleContext localctx, int precedence)\n        {\n            return true;\n        }\n\n        public virtual void Action(RuleContext _localctx, int ruleIndex, int actionIndex)\n        {\n        }\n\n        /// <summary>\n        /// Indicate that the recognizer has changed internal state that is\n        /// consistent with the ATN state passed in.\n        /// </summary>\n        /// <remarks>\n        /// Indicate that the recognizer has changed internal state that is\n        /// consistent with the ATN state passed in.  This way we always know\n        /// where we are in the ATN as the parser goes along. The rule\n        /// context objects form a stack that lets us see the stack of\n        /// invoking rules. Combine this and we have complete ATN\n        /// configuration information.\n        /// </remarks>\n        public int State\n        {\n            get\n            {\n                return _stateNumber;\n            }\n            set\n            {\n                int atnState = value;\n                //\t\tSystem.err.println(\"setState \"+atnState);\n                _stateNumber = atnState;\n            }\n        }\n\n        public abstract IIntStream InputStream\n        {\n            get;\n        }\n        //\t\tif ( traceATNStates ) _ctx.trace(atnState);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/RuleContext.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>A rule context is a record of a single rule invocation.</summary>\n    /// <remarks>\n    /// A rule context is a record of a single rule invocation. It knows\n    /// which context invoked it, if any. If there is no parent context, then\n    /// naturally the invoking state is not valid.  The parent link\n    /// provides a chain upwards from the current rule invocation to the root\n    /// of the invocation tree, forming a stack. We actually carry no\n    /// information about the rule associated with this context (except\n    /// when parsing). We keep only the state number of the invoking state from\n    /// the ATN submachine that invoked this. Contrast this with the s\n    /// pointer inside ParserRuleContext that tracks the current state\n    /// being \"executed\" for the current rule.\n    /// The parent contexts are useful for computing lookahead sets and\n    /// getting error information.\n    /// These objects are used during parsing and prediction.\n    /// For the special case of parsers, we use the subclass\n    /// ParserRuleContext.\n    /// </remarks>\n    /// <seealso cref=\"ParserRuleContext\"/>\n    public class RuleContext : IRuleNode\n    {\n        /// <summary>What context invoked this rule?</summary>\n        private Antlr4.Runtime.RuleContext _parent;\n\n        /// <summary>\n        /// What state invoked the rule associated with this context?\n        /// The \"return address\" is the followState of invokingState\n        /// If parent is null, this should be -1.\n        /// </summary>\n        /// <remarks>\n        /// What state invoked the rule associated with this context?\n        /// The \"return address\" is the followState of invokingState\n        /// If parent is null, this should be -1.\n        /// </remarks>\n        public int invokingState = -1;\n\n        public RuleContext()\n        {\n        }\n\n        public RuleContext(Antlr4.Runtime.RuleContext parent, int invokingState)\n        {\n            this._parent = parent;\n            //if ( parent!=null ) System.out.println(\"invoke \"+stateNumber+\" from \"+parent);\n            this.invokingState = invokingState;\n        }\n\n        public static Antlr4.Runtime.RuleContext GetChildContext(Antlr4.Runtime.RuleContext parent, int invokingState)\n        {\n            return new Antlr4.Runtime.RuleContext(parent, invokingState);\n        }\n\n        public virtual int Depth()\n        {\n            int n = 0;\n            Antlr4.Runtime.RuleContext p = this;\n            while (p != null)\n            {\n                p = p._parent;\n                n++;\n            }\n            return n;\n        }\n\n        /// <summary>\n        /// A context is empty if there is no invoking state; meaning nobody call\n        /// current context.\n        /// </summary>\n        /// <remarks>\n        /// A context is empty if there is no invoking state; meaning nobody call\n        /// current context.\n        /// </remarks>\n        public virtual bool IsEmpty\n        {\n            get\n            {\n                return invokingState == -1;\n            }\n        }\n\n        public virtual Interval SourceInterval\n        {\n            get\n            {\n                // satisfy the ParseTree / SyntaxTree interface\n                return Interval.Invalid;\n            }\n        }\n\n        RuleContext IRuleNode.RuleContext\n        {\n            get\n            {\n                return this;\n            }\n        }\n\n        public virtual Antlr4.Runtime.RuleContext Parent\n        {\n            get\n            {\n                return _parent;\n            }\n\t\t\tset\n\t\t\t{\n\t\t\t\t_parent = value;\n\t\t\t}\n        }\n\n        IRuleNode IRuleNode.Parent\n        {\n            get\n            {\n                return Parent;\n            }\n        }\n\n        IParseTree IParseTree.Parent\n        {\n            get\n            {\n                return Parent;\n            }\n        }\n\n        ITree ITree.Parent\n        {\n            get\n            {\n                return Parent;\n            }\n        }\n\n        public virtual Antlr4.Runtime.RuleContext Payload\n        {\n            get\n            {\n                return this;\n            }\n        }\n\n        object ITree.Payload\n        {\n            get\n            {\n                return Payload;\n            }\n        }\n\n        /// <summary>Return the combined text of all child nodes.</summary>\n        /// <remarks>\n        /// Return the combined text of all child nodes. This method only considers\n        /// tokens which have been added to the parse tree.\n        /// <p/>\n        /// Since tokens on hidden channels (e.g. whitespace or comments) are not\n        /// added to the parse trees, they will not appear in the output of this\n        /// method.\n        /// </remarks>\n        public virtual string GetText()\n        {\n            if (ChildCount == 0)\n            {\n                return string.Empty;\n            }\n            StringBuilder builder = new StringBuilder();\n            for (int i = 0; i < ChildCount; i++)\n            {\n                builder.Append(GetChild(i).GetText());\n            }\n            return builder.ToString();\n        }\n\n        public virtual int RuleIndex\n        {\n            get\n            {\n                return -1;\n            }\n        }\n\n\t/* For rule associated with this parse tree internal node, return\n\t * the outer alternative number used to match the input. Default\n\t * implementation does not compute nor store this alt num. Create\n\t * a subclass of ParserRuleContext with backing field and set\n\t * option contextSuperClass.\n\t * to set it.\n\t */\n\tpublic virtual int getAltNumber() { return Atn.ATN.INVALID_ALT_NUMBER; }\n\n\t/* Set the outer alternative number for this context node. Default\n\t * implementation does nothing to avoid backing field overhead for\n\t * trees that don't need it.  Create\n     * a subclass of ParserRuleContext with backing field and set\n     * option contextSuperClass.\n\t */\n\tpublic virtual void setAltNumber(int altNumber) { }\n\n        public virtual IParseTree GetChild(int i)\n        {\n            return null;\n        }\n\n        ITree ITree.GetChild(int i)\n        {\n            return GetChild(i);\n        }\n\n        public virtual int ChildCount\n        {\n            get\n            {\n                return 0;\n            }\n        }\n\n        public virtual T Accept<T>(IParseTreeVisitor<T> visitor)\n        {\n            return visitor.VisitChildren(this);\n        }\n\n        /// <summary>\n        /// Print out a whole tree, not just a node, in LISP format\n        /// (root child1 ..\n        /// </summary>\n        /// <remarks>\n        /// Print out a whole tree, not just a node, in LISP format\n        /// (root child1 .. childN). Print just a node if this is a leaf.\n        /// We have to know the recognizer so we can get rule names.\n        /// </remarks>\n        public virtual string ToStringTree(Parser recog)\n        {\n            return Trees.ToStringTree(this, recog);\n        }\n\n        /// <summary>\n        /// Print out a whole tree, not just a node, in LISP format\n        /// (root child1 ..\n        /// </summary>\n        /// <remarks>\n        /// Print out a whole tree, not just a node, in LISP format\n        /// (root child1 .. childN). Print just a node if this is a leaf.\n        /// </remarks>\n        public virtual string ToStringTree(IList<string> ruleNames)\n        {\n            return Trees.ToStringTree(this, ruleNames);\n        }\n\n        public virtual string ToStringTree()\n        {\n            return ToStringTree((IList<string>)null);\n        }\n\n        public override string ToString()\n        {\n            return ToString((IList<string>)null, (Antlr4.Runtime.RuleContext)null);\n        }\n\n        public string ToString(IRecognizer recog)\n        {\n            return ToString(recog, ParserRuleContext.EmptyContext);\n        }\n\n        public string ToString(IList<string> ruleNames)\n        {\n            return ToString(ruleNames, null);\n        }\n\n        // recog null unless ParserRuleContext, in which case we use subclass toString(...)\n        public virtual string ToString(IRecognizer recog, Antlr4.Runtime.RuleContext stop)\n        {\n            string[] ruleNames = recog != null ? recog.RuleNames : null;\n            IList<string> ruleNamesList = ruleNames != null ? Arrays.AsList(ruleNames) : null;\n            return ToString(ruleNamesList, stop);\n        }\n\n        public virtual string ToString(IList<string> ruleNames, Antlr4.Runtime.RuleContext stop)\n        {\n            StringBuilder buf = new StringBuilder();\n            Antlr4.Runtime.RuleContext p = this;\n            buf.Append(\"[\");\n            while (p != null && p != stop)\n            {\n                if (ruleNames == null)\n                {\n                    if (!p.IsEmpty)\n                    {\n                        buf.Append(p.invokingState);\n                    }\n                }\n                else\n                {\n                    int ruleIndex = p.RuleIndex;\n                    string ruleName = ruleIndex >= 0 && ruleIndex < ruleNames.Count ? ruleNames[ruleIndex] : ruleIndex.ToString();\n                    buf.Append(ruleName);\n                }\n                if (p.Parent != null && (ruleNames != null || !p.Parent.IsEmpty))\n                {\n                    buf.Append(\" \");\n                }\n                p = p.Parent;\n            }\n            buf.Append(\"]\");\n            return buf.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/RuleDependencyAttribute.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime\n{\n    using System;\n\n    [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\n    public sealed class RuleDependencyAttribute : Attribute\n    {\n        private readonly Type _recognizer;\n        private readonly int _rule;\n        private readonly int _version;\n        private readonly Dependents _dependents;\n\n        public RuleDependencyAttribute(Type recognizer, int rule, int version)\n        {\n            this._recognizer = recognizer;\n            this._rule = rule;\n            this._version = version;\n            this._dependents = Dependents.Parents | Dependents.Self;\n        }\n\n        public RuleDependencyAttribute(Type recognizer, int rule, int version, Dependents dependents)\n        {\n            this._recognizer = recognizer;\n            this._rule = rule;\n            this._version = version;\n            this._dependents = dependents | Dependents.Self;\n        }\n\n        public Type Recognizer\n        {\n            get\n            {\n                return _recognizer;\n            }\n        }\n\n        public int Rule\n        {\n            get\n            {\n                return _rule;\n            }\n        }\n\n        public int Version\n        {\n            get\n            {\n                return _version;\n            }\n        }\n\n        public Dependents Dependents\n        {\n            get\n            {\n                return _dependents;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/RuleVersionAttribute.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime\n{\n    using System;\n\n    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]\n    public sealed class RuleVersionAttribute : Attribute\n    {\n        private readonly int _version;\n\n        public RuleVersionAttribute(int version)\n        {\n            _version = version;\n        }\n\n        public int Version\n        {\n            get\n            {\n                return _version;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/Arrays.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Sharpen\n{\n    using System;\n    using System.Collections.Generic;\n    using StringBuilder = System.Text.StringBuilder;\n\n    internal static class Arrays\n    {\n        public static T[] CopyOf<T>(T[] array, int newSize)\n        {\n            if (array.Length == newSize)\n                return (T[])array.Clone();\n\n            Array.Resize(ref array, newSize);\n            return array;\n        }\n\n        public static IList<T> AsList<T>(params T[] array)\n        {\n            return array;\n        }\n\n        public static void Fill<T>(T[] array, T value)\n        {\n            for (int i = 0; i < array.Length; i++)\n                array[i] = value;\n        }\n\n        public static int HashCode<T>(T[] array)\n        {\n            if (array == null)\n                return 0;\n\n            int result = 1;\n            foreach (object o in array)\n                result = 31 * result + (o == null ? 0 : o.GetHashCode());\n\n            return result;\n        }\n\n        public static bool Equals<T>(T[] left, T[] right)\n        {\n            if (left == right)\n                return true;\n            else if (left == null || right == null)\n                return false;\n\n            if (left.Length != right.Length)\n                return false;\n\n            for (int i = 0; i < left.Length; i++)\n            {\n                if (!object.Equals(left[i], right[i]))\n                    return false;\n            }\n\n            return true;\n        }\n\n        public static string ToString<T>(T[] array)\n        {\n            if (array == null)\n                return \"null\";\n\n            StringBuilder builder = new StringBuilder();\n            builder.Append('[');\n            for (int i = 0; i < array.Length; i++)\n            {\n                if (i > 0)\n                    builder.Append(\", \");\n\n                T o = array[i];\n                if (o == null)\n                    builder.Append(\"null\");\n                else\n                    builder.Append(o);\n            }\n\n            builder.Append(']');\n            return builder.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/AtomicReference.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Sharpen\n{\n    using Interlocked = System.Threading.Interlocked;\n\n    public class AtomicReference<T>\n        where T : class\n    {\n#pragma warning disable 0420 // 'fieldname': a reference to a volatile field will not be treated as volatile\n        private volatile T _value;\n\n        public AtomicReference()\n        {\n        }\n\n        public AtomicReference(T value)\n        {\n            _value = value;\n        }\n\n        public T Get()\n        {\n            return _value;\n        }\n\n        public void Set(T value)\n        {\n            _value = value;\n        }\n\n        public bool CompareAndSet(T expect, T update)\n        {\n            return Interlocked.CompareExchange(ref _value, update, expect) == expect;\n        }\n\n        public T GetAndSet(T value)\n        {\n            return Interlocked.Exchange(ref _value, value);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/BitSet.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Sharpen\n{\n    using System;\n    using System.Text;\n\n    public class BitSet\n    {\n        private static readonly ulong[] EmptyBits = Collections.EmptyList<ulong>();\n        private const int BitsPerElement = 8 * sizeof(ulong);\n\n        private ulong[] _data = EmptyBits;\n\n        public BitSet()\n        {\n        }\n\n        public BitSet(int nbits)\n        {\n            if (nbits < 0)\n                throw new ArgumentOutOfRangeException(\"nbits\");\n\n            if (nbits > 0)\n            {\n                int length = (nbits + BitsPerElement - 1) / BitsPerElement;\n                _data = new ulong[length];\n            }\n        }\n\n        private static int GetBitCount(ulong[] value)\n        {\n            int data = 0;\n            uint size = (uint)value.Length;\n            const ulong m1 = 0x5555555555555555;\n            const ulong m2 = 0x3333333333333333;\n            const ulong m4 = 0x0F0F0F0F0F0F0F0F;\n            const ulong m8 = 0x00FF00FF00FF00FF;\n            const ulong m16 = 0x0000FFFF0000FFFF;\n            const ulong h01 = 0x0101010101010101;\n\n            uint bitCount = 0;\n            uint limit30 = size - size % 30;\n\n            // 64-bit tree merging (merging3)\n            for (uint i = 0; i < limit30; i += 30, data += 30)\n            {\n                ulong acc = 0;\n                for (uint j = 0; j < 30; j += 3)\n                {\n                    ulong count1 = value[data + j];\n                    ulong count2 = value[data + j + 1];\n                    ulong half1 = value[data + j + 2];\n                    ulong half2 = half1;\n                    half1 &= m1;\n                    half2 = (half2 >> 1) & m1;\n                    count1 -= (count1 >> 1) & m1;\n                    count2 -= (count2 >> 1) & m1;\n                    count1 += half1;\n                    count2 += half2;\n                    count1 = (count1 & m2) + ((count1 >> 2) & m2);\n                    count1 += (count2 & m2) + ((count2 >> 2) & m2);\n                    acc += (count1 & m4) + ((count1 >> 4) & m4);\n                }\n\n                acc = (acc & m8) + ((acc >> 8) & m8);\n                acc = (acc + (acc >> 16)) & m16;\n                acc = acc + (acc >> 32);\n                bitCount += (uint)acc;\n            }\n\n            // count the bits of the remaining bytes (MAX 29*8) using\n            // \"Counting bits set, in parallel\" from the \"Bit Twiddling Hacks\",\n            // the code uses wikipedia's 64-bit popcount_3() implementation:\n            // http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation\n            for (uint i = 0; i < size - limit30; i++)\n            {\n                ulong x = value[data + i];\n                x = x - ((x >> 1) & m1);\n                x = (x & m2) + ((x >> 2) & m2);\n                x = (x + (x >> 4)) & m4;\n                bitCount += (uint)((x * h01) >> 56);\n            }\n\n            return (int)bitCount;\n        }\n\n        private static readonly int[] index64 =\n        {\n            0, 47,  1, 56, 48, 27,  2, 60,\n           57, 49, 41, 37, 28, 16,  3, 61,\n           54, 58, 35, 52, 50, 42, 21, 44,\n           38, 32, 29, 23, 17, 11,  4, 62,\n           46, 55, 26, 59, 40, 36, 15, 53,\n           34, 51, 20, 43, 31, 22, 10, 45,\n           25, 39, 14, 33, 19, 30,  9, 24,\n           13, 18,  8, 12,  7,  6,  5, 63\n        };\n\n        private static int BitScanForward(ulong value)\n        {\n            if (value == 0)\n                return -1;\n\n            const ulong debruijn64 = 0x03f79d71b4cb0a89;\n            return index64[((value ^ (value - 1)) * debruijn64) >> 58];\n        }\n\n        public BitSet Clone()\n        {\n            BitSet result = new BitSet();\n            result._data = (ulong[])_data.Clone();\n            return result;\n        }\n\n        public void Clear(int index)\n        {\n            if (index < 0)\n                throw new ArgumentOutOfRangeException(\"index\");\n\n            int element = index / BitsPerElement;\n            if (element >= _data.Length)\n                return;\n\n            _data[element] &= ~(1UL << (index % BitsPerElement));\n        }\n\n\t\tpublic bool this[int index]\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn Get(index);\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\tSet(index);\n\t\t\t}\n\t\t}\n\n        public bool Get(int index)\n        {\n            if (index < 0)\n                throw new ArgumentOutOfRangeException(\"index\");\n\n            int element = index / BitsPerElement;\n            if (element >= _data.Length)\n                return false;\n\n            return (_data[element] & (1UL << (index % BitsPerElement))) != 0;\n        }\n\n        public void Set(int index)\n        {\n            if (index < 0)\n                throw new ArgumentOutOfRangeException(\"index\");\n\n            int element = index / BitsPerElement;\n            if (element >= _data.Length)\n                Array.Resize(ref _data, Math.Max(_data.Length * 2, element + 1));\n\n            _data[element] |= 1UL << (index % BitsPerElement);\n        }\n\n        public bool IsEmpty()\n        {\n            for (int i = 0; i < _data.Length; i++)\n            {\n                if (_data[i] != 0)\n                    return false;\n            }\n\n            return true;\n        }\n\n        public int Cardinality()\n        {\n            return GetBitCount(_data);\n        }\n\n        public int NextSetBit(int fromIndex)\n        {\n            if (fromIndex < 0)\n                throw new ArgumentOutOfRangeException(\"fromIndex\");\n\n            if (IsEmpty())\n                return -1;\n\n            int i = fromIndex / BitsPerElement;\n            if (i >= _data.Length)\n                return -1;\n\n            ulong current = _data[i] & ~((1UL << (fromIndex % BitsPerElement)) - 1);\n\n            while (true)\n            {\n                int bit = BitScanForward(current);\n                if (bit >= 0)\n                    return bit + i * BitsPerElement;\n\n                i++;\n                if (i >= _data.Length)\n                    break;\n\n                current = _data[i];\n            }\n\n            return -1;\n        }\n\n        public void And(BitSet set)\n        {\n            if (set == null)\n                throw new ArgumentNullException(\"set\");\n\n            int length = Math.Min(_data.Length, set._data.Length);\n            for (int i = 0; i < length; i++)\n                _data[i] &= set._data[i];\n\n            for (int i = length; i < _data.Length; i++)\n                _data[i] = 0;\n        }\n\n        public void Or(BitSet set)\n        {\n            if (set == null)\n                throw new ArgumentNullException(\"set\");\n\n            if (set._data.Length > _data.Length)\n                Array.Resize(ref _data, set._data.Length);\n\n            for (int i = 0; i < set._data.Length; i++)\n                _data[i] |= set._data[i];\n        }\n\n        public override bool Equals(object obj)\n        {\n            BitSet other = obj as BitSet;\n            if (other == null)\n                return false;\n\n            if (IsEmpty())\n                return other.IsEmpty();\n\n            int minLength = Math.Min(_data.Length, other._data.Length);\n            for (int i = 0; i < minLength; i++)\n            {\n                if (_data[i] != other._data[i])\n                    return false;\n            }\n\n            for (int i = minLength; i < _data.Length; i++)\n            {\n                if (_data[i] != 0)\n                    return false;\n            }\n\n            for (int i = minLength; i < other._data.Length; i++)\n            {\n                if (other._data[i] != 0)\n                    return false;\n            }\n\n            return true;\n        }\n\n        public override int GetHashCode()\n        {\n            ulong result = 1;\n            for (uint i = 0; i < _data.Length; i++)\n            {\n                if (_data[i] != 0)\n                {\n                    result = result * 31 ^ i;\n                    result = result * 31 ^ _data[i];\n                }\n            }\n\n            return result.GetHashCode();\n        }\n\n        public override string ToString()\n        {\n            StringBuilder builder = new StringBuilder();\n            builder.Append('{');\n\n            for (int i = NextSetBit(0); i >= 0; i = NextSetBit(i + 1))\n            {\n                if (builder.Length > 1)\n                    builder.Append(\", \");\n\n                builder.Append(i);\n            }\n\n            builder.Append('}');\n            return builder.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/Collections.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Sharpen\n{\n    using System.Collections.Generic;\n    using System.Collections.ObjectModel;\n\n    internal static class Collections\n    {\n\t\t/// <remarks>\n\t\t/// Available in .NET as Array.Empty but not to the net45 target.\n\t\t/// See: https://learn.microsoft.com/dotnet/api/system.array.empty.\n\t\t/// </remarks>\n\t\tpublic static T[] EmptyList<T>()\n        {\n            return EmptyListImpl<T>.Instance;\n        }\n\n        public static ReadOnlyDictionary<TKey, TValue> EmptyMap<TKey, TValue>()\n        {\n            return EmptyMapImpl<TKey, TValue>.Instance;\n        }\n\n        public static ReadOnlyCollection<T> SingletonList<T>(T item)\n        {\n            return new ReadOnlyCollection<T>(new T[] { item });\n        }\n\n        public static ReadOnlyDictionary<TKey, TValue> SingletonMap<TKey, TValue>(TKey key, TValue value)\n        {\n            return new ReadOnlyDictionary<TKey,TValue>(new Dictionary<TKey, TValue> { { key, value } });\n        }\n\n        private static class EmptyListImpl<T>\n        {\n#pragma warning disable CA1825\n            // Provides a solution for CA1825.\n\t\t\tpublic static readonly T[] Instance = new T[0];\n#pragma warning restore CA1825\n\t\t}\n\n\t\tprivate static class EmptyMapImpl<TKey, TValue>\n        {\n            public static readonly ReadOnlyDictionary<TKey, TValue> Instance =\n                new ReadOnlyDictionary<TKey, TValue>(new Dictionary<TKey, TValue>());\n        }\n    }\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/DictionaryExtensions.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Sharpen\n{\n    using System.Collections.Generic;\n\n    internal static class DictionaryExtensions\n    {\n        public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)\n            where TValue : class\n        {\n            TValue value;\n            if (!dictionary.TryGetValue(key, out value))\n                return null;\n\n            return value;\n        }\n\n        public static TValue Put<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)\n            where TValue : class\n        {\n            TValue previous;\n            if (!dictionary.TryGetValue(key, out previous))\n                previous = null;\n\n            dictionary[key] = value;\n            return previous;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/ListExtensions.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Sharpen\n{\n\tusing System.Collections.Generic;\n\n\tinternal static class ListExtensions\n    {\n        public static T Set<T>(this IList<T> list, int index, T value)\n            where T : class\n        {\n            T previous = list[index];\n            list[index] = value;\n            return previous;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/Runtime.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Sharpen\n{\n    using System;\n\n    internal static class Runtime\n    {\n        public static string Substring(string str, int beginOffset, int endOffset)\n        {\n            if (str == null)\n                throw new ArgumentNullException(\"str\");\n\n            return str.Substring(beginOffset, endOffset - beginOffset);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Sharpen/SequenceEqualityComparer.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Sharpen\n{\n    using System.Collections.Generic;\n    using System.Linq;\n\n    internal class SequenceEqualityComparer<T> : EqualityComparer<IEnumerable<T>>\n    {\n        private static readonly SequenceEqualityComparer<T> _default = new SequenceEqualityComparer<T>();\n\n        private readonly IEqualityComparer<T> _elementEqualityComparer = EqualityComparer<T>.Default;\n\n        public SequenceEqualityComparer()\n            : this(null)\n        {\n        }\n\n        public SequenceEqualityComparer(IEqualityComparer<T> elementComparer)\n        {\n            _elementEqualityComparer = elementComparer ?? EqualityComparer<T>.Default;\n        }\n\n        public new static SequenceEqualityComparer<T> Default\n        {\n            get\n            {\n                return _default;\n            }\n        }\n\n        public override bool Equals(IEnumerable<T> x, IEnumerable<T> y)\n        {\n            if (x == y)\n                return true;\n            if (x == null || y == null)\n                return false;\n\n            return x.SequenceEqual(y, _elementEqualityComparer);\n        }\n\n        public override int GetHashCode(IEnumerable<T> obj)\n        {\n            if (obj == null)\n                return 0;\n\n            int hashCode = 1;\n            foreach (T element in obj)\n                hashCode = 31 * hashCode + _elementEqualityComparer.GetHashCode(element);\n\n            return hashCode;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/TokenStreamRewriter.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// Useful for rewriting out a buffered input token stream after doing some\n    /// augmentation or other manipulations on it.\n    /// </summary>\n    /// <remarks>\n    /// Useful for rewriting out a buffered input token stream after doing some\n    /// augmentation or other manipulations on it.\n    /// <p>\n    /// You can insert stuff, replace, and delete chunks. Note that the operations\n    /// are done lazily--only if you convert the buffer to a\n    /// <see cref=\"string\"/>\n    /// with\n    /// <see cref=\"ITokenStream.GetText()\"/>\n    /// . This is very efficient because you are not\n    /// moving data around all the time. As the buffer of tokens is converted to\n    /// strings, the\n    /// <see cref=\"GetText()\"/>\n    /// method(s) scan the input token stream and\n    /// check to see if there is an operation at the current index. If so, the\n    /// operation is done and then normal\n    /// <see cref=\"string\"/>\n    /// rendering continues on the\n    /// buffer. This is like having multiple Turing machine instruction streams\n    /// (programs) operating on a single input tape. :)</p>\n    /// <p>\n    /// This rewriter makes no modifications to the token stream. It does not ask the\n    /// stream to fill itself up nor does it advance the input cursor. The token\n    /// stream\n    /// <see cref=\"IIntStream.Index()\"/>\n    /// will return the same value before and\n    /// after any\n    /// <see cref=\"GetText()\"/>\n    /// call.</p>\n    /// <p>\n    /// The rewriter only works on tokens that you have in the buffer and ignores the\n    /// current input cursor. If you are buffering tokens on-demand, calling\n    /// <see cref=\"GetText()\"/>\n    /// halfway through the input will only do rewrites for those\n    /// tokens in the first half of the file.</p>\n    /// <p>\n    /// Since the operations are done lazily at\n    /// <see cref=\"GetText()\"/>\n    /// -time, operations do\n    /// not screw up the token index values. That is, an insert operation at token\n    /// index\n    /// <c>i</c>\n    /// does not change the index values for tokens\n    /// <c>i</c>\n    /// +1..n-1.</p>\n    /// <p>\n    /// Because operations never actually alter the buffer, you may always get the\n    /// original token stream back without undoing anything. Since the instructions\n    /// are queued up, you can easily simulate transactions and roll back any changes\n    /// if there is an error just by removing instructions. For example,</p>\n    /// <pre>\n    /// CharStream input = new ANTLRFileStream(\"input\");\n    /// TLexer lex = new TLexer(input);\n    /// CommonTokenStream tokens = new CommonTokenStream(lex);\n    /// T parser = new T(tokens);\n    /// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);\n    /// parser.startRule();\n    /// </pre>\n    /// <p>\n    /// Then in the rules, you can execute (assuming rewriter is visible):</p>\n    /// <pre>\n    /// Token t,u;\n    /// ...\n    /// rewriter.insertAfter(t, \"text to put after t\");}\n    /// rewriter.insertAfter(u, \"text after u\");}\n    /// System.out.println(tokens.toString());\n    /// </pre>\n    /// <p>\n    /// You can also have multiple \"instruction streams\" and get multiple rewrites\n    /// from a single pass over the input. Just name the instruction streams and use\n    /// that name again when printing the buffer. This could be useful for generating\n    /// a C file and also its header file--all from the same buffer:</p>\n    /// <pre>\n    /// tokens.insertAfter(\"pass1\", t, \"text to put after t\");}\n    /// tokens.insertAfter(\"pass2\", u, \"text after u\");}\n    /// System.out.println(tokens.toString(\"pass1\"));\n    /// System.out.println(tokens.toString(\"pass2\"));\n    /// </pre>\n    /// <p>\n    /// If you don't use named rewrite streams, a \"default\" stream is used as the\n    /// first example shows.</p>\n    /// </remarks>\n    public class TokenStreamRewriter\n    {\n        public const string DefaultProgramName = \"default\";\n\n        public const int ProgramInitSize = 100;\n\n        public const int MinTokenIndex = 0;\n\n        public class RewriteOperation\n        {\n            protected internal readonly ITokenStream tokens;\n\n            /// <summary>What index into rewrites List are we?</summary>\n            protected internal int instructionIndex;\n\n            /// <summary>Token buffer index.</summary>\n            /// <remarks>Token buffer index.</remarks>\n            protected internal int index;\n\n            protected internal object text;\n\n            protected internal RewriteOperation(ITokenStream tokens, int index)\n            {\n                // Define the rewrite operation hierarchy\n                this.tokens = tokens;\n                this.index = index;\n            }\n\n            protected internal RewriteOperation(ITokenStream tokens, int index, object text)\n            {\n                this.tokens = tokens;\n                this.index = index;\n                this.text = text;\n            }\n\n            /// <summary>Execute the rewrite operation by possibly adding to the buffer.</summary>\n            /// <remarks>\n            /// Execute the rewrite operation by possibly adding to the buffer.\n            /// Return the index of the next token to operate on.\n            /// </remarks>\n            public virtual int Execute(StringBuilder buf)\n            {\n                return index;\n            }\n\n            public override string ToString()\n            {\n                string opName = GetType().FullName;\n                int index = opName.IndexOf('$');\n                opName = Sharpen.Runtime.Substring(opName, index + 1, opName.Length);\n                return \"<\" + opName + \"@\" + tokens.Get(this.index) + \":\\\"\" + text + \"\\\">\";\n            }\n        }\n\n        internal class InsertBeforeOp : TokenStreamRewriter.RewriteOperation\n        {\n            public InsertBeforeOp(ITokenStream tokens, int index, object text)\n                : base(tokens, index, text)\n            {\n            }\n\n            public override int Execute(StringBuilder buf)\n            {\n                buf.Append(text);\n                if (tokens.Get(index).Type != TokenConstants.EOF)\n                {\n                    buf.Append(tokens.Get(index).Text);\n                }\n                return index + 1;\n            }\n        }\n\n        /// <summary>\n        /// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp\n        /// instructions.\n        /// </summary>\n        /// <remarks>\n        /// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp\n        /// instructions.\n        /// </remarks>\n        internal class ReplaceOp : TokenStreamRewriter.RewriteOperation\n        {\n            protected internal int lastIndex;\n\n            public ReplaceOp(ITokenStream tokens, int from, int to, object text)\n                : base(tokens, from, text)\n            {\n                lastIndex = to;\n            }\n\n            public override int Execute(StringBuilder buf)\n            {\n                if (text != null)\n                {\n                    buf.Append(text);\n                }\n                return lastIndex + 1;\n            }\n\n            public override string ToString()\n            {\n                if (text == null)\n                {\n                    return \"<DeleteOp@\" + tokens.Get(index) + \"..\" + tokens.Get(lastIndex) + \">\";\n                }\n                return \"<ReplaceOp@\" + tokens.Get(index) + \"..\" + tokens.Get(lastIndex) + \":\\\"\" + text + \"\\\">\";\n            }\n        }\n\n        /// <summary>Our source stream</summary>\n        protected internal readonly ITokenStream tokens;\n\n        /// <summary>You may have multiple, named streams of rewrite operations.</summary>\n        /// <remarks>\n        /// You may have multiple, named streams of rewrite operations.\n        /// I'm calling these things \"programs.\"\n        /// Maps String (name) &#x2192; rewrite (List)\n        /// </remarks>\n        protected internal readonly IDictionary<string, IList<TokenStreamRewriter.RewriteOperation>> programs;\n\n        /// <summary>Map String (program name) &#x2192; Integer index</summary>\n        protected internal readonly IDictionary<string, int> lastRewriteTokenIndexes;\n\n        public TokenStreamRewriter(ITokenStream tokens)\n        {\n            this.tokens = tokens;\n            programs = new Dictionary<string, IList<TokenStreamRewriter.RewriteOperation>>();\n            programs[DefaultProgramName] = new List<TokenStreamRewriter.RewriteOperation>(ProgramInitSize);\n            lastRewriteTokenIndexes = new Dictionary<string, int>();\n        }\n\n        public ITokenStream TokenStream\n        {\n            get\n            {\n                return tokens;\n            }\n        }\n\n        public virtual void Rollback(int instructionIndex)\n        {\n            Rollback(DefaultProgramName, instructionIndex);\n        }\n\n        /// <summary>\n        /// Rollback the instruction stream for a program so that\n        /// the indicated instruction (via instructionIndex) is no\n        /// longer in the stream.\n        /// </summary>\n        /// <remarks>\n        /// Rollback the instruction stream for a program so that\n        /// the indicated instruction (via instructionIndex) is no\n        /// longer in the stream. UNTESTED!\n        /// </remarks>\n        public virtual void Rollback(string programName, int instructionIndex)\n        {\n            IList<TokenStreamRewriter.RewriteOperation> @is;\n            if (programs.TryGetValue(programName, out @is))\n            {\n                programs[programName] = new List<RewriteOperation>(@is.Skip(MinTokenIndex).Take(instructionIndex - MinTokenIndex));\n            }\n        }\n\n        public virtual void DeleteProgram()\n        {\n            DeleteProgram(DefaultProgramName);\n        }\n\n        /// <summary>Reset the program so that no instructions exist</summary>\n        public virtual void DeleteProgram(string programName)\n        {\n            Rollback(programName, MinTokenIndex);\n        }\n\n        public virtual void InsertAfter(IToken t, object text)\n        {\n            InsertAfter(DefaultProgramName, t, text);\n        }\n\n        public virtual void InsertAfter(int index, object text)\n        {\n            InsertAfter(DefaultProgramName, index, text);\n        }\n\n        public virtual void InsertAfter(string programName, IToken t, object text)\n        {\n            InsertAfter(programName, t.TokenIndex, text);\n        }\n\n        public virtual void InsertAfter(string programName, int index, object text)\n        {\n            // to insert after, just insert before next index (even if past end)\n            InsertBefore(programName, index + 1, text);\n        }\n\n        public virtual void InsertBefore(IToken t, object text)\n        {\n            InsertBefore(DefaultProgramName, t, text);\n        }\n\n        public virtual void InsertBefore(int index, object text)\n        {\n            InsertBefore(DefaultProgramName, index, text);\n        }\n\n        public virtual void InsertBefore(string programName, IToken t, object text)\n        {\n            InsertBefore(programName, t.TokenIndex, text);\n        }\n\n        public virtual void InsertBefore(string programName, int index, object text)\n        {\n            TokenStreamRewriter.RewriteOperation op = new TokenStreamRewriter.InsertBeforeOp(tokens, index, text);\n            IList<TokenStreamRewriter.RewriteOperation> rewrites = GetProgram(programName);\n            op.instructionIndex = rewrites.Count;\n            rewrites.Add(op);\n        }\n\n        public virtual void Replace(int index, object text)\n        {\n            Replace(DefaultProgramName, index, index, text);\n        }\n\n        public virtual void Replace(int from, int to, object text)\n        {\n            Replace(DefaultProgramName, from, to, text);\n        }\n\n        public virtual void Replace(IToken indexT, object text)\n        {\n            Replace(DefaultProgramName, indexT, indexT, text);\n        }\n\n        public virtual void Replace(IToken from, IToken to, object text)\n        {\n            Replace(DefaultProgramName, from, to, text);\n        }\n\n        public virtual void Replace(string programName, int from, int to, object text)\n        {\n            if (from > to || from < 0 || to < 0 || to >= tokens.Size)\n            {\n                throw new ArgumentException(\"replace: range invalid: \" + from + \"..\" + to + \"(size=\" + tokens.Size + \")\");\n            }\n            TokenStreamRewriter.RewriteOperation op = new TokenStreamRewriter.ReplaceOp(tokens, from, to, text);\n            IList<TokenStreamRewriter.RewriteOperation> rewrites = GetProgram(programName);\n            op.instructionIndex = rewrites.Count;\n            rewrites.Add(op);\n        }\n\n        public virtual void Replace(string programName, IToken from, IToken to, object text)\n        {\n            Replace(programName, from.TokenIndex, to.TokenIndex, text);\n        }\n\n        public virtual void Delete(int index)\n        {\n            Delete(DefaultProgramName, index, index);\n        }\n\n        public virtual void Delete(int from, int to)\n        {\n            Delete(DefaultProgramName, from, to);\n        }\n\n        public virtual void Delete(IToken indexT)\n        {\n            Delete(DefaultProgramName, indexT, indexT);\n        }\n\n        public virtual void Delete(IToken from, IToken to)\n        {\n            Delete(DefaultProgramName, from, to);\n        }\n\n        public virtual void Delete(string programName, int from, int to)\n        {\n            Replace(programName, from, to, null);\n        }\n\n        public virtual void Delete(string programName, IToken from, IToken to)\n        {\n            Replace(programName, from, to, null);\n        }\n\n        public virtual int LastRewriteTokenIndex\n        {\n            get\n            {\n                return GetLastRewriteTokenIndex(DefaultProgramName);\n            }\n        }\n\n        protected internal virtual int GetLastRewriteTokenIndex(string programName)\n        {\n            int I;\n            if (!lastRewriteTokenIndexes.TryGetValue(programName, out I))\n            {\n                return -1;\n            }\n            return I;\n        }\n\n        protected internal virtual void SetLastRewriteTokenIndex(string programName, int i)\n        {\n            lastRewriteTokenIndexes[programName] = i;\n        }\n\n        protected internal virtual IList<TokenStreamRewriter.RewriteOperation> GetProgram(string name)\n        {\n            IList<TokenStreamRewriter.RewriteOperation> @is;\n            if (!programs.TryGetValue(name, out @is))\n            {\n                @is = InitializeProgram(name);\n            }\n            return @is;\n        }\n\n        private IList<TokenStreamRewriter.RewriteOperation> InitializeProgram(string name)\n        {\n            IList<TokenStreamRewriter.RewriteOperation> @is = new List<TokenStreamRewriter.RewriteOperation>(ProgramInitSize);\n            programs[name] = @is;\n            return @is;\n        }\n\n        /// <summary>\n        /// Return the text from the original tokens altered per the\n        /// instructions given to this rewriter.\n        /// </summary>\n        /// <remarks>\n        /// Return the text from the original tokens altered per the\n        /// instructions given to this rewriter.\n        /// </remarks>\n        public virtual string GetText()\n        {\n            return GetText(DefaultProgramName, Interval.Of(0, tokens.Size - 1));\n        }\n\n        /// <summary>\n        /// Return the text associated with the tokens in the interval from the\n        /// original token stream but with the alterations given to this rewriter.\n        /// </summary>\n        /// <remarks>\n        /// Return the text associated with the tokens in the interval from the\n        /// original token stream but with the alterations given to this rewriter.\n        /// The interval refers to the indexes in the original token stream.\n        /// We do not alter the token stream in any way, so the indexes\n        /// and intervals are still consistent. Includes any operations done\n        /// to the first and last token in the interval. So, if you did an\n        /// insertBefore on the first token, you would get that insertion.\n        /// The same is true if you do an insertAfter the stop token.\n        /// </remarks>\n        public virtual string GetText(Interval interval)\n        {\n            return GetText(DefaultProgramName, interval);\n        }\n\n        public virtual string GetText(string programName, Interval interval)\n        {\n            IList<TokenStreamRewriter.RewriteOperation> rewrites;\n            if (!programs.TryGetValue(programName, out rewrites))\n                rewrites = null;\n\n            int start = interval.a;\n            int stop = interval.b;\n            // ensure start/end are in range\n            if (stop > tokens.Size - 1)\n            {\n                stop = tokens.Size - 1;\n            }\n            if (start < 0)\n            {\n                start = 0;\n            }\n            if (rewrites == null || rewrites.Count == 0)\n            {\n                return tokens.GetText(interval);\n            }\n            // no instructions to execute\n            StringBuilder buf = new StringBuilder();\n            // First, optimize instruction stream\n            IDictionary<int, TokenStreamRewriter.RewriteOperation> indexToOp = ReduceToSingleOperationPerIndex(rewrites);\n            // Walk buffer, executing instructions and emitting tokens\n            int i = start;\n            while (i <= stop && i < tokens.Size)\n            {\n                TokenStreamRewriter.RewriteOperation op;\n                if (indexToOp.TryGetValue(i, out op))\n                    indexToOp.Remove(i);\n\n                // remove so any left have index size-1\n                IToken t = tokens.Get(i);\n                if (op == null)\n                {\n                    // no operation at that index, just dump token\n                    if (t.Type != TokenConstants.EOF)\n                    {\n                        buf.Append(t.Text);\n                    }\n                    i++;\n                }\n                else\n                {\n                    // move to next token\n                    i = op.Execute(buf);\n                }\n            }\n            // execute operation and skip\n            // include stuff after end if it's last index in buffer\n            // So, if they did an insertAfter(lastValidIndex, \"foo\"), include\n            // foo if end==lastValidIndex.\n            if (stop == tokens.Size - 1)\n            {\n                // Scan any remaining operations after last token\n                // should be included (they will be inserts).\n                foreach (TokenStreamRewriter.RewriteOperation op in indexToOp.Values)\n                {\n                    if (op.index >= tokens.Size - 1)\n                    {\n                        buf.Append(op.text);\n                    }\n                }\n            }\n            return buf.ToString();\n        }\n\n        /// <summary>\n        /// We need to combine operations and report invalid operations (like\n        /// overlapping replaces that are not completed nested).\n        /// </summary>\n        /// <remarks>\n        /// We need to combine operations and report invalid operations (like\n        /// overlapping replaces that are not completed nested). Inserts to\n        /// same index need to be combined etc...  Here are the cases:\n        /// I.i.u I.j.v\t\t\t\t\t\t\t\tleave alone, nonoverlapping\n        /// I.i.u I.i.v\t\t\t\t\t\t\t\tcombine: Iivu\n        /// R.i-j.u R.x-y.v\t| i-j in x-y\t\t\tdelete first R\n        /// R.i-j.u R.i-j.v\t\t\t\t\t\t\tdelete first R\n        /// R.i-j.u R.x-y.v\t| x-y in i-j\t\t\tERROR\n        /// R.i-j.u R.x-y.v\t| boundaries overlap\tERROR\n        /// Delete special case of replace (text==null):\n        /// D.i-j.u D.x-y.v\t| boundaries overlap\tcombine to max(min)..max(right)\n        /// I.i.u R.x-y.v | i in (x+1)-y\t\t\tdelete I (since insert before\n        /// we're not deleting i)\n        /// I.i.u R.x-y.v | i not in (x+1)-y\t\tleave alone, nonoverlapping\n        /// R.x-y.v I.i.u | i in x-y\t\t\t\tERROR\n        /// R.x-y.v I.x.u \t\t\t\t\t\t\tR.x-y.uv (combine, delete I)\n        /// R.x-y.v I.i.u | i not in x-y\t\t\tleave alone, nonoverlapping\n        /// I.i.u = insert u before op @ index i\n        /// R.x-y.u = replace x-y indexed tokens with u\n        /// First we need to examine replaces. For any replace op:\n        /// 1. wipe out any insertions before op within that range.\n        /// 2. Drop any replace op before that is contained completely within\n        /// that range.\n        /// 3. Throw exception upon boundary overlap with any previous replace.\n        /// Then we can deal with inserts:\n        /// 1. for any inserts to same index, combine even if not adjacent.\n        /// 2. for any prior replace with same left boundary, combine this\n        /// insert with replace and delete this replace.\n        /// 3. throw exception if index in same range as previous replace\n        /// Don't actually delete; make op null in list. Easier to walk list.\n        /// Later we can throw as we add to index &#x2192; op map.\n        /// Note that I.2 R.2-2 will wipe out I.2 even though, technically, the\n        /// inserted stuff would be before the replace range. But, if you\n        /// add tokens in front of a method body '{' and then delete the method\n        /// body, I think the stuff before the '{' you added should disappear too.\n        /// Return a map from token index to operation.\n        /// </remarks>\n        protected internal virtual IDictionary<int, TokenStreamRewriter.RewriteOperation> ReduceToSingleOperationPerIndex(IList<TokenStreamRewriter.RewriteOperation> rewrites)\n        {\n            //\t\tSystem.out.println(\"rewrites=\"+rewrites);\n            // WALK REPLACES\n            for (int i = 0; i < rewrites.Count; i++)\n            {\n                TokenStreamRewriter.RewriteOperation op = rewrites[i];\n                if (op == null)\n                {\n                    continue;\n                }\n                if (!(op is TokenStreamRewriter.ReplaceOp))\n                {\n                    continue;\n                }\n                TokenStreamRewriter.ReplaceOp rop = (TokenStreamRewriter.ReplaceOp)rewrites[i];\n                // Wipe prior inserts within range\n                IList<TokenStreamRewriter.InsertBeforeOp> inserts = GetKindOfOps<TokenStreamRewriter.InsertBeforeOp>(rewrites, i);\n                foreach (TokenStreamRewriter.InsertBeforeOp iop in inserts)\n                {\n                    if (iop.index == rop.index)\n                    {\n                        // E.g., insert before 2, delete 2..2; update replace\n                        // text to include insert before, kill insert\n                        rewrites[iop.instructionIndex] = null;\n                        rop.text = iop.text.ToString() + (rop.text != null ? rop.text.ToString() : string.Empty);\n                    }\n                    else\n                    {\n                        if (iop.index > rop.index && iop.index <= rop.lastIndex)\n                        {\n                            // delete insert as it's a no-op.\n                            rewrites[iop.instructionIndex] = null;\n                        }\n                    }\n                }\n                // Drop any prior replaces contained within\n                IList<TokenStreamRewriter.ReplaceOp> prevReplaces = GetKindOfOps<TokenStreamRewriter.ReplaceOp>(rewrites, i);\n                foreach (TokenStreamRewriter.ReplaceOp prevRop in prevReplaces)\n                {\n                    if (prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex)\n                    {\n                        // delete replace as it's a no-op.\n                        rewrites[prevRop.instructionIndex] = null;\n                        continue;\n                    }\n                    // throw exception unless disjoint or identical\n                    bool disjoint = prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex;\n                    // Delete special case of replace (text==null):\n                    // D.i-j.u D.x-y.v\t| boundaries overlap\tcombine to max(min)..max(right)\n                    if (prevRop.text == null && rop.text == null && !disjoint)\n                    {\n                        //System.out.println(\"overlapping deletes: \"+prevRop+\", \"+rop);\n                        rewrites[prevRop.instructionIndex] = null;\n                        // kill first delete\n                        rop.index = Math.Min(prevRop.index, rop.index);\n                        rop.lastIndex = Math.Max(prevRop.lastIndex, rop.lastIndex);\n                        System.Console.Out.WriteLine(\"new rop \" + rop);\n                    }\n                    else\n                    {\n                        if (!disjoint)\n                        {\n                            throw new ArgumentException(\"replace op boundaries of \" + rop + \" overlap with previous \" + prevRop);\n                        }\n                    }\n                }\n            }\n            // WALK INSERTS\n            for (int i_1 = 0; i_1 < rewrites.Count; i_1++)\n            {\n                TokenStreamRewriter.RewriteOperation op = rewrites[i_1];\n                if (op == null)\n                {\n                    continue;\n                }\n                if (!(op is TokenStreamRewriter.InsertBeforeOp))\n                {\n                    continue;\n                }\n                TokenStreamRewriter.InsertBeforeOp iop = (TokenStreamRewriter.InsertBeforeOp)rewrites[i_1];\n                // combine current insert with prior if any at same index\n                IList<TokenStreamRewriter.InsertBeforeOp> prevInserts = GetKindOfOps<TokenStreamRewriter.InsertBeforeOp>(rewrites, i_1);\n                foreach (TokenStreamRewriter.InsertBeforeOp prevIop in prevInserts)\n                {\n                    if (prevIop.index == iop.index)\n                    {\n                        // combine objects\n                        // convert to strings...we're in process of toString'ing\n                        // whole token buffer so no lazy eval issue with any templates\n                        iop.text = CatOpText(iop.text, prevIop.text);\n                        // delete redundant prior insert\n                        rewrites[prevIop.instructionIndex] = null;\n                    }\n                }\n                // look for replaces where iop.index is in range; error\n                IList<TokenStreamRewriter.ReplaceOp> prevReplaces = GetKindOfOps<TokenStreamRewriter.ReplaceOp>(rewrites, i_1);\n                foreach (TokenStreamRewriter.ReplaceOp rop in prevReplaces)\n                {\n                    if (iop.index == rop.index)\n                    {\n                        rop.text = CatOpText(iop.text, rop.text);\n                        rewrites[i_1] = null;\n                        // delete current insert\n                        continue;\n                    }\n                    if (iop.index >= rop.index && iop.index <= rop.lastIndex)\n                    {\n                        throw new ArgumentException(\"insert op \" + iop + \" within boundaries of previous \" + rop);\n                    }\n                }\n            }\n            // System.out.println(\"rewrites after=\"+rewrites);\n            IDictionary<int, TokenStreamRewriter.RewriteOperation> m = new Dictionary<int, TokenStreamRewriter.RewriteOperation>();\n            for (int i_2 = 0; i_2 < rewrites.Count; i_2++)\n            {\n                TokenStreamRewriter.RewriteOperation op = rewrites[i_2];\n                if (op == null)\n                {\n                    continue;\n                }\n                // ignore deleted ops\n                if (m.ContainsKey(op.index))\n                {\n                    throw new InvalidOperationException(\"should only be one op per index\");\n                }\n                m[op.index] = op;\n            }\n            //System.out.println(\"index to op: \"+m);\n            return m;\n        }\n\n        protected internal virtual string CatOpText(object a, object b)\n        {\n            string x = string.Empty;\n            string y = string.Empty;\n            if (a != null)\n            {\n                x = a.ToString();\n            }\n            if (b != null)\n            {\n                y = b.ToString();\n            }\n            return x + y;\n        }\n\n        /// <summary>Get all operations before an index of a particular kind</summary>\n        protected internal virtual IList<T> GetKindOfOps<T>(IList<RewriteOperation> rewrites, int before)\n        {\n            return rewrites.Take(before).OfType<T>().ToList();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/TokenTypes.cs",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime\n{\n    public static class TokenTypes\n    {\n        public const int More = -2;\n\n        public const int Skip = -3;\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/AbstractParseTreeVisitor.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\n\nnamespace Antlr4.Runtime.Tree\n{\n    public abstract class AbstractParseTreeVisitor<Result> : IParseTreeVisitor<Result>\n    {\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation calls\n        /// <see cref=\"IParseTree.Accept{T}(IParseTreeVisitor{T})\"/>\n        /// on the\n        /// specified tree.</p>\n        /// </summary>\n        public virtual Result Visit(IParseTree tree)\n        {\n            return tree.Accept(this);\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation initializes the aggregate result to\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.DefaultResult()\">defaultResult()</see>\n        /// . Before visiting each child, it\n        /// calls\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.ShouldVisitNextChild(IRuleNode, Result)\">shouldVisitNextChild</see>\n        /// ; if the result\n        /// is\n        /// <see langword=\"false\"/>\n        /// no more children are visited and the current aggregate\n        /// result is returned. After visiting a child, the aggregate result is\n        /// updated by calling\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.AggregateResult(Result, Result)\">aggregateResult</see>\n        /// with the\n        /// previous aggregate result and the result of visiting the child.</p>\n        /// <p>The default implementation is not safe for use in visitors that modify\n        /// the tree structure. Visitors that modify the tree should override this\n        /// method to behave properly in respect to the specific algorithm in use.</p>\n        /// </summary>\n        public virtual Result VisitChildren(IRuleNode node)\n        {\n            Result result = DefaultResult;\n            int n = node.ChildCount;\n            for (int i = 0; i < n; i++)\n            {\n                if (!ShouldVisitNextChild(node, result))\n                {\n                    break;\n                }\n                IParseTree c = node.GetChild(i);\n                Result childResult = c.Accept(this);\n                result = AggregateResult(result, childResult);\n            }\n            return result;\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation returns the result of\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.DefaultResult()\">defaultResult</see>\n        /// .</p>\n        /// </summary>\n        public virtual Result VisitTerminal(ITerminalNode node)\n        {\n            return DefaultResult;\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The default implementation returns the result of\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.DefaultResult()\">defaultResult</see>\n        /// .</p>\n        /// </summary>\n        public virtual Result VisitErrorNode(IErrorNode node)\n        {\n            return DefaultResult;\n        }\n\n        /// <summary>Gets the default value returned by visitor methods.</summary>\n        /// <remarks>\n        /// Gets the default value returned by visitor methods. This value is\n        /// returned by the default implementations of\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.VisitTerminal(ITerminalNode)\">visitTerminal</see>\n        /// ,\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.VisitErrorNode(IErrorNode)\">visitErrorNode</see>\n        /// .\n        /// The default implementation of\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.VisitChildren(IRuleNode)\">visitChildren</see>\n        /// initializes its aggregate result to this value.\n        /// <p>The base implementation returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>The default value returned by visitor methods.</returns>\n        protected internal virtual Result DefaultResult\n        {\n            get\n            {\n                return default(Result);\n            }\n        }\n\n        /// <summary>Aggregates the results of visiting multiple children of a node.</summary>\n        /// <remarks>\n        /// Aggregates the results of visiting multiple children of a node. After\n        /// either all children are visited or\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.ShouldVisitNextChild(IRuleNode, Result)\"/>\n        /// returns\n        /// <see langword=\"false\"/>\n        /// , the aggregate value is returned as the result of\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.VisitChildren(IRuleNode)\"/>\n        /// .\n        /// <p>The default implementation returns\n        /// <paramref name=\"nextResult\"/>\n        /// , meaning\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.VisitChildren(IRuleNode)\"/>\n        /// will return the result of the last child visited\n        /// (or return the initial value if the node has no children).</p>\n        /// </remarks>\n        /// <param name=\"aggregate\">\n        /// The previous aggregate value. In the default\n        /// implementation, the aggregate value is initialized to\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.DefaultResult()\"/>\n        /// , which is passed as the\n        /// <paramref name=\"aggregate\"/>\n        /// argument\n        /// to this method after the first child node is visited.\n        /// </param>\n        /// <param name=\"nextResult\">\n        /// The result of the immediately preceeding call to visit\n        /// a child node.\n        /// </param>\n        /// <returns>The updated aggregate result.</returns>\n        protected internal virtual Result AggregateResult(Result aggregate, Result nextResult)\n        {\n            return nextResult;\n        }\n\n        /// <summary>\n        /// This method is called after visiting each child in\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.VisitChildren(IRuleNode)\"/>\n        /// . This method is first called before the first\n        /// child is visited; at that point\n        /// <paramref name=\"currentResult\"/>\n        /// will be the initial\n        /// value (in the default implementation, the initial value is returned by a\n        /// call to\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.DefaultResult()\"/>\n        /// . This method is not called after the last\n        /// child is visited.\n        /// <p>The default implementation always returns\n        /// <see langword=\"true\"/>\n        /// , indicating that\n        /// <c>visitChildren</c>\n        /// should only return after all children are visited.\n        /// One reason to override this method is to provide a \"short circuit\"\n        /// evaluation option for situations where the result of visiting a single\n        /// child has the potential to determine the result of the visit operation as\n        /// a whole.</p>\n        /// </summary>\n        /// <param name=\"node\">\n        /// The\n        /// <see cref=\"IRuleNode\"/>\n        /// whose children are currently being\n        /// visited.\n        /// </param>\n        /// <param name=\"currentResult\">\n        /// The current aggregate result of the children visited\n        /// to the current point.\n        /// </param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// to continue visiting children. Otherwise return\n        /// <see langword=\"false\"/>\n        /// to stop visiting children and immediately return the\n        /// current aggregate result from\n        /// <see cref=\"AbstractParseTreeVisitor{Result}.VisitChildren(IRuleNode)\"/>\n        /// .\n        /// </returns>\n        protected internal virtual bool ShouldVisitNextChild(IRuleNode node, Result currentResult)\n        {\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/ErrorNodeImpl.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\n\nnamespace Antlr4.Runtime.Tree\n{\n    /// <summary>\n    /// Represents a token that was consumed during resynchronization\n    /// rather than during a valid match operation.\n    /// </summary>\n    /// <remarks>\n    /// Represents a token that was consumed during resynchronization\n    /// rather than during a valid match operation. For example,\n    /// we will create this kind of a node during single token insertion\n    /// and deletion as well as during \"consume until error recovery set\"\n    /// upon no viable alternative exceptions.\n    /// </remarks>\n    public class ErrorNodeImpl : TerminalNodeImpl, IErrorNode\n    {\n        public ErrorNodeImpl(IToken token)\n            : base(token)\n        {\n        }\n\n        public override T Accept<T>(IParseTreeVisitor<T> visitor)\n        {\n            return visitor.VisitErrorNode(this);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/IErrorNode.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Tree\n{\n    public interface IErrorNode : ITerminalNode\n    {\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/IParseTree.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nnamespace Antlr4.Runtime.Tree\n{\n    /// <summary>\n    /// An interface to access the tree of\n    /// <see cref=\"Antlr4.Runtime.RuleContext\"/>\n    /// objects created\n    /// during a parse that makes the data structure look like a simple parse tree.\n    /// This node represents both internal nodes, rule invocations,\n    /// and leaf nodes, token matches.\n    /// <p>The payload is either a\n    /// <see cref=\"Antlr4.Runtime.IToken\"/>\n    /// or a\n    /// <see cref=\"Antlr4.Runtime.RuleContext\"/>\n    /// object.</p>\n    /// </summary>\n    public interface IParseTree : ISyntaxTree\n    {\n        new IParseTree Parent\n        {\n            get;\n        }\n\n        // the following methods narrow the return type; they are not additional methods\n        new IParseTree GetChild(int i);\n\n        /// <summary>\n        /// The\n        /// <see cref=\"IParseTreeVisitor{Result}\"/>\n        /// needs a double dispatch method.\n        /// </summary>\n        T Accept<T>(IParseTreeVisitor<T> visitor);\n\n        /// <summary>Return the combined text of all leaf nodes.</summary>\n        /// <remarks>\n        /// Return the combined text of all leaf nodes. Does not get any\n        /// off-channel tokens (if any) so won't return whitespace and\n        /// comments if they are sent to parser on hidden channel.\n        /// </remarks>\n        string GetText();\n\n        /// <summary>\n        /// Specialize toStringTree so that it can print out more information\n        /// based upon the parser.\n        /// </summary>\n        /// <remarks>\n        /// Specialize toStringTree so that it can print out more information\n        /// based upon the parser.\n        /// </remarks>\n        string ToStringTree(Parser parser);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/IParseTreeListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Tree\n{\n    public interface IParseTreeListener\n    {\n        void VisitTerminal(ITerminalNode node);\n\n        void VisitErrorNode(IErrorNode node);\n\n        void EnterEveryRule(ParserRuleContext ctx);\n\n        void ExitEveryRule(ParserRuleContext ctx);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/IParseTreeVisitor.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Tree\n{\n    /// <summary>This interface defines the basic notion of a parse tree visitor.</summary>\n    /// <remarks>\n    /// This interface defines the basic notion of a parse tree visitor. Generated\n    /// visitors implement this interface and the\n    /// <c>XVisitor</c>\n    /// interface for\n    /// grammar\n    /// <c>X</c>\n    /// .\n    /// </remarks>\n    /// <author>Sam Harwell</author>\n    public interface IParseTreeVisitor<out Result>\n    {\n        /// <summary>Visit a parse tree, and return a user-defined result of the operation.</summary>\n        /// <remarks>Visit a parse tree, and return a user-defined result of the operation.</remarks>\n        /// <param name=\"tree\">\n        /// The\n        /// <see cref=\"IParseTree\"/>\n        /// to visit.\n        /// </param>\n        /// <returns>The result of visiting the parse tree.</returns>\n        Result Visit(IParseTree tree);\n\n        /// <summary>\n        /// Visit the children of a node, and return a user-defined result\n        /// of the operation.\n        /// </summary>\n        /// <remarks>\n        /// Visit the children of a node, and return a user-defined result\n        /// of the operation.\n        /// </remarks>\n        /// <param name=\"node\">\n        /// The\n        /// <see cref=\"IRuleNode\"/>\n        /// whose children should be visited.\n        /// </param>\n        /// <returns>The result of visiting the children of the node.</returns>\n        Result VisitChildren(IRuleNode node);\n\n        /// <summary>Visit a terminal node, and return a user-defined result of the operation.</summary>\n        /// <remarks>Visit a terminal node, and return a user-defined result of the operation.</remarks>\n        /// <param name=\"node\">\n        /// The\n        /// <see cref=\"ITerminalNode\"/>\n        /// to visit.\n        /// </param>\n        /// <returns>The result of visiting the node.</returns>\n        Result VisitTerminal(ITerminalNode node);\n\n        /// <summary>Visit an error node, and return a user-defined result of the operation.</summary>\n        /// <remarks>Visit an error node, and return a user-defined result of the operation.</remarks>\n        /// <param name=\"node\">\n        /// The\n        /// <see cref=\"IErrorNode\"/>\n        /// to visit.\n        /// </param>\n        /// <returns>The result of visiting the node.</returns>\n        Result VisitErrorNode(IErrorNode node);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/IRuleNode.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Tree;\n\nnamespace Antlr4.Runtime.Tree\n{\n    public interface IRuleNode : IParseTree\n    {\n        Antlr4.Runtime.RuleContext RuleContext\n        {\n            get;\n        }\n\n        new IRuleNode Parent\n        {\n            get;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/ISyntaxTree.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Tree;\n\nnamespace Antlr4.Runtime.Tree\n{\n    /// <summary>\n    /// A tree that knows about an interval in a token stream\n    /// is some kind of syntax tree.\n    /// </summary>\n    /// <remarks>\n    /// A tree that knows about an interval in a token stream\n    /// is some kind of syntax tree. Subinterfaces distinguish\n    /// between parse trees and other kinds of syntax trees we might want to create.\n    /// </remarks>\n    public interface ISyntaxTree : ITree\n    {\n        /// <summary>\n        /// Return an\n        /// <see cref=\"Antlr4.Runtime.Misc.Interval\"/>\n        /// indicating the index in the\n        /// <see cref=\"Antlr4.Runtime.ITokenStream\"/>\n        /// of the first and last token associated with this\n        /// subtree. If this node is a leaf, then the interval represents a single\n        /// token.\n        /// <p>If source interval is unknown, this returns\n        /// <see cref=\"Antlr4.Runtime.Misc.Interval.Invalid\"/>\n        /// .</p>\n        /// </summary>\n        Interval SourceInterval\n        {\n            get;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/ITerminalNode.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Tree\n{\n    public interface ITerminalNode : IParseTree\n    {\n        IToken Symbol\n        {\n            get;\n        }\n\n        new IRuleNode Parent\n        {\n            get;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/ITree.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Tree\n{\n    /// <summary>The basic notion of a tree has a parent, a payload, and a list of children.</summary>\n    /// <remarks>\n    /// The basic notion of a tree has a parent, a payload, and a list of children.\n    /// It is the most abstract interface for all the trees used by ANTLR.\n    /// </remarks>\n    public interface ITree\n    {\n        /// <summary>The parent of this node.</summary>\n        /// <remarks>\n        /// The parent of this node. If the return value is null, then this\n        /// node is the root of the tree.\n        /// </remarks>\n        ITree Parent\n        {\n            get;\n        }\n\n        /// <summary>This method returns whatever object represents the data at this note.</summary>\n        /// <remarks>\n        /// This method returns whatever object represents the data at this note. For\n        /// example, for parse trees, the payload can be a\n        /// <see cref=\"Antlr4.Runtime.IToken\"/>\n        /// representing\n        /// a leaf node or a\n        /// <see cref=\"Antlr4.Runtime.RuleContext\"/>\n        /// object representing a rule\n        /// invocation. For abstract syntax trees (ASTs), this is a\n        /// <see cref=\"Antlr4.Runtime.IToken\"/>\n        /// object.\n        /// </remarks>\n        object Payload\n        {\n            get;\n        }\n\n        /// <summary>\n        /// If there are children, get the\n        /// <paramref name=\"i\"/>\n        /// th value indexed from 0.\n        /// </summary>\n        ITree GetChild(int i);\n\n        /// <summary>\n        /// How many children are there? If there is none, then this\n        /// node represents a leaf node.\n        /// </summary>\n        /// <remarks>\n        /// How many children are there? If there is none, then this\n        /// node represents a leaf node.\n        /// </remarks>\n        int ChildCount\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Print out a whole tree, not just a node, in LISP format\n        /// <c>(root child1 .. childN)</c>\n        /// . Print just a node if this is a leaf.\n        /// </summary>\n        string ToStringTree();\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/ParseTreeProperty.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Concurrent;\n\nnamespace Antlr4.Runtime.Tree\n{\n    /// <summary>Associate a property with a parse tree node.</summary>\n    /// <remarks>\n    /// Associate a property with a parse tree node. Useful with parse tree listeners\n    /// that need to associate values with particular tree nodes, kind of like\n    /// specifying a return value for the listener event method that visited a\n    /// particular node. Example:\n    /// <pre>\n    /// ParseTreeProperty&lt;Integer&gt; values = new ParseTreeProperty&lt;Integer&gt;();\n    /// values.put(tree, 36);\n    /// int x = values.get(tree);\n    /// values.removeFrom(tree);\n    /// </pre>\n    /// You would make one decl (values here) in the listener and use lots of times\n    /// in your event methods.\n    /// </remarks>\n    public class ParseTreeProperty<V>\n    {\n        protected internal ConcurrentDictionary<IParseTree, V> annotations = new ConcurrentDictionary<IParseTree, V>();\n\n        public virtual V Get(IParseTree node)\n        {\n            V value;\n            if (!annotations.TryGetValue(node, out value))\n                return default(V);\n\n            return value;\n        }\n\n        public virtual void Put(IParseTree node, V value)\n        {\n            annotations[node] = value;\n        }\n\n        public virtual V RemoveFrom(IParseTree node)\n        {\n            V value;\n            if (!annotations.TryRemove(node, out value))\n                return default(V);\n\n            return value;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/ParseTreeWalker.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nnamespace Antlr4.Runtime.Tree\n{\n    public class ParseTreeWalker\n    {\n        public static readonly ParseTreeWalker Default = new ParseTreeWalker();\n\n        /// <summary>\n        /// Performs a walk on the given parse tree starting at the root and going down recursively\n\t    /// with depth-first search. On each node, \n        /// <see cref=\"ParseTreeWalker.EnterRule(IParseTreeListener, IRuleNode)\"/> is called before\n\t    /// recursively walking down into child nodes, then\n\t    /// <see cref=\"ParseTreeWalker.ExitRule(IParseTreeListener, IRuleNode)\"/>\n        /// is called after the recursive call to wind up.\n        /// </summary>\n        /// <param name=\"listener\">The listener used by the walker to process grammar rules</param>\n        /// <param name=\"t\">The parse tree to be walked on</param>\n        public virtual void Walk(IParseTreeListener listener, IParseTree t)\n        {\n            if (t is IErrorNode)\n            {\n                listener.VisitErrorNode((IErrorNode)t);\n                return;\n            }\n            else\n            {\n                if (t is ITerminalNode)\n                {\n                    listener.VisitTerminal((ITerminalNode)t);\n                    return;\n                }\n            }\n            IRuleNode r = (IRuleNode)t;\n            EnterRule(listener, r);\n            int n = r.ChildCount;\n            for (int i = 0; i < n; i++)\n            {\n                Walk(listener, r.GetChild(i));\n            }\n            ExitRule(listener, r);\n        }\n\n        /// <summary>\n        /// Enters a grammar rule by first triggering the generic event \n        /// <see cref=\"IParseTreeListener.EnterEveryRule\"/>\n\t    /// then by triggering the event specific to the given parse tree node\n        /// </summary>\n        /// <param name=\"listener\"> The listener responding to the trigger events </param>\n        /// <param name=\"r\">The grammar rule containing the rule context</param>\n        protected internal virtual void EnterRule(IParseTreeListener listener, IRuleNode r)\n        {\n            ParserRuleContext ctx = (ParserRuleContext)r.RuleContext;\n            listener.EnterEveryRule(ctx);\n            ctx.EnterRule(listener);\n        }\n\n        /// <summary>\n        /// Exits a grammar rule by first triggering the event specific to the given parse tree node\n\t    /// then by triggering the generic event \n        /// <see cref=\"IParseTreeListener.ExitEveryRule\"/>\n        /// </summary>\n        /// <param name=\"listener\"> The listener responding to the trigger events </param>\n        /// <param name=\"r\">The grammar rule containing the rule context</param>\n        protected internal virtual void ExitRule(IParseTreeListener listener, IRuleNode r)\n        {\n            ParserRuleContext ctx = (ParserRuleContext)r.RuleContext;\n            ctx.ExitRule(listener);\n            listener.ExitEveryRule(ctx);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/Chunk.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree.Pattern;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>\n    /// A chunk is either a token tag, a rule tag, or a span of literal text within a\n    /// tree pattern.\n    /// </summary>\n    /// <remarks>\n    /// A chunk is either a token tag, a rule tag, or a span of literal text within a\n    /// tree pattern.\n    /// <p>The method\n    /// <see cref=\"ParseTreePatternMatcher.Split(string)\"/>\n    /// returns a list of\n    /// chunks in preparation for creating a token stream by\n    /// <see cref=\"ParseTreePatternMatcher.Tokenize(string)\"/>\n    /// . From there, we get a parse\n    /// tree from with\n    /// <see cref=\"ParseTreePatternMatcher.Compile(string, int)\"/>\n    /// . These\n    /// chunks are converted to\n    /// <see cref=\"RuleTagToken\"/>\n    /// ,\n    /// <see cref=\"TokenTagToken\"/>\n    /// , or the\n    /// regular tokens of the text surrounding the tags.</p>\n    /// </remarks>\n    internal abstract class Chunk\n    {\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/ParseTreeMatch.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Pattern;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>\n    /// Represents the result of matching a\n    /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n    /// against a tree pattern.\n    /// </summary>\n    public class ParseTreeMatch\n    {\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Tree()\"/>\n        /// .\n        /// </summary>\n        private readonly IParseTree tree;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Pattern()\"/>\n        /// .\n        /// </summary>\n        private readonly ParseTreePattern pattern;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Labels()\"/>\n        /// .\n        /// </summary>\n        private readonly MultiMap<string, IParseTree> labels;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"MismatchedNode()\"/>\n        /// .\n        /// </summary>\n        private readonly IParseTree mismatchedNode;\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"ParseTreeMatch\"/>\n        /// from the specified\n        /// parse tree and pattern.\n        /// </summary>\n        /// <param name=\"tree\">The parse tree to match against the pattern.</param>\n        /// <param name=\"pattern\">The parse tree pattern.</param>\n        /// <param name=\"labels\">\n        /// A mapping from label names to collections of\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// objects located by the tree pattern matching process.\n        /// </param>\n        /// <param name=\"mismatchedNode\">\n        /// The first node which failed to match the tree\n        /// pattern during the matching process.\n        /// </param>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"tree\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"pattern\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"labels\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// </exception>\n        public ParseTreeMatch(IParseTree tree, ParseTreePattern pattern, MultiMap<string, IParseTree> labels, IParseTree mismatchedNode)\n        {\n            if (tree == null)\n            {\n                throw new ArgumentException(\"tree cannot be null\");\n            }\n            if (pattern == null)\n            {\n                throw new ArgumentException(\"pattern cannot be null\");\n            }\n            if (labels == null)\n            {\n                throw new ArgumentException(\"labels cannot be null\");\n            }\n            this.tree = tree;\n            this.pattern = pattern;\n            this.labels = labels;\n            this.mismatchedNode = mismatchedNode;\n        }\n\n        /// <summary>\n        /// Get the last node associated with a specific\n        /// <paramref name=\"label\"/>\n        /// .\n        /// <p>For example, for pattern\n        /// <c>&lt;id:ID&gt;</c>\n        /// ,\n        /// <c>get(\"id\")</c>\n        /// returns the\n        /// node matched for that\n        /// <c>ID</c>\n        /// . If more than one node\n        /// matched the specified label, only the last is returned. If there is\n        /// no node associated with the label, this returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// <p>Pattern tags like\n        /// <c>&lt;ID&gt;</c>\n        /// and\n        /// <c>&lt;expr&gt;</c>\n        /// without labels are\n        /// considered to be labeled with\n        /// <c>ID</c>\n        /// and\n        /// <c>expr</c>\n        /// , respectively.</p>\n        /// </summary>\n        /// <param name=\"label\">The label to check.</param>\n        /// <returns>\n        /// The last\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// to match a tag with the specified\n        /// label, or\n        /// <see langword=\"null\"/>\n        /// if no parse tree matched a tag with the label.\n        /// </returns>\n        [return: Nullable]\n        public virtual IParseTree Get(string label)\n        {\n            IList<IParseTree> parseTrees = labels.Get(label);\n            if (parseTrees == null || parseTrees.Count == 0)\n            {\n                return null;\n            }\n            return parseTrees[parseTrees.Count - 1];\n        }\n\n        // return last if multiple\n        /// <summary>Return all nodes matching a rule or token tag with the specified label.</summary>\n        /// <remarks>\n        /// Return all nodes matching a rule or token tag with the specified label.\n        /// <p>If the\n        /// <paramref name=\"label\"/>\n        /// is the name of a parser rule or token in the\n        /// grammar, the resulting list will contain both the parse trees matching\n        /// rule or tags explicitly labeled with the label and the complete set of\n        /// parse trees matching the labeled and unlabeled tags in the pattern for\n        /// the parser rule or token. For example, if\n        /// <paramref name=\"label\"/>\n        /// is\n        /// <c>\"foo\"</c>\n        /// ,\n        /// the result will contain <em>all</em> of the following.</p>\n        /// <ul>\n        /// <li>Parse tree nodes matching tags of the form\n        /// <c>&lt;foo:anyRuleName&gt;</c>\n        /// and\n        /// <c>&lt;foo:AnyTokenName&gt;</c>\n        /// .</li>\n        /// <li>Parse tree nodes matching tags of the form\n        /// <c>&lt;anyLabel:foo&gt;</c>\n        /// .</li>\n        /// <li>Parse tree nodes matching tags of the form\n        /// <c>&lt;foo&gt;</c>\n        /// .</li>\n        /// </ul>\n        /// </remarks>\n        /// <param name=\"label\">The label.</param>\n        /// <returns>\n        /// A collection of all\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// nodes matching tags with\n        /// the specified\n        /// <paramref name=\"label\"/>\n        /// . If no nodes matched the label, an empty list\n        /// is returned.\n        /// </returns>\n        [return: NotNull]\n        public virtual IList<IParseTree> GetAll(string label)\n        {\n            IList<IParseTree> nodes = labels.Get(label);\n            if (nodes == null)\n            {\n                return Sharpen.Collections.EmptyList<IParseTree>();\n            }\n            return nodes;\n        }\n\n        /// <summary>Return a mapping from label &#x2192; [list of nodes].</summary>\n        /// <remarks>\n        /// Return a mapping from label &#x2192; [list of nodes].\n        /// <p>The map includes special entries corresponding to the names of rules and\n        /// tokens referenced in tags in the original pattern. For additional\n        /// information, see the description of\n        /// <see cref=\"GetAll(string)\"/>\n        /// .</p>\n        /// </remarks>\n        /// <returns>\n        /// A mapping from labels to parse tree nodes. If the parse tree\n        /// pattern did not contain any rule or token tags, this map will be empty.\n        /// </returns>\n        [NotNull]\n        public virtual MultiMap<string, IParseTree> Labels\n        {\n            get\n            {\n                return labels;\n            }\n        }\n\n        /// <summary>Get the node at which we first detected a mismatch.</summary>\n        /// <remarks>Get the node at which we first detected a mismatch.</remarks>\n        /// <returns>\n        /// the node at which we first detected a mismatch, or\n        /// <see langword=\"null\"/>\n        /// if the match was successful.\n        /// </returns>\n        [Nullable]\n        public virtual IParseTree MismatchedNode\n        {\n            get\n            {\n                return mismatchedNode;\n            }\n        }\n\n        /// <summary>Gets a value indicating whether the match operation succeeded.</summary>\n        /// <remarks>Gets a value indicating whether the match operation succeeded.</remarks>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if the match operation succeeded; otherwise,\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public virtual bool Succeeded\n        {\n            get\n            {\n                return mismatchedNode == null;\n            }\n        }\n\n        /// <summary>Get the tree pattern we are matching against.</summary>\n        /// <remarks>Get the tree pattern we are matching against.</remarks>\n        /// <returns>The tree pattern we are matching against.</returns>\n        [NotNull]\n        public virtual ParseTreePattern Pattern\n        {\n            get\n            {\n                return pattern;\n            }\n        }\n\n        /// <summary>Get the parse tree we are trying to match to a pattern.</summary>\n        /// <remarks>Get the parse tree we are trying to match to a pattern.</remarks>\n        /// <returns>\n        /// The\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// we are trying to match to a pattern.\n        /// </returns>\n        [NotNull]\n        public virtual IParseTree Tree\n        {\n            get\n            {\n                return tree;\n            }\n        }\n\n        /// <summary><inheritDoc/></summary>\n        public override string ToString()\n        {\n            return string.Format(\"Match {0}; found {1} labels\", Succeeded ? \"succeeded\" : \"failed\", Labels.Count);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/ParseTreePattern.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Pattern;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>\n    /// A pattern like\n    /// <c>&lt;ID&gt; = &lt;expr&gt;;</c>\n    /// converted to a\n    /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n    /// by\n    /// <see cref=\"ParseTreePatternMatcher.Compile(string, int)\"/>\n    /// .\n    /// </summary>\n    public class ParseTreePattern\n    {\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"PatternRuleIndex()\"/>\n        /// .\n        /// </summary>\n        private readonly int patternRuleIndex;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Pattern()\"/>\n        /// .\n        /// </summary>\n        [NotNull]\n        private readonly string pattern;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"PatternTree()\"/>\n        /// .\n        /// </summary>\n        [NotNull]\n        private readonly IParseTree patternTree;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Matcher()\"/>\n        /// .\n        /// </summary>\n        [NotNull]\n        private readonly ParseTreePatternMatcher matcher;\n\n        /// <summary>\n        /// Construct a new instance of the\n        /// <see cref=\"ParseTreePattern\"/>\n        /// class.\n        /// </summary>\n        /// <param name=\"matcher\">\n        /// The\n        /// <see cref=\"ParseTreePatternMatcher\"/>\n        /// which created this\n        /// tree pattern.\n        /// </param>\n        /// <param name=\"pattern\">The tree pattern in concrete syntax form.</param>\n        /// <param name=\"patternRuleIndex\">\n        /// The parser rule which serves as the root of the\n        /// tree pattern.\n        /// </param>\n        /// <param name=\"patternTree\">\n        /// The tree pattern in\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// form.\n        /// </param>\n        public ParseTreePattern(ParseTreePatternMatcher matcher, string pattern, int patternRuleIndex, IParseTree patternTree)\n        {\n            this.matcher = matcher;\n            this.patternRuleIndex = patternRuleIndex;\n            this.pattern = pattern;\n            this.patternTree = patternTree;\n        }\n\n        /// <summary>Match a specific parse tree against this tree pattern.</summary>\n        /// <remarks>Match a specific parse tree against this tree pattern.</remarks>\n        /// <param name=\"tree\">The parse tree to match against this tree pattern.</param>\n        /// <returns>\n        /// A\n        /// <see cref=\"ParseTreeMatch\"/>\n        /// object describing the result of the\n        /// match operation. The\n        /// <see cref=\"ParseTreeMatch.Succeeded()\"/>\n        /// method can be\n        /// used to determine whether or not the match was successful.\n        /// </returns>\n        [return: NotNull]\n        public virtual ParseTreeMatch Match(IParseTree tree)\n        {\n            return matcher.Match(tree, this);\n        }\n\n        /// <summary>Determine whether or not a parse tree matches this tree pattern.</summary>\n        /// <remarks>Determine whether or not a parse tree matches this tree pattern.</remarks>\n        /// <param name=\"tree\">The parse tree to match against this tree pattern.</param>\n        /// <returns>\n        ///\n        /// <see langword=\"true\"/>\n        /// if\n        /// <paramref name=\"tree\"/>\n        /// is a match for the current tree\n        /// pattern; otherwise,\n        /// <see langword=\"false\"/>\n        /// .\n        /// </returns>\n        public virtual bool Matches(IParseTree tree)\n        {\n            return matcher.Match(tree, this).Succeeded;\n        }\n\n        /// <summary>\n        /// Find all nodes using XPath and then try to match those subtrees against\n        /// this tree pattern.\n        /// </summary>\n        /// <remarks>\n        /// Find all nodes using XPath and then try to match those subtrees against\n        /// this tree pattern.\n        /// </remarks>\n        /// <param name=\"tree\">\n        /// The\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// to match against this pattern.\n        /// </param>\n        /// <param name=\"xpath\">An expression matching the nodes</param>\n        /// <returns>\n        /// A collection of\n        /// <see cref=\"ParseTreeMatch\"/>\n        /// objects describing the\n        /// successful matches. Unsuccessful matches are omitted from the result,\n        /// regardless of the reason for the failure.\n        /// </returns>\n        [return: NotNull]\n        public virtual IList<ParseTreeMatch> FindAll(IParseTree tree, string xpath)\n        {\n            ICollection<IParseTree> subtrees = XPath.FindAll(tree, xpath, matcher.Parser);\n            IList<ParseTreeMatch> matches = new List<ParseTreeMatch>();\n            foreach (IParseTree t in subtrees)\n            {\n                ParseTreeMatch match = Match(t);\n                if (match.Succeeded)\n                {\n                    matches.Add(match);\n                }\n            }\n            return matches;\n        }\n\n        /// <summary>\n        /// Get the\n        /// <see cref=\"ParseTreePatternMatcher\"/>\n        /// which created this tree pattern.\n        /// </summary>\n        /// <returns>\n        /// The\n        /// <see cref=\"ParseTreePatternMatcher\"/>\n        /// which created this tree\n        /// pattern.\n        /// </returns>\n        [NotNull]\n        public virtual ParseTreePatternMatcher Matcher\n        {\n            get\n            {\n                return matcher;\n            }\n        }\n\n        /// <summary>Get the tree pattern in concrete syntax form.</summary>\n        /// <remarks>Get the tree pattern in concrete syntax form.</remarks>\n        /// <returns>The tree pattern in concrete syntax form.</returns>\n        [NotNull]\n        public virtual string Pattern\n        {\n            get\n            {\n                return pattern;\n            }\n        }\n\n        /// <summary>\n        /// Get the parser rule which serves as the outermost rule for the tree\n        /// pattern.\n        /// </summary>\n        /// <remarks>\n        /// Get the parser rule which serves as the outermost rule for the tree\n        /// pattern.\n        /// </remarks>\n        /// <returns>\n        /// The parser rule which serves as the outermost rule for the tree\n        /// pattern.\n        /// </returns>\n        public virtual int PatternRuleIndex\n        {\n            get\n            {\n                return patternRuleIndex;\n            }\n        }\n\n        /// <summary>\n        /// Get the tree pattern as a\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// . The rule and token tags from\n        /// the pattern are present in the parse tree as terminal nodes with a symbol\n        /// of type\n        /// <see cref=\"RuleTagToken\"/>\n        /// or\n        /// <see cref=\"TokenTagToken\"/>\n        /// .\n        /// </summary>\n        /// <returns>\n        /// The tree pattern as a\n        /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n        /// .\n        /// </returns>\n        [NotNull]\n        public virtual IParseTree PatternTree\n        {\n            get\n            {\n                return patternTree;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/ParseTreePatternMatcher.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Pattern;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>\n    /// A tree pattern matching mechanism for ANTLR\n    /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n    /// s.\n    /// <p>Patterns are strings of source input text with special tags representing\n    /// token or rule references such as:</p>\n    /// <p>\n    /// <c>&lt;ID&gt; = &lt;expr&gt;;</c>\n    /// </p>\n    /// <p>Given a pattern start rule such as\n    /// <c>statement</c>\n    /// , this object constructs\n    /// a\n    /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n    /// with placeholders for the\n    /// <c>ID</c>\n    /// and\n    /// <c>expr</c>\n    /// subtree. Then the\n    /// <see cref=\"Match(Antlr4.Runtime.Tree.IParseTree, ParseTreePattern)\"/>\n    /// routines can compare an actual\n    /// <see cref=\"Antlr4.Runtime.Tree.IParseTree\"/>\n    /// from a parse with this pattern. Tag\n    /// <c>&lt;ID&gt;</c>\n    /// matches\n    /// any\n    /// <c>ID</c>\n    /// token and tag\n    /// <c>&lt;expr&gt;</c>\n    /// references the result of the\n    /// <c>expr</c>\n    /// rule (generally an instance of\n    /// <c>ExprContext</c>\n    /// .</p>\n    /// <p>Pattern\n    /// <c>x = 0;</c>\n    /// is a similar pattern that matches the same pattern\n    /// except that it requires the identifier to be\n    /// <c>x</c>\n    /// and the expression to\n    /// be\n    /// <c>0</c>\n    /// .</p>\n    /// <p>The\n    /// <see cref=\"Matches(Antlr4.Runtime.Tree.IParseTree, ParseTreePattern)\"/>\n    /// routines return\n    /// <see langword=\"true\"/>\n    /// or\n    /// <see langword=\"false\"/>\n    /// based\n    /// upon a match for the tree rooted at the parameter sent in. The\n    /// <see cref=\"Match(Antlr4.Runtime.Tree.IParseTree, ParseTreePattern)\"/>\n    /// routines return a\n    /// <see cref=\"ParseTreeMatch\"/>\n    /// object that\n    /// contains the parse tree, the parse tree pattern, and a map from tag name to\n    /// matched nodes (more below). A subtree that fails to match, returns with\n    /// <see cref=\"ParseTreeMatch.MismatchedNode\"/>\n    /// set to the first tree node that did not\n    /// match.</p>\n    /// <p>For efficiency, you can compile a tree pattern in string form to a\n    /// <see cref=\"ParseTreePattern\"/>\n    /// object.</p>\n    /// <p>See\n    /// <c>TestParseTreeMatcher</c>\n    /// for lots of examples.\n    /// <see cref=\"ParseTreePattern\"/>\n    /// has two static helper methods:\n    /// <see cref=\"ParseTreePattern.FindAll(Antlr4.Runtime.Tree.IParseTree, string)\"/>\n    /// and\n    /// <see cref=\"ParseTreePattern.Match(Antlr4.Runtime.Tree.IParseTree)\"/>\n    /// that\n    /// are easy to use but not super efficient because they create new\n    /// <see cref=\"ParseTreePatternMatcher\"/>\n    /// objects each time and have to compile the\n    /// pattern in string form before using it.</p>\n    /// <p>The lexer and parser that you pass into the\n    /// <see cref=\"ParseTreePatternMatcher\"/>\n    /// constructor are used to parse the pattern in string form. The lexer converts\n    /// the\n    /// <c>&lt;ID&gt; = &lt;expr&gt;;</c>\n    /// into a sequence of four tokens (assuming lexer\n    /// throws out whitespace or puts it on a hidden channel). Be aware that the\n    /// input stream is reset for the lexer (but not the parser; a\n    /// <see cref=\"Antlr4.Runtime.ParserInterpreter\"/>\n    /// is created to parse the input.). Any user-defined\n    /// fields you have put into the lexer might get changed when this mechanism asks\n    /// it to scan the pattern string.</p>\n    /// <p>Normally a parser does not accept token\n    /// <c>&lt;expr&gt;</c>\n    /// as a valid\n    /// <c>expr</c>\n    /// but, from the parser passed in, we create a special version of\n    /// the underlying grammar representation (an\n    /// <see cref=\"Antlr4.Runtime.Atn.ATN\"/>\n    /// ) that allows imaginary\n    /// tokens representing rules (\n    /// <c>&lt;expr&gt;</c>\n    /// ) to match entire rules. We call\n    /// these <em>bypass alternatives</em>.</p>\n    /// <p>Delimiters are\n    /// <c>&lt;</c>\n    /// and\n    /// <c>&gt;</c>\n    /// , with\n    /// <c>\\</c>\n    /// as the escape string\n    /// by default, but you can set them to whatever you want using\n    /// <see cref=\"SetDelimiters(string, string, string)\"/>\n    /// . You must escape both start and stop strings\n    /// <c>\\&lt;</c>\n    /// and\n    /// <c>\\&gt;</c>\n    /// .</p>\n    /// </summary>\n    public class ParseTreePatternMatcher\n    {\n        [System.Serializable]\n        public class CannotInvokeStartRule : Exception\n        {\n            public CannotInvokeStartRule(Exception e)\n                : base(e.Message, e)\n            {\n            }\n        }\n\n        [System.Serializable]\n        public class StartRuleDoesNotConsumeFullPattern : Exception\n        {\n            // Fixes https://github.com/antlr/antlr4/issues/413\n            // \"Tree pattern compilation doesn't check for a complete parse\"\n        }\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Lexer()\"/>\n        /// .\n        /// </summary>\n        private readonly Lexer lexer;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Parser()\"/>\n        /// .\n        /// </summary>\n        private readonly Parser parser;\n\n        protected internal string start = \"<\";\n\n        protected internal string stop = \">\";\n\n        protected internal string escape = \"\\\\\";\n\n        /// <summary>\n        /// Constructs a\n        /// <see cref=\"ParseTreePatternMatcher\"/>\n        /// or from a\n        /// <see cref=\"Antlr4.Runtime.Lexer\"/>\n        /// and\n        /// <see cref=\"Antlr4.Runtime.Parser\"/>\n        /// object. The lexer input stream is altered for tokenizing\n        /// the tree patterns. The parser is used as a convenient mechanism to get\n        /// the grammar name, plus token, rule names.\n        /// </summary>\n        public ParseTreePatternMatcher(Lexer lexer, Parser parser)\n        {\n            // e.g., \\< and \\> must escape BOTH!\n            this.lexer = lexer;\n            this.parser = parser;\n        }\n\n        /// <summary>\n        /// Set the delimiters used for marking rule and token tags within concrete\n        /// syntax used by the tree pattern parser.\n        /// </summary>\n        /// <remarks>\n        /// Set the delimiters used for marking rule and token tags within concrete\n        /// syntax used by the tree pattern parser.\n        /// </remarks>\n        /// <param name=\"start\">The start delimiter.</param>\n        /// <param name=\"stop\">The stop delimiter.</param>\n        /// <param name=\"escapeLeft\">The escape sequence to use for escaping a start or stop delimiter.</param>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"start\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// or empty.\n        /// </exception>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"stop\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// or empty.\n        /// </exception>\n        public virtual void SetDelimiters(string start, string stop, string escapeLeft)\n        {\n            if (string.IsNullOrEmpty(start))\n            {\n                throw new ArgumentException(\"start cannot be null or empty\");\n            }\n            if (string.IsNullOrEmpty(stop))\n            {\n                throw new ArgumentException(\"stop cannot be null or empty\");\n            }\n            this.start = start;\n            this.stop = stop;\n            this.escape = escapeLeft;\n        }\n\n        /// <summary>\n        /// Does\n        /// <paramref name=\"pattern\"/>\n        /// matched as rule\n        /// <paramref name=\"patternRuleIndex\"/>\n        /// match\n        /// <paramref name=\"tree\"/>\n        /// ?\n        /// </summary>\n        public virtual bool Matches(IParseTree tree, string pattern, int patternRuleIndex)\n        {\n            ParseTreePattern p = Compile(pattern, patternRuleIndex);\n            return Matches(tree, p);\n        }\n\n        /// <summary>\n        /// Does\n        /// <paramref name=\"pattern\"/>\n        /// matched as rule patternRuleIndex match tree? Pass in a\n        /// compiled pattern instead of a string representation of a tree pattern.\n        /// </summary>\n        public virtual bool Matches(IParseTree tree, ParseTreePattern pattern)\n        {\n            MultiMap<string, IParseTree> labels = new MultiMap<string, IParseTree>();\n            IParseTree mismatchedNode = MatchImpl(tree, pattern.PatternTree, labels);\n            return mismatchedNode == null;\n        }\n\n        /// <summary>\n        /// Compare\n        /// <paramref name=\"pattern\"/>\n        /// matched as rule\n        /// <paramref name=\"patternRuleIndex\"/>\n        /// against\n        /// <paramref name=\"tree\"/>\n        /// and return a\n        /// <see cref=\"ParseTreeMatch\"/>\n        /// object that contains the\n        /// matched elements, or the node at which the match failed.\n        /// </summary>\n        public virtual ParseTreeMatch Match(IParseTree tree, string pattern, int patternRuleIndex)\n        {\n            ParseTreePattern p = Compile(pattern, patternRuleIndex);\n            return Match(tree, p);\n        }\n\n        /// <summary>\n        /// Compare\n        /// <paramref name=\"pattern\"/>\n        /// matched against\n        /// <paramref name=\"tree\"/>\n        /// and return a\n        /// <see cref=\"ParseTreeMatch\"/>\n        /// object that contains the matched elements, or the\n        /// node at which the match failed. Pass in a compiled pattern instead of a\n        /// string representation of a tree pattern.\n        /// </summary>\n        [return: NotNull]\n        public virtual ParseTreeMatch Match(IParseTree tree, ParseTreePattern pattern)\n        {\n            MultiMap<string, IParseTree> labels = new MultiMap<string, IParseTree>();\n            IParseTree mismatchedNode = MatchImpl(tree, pattern.PatternTree, labels);\n            return new ParseTreeMatch(tree, pattern, labels, mismatchedNode);\n        }\n\n        /// <summary>\n        /// For repeated use of a tree pattern, compile it to a\n        /// <see cref=\"ParseTreePattern\"/>\n        /// using this method.\n        /// </summary>\n        public virtual ParseTreePattern Compile(string pattern, int patternRuleIndex)\n        {\n            IList<IToken> tokenList = Tokenize(pattern);\n            ListTokenSource tokenSrc = new ListTokenSource(tokenList);\n            CommonTokenStream tokens = new CommonTokenStream(tokenSrc);\n            ParserInterpreter parserInterp = new ParserInterpreter(parser.GrammarFileName,\n                                                                   parser.Vocabulary,\n                                                                   Arrays.AsList(parser.RuleNames),\n                                                                   parser.GetATNWithBypassAlts(),\n                                                                   tokens);\n            IParseTree tree = null;\n            try\n            {\n                parserInterp.ErrorHandler = new BailErrorStrategy();\n                tree = parserInterp.Parse(patternRuleIndex);\n            }\n            catch (ParseCanceledException e)\n            {\n                //\t\t\tSystem.out.println(\"pattern tree = \"+tree.toStringTree(parserInterp));\n                throw (RecognitionException)e.InnerException;\n            }\n            catch (RecognitionException)\n            {\n                throw;\n            }\n            catch (Exception e)\n            {\n                throw new ParseTreePatternMatcher.CannotInvokeStartRule(e);\n            }\n            // Make sure tree pattern compilation checks for a complete parse\n            if (tokens.LA(1) != TokenConstants.EOF)\n            {\n                throw new ParseTreePatternMatcher.StartRuleDoesNotConsumeFullPattern();\n            }\n            return new ParseTreePattern(this, pattern, patternRuleIndex, tree);\n        }\n\n        /// <summary>Used to convert the tree pattern string into a series of tokens.</summary>\n        /// <remarks>\n        /// Used to convert the tree pattern string into a series of tokens. The\n        /// input stream is reset.\n        /// </remarks>\n        [NotNull]\n        public virtual Lexer Lexer\n        {\n            get\n            {\n                return lexer;\n            }\n        }\n\n        /// <summary>\n        /// Used to collect to the grammar file name, token names, rule names for\n        /// used to parse the pattern into a parse tree.\n        /// </summary>\n        /// <remarks>\n        /// Used to collect to the grammar file name, token names, rule names for\n        /// used to parse the pattern into a parse tree.\n        /// </remarks>\n        [NotNull]\n        public virtual Parser Parser\n        {\n            get\n            {\n                return parser;\n            }\n        }\n\n        // ---- SUPPORT CODE ----\n        /// <summary>\n        /// Recursively walk\n        /// <paramref name=\"tree\"/>\n        /// against\n        /// <paramref name=\"patternTree\"/>\n        /// , filling\n        /// <c>match.</c>\n        /// <see cref=\"ParseTreeMatch.Labels\"/>\n        /// .\n        /// </summary>\n        /// <returns>\n        /// the first node encountered in\n        /// <paramref name=\"tree\"/>\n        /// which does not match\n        /// a corresponding node in\n        /// <paramref name=\"patternTree\"/>\n        /// , or\n        /// <see langword=\"null\"/>\n        /// if the match\n        /// was successful. The specific node returned depends on the matching\n        /// algorithm used by the implementation, and may be overridden.\n        /// </returns>\n        [return: Nullable]\n        protected internal virtual IParseTree MatchImpl(IParseTree tree, IParseTree patternTree, MultiMap<string, IParseTree> labels)\n        {\n            if (tree == null)\n            {\n                throw new ArgumentException(\"tree cannot be null\");\n            }\n            if (patternTree == null)\n            {\n                throw new ArgumentException(\"patternTree cannot be null\");\n            }\n            // x and <ID>, x and y, or x and x; or could be mismatched types\n            if (tree is ITerminalNode && patternTree is ITerminalNode)\n            {\n                ITerminalNode t1 = (ITerminalNode)tree;\n                ITerminalNode t2 = (ITerminalNode)patternTree;\n                IParseTree mismatchedNode = null;\n                // both are tokens and they have same type\n                if (t1.Symbol.Type == t2.Symbol.Type)\n                {\n                    if (t2.Symbol is TokenTagToken)\n                    {\n                        // x and <ID>\n                        TokenTagToken tokenTagToken = (TokenTagToken)t2.Symbol;\n                        // track label->list-of-nodes for both token name and label (if any)\n\n                        labels.Map(tokenTagToken.TokenName, tree);\n                        if (tokenTagToken.Label != null)\n                        {\n                            labels.Map(tokenTagToken.Label, tree);\n                        }\n                    }\n                    else\n                    {\n                        if (t1.GetText().Equals(t2.GetText(), StringComparison.Ordinal))\n                        {\n                        }\n                        else\n                        {\n                            // x and x\n                            // x and y\n                            if (mismatchedNode == null)\n                            {\n                                mismatchedNode = t1;\n                            }\n                        }\n                    }\n                }\n                else\n                {\n                    if (mismatchedNode == null)\n                    {\n                        mismatchedNode = t1;\n                    }\n                }\n                return mismatchedNode;\n            }\n            if (tree is ParserRuleContext && patternTree is ParserRuleContext)\n            {\n                ParserRuleContext r1 = (ParserRuleContext)tree;\n                ParserRuleContext r2 = (ParserRuleContext)patternTree;\n                IParseTree mismatchedNode = null;\n                // (expr ...) and <expr>\n                RuleTagToken ruleTagToken = GetRuleTagToken(r2);\n                if (ruleTagToken != null)\n                {\n                    if (r1.RuleIndex == r2.RuleIndex)\n                    {\n                        // track label->list-of-nodes for both rule name and label (if any)\n                        labels.Map(ruleTagToken.RuleName, tree);\n                        if (ruleTagToken.Label != null)\n                        {\n                            labels.Map(ruleTagToken.Label, tree);\n                        }\n                    }\n                    else\n                    {\n                        if (mismatchedNode == null)\n                        {\n                            mismatchedNode = r1;\n                        }\n                    }\n                    return mismatchedNode;\n                }\n                // (expr ...) and (expr ...)\n                if (r1.ChildCount != r2.ChildCount)\n                {\n                    if (mismatchedNode == null)\n                    {\n                        mismatchedNode = r1;\n                    }\n                    return mismatchedNode;\n                }\n                int n = r1.ChildCount;\n                for (int i = 0; i < n; i++)\n                {\n                    IParseTree childMatch = MatchImpl(r1.GetChild(i), patternTree.GetChild(i), labels);\n                    if (childMatch != null)\n                    {\n                        return childMatch;\n                    }\n                }\n                return mismatchedNode;\n            }\n            // if nodes aren't both tokens or both rule nodes, can't match\n            return tree;\n        }\n\n        /// <summary>\n        /// Is\n        /// <paramref name=\"t\"/>\n        ///\n        /// <c>(expr &lt;expr&gt;)</c>\n        /// subtree?\n        /// </summary>\n        protected internal virtual RuleTagToken GetRuleTagToken(IParseTree t)\n        {\n            if (t is IRuleNode)\n            {\n                IRuleNode r = (IRuleNode)t;\n                if (r.ChildCount == 1 && r.GetChild(0) is ITerminalNode)\n                {\n                    ITerminalNode c = (ITerminalNode)r.GetChild(0);\n                    if (c.Symbol is RuleTagToken)\n                    {\n                        //\t\t\t\t\tSystem.out.println(\"rule tag subtree \"+t.toStringTree(parser));\n                        return (RuleTagToken)c.Symbol;\n                    }\n                }\n            }\n            return null;\n        }\n\n        public virtual IList<IToken> Tokenize(string pattern)\n        {\n            // split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)\n            IList<Chunk> chunks = Split(pattern);\n            // create token stream from text and tags\n            IList<IToken> tokens = new List<IToken>();\n            foreach (Chunk chunk in chunks)\n            {\n                if (chunk is TagChunk)\n                {\n                    TagChunk tagChunk = (TagChunk)chunk;\n                    // add special rule token or conjure up new token from name\n                    if (System.Char.IsUpper(tagChunk.Tag[0]))\n                    {\n                        int ttype = parser.GetTokenType(tagChunk.Tag);\n                        if (ttype == TokenConstants.InvalidType)\n                        {\n                            throw new ArgumentException(\"Unknown token \" + tagChunk.Tag + \" in pattern: \" + pattern);\n                        }\n                        TokenTagToken t = new TokenTagToken(tagChunk.Tag, ttype, tagChunk.Label);\n                        tokens.Add(t);\n                    }\n                    else\n                    {\n                        if (System.Char.IsLower(tagChunk.Tag[0]))\n                        {\n                            int ruleIndex = parser.GetRuleIndex(tagChunk.Tag);\n                            if (ruleIndex == -1)\n                            {\n                                throw new ArgumentException(\"Unknown rule \" + tagChunk.Tag + \" in pattern: \" + pattern);\n                            }\n                            int ruleImaginaryTokenType = parser.GetATNWithBypassAlts().ruleToTokenType[ruleIndex];\n                            tokens.Add(new RuleTagToken(tagChunk.Tag, ruleImaginaryTokenType, tagChunk.Label));\n                        }\n                        else\n                        {\n                            throw new ArgumentException(\"invalid tag: \" + tagChunk.Tag + \" in pattern: \" + pattern);\n                        }\n                    }\n                }\n                else\n                {\n                    TextChunk textChunk = (TextChunk)chunk;\n                    AntlrInputStream @in = new AntlrInputStream(textChunk.Text);\n                    lexer.SetInputStream(@in);\n                    IToken t = lexer.NextToken();\n                    while (t.Type != TokenConstants.EOF)\n                    {\n                        tokens.Add(t);\n                        t = lexer.NextToken();\n                    }\n                }\n            }\n            //\t\tSystem.out.println(\"tokens=\"+tokens);\n            return tokens;\n        }\n\n        /// <summary>\n        /// Split\n        /// <c>&lt;ID&gt; = &lt;e:expr&gt; ;</c>\n        /// into 4 chunks for tokenizing by\n        /// <see cref=\"Tokenize(string)\"/>\n        /// .\n        /// </summary>\n        internal virtual IList<Chunk> Split(string pattern)\n        {\n            int p = 0;\n            int n = pattern.Length;\n            IList<Chunk> chunks = new List<Chunk>();\n            // find all start and stop indexes first, then collect\n            IList<int> starts = new List<int>();\n            IList<int> stops = new List<int>();\n            while (p < n)\n            {\n                if (p == pattern.IndexOf(escape + start, p))\n                {\n                    p += escape.Length + start.Length;\n                }\n                else\n                {\n                    if (p == pattern.IndexOf(escape + stop, p))\n                    {\n                        p += escape.Length + stop.Length;\n                    }\n                    else\n                    {\n                        if (p == pattern.IndexOf(start, p))\n                        {\n                            starts.Add(p);\n                            p += start.Length;\n                        }\n                        else\n                        {\n                            if (p == pattern.IndexOf(stop, p))\n                            {\n                                stops.Add(p);\n                                p += stop.Length;\n                            }\n                            else\n                            {\n                                p++;\n                            }\n                        }\n                    }\n                }\n            }\n            //\t\tSystem.out.println(\"\");\n            //\t\tSystem.out.println(starts);\n            //\t\tSystem.out.println(stops);\n            if (starts.Count > stops.Count)\n            {\n                throw new ArgumentException(\"unterminated tag in pattern: \" + pattern);\n            }\n            if (starts.Count < stops.Count)\n            {\n                throw new ArgumentException(\"missing start tag in pattern: \" + pattern);\n            }\n            int ntags = starts.Count;\n            for (int i = 0; i < ntags; i++)\n            {\n                if (starts[i] >= stops[i])\n                {\n                    throw new ArgumentException(\"tag delimiters out of order in pattern: \" + pattern);\n                }\n            }\n            // collect into chunks now\n            if (ntags == 0)\n            {\n                string text = Sharpen.Runtime.Substring(pattern, 0, n);\n                chunks.Add(new TextChunk(text));\n            }\n            if (ntags > 0 && starts[0] > 0)\n            {\n                // copy text up to first tag into chunks\n                string text = Sharpen.Runtime.Substring(pattern, 0, starts[0]);\n                chunks.Add(new TextChunk(text));\n            }\n            for (int i_1 = 0; i_1 < ntags; i_1++)\n            {\n                // copy inside of <tag>\n                string tag = Sharpen.Runtime.Substring(pattern, starts[i_1] + start.Length, stops[i_1]);\n                string ruleOrToken = tag;\n                string label = null;\n                int colon = tag.IndexOf(':');\n                if (colon >= 0)\n                {\n                    label = Sharpen.Runtime.Substring(tag, 0, colon);\n                    ruleOrToken = Sharpen.Runtime.Substring(tag, colon + 1, tag.Length);\n                }\n                chunks.Add(new TagChunk(label, ruleOrToken));\n                if (i_1 + 1 < ntags)\n                {\n                    // copy from end of <tag> to start of next\n                    string text = Sharpen.Runtime.Substring(pattern, stops[i_1] + stop.Length, starts[i_1 + 1]);\n                    chunks.Add(new TextChunk(text));\n                }\n            }\n            if (ntags > 0)\n            {\n                int afterLastTag = stops[ntags - 1] + stop.Length;\n                if (afterLastTag < n)\n                {\n                    // copy text from end of last tag to end\n                    string text = Sharpen.Runtime.Substring(pattern, afterLastTag, n);\n                    chunks.Add(new TextChunk(text));\n                }\n            }\n            // strip out the escape sequences from text chunks but not tags\n            for (int i_2 = 0; i_2 < chunks.Count; i_2++)\n            {\n                Chunk c = chunks[i_2];\n                if (c is TextChunk)\n                {\n                    TextChunk tc = (TextChunk)c;\n                    string unescaped = tc.Text.Replace(escape, string.Empty);\n                    if (unescaped.Length < tc.Text.Length)\n                    {\n                        chunks.Set(i_2, new TextChunk(unescaped));\n                    }\n                }\n            }\n            return chunks;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/RuleTagToken.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>\n    /// A\n    /// <see cref=\"Antlr4.Runtime.IToken\"/>\n    /// object representing an entire subtree matched by a parser\n    /// rule; e.g.,\n    /// <c>&lt;expr&gt;</c>\n    /// . These tokens are created for\n    /// <see cref=\"TagChunk\"/>\n    /// chunks where the tag corresponds to a parser rule.\n    /// </summary>\n    public class RuleTagToken : IToken\n    {\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"RuleName()\"/>\n        /// .\n        /// </summary>\n        private readonly string ruleName;\n\n        /// <summary>The token type for the current token.</summary>\n        /// <remarks>\n        /// The token type for the current token. This is the token type assigned to\n        /// the bypass alternative for the rule during ATN deserialization.\n        /// </remarks>\n        private readonly int bypassTokenType;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Label()\"/>\n        /// .\n        /// </summary>\n        private readonly string label;\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"RuleTagToken\"/>\n        /// with the specified rule\n        /// name and bypass token type and no label.\n        /// </summary>\n        /// <param name=\"ruleName\">The name of the parser rule this rule tag matches.</param>\n        /// <param name=\"bypassTokenType\">The bypass token type assigned to the parser rule.</param>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"ruleName\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// or empty.\n        /// </exception>\n        public RuleTagToken(string ruleName, int bypassTokenType)\n            : this(ruleName, bypassTokenType, null)\n        {\n        }\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"RuleTagToken\"/>\n        /// with the specified rule\n        /// name, bypass token type, and label.\n        /// </summary>\n        /// <param name=\"ruleName\">The name of the parser rule this rule tag matches.</param>\n        /// <param name=\"bypassTokenType\">The bypass token type assigned to the parser rule.</param>\n        /// <param name=\"label\">\n        /// The label associated with the rule tag, or\n        /// <see langword=\"null\"/>\n        /// if\n        /// the rule tag is unlabeled.\n        /// </param>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"ruleName\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// or empty.\n        /// </exception>\n        public RuleTagToken(string ruleName, int bypassTokenType, string label)\n        {\n            if (string.IsNullOrEmpty(ruleName))\n            {\n                throw new ArgumentException(\"ruleName cannot be null or empty.\");\n            }\n            this.ruleName = ruleName;\n            this.bypassTokenType = bypassTokenType;\n            this.label = label;\n        }\n\n        /// <summary>Gets the name of the rule associated with this rule tag.</summary>\n        /// <remarks>Gets the name of the rule associated with this rule tag.</remarks>\n        /// <returns>The name of the parser rule associated with this rule tag.</returns>\n        [NotNull]\n        public string RuleName\n        {\n            get\n            {\n                return ruleName;\n            }\n        }\n\n        /// <summary>Gets the label associated with the rule tag.</summary>\n        /// <remarks>Gets the label associated with the rule tag.</remarks>\n        /// <returns>\n        /// The name of the label associated with the rule tag, or\n        /// <see langword=\"null\"/>\n        /// if this is an unlabeled rule tag.\n        /// </returns>\n        [Nullable]\n        public string Label\n        {\n            get\n            {\n                return label;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>Rule tag tokens are always placed on the\n        /// <see cref=\"TokenConstants.DefaultChannel\"/>\n        /// .</p>\n        /// </summary>\n        public virtual int Channel\n        {\n            get\n            {\n                return TokenConstants.DefaultChannel;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>This method returns the rule tag formatted with\n        /// <c>&lt;</c>\n        /// and\n        /// <c>&gt;</c>\n        /// delimiters.</p>\n        /// </summary>\n        public virtual string Text\n        {\n            get\n            {\n                if (label != null)\n                {\n                    return \"<\" + label + \":\" + ruleName + \">\";\n                }\n                return \"<\" + ruleName + \">\";\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>Rule tag tokens have types assigned according to the rule bypass\n        /// transitions created during ATN deserialization.</p>\n        /// </summary>\n        public virtual int Type\n        {\n            get\n            {\n                return bypassTokenType;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// always returns 0.</p>\n        /// </summary>\n        public virtual int Line\n        {\n            get\n            {\n                return 0;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// always returns -1.</p>\n        /// </summary>\n        public virtual int Column\n        {\n            get\n            {\n                return -1;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// always returns -1.</p>\n        /// </summary>\n        public virtual int TokenIndex\n        {\n            get\n            {\n                return -1;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// always returns -1.</p>\n        /// </summary>\n        public virtual int StartIndex\n        {\n            get\n            {\n                return -1;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// always returns -1.</p>\n        /// </summary>\n        public virtual int StopIndex\n        {\n            get\n            {\n                return -1;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// always returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// </summary>\n        public virtual ITokenSource TokenSource\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// always returns\n        /// <see langword=\"null\"/>\n        /// .</p>\n        /// </summary>\n        public virtual ICharStream InputStream\n        {\n            get\n            {\n                return null;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"RuleTagToken\"/>\n        /// returns a string of the form\n        /// <c>ruleName:bypassTokenType</c>\n        /// .</p>\n        /// </summary>\n        public override string ToString()\n        {\n            return ruleName + \":\" + bypassTokenType;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/TagChunk.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree.Pattern;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>Represents a placeholder tag in a tree pattern.</summary>\n    /// <remarks>\n    /// Represents a placeholder tag in a tree pattern. A tag can have any of the\n    /// following forms.\n    /// <ul>\n    /// <li>\n    /// <c>expr</c>\n    /// : An unlabeled placeholder for a parser rule\n    /// <c>expr</c>\n    /// .</li>\n    /// <li>\n    /// <c>ID</c>\n    /// : An unlabeled placeholder for a token of type\n    /// <c>ID</c>\n    /// .</li>\n    /// <li>\n    /// <c>e:expr</c>\n    /// : A labeled placeholder for a parser rule\n    /// <c>expr</c>\n    /// .</li>\n    /// <li>\n    /// <c>id:ID</c>\n    /// : A labeled placeholder for a token of type\n    /// <c>ID</c>\n    /// .</li>\n    /// </ul>\n    /// This class does not perform any validation on the tag or label names aside\n    /// from ensuring that the tag is a non-null, non-empty string.\n    /// </remarks>\n    internal class TagChunk : Chunk\n    {\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Tag()\"/>\n        /// .\n        /// </summary>\n        private readonly string tag;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Label()\"/>\n        /// .\n        /// </summary>\n        private readonly string label;\n\n        /// <summary>\n        /// Construct a new instance of\n        /// <see cref=\"TagChunk\"/>\n        /// using the specified tag and\n        /// no label.\n        /// </summary>\n        /// <param name=\"tag\">\n        /// The tag, which should be the name of a parser rule or token\n        /// type.\n        /// </param>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"tag\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// or\n        /// empty.\n        /// </exception>\n        public TagChunk(string tag)\n            : this(null, tag)\n        {\n        }\n\n        /// <summary>\n        /// Construct a new instance of\n        /// <see cref=\"TagChunk\"/>\n        /// using the specified label\n        /// and tag.\n        /// </summary>\n        /// <param name=\"label\">\n        /// The label for the tag. If this is\n        /// <see langword=\"null\"/>\n        /// , the\n        /// <see cref=\"TagChunk\"/>\n        /// represents an unlabeled tag.\n        /// </param>\n        /// <param name=\"tag\">\n        /// The tag, which should be the name of a parser rule or token\n        /// type.\n        /// </param>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"tag\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// or\n        /// empty.\n        /// </exception>\n        public TagChunk(string label, string tag)\n        {\n            if (string.IsNullOrEmpty(tag))\n            {\n                throw new ArgumentException(\"tag cannot be null or empty\");\n            }\n            this.label = label;\n            this.tag = tag;\n        }\n\n        /// <summary>Get the tag for this chunk.</summary>\n        /// <remarks>Get the tag for this chunk.</remarks>\n        /// <returns>The tag for the chunk.</returns>\n        [NotNull]\n        public string Tag\n        {\n            get\n            {\n                return tag;\n            }\n        }\n\n        /// <summary>Get the label, if any, assigned to this chunk.</summary>\n        /// <remarks>Get the label, if any, assigned to this chunk.</remarks>\n        /// <returns>\n        /// The label assigned to this chunk, or\n        /// <see langword=\"null\"/>\n        /// if no label is\n        /// assigned to the chunk.\n        /// </returns>\n        [Nullable]\n        public string Label\n        {\n            get\n            {\n                return label;\n            }\n        }\n\n        /// <summary>This method returns a text representation of the tag chunk.</summary>\n        /// <remarks>\n        /// This method returns a text representation of the tag chunk. Labeled tags\n        /// are returned in the form\n        /// <c>label:tag</c>\n        /// , and unlabeled tags are\n        /// returned as just the tag name.\n        /// </remarks>\n        public override string ToString()\n        {\n            if (label != null)\n            {\n                return label + \":\" + tag;\n            }\n            return tag;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/TextChunk.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree.Pattern;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>\n    /// Represents a span of raw text (concrete syntax) between tags in a tree\n    /// pattern string.\n    /// </summary>\n    /// <remarks>\n    /// Represents a span of raw text (concrete syntax) between tags in a tree\n    /// pattern string.\n    /// </remarks>\n    internal class TextChunk : Chunk\n    {\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Text()\"/>\n        /// .\n        /// </summary>\n        [NotNull]\n        private readonly string text;\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"TextChunk\"/>\n        /// with the specified text.\n        /// </summary>\n        /// <param name=\"text\">The text of this chunk.</param>\n        /// <exception>\n        /// IllegalArgumentException\n        /// if\n        /// <paramref name=\"text\"/>\n        /// is\n        /// <see langword=\"null\"/>\n        /// .\n        /// </exception>\n        public TextChunk(string text)\n        {\n            if (text == null)\n            {\n                throw new ArgumentException(\"text cannot be null\");\n            }\n            this.text = text;\n        }\n\n        /// <summary>Gets the raw text of this chunk.</summary>\n        /// <remarks>Gets the raw text of this chunk.</remarks>\n        /// <returns>The text of the chunk.</returns>\n        [NotNull]\n        public string Text\n        {\n            get\n            {\n                return text;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"TextChunk\"/>\n        /// returns the result of\n        /// <see cref=\"Text()\"/>\n        /// in single quotes.</p>\n        /// </summary>\n        public override string ToString()\n        {\n            return \"'\" + text + \"'\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Pattern/TokenTagToken.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Tree.Pattern\n{\n    /// <summary>\n    /// A\n    /// <see cref=\"Antlr4.Runtime.IToken\"/>\n    /// object representing a token of a particular type; e.g.,\n    /// <c>&lt;ID&gt;</c>\n    /// . These tokens are created for\n    /// <see cref=\"TagChunk\"/>\n    /// chunks where the\n    /// tag corresponds to a lexer rule or token type.\n    /// </summary>\n    [System.Serializable]\n    public class TokenTagToken : CommonToken\n    {\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"TokenName()\"/>\n        /// .\n        /// </summary>\n        [NotNull]\n        private readonly string tokenName;\n\n        /// <summary>\n        /// This is the backing field for\n        /// <see cref=\"Label()\"/>\n        /// .\n        /// </summary>\n        [Nullable]\n        private readonly string label;\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"TokenTagToken\"/>\n        /// for an unlabeled tag\n        /// with the specified token name and type.\n        /// </summary>\n        /// <param name=\"tokenName\">The token name.</param>\n        /// <param name=\"type\">The token type.</param>\n        public TokenTagToken(string tokenName, int type)\n            : this(tokenName, type, null)\n        {\n        }\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"TokenTagToken\"/>\n        /// with the specified\n        /// token name, type, and label.\n        /// </summary>\n        /// <param name=\"tokenName\">The token name.</param>\n        /// <param name=\"type\">The token type.</param>\n        /// <param name=\"label\">\n        /// The label associated with the token tag, or\n        /// <see langword=\"null\"/>\n        /// if\n        /// the token tag is unlabeled.\n        /// </param>\n        public TokenTagToken(string tokenName, int type, string label)\n            : base(type)\n        {\n            this.tokenName = tokenName;\n            this.label = label;\n        }\n\n        /// <summary>Gets the token name.</summary>\n        /// <remarks>Gets the token name.</remarks>\n        /// <returns>The token name.</returns>\n        [NotNull]\n        public string TokenName\n        {\n            get\n            {\n                return tokenName;\n            }\n        }\n\n        /// <summary>Gets the label associated with the rule tag.</summary>\n        /// <remarks>Gets the label associated with the rule tag.</remarks>\n        /// <returns>\n        /// The name of the label associated with the rule tag, or\n        /// <see langword=\"null\"/>\n        /// if this is an unlabeled rule tag.\n        /// </returns>\n        [Nullable]\n        public string Label\n        {\n            get\n            {\n                return label;\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"TokenTagToken\"/>\n        /// returns the token tag\n        /// formatted with\n        /// <c>&lt;</c>\n        /// and\n        /// <c>&gt;</c>\n        /// delimiters.</p>\n        /// </summary>\n        public override string Text\n        {\n            get\n            {\n                if (label != null)\n                {\n                    return \"<\" + label + \":\" + tokenName + \">\";\n                }\n                return \"<\" + tokenName + \">\";\n            }\n        }\n\n        /// <summary>\n        /// <inheritDoc/>\n        /// <p>The implementation for\n        /// <see cref=\"TokenTagToken\"/>\n        /// returns a string of the form\n        /// <c>tokenName:type</c>\n        /// .</p>\n        /// </summary>\n        public override string ToString()\n        {\n            return tokenName + \":\" + Type;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/TerminalNodeImpl.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime.Misc;\n\nnamespace Antlr4.Runtime.Tree\n{\n    public class TerminalNodeImpl : ITerminalNode\n    {\n        private IToken _symbol;\n\n        private IRuleNode _parent;\n\n        public TerminalNodeImpl(IToken symbol)\n        {\n            this._symbol = symbol;\n        }\n\n        public virtual IParseTree GetChild(int i)\n        {\n            return null;\n        }\n\n        ITree ITree.GetChild(int i)\n        {\n            return GetChild(i);\n        }\n\n        public virtual IToken Symbol\n        {\n            get\n            {\n                return _symbol;\n            }\n        }\n\n        public virtual IRuleNode Parent\n        {\n            get\n            {\n                return _parent;\n            }\n\t\t\tset\n\t\t\t{\n\t\t\t\t_parent = value;\n\t\t\t}\n        }\n\n        IParseTree IParseTree.Parent\n        {\n            get\n            {\n                return Parent;\n            }\n        }\n\n        ITree ITree.Parent\n        {\n            get\n            {\n                return Parent;\n            }\n        }\n\n        public virtual IToken Payload\n        {\n            get\n            {\n                return Symbol;\n            }\n        }\n\n        object ITree.Payload\n        {\n            get\n            {\n                return Payload;\n            }\n        }\n\n        public virtual Interval SourceInterval\n        {\n            get\n            {\n                if (Symbol != null)\n                {\n                    int tokenIndex = Symbol.TokenIndex;\n                    return new Interval(tokenIndex, tokenIndex);\n                }\n                return Interval.Invalid;\n            }\n        }\n\n        public virtual int ChildCount\n        {\n            get\n            {\n                return 0;\n            }\n        }\n\n        public virtual T Accept<T>(IParseTreeVisitor<T> visitor)\n        {\n            return visitor.VisitTerminal(this);\n        }\n\n        public virtual string GetText()\n        {\n            if (Symbol != null)\n            {\n                return Symbol.Text;\n            }\n            return null;\n        }\n\n        public virtual string ToStringTree(Parser parser)\n        {\n            return ToString();\n        }\n\n        public override string ToString()\n        {\n            if (Symbol != null)\n            {\n                if (Symbol.Type == TokenConstants.EOF)\n                {\n                    return \"<EOF>\";\n                }\n                return Symbol.Text;\n            }\n            else\n            {\n                return \"<null>\";\n            }\n        }\n\n        public virtual string ToStringTree()\n        {\n            return ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Trees.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing System.Text;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime.Tree\n{\n    /// <summary>A set of utility routines useful for all kinds of ANTLR trees.</summary>\n    /// <remarks>A set of utility routines useful for all kinds of ANTLR trees.</remarks>\n    public class Trees\n    {\n        /// <summary>Print out a whole tree in LISP form.</summary>\n        /// <remarks>\n        /// Print out a whole tree in LISP form.\n        /// <see cref=\"GetNodeText(ITree, Antlr4.Runtime.Parser)\"/>\n        /// is used on the\n        /// node payloads to get the text for the nodes.  Detect\n        /// parse trees and extract data appropriately.\n        /// </remarks>\n        public static string ToStringTree(ITree t)\n        {\n            return ToStringTree(t, (IList<string>)null);\n        }\n\n        /// <summary>Print out a whole tree in LISP form.</summary>\n        /// <remarks>\n        /// Print out a whole tree in LISP form.\n        /// <see cref=\"GetNodeText(ITree, Antlr4.Runtime.Parser)\"/>\n        /// is used on the\n        /// node payloads to get the text for the nodes.  Detect\n        /// parse trees and extract data appropriately.\n        /// </remarks>\n        public static string ToStringTree(ITree t, Parser recog)\n        {\n            string[] ruleNames = recog != null ? recog.RuleNames : null;\n            IList<string> ruleNamesList = ruleNames != null ? Arrays.AsList(ruleNames) : null;\n            return ToStringTree(t, ruleNamesList);\n        }\n\n        /// <summary>Print out a whole tree in LISP form.</summary>\n        /// <remarks>\n        /// Print out a whole tree in LISP form.\n        /// <see cref=\"GetNodeText(ITree, Antlr4.Runtime.Parser)\"/>\n        /// is used on the\n        /// node payloads to get the text for the nodes.  Detect\n        /// parse trees and extract data appropriately.\n        /// </remarks>\n        public static string ToStringTree(ITree t, IList<string> ruleNames)\n        {\n            string s = Utils.EscapeWhitespace(GetNodeText(t, ruleNames), false);\n            if (t.ChildCount == 0)\n            {\n                return s;\n            }\n            StringBuilder buf = new StringBuilder();\n            buf.Append(\"(\");\n            s = Utils.EscapeWhitespace(GetNodeText(t, ruleNames), false);\n            buf.Append(s);\n            buf.Append(' ');\n            for (int i = 0; i < t.ChildCount; i++)\n            {\n                if (i > 0)\n                {\n                    buf.Append(' ');\n                }\n                buf.Append(ToStringTree(t.GetChild(i), ruleNames));\n            }\n            buf.Append(\")\");\n            return buf.ToString();\n        }\n\n        public static string GetNodeText(ITree t, Parser recog)\n        {\n            string[] ruleNames = recog != null ? recog.RuleNames : null;\n            IList<string> ruleNamesList = ruleNames != null ? Arrays.AsList(ruleNames) : null;\n            return GetNodeText(t, ruleNamesList);\n        }\n\n        public static string GetNodeText(ITree t, IList<string> ruleNames)\n        {\n            if (ruleNames != null)\n            {\n                if (t is RuleContext)\n                {\n                    int ruleIndex = ((RuleContext)t).RuleIndex;\n                    string ruleName = ruleNames[ruleIndex];\n\t\t\t\t\tint altNumber = ((RuleContext)t).getAltNumber();\n\t\t\t\t\tif ( altNumber!=Atn.ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\t\t\treturn ruleName+\":\"+altNumber;\n\t\t\t\t\t}\n                    return ruleName;\n                }\n                else\n                {\n                    if (t is IErrorNode)\n                    {\n                        return t.ToString();\n                    }\n                    else\n                    {\n                        if (t is ITerminalNode)\n                        {\n                            IToken symbol = ((ITerminalNode)t).Symbol;\n                            if (symbol != null)\n                            {\n                                string s = symbol.Text;\n                                return s;\n                            }\n                        }\n                    }\n                }\n            }\n            // no recog for rule names\n            object payload = t.Payload;\n            if (payload is IToken)\n            {\n                return ((IToken)payload).Text;\n            }\n            return t.Payload.ToString();\n        }\n\n        /// <summary>Return ordered list of all children of this node</summary>\n        public static IList<ITree> GetChildren(ITree t)\n        {\n            IList<ITree> kids = new List<ITree>();\n            for (int i = 0; i < t.ChildCount; i++)\n            {\n                kids.Add(t.GetChild(i));\n            }\n            return kids;\n        }\n\n        /// <summary>Return a list of all ancestors of this node.</summary>\n        /// <remarks>\n        /// Return a list of all ancestors of this node.  The first node of\n        /// list is the root and the last is the parent of this node.\n        /// </remarks>\n        [return: NotNull]\n        public static IList<ITree> GetAncestors(ITree t)\n        {\n            if (t.Parent == null)\n            {\n                return Collections.EmptyList<ITree>();\n            }\n            IList<ITree> ancestors = new List<ITree>();\n            t = t.Parent;\n            while (t != null)\n            {\n                ancestors.Insert(0, t);\n                // insert at start\n                t = t.Parent;\n            }\n            return ancestors;\n        }\n\n        public static ICollection<IParseTree> FindAllTokenNodes(IParseTree t, int ttype)\n        {\n            return FindAllNodes(t, ttype, true);\n        }\n\n        public static ICollection<IParseTree> FindAllRuleNodes(IParseTree t, int ruleIndex)\n        {\n            return FindAllNodes(t, ruleIndex, false);\n        }\n\n        public static IList<IParseTree> FindAllNodes(IParseTree t, int index, bool findTokens)\n        {\n            IList<IParseTree> nodes = new List<IParseTree>();\n            _findAllNodes(t, index, findTokens, nodes);\n            return nodes;\n        }\n\n        private static void _findAllNodes(IParseTree t, int index, bool findTokens, IList<IParseTree> nodes)\n        {\n            // check this node (the root) first\n            if (findTokens && t is ITerminalNode)\n            {\n                ITerminalNode tnode = (ITerminalNode)t;\n                if (tnode.Symbol.Type == index)\n                {\n                    nodes.Add(t);\n                }\n            }\n            else\n            {\n                if (!findTokens && t is ParserRuleContext)\n                {\n                    ParserRuleContext ctx = (ParserRuleContext)t;\n                    if (ctx.RuleIndex == index)\n                    {\n                        nodes.Add(t);\n                    }\n                }\n            }\n            // check children\n            for (int i = 0; i < t.ChildCount; i++)\n            {\n                _findAllNodes(t.GetChild(i), index, findTokens, nodes);\n            }\n        }\n\n        public static IList<IParseTree> Descendants(IParseTree t)\n        {\n            List<IParseTree> nodes = new List<IParseTree>();\n            nodes.Add(t);\n            int n = t.ChildCount;\n            for (int i = 0; i < n; i++)\n            {\n                nodes.AddRange(Descendants(t.GetChild(i)));\n            }\n            return nodes;\n        }\n\n        private Trees()\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPath.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    /// <summary>\n    /// Represent a subset of XPath XML path syntax for use in identifying nodes in\n    /// parse trees.\n    /// </summary>\n    /// <remarks>\n    /// Represent a subset of XPath XML path syntax for use in identifying nodes in\n    /// parse trees.\n    /// <p>\n    /// Split path into words and separators\n    /// <c>/</c>\n    /// and\n    /// <c>//</c>\n    /// via ANTLR\n    /// itself then walk path elements from left to right. At each separator-word\n    /// pair, find set of nodes. Next stage uses those as work list.</p>\n    /// <p>\n    /// The basic interface is\n    /// <see cref=\"FindAll(Antlr4.Runtime.Tree.IParseTree, string, Antlr4.Runtime.Parser)\">ParseTree.findAll</see>\n    /// <c>(tree, pathString, parser)</c>\n    /// .\n    /// But that is just shorthand for:</p>\n    /// <pre>\n    /// <see cref=\"XPath\"/>\n    /// p = new\n    /// <see cref=\"XPath(Antlr4.Runtime.Parser, string)\">XPath</see>\n    /// (parser, pathString);\n    /// return p.\n    /// <see cref=\"Evaluate(Antlr4.Runtime.Tree.IParseTree)\">evaluate</see>\n    /// (tree);\n    /// </pre>\n    /// <p>\n    /// See\n    /// <c>org.antlr.v4.test.TestXPath</c>\n    /// for descriptions. In short, this\n    /// allows operators:</p>\n    /// <dl>\n    /// <dt>/</dt> <dd>root</dd>\n    /// <dt>//</dt> <dd>anywhere</dd>\n    /// <dt>!</dt> <dd>invert; this must appear directly after root or anywhere\n    /// operator</dd>\n    /// </dl>\n    /// <p>\n    /// and path elements:</p>\n    /// <dl>\n    /// <dt>ID</dt> <dd>token name</dd>\n    /// <dt>'string'</dt> <dd>any string literal token from the grammar</dd>\n    /// <dt>expr</dt> <dd>rule name</dd>\n    /// <dt>*</dt> <dd>wildcard matching any node</dd>\n    /// </dl>\n    /// <p>\n    /// Whitespace is not allowed.</p>\n    /// </remarks>\n    public class XPath\n    {\n        public const string Wildcard = \"*\";\n\n        public const string Not = \"!\";\n\n        protected internal string path;\n\n        protected internal XPathElement[] elements;\n\n        protected internal Parser parser;\n\n        public XPath(Parser parser, string path)\n        {\n            // word not operator/separator\n            // word for invert operator\n            this.parser = parser;\n            this.path = path;\n            elements = Split(path);\n        }\n\n        //\t\tSystem.out.println(Arrays.toString(elements));\n        // TODO: check for invalid token/rule names, bad syntax\n        public virtual XPathElement[] Split(string path)\n        {\n            AntlrInputStream @in;\n            try\n            {\n                @in = new AntlrInputStream(new StringReader(path));\n            }\n            catch (IOException ioe)\n            {\n                throw new ArgumentException(\"Could not read path: \" + path, ioe);\n            }\n            XPathLexer lexer = new _XPathLexer_87(@in);\n            lexer.RemoveErrorListeners();\n            lexer.AddErrorListener(new XPathLexerErrorListener());\n            CommonTokenStream tokenStream = new CommonTokenStream(lexer);\n            try\n            {\n                tokenStream.Fill();\n            }\n            catch (LexerNoViableAltException e)\n            {\n                int pos = lexer.Column;\n                string msg = \"Invalid tokens or characters at index \" + pos + \" in path '\" + path + \"'\";\n                throw new ArgumentException(msg, e);\n            }\n            IList<IToken> tokens = tokenStream.GetTokens();\n            //\t\tSystem.out.println(\"path=\"+path+\"=>\"+tokens);\n            IList<XPathElement> elements = new List<XPathElement>();\n            int n = tokens.Count;\n            int i = 0;\n            while (i < n)\n            {\n                IToken el = tokens[i];\n                IToken next = null;\n                switch (el.Type)\n                {\n                    case XPathLexer.Root:\n                    case XPathLexer.Anywhere:\n                    {\n                        bool anywhere = el.Type == XPathLexer.Anywhere;\n                        i++;\n                        next = tokens[i];\n                        bool invert = next.Type == XPathLexer.Bang;\n                        if (invert)\n                        {\n                            i++;\n                            next = tokens[i];\n                        }\n                        XPathElement pathElement = GetXPathElement(next, anywhere);\n                        pathElement.invert = invert;\n                        elements.Add(pathElement);\n                        i++;\n                        break;\n                    }\n\n                    case XPathLexer.TokenRef:\n                    case XPathLexer.RuleRef:\n                    case XPathLexer.Wildcard:\n                    {\n                        elements.Add(GetXPathElement(el, false));\n                        i++;\n                        break;\n                    }\n\n                    case TokenConstants.EOF:\n                    {\n                        goto loop_break;\n                    }\n\n                    default:\n                    {\n                        throw new ArgumentException(\"Unknowth path element \" + el);\n                    }\n                }\n            }\nloop_break: ;\n            return elements.ToArray();\n        }\n\n        private sealed class _XPathLexer_87 : XPathLexer\n        {\n            public _XPathLexer_87(ICharStream baseArg1)\n                : base(baseArg1)\n            {\n            }\n\n            public override void Recover(LexerNoViableAltException e)\n            {\n                throw e;\n            }\n        }\n\n        /// <summary>\n        /// Convert word like\n        /// <c>*</c>\n        /// or\n        /// <c>ID</c>\n        /// or\n        /// <c>expr</c>\n        /// to a path\n        /// element.\n        /// <paramref name=\"anywhere\"/>\n        /// is\n        /// <see langword=\"true\"/>\n        /// if\n        /// <c>//</c>\n        /// precedes the\n        /// word.\n        /// </summary>\n        protected internal virtual XPathElement GetXPathElement(IToken wordToken, bool anywhere)\n        {\n            if (wordToken.Type == TokenConstants.EOF)\n            {\n                throw new ArgumentException(\"Missing path element at end of path\");\n            }\n            string word = wordToken.Text;\n            int ttype = parser.GetTokenType(word);\n            int ruleIndex = parser.GetRuleIndex(word);\n            switch (wordToken.Type)\n            {\n                case XPathLexer.Wildcard:\n                {\n                    return anywhere ? new XPathWildcardAnywhereElement() : (XPathElement)new XPathWildcardElement();\n                }\n\n                case XPathLexer.TokenRef:\n                case XPathLexer.String:\n                {\n                    if (ttype == TokenConstants.InvalidType)\n                    {\n                        throw new ArgumentException(word + \" at index \" + wordToken.StartIndex + \" isn't a valid token name\");\n                    }\n                    return anywhere ? new XPathTokenAnywhereElement(word, ttype) : (XPathElement)new XPathTokenElement(word, ttype);\n                }\n\n                default:\n                {\n                    if (ruleIndex == -1)\n                    {\n                        throw new ArgumentException(word + \" at index \" + wordToken.StartIndex + \" isn't a valid rule name\");\n                    }\n                    return anywhere ? new XPathRuleAnywhereElement(word, ruleIndex) : (XPathElement)new XPathRuleElement(word, ruleIndex);\n                }\n            }\n        }\n\n        public static ICollection<IParseTree> FindAll(IParseTree tree, string xpath, Parser parser)\n        {\n            Antlr4.Runtime.Tree.Xpath.XPath p = new Antlr4.Runtime.Tree.Xpath.XPath(parser, xpath);\n            return p.Evaluate(tree);\n        }\n\n        /// <summary>\n        /// Return a list of all nodes starting at\n        /// <paramref name=\"t\"/>\n        /// as root that satisfy the\n        /// path. The root\n        /// <c>/</c>\n        /// is relative to the node passed to\n        /// <see cref=\"Evaluate(Antlr4.Runtime.Tree.IParseTree)\"/>\n        /// .\n        /// </summary>\n        public virtual ICollection<IParseTree> Evaluate(IParseTree t)\n        {\n            ParserRuleContext dummyRoot = new ParserRuleContext();\n            dummyRoot.children = Antlr4.Runtime.Sharpen.Collections.SingletonList(t);\n            // don't set t's parent.\n            ICollection<IParseTree> work = new[] { dummyRoot };\n            int i = 0;\n            while (i < elements.Length)\n            {\n                HashSet<IParseTree> visited = new HashSet<IParseTree>();\n                ICollection<IParseTree> next = new List<IParseTree>();\n                foreach (IParseTree node in work)\n                {\n                    if (node.ChildCount > 0)\n                    {\n                        // only try to match next element if it has children\n                        // e.g., //func/*/stat might have a token node for which\n                        // we can't go looking for stat nodes.\n                        ICollection<IParseTree> matching = elements[i].Evaluate(node);\n                        foreach (IParseTree parseTree in matching)\n                        {\n                            if (visited.Add(parseTree))\n                                next.Add(parseTree);\n                        }\n                    }\n                }\n                i++;\n                work = next;\n            }\n            return work;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathElement.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    public abstract class XPathElement\n    {\n        protected internal string nodeName;\n\n        protected internal bool invert;\n\n        /// <summary>\n        /// Construct element like\n        /// <c>/ID</c>\n        /// or\n        /// <c>ID</c>\n        /// or\n        /// <c>/*</c>\n        /// etc...\n        /// op is null if just node\n        /// </summary>\n        public XPathElement(string nodeName)\n        {\n            this.nodeName = nodeName;\n        }\n\n        /// <summary>\n        /// Given tree rooted at\n        /// <paramref name=\"t\"/>\n        /// return all nodes matched by this path\n        /// element.\n        /// </summary>\n        public abstract ICollection<IParseTree> Evaluate(IParseTree t);\n\n        public override string ToString()\n        {\n            string inv = invert ? \"!\" : string.Empty;\n            return GetType().Name + \"[\" + inv + nodeName + \"]\";\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathLexer.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     ANTLR Version: 4.13.1\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\n// Generated from XPathLexer.g4 by ANTLR 4.13.1\n\n// Unreachable code detected\n#pragma warning disable 0162\n// The variable '...' is assigned but its value is never used\n#pragma warning disable 0219\n// Missing XML comment for publicly visible type or member '...'\n#pragma warning disable 1591\n// Ambiguous reference in cref attribute\n#pragma warning disable 419\n\nusing System;\nusing System.IO;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing DFA = Antlr4.Runtime.Dfa.DFA;\n\n[System.CodeDom.Compiler.GeneratedCode(\"ANTLR\", \"4.13.1\")]\n[System.CLSCompliant(false)]\npublic partial class XPathLexer : Lexer {\n\tprotected static DFA[] decisionToDFA;\n\tprotected static PredictionContextCache sharedContextCache = new PredictionContextCache();\n\tpublic const int\n\t\tTokenRef=1, RuleRef=2, Anywhere=3, Root=4, Wildcard=5, Bang=6, ID=7, String=8;\n\tpublic static string[] channelNames = {\n\t\t\"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"\n\t};\n\n\tpublic static string[] modeNames = {\n\t\t\"DEFAULT_MODE\"\n\t};\n\n\tpublic static readonly string[] ruleNames = {\n\t\t\"Anywhere\", \"Root\", \"Wildcard\", \"Bang\", \"ID\", \"NameChar\", \"NameStartChar\", \n\t\t\"String\"\n\t};\n\n\n\tpublic XPathLexer(ICharStream input)\n\t: this(input, Console.Out, Console.Error) { }\n\n\tpublic XPathLexer(ICharStream input, TextWriter output, TextWriter errorOutput)\n\t: base(input, output, errorOutput)\n\t{\n\t\tInterpreter = new LexerATNSimulator(this, _ATN, decisionToDFA, sharedContextCache);\n\t}\n\n\tprivate static readonly string[] _LiteralNames = {\n\t\tnull, null, null, \"'//'\", \"'/'\", \"'*'\", \"'!'\"\n\t};\n\tprivate static readonly string[] _SymbolicNames = {\n\t\tnull, \"TokenRef\", \"RuleRef\", \"Anywhere\", \"Root\", \"Wildcard\", \"Bang\", \"ID\", \n\t\t\"String\"\n\t};\n\tpublic static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames);\n\n\t[NotNull]\n\tpublic override IVocabulary Vocabulary\n\t{\n\t\tget\n\t\t{\n\t\t\treturn DefaultVocabulary;\n\t\t}\n\t}\n\n\tpublic override string GrammarFileName { get { return \"XPathLexer.g4\"; } }\n\n\tpublic override string[] RuleNames { get { return ruleNames; } }\n\n\tpublic override string[] ChannelNames { get { return channelNames; } }\n\n\tpublic override string[] ModeNames { get { return modeNames; } }\n\n\tpublic override int[] SerializedAtn { get { return _serializedATN; } }\n\n\tstatic XPathLexer() {\n\t\tdecisionToDFA = new DFA[_ATN.NumberOfDecisions];\n\t\tfor (int i = 0; i < _ATN.NumberOfDecisions; i++) {\n\t\t\tdecisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i);\n\t\t}\n\t}\n\tpublic override void Action(RuleContext _localctx, int ruleIndex, int actionIndex) {\n\t\tswitch (ruleIndex) {\n\t\tcase 4 : ID_action(_localctx, actionIndex); break;\n\t\t}\n\t}\n\tprivate void ID_action(RuleContext _localctx, int actionIndex) {\n\t\tswitch (actionIndex) {\n\t\tcase 0: \n\t\t\t\t\t\tString text = Text;\n\t\t\t\t\t\tif ( Char.IsUpper(text[0]) ) \n\t\t\t\t\t\t\tType = TokenRef;\n\t\t\t\t\t\telse \n\t\t\t\t\t\t\tType = RuleRef;\n\t\t\t\t\t\t break;\n\t\t}\n\t}\n\n\tprivate static int[] _serializedATN = {\n\t\t4,0,8,50,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,\n\t\t2,7,7,7,1,0,1,0,1,0,1,1,1,1,1,2,1,2,1,3,1,3,1,4,1,4,5,4,29,8,4,10,4,12,\n\t\t4,32,9,4,1,4,1,4,1,5,1,5,3,5,38,8,5,1,6,1,6,1,7,1,7,5,7,44,8,7,10,7,12,\n\t\t7,47,9,7,1,7,1,7,1,45,0,8,1,3,3,4,5,5,7,6,9,7,11,0,13,0,15,8,1,0,2,5,0,\n\t\t48,57,95,95,183,183,768,879,8255,8256,13,0,65,90,97,122,192,214,216,246,\n\t\t248,767,880,893,895,8191,8204,8205,8304,8591,11264,12271,12289,55295,63744,\n\t\t64975,65008,65533,50,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,\n\t\t9,1,0,0,0,0,15,1,0,0,0,1,17,1,0,0,0,3,20,1,0,0,0,5,22,1,0,0,0,7,24,1,0,\n\t\t0,0,9,26,1,0,0,0,11,37,1,0,0,0,13,39,1,0,0,0,15,41,1,0,0,0,17,18,5,47,\n\t\t0,0,18,19,5,47,0,0,19,2,1,0,0,0,20,21,5,47,0,0,21,4,1,0,0,0,22,23,5,42,\n\t\t0,0,23,6,1,0,0,0,24,25,5,33,0,0,25,8,1,0,0,0,26,30,3,13,6,0,27,29,3,11,\n\t\t5,0,28,27,1,0,0,0,29,32,1,0,0,0,30,28,1,0,0,0,30,31,1,0,0,0,31,33,1,0,\n\t\t0,0,32,30,1,0,0,0,33,34,6,4,0,0,34,10,1,0,0,0,35,38,3,13,6,0,36,38,7,0,\n\t\t0,0,37,35,1,0,0,0,37,36,1,0,0,0,38,12,1,0,0,0,39,40,7,1,0,0,40,14,1,0,\n\t\t0,0,41,45,5,39,0,0,42,44,9,0,0,0,43,42,1,0,0,0,44,47,1,0,0,0,45,46,1,0,\n\t\t0,0,45,43,1,0,0,0,46,48,1,0,0,0,47,45,1,0,0,0,48,49,5,39,0,0,49,16,1,0,\n\t\t0,0,4,0,30,37,45,1,1,4,0\n\t};\n\n\tpublic static readonly ATN _ATN =\n\t\tnew ATNDeserializer().Deserialize(_serializedATN);\n\n\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathLexer.g4",
    "content": "lexer grammar XPathLexer;\n\ntokens { TokenRef, RuleRef }\n\n/*\npath : separator? word (separator word)* EOF ;\n\nseparator\n\t:\t'/'  '!'\n\t|\t'//' '!'\n\t|\t'/'\n\t|\t'//'\n\t;\n\nword:\tTokenRef\n\t|\tRuleRef\n\t|\tString\n\t|\t'*'\n\t;\n*/\n\nAnywhere : '//' ;\nRoot\t : '/' ;\nWildcard : '*' ;\nBang\t : '!' ;\n\nID\t\t\t:\tNameStartChar NameChar*\n\t\t\t\t{\n\t\t\t\tString text = Text;\n\t\t\t\tif ( Char.IsUpper(text[0]) ) \n\t\t\t\t\tType = TokenRef;\n\t\t\t\telse \n\t\t\t\t\tType = RuleRef;\n\t\t\t\t}\n\t\t\t;\n\nfragment\nNameChar    :   NameStartChar\n            |   '0'..'9'\n            |   '_'\n            |   '\\u00B7'\n            |   '\\u0300'..'\\u036F'\n            |   '\\u203F'..'\\u2040'\n            ;\n\nfragment\nNameStartChar\n            :   'A'..'Z' | 'a'..'z'\n            |   '\\u00C0'..'\\u00D6'\n            |   '\\u00D8'..'\\u00F6'\n            |   '\\u00F8'..'\\u02FF'\n            |   '\\u0370'..'\\u037D'\n            |   '\\u037F'..'\\u1FFF'\n            |   '\\u200C'..'\\u200D'\n            |   '\\u2070'..'\\u218F'\n            |   '\\u2C00'..'\\u2FEF'\n            |   '\\u3001'..'\\uD7FF'\n            |   '\\uF900'..'\\uFDCF'\n            |   '\\uFDF0'..'\\uFFFD'\n            ; // ignores | ['\\u10000-'\\uEFFFF] ;\n\nString : '\\'' .*? '\\'' ;\n\n//Ws : [ \\t\\r\\n]+ -> skip ;\n\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathLexer.tokens",
    "content": "TokenRef=1\nRuleRef=2\nAnywhere=3\nRoot=4\nWildcard=5\nBang=6\nID=7\nString=8\n'//'=3\n'/'=4\n'*'=5\n'!'=6\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathLexerErrorListener.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree.Xpath;\nusing System.IO;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    public class XPathLexerErrorListener : IAntlrErrorListener<int>\n    {\n        public virtual void SyntaxError(TextWriter output, IRecognizer recognizer, int offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathRuleAnywhereElement.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    /// <summary>\n    /// Either\n    /// <c>ID</c>\n    /// at start of path or\n    /// <c>...//ID</c>\n    /// in middle of path.\n    /// </summary>\n    public class XPathRuleAnywhereElement : XPathElement\n    {\n        protected internal int ruleIndex;\n\n        public XPathRuleAnywhereElement(string ruleName, int ruleIndex)\n            : base(ruleName)\n        {\n            this.ruleIndex = ruleIndex;\n        }\n\n        public override ICollection<IParseTree> Evaluate(IParseTree t)\n        {\n            return Trees.FindAllRuleNodes(t, ruleIndex);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathRuleElement.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    public class XPathRuleElement : XPathElement\n    {\n        protected internal int ruleIndex;\n\n        public XPathRuleElement(string ruleName, int ruleIndex)\n            : base(ruleName)\n        {\n            this.ruleIndex = ruleIndex;\n        }\n\n        public override ICollection<IParseTree> Evaluate(IParseTree t)\n        {\n            // return all children of t that match nodeName\n            IList<IParseTree> nodes = new List<IParseTree>();\n            foreach (ITree c in Trees.GetChildren(t))\n            {\n                if (c is ParserRuleContext)\n                {\n                    ParserRuleContext ctx = (ParserRuleContext)c;\n                    if ((ctx.RuleIndex == ruleIndex && !invert) || (ctx.RuleIndex != ruleIndex && invert))\n                    {\n                        nodes.Add(ctx);\n                    }\n                }\n            }\n            return nodes;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathTokenAnywhereElement.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    public class XPathTokenAnywhereElement : XPathElement\n    {\n        protected internal int tokenType;\n\n        public XPathTokenAnywhereElement(string tokenName, int tokenType)\n            : base(tokenName)\n        {\n            this.tokenType = tokenType;\n        }\n\n        public override ICollection<IParseTree> Evaluate(IParseTree t)\n        {\n            return Trees.FindAllTokenNodes(t, tokenType);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathTokenElement.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    public class XPathTokenElement : XPathElement\n    {\n        protected internal int tokenType;\n\n        public XPathTokenElement(string tokenName, int tokenType)\n            : base(tokenName)\n        {\n            this.tokenType = tokenType;\n        }\n\n        public override ICollection<IParseTree> Evaluate(IParseTree t)\n        {\n            // return all children of t that match nodeName\n            IList<IParseTree> nodes = new List<IParseTree>();\n            foreach (ITree c in Trees.GetChildren(t))\n            {\n                if (c is ITerminalNode)\n                {\n                    ITerminalNode tnode = (ITerminalNode)c;\n                    if ((tnode.Symbol.Type == tokenType && !invert) || (tnode.Symbol.Type != tokenType && invert))\n                    {\n                        nodes.Add(tnode);\n                    }\n                }\n            }\n            return nodes;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathWildcardAnywhereElement.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    public class XPathWildcardAnywhereElement : XPathElement\n    {\n        public XPathWildcardAnywhereElement()\n            : base(XPath.Wildcard)\n        {\n        }\n\n        public override ICollection<IParseTree> Evaluate(IParseTree t)\n        {\n            if (invert)\n            {\n                return new List<IParseTree>();\n            }\n            // !* is weird but valid (empty)\n            return Trees.Descendants(t);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Tree/Xpath/XPathWildcardElement.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System.Collections.Generic;\nusing Antlr4.Runtime.Sharpen;\nusing Antlr4.Runtime.Tree;\nusing Antlr4.Runtime.Tree.Xpath;\n\nnamespace Antlr4.Runtime.Tree.Xpath\n{\n    public class XPathWildcardElement : XPathElement\n    {\n        public XPathWildcardElement()\n            : base(XPath.Wildcard)\n        {\n        }\n\n        public override ICollection<IParseTree> Evaluate(IParseTree t)\n        {\n            if (invert)\n            {\n                return new List<IParseTree>();\n            }\n            // !* is weird but valid (empty)\n            IList<IParseTree> kids = new List<IParseTree>();\n            foreach (ITree c in Trees.GetChildren(t))\n            {\n                kids.Add((IParseTree)c);\n            }\n            return kids;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/UnbufferedCharStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.IO;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>Do not buffer up the entire char stream.</summary>\n    /// <remarks>\n    /// Do not buffer up the entire char stream. It does keep a small buffer\n    /// for efficiency and also buffers while a mark exists (set by the\n    /// lookahead prediction in parser). \"Unbuffered\" here refers to fact\n    /// that it doesn't buffer all data, not that's it's on demand loading of char.\n    /// </remarks>\n    public class UnbufferedCharStream : ICharStream\n    {\n        /// <summary>A moving window buffer of the data being scanned.</summary>\n        /// <remarks>\n        /// A moving window buffer of the data being scanned. While there's a marker,\n        /// we keep adding to buffer. Otherwise,\n        /// <see cref=\"Consume()\">consume()</see>\n        /// resets so\n        /// we start filling at index 0 again.\n        /// </remarks>\n        protected internal int[] data;\n\n        /// <summary>\n        /// The number of characters currently in\n        /// <see cref=\"data\">data</see>\n        /// .\n        /// <p>This is not the buffer capacity, that's\n        /// <c>data.length</c>\n        /// .</p>\n        /// </summary>\n        protected internal int n;\n\n        /// <summary>\n        /// 0..n-1 index into\n        /// <see cref=\"data\">data</see>\n        /// of next character.\n        /// <p>The\n        /// <c>LA(1)</c>\n        /// character is\n        /// <c>data[p]</c>\n        /// . If\n        /// <c>p == n</c>\n        /// , we are\n        /// out of buffered characters.</p>\n        /// </summary>\n        protected internal int p = 0;\n\n        /// <summary>\n        /// Count up with\n        /// <see cref=\"Mark()\">mark()</see>\n        /// and down with\n        /// <see cref=\"Release(int)\">release()</see>\n        /// . When we\n        /// <c>release()</c>\n        /// the last mark,\n        /// <c>numMarkers</c>\n        /// reaches 0 and we reset the buffer. Copy\n        /// <c>data[p]..data[n-1]</c>\n        /// to\n        /// <c>data[0]..data[(n-1)-p]</c>\n        /// .\n        /// </summary>\n        protected internal int numMarkers = 0;\n\n        /// <summary>\n        /// This is the\n        /// <c>LA(-1)</c>\n        /// character for the current position.\n        /// </summary>\n        protected internal int lastChar = -1;\n\n        /// <summary>\n        /// When\n        /// <c>numMarkers &gt; 0</c>\n        /// , this is the\n        /// <c>LA(-1)</c>\n        /// character for the\n        /// first character in\n        /// <see cref=\"data\">data</see>\n        /// . Otherwise, this is unspecified.\n        /// </summary>\n        protected internal int lastCharBufferStart;\n\n        /// <summary>Absolute character index.</summary>\n        /// <remarks>\n        /// Absolute character index. It's the index of the character about to be\n        /// read via\n        /// <c>LA(1)</c>\n        /// . Goes from 0 to the number of characters in the\n        /// entire stream, although the stream size is unknown before the end is\n        /// reached.\n        /// </remarks>\n        protected internal int currentCharIndex = 0;\n\n        protected internal TextReader input;\n\n        /// <summary>The name or source of this char stream.</summary>\n        /// <remarks>The name or source of this char stream.</remarks>\n        public string name;\n\n        /// <summary>Useful for subclasses that pull char from other than this.input.</summary>\n        /// <remarks>Useful for subclasses that pull char from other than this.input.</remarks>\n        public UnbufferedCharStream()\n            : this(256)\n        {\n        }\n\n        /// <summary>Useful for subclasses that pull char from other than this.input.</summary>\n        /// <remarks>Useful for subclasses that pull char from other than this.input.</remarks>\n        public UnbufferedCharStream(int bufferSize)\n        {\n            n = 0;\n            data = new int[bufferSize];\n        }\n\n        public UnbufferedCharStream(Stream input)\n            : this(input, 256)\n        {\n        }\n\n        public UnbufferedCharStream(TextReader input)\n            : this(input, 256)\n        {\n        }\n\n        public UnbufferedCharStream(Stream input, int bufferSize)\n            : this(bufferSize)\n        {\n            this.input = new StreamReader(input);\n            Fill(1);\n        }\n\n        public UnbufferedCharStream(TextReader input, int bufferSize)\n            : this(bufferSize)\n        {\n            // prime\n            this.input = input;\n            Fill(1);\n        }\n\n        // prime\n        public virtual void Consume()\n        {\n            if (LA(1) == IntStreamConstants.EOF)\n            {\n                throw new InvalidOperationException(\"cannot consume EOF\");\n            }\n            // buf always has at least data[p==0] in this method due to ctor\n            lastChar = data[p];\n            // track last char for LA(-1)\n            if (p == n - 1 && numMarkers == 0)\n            {\n                n = 0;\n                p = -1;\n                // p++ will leave this at 0\n                lastCharBufferStart = lastChar;\n            }\n            p++;\n            currentCharIndex++;\n            Sync(1);\n        }\n\n        /// <summary>\n        /// Make sure we have 'need' elements from current position\n        /// <see cref=\"p\">p</see>\n        /// .\n        /// Last valid\n        /// <c>p</c>\n        /// index is\n        /// <c>data.length-1</c>\n        /// .\n        /// <c>p+need-1</c>\n        /// is\n        /// the char index 'need' elements ahead. If we need 1 element,\n        /// <c>(p+1-1)==p</c>\n        /// must be less than\n        /// <c>data.length</c>\n        /// .\n        /// </summary>\n        protected internal virtual void Sync(int want)\n        {\n            int need = (p + want - 1) - n + 1;\n            // how many more elements we need?\n            if (need > 0)\n            {\n                Fill(need);\n            }\n        }\n\n        /// <summary>\n        /// Add\n        /// <paramref name=\"n\"/>\n        /// characters to the buffer. Returns the number of characters\n        /// actually added to the buffer. If the return value is less than\n        /// <paramref name=\"n\"/>\n        /// ,\n        /// then EOF was reached before\n        /// <paramref name=\"n\"/>\n        /// characters could be added.\n        /// </summary>\n        protected internal virtual int Fill(int n)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                if (this.n > 0 && data[this.n - 1] == IntStreamConstants.EOF)\n                {\n                    return i;\n                }\n\n                int c = NextChar();\n                if (c > char.MaxValue || c == IntStreamConstants.EOF)\n                {\n                    Add(c);\n                }\n                else\n                {\n                    char ch = unchecked((char)c);\n                    if (Char.IsLowSurrogate(ch))\n                    {\n                        throw new ArgumentException(\"Invalid UTF-16 (low surrogate with no preceding high surrogate)\");\n                    }\n                    else if (Char.IsHighSurrogate(ch))\n                    {\n                        int lowSurrogate = NextChar();\n                        if (lowSurrogate > char.MaxValue)\n                        {\n                            throw new ArgumentException(\"Invalid UTF-16 (high surrogate followed by code point > U+FFFF\");\n                        }\n                        else if (lowSurrogate == IntStreamConstants.EOF)\n                        {\n                            throw new ArgumentException(\"Invalid UTF-16 (low surrogate with no preceding high surrogate)\");\n                        }\n                        else\n                        {\n                            char lowSurrogateChar = unchecked((char)lowSurrogate);\n                            if (Char.IsLowSurrogate(lowSurrogateChar))\n                            {\n                                Add(Char.ConvertToUtf32(ch, lowSurrogateChar));\n                            }\n                            else\n                            {\n                                throw new ArgumentException(\"Invalid UTF-16 (low surrogate with no preceding high surrogate)\");\n                            }\n                        }\n                    }\n                    else\n                    {\n                        Add(c);\n                    }\n                }\n            }\n            return n;\n        }\n\n        /// <summary>\n        /// Override to provide different source of characters than\n        /// <see cref=\"input\">input</see>\n        /// .\n        /// </summary>\n        /// <exception cref=\"System.IO.IOException\"/>\n        protected internal virtual int NextChar()\n        {\n            return input.Read();\n        }\n\n        protected internal virtual void Add(int c)\n        {\n            if (n >= data.Length)\n            {\n                data = Arrays.CopyOf(data, data.Length * 2);\n            }\n            data[n++] = c;\n        }\n\n        public virtual int LA(int i)\n        {\n            if (i == -1)\n            {\n                return lastChar;\n            }\n            // special case\n            Sync(i);\n            int index = p + i - 1;\n            if (index < 0)\n            {\n                throw new ArgumentOutOfRangeException();\n            }\n            if (index >= n)\n            {\n                return IntStreamConstants.EOF;\n            }\n            return data[index];\n        }\n\n        /// <summary>Return a marker that we can release later.</summary>\n        /// <remarks>\n        /// Return a marker that we can release later.\n        /// <p>The specific marker value used for this class allows for some level of\n        /// protection against misuse where\n        /// <c>seek()</c>\n        /// is called on a mark or\n        /// <c>release()</c>\n        /// is called in the wrong order.</p>\n        /// </remarks>\n        public virtual int Mark()\n        {\n            if (numMarkers == 0)\n            {\n                lastCharBufferStart = lastChar;\n            }\n            int mark = -numMarkers - 1;\n            numMarkers++;\n            return mark;\n        }\n\n        /// <summary>Decrement number of markers, resetting buffer if we hit 0.</summary>\n        /// <remarks>Decrement number of markers, resetting buffer if we hit 0.</remarks>\n        /// <param name=\"marker\"/>\n        public virtual void Release(int marker)\n        {\n            int expectedMark = -numMarkers;\n            if (marker != expectedMark)\n            {\n                throw new InvalidOperationException(\"release() called with an invalid marker.\");\n            }\n            numMarkers--;\n            if (numMarkers == 0 && p > 0)\n            {\n                // release buffer when we can, but don't do unnecessary work\n                // Copy data[p]..data[n-1] to data[0]..data[(n-1)-p], reset ptrs\n                // p is last valid char; move nothing if p==n as we have no valid char\n                System.Array.Copy(data, p, data, 0, n - p);\n                // shift n-p char from p to 0\n                n = n - p;\n                p = 0;\n                lastCharBufferStart = lastChar;\n            }\n        }\n\n        public virtual int Index\n        {\n            get\n            {\n                return currentCharIndex;\n            }\n        }\n\n        /// <summary>\n        /// Seek to absolute character index, which might not be in the current\n        /// sliding window.\n        /// </summary>\n        /// <remarks>\n        /// Seek to absolute character index, which might not be in the current\n        /// sliding window.  Move\n        /// <c>p</c>\n        /// to\n        /// <c>index-bufferStartIndex</c>\n        /// .\n        /// </remarks>\n        public virtual void Seek(int index)\n        {\n            if (index == currentCharIndex)\n            {\n                return;\n            }\n            if (index > currentCharIndex)\n            {\n                Sync(index - currentCharIndex);\n                index = Math.Min(index, BufferStartIndex + n - 1);\n            }\n            // index == to bufferStartIndex should set p to 0\n            int i = index - BufferStartIndex;\n            if (i < 0)\n            {\n                throw new ArgumentException(\"cannot seek to negative index \" + index);\n            }\n            else\n            {\n                if (i >= n)\n                {\n                    throw new NotSupportedException(\"seek to index outside buffer: \" + index + \" not in \" + BufferStartIndex + \"..\" + (BufferStartIndex + n));\n                }\n            }\n            p = i;\n            currentCharIndex = index;\n            if (p == 0)\n            {\n                lastChar = lastCharBufferStart;\n            }\n            else\n            {\n                lastChar = data[p - 1];\n            }\n        }\n\n        public virtual int Size\n        {\n            get\n            {\n                throw new NotSupportedException(\"Unbuffered stream cannot know its size\");\n            }\n        }\n\n        public virtual string SourceName\n        {\n            get\n            {\n                if (string.IsNullOrEmpty(name))\n                {\n                    return IntStreamConstants.UnknownSourceName;\n                }\n                return name;\n            }\n        }\n\n        public virtual string GetText(Interval interval)\n        {\n            if (interval.a < 0 || interval.b < interval.a - 1)\n            {\n                throw new ArgumentException(\"invalid interval\");\n            }\n            int bufferStartIndex = BufferStartIndex;\n            if (n > 0 && data[n - 1] == IntStreamConstants.EOF)\n            {\n                if (interval.a + interval.Length > bufferStartIndex + n)\n                {\n                    throw new ArgumentException(\"the interval extends past the end of the stream\");\n                }\n            }\n            if (interval.a < bufferStartIndex || interval.b >= bufferStartIndex + n)\n            {\n                throw new NotSupportedException(\"interval \" + interval + \" outside buffer: \" + bufferStartIndex + \"..\" + (bufferStartIndex + n - 1));\n            }\n            // convert from absolute to local index\n            int i = interval.a - bufferStartIndex;\n            // build a UTF-16 string from the Unicode code points in data\n            var sb = new StringBuilder(interval.Length);\n            for (int offset = 0; offset < interval.Length; offset++) {\n                sb.Append(Char.ConvertFromUtf32(data[i + offset]));\n            }\n            return sb.ToString();\n        }\n\n        protected internal int BufferStartIndex\n        {\n            get\n            {\n                return currentCharIndex - p;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/UnbufferedTokenStream.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing System;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    public class UnbufferedTokenStream : ITokenStream\n    {\n        private ITokenSource _tokenSource;\n\n        /// <summary>A moving window buffer of the data being scanned.</summary>\n        /// <remarks>\n        /// A moving window buffer of the data being scanned. While there's a marker,\n        /// we keep adding to buffer. Otherwise,\n        /// <see cref=\"Consume()\">consume()</see>\n        /// resets so\n        /// we start filling at index 0 again.\n        /// </remarks>\n        protected internal IToken[] tokens;\n\n        /// <summary>\n        /// The number of tokens currently in\n        /// <see cref=\"tokens\">tokens</see>\n        /// .\n        /// <p>This is not the buffer capacity, that's\n        /// <c>tokens.length</c>\n        /// .</p>\n        /// </summary>\n        protected internal int n;\n\n        /// <summary>\n        /// 0..n-1 index into\n        /// <see cref=\"tokens\">tokens</see>\n        /// of next token.\n        /// <p>The\n        /// <c>LT(1)</c>\n        /// token is\n        /// <c>tokens[p]</c>\n        /// . If\n        /// <c>p == n</c>\n        /// , we are\n        /// out of buffered tokens.</p>\n        /// </summary>\n        protected internal int p = 0;\n\n        /// <summary>\n        /// Count up with\n        /// <see cref=\"Mark()\">mark()</see>\n        /// and down with\n        /// <see cref=\"Release(int)\">release()</see>\n        /// . When we\n        /// <c>release()</c>\n        /// the last mark,\n        /// <c>numMarkers</c>\n        /// reaches 0 and we reset the buffer. Copy\n        /// <c>tokens[p]..tokens[n-1]</c>\n        /// to\n        /// <c>tokens[0]..tokens[(n-1)-p]</c>\n        /// .\n        /// </summary>\n        protected internal int numMarkers = 0;\n\n        /// <summary>\n        /// This is the\n        /// <c>LT(-1)</c>\n        /// token for the current position.\n        /// </summary>\n        protected internal IToken lastToken;\n\n        /// <summary>\n        /// When\n        /// <c>numMarkers &gt; 0</c>\n        /// , this is the\n        /// <c>LT(-1)</c>\n        /// token for the\n        /// first token in\n        /// <see cref=\"tokens\"/>\n        /// . Otherwise, this is\n        /// <see langword=\"null\"/>\n        /// .\n        /// </summary>\n        protected internal IToken lastTokenBufferStart;\n\n        /// <summary>Absolute token index.</summary>\n        /// <remarks>\n        /// Absolute token index. It's the index of the token about to be read via\n        /// <c>LT(1)</c>\n        /// . Goes from 0 to the number of tokens in the entire stream,\n        /// although the stream size is unknown before the end is reached.\n        /// <p>This value is used to set the token indexes if the stream provides tokens\n        /// that implement\n        /// <see cref=\"IWritableToken\"/>\n        /// .</p>\n        /// </remarks>\n        protected internal int currentTokenIndex = 0;\n\n        public UnbufferedTokenStream(ITokenSource tokenSource)\n            : this(tokenSource, 256)\n        {\n        }\n\n        public UnbufferedTokenStream(ITokenSource tokenSource, int bufferSize)\n        {\n            this.TokenSource = tokenSource;\n            this.tokens = new IToken[bufferSize];\n            n = 0;\n            Fill(1);\n        }\n\n        // prime the pump\n        public virtual IToken Get(int i)\n        {\n            int bufferStartIndex = GetBufferStartIndex();\n            if (i < bufferStartIndex || i >= bufferStartIndex + n)\n            {\n                throw new ArgumentOutOfRangeException(\"get(\" + i + \") outside buffer: \" + bufferStartIndex + \"..\" + (bufferStartIndex + n));\n            }\n            return tokens[i - bufferStartIndex];\n        }\n\n        public virtual IToken LT(int i)\n        {\n            if (i == -1)\n            {\n                return lastToken;\n            }\n            Sync(i);\n            int index = p + i - 1;\n            if (index < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"LT(\" + i + \") gives negative index\");\n            }\n            if (index >= n)\n            {\n                System.Diagnostics.Debug.Assert(n > 0 && tokens[n - 1].Type == TokenConstants.EOF);\n                return tokens[n - 1];\n            }\n            return tokens[index];\n        }\n\n        public virtual int LA(int i)\n        {\n            return LT(i).Type;\n        }\n\n        public virtual ITokenSource TokenSource\n        {\n            get\n            {\n                return _tokenSource;\n            }\n\t\t\tset\n\t\t\t{\n\t\t\t\t_tokenSource = value;\n\t\t\t}\n        }\n\n        [return: NotNull]\n        public virtual string GetText()\n        {\n            return string.Empty;\n        }\n\n        [return: NotNull]\n        public virtual string GetText(RuleContext ctx)\n        {\n            return GetText(ctx.SourceInterval);\n        }\n\n        [return: NotNull]\n        public virtual string GetText(IToken start, IToken stop)\n        {\n            if (start != null && stop != null)\n            {\n                return GetText(Interval.Of(start.TokenIndex, stop.TokenIndex));\n            }\n            throw new NotSupportedException(\"The specified start and stop symbols are not supported.\");\n        }\n\n        public virtual void Consume()\n        {\n            if (LA(1) == TokenConstants.EOF)\n            {\n                throw new InvalidOperationException(\"cannot consume EOF\");\n            }\n            // buf always has at least tokens[p==0] in this method due to ctor\n            lastToken = tokens[p];\n            // track last token for LT(-1)\n            // if we're at last token and no markers, opportunity to flush buffer\n            if (p == n - 1 && numMarkers == 0)\n            {\n                n = 0;\n                p = -1;\n                // p++ will leave this at 0\n                lastTokenBufferStart = lastToken;\n            }\n            p++;\n            currentTokenIndex++;\n            Sync(1);\n        }\n\n        /// <summary>\n        /// Make sure we have 'need' elements from current position\n        /// <see cref=\"p\">p</see>\n        /// . Last valid\n        /// <c>p</c>\n        /// index is\n        /// <c>tokens.length-1</c>\n        /// .\n        /// <c>p+need-1</c>\n        /// is the tokens index 'need' elements\n        /// ahead.  If we need 1 element,\n        /// <c>(p+1-1)==p</c>\n        /// must be less than\n        /// <c>tokens.length</c>\n        /// .\n        /// </summary>\n        protected internal virtual void Sync(int want)\n        {\n            int need = (p + want - 1) - n + 1;\n            // how many more elements we need?\n            if (need > 0)\n            {\n                Fill(need);\n            }\n        }\n\n        /// <summary>\n        /// Add\n        /// <paramref name=\"n\"/>\n        /// elements to the buffer. Returns the number of tokens\n        /// actually added to the buffer. If the return value is less than\n        /// <paramref name=\"n\"/>\n        /// ,\n        /// then EOF was reached before\n        /// <paramref name=\"n\"/>\n        /// tokens could be added.\n        /// </summary>\n        protected internal virtual int Fill(int n)\n        {\n            for (int i = 0; i < n; i++)\n            {\n                if (this.n > 0 && tokens[this.n - 1].Type == TokenConstants.EOF)\n                {\n                    return i;\n                }\n                IToken t = TokenSource.NextToken();\n                Add(t);\n            }\n            return n;\n        }\n\n        protected internal virtual void Add(IToken t)\n        {\n            if (n >= tokens.Length)\n            {\n                tokens = Arrays.CopyOf(tokens, tokens.Length * 2);\n            }\n            if (t is IWritableToken)\n            {\n                ((IWritableToken)t).TokenIndex = GetBufferStartIndex() + n;\n            }\n            tokens[n++] = t;\n        }\n\n        /// <summary>Return a marker that we can release later.</summary>\n        /// <remarks>\n        /// Return a marker that we can release later.\n        /// <p>The specific marker value used for this class allows for some level of\n        /// protection against misuse where\n        /// <c>seek()</c>\n        /// is called on a mark or\n        /// <c>release()</c>\n        /// is called in the wrong order.</p>\n        /// </remarks>\n        public virtual int Mark()\n        {\n            if (numMarkers == 0)\n            {\n                lastTokenBufferStart = lastToken;\n            }\n            int mark = -numMarkers - 1;\n            numMarkers++;\n            return mark;\n        }\n\n        public virtual void Release(int marker)\n        {\n            int expectedMark = -numMarkers;\n            if (marker != expectedMark)\n            {\n                throw new InvalidOperationException(\"release() called with an invalid marker.\");\n            }\n            numMarkers--;\n            if (numMarkers == 0)\n            {\n                // can we release buffer?\n                if (p > 0)\n                {\n                    // Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs\n                    // p is last valid token; move nothing if p==n as we have no valid char\n                    System.Array.Copy(tokens, p, tokens, 0, n - p);\n                    // shift n-p tokens from p to 0\n                    n = n - p;\n                    p = 0;\n                }\n                lastTokenBufferStart = lastToken;\n            }\n        }\n\n        public virtual int Index\n        {\n            get\n            {\n                return currentTokenIndex;\n            }\n        }\n\n        public virtual void Seek(int index)\n        {\n            // seek to absolute index\n            if (index == currentTokenIndex)\n            {\n                return;\n            }\n            if (index > currentTokenIndex)\n            {\n                Sync(index - currentTokenIndex);\n                index = Math.Min(index, GetBufferStartIndex() + n - 1);\n            }\n            int bufferStartIndex = GetBufferStartIndex();\n            int i = index - bufferStartIndex;\n            if (i < 0)\n            {\n                throw new ArgumentException(\"cannot seek to negative index \" + index);\n            }\n            else\n            {\n                if (i >= n)\n                {\n                    throw new NotSupportedException(\"seek to index outside buffer: \" + index + \" not in \" + bufferStartIndex + \"..\" + (bufferStartIndex + n));\n                }\n            }\n            p = i;\n            currentTokenIndex = index;\n            if (p == 0)\n            {\n                lastToken = lastTokenBufferStart;\n            }\n            else\n            {\n                lastToken = tokens[p - 1];\n            }\n        }\n\n        public virtual int Size\n        {\n            get\n            {\n                throw new NotSupportedException(\"Unbuffered stream cannot know its size\");\n            }\n        }\n\n        public virtual string SourceName\n        {\n            get\n            {\n                return TokenSource.SourceName;\n            }\n        }\n\n        [return: NotNull]\n        public virtual string GetText(Interval interval)\n        {\n            int bufferStartIndex = GetBufferStartIndex();\n            int bufferStopIndex = bufferStartIndex + tokens.Length - 1;\n            int start = interval.a;\n            int stop = interval.b;\n            if (start < bufferStartIndex || stop > bufferStopIndex)\n            {\n                throw new NotSupportedException(\"interval \" + interval + \" not in token buffer window: \" + bufferStartIndex + \"..\" + bufferStopIndex);\n            }\n            int a = start - bufferStartIndex;\n            int b = stop - bufferStartIndex;\n            StringBuilder buf = new StringBuilder();\n            for (int i = a; i <= b; i++)\n            {\n                IToken t = tokens[i];\n                buf.Append(t.Text);\n            }\n            return buf.ToString();\n        }\n\n        protected internal int GetBufferStartIndex()\n        {\n            return currentTokenIndex - p;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/src/Vocabulary.cs",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Sharpen;\n\nnamespace Antlr4.Runtime\n{\n    /// <summary>\n    /// This class provides a default implementation of the\n    /// <see cref=\"IVocabulary\"/>\n    /// interface.\n    /// </summary>\n    /// <author>Sam Harwell</author>\n    public class Vocabulary : IVocabulary\n    {\n        private static readonly string[] EmptyNames = Collections.EmptyList<string>();\n\n        /// <summary>\n        /// Gets an empty\n        /// <see cref=\"IVocabulary\"/>\n        /// instance.\n        /// <p>\n        /// No literal or symbol names are assigned to token types, so\n        /// <see cref=\"GetDisplayName(int)\"/>\n        /// returns the numeric value for all tokens\n        /// except\n        /// <see cref=\"TokenConstants.EOF\"/>\n        /// .</p>\n        /// </summary>\n        [NotNull]\n        public static readonly Vocabulary EmptyVocabulary = new Vocabulary(EmptyNames, EmptyNames, EmptyNames);\n\n        [NotNull]\n        private readonly string[] literalNames;\n\n        [NotNull]\n        private readonly string[] symbolicNames;\n\n        [NotNull]\n        private readonly string[] displayNames;\n\n        private readonly int maxTokenType;\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"Vocabulary\"/>\n        /// from the specified\n        /// literal and symbolic token names.\n        /// </summary>\n        /// <param name=\"literalNames\">\n        /// The literal names assigned to tokens, or\n        /// <see langword=\"null\"/>\n        /// if no literal names are assigned.\n        /// </param>\n        /// <param name=\"symbolicNames\">\n        /// The symbolic names assigned to tokens, or\n        /// <see langword=\"null\"/>\n        /// if no symbolic names are assigned.\n        /// </param>\n        /// <seealso cref=\"GetLiteralName(int)\"/>\n        /// <seealso cref=\"GetSymbolicName(int)\"/>\n        public Vocabulary(string[] literalNames, string[] symbolicNames)\n            : this(literalNames, symbolicNames, null)\n        {\n        }\n\n        /// <summary>\n        /// Constructs a new instance of\n        /// <see cref=\"Vocabulary\"/>\n        /// from the specified\n        /// literal, symbolic, and display token names.\n        /// </summary>\n        /// <param name=\"literalNames\">\n        /// The literal names assigned to tokens, or\n        /// <see langword=\"null\"/>\n        /// if no literal names are assigned.\n        /// </param>\n        /// <param name=\"symbolicNames\">\n        /// The symbolic names assigned to tokens, or\n        /// <see langword=\"null\"/>\n        /// if no symbolic names are assigned.\n        /// </param>\n        /// <param name=\"displayNames\">\n        /// The display names assigned to tokens, or\n        /// <see langword=\"null\"/>\n        /// to use the values in\n        /// <paramref name=\"literalNames\"/>\n        /// and\n        /// <paramref name=\"symbolicNames\"/>\n        /// as\n        /// the source of display names, as described in\n        /// <see cref=\"GetDisplayName(int)\"/>\n        /// .\n        /// </param>\n        /// <seealso cref=\"GetLiteralName(int)\"/>\n        /// <seealso cref=\"GetSymbolicName(int)\"/>\n        /// <seealso cref=\"GetDisplayName(int)\"/>\n        public Vocabulary(string[] literalNames, string[] symbolicNames, string[] displayNames)\n        {\n            this.literalNames = literalNames != null ? literalNames : EmptyNames;\n            this.symbolicNames = symbolicNames != null ? symbolicNames : EmptyNames;\n            this.displayNames = displayNames != null ? displayNames : EmptyNames;\n\t\t\tthis.maxTokenType =\n\t\t\t\tSystem.Math.Max(this.displayNames.Length,\n\t\t\t\t\t\t System.Math.Max(this.literalNames.Length, this.symbolicNames.Length)) - 1;\n\n        }\n\n\t\t/// <summary>\n\t\t/// Returns the highest token type value. It can be used to iterate from\n\t\t/// zero to that number, inclusively, thus querying all stored entries.\n\t\t/// </summary>\n        public virtual int getMaxTokenType()\n        {\n        \treturn maxTokenType;\n        }\n\n        [return: Nullable]\n        public virtual string GetLiteralName(int tokenType)\n        {\n            if (tokenType >= 0 && tokenType < literalNames.Length)\n            {\n                return literalNames[tokenType];\n            }\n            return null;\n        }\n\n        [return: Nullable]\n        public virtual string GetSymbolicName(int tokenType)\n        {\n            if (tokenType >= 0 && tokenType < symbolicNames.Length)\n            {\n                return symbolicNames[tokenType];\n            }\n            if (tokenType == TokenConstants.EOF)\n            {\n                return \"EOF\";\n            }\n            return null;\n        }\n\n        [return: NotNull]\n        public virtual string GetDisplayName(int tokenType)\n        {\n            if (tokenType >= 0 && tokenType < displayNames.Length)\n            {\n                string displayName = displayNames[tokenType];\n                if (displayName != null)\n                {\n                    return displayName;\n                }\n            }\n            string literalName = GetLiteralName(tokenType);\n            if (literalName != null)\n            {\n                return literalName;\n            }\n            string symbolicName = GetSymbolicName(tokenType);\n            if (symbolicName != null)\n            {\n                return symbolicName;\n            }\n            return tokenType.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/ErrorListener.cs",
    "content": "using Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\npublic class ErrorListener<S> : ConsoleErrorListener<S>\n{\n    public bool had_error;\n\n    public override void SyntaxError(TextWriter output, IRecognizer recognizer, S offendingSymbol, int line,\n        int col, string msg, RecognitionException e)\n    {\n        had_error = true;\n        base.SyntaxError(output, recognizer, offendingSymbol, line, col, msg, e);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/Program.cs",
    "content": "using Antlr4.Runtime;\nusing System;\nusing System.Linq;\nusing System.Text;\n\npublic class Program\n{\n    static void Main(string[] args)\n    {\n        bool show_tree = false;\n        bool show_tokens = false;\n        string file_name = null;\n        string input = null;\n        for (int i = 0; i < args.Length; ++i)\n        {\n            if (args[i].Equals(\"-tokens\"))\n            {\n                show_tokens = true;\n                continue;\n            }\n            else if (args[i].Equals(\"-tree\"))\n            {\n                show_tree = true;\n                continue;\n            }\n            else if (args[i].Equals(\"-input\"))\n                input = args[i];\n            else if (args[i].Equals(\"-file\"))\n                file_name = args[++i];\n        }\n        ICharStream str = null;\n        if (input == null && file_name == null)\n        {\n            StringBuilder sb = new StringBuilder();\n            int ch;\n            while ((ch = System.Console.Read()) != -1)\n            {\n                sb.Append((char)ch);\n            }\n            input = sb.ToString();\n            str = CharStreams.fromString(input);\n        }\n        else if (input != null)\n        {\n            str = CharStreams.fromString(input);\n        }\n        else if (file_name != null)\n        {\n            str = CharStreams.fromPath(file_name);\n        }\n        var lexer = new asm8080Lexer(str);\n        if (show_tokens)\n        {\n            StringBuilder new_s = new StringBuilder();\n            for (int i = 0; ; ++i)\n            {\n                var ro_token = lexer.NextToken();\n                var token = (CommonToken)ro_token;\n                token.TokenIndex = i;\n                new_s.AppendLine(token.ToString());\n                if (token.Type == Antlr4.Runtime.TokenConstants.EOF)\n                    break;\n            }\n            System.Console.Error.WriteLine(new_s.ToString());\n        }\n        lexer.Reset();\n        var tokens = new CommonTokenStream(lexer);\n        var parser = new asm8080Parser(tokens);\n        var listener_lexer = new ErrorListener<int>();\n        var listener_parser = new ErrorListener<IToken>();\n        lexer.AddErrorListener(listener_lexer);\n        parser.AddErrorListener(listener_parser);\n        parser.Profile = true;\n        var tree = parser.prog();\n        if (listener_lexer.had_error || listener_parser.had_error)\n        {\n            System.Console.Error.WriteLine(\"parse failed.\");\n        }\n        else\n        {\n            System.Console.Error.WriteLine(\"parse succeeded.\");\n        }\n        if (show_tree)\n        {\n            System.Console.Error.WriteLine(tree.ToStringTree());\n        }\n        System.Console.Out.WriteLine(String.Join(\", \", parser.ParseInfo.getDecisionInfo().Select(d => d.ToString())));\n        System.Environment.Exit(listener_lexer.had_error || listener_parser.had_error ? 1 : 0);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/Test.csproj",
    "content": "<!-- Template generated code from Antlr4BuildTasks.dotnet-antlr v 1.3 -->\n<Project Sdk=\"Microsoft.NET.Sdk\" >\n  <PropertyGroup>\n    <TargetFramework>net5.0</TargetFramework>\n    <OutputType>Exe</OutputType>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Antlr4 Include=\"asm8080.g4\" />\n  </ItemGroup>\n\n  <PropertyGroup>\n    <AntlrToolPath>../../../../tool/target/antlr4-*-SNAPSHOT-complete.jar</AntlrToolPath>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\Antlr4.csproj\" />\n    <PackageReference Include=\"Antlr4BuildTasks\" Version = \"8.13\" PrivateAssets=\"all\"/>\n  </ItemGroup>\n\n  <PropertyGroup>\n    <RestoreProjectStyle>PackageReference</RestoreProjectStyle>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|AnyCPU'\" >\n    <NoWarn>1701;1702;3021</NoWarn>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/Test.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.31019.35\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Test\", \"Test.csproj\", \"{FD11E8CC-1631-4FF3-9B44-F10084562311}\"\nEndProject\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Antlr4\", \"..\\..\\src\\Antlr4.csproj\", \"{A60B5000-4473-4D00-85C4-C3A4B469F608}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|Any CPU = Debug|Any CPU\n\t\tRelease|Any CPU = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{FD11E8CC-1631-4FF3-9B44-F10084562311}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{FD11E8CC-1631-4FF3-9B44-F10084562311}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{FD11E8CC-1631-4FF3-9B44-F10084562311}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{FD11E8CC-1631-4FF3-9B44-F10084562311}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{A60B5000-4473-4D00-85C4-C3A4B469F608}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{A60B5000-4473-4D00-85C4-C3A4B469F608}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{A60B5000-4473-4D00-85C4-C3A4B469F608}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{A60B5000-4473-4D00-85C4-C3A4B469F608}.Release|Any CPU.Build.0 = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {2FFB66F7-2552-4F2B-B97E-77B5F8743ED4}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/TreeOutput.cs",
    "content": "\n// Template generated code from Antlr4BuildTasks.dotnet-antlr v 1.3\n\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Tree;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\npublic class TreeOutput\n{\n    private static int changed = 0;\n    private static bool first_time = true;\n\n    public static StringBuilder OutputTree(IParseTree tree, Lexer lexer, Parser parser, CommonTokenStream stream)\n    {\n        changed = 0;\n        first_time = true;\n        var sb = new StringBuilder();\n        ParenthesizedAST(tree, sb, lexer, parser, stream);\n        return sb;\n    }\n\n    private static void ParenthesizedAST(IParseTree tree, StringBuilder sb, Lexer lexer, Parser parser, CommonTokenStream stream, int level = 0)\n    {\n        if (tree as TerminalNodeImpl != null)\n        {\n            TerminalNodeImpl tok = tree as TerminalNodeImpl;\n            Interval interval = tok.SourceInterval;\n            IList<IToken> inter = null;\n            if (tok.Symbol.TokenIndex >= 0)\n                inter = stream?.GetHiddenTokensToLeft(tok.Symbol.TokenIndex);\n            if (inter != null)\n                foreach (var t in inter)\n                {\n                    var ty = tok.Symbol.Type;\n                    var name = lexer.Vocabulary.GetSymbolicName(ty);\n                    StartLine(sb, level);\n                    sb.AppendLine(\"(\" + name + \" text = \" + PerformEscapes(t.Text) + \" \" + lexer.ChannelNames[t.Channel]);\n                }\n            {\n                var ty = tok.Symbol.Type;\n                var name = lexer.Vocabulary.GetSymbolicName(ty);\n                StartLine(sb, level);\n                sb.AppendLine(\"( \" + name + \" i =\" + tree.SourceInterval.a\n                    + \" txt =\" + PerformEscapes(tree.GetText())\n                    + \" tt =\" + tok.Symbol.Type\n                    + \" \" + lexer.ChannelNames[tok.Symbol.Channel]);\n            }\n        }\n        else\n        {\n            var x = tree as RuleContext;\n            var ri = x.RuleIndex;\n            var name = parser.RuleNames[ri];\n            StartLine(sb, level);\n            sb.Append(\"( \" + name);\n            sb.AppendLine();\n        }\n        for (int i = 0; i<tree.ChildCount; ++i)\n        {\n            var c = tree.GetChild(i);\n            ParenthesizedAST(c, sb, lexer, parser, stream, level + 1);\n        }\n        if (level == 0)\n        {\n            for (int k = 0; k < 1 + changed - level; ++k) sb.Append(\") \");\n            sb.AppendLine();\n            changed = 0;\n        }\n    }\n\n    private static void StartLine(StringBuilder sb, int level = 0)\n    {\n        if (changed - level >= 0)\n        {\n            if (!first_time)\n            {\n                for (int j = 0; j < level; ++j) sb.Append(\"  \");\n                for (int k = 0; k < 1 + changed - level; ++k) sb.Append(\") \");\n                sb.AppendLine();\n            }\n            changed = 0;\n            first_time = false;\n        }\n        changed = level;\n        for (int j = 0; j < level; ++j) sb.Append(\"  \");\n    }\n\n    private static string ToLiteral(string input)\n    {\n        using (var writer = new StringWriter())\n        {\n            var literal = input;\n            literal = literal.Replace(\"\\\\\", \"\\\\\\\\\");\n            return literal;\n        }\n    }\n\n    public static string PerformEscapes(string s)\n    {\n        StringBuilder new_s = new StringBuilder();\n        new_s.Append(ToLiteral(s));\n        return new_s.ToString();\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/asm8080.g4",
    "content": "/*\nBSD License\n\nCopyright (c) 2018, Tom Everett\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n3. Neither the name of Tom Everett nor the names of its contributors\n   may be used to endorse or promote products derived from this software\n   without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\n* http://fms.komkon.org/comp/CPUs/8080.txt\n*/\n\ngrammar asm8080;\n\nprog\n   : (line? EOL) +\n   ;\n\nline\n   : lbl? (instruction | directive)? comment?\n   ;\n\ninstruction\n   : opcode expressionlist?\n   ;\n\nopcode\n   : OPCODE\n   ;\n\nregister_\n   : REGISTER\n   ;\n\ndirective\n   : argument? assemblerdirective expressionlist\n   ;\n\nassemblerdirective\n   : ASSEMBLER_DIRECTIVE\n   ;\n\nlbl\n   : label ':'?\n   ;\n\nexpressionlist\n   : expression (',' expression)*\n   ;\n\nlabel\n   : name\n   ;\n\nexpression\n   : multiplyingExpression (('+' | '-') multiplyingExpression)*\n   ;\n\nmultiplyingExpression\n   : argument (('*' | '/') argument)*\n   ;\n\nargument\n   : number\n   | register_\n   | dollar\n   | name\n   | string\n   | ('(' expression ')')\n   ;\n\ndollar\n   : '$'\n   ;\n\nstring\n   : STRING\n   ;\n\nname\n   : NAME\n   ;\n\nnumber\n   : NUMBER\n   ;\n\ncomment\n   : COMMENT\n   ;\n\n\nASSEMBLER_DIRECTIVE\n   : (O R G) | (E N D) | (E Q U) | (D B) | (D W) | (D S) | (I F) | (E N D I F) | (S E T)\n   ;\n\n\nREGISTER\n   : 'A' | 'B' | 'C' | 'D' | 'E' | 'H' | 'L' | 'PC' | 'SP'\n   ;\n\n\nOPCODE\n   : (M O V) | (M V I) | (L D A) | (S T A) | (L D A X) | (S T A X) | (L H L D) | (S H L D) | (L X I) | (P U S H) | (P O P) | (X T H L) | (S P H L) | (P C H L) | (X C H G) | (A D D) | (S U B) | (I N R) | (D C R) | (C M P) | (A N A) | (O R A) | (X R A) | (A D I) | (S U I) | (C P I) | (A N I) | (O R I) | (X R I) | (D A A) | (A D C) | (A C I) | (S B B) | (S B I) | (D A D) | (I N X) | (D C X) | (J M P) | (C A L L) | (R E T) | (R A L) | (R A R) | (R L C) | (R R C) | (I N) | (O U T) | (C M C) | (S T C) | (C M A) | (H L T) | (N O P) | (D I) | (E I) | (R S T) | (J N Z) | (J Z) | (J N C) | (J C) | (J P O) | (J P E) | (J P) | (J M) | (C N Z) | (C Z) | (C N C) | (C C) | (C P O) | (C P E) | (C P) | (C M) | (R N Z) | (R Z) | (R N C) | (R C) | (R P O) | (R P E) | (R P) | (R M)\n   ;\n\n\nfragment A\n   : ('a' | 'A')\n   ;\n\n\nfragment B\n   : ('b' | 'B')\n   ;\n\n\nfragment C\n   : ('c' | 'C')\n   ;\n\n\nfragment D\n   : ('d' | 'D')\n   ;\n\n\nfragment E\n   : ('e' | 'E')\n   ;\n\n\nfragment F\n   : ('f' | 'F')\n   ;\n\n\nfragment G\n   : ('g' | 'G')\n   ;\n\n\nfragment H\n   : ('h' | 'H')\n   ;\n\n\nfragment I\n   : ('i' | 'I')\n   ;\n\n\nfragment J\n   : ('j' | 'J')\n   ;\n\n\nfragment K\n   : ('k' | 'K')\n   ;\n\n\nfragment L\n   : ('l' | 'L')\n   ;\n\n\nfragment M\n   : ('m' | 'M')\n   ;\n\n\nfragment N\n   : ('n' | 'N')\n   ;\n\n\nfragment O\n   : ('o' | 'O')\n   ;\n\n\nfragment P\n   : ('p' | 'P')\n   ;\n\n\nfragment Q\n   : ('q' | 'Q')\n   ;\n\n\nfragment R\n   : ('r' | 'R')\n   ;\n\n\nfragment S\n   : ('s' | 'S')\n   ;\n\n\nfragment T\n   : ('t' | 'T')\n   ;\n\n\nfragment U\n   : ('u' | 'U')\n   ;\n\n\nfragment V\n   : ('v' | 'V')\n   ;\n\n\nfragment W\n   : ('w' | 'W')\n   ;\n\n\nfragment X\n   : ('x' | 'X')\n   ;\n\n\nfragment Y\n   : ('y' | 'Y')\n   ;\n\n\nfragment Z\n   : ('z' | 'Z')\n   ;\n\n\nNAME\n   : [a-zA-Z] [a-zA-Z0-9.\"]*\n   ;\n\n\nNUMBER\n   : '$'? [0-9a-fA-F] + ('H' | 'h')?\n   ;\n\n\nCOMMENT\n   : ';' ~ [\\r\\n]* -> skip\n   ;\n\n\nSTRING\n   : '\\u0027' ~'\\u0027'* '\\u0027'\n   ;\n\n\nEOL\n   : [\\r\\n] +\n   ;\n\n\nWS\n   : [ \\t] -> skip\n   ;\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/cpm22.asm",
    "content": "\n;**************************************************************\n;*\n;*             C P / M   version   2 . 2\n;*\n;*   Reconstructed from memory image on February 27, 1981\n;*\n;*                by Clark A. Calkins\n;*\n;**************************************************************\n;\n;   Set memory limit here. This is the amount of contigeous\n; ram starting from 0000. CP/M will reside at the end of this space.\n;\nMEM\tEQU\t62\t;for a 62k system (TS802 TEST - WORKS OK).\n;\nIOBYTE\tEQU\t3\t;i/o definition byte.\nTDRIVE\tEQU\t4\t;current drive name and user number.\nENTRY\tEQU\t5\t;entry point for the cp/m bdos.\nTFCB\tEQU\t5CH\t;default file control block.\nTBUFF\tEQU\t80H\t;i/o buffer and command line storage.\nTBASE\tEQU\t100H\t;transiant program storage area.\n;\n;   Set control character equates.\n;\nCNTRLC\tEQU\t3\t;control-c\nCNTRLE\tEQU\t05H\t;control-e\nBS\tEQU\t08H\t;backspace\nTAB\tEQU\t09H\t;tab\nLF\tEQU\t0AH\t;line feed\nFF\tEQU\t0CH\t;form feed\nCR\tEQU\t0DH\t;carriage return\nCNTRLP\tEQU\t10H\t;control-p\nCNTRLR\tEQU\t12H\t;control-r\nCNTRLS\tEQU\t13H\t;control-s\nCNTRLU\tEQU\t15H\t;control-u\nCNTRLX\tEQU\t18H\t;control-x\nCNTRLZ\tEQU\t1AH\t;control-z (end-of-file mark)\nDEL\tEQU\t7FH\t;rubout\n;\n;   Set origin for CP/M\n;\n\tORG\t(MEM-7)*1024\n;\nCBASE\tJMP\tCOMMAND\t;execute command processor (ccp).\n\tJMP\tCLEARBUF\t;entry to empty input buffer before starting ccp.\n\n;\n;   Standard cp/m ccp input buffer. Format is (max length),\n; (actual length), (char #1), (char #2), (char #3), etc.\n;\nINBUFF\tDB\t127\t;length of input buffer.\n\tDB\t0\t;current length of contents.\n\tDB\t'Copyright'\n\tDB\t' 1979 (c) by Digital Research      '\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nINPOINT\tDW\tINBUFF+2;input line pointer\nNAMEPNT\tDW\t0\t;input line pointer used for error message. Points to\n;\t\t\t;start of name in error.\n;\n;   Routine to print (A) on the console. All registers used.\n;\nPRINT\tMOV\tE,A\t;setup bdos call.\n\tMVI\tC,2\n\tJMP\tENTRY\n;\n;   Routine to print (A) on the console and to save (BC).\n;\nPRINTB\tPUSH\tB\n\tCALL\tPRINT\n\tPOP\tB\n\tRET\n;\n;   Routine to send a carriage return, line feed combination\n; to the console.\n;\nCRLF\tMVI\tA,CR\n\tCALL\tPRINTB\n\tMVI\tA,LF\n\tJMP\tPRINTB\n;\n;   Routine to send one space to the console and save (BC).\n;\nSPACE\tMVI\tA,' '\n\tJMP\tPRINTB\n;\n;   Routine to print character string pointed to be (BC) on the\n; console. It must terminate with a null byte.\n;\nPLINE\tPUSH\tB\n\tCALL\tCRLF\n\tPOP\tH\nPLINE2\tMOV\tA,M\n\tORA\tA\n\tRZ\n\tINX\tH\n\tPUSH\tH\n\tCALL\tPRINT\n\tPOP\tH\n\tJMP\tPLINE2\n;\n;   Routine to reset the disk system.\n;\nRESDSK\tMVI\tC,13\n\tJMP\tENTRY\n;\n;   Routine to select disk (A).\n;\nDSKSEL\tMOV\tE,A\n\tMVI\tC,14\n\tJMP\tENTRY\n;\n;   Routine to call bdos and save the return code. The zero\n; flag is set on a return of 0ffh.\n;\nENTRY1\tCALL\tENTRY\n\tSTA\tRTNCODE\t;save return code.\n\tINR\tA\t;set zero if 0ffh returned.\n\tRET\n;\n;   Routine to open a file. (DE) must point to the FCB.\n;\nOPEN\tMVI\tC,15\n\tJMP\tENTRY1\n;\n;   Routine to open file at (FCB).\n;\nOPENFCB\tXRA\tA\t;clear the record number byte at fcb+32\n\tSTA\tFCB+32\n\tLXI\tD,FCB\n\tJMP\tOPEN\n;\n;   Routine to close a file. (DE) points to FCB.\n;\nCLOSE\tMVI\tC,16\n\tJMP\tENTRY1\n;\n;   Routine to search for the first file with ambigueous name\n; (DE).\n;\nSRCHFST\tMVI\tC,17\n\tJMP\tENTRY1\n;\n;   Search for the next ambigeous file name.\n;\nSRCHNXT\tMVI\tC,18\n\tJMP\tENTRY1\n;\n;   Search for file at (FCB).\n;\nSRCHFCB\tLXI\tD,FCB\n\tJMP\tSRCHFST\n;\n;   Routine to delete a file pointed to by (DE).\n;\nDELETE\tMVI\tC,19\n\tJMP\tENTRY\n;\n;   Routine to call the bdos and set the zero flag if a zero\n; status is returned.\n;\nENTRY2\tCALL\tENTRY\n\tORA\tA\t;set zero flag if appropriate.\n\tRET\n;\n;   Routine to read the next record from a sequential file.\n; (DE) points to the FCB.\n;\nRDREC\tMVI\tC,20\n\tJMP\tENTRY2\n;\n;   Routine to read file at (FCB).\n;\nREADFCB\tLXI\tD,FCB\n\tJMP\tRDREC\n;\n;   Routine to write the next record of a sequential file.\n; (DE) points to the FCB.\n;\nWRTREC\tMVI\tC,21\n\tJMP\tENTRY2\n;\n;   Routine to create the file pointed to by (DE).\n;\nCREATE\tMVI\tC,22\n\tJMP\tENTRY1\n;\n;   Routine to rename the file pointed to by (DE). Note that\n; the new name starts at (DE+16).\n;\nRENAM\tMVI\tC,23\n\tJMP\tENTRY\n;\n;   Get the current user code.\n;\nGETUSR\tMVI\tE,0FFH\n;\n;   Routne to get or set the current user code.\n; If (E) is FF then this is a GET, else it is a SET.\n;\nGETSETUC:MVI\tC,32\n\tJMP\tENTRY\n;\n;   Routine to set the current drive byte at (TDRIVE).\n;\nSETCDRV\tCALL\tGETUSR\t;get user number\n\tADD\tA\t;and shift into the upper 4 bits.\n\tADD\tA\n\tADD\tA\n\tADD\tA\n\tLXI\tH,CDRIVE;now add in the current drive number.\n\tORA\tM\n\tSTA\tTDRIVE\t;and save.\n\tRET\n;\n;   Move currently active drive down to (TDRIVE).\n;\nMOVECD\tLDA\tCDRIVE\n\tSTA\tTDRIVE\n\tRET\n;\n;   Routine to convert (A) into upper case ascii. Only letters\n; are affected.\n;\nUPPER\tCPI\t'a'\t;check for letters in the range of 'a' to 'z'.\n\tRC\n\tCPI\t'{'\n\tRNC\n\tANI\t5FH\t;convert it if found.\n\tRET\n;\n;   Routine to get a line of input. We must check to see if the\n; user is in (BATCH) mode. If so, then read the input from file\n; ($$$.SUB). At the end, reset to console input.\n;\nGETINP\tLDA\tBATCH\t;if =0, then use console input.\n\tORA\tA\n\tJZ\tGETINP1\n;\n;   Use the submit file ($$$.sub) which is prepared by a\n; SUBMIT run. It must be on drive (A) and it will be deleted\n; if and error occures (like eof).\n;\n\tLDA\tCDRIVE\t;select drive 0 if need be.\n\tORA\tA\n\tMVI\tA,0\t;always use drive A for submit.\n\tCNZ\tDSKSEL\t;select it if required.\n\tLXI\tD,BATCHFCB\n\tCALL\tOPEN\t;look for it.\n\tJZ\tGETINP1\t;if not there, use normal input.\n\tLDA\tBATCHFCB+15;get last record number+1.\n\tDCR\tA\n\tSTA\tBATCHFCB+32\n\tLXI\tD,BATCHFCB\n\tCALL\tRDREC\t;read last record.\n\tJNZ\tGETINP1\t;quit on end of file.\n;\n;   Move this record into input buffer.\n;\n\tLXI\tD,INBUFF+1\n\tLXI\tH,TBUFF\t;data was read into buffer here.\n\tMVI\tB,128\t;all 128 characters may be used.\n\tCALL\tHL2DE\t;(HL) to (DE), (B) bytes.\n\tLXI\tH,BATCHFCB+14\n\tMVI\tM,0\t;zero out the 's2' byte.\n\tINX\tH\t;and decrement the record count.\n\tDCR\tM\n\tLXI\tD,BATCHFCB;close the batch file now.\n\tCALL\tCLOSE\n\tJZ\tGETINP1\t;quit on an error.\n\tLDA\tCDRIVE\t;re-select previous drive if need be.\n\tORA\tA\n\tCNZ\tDSKSEL\t;don't do needless selects.\n;\n;   Print line just read on console.\n;\n\tLXI\tH,INBUFF+2\n\tCALL\tPLINE2\n\tCALL\tCHKCON\t;check console, quit on a key.\n\tJZ\tGETINP2\t;jump if no key is pressed.\n;\n;   Terminate the submit job on any keyboard input. Delete this\n; file such that it is not re-started and jump to normal keyboard\n; input section.\n;\n\tCALL\tDELBATCH;delete the batch file.\n\tJMP\tCMMND1\t;and restart command input.\n;\n;   Get here for normal keyboard input. Delete the submit file\n; incase there was one.\n;\nGETINP1\tCALL\tDELBATCH;delete file ($$$.sub).\n\tCALL\tSETCDRV\t;reset active disk.\n\tMVI\tC,10\t;get line from console device.\n\tLXI\tD,INBUFF\n\tCALL\tENTRY\n\tCALL\tMOVECD\t;reset current drive (again).\n;\n;   Convert input line to upper case.\n;\nGETINP2\tLXI\tH,INBUFF+1\n\tMOV\tB,M\t;(B)=character counter.\nGETINP3\tINX\tH\n\tMOV\tA,B\t;end of the line?\n\tORA\tA\n\tJZ\tGETINP4\n\tMOV\tA,M\t;convert to upper case.\n\tCALL\tUPPER\n\tMOV\tM,A\n\tDCR\tB\t;adjust character count.\n\tJMP\tGETINP3\nGETINP4\tMOV\tM,A\t;add trailing null.\n\tLXI\tH,INBUFF+2\n\tSHLD\tINPOINT\t;reset input line pointer.\n\tRET\n;\n;   Routine to check the console for a key pressed. The zero\n; flag is set is none, else the character is returned in (A).\n;\nCHKCON\tMVI\tC,11\t;check console.\n\tCALL\tENTRY\n\tORA\tA\n\tRZ\t\t;return if nothing.\n\tMVI\tC,1\t;else get character.\n\tCALL\tENTRY\n\tORA\tA\t;clear zero flag and return.\n\tRET\n;\n;   Routine to get the currently active drive number.\n;\nGETDSK\tMVI\tC,25\n\tJMP\tENTRY\n;\n;   Set the stabdard dma address.\n;\nSTDDMA\tLXI\tD,TBUFF\n;\n;   Routine to set the dma address to (DE).\n;\nDMASET\tMVI\tC,26\n\tJMP\tENTRY\n;\n;  Delete the batch file created by SUBMIT.\n;\nDELBATCH:LXI\tH,BATCH\t;is batch active?\n\tMOV\tA,M\n\tORA\tA\n\tRZ\n\tMVI\tM,0\t;yes, de-activate it.\n\tXRA\tA\n\tCALL\tDSKSEL\t;select drive 0 for sure.\n\tLXI\tD,BATCHFCB;and delete this file.\n\tCALL\tDELETE\n\tLDA\tCDRIVE\t;reset current drive.\n\tJMP\tDSKSEL\n;\n;   Check to two strings at (PATTRN1) and (PATTRN2). They must be\n; the same or we halt....\n;\nVERIFY\tLXI\tD,PATTRN1;these are the serial number bytes.\n\tLXI\tH,PATTRN2;ditto, but how could they be different?\n\tMVI\tB,6\t;6 bytes each.\nVERIFY1\tLDAX\tD\n\tCMP\tM\n\tJNZ\tHALT\t;jump to halt routine.\n\tINX\tD\n\tINX\tH\n\tDCR\tB\n\tJNZ\tVERIFY1\n\tRET\n;\n;   Print back file name with a '?' to indicate a syntax error.\n;\nSYNERR\tCALL\tCRLF\t;end current line.\n\tLHLD\tNAMEPNT\t;this points to name in error.\nSYNERR1\tMOV\tA,M\t;print it until a space or null is found.\n\tCPI\t' '\n\tJZ\tSYNERR2\n\tORA\tA\n\tJZ\tSYNERR2\n\tPUSH\tH\n\tCALL\tPRINT\n\tPOP\tH\n\tINX\tH\n\tJMP\tSYNERR1\nSYNERR2\tMVI\tA,'?'\t;add trailing '?'.\n\tCALL\tPRINT\n\tCALL\tCRLF\n\tCALL\tDELBATCH;delete any batch file.\n\tJMP\tCMMND1\t;and restart from console input.\n;\n;   Check character at (DE) for legal command input. Note that the\n; zero flag is set if the character is a delimiter.\n;\nCHECK\tLDAX\tD\n\tORA\tA\n\tRZ\n\tCPI\t' '\t;control characters are not legal here.\n\tJC\tSYNERR\n\tRZ\t\t;check for valid delimiter.\n\tCPI\t'='\n\tRZ\n\tCPI\t'_'\n\tRZ\n\tCPI\t'.'\n\tRZ\n\tCPI\t':'\n\tRZ\n\tCPI\t';'\n\tRZ\n\tCPI\t'<'\n\tRZ\n\tCPI\t'>'\n\tRZ\n\tRET\n;\n;   Get the next non-blank character from (DE).\n;\nNONBLANK:LDAX\tD\n\tORA\tA\t;string ends with a null.\n\tRZ\n\tCPI\t' '\n\tRNZ\n\tINX\tD\n\tJMP\tNONBLANK\n;\n;   Add (HL)=(HL)+(A)\n;\nADDHL\tADD\tL\n\tMOV\tL,A\n\tRNC\t;take care of any carry.\n\tINR\tH\n\tRET\n;\n;   Convert the first name in (FCB).\n;\nCONVFST\tMVI\tA,0\n;\n;   Format a file name (convert * to '?', etc.). On return,\n; (A)=0 is an unambigeous name was specified. Enter with (A) equal to\n; the position within the fcb for the name (either 0 or 16).\n;\nCONVERT\tLXI\tH,FCB\n\tCALL\tADDHL\n\tPUSH\tH\n\tPUSH\tH\n\tXRA\tA\n\tSTA\tCHGDRV\t;initialize drive change flag.\n\tLHLD\tINPOINT\t;set (HL) as pointer into input line.\n\tXCHG\n\tCALL\tNONBLANK;get next non-blank character.\n\tXCHG\n\tSHLD\tNAMEPNT\t;save pointer here for any error message.\n\tXCHG\n\tPOP\tH\n\tLDAX\tD\t;get first character.\n\tORA\tA\n\tJZ\tCONVRT1\n\tSBI\t'A'-1\t;might be a drive name, convert to binary.\n\tMOV\tB,A\t;and save.\n\tINX\tD\t;check next character for a ':'.\n\tLDAX\tD\n\tCPI\t':'\n\tJZ\tCONVRT2\n\tDCX\tD\t;nope, move pointer back to the start of the line.\nCONVRT1\tLDA\tCDRIVE\n\tMOV\tM,A\n\tJMP\tCONVRT3\nCONVRT2\tMOV\tA,B\n\tSTA\tCHGDRV\t;set change in drives flag.\n\tMOV\tM,B\n\tINX\tD\n;\n;   Convert the basic file name.\n;\nCONVRT3\tMVI\tB,08H\nCONVRT4\tCALL\tCHECK\n\tJZ\tCONVRT8\n\tINX\tH\n\tCPI\t'*'\t;note that an '*' will fill the remaining\n\tJNZ\tCONVRT5\t;field with '?'.\n\tMVI\tM,'?'\n\tJMP\tCONVRT6\nCONVRT5\tMOV\tM,A\n\tINX\tD\nCONVRT6\tDCR\tB\n\tJNZ\tCONVRT4\nCONVRT7\tCALL\tCHECK\t;get next delimiter.\n\tJZ\tGETEXT\n\tINX\tD\n\tJMP\tCONVRT7\nCONVRT8\tINX\tH\t;blank fill the file name.\n\tMVI\tM,' '\n\tDCR\tB\n\tJNZ\tCONVRT8\n;\n;   Get the extension and convert it.\n;\nGETEXT\tMVI\tB,03H\n\tCPI\t'.'\n\tJNZ\tGETEXT5\n\tINX\tD\nGETEXT1\tCALL\tCHECK\n\tJZ\tGETEXT5\n\tINX\tH\n\tCPI\t'*'\n\tJNZ\tGETEXT2\n\tMVI\tM,'?'\n\tJMP\tGETEXT3\nGETEXT2\tMOV\tM,A\n\tINX\tD\nGETEXT3\tDCR\tB\n\tJNZ\tGETEXT1\nGETEXT4\tCALL\tCHECK\n\tJZ\tGETEXT6\n\tINX\tD\n\tJMP\tGETEXT4\nGETEXT5\tINX\tH\n\tMVI\tM,' '\n\tDCR\tB\n\tJNZ\tGETEXT5\nGETEXT6\tMVI\tB,3\nGETEXT7\tINX\tH\n\tMVI\tM,0\n\tDCR\tB\n\tJNZ\tGETEXT7\n\tXCHG\n\tSHLD\tINPOINT\t;save input line pointer.\n\tPOP\tH\n;\n;   Check to see if this is an ambigeous file name specification.\n; Set the (A) register to non zero if it is.\n;\n\tLXI\tB,11\t;set name length.\nGETEXT8\tINX\tH\n\tMOV\tA,M\n\tCPI\t'?'\t;any question marks?\n\tJNZ\tGETEXT9\n\tINR\tB\t;count them.\nGETEXT9\tDCR\tC\n\tJNZ\tGETEXT8\n\tMOV\tA,B\n\tORA\tA\n\tRET\n;\n;   CP/M command table. Note commands can be either 3 or 4 characters long.\n;\nNUMCMDS\tEQU\t6\t;number of commands\nCMDTBL\tDB\t'DIR '\n\tDB\t'ERA '\n\tDB\t'TYPE'\n\tDB\t'SAVE'\n\tDB\t'REN '\n\tDB\t'USER'\n;\n;   The following six bytes must agree with those at (PATTRN2)\n; or cp/m will HALT. Why?\n;\nPATTRN1\tDB\t0,22,0,0,0,0;(* serial number bytes *).\n;\n;   Search the command table for a match with what has just\n; been entered. If a match is found, then we jump to the\n; proper section. Else jump to (UNKNOWN).\n; On return, the (C) register is set to the command number\n; that matched (or NUMCMDS+1 if no match).\n;\nSEARCH\tLXI\tH,CMDTBL\n\tMVI\tC,0\nSEARCH1\tMOV\tA,C\n\tCPI\tNUMCMDS\t;this commands exists.\n\tRNC\n\tLXI\tD,FCB+1\t;check this one.\n\tMVI\tB,4\t;max command length.\nSEARCH2\tLDAX\tD\n\tCMP\tM\n\tJNZ\tSEARCH3\t;not a match.\n\tINX\tD\n\tINX\tH\n\tDCR\tB\n\tJNZ\tSEARCH2\n\tLDAX\tD\t;allow a 3 character command to match.\n\tCPI\t' '\n\tJNZ\tSEARCH4\n\tMOV\tA,C\t;set return register for this command.\n\tRET\nSEARCH3\tINX\tH\n\tDCR\tB\n\tJNZ\tSEARCH3\nSEARCH4\tINR\tC\n\tJMP\tSEARCH1\n;\n;   Set the input buffer to empty and then start the command\n; processor (ccp).\n;\nCLEARBUF:XRA\tA\n\tSTA\tINBUFF+1;second byte is actual length.\n;\n;**************************************************************\n;*\n;*\n;* C C P  -   C o n s o l e   C o m m a n d   P r o c e s s o r\n;*\n;**************************************************************\n;*\nCOMMAND\tLXI\tSP,CCPSTACK;setup stack area.\n\tPUSH\tB\t;note that (C) should be equal to:\n\tMOV\tA,C\t;(uuuudddd) where 'uuuu' is the user number\n\tRAR\t\t;and 'dddd' is the drive number.\n\tRAR\n\tRAR\n\tRAR\n\tANI\t0FH\t;isolate the user number.\n\tMOV\tE,A\n\tCALL\tGETSETUC;and set it.\n\tCALL\tRESDSK\t;reset the disk system.\n\tSTA\tBATCH\t;clear batch mode flag.\n\tPOP\tB\n\tMOV\tA,C\n\tANI\t0FH\t;isolate the drive number.\n\tSTA\tCDRIVE\t;and save.\n\tCALL\tDSKSEL\t;...and select.\n\tLDA\tINBUFF+1\n\tORA\tA\t;anything in input buffer already?\n\tJNZ\tCMMND2\t;yes, we just process it.\n;\n;   Entry point to get a command line from the console.\n;\nCMMND1\tLXI\tSP,CCPSTACK;set stack straight.\n\tCALL\tCRLF\t;start a new line on the screen.\n\tCALL\tGETDSK\t;get current drive.\n\tADI\t'a'\n\tCALL\tPRINT\t;print current drive.\n\tMVI\tA,'>'\n\tCALL\tPRINT\t;and add prompt.\n\tCALL\tGETINP\t;get line from user.\n;\n;   Process command line here.\n;\nCMMND2\tLXI\tD,TBUFF\n\tCALL\tDMASET\t;set standard dma address.\n\tCALL\tGETDSK\n\tSTA\tCDRIVE\t;set current drive.\n\tCALL\tCONVFST\t;convert name typed in.\n\tCNZ\tSYNERR\t;wild cards are not allowed.\n\tLDA\tCHGDRV\t;if a change in drives was indicated,\n\tORA\tA\t;then treat this as an unknown command\n\tJNZ\tUNKNOWN\t;which gets executed.\n\tCALL\tSEARCH\t;else search command table for a match.\n;\n;   Note that an unknown command returns\n; with (A) pointing to the last address\n; in our table which is (UNKNOWN).\n;\n\tLXI\tH,CMDADR;now, look thru our address table for command (A).\n\tMOV\tE,A\t;set (DE) to command number.\n\tMVI\tD,0\n\tDAD\tD\n\tDAD\tD\t;(HL)=(CMDADR)+2*(command number).\n\tMOV\tA,M\t;now pick out this address.\n\tINX\tH\n\tMOV\tH,M\n\tMOV\tL,A\n\tPCHL\t\t;now execute it.\n;\n;   CP/M command address table.\n;\nCMDADR\tDW\tDIRECT,ERASE,TYPE,SAVE\n\tDW\tRENAME,USER,UNKNOWN\n;\n;   Halt the system. Reason for this is unknown at present.\n;\nHALT\tLXI\tH,76F3H\t;'DI HLT' instructions.\n\tSHLD\tCBASE\n\tLXI\tH,CBASE\n\tPCHL\n;\n;   Read error while TYPEing a file.\n;\nRDERROR\tLXI\tB,RDERR\n\tJMP\tPLINE\nRDERR\tDB\t'Read error',0\n;\n;   Required file was not located.\n;\nNONE\tLXI\tB,NOFILE\n\tJMP\tPLINE\nNOFILE\tDB\t'No file',0\n;\n;   Decode a command of the form 'A>filename number{ filename}.\n; Note that a drive specifier is not allowed on the first file\n; name. On return, the number is in register (A). Any error\n; causes 'filename?' to be printed and the command is aborted.\n;\nDECODE\tCALL\tCONVFST\t;convert filename.\n\tLDA\tCHGDRV\t;do not allow a drive to be specified.\n\tORA\tA\n\tJNZ\tSYNERR\n\tLXI\tH,FCB+1\t;convert number now.\n\tLXI\tB,11\t;(B)=sum register, (C)=max digit count.\nDECODE1\tMOV\tA,M\n\tCPI\t' '\t;a space terminates the numeral.\n\tJZ\tDECODE3\n\tINX\tH\n\tSUI\t'0'\t;make binary from ascii.\n\tCPI\t10\t;legal digit?\n\tJNC\tSYNERR\n\tMOV\tD,A\t;yes, save it in (D).\n\tMOV\tA,B\t;compute (B)=(B)*10 and check for overflow.\n\tANI\t0E0H\n\tJNZ\tSYNERR\n\tMOV\tA,B\n\tRLC\n\tRLC\n\tRLC\t;(A)=(B)*8\n\tADD\tB\t;.......*9\n\tJC\tSYNERR\n\tADD\tB\t;.......*10\n\tJC\tSYNERR\n\tADD\tD\t;add in new digit now.\nDECODE2\tJC\tSYNERR\n\tMOV\tB,A\t;and save result.\n\tDCR\tC\t;only look at 11 digits.\n\tJNZ\tDECODE1\n\tRET\nDECODE3\tMOV\tA,M\t;spaces must follow (why?).\n\tCPI\t' '\n\tJNZ\tSYNERR\n\tINX\tH\nDECODE4\tDCR\tC\n\tJNZ\tDECODE3\n\tMOV\tA,B\t;set (A)=the numeric value entered.\n\tRET\n;\n;   Move 3 bytes from (HL) to (DE). Note that there is only\n; one reference to this at (A2D5h).\n;\nMOVE3\tMVI\tB,3\n;\n;   Move (B) bytes from (HL) to (DE).\n;\nHL2DE\tMOV\tA,M\n\tSTAX\tD\n\tINX\tH\n\tINX\tD\n\tDCR\tB\n\tJNZ\tHL2DE\n\tRET\n;\n;   Compute (HL)=(TBUFF)+(A)+(C) and get the byte that's here.\n;\nEXTRACT\tLXI\tH,TBUFF\n\tADD\tC\n\tCALL\tADDHL\n\tMOV\tA,M\n\tRET\n;\n;  Check drive specified. If it means a change, then the new\n; drive will be selected. In any case, the drive byte of the\n; fcb will be set to null (means use current drive).\n;\nDSELECT\tXRA\tA\t;null out first byte of fcb.\n\tSTA\tFCB\n\tLDA\tCHGDRV\t;a drive change indicated?\n\tORA\tA\n\tRZ\n\tDCR\tA\t;yes, is it the same as the current drive?\n\tLXI\tH,CDRIVE\n\tCMP\tM\n\tRZ\n\tJMP\tDSKSEL\t;no. Select it then.\n;\n;   Check the drive selection and reset it to the previous\n; drive if it was changed for the preceeding command.\n;\nRESETDR\tLDA\tCHGDRV\t;drive change indicated?\n\tORA\tA\n\tRZ\n\tDCR\tA\t;yes, was it a different drive?\n\tLXI\tH,CDRIVE\n\tCMP\tM\n\tRZ\n\tLDA\tCDRIVE\t;yes, re-select our old drive.\n\tJMP\tDSKSEL\n;\n;**************************************************************\n;*\n;*           D I R E C T O R Y   C O M M A N D\n;*\n;**************************************************************\n;\nDIRECT\tCALL\tCONVFST\t;convert file name.\n\tCALL\tDSELECT\t;select indicated drive.\n\tLXI\tH,FCB+1\t;was any file indicated?\n\tMOV\tA,M\n\tCPI\t' '\n\tJNZ\tDIRECT2\n\tMVI\tB,11\t;no. Fill field with '?' - same as *.*.\nDIRECT1\tMVI\tM,'?'\n\tINX\tH\n\tDCR\tB\n\tJNZ\tDIRECT1\nDIRECT2\tMVI\tE,0\t;set initial cursor position.\n\tPUSH\tD\n\tCALL\tSRCHFCB\t;get first file name.\n\tCZ\tNONE\t;none found at all?\nDIRECT3\tJZ\tDIRECT9\t;terminate if no more names.\n\tLDA\tRTNCODE\t;get file's position in segment (0-3).\n\tRRC\n\tRRC\n\tRRC\n\tANI\t60H\t;(A)=position*32\n\tMOV\tC,A\n\tMVI\tA,10\n\tCALL\tEXTRACT\t;extract the tenth entry in fcb.\n\tRAL\t\t;check system file status bit.\n\tJC\tDIRECT8\t;we don't list them.\n\tPOP\tD\n\tMOV\tA,E\t;bump name count.\n\tINR\tE\n\tPUSH\tD\n\tANI\t03H\t;at end of line?\n\tPUSH\tPSW\n\tJNZ\tDIRECT4\n\tCALL\tCRLF\t;yes, end this line and start another.\n\tPUSH\tB\n\tCALL\tGETDSK\t;start line with ('A:').\n\tPOP\tB\n\tADI\t'A'\n\tCALL\tPRINTB\n\tMVI\tA,':'\n\tCALL\tPRINTB\n\tJMP\tDIRECT5\nDIRECT4\tCALL\tSPACE\t;add seperator between file names.\n\tMVI\tA,':'\n\tCALL\tPRINTB\nDIRECT5\tCALL\tSPACE\n\tMVI\tB,1\t;'extract' each file name character at a time.\nDIRECT6\tMOV\tA,B\n\tCALL\tEXTRACT\n\tANI\t7FH\t;strip bit 7 (status bit).\n\tCPI\t' '\t;are we at the end of the name?\n\tJNZ\tDRECT65\n\tPOP\tPSW\t;yes, don't print spaces at the end of a line.\n\tPUSH\tPSW\n\tCPI\t3\n\tJNZ\tDRECT63\n\tMVI\tA,9\t;first check for no extension.\n\tCALL\tEXTRACT\n\tANI\t7FH\n\tCPI\t' '\n\tJZ\tDIRECT7\t;don't print spaces.\nDRECT63\tMVI\tA,' '\t;else print them.\nDRECT65\tCALL\tPRINTB\n\tINR\tB\t;bump to next character psoition.\n\tMOV\tA,B\n\tCPI\t12\t;end of the name?\n\tJNC\tDIRECT7\n\tCPI\t9\t;nope, starting extension?\n\tJNZ\tDIRECT6\n\tCALL\tSPACE\t;yes, add seperating space.\n\tJMP\tDIRECT6\nDIRECT7\tPOP\tPSW\t;get the next file name.\nDIRECT8\tCALL\tCHKCON\t;first check console, quit on anything.\n\tJNZ\tDIRECT9\n\tCALL\tSRCHNXT\t;get next name.\n\tJMP\tDIRECT3\t;and continue with our list.\nDIRECT9\tPOP\tD\t;restore the stack and return to command level.\n\tJMP\tGETBACK\n;\n;**************************************************************\n;*\n;*                E R A S E   C O M M A N D\n;*\n;**************************************************************\n;\nERASE\tCALL\tCONVFST\t;convert file name.\n\tCPI\t11\t;was '*.*' entered?\n\tJNZ\tERASE1\n\tLXI\tB,YESNO\t;yes, ask for confirmation.\n\tCALL\tPLINE\n\tCALL\tGETINP\n\tLXI\tH,INBUFF+1\n\tDCR\tM\t;must be exactly 'y'.\n\tJNZ\tCMMND1\n\tINX\tH\n\tMOV\tA,M\n\tCPI\t'Y'\n\tJNZ\tCMMND1\n\tINX\tH\n\tSHLD\tINPOINT\t;save input line pointer.\nERASE1\tCALL\tDSELECT\t;select desired disk.\n\tLXI\tD,FCB\n\tCALL\tDELETE\t;delete the file.\n\tINR\tA\n\tCZ\tNONE\t;not there?\n\tJMP\tGETBACK\t;return to command level now.\nYESNO\tDB\t'All (y/n)?',0\n;\n;**************************************************************\n;*\n;*            T Y P E   C O M M A N D\n;*\n;**************************************************************\n;\nTYPE\tCALL\tCONVFST\t;convert file name.\n\tJNZ\tSYNERR\t;wild cards not allowed.\n\tCALL\tDSELECT\t;select indicated drive.\n\tCALL\tOPENFCB\t;open the file.\n\tJZ\tTYPE5\t;not there?\n\tCALL\tCRLF\t;ok, start a new line on the screen.\n\tLXI\tH,NBYTES;initialize byte counter.\n\tMVI\tM,0FFH\t;set to read first sector.\nTYPE1\tLXI\tH,NBYTES\nTYPE2\tMOV\tA,M\t;have we written the entire sector?\n\tCPI\t128\n\tJC\tTYPE3\n\tPUSH\tH\t;yes, read in the next one.\n\tCALL\tREADFCB\n\tPOP\tH\n\tJNZ\tTYPE4\t;end or error?\n\tXRA\tA\t;ok, clear byte counter.\n\tMOV\tM,A\nTYPE3\tINR\tM\t;count this byte.\n\tLXI\tH,TBUFF\t;and get the (A)th one from the buffer (TBUFF).\n\tCALL\tADDHL\n\tMOV\tA,M\n\tCPI\tCNTRLZ\t;end of file mark?\n\tJZ\tGETBACK\n\tCALL\tPRINT\t;no, print it.\n\tCALL\tCHKCON\t;check console, quit if anything ready.\n\tJNZ\tGETBACK\n\tJMP\tTYPE1\n;\n;   Get here on an end of file or read error.\n;\nTYPE4\tDCR\tA\t;read error?\n\tJZ\tGETBACK\n\tCALL\tRDERROR\t;yes, print message.\nTYPE5\tCALL\tRESETDR\t;and reset proper drive\n\tJMP\tSYNERR\t;now print file name with problem.\n;\n;**************************************************************\n;*\n;*            S A V E   C O M M A N D\n;*\n;**************************************************************\n;\nSAVE\tCALL\tDECODE\t;get numeric number that follows SAVE.\n\tPUSH\tPSW\t;save number of pages to write.\n\tCALL\tCONVFST\t;convert file name.\n\tJNZ\tSYNERR\t;wild cards not allowed.\n\tCALL\tDSELECT\t;select specified drive.\n\tLXI\tD,FCB\t;now delete this file.\n\tPUSH\tD\n\tCALL\tDELETE\n\tPOP\tD\n\tCALL\tCREATE\t;and create it again.\n\tJZ\tSAVE3\t;can't create?\n\tXRA\tA\t;clear record number byte.\n\tSTA\tFCB+32\n\tPOP\tPSW\t;convert pages to sectors.\n\tMOV\tL,A\n\tMVI\tH,0\n\tDAD\tH\t;(HL)=number of sectors to write.\n\tLXI\tD,TBASE\t;and we start from here.\nSAVE1\tMOV\tA,H\t;done yet?\n\tORA\tL\n\tJZ\tSAVE2\n\tDCX\tH\t;nope, count this and compute the start\n\tPUSH\tH\t;of the next 128 byte sector.\n\tLXI\tH,128\n\tDAD\tD\n\tPUSH\tH\t;save it and set the transfer address.\n\tCALL\tDMASET\n\tLXI\tD,FCB\t;write out this sector now.\n\tCALL\tWRTREC\n\tPOP\tD\t;reset (DE) to the start of the last sector.\n\tPOP\tH\t;restore sector count.\n\tJNZ\tSAVE3\t;write error?\n\tJMP\tSAVE1\n;\n;   Get here after writing all of the file.\n;\nSAVE2\tLXI\tD,FCB\t;now close the file.\n\tCALL\tCLOSE\n\tINR\tA\t;did it close ok?\n\tJNZ\tSAVE4\n;\n;   Print out error message (no space).\n;\nSAVE3\tLXI\tB,NOSPACE\n\tCALL\tPLINE\nSAVE4\tCALL\tSTDDMA\t;reset the standard dma address.\n\tJMP\tGETBACK\nNOSPACE\tDB\t'No space',0\n;\n;**************************************************************\n;*\n;*           R E N A M E   C O M M A N D\n;*\n;**************************************************************\n;\nRENAME\tCALL\tCONVFST\t;convert first file name.\n\tJNZ\tSYNERR\t;wild cards not allowed.\n\tLDA\tCHGDRV\t;remember any change in drives specified.\n\tPUSH\tPSW\n\tCALL\tDSELECT\t;and select this drive.\n\tCALL\tSRCHFCB\t;is this file present?\n\tJNZ\tRENAME6\t;yes, print error message.\n\tLXI\tH,FCB\t;yes, move this name into second slot.\n\tLXI\tD,FCB+16\n\tMVI\tB,16\n\tCALL\tHL2DE\n\tLHLD\tINPOINT\t;get input pointer.\n\tXCHG\n\tCALL\tNONBLANK;get next non blank character.\n\tCPI\t'='\t;only allow an '=' or '_' seperator.\n\tJZ\tRENAME1\n\tCPI\t'_'\n\tJNZ\tRENAME5\nRENAME1\tXCHG\n\tINX\tH\t;ok, skip seperator.\n\tSHLD\tINPOINT\t;save input line pointer.\n\tCALL\tCONVFST\t;convert this second file name now.\n\tJNZ\tRENAME5\t;again, no wild cards.\n\tPOP\tPSW\t;if a drive was specified, then it\n\tMOV\tB,A\t;must be the same as before.\n\tLXI\tH,CHGDRV\n\tMOV\tA,M\n\tORA\tA\n\tJZ\tRENAME2\n\tCMP\tB\n\tMOV\tM,B\n\tJNZ\tRENAME5\t;they were different, error.\nRENAME2\tMOV\tM,B;\treset as per the first file specification.\n\tXRA\tA\n\tSTA\tFCB\t;clear the drive byte of the fcb.\nRENAME3\tCALL\tSRCHFCB\t;and go look for second file.\n\tJZ\tRENAME4\t;doesn't exist?\n\tLXI\tD,FCB\n\tCALL\tRENAM\t;ok, rename the file.\n\tJMP\tGETBACK\n;\n;   Process rename errors here.\n;\nRENAME4\tCALL\tNONE\t;file not there.\n\tJMP\tGETBACK\nRENAME5\tCALL\tRESETDR\t;bad command format.\n\tJMP\tSYNERR\nRENAME6\tLXI\tB,EXISTS;destination file already exists.\n\tCALL\tPLINE\n\tJMP\tGETBACK\nEXISTS\tDB\t'File exists',0\n;\n;**************************************************************\n;*\n;*             U S E R   C O M M A N D\n;*\n;**************************************************************\n;\nUSER\tCALL\tDECODE\t;get numeric value following command.\n\tCPI\t16\t;legal user number?\n\tJNC\tSYNERR\n\tMOV\tE,A\t;yes but is there anything else?\n\tLDA\tFCB+1\n\tCPI\t' '\n\tJZ\tSYNERR\t;yes, that is not allowed.\n\tCALL\tGETSETUC;ok, set user code.\n\tJMP\tGETBACK1\n;\n;**************************************************************\n;*\n;*        T R A N S I A N T   P R O G R A M   C O M M A N D\n;*\n;**************************************************************\n;\nUNKNOWN\tCALL\tVERIFY\t;check for valid system (why?).\n\tLDA\tFCB+1\t;anything to execute?\n\tCPI\t' '\n\tJNZ\tUNKWN1\n\tLDA\tCHGDRV\t;nope, only a drive change?\n\tORA\tA\n\tJZ\tGETBACK1;neither???\n\tDCR\tA\n\tSTA\tCDRIVE\t;ok, store new drive.\n\tCALL\tMOVECD\t;set (TDRIVE) also.\n\tCALL\tDSKSEL\t;and select this drive.\n\tJMP\tGETBACK1;then return.\n;\n;   Here a file name was typed. Prepare to execute it.\n;\nUNKWN1\tLXI\tD,FCB+9\t;an extension specified?\n\tLDAX\tD\n\tCPI\t' '\n\tJNZ\tSYNERR\t;yes, not allowed.\nUNKWN2\tPUSH\tD\n\tCALL\tDSELECT\t;select specified drive.\n\tPOP\tD\n\tLXI\tH,COMFILE\t;set the extension to 'COM'.\n\tCALL\tMOVE3\n\tCALL\tOPENFCB\t;and open this file.\n\tJZ\tUNKWN9\t;not present?\n;\n;   Load in the program.\n;\n\tLXI\tH,TBASE\t;store the program starting here.\nUNKWN3\tPUSH\tH\n\tXCHG\n\tCALL\tDMASET\t;set transfer address.\n\tLXI\tD,FCB\t;and read the next record.\n\tCALL\tRDREC\n\tJNZ\tUNKWN4\t;end of file or read error?\n\tPOP\tH\t;nope, bump pointer for next sector.\n\tLXI\tD,128\n\tDAD\tD\n\tLXI\tD,CBASE\t;enough room for the whole file?\n\tMOV\tA,L\n\tSUB\tE\n\tMOV\tA,H\n\tSBB\tD\n\tJNC\tUNKWN0\t;no, it can't fit.\n\tJMP\tUNKWN3\n;\n;   Get here after finished reading.\n;\nUNKWN4\tPOP\tH\n\tDCR\tA\t;normal end of file?\n\tJNZ\tUNKWN0\n\tCALL\tRESETDR\t;yes, reset previous drive.\n\tCALL\tCONVFST\t;convert the first file name that follows\n\tLXI\tH,CHGDRV;command name.\n\tPUSH\tH\n\tMOV\tA,M\t;set drive code in default fcb.\n\tSTA\tFCB\n\tMVI\tA,16\t;put second name 16 bytes later.\n\tCALL\tCONVERT\t;convert second file name.\n\tPOP\tH\n\tMOV\tA,M\t;and set the drive for this second file.\n\tSTA\tFCB+16\n\tXRA\tA\t;clear record byte in fcb.\n\tSTA\tFCB+32\n\tLXI\tD,TFCB\t;move it into place at(005Ch).\n\tLXI\tH,FCB\n\tMVI\tB,33\n\tCALL\tHL2DE\n\tLXI\tH,INBUFF+2;now move the remainder of the input\nUNKWN5\tMOV\tA,M\t;line down to (0080h). Look for a non blank.\n\tORA\tA\t;or a null.\n\tJZ\tUNKWN6\n\tCPI\t' '\n\tJZ\tUNKWN6\n\tINX\tH\n\tJMP\tUNKWN5\n;\n;   Do the line move now. It ends in a null byte.\n;\nUNKWN6\tMVI\tB,0\t;keep a character count.\n\tLXI\tD,TBUFF+1;data gets put here.\nUNKWN7\tMOV\tA,M\t;move it now.\n\tSTAX\tD\n\tORA\tA\n\tJZ\tUNKWN8\n\tINR\tB\n\tINX\tH\n\tINX\tD\n\tJMP\tUNKWN7\nUNKWN8\tMOV\tA,B\t;now store the character count.\n\tSTA\tTBUFF\n\tCALL\tCRLF\t;clean up the screen.\n\tCALL\tSTDDMA\t;set standard transfer address.\n\tCALL\tSETCDRV\t;reset current drive.\n\tCALL\tTBASE\t;and execute the program.\n;\n;   Transiant programs return here (or reboot).\n;\n\tLXI\tSP,BATCH\t;set stack first off.\n\tCALL\tMOVECD\t;move current drive into place (TDRIVE).\n\tCALL\tDSKSEL\t;and reselect it.\n\tJMP\tCMMND1\t;back to comand mode.\n;\n;   Get here if some error occured.\n;\nUNKWN9\tCALL\tRESETDR\t;inproper format.\n\tJMP\tSYNERR\nUNKWN0\tLXI\tB,BADLOAD;read error or won't fit.\n\tCALL\tPLINE\n\tJMP\tGETBACK\nBADLOAD\tDB\t'Bad load',0\nCOMFILE\tDB\t'COM'\t;command file extension.\n;\n;   Get here to return to command level. We will reset the\n; previous active drive and then either return to command\n; level directly or print error message and then return.\n;\nGETBACK\tCALL\tRESETDR\t;reset previous drive.\nGETBACK1:CALL\tCONVFST\t;convert first name in (FCB).\n\tLDA\tFCB+1\t;if this was just a drive change request,\n\tSUI\t' '\t;make sure it was valid.\n\tLXI\tH,CHGDRV\n\tORA\tM\n\tJNZ\tSYNERR\n\tJMP\tCMMND1\t;ok, return to command level.\n;\n;   ccp stack area.\n;\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nCCPSTACK:EQU\t$\t;end of ccp stack area.\n;\n;   Batch (or SUBMIT) processing information storage.\n;\nBATCH\tDB\t0\t;batch mode flag (0=not active).\nBATCHFCB:DB\t0,'$$$     SUB',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n;\n;   File control block setup by the CCP.\n;\nFCB\tDB\t0,'           ',0,0,0,0,0,'           ',0,0,0,0,0\nRTNCODE\tDB\t0\t;status returned from bdos call.\nCDRIVE\tDB\t0\t;currently active drive.\nCHGDRV\tDB\t0\t;change in drives flag (0=no change).\nNBYTES\tDW\t0\t;byte counter used by TYPE.\n;\n;   Room for expansion?\n;\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0\n;\n;   Note that the following six bytes must match those at\n; (PATTRN1) or cp/m will HALT. Why?\n;\nPATTRN2\tDB\t0,22,0,0,0,0;(* serial number bytes *).\n;\n;**************************************************************\n;*\n;*                    B D O S   E N T R Y\n;*\n;**************************************************************\n;\nFBASE\tJMP\tFBASE1\n;\n;   Bdos error table.\n;\nBADSCTR\tDW\tERROR1\t;bad sector on read or write.\nBADSLCT\tDW\tERROR2\t;bad disk select.\nRODISK\tDW\tERROR3\t;disk is read only.\nROFILE\tDW\tERROR4\t;file is read only.\n;\n;   Entry into bdos. (DE) or (E) are the parameters passed. The\n; function number desired is in register (C).\n;\nFBASE1\tXCHG\t\t;save the (DE) parameters.\n\tSHLD\tPARAMS\n\tXCHG\n\tMOV\tA,E\t;and save register (E) in particular.\n\tSTA\tEPARAM\n\tLXI\tH,0\n\tSHLD\tSTATUS\t;clear return status.\n\tDAD\tSP\n\tSHLD\tUSRSTACK;save users stack pointer.\n\tLXI\tSP,STKAREA;and set our own.\n\tXRA\tA\t;clear auto select storage space.\n\tSTA\tAUTOFLAG\n\tSTA\tAUTO\n\tLXI\tH,GOBACK;set return address.\n\tPUSH\tH\n\tMOV\tA,C\t;get function number.\n\tCPI\tNFUNCTS\t;valid function number?\n\tRNC\n\tMOV\tC,E\t;keep single register function here.\n\tLXI\tH,FUNCTNS;now look thru the function table.\n\tMOV\tE,A\n\tMVI\tD,0\t;(DE)=function number.\n\tDAD\tD\n\tDAD\tD\t;(HL)=(start of table)+2*(function number).\n\tMOV\tE,M\n\tINX\tH\n\tMOV\tD,M\t;now (DE)=address for this function.\n\tLHLD\tPARAMS\t;retrieve parameters.\n\tXCHG\t\t;now (DE) has the original parameters.\n\tPCHL\t\t;execute desired function.\n;\n;   BDOS function jump table.\n;\nNFUNCTS\tEQU\t41\t;number of functions in followin table.\n;\nFUNCTNS\tDW\tWBOOT,GETCON,OUTCON,GETRDR,PUNCH,LIST,DIRCIO,GETIOB\n\tDW\tSETIOB,PRTSTR,RDBUFF,GETCSTS,GETVER,RSTDSK,SETDSK,OPENFIL\n\tDW\tCLOSEFIL,GETFST,GETNXT,DELFILE,READSEQ,WRTSEQ,FCREATE\n\tDW\tRENFILE,GETLOG,GETCRNT,PUTDMA,GETALOC,WRTPRTD,GETROV,SETATTR\n\tDW\tGETPARM,GETUSER,RDRANDOM,WTRANDOM,FILESIZE,SETRAN,LOGOFF,RTN\n\tDW\tRTN,WTSPECL\n;\n;   Bdos error message section.\n;\nERROR1\tLXI\tH,BADSEC\t;bad sector message.\n\tCALL\tPRTERR\t;print it and get a 1 char responce.\n\tCPI\tCNTRLC\t;re-boot request (control-c)?\n\tJZ\t0\t;yes.\n\tRET\t\t;no, return to retry i/o function.\n;\nERROR2\tLXI\tH,BADSEL\t;bad drive selected.\n\tJMP\tERROR5\n;\nERROR3\tLXI\tH,DISKRO\t;disk is read only.\n\tJMP\tERROR5\n;\nERROR4\tLXI\tH,FILERO\t;file is read only.\n;\nERROR5\tCALL\tPRTERR\n\tJMP\t0\t;always reboot on these errors.\n;\nBDOSERR\tDB\t'Bdos Err On '\nBDOSDRV\tDB\t' : $'\nBADSEC\tDB\t'Bad Sector$'\nBADSEL\tDB\t'Select$'\nFILERO\tDB\t'File '\nDISKRO\tDB\t'R/O$'\n;\n;   Print bdos error message.\n;\nPRTERR\tPUSH\tH\t;save second message pointer.\n\tCALL\tOUTCRLF\t;send (cr)(lf).\n\tLDA\tACTIVE\t;get active drive.\n\tADI\t'A'\t;make ascii.\n\tSTA\tBDOSDRV\t;and put in message.\n\tLXI\tB,BDOSERR;and print it.\n\tCALL\tPRTMESG\n\tPOP\tB\t;print second message line now.\n\tCALL\tPRTMESG\n;\n;   Get an input character. We will check our 1 character\n; buffer first. This may be set by the console status routine.\n;\nGETCHAR\tLXI\tH,CHARBUF;check character buffer.\n\tMOV\tA,M\t;anything present already?\n\tMVI\tM,0\t;...either case clear it.\n\tORA\tA\n\tRNZ\t\t;yes, use it.\n\tJMP\tCONIN\t;nope, go get a character responce.\n;\n;   Input and echo a character.\n;\nGETECHO\tCALL\tGETCHAR\t;input a character.\n\tCALL\tCHKCHAR\t;carriage control?\n\tRC\t\t;no, a regular control char so don't echo.\n\tPUSH\tPSW\t;ok, save character now.\n\tMOV\tC,A\n\tCALL\tOUTCON\t;and echo it.\n\tPOP\tPSW\t;get character and return.\n\tRET\n;\n;   Check character in (A). Set the zero flag on a carriage\n; control character and the carry flag on any other control\n; character.\n;\nCHKCHAR\tCPI\tCR\t;check for carriage return, line feed, backspace,\n\tRZ\t\t;or a tab.\n\tCPI\tLF\n\tRZ\n\tCPI\tTAB\n\tRZ\n\tCPI\tBS\n\tRZ\n\tCPI\t' '\t;other control char? Set carry flag.\n\tRET\n;\n;   Check the console during output. Halt on a control-s, then\n; reboot on a control-c. If anything else is ready, clear the\n; zero flag and return (the calling routine may want to do\n; something).\n;\nCKCONSOL:LDA\tCHARBUF\t;check buffer.\n\tORA\tA\t;if anything, just return without checking.\n\tJNZ\tCKCON2\n\tCALL\tCONST\t;nothing in buffer. Check console.\n\tANI\t01H\t;look at bit 0.\n\tRZ\t\t;return if nothing.\n\tCALL\tCONIN\t;ok, get it.\n\tCPI\tCNTRLS\t;if not control-s, return with zero cleared.\n\tJNZ\tCKCON1\n\tCALL\tCONIN\t;halt processing until another char\n\tCPI\tCNTRLC\t;is typed. Control-c?\n\tJZ\t0\t;yes, reboot now.\n\tXRA\tA\t;no, just pretend nothing was ever ready.\n\tRET\nCKCON1\tSTA\tCHARBUF\t;save character in buffer for later processing.\nCKCON2\tMVI\tA,1\t;set (A) to non zero to mean something is ready.\n\tRET\n;\n;   Output (C) to the screen. If the printer flip-flop flag\n; is set, we will send character to printer also. The console\n; will be checked in the process.\n;\nOUTCHAR\tLDA\tOUTFLAG\t;check output flag.\n\tORA\tA\t;anything and we won't generate output.\n\tJNZ\tOUTCHR1\n\tPUSH\tB\n\tCALL\tCKCONSOL;check console (we don't care whats there).\n\tPOP\tB\n\tPUSH\tB\n\tCALL\tCONOUT\t;output (C) to the screen.\n\tPOP\tB\n\tPUSH\tB\n\tLDA\tPRTFLAG\t;check printer flip-flop flag.\n\tORA\tA\n\tCNZ\tLIST\t;print it also if non-zero.\n\tPOP\tB\nOUTCHR1\tMOV\tA,C\t;update cursors position.\n\tLXI\tH,CURPOS\n\tCPI\tDEL\t;rubouts don't do anything here.\n\tRZ\n\tINR\tM\t;bump line pointer.\n\tCPI\t' '\t;and return if a normal character.\n\tRNC\n\tDCR\tM\t;restore and check for the start of the line.\n\tMOV\tA,M\n\tORA\tA\n\tRZ\t\t;ingnore control characters at the start of the line.\n\tMOV\tA,C\n\tCPI\tBS\t;is it a backspace?\n\tJNZ\tOUTCHR2\n\tDCR\tM\t;yes, backup pointer.\n\tRET\nOUTCHR2\tCPI\tLF\t;is it a line feed?\n\tRNZ\t\t;ignore anything else.\n\tMVI\tM,0\t;reset pointer to start of line.\n\tRET\n;\n;   Output (A) to the screen. If it is a control character\n; (other than carriage control), use ^x format.\n;\nSHOWIT\tMOV\tA,C\n\tCALL\tCHKCHAR\t;check character.\n\tJNC\tOUTCON\t;not a control, use normal output.\n\tPUSH\tPSW\n\tMVI\tC,'^'\t;for a control character, preceed it with '^'.\n\tCALL\tOUTCHAR\n\tPOP\tPSW\n\tORI\t'@'\t;and then use the letter equivelant.\n\tMOV\tC,A\n;\n;   Function to output (C) to the console device and expand tabs\n; if necessary.\n;\nOUTCON\tMOV\tA,C\n\tCPI\tTAB\t;is it a tab?\n\tJNZ\tOUTCHAR\t;use regular output.\nOUTCON1\tMVI\tC,' '\t;yes it is, use spaces instead.\n\tCALL\tOUTCHAR\n\tLDA\tCURPOS\t;go until the cursor is at a multiple of 8\n\n\tANI\t07H\t;position.\n\tJNZ\tOUTCON1\n\tRET\n;\n;   Echo a backspace character. Erase the prevoius character\n; on the screen.\n;\nBACKUP\tCALL\tBACKUP1\t;backup the screen 1 place.\n\tMVI\tC,' '\t;then blank that character.\n\tCALL\tCONOUT\nBACKUP1\tMVI\tC,BS\t;then back space once more.\n\tJMP\tCONOUT\n;\n;   Signal a deleted line. Print a '#' at the end and start\n; over.\n;\nNEWLINE\tMVI\tC,'#'\n\tCALL\tOUTCHAR\t;print this.\n\tCALL\tOUTCRLF\t;start new line.\nNEWLN1\tLDA\tCURPOS\t;move the cursor to the starting position.\n\tLXI\tH,STARTING\n\tCMP\tM\n\tRNC\t\t;there yet?\n\tMVI\tC,' '\n\tCALL\tOUTCHAR\t;nope, keep going.\n\tJMP\tNEWLN1\n;\n;   Output a (cr) (lf) to the console device (screen).\n;\nOUTCRLF\tMVI\tC,CR\n\tCALL\tOUTCHAR\n\tMVI\tC,LF\n\tJMP\tOUTCHAR\n;\n;   Print message pointed to by (BC). It will end with a '$'.\n;\nPRTMESG\tLDAX\tB\t;check for terminating character.\n\tCPI\t'$'\n\tRZ\n\tINX\tB\n\tPUSH\tB\t;otherwise, bump pointer and print it.\n\tMOV\tC,A\n\tCALL\tOUTCON\n\tPOP\tB\n\tJMP\tPRTMESG\n;\n;   Function to execute a buffered read.\n;\nRDBUFF\tLDA\tCURPOS\t;use present location as starting one.\n\tSTA\tSTARTING\n\tLHLD\tPARAMS\t;get the maximum buffer space.\n\tMOV\tC,M\n\tINX\tH\t;point to first available space.\n\tPUSH\tH\t;and save.\n\tMVI\tB,0\t;keep a character count.\nRDBUF1\tPUSH\tB\n\tPUSH\tH\nRDBUF2\tCALL\tGETCHAR\t;get the next input character.\n\tANI\t7FH\t;strip bit 7.\n\tPOP\tH\t;reset registers.\n\tPOP\tB\n\tCPI\tCR\t;en of the line?\n\tJZ\tRDBUF17\n\tCPI\tLF\n\tJZ\tRDBUF17\n\tCPI\tBS\t;how about a backspace?\n\tJNZ\tRDBUF3\n\tMOV\tA,B\t;yes, but ignore at the beginning of the line.\n\tORA\tA\n\tJZ\tRDBUF1\n\tDCR\tB\t;ok, update counter.\n\tLDA\tCURPOS\t;if we backspace to the start of the line,\n\tSTA\tOUTFLAG\t;treat as a cancel (control-x).\n\tJMP\tRDBUF10\nRDBUF3\tCPI\tDEL\t;user typed a rubout?\n\tJNZ\tRDBUF4\n\tMOV\tA,B\t;ignore at the start of the line.\n\tORA\tA\n\tJZ\tRDBUF1\n\tMOV\tA,M\t;ok, echo the prevoius character.\n\tDCR\tB\t;and reset pointers (counters).\n\tDCX\tH\n\tJMP\tRDBUF15\nRDBUF4\tCPI\tCNTRLE\t;physical end of line?\n\tJNZ\tRDBUF5\n\tPUSH\tB\t;yes, do it.\n\tPUSH\tH\n\tCALL\tOUTCRLF\n\tXRA\tA\t;and update starting position.\n\tSTA\tSTARTING\n\tJMP\tRDBUF2\nRDBUF5\tCPI\tCNTRLP\t;control-p?\n\tJNZ\tRDBUF6\n\tPUSH\tH\t;yes, flip the print flag filp-flop byte.\n\tLXI\tH,PRTFLAG\n\tMVI\tA,1\t;PRTFLAG=1-PRTFLAG\n\tSUB\tM\n\tMOV\tM,A\n\tPOP\tH\n\tJMP\tRDBUF1\nRDBUF6\tCPI\tCNTRLX\t;control-x (cancel)?\n\tJNZ\tRDBUF8\n\tPOP\tH\nRDBUF7\tLDA\tSTARTING;yes, backup the cursor to here.\n\tLXI\tH,CURPOS\n\tCMP\tM\n\tJNC\tRDBUFF\t;done yet?\n\tDCR\tM\t;no, decrement pointer and output back up one space.\n\tCALL\tBACKUP\n\tJMP\tRDBUF7\nRDBUF8\tCPI\tCNTRLU\t;cntrol-u (cancel line)?\n\tJNZ\tRDBUF9\n\tCALL\tNEWLINE\t;start a new line.\n\tPOP\tH\n\tJMP\tRDBUFF\nRDBUF9\tCPI\tCNTRLR\t;control-r?\n\tJNZ\tRDBUF14\nRDBUF10\tPUSH\tB\t;yes, start a new line and retype the old one.\n\tCALL\tNEWLINE\n\tPOP\tB\n\tPOP\tH\n\tPUSH\tH\n\tPUSH\tB\nRDBUF11\tMOV\tA,B\t;done whole line yet?\n\tORA\tA\n\tJZ\tRDBUF12\n\tINX\tH\t;nope, get next character.\n\tMOV\tC,M\n\tDCR\tB\t;count it.\n\tPUSH\tB\n\tPUSH\tH\n\tCALL\tSHOWIT\t;and display it.\n\tPOP\tH\n\tPOP\tB\n\tJMP\tRDBUF11\nRDBUF12\tPUSH\tH\t;done with line. If we were displaying\n\tLDA\tOUTFLAG\t;then update cursor position.\n\tORA\tA\n\tJZ\tRDBUF2\n\tLXI\tH,CURPOS;because this line is shorter, we must\n\tSUB\tM\t;back up the cursor (not the screen however)\n\tSTA\tOUTFLAG\t;some number of positions.\nRDBUF13\tCALL\tBACKUP\t;note that as long as (OUTFLAG) is non\n\tLXI\tH,OUTFLAG;zero, the screen will not be changed.\n\tDCR\tM\n\tJNZ\tRDBUF13\n\tJMP\tRDBUF2\t;now just get the next character.\n;\n;   Just a normal character, put this in our buffer and echo.\n;\nRDBUF14\tINX\tH\n\tMOV\tM,A\t;store character.\n\tINR\tB\t;and count it.\nRDBUF15\tPUSH\tB\n\tPUSH\tH\n\tMOV\tC,A\t;echo it now.\n\tCALL\tSHOWIT\n\tPOP\tH\n\tPOP\tB\n\tMOV\tA,M\t;was it an abort request?\n\tCPI\tCNTRLC\t;control-c abort?\n\tMOV\tA,B\n\tJNZ\tRDBUF16\n\tCPI\t1\t;only if at start of line.\n\tJZ\t0\nRDBUF16\tCMP\tC\t;nope, have we filled the buffer?\n\tJC\tRDBUF1\nRDBUF17\tPOP\tH\t;yes end the line and return.\n\tMOV\tM,B\n\tMVI\tC,CR\n\tJMP\tOUTCHAR\t;output (cr) and return.\n;\n;   Function to get a character from the console device.\n;\nGETCON\tCALL\tGETECHO\t;get and echo.\n\tJMP\tSETSTAT\t;save status and return.\n;\n;   Function to get a character from the tape reader device.\n;\nGETRDR\tCALL\tREADER\t;get a character from reader, set status and return.\n\tJMP\tSETSTAT\n;\n;  Function to perform direct console i/o. If (C) contains (FF)\n; then this is an input request. If (C) contains (FE) then\n; this is a status request. Otherwise we are to output (C).\n;\nDIRCIO\tMOV\tA,C\t;test for (FF).\n\tINR\tA\n\tJZ\tDIRC1\n\tINR\tA\t;test for (FE).\n\tJZ\tCONST\n\tJMP\tCONOUT\t;just output (C).\nDIRC1\tCALL\tCONST\t;this is an input request.\n\tORA\tA\n\tJZ\tGOBACK1\t;not ready? Just return (directly).\n\tCALL\tCONIN\t;yes, get character.\n\tJMP\tSETSTAT\t;set status and return.\n;\n;   Function to return the i/o byte.\n;\nGETIOB\tLDA\tIOBYTE\n\tJMP\tSETSTAT\n;\n;   Function to set the i/o byte.\n;\nSETIOB\tLXI\tH,IOBYTE\n\tMOV\tM,C\n\tRET\n;\n;   Function to print the character string pointed to by (DE)\n; on the console device. The string ends with a '$'.\n;\nPRTSTR\tXCHG\n\tMOV\tC,L\n\tMOV\tB,H\t;now (BC) points to it.\n\tJMP\tPRTMESG\n;\n;   Function to interigate the console device.\n;\nGETCSTS\tCALL\tCKCONSOL\n;\n;   Get here to set the status and return to the cleanup\n; section. Then back to the user.\n;\nSETSTAT\tSTA\tSTATUS\nRTN\tRET\n;\n;   Set the status to 1 (read or write error code).\n;\nIOERR1\tMVI\tA,1\n\tJMP\tSETSTAT\n;\nOUTFLAG\tDB\t0\t;output flag (non zero means no output).\nSTARTING:DB\t2\t;starting position for cursor.\nCURPOS\tDB\t0\t;cursor position (0=start of line).\nPRTFLAG\tDB\t0\t;printer flag (control-p toggle). List if non zero.\nCHARBUF\tDB\t0\t;single input character buffer.\n;\n;   Stack area for BDOS calls.\n;\nUSRSTACK:DW\t0\t;save users stack pointer here.\n;\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n\tDB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\nSTKAREA\tEQU\t$\t;end of stack area.\n;\nUSERNO\tDB\t0\t;current user number.\nACTIVE\tDB\t0\t;currently active drive.\nPARAMS\tDW\t0\t;save (DE) parameters here on entry.\nSTATUS\tDW\t0\t;status returned from bdos function.\n;\n;   Select error occured, jump to error routine.\n;\nSLCTERR\tLXI\tH,BADSLCT\n;\n;   Jump to (HL) indirectly.\n;\nJUMPHL\tMOV\tE,M\n\tINX\tH\n\tMOV\tD,M\t;now (DE) contain the desired address.\n\tXCHG\n\tPCHL\n;\n;   Block move. (DE) to (HL), (C) bytes total.\n;\nDE2HL\tINR\tC\t;is count down to zero?\nDE2HL1\tDCR\tC\n\tRZ\t\t;yes, we are done.\n\tLDAX\tD\t;no, move one more byte.\n\tMOV\tM,A\n\tINX\tD\n\tINX\tH\n\tJMP\tDE2HL1\t;and repeat.\n;\n;   Select the desired drive.\n;\nSELECT\tLDA\tACTIVE\t;get active disk.\n\tMOV\tC,A\n\tCALL\tSELDSK\t;select it.\n\tMOV\tA,H\t;valid drive?\n\tORA\tL\t;valid drive?\n\tRZ\t\t;return if not.\n;\n;   Here, the BIOS returned the address of the parameter block\n; in (HL). We will extract the necessary pointers and save them.\n;\n\tMOV\tE,M\t;yes, get address of translation table into (DE).\n\tINX\tH\n\tMOV\tD,M\n\tINX\tH\n\tSHLD\tSCRATCH1\t;save pointers to scratch areas.\n\tINX\tH\n\tINX\tH\n\tSHLD\tSCRATCH2\t;ditto.\n\tINX\tH\n\tINX\tH\n\tSHLD\tSCRATCH3\t;ditto.\n\tINX\tH\n\tINX\tH\n\tXCHG\t\t;now save the translation table address.\n\tSHLD\tXLATE\n\tLXI\tH,DIRBUF\t;put the next 8 bytes here.\n\tMVI\tC,8\t;they consist of the directory buffer\n\tCALL\tDE2HL\t;pointer, parameter block pointer,\n\tLHLD\tDISKPB\t;check and allocation vectors.\n\tXCHG\n\tLXI\tH,SECTORS\t;move parameter block into our ram.\n\tMVI\tC,15\t;it is 15 bytes long.\n\tCALL\tDE2HL\n\tLHLD\tDSKSIZE\t;check disk size.\n\tMOV\tA,H\t;more than 256 blocks on this?\n\tLXI\tH,BIGDISK\n\tMVI\tM,0FFH\t;set to samll.\n\tORA\tA\n\tJZ\tSELECT1\n\tMVI\tM,0\t;wrong, set to large.\nSELECT1\tMVI\tA,0FFH\t;clear the zero flag.\n\tORA\tA\n\tRET\n;\n;   Routine to home the disk track head and clear pointers.\n;\nHOMEDRV\tCALL\tHOME\t;home the head.\n\tXRA\tA\n\tLHLD\tSCRATCH2;set our track pointer also.\n\tMOV\tM,A\n\tINX\tH\n\tMOV\tM,A\n\tLHLD\tSCRATCH3;and our sector pointer.\n\tMOV\tM,A\n\tINX\tH\n\tMOV\tM,A\n\tRET\n;\n;   Do the actual disk read and check the error return status.\n;\nDOREAD\tCALL\tREAD\n\tJMP\tIORET\n;\n;   Do the actual disk write and handle any bios error.\n;\nDOWRITE\tCALL\tWRITE\nIORET\tORA\tA\n\tRZ\t\t;return unless an error occured.\n\tLXI\tH,BADSCTR;bad read/write on this sector.\n\tJMP\tJUMPHL\n;\n;   Routine to select the track and sector that the desired\n; block number falls in.\n;\nTRKSEC\tLHLD\tFILEPOS\t;get position of last accessed file\n\tMVI\tC,2\t;in directory and compute sector #.\n\tCALL\tSHIFTR\t;sector #=file-position/4.\n\tSHLD\tBLKNMBR\t;save this as the block number of interest.\n\tSHLD\tCKSUMTBL;what's it doing here too?\n;\n;   if the sector number has already been set (BLKNMBR), enter\n; at this point.\n;\nTRKSEC1\tLXI\tH,BLKNMBR\n\tMOV\tC,M\t;move sector number into (BC).\n\tINX\tH\n\tMOV\tB,M\n\tLHLD\tSCRATCH3;get current sector number and\n\tMOV\tE,M\t;move this into (DE).\n\tINX\tH\n\tMOV\tD,M\n\tLHLD\tSCRATCH2;get current track number.\n\tMOV\tA,M\t;and this into (HL).\n\tINX\tH\n\tMOV\tH,M\n\tMOV\tL,A\nTRKSEC2\tMOV\tA,C\t;is desired sector before current one?\n\tSUB\tE\n\tMOV\tA,B\n\tSBB\tD\n\tJNC\tTRKSEC3\n\tPUSH\tH\t;yes, decrement sectors by one track.\n\tLHLD\tSECTORS\t;get sectors per track.\n\tMOV\tA,E\n\tSUB\tL\n\tMOV\tE,A\n\tMOV\tA,D\n\tSBB\tH\n\tMOV\tD,A\t;now we have backed up one full track.\n\tPOP\tH\n\tDCX\tH\t;adjust track counter.\n\tJMP\tTRKSEC2\nTRKSEC3\tPUSH\tH\t;desired sector is after current one.\n\tLHLD\tSECTORS\t;get sectors per track.\n\tDAD\tD\t;bump sector pointer to next track.\n\tJC\tTRKSEC4\n\tMOV\tA,C\t;is desired sector now before current one?\n\tSUB\tL\n\tMOV\tA,B\n\tSBB\tH\n\tJC\tTRKSEC4\n\tXCHG\t\t;not yes, increment track counter\n\tPOP\tH\t;and continue until it is.\n\tINX\tH\n\tJMP\tTRKSEC3\n;\n;   here we have determined the track number that contains the\n; desired sector.\n;\nTRKSEC4\tPOP\tH\t;get track number (HL).\n\tPUSH\tB\n\tPUSH\tD\n\tPUSH\tH\n\tXCHG\n\tLHLD\tOFFSET\t;adjust for first track offset.\n\tDAD\tD\n\tMOV\tB,H\n\tMOV\tC,L\n\tCALL\tSETTRK\t;select this track.\n\tPOP\tD\t;reset current track pointer.\n\tLHLD\tSCRATCH2\n\tMOV\tM,E\n\tINX\tH\n\tMOV\tM,D\n\tPOP\tD\n\tLHLD\tSCRATCH3;reset the first sector on this track.\n\tMOV\tM,E\n\tINX\tH\n\tMOV\tM,D\n\tPOP\tB\n\tMOV\tA,C\t;now subtract the desired one.\n\tSUB\tE\t;to make it relative (1-# sectors/track).\n\tMOV\tC,A\n\tMOV\tA,B\n\tSBB\tD\n\tMOV\tB,A\n\tLHLD\tXLATE\t;translate this sector according to this table.\n\tXCHG\n\tCALL\tSECTRN\t;let the bios translate it.\n\tMOV\tC,L\n\tMOV\tB,H\n\tJMP\tSETSEC\t;and select it.\n;\n;   Compute block number from record number (SAVNREC) and\n; extent number (SAVEXT).\n;\nGETBLOCK:LXI\tH,BLKSHFT;get logical to physical conversion.\n\tMOV\tC,M\t;note that this is base 2 log of ratio.\n\tLDA\tSAVNREC\t;get record number.\nGETBLK1\tORA\tA\t;compute (A)=(A)/2^BLKSHFT.\n\tRAR\n\tDCR\tC\n\tJNZ\tGETBLK1\n\tMOV\tB,A\t;save result in (B).\n\tMVI\tA,8\n\tSUB\tM\n\tMOV\tC,A\t;compute (C)=8-BLKSHFT.\n\tLDA\tSAVEXT\nGETBLK2\tDCR\tC\t;compute (A)=SAVEXT*2^(8-BLKSHFT).\n\tJZ\tGETBLK3\n\tORA\tA\n\tRAL\n\tJMP\tGETBLK2\nGETBLK3\tADD\tB\n\tRET\n;\n;   Routine to extract the (BC) block byte from the fcb pointed\n; to by (PARAMS). If this is a big-disk, then these are 16 bit\n; block numbers, else they are 8 bit numbers.\n; Number is returned in (HL).\n;\nEXTBLK\tLHLD\tPARAMS\t;get fcb address.\n\tLXI\tD,16\t;block numbers start 16 bytes into fcb.\n\tDAD\tD\n\tDAD\tB\n\tLDA\tBIGDISK\t;are we using a big-disk?\n\tORA\tA\n\tJZ\tEXTBLK1\n\tMOV\tL,M\t;no, extract an 8 bit number from the fcb.\n\tMVI\tH,0\n\tRET\nEXTBLK1\tDAD\tB\t;yes, extract a 16 bit number.\n\tMOV\tE,M\n\tINX\tH\n\tMOV\tD,M\n\tXCHG\t\t;return in (HL).\n\tRET\n;\n;   Compute block number.\n;\nCOMBLK\tCALL\tGETBLOCK\n\tMOV\tC,A\n\tMVI\tB,0\n\tCALL\tEXTBLK\n\tSHLD\tBLKNMBR\n\tRET\n;\n;   Check for a zero block number (unused).\n;\nCHKBLK\tLHLD\tBLKNMBR\n\tMOV\tA,L\t;is it zero?\n\tORA\tH\n\tRET\n;\n;   Adjust physical block (BLKNMBR) and convert to logical\n; sector (LOGSECT). This is the starting sector of this block.\n; The actual sector of interest is then added to this and the\n; resulting sector number is stored back in (BLKNMBR). This\n; will still have to be adjusted for the track number.\n;\nLOGICAL\tLDA\tBLKSHFT\t;get log2(physical/logical sectors).\n\tLHLD\tBLKNMBR\t;get physical sector desired.\nLOGICL1\tDAD\tH\t;compute logical sector number.\n\tDCR\tA\t;note logical sectors are 128 bytes long.\n\tJNZ\tLOGICL1\n\tSHLD\tLOGSECT\t;save logical sector.\n\tLDA\tBLKMASK\t;get block mask.\n\tMOV\tC,A\n\tLDA\tSAVNREC\t;get next sector to access.\n\tANA\tC\t;extract the relative position within physical block.\n\tORA\tL\t;and add it too logical sector.\n\tMOV\tL,A\n\tSHLD\tBLKNMBR\t;and store.\n\tRET\n;\n;   Set (HL) to point to extent byte in fcb.\n;\nSETEXT\tLHLD\tPARAMS\n\tLXI\tD,12\t;it is the twelth byte.\n\tDAD\tD\n\tRET\n;\n;   Set (HL) to point to record count byte in fcb and (DE) to\n; next record number byte.\n;\nSETHLDE\tLHLD\tPARAMS\n\tLXI\tD,15\t;record count byte (#15).\n\tDAD\tD\n\tXCHG\n\tLXI\tH,17\t;next record number (#32).\n\tDAD\tD\n\tRET\n;\n;   Save current file data from fcb.\n;\nSTRDATA\tCALL\tSETHLDE\n\tMOV\tA,M\t;get and store record count byte.\n\tSTA\tSAVNREC\n\tXCHG\n\tMOV\tA,M\t;get and store next record number byte.\n\tSTA\tSAVNXT\n\tCALL\tSETEXT\t;point to extent byte.\n\tLDA\tEXTMASK\t;get extent mask.\n\tANA\tM\n\tSTA\tSAVEXT\t;and save extent here.\n\tRET\n;\n;   Set the next record to access. If (MODE) is set to 2, then\n; the last record byte (SAVNREC) has the correct number to access.\n; For sequential access, (MODE) will be equal to 1.\n;\nSETNREC\tCALL\tSETHLDE\n\tLDA\tMODE\t;get sequential flag (=1).\n\tCPI\t2\t;a 2 indicates that no adder is needed.\n\tJNZ\tSTNREC1\n\tXRA\tA\t;clear adder (random access?).\nSTNREC1\tMOV\tC,A\n\tLDA\tSAVNREC\t;get last record number.\n\tADD\tC\t;increment record count.\n\tMOV\tM,A\t;and set fcb's next record byte.\n\tXCHG\n\tLDA\tSAVNXT\t;get next record byte from storage.\n\tMOV\tM,A\t;and put this into fcb as number of records used.\n\tRET\n;\n;   Shift (HL) right (C) bits.\n;\nSHIFTR\tINR\tC\nSHIFTR1\tDCR\tC\n\tRZ\n\tMOV\tA,H\n\tORA\tA\n\tRAR\n\tMOV\tH,A\n\tMOV\tA,L\n\tRAR\n\tMOV\tL,A\n\tJMP\tSHIFTR1\n;\n;   Compute the check-sum for the directory buffer. Return\n; integer sum in (A).\n;\nCHECKSUM:MVI\tC,128\t;length of buffer.\n\tLHLD\tDIRBUF\t;get its location.\n\tXRA\tA\t;clear summation byte.\nCHKSUM1\tADD\tM\t;and compute sum ignoring carries.\n\tINX\tH\n\tDCR\tC\n\tJNZ\tCHKSUM1\n\tRET\n;\n;   Shift (HL) left (C) bits.\n;\nSHIFTL\tINR\tC\nSHIFTL1\tDCR\tC\n\tRZ\n\tDAD\tH\t;shift left 1 bit.\n\tJMP\tSHIFTL1\n;\n;   Routine to set a bit in a 16 bit value contained in (BC).\n; The bit set depends on the current drive selection.\n;\nSETBIT\tPUSH\tB\t;save 16 bit word.\n\tLDA\tACTIVE\t;get active drive.\n\tMOV\tC,A\n\tLXI\tH,1\n\tCALL\tSHIFTL\t;shift bit 0 into place.\n\tPOP\tB\t;now 'or' this with the original word.\n\tMOV\tA,C\n\tORA\tL\n\tMOV\tL,A\t;low byte done, do high byte.\n\tMOV\tA,B\n\tORA\tH\n\tMOV\tH,A\n\tRET\n;\n;   Extract the write protect status bit for the current drive.\n; The result is returned in (A), bit 0.\n;\nGETWPRT\tLHLD\tWRTPRT\t;get status bytes.\n\tLDA\tACTIVE\t;which drive is current?\n\tMOV\tC,A\n\tCALL\tSHIFTR\t;shift status such that bit 0 is the\n\tMOV\tA,L\t;one of interest for this drive.\n\tANI\t01H\t;and isolate it.\n\tRET\n;\n;   Function to write protect the current disk.\n;\nWRTPRTD\tLXI\tH,WRTPRT;point to status word.\n\tMOV\tC,M\t;set (BC) equal to the status.\n\tINX\tH\n\tMOV\tB,M\n\tCALL\tSETBIT\t;and set this bit according to current drive.\n\tSHLD\tWRTPRT\t;then save.\n\tLHLD\tDIRSIZE\t;now save directory size limit.\n\tINX\tH\t;remember the last one.\n\tXCHG\n\tLHLD\tSCRATCH1;and store it here.\n\tMOV\tM,E\t;put low byte.\n\tINX\tH\n\tMOV\tM,D\t;then high byte.\n\tRET\n;\n;   Check for a read only file.\n;\nCHKROFL\tCALL\tFCB2HL\t;set (HL) to file entry in directory buffer.\nCKROF1\tLXI\tD,9\t;look at bit 7 of the ninth byte.\n\tDAD\tD\n\tMOV\tA,M\n\tRAL\n\tRNC\t\t;return if ok.\n\tLXI\tH,ROFILE;else, print error message and terminate.\n\tJMP\tJUMPHL\n;\n;   Check the write protect status of the active disk.\n;\nCHKWPRT\tCALL\tGETWPRT\n\tRZ\t\t;return if ok.\n\tLXI\tH,RODISK;else print message and terminate.\n\tJMP\tJUMPHL\n;\n;   Routine to set (HL) pointing to the proper entry in the\n; directory buffer.\n;\nFCB2HL\tLHLD\tDIRBUF\t;get address of buffer.\n\tLDA\tFCBPOS\t;relative position of file.\n;\n;   Routine to add (A) to (HL).\n;\nADDA2HL\tADD\tL\n\tMOV\tL,A\n\tRNC\n\tINR\tH\t;take care of any carry.\n\tRET\n;\n;   Routine to get the 's2' byte from the fcb supplied in\n; the initial parameter specification.\n;\nGETS2\tLHLD\tPARAMS\t;get address of fcb.\n\tLXI\tD,14\t;relative position of 's2'.\n\tDAD\tD\n\tMOV\tA,M\t;extract this byte.\n\tRET\n;\n;   Clear the 's2' byte in the fcb.\n;\nCLEARS2\tCALL\tGETS2\t;this sets (HL) pointing to it.\n\tMVI\tM,0\t;now clear it.\n\tRET\n;\n;   Set bit 7 in the 's2' byte of the fcb.\n;\nSETS2B7\tCALL\tGETS2\t;get the byte.\n\tORI\t80H\t;and set bit 7.\n\tMOV\tM,A\t;then store.\n\tRET\n;\n;   Compare (FILEPOS) with (SCRATCH1) and set flags based on\n; the difference. This checks to see if there are more file\n; names in the directory. We are at (FILEPOS) and there are\n; (SCRATCH1) of them to check.\n;\nMOREFLS\tLHLD\tFILEPOS\t;we are here.\n\tXCHG\n\tLHLD\tSCRATCH1;and don't go past here.\n\tMOV\tA,E\t;compute difference but don't keep.\n\tSUB\tM\n\tINX\tH\n\tMOV\tA,D\n\tSBB\tM\t;set carry if no more names.\n\tRET\n;\n;   Call this routine to prevent (SCRATCH1) from being greater\n; than (FILEPOS).\n;\nCHKNMBR\tCALL\tMOREFLS\t;SCRATCH1 too big?\n\tRC\n\tINX\tD\t;yes, reset it to (FILEPOS).\n\tMOV\tM,D\n\tDCX\tH\n\tMOV\tM,E\n\tRET\n;\n;   Compute (HL)=(DE)-(HL)\n;\nSUBHL\tMOV\tA,E\t;compute difference.\n\tSUB\tL\n\tMOV\tL,A\t;store low byte.\n\tMOV\tA,D\n\tSBB\tH\n\tMOV\tH,A\t;and then high byte.\n\tRET\n;\n;   Set the directory checksum byte.\n;\nSETDIR\tMVI\tC,0FFH\n;\n;   Routine to set or compare the directory checksum byte. If\n; (C)=0ffh, then this will set the checksum byte. Else the byte\n; will be checked. If the check fails (the disk has been changed),\n; then this disk will be write protected.\n;\nCHECKDIR:LHLD\tCKSUMTBL\n\tXCHG\n\tLHLD\tALLOC1\n\tCALL\tSUBHL\n\tRNC\t\t;ok if (CKSUMTBL) > (ALLOC1), so return.\n\tPUSH\tB\n\tCALL\tCHECKSUM;else compute checksum.\n\tLHLD\tCHKVECT\t;get address of checksum table.\n\tXCHG\n\tLHLD\tCKSUMTBL\n\tDAD\tD\t;set (HL) to point to byte for this drive.\n\tPOP\tB\n\tINR\tC\t;set or check ?\n\tJZ\tCHKDIR1\n\tCMP\tM\t;check them.\n\tRZ\t\t;return if they are the same.\n\tCALL\tMOREFLS\t;not the same, do we care?\n\tRNC\n\tCALL\tWRTPRTD\t;yes, mark this as write protected.\n\tRET\nCHKDIR1\tMOV\tM,A\t;just set the byte.\n\tRET\n;\n;   Do a write to the directory of the current disk.\n;\nDIRWRITE:CALL\tSETDIR\t;set checksum byte.\n\tCALL\tDIRDMA\t;set directory dma address.\n\tMVI\tC,1\t;tell the bios to actually write.\n\tCALL\tDOWRITE\t;then do the write.\n\tJMP\tDEFDMA\n;\n;   Read from the directory.\n;\nDIRREAD\tCALL\tDIRDMA\t;set the directory dma address.\n\tCALL\tDOREAD\t;and read it.\n;\n;   Routine to set the dma address to the users choice.\n;\nDEFDMA\tLXI\tH,USERDMA;reset the default dma address and return.\n\tJMP\tDIRDMA1\n;\n;   Routine to set the dma address for directory work.\n;\nDIRDMA\tLXI\tH,DIRBUF\n;\n;   Set the dma address. On entry, (HL) points to\n; word containing the desired dma address.\n;\nDIRDMA1\tMOV\tC,M\n\tINX\tH\n\tMOV\tB,M\t;setup (BC) and go to the bios to set it.\n\tJMP\tSETDMA\n;\n;   Move the directory buffer into user's dma space.\n;\nMOVEDIR\tLHLD\tDIRBUF\t;buffer is located here, and\n\tXCHG\n\tLHLD\tUSERDMA; put it here.\n\tMVI\tC,128\t;this is its length.\n\tJMP\tDE2HL\t;move it now and return.\n;\n;   Check (FILEPOS) and set the zero flag if it equals 0ffffh.\n;\nCKFILPOS:LXI\tH,FILEPOS\n\tMOV\tA,M\n\tINX\tH\n\tCMP\tM\t;are both bytes the same?\n\tRNZ\n\tINR\tA\t;yes, but are they each 0ffh?\n\tRET\n;\n;   Set location (FILEPOS) to 0ffffh.\n;\nSTFILPOS:LXI\tH,0FFFFH\n\tSHLD\tFILEPOS\n\tRET\n;\n;   Move on to the next file position within the current\n; directory buffer. If no more exist, set pointer to 0ffffh\n; and the calling routine will check for this. Enter with (C)\n; equal to 0ffh to cause the checksum byte to be set, else we\n; will check this disk and set write protect if checksums are\n; not the same (applies only if another directory sector must\n; be read).\n;\nNXENTRY\tLHLD\tDIRSIZE\t;get directory entry size limit.\n\tXCHG\n\tLHLD\tFILEPOS\t;get current count.\n\tINX\tH\t;go on to the next one.\n\tSHLD\tFILEPOS\n\tCALL\tSUBHL\t;(HL)=(DIRSIZE)-(FILEPOS)\n\tJNC\tNXENT1\t;is there more room left?\n\tJMP\tSTFILPOS;no. Set this flag and return.\nNXENT1\tLDA\tFILEPOS\t;get file position within directory.\n\tANI\t03H\t;only look within this sector (only 4 entries fit).\n\tMVI\tB,5\t;convert to relative position (32 bytes each).\nNXENT2\tADD\tA\t;note that this is not efficient code.\n\tDCR\tB\t;5 'ADD A's would be better.\n\tJNZ\tNXENT2\n\tSTA\tFCBPOS\t;save it as position of fcb.\n\tORA\tA\n\tRNZ\t\t;return if we are within buffer.\n\tPUSH\tB\n\tCALL\tTRKSEC\t;we need the next directory sector.\n\tCALL\tDIRREAD\n\tPOP\tB\n\tJMP\tCHECKDIR\n;\n;   Routine to to get a bit from the disk space allocation\n; map. It is returned in (A), bit position 0. On entry to here,\n; set (BC) to the block number on the disk to check.\n; On return, (D) will contain the original bit position for\n; this block number and (HL) will point to the address for it.\n;\nCKBITMAP:MOV\tA,C\t;determine bit number of interest.\n\tANI\t07H\t;compute (D)=(E)=(C and 7)+1.\n\tINR\tA\n\tMOV\tE,A\t;save particular bit number.\n\tMOV\tD,A\n;\n;   compute (BC)=(BC)/8.\n;\n\tMOV\tA,C\n\tRRC\t\t;now shift right 3 bits.\n\tRRC\n\tRRC\n\tANI\t1FH\t;and clear bits 7,6,5.\n\tMOV\tC,A\n\tMOV\tA,B\n\tADD\tA\t;now shift (B) into bits 7,6,5.\n\tADD\tA\n\tADD\tA\n\tADD\tA\n\tADD\tA\n\tORA\tC\t;and add in (C).\n\tMOV\tC,A\t;ok, (C) ha been completed.\n\tMOV\tA,B\t;is there a better way of doing this?\n\tRRC\n\tRRC\n\tRRC\n\tANI\t1FH\n\tMOV\tB,A\t;and now (B) is completed.\n;\n;   use this as an offset into the disk space allocation\n; table.\n;\n\tLHLD\tALOCVECT\n\tDAD\tB\n\tMOV\tA,M\t;now get correct byte.\nCKBMAP1\tRLC\t\t;get correct bit into position 0.\n\tDCR\tE\n\tJNZ\tCKBMAP1\n\tRET\n;\n;   Set or clear the bit map such that block number (BC) will be marked\n; as used. On entry, if (E)=0 then this bit will be cleared, if it equals\n; 1 then it will be set (don't use anyother values).\n;\nSTBITMAP:PUSH\tD\n\tCALL\tCKBITMAP;get the byte of interest.\n\tANI\t0FEH\t;clear the affected bit.\n\tPOP\tB\n\tORA\tC\t;and now set it acording to (C).\n;\n;  entry to restore the original bit position and then store\n; in table. (A) contains the value, (D) contains the bit\n; position (1-8), and (HL) points to the address within the\n; space allocation table for this byte.\n;\nSTBMAP1\tRRC\t\t;restore original bit position.\n\tDCR\tD\n\tJNZ\tSTBMAP1\n\tMOV\tM,A\t;and stor byte in table.\n\tRET\n;\n;   Set/clear space used bits in allocation map for this file.\n; On entry, (C)=1 to set the map and (C)=0 to clear it.\n;\nSETFILE\tCALL\tFCB2HL\t;get address of fcb\n\tLXI\tD,16\n\tDAD\tD\t;get to block number bytes.\n\tPUSH\tB\n\tMVI\tC,17\t;check all 17 bytes (max) of table.\nSETFL1\tPOP\tD\n\tDCR\tC\t;done all bytes yet?\n\tRZ\n\tPUSH\tD\n\tLDA\tBIGDISK\t;check disk size for 16 bit block numbers.\n\tORA\tA\n\tJZ\tSETFL2\n\tPUSH\tB\t;only 8 bit numbers. set (BC) to this one.\n\tPUSH\tH\n\tMOV\tC,M\t;get low byte from table, always\n\tMVI\tB,0\t;set high byte to zero.\n\tJMP\tSETFL3\nSETFL2\tDCR\tC\t;for 16 bit block numbers, adjust counter.\n\tPUSH\tB\n\tMOV\tC,M\t;now get both the low and high bytes.\n\tINX\tH\n\tMOV\tB,M\n\tPUSH\tH\nSETFL3\tMOV\tA,C\t;block used?\n\tORA\tB\n\tJZ\tSETFL4\n\tLHLD\tDSKSIZE\t;is this block number within the\n\tMOV\tA,L\t;space on the disk?\n\tSUB\tC\n\tMOV\tA,H\n\tSBB\tB\n\tCNC\tSTBITMAP;yes, set the proper bit.\nSETFL4\tPOP\tH\t;point to next block number in fcb.\n\tINX\tH\n\tPOP\tB\n\tJMP\tSETFL1\n;\n;   Construct the space used allocation bit map for the active\n; drive. If a file name starts with '$' and it is under the\n; current user number, then (STATUS) is set to minus 1. Otherwise\n; it is not set at all.\n;\nBITMAP\tLHLD\tDSKSIZE\t;compute size of allocation table.\n\tMVI\tC,3\n\tCALL\tSHIFTR\t;(HL)=(HL)/8.\n\tINX\tH\t;at lease 1 byte.\n\tMOV\tB,H\n\tMOV\tC,L\t;set (BC) to the allocation table length.\n;\n;   Initialize the bitmap for this drive. Right now, the first\n; two bytes are specified by the disk parameter block. However\n; a patch could be entered here if it were necessary to setup\n; this table in a special mannor. For example, the bios could\n; determine locations of 'bad blocks' and set them as already\n; 'used' in the map.\n;\n\tLHLD\tALOCVECT;now zero out the table now.\nBITMAP1\tMVI\tM,0\n\tINX\tH\n\tDCX\tB\n\tMOV\tA,B\n\tORA\tC\n\tJNZ\tBITMAP1\n\tLHLD\tALLOC0\t;get initial space used by directory.\n\tXCHG\n\tLHLD\tALOCVECT;and put this into map.\n\tMOV\tM,E\n\tINX\tH\n\tMOV\tM,D\n;\n;   End of initialization portion.\n;\n\tCALL\tHOMEDRV\t;now home the drive.\n\tLHLD\tSCRATCH1\n\tMVI\tM,3\t;force next directory request to read\n\tINX\tH\t;in a sector.\n\tMVI\tM,0\n\tCALL\tSTFILPOS;clear initial file position also.\nBITMAP2\tMVI\tC,0FFH\t;read next file name in directory\n\tCALL\tNXENTRY\t;and set checksum byte.\n\tCALL\tCKFILPOS;is there another file?\n\tRZ\n\tCALL\tFCB2HL\t;yes, get its address.\n\tMVI\tA,0E5H\n\tCMP\tM\t;empty file entry?\n\tJZ\tBITMAP2\n\tLDA\tUSERNO\t;no, correct user number?\n\tCMP\tM\n\tJNZ\tBITMAP3\n\tINX\tH\n\tMOV\tA,M\t;yes, does name start with a '$'?\n\tSUI\t'$'\n\tJNZ\tBITMAP3\n\tDCR\tA\t;yes, set atatus to minus one.\n\tSTA\tSTATUS\nBITMAP3\tMVI\tC,1\t;now set this file's space as used in bit map.\n\tCALL\tSETFILE\n\tCALL\tCHKNMBR\t;keep (SCRATCH1) in bounds.\n\tJMP\tBITMAP2\n;\n;   Set the status (STATUS) and return.\n;\nSTSTATUS:LDA\tFNDSTAT\n\tJMP\tSETSTAT\n;\n;   Check extents in (A) and (C). Set the zero flag if they\n; are the same. The number of 16k chunks of disk space that\n; the directory extent covers is expressad is (EXTMASK+1).\n; No registers are modified.\n;\nSAMEXT\tPUSH\tB\n\tPUSH\tPSW\n\tLDA\tEXTMASK\t;get extent mask and use it to\n\tCMA\t\t;to compare both extent numbers.\n\tMOV\tB,A\t;save resulting mask here.\n\tMOV\tA,C\t;mask first extent and save in (C).\n\tANA\tB\n\tMOV\tC,A\n\tPOP\tPSW\t;now mask second extent and compare\n\tANA\tB\t;with the first one.\n\tSUB\tC\n\tANI\t1FH\t;(* only check buts 0-4 *)\n\tPOP\tB\t;the zero flag is set if they are the same.\n\tRET\t\t;restore (BC) and return.\n;\n;   Search for the first occurence of a file name. On entry,\n; register (C) should contain the number of bytes of the fcb\n; that must match.\n;\nFINDFST\tMVI\tA,0FFH\n\tSTA\tFNDSTAT\n\tLXI\tH,COUNTER;save character count.\n\tMOV\tM,C\n\tLHLD\tPARAMS\t;get filename to match.\n\tSHLD\tSAVEFCB\t;and save.\n\tCALL\tSTFILPOS;clear initial file position (set to 0ffffh).\n\tCALL\tHOMEDRV\t;home the drive.\n;\n;   Entry to locate the next occurence of a filename within the\n; directory. The disk is not expected to have been changed. If\n; it was, then it will be write protected.\n;\nFINDNXT\tMVI\tC,0\t;write protect the disk if changed.\n\tCALL\tNXENTRY\t;get next filename entry in directory.\n\tCALL\tCKFILPOS;is file position = 0ffffh?\n\tJZ\tFNDNXT6\t;yes, exit now then.\n\tLHLD\tSAVEFCB\t;set (DE) pointing to filename to match.\n\tXCHG\n\tLDAX\tD\n\tCPI\t0E5H\t;empty directory entry?\n\tJZ\tFNDNXT1\t;(* are we trying to reserect erased entries? *)\n\tPUSH\tD\n\tCALL\tMOREFLS\t;more files in directory?\n\tPOP\tD\n\tJNC\tFNDNXT6\t;no more. Exit now.\nFNDNXT1\tCALL\tFCB2HL\t;get address of this fcb in directory.\n\tLDA\tCOUNTER\t;get number of bytes (characters) to check.\n\tMOV\tC,A\n\tMVI\tB,0\t;initialize byte position counter.\nFNDNXT2\tMOV\tA,C\t;are we done with the compare?\n\tORA\tA\n\tJZ\tFNDNXT5\n\tLDAX\tD\t;no, check next byte.\n\tCPI\t'?'\t;don't care about this character?\n\tJZ\tFNDNXT4\n\tMOV\tA,B\t;get bytes position in fcb.\n\tCPI\t13\t;don't care about the thirteenth byte either.\n\tJZ\tFNDNXT4\n\tCPI\t12\t;extent byte?\n\tLDAX\tD\n\tJZ\tFNDNXT3\n\tSUB\tM\t;otherwise compare characters.\n\tANI\t7FH\n\tJNZ\tFINDNXT\t;not the same, check next entry.\n\tJMP\tFNDNXT4\t;so far so good, keep checking.\nFNDNXT3\tPUSH\tB\t;check the extent byte here.\n\tMOV\tC,M\n\tCALL\tSAMEXT\n\tPOP\tB\n\tJNZ\tFINDNXT\t;not the same, look some more.\n;\n;   So far the names compare. Bump pointers to the next byte\n; and continue until all (C) characters have been checked.\n;\nFNDNXT4\tINX\tD\t;bump pointers.\n\tINX\tH\n\tINR\tB\n\tDCR\tC\t;adjust character counter.\n\tJMP\tFNDNXT2\nFNDNXT5\tLDA\tFILEPOS\t;return the position of this entry.\n\tANI\t03H\n\tSTA\tSTATUS\n\tLXI\tH,FNDSTAT\n\tMOV\tA,M\n\tRAL\n\tRNC\n\tXRA\tA\n\tMOV\tM,A\n\tRET\n;\n;   Filename was not found. Set appropriate status.\n;\nFNDNXT6\tCALL\tSTFILPOS;set (FILEPOS) to 0ffffh.\n\tMVI\tA,0FFH\t;say not located.\n\tJMP\tSETSTAT\n;\n;   Erase files from the directory. Only the first byte of the\n; fcb will be affected. It is set to (E5).\n;\nERAFILE\tCALL\tCHKWPRT\t;is disk write protected?\n\tMVI\tC,12\t;only compare file names.\n\tCALL\tFINDFST\t;get first file name.\nERAFIL1\tCALL\tCKFILPOS;any found?\n\tRZ\t\t;nope, we must be done.\n\tCALL\tCHKROFL\t;is file read only?\n\tCALL\tFCB2HL\t;nope, get address of fcb and\n\tMVI\tM,0E5H\t;set first byte to 'empty'.\n\tMVI\tC,0\t;clear the space from the bit map.\n\tCALL\tSETFILE\n\tCALL\tDIRWRITE;now write the directory sector back out.\n\tCALL\tFINDNXT\t;find the next file name.\n\tJMP\tERAFIL1\t;and repeat process.\n;\n;   Look through the space allocation map (bit map) for the\n; next available block. Start searching at block number (BC-1).\n; The search procedure is to look for an empty block that is\n; before the starting block. If not empty, look at a later\n; block number. In this way, we return the closest empty block\n; on either side of the 'target' block number. This will speed\n; access on random devices. For serial devices, this should be\n; changed to look in the forward direction first and then start\n; at the front and search some more.\n;\n;   On return, (DE)= block number that is empty and (HL) =0\n; if no empry block was found.\n;\nFNDSPACE:MOV\tD,B\t;set (DE) as the block that is checked.\n\tMOV\tE,C\n;\n;   Look before target block. Registers (BC) are used as the lower\n; pointer and (DE) as the upper pointer.\n;\nFNDSPA1\tMOV\tA,C\t;is block 0 specified?\n\tORA\tB\n\tJZ\tFNDSPA2\n\tDCX\tB\t;nope, check previous block.\n\tPUSH\tD\n\tPUSH\tB\n\tCALL\tCKBITMAP\n\tRAR\t\t;is this block empty?\n\tJNC\tFNDSPA3\t;yes. use this.\n;\n;   Note that the above logic gets the first block that it finds\n; that is empty. Thus a file could be written 'backward' making\n; it very slow to access. This could be changed to look for the\n; first empty block and then continue until the start of this\n; empty space is located and then used that starting block.\n; This should help speed up access to some files especially on\n; a well used disk with lots of fairly small 'holes'.\n;\n\tPOP\tB\t;nope, check some more.\n\tPOP\tD\n;\n;   Now look after target block.\n;\nFNDSPA2\tLHLD\tDSKSIZE\t;is block (DE) within disk limits?\n\tMOV\tA,E\n\tSUB\tL\n\tMOV\tA,D\n\tSBB\tH\n\tJNC\tFNDSPA4\n\tINX\tD\t;yes, move on to next one.\n\tPUSH\tB\n\tPUSH\tD\n\tMOV\tB,D\n\tMOV\tC,E\n\tCALL\tCKBITMAP;check it.\n\tRAR\t\t;empty?\n\tJNC\tFNDSPA3\n\tPOP\tD\t;nope, continue searching.\n\tPOP\tB\n\tJMP\tFNDSPA1\n;\n;   Empty block found. Set it as used and return with (HL)\n; pointing to it (true?).\n;\nFNDSPA3\tRAL\t\t;reset byte.\n\tINR\tA\t;and set bit 0.\n\tCALL\tSTBMAP1\t;update bit map.\n\tPOP\tH\t;set return registers.\n\tPOP\tD\n\tRET\n;\n;   Free block was not found. If (BC) is not zero, then we have\n; not checked all of the disk space.\n;\nFNDSPA4\tMOV\tA,C\n\tORA\tB\n\tJNZ\tFNDSPA1\n\tLXI\tH,0\t;set 'not found' status.\n\tRET\n;\n;   Move a complete fcb entry into the directory and write it.\n;\nFCBSET\tMVI\tC,0\n\tMVI\tE,32\t;length of each entry.\n;\n;   Move (E) bytes from the fcb pointed to by (PARAMS) into\n; fcb in directory starting at relative byte (C). This updated\n; directory buffer is then written to the disk.\n;\nUPDATE\tPUSH\tD\n\tMVI\tB,0\t;set (BC) to relative byte position.\n\tLHLD\tPARAMS\t;get address of fcb.\n\tDAD\tB\t;compute starting byte.\n\tXCHG\n\tCALL\tFCB2HL\t;get address of fcb to update in directory.\n\tPOP\tB\t;set (C) to number of bytes to change.\n\tCALL\tDE2HL\nUPDATE1\tCALL\tTRKSEC\t;determine the track and sector affected.\n\tJMP\tDIRWRITE\t;then write this sector out.\n;\n;   Routine to change the name of all files on the disk with a\n; specified name. The fcb contains the current name as the\n; first 12 characters and the new name 16 bytes into the fcb.\n;\nCHGNAMES:CALL\tCHKWPRT\t;check for a write protected disk.\n\tMVI\tC,12\t;match first 12 bytes of fcb only.\n\tCALL\tFINDFST\t;get first name.\n\tLHLD\tPARAMS\t;get address of fcb.\n\tMOV\tA,M\t;get user number.\n\tLXI\tD,16\t;move over to desired name.\n\tDAD\tD\n\tMOV\tM,A\t;keep same user number.\nCHGNAM1\tCALL\tCKFILPOS;any matching file found?\n\tRZ\t\t;no, we must be done.\n\tCALL\tCHKROFL\t;check for read only file.\n\tMVI\tC,16\t;start 16 bytes into fcb.\n\tMVI\tE,12\t;and update the first 12 bytes of directory.\n\tCALL\tUPDATE\n\tCALL\tFINDNXT\t;get te next file name.\n\tJMP\tCHGNAM1\t;and continue.\n;\n;   Update a files attributes. The procedure is to search for\n; every file with the same name as shown in fcb (ignoring bit 7)\n; and then to update it (which includes bit 7). No other changes\n; are made.\n;\nSAVEATTR:MVI\tC,12\t;match first 12 bytes.\n\tCALL\tFINDFST\t;look for first filename.\nSAVATR1\tCALL\tCKFILPOS;was one found?\n\tRZ\t\t;nope, we must be done.\n\tMVI\tC,0\t;yes, update the first 12 bytes now.\n\tMVI\tE,12\n\tCALL\tUPDATE\t;update filename and write directory.\n\tCALL\tFINDNXT\t;and get the next file.\n\tJMP\tSAVATR1\t;then continue until done.\n;\n;  Open a file (name specified in fcb).\n;\nOPENIT\tMVI\tC,15\t;compare the first 15 bytes.\n\tCALL\tFINDFST\t;get the first one in directory.\n\tCALL\tCKFILPOS;any at all?\n\tRZ\nOPENIT1\tCALL\tSETEXT\t;point to extent byte within users fcb.\n\tMOV\tA,M\t;and get it.\n\tPUSH\tPSW\t;save it and address.\n\tPUSH\tH\n\tCALL\tFCB2HL\t;point to fcb in directory.\n\tXCHG\n\tLHLD\tPARAMS\t;this is the users copy.\n\tMVI\tC,32\t;move it into users space.\n\tPUSH\tD\n\tCALL\tDE2HL\n\tCALL\tSETS2B7\t;set bit 7 in 's2' byte (unmodified).\n\tPOP\tD\t;now get the extent byte from this fcb.\n\tLXI\tH,12\n\tDAD\tD\n\tMOV\tC,M\t;into (C).\n\tLXI\tH,15\t;now get the record count byte into (B).\n\tDAD\tD\n\tMOV\tB,M\n\tPOP\tH\t;keep the same extent as the user had originally.\n\tPOP\tPSW\n\tMOV\tM,A\n\tMOV\tA,C\t;is it the same as in the directory fcb?\n\tCMP\tM\n\tMOV\tA,B\t;if yes, then use the same record count.\n\tJZ\tOPENIT2\n\tMVI\tA,0\t;if the user specified an extent greater than\n\tJC\tOPENIT2\t;the one in the directory, then set record count to 0.\n\tMVI\tA,128\t;otherwise set to maximum.\nOPENIT2\tLHLD\tPARAMS\t;set record count in users fcb to (A).\n\tLXI\tD,15\n\tDAD\tD\t;compute relative position.\n\tMOV\tM,A\t;and set the record count.\n\tRET\n;\n;   Move two bytes from (DE) to (HL) if (and only if) (HL)\n; point to a zero value (16 bit).\n;   Return with zero flag set it (DE) was moved. Registers (DE)\n; and (HL) are not changed. However (A) is.\n;\nMOVEWORD:MOV\tA,M\t;check for a zero word.\n\tINX\tH\n\tORA\tM\t;both bytes zero?\n\tDCX\tH\n\tRNZ\t\t;nope, just return.\n\tLDAX\tD\t;yes, move two bytes from (DE) into\n\tMOV\tM,A\t;this zero space.\n\tINX\tD\n\tINX\tH\n\tLDAX\tD\n\tMOV\tM,A\n\tDCX\tD\t;don't disturb these registers.\n\tDCX\tH\n\tRET\n;\n;   Get here to close a file specified by (fcb).\n;\nCLOSEIT\tXRA\tA\t;clear status and file position bytes.\n\tSTA\tSTATUS\n\tSTA\tFILEPOS\n\tSTA\tFILEPOS+1\n\tCALL\tGETWPRT\t;get write protect bit for this drive.\n\tRNZ\t\t;just return if it is set.\n\tCALL\tGETS2\t;else get the 's2' byte.\n\tANI\t80H\t;and look at bit 7 (file unmodified?).\n\tRNZ\t\t;just return if set.\n\tMVI\tC,15\t;else look up this file in directory.\n\tCALL\tFINDFST\n\tCALL\tCKFILPOS;was it found?\n\tRZ\t\t;just return if not.\n\tLXI\tB,16\t;set (HL) pointing to records used section.\n\tCALL\tFCB2HL\n\tDAD\tB\n\tXCHG\n\tLHLD\tPARAMS\t;do the same for users specified fcb.\n\tDAD\tB\n\tMVI\tC,16\t;this many bytes are present in this extent.\nCLOSEIT1:LDA\tBIGDISK\t;8 or 16 bit record numbers?\n\tORA\tA\n\tJZ\tCLOSEIT4\n\tMOV\tA,M\t;just 8 bit. Get one from users fcb.\n\tORA\tA\n\tLDAX\tD\t;now get one from directory fcb.\n\tJNZ\tCLOSEIT2\n\tMOV\tM,A\t;users byte was zero. Update from directory.\nCLOSEIT2:ORA\tA\n\tJNZ\tCLOSEIT3\n\tMOV\tA,M\t;directories byte was zero, update from users fcb.\n\tSTAX\tD\nCLOSEIT3:CMP\tM\t;if neither one of these bytes were zero,\n\tJNZ\tCLOSEIT7\t;then close error if they are not the same.\n\tJMP\tCLOSEIT5\t;ok so far, get to next byte in fcbs.\nCLOSEIT4:CALL\tMOVEWORD;update users fcb if it is zero.\n\tXCHG\n\tCALL\tMOVEWORD;update directories fcb if it is zero.\n\tXCHG\n\tLDAX\tD\t;if these two values are no different,\n\tCMP\tM\t;then a close error occured.\n\tJNZ\tCLOSEIT7\n\tINX\tD\t;check second byte.\n\tINX\tH\n\tLDAX\tD\n\tCMP\tM\n\tJNZ\tCLOSEIT7\n\tDCR\tC\t;remember 16 bit values.\nCLOSEIT5:INX\tD\t;bump to next item in table.\n\tINX\tH\n\tDCR\tC\t;there are 16 entries only.\n\tJNZ\tCLOSEIT1;continue if more to do.\n\tLXI\tB,0FFECH;backup 20 places (extent byte).\n\tDAD\tB\n\tXCHG\n\tDAD\tB\n\tLDAX\tD\n\tCMP\tM\t;directory's extent already greater than the\n\tJC\tCLOSEIT6\t;users extent?\n\tMOV\tM,A\t;no, update directory extent.\n\tLXI\tB,3\t;and update the record count byte in\n\tDAD\tB\t;directories fcb.\n\tXCHG\n\tDAD\tB\n\tMOV\tA,M\t;get from user.\n\tSTAX\tD\t;and put in directory.\nCLOSEIT6:MVI\tA,0FFH\t;set 'was open and is now closed' byte.\n\tSTA\tCLOSEFLG\n\tJMP\tUPDATE1\t;update the directory now.\nCLOSEIT7:LXI\tH,STATUS;set return status and then return.\n\tDCR\tM\n\tRET\n;\n;   Routine to get the next empty space in the directory. It\n; will then be cleared for use.\n;\nGETEMPTY:CALL\tCHKWPRT\t;make sure disk is not write protected.\n\tLHLD\tPARAMS\t;save current parameters (fcb).\n\tPUSH\tH\n\tLXI\tH,EMPTYFCB;use special one for empty space.\n\tSHLD\tPARAMS\n\tMVI\tC,1\t;search for first empty spot in directory.\n\tCALL\tFINDFST\t;(* only check first byte *)\n\tCALL\tCKFILPOS;none?\n\tPOP\tH\n\tSHLD\tPARAMS\t;restore original fcb address.\n\tRZ\t\t;return if no more space.\n\tXCHG\n\tLXI\tH,15\t;point to number of records for this file.\n\tDAD\tD\n\tMVI\tC,17\t;and clear all of this space.\n\tXRA\tA\nGETMT1\tMOV\tM,A\n\tINX\tH\n\tDCR\tC\n\tJNZ\tGETMT1\n\tLXI\tH,13\t;clear the 's1' byte also.\n\tDAD\tD\n\tMOV\tM,A\n\tCALL\tCHKNMBR\t;keep (SCRATCH1) within bounds.\n\tCALL\tFCBSET\t;write out this fcb entry to directory.\n\tJMP\tSETS2B7\t;set 's2' byte bit 7 (unmodified at present).\n;\n;   Routine to close the current extent and open the next one\n; for reading.\n;\nGETNEXT\tXRA\tA\n\tSTA\tCLOSEFLG;clear close flag.\n\tCALL\tCLOSEIT\t;close this extent.\n\tCALL\tCKFILPOS\n\tRZ\t\t;not there???\n\tLHLD\tPARAMS\t;get extent byte.\n\tLXI\tB,12\n\tDAD\tB\n\tMOV\tA,M\t;and increment it.\n\tINR\tA\n\tANI\t1FH\t;keep within range 0-31.\n\tMOV\tM,A\n\tJZ\tGTNEXT1\t;overflow?\n\tMOV\tB,A\t;mask extent byte.\n\tLDA\tEXTMASK\n\tANA\tB\n\tLXI\tH,CLOSEFLG;check close flag (0ffh is ok).\n\tANA\tM\n\tJZ\tGTNEXT2\t;if zero, we must read in next extent.\n\tJMP\tGTNEXT3\t;else, it is already in memory.\nGTNEXT1\tLXI\tB,2\t;Point to the 's2' byte.\n\tDAD\tB\n\tINR\tM\t;and bump it.\n\tMOV\tA,M\t;too many extents?\n\tANI\t0FH\n\tJZ\tGTNEXT5\t;yes, set error code.\n;\n;   Get here to open the next extent.\n;\nGTNEXT2\tMVI\tC,15\t;set to check first 15 bytes of fcb.\n\tCALL\tFINDFST\t;find the first one.\n\tCALL\tCKFILPOS;none available?\n\tJNZ\tGTNEXT3\n\tLDA\tRDWRTFLG;no extent present. Can we open an empty one?\n\tINR\tA\t;0ffh means reading (so not possible).\n\tJZ\tGTNEXT5\t;or an error.\n\tCALL\tGETEMPTY;we are writing, get an empty entry.\n\tCALL\tCKFILPOS;none?\n\tJZ\tGTNEXT5\t;error if true.\n\tJMP\tGTNEXT4\t;else we are almost done.\nGTNEXT3\tCALL\tOPENIT1\t;open this extent.\nGTNEXT4\tCALL\tSTRDATA\t;move in updated data (rec #, extent #, etc.)\n\tXRA\tA\t;clear status and return.\n\tJMP\tSETSTAT\n;\n;   Error in extending the file. Too many extents were needed\n; or not enough space on the disk.\n;\nGTNEXT5\tCALL\tIOERR1\t;set error code, clear bit 7 of 's2'\n\tJMP\tSETS2B7\t;so this is not written on a close.\n;\n;   Read a sequential file.\n;\nRDSEQ\tMVI\tA,1\t;set sequential access mode.\n\tSTA\tMODE\nRDSEQ1\tMVI\tA,0FFH\t;don't allow reading unwritten space.\n\tSTA\tRDWRTFLG\n\tCALL\tSTRDATA\t;put rec# and ext# into fcb.\n\tLDA\tSAVNREC\t;get next record to read.\n\tLXI\tH,SAVNXT;get number of records in extent.\n\tCMP\tM\t;within this extent?\n\tJC\tRDSEQ2\n\tCPI\t128\t;no. Is this extent fully used?\n\tJNZ\tRDSEQ3\t;no. End-of-file.\n\tCALL\tGETNEXT\t;yes, open the next one.\n\tXRA\tA\t;reset next record to read.\n\tSTA\tSAVNREC\n\tLDA\tSTATUS\t;check on open, successful?\n\tORA\tA\n\tJNZ\tRDSEQ3\t;no, error.\nRDSEQ2\tCALL\tCOMBLK\t;ok. compute block number to read.\n\tCALL\tCHKBLK\t;check it. Within bounds?\n\tJZ\tRDSEQ3\t;no, error.\n\tCALL\tLOGICAL\t;convert (BLKNMBR) to logical sector (128 byte).\n\tCALL\tTRKSEC1\t;set the track and sector for this block #.\n\tCALL\tDOREAD\t;and read it.\n\tJMP\tSETNREC\t;and set the next record to be accessed.\n;\n;   Read error occured. Set status and return.\n;\nRDSEQ3\tJMP\tIOERR1\n;\n;   Write the next sequential record.\n;\nWTSEQ\tMVI\tA,1\t;set sequential access mode.\n\tSTA\tMODE\nWTSEQ1\tMVI\tA,0\t;allow an addition empty extent to be opened.\n\tSTA\tRDWRTFLG\n\tCALL\tCHKWPRT\t;check write protect status.\n\tLHLD\tPARAMS\n\tCALL\tCKROF1\t;check for read only file, (HL) already set to fcb.\n\tCALL\tSTRDATA\t;put updated data into fcb.\n\tLDA\tSAVNREC\t;get record number to write.\n\tCPI\t128\t;within range?\n\tJNC\tIOERR1\t;no, error(?).\n\tCALL\tCOMBLK\t;compute block number.\n\tCALL\tCHKBLK\t;check number.\n\tMVI\tC,0\t;is there one to write to?\n\tJNZ\tWTSEQ6\t;yes, go do it.\n\tCALL\tGETBLOCK;get next block number within fcb to use.\n\tSTA\tRELBLOCK;and save.\n\tLXI\tB,0\t;start looking for space from the start\n\tORA\tA\t;if none allocated as yet.\n\tJZ\tWTSEQ2\n\tMOV\tC,A\t;extract previous block number from fcb\n\tDCX\tB\t;so we can be closest to it.\n\tCALL\tEXTBLK\n\tMOV\tB,H\n\tMOV\tC,L\nWTSEQ2\tCALL\tFNDSPACE;find the next empty block nearest number (BC).\n\tMOV\tA,L\t;check for a zero number.\n\tORA\tH\n\tJNZ\tWTSEQ3\n\tMVI\tA,2\t;no more space?\n\tJMP\tSETSTAT\nWTSEQ3\tSHLD\tBLKNMBR\t;save block number to access.\n\tXCHG\t\t;put block number into (DE).\n\tLHLD\tPARAMS\t;now we must update the fcb for this\n\tLXI\tB,16\t;newly allocated block.\n\tDAD\tB\n\tLDA\tBIGDISK\t;8 or 16 bit block numbers?\n\tORA\tA\n\tLDA\tRELBLOCK\t;(* update this entry *)\n\tJZ\tWTSEQ4\t;zero means 16 bit ones.\n\tCALL\tADDA2HL\t;(HL)=(HL)+(A)\n\tMOV\tM,E\t;store new block number.\n\tJMP\tWTSEQ5\nWTSEQ4\tMOV\tC,A\t;compute spot in this 16 bit table.\n\tMVI\tB,0\n\tDAD\tB\n\tDAD\tB\n\tMOV\tM,E\t;stuff block number (DE) there.\n\tINX\tH\n\tMOV\tM,D\nWTSEQ5\tMVI\tC,2\t;set (C) to indicate writing to un-used disk space.\nWTSEQ6\tLDA\tSTATUS\t;are we ok so far?\n\tORA\tA\n\tRNZ\n\tPUSH\tB\t;yes, save write flag for bios (register C).\n\tCALL\tLOGICAL\t;convert (BLKNMBR) over to loical sectors.\n\tLDA\tMODE\t;get access mode flag (1=sequential,\n\tDCR\tA\t;0=random, 2=special?).\n\tDCR\tA\n\tJNZ\tWTSEQ9\n;\n;   Special random i/o from function #40. Maybe for M/PM, but the\n; current block, if it has not been written to, will be zeroed\n; out and then written (reason?).\n;\n\tPOP\tB\n\tPUSH\tB\n\tMOV\tA,C\t;get write status flag (2=writing unused space).\n\tDCR\tA\n\tDCR\tA\n\tJNZ\tWTSEQ9\n\tPUSH\tH\n\tLHLD\tDIRBUF\t;zero out the directory buffer.\n\tMOV\tD,A\t;note that (A) is zero here.\nWTSEQ7\tMOV\tM,A\n\tINX\tH\n\tINR\tD\t;do 128 bytes.\n\tJP\tWTSEQ7\n\tCALL\tDIRDMA\t;tell the bios the dma address for directory access.\n\tLHLD\tLOGSECT\t;get sector that starts current block.\n\tMVI\tC,2\t;set 'writing to unused space' flag.\nWTSEQ8\tSHLD\tBLKNMBR\t;save sector to write.\n\tPUSH\tB\n\tCALL\tTRKSEC1\t;determine its track and sector numbers.\n\tPOP\tB\n\tCALL\tDOWRITE\t;now write out 128 bytes of zeros.\n\tLHLD\tBLKNMBR\t;get sector number.\n\tMVI\tC,0\t;set normal write flag.\n\tLDA\tBLKMASK\t;determine if we have written the entire\n\tMOV\tB,A\t;physical block.\n\tANA\tL\n\tCMP\tB\n\tINX\tH\t;prepare for the next one.\n\tJNZ\tWTSEQ8\t;continue until (BLKMASK+1) sectors written.\n\tPOP\tH\t;reset next sector number.\n\tSHLD\tBLKNMBR\n\tCALL\tDEFDMA\t;and reset dma address.\n;\n;   Normal disk write. Set the desired track and sector then\n; do the actual write.\n;\nWTSEQ9\tCALL\tTRKSEC1\t;determine track and sector for this write.\n\tPOP\tB\t;get write status flag.\n\tPUSH\tB\n\tCALL\tDOWRITE\t;and write this out.\n\tPOP\tB\n\tLDA\tSAVNREC\t;get number of records in file.\n\tLXI\tH,SAVNXT;get last record written.\n\tCMP\tM\n\tJC\tWTSEQ10\n\tMOV\tM,A\t;we have to update record count.\n\tINR\tM\n\tMVI\tC,2\n;\n;*   This area has been patched to correct disk update problem\n;* when using blocking and de-blocking in the BIOS.\n;\nWTSEQ10\tNOP\t\t;was 'dcr c'\n\tNOP\t\t;was 'dcr c'\n\tLXI\tH,0\t;was 'jnz wtseq99'\n;\n; *   End of patch.\n;\n\tPUSH\tPSW\n\tCALL\tGETS2\t;set 'extent written to' flag.\n\tANI\t7FH\t;(* clear bit 7 *)\n\tMOV\tM,A\n\tPOP\tPSW\t;get record count for this extent.\nWTSEQ99\tCPI\t127\t;is it full?\n\tJNZ\tWTSEQ12\n\tLDA\tMODE\t;yes, are we in sequential mode?\n\tCPI\t1\n\tJNZ\tWTSEQ12\n\tCALL\tSETNREC\t;yes, set next record number.\n\tCALL\tGETNEXT\t;and get next empty space in directory.\n\tLXI\tH,STATUS;ok?\n\tMOV\tA,M\n\tORA\tA\n\tJNZ\tWTSEQ11\n\tDCR\tA\t;yes, set record count to -1.\n\tSTA\tSAVNREC\nWTSEQ11\tMVI\tM,0\t;clear status.\nWTSEQ12\tJMP\tSETNREC\t;set next record to access.\n;\n;   For random i/o, set the fcb for the desired record number\n; based on the 'r0,r1,r2' bytes. These bytes in the fcb are\n; used as follows:\n;\n;       fcb+35            fcb+34            fcb+33\n;  |     'r-2'      |      'r-1'      |      'r-0'     |\n;  |7             0 | 7             0 | 7             0|\n;  |0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0|\n;  |    overflow   | | extra |  extent   |   record #  |\n;  | ______________| |_extent|__number___|_____________|\n;                     also 's2'\n;\n;   On entry, register (C) contains 0ffh if this is a read\n; and thus we can not access unwritten disk space. Otherwise,\n; another extent will be opened (for writing) if required.\n;\nPOSITION:XRA\tA\t;set random i/o flag.\n\tSTA\tMODE\n;\n;   Special entry (function #40). M/PM ?\n;\nPOSITN1\tPUSH\tB\t;save read/write flag.\n\tLHLD\tPARAMS\t;get address of fcb.\n\tXCHG\n\tLXI\tH,33\t;now get byte 'r0'.\n\tDAD\tD\n\tMOV\tA,M\n\tANI\t7FH\t;keep bits 0-6 for the record number to access.\n\tPUSH\tPSW\n\tMOV\tA,M\t;now get bit 7 of 'r0' and bits 0-3 of 'r1'.\n\tRAL\n\tINX\tH\n\tMOV\tA,M\n\tRAL\n\tANI\t1FH\t;and save this in bits 0-4 of (C).\n\tMOV\tC,A\t;this is the extent byte.\n\tMOV\tA,M\t;now get the extra extent byte.\n\tRAR\n\tRAR\n\tRAR\n\tRAR\n\tANI\t0FH\n\tMOV\tB,A\t;and save it in (B).\n\tPOP\tPSW\t;get record number back to (A).\n\tINX\tH\t;check overflow byte 'r2'.\n\tMOV\tL,M\n\tINR\tL\n\tDCR\tL\n\tMVI\tL,6\t;prepare for error.\n\tJNZ\tPOSITN5\t;out of disk space error.\n\tLXI\tH,32\t;store record number into fcb.\n\tDAD\tD\n\tMOV\tM,A\n\tLXI\tH,12\t;and now check the extent byte.\n\tDAD\tD\n\tMOV\tA,C\n\tSUB\tM\t;same extent as before?\n\tJNZ\tPOSITN2\n\tLXI\tH,14\t;yes, check extra extent byte 's2' also.\n\tDAD\tD\n\tMOV\tA,B\n\tSUB\tM\n\tANI\t7FH\n\tJZ\tPOSITN3;same, we are almost done then.\n;\n;  Get here when another extent is required.\n;\nPOSITN2\tPUSH\tB\n\tPUSH\tD\n\tCALL\tCLOSEIT\t;close current extent.\n\tPOP\tD\n\tPOP\tB\n\tMVI\tL,3\t;prepare for error.\n\tLDA\tSTATUS\n\tINR\tA\n\tJZ\tPOSITN4\t;close error.\n\tLXI\tH,12\t;put desired extent into fcb now.\n\tDAD\tD\n\tMOV\tM,C\n\tLXI\tH,14\t;and store extra extent byte 's2'.\n\tDAD\tD\n\tMOV\tM,B\n\tCALL\tOPENIT\t;try and get this extent.\n\tLDA\tSTATUS\t;was it there?\n\tINR\tA\n\tJNZ\tPOSITN3\n\tPOP\tB\t;no. can we create a new one (writing?).\n\tPUSH\tB\n\tMVI\tL,4\t;prepare for error.\n\tINR\tC\n\tJZ\tPOSITN4\t;nope, reading unwritten space error.\n\tCALL\tGETEMPTY;yes we can, try to find space.\n\tMVI\tL,5\t;prepare for error.\n\tLDA\tSTATUS\n\tINR\tA\n\tJZ\tPOSITN4\t;out of space?\n;\n;   Normal return location. Clear error code and return.\n;\nPOSITN3\tPOP\tB\t;restore stack.\n\tXRA\tA\t;and clear error code byte.\n\tJMP\tSETSTAT\n;\n;   Error. Set the 's2' byte to indicate this (why?).\n;\nPOSITN4\tPUSH\tH\n\tCALL\tGETS2\n\tMVI\tM,0C0H\n\tPOP\tH\n;\n;   Return with error code (presently in L).\n;\nPOSITN5\tPOP\tB\n\tMOV\tA,L\t;get error code.\n\tSTA\tSTATUS\n\tJMP\tSETS2B7\n;\n;   Read a random record.\n;\nREADRAN\tMVI\tC,0FFH\t;set 'read' status.\n\tCALL\tPOSITION;position the file to proper record.\n\tCZ\tRDSEQ1\t;and read it as usual (if no errors).\n\tRET\n;\n;   Write to a random record.\n;\nWRITERAN:MVI\tC,0\t;set 'writing' flag.\n\tCALL\tPOSITION;position the file to proper record.\n\tCZ\tWTSEQ1\t;and write as usual (if no errors).\n\tRET\n;\n;   Compute the random record number. Enter with (HL) pointing\n; to a fcb an (DE) contains a relative location of a record\n; number. On exit, (C) contains the 'r0' byte, (B) the 'r1'\n; byte, and (A) the 'r2' byte.\n;\n;   On return, the zero flag is set if the record is within\n; bounds. Otherwise, an overflow occured.\n;\nCOMPRAND:XCHG\t\t;save fcb pointer in (DE).\n\tDAD\tD\t;compute relative position of record #.\n\tMOV\tC,M\t;get record number into (BC).\n\tMVI\tB,0\n\tLXI\tH,12\t;now get extent.\n\tDAD\tD\n\tMOV\tA,M\t;compute (BC)=(record #)+(extent)*128.\n\tRRC\t\t;move lower bit into bit 7.\n\tANI\t80H\t;and ignore all other bits.\n\tADD\tC\t;add to our record number.\n\tMOV\tC,A\n\tMVI\tA,0\t;take care of any carry.\n\tADC\tB\n\tMOV\tB,A\n\tMOV\tA,M\t;now get the upper bits of extent into\n\tRRC\t\t;bit positions 0-3.\n\tANI\t0FH\t;and ignore all others.\n\tADD\tB\t;add this in to 'r1' byte.\n\tMOV\tB,A\n\tLXI\tH,14\t;get the 's2' byte (extra extent).\n\tDAD\tD\n\tMOV\tA,M\n\tADD\tA\t;and shift it left 4 bits (bits 4-7).\n\tADD\tA\n\tADD\tA\n\tADD\tA\n\tPUSH\tPSW\t;save carry flag (bit 0 of flag byte).\n\tADD\tB\t;now add extra extent into 'r1'.\n\tMOV\tB,A\n\tPUSH\tPSW\t;and save carry (overflow byte 'r2').\n\tPOP\tH\t;bit 0 of (L) is the overflow indicator.\n\tMOV\tA,L\n\tPOP\tH\t;and same for first carry flag.\n\tORA\tL\t;either one of these set?\n\tANI\t01H\t;only check the carry flags.\n\tRET\n;\n;   Routine to setup the fcb (bytes 'r0', 'r1', 'r2') to\n; reflect the last record used for a random (or other) file.\n; This reads the directory and looks at all extents computing\n; the largerst record number for each and keeping the maximum\n; value only. Then 'r0', 'r1', and 'r2' will reflect this\n; maximum record number. This is used to compute the space used\n; by a random file.\n;\nRANSIZE\tMVI\tC,12\t;look thru directory for first entry with\n\tCALL\tFINDFST\t;this name.\n\tLHLD\tPARAMS\t;zero out the 'r0, r1, r2' bytes.\n\tLXI\tD,33\n\tDAD\tD\n\tPUSH\tH\n\tMOV\tM,D\t;note that (D)=0.\n\tINX\tH\n\tMOV\tM,D\n\tINX\tH\n\tMOV\tM,D\nRANSIZ1\tCALL\tCKFILPOS;is there an extent to process?\n\tJZ\tRANSIZ3\t;no, we are done.\n\tCALL\tFCB2HL\t;set (HL) pointing to proper fcb in dir.\n\tLXI\tD,15\t;point to last record in extent.\n\tCALL\tCOMPRAND;and compute random parameters.\n\tPOP\tH\n\tPUSH\tH\t;now check these values against those\n\tMOV\tE,A\t;already in fcb.\n\tMOV\tA,C\t;the carry flag will be set if those\n\tSUB\tM\t;in the fcb represent a larger size than\n\tINX\tH\t;this extent does.\n\tMOV\tA,B\n\tSBB\tM\n\tINX\tH\n\tMOV\tA,E\n\tSBB\tM\n\tJC\tRANSIZ2\n\tMOV\tM,E\t;we found a larger (in size) extent.\n\tDCX\tH\t;stuff these values into fcb.\n\tMOV\tM,B\n\tDCX\tH\n\tMOV\tM,C\nRANSIZ2\tCALL\tFINDNXT\t;now get the next extent.\n\tJMP\tRANSIZ1\t;continue til all done.\nRANSIZ3\tPOP\tH\t;we are done, restore the stack and\n\tRET\t\t;return.\n;\n;   Function to return the random record position of a given\n; file which has been read in sequential mode up to now.\n;\nSETRAN\tLHLD\tPARAMS\t;point to fcb.\n\tLXI\tD,32\t;and to last used record.\n\tCALL\tCOMPRAND;compute random position.\n\tLXI\tH,33\t;now stuff these values into fcb.\n\tDAD\tD\n\tMOV\tM,C\t;move 'r0'.\n\tINX\tH\n\tMOV\tM,B\t;and 'r1'.\n\tINX\tH\n\tMOV\tM,A\t;and lastly 'r2'.\n\tRET\n;\n;   This routine select the drive specified in (ACTIVE) and\n; update the login vector and bitmap table if this drive was\n; not already active.\n;\nLOGINDRV:LHLD\tLOGIN\t;get the login vector.\n\tLDA\tACTIVE\t;get the default drive.\n\tMOV\tC,A\n\tCALL\tSHIFTR\t;position active bit for this drive\n\tPUSH\tH\t;into bit 0.\n\tXCHG\n\tCALL\tSELECT\t;select this drive.\n\tPOP\tH\n\tCZ\tSLCTERR\t;valid drive?\n\tMOV\tA,L\t;is this a newly activated drive?\n\tRAR\n\tRC\n\tLHLD\tLOGIN\t;yes, update the login vector.\n\tMOV\tC,L\n\tMOV\tB,H\n\tCALL\tSETBIT\n\tSHLD\tLOGIN\t;and save.\n\tJMP\tBITMAP\t;now update the bitmap.\n;\n;   Function to set the active disk number.\n;\nSETDSK\tLDA\tEPARAM\t;get parameter passed and see if this\n\tLXI\tH,ACTIVE;represents a change in drives.\n\tCMP\tM\n\tRZ\n\tMOV\tM,A\t;yes it does, log it in.\n\tJMP\tLOGINDRV\n;\n;   This is the 'auto disk select' routine. The firsst byte\n; of the fcb is examined for a drive specification. If non\n; zero then the drive will be selected and loged in.\n;\nAUTOSEL\tMVI\tA,0FFH\t;say 'auto-select activated'.\n\tSTA\tAUTO\n\tLHLD\tPARAMS\t;get drive specified.\n\tMOV\tA,M\n\tANI\t1FH\t;look at lower 5 bits.\n\tDCR\tA\t;adjust for (1=A, 2=B) etc.\n\tSTA\tEPARAM\t;and save for the select routine.\n\tCPI\t1EH\t;check for 'no change' condition.\n\tJNC\tAUTOSL1\t;yes, don't change.\n\tLDA\tACTIVE\t;we must change, save currently active\n\tSTA\tOLDDRV\t;drive.\n\tMOV\tA,M\t;and save first byte of fcb also.\n\tSTA\tAUTOFLAG;this must be non-zero.\n\tANI\t0E0H\t;whats this for (bits 6,7 are used for\n\tMOV\tM,A\t;something)?\n\tCALL\tSETDSK\t;select and log in this drive.\nAUTOSL1\tLDA\tUSERNO\t;move user number into fcb.\n\tLHLD\tPARAMS\t;(* upper half of first byte *)\n\tORA\tM\n\tMOV\tM,A\n\tRET\t\t;and return (all done).\n;\n;   Function to return the current cp/m version number.\n;\nGETVER\tMVI\tA,022h\t;version 2.2\n\tJMP\tSETSTAT\n;\n;   Function to reset the disk system.\n;\nRSTDSK\tLXI\tH,0\t;clear write protect status and log\n\tSHLD\tWRTPRT\t;in vector.\n\tSHLD\tLOGIN\n\tXRA\tA\t;select drive 'A'.\n\tSTA\tACTIVE\n\tLXI\tH,TBUFF\t;setup default dma address.\n\tSHLD\tUSERDMA\n\tCALL\tDEFDMA\n\tJMP\tLOGINDRV;now log in drive 'A'.\n;\n;   Function to open a specified file.\n;\nOPENFIL\tCALL\tCLEARS2\t;clear 's2' byte.\n\tCALL\tAUTOSEL\t;select proper disk.\n\tJMP\tOPENIT\t;and open the file.\n;\n;   Function to close a specified file.\n;\nCLOSEFIL:CALL\tAUTOSEL\t;select proper disk.\n\tJMP\tCLOSEIT\t;and close the file.\n;\n;   Function to return the first occurence of a specified file\n; name. If the first byte of the fcb is '?' then the name will\n; not be checked (get the first entry no matter what).\n;\nGETFST\tMVI\tC,0\t;prepare for special search.\n\tXCHG\n\tMOV\tA,M\t;is first byte a '?'?\n\tCPI\t'?'\n\tJZ\tGETFST1\t;yes, just get very first entry (zero length match).\n\tCALL\tSETEXT\t;get the extension byte from fcb.\n\tMOV\tA,M\t;is it '?'? if yes, then we want\n\tCPI\t'?'\t;an entry with a specific 's2' byte.\n\tCNZ\tCLEARS2\t;otherwise, look for a zero 's2' byte.\n\tCALL\tAUTOSEL\t;select proper drive.\n\tMVI\tC,15\t;compare bytes 0-14 in fcb (12&13 excluded).\nGETFST1\tCALL\tFINDFST\t;find an entry and then move it into\n\tJMP\tMOVEDIR\t;the users dma space.\n;\n;   Function to return the next occurence of a file name.\n;\nGETNXT\tLHLD\tSAVEFCB\t;restore pointers. note that no\n\tSHLD\tPARAMS\t;other dbos calls are allowed.\n\tCALL\tAUTOSEL\t;no error will be returned, but the\n\tCALL\tFINDNXT\t;results will be wrong.\n\tJMP\tMOVEDIR\n;\n;   Function to delete a file by name.\n;\nDELFILE\tCALL\tAUTOSEL\t;select proper drive.\n\tCALL\tERAFILE\t;erase the file.\n\tJMP\tSTSTATUS;set status and return.\n;\n;   Function to execute a sequential read of the specified\n; record number.\n;\nREADSEQ\tCALL\tAUTOSEL\t;select proper drive then read.\n\tJMP\tRDSEQ\n;\n;   Function to write the net sequential record.\n;\nWRTSEQ\tCALL\tAUTOSEL\t;select proper drive then write.\n\tJMP\tWTSEQ\n;\n;   Create a file function.\n;\nFCREATE\tCALL\tCLEARS2\t;clear the 's2' byte on all creates.\n\tCALL\tAUTOSEL\t;select proper drive and get the next\n\tJMP\tGETEMPTY;empty directory space.\n;\n;   Function to rename a file.\n;\nRENFILE\tCALL\tAUTOSEL\t;select proper drive and then switch\n\tCALL\tCHGNAMES;file names.\n\tJMP\tSTSTATUS\n;\n;   Function to return the login vector.\n;\nGETLOG\tLHLD\tLOGIN\n\tJMP\tGETPRM1\n;\n;   Function to return the current disk assignment.\n;\nGETCRNT\tLDA\tACTIVE\n\tJMP\tSETSTAT\n;\n;   Function to set the dma address.\n;\nPUTDMA\tXCHG\n\tSHLD\tUSERDMA\t;save in our space and then get to\n\tJMP\tDEFDMA\t;the bios with this also.\n;\n;   Function to return the allocation vector.\n;\nGETALOC\tLHLD\tALOCVECT\n\tJMP\tGETPRM1\n;\n;   Function to return the read-only status vector.\n;\nGETROV\tLHLD\tWRTPRT\n\tJMP\tGETPRM1\n;\n;   Function to set the file attributes (read-only, system).\n;\nSETATTR\tCALL\tAUTOSEL\t;select proper drive then save attributes.\n\tCALL\tSAVEATTR\n\tJMP\tSTSTATUS\n;\n;   Function to return the address of the disk parameter block\n; for the current drive.\n;\nGETPARM\tLHLD\tDISKPB\nGETPRM1\tSHLD\tSTATUS\n\tRET\n;\n;   Function to get or set the user number. If (E) was (FF)\n; then this is a request to return the current user number.\n; Else set the user number from (E).\n;\nGETUSER\tLDA\tEPARAM\t;get parameter.\n\tCPI\t0FFH\t;get user number?\n\tJNZ\tSETUSER\n\tLDA\tUSERNO\t;yes, just do it.\n\tJMP\tSETSTAT\nSETUSER\tANI\t1FH\t;no, we should set it instead. keep low\n\tSTA\tUSERNO\t;bits (0-4) only.\n\tRET\n;\n;   Function to read a random record from a file.\n;\nRDRANDOM:CALL\tAUTOSEL\t;select proper drive and read.\n\tJMP\tREADRAN\n;\n;   Function to compute the file size for random files.\n;\nWTRANDOM:CALL\tAUTOSEL\t;select proper drive and write.\n\tJMP\tWRITERAN\n;\n;   Function to compute the size of a random file.\n;\nFILESIZE:CALL\tAUTOSEL\t;select proper drive and check file length\n\tJMP\tRANSIZE\n;\n;   Function #37. This allows a program to log off any drives.\n; On entry, set (DE) to contain a word with bits set for those\n; drives that are to be logged off. The log-in vector and the\n; write protect vector will be updated. This must be a M/PM\n; special function.\n;\nLOGOFF\tLHLD\tPARAMS\t;get drives to log off.\n\tMOV\tA,L\t;for each bit that is set, we want\n\tCMA\t\t;to clear that bit in (LOGIN)\n\tMOV\tE,A\t;and (WRTPRT).\n\tMOV\tA,H\n\tCMA\n\tLHLD\tLOGIN\t;reset the login vector.\n\tANA\tH\n\tMOV\tD,A\n\tMOV\tA,L\n\tANA\tE\n\tMOV\tE,A\n\tLHLD\tWRTPRT\n\tXCHG\n\tSHLD\tLOGIN\t;and save.\n\tMOV\tA,L\t;now do the write protect vector.\n\tANA\tE\n\tMOV\tL,A\n\tMOV\tA,H\n\tANA\tD\n\tMOV\tH,A\n\tSHLD\tWRTPRT\t;and save. all done.\n\tRET\n;\n;   Get here to return to the user.\n;\nGOBACK\tLDA\tAUTO\t;was auto select activated?\n\tORA\tA\n\tJZ\tGOBACK1\n\tLHLD\tPARAMS\t;yes, but was a change made?\n\tMVI\tM,0\t;(* reset first byte of fcb *)\n\tLDA\tAUTOFLAG\n\tORA\tA\n\tJZ\tGOBACK1\n\tMOV\tM,A\t;yes, reset first byte properly.\n\tLDA\tOLDDRV\t;and get the old drive and select it.\n\tSTA\tEPARAM\n\tCALL\tSETDSK\nGOBACK1\tLHLD\tUSRSTACK;reset the users stack pointer.\n\tSPHL\n\tLHLD\tSTATUS\t;get return status.\n\tMOV\tA,L\t;force version 1.4 compatability.\n\tMOV\tB,H\n\tRET\t\t;and go back to user.\n;\n;   Function #40. This is a special entry to do random i/o.\n; For the case where we are writing to unused disk space, this\n; space will be zeroed out first. This must be a M/PM special\n; purpose function, because why would any normal program even\n; care about the previous contents of a sector about to be\n; written over.\n;\nWTSPECL\tCALL\tAUTOSEL\t;select proper drive.\n\tMVI\tA,2\t;use special write mode.\n\tSTA\tMODE\n\tMVI\tC,0\t;set write indicator.\n\tCALL\tPOSITN1\t;position the file.\n\tCZ\tWTSEQ1\t;and write (if no errors).\n\tRET\n;\n;**************************************************************\n;*\n;*     BDOS data storage pool.\n;*\n;**************************************************************\n;\nEMPTYFCB:DB\t0E5H\t;empty directory segment indicator.\nWRTPRT\tDW\t0\t;write protect status for all 16 drives.\nLOGIN\tDW\t0\t;drive active word (1 bit per drive).\nUSERDMA\tDW\t080H\t;user's dma address (defaults to 80h).\n;\n;   Scratch areas from parameter block.\n;\nSCRATCH1:DW\t0\t;relative position within dir segment for file (0-3).\nSCRATCH2:DW\t0\t;last selected track number.\nSCRATCH3:DW\t0\t;last selected sector number.\n;\n;   Disk storage areas from parameter block.\n;\nDIRBUF\tDW\t0\t;address of directory buffer to use.\nDISKPB\tDW\t0\t;contains address of disk parameter block.\nCHKVECT\tDW\t0\t;address of check vector.\nALOCVECT:DW\t0\t;address of allocation vector (bit map).\n;\n;   Parameter block returned from the bios.\n;\nSECTORS\tDW\t0\t;sectors per track from bios.\nBLKSHFT\tDB\t0\t;block shift.\nBLKMASK\tDB\t0\t;block mask.\nEXTMASK\tDB\t0\t;extent mask.\nDSKSIZE\tDW\t0\t;disk size from bios (number of blocks-1).\nDIRSIZE\tDW\t0\t;directory size.\nALLOC0\tDW\t0\t;storage for first bytes of bit map (dir space used).\nALLOC1\tDW\t0\nOFFSET\tDW\t0\t;first usable track number.\nXLATE\tDW\t0\t;sector translation table address.\n;\n;\nCLOSEFLG:DB\t0\t;close flag (=0ffh is extent written ok).\nRDWRTFLG:DB\t0\t;read/write flag (0ffh=read, 0=write).\nFNDSTAT\tDB\t0\t;filename found status (0=found first entry).\nMODE\tDB\t0\t;I/o mode select (0=random, 1=sequential, 2=special random).\nEPARAM\tDB\t0\t;storage for register (E) on entry to bdos.\nRELBLOCK:DB\t0\t;relative position within fcb of block number written.\nCOUNTER\tDB\t0\t;byte counter for directory name searches.\nSAVEFCB\tDW\t0,0\t;save space for address of fcb (for directory searches).\nBIGDISK\tDB\t0\t;if =0 then disk is > 256 blocks long.\nAUTO\tDB\t0\t;if non-zero, then auto select activated.\nOLDDRV\tDB\t0\t;on auto select, storage for previous drive.\nAUTOFLAG:DB\t0\t;if non-zero, then auto select changed drives.\nSAVNXT\tDB\t0\t;storage for next record number to access.\nSAVEXT\tDB\t0\t;storage for extent number of file.\nSAVNREC\tDW\t0\t;storage for number of records in file.\nBLKNMBR\tDW\t0\t;block number (physical sector) used within a file or logical sector.\nLOGSECT\tDW\t0\t;starting logical (128 byte) sector of block (physical sector).\nFCBPOS\tDB\t0\t;relative position within buffer for fcb of file of interest.\nFILEPOS\tDW\t0\t;files position within directory (0 to max entries -1).\n;\n;   Disk directory buffer checksum bytes. One for each of the\n; 16 possible drives.\n;\nCKSUMTBL:DB\t0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n;\n;   Extra space ?\n;\n\tDB\t0,0,0,0\n;\n;**************************************************************\n;*\n;*        B I O S   J U M P   T A B L E\n;*\n;**************************************************************\n;\nBOOT\tJMP\t0\t;NOTE WE USE FAKE DESTINATIONS\nWBOOT\tJMP\t0\nCONST\tJMP\t0\nCONIN\tJMP\t0\nCONOUT\tJMP\t0\nLIST\tJMP\t0\nPUNCH\tJMP\t0\nREADER\tJMP\t0\nHOME\tJMP\t0\nSELDSK\tJMP\t0\nSETTRK\tJMP\t0\nSETSEC\tJMP\t0\nSETDMA\tJMP\t0\nREAD\tJMP\t0\nWRITE\tJMP\t0\nPRSTAT\tJMP\t0\nSECTRN\tJMP\t0\n;\n;*\n;******************   E N D   O F   C P / M   *****************\n;*\n\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-2693/test.sh",
    "content": "#!/usr/bin/bash\n\ndotnet restore\ndotnet build\ndotnet run -file cpm22.asm\nif [[ \"$?\" != \"0\" ]]\nthen\n    echo \"Issue 2693 test failed.\"\n    exit 1\nfi\n\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-3079/Arithmetic.g4",
    "content": "\n// Template generated code from Antlr4BuildTasks.dotnet-antlr v 2.2\n\ngrammar Arithmetic;\n\nfile : expression (SEMI expression)* EOF;\nexpression : expression POW expression | expression (TIMES | DIV) expression | expression (PLUS | MINUS) expression | LPAREN expression RPAREN | (PLUS | MINUS)* atom ;\natom : scientific | variable ;\nscientific : SCIENTIFIC_NUMBER ;\nvariable : VARIABLE ;\n\nVARIABLE : VALID_ID_START VALID_ID_CHAR* ;\nSCIENTIFIC_NUMBER : NUMBER (E SIGN? UNSIGNED_INTEGER)? ;\nLPAREN : '(' ;\nRPAREN : ')' ;\nPLUS : '+' ;\nMINUS : '-' ;\nTIMES : '*' ;\nDIV : '/' ;\nGT : '>' ;\nLT : '<' ;\nEQ : '=' ;\nPOINT : '.' ;\nPOW : '^' ;\nSEMI : ';' ;\nWS : [ \\r\\n\\t] + -> channel(HIDDEN) ;\n\nfragment VALID_ID_START : ('a' .. 'z') | ('A' .. 'Z') | '_' ;\nfragment VALID_ID_CHAR : VALID_ID_START | ('0' .. '9') ;\nfragment NUMBER : ('0' .. '9') + ('.' ('0' .. '9') +)? ;\nfragment UNSIGNED_INTEGER : ('0' .. '9')+ ;\nfragment E : 'E' | 'e' ;\nfragment SIGN : ('+' | '-') ;\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-3079/ErrorListener.cs",
    "content": "// Template generated code from Antlr4BuildTasks.dotnet-antlr v 2.2\n\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Misc;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\npublic class ErrorListener<S> : ConsoleErrorListener<S>\n{\n    public bool had_error;\n\n    public override void SyntaxError(TextWriter output, IRecognizer recognizer, S offendingSymbol, int line,\n        int col, string msg, RecognitionException e)\n    {\n        had_error = true;\n        base.SyntaxError(output, recognizer, offendingSymbol, line, col, msg, e);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-3079/Program.cs",
    "content": "// Template generated code from Antlr4BuildTasks.dotnet-antlr v 2.2\n\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Tree;\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.CompilerServices;\n\npublic class Program\n{\n    public static Parser Parser { get; set; }\n    public static Lexer Lexer { get; set; }\n    public static ITokenStream TokenStream { get; set; }\n    public static IParseTree Tree { get; set; }\n    public static IParseTree Parse(string input)\n    {\n        var str = new AntlrInputStream(input);\n        var lexer = new ArithmeticLexer(str);\n        Lexer = lexer;\n        var tokens = new CommonTokenStream(lexer);\n        TokenStream = tokens;\n        var parser = new ArithmeticParser(tokens);\n        Parser = parser;\n        var tree = parser.file();\n        Tree = tree;\n        return tree;\n    }\n\n    static void Main(string[] args)\n    {\n        bool show_tree = false;\n        bool show_tokens = false;\n        string file_name = null;\n        string input = null;\n        for (int i = 0; i < args.Length; ++i)\n        {\n            if (args[i].Equals(\"-tokens\"))\n            {\n                show_tokens = true;\n                continue;\n            }\n            else if (args[i].Equals(\"-tree\"))\n            {\n                show_tree = true;\n                continue;\n            }\n            else if (args[i].Equals(\"-input\"))\n                input = args[++i];\n            else if (args[i].Equals(\"-file\"))\n                file_name = args[++i];\n        }\n        ICharStream str = null;\n        if (input == null && file_name == null)\n        {\n            StringBuilder sb = new StringBuilder();\n            int ch;\n            while ((ch = System.Console.Read()) != -1)\n            {\n                sb.Append((char)ch);\n            }\n            input = sb.ToString();\n            \nstr = CharStreams.fromString(input);\n        } else if (input != null)\n        {\n            str = CharStreams.fromString(input);\n        } else if (file_name != null)\n        {\n            str = CharStreams.fromPath(file_name);\n        }\n        var lexer = new ArithmeticLexer(str);\n        if (show_tokens)\n        {\n            StringBuilder new_s = new StringBuilder();\n            for (int i = 0; ; ++i)\n            {\n                var ro_token = lexer.NextToken();\n                var token = (CommonToken)ro_token;\n                token.TokenIndex = i;\n                new_s.AppendLine(token.ToString());\n                if (token.Type == Antlr4.Runtime.TokenConstants.EOF)\n                    break;\n            }\n            System.Console.Error.WriteLine(new_s.ToString());\n            lexer.Reset();\n        }\n        var tokens = new CommonTokenStream(lexer);\n        var parser = new ArithmeticParser(tokens);\n        var listener_lexer = new ErrorListener<int>();\n        var listener_parser = new ErrorListener<IToken>();\n        lexer.AddErrorListener(listener_lexer);\n        parser.AddErrorListener(listener_parser);\n        var tree = parser.file();\n        if (listener_lexer.had_error || listener_parser.had_error)\n        {\n            System.Console.Error.WriteLine(\"parse failed.\");\n        }\n        else\n        {\n            System.Console.Error.WriteLine(\"parse succeeded.\");\n        }\n        if (show_tree)\n        {\n            System.Console.Error.WriteLine(tree.ToStringTree(parser));\n        }\n        System.Environment.Exit(listener_lexer.had_error || listener_parser.had_error ? 1 : 0);\n    }\n}\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-3079/Test.csproj",
    "content": "﻿<!-- Template generated code from Antlr4BuildTasks.dotnet-antlr v 2.2 -->\n<Project Sdk=\"Microsoft.NET.Sdk\" >\n  <PropertyGroup>\n    <TargetFramework>net5.0</TargetFramework>\n    <OutputType>Exe</OutputType>\n  </PropertyGroup>\n  \n  <ItemGroup>\n    <Antlr4 Include=\"Arithmetic.g4\" />\n  </ItemGroup>\n  \n  <PropertyGroup>\n    <AntlrToolPath>../../../../tool/target/antlr4-*-SNAPSHOT-complete.jar</AntlrToolPath>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <ProjectReference Include=\"../../src/Antlr4.csproj\" />\n    <PackageReference Include=\"Antlr4BuildTasks\" Version = \"8.13\" PrivateAssets=\"all\" />\n  </ItemGroup>\n\n  <PropertyGroup>\n    <RestoreProjectStyle>PackageReference</RestoreProjectStyle>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|AnyCPU'\" >\n    <NoWarn>1701;1702;3021</NoWarn>\n  </PropertyGroup>\n\n  <PropertyGroup>\n    <!--\n      need the CData since this blob is just going to\n      be embedded in a mini batch file by studio/msbuild\n    -->\n    <MyTester><![CDATA[\n\nset ERR=0\nfor %%G in (..\\examples\\*) do (\n  setlocal EnableDelayedExpansion\n  set FILE=%%G\n  set X1=%%~xG\n  set X2=%%~nG\n  set X3=%%~pG\n  if !X1! neq .errors (\n    echo !FILE!\n    cat !FILE! | bin\\Debug\\net5.0\\Test.exe\n    if not exist !FILE!.errors (\n      if ERRORLEVEL 1 set ERR=1\n    ) else (\n      echo Expected.\n    )\n  )\n)\nEXIT %ERR%\n\n]]></MyTester>\n</PropertyGroup>\n\n  <Target Name=\"Test\" >\n    <Message Text=\"testing\" />\n    <Exec Command=\"$(MyTester)\" >\n       <Output TaskParameter=\"ExitCode\" PropertyName =\"ErrorCode\" />\n    </Exec>\n    <Message Importance=\"high\" Text=\"$(ErrorCode)\"/>\n  </Target>\n\n</Project>\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-3079/Test.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.31019.35\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Test\", \"Test.csproj\", \"{1B229E17-E0E5-4D3B-8978-A4E61B9233E5}\"\nEndProject\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Antlr4\", \"..\\..\\src\\Antlr4.csproj\", \"{95247929-4C60-4CDF-B202-1BAE1C12AA57}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|Any CPU = Debug|Any CPU\n\t\tRelease|Any CPU = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{1B229E17-E0E5-4D3B-8978-A4E61B9233E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{1B229E17-E0E5-4D3B-8978-A4E61B9233E5}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{1B229E17-E0E5-4D3B-8978-A4E61B9233E5}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{1B229E17-E0E5-4D3B-8978-A4E61B9233E5}.Release|Any CPU.Build.0 = Release|Any CPU\n\t\t{95247929-4C60-4CDF-B202-1BAE1C12AA57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n\t\t{95247929-4C60-4CDF-B202-1BAE1C12AA57}.Debug|Any CPU.Build.0 = Debug|Any CPU\n\t\t{95247929-4C60-4CDF-B202-1BAE1C12AA57}.Release|Any CPU.ActiveCfg = Release|Any CPU\n\t\t{95247929-4C60-4CDF-B202-1BAE1C12AA57}.Release|Any CPU.Build.0 = Release|Any CPU\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {4819731D-3C62-4CFA-A99C-09103728C086}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-3079/readme.md",
    "content": "# How to test Issue 3079\n\n1) Build the Antlr Tool first.\n2) `bash test.sh` in this directory.\n\nNB: The CSharp runtime source is modified by the test.sh script to\nchange \"debug = true;\" for ParserATNSimulator.cs. There is no way to\nchange the value of the static readonly variable using System.Reflection\nafter the static initializer for the class has loaded. This is why\nit is change in the source here for this test and only this test.\n"
  },
  {
    "path": "runtime/CSharp/tests/issue-3079/test.sh",
    "content": "#\n\ncat ../../src/Atn/ParserATNSimulator.cs > ParserATNSimulator.save\ncat ParserATNSimulator.save | sed 's/bool debug = false;/bool debug = true;/' > ../../src/Atn/ParserATNSimulator.cs\ndotnet restore\ndotnet build\ndotnet run -input \"1+2\"\nif [[ \"$?\" != \"0\" ]]\nthen\n    echo \"Issue 2693 test failed.\"\n    exit 1\nelse\n    echo \"Test passed--did not crash.\"\nfi\n"
  },
  {
    "path": "runtime/Cpp/CMakeLists.txt",
    "content": "# -*- mode:cmake -*-\ncmake_minimum_required (VERSION 3.15)\n# 3.14 needed because of FetchContent\n# 3.15 needed to avid spew of warnings related to overriding cl command line flags\n\nset(CMAKE_MACOSX_RPATH OFF)\n\nenable_testing()\n\n# Detect build type, fallback to release and throw a warning if use didn't specify any\nif(NOT CMAKE_BUILD_TYPE)\n  message(WARNING \"Build type not set, falling back to Release mode.\n To specify build type use:\n -DCMAKE_BUILD_TYPE=<mode> where <mode> is Debug or Release.\")\n  set(CMAKE_BUILD_TYPE \"Release\" CACHE STRING\n       \"Choose the type of build, options are: Debug Release.\"\n       FORCE)\nendif(NOT CMAKE_BUILD_TYPE)\n\nif(NOT WITH_DEMO)\n  message(STATUS \"Building without demo. To enable demo build use: -DWITH_DEMO=True\")\n  set(WITH_DEMO False CACHE STRING\n    \"Chose to build with or without demo executable\"\n    FORCE)\nendif(NOT WITH_DEMO)\n\noption(WITH_LIBCXX \"Building with clang++ and libc++(in Linux). To enable with: -DWITH_LIBCXX=On\" Off)\noption(WITH_STATIC_CRT \"(Visual C++) Enable to statically link CRT, which avoids requiring users to install the redistribution package.\n To disable with: -DWITH_STATIC_CRT=Off\" On)\noption(DISABLE_WARNINGS \"Suppress compiler warnings for all built ANTLR targets\" OFF)\n \ncmake_policy(SET CMP0091 NEW) # Enable use of CMAKE_MSVC_RUNTIME_LIBRARY\nif(WITH_STATIC_CRT)\n  set(CMAKE_MSVC_RUNTIME_LIBRARY \"MultiThreaded$<$<CONFIG:Debug>:Debug>\")\nelse()\n  set(CMAKE_MSVC_RUNTIME_LIBRARY \"MultiThreaded$<$<CONFIG:Debug>:Debug>DLL\")\nendif(WITH_STATIC_CRT)\n\nproject(LIBANTLR4)\n\nif(APPLE)\n  find_library(COREFOUNDATION_LIBRARY CoreFoundation)\nendif()\n\nfile(STRINGS \"VERSION\" ANTLR_VERSION)\n\nif(WITH_DEMO)\n  # Java is not necessary if building without demos.\n  find_package(Java COMPONENTS Runtime REQUIRED)\n\n  if(NOT ANTLR_JAR_LOCATION)\n    message(FATAL_ERROR \"Missing antlr4.jar location. You can specify it's path using: -DANTLR_JAR_LOCATION=<path>\")\n  else()\n    get_filename_component(ANTLR_NAME ${ANTLR_JAR_LOCATION} NAME_WE)\n    if(NOT EXISTS \"${ANTLR_JAR_LOCATION}\")\n      message(FATAL_ERROR \"Unable to find ${ANTLR_NAME} in ${ANTLR_JAR_LOCATION}\")\n    else()\n      message(STATUS \"Found ${ANTLR_NAME}: ${ANTLR_JAR_LOCATION}\")\n    endif()\n  endif()\nendif(WITH_DEMO)\n\nif(CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n  set(MY_CXX_WARNING_FLAGS \"  /W4\")\n\n  if(DISABLE_WARNINGS)\n    set(MY_CXX_WARNING_FLAGS \"  /w\")\n  endif()\nelse()\n  set(MY_CXX_WARNING_FLAGS \"  -Wall -pedantic -W\")\n\n  if(DISABLE_WARNINGS)\n    set(MY_CXX_WARNING_FLAGS \"  -w\")\n  endif()\nendif()\n\n# Define USE_UTF8_INSTEAD_OF_CODECVT macro.\n# set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -DUSE_UTF8_INSTEAD_OF_CODECVT\")\n\n# Initialize CXXFLAGS.\nif(NOT DEFINED CMAKE_CXX_STANDARD)\n  # only set CMAKE_CXX_STANDARD if not already set\n  # this allows the standard to be set by the caller, for example with -DCMAKE_CXX_STANDARD:STRING=17\n  set(CMAKE_CXX_STANDARD 17)\nendif()\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nset(CMAKE_CXX_FLAGS                  \"${CMAKE_CXX_FLAGS} ${MY_CXX_WARNING_FLAGS}\")\n\nif(CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n  set(CMAKE_CXX_FLAGS_DEBUG          \"${CMAKE_CXX_FLAGS_DEBUG} /Od /Zi /MP ${MY_CXX_WARNING_FLAGS}\")\n  set(CMAKE_CXX_FLAGS_MINSIZEREL     \"${CMAKE_CXX_FLAGS_MINSIZEREL} /O1 /Oi /Ob2 /Gy /MP /DNDEBUG ${MY_CXX_WARNING_FLAGS}\")\n  set(CMAKE_CXX_FLAGS_RELEASE        \"${CMAKE_CXX_FLAGS_RELEASE} /O2 /Oi /Ob2 /Gy /MP /DNDEBUG ${MY_CXX_WARNING_FLGAS}\")\n  set(CMAKE_CXX_FLAGS_RELWITHDEBINFO \"${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /O2 /Oi /Ob2 /Gy /MP /Zi ${MY_CXX_WARNING_FLAGS}\")\nelse()\n  set(CMAKE_CXX_FLAGS_DEBUG          \"${CMAKE_CXX_FLAGS_DEBUG} -O0 -g ${MY_CXX_WARNING_FLAGS}\")\n  set(CMAKE_CXX_FLAGS_MINSIZEREL     \"${CMAKE_CXX_FLAGS_MINSIZEREL} -Os -DNDEBUG ${MY_CXX_WARNING_FLAGS}\")\n  set(CMAKE_CXX_FLAGS_RELEASE        \"${CMAKE_CXX_FLAGS_RELEASE} -O3 -DNDEBUG ${MY_CXX_WARNING_FLGAS}\")\n  set(CMAKE_CXX_FLAGS_RELWITHDEBINFO \"${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -O2 -g ${MY_CXX_WARNING_FLAGS}\")\nendif()\n\n# Compiler-specific C++17 activation.\nif(CMAKE_CXX_COMPILER_ID MATCHES \"GNU\" OR CMAKE_CXX_COMPILER_ID MATCHES \"Intel\")\n    execute_process(\n        COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)\n    # Just g++-5.0 and greater contain <codecvt> header. (test in ubuntu)\n    if(NOT (GCC_VERSION VERSION_GREATER 5.0 OR GCC_VERSION VERSION_EQUAL 5.0))\n        message(FATAL_ERROR \"${PROJECT_NAME} requires g++ 5.0 or greater.\")\n    endif ()\nelseif (CMAKE_CXX_COMPILER_ID MATCHES \"Clang\" AND ANDROID)\n\t# Need -Os cflag and cxxflags here to work with exception handling on armeabi.\n\t# see  https://github.com/android-ndk/ndk/issues/573\n\t# and without -stdlib=libc++ cxxflags\nelseif (CMAKE_CXX_COMPILER_ID MATCHES \"Clang\" AND APPLE)\n    set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++\")\nelseif (CMAKE_CXX_COMPILER_ID MATCHES \"Clang\" AND ( CMAKE_SYSTEM_NAME MATCHES \"Linux\" OR CMAKE_SYSTEM_NAME MATCHES \"FreeBSD\") )\n    execute_process(\n        COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE CLANG_VERSION)\n    if(NOT (CLANG_VERSION VERSION_GREATER 4.2.1 OR CLANG_VERSION VERSION_EQUAL 4.2.1))\n        message(FATAL_ERROR \"${PROJECT_NAME} requires clang 4.2.1 or greater.\")\n    endif()\n    # You can use libc++ to compile this project when g++ is NOT greater than or equal to 5.0.\n    if(WITH_LIBCXX)\n        set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -stdlib=libc++\")\n    endif()\nelseif(MSVC_VERSION GREATER 1800 OR MSVC_VERSION EQUAL 1800)\n  # Visual Studio 2012+ supports C++17 features\nelseif(CMAKE_SYSTEM_NAME MATCHES \"Emscripten\")\n    set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++\")\nelse()\n    message(FATAL_ERROR \"Your C++ compiler does not support C++17.\")\nendif()\n\n\nadd_subdirectory(runtime)\nif(WITH_DEMO)\n add_subdirectory(demo)\nendif(WITH_DEMO)\n\ninclude(GNUInstallDirs)\n\n# Generate CMake Package Files only if install is active\nif (ANTLR4_INSTALL)\n\n  include(CMakePackageConfigHelpers)\n\n  if(NOT ANTLR4_CMAKE_DIR)\n    set(ANTLR4_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake CACHE STRING\n      \"Installation directory for cmake files.\" FORCE )\n  endif(NOT ANTLR4_CMAKE_DIR)\n\n  set(version_runtime_config ${PROJECT_BINARY_DIR}/antlr4-runtime-config-version.cmake)\n  set(version_generator_config ${PROJECT_BINARY_DIR}/antlr4-generator-config-version.cmake)\n  set(project_runtime_config ${PROJECT_BINARY_DIR}/antlr4-runtime-config.cmake)\n  set(project_generator_config ${PROJECT_BINARY_DIR}/antlr4-generator-config.cmake)\n  set(targets_export_name antlr4-targets)\n\n  set(ANTLR4_LIB_DIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING\n      \"Installation directory for libraries, relative to ${CMAKE_INSTALL_PREFIX}.\")\n\n  set(ANTLR4_INCLUDE_DIR ${CMAKE_INSTALL_INCLUDEDIR}/antlr4-runtime CACHE STRING\n      \"Installation directory for include files, relative to ${CMAKE_INSTALL_PREFIX}.\")\n\n  configure_package_config_file(\n    cmake/antlr4-runtime.cmake.in\n    ${project_runtime_config}\n    INSTALL_DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-runtime\n    PATH_VARS\n    ANTLR4_INCLUDE_DIR\n    ANTLR4_LIB_DIR )\n\n  configure_package_config_file(\n    cmake/antlr4-generator.cmake.in\n    ${project_generator_config}\n    INSTALL_DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-generator\n    PATH_VARS\n    ANTLR4_INCLUDE_DIR\n    ANTLR4_LIB_DIR )\n\n  write_basic_package_version_file(\n    ${version_runtime_config}\n    VERSION ${ANTLR_VERSION}\n    COMPATIBILITY SameMajorVersion )\n\n  write_basic_package_version_file(\n    ${version_generator_config}\n    VERSION ${ANTLR_VERSION}\n    COMPATIBILITY SameMajorVersion )\n\n  install(EXPORT ${targets_export_name}\n          DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-runtime )\n\n  install(FILES ${project_runtime_config}\n                ${version_runtime_config}\n          DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-runtime )\n\n  install(FILES ${project_generator_config}\n                ${version_generator_config}\n          DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-generator )\n\nendif(ANTLR4_INSTALL)\n\nif(EXISTS LICENSE.txt)\ninstall(FILES LICENSE.txt\n        DESTINATION ${CMAKE_INSTALL_DOCDIR})\nelseif(EXISTS ../../LICENSE.txt)\ninstall(FILES ../../LICENSE.txt\n    DESTINATION ${CMAKE_INSTALL_DOCDIR})\nendif()\n\ninstall(FILES README.md VERSION\n    DESTINATION ${CMAKE_INSTALL_DOCDIR})\n\nset(CPACK_PACKAGE_CONTACT \"antlr-discussion@googlegroups.com\")\nset(CPACK_PACKAGE_VERSION ${ANTLR_VERSION})\ninclude(CPack)\n"
  },
  {
    "path": "runtime/Cpp/CMakeSettings.json",
    "content": "{\n    // See https://go.microsoft.com//fwlink//?linkid=834763 for more information about this file.\n    \"configurations\": [\n        {\n            \"name\": \"x86-Debug\",\n            \"generator\": \"Ninja\",\n            \"configurationType\": \"Debug\",\n            \"inheritEnvironments\": [ \"msvc_x86\" ],\n            \"buildRoot\": \"${projectDir}\\\\out\\\\build\\\\${name}\",\n            \"installRoot\": \"${projectDir}\\\\out\\\\install\\\\${name}\",\n            \"cmakeCommandArgs\": \"\",\n            \"variables\": [\n                {\n                    \"name\": \"ANTLR4_INSTALL\",\n                    \"value\": \"1\"\n                },\n                {\n                    \"name\": \"WITH_STATIC_CRT\",\n                    \"value\": \"OFF\"\n                },\n                {\n                    \"name\": \"WITH_DEMO\",\n                    \"value\": \"OFF\"\n                }\n            ],\n            \"buildCommandArgs\": \"-v\",\n            \"ctestCommandArgs\": \"\"\n        },\n        {\n            \"name\": \"x86-Release\",\n            \"generator\": \"Ninja\",\n            \"configurationType\": \"RelWithDebInfo\",\n            \"inheritEnvironments\": [ \"msvc_x86\" ],\n            \"buildRoot\": \"${projectDir}\\\\out\\\\build\\\\${name}\",\n            \"installRoot\": \"${projectDir}\\\\out\\\\install\\\\${name}\",\n            \"cmakeCommandArgs\": \"\",\n            \"variables\": [\n                {\n                    \"name\": \"ANTLR4_INSTALL\",\n                    \"value\": \"1\"\n                },\n                {\n                    \"name\": \"WITH_STATIC_CRT\",\n                    \"value\": \"OFF\"\n                },\n                {\n                    \"name\": \"WITH_DEMO\",\n                    \"value\": \"OFF\"\n                }\n            ],\n            \"buildCommandArgs\": \"-v\",\n            \"ctestCommandArgs\": \"\"\n        },\n        {\n            \"name\": \"x64-Debug\",\n            \"generator\": \"Ninja\",\n            \"configurationType\": \"Debug\",\n            \"inheritEnvironments\": [ \"msvc_x64_x64\" ],\n            \"buildRoot\": \"${projectDir}\\\\out\\\\build\\\\${name}\",\n            \"installRoot\": \"${projectDir}\\\\out\\\\install\\\\${name}\",\n            \"cmakeCommandArgs\": \"\",\n            \"variables\": [\n                {\n                    \"name\": \"ANTLR4_INSTALL\",\n                    \"value\": \"1\"\n                },\n                {\n                    \"name\": \"WITH_STATIC_CRT\",\n                    \"value\": \"OFF\"\n                },\n                {\n                    \"name\": \"WITH_DEMO\",\n                    \"value\": \"OFF\"\n                }\n            ],\n            \"buildCommandArgs\": \"-v\",\n            \"ctestCommandArgs\": \"\"\n        },\n        {\n            \"name\": \"x64-Release\",\n            \"generator\": \"Ninja\",\n            \"configurationType\": \"RelWithDebInfo\",\n            \"inheritEnvironments\": [ \"msvc_x64_x64\" ],\n            \"buildRoot\": \"${projectDir}\\\\out\\\\build\\\\${name}\",\n            \"installRoot\": \"${projectDir}\\\\out\\\\install\\\\${name}\",\n            \"cmakeCommandArgs\": \"\",\n            \"variables\": [\n                {\n                    \"name\": \"ANTLR4_INSTALL\",\n                    \"value\": \"1\"\n                },\n                {\n                    \"name\": \"WITH_STATIC_CRT\",\n                    \"value\": \"OFF\"\n                },\n                {\n                    \"name\": \"WITH_DEMO\",\n                    \"value\": \"OFF\"\n                }\n            ],\n            \"buildCommandArgs\": \"-v\",\n            \"ctestCommandArgs\": \"\"\n        }\n    ]\n}"
  },
  {
    "path": "runtime/Cpp/README.md",
    "content": "# C++ target for ANTLR 4\n\nThis folder contains the C++ runtime support for ANTLR.  See [the canonical antlr4 repository](https://github.com/antlr/antlr4) for in depth detail about how to use ANTLR 4.\n\n## Authors and major contributors\n\nANTLR 4 is the result of substantial effort of the following people:\n\n* [Terence Parr](http://www.cs.usfca.edu/~parrt/), parrt@cs.usfca.edu\n  ANTLR project lead and supreme dictator for life\n  [University of San Francisco](http://www.usfca.edu/)\n* [Sam Harwell](http://tunnelvisionlabs.com/)\n  Tool co-author, Java and C# target)\n\nThe C++ target has been the work of the following people:\n\n* Dan McLaughlin, dan.mclaughlin@gmail.com (initial port, got code to compile)\n* David Sisson, dsisson@google.com (initial port, made the runtime C++ tests runnable)\n* [Mike Lischke](http://www.soft-gems.net), mike@lischke-online.de (brought the initial port to a working library, made most runtime tests passing)\n\n## Other contributors\n\n* Marcin Szalowicz, mszalowicz@mailplus.pl (cmake build setup)\n* Tim O'Callaghan, timo@linux.com (additional superbuild cmake pattern script)\n\n## Project Status\n\n* Building on macOS, Windows, Android and Linux\n* No errors and warnings\n* Library linking\n* Some unit tests in the macOS project, for important base classes with almost 100% code coverage.\n* All memory allocations checked\n* Simple command line demo application working on all supported platforms.\n* All runtime tests pass.\n\n### Build + Usage Notes\n\nThe minimum C++ version to compile the ANTLR C++ runtime with is C++17. The supplied projects can built the runtime either as static or dynamic library, as both 32bit and 64bit arch. The macOS project contains a target for iOS and can also be built using cmake (instead of XCode).\n\nInclude the antlr4-runtime.h umbrella header in your target application to get everything needed to use the library.\n\nIf you are compiling with cmake, the minimum version required is cmake 2.8.\nBy default, the libraries produced by the CMake build target C++17. If you want to target a different C++ standard, you can explicitly pass the standard - e.g. `-DCMAKE_CXX_STANDARD=17`.\n\n#### Compiling on Windows with Visual Studio using he Visual Studio projects\nSimply open the VS project from the runtime folder (VS 2019+) and build it.\n\n#### Compiling on Windows using cmake with Visual Studio VS2019 and later\nUse the \"Open Folder\" Feature from the File->Open->Folder menu to open the runtime/Cpp directory.\nIt will automatically use the CMake description to open up a Visual Studio Solution.\n\n#### Compiling on macOS\nEither open the included XCode project and build that or use the cmake compilation as described for linux.\n\n#### Compiling on Android\nTry run cmake -DCMAKE_ANDROID_NDK=/folder/of/android_ndkr17_and_above -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_API=14 -DCMAKE_ANDROID_ARCH_ABI=x86 -DCMAKE_ANDROID_STL_TYPE=c++_shared -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang -DCMAKE_BUILD_TYPE=Release /folder/antlr4_src_dir -G Ninja.\n\n#### Compiling on Linux\n- cd \\<antlr4-dir\\>/runtime/Cpp (this is where this readme is located)\n- mkdir build && mkdir run && cd build\n- cmake .. -DANTLR_JAR_LOCATION=full/path/to/antlr4-4.5.4-SNAPSHOT.jar -DWITH_DEMO=True\n- make\n- DESTDIR=\\<antlr4-dir\\>/runtime/Cpp/run make install\n\nIf you don't want to build the demo then replace the \"cmake .. -DANTLR_JAR_LOCATION<...>\" command in the above recipe with \"cmake ..\" without any further parameters.\nThere is another cmake script available in the subfolder cmake/ for those who prefer the superbuild cmake pattern.\n\n#### CMake Package support\nIf the CMake variable 'ANTLR4_INSTALL' is set, CMake Packages will be build and installed during the install step.\nThey expose two packages: antlr4_runtime and antlr4_generator which can be referenced to ease up the use of the\nANTLR Generator and runtime.\nUse and Sample can be found [here](cmake/Antlr4Package.md)\n"
  },
  {
    "path": "runtime/Cpp/VERSION",
    "content": "4.13.2\n"
  },
  {
    "path": "runtime/Cpp/cmake/Antlr4Package.md",
    "content": "# CMake Antlr4 Package Usage\n\n## The `antlr4-generator` Package\n\nTo use the Package you must insert a\n```cmake\nfind_package(antlr4-generator REQUIRED)\n```\nline in your `CMakeList.txt` file.\n\nThe package exposes a function `antlr4_generate` that generates the required setup to call ANTLR for a\ngiven input file during build.\n\nThe following table lists the parameters that can be used with the function:\n\nArgument# | Required  | Default | Use\n----------|-----------|---------|---\n0 | Yes | n/a | Unique target name. It is used to generate CMake Variables to reference the various outputs of the generation\n1 | Yes | n/a | Input file containing the lexer/parser definition\n2 | Yes | n/a | Type of Rules contained in the input: LEXER, PARSER or BOTH\n4 | No  | FALSE | Boolean to indicate if a listener interface should be generated\n5 | No  | FALSE | Boolean to indicate if a visitor interface should be generated\n6 | No  | none | C++ namespace in which the generated classes should be placed\n7 | No  | none | Additional files on which the input depends\n8 | No  | none | Library path to use during generation\n\nThe `ANTLR4_JAR_LOCATION` CMake variable must be set to the location where the `antlr-4*-complete.jar` generator is located. You can download the file from [here](http://www.antlr.org/download.html).\n\nAdditional options to the ANTLR4 generator can be passed in the `ANTLR4_GENERATED_OPTIONS` variable. Add the installation prefix of `antlr4-runtime` to `CMAKE_PREFIX_PATH` or set\n `antlr4-runtime_DIR` to a directory containing the files.\n\nThe following CMake variables are available following a call to `antlr4_generate`\n\nOutput variable  | Meaning\n---|---\n`ANTLR4_INCLUDE_DIR_<Target name>`       | Directory containing the generated header files\n`ANTLR4_SRC_FILES_<Target name>`         | List of generated source files\n`ANTLR4_TOKEN_FILES_<Target name>`       | List of generated token files\n`ANTLR4_TOKEN_DIRECTORY_<Target name>`  | Directory containing the generated token files\n\n#### Sample:\n```cmake\n # generate parser with visitor classes.\n # put the classes in C++ namespace 'antlrcpptest::'\n antlr4_generate(\n   antlrcpptest_parser\n   ${CMAKE_CURRENT_SOURCE_DIR}/TLexer.g4\n   LEXER\n   FALSE\n   TRUE\n   \"antlrcpptest\"\n   )\n```\n\n**Remember that the ANTLR generator requires a working Java installation on your machine!**\n\n## The `antlr4-runtime` Package\n\nTo use the Package you must insert a\n```cmake\nfind_package(antlr4-runtime REQUIRED)\n```\nline in your `CMakeList.txt` file.\n\nThe package exposes two different targets:\n\nTarget|Use\n--|--\nantlr4_shared|Shared library version of the runtime\nantlr4_static|Static library version of the runtime\n\nBoth set the following CMake variables:\n\nOutput variable  | Meaning\n---|---\n`ANTLR4_INCLUDE_DIR` | Include directory containing the runtime header files\n`ANTLR4_LIB_DIR`      | Library directory containing the runtime library files\n\n#### Sample:\n```cmake\n# add runtime include directories on this project.\ninclude_directories( ${ANTLR4_INCLUDE_DIR} )\n\n# add runtime to project dependencies\nadd_dependencies( Parsertest antlr4_shared )\n\n# add runtime to project link libraries\ntarget_link_libraries( Parsertest PRIVATE\n                       antlr4_shared)\n```\n\n### Full Example:\n```cmake\n # Bring in the required packages\n find_package(antlr4-runtime REQUIRED)\n find_package(antlr4-generator REQUIRED)\n\n # Set path to generator\n set(ANTLR4_JAR_LOCATION ${PROJECT_SOURCE_DIR}/thirdparty/antlr/antlr-4.13.2-complete.jar)\n\n # generate lexer\n antlr4_generate(\n   antlrcpptest_lexer\n   ${CMAKE_CURRENT_SOURCE_DIR}/TLexer.g4\n   LEXER\n   FALSE\n   FALSE\n   \"antlrcpptest\"\n   )\n\n # generate parser\n antlr4_generate(\n   antlrcpptest_parser\n   ${CMAKE_CURRENT_SOURCE_DIR}/TParser.g4\n   PARSER\n   FALSE\n   TRUE\n   \"antlrcpptest\"\n   \"${ANTLR4_TOKEN_FILES_antlrcpptest_lexer}\"\n   \"${ANTLR4_TOKEN_DIRECTORY_antlrcpptest_lexer}\"\n   )\n\n # add directories for generated include files\n include_directories( ${PROJECT_BINARY_DIR} ${ANTLR4_INCLUDE_DIR} ${ANTLR4_INCLUDE_DIR_antlrcpptest_lexer} ${ANTLR4_INCLUDE_DIR_antlrcpptest_parser} )\n\n # add generated source files\n add_executable( Parsertest main.cpp ${ANTLR4_SRC_FILES_antlrcpptest_lexer} ${ANTLR4_SRC_FILES_antlrcpptest_parser} )\n\n # add required runtime library\n add_dependencies( Parsertest antlr4_shared )\n\n target_link_libraries( Parsertest PRIVATE\n                        antlr4_shared)\n\n```\n\n"
  },
  {
    "path": "runtime/Cpp/cmake/ExternalAntlr4Cpp.cmake",
    "content": "cmake_minimum_required(VERSION 3.7)\n\nif(POLICY CMP0114)\n    cmake_policy(SET CMP0114 NEW)\nendif()\n\ninclude(ExternalProject)\n\nset(ANTLR4_ROOT ${CMAKE_CURRENT_BINARY_DIR}/antlr4_runtime/src/antlr4_runtime)\nset(ANTLR4_INCLUDE_DIRS ${ANTLR4_ROOT}/runtime/Cpp/runtime/src)\nset(ANTLR4_GIT_REPOSITORY https://github.com/antlr/antlr4.git)\nif(NOT DEFINED ANTLR4_TAG)\n  # Set to branch name to keep library updated at the cost of needing to rebuild after 'clean'\n  # Set to commit hash to keep the build stable and does not need to rebuild after 'clean'\n  set(ANTLR4_TAG master)\nendif()\n\n# Ensure that the include dir already exists at configure time (to avoid cmake erroring\n# on non-existent include dirs)\nfile(MAKE_DIRECTORY \"${ANTLR4_INCLUDE_DIRS}\")\n\nif(${CMAKE_GENERATOR} MATCHES \"Visual Studio.*\")\n  set(ANTLR4_OUTPUT_DIR ${ANTLR4_ROOT}/runtime/Cpp/runtime/$(Configuration))\nelseif(${CMAKE_GENERATOR} MATCHES \"Xcode.*\")\n  set(ANTLR4_OUTPUT_DIR ${ANTLR4_ROOT}/runtime/Cpp/runtime/$(CONFIGURATION))\nelse()\n  set(ANTLR4_OUTPUT_DIR ${ANTLR4_ROOT}/runtime/Cpp/runtime)\nendif()\n\nif(MSVC)\n  set(ANTLR4_STATIC_LIBRARIES\n      ${ANTLR4_OUTPUT_DIR}/antlr4-runtime-static.lib)\n  set(ANTLR4_SHARED_LIBRARIES\n      ${ANTLR4_OUTPUT_DIR}/antlr4-runtime.lib)\n  set(ANTLR4_RUNTIME_LIBRARIES\n      ${ANTLR4_OUTPUT_DIR}/antlr4-runtime.dll)\nelse()\n  set(ANTLR4_STATIC_LIBRARIES\n      ${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.a)\n  if(MINGW)\n    set(ANTLR4_SHARED_LIBRARIES\n        ${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dll.a)\n    set(ANTLR4_RUNTIME_LIBRARIES\n        ${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dll)\n  elseif(CYGWIN)\n    set(ANTLR4_SHARED_LIBRARIES\n        ${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dll.a)\n    set(ANTLR4_RUNTIME_LIBRARIES\n        ${ANTLR4_OUTPUT_DIR}/cygantlr4-runtime-4.13.2.dll)\n  elseif(APPLE)\n    set(ANTLR4_RUNTIME_LIBRARIES\n        ${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dylib)\n  else()\n    set(ANTLR4_RUNTIME_LIBRARIES\n        ${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.so)\n  endif()\nendif()\n\nif(${CMAKE_GENERATOR} MATCHES \".* Makefiles\")\n  # This avoids\n  # 'warning: jobserver unavailable: using -j1. Add '+' to parent make rule.'\n  set(ANTLR4_BUILD_COMMAND $(MAKE))\nelseif(${CMAKE_GENERATOR} MATCHES \"Visual Studio.*\")\n  set(ANTLR4_BUILD_COMMAND\n      ${CMAKE_COMMAND}\n          --build .\n          --config $(Configuration)\n          --target)\nelseif(${CMAKE_GENERATOR} MATCHES \"Xcode.*\")\n  set(ANTLR4_BUILD_COMMAND\n      ${CMAKE_COMMAND}\n          --build .\n          --config $(CONFIGURATION)\n          --target)\nelse()\n  set(ANTLR4_BUILD_COMMAND\n      ${CMAKE_COMMAND}\n          --build .\n          --target)\nendif()\n\nif(NOT DEFINED ANTLR4_WITH_STATIC_CRT)\n  set(ANTLR4_WITH_STATIC_CRT ON)\nendif()\n\nif(ANTLR4_ZIP_REPOSITORY)\n  ExternalProject_Add(\n      antlr4_runtime\n      PREFIX antlr4_runtime\n      URL ${ANTLR4_ZIP_REPOSITORY}\n      DOWNLOAD_DIR ${CMAKE_CURRENT_BINARY_DIR}\n      BUILD_COMMAND \"\"\n      BUILD_IN_SOURCE 1\n      SOURCE_DIR ${ANTLR4_ROOT}\n      SOURCE_SUBDIR runtime/Cpp\n      CMAKE_CACHE_ARGS\n          -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}\n          -DWITH_STATIC_CRT:BOOL=${ANTLR4_WITH_STATIC_CRT}\n          -DDISABLE_WARNINGS:BOOL=ON\n          # -DCMAKE_CXX_STANDARD:STRING=17 # if desired, compile the runtime with a different C++ standard\n          # -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD} # alternatively, compile the runtime with the same C++ standard as the outer project\n      INSTALL_COMMAND \"\"\n      EXCLUDE_FROM_ALL 1)\nelse()\n  ExternalProject_Add(\n      antlr4_runtime\n      PREFIX antlr4_runtime\n      GIT_REPOSITORY ${ANTLR4_GIT_REPOSITORY}\n      GIT_TAG ${ANTLR4_TAG}\n      DOWNLOAD_DIR ${CMAKE_CURRENT_BINARY_DIR}\n      BUILD_COMMAND \"\"\n      BUILD_IN_SOURCE 1\n      SOURCE_DIR ${ANTLR4_ROOT}\n      SOURCE_SUBDIR runtime/Cpp\n      CMAKE_CACHE_ARGS\n          -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}\n          -DWITH_STATIC_CRT:BOOL=${ANTLR4_WITH_STATIC_CRT}\n          -DDISABLE_WARNINGS:BOOL=ON\n          # -DCMAKE_CXX_STANDARD:STRING=17 # if desired, compile the runtime with a different C++ standard\n          # -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD} # alternatively, compile the runtime with the same C++ standard as the outer project\n      INSTALL_COMMAND \"\"\n      EXCLUDE_FROM_ALL 1)\nendif()\n\n# Separate build step as rarely people want both\nset(ANTLR4_BUILD_DIR ${ANTLR4_ROOT})\nif(${CMAKE_VERSION} VERSION_GREATER_EQUAL \"3.14.0\")\n  # CMake 3.14 builds in above's SOURCE_SUBDIR when BUILD_IN_SOURCE is true\n  set(ANTLR4_BUILD_DIR ${ANTLR4_ROOT}/runtime/Cpp)\nendif()\n\nExternalProject_Add_Step(\n    antlr4_runtime\n    build_static\n    COMMAND ${ANTLR4_BUILD_COMMAND} antlr4_static\n    # Depend on target instead of step (a custom command)\n    # to avoid running dependent steps concurrently\n    DEPENDS antlr4_runtime\n    BYPRODUCTS ${ANTLR4_STATIC_LIBRARIES}\n    EXCLUDE_FROM_MAIN 1\n    WORKING_DIRECTORY ${ANTLR4_BUILD_DIR})\nExternalProject_Add_StepTargets(antlr4_runtime build_static)\n\nadd_library(antlr4_static STATIC IMPORTED)\nadd_dependencies(antlr4_static antlr4_runtime-build_static)\nset_target_properties(antlr4_static PROPERTIES\n                      IMPORTED_LOCATION ${ANTLR4_STATIC_LIBRARIES})\ntarget_include_directories(antlr4_static\n    INTERFACE\n        ${ANTLR4_INCLUDE_DIRS}\n)\n\nExternalProject_Add_Step(\n    antlr4_runtime\n    build_shared\n    COMMAND ${ANTLR4_BUILD_COMMAND} antlr4_shared\n    # Depend on target instead of step (a custom command)\n    # to avoid running dependent steps concurrently\n    DEPENDS antlr4_runtime\n    BYPRODUCTS ${ANTLR4_SHARED_LIBRARIES} ${ANTLR4_RUNTIME_LIBRARIES}\n    EXCLUDE_FROM_MAIN 1\n    WORKING_DIRECTORY ${ANTLR4_BUILD_DIR})\nExternalProject_Add_StepTargets(antlr4_runtime build_shared)\n\nadd_library(antlr4_shared SHARED IMPORTED)\nadd_dependencies(antlr4_shared antlr4_runtime-build_shared)\nset_target_properties(antlr4_shared PROPERTIES\n                      IMPORTED_LOCATION ${ANTLR4_RUNTIME_LIBRARIES})\ntarget_include_directories(antlr4_shared\n    INTERFACE\n        ${ANTLR4_INCLUDE_DIRS}\n)\n\nif(ANTLR4_SHARED_LIBRARIES)\n  set_target_properties(antlr4_shared PROPERTIES\n                        IMPORTED_IMPLIB ${ANTLR4_SHARED_LIBRARIES})\nendif()\n"
  },
  {
    "path": "runtime/Cpp/cmake/FindANTLR.cmake",
    "content": "find_package(Java QUIET COMPONENTS Runtime)\n\nif(NOT ANTLR_EXECUTABLE)\n  find_program(ANTLR_EXECUTABLE\n               NAMES antlr.jar antlr4.jar antlr-4.jar antlr-4.13.2-complete.jar)\nendif()\n\nif(ANTLR_EXECUTABLE AND Java_JAVA_EXECUTABLE)\n  execute_process(\n      COMMAND ${Java_JAVA_EXECUTABLE} -jar ${ANTLR_EXECUTABLE}\n      OUTPUT_VARIABLE ANTLR_COMMAND_OUTPUT\n      ERROR_VARIABLE ANTLR_COMMAND_ERROR\n      RESULT_VARIABLE ANTLR_COMMAND_RESULT\n      OUTPUT_STRIP_TRAILING_WHITESPACE)\n\n  if(ANTLR_COMMAND_RESULT EQUAL 0)\n    string(REGEX MATCH \"Version [0-9]+(\\\\.[0-9]+)*\" ANTLR_VERSION ${ANTLR_COMMAND_OUTPUT})\n    string(REPLACE \"Version \" \"\" ANTLR_VERSION ${ANTLR_VERSION})\n  else()\n    message(\n        SEND_ERROR\n        \"Command '${Java_JAVA_EXECUTABLE} -jar ${ANTLR_EXECUTABLE}' \"\n        \"failed with the output '${ANTLR_COMMAND_ERROR}'\")\n  endif()\n\n  macro(ANTLR_TARGET Name InputFile)\n    set(ANTLR_OPTIONS LEXER PARSER LISTENER VISITOR)\n    set(ANTLR_ONE_VALUE_ARGS PACKAGE OUTPUT_DIRECTORY DEPENDS_ANTLR)\n    set(ANTLR_MULTI_VALUE_ARGS COMPILE_FLAGS DEPENDS)\n    cmake_parse_arguments(ANTLR_TARGET\n                          \"${ANTLR_OPTIONS}\"\n                          \"${ANTLR_ONE_VALUE_ARGS}\"\n                          \"${ANTLR_MULTI_VALUE_ARGS}\"\n                          ${ARGN})\n\n    set(ANTLR_${Name}_INPUT ${InputFile})\n\n    get_filename_component(ANTLR_INPUT ${InputFile} NAME_WE)\n\n    if(ANTLR_TARGET_OUTPUT_DIRECTORY)\n      set(ANTLR_${Name}_OUTPUT_DIR ${ANTLR_TARGET_OUTPUT_DIRECTORY})\n    else()\n      set(ANTLR_${Name}_OUTPUT_DIR\n          ${CMAKE_CURRENT_BINARY_DIR}/antlr4cpp_generated_src/${ANTLR_INPUT})\n    endif()\n\n    unset(ANTLR_${Name}_CXX_OUTPUTS)\n\n    if((ANTLR_TARGET_LEXER AND NOT ANTLR_TARGET_PARSER) OR\n       (ANTLR_TARGET_PARSER AND NOT ANTLR_TARGET_LEXER))\n      list(APPEND ANTLR_${Name}_CXX_OUTPUTS\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.h\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.cpp)\n      set(ANTLR_${Name}_OUTPUTS\n          ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.interp\n          ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.tokens)\n    else()\n      list(APPEND ANTLR_${Name}_CXX_OUTPUTS\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.h\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.cpp\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Parser.h\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Parser.cpp)\n      list(APPEND ANTLR_${Name}_OUTPUTS\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.interp\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.tokens)\n    endif()\n\n    if(ANTLR_TARGET_LISTENER)\n      list(APPEND ANTLR_${Name}_CXX_OUTPUTS\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseListener.h\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseListener.cpp\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Listener.h\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Listener.cpp)\n      list(APPEND ANTLR_TARGET_COMPILE_FLAGS -listener)\n    endif()\n\n    if(ANTLR_TARGET_VISITOR)\n      list(APPEND ANTLR_${Name}_CXX_OUTPUTS\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseVisitor.h\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseVisitor.cpp\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Visitor.h\n           ${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Visitor.cpp)\n      list(APPEND ANTLR_TARGET_COMPILE_FLAGS -visitor)\n    endif()\n\n    if(ANTLR_TARGET_PACKAGE)\n      list(APPEND ANTLR_TARGET_COMPILE_FLAGS -package ${ANTLR_TARGET_PACKAGE})\n    endif()\n\n    list(APPEND ANTLR_${Name}_OUTPUTS ${ANTLR_${Name}_CXX_OUTPUTS})\n\n    if(ANTLR_TARGET_DEPENDS_ANTLR)\n      if(ANTLR_${ANTLR_TARGET_DEPENDS_ANTLR}_INPUT)\n        list(APPEND ANTLR_TARGET_DEPENDS\n             ${ANTLR_${ANTLR_TARGET_DEPENDS_ANTLR}_INPUT})\n        list(APPEND ANTLR_TARGET_DEPENDS\n             ${ANTLR_${ANTLR_TARGET_DEPENDS_ANTLR}_OUTPUTS})\n      else()\n        message(SEND_ERROR\n                \"ANTLR target '${ANTLR_TARGET_DEPENDS_ANTLR}' not found\")\n      endif()\n    endif()\n\n    add_custom_command(\n        OUTPUT ${ANTLR_${Name}_OUTPUTS}\n        COMMAND ${Java_JAVA_EXECUTABLE} -jar ${ANTLR_EXECUTABLE}\n                ${InputFile}\n                -o ${ANTLR_${Name}_OUTPUT_DIR}\n                -no-listener\n                -Dlanguage=Cpp\n                ${ANTLR_TARGET_COMPILE_FLAGS}\n        DEPENDS ${InputFile}\n                ${ANTLR_TARGET_DEPENDS}\n        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}\n        COMMENT \"Building ${Name} with ANTLR ${ANTLR_VERSION}\")\n  endmacro(ANTLR_TARGET)\n\nendif(ANTLR_EXECUTABLE AND Java_JAVA_EXECUTABLE)\n\ninclude(FindPackageHandleStandardArgs)\nfind_package_handle_standard_args(\n    ANTLR\n    REQUIRED_VARS ANTLR_EXECUTABLE Java_JAVA_EXECUTABLE\n    VERSION_VAR ANTLR_VERSION)\n"
  },
  {
    "path": "runtime/Cpp/cmake/README.md",
    "content": "## Getting started with Antlr4Cpp\n\nHere is how you can use this external project to create the antlr4cpp demo to start your project off.\n\n1. Create your project source folder somewhere. e.g. ~/srcfolder/\n   1. Make a subfolder cmake\n   2. Copy the files in this folder to srcfolder/cmake\n   3. Cut below and use it to create srcfolder/CMakeLists.txt\n   4. Copy main.cpp, TLexer.g4 and TParser.g4 to srcfolder/ from [here](https://github.com/antlr/antlr4/tree/master/runtime/Cpp/demo)\n2. Make a build folder e.g. ~/buildfolder/\n3. From the buildfolder, run `cmake ~/srcfolder; make`\n\n```cmake\n# minimum required CMAKE version\nCMAKE_MINIMUM_REQUIRED(VERSION 3.7 FATAL_ERROR)\n\nlist(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)\n\n# compiler must be 17\nset(CMAKE_CXX_STANDARD 17)\n\n# required if linking to static library\nadd_definitions(-DANTLR4CPP_STATIC)\n\n# using /MD flag for antlr4_runtime (for Visual C++ compilers only)\nset(ANTLR4_WITH_STATIC_CRT OFF)\n\n# Specify the version of the antlr4 library needed for this project.\n# By default the latest version of antlr4 will be used.  You can specify a\n# specific, stable version by setting a repository tag value or a link\n# to a zip file containing the libary source.\n# set(ANTLR4_TAG 4.13.2)\n# set(ANTLR4_ZIP_REPOSITORY https://github.com/antlr/antlr4/archive/refs/tags/4.13.2.zip)\n\n# add external build for antlrcpp\ninclude(ExternalAntlr4Cpp)\n# add antlr4cpp artifacts to project environment\ninclude_directories(${ANTLR4_INCLUDE_DIRS})\n\n# set variable pointing to the antlr tool that supports C++\n# this is not required if the jar file can be found under PATH environment\nset(ANTLR_EXECUTABLE /home/user/antlr-4.13.2-complete.jar)\n# add macros to generate ANTLR Cpp code from grammar\nfind_package(ANTLR REQUIRED)\n\n# Call macro to add lexer and grammar to your build dependencies.\nantlr_target(SampleGrammarLexer TLexer.g4 LEXER\n             PACKAGE antlrcpptest)\nantlr_target(SampleGrammarParser TParser.g4 PARSER\n             PACKAGE antlrcpptest\n             DEPENDS_ANTLR SampleGrammarLexer\n             COMPILE_FLAGS -lib ${ANTLR_SampleGrammarLexer_OUTPUT_DIR})\n\n# include generated files in project environment\ninclude_directories(${ANTLR_SampleGrammarLexer_OUTPUT_DIR})\ninclude_directories(${ANTLR_SampleGrammarParser_OUTPUT_DIR})\n\n# add generated grammar to demo binary target\nadd_executable(demo main.cpp\n               ${ANTLR_SampleGrammarLexer_CXX_OUTPUTS}\n               ${ANTLR_SampleGrammarParser_CXX_OUTPUTS})\ntarget_link_libraries(demo antlr4_static)\n```\n\n## Documentation for FindANTLR\n\nThe module defines the following variables:\n\n```\nANTLR_FOUND - true is ANTLR jar executable is found\nANTLR_EXECUTABLE - the path to the ANTLR jar executable\nANTLR_VERSION - the version of ANTLR\n```\n\nIf ANTLR is found, the module will  provide the macros:\n\n```\nANTLR_TARGET(<name> <input>\n             [PACKAGE namespace]\n             [OUTPUT_DIRECTORY dir]\n             [DEPENDS_ANTLR <target>]\n             [COMPILE_FLAGS [args...]]\n             [DEPENDS [depends...]]\n             [LEXER]\n             [PARSER]\n             [LISTENER]\n             [VISITOR])\n```\n\nwhich creates a custom command to generate C++ files from `<input>`. Running the macro defines the following variables:\n\n```\nANTLR_${name}_INPUT - the ANTLR input used for the macro\nANTLR_${name}_OUTPUTS - the outputs generated by ANTLR\nANTLR_${name}_CXX_OUTPUTS - the C++ outputs generated by ANTLR\nANTLR_${name}_OUTPUT_DIR - the output directory for ANTLR\n```\n\nThe options are:\n\n* `PACKAGE` - defines a namespace for the generated C++ files\n* `OUTPUT_DIRECTORY` - the output directory for the generated files. By default it uses `${CMAKE_CURRENT_BINARY_DIR}`\n* `DEPENDS_ANTLR` - the dependent target generated from antlr_target for the current call\n* `COMPILE_FLAGS` - additional compile flags for ANTLR tool\n* `DEPENDS` - specify the files on which the command depends. It works the same way `DEPENDS` in [`add_custom_command()`](https://cmake.org/cmake/help/v3.11/command/add_custom_command.html)\n* `LEXER` - specify that the input file is a lexer grammar\n* `PARSER` - specify that the input file is a parser grammar\n* `LISTENER` - tell ANTLR tool to generate a parse tree listener\n* `VISITOR` - tell ANTLR tool to generate a parse tree visitor\n\n### Examples\n\nTo generate C++ files from an ANTLR input file T.g4, which defines both lexer and parser grammar one may call:\n\n```cmake\nfind_package(ANTLR REQUIRED)\nantlr_target(Sample T.g4)\n```\n\nNote that this command will do nothing unless the outputs of `Sample`, i.e. `ANTLR_Sample_CXX_OUTPUTS` gets used by some target.\n\n## Documentation for ExternalAntlr4Cpp\n\nIncluding ExternalAntlr4Cpp will add `antlr4_static` and `antlr4_shared` as an optional target. It will also define the following variables:\n\n```\nANTLR4_INCLUDE_DIRS - the include directory that should be included when compiling C++ source file\nANTLR4_STATIC_LIBRARIES - path to antlr4 static library\nANTLR4_SHARED_LIBRARIES - path to antlr4 shared library\nANTLR4_RUNTIME_LIBRARIES - path to antlr4 shared runtime library (such as DLL, DYLIB and SO file)\nANTLR4_TAG - branch/tag used for building antlr4 library\n```\n\n`ANTLR4_TAG` is set to master branch by default to keep the antlr4 library up to date. However, this will require a rebuild after every `clean` is called. Set `ANTLR4_TAG` to a desired commit hash value to avoid rebuilding after every `clean` and keep the build stable, at the cost of not automatically updating to latest commit.\n\nBy defualt the ANTLR C++ runtime source is cloned from GitHub. However, users may specify `ANTLR4_ZIP_REPOSITORY` in order to download source as a zip file from [ANTLR downloads](http://www.antlr.org/download.html) (under *C++ Target*) or other locations. For example, this variable could list a zip file included in your the project directory.  This is useful for maintaining a canonical source tree for each new build.\n\nVisual C++ compiler users may want to additionally define `ANTLR4_WITH_STATIC_CRT` before including the file. Set `ANTLR4_WITH_STATIC_CRT` to true if ANTLR4 C++ runtime library should be compiled with `/MT` flag, otherwise will be compiled with `/MD` flag. This variable has a default value of `OFF`. Changing `ANTLR4_WITH_STATIC_CRT` after building the library may require reinitialization of CMake or `clean` for the library to get rebuilt.\n\nYou may need to modify your local copy of ExternalAntlr4Cpp.cmake to modify some build settings. For example, to specify the C++ standard to use when building the runtime, add `-DCMAKE_CXX_STANDARD:STRING=17` to `CMAKE_CACHE_ARGS`.\n\n### Examples\n\nTo build and link ANTLR4 static library to a target one may call:\n\n```cmake\ninclude(ExternalAntlr4Cpp)\ninclude_directories(${ANTLR4_INCLUDE_DIRS})\nadd_executable(output main.cpp)\ntarget_link_libraries(output antlr4_static)\n```\n\nIt may also be a good idea to copy the runtime libraries (DLL, DYLIB or SO file) to the executable for it to run properly after build. i.e. To build and link antlr4 shared library to a target one may call:\n\n```cmake\ninclude(ExternalAntlr4Cpp)\ninclude_directories(${ANTLR4_INCLUDE_DIRS})\nadd_executable(output main.cpp)\ntarget_link_libraries(output antlr4_shared)\nadd_custom_command(TARGET output\n                   POST_BUILD\n                   COMMAND ${CMAKE_COMMAND}\n                           -E copy ${ANTLR4_RUNTIME_LIBRARIES} .\n                   WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})\n```\n"
  },
  {
    "path": "runtime/Cpp/cmake/antlr4-generator.cmake.in",
    "content": "set(ANTLR_VERSION @ANTLR_VERSION@)\n\n@PACKAGE_INIT@\n\nif (NOT ANTLR4_CPP_GENERATED_SRC_DIR)\n  set(ANTLR4_GENERATED_SRC_DIR ${CMAKE_BINARY_DIR}/antlr4_generated_src)\nendif()\n\nFIND_PACKAGE(Java COMPONENTS Runtime REQUIRED)\n\n#\n# The ANTLR generator will output the following files given the input file f.g4\n#\n# Input  -> f.g4\n# Output -> f.h\n#        -> f.cpp\n#\n# the following files will only be produced if there is a parser contained\n# Flag -visitor active\n# Output -> <f>BaseVisitor.h\n#        -> <f>BaseVisitor.cpp\n#        -> <f>Visitor.h\n#        -> <f>Visitor.cpp\n#\n# Flag -listener active\n# Output -> <f>BaseListener.h\n#        -> <f>BaseListener.cpp\n#        -> <f>Listener.h\n#        -> <f>Listener.cpp\n#\n# See documentation in markup\n#\nfunction(antlr4_generate\n    Antlr4_ProjectTarget\n    Antlr4_InputFile\n    Antlr4_GeneratorType\n    )\n\n  set( Antlr4_GeneratedSrcDir ${ANTLR4_GENERATED_SRC_DIR}/${Antlr4_ProjectTarget} )\n\n  get_filename_component(Antlr4_InputFileBaseName ${Antlr4_InputFile} NAME_WE )\n\n  list( APPEND Antlr4_GeneratorStatusMessage \"Common Include-, Source- and Tokenfiles\" )\n\n  if ( ${Antlr4_GeneratorType} STREQUAL \"LEXER\")\n    set(Antlr4_LexerBaseName \"${Antlr4_InputFileBaseName}\")\n    set(Antlr4_ParserBaseName \"\")\n  else()\n    if ( ${Antlr4_GeneratorType} STREQUAL \"PARSER\")\n      set(Antlr4_LexerBaseName \"\")\n      set(Antlr4_ParserBaseName \"${Antlr4_InputFileBaseName}\")\n    else()\n      if ( ${Antlr4_GeneratorType} STREQUAL \"BOTH\")\n        set(Antlr4_LexerBaseName \"${Antlr4_InputFileBaseName}Lexer\")\n        set(Antlr4_ParserBaseName \"${Antlr4_InputFileBaseName}Parser\")\n      else()\n        message(FATAL_ERROR \"The third parameter must be LEXER, PARSER or BOTH\")\n      endif ()\n    endif ()\n  endif ()\n\n  # Prepare list of generated targets\n  list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}.tokens\" )\n  list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}.interp\" )\n  list( APPEND DependentTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}.tokens\" )\n\n  if ( NOT ${Antlr4_LexerBaseName} STREQUAL \"\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_LexerBaseName}.h\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_LexerBaseName}.cpp\" )\n  endif ()\n\n  if ( NOT ${Antlr4_ParserBaseName} STREQUAL \"\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_ParserBaseName}.h\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_ParserBaseName}.cpp\" )\n  endif ()\n\n  # process optional arguments ...\n\n  if ( ( ARGC GREATER_EQUAL 4 ) AND ARGV3 )\n    set(Antlr4_BuildListenerOption \"-listener\")\n\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseListener.h\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseListener.cpp\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Listener.h\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Listener.cpp\" )\n\n    list( APPEND Antlr4_GeneratorStatusMessage \", Listener Include- and Sourcefiles\" )\n  else()\n    set(Antlr4_BuildListenerOption \"-no-listener\")\n  endif ()\n\n  if ( ( ARGC GREATER_EQUAL 5 ) AND ARGV4 )\n    set(Antlr4_BuildVisitorOption \"-visitor\")\n\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseVisitor.h\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseVisitor.cpp\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Visitor.h\" )\n    list( APPEND Antlr4_GeneratedTargets \"${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Visitor.cpp\" )\n\n    list( APPEND Antlr4_GeneratorStatusMessage \", Visitor Include- and Sourcefiles\" )\n  else()\n    set(Antlr4_BuildVisitorOption \"-no-visitor\")\n  endif ()\n\n  if ( (ARGC GREATER_EQUAL 6 ) AND (NOT ${ARGV5} STREQUAL \"\") )\n    set(Antlr4_NamespaceOption \"-package;${ARGV5}\")\n\n    list( APPEND Antlr4_GeneratorStatusMessage \" in Namespace ${ARGV5}\" )\n  else()\n    set(Antlr4_NamespaceOption \"\")\n  endif ()\n\n  if ( (ARGC GREATER_EQUAL 7 ) AND (NOT ${ARGV6} STREQUAL \"\") )\n    set(Antlr4_AdditionalDependencies ${ARGV6})\n  else()\n    set(Antlr4_AdditionalDependencies \"\")\n  endif ()\n\n  if ( (ARGC GREATER_EQUAL 8 ) AND (NOT ${ARGV7} STREQUAL \"\") )\n    set(Antlr4_LibOption \"-lib;${ARGV7}\")\n\n    list( APPEND Antlr4_GeneratorStatusMessage \" using Library ${ARGV7}\" )\n  else()\n    set(Antlr4_LibOption \"\")\n  endif ()\n\n  if(NOT Java_FOUND)\n    message(FATAL_ERROR \"Java is required to process grammar or lexer files! - Use 'FIND_PACKAGE(Java COMPONENTS Runtime REQUIRED)'\")\n  endif()\n\n  if(NOT EXISTS \"${ANTLR4_JAR_LOCATION}\")\n    message(FATAL_ERROR \"Unable to find antlr tool. ANTLR4_JAR_LOCATION:${ANTLR4_JAR_LOCATION}\")\n  endif()\n\n  # The call to generate the files\n  add_custom_command(\n    OUTPUT ${Antlr4_GeneratedTargets}\n    # Remove target directory\n    COMMAND\n    ${CMAKE_COMMAND} -E remove_directory ${Antlr4_GeneratedSrcDir}\n    # Create target directory\n    COMMAND\n    ${CMAKE_COMMAND} -E make_directory ${Antlr4_GeneratedSrcDir}\n    COMMAND\n    # Generate files\n    \"${Java_JAVA_EXECUTABLE}\" -jar \"${ANTLR4_JAR_LOCATION}\" -Werror -Dlanguage=Cpp ${Antlr4_BuildListenerOption} ${Antlr4_BuildVisitorOption} ${Antlr4_LibOption} ${ANTLR4_GENERATED_OPTIONS} -o \"${Antlr4_GeneratedSrcDir}\" ${Antlr4_NamespaceOption} \"${Antlr4_InputFile}\"\n    WORKING_DIRECTORY \"${CMAKE_BINARY_DIR}\"\n    MAIN_DEPENDENCY \"${Antlr4_InputFile}\"\n    DEPENDS ${Antlr4_AdditionalDependencies}\n    )\n\n  # set output variables in parent scope\n  set( ANTLR4_INCLUDE_DIR_${Antlr4_ProjectTarget} ${Antlr4_GeneratedSrcDir} PARENT_SCOPE)\n  set( ANTLR4_SRC_FILES_${Antlr4_ProjectTarget} ${Antlr4_GeneratedTargets} PARENT_SCOPE)\n  set( ANTLR4_TOKEN_FILES_${Antlr4_ProjectTarget} ${DependentTargets} PARENT_SCOPE)\n  set( ANTLR4_TOKEN_DIRECTORY_${Antlr4_ProjectTarget} ${Antlr4_GeneratedSrcDir} PARENT_SCOPE)\n\n  # export generated cpp files into list\n  foreach(generated_file ${Antlr4_GeneratedTargets})\n\n    if (NOT CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n      set_source_files_properties(\n        ${generated_file}\n        PROPERTIES\n        COMPILE_FLAGS -Wno-overloaded-virtual\n        )\n    endif ()\n\n    if (CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n      set_source_files_properties(\n        ${generated_file}\n        PROPERTIES\n        COMPILE_FLAGS -wd4251\n        )\n    endif ()\n\n  endforeach(generated_file)\n\nmessage(STATUS \"Antlr4 ${Antlr4_ProjectTarget} - Building \" ${Antlr4_GeneratorStatusMessage} )\n\nendfunction()\n"
  },
  {
    "path": "runtime/Cpp/cmake/antlr4-runtime.cmake.in",
    "content": "set(ANTLR_VERSION @ANTLR_VERSION@)\n\n@PACKAGE_INIT@\n\nset_and_check(ANTLR4_INCLUDE_DIR \"@PACKAGE_ANTLR4_INCLUDE_DIR@\")\nset_and_check(ANTLR4_LIB_DIR \"@PACKAGE_ANTLR4_LIB_DIR@\")\n\ninclude(CMakeFindDependencyMacro)\nfind_dependency(Threads)\n\ninclude(${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake)\n\ncheck_required_components(antlr)\n"
  },
  {
    "path": "runtime/Cpp/demo/CMakeLists.txt",
    "content": "# -*- mode:cmake -*-\nif(NOT UNIX)\n  message(WARNING \"Unsupported operating system\")\nendif()\n\nset(antlr4-demo-GENERATED_SRC\n   ${PROJECT_SOURCE_DIR}/demo/generated/TLexer.cpp \n   ${PROJECT_SOURCE_DIR}/demo/generated/TParser.cpp\n   ${PROJECT_SOURCE_DIR}/demo/generated/TParserBaseListener.cpp\n   ${PROJECT_SOURCE_DIR}/demo/generated/TParserBaseVisitor.cpp\n   ${PROJECT_SOURCE_DIR}/demo/generated/TParserListener.cpp\n   ${PROJECT_SOURCE_DIR}/demo/generated/TParserVisitor.cpp\n )\n\nforeach(src_file ${antlr4-demo-GENERATED_SRC})\n      set_source_files_properties(\n          ${src_file}\n          PROPERTIES\n          GENERATED TRUE\n          )\nendforeach(src_file ${antlr4-demo-GENERATED_SRC})\n\nadd_custom_target(GenerateParser DEPENDS ${antlr4-demo-GENERATED_SRC})\nadd_custom_command(OUTPUT ${antlr4-demo-GENERATED_SRC}\n   COMMAND \n   ${CMAKE_COMMAND} -E make_directory ${PROJECT_SOURCE_DIR}/demo/generated/\n   COMMAND\n   \"${Java_JAVA_EXECUTABLE}\" -jar ${ANTLR_JAR_LOCATION} -Werror -Dlanguage=Cpp -listener -visitor -o ${PROJECT_SOURCE_DIR}/demo/generated/ -package antlrcpptest ${PROJECT_SOURCE_DIR}/demo/TLexer.g4 ${PROJECT_SOURCE_DIR}/demo/TParser.g4\n   WORKING_DIRECTORY \"${CMAKE_BINARY_DIR}\"\n   DEPENDS ${PROJECT_SOURCE_DIR}/demo/TLexer.g4 ${PROJECT_SOURCE_DIR}/demo/TParser.g4\n   )\n\ninclude_directories(\n  ${PROJECT_SOURCE_DIR}/runtime/src\n  ${PROJECT_SOURCE_DIR}/runtime/src/misc\n  ${PROJECT_SOURCE_DIR}/runtime/src/atn\n  ${PROJECT_SOURCE_DIR}/runtime/src/dfa\n  ${PROJECT_SOURCE_DIR}/runtime/src/tree\n  ${PROJECT_SOURCE_DIR}/runtime/src/support\n  ${PROJECT_SOURCE_DIR}/demo/generated\n  )\n\n#file(GLOB antlr4-demo_SRC \"${PROJECT_SOURCE_DIR}/demo/generated/*\")\nset(antlr4-demo_SRC \n  ${PROJECT_SOURCE_DIR}/demo/Linux/main.cpp\n  ${antlr4-demo-GENERATED_SRC}\n  )\n\nif(NOT CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n  set (flags_1 \"-Wno-overloaded-virtual\")\nelse()\n  set (flags_1 \"-MP /wd4251\")\nendif()\n\nforeach(src_file ${antlr4-demo_SRC})\n      set_source_files_properties(\n          ${src_file}\n          PROPERTIES\n          COMPILE_FLAGS \"${COMPILE_FLAGS} ${flags_1}\"\n          )\nendforeach(src_file ${antlr4-demo_SRC})\n\nadd_executable(antlr4-demo\n  ${antlr4-demo_SRC}\n  )\n#add_precompiled_header(antlr4-demo ${PROJECT_SOURCE_DIR}/runtime/src/antlrcpp-Prefix.h)\n\nif(CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n  target_compile_options(antlr4-demo PRIVATE \"/MT$<$<CONFIG:Debug>:d>\")\nendif()\n\nadd_dependencies(antlr4-demo GenerateParser)\n\ntarget_link_libraries(antlr4-demo antlr4_static)\n\ninstall(TARGETS antlr4-demo \n        DESTINATION \"share\" \n        COMPONENT dev \n        )\n\n"
  },
  {
    "path": "runtime/Cpp/demo/Linux/main.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n//\n//  main.cpp\n//  antlr4-cpp-demo\n//\n//  Created by Mike Lischke on 13.03.16.\n//\n\n#include <iostream>\n\n#include \"antlr4-runtime.h\"\n#include \"TLexer.h\"\n#include \"TParser.h\"\n\nusing namespace antlrcpptest;\nusing namespace antlr4;\n\nint main(int , const char **) {\n  ANTLRInputStream input(u8\"🍴 = 🍐 + \\\"😎\\\";(((x * π))) * µ + ∰; a + (x * (y ? 0 : 1) + z);\");\n  TLexer lexer(&input);\n  CommonTokenStream tokens(&lexer);\n\n  tokens.fill();\n  for (auto token : tokens.getTokens()) {\n    std::cout << token->toString() << std::endl;\n  }\n\n  TParser parser(&tokens);\n  tree::ParseTree* tree = parser.main();\n\n  std::cout << tree->toStringTree(&parser) << std::endl << std::endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlr4-cpp-demo/main.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n//\n//  main.cpp\n//  antlr4-cpp-demo\n//\n//  Created by Mike Lischke on 13.03.16.\n//\n\n#include <iostream>\n\n#include \"antlr4-runtime.h\"\n#include \"TLexer.h\"\n#include \"TParser.h\"\n\nusing namespace antlrcpptest;\nusing namespace antlr4;\n\nint main(int , const char **) {\n  ANTLRInputStream input(u8\"🍴 = 🍐 + \\\"😎\\\";(((x * π))) * µ + ∰; a + (x * (y ? 0 : 1) + z);\");\n  TLexer lexer(&input);\n  CommonTokenStream tokens(&lexer);\n\n  tokens.fill();\n  for (auto token : tokens.getTokens()) {\n    std::cout << token->toString() << std::endl;\n  }\n\n  TParser parser(&tokens);\n  tree::ParseTree *tree = parser.main();\n\n  std::cout << tree->toStringTree(&parser) << std::endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp Tests/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>BNDL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>1</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp Tests/InputHandlingTests.mm",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2016 Mike Lischke\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#import <XCTest/XCTest.h>\n\n#include \"ANTLRInputStream.h\"\n#include \"Exceptions.h\"\n#include \"Interval.h\"\n#include \"UnbufferedTokenStream.h\"\n#include \"StringUtils.h\"\n\nusing namespace antlrcpp;\nusing namespace antlr4;\nusing namespace antlr4::misc;\n\n@interface InputHandlingTests : XCTestCase\n\n@end\n\n@implementation InputHandlingTests\n\n- (void)setUp {\n  [super setUp];\n  // Put setup code here. This method is called before the invocation of each test method in the class.\n}\n\n- (void)tearDown {\n  // Put teardown code here. This method is called after the invocation of each test method in the class.\n  [super tearDown];\n}\n\n- (void)testANTLRInputStreamCreation {\n  ANTLRInputStream stream1;\n  XCTAssert(stream1.toString().empty());\n  XCTAssertEqual(stream1.index(), 0U);\n\n  ANTLRInputStream stream2(\"To be or not to be\");\n  XCTAssert(stream2.toString() == \"To be or not to be\");\n  XCTAssertEqual(stream2.index(), 0U);\n  XCTAssertEqual(stream2.size(), 18U);\n\n  char data[] = \"Lorem ipsum dolor sit amet\";\n  ANTLRInputStream stream3(data, sizeof(data) / sizeof(data[0]));\n  XCTAssert(stream3.toString() == std::string(\"Lorem ipsum dolor sit amet\\0\", 27));\n  XCTAssertEqual(stream3.index(), 0U);\n  XCTAssertEqual(stream3.size(), 27U);\n\n  std::stringstream input(\"Lorem ipsum dolor sit amet\");\n  ANTLRInputStream stream4(input);\n  std::string content = stream4.toString();\n  XCTAssertEqual(content, \"Lorem ipsum dolor sit amet\"); // Now as utf-8 string.\n  XCTAssertEqual(stream4.index(), 0U);\n  XCTAssertEqual(stream4.size(), 26U);\n\n  std::string longString(33333, 'a');\n  input.str(longString);\n  stream4.load(input);\n  XCTAssertEqual(stream4.index(), 0U);\n  XCTAssertEqual(stream4.size(), 33333U);\n\n  input.clear();\n  stream4.load(input);\n  XCTAssertEqual(stream4.size(), 0U);\n}\n\n- (void)testANTLRInputStreamUse {\n  std::string text(u8\"🚧Lorem ipsum dolor sit amet🕶\");\n  std::u32string wtext = utf8_to_utf32(text.c_str(), text.c_str() + text.size()); // Convert to UTF-32.\n  ANTLRInputStream stream(text);\n  XCTAssertEqual(stream.index(), 0U);\n  XCTAssertEqual(stream.size(), wtext.size());\n\n  for (size_t i = 0; i < stream.size(); ++i) {\n    stream.consume();\n    XCTAssertEqual(stream.index(), i + 1);\n  }\n\n  try {\n    stream.consume();\n    XCTFail();\n  } catch (IllegalStateException &e) {\n    // Expected.\n    std::string message = e.what();\n    XCTAssertEqual(message, \"cannot consume EOF\");\n  }\n\n  XCTAssertEqual(stream.index(), wtext.size());\n  stream.reset();\n  XCTAssertEqual(stream.index(), 0U);\n\n  XCTAssertEqual(stream.LA(0), 0ULL);\n  for (size_t i = 1; i < wtext.size(); ++i) {\n    XCTAssertEqual(stream.LA(static_cast<ssize_t>(i)), wtext[i - 1]); // LA(1) means: current char.\n    XCTAssertEqual(stream.LT(static_cast<ssize_t>(i)), wtext[i - 1]); // LT is mapped to LA.\n    XCTAssertEqual(stream.index(), 0U); // No consumption when looking ahead.\n  }\n\n  stream.seek(wtext.size() - 1);\n  XCTAssertEqual(stream.index(), wtext.size() - 1);\n\n  stream.seek(wtext.size() / 2);\n  XCTAssertEqual(stream.index(), wtext.size() / 2);\n\n  stream.seek(wtext.size() - 1);\n  for (ssize_t i = 1; i < static_cast<ssize_t>(wtext.size()) - 1; ++i) {\n    XCTAssertEqual(stream.LA(-i), wtext[wtext.size() - i - 1]); // LA(-1) means: previous char.\n    XCTAssertEqual(stream.LT(-i), wtext[wtext.size() - i - 1]); // LT is mapped to LA.\n    XCTAssertEqual(stream.index(), wtext.size() - 1); // No consumption when looking ahead.\n  }\n\n  XCTAssertEqual(stream.LA(-10000), IntStream::EOF);\n\n  // Mark and release do nothing.\n  stream.reset();\n  XCTAssertEqual(stream.index(), 0U);\n  ssize_t marker = stream.mark();\n  XCTAssertEqual(marker, -1);\n  stream.seek(10);\n  XCTAssertEqual(stream.index(), 10U);\n  XCTAssertEqual(stream.mark(), -1);\n\n  stream.release(marker);\n  XCTAssertEqual(stream.index(), 10U);\n\n  misc::Interval interval1(2, 10UL); // From - to, inclusive.\n  std::string output = stream.getText(interval1);\n  std::string sub = utf32_to_utf8(wtext.substr(2, 9));\n  XCTAssertEqual(output, sub);\n\n  misc::Interval interval2(200, 10UL); // Start beyond bounds.\n  output = stream.getText(interval2);\n  XCTAssert(output.empty());\n\n  misc::Interval interval3(0, 200UL); // End beyond bounds.\n  output = stream.getText(interval3);\n  XCTAssertEqual(output, text);\n\n  stream.name = \"unit tests\"; // Quite useless test, as \"name\" is a public field.\n  XCTAssertEqual(stream.getSourceName(), \"unit tests\");\n}\n\n- (void)testUnbufferedTokenSteam {\n  //UnbufferedTokenStream stream;\n}\n\n@end\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp Tests/MiscClassTests.mm",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2016 Mike Lischke\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#import <XCTest/XCTest.h>\n\n#include \"antlr4-runtime.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\n@interface MiscClassTests : XCTestCase\n\n@end\n\n@implementation MiscClassTests\n\n- (void)setUp {\n  [super setUp];\n  // Put setup code here. This method is called before the invocation of each test method in the class.\n}\n\n- (void)tearDown {\n  // Put teardown code here. This method is called after the invocation of each test method in the class.\n  [super tearDown];\n}\n\n- (void)testCPPUtils {\n\n  class A { public: virtual ~A() {}; };\n  class B : public A { public: virtual ~B() {}; };\n  class C : public A { public: virtual ~C() {}; };\n  class D : public C { public: virtual ~D() {}; };\n\n  {\n    A *a = new A(); B *b = new B(); C *c = new C(); D *d = new D();\n    XCTAssert(is<A*>(b));\n    XCTAssertFalse(is<B*>(a));\n    XCTAssert(is<A*>(c));\n    XCTAssertFalse(is<B*>(c));\n    XCTAssert(is<A*>(d));\n    XCTAssert(is<C*>(d));\n    XCTAssertFalse(is<B*>(d));\n    delete a; delete b; delete c; delete d;\n  }\n  {\n    Ref<A> a(new A());\n    Ref<B> b(new B());\n    Ref<C> c(new C());\n    Ref<D> d(new D());\n    XCTAssert(is<A>(b));\n    XCTAssertFalse(is<B>(a));\n    XCTAssert(is<A>(c));\n    XCTAssertFalse(is<B>(c));\n    XCTAssert(is<A>(d));\n    XCTAssert(is<C>(d));\n    XCTAssertFalse(is<B>(d));\n  }\n}\n\n- (void)testMurmurHash {\n  XCTAssertEqual(MurmurHash::initialize(), 0U);\n  XCTAssertEqual(MurmurHash::initialize(31), 31U);\n\n  // In absence of real test vectors (64bit) for murmurhash I instead check if I can find duplicate hash values\n  // in a deterministic and a random sequence of 100K values each.\n  std::set<size_t> hashs;\n  for (size_t i = 0; i < 100000; ++i) {\n    std::vector<size_t> data = { i, static_cast<size_t>(i * M_PI), arc4random() };\n    size_t hash = 0;\n    for (auto value : data)\n      hash = MurmurHash::update(hash, value);\n    hash = MurmurHash::finish(hash, data.size());\n    hashs.insert(hash);\n  }\n  XCTAssertEqual(hashs.size(), 100000U, @\"At least one duplicate hash found.\");\n\n  hashs.clear();\n  for (size_t i = 0; i < 100000; ++i) {\n    std::vector<size_t> data = { i, static_cast<size_t>(i * M_PI) };\n    size_t hash = 0;\n    for (auto value : data)\n      hash = MurmurHash::update(hash, value);\n    hash = MurmurHash::finish(hash, data.size());\n    hashs.insert(hash);\n  }\n  XCTAssertEqual(hashs.size(), 100000U, @\"At least one duplicate hash found.\");\n\n  // Another test with fixed input but varying seeds.\n  // Note: the higher the seed the less LSDs are in the result (for small input data).\n  hashs.clear();\n  std::vector<size_t> data = { L'µ', 'a', '@', '1' };\n  for (size_t i = 0; i < 100000; ++i) {\n    size_t hash = i;\n    for (auto value : data)\n      hash = MurmurHash::update(hash, value);\n    hash = MurmurHash::finish(hash, data.size());\n    hashs.insert(hash);\n  }\n  XCTAssertEqual(hashs.size(), 100000U, @\"At least one duplicate hash found.\");\n}\n\n- (void)testInterval {\n  // The Interval class contains no error handling (checks for invalid intervals), hence some of the results\n  // look strange as we test of course such intervals as well.\n  XCTAssertEqual(Interval().length(), 0UL);\n  XCTAssertEqual(Interval(0, 0UL).length(), 1UL); // Remember: it's an inclusive interval.\n  XCTAssertEqual(Interval(100, 100UL).length(), 1UL);\n  XCTAssertEqual(Interval(-1L, -1).length(), 1UL); // Unwanted behavior: negative ranges.\n  XCTAssertEqual(Interval(-1L, -2).length(), 0UL);\n  XCTAssertEqual(Interval(100, 50UL).length(), 0UL);\n\n  XCTAssert(Interval() == Interval(-1L, -2));\n  XCTAssert(Interval(0, 0UL) == Interval(0, 0UL));\n  XCTAssertFalse(Interval(0, 1UL) == Interval(1, 2UL));\n\n  XCTAssertEqual(Interval().hashCode(), 22070U);\n  XCTAssertEqual(Interval(0, 0UL).hashCode(), 22103U);\n  XCTAssertEqual(Interval(10, 2000UL).hashCode(), 24413U);\n\n  // Results for the interval test functions in this order:\n  // startsBeforeDisjoint\n  // startsBeforeNonDisjoint\n  // startsAfter\n  // startsAfterDisjoint\n  // startsAfterNonDisjoint\n  // disjoint\n  // adjacent\n  // properlyContains\n\n  typedef std::vector<bool> TestResults;\n  struct TestEntry { size_t runningNumber; Interval interval1, interval2; TestResults results; };\n  std::vector<TestEntry> testData = {\n    // Extreme cases + invalid intervals.\n    { 0, Interval(), Interval(10, 20UL), { true, false, false, false, false, true, false, false } },\n    { 1, Interval(1, 1UL), Interval(1, 1UL), { false, true, false, false, false, false, false, true } },\n    { 2, Interval(10000, 10000UL), Interval(10000, 10000UL), { false, true, false, false, false, false, false, true } },\n    { 3, Interval(100, 10UL), Interval(100, 10UL), { false, false, false, true, false, true, false, true } },\n    { 4, Interval(100, 10UL), Interval(10, 100UL), { false, false, true, false, true, false, false, false } },\n    { 5, Interval(10, 100UL), Interval(100, 10UL), { false, true, false, false, false, false, false, true } },\n\n    // First starts before second. End varies.\n    { 20, Interval(10, 12UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 21, Interval(10, 12UL), Interval(13, 100UL), { true, false, false, false, false, true, true, false } },\n    { 22, Interval(10, 12UL), Interval(14, 100UL), { true, false, false, false, false, true, false, false } },\n    { 23, Interval(10, 13UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 24, Interval(10, 14UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 25, Interval(10, 99UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 26, Interval(10, 100UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },\n    { 27, Interval(10, 101UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },\n    { 28, Interval(10, 1000UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },\n\n    // First and second start equal. End varies.\n    { 30, Interval(12, 12UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 31, Interval(12, 12UL), Interval(13, 100UL), { true, false, false, false, false, true, true, false } },\n    { 32, Interval(12, 12UL), Interval(14, 100UL), { true, false, false, false, false, true, false, false } },\n    { 33, Interval(12, 13UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 34, Interval(12, 14UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 35, Interval(12, 99UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },\n    { 36, Interval(12, 100UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },\n    { 37, Interval(12, 101UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },\n    { 38, Interval(12, 1000UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },\n\n    // First starts after second. End varies.\n    { 40, Interval(15, 12UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },\n    { 41, Interval(15, 12UL), Interval(13, 100UL), { false, false, true, false, true, false, true, false } },\n    { 42, Interval(15, 12UL), Interval(14, 100UL), { false, false, true, false, true, false, false, false } },\n    { 43, Interval(15, 13UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },\n    { 44, Interval(15, 14UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },\n    { 45, Interval(15, 99UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },\n    { 46, Interval(15, 100UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },\n    { 47, Interval(15, 101UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },\n    { 48, Interval(15, 1000UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },\n\n    // First ends before second. Start varies.\n    { 50, Interval(10, 90UL), Interval(20, 100UL), { false, true, false, false, false, false, false, false } },\n    { 51, Interval(19, 90UL), Interval(20, 100UL), { false, true, false, false, false, false, false, false } },\n    { 52, Interval(20, 90UL), Interval(20, 100UL), { false, true, false, false, false, false, false, false } },\n    { 53, Interval(21, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 54, Interval(98, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 55, Interval(99, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 56, Interval(100, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 57, Interval(101, 90UL), Interval(20, 100UL), { false, false, true, true, false, true, true, false } },\n    { 58, Interval(1000, 90UL), Interval(20, 100UL), { false, false, true, true, false, true, false, false } },\n\n    // First and second end equal. Start varies.\n    { 60, Interval(10, 100UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },\n    { 61, Interval(19, 100UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },\n    { 62, Interval(20, 100UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },\n    { 63, Interval(21, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 64, Interval(98, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 65, Interval(99, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 66, Interval(100, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 67, Interval(101, 100UL), Interval(20, 100UL), { false, false, true, true, false, true, true, false } },\n    { 68, Interval(1000, 100UL), Interval(20, 100UL), { false, false, true, true, false, true, false, false } },\n\n    // First ends after second. Start varies.\n    { 70, Interval(10, 1000UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },\n    { 71, Interval(19, 1000UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },\n    { 72, Interval(20, 1000UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },\n    { 73, Interval(21, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 74, Interval(98, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 75, Interval(99, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 76, Interval(100, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },\n    { 77, Interval(101, 1000UL), Interval(20, 100UL), { false, false, true, true, false, true, true, false } },\n    { 78, Interval(1000, 1000UL), Interval(20, 100UL), { false, false, true, true, false, true, false, false } },\n\n    // It's possible to add more tests with borders that touch each other (e.g. first starts before/on/after second\n    // and first ends directly before/after second. However, such cases are not handled differently in the Interval\n    // class\n    // (only adjacent intervals, where first ends directly before second starts and vice versa. So I ommitted them here.\n  };\n\n  for (auto &entry : testData) {\n    XCTAssert(entry.interval1.startsBeforeDisjoint(entry.interval2) == entry.results[0], @\"entry: %zu\",\n              entry.runningNumber);\n    XCTAssert(entry.interval1.startsBeforeNonDisjoint(entry.interval2) == entry.results[1], @\"entry: %zu\",\n              entry.runningNumber);\n    XCTAssert(entry.interval1.startsAfter(entry.interval2) == entry.results[2], @\"entry: %zu\", entry.runningNumber);\n    XCTAssert(entry.interval1.startsAfterDisjoint(entry.interval2) == entry.results[3], @\"entry: %zu\",\n              entry.runningNumber);\n    XCTAssert(entry.interval1.startsAfterNonDisjoint(entry.interval2) == entry.results[4], @\"entry: %zu\",\n              entry.runningNumber);\n    XCTAssert(entry.interval1.disjoint(entry.interval2) == entry.results[5], @\"entry: %zu\", entry.runningNumber);\n    XCTAssert(entry.interval1.adjacent(entry.interval2) == entry.results[6], @\"entry: %zu\", entry.runningNumber);\n    XCTAssert(entry.interval1.properlyContains(entry.interval2) == entry.results[7], @\"entry: %zu\",\n              entry.runningNumber);\n  }\n\n  XCTAssert(Interval().Union(Interval(10, 100UL)) == Interval(-1L, 100));\n  XCTAssert(Interval(10, 10UL).Union(Interval(10, 100UL)) == Interval(10, 100UL));\n  XCTAssert(Interval(10, 11UL).Union(Interval(10, 100UL)) == Interval(10, 100UL));\n  XCTAssert(Interval(10, 1000UL).Union(Interval(10, 100UL)) == Interval(10, 1000UL));\n  XCTAssert(Interval(1000, 30UL).Union(Interval(10, 100UL)) == Interval(10, 100UL));\n  XCTAssert(Interval(1000, 2000UL).Union(Interval(10, 100UL)) == Interval(10, 2000UL));\n  XCTAssert(Interval(500, 2000UL).Union(Interval(10, 1000UL)) == Interval(10, 2000UL));\n\n  XCTAssert(Interval().intersection(Interval(10, 100UL)) == Interval(10, -2L));\n  XCTAssert(Interval(10, 10UL).intersection(Interval(10, 100UL)) == Interval(10, 10UL));\n  XCTAssert(Interval(10, 11UL).intersection(Interval(10, 100UL)) == Interval(10, 11UL));\n  XCTAssert(Interval(10, 1000UL).intersection(Interval(10, 100UL)) == Interval(10, 100UL));\n  XCTAssert(Interval(1000, 30UL).intersection(Interval(10, 100UL)) == Interval(1000, 30UL));\n  XCTAssert(Interval(1000, 2000UL).intersection(Interval(10, 100UL)) == Interval(1000, 100UL));\n  XCTAssert(Interval(500, 2000UL).intersection(Interval(10, 1000UL)) == Interval(500, 1000UL));\n\n  XCTAssert(Interval().toString() == \"-1..-2\");\n  XCTAssert(Interval(10, 10UL).toString() == \"10..10\");\n  XCTAssert(Interval(1000, 2000UL).toString() == \"1000..2000\");\n  XCTAssert(Interval(500UL, INT_MAX).toString() == \"500..\" + std::to_string(INT_MAX));\n}\n\n- (void)testIntervalSet {\n  XCTAssertFalse(IntervalSet().isReadOnly());\n  XCTAssert(IntervalSet().isEmpty());\n\n  IntervalSet set1;\n  set1.setReadOnly(true);\n  XCTAssert(set1.isReadOnly());\n\n  XCTAssert(IntervalSet() == IntervalSet::EMPTY_SET);\n\n  std::vector<Interval> intervals = { Interval(), Interval(10, 20UL), Interval(20, 100UL), Interval(1000, 2000UL) };\n  IntervalSet set2(intervals);\n  XCTAssertFalse(set2.isEmpty());\n  XCTAssertFalse(set2.contains(9UL));\n  XCTAssert(set2.contains(10UL));\n  XCTAssert(set2.contains(20UL));\n  XCTAssertTrue(set2.contains(22UL));\n  XCTAssert(set2.contains(1111UL));\n  XCTAssertFalse(set2.contains(10000UL));\n  XCTAssertEqual(set2.getSingleElement(), Token::INVALID_TYPE);\n  XCTAssertEqual(set2.getMinElement(), -1);\n  XCTAssertEqual(set2.getMaxElement(), 2000);\n\n  IntervalSet set3(set2);\n  XCTAssertFalse(set3.isEmpty());\n  XCTAssertFalse(set3.contains(9UL));\n  XCTAssert(set3.contains(10UL));\n  XCTAssert(set3.contains(20UL));\n  XCTAssertTrue(set3.contains(22UL));\n  XCTAssert(set3.contains(1111UL));\n  XCTAssertFalse(set3.contains(10000UL));\n  XCTAssertEqual(set3.getSingleElement(), Token::INVALID_TYPE);\n  XCTAssertEqual(set3.getMinElement(), 10);\n  XCTAssertEqual(set3.getMaxElement(), 2000);\n\n  set3.add(Interval(100, 1000UL));\n  XCTAssertEqual(set3.getMinElement(), 10);\n  set3.add(Interval(9, 1000UL));\n  XCTAssertEqual(set3.getMinElement(), 9);\n  set3.add(Interval(1, 1UL));\n  XCTAssertEqual(set3.getMinElement(), 1);\n\n  IntervalSet set4;\n  set4.add(10);\n  XCTAssertEqual(set4.getSingleElement(), 10);\n  XCTAssertEqual(set4.getMinElement(), 10);\n  XCTAssertEqual(set4.getMaxElement(), 10);\n\n  set4.clear();\n  XCTAssert(set4.isEmpty());\n  set4.add(Interval(10, 10UL));\n  XCTAssertEqual(set4.getSingleElement(), 10);\n  XCTAssertEqual(set4.getMinElement(), 10);\n  XCTAssertEqual(set4.getMaxElement(), 10);\n  set4.setReadOnly(true);\n  try {\n    set4.clear();\n    XCTFail(@\"Expected exception\");\n  } catch (IllegalStateException &e) {\n  }\n\n  try {\n    set4.setReadOnly(false);\n    XCTFail(@\"Expected exception\");\n  } catch (IllegalStateException &e) {\n  }\n\n  try {\n    set4 = IntervalSet::of(12345);\n    XCTFail(@\"Expected exception\");\n  } catch (IllegalStateException &e) {\n  }\n\n  IntervalSet set5 = IntervalSet::of(12345);\n  XCTAssertEqual(set5.getSingleElement(), 12345);\n  XCTAssertEqual(set5.getMinElement(), 12345);\n  XCTAssertEqual(set5.getMaxElement(), 12345);\n\n  IntervalSet set6(10, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50);\n  XCTAssertEqual(set6.getMinElement(), 5);\n  XCTAssertEqual(set6.getMaxElement(), 50);\n  XCTAssertEqual(set6.size(), 10U);\n  set6.add(12, 18);\n  XCTAssertEqual(set6.size(), 16U); // (15, 15) replaced by (12, 18)\n  set6.add(9, 33);\n  XCTAssertEqual(set6.size(), 30U); // (10, 10), (12, 18), (20, 20), (25, 25) and (30, 30) replaced by (9, 33)\n\n  XCTAssert(IntervalSet(3, 1, 2, 10).Or(IntervalSet(3, 1, 2, 5)) == IntervalSet(4, 1, 2, 5, 10));\n  XCTAssert(IntervalSet({ Interval(2, 10UL) }).Or(IntervalSet({ Interval(5, 8UL) })) == IntervalSet({ Interval(2, 10UL) }));\n\n  XCTAssert(IntervalSet::of(1, 10).complement(IntervalSet::of(7, 55)) == IntervalSet::of(11, 55));\n  XCTAssert(IntervalSet::of(1, 10).complement(IntervalSet::of(20, 55)) == IntervalSet::of(20, 55));\n  XCTAssert(IntervalSet::of(1, 10).complement(IntervalSet::of(5, 6)) == IntervalSet::EMPTY_SET);\n  XCTAssert(IntervalSet::of(15, 20).complement(IntervalSet::of(7, 55)) ==\n            IntervalSet({ Interval(7, 14UL), Interval(21, 55UL) }));\n  XCTAssert(IntervalSet({ Interval(1, 10UL), Interval(30, 35UL) }).complement(IntervalSet::of(7, 55)) ==\n            IntervalSet({ Interval(11, 29UL), Interval(36, 55UL) }));\n\n  XCTAssert(IntervalSet::of(1, 10).And(IntervalSet::of(7, 55)) == IntervalSet::of(7, 10));\n  XCTAssert(IntervalSet::of(1, 10).And(IntervalSet::of(20, 55)) == IntervalSet::EMPTY_SET);\n  XCTAssert(IntervalSet::of(1, 10).And(IntervalSet::of(5, 6)) == IntervalSet::of(5, 6));\n  XCTAssert(IntervalSet::of(15, 20).And(IntervalSet::of(7, 55)) == IntervalSet::of(15, 20));\n\n  XCTAssert(IntervalSet::of(1, 10).subtract(IntervalSet::of(7, 55)) == IntervalSet::of(1, 6));\n  XCTAssert(IntervalSet::of(1, 10).subtract(IntervalSet::of(20, 55)) == IntervalSet::of(1, 10));\n  XCTAssert(IntervalSet::of(1, 10).subtract(IntervalSet::of(5, 6)) ==\n            IntervalSet({ Interval(1, 4UL), Interval(7, 10UL) }));\n  XCTAssert(IntervalSet::of(15, 20).subtract(IntervalSet::of(7, 55)) == IntervalSet::EMPTY_SET);\n}\n\n@end\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp Tests/antlrcpp_Tests.mm",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2015 Dan McLaughlin\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#import <Cocoa/Cocoa.h>\n#import <XCTest/XCTest.h>\n\n#include \"ParserATNSimulator.h\"\n#include \"DFA.h\"\n#include \"ATN.h\"\n\n#include <vector>\n\nusing namespace antlr4;\n\n@interface antlrcpp_Tests : XCTestCase\n\n@end\n\n@implementation antlrcpp_Tests\n\n- (void)setUp {\n    [super setUp];\n    // Put setup code here. This method is called before the invocation of each test method in the class.\n}\n\n- (void)tearDown {\n    // Put teardown code here. This method is called after the invocation of each test method in the class.\n    [super tearDown];\n}\n\n@end\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp-demo.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 46;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t2707D9C22764C11300D99A45 /* libantlr4-runtime.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 2707D9BC2764C04C00D99A45 /* libantlr4-runtime.dylib */; };\n\t\t270925B11CDB455B00522D32 /* TLexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27A23EA11CC2A8D60036D8A3 /* TLexer.cpp */; };\n\t\t2747A7131CA6C46C0030247B /* InputHandlingTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2747A7121CA6C46C0030247B /* InputHandlingTests.mm */; };\n\t\t274FC6D91CA96B6C008D4374 /* MiscClassTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 274FC6D81CA96B6C008D4374 /* MiscClassTests.mm */; };\n\t\t27C66A6A1C9591280021E494 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C66A691C9591280021E494 /* main.cpp */; };\n\t\t27C6E1801C972FFC0079AF06 /* TParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E1741C972FFC0079AF06 /* TParser.cpp */; };\n\t\t27C6E1811C972FFC0079AF06 /* TParserBaseListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E1771C972FFC0079AF06 /* TParserBaseListener.cpp */; };\n\t\t27C6E1821C972FFC0079AF06 /* TParserBaseVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E1791C972FFC0079AF06 /* TParserBaseVisitor.cpp */; };\n\t\t27C6E1831C972FFC0079AF06 /* TParserListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E17B1C972FFC0079AF06 /* TParserListener.cpp */; };\n\t\t27C6E1841C972FFC0079AF06 /* TParserVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E17D1C972FFC0079AF06 /* TParserVisitor.cpp */; };\n\t\t37F1356D1B4AC02800E0CACF /* antlrcpp_Tests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 37F1356C1B4AC02800E0CACF /* antlrcpp_Tests.mm */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXContainerItemProxy section */\n\t\t2707D9BB2764C04C00D99A45 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 37D727AA1867AF1E007B6D10;\n\t\t\tremoteInfo = antlr4;\n\t\t};\n\t\t2707D9BD2764C04C00D99A45 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 37C147171B4D5A04008EDDDB;\n\t\t\tremoteInfo = antlr4_static;\n\t\t};\n\t\t2707D9BF2764C04C00D99A45 /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;\n\t\t\tproxyType = 2;\n\t\t\tremoteGlobalIDString = 270C67F01CDB4F1E00116E17;\n\t\t\tremoteInfo = antlr4_ios;\n\t\t};\n/* End PBXContainerItemProxy section */\n\n/* Begin PBXCopyFilesBuildPhase section */\n\t\t27C66A651C9591280021E494 /* CopyFiles */ = {\n\t\t\tisa = PBXCopyFilesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tdstPath = /usr/share/man/man1/;\n\t\t\tdstSubfolderSpec = 0;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 1;\n\t\t};\n/* End PBXCopyFilesBuildPhase section */\n\n/* Begin PBXFileReference section */\n\t\t2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = antlrcpp.xcodeproj; path = ../../runtime/antlrcpp.xcodeproj; sourceTree = \"<group>\"; };\n\t\t2747A7121CA6C46C0030247B /* InputHandlingTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InputHandlingTests.mm; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t274FC6D81CA96B6C008D4374 /* MiscClassTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MiscClassTests.mm; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; };\n\t\t27A23EA11CC2A8D60036D8A3 /* TLexer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TLexer.cpp; path = ../generated/TLexer.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27A23EA21CC2A8D60036D8A3 /* TLexer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TLexer.h; path = ../generated/TLexer.h; sourceTree = \"<group>\"; };\n\t\t27C66A671C9591280021E494 /* antlr4-cpp-demo */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.executable\"; includeInIndex = 0; path = \"antlr4-cpp-demo\"; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t27C66A691C9591280021E494 /* main.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27C66A731C9592400021E494 /* TLexer.g4 */ = {isa = PBXFileReference; lastKnownFileType = text; name = TLexer.g4; path = ../../TLexer.g4; sourceTree = \"<group>\"; };\n\t\t27C66A741C9592400021E494 /* TParser.g4 */ = {isa = PBXFileReference; lastKnownFileType = text; name = TParser.g4; path = ../../TParser.g4; sourceTree = \"<group>\"; };\n\t\t27C6E1741C972FFC0079AF06 /* TParser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParser.cpp; path = ../generated/TParser.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27C6E1751C972FFC0079AF06 /* TParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParser.h; path = ../generated/TParser.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27C6E1771C972FFC0079AF06 /* TParserBaseListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserBaseListener.cpp; path = ../generated/TParserBaseListener.cpp; sourceTree = \"<group>\"; };\n\t\t27C6E1781C972FFC0079AF06 /* TParserBaseListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserBaseListener.h; path = ../generated/TParserBaseListener.h; sourceTree = \"<group>\"; };\n\t\t27C6E1791C972FFC0079AF06 /* TParserBaseVisitor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserBaseVisitor.cpp; path = ../generated/TParserBaseVisitor.cpp; sourceTree = \"<group>\"; };\n\t\t27C6E17B1C972FFC0079AF06 /* TParserListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserListener.cpp; path = ../generated/TParserListener.cpp; sourceTree = \"<group>\"; };\n\t\t27C6E17C1C972FFC0079AF06 /* TParserListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserListener.h; path = ../generated/TParserListener.h; sourceTree = \"<group>\"; };\n\t\t27C6E17D1C972FFC0079AF06 /* TParserVisitor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserVisitor.cpp; path = ../generated/TParserVisitor.cpp; sourceTree = \"<group>\"; };\n\t\t27C6E1851C97322F0079AF06 /* TParserBaseVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserBaseVisitor.h; path = ../generated/TParserBaseVisitor.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27C6E1861C97322F0079AF06 /* TParserVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserVisitor.h; path = ../generated/TParserVisitor.h; sourceTree = \"<group>\"; };\n\t\t37F135681B4AC02800E0CACF /* antlrcpp Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = \"antlrcpp Tests.xctest\"; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t37F1356B1B4AC02800E0CACF /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = \"<group>\"; };\n\t\t37F1356C1B4AC02800E0CACF /* antlrcpp_Tests.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = antlrcpp_Tests.mm; sourceTree = \"<group>\"; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\t27C66A641C9591280021E494 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t2707D9C22764C11300D99A45 /* libantlr4-runtime.dylib in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37F135651B4AC02800E0CACF /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t2707D9B62764C04C00D99A45 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t2707D9BC2764C04C00D99A45 /* libantlr4-runtime.dylib */,\n\t\t\t\t2707D9BE2764C04C00D99A45 /* libantlr4-runtime.a */,\n\t\t\t\t2707D9C02764C04C00D99A45 /* antlr4_ios.framework */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t2707D9C12764C11300D99A45 /* Frameworks */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t);\n\t\t\tname = Frameworks;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t27874F221CCBB34200AF1C53 /* Linked Frameworks */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */,\n\t\t\t);\n\t\t\tname = \"Linked Frameworks\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t27C66A5C1C958EB50021E494 /* generated */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t27A23EA11CC2A8D60036D8A3 /* TLexer.cpp */,\n\t\t\t\t27A23EA21CC2A8D60036D8A3 /* TLexer.h */,\n\t\t\t\t27C6E1741C972FFC0079AF06 /* TParser.cpp */,\n\t\t\t\t27C6E1751C972FFC0079AF06 /* TParser.h */,\n\t\t\t\t27C6E1771C972FFC0079AF06 /* TParserBaseListener.cpp */,\n\t\t\t\t27C6E1781C972FFC0079AF06 /* TParserBaseListener.h */,\n\t\t\t\t27C6E1791C972FFC0079AF06 /* TParserBaseVisitor.cpp */,\n\t\t\t\t27C6E1851C97322F0079AF06 /* TParserBaseVisitor.h */,\n\t\t\t\t27C6E17B1C972FFC0079AF06 /* TParserListener.cpp */,\n\t\t\t\t27C6E17C1C972FFC0079AF06 /* TParserListener.h */,\n\t\t\t\t27C6E17D1C972FFC0079AF06 /* TParserVisitor.cpp */,\n\t\t\t\t27C6E1861C97322F0079AF06 /* TParserVisitor.h */,\n\t\t\t);\n\t\t\tname = generated;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t27C66A681C9591280021E494 /* antlr4-cpp-demo */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t27C66A691C9591280021E494 /* main.cpp */,\n\t\t\t\t27C66A731C9592400021E494 /* TLexer.g4 */,\n\t\t\t\t27C66A741C9592400021E494 /* TParser.g4 */,\n\t\t\t);\n\t\t\tpath = \"antlr4-cpp-demo\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t37D727A11867AF1E007B6D10 = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */,\n\t\t\t\t27C66A681C9591280021E494 /* antlr4-cpp-demo */,\n\t\t\t\t37F135691B4AC02800E0CACF /* antlrcpp Tests */,\n\t\t\t\t27C66A5C1C958EB50021E494 /* generated */,\n\t\t\t\t27874F221CCBB34200AF1C53 /* Linked Frameworks */,\n\t\t\t\t37D727AB1867AF1E007B6D10 /* Products */,\n\t\t\t\t2707D9C12764C11300D99A45 /* Frameworks */,\n\t\t\t);\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t37D727AB1867AF1E007B6D10 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t37F135681B4AC02800E0CACF /* antlrcpp Tests.xctest */,\n\t\t\t\t27C66A671C9591280021E494 /* antlr4-cpp-demo */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t37F135691B4AC02800E0CACF /* antlrcpp Tests */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t37F1356A1B4AC02800E0CACF /* Supporting Files */,\n\t\t\t\t37F1356C1B4AC02800E0CACF /* antlrcpp_Tests.mm */,\n\t\t\t\t2747A7121CA6C46C0030247B /* InputHandlingTests.mm */,\n\t\t\t\t274FC6D81CA96B6C008D4374 /* MiscClassTests.mm */,\n\t\t\t);\n\t\t\tpath = \"antlrcpp Tests\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t37F1356A1B4AC02800E0CACF /* Supporting Files */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t37F1356B1B4AC02800E0CACF /* Info.plist */,\n\t\t\t);\n\t\t\tname = \"Supporting Files\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXNativeTarget section */\n\t\t27C66A661C9591280021E494 /* antlr4-cpp-demo */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 27C66A6B1C9591280021E494 /* Build configuration list for PBXNativeTarget \"antlr4-cpp-demo\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t27C66A721C9591EF0021E494 /* Generate Parser */,\n\t\t\t\t27C66A631C9591280021E494 /* Sources */,\n\t\t\t\t27C66A641C9591280021E494 /* Frameworks */,\n\t\t\t\t27C66A651C9591280021E494 /* CopyFiles */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = \"antlr4-cpp-demo\";\n\t\t\tproductName = \"antlr4-cpp-demo\";\n\t\t\tproductReference = 27C66A671C9591280021E494 /* antlr4-cpp-demo */;\n\t\t\tproductType = \"com.apple.product-type.tool\";\n\t\t};\n\t\t37F135671B4AC02800E0CACF /* antlrcpp Tests */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 37F135731B4AC02800E0CACF /* Build configuration list for PBXNativeTarget \"antlrcpp Tests\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t37F135641B4AC02800E0CACF /* Sources */,\n\t\t\t\t37F135651B4AC02800E0CACF /* Frameworks */,\n\t\t\t\t37F135661B4AC02800E0CACF /* Resources */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = \"antlrcpp Tests\";\n\t\t\tproductName = \"antlrcpp Tests\";\n\t\t\tproductReference = 37F135681B4AC02800E0CACF /* antlrcpp Tests.xctest */;\n\t\t\tproductType = \"com.apple.product-type.bundle.unit-test\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t37D727A21867AF1E007B6D10 /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tLastUpgradeCheck = 1010;\n\t\t\t\tORGANIZATIONNAME = \"ANTLR4 Project\";\n\t\t\t\tTargetAttributes = {\n\t\t\t\t\t27C66A661C9591280021E494 = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 7.2.1;\n\t\t\t\t\t};\n\t\t\t\t\t37F135671B4AC02800E0CACF = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 6.3.2;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tbuildConfigurationList = 37D727A51867AF1E007B6D10 /* Build configuration list for PBXProject \"antlrcpp-demo\" */;\n\t\t\tcompatibilityVersion = \"Xcode 3.2\";\n\t\t\tdevelopmentRegion = English;\n\t\t\thasScannedForEncodings = 0;\n\t\t\tknownRegions = (\n\t\t\t\tEnglish,\n\t\t\t\ten,\n\t\t\t);\n\t\t\tmainGroup = 37D727A11867AF1E007B6D10;\n\t\t\tproductRefGroup = 37D727AB1867AF1E007B6D10 /* Products */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectReferences = (\n\t\t\t\t{\n\t\t\t\t\tProductGroup = 2707D9B62764C04C00D99A45 /* Products */;\n\t\t\t\t\tProjectRef = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;\n\t\t\t\t},\n\t\t\t);\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\t37F135671B4AC02800E0CACF /* antlrcpp Tests */,\n\t\t\t\t27C66A661C9591280021E494 /* antlr4-cpp-demo */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXReferenceProxy section */\n\t\t2707D9BC2764C04C00D99A45 /* libantlr4-runtime.dylib */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = \"compiled.mach-o.dylib\";\n\t\t\tpath = \"libantlr4-runtime.dylib\";\n\t\t\tremoteRef = 2707D9BB2764C04C00D99A45 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\t2707D9BE2764C04C00D99A45 /* libantlr4-runtime.a */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = archive.ar;\n\t\t\tpath = \"libantlr4-runtime.a\";\n\t\t\tremoteRef = 2707D9BD2764C04C00D99A45 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n\t\t2707D9C02764C04C00D99A45 /* antlr4_ios.framework */ = {\n\t\t\tisa = PBXReferenceProxy;\n\t\t\tfileType = wrapper.framework;\n\t\t\tpath = antlr4_ios.framework;\n\t\t\tremoteRef = 2707D9BF2764C04C00D99A45 /* PBXContainerItemProxy */;\n\t\t\tsourceTree = BUILT_PRODUCTS_DIR;\n\t\t};\n/* End PBXReferenceProxy section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\t37F135661B4AC02800E0CACF /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXShellScriptBuildPhase section */\n\t\t27C66A721C9591EF0021E494 /* Generate Parser */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t);\n\t\t\tname = \"Generate Parser\";\n\t\t\toutputPaths = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"pushd ..\\nif [ TParser.g4 -nt generated/TParser.cpp  -o  TLexer.g4 -nt generated/TLexer.cpp ]; then\\n./generate.sh;\\nfi\\npopd\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n/* End PBXShellScriptBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\t27C66A631C9591280021E494 /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t27C66A6A1C9591280021E494 /* main.cpp in Sources */,\n\t\t\t\t27C6E1821C972FFC0079AF06 /* TParserBaseVisitor.cpp in Sources */,\n\t\t\t\t270925B11CDB455B00522D32 /* TLexer.cpp in Sources */,\n\t\t\t\t27C6E1831C972FFC0079AF06 /* TParserListener.cpp in Sources */,\n\t\t\t\t27C6E1811C972FFC0079AF06 /* TParserBaseListener.cpp in Sources */,\n\t\t\t\t27C6E1841C972FFC0079AF06 /* TParserVisitor.cpp in Sources */,\n\t\t\t\t27C6E1801C972FFC0079AF06 /* TParser.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37F135641B4AC02800E0CACF /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t37F1356D1B4AC02800E0CACF /* antlrcpp_Tests.mm in Sources */,\n\t\t\t\t2747A7131CA6C46C0030247B /* InputHandlingTests.mm in Sources */,\n\t\t\t\t274FC6D91CA96B6C008D4374 /* MiscClassTests.mm in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin XCBuildConfiguration section */\n\t\t27C66A6C1C9591280021E494 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = YES;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t27C66A6D1C9591280021E494 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCODE_SIGN_IDENTITY = \"-\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t37D727B51867AF1E007B6D10 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_TESTABILITY = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_ENABLE_OBJC_EXCEPTIONS = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = NO;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_SIGN_COMPARE = YES;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_PARAMETER = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\t../../runtime/src/tree/pattern,\n\t\t\t\t\t../../runtime/src/tree,\n\t\t\t\t\t../../runtime/src/support,\n\t\t\t\t\t../../runtime/src/misc,\n\t\t\t\t\t../../runtime/src/dfa,\n\t\t\t\t\t../../runtime/src/atn,\n\t\t\t\t\t../../runtime/src,\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 11.1;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t37D727B61867AF1E007B6D10 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCOPY_PHASE_STRIP = YES;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tENABLE_NS_ASSERTIONS = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_ENABLE_OBJC_EXCEPTIONS = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_SIGN_COMPARE = YES;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_PARAMETER = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\t../../runtime/src/tree/pattern,\n\t\t\t\t\t../../runtime/src/tree,\n\t\t\t\t\t../../runtime/src/support,\n\t\t\t\t\t../../runtime/src/misc,\n\t\t\t\t\t../../runtime/src/dfa,\n\t\t\t\t\t../../runtime/src/atn,\n\t\t\t\t\t../../runtime/src,\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 11.1;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t37F135711B4AC02800E0CACF /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tFRAMEWORK_SEARCH_PATHS = (\n\t\t\t\t\t\"$(DEVELOPER_FRAMEWORKS_DIR)\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tINFOPLIST_FILE = \"antlrcpp Tests/Info.plist\";\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = \"$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks\";\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = YES;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"com.antlr.$(PRODUCT_NAME:rfc1034identifier)\";\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t37F135721B4AC02800E0CACF /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tFRAMEWORK_SEARCH_PATHS = (\n\t\t\t\t\t\"$(DEVELOPER_FRAMEWORKS_DIR)\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tINFOPLIST_FILE = \"antlrcpp Tests/Info.plist\";\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = \"$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks\";\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"com.antlr.$(PRODUCT_NAME:rfc1034identifier)\";\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t27C66A6B1C9591280021E494 /* Build configuration list for PBXNativeTarget \"antlr4-cpp-demo\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t27C66A6C1C9591280021E494 /* Debug */,\n\t\t\t\t27C66A6D1C9591280021E494 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t37D727A51867AF1E007B6D10 /* Build configuration list for PBXProject \"antlrcpp-demo\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t37D727B51867AF1E007B6D10 /* Debug */,\n\t\t\t\t37D727B61867AF1E007B6D10 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t37F135731B4AC02800E0CACF /* Build configuration list for PBXNativeTarget \"antlrcpp Tests\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t37F135711B4AC02800E0CACF /* Debug */,\n\t\t\t\t37F135721B4AC02800E0CACF /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = 37D727A21867AF1E007B6D10 /* Project object */;\n}\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp-demo.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp-demo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp-demo.xcodeproj/xcshareddata/xcschemes/antlr4-cpp-demo.xcscheme",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1010\"\n   version = \"1.3\">\n   <BuildAction\n      parallelizeBuildables = \"YES\"\n      buildImplicitDependencies = \"YES\">\n      <BuildActionEntries>\n         <BuildActionEntry\n            buildForTesting = \"YES\"\n            buildForRunning = \"YES\"\n            buildForProfiling = \"YES\"\n            buildForArchiving = \"YES\"\n            buildForAnalyzing = \"YES\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"27C66A661C9591280021E494\"\n               BuildableName = \"antlr4-cpp-demo\"\n               BlueprintName = \"antlr4-cpp-demo\"\n               ReferencedContainer = \"container:antlrcpp-demo.xcodeproj\">\n            </BuildableReference>\n         </BuildActionEntry>\n      </BuildActionEntries>\n   </BuildAction>\n   <TestAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      codeCoverageEnabled = \"YES\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\">\n      <Testables>\n         <TestableReference\n            skipped = \"NO\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"37F135671B4AC02800E0CACF\"\n               BuildableName = \"antlrcpp Tests.xctest\"\n               BlueprintName = \"antlrcpp Tests\"\n               ReferencedContainer = \"container:antlrcpp-demo.xcodeproj\">\n            </BuildableReference>\n         </TestableReference>\n      </Testables>\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"27C66A661C9591280021E494\"\n            BuildableName = \"antlr4-cpp-demo\"\n            BlueprintName = \"antlr4-cpp-demo\"\n            ReferencedContainer = \"container:antlrcpp-demo.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n      <AdditionalOptions>\n      </AdditionalOptions>\n   </TestAction>\n   <LaunchAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      launchStyle = \"0\"\n      useCustomWorkingDirectory = \"NO\"\n      ignoresPersistentStateOnLaunch = \"NO\"\n      debugDocumentVersioning = \"YES\"\n      debugServiceExtension = \"internal\"\n      allowLocationSimulation = \"YES\">\n      <BuildableProductRunnable\n         runnableDebuggingMode = \"0\">\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"27C66A661C9591280021E494\"\n            BuildableName = \"antlr4-cpp-demo\"\n            BlueprintName = \"antlr4-cpp-demo\"\n            ReferencedContainer = \"container:antlrcpp-demo.xcodeproj\">\n         </BuildableReference>\n      </BuildableProductRunnable>\n      <AdditionalOptions>\n      </AdditionalOptions>\n   </LaunchAction>\n   <ProfileAction\n      buildConfiguration = \"Release\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\"\n      savedToolIdentifier = \"\"\n      useCustomWorkingDirectory = \"NO\"\n      debugDocumentVersioning = \"YES\">\n      <BuildableProductRunnable\n         runnableDebuggingMode = \"0\">\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"27C66A661C9591280021E494\"\n            BuildableName = \"antlr4-cpp-demo\"\n            BlueprintName = \"antlr4-cpp-demo\"\n            ReferencedContainer = \"container:antlrcpp-demo.xcodeproj\">\n         </BuildableReference>\n      </BuildableProductRunnable>\n   </ProfileAction>\n   <AnalyzeAction\n      buildConfiguration = \"Debug\">\n   </AnalyzeAction>\n   <ArchiveAction\n      buildConfiguration = \"Release\"\n      revealArchiveInOrganizer = \"YES\">\n   </ArchiveAction>\n</Scheme>\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/antlrcpp-demo.xcodeproj/xcshareddata/xcschemes/antlrcpp Tests.xcscheme",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1010\"\n   version = \"1.3\">\n   <BuildAction\n      parallelizeBuildables = \"YES\"\n      buildImplicitDependencies = \"YES\">\n   </BuildAction>\n   <TestAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\">\n      <Testables>\n         <TestableReference\n            skipped = \"NO\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"37F135671B4AC02800E0CACF\"\n               BuildableName = \"antlrcpp Tests.xctest\"\n               BlueprintName = \"antlrcpp Tests\"\n               ReferencedContainer = \"container:antlrcpp-demo.xcodeproj\">\n            </BuildableReference>\n         </TestableReference>\n      </Testables>\n      <AdditionalOptions>\n      </AdditionalOptions>\n   </TestAction>\n   <LaunchAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      launchStyle = \"0\"\n      useCustomWorkingDirectory = \"NO\"\n      ignoresPersistentStateOnLaunch = \"NO\"\n      debugDocumentVersioning = \"YES\"\n      debugServiceExtension = \"internal\"\n      allowLocationSimulation = \"YES\">\n      <AdditionalOptions>\n      </AdditionalOptions>\n   </LaunchAction>\n   <ProfileAction\n      buildConfiguration = \"Release\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\"\n      savedToolIdentifier = \"\"\n      useCustomWorkingDirectory = \"NO\"\n      debugDocumentVersioning = \"YES\">\n   </ProfileAction>\n   <AnalyzeAction\n      buildConfiguration = \"Debug\">\n   </AnalyzeAction>\n   <ArchiveAction\n      buildConfiguration = \"Release\"\n      revealArchiveInOrganizer = \"YES\">\n   </ArchiveAction>\n</Scheme>\n"
  },
  {
    "path": "runtime/Cpp/demo/Mac/build.sh",
    "content": "#!/bin/sh\n#   [The \"BSD license\"]\n#   Copyright (c) 2013 Terence Parr\n#   Copyright (c) 2013 Dan McLaughlin\n#   All rights reserved.\n\n#   Redistribution and use in source and binary forms, with or without\n#   modification, are permitted provided that the following conditions\n#   are met:\n\n#   1. Redistributions of source code must retain the above copyright\n#      notice, this list of conditions and the following disclaimer.\n#   2. Redistributions in binary form must reproduce the above copyright\n#      notice, this list of conditions and the following disclaimer in the\n#      documentation and/or other materials provided with the distribution.\n#   3. The name of the author may not be used to endorse or promote products\n#      derived from this software without specific prior written permission.\n\n#   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n#   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n#   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n#   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n#   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n#   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n#   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n#   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n#   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n#  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nCURRENT_DIR=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\nANTLRCPP_XCODEPROJ=\"${CURRENT_DIR}/antlrcpp.xcodeproj\"\n\n# OS X\nxcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp -configuration Release $@\nxcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp -configuration Debug $@\n\n# iOS\n#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone -configuration Release -sdk iphoneos $@\n#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone -configuration Debug -sdk iphoneos $@\n#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone_sim -configuration Release -sdk iphonesimulator $@\n#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone_sim -configuration Debug -sdk iphonesimulator $@\n\n"
  },
  {
    "path": "runtime/Cpp/demo/README.md",
    "content": "## Demo application for the ANTLR 4 C++ target\n\nThis demo app shows how to build the ANTLR runtime both as dynamic and static library and how to use a parser generated from a simple demo grammar.\n\nA few steps are necessary to get this to work:\n\n- Download the current ANTLR jar and place it in this folder.\n- Open the generation script for your platform (generate.cmd for Windows, generate.sh for *nix/OSX) and update the LOCATION var to the actual name of the jar you downloaded.\n- Run the generation script. This will generate a test parser + lexer, along with listener + visitor classes in a subfolder named \"generated\". This is where the demo application looks for these files.\n- Open the project in the folder that matches your system.\n- Compile and run.\n\nCompilation is done as described in the [runtime/cpp/readme.md](../README.md) file.\n"
  },
  {
    "path": "runtime/Cpp/demo/TLexer.g4",
    "content": "lexer grammar TLexer;\n\n// These are all supported lexer sections:\n\n// Lexer file header. Appears at the top of h + cpp files. Use e.g. for copyrights.\n@lexer::header {/* lexer header section */}\n\n// Appears before any #include in h + cpp files.\n@lexer::preinclude {/* lexer precinclude section */}\n\n// Follows directly after the standard #includes in h + cpp files.\n@lexer::postinclude {\n/* lexer postinclude section */\n#ifndef _WIN32\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#endif\n}\n\n// Directly preceds the lexer class declaration in the h file (e.g. for additional types etc.).\n@lexer::context {/* lexer context section */}\n\n// Appears in the public part of the lexer in the h file.\n@lexer::members {/* public lexer declarations section */\nbool canTestFoo() { return true; }\nbool isItFoo() { return true; }\nbool isItBar() { return true; }\n\nvoid myFooLexerAction() { /* do something*/ };\nvoid myBarLexerAction() { /* do something*/ };\n}\n\n// Appears in the private part of the lexer in the h file.\n@lexer::declarations {/* private lexer declarations/members section */}\n\n// Appears in line with the other class member definitions in the cpp file.\n@lexer::definitions {/* lexer definitions section */}\n\nchannels { CommentsChannel, DirectiveChannel }\n\ntokens {\n\tDUMMY\n}\n\nReturn: 'return';\nContinue: 'continue';\n\nINT: Digit+;\nDigit: [0-9];\n\nID: LETTER (LETTER | '0'..'9')*;\nfragment LETTER : [a-zA-Z\\u0080-\\u{10FFFF}];\n\nLessThan: '<';\nGreaterThan:  '>';\nEqual: '=';\nAnd: 'and';\n\nColon: ':';\nSemicolon: ';';\nPlus: '+';\nMinus: '-';\nStar: '*';\nOpenPar: '(';\nClosePar: ')';\nOpenCurly: '{' -> pushMode(Mode1);\nCloseCurly: '}' -> popMode;\nQuestionMark: '?';\nComma: ',' -> skip;\nDollar: '$' -> more, mode(Mode1);\nAmpersand: '&' -> type(DUMMY);\n\nString: '\"' .*? '\"';\nFoo: {canTestFoo()}? 'foo' {isItFoo()}? { myFooLexerAction(); };\nBar: 'bar' {isItBar()}? { myBarLexerAction(); };\nAny: Foo Dot Bar? DotDot Baz;\n\nComment : '#' ~[\\r\\n]* '\\r'? '\\n' -> channel(CommentsChannel);\nWS: [ \\t\\r\\n]+ -> channel(99);\n\nfragment Baz: 'Baz';\n\nmode Mode1;\nDot: '.';\n\nmode Mode2;\nDotDot: '..';\n"
  },
  {
    "path": "runtime/Cpp/demo/TParser.g4",
    "content": "parser grammar TParser;\n\noptions {\n\ttokenVocab = TLexer;\n}\n\n// These are all supported parser sections:\n\n// Parser file header. Appears at the top in all parser related files. Use e.g. for copyrights.\n@parser::header {/* parser/listener/visitor header section */}\n\n// Appears before any #include in h + cpp files.\n@parser::preinclude {/* parser precinclude section */}\n\n// Follows directly after the standard #includes in h + cpp files.\n@parser::postinclude {\n/* parser postinclude section */\n#ifndef _WIN32\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#endif\n}\n\n// Directly preceeds the parser class declaration in the h file (e.g. for additional types etc.).\n@parser::context {/* parser context section */}\n\n// Appears in the private part of the parser in the h file.\n// The function bodies could also appear in the definitions section, but I want to maximize\n// Java compatibility, so we can also create a Java parser from this grammar.\n// Still, some tweaking is necessary after the Java file generation (e.g. bool -> boolean).\n@parser::members {\n/* public parser declarations/members section */\nbool myAction() { return true; }\nbool doesItBlend() { return true; }\nvoid cleanUp() {}\nvoid doInit() {}\nvoid doAfter() {}\n}\n\n// Appears in the public part of the parser in the h file.\n@parser::declarations {/* private parser declarations section */}\n\n// Appears in line with the other class member definitions in the cpp file.\n@parser::definitions {/* parser definitions section */}\n\n// Additionally there are similar sections for (base)listener and (base)visitor files.\n@parser::listenerpreinclude {/* listener preinclude section */}\n@parser::listenerpostinclude {/* listener postinclude section */}\n@parser::listenerdeclarations {/* listener public declarations/members section */}\n@parser::listenermembers {/* listener private declarations/members section */}\n@parser::listenerdefinitions {/* listener definitions section */}\n\n@parser::baselistenerpreinclude {/* base listener preinclude section */}\n@parser::baselistenerpostinclude {/* base listener postinclude section */}\n@parser::baselistenerdeclarations {/* base listener public declarations/members section */}\n@parser::baselistenermembers {/* base listener private declarations/members section */}\n@parser::baselistenerdefinitions {/* base listener definitions section */}\n\n@parser::visitorpreinclude {/* visitor preinclude section */}\n@parser::visitorpostinclude {/* visitor postinclude section */}\n@parser::visitordeclarations {/* visitor public declarations/members section */}\n@parser::visitormembers {/* visitor private declarations/members section */}\n@parser::visitordefinitions {/* visitor definitions section */}\n\n@parser::basevisitorpreinclude {/* base visitor preinclude section */}\n@parser::basevisitorpostinclude {/* base visitor postinclude section */}\n@parser::basevisitordeclarations {/* base visitor public declarations/members section */}\n@parser::basevisitormembers {/* base visitor private declarations/members section */}\n@parser::basevisitordefinitions {/* base visitor definitions section */}\n\n// Actual grammar start.\nmain: stat+ EOF;\ndivide : ID (and_ GreaterThan)? {doesItBlend()}?;\nand_ @init{ doInit(); } @after { doAfter(); } : And ;\n\nconquer:\n\tdivide+\n\t| {doesItBlend()}? and_ { myAction(); }\n\t| ID (LessThan* divide)?? { $ID.text; }\n;\n\n// Unused rule to demonstrate some of the special features.\nunused[double input = 111] returns [double calculated] locals [int _a, double _b, int _c] @init{ doInit(); } @after { doAfter(); } :\n\tstat\n;\ncatch [...] {\n  // Replaces the standard exception handling.\n}\nfinally {\n  cleanUp();\n}\n\nunused2:\n\t(unused[1] .)+ (Colon | Semicolon | Plus)? ~Semicolon\n;\n\nstat: expr Equal expr Semicolon\n    | expr Semicolon\n;\n\nexpr: expr Star expr\n    | expr Plus expr\n    | OpenPar expr ClosePar\n    | <assoc = right> expr QuestionMark expr Colon expr\n    | <assoc = right> expr Equal expr\n    | identifier = id\n    | flowControl\n    | INT\n    | String\n;\n\nflowControl:\n\tReturn expr # Return\n\t| Continue # Continue\n;\n\nid: ID;\narray : OpenCurly el += INT (Comma el += INT)* CloseCurly;\nidarray : OpenCurly element += id (Comma element += id)* CloseCurly;\nany: t = .;\n"
  },
  {
    "path": "runtime/Cpp/demo/Windows/antlr4-cpp-demo/antlr4-cpp-demo-vs2022.vcxproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"14.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug DLL|Win32\">\n      <Configuration>Debug DLL</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug DLL|x64\">\n      <Configuration>Debug DLL</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug Static|Win32\">\n      <Configuration>Debug Static</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug Static|x64\">\n      <Configuration>Debug Static</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release DLL|Win32\">\n      <Configuration>Release DLL</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release DLL|x64\">\n      <Configuration>Release DLL</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release Static|Win32\">\n      <Configuration>Release Static</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release Static|x64\">\n      <Configuration>Release Static</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <ProjectGuid>{24EC5104-7402-4C76-B66B-27ADBE062D68}</ProjectGuid>\n    <Keyword>Win32Proj</Keyword>\n    <RootNamespace>antlr4cppdemo</RootNamespace>\n    <ProjectName>antlr4cpp-demo</ProjectName>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SDLCheck>true</SDLCheck>\n      <AdditionalIncludeDirectories>$(SolutionDir)..\\generated;$(SolutionDir)..\\..\\runtime\\src;$(SolutionDir)..\\..\\runtime\\src\\atn;$(SolutionDir)..\\..\\runtime\\src\\dfa;$(SolutionDir)..\\..\\runtime\\src\\misc;$(SolutionDir)..\\..\\runtime\\src\\support;$(SolutionDir)..\\..\\runtime\\src\\tree;$(SolutionDir)..\\..\\runtime\\src\\tree\\xpath;$(SolutionDir)..\\..\\runtime\\src\\tree\\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"..\\..\\generated\\TLexer.cpp\" />\n    <ClCompile Include=\"..\\..\\generated\\TParser.cpp\" />\n    <ClCompile Include=\"..\\..\\generated\\TParserBaseListener.cpp\" />\n    <ClCompile Include=\"..\\..\\generated\\TParserBaseVisitor.cpp\" />\n    <ClCompile Include=\"..\\..\\generated\\TParserListener.cpp\" />\n    <ClCompile Include=\"..\\..\\generated\\TParserVisitor.cpp\" />\n    <ClCompile Include=\"main.cpp\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"..\\..\\generated\\TLexer.h\" />\n    <ClInclude Include=\"..\\..\\generated\\TParser.h\" />\n    <ClInclude Include=\"..\\..\\generated\\TParserBaseListener.h\" />\n    <ClInclude Include=\"..\\..\\generated\\TParserBaseVisitor.h\" />\n    <ClInclude Include=\"..\\..\\generated\\TParserListener.h\" />\n    <ClInclude Include=\"..\\..\\generated\\TParserVisitor.h\" />\n    <ClInclude Include=\"main.h\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\..\\runtime\\antlr4cpp-vs2022.vcxproj\">\n      <Project>{a9762991-1b57-4dce-90c0-ee42b96947be}</Project>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n</Project>"
  },
  {
    "path": "runtime/Cpp/demo/Windows/antlr4-cpp-demo/antlr4-cpp-demo-vs2022.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"Source Files\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"Resource Files\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n    <Filter Include=\"generated\">\n      <UniqueIdentifier>{ef397b7b-1192-4d44-93ed-fadaec7622e8}</UniqueIdentifier>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"main.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"..\\..\\generated\\TParser.cpp\">\n      <Filter>generated</Filter>\n    </ClCompile>\n    <ClCompile Include=\"..\\..\\generated\\TParserBaseListener.cpp\">\n      <Filter>generated</Filter>\n    </ClCompile>\n    <ClCompile Include=\"..\\..\\generated\\TParserBaseVisitor.cpp\">\n      <Filter>generated</Filter>\n    </ClCompile>\n    <ClCompile Include=\"..\\..\\generated\\TParserListener.cpp\">\n      <Filter>generated</Filter>\n    </ClCompile>\n    <ClCompile Include=\"..\\..\\generated\\TParserVisitor.cpp\">\n      <Filter>generated</Filter>\n    </ClCompile>\n    <ClCompile Include=\"..\\..\\generated\\TLexer.cpp\">\n      <Filter>generated</Filter>\n    </ClCompile>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"..\\..\\generated\\TLexer.h\">\n      <Filter>generated</Filter>\n    </ClInclude>\n    <ClInclude Include=\"..\\..\\generated\\TParser.h\">\n      <Filter>generated</Filter>\n    </ClInclude>\n    <ClInclude Include=\"..\\..\\generated\\TParserBaseListener.h\">\n      <Filter>generated</Filter>\n    </ClInclude>\n    <ClInclude Include=\"..\\..\\generated\\TParserBaseVisitor.h\">\n      <Filter>generated</Filter>\n    </ClInclude>\n    <ClInclude Include=\"..\\..\\generated\\TParserListener.h\">\n      <Filter>generated</Filter>\n    </ClInclude>\n    <ClInclude Include=\"..\\..\\generated\\TParserVisitor.h\">\n      <Filter>generated</Filter>\n    </ClInclude>\n    <ClInclude Include=\"main.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "runtime/Cpp/demo/Windows/antlr4-cpp-demo/main.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n//\n//  main.cpp\n//  antlr4-cpp-demo\n//\n//  Created by Mike Lischke on 13.03.16.\n//\n\n#include <iostream>\n\n#include \"antlr4-runtime.h\"\n#include \"TLexer.h\"\n#include \"TParser.h\"\n\n#include <Windows.h>\n\n#pragma execution_character_set(\"utf-8\")\n\nusing namespace antlrcpptest;\nusing namespace antlr4;\n\nint main(int argc, const char * argv[]) {\n\n  ANTLRInputStream input(\"a = b + \\\"c\\\";(((x * d))) * e + f; a + (x * (y ? 0 : 1) + z);\");\n  TLexer lexer(&input);\n  CommonTokenStream tokens(&lexer);\n\n  TParser parser(&tokens);\n  tree::ParseTree *tree = parser.main();\n\n  auto s = tree->toStringTree(&parser);\n  std::cout << \"Parse Tree: \" << s << std::endl;\n\n  return 0;\n}\n"
  },
  {
    "path": "runtime/Cpp/demo/Windows/antlr4cpp-vs2022.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 17\nVisualStudioVersion = 17.0.32014.148\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"antlr4cpp-vs2022\", \"..\\..\\runtime\\antlr4cpp-vs2022.vcxproj\", \"{52618D4B-6EC4-49AD-8B83-52686244E8F3}\"\nEndProject\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"antlr4cpp-demo\", \"antlr4-cpp-demo\\antlr4-cpp-demo-vs2022.vcxproj\", \"{24EC5104-7402-4C76-B66B-27ADBE062D68}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug DLL|x64 = Debug DLL|x64\n\t\tDebug DLL|x86 = Debug DLL|x86\n\t\tDebug Static|x64 = Debug Static|x64\n\t\tDebug Static|x86 = Debug Static|x86\n\t\tRelease DLL|x64 = Release DLL|x64\n\t\tRelease DLL|x86 = Release DLL|x86\n\t\tRelease Static|x64 = Release Static|x64\n\t\tRelease Static|x86 = Release Static|x86\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x64.ActiveCfg = Debug DLL|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x64.Build.0 = Debug DLL|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x86.ActiveCfg = Debug DLL|Win32\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x86.Build.0 = Debug DLL|Win32\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x64.ActiveCfg = Debug Static|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x64.Build.0 = Debug Static|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x86.ActiveCfg = Debug Static|Win32\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x86.Build.0 = Debug Static|Win32\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x64.ActiveCfg = Release DLL|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x64.Build.0 = Release DLL|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x86.ActiveCfg = Release DLL|Win32\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x86.Build.0 = Release DLL|Win32\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x64.ActiveCfg = Release Static|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x64.Build.0 = Release Static|x64\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x86.ActiveCfg = Release Static|Win32\n\t\t{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x86.Build.0 = Release Static|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x64.ActiveCfg = Debug DLL|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x64.Build.0 = Debug DLL|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x86.ActiveCfg = Debug DLL|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x86.Build.0 = Debug DLL|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x64.ActiveCfg = Debug Static|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x64.Build.0 = Debug Static|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x86.ActiveCfg = Debug Static|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x86.Build.0 = Debug Static|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x64.ActiveCfg = Release DLL|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x64.Build.0 = Release DLL|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x86.ActiveCfg = Release DLL|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x86.Build.0 = Release DLL|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x64.ActiveCfg = Release Static|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x64.Build.0 = Release Static|x64\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x86.ActiveCfg = Release Static|Win32\n\t\t{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x86.Build.0 = Release Static|Win32\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {93CE9298-807C-4EAD-B1E6-7109DD1A78FA}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "runtime/Cpp/demo/generate.cmd",
    "content": "@echo off\n:: Created 2016, Mike Lischke (public domain)\n\n:: This script is used to generate source files from the test grammars in the same folder. The generated files are placed\n:: into a subfolder \"generated\" which the demo project uses to compile a demo binary.\n\n:: Download the ANLTR jar and place it in the same folder as this script (or adjust the LOCATION var accordingly).\n\nset LOCATION=antlr-4.13.2-complete.jar\njava -jar %LOCATION% -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4\n::java -jar %LOCATION% -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest -XdbgST TLexer.g4 TParser.g4\n::java -jar %LOCATION% -Dlanguage=Java -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4\n\n"
  },
  {
    "path": "runtime/Cpp/demo/generate.sh",
    "content": "#!/bin/bash\nset -o errexit\n\n# Created 2016, Mike Lischke (public domain)\n\n# This script is used to generate source files from the test grammars in the same folder. The generated files are placed\n# into a subfolder \"generated\" which the demo project uses to compile a demo binary.\n\n# There are 2 ways of running the ANTLR generator here.\n\n# 1) Running from jar. Use the given jar (or replace it by another one you built or downloaded) for generation.\n#LOCATION=antlr4-4.5.4-SNAPSHOT.jar\n#java -jar $LOCATION -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4\n#java -jar $LOCATION -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest -XdbgST TLexer.g4 TParser.g4\n#java -jar $LOCATION -Dlanguage=Java -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4\n\n# 2) Running from class path. This requires that you have both antlr3 and antlr4 compiled. In this scenario no installation\n#    is needed. You just compile the java class files (using \"mvn compile\" in both the antlr4 and the antlr3 root folders).\n#    The script then runs the generation using these class files, by specifying them on the classpath.\n#    Also the string template jar is needed. Adjust CLASSPATH if you have stored the jar in a different folder as this script assumes.\n#    Furthermore is assumed that the antlr3 folder is located side-by-side with the antlr4 folder. Adjust CLASSPATH if not.\n#    This approach is especially useful if you are working on a target stg file, as it doesn't require to regenerate the\n#    antlr jar over and over again.\nCLASSPATH=../../../tool/resources/:ST-4.0.8.jar:../../../tool/target/classes:../../../runtime/Java/target/classes:../../../../antlr3/runtime/Java/target/classes\n\njava -cp $CLASSPATH org.antlr.v4.Tool -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4\n#java -cp $CLASSPATH org.antlr.v4.Tool -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest -XdbgST TLexer.g4 TParser.g4\n#java -cp $CLASSPATH org.antlr.v4.Tool -Dlanguage=Java -listener -visitor -o generated/ TLexer.g4 TParser.g4\n"
  },
  {
    "path": "runtime/Cpp/deploy-macos.sh",
    "content": "#!/bin/bash\n\n# Clean left overs from previous builds if there are any\nrm -rf antlr4-runtime build lib\nrm -f antlr4-cpp-runtime-macos.zip\n\n# Binaries\ncmake . -D CMAKE_OSX_ARCHITECTURES=\"arm64; x86_64\" -DCMAKE_BUILD_TYPE=Release &> /dev/null\nmake -j 8\n\nrm -rf lib\nmkdir lib\ncp runtime/libantlr4-runtime.dylib lib\ncp runtime/libantlr4-runtime.a lib\n\n# Headers\nrm -f -R antlr4-runtime\npushd runtime/src\nfind . -name '*.h' | cpio -pdm ../../antlr4-runtime\npopd\n\n# Zip up and clean up\nzip -r antlr4-cpp-runtime-macos.zip antlr4-runtime lib\n\nrm -f -R antlr4-runtime build lib\n\n# Deploy\n#cp antlr4-cpp-runtime-macos.zip ~/antlr/sites/website-antlr4/download\n"
  },
  {
    "path": "runtime/Cpp/deploy-source.sh",
    "content": "#!/bin/bash\n\n# Zip it\nrm -f antlr4-cpp-runtime-source.zip\nzip -r antlr4-cpp-runtime-source.zip \"README.md\" \"cmake\" \"demo\" \"runtime\" \"CMakeLists.txt\" \"deploy-macos.sh\" \"deploy-source.sh\" \"deploy-windows.cmd\" \"VERSION\" \\\n  -X -x \"*.DS_Store*\" \"antlrcpp.xcodeproj/xcuserdata/*\" \"*Build*\" \"*DerivedData*\" \"*.jar\" \"demo/generated/*\" \"*.vscode*\" \"runtime/build/*\" \\\n  \"runtime/*.dylib\" \"*.a\" \"runtime/thirdparty/*\" \"runtime/CMakeFiles/*\"\n\n# Add the license file from the ANTLR root as well.\npushd ../../\nzip runtime/cpp/antlr4-cpp-runtime-source.zip LICENSE.txt\npopd\n\n# Deploy\n#cp antlr4-cpp-runtime-source.zip ~/antlr/sites/website-antlr4/download\n"
  },
  {
    "path": "runtime/Cpp/deploy-windows.cmd",
    "content": "@echo off\nsetlocal\n\nif [%1] == [] goto Usage\n\nrem Clean left overs from previous builds if there are any\nif exist bin rmdir /S /Q runtime\\bin\nif exist obj rmdir /S /Q runtime\\obj\nif exist lib rmdir /S /Q lib\nif exist antlr4-runtime rmdir /S /Q antlr4-runtime\nif exist antlr4-cpp-runtime-vs2019.zip erase antlr4-cpp-runtime-vs2019.zip\nif exist antlr4-cpp-runtime-vs2022.zip erase antlr4-cpp-runtime-vs2022.zip\n\nrem Headers\necho Copying header files ...\nxcopy runtime\\src\\*.h antlr4-runtime\\ /s /q\n\nrem Binaries\nrem VS 2019 disabled by default. Change the X to a C to enable it.\nif exist \"X:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\%1\\Common7\\Tools\\VsDevCmd.bat\" (\n  echo.\n\n  call \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\%1\\Common7\\Tools\\VsDevCmd.bat\"\n\n  pushd runtime\n  msbuild antlr4cpp-vs2019.vcxproj /p:configuration=\"Release DLL\" /p:platform=Win32\n  msbuild antlr4cpp-vs2019.vcxproj /p:configuration=\"Release DLL\" /p:platform=x64\n  popd\n\n  7z a antlr4-cpp-runtime-vs2019.zip antlr4-runtime\n  xcopy runtime\\bin\\*.dll lib\\ /s\n  xcopy runtime\\bin\\*.lib lib\\ /s\n  7z a antlr4-cpp-runtime-vs2019.zip lib\n\n  rmdir /S /Q lib\n  rmdir /S /Q runtime\\bin\n  rmdir /S /Q runtime\\obj\n\n  rem if exist antlr4-cpp-runtime-vs2019.zip copy antlr4-cpp-runtime-vs2019.zip ~/antlr/sites/website-antlr4/download\n)\n\nset VCTargetsPath=C:\\Program Files\\Microsoft Visual Studio\\2022\\%1\\MSBuild\\Microsoft\\VC\\v170\\\nif exist \"C:\\Program Files\\Microsoft Visual Studio\\2022\\%1\\Common7\\Tools\\VsDevCmd.bat\" (\n  echo.\n\n  call \"C:\\Program Files\\Microsoft Visual Studio\\2022\\%1\\Common7\\Tools\\VsDevCmd.bat\"\n\n  pushd runtime\n  msbuild antlr4cpp-vs2022.vcxproj /p:configuration=\"Release DLL\" /p:platform=Win32\n  msbuild antlr4cpp-vs2022.vcxproj /p:configuration=\"Release DLL\" /p:platform=x64\n  popd\n\n  7z a antlr4-cpp-runtime-vs2022.zip antlr4-runtime\n  xcopy runtime\\bin\\*.dll lib\\ /s\n  xcopy runtime\\bin\\*.lib lib\\ /s\n  7z a antlr4-cpp-runtime-vs2022.zip lib\n\n  rmdir /S /Q lib\n  rmdir /S /Q runtime\\bin\n  rmdir /S /Q runtime\\obj\n\n  rem if exist antlr4-cpp-runtime-vs2022.zip copy antlr4-cpp-runtime-vs2022.zip ~/antlr/sites/website-antlr4/download\n)\n\nrmdir /S /Q antlr4-runtime\necho.\necho === Build done ===\n\ngoto end\n\n:Usage\n\necho This script builds Visual Studio 2019 and/or 2022 libraries of the ANTLR4 runtime.\necho You have to specify the type of your VS installation (Community, Professional etc.) to construct\necho the correct build tools path.\necho.\necho Example:\necho   %0 Professional\necho.\n\n:end\n"
  },
  {
    "path": "runtime/Cpp/runtime/CMakeLists.txt",
    "content": "option(ANTLR_BUILD_CPP_TESTS \"Build C++ tests.\" ON)\noption(TRACE_ATN \"Trace ATN simulation\" OFF)\noption(ANTLR_BUILD_SHARED \"Build the shared library of the ANTLR runtime\" ON)\noption(ANTLR_BUILD_STATIC \"Build the static library of the ANTLR runtime\" ON)\n\nif (NOT ANTLR_BUILD_SHARED AND NOT ANTLR_BUILD_STATIC)\n  message(FATAL_ERROR \"Options ANTLR_BUILD_SHARED and ANTLR_BUILD_STATIC can't both be OFF\")\nendif()\n\nset(libantlrcpp_INCLUDE_INSTALL_DIR \"${CMAKE_INSTALL_INCLUDEDIR}/antlr4-runtime\")\n\nset(libantlrcpp_INCLUDE_DIRS\n  ${PROJECT_SOURCE_DIR}/runtime/src\n  ${PROJECT_SOURCE_DIR}/runtime/src/atn\n  ${PROJECT_SOURCE_DIR}/runtime/src/dfa\n  ${PROJECT_SOURCE_DIR}/runtime/src/internal\n  ${PROJECT_SOURCE_DIR}/runtime/src/misc\n  ${PROJECT_SOURCE_DIR}/runtime/src/support\n  ${PROJECT_SOURCE_DIR}/runtime/src/tree\n  ${PROJECT_SOURCE_DIR}/runtime/src/tree/pattern\n  ${PROJECT_SOURCE_DIR}/runtime/src/tree/xpath\n)\n\n\nfile(GLOB libantlrcpp_SRC\n  \"${PROJECT_SOURCE_DIR}/runtime/src/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/atn/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/dfa/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/internal/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/misc/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/support/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/tree/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/tree/pattern/*.cpp\"\n  \"${PROJECT_SOURCE_DIR}/runtime/src/tree/xpath/*.cpp\"\n)\n\nif (ANTLR_BUILD_SHARED)\n  add_library(antlr4_shared SHARED ${libantlrcpp_SRC})\n  target_include_directories(antlr4_shared PUBLIC \n    \"$<BUILD_INTERFACE:${libantlrcpp_INCLUDE_DIRS}>\" \n    \"$<INSTALL_INTERFACE:${libantlrcpp_INCLUDE_INSTALL_DIR}>\")\nendif()\nif (ANTLR_BUILD_STATIC)\n  add_library(antlr4_static STATIC ${libantlrcpp_SRC})\n  target_include_directories(antlr4_static PUBLIC \n    \"$<BUILD_INTERFACE:${libantlrcpp_INCLUDE_DIRS}>\" \n    \"$<INSTALL_INTERFACE:${libantlrcpp_INCLUDE_INSTALL_DIR}>\")\nendif()\n\nif (CMAKE_HOST_UNIX)\n  # Make sure to link against threads (pthreads) library in order to be able to\n  # make use of std::call_once in the code without producing runtime errors\n  # (see also https://github.com/antlr/antlr4/issues/3708 and/or https://stackoverflow.com/q/51584960).\n  find_package(Threads REQUIRED)\n\n  if (TARGET antlr4_shared)\n    target_link_libraries(antlr4_shared Threads::Threads)\n  endif()\n  if (TARGET antlr4_static)\n    target_link_libraries(antlr4_static Threads::Threads)\n  endif()\nendif()\n\nIF(TRACE_ATN)\n    ADD_DEFINITIONS(-DTRACE_ATN_SIM=1)\nENDIF(TRACE_ATN)\n\nif (ANTLR_BUILD_CPP_TESTS)\n  include(FetchContent)\n\n  FetchContent_Declare(\n    googletest\n    URL https://github.com/google/googletest/archive/refs/tags/v1.16.0.zip\n  )\n\n  if(WITH_STATIC_CRT)\n    set(gtest_force_shared_crt ON CACHE BOOL \"\" FORCE)\n  endif()\n\n  FetchContent_MakeAvailable(googletest)\n\n  file(GLOB libantlrcpp_TESTS\n    \"${PROJECT_SOURCE_DIR}/runtime/tests/*.cpp\"\n  )\n\n  add_executable(\n    antlr4_tests\n    ${libantlrcpp_TESTS}\n  )\n\n  target_link_libraries(\n    antlr4_tests\n\t$<IF:$<TARGET_EXISTS:antlr4_static>,antlr4_static,antlr4_shared>\n    gtest_main\n  )\n\n  include(GoogleTest)\n\n  gtest_discover_tests(antlr4_tests)\nendif()\n\nif(APPLE)\n  if (TARGET antlr4_shared)\n    target_link_libraries(antlr4_shared ${COREFOUNDATION_LIBRARY})\n  endif()\n  if (TARGET antlr4_static)\n    target_link_libraries(antlr4_static ${COREFOUNDATION_LIBRARY})\n  endif()\nendif()\n\nif(CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n  set(disabled_compile_warnings \"/wd4251\")\nelse()\n  set(disabled_compile_warnings \"-Wno-overloaded-virtual\")\nendif()\n\n\nif(CMAKE_CXX_COMPILER_ID MATCHES \"Clang\")\n  set(disabled_compile_warnings \"${disabled_compile_warnings} -Wno-dollar-in-identifier-extension -Wno-four-char-constants\")\nelseif(CMAKE_CXX_COMPILER_ID MATCHES \"GNU\" OR CMAKE_CXX_COMPILER_ID MATCHES \"Intel\")\n  set(disabled_compile_warnings \"${disabled_compile_warnings} -Wno-multichar\")\nendif()\n\nset(extra_share_compile_flags \"\")\nset(extra_static_compile_flags \"\")\nset(static_lib_suffix \"\")\n\nif (WIN32)\n  set(static_lib_suffix \"-static\")\n  if (TARGET antlr4_shared)\n    target_compile_definitions(antlr4_shared PUBLIC ANTLR4CPP_EXPORTS)\n  endif()\n  if (TARGET antlr4_static)\n    target_compile_definitions(antlr4_static PUBLIC ANTLR4CPP_STATIC)\n  endif()\n  if(CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n    set(extra_share_compile_flags \"-MP /wd4251\")\n    set(extra_static_compile_flags \"-MP\")\n  endif()\nendif()\n\nif (TARGET antlr4_shared)\n  set_target_properties(antlr4_shared\n                        PROPERTIES VERSION   ${ANTLR_VERSION}\n                                   SOVERSION ${ANTLR_VERSION}\n                                   OUTPUT_NAME antlr4-runtime\n                                   COMPILE_FLAGS \"${disabled_compile_warnings} ${extra_share_compile_flags}\")\nendif()\n\nif (TARGET antlr4_static)\n  set_target_properties(antlr4_static\n                        PROPERTIES VERSION   ${ANTLR_VERSION}\n                                   SOVERSION ${ANTLR_VERSION}\n                                   OUTPUT_NAME \"antlr4-runtime${static_lib_suffix}\"\n                                   COMPILE_PDB_NAME \"antlr4-runtime${static_lib_suffix}\"\n                                   COMPILE_FLAGS \"${disabled_compile_warnings} ${extra_static_compile_flags}\")\nendif()\n\nif (ANTLR_BUILD_CPP_TESTS)\n  # Copy the generated binaries to dist folder (required by test suite)\n  if (TARGET antlr4_shared)\n  add_custom_command(\n      TARGET antlr4_shared\n      POST_BUILD\n      COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_HOME_DIRECTORY}/dist\n      COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:antlr4_shared> ${CMAKE_HOME_DIRECTORY}/dist\n      COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_LINKER_FILE:antlr4_shared> ${CMAKE_HOME_DIRECTORY}/dist)\n  endif()\n  \n  if (TARGET antlr4_static)\n    add_custom_command(\n      TARGET antlr4_static\n      POST_BUILD\n      COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_HOME_DIRECTORY}/dist\n      COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:antlr4_static> ${CMAKE_HOME_DIRECTORY}/dist)\n  endif()\nendif()\n\nif (TARGET antlr4_shared)\n  install(TARGETS antlr4_shared\n          EXPORT antlr4-targets\n          ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}\n          LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}\n          RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})\nendif()\n\nif (TARGET antlr4_static)\n  install(TARGETS antlr4_static\n          EXPORT antlr4-targets\n          ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}\n          LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}\n          RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})\nendif()\n\ninstall(DIRECTORY \"${PROJECT_SOURCE_DIR}/runtime/src/\"\n        DESTINATION \"${libantlrcpp_INCLUDE_INSTALL_DIR}\"\n        COMPONENT dev\n        FILES_MATCHING PATTERN \"*.h\"\n        )\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlr4cpp-vs2019.vcxproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug Static|Win32\">\n      <Configuration>Debug Static</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug Static|x64\">\n      <Configuration>Debug Static</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug DLL|Win32\">\n      <Configuration>Debug DLL</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug DLL|x64\">\n      <Configuration>Debug DLL</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release Static|Win32\">\n      <Configuration>Release Static</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release Static|x64\">\n      <Configuration>Release Static</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release DLL|Win32\">\n      <Configuration>Release DLL</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release DLL|x64\">\n      <Configuration>Release DLL</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <ProjectGuid>{83BE66CD-9C4F-4F84-B72A-DD1855C8FC8A}</ProjectGuid>\n    <Keyword>Win32Proj</Keyword>\n    <RootNamespace>antlr4cpp</RootNamespace>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v142</PlatformToolset>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2019\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_DLL;ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_DLL;ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"src\\ANTLRErrorListener.cpp\" />\n    <ClCompile Include=\"src\\ANTLRErrorStrategy.cpp\" />\n    <ClCompile Include=\"src\\ANTLRFileStream.cpp\" />\n    <ClCompile Include=\"src\\ANTLRInputStream.cpp\" />\n    <ClCompile Include=\"src\\atn\\ActionTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\AmbiguityInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\ArrayPredictionContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATN.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNConfig.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNConfigSet.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNDeserializationOptions.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNDeserializer.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNState.cpp\" />\n    <ClCompile Include=\"src\\atn\\AtomTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\ContextSensitivityInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\DecisionEventInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\DecisionInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\DecisionState.cpp\" />\n    <ClCompile Include=\"src\\atn\\EpsilonTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\ErrorInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerActionExecutor.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerATNConfig.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerChannelAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerCustomAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerIndexedCustomAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerModeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerMoreAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerPopModeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerPushModeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerSkipAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerTypeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LL1Analyzer.cpp\" />\n    <ClCompile Include=\"src\\atn\\LookaheadEventInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\NotSetTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\OrderedATNConfigSet.cpp\" />\n    <ClCompile Include=\"src\\atn\\ParseInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\ParserATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\PrecedencePredicateTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredicateEvalInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredicateTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionContextCache.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionContextMergeCache.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionMode.cpp\" />\n    <ClCompile Include=\"src\\atn\\ProfilingATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\RangeTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\RuleTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\SemanticContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\SetTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\SingletonPredictionContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\StarLoopbackState.cpp\" />\n    <ClCompile Include=\"src\\atn\\Transition.cpp\" />\n    <ClCompile Include=\"src\\atn\\WildcardTransition.cpp\" />\n    <ClCompile Include=\"src\\BailErrorStrategy.cpp\" />\n    <ClCompile Include=\"src\\BaseErrorListener.cpp\" />\n    <ClCompile Include=\"src\\BufferedTokenStream.cpp\" />\n    <ClCompile Include=\"src\\CharStream.cpp\" />\n    <ClCompile Include=\"src\\CommonToken.cpp\" />\n    <ClCompile Include=\"src\\CommonTokenFactory.cpp\" />\n    <ClCompile Include=\"src\\CommonTokenStream.cpp\" />\n    <ClCompile Include=\"src\\ConsoleErrorListener.cpp\" />\n    <ClCompile Include=\"src\\DefaultErrorStrategy.cpp\" />\n    <ClCompile Include=\"src\\dfa\\DFA.cpp\" />\n    <ClCompile Include=\"src\\dfa\\DFASerializer.cpp\" />\n    <ClCompile Include=\"src\\dfa\\DFAState.cpp\" />\n    <ClCompile Include=\"src\\dfa\\LexerDFASerializer.cpp\" />\n    <ClCompile Include=\"src\\DiagnosticErrorListener.cpp\" />\n    <ClCompile Include=\"src\\Exceptions.cpp\" />\n    <ClCompile Include=\"src\\FailedPredicateException.cpp\" />\n    <ClCompile Include=\"src\\InputMismatchException.cpp\" />\n    <ClCompile Include=\"src\\internal\\Synchronization.cpp\" />\n    <ClCompile Include=\"src\\InterpreterRuleContext.cpp\" />\n    <ClCompile Include=\"src\\IntStream.cpp\" />\n    <ClCompile Include=\"src\\Lexer.cpp\" />\n    <ClCompile Include=\"src\\LexerInterpreter.cpp\" />\n    <ClCompile Include=\"src\\LexerNoViableAltException.cpp\" />\n    <ClCompile Include=\"src\\ListTokenSource.cpp\" />\n    <ClCompile Include=\"src\\misc\\InterpreterDataReader.cpp\" />\n    <ClCompile Include=\"src\\misc\\Interval.cpp\" />\n    <ClCompile Include=\"src\\misc\\IntervalSet.cpp\" />\n    <ClCompile Include=\"src\\misc\\MurmurHash.cpp\" />\n    <ClCompile Include=\"src\\misc\\Predicate.cpp\" />\n    <ClCompile Include=\"src\\NoViableAltException.cpp\" />\n    <ClCompile Include=\"src\\Parser.cpp\" />\n    <ClCompile Include=\"src\\ParserInterpreter.cpp\" />\n    <ClCompile Include=\"src\\ParserRuleContext.cpp\" />\n    <ClCompile Include=\"src\\ProxyErrorListener.cpp\" />\n    <ClCompile Include=\"src\\RecognitionException.cpp\" />\n    <ClCompile Include=\"src\\Recognizer.cpp\" />\n    <ClCompile Include=\"src\\RuleContext.cpp\" />\n    <ClCompile Include=\"src\\RuleContextWithAltNum.cpp\" />\n    <ClCompile Include=\"src\\RuntimeMetaData.cpp\" />\n    <ClCompile Include=\"src\\support\\Any.cpp\" />\n    <ClCompile Include=\"src\\support\\Arrays.cpp\" />\n    <ClCompile Include=\"src\\support\\CPPUtils.cpp\" />\n    <ClCompile Include=\"src\\support\\StringUtils.cpp\" />\n    <ClCompile Include=\"src\\support\\Utf8.cpp\" />\n    <ClCompile Include=\"src\\Token.cpp\" />\n    <ClCompile Include=\"src\\TokenSource.cpp\" />\n    <ClCompile Include=\"src\\TokenStream.cpp\" />\n    <ClCompile Include=\"src\\TokenStreamRewriter.cpp\" />\n    <ClCompile Include=\"src\\tree\\ErrorNodeImpl.cpp\" />\n    <ClCompile Include=\"src\\tree\\IterativeParseTreeWalker.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTree.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTreeListener.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTreeVisitor.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTreeWalker.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\Chunk.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreeMatch.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePattern.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\RuleTagToken.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\TagChunk.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\TextChunk.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\TokenTagToken.cpp\" />\n    <ClCompile Include=\"src\\tree\\TerminalNodeImpl.cpp\" />\n    <ClCompile Include=\"src\\tree\\Trees.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPath.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexer.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexerErrorListener.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardElement.cpp\" />\n    <ClCompile Include=\"src\\UnbufferedCharStream.cpp\" />\n    <ClCompile Include=\"src\\UnbufferedTokenStream.cpp\" />\n    <ClCompile Include=\"src\\Vocabulary.cpp\" />\n    <ClCompile Include=\"src\\WritableToken.cpp\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"src\\antlr4-common.h\" />\n    <ClInclude Include=\"src\\ANTLRErrorListener.h\" />\n    <ClInclude Include=\"src\\ANTLRErrorStrategy.h\" />\n    <ClInclude Include=\"src\\ANTLRFileStream.h\" />\n    <ClInclude Include=\"src\\ANTLRInputStream.h\" />\n    <ClInclude Include=\"src\\atn\\ActionTransition.h\" />\n    <ClInclude Include=\"src\\atn\\AmbiguityInfo.h\" />\n    <ClInclude Include=\"src\\atn\\ArrayPredictionContext.h\" />\n    <ClInclude Include=\"src\\atn\\ATN.h\" />\n    <ClInclude Include=\"src\\atn\\ATNConfig.h\" />\n    <ClInclude Include=\"src\\atn\\ATNConfigSet.h\" />\n    <ClInclude Include=\"src\\atn\\ATNDeserializationOptions.h\" />\n    <ClInclude Include=\"src\\atn\\ATNDeserializer.h\" />\n    <ClInclude Include=\"src\\atn\\ATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\ATNState.h\" />\n    <ClInclude Include=\"src\\atn\\ATNType.h\" />\n    <ClInclude Include=\"src\\atn\\AtomTransition.h\" />\n    <ClInclude Include=\"src\\atn\\BasicBlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\BasicState.h\" />\n    <ClInclude Include=\"src\\atn\\BlockEndState.h\" />\n    <ClInclude Include=\"src\\atn\\BlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\ContextSensitivityInfo.h\" />\n    <ClInclude Include=\"src\\atn\\DecisionEventInfo.h\" />\n    <ClInclude Include=\"src\\atn\\DecisionInfo.h\" />\n    <ClInclude Include=\"src\\atn\\DecisionState.h\" />\n    <ClInclude Include=\"src\\atn\\EpsilonTransition.h\" />\n    <ClInclude Include=\"src\\atn\\ErrorInfo.h\" />\n    <ClInclude Include=\"src\\atn\\LexerAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerActionExecutor.h\" />\n    <ClInclude Include=\"src\\atn\\LexerActionType.h\" />\n    <ClInclude Include=\"src\\atn\\LexerATNConfig.h\" />\n    <ClInclude Include=\"src\\atn\\LexerATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\LexerChannelAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerCustomAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerIndexedCustomAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerModeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerMoreAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerPopModeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerPushModeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerSkipAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerTypeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LL1Analyzer.h\" />\n    <ClInclude Include=\"src\\atn\\LookaheadEventInfo.h\" />\n    <ClInclude Include=\"src\\atn\\LoopEndState.h\" />\n    <ClInclude Include=\"src\\atn\\NotSetTransition.h\" />\n    <ClInclude Include=\"src\\atn\\OrderedATNConfigSet.h\" />\n    <ClInclude Include=\"src\\atn\\ParseInfo.h\" />\n    <ClInclude Include=\"src\\atn\\ParserATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\PlusBlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\PlusLoopbackState.h\" />\n    <ClInclude Include=\"src\\atn\\PrecedencePredicateTransition.h\" />\n    <ClInclude Include=\"src\\atn\\PredicateEvalInfo.h\" />\n    <ClInclude Include=\"src\\atn\\PredicateTransition.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContext.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContextCache.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCache.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCacheOptions.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionMode.h\" />\n    <ClInclude Include=\"src\\atn\\ProfilingATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\RangeTransition.h\" />\n    <ClInclude Include=\"src\\atn\\RuleStartState.h\" />\n    <ClInclude Include=\"src\\atn\\RuleStopState.h\" />\n    <ClInclude Include=\"src\\atn\\RuleTransition.h\" />\n    <ClInclude Include=\"src\\atn\\SemanticContext.h\" />\n    <ClInclude Include=\"src\\atn\\SetTransition.h\" />\n    <ClInclude Include=\"src\\atn\\SingletonPredictionContext.h\" />\n    <ClInclude Include=\"src\\atn\\StarBlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\StarLoopbackState.h\" />\n    <ClInclude Include=\"src\\atn\\StarLoopEntryState.h\" />\n    <ClInclude Include=\"src\\atn\\TokensStartState.h\" />\n    <ClInclude Include=\"src\\atn\\Transition.h\" />\n    <ClInclude Include=\"src\\atn\\WildcardTransition.h\" />\n    <ClInclude Include=\"src\\BailErrorStrategy.h\" />\n    <ClInclude Include=\"src\\BaseErrorListener.h\" />\n    <ClInclude Include=\"src\\BufferedTokenStream.h\" />\n    <ClInclude Include=\"src\\CharStream.h\" />\n    <ClInclude Include=\"src\\CommonToken.h\" />\n    <ClInclude Include=\"src\\CommonTokenFactory.h\" />\n    <ClInclude Include=\"src\\CommonTokenStream.h\" />\n    <ClInclude Include=\"src\\ConsoleErrorListener.h\" />\n    <ClInclude Include=\"src\\DefaultErrorStrategy.h\" />\n    <ClInclude Include=\"src\\dfa\\DFA.h\" />\n    <ClInclude Include=\"src\\dfa\\DFASerializer.h\" />\n    <ClInclude Include=\"src\\dfa\\DFAState.h\" />\n    <ClInclude Include=\"src\\dfa\\LexerDFASerializer.h\" />\n    <ClInclude Include=\"src\\DiagnosticErrorListener.h\" />\n    <ClInclude Include=\"src\\Exceptions.h\" />\n    <ClInclude Include=\"src\\FailedPredicateException.h\" />\n    <ClInclude Include=\"src\\InputMismatchException.h\" />\n    <ClInclude Include=\"src\\internal\\Synchronization.h\" />\n    <ClInclude Include=\"src\\InterpreterRuleContext.h\" />\n    <ClInclude Include=\"src\\IntStream.h\" />\n    <ClInclude Include=\"src\\Lexer.h\" />\n    <ClInclude Include=\"src\\LexerInterpreter.h\" />\n    <ClInclude Include=\"src\\LexerNoViableAltException.h\" />\n    <ClInclude Include=\"src\\ListTokenSource.h\" />\n    <ClInclude Include=\"src\\misc\\InterpreterDataReader.h\" />\n    <ClInclude Include=\"src\\misc\\Interval.h\" />\n    <ClInclude Include=\"src\\misc\\IntervalSet.h\" />\n    <ClInclude Include=\"src\\misc\\MurmurHash.h\" />\n    <ClInclude Include=\"src\\misc\\Predicate.h\" />\n    <ClInclude Include=\"src\\NoViableAltException.h\" />\n    <ClInclude Include=\"src\\Parser.h\" />\n    <ClInclude Include=\"src\\ParserInterpreter.h\" />\n    <ClInclude Include=\"src\\ParserRuleContext.h\" />\n    <ClInclude Include=\"src\\ProxyErrorListener.h\" />\n    <ClInclude Include=\"src\\RecognitionException.h\" />\n    <ClInclude Include=\"src\\Recognizer.h\" />\n    <ClInclude Include=\"src\\RuleContext.h\" />\n    <ClInclude Include=\"src\\RuleContextWithAltNum.h\" />\n    <ClInclude Include=\"src\\RuntimeMetaData.h\" />\n    <ClInclude Include=\"src\\support\\Any.h\" />\n    <ClInclude Include=\"src\\support\\Arrays.h\" />\n    <ClInclude Include=\"src\\support\\BitSet.h\" />\n    <ClInclude Include=\"src\\support\\Casts.h\" />\n    <ClInclude Include=\"src\\support\\CPPUtils.h\" />\n    <ClInclude Include=\"src\\support\\Declarations.h\" />\n    <ClInclude Include=\"src\\support\\StringUtils.h\" />\n    <ClInclude Include=\"src\\support\\Unicode.h\" />\n    <ClInclude Include=\"src\\support\\Utf8.h\" />\n    <ClInclude Include=\"src\\Token.h\" />\n    <ClInclude Include=\"src\\TokenFactory.h\" />\n    <ClInclude Include=\"src\\TokenSource.h\" />\n    <ClInclude Include=\"src\\TokenStream.h\" />\n    <ClInclude Include=\"src\\TokenStreamRewriter.h\" />\n    <ClInclude Include=\"src\\tree\\AbstractParseTreeVisitor.h\" />\n    <ClInclude Include=\"src\\tree\\ErrorNode.h\" />\n    <ClInclude Include=\"src\\tree\\ErrorNodeImpl.h\" />\n    <ClInclude Include=\"src\\tree\\IterativeParseTreeWalker.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTree.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeListener.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeProperty.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeVisitor.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeWalker.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\Chunk.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreeMatch.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePattern.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\RuleTagToken.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\TagChunk.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\TextChunk.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\TokenTagToken.h\" />\n    <ClInclude Include=\"src\\tree\\TerminalNode.h\" />\n    <ClInclude Include=\"src\\tree\\TerminalNodeImpl.h\" />\n    <ClInclude Include=\"src\\tree\\Trees.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPath.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexer.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexerErrorListener.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardElement.h\" />\n    <ClInclude Include=\"src\\UnbufferedCharStream.h\" />\n    <ClInclude Include=\"src\\UnbufferedTokenStream.h\" />\n    <ClInclude Include=\"src\\Vocabulary.h\" />\n    <ClInclude Include=\"src\\WritableToken.h\" />\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n</Project>\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlr4cpp-vs2019.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"Source Files\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"Resource Files\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\\atn\">\n      <UniqueIdentifier>{587a2726-4856-4d21-937a-fbaebaa90232}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\atn\">\n      <UniqueIdentifier>{2662156f-1508-4dad-b991-a8298a6db9bf}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\dfa\">\n      <UniqueIdentifier>{5b1e59b1-7fa5-46a5-8d92-965bd709cca0}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\dfa\">\n      <UniqueIdentifier>{9de9fe74-5d67-441d-a972-3cebe6dfbfcc}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\misc\">\n      <UniqueIdentifier>{89fd3896-0ab1-476d-8d64-a57f10a5e73b}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\misc\">\n      <UniqueIdentifier>{23939d7b-8e11-421e-80eb-b2cfdfdd64e9}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\support\">\n      <UniqueIdentifier>{05f2bacb-b5b2-4ca3-abe1-ca9a7239ecaa}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\support\">\n      <UniqueIdentifier>{d3b2ae2d-836b-4c73-8180-aca4ebb7d658}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\tree\">\n      <UniqueIdentifier>{6674a0f0-c65d-4a00-a9e5-1f243b89d0a2}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\tree\">\n      <UniqueIdentifier>{1893fffe-7a2b-4708-8ce5-003aa9b749f7}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\tree\\pattern\">\n      <UniqueIdentifier>{053a0632-27bc-4043-b5e8-760951b3b5b9}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\tree\\pattern\">\n      <UniqueIdentifier>{048c180d-44cf-49ca-a7aa-d0053fea07f5}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\tree\\xpath\">\n      <UniqueIdentifier>{3181cae5-cc15-4050-8c45-22af44a823de}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\tree\\xpath\">\n      <UniqueIdentifier>{290632d2-c56e-4005-a417-eb83b9531e1a}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\internal\">\n      <UniqueIdentifier>{b4b32b3f-e97a-448a-98e6-cbf901862bd4}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\internal\">\n      <UniqueIdentifier>{f8c2bdf9-7e81-4f31-ba17-06b16ba2f081}</UniqueIdentifier>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"src\\ANTLRErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ANTLRErrorStrategy.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ANTLRFileStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ANTLRInputStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\BailErrorStrategy.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\BaseErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\BufferedTokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CharStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CommonToken.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CommonTokenFactory.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CommonTokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ConsoleErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\DefaultErrorStrategy.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\DiagnosticErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Exceptions.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\FailedPredicateException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\InputMismatchException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\InterpreterRuleContext.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\IntStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Lexer.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\LexerInterpreter.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\LexerNoViableAltException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ListTokenSource.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\NoViableAltException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Parser.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ParserInterpreter.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ParserRuleContext.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ProxyErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RecognitionException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Recognizer.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RuleContext.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Token.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenFactory.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenSource.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenStreamRewriter.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\UnbufferedCharStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\UnbufferedTokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\WritableToken.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\DecisionState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\EpsilonTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerATNConfig.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LL1Analyzer.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LoopEndState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\NotSetTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\OrderedATNConfigSet.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ParserATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PlusBlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PlusLoopbackState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PrecedencePredicateTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredicateTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionMode.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RangeTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RuleStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RuleStopState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RuleTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\SemanticContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\SetTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\SingletonPredictionContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\StarBlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\StarLoopbackState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\StarLoopEntryState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\TokensStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\Transition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\WildcardTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ActionTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ArrayPredictionContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATN.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNConfig.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNConfigSet.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNDeserializationOptions.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNDeserializer.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNType.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\AtomTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BasicBlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BasicState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BlockEndState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\LexerDFASerializer.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\DFA.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\DFASerializer.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\DFAState.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\Interval.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\IntervalSet.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\MurmurHash.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Arrays.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\BitSet.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\CPPUtils.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Declarations.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\AbstractParseTreeVisitor.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ErrorNode.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ErrorNodeImpl.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTree.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeListener.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeProperty.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeVisitor.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeWalker.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\TerminalNode.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\TerminalNodeImpl.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\Trees.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\Chunk.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreeMatch.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePattern.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\RuleTagToken.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\TagChunk.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\TextChunk.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\TokenTagToken.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexer.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Vocabulary.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\AmbiguityInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ContextSensitivityInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\DecisionEventInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\DecisionInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ErrorInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerActionExecutor.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerActionType.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerChannelAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerCustomAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerIndexedCustomAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerModeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerMoreAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerPopModeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerPushModeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerSkipAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerTypeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LookaheadEventInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ParseInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredicateEvalInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ProfilingATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\Predicate.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RuleContextWithAltNum.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RuntimeMetaData.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\StringUtils.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPath.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexerErrorListener.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\antlr4-common.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\IterativeParseTreeWalker.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\InterpreterDataReader.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\internal\\Synchronization.h\">\n      <Filter>Header Files\\internal</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Casts.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Unicode.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Any.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Utf8.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCache.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCacheOptions.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContextCache.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"src\\ANTLRFileStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ANTLRInputStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\BailErrorStrategy.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\BaseErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\BufferedTokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CharStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CommonToken.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CommonTokenFactory.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CommonTokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ConsoleErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\DefaultErrorStrategy.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\DiagnosticErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Exceptions.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\FailedPredicateException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\InputMismatchException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\InterpreterRuleContext.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\IntStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Lexer.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\LexerInterpreter.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\LexerNoViableAltException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ListTokenSource.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\NoViableAltException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Parser.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ParserInterpreter.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ParserRuleContext.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ProxyErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RecognitionException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Recognizer.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RuleContext.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\TokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\TokenStreamRewriter.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\UnbufferedCharStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\UnbufferedTokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ActionTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ArrayPredictionContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATN.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNConfig.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNConfigSet.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNDeserializationOptions.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNDeserializer.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNState.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\AtomTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\DecisionState.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\EpsilonTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerATNConfig.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LL1Analyzer.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\NotSetTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\OrderedATNConfigSet.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ParserATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PrecedencePredicateTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredicateTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionMode.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\RangeTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\RuleTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\SemanticContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\SetTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\SingletonPredictionContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\StarLoopbackState.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\Transition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\WildcardTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\DFA.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\DFASerializer.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\DFAState.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\LexerDFASerializer.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\Interval.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\IntervalSet.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\MurmurHash.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\Arrays.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\CPPUtils.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ErrorNodeImpl.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTreeWalker.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\TerminalNodeImpl.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\Trees.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreeMatch.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePattern.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\RuleTagToken.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\TagChunk.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\TextChunk.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\TokenTagToken.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\AmbiguityInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ContextSensitivityInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\DecisionEventInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\DecisionInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ErrorInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerActionExecutor.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerChannelAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerCustomAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerIndexedCustomAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerModeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerMoreAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerPopModeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerPushModeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerSkipAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerTypeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LookaheadEventInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ParseInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredicateEvalInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ProfilingATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RuleContextWithAltNum.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RuntimeMetaData.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\StringUtils.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPath.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexer.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexerErrorListener.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Vocabulary.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTree.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\IterativeParseTreeWalker.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\InterpreterDataReader.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ANTLRErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ANTLRErrorStrategy.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\Predicate.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Token.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\TokenSource.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\WritableToken.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\Any.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTreeListener.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTreeVisitor.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\Chunk.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\internal\\Synchronization.cpp\">\n      <Filter>Source Files\\internal</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\Utf8.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionContextMergeCache.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionContextCache.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "runtime/Cpp/runtime/antlr4cpp-vs2022.vcxproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug Static|Win32\">\n      <Configuration>Debug Static</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug Static|x64\">\n      <Configuration>Debug Static</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug DLL|Win32\">\n      <Configuration>Debug DLL</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug DLL|x64\">\n      <Configuration>Debug DLL</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release Static|Win32\">\n      <Configuration>Release Static</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release Static|x64\">\n      <Configuration>Release Static</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release DLL|Win32\">\n      <Configuration>Release DLL</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release DLL|x64\">\n      <Configuration>Release DLL</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <ProjectGuid>{52618D4B-6EC4-49AD-8B83-52686244E8F3}</ProjectGuid>\n    <Keyword>Win32Proj</Keyword>\n    <RootNamespace>antlr4cpp</RootNamespace>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\" Label=\"Configuration\">\n    <ConfigurationType>StaticLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n    <PlatformToolset>v143</PlatformToolset>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <OutDir>$(SolutionDir)bin\\vs-2022\\$(PlatformTarget)\\$(Configuration)\\</OutDir>\n    <IntDir>$(SolutionDir)obj\\$(PlatformTarget)\\$(Configuration)\\$(ProjectName)\\</IntDir>\n    <TargetName>antlr4-runtime</TargetName>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <MinimalRebuild>false</MinimalRebuild>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_DLL;ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_DLL;ANTLR4CPP_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n    <ClCompile>\n      <WarningLevel>Level4</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <AdditionalIncludeDirectories>src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PrecompiledHeaderFile>\n      </PrecompiledHeaderFile>\n      <ForcedIncludeFiles>\n      </ForcedIncludeFiles>\n      <DisableSpecificWarnings>4251</DisableSpecificWarnings>\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\n      <AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>\n      <LanguageStandard>stdcpp17</LanguageStandard>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"src\\ANTLRErrorListener.cpp\" />\n    <ClCompile Include=\"src\\ANTLRErrorStrategy.cpp\" />\n    <ClCompile Include=\"src\\ANTLRFileStream.cpp\" />\n    <ClCompile Include=\"src\\ANTLRInputStream.cpp\" />\n    <ClCompile Include=\"src\\atn\\ActionTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\AmbiguityInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\ArrayPredictionContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATN.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNConfig.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNConfigSet.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNDeserializationOptions.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNDeserializer.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\ATNState.cpp\" />\n    <ClCompile Include=\"src\\atn\\AtomTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\ContextSensitivityInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\DecisionEventInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\DecisionInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\DecisionState.cpp\" />\n    <ClCompile Include=\"src\\atn\\EpsilonTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\ErrorInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerActionExecutor.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerATNConfig.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerChannelAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerCustomAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerIndexedCustomAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerModeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerMoreAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerPopModeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerPushModeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerSkipAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LexerTypeAction.cpp\" />\n    <ClCompile Include=\"src\\atn\\LL1Analyzer.cpp\" />\n    <ClCompile Include=\"src\\atn\\LookaheadEventInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\NotSetTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\OrderedATNConfigSet.cpp\" />\n    <ClCompile Include=\"src\\atn\\ParseInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\ParserATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\PrecedencePredicateTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredicateEvalInfo.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredicateTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionContextCache.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionContextMergeCache.cpp\" />\n    <ClCompile Include=\"src\\atn\\PredictionMode.cpp\" />\n    <ClCompile Include=\"src\\atn\\ProfilingATNSimulator.cpp\" />\n    <ClCompile Include=\"src\\atn\\RangeTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\RuleTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\SemanticContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\SetTransition.cpp\" />\n    <ClCompile Include=\"src\\atn\\SingletonPredictionContext.cpp\" />\n    <ClCompile Include=\"src\\atn\\StarLoopbackState.cpp\" />\n    <ClCompile Include=\"src\\atn\\Transition.cpp\" />\n    <ClCompile Include=\"src\\atn\\WildcardTransition.cpp\" />\n    <ClCompile Include=\"src\\BailErrorStrategy.cpp\" />\n    <ClCompile Include=\"src\\BaseErrorListener.cpp\" />\n    <ClCompile Include=\"src\\BufferedTokenStream.cpp\" />\n    <ClCompile Include=\"src\\CharStream.cpp\" />\n    <ClCompile Include=\"src\\CommonToken.cpp\" />\n    <ClCompile Include=\"src\\CommonTokenFactory.cpp\" />\n    <ClCompile Include=\"src\\CommonTokenStream.cpp\" />\n    <ClCompile Include=\"src\\ConsoleErrorListener.cpp\" />\n    <ClCompile Include=\"src\\DefaultErrorStrategy.cpp\" />\n    <ClCompile Include=\"src\\dfa\\DFA.cpp\" />\n    <ClCompile Include=\"src\\dfa\\DFASerializer.cpp\" />\n    <ClCompile Include=\"src\\dfa\\DFAState.cpp\" />\n    <ClCompile Include=\"src\\dfa\\LexerDFASerializer.cpp\" />\n    <ClCompile Include=\"src\\DiagnosticErrorListener.cpp\" />\n    <ClCompile Include=\"src\\Exceptions.cpp\" />\n    <ClCompile Include=\"src\\FailedPredicateException.cpp\" />\n    <ClCompile Include=\"src\\InputMismatchException.cpp\" />\n    <ClCompile Include=\"src\\internal\\Synchronization.cpp\" />\n    <ClCompile Include=\"src\\InterpreterRuleContext.cpp\" />\n    <ClCompile Include=\"src\\IntStream.cpp\" />\n    <ClCompile Include=\"src\\Lexer.cpp\" />\n    <ClCompile Include=\"src\\LexerInterpreter.cpp\" />\n    <ClCompile Include=\"src\\LexerNoViableAltException.cpp\" />\n    <ClCompile Include=\"src\\ListTokenSource.cpp\" />\n    <ClCompile Include=\"src\\misc\\InterpreterDataReader.cpp\" />\n    <ClCompile Include=\"src\\misc\\Interval.cpp\" />\n    <ClCompile Include=\"src\\misc\\IntervalSet.cpp\" />\n    <ClCompile Include=\"src\\misc\\MurmurHash.cpp\" />\n    <ClCompile Include=\"src\\misc\\Predicate.cpp\" />\n    <ClCompile Include=\"src\\NoViableAltException.cpp\" />\n    <ClCompile Include=\"src\\Parser.cpp\" />\n    <ClCompile Include=\"src\\ParserInterpreter.cpp\" />\n    <ClCompile Include=\"src\\ParserRuleContext.cpp\" />\n    <ClCompile Include=\"src\\ProxyErrorListener.cpp\" />\n    <ClCompile Include=\"src\\RecognitionException.cpp\" />\n    <ClCompile Include=\"src\\Recognizer.cpp\" />\n    <ClCompile Include=\"src\\RuleContext.cpp\" />\n    <ClCompile Include=\"src\\RuleContextWithAltNum.cpp\" />\n    <ClCompile Include=\"src\\RuntimeMetaData.cpp\" />\n    <ClCompile Include=\"src\\support\\Any.cpp\" />\n    <ClCompile Include=\"src\\support\\Arrays.cpp\" />\n    <ClCompile Include=\"src\\support\\CPPUtils.cpp\" />\n    <ClCompile Include=\"src\\support\\StringUtils.cpp\" />\n    <ClCompile Include=\"src\\support\\Utf8.cpp\" />\n    <ClCompile Include=\"src\\Token.cpp\" />\n    <ClCompile Include=\"src\\TokenSource.cpp\" />\n    <ClCompile Include=\"src\\TokenStream.cpp\" />\n    <ClCompile Include=\"src\\TokenStreamRewriter.cpp\" />\n    <ClCompile Include=\"src\\tree\\ErrorNodeImpl.cpp\" />\n    <ClCompile Include=\"src\\tree\\IterativeParseTreeWalker.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTree.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTreeListener.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTreeVisitor.cpp\" />\n    <ClCompile Include=\"src\\tree\\ParseTreeWalker.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\Chunk.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreeMatch.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePattern.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\RuleTagToken.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\TagChunk.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\TextChunk.cpp\" />\n    <ClCompile Include=\"src\\tree\\pattern\\TokenTagToken.cpp\" />\n    <ClCompile Include=\"src\\tree\\TerminalNodeImpl.cpp\" />\n    <ClCompile Include=\"src\\tree\\Trees.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPath.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexer.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexerErrorListener.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.cpp\" />\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardElement.cpp\" />\n    <ClCompile Include=\"src\\UnbufferedCharStream.cpp\" />\n    <ClCompile Include=\"src\\UnbufferedTokenStream.cpp\" />\n    <ClCompile Include=\"src\\Vocabulary.cpp\" />\n    <ClCompile Include=\"src\\WritableToken.cpp\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"src\\antlr4-common.h\" />\n    <ClInclude Include=\"src\\ANTLRErrorListener.h\" />\n    <ClInclude Include=\"src\\ANTLRErrorStrategy.h\" />\n    <ClInclude Include=\"src\\ANTLRFileStream.h\" />\n    <ClInclude Include=\"src\\ANTLRInputStream.h\" />\n    <ClInclude Include=\"src\\atn\\ActionTransition.h\" />\n    <ClInclude Include=\"src\\atn\\AmbiguityInfo.h\" />\n    <ClInclude Include=\"src\\atn\\ArrayPredictionContext.h\" />\n    <ClInclude Include=\"src\\atn\\ATN.h\" />\n    <ClInclude Include=\"src\\atn\\ATNConfig.h\" />\n    <ClInclude Include=\"src\\atn\\ATNConfigSet.h\" />\n    <ClInclude Include=\"src\\atn\\ATNDeserializationOptions.h\" />\n    <ClInclude Include=\"src\\atn\\ATNDeserializer.h\" />\n    <ClInclude Include=\"src\\atn\\ATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\ATNState.h\" />\n    <ClInclude Include=\"src\\atn\\ATNType.h\" />\n    <ClInclude Include=\"src\\atn\\AtomTransition.h\" />\n    <ClInclude Include=\"src\\atn\\BasicBlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\BasicState.h\" />\n    <ClInclude Include=\"src\\atn\\BlockEndState.h\" />\n    <ClInclude Include=\"src\\atn\\BlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\ContextSensitivityInfo.h\" />\n    <ClInclude Include=\"src\\atn\\DecisionEventInfo.h\" />\n    <ClInclude Include=\"src\\atn\\DecisionInfo.h\" />\n    <ClInclude Include=\"src\\atn\\DecisionState.h\" />\n    <ClInclude Include=\"src\\atn\\EpsilonTransition.h\" />\n    <ClInclude Include=\"src\\atn\\ErrorInfo.h\" />\n    <ClInclude Include=\"src\\atn\\LexerAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerActionExecutor.h\" />\n    <ClInclude Include=\"src\\atn\\LexerActionType.h\" />\n    <ClInclude Include=\"src\\atn\\LexerATNConfig.h\" />\n    <ClInclude Include=\"src\\atn\\LexerATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\LexerChannelAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerCustomAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerIndexedCustomAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerModeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerMoreAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerPopModeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerPushModeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerSkipAction.h\" />\n    <ClInclude Include=\"src\\atn\\LexerTypeAction.h\" />\n    <ClInclude Include=\"src\\atn\\LL1Analyzer.h\" />\n    <ClInclude Include=\"src\\atn\\LookaheadEventInfo.h\" />\n    <ClInclude Include=\"src\\atn\\LoopEndState.h\" />\n    <ClInclude Include=\"src\\atn\\NotSetTransition.h\" />\n    <ClInclude Include=\"src\\atn\\OrderedATNConfigSet.h\" />\n    <ClInclude Include=\"src\\atn\\ParseInfo.h\" />\n    <ClInclude Include=\"src\\atn\\ParserATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\PlusBlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\PlusLoopbackState.h\" />\n    <ClInclude Include=\"src\\atn\\PrecedencePredicateTransition.h\" />\n    <ClInclude Include=\"src\\atn\\PredicateEvalInfo.h\" />\n    <ClInclude Include=\"src\\atn\\PredicateTransition.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContext.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContextCache.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCache.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCacheOptions.h\" />\n    <ClInclude Include=\"src\\atn\\PredictionMode.h\" />\n    <ClInclude Include=\"src\\atn\\ProfilingATNSimulator.h\" />\n    <ClInclude Include=\"src\\atn\\RangeTransition.h\" />\n    <ClInclude Include=\"src\\atn\\RuleStartState.h\" />\n    <ClInclude Include=\"src\\atn\\RuleStopState.h\" />\n    <ClInclude Include=\"src\\atn\\RuleTransition.h\" />\n    <ClInclude Include=\"src\\atn\\SemanticContext.h\" />\n    <ClInclude Include=\"src\\atn\\SetTransition.h\" />\n    <ClInclude Include=\"src\\atn\\SingletonPredictionContext.h\" />\n    <ClInclude Include=\"src\\atn\\StarBlockStartState.h\" />\n    <ClInclude Include=\"src\\atn\\StarLoopbackState.h\" />\n    <ClInclude Include=\"src\\atn\\StarLoopEntryState.h\" />\n    <ClInclude Include=\"src\\atn\\TokensStartState.h\" />\n    <ClInclude Include=\"src\\atn\\Transition.h\" />\n    <ClInclude Include=\"src\\atn\\WildcardTransition.h\" />\n    <ClInclude Include=\"src\\BailErrorStrategy.h\" />\n    <ClInclude Include=\"src\\BaseErrorListener.h\" />\n    <ClInclude Include=\"src\\BufferedTokenStream.h\" />\n    <ClInclude Include=\"src\\CharStream.h\" />\n    <ClInclude Include=\"src\\CommonToken.h\" />\n    <ClInclude Include=\"src\\CommonTokenFactory.h\" />\n    <ClInclude Include=\"src\\CommonTokenStream.h\" />\n    <ClInclude Include=\"src\\ConsoleErrorListener.h\" />\n    <ClInclude Include=\"src\\DefaultErrorStrategy.h\" />\n    <ClInclude Include=\"src\\dfa\\DFA.h\" />\n    <ClInclude Include=\"src\\dfa\\DFASerializer.h\" />\n    <ClInclude Include=\"src\\dfa\\DFAState.h\" />\n    <ClInclude Include=\"src\\dfa\\LexerDFASerializer.h\" />\n    <ClInclude Include=\"src\\DiagnosticErrorListener.h\" />\n    <ClInclude Include=\"src\\Exceptions.h\" />\n    <ClInclude Include=\"src\\FailedPredicateException.h\" />\n    <ClInclude Include=\"src\\InputMismatchException.h\" />\n    <ClInclude Include=\"src\\internal\\Synchronization.h\" />\n    <ClInclude Include=\"src\\InterpreterRuleContext.h\" />\n    <ClInclude Include=\"src\\IntStream.h\" />\n    <ClInclude Include=\"src\\Lexer.h\" />\n    <ClInclude Include=\"src\\LexerInterpreter.h\" />\n    <ClInclude Include=\"src\\LexerNoViableAltException.h\" />\n    <ClInclude Include=\"src\\ListTokenSource.h\" />\n    <ClInclude Include=\"src\\misc\\InterpreterDataReader.h\" />\n    <ClInclude Include=\"src\\misc\\Interval.h\" />\n    <ClInclude Include=\"src\\misc\\IntervalSet.h\" />\n    <ClInclude Include=\"src\\misc\\MurmurHash.h\" />\n    <ClInclude Include=\"src\\misc\\Predicate.h\" />\n    <ClInclude Include=\"src\\NoViableAltException.h\" />\n    <ClInclude Include=\"src\\Parser.h\" />\n    <ClInclude Include=\"src\\ParserInterpreter.h\" />\n    <ClInclude Include=\"src\\ParserRuleContext.h\" />\n    <ClInclude Include=\"src\\ProxyErrorListener.h\" />\n    <ClInclude Include=\"src\\RecognitionException.h\" />\n    <ClInclude Include=\"src\\Recognizer.h\" />\n    <ClInclude Include=\"src\\RuleContext.h\" />\n    <ClInclude Include=\"src\\RuleContextWithAltNum.h\" />\n    <ClInclude Include=\"src\\RuntimeMetaData.h\" />\n    <ClInclude Include=\"src\\support\\Any.h\" />\n    <ClInclude Include=\"src\\support\\Arrays.h\" />\n    <ClInclude Include=\"src\\support\\BitSet.h\" />\n    <ClInclude Include=\"src\\support\\Casts.h\" />\n    <ClInclude Include=\"src\\support\\CPPUtils.h\" />\n    <ClInclude Include=\"src\\support\\Declarations.h\" />\n    <ClInclude Include=\"src\\support\\StringUtils.h\" />\n    <ClInclude Include=\"src\\support\\Unicode.h\" />\n    <ClInclude Include=\"src\\support\\Utf8.h\" />\n    <ClInclude Include=\"src\\Token.h\" />\n    <ClInclude Include=\"src\\TokenFactory.h\" />\n    <ClInclude Include=\"src\\TokenSource.h\" />\n    <ClInclude Include=\"src\\TokenStream.h\" />\n    <ClInclude Include=\"src\\TokenStreamRewriter.h\" />\n    <ClInclude Include=\"src\\tree\\AbstractParseTreeVisitor.h\" />\n    <ClInclude Include=\"src\\tree\\ErrorNode.h\" />\n    <ClInclude Include=\"src\\tree\\ErrorNodeImpl.h\" />\n    <ClInclude Include=\"src\\tree\\IterativeParseTreeWalker.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTree.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeListener.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeProperty.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeVisitor.h\" />\n    <ClInclude Include=\"src\\tree\\ParseTreeWalker.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\Chunk.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreeMatch.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePattern.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\RuleTagToken.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\TagChunk.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\TextChunk.h\" />\n    <ClInclude Include=\"src\\tree\\pattern\\TokenTagToken.h\" />\n    <ClInclude Include=\"src\\tree\\TerminalNode.h\" />\n    <ClInclude Include=\"src\\tree\\TerminalNodeImpl.h\" />\n    <ClInclude Include=\"src\\tree\\Trees.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPath.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexer.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexerErrorListener.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.h\" />\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardElement.h\" />\n    <ClInclude Include=\"src\\UnbufferedCharStream.h\" />\n    <ClInclude Include=\"src\\UnbufferedTokenStream.h\" />\n    <ClInclude Include=\"src\\Vocabulary.h\" />\n    <ClInclude Include=\"src\\WritableToken.h\" />\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n</Project>\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlr4cpp-vs2022.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"Source Files\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"Resource Files\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\\atn\">\n      <UniqueIdentifier>{587a2726-4856-4d21-937a-fbaebaa90232}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\atn\">\n      <UniqueIdentifier>{2662156f-1508-4dad-b991-a8298a6db9bf}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\dfa\">\n      <UniqueIdentifier>{5b1e59b1-7fa5-46a5-8d92-965bd709cca0}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\dfa\">\n      <UniqueIdentifier>{9de9fe74-5d67-441d-a972-3cebe6dfbfcc}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\misc\">\n      <UniqueIdentifier>{89fd3896-0ab1-476d-8d64-a57f10a5e73b}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\misc\">\n      <UniqueIdentifier>{23939d7b-8e11-421e-80eb-b2cfdfdd64e9}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\support\">\n      <UniqueIdentifier>{05f2bacb-b5b2-4ca3-abe1-ca9a7239ecaa}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\support\">\n      <UniqueIdentifier>{d3b2ae2d-836b-4c73-8180-aca4ebb7d658}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\tree\">\n      <UniqueIdentifier>{6674a0f0-c65d-4a00-a9e5-1f243b89d0a2}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\tree\">\n      <UniqueIdentifier>{1893fffe-7a2b-4708-8ce5-003aa9b749f7}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\tree\\pattern\">\n      <UniqueIdentifier>{053a0632-27bc-4043-b5e8-760951b3b5b9}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\tree\\pattern\">\n      <UniqueIdentifier>{048c180d-44cf-49ca-a7aa-d0053fea07f5}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\tree\\xpath\">\n      <UniqueIdentifier>{3181cae5-cc15-4050-8c45-22af44a823de}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\tree\\xpath\">\n      <UniqueIdentifier>{290632d2-c56e-4005-a417-eb83b9531e1a}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Source Files\\internal\">\n      <UniqueIdentifier>{b4b32b3f-e97a-448a-98e6-cbf901862bd4}</UniqueIdentifier>\n    </Filter>\n    <Filter Include=\"Header Files\\internal\">\n      <UniqueIdentifier>{f8c2bdf9-7e81-4f31-ba17-06b16ba2f081}</UniqueIdentifier>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"src\\ANTLRErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ANTLRErrorStrategy.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ANTLRFileStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ANTLRInputStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\BailErrorStrategy.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\BaseErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\BufferedTokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CharStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CommonToken.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CommonTokenFactory.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\CommonTokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ConsoleErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\DefaultErrorStrategy.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\DiagnosticErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Exceptions.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\FailedPredicateException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\InputMismatchException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\InterpreterRuleContext.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\IntStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Lexer.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\LexerInterpreter.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\LexerNoViableAltException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ListTokenSource.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\NoViableAltException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Parser.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ParserInterpreter.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ParserRuleContext.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\ProxyErrorListener.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RecognitionException.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Recognizer.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RuleContext.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Token.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenFactory.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenSource.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\TokenStreamRewriter.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\UnbufferedCharStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\UnbufferedTokenStream.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\WritableToken.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\DecisionState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\EpsilonTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerATNConfig.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LL1Analyzer.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LoopEndState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\NotSetTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\OrderedATNConfigSet.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ParserATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PlusBlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PlusLoopbackState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PrecedencePredicateTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredicateTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionMode.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RangeTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RuleStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RuleStopState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\RuleTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\SemanticContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\SetTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\SingletonPredictionContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\StarBlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\StarLoopbackState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\StarLoopEntryState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\TokensStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\Transition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\WildcardTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ActionTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ArrayPredictionContext.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATN.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNConfig.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNConfigSet.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNDeserializationOptions.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNDeserializer.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ATNType.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\AtomTransition.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BasicBlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BasicState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BlockEndState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\BlockStartState.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\LexerDFASerializer.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\DFA.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\DFASerializer.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\dfa\\DFAState.h\">\n      <Filter>Header Files\\dfa</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\Interval.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\IntervalSet.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\MurmurHash.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Arrays.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\BitSet.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\CPPUtils.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Declarations.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\AbstractParseTreeVisitor.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ErrorNode.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ErrorNodeImpl.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTree.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeListener.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeProperty.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeVisitor.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\ParseTreeWalker.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\TerminalNode.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\TerminalNodeImpl.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\Trees.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\Chunk.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreeMatch.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePattern.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\RuleTagToken.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\TagChunk.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\TextChunk.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\pattern\\TokenTagToken.h\">\n      <Filter>Header Files\\tree\\pattern</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexer.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\Vocabulary.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\AmbiguityInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ContextSensitivityInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\DecisionEventInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\DecisionInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ErrorInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerActionExecutor.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerActionType.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerChannelAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerCustomAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerIndexedCustomAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerModeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerMoreAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerPopModeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerPushModeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerSkipAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LexerTypeAction.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\LookaheadEventInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ParseInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredicateEvalInfo.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\ProfilingATNSimulator.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\Predicate.h\">\n      <Filter>Header Files\\misc</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RuleContextWithAltNum.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\RuntimeMetaData.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\StringUtils.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPath.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathLexerErrorListener.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathRuleElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathTokenElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\xpath\\XPathWildcardElement.h\">\n      <Filter>Header Files\\tree\\xpath</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\antlr4-common.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\tree\\IterativeParseTreeWalker.h\">\n      <Filter>Header Files\\tree</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\misc\\InterpreterDataReader.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\internal\\Synchronization.h\">\n      <Filter>Header Files\\internal</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Casts.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Unicode.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Any.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\support\\Utf8.h\">\n      <Filter>Header Files\\support</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCache.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContextMergeCacheOptions.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n    <ClInclude Include=\"src\\atn\\PredictionContextCache.h\">\n      <Filter>Header Files\\atn</Filter>\n    </ClInclude>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"src\\ANTLRFileStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ANTLRInputStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\BailErrorStrategy.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\BaseErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\BufferedTokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CharStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CommonToken.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CommonTokenFactory.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\CommonTokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ConsoleErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\DefaultErrorStrategy.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\DiagnosticErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Exceptions.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\FailedPredicateException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\InputMismatchException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\InterpreterRuleContext.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\IntStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Lexer.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\LexerInterpreter.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\LexerNoViableAltException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ListTokenSource.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\NoViableAltException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Parser.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ParserInterpreter.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ParserRuleContext.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ProxyErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RecognitionException.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Recognizer.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RuleContext.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\TokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\TokenStreamRewriter.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\UnbufferedCharStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\UnbufferedTokenStream.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ActionTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ArrayPredictionContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATN.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNConfig.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNConfigSet.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNDeserializationOptions.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNDeserializer.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ATNState.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\AtomTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\DecisionState.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\EpsilonTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerATNConfig.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LL1Analyzer.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\NotSetTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\OrderedATNConfigSet.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ParserATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PrecedencePredicateTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredicateTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionMode.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\RangeTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\RuleTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\SemanticContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\SetTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\SingletonPredictionContext.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\StarLoopbackState.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\Transition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\WildcardTransition.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\DFA.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\DFASerializer.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\DFAState.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\dfa\\LexerDFASerializer.cpp\">\n      <Filter>Source Files\\dfa</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\Interval.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\IntervalSet.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\MurmurHash.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\Arrays.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\CPPUtils.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ErrorNodeImpl.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTreeWalker.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\TerminalNodeImpl.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\Trees.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreeMatch.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePattern.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\ParseTreePatternMatcher.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\RuleTagToken.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\TagChunk.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\TextChunk.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\TokenTagToken.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\AmbiguityInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ContextSensitivityInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\DecisionEventInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\DecisionInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ErrorInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerActionExecutor.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerChannelAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerCustomAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerIndexedCustomAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerModeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerMoreAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerPopModeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerPushModeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerSkipAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerTypeAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LookaheadEventInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ParseInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredicateEvalInfo.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\ProfilingATNSimulator.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RuleContextWithAltNum.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\RuntimeMetaData.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\StringUtils.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPath.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexer.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathLexerErrorListener.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleAnywhereElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathRuleElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenAnywhereElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathTokenElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardAnywhereElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\xpath\\XPathWildcardElement.cpp\">\n      <Filter>Source Files\\tree\\xpath</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Vocabulary.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTree.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\IterativeParseTreeWalker.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\InterpreterDataReader.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ANTLRErrorListener.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\ANTLRErrorStrategy.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\LexerAction.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\misc\\Predicate.cpp\">\n      <Filter>Source Files\\misc</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\Token.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\TokenSource.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\WritableToken.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\Any.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTreeListener.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\ParseTreeVisitor.cpp\">\n      <Filter>Source Files\\tree</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\tree\\pattern\\Chunk.cpp\">\n      <Filter>Source Files\\tree\\pattern</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\internal\\Synchronization.cpp\">\n      <Filter>Source Files\\internal</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\support\\Utf8.cpp\">\n      <Filter>Source Files\\support</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionContextMergeCache.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n    <ClCompile Include=\"src\\atn\\PredictionContextCache.cpp\">\n      <Filter>Source Files\\atn</Filter>\n    </ClCompile>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp-ios/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>FMWK</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>NSPrincipalClass</key>\n\t<string></string>\n</dict>\n</plist>\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp-ios/antlrcpp_ios.h",
    "content": "//\n//  antlrcpp-ios.h\n//  antlrcpp-ios\n//\n//  Created by Mike Lischke on 05.05.16.\n//  Copyright © 2016 Mike Lischke. All rights reserved.\n//\n\n#import <UIKit/UIKit.h>\n\n//! Project version number for antlrcpp-ios.\nFOUNDATION_EXPORT double antlrcpp_iosVersionNumber;\n\n//! Project version string for antlrcpp-ios.\nFOUNDATION_EXPORT const unsigned char antlrcpp_iosVersionString[];\n\n#include \"antlr4-runtime.h\"\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 54;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t270C67F31CDB4F1E00116E17 /* antlrcpp_ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 270C67F21CDB4F1E00116E17 /* antlrcpp_ios.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276566E01DA93BFB000869BE /* ParseTree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276566DF1DA93BFB000869BE /* ParseTree.cpp */; };\n\t\t276566E11DA93BFB000869BE /* ParseTree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276566DF1DA93BFB000869BE /* ParseTree.cpp */; };\n\t\t276566E21DA93BFB000869BE /* ParseTree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276566DF1DA93BFB000869BE /* ParseTree.cpp */; };\n\t\t276E5D2E1CDB57AA003FF4B4 /* ANTLRErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0C1CDB57AA003FF4B4 /* ANTLRErrorListener.h */; };\n\t\t276E5D2F1CDB57AA003FF4B4 /* ANTLRErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0C1CDB57AA003FF4B4 /* ANTLRErrorListener.h */; };\n\t\t276E5D301CDB57AA003FF4B4 /* ANTLRErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0C1CDB57AA003FF4B4 /* ANTLRErrorListener.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D311CDB57AA003FF4B4 /* ANTLRErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0D1CDB57AA003FF4B4 /* ANTLRErrorStrategy.h */; };\n\t\t276E5D321CDB57AA003FF4B4 /* ANTLRErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0D1CDB57AA003FF4B4 /* ANTLRErrorStrategy.h */; };\n\t\t276E5D331CDB57AA003FF4B4 /* ANTLRErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0D1CDB57AA003FF4B4 /* ANTLRErrorStrategy.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D341CDB57AA003FF4B4 /* ANTLRFileStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C0E1CDB57AA003FF4B4 /* ANTLRFileStream.cpp */; };\n\t\t276E5D351CDB57AA003FF4B4 /* ANTLRFileStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C0E1CDB57AA003FF4B4 /* ANTLRFileStream.cpp */; };\n\t\t276E5D361CDB57AA003FF4B4 /* ANTLRFileStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C0E1CDB57AA003FF4B4 /* ANTLRFileStream.cpp */; };\n\t\t276E5D371CDB57AA003FF4B4 /* ANTLRFileStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0F1CDB57AA003FF4B4 /* ANTLRFileStream.h */; };\n\t\t276E5D381CDB57AA003FF4B4 /* ANTLRFileStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0F1CDB57AA003FF4B4 /* ANTLRFileStream.h */; };\n\t\t276E5D391CDB57AA003FF4B4 /* ANTLRFileStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C0F1CDB57AA003FF4B4 /* ANTLRFileStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D3A1CDB57AA003FF4B4 /* ANTLRInputStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C101CDB57AA003FF4B4 /* ANTLRInputStream.cpp */; };\n\t\t276E5D3B1CDB57AA003FF4B4 /* ANTLRInputStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C101CDB57AA003FF4B4 /* ANTLRInputStream.cpp */; };\n\t\t276E5D3C1CDB57AA003FF4B4 /* ANTLRInputStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C101CDB57AA003FF4B4 /* ANTLRInputStream.cpp */; };\n\t\t276E5D3D1CDB57AA003FF4B4 /* ANTLRInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C111CDB57AA003FF4B4 /* ANTLRInputStream.h */; };\n\t\t276E5D3E1CDB57AA003FF4B4 /* ANTLRInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C111CDB57AA003FF4B4 /* ANTLRInputStream.h */; };\n\t\t276E5D3F1CDB57AA003FF4B4 /* ANTLRInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C111CDB57AA003FF4B4 /* ANTLRInputStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D461CDB57AA003FF4B4 /* ActionTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C151CDB57AA003FF4B4 /* ActionTransition.cpp */; };\n\t\t276E5D471CDB57AA003FF4B4 /* ActionTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C151CDB57AA003FF4B4 /* ActionTransition.cpp */; };\n\t\t276E5D481CDB57AA003FF4B4 /* ActionTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C151CDB57AA003FF4B4 /* ActionTransition.cpp */; };\n\t\t276E5D491CDB57AA003FF4B4 /* ActionTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C161CDB57AA003FF4B4 /* ActionTransition.h */; };\n\t\t276E5D4A1CDB57AA003FF4B4 /* ActionTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C161CDB57AA003FF4B4 /* ActionTransition.h */; };\n\t\t276E5D4B1CDB57AA003FF4B4 /* ActionTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C161CDB57AA003FF4B4 /* ActionTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D4C1CDB57AA003FF4B4 /* AmbiguityInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C171CDB57AA003FF4B4 /* AmbiguityInfo.cpp */; };\n\t\t276E5D4D1CDB57AA003FF4B4 /* AmbiguityInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C171CDB57AA003FF4B4 /* AmbiguityInfo.cpp */; };\n\t\t276E5D4E1CDB57AA003FF4B4 /* AmbiguityInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C171CDB57AA003FF4B4 /* AmbiguityInfo.cpp */; };\n\t\t276E5D4F1CDB57AA003FF4B4 /* AmbiguityInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C181CDB57AA003FF4B4 /* AmbiguityInfo.h */; };\n\t\t276E5D501CDB57AA003FF4B4 /* AmbiguityInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C181CDB57AA003FF4B4 /* AmbiguityInfo.h */; };\n\t\t276E5D511CDB57AA003FF4B4 /* AmbiguityInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C181CDB57AA003FF4B4 /* AmbiguityInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D521CDB57AA003FF4B4 /* ArrayPredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C191CDB57AA003FF4B4 /* ArrayPredictionContext.cpp */; };\n\t\t276E5D531CDB57AA003FF4B4 /* ArrayPredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C191CDB57AA003FF4B4 /* ArrayPredictionContext.cpp */; };\n\t\t276E5D541CDB57AA003FF4B4 /* ArrayPredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C191CDB57AA003FF4B4 /* ArrayPredictionContext.cpp */; };\n\t\t276E5D551CDB57AA003FF4B4 /* ArrayPredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1A1CDB57AA003FF4B4 /* ArrayPredictionContext.h */; };\n\t\t276E5D561CDB57AA003FF4B4 /* ArrayPredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1A1CDB57AA003FF4B4 /* ArrayPredictionContext.h */; };\n\t\t276E5D571CDB57AA003FF4B4 /* ArrayPredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1A1CDB57AA003FF4B4 /* ArrayPredictionContext.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D581CDB57AA003FF4B4 /* ATN.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1B1CDB57AA003FF4B4 /* ATN.cpp */; };\n\t\t276E5D591CDB57AA003FF4B4 /* ATN.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1B1CDB57AA003FF4B4 /* ATN.cpp */; };\n\t\t276E5D5A1CDB57AA003FF4B4 /* ATN.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1B1CDB57AA003FF4B4 /* ATN.cpp */; };\n\t\t276E5D5B1CDB57AA003FF4B4 /* ATN.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1C1CDB57AA003FF4B4 /* ATN.h */; };\n\t\t276E5D5C1CDB57AA003FF4B4 /* ATN.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1C1CDB57AA003FF4B4 /* ATN.h */; };\n\t\t276E5D5D1CDB57AA003FF4B4 /* ATN.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1C1CDB57AA003FF4B4 /* ATN.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D5E1CDB57AA003FF4B4 /* ATNConfig.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1D1CDB57AA003FF4B4 /* ATNConfig.cpp */; };\n\t\t276E5D5F1CDB57AA003FF4B4 /* ATNConfig.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1D1CDB57AA003FF4B4 /* ATNConfig.cpp */; };\n\t\t276E5D601CDB57AA003FF4B4 /* ATNConfig.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1D1CDB57AA003FF4B4 /* ATNConfig.cpp */; };\n\t\t276E5D611CDB57AA003FF4B4 /* ATNConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1E1CDB57AA003FF4B4 /* ATNConfig.h */; };\n\t\t276E5D621CDB57AA003FF4B4 /* ATNConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1E1CDB57AA003FF4B4 /* ATNConfig.h */; };\n\t\t276E5D631CDB57AA003FF4B4 /* ATNConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C1E1CDB57AA003FF4B4 /* ATNConfig.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D641CDB57AA003FF4B4 /* ATNConfigSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1F1CDB57AA003FF4B4 /* ATNConfigSet.cpp */; };\n\t\t276E5D651CDB57AA003FF4B4 /* ATNConfigSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1F1CDB57AA003FF4B4 /* ATNConfigSet.cpp */; };\n\t\t276E5D661CDB57AA003FF4B4 /* ATNConfigSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C1F1CDB57AA003FF4B4 /* ATNConfigSet.cpp */; };\n\t\t276E5D671CDB57AA003FF4B4 /* ATNConfigSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C201CDB57AA003FF4B4 /* ATNConfigSet.h */; };\n\t\t276E5D681CDB57AA003FF4B4 /* ATNConfigSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C201CDB57AA003FF4B4 /* ATNConfigSet.h */; };\n\t\t276E5D691CDB57AA003FF4B4 /* ATNConfigSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C201CDB57AA003FF4B4 /* ATNConfigSet.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D6A1CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C211CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp */; };\n\t\t276E5D6B1CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C211CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp */; };\n\t\t276E5D6C1CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C211CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp */; };\n\t\t276E5D6D1CDB57AA003FF4B4 /* ATNDeserializationOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C221CDB57AA003FF4B4 /* ATNDeserializationOptions.h */; };\n\t\t276E5D6E1CDB57AA003FF4B4 /* ATNDeserializationOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C221CDB57AA003FF4B4 /* ATNDeserializationOptions.h */; };\n\t\t276E5D6F1CDB57AA003FF4B4 /* ATNDeserializationOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C221CDB57AA003FF4B4 /* ATNDeserializationOptions.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D701CDB57AA003FF4B4 /* ATNDeserializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C231CDB57AA003FF4B4 /* ATNDeserializer.cpp */; };\n\t\t276E5D711CDB57AA003FF4B4 /* ATNDeserializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C231CDB57AA003FF4B4 /* ATNDeserializer.cpp */; };\n\t\t276E5D721CDB57AA003FF4B4 /* ATNDeserializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C231CDB57AA003FF4B4 /* ATNDeserializer.cpp */; };\n\t\t276E5D731CDB57AA003FF4B4 /* ATNDeserializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C241CDB57AA003FF4B4 /* ATNDeserializer.h */; };\n\t\t276E5D741CDB57AA003FF4B4 /* ATNDeserializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C241CDB57AA003FF4B4 /* ATNDeserializer.h */; };\n\t\t276E5D751CDB57AA003FF4B4 /* ATNDeserializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C241CDB57AA003FF4B4 /* ATNDeserializer.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D7C1CDB57AA003FF4B4 /* ATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C271CDB57AA003FF4B4 /* ATNSimulator.cpp */; };\n\t\t276E5D7D1CDB57AA003FF4B4 /* ATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C271CDB57AA003FF4B4 /* ATNSimulator.cpp */; };\n\t\t276E5D7E1CDB57AA003FF4B4 /* ATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C271CDB57AA003FF4B4 /* ATNSimulator.cpp */; };\n\t\t276E5D7F1CDB57AA003FF4B4 /* ATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C281CDB57AA003FF4B4 /* ATNSimulator.h */; };\n\t\t276E5D801CDB57AA003FF4B4 /* ATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C281CDB57AA003FF4B4 /* ATNSimulator.h */; };\n\t\t276E5D811CDB57AA003FF4B4 /* ATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C281CDB57AA003FF4B4 /* ATNSimulator.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D821CDB57AA003FF4B4 /* ATNState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C291CDB57AA003FF4B4 /* ATNState.cpp */; };\n\t\t276E5D831CDB57AA003FF4B4 /* ATNState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C291CDB57AA003FF4B4 /* ATNState.cpp */; };\n\t\t276E5D841CDB57AA003FF4B4 /* ATNState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C291CDB57AA003FF4B4 /* ATNState.cpp */; };\n\t\t276E5D851CDB57AA003FF4B4 /* ATNState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2A1CDB57AA003FF4B4 /* ATNState.h */; };\n\t\t276E5D861CDB57AA003FF4B4 /* ATNState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2A1CDB57AA003FF4B4 /* ATNState.h */; };\n\t\t276E5D871CDB57AA003FF4B4 /* ATNState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2A1CDB57AA003FF4B4 /* ATNState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D8B1CDB57AA003FF4B4 /* ATNType.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2C1CDB57AA003FF4B4 /* ATNType.h */; };\n\t\t276E5D8C1CDB57AA003FF4B4 /* ATNType.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2C1CDB57AA003FF4B4 /* ATNType.h */; };\n\t\t276E5D8D1CDB57AA003FF4B4 /* ATNType.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2C1CDB57AA003FF4B4 /* ATNType.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D8E1CDB57AA003FF4B4 /* AtomTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C2D1CDB57AA003FF4B4 /* AtomTransition.cpp */; };\n\t\t276E5D8F1CDB57AA003FF4B4 /* AtomTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C2D1CDB57AA003FF4B4 /* AtomTransition.cpp */; };\n\t\t276E5D901CDB57AA003FF4B4 /* AtomTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C2D1CDB57AA003FF4B4 /* AtomTransition.cpp */; };\n\t\t276E5D911CDB57AA003FF4B4 /* AtomTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2E1CDB57AA003FF4B4 /* AtomTransition.h */; };\n\t\t276E5D921CDB57AA003FF4B4 /* AtomTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2E1CDB57AA003FF4B4 /* AtomTransition.h */; };\n\t\t276E5D931CDB57AA003FF4B4 /* AtomTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C2E1CDB57AA003FF4B4 /* AtomTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D971CDB57AA003FF4B4 /* BasicBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C301CDB57AA003FF4B4 /* BasicBlockStartState.h */; };\n\t\t276E5D981CDB57AA003FF4B4 /* BasicBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C301CDB57AA003FF4B4 /* BasicBlockStartState.h */; };\n\t\t276E5D991CDB57AA003FF4B4 /* BasicBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C301CDB57AA003FF4B4 /* BasicBlockStartState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5D9D1CDB57AA003FF4B4 /* BasicState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C321CDB57AA003FF4B4 /* BasicState.h */; };\n\t\t276E5D9E1CDB57AA003FF4B4 /* BasicState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C321CDB57AA003FF4B4 /* BasicState.h */; };\n\t\t276E5D9F1CDB57AA003FF4B4 /* BasicState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C321CDB57AA003FF4B4 /* BasicState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DA31CDB57AA003FF4B4 /* BlockEndState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C341CDB57AA003FF4B4 /* BlockEndState.h */; };\n\t\t276E5DA41CDB57AA003FF4B4 /* BlockEndState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C341CDB57AA003FF4B4 /* BlockEndState.h */; };\n\t\t276E5DA51CDB57AA003FF4B4 /* BlockEndState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C341CDB57AA003FF4B4 /* BlockEndState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DA61CDB57AA003FF4B4 /* BlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C351CDB57AA003FF4B4 /* BlockStartState.h */; };\n\t\t276E5DA71CDB57AA003FF4B4 /* BlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C351CDB57AA003FF4B4 /* BlockStartState.h */; };\n\t\t276E5DA81CDB57AA003FF4B4 /* BlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C351CDB57AA003FF4B4 /* BlockStartState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DAC1CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C371CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp */; };\n\t\t276E5DAD1CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C371CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp */; };\n\t\t276E5DAE1CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C371CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp */; };\n\t\t276E5DAF1CDB57AA003FF4B4 /* ContextSensitivityInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C381CDB57AA003FF4B4 /* ContextSensitivityInfo.h */; };\n\t\t276E5DB01CDB57AA003FF4B4 /* ContextSensitivityInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C381CDB57AA003FF4B4 /* ContextSensitivityInfo.h */; };\n\t\t276E5DB11CDB57AA003FF4B4 /* ContextSensitivityInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C381CDB57AA003FF4B4 /* ContextSensitivityInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DB21CDB57AA003FF4B4 /* DecisionEventInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C391CDB57AA003FF4B4 /* DecisionEventInfo.cpp */; };\n\t\t276E5DB31CDB57AA003FF4B4 /* DecisionEventInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C391CDB57AA003FF4B4 /* DecisionEventInfo.cpp */; };\n\t\t276E5DB41CDB57AA003FF4B4 /* DecisionEventInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C391CDB57AA003FF4B4 /* DecisionEventInfo.cpp */; };\n\t\t276E5DB51CDB57AA003FF4B4 /* DecisionEventInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3A1CDB57AA003FF4B4 /* DecisionEventInfo.h */; };\n\t\t276E5DB61CDB57AA003FF4B4 /* DecisionEventInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3A1CDB57AA003FF4B4 /* DecisionEventInfo.h */; };\n\t\t276E5DB71CDB57AA003FF4B4 /* DecisionEventInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3A1CDB57AA003FF4B4 /* DecisionEventInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DB81CDB57AA003FF4B4 /* DecisionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C3B1CDB57AA003FF4B4 /* DecisionInfo.cpp */; };\n\t\t276E5DB91CDB57AA003FF4B4 /* DecisionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C3B1CDB57AA003FF4B4 /* DecisionInfo.cpp */; };\n\t\t276E5DBA1CDB57AA003FF4B4 /* DecisionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C3B1CDB57AA003FF4B4 /* DecisionInfo.cpp */; };\n\t\t276E5DBB1CDB57AA003FF4B4 /* DecisionInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3C1CDB57AA003FF4B4 /* DecisionInfo.h */; };\n\t\t276E5DBC1CDB57AA003FF4B4 /* DecisionInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3C1CDB57AA003FF4B4 /* DecisionInfo.h */; };\n\t\t276E5DBD1CDB57AA003FF4B4 /* DecisionInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3C1CDB57AA003FF4B4 /* DecisionInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DBE1CDB57AA003FF4B4 /* DecisionState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C3D1CDB57AA003FF4B4 /* DecisionState.cpp */; };\n\t\t276E5DBF1CDB57AA003FF4B4 /* DecisionState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C3D1CDB57AA003FF4B4 /* DecisionState.cpp */; };\n\t\t276E5DC01CDB57AA003FF4B4 /* DecisionState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C3D1CDB57AA003FF4B4 /* DecisionState.cpp */; };\n\t\t276E5DC11CDB57AA003FF4B4 /* DecisionState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3E1CDB57AA003FF4B4 /* DecisionState.h */; };\n\t\t276E5DC21CDB57AA003FF4B4 /* DecisionState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3E1CDB57AA003FF4B4 /* DecisionState.h */; };\n\t\t276E5DC31CDB57AA003FF4B4 /* DecisionState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C3E1CDB57AA003FF4B4 /* DecisionState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DCA1CDB57AA003FF4B4 /* EpsilonTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C411CDB57AA003FF4B4 /* EpsilonTransition.cpp */; };\n\t\t276E5DCB1CDB57AA003FF4B4 /* EpsilonTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C411CDB57AA003FF4B4 /* EpsilonTransition.cpp */; };\n\t\t276E5DCC1CDB57AA003FF4B4 /* EpsilonTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C411CDB57AA003FF4B4 /* EpsilonTransition.cpp */; };\n\t\t276E5DCD1CDB57AA003FF4B4 /* EpsilonTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C421CDB57AA003FF4B4 /* EpsilonTransition.h */; };\n\t\t276E5DCE1CDB57AA003FF4B4 /* EpsilonTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C421CDB57AA003FF4B4 /* EpsilonTransition.h */; };\n\t\t276E5DCF1CDB57AA003FF4B4 /* EpsilonTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C421CDB57AA003FF4B4 /* EpsilonTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DD01CDB57AA003FF4B4 /* ErrorInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C431CDB57AA003FF4B4 /* ErrorInfo.cpp */; };\n\t\t276E5DD11CDB57AA003FF4B4 /* ErrorInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C431CDB57AA003FF4B4 /* ErrorInfo.cpp */; };\n\t\t276E5DD21CDB57AA003FF4B4 /* ErrorInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C431CDB57AA003FF4B4 /* ErrorInfo.cpp */; };\n\t\t276E5DD31CDB57AA003FF4B4 /* ErrorInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C441CDB57AA003FF4B4 /* ErrorInfo.h */; };\n\t\t276E5DD41CDB57AA003FF4B4 /* ErrorInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C441CDB57AA003FF4B4 /* ErrorInfo.h */; };\n\t\t276E5DD51CDB57AA003FF4B4 /* ErrorInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C441CDB57AA003FF4B4 /* ErrorInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DD61CDB57AA003FF4B4 /* LexerAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C451CDB57AA003FF4B4 /* LexerAction.h */; };\n\t\t276E5DD71CDB57AA003FF4B4 /* LexerAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C451CDB57AA003FF4B4 /* LexerAction.h */; };\n\t\t276E5DD81CDB57AA003FF4B4 /* LexerAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C451CDB57AA003FF4B4 /* LexerAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DD91CDB57AA003FF4B4 /* LexerActionExecutor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C461CDB57AA003FF4B4 /* LexerActionExecutor.cpp */; };\n\t\t276E5DDA1CDB57AA003FF4B4 /* LexerActionExecutor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C461CDB57AA003FF4B4 /* LexerActionExecutor.cpp */; };\n\t\t276E5DDB1CDB57AA003FF4B4 /* LexerActionExecutor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C461CDB57AA003FF4B4 /* LexerActionExecutor.cpp */; };\n\t\t276E5DDC1CDB57AA003FF4B4 /* LexerActionExecutor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C471CDB57AA003FF4B4 /* LexerActionExecutor.h */; };\n\t\t276E5DDD1CDB57AA003FF4B4 /* LexerActionExecutor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C471CDB57AA003FF4B4 /* LexerActionExecutor.h */; };\n\t\t276E5DDE1CDB57AA003FF4B4 /* LexerActionExecutor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C471CDB57AA003FF4B4 /* LexerActionExecutor.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DE21CDB57AA003FF4B4 /* LexerActionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C491CDB57AA003FF4B4 /* LexerActionType.h */; };\n\t\t276E5DE31CDB57AA003FF4B4 /* LexerActionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C491CDB57AA003FF4B4 /* LexerActionType.h */; };\n\t\t276E5DE41CDB57AA003FF4B4 /* LexerActionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C491CDB57AA003FF4B4 /* LexerActionType.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DE51CDB57AA003FF4B4 /* LexerATNConfig.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4A1CDB57AA003FF4B4 /* LexerATNConfig.cpp */; };\n\t\t276E5DE61CDB57AA003FF4B4 /* LexerATNConfig.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4A1CDB57AA003FF4B4 /* LexerATNConfig.cpp */; };\n\t\t276E5DE71CDB57AA003FF4B4 /* LexerATNConfig.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4A1CDB57AA003FF4B4 /* LexerATNConfig.cpp */; };\n\t\t276E5DE81CDB57AA003FF4B4 /* LexerATNConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4B1CDB57AA003FF4B4 /* LexerATNConfig.h */; };\n\t\t276E5DE91CDB57AA003FF4B4 /* LexerATNConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4B1CDB57AA003FF4B4 /* LexerATNConfig.h */; };\n\t\t276E5DEA1CDB57AA003FF4B4 /* LexerATNConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4B1CDB57AA003FF4B4 /* LexerATNConfig.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DEB1CDB57AA003FF4B4 /* LexerATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4C1CDB57AA003FF4B4 /* LexerATNSimulator.cpp */; };\n\t\t276E5DEC1CDB57AA003FF4B4 /* LexerATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4C1CDB57AA003FF4B4 /* LexerATNSimulator.cpp */; };\n\t\t276E5DED1CDB57AA003FF4B4 /* LexerATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4C1CDB57AA003FF4B4 /* LexerATNSimulator.cpp */; };\n\t\t276E5DEE1CDB57AA003FF4B4 /* LexerATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4D1CDB57AA003FF4B4 /* LexerATNSimulator.h */; };\n\t\t276E5DEF1CDB57AA003FF4B4 /* LexerATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4D1CDB57AA003FF4B4 /* LexerATNSimulator.h */; };\n\t\t276E5DF01CDB57AA003FF4B4 /* LexerATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4D1CDB57AA003FF4B4 /* LexerATNSimulator.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DF11CDB57AA003FF4B4 /* LexerChannelAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4E1CDB57AA003FF4B4 /* LexerChannelAction.cpp */; };\n\t\t276E5DF21CDB57AA003FF4B4 /* LexerChannelAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4E1CDB57AA003FF4B4 /* LexerChannelAction.cpp */; };\n\t\t276E5DF31CDB57AA003FF4B4 /* LexerChannelAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C4E1CDB57AA003FF4B4 /* LexerChannelAction.cpp */; };\n\t\t276E5DF41CDB57AA003FF4B4 /* LexerChannelAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4F1CDB57AA003FF4B4 /* LexerChannelAction.h */; };\n\t\t276E5DF51CDB57AA003FF4B4 /* LexerChannelAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4F1CDB57AA003FF4B4 /* LexerChannelAction.h */; };\n\t\t276E5DF61CDB57AA003FF4B4 /* LexerChannelAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C4F1CDB57AA003FF4B4 /* LexerChannelAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DF71CDB57AA003FF4B4 /* LexerCustomAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C501CDB57AA003FF4B4 /* LexerCustomAction.cpp */; };\n\t\t276E5DF81CDB57AA003FF4B4 /* LexerCustomAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C501CDB57AA003FF4B4 /* LexerCustomAction.cpp */; };\n\t\t276E5DF91CDB57AA003FF4B4 /* LexerCustomAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C501CDB57AA003FF4B4 /* LexerCustomAction.cpp */; };\n\t\t276E5DFA1CDB57AA003FF4B4 /* LexerCustomAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C511CDB57AA003FF4B4 /* LexerCustomAction.h */; };\n\t\t276E5DFB1CDB57AA003FF4B4 /* LexerCustomAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C511CDB57AA003FF4B4 /* LexerCustomAction.h */; };\n\t\t276E5DFC1CDB57AA003FF4B4 /* LexerCustomAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C511CDB57AA003FF4B4 /* LexerCustomAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5DFD1CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C521CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp */; };\n\t\t276E5DFE1CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C521CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp */; };\n\t\t276E5DFF1CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C521CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp */; };\n\t\t276E5E001CDB57AA003FF4B4 /* LexerIndexedCustomAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C531CDB57AA003FF4B4 /* LexerIndexedCustomAction.h */; };\n\t\t276E5E011CDB57AA003FF4B4 /* LexerIndexedCustomAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C531CDB57AA003FF4B4 /* LexerIndexedCustomAction.h */; };\n\t\t276E5E021CDB57AA003FF4B4 /* LexerIndexedCustomAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C531CDB57AA003FF4B4 /* LexerIndexedCustomAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E031CDB57AA003FF4B4 /* LexerModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C541CDB57AA003FF4B4 /* LexerModeAction.cpp */; };\n\t\t276E5E041CDB57AA003FF4B4 /* LexerModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C541CDB57AA003FF4B4 /* LexerModeAction.cpp */; };\n\t\t276E5E051CDB57AA003FF4B4 /* LexerModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C541CDB57AA003FF4B4 /* LexerModeAction.cpp */; };\n\t\t276E5E061CDB57AA003FF4B4 /* LexerModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C551CDB57AA003FF4B4 /* LexerModeAction.h */; };\n\t\t276E5E071CDB57AA003FF4B4 /* LexerModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C551CDB57AA003FF4B4 /* LexerModeAction.h */; };\n\t\t276E5E081CDB57AA003FF4B4 /* LexerModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C551CDB57AA003FF4B4 /* LexerModeAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E091CDB57AA003FF4B4 /* LexerMoreAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C561CDB57AA003FF4B4 /* LexerMoreAction.cpp */; };\n\t\t276E5E0A1CDB57AA003FF4B4 /* LexerMoreAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C561CDB57AA003FF4B4 /* LexerMoreAction.cpp */; };\n\t\t276E5E0B1CDB57AA003FF4B4 /* LexerMoreAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C561CDB57AA003FF4B4 /* LexerMoreAction.cpp */; };\n\t\t276E5E0C1CDB57AA003FF4B4 /* LexerMoreAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C571CDB57AA003FF4B4 /* LexerMoreAction.h */; };\n\t\t276E5E0D1CDB57AA003FF4B4 /* LexerMoreAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C571CDB57AA003FF4B4 /* LexerMoreAction.h */; };\n\t\t276E5E0E1CDB57AA003FF4B4 /* LexerMoreAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C571CDB57AA003FF4B4 /* LexerMoreAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E0F1CDB57AA003FF4B4 /* LexerPopModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C581CDB57AA003FF4B4 /* LexerPopModeAction.cpp */; };\n\t\t276E5E101CDB57AA003FF4B4 /* LexerPopModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C581CDB57AA003FF4B4 /* LexerPopModeAction.cpp */; };\n\t\t276E5E111CDB57AA003FF4B4 /* LexerPopModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C581CDB57AA003FF4B4 /* LexerPopModeAction.cpp */; };\n\t\t276E5E121CDB57AA003FF4B4 /* LexerPopModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C591CDB57AA003FF4B4 /* LexerPopModeAction.h */; };\n\t\t276E5E131CDB57AA003FF4B4 /* LexerPopModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C591CDB57AA003FF4B4 /* LexerPopModeAction.h */; };\n\t\t276E5E141CDB57AA003FF4B4 /* LexerPopModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C591CDB57AA003FF4B4 /* LexerPopModeAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E151CDB57AA003FF4B4 /* LexerPushModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5A1CDB57AA003FF4B4 /* LexerPushModeAction.cpp */; };\n\t\t276E5E161CDB57AA003FF4B4 /* LexerPushModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5A1CDB57AA003FF4B4 /* LexerPushModeAction.cpp */; };\n\t\t276E5E171CDB57AA003FF4B4 /* LexerPushModeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5A1CDB57AA003FF4B4 /* LexerPushModeAction.cpp */; };\n\t\t276E5E181CDB57AA003FF4B4 /* LexerPushModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5B1CDB57AA003FF4B4 /* LexerPushModeAction.h */; };\n\t\t276E5E191CDB57AA003FF4B4 /* LexerPushModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5B1CDB57AA003FF4B4 /* LexerPushModeAction.h */; };\n\t\t276E5E1A1CDB57AA003FF4B4 /* LexerPushModeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5B1CDB57AA003FF4B4 /* LexerPushModeAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E1B1CDB57AA003FF4B4 /* LexerSkipAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5C1CDB57AA003FF4B4 /* LexerSkipAction.cpp */; };\n\t\t276E5E1C1CDB57AA003FF4B4 /* LexerSkipAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5C1CDB57AA003FF4B4 /* LexerSkipAction.cpp */; };\n\t\t276E5E1D1CDB57AA003FF4B4 /* LexerSkipAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5C1CDB57AA003FF4B4 /* LexerSkipAction.cpp */; };\n\t\t276E5E1E1CDB57AA003FF4B4 /* LexerSkipAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5D1CDB57AA003FF4B4 /* LexerSkipAction.h */; };\n\t\t276E5E1F1CDB57AA003FF4B4 /* LexerSkipAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5D1CDB57AA003FF4B4 /* LexerSkipAction.h */; };\n\t\t276E5E201CDB57AA003FF4B4 /* LexerSkipAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5D1CDB57AA003FF4B4 /* LexerSkipAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E211CDB57AA003FF4B4 /* LexerTypeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5E1CDB57AA003FF4B4 /* LexerTypeAction.cpp */; };\n\t\t276E5E221CDB57AA003FF4B4 /* LexerTypeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5E1CDB57AA003FF4B4 /* LexerTypeAction.cpp */; };\n\t\t276E5E231CDB57AA003FF4B4 /* LexerTypeAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C5E1CDB57AA003FF4B4 /* LexerTypeAction.cpp */; };\n\t\t276E5E241CDB57AA003FF4B4 /* LexerTypeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5F1CDB57AA003FF4B4 /* LexerTypeAction.h */; };\n\t\t276E5E251CDB57AA003FF4B4 /* LexerTypeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5F1CDB57AA003FF4B4 /* LexerTypeAction.h */; };\n\t\t276E5E261CDB57AA003FF4B4 /* LexerTypeAction.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C5F1CDB57AA003FF4B4 /* LexerTypeAction.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E271CDB57AA003FF4B4 /* LL1Analyzer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C601CDB57AA003FF4B4 /* LL1Analyzer.cpp */; };\n\t\t276E5E281CDB57AA003FF4B4 /* LL1Analyzer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C601CDB57AA003FF4B4 /* LL1Analyzer.cpp */; };\n\t\t276E5E291CDB57AA003FF4B4 /* LL1Analyzer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C601CDB57AA003FF4B4 /* LL1Analyzer.cpp */; };\n\t\t276E5E2A1CDB57AA003FF4B4 /* LL1Analyzer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C611CDB57AA003FF4B4 /* LL1Analyzer.h */; };\n\t\t276E5E2B1CDB57AA003FF4B4 /* LL1Analyzer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C611CDB57AA003FF4B4 /* LL1Analyzer.h */; };\n\t\t276E5E2C1CDB57AA003FF4B4 /* LL1Analyzer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C611CDB57AA003FF4B4 /* LL1Analyzer.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E2D1CDB57AA003FF4B4 /* LookaheadEventInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C621CDB57AA003FF4B4 /* LookaheadEventInfo.cpp */; };\n\t\t276E5E2E1CDB57AA003FF4B4 /* LookaheadEventInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C621CDB57AA003FF4B4 /* LookaheadEventInfo.cpp */; };\n\t\t276E5E2F1CDB57AA003FF4B4 /* LookaheadEventInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C621CDB57AA003FF4B4 /* LookaheadEventInfo.cpp */; };\n\t\t276E5E301CDB57AA003FF4B4 /* LookaheadEventInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C631CDB57AA003FF4B4 /* LookaheadEventInfo.h */; };\n\t\t276E5E311CDB57AA003FF4B4 /* LookaheadEventInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C631CDB57AA003FF4B4 /* LookaheadEventInfo.h */; };\n\t\t276E5E321CDB57AA003FF4B4 /* LookaheadEventInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C631CDB57AA003FF4B4 /* LookaheadEventInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E361CDB57AA003FF4B4 /* LoopEndState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C651CDB57AA003FF4B4 /* LoopEndState.h */; };\n\t\t276E5E371CDB57AA003FF4B4 /* LoopEndState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C651CDB57AA003FF4B4 /* LoopEndState.h */; };\n\t\t276E5E381CDB57AA003FF4B4 /* LoopEndState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C651CDB57AA003FF4B4 /* LoopEndState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E3C1CDB57AA003FF4B4 /* NotSetTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C671CDB57AA003FF4B4 /* NotSetTransition.cpp */; };\n\t\t276E5E3D1CDB57AA003FF4B4 /* NotSetTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C671CDB57AA003FF4B4 /* NotSetTransition.cpp */; };\n\t\t276E5E3E1CDB57AA003FF4B4 /* NotSetTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C671CDB57AA003FF4B4 /* NotSetTransition.cpp */; };\n\t\t276E5E3F1CDB57AA003FF4B4 /* NotSetTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C681CDB57AA003FF4B4 /* NotSetTransition.h */; };\n\t\t276E5E401CDB57AA003FF4B4 /* NotSetTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C681CDB57AA003FF4B4 /* NotSetTransition.h */; };\n\t\t276E5E411CDB57AA003FF4B4 /* NotSetTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C681CDB57AA003FF4B4 /* NotSetTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E421CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C691CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp */; };\n\t\t276E5E431CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C691CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp */; };\n\t\t276E5E441CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C691CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp */; };\n\t\t276E5E451CDB57AA003FF4B4 /* OrderedATNConfigSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6A1CDB57AA003FF4B4 /* OrderedATNConfigSet.h */; };\n\t\t276E5E461CDB57AA003FF4B4 /* OrderedATNConfigSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6A1CDB57AA003FF4B4 /* OrderedATNConfigSet.h */; };\n\t\t276E5E471CDB57AA003FF4B4 /* OrderedATNConfigSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6A1CDB57AA003FF4B4 /* OrderedATNConfigSet.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E481CDB57AA003FF4B4 /* ParseInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C6B1CDB57AA003FF4B4 /* ParseInfo.cpp */; };\n\t\t276E5E491CDB57AA003FF4B4 /* ParseInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C6B1CDB57AA003FF4B4 /* ParseInfo.cpp */; };\n\t\t276E5E4A1CDB57AA003FF4B4 /* ParseInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C6B1CDB57AA003FF4B4 /* ParseInfo.cpp */; };\n\t\t276E5E4B1CDB57AA003FF4B4 /* ParseInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6C1CDB57AA003FF4B4 /* ParseInfo.h */; };\n\t\t276E5E4C1CDB57AA003FF4B4 /* ParseInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6C1CDB57AA003FF4B4 /* ParseInfo.h */; };\n\t\t276E5E4D1CDB57AA003FF4B4 /* ParseInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6C1CDB57AA003FF4B4 /* ParseInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E4E1CDB57AA003FF4B4 /* ParserATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C6D1CDB57AA003FF4B4 /* ParserATNSimulator.cpp */; };\n\t\t276E5E4F1CDB57AA003FF4B4 /* ParserATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C6D1CDB57AA003FF4B4 /* ParserATNSimulator.cpp */; };\n\t\t276E5E501CDB57AA003FF4B4 /* ParserATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C6D1CDB57AA003FF4B4 /* ParserATNSimulator.cpp */; };\n\t\t276E5E511CDB57AA003FF4B4 /* ParserATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6E1CDB57AA003FF4B4 /* ParserATNSimulator.h */; };\n\t\t276E5E521CDB57AA003FF4B4 /* ParserATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6E1CDB57AA003FF4B4 /* ParserATNSimulator.h */; };\n\t\t276E5E531CDB57AA003FF4B4 /* ParserATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C6E1CDB57AA003FF4B4 /* ParserATNSimulator.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E571CDB57AA003FF4B4 /* PlusBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C701CDB57AA003FF4B4 /* PlusBlockStartState.h */; };\n\t\t276E5E581CDB57AA003FF4B4 /* PlusBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C701CDB57AA003FF4B4 /* PlusBlockStartState.h */; };\n\t\t276E5E591CDB57AA003FF4B4 /* PlusBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C701CDB57AA003FF4B4 /* PlusBlockStartState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E5D1CDB57AA003FF4B4 /* PlusLoopbackState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C721CDB57AA003FF4B4 /* PlusLoopbackState.h */; };\n\t\t276E5E5E1CDB57AA003FF4B4 /* PlusLoopbackState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C721CDB57AA003FF4B4 /* PlusLoopbackState.h */; };\n\t\t276E5E5F1CDB57AA003FF4B4 /* PlusLoopbackState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C721CDB57AA003FF4B4 /* PlusLoopbackState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E601CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C731CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp */; };\n\t\t276E5E611CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C731CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp */; };\n\t\t276E5E621CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C731CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp */; };\n\t\t276E5E631CDB57AA003FF4B4 /* PrecedencePredicateTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C741CDB57AA003FF4B4 /* PrecedencePredicateTransition.h */; };\n\t\t276E5E641CDB57AA003FF4B4 /* PrecedencePredicateTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C741CDB57AA003FF4B4 /* PrecedencePredicateTransition.h */; };\n\t\t276E5E651CDB57AA003FF4B4 /* PrecedencePredicateTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C741CDB57AA003FF4B4 /* PrecedencePredicateTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E661CDB57AA003FF4B4 /* PredicateEvalInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C751CDB57AA003FF4B4 /* PredicateEvalInfo.cpp */; };\n\t\t276E5E671CDB57AA003FF4B4 /* PredicateEvalInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C751CDB57AA003FF4B4 /* PredicateEvalInfo.cpp */; };\n\t\t276E5E681CDB57AA003FF4B4 /* PredicateEvalInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C751CDB57AA003FF4B4 /* PredicateEvalInfo.cpp */; };\n\t\t276E5E691CDB57AA003FF4B4 /* PredicateEvalInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C761CDB57AA003FF4B4 /* PredicateEvalInfo.h */; };\n\t\t276E5E6A1CDB57AA003FF4B4 /* PredicateEvalInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C761CDB57AA003FF4B4 /* PredicateEvalInfo.h */; };\n\t\t276E5E6B1CDB57AA003FF4B4 /* PredicateEvalInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C761CDB57AA003FF4B4 /* PredicateEvalInfo.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E6C1CDB57AA003FF4B4 /* PredicateTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C771CDB57AA003FF4B4 /* PredicateTransition.cpp */; };\n\t\t276E5E6D1CDB57AA003FF4B4 /* PredicateTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C771CDB57AA003FF4B4 /* PredicateTransition.cpp */; };\n\t\t276E5E6E1CDB57AA003FF4B4 /* PredicateTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C771CDB57AA003FF4B4 /* PredicateTransition.cpp */; };\n\t\t276E5E6F1CDB57AA003FF4B4 /* PredicateTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C781CDB57AA003FF4B4 /* PredicateTransition.h */; };\n\t\t276E5E701CDB57AA003FF4B4 /* PredicateTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C781CDB57AA003FF4B4 /* PredicateTransition.h */; };\n\t\t276E5E711CDB57AA003FF4B4 /* PredicateTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C781CDB57AA003FF4B4 /* PredicateTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E721CDB57AA003FF4B4 /* PredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C791CDB57AA003FF4B4 /* PredictionContext.cpp */; };\n\t\t276E5E731CDB57AA003FF4B4 /* PredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C791CDB57AA003FF4B4 /* PredictionContext.cpp */; };\n\t\t276E5E741CDB57AA003FF4B4 /* PredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C791CDB57AA003FF4B4 /* PredictionContext.cpp */; };\n\t\t276E5E751CDB57AA003FF4B4 /* PredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7A1CDB57AA003FF4B4 /* PredictionContext.h */; };\n\t\t276E5E761CDB57AA003FF4B4 /* PredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7A1CDB57AA003FF4B4 /* PredictionContext.h */; };\n\t\t276E5E771CDB57AA003FF4B4 /* PredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7A1CDB57AA003FF4B4 /* PredictionContext.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E781CDB57AA003FF4B4 /* PredictionMode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7B1CDB57AA003FF4B4 /* PredictionMode.cpp */; };\n\t\t276E5E791CDB57AA003FF4B4 /* PredictionMode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7B1CDB57AA003FF4B4 /* PredictionMode.cpp */; };\n\t\t276E5E7A1CDB57AA003FF4B4 /* PredictionMode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7B1CDB57AA003FF4B4 /* PredictionMode.cpp */; };\n\t\t276E5E7B1CDB57AA003FF4B4 /* PredictionMode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7C1CDB57AA003FF4B4 /* PredictionMode.h */; };\n\t\t276E5E7C1CDB57AA003FF4B4 /* PredictionMode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7C1CDB57AA003FF4B4 /* PredictionMode.h */; };\n\t\t276E5E7D1CDB57AA003FF4B4 /* PredictionMode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7C1CDB57AA003FF4B4 /* PredictionMode.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E7E1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7D1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp */; };\n\t\t276E5E7F1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7D1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp */; };\n\t\t276E5E801CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7D1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp */; };\n\t\t276E5E811CDB57AA003FF4B4 /* ProfilingATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7E1CDB57AA003FF4B4 /* ProfilingATNSimulator.h */; };\n\t\t276E5E821CDB57AA003FF4B4 /* ProfilingATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7E1CDB57AA003FF4B4 /* ProfilingATNSimulator.h */; };\n\t\t276E5E831CDB57AA003FF4B4 /* ProfilingATNSimulator.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C7E1CDB57AA003FF4B4 /* ProfilingATNSimulator.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E841CDB57AA003FF4B4 /* RangeTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7F1CDB57AA003FF4B4 /* RangeTransition.cpp */; };\n\t\t276E5E851CDB57AA003FF4B4 /* RangeTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7F1CDB57AA003FF4B4 /* RangeTransition.cpp */; };\n\t\t276E5E861CDB57AA003FF4B4 /* RangeTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C7F1CDB57AA003FF4B4 /* RangeTransition.cpp */; };\n\t\t276E5E871CDB57AA003FF4B4 /* RangeTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C801CDB57AA003FF4B4 /* RangeTransition.h */; };\n\t\t276E5E881CDB57AA003FF4B4 /* RangeTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C801CDB57AA003FF4B4 /* RangeTransition.h */; };\n\t\t276E5E891CDB57AA003FF4B4 /* RangeTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C801CDB57AA003FF4B4 /* RangeTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E8D1CDB57AA003FF4B4 /* RuleStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C821CDB57AA003FF4B4 /* RuleStartState.h */; };\n\t\t276E5E8E1CDB57AA003FF4B4 /* RuleStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C821CDB57AA003FF4B4 /* RuleStartState.h */; };\n\t\t276E5E8F1CDB57AA003FF4B4 /* RuleStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C821CDB57AA003FF4B4 /* RuleStartState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E931CDB57AA003FF4B4 /* RuleStopState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C841CDB57AA003FF4B4 /* RuleStopState.h */; };\n\t\t276E5E941CDB57AA003FF4B4 /* RuleStopState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C841CDB57AA003FF4B4 /* RuleStopState.h */; };\n\t\t276E5E951CDB57AA003FF4B4 /* RuleStopState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C841CDB57AA003FF4B4 /* RuleStopState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E961CDB57AA003FF4B4 /* RuleTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C851CDB57AA003FF4B4 /* RuleTransition.cpp */; };\n\t\t276E5E971CDB57AA003FF4B4 /* RuleTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C851CDB57AA003FF4B4 /* RuleTransition.cpp */; };\n\t\t276E5E981CDB57AA003FF4B4 /* RuleTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C851CDB57AA003FF4B4 /* RuleTransition.cpp */; };\n\t\t276E5E991CDB57AA003FF4B4 /* RuleTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C861CDB57AA003FF4B4 /* RuleTransition.h */; };\n\t\t276E5E9A1CDB57AA003FF4B4 /* RuleTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C861CDB57AA003FF4B4 /* RuleTransition.h */; };\n\t\t276E5E9B1CDB57AA003FF4B4 /* RuleTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C861CDB57AA003FF4B4 /* RuleTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5E9C1CDB57AA003FF4B4 /* SemanticContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C871CDB57AA003FF4B4 /* SemanticContext.cpp */; };\n\t\t276E5E9D1CDB57AA003FF4B4 /* SemanticContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C871CDB57AA003FF4B4 /* SemanticContext.cpp */; };\n\t\t276E5E9E1CDB57AA003FF4B4 /* SemanticContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C871CDB57AA003FF4B4 /* SemanticContext.cpp */; };\n\t\t276E5E9F1CDB57AA003FF4B4 /* SemanticContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C881CDB57AA003FF4B4 /* SemanticContext.h */; };\n\t\t276E5EA01CDB57AA003FF4B4 /* SemanticContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C881CDB57AA003FF4B4 /* SemanticContext.h */; };\n\t\t276E5EA11CDB57AA003FF4B4 /* SemanticContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C881CDB57AA003FF4B4 /* SemanticContext.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EA21CDB57AA003FF4B4 /* SetTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C891CDB57AA003FF4B4 /* SetTransition.cpp */; };\n\t\t276E5EA31CDB57AA003FF4B4 /* SetTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C891CDB57AA003FF4B4 /* SetTransition.cpp */; };\n\t\t276E5EA41CDB57AA003FF4B4 /* SetTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C891CDB57AA003FF4B4 /* SetTransition.cpp */; };\n\t\t276E5EA51CDB57AA003FF4B4 /* SetTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8A1CDB57AA003FF4B4 /* SetTransition.h */; };\n\t\t276E5EA61CDB57AA003FF4B4 /* SetTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8A1CDB57AA003FF4B4 /* SetTransition.h */; };\n\t\t276E5EA71CDB57AA003FF4B4 /* SetTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8A1CDB57AA003FF4B4 /* SetTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EA81CDB57AA003FF4B4 /* SingletonPredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C8B1CDB57AA003FF4B4 /* SingletonPredictionContext.cpp */; };\n\t\t276E5EA91CDB57AA003FF4B4 /* SingletonPredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C8B1CDB57AA003FF4B4 /* SingletonPredictionContext.cpp */; };\n\t\t276E5EAA1CDB57AA003FF4B4 /* SingletonPredictionContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C8B1CDB57AA003FF4B4 /* SingletonPredictionContext.cpp */; };\n\t\t276E5EAB1CDB57AA003FF4B4 /* SingletonPredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8C1CDB57AA003FF4B4 /* SingletonPredictionContext.h */; };\n\t\t276E5EAC1CDB57AA003FF4B4 /* SingletonPredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8C1CDB57AA003FF4B4 /* SingletonPredictionContext.h */; };\n\t\t276E5EAD1CDB57AA003FF4B4 /* SingletonPredictionContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8C1CDB57AA003FF4B4 /* SingletonPredictionContext.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EB11CDB57AA003FF4B4 /* StarBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8E1CDB57AA003FF4B4 /* StarBlockStartState.h */; };\n\t\t276E5EB21CDB57AA003FF4B4 /* StarBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8E1CDB57AA003FF4B4 /* StarBlockStartState.h */; };\n\t\t276E5EB31CDB57AA003FF4B4 /* StarBlockStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C8E1CDB57AA003FF4B4 /* StarBlockStartState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EB41CDB57AA003FF4B4 /* StarLoopbackState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C8F1CDB57AA003FF4B4 /* StarLoopbackState.cpp */; };\n\t\t276E5EB51CDB57AA003FF4B4 /* StarLoopbackState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C8F1CDB57AA003FF4B4 /* StarLoopbackState.cpp */; };\n\t\t276E5EB61CDB57AA003FF4B4 /* StarLoopbackState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C8F1CDB57AA003FF4B4 /* StarLoopbackState.cpp */; };\n\t\t276E5EB71CDB57AA003FF4B4 /* StarLoopbackState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C901CDB57AA003FF4B4 /* StarLoopbackState.h */; };\n\t\t276E5EB81CDB57AA003FF4B4 /* StarLoopbackState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C901CDB57AA003FF4B4 /* StarLoopbackState.h */; };\n\t\t276E5EB91CDB57AA003FF4B4 /* StarLoopbackState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C901CDB57AA003FF4B4 /* StarLoopbackState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EBD1CDB57AA003FF4B4 /* StarLoopEntryState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C921CDB57AA003FF4B4 /* StarLoopEntryState.h */; };\n\t\t276E5EBE1CDB57AA003FF4B4 /* StarLoopEntryState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C921CDB57AA003FF4B4 /* StarLoopEntryState.h */; };\n\t\t276E5EBF1CDB57AA003FF4B4 /* StarLoopEntryState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C921CDB57AA003FF4B4 /* StarLoopEntryState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EC31CDB57AA003FF4B4 /* TokensStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C941CDB57AA003FF4B4 /* TokensStartState.h */; };\n\t\t276E5EC41CDB57AA003FF4B4 /* TokensStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C941CDB57AA003FF4B4 /* TokensStartState.h */; };\n\t\t276E5EC51CDB57AA003FF4B4 /* TokensStartState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C941CDB57AA003FF4B4 /* TokensStartState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EC61CDB57AA003FF4B4 /* Transition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C951CDB57AA003FF4B4 /* Transition.cpp */; };\n\t\t276E5EC71CDB57AA003FF4B4 /* Transition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C951CDB57AA003FF4B4 /* Transition.cpp */; };\n\t\t276E5EC81CDB57AA003FF4B4 /* Transition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C951CDB57AA003FF4B4 /* Transition.cpp */; };\n\t\t276E5EC91CDB57AA003FF4B4 /* Transition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C961CDB57AA003FF4B4 /* Transition.h */; };\n\t\t276E5ECA1CDB57AA003FF4B4 /* Transition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C961CDB57AA003FF4B4 /* Transition.h */; };\n\t\t276E5ECB1CDB57AA003FF4B4 /* Transition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C961CDB57AA003FF4B4 /* Transition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5ECC1CDB57AA003FF4B4 /* WildcardTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C971CDB57AA003FF4B4 /* WildcardTransition.cpp */; };\n\t\t276E5ECD1CDB57AA003FF4B4 /* WildcardTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C971CDB57AA003FF4B4 /* WildcardTransition.cpp */; };\n\t\t276E5ECE1CDB57AA003FF4B4 /* WildcardTransition.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C971CDB57AA003FF4B4 /* WildcardTransition.cpp */; };\n\t\t276E5ECF1CDB57AA003FF4B4 /* WildcardTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C981CDB57AA003FF4B4 /* WildcardTransition.h */; };\n\t\t276E5ED01CDB57AA003FF4B4 /* WildcardTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C981CDB57AA003FF4B4 /* WildcardTransition.h */; };\n\t\t276E5ED11CDB57AA003FF4B4 /* WildcardTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C981CDB57AA003FF4B4 /* WildcardTransition.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5ED21CDB57AA003FF4B4 /* BailErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C991CDB57AA003FF4B4 /* BailErrorStrategy.cpp */; };\n\t\t276E5ED31CDB57AA003FF4B4 /* BailErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C991CDB57AA003FF4B4 /* BailErrorStrategy.cpp */; };\n\t\t276E5ED41CDB57AA003FF4B4 /* BailErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C991CDB57AA003FF4B4 /* BailErrorStrategy.cpp */; };\n\t\t276E5ED51CDB57AA003FF4B4 /* BailErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9A1CDB57AA003FF4B4 /* BailErrorStrategy.h */; };\n\t\t276E5ED61CDB57AA003FF4B4 /* BailErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9A1CDB57AA003FF4B4 /* BailErrorStrategy.h */; };\n\t\t276E5ED71CDB57AA003FF4B4 /* BailErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9A1CDB57AA003FF4B4 /* BailErrorStrategy.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5ED81CDB57AA003FF4B4 /* BaseErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9B1CDB57AA003FF4B4 /* BaseErrorListener.cpp */; };\n\t\t276E5ED91CDB57AA003FF4B4 /* BaseErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9B1CDB57AA003FF4B4 /* BaseErrorListener.cpp */; };\n\t\t276E5EDA1CDB57AA003FF4B4 /* BaseErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9B1CDB57AA003FF4B4 /* BaseErrorListener.cpp */; };\n\t\t276E5EDB1CDB57AA003FF4B4 /* BaseErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9C1CDB57AA003FF4B4 /* BaseErrorListener.h */; };\n\t\t276E5EDC1CDB57AA003FF4B4 /* BaseErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9C1CDB57AA003FF4B4 /* BaseErrorListener.h */; };\n\t\t276E5EDD1CDB57AA003FF4B4 /* BaseErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9C1CDB57AA003FF4B4 /* BaseErrorListener.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EDE1CDB57AA003FF4B4 /* BufferedTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9D1CDB57AA003FF4B4 /* BufferedTokenStream.cpp */; };\n\t\t276E5EDF1CDB57AA003FF4B4 /* BufferedTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9D1CDB57AA003FF4B4 /* BufferedTokenStream.cpp */; };\n\t\t276E5EE01CDB57AA003FF4B4 /* BufferedTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9D1CDB57AA003FF4B4 /* BufferedTokenStream.cpp */; };\n\t\t276E5EE11CDB57AA003FF4B4 /* BufferedTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9E1CDB57AA003FF4B4 /* BufferedTokenStream.h */; };\n\t\t276E5EE21CDB57AA003FF4B4 /* BufferedTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9E1CDB57AA003FF4B4 /* BufferedTokenStream.h */; };\n\t\t276E5EE31CDB57AA003FF4B4 /* BufferedTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5C9E1CDB57AA003FF4B4 /* BufferedTokenStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EE41CDB57AA003FF4B4 /* CharStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9F1CDB57AA003FF4B4 /* CharStream.cpp */; };\n\t\t276E5EE51CDB57AA003FF4B4 /* CharStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9F1CDB57AA003FF4B4 /* CharStream.cpp */; };\n\t\t276E5EE61CDB57AA003FF4B4 /* CharStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5C9F1CDB57AA003FF4B4 /* CharStream.cpp */; };\n\t\t276E5EE71CDB57AA003FF4B4 /* CharStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA01CDB57AA003FF4B4 /* CharStream.h */; };\n\t\t276E5EE81CDB57AA003FF4B4 /* CharStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA01CDB57AA003FF4B4 /* CharStream.h */; };\n\t\t276E5EE91CDB57AA003FF4B4 /* CharStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA01CDB57AA003FF4B4 /* CharStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EEA1CDB57AA003FF4B4 /* CommonToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA11CDB57AA003FF4B4 /* CommonToken.cpp */; };\n\t\t276E5EEB1CDB57AA003FF4B4 /* CommonToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA11CDB57AA003FF4B4 /* CommonToken.cpp */; };\n\t\t276E5EEC1CDB57AA003FF4B4 /* CommonToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA11CDB57AA003FF4B4 /* CommonToken.cpp */; };\n\t\t276E5EED1CDB57AA003FF4B4 /* CommonToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA21CDB57AA003FF4B4 /* CommonToken.h */; };\n\t\t276E5EEE1CDB57AA003FF4B4 /* CommonToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA21CDB57AA003FF4B4 /* CommonToken.h */; };\n\t\t276E5EEF1CDB57AA003FF4B4 /* CommonToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA21CDB57AA003FF4B4 /* CommonToken.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EF01CDB57AA003FF4B4 /* CommonTokenFactory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA31CDB57AA003FF4B4 /* CommonTokenFactory.cpp */; };\n\t\t276E5EF11CDB57AA003FF4B4 /* CommonTokenFactory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA31CDB57AA003FF4B4 /* CommonTokenFactory.cpp */; };\n\t\t276E5EF21CDB57AA003FF4B4 /* CommonTokenFactory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA31CDB57AA003FF4B4 /* CommonTokenFactory.cpp */; };\n\t\t276E5EF31CDB57AA003FF4B4 /* CommonTokenFactory.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA41CDB57AA003FF4B4 /* CommonTokenFactory.h */; };\n\t\t276E5EF41CDB57AA003FF4B4 /* CommonTokenFactory.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA41CDB57AA003FF4B4 /* CommonTokenFactory.h */; };\n\t\t276E5EF51CDB57AA003FF4B4 /* CommonTokenFactory.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA41CDB57AA003FF4B4 /* CommonTokenFactory.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EF61CDB57AA003FF4B4 /* CommonTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA51CDB57AA003FF4B4 /* CommonTokenStream.cpp */; };\n\t\t276E5EF71CDB57AA003FF4B4 /* CommonTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA51CDB57AA003FF4B4 /* CommonTokenStream.cpp */; };\n\t\t276E5EF81CDB57AA003FF4B4 /* CommonTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA51CDB57AA003FF4B4 /* CommonTokenStream.cpp */; };\n\t\t276E5EF91CDB57AA003FF4B4 /* CommonTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA61CDB57AA003FF4B4 /* CommonTokenStream.h */; };\n\t\t276E5EFA1CDB57AA003FF4B4 /* CommonTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA61CDB57AA003FF4B4 /* CommonTokenStream.h */; };\n\t\t276E5EFB1CDB57AA003FF4B4 /* CommonTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA61CDB57AA003FF4B4 /* CommonTokenStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5EFC1CDB57AA003FF4B4 /* ConsoleErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA71CDB57AA003FF4B4 /* ConsoleErrorListener.cpp */; };\n\t\t276E5EFD1CDB57AA003FF4B4 /* ConsoleErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA71CDB57AA003FF4B4 /* ConsoleErrorListener.cpp */; };\n\t\t276E5EFE1CDB57AA003FF4B4 /* ConsoleErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA71CDB57AA003FF4B4 /* ConsoleErrorListener.cpp */; };\n\t\t276E5EFF1CDB57AA003FF4B4 /* ConsoleErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA81CDB57AA003FF4B4 /* ConsoleErrorListener.h */; };\n\t\t276E5F001CDB57AA003FF4B4 /* ConsoleErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA81CDB57AA003FF4B4 /* ConsoleErrorListener.h */; };\n\t\t276E5F011CDB57AA003FF4B4 /* ConsoleErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CA81CDB57AA003FF4B4 /* ConsoleErrorListener.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F021CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA91CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp */; };\n\t\t276E5F031CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA91CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp */; };\n\t\t276E5F041CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CA91CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp */; };\n\t\t276E5F051CDB57AA003FF4B4 /* DefaultErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAA1CDB57AA003FF4B4 /* DefaultErrorStrategy.h */; };\n\t\t276E5F061CDB57AA003FF4B4 /* DefaultErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAA1CDB57AA003FF4B4 /* DefaultErrorStrategy.h */; };\n\t\t276E5F071CDB57AA003FF4B4 /* DefaultErrorStrategy.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAA1CDB57AA003FF4B4 /* DefaultErrorStrategy.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F081CDB57AA003FF4B4 /* DFA.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CAC1CDB57AA003FF4B4 /* DFA.cpp */; };\n\t\t276E5F091CDB57AA003FF4B4 /* DFA.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CAC1CDB57AA003FF4B4 /* DFA.cpp */; };\n\t\t276E5F0A1CDB57AA003FF4B4 /* DFA.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CAC1CDB57AA003FF4B4 /* DFA.cpp */; };\n\t\t276E5F0B1CDB57AA003FF4B4 /* DFA.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAD1CDB57AA003FF4B4 /* DFA.h */; };\n\t\t276E5F0C1CDB57AA003FF4B4 /* DFA.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAD1CDB57AA003FF4B4 /* DFA.h */; };\n\t\t276E5F0D1CDB57AA003FF4B4 /* DFA.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAD1CDB57AA003FF4B4 /* DFA.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F0E1CDB57AA003FF4B4 /* DFASerializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CAE1CDB57AA003FF4B4 /* DFASerializer.cpp */; };\n\t\t276E5F0F1CDB57AA003FF4B4 /* DFASerializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CAE1CDB57AA003FF4B4 /* DFASerializer.cpp */; };\n\t\t276E5F101CDB57AA003FF4B4 /* DFASerializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CAE1CDB57AA003FF4B4 /* DFASerializer.cpp */; };\n\t\t276E5F111CDB57AA003FF4B4 /* DFASerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAF1CDB57AA003FF4B4 /* DFASerializer.h */; };\n\t\t276E5F121CDB57AA003FF4B4 /* DFASerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAF1CDB57AA003FF4B4 /* DFASerializer.h */; };\n\t\t276E5F131CDB57AA003FF4B4 /* DFASerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CAF1CDB57AA003FF4B4 /* DFASerializer.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F141CDB57AA003FF4B4 /* DFAState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB01CDB57AA003FF4B4 /* DFAState.cpp */; };\n\t\t276E5F151CDB57AA003FF4B4 /* DFAState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB01CDB57AA003FF4B4 /* DFAState.cpp */; };\n\t\t276E5F161CDB57AA003FF4B4 /* DFAState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB01CDB57AA003FF4B4 /* DFAState.cpp */; };\n\t\t276E5F171CDB57AA003FF4B4 /* DFAState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB11CDB57AA003FF4B4 /* DFAState.h */; };\n\t\t276E5F181CDB57AA003FF4B4 /* DFAState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB11CDB57AA003FF4B4 /* DFAState.h */; };\n\t\t276E5F191CDB57AA003FF4B4 /* DFAState.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB11CDB57AA003FF4B4 /* DFAState.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F1A1CDB57AA003FF4B4 /* LexerDFASerializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB21CDB57AA003FF4B4 /* LexerDFASerializer.cpp */; };\n\t\t276E5F1B1CDB57AA003FF4B4 /* LexerDFASerializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB21CDB57AA003FF4B4 /* LexerDFASerializer.cpp */; };\n\t\t276E5F1C1CDB57AA003FF4B4 /* LexerDFASerializer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB21CDB57AA003FF4B4 /* LexerDFASerializer.cpp */; };\n\t\t276E5F1D1CDB57AA003FF4B4 /* LexerDFASerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB31CDB57AA003FF4B4 /* LexerDFASerializer.h */; };\n\t\t276E5F1E1CDB57AA003FF4B4 /* LexerDFASerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB31CDB57AA003FF4B4 /* LexerDFASerializer.h */; };\n\t\t276E5F1F1CDB57AA003FF4B4 /* LexerDFASerializer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB31CDB57AA003FF4B4 /* LexerDFASerializer.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F201CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB41CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp */; };\n\t\t276E5F211CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB41CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp */; };\n\t\t276E5F221CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB41CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp */; };\n\t\t276E5F231CDB57AA003FF4B4 /* DiagnosticErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB51CDB57AA003FF4B4 /* DiagnosticErrorListener.h */; };\n\t\t276E5F241CDB57AA003FF4B4 /* DiagnosticErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB51CDB57AA003FF4B4 /* DiagnosticErrorListener.h */; };\n\t\t276E5F251CDB57AA003FF4B4 /* DiagnosticErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB51CDB57AA003FF4B4 /* DiagnosticErrorListener.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F261CDB57AA003FF4B4 /* Exceptions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB61CDB57AA003FF4B4 /* Exceptions.cpp */; };\n\t\t276E5F271CDB57AA003FF4B4 /* Exceptions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB61CDB57AA003FF4B4 /* Exceptions.cpp */; };\n\t\t276E5F281CDB57AA003FF4B4 /* Exceptions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB61CDB57AA003FF4B4 /* Exceptions.cpp */; };\n\t\t276E5F291CDB57AA003FF4B4 /* Exceptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB71CDB57AA003FF4B4 /* Exceptions.h */; };\n\t\t276E5F2A1CDB57AA003FF4B4 /* Exceptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB71CDB57AA003FF4B4 /* Exceptions.h */; };\n\t\t276E5F2B1CDB57AA003FF4B4 /* Exceptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB71CDB57AA003FF4B4 /* Exceptions.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F2C1CDB57AA003FF4B4 /* FailedPredicateException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB81CDB57AA003FF4B4 /* FailedPredicateException.cpp */; };\n\t\t276E5F2D1CDB57AA003FF4B4 /* FailedPredicateException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB81CDB57AA003FF4B4 /* FailedPredicateException.cpp */; };\n\t\t276E5F2E1CDB57AA003FF4B4 /* FailedPredicateException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CB81CDB57AA003FF4B4 /* FailedPredicateException.cpp */; };\n\t\t276E5F2F1CDB57AA003FF4B4 /* FailedPredicateException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB91CDB57AA003FF4B4 /* FailedPredicateException.h */; };\n\t\t276E5F301CDB57AA003FF4B4 /* FailedPredicateException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB91CDB57AA003FF4B4 /* FailedPredicateException.h */; };\n\t\t276E5F311CDB57AA003FF4B4 /* FailedPredicateException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CB91CDB57AA003FF4B4 /* FailedPredicateException.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F321CDB57AA003FF4B4 /* InputMismatchException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBA1CDB57AA003FF4B4 /* InputMismatchException.cpp */; };\n\t\t276E5F331CDB57AA003FF4B4 /* InputMismatchException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBA1CDB57AA003FF4B4 /* InputMismatchException.cpp */; };\n\t\t276E5F341CDB57AA003FF4B4 /* InputMismatchException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBA1CDB57AA003FF4B4 /* InputMismatchException.cpp */; };\n\t\t276E5F351CDB57AA003FF4B4 /* InputMismatchException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBB1CDB57AA003FF4B4 /* InputMismatchException.h */; };\n\t\t276E5F361CDB57AA003FF4B4 /* InputMismatchException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBB1CDB57AA003FF4B4 /* InputMismatchException.h */; };\n\t\t276E5F371CDB57AA003FF4B4 /* InputMismatchException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBB1CDB57AA003FF4B4 /* InputMismatchException.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F381CDB57AA003FF4B4 /* InterpreterRuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBC1CDB57AA003FF4B4 /* InterpreterRuleContext.cpp */; };\n\t\t276E5F391CDB57AA003FF4B4 /* InterpreterRuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBC1CDB57AA003FF4B4 /* InterpreterRuleContext.cpp */; };\n\t\t276E5F3A1CDB57AA003FF4B4 /* InterpreterRuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBC1CDB57AA003FF4B4 /* InterpreterRuleContext.cpp */; };\n\t\t276E5F3B1CDB57AA003FF4B4 /* InterpreterRuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBD1CDB57AA003FF4B4 /* InterpreterRuleContext.h */; };\n\t\t276E5F3C1CDB57AA003FF4B4 /* InterpreterRuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBD1CDB57AA003FF4B4 /* InterpreterRuleContext.h */; };\n\t\t276E5F3D1CDB57AA003FF4B4 /* InterpreterRuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBD1CDB57AA003FF4B4 /* InterpreterRuleContext.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F3E1CDB57AA003FF4B4 /* IntStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBE1CDB57AA003FF4B4 /* IntStream.cpp */; };\n\t\t276E5F3F1CDB57AA003FF4B4 /* IntStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBE1CDB57AA003FF4B4 /* IntStream.cpp */; };\n\t\t276E5F401CDB57AA003FF4B4 /* IntStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CBE1CDB57AA003FF4B4 /* IntStream.cpp */; };\n\t\t276E5F411CDB57AA003FF4B4 /* IntStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBF1CDB57AA003FF4B4 /* IntStream.h */; };\n\t\t276E5F421CDB57AA003FF4B4 /* IntStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBF1CDB57AA003FF4B4 /* IntStream.h */; };\n\t\t276E5F431CDB57AA003FF4B4 /* IntStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CBF1CDB57AA003FF4B4 /* IntStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F471CDB57AA003FF4B4 /* Lexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC11CDB57AA003FF4B4 /* Lexer.cpp */; };\n\t\t276E5F481CDB57AA003FF4B4 /* Lexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC11CDB57AA003FF4B4 /* Lexer.cpp */; };\n\t\t276E5F491CDB57AA003FF4B4 /* Lexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC11CDB57AA003FF4B4 /* Lexer.cpp */; };\n\t\t276E5F4A1CDB57AA003FF4B4 /* Lexer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC21CDB57AA003FF4B4 /* Lexer.h */; };\n\t\t276E5F4B1CDB57AA003FF4B4 /* Lexer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC21CDB57AA003FF4B4 /* Lexer.h */; };\n\t\t276E5F4C1CDB57AA003FF4B4 /* Lexer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC21CDB57AA003FF4B4 /* Lexer.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F4D1CDB57AA003FF4B4 /* LexerInterpreter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC31CDB57AA003FF4B4 /* LexerInterpreter.cpp */; };\n\t\t276E5F4E1CDB57AA003FF4B4 /* LexerInterpreter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC31CDB57AA003FF4B4 /* LexerInterpreter.cpp */; };\n\t\t276E5F4F1CDB57AA003FF4B4 /* LexerInterpreter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC31CDB57AA003FF4B4 /* LexerInterpreter.cpp */; };\n\t\t276E5F501CDB57AA003FF4B4 /* LexerInterpreter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC41CDB57AA003FF4B4 /* LexerInterpreter.h */; };\n\t\t276E5F511CDB57AA003FF4B4 /* LexerInterpreter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC41CDB57AA003FF4B4 /* LexerInterpreter.h */; };\n\t\t276E5F521CDB57AA003FF4B4 /* LexerInterpreter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC41CDB57AA003FF4B4 /* LexerInterpreter.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F531CDB57AA003FF4B4 /* LexerNoViableAltException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC51CDB57AA003FF4B4 /* LexerNoViableAltException.cpp */; };\n\t\t276E5F541CDB57AA003FF4B4 /* LexerNoViableAltException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC51CDB57AA003FF4B4 /* LexerNoViableAltException.cpp */; };\n\t\t276E5F551CDB57AA003FF4B4 /* LexerNoViableAltException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC51CDB57AA003FF4B4 /* LexerNoViableAltException.cpp */; };\n\t\t276E5F561CDB57AA003FF4B4 /* LexerNoViableAltException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC61CDB57AA003FF4B4 /* LexerNoViableAltException.h */; };\n\t\t276E5F571CDB57AA003FF4B4 /* LexerNoViableAltException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC61CDB57AA003FF4B4 /* LexerNoViableAltException.h */; };\n\t\t276E5F581CDB57AA003FF4B4 /* LexerNoViableAltException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC61CDB57AA003FF4B4 /* LexerNoViableAltException.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F591CDB57AA003FF4B4 /* ListTokenSource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC71CDB57AA003FF4B4 /* ListTokenSource.cpp */; };\n\t\t276E5F5A1CDB57AA003FF4B4 /* ListTokenSource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC71CDB57AA003FF4B4 /* ListTokenSource.cpp */; };\n\t\t276E5F5B1CDB57AA003FF4B4 /* ListTokenSource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CC71CDB57AA003FF4B4 /* ListTokenSource.cpp */; };\n\t\t276E5F5C1CDB57AA003FF4B4 /* ListTokenSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC81CDB57AA003FF4B4 /* ListTokenSource.h */; };\n\t\t276E5F5D1CDB57AA003FF4B4 /* ListTokenSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC81CDB57AA003FF4B4 /* ListTokenSource.h */; };\n\t\t276E5F5E1CDB57AA003FF4B4 /* ListTokenSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CC81CDB57AA003FF4B4 /* ListTokenSource.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F5F1CDB57AA003FF4B4 /* Interval.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCA1CDB57AA003FF4B4 /* Interval.cpp */; };\n\t\t276E5F601CDB57AA003FF4B4 /* Interval.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCA1CDB57AA003FF4B4 /* Interval.cpp */; };\n\t\t276E5F611CDB57AA003FF4B4 /* Interval.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCA1CDB57AA003FF4B4 /* Interval.cpp */; };\n\t\t276E5F621CDB57AA003FF4B4 /* Interval.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCB1CDB57AA003FF4B4 /* Interval.h */; };\n\t\t276E5F631CDB57AA003FF4B4 /* Interval.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCB1CDB57AA003FF4B4 /* Interval.h */; };\n\t\t276E5F641CDB57AA003FF4B4 /* Interval.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCB1CDB57AA003FF4B4 /* Interval.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F651CDB57AA003FF4B4 /* IntervalSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCC1CDB57AA003FF4B4 /* IntervalSet.cpp */; };\n\t\t276E5F661CDB57AA003FF4B4 /* IntervalSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCC1CDB57AA003FF4B4 /* IntervalSet.cpp */; };\n\t\t276E5F671CDB57AA003FF4B4 /* IntervalSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCC1CDB57AA003FF4B4 /* IntervalSet.cpp */; };\n\t\t276E5F681CDB57AA003FF4B4 /* IntervalSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCD1CDB57AA003FF4B4 /* IntervalSet.h */; };\n\t\t276E5F691CDB57AA003FF4B4 /* IntervalSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCD1CDB57AA003FF4B4 /* IntervalSet.h */; };\n\t\t276E5F6A1CDB57AA003FF4B4 /* IntervalSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCD1CDB57AA003FF4B4 /* IntervalSet.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F6B1CDB57AA003FF4B4 /* MurmurHash.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCE1CDB57AA003FF4B4 /* MurmurHash.cpp */; };\n\t\t276E5F6C1CDB57AA003FF4B4 /* MurmurHash.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCE1CDB57AA003FF4B4 /* MurmurHash.cpp */; };\n\t\t276E5F6D1CDB57AA003FF4B4 /* MurmurHash.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CCE1CDB57AA003FF4B4 /* MurmurHash.cpp */; };\n\t\t276E5F6E1CDB57AA003FF4B4 /* MurmurHash.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCF1CDB57AA003FF4B4 /* MurmurHash.h */; };\n\t\t276E5F6F1CDB57AA003FF4B4 /* MurmurHash.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCF1CDB57AA003FF4B4 /* MurmurHash.h */; };\n\t\t276E5F701CDB57AA003FF4B4 /* MurmurHash.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CCF1CDB57AA003FF4B4 /* MurmurHash.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F741CDB57AA003FF4B4 /* Predicate.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD11CDB57AA003FF4B4 /* Predicate.h */; };\n\t\t276E5F751CDB57AA003FF4B4 /* Predicate.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD11CDB57AA003FF4B4 /* Predicate.h */; };\n\t\t276E5F761CDB57AA003FF4B4 /* Predicate.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD11CDB57AA003FF4B4 /* Predicate.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F7D1CDB57AA003FF4B4 /* NoViableAltException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD41CDB57AA003FF4B4 /* NoViableAltException.cpp */; };\n\t\t276E5F7E1CDB57AA003FF4B4 /* NoViableAltException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD41CDB57AA003FF4B4 /* NoViableAltException.cpp */; };\n\t\t276E5F7F1CDB57AA003FF4B4 /* NoViableAltException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD41CDB57AA003FF4B4 /* NoViableAltException.cpp */; };\n\t\t276E5F801CDB57AA003FF4B4 /* NoViableAltException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD51CDB57AA003FF4B4 /* NoViableAltException.h */; };\n\t\t276E5F811CDB57AA003FF4B4 /* NoViableAltException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD51CDB57AA003FF4B4 /* NoViableAltException.h */; };\n\t\t276E5F821CDB57AA003FF4B4 /* NoViableAltException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD51CDB57AA003FF4B4 /* NoViableAltException.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F831CDB57AA003FF4B4 /* Parser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD61CDB57AA003FF4B4 /* Parser.cpp */; };\n\t\t276E5F841CDB57AA003FF4B4 /* Parser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD61CDB57AA003FF4B4 /* Parser.cpp */; };\n\t\t276E5F851CDB57AA003FF4B4 /* Parser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD61CDB57AA003FF4B4 /* Parser.cpp */; };\n\t\t276E5F861CDB57AA003FF4B4 /* Parser.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD71CDB57AA003FF4B4 /* Parser.h */; };\n\t\t276E5F871CDB57AA003FF4B4 /* Parser.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD71CDB57AA003FF4B4 /* Parser.h */; };\n\t\t276E5F881CDB57AA003FF4B4 /* Parser.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD71CDB57AA003FF4B4 /* Parser.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F891CDB57AA003FF4B4 /* ParserInterpreter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD81CDB57AA003FF4B4 /* ParserInterpreter.cpp */; };\n\t\t276E5F8A1CDB57AA003FF4B4 /* ParserInterpreter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD81CDB57AA003FF4B4 /* ParserInterpreter.cpp */; };\n\t\t276E5F8B1CDB57AA003FF4B4 /* ParserInterpreter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CD81CDB57AA003FF4B4 /* ParserInterpreter.cpp */; };\n\t\t276E5F8C1CDB57AA003FF4B4 /* ParserInterpreter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD91CDB57AA003FF4B4 /* ParserInterpreter.h */; };\n\t\t276E5F8D1CDB57AA003FF4B4 /* ParserInterpreter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD91CDB57AA003FF4B4 /* ParserInterpreter.h */; };\n\t\t276E5F8E1CDB57AA003FF4B4 /* ParserInterpreter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CD91CDB57AA003FF4B4 /* ParserInterpreter.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F8F1CDB57AA003FF4B4 /* ParserRuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDA1CDB57AA003FF4B4 /* ParserRuleContext.cpp */; };\n\t\t276E5F901CDB57AA003FF4B4 /* ParserRuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDA1CDB57AA003FF4B4 /* ParserRuleContext.cpp */; };\n\t\t276E5F911CDB57AA003FF4B4 /* ParserRuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDA1CDB57AA003FF4B4 /* ParserRuleContext.cpp */; };\n\t\t276E5F921CDB57AA003FF4B4 /* ParserRuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDB1CDB57AA003FF4B4 /* ParserRuleContext.h */; };\n\t\t276E5F931CDB57AA003FF4B4 /* ParserRuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDB1CDB57AA003FF4B4 /* ParserRuleContext.h */; };\n\t\t276E5F941CDB57AA003FF4B4 /* ParserRuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDB1CDB57AA003FF4B4 /* ParserRuleContext.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F951CDB57AA003FF4B4 /* ProxyErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDC1CDB57AA003FF4B4 /* ProxyErrorListener.cpp */; };\n\t\t276E5F961CDB57AA003FF4B4 /* ProxyErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDC1CDB57AA003FF4B4 /* ProxyErrorListener.cpp */; };\n\t\t276E5F971CDB57AA003FF4B4 /* ProxyErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDC1CDB57AA003FF4B4 /* ProxyErrorListener.cpp */; };\n\t\t276E5F981CDB57AA003FF4B4 /* ProxyErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDD1CDB57AA003FF4B4 /* ProxyErrorListener.h */; };\n\t\t276E5F991CDB57AA003FF4B4 /* ProxyErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDD1CDB57AA003FF4B4 /* ProxyErrorListener.h */; };\n\t\t276E5F9A1CDB57AA003FF4B4 /* ProxyErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDD1CDB57AA003FF4B4 /* ProxyErrorListener.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5F9B1CDB57AA003FF4B4 /* RecognitionException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDE1CDB57AA003FF4B4 /* RecognitionException.cpp */; };\n\t\t276E5F9C1CDB57AA003FF4B4 /* RecognitionException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDE1CDB57AA003FF4B4 /* RecognitionException.cpp */; };\n\t\t276E5F9D1CDB57AA003FF4B4 /* RecognitionException.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CDE1CDB57AA003FF4B4 /* RecognitionException.cpp */; };\n\t\t276E5F9E1CDB57AA003FF4B4 /* RecognitionException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDF1CDB57AA003FF4B4 /* RecognitionException.h */; };\n\t\t276E5F9F1CDB57AA003FF4B4 /* RecognitionException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDF1CDB57AA003FF4B4 /* RecognitionException.h */; };\n\t\t276E5FA01CDB57AA003FF4B4 /* RecognitionException.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CDF1CDB57AA003FF4B4 /* RecognitionException.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FA11CDB57AA003FF4B4 /* Recognizer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE01CDB57AA003FF4B4 /* Recognizer.cpp */; };\n\t\t276E5FA21CDB57AA003FF4B4 /* Recognizer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE01CDB57AA003FF4B4 /* Recognizer.cpp */; };\n\t\t276E5FA31CDB57AA003FF4B4 /* Recognizer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE01CDB57AA003FF4B4 /* Recognizer.cpp */; };\n\t\t276E5FA41CDB57AA003FF4B4 /* Recognizer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE11CDB57AA003FF4B4 /* Recognizer.h */; };\n\t\t276E5FA51CDB57AA003FF4B4 /* Recognizer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE11CDB57AA003FF4B4 /* Recognizer.h */; };\n\t\t276E5FA61CDB57AA003FF4B4 /* Recognizer.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE11CDB57AA003FF4B4 /* Recognizer.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FA71CDB57AA003FF4B4 /* RuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE21CDB57AA003FF4B4 /* RuleContext.cpp */; };\n\t\t276E5FA81CDB57AA003FF4B4 /* RuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE21CDB57AA003FF4B4 /* RuleContext.cpp */; };\n\t\t276E5FA91CDB57AA003FF4B4 /* RuleContext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE21CDB57AA003FF4B4 /* RuleContext.cpp */; };\n\t\t276E5FAA1CDB57AA003FF4B4 /* RuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE31CDB57AA003FF4B4 /* RuleContext.h */; };\n\t\t276E5FAB1CDB57AA003FF4B4 /* RuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE31CDB57AA003FF4B4 /* RuleContext.h */; };\n\t\t276E5FAC1CDB57AA003FF4B4 /* RuleContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE31CDB57AA003FF4B4 /* RuleContext.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FAD1CDB57AA003FF4B4 /* Arrays.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE51CDB57AA003FF4B4 /* Arrays.cpp */; };\n\t\t276E5FAE1CDB57AA003FF4B4 /* Arrays.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE51CDB57AA003FF4B4 /* Arrays.cpp */; };\n\t\t276E5FAF1CDB57AA003FF4B4 /* Arrays.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE51CDB57AA003FF4B4 /* Arrays.cpp */; };\n\t\t276E5FB01CDB57AA003FF4B4 /* Arrays.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE61CDB57AA003FF4B4 /* Arrays.h */; };\n\t\t276E5FB11CDB57AA003FF4B4 /* Arrays.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE61CDB57AA003FF4B4 /* Arrays.h */; };\n\t\t276E5FB21CDB57AA003FF4B4 /* Arrays.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE61CDB57AA003FF4B4 /* Arrays.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FB31CDB57AA003FF4B4 /* BitSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE71CDB57AA003FF4B4 /* BitSet.h */; };\n\t\t276E5FB41CDB57AA003FF4B4 /* BitSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE71CDB57AA003FF4B4 /* BitSet.h */; };\n\t\t276E5FB51CDB57AA003FF4B4 /* BitSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE71CDB57AA003FF4B4 /* BitSet.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FB61CDB57AA003FF4B4 /* CPPUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE81CDB57AA003FF4B4 /* CPPUtils.cpp */; };\n\t\t276E5FB71CDB57AA003FF4B4 /* CPPUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE81CDB57AA003FF4B4 /* CPPUtils.cpp */; };\n\t\t276E5FB81CDB57AA003FF4B4 /* CPPUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CE81CDB57AA003FF4B4 /* CPPUtils.cpp */; };\n\t\t276E5FB91CDB57AA003FF4B4 /* CPPUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE91CDB57AA003FF4B4 /* CPPUtils.h */; };\n\t\t276E5FBA1CDB57AA003FF4B4 /* CPPUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE91CDB57AA003FF4B4 /* CPPUtils.h */; };\n\t\t276E5FBB1CDB57AA003FF4B4 /* CPPUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CE91CDB57AA003FF4B4 /* CPPUtils.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FBC1CDB57AA003FF4B4 /* Declarations.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CEA1CDB57AA003FF4B4 /* Declarations.h */; };\n\t\t276E5FBD1CDB57AA003FF4B4 /* Declarations.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CEA1CDB57AA003FF4B4 /* Declarations.h */; };\n\t\t276E5FBE1CDB57AA003FF4B4 /* Declarations.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CEA1CDB57AA003FF4B4 /* Declarations.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FC51CDB57AA003FF4B4 /* StringUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CED1CDB57AA003FF4B4 /* StringUtils.cpp */; };\n\t\t276E5FC61CDB57AA003FF4B4 /* StringUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CED1CDB57AA003FF4B4 /* StringUtils.cpp */; };\n\t\t276E5FC71CDB57AA003FF4B4 /* StringUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CED1CDB57AA003FF4B4 /* StringUtils.cpp */; };\n\t\t276E5FC81CDB57AA003FF4B4 /* StringUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CEE1CDB57AA003FF4B4 /* StringUtils.h */; };\n\t\t276E5FC91CDB57AA003FF4B4 /* StringUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CEE1CDB57AA003FF4B4 /* StringUtils.h */; };\n\t\t276E5FCA1CDB57AA003FF4B4 /* StringUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CEE1CDB57AA003FF4B4 /* StringUtils.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FCE1CDB57AA003FF4B4 /* Token.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF01CDB57AA003FF4B4 /* Token.h */; };\n\t\t276E5FCF1CDB57AA003FF4B4 /* Token.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF01CDB57AA003FF4B4 /* Token.h */; };\n\t\t276E5FD01CDB57AA003FF4B4 /* Token.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF01CDB57AA003FF4B4 /* Token.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FD41CDB57AA003FF4B4 /* TokenFactory.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF21CDB57AA003FF4B4 /* TokenFactory.h */; };\n\t\t276E5FD51CDB57AA003FF4B4 /* TokenFactory.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF21CDB57AA003FF4B4 /* TokenFactory.h */; };\n\t\t276E5FD61CDB57AA003FF4B4 /* TokenFactory.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF21CDB57AA003FF4B4 /* TokenFactory.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FDA1CDB57AA003FF4B4 /* TokenSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF41CDB57AA003FF4B4 /* TokenSource.h */; };\n\t\t276E5FDB1CDB57AA003FF4B4 /* TokenSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF41CDB57AA003FF4B4 /* TokenSource.h */; };\n\t\t276E5FDC1CDB57AA003FF4B4 /* TokenSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF41CDB57AA003FF4B4 /* TokenSource.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FDD1CDB57AA003FF4B4 /* TokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CF51CDB57AA003FF4B4 /* TokenStream.cpp */; };\n\t\t276E5FDE1CDB57AA003FF4B4 /* TokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CF51CDB57AA003FF4B4 /* TokenStream.cpp */; };\n\t\t276E5FDF1CDB57AA003FF4B4 /* TokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CF51CDB57AA003FF4B4 /* TokenStream.cpp */; };\n\t\t276E5FE01CDB57AA003FF4B4 /* TokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF61CDB57AA003FF4B4 /* TokenStream.h */; };\n\t\t276E5FE11CDB57AA003FF4B4 /* TokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF61CDB57AA003FF4B4 /* TokenStream.h */; };\n\t\t276E5FE21CDB57AA003FF4B4 /* TokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF61CDB57AA003FF4B4 /* TokenStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FE31CDB57AA003FF4B4 /* TokenStreamRewriter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CF71CDB57AA003FF4B4 /* TokenStreamRewriter.cpp */; };\n\t\t276E5FE41CDB57AA003FF4B4 /* TokenStreamRewriter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CF71CDB57AA003FF4B4 /* TokenStreamRewriter.cpp */; };\n\t\t276E5FE51CDB57AA003FF4B4 /* TokenStreamRewriter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CF71CDB57AA003FF4B4 /* TokenStreamRewriter.cpp */; };\n\t\t276E5FE61CDB57AA003FF4B4 /* TokenStreamRewriter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF81CDB57AA003FF4B4 /* TokenStreamRewriter.h */; };\n\t\t276E5FE71CDB57AA003FF4B4 /* TokenStreamRewriter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF81CDB57AA003FF4B4 /* TokenStreamRewriter.h */; };\n\t\t276E5FE81CDB57AA003FF4B4 /* TokenStreamRewriter.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CF81CDB57AA003FF4B4 /* TokenStreamRewriter.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FE91CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFA1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h */; };\n\t\t276E5FEA1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFA1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h */; };\n\t\t276E5FEB1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFA1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FEC1CDB57AA003FF4B4 /* ErrorNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFB1CDB57AA003FF4B4 /* ErrorNode.h */; };\n\t\t276E5FED1CDB57AA003FF4B4 /* ErrorNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFB1CDB57AA003FF4B4 /* ErrorNode.h */; };\n\t\t276E5FEE1CDB57AA003FF4B4 /* ErrorNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFB1CDB57AA003FF4B4 /* ErrorNode.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FEF1CDB57AA003FF4B4 /* ErrorNodeImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CFC1CDB57AA003FF4B4 /* ErrorNodeImpl.cpp */; };\n\t\t276E5FF01CDB57AA003FF4B4 /* ErrorNodeImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CFC1CDB57AA003FF4B4 /* ErrorNodeImpl.cpp */; };\n\t\t276E5FF11CDB57AA003FF4B4 /* ErrorNodeImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5CFC1CDB57AA003FF4B4 /* ErrorNodeImpl.cpp */; };\n\t\t276E5FF21CDB57AA003FF4B4 /* ErrorNodeImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFD1CDB57AA003FF4B4 /* ErrorNodeImpl.h */; };\n\t\t276E5FF31CDB57AA003FF4B4 /* ErrorNodeImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFD1CDB57AA003FF4B4 /* ErrorNodeImpl.h */; };\n\t\t276E5FF41CDB57AA003FF4B4 /* ErrorNodeImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFD1CDB57AA003FF4B4 /* ErrorNodeImpl.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FF51CDB57AA003FF4B4 /* ParseTree.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFE1CDB57AA003FF4B4 /* ParseTree.h */; };\n\t\t276E5FF61CDB57AA003FF4B4 /* ParseTree.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFE1CDB57AA003FF4B4 /* ParseTree.h */; };\n\t\t276E5FF71CDB57AA003FF4B4 /* ParseTree.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5CFE1CDB57AA003FF4B4 /* ParseTree.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E5FFB1CDB57AA003FF4B4 /* ParseTreeListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D001CDB57AA003FF4B4 /* ParseTreeListener.h */; };\n\t\t276E5FFC1CDB57AA003FF4B4 /* ParseTreeListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D001CDB57AA003FF4B4 /* ParseTreeListener.h */; };\n\t\t276E5FFD1CDB57AA003FF4B4 /* ParseTreeListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D001CDB57AA003FF4B4 /* ParseTreeListener.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60011CDB57AA003FF4B4 /* ParseTreeProperty.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D021CDB57AA003FF4B4 /* ParseTreeProperty.h */; };\n\t\t276E60021CDB57AA003FF4B4 /* ParseTreeProperty.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D021CDB57AA003FF4B4 /* ParseTreeProperty.h */; };\n\t\t276E60031CDB57AA003FF4B4 /* ParseTreeProperty.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D021CDB57AA003FF4B4 /* ParseTreeProperty.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60041CDB57AA003FF4B4 /* ParseTreeVisitor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D031CDB57AA003FF4B4 /* ParseTreeVisitor.h */; };\n\t\t276E60051CDB57AA003FF4B4 /* ParseTreeVisitor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D031CDB57AA003FF4B4 /* ParseTreeVisitor.h */; };\n\t\t276E60061CDB57AA003FF4B4 /* ParseTreeVisitor.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D031CDB57AA003FF4B4 /* ParseTreeVisitor.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60071CDB57AA003FF4B4 /* ParseTreeWalker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D041CDB57AA003FF4B4 /* ParseTreeWalker.cpp */; };\n\t\t276E60081CDB57AA003FF4B4 /* ParseTreeWalker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D041CDB57AA003FF4B4 /* ParseTreeWalker.cpp */; };\n\t\t276E60091CDB57AA003FF4B4 /* ParseTreeWalker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D041CDB57AA003FF4B4 /* ParseTreeWalker.cpp */; };\n\t\t276E600A1CDB57AA003FF4B4 /* ParseTreeWalker.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D051CDB57AA003FF4B4 /* ParseTreeWalker.h */; };\n\t\t276E600B1CDB57AA003FF4B4 /* ParseTreeWalker.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D051CDB57AA003FF4B4 /* ParseTreeWalker.h */; };\n\t\t276E600C1CDB57AA003FF4B4 /* ParseTreeWalker.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D051CDB57AA003FF4B4 /* ParseTreeWalker.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E600D1CDB57AA003FF4B4 /* Chunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D071CDB57AA003FF4B4 /* Chunk.h */; };\n\t\t276E600E1CDB57AA003FF4B4 /* Chunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D071CDB57AA003FF4B4 /* Chunk.h */; };\n\t\t276E600F1CDB57AA003FF4B4 /* Chunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D071CDB57AA003FF4B4 /* Chunk.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60101CDB57AA003FF4B4 /* ParseTreeMatch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D081CDB57AA003FF4B4 /* ParseTreeMatch.cpp */; };\n\t\t276E60111CDB57AA003FF4B4 /* ParseTreeMatch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D081CDB57AA003FF4B4 /* ParseTreeMatch.cpp */; };\n\t\t276E60121CDB57AA003FF4B4 /* ParseTreeMatch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D081CDB57AA003FF4B4 /* ParseTreeMatch.cpp */; };\n\t\t276E60131CDB57AA003FF4B4 /* ParseTreeMatch.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D091CDB57AA003FF4B4 /* ParseTreeMatch.h */; };\n\t\t276E60141CDB57AA003FF4B4 /* ParseTreeMatch.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D091CDB57AA003FF4B4 /* ParseTreeMatch.h */; };\n\t\t276E60151CDB57AA003FF4B4 /* ParseTreeMatch.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D091CDB57AA003FF4B4 /* ParseTreeMatch.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60161CDB57AA003FF4B4 /* ParseTreePattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0A1CDB57AA003FF4B4 /* ParseTreePattern.cpp */; };\n\t\t276E60171CDB57AA003FF4B4 /* ParseTreePattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0A1CDB57AA003FF4B4 /* ParseTreePattern.cpp */; };\n\t\t276E60181CDB57AA003FF4B4 /* ParseTreePattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0A1CDB57AA003FF4B4 /* ParseTreePattern.cpp */; };\n\t\t276E60191CDB57AA003FF4B4 /* ParseTreePattern.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0B1CDB57AA003FF4B4 /* ParseTreePattern.h */; };\n\t\t276E601A1CDB57AA003FF4B4 /* ParseTreePattern.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0B1CDB57AA003FF4B4 /* ParseTreePattern.h */; };\n\t\t276E601B1CDB57AA003FF4B4 /* ParseTreePattern.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0B1CDB57AA003FF4B4 /* ParseTreePattern.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E601C1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0C1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp */; };\n\t\t276E601D1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0C1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp */; };\n\t\t276E601E1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0C1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp */; };\n\t\t276E601F1CDB57AA003FF4B4 /* ParseTreePatternMatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0D1CDB57AA003FF4B4 /* ParseTreePatternMatcher.h */; };\n\t\t276E60201CDB57AA003FF4B4 /* ParseTreePatternMatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0D1CDB57AA003FF4B4 /* ParseTreePatternMatcher.h */; };\n\t\t276E60211CDB57AA003FF4B4 /* ParseTreePatternMatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0D1CDB57AA003FF4B4 /* ParseTreePatternMatcher.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60221CDB57AA003FF4B4 /* RuleTagToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0E1CDB57AA003FF4B4 /* RuleTagToken.cpp */; };\n\t\t276E60231CDB57AA003FF4B4 /* RuleTagToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0E1CDB57AA003FF4B4 /* RuleTagToken.cpp */; };\n\t\t276E60241CDB57AA003FF4B4 /* RuleTagToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D0E1CDB57AA003FF4B4 /* RuleTagToken.cpp */; };\n\t\t276E60251CDB57AA003FF4B4 /* RuleTagToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0F1CDB57AA003FF4B4 /* RuleTagToken.h */; };\n\t\t276E60261CDB57AA003FF4B4 /* RuleTagToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0F1CDB57AA003FF4B4 /* RuleTagToken.h */; };\n\t\t276E60271CDB57AA003FF4B4 /* RuleTagToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D0F1CDB57AA003FF4B4 /* RuleTagToken.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60281CDB57AA003FF4B4 /* TagChunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D101CDB57AA003FF4B4 /* TagChunk.cpp */; };\n\t\t276E60291CDB57AA003FF4B4 /* TagChunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D101CDB57AA003FF4B4 /* TagChunk.cpp */; };\n\t\t276E602A1CDB57AA003FF4B4 /* TagChunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D101CDB57AA003FF4B4 /* TagChunk.cpp */; };\n\t\t276E602B1CDB57AA003FF4B4 /* TagChunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D111CDB57AA003FF4B4 /* TagChunk.h */; };\n\t\t276E602C1CDB57AA003FF4B4 /* TagChunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D111CDB57AA003FF4B4 /* TagChunk.h */; };\n\t\t276E602D1CDB57AA003FF4B4 /* TagChunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D111CDB57AA003FF4B4 /* TagChunk.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E602E1CDB57AA003FF4B4 /* TextChunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D121CDB57AA003FF4B4 /* TextChunk.cpp */; };\n\t\t276E602F1CDB57AA003FF4B4 /* TextChunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D121CDB57AA003FF4B4 /* TextChunk.cpp */; };\n\t\t276E60301CDB57AA003FF4B4 /* TextChunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D121CDB57AA003FF4B4 /* TextChunk.cpp */; };\n\t\t276E60311CDB57AA003FF4B4 /* TextChunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D131CDB57AA003FF4B4 /* TextChunk.h */; };\n\t\t276E60321CDB57AA003FF4B4 /* TextChunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D131CDB57AA003FF4B4 /* TextChunk.h */; };\n\t\t276E60331CDB57AA003FF4B4 /* TextChunk.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D131CDB57AA003FF4B4 /* TextChunk.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60341CDB57AA003FF4B4 /* TokenTagToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D141CDB57AA003FF4B4 /* TokenTagToken.cpp */; };\n\t\t276E60351CDB57AA003FF4B4 /* TokenTagToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D141CDB57AA003FF4B4 /* TokenTagToken.cpp */; };\n\t\t276E60361CDB57AA003FF4B4 /* TokenTagToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D141CDB57AA003FF4B4 /* TokenTagToken.cpp */; };\n\t\t276E60371CDB57AA003FF4B4 /* TokenTagToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D151CDB57AA003FF4B4 /* TokenTagToken.h */; };\n\t\t276E60381CDB57AA003FF4B4 /* TokenTagToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D151CDB57AA003FF4B4 /* TokenTagToken.h */; };\n\t\t276E60391CDB57AA003FF4B4 /* TokenTagToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D151CDB57AA003FF4B4 /* TokenTagToken.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60401CDB57AA003FF4B4 /* TerminalNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D181CDB57AA003FF4B4 /* TerminalNode.h */; };\n\t\t276E60411CDB57AA003FF4B4 /* TerminalNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D181CDB57AA003FF4B4 /* TerminalNode.h */; };\n\t\t276E60421CDB57AA003FF4B4 /* TerminalNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D181CDB57AA003FF4B4 /* TerminalNode.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60431CDB57AA003FF4B4 /* TerminalNodeImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D191CDB57AA003FF4B4 /* TerminalNodeImpl.cpp */; };\n\t\t276E60441CDB57AA003FF4B4 /* TerminalNodeImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D191CDB57AA003FF4B4 /* TerminalNodeImpl.cpp */; };\n\t\t276E60451CDB57AA003FF4B4 /* TerminalNodeImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D191CDB57AA003FF4B4 /* TerminalNodeImpl.cpp */; };\n\t\t276E60461CDB57AA003FF4B4 /* TerminalNodeImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D1A1CDB57AA003FF4B4 /* TerminalNodeImpl.h */; };\n\t\t276E60471CDB57AA003FF4B4 /* TerminalNodeImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D1A1CDB57AA003FF4B4 /* TerminalNodeImpl.h */; };\n\t\t276E60481CDB57AA003FF4B4 /* TerminalNodeImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D1A1CDB57AA003FF4B4 /* TerminalNodeImpl.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E604F1CDB57AA003FF4B4 /* Trees.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D1D1CDB57AA003FF4B4 /* Trees.cpp */; };\n\t\t276E60501CDB57AA003FF4B4 /* Trees.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D1D1CDB57AA003FF4B4 /* Trees.cpp */; };\n\t\t276E60511CDB57AA003FF4B4 /* Trees.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D1D1CDB57AA003FF4B4 /* Trees.cpp */; };\n\t\t276E60521CDB57AA003FF4B4 /* Trees.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D1E1CDB57AA003FF4B4 /* Trees.h */; };\n\t\t276E60531CDB57AA003FF4B4 /* Trees.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D1E1CDB57AA003FF4B4 /* Trees.h */; };\n\t\t276E60541CDB57AA003FF4B4 /* Trees.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D1E1CDB57AA003FF4B4 /* Trees.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E605B1CDB57AA003FF4B4 /* UnbufferedCharStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D221CDB57AA003FF4B4 /* UnbufferedCharStream.cpp */; };\n\t\t276E605C1CDB57AA003FF4B4 /* UnbufferedCharStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D221CDB57AA003FF4B4 /* UnbufferedCharStream.cpp */; };\n\t\t276E605D1CDB57AA003FF4B4 /* UnbufferedCharStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D221CDB57AA003FF4B4 /* UnbufferedCharStream.cpp */; };\n\t\t276E605E1CDB57AA003FF4B4 /* UnbufferedCharStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D231CDB57AA003FF4B4 /* UnbufferedCharStream.h */; };\n\t\t276E605F1CDB57AA003FF4B4 /* UnbufferedCharStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D231CDB57AA003FF4B4 /* UnbufferedCharStream.h */; };\n\t\t276E60601CDB57AA003FF4B4 /* UnbufferedCharStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D231CDB57AA003FF4B4 /* UnbufferedCharStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60611CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D241CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp */; };\n\t\t276E60621CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D241CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp */; };\n\t\t276E60631CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D241CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp */; };\n\t\t276E60641CDB57AA003FF4B4 /* UnbufferedTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D251CDB57AA003FF4B4 /* UnbufferedTokenStream.h */; };\n\t\t276E60651CDB57AA003FF4B4 /* UnbufferedTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D251CDB57AA003FF4B4 /* UnbufferedTokenStream.h */; };\n\t\t276E60661CDB57AA003FF4B4 /* UnbufferedTokenStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D251CDB57AA003FF4B4 /* UnbufferedTokenStream.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E606A1CDB57AA003FF4B4 /* Vocabulary.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D271CDB57AA003FF4B4 /* Vocabulary.cpp */; };\n\t\t276E606B1CDB57AA003FF4B4 /* Vocabulary.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D271CDB57AA003FF4B4 /* Vocabulary.cpp */; };\n\t\t276E606C1CDB57AA003FF4B4 /* Vocabulary.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 276E5D271CDB57AA003FF4B4 /* Vocabulary.cpp */; };\n\t\t276E606D1CDB57AA003FF4B4 /* Vocabulary.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D281CDB57AA003FF4B4 /* Vocabulary.h */; };\n\t\t276E606E1CDB57AA003FF4B4 /* Vocabulary.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D281CDB57AA003FF4B4 /* Vocabulary.h */; };\n\t\t276E606F1CDB57AA003FF4B4 /* Vocabulary.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D281CDB57AA003FF4B4 /* Vocabulary.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t276E60731CDB57AA003FF4B4 /* WritableToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D2A1CDB57AA003FF4B4 /* WritableToken.h */; };\n\t\t276E60741CDB57AA003FF4B4 /* WritableToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D2A1CDB57AA003FF4B4 /* WritableToken.h */; };\n\t\t276E60751CDB57AA003FF4B4 /* WritableToken.h in Headers */ = {isa = PBXBuildFile; fileRef = 276E5D2A1CDB57AA003FF4B4 /* WritableToken.h */; settings = {ATTRIBUTES = (Public, ); }; };\n\t\t27745F031CE49C000067C6A3 /* RuntimeMetaData.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27745EFB1CE49C000067C6A3 /* RuntimeMetaData.cpp */; };\n\t\t27745F041CE49C000067C6A3 /* RuntimeMetaData.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27745EFB1CE49C000067C6A3 /* RuntimeMetaData.cpp */; };\n\t\t27745F051CE49C000067C6A3 /* RuntimeMetaData.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27745EFB1CE49C000067C6A3 /* RuntimeMetaData.cpp */; };\n\t\t27745F061CE49C000067C6A3 /* RuntimeMetaData.h in Headers */ = {isa = PBXBuildFile; fileRef = 27745EFC1CE49C000067C6A3 /* RuntimeMetaData.h */; };\n\t\t27745F071CE49C000067C6A3 /* RuntimeMetaData.h in Headers */ = {isa = PBXBuildFile; fileRef = 27745EFC1CE49C000067C6A3 /* RuntimeMetaData.h */; };\n\t\t27745F081CE49C000067C6A3 /* RuntimeMetaData.h in Headers */ = {isa = PBXBuildFile; fileRef = 27745EFC1CE49C000067C6A3 /* RuntimeMetaData.h */; };\n\t\t27874F1E1CCB7A0700AF1C53 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */; };\n\t\t27874F211CCB7B1700AF1C53 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */; };\n\t\t2793DC851F08083F00A84290 /* TokenSource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC841F08083F00A84290 /* TokenSource.cpp */; };\n\t\t2793DC861F08083F00A84290 /* TokenSource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC841F08083F00A84290 /* TokenSource.cpp */; };\n\t\t2793DC871F08083F00A84290 /* TokenSource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC841F08083F00A84290 /* TokenSource.cpp */; };\n\t\t2793DC891F08087500A84290 /* Chunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC881F08087500A84290 /* Chunk.cpp */; };\n\t\t2793DC8A1F08087500A84290 /* Chunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC881F08087500A84290 /* Chunk.cpp */; };\n\t\t2793DC8B1F08087500A84290 /* Chunk.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC881F08087500A84290 /* Chunk.cpp */; };\n\t\t2793DC8D1F08088F00A84290 /* ParseTreeListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC8C1F08088F00A84290 /* ParseTreeListener.cpp */; };\n\t\t2793DC8E1F08088F00A84290 /* ParseTreeListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC8C1F08088F00A84290 /* ParseTreeListener.cpp */; };\n\t\t2793DC8F1F08088F00A84290 /* ParseTreeListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC8C1F08088F00A84290 /* ParseTreeListener.cpp */; };\n\t\t2793DC991F0808E100A84290 /* ParseTreeVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC951F0808E100A84290 /* ParseTreeVisitor.cpp */; };\n\t\t2793DC9A1F0808E100A84290 /* ParseTreeVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC951F0808E100A84290 /* ParseTreeVisitor.cpp */; };\n\t\t2793DC9B1F0808E100A84290 /* ParseTreeVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC951F0808E100A84290 /* ParseTreeVisitor.cpp */; };\n\t\t2793DC9D1F08090D00A84290 /* Any.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC9C1F08090D00A84290 /* Any.cpp */; };\n\t\t2793DC9E1F08090D00A84290 /* Any.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC9C1F08090D00A84290 /* Any.cpp */; };\n\t\t2793DC9F1F08090D00A84290 /* Any.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DC9C1F08090D00A84290 /* Any.cpp */; };\n\t\t2793DCA41F08095F00A84290 /* ANTLRErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA01F08095F00A84290 /* ANTLRErrorListener.cpp */; };\n\t\t2793DCA51F08095F00A84290 /* ANTLRErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA01F08095F00A84290 /* ANTLRErrorListener.cpp */; };\n\t\t2793DCA61F08095F00A84290 /* ANTLRErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA01F08095F00A84290 /* ANTLRErrorListener.cpp */; };\n\t\t2793DCA71F08095F00A84290 /* ANTLRErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA11F08095F00A84290 /* ANTLRErrorStrategy.cpp */; };\n\t\t2793DCA81F08095F00A84290 /* ANTLRErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA11F08095F00A84290 /* ANTLRErrorStrategy.cpp */; };\n\t\t2793DCA91F08095F00A84290 /* ANTLRErrorStrategy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA11F08095F00A84290 /* ANTLRErrorStrategy.cpp */; };\n\t\t2793DCAA1F08095F00A84290 /* Token.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA21F08095F00A84290 /* Token.cpp */; };\n\t\t2793DCAB1F08095F00A84290 /* Token.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA21F08095F00A84290 /* Token.cpp */; };\n\t\t2793DCAC1F08095F00A84290 /* Token.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA21F08095F00A84290 /* Token.cpp */; };\n\t\t2793DCAD1F08095F00A84290 /* WritableToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA31F08095F00A84290 /* WritableToken.cpp */; };\n\t\t2793DCAE1F08095F00A84290 /* WritableToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA31F08095F00A84290 /* WritableToken.cpp */; };\n\t\t2793DCAF1F08095F00A84290 /* WritableToken.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCA31F08095F00A84290 /* WritableToken.cpp */; };\n\t\t2793DCB61F08099C00A84290 /* LexerAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCB11F08099C00A84290 /* LexerAction.cpp */; };\n\t\t2793DCB71F08099C00A84290 /* LexerAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCB11F08099C00A84290 /* LexerAction.cpp */; };\n\t\t2793DCB81F08099C00A84290 /* LexerAction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2793DCB11F08099C00A84290 /* LexerAction.cpp */; };\n\t\t2794D8561CE7821B00FADD0F /* antlr4-common.h in Headers */ = {isa = PBXBuildFile; fileRef = 2794D8551CE7821B00FADD0F /* antlr4-common.h */; };\n\t\t2794D8571CE7821B00FADD0F /* antlr4-common.h in Headers */ = {isa = PBXBuildFile; fileRef = 2794D8551CE7821B00FADD0F /* antlr4-common.h */; };\n\t\t2794D8581CE7821B00FADD0F /* antlr4-common.h in Headers */ = {isa = PBXBuildFile; fileRef = 2794D8551CE7821B00FADD0F /* antlr4-common.h */; };\n\t\t27AC52D01CE773A80093AAAB /* antlr4-runtime.h in Headers */ = {isa = PBXBuildFile; fileRef = 27AC52CF1CE773A80093AAAB /* antlr4-runtime.h */; };\n\t\t27AC52D11CE773A80093AAAB /* antlr4-runtime.h in Headers */ = {isa = PBXBuildFile; fileRef = 27AC52CF1CE773A80093AAAB /* antlr4-runtime.h */; };\n\t\t27AC52D21CE773A80093AAAB /* antlr4-runtime.h in Headers */ = {isa = PBXBuildFile; fileRef = 27AC52CF1CE773A80093AAAB /* antlr4-runtime.h */; };\n\t\t27B36AC61DACE7AF0069C868 /* RuleContextWithAltNum.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27B36AC41DACE7AF0069C868 /* RuleContextWithAltNum.cpp */; };\n\t\t27B36AC71DACE7AF0069C868 /* RuleContextWithAltNum.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27B36AC41DACE7AF0069C868 /* RuleContextWithAltNum.cpp */; };\n\t\t27B36AC81DACE7AF0069C868 /* RuleContextWithAltNum.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27B36AC41DACE7AF0069C868 /* RuleContextWithAltNum.cpp */; };\n\t\t27B36AC91DACE7AF0069C868 /* RuleContextWithAltNum.h in Headers */ = {isa = PBXBuildFile; fileRef = 27B36AC51DACE7AF0069C868 /* RuleContextWithAltNum.h */; };\n\t\t27B36ACA1DACE7AF0069C868 /* RuleContextWithAltNum.h in Headers */ = {isa = PBXBuildFile; fileRef = 27B36AC51DACE7AF0069C868 /* RuleContextWithAltNum.h */; };\n\t\t27B36ACB1DACE7AF0069C868 /* RuleContextWithAltNum.h in Headers */ = {isa = PBXBuildFile; fileRef = 27B36AC51DACE7AF0069C868 /* RuleContextWithAltNum.h */; };\n\t\t27C375841EA1059C00B5883C /* InterpreterDataReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C375821EA1059C00B5883C /* InterpreterDataReader.cpp */; };\n\t\t27C375851EA1059C00B5883C /* InterpreterDataReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C375821EA1059C00B5883C /* InterpreterDataReader.cpp */; };\n\t\t27C375861EA1059C00B5883C /* InterpreterDataReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C375821EA1059C00B5883C /* InterpreterDataReader.cpp */; };\n\t\t27C375871EA1059C00B5883C /* InterpreterDataReader.h in Headers */ = {isa = PBXBuildFile; fileRef = 27C375831EA1059C00B5883C /* InterpreterDataReader.h */; };\n\t\t27C375881EA1059C00B5883C /* InterpreterDataReader.h in Headers */ = {isa = PBXBuildFile; fileRef = 27C375831EA1059C00B5883C /* InterpreterDataReader.h */; };\n\t\t27C375891EA1059C00B5883C /* InterpreterDataReader.h in Headers */ = {isa = PBXBuildFile; fileRef = 27C375831EA1059C00B5883C /* InterpreterDataReader.h */; };\n\t\t27D414521DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27D414501DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp */; };\n\t\t27D414531DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27D414501DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp */; };\n\t\t27D414541DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27D414501DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp */; };\n\t\t27D414551DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h in Headers */ = {isa = PBXBuildFile; fileRef = 27D414511DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h */; };\n\t\t27D414561DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h in Headers */ = {isa = PBXBuildFile; fileRef = 27D414511DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h */; };\n\t\t27D414571DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h in Headers */ = {isa = PBXBuildFile; fileRef = 27D414511DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h */; };\n\t\t27DB449D1D045537007E790B /* XPath.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448B1D045537007E790B /* XPath.cpp */; };\n\t\t27DB449E1D045537007E790B /* XPath.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB448C1D045537007E790B /* XPath.h */; };\n\t\t27DB449F1D045537007E790B /* XPathElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448D1D045537007E790B /* XPathElement.cpp */; };\n\t\t27DB44A01D045537007E790B /* XPathElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB448E1D045537007E790B /* XPathElement.h */; };\n\t\t27DB44A11D045537007E790B /* XPathLexerErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448F1D045537007E790B /* XPathLexerErrorListener.cpp */; };\n\t\t27DB44A21D045537007E790B /* XPathLexerErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44901D045537007E790B /* XPathLexerErrorListener.h */; };\n\t\t27DB44A31D045537007E790B /* XPathRuleAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44911D045537007E790B /* XPathRuleAnywhereElement.cpp */; };\n\t\t27DB44A41D045537007E790B /* XPathRuleAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44921D045537007E790B /* XPathRuleAnywhereElement.h */; };\n\t\t27DB44A51D045537007E790B /* XPathRuleElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44931D045537007E790B /* XPathRuleElement.cpp */; };\n\t\t27DB44A61D045537007E790B /* XPathRuleElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44941D045537007E790B /* XPathRuleElement.h */; };\n\t\t27DB44A71D045537007E790B /* XPathTokenAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44951D045537007E790B /* XPathTokenAnywhereElement.cpp */; };\n\t\t27DB44A81D045537007E790B /* XPathTokenAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44961D045537007E790B /* XPathTokenAnywhereElement.h */; };\n\t\t27DB44A91D045537007E790B /* XPathTokenElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44971D045537007E790B /* XPathTokenElement.cpp */; };\n\t\t27DB44AA1D045537007E790B /* XPathTokenElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44981D045537007E790B /* XPathTokenElement.h */; };\n\t\t27DB44AB1D045537007E790B /* XPathWildcardAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44991D045537007E790B /* XPathWildcardAnywhereElement.cpp */; };\n\t\t27DB44AC1D045537007E790B /* XPathWildcardAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB449A1D045537007E790B /* XPathWildcardAnywhereElement.h */; };\n\t\t27DB44AD1D045537007E790B /* XPathWildcardElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB449B1D045537007E790B /* XPathWildcardElement.cpp */; };\n\t\t27DB44AE1D045537007E790B /* XPathWildcardElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB449C1D045537007E790B /* XPathWildcardElement.h */; };\n\t\t27DB44B11D0463CC007E790B /* XPathLexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44AF1D0463CC007E790B /* XPathLexer.cpp */; };\n\t\t27DB44B21D0463CC007E790B /* XPathLexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44AF1D0463CC007E790B /* XPathLexer.cpp */; };\n\t\t27DB44B31D0463CC007E790B /* XPathLexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44AF1D0463CC007E790B /* XPathLexer.cpp */; };\n\t\t27DB44B41D0463CC007E790B /* XPathLexer.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44B01D0463CC007E790B /* XPathLexer.h */; };\n\t\t27DB44B51D0463CC007E790B /* XPathLexer.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44B01D0463CC007E790B /* XPathLexer.h */; };\n\t\t27DB44B61D0463CC007E790B /* XPathLexer.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44B01D0463CC007E790B /* XPathLexer.h */; };\n\t\t27DB44B71D0463DA007E790B /* XPath.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448B1D045537007E790B /* XPath.cpp */; };\n\t\t27DB44B81D0463DA007E790B /* XPath.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB448C1D045537007E790B /* XPath.h */; };\n\t\t27DB44B91D0463DA007E790B /* XPathElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448D1D045537007E790B /* XPathElement.cpp */; };\n\t\t27DB44BA1D0463DA007E790B /* XPathElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB448E1D045537007E790B /* XPathElement.h */; };\n\t\t27DB44BB1D0463DA007E790B /* XPathLexerErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448F1D045537007E790B /* XPathLexerErrorListener.cpp */; };\n\t\t27DB44BC1D0463DA007E790B /* XPathLexerErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44901D045537007E790B /* XPathLexerErrorListener.h */; };\n\t\t27DB44BD1D0463DA007E790B /* XPathRuleAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44911D045537007E790B /* XPathRuleAnywhereElement.cpp */; };\n\t\t27DB44BE1D0463DA007E790B /* XPathRuleAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44921D045537007E790B /* XPathRuleAnywhereElement.h */; };\n\t\t27DB44BF1D0463DA007E790B /* XPathRuleElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44931D045537007E790B /* XPathRuleElement.cpp */; };\n\t\t27DB44C01D0463DA007E790B /* XPathRuleElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44941D045537007E790B /* XPathRuleElement.h */; };\n\t\t27DB44C11D0463DA007E790B /* XPathTokenAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44951D045537007E790B /* XPathTokenAnywhereElement.cpp */; };\n\t\t27DB44C21D0463DA007E790B /* XPathTokenAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44961D045537007E790B /* XPathTokenAnywhereElement.h */; };\n\t\t27DB44C31D0463DA007E790B /* XPathTokenElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44971D045537007E790B /* XPathTokenElement.cpp */; };\n\t\t27DB44C41D0463DA007E790B /* XPathTokenElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44981D045537007E790B /* XPathTokenElement.h */; };\n\t\t27DB44C51D0463DA007E790B /* XPathWildcardAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44991D045537007E790B /* XPathWildcardAnywhereElement.cpp */; };\n\t\t27DB44C61D0463DA007E790B /* XPathWildcardAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB449A1D045537007E790B /* XPathWildcardAnywhereElement.h */; };\n\t\t27DB44C71D0463DA007E790B /* XPathWildcardElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB449B1D045537007E790B /* XPathWildcardElement.cpp */; };\n\t\t27DB44C81D0463DA007E790B /* XPathWildcardElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB449C1D045537007E790B /* XPathWildcardElement.h */; };\n\t\t27DB44C91D0463DB007E790B /* XPath.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448B1D045537007E790B /* XPath.cpp */; };\n\t\t27DB44CA1D0463DB007E790B /* XPath.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB448C1D045537007E790B /* XPath.h */; };\n\t\t27DB44CB1D0463DB007E790B /* XPathElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448D1D045537007E790B /* XPathElement.cpp */; };\n\t\t27DB44CC1D0463DB007E790B /* XPathElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB448E1D045537007E790B /* XPathElement.h */; };\n\t\t27DB44CD1D0463DB007E790B /* XPathLexerErrorListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB448F1D045537007E790B /* XPathLexerErrorListener.cpp */; };\n\t\t27DB44CE1D0463DB007E790B /* XPathLexerErrorListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44901D045537007E790B /* XPathLexerErrorListener.h */; };\n\t\t27DB44CF1D0463DB007E790B /* XPathRuleAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44911D045537007E790B /* XPathRuleAnywhereElement.cpp */; };\n\t\t27DB44D01D0463DB007E790B /* XPathRuleAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44921D045537007E790B /* XPathRuleAnywhereElement.h */; };\n\t\t27DB44D11D0463DB007E790B /* XPathRuleElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44931D045537007E790B /* XPathRuleElement.cpp */; };\n\t\t27DB44D21D0463DB007E790B /* XPathRuleElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44941D045537007E790B /* XPathRuleElement.h */; };\n\t\t27DB44D31D0463DB007E790B /* XPathTokenAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44951D045537007E790B /* XPathTokenAnywhereElement.cpp */; };\n\t\t27DB44D41D0463DB007E790B /* XPathTokenAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44961D045537007E790B /* XPathTokenAnywhereElement.h */; };\n\t\t27DB44D51D0463DB007E790B /* XPathTokenElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44971D045537007E790B /* XPathTokenElement.cpp */; };\n\t\t27DB44D61D0463DB007E790B /* XPathTokenElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB44981D045537007E790B /* XPathTokenElement.h */; };\n\t\t27DB44D71D0463DB007E790B /* XPathWildcardAnywhereElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB44991D045537007E790B /* XPathWildcardAnywhereElement.cpp */; };\n\t\t27DB44D81D0463DB007E790B /* XPathWildcardAnywhereElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB449A1D045537007E790B /* XPathWildcardAnywhereElement.h */; };\n\t\t27DB44D91D0463DB007E790B /* XPathWildcardElement.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27DB449B1D045537007E790B /* XPathWildcardElement.cpp */; };\n\t\t27DB44DA1D0463DB007E790B /* XPathWildcardElement.h in Headers */ = {isa = PBXBuildFile; fileRef = 27DB449C1D045537007E790B /* XPathWildcardElement.h */; };\n\t\t27F4A8561D4CEB2A00E067EE /* Any.h in Headers */ = {isa = PBXBuildFile; fileRef = 27F4A8551D4CEB2A00E067EE /* Any.h */; };\n\t\t9B25DCA12910249100DF9703 /* FlatHashSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DC9F2910249100DF9703 /* FlatHashSet.h */; };\n\t\t9B25DCA22910249100DF9703 /* FlatHashSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DC9F2910249100DF9703 /* FlatHashSet.h */; };\n\t\t9B25DCA32910249100DF9703 /* FlatHashSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DC9F2910249100DF9703 /* FlatHashSet.h */; };\n\t\t9B25DCA42910249100DF9703 /* FlatHashMap.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCA02910249100DF9703 /* FlatHashMap.h */; };\n\t\t9B25DCA52910249100DF9703 /* FlatHashMap.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCA02910249100DF9703 /* FlatHashMap.h */; };\n\t\t9B25DCA62910249100DF9703 /* FlatHashMap.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCA02910249100DF9703 /* FlatHashMap.h */; };\n\t\t9B25DCA82910252800DF9703 /* Version.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCA72910252800DF9703 /* Version.h */; };\n\t\t9B25DCA92910252800DF9703 /* Version.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCA72910252800DF9703 /* Version.h */; };\n\t\t9B25DCAA2910252800DF9703 /* Version.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCA72910252800DF9703 /* Version.h */; };\n\t\t9B25DCAC291025B700DF9703 /* ATNStateType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCAB291025B700DF9703 /* ATNStateType.h */; };\n\t\t9B25DCAD291025B700DF9703 /* ATNStateType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCAB291025B700DF9703 /* ATNStateType.h */; };\n\t\t9B25DCAE291025B700DF9703 /* ATNStateType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCAB291025B700DF9703 /* ATNStateType.h */; };\n\t\t9B25DCB0291026DE00DF9703 /* ParserATNSimulatorOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCAF291026DE00DF9703 /* ParserATNSimulatorOptions.h */; };\n\t\t9B25DCB1291026DE00DF9703 /* ParserATNSimulatorOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCAF291026DE00DF9703 /* ParserATNSimulatorOptions.h */; };\n\t\t9B25DCB2291026DE00DF9703 /* ParserATNSimulatorOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCAF291026DE00DF9703 /* ParserATNSimulatorOptions.h */; };\n\t\t9B25DCB92910278000DF9703 /* PredictionContextCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB32910278000DF9703 /* PredictionContextCache.h */; };\n\t\t9B25DCBA2910278000DF9703 /* PredictionContextCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB32910278000DF9703 /* PredictionContextCache.h */; };\n\t\t9B25DCBB2910278000DF9703 /* PredictionContextCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB32910278000DF9703 /* PredictionContextCache.h */; };\n\t\t9B25DCBC2910278000DF9703 /* PredictionContextMergeCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB42910278000DF9703 /* PredictionContextMergeCache.h */; };\n\t\t9B25DCBD2910278000DF9703 /* PredictionContextMergeCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB42910278000DF9703 /* PredictionContextMergeCache.h */; };\n\t\t9B25DCBE2910278000DF9703 /* PredictionContextMergeCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB42910278000DF9703 /* PredictionContextMergeCache.h */; };\n\t\t9B25DCBF2910278000DF9703 /* PredictionContextType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB52910278000DF9703 /* PredictionContextType.h */; };\n\t\t9B25DCC02910278000DF9703 /* PredictionContextType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB52910278000DF9703 /* PredictionContextType.h */; };\n\t\t9B25DCC12910278000DF9703 /* PredictionContextType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB52910278000DF9703 /* PredictionContextType.h */; };\n\t\t9B25DCC22910278000DF9703 /* PredictionContextCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCB62910278000DF9703 /* PredictionContextCache.cpp */; };\n\t\t9B25DCC32910278000DF9703 /* PredictionContextCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCB62910278000DF9703 /* PredictionContextCache.cpp */; };\n\t\t9B25DCC42910278000DF9703 /* PredictionContextCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCB62910278000DF9703 /* PredictionContextCache.cpp */; };\n\t\t9B25DCC52910278000DF9703 /* PredictionContextMergeCacheOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB72910278000DF9703 /* PredictionContextMergeCacheOptions.h */; };\n\t\t9B25DCC62910278000DF9703 /* PredictionContextMergeCacheOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB72910278000DF9703 /* PredictionContextMergeCacheOptions.h */; };\n\t\t9B25DCC72910278000DF9703 /* PredictionContextMergeCacheOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCB72910278000DF9703 /* PredictionContextMergeCacheOptions.h */; };\n\t\t9B25DCC82910278000DF9703 /* PredictionContextMergeCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCB82910278000DF9703 /* PredictionContextMergeCache.cpp */; };\n\t\t9B25DCC92910278000DF9703 /* PredictionContextMergeCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCB82910278000DF9703 /* PredictionContextMergeCache.cpp */; };\n\t\t9B25DCCA2910278000DF9703 /* PredictionContextMergeCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCB82910278000DF9703 /* PredictionContextMergeCache.cpp */; };\n\t\t9B25DCCD291027EE00DF9703 /* SemanticContextType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCCB291027ED00DF9703 /* SemanticContextType.h */; };\n\t\t9B25DCCE291027EE00DF9703 /* SemanticContextType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCCB291027ED00DF9703 /* SemanticContextType.h */; };\n\t\t9B25DCCF291027EE00DF9703 /* SemanticContextType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCCB291027ED00DF9703 /* SemanticContextType.h */; };\n\t\t9B25DCD0291027EE00DF9703 /* SerializedATNView.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCCC291027EE00DF9703 /* SerializedATNView.h */; };\n\t\t9B25DCD1291027EE00DF9703 /* SerializedATNView.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCCC291027EE00DF9703 /* SerializedATNView.h */; };\n\t\t9B25DCD2291027EE00DF9703 /* SerializedATNView.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCCC291027EE00DF9703 /* SerializedATNView.h */; };\n\t\t9B25DCD52910282B00DF9703 /* TransitionType.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCD32910282B00DF9703 /* TransitionType.cpp */; };\n\t\t9B25DCD62910282B00DF9703 /* TransitionType.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCD32910282B00DF9703 /* TransitionType.cpp */; };\n\t\t9B25DCD72910282B00DF9703 /* TransitionType.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCD32910282B00DF9703 /* TransitionType.cpp */; };\n\t\t9B25DCD82910282B00DF9703 /* TransitionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCD42910282B00DF9703 /* TransitionType.h */; };\n\t\t9B25DCD92910282B00DF9703 /* TransitionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCD42910282B00DF9703 /* TransitionType.h */; };\n\t\t9B25DCDA2910282B00DF9703 /* TransitionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCD42910282B00DF9703 /* TransitionType.h */; };\n\t\t9B25DCDE2910287000DF9703 /* Synchronization.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCDC2910287000DF9703 /* Synchronization.cpp */; };\n\t\t9B25DCDF2910287000DF9703 /* Synchronization.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCDC2910287000DF9703 /* Synchronization.cpp */; };\n\t\t9B25DCE02910287000DF9703 /* Synchronization.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCDC2910287000DF9703 /* Synchronization.cpp */; };\n\t\t9B25DCE12910287000DF9703 /* Synchronization.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCDD2910287000DF9703 /* Synchronization.h */; };\n\t\t9B25DCE22910287000DF9703 /* Synchronization.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCDD2910287000DF9703 /* Synchronization.h */; };\n\t\t9B25DCE32910287000DF9703 /* Synchronization.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCDD2910287000DF9703 /* Synchronization.h */; };\n\t\t9B25DCE5291028BC00DF9703 /* Casts.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE4291028BC00DF9703 /* Casts.h */; };\n\t\t9B25DCE6291028BC00DF9703 /* Casts.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE4291028BC00DF9703 /* Casts.h */; };\n\t\t9B25DCE7291028BC00DF9703 /* Casts.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE4291028BC00DF9703 /* Casts.h */; };\n\t\t9B25DCEB291028D000DF9703 /* Unicode.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE8291028D000DF9703 /* Unicode.h */; };\n\t\t9B25DCEC291028D000DF9703 /* Unicode.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE8291028D000DF9703 /* Unicode.h */; };\n\t\t9B25DCED291028D000DF9703 /* Unicode.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE8291028D000DF9703 /* Unicode.h */; };\n\t\t9B25DCEE291028D000DF9703 /* Utf8.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE9291028D000DF9703 /* Utf8.h */; };\n\t\t9B25DCEF291028D000DF9703 /* Utf8.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE9291028D000DF9703 /* Utf8.h */; };\n\t\t9B25DCF0291028D000DF9703 /* Utf8.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B25DCE9291028D000DF9703 /* Utf8.h */; };\n\t\t9B25DCF1291028D000DF9703 /* Utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCEA291028D000DF9703 /* Utf8.cpp */; };\n\t\t9B25DCF2291028D000DF9703 /* Utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCEA291028D000DF9703 /* Utf8.cpp */; };\n\t\t9B25DCF3291028D000DF9703 /* Utf8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B25DCEA291028D000DF9703 /* Utf8.cpp */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXFileReference section */\n\t\t270C67F01CDB4F1E00116E17 /* antlr4_ios.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = antlr4_ios.framework; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t270C67F21CDB4F1E00116E17 /* antlrcpp_ios.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = antlrcpp_ios.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t270C67F41CDB4F1E00116E17 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = \"<group>\"; };\n\t\t276566DF1DA93BFB000869BE /* ParseTree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseTree.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C0C1CDB57AA003FF4B4 /* ANTLRErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ANTLRErrorListener.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C0D1CDB57AA003FF4B4 /* ANTLRErrorStrategy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ANTLRErrorStrategy.h; sourceTree = \"<group>\"; };\n\t\t276E5C0E1CDB57AA003FF4B4 /* ANTLRFileStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ANTLRFileStream.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C0F1CDB57AA003FF4B4 /* ANTLRFileStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ANTLRFileStream.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C101CDB57AA003FF4B4 /* ANTLRInputStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ANTLRInputStream.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C111CDB57AA003FF4B4 /* ANTLRInputStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ANTLRInputStream.h; sourceTree = \"<group>\"; };\n\t\t276E5C151CDB57AA003FF4B4 /* ActionTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ActionTransition.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C161CDB57AA003FF4B4 /* ActionTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ActionTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C171CDB57AA003FF4B4 /* AmbiguityInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AmbiguityInfo.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C181CDB57AA003FF4B4 /* AmbiguityInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AmbiguityInfo.h; sourceTree = \"<group>\"; };\n\t\t276E5C191CDB57AA003FF4B4 /* ArrayPredictionContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; lineEnding = 0; path = ArrayPredictionContext.cpp; sourceTree = \"<group>\"; wrapsLines = 0; xcLanguageSpecificationIdentifier = xcode.lang.cpp; };\n\t\t276E5C1A1CDB57AA003FF4B4 /* ArrayPredictionContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = ArrayPredictionContext.h; sourceTree = \"<group>\"; wrapsLines = 0; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; };\n\t\t276E5C1B1CDB57AA003FF4B4 /* ATN.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATN.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C1C1CDB57AA003FF4B4 /* ATN.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATN.h; sourceTree = \"<group>\"; };\n\t\t276E5C1D1CDB57AA003FF4B4 /* ATNConfig.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; lineEnding = 0; path = ATNConfig.cpp; sourceTree = \"<group>\"; wrapsLines = 0; xcLanguageSpecificationIdentifier = xcode.lang.cpp; };\n\t\t276E5C1E1CDB57AA003FF4B4 /* ATNConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = ATNConfig.h; sourceTree = \"<group>\"; wrapsLines = 0; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; };\n\t\t276E5C1F1CDB57AA003FF4B4 /* ATNConfigSet.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNConfigSet.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C201CDB57AA003FF4B4 /* ATNConfigSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNConfigSet.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C211CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNDeserializationOptions.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C221CDB57AA003FF4B4 /* ATNDeserializationOptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNDeserializationOptions.h; sourceTree = \"<group>\"; };\n\t\t276E5C231CDB57AA003FF4B4 /* ATNDeserializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNDeserializer.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C241CDB57AA003FF4B4 /* ATNDeserializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNDeserializer.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C271CDB57AA003FF4B4 /* ATNSimulator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; lineEnding = 0; path = ATNSimulator.cpp; sourceTree = \"<group>\"; xcLanguageSpecificationIdentifier = xcode.lang.cpp; };\n\t\t276E5C281CDB57AA003FF4B4 /* ATNSimulator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = ATNSimulator.h; sourceTree = \"<group>\"; wrapsLines = 0; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; };\n\t\t276E5C291CDB57AA003FF4B4 /* ATNState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ATNState.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C2A1CDB57AA003FF4B4 /* ATNState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNState.h; sourceTree = \"<group>\"; };\n\t\t276E5C2C1CDB57AA003FF4B4 /* ATNType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNType.h; sourceTree = \"<group>\"; };\n\t\t276E5C2D1CDB57AA003FF4B4 /* AtomTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AtomTransition.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C2E1CDB57AA003FF4B4 /* AtomTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AtomTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C301CDB57AA003FF4B4 /* BasicBlockStartState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BasicBlockStartState.h; sourceTree = \"<group>\"; };\n\t\t276E5C321CDB57AA003FF4B4 /* BasicState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BasicState.h; sourceTree = \"<group>\"; };\n\t\t276E5C341CDB57AA003FF4B4 /* BlockEndState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BlockEndState.h; sourceTree = \"<group>\"; };\n\t\t276E5C351CDB57AA003FF4B4 /* BlockStartState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BlockStartState.h; sourceTree = \"<group>\"; };\n\t\t276E5C371CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ContextSensitivityInfo.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C381CDB57AA003FF4B4 /* ContextSensitivityInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ContextSensitivityInfo.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C391CDB57AA003FF4B4 /* DecisionEventInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DecisionEventInfo.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C3A1CDB57AA003FF4B4 /* DecisionEventInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DecisionEventInfo.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C3B1CDB57AA003FF4B4 /* DecisionInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DecisionInfo.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C3C1CDB57AA003FF4B4 /* DecisionInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DecisionInfo.h; sourceTree = \"<group>\"; };\n\t\t276E5C3D1CDB57AA003FF4B4 /* DecisionState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DecisionState.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C3E1CDB57AA003FF4B4 /* DecisionState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DecisionState.h; sourceTree = \"<group>\"; };\n\t\t276E5C411CDB57AA003FF4B4 /* EpsilonTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = EpsilonTransition.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C421CDB57AA003FF4B4 /* EpsilonTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EpsilonTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C431CDB57AA003FF4B4 /* ErrorInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ErrorInfo.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C441CDB57AA003FF4B4 /* ErrorInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ErrorInfo.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C451CDB57AA003FF4B4 /* LexerAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C461CDB57AA003FF4B4 /* LexerActionExecutor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerActionExecutor.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C471CDB57AA003FF4B4 /* LexerActionExecutor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerActionExecutor.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C491CDB57AA003FF4B4 /* LexerActionType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerActionType.h; sourceTree = \"<group>\"; };\n\t\t276E5C4A1CDB57AA003FF4B4 /* LexerATNConfig.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerATNConfig.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C4B1CDB57AA003FF4B4 /* LexerATNConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerATNConfig.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C4C1CDB57AA003FF4B4 /* LexerATNSimulator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerATNSimulator.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C4D1CDB57AA003FF4B4 /* LexerATNSimulator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerATNSimulator.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C4E1CDB57AA003FF4B4 /* LexerChannelAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerChannelAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C4F1CDB57AA003FF4B4 /* LexerChannelAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerChannelAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C501CDB57AA003FF4B4 /* LexerCustomAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerCustomAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C511CDB57AA003FF4B4 /* LexerCustomAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerCustomAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C521CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerIndexedCustomAction.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C531CDB57AA003FF4B4 /* LexerIndexedCustomAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerIndexedCustomAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C541CDB57AA003FF4B4 /* LexerModeAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerModeAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C551CDB57AA003FF4B4 /* LexerModeAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerModeAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C561CDB57AA003FF4B4 /* LexerMoreAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerMoreAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C571CDB57AA003FF4B4 /* LexerMoreAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerMoreAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C581CDB57AA003FF4B4 /* LexerPopModeAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerPopModeAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C591CDB57AA003FF4B4 /* LexerPopModeAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerPopModeAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C5A1CDB57AA003FF4B4 /* LexerPushModeAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerPushModeAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C5B1CDB57AA003FF4B4 /* LexerPushModeAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerPushModeAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C5C1CDB57AA003FF4B4 /* LexerSkipAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerSkipAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C5D1CDB57AA003FF4B4 /* LexerSkipAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerSkipAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C5E1CDB57AA003FF4B4 /* LexerTypeAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerTypeAction.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C5F1CDB57AA003FF4B4 /* LexerTypeAction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerTypeAction.h; sourceTree = \"<group>\"; };\n\t\t276E5C601CDB57AA003FF4B4 /* LL1Analyzer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LL1Analyzer.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C611CDB57AA003FF4B4 /* LL1Analyzer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LL1Analyzer.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C621CDB57AA003FF4B4 /* LookaheadEventInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LookaheadEventInfo.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C631CDB57AA003FF4B4 /* LookaheadEventInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LookaheadEventInfo.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C651CDB57AA003FF4B4 /* LoopEndState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LoopEndState.h; sourceTree = \"<group>\"; };\n\t\t276E5C671CDB57AA003FF4B4 /* NotSetTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = NotSetTransition.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C681CDB57AA003FF4B4 /* NotSetTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NotSetTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C691CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = OrderedATNConfigSet.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C6A1CDB57AA003FF4B4 /* OrderedATNConfigSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OrderedATNConfigSet.h; sourceTree = \"<group>\"; };\n\t\t276E5C6B1CDB57AA003FF4B4 /* ParseInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseInfo.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C6C1CDB57AA003FF4B4 /* ParseInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseInfo.h; sourceTree = \"<group>\"; };\n\t\t276E5C6D1CDB57AA003FF4B4 /* ParserATNSimulator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParserATNSimulator.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C6E1CDB57AA003FF4B4 /* ParserATNSimulator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParserATNSimulator.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C701CDB57AA003FF4B4 /* PlusBlockStartState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlusBlockStartState.h; sourceTree = \"<group>\"; };\n\t\t276E5C721CDB57AA003FF4B4 /* PlusLoopbackState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlusLoopbackState.h; sourceTree = \"<group>\"; };\n\t\t276E5C731CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PrecedencePredicateTransition.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C741CDB57AA003FF4B4 /* PrecedencePredicateTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrecedencePredicateTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C751CDB57AA003FF4B4 /* PredicateEvalInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PredicateEvalInfo.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C761CDB57AA003FF4B4 /* PredicateEvalInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredicateEvalInfo.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C771CDB57AA003FF4B4 /* PredicateTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PredicateTransition.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C781CDB57AA003FF4B4 /* PredicateTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredicateTransition.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C791CDB57AA003FF4B4 /* PredictionContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PredictionContext.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C7A1CDB57AA003FF4B4 /* PredictionContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredictionContext.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C7B1CDB57AA003FF4B4 /* PredictionMode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PredictionMode.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C7C1CDB57AA003FF4B4 /* PredictionMode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredictionMode.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C7D1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ProfilingATNSimulator.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C7E1CDB57AA003FF4B4 /* ProfilingATNSimulator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ProfilingATNSimulator.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C7F1CDB57AA003FF4B4 /* RangeTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RangeTransition.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C801CDB57AA003FF4B4 /* RangeTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RangeTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C821CDB57AA003FF4B4 /* RuleStartState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleStartState.h; sourceTree = \"<group>\"; };\n\t\t276E5C841CDB57AA003FF4B4 /* RuleStopState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleStopState.h; sourceTree = \"<group>\"; };\n\t\t276E5C851CDB57AA003FF4B4 /* RuleTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RuleTransition.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C861CDB57AA003FF4B4 /* RuleTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C871CDB57AA003FF4B4 /* SemanticContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SemanticContext.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C881CDB57AA003FF4B4 /* SemanticContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SemanticContext.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C891CDB57AA003FF4B4 /* SetTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SetTransition.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C8A1CDB57AA003FF4B4 /* SetTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SetTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C8B1CDB57AA003FF4B4 /* SingletonPredictionContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SingletonPredictionContext.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C8C1CDB57AA003FF4B4 /* SingletonPredictionContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SingletonPredictionContext.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C8E1CDB57AA003FF4B4 /* StarBlockStartState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StarBlockStartState.h; sourceTree = \"<group>\"; };\n\t\t276E5C8F1CDB57AA003FF4B4 /* StarLoopbackState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StarLoopbackState.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C901CDB57AA003FF4B4 /* StarLoopbackState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StarLoopbackState.h; sourceTree = \"<group>\"; };\n\t\t276E5C921CDB57AA003FF4B4 /* StarLoopEntryState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StarLoopEntryState.h; sourceTree = \"<group>\"; };\n\t\t276E5C941CDB57AA003FF4B4 /* TokensStartState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TokensStartState.h; sourceTree = \"<group>\"; };\n\t\t276E5C951CDB57AA003FF4B4 /* Transition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Transition.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C961CDB57AA003FF4B4 /* Transition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Transition.h; sourceTree = \"<group>\"; };\n\t\t276E5C971CDB57AA003FF4B4 /* WildcardTransition.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WildcardTransition.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C981CDB57AA003FF4B4 /* WildcardTransition.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WildcardTransition.h; sourceTree = \"<group>\"; };\n\t\t276E5C991CDB57AA003FF4B4 /* BailErrorStrategy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BailErrorStrategy.cpp; sourceTree = \"<group>\"; };\n\t\t276E5C9A1CDB57AA003FF4B4 /* BailErrorStrategy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BailErrorStrategy.h; sourceTree = \"<group>\"; };\n\t\t276E5C9B1CDB57AA003FF4B4 /* BaseErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BaseErrorListener.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C9C1CDB57AA003FF4B4 /* BaseErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BaseErrorListener.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5C9D1CDB57AA003FF4B4 /* BufferedTokenStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; lineEnding = 0; path = BufferedTokenStream.cpp; sourceTree = \"<group>\"; xcLanguageSpecificationIdentifier = xcode.lang.cpp; };\n\t\t276E5C9E1CDB57AA003FF4B4 /* BufferedTokenStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = BufferedTokenStream.h; sourceTree = \"<group>\"; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; };\n\t\t276E5C9F1CDB57AA003FF4B4 /* CharStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CharStream.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CA01CDB57AA003FF4B4 /* CharStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CharStream.h; sourceTree = \"<group>\"; };\n\t\t276E5CA11CDB57AA003FF4B4 /* CommonToken.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CommonToken.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CA21CDB57AA003FF4B4 /* CommonToken.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonToken.h; sourceTree = \"<group>\"; };\n\t\t276E5CA31CDB57AA003FF4B4 /* CommonTokenFactory.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CommonTokenFactory.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CA41CDB57AA003FF4B4 /* CommonTokenFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonTokenFactory.h; sourceTree = \"<group>\"; };\n\t\t276E5CA51CDB57AA003FF4B4 /* CommonTokenStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CommonTokenStream.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CA61CDB57AA003FF4B4 /* CommonTokenStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonTokenStream.h; sourceTree = \"<group>\"; };\n\t\t276E5CA71CDB57AA003FF4B4 /* ConsoleErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ConsoleErrorListener.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CA81CDB57AA003FF4B4 /* ConsoleErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ConsoleErrorListener.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CA91CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DefaultErrorStrategy.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CAA1CDB57AA003FF4B4 /* DefaultErrorStrategy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DefaultErrorStrategy.h; sourceTree = \"<group>\"; };\n\t\t276E5CAC1CDB57AA003FF4B4 /* DFA.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DFA.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CAD1CDB57AA003FF4B4 /* DFA.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DFA.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CAE1CDB57AA003FF4B4 /* DFASerializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DFASerializer.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CAF1CDB57AA003FF4B4 /* DFASerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DFASerializer.h; sourceTree = \"<group>\"; };\n\t\t276E5CB01CDB57AA003FF4B4 /* DFAState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DFAState.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CB11CDB57AA003FF4B4 /* DFAState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DFAState.h; sourceTree = \"<group>\"; };\n\t\t276E5CB21CDB57AA003FF4B4 /* LexerDFASerializer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerDFASerializer.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CB31CDB57AA003FF4B4 /* LexerDFASerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerDFASerializer.h; sourceTree = \"<group>\"; };\n\t\t276E5CB41CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DiagnosticErrorListener.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CB51CDB57AA003FF4B4 /* DiagnosticErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DiagnosticErrorListener.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CB61CDB57AA003FF4B4 /* Exceptions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Exceptions.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CB71CDB57AA003FF4B4 /* Exceptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Exceptions.h; sourceTree = \"<group>\"; };\n\t\t276E5CB81CDB57AA003FF4B4 /* FailedPredicateException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FailedPredicateException.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CB91CDB57AA003FF4B4 /* FailedPredicateException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FailedPredicateException.h; sourceTree = \"<group>\"; };\n\t\t276E5CBA1CDB57AA003FF4B4 /* InputMismatchException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InputMismatchException.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CBB1CDB57AA003FF4B4 /* InputMismatchException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InputMismatchException.h; sourceTree = \"<group>\"; };\n\t\t276E5CBC1CDB57AA003FF4B4 /* InterpreterRuleContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InterpreterRuleContext.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CBD1CDB57AA003FF4B4 /* InterpreterRuleContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InterpreterRuleContext.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CBE1CDB57AA003FF4B4 /* IntStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IntStream.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CBF1CDB57AA003FF4B4 /* IntStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IntStream.h; sourceTree = \"<group>\"; };\n\t\t276E5CC11CDB57AA003FF4B4 /* Lexer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Lexer.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CC21CDB57AA003FF4B4 /* Lexer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Lexer.h; sourceTree = \"<group>\"; };\n\t\t276E5CC31CDB57AA003FF4B4 /* LexerInterpreter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerInterpreter.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CC41CDB57AA003FF4B4 /* LexerInterpreter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerInterpreter.h; sourceTree = \"<group>\"; };\n\t\t276E5CC51CDB57AA003FF4B4 /* LexerNoViableAltException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerNoViableAltException.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CC61CDB57AA003FF4B4 /* LexerNoViableAltException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LexerNoViableAltException.h; sourceTree = \"<group>\"; };\n\t\t276E5CC71CDB57AA003FF4B4 /* ListTokenSource.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ListTokenSource.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CC81CDB57AA003FF4B4 /* ListTokenSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ListTokenSource.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CCA1CDB57AA003FF4B4 /* Interval.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Interval.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CCB1CDB57AA003FF4B4 /* Interval.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Interval.h; sourceTree = \"<group>\"; };\n\t\t276E5CCC1CDB57AA003FF4B4 /* IntervalSet.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IntervalSet.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CCD1CDB57AA003FF4B4 /* IntervalSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IntervalSet.h; sourceTree = \"<group>\"; };\n\t\t276E5CCE1CDB57AA003FF4B4 /* MurmurHash.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MurmurHash.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CCF1CDB57AA003FF4B4 /* MurmurHash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MurmurHash.h; sourceTree = \"<group>\"; };\n\t\t276E5CD11CDB57AA003FF4B4 /* Predicate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Predicate.h; sourceTree = \"<group>\"; };\n\t\t276E5CD41CDB57AA003FF4B4 /* NoViableAltException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = NoViableAltException.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CD51CDB57AA003FF4B4 /* NoViableAltException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NoViableAltException.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CD61CDB57AA003FF4B4 /* Parser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Parser.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CD71CDB57AA003FF4B4 /* Parser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Parser.h; sourceTree = \"<group>\"; };\n\t\t276E5CD81CDB57AA003FF4B4 /* ParserInterpreter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParserInterpreter.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CD91CDB57AA003FF4B4 /* ParserInterpreter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParserInterpreter.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CDA1CDB57AA003FF4B4 /* ParserRuleContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParserRuleContext.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CDB1CDB57AA003FF4B4 /* ParserRuleContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParserRuleContext.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CDC1CDB57AA003FF4B4 /* ProxyErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ProxyErrorListener.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CDD1CDB57AA003FF4B4 /* ProxyErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ProxyErrorListener.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CDE1CDB57AA003FF4B4 /* RecognitionException.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RecognitionException.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CDF1CDB57AA003FF4B4 /* RecognitionException.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RecognitionException.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CE01CDB57AA003FF4B4 /* Recognizer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Recognizer.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CE11CDB57AA003FF4B4 /* Recognizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Recognizer.h; sourceTree = \"<group>\"; };\n\t\t276E5CE21CDB57AA003FF4B4 /* RuleContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RuleContext.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CE31CDB57AA003FF4B4 /* RuleContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleContext.h; sourceTree = \"<group>\"; };\n\t\t276E5CE51CDB57AA003FF4B4 /* Arrays.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Arrays.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CE61CDB57AA003FF4B4 /* Arrays.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Arrays.h; sourceTree = \"<group>\"; };\n\t\t276E5CE71CDB57AA003FF4B4 /* BitSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BitSet.h; sourceTree = \"<group>\"; };\n\t\t276E5CE81CDB57AA003FF4B4 /* CPPUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CPPUtils.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CE91CDB57AA003FF4B4 /* CPPUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = CPPUtils.h; sourceTree = \"<group>\"; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; };\n\t\t276E5CEA1CDB57AA003FF4B4 /* Declarations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Declarations.h; sourceTree = \"<group>\"; };\n\t\t276E5CED1CDB57AA003FF4B4 /* StringUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StringUtils.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CEE1CDB57AA003FF4B4 /* StringUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StringUtils.h; sourceTree = \"<group>\"; };\n\t\t276E5CF01CDB57AA003FF4B4 /* Token.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Token.h; sourceTree = \"<group>\"; };\n\t\t276E5CF21CDB57AA003FF4B4 /* TokenFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TokenFactory.h; sourceTree = \"<group>\"; };\n\t\t276E5CF41CDB57AA003FF4B4 /* TokenSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TokenSource.h; sourceTree = \"<group>\"; };\n\t\t276E5CF51CDB57AA003FF4B4 /* TokenStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TokenStream.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CF61CDB57AA003FF4B4 /* TokenStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TokenStream.h; sourceTree = \"<group>\"; };\n\t\t276E5CF71CDB57AA003FF4B4 /* TokenStreamRewriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TokenStreamRewriter.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CF81CDB57AA003FF4B4 /* TokenStreamRewriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TokenStreamRewriter.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5CFA1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AbstractParseTreeVisitor.h; sourceTree = \"<group>\"; };\n\t\t276E5CFB1CDB57AA003FF4B4 /* ErrorNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ErrorNode.h; sourceTree = \"<group>\"; };\n\t\t276E5CFC1CDB57AA003FF4B4 /* ErrorNodeImpl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ErrorNodeImpl.cpp; sourceTree = \"<group>\"; };\n\t\t276E5CFD1CDB57AA003FF4B4 /* ErrorNodeImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ErrorNodeImpl.h; sourceTree = \"<group>\"; };\n\t\t276E5CFE1CDB57AA003FF4B4 /* ParseTree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTree.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D001CDB57AA003FF4B4 /* ParseTreeListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTreeListener.h; sourceTree = \"<group>\"; };\n\t\t276E5D021CDB57AA003FF4B4 /* ParseTreeProperty.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTreeProperty.h; sourceTree = \"<group>\"; };\n\t\t276E5D031CDB57AA003FF4B4 /* ParseTreeVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTreeVisitor.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D041CDB57AA003FF4B4 /* ParseTreeWalker.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseTreeWalker.cpp; sourceTree = \"<group>\"; };\n\t\t276E5D051CDB57AA003FF4B4 /* ParseTreeWalker.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTreeWalker.h; sourceTree = \"<group>\"; };\n\t\t276E5D071CDB57AA003FF4B4 /* Chunk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Chunk.h; sourceTree = \"<group>\"; };\n\t\t276E5D081CDB57AA003FF4B4 /* ParseTreeMatch.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseTreeMatch.cpp; sourceTree = \"<group>\"; };\n\t\t276E5D091CDB57AA003FF4B4 /* ParseTreeMatch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTreeMatch.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D0A1CDB57AA003FF4B4 /* ParseTreePattern.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseTreePattern.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D0B1CDB57AA003FF4B4 /* ParseTreePattern.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTreePattern.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D0C1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseTreePatternMatcher.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D0D1CDB57AA003FF4B4 /* ParseTreePatternMatcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParseTreePatternMatcher.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D0E1CDB57AA003FF4B4 /* RuleTagToken.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RuleTagToken.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D0F1CDB57AA003FF4B4 /* RuleTagToken.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleTagToken.h; sourceTree = \"<group>\"; };\n\t\t276E5D101CDB57AA003FF4B4 /* TagChunk.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TagChunk.cpp; sourceTree = \"<group>\"; };\n\t\t276E5D111CDB57AA003FF4B4 /* TagChunk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TagChunk.h; sourceTree = \"<group>\"; };\n\t\t276E5D121CDB57AA003FF4B4 /* TextChunk.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TextChunk.cpp; sourceTree = \"<group>\"; };\n\t\t276E5D131CDB57AA003FF4B4 /* TextChunk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TextChunk.h; sourceTree = \"<group>\"; };\n\t\t276E5D141CDB57AA003FF4B4 /* TokenTagToken.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TokenTagToken.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D151CDB57AA003FF4B4 /* TokenTagToken.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TokenTagToken.h; sourceTree = \"<group>\"; };\n\t\t276E5D181CDB57AA003FF4B4 /* TerminalNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TerminalNode.h; sourceTree = \"<group>\"; };\n\t\t276E5D191CDB57AA003FF4B4 /* TerminalNodeImpl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TerminalNodeImpl.cpp; sourceTree = \"<group>\"; };\n\t\t276E5D1A1CDB57AA003FF4B4 /* TerminalNodeImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TerminalNodeImpl.h; sourceTree = \"<group>\"; };\n\t\t276E5D1D1CDB57AA003FF4B4 /* Trees.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Trees.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D1E1CDB57AA003FF4B4 /* Trees.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Trees.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D221CDB57AA003FF4B4 /* UnbufferedCharStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UnbufferedCharStream.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D231CDB57AA003FF4B4 /* UnbufferedCharStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UnbufferedCharStream.h; sourceTree = \"<group>\"; };\n\t\t276E5D241CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UnbufferedTokenStream.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D251CDB57AA003FF4B4 /* UnbufferedTokenStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UnbufferedTokenStream.h; sourceTree = \"<group>\"; };\n\t\t276E5D271CDB57AA003FF4B4 /* Vocabulary.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Vocabulary.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t276E5D281CDB57AA003FF4B4 /* Vocabulary.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Vocabulary.h; sourceTree = \"<group>\"; };\n\t\t276E5D2A1CDB57AA003FF4B4 /* WritableToken.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WritableToken.h; sourceTree = \"<group>\"; };\n\t\t27745EFB1CE49C000067C6A3 /* RuntimeMetaData.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RuntimeMetaData.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27745EFC1CE49C000067C6A3 /* RuntimeMetaData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuntimeMetaData.h; sourceTree = \"<group>\"; };\n\t\t27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; };\n\t\t2793DC841F08083F00A84290 /* TokenSource.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TokenSource.cpp; sourceTree = \"<group>\"; };\n\t\t2793DC881F08087500A84290 /* Chunk.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Chunk.cpp; sourceTree = \"<group>\"; };\n\t\t2793DC8C1F08088F00A84290 /* ParseTreeListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseTreeListener.cpp; sourceTree = \"<group>\"; };\n\t\t2793DC951F0808E100A84290 /* ParseTreeVisitor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ParseTreeVisitor.cpp; sourceTree = \"<group>\"; };\n\t\t2793DC9C1F08090D00A84290 /* Any.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Any.cpp; sourceTree = \"<group>\"; };\n\t\t2793DCA01F08095F00A84290 /* ANTLRErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ANTLRErrorListener.cpp; sourceTree = \"<group>\"; };\n\t\t2793DCA11F08095F00A84290 /* ANTLRErrorStrategy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ANTLRErrorStrategy.cpp; sourceTree = \"<group>\"; };\n\t\t2793DCA21F08095F00A84290 /* Token.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Token.cpp; sourceTree = \"<group>\"; };\n\t\t2793DCA31F08095F00A84290 /* WritableToken.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WritableToken.cpp; sourceTree = \"<group>\"; };\n\t\t2793DCB11F08099C00A84290 /* LexerAction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LexerAction.cpp; sourceTree = \"<group>\"; };\n\t\t2794D8551CE7821B00FADD0F /* antlr4-common.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = \"antlr4-common.h\"; sourceTree = \"<group>\"; };\n\t\t27AC52CF1CE773A80093AAAB /* antlr4-runtime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = \"antlr4-runtime.h\"; sourceTree = \"<group>\"; };\n\t\t27B36AC41DACE7AF0069C868 /* RuleContextWithAltNum.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RuleContextWithAltNum.cpp; sourceTree = \"<group>\"; };\n\t\t27B36AC51DACE7AF0069C868 /* RuleContextWithAltNum.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuleContextWithAltNum.h; sourceTree = \"<group>\"; };\n\t\t27C375821EA1059C00B5883C /* InterpreterDataReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = InterpreterDataReader.cpp; sourceTree = \"<group>\"; };\n\t\t27C375831EA1059C00B5883C /* InterpreterDataReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InterpreterDataReader.h; sourceTree = \"<group>\"; };\n\t\t27D414501DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = IterativeParseTreeWalker.cpp; sourceTree = \"<group>\"; };\n\t\t27D414511DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IterativeParseTreeWalker.h; sourceTree = \"<group>\"; };\n\t\t27DB448B1D045537007E790B /* XPath.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPath.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB448C1D045537007E790B /* XPath.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPath.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB448D1D045537007E790B /* XPathElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathElement.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB448E1D045537007E790B /* XPathElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathElement.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB448F1D045537007E790B /* XPathLexerErrorListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathLexerErrorListener.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44901D045537007E790B /* XPathLexerErrorListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathLexerErrorListener.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44911D045537007E790B /* XPathRuleAnywhereElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathRuleAnywhereElement.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44921D045537007E790B /* XPathRuleAnywhereElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathRuleAnywhereElement.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44931D045537007E790B /* XPathRuleElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathRuleElement.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44941D045537007E790B /* XPathRuleElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathRuleElement.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44951D045537007E790B /* XPathTokenAnywhereElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathTokenAnywhereElement.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44961D045537007E790B /* XPathTokenAnywhereElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathTokenAnywhereElement.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44971D045537007E790B /* XPathTokenElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathTokenElement.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44981D045537007E790B /* XPathTokenElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathTokenElement.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44991D045537007E790B /* XPathWildcardAnywhereElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathWildcardAnywhereElement.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB449A1D045537007E790B /* XPathWildcardAnywhereElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathWildcardAnywhereElement.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB449B1D045537007E790B /* XPathWildcardElement.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathWildcardElement.cpp; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB449C1D045537007E790B /* XPathWildcardElement.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathWildcardElement.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27DB44AF1D0463CC007E790B /* XPathLexer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPathLexer.cpp; sourceTree = \"<group>\"; };\n\t\t27DB44B01D0463CC007E790B /* XPathLexer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XPathLexer.h; sourceTree = \"<group>\"; wrapsLines = 0; };\n\t\t27F4A8551D4CEB2A00E067EE /* Any.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Any.h; sourceTree = \"<group>\"; };\n\t\t37C147171B4D5A04008EDDDB /* libantlr4-runtime.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = \"libantlr4-runtime.a\"; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t37D727AA1867AF1E007B6D10 /* libantlr4-runtime.dylib */ = {isa = PBXFileReference; explicitFileType = \"compiled.mach-o.dylib\"; includeInIndex = 0; path = \"libantlr4-runtime.dylib\"; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t9B25DC9F2910249100DF9703 /* FlatHashSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FlatHashSet.h; sourceTree = \"<group>\"; };\n\t\t9B25DCA02910249100DF9703 /* FlatHashMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FlatHashMap.h; sourceTree = \"<group>\"; };\n\t\t9B25DCA72910252800DF9703 /* Version.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Version.h; sourceTree = \"<group>\"; };\n\t\t9B25DCAB291025B700DF9703 /* ATNStateType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ATNStateType.h; sourceTree = \"<group>\"; };\n\t\t9B25DCAF291026DE00DF9703 /* ParserATNSimulatorOptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ParserATNSimulatorOptions.h; sourceTree = \"<group>\"; };\n\t\t9B25DCB32910278000DF9703 /* PredictionContextCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredictionContextCache.h; sourceTree = \"<group>\"; };\n\t\t9B25DCB42910278000DF9703 /* PredictionContextMergeCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredictionContextMergeCache.h; sourceTree = \"<group>\"; };\n\t\t9B25DCB52910278000DF9703 /* PredictionContextType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredictionContextType.h; sourceTree = \"<group>\"; };\n\t\t9B25DCB62910278000DF9703 /* PredictionContextCache.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PredictionContextCache.cpp; sourceTree = \"<group>\"; };\n\t\t9B25DCB72910278000DF9703 /* PredictionContextMergeCacheOptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PredictionContextMergeCacheOptions.h; sourceTree = \"<group>\"; };\n\t\t9B25DCB82910278000DF9703 /* PredictionContextMergeCache.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PredictionContextMergeCache.cpp; sourceTree = \"<group>\"; };\n\t\t9B25DCCB291027ED00DF9703 /* SemanticContextType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SemanticContextType.h; sourceTree = \"<group>\"; };\n\t\t9B25DCCC291027EE00DF9703 /* SerializedATNView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SerializedATNView.h; sourceTree = \"<group>\"; };\n\t\t9B25DCD32910282B00DF9703 /* TransitionType.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TransitionType.cpp; sourceTree = \"<group>\"; };\n\t\t9B25DCD42910282B00DF9703 /* TransitionType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TransitionType.h; sourceTree = \"<group>\"; };\n\t\t9B25DCDC2910287000DF9703 /* Synchronization.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Synchronization.cpp; sourceTree = \"<group>\"; };\n\t\t9B25DCDD2910287000DF9703 /* Synchronization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Synchronization.h; sourceTree = \"<group>\"; };\n\t\t9B25DCE4291028BC00DF9703 /* Casts.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Casts.h; sourceTree = \"<group>\"; };\n\t\t9B25DCE8291028D000DF9703 /* Unicode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Unicode.h; sourceTree = \"<group>\"; };\n\t\t9B25DCE9291028D000DF9703 /* Utf8.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Utf8.h; sourceTree = \"<group>\"; };\n\t\t9B25DCEA291028D000DF9703 /* Utf8.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Utf8.cpp; sourceTree = \"<group>\"; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\t270C67EC1CDB4F1E00116E17 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37C147141B4D5A04008EDDDB /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t27874F1E1CCB7A0700AF1C53 /* CoreFoundation.framework in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37D727A71867AF1E007B6D10 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t27874F211CCB7B1700AF1C53 /* CoreFoundation.framework in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t270C67F11CDB4F1E00116E17 /* antlrcpp-ios */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t270C67F21CDB4F1E00116E17 /* antlrcpp_ios.h */,\n\t\t\t\t270C67F41CDB4F1E00116E17 /* Info.plist */,\n\t\t\t);\n\t\t\tpath = \"antlrcpp-ios\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t276E5C0A1CDB57AA003FF4B4 /* runtime */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t276E5C121CDB57AA003FF4B4 /* atn */,\n\t\t\t\t276E5CAB1CDB57AA003FF4B4 /* dfa */,\n\t\t\t\t9B25DCDB2910287000DF9703 /* internal */,\n\t\t\t\t276E5CC91CDB57AA003FF4B4 /* misc */,\n\t\t\t\t276E5CE41CDB57AA003FF4B4 /* support */,\n\t\t\t\t276E5CF91CDB57AA003FF4B4 /* tree */,\n\t\t\t\t2794D8551CE7821B00FADD0F /* antlr4-common.h */,\n\t\t\t\t27AC52CF1CE773A80093AAAB /* antlr4-runtime.h */,\n\t\t\t\t2793DCA01F08095F00A84290 /* ANTLRErrorListener.cpp */,\n\t\t\t\t276E5C0C1CDB57AA003FF4B4 /* ANTLRErrorListener.h */,\n\t\t\t\t2793DCA11F08095F00A84290 /* ANTLRErrorStrategy.cpp */,\n\t\t\t\t276E5C0D1CDB57AA003FF4B4 /* ANTLRErrorStrategy.h */,\n\t\t\t\t276E5C0E1CDB57AA003FF4B4 /* ANTLRFileStream.cpp */,\n\t\t\t\t276E5C0F1CDB57AA003FF4B4 /* ANTLRFileStream.h */,\n\t\t\t\t276E5C101CDB57AA003FF4B4 /* ANTLRInputStream.cpp */,\n\t\t\t\t276E5C111CDB57AA003FF4B4 /* ANTLRInputStream.h */,\n\t\t\t\t276E5C991CDB57AA003FF4B4 /* BailErrorStrategy.cpp */,\n\t\t\t\t276E5C9A1CDB57AA003FF4B4 /* BailErrorStrategy.h */,\n\t\t\t\t276E5C9B1CDB57AA003FF4B4 /* BaseErrorListener.cpp */,\n\t\t\t\t276E5C9C1CDB57AA003FF4B4 /* BaseErrorListener.h */,\n\t\t\t\t276E5C9D1CDB57AA003FF4B4 /* BufferedTokenStream.cpp */,\n\t\t\t\t276E5C9E1CDB57AA003FF4B4 /* BufferedTokenStream.h */,\n\t\t\t\t276E5C9F1CDB57AA003FF4B4 /* CharStream.cpp */,\n\t\t\t\t276E5CA01CDB57AA003FF4B4 /* CharStream.h */,\n\t\t\t\t276E5CA11CDB57AA003FF4B4 /* CommonToken.cpp */,\n\t\t\t\t276E5CA21CDB57AA003FF4B4 /* CommonToken.h */,\n\t\t\t\t276E5CA31CDB57AA003FF4B4 /* CommonTokenFactory.cpp */,\n\t\t\t\t276E5CA41CDB57AA003FF4B4 /* CommonTokenFactory.h */,\n\t\t\t\t276E5CA51CDB57AA003FF4B4 /* CommonTokenStream.cpp */,\n\t\t\t\t276E5CA61CDB57AA003FF4B4 /* CommonTokenStream.h */,\n\t\t\t\t276E5CA71CDB57AA003FF4B4 /* ConsoleErrorListener.cpp */,\n\t\t\t\t276E5CA81CDB57AA003FF4B4 /* ConsoleErrorListener.h */,\n\t\t\t\t276E5CA91CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp */,\n\t\t\t\t276E5CAA1CDB57AA003FF4B4 /* DefaultErrorStrategy.h */,\n\t\t\t\t276E5CB41CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp */,\n\t\t\t\t276E5CB51CDB57AA003FF4B4 /* DiagnosticErrorListener.h */,\n\t\t\t\t276E5CB61CDB57AA003FF4B4 /* Exceptions.cpp */,\n\t\t\t\t276E5CB71CDB57AA003FF4B4 /* Exceptions.h */,\n\t\t\t\t276E5CB81CDB57AA003FF4B4 /* FailedPredicateException.cpp */,\n\t\t\t\t276E5CB91CDB57AA003FF4B4 /* FailedPredicateException.h */,\n\t\t\t\t9B25DCA02910249100DF9703 /* FlatHashMap.h */,\n\t\t\t\t9B25DC9F2910249100DF9703 /* FlatHashSet.h */,\n\t\t\t\t276E5CBA1CDB57AA003FF4B4 /* InputMismatchException.cpp */,\n\t\t\t\t276E5CBB1CDB57AA003FF4B4 /* InputMismatchException.h */,\n\t\t\t\t276E5CBC1CDB57AA003FF4B4 /* InterpreterRuleContext.cpp */,\n\t\t\t\t276E5CBD1CDB57AA003FF4B4 /* InterpreterRuleContext.h */,\n\t\t\t\t276E5CBE1CDB57AA003FF4B4 /* IntStream.cpp */,\n\t\t\t\t276E5CBF1CDB57AA003FF4B4 /* IntStream.h */,\n\t\t\t\t276E5CC11CDB57AA003FF4B4 /* Lexer.cpp */,\n\t\t\t\t276E5CC21CDB57AA003FF4B4 /* Lexer.h */,\n\t\t\t\t276E5CC31CDB57AA003FF4B4 /* LexerInterpreter.cpp */,\n\t\t\t\t276E5CC41CDB57AA003FF4B4 /* LexerInterpreter.h */,\n\t\t\t\t276E5CC51CDB57AA003FF4B4 /* LexerNoViableAltException.cpp */,\n\t\t\t\t276E5CC61CDB57AA003FF4B4 /* LexerNoViableAltException.h */,\n\t\t\t\t276E5CC71CDB57AA003FF4B4 /* ListTokenSource.cpp */,\n\t\t\t\t276E5CC81CDB57AA003FF4B4 /* ListTokenSource.h */,\n\t\t\t\t276E5CD41CDB57AA003FF4B4 /* NoViableAltException.cpp */,\n\t\t\t\t276E5CD51CDB57AA003FF4B4 /* NoViableAltException.h */,\n\t\t\t\t276E5CD61CDB57AA003FF4B4 /* Parser.cpp */,\n\t\t\t\t276E5CD71CDB57AA003FF4B4 /* Parser.h */,\n\t\t\t\t276E5CD81CDB57AA003FF4B4 /* ParserInterpreter.cpp */,\n\t\t\t\t276E5CD91CDB57AA003FF4B4 /* ParserInterpreter.h */,\n\t\t\t\t276E5CDA1CDB57AA003FF4B4 /* ParserRuleContext.cpp */,\n\t\t\t\t276E5CDB1CDB57AA003FF4B4 /* ParserRuleContext.h */,\n\t\t\t\t276E5CDC1CDB57AA003FF4B4 /* ProxyErrorListener.cpp */,\n\t\t\t\t276E5CDD1CDB57AA003FF4B4 /* ProxyErrorListener.h */,\n\t\t\t\t276E5CDE1CDB57AA003FF4B4 /* RecognitionException.cpp */,\n\t\t\t\t276E5CDF1CDB57AA003FF4B4 /* RecognitionException.h */,\n\t\t\t\t276E5CE01CDB57AA003FF4B4 /* Recognizer.cpp */,\n\t\t\t\t276E5CE11CDB57AA003FF4B4 /* Recognizer.h */,\n\t\t\t\t276E5CE21CDB57AA003FF4B4 /* RuleContext.cpp */,\n\t\t\t\t276E5CE31CDB57AA003FF4B4 /* RuleContext.h */,\n\t\t\t\t27B36AC41DACE7AF0069C868 /* RuleContextWithAltNum.cpp */,\n\t\t\t\t27B36AC51DACE7AF0069C868 /* RuleContextWithAltNum.h */,\n\t\t\t\t27745EFB1CE49C000067C6A3 /* RuntimeMetaData.cpp */,\n\t\t\t\t27745EFC1CE49C000067C6A3 /* RuntimeMetaData.h */,\n\t\t\t\t2793DCA21F08095F00A84290 /* Token.cpp */,\n\t\t\t\t276E5CF01CDB57AA003FF4B4 /* Token.h */,\n\t\t\t\t276E5CF21CDB57AA003FF4B4 /* TokenFactory.h */,\n\t\t\t\t2793DC841F08083F00A84290 /* TokenSource.cpp */,\n\t\t\t\t276E5CF41CDB57AA003FF4B4 /* TokenSource.h */,\n\t\t\t\t276E5CF51CDB57AA003FF4B4 /* TokenStream.cpp */,\n\t\t\t\t276E5CF61CDB57AA003FF4B4 /* TokenStream.h */,\n\t\t\t\t276E5CF71CDB57AA003FF4B4 /* TokenStreamRewriter.cpp */,\n\t\t\t\t276E5CF81CDB57AA003FF4B4 /* TokenStreamRewriter.h */,\n\t\t\t\t276E5D221CDB57AA003FF4B4 /* UnbufferedCharStream.cpp */,\n\t\t\t\t276E5D231CDB57AA003FF4B4 /* UnbufferedCharStream.h */,\n\t\t\t\t276E5D241CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp */,\n\t\t\t\t276E5D251CDB57AA003FF4B4 /* UnbufferedTokenStream.h */,\n\t\t\t\t9B25DCA72910252800DF9703 /* Version.h */,\n\t\t\t\t276E5D271CDB57AA003FF4B4 /* Vocabulary.cpp */,\n\t\t\t\t276E5D281CDB57AA003FF4B4 /* Vocabulary.h */,\n\t\t\t\t2793DCA31F08095F00A84290 /* WritableToken.cpp */,\n\t\t\t\t276E5D2A1CDB57AA003FF4B4 /* WritableToken.h */,\n\t\t\t);\n\t\t\tname = runtime;\n\t\t\tpath = src;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t276E5C121CDB57AA003FF4B4 /* atn */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t276E5C151CDB57AA003FF4B4 /* ActionTransition.cpp */,\n\t\t\t\t276E5C161CDB57AA003FF4B4 /* ActionTransition.h */,\n\t\t\t\t276E5C171CDB57AA003FF4B4 /* AmbiguityInfo.cpp */,\n\t\t\t\t276E5C181CDB57AA003FF4B4 /* AmbiguityInfo.h */,\n\t\t\t\t276E5C191CDB57AA003FF4B4 /* ArrayPredictionContext.cpp */,\n\t\t\t\t276E5C1A1CDB57AA003FF4B4 /* ArrayPredictionContext.h */,\n\t\t\t\t276E5C1B1CDB57AA003FF4B4 /* ATN.cpp */,\n\t\t\t\t276E5C1C1CDB57AA003FF4B4 /* ATN.h */,\n\t\t\t\t276E5C1D1CDB57AA003FF4B4 /* ATNConfig.cpp */,\n\t\t\t\t276E5C1E1CDB57AA003FF4B4 /* ATNConfig.h */,\n\t\t\t\t276E5C1F1CDB57AA003FF4B4 /* ATNConfigSet.cpp */,\n\t\t\t\t276E5C201CDB57AA003FF4B4 /* ATNConfigSet.h */,\n\t\t\t\t276E5C211CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp */,\n\t\t\t\t276E5C221CDB57AA003FF4B4 /* ATNDeserializationOptions.h */,\n\t\t\t\t276E5C231CDB57AA003FF4B4 /* ATNDeserializer.cpp */,\n\t\t\t\t276E5C241CDB57AA003FF4B4 /* ATNDeserializer.h */,\n\t\t\t\t276E5C271CDB57AA003FF4B4 /* ATNSimulator.cpp */,\n\t\t\t\t276E5C281CDB57AA003FF4B4 /* ATNSimulator.h */,\n\t\t\t\t276E5C291CDB57AA003FF4B4 /* ATNState.cpp */,\n\t\t\t\t276E5C2A1CDB57AA003FF4B4 /* ATNState.h */,\n\t\t\t\t9B25DCAB291025B700DF9703 /* ATNStateType.h */,\n\t\t\t\t276E5C2C1CDB57AA003FF4B4 /* ATNType.h */,\n\t\t\t\t276E5C2D1CDB57AA003FF4B4 /* AtomTransition.cpp */,\n\t\t\t\t276E5C2E1CDB57AA003FF4B4 /* AtomTransition.h */,\n\t\t\t\t276E5C301CDB57AA003FF4B4 /* BasicBlockStartState.h */,\n\t\t\t\t276E5C321CDB57AA003FF4B4 /* BasicState.h */,\n\t\t\t\t276E5C341CDB57AA003FF4B4 /* BlockEndState.h */,\n\t\t\t\t276E5C351CDB57AA003FF4B4 /* BlockStartState.h */,\n\t\t\t\t276E5C371CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp */,\n\t\t\t\t276E5C381CDB57AA003FF4B4 /* ContextSensitivityInfo.h */,\n\t\t\t\t276E5C391CDB57AA003FF4B4 /* DecisionEventInfo.cpp */,\n\t\t\t\t276E5C3A1CDB57AA003FF4B4 /* DecisionEventInfo.h */,\n\t\t\t\t276E5C3B1CDB57AA003FF4B4 /* DecisionInfo.cpp */,\n\t\t\t\t276E5C3C1CDB57AA003FF4B4 /* DecisionInfo.h */,\n\t\t\t\t276E5C3D1CDB57AA003FF4B4 /* DecisionState.cpp */,\n\t\t\t\t276E5C3E1CDB57AA003FF4B4 /* DecisionState.h */,\n\t\t\t\t276E5C411CDB57AA003FF4B4 /* EpsilonTransition.cpp */,\n\t\t\t\t276E5C421CDB57AA003FF4B4 /* EpsilonTransition.h */,\n\t\t\t\t276E5C431CDB57AA003FF4B4 /* ErrorInfo.cpp */,\n\t\t\t\t276E5C441CDB57AA003FF4B4 /* ErrorInfo.h */,\n\t\t\t\t2793DCB11F08099C00A84290 /* LexerAction.cpp */,\n\t\t\t\t276E5C451CDB57AA003FF4B4 /* LexerAction.h */,\n\t\t\t\t276E5C461CDB57AA003FF4B4 /* LexerActionExecutor.cpp */,\n\t\t\t\t276E5C471CDB57AA003FF4B4 /* LexerActionExecutor.h */,\n\t\t\t\t276E5C491CDB57AA003FF4B4 /* LexerActionType.h */,\n\t\t\t\t276E5C4A1CDB57AA003FF4B4 /* LexerATNConfig.cpp */,\n\t\t\t\t276E5C4B1CDB57AA003FF4B4 /* LexerATNConfig.h */,\n\t\t\t\t276E5C4C1CDB57AA003FF4B4 /* LexerATNSimulator.cpp */,\n\t\t\t\t276E5C4D1CDB57AA003FF4B4 /* LexerATNSimulator.h */,\n\t\t\t\t276E5C4E1CDB57AA003FF4B4 /* LexerChannelAction.cpp */,\n\t\t\t\t276E5C4F1CDB57AA003FF4B4 /* LexerChannelAction.h */,\n\t\t\t\t276E5C501CDB57AA003FF4B4 /* LexerCustomAction.cpp */,\n\t\t\t\t276E5C511CDB57AA003FF4B4 /* LexerCustomAction.h */,\n\t\t\t\t276E5C521CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp */,\n\t\t\t\t276E5C531CDB57AA003FF4B4 /* LexerIndexedCustomAction.h */,\n\t\t\t\t276E5C541CDB57AA003FF4B4 /* LexerModeAction.cpp */,\n\t\t\t\t276E5C551CDB57AA003FF4B4 /* LexerModeAction.h */,\n\t\t\t\t276E5C561CDB57AA003FF4B4 /* LexerMoreAction.cpp */,\n\t\t\t\t276E5C571CDB57AA003FF4B4 /* LexerMoreAction.h */,\n\t\t\t\t276E5C581CDB57AA003FF4B4 /* LexerPopModeAction.cpp */,\n\t\t\t\t276E5C591CDB57AA003FF4B4 /* LexerPopModeAction.h */,\n\t\t\t\t276E5C5A1CDB57AA003FF4B4 /* LexerPushModeAction.cpp */,\n\t\t\t\t276E5C5B1CDB57AA003FF4B4 /* LexerPushModeAction.h */,\n\t\t\t\t276E5C5C1CDB57AA003FF4B4 /* LexerSkipAction.cpp */,\n\t\t\t\t276E5C5D1CDB57AA003FF4B4 /* LexerSkipAction.h */,\n\t\t\t\t276E5C5E1CDB57AA003FF4B4 /* LexerTypeAction.cpp */,\n\t\t\t\t276E5C5F1CDB57AA003FF4B4 /* LexerTypeAction.h */,\n\t\t\t\t276E5C601CDB57AA003FF4B4 /* LL1Analyzer.cpp */,\n\t\t\t\t276E5C611CDB57AA003FF4B4 /* LL1Analyzer.h */,\n\t\t\t\t276E5C621CDB57AA003FF4B4 /* LookaheadEventInfo.cpp */,\n\t\t\t\t276E5C631CDB57AA003FF4B4 /* LookaheadEventInfo.h */,\n\t\t\t\t276E5C651CDB57AA003FF4B4 /* LoopEndState.h */,\n\t\t\t\t276E5C671CDB57AA003FF4B4 /* NotSetTransition.cpp */,\n\t\t\t\t276E5C681CDB57AA003FF4B4 /* NotSetTransition.h */,\n\t\t\t\t276E5C691CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp */,\n\t\t\t\t276E5C6A1CDB57AA003FF4B4 /* OrderedATNConfigSet.h */,\n\t\t\t\t276E5C6B1CDB57AA003FF4B4 /* ParseInfo.cpp */,\n\t\t\t\t276E5C6C1CDB57AA003FF4B4 /* ParseInfo.h */,\n\t\t\t\t276E5C6D1CDB57AA003FF4B4 /* ParserATNSimulator.cpp */,\n\t\t\t\t276E5C6E1CDB57AA003FF4B4 /* ParserATNSimulator.h */,\n\t\t\t\t9B25DCAF291026DE00DF9703 /* ParserATNSimulatorOptions.h */,\n\t\t\t\t276E5C701CDB57AA003FF4B4 /* PlusBlockStartState.h */,\n\t\t\t\t276E5C721CDB57AA003FF4B4 /* PlusLoopbackState.h */,\n\t\t\t\t276E5C731CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp */,\n\t\t\t\t276E5C741CDB57AA003FF4B4 /* PrecedencePredicateTransition.h */,\n\t\t\t\t276E5C751CDB57AA003FF4B4 /* PredicateEvalInfo.cpp */,\n\t\t\t\t276E5C761CDB57AA003FF4B4 /* PredicateEvalInfo.h */,\n\t\t\t\t276E5C771CDB57AA003FF4B4 /* PredicateTransition.cpp */,\n\t\t\t\t276E5C781CDB57AA003FF4B4 /* PredicateTransition.h */,\n\t\t\t\t276E5C791CDB57AA003FF4B4 /* PredictionContext.cpp */,\n\t\t\t\t276E5C7A1CDB57AA003FF4B4 /* PredictionContext.h */,\n\t\t\t\t9B25DCB62910278000DF9703 /* PredictionContextCache.cpp */,\n\t\t\t\t9B25DCB32910278000DF9703 /* PredictionContextCache.h */,\n\t\t\t\t9B25DCB82910278000DF9703 /* PredictionContextMergeCache.cpp */,\n\t\t\t\t9B25DCB42910278000DF9703 /* PredictionContextMergeCache.h */,\n\t\t\t\t9B25DCB72910278000DF9703 /* PredictionContextMergeCacheOptions.h */,\n\t\t\t\t9B25DCB52910278000DF9703 /* PredictionContextType.h */,\n\t\t\t\t276E5C7B1CDB57AA003FF4B4 /* PredictionMode.cpp */,\n\t\t\t\t276E5C7C1CDB57AA003FF4B4 /* PredictionMode.h */,\n\t\t\t\t276E5C7D1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp */,\n\t\t\t\t276E5C7E1CDB57AA003FF4B4 /* ProfilingATNSimulator.h */,\n\t\t\t\t276E5C7F1CDB57AA003FF4B4 /* RangeTransition.cpp */,\n\t\t\t\t276E5C801CDB57AA003FF4B4 /* RangeTransition.h */,\n\t\t\t\t276E5C821CDB57AA003FF4B4 /* RuleStartState.h */,\n\t\t\t\t276E5C841CDB57AA003FF4B4 /* RuleStopState.h */,\n\t\t\t\t276E5C851CDB57AA003FF4B4 /* RuleTransition.cpp */,\n\t\t\t\t276E5C861CDB57AA003FF4B4 /* RuleTransition.h */,\n\t\t\t\t276E5C871CDB57AA003FF4B4 /* SemanticContext.cpp */,\n\t\t\t\t276E5C881CDB57AA003FF4B4 /* SemanticContext.h */,\n\t\t\t\t9B25DCCB291027ED00DF9703 /* SemanticContextType.h */,\n\t\t\t\t9B25DCCC291027EE00DF9703 /* SerializedATNView.h */,\n\t\t\t\t276E5C891CDB57AA003FF4B4 /* SetTransition.cpp */,\n\t\t\t\t276E5C8A1CDB57AA003FF4B4 /* SetTransition.h */,\n\t\t\t\t276E5C8B1CDB57AA003FF4B4 /* SingletonPredictionContext.cpp */,\n\t\t\t\t276E5C8C1CDB57AA003FF4B4 /* SingletonPredictionContext.h */,\n\t\t\t\t276E5C8E1CDB57AA003FF4B4 /* StarBlockStartState.h */,\n\t\t\t\t276E5C8F1CDB57AA003FF4B4 /* StarLoopbackState.cpp */,\n\t\t\t\t276E5C901CDB57AA003FF4B4 /* StarLoopbackState.h */,\n\t\t\t\t276E5C921CDB57AA003FF4B4 /* StarLoopEntryState.h */,\n\t\t\t\t276E5C941CDB57AA003FF4B4 /* TokensStartState.h */,\n\t\t\t\t276E5C951CDB57AA003FF4B4 /* Transition.cpp */,\n\t\t\t\t276E5C961CDB57AA003FF4B4 /* Transition.h */,\n\t\t\t\t9B25DCD32910282B00DF9703 /* TransitionType.cpp */,\n\t\t\t\t9B25DCD42910282B00DF9703 /* TransitionType.h */,\n\t\t\t\t276E5C971CDB57AA003FF4B4 /* WildcardTransition.cpp */,\n\t\t\t\t276E5C981CDB57AA003FF4B4 /* WildcardTransition.h */,\n\t\t\t);\n\t\t\tpath = atn;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t276E5CAB1CDB57AA003FF4B4 /* dfa */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t276E5CAC1CDB57AA003FF4B4 /* DFA.cpp */,\n\t\t\t\t276E5CAD1CDB57AA003FF4B4 /* DFA.h */,\n\t\t\t\t276E5CAE1CDB57AA003FF4B4 /* DFASerializer.cpp */,\n\t\t\t\t276E5CAF1CDB57AA003FF4B4 /* DFASerializer.h */,\n\t\t\t\t276E5CB01CDB57AA003FF4B4 /* DFAState.cpp */,\n\t\t\t\t276E5CB11CDB57AA003FF4B4 /* DFAState.h */,\n\t\t\t\t276E5CB21CDB57AA003FF4B4 /* LexerDFASerializer.cpp */,\n\t\t\t\t276E5CB31CDB57AA003FF4B4 /* LexerDFASerializer.h */,\n\t\t\t);\n\t\t\tpath = dfa;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t276E5CC91CDB57AA003FF4B4 /* misc */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t27C375821EA1059C00B5883C /* InterpreterDataReader.cpp */,\n\t\t\t\t27C375831EA1059C00B5883C /* InterpreterDataReader.h */,\n\t\t\t\t276E5CCA1CDB57AA003FF4B4 /* Interval.cpp */,\n\t\t\t\t276E5CCB1CDB57AA003FF4B4 /* Interval.h */,\n\t\t\t\t276E5CCC1CDB57AA003FF4B4 /* IntervalSet.cpp */,\n\t\t\t\t276E5CCD1CDB57AA003FF4B4 /* IntervalSet.h */,\n\t\t\t\t276E5CCE1CDB57AA003FF4B4 /* MurmurHash.cpp */,\n\t\t\t\t276E5CCF1CDB57AA003FF4B4 /* MurmurHash.h */,\n\t\t\t\t276E5CD11CDB57AA003FF4B4 /* Predicate.h */,\n\t\t\t);\n\t\t\tpath = misc;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t276E5CE41CDB57AA003FF4B4 /* support */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t2793DC9C1F08090D00A84290 /* Any.cpp */,\n\t\t\t\t27F4A8551D4CEB2A00E067EE /* Any.h */,\n\t\t\t\t276E5CE51CDB57AA003FF4B4 /* Arrays.cpp */,\n\t\t\t\t276E5CE61CDB57AA003FF4B4 /* Arrays.h */,\n\t\t\t\t276E5CE71CDB57AA003FF4B4 /* BitSet.h */,\n\t\t\t\t9B25DCE4291028BC00DF9703 /* Casts.h */,\n\t\t\t\t276E5CE81CDB57AA003FF4B4 /* CPPUtils.cpp */,\n\t\t\t\t276E5CE91CDB57AA003FF4B4 /* CPPUtils.h */,\n\t\t\t\t276E5CEA1CDB57AA003FF4B4 /* Declarations.h */,\n\t\t\t\t276E5CED1CDB57AA003FF4B4 /* StringUtils.cpp */,\n\t\t\t\t276E5CEE1CDB57AA003FF4B4 /* StringUtils.h */,\n\t\t\t\t9B25DCE8291028D000DF9703 /* Unicode.h */,\n\t\t\t\t9B25DCEA291028D000DF9703 /* Utf8.cpp */,\n\t\t\t\t9B25DCE9291028D000DF9703 /* Utf8.h */,\n\t\t\t);\n\t\t\tpath = support;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t276E5CF91CDB57AA003FF4B4 /* tree */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t276E5D061CDB57AA003FF4B4 /* pattern */,\n\t\t\t\t27DB448A1D045537007E790B /* xpath */,\n\t\t\t\t276E5CFA1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h */,\n\t\t\t\t276E5CFB1CDB57AA003FF4B4 /* ErrorNode.h */,\n\t\t\t\t276E5CFC1CDB57AA003FF4B4 /* ErrorNodeImpl.cpp */,\n\t\t\t\t276E5CFD1CDB57AA003FF4B4 /* ErrorNodeImpl.h */,\n\t\t\t\t27D414501DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp */,\n\t\t\t\t27D414511DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h */,\n\t\t\t\t276566DF1DA93BFB000869BE /* ParseTree.cpp */,\n\t\t\t\t276E5CFE1CDB57AA003FF4B4 /* ParseTree.h */,\n\t\t\t\t2793DC8C1F08088F00A84290 /* ParseTreeListener.cpp */,\n\t\t\t\t276E5D001CDB57AA003FF4B4 /* ParseTreeListener.h */,\n\t\t\t\t276E5D021CDB57AA003FF4B4 /* ParseTreeProperty.h */,\n\t\t\t\t2793DC951F0808E100A84290 /* ParseTreeVisitor.cpp */,\n\t\t\t\t276E5D031CDB57AA003FF4B4 /* ParseTreeVisitor.h */,\n\t\t\t\t276E5D041CDB57AA003FF4B4 /* ParseTreeWalker.cpp */,\n\t\t\t\t276E5D051CDB57AA003FF4B4 /* ParseTreeWalker.h */,\n\t\t\t\t276E5D181CDB57AA003FF4B4 /* TerminalNode.h */,\n\t\t\t\t276E5D191CDB57AA003FF4B4 /* TerminalNodeImpl.cpp */,\n\t\t\t\t276E5D1A1CDB57AA003FF4B4 /* TerminalNodeImpl.h */,\n\t\t\t\t276E5D1D1CDB57AA003FF4B4 /* Trees.cpp */,\n\t\t\t\t276E5D1E1CDB57AA003FF4B4 /* Trees.h */,\n\t\t\t);\n\t\t\tpath = tree;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t276E5D061CDB57AA003FF4B4 /* pattern */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t2793DC881F08087500A84290 /* Chunk.cpp */,\n\t\t\t\t276E5D071CDB57AA003FF4B4 /* Chunk.h */,\n\t\t\t\t276E5D081CDB57AA003FF4B4 /* ParseTreeMatch.cpp */,\n\t\t\t\t276E5D091CDB57AA003FF4B4 /* ParseTreeMatch.h */,\n\t\t\t\t276E5D0A1CDB57AA003FF4B4 /* ParseTreePattern.cpp */,\n\t\t\t\t276E5D0B1CDB57AA003FF4B4 /* ParseTreePattern.h */,\n\t\t\t\t276E5D0C1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp */,\n\t\t\t\t276E5D0D1CDB57AA003FF4B4 /* ParseTreePatternMatcher.h */,\n\t\t\t\t276E5D0E1CDB57AA003FF4B4 /* RuleTagToken.cpp */,\n\t\t\t\t276E5D0F1CDB57AA003FF4B4 /* RuleTagToken.h */,\n\t\t\t\t276E5D101CDB57AA003FF4B4 /* TagChunk.cpp */,\n\t\t\t\t276E5D111CDB57AA003FF4B4 /* TagChunk.h */,\n\t\t\t\t276E5D121CDB57AA003FF4B4 /* TextChunk.cpp */,\n\t\t\t\t276E5D131CDB57AA003FF4B4 /* TextChunk.h */,\n\t\t\t\t276E5D141CDB57AA003FF4B4 /* TokenTagToken.cpp */,\n\t\t\t\t276E5D151CDB57AA003FF4B4 /* TokenTagToken.h */,\n\t\t\t);\n\t\t\tpath = pattern;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t27874F221CCBB34200AF1C53 /* Linked Frameworks */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */,\n\t\t\t);\n\t\t\tname = \"Linked Frameworks\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t27DB448A1D045537007E790B /* xpath */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t27DB448B1D045537007E790B /* XPath.cpp */,\n\t\t\t\t27DB448C1D045537007E790B /* XPath.h */,\n\t\t\t\t27DB448D1D045537007E790B /* XPathElement.cpp */,\n\t\t\t\t27DB448E1D045537007E790B /* XPathElement.h */,\n\t\t\t\t27DB44AF1D0463CC007E790B /* XPathLexer.cpp */,\n\t\t\t\t27DB44B01D0463CC007E790B /* XPathLexer.h */,\n\t\t\t\t27DB448F1D045537007E790B /* XPathLexerErrorListener.cpp */,\n\t\t\t\t27DB44901D045537007E790B /* XPathLexerErrorListener.h */,\n\t\t\t\t27DB44911D045537007E790B /* XPathRuleAnywhereElement.cpp */,\n\t\t\t\t27DB44921D045537007E790B /* XPathRuleAnywhereElement.h */,\n\t\t\t\t27DB44931D045537007E790B /* XPathRuleElement.cpp */,\n\t\t\t\t27DB44941D045537007E790B /* XPathRuleElement.h */,\n\t\t\t\t27DB44951D045537007E790B /* XPathTokenAnywhereElement.cpp */,\n\t\t\t\t27DB44961D045537007E790B /* XPathTokenAnywhereElement.h */,\n\t\t\t\t27DB44971D045537007E790B /* XPathTokenElement.cpp */,\n\t\t\t\t27DB44981D045537007E790B /* XPathTokenElement.h */,\n\t\t\t\t27DB44991D045537007E790B /* XPathWildcardAnywhereElement.cpp */,\n\t\t\t\t27DB449A1D045537007E790B /* XPathWildcardAnywhereElement.h */,\n\t\t\t\t27DB449B1D045537007E790B /* XPathWildcardElement.cpp */,\n\t\t\t\t27DB449C1D045537007E790B /* XPathWildcardElement.h */,\n\t\t\t);\n\t\t\tpath = xpath;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t37D727A11867AF1E007B6D10 = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t270C67F11CDB4F1E00116E17 /* antlrcpp-ios */,\n\t\t\t\t27874F221CCBB34200AF1C53 /* Linked Frameworks */,\n\t\t\t\t37D727AB1867AF1E007B6D10 /* Products */,\n\t\t\t\t276E5C0A1CDB57AA003FF4B4 /* runtime */,\n\t\t\t);\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t37D727AB1867AF1E007B6D10 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t37D727AA1867AF1E007B6D10 /* libantlr4-runtime.dylib */,\n\t\t\t\t37C147171B4D5A04008EDDDB /* libantlr4-runtime.a */,\n\t\t\t\t270C67F01CDB4F1E00116E17 /* antlr4_ios.framework */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t9B25DCDB2910287000DF9703 /* internal */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t9B25DCDC2910287000DF9703 /* Synchronization.cpp */,\n\t\t\t\t9B25DCDD2910287000DF9703 /* Synchronization.h */,\n\t\t\t);\n\t\t\tpath = internal;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXHeadersBuildPhase section */\n\t\t270C67ED1CDB4F1E00116E17 /* Headers */ = {\n\t\t\tisa = PBXHeadersBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t276E5FEB1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h in Headers */,\n\t\t\t\t276E60331CDB57AA003FF4B4 /* TextChunk.h in Headers */,\n\t\t\t\t276E5F431CDB57AA003FF4B4 /* IntStream.h in Headers */,\n\t\t\t\t276E5D5D1CDB57AA003FF4B4 /* ATN.h in Headers */,\n\t\t\t\t276E60601CDB57AA003FF4B4 /* UnbufferedCharStream.h in Headers */,\n\t\t\t\t9B25DCAA2910252800DF9703 /* Version.h in Headers */,\n\t\t\t\t276E5DD81CDB57AA003FF4B4 /* LexerAction.h in Headers */,\n\t\t\t\t276E5FF71CDB57AA003FF4B4 /* ParseTree.h in Headers */,\n\t\t\t\t276E5DA81CDB57AA003FF4B4 /* BlockStartState.h in Headers */,\n\t\t\t\t276E5FE21CDB57AA003FF4B4 /* TokenStream.h in Headers */,\n\t\t\t\t276E5D6F1CDB57AA003FF4B4 /* ATNDeserializationOptions.h in Headers */,\n\t\t\t\t27DB44CA1D0463DB007E790B /* XPath.h in Headers */,\n\t\t\t\t276E5EDD1CDB57AA003FF4B4 /* BaseErrorListener.h in Headers */,\n\t\t\t\t9B25DCBE2910278000DF9703 /* PredictionContextMergeCache.h in Headers */,\n\t\t\t\t276E5DB71CDB57AA003FF4B4 /* DecisionEventInfo.h in Headers */,\n\t\t\t\t27DB44D01D0463DB007E790B /* XPathRuleAnywhereElement.h in Headers */,\n\t\t\t\t27AC52D21CE773A80093AAAB /* antlr4-runtime.h in Headers */,\n\t\t\t\t276E5E2C1CDB57AA003FF4B4 /* LL1Analyzer.h in Headers */,\n\t\t\t\t276E5EAD1CDB57AA003FF4B4 /* SingletonPredictionContext.h in Headers */,\n\t\t\t\t276E5E1A1CDB57AA003FF4B4 /* LexerPushModeAction.h in Headers */,\n\t\t\t\t276E5ECB1CDB57AA003FF4B4 /* Transition.h in Headers */,\n\t\t\t\t276E5EA11CDB57AA003FF4B4 /* SemanticContext.h in Headers */,\n\t\t\t\t27DB44DA1D0463DB007E790B /* XPathWildcardElement.h in Headers */,\n\t\t\t\t276E5F5E1CDB57AA003FF4B4 /* ListTokenSource.h in Headers */,\n\t\t\t\t276E5F8E1CDB57AA003FF4B4 /* ParserInterpreter.h in Headers */,\n\t\t\t\t276E5DDE1CDB57AA003FF4B4 /* LexerActionExecutor.h in Headers */,\n\t\t\t\t276E5F4C1CDB57AA003FF4B4 /* Lexer.h in Headers */,\n\t\t\t\t276E5F641CDB57AA003FF4B4 /* Interval.h in Headers */,\n\t\t\t\t276E5DA51CDB57AA003FF4B4 /* BlockEndState.h in Headers */,\n\t\t\t\t276E5E831CDB57AA003FF4B4 /* ProfilingATNSimulator.h in Headers */,\n\t\t\t\t276E5D991CDB57AA003FF4B4 /* BasicBlockStartState.h in Headers */,\n\t\t\t\t27C375891EA1059C00B5883C /* InterpreterDataReader.h in Headers */,\n\t\t\t\t276E5E9B1CDB57AA003FF4B4 /* RuleTransition.h in Headers */,\n\t\t\t\t276E60031CDB57AA003FF4B4 /* ParseTreeProperty.h in Headers */,\n\t\t\t\t276E5D8D1CDB57AA003FF4B4 /* ATNType.h in Headers */,\n\t\t\t\t276E5FFD1CDB57AA003FF4B4 /* ParseTreeListener.h in Headers */,\n\t\t\t\t276E5D9F1CDB57AA003FF4B4 /* BasicState.h in Headers */,\n\t\t\t\t276E5FAC1CDB57AA003FF4B4 /* RuleContext.h in Headers */,\n\t\t\t\t276E60271CDB57AA003FF4B4 /* RuleTagToken.h in Headers */,\n\t\t\t\t276E5F011CDB57AA003FF4B4 /* ConsoleErrorListener.h in Headers */,\n\t\t\t\t276E5D331CDB57AA003FF4B4 /* ANTLRErrorStrategy.h in Headers */,\n\t\t\t\t276E5E0E1CDB57AA003FF4B4 /* LexerMoreAction.h in Headers */,\n\t\t\t\t276E5D4B1CDB57AA003FF4B4 /* ActionTransition.h in Headers */,\n\t\t\t\t276E5E8F1CDB57AA003FF4B4 /* RuleStartState.h in Headers */,\n\t\t\t\t276E5E201CDB57AA003FF4B4 /* LexerSkipAction.h in Headers */,\n\t\t\t\t276E5E381CDB57AA003FF4B4 /* LoopEndState.h in Headers */,\n\t\t\t\t9B25DCED291028D000DF9703 /* Unicode.h in Headers */,\n\t\t\t\t276E5D691CDB57AA003FF4B4 /* ATNConfigSet.h in Headers */,\n\t\t\t\t276E5D391CDB57AA003FF4B4 /* ANTLRFileStream.h in Headers */,\n\t\t\t\t276E5D301CDB57AA003FF4B4 /* ANTLRErrorListener.h in Headers */,\n\t\t\t\t27B36ACB1DACE7AF0069C868 /* RuleContextWithAltNum.h in Headers */,\n\t\t\t\t276E5FCA1CDB57AA003FF4B4 /* StringUtils.h in Headers */,\n\t\t\t\t276E5EF51CDB57AA003FF4B4 /* CommonTokenFactory.h in Headers */,\n\t\t\t\t276E5F191CDB57AA003FF4B4 /* DFAState.h in Headers */,\n\t\t\t\t276E5FA61CDB57AA003FF4B4 /* Recognizer.h in Headers */,\n\t\t\t\t276E60751CDB57AA003FF4B4 /* WritableToken.h in Headers */,\n\t\t\t\t9B25DCD2291027EE00DF9703 /* SerializedATNView.h in Headers */,\n\t\t\t\t276E5D3F1CDB57AA003FF4B4 /* ANTLRInputStream.h in Headers */,\n\t\t\t\t276E5FD01CDB57AA003FF4B4 /* Token.h in Headers */,\n\t\t\t\t9B25DCC12910278000DF9703 /* PredictionContextType.h in Headers */,\n\t\t\t\t276E60421CDB57AA003FF4B4 /* TerminalNode.h in Headers */,\n\t\t\t\t9B25DCCF291027EE00DF9703 /* SemanticContextType.h in Headers */,\n\t\t\t\t276E5D751CDB57AA003FF4B4 /* ATNDeserializer.h in Headers */,\n\t\t\t\t276E5D871CDB57AA003FF4B4 /* ATNState.h in Headers */,\n\t\t\t\t276E5E7D1CDB57AA003FF4B4 /* PredictionMode.h in Headers */,\n\t\t\t\t276E5EBF1CDB57AA003FF4B4 /* StarLoopEntryState.h in Headers */,\n\t\t\t\t276E5FA01CDB57AA003FF4B4 /* RecognitionException.h in Headers */,\n\t\t\t\t276E5EA71CDB57AA003FF4B4 /* SetTransition.h in Headers */,\n\t\t\t\t276E5F1F1CDB57AA003FF4B4 /* LexerDFASerializer.h in Headers */,\n\t\t\t\t276E5E471CDB57AA003FF4B4 /* OrderedATNConfigSet.h in Headers */,\n\t\t\t\t276E5DF61CDB57AA003FF4B4 /* LexerChannelAction.h in Headers */,\n\t\t\t\t276E5FB21CDB57AA003FF4B4 /* Arrays.h in Headers */,\n\t\t\t\t276E5F821CDB57AA003FF4B4 /* NoViableAltException.h in Headers */,\n\t\t\t\t276E5DEA1CDB57AA003FF4B4 /* LexerATNConfig.h in Headers */,\n\t\t\t\t9B25DCA32910249100DF9703 /* FlatHashSet.h in Headers */,\n\t\t\t\t276E60481CDB57AA003FF4B4 /* TerminalNodeImpl.h in Headers */,\n\t\t\t\t27745F081CE49C000067C6A3 /* RuntimeMetaData.h in Headers */,\n\t\t\t\t9B25DCBB2910278000DF9703 /* PredictionContextCache.h in Headers */,\n\t\t\t\t276E5FF41CDB57AA003FF4B4 /* ErrorNodeImpl.h in Headers */,\n\t\t\t\t276E5EC51CDB57AA003FF4B4 /* TokensStartState.h in Headers */,\n\t\t\t\t276E5F2B1CDB57AA003FF4B4 /* Exceptions.h in Headers */,\n\t\t\t\t276E5F251CDB57AA003FF4B4 /* DiagnosticErrorListener.h in Headers */,\n\t\t\t\t276E5E141CDB57AA003FF4B4 /* LexerPopModeAction.h in Headers */,\n\t\t\t\t276E5ED71CDB57AA003FF4B4 /* BailErrorStrategy.h in Headers */,\n\t\t\t\t27DB44CE1D0463DB007E790B /* XPathLexerErrorListener.h in Headers */,\n\t\t\t\t276E5DCF1CDB57AA003FF4B4 /* EpsilonTransition.h in Headers */,\n\t\t\t\t276E5FBE1CDB57AA003FF4B4 /* Declarations.h in Headers */,\n\t\t\t\t276E600C1CDB57AA003FF4B4 /* ParseTreeWalker.h in Headers */,\n\t\t\t\t276E5E771CDB57AA003FF4B4 /* PredictionContext.h in Headers */,\n\t\t\t\t276E60151CDB57AA003FF4B4 /* ParseTreeMatch.h in Headers */,\n\t\t\t\t27DB44CC1D0463DB007E790B /* XPathElement.h in Headers */,\n\t\t\t\t9B25DCF0291028D000DF9703 /* Utf8.h in Headers */,\n\t\t\t\t276E5F581CDB57AA003FF4B4 /* LexerNoViableAltException.h in Headers */,\n\t\t\t\t276E5D811CDB57AA003FF4B4 /* ATNSimulator.h in Headers */,\n\t\t\t\t27DB44B61D0463CC007E790B /* XPathLexer.h in Headers */,\n\t\t\t\t276E602D1CDB57AA003FF4B4 /* TagChunk.h in Headers */,\n\t\t\t\t276E5E951CDB57AA003FF4B4 /* RuleStopState.h in Headers */,\n\t\t\t\t9B25DCE32910287000DF9703 /* Synchronization.h in Headers */,\n\t\t\t\t276E5F761CDB57AA003FF4B4 /* Predicate.h in Headers */,\n\t\t\t\t9B25DCB2291026DE00DF9703 /* ParserATNSimulatorOptions.h in Headers */,\n\t\t\t\t276E5F941CDB57AA003FF4B4 /* ParserRuleContext.h in Headers */,\n\t\t\t\t276E5FEE1CDB57AA003FF4B4 /* ErrorNode.h in Headers */,\n\t\t\t\t276E5EB91CDB57AA003FF4B4 /* StarLoopbackState.h in Headers */,\n\t\t\t\t276E5E5F1CDB57AA003FF4B4 /* PlusLoopbackState.h in Headers */,\n\t\t\t\t276E5E081CDB57AA003FF4B4 /* LexerModeAction.h in Headers */,\n\t\t\t\t276E5E591CDB57AA003FF4B4 /* PlusBlockStartState.h in Headers */,\n\t\t\t\t276E5D931CDB57AA003FF4B4 /* AtomTransition.h in Headers */,\n\t\t\t\t276E5F521CDB57AA003FF4B4 /* LexerInterpreter.h in Headers */,\n\t\t\t\t9B25DCA62910249100DF9703 /* FlatHashMap.h in Headers */,\n\t\t\t\t276E5F311CDB57AA003FF4B4 /* FailedPredicateException.h in Headers */,\n\t\t\t\t276E5E321CDB57AA003FF4B4 /* LookaheadEventInfo.h in Headers */,\n\t\t\t\t276E5F0D1CDB57AA003FF4B4 /* DFA.h in Headers */,\n\t\t\t\t276E606F1CDB57AA003FF4B4 /* Vocabulary.h in Headers */,\n\t\t\t\t9B25DCAE291025B700DF9703 /* ATNStateType.h in Headers */,\n\t\t\t\t276E60541CDB57AA003FF4B4 /* Trees.h in Headers */,\n\t\t\t\t276E5FB51CDB57AA003FF4B4 /* BitSet.h in Headers */,\n\t\t\t\t276E5F9A1CDB57AA003FF4B4 /* ProxyErrorListener.h in Headers */,\n\t\t\t\t276E5E411CDB57AA003FF4B4 /* NotSetTransition.h in Headers */,\n\t\t\t\t276E5E891CDB57AA003FF4B4 /* RangeTransition.h in Headers */,\n\t\t\t\t27DB44D21D0463DB007E790B /* XPathRuleElement.h in Headers */,\n\t\t\t\t27D414571DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h in Headers */,\n\t\t\t\t276E601B1CDB57AA003FF4B4 /* ParseTreePattern.h in Headers */,\n\t\t\t\t276E5DFC1CDB57AA003FF4B4 /* LexerCustomAction.h in Headers */,\n\t\t\t\t276E5FE81CDB57AA003FF4B4 /* TokenStreamRewriter.h in Headers */,\n\t\t\t\t276E5DF01CDB57AA003FF4B4 /* LexerATNSimulator.h in Headers */,\n\t\t\t\t276E5DD51CDB57AA003FF4B4 /* ErrorInfo.h in Headers */,\n\t\t\t\t276E5E261CDB57AA003FF4B4 /* LexerTypeAction.h in Headers */,\n\t\t\t\t27DB44D61D0463DB007E790B /* XPathTokenElement.h in Headers */,\n\t\t\t\t276E5DE41CDB57AA003FF4B4 /* LexerActionType.h in Headers */,\n\t\t\t\t276E5D511CDB57AA003FF4B4 /* AmbiguityInfo.h in Headers */,\n\t\t\t\t276E5E711CDB57AA003FF4B4 /* PredicateTransition.h in Headers */,\n\t\t\t\t276E5EE91CDB57AA003FF4B4 /* CharStream.h in Headers */,\n\t\t\t\t276E60061CDB57AA003FF4B4 /* ParseTreeVisitor.h in Headers */,\n\t\t\t\t276E5D571CDB57AA003FF4B4 /* ArrayPredictionContext.h in Headers */,\n\t\t\t\t276E5E531CDB57AA003FF4B4 /* ParserATNSimulator.h in Headers */,\n\t\t\t\t276E60661CDB57AA003FF4B4 /* UnbufferedTokenStream.h in Headers */,\n\t\t\t\t276E5F6A1CDB57AA003FF4B4 /* IntervalSet.h in Headers */,\n\t\t\t\t276E5E651CDB57AA003FF4B4 /* PrecedencePredicateTransition.h in Headers */,\n\t\t\t\t276E5F071CDB57AA003FF4B4 /* DefaultErrorStrategy.h in Headers */,\n\t\t\t\t276E5F3D1CDB57AA003FF4B4 /* InterpreterRuleContext.h in Headers */,\n\t\t\t\t276E5F131CDB57AA003FF4B4 /* DFASerializer.h in Headers */,\n\t\t\t\t2794D8581CE7821B00FADD0F /* antlr4-common.h in Headers */,\n\t\t\t\t276E5F371CDB57AA003FF4B4 /* InputMismatchException.h in Headers */,\n\t\t\t\t276E5FDC1CDB57AA003FF4B4 /* TokenSource.h in Headers */,\n\t\t\t\t276E5ED11CDB57AA003FF4B4 /* WildcardTransition.h in Headers */,\n\t\t\t\t276E600F1CDB57AA003FF4B4 /* Chunk.h in Headers */,\n\t\t\t\t276E5FBB1CDB57AA003FF4B4 /* CPPUtils.h in Headers */,\n\t\t\t\t9B25DCC72910278000DF9703 /* PredictionContextMergeCacheOptions.h in Headers */,\n\t\t\t\t276E5EE31CDB57AA003FF4B4 /* BufferedTokenStream.h in Headers */,\n\t\t\t\t276E5DB11CDB57AA003FF4B4 /* ContextSensitivityInfo.h in Headers */,\n\t\t\t\t276E5E021CDB57AA003FF4B4 /* LexerIndexedCustomAction.h in Headers */,\n\t\t\t\t276E5FD61CDB57AA003FF4B4 /* TokenFactory.h in Headers */,\n\t\t\t\t276E5EFB1CDB57AA003FF4B4 /* CommonTokenStream.h in Headers */,\n\t\t\t\t276E5EB31CDB57AA003FF4B4 /* StarBlockStartState.h in Headers */,\n\t\t\t\t276E5F701CDB57AA003FF4B4 /* MurmurHash.h in Headers */,\n\t\t\t\t276E60211CDB57AA003FF4B4 /* ParseTreePatternMatcher.h in Headers */,\n\t\t\t\t276E5D631CDB57AA003FF4B4 /* ATNConfig.h in Headers */,\n\t\t\t\t27DB44D41D0463DB007E790B /* XPathTokenAnywhereElement.h in Headers */,\n\t\t\t\t9B25DCE7291028BC00DF9703 /* Casts.h in Headers */,\n\t\t\t\t27DB44D81D0463DB007E790B /* XPathWildcardAnywhereElement.h in Headers */,\n\t\t\t\t276E5E4D1CDB57AA003FF4B4 /* ParseInfo.h in Headers */,\n\t\t\t\t276E5F881CDB57AA003FF4B4 /* Parser.h in Headers */,\n\t\t\t\t276E5DBD1CDB57AA003FF4B4 /* DecisionInfo.h in Headers */,\n\t\t\t\t276E5DC31CDB57AA003FF4B4 /* DecisionState.h in Headers */,\n\t\t\t\t276E5E6B1CDB57AA003FF4B4 /* PredicateEvalInfo.h in Headers */,\n\t\t\t\t276E5EEF1CDB57AA003FF4B4 /* CommonToken.h in Headers */,\n\t\t\t\t270C67F31CDB4F1E00116E17 /* antlrcpp_ios.h in Headers */,\n\t\t\t\t9B25DCDA2910282B00DF9703 /* TransitionType.h in Headers */,\n\t\t\t\t276E60391CDB57AA003FF4B4 /* TokenTagToken.h in Headers */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37C147151B4D5A04008EDDDB /* Headers */ = {\n\t\t\tisa = PBXHeadersBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t276E5FEA1CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h in Headers */,\n\t\t\t\t276E60321CDB57AA003FF4B4 /* TextChunk.h in Headers */,\n\t\t\t\t276E5F421CDB57AA003FF4B4 /* IntStream.h in Headers */,\n\t\t\t\t276E5D5C1CDB57AA003FF4B4 /* ATN.h in Headers */,\n\t\t\t\t276E605F1CDB57AA003FF4B4 /* UnbufferedCharStream.h in Headers */,\n\t\t\t\t276E5DD71CDB57AA003FF4B4 /* LexerAction.h in Headers */,\n\t\t\t\t276E5FF61CDB57AA003FF4B4 /* ParseTree.h in Headers */,\n\t\t\t\t27AC52D11CE773A80093AAAB /* antlr4-runtime.h in Headers */,\n\t\t\t\t276E5DA71CDB57AA003FF4B4 /* BlockStartState.h in Headers */,\n\t\t\t\t276E5FE11CDB57AA003FF4B4 /* TokenStream.h in Headers */,\n\t\t\t\t276E5D6E1CDB57AA003FF4B4 /* ATNDeserializationOptions.h in Headers */,\n\t\t\t\t276E5EDC1CDB57AA003FF4B4 /* BaseErrorListener.h in Headers */,\n\t\t\t\t9B25DCBA2910278000DF9703 /* PredictionContextCache.h in Headers */,\n\t\t\t\t276E5DB61CDB57AA003FF4B4 /* DecisionEventInfo.h in Headers */,\n\t\t\t\t276E5E2B1CDB57AA003FF4B4 /* LL1Analyzer.h in Headers */,\n\t\t\t\t27DB44BA1D0463DA007E790B /* XPathElement.h in Headers */,\n\t\t\t\t27C375881EA1059C00B5883C /* InterpreterDataReader.h in Headers */,\n\t\t\t\t276E5EAC1CDB57AA003FF4B4 /* SingletonPredictionContext.h in Headers */,\n\t\t\t\t276E5E191CDB57AA003FF4B4 /* LexerPushModeAction.h in Headers */,\n\t\t\t\t276E5ECA1CDB57AA003FF4B4 /* Transition.h in Headers */,\n\t\t\t\t9B25DCBD2910278000DF9703 /* PredictionContextMergeCache.h in Headers */,\n\t\t\t\t276E5EA01CDB57AA003FF4B4 /* SemanticContext.h in Headers */,\n\t\t\t\t276E5F5D1CDB57AA003FF4B4 /* ListTokenSource.h in Headers */,\n\t\t\t\t9B25DCE22910287000DF9703 /* Synchronization.h in Headers */,\n\t\t\t\t276E5F8D1CDB57AA003FF4B4 /* ParserInterpreter.h in Headers */,\n\t\t\t\t27D414561DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h in Headers */,\n\t\t\t\t276E5DDD1CDB57AA003FF4B4 /* LexerActionExecutor.h in Headers */,\n\t\t\t\t276E5F4B1CDB57AA003FF4B4 /* Lexer.h in Headers */,\n\t\t\t\t276E5F631CDB57AA003FF4B4 /* Interval.h in Headers */,\n\t\t\t\t276E5DA41CDB57AA003FF4B4 /* BlockEndState.h in Headers */,\n\t\t\t\t9B25DCA92910252800DF9703 /* Version.h in Headers */,\n\t\t\t\t27DB44C21D0463DA007E790B /* XPathTokenAnywhereElement.h in Headers */,\n\t\t\t\t276E5E821CDB57AA003FF4B4 /* ProfilingATNSimulator.h in Headers */,\n\t\t\t\t27DB44C41D0463DA007E790B /* XPathTokenElement.h in Headers */,\n\t\t\t\t276E5D981CDB57AA003FF4B4 /* BasicBlockStartState.h in Headers */,\n\t\t\t\t276E5E9A1CDB57AA003FF4B4 /* RuleTransition.h in Headers */,\n\t\t\t\t27DB44B81D0463DA007E790B /* XPath.h in Headers */,\n\t\t\t\t276E60021CDB57AA003FF4B4 /* ParseTreeProperty.h in Headers */,\n\t\t\t\t9B25DCC02910278000DF9703 /* PredictionContextType.h in Headers */,\n\t\t\t\t9B25DCEC291028D000DF9703 /* Unicode.h in Headers */,\n\t\t\t\t276E5D8C1CDB57AA003FF4B4 /* ATNType.h in Headers */,\n\t\t\t\t276E5FFC1CDB57AA003FF4B4 /* ParseTreeListener.h in Headers */,\n\t\t\t\t276E5D9E1CDB57AA003FF4B4 /* BasicState.h in Headers */,\n\t\t\t\t276E5FAB1CDB57AA003FF4B4 /* RuleContext.h in Headers */,\n\t\t\t\t276E60261CDB57AA003FF4B4 /* RuleTagToken.h in Headers */,\n\t\t\t\t276E5F001CDB57AA003FF4B4 /* ConsoleErrorListener.h in Headers */,\n\t\t\t\t27B36ACA1DACE7AF0069C868 /* RuleContextWithAltNum.h in Headers */,\n\t\t\t\t276E5D321CDB57AA003FF4B4 /* ANTLRErrorStrategy.h in Headers */,\n\t\t\t\t276E5E0D1CDB57AA003FF4B4 /* LexerMoreAction.h in Headers */,\n\t\t\t\t276E5D4A1CDB57AA003FF4B4 /* ActionTransition.h in Headers */,\n\t\t\t\t276E5E8E1CDB57AA003FF4B4 /* RuleStartState.h in Headers */,\n\t\t\t\t276E5E1F1CDB57AA003FF4B4 /* LexerSkipAction.h in Headers */,\n\t\t\t\t276E5E371CDB57AA003FF4B4 /* LoopEndState.h in Headers */,\n\t\t\t\t276E5D681CDB57AA003FF4B4 /* ATNConfigSet.h in Headers */,\n\t\t\t\t276E5D381CDB57AA003FF4B4 /* ANTLRFileStream.h in Headers */,\n\t\t\t\t27DB44C01D0463DA007E790B /* XPathRuleElement.h in Headers */,\n\t\t\t\t276E5D2F1CDB57AA003FF4B4 /* ANTLRErrorListener.h in Headers */,\n\t\t\t\t276E5FC91CDB57AA003FF4B4 /* StringUtils.h in Headers */,\n\t\t\t\t276E5EF41CDB57AA003FF4B4 /* CommonTokenFactory.h in Headers */,\n\t\t\t\t276E5F181CDB57AA003FF4B4 /* DFAState.h in Headers */,\n\t\t\t\t276E5FA51CDB57AA003FF4B4 /* Recognizer.h in Headers */,\n\t\t\t\t276E60741CDB57AA003FF4B4 /* WritableToken.h in Headers */,\n\t\t\t\t276E5D3E1CDB57AA003FF4B4 /* ANTLRInputStream.h in Headers */,\n\t\t\t\t276E5FCF1CDB57AA003FF4B4 /* Token.h in Headers */,\n\t\t\t\t276E60411CDB57AA003FF4B4 /* TerminalNode.h in Headers */,\n\t\t\t\t276E5D741CDB57AA003FF4B4 /* ATNDeserializer.h in Headers */,\n\t\t\t\t27DB44B51D0463CC007E790B /* XPathLexer.h in Headers */,\n\t\t\t\t276E5D861CDB57AA003FF4B4 /* ATNState.h in Headers */,\n\t\t\t\t276E5E7C1CDB57AA003FF4B4 /* PredictionMode.h in Headers */,\n\t\t\t\t276E5EBE1CDB57AA003FF4B4 /* StarLoopEntryState.h in Headers */,\n\t\t\t\t276E5F9F1CDB57AA003FF4B4 /* RecognitionException.h in Headers */,\n\t\t\t\t27DB44BE1D0463DA007E790B /* XPathRuleAnywhereElement.h in Headers */,\n\t\t\t\t27745F071CE49C000067C6A3 /* RuntimeMetaData.h in Headers */,\n\t\t\t\t276E5EA61CDB57AA003FF4B4 /* SetTransition.h in Headers */,\n\t\t\t\t276E5F1E1CDB57AA003FF4B4 /* LexerDFASerializer.h in Headers */,\n\t\t\t\t276E5E461CDB57AA003FF4B4 /* OrderedATNConfigSet.h in Headers */,\n\t\t\t\t276E5DF51CDB57AA003FF4B4 /* LexerChannelAction.h in Headers */,\n\t\t\t\t276E5FB11CDB57AA003FF4B4 /* Arrays.h in Headers */,\n\t\t\t\t9B25DCA22910249100DF9703 /* FlatHashSet.h in Headers */,\n\t\t\t\t276E5F811CDB57AA003FF4B4 /* NoViableAltException.h in Headers */,\n\t\t\t\t276E5DE91CDB57AA003FF4B4 /* LexerATNConfig.h in Headers */,\n\t\t\t\t276E60471CDB57AA003FF4B4 /* TerminalNodeImpl.h in Headers */,\n\t\t\t\t276E5FF31CDB57AA003FF4B4 /* ErrorNodeImpl.h in Headers */,\n\t\t\t\t276E5EC41CDB57AA003FF4B4 /* TokensStartState.h in Headers */,\n\t\t\t\t276E5F2A1CDB57AA003FF4B4 /* Exceptions.h in Headers */,\n\t\t\t\t27DB44C61D0463DA007E790B /* XPathWildcardAnywhereElement.h in Headers */,\n\t\t\t\t9B25DCE6291028BC00DF9703 /* Casts.h in Headers */,\n\t\t\t\t276E5F241CDB57AA003FF4B4 /* DiagnosticErrorListener.h in Headers */,\n\t\t\t\t276E5E131CDB57AA003FF4B4 /* LexerPopModeAction.h in Headers */,\n\t\t\t\t276E5ED61CDB57AA003FF4B4 /* BailErrorStrategy.h in Headers */,\n\t\t\t\t276E5DCE1CDB57AA003FF4B4 /* EpsilonTransition.h in Headers */,\n\t\t\t\t276E5FBD1CDB57AA003FF4B4 /* Declarations.h in Headers */,\n\t\t\t\t276E600B1CDB57AA003FF4B4 /* ParseTreeWalker.h in Headers */,\n\t\t\t\t9B25DCCE291027EE00DF9703 /* SemanticContextType.h in Headers */,\n\t\t\t\t276E5E761CDB57AA003FF4B4 /* PredictionContext.h in Headers */,\n\t\t\t\t276E60141CDB57AA003FF4B4 /* ParseTreeMatch.h in Headers */,\n\t\t\t\t276E5F571CDB57AA003FF4B4 /* LexerNoViableAltException.h in Headers */,\n\t\t\t\t276E5D801CDB57AA003FF4B4 /* ATNSimulator.h in Headers */,\n\t\t\t\t276E602C1CDB57AA003FF4B4 /* TagChunk.h in Headers */,\n\t\t\t\t276E5E941CDB57AA003FF4B4 /* RuleStopState.h in Headers */,\n\t\t\t\t276E5F751CDB57AA003FF4B4 /* Predicate.h in Headers */,\n\t\t\t\t276E5F931CDB57AA003FF4B4 /* ParserRuleContext.h in Headers */,\n\t\t\t\t276E5FED1CDB57AA003FF4B4 /* ErrorNode.h in Headers */,\n\t\t\t\t276E5EB81CDB57AA003FF4B4 /* StarLoopbackState.h in Headers */,\n\t\t\t\t276E5E5E1CDB57AA003FF4B4 /* PlusLoopbackState.h in Headers */,\n\t\t\t\t276E5E071CDB57AA003FF4B4 /* LexerModeAction.h in Headers */,\n\t\t\t\t276E5E581CDB57AA003FF4B4 /* PlusBlockStartState.h in Headers */,\n\t\t\t\t276E5D921CDB57AA003FF4B4 /* AtomTransition.h in Headers */,\n\t\t\t\t276E5F511CDB57AA003FF4B4 /* LexerInterpreter.h in Headers */,\n\t\t\t\t9B25DCB1291026DE00DF9703 /* ParserATNSimulatorOptions.h in Headers */,\n\t\t\t\t276E5F301CDB57AA003FF4B4 /* FailedPredicateException.h in Headers */,\n\t\t\t\t276E5E311CDB57AA003FF4B4 /* LookaheadEventInfo.h in Headers */,\n\t\t\t\t276E5F0C1CDB57AA003FF4B4 /* DFA.h in Headers */,\n\t\t\t\t276E606E1CDB57AA003FF4B4 /* Vocabulary.h in Headers */,\n\t\t\t\t276E60531CDB57AA003FF4B4 /* Trees.h in Headers */,\n\t\t\t\t276E5FB41CDB57AA003FF4B4 /* BitSet.h in Headers */,\n\t\t\t\t276E5F991CDB57AA003FF4B4 /* ProxyErrorListener.h in Headers */,\n\t\t\t\t276E5E401CDB57AA003FF4B4 /* NotSetTransition.h in Headers */,\n\t\t\t\t9B25DCD92910282B00DF9703 /* TransitionType.h in Headers */,\n\t\t\t\t9B25DCD1291027EE00DF9703 /* SerializedATNView.h in Headers */,\n\t\t\t\t276E5E881CDB57AA003FF4B4 /* RangeTransition.h in Headers */,\n\t\t\t\t276E601A1CDB57AA003FF4B4 /* ParseTreePattern.h in Headers */,\n\t\t\t\t276E5DFB1CDB57AA003FF4B4 /* LexerCustomAction.h in Headers */,\n\t\t\t\t276E5FE71CDB57AA003FF4B4 /* TokenStreamRewriter.h in Headers */,\n\t\t\t\t9B25DCC62910278000DF9703 /* PredictionContextMergeCacheOptions.h in Headers */,\n\t\t\t\t276E5DEF1CDB57AA003FF4B4 /* LexerATNSimulator.h in Headers */,\n\t\t\t\t276E5DD41CDB57AA003FF4B4 /* ErrorInfo.h in Headers */,\n\t\t\t\t276E5E251CDB57AA003FF4B4 /* LexerTypeAction.h in Headers */,\n\t\t\t\t276E5DE31CDB57AA003FF4B4 /* LexerActionType.h in Headers */,\n\t\t\t\t276E5D501CDB57AA003FF4B4 /* AmbiguityInfo.h in Headers */,\n\t\t\t\t276E5E701CDB57AA003FF4B4 /* PredicateTransition.h in Headers */,\n\t\t\t\t9B25DCEF291028D000DF9703 /* Utf8.h in Headers */,\n\t\t\t\t276E5EE81CDB57AA003FF4B4 /* CharStream.h in Headers */,\n\t\t\t\t276E60051CDB57AA003FF4B4 /* ParseTreeVisitor.h in Headers */,\n\t\t\t\t9B25DCAD291025B700DF9703 /* ATNStateType.h in Headers */,\n\t\t\t\t276E5D561CDB57AA003FF4B4 /* ArrayPredictionContext.h in Headers */,\n\t\t\t\t276E5E521CDB57AA003FF4B4 /* ParserATNSimulator.h in Headers */,\n\t\t\t\t2794D8571CE7821B00FADD0F /* antlr4-common.h in Headers */,\n\t\t\t\t276E60651CDB57AA003FF4B4 /* UnbufferedTokenStream.h in Headers */,\n\t\t\t\t276E5F691CDB57AA003FF4B4 /* IntervalSet.h in Headers */,\n\t\t\t\t276E5E641CDB57AA003FF4B4 /* PrecedencePredicateTransition.h in Headers */,\n\t\t\t\t276E5F061CDB57AA003FF4B4 /* DefaultErrorStrategy.h in Headers */,\n\t\t\t\t276E5F3C1CDB57AA003FF4B4 /* InterpreterRuleContext.h in Headers */,\n\t\t\t\t27DB44BC1D0463DA007E790B /* XPathLexerErrorListener.h in Headers */,\n\t\t\t\t276E5F121CDB57AA003FF4B4 /* DFASerializer.h in Headers */,\n\t\t\t\t276E5F361CDB57AA003FF4B4 /* InputMismatchException.h in Headers */,\n\t\t\t\t276E5FDB1CDB57AA003FF4B4 /* TokenSource.h in Headers */,\n\t\t\t\t276E5ED01CDB57AA003FF4B4 /* WildcardTransition.h in Headers */,\n\t\t\t\t276E600E1CDB57AA003FF4B4 /* Chunk.h in Headers */,\n\t\t\t\t276E5FBA1CDB57AA003FF4B4 /* CPPUtils.h in Headers */,\n\t\t\t\t276E5EE21CDB57AA003FF4B4 /* BufferedTokenStream.h in Headers */,\n\t\t\t\t276E5DB01CDB57AA003FF4B4 /* ContextSensitivityInfo.h in Headers */,\n\t\t\t\t276E5E011CDB57AA003FF4B4 /* LexerIndexedCustomAction.h in Headers */,\n\t\t\t\t276E5FD51CDB57AA003FF4B4 /* TokenFactory.h in Headers */,\n\t\t\t\t276E5EFA1CDB57AA003FF4B4 /* CommonTokenStream.h in Headers */,\n\t\t\t\t276E5EB21CDB57AA003FF4B4 /* StarBlockStartState.h in Headers */,\n\t\t\t\t276E5F6F1CDB57AA003FF4B4 /* MurmurHash.h in Headers */,\n\t\t\t\t27DB44C81D0463DA007E790B /* XPathWildcardElement.h in Headers */,\n\t\t\t\t276E60201CDB57AA003FF4B4 /* ParseTreePatternMatcher.h in Headers */,\n\t\t\t\t276E5D621CDB57AA003FF4B4 /* ATNConfig.h in Headers */,\n\t\t\t\t276E5E4C1CDB57AA003FF4B4 /* ParseInfo.h in Headers */,\n\t\t\t\t276E5F871CDB57AA003FF4B4 /* Parser.h in Headers */,\n\t\t\t\t276E5DBC1CDB57AA003FF4B4 /* DecisionInfo.h in Headers */,\n\t\t\t\t276E5DC21CDB57AA003FF4B4 /* DecisionState.h in Headers */,\n\t\t\t\t9B25DCA52910249100DF9703 /* FlatHashMap.h in Headers */,\n\t\t\t\t276E5E6A1CDB57AA003FF4B4 /* PredicateEvalInfo.h in Headers */,\n\t\t\t\t276E5EEE1CDB57AA003FF4B4 /* CommonToken.h in Headers */,\n\t\t\t\t276E60381CDB57AA003FF4B4 /* TokenTagToken.h in Headers */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37D727A81867AF1E007B6D10 /* Headers */ = {\n\t\t\tisa = PBXHeadersBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t276E5FE91CDB57AA003FF4B4 /* AbstractParseTreeVisitor.h in Headers */,\n\t\t\t\t27DB44AC1D045537007E790B /* XPathWildcardAnywhereElement.h in Headers */,\n\t\t\t\t276E60311CDB57AA003FF4B4 /* TextChunk.h in Headers */,\n\t\t\t\t276E5F411CDB57AA003FF4B4 /* IntStream.h in Headers */,\n\t\t\t\t276E5D5B1CDB57AA003FF4B4 /* ATN.h in Headers */,\n\t\t\t\t9B25DCA82910252800DF9703 /* Version.h in Headers */,\n\t\t\t\t276E605E1CDB57AA003FF4B4 /* UnbufferedCharStream.h in Headers */,\n\t\t\t\t276E5DD61CDB57AA003FF4B4 /* LexerAction.h in Headers */,\n\t\t\t\t27DB44A41D045537007E790B /* XPathRuleAnywhereElement.h in Headers */,\n\t\t\t\t276E5FF51CDB57AA003FF4B4 /* ParseTree.h in Headers */,\n\t\t\t\t27AC52D01CE773A80093AAAB /* antlr4-runtime.h in Headers */,\n\t\t\t\t276E5DA61CDB57AA003FF4B4 /* BlockStartState.h in Headers */,\n\t\t\t\t276E5FE01CDB57AA003FF4B4 /* TokenStream.h in Headers */,\n\t\t\t\t9B25DCBC2910278000DF9703 /* PredictionContextMergeCache.h in Headers */,\n\t\t\t\t276E5D6D1CDB57AA003FF4B4 /* ATNDeserializationOptions.h in Headers */,\n\t\t\t\t276E5EDB1CDB57AA003FF4B4 /* BaseErrorListener.h in Headers */,\n\t\t\t\t276E5DB51CDB57AA003FF4B4 /* DecisionEventInfo.h in Headers */,\n\t\t\t\t276E5E2A1CDB57AA003FF4B4 /* LL1Analyzer.h in Headers */,\n\t\t\t\t276E5EAB1CDB57AA003FF4B4 /* SingletonPredictionContext.h in Headers */,\n\t\t\t\t276E5E181CDB57AA003FF4B4 /* LexerPushModeAction.h in Headers */,\n\t\t\t\t276E5EC91CDB57AA003FF4B4 /* Transition.h in Headers */,\n\t\t\t\t276E5E9F1CDB57AA003FF4B4 /* SemanticContext.h in Headers */,\n\t\t\t\t276E5F5C1CDB57AA003FF4B4 /* ListTokenSource.h in Headers */,\n\t\t\t\t276E5F8C1CDB57AA003FF4B4 /* ParserInterpreter.h in Headers */,\n\t\t\t\t276E5DDC1CDB57AA003FF4B4 /* LexerActionExecutor.h in Headers */,\n\t\t\t\t276E5F4A1CDB57AA003FF4B4 /* Lexer.h in Headers */,\n\t\t\t\t276E5F621CDB57AA003FF4B4 /* Interval.h in Headers */,\n\t\t\t\t276E5DA31CDB57AA003FF4B4 /* BlockEndState.h in Headers */,\n\t\t\t\t276E5E811CDB57AA003FF4B4 /* ProfilingATNSimulator.h in Headers */,\n\t\t\t\t276E5D971CDB57AA003FF4B4 /* BasicBlockStartState.h in Headers */,\n\t\t\t\t276E5E991CDB57AA003FF4B4 /* RuleTransition.h in Headers */,\n\t\t\t\t27C375871EA1059C00B5883C /* InterpreterDataReader.h in Headers */,\n\t\t\t\t276E60011CDB57AA003FF4B4 /* ParseTreeProperty.h in Headers */,\n\t\t\t\t276E5D8B1CDB57AA003FF4B4 /* ATNType.h in Headers */,\n\t\t\t\t276E5FFB1CDB57AA003FF4B4 /* ParseTreeListener.h in Headers */,\n\t\t\t\t276E5D9D1CDB57AA003FF4B4 /* BasicState.h in Headers */,\n\t\t\t\t276E5FAA1CDB57AA003FF4B4 /* RuleContext.h in Headers */,\n\t\t\t\t276E60251CDB57AA003FF4B4 /* RuleTagToken.h in Headers */,\n\t\t\t\t276E5EFF1CDB57AA003FF4B4 /* ConsoleErrorListener.h in Headers */,\n\t\t\t\t276E5D311CDB57AA003FF4B4 /* ANTLRErrorStrategy.h in Headers */,\n\t\t\t\t276E5E0C1CDB57AA003FF4B4 /* LexerMoreAction.h in Headers */,\n\t\t\t\t276E5D491CDB57AA003FF4B4 /* ActionTransition.h in Headers */,\n\t\t\t\t276E5E8D1CDB57AA003FF4B4 /* RuleStartState.h in Headers */,\n\t\t\t\t276E5E1E1CDB57AA003FF4B4 /* LexerSkipAction.h in Headers */,\n\t\t\t\t276E5E361CDB57AA003FF4B4 /* LoopEndState.h in Headers */,\n\t\t\t\t276E5D671CDB57AA003FF4B4 /* ATNConfigSet.h in Headers */,\n\t\t\t\t9B25DCEB291028D000DF9703 /* Unicode.h in Headers */,\n\t\t\t\t276E5D371CDB57AA003FF4B4 /* ANTLRFileStream.h in Headers */,\n\t\t\t\t27DB44B41D0463CC007E790B /* XPathLexer.h in Headers */,\n\t\t\t\t276E5D2E1CDB57AA003FF4B4 /* ANTLRErrorListener.h in Headers */,\n\t\t\t\t27B36AC91DACE7AF0069C868 /* RuleContextWithAltNum.h in Headers */,\n\t\t\t\t276E5FC81CDB57AA003FF4B4 /* StringUtils.h in Headers */,\n\t\t\t\t276E5EF31CDB57AA003FF4B4 /* CommonTokenFactory.h in Headers */,\n\t\t\t\t276E5F171CDB57AA003FF4B4 /* DFAState.h in Headers */,\n\t\t\t\t276E5FA41CDB57AA003FF4B4 /* Recognizer.h in Headers */,\n\t\t\t\t276E60731CDB57AA003FF4B4 /* WritableToken.h in Headers */,\n\t\t\t\t9B25DCD0291027EE00DF9703 /* SerializedATNView.h in Headers */,\n\t\t\t\t276E5D3D1CDB57AA003FF4B4 /* ANTLRInputStream.h in Headers */,\n\t\t\t\t276E5FCE1CDB57AA003FF4B4 /* Token.h in Headers */,\n\t\t\t\t9B25DCBF2910278000DF9703 /* PredictionContextType.h in Headers */,\n\t\t\t\t276E60401CDB57AA003FF4B4 /* TerminalNode.h in Headers */,\n\t\t\t\t9B25DCCD291027EE00DF9703 /* SemanticContextType.h in Headers */,\n\t\t\t\t276E5D731CDB57AA003FF4B4 /* ATNDeserializer.h in Headers */,\n\t\t\t\t276E5D851CDB57AA003FF4B4 /* ATNState.h in Headers */,\n\t\t\t\t276E5E7B1CDB57AA003FF4B4 /* PredictionMode.h in Headers */,\n\t\t\t\t276E5EBD1CDB57AA003FF4B4 /* StarLoopEntryState.h in Headers */,\n\t\t\t\t276E5F9E1CDB57AA003FF4B4 /* RecognitionException.h in Headers */,\n\t\t\t\t27745F061CE49C000067C6A3 /* RuntimeMetaData.h in Headers */,\n\t\t\t\t276E5EA51CDB57AA003FF4B4 /* SetTransition.h in Headers */,\n\t\t\t\t276E5F1D1CDB57AA003FF4B4 /* LexerDFASerializer.h in Headers */,\n\t\t\t\t276E5E451CDB57AA003FF4B4 /* OrderedATNConfigSet.h in Headers */,\n\t\t\t\t276E5DF41CDB57AA003FF4B4 /* LexerChannelAction.h in Headers */,\n\t\t\t\t276E5FB01CDB57AA003FF4B4 /* Arrays.h in Headers */,\n\t\t\t\t276E5F801CDB57AA003FF4B4 /* NoViableAltException.h in Headers */,\n\t\t\t\t9B25DCA12910249100DF9703 /* FlatHashSet.h in Headers */,\n\t\t\t\t276E5DE81CDB57AA003FF4B4 /* LexerATNConfig.h in Headers */,\n\t\t\t\t276E60461CDB57AA003FF4B4 /* TerminalNodeImpl.h in Headers */,\n\t\t\t\t9B25DCB92910278000DF9703 /* PredictionContextCache.h in Headers */,\n\t\t\t\t276E5FF21CDB57AA003FF4B4 /* ErrorNodeImpl.h in Headers */,\n\t\t\t\t276E5EC31CDB57AA003FF4B4 /* TokensStartState.h in Headers */,\n\t\t\t\t276E5F291CDB57AA003FF4B4 /* Exceptions.h in Headers */,\n\t\t\t\t276E5F231CDB57AA003FF4B4 /* DiagnosticErrorListener.h in Headers */,\n\t\t\t\t27DB449E1D045537007E790B /* XPath.h in Headers */,\n\t\t\t\t276E5E121CDB57AA003FF4B4 /* LexerPopModeAction.h in Headers */,\n\t\t\t\t276E5ED51CDB57AA003FF4B4 /* BailErrorStrategy.h in Headers */,\n\t\t\t\t276E5DCD1CDB57AA003FF4B4 /* EpsilonTransition.h in Headers */,\n\t\t\t\t276E5FBC1CDB57AA003FF4B4 /* Declarations.h in Headers */,\n\t\t\t\t276E600A1CDB57AA003FF4B4 /* ParseTreeWalker.h in Headers */,\n\t\t\t\t276E5E751CDB57AA003FF4B4 /* PredictionContext.h in Headers */,\n\t\t\t\t276E60131CDB57AA003FF4B4 /* ParseTreeMatch.h in Headers */,\n\t\t\t\t276E5F561CDB57AA003FF4B4 /* LexerNoViableAltException.h in Headers */,\n\t\t\t\t9B25DCEE291028D000DF9703 /* Utf8.h in Headers */,\n\t\t\t\t276E5D7F1CDB57AA003FF4B4 /* ATNSimulator.h in Headers */,\n\t\t\t\t276E602B1CDB57AA003FF4B4 /* TagChunk.h in Headers */,\n\t\t\t\t276E5E931CDB57AA003FF4B4 /* RuleStopState.h in Headers */,\n\t\t\t\t276E5F741CDB57AA003FF4B4 /* Predicate.h in Headers */,\n\t\t\t\t276E5F921CDB57AA003FF4B4 /* ParserRuleContext.h in Headers */,\n\t\t\t\t9B25DCE12910287000DF9703 /* Synchronization.h in Headers */,\n\t\t\t\t276E5FEC1CDB57AA003FF4B4 /* ErrorNode.h in Headers */,\n\t\t\t\t9B25DCB0291026DE00DF9703 /* ParserATNSimulatorOptions.h in Headers */,\n\t\t\t\t276E5EB71CDB57AA003FF4B4 /* StarLoopbackState.h in Headers */,\n\t\t\t\t276E5E5D1CDB57AA003FF4B4 /* PlusLoopbackState.h in Headers */,\n\t\t\t\t276E5E061CDB57AA003FF4B4 /* LexerModeAction.h in Headers */,\n\t\t\t\t276E5E571CDB57AA003FF4B4 /* PlusBlockStartState.h in Headers */,\n\t\t\t\t276E5D911CDB57AA003FF4B4 /* AtomTransition.h in Headers */,\n\t\t\t\t276E5F501CDB57AA003FF4B4 /* LexerInterpreter.h in Headers */,\n\t\t\t\t27DB44AE1D045537007E790B /* XPathWildcardElement.h in Headers */,\n\t\t\t\t276E5F2F1CDB57AA003FF4B4 /* FailedPredicateException.h in Headers */,\n\t\t\t\t9B25DCA42910249100DF9703 /* FlatHashMap.h in Headers */,\n\t\t\t\t276E5E301CDB57AA003FF4B4 /* LookaheadEventInfo.h in Headers */,\n\t\t\t\t276E5F0B1CDB57AA003FF4B4 /* DFA.h in Headers */,\n\t\t\t\t276E606D1CDB57AA003FF4B4 /* Vocabulary.h in Headers */,\n\t\t\t\t276E60521CDB57AA003FF4B4 /* Trees.h in Headers */,\n\t\t\t\t9B25DCAC291025B700DF9703 /* ATNStateType.h in Headers */,\n\t\t\t\t276E5FB31CDB57AA003FF4B4 /* BitSet.h in Headers */,\n\t\t\t\t27DB44AA1D045537007E790B /* XPathTokenElement.h in Headers */,\n\t\t\t\t276E5F981CDB57AA003FF4B4 /* ProxyErrorListener.h in Headers */,\n\t\t\t\t276E5E3F1CDB57AA003FF4B4 /* NotSetTransition.h in Headers */,\n\t\t\t\t276E5E871CDB57AA003FF4B4 /* RangeTransition.h in Headers */,\n\t\t\t\t276E60191CDB57AA003FF4B4 /* ParseTreePattern.h in Headers */,\n\t\t\t\t27D414551DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.h in Headers */,\n\t\t\t\t276E5DFA1CDB57AA003FF4B4 /* LexerCustomAction.h in Headers */,\n\t\t\t\t276E5FE61CDB57AA003FF4B4 /* TokenStreamRewriter.h in Headers */,\n\t\t\t\t276E5DEE1CDB57AA003FF4B4 /* LexerATNSimulator.h in Headers */,\n\t\t\t\t27DB44A61D045537007E790B /* XPathRuleElement.h in Headers */,\n\t\t\t\t276E5DD31CDB57AA003FF4B4 /* ErrorInfo.h in Headers */,\n\t\t\t\t276E5E241CDB57AA003FF4B4 /* LexerTypeAction.h in Headers */,\n\t\t\t\t276E5DE21CDB57AA003FF4B4 /* LexerActionType.h in Headers */,\n\t\t\t\t276E5D4F1CDB57AA003FF4B4 /* AmbiguityInfo.h in Headers */,\n\t\t\t\t276E5E6F1CDB57AA003FF4B4 /* PredicateTransition.h in Headers */,\n\t\t\t\t276E5EE71CDB57AA003FF4B4 /* CharStream.h in Headers */,\n\t\t\t\t276E60041CDB57AA003FF4B4 /* ParseTreeVisitor.h in Headers */,\n\t\t\t\t276E5D551CDB57AA003FF4B4 /* ArrayPredictionContext.h in Headers */,\n\t\t\t\t276E5E511CDB57AA003FF4B4 /* ParserATNSimulator.h in Headers */,\n\t\t\t\t2794D8561CE7821B00FADD0F /* antlr4-common.h in Headers */,\n\t\t\t\t276E60641CDB57AA003FF4B4 /* UnbufferedTokenStream.h in Headers */,\n\t\t\t\t276E5F681CDB57AA003FF4B4 /* IntervalSet.h in Headers */,\n\t\t\t\t276E5E631CDB57AA003FF4B4 /* PrecedencePredicateTransition.h in Headers */,\n\t\t\t\t276E5F051CDB57AA003FF4B4 /* DefaultErrorStrategy.h in Headers */,\n\t\t\t\t276E5F3B1CDB57AA003FF4B4 /* InterpreterRuleContext.h in Headers */,\n\t\t\t\t276E5F111CDB57AA003FF4B4 /* DFASerializer.h in Headers */,\n\t\t\t\t276E5F351CDB57AA003FF4B4 /* InputMismatchException.h in Headers */,\n\t\t\t\t276E5FDA1CDB57AA003FF4B4 /* TokenSource.h in Headers */,\n\t\t\t\t276E5ECF1CDB57AA003FF4B4 /* WildcardTransition.h in Headers */,\n\t\t\t\t276E600D1CDB57AA003FF4B4 /* Chunk.h in Headers */,\n\t\t\t\t276E5FB91CDB57AA003FF4B4 /* CPPUtils.h in Headers */,\n\t\t\t\t276E5EE11CDB57AA003FF4B4 /* BufferedTokenStream.h in Headers */,\n\t\t\t\t9B25DCC52910278000DF9703 /* PredictionContextMergeCacheOptions.h in Headers */,\n\t\t\t\t276E5DAF1CDB57AA003FF4B4 /* ContextSensitivityInfo.h in Headers */,\n\t\t\t\t276E5E001CDB57AA003FF4B4 /* LexerIndexedCustomAction.h in Headers */,\n\t\t\t\t27DB44A81D045537007E790B /* XPathTokenAnywhereElement.h in Headers */,\n\t\t\t\t276E5FD41CDB57AA003FF4B4 /* TokenFactory.h in Headers */,\n\t\t\t\t276E5EF91CDB57AA003FF4B4 /* CommonTokenStream.h in Headers */,\n\t\t\t\t27F4A8561D4CEB2A00E067EE /* Any.h in Headers */,\n\t\t\t\t276E5EB11CDB57AA003FF4B4 /* StarBlockStartState.h in Headers */,\n\t\t\t\t276E5F6E1CDB57AA003FF4B4 /* MurmurHash.h in Headers */,\n\t\t\t\t276E601F1CDB57AA003FF4B4 /* ParseTreePatternMatcher.h in Headers */,\n\t\t\t\t276E5D611CDB57AA003FF4B4 /* ATNConfig.h in Headers */,\n\t\t\t\t9B25DCE5291028BC00DF9703 /* Casts.h in Headers */,\n\t\t\t\t27DB44A21D045537007E790B /* XPathLexerErrorListener.h in Headers */,\n\t\t\t\t276E5E4B1CDB57AA003FF4B4 /* ParseInfo.h in Headers */,\n\t\t\t\t276E5F861CDB57AA003FF4B4 /* Parser.h in Headers */,\n\t\t\t\t27DB44A01D045537007E790B /* XPathElement.h in Headers */,\n\t\t\t\t276E5DBB1CDB57AA003FF4B4 /* DecisionInfo.h in Headers */,\n\t\t\t\t276E5DC11CDB57AA003FF4B4 /* DecisionState.h in Headers */,\n\t\t\t\t276E5E691CDB57AA003FF4B4 /* PredicateEvalInfo.h in Headers */,\n\t\t\t\t276E5EED1CDB57AA003FF4B4 /* CommonToken.h in Headers */,\n\t\t\t\t9B25DCD82910282B00DF9703 /* TransitionType.h in Headers */,\n\t\t\t\t276E60371CDB57AA003FF4B4 /* TokenTagToken.h in Headers */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXHeadersBuildPhase section */\n\n/* Begin PBXNativeTarget section */\n\t\t270C67EF1CDB4F1E00116E17 /* antlr4_ios */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 270C67F71CDB4F1E00116E17 /* Build configuration list for PBXNativeTarget \"antlr4_ios\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t270C67EB1CDB4F1E00116E17 /* Sources */,\n\t\t\t\t270C67EC1CDB4F1E00116E17 /* Frameworks */,\n\t\t\t\t270C67ED1CDB4F1E00116E17 /* Headers */,\n\t\t\t\t270C67EE1CDB4F1E00116E17 /* Resources */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = antlr4_ios;\n\t\t\tproductName = \"antlrcpp-ios\";\n\t\t\tproductReference = 270C67F01CDB4F1E00116E17 /* antlr4_ios.framework */;\n\t\t\tproductType = \"com.apple.product-type.framework\";\n\t\t};\n\t\t37C147161B4D5A04008EDDDB /* antlr4_static */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 37C147211B4D5A04008EDDDB /* Build configuration list for PBXNativeTarget \"antlr4_static\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t37C147131B4D5A04008EDDDB /* Sources */,\n\t\t\t\t37C147141B4D5A04008EDDDB /* Frameworks */,\n\t\t\t\t37C147151B4D5A04008EDDDB /* Headers */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = antlr4_static;\n\t\t\tproductName = antlrcpp_static;\n\t\t\tproductReference = 37C147171B4D5A04008EDDDB /* libantlr4-runtime.a */;\n\t\t\tproductType = \"com.apple.product-type.library.static\";\n\t\t};\n\t\t37D727A91867AF1E007B6D10 /* antlr4 */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 37D727B71867AF1E007B6D10 /* Build configuration list for PBXNativeTarget \"antlr4\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t37D727A61867AF1E007B6D10 /* Sources */,\n\t\t\t\t37D727A71867AF1E007B6D10 /* Frameworks */,\n\t\t\t\t37D727A81867AF1E007B6D10 /* Headers */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = antlr4;\n\t\t\tproductName = antlrcpp;\n\t\t\tproductReference = 37D727AA1867AF1E007B6D10 /* libantlr4-runtime.dylib */;\n\t\t\tproductType = \"com.apple.product-type.library.dynamic\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t37D727A21867AF1E007B6D10 /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tLastUpgradeCheck = 1240;\n\t\t\t\tORGANIZATIONNAME = ANTLR;\n\t\t\t\tTargetAttributes = {\n\t\t\t\t\t270C67EF1CDB4F1E00116E17 = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 7.3.1;\n\t\t\t\t\t};\n\t\t\t\t\t37C147161B4D5A04008EDDDB = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 6.3.2;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tbuildConfigurationList = 37D727A51867AF1E007B6D10 /* Build configuration list for PBXProject \"antlrcpp\" */;\n\t\t\tcompatibilityVersion = \"Xcode 12.0\";\n\t\t\tdevelopmentRegion = en;\n\t\t\thasScannedForEncodings = 0;\n\t\t\tknownRegions = (\n\t\t\t\ten,\n\t\t\t\tBase,\n\t\t\t);\n\t\t\tmainGroup = 37D727A11867AF1E007B6D10;\n\t\t\tproductRefGroup = 37D727AB1867AF1E007B6D10 /* Products */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\t37D727A91867AF1E007B6D10 /* antlr4 */,\n\t\t\t\t37C147161B4D5A04008EDDDB /* antlr4_static */,\n\t\t\t\t270C67EF1CDB4F1E00116E17 /* antlr4_ios */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\t270C67EE1CDB4F1E00116E17 /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\t270C67EB1CDB4F1E00116E17 /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t276E5F671CDB57AA003FF4B4 /* IntervalSet.cpp in Sources */,\n\t\t\t\t276E5D3C1CDB57AA003FF4B4 /* ANTLRInputStream.cpp in Sources */,\n\t\t\t\t276E5FC71CDB57AA003FF4B4 /* StringUtils.cpp in Sources */,\n\t\t\t\t276E5D361CDB57AA003FF4B4 /* ANTLRFileStream.cpp in Sources */,\n\t\t\t\t276E5D541CDB57AA003FF4B4 /* ArrayPredictionContext.cpp in Sources */,\n\t\t\t\t276E5F0A1CDB57AA003FF4B4 /* DFA.cpp in Sources */,\n\t\t\t\t276E5E231CDB57AA003FF4B4 /* LexerTypeAction.cpp in Sources */,\n\t\t\t\t276E5DB41CDB57AA003FF4B4 /* DecisionEventInfo.cpp in Sources */,\n\t\t\t\t276E60451CDB57AA003FF4B4 /* TerminalNodeImpl.cpp in Sources */,\n\t\t\t\t276E5DD21CDB57AA003FF4B4 /* ErrorInfo.cpp in Sources */,\n\t\t\t\t276E5F551CDB57AA003FF4B4 /* LexerNoViableAltException.cpp in Sources */,\n\t\t\t\t2793DCB81F08099C00A84290 /* LexerAction.cpp in Sources */,\n\t\t\t\t27C375861EA1059C00B5883C /* InterpreterDataReader.cpp in Sources */,\n\t\t\t\t276E5E1D1CDB57AA003FF4B4 /* LexerSkipAction.cpp in Sources */,\n\t\t\t\t276E5D721CDB57AA003FF4B4 /* ATNDeserializer.cpp in Sources */,\n\t\t\t\t2793DC8B1F08087500A84290 /* Chunk.cpp in Sources */,\n\t\t\t\t9B25DCE02910287000DF9703 /* Synchronization.cpp in Sources */,\n\t\t\t\t276E5E2F1CDB57AA003FF4B4 /* LookaheadEventInfo.cpp in Sources */,\n\t\t\t\t276E5DFF1CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp in Sources */,\n\t\t\t\t276E60511CDB57AA003FF4B4 /* Trees.cpp in Sources */,\n\t\t\t\t276E5EB61CDB57AA003FF4B4 /* StarLoopbackState.cpp in Sources */,\n\t\t\t\t276E5E621CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp in Sources */,\n\t\t\t\t276E5E051CDB57AA003FF4B4 /* LexerModeAction.cpp in Sources */,\n\t\t\t\t276E5F491CDB57AA003FF4B4 /* Lexer.cpp in Sources */,\n\t\t\t\t276E5EDA1CDB57AA003FF4B4 /* BaseErrorListener.cpp in Sources */,\n\t\t\t\t27DB44C91D0463DB007E790B /* XPath.cpp in Sources */,\n\t\t\t\t276E5DBA1CDB57AA003FF4B4 /* DecisionInfo.cpp in Sources */,\n\t\t\t\t276E5F611CDB57AA003FF4B4 /* Interval.cpp in Sources */,\n\t\t\t\t276E5F911CDB57AA003FF4B4 /* ParserRuleContext.cpp in Sources */,\n\t\t\t\t276E5E111CDB57AA003FF4B4 /* LexerPopModeAction.cpp in Sources */,\n\t\t\t\t276E5E6E1CDB57AA003FF4B4 /* PredicateTransition.cpp in Sources */,\n\t\t\t\t276E5E7A1CDB57AA003FF4B4 /* PredictionMode.cpp in Sources */,\n\t\t\t\t276E605D1CDB57AA003FF4B4 /* UnbufferedCharStream.cpp in Sources */,\n\t\t\t\t276E5F341CDB57AA003FF4B4 /* InputMismatchException.cpp in Sources */,\n\t\t\t\t27DB44D91D0463DB007E790B /* XPathWildcardElement.cpp in Sources */,\n\t\t\t\t276E5E741CDB57AA003FF4B4 /* PredictionContext.cpp in Sources */,\n\t\t\t\t27DB44CB1D0463DB007E790B /* XPathElement.cpp in Sources */,\n\t\t\t\t276E5E171CDB57AA003FF4B4 /* LexerPushModeAction.cpp in Sources */,\n\t\t\t\t276E5EF21CDB57AA003FF4B4 /* CommonTokenFactory.cpp in Sources */,\n\t\t\t\t276E5DF31CDB57AA003FF4B4 /* LexerChannelAction.cpp in Sources */,\n\t\t\t\t276E60631CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp in Sources */,\n\t\t\t\t276E5DDB1CDB57AA003FF4B4 /* LexerActionExecutor.cpp in Sources */,\n\t\t\t\t2793DCAF1F08095F00A84290 /* WritableToken.cpp in Sources */,\n\t\t\t\t276E5E9E1CDB57AA003FF4B4 /* SemanticContext.cpp in Sources */,\n\t\t\t\t276E5EC81CDB57AA003FF4B4 /* Transition.cpp in Sources */,\n\t\t\t\t276E601E1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp in Sources */,\n\t\t\t\t276E5F221CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp in Sources */,\n\t\t\t\t276E5D481CDB57AA003FF4B4 /* ActionTransition.cpp in Sources */,\n\t\t\t\t276E5ED41CDB57AA003FF4B4 /* BailErrorStrategy.cpp in Sources */,\n\t\t\t\t2793DC9B1F0808E100A84290 /* ParseTreeVisitor.cpp in Sources */,\n\t\t\t\t2793DCAC1F08095F00A84290 /* Token.cpp in Sources */,\n\t\t\t\t276E5FA31CDB57AA003FF4B4 /* Recognizer.cpp in Sources */,\n\t\t\t\t276E5D6C1CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp in Sources */,\n\t\t\t\t276E60361CDB57AA003FF4B4 /* TokenTagToken.cpp in Sources */,\n\t\t\t\t27DB44D51D0463DB007E790B /* XPathTokenElement.cpp in Sources */,\n\t\t\t\t27DB44D11D0463DB007E790B /* XPathRuleElement.cpp in Sources */,\n\t\t\t\t276E5DED1CDB57AA003FF4B4 /* LexerATNSimulator.cpp in Sources */,\n\t\t\t\t276E606C1CDB57AA003FF4B4 /* Vocabulary.cpp in Sources */,\n\t\t\t\t276E5F1C1CDB57AA003FF4B4 /* LexerDFASerializer.cpp in Sources */,\n\t\t\t\t276E60181CDB57AA003FF4B4 /* ParseTreePattern.cpp in Sources */,\n\t\t\t\t276E5DE71CDB57AA003FF4B4 /* LexerATNConfig.cpp in Sources */,\n\t\t\t\t27B36AC81DACE7AF0069C868 /* RuleContextWithAltNum.cpp in Sources */,\n\t\t\t\t9B25DCC42910278000DF9703 /* PredictionContextCache.cpp in Sources */,\n\t\t\t\t276E5F101CDB57AA003FF4B4 /* DFASerializer.cpp in Sources */,\n\t\t\t\t276E5F2E1CDB57AA003FF4B4 /* FailedPredicateException.cpp in Sources */,\n\t\t\t\t27D414541DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp in Sources */,\n\t\t\t\t276E5F8B1CDB57AA003FF4B4 /* ParserInterpreter.cpp in Sources */,\n\t\t\t\t276E5D4E1CDB57AA003FF4B4 /* AmbiguityInfo.cpp in Sources */,\n\t\t\t\t276E5F161CDB57AA003FF4B4 /* DFAState.cpp in Sources */,\n\t\t\t\t276E60091CDB57AA003FF4B4 /* ParseTreeWalker.cpp in Sources */,\n\t\t\t\t27DB44CD1D0463DB007E790B /* XPathLexerErrorListener.cpp in Sources */,\n\t\t\t\t276E5F9D1CDB57AA003FF4B4 /* RecognitionException.cpp in Sources */,\n\t\t\t\t276E5EA41CDB57AA003FF4B4 /* SetTransition.cpp in Sources */,\n\t\t\t\t276E5D841CDB57AA003FF4B4 /* ATNState.cpp in Sources */,\n\t\t\t\t276E60241CDB57AA003FF4B4 /* RuleTagToken.cpp in Sources */,\n\t\t\t\t276E5E501CDB57AA003FF4B4 /* ParserATNSimulator.cpp in Sources */,\n\t\t\t\t276E602A1CDB57AA003FF4B4 /* TagChunk.cpp in Sources */,\n\t\t\t\t276E5F7F1CDB57AA003FF4B4 /* NoViableAltException.cpp in Sources */,\n\t\t\t\t27745F051CE49C000067C6A3 /* RuntimeMetaData.cpp in Sources */,\n\t\t\t\t276E5DAE1CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp in Sources */,\n\t\t\t\t2793DCA61F08095F00A84290 /* ANTLRErrorListener.cpp in Sources */,\n\t\t\t\t276E5D661CDB57AA003FF4B4 /* ATNConfigSet.cpp in Sources */,\n\t\t\t\t2793DC9F1F08090D00A84290 /* Any.cpp in Sources */,\n\t\t\t\t276E5FAF1CDB57AA003FF4B4 /* Arrays.cpp in Sources */,\n\t\t\t\t276E5ECE1CDB57AA003FF4B4 /* WildcardTransition.cpp in Sources */,\n\t\t\t\t276E5E861CDB57AA003FF4B4 /* RangeTransition.cpp in Sources */,\n\t\t\t\t276E5D7E1CDB57AA003FF4B4 /* ATNSimulator.cpp in Sources */,\n\t\t\t\t276E5E801CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp in Sources */,\n\t\t\t\t2793DCA91F08095F00A84290 /* ANTLRErrorStrategy.cpp in Sources */,\n\t\t\t\t276E5F401CDB57AA003FF4B4 /* IntStream.cpp in Sources */,\n\t\t\t\t276E5F5B1CDB57AA003FF4B4 /* ListTokenSource.cpp in Sources */,\n\t\t\t\t276E5F6D1CDB57AA003FF4B4 /* MurmurHash.cpp in Sources */,\n\t\t\t\t276E5FDF1CDB57AA003FF4B4 /* TokenStream.cpp in Sources */,\n\t\t\t\t276E5FF11CDB57AA003FF4B4 /* ErrorNodeImpl.cpp in Sources */,\n\t\t\t\t27DB44D71D0463DB007E790B /* XPathWildcardAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5E4A1CDB57AA003FF4B4 /* ParseInfo.cpp in Sources */,\n\t\t\t\t276E5E3E1CDB57AA003FF4B4 /* NotSetTransition.cpp in Sources */,\n\t\t\t\t27DB44B31D0463CC007E790B /* XPathLexer.cpp in Sources */,\n\t\t\t\t276E60301CDB57AA003FF4B4 /* TextChunk.cpp in Sources */,\n\t\t\t\t27DB44CF1D0463DB007E790B /* XPathRuleAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5E441CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp in Sources */,\n\t\t\t\t276E5DCC1CDB57AA003FF4B4 /* EpsilonTransition.cpp in Sources */,\n\t\t\t\t2793DC8F1F08088F00A84290 /* ParseTreeListener.cpp in Sources */,\n\t\t\t\t276E5D5A1CDB57AA003FF4B4 /* ATN.cpp in Sources */,\n\t\t\t\t276E5EE61CDB57AA003FF4B4 /* CharStream.cpp in Sources */,\n\t\t\t\t276E5EE01CDB57AA003FF4B4 /* BufferedTokenStream.cpp in Sources */,\n\t\t\t\t9B25DCCA2910278000DF9703 /* PredictionContextMergeCache.cpp in Sources */,\n\t\t\t\t276E5F041CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp in Sources */,\n\t\t\t\t276E5FE51CDB57AA003FF4B4 /* TokenStreamRewriter.cpp in Sources */,\n\t\t\t\t9B25DCD72910282B00DF9703 /* TransitionType.cpp in Sources */,\n\t\t\t\t276E5FA91CDB57AA003FF4B4 /* RuleContext.cpp in Sources */,\n\t\t\t\t276E5D601CDB57AA003FF4B4 /* ATNConfig.cpp in Sources */,\n\t\t\t\t276E5EFE1CDB57AA003FF4B4 /* ConsoleErrorListener.cpp in Sources */,\n\t\t\t\t276E5EAA1CDB57AA003FF4B4 /* SingletonPredictionContext.cpp in Sources */,\n\t\t\t\t9B25DCF3291028D000DF9703 /* Utf8.cpp in Sources */,\n\t\t\t\t276E5E681CDB57AA003FF4B4 /* PredicateEvalInfo.cpp in Sources */,\n\t\t\t\t276E5F281CDB57AA003FF4B4 /* Exceptions.cpp in Sources */,\n\t\t\t\t276E5F851CDB57AA003FF4B4 /* Parser.cpp in Sources */,\n\t\t\t\t276E5DC01CDB57AA003FF4B4 /* DecisionState.cpp in Sources */,\n\t\t\t\t276E5E981CDB57AA003FF4B4 /* RuleTransition.cpp in Sources */,\n\t\t\t\t276E5EF81CDB57AA003FF4B4 /* CommonTokenStream.cpp in Sources */,\n\t\t\t\t2793DC871F08083F00A84290 /* TokenSource.cpp in Sources */,\n\t\t\t\t276E60121CDB57AA003FF4B4 /* ParseTreeMatch.cpp in Sources */,\n\t\t\t\t276566E21DA93BFB000869BE /* ParseTree.cpp in Sources */,\n\t\t\t\t276E5EEC1CDB57AA003FF4B4 /* CommonToken.cpp in Sources */,\n\t\t\t\t276E5D901CDB57AA003FF4B4 /* AtomTransition.cpp in Sources */,\n\t\t\t\t276E5E0B1CDB57AA003FF4B4 /* LexerMoreAction.cpp in Sources */,\n\t\t\t\t276E5F3A1CDB57AA003FF4B4 /* InterpreterRuleContext.cpp in Sources */,\n\t\t\t\t276E5F971CDB57AA003FF4B4 /* ProxyErrorListener.cpp in Sources */,\n\t\t\t\t276E5DF91CDB57AA003FF4B4 /* LexerCustomAction.cpp in Sources */,\n\t\t\t\t276E5F4F1CDB57AA003FF4B4 /* LexerInterpreter.cpp in Sources */,\n\t\t\t\t276E5E291CDB57AA003FF4B4 /* LL1Analyzer.cpp in Sources */,\n\t\t\t\t27DB44D31D0463DB007E790B /* XPathTokenAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5FB81CDB57AA003FF4B4 /* CPPUtils.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37C147131B4D5A04008EDDDB /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t276E5F661CDB57AA003FF4B4 /* IntervalSet.cpp in Sources */,\n\t\t\t\t276E5D3B1CDB57AA003FF4B4 /* ANTLRInputStream.cpp in Sources */,\n\t\t\t\t276E5FC61CDB57AA003FF4B4 /* StringUtils.cpp in Sources */,\n\t\t\t\t276E5D351CDB57AA003FF4B4 /* ANTLRFileStream.cpp in Sources */,\n\t\t\t\t276E5D531CDB57AA003FF4B4 /* ArrayPredictionContext.cpp in Sources */,\n\t\t\t\t276E5F091CDB57AA003FF4B4 /* DFA.cpp in Sources */,\n\t\t\t\t276E5E221CDB57AA003FF4B4 /* LexerTypeAction.cpp in Sources */,\n\t\t\t\t276E5DB31CDB57AA003FF4B4 /* DecisionEventInfo.cpp in Sources */,\n\t\t\t\t276E60441CDB57AA003FF4B4 /* TerminalNodeImpl.cpp in Sources */,\n\t\t\t\t276E5DD11CDB57AA003FF4B4 /* ErrorInfo.cpp in Sources */,\n\t\t\t\t276E5F541CDB57AA003FF4B4 /* LexerNoViableAltException.cpp in Sources */,\n\t\t\t\t2793DCB71F08099C00A84290 /* LexerAction.cpp in Sources */,\n\t\t\t\t27C375851EA1059C00B5883C /* InterpreterDataReader.cpp in Sources */,\n\t\t\t\t276E5E1C1CDB57AA003FF4B4 /* LexerSkipAction.cpp in Sources */,\n\t\t\t\t276E5D711CDB57AA003FF4B4 /* ATNDeserializer.cpp in Sources */,\n\t\t\t\t2793DC8A1F08087500A84290 /* Chunk.cpp in Sources */,\n\t\t\t\t9B25DCDF2910287000DF9703 /* Synchronization.cpp in Sources */,\n\t\t\t\t276E5E2E1CDB57AA003FF4B4 /* LookaheadEventInfo.cpp in Sources */,\n\t\t\t\t276E5DFE1CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp in Sources */,\n\t\t\t\t276E60501CDB57AA003FF4B4 /* Trees.cpp in Sources */,\n\t\t\t\t276E5EB51CDB57AA003FF4B4 /* StarLoopbackState.cpp in Sources */,\n\t\t\t\t276E5E611CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp in Sources */,\n\t\t\t\t276E5E041CDB57AA003FF4B4 /* LexerModeAction.cpp in Sources */,\n\t\t\t\t276E5F481CDB57AA003FF4B4 /* Lexer.cpp in Sources */,\n\t\t\t\t276E5ED91CDB57AA003FF4B4 /* BaseErrorListener.cpp in Sources */,\n\t\t\t\t27DB44B71D0463DA007E790B /* XPath.cpp in Sources */,\n\t\t\t\t276E5DB91CDB57AA003FF4B4 /* DecisionInfo.cpp in Sources */,\n\t\t\t\t276E5F601CDB57AA003FF4B4 /* Interval.cpp in Sources */,\n\t\t\t\t276E5F901CDB57AA003FF4B4 /* ParserRuleContext.cpp in Sources */,\n\t\t\t\t276E5E101CDB57AA003FF4B4 /* LexerPopModeAction.cpp in Sources */,\n\t\t\t\t276E5E6D1CDB57AA003FF4B4 /* PredicateTransition.cpp in Sources */,\n\t\t\t\t276E5E791CDB57AA003FF4B4 /* PredictionMode.cpp in Sources */,\n\t\t\t\t276E605C1CDB57AA003FF4B4 /* UnbufferedCharStream.cpp in Sources */,\n\t\t\t\t276E5F331CDB57AA003FF4B4 /* InputMismatchException.cpp in Sources */,\n\t\t\t\t27DB44C71D0463DA007E790B /* XPathWildcardElement.cpp in Sources */,\n\t\t\t\t276E5E731CDB57AA003FF4B4 /* PredictionContext.cpp in Sources */,\n\t\t\t\t27DB44B91D0463DA007E790B /* XPathElement.cpp in Sources */,\n\t\t\t\t276E5E161CDB57AA003FF4B4 /* LexerPushModeAction.cpp in Sources */,\n\t\t\t\t276E5EF11CDB57AA003FF4B4 /* CommonTokenFactory.cpp in Sources */,\n\t\t\t\t276E5DF21CDB57AA003FF4B4 /* LexerChannelAction.cpp in Sources */,\n\t\t\t\t276E60621CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp in Sources */,\n\t\t\t\t276E5DDA1CDB57AA003FF4B4 /* LexerActionExecutor.cpp in Sources */,\n\t\t\t\t2793DCAE1F08095F00A84290 /* WritableToken.cpp in Sources */,\n\t\t\t\t276E5E9D1CDB57AA003FF4B4 /* SemanticContext.cpp in Sources */,\n\t\t\t\t276E5EC71CDB57AA003FF4B4 /* Transition.cpp in Sources */,\n\t\t\t\t276E601D1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp in Sources */,\n\t\t\t\t276E5F211CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp in Sources */,\n\t\t\t\t276E5D471CDB57AA003FF4B4 /* ActionTransition.cpp in Sources */,\n\t\t\t\t276E5ED31CDB57AA003FF4B4 /* BailErrorStrategy.cpp in Sources */,\n\t\t\t\t2793DC9A1F0808E100A84290 /* ParseTreeVisitor.cpp in Sources */,\n\t\t\t\t2793DCAB1F08095F00A84290 /* Token.cpp in Sources */,\n\t\t\t\t276E5FA21CDB57AA003FF4B4 /* Recognizer.cpp in Sources */,\n\t\t\t\t276E5D6B1CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp in Sources */,\n\t\t\t\t276E60351CDB57AA003FF4B4 /* TokenTagToken.cpp in Sources */,\n\t\t\t\t27DB44C31D0463DA007E790B /* XPathTokenElement.cpp in Sources */,\n\t\t\t\t27DB44BF1D0463DA007E790B /* XPathRuleElement.cpp in Sources */,\n\t\t\t\t276E5DEC1CDB57AA003FF4B4 /* LexerATNSimulator.cpp in Sources */,\n\t\t\t\t276E606B1CDB57AA003FF4B4 /* Vocabulary.cpp in Sources */,\n\t\t\t\t276E5F1B1CDB57AA003FF4B4 /* LexerDFASerializer.cpp in Sources */,\n\t\t\t\t276E60171CDB57AA003FF4B4 /* ParseTreePattern.cpp in Sources */,\n\t\t\t\t276E5DE61CDB57AA003FF4B4 /* LexerATNConfig.cpp in Sources */,\n\t\t\t\t27B36AC71DACE7AF0069C868 /* RuleContextWithAltNum.cpp in Sources */,\n\t\t\t\t9B25DCC32910278000DF9703 /* PredictionContextCache.cpp in Sources */,\n\t\t\t\t276E5F0F1CDB57AA003FF4B4 /* DFASerializer.cpp in Sources */,\n\t\t\t\t276E5F2D1CDB57AA003FF4B4 /* FailedPredicateException.cpp in Sources */,\n\t\t\t\t27D414531DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp in Sources */,\n\t\t\t\t276E5F8A1CDB57AA003FF4B4 /* ParserInterpreter.cpp in Sources */,\n\t\t\t\t276E5D4D1CDB57AA003FF4B4 /* AmbiguityInfo.cpp in Sources */,\n\t\t\t\t276E5F151CDB57AA003FF4B4 /* DFAState.cpp in Sources */,\n\t\t\t\t276E60081CDB57AA003FF4B4 /* ParseTreeWalker.cpp in Sources */,\n\t\t\t\t27DB44BB1D0463DA007E790B /* XPathLexerErrorListener.cpp in Sources */,\n\t\t\t\t276E5F9C1CDB57AA003FF4B4 /* RecognitionException.cpp in Sources */,\n\t\t\t\t276E5EA31CDB57AA003FF4B4 /* SetTransition.cpp in Sources */,\n\t\t\t\t276E5D831CDB57AA003FF4B4 /* ATNState.cpp in Sources */,\n\t\t\t\t276E60231CDB57AA003FF4B4 /* RuleTagToken.cpp in Sources */,\n\t\t\t\t276E5E4F1CDB57AA003FF4B4 /* ParserATNSimulator.cpp in Sources */,\n\t\t\t\t276E60291CDB57AA003FF4B4 /* TagChunk.cpp in Sources */,\n\t\t\t\t276E5F7E1CDB57AA003FF4B4 /* NoViableAltException.cpp in Sources */,\n\t\t\t\t27745F041CE49C000067C6A3 /* RuntimeMetaData.cpp in Sources */,\n\t\t\t\t276E5DAD1CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp in Sources */,\n\t\t\t\t2793DCA51F08095F00A84290 /* ANTLRErrorListener.cpp in Sources */,\n\t\t\t\t276E5D651CDB57AA003FF4B4 /* ATNConfigSet.cpp in Sources */,\n\t\t\t\t2793DC9E1F08090D00A84290 /* Any.cpp in Sources */,\n\t\t\t\t276E5FAE1CDB57AA003FF4B4 /* Arrays.cpp in Sources */,\n\t\t\t\t276E5ECD1CDB57AA003FF4B4 /* WildcardTransition.cpp in Sources */,\n\t\t\t\t276E5E851CDB57AA003FF4B4 /* RangeTransition.cpp in Sources */,\n\t\t\t\t276E5D7D1CDB57AA003FF4B4 /* ATNSimulator.cpp in Sources */,\n\t\t\t\t276E5E7F1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp in Sources */,\n\t\t\t\t2793DCA81F08095F00A84290 /* ANTLRErrorStrategy.cpp in Sources */,\n\t\t\t\t276E5F3F1CDB57AA003FF4B4 /* IntStream.cpp in Sources */,\n\t\t\t\t276E5F5A1CDB57AA003FF4B4 /* ListTokenSource.cpp in Sources */,\n\t\t\t\t276E5F6C1CDB57AA003FF4B4 /* MurmurHash.cpp in Sources */,\n\t\t\t\t276E5FDE1CDB57AA003FF4B4 /* TokenStream.cpp in Sources */,\n\t\t\t\t276E5FF01CDB57AA003FF4B4 /* ErrorNodeImpl.cpp in Sources */,\n\t\t\t\t27DB44C51D0463DA007E790B /* XPathWildcardAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5E491CDB57AA003FF4B4 /* ParseInfo.cpp in Sources */,\n\t\t\t\t276E5E3D1CDB57AA003FF4B4 /* NotSetTransition.cpp in Sources */,\n\t\t\t\t27DB44B21D0463CC007E790B /* XPathLexer.cpp in Sources */,\n\t\t\t\t276E602F1CDB57AA003FF4B4 /* TextChunk.cpp in Sources */,\n\t\t\t\t27DB44BD1D0463DA007E790B /* XPathRuleAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5E431CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp in Sources */,\n\t\t\t\t276E5DCB1CDB57AA003FF4B4 /* EpsilonTransition.cpp in Sources */,\n\t\t\t\t2793DC8E1F08088F00A84290 /* ParseTreeListener.cpp in Sources */,\n\t\t\t\t276E5D591CDB57AA003FF4B4 /* ATN.cpp in Sources */,\n\t\t\t\t276E5EE51CDB57AA003FF4B4 /* CharStream.cpp in Sources */,\n\t\t\t\t276E5EDF1CDB57AA003FF4B4 /* BufferedTokenStream.cpp in Sources */,\n\t\t\t\t9B25DCC92910278000DF9703 /* PredictionContextMergeCache.cpp in Sources */,\n\t\t\t\t276E5F031CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp in Sources */,\n\t\t\t\t276E5FE41CDB57AA003FF4B4 /* TokenStreamRewriter.cpp in Sources */,\n\t\t\t\t9B25DCD62910282B00DF9703 /* TransitionType.cpp in Sources */,\n\t\t\t\t276E5FA81CDB57AA003FF4B4 /* RuleContext.cpp in Sources */,\n\t\t\t\t276E5D5F1CDB57AA003FF4B4 /* ATNConfig.cpp in Sources */,\n\t\t\t\t276E5EFD1CDB57AA003FF4B4 /* ConsoleErrorListener.cpp in Sources */,\n\t\t\t\t276E5EA91CDB57AA003FF4B4 /* SingletonPredictionContext.cpp in Sources */,\n\t\t\t\t9B25DCF2291028D000DF9703 /* Utf8.cpp in Sources */,\n\t\t\t\t276E5E671CDB57AA003FF4B4 /* PredicateEvalInfo.cpp in Sources */,\n\t\t\t\t276E5F271CDB57AA003FF4B4 /* Exceptions.cpp in Sources */,\n\t\t\t\t276E5F841CDB57AA003FF4B4 /* Parser.cpp in Sources */,\n\t\t\t\t276E5DBF1CDB57AA003FF4B4 /* DecisionState.cpp in Sources */,\n\t\t\t\t276E5E971CDB57AA003FF4B4 /* RuleTransition.cpp in Sources */,\n\t\t\t\t276E5EF71CDB57AA003FF4B4 /* CommonTokenStream.cpp in Sources */,\n\t\t\t\t2793DC861F08083F00A84290 /* TokenSource.cpp in Sources */,\n\t\t\t\t276E60111CDB57AA003FF4B4 /* ParseTreeMatch.cpp in Sources */,\n\t\t\t\t276566E11DA93BFB000869BE /* ParseTree.cpp in Sources */,\n\t\t\t\t276E5EEB1CDB57AA003FF4B4 /* CommonToken.cpp in Sources */,\n\t\t\t\t276E5D8F1CDB57AA003FF4B4 /* AtomTransition.cpp in Sources */,\n\t\t\t\t276E5E0A1CDB57AA003FF4B4 /* LexerMoreAction.cpp in Sources */,\n\t\t\t\t276E5F391CDB57AA003FF4B4 /* InterpreterRuleContext.cpp in Sources */,\n\t\t\t\t276E5F961CDB57AA003FF4B4 /* ProxyErrorListener.cpp in Sources */,\n\t\t\t\t276E5DF81CDB57AA003FF4B4 /* LexerCustomAction.cpp in Sources */,\n\t\t\t\t276E5F4E1CDB57AA003FF4B4 /* LexerInterpreter.cpp in Sources */,\n\t\t\t\t276E5E281CDB57AA003FF4B4 /* LL1Analyzer.cpp in Sources */,\n\t\t\t\t27DB44C11D0463DA007E790B /* XPathTokenAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5FB71CDB57AA003FF4B4 /* CPPUtils.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t37D727A61867AF1E007B6D10 /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t276E5F651CDB57AA003FF4B4 /* IntervalSet.cpp in Sources */,\n\t\t\t\t276E5D3A1CDB57AA003FF4B4 /* ANTLRInputStream.cpp in Sources */,\n\t\t\t\t276E5FC51CDB57AA003FF4B4 /* StringUtils.cpp in Sources */,\n\t\t\t\t276E5D341CDB57AA003FF4B4 /* ANTLRFileStream.cpp in Sources */,\n\t\t\t\t276E5D521CDB57AA003FF4B4 /* ArrayPredictionContext.cpp in Sources */,\n\t\t\t\t276E5F081CDB57AA003FF4B4 /* DFA.cpp in Sources */,\n\t\t\t\t276E5E211CDB57AA003FF4B4 /* LexerTypeAction.cpp in Sources */,\n\t\t\t\t27DB449F1D045537007E790B /* XPathElement.cpp in Sources */,\n\t\t\t\t276E5DB21CDB57AA003FF4B4 /* DecisionEventInfo.cpp in Sources */,\n\t\t\t\t276E60431CDB57AA003FF4B4 /* TerminalNodeImpl.cpp in Sources */,\n\t\t\t\t276E5DD01CDB57AA003FF4B4 /* ErrorInfo.cpp in Sources */,\n\t\t\t\t2793DCB61F08099C00A84290 /* LexerAction.cpp in Sources */,\n\t\t\t\t276E5F531CDB57AA003FF4B4 /* LexerNoViableAltException.cpp in Sources */,\n\t\t\t\t27C375841EA1059C00B5883C /* InterpreterDataReader.cpp in Sources */,\n\t\t\t\t276E5E1B1CDB57AA003FF4B4 /* LexerSkipAction.cpp in Sources */,\n\t\t\t\t2793DC891F08087500A84290 /* Chunk.cpp in Sources */,\n\t\t\t\t9B25DCDE2910287000DF9703 /* Synchronization.cpp in Sources */,\n\t\t\t\t276E5D701CDB57AA003FF4B4 /* ATNDeserializer.cpp in Sources */,\n\t\t\t\t276E5E2D1CDB57AA003FF4B4 /* LookaheadEventInfo.cpp in Sources */,\n\t\t\t\t276E5DFD1CDB57AA003FF4B4 /* LexerIndexedCustomAction.cpp in Sources */,\n\t\t\t\t276E604F1CDB57AA003FF4B4 /* Trees.cpp in Sources */,\n\t\t\t\t276E5EB41CDB57AA003FF4B4 /* StarLoopbackState.cpp in Sources */,\n\t\t\t\t276E5E601CDB57AA003FF4B4 /* PrecedencePredicateTransition.cpp in Sources */,\n\t\t\t\t27DB44A31D045537007E790B /* XPathRuleAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5E031CDB57AA003FF4B4 /* LexerModeAction.cpp in Sources */,\n\t\t\t\t276E5F471CDB57AA003FF4B4 /* Lexer.cpp in Sources */,\n\t\t\t\t276E5ED81CDB57AA003FF4B4 /* BaseErrorListener.cpp in Sources */,\n\t\t\t\t276E5DB81CDB57AA003FF4B4 /* DecisionInfo.cpp in Sources */,\n\t\t\t\t276E5F5F1CDB57AA003FF4B4 /* Interval.cpp in Sources */,\n\t\t\t\t276E5F8F1CDB57AA003FF4B4 /* ParserRuleContext.cpp in Sources */,\n\t\t\t\t276E5E0F1CDB57AA003FF4B4 /* LexerPopModeAction.cpp in Sources */,\n\t\t\t\t276E5E6C1CDB57AA003FF4B4 /* PredicateTransition.cpp in Sources */,\n\t\t\t\t276E5E781CDB57AA003FF4B4 /* PredictionMode.cpp in Sources */,\n\t\t\t\t276E605B1CDB57AA003FF4B4 /* UnbufferedCharStream.cpp in Sources */,\n\t\t\t\t276E5F321CDB57AA003FF4B4 /* InputMismatchException.cpp in Sources */,\n\t\t\t\t276E5E721CDB57AA003FF4B4 /* PredictionContext.cpp in Sources */,\n\t\t\t\t276E5E151CDB57AA003FF4B4 /* LexerPushModeAction.cpp in Sources */,\n\t\t\t\t276E5EF01CDB57AA003FF4B4 /* CommonTokenFactory.cpp in Sources */,\n\t\t\t\t276E5DF11CDB57AA003FF4B4 /* LexerChannelAction.cpp in Sources */,\n\t\t\t\t276E60611CDB57AA003FF4B4 /* UnbufferedTokenStream.cpp in Sources */,\n\t\t\t\t276E5DD91CDB57AA003FF4B4 /* LexerActionExecutor.cpp in Sources */,\n\t\t\t\t27DB449D1D045537007E790B /* XPath.cpp in Sources */,\n\t\t\t\t2793DCAD1F08095F00A84290 /* WritableToken.cpp in Sources */,\n\t\t\t\t276E5E9C1CDB57AA003FF4B4 /* SemanticContext.cpp in Sources */,\n\t\t\t\t27DB44AD1D045537007E790B /* XPathWildcardElement.cpp in Sources */,\n\t\t\t\t276E5EC61CDB57AA003FF4B4 /* Transition.cpp in Sources */,\n\t\t\t\t276E601C1CDB57AA003FF4B4 /* ParseTreePatternMatcher.cpp in Sources */,\n\t\t\t\t27DB44A51D045537007E790B /* XPathRuleElement.cpp in Sources */,\n\t\t\t\t276E5F201CDB57AA003FF4B4 /* DiagnosticErrorListener.cpp in Sources */,\n\t\t\t\t276E5D461CDB57AA003FF4B4 /* ActionTransition.cpp in Sources */,\n\t\t\t\t2793DC991F0808E100A84290 /* ParseTreeVisitor.cpp in Sources */,\n\t\t\t\t2793DCAA1F08095F00A84290 /* Token.cpp in Sources */,\n\t\t\t\t276E5ED21CDB57AA003FF4B4 /* BailErrorStrategy.cpp in Sources */,\n\t\t\t\t276E5FA11CDB57AA003FF4B4 /* Recognizer.cpp in Sources */,\n\t\t\t\t276E5D6A1CDB57AA003FF4B4 /* ATNDeserializationOptions.cpp in Sources */,\n\t\t\t\t276E60341CDB57AA003FF4B4 /* TokenTagToken.cpp in Sources */,\n\t\t\t\t276E5DEB1CDB57AA003FF4B4 /* LexerATNSimulator.cpp in Sources */,\n\t\t\t\t276E606A1CDB57AA003FF4B4 /* Vocabulary.cpp in Sources */,\n\t\t\t\t276E5F1A1CDB57AA003FF4B4 /* LexerDFASerializer.cpp in Sources */,\n\t\t\t\t276E60161CDB57AA003FF4B4 /* ParseTreePattern.cpp in Sources */,\n\t\t\t\t276E5DE51CDB57AA003FF4B4 /* LexerATNConfig.cpp in Sources */,\n\t\t\t\t27B36AC61DACE7AF0069C868 /* RuleContextWithAltNum.cpp in Sources */,\n\t\t\t\t9B25DCC22910278000DF9703 /* PredictionContextCache.cpp in Sources */,\n\t\t\t\t276E5F0E1CDB57AA003FF4B4 /* DFASerializer.cpp in Sources */,\n\t\t\t\t276E5F2C1CDB57AA003FF4B4 /* FailedPredicateException.cpp in Sources */,\n\t\t\t\t27D414521DEB0D3D00D0F3F9 /* IterativeParseTreeWalker.cpp in Sources */,\n\t\t\t\t27DB44A71D045537007E790B /* XPathTokenAnywhereElement.cpp in Sources */,\n\t\t\t\t276E5F891CDB57AA003FF4B4 /* ParserInterpreter.cpp in Sources */,\n\t\t\t\t276E5D4C1CDB57AA003FF4B4 /* AmbiguityInfo.cpp in Sources */,\n\t\t\t\t276E5F141CDB57AA003FF4B4 /* DFAState.cpp in Sources */,\n\t\t\t\t276E60071CDB57AA003FF4B4 /* ParseTreeWalker.cpp in Sources */,\n\t\t\t\t276E5F9B1CDB57AA003FF4B4 /* RecognitionException.cpp in Sources */,\n\t\t\t\t276E5EA21CDB57AA003FF4B4 /* SetTransition.cpp in Sources */,\n\t\t\t\t276E5D821CDB57AA003FF4B4 /* ATNState.cpp in Sources */,\n\t\t\t\t276E60221CDB57AA003FF4B4 /* RuleTagToken.cpp in Sources */,\n\t\t\t\t276E5E4E1CDB57AA003FF4B4 /* ParserATNSimulator.cpp in Sources */,\n\t\t\t\t276E60281CDB57AA003FF4B4 /* TagChunk.cpp in Sources */,\n\t\t\t\t276E5F7D1CDB57AA003FF4B4 /* NoViableAltException.cpp in Sources */,\n\t\t\t\t27745F031CE49C000067C6A3 /* RuntimeMetaData.cpp in Sources */,\n\t\t\t\t276E5DAC1CDB57AA003FF4B4 /* ContextSensitivityInfo.cpp in Sources */,\n\t\t\t\t2793DCA41F08095F00A84290 /* ANTLRErrorListener.cpp in Sources */,\n\t\t\t\t276E5D641CDB57AA003FF4B4 /* ATNConfigSet.cpp in Sources */,\n\t\t\t\t2793DC9D1F08090D00A84290 /* Any.cpp in Sources */,\n\t\t\t\t276E5FAD1CDB57AA003FF4B4 /* Arrays.cpp in Sources */,\n\t\t\t\t276E5ECC1CDB57AA003FF4B4 /* WildcardTransition.cpp in Sources */,\n\t\t\t\t276E5E841CDB57AA003FF4B4 /* RangeTransition.cpp in Sources */,\n\t\t\t\t276E5D7C1CDB57AA003FF4B4 /* ATNSimulator.cpp in Sources */,\n\t\t\t\t276E5E7E1CDB57AA003FF4B4 /* ProfilingATNSimulator.cpp in Sources */,\n\t\t\t\t2793DCA71F08095F00A84290 /* ANTLRErrorStrategy.cpp in Sources */,\n\t\t\t\t276E5F3E1CDB57AA003FF4B4 /* IntStream.cpp in Sources */,\n\t\t\t\t276E5F591CDB57AA003FF4B4 /* ListTokenSource.cpp in Sources */,\n\t\t\t\t276E5F6B1CDB57AA003FF4B4 /* MurmurHash.cpp in Sources */,\n\t\t\t\t276E5FDD1CDB57AA003FF4B4 /* TokenStream.cpp in Sources */,\n\t\t\t\t276E5FEF1CDB57AA003FF4B4 /* ErrorNodeImpl.cpp in Sources */,\n\t\t\t\t276E5E481CDB57AA003FF4B4 /* ParseInfo.cpp in Sources */,\n\t\t\t\t276E5E3C1CDB57AA003FF4B4 /* NotSetTransition.cpp in Sources */,\n\t\t\t\t276E602E1CDB57AA003FF4B4 /* TextChunk.cpp in Sources */,\n\t\t\t\t276E5E421CDB57AA003FF4B4 /* OrderedATNConfigSet.cpp in Sources */,\n\t\t\t\t276E5DCA1CDB57AA003FF4B4 /* EpsilonTransition.cpp in Sources */,\n\t\t\t\t276E5D581CDB57AA003FF4B4 /* ATN.cpp in Sources */,\n\t\t\t\t276E5EE41CDB57AA003FF4B4 /* CharStream.cpp in Sources */,\n\t\t\t\t27DB44AB1D045537007E790B /* XPathWildcardAnywhereElement.cpp in Sources */,\n\t\t\t\t2793DC8D1F08088F00A84290 /* ParseTreeListener.cpp in Sources */,\n\t\t\t\t276E5EDE1CDB57AA003FF4B4 /* BufferedTokenStream.cpp in Sources */,\n\t\t\t\t276E5F021CDB57AA003FF4B4 /* DefaultErrorStrategy.cpp in Sources */,\n\t\t\t\t276E5FE31CDB57AA003FF4B4 /* TokenStreamRewriter.cpp in Sources */,\n\t\t\t\t9B25DCC82910278000DF9703 /* PredictionContextMergeCache.cpp in Sources */,\n\t\t\t\t27DB44A11D045537007E790B /* XPathLexerErrorListener.cpp in Sources */,\n\t\t\t\t276E5FA71CDB57AA003FF4B4 /* RuleContext.cpp in Sources */,\n\t\t\t\t9B25DCD52910282B00DF9703 /* TransitionType.cpp in Sources */,\n\t\t\t\t27DB44B11D0463CC007E790B /* XPathLexer.cpp in Sources */,\n\t\t\t\t276E5D5E1CDB57AA003FF4B4 /* ATNConfig.cpp in Sources */,\n\t\t\t\t276E5EFC1CDB57AA003FF4B4 /* ConsoleErrorListener.cpp in Sources */,\n\t\t\t\t276E5EA81CDB57AA003FF4B4 /* SingletonPredictionContext.cpp in Sources */,\n\t\t\t\t9B25DCF1291028D000DF9703 /* Utf8.cpp in Sources */,\n\t\t\t\t276E5E661CDB57AA003FF4B4 /* PredicateEvalInfo.cpp in Sources */,\n\t\t\t\t276E5F261CDB57AA003FF4B4 /* Exceptions.cpp in Sources */,\n\t\t\t\t276E5F831CDB57AA003FF4B4 /* Parser.cpp in Sources */,\n\t\t\t\t276E5DBE1CDB57AA003FF4B4 /* DecisionState.cpp in Sources */,\n\t\t\t\t276E5E961CDB57AA003FF4B4 /* RuleTransition.cpp in Sources */,\n\t\t\t\t276E5EF61CDB57AA003FF4B4 /* CommonTokenStream.cpp in Sources */,\n\t\t\t\t2793DC851F08083F00A84290 /* TokenSource.cpp in Sources */,\n\t\t\t\t276E60101CDB57AA003FF4B4 /* ParseTreeMatch.cpp in Sources */,\n\t\t\t\t276566E01DA93BFB000869BE /* ParseTree.cpp in Sources */,\n\t\t\t\t276E5EEA1CDB57AA003FF4B4 /* CommonToken.cpp in Sources */,\n\t\t\t\t276E5D8E1CDB57AA003FF4B4 /* AtomTransition.cpp in Sources */,\n\t\t\t\t276E5E091CDB57AA003FF4B4 /* LexerMoreAction.cpp in Sources */,\n\t\t\t\t276E5F381CDB57AA003FF4B4 /* InterpreterRuleContext.cpp in Sources */,\n\t\t\t\t276E5F951CDB57AA003FF4B4 /* ProxyErrorListener.cpp in Sources */,\n\t\t\t\t276E5DF71CDB57AA003FF4B4 /* LexerCustomAction.cpp in Sources */,\n\t\t\t\t276E5F4D1CDB57AA003FF4B4 /* LexerInterpreter.cpp in Sources */,\n\t\t\t\t276E5E271CDB57AA003FF4B4 /* LL1Analyzer.cpp in Sources */,\n\t\t\t\t27DB44A91D045537007E790B /* XPathTokenElement.cpp in Sources */,\n\t\t\t\t276E5FB61CDB57AA003FF4B4 /* CPPUtils.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin XCBuildConfiguration section */\n\t\t270C67F51CDB4F1E00116E17 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\t\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"\";\n\t\t\t\tCURRENT_PROJECT_VERSION = 1;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tDEFINES_MODULE = YES;\n\t\t\t\tDYLIB_COMPATIBILITY_VERSION = 1;\n\t\t\t\tDYLIB_CURRENT_VERSION = 1;\n\t\t\t\tDYLIB_INSTALL_NAME_BASE = \"@rpath\";\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tINFOPLIST_FILE = \"antlrcpp-ios/Info.plist\";\n\t\t\t\tINSTALL_PATH = \"$(LOCAL_LIBRARY_DIR)/Frameworks\";\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 12.0;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t\t\"@loader_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = YES;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"org.antlr.v4.runtime.antlrcpp-ios\";\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tSDKROOT = iphoneos;\n\t\t\t\tSKIP_INSTALL = YES;\n\t\t\t\tTARGETED_DEVICE_FAMILY = \"1,2\";\n\t\t\t\tVERSIONING_SYSTEM = \"apple-generic\";\n\t\t\t\tVERSION_INFO_PREFIX = \"\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t270C67F61CDB4F1E00116E17 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_ANALYZER_NONNULL = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\t\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tCURRENT_PROJECT_VERSION = 1;\n\t\t\t\tDEFINES_MODULE = YES;\n\t\t\t\tDYLIB_COMPATIBILITY_VERSION = 1;\n\t\t\t\tDYLIB_CURRENT_VERSION = 1;\n\t\t\t\tDYLIB_INSTALL_NAME_BASE = \"@rpath\";\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tINFOPLIST_FILE = \"antlrcpp-ios/Info.plist\";\n\t\t\t\tINSTALL_PATH = \"$(LOCAL_LIBRARY_DIR)/Frameworks\";\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 12.0;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t\t\"@loader_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"org.antlr.v4.runtime.antlrcpp-ios\";\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tSDKROOT = iphoneos;\n\t\t\t\tSKIP_INSTALL = YES;\n\t\t\t\tTARGETED_DEVICE_FAMILY = \"1,2\";\n\t\t\t\tVALIDATE_PRODUCT = YES;\n\t\t\t\tVERSIONING_SYSTEM = \"apple-generic\";\n\t\t\t\tVERSION_INFO_PREFIX = \"\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t37C1471F1B4D5A04008EDDDB /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tEXECUTABLE_PREFIX = lib;\n\t\t\t\tGCC_ENABLE_CPP_EXCEPTIONS = YES;\n\t\t\t\tGCC_ENABLE_CPP_RTTI = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = YES;\n\t\t\t\tPRODUCT_NAME = \"antlr4-runtime\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t37C147201B4D5A04008EDDDB /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tEXECUTABLE_PREFIX = lib;\n\t\t\t\tGCC_ENABLE_CPP_EXCEPTIONS = YES;\n\t\t\t\tGCC_ENABLE_CPP_RTTI = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tPRODUCT_NAME = \"antlr4-runtime\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t37D727B51867AF1E007B6D10 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_ASSIGN_ENUM = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_TESTABILITY = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_ENABLE_OBJC_EXCEPTIONS = YES;\n\t\t\t\tGCC_INLINES_ARE_PRIVATE_EXTERN = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = YES;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_MISSING_NEWLINE = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;\n\t\t\t\tGCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;\n\t\t\t\tGCC_WARN_SIGN_COMPARE = YES;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_LABEL = YES;\n\t\t\t\tGCC_WARN_UNUSED_PARAMETER = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\tsrc/,\n\t\t\t\t\tthirdparty/utfcpp/source/,\n\t\t\t\t\tthirdparty/utfcpp/source/utf8/,\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 11.1;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t37D727B61867AF1E007B6D10 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++17\";\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_ASSIGN_ENUM = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\tCOPY_PHASE_STRIP = YES;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tENABLE_NS_ASSERTIONS = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_ENABLE_OBJC_EXCEPTIONS = YES;\n\t\t\t\tGCC_INLINES_ARE_PRIVATE_EXTERN = YES;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = \"$(inherited)\";\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = YES;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_MISSING_NEWLINE = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;\n\t\t\t\tGCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;\n\t\t\t\tGCC_WARN_SIGN_COMPARE = YES;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_LABEL = YES;\n\t\t\t\tGCC_WARN_UNUSED_PARAMETER = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\tsrc/,\n\t\t\t\t\tthirdparty/utfcpp/source/,\n\t\t\t\t\tthirdparty/utfcpp/source/utf8/,\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 11.1;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t37D727B81867AF1E007B6D10 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tEXECUTABLE_PREFIX = lib;\n\t\t\t\tLD_DYLIB_INSTALL_NAME = \"$(EXECUTABLE_PATH)\";\n\t\t\t\tOTHER_CPLUSPLUSFLAGS = (\n\t\t\t\t\t\"$(OTHER_CFLAGS)\",\n\t\t\t\t\t\"-fvisibility=hidden\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)-runtime\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t37D727B91867AF1E007B6D10 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;\n\t\t\t\tEXECUTABLE_PREFIX = lib;\n\t\t\t\tLD_DYLIB_INSTALL_NAME = \"$(EXECUTABLE_PATH)\";\n\t\t\t\tOTHER_CPLUSPLUSFLAGS = (\n\t\t\t\t\t\"$(OTHER_CFLAGS)\",\n\t\t\t\t\t\"-fvisibility=hidden\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)-runtime\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t270C67F71CDB4F1E00116E17 /* Build configuration list for PBXNativeTarget \"antlr4_ios\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t270C67F51CDB4F1E00116E17 /* Debug */,\n\t\t\t\t270C67F61CDB4F1E00116E17 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t37C147211B4D5A04008EDDDB /* Build configuration list for PBXNativeTarget \"antlr4_static\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t37C1471F1B4D5A04008EDDDB /* Debug */,\n\t\t\t\t37C147201B4D5A04008EDDDB /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t37D727A51867AF1E007B6D10 /* Build configuration list for PBXProject \"antlrcpp\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t37D727B51867AF1E007B6D10 /* Debug */,\n\t\t\t\t37D727B61867AF1E007B6D10 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t37D727B71867AF1E007B6D10 /* Build configuration list for PBXNativeTarget \"antlr4\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t37D727B81867AF1E007B6D10 /* Debug */,\n\t\t\t\t37D727B91867AF1E007B6D10 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = 37D727A21867AF1E007B6D10 /* Project object */;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"self:\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>IDEDidComputeMac32BitWarning</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp.xcodeproj/xcshareddata/xcschemes/antlr4.xcscheme",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1240\"\n   version = \"1.3\">\n   <BuildAction\n      parallelizeBuildables = \"YES\"\n      buildImplicitDependencies = \"YES\">\n      <BuildActionEntries>\n         <BuildActionEntry\n            buildForTesting = \"YES\"\n            buildForRunning = \"YES\"\n            buildForProfiling = \"YES\"\n            buildForArchiving = \"YES\"\n            buildForAnalyzing = \"YES\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"37D727A91867AF1E007B6D10\"\n               BuildableName = \"libantlr4-runtime.dylib\"\n               BlueprintName = \"antlr4\"\n               ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n            </BuildableReference>\n         </BuildActionEntry>\n      </BuildActionEntries>\n   </BuildAction>\n   <TestAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\">\n      <Testables>\n      </Testables>\n   </TestAction>\n   <LaunchAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      launchStyle = \"0\"\n      useCustomWorkingDirectory = \"NO\"\n      ignoresPersistentStateOnLaunch = \"NO\"\n      debugDocumentVersioning = \"YES\"\n      debugServiceExtension = \"internal\"\n      allowLocationSimulation = \"YES\">\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"37D727A91867AF1E007B6D10\"\n            BuildableName = \"libantlr4-runtime.dylib\"\n            BlueprintName = \"antlr4\"\n            ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n   </LaunchAction>\n   <ProfileAction\n      buildConfiguration = \"Release\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\"\n      savedToolIdentifier = \"\"\n      useCustomWorkingDirectory = \"NO\"\n      debugDocumentVersioning = \"YES\">\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"37D727A91867AF1E007B6D10\"\n            BuildableName = \"libantlr4-runtime.dylib\"\n            BlueprintName = \"antlr4\"\n            ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n   </ProfileAction>\n   <AnalyzeAction\n      buildConfiguration = \"Debug\">\n   </AnalyzeAction>\n   <ArchiveAction\n      buildConfiguration = \"Release\"\n      revealArchiveInOrganizer = \"YES\">\n   </ArchiveAction>\n</Scheme>\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp.xcodeproj/xcshareddata/xcschemes/antlr4_ios.xcscheme",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1240\"\n   version = \"1.3\">\n   <BuildAction\n      parallelizeBuildables = \"YES\"\n      buildImplicitDependencies = \"YES\">\n      <BuildActionEntries>\n         <BuildActionEntry\n            buildForTesting = \"YES\"\n            buildForRunning = \"YES\"\n            buildForProfiling = \"YES\"\n            buildForArchiving = \"YES\"\n            buildForAnalyzing = \"YES\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"270C67EF1CDB4F1E00116E17\"\n               BuildableName = \"antlr4_ios.framework\"\n               BlueprintName = \"antlr4_ios\"\n               ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n            </BuildableReference>\n         </BuildActionEntry>\n      </BuildActionEntries>\n   </BuildAction>\n   <TestAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\">\n      <Testables>\n      </Testables>\n   </TestAction>\n   <LaunchAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      launchStyle = \"0\"\n      useCustomWorkingDirectory = \"NO\"\n      ignoresPersistentStateOnLaunch = \"NO\"\n      debugDocumentVersioning = \"YES\"\n      debugServiceExtension = \"internal\"\n      allowLocationSimulation = \"YES\">\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"270C67EF1CDB4F1E00116E17\"\n            BuildableName = \"antlr4_ios.framework\"\n            BlueprintName = \"antlr4_ios\"\n            ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n   </LaunchAction>\n   <ProfileAction\n      buildConfiguration = \"Release\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\"\n      savedToolIdentifier = \"\"\n      useCustomWorkingDirectory = \"NO\"\n      debugDocumentVersioning = \"YES\">\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"270C67EF1CDB4F1E00116E17\"\n            BuildableName = \"antlr4_ios.framework\"\n            BlueprintName = \"antlr4_ios\"\n            ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n   </ProfileAction>\n   <AnalyzeAction\n      buildConfiguration = \"Debug\">\n   </AnalyzeAction>\n   <ArchiveAction\n      buildConfiguration = \"Release\"\n      revealArchiveInOrganizer = \"YES\">\n   </ArchiveAction>\n</Scheme>\n"
  },
  {
    "path": "runtime/Cpp/runtime/antlrcpp.xcodeproj/xcshareddata/xcschemes/antlr4_static.xcscheme",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1240\"\n   version = \"1.3\">\n   <BuildAction\n      parallelizeBuildables = \"YES\"\n      buildImplicitDependencies = \"YES\">\n      <BuildActionEntries>\n         <BuildActionEntry\n            buildForTesting = \"YES\"\n            buildForRunning = \"YES\"\n            buildForProfiling = \"YES\"\n            buildForArchiving = \"YES\"\n            buildForAnalyzing = \"YES\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"37C147161B4D5A04008EDDDB\"\n               BuildableName = \"libantlr4-runtime.a\"\n               BlueprintName = \"antlr4_static\"\n               ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n            </BuildableReference>\n         </BuildActionEntry>\n      </BuildActionEntries>\n   </BuildAction>\n   <TestAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\">\n      <Testables>\n      </Testables>\n   </TestAction>\n   <LaunchAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      launchStyle = \"0\"\n      useCustomWorkingDirectory = \"NO\"\n      ignoresPersistentStateOnLaunch = \"NO\"\n      debugDocumentVersioning = \"YES\"\n      debugServiceExtension = \"internal\"\n      allowLocationSimulation = \"YES\">\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"37C147161B4D5A04008EDDDB\"\n            BuildableName = \"libantlr4-runtime.a\"\n            BlueprintName = \"antlr4_static\"\n            ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n   </LaunchAction>\n   <ProfileAction\n      buildConfiguration = \"Release\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\"\n      savedToolIdentifier = \"\"\n      useCustomWorkingDirectory = \"NO\"\n      debugDocumentVersioning = \"YES\">\n      <MacroExpansion>\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"37C147161B4D5A04008EDDDB\"\n            BuildableName = \"libantlr4-runtime.a\"\n            BlueprintName = \"antlr4_static\"\n            ReferencedContainer = \"container:antlrcpp.xcodeproj\">\n         </BuildableReference>\n      </MacroExpansion>\n   </ProfileAction>\n   <AnalyzeAction\n      buildConfiguration = \"Debug\">\n   </AnalyzeAction>\n   <ArchiveAction\n      buildConfiguration = \"Release\"\n      revealArchiveInOrganizer = \"YES\">\n   </ArchiveAction>\n</Scheme>\n"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/ANTLR4.Runtime.cpp.noarch.nuspec",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<package xmlns=\"http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd\">\n  <metadata>\n    <id>ANTLR4.Runtime.cpp.vs$vs$.noarch</id>\n    <version>$version$$pre$</version>\n    <title>ANTLR4 Runtime c++ vs$vs$ $link$</title>\n    <authors>Terence Parr &amp; Contributors</authors>\n    <requireLicenseAcceptance>true</requireLicenseAcceptance>\n    <license type='expression'>BSL-1.0</license>\n    <icon>image\\antlr4.jpg</icon>\n    <projectUrl>https://www.antlr.org/</projectUrl>\n    <description>ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files. It's widely used to build languages, tools, and frameworks. From a grammar, ANTLR generates a parser that can build and walk parse trees..</description>\n    <releaseNotes>See project URL</releaseNotes>\n    <copyright>Copyright 2014-2022</copyright>\n    <language></language>\n\t<repository type='git' url='git@github.com:antlr/antlr4.git' branch='$version$' />\n  </metadata>\n  <files>\n    <file src=\"antlr4.jpg\" \t\t\t\t\t\t\ttarget=\"image\\antlr4.jpg\" />\n    <file src=\"..\\src\\**\\*.h\" \t\t\t\t\t\ttarget=\"build\\native\\inc\\\" />\n    <file src=\"ANTLR4.Runtime.cpp.noarch.targets\" \ttarget=\"build\\native\\ANTLR4.Runtime.cpp.vs$vs$.noarch.targets\" />\n  </files>\n</package>"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/ANTLR4.Runtime.cpp.noarch.targets",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemDefinitionGroup>\n    <ClCompile>\n      <AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n    </ClCompile>\n  </ItemDefinitionGroup>\n</Project>"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/ANTLR4.Runtime.cpp.shared.nuspec",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<package xmlns=\"http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd\">\n  <metadata>\n    <id>ANTLR4.Runtime.cpp.vs$vs$.shared</id>\n    <version>$version$$pre$</version>\n    <title>ANTLR4 Runtime c++ vs$vs$ shared</title>\n    <authors>Terence Parr &amp; Contributors</authors>\n    <requireLicenseAcceptance>true</requireLicenseAcceptance>\n    <license type='expression'>BSL-1.0</license>\n    <icon>image\\antlr4.jpg</icon>\n    <projectUrl>https://www.antlr.org/</projectUrl>\n    <description>ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files. It's widely used to build languages, tools, and frameworks. From a grammar, ANTLR generates a parser that can build and walk parse trees..</description>\n    <releaseNotes>releaseNotes</releaseNotes>\n    <copyright>Copyright 2006-2022</copyright>\n    <language></language>\n\t<repository type='git' url='git@github.com:antlr/antlr4.git' branch='$version$' />\n\t<dependencies>\n        <dependency id=\"ANTLR4.Runtime.cpp.vs$vs$.noarch\" version='$version$$pre$'/>\n    </dependencies>\n  </metadata>\n  <files>\n    <file src=\"antlr4.jpg\" \t\t\t\t\t\t\ttarget=\"image\\antlr4.jpg\" />\n    <file src=\"..\\bin\\vs-$vs$\\x86\\Debug DLL\\*\" \t\ttarget=\"build\\native\\x86\\dbg\\\" />\n    <file src=\"..\\bin\\vs-$vs$\\x86\\Release DLL\\*\" \ttarget=\"build\\native\\x86\\rel\\\" />\n    <file src=\"..\\bin\\vs-$vs$\\x64\\Debug DLL\\*\" \t\ttarget=\"build\\native\\x64\\dbg\\\" />\n\t<file src=\"..\\bin\\vs-$vs$\\x64\\Release DLL\\*\" \ttarget=\"build\\native\\x64\\rel\\\" />\n    <file src=\"ANTLR4.Runtime.cpp.shared.targets\" \ttarget=\"build\\native\\ANTLR4.Runtime.cpp.vs$vs$.shared.targets\" />\n    <file src=\"ANTLR4.Runtime.cpp.shared.props\" \ttarget=\"build\\native\\ANTLR4.Runtime.cpp.vs$vs$.shared.props\" />\n  </files>\n</package>"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/ANTLR4.Runtime.cpp.shared.props",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n    <PropertyGroup Label=\"UserMacros\" Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n        <ANTLR4>$(MSBuildThisFileDirectory)x86\\dbg</ANTLR4>\n    </PropertyGroup>\n    <PropertyGroup Label=\"UserMacros\" Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x86'\">\n        <ANTLR4>$(MSBuildThisFileDirectory)x86\\dbg</ANTLR4>\n    </PropertyGroup>\n    <PropertyGroup Label=\"UserMacros\" Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n        <ANTLR4>$(MSBuildThisFileDirectory)x64\\dbg</ANTLR4>\n    </PropertyGroup>\n    <PropertyGroup Label=\"UserMacros\" Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n        <ANTLR4>$(MSBuildThisFileDirectory)x86\\rel</ANTLR4>\n    </PropertyGroup>\n    <PropertyGroup Label=\"UserMacros\" Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x86'\">\n        <ANTLR4>$(MSBuildThisFileDirectory)x86\\rel</ANTLR4>\n    </PropertyGroup>\n    <PropertyGroup Label=\"UserMacros\" Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n        <ANTLR4>$(MSBuildThisFileDirectory)x64\\rel</ANTLR4>\n    </PropertyGroup>\n</Project>"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/ANTLR4.Runtime.cpp.shared.targets",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemDefinitionGroup>\n    <Lib>\n        <AdditionalDependencies>antlr4-runtime.lib;%(AdditionalDependencies)</AdditionalDependencies>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Debug DLL|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Release DLL|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n  </ItemDefinitionGroup>\n</Project>\n"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/ANTLR4.Runtime.cpp.static.nuspec",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<package xmlns=\"http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd\">\n  <metadata>\n    <id>ANTLR4.Runtime.cpp.vs$vs$.static</id>\n    <version>$version$$pre$</version>\n    <title>ANTLR4 Runtime c++ vs$vs$ static</title>\n    <authors>Terence Parr &amp; Contributors</authors>\n    <requireLicenseAcceptance>true</requireLicenseAcceptance>\n    <license type='expression'>BSL-1.0</license>\n    <icon>image\\antlr4.jpg</icon>\n    <projectUrl>https://www.antlr.org/</projectUrl>\n    <description>ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files. It's widely used to build languages, tools, and frameworks. From a grammar, ANTLR generates a parser that can build and walk parse trees..</description>\n    <releaseNotes>releaseNotes</releaseNotes>\n    <copyright>Copyright 2006-2022</copyright>\n    <language></language>\n\t<repository type='git' url='git@github.com:antlr/antlr4.git' branch='$version$' />\n\t<dependencies>\n        <dependency id=\"ANTLR4.Runtime.cpp.vs$vs$.noarch\" version='$version$$pre$'/>\n    </dependencies>\n  </metadata>\n  <files>\n    <file src=\"antlr4.jpg\" \t\t\t\t\t\t\t\ttarget=\"image\\antlr4.jpg\" />\n    <file src=\"..\\bin\\vs-$vs$\\x86\\Debug Static\\*\" \t\ttarget=\"build\\native\\x86\\dbg\\\" />\n    <file src=\"..\\bin\\vs-$vs$\\x86\\Release Static\\*\" \ttarget=\"build\\native\\x86\\rel\\\" />\n    <file src=\"..\\bin\\vs-$vs$\\x64\\Debug Static\\*\" \t\ttarget=\"build\\native\\x64\\dbg\\\" />\n    <file src=\"..\\bin\\vs-$vs$\\x64\\Release Static\\*\" \ttarget=\"build\\native\\x64\\rel\\\" />\n\t<file src=\"ANTLR4.Runtime.cpp.static.targets\" \t\ttarget=\"build\\native\\ANTLR4.Runtime.cpp.vs$vs$.static.targets\" />\n  </files>\n</package>"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/ANTLR4.Runtime.cpp.static.targets",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemDefinitionGroup>\n    <Lib>\n        <AdditionalDependencies>antlr4-runtime.lib;%(AdditionalDependencies)</AdditionalDependencies>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Lib  Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Lib>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Debug Static|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\dbg;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Release Static|Win32'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x86'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x86\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n    <Link  Condition=\"'$(Configuration)|$(Platform)'=='Release Static|x64'\">\n        <AdditionalLibraryDirectories>$(MSBuildThisFileDirectory)x64\\rel;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>\n    </Link>\n  </ItemDefinitionGroup>\n</Project>\n"
  },
  {
    "path": "runtime/Cpp/runtime/nuget/pack.cmd",
    "content": "echo off\nrem echo Usage:\nrem echo ------\nrem echo pack vsvers version [pre]      // pack 2019 4.9.1 -beta\nrem echo ------\nsetlocal enableextensions enabledelayedexpansion\n\nif \"%1\"==\"\" goto usage\nif \"%2\"==\"\" goto usage\nset PRE=%3\nset PLATFORM=Win32\n\nrem -version ^^[16.0^^,17.0^^)\nset VS_VERSION=vs%1\nrem  should be set \"VSWHERE='%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe  -property installationPath -version ^[16.0^,17.0^)'\"\nif %VS_VERSION%==vs2019 (\n  set \"VSWHERE='C:\\PROGRA~2\\\"Microsoft Visual Studio\"\\Installer\\vswhere.exe  -latest -property installationPath -version ^[16.0^,17.0^)'\"\n) else (\nif %VS_VERSION%==vs2022 (\n  set \"VSWHERE='C:\\PROGRA~2\\\"Microsoft Visual Studio\"\\Installer\\vswhere.exe  -latest -property installationPath -version ^[17.0^,18.0^)'\"\n)\n)\nfor /f \" delims=\" %%a in (%VSWHERE%) do @set \"VSCOMNTOOLS=%%a\"\n\necho ============= %VSCOMNTOOLS% =============\n\nif %VS_VERSION%==vs2019 (\n  set VS_VARSALL=..\\..\\VC\\Auxiliary\\Build\\vcvarsall.bat\n  set \"VS160COMNTOOLS=%VSCOMNTOOLS%\\Common7\\Tools\\\"\n) else (\n  if %VS_VERSION%==vs2022 (\n    set VS_VARSALL=..\\..\\VC\\Auxiliary\\Build\\vcvarsall.bat\n    set \"VS170COMNTOOLS=%VSCOMNTOOLS%\\Common7\\Tools\\\"\n  ) else (\n    set VS_VARSALL=..\\..\\VC\\vcvarsall.bat\n  )\n)\n\nif not defined VCINSTALLDIR (\n  if %VS_VERSION%==vs2019 (\n    if %PLATFORM%==x64 (\n      call \"%VS160COMNTOOLS%%VS_VARSALL%\" x86_amd64 8.1\n    ) else (\n      call \"%VS160COMNTOOLS%%VS_VARSALL%\" x86 8.1\n    )\n  ) else (\n    if %VS_VERSION%==vs2022 (\n      if %PLATFORM%==x64 (\n        call \"%VS170COMNTOOLS%%VS_VARSALL%\" x86_amd64 8.1\n      ) else (\n        call \"%VS170COMNTOOLS%%VS_VARSALL%\" x86 8.1\n      )\n    )\n  )\n)\n\nif not defined VSINSTALLDIR (\n  echo Error: No Visual cpp environment found.\n  echo Please run this script from a Visual Studio Command Prompt\n  echo or run \"%%VSnnCOMNTOOLS%%\\vsvars32.bat\" first.\n  goto :buildfailed\n)\n\n\npushd ..\\\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=Win32 \t-p:Configuration=\"Debug DLL\"\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=Win32 \t-p:Configuration=\"Release DLL\"\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=Win32 \t-p:Configuration=\"Debug Static\"\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=Win32 \t-p:Configuration=\"Release Static\"\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=x64 \t\t-p:Configuration=\"Debug DLL\"\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=x64 \t\t-p:Configuration=\"Release DLL\"\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=x64 \t\t-p:Configuration=\"Debug Static\"\ncall msbuild antlr4cpp-vs%1.vcxproj -t:rebuild -p:Platform=x64 \t\t-p:Configuration=\"Release Static\"\npopd\n\ndel *nupkg\necho nuget pack ANTLR4.Runtime.cpp.noarch.nuspec \t\t\t\t-p vs=%1 -p version=%2 -p pre=%pre%\ncall nuget pack ANTLR4.Runtime.cpp.noarch.nuspec \t\t\t\t-p vs=%1 -p version=%2 -p pre=%pre%\necho nuget pack ANTLR4.Runtime.cpp.shared.nuspec \t-symbols \t-p vs=%1 -p version=%2 -p pre=%pre%\ncall nuget pack ANTLR4.Runtime.cpp.shared.nuspec \t-symbols \t-p vs=%1 -p version=%2 -p pre=%pre%\necho nuget pack ANTLR4.Runtime.cpp.static.nuspec \t-symbols \t-p vs=%1 -p version=%2 -p pre=%pre%\ncall nuget pack ANTLR4.Runtime.cpp.static.nuspec \t-symbols \t-p vs=%1 -p version=%2 -p pre=%pre%\n\ngoto exit\n:usage\necho Usage:\necho ------\necho \"pack vsvers version [pre]\"      // pack 2019 4.9.1 -beta\necho ------\n:exit\n:buildfailed\nendlocal\nrem echo on"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRErrorListener.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"ANTLRErrorListener.h\"\n\nantlr4::ANTLRErrorListener::~ANTLRErrorListener()\n{\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRErrorListener.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"RecognitionException.h\"\n\nnamespace antlrcpp {\n  class BitSet;\n}\n\nnamespace antlr4 {\n\n  /// How to emit recognition errors (an interface in Java).\n  class ANTLR4CPP_PUBLIC ANTLRErrorListener {\n  public:\n    virtual ~ANTLRErrorListener();\n\n    /// <summary>\n    /// Upon syntax error, notify any interested parties. This is not how to\n    /// recover from errors or compute error messages. <seealso cref=\"ANTLRErrorStrategy\"/>\n    /// specifies how to recover from syntax errors and how to compute error\n    /// messages. This listener's job is simply to emit a computed message,\n    /// though it has enough information to create its own message in many cases.\n    /// <p/>\n    /// The <seealso cref=\"RecognitionException\"/> is non-null for all syntax errors except\n    /// when we discover mismatched token errors that we can recover from\n    /// in-line, without returning from the surrounding rule (via the single\n    /// token insertion and deletion mechanism).\n    /// </summary>\n    /// <param name=\"recognizer\">\n    ///        What parser got the error. From this\n    /// \t\t  object, you can access the context as well\n    /// \t\t  as the input stream. </param>\n    /// <param name=\"offendingSymbol\">\n    ///        The offending token in the input token\n    /// \t\t  stream, unless recognizer is a lexer (then it's null). If\n    /// \t\t  no viable alternative error, {@code e} has token at which we\n    /// \t\t  started production for the decision. </param>\n    /// <param name=\"line\">\n    /// \t\t  The line number in the input where the error occurred. </param>\n    /// <param name=\"charPositionInLine\">\n    /// \t\t  The character position within that line where the error occurred. </param>\n    /// <param name=\"msg\">\n    /// \t\t  The message to emit. </param>\n    /// <param name=\"e\">\n    ///        The exception generated by the parser that led to\n    ///        the reporting of an error. It is null in the case where\n    ///        the parser was able to recover in line without exiting the\n    ///        surrounding rule. </param>\n    virtual void syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line,\n                             size_t charPositionInLine, const std::string &msg, std::exception_ptr e) = 0;\n\n    /**\n     * This method is called by the parser when a full-context prediction\n     * results in an ambiguity.\n     *\n     * <p>Each full-context prediction which does not result in a syntax error\n     * will call either {@link #reportContextSensitivity} or\n     * {@link #reportAmbiguity}.</p>\n     *\n     * <p>When {@code ambigAlts} is not null, it contains the set of potentially\n     * viable alternatives identified by the prediction algorithm. When\n     * {@code ambigAlts} is null, use {@link ATNConfigSet#getAlts} to obtain the\n     * represented alternatives from the {@code configs} argument.</p>\n     *\n     * <p>When {@code exact} is {@code true}, <em>all</em> of the potentially\n     * viable alternatives are truly viable, i.e. this is reporting an exact\n     * ambiguity. When {@code exact} is {@code false}, <em>at least two</em> of\n     * the potentially viable alternatives are viable for the current input, but\n     * the prediction algorithm terminated as soon as it determined that at\n     * least the <em>minimum</em> potentially viable alternative is truly\n     * viable.</p>\n     *\n     * <p>When the {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} prediction\n     * mode is used, the parser is required to identify exact ambiguities so\n     * {@code exact} will always be {@code true}.</p>\n     *\n     * <p>This method is not used by lexers.</p>\n     *\n     * @param recognizer the parser instance\n     * @param dfa the DFA for the current decision\n     * @param startIndex the input index where the decision started\n     * @param stopIndex the input input where the ambiguity was identified\n     * @param exact {@code true} if the ambiguity is exactly known, otherwise\n     * {@code false}. This is always {@code true} when\n     * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used.\n     * @param ambigAlts the potentially ambiguous alternatives, or {@code null}\n     * to indicate that the potentially ambiguous alternatives are the complete\n     * set of represented alternatives in {@code configs}\n     * @param configs the ATN configuration set where the ambiguity was\n     * identified\n     */\n    virtual void reportAmbiguity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex, bool exact,\n      const antlrcpp::BitSet &ambigAlts, atn::ATNConfigSet *configs) = 0;\n\n    /**\n     * This method is called when an SLL conflict occurs and the parser is about\n     * to use the full context information to make an LL decision.\n     *\n     * <p>If one or more configurations in {@code configs} contains a semantic\n     * predicate, the predicates are evaluated before this method is called. The\n     * subset of alternatives which are still viable after predicates are\n     * evaluated is reported in {@code conflictingAlts}.</p>\n     *\n     * <p>This method is not used by lexers.</p>\n     *\n     * @param recognizer the parser instance\n     * @param dfa the DFA for the current decision\n     * @param startIndex the input index where the decision started\n     * @param stopIndex the input index where the SLL conflict occurred\n     * @param conflictingAlts The specific conflicting alternatives. If this is\n     * {@code null}, the conflicting alternatives are all alternatives\n     * represented in {@code configs}. At the moment, conflictingAlts is non-null\n     * (for the reference implementation, but Sam's optimized version can see this\n     * as null).\n     * @param configs the ATN configuration set where the SLL conflict was\n     * detected\n     */\n    virtual void reportAttemptingFullContext(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n      const antlrcpp::BitSet &conflictingAlts, atn::ATNConfigSet *configs) = 0;\n\n    /**\n     * This method is called by the parser when a full-context prediction has a\n     * unique result.\n     *\n     * <p>Each full-context prediction which does not result in a syntax error\n     * will call either {@link #reportContextSensitivity} or\n     * {@link #reportAmbiguity}.</p>\n     *\n     * <p>For prediction implementations that only evaluate full-context\n     * predictions when an SLL conflict is found (including the default\n     * {@link ParserATNSimulator} implementation), this method reports cases\n     * where SLL conflicts were resolved to unique full-context predictions,\n     * i.e. the decision was context-sensitive. This report does not necessarily\n     * indicate a problem, and it may appear even in completely unambiguous\n     * grammars.</p>\n     *\n     * <p>{@code configs} may have more than one represented alternative if the\n     * full-context prediction algorithm does not evaluate predicates before\n     * beginning the full-context prediction. In all cases, the final prediction\n     * is passed as the {@code prediction} argument.</p>\n     *\n     * <p>Note that the definition of \"context sensitivity\" in this method\n     * differs from the concept in {@link DecisionInfo#contextSensitivities}.\n     * This method reports all instances where an SLL conflict occurred but LL\n     * parsing produced a unique result, whether or not that unique result\n     * matches the minimum alternative in the SLL conflicting set.</p>\n     *\n     * <p>This method is not used by lexers.</p>\n     *\n     * @param recognizer the parser instance\n     * @param dfa the DFA for the current decision\n     * @param startIndex the input index where the decision started\n     * @param stopIndex the input index where the context sensitivity was\n     * finally determined\n     * @param prediction the unambiguous result of the full-context prediction\n     * @param configs the ATN configuration set where the unambiguous prediction\n     * was determined\n     */\n    virtual void reportContextSensitivity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n      size_t prediction, atn::ATNConfigSet *configs) = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRErrorStrategy.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"ANTLRErrorStrategy.h\"\n\nantlr4::ANTLRErrorStrategy::~ANTLRErrorStrategy()\n{\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRErrorStrategy.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n\nnamespace antlr4 {\n  class Parser;\n\n  /// <summary>\n  /// The interface for defining strategies to deal with syntax errors encountered\n  /// during a parse by ANTLR-generated parsers. We distinguish between three\n  /// different kinds of errors:\n  ///\n  /// <ul>\n  /// <li>The parser could not figure out which path to take in the ATN (none of\n  /// the available alternatives could possibly match)</li>\n  /// <li>The current input does not match what we were looking for</li>\n  /// <li>A predicate evaluated to false</li>\n  /// </ul>\n  ///\n  /// Implementations of this interface report syntax errors by calling\n  /// <seealso cref=\"Parser#notifyErrorListeners\"/>.\n  /// <p/>\n  /// TODO: what to do about lexers\n  /// </summary>\n  class ANTLR4CPP_PUBLIC ANTLRErrorStrategy {\n  public:\n\n    /// <summary>\n    /// Reset the error handler state for the specified {@code recognizer}. </summary>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    virtual ~ANTLRErrorStrategy();\n\n    virtual void reset(Parser *recognizer) = 0;\n\n    /**\n     * This method is called when an unexpected symbol is encountered during an\n     * inline match operation, such as {@link Parser#match}. If the error\n     * strategy successfully recovers from the match failure, this method\n     * returns the {@link Token} instance which should be treated as the\n     * successful result of the match.\n     *\n     * <p>This method handles the consumption of any tokens - the caller should\n     * <b>not</b> call {@link Parser#consume} after a successful recovery.</p>\n     *\n     * <p>Note that the calling code will not report an error if this method\n     * returns successfully. The error strategy implementation is responsible\n     * for calling {@link Parser#notifyErrorListeners} as appropriate.</p>\n     *\n     * @param recognizer the parser instance\n     * @throws RecognitionException if the error strategy was not able to\n     * recover from the unexpected input symbol\n     */\n    virtual Token* recoverInline(Parser *recognizer) = 0;\n\n    /// <summary>\n    /// This method is called to recover from exception {@code e}. This method is\n    /// called after <seealso cref=\"#reportError\"/> by the default exception handler\n    /// generated for a rule method.\n    /// </summary>\n    /// <seealso cref= #reportError\n    /// </seealso>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <param name=\"e\"> the recognition exception to recover from </param>\n    /// <exception cref=\"RecognitionException\"> if the error strategy could not recover from\n    /// the recognition exception </exception>\n    virtual void recover(Parser *recognizer, std::exception_ptr e) = 0;\n\n    /// <summary>\n    /// This method provides the error handler with an opportunity to handle\n    /// syntactic or semantic errors in the input stream before they result in a\n    /// <seealso cref=\"RecognitionException\"/>.\n    /// <p/>\n    /// The generated code currently contains calls to <seealso cref=\"#sync\"/> after\n    /// entering the decision state of a closure block ({@code (...)*} or\n    /// {@code (...)+}).\n    /// <p/>\n    /// For an implementation based on Jim Idle's \"magic sync\" mechanism, see\n    /// <seealso cref=\"DefaultErrorStrategy#sync\"/>.\n    /// </summary>\n    /// <seealso cref= DefaultErrorStrategy#sync\n    /// </seealso>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <exception cref=\"RecognitionException\"> if an error is detected by the error\n    /// strategy but cannot be automatically recovered at the current state in\n    /// the parsing process </exception>\n    virtual void sync(Parser *recognizer) = 0;\n\n    /// <summary>\n    /// Tests whether or not {@code recognizer} is in the process of recovering\n    /// from an error. In error recovery mode, <seealso cref=\"Parser#consume\"/> adds\n    /// symbols to the parse tree by calling\n    /// {@link Parser#createErrorNode(ParserRuleContext, Token)} then\n    /// {@link ParserRuleContext#addErrorNode(ErrorNode)} instead of\n    /// {@link Parser#createTerminalNode(ParserRuleContext, Token)}.\n    /// </summary>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <returns> {@code true} if the parser is currently recovering from a parse\n    /// error, otherwise {@code false} </returns>\n    virtual bool inErrorRecoveryMode(Parser *recognizer) = 0;\n\n    /// <summary>\n    /// This method is called by when the parser successfully matches an input\n    /// symbol.\n    /// </summary>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    virtual void reportMatch(Parser *recognizer) = 0;\n\n    /// <summary>\n    /// Report any kind of <seealso cref=\"RecognitionException\"/>. This method is called by\n    /// the default exception handler generated for a rule method.\n    /// </summary>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <param name=\"e\"> the recognition exception to report </param>\n    virtual void reportError(Parser *recognizer, const RecognitionException &e) = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRFileStream.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include \"ANTLRInputStream.h\"\n#include \"ANTLRFileStream.h\"\n\nusing namespace antlr4;\n\nvoid ANTLRFileStream::loadFromFile(const std::string &fileName) {\n  _fileName = fileName;\n  if (_fileName.empty()) {\n    return;\n  }\n\n  std::ifstream stream(fileName, std::ios::binary);\n\n  ANTLRInputStream::load(stream);\n}\n\nstd::string ANTLRFileStream::getSourceName() const {\n  return _fileName;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRFileStream.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"ANTLRInputStream.h\"\n\nnamespace antlr4 {\n\n  /// This is an ANTLRInputStream that is loaded from a file all at once\n  /// when you construct the object (or call load()).\n  // TODO: this class needs testing.\n  class ANTLR4CPP_PUBLIC ANTLRFileStream : public ANTLRInputStream {\n  public:\n    ANTLRFileStream() = default;\n    ANTLRFileStream(const std::string &) = delete;\n    ANTLRFileStream(const char *data, size_t length) = delete;\n    ANTLRFileStream(std::istream &stream) = delete;\n\n    // Assumes a file name encoded in UTF-8 and file content in the same encoding (with or w/o BOM).\n    virtual void loadFromFile(const std::string &fileName);\n    std::string getSourceName() const override;\n\n  private:\n    std::string _fileName; // UTF-8 encoded file name.\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRInputStream.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string_view>\n#include <cassert>\n#include <utility>\n#include <string>\n#include <string.h>\n\n#include \"Exceptions.h\"\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"IntStream.h\"\n\n#include \"support/Utf8.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"ANTLRInputStream.h\"\n\nusing namespace antlr4;\nusing namespace antlrcpp;\n\nusing misc::Interval;\n\nANTLRInputStream::ANTLRInputStream() {\n  InitializeInstanceFields();\n}\n\nANTLRInputStream::ANTLRInputStream(std::string_view input): ANTLRInputStream() {\n  load(input.data(), input.length());\n}\n\nANTLRInputStream::ANTLRInputStream(const char *data, size_t length) {\n  load(data, length);\n}\n\nANTLRInputStream::ANTLRInputStream(std::istream &stream): ANTLRInputStream() {\n  load(stream);\n}\n\nvoid ANTLRInputStream::load(const std::string &input, bool lenient) {\n  load(input.data(), input.size(), lenient);\n}\n\nvoid ANTLRInputStream::load(const char *data, size_t length, bool lenient) {\n  // Remove the UTF-8 BOM if present.\n  const char *bom = \"\\xef\\xbb\\xbf\";\n  if (length >= 3 && strncmp(data, bom, 3) == 0) {\n    data += 3;\n    length -= 3;\n  }\n  if (lenient) {\n    _data = Utf8::lenientDecode(std::string_view(data, length));\n  } else {\n    auto maybe_utf32 = Utf8::strictDecode(std::string_view(data, length));\n    if (!maybe_utf32.has_value()) {\n      throw IllegalArgumentException(\"UTF-8 string contains an illegal byte sequence\");\n    }\n    _data = std::move(maybe_utf32).value();\n  }\n  p = 0;\n}\n\nvoid ANTLRInputStream::load(std::istream &stream, bool lenient) {\n  if (!stream.good() || stream.eof()) // No fail, bad or EOF.\n    return;\n\n  _data.clear();\n\n  std::string s((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());\n  load(s.data(), s.length(), lenient);\n}\n\nvoid ANTLRInputStream::reset() {\n  p = 0;\n}\n\nvoid ANTLRInputStream::consume() {\n  if (p >= _data.size()) {\n    assert(LA(1) == IntStream::EOF);\n    throw IllegalStateException(\"cannot consume EOF\");\n  }\n\n  if (p < _data.size()) {\n    p++;\n  }\n}\n\nsize_t ANTLRInputStream::LA(ssize_t i) {\n  if (i == 0) {\n    return 0; // undefined\n  }\n\n  ssize_t position = static_cast<ssize_t>(p);\n  if (i < 0) {\n    i++; // e.g., translate LA(-1) to use offset i=0; then _data[p+0-1]\n    if ((position + i - 1) < 0) {\n      return IntStream::EOF; // invalid; no char before first char\n    }\n  }\n\n  if ((position + i - 1) >= static_cast<ssize_t>(_data.size())) {\n    return IntStream::EOF;\n  }\n\n  return _data[static_cast<size_t>((position + i - 1))];\n}\n\nsize_t ANTLRInputStream::LT(ssize_t i) {\n  return LA(i);\n}\n\nsize_t ANTLRInputStream::index() {\n  return p;\n}\n\nsize_t ANTLRInputStream::size() {\n  return _data.size();\n}\n\n// Mark/release do nothing. We have entire buffer.\nssize_t ANTLRInputStream::mark() {\n  return -1;\n}\n\nvoid ANTLRInputStream::release(ssize_t /* marker */) {\n}\n\nvoid ANTLRInputStream::seek(size_t index) {\n  if (index <= p) {\n    p = index; // just jump; don't update stream state (line, ...)\n    return;\n  }\n  // seek forward, consume until p hits index or n (whichever comes first)\n  index = std::min(index, _data.size());\n  while (p < index) {\n    consume();\n  }\n}\n\nstd::string ANTLRInputStream::getText(const Interval &interval) {\n  if (interval.a < 0 || interval.b < 0) {\n    return \"\";\n  }\n\n  size_t start = static_cast<size_t>(interval.a);\n  size_t stop = static_cast<size_t>(interval.b);\n\n\n  if (stop >= _data.size()) {\n    stop = _data.size() - 1;\n  }\n\n  size_t count = stop - start + 1;\n  if (start >= _data.size()) {\n    return \"\";\n  }\n\n  auto maybeUtf8 = Utf8::strictEncode(std::u32string_view(_data).substr(start, count));\n  if (!maybeUtf8.has_value()) {\n    throw IllegalArgumentException(\"Input stream contains invalid Unicode code points\");\n  }\n  return std::move(maybeUtf8).value();\n}\n\nstd::string ANTLRInputStream::getSourceName() const {\n  if (name.empty()) {\n    return IntStream::UNKNOWN_SOURCE_NAME;\n  }\n  return name;\n}\n\nstd::string ANTLRInputStream::toString() const {\n  auto maybeUtf8 = Utf8::strictEncode(_data);\n  if (!maybeUtf8.has_value()) {\n    throw IllegalArgumentException(\"Input stream contains invalid Unicode code points\");\n  }\n  return std::move(maybeUtf8).value();\n}\n\nvoid ANTLRInputStream::InitializeInstanceFields() {\n  p = 0;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ANTLRInputStream.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include <string_view>\n\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"CharStream.h\"\n\nnamespace antlr4 {\n\n  // Vacuum all input from a stream and then treat it\n  // like a string. Can also pass in a string or char[] to use.\n  // Input is expected to be encoded in UTF-8 and converted to UTF-32 internally.\n  class ANTLR4CPP_PUBLIC ANTLRInputStream : public CharStream {\n  protected:\n    /// The data being scanned.\n    // UTF-32\n    std::u32string _data;\n\n    /// 0..n-1 index into string of next char </summary>\n    size_t p;\n\n  public:\n    /// What is name or source of this char stream?\n    std::string name;\n\n    ANTLRInputStream();\n\n    ANTLRInputStream(std::string_view input);\n\n    ANTLRInputStream(const char *data, size_t length);\n    ANTLRInputStream(std::istream &stream);\n\n    virtual void load(const std::string &input, bool lenient);\n    virtual void load(const char *data, size_t length, bool lenient);\n    virtual void load(std::istream &stream, bool lenient);\n\n    virtual void load(const std::string &input) { load(input, false); }\n    virtual void load(const char *data, size_t length) { load(data, length, false); }\n    virtual void load(std::istream &stream) { load(stream, false); }\n\n    /// Reset the stream so that it's in the same state it was\n    /// when the object was created *except* the data array is not\n    /// touched.\n    virtual void reset();\n    void consume() override;\n    size_t LA(ssize_t i) override;\n    virtual size_t LT(ssize_t i);\n\n    /// <summary>\n    /// Return the current input symbol index 0..n where n indicates the\n    ///  last symbol has been read.  The index is the index of char to\n    ///  be returned from LA(1).\n    /// </summary>\n    size_t index() override;\n    size_t size() override;\n\n    /// <summary>\n    /// mark/release do nothing; we have entire buffer </summary>\n    ssize_t mark() override;\n    void release(ssize_t marker) override;\n\n    /// <summary>\n    /// consume() ahead until p==index; can't just set p=index as we must\n    ///  update line and charPositionInLine. If we seek backwards, just set p\n    /// </summary>\n    void seek(size_t index) override;\n    std::string getText(const misc::Interval &interval) override;\n    std::string getSourceName() const override;\n    std::string toString() const override;\n\n  private:\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/BailErrorStrategy.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include \"Exceptions.h\"\n#include \"Token.h\"\n#include \"ParserRuleContext.h\"\n#include \"InputMismatchException.h\"\n#include \"Parser.h\"\n\n#include \"BailErrorStrategy.h\"\n\nusing namespace antlr4;\n\nvoid BailErrorStrategy::recover(Parser *recognizer, std::exception_ptr e) {\n  ParserRuleContext *context = recognizer->getContext();\n  do {\n    context->exception = e;\n    if (context->parent == nullptr)\n      break;\n    context = static_cast<ParserRuleContext *>(context->parent);\n  } while (true);\n\n  try {\n    std::rethrow_exception(e); // Throw the exception to be able to catch and rethrow nested.\n#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026\n  } catch (RecognitionException &inner) {\n    throw ParseCancellationException(inner.what());\n#else\n  } catch (RecognitionException & /*inner*/) {\n    std::throw_with_nested(ParseCancellationException());\n#endif\n  }\n}\n\nToken* BailErrorStrategy::recoverInline(Parser *recognizer)  {\n  InputMismatchException e(recognizer);\n  std::exception_ptr exception = std::make_exception_ptr(e);\n\n  ParserRuleContext *context = recognizer->getContext();\n  do {\n    context->exception = exception;\n    if (context->parent == nullptr)\n      break;\n    context = static_cast<ParserRuleContext *>(context->parent);\n  } while (true);\n\n  try {\n    throw e;\n#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026\n  } catch (InputMismatchException &inner) {\n    throw ParseCancellationException(inner.what());\n#else\n  } catch (InputMismatchException & /*inner*/) {\n    std::throw_with_nested(ParseCancellationException());\n#endif\n  }\n}\n\nvoid BailErrorStrategy::sync(Parser * /*recognizer*/) {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/BailErrorStrategy.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"DefaultErrorStrategy.h\"\n\nnamespace antlr4 {\n\n  /**\n   * This implementation of {@link ANTLRErrorStrategy} responds to syntax errors\n   * by immediately canceling the parse operation with a\n   * {@link ParseCancellationException}. The implementation ensures that the\n   * {@link ParserRuleContext#exception} field is set for all parse tree nodes\n   * that were not completed prior to encountering the error.\n   *\n   * <p>\n   * This error strategy is useful in the following scenarios.</p>\n   *\n   * <ul>\n   * <li><strong>Two-stage parsing:</strong> This error strategy allows the first\n   * stage of two-stage parsing to immediately terminate if an error is\n   * encountered, and immediately fall back to the second stage. In addition to\n   * avoiding wasted work by attempting to recover from errors here, the empty\n   * implementation of {@link BailErrorStrategy#sync} improves the performance of\n   * the first stage.</li>\n   * <li><strong>Silent validation:</strong> When syntax errors are not being\n   * reported or logged, and the parse result is simply ignored if errors occur,\n   * the {@link BailErrorStrategy} avoids wasting work on recovering from errors\n   * when the result will be ignored either way.</li>\n   * </ul>\n   *\n   * <p>\n   * {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>\n   *\n   * @see Parser#setErrorHandler(ANTLRErrorStrategy)\n   */\n  class ANTLR4CPP_PUBLIC BailErrorStrategy : public DefaultErrorStrategy {\n    /// <summary>\n    /// Instead of recovering from exception {@code e}, re-throw it wrapped\n    ///  in a <seealso cref=\"ParseCancellationException\"/> so it is not caught by the\n    ///  rule function catches.  Use <seealso cref=\"Exception#getCause()\"/> to get the\n    ///  original <seealso cref=\"RecognitionException\"/>.\n    /// </summary>\n  public:\n    void recover(Parser *recognizer, std::exception_ptr e) override;\n\n    /// Make sure we don't attempt to recover inline; if the parser\n    ///  successfully recovers, it won't throw an exception.\n    Token* recoverInline(Parser *recognizer) override;\n\n    /// <summary>\n    /// Make sure we don't attempt to recover from problems in subrules. </summary>\n    void sync(Parser *recognizer) override;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/BaseErrorListener.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"BaseErrorListener.h\"\n#include \"Token.h\"\n#include \"RecognitionException.h\"\n\nusing namespace antlr4;\n\nvoid BaseErrorListener::syntaxError(Recognizer * /*recognizer*/, Token * /*offendingSymbol*/, size_t /*line*/,\n  size_t /*charPositionInLine*/, const std::string &/*msg*/, std::exception_ptr /*e*/) {\n}\n\nvoid BaseErrorListener::reportAmbiguity(Parser * /*recognizer*/, const dfa::DFA &/*dfa*/, size_t /*startIndex*/,\n  size_t /*stopIndex*/, bool /*exact*/, const antlrcpp::BitSet &/*ambigAlts*/, atn::ATNConfigSet * /*configs*/) {\n}\n\nvoid BaseErrorListener::reportAttemptingFullContext(Parser * /*recognizer*/, const dfa::DFA &/*dfa*/, size_t /*startIndex*/,\n  size_t /*stopIndex*/, const antlrcpp::BitSet &/*conflictingAlts*/, atn::ATNConfigSet * /*configs*/) {\n}\n\nvoid BaseErrorListener::reportContextSensitivity(Parser * /*recognizer*/, const dfa::DFA &/*dfa*/, size_t /*startIndex*/,\n  size_t /*stopIndex*/, size_t /*prediction*/, atn::ATNConfigSet * /*configs*/) {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/BaseErrorListener.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"ANTLRErrorListener.h\"\n\nnamespace antlrcpp {\n  class BitSet;\n}\n\nnamespace antlr4 {\n\n  /**\n   * Provides an empty default implementation of {@link ANTLRErrorListener}. The\n   * default implementation of each method does nothing, but can be overridden as\n   * necessary.\n   */\n  class ANTLR4CPP_PUBLIC BaseErrorListener : public ANTLRErrorListener {\n\n    void syntaxError(Recognizer *recognizer, Token * offendingSymbol, size_t line, size_t charPositionInLine,\n      const std::string &msg, std::exception_ptr e) override;\n\n    void reportAmbiguity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex, bool exact,\n      const antlrcpp::BitSet &ambigAlts, atn::ATNConfigSet *configs) override;\n\n    void reportAttemptingFullContext(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n      const antlrcpp::BitSet &conflictingAlts, atn::ATNConfigSet *configs) override;\n\n    void reportContextSensitivity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n      size_t prediction, atn::ATNConfigSet *configs) override;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/BufferedTokenStream.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <memory>\n#include <string>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"WritableToken.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"Lexer.h\"\n#include \"RuleContext.h\"\n#include \"misc/Interval.h\"\n#include \"Exceptions.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"BufferedTokenStream.h\"\n\nusing namespace antlr4;\nusing namespace antlrcpp;\n\nBufferedTokenStream::BufferedTokenStream(TokenSource *tokenSource) : _tokenSource(tokenSource){\n  InitializeInstanceFields();\n}\n\nTokenSource* BufferedTokenStream::getTokenSource() const {\n  return _tokenSource;\n}\n\nsize_t BufferedTokenStream::index() {\n  return _p;\n}\n\nssize_t BufferedTokenStream::mark() {\n  return 0;\n}\n\nvoid BufferedTokenStream::release(ssize_t /*marker*/) {\n  // no resources to release\n}\n\nvoid BufferedTokenStream::reset() {\n  seek(0);\n}\n\nvoid BufferedTokenStream::seek(size_t index) {\n  lazyInit();\n  _p = adjustSeekIndex(index);\n}\n\nsize_t BufferedTokenStream::size() {\n  return _tokens.size();\n}\n\nvoid BufferedTokenStream::consume() {\n  bool skipEofCheck = false;\n  if (!_needSetup) {\n    if (_fetchedEOF) {\n      // the last token in tokens is EOF. skip check if p indexes any\n      // fetched token except the last.\n      skipEofCheck = _p < _tokens.size() - 1;\n    } else {\n      // no EOF token in tokens. skip check if p indexes a fetched token.\n      skipEofCheck = _p < _tokens.size();\n    }\n  } else {\n    // not yet initialized\n    skipEofCheck = false;\n  }\n\n  if (!skipEofCheck && LA(1) == Token::EOF) {\n    throw IllegalStateException(\"cannot consume EOF\");\n  }\n\n  if (sync(_p + 1)) {\n    _p = adjustSeekIndex(_p + 1);\n  }\n}\n\nbool BufferedTokenStream::sync(size_t i) {\n  if (i + 1 < _tokens.size())\n    return true;\n  size_t n = i - _tokens.size() + 1; // how many more elements we need?\n\n  if (n > 0) {\n    size_t fetched = fetch(n);\n    return fetched >= n;\n  }\n\n  return true;\n}\n\nsize_t BufferedTokenStream::fetch(size_t n) {\n  if (_fetchedEOF) {\n    return 0;\n  }\n\n  size_t i = 0;\n  while (i < n) {\n    std::unique_ptr<Token> t(_tokenSource->nextToken());\n\n    if (is<WritableToken *>(t.get())) {\n      (static_cast<WritableToken *>(t.get()))->setTokenIndex(_tokens.size());\n    }\n\n    _tokens.push_back(std::move(t));\n    ++i;\n\n    if (_tokens.back()->getType() == Token::EOF) {\n      _fetchedEOF = true;\n      break;\n    }\n  }\n\n  return i;\n}\n\nToken* BufferedTokenStream::get(size_t i) const {\n  if (i >= _tokens.size()) {\n    throw IndexOutOfBoundsException(std::string(\"token index \") +\n                                    std::to_string(i) +\n                                    std::string(\" out of range 0..\") +\n                                    std::to_string(_tokens.size() - 1));\n  }\n  return _tokens[i].get();\n}\n\nstd::vector<Token *> BufferedTokenStream::get(size_t start, size_t stop) {\n  std::vector<Token *> subset;\n\n  lazyInit();\n\n  if (_tokens.empty()) {\n    return subset;\n  }\n\n  if (stop >= _tokens.size()) {\n    stop = _tokens.size() - 1;\n  }\n  for (size_t i = start; i <= stop; i++) {\n    Token *t = _tokens[i].get();\n    if (t->getType() == Token::EOF) {\n      break;\n    }\n    subset.push_back(t);\n  }\n  return subset;\n}\n\nsize_t BufferedTokenStream::LA(ssize_t i) {\n  return LT(i)->getType();\n}\n\nToken* BufferedTokenStream::LB(size_t k) {\n  if (k > _p) {\n    return nullptr;\n  }\n  return _tokens[_p - k].get();\n}\n\nToken* BufferedTokenStream::LT(ssize_t k) {\n  lazyInit();\n  if (k == 0) {\n    return nullptr;\n  }\n  if (k < 0) {\n    return LB(-k);\n  }\n\n  size_t i = _p + k - 1;\n  sync(i);\n  if (i >= _tokens.size()) { // return EOF token\n                             // EOF must be last token\n    return _tokens.back().get();\n  }\n\n  return _tokens[i].get();\n}\n\nssize_t BufferedTokenStream::adjustSeekIndex(size_t i) {\n  return i;\n}\n\nvoid BufferedTokenStream::lazyInit() {\n  if (_needSetup) {\n    setup();\n  }\n}\n\nvoid BufferedTokenStream::setup() {\n  _needSetup = false;\n  sync(0);\n  _p = adjustSeekIndex(0);\n}\n\nvoid BufferedTokenStream::setTokenSource(TokenSource *tokenSource) {\n  _tokenSource = tokenSource;\n  _tokens.clear();\n  _fetchedEOF = false;\n  _needSetup = true;\n}\n\nstd::vector<Token *> BufferedTokenStream::getTokens() {\n  std::vector<Token *> result;\n  for (auto &t : _tokens)\n    result.push_back(t.get());\n  return result;\n}\n\nstd::vector<Token *> BufferedTokenStream::getTokens(size_t start, size_t stop) {\n  return getTokens(start, stop, std::vector<size_t>());\n}\n\nstd::vector<Token *> BufferedTokenStream::getTokens(size_t start, size_t stop, const std::vector<size_t> &types) {\n  lazyInit();\n  if (stop >= _tokens.size() || start >= _tokens.size()) {\n    throw IndexOutOfBoundsException(std::string(\"start \") +\n                                    std::to_string(start) +\n                                    std::string(\" or stop \") +\n                                    std::to_string(stop) +\n                                    std::string(\" not in 0..\") +\n                                    std::to_string(_tokens.size() - 1));\n  }\n\n  std::vector<Token *> filteredTokens;\n\n  if (start > stop) {\n    return filteredTokens;\n  }\n\n  for (size_t i = start; i <= stop; i++) {\n    Token *tok = _tokens[i].get();\n\n    if (types.empty() || std::find(types.begin(), types.end(), tok->getType()) != types.end()) {\n      filteredTokens.push_back(tok);\n    }\n  }\n  return filteredTokens;\n}\n\nstd::vector<Token *> BufferedTokenStream::getTokens(size_t start, size_t stop, size_t ttype) {\n  std::vector<size_t> s;\n  s.push_back(ttype);\n  return getTokens(start, stop, s);\n}\n\nssize_t BufferedTokenStream::nextTokenOnChannel(size_t i, size_t channel) {\n  sync(i);\n  if (i >= size()) {\n    return size() - 1;\n  }\n\n  Token *token = _tokens[i].get();\n  while (token->getChannel() != channel) {\n    if (token->getType() == Token::EOF) {\n      return i;\n    }\n    i++;\n    sync(i);\n    token = _tokens[i].get();\n  }\n  return i;\n}\n\nssize_t BufferedTokenStream::previousTokenOnChannel(size_t i, size_t channel) {\n  sync(i);\n  if (i >= size()) {\n    // the EOF token is on every channel\n    return size() - 1;\n  }\n\n  while (true) {\n    Token *token = _tokens[i].get();\n    if (token->getType() == Token::EOF || token->getChannel() == channel) {\n      return i;\n    }\n\n    if (i == 0)\n      return -1;\n    i--;\n  }\n  return i;\n}\n\nstd::vector<Token *> BufferedTokenStream::getHiddenTokensToRight(size_t tokenIndex, ssize_t channel) {\n  lazyInit();\n  if (tokenIndex >= _tokens.size()) {\n    throw IndexOutOfBoundsException(std::to_string(tokenIndex) + \" not in 0..\" + std::to_string(_tokens.size() - 1));\n  }\n\n  ssize_t nextOnChannel = nextTokenOnChannel(tokenIndex + 1, Lexer::DEFAULT_TOKEN_CHANNEL);\n  size_t to;\n  size_t from = tokenIndex + 1;\n  // if none onchannel to right, nextOnChannel=-1 so set to = last token\n  if (nextOnChannel == -1) {\n    to = static_cast<ssize_t>(size() - 1);\n  } else {\n    to = nextOnChannel;\n  }\n\n  return filterForChannel(from, to, channel);\n}\n\nstd::vector<Token *> BufferedTokenStream::getHiddenTokensToRight(size_t tokenIndex) {\n  return getHiddenTokensToRight(tokenIndex, -1);\n}\n\nstd::vector<Token *> BufferedTokenStream::getHiddenTokensToLeft(size_t tokenIndex, ssize_t channel) {\n  lazyInit();\n  if (tokenIndex >= _tokens.size()) {\n    throw IndexOutOfBoundsException(std::to_string(tokenIndex) + \" not in 0..\" + std::to_string(_tokens.size() - 1));\n  }\n\n  if (tokenIndex == 0) {\n    // Obviously no tokens can appear before the first token.\n    return { };\n  }\n\n  ssize_t prevOnChannel = previousTokenOnChannel(tokenIndex - 1, Lexer::DEFAULT_TOKEN_CHANNEL);\n  if (prevOnChannel == static_cast<ssize_t>(tokenIndex - 1)) {\n    return { };\n  }\n  // if none onchannel to left, prevOnChannel=-1 then from=0\n  size_t from = static_cast<size_t>(prevOnChannel + 1);\n  size_t to = tokenIndex - 1;\n\n  return filterForChannel(from, to, channel);\n}\n\nstd::vector<Token *> BufferedTokenStream::getHiddenTokensToLeft(size_t tokenIndex) {\n  return getHiddenTokensToLeft(tokenIndex, -1);\n}\n\nstd::vector<Token *> BufferedTokenStream::filterForChannel(size_t from, size_t to, ssize_t channel) {\n  std::vector<Token *> hidden;\n  for (size_t i = from; i <= to; i++) {\n    Token *t = _tokens[i].get();\n    if (channel == -1) {\n      if (t->getChannel() != Lexer::DEFAULT_TOKEN_CHANNEL) {\n        hidden.push_back(t);\n      }\n    } else {\n      if (t->getChannel() == static_cast<size_t>(channel)) {\n        hidden.push_back(t);\n      }\n    }\n  }\n\n  return hidden;\n}\n\nbool BufferedTokenStream::isInitialized() const {\n  return !_needSetup;\n}\n\n/**\n * Get the text of all tokens in this buffer.\n */\nstd::string BufferedTokenStream::getSourceName() const\n{\n  return _tokenSource->getSourceName();\n}\n\nstd::string BufferedTokenStream::getText() {\n  fill();\n  return getText(misc::Interval(0U, size() - 1));\n}\n\nstd::string BufferedTokenStream::getText(const misc::Interval &interval) {\n  lazyInit();\n  size_t start = interval.a;\n  size_t stop = interval.b;\n  if (start == INVALID_INDEX || stop == INVALID_INDEX) {\n    return \"\";\n  }\n  sync(stop);\n  if (stop >= _tokens.size()) {\n    stop = _tokens.size() - 1;\n  }\n\n  std::stringstream ss;\n  for (size_t i = start; i <= stop; i++) {\n    Token *t = _tokens[i].get();\n    if (t->getType() == Token::EOF) {\n      break;\n    }\n    ss << t->getText();\n  }\n  return ss.str();\n}\n\nstd::string BufferedTokenStream::getText(RuleContext *ctx) {\n  return getText(ctx->getSourceInterval());\n}\n\nstd::string BufferedTokenStream::getText(Token *start, Token *stop) {\n  if (start != nullptr && stop != nullptr) {\n    return getText(misc::Interval(start->getTokenIndex(), stop->getTokenIndex()));\n  }\n\n  return \"\";\n}\n\nvoid BufferedTokenStream::fill() {\n  lazyInit();\n  const size_t blockSize = 1000;\n  while (true) {\n    size_t fetched = fetch(blockSize);\n    if (fetched < blockSize) {\n      return;\n    }\n  }\n}\n\nvoid BufferedTokenStream::InitializeInstanceFields() {\n  _needSetup = true;\n  _fetchedEOF = false;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/BufferedTokenStream.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"TokenStream.h\"\n\nnamespace antlr4 {\n\n  /**\n   * This implementation of {@link TokenStream} loads tokens from a\n   * {@link TokenSource} on-demand, and places the tokens in a buffer to provide\n   * access to any previous token by index.\n   *\n   * <p>\n   * This token stream ignores the value of {@link Token#getChannel}. If your\n   * parser requires the token stream filter tokens to only those on a particular\n   * channel, such as {@link Token#DEFAULT_CHANNEL} or\n   * {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a\n   * {@link CommonTokenStream}.</p>\n   */\n  class ANTLR4CPP_PUBLIC BufferedTokenStream : public TokenStream {\n  public:\n    BufferedTokenStream(TokenSource *tokenSource);\n    BufferedTokenStream(const BufferedTokenStream& other) = delete;\n\n    BufferedTokenStream& operator = (const BufferedTokenStream& other) = delete;\n\n    TokenSource* getTokenSource() const override;\n    size_t index() override;\n    ssize_t mark() override;\n\n    void release(ssize_t marker) override;\n    virtual void reset();\n    void seek(size_t index) override;\n\n    size_t size() override;\n    void consume() override;\n\n    Token* get(size_t i) const override;\n\n    /// Get all tokens from start..stop inclusively.\n    virtual std::vector<Token *> get(size_t start, size_t stop);\n\n    size_t LA(ssize_t i) override;\n    Token* LT(ssize_t k) override;\n\n    /// Reset this token stream by setting its token source.\n    virtual void setTokenSource(TokenSource *tokenSource);\n    virtual std::vector<Token *> getTokens();\n    virtual std::vector<Token *> getTokens(size_t start, size_t stop);\n\n    /// <summary>\n    /// Given a start and stop index, return a List of all tokens in\n    ///  the token type BitSet.  Return null if no tokens were found.  This\n    ///  method looks at both on and off channel tokens.\n    /// </summary>\n    virtual std::vector<Token *> getTokens(size_t start, size_t stop, const std::vector<size_t> &types);\n    virtual std::vector<Token *> getTokens(size_t start, size_t stop, size_t ttype);\n\n    /// Collect all tokens on specified channel to the right of\n    ///  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or\n    ///  EOF. If channel is -1, find any non default channel token.\n    virtual std::vector<Token *> getHiddenTokensToRight(size_t tokenIndex, ssize_t channel);\n\n    /// <summary>\n    /// Collect all hidden tokens (any off-default channel) to the right of\n    ///  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL\n    ///  or EOF.\n    /// </summary>\n    virtual std::vector<Token *> getHiddenTokensToRight(size_t tokenIndex);\n\n    /// <summary>\n    /// Collect all tokens on specified channel to the left of\n    ///  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n    ///  If channel is -1, find any non default channel token.\n    /// </summary>\n    virtual std::vector<Token *> getHiddenTokensToLeft(size_t tokenIndex, ssize_t channel);\n\n    /// <summary>\n    /// Collect all hidden tokens (any off-default channel) to the left of\n    ///  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n    /// </summary>\n    virtual std::vector<Token *> getHiddenTokensToLeft(size_t tokenIndex);\n\n    std::string getSourceName() const override;\n    std::string getText() override;\n    std::string getText(const misc::Interval &interval) override;\n    std::string getText(RuleContext *ctx) override;\n    std::string getText(Token *start, Token *stop) override;\n\n    /// Get all tokens from lexer until EOF.\n    virtual void fill();\n\n  protected:\n    /**\n     * The {@link TokenSource} from which tokens for this stream are fetched.\n     */\n    TokenSource *_tokenSource;\n\n    /**\n     * A collection of all tokens fetched from the token source. The list is\n     * considered a complete view of the input once {@link #fetchedEOF} is set\n     * to {@code true}.\n     */\n    std::vector<std::unique_ptr<Token>> _tokens;\n\n    /**\n     * The index into {@link #tokens} of the current token (next token to\n     * {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be\n     * {@link #LT LT(1)}.\n     *\n     * <p>This field is set to -1 when the stream is first constructed or when\n     * {@link #setTokenSource} is called, indicating that the first token has\n     * not yet been fetched from the token source. For additional information,\n     * see the documentation of {@link IntStream} for a description of\n     * Initializing Methods.</p>\n     */\n    // ml: since -1 requires to make this member signed for just this single aspect we use a member _needSetup instead.\n    //     Use bool isInitialized() to find out if this stream has started reading.\n    size_t _p;\n\n    /**\n     * Indicates whether the {@link Token#EOF} token has been fetched from\n     * {@link #tokenSource} and added to {@link #tokens}. This field improves\n     * performance for the following cases:\n     *\n     * <ul>\n     * <li>{@link #consume}: The lookahead check in {@link #consume} to prevent\n     * consuming the EOF symbol is optimized by checking the values of\n     * {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li>\n     * <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into\n     * {@link #tokens} is trivial with this field.</li>\n     * <ul>\n     */\n    bool _fetchedEOF;\n\n    /// <summary>\n    /// Make sure index {@code i} in tokens has a token.\n    /// </summary>\n    /// <returns> {@code true} if a token is located at index {@code i}, otherwise\n    ///    {@code false}. </returns>\n    /// <seealso cref= #get(int i) </seealso>\n    virtual bool sync(size_t i);\n\n    /// <summary>\n    /// Add {@code n} elements to buffer.\n    /// </summary>\n    /// <returns> The actual number of elements added to the buffer. </returns>\n    virtual size_t fetch(size_t n);\n\n    virtual Token* LB(size_t k);\n\n    /// Allowed derived classes to modify the behavior of operations which change\n    /// the current stream position by adjusting the target token index of a seek\n    /// operation. The default implementation simply returns {@code i}. If an\n    /// exception is thrown in this method, the current stream index should not be\n    /// changed.\n    /// <p/>\n    /// For example, <seealso cref=\"CommonTokenStream\"/> overrides this method to ensure that\n    /// the seek target is always an on-channel token.\n    ///\n    /// <param name=\"i\"> The target token index. </param>\n    /// <returns> The adjusted target token index. </returns>\n    virtual ssize_t adjustSeekIndex(size_t i);\n    void lazyInit();\n    virtual void setup();\n\n    /**\n     * Given a starting index, return the index of the next token on channel.\n     * Return {@code i} if {@code tokens[i]} is on channel. Return the index of\n     * the EOF token if there are no tokens on channel between {@code i} and\n     * EOF.\n     */\n    virtual ssize_t nextTokenOnChannel(size_t i, size_t channel);\n\n    /**\n     * Given a starting index, return the index of the previous token on\n     * channel. Return {@code i} if {@code tokens[i]} is on channel. Return -1\n     * if there are no tokens on channel between {@code i} and 0.\n     *\n     * <p>\n     * If {@code i} specifies an index at or after the EOF token, the EOF token\n     * index is returned. This is due to the fact that the EOF token is treated\n     * as though it were on every channel.</p>\n     */\n    virtual ssize_t previousTokenOnChannel(size_t i, size_t channel);\n\n    virtual std::vector<Token *> filterForChannel(size_t from, size_t to, ssize_t channel);\n\n    bool isInitialized() const;\n\n  private:\n    bool _needSetup;\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CharStream.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"CharStream.h\"\n\nusing namespace antlr4;\n\nCharStream::~CharStream() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CharStream.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"IntStream.h\"\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n\nnamespace antlr4 {\n\n  /// A source of characters for an ANTLR lexer.\n  class ANTLR4CPP_PUBLIC CharStream : public IntStream {\n  public:\n    ~CharStream() override;\n\n    /// This method returns the text for a range of characters within this input\n    /// stream. This method is guaranteed to not throw an exception if the\n    /// specified interval lies entirely within a marked range. For more\n    /// information about marked ranges, see IntStream::mark.\n    ///\n    /// <param name=\"interval\"> an interval within the stream </param>\n    /// <returns> the text of the specified interval\n    /// </returns>\n    /// <exception cref=\"NullPointerException\"> if {@code interval} is {@code null} </exception>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code interval.a < 0}, or if\n    /// {@code interval.b < interval.a - 1}, or if {@code interval.b} lies at or\n    /// past the end of the stream </exception>\n    /// <exception cref=\"UnsupportedOperationException\"> if the stream does not support\n    /// getting the text of the specified interval </exception>\n    virtual std::string getText(const misc::Interval &interval) = 0;\n\n    virtual std::string toString() const = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CommonToken.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"TokenSource.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"CharStream.h\"\n#include \"Recognizer.h\"\n#include \"Vocabulary.h\"\n\n#include \"misc/Interval.h\"\n\n#include \"support/CPPUtils.h\"\n#include \"support/StringUtils.h\"\n\n#include \"CommonToken.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::misc;\n\nusing namespace antlrcpp;\n\nconst std::pair<TokenSource*, CharStream*> CommonToken::EMPTY_SOURCE;\n\nCommonToken::CommonToken(size_t type) {\n  InitializeInstanceFields();\n  _type = type;\n}\n\nCommonToken::CommonToken(std::pair<TokenSource*, CharStream*> source, size_t type, size_t channel, size_t start, size_t stop) {\n  InitializeInstanceFields();\n  _source = source;\n  _type = type;\n  _channel = channel;\n  _start = start;\n  _stop = stop;\n  if (_source.first != nullptr) {\n    _line = static_cast<int>(source.first->getLine());\n    _charPositionInLine = source.first->getCharPositionInLine();\n  }\n}\n\nCommonToken::CommonToken(size_t type, const std::string &text) {\n  InitializeInstanceFields();\n  _type = type;\n  _channel = DEFAULT_CHANNEL;\n  _text = text;\n  _source = EMPTY_SOURCE;\n}\n\nCommonToken::CommonToken(Token *oldToken) {\n  InitializeInstanceFields();\n  _type = oldToken->getType();\n  _line = oldToken->getLine();\n  _index = oldToken->getTokenIndex();\n  _charPositionInLine = oldToken->getCharPositionInLine();\n  _channel = oldToken->getChannel();\n  _start = oldToken->getStartIndex();\n  _stop = oldToken->getStopIndex();\n\n  if (is<CommonToken *>(oldToken)) {\n    _text = (static_cast<CommonToken *>(oldToken))->_text;\n    _source = (static_cast<CommonToken *>(oldToken))->_source;\n  } else {\n    _text = oldToken->getText();\n    _source = { oldToken->getTokenSource(), oldToken->getInputStream() };\n  }\n}\n\nsize_t CommonToken::getType() const {\n  return _type;\n}\n\nvoid CommonToken::setLine(size_t line) {\n  _line = line;\n}\n\nstd::string CommonToken::getText() const {\n  if (!_text.empty()) {\n    return _text;\n  }\n\n  CharStream *input = getInputStream();\n  if (input == nullptr) {\n    return \"\";\n  }\n  size_t n = input->size();\n  if (_start < n && _stop < n) {\n    return input->getText(misc::Interval(_start, _stop));\n  } else {\n    return \"<EOF>\";\n  }\n}\n\nvoid CommonToken::setText(const std::string &text) {\n  _text = text;\n}\n\nsize_t CommonToken::getLine() const {\n  return _line;\n}\n\nsize_t CommonToken::getCharPositionInLine() const {\n  return _charPositionInLine;\n}\n\nvoid CommonToken::setCharPositionInLine(size_t charPositionInLine) {\n  _charPositionInLine = charPositionInLine;\n}\n\nsize_t CommonToken::getChannel() const {\n  return _channel;\n}\n\nvoid CommonToken::setChannel(size_t channel) {\n  _channel = channel;\n}\n\nvoid CommonToken::setType(size_t type) {\n  _type = type;\n}\n\nsize_t CommonToken::getStartIndex() const {\n  return _start;\n}\n\nvoid CommonToken::setStartIndex(size_t start) {\n  _start = start;\n}\n\nsize_t CommonToken::getStopIndex() const {\n  return _stop;\n}\n\nvoid CommonToken::setStopIndex(size_t stop) {\n  _stop = stop;\n}\n\nsize_t CommonToken::getTokenIndex() const {\n  return _index;\n}\n\nvoid CommonToken::setTokenIndex(size_t index) {\n  _index = index;\n}\n\nantlr4::TokenSource *CommonToken::getTokenSource() const {\n  return _source.first;\n}\n\nantlr4::CharStream *CommonToken::getInputStream() const {\n  return _source.second;\n}\n\nstd::string CommonToken::toString() const {\n  return toString(nullptr);\n}\n\nstd::string CommonToken::toString(Recognizer *r) const {\n  std::stringstream ss;\n\n  std::string channelStr;\n  if (_channel > 0) {\n    channelStr = \",channel=\" + std::to_string(_channel);\n  }\n  std::string txt = getText();\n  if (!txt.empty()) {\n    txt = antlrcpp::escapeWhitespace(txt);\n  } else {\n    txt = \"<no text>\";\n  }\n\n  std::string typeString = std::to_string(symbolToNumeric(_type));\n  if (r != nullptr)\n    typeString = r->getVocabulary().getDisplayName(_type);\n\n  ss << \"[@\" << symbolToNumeric(getTokenIndex()) << \",\" << symbolToNumeric(_start) << \":\" << symbolToNumeric(_stop)\n    << \"='\" << txt << \"',<\" << typeString << \">\" << channelStr << \",\" << _line << \":\"\n    << getCharPositionInLine() << \"]\";\n\n  return ss.str();\n}\n\nvoid CommonToken::InitializeInstanceFields() {\n  _type = 0;\n  _line = 0;\n  _charPositionInLine = INVALID_INDEX;\n  _channel = DEFAULT_CHANNEL;\n  _index = INVALID_INDEX;\n  _start = 0;\n  _stop = 0;\n  _source = EMPTY_SOURCE;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CommonToken.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"WritableToken.h\"\n\nnamespace antlr4 {\n\n  class ANTLR4CPP_PUBLIC CommonToken : public WritableToken {\n  protected:\n    /**\n     * An empty {@link Pair} which is used as the default value of\n     * {@link #source} for tokens that do not have a source.\n     */\n    static const std::pair<TokenSource *, CharStream *> EMPTY_SOURCE;\n\n    /**\n     * This is the backing field for {@link #getType} and {@link #setType}.\n     */\n    size_t _type;\n\n    /**\n     * This is the backing field for {@link #getLine} and {@link #setLine}.\n     */\n    size_t _line;\n\n    /**\n     * This is the backing field for {@link #getCharPositionInLine} and\n     * {@link #setCharPositionInLine}.\n     */\n    size_t _charPositionInLine; // set to invalid position\n\n    /**\n     * This is the backing field for {@link #getChannel} and\n     * {@link #setChannel}.\n     */\n    size_t _channel;\n\n    /**\n     * This is the backing field for {@link #getTokenSource} and\n     * {@link #getInputStream}.\n     *\n     * <p>\n     * These properties share a field to reduce the memory footprint of\n     * {@link CommonToken}. Tokens created by a {@link CommonTokenFactory} from\n     * the same source and input stream share a reference to the same\n     * {@link Pair} containing these values.</p>\n     */\n\n    std::pair<TokenSource *, CharStream *> _source; // ml: pure references, usually from statically allocated classes.\n\n    /**\n     * This is the backing field for {@link #getText} when the token text is\n     * explicitly set in the constructor or via {@link #setText}.\n     *\n     * @see #getText()\n     */\n    std::string _text;\n\n    /**\n     * This is the backing field for {@link #getTokenIndex} and\n     * {@link #setTokenIndex}.\n     */\n    size_t _index;\n\n    /**\n     * This is the backing field for {@link #getStartIndex} and\n     * {@link #setStartIndex}.\n     */\n    size_t _start;\n\n    /**\n     * This is the backing field for {@link #getStopIndex} and\n     * {@link #setStopIndex}.\n     */\n    size_t _stop;\n\n  public:\n    /**\n     * Constructs a new {@link CommonToken} with the specified token type.\n     *\n     * @param type The token type.\n     */\n    CommonToken(size_t type);\n    CommonToken(std::pair<TokenSource*, CharStream*> source, size_t type, size_t channel, size_t start, size_t stop);\n\n    /**\n     * Constructs a new {@link CommonToken} with the specified token type and\n     * text.\n     *\n     * @param type The token type.\n     * @param text The text of the token.\n     */\n    CommonToken(size_t type, const std::string &text);\n\n    /**\n     * Constructs a new {@link CommonToken} as a copy of another {@link Token}.\n     *\n     * <p>\n     * If {@code oldToken} is also a {@link CommonToken} instance, the newly\n     * constructed token will share a reference to the {@link #text} field and\n     * the {@link Pair} stored in {@link #source}. Otherwise, {@link #text} will\n     * be assigned the result of calling {@link #getText}, and {@link #source}\n     * will be constructed from the result of {@link Token#getTokenSource} and\n     * {@link Token#getInputStream}.</p>\n     *\n     * @param oldToken The token to copy.\n     */\n    CommonToken(Token *oldToken);\n\n    size_t getType() const override;\n\n    /**\n     * Explicitly set the text for this token. If {code text} is not\n     * {@code null}, then {@link #getText} will return this value rather than\n     * extracting the text from the input.\n     *\n     * @param text The explicit text of the token, or {@code null} if the text\n     * should be obtained from the input along with the start and stop indexes\n     * of the token.\n     */\n    void setText(const std::string &text) override;\n    std::string getText() const override;\n\n    void setLine(size_t line) override;\n    size_t getLine() const override;\n\n    size_t getCharPositionInLine() const override;\n    void setCharPositionInLine(size_t charPositionInLine) override;\n\n    size_t getChannel() const override;\n    void setChannel(size_t channel) override;\n\n    void setType(size_t type) override;\n\n    size_t getStartIndex() const override;\n    virtual void setStartIndex(size_t start);\n\n    size_t getStopIndex() const override;\n    virtual void setStopIndex(size_t stop);\n\n    size_t getTokenIndex() const override;\n    void setTokenIndex(size_t index) override;\n\n    TokenSource *getTokenSource() const override;\n    CharStream *getInputStream() const override;\n\n    std::string toString() const override;\n\n    virtual std::string toString(Recognizer *r) const;\n  private:\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CommonTokenFactory.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/Interval.h\"\n#include \"CommonToken.h\"\n#include \"CharStream.h\"\n\n#include \"CommonTokenFactory.h\"\n\nusing namespace antlr4;\n\nconst std::unique_ptr<TokenFactory<CommonToken>> CommonTokenFactory::DEFAULT(new CommonTokenFactory);\n\nCommonTokenFactory::CommonTokenFactory(bool copyText_) : copyText(copyText_) {\n}\n\nCommonTokenFactory::CommonTokenFactory() : CommonTokenFactory(false) {\n}\n\nstd::unique_ptr<CommonToken> CommonTokenFactory::create(std::pair<TokenSource*, CharStream*> source, size_t type,\n  const std::string &text, size_t channel, size_t start, size_t stop, size_t line, size_t charPositionInLine) {\n\n  std::unique_ptr<CommonToken> t(new CommonToken(source, type, channel, start, stop));\n  t->setLine(line);\n  t->setCharPositionInLine(charPositionInLine);\n  if (text != \"\") {\n    t->setText(text);\n  } else if (copyText && source.second != nullptr) {\n    t->setText(source.second->getText(misc::Interval(start, stop)));\n  }\n\n  return t;\n}\n\nstd::unique_ptr<CommonToken> CommonTokenFactory::create(size_t type, const std::string &text) {\n  return std::unique_ptr<CommonToken>(new CommonToken(type, text));\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CommonTokenFactory.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"TokenFactory.h\"\n\nnamespace antlr4 {\n\n  /**\n   * This default implementation of {@link TokenFactory} creates\n   * {@link CommonToken} objects.\n   */\n  class ANTLR4CPP_PUBLIC CommonTokenFactory : public TokenFactory<CommonToken> {\n  public:\n    /**\n     * The default {@link CommonTokenFactory} instance.\n     *\n     * <p>\n     * This token factory does not explicitly copy token text when constructing\n     * tokens.</p>\n     */\n    static const std::unique_ptr<TokenFactory<CommonToken>> DEFAULT;\n\n  protected:\n    /**\n     * Indicates whether {@link CommonToken#setText} should be called after\n     * constructing tokens to explicitly set the text. This is useful for cases\n     * where the input stream might not be able to provide arbitrary substrings\n     * of text from the input after the lexer creates a token (e.g. the\n     * implementation of {@link CharStream#getText} in\n     * {@link UnbufferedCharStream} throws an\n     * {@link UnsupportedOperationException}). Explicitly setting the token text\n     * allows {@link Token#getText} to be called at any time regardless of the\n     * input stream implementation.\n     *\n     * <p>\n     * The default value is {@code false} to avoid the performance and memory\n     * overhead of copying text for every token unless explicitly requested.</p>\n     */\n    const bool copyText;\n\n  public:\n    /**\n     * Constructs a {@link CommonTokenFactory} with the specified value for\n     * {@link #copyText}.\n     *\n     * <p>\n     * When {@code copyText} is {@code false}, the {@link #DEFAULT} instance\n     * should be used instead of constructing a new instance.</p>\n     *\n     * @param copyText The value for {@link #copyText}.\n     */\n    CommonTokenFactory(bool copyText);\n\n    /**\n     * Constructs a {@link CommonTokenFactory} with {@link #copyText} set to\n     * {@code false}.\n     *\n     * <p>\n     * The {@link #DEFAULT} instance should be used instead of calling this\n     * directly.</p>\n     */\n    CommonTokenFactory();\n\n    std::unique_ptr<CommonToken> create(std::pair<TokenSource*, CharStream*> source, size_t type,\n      const std::string &text, size_t channel, size_t start, size_t stop, size_t line, size_t charPositionInLine) override;\n\n    std::unique_ptr<CommonToken> create(size_t type, const std::string &text) override;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CommonTokenStream.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"Token.h\"\n\n#include \"antlr4-common.h\"\n#include \"CommonTokenStream.h\"\n\nusing namespace antlr4;\n\nCommonTokenStream::CommonTokenStream(TokenSource *tokenSource) : CommonTokenStream(tokenSource, Token::DEFAULT_CHANNEL) {\n}\n\nCommonTokenStream::CommonTokenStream(TokenSource *tokenSource, size_t channel_)\n: BufferedTokenStream(tokenSource), channel(channel_) {\n}\n\nssize_t CommonTokenStream::adjustSeekIndex(size_t i) {\n  return nextTokenOnChannel(i, channel);\n}\n\nToken* CommonTokenStream::LB(size_t k) {\n  if (k == 0 || k > _p) {\n    return nullptr;\n  }\n\n  ssize_t i = static_cast<ssize_t>(_p);\n  size_t n = 1;\n  // find k good tokens looking backwards\n  while (n <= k) {\n    // skip off-channel tokens\n    i = previousTokenOnChannel(i - 1, channel);\n    n++;\n  }\n  if (i < 0) {\n    return nullptr;\n  }\n\n  return _tokens[i].get();\n}\n\nToken* CommonTokenStream::LT(ssize_t k) {\n  lazyInit();\n  if (k == 0) {\n    return nullptr;\n  }\n  if (k < 0) {\n    return LB(static_cast<size_t>(-k));\n  }\n  size_t i = _p;\n  ssize_t n = 1; // we know tokens[p] is a good one\n                 // find k good tokens\n  while (n < k) {\n    // skip off-channel tokens, but make sure to not look past EOF\n    if (sync(i + 1)) {\n      i = nextTokenOnChannel(i + 1, channel);\n    }\n    n++;\n  }\n\n  return _tokens[i].get();\n}\n\nint CommonTokenStream::getNumberOfOnChannelTokens() {\n  int n = 0;\n  fill();\n  for (size_t i = 0; i < _tokens.size(); i++) {\n    Token *t = _tokens[i].get();\n    if (t->getChannel() == channel) {\n      n++;\n    }\n    if (t->getType() == Token::EOF) {\n      break;\n    }\n  }\n  return n;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/CommonTokenStream.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"BufferedTokenStream.h\"\n\nnamespace antlr4 {\n\n  /**\n   * This class extends {@link BufferedTokenStream} with functionality to filter\n   * token streams to tokens on a particular channel (tokens where\n   * {@link Token#getChannel} returns a particular value).\n   *\n   * <p>\n   * This token stream provides access to all tokens by index or when calling\n   * methods like {@link #getText}. The channel filtering is only used for code\n   * accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and\n   * {@link #LB}.</p>\n   *\n   * <p>\n   * By default, tokens are placed on the default channel\n   * ({@link Token#DEFAULT_CHANNEL}), but may be reassigned by using the\n   * {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to\n   * call {@link Lexer#setChannel}.\n   * </p>\n   *\n   * <p>\n   * Note: lexer rules which use the {@code ->skip} lexer command or call\n   * {@link Lexer#skip} do not produce tokens at all, so input text matched by\n   * such a rule will not be available as part of the token stream, regardless of\n   * channel.</p>\n   */\n  class ANTLR4CPP_PUBLIC CommonTokenStream : public BufferedTokenStream {\n  public:\n    /**\n     * Constructs a new {@link CommonTokenStream} using the specified token\n     * source and the default token channel ({@link Token#DEFAULT_CHANNEL}).\n     *\n     * @param tokenSource The token source.\n     */\n    CommonTokenStream(TokenSource *tokenSource);\n\n    /**\n     * Constructs a new {@link CommonTokenStream} using the specified token\n     * source and filtering tokens to the specified channel. Only tokens whose\n     * {@link Token#getChannel} matches {@code channel} or have the\n     * {@link Token#getType} equal to {@link Token#EOF} will be returned by the\n     * token stream lookahead methods.\n     *\n     * @param tokenSource The token source.\n     * @param channel The channel to use for filtering tokens.\n     */\n    CommonTokenStream(TokenSource *tokenSource, size_t channel);\n\n    Token* LT(ssize_t k) override;\n\n    /// Count EOF just once.\n    virtual int getNumberOfOnChannelTokens();\n    \n  protected:\n    /**\n     * Specifies the channel to use for filtering tokens.\n     *\n     * <p>\n     * The default value is {@link Token#DEFAULT_CHANNEL}, which matches the\n     * default channel assigned to tokens created by the lexer.</p>\n     */\n    size_t channel;\n\n    ssize_t adjustSeekIndex(size_t i) override;\n\n    Token* LB(size_t k) override;\n\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ConsoleErrorListener.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"Token.h\"\n#include \"ConsoleErrorListener.h\"\n\nusing namespace antlr4;\n\nConsoleErrorListener ConsoleErrorListener::INSTANCE;\n\nvoid ConsoleErrorListener::syntaxError(Recognizer * /*recognizer*/, Token * /*offendingSymbol*/,\n  size_t line, size_t charPositionInLine, const std::string &msg, std::exception_ptr /*e*/)  {\n  std::cerr << \"line \" << line << \":\" << charPositionInLine << \" \" << msg << std::endl;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ConsoleErrorListener.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"BaseErrorListener.h\"\n\nnamespace antlr4 {\n\n  class ANTLR4CPP_PUBLIC ConsoleErrorListener : public BaseErrorListener {\n  public:\n    /**\n     * Provides a default instance of {@link ConsoleErrorListener}.\n     */\n    static ConsoleErrorListener INSTANCE;\n\n    /**\n     * {@inheritDoc}\n     *\n     * <p>\n     * This implementation prints messages to {@link System#err} containing the\n     * values of {@code line}, {@code charPositionInLine}, and {@code msg} using\n     * the following format.</p>\n     *\n     * <pre>\n     * line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>\n     * </pre>\n     */\n    void syntaxError(Recognizer *recognizer, Token * offendingSymbol, size_t line, size_t charPositionInLine,\n                             const std::string &msg, std::exception_ptr e) override;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/DefaultErrorStrategy.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"NoViableAltException.h\"\n#include \"atn/ATNStateType.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/ParserATNSimulator.h\"\n#include \"InputMismatchException.h\"\n#include \"FailedPredicateException.h\"\n#include \"ParserRuleContext.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/ATN.h\"\n#include \"atn/ATNState.h\"\n#include \"support/StringUtils.h\"\n#include \"support/Casts.h\"\n#include \"Parser.h\"\n#include \"CommonToken.h\"\n#include \"Vocabulary.h\"\n\n#include \"DefaultErrorStrategy.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nusing namespace antlrcpp;\n\nDefaultErrorStrategy::DefaultErrorStrategy() {\n  InitializeInstanceFields();\n}\n\nDefaultErrorStrategy::~DefaultErrorStrategy() {\n}\n\nvoid DefaultErrorStrategy::reset(Parser *recognizer) {\n  _errorSymbols.clear();\n  endErrorCondition(recognizer);\n}\n\nvoid DefaultErrorStrategy::beginErrorCondition(Parser * /*recognizer*/) {\n  errorRecoveryMode = true;\n}\n\nbool DefaultErrorStrategy::inErrorRecoveryMode(Parser * /*recognizer*/) {\n  return errorRecoveryMode;\n}\n\nvoid DefaultErrorStrategy::endErrorCondition(Parser * /*recognizer*/) {\n  errorRecoveryMode = false;\n  lastErrorIndex = -1;\n}\n\nvoid DefaultErrorStrategy::reportMatch(Parser *recognizer) {\n  endErrorCondition(recognizer);\n}\n\nvoid DefaultErrorStrategy::reportError(Parser *recognizer, const RecognitionException &e) {\n  // If we've already reported an error and have not matched a token\n  // yet successfully, don't report any errors.\n  if (inErrorRecoveryMode(recognizer)) {\n    return; // don't report spurious errors\n  }\n\n  beginErrorCondition(recognizer);\n  if (is<const NoViableAltException *>(&e)) {\n    reportNoViableAlternative(recognizer, static_cast<const NoViableAltException &>(e));\n  } else if (is<const InputMismatchException *>(&e)) {\n    reportInputMismatch(recognizer, static_cast<const InputMismatchException &>(e));\n  } else if (is<const FailedPredicateException *>(&e)) {\n    reportFailedPredicate(recognizer, static_cast<const FailedPredicateException &>(e));\n  } else if (is<const RecognitionException *>(&e)) {\n    recognizer->notifyErrorListeners(e.getOffendingToken(), e.what(), std::current_exception());\n  }\n}\n\nvoid DefaultErrorStrategy::recover(Parser *recognizer, std::exception_ptr /*e*/) {\n  if (lastErrorIndex == static_cast<int>(recognizer->getInputStream()->index()) &&\n      lastErrorStates.contains(recognizer->getState())) {\n\n    // uh oh, another error at same token index and previously-visited\n    // state in ATN; must be a case where LT(1) is in the recovery\n    // token set so nothing got consumed. Consume a single token\n    // at least to prevent an infinite loop; this is a failsafe.\n    recognizer->consume();\n  }\n  lastErrorIndex = static_cast<int>(recognizer->getInputStream()->index());\n  lastErrorStates.add(recognizer->getState());\n  misc::IntervalSet followSet = getErrorRecoverySet(recognizer);\n  consumeUntil(recognizer, followSet);\n}\n\nvoid DefaultErrorStrategy::sync(Parser *recognizer) {\n  atn::ATNState *s = recognizer->getInterpreter<atn::ATNSimulator>()->atn.states[recognizer->getState()];\n\n  // If already recovering, don't try to sync\n  if (inErrorRecoveryMode(recognizer)) {\n    return;\n  }\n\n  TokenStream *tokens = recognizer->getTokenStream();\n  size_t la = tokens->LA(1);\n\n  // try cheaper subset first; might get lucky. seems to shave a wee bit off\n  auto nextTokens = recognizer->getATN().nextTokens(s);\n  if (nextTokens.contains(Token::EPSILON) || nextTokens.contains(la)) {\n    return;\n  }\n\n  switch (s->getStateType()) {\n    case atn::ATNStateType::BLOCK_START:\n    case atn::ATNStateType::STAR_BLOCK_START:\n    case atn::ATNStateType::PLUS_BLOCK_START:\n    case atn::ATNStateType::STAR_LOOP_ENTRY:\n      // report error and recover if possible\n      if (singleTokenDeletion(recognizer) != nullptr) {\n        return;\n      }\n\n      throw InputMismatchException(recognizer);\n\n    case atn::ATNStateType::PLUS_LOOP_BACK:\n    case atn::ATNStateType::STAR_LOOP_BACK: {\n      reportUnwantedToken(recognizer);\n      misc::IntervalSet expecting = recognizer->getExpectedTokens();\n      misc::IntervalSet whatFollowsLoopIterationOrRule = expecting.Or(getErrorRecoverySet(recognizer));\n      consumeUntil(recognizer, whatFollowsLoopIterationOrRule);\n    }\n      break;\n\n    default:\n      // do nothing if we can't identify the exact kind of ATN state\n      break;\n  }\n}\n\nvoid DefaultErrorStrategy::reportNoViableAlternative(Parser *recognizer, const NoViableAltException &e) {\n  TokenStream *tokens = recognizer->getTokenStream();\n  std::string input;\n  if (tokens != nullptr) {\n    if (e.getStartToken()->getType() == Token::EOF) {\n      input = \"<EOF>\";\n    } else {\n      input = tokens->getText(e.getStartToken(), e.getOffendingToken());\n    }\n  } else {\n    input = \"<unknown input>\";\n  }\n  std::string msg = \"no viable alternative at input \" + escapeWSAndQuote(input);\n  recognizer->notifyErrorListeners(e.getOffendingToken(), msg, std::make_exception_ptr(e));\n}\n\nvoid DefaultErrorStrategy::reportInputMismatch(Parser *recognizer, const InputMismatchException &e) {\n  std::string msg = \"mismatched input \" + getTokenErrorDisplay(e.getOffendingToken()) +\n  \" expecting \" + e.getExpectedTokens().toString(recognizer->getVocabulary());\n  recognizer->notifyErrorListeners(e.getOffendingToken(), msg, std::make_exception_ptr(e));\n}\n\nvoid DefaultErrorStrategy::reportFailedPredicate(Parser *recognizer, const FailedPredicateException &e) {\n  const std::string& ruleName = recognizer->getRuleNames()[recognizer->getContext()->getRuleIndex()];\n  std::string msg = \"rule \" + ruleName + \" \" + e.what();\n  recognizer->notifyErrorListeners(e.getOffendingToken(), msg, std::make_exception_ptr(e));\n}\n\nvoid DefaultErrorStrategy::reportUnwantedToken(Parser *recognizer) {\n  if (inErrorRecoveryMode(recognizer)) {\n    return;\n  }\n\n  beginErrorCondition(recognizer);\n\n  Token *t = recognizer->getCurrentToken();\n  std::string tokenName = getTokenErrorDisplay(t);\n  misc::IntervalSet expecting = getExpectedTokens(recognizer);\n\n  std::string msg = \"extraneous input \" + tokenName + \" expecting \" + expecting.toString(recognizer->getVocabulary());\n  recognizer->notifyErrorListeners(t, msg, nullptr);\n}\n\nvoid DefaultErrorStrategy::reportMissingToken(Parser *recognizer) {\n  if (inErrorRecoveryMode(recognizer)) {\n    return;\n  }\n\n  beginErrorCondition(recognizer);\n\n  Token *t = recognizer->getCurrentToken();\n  misc::IntervalSet expecting = getExpectedTokens(recognizer);\n  std::string expectedText = expecting.toString(recognizer->getVocabulary());\n  std::string msg = \"missing \" + expectedText + \" at \" + getTokenErrorDisplay(t);\n\n  recognizer->notifyErrorListeners(t, msg, nullptr);\n}\n\nToken* DefaultErrorStrategy::recoverInline(Parser *recognizer) {\n  // Single token deletion.\n  Token *matchedSymbol = singleTokenDeletion(recognizer);\n  if (matchedSymbol) {\n    // We have deleted the extra token.\n    // Now, move past ttype token as if all were ok.\n    recognizer->consume();\n    return matchedSymbol;\n  }\n\n  // Single token insertion.\n  if (singleTokenInsertion(recognizer)) {\n    return getMissingSymbol(recognizer);\n  }\n\n  // Even that didn't work; must throw the exception.\n  throw InputMismatchException(recognizer);\n}\n\nbool DefaultErrorStrategy::singleTokenInsertion(Parser *recognizer) {\n  ssize_t currentSymbolType = recognizer->getInputStream()->LA(1);\n\n  // if current token is consistent with what could come after current\n  // ATN state, then we know we're missing a token; error recovery\n  // is free to conjure up and insert the missing token\n  atn::ATNState *currentState = recognizer->getInterpreter<atn::ATNSimulator>()->atn.states[recognizer->getState()];\n  atn::ATNState *next = currentState->transitions[0]->target;\n  const atn::ATN &atn = recognizer->getInterpreter<atn::ATNSimulator>()->atn;\n  misc::IntervalSet expectingAtLL2 = atn.nextTokens(next, recognizer->getContext());\n  if (expectingAtLL2.contains(currentSymbolType)) {\n    reportMissingToken(recognizer);\n    return true;\n  }\n  return false;\n}\n\nToken* DefaultErrorStrategy::singleTokenDeletion(Parser *recognizer) {\n  size_t nextTokenType = recognizer->getInputStream()->LA(2);\n  misc::IntervalSet expecting = getExpectedTokens(recognizer);\n  if (expecting.contains(nextTokenType)) {\n    reportUnwantedToken(recognizer);\n    recognizer->consume(); // simply delete extra token\n                           // we want to return the token we're actually matching\n    Token *matchedSymbol = recognizer->getCurrentToken();\n    reportMatch(recognizer); // we know current token is correct\n    return matchedSymbol;\n  }\n  return nullptr;\n}\n\nToken* DefaultErrorStrategy::getMissingSymbol(Parser *recognizer) {\n  Token *currentSymbol = recognizer->getCurrentToken();\n  misc::IntervalSet expecting = getExpectedTokens(recognizer);\n  size_t expectedTokenType = expecting.getMinElement(); // get any element\n  std::string tokenText;\n  if (expectedTokenType == Token::EOF) {\n    tokenText = \"<missing EOF>\";\n  } else {\n    tokenText = \"<missing \" + recognizer->getVocabulary().getDisplayName(expectedTokenType) + \">\";\n  }\n  Token *current = currentSymbol;\n  Token *lookback = recognizer->getTokenStream()->LT(-1);\n  if (current->getType() == Token::EOF && lookback != nullptr) {\n    current = lookback;\n  }\n\n  _errorSymbols.push_back(recognizer->getTokenFactory()->create(\n    { current->getTokenSource(), current->getTokenSource()->getInputStream() },\n    expectedTokenType, tokenText, Token::DEFAULT_CHANNEL, INVALID_INDEX, INVALID_INDEX,\n    current->getLine(), current->getCharPositionInLine()));\n\n  return _errorSymbols.back().get();\n}\n\nmisc::IntervalSet DefaultErrorStrategy::getExpectedTokens(Parser *recognizer) {\n  return recognizer->getExpectedTokens();\n}\n\nstd::string DefaultErrorStrategy::getTokenErrorDisplay(Token *t) {\n  if (t == nullptr) {\n    return \"<no Token>\";\n  }\n  std::string s = getSymbolText(t);\n  if (s == \"\") {\n    if (getSymbolType(t) == Token::EOF) {\n      s = \"<EOF>\";\n    } else {\n      s = \"<\" + std::to_string(getSymbolType(t)) + \">\";\n    }\n  }\n  return escapeWSAndQuote(s);\n}\n\nstd::string DefaultErrorStrategy::getSymbolText(Token *symbol) {\n  return symbol->getText();\n}\n\nsize_t DefaultErrorStrategy::getSymbolType(Token *symbol) {\n  return symbol->getType();\n}\n\nstd::string DefaultErrorStrategy::escapeWSAndQuote(const std::string &s) const {\n  std::string result;\n  result.reserve(s.size() + 2);\n  result.push_back('\\'');\n  antlrcpp::escapeWhitespace(result, s);\n  result.push_back('\\'');\n  result.shrink_to_fit();\n  return result;\n}\n\nmisc::IntervalSet DefaultErrorStrategy::getErrorRecoverySet(Parser *recognizer) {\n  const atn::ATN &atn = recognizer->getInterpreter<atn::ATNSimulator>()->atn;\n  RuleContext *ctx = recognizer->getContext();\n  misc::IntervalSet recoverSet;\n  while (ctx->invokingState != ATNState::INVALID_STATE_NUMBER) {\n    // compute what follows who invoked us\n    atn::ATNState *invokingState = atn.states[ctx->invokingState];\n    const atn::RuleTransition *rt = downCast<const atn::RuleTransition*>(invokingState->transitions[0].get());\n    misc::IntervalSet follow = atn.nextTokens(rt->followState);\n    recoverSet.addAll(follow);\n\n    if (ctx->parent == nullptr)\n      break;\n    ctx = static_cast<RuleContext *>(ctx->parent);\n  }\n  recoverSet.remove(Token::EPSILON);\n\n  return recoverSet;\n}\n\nvoid DefaultErrorStrategy::consumeUntil(Parser *recognizer, const misc::IntervalSet &set) {\n  size_t ttype = recognizer->getInputStream()->LA(1);\n  while (ttype != Token::EOF && !set.contains(ttype)) {\n    recognizer->consume();\n    ttype = recognizer->getInputStream()->LA(1);\n  }\n}\n\nvoid DefaultErrorStrategy::InitializeInstanceFields() {\n  errorRecoveryMode = false;\n  lastErrorIndex = -1;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/DefaultErrorStrategy.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"ANTLRErrorStrategy.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"misc/IntervalSet.h\"\n\nnamespace antlr4 {\n\n  /**\n   * This is the default implementation of {@link ANTLRErrorStrategy} used for\n   * error reporting and recovery in ANTLR parsers.\n   */\n  class ANTLR4CPP_PUBLIC DefaultErrorStrategy : public ANTLRErrorStrategy {\n  public:\n    DefaultErrorStrategy();\n    DefaultErrorStrategy(DefaultErrorStrategy const& other) = delete;\n    ~DefaultErrorStrategy() override;\n\n    DefaultErrorStrategy& operator = (DefaultErrorStrategy const& other) = delete;\n\n  protected:\n    /**\n     * Indicates whether the error strategy is currently \"recovering from an\n     * error\". This is used to suppress reporting multiple error messages while\n     * attempting to recover from a detected syntax error.\n     *\n     * @see #inErrorRecoveryMode\n     */\n    bool errorRecoveryMode;\n\n    /** The index into the input stream where the last error occurred.\n     * \tThis is used to prevent infinite loops where an error is found\n     *  but no token is consumed during recovery...another error is found,\n     *  ad nauseum.  This is a failsafe mechanism to guarantee that at least\n     *  one token/tree node is consumed for two errors.\n     */\n    int lastErrorIndex;\n\n    misc::IntervalSet lastErrorStates;\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// The default implementation simply calls <seealso cref=\"#endErrorCondition\"/> to\n    /// ensure that the handler is not in error recovery mode.\n    /// </summary>\n  public:\n    void reset(Parser *recognizer) override;\n\n    /// <summary>\n    /// This method is called to enter error recovery mode when a recognition\n    /// exception is reported.\n    /// </summary>\n    /// <param name=\"recognizer\"> the parser instance </param>\n  protected:\n    virtual void beginErrorCondition(Parser *recognizer);\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// </summary>\n  public:\n    bool inErrorRecoveryMode(Parser *recognizer) override;\n\n    /// <summary>\n    /// This method is called to leave error recovery mode after recovering from\n    /// a recognition exception.\n    /// </summary>\n    /// <param name=\"recognizer\"> </param>\n  protected:\n    virtual void endErrorCondition(Parser *recognizer);\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// The default implementation simply calls <seealso cref=\"#endErrorCondition\"/>.\n    /// </summary>\n  public:\n    void reportMatch(Parser *recognizer) override;\n\n    /// {@inheritDoc}\n    /// <p/>\n    /// The default implementation returns immediately if the handler is already\n    /// in error recovery mode. Otherwise, it calls <seealso cref=\"#beginErrorCondition\"/>\n    /// and dispatches the reporting task based on the runtime type of {@code e}\n    /// according to the following table.\n    ///\n    /// <ul>\n    /// <li><seealso cref=\"NoViableAltException\"/>: Dispatches the call to\n    /// <seealso cref=\"#reportNoViableAlternative\"/></li>\n    /// <li><seealso cref=\"InputMismatchException\"/>: Dispatches the call to\n    /// <seealso cref=\"#reportInputMismatch\"/></li>\n    /// <li><seealso cref=\"FailedPredicateException\"/>: Dispatches the call to\n    /// <seealso cref=\"#reportFailedPredicate\"/></li>\n    /// <li>All other types: calls <seealso cref=\"Parser#notifyErrorListeners\"/> to report\n    /// the exception</li>\n    /// </ul>\n    void reportError(Parser *recognizer, const RecognitionException &e) override;\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// The default implementation resynchronizes the parser by consuming tokens\n    /// until we find one in the resynchronization set--loosely the set of tokens\n    /// that can follow the current rule.\n    /// </summary>\n    void recover(Parser *recognizer, std::exception_ptr e) override;\n\n    /**\n     * The default implementation of {@link ANTLRErrorStrategy#sync} makes sure\n     * that the current lookahead symbol is consistent with what were expecting\n     * at this point in the ATN. You can call this anytime but ANTLR only\n     * generates code to check before subrules/loops and each iteration.\n     *\n     * <p>Implements Jim Idle's magic sync mechanism in closures and optional\n     * subrules. E.g.,</p>\n     *\n     * <pre>\n     * a : sync ( stuff sync )* ;\n     * sync : {consume to what can follow sync} ;\n     * </pre>\n     *\n     * At the start of a sub rule upon error, {@link #sync} performs single\n     * token deletion, if possible. If it can't do that, it bails on the current\n     * rule and uses the default error recovery, which consumes until the\n     * resynchronization set of the current rule.\n     *\n     * <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block\n     * with an empty alternative), then the expected set includes what follows\n     * the subrule.</p>\n     *\n     * <p>During loop iteration, it consumes until it sees a token that can start a\n     * sub rule or what follows loop. Yes, that is pretty aggressive. We opt to\n     * stay in the loop as long as possible.</p>\n     *\n     * <p><strong>ORIGINS</strong></p>\n     *\n     * <p>Previous versions of ANTLR did a poor job of their recovery within loops.\n     * A single mismatch token or missing token would force the parser to bail\n     * out of the entire rules surrounding the loop. So, for rule</p>\n     *\n     * <pre>\n     * classDef : 'class' ID '{' member* '}'\n     * </pre>\n     *\n     * input with an extra token between members would force the parser to\n     * consume until it found the next class definition rather than the next\n     * member definition of the current class.\n     *\n     * <p>This functionality cost a little bit of effort because the parser has to\n     * compare token set at the start of the loop and at each iteration. If for\n     * some reason speed is suffering for you, you can turn off this\n     * functionality by simply overriding this method as a blank { }.</p>\n     */\n    void sync(Parser *recognizer) override;\n\n    /// <summary>\n    /// This is called by <seealso cref=\"#reportError\"/> when the exception is a\n    /// <seealso cref=\"NoViableAltException\"/>.\n    /// </summary>\n    /// <seealso cref= #reportError\n    /// </seealso>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <param name=\"e\"> the recognition exception </param>\n  protected:\n    virtual void reportNoViableAlternative(Parser *recognizer, const NoViableAltException &e);\n\n    /// <summary>\n    /// This is called by <seealso cref=\"#reportError\"/> when the exception is an\n    /// <seealso cref=\"InputMismatchException\"/>.\n    /// </summary>\n    /// <seealso cref= #reportError\n    /// </seealso>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <param name=\"e\"> the recognition exception </param>\n    virtual void reportInputMismatch(Parser *recognizer, const InputMismatchException &e);\n\n    /// <summary>\n    /// This is called by <seealso cref=\"#reportError\"/> when the exception is a\n    /// <seealso cref=\"FailedPredicateException\"/>.\n    /// </summary>\n    /// <seealso cref= #reportError\n    /// </seealso>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <param name=\"e\"> the recognition exception </param>\n    virtual void reportFailedPredicate(Parser *recognizer, const FailedPredicateException &e);\n\n    /**\n     * This method is called to report a syntax error which requires the removal\n     * of a token from the input stream. At the time this method is called, the\n     * erroneous symbol is current {@code LT(1)} symbol and has not yet been\n     * removed from the input stream. When this method returns,\n     * {@code recognizer} is in error recovery mode.\n     *\n     * <p>This method is called when {@link #singleTokenDeletion} identifies\n     * single-token deletion as a viable recovery strategy for a mismatched\n     * input error.</p>\n     *\n     * <p>The default implementation simply returns if the handler is already in\n     * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n     * enter error recovery mode, followed by calling\n     * {@link Parser#notifyErrorListeners}.</p>\n     *\n     * @param recognizer the parser instance\n     */\n    virtual void reportUnwantedToken(Parser *recognizer);\n\n    /**\n     * This method is called to report a syntax error which requires the\n     * insertion of a missing token into the input stream. At the time this\n     * method is called, the missing token has not yet been inserted. When this\n     * method returns, {@code recognizer} is in error recovery mode.\n     *\n     * <p>This method is called when {@link #singleTokenInsertion} identifies\n     * single-token insertion as a viable recovery strategy for a mismatched\n     * input error.</p>\n     *\n     * <p>The default implementation simply returns if the handler is already in\n     * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n     * enter error recovery mode, followed by calling\n     * {@link Parser#notifyErrorListeners}.</p>\n     *\n     * @param recognizer the parser instance\n     */\n    virtual void reportMissingToken(Parser *recognizer);\n\n  public:\n    /**\n     * {@inheritDoc}\n     *\n     * <p>The default implementation attempts to recover from the mismatched input\n     * by using single token insertion and deletion as described below. If the\n     * recovery attempt fails, this method throws an\n     * {@link InputMismatchException}.</p>\n     *\n     * <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>\n     *\n     * <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the\n     * right token, however, then assume {@code LA(1)} is some extra spurious\n     * token and delete it. Then consume and return the next token (which was\n     * the {@code LA(2)} token) as the successful result of the match operation.</p>\n     *\n     * <p>This recovery strategy is implemented by {@link #singleTokenDeletion}.</p>\n     *\n     * <p><strong>MISSING TOKEN</strong> (single token insertion)</p>\n     *\n     * <p>If current token (at {@code LA(1)}) is consistent with what could come\n     * after the expected {@code LA(1)} token, then assume the token is missing\n     * and use the parser's {@link TokenFactory} to create it on the fly. The\n     * \"insertion\" is performed by returning the created token as the successful\n     * result of the match operation.</p>\n     *\n     * <p>This recovery strategy is implemented by {@link #singleTokenInsertion}.</p>\n     *\n     * <p><strong>EXAMPLE</strong></p>\n     *\n     * <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When\n     * the parser returns from the nested call to {@code expr}, it will have\n     * call chain:</p>\n     *\n     * <pre>\n     * stat &rarr; expr &rarr; atom\n     * </pre>\n     *\n     * and it will be trying to match the {@code ')'} at this point in the\n     * derivation:\n     *\n     * <pre>\n     * =&gt; ID '=' '(' INT ')' ('+' atom)* ';'\n     *                    ^\n     * </pre>\n     *\n     * The attempt to match {@code ')'} will fail when it sees {@code ';'} and\n     * call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'}\n     * is in the set of tokens that can follow the {@code ')'} token reference\n     * in rule {@code atom}. It can assume that you forgot the {@code ')'}.\n     */\n    Token* recoverInline(Parser *recognizer) override;\n\n    /// <summary>\n    /// This method implements the single-token insertion inline error recovery\n    /// strategy. It is called by <seealso cref=\"#recoverInline\"/> if the single-token\n    /// deletion strategy fails to recover from the mismatched input. If this\n    /// method returns {@code true}, {@code recognizer} will be in error recovery\n    /// mode.\n    /// <p/>\n    /// This method determines whether or not single-token insertion is viable by\n    /// checking if the {@code LA(1)} input symbol could be successfully matched\n    /// if it were instead the {@code LA(2)} symbol. If this method returns\n    /// {@code true}, the caller is responsible for creating and inserting a\n    /// token with the correct type to produce this behavior.\n    /// </summary>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <returns> {@code true} if single-token insertion is a viable recovery\n    /// strategy for the current mismatched input, otherwise {@code false} </returns>\n  protected:\n    virtual bool singleTokenInsertion(Parser *recognizer);\n\n    /// <summary>\n    /// This method implements the single-token deletion inline error recovery\n    /// strategy. It is called by <seealso cref=\"#recoverInline\"/> to attempt to recover\n    /// from mismatched input. If this method returns null, the parser and error\n    /// handler state will not have changed. If this method returns non-null,\n    /// {@code recognizer} will <em>not</em> be in error recovery mode since the\n    /// returned token was a successful match.\n    /// <p/>\n    /// If the single-token deletion is successful, this method calls\n    /// <seealso cref=\"#reportUnwantedToken\"/> to report the error, followed by\n    /// <seealso cref=\"Parser#consume\"/> to actually \"delete\" the extraneous token. Then,\n    /// before returning <seealso cref=\"#reportMatch\"/> is called to signal a successful\n    /// match.\n    /// </summary>\n    /// <param name=\"recognizer\"> the parser instance </param>\n    /// <returns> the successfully matched <seealso cref=\"Token\"/> instance if single-token\n    /// deletion successfully recovers from the mismatched input, otherwise\n    /// {@code null} </returns>\n    virtual Token* singleTokenDeletion(Parser *recognizer);\n\n    /// <summary>\n    /// Conjure up a missing token during error recovery.\n    ///\n    ///  The recognizer attempts to recover from single missing\n    ///  symbols. But, actions might refer to that missing symbol.\n    ///  For example, x=ID {f($x);}. The action clearly assumes\n    ///  that there has been an identifier matched previously and that\n    ///  $x points at that token. If that token is missing, but\n    ///  the next token in the stream is what we want we assume that\n    ///  this token is missing and we keep going. Because we\n    ///  have to return some token to replace the missing token,\n    ///  we have to conjure one up. This method gives the user control\n    ///  over the tokens returned for missing tokens. Mostly,\n    ///  you will want to create something special for identifier\n    ///  tokens. For literals such as '{' and ',', the default\n    ///  action in the parser or tree parser works. It simply creates\n    ///  a CommonToken of the appropriate type. The text will be the token.\n    ///  If you change what tokens must be created by the lexer,\n    ///  override this method to create the appropriate tokens.\n    /// </summary>\n    virtual Token* getMissingSymbol(Parser *recognizer);\n\n    virtual misc::IntervalSet getExpectedTokens(Parser *recognizer);\n\n    /// <summary>\n    /// How should a token be displayed in an error message? The default\n    ///  is to display just the text, but during development you might\n    ///  want to have a lot of information spit out.  Override in that case\n    ///  to use t.toString() (which, for CommonToken, dumps everything about\n    ///  the token). This is better than forcing you to override a method in\n    ///  your token objects because you don't have to go modify your lexer\n    ///  so that it creates a new class.\n    /// </summary>\n    virtual std::string getTokenErrorDisplay(Token *t);\n\n    virtual std::string getSymbolText(Token *symbol);\n\n    virtual size_t getSymbolType(Token *symbol);\n\n    virtual std::string escapeWSAndQuote(const std::string &s) const;\n\n    /*  Compute the error recovery set for the current rule.  During\n     *  rule invocation, the parser pushes the set of tokens that can\n     *  follow that rule reference on the stack; this amounts to\n     *  computing FIRST of what follows the rule reference in the\n     *  enclosing rule. See LinearApproximator.FIRST().\n     *  This local follow set only includes tokens\n     *  from within the rule; i.e., the FIRST computation done by\n     *  ANTLR stops at the end of a rule.\n     *\n     *  EXAMPLE\n     *\n     *  When you find a \"no viable alt exception\", the input is not\n     *  consistent with any of the alternatives for rule r.  The best\n     *  thing to do is to consume tokens until you see something that\n     *  can legally follow a call to r *or* any rule that called r.\n     *  You don't want the exact set of viable next tokens because the\n     *  input might just be missing a token--you might consume the\n     *  rest of the input looking for one of the missing tokens.\n     *\n     *  Consider grammar:\n     *\n     *  a : '[' b ']'\n     *    | '(' b ')'\n     *    ;\n     *  b : c '^' INT ;\n     *  c : ID\n     *    | INT\n     *    ;\n     *\n     *  At each rule invocation, the set of tokens that could follow\n     *  that rule is pushed on a stack.  Here are the various\n     *  context-sensitive follow sets:\n     *\n     *  FOLLOW(b1_in_a) = FIRST(']') = ']'\n     *  FOLLOW(b2_in_a) = FIRST(')') = ')'\n     *  FOLLOW(c_in_b) = FIRST('^') = '^'\n     *\n     *  Upon erroneous input \"[]\", the call chain is\n     *\n     *  a -> b -> c\n     *\n     *  and, hence, the follow context stack is:\n     *\n     *  depth     follow set       start of rule execution\n     *    0         <EOF>                    a (from main())\n     *    1          ']'                     b\n     *    2          '^'                     c\n     *\n     *  Notice that ')' is not included, because b would have to have\n     *  been called from a different context in rule a for ')' to be\n     *  included.\n     *\n     *  For error recovery, we cannot consider FOLLOW(c)\n     *  (context-sensitive or otherwise).  We need the combined set of\n     *  all context-sensitive FOLLOW sets--the set of all tokens that\n     *  could follow any reference in the call chain.  We need to\n     *  resync to one of those tokens.  Note that FOLLOW(c)='^' and if\n     *  we resync'd to that token, we'd consume until EOF.  We need to\n     *  sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.\n     *  In this case, for input \"[]\", LA(1) is ']' and in the set, so we would\n     *  not consume anything. After printing an error, rule c would\n     *  return normally.  Rule b would not find the required '^' though.\n     *  At this point, it gets a mismatched token error and throws an\n     *  exception (since LA(1) is not in the viable following token\n     *  set).  The rule exception handler tries to recover, but finds\n     *  the same recovery set and doesn't consume anything.  Rule b\n     *  exits normally returning to rule a.  Now it finds the ']' (and\n     *  with the successful match exits errorRecovery mode).\n     *\n     *  So, you can see that the parser walks up the call chain looking\n     *  for the token that was a member of the recovery set.\n     *\n     *  Errors are not generated in errorRecovery mode.\n     *\n     *  ANTLR's error recovery mechanism is based upon original ideas:\n     *\n     *  \"Algorithms + Data Structures = Programs\" by Niklaus Wirth\n     *\n     *  and\n     *\n     *  \"A note on error recovery in recursive descent parsers\":\n     *  http://portal.acm.org/citation.cfm?id=947902.947905\n     *\n     *  Later, Josef Grosch had some good ideas:\n     *\n     *  \"Efficient and Comfortable Error Recovery in Recursive Descent\n     *  Parsers\":\n     *  ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip\n     *\n     *  Like Grosch I implement context-sensitive FOLLOW sets that are combined\n     *  at run-time upon error to avoid overhead during parsing.\n     */\n    virtual misc::IntervalSet getErrorRecoverySet(Parser *recognizer);\n\n    /// <summary>\n    /// Consume tokens until one matches the given token set. </summary>\n    virtual void consumeUntil(Parser *recognizer, const misc::IntervalSet &set);\n\n  private:\n    std::vector<std::unique_ptr<Token>> _errorSymbols; // Temporarily created token.\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/DiagnosticErrorListener.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"atn/PredictionContext.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATNConfig.h\"\n#include \"atn/ATNConfigSet.h\"\n#include \"Parser.h\"\n#include \"misc/Interval.h\"\n#include \"dfa/DFA.h\"\n\n#include \"DiagnosticErrorListener.h\"\n\nusing namespace antlr4;\n\nDiagnosticErrorListener::DiagnosticErrorListener() : DiagnosticErrorListener(true) {\n}\n\nDiagnosticErrorListener::DiagnosticErrorListener(bool exactOnly_) : exactOnly(exactOnly_) {\n}\n\nvoid DiagnosticErrorListener::reportAmbiguity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n   bool exact, const antlrcpp::BitSet &ambigAlts, atn::ATNConfigSet *configs) {\n  if (exactOnly && !exact) {\n    return;\n  }\n\n  std::string decision = getDecisionDescription(recognizer, dfa);\n  antlrcpp::BitSet conflictingAlts = getConflictingAlts(ambigAlts, configs);\n  std::string text = recognizer->getTokenStream()->getText(misc::Interval(startIndex, stopIndex));\n  std::string message = \"reportAmbiguity d=\" + decision + \": ambigAlts=\" + conflictingAlts.toString() +\n    \", input='\" + text + \"'\";\n\n  recognizer->notifyErrorListeners(message);\n}\n\nvoid DiagnosticErrorListener::reportAttemptingFullContext(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex,\n  size_t stopIndex, const antlrcpp::BitSet &/*conflictingAlts*/, atn::ATNConfigSet * /*configs*/) {\n  std::string decision = getDecisionDescription(recognizer, dfa);\n  std::string text = recognizer->getTokenStream()->getText(misc::Interval(startIndex, stopIndex));\n  std::string message = \"reportAttemptingFullContext d=\" + decision + \", input='\" + text + \"'\";\n  recognizer->notifyErrorListeners(message);\n}\n\nvoid DiagnosticErrorListener::reportContextSensitivity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex,\n  size_t stopIndex, size_t /*prediction*/, atn::ATNConfigSet * /*configs*/) {\n  std::string decision = getDecisionDescription(recognizer, dfa);\n  std::string text = recognizer->getTokenStream()->getText(misc::Interval(startIndex, stopIndex));\n  std::string message = \"reportContextSensitivity d=\" + decision + \", input='\" + text + \"'\";\n  recognizer->notifyErrorListeners(message);\n}\n\nstd::string DiagnosticErrorListener::getDecisionDescription(Parser *recognizer, const dfa::DFA &dfa) {\n  size_t decision = dfa.decision;\n  size_t ruleIndex = (reinterpret_cast<atn::ATNState*>(dfa.atnStartState))->ruleIndex;\n\n  const std::vector<std::string>& ruleNames = recognizer->getRuleNames();\n  if (ruleIndex == INVALID_INDEX || ruleIndex >= ruleNames.size()) {\n    return std::to_string(decision);\n  }\n\n  std::string ruleName = ruleNames[ruleIndex];\n  if (ruleName == \"\" || ruleName.empty())  {\n    return std::to_string(decision);\n  }\n\n  return std::to_string(decision) + \" (\" + ruleName + \")\";\n}\n\nantlrcpp::BitSet DiagnosticErrorListener::getConflictingAlts(const antlrcpp::BitSet &reportedAlts,\n                                                             atn::ATNConfigSet *configs) {\n  if (reportedAlts.count() > 0) { // Not exactly like the original Java code, but this listener is only used\n                                  // in the TestRig (where it never provides a good alt set), so it's probably ok so.\n    return reportedAlts;\n  }\n\n  antlrcpp::BitSet result;\n  for (auto &config : configs->configs) {\n    result.set(config->alt);\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/DiagnosticErrorListener.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"BaseErrorListener.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// This implementation of <seealso cref=\"ANTLRErrorListener\"/> can be used to identify\n  /// certain potential correctness and performance problems in grammars. \"Reports\"\n  /// are made by calling <seealso cref=\"Parser#notifyErrorListeners\"/> with the appropriate\n  /// message.\n  ///\n  /// <ul>\n  /// <li><b>Ambiguities</b>: These are cases where more than one path through the\n  /// grammar can match the input.</li>\n  /// <li><b>Weak context sensitivity</b>: These are cases where full-context\n  /// prediction resolved an SLL conflict to a unique alternative which equaled the\n  /// minimum alternative of the SLL conflict.</li>\n  /// <li><b>Strong (forced) context sensitivity</b>: These are cases where the\n  /// full-context prediction resolved an SLL conflict to a unique alternative,\n  /// <em>and</em> the minimum alternative of the SLL conflict was found to not be\n  /// a truly viable alternative. Two-stage parsing cannot be used for inputs where\n  /// this situation occurs.</li>\n  /// </ul>\n  ///\n  /// @author Sam Harwell\n  /// </summary>\n  class ANTLR4CPP_PUBLIC DiagnosticErrorListener : public BaseErrorListener {\n    /// <summary>\n    /// When {@code true}, only exactly known ambiguities are reported.\n    /// </summary>\n  protected:\n    const bool exactOnly;\n\n    /// <summary>\n    /// Initializes a new instance of <seealso cref=\"DiagnosticErrorListener\"/> which only\n    /// reports exact ambiguities.\n    /// </summary>\n  public:\n    DiagnosticErrorListener();\n\n    /// <summary>\n    /// Initializes a new instance of <seealso cref=\"DiagnosticErrorListener\"/>, specifying\n    /// whether all ambiguities or only exact ambiguities are reported.\n    /// </summary>\n    /// <param name=\"exactOnly\"> {@code true} to report only exact ambiguities, otherwise\n    /// {@code false} to report all ambiguities. </param>\n    DiagnosticErrorListener(bool exactOnly);\n\n    void reportAmbiguity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex, bool exact,\n      const antlrcpp::BitSet &ambigAlts, atn::ATNConfigSet *configs) override;\n\n    void reportAttemptingFullContext(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n      const antlrcpp::BitSet &conflictingAlts, atn::ATNConfigSet *configs) override;\n\n    void reportContextSensitivity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n      size_t prediction, atn::ATNConfigSet *configs) override;\n\n  protected:\n    virtual std::string getDecisionDescription(Parser *recognizer, const dfa::DFA &dfa);\n\n    /// <summary>\n    /// Computes the set of conflicting or ambiguous alternatives from a\n    /// configuration set, if that information was not already provided by the\n    /// parser.\n    /// </summary>\n    /// <param name=\"reportedAlts\"> The set of conflicting or ambiguous alternatives, as\n    /// reported by the parser. </param>\n    /// <param name=\"configs\"> The conflicting or ambiguous configuration set. </param>\n    /// <returns> Returns {@code reportedAlts} if it is not {@code null}, otherwise\n    /// returns the set of alternatives represented in {@code configs}. </returns>\n    virtual antlrcpp::BitSet getConflictingAlts(const antlrcpp::BitSet &reportedAlts, atn::ATNConfigSet *configs);\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Exceptions.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <string>\n#include \"Exceptions.h\"\n\nusing namespace antlr4;\n\nRuntimeException::RuntimeException(const std::string &msg) : std::exception(), _message(msg) {\n}\n\nconst char* RuntimeException::what() const noexcept {\n  return _message.c_str();\n}\n\n//------------------ IOException ---------------------------------------------------------------------------------------\n\nIOException::IOException(const std::string &msg) : std::exception(), _message(msg) {\n}\n\nconst char* IOException::what() const noexcept {\n  return _message.c_str();\n}\n\n//------------------ IllegalStateException -----------------------------------------------------------------------------\n\nIllegalStateException::~IllegalStateException() {\n}\n\n//------------------ IllegalArgumentException --------------------------------------------------------------------------\n\nIllegalArgumentException::~IllegalArgumentException() {\n}\n\n//------------------ NullPointerException ------------------------------------------------------------------------------\n\nNullPointerException::~NullPointerException() {\n}\n\n//------------------ IndexOutOfBoundsException -------------------------------------------------------------------------\n\nIndexOutOfBoundsException::~IndexOutOfBoundsException() {\n}\n\n//------------------ UnsupportedOperationException ---------------------------------------------------------------------\n\nUnsupportedOperationException::~UnsupportedOperationException() {\n}\n\n//------------------ EmptyStackException -------------------------------------------------------------------------------\n\nEmptyStackException::~EmptyStackException() {\n}\n\n//------------------ CancellationException -----------------------------------------------------------------------------\n\nCancellationException::~CancellationException() {\n}\n\n//------------------ ParseCancellationException ------------------------------------------------------------------------\n\nParseCancellationException::~ParseCancellationException() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Exceptions.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <string>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\n\n  // An exception hierarchy modelled loosely after java.lang.* exceptions.\n  class ANTLR4CPP_PUBLIC RuntimeException : public std::exception {\n  private:\n    std::string _message;\n  public:\n    RuntimeException(const std::string &msg = \"\");\n\n    const char* what() const noexcept override;\n  };\n\n  class ANTLR4CPP_PUBLIC IllegalStateException : public RuntimeException {\n  public:\n    IllegalStateException(const std::string &msg = \"\") : RuntimeException(msg) {}\n    IllegalStateException(IllegalStateException const&) = default;\n    ~IllegalStateException() override;\n    IllegalStateException& operator=(IllegalStateException const&) = default;\n  };\n\n  class ANTLR4CPP_PUBLIC IllegalArgumentException : public RuntimeException {\n  public:\n    IllegalArgumentException(IllegalArgumentException const&) = default;\n    IllegalArgumentException(const std::string &msg = \"\") : RuntimeException(msg) {}\n    ~IllegalArgumentException() override;\n    IllegalArgumentException& operator=(IllegalArgumentException const&) = default;\n  };\n\n  class ANTLR4CPP_PUBLIC NullPointerException : public RuntimeException {\n  public:\n    NullPointerException(const std::string &msg = \"\") : RuntimeException(msg) {}\n    NullPointerException(NullPointerException const&) = default;\n    ~NullPointerException() override;\n    NullPointerException& operator=(NullPointerException const&) = default;\n  };\n\n  class ANTLR4CPP_PUBLIC IndexOutOfBoundsException : public RuntimeException {\n  public:\n    IndexOutOfBoundsException(const std::string &msg = \"\") : RuntimeException(msg) {}\n    IndexOutOfBoundsException(IndexOutOfBoundsException const&) = default;\n    ~IndexOutOfBoundsException() override;\n    IndexOutOfBoundsException& operator=(IndexOutOfBoundsException const&) = default;\n  };\n\n  class ANTLR4CPP_PUBLIC UnsupportedOperationException : public RuntimeException {\n  public:\n    UnsupportedOperationException(const std::string &msg = \"\") : RuntimeException(msg) {}\n    UnsupportedOperationException(UnsupportedOperationException const&) = default;\n    ~UnsupportedOperationException() override;\n    UnsupportedOperationException& operator=(UnsupportedOperationException const&) = default;\n\n  };\n\n  class ANTLR4CPP_PUBLIC EmptyStackException : public RuntimeException {\n  public:\n    EmptyStackException(const std::string &msg = \"\") : RuntimeException(msg) {}\n    EmptyStackException(EmptyStackException const&) = default;\n    ~EmptyStackException() override;\n    EmptyStackException& operator=(EmptyStackException const&) = default;\n  };\n\n  // IOException is not a runtime exception (in the java hierarchy).\n  // Hence we have to duplicate the RuntimeException implementation.\n  class ANTLR4CPP_PUBLIC IOException : public std::exception {\n  private:\n    std::string _message;\n\n  public:\n    IOException(const std::string &msg = \"\");\n\n    const char* what() const noexcept override;\n  };\n\n  class ANTLR4CPP_PUBLIC CancellationException : public IllegalStateException {\n  public:\n    CancellationException(const std::string &msg = \"\") : IllegalStateException(msg) {}\n    CancellationException(CancellationException const&) = default;\n    ~CancellationException() override;\n    CancellationException& operator=(CancellationException const&) = default;\n  };\n\n  class ANTLR4CPP_PUBLIC ParseCancellationException : public CancellationException {\n  public:\n    ParseCancellationException(const std::string &msg = \"\") : CancellationException(msg) {}\n    ParseCancellationException(ParseCancellationException const&) = default;\n    ~ParseCancellationException() override;\n    ParseCancellationException& operator=(ParseCancellationException const&) = default;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/FailedPredicateException.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/ParserATNSimulator.h\"\n#include \"atn/TransitionType.h\"\n#include \"Parser.h\"\n#include \"atn/PredicateTransition.h\"\n#include \"atn/ATN.h\"\n#include \"atn/ATNState.h\"\n#include \"support/Casts.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"FailedPredicateException.h\"\n\nusing namespace antlr4;\nusing namespace antlrcpp;\n\nFailedPredicateException::FailedPredicateException(Parser *recognizer) : FailedPredicateException(recognizer, \"\", \"\") {\n}\n\nFailedPredicateException::FailedPredicateException(Parser *recognizer, const std::string &predicate): FailedPredicateException(recognizer, predicate, \"\") {\n}\n\nFailedPredicateException::FailedPredicateException(Parser *recognizer, const std::string &predicate, const std::string &message)\n  : RecognitionException(!message.empty() ? message : \"failed predicate: \" + predicate + \"?\", recognizer,\n                         recognizer->getInputStream(), recognizer->getContext(), recognizer->getCurrentToken()) {\n\n  atn::ATNState *s = recognizer->getInterpreter<atn::ATNSimulator>()->atn.states[recognizer->getState()];\n  const atn::Transition *transition = s->transitions[0].get();\n  if (transition->getTransitionType() == atn::TransitionType::PREDICATE) {\n    _ruleIndex = downCast<const atn::PredicateTransition&>(*transition).getRuleIndex();\n    _predicateIndex = downCast<const atn::PredicateTransition&>(*transition).getPredIndex();\n  } else {\n    _ruleIndex = 0;\n    _predicateIndex = 0;\n  }\n\n  _predicate = predicate;\n}\n\nsize_t FailedPredicateException::getRuleIndex() {\n  return _ruleIndex;\n}\n\nsize_t FailedPredicateException::getPredIndex() {\n  return _predicateIndex;\n}\n\nstd::string FailedPredicateException::getPredicate() {\n  return _predicate;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/FailedPredicateException.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"RecognitionException.h\"\n\nnamespace antlr4 {\n\n  /// A semantic predicate failed during validation.  Validation of predicates\n  /// occurs when normally parsing the alternative just like matching a token.\n  /// Disambiguating predicate evaluation occurs when we test a predicate during\n  /// prediction.\n  class ANTLR4CPP_PUBLIC FailedPredicateException : public RecognitionException {\n  public:\n    explicit FailedPredicateException(Parser *recognizer);\n    FailedPredicateException(Parser *recognizer, const std::string &predicate);\n    FailedPredicateException(Parser *recognizer, const std::string &predicate, const std::string &message);\n\n    virtual size_t getRuleIndex();\n    virtual size_t getPredIndex();\n    virtual std::string getPredicate();\n\n  private:\n    size_t _ruleIndex;\n    size_t _predicateIndex;\n    std::string _predicate;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/FlatHashMap.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\n#if ANTLR4CPP_USING_ABSEIL\n#include \"absl/container/flat_hash_map.h\"\n#else\n#include <utility>\n#include <unordered_map>\n#endif\n\n// By default ANTLRv4 uses containers provided by the C++ standard library. In most deployments this\n// is fine, however in some using custom containers may be preferred. This header allows that by\n// optionally supporting some alternative implementations and allowing for more easier patching of\n// other alternatives.\n\nnamespace antlr4 {\n\n#if ANTLR4CPP_USING_ABSEIL\n  template <typename Key, typename Value,\n            typename Hash = typename absl::flat_hash_map<Key, Value>::hasher,\n            typename Equal = typename absl::flat_hash_map<Key, Value>::key_equal,\n            typename Allocator = typename absl::flat_hash_map<Key, Value>::allocator_type>\n  using FlatHashMap = absl::flat_hash_map<Key, Value, Hash, Equal, Allocator>;\n#else\n  template <typename Key, typename Value,\n            typename Hash = std::hash<Key>,\n            typename Equal = std::equal_to<Key>,\n            typename Allocator = std::allocator<std::pair<const Key, Value>>>\n  using FlatHashMap = std::unordered_map<Key, Value, Hash, Equal, Allocator>;\n#endif\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/FlatHashSet.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\n#if ANTLR4CPP_USING_ABSEIL\n#include \"absl/container/flat_hash_set.h\"\n#else\n#include <unordered_set>\n#endif\n\n// By default ANTLRv4 uses containers provided by the C++ standard library. In most deployments this\n// is fine, however in some using custom containers may be preferred. This header allows that by\n// optionally supporting some alternative implementations and allowing for more easier patching of\n// other alternatives.\n\nnamespace antlr4 {\n\n#if ANTLR4CPP_USING_ABSEIL\n  template <typename Key,\n            typename Hash = typename absl::flat_hash_set<Key>::hasher,\n            typename Equal = typename absl::flat_hash_set<Key>::key_equal,\n            typename Allocator = typename absl::flat_hash_set<Key>::allocator_type>\n  using FlatHashSet = absl::flat_hash_set<Key, Hash, Equal, Allocator>;\n#else\n  template <typename Key,\n            typename Hash = std::hash<Key>,\n            typename Equal = std::equal_to<Key>,\n            typename Allocator = std::allocator<Key>>\n  using FlatHashSet = std::unordered_set<Key, Hash, Equal, Allocator>;\n#endif\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/InputMismatchException.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"Parser.h\"\n\n#include \"InputMismatchException.h\"\n\nusing namespace antlr4;\n\nInputMismatchException::InputMismatchException(Parser *recognizer)\n  : RecognitionException(recognizer, recognizer->getInputStream(), recognizer->getContext(),\n                         recognizer->getCurrentToken()) {\n}\n\nInputMismatchException::~InputMismatchException() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/InputMismatchException.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"RecognitionException.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// This signifies any kind of mismatched input exceptions such as\n  ///  when the current input does not match the expected token.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC InputMismatchException : public RecognitionException {\n  public:\n    InputMismatchException(Parser *recognizer);\n    InputMismatchException(InputMismatchException const&) = default;\n    ~InputMismatchException() override;\n    InputMismatchException& operator=(InputMismatchException const&) = default;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/IntStream.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include \"IntStream.h\"\n\nusing namespace antlr4;\n\nconst std::string IntStream::UNKNOWN_SOURCE_NAME = \"<unknown>\";\n\nIntStream::~IntStream() = default;\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/IntStream.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <limits>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// A simple stream of symbols whose values are represented as integers. This\n  /// interface provides <em>marked ranges</em> with support for a minimum level\n  /// of buffering necessary to implement arbitrary lookahead during prediction.\n  /// For more information on marked ranges, see <seealso cref=\"#mark\"/>.\n  /// <p/>\n  /// <strong>Initializing Methods:</strong> Some methods in this interface have\n  /// unspecified behavior if no call to an initializing method has occurred after\n  /// the stream was constructed. The following is a list of initializing methods:\n  ///\n  /// <ul>\n  ///   <li><seealso cref=\"#LA\"/></li>\n  ///   <li><seealso cref=\"#consume\"/></li>\n  ///   <li><seealso cref=\"#size\"/></li>\n  /// </ul>\n  /// </summary>\n  class ANTLR4CPP_PUBLIC IntStream {\n  public:\n    static constexpr size_t EOF = std::numeric_limits<size_t>::max();\n\n    /// The value returned by <seealso cref=\"#LA LA()\"/> when the end of the stream is\n    /// reached.\n    /// No explicit EOF definition. We got EOF on all platforms.\n    //static const size_t _EOF = std::ios::eofbit;\n\n    /// <summary>\n    /// The value returned by <seealso cref=\"#getSourceName\"/> when the actual name of the\n    /// underlying source is not known.\n    /// </summary>\n    static const std::string UNKNOWN_SOURCE_NAME;\n\n    virtual ~IntStream();\n\n    /// <summary>\n    /// Consumes the current symbol in the stream. This method has the following\n    /// effects:\n    ///\n    /// <ul>\n    ///   <li><strong>Forward movement:</strong> The value of <seealso cref=\"#index index()\"/>\n    ///\t\tbefore calling this method is less than the value of {@code index()}\n    ///\t\tafter calling this method.</li>\n    ///   <li><strong>Ordered lookahead:</strong> The value of {@code LA(1)} before\n    ///\t\tcalling this method becomes the value of {@code LA(-1)} after calling\n    ///\t\tthis method.</li>\n    /// </ul>\n    ///\n    /// Note that calling this method does not guarantee that {@code index()} is\n    /// incremented by exactly 1, as that would preclude the ability to implement\n    /// filtering streams (e.g. <seealso cref=\"CommonTokenStream\"/> which distinguishes\n    /// between \"on-channel\" and \"off-channel\" tokens).\n    /// </summary>\n    /// <exception cref=\"IllegalStateException\"> if an attempt is made to consume the the\n    /// end of the stream (i.e. if {@code LA(1)==}<seealso cref=\"#EOF EOF\"/> before calling\n    /// {@code consume}). </exception>\n    virtual void consume() = 0;\n\n    /// <summary>\n    /// Gets the value of the symbol at offset {@code i} from the current\n    /// position. When {@code i==1}, this method returns the value of the current\n    /// symbol in the stream (which is the next symbol to be consumed). When\n    /// {@code i==-1}, this method returns the value of the previously read\n    /// symbol in the stream. It is not valid to call this method with\n    /// {@code i==0}, but the specific behavior is unspecified because this\n    /// method is frequently called from performance-critical code.\n    /// <p/>\n    /// This method is guaranteed to succeed if any of the following are true:\n    ///\n    /// <ul>\n    ///   <li>{@code i>0}</li>\n    ///   <li>{@code i==-1} and <seealso cref=\"#index index()\"/> returns a value greater\n    ///     than the value of {@code index()} after the stream was constructed\n    ///     and {@code LA(1)} was called in that order. Specifying the current\n    ///     {@code index()} relative to the index after the stream was created\n    ///     allows for filtering implementations that do not return every symbol\n    ///     from the underlying source. Specifying the call to {@code LA(1)}\n    ///     allows for lazily initialized streams.</li>\n    ///   <li>{@code LA(i)} refers to a symbol consumed within a marked region\n    ///     that has not yet been released.</li>\n    /// </ul>\n    ///\n    /// If {@code i} represents a position at or beyond the end of the stream,\n    /// this method returns <seealso cref=\"#EOF\"/>.\n    /// <p/>\n    /// The return value is unspecified if {@code i<0} and fewer than {@code -i}\n    /// calls to <seealso cref=\"#consume consume()\"/> have occurred from the beginning of\n    /// the stream before calling this method.\n    /// </summary>\n    /// <exception cref=\"UnsupportedOperationException\"> if the stream does not support\n    /// retrieving the value of the specified symbol </exception>\n    virtual size_t LA(ssize_t i) = 0;\n\n    /// <summary>\n    /// A mark provides a guarantee that <seealso cref=\"#seek seek()\"/> operations will be\n    /// valid over a \"marked range\" extending from the index where {@code mark()}\n    /// was called to the current <seealso cref=\"#index index()\"/>. This allows the use of\n    /// streaming input sources by specifying the minimum buffering requirements\n    /// to support arbitrary lookahead during prediction.\n    /// <p/>\n    /// The returned mark is an opaque handle (type {@code int}) which is passed\n    /// to <seealso cref=\"#release release()\"/> when the guarantees provided by the marked\n    /// range are no longer necessary. When calls to\n    /// {@code mark()}/{@code release()} are nested, the marks must be released\n    /// in reverse order of which they were obtained. Since marked regions are\n    /// used during performance-critical sections of prediction, the specific\n    /// behavior of invalid usage is unspecified (i.e. a mark is not released, or\n    /// a mark is released twice, or marks are not released in reverse order from\n    /// which they were created).\n    /// <p/>\n    /// The behavior of this method is unspecified if no call to an\n    /// <seealso cref=\"IntStream initializing method\"/> has occurred after this stream was\n    /// constructed.\n    /// <p/>\n    /// This method does not change the current position in the input stream.\n    /// <p/>\n    /// The following example shows the use of <seealso cref=\"#mark mark()\"/>,\n    /// <seealso cref=\"#release release(mark)\"/>, <seealso cref=\"#index index()\"/>, and\n    /// <seealso cref=\"#seek seek(index)\"/> as part of an operation to safely work within a\n    /// marked region, then restore the stream position to its original value and\n    /// release the mark.\n    /// <pre>\n    /// IntStream stream = ...;\n    /// int index = -1;\n    /// int mark = stream.mark();\n    /// try {\n    ///   index = stream.index();\n    ///   // perform work here...\n    /// } finally {\n    ///   if (index != -1) {\n    ///     stream.seek(index);\n    ///   }\n    ///   stream.release(mark);\n    /// }\n    /// </pre>\n    /// </summary>\n    /// <returns> An opaque marker which should be passed to\n    /// <seealso cref=\"#release release()\"/> when the marked range is no longer required. </returns>\n    virtual ssize_t mark() = 0;\n\n    /// <summary>\n    /// This method releases a marked range created by a call to\n    /// <seealso cref=\"#mark mark()\"/>. Calls to {@code release()} must appear in the\n    /// reverse order of the corresponding calls to {@code mark()}. If a mark is\n    /// released twice, or if marks are not released in reverse order of the\n    /// corresponding calls to {@code mark()}, the behavior is unspecified.\n    /// <p/>\n    /// For more information and an example, see <seealso cref=\"#mark\"/>.\n    /// </summary>\n    /// <param name=\"marker\"> A marker returned by a call to {@code mark()}. </param>\n    /// <seealso cref= #mark </seealso>\n    virtual void release(ssize_t marker) = 0;\n\n    /// <summary>\n    /// Return the index into the stream of the input symbol referred to by\n    /// {@code LA(1)}.\n    /// <p/>\n    /// The behavior of this method is unspecified if no call to an\n    /// <seealso cref=\"IntStream initializing method\"/> has occurred after this stream was\n    /// constructed.\n    /// </summary>\n    virtual size_t index() = 0;\n\n    /// <summary>\n    /// Set the input cursor to the position indicated by {@code index}. If the\n    /// specified index lies past the end of the stream, the operation behaves as\n    /// though {@code index} was the index of the EOF symbol. After this method\n    /// returns without throwing an exception, the at least one of the following\n    /// will be true.\n    ///\n    /// <ul>\n    ///   <li><seealso cref=\"#index index()\"/> will return the index of the first symbol\n    ///     appearing at or after the specified {@code index}. Specifically,\n    ///     implementations which filter their sources should automatically\n    ///     adjust {@code index} forward the minimum amount required for the\n    ///     operation to target a non-ignored symbol.</li>\n    ///   <li>{@code LA(1)} returns <seealso cref=\"#EOF\"/></li>\n    /// </ul>\n    ///\n    /// This operation is guaranteed to not throw an exception if {@code index}\n    /// lies within a marked region. For more information on marked regions, see\n    /// <seealso cref=\"#mark\"/>. The behavior of this method is unspecified if no call to\n    /// an <seealso cref=\"IntStream initializing method\"/> has occurred after this stream\n    /// was constructed.\n    /// </summary>\n    /// <param name=\"index\"> The absolute index to seek to.\n    /// </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code index} is less than 0 </exception>\n    /// <exception cref=\"UnsupportedOperationException\"> if the stream does not support\n    /// seeking to the specified index </exception>\n    virtual void seek(size_t index) = 0;\n\n    /// <summary>\n    /// Returns the total number of symbols in the stream, including a single EOF\n    /// symbol.\n    /// </summary>\n    /// <exception cref=\"UnsupportedOperationException\"> if the size of the stream is\n    /// unknown. </exception>\n    virtual size_t size() = 0;\n\n    /// <summary>\n    /// Gets the name of the underlying symbol source. This method returns a\n    /// non-null, non-empty string. If such a name is not known, this method\n    /// returns <seealso cref=\"#UNKNOWN_SOURCE_NAME\"/>.\n    /// </summary>\n    virtual std::string getSourceName() const = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/InterpreterRuleContext.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"InterpreterRuleContext.h\"\n\nusing namespace antlr4;\n\nInterpreterRuleContext::InterpreterRuleContext() : ParserRuleContext() {\n}\n\nInterpreterRuleContext::InterpreterRuleContext(ParserRuleContext *parent, size_t invokingStateNumber, size_t ruleIndex)\n  : ParserRuleContext(parent, invokingStateNumber), _ruleIndex(ruleIndex) {\n}\n\nsize_t InterpreterRuleContext::getRuleIndex() const {\n  return _ruleIndex;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/InterpreterRuleContext.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"ParserRuleContext.h\"\n\nnamespace antlr4 {\n\n  /**\n   * This class extends {@link ParserRuleContext} by allowing the value of\n   * {@link #getRuleIndex} to be explicitly set for the context.\n   *\n   * <p>\n   * {@link ParserRuleContext} does not include field storage for the rule index\n   * since the context classes created by the code generator override the\n   * {@link #getRuleIndex} method to return the correct value for that context.\n   * Since the parser interpreter does not use the context classes generated for a\n   * parser, this class (with slightly more memory overhead per node) is used to\n   * provide equivalent functionality.</p>\n   */\n  class ANTLR4CPP_PUBLIC InterpreterRuleContext : public ParserRuleContext {\n  public:\n    InterpreterRuleContext();\n\n    /**\n     * Constructs a new {@link InterpreterRuleContext} with the specified\n     * parent, invoking state, and rule index.\n     *\n     * @param parent The parent context.\n     * @param invokingStateNumber The invoking state number.\n     * @param ruleIndex The rule index for the current context.\n     */\n    InterpreterRuleContext(ParserRuleContext *parent, size_t invokingStateNumber, size_t ruleIndex);\n\n    size_t getRuleIndex() const override;\n\n  protected:\n    /** This is the backing field for {@link #getRuleIndex}. */\n    const size_t _ruleIndex = INVALID_INDEX;\n};\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Lexer.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"atn/LexerATNSimulator.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"Exceptions.h\"\n#include \"misc/Interval.h\"\n#include \"CommonTokenFactory.h\"\n#include \"LexerNoViableAltException.h\"\n#include \"ANTLRErrorListener.h\"\n#include \"support/CPPUtils.h\"\n#include \"CommonToken.h\"\n\n#include \"Lexer.h\"\n\n#define DEBUG_LEXER 0\n\nusing namespace antlrcpp;\nusing namespace antlr4;\n\nLexer::Lexer() : Recognizer() {\n  InitializeInstanceFields();\n  _input = nullptr;\n}\n\nLexer::Lexer(CharStream *input) : Recognizer(), _input(input) {\n  InitializeInstanceFields();\n}\n\nvoid Lexer::reset() {\n  // wack Lexer state variables\n  _input->seek(0); // rewind the input\n\n  _syntaxErrors = 0;\n  token.reset();\n  type = Token::INVALID_TYPE;\n  channel = Token::DEFAULT_CHANNEL;\n  tokenStartCharIndex = INVALID_INDEX;\n  tokenStartCharPositionInLine = 0;\n  tokenStartLine = 0;\n  type = 0;\n  _text = \"\";\n\n  hitEOF = false;\n  mode = Lexer::DEFAULT_MODE;\n  modeStack.clear();\n\n  getInterpreter<atn::LexerATNSimulator>()->reset();\n}\n\nstd::unique_ptr<Token> Lexer::nextToken() {\n  // Mark start location in char stream so unbuffered streams are\n  // guaranteed at least have text of current token\n  ssize_t tokenStartMarker = _input->mark();\n\n  auto onExit = finally([this, tokenStartMarker]{\n    // make sure we release marker after match or\n    // unbuffered char stream will keep buffering\n    _input->release(tokenStartMarker);\n  });\n\n  while (true) {\n  outerContinue:\n    if (hitEOF) {\n      emitEOF();\n      return std::move(token);\n    }\n\n    token.reset();\n    channel = Token::DEFAULT_CHANNEL;\n    tokenStartCharIndex = _input->index();\n    tokenStartCharPositionInLine = getInterpreter<atn::LexerATNSimulator>()->getCharPositionInLine();\n    tokenStartLine = getInterpreter<atn::LexerATNSimulator>()->getLine();\n    _text = \"\";\n    do {\n      type = Token::INVALID_TYPE;\n      size_t ttype;\n      try {\n        ttype = getInterpreter<atn::LexerATNSimulator>()->match(_input, mode);\n      } catch (LexerNoViableAltException &e) {\n        notifyListeners(e); // report error\n        recover(e);\n        ttype = SKIP;\n      }\n      if (_input->LA(1) == EOF) {\n        hitEOF = true;\n      }\n      if (type == Token::INVALID_TYPE) {\n        type = ttype;\n      }\n      if (type == SKIP) {\n        goto outerContinue;\n      }\n    } while (type == MORE);\n    if (token == nullptr) {\n      emit();\n    }\n    return std::move(token);\n  }\n}\n\nvoid Lexer::skip() {\n  type = SKIP;\n}\n\nvoid Lexer::more() {\n  type = MORE;\n}\n\nvoid Lexer::setMode(size_t m) {\n  mode = m;\n}\n\nvoid Lexer::pushMode(size_t m) {\n#if DEBUG_LEXER == 1\n    std::cout << \"pushMode \" << m << std::endl;\n#endif\n\n  modeStack.push_back(mode);\n  setMode(m);\n}\n\nsize_t Lexer::popMode() {\n  if (modeStack.empty()) {\n    throw EmptyStackException();\n  }\n#if DEBUG_LEXER == 1\n    std::cout << std::string(\"popMode back to \") << modeStack.back() << std::endl;\n#endif\n\n  setMode(modeStack.back());\n  modeStack.pop_back();\n  return mode;\n}\n\n\nTokenFactory<CommonToken>* Lexer::getTokenFactory() {\n  return _factory;\n}\n\nvoid Lexer::setInputStream(IntStream *input) {\n  reset();\n  _input = dynamic_cast<CharStream*>(input);\n}\n\nstd::string Lexer::getSourceName() {\n  return _input->getSourceName();\n}\n\nCharStream* Lexer::getInputStream() {\n  return _input;\n}\n\nvoid Lexer::emit(std::unique_ptr<Token> newToken) {\n  token = std::move(newToken);\n}\n\nToken* Lexer::emit() {\n  emit(_factory->create({ this, _input }, type, _text, channel,\n    tokenStartCharIndex, getCharIndex() - 1, tokenStartLine, tokenStartCharPositionInLine));\n  return token.get();\n}\n\nToken* Lexer::emitEOF() {\n  size_t cpos = getCharPositionInLine();\n  size_t line = getLine();\n  emit(_factory->create({ this, _input }, EOF, \"\", Token::DEFAULT_CHANNEL, _input->index(), _input->index() - 1, line, cpos));\n  return token.get();\n}\n\nsize_t Lexer::getLine() const {\n  return getInterpreter<atn::LexerATNSimulator>()->getLine();\n}\n\nsize_t Lexer::getCharPositionInLine() {\n  return getInterpreter<atn::LexerATNSimulator>()->getCharPositionInLine();\n}\n\nvoid Lexer::setLine(size_t line) {\n  getInterpreter<atn::LexerATNSimulator>()->setLine(line);\n}\n\nvoid Lexer::setCharPositionInLine(size_t charPositionInLine) {\n  getInterpreter<atn::LexerATNSimulator>()->setCharPositionInLine(charPositionInLine);\n}\n\nsize_t Lexer::getCharIndex() {\n  return _input->index();\n}\n\nstd::string Lexer::getText() {\n  if (!_text.empty()) {\n    return _text;\n  }\n  return getInterpreter<atn::LexerATNSimulator>()->getText(_input);\n}\n\nvoid Lexer::setText(const std::string &text) {\n  _text = text;\n}\n\nstd::unique_ptr<Token> Lexer::getToken() {\n  return std::move(token);\n}\n\nvoid Lexer::setToken(std::unique_ptr<Token> newToken) {\n  token = std::move(newToken);\n}\n\nvoid Lexer::setType(size_t ttype) {\n  type = ttype;\n}\n\nsize_t Lexer::getType() {\n  return type;\n}\n\nvoid Lexer::setChannel(size_t newChannel) {\n  channel = newChannel;\n}\n\nsize_t Lexer::getChannel() {\n  return channel;\n}\n\nstd::vector<std::unique_ptr<Token>> Lexer::getAllTokens() {\n  std::vector<std::unique_ptr<Token>> tokens;\n  std::unique_ptr<Token> t = nextToken();\n  while (t->getType() != EOF) {\n    tokens.push_back(std::move(t));\n    t = nextToken();\n  }\n  return tokens;\n}\n\nvoid Lexer::recover(const LexerNoViableAltException &/*e*/) {\n  if (_input->LA(1) != EOF) {\n    // skip a char and try again\n    getInterpreter<atn::LexerATNSimulator>()->consume(_input);\n  }\n}\n\nvoid Lexer::notifyListeners(const LexerNoViableAltException & /*e*/) {\n  ++_syntaxErrors;\n  std::string text = _input->getText(misc::Interval(tokenStartCharIndex, _input->index()));\n  std::string msg = std::string(\"token recognition error at: '\") + getErrorDisplay(text) + std::string(\"'\");\n\n  ProxyErrorListener &listener = getErrorListenerDispatch();\n  listener.syntaxError(this, nullptr, tokenStartLine, tokenStartCharPositionInLine, msg, std::current_exception());\n}\n\nstd::string Lexer::getErrorDisplay(const std::string &s) {\n  std::stringstream ss;\n  for (auto c : s) {\n    switch (c) {\n    case '\\n':\n      ss << \"\\\\n\";\n      break;\n    case '\\t':\n      ss << \"\\\\t\";\n      break;\n    case '\\r':\n      ss << \"\\\\r\";\n      break;\n    default:\n      ss << c;\n      break;\n    }\n  }\n  return ss.str();\n}\n\nvoid Lexer::recover(RecognitionException * /*re*/) {\n  // TODO: Do we lose character or line position information?\n  _input->consume();\n}\n\nsize_t Lexer::getNumberOfSyntaxErrors() {\n  return _syntaxErrors;\n}\n\nvoid Lexer::InitializeInstanceFields() {\n  _syntaxErrors = 0;\n  token = nullptr;\n  _factory = CommonTokenFactory::DEFAULT.get();\n  tokenStartCharIndex = INVALID_INDEX;\n  tokenStartLine = 0;\n  tokenStartCharPositionInLine = 0;\n  hitEOF = false;\n  channel = 0;\n  type = 0;\n  mode = Lexer::DEFAULT_MODE;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Lexer.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <limits>\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"Recognizer.h\"\n#include \"antlr4-common.h\"\n#include \"TokenSource.h\"\n#include \"CharStream.h\"\n#include \"Token.h\"\n\nnamespace antlr4 {\n\n  /// A lexer is recognizer that draws input symbols from a character stream.\n  /// lexer grammars result in a subclass of this object. A Lexer object\n  /// uses simplified match() and error recovery mechanisms in the interest\n  /// of speed.\n  class ANTLR4CPP_PUBLIC Lexer : public Recognizer, public TokenSource {\n  public:\n    static constexpr size_t DEFAULT_MODE = 0;\n    static constexpr size_t MORE = std::numeric_limits<size_t>::max() - 1;\n    static constexpr size_t SKIP = std::numeric_limits<size_t>::max() - 2;\n\n    static constexpr size_t DEFAULT_TOKEN_CHANNEL = Token::DEFAULT_CHANNEL;\n    static constexpr size_t HIDDEN = Token::HIDDEN_CHANNEL;\n    static constexpr size_t MIN_CHAR_VALUE = 0;\n    static constexpr size_t MAX_CHAR_VALUE = 0x10FFFF;\n\n    CharStream *_input; // Pure reference, usually from statically allocated instance.\n\n  protected:\n    /// How to create token objects.\n    TokenFactory<CommonToken> *_factory;\n\n  public:\n    /// The goal of all lexer rules/methods is to create a token object.\n    ///  This is an instance variable as multiple rules may collaborate to\n    ///  create a single token.  nextToken will return this object after\n    ///  matching lexer rule(s).  If you subclass to allow multiple token\n    ///  emissions, then set this to the last token to be matched or\n    ///  something nonnull so that the auto token emit mechanism will not\n    ///  emit another token.\n\n    // Life cycle of a token is this:\n    // Created by emit() (via the token factory) or by action code, holding ownership of it.\n    // Ownership is handed over to the token stream when calling nextToken().\n    std::unique_ptr<Token> token;\n\n    /// <summary>\n    /// What character index in the stream did the current token start at?\n    ///  Needed, for example, to get the text for current token.  Set at\n    ///  the start of nextToken.\n    /// </summary>\n    size_t tokenStartCharIndex;\n\n    /// <summary>\n    /// The line on which the first character of the token resides </summary>\n    size_t tokenStartLine;\n\n    /// The character position of first character within the line.\n    size_t tokenStartCharPositionInLine;\n\n    /// Once we see EOF on char stream, next token will be EOF.\n    /// If you have DONE : EOF ; then you see DONE EOF.\n    bool hitEOF;\n\n    /// The channel number for the current token.\n    size_t channel;\n\n    /// The token type for the current token.\n    size_t type;\n\n    // Use the vector as a stack.\n    std::vector<size_t> modeStack;\n    size_t mode;\n\n    Lexer();\n    Lexer(CharStream *input);\n    ~Lexer() override {}\n\n    virtual void reset();\n\n    /// Return a token from this source; i.e., match a token on the char stream.\n    std::unique_ptr<Token> nextToken() override;\n\n    /// Instruct the lexer to skip creating a token for current lexer rule\n    /// and look for another token.  nextToken() knows to keep looking when\n    /// a lexer rule finishes with token set to SKIP_TOKEN.  Recall that\n    /// if token == null at end of any token rule, it creates one for you\n    /// and emits it.\n    virtual void skip();\n    virtual void more();\n    virtual void setMode(size_t m);\n    virtual void pushMode(size_t m);\n    virtual size_t popMode();\n\n    template<typename T1>\n    void setTokenFactory(TokenFactory<T1> *factory)  {\n      this->_factory = factory;\n    }\n\n    TokenFactory<CommonToken>* getTokenFactory() override;\n\n    /// Set the char stream and reset the lexer\n    void setInputStream(IntStream *input) override;\n\n    std::string getSourceName() override;\n\n    CharStream* getInputStream() override;\n\n    /// By default does not support multiple emits per nextToken invocation\n    /// for efficiency reasons. Subclasses can override this method, nextToken,\n    /// and getToken (to push tokens into a list and pull from that list\n    /// rather than a single variable as this implementation does).\n    virtual void emit(std::unique_ptr<Token> newToken);\n\n    /// The standard method called to automatically emit a token at the\n    /// outermost lexical rule.  The token object should point into the\n    /// char buffer start..stop.  If there is a text override in 'text',\n    /// use that to set the token's text.  Override this method to emit\n    /// custom Token objects or provide a new factory.\n    virtual Token* emit();\n\n    virtual Token* emitEOF();\n\n    size_t getLine() const override;\n\n    size_t getCharPositionInLine() override;\n\n    virtual void setLine(size_t line);\n\n    virtual void setCharPositionInLine(size_t charPositionInLine);\n\n    /// What is the index of the current character of lookahead?\n    virtual size_t getCharIndex();\n\n    /// Return the text matched so far for the current token or any\n    /// text override.\n    virtual std::string getText();\n\n    /// Set the complete text of this token; it wipes any previous\n    /// changes to the text.\n    virtual void setText(const std::string &text);\n\n    /// Override if emitting multiple tokens.\n    virtual std::unique_ptr<Token> getToken();\n\n    virtual void setToken(std::unique_ptr<Token> newToken);\n\n    virtual void setType(size_t ttype);\n\n    virtual size_t getType();\n\n    virtual void setChannel(size_t newChannel);\n\n    virtual size_t getChannel();\n\n    virtual const std::vector<std::string>& getChannelNames() const = 0;\n\n    virtual const std::vector<std::string>& getModeNames() const = 0;\n\n    /// Return a list of all Token objects in input char stream.\n    /// Forces load of all tokens. Does not include EOF token.\n    virtual std::vector<std::unique_ptr<Token>> getAllTokens();\n\n    virtual void recover(const LexerNoViableAltException &e);\n\n    virtual void notifyListeners(const LexerNoViableAltException &e);\n\n    virtual std::string getErrorDisplay(const std::string &s);\n\n    /// Lexers can normally match any char in it's vocabulary after matching\n    /// a token, so do the easy thing and just kill a character and hope\n    /// it all works out.  You can instead use the rule invocation stack\n    /// to do sophisticated error recovery if you are in a fragment rule.\n    virtual void recover(RecognitionException *re);\n\n    /// <summary>\n    /// Gets the number of syntax errors reported during parsing. This value is\n    /// incremented each time <seealso cref=\"#notifyErrorListeners\"/> is called.\n    /// </summary>\n    /// <seealso cref= #notifyListeners </seealso>\n    virtual size_t getNumberOfSyntaxErrors();\n\n  protected:\n    /// You can set the text for the current token to override what is in\n    /// the input char buffer (via setText()).\n    std::string _text;\n\n  private:\n    size_t _syntaxErrors;\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/LexerInterpreter.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"atn/ATNType.h\"\n#include \"atn/LexerATNSimulator.h\"\n#include \"dfa/DFA.h\"\n#include \"Exceptions.h\"\n#include \"Vocabulary.h\"\n\n#include \"LexerInterpreter.h\"\n\nusing namespace antlr4;\n\nLexerInterpreter::LexerInterpreter(const std::string &grammarFileName, const dfa::Vocabulary &vocabulary,\n  const std::vector<std::string> &ruleNames, const std::vector<std::string> &channelNames, const std::vector<std::string> &modeNames,\n  const atn::ATN &atn, CharStream *input)\n  : Lexer(input), _grammarFileName(grammarFileName), _atn(atn), _ruleNames(ruleNames),\n                  _channelNames(channelNames), _modeNames(modeNames),\n                  _vocabulary(vocabulary) {\n\n  if (_atn.grammarType != atn::ATNType::LEXER) {\n    throw IllegalArgumentException(\"The ATN must be a lexer ATN.\");\n  }\n\n  for (size_t i = 0; i < atn.getNumberOfDecisions(); ++i) {\n    _decisionToDFA.push_back(dfa::DFA(_atn.getDecisionState(i), i));\n  }\n  _interpreter = new atn::LexerATNSimulator(this, _atn, _decisionToDFA, _sharedContextCache); /* mem-check: deleted in d-tor */\n}\n\nLexerInterpreter::~LexerInterpreter()\n{\n  delete _interpreter;\n}\n\nconst atn::ATN& LexerInterpreter::getATN() const {\n  return _atn;\n}\n\nstd::string LexerInterpreter::getGrammarFileName() const {\n  return _grammarFileName;\n}\n\nconst std::vector<std::string>& LexerInterpreter::getRuleNames() const {\n  return _ruleNames;\n}\n\nconst std::vector<std::string>& LexerInterpreter::getChannelNames() const {\n  return _channelNames;\n}\n\nconst std::vector<std::string>& LexerInterpreter::getModeNames() const {\n  return _modeNames;\n}\n\nconst dfa::Vocabulary& LexerInterpreter::getVocabulary() const {\n  return _vocabulary;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/LexerInterpreter.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include \"Lexer.h\"\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContext.h\"\n#include \"atn/PredictionContextCache.h\"\n#include \"Vocabulary.h\"\n\nnamespace antlr4 {\n\n  class ANTLR4CPP_PUBLIC LexerInterpreter : public Lexer {\n  public:\n    LexerInterpreter(const std::string &grammarFileName, const dfa::Vocabulary &vocabulary,\n                     const std::vector<std::string> &ruleNames, const std::vector<std::string> &channelNames,\n                     const std::vector<std::string> &modeNames, const atn::ATN &atn, CharStream *input);\n\n    ~LexerInterpreter() override;\n\n    const atn::ATN& getATN() const override;\n    std::string getGrammarFileName() const override;\n    const std::vector<std::string>& getRuleNames() const override;\n    const std::vector<std::string>& getChannelNames() const override;\n    const std::vector<std::string>& getModeNames() const override;\n\n    const dfa::Vocabulary& getVocabulary() const override;\n\n  protected:\n    const std::string _grammarFileName;\n    const atn::ATN &_atn;\n\n    const std::vector<std::string> &_ruleNames;\n    const std::vector<std::string> &_channelNames;\n    const std::vector<std::string> &_modeNames;\n    std::vector<dfa::DFA> _decisionToDFA;\n\n    atn::PredictionContextCache _sharedContextCache;\n\n  private:\n    dfa::Vocabulary _vocabulary;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/LexerNoViableAltException.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"misc/Interval.h\"\n#include \"support/CPPUtils.h\"\n#include \"CharStream.h\"\n#include \"Lexer.h\"\n\n#include \"LexerNoViableAltException.h\"\n\nusing namespace antlr4;\n\nLexerNoViableAltException::LexerNoViableAltException(Lexer *lexer, CharStream *input, size_t startIndex,\n                                                     atn::ATNConfigSet *deadEndConfigs)\n  : RecognitionException(lexer, input, nullptr, nullptr), _startIndex(startIndex), _deadEndConfigs(deadEndConfigs) {\n}\n\nsize_t LexerNoViableAltException::getStartIndex() {\n  return _startIndex;\n}\n\natn::ATNConfigSet* LexerNoViableAltException::getDeadEndConfigs() {\n  return _deadEndConfigs;\n}\n\nstd::string LexerNoViableAltException::toString() {\n  std::string symbol;\n  if (_startIndex < getInputStream()->size()) {\n    symbol = static_cast<CharStream *>(getInputStream())->getText(misc::Interval(_startIndex, _startIndex));\n    symbol = antlrcpp::escapeWhitespace(symbol, false);\n  }\n  std::string format = \"LexerNoViableAltException('\" + symbol + \"')\";\n  return format;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/LexerNoViableAltException.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"RecognitionException.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATNConfigSet.h\"\n\nnamespace antlr4 {\n\n  class ANTLR4CPP_PUBLIC LexerNoViableAltException : public RecognitionException {\n  public:\n    LexerNoViableAltException(Lexer *lexer, CharStream *input, size_t startIndex,\n                              atn::ATNConfigSet *deadEndConfigs);\n\n    virtual size_t getStartIndex();\n    virtual atn::ATNConfigSet* getDeadEndConfigs();\n    virtual std::string toString();\n\n  private:\n    /// Matching attempted at what input index?\n    const size_t _startIndex;\n\n    /// Which configurations did we try at input.index() that couldn't match input.LA(1)?\n    atn::ATNConfigSet *_deadEndConfigs;\n\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ListTokenSource.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"CommonToken.h\"\n#include \"CharStream.h\"\n\n#include \"ListTokenSource.h\"\n\nusing namespace antlr4;\n\nListTokenSource::ListTokenSource(std::vector<std::unique_ptr<Token>> tokens_) : ListTokenSource(std::move(tokens_), \"\") {\n}\n\nListTokenSource::ListTokenSource(std::vector<std::unique_ptr<Token>> tokens_, const std::string &sourceName_)\n  : tokens(std::move(tokens_)), sourceName(sourceName_) {\n  InitializeInstanceFields();\n  if (tokens.empty()) {\n    throw \"tokens cannot be null\";\n  }\n\n  // Check if there is an eof token and create one if not.\n  if (tokens.back()->getType() != Token::EOF) {\n    Token *lastToken = tokens.back().get();\n    size_t start = INVALID_INDEX;\n    size_t previousStop = lastToken->getStopIndex();\n    if (previousStop != INVALID_INDEX) {\n      start = previousStop + 1;\n    }\n\n    size_t stop = std::max(INVALID_INDEX, start - 1);\n    tokens.emplace_back((_factory->create({ this, getInputStream() }, Token::EOF, \"EOF\",\n      Token::DEFAULT_CHANNEL, start, stop, static_cast<int>(lastToken->getLine()), lastToken->getCharPositionInLine())));\n  }\n}\n\nsize_t ListTokenSource::getCharPositionInLine() {\n  if (i < tokens.size()) {\n    return tokens[i]->getCharPositionInLine();\n  }\n  return 0;\n}\n\nstd::unique_ptr<Token> ListTokenSource::nextToken() {\n  if (i < tokens.size()) {\n    return std::move(tokens[i++]);\n  }\n  return nullptr;\n}\n\nsize_t ListTokenSource::getLine() const {\n  if (i < tokens.size()) {\n    return tokens[i]->getLine();\n  }\n\n  return 1;\n}\n\nCharStream *ListTokenSource::getInputStream() {\n  if (i < tokens.size()) {\n    return tokens[i]->getInputStream();\n  } else if (!tokens.empty()) {\n    return tokens.back()->getInputStream();\n  }\n\n  // no input stream information is available\n  return nullptr;\n}\n\nstd::string ListTokenSource::getSourceName() {\n  if (sourceName != \"\") {\n    return sourceName;\n  }\n\n  CharStream *inputStream = getInputStream();\n  if (inputStream != nullptr) {\n    return inputStream->getSourceName();\n  }\n\n  return \"List\";\n}\n\nTokenFactory<CommonToken>* ListTokenSource::getTokenFactory() {\n  return _factory;\n}\n\nvoid ListTokenSource::InitializeInstanceFields() {\n  i = 0;\n  _factory = CommonTokenFactory::DEFAULT.get();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ListTokenSource.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"TokenSource.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"CommonTokenFactory.h\"\n\nnamespace antlr4 {\n\n  /// Provides an implementation of <seealso cref=\"TokenSource\"/> as a wrapper around a list\n  /// of <seealso cref=\"Token\"/> objects.\n  ///\n  /// If the final token in the list is an <seealso cref=\"Token#EOF\"/> token, it will be used\n  /// as the EOF token for every call to <seealso cref=\"#nextToken\"/> after the end of the\n  /// list is reached. Otherwise, an EOF token will be created.\n  class ANTLR4CPP_PUBLIC ListTokenSource : public TokenSource {\n  protected:\n    // This list will be emptied token by token as we call nextToken().\n    // Token streams can be used to buffer tokens for a while.\n    std::vector<std::unique_ptr<Token>> tokens;\n\n  private:\n    /// <summary>\n    /// The name of the input source. If this value is {@code null}, a call to\n    /// <seealso cref=\"#getSourceName\"/> should return the source name used to create the\n    /// the next token in <seealso cref=\"#tokens\"/> (or the previous token if the end of\n    /// the input has been reached).\n    /// </summary>\n    const std::string sourceName;\n\n  protected:\n    /// The index into <seealso cref=\"#tokens\"/> of token to return by the next call to\n    /// <seealso cref=\"#nextToken\"/>. The end of the input is indicated by this value\n    /// being greater than or equal to the number of items in <seealso cref=\"#tokens\"/>.\n    size_t i;\n\n  private:\n    /// This is the backing field for <seealso cref=\"#getTokenFactory\"/> and\n    /// <seealso cref=\"setTokenFactory\"/>.\n    TokenFactory<CommonToken> *_factory = CommonTokenFactory::DEFAULT.get();\n\n  public:\n    /// Constructs a new <seealso cref=\"ListTokenSource\"/> instance from the specified\n    /// collection of <seealso cref=\"Token\"/> objects.\n    ///\n    /// <param name=\"tokens\"> The collection of <seealso cref=\"Token\"/> objects to provide as a\n    /// <seealso cref=\"TokenSource\"/>. </param>\n    /// <exception cref=\"NullPointerException\"> if {@code tokens} is {@code null} </exception>\n    ListTokenSource(std::vector<std::unique_ptr<Token>> tokens);\n    ListTokenSource(const ListTokenSource& other) = delete;\n\n    ListTokenSource& operator = (const ListTokenSource& other) = delete;\n\n    /// <summary>\n    /// Constructs a new <seealso cref=\"ListTokenSource\"/> instance from the specified\n    /// collection of <seealso cref=\"Token\"/> objects and source name.\n    /// </summary>\n    /// <param name=\"tokens\"> The collection of <seealso cref=\"Token\"/> objects to provide as a\n    /// <seealso cref=\"TokenSource\"/>. </param>\n    /// <param name=\"sourceName\"> The name of the <seealso cref=\"TokenSource\"/>. If this value is\n    /// {@code null}, <seealso cref=\"#getSourceName\"/> will attempt to infer the name from\n    /// the next <seealso cref=\"Token\"/> (or the previous token if the end of the input has\n    /// been reached).\n    /// </param>\n    /// <exception cref=\"NullPointerException\"> if {@code tokens} is {@code null} </exception>\n    ListTokenSource(std::vector<std::unique_ptr<Token>> tokens_, const std::string &sourceName_);\n\n    size_t getCharPositionInLine() override;\n    std::unique_ptr<Token> nextToken() override;\n    size_t getLine() const override;\n    CharStream* getInputStream() override;\n    std::string getSourceName() override;\n\n    template<typename T1>\n    void setTokenFactory(TokenFactory<T1> *factory) {\n      this->_factory = factory;\n    }\n\n    TokenFactory<CommonToken>* getTokenFactory() override;\n\n  private:\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/NoViableAltException.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"Parser.h\"\n\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"NoViableAltException.h\"\n\nusing namespace antlr4;\n\nnamespace {\n\n// Create a normal shared pointer if the configurations are to be deleted. If not, then\n// the shared pointer is created with a deleter that does nothing.\nRef<atn::ATNConfigSet> buildConfigsRef(atn::ATNConfigSet *configs, bool deleteConfigs) {\n  if (deleteConfigs) {\n    return Ref<atn::ATNConfigSet>(configs);\n  } else {\n    return Ref<atn::ATNConfigSet>(configs, [](atn::ATNConfigSet *){});\n  }\n}\n\n}\n\nNoViableAltException::NoViableAltException(Parser *recognizer)\n  : NoViableAltException(recognizer, recognizer->getTokenStream(), recognizer->getCurrentToken(),\n                         recognizer->getCurrentToken(), nullptr, recognizer->getContext(), false) {\n}\n\nNoViableAltException::NoViableAltException(Parser *recognizer, TokenStream *input,Token *startToken,\n  Token *offendingToken, atn::ATNConfigSet *deadEndConfigs, ParserRuleContext *ctx, bool deleteConfigs)\n  : RecognitionException(\"No viable alternative\", recognizer, input, ctx, offendingToken),\n    _deadEndConfigs(buildConfigsRef(deadEndConfigs, deleteConfigs)), _startToken(startToken) {\n}\n\nNoViableAltException::~NoViableAltException() {\n}\n\nToken* NoViableAltException::getStartToken() const {\n  return _startToken;\n}\n\natn::ATNConfigSet* NoViableAltException::getDeadEndConfigs() const {\n  return _deadEndConfigs.get();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/NoViableAltException.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"RecognitionException.h\"\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"atn/ATNConfigSet.h\"\n\nnamespace antlr4 {\n\n  /// Indicates that the parser could not decide which of two or more paths\n  /// to take based upon the remaining input. It tracks the starting token\n  /// of the offending input and also knows where the parser was\n  /// in the various paths when the error. Reported by reportNoViableAlternative()\n  class ANTLR4CPP_PUBLIC NoViableAltException : public RecognitionException {\n  public:\n    NoViableAltException(Parser *recognizer); // LL(1) error\n    NoViableAltException(Parser *recognizer, TokenStream *input,Token *startToken,\n      Token *offendingToken, atn::ATNConfigSet *deadEndConfigs, ParserRuleContext *ctx, bool deleteConfigs);\n    ~NoViableAltException() override;\n    \n    virtual Token* getStartToken() const;\n    virtual atn::ATNConfigSet* getDeadEndConfigs() const;\n\n  private:\n    /// Which configurations did we try at input.index() that couldn't match input.LT(1)?\n    /// Shared pointer that conditionally deletes the configurations (based on flag\n    /// passed during construction)\n    Ref<atn::ATNConfigSet> _deadEndConfigs;\n\n    /// The token object at the start index; the input stream might\n    /// not be buffering tokens so get a reference to it. (At the\n    /// time the error occurred, of course the stream needs to keep a\n    /// buffer all of the tokens but later we might not have access to those.)\n    Token *_startToken;\n\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Parser.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"atn/ATNDeserializationOptions.h\"\n#include \"ANTLRErrorStrategy.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"tree/pattern/ParseTreePatternMatcher.h\"\n#include \"dfa/DFA.h\"\n#include \"ParserRuleContext.h\"\n#include \"tree/TerminalNode.h\"\n#include \"tree/ErrorNodeImpl.h\"\n#include \"Lexer.h\"\n#include \"atn/ParserATNSimulator.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/RuleStartState.h\"\n#include \"DefaultErrorStrategy.h\"\n#include \"atn/ATNDeserializer.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/ATN.h\"\n#include \"Exceptions.h\"\n#include \"ANTLRErrorListener.h\"\n#include \"tree/pattern/ParseTreePattern.h\"\n#include \"internal/Synchronization.h\"\n\n#include \"atn/ProfilingATNSimulator.h\"\n#include \"atn/ParseInfo.h\"\n\n#include \"Parser.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::internal;\nusing namespace antlrcpp;\n\nnamespace {\n\nstruct BypassAltsAtnCache final {\n  std::shared_mutex mutex;\n  /// This field maps from the serialized ATN string to the deserialized <seealso cref=\"ATN\"/> with\n  /// bypass alternatives.\n  ///\n  /// <seealso cref= ATNDeserializationOptions#isGenerateRuleBypassTransitions() </seealso>\n  std::map<std::vector<int32_t>, std::unique_ptr<const atn::ATN>, std::less<>> map;\n};\n\nBypassAltsAtnCache* getBypassAltsAtnCache() {\n  static BypassAltsAtnCache* const instance = new BypassAltsAtnCache();\n  return instance;\n}\n\n}\n\nParser::TraceListener::TraceListener(Parser *outerInstance_) : outerInstance(outerInstance_) {\n}\n\nParser::TraceListener::~TraceListener() {\n}\n\nvoid Parser::TraceListener::enterEveryRule(ParserRuleContext *ctx) {\n  std::cout << \"enter   \" << outerInstance->getRuleNames()[ctx->getRuleIndex()]\n    << \", LT(1)=\" << outerInstance->_input->LT(1)->getText() << std::endl;\n}\n\nvoid Parser::TraceListener::visitTerminal(tree::TerminalNode *node) {\n  std::cout << \"consume \" << node->getSymbol() << \" rule \"\n    << outerInstance->getRuleNames()[outerInstance->getContext()->getRuleIndex()] << std::endl;\n}\n\nvoid Parser::TraceListener::visitErrorNode(tree::ErrorNode * /*node*/) {\n}\n\nvoid Parser::TraceListener::exitEveryRule(ParserRuleContext *ctx) {\n  std::cout << \"exit    \" << outerInstance->getRuleNames()[ctx->getRuleIndex()]\n    << \", LT(1)=\" << outerInstance->_input->LT(1)->getText() << std::endl;\n}\n\nParser::TrimToSizeListener Parser::TrimToSizeListener::INSTANCE;\n\nParser::TrimToSizeListener::~TrimToSizeListener() {\n}\n\nvoid Parser::TrimToSizeListener::enterEveryRule(ParserRuleContext * /*ctx*/) {\n}\n\nvoid Parser::TrimToSizeListener::visitTerminal(tree::TerminalNode * /*node*/) {\n}\n\nvoid Parser::TrimToSizeListener::visitErrorNode(tree::ErrorNode * /*node*/) {\n}\n\nvoid Parser::TrimToSizeListener::exitEveryRule(ParserRuleContext * ctx) {\n  ctx->children.shrink_to_fit();\n}\n\nParser::Parser(TokenStream *input) {\n  InitializeInstanceFields();\n  setInputStream(input);\n}\n\nParser::~Parser() {\n  _tracker.reset();\n  delete _tracer;\n}\n\nvoid Parser::reset() {\n  if (getInputStream() != nullptr) {\n    getInputStream()->seek(0);\n  }\n  _errHandler->reset(this); // Watch out, this is not shared_ptr.reset().\n\n  _matchedEOF = false;\n  _syntaxErrors = 0;\n  setTrace(false);\n  _precedenceStack.clear();\n  _precedenceStack.push_back(0);\n  _ctx = nullptr;\n  _tracker.reset();\n\n  atn::ATNSimulator *interpreter = getInterpreter<atn::ParserATNSimulator>();\n  if (interpreter != nullptr) {\n    interpreter->reset();\n  }\n}\n\nToken* Parser::match(size_t ttype) {\n  Token *t = getCurrentToken();\n  if (t->getType() == ttype) {\n    if (ttype == EOF) {\n      _matchedEOF = true;\n    }\n    _errHandler->reportMatch(this);\n    consume();\n  } else {\n    t = _errHandler->recoverInline(this);\n    if (_buildParseTrees && t->getTokenIndex() == INVALID_INDEX) {\n      // we must have conjured up a new token during single token insertion\n      // if it's not the current symbol\n      _ctx->addChild(createErrorNode(t));\n    }\n  }\n  return t;\n}\n\nToken* Parser::matchWildcard() {\n  Token *t = getCurrentToken();\n  if (t->getType() > 0) {\n    _errHandler->reportMatch(this);\n    consume();\n  } else {\n    t = _errHandler->recoverInline(this);\n    if (_buildParseTrees && t->getTokenIndex() == INVALID_INDEX) {\n      // we must have conjured up a new token during single token insertion\n      // if it's not the current symbol\n      _ctx->addChild(createErrorNode(t));\n    }\n  }\n\n  return t;\n}\n\nvoid Parser::setBuildParseTree(bool buildParseTrees) {\n  this->_buildParseTrees = buildParseTrees;\n}\n\nbool Parser::getBuildParseTree() {\n  return _buildParseTrees;\n}\n\nvoid Parser::setTrimParseTree(bool trimParseTrees) {\n  if (trimParseTrees) {\n    if (getTrimParseTree()) {\n      return;\n    }\n    addParseListener(&TrimToSizeListener::INSTANCE);\n  } else {\n    removeParseListener(&TrimToSizeListener::INSTANCE);\n  }\n}\n\nbool Parser::getTrimParseTree() {\n  return std::find(getParseListeners().begin(), getParseListeners().end(), &TrimToSizeListener::INSTANCE) != getParseListeners().end();\n}\n\nstd::vector<tree::ParseTreeListener *> Parser::getParseListeners() {\n  return _parseListeners;\n}\n\nvoid Parser::addParseListener(tree::ParseTreeListener *listener) {\n  if (!listener) {\n    throw NullPointerException(\"listener\");\n  }\n\n  this->_parseListeners.push_back(listener);\n}\n\nvoid Parser::removeParseListener(tree::ParseTreeListener *listener) {\n  if (!_parseListeners.empty()) {\n    auto it = std::find(_parseListeners.begin(), _parseListeners.end(), listener);\n    if (it != _parseListeners.end()) {\n      _parseListeners.erase(it);\n    }\n  }\n}\n\nvoid Parser::removeParseListeners() {\n  _parseListeners.clear();\n}\n\nvoid Parser::triggerEnterRuleEvent() {\n  for (auto *listener : _parseListeners) {\n    listener->enterEveryRule(_ctx);\n    _ctx->enterRule(listener);\n  }\n}\n\nvoid Parser::triggerExitRuleEvent() {\n  // reverse order walk of listeners\n  for (auto it = _parseListeners.rbegin(); it != _parseListeners.rend(); ++it) {\n    _ctx->exitRule(*it);\n    (*it)->exitEveryRule(_ctx);\n  }\n}\n\nsize_t Parser::getNumberOfSyntaxErrors() {\n  return _syntaxErrors;\n}\n\nTokenFactory<CommonToken>* Parser::getTokenFactory() {\n  return _input->getTokenSource()->getTokenFactory();\n}\n\nconst atn::ATN& Parser::getATNWithBypassAlts() {\n  auto serializedAtn = getSerializedATN();\n  if (serializedAtn.empty()) {\n    throw UnsupportedOperationException(\"The current parser does not support an ATN with bypass alternatives.\");\n  }\n  // XXX: using the entire serialized ATN as key into the map is a big resource waste.\n  //      How large can that thing become?\n  auto *cache = getBypassAltsAtnCache();\n  {\n    std::shared_lock<std::shared_mutex> lock(cache->mutex);\n    auto existing = cache->map.find(serializedAtn);\n    if (existing != cache->map.end()) {\n      return *existing->second;\n    }\n  }\n\n  std::unique_lock<std::shared_mutex> lock(cache->mutex);\n  auto existing = cache->map.find(serializedAtn);\n  if (existing != cache->map.end()) {\n    return *existing->second;\n  }\n  atn::ATNDeserializationOptions deserializationOptions;\n  deserializationOptions.setGenerateRuleBypassTransitions(true);\n  atn::ATNDeserializer deserializer(deserializationOptions);\n  auto atn = deserializer.deserialize(serializedAtn);\n  return *cache->map.insert(std::make_pair(std::vector<int32_t>(serializedAtn.begin(), serializedAtn.end()), std::move(atn))).first->second;\n}\n\ntree::pattern::ParseTreePattern Parser::compileParseTreePattern(const std::string &pattern, int patternRuleIndex) {\n  if (getTokenStream() != nullptr) {\n    TokenSource *tokenSource = getTokenStream()->getTokenSource();\n    if (is<Lexer*>(tokenSource)) {\n      Lexer *lexer = dynamic_cast<Lexer *>(tokenSource);\n      return compileParseTreePattern(pattern, patternRuleIndex, lexer);\n    }\n  }\n  throw UnsupportedOperationException(\"Parser can't discover a lexer to use\");\n}\n\ntree::pattern::ParseTreePattern Parser::compileParseTreePattern(const std::string &pattern, int patternRuleIndex,\n  Lexer *lexer) {\n  tree::pattern::ParseTreePatternMatcher m(lexer, this);\n  return m.compile(pattern, patternRuleIndex);\n}\n\nRef<ANTLRErrorStrategy> Parser::getErrorHandler() {\n  return _errHandler;\n}\n\nvoid Parser::setErrorHandler(Ref<ANTLRErrorStrategy> const& handler) {\n  _errHandler = handler;\n}\n\nIntStream* Parser::getInputStream() {\n  return getTokenStream();\n}\n\nvoid Parser::setInputStream(IntStream *input) {\n  setTokenStream(static_cast<TokenStream*>(input));\n}\n\nTokenStream* Parser::getTokenStream() {\n  return _input;\n}\n\nvoid Parser::setTokenStream(TokenStream *input) {\n  _input = nullptr; // Just a reference we don't own.\n  reset();\n  _input = input;\n}\n\nToken* Parser::getCurrentToken() {\n  return _input->LT(1);\n}\n\nvoid Parser::notifyErrorListeners(const std::string &msg) {\n  notifyErrorListeners(getCurrentToken(), msg, nullptr);\n}\n\nvoid Parser::notifyErrorListeners(Token *offendingToken, const std::string &msg, std::exception_ptr e) {\n  _syntaxErrors++;\n  size_t line = offendingToken->getLine();\n  size_t charPositionInLine = offendingToken->getCharPositionInLine();\n\n  ProxyErrorListener &listener = getErrorListenerDispatch();\n  listener.syntaxError(this, offendingToken, line, charPositionInLine, msg, e);\n}\n\nToken* Parser::consume() {\n  Token *o = getCurrentToken();\n  if (o->getType() != EOF) {\n    getInputStream()->consume();\n  }\n\n  bool hasListener = _parseListeners.size() > 0 && !_parseListeners.empty();\n  if (_buildParseTrees || hasListener) {\n    if (_errHandler->inErrorRecoveryMode(this)) {\n      tree::ErrorNode *node = createErrorNode(o);\n      _ctx->addChild(node);\n      if (_parseListeners.size() > 0) {\n        for (auto *listener : _parseListeners) {\n          listener->visitErrorNode(node);\n        }\n      }\n    } else {\n      tree::TerminalNode *node = _ctx->addChild(createTerminalNode(o));\n      if (_parseListeners.size() > 0) {\n        for (auto *listener : _parseListeners) {\n          listener->visitTerminal(node);\n        }\n      }\n    }\n  }\n  return o;\n}\n\nvoid Parser::addContextToParseTree() {\n  // Add current context to parent if we have a parent.\n  if (_ctx->parent == nullptr)\n    return;\n\n  downCast<ParserRuleContext*>(_ctx->parent)->addChild(_ctx);\n}\n\nvoid Parser::enterRule(ParserRuleContext *localctx, size_t state, size_t /*ruleIndex*/) {\n  setState(state);\n  _ctx = localctx;\n  _ctx->start = _input->LT(1);\n  if (_buildParseTrees) {\n    addContextToParseTree();\n  }\n  if (_parseListeners.size() > 0) {\n    triggerEnterRuleEvent();\n  }\n}\n\nvoid Parser::exitRule() {\n  if (_matchedEOF) {\n    // if we have matched EOF, it cannot consume past EOF so we use LT(1) here\n    _ctx->stop = _input->LT(1); // LT(1) will be end of file\n  } else {\n    _ctx->stop = _input->LT(-1); // stop node is what we just matched\n  }\n\n  // trigger event on ctx, before it reverts to parent\n  if (_parseListeners.size() > 0) {\n    triggerExitRuleEvent();\n  }\n  setState(_ctx->invokingState);\n  _ctx = downCast<ParserRuleContext*>(_ctx->parent);\n}\n\nvoid Parser::enterOuterAlt(ParserRuleContext *localctx, size_t altNum) {\n  localctx->setAltNumber(altNum);\n\n  // if we have new localctx, make sure we replace existing ctx\n  // that is previous child of parse tree\n  if (_buildParseTrees && _ctx != localctx) {\n    if (_ctx->parent != nullptr) {\n      ParserRuleContext *parent = downCast<ParserRuleContext*>(_ctx->parent);\n      parent->removeLastChild();\n      parent->addChild(localctx);\n    }\n  }\n  _ctx = localctx;\n}\n\nint Parser::getPrecedence() const {\n  if (_precedenceStack.empty()) {\n    return -1;\n  }\n\n  return _precedenceStack.back();\n}\n\nvoid Parser::enterRecursionRule(ParserRuleContext *localctx, size_t ruleIndex) {\n  enterRecursionRule(localctx, getATN().ruleToStartState[ruleIndex]->stateNumber, ruleIndex, 0);\n}\n\nvoid Parser::enterRecursionRule(ParserRuleContext *localctx, size_t state, size_t /*ruleIndex*/, int precedence) {\n  setState(state);\n  _precedenceStack.push_back(precedence);\n  _ctx = localctx;\n  _ctx->start = _input->LT(1);\n  if (!_parseListeners.empty()) {\n    triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n  }\n}\n\nvoid Parser::pushNewRecursionContext(ParserRuleContext *localctx, size_t state, size_t /*ruleIndex*/) {\n  ParserRuleContext *previous = _ctx;\n  previous->parent = localctx;\n  previous->invokingState = state;\n  previous->stop = _input->LT(-1);\n\n  _ctx = localctx;\n  _ctx->start = previous->start;\n  if (_buildParseTrees) {\n    _ctx->addChild(previous);\n  }\n\n  if (_parseListeners.size() > 0) {\n    triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n  }\n}\n\nvoid Parser::unrollRecursionContexts(ParserRuleContext *parentctx) {\n  _precedenceStack.pop_back();\n  _ctx->stop = _input->LT(-1);\n  ParserRuleContext *retctx = _ctx; // save current ctx (return value)\n\n  // unroll so ctx is as it was before call to recursive method\n  if (_parseListeners.size() > 0) {\n    while (_ctx != parentctx) {\n      triggerExitRuleEvent();\n      _ctx = downCast<ParserRuleContext*>(_ctx->parent);\n    }\n  } else {\n    _ctx = parentctx;\n  }\n\n  // hook into tree\n  retctx->parent = parentctx;\n\n  if (_buildParseTrees && parentctx != nullptr) {\n    // add return ctx into invoking rule's tree\n    parentctx->addChild(retctx);\n  }\n}\n\nParserRuleContext* Parser::getInvokingContext(size_t ruleIndex) {\n  ParserRuleContext *p = _ctx;\n  while (p) {\n    if (p->getRuleIndex() == ruleIndex) {\n      return p;\n    }\n    if (p->parent == nullptr)\n      break;\n    p = downCast<ParserRuleContext*>(p->parent);\n  }\n  return nullptr;\n}\n\nParserRuleContext* Parser::getContext() {\n  return _ctx;\n}\n\nvoid Parser::setContext(ParserRuleContext *ctx) {\n  _ctx = ctx;\n}\n\nbool Parser::precpred(RuleContext * /*localctx*/, int precedence) {\n  return precedence >= _precedenceStack.back();\n}\n\nbool Parser::inContext(const std::string &/*context*/) {\n  // TODO: useful in parser?\n  return false;\n}\n\nbool Parser::isExpectedToken(size_t symbol) {\n  const atn::ATN &atn = getInterpreter<atn::ParserATNSimulator>()->atn;\n  ParserRuleContext *ctx = _ctx;\n  atn::ATNState *s = atn.states[getState()];\n  misc::IntervalSet following = atn.nextTokens(s);\n\n  if (following.contains(symbol)) {\n    return true;\n  }\n\n  if (!following.contains(Token::EPSILON)) {\n    return false;\n  }\n\n  while (ctx && ctx->invokingState != ATNState::INVALID_STATE_NUMBER && following.contains(Token::EPSILON)) {\n    atn::ATNState *invokingState = atn.states[ctx->invokingState];\n    const atn::RuleTransition *rt = static_cast<const atn::RuleTransition*>(invokingState->transitions[0].get());\n    following = atn.nextTokens(rt->followState);\n    if (following.contains(symbol)) {\n      return true;\n    }\n\n    ctx = downCast<ParserRuleContext*>(ctx->parent);\n  }\n\n  if (following.contains(Token::EPSILON) && symbol == EOF) {\n    return true;\n  }\n\n  return false;\n}\n\nbool Parser::isMatchedEOF() const {\n  return _matchedEOF;\n}\n\nmisc::IntervalSet Parser::getExpectedTokens() {\n  return getATN().getExpectedTokens(getState(), getContext());\n}\n\nmisc::IntervalSet Parser::getExpectedTokensWithinCurrentRule() {\n  const atn::ATN &atn = getInterpreter<atn::ParserATNSimulator>()->atn;\n  atn::ATNState *s = atn.states[getState()];\n  return atn.nextTokens(s);\n}\n\nsize_t Parser::getRuleIndex(const std::string &ruleName) {\n  const std::map<std::string, size_t> &m = getRuleIndexMap();\n  auto iterator = m.find(ruleName);\n  if (iterator == m.end()) {\n    return INVALID_INDEX;\n  }\n  return iterator->second;\n}\n\nParserRuleContext* Parser::getRuleContext() {\n  return _ctx;\n}\n\nstd::vector<std::string> Parser::getRuleInvocationStack() {\n  return getRuleInvocationStack(_ctx);\n}\n\nstd::vector<std::string> Parser::getRuleInvocationStack(RuleContext *p) {\n  std::vector<std::string> const& ruleNames = getRuleNames();\n  std::vector<std::string> stack;\n  RuleContext *run = p;\n  while (run != nullptr) {\n    // compute what follows who invoked us\n    size_t ruleIndex = run->getRuleIndex();\n    if (ruleIndex == INVALID_INDEX ) {\n      stack.push_back(\"n/a\");\n    } else {\n      stack.push_back(ruleNames[ruleIndex]);\n    }\n    if (!RuleContext::is(run->parent)) {\n      break;\n    }\n    run = downCast<RuleContext*>(run->parent);\n  }\n  return stack;\n}\n\nstd::vector<std::string> Parser::getDFAStrings() {\n  atn::ParserATNSimulator *simulator = getInterpreter<atn::ParserATNSimulator>();\n  if (!simulator->decisionToDFA.empty()) {\n    UniqueLock<Mutex> lck(_mutex);\n\n    std::vector<std::string> s;\n    for (size_t d = 0; d < simulator->decisionToDFA.size(); d++) {\n      dfa::DFA &dfa = simulator->decisionToDFA[d];\n      s.push_back(dfa.toString(getVocabulary()));\n    }\n    return s;\n  }\n  return std::vector<std::string>();\n}\n\nvoid Parser::dumpDFA() {\n  atn::ParserATNSimulator *simulator = getInterpreter<atn::ParserATNSimulator>();\n  if (!simulator->decisionToDFA.empty()) {\n    UniqueLock<Mutex> lck(_mutex);\n    bool seenOne = false;\n    for (size_t d = 0; d < simulator->decisionToDFA.size(); d++) {\n      dfa::DFA &dfa = simulator->decisionToDFA[d];\n      if (!dfa.states.empty()) {\n        if (seenOne) {\n          std::cout << std::endl;\n        }\n        std::cout << \"Decision \" << dfa.decision << \":\" << std::endl;\n        std::cout << dfa.toString(getVocabulary());\n        seenOne = true;\n      }\n    }\n  }\n}\n\nstd::string Parser::getSourceName() {\n  return _input->getSourceName();\n}\n\natn::ParseInfo Parser::getParseInfo() const {\n  atn::ParserATNSimulator *simulator = getInterpreter<atn::ParserATNSimulator>();\n  return atn::ParseInfo(dynamic_cast<atn::ProfilingATNSimulator*>(simulator));\n}\n\nvoid Parser::setProfile(bool profile) {\n  atn::ParserATNSimulator *interp = getInterpreter<atn::ParserATNSimulator>();\n  atn::PredictionMode saveMode = interp != nullptr ? interp->getPredictionMode() : atn::PredictionMode::LL;\n  if (profile) {\n    if (!is<atn::ProfilingATNSimulator *>(interp)) {\n      setInterpreter(new atn::ProfilingATNSimulator(this)); /* mem-check: replacing existing interpreter which gets deleted. */\n    }\n  } else if (is<atn::ProfilingATNSimulator *>(interp)) {\n    /* mem-check: replacing existing interpreter which gets deleted. */\n    atn::ParserATNSimulator *sim = new atn::ParserATNSimulator(this, getATN(), interp->decisionToDFA, interp->getSharedContextCache());\n    setInterpreter(sim);\n  }\n  getInterpreter<atn::ParserATNSimulator>()->setPredictionMode(saveMode);\n}\n\nvoid Parser::setTrace(bool trace) {\n  if (!trace) {\n    if (_tracer)\n      removeParseListener(_tracer);\n    delete _tracer;\n    _tracer = nullptr;\n  } else {\n    if (_tracer)\n      removeParseListener(_tracer); // Just in case this is triggered multiple times.\n    _tracer = new TraceListener(this);\n    addParseListener(_tracer);\n  }\n}\n\nbool Parser::isTrace() const {\n  return _tracer != nullptr;\n}\n\ntree::TerminalNode *Parser::createTerminalNode(Token *t) {\n  return _tracker.createInstance<tree::TerminalNodeImpl>(t);\n}\n\ntree::ErrorNode *Parser::createErrorNode(Token *t) {\n  return _tracker.createInstance<tree::ErrorNodeImpl>(t);\n}\n\nvoid Parser::InitializeInstanceFields() {\n  _errHandler = std::make_shared<DefaultErrorStrategy>();\n  _precedenceStack.clear();\n  _precedenceStack.push_back(0);\n  _buildParseTrees = true;\n  _syntaxErrors = 0;\n  _matchedEOF = false;\n  _input = nullptr;\n  _tracer = nullptr;\n  _ctx = nullptr;\n}\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Parser.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"Recognizer.h\"\n#include \"misc/IntervalSet.h\"\n#include \"ANTLRErrorStrategy.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"tree/ParseTreeListener.h\"\n#include \"tree/ParseTree.h\"\n#include \"TokenStream.h\"\n#include \"TokenSource.h\"\n#include \"misc/Interval.h\"\n\nnamespace antlr4 {\n\n  /// This is all the parsing support code essentially; most of it is error recovery stuff.\n  class ANTLR4CPP_PUBLIC Parser : public Recognizer {\n  public:\n\n    class TraceListener : public tree::ParseTreeListener {\n    public:\n      TraceListener(Parser *outerInstance);\n      ~TraceListener() override;\n\n      void enterEveryRule(ParserRuleContext *ctx) override;\n      void visitTerminal(tree::TerminalNode *node) override;\n      void visitErrorNode(tree::ErrorNode *node) override;\n      void exitEveryRule(ParserRuleContext *ctx) override;\n\n    private:\n      Parser *const outerInstance;\n    };\n\n    class TrimToSizeListener : public tree::ParseTreeListener {\n    public:\n      static TrimToSizeListener INSTANCE;\n\n      ~TrimToSizeListener() override;\n\n      void enterEveryRule(ParserRuleContext *ctx) override;\n      void visitTerminal(tree::TerminalNode *node) override;\n      void visitErrorNode(tree::ErrorNode *node) override;\n      void exitEveryRule(ParserRuleContext *ctx) override;\n    };\n\n    Parser(TokenStream *input);\n    ~Parser() override;\n\n    /// reset the parser's state\n    virtual void reset();\n\n    /// <summary>\n    /// Match current input symbol against {@code ttype}. If the symbol type\n    /// matches, <seealso cref=\"ANTLRErrorStrategy#reportMatch\"/> and <seealso cref=\"#consume\"/> are\n    /// called to complete the match process.\n    ///\n    /// If the symbol type does not match,\n    /// <seealso cref=\"ANTLRErrorStrategy#recoverInline\"/> is called on the current error\n    /// strategy to attempt recovery. If <seealso cref=\"#getBuildParseTree\"/> is\n    /// {@code true} and the token index of the symbol returned by\n    /// <seealso cref=\"ANTLRErrorStrategy#recoverInline\"/> is -1, the symbol is added to\n    /// the parse tree by calling {@link #createErrorNode(ParserRuleContext, Token)} then\n    /// {@link ParserRuleContext#addErrorNode(ErrorNode)}.\n    /// </summary>\n    /// <param name=\"ttype\"> the token type to match </param>\n    /// <returns> the matched symbol </returns>\n    /// <exception cref=\"RecognitionException\"> if the current input symbol did not match\n    /// {@code ttype} and the error strategy could not recover from the\n    /// mismatched symbol </exception>\n    virtual Token* match(size_t ttype);\n\n    /// <summary>\n    /// Match current input symbol as a wildcard. If the symbol type matches\n    /// (i.e. has a value greater than 0), <seealso cref=\"ANTLRErrorStrategy#reportMatch\"/>\n    /// and <seealso cref=\"#consume\"/> are called to complete the match process.\n    /// <p/>\n    /// If the symbol type does not match,\n    /// <seealso cref=\"ANTLRErrorStrategy#recoverInline\"/> is called on the current error\n    /// strategy to attempt recovery. If <seealso cref=\"#getBuildParseTree\"/> is\n    /// {@code true} and the token index of the symbol returned by\n    /// <seealso cref=\"ANTLRErrorStrategy#recoverInline\"/> is -1, the symbol is added to\n    /// the parse tree by calling <seealso cref=\"ParserRuleContext#addErrorNode\"/>.\n    /// </summary>\n    /// <returns> the matched symbol </returns>\n    /// <exception cref=\"RecognitionException\"> if the current input symbol did not match\n    /// a wildcard and the error strategy could not recover from the mismatched\n    /// symbol </exception>\n    virtual Token* matchWildcard();\n\n    /// <summary>\n    /// Track the <seealso cref=\"ParserRuleContext\"/> objects during the parse and hook\n    /// them up using the <seealso cref=\"ParserRuleContext#children\"/> list so that it\n    /// forms a parse tree. The <seealso cref=\"ParserRuleContext\"/> returned from the start\n    /// rule represents the root of the parse tree.\n    /// <p/>\n    /// Note that if we are not building parse trees, rule contexts only point\n    /// upwards. When a rule exits, it returns the context but that gets garbage\n    /// collected if nobody holds a reference. It points upwards but nobody\n    /// points at it.\n    /// <p/>\n    /// When we build parse trees, we are adding all of these contexts to\n    /// <seealso cref=\"ParserRuleContext#children\"/> list. Contexts are then not candidates\n    /// for garbage collection.\n    /// </summary>\n    virtual void setBuildParseTree(bool buildParseTrees);\n\n    /// <summary>\n    /// Gets whether or not a complete parse tree will be constructed while\n    /// parsing. This property is {@code true} for a newly constructed parser.\n    /// </summary>\n    /// <returns> {@code true} if a complete parse tree will be constructed while\n    /// parsing, otherwise {@code false} </returns>\n    virtual bool getBuildParseTree();\n\n    /// <summary>\n    /// Trim the internal lists of the parse tree during parsing to conserve memory.\n    /// This property is set to {@code false} by default for a newly constructed parser.\n    /// </summary>\n    /// <param name=\"trimParseTrees\"> {@code true} to trim the capacity of the <seealso cref=\"ParserRuleContext#children\"/>\n    /// list to its size after a rule is parsed. </param>\n    virtual void setTrimParseTree(bool trimParseTrees);\n\n    /// <returns> {@code true} if the <seealso cref=\"ParserRuleContext#children\"/> list is trimmed\n    /// using the default <seealso cref=\"Parser.TrimToSizeListener\"/> during the parse process. </returns>\n    virtual bool getTrimParseTree();\n\n    virtual std::vector<tree::ParseTreeListener *> getParseListeners();\n\n    /// <summary>\n    /// Registers {@code listener} to receive events during the parsing process.\n    /// <p/>\n    /// To support output-preserving grammar transformations (including but not\n    /// limited to left-recursion removal, automated left-factoring, and\n    /// optimized code generation), calls to listener methods during the parse\n    /// may differ substantially from calls made by\n    /// <seealso cref=\"ParseTreeWalker#DEFAULT\"/> used after the parse is complete. In\n    /// particular, rule entry and exit events may occur in a different order\n    /// during the parse than after the parser. In addition, calls to certain\n    /// rule entry methods may be omitted.\n    /// <p/>\n    /// With the following specific exceptions, calls to listener events are\n    /// <em>deterministic</em>, i.e. for identical input the calls to listener\n    /// methods will be the same.\n    ///\n    /// <ul>\n    /// <li>Alterations to the grammar used to generate code may change the\n    /// behavior of the listener calls.</li>\n    /// <li>Alterations to the command line options passed to ANTLR 4 when\n    /// generating the parser may change the behavior of the listener calls.</li>\n    /// <li>Changing the version of the ANTLR Tool used to generate the parser\n    /// may change the behavior of the listener calls.</li>\n    /// </ul>\n    /// </summary>\n    /// <param name=\"listener\"> the listener to add\n    /// </param>\n    /// <exception cref=\"NullPointerException\"> if {@code} listener is {@code null} </exception>\n    virtual void addParseListener(tree::ParseTreeListener *listener);\n\n    /// <summary>\n    /// Remove {@code listener} from the list of parse listeners.\n    /// <p/>\n    /// If {@code listener} is {@code null} or has not been added as a parse\n    /// listener, this method does nothing.\n    /// </summary>\n    /// <seealso cref= #addParseListener\n    /// </seealso>\n    /// <param name=\"listener\"> the listener to remove </param>\n    virtual void removeParseListener(tree::ParseTreeListener *listener);\n\n    /// <summary>\n    /// Remove all parse listeners.\n    /// </summary>\n    /// <seealso cref= #addParseListener </seealso>\n    virtual void removeParseListeners();\n\n    /// <summary>\n    /// Notify any parse listeners of an enter rule event.\n    /// </summary>\n    /// <seealso cref= #addParseListener </seealso>\n    virtual void triggerEnterRuleEvent();\n\n    /// <summary>\n    /// Notify any parse listeners of an exit rule event.\n    /// </summary>\n    /// <seealso cref= #addParseListener </seealso>\n    virtual void triggerExitRuleEvent();\n\n    /// <summary>\n    /// Gets the number of syntax errors reported during parsing. This value is\n    /// incremented each time <seealso cref=\"#notifyErrorListeners\"/> is called.\n    /// </summary>\n    /// <seealso cref= #notifyErrorListeners </seealso>\n    virtual size_t getNumberOfSyntaxErrors();\n\n    TokenFactory<CommonToken>* getTokenFactory() override;\n\n    /// <summary>\n    /// Tell our token source and error strategy about a new way to create tokens. </summary>\n    template<typename T1>\n    void setTokenFactory(TokenFactory<T1> *factory)  {\n      _input->getTokenSource()->setTokenFactory(factory);\n    }\n\n    /// The ATN with bypass alternatives is expensive to create so we create it\n    /// lazily. The ATN is owned by us.\n    virtual const atn::ATN& getATNWithBypassAlts();\n\n    /// <summary>\n    /// The preferred method of getting a tree pattern. For example, here's a\n    /// sample use:\n    ///\n    /// <pre>\n    /// ParseTree t = parser.expr();\n    /// ParseTreePattern p = parser.compileParseTreePattern(\"<ID>+0\", MyParser.RULE_expr);\n    /// ParseTreeMatch m = p.match(t);\n    /// String id = m.get(\"ID\");\n    /// </pre>\n    /// </summary>\n    virtual tree::pattern::ParseTreePattern compileParseTreePattern(const std::string &pattern, int patternRuleIndex);\n\n    /// <summary>\n    /// The same as <seealso cref=\"#compileParseTreePattern(String, int)\"/> but specify a\n    /// <seealso cref=\"Lexer\"/> rather than trying to deduce it from this parser.\n    /// </summary>\n    virtual tree::pattern::ParseTreePattern compileParseTreePattern(const std::string &pattern, int patternRuleIndex,\n                                                                    Lexer *lexer);\n\n    virtual Ref<ANTLRErrorStrategy> getErrorHandler();\n    virtual void setErrorHandler(Ref<ANTLRErrorStrategy> const& handler);\n\n    IntStream* getInputStream() override;\n    void setInputStream(IntStream *input) override;\n\n    virtual TokenStream* getTokenStream();\n\n    /// Set the token stream and reset the parser.\n    virtual void setTokenStream(TokenStream *input);\n\n    /// <summary>\n    /// Match needs to return the current input symbol, which gets put\n    ///  into the label for the associated token ref; e.g., x=ID.\n    /// </summary>\n    virtual Token* getCurrentToken();\n\n    void notifyErrorListeners(const std::string &msg);\n\n    virtual void notifyErrorListeners(Token *offendingToken, const std::string &msg, std::exception_ptr e);\n\n    /// Consume and return the <seealso cref=\"#getCurrentToken current symbol\"/>.\n    /// <p/>\n    /// E.g., given the following input with {@code A} being the current\n    /// lookahead symbol, this function moves the cursor to {@code B} and returns\n    /// {@code A}.\n    ///\n    /// <pre>\n    ///  A B\n    ///  ^\n    /// </pre>\n    ///\n    /// If the parser is not in error recovery mode, the consumed symbol is added\n    /// to the parse tree using <seealso cref=\"ParserRuleContext#addChild(TerminalNode)\"/>, and\n    /// <seealso cref=\"ParseTreeListener#visitTerminal\"/> is called on any parse listeners.\n    /// If the parser <em>is</em> in error recovery mode, the consumed symbol is\n    /// added to the parse tree using {@link #createErrorNode(ParserRuleContext, Token)} then\n    /// {@link ParserRuleContext#addErrorNode(ErrorNode)} and\n    /// <seealso cref=\"ParseTreeListener#visitErrorNode\"/> is called on any parse\n    /// listeners.\n    virtual Token* consume();\n\n    /// Always called by generated parsers upon entry to a rule. Access field\n    /// <seealso cref=\"#_ctx\"/> get the current context.\n    virtual void enterRule(ParserRuleContext *localctx, size_t state, size_t ruleIndex);\n\n    void exitRule();\n\n    virtual void enterOuterAlt(ParserRuleContext *localctx, size_t altNum);\n\n    /**\n     * Get the precedence level for the top-most precedence rule.\n     *\n     * @return The precedence level for the top-most precedence rule, or -1 if\n     * the parser context is not nested within a precedence rule.\n     */\n    int getPrecedence() const;\n\n    /// @deprecated Use\n    /// <seealso cref=\"#enterRecursionRule(ParserRuleContext, int, int, int)\"/> instead.\n    virtual void enterRecursionRule(ParserRuleContext *localctx, size_t ruleIndex);\n    virtual void enterRecursionRule(ParserRuleContext *localctx, size_t state, size_t ruleIndex, int precedence);\n\n    /** Like {@link #enterRule} but for recursive rules.\n     *  Make the current context the child of the incoming localctx.\n     */\n    virtual void pushNewRecursionContext(ParserRuleContext *localctx, size_t state, size_t ruleIndex);\n    virtual void unrollRecursionContexts(ParserRuleContext *parentctx);\n    virtual ParserRuleContext* getInvokingContext(size_t ruleIndex);\n    virtual ParserRuleContext* getContext();\n    virtual void setContext(ParserRuleContext *ctx);\n    bool precpred(RuleContext *localctx, int precedence) override;\n    virtual bool inContext(const std::string &context);\n\n    /// <summary>\n    /// Checks whether or not {@code symbol} can follow the current state in the\n    /// ATN. The behavior of this method is equivalent to the following, but is\n    /// implemented such that the complete context-sensitive follow set does not\n    /// need to be explicitly constructed.\n    ///\n    /// <pre>\n    /// return getExpectedTokens().contains(symbol);\n    /// </pre>\n    /// </summary>\n    /// <param name=\"symbol\"> the symbol type to check </param>\n    /// <returns> {@code true} if {@code symbol} can follow the current state in\n    /// the ATN, otherwise {@code false}. </returns>\n    virtual bool isExpectedToken(size_t symbol);\n\n    bool isMatchedEOF() const;\n\n    /// <summary>\n    /// Computes the set of input symbols which could follow the current parser\n    /// state and context, as given by <seealso cref=\"#getState\"/> and <seealso cref=\"#getContext\"/>,\n    /// respectively.\n    /// </summary>\n    /// <seealso cref= ATN#getExpectedTokens(int, RuleContext) </seealso>\n    virtual misc::IntervalSet getExpectedTokens();\n\n    virtual misc::IntervalSet getExpectedTokensWithinCurrentRule();\n\n    /// Get a rule's index (i.e., {@code RULE_ruleName} field) or INVALID_INDEX if not found.\n    virtual size_t getRuleIndex(const std::string &ruleName);\n\n    virtual ParserRuleContext* getRuleContext();\n\n    /// <summary>\n    /// Return List&lt;String&gt; of the rule names in your parser instance\n    ///  leading up to a call to the current rule.  You could override if\n    ///  you want more details such as the file/line info of where\n    ///  in the ATN a rule is invoked.\n    ///\n    ///  This is very useful for error messages.\n    /// </summary>\n    virtual std::vector<std::string> getRuleInvocationStack();\n\n    virtual std::vector<std::string> getRuleInvocationStack(RuleContext *p);\n\n    /// <summary>\n    /// For debugging and other purposes. </summary>\n    virtual std::vector<std::string> getDFAStrings();\n\n    /// <summary>\n    /// For debugging and other purposes. </summary>\n    virtual void dumpDFA();\n\n    virtual std::string getSourceName();\n\n    atn::ParseInfo getParseInfo() const;\n\n    /**\n     * @since 4.3\n     */\n    void setProfile(bool profile);\n\n    /// <summary>\n    /// During a parse is sometimes useful to listen in on the rule entry and exit\n    ///  events as well as token matches. This is for quick and dirty debugging.\n    /// </summary>\n    virtual void setTrace(bool trace);\n\n    /**\n     * Gets whether a {@link TraceListener} is registered as a parse listener\n     * for the parser.\n     *\n     * @see #setTrace(boolean)\n     */\n    bool isTrace() const;\n\n    tree::ParseTreeTracker& getTreeTracker() { return _tracker; }\n\n    /** How to create a token leaf node associated with a parent.\n     *  Typically, the terminal node to create is not a function of the parent\n     *  but this method must still set the parent pointer of the terminal node\n     *  returned. I would prefer having {@link ParserRuleContext#addAnyChild(ParseTree)}\n     *  set the parent pointer, but the parent pointer is implementation dependent\n     *  and currently there is no setParent() in {@link TerminalNode} (and can't\n     *  add method in Java 1.7 without breaking backward compatibility).\n     *\n     * @since 4.7\n     */\n    tree::TerminalNode *createTerminalNode(Token *t);\n\n    /** How to create an error node, given a token, associated with a parent.\n       *  Typically, the error node to create is not a function of the parent\n       *  but this method must still set the parent pointer of the terminal node\n       *  returned. I would prefer having {@link ParserRuleContext#addAnyChild(ParseTree)}\n       *  set the parent pointer, but the parent pointer is implementation dependent\n       *  and currently there is no setParent() in {@link ErrorNode} (and can't\n       *  add method in Java 1.7 without breaking backward compatibility).\n       *\n       * @since 4.7\n       */\n    tree::ErrorNode *createErrorNode(Token *t);\n\n  protected:\n    /// The ParserRuleContext object for the currently executing rule.\n    /// This is always non-null during the parsing process.\n    // ml: this is one of the contexts tracked in _allocatedContexts.\n    ParserRuleContext *_ctx;\n\n    /// The error handling strategy for the parser. The default is DefaultErrorStrategy.\n    /// See also getErrorHandler.\n    Ref<ANTLRErrorStrategy> _errHandler;\n\n    /// <summary>\n    /// The input stream.\n    /// </summary>\n    /// <seealso cref= #getInputStream </seealso>\n    /// <seealso cref= #setInputStream </seealso>\n    TokenStream *_input;\n\n    std::vector<int> _precedenceStack;\n\n    /// <summary>\n    /// Specifies whether or not the parser should construct a parse tree during\n    /// the parsing process. The default value is {@code true}.\n    /// </summary>\n    /// <seealso cref= #getBuildParseTree </seealso>\n    /// <seealso cref= #setBuildParseTree </seealso>\n    bool _buildParseTrees;\n\n    /// The list of <seealso cref=\"ParseTreeListener\"/> listeners registered to receive\n    /// events during the parse.\n    /// <seealso cref= #addParseListener </seealso>\n    std::vector<tree::ParseTreeListener *> _parseListeners;\n\n    /// <summary>\n    /// The number of syntax errors reported during parsing. This value is\n    /// incremented each time <seealso cref=\"#notifyErrorListeners\"/> is called.\n    /// </summary>\n    size_t _syntaxErrors;\n\n    /** Indicates parser has match()ed EOF token. See {@link #exitRule()}. */\n    bool _matchedEOF;\n\n    virtual void addContextToParseTree();\n\n    // All rule contexts created during a parse run. This is cleared when calling reset().\n    tree::ParseTreeTracker _tracker;\n\n  private:\n    /// When setTrace(true) is called, a reference to the\n    /// TraceListener is stored here so it can be easily removed in a\n    /// later call to setTrace(false). The listener itself is\n    /// implemented as a parser listener so this field is not directly used by\n    /// other parser methods.\n    TraceListener *_tracer;\n\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ParserInterpreter.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"dfa/DFA.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/RuleStartState.h\"\n#include \"InterpreterRuleContext.h\"\n#include \"atn/ParserATNSimulator.h\"\n#include \"ANTLRErrorStrategy.h\"\n#include \"atn/LoopEndState.h\"\n#include \"FailedPredicateException.h\"\n#include \"atn/StarLoopEntryState.h\"\n#include \"atn/AtomTransition.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/PredicateTransition.h\"\n#include \"atn/PrecedencePredicateTransition.h\"\n#include \"atn/ActionTransition.h\"\n#include \"atn/ATN.h\"\n#include \"atn/RuleStopState.h\"\n#include \"Lexer.h\"\n#include \"Token.h\"\n#include \"Vocabulary.h\"\n#include \"InputMismatchException.h\"\n#include \"CommonToken.h\"\n#include \"tree/ErrorNode.h\"\n\n#include \"support/CPPUtils.h\"\n#include \"support/Casts.h\"\n\n#include \"ParserInterpreter.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\n\nusing namespace antlrcpp;\n\nParserInterpreter::ParserInterpreter(const std::string &grammarFileName, const dfa::Vocabulary &vocabulary,\n  const std::vector<std::string> &ruleNames, const atn::ATN &atn, TokenStream *input)\n  : Parser(input), _grammarFileName(grammarFileName), _atn(atn), _ruleNames(ruleNames), _vocabulary(vocabulary) {\n\n  // init decision DFA\n  for (size_t i = 0; i < atn.getNumberOfDecisions(); ++i) {\n    atn::DecisionState *decisionState = atn.getDecisionState(i);\n    _decisionToDFA.push_back(dfa::DFA(decisionState, i));\n  }\n\n  // get atn simulator that knows how to do predictions\n  _interpreter = new atn::ParserATNSimulator(this, atn, _decisionToDFA, _sharedContextCache); /* mem-check: deleted in d-tor */\n}\n\nParserInterpreter::~ParserInterpreter() {\n  delete _interpreter;\n}\n\nvoid ParserInterpreter::reset() {\n  Parser::reset();\n  _overrideDecisionReached = false;\n  _overrideDecisionRoot = nullptr;\n}\n\nconst atn::ATN& ParserInterpreter::getATN() const {\n  return _atn;\n}\n\nconst dfa::Vocabulary& ParserInterpreter::getVocabulary() const {\n  return _vocabulary;\n}\n\nconst std::vector<std::string>& ParserInterpreter::getRuleNames() const {\n  return _ruleNames;\n}\n\nstd::string ParserInterpreter::getGrammarFileName() const {\n  return _grammarFileName;\n}\n\nParserRuleContext* ParserInterpreter::parse(size_t startRuleIndex) {\n  atn::RuleStartState *startRuleStartState = _atn.ruleToStartState[startRuleIndex];\n\n  _rootContext = createInterpreterRuleContext(nullptr, atn::ATNState::INVALID_STATE_NUMBER, startRuleIndex);\n\n  if (startRuleStartState->isLeftRecursiveRule) {\n    enterRecursionRule(_rootContext, startRuleStartState->stateNumber, startRuleIndex, 0);\n  } else {\n    enterRule(_rootContext, startRuleStartState->stateNumber, startRuleIndex);\n  }\n\n  while (true) {\n    atn::ATNState *p = getATNState();\n    switch (p->getStateType()) {\n      case atn::ATNStateType::RULE_STOP :\n        // pop; return from rule\n        if (_ctx->isEmpty()) {\n          if (startRuleStartState->isLeftRecursiveRule) {\n            ParserRuleContext *result = _ctx;\n            auto parentContext = _parentContextStack.top();\n            _parentContextStack.pop();\n            unrollRecursionContexts(parentContext.first);\n            return result;\n          } else {\n            exitRule();\n            return _rootContext;\n          }\n        }\n\n        visitRuleStopState(p);\n        break;\n\n      default :\n        try {\n          visitState(p);\n        }\n        catch (RecognitionException &e) {\n          setState(_atn.ruleToStopState[p->ruleIndex]->stateNumber);\n          getErrorHandler()->reportError(this, e);\n          getContext()->exception = std::current_exception();\n          recover(e);\n        }\n\n        break;\n    }\n  }\n}\n\nvoid ParserInterpreter::enterRecursionRule(ParserRuleContext *localctx, size_t state, size_t ruleIndex, int precedence) {\n  _parentContextStack.push({ _ctx, localctx->invokingState });\n  Parser::enterRecursionRule(localctx, state, ruleIndex, precedence);\n}\n\nvoid ParserInterpreter::addDecisionOverride(int decision, int tokenIndex, int forcedAlt) {\n  _overrideDecision = decision;\n  _overrideDecisionInputIndex = tokenIndex;\n  _overrideDecisionAlt = forcedAlt;\n}\n\nRef<InterpreterRuleContext> ParserInterpreter::getOverrideDecisionRoot() const {\n  return _overrideDecisionRoot;\n}\n\nInterpreterRuleContext* ParserInterpreter::getRootContext() {\n  return _rootContext;\n}\n\natn::ATNState* ParserInterpreter::getATNState() {\n  return _atn.states[getState()];\n}\n\nvoid ParserInterpreter::visitState(atn::ATNState *p) {\n  size_t predictedAlt = 1;\n  if (DecisionState::is(p)) {\n    predictedAlt = visitDecisionState(downCast<DecisionState*>(p));\n  }\n\n  const atn::Transition *transition = p->transitions[predictedAlt - 1].get();\n  switch (transition->getTransitionType()) {\n    case atn::TransitionType::EPSILON:\n      if (p->getStateType() == ATNStateType::STAR_LOOP_ENTRY &&\n        (downCast<StarLoopEntryState *>(p))->isPrecedenceDecision &&\n        !LoopEndState::is(transition->target)) {\n        // We are at the start of a left recursive rule's (...)* loop\n        // and we're not taking the exit branch of loop.\n        InterpreterRuleContext *localctx = createInterpreterRuleContext(_parentContextStack.top().first,\n          _parentContextStack.top().second, static_cast<int>(_ctx->getRuleIndex()));\n        pushNewRecursionContext(localctx, _atn.ruleToStartState[p->ruleIndex]->stateNumber, static_cast<int>(_ctx->getRuleIndex()));\n      }\n      break;\n\n    case atn::TransitionType::ATOM:\n      match(static_cast<int>(static_cast<const atn::AtomTransition*>(transition)->_label));\n      break;\n\n    case atn::TransitionType::RANGE:\n    case atn::TransitionType::SET:\n    case atn::TransitionType::NOT_SET:\n      if (!transition->matches(static_cast<int>(_input->LA(1)), Token::MIN_USER_TOKEN_TYPE, Lexer::MAX_CHAR_VALUE)) {\n        recoverInline();\n      }\n      matchWildcard();\n      break;\n\n    case atn::TransitionType::WILDCARD:\n      matchWildcard();\n      break;\n\n    case atn::TransitionType::RULE:\n    {\n      atn::RuleStartState *ruleStartState = static_cast<atn::RuleStartState*>(transition->target);\n      size_t ruleIndex = ruleStartState->ruleIndex;\n      InterpreterRuleContext *newctx = createInterpreterRuleContext(_ctx, p->stateNumber, ruleIndex);\n      if (ruleStartState->isLeftRecursiveRule) {\n        enterRecursionRule(newctx, ruleStartState->stateNumber, ruleIndex, static_cast<const atn::RuleTransition*>(transition)->precedence);\n      } else {\n        enterRule(newctx, transition->target->stateNumber, ruleIndex);\n      }\n    }\n      break;\n\n    case atn::TransitionType::PREDICATE:\n    {\n      const atn::PredicateTransition *predicateTransition = static_cast<const atn::PredicateTransition*>(transition);\n      if (!sempred(_ctx, predicateTransition->getRuleIndex(), predicateTransition->getPredIndex())) {\n        throw FailedPredicateException(this);\n      }\n    }\n      break;\n\n    case atn::TransitionType::ACTION:\n    {\n      const atn::ActionTransition *actionTransition = static_cast<const atn::ActionTransition*>(transition);\n      action(_ctx, actionTransition->ruleIndex, actionTransition->actionIndex);\n    }\n      break;\n\n    case atn::TransitionType::PRECEDENCE:\n    {\n      if (!precpred(_ctx, static_cast<const atn::PrecedencePredicateTransition*>(transition)->getPrecedence())) {\n        throw FailedPredicateException(this, \"precpred(_ctx, \" + std::to_string(static_cast<const atn::PrecedencePredicateTransition*>(transition)->getPrecedence()) +  \")\");\n      }\n    }\n      break;\n\n    default:\n      throw UnsupportedOperationException(\"Unrecognized ATN transition type.\");\n  }\n\n  setState(transition->target->stateNumber);\n}\n\nsize_t ParserInterpreter::visitDecisionState(DecisionState *p) {\n  size_t predictedAlt = 1;\n  if (p->transitions.size() > 1) {\n    getErrorHandler()->sync(this);\n    int decision = p->decision;\n    if (decision == _overrideDecision && _input->index() == _overrideDecisionInputIndex && !_overrideDecisionReached) {\n      predictedAlt = _overrideDecisionAlt;\n      _overrideDecisionReached = true;\n    } else {\n      predictedAlt = getInterpreter<ParserATNSimulator>()->adaptivePredict(_input, decision, _ctx);\n    }\n  }\n  return predictedAlt;\n}\n\nInterpreterRuleContext* ParserInterpreter::createInterpreterRuleContext(ParserRuleContext *parent,\n  size_t invokingStateNumber, size_t ruleIndex) {\n  return _tracker.createInstance<InterpreterRuleContext>(parent, invokingStateNumber, ruleIndex);\n}\n\nvoid ParserInterpreter::visitRuleStopState(atn::ATNState *p) {\n  atn::RuleStartState *ruleStartState = _atn.ruleToStartState[p->ruleIndex];\n  if (ruleStartState->isLeftRecursiveRule) {\n    std::pair<ParserRuleContext *, size_t> parentContext = _parentContextStack.top();\n    _parentContextStack.pop();\n\n    unrollRecursionContexts(parentContext.first);\n    setState(parentContext.second);\n  } else {\n    exitRule();\n  }\n\n  const atn::RuleTransition *ruleTransition = static_cast<const atn::RuleTransition*>(_atn.states[getState()]->transitions[0].get());\n  setState(ruleTransition->followState->stateNumber);\n}\n\nvoid ParserInterpreter::recover(RecognitionException &e) {\n  size_t i = _input->index();\n  getErrorHandler()->recover(this, std::make_exception_ptr(e));\n\n  if (_input->index() == i) {\n    // no input consumed, better add an error node\n    if (is<InputMismatchException *>(&e)) {\n      InputMismatchException &ime = static_cast<InputMismatchException&>(e);\n      Token *tok = e.getOffendingToken();\n      size_t expectedTokenType = ime.getExpectedTokens().getMinElement(); // get any element\n      _errorToken = getTokenFactory()->create({ tok->getTokenSource(), tok->getTokenSource()->getInputStream() },\n        expectedTokenType, tok->getText(), Token::DEFAULT_CHANNEL, INVALID_INDEX, INVALID_INDEX, // invalid start/stop\n        tok->getLine(), tok->getCharPositionInLine());\n      _ctx->addChild(createErrorNode(_errorToken.get()));\n    }\n    else { // NoViableAlt\n      Token *tok = e.getOffendingToken();\n      _errorToken = getTokenFactory()->create({ tok->getTokenSource(), tok->getTokenSource()->getInputStream() },\n        Token::INVALID_TYPE, tok->getText(), Token::DEFAULT_CHANNEL, INVALID_INDEX, INVALID_INDEX, // invalid start/stop\n        tok->getLine(), tok->getCharPositionInLine());\n      _ctx->addChild(createErrorNode(_errorToken.get()));\n    }\n  }\n}\n\nToken* ParserInterpreter::recoverInline() {\n  return _errHandler->recoverInline(this);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ParserInterpreter.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"Parser.h\"\n#include \"Token.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATN.h\"\n#include \"support/BitSet.h\"\n#include \"atn/PredictionContext.h\"\n#include \"atn/PredictionContextCache.h\"\n#include \"Vocabulary.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// A parser simulator that mimics what ANTLR's generated\n  ///  parser code does. A ParserATNSimulator is used to make\n  ///  predictions via adaptivePredict but this class moves a pointer through the\n  ///  ATN to simulate parsing. ParserATNSimulator just\n  ///  makes us efficient rather than having to backtrack, for example.\n  ///\n  ///  This properly creates parse trees even for left recursive rules.\n  ///\n  ///  We rely on the left recursive rule invocation and special predicate\n  ///  transitions to make left recursive rules work.\n  ///\n  ///  See TestParserInterpreter for examples.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC ParserInterpreter : public Parser {\n  public:\n    ParserInterpreter(const std::string &grammarFileName, const dfa::Vocabulary &vocabulary,\n                      const std::vector<std::string> &ruleNames, const atn::ATN &atn, TokenStream *input);\n    ~ParserInterpreter() override;\n\n    void reset() override;\n\n    const atn::ATN& getATN() const override;\n\n    const dfa::Vocabulary& getVocabulary() const override;\n\n    const std::vector<std::string>& getRuleNames() const override;\n    std::string getGrammarFileName() const override;\n\n    /// Begin parsing at startRuleIndex\n    virtual ParserRuleContext* parse(size_t startRuleIndex);\n\n    void enterRecursionRule(ParserRuleContext *localctx, size_t state, size_t ruleIndex, int precedence) override;\n\n\n    /** Override this parser interpreters normal decision-making process\n     *  at a particular decision and input token index. Instead of\n     *  allowing the adaptive prediction mechanism to choose the\n     *  first alternative within a block that leads to a successful parse,\n     *  force it to take the alternative, 1..n for n alternatives.\n     *\n     *  As an implementation limitation right now, you can only specify one\n     *  override. This is sufficient to allow construction of different\n     *  parse trees for ambiguous input. It means re-parsing the entire input\n     *  in general because you're never sure where an ambiguous sequence would\n     *  live in the various parse trees. For example, in one interpretation,\n     *  an ambiguous input sequence would be matched completely in expression\n     *  but in another it could match all the way back to the root.\n     *\n     *  s : e '!'? ;\n     *  e : ID\n     *    | ID '!'\n     *    ;\n     *\n     *  Here, x! can be matched as (s (e ID) !) or (s (e ID !)). In the first\n     *  case, the ambiguous sequence is fully contained only by the root.\n     *  In the second case, the ambiguous sequences fully contained within just\n     *  e, as in: (e ID !).\n     *\n     *  Rather than trying to optimize this and make\n     *  some intelligent decisions for optimization purposes, I settled on\n     *  just re-parsing the whole input and then using\n     *  {link Trees#getRootOfSubtreeEnclosingRegion} to find the minimal\n     *  subtree that contains the ambiguous sequence. I originally tried to\n     *  record the call stack at the point the parser detected and ambiguity but\n     *  left recursive rules create a parse tree stack that does not reflect\n     *  the actual call stack. That impedance mismatch was enough to make\n     *  it it challenging to restart the parser at a deeply nested rule\n     *  invocation.\n     *\n     *  Only parser interpreters can override decisions so as to avoid inserting\n     *  override checking code in the critical ALL(*) prediction execution path.\n     *\n     *  @since 4.5.1\n     */\n    void addDecisionOverride(int decision, int tokenIndex, int forcedAlt);\n\n    Ref<InterpreterRuleContext> getOverrideDecisionRoot() const;\n\n    /** Return the root of the parse, which can be useful if the parser\n     *  bails out. You still can access the top node. Note that,\n     *  because of the way left recursive rules add children, it's possible\n     *  that the root will not have any children if the start rule immediately\n     *  called and left recursive rule that fails.\n     *\n     * @since 4.5.1\n     */\n    InterpreterRuleContext* getRootContext();\n\n  protected:\n    const std::string _grammarFileName;\n    const atn::ATN &_atn;\n\n    std::vector<std::string> _ruleNames;\n\n    std::vector<dfa::DFA> _decisionToDFA; // not shared like it is for generated parsers\n    atn::PredictionContextCache _sharedContextCache;\n\n    /** This stack corresponds to the _parentctx, _parentState pair of locals\n     *  that would exist on call stack frames with a recursive descent parser;\n     *  in the generated function for a left-recursive rule you'd see:\n     *\n     *  private EContext e(int _p) throws RecognitionException {\n     *      ParserRuleContext _parentctx = _ctx;    // Pair.a\n     *      int _parentState = getState();          // Pair.b\n     *      ...\n     *  }\n     *\n     *  Those values are used to create new recursive rule invocation contexts\n     *  associated with left operand of an alt like \"expr '*' expr\".\n     */\n    std::stack<std::pair<ParserRuleContext *, size_t>> _parentContextStack;\n\n    /** We need a map from (decision,inputIndex)->forced alt for computing ambiguous\n     *  parse trees. For now, we allow exactly one override.\n     */\n    int _overrideDecision = -1;\n    size_t _overrideDecisionInputIndex = INVALID_INDEX;\n    size_t _overrideDecisionAlt = INVALID_INDEX;\n    bool _overrideDecisionReached = false; // latch and only override once; error might trigger infinite loop\n\n    /** What is the current context when we override a decision? This tells\n     *  us what the root of the parse tree is when using override\n     *  for an ambiguity/lookahead check.\n     */\n    Ref<InterpreterRuleContext> _overrideDecisionRoot;\n    InterpreterRuleContext* _rootContext;\n\n    virtual atn::ATNState *getATNState();\n    virtual void visitState(atn::ATNState *p);\n\n    /** Method visitDecisionState() is called when the interpreter reaches\n     *  a decision state (instance of DecisionState). It gives an opportunity\n     *  for subclasses to track interesting things.\n     */\n    size_t visitDecisionState(atn::DecisionState *p);\n\n    /** Provide simple \"factory\" for InterpreterRuleContext's.\n     *  @since 4.5.1\n     */\n    InterpreterRuleContext* createInterpreterRuleContext(ParserRuleContext *parent, size_t invokingStateNumber, size_t ruleIndex);\n\n    virtual void visitRuleStopState(atn::ATNState *p);\n\n    /** Rely on the error handler for this parser but, if no tokens are consumed\n     *  to recover, add an error node. Otherwise, nothing is seen in the parse\n     *  tree.\n     */\n    void recover(RecognitionException &e);\n    Token* recoverInline();\n\n  private:\n    const dfa::Vocabulary &_vocabulary;\n    std::unique_ptr<Token> _errorToken;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ParserRuleContext.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"tree/TerminalNode.h\"\n#include \"tree/ErrorNode.h\"\n#include \"misc/Interval.h\"\n#include \"Parser.h\"\n#include \"Token.h\"\n\n#include \"support/Casts.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"ParserRuleContext.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::tree;\n\nusing namespace antlrcpp;\n\nParserRuleContext ParserRuleContext::EMPTY;\n\nParserRuleContext::ParserRuleContext()\n  : start(nullptr), stop(nullptr) {\n}\n\nParserRuleContext::ParserRuleContext(ParserRuleContext *parent, size_t invokingStateNumber)\n: RuleContext(parent, invokingStateNumber), start(nullptr), stop(nullptr) {\n}\n\nvoid ParserRuleContext::copyFrom(ParserRuleContext *ctx) {\n  // from RuleContext\n  this->parent = ctx->parent;\n  this->invokingState = ctx->invokingState;\n\n  this->start = ctx->start;\n  this->stop = ctx->stop;\n\n  // copy any error nodes to alt label node\n  if (!ctx->children.empty()) {\n    for (auto *child : ctx->children) {\n      if (ErrorNode::is(child)) {\n        downCast<ErrorNode*>(child)->setParent(this);\n        children.push_back(child);\n      }\n    }\n\n    // Remove the just reparented error nodes from the source context.\n    ctx->children.erase(std::remove_if(ctx->children.begin(), ctx->children.end(), [this](tree::ParseTree *e) -> bool {\n      return std::find(children.begin(), children.end(), e) != children.end();\n    }), ctx->children.end());\n  }\n}\n\nvoid ParserRuleContext::enterRule(tree::ParseTreeListener * /*listener*/) {\n}\n\nvoid ParserRuleContext::exitRule(tree::ParseTreeListener * /*listener*/) {\n}\n\ntree::TerminalNode* ParserRuleContext::addChild(tree::TerminalNode *t) {\n  t->setParent(this);\n  children.push_back(t);\n  return t;\n}\n\nRuleContext* ParserRuleContext::addChild(RuleContext *ruleInvocation) {\n  children.push_back(ruleInvocation);\n  return ruleInvocation;\n}\n\nvoid ParserRuleContext::removeLastChild() {\n  if (!children.empty()) {\n    children.pop_back();\n  }\n}\n\ntree::TerminalNode* ParserRuleContext::getToken(size_t ttype, size_t i) const {\n  if (i >= children.size()) {\n    return nullptr;\n  }\n  size_t j = 0; // what token with ttype have we found?\n  for (auto *child : children) {\n    if (TerminalNode::is(child)) {\n      tree::TerminalNode *typedChild = downCast<tree::TerminalNode*>(child);\n      Token *symbol = typedChild->getSymbol();\n      if (symbol->getType() == ttype) {\n        if (j++ == i) {\n          return typedChild;\n        }\n      }\n    }\n  }\n  return nullptr;\n}\n\nstd::vector<tree::TerminalNode *> ParserRuleContext::getTokens(size_t ttype) const {\n  std::vector<tree::TerminalNode*> tokens;\n  for (auto *child : children) {\n    if (TerminalNode::is(child)) {\n      tree::TerminalNode *typedChild = downCast<tree::TerminalNode*>(child);\n      Token *symbol = typedChild->getSymbol();\n      if (symbol->getType() == ttype) {\n        tokens.push_back(typedChild);\n      }\n    }\n  }\n  return tokens;\n}\n\nmisc::Interval ParserRuleContext::getSourceInterval() {\n  if (start == nullptr) {\n    return misc::Interval::INVALID;\n  }\n\n  if (stop == nullptr || stop->getTokenIndex() < start->getTokenIndex()) {\n    return misc::Interval(start->getTokenIndex(), start->getTokenIndex() - 1); // empty\n  }\n  return misc::Interval(start->getTokenIndex(), stop->getTokenIndex());\n}\n\nToken* ParserRuleContext::getStart() const {\n  return start;\n}\n\nToken* ParserRuleContext::getStop() const {\n  return stop;\n}\n\nstd::string ParserRuleContext::toInfoString(Parser *recognizer) {\n  std::vector<std::string> rules = recognizer->getRuleInvocationStack(this);\n  std::reverse(rules.begin(), rules.end());\n  std::string rulesStr = antlrcpp::arrayToString(rules);\n  return \"ParserRuleContext\" + rulesStr + \"{start=\" + std::to_string(start->getTokenIndex()) + \", stop=\" +\n    std::to_string(stop->getTokenIndex()) + '}';\n}\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ParserRuleContext.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"RuleContext.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"support/CPPUtils.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// A rule invocation record for parsing.\n  ///\n  ///  Contains all of the information about the current rule not stored in the\n  ///  RuleContext. It handles parse tree children list, Any ATN state\n  ///  tracing, and the default values available for rule invocatons:\n  ///  start, stop, rule index, current alt number.\n  ///\n  ///  Subclasses made for each rule and grammar track the parameters,\n  ///  return values, locals, and labels specific to that rule. These\n  ///  are the objects that are returned from rules.\n  ///\n  ///  Note text is not an actual field of a rule return value; it is computed\n  ///  from start and stop using the input stream's toString() method.  I\n  ///  could add a ctor to this so that we can pass in and store the input\n  ///  stream, but I'm not sure we want to do that.  It would seem to be undefined\n  ///  to get the .text property anyway if the rule matches tokens from multiple\n  ///  input streams.\n  ///\n  ///  I do not use getters for fields of objects that are used simply to\n  ///  group values such as this aggregate.  The getters/setters are there to\n  ///  satisfy the superclass interface.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC ParserRuleContext : public RuleContext {\n  public:\n    static ParserRuleContext EMPTY;\n\n    /// <summary>\n    /// For debugging/tracing purposes, we want to track all of the nodes in\n    ///  the ATN traversed by the parser for a particular rule.\n    ///  This list indicates the sequence of ATN nodes used to match\n    ///  the elements of the children list. This list does not include\n    ///  ATN nodes and other rules used to match rule invocations. It\n    ///  traces the rule invocation node itself but nothing inside that\n    ///  other rule's ATN submachine.\n    ///\n    ///  There is NOT a one-to-one correspondence between the children and\n    ///  states list. There are typically many nodes in the ATN traversed\n    ///  for each element in the children list. For example, for a rule\n    ///  invocation there is the invoking state and the following state.\n    ///\n    ///  The parser setState() method updates field s and adds it to this list\n    ///  if we are debugging/tracing.\n    ///\n    ///  This does not trace states visited during prediction.\n    /// </summary>\n    //\tpublic List<Integer> states;\n\n    Token *start;\n    Token *stop;\n\n    /// The exception that forced this rule to return. If the rule successfully\n    /// completed, this is \"null exception pointer\".\n    std::exception_ptr exception;\n\n    ParserRuleContext();\n    ParserRuleContext(ParserRuleContext *parent, size_t invokingStateNumber);\n\n    /** COPY a ctx (I'm deliberately not using copy constructor) to avoid\n     *  confusion with creating node with parent. Does not copy children\n     *  (except error leaves).\n     */\n    virtual void copyFrom(ParserRuleContext *ctx);\n\n\n    // Double dispatch methods for listeners\n\n    virtual void enterRule(tree::ParseTreeListener *listener);\n    virtual void exitRule(tree::ParseTreeListener *listener);\n\n    /** Add a token leaf node child and force its parent to be this node. */\n    tree::TerminalNode* addChild(tree::TerminalNode *t);\n    RuleContext* addChild(RuleContext *ruleInvocation);\n\n    /// Used by enterOuterAlt to toss out a RuleContext previously added as\n    /// we entered a rule. If we have # label, we will need to remove\n    /// generic ruleContext object.\n    void removeLastChild();\n\n    tree::TerminalNode* getToken(size_t ttype, std::size_t i) const;\n\n    std::vector<tree::TerminalNode*> getTokens(size_t ttype) const;\n\n    template<typename T>\n    T* getRuleContext(size_t i) const {\n      static_assert(std::is_base_of_v<RuleContext, T>, \"T must be derived from RuleContext\");\n      size_t j = 0; // what element have we found with ctxType?\n      for (auto *child : children) {\n        if (RuleContext::is(child)) {\n          if (auto *typedChild = dynamic_cast<T*>(child); typedChild != nullptr) {\n            if (j++ == i) {\n              return typedChild;\n            }\n          }\n        }\n      }\n      return nullptr;\n    }\n\n    template<typename T>\n    std::vector<T*> getRuleContexts() const {\n      static_assert(std::is_base_of_v<RuleContext, T>, \"T must be derived from RuleContext\");\n      std::vector<T*> contexts;\n      for (auto *child : children) {\n        if (RuleContext::is(child)) {\n          if (auto *typedChild = dynamic_cast<T*>(child); typedChild != nullptr) {\n            contexts.push_back(typedChild);\n          }\n        }\n      }\n      return contexts;\n    }\n\n    misc::Interval getSourceInterval() override;\n\n    /**\n     * Get the initial token in this context.\n     * Note that the range from start to stop is inclusive, so for rules that do not consume anything\n     * (for example, zero length or error productions) this token may exceed stop.\n     */\n    Token* getStart() const;\n\n    /**\n     * Get the final token in this context.\n     * Note that the range from start to stop is inclusive, so for rules that do not consume anything\n     * (for example, zero length or error productions) this token may precede start.\n     */\n    Token* getStop() const;\n\n    /// <summary>\n    /// Used for rule context info debugging during parse-time, not so much for ATN debugging </summary>\n    virtual std::string toInfoString(Parser *recognizer);\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ProxyErrorListener.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"Token.h\"\n#include \"ANTLRErrorListener.h\"\n#include \"ProxyErrorListener.h\"\n\nusing namespace antlr4;\n\nvoid ProxyErrorListener::addErrorListener(ANTLRErrorListener *listener) {\n  if (listener == nullptr) {\n    throw \"listener cannot be null.\";\n  }\n\n  _delegates.insert(listener);\n}\n\nvoid ProxyErrorListener::removeErrorListener(ANTLRErrorListener *listener) {\n  _delegates.erase(listener);\n}\n\nvoid ProxyErrorListener::removeErrorListeners() {\n  _delegates.clear();\n}\n\nvoid ProxyErrorListener::syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line,\n  size_t charPositionInLine, const std::string &msg, std::exception_ptr e) {\n\n  for (auto *listener : _delegates) {\n    listener->syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e);\n  }\n}\n\nvoid ProxyErrorListener::reportAmbiguity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n  bool exact, const antlrcpp::BitSet &ambigAlts, atn::ATNConfigSet *configs) {\n  for (auto *listener : _delegates) {\n    listener->reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs);\n  }\n}\n\nvoid ProxyErrorListener::reportAttemptingFullContext(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex,\n  size_t stopIndex, const antlrcpp::BitSet &conflictingAlts, atn::ATNConfigSet *configs) {\n  for (auto *listener : _delegates) {\n    listener->reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs);\n  }\n}\n\nvoid ProxyErrorListener::reportContextSensitivity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n  size_t prediction, atn::ATNConfigSet *configs) {\n  for (auto *listener : _delegates) {\n    listener->reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs);\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/ProxyErrorListener.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"ANTLRErrorListener.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"Exceptions.h\"\n\nnamespace antlr4 {\n\n  /// This implementation of ANTLRErrorListener dispatches all calls to a\n  /// collection of delegate listeners. This reduces the effort required to support multiple\n  /// listeners.\n  class ANTLR4CPP_PUBLIC ProxyErrorListener : public ANTLRErrorListener {\n  private:\n    std::set<ANTLRErrorListener *> _delegates; // Not owned.\n\n  public:\n    void addErrorListener(ANTLRErrorListener *listener);\n    void removeErrorListener(ANTLRErrorListener *listener);\n    void removeErrorListeners();\n\n    void syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line, size_t charPositionInLine,\n                     const std::string &msg, std::exception_ptr e) override;\n\n    void reportAmbiguity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex, bool exact,\n                                 const antlrcpp::BitSet &ambigAlts, atn::ATNConfigSet *configs) override;\n\n    void reportAttemptingFullContext(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n      const antlrcpp::BitSet &conflictingAlts, atn::ATNConfigSet *configs) override;\n\n    void reportContextSensitivity(Parser *recognizer, const dfa::DFA &dfa, size_t startIndex, size_t stopIndex,\n                                          size_t prediction, atn::ATNConfigSet *configs) override;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RecognitionException.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/ATN.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"Recognizer.h\"\n#include \"ParserRuleContext.h\"\n#include \"misc/IntervalSet.h\"\n\n#include \"RecognitionException.h\"\n\nusing namespace antlr4;\n\nRecognitionException::RecognitionException(Recognizer *recognizer, IntStream *input, ParserRuleContext *ctx,\n                                           Token *offendingToken)\n  : RecognitionException(\"\", recognizer, input, ctx, offendingToken) {\n}\n\nRecognitionException::RecognitionException(const std::string &message, Recognizer *recognizer, IntStream *input,\n                                           ParserRuleContext *ctx, Token *offendingToken)\n  : RuntimeException(message), _recognizer(recognizer), _input(input), _ctx(ctx), _offendingToken(offendingToken) {\n  InitializeInstanceFields();\n  if (recognizer != nullptr) {\n    _offendingState = recognizer->getState();\n  }\n}\n\nRecognitionException::~RecognitionException() {\n}\n\nsize_t RecognitionException::getOffendingState() const {\n  return _offendingState;\n}\n\nvoid RecognitionException::setOffendingState(size_t offendingState) {\n  _offendingState = offendingState;\n}\n\nmisc::IntervalSet RecognitionException::getExpectedTokens() const {\n  if (_recognizer) {\n    return _recognizer->getATN().getExpectedTokens(_offendingState, _ctx);\n  }\n  return misc::IntervalSet::EMPTY_SET;\n}\n\nRuleContext* RecognitionException::getCtx() const {\n  return _ctx;\n}\n\nIntStream* RecognitionException::getInputStream() const {\n  return _input;\n}\n\nToken* RecognitionException::getOffendingToken() const {\n  return _offendingToken;\n}\n\nRecognizer* RecognitionException::getRecognizer() const {\n  return _recognizer;\n}\n\nvoid RecognitionException::InitializeInstanceFields() {\n  _offendingState = INVALID_INDEX;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RecognitionException.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/IntervalSet.h\"\n#include \"Token.h\"\n#include \"Exceptions.h\"\n\nnamespace antlr4 {\n\n  /// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n  /// 3 kinds of errors: prediction errors, failed predicate errors, and\n  /// mismatched input errors. In each case, the parser knows where it is\n  /// in the input, where it is in the ATN, the rule invocation stack,\n  /// and what kind of problem occurred.\n  class ANTLR4CPP_PUBLIC RecognitionException : public RuntimeException {\n  private:\n    /// The Recognizer where this exception originated.\n    Recognizer *_recognizer;\n    IntStream *_input;\n    ParserRuleContext *_ctx;\n\n    /// The current Token when an error occurred. Since not all streams\n    /// support accessing symbols by index, we have to track the Token\n    /// instance itself.\n    Token *_offendingToken;\n\n    size_t _offendingState;\n\n  public:\n    RecognitionException(Recognizer *recognizer, IntStream *input, ParserRuleContext *ctx,\n                         Token *offendingToken = nullptr);\n    RecognitionException(const std::string &message, Recognizer *recognizer, IntStream *input,\n                         ParserRuleContext *ctx, Token *offendingToken = nullptr);\n    RecognitionException(RecognitionException const&) = default;\n    ~RecognitionException() override;\n    RecognitionException& operator=(RecognitionException const&) = default;\n\n    /// Get the ATN state number the parser was in at the time the error\n    /// occurred. For NoViableAltException and\n    /// LexerNoViableAltException exceptions, this is the\n    /// DecisionState number. For others, it is the state whose outgoing\n    /// edge we couldn't match.\n    ///\n    /// If the state number is not known, this method returns -1.\n    virtual size_t getOffendingState() const;\n\n  protected:\n    void setOffendingState(size_t offendingState);\n\n    /// Gets the set of input symbols which could potentially follow the\n    /// previously matched symbol at the time this exception was thrown.\n    ///\n    /// If the set of expected tokens is not known and could not be computed,\n    /// this method returns an empty set.\n    ///\n    /// @returns The set of token types that could potentially follow the current\n    /// state in the ATN, or an empty set if the information is not available.\n  public:\n    virtual misc::IntervalSet getExpectedTokens() const;\n\n    /// <summary>\n    /// Gets the <seealso cref=\"RuleContext\"/> at the time this exception was thrown.\n    /// <p/>\n    /// If the context is not available, this method returns {@code null}.\n    /// </summary>\n    /// <returns> The <seealso cref=\"RuleContext\"/> at the time this exception was thrown.\n    /// If the context is not available, this method returns {@code null}. </returns>\n    virtual RuleContext* getCtx() const;\n\n    /// <summary>\n    /// Gets the input stream which is the symbol source for the recognizer where\n    /// this exception was thrown.\n    /// <p/>\n    /// If the input stream is not available, this method returns {@code null}.\n    /// </summary>\n    /// <returns> The input stream which is the symbol source for the recognizer\n    /// where this exception was thrown, or {@code null} if the stream is not\n    /// available. </returns>\n    virtual IntStream* getInputStream() const;\n\n    virtual Token* getOffendingToken() const;\n\n    /// <summary>\n    /// Gets the <seealso cref=\"Recognizer\"/> where this exception occurred.\n    /// <p/>\n    /// If the recognizer is not available, this method returns {@code null}.\n    /// </summary>\n    /// <returns> The recognizer where this exception occurred, or {@code null} if\n    /// the recognizer is not available. </returns>\n    virtual Recognizer* getRecognizer() const;\n\n  private:\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Recognizer.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string_view>\n#include <map>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"ConsoleErrorListener.h\"\n#include \"ANTLRErrorListener.h\"\n#include \"atn/ATNState.h\"\n#include \"RecognitionException.h\"\n#include \"support/CPPUtils.h\"\n#include \"Token.h\"\n#include \"atn/ATN.h\"\n#include \"atn/ATNSimulator.h\"\n#include \"support/CPPUtils.h\"\n#include \"support/StringUtils.h\"\n\n#include \"Vocabulary.h\"\n\n#include \"Recognizer.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::internal;\n\nstd::map<const dfa::Vocabulary*, std::map<std::string_view, size_t>> Recognizer::_tokenTypeMapCache;\nstd::map<std::vector<std::string>, std::map<std::string, size_t>> Recognizer::_ruleIndexMapCache;\n\nRecognizer::Recognizer() {\n  InitializeInstanceFields();\n  _proxListener.addErrorListener(&ConsoleErrorListener::INSTANCE);\n}\n\nRecognizer::~Recognizer() {\n}\n\nstd::map<std::string_view, size_t> Recognizer::getTokenTypeMap() {\n  const dfa::Vocabulary& vocabulary = getVocabulary();\n\n  UniqueLock<Mutex> lck(_mutex);\n  std::map<std::string_view, size_t> result;\n  auto iterator = _tokenTypeMapCache.find(&vocabulary);\n  if (iterator != _tokenTypeMapCache.end()) {\n    result = iterator->second;\n  } else {\n    for (size_t i = 0; i <= getATN().maxTokenType; ++i) {\n      std::string_view literalName = vocabulary.getLiteralName(i);\n      if (!literalName.empty()) {\n        result[literalName] = i;\n      }\n\n      std::string_view symbolicName = vocabulary.getSymbolicName(i);\n      if (!symbolicName.empty()) {\n        result[symbolicName] = i;\n      }\n    }\n    result[\"EOF\"] = EOF;\n    _tokenTypeMapCache[&vocabulary] = result;\n  }\n\n  return result;\n}\n\nstd::map<std::string, size_t> Recognizer::getRuleIndexMap() {\n  const std::vector<std::string>& ruleNames = getRuleNames();\n  if (ruleNames.empty()) {\n    throw \"The current recognizer does not provide a list of rule names.\";\n  }\n\n  UniqueLock<Mutex> lck(_mutex);\n  std::map<std::string, size_t> result;\n  auto iterator = _ruleIndexMapCache.find(ruleNames);\n  if (iterator != _ruleIndexMapCache.end()) {\n    result = iterator->second;\n  } else {\n    result = antlrcpp::toMap(ruleNames);\n    _ruleIndexMapCache[ruleNames] = result;\n  }\n  return result;\n}\n\nsize_t Recognizer::getTokenType(std::string_view tokenName) {\n  const std::map<std::string_view, size_t> &map = getTokenTypeMap();\n  auto iterator = map.find(tokenName);\n  if (iterator == map.end())\n    return Token::INVALID_TYPE;\n\n  return iterator->second;\n}\n\nvoid Recognizer::setInterpreter(atn::ATNSimulator *interpreter) {\n  // Usually the interpreter is set by the descendant (lexer or parser (simulator), but can also be exchanged\n  // by the profiling ATN simulator.\n  delete _interpreter;\n  _interpreter = interpreter;\n}\n\nstd::string Recognizer::getErrorHeader(RecognitionException *e) {\n  // We're having issues with cross header dependencies, these two classes will need to be\n  // rewritten to remove that.\n  size_t line = e->getOffendingToken()->getLine();\n  size_t charPositionInLine = e->getOffendingToken()->getCharPositionInLine();\n  return std::string(\"line \") + std::to_string(line) + \":\" + std::to_string(charPositionInLine);\n\n}\n\nstd::string Recognizer::getTokenErrorDisplay(Token *t) {\n  if (t == nullptr) {\n    return \"<no Token>\";\n  }\n  std::string s = t->getText();\n  if (s == \"\") {\n    if (t->getType() == EOF) {\n      s = \"<EOF>\";\n    } else {\n      s = std::string(\"<\") + std::to_string(t->getType()) + std::string(\">\");\n    }\n  }\n\n  std::string result;\n  result.reserve(s.size() + 2);\n  result.push_back('\\'');\n  antlrcpp::escapeWhitespace(result, s);\n  result.push_back('\\'');\n  result.shrink_to_fit();\n  return result;\n}\n\nvoid Recognizer::addErrorListener(ANTLRErrorListener *listener) {\n  _proxListener.addErrorListener(listener);\n}\n\nvoid Recognizer::removeErrorListener(ANTLRErrorListener *listener) {\n  _proxListener.removeErrorListener(listener);\n}\n\nvoid Recognizer::removeErrorListeners() {\n  _proxListener.removeErrorListeners();\n}\n\nProxyErrorListener& Recognizer::getErrorListenerDispatch() {\n  return _proxListener;\n}\n\nbool Recognizer::sempred(RuleContext * /*localctx*/, size_t /*ruleIndex*/, size_t /*actionIndex*/) {\n  return true;\n}\n\nbool Recognizer::precpred(RuleContext * /*localctx*/, int /*precedence*/) {\n  return true;\n}\n\nvoid Recognizer::action(RuleContext * /*localctx*/, size_t /*ruleIndex*/, size_t /*actionIndex*/) {\n}\n\nvoid Recognizer::InitializeInstanceFields() {\n  _stateNumber = ATNState::INVALID_STATE_NUMBER;\n  _interpreter = nullptr;\n}\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Recognizer.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string_view>\n#include <limits>\n#include <map>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"ProxyErrorListener.h\"\n#include \"ANTLRErrorListener.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"support/Casts.h\"\n#include \"atn/SerializedATNView.h\"\n#include \"internal/Synchronization.h\"\n\nnamespace antlr4 {\n\n  class ANTLR4CPP_PUBLIC Recognizer {\n  public:\n    static constexpr size_t EOF = std::numeric_limits<size_t>::max();\n\n    Recognizer();\n    Recognizer(Recognizer const&) = delete;\n    virtual ~Recognizer();\n\n    Recognizer& operator=(Recognizer const&) = delete;\n\n    virtual std::vector<std::string> const& getRuleNames() const = 0;\n\n    /**\n     * Get the vocabulary used by the recognizer.\n     *\n     * @return A {@link Vocabulary} instance providing information about the\n     * vocabulary used by the grammar.\n     */\n    virtual dfa::Vocabulary const& getVocabulary() const = 0;\n\n    /// <summary>\n    /// Get a map from token names to token types.\n    /// <p/>\n    /// Used for XPath and tree pattern compilation.\n    /// </summary>\n    virtual std::map<std::string_view, size_t> getTokenTypeMap();\n\n    /// <summary>\n    /// Get a map from rule names to rule indexes.\n    /// <p/>\n    /// Used for XPath and tree pattern compilation.\n    /// </summary>\n    virtual std::map<std::string, size_t> getRuleIndexMap();\n\n    virtual size_t getTokenType(std::string_view tokenName);\n\n    /// <summary>\n    /// If this recognizer was generated, it will have a serialized ATN\n    /// representation of the grammar.\n    /// <p/>\n    /// For interpreters, we don't know their serialized ATN despite having\n    /// created the interpreter from it.\n    /// </summary>\n    virtual atn::SerializedATNView getSerializedATN() const {\n      throw \"there is no serialized ATN\";\n    }\n\n    /// <summary>\n    /// For debugging and other purposes, might want the grammar name.\n    ///  Have ANTLR generate an implementation for this method.\n    /// </summary>\n    virtual std::string getGrammarFileName() const = 0;\n\n    /// Get the ATN interpreter (in fact one of it's descendants) used by the recognizer for prediction.\n    /// @returns The ATN interpreter used by the recognizer for prediction.\n    template <class T>\n    T* getInterpreter() const {\n      return antlrcpp::downCast<T *>(_interpreter);\n    }\n\n    /**\n     * Set the ATN interpreter used by the recognizer for prediction.\n     *\n     * @param interpreter The ATN interpreter used by the recognizer for\n     * prediction.\n     */\n    void setInterpreter(atn::ATNSimulator *interpreter);\n\n    /// What is the error header, normally line/character position information?\n    virtual std::string getErrorHeader(RecognitionException *e);\n\n    /** How should a token be displayed in an error message? The default\n     *  is to display just the text, but during development you might\n     *  want to have a lot of information spit out.  Override in that case\n     *  to use t.toString() (which, for CommonToken, dumps everything about\n     *  the token). This is better than forcing you to override a method in\n     *  your token objects because you don't have to go modify your lexer\n     *  so that it creates a new Java type.\n     *\n     * @deprecated This method is not called by the ANTLR 4 Runtime. Specific\n     * implementations of {@link ANTLRErrorStrategy} may provide a similar\n     * feature when necessary. For example, see\n     * {@link DefaultErrorStrategy#getTokenErrorDisplay}.\n     */\n    virtual std::string getTokenErrorDisplay(Token *t);\n\n    /// <exception cref=\"NullPointerException\"> if {@code listener} is {@code null}. </exception>\n    virtual void addErrorListener(ANTLRErrorListener *listener);\n\n    virtual void removeErrorListener(ANTLRErrorListener *listener);\n\n    virtual void removeErrorListeners();\n\n    virtual ProxyErrorListener& getErrorListenerDispatch();\n\n    // subclass needs to override these if there are sempreds or actions\n    // that the ATN interp needs to execute\n    virtual bool sempred(RuleContext *localctx, size_t ruleIndex, size_t actionIndex);\n\n    virtual bool precpred(RuleContext *localctx, int precedence);\n\n    virtual void action(RuleContext *localctx, size_t ruleIndex, size_t actionIndex);\n\n    size_t getState() const { return _stateNumber; }\n\n    // Get the ATN used by the recognizer for prediction.\n    virtual const atn::ATN& getATN() const = 0;\n\n    /// <summary>\n    /// Indicate that the recognizer has changed internal state that is\n    ///  consistent with the ATN state passed in.  This way we always know\n    ///  where we are in the ATN as the parser goes along. The rule\n    ///  context objects form a stack that lets us see the stack of\n    ///  invoking rules. Combine this and we have complete ATN\n    ///  configuration information.\n    /// </summary>\n    void setState(size_t atnState) { _stateNumber = atnState; }\n\n    virtual IntStream* getInputStream() = 0;\n\n    virtual void setInputStream(IntStream *input) = 0;\n\n    virtual TokenFactory<CommonToken>* getTokenFactory() = 0;\n\n    template<typename T1>\n    void setTokenFactory(TokenFactory<T1> *input);\n\n  protected:\n    atn::ATNSimulator *_interpreter; // Set and deleted in descendants (or the profiler).\n\n    // Mutex to manage synchronized access for multithreading.\n    internal::Mutex _mutex;\n\n  private:\n    static std::map<const dfa::Vocabulary*, std::map<std::string_view, size_t>> _tokenTypeMapCache;\n    static std::map<std::vector<std::string>, std::map<std::string, size_t>> _ruleIndexMapCache;\n\n    ProxyErrorListener _proxListener; // Manages a collection of listeners.\n\n    size_t _stateNumber;\n\n    void InitializeInstanceFields();\n\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RuleContext.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"tree/Trees.h\"\n#include \"tree/ParseTreeType.h\"\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"Parser.h\"\n#include \"atn/ATN.h\"\n#include \"atn/ATNState.h\"\n#include \"tree/ParseTreeVisitor.h\"\n\n#include \"RuleContext.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::tree;\n\nRuleContext::RuleContext() : ParseTree(ParseTreeType::RULE) {\n  InitializeInstanceFields();\n}\n\nRuleContext::RuleContext(RuleContext *parent_, size_t invokingState_) : ParseTree(ParseTreeType::RULE) {\n  InitializeInstanceFields();\n  this->parent = parent_;\n  this->invokingState = invokingState_;\n}\n\nint RuleContext::depth() {\n  int n = 1;\n  RuleContext *p = this;\n  while (true) {\n    if (p->parent == nullptr)\n      break;\n    p = static_cast<RuleContext *>(p->parent);\n    n++;\n  }\n  return n;\n}\n\nbool RuleContext::isEmpty() {\n  return invokingState == ATNState::INVALID_STATE_NUMBER;\n}\n\nmisc::Interval RuleContext::getSourceInterval() {\n  return misc::Interval::INVALID;\n}\n\nstd::string RuleContext::getText() {\n  if (children.empty()) {\n    return \"\";\n  }\n\n  std::stringstream ss;\n  for (size_t i = 0; i < children.size(); i++) {\n    ParseTree *tree = children[i];\n    if (tree != nullptr)\n      ss << tree->getText();\n  }\n\n  return ss.str();\n}\n\nsize_t RuleContext::getRuleIndex() const {\n  return INVALID_INDEX;\n}\n\nsize_t RuleContext::getAltNumber() const {\n  return atn::ATN::INVALID_ALT_NUMBER;\n}\n\nvoid RuleContext::setAltNumber(size_t /*altNumber*/) {\n}\n\nstd::any RuleContext::accept(tree::ParseTreeVisitor *visitor) {\n  return visitor->visitChildren(this);\n}\n\nstd::string RuleContext::toStringTree(Parser *recog, bool pretty) {\n  return tree::Trees::toStringTree(this, recog, pretty);\n}\n\nstd::string RuleContext::toStringTree(std::vector<std::string> &ruleNames, bool pretty) {\n  return tree::Trees::toStringTree(this, ruleNames, pretty);\n}\n\nstd::string RuleContext::toStringTree(bool pretty) {\n  return toStringTree(nullptr, pretty);\n}\n\n\nstd::string RuleContext::toString(const std::vector<std::string> &ruleNames) {\n  return toString(ruleNames, nullptr);\n}\n\n\nstd::string RuleContext::toString(const std::vector<std::string> &ruleNames, RuleContext *stop) {\n  std::stringstream ss;\n\n  RuleContext *currentParent = this;\n  ss << \"[\";\n  while (currentParent != stop) {\n    if (ruleNames.empty()) {\n      if (!currentParent->isEmpty()) {\n        ss << currentParent->invokingState;\n      }\n    } else {\n      size_t ruleIndex = currentParent->getRuleIndex();\n\n      std::string ruleName = (ruleIndex < ruleNames.size()) ? ruleNames[ruleIndex] : std::to_string(ruleIndex);\n      ss << ruleName;\n    }\n\n    if (currentParent->parent == nullptr) // No parent anymore.\n      break;\n    currentParent = static_cast<RuleContext *>(currentParent->parent);\n    if (!ruleNames.empty() || !currentParent->isEmpty()) {\n      ss << \" \";\n    }\n  }\n\n  ss << \"]\";\n\n  return ss.str();\n}\n\nstd::string RuleContext::toString() {\n  return toString(nullptr);\n}\n\nstd::string RuleContext::toString(Recognizer *recog) {\n  return toString(recog, &ParserRuleContext::EMPTY);\n}\n\nstd::string RuleContext::toString(Recognizer *recog, RuleContext *stop) {\n  if (recog == nullptr)\n    return toString(std::vector<std::string>(), stop); // Don't use an initializer {} here or we end up calling ourselve recursivly.\n  return toString(recog->getRuleNames(), stop);\n}\n\nvoid RuleContext::InitializeInstanceFields() {\n  invokingState = INVALID_INDEX;\n}\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RuleContext.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"tree/ParseTreeType.h\"\n#include \"misc/Interval.h\"\n#include \"tree/ParseTree.h\"\n\nnamespace antlr4 {\n\n  /** A rule context is a record of a single rule invocation.\n   *\n   *  We form a stack of these context objects using the parent\n   *  pointer. A parent pointer of null indicates that the current\n   *  context is the bottom of the stack. The ParserRuleContext subclass\n   *  as a children list so that we can turn this data structure into a\n   *  tree.\n   *\n   *  The root node always has a null pointer and invokingState of -1.\n   *\n   *  Upon entry to parsing, the first invoked rule function creates a\n   *  context object (asubclass specialized for that rule such as\n   *  SContext) and makes it the root of a parse tree, recorded by field\n   *  Parser._ctx.\n   *\n   *  public final SContext s() throws RecognitionException {\n   *      SContext _localctx = new SContext(_ctx, getState()); <-- create new node\n   *      enterRule(_localctx, 0, RULE_s);                     <-- push it\n   *      ...\n   *      exitRule();                                          <-- pop back to _localctx\n   *      return _localctx;\n   *  }\n   *\n   *  A subsequent rule invocation of r from the start rule s pushes a\n   *  new context object for r whose parent points at s and use invoking\n   *  state is the state with r emanating as edge label.\n   *\n   *  The invokingState fields from a context object to the root\n   *  together form a stack of rule indication states where the root\n   *  (bottom of the stack) has a -1 sentinel value. If we invoke start\n   *  symbol s then call r1, which calls r2, the  would look like\n   *  this:\n   *\n   *     SContext[-1]   <- root node (bottom of the stack)\n   *     R1Context[p]   <- p in rule s called r1\n   *     R2Context[q]   <- q in rule r1 called r2\n   *\n   *  So the top of the stack, _ctx, represents a call to the current\n   *  rule and it holds the return address from another rule that invoke\n   *  to this rule. To invoke a rule, we must always have a current context.\n   *\n   *  The parent contexts are useful for computing lookahead sets and\n   *  getting error information.\n   *\n   *  These objects are used during parsing and prediction.\n   *  For the special case of parsers, we use the subclass\n   *  ParserRuleContext.\n   *\n   *  @see ParserRuleContext\n   */\n  class ANTLR4CPP_PUBLIC RuleContext : public tree::ParseTree {\n  public:\n    static bool is(const tree::ParseTree &parseTree) { return parseTree.getTreeType() == tree::ParseTreeType::RULE; }\n\n    static bool is(const tree::ParseTree *parseTree) { return parseTree != nullptr && is(*parseTree); }\n\n    /// What state invoked the rule associated with this context?\n    /// The \"return address\" is the followState of invokingState\n    /// If parent is null, this should be -1 and this context object represents the start rule.\n    size_t invokingState;\n\n    RuleContext();\n    RuleContext(RuleContext *parent, size_t invokingState);\n\n    virtual int depth();\n\n    /// A context is empty if there is no invoking state; meaning nobody called current context.\n    virtual bool isEmpty();\n\n    // satisfy the ParseTree / SyntaxTree interface\n\n    misc::Interval getSourceInterval() override;\n\n    std::string getText() override;\n\n    virtual size_t getRuleIndex() const;\n\n    /** For rule associated with this parse tree internal node, return\n     *  the outer alternative number used to match the input. Default\n     *  implementation does not compute nor store this alt num. Create\n     *  a subclass of ParserRuleContext with backing field and set\n     *  option contextSuperClass.\n     *  to set it.\n     *\n     *  @since 4.5.3\n     */\n    virtual size_t getAltNumber() const;\n\n    /** Set the outer alternative number for this context node. Default\n     *  implementation does nothing to avoid backing field overhead for\n     *  trees that don't need it.  Create\n     *  a subclass of ParserRuleContext with backing field and set\n     *  option contextSuperClass.\n     *\n     *  @since 4.5.3\n     */\n    virtual void setAltNumber(size_t altNumber);\n\n    std::any accept(tree::ParseTreeVisitor *visitor) override;\n\n    /// <summary>\n    /// Print out a whole tree, not just a node, in LISP format\n    ///  (root child1 .. childN). Print just a node if this is a leaf.\n    ///  We have to know the recognizer so we can get rule names.\n    /// </summary>\n    std::string toStringTree(Parser *recog, bool pretty = false) override;\n\n    /// <summary>\n    /// Print out a whole tree, not just a node, in LISP format\n    ///  (root child1 .. childN). Print just a node if this is a leaf.\n    /// </summary>\n    virtual std::string toStringTree(std::vector<std::string> &ruleNames, bool pretty = false);\n\n    std::string toStringTree(bool pretty = false) override;\n    std::string toString() override;\n    std::string toString(Recognizer *recog);\n    std::string toString(const std::vector<std::string> &ruleNames);\n\n    // recog null unless ParserRuleContext, in which case we use subclass toString(...)\n    std::string toString(Recognizer *recog, RuleContext *stop);\n\n    virtual std::string toString(const std::vector<std::string> &ruleNames, RuleContext *stop);\n\n  private:\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RuleContextWithAltNum.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/ATN.h\"\n\n#include \"RuleContextWithAltNum.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nRuleContextWithAltNum::RuleContextWithAltNum() : ParserRuleContext() {\n  altNum = ATN::INVALID_ALT_NUMBER;\n}\n\nRuleContextWithAltNum::RuleContextWithAltNum(ParserRuleContext *parent, int invokingStateNumber)\n  : ParserRuleContext(parent, invokingStateNumber) {\n}\n\nsize_t RuleContextWithAltNum::getAltNumber() const {\n  return altNum;\n}\n\nvoid RuleContextWithAltNum::setAltNumber(size_t number) {\n  altNum = number;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RuleContextWithAltNum.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"ParserRuleContext.h\"\n\nnamespace antlr4 {\n\n  /// A handy class for use with\n  ///\n  ///  options {contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum;}\n  ///\n  ///  that provides a backing field / impl for the outer alternative number\n  ///  matched for an internal parse tree node.\n  ///\n  ///  I'm only putting into Java runtime as I'm certain I'm the only one that\n  ///  will really every use this.\n  class ANTLR4CPP_PUBLIC RuleContextWithAltNum : public ParserRuleContext {\n  public:\n    size_t altNum = 0;\n\n    RuleContextWithAltNum();\n    RuleContextWithAltNum(ParserRuleContext *parent, int invokingStateNumber);\n\n    size_t getAltNumber() const override;\n    void setAltNumber(size_t altNum) override;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RuntimeMetaData.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"RuntimeMetaData.h\"\n#include \"Version.h\"\n\nusing namespace antlr4;\n\nconst std::string RuntimeMetaData::VERSION = ANTLRCPP_VERSION_STRING;\n\nstd::string RuntimeMetaData::getRuntimeVersion() {\n  return VERSION;\n}\n\nvoid RuntimeMetaData::checkVersion(const std::string &generatingToolVersion, const std::string &compileTimeVersion) {\n  std::string runtimeVersion = VERSION;\n  bool runtimeConflictsWithGeneratingTool = false;\n  bool runtimeConflictsWithCompileTimeTool = false;\n\n  if (generatingToolVersion != \"\") {\n    runtimeConflictsWithGeneratingTool = runtimeVersion != generatingToolVersion\n      && getMajorMinorVersion(runtimeVersion) != getMajorMinorVersion(generatingToolVersion);\n  }\n\n  runtimeConflictsWithCompileTimeTool = runtimeVersion != compileTimeVersion\n    && getMajorMinorVersion(runtimeVersion) != getMajorMinorVersion(compileTimeVersion);\n\n  if (runtimeConflictsWithGeneratingTool) {\n    std::cerr << \"ANTLR Tool version \" << generatingToolVersion << \" used for code generation does not match \"\n      \"the current runtime version \" << runtimeVersion << std::endl;\n  }\n  if (runtimeConflictsWithCompileTimeTool) {\n    std::cerr << \"ANTLR Runtime version \" << compileTimeVersion << \" used for parser compilation does not match \"\n      \"the current runtime version \" << runtimeVersion << std::endl;\n  }\n}\n\nstd::string RuntimeMetaData::getMajorMinorVersion(const std::string &version) {\n  size_t firstDot = version.find('.');\n  size_t secondDot = firstDot != std::string::npos ? version.find('.', firstDot + 1) : std::string::npos;\n  size_t firstDash = version.find('-');\n  size_t referenceLength = version.size();\n  if (secondDot != std::string::npos) {\n    referenceLength = std::min(referenceLength, secondDot);\n  }\n\n  if (firstDash != std::string::npos) {\n    referenceLength = std::min(referenceLength, firstDash);\n  }\n\n  return version.substr(0, referenceLength);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/RuntimeMetaData.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// This class provides access to the current version of the ANTLR 4 runtime\n  /// library as compile-time and runtime constants, along with methods for\n  /// checking for matching version numbers and notifying listeners in the case\n  /// where a version mismatch is detected.\n  ///\n  /// <para>\n  /// The runtime version information is provided by <seealso cref=\"#VERSION\"/> and\n  /// <seealso cref=\"#getRuntimeVersion()\"/>. Detailed information about these values is\n  /// provided in the documentation for each member.</para>\n  ///\n  /// <para>\n  /// The runtime version check is implemented by <seealso cref=\"#checkVersion\"/>. Detailed\n  /// information about incorporating this call into user code, as well as its use\n  /// in generated code, is provided in the documentation for the method.</para>\n  ///\n  /// <para>\n  /// Version strings x.y and x.y.z are considered \"compatible\" and no error\n  /// would be generated. Likewise, version strings x.y-SNAPSHOT and x.y.z are\n  /// considered \"compatible\" because the major and minor components x.y\n  /// are the same in each.</para>\n  ///\n  /// <para>\n  /// To trap any error messages issued by this code, use System.setErr()\n  /// in your main() startup code.\n  /// </para>\n  ///\n  /// @since 4.3\n  /// </summary>\n  class ANTLR4CPP_PUBLIC RuntimeMetaData {\n  public:\n    /// A compile-time constant containing the current version of the ANTLR 4\n    /// runtime library.\n    ///\n    /// <para>\n    /// This compile-time constant value allows generated parsers and other\n    /// libraries to include a literal reference to the version of the ANTLR 4\n    /// runtime library the code was compiled against. At each release, we\n    /// change this value.</para>\n    ///\n    /// <para>Version numbers are assumed to have the form\n    ///\n    /// <em>major</em>.<em>minor</em>.<em>patch</em>.<em>revision</em>-<em>suffix</em>,\n    ///\n    /// with the individual components defined as follows.</para>\n    ///\n    /// <ul>\n    /// <li><em>major</em> is a required non-negative integer, and is equal to\n    /// {@code 4} for ANTLR 4.</li>\n    /// <li><em>minor</em> is a required non-negative integer.</li>\n    /// <li><em>patch</em> is an optional non-negative integer. When\n    /// <em>patch</em> is omitted, the {@code .} (dot) appearing before it is\n    /// also omitted.</li>\n    /// <li><em>revision</em> is an optional non-negative integer, and may only\n    /// be included when <em>patch</em> is also included. When <em>revision</em>\n    /// is omitted, the {@code .} (dot) appearing before it is also omitted.</li>\n    /// <li><em>suffix</em> is an optional string. When <em>suffix</em> is\n    /// omitted, the {@code -} (hyphen-minus) appearing before it is also\n    /// omitted.</li>\n    /// </ul>\n    static const std::string VERSION;\n\n    /// <summary>\n    /// Gets the currently executing version of the ANTLR 4 runtime library.\n    ///\n    /// <para>\n    /// This method provides runtime access to the <seealso cref=\"#VERSION\"/> field, as\n    /// opposed to directly referencing the field as a compile-time constant.</para>\n    /// </summary>\n    /// <returns> The currently executing version of the ANTLR 4 library </returns>\n\n    static std::string getRuntimeVersion();\n\n    /// <summary>\n    /// This method provides the ability to detect mismatches between the version\n    /// of ANTLR 4 used to generate a parser, the version of the ANTLR runtime a\n    /// parser was compiled against, and the version of the ANTLR runtime which\n    /// is currently executing.\n    ///\n    /// <para>\n    /// The version check is designed to detect the following two specific\n    /// scenarios.</para>\n    ///\n    /// <ul>\n    /// <li>The ANTLR Tool version used for code generation does not match the\n    /// currently executing runtime version.</li>\n    /// <li>The ANTLR Runtime version referenced at the time a parser was\n    /// compiled does not match the currently executing runtime version.</li>\n    /// </ul>\n    ///\n    /// <para>\n    /// Starting with ANTLR 4.3, the code generator emits a call to this method\n    /// using two constants in each generated lexer and parser: a hard-coded\n    /// constant indicating the version of the tool used to generate the parser\n    /// and a reference to the compile-time constant <seealso cref=\"#VERSION\"/>. At\n    /// runtime, this method is called during the initialization of the generated\n    /// parser to detect mismatched versions, and notify the registered listeners\n    /// prior to creating instances of the parser.</para>\n    ///\n    /// <para>\n    /// This method does not perform any detection or filtering of semantic\n    /// changes between tool and runtime versions. It simply checks for a\n    /// version match and emits an error to stderr if a difference\n    /// is detected.</para>\n    ///\n    /// <para>\n    /// Note that some breaking changes between releases could result in other\n    /// types of runtime exceptions, such as a <seealso cref=\"LinkageError\"/>, prior to\n    /// calling this method. In these cases, the underlying version mismatch will\n    /// not be reported here. This method is primarily intended to\n    /// notify users of potential semantic changes between releases that do not\n    /// result in binary compatibility problems which would be detected by the\n    /// class loader. As with semantic changes, changes that break binary\n    /// compatibility between releases are mentioned in the release notes\n    /// accompanying the affected release.</para>\n    ///\n    /// <para>\n    /// <strong>Additional note for target developers:</strong> The version check\n    /// implemented by this class is designed to address specific compatibility\n    /// concerns that may arise during the execution of Java applications. Other\n    /// targets should consider the implementation of this method in the context\n    /// of that target's known execution environment, which may or may not\n    /// resemble the design provided for the Java target.</para>\n    /// </summary>\n    /// <param name=\"generatingToolVersion\"> The version of the tool used to generate a parser.\n    /// This value may be null when called from user code that was not generated\n    /// by, and does not reference, the ANTLR 4 Tool itself. </param>\n    /// <param name=\"compileTimeVersion\"> The version of the runtime the parser was\n    /// compiled against. This should always be passed using a direct reference\n    /// to <seealso cref=\"#VERSION\"/>. </param>\n    static void checkVersion(const std::string &generatingToolVersion, const std::string &compileTimeVersion);\n\n    /// <summary>\n    /// Gets the major and minor version numbers from a version string. For\n    /// details about the syntax of the input {@code version}.\n    /// E.g., from x.y.z return x.y.\n    /// </summary>\n    /// <param name=\"version\"> The complete version string. </param>\n    /// <returns> A string of the form <em>major</em>.<em>minor</em> containing\n    /// only the major and minor components of the version string. </returns>\n    static std::string getMajorMinorVersion(const std::string &version);\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Token.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"Token.h\"\n\nantlr4::Token::~Token() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Token.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <limits>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"IntStream.h\"\n\nnamespace antlr4 {\n\n  /// A token has properties: text, type, line, character position in the line\n  /// (so we can ignore tabs), token channel, index, and source from which\n  /// we obtained this token.\n  class ANTLR4CPP_PUBLIC Token {\n  public:\n    static constexpr size_t INVALID_TYPE = 0;\n\n    /// During lookahead operations, this \"token\" signifies we hit rule end ATN state\n    /// and did not follow it despite needing to.\n    static constexpr size_t EPSILON = std::numeric_limits<size_t>::max() - 1;\n    static constexpr size_t MIN_USER_TOKEN_TYPE = 1;\n    static constexpr size_t EOF = IntStream::EOF;\n\n    virtual ~Token();\n\n    /// All tokens go to the parser (unless skip() is called in that rule)\n    /// on a particular \"channel\".  The parser tunes to a particular channel\n    /// so that whitespace etc... can go to the parser on a \"hidden\" channel.\n    static constexpr size_t DEFAULT_CHANNEL = 0;\n\n    /// Anything on different channel than DEFAULT_CHANNEL is not parsed\n    /// by parser.\n    static constexpr size_t HIDDEN_CHANNEL = 1;\n\n    /**\n     * This is the minimum constant value which can be assigned to a\n     * user-defined token channel.\n     *\n     * <p>\n     * The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are\n     * assigned to the predefined channels {@link #DEFAULT_CHANNEL} and\n     * {@link #HIDDEN_CHANNEL}.</p>\n     *\n     * @see Token#getChannel()\n     */\n    static constexpr size_t MIN_USER_CHANNEL_VALUE = 2;\n\n    /// Get the text of the token.\n    virtual std::string getText() const = 0;\n\n    /// Get the token type of the token\n    virtual size_t getType() const = 0;\n\n    /// The line number on which the 1st character of this token was matched,  line=1..n\n    virtual size_t getLine() const = 0;\n\n    /// The index of the first character of this token relative to the\n    /// beginning of the line at which it occurs, 0..n-1\n    virtual size_t getCharPositionInLine() const = 0;\n\n    /// Return the channel this token. Each token can arrive at the parser\n    /// on a different channel, but the parser only \"tunes\" to a single channel.\n    /// The parser ignores everything not on DEFAULT_CHANNEL.\n    virtual size_t getChannel() const = 0;\n\n    /// An index from 0..n-1 of the token object in the input stream.\n    /// This must be valid in order to print token streams and\n    /// use TokenRewriteStream.\n    ///\n    /// Return INVALID_INDEX to indicate that this token was conjured up since\n    /// it doesn't have a valid index.\n    virtual size_t getTokenIndex() const = 0;\n\n    /// The starting character index of the token\n    /// This method is optional; return INVALID_INDEX if not implemented.\n    virtual size_t getStartIndex() const = 0;\n\n    /// The last character index of the token.\n    /// This method is optional; return INVALID_INDEX if not implemented.\n    virtual size_t getStopIndex() const = 0;\n\n    /// Gets the <seealso cref=\"TokenSource\"/> which created this token.\n    virtual TokenSource *getTokenSource() const = 0;\n\n    /// Gets the <seealso cref=\"CharStream\"/> from which this token was derived.\n    virtual CharStream *getInputStream() const = 0;\n\n    virtual std::string toString() const = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/TokenFactory.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\n\n  /// The default mechanism for creating tokens. It's used by default in Lexer and\n  ///  the error handling strategy (to create missing tokens).  Notifying the parser\n  ///  of a new factory means that it notifies it's token source and error strategy.\n  template<typename Symbol>\n  class ANTLR4CPP_PUBLIC TokenFactory {\n  public:\n    virtual ~TokenFactory() {}\n\n    /// This is the method used to create tokens in the lexer and in the\n    /// error handling strategy. If text!=null, than the start and stop positions\n    /// are wiped to -1 in the text override is set in the CommonToken.\n    virtual std::unique_ptr<Symbol> create(std::pair<TokenSource *, CharStream *> source, size_t type, const std::string &text,\n      size_t channel, size_t start, size_t stop, size_t line, size_t charPositionInLine) = 0;\n\n    /// Generically useful\n    virtual std::unique_ptr<Symbol> create(size_t type, const std::string &text) = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/TokenSource.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"TokenSource.h\"\n\nantlr4::TokenSource::~TokenSource() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/TokenSource.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"TokenFactory.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// A source of tokens must provide a sequence of tokens via <seealso cref=\"#nextToken()\"/>\n  /// and also must reveal it's source of characters; <seealso cref=\"CommonToken\"/>'s text is\n  /// computed from a <seealso cref=\"CharStream\"/>; it only store indices into the char\n  /// stream.\n  /// <p/>\n  /// Errors from the lexer are never passed to the parser. Either you want to keep\n  /// going or you do not upon token recognition error. If you do not want to\n  /// continue lexing then you do not want to continue parsing. Just throw an\n  /// exception not under <seealso cref=\"RecognitionException\"/> and Java will naturally toss\n  /// you all the way out of the recognizers. If you want to continue lexing then\n  /// you should not throw an exception to the parser--it has already requested a\n  /// token. Keep lexing until you get a valid one. Just report errors and keep\n  /// going, looking for a valid token.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC TokenSource {\n  public:\n    virtual ~TokenSource();\n\n    /// Return a <seealso cref=\"Token\"/> object from your input stream (usually a\n    /// <seealso cref=\"CharStream\"/>). Do not fail/return upon lexing error; keep chewing\n    /// on the characters until you get a good one; errors are not passed through\n    /// to the parser.\n    virtual std::unique_ptr<Token> nextToken() = 0;\n\n    /// <summary>\n    /// Get the line number for the current position in the input stream. The\n    /// first line in the input is line 1.\n    /// </summary>\n    /// <returns> The line number for the current position in the input stream, or\n    /// 0 if the current token source does not track line numbers. </returns>\n    virtual size_t getLine() const = 0;\n\n    /// <summary>\n    /// Get the index into the current line for the current position in the input\n    /// stream. The first character on a line has position 0.\n    /// </summary>\n    /// <returns> The line number for the current position in the input stream, or\n    /// (sze_t)-1 if the current token source does not track character positions. </returns>\n    virtual size_t getCharPositionInLine() = 0;\n\n    /// <summary>\n    /// Get the <seealso cref=\"CharStream\"/> from which this token source is currently\n    /// providing tokens.\n    /// </summary>\n    /// <returns> The <seealso cref=\"CharStream\"/> associated with the current position in\n    /// the input, or {@code null} if no input stream is available for the token\n    /// source. </returns>\n    virtual CharStream* getInputStream() = 0;\n\n    /// <summary>\n    /// Gets the name of the underlying input source. This method returns a\n    /// non-null, non-empty string. If such a name is not known, this method\n    /// returns <seealso cref=\"IntStream#UNKNOWN_SOURCE_NAME\"/>.\n    /// </summary>\n    virtual std::string getSourceName() = 0;\n\n    /// <summary>\n    /// Set the <seealso cref=\"TokenFactory\"/> this token source should use for creating\n    /// <seealso cref=\"Token\"/> objects from the input.\n    /// </summary>\n    /// <param name=\"factory\"> The <seealso cref=\"TokenFactory\"/> to use for creating tokens. </param>\n    template<typename T1>\n    void setTokenFactory(TokenFactory<T1> * /*factory*/) {}\n\n    /// <summary>\n    /// Gets the <seealso cref=\"TokenFactory\"/> this token source is currently using for\n    /// creating <seealso cref=\"Token\"/> objects from the input.\n    /// </summary>\n    /// <returns> The <seealso cref=\"TokenFactory\"/> currently used by this token source. </returns>\n    virtual TokenFactory<CommonToken>* getTokenFactory() = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/TokenStream.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"TokenStream.h\"\n\nusing namespace antlr4;\n\nTokenStream::~TokenStream() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/TokenStream.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"IntStream.h\"\n\nnamespace antlr4 {\n\n  /// <summary>\n  /// An <seealso cref=\"IntStream\"/> whose symbols are <seealso cref=\"Token\"/> instances.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC TokenStream : public IntStream {\n    /// <summary>\n    /// Get the <seealso cref=\"Token\"/> instance associated with the value returned by\n    /// <seealso cref=\"#LA LA(k)\"/>. This method has the same pre- and post-conditions as\n    /// <seealso cref=\"IntStream#LA\"/>. In addition, when the preconditions of this method\n    /// are met, the return value is non-null and the value of\n    /// {@code LT(k).getType()==LA(k)}.\n    /// </summary>\n    /// <seealso cref= IntStream#LA </seealso>\n  public:\n    ~TokenStream() override;\n\n    virtual Token* LT(ssize_t k) = 0;\n\n    /// <summary>\n    /// Gets the <seealso cref=\"Token\"/> at the specified {@code index} in the stream. When\n    /// the preconditions of this method are met, the return value is non-null.\n    /// <p/>\n    /// The preconditions for this method are the same as the preconditions of\n    /// <seealso cref=\"IntStream#seek\"/>. If the behavior of {@code seek(index)} is\n    /// unspecified for the current state and given {@code index}, then the\n    /// behavior of this method is also unspecified.\n    /// <p/>\n    /// The symbol referred to by {@code index} differs from {@code seek()} only\n    /// in the case of filtering streams where {@code index} lies before the end\n    /// of the stream. Unlike {@code seek()}, this method does not adjust\n    /// {@code index} to point to a non-ignored symbol.\n    /// </summary>\n    /// <exception cref=\"IllegalArgumentException\"> if {code index} is less than 0 </exception>\n    /// <exception cref=\"UnsupportedOperationException\"> if the stream does not support\n    /// retrieving the token at the specified index </exception>\n    virtual Token* get(size_t index) const = 0;\n\n    /// Gets the underlying TokenSource which provides tokens for this stream.\n    virtual TokenSource* getTokenSource() const = 0;\n\n    /// <summary>\n    /// Return the text of all tokens within the specified {@code interval}. This\n    /// method behaves like the following code (including potential exceptions\n    /// for violating preconditions of <seealso cref=\"#get\"/>, but may be optimized by the\n    /// specific implementation.\n    ///\n    /// <pre>\n    /// TokenStream stream = ...;\n    /// String text = \"\";\n    /// for (int i = interval.a; i <= interval.b; i++) {\n    ///   text += stream.get(i).getText();\n    /// }\n    /// </pre>\n    /// </summary>\n    /// <param name=\"interval\"> The interval of tokens within this stream to get text\n    /// for. </param>\n    /// <returns> The text of all tokens within the specified interval in this\n    /// stream.\n    /// </returns>\n    /// <exception cref=\"NullPointerException\"> if {@code interval} is {@code null} </exception>\n    virtual std::string getText(const misc::Interval &interval) = 0;\n\n    /// <summary>\n    /// Return the text of all tokens in the stream. This method behaves like the\n    /// following code, including potential exceptions from the calls to\n    /// <seealso cref=\"IntStream#size\"/> and <seealso cref=\"#getText(Interval)\"/>, but may be\n    /// optimized by the specific implementation.\n    ///\n    /// <pre>\n    /// TokenStream stream = ...;\n    /// String text = stream.getText(new Interval(0, stream.size()));\n    /// </pre>\n    /// </summary>\n    /// <returns> The text of all tokens in the stream. </returns>\n    virtual std::string getText() = 0;\n\n    /// <summary>\n    /// Return the text of all tokens in the source interval of the specified\n    /// context. This method behaves like the following code, including potential\n    /// exceptions from the call to <seealso cref=\"#getText(Interval)\"/>, but may be\n    /// optimized by the specific implementation.\n    /// </p>\n    /// If {@code ctx.getSourceInterval()} does not return a valid interval of\n    /// tokens provided by this stream, the behavior is unspecified.\n    ///\n    /// <pre>\n    /// TokenStream stream = ...;\n    /// String text = stream.getText(ctx.getSourceInterval());\n    /// </pre>\n    /// </summary>\n    /// <param name=\"ctx\"> The context providing the source interval of tokens to get\n    /// text for. </param>\n    /// <returns> The text of all tokens within the source interval of {@code ctx}. </returns>\n    virtual std::string getText(RuleContext *ctx) = 0;\n\n    /// <summary>\n    /// Return the text of all tokens in this stream between {@code start} and\n    /// {@code stop} (inclusive).\n    /// <p/>\n    /// If the specified {@code start} or {@code stop} token was not provided by\n    /// this stream, or if the {@code stop} occurred before the {@code start}\n    /// token, the behavior is unspecified.\n    /// <p/>\n    /// For streams which ensure that the <seealso cref=\"Token#getTokenIndex\"/> method is\n    /// accurate for all of its provided tokens, this method behaves like the\n    /// following code. Other streams may implement this method in other ways\n    /// provided the behavior is consistent with this at a high level.\n    ///\n    /// <pre>\n    /// TokenStream stream = ...;\n    /// String text = \"\";\n    /// for (int i = start.getTokenIndex(); i <= stop.getTokenIndex(); i++) {\n    ///   text += stream.get(i).getText();\n    /// }\n    /// </pre>\n    /// </summary>\n    /// <param name=\"start\"> The first token in the interval to get text for. </param>\n    /// <param name=\"stop\"> The last token in the interval to get text for (inclusive). </param>\n    /// <returns> The text of all tokens lying between the specified {@code start}\n    /// and {@code stop} tokens.\n    /// </returns>\n    /// <exception cref=\"UnsupportedOperationException\"> if this stream does not support\n    /// this method for the specified tokens </exception>\n    virtual std::string getText(Token *start, Token *stop) = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/TokenStreamRewriter.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <unordered_map>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"Exceptions.h\"\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"TokenStream.h\"\n\n#include \"TokenStreamRewriter.h\"\n\nusing namespace antlr4;\n\nusing antlr4::misc::Interval;\n\nTokenStreamRewriter::RewriteOperation::RewriteOperation(TokenStreamRewriter *outerInstance_, size_t index_)\n  : outerInstance(outerInstance_) {\n\n  InitializeInstanceFields();\n  this->index = index_;\n}\n\nTokenStreamRewriter::RewriteOperation::RewriteOperation(TokenStreamRewriter *outerInstance_, size_t index_,\n  const std::string& text_) : outerInstance(outerInstance_) {\n\n  InitializeInstanceFields();\n  this->index = index_;\n  this->text = text_;\n}\n\nTokenStreamRewriter::RewriteOperation::~RewriteOperation()\n{\n}\n\nsize_t TokenStreamRewriter::RewriteOperation::execute(std::string * /*buf*/) {\n  return index;\n}\n\nstd::string TokenStreamRewriter::RewriteOperation::toString() {\n  std::string opName = \"TokenStreamRewriter\";\n  size_t dollarIndex = opName.find('$');\n  opName = opName.substr(dollarIndex + 1, opName.length() - (dollarIndex + 1));\n  return \"<\" + opName + \"@\" + outerInstance->tokens->get(dollarIndex)->getText() + \":\\\"\" + text + \"\\\">\";\n}\n\nvoid TokenStreamRewriter::RewriteOperation::InitializeInstanceFields() {\n  instructionIndex = 0;\n  index = 0;\n}\n\nTokenStreamRewriter::InsertBeforeOp::InsertBeforeOp(TokenStreamRewriter *outerInstance_, size_t index_, const std::string& text_)\n: RewriteOperation(outerInstance_, index_, text_), outerInstance(outerInstance_) {\n}\n\nsize_t TokenStreamRewriter::InsertBeforeOp::execute(std::string *buf) {\n  buf->append(text);\n  if (outerInstance->tokens->get(index)->getType() != Token::EOF) {\n    buf->append(outerInstance->tokens->get(index)->getText());\n  }\n  return index + 1;\n}\n\nTokenStreamRewriter::ReplaceOp::ReplaceOp(TokenStreamRewriter *outerInstance_, size_t from, size_t to, const std::string& text)\n: RewriteOperation(outerInstance_, from, text), outerInstance(outerInstance_) {\n\n  InitializeInstanceFields();\n  lastIndex = to;\n}\n\nsize_t TokenStreamRewriter::ReplaceOp::execute(std::string *buf) {\n  buf->append(text);\n  return lastIndex + 1;\n}\n\nstd::string TokenStreamRewriter::ReplaceOp::toString() {\n  if (text.empty()) {\n    return \"<DeleteOp@\" + outerInstance->tokens->get(index)->getText() + \"..\" + outerInstance->tokens->get(lastIndex)->getText() + \">\";\n  }\n  return \"<ReplaceOp@\" + outerInstance->tokens->get(index)->getText() + \"..\" + outerInstance->tokens->get(lastIndex)->getText() + \":\\\"\" + text + \"\\\">\";\n}\n\nvoid TokenStreamRewriter::ReplaceOp::InitializeInstanceFields() {\n  lastIndex = 0;\n}\n\n//------------------ TokenStreamRewriter -------------------------------------------------------------------------------\n\nconst std::string TokenStreamRewriter::DEFAULT_PROGRAM_NAME = \"default\";\n\nTokenStreamRewriter::TokenStreamRewriter(TokenStream *tokens_) : tokens(tokens_) {\n  _programs[DEFAULT_PROGRAM_NAME].reserve(PROGRAM_INIT_SIZE);\n}\n\nTokenStreamRewriter::~TokenStreamRewriter() {\n  for (const auto &program : _programs) {\n    for (auto *operation : program.second) {\n      delete operation;\n    }\n  }\n}\n\nTokenStream *TokenStreamRewriter::getTokenStream() {\n  return tokens;\n}\n\nvoid TokenStreamRewriter::rollback(size_t instructionIndex) {\n  rollback(DEFAULT_PROGRAM_NAME, instructionIndex);\n}\n\nvoid TokenStreamRewriter::rollback(const std::string &programName, size_t instructionIndex) {\n  std::vector<RewriteOperation*> is = _programs[programName];\n  if (is.size() > 0) {\n    _programs.insert({ programName, std::vector<RewriteOperation*>(is.begin() + MIN_TOKEN_INDEX, is.begin() + instructionIndex) });\n  }\n}\n\nvoid TokenStreamRewriter::deleteProgram() {\n  deleteProgram(DEFAULT_PROGRAM_NAME);\n}\n\nvoid TokenStreamRewriter::deleteProgram(const std::string &programName) {\n  rollback(programName, MIN_TOKEN_INDEX);\n}\n\nvoid TokenStreamRewriter::insertAfter(Token *t, const std::string& text) {\n  insertAfter(DEFAULT_PROGRAM_NAME, t, text);\n}\n\nvoid TokenStreamRewriter::insertAfter(size_t index, const std::string& text) {\n  insertAfter(DEFAULT_PROGRAM_NAME, index, text);\n}\n\nvoid TokenStreamRewriter::insertAfter(const std::string &programName, Token *t, const std::string& text) {\n  insertAfter(programName, t->getTokenIndex(), text);\n}\n\nvoid TokenStreamRewriter::insertAfter(const std::string &programName, size_t index, const std::string& text) {\n  // to insert after, just insert before next index (even if past end)\n  insertBefore(programName, index + 1, text);\n}\n\nvoid TokenStreamRewriter::insertBefore(Token *t, const std::string& text) {\n  insertBefore(DEFAULT_PROGRAM_NAME, t, text);\n}\n\nvoid TokenStreamRewriter::insertBefore(size_t index, const std::string& text) {\n  insertBefore(DEFAULT_PROGRAM_NAME, index, text);\n}\n\nvoid TokenStreamRewriter::insertBefore(const std::string &programName, Token *t, const std::string& text) {\n  insertBefore(programName, t->getTokenIndex(), text);\n}\n\nvoid TokenStreamRewriter::insertBefore(const std::string &programName, size_t index, const std::string& text) {\n  RewriteOperation *op = new InsertBeforeOp(this, index, text); /* mem-check: deleted in d-tor */\n  std::vector<RewriteOperation*> &rewrites = getProgram(programName);\n  op->instructionIndex = rewrites.size();\n  rewrites.push_back(op);\n}\n\nvoid TokenStreamRewriter::replace(size_t index, const std::string& text) {\n  replace(DEFAULT_PROGRAM_NAME, index, index, text);\n}\n\nvoid TokenStreamRewriter::replace(size_t from, size_t to, const std::string& text) {\n  replace(DEFAULT_PROGRAM_NAME, from, to, text);\n}\n\nvoid TokenStreamRewriter::replace(Token *indexT, const std::string& text) {\n  replace(DEFAULT_PROGRAM_NAME, indexT, indexT, text);\n}\n\nvoid TokenStreamRewriter::replace(Token *from, Token *to, const std::string& text) {\n  replace(DEFAULT_PROGRAM_NAME, from, to, text);\n}\n\nvoid TokenStreamRewriter::replace(const std::string &programName, size_t from, size_t to, const std::string& text) {\n  if (from > to || to >= tokens->size()) {\n    throw IllegalArgumentException(\"replace: range invalid: \" + std::to_string(from) + \"..\" + std::to_string(to) +\n                                   \"(size = \" + std::to_string(tokens->size()) + \")\");\n  }\n  RewriteOperation *op = new ReplaceOp(this, from, to, text); /* mem-check: deleted in d-tor */\n  std::vector<RewriteOperation*> &rewrites = getProgram(programName);\n  op->instructionIndex = rewrites.size();\n  rewrites.push_back(op);\n}\n\nvoid TokenStreamRewriter::replace(const std::string &programName, Token *from, Token *to, const std::string& text) {\n  replace(programName, from->getTokenIndex(), to->getTokenIndex(), text);\n}\n\nvoid TokenStreamRewriter::Delete(size_t index) {\n  Delete(DEFAULT_PROGRAM_NAME, index, index);\n}\n\nvoid TokenStreamRewriter::Delete(size_t from, size_t to) {\n  Delete(DEFAULT_PROGRAM_NAME, from, to);\n}\n\nvoid TokenStreamRewriter::Delete(Token *indexT) {\n  Delete(DEFAULT_PROGRAM_NAME, indexT, indexT);\n}\n\nvoid TokenStreamRewriter::Delete(Token *from, Token *to) {\n  Delete(DEFAULT_PROGRAM_NAME, from, to);\n}\n\nvoid TokenStreamRewriter::Delete(const std::string &programName, size_t from, size_t to) {\n  std::string nullString;\n  replace(programName, from, to, nullString);\n}\n\nvoid TokenStreamRewriter::Delete(const std::string &programName, Token *from, Token *to) {\n  std::string nullString;\n  replace(programName, from, to, nullString);\n}\n\nsize_t TokenStreamRewriter::getLastRewriteTokenIndex() {\n  return getLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME);\n}\n\nsize_t TokenStreamRewriter::getLastRewriteTokenIndex(const std::string &programName) {\n  if (_lastRewriteTokenIndexes.find(programName) == _lastRewriteTokenIndexes.end()) {\n    return INVALID_INDEX;\n  }\n  return _lastRewriteTokenIndexes[programName];\n}\n\nvoid TokenStreamRewriter::setLastRewriteTokenIndex(const std::string &programName, size_t i) {\n  _lastRewriteTokenIndexes.insert({ programName, i });\n}\n\nstd::vector<TokenStreamRewriter::RewriteOperation*>& TokenStreamRewriter::getProgram(const std::string &name) {\n  auto iterator = _programs.find(name);\n  if (iterator == _programs.end()) {\n    return initializeProgram(name);\n  }\n  return iterator->second;\n}\n\nstd::vector<TokenStreamRewriter::RewriteOperation*>& TokenStreamRewriter::initializeProgram(const std::string &name) {\n  _programs[name].reserve(PROGRAM_INIT_SIZE);\n  return _programs[name];\n}\n\nstd::string TokenStreamRewriter::getText() {\n  return getText(DEFAULT_PROGRAM_NAME, Interval(0UL, tokens->size() - 1));\n}\n\nstd::string TokenStreamRewriter::getText(std::string programName) {\n  return getText(programName, Interval(0UL, tokens->size() - 1));\n}\n\nstd::string TokenStreamRewriter::getText(const Interval &interval) {\n  return getText(DEFAULT_PROGRAM_NAME, interval);\n}\n\nstd::string TokenStreamRewriter::getText(const std::string &programName, const Interval &interval) {\n  std::vector<TokenStreamRewriter::RewriteOperation*> &rewrites = _programs[programName];\n  size_t start = interval.a;\n  size_t stop = interval.b;\n\n  // ensure start/end are in range\n  if (stop > tokens->size() - 1) {\n    stop = tokens->size() - 1;\n  }\n  if (start == INVALID_INDEX) {\n    start = 0;\n  }\n\n  if (rewrites.empty() || rewrites.empty()) {\n    return tokens->getText(interval); // no instructions to execute\n  }\n  std::string buf;\n\n  // First, optimize instruction stream\n  std::unordered_map<size_t, TokenStreamRewriter::RewriteOperation*> indexToOp = reduceToSingleOperationPerIndex(rewrites);\n\n  // Walk buffer, executing instructions and emitting tokens\n  size_t i = start;\n  while (i <= stop && i < tokens->size()) {\n    RewriteOperation *op = indexToOp[i];\n    indexToOp.erase(i); // remove so any left have index size-1\n    Token *t = tokens->get(i);\n    if (op == nullptr) {\n      // no operation at that index, just dump token\n      if (t->getType() != Token::EOF) {\n        buf.append(t->getText());\n      }\n      i++; // move to next token\n    }\n    else {\n      i = op->execute(&buf); // execute operation and skip\n    }\n  }\n\n  // include stuff after end if it's last index in buffer\n  // So, if they did an insertAfter(lastValidIndex, \"foo\"), include\n  // foo if end==lastValidIndex.\n  if (stop == tokens->size() - 1) {\n    // Scan any remaining operations after last token\n    // should be included (they will be inserts).\n    for (auto op : indexToOp) {\n      if (op.second->index >= tokens->size() - 1) {\n        buf.append(op.second->text);\n      }\n    }\n  }\n  return buf;\n}\n\nstd::unordered_map<size_t, TokenStreamRewriter::RewriteOperation*> TokenStreamRewriter::reduceToSingleOperationPerIndex(\n  std::vector<TokenStreamRewriter::RewriteOperation*> &rewrites) {\n\n  // Reset the instructionIndex\n  for (size_t i = 0; i < rewrites.size(); ++i) {\n    rewrites[i]->instructionIndex = i;\n  }\n\n  // WALK REPLACES\n  for (size_t i = 0; i < rewrites.size(); ++i) {\n    TokenStreamRewriter::RewriteOperation *op = rewrites[i];\n    ReplaceOp *rop = dynamic_cast<ReplaceOp *>(op);\n    if (rop == nullptr)\n      continue;\n\n    // Wipe prior inserts within range\n    std::vector<InsertBeforeOp *> inserts = getKindOfOps<InsertBeforeOp>(rewrites, i);\n    for (auto *iop : inserts) {\n      if (iop->index == rop->index) {\n        // E.g., insert before 2, delete 2..2; update replace\n        // text to include insert before, kill insert\n        rop->text = iop->text + (!rop->text.empty() ? rop->text : \"\");\n        rewrites[iop->instructionIndex] = nullptr;\n        delete iop;\n      }\n      else if (iop->index > rop->index && iop->index <= rop->lastIndex) {\n        // delete insert as it's a no-op.\n        rewrites[iop->instructionIndex] = nullptr;\n        delete iop;\n      }\n    }\n    // Drop any prior replaces contained within\n    std::vector<ReplaceOp*> prevReplaces = getKindOfOps<ReplaceOp>(rewrites, i);\n    for (auto *prevRop : prevReplaces) {\n      if (prevRop->index >= rop->index && prevRop->lastIndex <= rop->lastIndex) {\n        // delete replace as it's a no-op.\n        rewrites[prevRop->instructionIndex] = nullptr;\n        delete prevRop;\n        continue;\n      }\n      // throw exception unless disjoint or identical\n      bool disjoint = prevRop->lastIndex < rop->index || prevRop->index > rop->lastIndex;\n      // Delete special case of replace (text==null):\n      // D.i-j.u D.x-y.v    | boundaries overlap    combine to max(min)..max(right)\n      if (prevRop->text.empty() && rop->text.empty() && !disjoint) {\n        rop->index = std::min(prevRop->index, rop->index);\n        rop->lastIndex = std::max(prevRop->lastIndex, rop->lastIndex);\n        rewrites[prevRop->instructionIndex] = nullptr; // kill first delete\n        delete prevRop;\n      }\n      else if (!disjoint) {\n        throw IllegalArgumentException(\"replace op boundaries of \" + rop->toString() +\n                                       \" overlap with previous \" + prevRop->toString());\n      }\n    }\n  }\n\n  // WALK INSERTS\n  for (size_t i = 0; i < rewrites.size(); i++) {\n    InsertBeforeOp *iop = dynamic_cast<InsertBeforeOp *>(rewrites[i]);\n    if (iop == nullptr)\n      continue;\n\n    // combine current insert with prior if any at same index\n\n    std::vector<InsertBeforeOp *> prevInserts = getKindOfOps<InsertBeforeOp>(rewrites, i);\n    for (auto *prevIop : prevInserts) {\n      if (prevIop->index == iop->index) { // combine objects\n                                          // convert to strings...we're in process of toString'ing\n                                          // whole token buffer so no lazy eval issue with any templates\n        iop->text = catOpText(&iop->text, &prevIop->text);\n        // delete redundant prior insert\n        rewrites[prevIop->instructionIndex] = nullptr;\n        delete prevIop;\n      }\n    }\n    // look for replaces where iop.index is in range; error\n    std::vector<ReplaceOp*> prevReplaces = getKindOfOps<ReplaceOp>(rewrites, i);\n    for (auto *rop : prevReplaces) {\n      if (iop->index == rop->index) {\n        rop->text = catOpText(&iop->text, &rop->text);\n        delete rewrites[i];\n        rewrites[i] = nullptr; // delete current insert\n        continue;\n      }\n      if (iop->index >= rop->index && iop->index <= rop->lastIndex) {\n        throw IllegalArgumentException(\"insert op \" + iop->toString() + \" within boundaries of previous \" + rop->toString());\n      }\n    }\n  }\n\n  std::unordered_map<size_t, TokenStreamRewriter::RewriteOperation*> m;\n  for (TokenStreamRewriter::RewriteOperation *op : rewrites) {\n    if (op == nullptr) { // ignore deleted ops\n      continue;\n    }\n    if (m.count(op->index) > 0) {\n      throw RuntimeException(\"should only be one op per index\");\n    }\n    m[op->index] = op;\n  }\n\n  return m;\n}\n\nstd::string TokenStreamRewriter::catOpText(std::string *a, std::string *b) {\n  std::string x = \"\";\n  std::string y = \"\";\n  if (a != nullptr) {\n    x = *a;\n  }\n  if (b != nullptr) {\n    y = *b;\n  }\n  return x + y;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/TokenStreamRewriter.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <unordered_map>\n#include <map>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"Token.h\"\n#include \"misc/Interval.h\"\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\n\n  /**\n   * Useful for rewriting out a buffered input token stream after doing some\n   * augmentation or other manipulations on it.\n   *\n   * <p>\n   * You can insert stuff, replace, and delete chunks. Note that the operations\n   * are done lazily--only if you convert the buffer to a {@link String} with\n   * {@link TokenStream#getText()}. This is very efficient because you are not\n   * moving data around all the time. As the buffer of tokens is converted to\n   * strings, the {@link #getText()} method(s) scan the input token stream and\n   * check to see if there is an operation at the current index. If so, the\n   * operation is done and then normal {@link String} rendering continues on the\n   * buffer. This is like having multiple Turing machine instruction streams\n   * (programs) operating on a single input tape. :)</p>\n   *\n   * <p>\n   * This rewriter makes no modifications to the token stream. It does not ask the\n   * stream to fill itself up nor does it advance the input cursor. The token\n   * stream {@link TokenStream#index()} will return the same value before and\n   * after any {@link #getText()} call.</p>\n   *\n   * <p>\n   * The rewriter only works on tokens that you have in the buffer and ignores the\n   * current input cursor. If you are buffering tokens on-demand, calling\n   * {@link #getText()} halfway through the input will only do rewrites for those\n   * tokens in the first half of the file.</p>\n   *\n   * <p>\n   * Since the operations are done lazily at {@link #getText}-time, operations do\n   * not screw up the token index values. That is, an insert operation at token\n   * index {@code i} does not change the index values for tokens\n   * {@code i}+1..n-1.</p>\n   *\n   * <p>\n   * Because operations never actually alter the buffer, you may always get the\n   * original token stream back without undoing anything. Since the instructions\n   * are queued up, you can easily simulate transactions and roll back any changes\n   * if there is an error just by removing instructions. For example,</p>\n   *\n   * <pre>\n   * CharStream input = new ANTLRFileStream(\"input\");\n   * TLexer lex = new TLexer(input);\n   * CommonTokenStream tokens = new CommonTokenStream(lex);\n   * T parser = new T(tokens);\n   * TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);\n   * parser.startRule();\n   * </pre>\n   *\n   * <p>\n   * Then in the rules, you can execute (assuming rewriter is visible):</p>\n   *\n   * <pre>\n   * Token t,u;\n   * ...\n   * rewriter.insertAfter(t, \"text to put after t\");}\n   * rewriter.insertAfter(u, \"text after u\");}\n   * System.out.println(rewriter.getText());\n   * </pre>\n   *\n   * <p>\n   * You can also have multiple \"instruction streams\" and get multiple rewrites\n   * from a single pass over the input. Just name the instruction streams and use\n   * that name again when printing the buffer. This could be useful for generating\n   * a C file and also its header file--all from the same buffer:</p>\n   *\n   * <pre>\n   * rewriter.insertAfter(\"pass1\", t, \"text to put after t\");}\n   * rewriter.insertAfter(\"pass2\", u, \"text after u\");}\n   * System.out.println(rewriter.getText(\"pass1\"));\n   * System.out.println(rewriter.getText(\"pass2\"));\n   * </pre>\n   *\n   * <p>\n   * If you don't use named rewrite streams, a \"default\" stream is used as the\n   * first example shows.</p>\n   */\n  class ANTLR4CPP_PUBLIC TokenStreamRewriter {\n  public:\n    static const std::string DEFAULT_PROGRAM_NAME;\n    static constexpr size_t PROGRAM_INIT_SIZE = 100;\n    static constexpr size_t MIN_TOKEN_INDEX = 0;\n\n    TokenStreamRewriter(TokenStream *tokens);\n    virtual ~TokenStreamRewriter();\n\n    TokenStream *getTokenStream();\n\n    virtual void rollback(size_t instructionIndex);\n\n    /// Rollback the instruction stream for a program so that\n    /// the indicated instruction (via instructionIndex) is no\n    /// longer in the stream.  UNTESTED!\n    virtual void rollback(const std::string &programName, size_t instructionIndex);\n\n    virtual void deleteProgram();\n\n    /// Reset the program so that no instructions exist.\n    virtual void deleteProgram(const std::string &programName);\n    virtual void insertAfter(Token *t, const std::string& text);\n    virtual void insertAfter(size_t index, const std::string& text);\n    virtual void insertAfter(const std::string &programName, Token *t, const std::string& text);\n    virtual void insertAfter(const std::string &programName, size_t index, const std::string& text);\n\n    virtual void insertBefore(Token *t, const std::string& text);\n    virtual void insertBefore(size_t index, const std::string& text);\n    virtual void insertBefore(const std::string &programName, Token *t, const std::string& text);\n    virtual void insertBefore(const std::string &programName, size_t index, const std::string& text);\n\n    virtual void replace(size_t index, const std::string& text);\n    virtual void replace(size_t from, size_t to, const std::string& text);\n    virtual void replace(Token *indexT, const std::string& text);\n    virtual void replace(Token *from, Token *to, const std::string& text);\n    virtual void replace(const std::string &programName, size_t from, size_t to, const std::string& text);\n    virtual void replace(const std::string &programName, Token *from, Token *to, const std::string& text);\n\n    virtual void Delete(size_t index);\n    virtual void Delete(size_t from, size_t to);\n    virtual void Delete(Token *indexT);\n    virtual void Delete(Token *from, Token *to);\n    virtual void Delete(const std::string &programName, size_t from, size_t to);\n    virtual void Delete(const std::string &programName, Token *from, Token *to);\n\n    virtual size_t getLastRewriteTokenIndex();\n\n    /// Return the text from the original tokens altered per the\n    /// instructions given to this rewriter.\n    virtual std::string getText();\n\n    /** Return the text from the original tokens altered per the\n     *  instructions given to this rewriter in programName.\n     */\n    std::string getText(std::string programName);\n\n    /// Return the text associated with the tokens in the interval from the\n    /// original token stream but with the alterations given to this rewriter.\n    /// The interval refers to the indexes in the original token stream.\n    /// We do not alter the token stream in any way, so the indexes\n    /// and intervals are still consistent. Includes any operations done\n    /// to the first and last token in the interval. So, if you did an\n    /// insertBefore on the first token, you would get that insertion.\n    /// The same is true if you do an insertAfter the stop token.\n    virtual std::string getText(const misc::Interval &interval);\n\n    virtual std::string getText(const std::string &programName, const misc::Interval &interval);\n\n  protected:\n    class RewriteOperation {\n    public:\n      /// What index into rewrites List are we?\n      size_t index;\n      std::string text;\n\n      /// Token buffer index.\n      size_t instructionIndex;\n\n      RewriteOperation(TokenStreamRewriter *outerInstance, size_t index);\n      RewriteOperation(TokenStreamRewriter *outerInstance, size_t index, const std::string& text);\n      virtual ~RewriteOperation();\n\n      /// Execute the rewrite operation by possibly adding to the buffer.\n      /// Return the index of the next token to operate on.\n\n      virtual size_t execute(std::string *buf);\n      virtual std::string toString();\n\n    private:\n      TokenStreamRewriter *const outerInstance;\n      void InitializeInstanceFields();\n    };\n\n    class InsertBeforeOp : public RewriteOperation {\n    private:\n      TokenStreamRewriter *const outerInstance;\n\n    public:\n      InsertBeforeOp(TokenStreamRewriter *outerInstance, size_t index, const std::string& text);\n\n      size_t execute(std::string *buf) override;\n    };\n\n    class ReplaceOp : public RewriteOperation {\n    private:\n      TokenStreamRewriter *const outerInstance;\n\n    public:\n      size_t lastIndex;\n\n      ReplaceOp(TokenStreamRewriter *outerInstance, size_t from, size_t to, const std::string& text);\n      size_t execute(std::string *buf) override;\n      std::string toString() override;\n\n    private:\n      void InitializeInstanceFields();\n    };\n\n    /// Our source stream\n    TokenStream *const tokens;\n\n    /// You may have multiple, named streams of rewrite operations.\n    /// I'm calling these things \"programs.\"\n    /// Maps String (name) -> rewrite (List)\n    std::map<std::string, std::vector<RewriteOperation*>> _programs;\n\n    /// <summary>\n    /// Map String (program name) -> Integer index </summary>\n    std::map<std::string, size_t> _lastRewriteTokenIndexes;\n    virtual size_t getLastRewriteTokenIndex(const std::string &programName);\n    virtual void setLastRewriteTokenIndex(const std::string &programName, size_t i);\n    virtual std::vector<RewriteOperation*>& getProgram(const std::string &name);\n\n    /// <summary>\n    /// We need to combine operations and report invalid operations (like\n    ///  overlapping replaces that are not completed nested).  Inserts to\n    ///  same index need to be combined etc...   Here are the cases:\n    ///\n    ///  I.i.u I.j.v                                leave alone, nonoverlapping\n    ///  I.i.u I.i.v                                combine: Iivu\n    ///\n    ///  R.i-j.u R.x-y.v    | i-j in x-y            delete first R\n    ///  R.i-j.u R.i-j.v                            delete first R\n    ///  R.i-j.u R.x-y.v    | x-y in i-j            ERROR\n    ///  R.i-j.u R.x-y.v    | boundaries overlap    ERROR\n    ///\n    ///  Delete special case of replace (text==null):\n    ///  D.i-j.u D.x-y.v    | boundaries overlap    combine to max(min)..max(right)\n    ///\n    ///  I.i.u R.x-y.v | i in (x+1)-y           delete I (since insert before\n    ///                                         we're not deleting i)\n    ///  I.i.u R.x-y.v | i not in (x+1)-y       leave alone, nonoverlapping\n    ///  R.x-y.v I.i.u | i in x-y               ERROR\n    ///  R.x-y.v I.x.u                          R.x-y.uv (combine, delete I)\n    ///  R.x-y.v I.i.u | i not in x-y           leave alone, nonoverlapping\n    ///\n    ///  I.i.u = insert u before op @ index i\n    ///  R.x-y.u = replace x-y indexed tokens with u\n    ///\n    ///  First we need to examine replaces.  For any replace op:\n    ///\n    ///         1. wipe out any insertions before op within that range.\n    ///     2. Drop any replace op before that is contained completely within\n    ///         that range.\n    ///     3. Throw exception upon boundary overlap with any previous replace.\n    ///\n    ///  Then we can deal with inserts:\n    ///\n    ///         1. for any inserts to same index, combine even if not adjacent.\n    ///         2. for any prior replace with same left boundary, combine this\n    ///         insert with replace and delete this replace.\n    ///         3. throw exception if index in same range as previous replace\n    ///\n    ///  Don't actually delete; make op null in list. Easier to walk list.\n    ///  Later we can throw as we add to index -> op map.\n    ///\n    ///  Note that I.2 R.2-2 will wipe out I.2 even though, technically, the\n    ///  inserted stuff would be before the replace range.  But, if you\n    ///  add tokens in front of a method body '{' and then delete the method\n    ///  body, I think the stuff before the '{' you added should disappear too.\n    ///\n    ///  Return a map from token index to operation.\n    /// </summary>\n    virtual std::unordered_map<size_t, RewriteOperation*> reduceToSingleOperationPerIndex(std::vector<RewriteOperation*> &rewrites);\n\n    virtual std::string catOpText(std::string *a, std::string *b);\n\n    /// Get all operations before an index of a particular kind.\n    template <typename T>\n    std::vector<T *> getKindOfOps(std::vector<RewriteOperation *> rewrites, size_t before) {\n      std::vector<T *> ops;\n      for (size_t i = 0; i < before && i < rewrites.size(); i++) {\n        T *op = dynamic_cast<T *>(rewrites[i]);\n        if (op == nullptr) { // ignore deleted or non matching entries\n          continue;\n        }\n        ops.push_back(op);\n      }\n      return ops;\n    }\n\n  private:\n    std::vector<RewriteOperation *>& initializeProgram(const std::string &name);\n\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/UnbufferedCharStream.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <string>\n#include <utility>\n#include <cstddef>\n#include \"misc/Interval.h\"\n#include \"antlr4-common.h\"\n#include \"Exceptions.h\"\n#include \"support/Utf8.h\"\n\n#include \"UnbufferedCharStream.h\"\n\nusing namespace antlrcpp;\nusing namespace antlr4;\nusing namespace antlr4::misc;\n\nUnbufferedCharStream::UnbufferedCharStream(std::wistream &input)\n    : _p(0), _numMarkers(0), _lastChar(0), _lastCharBufferStart(0), _currentCharIndex(0), _input(input) {\n  // The vector's size is what used to be n in Java code.\n  fill(1); // prime\n}\n\nvoid UnbufferedCharStream::consume() {\n  if (LA(1) == EOF) {\n    throw IllegalStateException(\"cannot consume EOF\");\n  }\n\n  // buf always has at least data[p==0] in this method due to ctor\n  _lastChar = _data[_p]; // track last char for LA(-1)\n\n  if (_p == _data.size() - 1 && _numMarkers == 0) {\n    size_t capacity = _data.capacity();\n    _data.clear();\n    _data.reserve(capacity);\n\n    _p = 0;\n    _lastCharBufferStart = _lastChar;\n  } else {\n    _p++;\n  }\n\n  _currentCharIndex++;\n  sync(1);\n}\n\nvoid UnbufferedCharStream::sync(size_t want) {\n  if (_p + want <= _data.size()) // Already enough data loaded?\n    return;\n\n  fill(_p + want - _data.size());\n}\n\nsize_t UnbufferedCharStream::fill(size_t n) {\n  for (size_t i = 0; i < n; i++) {\n    if (_data.size() > 0 && _data.back() == 0xFFFF) {\n      return i;\n    }\n\n    try {\n      char32_t c = nextChar();\n      add(c);\n#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026\n    } catch (IOException &ioe) {\n      // throw_with_nested is not available before VS 2015.\n      throw ioe;\n#else\n    } catch (IOException & /*ioe*/) {\n      std::throw_with_nested(RuntimeException());\n#endif\n    }\n  }\n\n  return n;\n}\n\nchar32_t UnbufferedCharStream::nextChar()  {\n  return _input.get();\n}\n\nvoid UnbufferedCharStream::add(char32_t c) {\n  _data += c;\n}\n\nsize_t UnbufferedCharStream::LA(ssize_t i) {\n  if (i == -1) { // special case\n    return _lastChar;\n  }\n\n  // We can look back only as many chars as we have buffered.\n  ssize_t index = static_cast<ssize_t>(_p) + i - 1;\n  if (index < 0) {\n    throw IndexOutOfBoundsException();\n  }\n\n  if (i > 0) {\n    sync(static_cast<size_t>(i)); // No need to sync if we look back.\n  }\n  if (static_cast<size_t>(index) >= _data.size()) {\n    return EOF;\n  }\n\n  if (_data[static_cast<size_t>(index)] == std::char_traits<wchar_t>::eof()) {\n    return EOF;\n  }\n\n  return _data[static_cast<size_t>(index)];\n}\n\nssize_t UnbufferedCharStream::mark() {\n  if (_numMarkers == 0) {\n    _lastCharBufferStart = _lastChar;\n  }\n\n  ssize_t mark = -static_cast<ssize_t>(_numMarkers) - 1;\n  _numMarkers++;\n  return mark;\n}\n\nvoid UnbufferedCharStream::release(ssize_t marker) {\n  ssize_t expectedMark = -static_cast<ssize_t>(_numMarkers);\n  if (marker != expectedMark) {\n    throw IllegalStateException(\"release() called with an invalid marker.\");\n  }\n\n  _numMarkers--;\n  if (_numMarkers == 0 && _p > 0) {\n    _data.erase(0, _p);\n    _p = 0;\n    _lastCharBufferStart = _lastChar;\n  }\n}\n\nsize_t UnbufferedCharStream::index() {\n  return _currentCharIndex;\n}\n\nvoid UnbufferedCharStream::seek(size_t index) {\n  if (index == _currentCharIndex) {\n    return;\n  }\n\n  if (index > _currentCharIndex) {\n    sync(index - _currentCharIndex);\n    index = std::min(index, getBufferStartIndex() + _data.size() - 1);\n  }\n\n  // index == to bufferStartIndex should set p to 0\n  ssize_t i = static_cast<ssize_t>(index) - static_cast<ssize_t>(getBufferStartIndex());\n  if (i < 0) {\n    throw IllegalArgumentException(std::string(\"cannot seek to negative index \") + std::to_string(index));\n  } else if (i >= static_cast<ssize_t>(_data.size())) {\n    throw UnsupportedOperationException(\"Seek to index outside buffer: \" + std::to_string(index) +\n                                        \" not in \" + std::to_string(getBufferStartIndex()) + \"..\" +\n                                        std::to_string(getBufferStartIndex() + _data.size()));\n  }\n\n  _p = static_cast<size_t>(i);\n  _currentCharIndex = index;\n  if (_p == 0) {\n    _lastChar = _lastCharBufferStart;\n  } else {\n    _lastChar = _data[_p - 1];\n  }\n}\n\nsize_t UnbufferedCharStream::size() {\n  throw UnsupportedOperationException(\"Unbuffered stream cannot know its size\");\n}\n\nstd::string UnbufferedCharStream::getSourceName() const {\n  if (name.empty()) {\n    return UNKNOWN_SOURCE_NAME;\n  }\n\n  return name;\n}\n\nstd::string UnbufferedCharStream::getText(const misc::Interval &interval) {\n  if (interval.a < 0 || interval.b < interval.a - 1) {\n    throw IllegalArgumentException(\"invalid interval\");\n  }\n\n  size_t bufferStartIndex = getBufferStartIndex();\n  if (!_data.empty() && _data.back() == 0xFFFF) {\n    if (interval.a + interval.length() > bufferStartIndex + _data.size()) {\n      throw IllegalArgumentException(\"the interval extends past the end of the stream\");\n    }\n  }\n\n  if (interval.a < static_cast<ssize_t>(bufferStartIndex) || interval.b >= ssize_t(bufferStartIndex + _data.size())) {\n    throw UnsupportedOperationException(\"interval \" + interval.toString() + \" outside buffer: \" +\n      std::to_string(bufferStartIndex) + \"..\" + std::to_string(bufferStartIndex + _data.size() - 1));\n  }\n  // convert from absolute to local index\n  size_t i = interval.a - bufferStartIndex;\n  auto maybeUtf8 = Utf8::strictEncode(std::u32string_view(_data).substr(i, interval.length()));\n  if (!maybeUtf8.has_value()) {\n    throw IllegalArgumentException(\"Unbuffered stream contains invalid Unicode code points\");\n  }\n  return std::move(maybeUtf8).value();\n}\n\nstd::string UnbufferedCharStream::toString() const {\n  throw UnsupportedOperationException(\"Unbuffered stream cannot be materialized to a string\");\n}\n\nsize_t UnbufferedCharStream::getBufferStartIndex() const {\n  return _currentCharIndex - _p;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/UnbufferedCharStream.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"CharStream.h\"\n\nnamespace antlr4 {\n\n  /// Do not buffer up the entire char stream. It does keep a small buffer\n  /// for efficiency and also buffers while a mark exists (set by the\n  /// lookahead prediction in parser). \"Unbuffered\" here refers to fact\n  /// that it doesn't buffer all data, not that's it's on demand loading of char.\n  class ANTLR4CPP_PUBLIC UnbufferedCharStream : public CharStream {\n  public:\n    /// The name or source of this char stream.\n    std::string name;\n\n    explicit UnbufferedCharStream(std::wistream &input);\n\n    void consume() override;\n    size_t LA(ssize_t i) override;\n\n    /// <summary>\n    /// Return a marker that we can release later.\n    /// <p/>\n    /// The specific marker value used for this class allows for some level of\n    /// protection against misuse where {@code seek()} is called on a mark or\n    /// {@code release()} is called in the wrong order.\n    /// </summary>\n    ssize_t mark() override;\n\n    /// <summary>\n    /// Decrement number of markers, resetting buffer if we hit 0. </summary>\n    /// <param name=\"marker\"> </param>\n    void release(ssize_t marker) override;\n    size_t index() override;\n\n    /// <summary>\n    /// Seek to absolute character index, which might not be in the current\n    ///  sliding window.  Move {@code p} to {@code index-bufferStartIndex}.\n    /// </summary>\n    void seek(size_t index) override;\n    size_t size() override;\n    std::string getSourceName() const override;\n    std::string getText(const misc::Interval &interval) override;\n\n    std::string toString() const override;\n\n  protected:\n    /// A moving window buffer of the data being scanned. While there's a marker,\n    /// we keep adding to buffer. Otherwise, <seealso cref=\"#consume consume()\"/> resets so\n    /// we start filling at index 0 again.\n    // UTF-32 encoded.\n    std::u32string _data;\n    typedef char32_t storage_type;\n\n    /// <summary>\n    /// 0..n-1 index into <seealso cref=\"#data data\"/> of next character.\n    /// <p/>\n    /// The {@code LA(1)} character is {@code data[p]}. If {@code p == n}, we are\n    /// out of buffered characters.\n    /// </summary>\n    size_t _p;\n\n    /// <summary>\n    /// Count up with <seealso cref=\"#mark mark()\"/> and down with\n    /// <seealso cref=\"#release release()\"/>. When we {@code release()} the last mark,\n    /// {@code numMarkers} reaches 0 and we reset the buffer. Copy\n    /// {@code data[p]..data[n-1]} to {@code data[0]..data[(n-1)-p]}.\n    /// </summary>\n    size_t _numMarkers;\n\n    /// This is the {@code LA(-1)} character for the current position.\n    size_t _lastChar; // UTF-32\n\n    /// <summary>\n    /// When {@code numMarkers > 0}, this is the {@code LA(-1)} character for the\n    /// first character in <seealso cref=\"#data data\"/>. Otherwise, this is unspecified.\n    /// </summary>\n    size_t _lastCharBufferStart; // UTF-32\n\n    /// <summary>\n    /// Absolute character index. It's the index of the character about to be\n    /// read via {@code LA(1)}. Goes from 0 to the number of characters in the\n    /// entire stream, although the stream size is unknown before the end is\n    /// reached.\n    /// </summary>\n    size_t _currentCharIndex;\n\n    std::wistream &_input;\n\n    /// <summary>\n    /// Make sure we have 'want' elements from current position <seealso cref=\"#p p\"/>.\n    /// Last valid {@code p} index is {@code data.length-1}. {@code p+need-1} is\n    /// the char index 'need' elements ahead. If we need 1 element,\n    /// {@code (p+1-1)==p} must be less than {@code data.length}.\n    /// </summary>\n    virtual void sync(size_t want);\n\n    /// <summary>\n    /// Add {@code n} characters to the buffer. Returns the number of characters\n    /// actually added to the buffer. If the return value is less than {@code n},\n    /// then EOF was reached before {@code n} characters could be added.\n    /// </summary>\n    virtual size_t fill(size_t n);\n\n    /// Override to provide different source of characters than\n    /// <seealso cref=\"#input input\"/>.\n    virtual char32_t nextChar();\n    virtual void add(char32_t c);\n    size_t getBufferStartIndex() const;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/UnbufferedTokenStream.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <memory>\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"Exceptions.h\"\n#include \"assert.h\"\n#include \"TokenSource.h\"\n#include \"support/Arrays.h\"\n#include \"misc/Interval.h\"\n#include \"RuleContext.h\"\n#include \"WritableToken.h\"\n\n#include \"UnbufferedTokenStream.h\"\n\nusing namespace antlr4;\n\nUnbufferedTokenStream::UnbufferedTokenStream(TokenSource *tokenSource) : UnbufferedTokenStream(tokenSource, 256) {\n}\n\nUnbufferedTokenStream::UnbufferedTokenStream(TokenSource *tokenSource, int /*bufferSize*/)\n  : _tokenSource(tokenSource), _lastToken(nullptr), _lastTokenBufferStart(nullptr)\n{\n  InitializeInstanceFields();\n  fill(1); // prime the pump\n}\n\nUnbufferedTokenStream::~UnbufferedTokenStream() {\n}\n\nToken* UnbufferedTokenStream::get(size_t i) const\n{ // get absolute index\n  size_t bufferStartIndex = getBufferStartIndex();\n  if (i < bufferStartIndex || i >= bufferStartIndex + _tokens.size()) {\n    throw IndexOutOfBoundsException(std::string(\"get(\") + std::to_string(i) + std::string(\") outside buffer: \")\n      + std::to_string(bufferStartIndex) + std::string(\"..\") + std::to_string(bufferStartIndex + _tokens.size()));\n  }\n  return _tokens[i - bufferStartIndex].get();\n}\n\nToken* UnbufferedTokenStream::LT(ssize_t i)\n{\n  if (i == -1) {\n    return _lastToken;\n  }\n\n  sync(i);\n  ssize_t index = static_cast<ssize_t>(_p) + i - 1;\n  if (index < 0) {\n    throw IndexOutOfBoundsException(std::string(\"LT(\") + std::to_string(i) + std::string(\") gives negative index\"));\n  }\n\n  if (index >= static_cast<ssize_t>(_tokens.size())) {\n    assert(_tokens.size() > 0 && _tokens.back()->getType() == EOF);\n    return _tokens.back().get();\n  }\n\n  return _tokens[static_cast<size_t>(index)].get();\n}\n\nsize_t UnbufferedTokenStream::LA(ssize_t i)\n{\n  return LT(i)->getType();\n}\n\nTokenSource* UnbufferedTokenStream::getTokenSource() const\n{\n  return _tokenSource;\n}\n\nstd::string UnbufferedTokenStream::getText()\n{\n  return \"\";\n}\n\nstd::string UnbufferedTokenStream::getText(RuleContext* ctx)\n{\n  return getText(ctx->getSourceInterval());\n}\n\nstd::string UnbufferedTokenStream::getText(Token *start, Token *stop)\n{\n  return getText(misc::Interval(start->getTokenIndex(), stop->getTokenIndex()));\n}\n\nvoid UnbufferedTokenStream::consume()\n{\n  if (LA(1) == EOF) {\n    throw IllegalStateException(\"cannot consume EOF\");\n  }\n\n  // buf always has at least tokens[p==0] in this method due to ctor\n  _lastToken = _tokens[_p].get(); // track last token for LT(-1)\n\n  // if we're at last token and no markers, opportunity to flush buffer\n  if (_p == _tokens.size() - 1 && _numMarkers == 0) {\n    _tokens.clear();\n    _p = 0;\n    _lastTokenBufferStart = _lastToken;\n  } else {\n    ++_p;\n  }\n\n  ++_currentTokenIndex;\n  sync(1);\n}\n\n/// <summary>\n/// Make sure we have 'need' elements from current position <seealso cref=\"#p p\"/>. Last valid\n///  {@code p} index is {@code tokens.length-1}.  {@code p+need-1} is the tokens index 'need' elements\n///  ahead.  If we need 1 element, {@code (p+1-1)==p} must be less than {@code tokens.length}.\n/// </summary>\nvoid UnbufferedTokenStream::sync(ssize_t want)\n{\n  ssize_t need = (static_cast<ssize_t>(_p) + want - 1) - static_cast<ssize_t>(_tokens.size()) + 1; // how many more elements we need?\n  if (need > 0) {\n    fill(static_cast<size_t>(need));\n  }\n}\n\n/// <summary>\n/// Add {@code n} elements to the buffer. Returns the number of tokens\n/// actually added to the buffer. If the return value is less than {@code n},\n/// then EOF was reached before {@code n} tokens could be added.\n/// </summary>\nsize_t UnbufferedTokenStream::fill(size_t n)\n{\n  for (size_t i = 0; i < n; i++) {\n    if (_tokens.size() > 0 && _tokens.back()->getType() == EOF) {\n      return i;\n    }\n\n    add(_tokenSource->nextToken());\n  }\n\n  return n;\n}\n\nvoid UnbufferedTokenStream::add(std::unique_ptr<Token> t)\n{\n  WritableToken *writable = dynamic_cast<WritableToken *>(t.get());\n  if (writable != nullptr) {\n    writable->setTokenIndex(int(getBufferStartIndex() + _tokens.size()));\n  }\n\n  _tokens.push_back(std::move(t));\n}\n\n/// <summary>\n/// Return a marker that we can release later.\n/// <p/>\n/// The specific marker value used for this class allows for some level of\n/// protection against misuse where {@code seek()} is called on a mark or\n/// {@code release()} is called in the wrong order.\n/// </summary>\nssize_t UnbufferedTokenStream::mark()\n{\n  if (_numMarkers == 0) {\n    _lastTokenBufferStart = _lastToken;\n  }\n\n  int mark = -_numMarkers - 1;\n  _numMarkers++;\n  return mark;\n}\n\nvoid UnbufferedTokenStream::release(ssize_t marker)\n{\n  ssize_t expectedMark = -_numMarkers;\n  if (marker != expectedMark) {\n    throw IllegalStateException(\"release() called with an invalid marker.\");\n  }\n\n  _numMarkers--;\n  if (_numMarkers == 0) { // can we release buffer?\n    if (_p > 0) {\n      // Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs\n      // p is last valid token; move nothing if p==n as we have no valid char\n      _tokens.erase(_tokens.begin(), _tokens.begin() + static_cast<ssize_t>(_p));\n      _p = 0;\n    }\n\n    _lastTokenBufferStart = _lastToken;\n  }\n}\n\nsize_t UnbufferedTokenStream::index()\n{\n  return _currentTokenIndex;\n}\n\nvoid UnbufferedTokenStream::seek(size_t index)\n{ // seek to absolute index\n  if (index == _currentTokenIndex) {\n    return;\n  }\n\n  if (index > _currentTokenIndex) {\n    sync(ssize_t(index - _currentTokenIndex));\n    index = std::min(index, getBufferStartIndex() + _tokens.size() - 1);\n  }\n\n  size_t bufferStartIndex = getBufferStartIndex();\n  if (bufferStartIndex > index) {\n    throw IllegalArgumentException(std::string(\"cannot seek to negative index \") + std::to_string(index));\n  }\n\n  size_t i = index - bufferStartIndex;\n  if (i >= _tokens.size()) {\n    throw UnsupportedOperationException(std::string(\"seek to index outside buffer: \") + std::to_string(index) +\n      \" not in \" + std::to_string(bufferStartIndex) + \"..\" + std::to_string(bufferStartIndex + _tokens.size()));\n  }\n\n  _p = i;\n  _currentTokenIndex = index;\n  if (_p == 0) {\n    _lastToken = _lastTokenBufferStart;\n  } else {\n    _lastToken = _tokens[_p - 1].get();\n  }\n}\n\nsize_t UnbufferedTokenStream::size()\n{\n  throw UnsupportedOperationException(\"Unbuffered stream cannot know its size\");\n}\n\nstd::string UnbufferedTokenStream::getSourceName() const\n{\n  return _tokenSource->getSourceName();\n}\n\nstd::string UnbufferedTokenStream::getText(const misc::Interval &interval)\n{\n  size_t bufferStartIndex = getBufferStartIndex();\n  size_t bufferStopIndex = bufferStartIndex + _tokens.size() - 1;\n\n  size_t start = interval.a;\n  size_t stop = interval.b;\n  if (start < bufferStartIndex || stop > bufferStopIndex) {\n    throw UnsupportedOperationException(std::string(\"interval \") + interval.toString() +\n      \" not in token buffer window: \" + std::to_string(bufferStartIndex) + \"..\" + std::to_string(bufferStopIndex));\n  }\n\n  size_t a = start - bufferStartIndex;\n  size_t b = stop - bufferStartIndex;\n\n  std::stringstream ss;\n  for (size_t i = a; i <= b; i++) {\n    Token *t = _tokens[i].get();\n    if (i > 0)\n      ss << \", \";\n    ss << t->getText();\n  }\n\n  return ss.str();\n}\n\nsize_t UnbufferedTokenStream::getBufferStartIndex() const\n{\n  return _currentTokenIndex - _p;\n}\n\nvoid UnbufferedTokenStream::InitializeInstanceFields()\n{\n  _p = 0;\n  _numMarkers = 0;\n  _currentTokenIndex = 0;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/UnbufferedTokenStream.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"TokenStream.h\"\n\nnamespace antlr4 {\n\n  class ANTLR4CPP_PUBLIC UnbufferedTokenStream : public TokenStream {\n  public:\n    UnbufferedTokenStream(TokenSource *tokenSource);\n    UnbufferedTokenStream(TokenSource *tokenSource, int bufferSize);\n    UnbufferedTokenStream(const UnbufferedTokenStream& other) = delete;\n    ~UnbufferedTokenStream() override;\n\n    UnbufferedTokenStream& operator = (const UnbufferedTokenStream& other) = delete;\n\n    Token* get(size_t i) const override;\n    Token* LT(ssize_t i) override;\n    size_t LA(ssize_t i) override;\n\n    TokenSource* getTokenSource() const override;\n\n    std::string getText(const misc::Interval &interval) override;\n    std::string getText() override;\n    std::string getText(RuleContext *ctx) override;\n    std::string getText(Token *start, Token *stop) override;\n\n    void consume() override;\n\n    /// <summary>\n    /// Return a marker that we can release later.\n    /// <p/>\n    /// The specific marker value used for this class allows for some level of\n    /// protection against misuse where {@code seek()} is called on a mark or\n    /// {@code release()} is called in the wrong order.\n    /// </summary>\n    ssize_t mark() override;\n    void release(ssize_t marker) override;\n    size_t index() override;\n    void seek(size_t index) override;\n    size_t size() override;\n    std::string getSourceName() const override;\n\n  protected:\n    /// Make sure we have 'need' elements from current position p. Last valid\n    /// p index is tokens.length - 1.  p + need - 1 is the tokens index 'need' elements\n    /// ahead.  If we need 1 element, (p+1-1)==p must be less than tokens.length.\n    TokenSource *_tokenSource;\n\n    /// <summary>\n    /// A moving window buffer of the data being scanned. While there's a marker,\n    /// we keep adding to buffer. Otherwise, <seealso cref=\"#consume consume()\"/> resets so\n    /// we start filling at index 0 again.\n    /// </summary>\n\n    std::vector<std::unique_ptr<Token>> _tokens;\n\n    /// <summary>\n    /// 0..n-1 index into <seealso cref=\"#tokens tokens\"/> of next token.\n    /// <p/>\n    /// The {@code LT(1)} token is {@code tokens[p]}. If {@code p == n}, we are\n    /// out of buffered tokens.\n    /// </summary>\n    size_t _p;\n\n    /// <summary>\n    /// Count up with <seealso cref=\"#mark mark()\"/> and down with\n    /// <seealso cref=\"#release release()\"/>. When we {@code release()} the last mark,\n    /// {@code numMarkers} reaches 0 and we reset the buffer. Copy\n    /// {@code tokens[p]..tokens[n-1]} to {@code tokens[0]..tokens[(n-1)-p]}.\n    /// </summary>\n    int _numMarkers;\n\n    /// <summary>\n    /// This is the {@code LT(-1)} token for the current position.\n    /// </summary>\n    Token *_lastToken;\n\n    /// <summary>\n    /// When {@code numMarkers > 0}, this is the {@code LT(-1)} token for the\n    /// first token in <seealso cref=\"#tokens\"/>. Otherwise, this is {@code null}.\n    /// </summary>\n    Token *_lastTokenBufferStart;\n\n    /// <summary>\n    /// Absolute token index. It's the index of the token about to be read via\n    /// {@code LT(1)}. Goes from 0 to the number of tokens in the entire stream,\n    /// although the stream size is unknown before the end is reached.\n    /// <p/>\n    /// This value is used to set the token indexes if the stream provides tokens\n    /// that implement <seealso cref=\"WritableToken\"/>.\n    /// </summary>\n    size_t _currentTokenIndex;\n\n    virtual void sync(ssize_t want);\n\n    /// <summary>\n    /// Add {@code n} elements to the buffer. Returns the number of tokens\n    /// actually added to the buffer. If the return value is less than {@code n},\n    /// then EOF was reached before {@code n} tokens could be added.\n    /// </summary>\n    virtual size_t fill(size_t n);\n    virtual void add(std::unique_ptr<Token> t);\n\n    size_t getBufferStartIndex() const;\n\n  private:\n    void InitializeInstanceFields();\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Version.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\n#define ANTLRCPP_VERSION_MAJOR 4\n#define ANTLRCPP_VERSION_MINOR 13\n#define ANTLRCPP_VERSION_PATCH 2\n\n#define ANTLRCPP_MAKE_VERSION(major, minor, patch) ((major) * 100000 + (minor) * 1000 + (patch))\n\n#define ANTLRCPP_VERSION \\\n  ANTLRCPP_MAKE_VERSION(ANTLR4CPP_VERSION_MAJOR, ANTLR4CPP_VERSION_MINOR, ANTLR4CPP_VERSION_PATCH)\n\n#define ANTLRCPP_VERSION_STRING \\\n  ANTLR4CPP_STRINGIFY(ANTLR4CPP_VERSION_MAJOR) \".\" \\\n  ANTLR4CPP_STRINGIFY(ANTLR4CPP_VERSION_MINOR) \".\" \\\n  ANTLR4CPP_STRINGIFY(ANTLR4CPP_VERSION_PATCH)\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Vocabulary.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string_view>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"Token.h\"\n\n#include \"Vocabulary.h\"\n\nusing namespace antlr4::dfa;\n\nconst Vocabulary Vocabulary::EMPTY_VOCABULARY;\n\nVocabulary::Vocabulary(std::vector<std::string> literalNames, std::vector<std::string> symbolicNames)\n: Vocabulary(std::move(literalNames), std::move(symbolicNames), {}) {\n}\n\nVocabulary::Vocabulary(std::vector<std::string> literalNames,\n  std::vector<std::string> symbolicNames, std::vector<std::string> displayNames)\n  : _literalNames(std::move(literalNames)), _symbolicNames(std::move(symbolicNames)), _displayNames(std::move(displayNames)),\n    _maxTokenType(std::max(_displayNames.size(), std::max(_literalNames.size(), _symbolicNames.size())) - 1) {\n  // See note here on -1 part: https://github.com/antlr/antlr4/pull/1146\n}\n\nstd::string_view Vocabulary::getLiteralName(size_t tokenType) const {\n  if (tokenType < _literalNames.size()) {\n    return _literalNames[tokenType];\n  }\n\n  return \"\";\n}\n\nstd::string_view Vocabulary::getSymbolicName(size_t tokenType) const {\n  if (tokenType == Token::EOF) {\n    return \"EOF\";\n  }\n\n  if (tokenType < _symbolicNames.size()) {\n    return _symbolicNames[tokenType];\n  }\n\n  return \"\";\n}\n\nstd::string Vocabulary::getDisplayName(size_t tokenType) const {\n  if (tokenType < _displayNames.size()) {\n    std::string_view displayName = _displayNames[tokenType];\n    if (!displayName.empty()) {\n      return std::string(displayName);\n    }\n  }\n\n  std::string_view literalName = getLiteralName(tokenType);\n  if (!literalName.empty()) {\n    return std::string(literalName);\n  }\n\n  std::string_view symbolicName = getSymbolicName(tokenType);\n  if (!symbolicName.empty()) {\n    return std::string(symbolicName);\n  }\n\n  return std::to_string(tokenType);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/Vocabulary.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string_view>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace dfa {\n\n  /// This class provides a default implementation of the <seealso cref=\"Vocabulary\"/>\n  /// interface.\n  class ANTLR4CPP_PUBLIC Vocabulary final {\n  public:\n    /// Gets an empty <seealso cref=\"Vocabulary\"/> instance.\n    ///\n    /// <para>\n    /// No literal or symbol names are assigned to token types, so\n    /// <seealso cref=\"#getDisplayName(int)\"/> returns the numeric value for all tokens\n    /// except <seealso cref=\"Token#EOF\"/>.</para>\n    [[deprecated(\"Use the default constructor of Vocabulary instead.\")]] static const Vocabulary EMPTY_VOCABULARY;\n\n    Vocabulary() {}\n\n    Vocabulary(const Vocabulary&) = default;\n\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"Vocabulary\"/> from the specified\n    /// literal and symbolic token names.\n    /// </summary>\n    /// <param name=\"literalNames\"> The literal names assigned to tokens, or {@code null}\n    /// if no literal names are assigned. </param>\n    /// <param name=\"symbolicNames\"> The symbolic names assigned to tokens, or\n    /// {@code null} if no symbolic names are assigned.\n    /// </param>\n    /// <seealso cref= #getLiteralName(int) </seealso>\n    /// <seealso cref= #getSymbolicName(int) </seealso>\n    Vocabulary(std::vector<std::string> literalNames, std::vector<std::string> symbolicNames);\n\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"Vocabulary\"/> from the specified\n    /// literal, symbolic, and display token names.\n    /// </summary>\n    /// <param name=\"literalNames\"> The literal names assigned to tokens, or {@code null}\n    /// if no literal names are assigned. </param>\n    /// <param name=\"symbolicNames\"> The symbolic names assigned to tokens, or\n    /// {@code null} if no symbolic names are assigned. </param>\n    /// <param name=\"displayNames\"> The display names assigned to tokens, or {@code null}\n    /// to use the values in {@code literalNames} and {@code symbolicNames} as\n    /// the source of display names, as described in\n    /// <seealso cref=\"#getDisplayName(int)\"/>.\n    /// </param>\n    /// <seealso cref= #getLiteralName(int) </seealso>\n    /// <seealso cref= #getSymbolicName(int) </seealso>\n    /// <seealso cref= #getDisplayName(int) </seealso>\n    Vocabulary(std::vector<std::string> literalNames, std::vector<std::string> symbolicNames,\n               std::vector<std::string> displayNames);\n\n    /// <summary>\n    /// Returns the highest token type value. It can be used to iterate from\n    /// zero to that number, inclusively, thus querying all stored entries. </summary>\n    /// <returns> the highest token type value </returns>\n    constexpr size_t getMaxTokenType() const { return _maxTokenType; }\n\n    /// <summary>\n    /// Gets the string literal associated with a token type. The string returned\n    /// by this method, when not {@code null}, can be used unaltered in a parser\n    /// grammar to represent this token type.\n    ///\n    /// <para>The following table shows examples of lexer rules and the literal\n    /// names assigned to the corresponding token types.</para>\n    ///\n    /// <table>\n    ///  <tr>\n    ///   <th>Rule</th>\n    ///   <th>Literal Name</th>\n    ///   <th>Java String Literal</th>\n    ///  </tr>\n    ///  <tr>\n    ///   <td>{@code THIS : 'this';}</td>\n    ///   <td>{@code 'this'}</td>\n    ///   <td>{@code \"'this'\"}</td>\n    ///  </tr>\n    ///  <tr>\n    ///   <td>{@code SQUOTE : '\\'';}</td>\n    ///   <td>{@code '\\''}</td>\n    ///   <td>{@code \"'\\\\''\"}</td>\n    ///  </tr>\n    ///  <tr>\n    ///   <td>{@code ID : [A-Z]+;}</td>\n    ///   <td>n/a</td>\n    ///   <td>{@code null}</td>\n    ///  </tr>\n    /// </table>\n    /// </summary>\n    /// <param name=\"tokenType\"> The token type.\n    /// </param>\n    /// <returns> The string literal associated with the specified token type, or\n    /// {@code null} if no string literal is associated with the type. </returns>\n    std::string_view getLiteralName(size_t tokenType) const;\n\n    /// <summary>\n    /// Gets the symbolic name associated with a token type. The string returned\n    /// by this method, when not {@code null}, can be used unaltered in a parser\n    /// grammar to represent this token type.\n    ///\n    /// <para>This method supports token types defined by any of the following\n    /// methods:</para>\n    ///\n    /// <ul>\n    ///  <li>Tokens created by lexer rules.</li>\n    ///  <li>Tokens defined in a <code>tokens{}</code> block in a lexer or parser\n    ///  grammar.</li>\n    ///  <li>The implicitly defined {@code EOF} token, which has the token type\n    ///  <seealso cref=\"Token#EOF\"/>.</li>\n    /// </ul>\n    ///\n    /// <para>The following table shows examples of lexer rules and the literal\n    /// names assigned to the corresponding token types.</para>\n    ///\n    /// <table>\n    ///  <tr>\n    ///   <th>Rule</th>\n    ///   <th>Symbolic Name</th>\n    ///  </tr>\n    ///  <tr>\n    ///   <td>{@code THIS : 'this';}</td>\n    ///   <td>{@code THIS}</td>\n    ///  </tr>\n    ///  <tr>\n    ///   <td>{@code SQUOTE : '\\'';}</td>\n    ///   <td>{@code SQUOTE}</td>\n    ///  </tr>\n    ///  <tr>\n    ///   <td>{@code ID : [A-Z]+;}</td>\n    ///   <td>{@code ID}</td>\n    ///  </tr>\n    /// </table>\n    /// </summary>\n    /// <param name=\"tokenType\"> The token type.\n    /// </param>\n    /// <returns> The symbolic name associated with the specified token type, or\n    /// {@code null} if no symbolic name is associated with the type. </returns>\n    std::string_view getSymbolicName(size_t tokenType) const;\n\n    /// <summary>\n    /// Gets the display name of a token type.\n    ///\n    /// <para>ANTLR provides a default implementation of this method, but\n    /// applications are free to override the behavior in any manner which makes\n    /// sense for the application. The default implementation returns the first\n    /// result from the following list which produces a non-{@code null}\n    /// result.</para>\n    ///\n    /// <ol>\n    ///  <li>The result of <seealso cref=\"#getLiteralName\"/></li>\n    ///  <li>The result of <seealso cref=\"#getSymbolicName\"/></li>\n    ///  <li>The result of <seealso cref=\"Integer#toString\"/></li>\n    /// </ol>\n    /// </summary>\n    /// <param name=\"tokenType\"> The token type.\n    /// </param>\n    /// <returns> The display name of the token type, for use in error reporting or\n    /// other user-visible messages which reference specific token types. </returns>\n    std::string getDisplayName(size_t tokenType) const;\n\n  private:\n    std::vector<std::string> const _literalNames;\n    std::vector<std::string> const _symbolicNames;\n    std::vector<std::string> const _displayNames;\n    const size_t _maxTokenType = 0;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/WritableToken.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"WritableToken.h\"\n\nantlr4::WritableToken::~WritableToken() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/WritableToken.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n\nnamespace antlr4 {\n\n  class ANTLR4CPP_PUBLIC WritableToken : public Token {\n  public:\n    ~WritableToken() override;\n    virtual void setText(const std::string &text) = 0;\n    virtual void setType(size_t ttype) = 0;\n    virtual void setLine(size_t line) = 0;\n    virtual void setCharPositionInLine(size_t pos) = 0;\n    virtual void setChannel(size_t channel) = 0;\n    virtual void setTokenIndex(size_t index) = 0;\n  };\n\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/antlr4-common.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <algorithm>\n#include <any>\n#include <atomic>\n#include <bitset>\n#include <cassert>\n#include <climits>\n#include <cstddef>\n#include <cstdint>\n#include <cstdlib>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <memory>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <string_view>\n#include <typeinfo>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n// Defines for the Guid class and other platform dependent stuff.\n#ifdef _WIN32\n  #ifdef _MSC_VER\n    #pragma warning (disable: 4250) // Class inherits by dominance.\n    #pragma warning (disable: 4512) // assignment operator could not be generated\n\n    #if _MSC_VER < 1900\n      // Before VS 2015 code like \"while (true)\" will create a (useless) warning in level 4.\n      #pragma warning (disable: 4127) // conditional expression is constant\n    #endif\n  #endif\n\n  #ifdef _WIN64\n    typedef __int64 ssize_t;\n  #else\n    typedef __int32 ssize_t;\n  #endif\n\n  #ifdef ANTLR4CPP_EXPORTS\n    #define ANTLR4CPP_PUBLIC __declspec(dllexport)\n  #else\n    #ifdef ANTLR4CPP_STATIC\n      #define ANTLR4CPP_PUBLIC\n    #else\n      #define ANTLR4CPP_PUBLIC __declspec(dllimport)\n    #endif\n  #endif\n\n#elif defined(__APPLE__)\n  #if __GNUC__ >= 4\n    #define ANTLR4CPP_PUBLIC __attribute__ ((visibility (\"default\")))\n  #else\n    #define ANTLR4CPP_PUBLIC\n  #endif\n#else\n  #if __GNUC__ >= 6\n    #define ANTLR4CPP_PUBLIC __attribute__ ((visibility (\"default\")))\n  #else\n    #define ANTLR4CPP_PUBLIC\n  #endif\n#endif\n\n#ifdef __has_builtin\n#define ANTLR4CPP_HAVE_BUILTIN(x) __has_builtin(x)\n#else\n#define ANTLR4CPP_HAVE_BUILTIN(x) 0\n#endif\n\n#define ANTLR4CPP_INTERNAL_STRINGIFY(x) #x\n#define ANTLR4CPP_STRINGIFY(x) ANTLR4CPP_INTERNAL_STRINGIFY(x)\n\n// We use everything from the C++ standard library by default.\n#ifndef ANTLR4CPP_USING_ABSEIL\n#define ANTLR4CPP_USING_ABSEIL 0\n#endif\n\n#include \"support/Declarations.h\"\n\n// We have to undefine this symbol as ANTLR will use this name for own members and even\n// generated functions. Because EOF is a global macro we cannot use e.g. a namespace scope to disambiguate.\n#ifdef EOF\n#undef EOF\n#endif\n\n#define INVALID_INDEX std::numeric_limits<size_t>::max()\ntemplate<class T> using Ref = std::shared_ptr<T>;\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/antlr4-runtime.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n// This is the umbrella header for all ANTLR4 C++ runtime headers.\n\n// IWYU pragma: begin_exports\n\n#include \"antlr4-common.h\"\n\n#include \"ANTLRErrorListener.h\"\n#include \"ANTLRErrorStrategy.h\"\n#include \"ANTLRFileStream.h\"\n#include \"ANTLRInputStream.h\"\n#include \"BailErrorStrategy.h\"\n#include \"BaseErrorListener.h\"\n#include \"BufferedTokenStream.h\"\n#include \"CharStream.h\"\n#include \"CommonToken.h\"\n#include \"CommonTokenFactory.h\"\n#include \"CommonTokenStream.h\"\n#include \"ConsoleErrorListener.h\"\n#include \"DefaultErrorStrategy.h\"\n#include \"DiagnosticErrorListener.h\"\n#include \"Exceptions.h\"\n#include \"FailedPredicateException.h\"\n#include \"InputMismatchException.h\"\n#include \"IntStream.h\"\n#include \"InterpreterRuleContext.h\"\n#include \"Lexer.h\"\n#include \"LexerInterpreter.h\"\n#include \"LexerNoViableAltException.h\"\n#include \"ListTokenSource.h\"\n#include \"NoViableAltException.h\"\n#include \"Parser.h\"\n#include \"ParserInterpreter.h\"\n#include \"ParserRuleContext.h\"\n#include \"ProxyErrorListener.h\"\n#include \"RecognitionException.h\"\n#include \"Recognizer.h\"\n#include \"RuleContext.h\"\n#include \"RuleContextWithAltNum.h\"\n#include \"RuntimeMetaData.h\"\n#include \"Token.h\"\n#include \"TokenFactory.h\"\n#include \"TokenSource.h\"\n#include \"TokenStream.h\"\n#include \"TokenStreamRewriter.h\"\n#include \"UnbufferedCharStream.h\"\n#include \"UnbufferedTokenStream.h\"\n#include \"Version.h\"\n#include \"Vocabulary.h\"\n#include \"Vocabulary.h\"\n#include \"WritableToken.h\"\n#include \"atn/ATN.h\"\n#include \"atn/ATNConfig.h\"\n#include \"atn/ATNConfigSet.h\"\n#include \"atn/ATNDeserializationOptions.h\"\n#include \"atn/ATNDeserializer.h\"\n#include \"atn/ATNSimulator.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/ATNType.h\"\n#include \"atn/ActionTransition.h\"\n#include \"atn/AmbiguityInfo.h\"\n#include \"atn/ArrayPredictionContext.h\"\n#include \"atn/AtomTransition.h\"\n#include \"atn/BasicBlockStartState.h\"\n#include \"atn/BasicState.h\"\n#include \"atn/BlockEndState.h\"\n#include \"atn/BlockStartState.h\"\n#include \"atn/ContextSensitivityInfo.h\"\n#include \"atn/DecisionEventInfo.h\"\n#include \"atn/DecisionInfo.h\"\n#include \"atn/DecisionState.h\"\n#include \"atn/EpsilonTransition.h\"\n#include \"atn/ErrorInfo.h\"\n#include \"atn/LL1Analyzer.h\"\n#include \"atn/LexerATNConfig.h\"\n#include \"atn/LexerATNSimulator.h\"\n#include \"atn/LexerAction.h\"\n#include \"atn/LexerActionExecutor.h\"\n#include \"atn/LexerActionType.h\"\n#include \"atn/LexerChannelAction.h\"\n#include \"atn/LexerCustomAction.h\"\n#include \"atn/LexerIndexedCustomAction.h\"\n#include \"atn/LexerModeAction.h\"\n#include \"atn/LexerMoreAction.h\"\n#include \"atn/LexerPopModeAction.h\"\n#include \"atn/LexerPushModeAction.h\"\n#include \"atn/LexerSkipAction.h\"\n#include \"atn/LexerTypeAction.h\"\n#include \"atn/LookaheadEventInfo.h\"\n#include \"atn/LoopEndState.h\"\n#include \"atn/NotSetTransition.h\"\n#include \"atn/OrderedATNConfigSet.h\"\n#include \"atn/ParseInfo.h\"\n#include \"atn/ParserATNSimulator.h\"\n#include \"atn/ParserATNSimulatorOptions.h\"\n#include \"atn/PlusBlockStartState.h\"\n#include \"atn/PlusLoopbackState.h\"\n#include \"atn/PrecedencePredicateTransition.h\"\n#include \"atn/PredicateEvalInfo.h\"\n#include \"atn/PredicateTransition.h\"\n#include \"atn/PredictionContext.h\"\n#include \"atn/PredictionContextCache.h\"\n#include \"atn/PredictionContextMergeCache.h\"\n#include \"atn/PredictionContextMergeCacheOptions.h\"\n#include \"atn/PredictionMode.h\"\n#include \"atn/ProfilingATNSimulator.h\"\n#include \"atn/RangeTransition.h\"\n#include \"atn/RuleStartState.h\"\n#include \"atn/RuleStopState.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/SemanticContext.h\"\n#include \"atn/SerializedATNView.h\"\n#include \"atn/SetTransition.h\"\n#include \"atn/SingletonPredictionContext.h\"\n#include \"atn/StarBlockStartState.h\"\n#include \"atn/StarLoopEntryState.h\"\n#include \"atn/StarLoopbackState.h\"\n#include \"atn/TokensStartState.h\"\n#include \"atn/Transition.h\"\n#include \"atn/WildcardTransition.h\"\n#include \"dfa/DFA.h\"\n#include \"dfa/DFASerializer.h\"\n#include \"dfa/DFAState.h\"\n#include \"dfa/LexerDFASerializer.h\"\n#include \"misc/InterpreterDataReader.h\"\n#include \"misc/Interval.h\"\n#include \"misc/IntervalSet.h\"\n#include \"misc/MurmurHash.h\"\n#include \"misc/Predicate.h\"\n#include \"support/Any.h\"\n#include \"support/Arrays.h\"\n#include \"support/BitSet.h\"\n#include \"support/Casts.h\"\n#include \"support/CPPUtils.h\"\n#include \"tree/AbstractParseTreeVisitor.h\"\n#include \"tree/ErrorNode.h\"\n#include \"tree/ErrorNodeImpl.h\"\n#include \"tree/ParseTree.h\"\n#include \"tree/ParseTreeListener.h\"\n#include \"tree/ParseTreeProperty.h\"\n#include \"tree/ParseTreeVisitor.h\"\n#include \"tree/ParseTreeWalker.h\"\n#include \"tree/TerminalNode.h\"\n#include \"tree/TerminalNodeImpl.h\"\n#include \"tree/Trees.h\"\n#include \"tree/pattern/Chunk.h\"\n#include \"tree/pattern/ParseTreeMatch.h\"\n#include \"tree/pattern/ParseTreePattern.h\"\n#include \"tree/pattern/ParseTreePatternMatcher.h\"\n#include \"tree/pattern/RuleTagToken.h\"\n#include \"tree/pattern/TagChunk.h\"\n#include \"tree/pattern/TextChunk.h\"\n#include \"tree/pattern/TokenTagToken.h\"\n#include \"tree/xpath/XPath.h\"\n#include \"tree/xpath/XPathElement.h\"\n#include \"tree/xpath/XPathLexer.h\"\n#include \"tree/xpath/XPathLexerErrorListener.h\"\n#include \"tree/xpath/XPathRuleAnywhereElement.h\"\n#include \"tree/xpath/XPathRuleElement.h\"\n#include \"tree/xpath/XPathTokenAnywhereElement.h\"\n#include \"tree/xpath/XPathTokenElement.h\"\n#include \"tree/xpath/XPathWildcardAnywhereElement.h\"\n#include \"tree/xpath/XPathWildcardElement.h\"\n#include \"internal/Synchronization.h\"\n\n// IWYU pragma: end_exports\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATN.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <cstddef>\n#include \"atn/LL1Analyzer.h\"\n#include \"atn/ATNState.h\"\n#include \"Token.h\"\n#include \"atn/RuleTransition.h\"\n#include \"misc/IntervalSet.h\"\n#include \"RuleContext.h\"\n#include \"atn/DecisionState.h\"\n#include \"Recognizer.h\"\n#include \"atn/ATNType.h\"\n#include \"Exceptions.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"atn/ATN.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::internal;\nusing namespace antlrcpp;\n\nATN::ATN() : ATN(ATNType::LEXER, 0) {}\n\nATN::ATN(ATNType grammarType_, size_t maxTokenType_) : grammarType(grammarType_), maxTokenType(maxTokenType_) {}\n\nATN::~ATN() {\n  for (ATNState *state : states) {\n    delete state;\n  }\n}\n\nmisc::IntervalSet ATN::nextTokens(ATNState *s, RuleContext *ctx) const {\n  LL1Analyzer analyzer(*this);\n  return analyzer.LOOK(s, ctx);\n\n}\n\nmisc::IntervalSet const& ATN::nextTokens(ATNState *s) const {\n  if (!s->_nextTokenUpdated) {\n    UniqueLock<Mutex> lock(_mutex);\n    if (!s->_nextTokenUpdated) {\n      s->_nextTokenWithinRule = nextTokens(s, nullptr);\n      s->_nextTokenUpdated = true;\n    }\n  }\n  return s->_nextTokenWithinRule;\n}\n\nvoid ATN::addState(ATNState *state) {\n  if (state != nullptr) {\n    //state->atn = this;\n    state->stateNumber = static_cast<int>(states.size());\n  }\n\n  states.push_back(state);\n}\n\nvoid ATN::removeState(ATNState *state) {\n  delete states.at(state->stateNumber);// just free mem, don't shift states in list\n  states.at(state->stateNumber) = nullptr;\n}\n\nint ATN::defineDecisionState(DecisionState *s) {\n  decisionToState.push_back(s);\n  s->decision = static_cast<int>(decisionToState.size() - 1);\n  return s->decision;\n}\n\nDecisionState *ATN::getDecisionState(size_t decision) const {\n  if (!decisionToState.empty()) {\n    return decisionToState[decision];\n  }\n  return nullptr;\n}\n\nsize_t ATN::getNumberOfDecisions() const {\n  return decisionToState.size();\n}\n\nmisc::IntervalSet ATN::getExpectedTokens(size_t stateNumber, RuleContext *context) const {\n  if (stateNumber == ATNState::INVALID_STATE_NUMBER || stateNumber >= states.size()) {\n    throw IllegalArgumentException(\"Invalid state number.\");\n  }\n\n  RuleContext *ctx = context;\n  ATNState *s = states.at(stateNumber);\n  misc::IntervalSet following = nextTokens(s);\n  if (!following.contains(Token::EPSILON)) {\n    return following;\n  }\n\n  misc::IntervalSet expected;\n  expected.addAll(following);\n  expected.remove(Token::EPSILON);\n  while (ctx && ctx->invokingState != ATNState::INVALID_STATE_NUMBER && following.contains(Token::EPSILON)) {\n    ATNState *invokingState = states.at(ctx->invokingState);\n    const RuleTransition *rt = static_cast<const RuleTransition*>(invokingState->transitions[0].get());\n    following = nextTokens(rt->followState);\n    expected.addAll(following);\n    expected.remove(Token::EPSILON);\n\n    if (ctx->parent == nullptr) {\n      break;\n    }\n    ctx = static_cast<RuleContext *>(ctx->parent);\n  }\n\n  if (following.contains(Token::EPSILON)) {\n    expected.add(Token::EOF);\n  }\n\n  return expected;\n}\n\nstd::string ATN::toString() const {\n  std::stringstream ss;\n  std::string type;\n  switch (grammarType) {\n    case ATNType::LEXER:\n      type = \"LEXER \";\n      break;\n\n    case ATNType::PARSER:\n      type = \"PARSER \";\n      break;\n\n    default:\n      break;\n  }\n  ss << \"(\" << type << \"ATN \" << std::hex << this << std::dec << \") maxTokenType: \" << maxTokenType << std::endl;\n  ss << \"states (\" << states.size() << \") {\" << std::endl;\n\n  size_t index = 0;\n  for (auto *state : states) {\n    if (state == nullptr) {\n      ss << \"  \" << index++ << \": nul\" << std::endl;\n    } else {\n      std::string text = state->toString();\n      ss << \"  \" << index++ << \": \" << indent(text, \"  \", false) << std::endl;\n    }\n  }\n\n  index = 0;\n  for (auto *state : decisionToState) {\n    if (state == nullptr) {\n      ss << \"  \" << index++ << \": nul\" << std::endl;\n    } else {\n      std::string text = state->toString();\n      ss << \"  \" << index++ << \": \" << indent(text, \"  \", false) << std::endl;\n    }\n  }\n\n  ss << \"}\";\n\n  return ss.str();\n}\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATN.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"RuleContext.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"internal/Synchronization.h\"\n\n// GCC generates a warning when forward-declaring ATN if ATN has already been\n// declared due to the attributes added by ANTLR4CPP_PUBLIC.\n// See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=39159\n// Add constant that can be checked so forward-declarations can be omitted.\n#define ANTLR4CPP_ATN_DECLARED\n\nnamespace antlr4 {\nnamespace atn {\n\n  class LexerATNSimulator;\n  class ParserATNSimulator;\n\n  class ANTLR4CPP_PUBLIC ATN {\n  public:\n    static constexpr size_t INVALID_ALT_NUMBER = 0;\n\n    /// Used for runtime deserialization of ATNs from strings.\n    ATN();\n\n    ATN(ATNType grammarType, size_t maxTokenType);\n\n    ATN(const ATN&) = delete;\n\n    ATN(ATN&&) = delete;\n\n    ~ATN();\n\n    ATN& operator=(const ATN&) = delete;\n\n    ATN& operator=(ATN&&) = delete;\n\n    std::vector<ATNState *> states;\n\n    /// Each subrule/rule is a decision point and we must track them so we\n    /// can go back later and build DFA predictors for them.  This includes\n    /// all the rules, subrules, optional blocks, ()+, ()* etc...\n    std::vector<DecisionState *> decisionToState;\n\n    /// Maps from rule index to starting state number.\n    std::vector<RuleStartState *> ruleToStartState;\n\n    /// Maps from rule index to stop state number.\n    std::vector<RuleStopState *> ruleToStopState;\n\n    /// The type of the ATN.\n    ATNType grammarType;\n\n    /// The maximum value for any symbol recognized by a transition in the ATN.\n    size_t maxTokenType;\n\n    /// <summary>\n    /// For lexer ATNs, this maps the rule index to the resulting token type.\n    /// For parser ATNs, this maps the rule index to the generated bypass token\n    /// type if the\n    /// <seealso cref=\"ATNDeserializationOptions#isGenerateRuleBypassTransitions\"/>\n    /// deserialization option was specified; otherwise, this is {@code null}.\n    /// </summary>\n    std::vector<size_t> ruleToTokenType;\n\n    /// For lexer ATNs, this is an array of {@link LexerAction} objects which may\n    /// be referenced by action transitions in the ATN.\n    std::vector<Ref<const LexerAction>> lexerActions;\n\n    std::vector<TokensStartState *> modeToStartState;\n\n    /// <summary>\n    /// Compute the set of valid tokens that can occur starting in state {@code s}.\n    ///  If {@code ctx} is null, the set of tokens will not include what can follow\n    ///  the rule surrounding {@code s}. In other words, the set will be\n    ///  restricted to tokens reachable staying within {@code s}'s rule.\n    /// </summary>\n    misc::IntervalSet nextTokens(ATNState *s, RuleContext *ctx) const;\n\n    /// <summary>\n    /// Compute the set of valid tokens that can occur starting in {@code s} and\n    /// staying in same rule. <seealso cref=\"Token#EPSILON\"/> is in set if we reach end of\n    /// rule.\n    /// </summary>\n    misc::IntervalSet const& nextTokens(ATNState *s) const;\n\n    void addState(ATNState *state);\n\n    void removeState(ATNState *state);\n\n    int defineDecisionState(DecisionState *s);\n\n    DecisionState *getDecisionState(size_t decision) const;\n\n    size_t getNumberOfDecisions() const;\n\n    /// <summary>\n    /// Computes the set of input symbols which could follow ATN state number\n    /// {@code stateNumber} in the specified full {@code context}. This method\n    /// considers the complete parser context, but does not evaluate semantic\n    /// predicates (i.e. all predicates encountered during the calculation are\n    /// assumed true). If a path in the ATN exists from the starting state to the\n    /// <seealso cref=\"RuleStopState\"/> of the outermost context without matching any\n    /// symbols, <seealso cref=\"Token#EOF\"/> is added to the returned set.\n    /// <p/>\n    /// If {@code context} is {@code null}, it is treated as\n    /// <seealso cref=\"ParserRuleContext#EMPTY\"/>.\n    /// </summary>\n    /// <param name=\"stateNumber\"> the ATN state number </param>\n    /// <param name=\"context\"> the full parse context </param>\n    /// <returns> The set of potentially valid input symbols which could follow the\n    /// specified state in the specified context. </returns>\n    /// <exception cref=\"IllegalArgumentException\"> if the ATN does not contain a state with\n    /// number {@code stateNumber} </exception>\n    misc::IntervalSet getExpectedTokens(size_t stateNumber, RuleContext *context) const;\n\n    std::string toString() const;\n\n  private:\n    friend class LexerATNSimulator;\n    friend class ParserATNSimulator;\n\n    mutable internal::Mutex _mutex;\n    mutable internal::SharedMutex _stateMutex;\n    mutable internal::SharedMutex _edgeMutex;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNConfig.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContext.h\"\n#include \"SemanticContext.h\"\n\n#include \"atn/ATNConfig.h\"\n\nusing namespace antlr4::atn;\n\nnamespace {\n\n/**\n * This field stores the bit mask for implementing the\n * {@link #isPrecedenceFilterSuppressed} property as a bit within the\n * existing {@link #reachesIntoOuterContext} field.\n */\ninline constexpr size_t SUPPRESS_PRECEDENCE_FILTER = 0x40000000;\n\n}\n\nATNConfig::ATNConfig(ATNState *state, size_t alt, Ref<const PredictionContext> context)\n    : ATNConfig(state, alt, std::move(context), 0, SemanticContext::Empty::Instance) {}\n\nATNConfig::ATNConfig(ATNState *state, size_t alt, Ref<const PredictionContext> context, Ref<const SemanticContext> semanticContext)\n    : ATNConfig(state, alt, std::move(context), 0, std::move(semanticContext)) {}\n\nATNConfig::ATNConfig(ATNConfig const& other, Ref<const SemanticContext> semanticContext)\n    : ATNConfig(other.state, other.alt, other.context, other.reachesIntoOuterContext, std::move(semanticContext)) {}\n\nATNConfig::ATNConfig(ATNConfig const& other, ATNState *state)\n    : ATNConfig(state, other.alt, other.context, other.reachesIntoOuterContext, other.semanticContext) {}\n\nATNConfig::ATNConfig(ATNConfig const& other, ATNState *state, Ref<const SemanticContext> semanticContext)\n    : ATNConfig(state, other.alt, other.context, other.reachesIntoOuterContext, std::move(semanticContext)) {}\n\nATNConfig::ATNConfig(ATNConfig const& other, ATNState *state, Ref<const PredictionContext> context)\n    : ATNConfig(state, other.alt, std::move(context), other.reachesIntoOuterContext, other.semanticContext) {}\n\nATNConfig::ATNConfig(ATNConfig const& other, ATNState *state, Ref<const PredictionContext> context, Ref<const SemanticContext> semanticContext)\n    : ATNConfig(state, other.alt, std::move(context), other.reachesIntoOuterContext, std::move(semanticContext)) {}\n\nATNConfig::ATNConfig(ATNState *state, size_t alt, Ref<const PredictionContext> context, size_t reachesIntoOuterContext, Ref<const SemanticContext> semanticContext)\n    : state(state), alt(alt), context(std::move(context)), reachesIntoOuterContext(reachesIntoOuterContext), semanticContext(std::move(semanticContext)) {}\n\nsize_t ATNConfig::hashCode() const {\n  size_t hashCode = misc::MurmurHash::initialize(7);\n  hashCode = misc::MurmurHash::update(hashCode, state->stateNumber);\n  hashCode = misc::MurmurHash::update(hashCode, alt);\n  hashCode = misc::MurmurHash::update(hashCode, context);\n  hashCode = misc::MurmurHash::update(hashCode, semanticContext);\n  hashCode = misc::MurmurHash::finish(hashCode, 4);\n  return hashCode;\n}\n\nsize_t ATNConfig::getOuterContextDepth() const {\n  return reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER;\n}\n\nbool ATNConfig::isPrecedenceFilterSuppressed() const {\n  return (reachesIntoOuterContext & SUPPRESS_PRECEDENCE_FILTER) != 0;\n}\n\nvoid ATNConfig::setPrecedenceFilterSuppressed(bool value) {\n  if (value) {\n    reachesIntoOuterContext |= SUPPRESS_PRECEDENCE_FILTER;\n  } else {\n    reachesIntoOuterContext &= ~SUPPRESS_PRECEDENCE_FILTER;\n  }\n}\n\nbool ATNConfig::operator==(const ATNConfig &other) const {\n  return state->stateNumber == other.state->stateNumber && alt == other.alt &&\n    ((context == other.context) || (*context == *other.context)) &&\n    *semanticContext == *other.semanticContext &&\n    isPrecedenceFilterSuppressed() == other.isPrecedenceFilterSuppressed();\n}\n\nstd::string ATNConfig::toString() const {\n  return toString(true);\n}\n\nstd::string ATNConfig::toString(bool showAlt) const {\n  std::stringstream ss;\n  ss << \"(\";\n\n  ss << state->toString();\n  if (showAlt) {\n    ss << \",\" << alt;\n  }\n  if (context) {\n    ss << \",[\" << context->toString() << \"]\";\n  }\n  if (semanticContext != nullptr && semanticContext != SemanticContext::Empty::Instance) {\n    ss << \",\" << semanticContext->toString();\n  }\n  if (getOuterContextDepth() > 0) {\n    ss << \",up=\" << getOuterContextDepth();\n  }\n  ss << \")\";\n\n  return ss.str();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNConfig.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <unordered_set>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include <cassert>\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/SemanticContext.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// A tuple: (ATN state, predicted alt, syntactic, semantic context).\n  ///  The syntactic context is a graph-structured stack node whose\n  ///  path(s) to the root is the rule invocation(s)\n  ///  chain used to arrive at the state.  The semantic context is\n  ///  the tree of semantic predicates encountered before reaching\n  ///  an ATN state.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC ATNConfig {\n  public:\n    struct Hasher\n    {\n      size_t operator()(Ref<ATNConfig> const& k) const {\n        return k->hashCode();\n      }\n\n      size_t operator()(ATNConfig const& k) const {\n        return k.hashCode();\n      }\n    };\n\n    struct Comparer {\n      bool operator()(Ref<ATNConfig> const& lhs, Ref<ATNConfig> const& rhs) const {\n        return (lhs == rhs) || (*lhs == *rhs);\n      }\n\n      bool operator()(ATNConfig const& lhs, ATNConfig const& rhs) const {\n        return (&lhs == &rhs) || (lhs == rhs);\n      }\n    };\n\n    using Set = std::unordered_set<Ref<ATNConfig>, Hasher, Comparer>;\n\n    /// The ATN state associated with this configuration.\n    ATNState *state = nullptr;\n\n    /// What alt (or lexer rule) is predicted by this configuration.\n    const size_t alt = 0;\n\n    /// The stack of invoking states leading to the rule/states associated\n    /// with this config.  We track only those contexts pushed during\n    /// execution of the ATN simulator.\n    ///\n    /// Can be shared between multiple ANTConfig instances.\n    Ref<const PredictionContext> context;\n\n    /**\n     * We cannot execute predicates dependent upon local context unless\n     * we know for sure we are in the correct context. Because there is\n     * no way to do this efficiently, we simply cannot evaluate\n     * dependent predicates unless we are in the rule that initially\n     * invokes the ATN simulator.\n     *\n     * <p>\n     * closure() tracks the depth of how far we dip into the outer context:\n     * depth > 0.  Note that it may not be totally accurate depth since I\n     * don't ever decrement. TODO: make it a boolean then</p>\n     *\n     * <p>\n     * For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method\n     * is also backed by this field. Since the field is publicly accessible, the\n     * highest bit which would not cause the value to become negative is used to\n     * store this field. This choice minimizes the risk that code which only\n     * compares this value to 0 would be affected by the new purpose of the\n     * flag. It also ensures the performance of the existing {@link ATNConfig}\n     * constructors as well as certain operations like\n     * {@link ATNConfigSet#add(ATNConfig, DoubleKeyMap)} method are\n     * <em>completely</em> unaffected by the change.</p>\n     */\n    size_t reachesIntoOuterContext = 0;\n\n    /// Can be shared between multiple ATNConfig instances.\n    Ref<const SemanticContext> semanticContext;\n\n    ATNConfig(ATNState *state, size_t alt, Ref<const PredictionContext> context);\n    ATNConfig(ATNState *state, size_t alt, Ref<const PredictionContext> context, Ref<const SemanticContext> semanticContext);\n\n    ATNConfig(ATNConfig const& other, Ref<const SemanticContext> semanticContext);\n    ATNConfig(ATNConfig const& other, ATNState *state);\n    ATNConfig(ATNConfig const& other, ATNState *state, Ref<const SemanticContext> semanticContext);\n    ATNConfig(ATNConfig const& other, ATNState *state, Ref<const PredictionContext> context);\n    ATNConfig(ATNConfig const& other, ATNState *state, Ref<const PredictionContext> context, Ref<const SemanticContext> semanticContext);\n\n    ATNConfig(ATNConfig const&) = default;\n\n    ATNConfig(ATNConfig&&) = default;\n\n    virtual ~ATNConfig() = default;\n\n    virtual size_t hashCode() const;\n\n    /**\n     * This method gets the value of the {@link #reachesIntoOuterContext} field\n     * as it existed prior to the introduction of the\n     * {@link #isPrecedenceFilterSuppressed} method.\n     */\n    size_t getOuterContextDepth() const;\n    bool isPrecedenceFilterSuppressed() const;\n    void setPrecedenceFilterSuppressed(bool value);\n\n    /// An ATN configuration is equal to another if both have\n    /// the same state, they predict the same alternative, and\n    /// syntactic/semantic contexts are the same.\n    bool operator==(const ATNConfig &other) const;\n    bool operator!=(const ATNConfig &other) const;\n\n    virtual std::string toString() const;\n    std::string toString(bool showAlt) const;\n\n  private:\n    ATNConfig(ATNState *state, size_t alt, Ref<const PredictionContext> context, size_t reachesIntoOuterContext, Ref<const SemanticContext> semanticContext);\n  };\n\n} // namespace atn\n} // namespace antlr4\n\n\n// Hash function for ATNConfig.\n\nnamespace std {\n  using antlr4::atn::ATNConfig;\n\n  template <> struct hash<ATNConfig>\n  {\n    size_t operator() (const ATNConfig &x) const\n    {\n      return x.hashCode();\n    }\n  };\n\n  template <> struct hash<std::vector<Ref<ATNConfig>>>\n  {\n    size_t operator() (const std::vector<Ref<ATNConfig>> &vector) const\n    {\n      std::size_t seed = 0;\n      for (const auto &config : vector) {\n        seed ^= config->hashCode() + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n      }\n      return seed;\n    }\n  };\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNConfigSet.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <cassert>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"atn/PredictionContext.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATNConfig.h\"\n#include \"atn/ATNSimulator.h\"\n#include \"Exceptions.h\"\n#include \"atn/SemanticContext.h\"\n#include \"support/Arrays.h\"\n\n#include \"atn/ATNConfigSet.h\"\n\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nnamespace {\n\n}\n\nATNConfigSet::ATNConfigSet() : ATNConfigSet(true) {}\n\nATNConfigSet::ATNConfigSet(const ATNConfigSet &other)\n    : fullCtx(other.fullCtx), _configLookup(other._configLookup.bucket_count(), ATNConfigHasher{this}, ATNConfigComparer{this}) {\n  addAll(other);\n  uniqueAlt = other.uniqueAlt;\n  conflictingAlts = other.conflictingAlts;\n  hasSemanticContext = other.hasSemanticContext;\n  dipsIntoOuterContext = other.dipsIntoOuterContext;\n}\n\nATNConfigSet::ATNConfigSet(bool fullCtx)\n    : fullCtx(fullCtx), _configLookup(0, ATNConfigHasher{this}, ATNConfigComparer{this}) {}\n\nbool ATNConfigSet::add(const Ref<ATNConfig> &config) {\n  return add(config, nullptr);\n}\n\nbool ATNConfigSet::add(const Ref<ATNConfig> &config, PredictionContextMergeCache *mergeCache) {\n  assert(config);\n\n  if (_readonly) {\n    throw IllegalStateException(\"This set is readonly\");\n  }\n  if (config->semanticContext != SemanticContext::Empty::Instance) {\n    hasSemanticContext = true;\n  }\n  if (config->getOuterContextDepth() > 0) {\n    dipsIntoOuterContext = true;\n  }\n\n  auto existing = _configLookup.find(config.get());\n  if (existing == _configLookup.end()) {\n    _configLookup.insert(config.get());\n    _cachedHashCode = 0;\n    configs.push_back(config); // track order here\n\n    return true;\n  }\n\n  // a previous (s,i,pi,_), merge with it and save result\n  bool rootIsWildcard = !fullCtx;\n  Ref<const PredictionContext> merged = PredictionContext::merge((*existing)->context, config->context, rootIsWildcard, mergeCache);\n  // no need to check for existing.context, config.context in cache\n  // since only way to create new graphs is \"call rule\" and here. We\n  // cache at both places.\n  (*existing)->reachesIntoOuterContext = std::max((*existing)->reachesIntoOuterContext, config->reachesIntoOuterContext);\n\n  // make sure to preserve the precedence filter suppression during the merge\n  if (config->isPrecedenceFilterSuppressed()) {\n    (*existing)->setPrecedenceFilterSuppressed(true);\n  }\n\n  (*existing)->context = std::move(merged); // replace context; no need to alt mapping\n\n  return true;\n}\n\nbool ATNConfigSet::addAll(const ATNConfigSet &other) {\n  for (const auto &c : other.configs) {\n    add(c);\n  }\n  return false;\n}\n\nstd::vector<ATNState*> ATNConfigSet::getStates() const {\n  std::vector<ATNState*> states;\n  states.reserve(configs.size());\n  for (const auto &c : configs) {\n    states.push_back(c->state);\n  }\n  return states;\n}\n\n/**\n * Gets the complete set of represented alternatives for the configuration\n * set.\n *\n * @return the set of represented alternatives in this configuration set\n *\n * @since 4.3\n */\n\nBitSet ATNConfigSet::getAlts() const {\n  BitSet alts;\n  for (const auto &config : configs) {\n    alts.set(config->alt);\n  }\n  return alts;\n}\n\nstd::vector<Ref<const SemanticContext>> ATNConfigSet::getPredicates() const {\n  std::vector<Ref<const SemanticContext>> preds;\n  preds.reserve(configs.size());\n  for (const auto &c : configs) {\n    if (c->semanticContext != SemanticContext::Empty::Instance) {\n      preds.push_back(c->semanticContext);\n    }\n  }\n  return preds;\n}\n\nconst Ref<ATNConfig>& ATNConfigSet::get(size_t i) const {\n  return configs[i];\n}\n\nvoid ATNConfigSet::optimizeConfigs(ATNSimulator *interpreter) {\n  assert(interpreter);\n\n  if (_readonly) {\n    throw IllegalStateException(\"This set is readonly\");\n  }\n  if (_configLookup.empty())\n    return;\n\n  for (const auto &config : configs) {\n    config->context = interpreter->getCachedContext(config->context);\n  }\n}\n\nbool ATNConfigSet::equals(const ATNConfigSet &other) const {\n  if (&other == this) {\n    return true;\n  }\n\n  if (configs.size() != other.configs.size())\n    return false;\n\n  if (fullCtx != other.fullCtx || uniqueAlt != other.uniqueAlt ||\n      conflictingAlts != other.conflictingAlts || hasSemanticContext != other.hasSemanticContext ||\n      dipsIntoOuterContext != other.dipsIntoOuterContext) // includes stack context\n    return false;\n\n  return Arrays::equals(configs, other.configs);\n}\n\nsize_t ATNConfigSet::hashCode() const {\n  size_t cachedHashCode = _cachedHashCode.load(std::memory_order_relaxed);\n  if (!isReadonly() || cachedHashCode == 0) {\n    cachedHashCode = 1;\n    for (const auto &i : configs) {\n      cachedHashCode = 31 * cachedHashCode + i->hashCode(); // Same as Java's list hashCode impl.\n    }\n    _cachedHashCode.store(cachedHashCode, std::memory_order_relaxed);\n  }\n  return cachedHashCode;\n}\n\nsize_t ATNConfigSet::size() const {\n  return configs.size();\n}\n\nbool ATNConfigSet::isEmpty() const {\n  return configs.empty();\n}\n\nvoid ATNConfigSet::clear() {\n  if (_readonly) {\n    throw IllegalStateException(\"This set is readonly\");\n  }\n  configs.clear();\n  _cachedHashCode = 0;\n  _configLookup.clear();\n}\n\nbool ATNConfigSet::isReadonly() const {\n  return _readonly;\n}\n\nvoid ATNConfigSet::setReadonly(bool readonly) {\n  _readonly = readonly;\n  LookupContainer(0, ATNConfigHasher{this}, ATNConfigComparer{this}).swap(_configLookup);\n}\n\nstd::string ATNConfigSet::toString() const {\n  std::stringstream ss;\n  ss << \"[\";\n  for (size_t i = 0; i < configs.size(); i++) {\n    if ( i>0 ) ss << \", \";\n    ss << configs[i]->toString();\n  }\n  ss << \"]\";\n\n  if (hasSemanticContext) {\n    ss << \",hasSemanticContext=\" << (hasSemanticContext?\"true\":\"false\");\n  }\n  if (uniqueAlt != ATN::INVALID_ALT_NUMBER) {\n    ss << \",uniqueAlt=\" << uniqueAlt;\n  }\n\n  if (conflictingAlts.count() > 0) {\n    ss << \",conflictingAlts=\";\n    ss << conflictingAlts.toString();\n  }\n\n  if (dipsIntoOuterContext) {\n    ss << \",dipsIntoOuterContext\";\n  }\n  return ss.str();\n}\n\nsize_t ATNConfigSet::hashCode(const ATNConfig &other) const {\n  size_t hashCode = 7;\n  hashCode = 31 * hashCode + other.state->stateNumber;\n  hashCode = 31 * hashCode + other.alt;\n  hashCode = 31 * hashCode + other.semanticContext->hashCode();\n  return hashCode;\n}\n\nbool ATNConfigSet::equals(const ATNConfig &lhs, const ATNConfig &rhs) const {\n  return lhs.state->stateNumber == rhs.state->stateNumber && lhs.alt == rhs.alt && *lhs.semanticContext == *rhs.semanticContext;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNConfigSet.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include <cassert>\n\n#include \"support/BitSet.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContext.h\"\n#include \"atn/ATNConfig.h\"\n#include \"FlatHashSet.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Specialized set that can track info about the set, with support for combining similar configurations using a\n  /// graph-structured stack.\n  class ANTLR4CPP_PUBLIC ATNConfigSet {\n  public:\n    /// Track the elements as they are added to the set; supports get(i)\n    std::vector<Ref<ATNConfig>> configs;\n\n    // TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation\n    // TODO: can we track conflicts as they are added to save scanning configs later?\n    size_t uniqueAlt = 0;\n\n    /** Currently this is only used when we detect SLL conflict; this does\n     *  not necessarily represent the ambiguous alternatives. In fact,\n     *  I should also point out that this seems to include predicated alternatives\n     *  that have predicates that evaluate to false. Computed in computeTargetState().\n     */\n    antlrcpp::BitSet conflictingAlts;\n\n    // Used in parser and lexer. In lexer, it indicates we hit a pred\n    // while computing a closure operation.  Don't make a DFA state from this.\n    bool hasSemanticContext = false;\n    bool dipsIntoOuterContext = false;\n\n    /// Indicates that this configuration set is part of a full context\n    /// LL prediction. It will be used to determine how to merge $. With SLL\n    /// it's a wildcard whereas it is not for LL context merge.\n    const bool fullCtx = true;\n\n    ATNConfigSet();\n\n    ATNConfigSet(const ATNConfigSet &other);\n\n    ATNConfigSet(ATNConfigSet&&) = delete;\n\n    explicit ATNConfigSet(bool fullCtx);\n\n    virtual ~ATNConfigSet() = default;\n\n    bool add(const Ref<ATNConfig> &config);\n\n    /// <summary>\n    /// Adding a new config means merging contexts with existing configs for\n    /// {@code (s, i, pi, _)}, where {@code s} is the\n    /// <seealso cref=\"ATNConfig#state\"/>, {@code i} is the <seealso cref=\"ATNConfig#alt\"/>, and\n    /// {@code pi} is the <seealso cref=\"ATNConfig#semanticContext\"/>. We use\n    /// {@code (s,i,pi)} as key.\n    /// <p/>\n    /// This method updates <seealso cref=\"#dipsIntoOuterContext\"/> and\n    /// <seealso cref=\"#hasSemanticContext\"/> when necessary.\n    /// </summary>\n    bool add(const Ref<ATNConfig> &config, PredictionContextMergeCache *mergeCache);\n\n    bool addAll(const ATNConfigSet &other);\n\n    std::vector<ATNState*> getStates() const;\n\n    /**\n     * Gets the complete set of represented alternatives for the configuration\n     * set.\n     *\n     * @return the set of represented alternatives in this configuration set\n     *\n     * @since 4.3\n     */\n    antlrcpp::BitSet getAlts() const;\n    std::vector<Ref<const SemanticContext>> getPredicates() const;\n\n    const Ref<ATNConfig>& get(size_t i) const;\n\n    void optimizeConfigs(ATNSimulator *interpreter);\n\n    size_t size() const;\n    bool isEmpty() const;\n    void clear();\n    bool isReadonly() const;\n    void setReadonly(bool readonly);\n\n    virtual size_t hashCode() const;\n\n    virtual bool equals(const ATNConfigSet &other) const;\n\n    virtual std::string toString() const;\n\n  private:\n    struct ATNConfigHasher final {\n      const ATNConfigSet* atnConfigSet;\n\n      size_t operator()(const ATNConfig *other) const {\n        assert(other != nullptr);\n        return atnConfigSet->hashCode(*other);\n      }\n    };\n\n    struct ATNConfigComparer final {\n      const ATNConfigSet* atnConfigSet;\n\n      bool operator()(const ATNConfig *lhs, const ATNConfig *rhs) const {\n        assert(lhs != nullptr);\n        assert(rhs != nullptr);\n        return atnConfigSet->equals(*lhs, *rhs);\n      }\n    };\n\n    mutable std::atomic<size_t> _cachedHashCode = 0;\n\n    /// Indicates that the set of configurations is read-only. Do not\n    /// allow any code to manipulate the set; DFA states will point at\n    /// the sets and they must not change. This does not protect the other\n    /// fields; in particular, conflictingAlts is set after\n    /// we've made this readonly.\n    bool _readonly = false;\n\n    virtual size_t hashCode(const ATNConfig &atnConfig) const;\n\n    virtual bool equals(const ATNConfig &lhs, const ATNConfig &rhs) const;\n\n    using LookupContainer = FlatHashSet<ATNConfig*, ATNConfigHasher, ATNConfigComparer>;\n\n    /// All configs but hashed by (s, i, _, pi) not including context. Wiped out\n    /// when we go readonly as this set becomes a DFA state.\n    LookupContainer _configLookup;\n  };\n\n  inline bool operator==(const ATNConfigSet &lhs, const ATNConfigSet &rhs) { return lhs.equals(rhs); }\n\n  inline bool operator!=(const ATNConfigSet &lhs, const ATNConfigSet &rhs) { return !operator==(lhs, rhs); }\n\n} // namespace atn\n} // namespace antlr4\n\nnamespace std {\n\ntemplate <>\nstruct hash<::antlr4::atn::ATNConfigSet> {\n  size_t operator()(const ::antlr4::atn::ATNConfigSet &atnConfigSet) const {\n    return atnConfigSet.hashCode();\n  }\n};\n\n} // namespace std\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNDeserializationOptions.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include \"atn/ATNDeserializationOptions.h\"\n#include \"Exceptions.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nATNDeserializationOptions::ATNDeserializationOptions(ATNDeserializationOptions *options)\n    : _readOnly(false), _verifyATN(options->_verifyATN),\n      _generateRuleBypassTransitions(options->_generateRuleBypassTransitions) {}\n\nconst ATNDeserializationOptions& ATNDeserializationOptions::getDefaultOptions() {\n  static const std::unique_ptr<const ATNDeserializationOptions> defaultOptions = std::make_unique<const ATNDeserializationOptions>();\n  return *defaultOptions;\n}\n\nvoid ATNDeserializationOptions::makeReadOnly() {\n  _readOnly = true;\n}\n\nvoid ATNDeserializationOptions::setVerifyATN(bool verify) {\n  throwIfReadOnly();\n  _verifyATN = verify;\n}\n\nvoid ATNDeserializationOptions::setGenerateRuleBypassTransitions(bool generate) {\n  throwIfReadOnly();\n  _generateRuleBypassTransitions = generate;\n}\n\nvoid ATNDeserializationOptions::throwIfReadOnly() const {\n  if (isReadOnly()) {\n    throw IllegalStateException(\"ATNDeserializationOptions is read only.\");\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNDeserializationOptions.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\nclass ANTLR4CPP_PUBLIC ATNDeserializationOptions final {\npublic:\n  ATNDeserializationOptions()\n    : _readOnly(false), _verifyATN(true), _generateRuleBypassTransitions(false) {}\n\n  // TODO: Is this useful? If so we should mark it as explicit, otherwise remove it.\n  ATNDeserializationOptions(ATNDeserializationOptions *options);\n\n  ATNDeserializationOptions(const ATNDeserializationOptions&) = default;\n\n  ATNDeserializationOptions& operator=(const ATNDeserializationOptions&) = default;\n\n  static const ATNDeserializationOptions& getDefaultOptions();\n\n  bool isReadOnly() const { return _readOnly; }\n\n  void makeReadOnly();\n\n  bool isVerifyATN() const { return _verifyATN; }\n\n  void setVerifyATN(bool verify);\n\n  bool isGenerateRuleBypassTransitions() const { return _generateRuleBypassTransitions; }\n\n  void setGenerateRuleBypassTransitions(bool generate);\n\nprivate:\n  void throwIfReadOnly() const;\n\n  bool _readOnly;\n  bool _verifyATN;\n  bool _generateRuleBypassTransitions;\n};\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNDeserializer.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"atn/ATNDeserializationOptions.h\"\n\n#include \"atn/ATNStateType.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATNType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/ATN.h\"\n\n#include \"atn/LoopEndState.h\"\n#include \"atn/DecisionState.h\"\n#include \"atn/RuleStartState.h\"\n#include \"atn/RuleStopState.h\"\n#include \"atn/TokensStartState.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/EpsilonTransition.h\"\n#include \"atn/PlusLoopbackState.h\"\n#include \"atn/PlusBlockStartState.h\"\n#include \"atn/StarLoopbackState.h\"\n#include \"atn/BasicBlockStartState.h\"\n#include \"atn/BasicState.h\"\n#include \"atn/BlockEndState.h\"\n#include \"atn/StarLoopEntryState.h\"\n\n#include \"atn/AtomTransition.h\"\n#include \"atn/StarBlockStartState.h\"\n#include \"atn/RangeTransition.h\"\n#include \"atn/PredicateTransition.h\"\n#include \"atn/PrecedencePredicateTransition.h\"\n#include \"atn/ActionTransition.h\"\n#include \"atn/SetTransition.h\"\n#include \"atn/NotSetTransition.h\"\n#include \"atn/WildcardTransition.h\"\n#include \"atn/TransitionType.h\"\n#include \"Token.h\"\n\n#include \"misc/IntervalSet.h\"\n#include \"Exceptions.h\"\n#include \"support/CPPUtils.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerCustomAction.h\"\n#include \"atn/LexerChannelAction.h\"\n#include \"atn/LexerModeAction.h\"\n#include \"atn/LexerMoreAction.h\"\n#include \"atn/LexerPopModeAction.h\"\n#include \"atn/LexerPushModeAction.h\"\n#include \"atn/LexerSkipAction.h\"\n#include \"atn/LexerTypeAction.h\"\n\n#include \"atn/ATNDeserializer.h\"\n\n#include <string_view>\n#include <memory>\n#include <utility>\n#include <cstddef>\n#include <cassert>\n#include <string>\n#include <vector>\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nnamespace {\n\n  void checkCondition(bool condition, std::string_view message) {\n    if (!condition) {\n      throw IllegalStateException(std::string(message));\n    }\n  }\n\n  void checkCondition(bool condition) {\n    checkCondition(condition, \"\");\n  }\n\n  /**\n   * Analyze the {@link StarLoopEntryState} states in the specified ATN to set\n   * the {@link StarLoopEntryState#isPrecedenceDecision} field to the\n   * correct value.\n   *\n   * @param atn The ATN.\n   */\n  void markPrecedenceDecisions(const ATN &atn) {\n    for (ATNState *state : atn.states) {\n      if (!StarLoopEntryState::is(state)) {\n        continue;\n      }\n\n      /* We analyze the ATN to determine if this ATN decision state is the\n      * decision for the closure block that determines whether a\n      * precedence rule should continue or complete.\n      */\n      if (atn.ruleToStartState[state->ruleIndex]->isLeftRecursiveRule) {\n        ATNState *maybeLoopEndState = state->transitions[state->transitions.size() - 1]->target;\n        if (LoopEndState::is(maybeLoopEndState)) {\n          if (maybeLoopEndState->epsilonOnlyTransitions && RuleStopState::is(maybeLoopEndState->transitions[0]->target)) {\n            downCast<StarLoopEntryState*>(state)->isPrecedenceDecision = true;\n          }\n        }\n      }\n    }\n  }\n\n  Ref<const LexerAction> lexerActionFactory(LexerActionType type, int data1, int data2) {\n    switch (type) {\n      case LexerActionType::CHANNEL:\n        return std::make_shared<LexerChannelAction>(data1);\n\n      case LexerActionType::CUSTOM:\n        return std::make_shared<LexerCustomAction>(data1, data2);\n\n      case LexerActionType::MODE:\n        return std::make_shared< LexerModeAction>(data1);\n\n      case LexerActionType::MORE:\n        return LexerMoreAction::getInstance();\n\n      case LexerActionType::POP_MODE:\n        return LexerPopModeAction::getInstance();\n\n      case LexerActionType::PUSH_MODE:\n        return std::make_shared<LexerPushModeAction>(data1);\n\n      case LexerActionType::SKIP:\n        return LexerSkipAction::getInstance();\n\n      case LexerActionType::TYPE:\n        return std::make_shared<LexerTypeAction>(data1);\n\n      default:\n        throw IllegalArgumentException(\"The specified lexer action type \" + std::to_string(static_cast<size_t>(type)) +\n                                      \" is not valid.\");\n    }\n  }\n\n  ConstTransitionPtr edgeFactory(const ATN &atn, TransitionType type, size_t trg, size_t arg1, size_t arg2,\n                                        size_t arg3, const std::vector<misc::IntervalSet> &sets) {\n    ATNState *target = atn.states[trg];\n    switch (type) {\n      case TransitionType::EPSILON:\n        return std::make_unique<EpsilonTransition>(target);\n      case TransitionType::RANGE:\n        if (arg3 != 0) {\n          return std::make_unique<RangeTransition>(target, Token::EOF, arg2);\n        } else {\n          return std::make_unique<RangeTransition>(target, arg1, arg2);\n        }\n      case TransitionType::RULE:\n        return std::make_unique<RuleTransition>(downCast<RuleStartState*>(atn.states[arg1]), arg2, (int)arg3, target);\n      case TransitionType::PREDICATE:\n        return std::make_unique<PredicateTransition>(target, arg1, arg2, arg3 != 0);\n      case TransitionType::PRECEDENCE:\n        return std::make_unique<PrecedencePredicateTransition>(target, (int)arg1);\n      case TransitionType::ATOM:\n        if (arg3 != 0) {\n          return std::make_unique<AtomTransition>(target, Token::EOF);\n        } else {\n          return std::make_unique<AtomTransition>(target, arg1);\n        }\n      case TransitionType::ACTION:\n        return std::make_unique<ActionTransition>(target, arg1, arg2, arg3 != 0);\n      case TransitionType::SET:\n        return std::make_unique<SetTransition>(target, sets[arg1]);\n      case TransitionType::NOT_SET:\n        return std::make_unique<NotSetTransition>(target, sets[arg1]);\n      case TransitionType::WILDCARD:\n        return std::make_unique<WildcardTransition>(target);\n    }\n\n    throw IllegalArgumentException(\"The specified transition type is not valid.\");\n  }\n\n  /* mem check: all created instances are freed in the d-tor of the ATN. */\n  ATNState* stateFactory(ATNStateType type, size_t ruleIndex) {\n    ATNState *s;\n    switch (type) {\n      case ATNStateType::INVALID:\n        return nullptr;\n      case ATNStateType::BASIC :\n        s = new BasicState();\n        break;\n      case ATNStateType::RULE_START :\n        s = new RuleStartState();\n        break;\n      case ATNStateType::BLOCK_START :\n        s = new BasicBlockStartState();\n        break;\n      case ATNStateType::PLUS_BLOCK_START :\n        s = new PlusBlockStartState();\n        break;\n      case ATNStateType::STAR_BLOCK_START :\n        s = new StarBlockStartState();\n        break;\n      case ATNStateType::TOKEN_START :\n        s = new TokensStartState();\n        break;\n      case ATNStateType::RULE_STOP :\n        s = new RuleStopState();\n        break;\n      case ATNStateType::BLOCK_END :\n        s = new BlockEndState();\n        break;\n      case ATNStateType::STAR_LOOP_BACK :\n        s = new StarLoopbackState();\n        break;\n      case ATNStateType::STAR_LOOP_ENTRY :\n        s = new StarLoopEntryState();\n        break;\n      case ATNStateType::PLUS_LOOP_BACK :\n        s = new PlusLoopbackState();\n        break;\n      case ATNStateType::LOOP_END :\n        s = new LoopEndState();\n        break;\n      default :\n        std::string message = \"The specified state type \" + std::to_string(static_cast<size_t>(type)) + \" is not valid.\";\n        throw IllegalArgumentException(message);\n    }\n    assert(s->getStateType() == type);\n    s->ruleIndex = ruleIndex;\n    return s;\n  }\n\n  ssize_t readUnicodeInt32(SerializedATNView data, int& p) {\n    return static_cast<ssize_t>(data[p++]);\n  }\n\n  void deserializeSets(\n    SerializedATNView data,\n    int& p,\n    std::vector<misc::IntervalSet>& sets) {\n    size_t nsets = data[p++];\n    sets.reserve(sets.size() + nsets);\n    for (size_t i = 0; i < nsets; i++) {\n      size_t nintervals = data[p++];\n      misc::IntervalSet set;\n\n      bool containsEof = data[p++] != 0;\n      if (containsEof) {\n        set.add(-1);\n      }\n\n      for (size_t j = 0; j < nintervals; j++) {\n        auto a = readUnicodeInt32(data, p);\n        auto b = readUnicodeInt32(data, p);\n        set.add(a, b);\n      }\n      sets.push_back(set);\n    }\n  }\n\n}\n\nATNDeserializer::ATNDeserializer() : ATNDeserializer(ATNDeserializationOptions::getDefaultOptions()) {}\n\nATNDeserializer::ATNDeserializer(ATNDeserializationOptions deserializationOptions) : _deserializationOptions(std::move(deserializationOptions)) {}\n\nstd::unique_ptr<ATN> ATNDeserializer::deserialize(SerializedATNView data) const {\n  int p = 0;\n  int version = data[p++];\n  if (version != SERIALIZED_VERSION) {\n    std::string reason = \"Could not deserialize ATN with version\" + std::to_string(version) + \"(expected \" + std::to_string(SERIALIZED_VERSION) + \").\";\n\n    throw UnsupportedOperationException(reason);\n  }\n\n  ATNType grammarType = (ATNType)data[p++];\n  size_t maxTokenType = data[p++];\n  auto atn = std::make_unique<ATN>(grammarType, maxTokenType);\n\n  //\n  // STATES\n  //\n  {\n    std::vector<std::pair<LoopEndState*, size_t>> loopBackStateNumbers;\n    std::vector<std::pair<BlockStartState*, size_t>> endStateNumbers;\n    size_t nstates = data[p++];\n    atn->states.reserve(nstates);\n    loopBackStateNumbers.reserve(nstates);  // Reserve worst case size, its short lived.\n    endStateNumbers.reserve(nstates);  // Reserve worst case size, its short lived.\n    for (size_t i = 0; i < nstates; i++) {\n      ATNStateType stype = static_cast<ATNStateType>(data[p++]);\n      // ignore bad type of states\n      if (stype == ATNStateType::INVALID) {\n        atn->addState(nullptr);\n        continue;\n      }\n\n      size_t ruleIndex = data[p++];\n      ATNState *s = stateFactory(stype, ruleIndex);\n      if (stype == ATNStateType::LOOP_END) { // special case\n        int loopBackStateNumber = data[p++];\n        loopBackStateNumbers.push_back({ downCast<LoopEndState*>(s),  loopBackStateNumber });\n      } else if (BlockStartState::is(s)) {\n        int endStateNumber = data[p++];\n        endStateNumbers.push_back({ downCast<BlockStartState*>(s), endStateNumber });\n      }\n      atn->addState(s);\n    }\n\n    // delay the assignment of loop back and end states until we know all the state instances have been initialized\n    for (auto &pair : loopBackStateNumbers) {\n      pair.first->loopBackState = atn->states[pair.second];\n    }\n\n    for (auto &pair : endStateNumbers) {\n      pair.first->endState = downCast<BlockEndState*>(atn->states[pair.second]);\n    }\n  }\n\n  size_t numNonGreedyStates = data[p++];\n  for (size_t i = 0; i < numNonGreedyStates; i++) {\n    size_t stateNumber = data[p++];\n    // The serialized ATN must be specifying the right states, so that the\n    // cast below is correct.\n    downCast<DecisionState*>(atn->states[stateNumber])->nonGreedy = true;\n  }\n\n  size_t numPrecedenceStates = data[p++];\n  for (size_t i = 0; i < numPrecedenceStates; i++) {\n    size_t stateNumber = data[p++];\n    downCast<RuleStartState*>(atn->states[stateNumber])->isLeftRecursiveRule = true;\n  }\n\n  //\n  // RULES\n  //\n  size_t nrules = data[p++];\n  atn->ruleToStartState.reserve(nrules);\n  for (size_t i = 0; i < nrules; i++) {\n    size_t s = data[p++];\n    // Also here, the serialized atn must ensure to point to the correct class type.\n    RuleStartState *startState = downCast<RuleStartState*>(atn->states[s]);\n    atn->ruleToStartState.push_back(startState);\n    if (atn->grammarType == ATNType::LEXER) {\n      size_t tokenType = data[p++];\n      atn->ruleToTokenType.push_back(tokenType);\n    }\n  }\n\n  atn->ruleToStopState.resize(nrules);\n  for (ATNState *state : atn->states) {\n    if (!RuleStopState::is(state)) {\n      continue;\n    }\n\n    RuleStopState *stopState = downCast<RuleStopState*>(state);\n    atn->ruleToStopState[state->ruleIndex] = stopState;\n    atn->ruleToStartState[state->ruleIndex]->stopState = stopState;\n  }\n\n  //\n  // MODES\n  //\n  size_t nmodes = data[p++];\n  atn->modeToStartState.reserve(nmodes);\n  for (size_t i = 0; i < nmodes; i++) {\n    size_t s = data[p++];\n    atn->modeToStartState.push_back(downCast<TokensStartState*>(atn->states[s]));\n  }\n\n  //\n  // SETS\n  //\n  {\n    std::vector<misc::IntervalSet> sets;\n\n    deserializeSets(data, p, sets);\n    sets.shrink_to_fit();\n\n    //\n    // EDGES\n    //\n    int nedges = data[p++];\n    for (int i = 0; i < nedges; i++) {\n      size_t src = data[p];\n      size_t trg = data[p + 1];\n      TransitionType ttype = static_cast<TransitionType>(data[p + 2]);\n      size_t arg1 = data[p + 3];\n      size_t arg2 = data[p + 4];\n      size_t arg3 = data[p + 5];\n      ConstTransitionPtr trans = edgeFactory(*atn, ttype, trg, arg1, arg2, arg3, sets);\n      ATNState *srcState = atn->states[src];\n      srcState->addTransition(std::move(trans));\n      p += 6;\n    }\n  }\n  // edges for rule stop states can be derived, so they aren't serialized\n  for (ATNState *state : atn->states) {\n    for (size_t i = 0; i < state->transitions.size(); i++) {\n      const Transition *t = state->transitions[i].get();\n      if (!RuleTransition::is(t)) {\n        continue;\n      }\n\n      const RuleTransition *ruleTransition = downCast<const RuleTransition*>(t);\n      size_t outermostPrecedenceReturn = INVALID_INDEX;\n      if (atn->ruleToStartState[ruleTransition->target->ruleIndex]->isLeftRecursiveRule) {\n        if (ruleTransition->precedence == 0) {\n          outermostPrecedenceReturn = ruleTransition->target->ruleIndex;\n        }\n      }\n\n      ConstTransitionPtr returnTransition = std::make_unique<EpsilonTransition>(ruleTransition->followState, outermostPrecedenceReturn);\n      atn->ruleToStopState[ruleTransition->target->ruleIndex]->addTransition(std::move(returnTransition));\n    }\n  }\n\n  for (ATNState *state : atn->states) {\n    if (BlockStartState::is(state)) {\n      BlockStartState *startState = downCast<BlockStartState*>(state);\n\n      // we need to know the end state to set its start state\n      if (startState->endState == nullptr) {\n        throw IllegalStateException();\n      }\n\n      // block end states can only be associated to a single block start state\n      if (startState->endState->startState != nullptr) {\n        throw IllegalStateException();\n      }\n\n      startState->endState->startState = downCast<BlockStartState*>(state);\n    }\n\n    if (PlusLoopbackState::is(state)) {\n      PlusLoopbackState *loopbackState = downCast<PlusLoopbackState*>(state);\n      for (size_t i = 0; i < loopbackState->transitions.size(); i++) {\n        ATNState *target = loopbackState->transitions[i]->target;\n        if (PlusBlockStartState::is(target)) {\n          (downCast<PlusBlockStartState*>(target))->loopBackState = loopbackState;\n        }\n      }\n    } else if (StarLoopbackState::is(state)) {\n      StarLoopbackState *loopbackState = downCast<StarLoopbackState*>(state);\n      for (size_t i = 0; i < loopbackState->transitions.size(); i++) {\n        ATNState *target = loopbackState->transitions[i]->target;\n        if (StarLoopEntryState::is(target)) {\n          downCast<StarLoopEntryState*>(target)->loopBackState = loopbackState;\n        }\n      }\n    }\n  }\n\n  //\n  // DECISIONS\n  //\n  size_t ndecisions = data[p++];\n  atn->decisionToState.reserve(ndecisions);\n  for (size_t i = 0; i < ndecisions; i++) {\n    size_t s = data[p++];\n    DecisionState *decState = downCast<DecisionState*>(atn->states[s]);\n    if (decState == nullptr)\n      throw IllegalStateException();\n\n    atn->decisionToState.push_back(decState);\n    decState->decision = static_cast<int>(i);\n  }\n\n  //\n  // LEXER ACTIONS\n  //\n  if (atn->grammarType == ATNType::LEXER) {\n    atn->lexerActions.resize(data[p++]);\n    for (size_t i = 0; i < atn->lexerActions.size(); i++) {\n      LexerActionType actionType = static_cast<LexerActionType>(data[p++]);\n      int data1 = data[p++];\n      int data2 = data[p++];\n      atn->lexerActions[i] = lexerActionFactory(actionType, data1, data2);\n    }\n  }\n\n  markPrecedenceDecisions(*atn);\n\n  if (_deserializationOptions.isVerifyATN()) {\n    verifyATN(*atn);\n  }\n\n  if (_deserializationOptions.isGenerateRuleBypassTransitions() && atn->grammarType == ATNType::PARSER) {\n    atn->ruleToTokenType.resize(atn->ruleToStartState.size());\n    for (size_t i = 0; i < atn->ruleToStartState.size(); i++) {\n      atn->ruleToTokenType[i] = static_cast<int>(atn->maxTokenType + i + 1);\n    }\n\n    for (std::vector<RuleStartState*>::size_type i = 0; i < atn->ruleToStartState.size(); i++) {\n      BasicBlockStartState *bypassStart = new BasicBlockStartState(); /* mem check: freed in ATN d-tor */\n      bypassStart->ruleIndex = static_cast<int>(i);\n      atn->addState(bypassStart);\n\n      BlockEndState *bypassStop = new BlockEndState(); /* mem check: freed in ATN d-tor */\n      bypassStop->ruleIndex = static_cast<int>(i);\n      atn->addState(bypassStop);\n\n      bypassStart->endState = bypassStop;\n      atn->defineDecisionState(bypassStart);\n\n      bypassStop->startState = bypassStart;\n\n      ATNState *endState;\n      const Transition *excludeTransition = nullptr;\n      if (atn->ruleToStartState[i]->isLeftRecursiveRule) {\n        // wrap from the beginning of the rule to the StarLoopEntryState\n        endState = nullptr;\n        for (ATNState *state : atn->states) {\n          if (state->ruleIndex != i) {\n            continue;\n          }\n\n          if (!StarLoopEntryState::is(state)) {\n            continue;\n          }\n\n          ATNState *maybeLoopEndState = state->transitions[state->transitions.size() - 1]->target;\n          if (!LoopEndState::is(maybeLoopEndState)) {\n            continue;\n          }\n\n          if (maybeLoopEndState->epsilonOnlyTransitions && RuleStopState::is(maybeLoopEndState->transitions[0]->target)) {\n            endState = state;\n            break;\n          }\n        }\n\n        if (endState == nullptr) {\n          throw UnsupportedOperationException(\"Couldn't identify final state of the precedence rule prefix section.\");\n\n        }\n\n        excludeTransition = (static_cast<StarLoopEntryState*>(endState))->loopBackState->transitions[0].get();\n      } else {\n        endState = atn->ruleToStopState[i];\n      }\n\n      // all non-excluded transitions that currently target end state need to target blockEnd instead\n      for (ATNState *state : atn->states) {\n        for (auto &transition : state->transitions) {\n          if (transition.get() == excludeTransition) {\n            continue;\n          }\n\n          if (transition->target == endState) {\n            const_cast<Transition*>(transition.get())->target = bypassStop;\n          }\n        }\n      }\n\n      // all transitions leaving the rule start state need to leave blockStart instead\n      while (atn->ruleToStartState[i]->transitions.size() > 0) {\n        ConstTransitionPtr transition = atn->ruleToStartState[i]->removeTransition(atn->ruleToStartState[i]->transitions.size() - 1);\n        bypassStart->addTransition(std::move(transition));\n      }\n\n      // link the new states\n      atn->ruleToStartState[i]->addTransition(std::make_unique<EpsilonTransition>(bypassStart));\n      bypassStop->addTransition(std::make_unique<EpsilonTransition>(endState));\n\n      ATNState *matchState = new BasicState(); /* mem check: freed in ATN d-tor */\n      atn->addState(matchState);\n      matchState->addTransition(std::make_unique<AtomTransition>(bypassStop, atn->ruleToTokenType[i]));\n      bypassStart->addTransition(std::make_unique<EpsilonTransition>(matchState));\n    }\n\n    if (_deserializationOptions.isVerifyATN()) {\n      // reverify after modification\n      verifyATN(*atn);\n    }\n  }\n\n  return atn;\n}\n\nvoid ATNDeserializer::verifyATN(const ATN &atn) const {\n  // verify assumptions\n  for (ATNState *state : atn.states) {\n    if (state == nullptr) {\n      continue;\n    }\n\n    checkCondition(state->epsilonOnlyTransitions || state->transitions.size() <= 1);\n\n    if (PlusBlockStartState::is(state)) {\n      checkCondition((downCast<PlusBlockStartState*>(state))->loopBackState != nullptr);\n    }\n\n    if (StarLoopEntryState::is(state)) {\n      StarLoopEntryState *starLoopEntryState = downCast<StarLoopEntryState*>(state);\n      checkCondition(starLoopEntryState->loopBackState != nullptr);\n      checkCondition(starLoopEntryState->transitions.size() == 2);\n\n      if (StarBlockStartState::is(starLoopEntryState->transitions[0]->target)) {\n        checkCondition(downCast<LoopEndState*>(starLoopEntryState->transitions[1]->target) != nullptr);\n        checkCondition(!starLoopEntryState->nonGreedy);\n      } else if (LoopEndState::is(starLoopEntryState->transitions[0]->target)) {\n        checkCondition(StarBlockStartState::is(starLoopEntryState->transitions[1]->target));\n        checkCondition(starLoopEntryState->nonGreedy);\n      } else {\n        throw IllegalStateException();\n      }\n    }\n\n    if (StarLoopbackState::is(state)) {\n      checkCondition(state->transitions.size() == 1);\n      checkCondition(StarLoopEntryState::is(state->transitions[0]->target));\n    }\n\n    if (LoopEndState::is(state)) {\n      checkCondition((downCast<LoopEndState*>(state))->loopBackState != nullptr);\n    }\n\n    if (RuleStartState::is(state)) {\n      checkCondition((downCast<RuleStartState*>(state))->stopState != nullptr);\n    }\n\n    if (BlockStartState::is(state)) {\n      checkCondition((downCast<BlockStartState*>(state))->endState != nullptr);\n    }\n\n    if (BlockEndState::is(state)) {\n      checkCondition((downCast<BlockEndState*>(state))->startState != nullptr);\n    }\n\n    if (DecisionState::is(state)) {\n      DecisionState *decisionState = downCast<DecisionState*>(state);\n      checkCondition(decisionState->transitions.size() <= 1 || decisionState->decision >= 0);\n    } else {\n      checkCondition(state->transitions.size() <= 1 || RuleStopState::is(state));\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNDeserializer.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <cstddef>\n#include \"atn/ATNDeserializationOptions.h\"\n#include \"antlr4-common.h\"\n#include \"atn/SerializedATNView.h\"\n#include \"atn/LexerAction.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC ATNDeserializer final {\n  public:\n    static constexpr size_t SERIALIZED_VERSION = 4;\n\n    ATNDeserializer();\n\n    explicit ATNDeserializer(ATNDeserializationOptions deserializationOptions);\n\n    std::unique_ptr<ATN> deserialize(SerializedATNView input) const;\n    void verifyATN(const ATN &atn) const;\n\n  private:\n    const ATNDeserializationOptions _deserializationOptions;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNSimulator.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <limits>\n#include <memory>\n#include \"atn/ATNSimulator.h\"\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNConfigSet.h\"\n#include \"atn/ATNDeserializer.h\"\n#include \"atn/ATNType.h\"\n#include \"dfa/DFAState.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::dfa;\nusing namespace antlr4::atn;\n\nconst Ref<DFAState> ATNSimulator::ERROR = std::make_shared<DFAState>(std::numeric_limits<int>::max());\n\nATNSimulator::ATNSimulator(const ATN &atn, PredictionContextCache &sharedContextCache)\n    : atn(atn), _sharedContextCache(sharedContextCache) {}\n\nvoid ATNSimulator::clearDFA() {\n  throw UnsupportedOperationException(\"This ATN simulator does not support clearing the DFA.\");\n}\n\nPredictionContextCache& ATNSimulator::getSharedContextCache() const {\n  return _sharedContextCache;\n}\n\nRef<const PredictionContext> ATNSimulator::getCachedContext(const Ref<const PredictionContext> &context) {\n  // This function must only be called with an active state lock, as we are going to change a shared structure.\n  return PredictionContext::getCachedContext(context, getSharedContextCache());\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNSimulator.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"atn/ATN.h\"\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContext.h\"\n#include \"atn/PredictionContextCache.h\"\n#include \"misc/IntervalSet.h\"\n#include \"support/CPPUtils.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC ATNSimulator {\n  public:\n    /// Must distinguish between missing edge and edge we know leads nowhere.\n    static const Ref<dfa::DFAState> ERROR;\n    const ATN &atn;\n\n    ATNSimulator(const ATN &atn, PredictionContextCache &sharedContextCache);\n\n    virtual ~ATNSimulator() = default;\n\n    virtual void reset() = 0;\n\n    /**\n     * Clear the DFA cache used by the current instance. Since the DFA cache may\n     * be shared by multiple ATN simulators, this method may affect the\n     * performance (but not accuracy) of other parsers which are being used\n     * concurrently.\n     *\n     * @throws UnsupportedOperationException if the current instance does not\n     * support clearing the DFA.\n     *\n     * @since 4.3\n     */\n    virtual void clearDFA();\n\n    PredictionContextCache& getSharedContextCache() const;\n    Ref<const PredictionContext> getCachedContext(const Ref<const PredictionContext> &context);\n\n  protected:\n    /// <summary>\n    /// The context cache maps all PredictionContext objects that are equals()\n    ///  to a single cached copy. This cache is shared across all contexts\n    ///  in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet\n    ///  to use only cached nodes/graphs in addDFAState(). We don't want to\n    ///  fill this during closure() since there are lots of contexts that\n    ///  pop up but are not used ever again. It also greatly slows down closure().\n    ///  <p/>\n    ///  This cache makes a huge difference in memory and a little bit in speed.\n    ///  For the Java grammar on java.*, it dropped the memory requirements\n    ///  at the end from 25M to 16M. We don't store any of the full context\n    ///  graphs in the DFA because they are limited to local context only,\n    ///  but apparently there's a lot of repetition there as well. We optimize\n    ///  the config contexts before storing the config set in the DFA states\n    ///  by literally rebuilding them with cached subgraphs only.\n    ///  <p/>\n    ///  I tried a cache for use during closure operations, that was\n    ///  whacked after each adaptivePredict(). It cost a little bit\n    ///  more time I think and doesn't save on the overall footprint\n    ///  so it's not worth the complexity.\n    /// </summary>\n    PredictionContextCache &_sharedContextCache;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNState.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"atn/ATN.h\"\n#include \"atn/Transition.h\"\n#include \"misc/IntervalSet.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"atn/ATNState.h\"\n\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nsize_t ATNState::hashCode() const {\n  return stateNumber;\n}\n\nbool ATNState::equals(const ATNState &other) const {\n  return stateNumber == other.stateNumber;\n}\n\nbool ATNState::isNonGreedyExitState() const {\n  return false;\n}\n\nstd::string ATNState::toString() const {\n  return std::to_string(stateNumber);\n}\n\nvoid ATNState::addTransition(ConstTransitionPtr e) {\n  addTransition(transitions.size(), std::move(e));\n}\n\nvoid ATNState::addTransition(size_t index, ConstTransitionPtr e) {\n  for (const auto &transition : transitions)\n    if (transition->target->stateNumber == e->target->stateNumber) {\n      return;\n    }\n\n  if (transitions.empty()) {\n    epsilonOnlyTransitions = e->isEpsilon();\n  } else if (epsilonOnlyTransitions != e->isEpsilon()) {\n    std::cerr << \"ATN state %d has both epsilon and non-epsilon transitions.\\n\" << stateNumber;\n    epsilonOnlyTransitions = false;\n  }\n\n  transitions.insert(transitions.begin() + index, std::move(e));\n}\n\nConstTransitionPtr ATNState::removeTransition(size_t index) {\n  ConstTransitionPtr result = std::move(transitions[index]);\n  transitions.erase(transitions.begin() + index);\n  return result;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <limits>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"misc/IntervalSet.h\"\n#include \"antlr4-common.h\"\n#include \"atn/Transition.h\"\n#include \"atn/ATNStateType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// The following images show the relation of states and\n  /// <seealso cref=\"ATNState#transitions\"/> for various grammar constructs.\n  ///\n  /// <ul>\n  ///\n  /// <li>Solid edges marked with an &#0949; indicate a required\n  /// <seealso cref=\"EpsilonTransition\"/>.</li>\n  ///\n  /// <li>Dashed edges indicate locations where any transition derived from\n  /// <seealso cref=\"Transition\"/> might appear.</li>\n  ///\n  /// <li>Dashed nodes are place holders for either a sequence of linked\n  /// <seealso cref=\"BasicState\"/> states or the inclusion of a block representing a nested\n  /// construct in one of the forms below.</li>\n  ///\n  /// <li>Nodes showing multiple outgoing alternatives with a {@code ...} support\n  /// any number of alternatives (one or more). Nodes without the {@code ...} only\n  /// support the exact number of alternatives shown in the diagram.</li>\n  ///\n  /// </ul>\n  ///\n  /// <h2>Basic Blocks</h2>\n  ///\n  /// <h3>Rule</h3>\n  ///\n  /// <embed src=\"images/Rule.svg\" type=\"image/svg+xml\"/>\n  ///\n  /// <h3>Block of 1 or more alternatives</h3>\n  ///\n  /// <embed src=\"images/Block.svg\" type=\"image/svg+xml\"/>\n  ///\n  /// <h2>Greedy Loops</h2>\n  ///\n  /// <h3>Greedy Closure: {@code (...)*}</h3>\n  ///\n  /// <embed src=\"images/ClosureGreedy.svg\" type=\"image/svg+xml\"/>\n  ///\n  /// <h3>Greedy Positive Closure: {@code (...)+}</h3>\n  ///\n  /// <embed src=\"images/PositiveClosureGreedy.svg\" type=\"image/svg+xml\"/>\n  ///\n  /// <h3>Greedy Optional: {@code (...)?}</h3>\n  ///\n  /// <embed src=\"images/OptionalGreedy.svg\" type=\"image/svg+xml\"/>\n  ///\n  /// <h2>Non-Greedy Loops</h2>\n  ///\n  /// <h3>Non-Greedy Closure: {@code (...)*?}</h3>\n  ///\n  /// <embed src=\"images/ClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n  ///\n  /// <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>\n  ///\n  /// <embed src=\"images/PositiveClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n  ///\n  /// <h3>Non-Greedy Optional: {@code (...)??}</h3>\n  ///\n  /// <embed src=\"images/OptionalNonGreedy.svg\" type=\"image/svg+xml\"/>\n  /// </summary>\n\n// GCC generates a warning here if ATN has already been declared due to the\n// attributes added by ANTLR4CPP_PUBLIC.\n// See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=39159\n// Only forward-declare if it hasn't already been declared.\n#ifndef ANTLR4CPP_ATN_DECLARED\n  class ANTLR4CPP_PUBLIC ATN;\n#endif\n\n  class ANTLR4CPP_PUBLIC ATNState {\n  public:\n    static constexpr size_t INITIAL_NUM_TRANSITIONS = 4;\n    static constexpr size_t INVALID_STATE_NUMBER = std::numeric_limits<size_t>::max();\n\n    size_t stateNumber = INVALID_STATE_NUMBER;\n    size_t ruleIndex = 0; // at runtime, we don't have Rule objects\n    bool epsilonOnlyTransitions = false;\n\n    /// Track the transitions emanating from this ATN state.\n    std::vector<ConstTransitionPtr> transitions;\n\n    ATNState() = delete;\n\n    ATNState(ATNState const&) = delete;\n\n    ATNState(ATNState&&) = delete;\n\n    virtual ~ATNState() = default;\n\n    ATNState& operator=(ATNState const&) = delete;\n\n    ATNState& operator=(ATNState&&) = delete;\n\n    void addTransition(ConstTransitionPtr e);\n    void addTransition(size_t index, ConstTransitionPtr e);\n    ConstTransitionPtr removeTransition(size_t index);\n\n    virtual size_t hashCode() const;\n    virtual bool equals(const ATNState &other) const;\n\n    virtual bool isNonGreedyExitState() const;\n    virtual std::string toString() const;\n\n    ATNStateType getStateType() const { return _stateType; }\n\n  protected:\n    explicit ATNState(ATNStateType stateType) : _stateType(stateType) {}\n\n  private:\n    /// Used to cache lookahead during parsing, not used during construction.\n\n    misc::IntervalSet _nextTokenWithinRule;\n    std::atomic<bool> _nextTokenUpdated { false };\n\n    const ATNStateType _stateType;\n\n    friend class ATN;\n  };\n\n  inline bool operator==(const ATNState &lhs, const ATNState &rhs) { return lhs.equals(rhs); }\n\n  inline bool operator!=(const ATNState &lhs, const ATNState &rhs) { return !operator==(lhs, rhs); }\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNStateType.cpp",
    "content": "#include <string>\n#include \"atn/ATNStateType.h\"\n\nstd::string antlr4::atn::atnStateTypeName(ATNStateType atnStateType) {\n  switch (atnStateType) {\n    case ATNStateType::INVALID:\n      return \"INVALID\";\n    case ATNStateType::BASIC:\n      return \"BASIC\";\n    case ATNStateType::RULE_START:\n      return \"RULE_START\";\n    case ATNStateType::BLOCK_START:\n      return \"BLOCK_START\";\n    case ATNStateType::PLUS_BLOCK_START:\n      return \"PLUS_BLOCK_START\";\n    case ATNStateType::STAR_BLOCK_START:\n      return \"STAR_BLOCK_START\";\n    case ATNStateType::TOKEN_START:\n      return \"TOKEN_START\";\n    case ATNStateType::RULE_STOP:\n      return \"RULE_STOP\";\n    case ATNStateType::BLOCK_END:\n      return \"BLOCK_END\";\n    case ATNStateType::STAR_LOOP_BACK:\n      return \"STAR_LOOP_BACK\";\n    case ATNStateType::STAR_LOOP_ENTRY:\n      return \"STAR_LOOP_ENTRY\";\n    case ATNStateType::PLUS_LOOP_BACK:\n      return \"PLUS_LOOP_BACK\";\n    case ATNStateType::LOOP_END:\n      return \"LOOP_END\";\n  }\n  return \"UNKNOWN\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNStateType.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include <string>\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  // Constants for ATNState serialization.\n  enum class ATNStateType : size_t {\n    INVALID = 0,\n    BASIC = 1,\n    RULE_START = 2,\n    BLOCK_START = 3,\n    PLUS_BLOCK_START = 4,\n    STAR_BLOCK_START = 5,\n    TOKEN_START = 6,\n    RULE_STOP = 7,\n    BLOCK_END = 8,\n    STAR_LOOP_BACK = 9,\n    STAR_LOOP_ENTRY = 10,\n    PLUS_LOOP_BACK = 11,\n    LOOP_END = 12,\n  };\n\n  ANTLR4CPP_PUBLIC std::string atnStateTypeName(ATNStateType atnStateType);\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ATNType.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Represents the type of recognizer an ATN applies to.\n  enum class ATNType {\n    LEXER = 0,\n    PARSER = 1,\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ActionTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/ActionTransition.h\"\n\nusing namespace antlr4::atn;\n\nActionTransition::ActionTransition(ATNState *target, size_t ruleIndex)\n  : Transition(TransitionType::ACTION, target), ruleIndex(ruleIndex), actionIndex(INVALID_INDEX), isCtxDependent(false) {\n}\n\nActionTransition::ActionTransition(ATNState *target, size_t ruleIndex, size_t actionIndex, bool isCtxDependent)\n  : Transition(TransitionType::ACTION, target), ruleIndex(ruleIndex), actionIndex(actionIndex), isCtxDependent(isCtxDependent) {\n}\n\nbool ActionTransition::isEpsilon() const {\n  return true; // we are to be ignored by analysis 'cept for predicates\n}\n\nbool ActionTransition::matches(size_t /*symbol*/, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return false;\n}\n\nstd::string ActionTransition::toString() const {\n  return \" ACTION \" + Transition::toString() + \" { ruleIndex: \" + std::to_string(ruleIndex) + \", actionIndex: \" +\n  std::to_string(actionIndex) + \", isCtxDependent: \" + std::to_string(isCtxDependent) + \" }\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ActionTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC ActionTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::ACTION; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    const size_t ruleIndex;\n    const size_t actionIndex;\n    const bool isCtxDependent; // e.g., $i ref in action\n\n    ActionTransition(ATNState *target, size_t ruleIndex);\n\n    ActionTransition(ATNState *target, size_t ruleIndex, size_t actionIndex, bool isCtxDependent);\n\n    bool isEpsilon() const override;\n\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/AmbiguityInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/AmbiguityInfo.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nAmbiguityInfo::AmbiguityInfo(size_t decision, ATNConfigSet *configs, const antlrcpp::BitSet &ambigAlts,\n                             TokenStream *input, size_t startIndex, size_t stopIndex, bool fullCtx)\n  : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx) {\n\n  this->ambigAlts = ambigAlts;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/AmbiguityInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"atn/DecisionEventInfo.h\"\n#include \"antlr4-common.h\"\n#include \"support/BitSet.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// This class represents profiling event information for an ambiguity.\n  /// Ambiguities are decisions where a particular input resulted in an SLL\n  /// conflict, followed by LL prediction also reaching a conflict state\n  /// (indicating a true ambiguity in the grammar).\n  ///\n  /// <para>\n  /// This event may be reported during SLL prediction in cases where the\n  /// conflicting SLL configuration set provides sufficient information to\n  /// determine that the SLL conflict is truly an ambiguity. For example, if none\n  /// of the ATN configurations in the conflicting SLL configuration set have\n  /// traversed a global follow transition (i.e.\n  /// <seealso cref=\"ATNConfig#reachesIntoOuterContext\"/> is 0 for all configurations), then\n  /// the result of SLL prediction for that input is known to be equivalent to the\n  /// result of LL prediction for that input.</para>\n  ///\n  /// <para>\n  /// In some cases, the minimum represented alternative in the conflicting LL\n  /// configuration set is not equal to the minimum represented alternative in the\n  /// conflicting SLL configuration set. Grammars and inputs which result in this\n  /// scenario are unable to use <seealso cref=\"PredictionMode#SLL\"/>, which in turn means\n  /// they cannot use the two-stage parsing strategy to improve parsing performance\n  /// for that input.</para>\n  /// </summary>\n  /// <seealso cref= ParserATNSimulator#reportAmbiguity </seealso>\n  /// <seealso cref= ANTLRErrorListener#reportAmbiguity\n  ///\n  /// @since 4.3 </seealso>\n  class ANTLR4CPP_PUBLIC AmbiguityInfo : public DecisionEventInfo {\n  public:\n    /// The set of alternative numbers for this decision event that lead to a valid parse.\n    antlrcpp::BitSet ambigAlts;\n\n    /// <summary>\n    /// Constructs a new instance of the <seealso cref=\"AmbiguityInfo\"/> class with the\n    /// specified detailed ambiguity information.\n    /// </summary>\n    /// <param name=\"decision\"> The decision number </param>\n    /// <param name=\"configs\"> The final configuration set identifying the ambiguous\n    /// alternatives for the current input </param>\n    /// <param name=\"ambigAlts\"> The set of alternatives in the decision that lead to a valid parse.\n    ///                  The predicted alt is the min(ambigAlts) </param>\n    /// <param name=\"input\"> The input token stream </param>\n    /// <param name=\"startIndex\"> The start index for the current prediction </param>\n    /// <param name=\"stopIndex\"> The index at which the ambiguity was identified during\n    /// prediction </param>\n    /// <param name=\"fullCtx\"> {@code true} if the ambiguity was identified during LL\n    /// prediction; otherwise, {@code false} if the ambiguity was identified\n    /// during SLL prediction </param>\n    AmbiguityInfo(size_t decision, ATNConfigSet *configs, const antlrcpp::BitSet &ambigAlts, TokenStream *input,\n                  size_t startIndex, size_t stopIndex, bool fullCtx);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ArrayPredictionContext.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"atn/ArrayPredictionContext.h\"\n\n#include <memory>\n#include <sstream>\n#include <cassert>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstring>\n\n#include \"antlr4-common.h\"\n#include \"atn/SingletonPredictionContext.h\"\n#include \"atn/HashUtils.h\"\n#include \"misc/MurmurHash.h\"\n#include \"support/Casts.h\"\n\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nnamespace {\n\n  bool predictionContextEqual(const Ref<const PredictionContext> &lhs, const Ref<const PredictionContext> &rhs) {\n    // parent PredictionContext pointers can be null during full context mode and\n    // the ctxs are in an ArrayPredictionContext.  If both are null, return true\n    // if just one is null, return false. If both are non-null, do comparison.\n    if ( lhs == nullptr ) return rhs == nullptr;\n    if ( rhs == nullptr ) return false; // lhs!=null and rhs==null\n    return *lhs == *rhs;                // both nonnull\n  }\n\n}\n\nArrayPredictionContext::ArrayPredictionContext(const SingletonPredictionContext &predictionContext)\n    : ArrayPredictionContext({ predictionContext.parent }, { predictionContext.returnState }) {}\n\nArrayPredictionContext::ArrayPredictionContext(std::vector<Ref<const PredictionContext>> parents,\n                                               std::vector<size_t> returnStates)\n    : PredictionContext(PredictionContextType::ARRAY), parents(std::move(parents)), returnStates(std::move(returnStates)) {\n  assert(this->parents.size() > 0);\n  assert(this->returnStates.size() > 0);\n  assert(this->parents.size() == this->returnStates.size());\n}\n\nbool ArrayPredictionContext::isEmpty() const {\n  // Since EMPTY_RETURN_STATE can only appear in the last position, we don't need to verify that size == 1.\n  return returnStates[0] == EMPTY_RETURN_STATE;\n}\n\nsize_t ArrayPredictionContext::size() const {\n  return returnStates.size();\n}\n\nconst Ref<const PredictionContext>& ArrayPredictionContext::getParent(size_t index) const {\n  return parents[index];\n}\n\nsize_t ArrayPredictionContext::getReturnState(size_t index) const {\n  return returnStates[index];\n}\n\nsize_t ArrayPredictionContext::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getContextType()));\n  for (const auto &parent : parents) {\n    hash = MurmurHash::update(hash, parent);\n  }\n  for (const auto &returnState : returnStates) {\n    hash = MurmurHash::update(hash, returnState);\n  }\n  return MurmurHash::finish(hash, 1 + parents.size() + returnStates.size());\n}\n\nbool ArrayPredictionContext::equals(const PredictionContext &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getContextType() != other.getContextType()) {\n    return false;\n  }\n  const auto &array = downCast<const ArrayPredictionContext&>(other);\n  const bool sameSize = returnStates.size() == array.returnStates.size() &&\n                        parents.size() == array.parents.size();\n  if ( !sameSize ) {\n      return false;\n  }\n\n  const bool sameHash = cachedHashCodeEqual(cachedHashCode(), array.cachedHashCode());\n  if ( !sameHash ) {\n      return false;\n  }\n\n  const size_t stateSizeBytes = sizeof(decltype(returnStates)::value_type);\n  const bool returnStateArraysEqual =\n          std::memcmp(returnStates.data(), array.returnStates.data(),\n                      returnStates.size() * stateSizeBytes) == 0;\n  if ( !returnStateArraysEqual ) {\n      return false;\n  }\n\n  // stack of contexts is the same\n  const bool parentCtxEqual =\n          std::equal(parents.begin(), parents.end(), array.parents.begin(), predictionContextEqual);\n  return parentCtxEqual;\n}\n\nstd::string ArrayPredictionContext::toString() const {\n  if (isEmpty()) {\n    return \"[]\";\n  }\n\n  std::stringstream ss;\n  ss << \"[\";\n  for (size_t i = 0; i < returnStates.size(); i++) {\n    if (i > 0) {\n      ss << \", \";\n    }\n    if (returnStates[i] == EMPTY_RETURN_STATE) {\n      ss << \"$\";\n      continue;\n    }\n    ss << returnStates[i];\n    if (parents[i] != nullptr) {\n      ss << \" \" << parents[i]->toString();\n    } else {\n      ss << \"nul\";\n    }\n  }\n  ss << \"]\";\n  return ss.str();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ArrayPredictionContext.h",
    "content": "﻿\n/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContext.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class SingletonPredictionContext;\n\n  class ANTLR4CPP_PUBLIC ArrayPredictionContext final : public PredictionContext {\n  public:\n    static bool is(const PredictionContext &predictionContext) { return predictionContext.getContextType() == PredictionContextType::ARRAY; }\n\n    static bool is(const PredictionContext *predictionContext) { return predictionContext != nullptr && is(*predictionContext); }\n\n    /// Parent can be empty only if full ctx mode and we make an array\n    /// from EMPTY and non-empty. We merge EMPTY by using null parent and\n    /// returnState == EMPTY_RETURN_STATE.\n    // Also here: we use a strong reference to our parents to avoid having them freed prematurely.\n    //            See also SinglePredictionContext.\n    std::vector<Ref<const PredictionContext>> parents;\n\n    /// Sorted for merge, no duplicates; if present, EMPTY_RETURN_STATE is always last.\n    std::vector<size_t> returnStates;\n\n    explicit ArrayPredictionContext(const SingletonPredictionContext &predictionContext);\n\n    ArrayPredictionContext(std::vector<Ref<const PredictionContext>> parents, std::vector<size_t> returnStates);\n\n    ArrayPredictionContext(ArrayPredictionContext&&) = default;\n\n    bool isEmpty() const override;\n    size_t size() const override;\n    const Ref<const PredictionContext>& getParent(size_t index) const override;\n    size_t getReturnState(size_t index) const override;\n    bool equals(const PredictionContext &other) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/AtomTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"misc/IntervalSet.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\n#include \"atn/AtomTransition.h\"\n\nusing namespace antlr4::misc;\nusing namespace antlr4::atn;\n\nAtomTransition::AtomTransition(ATNState *target, size_t label) : Transition(TransitionType::ATOM, target), _label(label) {\n}\n\nIntervalSet AtomTransition::label() const {\n  return IntervalSet::of((int)_label);\n}\n\nbool AtomTransition::matches(size_t symbol, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return _label == symbol;\n}\n\nstd::string AtomTransition::toString() const {\n  return \"ATOM \" + Transition::toString() + \" { label: \" + std::to_string(_label) + \" }\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/AtomTransition.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// TODO: make all transitions sets? no, should remove set edges.\n  class ANTLR4CPP_PUBLIC AtomTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::ATOM; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    /// The token type or character value; or, signifies special label.\n    /// TODO: rename this to label\n    const size_t _label;\n\n    AtomTransition(ATNState *target, size_t label);\n\n    misc::IntervalSet label() const override;\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/BasicBlockStartState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/BlockStartState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC BasicBlockStartState final : public BlockStartState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::BLOCK_START; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    BasicBlockStartState() : BlockStartState(ATNStateType::BLOCK_START) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/BasicState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC BasicState final : public ATNState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::BASIC; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    BasicState() : ATNState(ATNStateType::BASIC) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/BlockEndState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Terminal node of a simple {@code (a|b|c)} block.\n  class ANTLR4CPP_PUBLIC BlockEndState final : public ATNState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::BLOCK_END; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    BlockStartState *startState = nullptr;\n\n    BlockEndState() : ATNState(ATNStateType::BLOCK_END) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/BlockStartState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/DecisionState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  ///  The start of a regular {@code (...)} block.\n  class ANTLR4CPP_PUBLIC BlockStartState : public DecisionState {\n  public:\n    static bool is(const ATNState &atnState) {\n      const auto stateType = atnState.getStateType();\n      return stateType >= ATNStateType::BLOCK_START && stateType <= ATNStateType::STAR_BLOCK_START;\n    }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    BlockEndState *endState = nullptr;\n\n  protected:\n    using DecisionState::DecisionState;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ContextSensitivityInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/ContextSensitivityInfo.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nContextSensitivityInfo::ContextSensitivityInfo(size_t decision, ATNConfigSet *configs, TokenStream *input,\n  size_t startIndex, size_t stopIndex)\n  : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, true) {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ContextSensitivityInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/DecisionEventInfo.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// This class represents profiling event information for a context sensitivity.\n  /// Context sensitivities are decisions where a particular input resulted in an\n  /// SLL conflict, but LL prediction produced a single unique alternative.\n  ///\n  /// <para>\n  /// In some cases, the unique alternative identified by LL prediction is not\n  /// equal to the minimum represented alternative in the conflicting SLL\n  /// configuration set. Grammars and inputs which result in this scenario are\n  /// unable to use <seealso cref=\"PredictionMode#SLL\"/>, which in turn means they cannot use\n  /// the two-stage parsing strategy to improve parsing performance for that\n  /// input.</para>\n  /// </summary>\n  /// <seealso cref= ParserATNSimulator#reportContextSensitivity </seealso>\n  /// <seealso cref= ANTLRErrorListener#reportContextSensitivity\n  ///\n  /// @since 4.3 </seealso>\n  class ANTLR4CPP_PUBLIC ContextSensitivityInfo : public DecisionEventInfo {\n  public:\n    /// <summary>\n    /// Constructs a new instance of the <seealso cref=\"ContextSensitivityInfo\"/> class\n    /// with the specified detailed context sensitivity information.\n    /// </summary>\n    /// <param name=\"decision\"> The decision number </param>\n    /// <param name=\"configs\"> The final configuration set containing the unique\n    /// alternative identified by full-context prediction </param>\n    /// <param name=\"input\"> The input token stream </param>\n    /// <param name=\"startIndex\"> The start index for the current prediction </param>\n    /// <param name=\"stopIndex\"> The index at which the context sensitivity was\n    /// identified during full-context prediction </param>\n    ContextSensitivityInfo(size_t decision, ATNConfigSet *configs, TokenStream *input, size_t startIndex, size_t stopIndex);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/DecisionEventInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/DecisionEventInfo.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nDecisionEventInfo::DecisionEventInfo(size_t decision, ATNConfigSet *configs, TokenStream *input, size_t startIndex,\n  size_t stopIndex, bool fullCtx)\n  : decision(decision), configs(configs), input(input), startIndex(startIndex), stopIndex(stopIndex), fullCtx(fullCtx) {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/DecisionEventInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// This is the base class for gathering detailed information about prediction\n  /// events which occur during parsing.\n  ///\n  /// Note that we could record the parser call stack at the time this event\n  /// occurred but in the presence of left recursive rules, the stack is kind of\n  /// meaningless. It's better to look at the individual configurations for their\n  /// individual stacks. Of course that is a <seealso cref=\"PredictionContext\"/> object\n  /// not a parse tree node and so it does not have information about the extent\n  /// (start...stop) of the various subtrees. Examining the stack tops of all\n  /// configurations provide the return states for the rule invocations.\n  /// From there you can get the enclosing rule.\n  ///\n  /// @since 4.3\n  /// </summary>\n  class ANTLR4CPP_PUBLIC DecisionEventInfo {\n  public:\n    /// <summary>\n    /// The invoked decision number which this event is related to.\n    /// </summary>\n    /// <seealso cref= ATN#decisionToState </seealso>\n    const size_t decision;\n\n    /// <summary>\n    /// The configuration set containing additional information relevant to the\n    /// prediction state when the current event occurred, or {@code null} if no\n    /// additional information is relevant or available.\n    /// </summary>\n    const ATNConfigSet *configs;\n\n    /// <summary>\n    /// The input token stream which is being parsed.\n    /// </summary>\n    const TokenStream *input;\n\n    /// <summary>\n    /// The token index in the input stream at which the current prediction was\n    /// originally invoked.\n    /// </summary>\n    const size_t startIndex;\n\n    /// <summary>\n    /// The token index in the input stream at which the current event occurred.\n    /// </summary>\n    const size_t stopIndex;\n\n    /// <summary>\n    /// {@code true} if the current event occurred during LL prediction;\n    /// otherwise, {@code false} if the input occurred during SLL prediction.\n    /// </summary>\n    const bool fullCtx;\n\n    DecisionEventInfo(size_t decision, ATNConfigSet *configs, TokenStream *input, size_t startIndex,\n                      size_t stopIndex, bool fullCtx);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/DecisionInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <string>\n#include <cstddef>\n#include \"atn/ErrorInfo.h\"\n#include \"atn/LookaheadEventInfo.h\"\n\n#include \"atn/DecisionInfo.h\"\n\nusing namespace antlr4::atn;\n\nDecisionInfo::DecisionInfo(size_t decision) : decision(decision) {\n}\n\nstd::string DecisionInfo::toString() const {\n  std::stringstream ss;\n\n  ss << \"{decision=\" << decision << \", contextSensitivities=\" << contextSensitivities.size() << \", errors=\";\n  ss << errors.size() << \", ambiguities=\" << ambiguities.size() << \", SLL_lookahead=\" << SLL_TotalLook;\n  ss << \", SLL_ATNTransitions=\" << SLL_ATNTransitions << \", SLL_DFATransitions=\" << SLL_DFATransitions;\n  ss << \", LL_Fallback=\" << LL_Fallback << \", LL_lookahead=\" << LL_TotalLook << \", LL_ATNTransitions=\" << LL_ATNTransitions << '}';\n\n  return ss.str();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/DecisionInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"atn/ContextSensitivityInfo.h\"\n#include \"antlr4-common.h\"\n#include \"atn/AmbiguityInfo.h\"\n#include \"atn/PredicateEvalInfo.h\"\n#include \"atn/ErrorInfo.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class LookaheadEventInfo;\n\n  /// <summary>\n  /// This class contains profiling gathered for a particular decision.\n  ///\n  /// <para>\n  /// Parsing performance in ANTLR 4 is heavily influenced by both static factors\n  /// (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the\n  /// choice of input and the state of the DFA cache at the time profiling\n  /// operations are started). For best results, gather and use aggregate\n  /// statistics from a large sample of inputs representing the inputs expected in\n  /// production before using the results to make changes in the grammar.</para>\n  ///\n  /// @since 4.3\n  /// </summary>\n  class ANTLR4CPP_PUBLIC DecisionInfo {\n  public:\n    /// <summary>\n    /// The decision number, which is an index into <seealso cref=\"ATN#decisionToState\"/>.\n    /// </summary>\n    const size_t decision;\n\n    /// <summary>\n    /// The total number of times <seealso cref=\"ParserATNSimulator#adaptivePredict\"/> was\n    /// invoked for this decision.\n    /// </summary>\n    long long invocations = 0;\n\n    /// <summary>\n    /// The total time spent in <seealso cref=\"ParserATNSimulator#adaptivePredict\"/> for\n    /// this decision, in nanoseconds.\n    ///\n    /// <para>\n    /// The value of this field contains the sum of differential results obtained\n    /// by <seealso cref=\"System#nanoTime()\"/>, and is not adjusted to compensate for JIT\n    /// and/or garbage collection overhead. For best accuracy, use a modern JVM\n    /// implementation that provides precise results from\n    /// <seealso cref=\"System#nanoTime()\"/>, and perform profiling in a separate process\n    /// which is warmed up by parsing the input prior to profiling. If desired,\n    /// call <seealso cref=\"ATNSimulator#clearDFA\"/> to reset the DFA cache to its initial\n    /// state before starting the profiling measurement pass.</para>\n    /// </summary>\n    long long timeInPrediction = 0;\n\n    /// <summary>\n    /// The sum of the lookahead required for SLL prediction for this decision.\n    /// Note that SLL prediction is used before LL prediction for performance\n    /// reasons even when <seealso cref=\"PredictionMode#LL\"/> or\n    /// <seealso cref=\"PredictionMode#LL_EXACT_AMBIG_DETECTION\"/> is used.\n    /// </summary>\n    long long SLL_TotalLook = 0;\n\n    /// <summary>\n    /// Gets the minimum lookahead required for any single SLL prediction to\n    /// complete for this decision, by reaching a unique prediction, reaching an\n    /// SLL conflict state, or encountering a syntax error.\n    /// </summary>\n    long long SLL_MinLook = 0;\n\n    /// <summary>\n    /// Gets the maximum lookahead required for any single SLL prediction to\n    /// complete for this decision, by reaching a unique prediction, reaching an\n    /// SLL conflict state, or encountering a syntax error.\n    /// </summary>\n    long long SLL_MaxLook = 0;\n\n    /// Gets the <seealso cref=\"LookaheadEventInfo\"/> associated with the event where the\n    /// <seealso cref=\"#SLL_MaxLook\"/> value was set.\n    Ref<LookaheadEventInfo> SLL_MaxLookEvent;\n\n    /// <summary>\n    /// The sum of the lookahead required for LL prediction for this decision.\n    /// Note that LL prediction is only used when SLL prediction reaches a\n    /// conflict state.\n    /// </summary>\n    long long LL_TotalLook = 0;\n\n    /// <summary>\n    /// Gets the minimum lookahead required for any single LL prediction to\n    /// complete for this decision. An LL prediction completes when the algorithm\n    /// reaches a unique prediction, a conflict state (for\n    /// <seealso cref=\"PredictionMode#LL\"/>, an ambiguity state (for\n    /// <seealso cref=\"PredictionMode#LL_EXACT_AMBIG_DETECTION\"/>, or a syntax error.\n    /// </summary>\n    long long LL_MinLook = 0;\n\n    /// <summary>\n    /// Gets the maximum lookahead required for any single LL prediction to\n    /// complete for this decision. An LL prediction completes when the algorithm\n    /// reaches a unique prediction, a conflict state (for\n    /// <seealso cref=\"PredictionMode#LL\"/>, an ambiguity state (for\n    /// <seealso cref=\"PredictionMode#LL_EXACT_AMBIG_DETECTION\"/>, or a syntax error.\n    /// </summary>\n    long long LL_MaxLook = 0;\n\n    /// <summary>\n    /// Gets the <seealso cref=\"LookaheadEventInfo\"/> associated with the event where the\n    /// <seealso cref=\"#LL_MaxLook\"/> value was set.\n    /// </summary>\n    Ref<LookaheadEventInfo> LL_MaxLookEvent;\n\n    /// <summary>\n    /// A collection of <seealso cref=\"ContextSensitivityInfo\"/> instances describing the\n    /// context sensitivities encountered during LL prediction for this decision.\n    /// </summary>\n    /// <seealso cref= ContextSensitivityInfo </seealso>\n    std::vector<ContextSensitivityInfo> contextSensitivities;\n\n    /// <summary>\n    /// A collection of <seealso cref=\"ErrorInfo\"/> instances describing the parse errors\n    /// identified during calls to <seealso cref=\"ParserATNSimulator#adaptivePredict\"/> for\n    /// this decision.\n    /// </summary>\n    /// <seealso cref= ErrorInfo </seealso>\n    std::vector<ErrorInfo> errors;\n\n    /// <summary>\n    /// A collection of <seealso cref=\"AmbiguityInfo\"/> instances describing the\n    /// ambiguities encountered during LL prediction for this decision.\n    /// </summary>\n    /// <seealso cref= AmbiguityInfo </seealso>\n    std::vector<AmbiguityInfo> ambiguities;\n\n    /// <summary>\n    /// A collection of <seealso cref=\"PredicateEvalInfo\"/> instances describing the\n    /// results of evaluating individual predicates during prediction for this\n    /// decision.\n    /// </summary>\n    /// <seealso cref= PredicateEvalInfo </seealso>\n    std::vector<PredicateEvalInfo> predicateEvals;\n\n    /// <summary>\n    /// The total number of ATN transitions required during SLL prediction for\n    /// this decision. An ATN transition is determined by the number of times the\n    /// DFA does not contain an edge that is required for prediction, resulting\n    /// in on-the-fly computation of that edge.\n    ///\n    /// <para>\n    /// If DFA caching of SLL transitions is employed by the implementation, ATN\n    /// computation may cache the computed edge for efficient lookup during\n    /// future parsing of this decision. Otherwise, the SLL parsing algorithm\n    /// will use ATN transitions exclusively.</para>\n    /// </summary>\n    /// <seealso cref= #SLL_ATNTransitions </seealso>\n    /// <seealso cref= ParserATNSimulator#computeTargetState </seealso>\n    /// <seealso cref= LexerATNSimulator#computeTargetState </seealso>\n    long long SLL_ATNTransitions = 0;\n\n    /// <summary>\n    /// The total number of DFA transitions required during SLL prediction for\n    /// this decision.\n    ///\n    /// <para>If the ATN simulator implementation does not use DFA caching for SLL\n    /// transitions, this value will be 0.</para>\n    /// </summary>\n    /// <seealso cref= ParserATNSimulator#getExistingTargetState </seealso>\n    /// <seealso cref= LexerATNSimulator#getExistingTargetState </seealso>\n    long long SLL_DFATransitions = 0;\n\n    /// <summary>\n    /// Gets the total number of times SLL prediction completed in a conflict\n    /// state, resulting in fallback to LL prediction.\n    ///\n    /// <para>Note that this value is not related to whether or not\n    /// <seealso cref=\"PredictionMode#SLL\"/> may be used successfully with a particular\n    /// grammar. If the ambiguity resolution algorithm applied to the SLL\n    /// conflicts for this decision produce the same result as LL prediction for\n    /// this decision, <seealso cref=\"PredictionMode#SLL\"/> would produce the same overall\n    /// parsing result as <seealso cref=\"PredictionMode#LL\"/>.</para>\n    /// </summary>\n    long long LL_Fallback = 0;\n\n    /// <summary>\n    /// The total number of ATN transitions required during LL prediction for\n    /// this decision. An ATN transition is determined by the number of times the\n    /// DFA does not contain an edge that is required for prediction, resulting\n    /// in on-the-fly computation of that edge.\n    ///\n    /// <para>\n    /// If DFA caching of LL transitions is employed by the implementation, ATN\n    /// computation may cache the computed edge for efficient lookup during\n    /// future parsing of this decision. Otherwise, the LL parsing algorithm will\n    /// use ATN transitions exclusively.</para>\n    /// </summary>\n    /// <seealso cref= #LL_DFATransitions </seealso>\n    /// <seealso cref= ParserATNSimulator#computeTargetState </seealso>\n    /// <seealso cref= LexerATNSimulator#computeTargetState </seealso>\n    long long LL_ATNTransitions = 0;\n\n    /// <summary>\n    /// The total number of DFA transitions required during LL prediction for\n    /// this decision.\n    ///\n    /// <para>If the ATN simulator implementation does not use DFA caching for LL\n    /// transitions, this value will be 0.</para>\n    /// </summary>\n    /// <seealso cref= ParserATNSimulator#getExistingTargetState </seealso>\n    /// <seealso cref= LexerATNSimulator#getExistingTargetState </seealso>\n    long long LL_DFATransitions = 0;\n\n    /// <summary>\n    /// Constructs a new instance of the <seealso cref=\"DecisionInfo\"/> class to contain\n    /// statistics for a particular decision.\n    /// </summary>\n    /// <param name=\"decision\"> The decision number </param>\n    explicit DecisionInfo(size_t decision);\n\n    std::string toString() const;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/DecisionState.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include \"atn/ATNState.h\"\n#include \"atn/DecisionState.h\"\n\nusing namespace antlr4::atn;\n\nstd::string DecisionState::toString() const {\n  return ATNState::toString();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/DecisionState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC DecisionState : public ATNState {\n  public:\n    static bool is(const ATNState &atnState) {\n      const auto stateType = atnState.getStateType();\n      return (stateType >= ATNStateType::BLOCK_START && stateType <= ATNStateType::TOKEN_START) ||\n              stateType == ATNStateType::PLUS_LOOP_BACK ||\n              stateType == ATNStateType::STAR_LOOP_ENTRY;\n    }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    int decision = -1;\n    bool nonGreedy = false;\n\n    std::string toString() const override;\n\n  protected:\n    using ATNState::ATNState;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/EpsilonTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/EpsilonTransition.h\"\n\nusing namespace antlr4::atn;\n\nEpsilonTransition::EpsilonTransition(ATNState *target) : EpsilonTransition(target, INVALID_INDEX) {\n}\n\nEpsilonTransition::EpsilonTransition(ATNState *target, size_t outermostPrecedenceReturn)\n  : Transition(TransitionType::EPSILON, target), _outermostPrecedenceReturn(outermostPrecedenceReturn) {\n}\n\nsize_t EpsilonTransition::outermostPrecedenceReturn() const {\n  return _outermostPrecedenceReturn;\n}\n\nbool EpsilonTransition::isEpsilon() const {\n  return true;\n}\n\nbool EpsilonTransition::matches(size_t /*symbol*/, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return false;\n}\n\nstd::string EpsilonTransition::toString() const {\n  return \"EPSILON \" + Transition::toString() + \" {}\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/EpsilonTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC EpsilonTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::EPSILON; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    explicit EpsilonTransition(ATNState *target);\n    EpsilonTransition(ATNState *target, size_t outermostPrecedenceReturn);\n\n    /**\n     * @return the rule index of a precedence rule for which this transition is\n     * returning from, where the precedence value is 0; otherwise, INVALID_INDEX.\n     *\n     * @see ATNConfig#isPrecedenceFilterSuppressed()\n     * @see ParserATNSimulator#applyPrecedenceFilter(ATNConfigSet)\n     * @since 4.4.1\n     */\n    size_t outermostPrecedenceReturn() const;\n\n    bool isEpsilon() const override;\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n\n  private:\n    const size_t _outermostPrecedenceReturn; // A rule index.\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ErrorInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/ATNConfigSet.h\"\n\n#include \"atn/ErrorInfo.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nErrorInfo::ErrorInfo(size_t decision, ATNConfigSet *configs, TokenStream *input, size_t startIndex, size_t stopIndex, bool fullCtx)\n  : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx) {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ErrorInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/DecisionEventInfo.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// This class represents profiling event information for a syntax error\n  /// identified during prediction. Syntax errors occur when the prediction\n  /// algorithm is unable to identify an alternative which would lead to a\n  /// successful parse.\n  /// </summary>\n  /// <seealso cref= Parser#notifyErrorListeners(Token, String, RecognitionException) </seealso>\n  /// <seealso cref= ANTLRErrorListener#syntaxError\n  ///\n  /// @since 4.3 </seealso>\n  class ANTLR4CPP_PUBLIC ErrorInfo : public DecisionEventInfo {\n  public:\n    /// <summary>\n    /// Constructs a new instance of the <seealso cref=\"ErrorInfo\"/> class with the\n    /// specified detailed syntax error information.\n    /// </summary>\n    /// <param name=\"decision\"> The decision number </param>\n    /// <param name=\"configs\"> The final configuration set reached during prediction\n    /// prior to reaching the <seealso cref=\"ATNSimulator#ERROR\"/> state </param>\n    /// <param name=\"input\"> The input token stream </param>\n    /// <param name=\"startIndex\"> The start index for the current prediction </param>\n    /// <param name=\"stopIndex\"> The index at which the syntax error was identified </param>\n    /// <param name=\"fullCtx\"> {@code true} if the syntax error was identified during LL\n    /// prediction; otherwise, {@code false} if the syntax error was identified\n    /// during SLL prediction </param>\n    ErrorInfo(size_t decision, ATNConfigSet *configs, TokenStream *input, size_t startIndex, size_t stopIndex,\n              bool fullCtx);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/HashUtils.h",
    "content": "/* Copyright (c) 2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n\nnamespace antlr4 {\nnamespace atn {\n\n  inline bool cachedHashCodeEqual(size_t lhs, size_t rhs) {\n    return lhs == rhs || lhs == 0 || rhs == 0;\n  }\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LL1Analyzer.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <unordered_set>\n#include <vector>\n#include <cstddef>\n#include \"atn/RuleStopState.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/TransitionType.h\"\n#include \"Token.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/Transition.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/SingletonPredictionContext.h\"\n#include \"atn/WildcardTransition.h\"\n#include \"atn/NotSetTransition.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/ATNConfig.h\"\n\n#include \"support/CPPUtils.h\"\n\n#include \"atn/LL1Analyzer.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nnamespace {\n\n  struct ATNConfigHasher final {\n    size_t operator()(const ATNConfig& atn_config) const {\n      return atn_config.hashCode();\n    }\n  };\n\n  struct ATNConfigComparer final {\n    bool operator()(const ATNConfig& lhs, const ATNConfig& rhs) const {\n      return lhs == rhs;\n    }\n  };\n\n  class LL1AnalyzerImpl final {\n  public:\n    LL1AnalyzerImpl(const ATN& atn, misc::IntervalSet& look, bool seeThruPreds, bool addEOF) : _atn(atn), _look(look), _seeThruPreds(seeThruPreds), _addEOF(addEOF) {}\n\n    /// <summary>\n    /// Compute set of tokens that can follow {@code s} in the ATN in the\n    /// specified {@code ctx}.\n    /// <p/>\n    /// If {@code ctx} is {@code null} and {@code stopState} or the end of the\n    /// rule containing {@code s} is reached, <seealso cref=\"Token#EPSILON\"/> is added to\n    /// the result set. If {@code ctx} is not {@code null} and {@code addEOF} is\n    /// {@code true} and {@code stopState} or the end of the outermost rule is\n    /// reached, <seealso cref=\"Token#EOF\"/> is added to the result set.\n    /// </summary>\n    /// <param name=\"s\"> the ATN state. </param>\n    /// <param name=\"stopState\"> the ATN state to stop at. This can be a\n    /// <seealso cref=\"BlockEndState\"/> to detect epsilon paths through a closure. </param>\n    /// <param name=\"ctx\"> The outer context, or {@code null} if the outer context should\n    /// not be used. </param>\n    /// <param name=\"look\"> The result lookahead set. </param>\n    /// <param name=\"lookBusy\"> A set used for preventing epsilon closures in the ATN\n    /// from causing a stack overflow. Outside code should pass\n    /// {@code new HashSet<ATNConfig>} for this argument. </param>\n    /// <param name=\"calledRuleStack\"> A set used for preventing left recursion in the\n    /// ATN from causing a stack overflow. Outside code should pass\n    /// {@code new BitSet()} for this argument. </param>\n    /// <param name=\"seeThruPreds\"> {@code true} to true semantic predicates as\n    /// implicitly {@code true} and \"see through them\", otherwise {@code false}\n    /// to treat semantic predicates as opaque and add <seealso cref=\"#HIT_PRED\"/> to the\n    /// result if one is encountered. </param>\n    /// <param name=\"addEOF\"> Add <seealso cref=\"Token#EOF\"/> to the result if the end of the\n    /// outermost context is reached. This parameter has no effect if {@code ctx}\n    /// is {@code null}. </param>\n    void LOOK(ATNState *s, ATNState *stopState, Ref<const PredictionContext> const& ctx) {\n      if (!_lookBusy.insert(ATNConfig(s, 0, ctx)).second) {\n        return;\n      }\n\n      // ml: s can never be null, hence no need to check if stopState is != null.\n      if (s == stopState) {\n        if (ctx == nullptr) {\n          _look.add(Token::EPSILON);\n          return;\n        } else if (ctx->isEmpty() && _addEOF) {\n          _look.add(Token::EOF);\n          return;\n        }\n      }\n\n      if (s->getStateType() == ATNStateType::RULE_STOP) {\n        if (ctx == nullptr) {\n          _look.add(Token::EPSILON);\n          return;\n        } else if (ctx->isEmpty() && _addEOF) {\n          _look.add(Token::EOF);\n          return;\n        }\n\n        if (ctx != PredictionContext::EMPTY) {\n          bool removed = _calledRuleStack.test(s->ruleIndex);\n          _calledRuleStack[s->ruleIndex] = false;\n          // run thru all possible stack tops in ctx\n          for (size_t i = 0; i < ctx->size(); i++) {\n            ATNState *returnState = _atn.states[ctx->getReturnState(i)];\n            LOOK(returnState, stopState, ctx->getParent(i));\n          }\n          if (removed) {\n            _calledRuleStack.set(s->ruleIndex);\n          }\n          return;\n        }\n      }\n\n      size_t n = s->transitions.size();\n      for (size_t i = 0; i < n; i++) {\n        const Transition *t = s->transitions[i].get();\n        const auto tType = t->getTransitionType();\n\n        if (tType == TransitionType::RULE) {\n          if (_calledRuleStack[(static_cast<const RuleTransition*>(t))->target->ruleIndex]) {\n            continue;\n          }\n\n          Ref<const PredictionContext> newContext = SingletonPredictionContext::create(ctx, (static_cast<const RuleTransition*>(t))->followState->stateNumber);\n\n          _calledRuleStack.set((static_cast<const RuleTransition*>(t))->target->ruleIndex);\n          LOOK(t->target, stopState, newContext);\n          _calledRuleStack[(static_cast<const RuleTransition*>(t))->target->ruleIndex] = false;\n\n        } else if (tType == TransitionType::PREDICATE || tType == TransitionType::PRECEDENCE) {\n          if (_seeThruPreds) {\n            LOOK(t->target, stopState, ctx);\n          } else {\n            _look.add(LL1Analyzer::HIT_PRED);\n          }\n        } else if (t->isEpsilon()) {\n          LOOK(t->target, stopState, ctx);\n        } else if (tType == TransitionType::WILDCARD) {\n          _look.addAll(misc::IntervalSet::of(Token::MIN_USER_TOKEN_TYPE, static_cast<ssize_t>(_atn.maxTokenType)));\n        } else {\n          misc::IntervalSet set = t->label();\n          if (!set.isEmpty()) {\n            if (tType == TransitionType::NOT_SET) {\n              set = set.complement(misc::IntervalSet::of(Token::MIN_USER_TOKEN_TYPE, static_cast<ssize_t>(_atn.maxTokenType)));\n            }\n            _look.addAll(set);\n          }\n        }\n      }\n    }\n\n  private:\n    const ATN& _atn;\n    misc::IntervalSet& _look;\n    antlrcpp::BitSet _calledRuleStack;\n    std::unordered_set<ATNConfig, ATNConfigHasher, ATNConfigComparer> _lookBusy;\n    bool _seeThruPreds;\n    bool _addEOF;\n  };\n\n}\n\nstd::vector<misc::IntervalSet> LL1Analyzer::getDecisionLookahead(ATNState *s) const {\n  std::vector<misc::IntervalSet> look;\n\n  if (s == nullptr) {\n    return look;\n  }\n\n  look.resize(s->transitions.size()); // Fills all interval sets with defaults.\n  for (size_t alt = 0; alt < s->transitions.size(); alt++) {\n    LL1AnalyzerImpl impl(_atn, look[alt], false, false);\n    impl.LOOK(s->transitions[alt]->target, nullptr, PredictionContext::EMPTY);\n    // Wipe out lookahead for this alternative if we found nothing\n    // or we had a predicate when we !seeThruPreds\n    if (look[alt].size() == 0 || look[alt].contains(LL1Analyzer::HIT_PRED)) {\n      look[alt].clear();\n    }\n  }\n  return look;\n}\n\nmisc::IntervalSet LL1Analyzer::LOOK(ATNState *s, RuleContext *ctx) const {\n  return LOOK(s, nullptr, ctx);\n}\n\nmisc::IntervalSet LL1Analyzer::LOOK(ATNState *s, ATNState *stopState, RuleContext *ctx) const {\n  Ref<const PredictionContext> lookContext = ctx != nullptr ? PredictionContext::fromRuleContext(_atn, ctx) : nullptr;\n  misc::IntervalSet r;\n  LL1AnalyzerImpl impl(_atn, r, true, true);\n  impl.LOOK(s, stopState, lookContext);\n  return r;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LL1Analyzer.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <cstddef>\n#include \"Token.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATNConfig.h\"\n#include \"atn/PredictionContext.h\"\n#include \"support/BitSet.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC LL1Analyzer final {\n  public:\n    /// Special value added to the lookahead sets to indicate that we hit\n    ///  a predicate during analysis if {@code seeThruPreds==false}.\n    static constexpr size_t HIT_PRED = Token::INVALID_TYPE;\n\n    explicit LL1Analyzer(const atn::ATN &atn) : _atn(atn) {}\n\n    /// <summary>\n    /// Calculates the SLL(1) expected lookahead set for each outgoing transition\n    /// of an <seealso cref=\"ATNState\"/>. The returned array has one element for each\n    /// outgoing transition in {@code s}. If the closure from transition\n    /// <em>i</em> leads to a semantic predicate before matching a symbol, the\n    /// element at index <em>i</em> of the result will be {@code null}.\n    /// </summary>\n    /// <param name=\"s\"> the ATN state </param>\n    /// <returns> the expected symbols for each outgoing transition of {@code s}. </returns>\n    std::vector<misc::IntervalSet> getDecisionLookahead(ATNState *s) const;\n\n    /// <summary>\n    /// Compute set of tokens that can follow {@code s} in the ATN in the\n    /// specified {@code ctx}.\n    /// <p/>\n    /// If {@code ctx} is {@code null} and the end of the rule containing\n    /// {@code s} is reached, <seealso cref=\"Token#EPSILON\"/> is added to the result set.\n    /// If {@code ctx} is not {@code null} and the end of the outermost rule is\n    /// reached, <seealso cref=\"Token#EOF\"/> is added to the result set.\n    /// </summary>\n    /// <param name=\"s\"> the ATN state </param>\n    /// <param name=\"ctx\"> the complete parser context, or {@code null} if the context\n    /// should be ignored\n    /// </param>\n    /// <returns> The set of tokens that can follow {@code s} in the ATN in the\n    /// specified {@code ctx}. </returns>\n    misc::IntervalSet LOOK(ATNState *s, RuleContext *ctx) const;\n\n    /// <summary>\n    /// Compute set of tokens that can follow {@code s} in the ATN in the\n    /// specified {@code ctx}.\n    /// <p/>\n    /// If {@code ctx} is {@code null} and the end of the rule containing\n    /// {@code s} is reached, <seealso cref=\"Token#EPSILON\"/> is added to the result set.\n    /// If {@code ctx} is not {@code null} and the end of the outermost rule is\n    /// reached, <seealso cref=\"Token#EOF\"/> is added to the result set.\n    /// </summary>\n    /// <param name=\"s\"> the ATN state </param>\n    /// <param name=\"stopState\"> the ATN state to stop at. This can be a\n    /// <seealso cref=\"BlockEndState\"/> to detect epsilon paths through a closure. </param>\n    /// <param name=\"ctx\"> the complete parser context, or {@code null} if the context\n    /// should be ignored\n    /// </param>\n    /// <returns> The set of tokens that can follow {@code s} in the ATN in the\n    /// specified {@code ctx}. </returns>\n    misc::IntervalSet LOOK(ATNState *s, ATNState *stopState, RuleContext *ctx) const;\n\n  private:\n    const atn::ATN &_atn;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerATNConfig.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/DecisionState.h\"\n#include \"atn/PredictionContext.h\"\n#include \"SemanticContext.h\"\n#include \"atn/LexerActionExecutor.h\"\n\n#include \"support/CPPUtils.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerATNConfig.h\"\n\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nLexerATNConfig::LexerATNConfig(ATNState *state, int alt, Ref<const PredictionContext> context)\n    : ATNConfig(state, alt, std::move(context)) {}\n\nLexerATNConfig::LexerATNConfig(ATNState *state, int alt, Ref<const PredictionContext> context, Ref<const LexerActionExecutor> lexerActionExecutor)\n    : ATNConfig(state, alt, std::move(context)), _lexerActionExecutor(std::move(lexerActionExecutor)) {}\n\nLexerATNConfig::LexerATNConfig(LexerATNConfig const& other, ATNState *state)\n    : ATNConfig(other, state), _lexerActionExecutor(other._lexerActionExecutor), _passedThroughNonGreedyDecision(checkNonGreedyDecision(other, state)) {}\n\nLexerATNConfig::LexerATNConfig(LexerATNConfig const& other, ATNState *state, Ref<const LexerActionExecutor> lexerActionExecutor)\n    : ATNConfig(other, state), _lexerActionExecutor(std::move(lexerActionExecutor)), _passedThroughNonGreedyDecision(checkNonGreedyDecision(other, state)) {}\n\nLexerATNConfig::LexerATNConfig(LexerATNConfig const& other, ATNState *state, Ref<const PredictionContext> context)\n    : ATNConfig(other, state, std::move(context)), _lexerActionExecutor(other._lexerActionExecutor), _passedThroughNonGreedyDecision(checkNonGreedyDecision(other, state)) {}\n\nsize_t LexerATNConfig::hashCode() const {\n  size_t hashCode = misc::MurmurHash::initialize(7);\n  hashCode = misc::MurmurHash::update(hashCode, state->stateNumber);\n  hashCode = misc::MurmurHash::update(hashCode, alt);\n  hashCode = misc::MurmurHash::update(hashCode, context);\n  hashCode = misc::MurmurHash::update(hashCode, semanticContext);\n  hashCode = misc::MurmurHash::update(hashCode, _passedThroughNonGreedyDecision ? 1 : 0);\n  hashCode = misc::MurmurHash::update(hashCode, _lexerActionExecutor);\n  hashCode = misc::MurmurHash::finish(hashCode, 6);\n  return hashCode;\n}\n\nbool LexerATNConfig::operator==(const LexerATNConfig& other) const\n{\n  if (this == &other)\n    return true;\n\n  if (_passedThroughNonGreedyDecision != other._passedThroughNonGreedyDecision)\n    return false;\n\n  if (_lexerActionExecutor == nullptr)\n    return other._lexerActionExecutor == nullptr;\n  if (*_lexerActionExecutor != *(other._lexerActionExecutor)) {\n    return false;\n  }\n\n  return ATNConfig::operator==(other);\n}\n\nbool LexerATNConfig::checkNonGreedyDecision(LexerATNConfig const& source, ATNState *target) {\n  return source._passedThroughNonGreedyDecision ||\n    (DecisionState::is(target) && downCast<DecisionState*>(target)->nonGreedy);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerATNConfig.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/ATNConfig.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC LexerATNConfig final : public ATNConfig {\n  public:\n    LexerATNConfig(ATNState *state, int alt, Ref<const PredictionContext> context);\n    LexerATNConfig(ATNState *state, int alt, Ref<const PredictionContext> context, Ref<const LexerActionExecutor> lexerActionExecutor);\n\n    LexerATNConfig(LexerATNConfig const& other, ATNState *state);\n    LexerATNConfig(LexerATNConfig const& other, ATNState *state, Ref<const LexerActionExecutor> lexerActionExecutor);\n    LexerATNConfig(LexerATNConfig const& other, ATNState *state, Ref<const PredictionContext> context);\n\n    /**\n     * Gets the {@link LexerActionExecutor} capable of executing the embedded\n     * action(s) for the current configuration.\n     */\n    const Ref<const LexerActionExecutor>& getLexerActionExecutor() const { return _lexerActionExecutor; }\n    bool hasPassedThroughNonGreedyDecision() const { return _passedThroughNonGreedyDecision; }\n\n    size_t hashCode() const override;\n\n    bool operator==(const LexerATNConfig& other) const;\n\n  private:\n    /**\n     * This is the backing field for {@link #getLexerActionExecutor}.\n     */\n    const Ref<const LexerActionExecutor> _lexerActionExecutor;\n    const bool _passedThroughNonGreedyDecision = false;\n\n    static bool checkNonGreedyDecision(LexerATNConfig const& source, ATNState *target);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerATNSimulator.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cassert>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"IntStream.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/OrderedATNConfigSet.h\"\n#include \"Token.h\"\n#include \"LexerNoViableAltException.h\"\n#include \"atn/RuleStopState.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/SingletonPredictionContext.h\"\n#include \"atn/PredicateTransition.h\"\n#include \"atn/ActionTransition.h\"\n#include \"atn/TokensStartState.h\"\n#include \"misc/Interval.h\"\n#include \"dfa/DFA.h\"\n#include \"Lexer.h\"\n#include \"internal/Synchronization.h\"\n\n#include \"dfa/DFAState.h\"\n#include \"atn/LexerATNConfig.h\"\n#include \"atn/LexerActionExecutor.h\"\n\n#include \"atn/LexerATNSimulator.h\"\n\n#ifndef LEXER_DEBUG_ATN\n#define LEXER_DEBUG_ATN 0\n#endif\n#ifndef LEXER_DEBUG_DFA\n#define LEXER_DEBUG_DFA 0\n#endif\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::internal;\nusing namespace antlrcpp;\n\nvoid LexerATNSimulator::SimState::reset() {\n  *this = SimState();\n}\n\nLexerATNSimulator::LexerATNSimulator(const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                                     PredictionContextCache &sharedContextCache)\n  : LexerATNSimulator(nullptr, atn, decisionToDFA, sharedContextCache) {\n}\n\nLexerATNSimulator::LexerATNSimulator(Lexer *recog, const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                                     PredictionContextCache &sharedContextCache)\n  : ATNSimulator(atn, sharedContextCache), _recog(recog), _decisionToDFA(decisionToDFA) {\n  InitializeInstanceFields();\n}\n\nvoid LexerATNSimulator::copyState(LexerATNSimulator *simulator) {\n  _charPositionInLine = simulator->_charPositionInLine;\n  _line = simulator->_line;\n  _mode = simulator->_mode;\n  _startIndex = simulator->_startIndex;\n}\n\nsize_t LexerATNSimulator::match(CharStream *input, size_t mode) {\n  _mode = mode;\n  ssize_t mark = input->mark();\n\n  auto onExit = finally([input, mark] {\n    input->release(mark);\n  });\n\n  _startIndex = input->index();\n  _prevAccept.reset();\n  const dfa::DFA &dfa = _decisionToDFA[mode];\n  dfa::DFAState* s0;\n  {\n    SharedLock<SharedMutex> stateLock(atn._stateMutex);\n    s0 = dfa.s0;\n  }\n  if (s0 == nullptr) {\n    return matchATN(input);\n  } else {\n    return execATN(input, s0);\n  }\n}\n\nvoid LexerATNSimulator::reset() {\n  _prevAccept.reset();\n  _startIndex = 0;\n  _line = 1;\n  _charPositionInLine = 0;\n  _mode = Lexer::DEFAULT_MODE;\n}\n\nvoid LexerATNSimulator::clearDFA() {\n  size_t size = _decisionToDFA.size();\n  _decisionToDFA.clear();\n  for (size_t d = 0; d < size; ++d) {\n    _decisionToDFA.emplace_back(atn.getDecisionState(d), d);\n  }\n}\n\nsize_t LexerATNSimulator::matchATN(CharStream *input) {\n  ATNState *startState = atn.modeToStartState[_mode];\n\n  std::unique_ptr<ATNConfigSet> s0_closure = computeStartState(input, startState);\n\n  bool suppressEdge = s0_closure->hasSemanticContext;\n  s0_closure->hasSemanticContext = false;\n\n  dfa::DFAState *next = addDFAState(s0_closure.release(), suppressEdge);\n\n  size_t predict = execATN(input, next);\n\n  return predict;\n}\n\nsize_t LexerATNSimulator::execATN(CharStream *input, dfa::DFAState *ds0) {\n  if (ds0->isAcceptState) {\n    // allow zero-length tokens\n    // ml: in Java code this method uses 3 params. The first is a member var of the class anyway (_prevAccept), so why pass it here?\n    captureSimState(input, ds0);\n  }\n\n  size_t t = input->LA(1);\n  dfa::DFAState *s = ds0; // s is current/from DFA state\n\n  while (true) { // while more work\n    // As we move src->trg, src->trg, we keep track of the previous trg to\n    // avoid looking up the DFA state again, which is expensive.\n    // If the previous target was already part of the DFA, we might\n    // be able to avoid doing a reach operation upon t. If s!=null,\n    // it means that semantic predicates didn't prevent us from\n    // creating a DFA state. Once we know s!=null, we check to see if\n    // the DFA state has an edge already for t. If so, we can just reuse\n    // it's configuration set; there's no point in re-computing it.\n    // This is kind of like doing DFA simulation within the ATN\n    // simulation because DFA simulation is really just a way to avoid\n    // computing reach/closure sets. Technically, once we know that\n    // we have a previously added DFA state, we could jump over to\n    // the DFA simulator. But, that would mean popping back and forth\n    // a lot and making things more complicated algorithmically.\n    // This optimization makes a lot of sense for loops within DFA.\n    // A character will take us back to an existing DFA state\n    // that already has lots of edges out of it. e.g., .* in comments.\n    dfa::DFAState *target = getExistingTargetState(s, t);\n    if (target == nullptr) {\n      target = computeTargetState(input, s, t);\n    }\n\n    if (target == ERROR.get()) {\n      break;\n    }\n\n    // If this is a consumable input element, make sure to consume before\n    // capturing the accept state so the input index, line, and char\n    // position accurately reflect the state of the interpreter at the\n    // end of the token.\n    if (t != Token::EOF) {\n      consume(input);\n    }\n\n    if (target->isAcceptState) {\n      captureSimState(input, target);\n      if (t == Token::EOF) {\n        break;\n      }\n    }\n\n    t = input->LA(1);\n    s = target; // flip; current DFA target becomes new src/from state\n  }\n\n  return failOrAccept(input, s->configs.get(), t);\n}\n\ndfa::DFAState *LexerATNSimulator::getExistingTargetState(dfa::DFAState *s, size_t t) {\n  dfa::DFAState* retval = nullptr;\n  SharedLock<SharedMutex> edgeLock(atn._edgeMutex);\n  if (t <= MAX_DFA_EDGE) {\n    auto iterator = s->edges.find(t - MIN_DFA_EDGE);\n#if LEXER_DEBUG_ATN == 1\n    if (iterator != s->edges.end()) {\n      std::cout << std::string(\"reuse state \") << s->stateNumber << std::string(\" edge to \") << iterator->second->stateNumber << std::endl;\n    }\n#endif\n\n    if (iterator != s->edges.end())\n      retval = iterator->second;\n  }\n  return retval;\n}\n\ndfa::DFAState *LexerATNSimulator::computeTargetState(CharStream *input, dfa::DFAState *s, size_t t) {\n  OrderedATNConfigSet *reach = new OrderedATNConfigSet(); /* mem-check: deleted on error or managed by new DFA state. */\n\n  // if we don't find an existing DFA state\n  // Fill reach starting from closure, following t transitions\n  getReachableConfigSet(input, s->configs.get(), reach, t);\n\n  if (reach->isEmpty()) { // we got nowhere on t from s\n    if (!reach->hasSemanticContext) {\n      // we got nowhere on t, don't throw out this knowledge; it'd\n      // cause a failover from DFA later.\n      addDFAEdge(s, t, ERROR.get());\n    }\n    delete reach;\n\n    // stop when we can't match any more char\n    return ERROR.get();\n  }\n\n  // Add an edge from s to target DFA found/created for reach\n  return addDFAEdge(s, t, reach);\n}\n\nsize_t LexerATNSimulator::failOrAccept(CharStream *input, ATNConfigSet *reach, size_t t) {\n  if (_prevAccept.dfaState != nullptr) {\n    accept(input, _prevAccept.dfaState->lexerActionExecutor, _startIndex, _prevAccept.index, _prevAccept.line, _prevAccept.charPos);\n    return _prevAccept.dfaState->prediction;\n  } else {\n    // if no accept and EOF is first char, return EOF\n    if (t == Token::EOF && input->index() == _startIndex) {\n      return Token::EOF;\n    }\n\n    throw LexerNoViableAltException(_recog, input, _startIndex, reach);\n  }\n}\n\nvoid LexerATNSimulator::getReachableConfigSet(CharStream *input, ATNConfigSet *closure_, ATNConfigSet *reach, size_t t) {\n  // this is used to skip processing for configs which have a lower priority\n  // than a config that already reached an accept state for the same rule\n  size_t skipAlt = ATN::INVALID_ALT_NUMBER;\n\n  for (const auto &c : closure_->configs) {\n    bool currentAltReachedAcceptState = c->alt == skipAlt;\n    if (currentAltReachedAcceptState && (std::static_pointer_cast<LexerATNConfig>(c))->hasPassedThroughNonGreedyDecision()) {\n      continue;\n    }\n\n#if LEXER_DEBUG_ATN == 1\n      std::cout << \"testing \" << getTokenName((int)t) << \" at \" << c->toString(true) << std::endl;\n#endif\n\n    size_t n = c->state->transitions.size();\n    for (size_t ti = 0; ti < n; ti++) { // for each transition\n      const Transition *trans = c->state->transitions[ti].get();\n      ATNState *target = getReachableTarget(trans, (int)t);\n      if (target != nullptr) {\n        auto lexerActionExecutor = downCast<const LexerATNConfig&>(*c).getLexerActionExecutor();\n        if (lexerActionExecutor != nullptr) {\n          lexerActionExecutor = lexerActionExecutor->fixOffsetBeforeMatch((int)input->index() - (int)_startIndex);\n        }\n\n        bool treatEofAsEpsilon = t == Token::EOF;\n        Ref<LexerATNConfig> config = std::make_shared<LexerATNConfig>(downCast<const LexerATNConfig&>(*c),\n          target, std::move(lexerActionExecutor));\n\n        if (closure(input, config, reach, currentAltReachedAcceptState, true, treatEofAsEpsilon)) {\n          // any remaining configs for this alt have a lower priority than\n          // the one that just reached an accept state.\n          skipAlt = c->alt;\n          break;\n        }\n      }\n    }\n  }\n}\n\nvoid LexerATNSimulator::accept(CharStream *input, const Ref<const LexerActionExecutor> &lexerActionExecutor, size_t /*startIndex*/,\n                               size_t index, size_t line, size_t charPos) {\n#if LEXER_DEBUG_ATN == 1\n    std::cout << \"ACTION \";\n    std::cout << toString(lexerActionExecutor) << std::endl;\n#endif\n\n  // seek to after last char in token\n  input->seek(index);\n  _line = line;\n  _charPositionInLine = (int)charPos;\n\n  if (lexerActionExecutor != nullptr && _recog != nullptr) {\n    lexerActionExecutor->execute(_recog, input, _startIndex);\n  }\n}\n\natn::ATNState *LexerATNSimulator::getReachableTarget(const Transition *trans, size_t t) {\n  if (trans->matches(t, Lexer::MIN_CHAR_VALUE, Lexer::MAX_CHAR_VALUE)) {\n    return trans->target;\n  }\n\n  return nullptr;\n}\n\nstd::unique_ptr<ATNConfigSet> LexerATNSimulator::computeStartState(CharStream *input, ATNState *p) {\n  Ref<const PredictionContext> initialContext = PredictionContext::EMPTY; // ml: the purpose of this assignment is unclear\n  std::unique_ptr<ATNConfigSet> configs(new OrderedATNConfigSet());\n  for (size_t i = 0; i < p->transitions.size(); i++) {\n    ATNState *target = p->transitions[i]->target;\n    Ref<LexerATNConfig> c = std::make_shared<LexerATNConfig>(target, (int)(i + 1), initialContext);\n    closure(input, c, configs.get(), false, false, false);\n  }\n\n  return configs;\n}\n\nbool LexerATNSimulator::closure(CharStream *input, const Ref<LexerATNConfig> &config, ATNConfigSet *configs,\n                                bool currentAltReachedAcceptState, bool speculative, bool treatEofAsEpsilon) {\n#if LEXER_DEBUG_ATN == 1\n    std::cout << \"closure(\" << config->toString(true) << \")\" << std::endl;\n#endif\n\n  if (config->state != nullptr && config->state->getStateType() == ATNStateType::RULE_STOP) {\n#if LEXER_DEBUG_ATN == 1\n      if (_recog != nullptr) {\n        std::cout << \"closure at \" << _recog->getRuleNames()[config->state->ruleIndex] << \" rule stop \" << config << std::endl;\n      } else {\n        std::cout << \"closure at rule stop \" << config << std::endl;\n      }\n#endif\n\n    if (config->context == nullptr || config->context->hasEmptyPath()) {\n      if (config->context == nullptr || config->context->isEmpty()) {\n        configs->add(config);\n        return true;\n      } else {\n        configs->add(std::make_shared<LexerATNConfig>(*config, config->state, PredictionContext::EMPTY));\n        currentAltReachedAcceptState = true;\n      }\n    }\n\n    if (config->context != nullptr && !config->context->isEmpty()) {\n      for (size_t i = 0; i < config->context->size(); i++) {\n        if (config->context->getReturnState(i) != PredictionContext::EMPTY_RETURN_STATE) {\n          Ref<const PredictionContext> newContext = config->context->getParent(i); // \"pop\" return state\n          ATNState *returnState = atn.states[config->context->getReturnState(i)];\n          Ref<LexerATNConfig> c = std::make_shared<LexerATNConfig>(*config, returnState, newContext);\n          currentAltReachedAcceptState = closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n        }\n      }\n    }\n\n    return currentAltReachedAcceptState;\n  }\n\n  // optimization\n  if (!config->state->epsilonOnlyTransitions) {\n    if (!currentAltReachedAcceptState || !config->hasPassedThroughNonGreedyDecision()) {\n      configs->add(config);\n    }\n  }\n\n  ATNState *p = config->state;\n  for (size_t i = 0; i < p->transitions.size(); i++) {\n    const Transition *t = p->transitions[i].get();\n    Ref<LexerATNConfig> c = getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon);\n    if (c != nullptr) {\n      currentAltReachedAcceptState = closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n    }\n  }\n\n  return currentAltReachedAcceptState;\n}\n\nRef<LexerATNConfig> LexerATNSimulator::getEpsilonTarget(CharStream *input, const Ref<LexerATNConfig> &config, const Transition *t,\n  ATNConfigSet *configs, bool speculative, bool treatEofAsEpsilon) {\n\n  Ref<LexerATNConfig> c = nullptr;\n  switch (t->getTransitionType()) {\n    case TransitionType::RULE: {\n      const RuleTransition *ruleTransition = static_cast<const RuleTransition*>(t);\n      Ref<const PredictionContext> newContext = SingletonPredictionContext::create(config->context, ruleTransition->followState->stateNumber);\n      c = std::make_shared<LexerATNConfig>(*config, t->target, newContext);\n      break;\n    }\n\n    case TransitionType::PRECEDENCE:\n      throw UnsupportedOperationException(\"Precedence predicates are not supported in lexers.\");\n\n    case TransitionType::PREDICATE: {\n      /*  Track traversing semantic predicates. If we traverse,\n       we cannot add a DFA state for this \"reach\" computation\n       because the DFA would not test the predicate again in the\n       future. Rather than creating collections of semantic predicates\n       like v3 and testing them on prediction, v4 will test them on the\n       fly all the time using the ATN not the DFA. This is slower but\n       semantically it's not used that often. One of the key elements to\n       this predicate mechanism is not adding DFA states that see\n       predicates immediately afterwards in the ATN. For example,\n\n       a : ID {p1}? | ID {p2}? ;\n\n       should create the start state for rule 'a' (to save start state\n       competition), but should not create target of ID state. The\n       collection of ATN states the following ID references includes\n       states reached by traversing predicates. Since this is when we\n       test them, we cannot cash the DFA state target of ID.\n       */\n      const PredicateTransition *pt = static_cast<const PredicateTransition*>(t);\n\n#if LEXER_DEBUG_ATN == 1\n        std::cout << \"EVAL rule \" << pt->getRuleIndex() << \":\" << pt->getPredIndex() << std::endl;\n#endif\n\n      configs->hasSemanticContext = true;\n      if (evaluatePredicate(input, pt->getRuleIndex(), pt->getPredIndex(), speculative)) {\n        c = std::make_shared<LexerATNConfig>(*config, t->target);\n      }\n      break;\n    }\n\n    case TransitionType::ACTION:\n      if (config->context == nullptr|| config->context->hasEmptyPath()) {\n        // execute actions anywhere in the start rule for a token.\n        //\n        // TODO: if the entry rule is invoked recursively, some\n        // actions may be executed during the recursive call. The\n        // problem can appear when hasEmptyPath() is true but\n        // isEmpty() is false. In this case, the config needs to be\n        // split into two contexts - one with just the empty path\n        // and another with everything but the empty path.\n        // Unfortunately, the current algorithm does not allow\n        // getEpsilonTarget to return two configurations, so\n        // additional modifications are needed before we can support\n        // the split operation.\n        auto lexerActionExecutor = LexerActionExecutor::append(config->getLexerActionExecutor(),\n          atn.lexerActions[static_cast<const ActionTransition *>(t)->actionIndex]);\n        c = std::make_shared<LexerATNConfig>(*config, t->target, std::move(lexerActionExecutor));\n        break;\n      }\n      else {\n        // ignore actions in referenced rules\n        c = std::make_shared<LexerATNConfig>(*config, t->target);\n        break;\n      }\n\n    case TransitionType::EPSILON:\n      c = std::make_shared<LexerATNConfig>(*config, t->target);\n      break;\n\n    case TransitionType::ATOM:\n    case TransitionType::RANGE:\n    case TransitionType::SET:\n      if (treatEofAsEpsilon) {\n        if (t->matches(Token::EOF, Lexer::MIN_CHAR_VALUE, Lexer::MAX_CHAR_VALUE)) {\n          c = std::make_shared<LexerATNConfig>(*config, t->target);\n          break;\n        }\n      }\n\n      break;\n\n    default: // To silence the compiler. Other transition types are not used here.\n      break;\n  }\n\n  return c;\n}\n\nbool LexerATNSimulator::evaluatePredicate(CharStream *input, size_t ruleIndex, size_t predIndex, bool speculative) {\n  // assume true if no recognizer was provided\n  if (_recog == nullptr) {\n    return true;\n  }\n\n  if (!speculative) {\n    return _recog->sempred(nullptr, ruleIndex, predIndex);\n  }\n\n  size_t savedCharPositionInLine = _charPositionInLine;\n  size_t savedLine = _line;\n  size_t index = input->index();\n  ssize_t marker = input->mark();\n\n  auto onExit = finally([this, input, savedCharPositionInLine, savedLine, index, marker] {\n    _charPositionInLine = savedCharPositionInLine;\n    _line = savedLine;\n    input->seek(index);\n    input->release(marker);\n  });\n\n  consume(input);\n  return _recog->sempred(nullptr, ruleIndex, predIndex);\n}\n\nvoid LexerATNSimulator::captureSimState(CharStream *input, dfa::DFAState *dfaState) {\n  _prevAccept.index = input->index();\n  _prevAccept.line = _line;\n  _prevAccept.charPos = _charPositionInLine;\n  _prevAccept.dfaState = dfaState;\n}\n\ndfa::DFAState *LexerATNSimulator::addDFAEdge(dfa::DFAState *from, size_t t, ATNConfigSet *q) {\n  /* leading to this call, ATNConfigSet.hasSemanticContext is used as a\n   * marker indicating dynamic predicate evaluation makes this edge\n   * dependent on the specific input sequence, so the static edge in the\n   * DFA should be omitted. The target DFAState is still created since\n   * execATN has the ability to resynchronize with the DFA state cache\n   * following the predicate evaluation step.\n   *\n   * TJP notes: next time through the DFA, we see a pred again and eval.\n   * If that gets us to a previously created (but dangling) DFA\n   * state, we can continue in pure DFA mode from there.\n   */\n  bool suppressEdge = q->hasSemanticContext;\n  q->hasSemanticContext = false;\n\n  dfa::DFAState *to = addDFAState(q);\n\n  if (suppressEdge) {\n    return to;\n  }\n\n  addDFAEdge(from, t, to);\n  return to;\n}\n\nvoid LexerATNSimulator::addDFAEdge(dfa::DFAState *p, size_t t, dfa::DFAState *q) {\n  if (/*t < MIN_DFA_EDGE ||*/ t > MAX_DFA_EDGE) { // MIN_DFA_EDGE is 0\n    // Only track edges within the DFA bounds\n    return;\n  }\n\n  UniqueLock<SharedMutex> edgeLock(atn._edgeMutex);\n  p->edges[t - MIN_DFA_EDGE] = q; // connect\n}\n\ndfa::DFAState *LexerATNSimulator::addDFAState(ATNConfigSet *configs) {\n  return addDFAState(configs, true);\n}\n\ndfa::DFAState *LexerATNSimulator::addDFAState(ATNConfigSet *configs, bool suppressEdge) {\n  /* the lexer evaluates predicates on-the-fly; by this point configs\n   * should not contain any configurations with unevaluated predicates.\n   */\n  assert(!configs->hasSemanticContext);\n\n  dfa::DFAState *proposed = new dfa::DFAState(std::unique_ptr<ATNConfigSet>(configs)); /* mem-check: managed by the DFA or deleted below */\n  Ref<ATNConfig> firstConfigWithRuleStopState = nullptr;\n  for (const auto &c : configs->configs) {\n    if (RuleStopState::is(c->state)) {\n      firstConfigWithRuleStopState = c;\n      break;\n    }\n  }\n\n  if (firstConfigWithRuleStopState != nullptr) {\n    proposed->isAcceptState = true;\n    proposed->lexerActionExecutor = downCast<const LexerATNConfig&>(*firstConfigWithRuleStopState).getLexerActionExecutor();\n    proposed->prediction = atn.ruleToTokenType[firstConfigWithRuleStopState->state->ruleIndex];\n  }\n\n  dfa::DFA &dfa = _decisionToDFA[_mode];\n\n  {\n    UniqueLock<SharedMutex> stateLock(atn._stateMutex);\n    auto [existing, inserted] = dfa.states.insert(proposed);\n    if (!inserted) {\n      delete proposed;\n      proposed = *existing;\n    } else {\n      // Previously we did a lookup, then set fields, then inserted. It was `dfa.states.size()`,\n      // since we already inserted we need to subtract one.\n      proposed->stateNumber = static_cast<int>(dfa.states.size() - 1);\n      proposed->configs->setReadonly(true);\n    }\n    if (!suppressEdge) {\n      dfa.s0 = proposed;\n    }\n  }\n\n  return proposed;\n}\n\ndfa::DFA& LexerATNSimulator::getDFA(size_t mode) {\n  return _decisionToDFA[mode];\n}\n\nstd::string LexerATNSimulator::getText(CharStream *input) {\n  // index is first lookahead char, don't include.\n  return input->getText(misc::Interval(_startIndex, input->index() - 1));\n}\n\nsize_t LexerATNSimulator::getLine() const {\n  return _line;\n}\n\nvoid LexerATNSimulator::setLine(size_t line) {\n  _line = line;\n}\n\nsize_t LexerATNSimulator::getCharPositionInLine() {\n  return _charPositionInLine;\n}\n\nvoid LexerATNSimulator::setCharPositionInLine(size_t charPositionInLine) {\n  _charPositionInLine = charPositionInLine;\n}\n\nvoid LexerATNSimulator::consume(CharStream *input) {\n  size_t curChar = input->LA(1);\n  if (curChar == '\\n') {\n    _line++;\n    _charPositionInLine = 0;\n  } else {\n    _charPositionInLine++;\n  }\n  input->consume();\n}\n\nstd::string LexerATNSimulator::getTokenName(size_t t) {\n  if (t == Token::EOF) {\n    return \"EOF\";\n  }\n  return std::string(\"'\") + static_cast<char>(t) + std::string(\"'\");\n}\n\nvoid LexerATNSimulator::InitializeInstanceFields() {\n  _startIndex = 0;\n  _line = 1;\n  _charPositionInLine = 0;\n  _mode = antlr4::Lexer::DEFAULT_MODE;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerATNSimulator.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include <atomic>\n\n#include \"atn/ATNSimulator.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerATNConfig.h\"\n#include \"atn/ATNConfigSet.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// \"dup\" of ParserInterpreter\n  class ANTLR4CPP_PUBLIC LexerATNSimulator : public ATNSimulator {\n  protected:\n    struct ANTLR4CPP_PUBLIC SimState final {\n      size_t index = INVALID_INDEX;\n      size_t line = 0;\n      size_t charPos = INVALID_INDEX;\n      dfa::DFAState *dfaState = nullptr;\n\n      void reset();\n    };\n\n  public:\n    static constexpr size_t MIN_DFA_EDGE = 0;\n    static constexpr size_t MAX_DFA_EDGE = 127; // forces unicode to stay in ATN\n\n  protected:\n    /// <summary>\n    /// When we hit an accept state in either the DFA or the ATN, we\n    ///  have to notify the character stream to start buffering characters\n    ///  via <seealso cref=\"IntStream#mark\"/> and record the current state. The current sim state\n    ///  includes the current index into the input, the current line,\n    ///  and current character position in that line. Note that the Lexer is\n    ///  tracking the starting line and characterization of the token. These\n    ///  variables track the \"state\" of the simulator when it hits an accept state.\n    /// <p/>\n    ///  We track these variables separately for the DFA and ATN simulation\n    ///  because the DFA simulation often has to fail over to the ATN\n    ///  simulation. If the ATN simulation fails, we need the DFA to fall\n    ///  back to its previously accepted state, if any. If the ATN succeeds,\n    ///  then the ATN does the accept and the DFA simulator that invoked it\n    ///  can simply return the predicted token type.\n    /// </summary>\n    Lexer *const _recog;\n\n    /// The current token's starting index into the character stream.\n    ///  Shared across DFA to ATN simulation in case the ATN fails and the\n    ///  DFA did not have a previous accept state. In this case, we use the\n    ///  ATN-generated exception object.\n    size_t _startIndex;\n\n    /// line number 1..n within the input.\n    size_t _line;\n\n    /// The index of the character relative to the beginning of the line 0..n-1.\n    size_t _charPositionInLine;\n\n  public:\n    std::vector<dfa::DFA> &_decisionToDFA;\n\n  protected:\n    size_t _mode;\n\n    /// Used during DFA/ATN exec to record the most recent accept configuration info.\n    SimState _prevAccept;\n\n  public:\n    LexerATNSimulator(const ATN &atn, std::vector<dfa::DFA> &decisionToDFA, PredictionContextCache &sharedContextCache);\n    LexerATNSimulator(Lexer *recog, const ATN &atn, std::vector<dfa::DFA> &decisionToDFA, PredictionContextCache &sharedContextCache);\n    ~LexerATNSimulator() override = default;\n\n    virtual void copyState(LexerATNSimulator *simulator);\n    virtual size_t match(CharStream *input, size_t mode);\n    void reset() override;\n\n    void clearDFA() override;\n\n  protected:\n    virtual size_t matchATN(CharStream *input);\n    virtual size_t execATN(CharStream *input, dfa::DFAState *ds0);\n\n    /// <summary>\n    /// Get an existing target state for an edge in the DFA. If the target state\n    /// for the edge has not yet been computed or is otherwise not available,\n    /// this method returns {@code null}.\n    /// </summary>\n    /// <param name=\"s\"> The current DFA state </param>\n    /// <param name=\"t\"> The next input symbol </param>\n    /// <returns> The existing target DFA state for the given input symbol\n    /// {@code t}, or {@code null} if the target state for this edge is not\n    /// already cached </returns>\n    virtual dfa::DFAState *getExistingTargetState(dfa::DFAState *s, size_t t);\n\n    /// <summary>\n    /// Compute a target state for an edge in the DFA, and attempt to add the\n    /// computed state and corresponding edge to the DFA.\n    /// </summary>\n    /// <param name=\"input\"> The input stream </param>\n    /// <param name=\"s\"> The current DFA state </param>\n    /// <param name=\"t\"> The next input symbol\n    /// </param>\n    /// <returns> The computed target DFA state for the given input symbol\n    /// {@code t}. If {@code t} does not lead to a valid DFA state, this method\n    /// returns <seealso cref=\"#ERROR\"/>. </returns>\n    virtual dfa::DFAState *computeTargetState(CharStream *input, dfa::DFAState *s, size_t t);\n\n    virtual size_t failOrAccept(CharStream *input, ATNConfigSet *reach, size_t t);\n\n    /// <summary>\n    /// Given a starting configuration set, figure out all ATN configurations\n    ///  we can reach upon input {@code t}. Parameter {@code reach} is a return\n    ///  parameter.\n    /// </summary>\n    void getReachableConfigSet(CharStream *input, ATNConfigSet *closure_, // closure_ as we have a closure() already\n                               ATNConfigSet *reach, size_t t);\n\n    virtual void accept(CharStream *input, const Ref<const LexerActionExecutor> &lexerActionExecutor, size_t startIndex, size_t index,\n                        size_t line, size_t charPos);\n\n    virtual ATNState *getReachableTarget(const Transition *trans, size_t t);\n\n    virtual std::unique_ptr<ATNConfigSet> computeStartState(CharStream *input, ATNState *p);\n\n    /// <summary>\n    /// Since the alternatives within any lexer decision are ordered by\n    /// preference, this method stops pursuing the closure as soon as an accept\n    /// state is reached. After the first accept state is reached by depth-first\n    /// search from {@code config}, all other (potentially reachable) states for\n    /// this rule would have a lower priority.\n    /// </summary>\n    /// <returns> {@code true} if an accept state is reached, otherwise\n    /// {@code false}. </returns>\n    virtual bool closure(CharStream *input, const Ref<LexerATNConfig> &config, ATNConfigSet *configs,\n                         bool currentAltReachedAcceptState, bool speculative, bool treatEofAsEpsilon);\n\n    // side-effect: can alter configs.hasSemanticContext\n    virtual Ref<LexerATNConfig> getEpsilonTarget(CharStream *input, const Ref<LexerATNConfig> &config, const Transition *t,\n      ATNConfigSet *configs, bool speculative, bool treatEofAsEpsilon);\n\n    /// <summary>\n    /// Evaluate a predicate specified in the lexer.\n    /// <p/>\n    /// If {@code speculative} is {@code true}, this method was called before\n    /// <seealso cref=\"#consume\"/> for the matched character. This method should call\n    /// <seealso cref=\"#consume\"/> before evaluating the predicate to ensure position\n    /// sensitive values, including <seealso cref=\"Lexer#getText\"/>, <seealso cref=\"Lexer#getLine\"/>,\n    /// and <seealso cref=\"Lexer#getCharPositionInLine\"/>, properly reflect the current\n    /// lexer state. This method should restore {@code input} and the simulator\n    /// to the original state before returning (i.e. undo the actions made by the\n    /// call to <seealso cref=\"#consume\"/>.\n    /// </summary>\n    /// <param name=\"input\"> The input stream. </param>\n    /// <param name=\"ruleIndex\"> The rule containing the predicate. </param>\n    /// <param name=\"predIndex\"> The index of the predicate within the rule. </param>\n    /// <param name=\"speculative\"> {@code true} if the current index in {@code input} is\n    /// one character before the predicate's location.\n    /// </param>\n    /// <returns> {@code true} if the specified predicate evaluates to\n    /// {@code true}. </returns>\n    virtual bool evaluatePredicate(CharStream *input, size_t ruleIndex, size_t predIndex, bool speculative);\n\n    virtual void captureSimState(CharStream *input, dfa::DFAState *dfaState);\n    virtual dfa::DFAState* addDFAEdge(dfa::DFAState *from, size_t t, ATNConfigSet *q);\n    virtual void addDFAEdge(dfa::DFAState *p, size_t t, dfa::DFAState *q);\n\n    /// <summary>\n    /// Add a new DFA state if there isn't one with this set of\n    /// configurations already. This method also detects the first\n    /// configuration containing an ATN rule stop state. Later, when\n    /// traversing the DFA, we will know which rule to accept.\n    /// </summary>\n    virtual dfa::DFAState *addDFAState(ATNConfigSet *configs);\n\n    virtual dfa::DFAState *addDFAState(ATNConfigSet *configs, bool suppressEdge);\n\n  public:\n    dfa::DFA& getDFA(size_t mode);\n\n    /// Get the text matched so far for the current token.\n    virtual std::string getText(CharStream *input);\n    virtual size_t getLine() const;\n    virtual void setLine(size_t line);\n    virtual size_t getCharPositionInLine();\n    virtual void setCharPositionInLine(size_t charPositionInLine);\n    virtual void consume(CharStream *input);\n    virtual std::string getTokenName(size_t t);\n\n  private:\n    void InitializeInstanceFields();\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerAction.cpp",
    "content": "#include <limits>\n#include <cstddef>\n#include \"LexerAction.h\"\n\nusing namespace antlr4::atn;\n\nsize_t LexerAction::hashCode() const {\n  auto hash = cachedHashCode();\n  if (hash == 0) {\n    hash = hashCodeImpl();\n    if (hash == 0) {\n      hash = std::numeric_limits<size_t>::max();\n    }\n    _hashCode.store(hash, std::memory_order_relaxed);\n  }\n  return hash;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerActionType.h\"\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Represents a single action which can be executed following the successful\n  /// match of a lexer rule. Lexer actions are used for both embedded action syntax\n  /// and ANTLR 4's new lexer command syntax.\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerAction {\n  public:\n    virtual ~LexerAction() = default;\n\n    /// <summary>\n    /// Gets the serialization type of the lexer action.\n    /// </summary>\n    /// <returns> The serialization type of the lexer action. </returns>\n    ///\n    /// IMPORTANT: Unlike Java, this returns LexerActionType::INDEXED_CUSTOM for instances of\n    /// LexerIndexedCustomAction. If you need the wrapped action type, use\n    /// LexerIndexedCustomAction::getAction()->getActionType().\n    LexerActionType getActionType() const { return _actionType; }\n\n    /// <summary>\n    /// Gets whether the lexer action is position-dependent. Position-dependent\n    /// actions may have different semantics depending on the <seealso cref=\"CharStream\"/>\n    /// index at the time the action is executed.\n    ///\n    /// <para>Many lexer commands, including {@code type}, {@code skip}, and\n    /// {@code more}, do not check the input index during their execution.\n    /// Actions like this are position-independent, and may be stored more\n    /// efficiently as part of the <seealso cref=\"LexerATNConfig#lexerActionExecutor\"/>.</para>\n    /// </summary>\n    /// <returns> {@code true} if the lexer action semantics can be affected by the\n    /// position of the input <seealso cref=\"CharStream\"/> at the time it is executed;\n    /// otherwise, {@code false}. </returns>\n    bool isPositionDependent() const { return _positionDependent; }\n\n    /// <summary>\n    /// Execute the lexer action in the context of the specified <seealso cref=\"Lexer\"/>.\n    ///\n    /// <para>For position-dependent actions, the input stream must already be\n    /// positioned correctly prior to calling this method.</para>\n    /// </summary>\n    /// <param name=\"lexer\"> The lexer instance. </param>\n    virtual void execute(Lexer *lexer) const = 0;\n\n    size_t hashCode() const;\n\n    virtual bool equals(const LexerAction &other) const = 0;\n\n    virtual std::string toString() const = 0;\n\n  protected:\n    LexerAction(LexerActionType actionType, bool positionDependent)\n        : _actionType(actionType), _hashCode(0), _positionDependent(positionDependent) {}\n\n    virtual size_t hashCodeImpl() const = 0;\n\n    size_t cachedHashCode() const { return _hashCode.load(std::memory_order_relaxed); }\n\n  private:\n    const LexerActionType _actionType;\n    mutable std::atomic<size_t> _hashCode;\n    const bool _positionDependent;\n  };\n\n  inline bool operator==(const LexerAction &lhs, const LexerAction &rhs) {\n    return lhs.equals(rhs);\n  }\n\n  inline bool operator!=(const LexerAction &lhs, const LexerAction &rhs) {\n    return !operator==(lhs, rhs);\n  }\n\n}  // namespace atn\n}  // namespace antlr4\n\nnamespace std {\n\n  template <>\n  struct hash<::antlr4::atn::LexerAction> {\n    size_t operator()(const ::antlr4::atn::LexerAction &lexerAction) const {\n      return lexerAction.hashCode();\n    }\n  };\n\n}  // namespace std\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerActionExecutor.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <limits>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerIndexedCustomAction.h\"\n#include \"atn/HashUtils.h\"\n#include \"support/CPPUtils.h\"\n#include \"support/Arrays.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerActionExecutor.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nnamespace {\n\n  bool lexerActionEqual(const Ref<const LexerAction> &lhs, const Ref<const LexerAction> &rhs) {\n    return *lhs == *rhs;\n  }\n\n}\n\nLexerActionExecutor::LexerActionExecutor(std::vector<Ref<const LexerAction>> lexerActions)\n    : _lexerActions(std::move(lexerActions)), _hashCode(0) {}\n\nRef<const LexerActionExecutor> LexerActionExecutor::append(const Ref<const LexerActionExecutor> &lexerActionExecutor,\n                                                           Ref<const LexerAction> lexerAction) {\n  if (lexerActionExecutor == nullptr) {\n    return std::make_shared<LexerActionExecutor>(std::vector<Ref<const LexerAction>>{ std::move(lexerAction) });\n  }\n  std::vector<Ref<const LexerAction>> lexerActions;\n  lexerActions.reserve(lexerActionExecutor->_lexerActions.size() + 1);\n  lexerActions.insert(lexerActions.begin(), lexerActionExecutor->_lexerActions.begin(), lexerActionExecutor->_lexerActions.end());\n  lexerActions.push_back(std::move(lexerAction));\n  return std::make_shared<LexerActionExecutor>(std::move(lexerActions));\n}\n\nRef<const LexerActionExecutor> LexerActionExecutor::fixOffsetBeforeMatch(int offset) const {\n  std::vector<Ref<const LexerAction>> updatedLexerActions;\n  for (size_t i = 0; i < _lexerActions.size(); i++) {\n    if (_lexerActions[i]->isPositionDependent() && !LexerIndexedCustomAction::is(*_lexerActions[i])) {\n      if (updatedLexerActions.empty()) {\n        updatedLexerActions = _lexerActions; // Make a copy.\n      }\n      updatedLexerActions[i] = std::make_shared<LexerIndexedCustomAction>(offset, _lexerActions[i]);\n    }\n  }\n  if (updatedLexerActions.empty()) {\n    return shared_from_this();\n  }\n  return std::make_shared<LexerActionExecutor>(std::move(updatedLexerActions));\n}\n\nconst std::vector<Ref<const LexerAction>>& LexerActionExecutor::getLexerActions() const {\n  return _lexerActions;\n}\n\nvoid LexerActionExecutor::execute(Lexer *lexer, CharStream *input, size_t startIndex) const {\n  bool requiresSeek = false;\n  size_t stopIndex = input->index();\n\n  auto onExit = finally([requiresSeek, input, stopIndex]() {\n    if (requiresSeek) {\n      input->seek(stopIndex);\n    }\n  });\n  for (const auto &lexerAction : _lexerActions) {\n    if (LexerIndexedCustomAction::is(*lexerAction)) {\n      int offset = downCast<const LexerIndexedCustomAction&>(*lexerAction).getOffset();\n      input->seek(startIndex + offset);\n      requiresSeek = (startIndex + offset) != stopIndex;\n    } else if (lexerAction->isPositionDependent()) {\n      input->seek(stopIndex);\n      requiresSeek = false;\n    }\n    lexerAction->execute(lexer);\n  }\n}\n\nsize_t LexerActionExecutor::hashCode() const {\n  auto hash = _hashCode.load(std::memory_order_relaxed);\n  if (hash == 0) {\n    hash = MurmurHash::initialize();\n    for (const auto &lexerAction : _lexerActions) {\n      hash = MurmurHash::update(hash, lexerAction);\n    }\n    hash = MurmurHash::finish(hash, _lexerActions.size());\n    if (hash == 0) {\n      hash = std::numeric_limits<size_t>::max();\n    }\n    _hashCode.store(hash, std::memory_order_relaxed);\n  }\n  return hash;\n}\n\nbool LexerActionExecutor::equals(const LexerActionExecutor &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  return cachedHashCodeEqual(_hashCode.load(std::memory_order_relaxed), other._hashCode.load(std::memory_order_relaxed)) &&\n         _lexerActions.size() == other._lexerActions.size() &&\n         std::equal(_lexerActions.begin(), _lexerActions.end(), other._lexerActions.begin(), lexerActionEqual);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerActionExecutor.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <cstddef>\n#include \"CharStream.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerAction.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Represents an executor for a sequence of lexer actions which traversed during\n  /// the matching operation of a lexer rule (token).\n  ///\n  /// <para>The executor tracks position information for position-dependent lexer actions\n  /// efficiently, ensuring that actions appearing only at the end of the rule do\n  /// not cause bloating of the <seealso cref=\"DFA\"/> created for the lexer.</para>\n  class ANTLR4CPP_PUBLIC LexerActionExecutor final : public std::enable_shared_from_this<LexerActionExecutor> {\n  public:\n    /// <summary>\n    /// Constructs an executor for a sequence of <seealso cref=\"LexerAction\"/> actions. </summary>\n    /// <param name=\"lexerActions\"> The lexer actions to execute. </param>\n    explicit LexerActionExecutor(std::vector<Ref<const LexerAction>> lexerActions);\n\n    /// <summary>\n    /// Creates a <seealso cref=\"LexerActionExecutor\"/> which executes the actions for\n    /// the input {@code lexerActionExecutor} followed by a specified\n    /// {@code lexerAction}.\n    /// </summary>\n    /// <param name=\"lexerActionExecutor\"> The executor for actions already traversed by\n    /// the lexer while matching a token within a particular\n    /// <seealso cref=\"LexerATNConfig\"/>. If this is {@code null}, the method behaves as\n    /// though it were an empty executor. </param>\n    /// <param name=\"lexerAction\"> The lexer action to execute after the actions\n    /// specified in {@code lexerActionExecutor}.\n    /// </param>\n    /// <returns> A <seealso cref=\"LexerActionExecutor\"/> for executing the combine actions\n    /// of {@code lexerActionExecutor} and {@code lexerAction}. </returns>\n    static Ref<const LexerActionExecutor> append(const Ref<const LexerActionExecutor> &lexerActionExecutor,\n                                                 Ref<const LexerAction> lexerAction);\n\n    /// <summary>\n    /// Creates a <seealso cref=\"LexerActionExecutor\"/> which encodes the current offset\n    /// for position-dependent lexer actions.\n    ///\n    /// <para>Normally, when the executor encounters lexer actions where\n    /// <seealso cref=\"LexerAction#isPositionDependent\"/> returns {@code true}, it calls\n    /// <seealso cref=\"IntStream#seek\"/> on the input <seealso cref=\"CharStream\"/> to set the input\n    /// position to the <em>end</em> of the current token. This behavior provides\n    /// for efficient DFA representation of lexer actions which appear at the end\n    /// of a lexer rule, even when the lexer rule matches a variable number of\n    /// characters.</para>\n    ///\n    /// <para>Prior to traversing a match transition in the ATN, the current offset\n    /// from the token start index is assigned to all position-dependent lexer\n    /// actions which have not already been assigned a fixed offset. By storing\n    /// the offsets relative to the token start index, the DFA representation of\n    /// lexer actions which appear in the middle of tokens remains efficient due\n    /// to sharing among tokens of the same length, regardless of their absolute\n    /// position in the input stream.</para>\n    ///\n    /// <para>If the current executor already has offsets assigned to all\n    /// position-dependent lexer actions, the method returns {@code this}.</para>\n    /// </summary>\n    /// <param name=\"offset\"> The current offset to assign to all position-dependent\n    /// lexer actions which do not already have offsets assigned.\n    /// </param>\n    /// <returns> A <seealso cref=\"LexerActionExecutor\"/> which stores input stream offsets\n    /// for all position-dependent lexer actions. </returns>\n    Ref<const LexerActionExecutor> fixOffsetBeforeMatch(int offset) const;\n\n    /// <summary>\n    /// Gets the lexer actions to be executed by this executor. </summary>\n    /// <returns> The lexer actions to be executed by this executor. </returns>\n    const std::vector<Ref<const LexerAction>>& getLexerActions() const;\n\n    /// <summary>\n    /// Execute the actions encapsulated by this executor within the context of a\n    /// particular <seealso cref=\"Lexer\"/>.\n    ///\n    /// <para>This method calls <seealso cref=\"IntStream#seek\"/> to set the position of the\n    /// {@code input} <seealso cref=\"CharStream\"/> prior to calling\n    /// <seealso cref=\"LexerAction#execute\"/> on a position-dependent action. Before the\n    /// method returns, the input position will be restored to the same position\n    /// it was in when the method was invoked.</para>\n    /// </summary>\n    /// <param name=\"lexer\"> The lexer instance. </param>\n    /// <param name=\"input\"> The input stream which is the source for the current token.\n    /// When this method is called, the current <seealso cref=\"IntStream#index\"/> for\n    /// {@code input} should be the start of the following token, i.e. 1\n    /// character past the end of the current token. </param>\n    /// <param name=\"startIndex\"> The token start index. This value may be passed to\n    /// <seealso cref=\"IntStream#seek\"/> to set the {@code input} position to the beginning\n    /// of the token. </param>\n    void execute(Lexer *lexer, CharStream *input, size_t startIndex) const;\n\n    size_t hashCode() const;\n\n    bool equals(const LexerActionExecutor &other) const;\n\n  private:\n    const std::vector<Ref<const LexerAction>> _lexerActions;\n    mutable std::atomic<size_t> _hashCode;\n  };\n\n  inline bool operator==(const LexerActionExecutor &lhs, const LexerActionExecutor &rhs) {\n    return lhs.equals(rhs);\n  }\n\n  inline bool operator!=(const LexerActionExecutor &lhs, const LexerActionExecutor &rhs) {\n    return !operator==(lhs, rhs);\n  }\n\n}  // namespace atn\n}  // namespace antlr4\n\nnamespace std {\n\n  template <>\n  struct hash<::antlr4::atn::LexerActionExecutor> {\n    size_t operator()(const ::antlr4::atn::LexerActionExecutor &lexerActionExecutor) const {\n      return lexerActionExecutor.hashCode();\n    }\n  };\n\n}  // namespace std\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerActionType.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Represents the serialization type of a <seealso cref=\"LexerAction\"/>.\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  enum class LexerActionType : size_t {\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerChannelAction\"/> action.\n    /// </summary>\n    CHANNEL = 0,\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerCustomAction\"/> action.\n    /// </summary>\n    CUSTOM,\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerModeAction\"/> action.\n    /// </summary>\n    MODE,\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerMoreAction\"/> action.\n    /// </summary>\n    MORE,\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerPopModeAction\"/> action.\n    /// </summary>\n    POP_MODE,\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerPushModeAction\"/> action.\n    /// </summary>\n    PUSH_MODE,\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerSkipAction\"/> action.\n    /// </summary>\n    SKIP,\n    /// <summary>\n    /// The type of a <seealso cref=\"LexerTypeAction\"/> action.\n    /// </summary>\n    TYPE,\n\n    INDEXED_CUSTOM,\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerChannelAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"Lexer.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerChannelAction.h\"\n\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nLexerChannelAction::LexerChannelAction(int channel)\n    : LexerAction(LexerActionType::CHANNEL, false), _channel(channel) {}\n\nvoid LexerChannelAction::execute(Lexer *lexer) const {\n  lexer->setChannel(getChannel());\n}\n\nsize_t LexerChannelAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  hash = MurmurHash::update(hash, getChannel());\n  return MurmurHash::finish(hash, 2);\n}\n\nbool LexerChannelAction::equals(const LexerAction &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getActionType() != other.getActionType()) {\n    return false;\n  }\n  const auto &lexerAction = downCast<const LexerChannelAction&>(other);\n  return getChannel() == lexerAction.getChannel();\n}\n\nstd::string LexerChannelAction::toString() const {\n  return \"channel(\" + std::to_string(getChannel()) + \")\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerChannelAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerAction.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerActionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  using antlr4::Lexer;\n\n  /// <summary>\n  /// Implements the {@code channel} lexer action by calling\n  /// <seealso cref=\"Lexer#setChannel\"/> with the assigned channel.\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerChannelAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::CHANNEL; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Constructs a new {@code channel} action with the specified channel value. </summary>\n    /// <param name=\"channel\"> The channel value to pass to <seealso cref=\"Lexer#setChannel\"/>. </param>\n    explicit LexerChannelAction(int channel);\n\n    /// <summary>\n    /// Gets the channel to use for the <seealso cref=\"Token\"/> created by the lexer.\n    /// </summary>\n    /// <returns> The channel to use for the <seealso cref=\"Token\"/> created by the lexer. </returns>\n    int getChannel() const { return _channel; }\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>This action is implemented by calling <seealso cref=\"Lexer#setChannel\"/> with the\n    /// value provided by <seealso cref=\"#getChannel\"/>.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &other) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    const int _channel;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerCustomAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"Lexer.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerCustomAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nLexerCustomAction::LexerCustomAction(size_t ruleIndex, size_t actionIndex)\n    : LexerAction(LexerActionType::CUSTOM, true), _ruleIndex(ruleIndex), _actionIndex(actionIndex) {}\n\nvoid LexerCustomAction::execute(Lexer *lexer) const {\n  lexer->action(nullptr, getRuleIndex(), getActionIndex());\n}\n\nsize_t LexerCustomAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  hash = MurmurHash::update(hash, getRuleIndex());\n  hash = MurmurHash::update(hash, getActionIndex());\n  return MurmurHash::finish(hash, 3);\n}\n\nbool LexerCustomAction::equals(const LexerAction &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getActionType() != other.getActionType()) {\n    return false;\n  }\n  const auto &lexerAction = downCast<const LexerCustomAction&>(other);\n  return getRuleIndex() == lexerAction.getRuleIndex() && getActionIndex() == lexerAction.getActionIndex();\n}\n\nstd::string LexerCustomAction::toString() const {\n  return \"custom(\" + std::to_string(getRuleIndex()) + \", \" + std::to_string(getActionIndex()) + \")\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerCustomAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerAction.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerActionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Executes a custom lexer action by calling <seealso cref=\"Recognizer#action\"/> with the\n  /// rule and action indexes assigned to the custom action. The implementation of\n  /// a custom action is added to the generated code for the lexer in an override\n  /// of <seealso cref=\"Recognizer#action\"/> when the grammar is compiled.\n  ///\n  /// <para>This class may represent embedded actions created with the <code>{...}</code>\n  /// syntax in ANTLR 4, as well as actions created for lexer commands where the\n  /// command argument could not be evaluated when the grammar was compiled.</para>\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerCustomAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::CUSTOM; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Constructs a custom lexer action with the specified rule and action\n    /// indexes.\n    /// </summary>\n    /// <param name=\"ruleIndex\"> The rule index to use for calls to\n    /// <seealso cref=\"Recognizer#action\"/>. </param>\n    /// <param name=\"actionIndex\"> The action index to use for calls to\n    /// <seealso cref=\"Recognizer#action\"/>. </param>\n    LexerCustomAction(size_t ruleIndex, size_t actionIndex);\n\n    /// <summary>\n    /// Gets the rule index to use for calls to <seealso cref=\"Recognizer#action\"/>.\n    /// </summary>\n    /// <returns> The rule index for the custom action. </returns>\n    size_t getRuleIndex() const { return _ruleIndex; }\n\n    /// <summary>\n    /// Gets the action index to use for calls to <seealso cref=\"Recognizer#action\"/>.\n    /// </summary>\n    /// <returns> The action index for the custom action. </returns>\n    size_t getActionIndex() const { return _actionIndex; }\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>Custom actions are implemented by calling <seealso cref=\"Lexer#action\"/> with the\n    /// appropriate rule and action indexes.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &other) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    const size_t _ruleIndex;\n    const size_t _actionIndex;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerIndexedCustomAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"atn/HashUtils.h\"\n#include \"antlr4-common.h\"\n#include \"misc/MurmurHash.h\"\n#include \"Lexer.h\"\n#include \"support/CPPUtils.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerIndexedCustomAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nLexerIndexedCustomAction::LexerIndexedCustomAction(int offset, Ref<const LexerAction> action)\n    : LexerAction(LexerActionType::INDEXED_CUSTOM, true), _action(std::move(action)), _offset(offset) {}\n\nvoid LexerIndexedCustomAction::execute(Lexer *lexer) const {\n  // assume the input stream position was properly set by the calling code\n  getAction()->execute(lexer);\n}\n\nsize_t LexerIndexedCustomAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  hash = MurmurHash::update(hash, getOffset());\n  hash = MurmurHash::update(hash, getAction());\n  return MurmurHash::finish(hash, 3);\n}\n\nbool LexerIndexedCustomAction::equals(const LexerAction &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getActionType() != other.getActionType()) {\n    return false;\n  }\n  const auto &lexerAction = downCast<const LexerIndexedCustomAction&>(other);\n  return getOffset() == lexerAction.getOffset() &&\n         cachedHashCodeEqual(cachedHashCode(), lexerAction.cachedHashCode()) &&\n         *getAction() == *lexerAction.getAction();\n}\n\nstd::string LexerIndexedCustomAction::toString() const {\n  return \"indexedCustom(\" + std::to_string(getOffset()) + \", \" + getAction()->toString() + \")\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerIndexedCustomAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"RuleContext.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerAction.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// This implementation of <seealso cref=\"LexerAction\"/> is used for tracking input offsets\n  /// for position-dependent actions within a <seealso cref=\"LexerActionExecutor\"/>.\n  ///\n  /// <para>This action is not serialized as part of the ATN, and is only required for\n  /// position-dependent lexer actions which appear at a location other than the\n  /// end of a rule. For more information about DFA optimizations employed for\n  /// lexer actions, see <seealso cref=\"LexerActionExecutor#append\"/> and\n  /// <seealso cref=\"LexerActionExecutor#fixOffsetBeforeMatch\"/>.</para>\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerIndexedCustomAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::INDEXED_CUSTOM; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Constructs a new indexed custom action by associating a character offset\n    /// with a <seealso cref=\"LexerAction\"/>.\n    ///\n    /// <para>Note: This class is only required for lexer actions for which\n    /// <seealso cref=\"LexerAction#isPositionDependent\"/> returns {@code true}.</para>\n    /// </summary>\n    /// <param name=\"offset\"> The offset into the input <seealso cref=\"CharStream\"/>, relative to\n    /// the token start index, at which the specified lexer action should be\n    /// executed. </param>\n    /// <param name=\"action\"> The lexer action to execute at a particular offset in the\n    /// input <seealso cref=\"CharStream\"/>. </param>\n    LexerIndexedCustomAction(int offset, Ref<const LexerAction> action);\n\n    /// <summary>\n    /// Gets the location in the input <seealso cref=\"CharStream\"/> at which the lexer\n    /// action should be executed. The value is interpreted as an offset relative\n    /// to the token start index.\n    /// </summary>\n    /// <returns> The location in the input <seealso cref=\"CharStream\"/> at which the lexer\n    /// action should be executed. </returns>\n    int getOffset() const { return _offset; }\n\n    /// <summary>\n    /// Gets the lexer action to execute.\n    /// </summary>\n    /// <returns> A <seealso cref=\"LexerAction\"/> object which executes the lexer action. </returns>\n    const Ref<const LexerAction>& getAction() const { return _action; }\n\n    void execute(Lexer *lexer) const override;\n    bool equals(const LexerAction &other) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    const Ref<const LexerAction> _action;\n    const int _offset;\n  };\n\n} // namespace atn\n} // namespace antlr4\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerModeAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"Lexer.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerModeAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nLexerModeAction::LexerModeAction(int mode) : LexerAction(LexerActionType::MODE, false), _mode(mode) {}\n\nvoid LexerModeAction::execute(Lexer *lexer) const {\n  lexer->setMode(getMode());\n}\n\nsize_t LexerModeAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  hash = MurmurHash::update(hash, getMode());\n  return MurmurHash::finish(hash, 2);\n}\n\nbool LexerModeAction::equals(const LexerAction &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getActionType() != other.getActionType()) {\n    return false;\n  }\n  const auto &lexerAction = downCast<const LexerModeAction&>(other);\n  return getMode() == lexerAction.getMode();\n}\n\nstd::string LexerModeAction::toString() const {\n  return \"mode(\" + std::to_string(getMode()) + \")\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerModeAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerAction.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerActionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Implements the {@code mode} lexer action by calling <seealso cref=\"Lexer#mode\"/> with\n  /// the assigned mode.\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerModeAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::MODE; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Constructs a new {@code mode} action with the specified mode value. </summary>\n    /// <param name=\"mode\"> The mode value to pass to <seealso cref=\"Lexer#mode\"/>. </param>\n    explicit LexerModeAction(int mode);\n\n    /// <summary>\n    /// Get the lexer mode this action should transition the lexer to.\n    /// </summary>\n    /// <returns> The lexer mode for this {@code mode} command. </returns>\n    int getMode() const { return _mode; }\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>This action is implemented by calling <seealso cref=\"Lexer#mode\"/> with the\n    /// value provided by <seealso cref=\"#getMode\"/>.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &obj) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    const int _mode;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerMoreAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"antlr4-common.h\"\n#include \"Lexer.h\"\n\n#include \"atn/LexerMoreAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\n\nconst Ref<const LexerMoreAction>& LexerMoreAction::getInstance() {\n  static const Ref<const LexerMoreAction> instance(new LexerMoreAction());\n  return instance;\n}\n\nvoid LexerMoreAction::execute(Lexer *lexer) const {\n  lexer->more();\n}\n\nsize_t LexerMoreAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  return MurmurHash::finish(hash, 1);\n}\n\nbool LexerMoreAction::equals(const LexerAction &other) const {\n  return this == std::addressof(other);\n}\n\nstd::string LexerMoreAction::toString() const {\n  return \"more\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerMoreAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerAction.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerActionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Implements the {@code more} lexer action by calling <seealso cref=\"Lexer#more\"/>.\n  ///\n  /// <para>The {@code more} command does not have any parameters, so this action is\n  /// implemented as a singleton instance exposed by <seealso cref=\"#INSTANCE\"/>.</para>\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerMoreAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::MORE; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Provides a singleton instance of this parameterless lexer action.\n    /// </summary>\n    static const Ref<const LexerMoreAction>& getInstance();\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>This action is implemented by calling <seealso cref=\"Lexer#more\"/>.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &obj) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    /// Constructs the singleton instance of the lexer {@code more} command.\n    LexerMoreAction() : LexerAction(LexerActionType::MORE, false) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerPopModeAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"antlr4-common.h\"\n#include \"Lexer.h\"\n\n#include \"atn/LexerPopModeAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\n\nconst Ref<const LexerPopModeAction>& LexerPopModeAction::getInstance() {\n  static const Ref<const LexerPopModeAction> instance(new LexerPopModeAction());\n  return instance;\n}\n\nvoid LexerPopModeAction::execute(Lexer *lexer) const {\n  lexer->popMode();\n}\n\nsize_t LexerPopModeAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  return MurmurHash::finish(hash, 1);\n}\n\nbool LexerPopModeAction::equals(const LexerAction &other) const {\n  return this == std::addressof(other);\n}\n\nstd::string LexerPopModeAction::toString() const {\n  return \"popMode\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerPopModeAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerAction.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerActionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Implements the {@code popMode} lexer action by calling <seealso cref=\"Lexer#popMode\"/>.\n  ///\n  /// <para>The {@code popMode} command does not have any parameters, so this action is\n  /// implemented as a singleton instance exposed by <seealso cref=\"#INSTANCE\"/>.</para>\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerPopModeAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::POP_MODE; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Provides a singleton instance of this parameterless lexer action.\n    /// </summary>\n    static const Ref<const LexerPopModeAction>& getInstance();\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>This action is implemented by calling <seealso cref=\"Lexer#popMode\"/>.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &other) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    /// Constructs the singleton instance of the lexer {@code popMode} command.\n    LexerPopModeAction() : LexerAction(LexerActionType::POP_MODE, false) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerPushModeAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"Lexer.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerPushModeAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nLexerPushModeAction::LexerPushModeAction(int mode) : LexerAction(LexerActionType::PUSH_MODE, false), _mode(mode) {}\n\nvoid LexerPushModeAction::execute(Lexer *lexer) const {\n  lexer->pushMode(getMode());\n}\n\nsize_t LexerPushModeAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  hash = MurmurHash::update(hash, getMode());\n  return MurmurHash::finish(hash, 2);\n}\n\nbool LexerPushModeAction::equals(const LexerAction &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getActionType() != other.getActionType()) {\n    return false;\n  }\n  const auto &lexerAction = downCast<const LexerPushModeAction&>(other);\n  return getMode() == lexerAction.getMode();\n}\n\nstd::string LexerPushModeAction::toString() const {\n  return \"pushMode(\" + std::to_string(getMode()) + \")\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerPushModeAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerAction.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerActionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Implements the {@code pushMode} lexer action by calling\n  /// <seealso cref=\"Lexer#pushMode\"/> with the assigned mode.\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerPushModeAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::PUSH_MODE; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Constructs a new {@code pushMode} action with the specified mode value. </summary>\n    /// <param name=\"mode\"> The mode value to pass to <seealso cref=\"Lexer#pushMode\"/>. </param>\n    explicit LexerPushModeAction(int mode);\n\n    /// <summary>\n    /// Get the lexer mode this action should transition the lexer to.\n    /// </summary>\n    /// <returns> The lexer mode for this {@code pushMode} command. </returns>\n    int getMode() const { return _mode; }\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>This action is implemented by calling <seealso cref=\"Lexer#pushMode\"/> with the\n    /// value provided by <seealso cref=\"#getMode\"/>.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &obj) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    const int _mode;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerSkipAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"antlr4-common.h\"\n#include \"Lexer.h\"\n\n#include \"atn/LexerSkipAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\n\nconst Ref<const LexerSkipAction>& LexerSkipAction::getInstance() {\n  static const Ref<const LexerSkipAction> instance(new LexerSkipAction());\n  return instance;\n}\n\nvoid LexerSkipAction::execute(Lexer *lexer) const {\n  lexer->skip();\n}\n\nsize_t LexerSkipAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  return MurmurHash::finish(hash, 1);\n}\n\nbool LexerSkipAction::equals(const LexerAction &other) const {\n  return this == std::addressof(other);\n}\n\nstd::string LexerSkipAction::toString() const {\n  return \"skip\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerSkipAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerAction.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerActionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// Implements the {@code skip} lexer action by calling <seealso cref=\"Lexer#skip\"/>.\n  ///\n  /// <para>The {@code skip} command does not have any parameters, so this action is\n  /// implemented as a singleton instance exposed by <seealso cref=\"#INSTANCE\"/>.</para>\n  ///\n  /// @author Sam Harwell\n  /// @since 4.2\n  /// </summary>\n  class ANTLR4CPP_PUBLIC LexerSkipAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::SKIP; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// Provides a singleton instance of this parameterless lexer action.\n    static const Ref<const LexerSkipAction>& getInstance();\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>This action is implemented by calling <seealso cref=\"Lexer#skip\"/>.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &obj) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    /// Constructs the singleton instance of the lexer {@code skip} command.\n    LexerSkipAction() : LexerAction(LexerActionType::SKIP, false) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerTypeAction.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"Lexer.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/LexerTypeAction.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\nusing namespace antlrcpp;\n\nLexerTypeAction::LexerTypeAction(int type) : LexerAction(LexerActionType::TYPE, false), _type(type) {}\n\nvoid LexerTypeAction::execute(Lexer *lexer) const {\n  lexer->setType(getType());\n}\n\nsize_t LexerTypeAction::hashCodeImpl() const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, static_cast<size_t>(getActionType()));\n  hash = MurmurHash::update(hash, getType());\n  return MurmurHash::finish(hash, 2);\n}\n\nbool LexerTypeAction::equals(const LexerAction &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getActionType() != other.getActionType()) {\n    return false;\n  }\n  const auto &lexerAction = downCast<const LexerTypeAction&>(other);\n  return getType() == lexerAction.getType();\n}\n\nstd::string LexerTypeAction::toString() const {\n  return \"type(\" + std::to_string(getType()) + \")\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LexerTypeAction.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"atn/LexerActionType.h\"\n#include \"antlr4-common.h\"\n#include \"atn/LexerAction.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Implements the {@code type} lexer action by calling <seealso cref=\"Lexer#setType\"/>\n  /// with the assigned type.\n  class ANTLR4CPP_PUBLIC LexerTypeAction final : public LexerAction {\n  public:\n    static bool is(const LexerAction &lexerAction) { return lexerAction.getActionType() == LexerActionType::TYPE; }\n\n    static bool is(const LexerAction *lexerAction) { return lexerAction != nullptr && is(*lexerAction); }\n\n    /// <summary>\n    /// Constructs a new {@code type} action with the specified token type value. </summary>\n    /// <param name=\"type\"> The type to assign to the token using <seealso cref=\"Lexer#setType\"/>. </param>\n    explicit LexerTypeAction(int type);\n\n    /// <summary>\n    /// Gets the type to assign to a token created by the lexer. </summary>\n    /// <returns> The type to assign to a token created by the lexer. </returns>\n    int getType() const { return _type; }\n\n    /// <summary>\n    /// {@inheritDoc}\n    ///\n    /// <para>This action is implemented by calling <seealso cref=\"Lexer#setType\"/> with the\n    /// value provided by <seealso cref=\"#getType\"/>.</para>\n    /// </summary>\n    void execute(Lexer *lexer) const override;\n\n    bool equals(const LexerAction &obj) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n\n  private:\n    const int _type;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LookaheadEventInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/LookaheadEventInfo.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nLookaheadEventInfo::LookaheadEventInfo(size_t decision, ATNConfigSet *configs, size_t predictedAlt,\n  TokenStream *input, size_t startIndex, size_t stopIndex, bool fullCtx)\n  : DecisionEventInfo(decision, configs, input, startIndex, stopIndex, fullCtx) {\n\n  this->predictedAlt = predictedAlt;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LookaheadEventInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/DecisionEventInfo.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// This class represents profiling event information for tracking the lookahead\n  /// depth required in order to make a prediction.\n  class ANTLR4CPP_PUBLIC LookaheadEventInfo : public DecisionEventInfo {\n  public:\n    /// The alternative chosen by adaptivePredict(), not necessarily\n    ///  the outermost alt shown for a rule; left-recursive rules have\n    ///  user-level alts that differ from the rewritten rule with a (...) block\n    ///  and a (..)* loop.\n    size_t predictedAlt = 0;\n\n    /// <summary>\n    /// Constructs a new instance of the <seealso cref=\"LookaheadEventInfo\"/> class with\n    /// the specified detailed lookahead information.\n    /// </summary>\n    /// <param name=\"decision\"> The decision number </param>\n    /// <param name=\"configs\"> The final configuration set containing the necessary\n    /// information to determine the result of a prediction, or {@code null} if\n    /// the final configuration set is not available </param>\n    /// <param name=\"input\"> The input token stream </param>\n    /// <param name=\"startIndex\"> The start index for the current prediction </param>\n    /// <param name=\"stopIndex\"> The index at which the prediction was finally made </param>\n    /// <param name=\"fullCtx\"> {@code true} if the current lookahead is part of an LL\n    /// prediction; otherwise, {@code false} if the current lookahead is part of\n    /// an SLL prediction </param>\n    LookaheadEventInfo(size_t decision, ATNConfigSet *configs, size_t predictedAlt, TokenStream *input, size_t startIndex,\n                       size_t stopIndex, bool fullCtx);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/LoopEndState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Mark the end of a * or + loop.\n  class ANTLR4CPP_PUBLIC LoopEndState final : public ATNState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::LOOP_END; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    ATNState *loopBackState = nullptr;\n\n    LoopEndState() : ATNState(ATNStateType::LOOP_END) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/NotSetTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"atn/NotSetTransition.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"misc/IntervalSet.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nNotSetTransition::NotSetTransition(ATNState *target, misc::IntervalSet set) : SetTransition(TransitionType::NOT_SET, target, std::move(set)) {}\n\nbool NotSetTransition::matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const {\n  return symbol >= minVocabSymbol && symbol <= maxVocabSymbol\n    && !SetTransition::matches(symbol, minVocabSymbol, maxVocabSymbol);\n}\n\nstd::string NotSetTransition::toString() const {\n  return \"NOT_SET \" + Transition::toString() + \" { \" + SetTransition::toString() + \" }\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/NotSetTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/SetTransition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC NotSetTransition final : public SetTransition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::NOT_SET; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    NotSetTransition(ATNState *target, misc::IntervalSet set);\n\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/OrderedATNConfigSet.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include \"atn/OrderedATNConfigSet.h\"\n\nusing namespace antlr4::atn;\n\nsize_t OrderedATNConfigSet::hashCode(const ATNConfig &atnConfig) const {\n  return atnConfig.hashCode();\n}\n\nbool OrderedATNConfigSet::equals(const ATNConfig &lhs, const ATNConfig &rhs) const {\n  return lhs == rhs;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/OrderedATNConfigSet.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"atn/ATNConfigSet.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATNConfig.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC OrderedATNConfigSet final : public ATNConfigSet {\n  public:\n    OrderedATNConfigSet() = default;\n\n  private:\n    size_t hashCode(const ATNConfig &atnConfig) const override;\n\n    bool equals(const ATNConfig &lhs, const ATNConfig &rhs) const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ParseInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <cstddef>\n#include \"atn/ProfilingATNSimulator.h\"\n#include \"dfa/DFA.h\"\n\n#include \"atn/ParseInfo.h\"\n\nusing namespace antlr4::atn;\n\nParseInfo::ParseInfo(ProfilingATNSimulator *atnSimulator) : _atnSimulator(atnSimulator) {\n}\n\nParseInfo::~ParseInfo() {\n}\n\nstd::vector<DecisionInfo> ParseInfo::getDecisionInfo() {\n  return _atnSimulator->getDecisionInfo();\n}\n\nstd::vector<size_t> ParseInfo::getLLDecisions() {\n  std::vector<DecisionInfo> decisions = _atnSimulator->getDecisionInfo();\n  std::vector<size_t> LL;\n  for (size_t i = 0; i < decisions.size(); ++i) {\n    long long fallBack = decisions[i].LL_Fallback;\n    if (fallBack > 0) {\n      LL.push_back(i);\n    }\n  }\n  return LL;\n}\n\nlong long ParseInfo::getTotalTimeInPrediction() {\n  std::vector<DecisionInfo> decisions = _atnSimulator->getDecisionInfo();\n  long long t = 0;\n  for (size_t i = 0; i < decisions.size(); ++i) {\n    t += decisions[i].timeInPrediction;\n  }\n  return t;\n}\n\nlong long ParseInfo::getTotalSLLLookaheadOps() {\n  std::vector<DecisionInfo> decisions = _atnSimulator->getDecisionInfo();\n  long long k = 0;\n  for (size_t i = 0; i < decisions.size(); ++i) {\n    k += decisions[i].SLL_TotalLook;\n  }\n  return k;\n}\n\nlong long ParseInfo::getTotalLLLookaheadOps() {\n  std::vector<DecisionInfo> decisions = _atnSimulator->getDecisionInfo();\n  long long k = 0;\n  for (size_t i = 0; i < decisions.size(); i++) {\n    k += decisions[i].LL_TotalLook;\n  }\n  return k;\n}\n\nlong long ParseInfo::getTotalSLLATNLookaheadOps() {\n  std::vector<DecisionInfo> decisions = _atnSimulator->getDecisionInfo();\n  long long k = 0;\n  for (size_t i = 0; i < decisions.size(); ++i) {\n    k += decisions[i].SLL_ATNTransitions;\n  }\n  return k;\n}\n\nlong long ParseInfo::getTotalLLATNLookaheadOps() {\n  std::vector<DecisionInfo> decisions = _atnSimulator->getDecisionInfo();\n  long long k = 0;\n  for (size_t i = 0; i < decisions.size(); ++i) {\n    k += decisions[i].LL_ATNTransitions;\n  }\n  return k;\n}\n\nlong long ParseInfo::getTotalATNLookaheadOps() {\n  std::vector<DecisionInfo> decisions = _atnSimulator->getDecisionInfo();\n  long long k = 0;\n  for (size_t i = 0; i < decisions.size(); ++i) {\n    k += decisions[i].SLL_ATNTransitions;\n    k += decisions[i].LL_ATNTransitions;\n  }\n  return k;\n}\n\nsize_t ParseInfo::getDFASize() {\n  size_t n = 0;\n  std::vector<dfa::DFA> &decisionToDFA = _atnSimulator->decisionToDFA;\n  for (size_t i = 0; i < decisionToDFA.size(); ++i) {\n    n += getDFASize(i);\n  }\n  return n;\n}\n\nsize_t ParseInfo::getDFASize(size_t decision) {\n  dfa::DFA &decisionToDFA = _atnSimulator->decisionToDFA[decision];\n  return decisionToDFA.states.size();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ParseInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/DecisionInfo.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ProfilingATNSimulator;\n\n  /// This class provides access to specific and aggregate statistics gathered\n  /// during profiling of a parser.\n  class ANTLR4CPP_PUBLIC ParseInfo {\n  public:\n    ParseInfo(ProfilingATNSimulator *atnSimulator);\n    ParseInfo(ParseInfo const&) = default;\n    virtual ~ParseInfo();\n\n    ParseInfo& operator=(ParseInfo const&) = default;\n\n    /// <summary>\n    /// Gets an array of <seealso cref=\"DecisionInfo\"/> instances containing the profiling\n    /// information gathered for each decision in the ATN.\n    /// </summary>\n    /// <returns> An array of <seealso cref=\"DecisionInfo\"/> instances, indexed by decision\n    /// number. </returns>\n    virtual std::vector<DecisionInfo> getDecisionInfo();\n\n    /// <summary>\n    /// Gets the decision numbers for decisions that required one or more\n    /// full-context predictions during parsing. These are decisions for which\n    /// <seealso cref=\"DecisionInfo#LL_Fallback\"/> is non-zero.\n    /// </summary>\n    /// <returns> A list of decision numbers which required one or more\n    /// full-context predictions during parsing. </returns>\n    virtual std::vector<size_t> getLLDecisions();\n\n    /// <summary>\n    /// Gets the total time spent during prediction across all decisions made\n    /// during parsing. This value is the sum of\n    /// <seealso cref=\"DecisionInfo#timeInPrediction\"/> for all decisions.\n    /// </summary>\n    virtual long long getTotalTimeInPrediction();\n\n    /// <summary>\n    /// Gets the total number of SLL lookahead operations across all decisions\n    /// made during parsing. This value is the sum of\n    /// <seealso cref=\"DecisionInfo#SLL_TotalLook\"/> for all decisions.\n    /// </summary>\n    virtual long long getTotalSLLLookaheadOps();\n\n    /// <summary>\n    /// Gets the total number of LL lookahead operations across all decisions\n    /// made during parsing. This value is the sum of\n    /// <seealso cref=\"DecisionInfo#LL_TotalLook\"/> for all decisions.\n    /// </summary>\n    virtual long long getTotalLLLookaheadOps();\n\n    /// <summary>\n    /// Gets the total number of ATN lookahead operations for SLL prediction\n    /// across all decisions made during parsing.\n    /// </summary>\n    virtual long long getTotalSLLATNLookaheadOps();\n\n    /// <summary>\n    /// Gets the total number of ATN lookahead operations for LL prediction\n    /// across all decisions made during parsing.\n    /// </summary>\n    virtual long long getTotalLLATNLookaheadOps();\n\n    /// <summary>\n    /// Gets the total number of ATN lookahead operations for SLL and LL\n    /// prediction across all decisions made during parsing.\n    ///\n    /// <para>\n    /// This value is the sum of <seealso cref=\"#getTotalSLLATNLookaheadOps\"/> and\n    /// <seealso cref=\"#getTotalLLATNLookaheadOps\"/>.</para>\n    /// </summary>\n    virtual long long getTotalATNLookaheadOps();\n\n    /// <summary>\n    /// Gets the total number of DFA states stored in the DFA cache for all\n    /// decisions in the ATN.\n    /// </summary>\n    virtual size_t getDFASize();\n\n    /// <summary>\n    /// Gets the total number of DFA states stored in the DFA cache for a\n    /// particular decision.\n    /// </summary>\n    virtual size_t getDFASize(size_t decision);\n\n  protected:\n    const ProfilingATNSimulator *_atnSimulator; // non-owning, we are created by this simulator.\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ParserATNSimulator.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cassert>\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"dfa/DFA.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/TransitionType.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"NoViableAltException.h\"\n#include \"atn/DecisionState.h\"\n#include \"ParserRuleContext.h\"\n#include \"misc/IntervalSet.h\"\n#include \"Parser.h\"\n#include \"CommonTokenStream.h\"\n#include \"atn/NotSetTransition.h\"\n#include \"atn/AtomTransition.h\"\n#include \"atn/RuleTransition.h\"\n#include \"atn/PredicateTransition.h\"\n#include \"atn/PrecedencePredicateTransition.h\"\n#include \"atn/SingletonPredictionContext.h\"\n#include \"atn/ActionTransition.h\"\n#include \"atn/EpsilonTransition.h\"\n#include \"atn/RuleStopState.h\"\n#include \"atn/ATNConfigSet.h\"\n#include \"atn/ATNConfig.h\"\n#include \"internal/Synchronization.h\"\n\n#include \"atn/StarLoopEntryState.h\"\n#include \"atn/BlockStartState.h\"\n#include \"atn/BlockEndState.h\"\n\n#include \"misc/Interval.h\"\n#include \"ANTLRErrorListener.h\"\n\n#include \"Vocabulary.h\"\n#include \"support/Arrays.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/ParserATNSimulator.h\"\n\n#ifndef DEBUG_ATN\n#define DEBUG_ATN 0\n#endif\n#ifndef TRACE_ATN_SIM\n#define TRACE_ATN_SIM 0\n#endif\n#ifndef DFA_DEBUG\n#define DFA_DEBUG 0\n#endif\n#ifndef RETRY_DEBUG\n#define RETRY_DEBUG 0\n#endif\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::internal;\nusing namespace antlrcpp;\n\nconst bool ParserATNSimulator::TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT = ParserATNSimulator::getLrLoopSetting();\n\nParserATNSimulator::ParserATNSimulator(const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                                       PredictionContextCache &sharedContextCache)\n: ParserATNSimulator(nullptr, atn, decisionToDFA, sharedContextCache) {\n}\n\nParserATNSimulator::ParserATNSimulator(Parser *parser, const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                                       PredictionContextCache &sharedContextCache)\n: ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache, ParserATNSimulatorOptions()) {}\n\nParserATNSimulator::ParserATNSimulator(Parser *parser, const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                                       PredictionContextCache &sharedContextCache,\n                                       const ParserATNSimulatorOptions &options)\n: ATNSimulator(atn, sharedContextCache), decisionToDFA(decisionToDFA), parser(parser),\n  mergeCache(options.getPredictionContextMergeCacheOptions()) {\n  InitializeInstanceFields();\n}\n\nvoid ParserATNSimulator::reset() {\n}\n\nvoid ParserATNSimulator::clearDFA() {\n  int size = (int)decisionToDFA.size();\n  decisionToDFA.clear();\n  for (int d = 0; d < size; ++d) {\n    decisionToDFA.push_back(dfa::DFA(atn.getDecisionState(d), d));\n  }\n}\n\nsize_t ParserATNSimulator::adaptivePredict(TokenStream *input, size_t decision, ParserRuleContext *outerContext) {\n\n#if DEBUG_ATN == 1 || TRACE_ATN_SIM == 1\n    std::cout << \"adaptivePredict decision \" << decision << \" exec LA(1)==\" << getLookaheadName(input) << \" line \"\n      << input->LT(1)->getLine() << \":\" << input->LT(1)->getCharPositionInLine() << std::endl;\n#endif\n\n  _input = input;\n  _startIndex = input->index();\n  _outerContext = outerContext;\n  dfa::DFA &dfa = decisionToDFA[decision];\n  _dfa = &dfa;\n\n  ssize_t m = input->mark();\n  size_t index = _startIndex;\n\n  // Now we are certain to have a specific decision's DFA\n  // But, do we still need an initial state?\n  auto onExit = finally([this, input, index, m] {\n    if (mergeCache.getOptions().getClearEveryN() != 0) {\n      if (++_mergeCacheCounter == mergeCache.getOptions().getClearEveryN()) {\n        mergeCache.clear();\n        _mergeCacheCounter = 0;\n      }\n    }\n    _dfa = nullptr;\n    input->seek(index);\n    input->release(m);\n  });\n\n  dfa::DFAState *s0;\n  {\n    SharedLock<SharedMutex> stateLock(atn._stateMutex);\n    if (dfa.isPrecedenceDfa()) {\n      // the start state for a precedence DFA depends on the current\n      // parser precedence, and is provided by a DFA method.\n      SharedLock<SharedMutex> edgeLock(atn._edgeMutex);\n      s0 = dfa.getPrecedenceStartState(parser->getPrecedence());\n    } else {\n      // the start state for a \"regular\" DFA is just s0\n      s0 = dfa.s0;\n    }\n  }\n\n  if (s0 == nullptr) {\n    auto s0_closure = computeStartState(dfa.atnStartState, &ParserRuleContext::EMPTY, false);\n    std::unique_ptr<dfa::DFAState> newState;\n    std::unique_ptr<dfa::DFAState> oldState;\n    UniqueLock<SharedMutex> stateLock(atn._stateMutex);\n    dfa::DFAState* ds0 = dfa.s0;\n    if (dfa.isPrecedenceDfa()) {\n      /* If this is a precedence DFA, we use applyPrecedenceFilter\n       * to convert the computed start state to a precedence start\n       * state. We then use DFA.setPrecedenceStartState to set the\n       * appropriate start state for the precedence level rather\n       * than simply setting DFA.s0.\n       */\n      ds0->configs = std::move(s0_closure); // not used for prediction but useful to know start configs anyway\n      newState = std::make_unique<dfa::DFAState>(applyPrecedenceFilter(ds0->configs.get()));\n      s0 = addDFAState(dfa, newState.get());\n      UniqueLock<SharedMutex> edgeLock(atn._edgeMutex);\n      dfa.setPrecedenceStartState(parser->getPrecedence(), s0);\n    } else {\n      newState = std::make_unique<dfa::DFAState>(std::move(s0_closure));\n      s0 = addDFAState(dfa, newState.get());\n      if (ds0 != s0) {\n        oldState.reset(ds0);\n        dfa.s0 = s0;\n      }\n    }\n    if (s0 == newState.get()) {\n      newState.release();\n    }\n  }\n\n  // We can start with an existing DFA.\n  size_t alt = execATN(dfa, s0, input, index, outerContext != nullptr ? outerContext : &ParserRuleContext::EMPTY);\n\n  return alt;\n}\n\nsize_t ParserATNSimulator::execATN(dfa::DFA &dfa, dfa::DFAState *s0, TokenStream *input, size_t startIndex,\n                                   ParserRuleContext *outerContext) {\n\n#if DEBUG_ATN == 1 || TRACE_ATN_SIM == 1\n    std::cout << \"execATN decision \" << dfa.decision << \", DFA state \" << s0->toString() <<\n      \", LA(1)==\" << getLookaheadName(input) <<\n      \" line \" << input->LT(1)->getLine() << \":\" << input->LT(1)->getCharPositionInLine() << std::endl;\n#endif\n\n  dfa::DFAState *previousD = s0;\n\n#if DEBUG_ATN == 1\n    std::cout << \"s0 = \" << s0->toString() << std::endl;\n#endif\n\n  size_t t = input->LA(1);\n\n  while (true) { // while more work\n    dfa::DFAState *D = getExistingTargetState(previousD, t);\n    if (D == nullptr) {\n      D = computeTargetState(dfa, previousD, t);\n    }\n\n    if (D == ERROR.get()) {\n      // if any configs in previous dipped into outer context, that\n      // means that input up to t actually finished entry rule\n      // at least for SLL decision. Full LL doesn't dip into outer\n      // so don't need special case.\n      // We will get an error no matter what so delay until after\n      // decision; better error message. Also, no reachable target\n      // ATN states in SLL implies LL will also get nowhere.\n      // If conflict in states that dip out, choose min since we\n      // will get error no matter what.\n      NoViableAltException e = noViableAlt(input, outerContext, previousD->configs.get(), startIndex, false);\n      input->seek(startIndex);\n      size_t alt = getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD->configs.get(), outerContext);\n      if (alt != ATN::INVALID_ALT_NUMBER) {\n        return alt;\n      }\n\n      throw e;\n    }\n\n    if (D->requiresFullContext && _mode != PredictionMode::SLL) {\n      // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n      BitSet conflictingAlts;\n      if (D->predicates.size() != 0) {\n#if DEBUG_ATN == 1\n          std::cout << \"DFA state has preds in DFA sim LL failover\" << std::endl;\n#endif\n\n        size_t conflictIndex = input->index();\n        if (conflictIndex != startIndex) {\n          input->seek(startIndex);\n        }\n\n        conflictingAlts = evalSemanticContext(D->predicates, outerContext, true);\n        if (conflictingAlts.count() == 1) {\n#if DEBUG_ATN == 1\n            std::cout << \"Full LL avoided\" << std::endl;\n#endif\n\n          return conflictingAlts.nextSetBit(0);\n        }\n\n        if (conflictIndex != startIndex) {\n          // restore the index so reporting the fallback to full\n          // context occurs with the index at the correct spot\n          input->seek(conflictIndex);\n        }\n      }\n\n#if DFA_DEBUG == 1\n        std::cout << \"ctx sensitive state \" << outerContext << \" in \" << D << std::endl;\n#endif\n\n      bool fullCtx = true;\n      std::unique_ptr<ATNConfigSet> s0_closure = computeStartState(dfa.atnStartState, outerContext, fullCtx);\n      reportAttemptingFullContext(dfa, conflictingAlts, D->configs.get(), startIndex, input->index());\n      size_t alt = execATNWithFullContext(dfa, D, s0_closure.get(), input, startIndex, outerContext);\n      return alt;\n    }\n\n    if (D->isAcceptState) {\n      if (D->predicates.empty()) {\n        return D->prediction;\n      }\n\n      size_t stopIndex = input->index();\n      input->seek(startIndex);\n      BitSet alts = evalSemanticContext(D->predicates, outerContext, true);\n      switch (alts.count()) {\n        case 0:\n          throw noViableAlt(input, outerContext, D->configs.get(), startIndex, false);\n\n        case 1:\n          return alts.nextSetBit(0);\n\n        default:\n          // report ambiguity after predicate evaluation to make sure the correct\n          // set of ambig alts is reported.\n          reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D->configs.get());\n          return alts.nextSetBit(0);\n      }\n    }\n\n    previousD = D;\n\n    if (t != Token::EOF) {\n      input->consume();\n      t = input->LA(1);\n    }\n  }\n}\n\ndfa::DFAState *ParserATNSimulator::getExistingTargetState(dfa::DFAState *previousD, size_t t) {\n  dfa::DFAState* retval;\n  SharedLock<SharedMutex> edgeLock(atn._edgeMutex);\n  auto iterator = previousD->edges.find(t);\n  retval = (iterator == previousD->edges.end()) ? nullptr : iterator->second;\n  return retval;\n}\n\ndfa::DFAState *ParserATNSimulator::computeTargetState(dfa::DFA &dfa, dfa::DFAState *previousD, size_t t) {\n  std::unique_ptr<ATNConfigSet> reach = computeReachSet(previousD->configs.get(), t, false);\n  if (reach == nullptr) {\n    addDFAEdge(dfa, previousD, t, ERROR.get());\n    return ERROR.get();\n  }\n\n  // create new target state; we'll add to DFA after it's complete\n  dfa::DFAState *D = new dfa::DFAState(std::move(reach)); /* mem-check: managed by the DFA or deleted below, \"reach\" is no longer valid now. */\n  size_t predictedAlt = getUniqueAlt(D->configs.get());\n\n  if (predictedAlt != ATN::INVALID_ALT_NUMBER) {\n    // NO CONFLICT, UNIQUELY PREDICTED ALT\n    D->isAcceptState = true;\n    D->configs->uniqueAlt = predictedAlt;\n    D->prediction = predictedAlt;\n  } else if (PredictionModeClass::hasSLLConflictTerminatingPrediction(_mode, D->configs.get())) {\n    // MORE THAN ONE VIABLE ALTERNATIVE\n    D->configs->conflictingAlts = getConflictingAlts(D->configs.get());\n    D->requiresFullContext = true;\n    // in SLL-only mode, we will stop at this state and return the minimum alt\n    D->isAcceptState = true;\n    D->prediction = D->configs->conflictingAlts.nextSetBit(0);\n  }\n\n  if (D->isAcceptState && D->configs->hasSemanticContext) {\n    predicateDFAState(D, atn.getDecisionState(dfa.decision));\n    if (D->predicates.size() != 0) {\n      D->prediction = ATN::INVALID_ALT_NUMBER;\n    }\n  }\n\n  // all adds to dfa are done after we've created full D state\n  dfa::DFAState *state = addDFAEdge(dfa, previousD, t, D);\n  if (state != D) {\n    delete D; // If the new state exists already we don't need it and use the existing one instead.\n  }\n  return state;\n}\n\nvoid ParserATNSimulator::predicateDFAState(dfa::DFAState *dfaState, DecisionState *decisionState) {\n  // We need to test all predicates, even in DFA states that\n  // uniquely predict alternative.\n  size_t nalts = decisionState->transitions.size();\n\n  // Update DFA so reach becomes accept state with (predicate,alt)\n  // pairs if preds found for conflicting alts\n  BitSet altsToCollectPredsFrom = getConflictingAltsOrUniqueAlt(dfaState->configs.get());\n  std::vector<Ref<const SemanticContext>> altToPred = getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState->configs.get(), nalts);\n  if (!altToPred.empty()) {\n    dfaState->predicates = getPredicatePredictions(altsToCollectPredsFrom, altToPred);\n    dfaState->prediction = ATN::INVALID_ALT_NUMBER; // make sure we use preds\n  } else {\n    // There are preds in configs but they might go away\n    // when OR'd together like {p}? || NONE == NONE. If neither\n    // alt has preds, resolve to min alt\n    dfaState->prediction = altsToCollectPredsFrom.nextSetBit(0);\n  }\n}\n\nsize_t ParserATNSimulator::execATNWithFullContext(dfa::DFA &dfa, dfa::DFAState *D, ATNConfigSet *s0,\n  TokenStream *input, size_t startIndex, ParserRuleContext *outerContext) {\n\n#if TRACE_ATN_SIM == 1\n    std::cout << \"execATNWithFullContext \" << s0->toString() << std::endl;\n#endif\n\n  bool fullCtx = true;\n  bool foundExactAmbig = false;\n\n  std::unique_ptr<ATNConfigSet> reach;\n  ATNConfigSet *previous = s0;\n  input->seek(startIndex);\n  size_t t = input->LA(1);\n  size_t predictedAlt;\n\n  while (true) {\n    reach = computeReachSet(previous, t, fullCtx);\n    if (reach == nullptr) {\n      // if any configs in previous dipped into outer context, that\n      // means that input up to t actually finished entry rule\n      // at least for LL decision. Full LL doesn't dip into outer\n      // so don't need special case.\n      // We will get an error no matter what so delay until after\n      // decision; better error message. Also, no reachable target\n      // ATN states in SLL implies LL will also get nowhere.\n      // If conflict in states that dip out, choose min since we\n      // will get error no matter what.\n      NoViableAltException e = noViableAlt(input, outerContext, previous, startIndex, previous != s0);\n      input->seek(startIndex);\n      size_t alt = getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);\n      if (alt != ATN::INVALID_ALT_NUMBER) {\n        return alt;\n      }\n      throw e;\n    }\n    if (previous != s0) // Don't delete the start set.\n        delete previous;\n    previous = nullptr;\n\n    std::vector<BitSet> altSubSets = PredictionModeClass::getConflictingAltSubsets(reach.get());\n    reach->uniqueAlt = getUniqueAlt(reach.get());\n    // unique prediction?\n    if (reach->uniqueAlt != ATN::INVALID_ALT_NUMBER) {\n      predictedAlt = reach->uniqueAlt;\n      break;\n    }\n    if (_mode != PredictionMode::LL_EXACT_AMBIG_DETECTION) {\n      predictedAlt = PredictionModeClass::resolvesToJustOneViableAlt(altSubSets);\n      if (predictedAlt != ATN::INVALID_ALT_NUMBER) {\n        break;\n      }\n    } else {\n      // In exact ambiguity mode, we never try to terminate early.\n      // Just keeps scarfing until we know what the conflict is\n      if (PredictionModeClass::allSubsetsConflict(altSubSets) && PredictionModeClass::allSubsetsEqual(altSubSets)) {\n        foundExactAmbig = true;\n        predictedAlt = PredictionModeClass::getSingleViableAlt(altSubSets);\n        break;\n      }\n      // else there are multiple non-conflicting subsets or\n      // we're not sure what the ambiguity is yet.\n      // So, keep going.\n    }\n    previous = reach.release();\n\n    if (t != Token::EOF) {\n      input->consume();\n      t = input->LA(1);\n    }\n  }\n\n  // If the configuration set uniquely predicts an alternative,\n  // without conflict, then we know that it's a full LL decision\n  // not SLL.\n  if (reach->uniqueAlt != ATN::INVALID_ALT_NUMBER) {\n    reportContextSensitivity(dfa, predictedAlt, reach.get(), startIndex, input->index());\n    return predictedAlt;\n  }\n\n  // We do not check predicates here because we have checked them\n  // on-the-fly when doing full context prediction.\n\n  /*\n   In non-exact ambiguity detection mode, we might\tactually be able to\n   detect an exact ambiguity, but I'm not going to spend the cycles\n   needed to check. We only emit ambiguity warnings in exact ambiguity\n   mode.\n\n   For example, we might know that we have conflicting configurations.\n   But, that does not mean that there is no way forward without a\n   conflict. It's possible to have nonconflicting alt subsets as in:\n\n   LL altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n\n   from\n\n   [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n   (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n\n   In this case, (17,1,[5 $]) indicates there is some next sequence that\n   would resolve this without conflict to alternative 1. Any other viable\n   next sequence, however, is associated with a conflict.  We stop\n   looking for input because no amount of further lookahead will alter\n   the fact that we should predict alternative 1.  We just can't say for\n   sure that there is an ambiguity without looking further.\n   */\n  reportAmbiguity(dfa, D, startIndex, input->index(), foundExactAmbig, reach->getAlts(), reach.get());\n\n  return predictedAlt;\n}\n\nstd::unique_ptr<ATNConfigSet> ParserATNSimulator::computeReachSet(ATNConfigSet *closure_, size_t t, bool fullCtx) {\n\n  std::unique_ptr<ATNConfigSet> intermediate(new ATNConfigSet(fullCtx));\n\n  /* Configurations already in a rule stop state indicate reaching the end\n   * of the decision rule (local context) or end of the start rule (full\n   * context). Once reached, these configurations are never updated by a\n   * closure operation, so they are handled separately for the performance\n   * advantage of having a smaller intermediate set when calling closure.\n   *\n   * For full-context reach operations, separate handling is required to\n   * ensure that the alternative matching the longest overall sequence is\n   * chosen when multiple such configurations can match the input.\n   */\n  std::vector<Ref<ATNConfig>> skippedStopStates;\n\n  // First figure out where we can reach on input t\n  for (const auto &c : closure_->configs) {\n    if (RuleStopState::is(c->state)) {\n      assert(c->context->isEmpty());\n\n      if (fullCtx || t == Token::EOF) {\n        skippedStopStates.push_back(c);\n      }\n\n      continue;\n    }\n\n    size_t n = c->state->transitions.size();\n    for (size_t ti = 0; ti < n; ti++) { // for each transition\n      const Transition *trans = c->state->transitions[ti].get();\n      ATNState *target = getReachableTarget(trans, (int)t);\n      if (target != nullptr) {\n        intermediate->add(std::make_shared<ATNConfig>(*c, target), &mergeCache);\n      }\n    }\n  }\n\n  // Now figure out where the reach operation can take us...\n  std::unique_ptr<ATNConfigSet> reach;\n\n  /* This block optimizes the reach operation for intermediate sets which\n   * trivially indicate a termination state for the overall\n   * adaptivePredict operation.\n   *\n   * The conditions assume that intermediate\n   * contains all configurations relevant to the reach set, but this\n   * condition is not true when one or more configurations have been\n   * withheld in skippedStopStates, or when the current symbol is EOF.\n   */\n  if (skippedStopStates.empty() && t != Token::EOF) {\n    if (intermediate->size() == 1) {\n      // Don't pursue the closure if there is just one state.\n      // It can only have one alternative; just add to result\n      // Also don't pursue the closure if there is unique alternative\n      // among the configurations.\n      reach = std::move(intermediate);\n    } else if (getUniqueAlt(intermediate.get()) != ATN::INVALID_ALT_NUMBER) {\n      // Also don't pursue the closure if there is unique alternative\n      // among the configurations.\n      reach = std::move(intermediate);\n    }\n  }\n\n  /* If the reach set could not be trivially determined, perform a closure\n   * operation on the intermediate set to compute its initial value.\n   */\n  if (reach == nullptr) {\n    reach.reset(new ATNConfigSet(fullCtx));\n    ATNConfig::Set closureBusy;\n\n    bool treatEofAsEpsilon = t == Token::EOF;\n    for (const auto &c : intermediate->configs) {\n      closure(c, reach.get(), closureBusy, false, fullCtx, treatEofAsEpsilon);\n    }\n  }\n\n  if (t == IntStream::EOF) {\n    /* After consuming EOF no additional input is possible, so we are\n     * only interested in configurations which reached the end of the\n     * decision rule (local context) or end of the start rule (full\n     * context). Update reach to contain only these configurations. This\n     * handles both explicit EOF transitions in the grammar and implicit\n     * EOF transitions following the end of the decision or start rule.\n     *\n     * When reach==intermediate, no closure operation was performed. In\n     * this case, removeAllConfigsNotInRuleStopState needs to check for\n     * reachable rule stop states as well as configurations already in\n     * a rule stop state.\n     *\n     * This is handled before the configurations in skippedStopStates,\n     * because any configurations potentially added from that list are\n     * already guaranteed to meet this condition whether or not it's\n     * required.\n     */\n    ATNConfigSet *temp = removeAllConfigsNotInRuleStopState(reach.get(), *reach == *intermediate);\n    if (temp != reach.get())\n      reach.reset(temp); // We got a new set, so use that.\n  }\n\n  /* If skippedStopStates is not null, then it contains at least one\n   * configuration. For full-context reach operations, these\n   * configurations reached the end of the start rule, in which case we\n   * only add them back to reach if no configuration during the current\n   * closure operation reached such a state. This ensures adaptivePredict\n   * chooses an alternative matching the longest overall sequence when\n   * multiple alternatives are viable.\n   */\n  if (skippedStopStates.size() > 0 && (!fullCtx || !PredictionModeClass::hasConfigInRuleStopState(reach.get()))) {\n    assert(!skippedStopStates.empty());\n\n    for (const auto &c : skippedStopStates) {\n      reach->add(c, &mergeCache);\n    }\n  }\n\n#if DEBUG_ATN == 1 || TRACE_ATN_SIM == 1\n    std::cout << \"computeReachSet \" << closure_->toString() << \" -> \" << reach->toString() << std::endl;\n#endif\n\n    if (reach->isEmpty()) {\n    return nullptr;\n  }\n  return reach;\n}\n\nATNConfigSet* ParserATNSimulator::removeAllConfigsNotInRuleStopState(ATNConfigSet *configs,\n  bool lookToEndOfRule) {\n  if (PredictionModeClass::allConfigsInRuleStopStates(configs)) {\n    return configs;\n  }\n\n  ATNConfigSet *result = new ATNConfigSet(configs->fullCtx); /* mem-check: released by caller */\n\n  for (const auto &config : configs->configs) {\n    if (config->state != nullptr && config->state->getStateType() == ATNStateType::RULE_STOP) {\n      result->add(config, &mergeCache);\n      continue;\n    }\n\n    if (lookToEndOfRule && config->state->epsilonOnlyTransitions) {\n      misc::IntervalSet nextTokens = atn.nextTokens(config->state);\n      if (nextTokens.contains(Token::EPSILON)) {\n        ATNState *endOfRuleState = atn.ruleToStopState[config->state->ruleIndex];\n        result->add(std::make_shared<ATNConfig>(*config, endOfRuleState), &mergeCache);\n      }\n    }\n  }\n\n  return result;\n}\n\nstd::unique_ptr<ATNConfigSet> ParserATNSimulator::computeStartState(ATNState *p, RuleContext *ctx, bool fullCtx) {\n  // always at least the implicit call to start rule\n  Ref<const PredictionContext> initialContext = PredictionContext::fromRuleContext(atn, ctx);\n  std::unique_ptr<ATNConfigSet> configs(new ATNConfigSet(fullCtx));\n\n#if DEBUG_ATN == 1 || TRACE_ATN_SIM == 1\n    std::cout << \"computeStartState from ATN state \" << p->toString() << \" initialContext=\" << initialContext->toString() << std::endl;\n#endif\n\n    for (size_t i = 0; i < p->transitions.size(); i++) {\n    ATNState *target = p->transitions[i]->target;\n    Ref<ATNConfig> c = std::make_shared<ATNConfig>(target, (int)i + 1, initialContext);\n    ATNConfig::Set closureBusy;\n    closure(c, configs.get(), closureBusy, true, fullCtx, false);\n  }\n\n  return configs;\n}\n\nstd::unique_ptr<ATNConfigSet> ParserATNSimulator::applyPrecedenceFilter(ATNConfigSet *configs) {\n  std::map<size_t, Ref<const PredictionContext>> statesFromAlt1;\n  std::unique_ptr<ATNConfigSet> configSet(new ATNConfigSet(configs->fullCtx));\n  for (const auto &config : configs->configs) {\n    // handle alt 1 first\n    if (config->alt != 1) {\n      continue;\n    }\n\n    Ref<const SemanticContext> updatedContext = config->semanticContext->evalPrecedence(parser, _outerContext);\n    if (updatedContext == nullptr) {\n      // the configuration was eliminated\n      continue;\n    }\n\n    statesFromAlt1[config->state->stateNumber] = config->context;\n    if (updatedContext != config->semanticContext) {\n      configSet->add(std::make_shared<ATNConfig>(*config, updatedContext), &mergeCache);\n    }\n    else {\n      configSet->add(config, &mergeCache);\n    }\n  }\n\n  for (const auto &config : configs->configs) {\n    if (config->alt == 1) {\n      // already handled\n      continue;\n    }\n\n    if (!config->isPrecedenceFilterSuppressed()) {\n      /* In the future, this elimination step could be updated to also\n       * filter the prediction context for alternatives predicting alt>1\n       * (basically a graph subtraction algorithm).\n       */\n      auto iterator = statesFromAlt1.find(config->state->stateNumber);\n      if (iterator != statesFromAlt1.end() && *iterator->second == *config->context) {\n        // eliminated\n        continue;\n      }\n    }\n\n    configSet->add(config, &mergeCache);\n  }\n\n  return configSet;\n}\n\natn::ATNState* ParserATNSimulator::getReachableTarget(const Transition *trans, size_t ttype) {\n  if (trans->matches(ttype, 0, atn.maxTokenType)) {\n    return trans->target;\n  }\n\n  return nullptr;\n}\n\n// Note that caller must memory manage the returned value from this function\nstd::vector<Ref<const SemanticContext>> ParserATNSimulator::getPredsForAmbigAlts(const BitSet &ambigAlts,\n  ATNConfigSet *configs, size_t nalts) {\n  // REACH=[1|1|[]|0:0, 1|2|[]|0:1]\n  /* altToPred starts as an array of all null contexts. The entry at index i\n   * corresponds to alternative i. altToPred[i] may have one of three values:\n   *   1. null: no ATNConfig c is found such that c.alt==i\n   *   2. SemanticContext.NONE: At least one ATNConfig c exists such that\n   *      c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,\n   *      alt i has at least one un-predicated config.\n   *   3. Non-NONE Semantic Context: There exists at least one, and for all\n   *      ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.\n   *\n   * From this, it is clear that NONE||anything==NONE.\n   */\n  std::vector<Ref<const SemanticContext>> altToPred(nalts + 1);\n\n  for (const auto &c : configs->configs) {\n    if (ambigAlts.test(c->alt)) {\n      altToPred[c->alt] = SemanticContext::Or(altToPred[c->alt], c->semanticContext);\n    }\n  }\n\n  size_t nPredAlts = 0;\n  for (size_t i = 1; i <= nalts; i++) {\n    if (altToPred[i] == nullptr) {\n      altToPred[i] = SemanticContext::Empty::Instance;\n    } else if (altToPred[i] != SemanticContext::Empty::Instance) {\n      nPredAlts++;\n    }\n  }\n\n  // nonambig alts are null in altToPred\n  if (nPredAlts == 0) {\n    altToPred.clear();\n  }\n#if DEBUG_ATN == 1\n    std::cout << \"getPredsForAmbigAlts result \" << Arrays::toString(altToPred) << std::endl;\n#endif\n\n  return altToPred;\n}\n\nstd::vector<dfa::DFAState::PredPrediction> ParserATNSimulator::getPredicatePredictions(const antlrcpp::BitSet &ambigAlts,\n                                                                                       const std::vector<Ref<const SemanticContext>> &altToPred) {\n  bool containsPredicate = std::find_if(altToPred.begin(), altToPred.end(), [](const Ref<const SemanticContext> &context) {\n    return context != SemanticContext::Empty::Instance;\n  }) != altToPred.end();\n  std::vector<dfa::DFAState::PredPrediction> pairs;\n  if (containsPredicate) {\n    for (size_t i = 1; i < altToPred.size(); i++) {\n      const auto &pred = altToPred[i];\n      assert(pred != nullptr); // unpredicted is indicated by SemanticContext.NONE\n      if (ambigAlts.test(i)) {\n        pairs.emplace_back(pred, static_cast<int>(i));\n      }\n    }\n  }\n  return pairs;\n}\n\nsize_t ParserATNSimulator::getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(ATNConfigSet *configs,\n  ParserRuleContext *outerContext)\n{\n  std::pair<ATNConfigSet *, ATNConfigSet *> sets = splitAccordingToSemanticValidity(configs, outerContext);\n  std::unique_ptr<ATNConfigSet> semValidConfigs(sets.first);\n  std::unique_ptr<ATNConfigSet> semInvalidConfigs(sets.second);\n  size_t alt = getAltThatFinishedDecisionEntryRule(semValidConfigs.get());\n  if (alt != ATN::INVALID_ALT_NUMBER) { // semantically/syntactically viable path exists\n    return alt;\n  }\n  // Is there a syntactically valid path with a failed pred?\n  if (!semInvalidConfigs->configs.empty()) {\n    alt = getAltThatFinishedDecisionEntryRule(semInvalidConfigs.get());\n    if (alt != ATN::INVALID_ALT_NUMBER) { // syntactically viable path exists\n      return alt;\n    }\n  }\n  return ATN::INVALID_ALT_NUMBER;\n}\n\nsize_t ParserATNSimulator::getAltThatFinishedDecisionEntryRule(ATNConfigSet *configs) {\n  misc::IntervalSet alts;\n  for (const auto &c : configs->configs) {\n    if (c->getOuterContextDepth() > 0 || (c->state != nullptr && c->state->getStateType() == ATNStateType::RULE_STOP && c->context->hasEmptyPath())) {\n      alts.add(c->alt);\n    }\n  }\n  if (alts.size() == 0) {\n    return ATN::INVALID_ALT_NUMBER;\n  }\n  return alts.getMinElement();\n}\n\nstd::pair<ATNConfigSet *, ATNConfigSet *> ParserATNSimulator::splitAccordingToSemanticValidity(ATNConfigSet *configs,\n  ParserRuleContext *outerContext) {\n\n  // mem-check: both pointers must be freed by the caller.\n  ATNConfigSet *succeeded(new ATNConfigSet(configs->fullCtx));\n  ATNConfigSet *failed(new ATNConfigSet(configs->fullCtx));\n  for (const auto &c : configs->configs) {\n    if (c->semanticContext != SemanticContext::Empty::Instance) {\n      bool predicateEvaluationResult = evalSemanticContext(c->semanticContext, outerContext, c->alt, configs->fullCtx);\n      if (predicateEvaluationResult) {\n        succeeded->add(c);\n      } else {\n        failed->add(c);\n      }\n    } else {\n      succeeded->add(c);\n    }\n  }\n  return { succeeded, failed };\n}\n\nBitSet ParserATNSimulator::evalSemanticContext(const std::vector<dfa::DFAState::PredPrediction> &predPredictions,\n                                               ParserRuleContext *outerContext, bool complete) {\n  BitSet predictions;\n  for (const auto &prediction : predPredictions) {\n    if (prediction.pred == SemanticContext::Empty::Instance) {\n      predictions.set(prediction.alt);\n      if (!complete) {\n        break;\n      }\n      continue;\n    }\n\n    bool fullCtx = false; // in dfa\n    bool predicateEvaluationResult = evalSemanticContext(prediction.pred, outerContext, prediction.alt, fullCtx);\n#if DEBUG_ATN == 1 || DFA_DEBUG == 1\n      std::cout << \"eval pred \" << prediction.toString() << \" = \" << predicateEvaluationResult << std::endl;\n#endif\n\n    if (predicateEvaluationResult) {\n#if DEBUG_ATN == 1 || DFA_DEBUG == 1\n        std::cout << \"PREDICT \" << prediction.alt << std::endl;\n#endif\n\n      predictions.set(prediction.alt);\n      if (!complete) {\n        break;\n      }\n    }\n  }\n\n  return predictions;\n}\n\nbool ParserATNSimulator::evalSemanticContext(Ref<const SemanticContext> const& pred, ParserRuleContext *parserCallStack,\n                                             size_t /*alt*/, bool /*fullCtx*/) {\n  return pred->eval(parser, parserCallStack);\n}\n\nvoid ParserATNSimulator::closure(Ref<ATNConfig> const& config, ATNConfigSet *configs, ATNConfig::Set &closureBusy,\n                                 bool collectPredicates, bool fullCtx, bool treatEofAsEpsilon) {\n  const int initialDepth = 0;\n  closureCheckingStopState(config, configs, closureBusy, collectPredicates, fullCtx, initialDepth, treatEofAsEpsilon);\n\n  assert(!fullCtx || !configs->dipsIntoOuterContext);\n}\n\nvoid ParserATNSimulator::closureCheckingStopState(Ref<ATNConfig> const& config, ATNConfigSet *configs,\n  ATNConfig::Set &closureBusy, bool collectPredicates, bool fullCtx, int depth, bool treatEofAsEpsilon) {\n\n#if TRACE_ATN_SIM == 1\n    std::cout << \"closure(\" << config->toString(true) << \")\" << std::endl;\n#endif\n\n  if (config->state != nullptr && config->state->getStateType() == ATNStateType::RULE_STOP) {\n    // We hit rule end. If we have context info, use it\n    // run thru all possible stack tops in ctx\n    if (!config->context->isEmpty()) {\n      for (size_t i = 0; i < config->context->size(); i++) {\n        if (config->context->getReturnState(i) == PredictionContext::EMPTY_RETURN_STATE) {\n          if (fullCtx) {\n            configs->add(std::make_shared<ATNConfig>(*config, config->state, PredictionContext::EMPTY), &mergeCache);\n            continue;\n          } else {\n            // we have no context info, just chase follow links (if greedy)\n#if DEBUG_ATN == 1\n              std::cout << \"FALLING off rule \" << getRuleName(config->state->ruleIndex) << std::endl;\n#endif\n            closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);\n          }\n          continue;\n        }\n        ATNState *returnState = atn.states[config->context->getReturnState(i)];\n        Ref<const PredictionContext> newContext = config->context->getParent(i); // \"pop\" return state\n        Ref<ATNConfig> c = std::make_shared<ATNConfig>(returnState, config->alt, newContext, config->semanticContext);\n        // While we have context to pop back from, we may have\n        // gotten that context AFTER having falling off a rule.\n        // Make sure we track that we are now out of context.\n        //\n        // This assignment also propagates the\n        // isPrecedenceFilterSuppressed() value to the new\n        // configuration.\n        c->reachesIntoOuterContext = config->reachesIntoOuterContext;\n        assert(depth > INT_MIN);\n\n        closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon);\n      }\n      return;\n    } else if (fullCtx) {\n      // reached end of start rule\n      configs->add(config, &mergeCache);\n      return;\n    } else {\n      // else if we have no context info, just chase follow links (if greedy)\n    }\n  }\n\n  closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);\n}\n\nvoid ParserATNSimulator::closure_(Ref<ATNConfig> const& config, ATNConfigSet *configs, ATNConfig::Set &closureBusy,\n                                  bool collectPredicates, bool fullCtx, int depth, bool treatEofAsEpsilon) {\n  ATNState *p = config->state;\n  // optimization\n  if (!p->epsilonOnlyTransitions) {\n    // make sure to not return here, because EOF transitions can act as\n    // both epsilon transitions and non-epsilon transitions.\n    configs->add(config, &mergeCache);\n  }\n\n  for (size_t i = 0; i < p->transitions.size(); i++) {\n    if (i == 0 && canDropLoopEntryEdgeInLeftRecursiveRule(config.get()))\n      continue;\n\n    const Transition *t = p->transitions[i].get();\n    bool continueCollecting = !(t != nullptr && t->getTransitionType() == TransitionType::ACTION) && collectPredicates;\n    Ref<ATNConfig> c = getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEofAsEpsilon);\n    if (c != nullptr) {\n      int newDepth = depth;\n      if (config->state != nullptr && config->state->getStateType() == ATNStateType::RULE_STOP) {\n        assert(!fullCtx);\n\n        // target fell off end of rule; mark resulting c as having dipped into outer context\n        // We can't get here if incoming config was rule stop and we had context\n        // track how far we dip into outer context.  Might\n        // come in handy and we avoid evaluating context dependent\n        // preds if this is > 0.\n\n        if (closureBusy.count(c) > 0) {\n          // avoid infinite recursion for right-recursive rules\n          continue;\n        }\n        closureBusy.insert(c);\n\n        if (_dfa != nullptr && _dfa->isPrecedenceDfa()) {\n          size_t outermostPrecedenceReturn = downCast<const EpsilonTransition *>(t)->outermostPrecedenceReturn();\n          if (outermostPrecedenceReturn == _dfa->atnStartState->ruleIndex) {\n            c->setPrecedenceFilterSuppressed(true);\n          }\n        }\n\n        c->reachesIntoOuterContext++;\n\n        if (!t->isEpsilon()) {\n          // avoid infinite recursion for EOF* and EOF+\n          if (closureBusy.count(c) == 0) {\n            closureBusy.insert(c);\n          } else {\n            continue;\n          }\n        }\n\n        configs->dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method\n        assert(newDepth > INT_MIN);\n\n        newDepth--;\n#if DFA_DEBUG == 1\n          std::cout << \"dips into outer ctx: \" << c << std::endl;\n#endif\n\n      } else  if (!t->isEpsilon()) {\n        // avoid infinite recursion for EOF* and EOF+\n        if (closureBusy.count(c) == 0) {\n          closureBusy.insert(c);\n        } else {\n          continue;\n        }\n      }\n\n      if (t != nullptr && t->getTransitionType() == TransitionType::RULE) {\n        // latch when newDepth goes negative - once we step out of the entry context we can't return\n        if (newDepth >= 0) {\n          newDepth++;\n        }\n      }\n\n      closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon);\n    }\n  }\n}\n\nbool ParserATNSimulator::canDropLoopEntryEdgeInLeftRecursiveRule(ATNConfig *config) const {\n  if (TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT)\n    return false;\n\n  ATNState *p = config->state;\n\n  // First check to see if we are in StarLoopEntryState generated during\n  // left-recursion elimination. For efficiency, also check if\n  // the context has an empty stack case. If so, it would mean\n  // global FOLLOW so we can't perform optimization\n  if (p->getStateType() != ATNStateType::STAR_LOOP_ENTRY ||\n      !((StarLoopEntryState *)p)->isPrecedenceDecision || // Are we the special loop entry/exit state?\n      config->context->isEmpty() ||                      // If SLL wildcard\n      config->context->hasEmptyPath())\n  {\n    return false;\n  }\n\n  // Require all return states to return back to the same rule\n  // that p is in.\n  size_t numCtxs = config->context->size();\n  for (size_t i = 0; i < numCtxs; i++) { // for each stack context\n    ATNState *returnState = atn.states[config->context->getReturnState(i)];\n    if (returnState->ruleIndex != p->ruleIndex)\n      return false;\n  }\n\n  BlockStartState *decisionStartState = (BlockStartState *)p->transitions[0]->target;\n  size_t blockEndStateNum = decisionStartState->endState->stateNumber;\n  BlockEndState *blockEndState = (BlockEndState *)atn.states[blockEndStateNum];\n\n  // Verify that the top of each stack context leads to loop entry/exit\n  // state through epsilon edges and w/o leaving rule.\n  for (size_t i = 0; i < numCtxs; i++) {                           // for each stack context\n    size_t returnStateNumber = config->context->getReturnState(i);\n    ATNState *returnState = atn.states[returnStateNumber];\n    // All states must have single outgoing epsilon edge.\n    if (returnState->transitions.size() != 1 || !returnState->transitions[0]->isEpsilon())\n    {\n      return false;\n    }\n\n    // Look for prefix op case like 'not expr', (' type ')' expr\n    ATNState *returnStateTarget = returnState->transitions[0]->target;\n    if (returnState->getStateType() == ATNStateType::BLOCK_END && returnStateTarget == p) {\n      continue;\n    }\n\n    // Look for 'expr op expr' or case where expr's return state is block end\n    // of (...)* internal block; the block end points to loop back\n    // which points to p but we don't need to check that\n    if (returnState == blockEndState) {\n      continue;\n    }\n\n    // Look for ternary expr ? expr : expr. The return state points at block end,\n    // which points at loop entry state\n    if (returnStateTarget == blockEndState) {\n      continue;\n    }\n\n    // Look for complex prefix 'between expr and expr' case where 2nd expr's\n    // return state points at block end state of (...)* internal block\n    if (returnStateTarget->getStateType() == ATNStateType::BLOCK_END &&\n        returnStateTarget->transitions.size() == 1 &&\n        returnStateTarget->transitions[0]->isEpsilon() &&\n        returnStateTarget->transitions[0]->target == p)\n    {\n      continue;\n    }\n\n    // Anything else ain't conforming.\n    return false;\n  }\n\n  return true;\n}\n\nstd::string ParserATNSimulator::getRuleName(size_t index) {\n  if (parser != nullptr) {\n    return parser->getRuleNames()[index];\n  }\n  return \"<rule \" + std::to_string(index) + \">\";\n}\n\nRef<ATNConfig> ParserATNSimulator::getEpsilonTarget(Ref<ATNConfig> const& config, const Transition *t, bool collectPredicates,\n                                                    bool inContext, bool fullCtx, bool treatEofAsEpsilon) {\n  switch (t->getTransitionType()) {\n    case TransitionType::RULE:\n      return ruleTransition(config, static_cast<const RuleTransition*>(t));\n\n    case TransitionType::PRECEDENCE:\n      return precedenceTransition(config, static_cast<const PrecedencePredicateTransition*>(t), collectPredicates, inContext, fullCtx);\n\n    case TransitionType::PREDICATE:\n      return predTransition(config, static_cast<const PredicateTransition*>(t), collectPredicates, inContext, fullCtx);\n\n    case TransitionType::ACTION:\n      return actionTransition(config, static_cast<const ActionTransition*>(t));\n\n    case TransitionType::EPSILON:\n      return std::make_shared<ATNConfig>(*config, t->target);\n\n    case TransitionType::ATOM:\n    case TransitionType::RANGE:\n    case TransitionType::SET:\n      // EOF transitions act like epsilon transitions after the first EOF\n      // transition is traversed\n      if (treatEofAsEpsilon) {\n        if (t->matches(Token::EOF, 0, 1)) {\n          return std::make_shared<ATNConfig>(*config, t->target);\n        }\n      }\n\n      return nullptr;\n\n    default:\n      return nullptr;\n  }\n}\n\nRef<ATNConfig> ParserATNSimulator::actionTransition(Ref<ATNConfig> const& config, const ActionTransition *t) {\n#if DFA_DEBUG == 1\n    std::cout << \"ACTION edge \" << t->ruleIndex << \":\" << t->actionIndex << std::endl;\n#endif\n\n  return std::make_shared<ATNConfig>(*config, t->target);\n}\n\nRef<ATNConfig> ParserATNSimulator::precedenceTransition(Ref<ATNConfig> const& config, const PrecedencePredicateTransition *pt,\n    bool collectPredicates, bool inContext, bool fullCtx) {\n#if DFA_DEBUG == 1\n    std::cout << \"PRED (collectPredicates=\" << collectPredicates << \") \" << pt->getPrecedence() << \">=_p\" << \", ctx dependent=true\" << std::endl;\n    if (parser != nullptr) {\n      std::cout << \"context surrounding pred is \" << Arrays::listToString(parser->getRuleInvocationStack(), \", \") << std::endl;\n    }\n#endif\n\n  Ref<ATNConfig> c;\n  if (collectPredicates && inContext) {\n    const auto &predicate = pt->getPredicate();\n\n    if (fullCtx) {\n      // In full context mode, we can evaluate predicates on-the-fly\n      // during closure, which dramatically reduces the size of\n      // the config sets. It also obviates the need to test predicates\n      // later during conflict resolution.\n      size_t currentPosition = _input->index();\n      _input->seek(_startIndex);\n      bool predSucceeds = evalSemanticContext(predicate, _outerContext, config->alt, fullCtx);\n      _input->seek(currentPosition);\n      if (predSucceeds) {\n        c = std::make_shared<ATNConfig>(*config, pt->target); // no pred context\n      }\n    } else {\n      Ref<const SemanticContext> newSemCtx = SemanticContext::And(config->semanticContext, predicate);\n      c = std::make_shared<ATNConfig>(*config, pt->target, std::move(newSemCtx));\n    }\n  } else {\n    c = std::make_shared<ATNConfig>(*config, pt->target);\n  }\n\n#if DFA_DEBUG == 1\n    std::cout << \"config from pred transition=\" << c << std::endl;\n#endif\n\n  return c;\n}\n\nRef<ATNConfig> ParserATNSimulator::predTransition(Ref<ATNConfig> const& config, const PredicateTransition *pt,\n  bool collectPredicates, bool inContext, bool fullCtx) {\n#if DFA_DEBUG == 1\n    std::cout << \"PRED (collectPredicates=\" << collectPredicates << \") \" << pt->getRuleIndex() << \":\" << pt->getPredIndex() << \", ctx dependent=\" << pt->isCtxDependent() << std::endl;\n    if (parser != nullptr) {\n      std::cout << \"context surrounding pred is \" << Arrays::listToString(parser->getRuleInvocationStack(), \", \") << std::endl;\n    }\n#endif\n\n  Ref<ATNConfig> c = nullptr;\n  if (collectPredicates && (!pt->isCtxDependent() || (pt->isCtxDependent() && inContext))) {\n    const auto &predicate = pt->getPredicate();\n    if (fullCtx) {\n      // In full context mode, we can evaluate predicates on-the-fly\n      // during closure, which dramatically reduces the size of\n      // the config sets. It also obviates the need to test predicates\n      // later during conflict resolution.\n      size_t currentPosition = _input->index();\n      _input->seek(_startIndex);\n      bool predSucceeds = evalSemanticContext(predicate, _outerContext, config->alt, fullCtx);\n      _input->seek(currentPosition);\n      if (predSucceeds) {\n        c = std::make_shared<ATNConfig>(*config, pt->target); // no pred context\n      }\n    } else {\n      Ref<const SemanticContext> newSemCtx = SemanticContext::And(config->semanticContext, predicate);\n      c = std::make_shared<ATNConfig>(*config, pt->target, std::move(newSemCtx));\n    }\n  } else {\n    c = std::make_shared<ATNConfig>(*config, pt->target);\n  }\n\n#if DFA_DEBUG == 1\n    std::cout << \"config from pred transition=\" << c << std::endl;\n#endif\n\n  return c;\n}\n\nRef<ATNConfig> ParserATNSimulator::ruleTransition(Ref<ATNConfig> const& config, const RuleTransition *t) {\n#if DFA_DEBUG == 1\n    std::cout << \"CALL rule \" << getRuleName(t->target->ruleIndex) << \", ctx=\" << config->context << std::endl;\n#endif\n\n  atn::ATNState *returnState = t->followState;\n  Ref<const PredictionContext> newContext = SingletonPredictionContext::create(config->context, returnState->stateNumber);\n  return std::make_shared<ATNConfig>(*config, t->target, newContext);\n}\n\nBitSet ParserATNSimulator::getConflictingAlts(ATNConfigSet *configs) {\n  std::vector<BitSet> altsets = PredictionModeClass::getConflictingAltSubsets(configs);\n  return PredictionModeClass::getAlts(altsets);\n}\n\nBitSet ParserATNSimulator::getConflictingAltsOrUniqueAlt(ATNConfigSet *configs) {\n  BitSet conflictingAlts;\n  if (configs->uniqueAlt != ATN::INVALID_ALT_NUMBER) {\n    conflictingAlts.set(configs->uniqueAlt);\n  } else {\n    conflictingAlts = configs->conflictingAlts;\n  }\n  return conflictingAlts;\n}\n\nstd::string ParserATNSimulator::getTokenName(size_t t) {\n  if (t == Token::EOF) {\n    return \"EOF\";\n  }\n\n  const dfa::Vocabulary &vocabulary = parser != nullptr ? parser->getVocabulary() : dfa::Vocabulary();\n  std::string displayName = vocabulary.getDisplayName(t);\n  if (displayName == std::to_string(t)) {\n    return displayName;\n  }\n\n  return displayName + \"<\" + std::to_string(t) + \">\";\n}\n\nstd::string ParserATNSimulator::getLookaheadName(TokenStream *input) {\n  return getTokenName(input->LA(1));\n}\n\nvoid ParserATNSimulator::dumpDeadEndConfigs(NoViableAltException &nvae) {\n  std::cerr << \"dead end configs: \";\n  for (const auto &c : nvae.getDeadEndConfigs()->configs) {\n    std::string trans = \"no edges\";\n    if (c->state->transitions.size() > 0) {\n      const Transition *t = c->state->transitions[0].get();\n      if (t != nullptr && t->getTransitionType() == TransitionType::ATOM) {\n        const AtomTransition *at = static_cast<const AtomTransition*>(t);\n        trans = \"Atom \" + getTokenName(at->_label);\n      } else if (t != nullptr && t->getTransitionType() == TransitionType::SET) {\n        const SetTransition *st = static_cast<const SetTransition*>(t);\n        trans = \"Set \";\n        trans += st->set.toString();\n      } else if (t != nullptr && t->getTransitionType() == TransitionType::NOT_SET) {\n        const SetTransition *st = static_cast<const NotSetTransition*>(t);\n        trans = \"~Set \";\n        trans += st->set.toString();\n      }\n    }\n    std::cerr << c->toString(true) + \":\" + trans;\n  }\n}\n\nNoViableAltException ParserATNSimulator::noViableAlt(TokenStream *input, ParserRuleContext *outerContext,\n  ATNConfigSet *configs, size_t startIndex, bool deleteConfigs) {\n  return NoViableAltException(parser, input, input->get(startIndex), input->LT(1), configs, outerContext, deleteConfigs);\n}\n\nsize_t ParserATNSimulator::getUniqueAlt(ATNConfigSet *configs) {\n  size_t alt = ATN::INVALID_ALT_NUMBER;\n  for (const auto &c : configs->configs) {\n    if (alt == ATN::INVALID_ALT_NUMBER) {\n      alt = c->alt; // found first alt\n    } else if (c->alt != alt) {\n      return ATN::INVALID_ALT_NUMBER;\n    }\n  }\n  return alt;\n}\n\ndfa::DFAState *ParserATNSimulator::addDFAEdge(dfa::DFA &dfa, dfa::DFAState *from, ssize_t t, dfa::DFAState *to) {\n#if DFA_DEBUG == 1\n    std::cout << \"EDGE \" << from << \" -> \" << to << \" upon \" << getTokenName(t) << std::endl;\n#endif\n\n  if (to == nullptr) {\n    return nullptr;\n  }\n\n  {\n    UniqueLock<SharedMutex> stateLock(atn._stateMutex);\n    to = addDFAState(dfa, to); // used existing if possible not incoming\n  }\n  if (from == nullptr || t > (int)atn.maxTokenType) {\n    return to;\n  }\n\n  {\n    UniqueLock<SharedMutex> edgeLock(atn._edgeMutex);\n    from->edges[t] = to; // connect\n  }\n\n#if DFA_DEBUG == 1\n    std::string dfaText;\n    if (parser != nullptr) {\n      dfaText = dfa.toString(parser->getVocabulary());\n    } else {\n      dfaText = dfa.toString(dfa::Vocabulary());\n    }\n    std::cout << \"DFA=\\n\" << dfaText << std::endl;\n#endif\n\n  return to;\n}\n\ndfa::DFAState *ParserATNSimulator::addDFAState(dfa::DFA &dfa, dfa::DFAState *D) {\n  if (D == ERROR.get()) {\n    return D;\n  }\n\n  // Optimizing the configs below should not alter the hash code. Thus we can just do an insert\n  // which will only succeed if an equivalent DFAState does not already exist.\n  auto [existing, inserted] = dfa.states.insert(D);\n  if (!inserted) {\n#if TRACE_ATN_SIM == 1\n      std::cout << \"addDFAState \" << D->toString() << \" exists\" << std::endl;\n#endif\n    return *existing;\n  }\n\n  // Previously we did a lookup, then set fields, then inserted. It was `dfa.states.size()`, since\n  // we already inserted we need to subtract one.\n  D->stateNumber = static_cast<int>(dfa.states.size() - 1);\n\n#if TRACE_ATN_SIM == 1\n    std::cout << \"addDFAState new \" << D->toString() << std::endl;\n#endif\n\n  if (!D->configs->isReadonly()) {\n    D->configs->optimizeConfigs(this);\n    D->configs->setReadonly(true);\n  }\n\n#if DFA_DEBUG == 1\n  std::cout << \"adding new DFA state: \" << D << std::endl;\n#endif\n\n  return D;\n}\n\nvoid ParserATNSimulator::reportAttemptingFullContext(dfa::DFA &dfa, const antlrcpp::BitSet &conflictingAlts,\n  ATNConfigSet *configs, size_t startIndex, size_t stopIndex) {\n#if DFA_DEBUG == 1 || RETRY_DEBUG == 1\n    misc::Interval interval = misc::Interval((int)startIndex, (int)stopIndex);\n    std::cout << \"reportAttemptingFullContext decision=\" << dfa.decision << \":\" << configs << \", input=\" << parser->getTokenStream()->getText(interval) << std::endl;\n#endif\n\n  if (parser != nullptr) {\n    parser->getErrorListenerDispatch().reportAttemptingFullContext(parser, dfa, startIndex, stopIndex, conflictingAlts, configs);\n  }\n}\n\nvoid ParserATNSimulator::reportContextSensitivity(dfa::DFA &dfa, size_t prediction, ATNConfigSet *configs,\n  size_t startIndex, size_t stopIndex) {\n#if DFA_DEBUG == 1 || RETRY_DEBUG == 1\n    misc::Interval interval = misc::Interval(startIndex, stopIndex);\n    std::cout << \"reportContextSensitivity decision=\" << dfa.decision << \":\" << configs << \", input=\" << parser->getTokenStream()->getText(interval) << std::endl;\n#endif\n\n  if (parser != nullptr) {\n    parser->getErrorListenerDispatch().reportContextSensitivity(parser, dfa, startIndex, stopIndex, prediction, configs);\n  }\n}\n\nvoid ParserATNSimulator::reportAmbiguity(dfa::DFA &dfa, dfa::DFAState * /*D*/, size_t startIndex, size_t stopIndex,\n                                         bool exact, const antlrcpp::BitSet &ambigAlts, ATNConfigSet *configs) {\n#if DFA_DEBUG == 1 || RETRY_DEBUG == 1\n    misc::Interval interval = misc::Interval((int)startIndex, (int)stopIndex);\n    std::cout << \"reportAmbiguity \" << ambigAlts << \":\" << configs << \", input=\" << parser->getTokenStream()->getText(interval) << std::endl;\n#endif\n\n  if (parser != nullptr) {\n    parser->getErrorListenerDispatch().reportAmbiguity(parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs);\n  }\n}\n\nvoid ParserATNSimulator::setPredictionMode(PredictionMode newMode) {\n  _mode = newMode;\n}\n\natn::PredictionMode ParserATNSimulator::getPredictionMode() {\n  return _mode;\n}\n\nParser* ParserATNSimulator::getParser() {\n  return parser;\n}\n\n#ifdef _MSC_VER\n#pragma warning (disable:4996) // 'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead.\n#endif\n\nbool ParserATNSimulator::getLrLoopSetting() {\n  char *var = std::getenv(\"TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT\");\n  if (var == nullptr)\n    return false;\n  std::string value(var);\n  return value == \"true\" || value == \"1\";\n}\n\n#ifdef _MSC_VER\n#pragma warning (default:4996)\n#endif\n\nvoid ParserATNSimulator::InitializeInstanceFields() {\n  _mode = PredictionMode::LL;\n  _startIndex = 0;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ParserATNSimulator.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"PredictionMode.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"dfa/DFAState.h\"\n#include \"atn/ATNSimulator.h\"\n#include \"atn/PredictionContext.h\"\n#include \"atn/PredictionContextMergeCache.h\"\n#include \"atn/ParserATNSimulatorOptions.h\"\n#include \"SemanticContext.h\"\n#include \"atn/ATNConfig.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /**\n   * The embodiment of the adaptive LL(*), ALL(*), parsing strategy.\n   *\n   * <p>\n   * The basic complexity of the adaptive strategy makes it harder to understand.\n   * We begin with ATN simulation to build paths in a DFA. Subsequent prediction\n   * requests go through the DFA first. If they reach a state without an edge for\n   * the current symbol, the algorithm fails over to the ATN simulation to\n   * complete the DFA path for the current input (until it finds a conflict state\n   * or uniquely predicting state).</p>\n   *\n   * <p>\n   * All of that is done without using the outer context because we want to create\n   * a DFA that is not dependent upon the rule invocation stack when we do a\n   * prediction. One DFA works in all contexts. We avoid using context not\n   * necessarily because it's slower, although it can be, but because of the DFA\n   * caching problem. The closure routine only considers the rule invocation stack\n   * created during prediction beginning in the decision rule. For example, if\n   * prediction occurs without invoking another rule's ATN, there are no context\n   * stacks in the configurations. When lack of context leads to a conflict, we\n   * don't know if it's an ambiguity or a weakness in the strong LL(*) parsing\n   * strategy (versus full LL(*)).</p>\n   *\n   * <p>\n   * When SLL yields a configuration set with conflict, we rewind the input and\n   * retry the ATN simulation, this time using full outer context without adding\n   * to the DFA. Configuration context stacks will be the full invocation stacks\n   * from the start rule. If we get a conflict using full context, then we can\n   * definitively say we have a true ambiguity for that input sequence. If we\n   * don't get a conflict, it implies that the decision is sensitive to the outer\n   * context. (It is not context-sensitive in the sense of context-sensitive\n   * grammars.)</p>\n   *\n   * <p>\n   * The next time we reach this DFA state with an SLL conflict, through DFA\n   * simulation, we will again retry the ATN simulation using full context mode.\n   * This is slow because we can't save the results and have to \"interpret\" the\n   * ATN each time we get that input.</p>\n   *\n   * <p>\n   * <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>\n   *\n   * <p>\n   * We could cache results from full context to predicted alternative easily and\n   * that saves a lot of time but doesn't work in presence of predicates. The set\n   * of visible predicates from the ATN start state changes depending on the\n   * context, because closure can fall off the end of a rule. I tried to cache\n   * tuples (stack context, semantic context, predicted alt) but it was slower\n   * than interpreting and much more complicated. Also required a huge amount of\n   * memory. The goal is not to create the world's fastest parser anyway. I'd like\n   * to keep this algorithm simple. By launching multiple threads, we can improve\n   * the speed of parsing across a large number of files.</p>\n   *\n   * <p>\n   * There is no strict ordering between the amount of input used by SLL vs LL,\n   * which makes it really hard to build a cache for full context. Let's say that\n   * we have input A B C that leads to an SLL conflict with full context X. That\n   * implies that using X we might only use A B but we could also use A B C D to\n   * resolve conflict. Input A B C D could predict alternative 1 in one position\n   * in the input and A B C E could predict alternative 2 in another position in\n   * input. The conflicting SLL configurations could still be non-unique in the\n   * full context prediction, which would lead us to requiring more input than the\n   * original A B C.\tTo make a\tprediction cache work, we have to track\tthe exact\n   * input\tused during the previous prediction. That amounts to a cache that maps\n   * X to a specific DFA for that context.</p>\n   *\n   * <p>\n   * Something should be done for left-recursive expression predictions. They are\n   * likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry\n   * with full LL thing Sam does.</p>\n   *\n   * <p>\n   * <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>\n   *\n   * <p>\n   * We avoid doing full context retry when the outer context is empty, we did not\n   * dip into the outer context by falling off the end of the decision state rule,\n   * or when we force SLL mode.</p>\n   *\n   * <p>\n   * As an example of the not dip into outer context case, consider as super\n   * constructor calls versus function calls. One grammar might look like\n   * this:</p>\n   *\n   * <pre>\n   * ctorBody\n   *   : '{' superCall? stat* '}'\n   *   ;\n   * </pre>\n   *\n   * <p>\n   * Or, you might see something like</p>\n   *\n   * <pre>\n   * stat\n   *   : superCall ';'\n   *   | expression ';'\n   *   | ...\n   *   ;\n   * </pre>\n   *\n   * <p>\n   * In both cases I believe that no closure operations will dip into the outer\n   * context. In the first case ctorBody in the worst case will stop at the '}'.\n   * In the 2nd case it should stop at the ';'. Both cases should stay within the\n   * entry rule and not dip into the outer context.</p>\n   *\n   * <p>\n   * <strong>PREDICATES</strong></p>\n   *\n   * <p>\n   * Predicates are always evaluated if present in either SLL or LL both. SLL and\n   * LL simulation deals with predicates differently. SLL collects predicates as\n   * it performs closure operations like ANTLR v3 did. It delays predicate\n   * evaluation until it reaches and accept state. This allows us to cache the SLL\n   * ATN simulation whereas, if we had evaluated predicates on-the-fly during\n   * closure, the DFA state configuration sets would be different and we couldn't\n   * build up a suitable DFA.</p>\n   *\n   * <p>\n   * When building a DFA accept state during ATN simulation, we evaluate any\n   * predicates and return the sole semantically valid alternative. If there is\n   * more than 1 alternative, we report an ambiguity. If there are 0 alternatives,\n   * we throw an exception. Alternatives without predicates act like they have\n   * true predicates. The simple way to think about it is to strip away all\n   * alternatives with false predicates and choose the minimum alternative that\n   * remains.</p>\n   *\n   * <p>\n   * When we start in the DFA and reach an accept state that's predicated, we test\n   * those and return the minimum semantically viable alternative. If no\n   * alternatives are viable, we throw an exception.</p>\n   *\n   * <p>\n   * During full LL ATN simulation, closure always evaluates predicates and\n   * on-the-fly. This is crucial to reducing the configuration set size during\n   * closure. It hits a landmine when parsing with the Java grammar, for example,\n   * without this on-the-fly evaluation.</p>\n   *\n   * <p>\n   * <strong>SHARING DFA</strong></p>\n   *\n   * <p>\n   * All instances of the same parser share the same decision DFAs through a\n   * static field. Each instance gets its own ATN simulator but they share the\n   * same {@link #decisionToDFA} field. They also share a\n   * {@link PredictionContextCache} object that makes sure that all\n   * {@link PredictionContext} objects are shared among the DFA states. This makes\n   * a big size difference.</p>\n   *\n   * <p>\n   * <strong>THREAD SAFETY</strong></p>\n   *\n   * <p>\n   * The {@link ParserATNSimulator} locks on the {@link #decisionToDFA} field when\n   * it adds a new DFA object to that array. {@link #addDFAEdge}\n   * locks on the DFA for the current decision when setting the\n   * {@link DFAState#edges} field. {@link #addDFAState} locks on\n   * the DFA for the current decision when looking up a DFA state to see if it\n   * already exists. We must make sure that all requests to add DFA states that\n   * are equivalent result in the same shared DFA object. This is because lots of\n   * threads will be trying to update the DFA at once. The\n   * {@link #addDFAState} method also locks inside the DFA lock\n   * but this time on the shared context cache when it rebuilds the\n   * configurations' {@link PredictionContext} objects using cached\n   * subgraphs/nodes. No other locking occurs, even during DFA simulation. This is\n   * safe as long as we can guarantee that all threads referencing\n   * {@code s.edge[t]} get the same physical target {@link DFAState}, or\n   * {@code null}. Once into the DFA, the DFA simulation does not reference the\n   * {@link DFA#states} map. It follows the {@link DFAState#edges} field to new\n   * targets. The DFA simulator will either find {@link DFAState#edges} to be\n   * {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or\n   * {@code dfa.edges[t]} to be non-null. The\n   * {@link #addDFAEdge} method could be racing to set the field\n   * but in either case the DFA simulator works; if {@code null}, and requests ATN\n   * simulation. It could also race trying to get {@code dfa.edges[t]}, but either\n   * way it will work because it's not doing a test and set operation.</p>\n   *\n   * <p>\n   * <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage\n   * Parsing)</strong></p>\n   *\n   * <p>\n   * Sam pointed out that if SLL does not give a syntax error, then there is no\n   * point in doing full LL, which is slower. We only have to try LL if we get a\n   * syntax error. For maximum speed, Sam starts the parser set to pure SLL\n   * mode with the {@link BailErrorStrategy}:</p>\n   *\n   * <pre>\n   * parser.{@link Parser#getInterpreter() getInterpreter()}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};\n   * parser.{@link Parser#setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());\n   * </pre>\n   *\n   * <p>\n   * If it does not get a syntax error, then we're done. If it does get a syntax\n   * error, we need to retry with the combined SLL/LL strategy.</p>\n   *\n   * <p>\n   * The reason this works is as follows. If there are no SLL conflicts, then the\n   * grammar is SLL (at least for that input set). If there is an SLL conflict,\n   * the full LL analysis must yield a set of viable alternatives which is a\n   * subset of the alternatives reported by SLL. If the LL set is a singleton,\n   * then the grammar is LL but not SLL. If the LL set is the same size as the SLL\n   * set, the decision is SLL. If the LL set has size &gt; 1, then that decision\n   * is truly ambiguous on the current input. If the LL set is smaller, then the\n   * SLL conflict resolution might choose an alternative that the full LL would\n   * rule out as a possibility based upon better context information. If that's\n   * the case, then the SLL parse will definitely get an error because the full LL\n   * analysis says it's not viable. If SLL conflict resolution chooses an\n   * alternative within the LL set, them both SLL and LL would choose the same\n   * alternative because they both choose the minimum of multiple conflicting\n   * alternatives.</p>\n   *\n   * <p>\n   * Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and\n   * a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL\n   * parsing will get an error because SLL will pursue alternative 1. If\n   * <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will\n   * choose the same alternative because alternative one is the minimum of either\n   * set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax\n   * error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>\n   *\n   * <p>\n   * Of course, if the input is invalid, then we will get an error for sure in\n   * both SLL and LL parsing. Erroneous input will therefore require 2 passes over\n   * the input.</p>\n   */\n  class ANTLR4CPP_PUBLIC ParserATNSimulator : public ATNSimulator {\n  public:\n    /// Testing only!\n    ParserATNSimulator(const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                       PredictionContextCache &sharedContextCache);\n\n    ParserATNSimulator(Parser *parser, const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                       PredictionContextCache &sharedContextCache);\n\n    ParserATNSimulator(Parser *parser, const ATN &atn, std::vector<dfa::DFA> &decisionToDFA,\n                       PredictionContextCache &sharedContextCache,\n                       const ParserATNSimulatorOptions &options);\n\n    void reset() override;\n    void clearDFA() override;\n    virtual size_t adaptivePredict(TokenStream *input, size_t decision, ParserRuleContext *outerContext);\n\n    static const bool TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT;\n\n    std::vector<dfa::DFA> &decisionToDFA;\n\n    /** Implements first-edge (loop entry) elimination as an optimization\n     *  during closure operations.  See antlr/antlr4#1398.\n     *\n     * The optimization is to avoid adding the loop entry config when\n     * the exit path can only lead back to the same\n     * StarLoopEntryState after popping context at the rule end state\n     * (traversing only epsilon edges, so we're still in closure, in\n     * this same rule).\n     *\n     * We need to detect any state that can reach loop entry on\n     * epsilon w/o exiting rule. We don't have to look at FOLLOW\n     * links, just ensure that all stack tops for config refer to key\n     * states in LR rule.\n     *\n     * To verify we are in the right situation we must first check\n     * closure is at a StarLoopEntryState generated during LR removal.\n     * Then we check that each stack top of context is a return state\n     * from one of these cases:\n     *\n     *   1. 'not' expr, '(' type ')' expr. The return state points at loop entry state\n     *   2. expr op expr. The return state is the block end of internal block of (...)*\n     *   3. 'between' expr 'and' expr. The return state of 2nd expr reference.\n     *      That state points at block end of internal block of (...)*.\n     *   4. expr '?' expr ':' expr. The return state points at block end,\n     *      which points at loop entry state.\n     *\n     * If any is true for each stack top, then closure does not add a\n     * config to the current config set for edge[0], the loop entry branch.\n     *\n     *  Conditions fail if any context for the current config is:\n     *\n     *   a. empty (we'd fall out of expr to do a global FOLLOW which could\n     *      even be to some weird spot in expr) or,\n     *   b. lies outside of expr or,\n     *   c. lies within expr but at a state not the BlockEndState\n     *   generated during LR removal\n     *\n     * Do we need to evaluate predicates ever in closure for this case?\n     *\n     * No. Predicates, including precedence predicates, are only\n     * evaluated when computing a DFA start state. I.e., only before\n     * the lookahead (but not parser) consumes a token.\n     *\n     * There are no epsilon edges allowed in LR rule alt blocks or in\n     * the \"primary\" part (ID here). If closure is in\n     * StarLoopEntryState any lookahead operation will have consumed a\n     * token as there are no epsilon-paths that lead to\n     * StarLoopEntryState. We do not have to evaluate predicates\n     * therefore if we are in the generated StarLoopEntryState of a LR\n     * rule. Note that when making a prediction starting at that\n     * decision point, decision d=2, compute-start-state performs\n     * closure starting at edges[0], edges[1] emanating from\n     * StarLoopEntryState. That means it is not performing closure on\n     * StarLoopEntryState during compute-start-state.\n     *\n     * How do we know this always gives same prediction answer?\n     *\n     * Without predicates, loop entry and exit paths are ambiguous\n     * upon remaining input +b (in, say, a+b). Either paths lead to\n     * valid parses. Closure can lead to consuming + immediately or by\n     * falling out of this call to expr back into expr and loop back\n     * again to StarLoopEntryState to match +b. In this special case,\n     * we choose the more efficient path, which is to take the bypass\n     * path.\n     *\n     * The lookahead language has not changed because closure chooses\n     * one path over the other. Both paths lead to consuming the same\n     * remaining input during a lookahead operation. If the next token\n     * is an operator, lookahead will enter the choice block with\n     * operators. If it is not, lookahead will exit expr. Same as if\n     * closure had chosen to enter the choice block immediately.\n     *\n     * Closure is examining one config (some loopentrystate, some alt,\n     * context) which means it is considering exactly one alt. Closure\n     * always copies the same alt to any derived configs.\n     *\n     * How do we know this optimization doesn't mess up precedence in\n     * our parse trees?\n     *\n     * Looking through expr from left edge of stat only has to confirm\n     * that an input, say, a+b+c; begins with any valid interpretation\n     * of an expression. The precedence actually doesn't matter when\n     * making a decision in stat seeing through expr. It is only when\n     * parsing rule expr that we must use the precedence to get the\n     * right interpretation and, hence, parse tree.\n     */\n    bool canDropLoopEntryEdgeInLeftRecursiveRule(ATNConfig *config) const;\n    virtual std::string getRuleName(size_t index);\n\n    virtual Ref<ATNConfig> precedenceTransition(Ref<ATNConfig> const& config, const PrecedencePredicateTransition *pt,\n                                                bool collectPredicates, bool inContext, bool fullCtx);\n\n    void setPredictionMode(PredictionMode newMode);\n    PredictionMode getPredictionMode();\n\n    Parser* getParser();\n\n    virtual std::string getTokenName(size_t t);\n\n    virtual std::string getLookaheadName(TokenStream *input);\n\n    /// <summary>\n    /// Used for debugging in adaptivePredict around execATN but I cut\n    ///  it out for clarity now that alg. works well. We can leave this\n    ///  \"dead\" code for a bit.\n    /// </summary>\n    virtual void dumpDeadEndConfigs(NoViableAltException &nvae);\n\n  protected:\n    Parser *const parser;\n\n    /// <summary>\n    /// Each prediction operation uses a cache for merge of prediction contexts.\n    /// Don't keep around as it wastes huge amounts of memory. The merge cache\n    /// isn't synchronized but we're ok since two threads shouldn't reuse same\n    /// parser/atnsim object because it can only handle one input at a time.\n    /// This maps graphs a and b to merged result c. (a,b)->c. We can avoid\n    /// the merge if we ever see a and b again.  Note that (b,a)->c should\n    /// also be examined during cache lookup.\n    /// </summary>\n    PredictionContextMergeCache mergeCache;\n    size_t _mergeCacheCounter = 0;\n\n    // LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n    TokenStream *_input;\n    size_t _startIndex;\n    ParserRuleContext *_outerContext;\n    dfa::DFA *_dfa; // Reference into the decisionToDFA vector.\n\n    /// <summary>\n    /// Performs ATN simulation to compute a predicted alternative based\n    ///  upon the remaining input, but also updates the DFA cache to avoid\n    ///  having to traverse the ATN again for the same input sequence.\n    ///\n    /// There are some key conditions we're looking for after computing a new\n    /// set of ATN configs (proposed DFA state):\n    /// if the set is empty, there is no viable alternative for current symbol\n    /// does the state uniquely predict an alternative?\n    /// does the state have a conflict that would prevent us from\n    ///         putting it on the work list?\n    ///\n    /// We also have some key operations to do:\n    /// add an edge from previous DFA state to potentially new DFA state, D,\n    ///         upon current symbol but only if adding to work list, which means in all\n    ///         cases except no viable alternative (and possibly non-greedy decisions?)\n    /// collecting predicates and adding semantic context to DFA accept states\n    /// adding rule context to context-sensitive DFA accept states\n    /// consuming an input symbol\n    /// reporting a conflict\n    /// reporting an ambiguity\n    /// reporting a context sensitivity\n    /// reporting insufficient predicates\n    ///\n    /// cover these cases:\n    ///    dead end\n    ///    single alt\n    ///    single alt + preds\n    ///    conflict\n    ///    conflict + preds\n    /// </summary>\n    virtual size_t execATN(dfa::DFA &dfa, dfa::DFAState *s0, TokenStream *input, size_t startIndex,\n                           ParserRuleContext *outerContext);\n\n    /// <summary>\n    /// Get an existing target state for an edge in the DFA. If the target state\n    /// for the edge has not yet been computed or is otherwise not available,\n    /// this method returns {@code null}.\n    /// </summary>\n    /// <param name=\"previousD\"> The current DFA state </param>\n    /// <param name=\"t\"> The next input symbol </param>\n    /// <returns> The existing target DFA state for the given input symbol\n    /// {@code t}, or {@code null} if the target state for this edge is not\n    /// already cached </returns>\n    virtual dfa::DFAState* getExistingTargetState(dfa::DFAState *previousD, size_t t);\n\n    /// <summary>\n    /// Compute a target state for an edge in the DFA, and attempt to add the\n    /// computed state and corresponding edge to the DFA.\n    /// </summary>\n    /// <param name=\"dfa\"> The DFA </param>\n    /// <param name=\"previousD\"> The current DFA state </param>\n    /// <param name=\"t\"> The next input symbol\n    /// </param>\n    /// <returns> The computed target DFA state for the given input symbol\n    /// {@code t}. If {@code t} does not lead to a valid DFA state, this method\n    /// returns <seealso cref=\"#ERROR\"/>. </returns>\n    virtual dfa::DFAState *computeTargetState(dfa::DFA &dfa, dfa::DFAState *previousD, size_t t);\n\n    virtual void predicateDFAState(dfa::DFAState *dfaState, DecisionState *decisionState);\n\n    // comes back with reach.uniqueAlt set to a valid alt\n    virtual size_t execATNWithFullContext(dfa::DFA &dfa, dfa::DFAState *D, ATNConfigSet *s0,\n                                          TokenStream *input, size_t startIndex, ParserRuleContext *outerContext); // how far we got before failing over\n\n    virtual std::unique_ptr<ATNConfigSet> computeReachSet(ATNConfigSet *closure, size_t t, bool fullCtx);\n\n    /// <summary>\n    /// Return a configuration set containing only the configurations from\n    /// {@code configs} which are in a <seealso cref=\"RuleStopState\"/>. If all\n    /// configurations in {@code configs} are already in a rule stop state, this\n    /// method simply returns {@code configs}.\n    /// <p/>\n    /// When {@code lookToEndOfRule} is true, this method uses\n    /// <seealso cref=\"ATN#nextTokens\"/> for each configuration in {@code configs} which is\n    /// not already in a rule stop state to see if a rule stop state is reachable\n    /// from the configuration via epsilon-only transitions.\n    /// </summary>\n    /// <param name=\"configs\"> the configuration set to update </param>\n    /// <param name=\"lookToEndOfRule\"> when true, this method checks for rule stop states\n    /// reachable by epsilon-only transitions from each configuration in\n    /// {@code configs}.\n    /// </param>\n    /// <returns> {@code configs} if all configurations in {@code configs} are in a\n    /// rule stop state, otherwise return a new configuration set containing only\n    /// the configurations from {@code configs} which are in a rule stop state </returns>\n    virtual ATNConfigSet* removeAllConfigsNotInRuleStopState(ATNConfigSet *configs, bool lookToEndOfRule);\n\n    virtual std::unique_ptr<ATNConfigSet> computeStartState(ATNState *p, RuleContext *ctx, bool fullCtx);\n\n    /* parrt internal source braindump that doesn't mess up\n     * external API spec.\n\n     applyPrecedenceFilter is an optimization to avoid highly\n     nonlinear prediction of expressions and other left recursive\n     rules. The precedence predicates such as {3>=prec}? Are highly\n     context-sensitive in that they can only be properly evaluated\n     in the context of the proper prec argument. Without pruning,\n     these predicates are normal predicates evaluated when we reach\n     conflict state (or unique prediction). As we cannot evaluate\n     these predicates out of context, the resulting conflict leads\n     to full LL evaluation and nonlinear prediction which shows up\n     very clearly with fairly large expressions.\n\n     Example grammar:\n\n     e : e '*' e\n     | e '+' e\n     | INT\n     ;\n\n     We convert that to the following:\n\n     e[int prec]\n     :   INT\n     ( {3>=prec}? '*' e[4]\n     | {2>=prec}? '+' e[3]\n     )*\n     ;\n\n     The (..)* loop has a decision for the inner block as well as\n     an enter or exit decision, which is what concerns us here. At\n     the 1st + of input 1+2+3, the loop entry sees both predicates\n     and the loop exit also sees both predicates by falling off the\n     edge of e.  This is because we have no stack information with\n     SLL and find the follow of e, which will hit the return states\n     inside the loop after e[4] and e[3], which brings it back to\n     the enter or exit decision. In this case, we know that we\n     cannot evaluate those predicates because we have fallen off\n     the edge of the stack and will in general not know which prec\n     parameter is the right one to use in the predicate.\n\n     Because we have special information, that these are precedence\n     predicates, we can resolve them without failing over to full\n     LL despite their context sensitive nature. We make an\n     assumption that prec[-1] <= prec[0], meaning that the current\n     precedence level is greater than or equal to the precedence\n     level of recursive invocations above us in the stack. For\n     example, if predicate {3>=prec}? is true of the current prec,\n     then one option is to enter the loop to match it now. The\n     other option is to exit the loop and the left recursive rule\n     to match the current operator in rule invocation further up\n     the stack. But, we know that all of those prec are lower or\n     the same value and so we can decide to enter the loop instead\n     of matching it later. That means we can strip out the other\n     configuration for the exit branch.\n\n     So imagine we have (14,1,$,{2>=prec}?) and then\n     (14,2,$-dipsIntoOuterContext,{2>=prec}?). The optimization\n     allows us to collapse these two configurations. We know that\n     if {2>=prec}? is true for the current prec parameter, it will\n     also be true for any prec from an invoking e call, indicated\n     by dipsIntoOuterContext. As the predicates are both true, we\n     have the option to evaluate them early in the decision start\n     state. We do this by stripping both predicates and choosing to\n     enter the loop as it is consistent with the notion of operator\n     precedence. It's also how the full LL conflict resolution\n     would work.\n\n     The solution requires a different DFA start state for each\n     precedence level.\n\n     The basic filter mechanism is to remove configurations of the\n     form (p, 2, pi) if (p, 1, pi) exists for the same p and pi. In\n     other words, for the same ATN state and predicate context,\n     remove any configuration associated with an exit branch if\n     there is a configuration associated with the enter branch.\n\n     It's also the case that the filter evaluates precedence\n     predicates and resolves conflicts according to precedence\n     levels. For example, for input 1+2+3 at the first +, we see\n     prediction filtering\n\n     [(11,1,[$],{3>=prec}?), (14,1,[$],{2>=prec}?), (5,2,[$],up=1),\n     (11,2,[$],up=1), (14,2,[$],up=1)],hasSemanticContext=true,dipsIntoOuterContext\n\n     to\n\n     [(11,1,[$]), (14,1,[$]), (5,2,[$],up=1)],dipsIntoOuterContext\n\n     This filters because {3>=prec}? evals to true and collapses\n     (11,1,[$],{3>=prec}?) and (11,2,[$],up=1) since early conflict\n     resolution based upon rules of operator precedence fits with\n     our usual match first alt upon conflict.\n\n     We noticed a problem where a recursive call resets precedence\n     to 0. Sam's fix: each config has flag indicating if it has\n     returned from an expr[0] call. then just don't filter any\n     config with that flag set. flag is carried along in\n     closure(). so to avoid adding field, set bit just under sign\n     bit of dipsIntoOuterContext (SUPPRESS_PRECEDENCE_FILTER).\n     With the change you filter \"unless (p, 2, pi) was reached\n     after leaving the rule stop state of the LR rule containing\n     state p, corresponding to a rule invocation with precedence\n     level 0\"\n     */\n\n    /**\n     * This method transforms the start state computed by\n     * {@link #computeStartState} to the special start state used by a\n     * precedence DFA for a particular precedence value. The transformation\n     * process applies the following changes to the start state's configuration\n     * set.\n     *\n     * <ol>\n     * <li>Evaluate the precedence predicates for each configuration using\n     * {@link SemanticContext#evalPrecedence}.</li>\n     * <li>When {@link ATNConfig#isPrecedenceFilterSuppressed} is {@code false},\n     * remove all configurations which predict an alternative greater than 1,\n     * for which another configuration that predicts alternative 1 is in the\n     * same ATN state with the same prediction context. This transformation is\n     * valid for the following reasons:\n     * <ul>\n     * <li>The closure block cannot contain any epsilon transitions which bypass\n     * the body of the closure, so all states reachable via alternative 1 are\n     * part of the precedence alternatives of the transformed left-recursive\n     * rule.</li>\n     * <li>The \"primary\" portion of a left recursive rule cannot contain an\n     * epsilon transition, so the only way an alternative other than 1 can exist\n     * in a state that is also reachable via alternative 1 is by nesting calls\n     * to the left-recursive rule, with the outer calls not being at the\n     * preferred precedence level. The\n     * {@link ATNConfig#isPrecedenceFilterSuppressed} property marks ATN\n     * configurations which do not meet this condition, and therefore are not\n     * eligible for elimination during the filtering process.</li>\n     * </ul>\n     * </li>\n     * </ol>\n     *\n     * <p>\n     * The prediction context must be considered by this filter to address\n     * situations like the following.\n     * </p>\n     * <code>\n     * <pre>\n     * grammar TA;\n     * prog: statement* EOF;\n     * statement: letterA | statement letterA 'b' ;\n     * letterA: 'a';\n     * </pre>\n     * </code>\n     * <p>\n     * If the above grammar, the ATN state immediately before the token\n     * reference {@code 'a'} in {@code letterA} is reachable from the left edge\n     * of both the primary and closure blocks of the left-recursive rule\n     * {@code statement}. The prediction context associated with each of these\n     * configurations distinguishes between them, and prevents the alternative\n     * which stepped out to {@code prog} (and then back in to {@code statement}\n     * from being eliminated by the filter.\n     * </p>\n     *\n     * @param configs The configuration set computed by\n     * {@link #computeStartState} as the start state for the DFA.\n     * @return The transformed configuration set representing the start state\n     * for a precedence DFA at a particular precedence level (determined by\n     * calling {@link Parser#getPrecedence}).\n     */\n    std::unique_ptr<ATNConfigSet> applyPrecedenceFilter(ATNConfigSet *configs);\n\n    virtual ATNState *getReachableTarget(const Transition *trans, size_t ttype);\n\n    virtual std::vector<Ref<const SemanticContext>> getPredsForAmbigAlts(const antlrcpp::BitSet &ambigAlts,\n                                                                   ATNConfigSet *configs, size_t nalts);\n\n    std::vector<dfa::DFAState::PredPrediction> getPredicatePredictions(const antlrcpp::BitSet &ambigAlts,\n                                                                       const std::vector<Ref<const SemanticContext>> &altToPred);\n\n    /**\n     * This method is used to improve the localization of error messages by\n     * choosing an alternative rather than throwing a\n     * {@link NoViableAltException} in particular prediction scenarios where the\n     * {@link #ERROR} state was reached during ATN simulation.\n     *\n     * <p>\n     * The default implementation of this method uses the following\n     * algorithm to identify an ATN configuration which successfully parsed the\n     * decision entry rule. Choosing such an alternative ensures that the\n     * {@link ParserRuleContext} returned by the calling rule will be complete\n     * and valid, and the syntax error will be reported later at a more\n     * localized location.</p>\n     *\n     * <ul>\n     * <li>If a syntactically valid path or paths reach the end of the decision rule and\n     * they are semantically valid if predicated, return the min associated alt.</li>\n     * <li>Else, if a semantically invalid but syntactically valid path exist\n     * or paths exist, return the minimum associated alt.\n     * </li>\n     * <li>Otherwise, return {@link ATN#INVALID_ALT_NUMBER}.</li>\n     * </ul>\n     *\n     * <p>\n     * In some scenarios, the algorithm described above could predict an\n     * alternative which will result in a {@link FailedPredicateException} in\n     * the parser. Specifically, this could occur if the <em>only</em> configuration\n     * capable of successfully parsing to the end of the decision rule is\n     * blocked by a semantic predicate. By choosing this alternative within\n     * {@link #adaptivePredict} instead of throwing a\n     * {@link NoViableAltException}, the resulting\n     * {@link FailedPredicateException} in the parser will identify the specific\n     * predicate which is preventing the parser from successfully parsing the\n     * decision rule, which helps developers identify and correct logic errors\n     * in semantic predicates.\n     * </p>\n     *\n     * @param configs The ATN configurations which were valid immediately before\n     * the {@link #ERROR} state was reached\n     * @param outerContext The is the \\gamma_0 initial parser context from the paper\n     * or the parser stack at the instant before prediction commences.\n     *\n     * @return The value to return from {@link #adaptivePredict}, or\n     * {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not\n     * identified and {@link #adaptivePredict} should report an error instead.\n     */\n    size_t getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(ATNConfigSet *configs,\n                                                                   ParserRuleContext *outerContext);\n\n    virtual size_t getAltThatFinishedDecisionEntryRule(ATNConfigSet *configs);\n\n    /** Walk the list of configurations and split them according to\n     *  those that have preds evaluating to true/false.  If no pred, assume\n     *  true pred and include in succeeded set.  Returns Pair of sets.\n     *\n     *  Create a new set so as not to alter the incoming parameter.\n     *\n     *  Assumption: the input stream has been restored to the starting point\n     *  prediction, which is where predicates need to evaluate.\n     */\n    std::pair<ATNConfigSet *, ATNConfigSet *> splitAccordingToSemanticValidity(ATNConfigSet *configs,\n                                                                               ParserRuleContext *outerContext);\n\n    /// <summary>\n    /// Look through a list of predicate/alt pairs, returning alts for the\n    ///  pairs that win. A {@code NONE} predicate indicates an alt containing an\n    ///  unpredicated config which behaves as \"always true.\" If !complete\n    ///  then we stop at the first predicate that evaluates to true. This\n    ///  includes pairs with null predicates.\n    /// </summary>\n    antlrcpp::BitSet evalSemanticContext(const std::vector<dfa::DFAState::PredPrediction> &predPredictions,\n                                         ParserRuleContext *outerContext, bool complete);\n\n    /**\n     * Evaluate a semantic context within a specific parser context.\n     *\n     * <p>\n     * This method might not be called for every semantic context evaluated\n     * during the prediction process. In particular, we currently do not\n     * evaluate the following but it may change in the future:</p>\n     *\n     * <ul>\n     * <li>Precedence predicates (represented by\n     * {@link SemanticContext.PrecedencePredicate}) are not currently evaluated\n     * through this method.</li>\n     * <li>Operator predicates (represented by {@link SemanticContext.AND} and\n     * {@link SemanticContext.OR}) are evaluated as a single semantic\n     * context, rather than evaluating the operands individually.\n     * Implementations which require evaluation results from individual\n     * predicates should override this method to explicitly handle evaluation of\n     * the operands within operator predicates.</li>\n     * </ul>\n     *\n     * @param pred The semantic context to evaluate\n     * @param parserCallStack The parser context in which to evaluate the\n     * semantic context\n     * @param alt The alternative which is guarded by {@code pred}\n     * @param fullCtx {@code true} if the evaluation is occurring during LL\n     * prediction; otherwise, {@code false} if the evaluation is occurring\n     * during SLL prediction\n     *\n     * @since 4.3\n     */\n    virtual bool evalSemanticContext(Ref<const SemanticContext> const& pred, ParserRuleContext *parserCallStack,\n                                     size_t alt, bool fullCtx);\n\n    /* TODO: If we are doing predicates, there is no point in pursuing\n     closure operations if we reach a DFA state that uniquely predicts\n     alternative. We will not be caching that DFA state and it is a\n     waste to pursue the closure. Might have to advance when we do\n     ambig detection thought :(\n     */\n    virtual void closure(Ref<ATNConfig> const& config, ATNConfigSet *configs, ATNConfig::Set &closureBusy,\n                         bool collectPredicates, bool fullCtx, bool treatEofAsEpsilon);\n\n    virtual void closureCheckingStopState(Ref<ATNConfig> const& config, ATNConfigSet *configs, ATNConfig::Set &closureBusy,\n                                          bool collectPredicates, bool fullCtx, int depth, bool treatEofAsEpsilon);\n\n    /// Do the actual work of walking epsilon edges.\n    virtual void closure_(Ref<ATNConfig> const& config, ATNConfigSet *configs, ATNConfig::Set &closureBusy,\n                          bool collectPredicates, bool fullCtx, int depth, bool treatEofAsEpsilon);\n\n    virtual Ref<ATNConfig> getEpsilonTarget(Ref<ATNConfig> const& config, const Transition *t, bool collectPredicates,\n                                            bool inContext, bool fullCtx, bool treatEofAsEpsilon);\n    virtual Ref<ATNConfig> actionTransition(Ref<ATNConfig> const& config, const ActionTransition *t);\n\n    virtual Ref<ATNConfig> predTransition(Ref<ATNConfig> const& config, const PredicateTransition *pt, bool collectPredicates,\n                                          bool inContext, bool fullCtx);\n\n    virtual Ref<ATNConfig> ruleTransition(Ref<ATNConfig> const& config, const RuleTransition *t);\n\n    /**\n     * Gets a {@link BitSet} containing the alternatives in {@code configs}\n     * which are part of one or more conflicting alternative subsets.\n     *\n     * @param configs The {@link ATNConfigSet} to analyze.\n     * @return The alternatives in {@code configs} which are part of one or more\n     * conflicting alternative subsets. If {@code configs} does not contain any\n     * conflicting subsets, this method returns an empty {@link BitSet}.\n     */\n    virtual antlrcpp::BitSet getConflictingAlts(ATNConfigSet *configs);\n\n    /// <summary>\n    /// Sam pointed out a problem with the previous definition, v3, of\n    /// ambiguous states. If we have another state associated with conflicting\n    /// alternatives, we should keep going. For example, the following grammar\n    ///\n    /// s : (ID | ID ID?) ';' ;\n    ///\n    /// When the ATN simulation reaches the state before ';', it has a DFA\n    /// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally\n    /// 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node\n    /// because alternative to has another way to continue, via [6|2|[]].\n    /// The key is that we have a single state that has config's only associated\n    /// with a single alternative, 2, and crucially the state transitions\n    /// among the configurations are all non-epsilon transitions. That means\n    /// we don't consider any conflicts that include alternative 2. So, we\n    /// ignore the conflict between alts 1 and 2. We ignore a set of\n    /// conflicting alts when there is an intersection with an alternative\n    /// associated with a single alt state in the state->config-list map.\n    ///\n    /// It's also the case that we might have two conflicting configurations but\n    /// also a 3rd nonconflicting configuration for a different alternative:\n    /// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:\n    ///\n    /// a : A | A | A B ;\n    ///\n    /// After matching input A, we reach the stop state for rule A, state 1.\n    /// State 8 is the state right before B. Clearly alternatives 1 and 2\n    /// conflict and no amount of further lookahead will separate the two.\n    /// However, alternative 3 will be able to continue and so we do not\n    /// stop working on this state. In the previous example, we're concerned\n    /// with states associated with the conflicting alternatives. Here alt\n    /// 3 is not associated with the conflicting configs, but since we can continue\n    /// looking for input reasonably, I don't declare the state done. We\n    /// ignore a set of conflicting alts when we have an alternative\n    /// that we still need to pursue.\n    /// </summary>\n\n    virtual antlrcpp::BitSet getConflictingAltsOrUniqueAlt(ATNConfigSet *configs);\n\n    virtual NoViableAltException noViableAlt(TokenStream *input, ParserRuleContext *outerContext,\n                                              ATNConfigSet *configs, size_t startIndex, bool deleteConfigs);\n\n    static size_t getUniqueAlt(ATNConfigSet *configs);\n\n    /// <summary>\n    /// Add an edge to the DFA, if possible. This method calls\n    /// <seealso cref=\"#addDFAState\"/> to ensure the {@code to} state is present in the\n    /// DFA. If {@code from} is {@code null}, or if {@code t} is outside the\n    /// range of edges that can be represented in the DFA tables, this method\n    /// returns without adding the edge to the DFA.\n    /// <p/>\n    /// If {@code to} is {@code null}, this method returns {@code null}.\n    /// Otherwise, this method returns the <seealso cref=\"DFAState\"/> returned by calling\n    /// <seealso cref=\"#addDFAState\"/> for the {@code to} state.\n    /// </summary>\n    /// <param name=\"dfa\"> The DFA </param>\n    /// <param name=\"from\"> The source state for the edge </param>\n    /// <param name=\"t\"> The input symbol </param>\n    /// <param name=\"to\"> The target state for the edge\n    /// </param>\n    /// <returns> If {@code to} is {@code null}, this method returns {@code null};\n    /// otherwise this method returns the result of calling <seealso cref=\"#addDFAState\"/>\n    /// on {@code to} </returns>\n    virtual dfa::DFAState *addDFAEdge(dfa::DFA &dfa, dfa::DFAState *from, ssize_t t, dfa::DFAState *to);\n\n    /// <summary>\n    /// Add state {@code D} to the DFA if it is not already present, and return\n    /// the actual instance stored in the DFA. If a state equivalent to {@code D}\n    /// is already in the DFA, the existing state is returned. Otherwise this\n    /// method returns {@code D} after adding it to the DFA.\n    /// <p/>\n    /// If {@code D} is <seealso cref=\"#ERROR\"/>, this method returns <seealso cref=\"#ERROR\"/> and\n    /// does not change the DFA.\n    /// </summary>\n    /// <param name=\"dfa\"> The dfa </param>\n    /// <param name=\"D\"> The DFA state to add </param>\n    /// <returns> The state stored in the DFA. This will be either the existing\n    /// state if {@code D} is already in the DFA, or {@code D} itself if the\n    /// state was not already present. </returns>\n    virtual dfa::DFAState *addDFAState(dfa::DFA &dfa, dfa::DFAState *D);\n\n    virtual void reportAttemptingFullContext(dfa::DFA &dfa, const antlrcpp::BitSet &conflictingAlts,\n      ATNConfigSet *configs, size_t startIndex, size_t stopIndex);\n\n    virtual void reportContextSensitivity(dfa::DFA &dfa, size_t prediction, ATNConfigSet *configs,\n                                          size_t startIndex, size_t stopIndex);\n\n    /// If context sensitive parsing, we know it's ambiguity not conflict.\n    virtual void reportAmbiguity(dfa::DFA &dfa,\n                                 dfa::DFAState *D, // the DFA state from execATN() that had SLL conflicts\n                                 size_t startIndex, size_t stopIndex,\n                                 bool exact,\n                                 const antlrcpp::BitSet &ambigAlts,\n                                 ATNConfigSet *configs); // configs that LL not SLL considered conflicting\n\n  private:\n    // SLL, LL, or LL + exact ambig detection?\n    PredictionMode _mode;\n\n    static bool getLrLoopSetting();\n    void InitializeInstanceFields();\n  };\n\n} // namespace atn\n} // namespace antlr4\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ParserATNSimulatorOptions.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include <utility>\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContextMergeCacheOptions.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC ParserATNSimulatorOptions final {\n  public:\n    ParserATNSimulatorOptions& setPredictionContextMergeCacheOptions(\n        PredictionContextMergeCacheOptions predictionContextMergeCacheOptions) {\n      _predictionContextMergeCacheOptions = std::move(predictionContextMergeCacheOptions);\n      return *this;\n    }\n\n    const PredictionContextMergeCacheOptions& getPredictionContextMergeCacheOptions() const {\n      return _predictionContextMergeCacheOptions;\n    }\n\n  private:\n    PredictionContextMergeCacheOptions _predictionContextMergeCacheOptions;\n  };\n\n}  // namespace atn\n}  // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PlusBlockStartState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/BlockStartState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Start of {@code (A|B|...)+} loop. Technically a decision state, but\n  /// we don't use for code generation; somebody might need it, so I'm defining\n  /// it for completeness. In reality, the <seealso cref=\"PlusLoopbackState\"/> node is the\n  /// real decision-making note for {@code A+}.\n  class ANTLR4CPP_PUBLIC PlusBlockStartState final : public BlockStartState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::PLUS_BLOCK_START; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    PlusLoopbackState *loopBackState = nullptr;\n\n    PlusBlockStartState() : BlockStartState(ATNStateType::PLUS_BLOCK_START) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PlusLoopbackState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/DecisionState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// Decision state for {@code A+} and {@code (A|B)+}. It has two transitions:\n  /// one to the loop back to start of the block and one to exit.\n  class ANTLR4CPP_PUBLIC PlusLoopbackState final : public DecisionState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::PLUS_LOOP_BACK; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    PlusLoopbackState() : DecisionState(ATNStateType::PLUS_LOOP_BACK) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PrecedencePredicateTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"atn/ATNState.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/PrecedencePredicateTransition.h\"\n\nusing namespace antlr4::atn;\n\nPrecedencePredicateTransition::PrecedencePredicateTransition(ATNState *target, int precedence)\n  : Transition(TransitionType::PRECEDENCE, target), _predicate(std::make_shared<SemanticContext::PrecedencePredicate>(precedence)) {}\n\nbool PrecedencePredicateTransition::isEpsilon() const {\n  return true;\n}\n\nbool PrecedencePredicateTransition::matches(size_t /*symbol*/, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return false;\n}\n\nstd::string PrecedencePredicateTransition::toString() const {\n  return \"PRECEDENCE \" + Transition::toString() + \" { precedence: \" + std::to_string(getPrecedence()) + \" }\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PrecedencePredicateTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"atn/Transition.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/SemanticContext.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC PrecedencePredicateTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::PRECEDENCE; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    PrecedencePredicateTransition(ATNState *target, int precedence);\n\n    int getPrecedence() const { return _predicate->precedence; }\n\n    bool isEpsilon() const override;\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n    std::string toString() const override;\n\n    const Ref<const SemanticContext::PrecedencePredicate>& getPredicate() const { return _predicate; }\n\n  private:\n    const std::shared_ptr<const SemanticContext::PrecedencePredicate> _predicate;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredicateEvalInfo.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <cstddef>\n#include \"SemanticContext.h\"\n\n#include \"antlr4-common.h\"\n#include \"atn/PredicateEvalInfo.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nPredicateEvalInfo::PredicateEvalInfo(size_t decision, TokenStream *input, size_t startIndex, size_t stopIndex,\n  Ref<const SemanticContext> semctx, bool evalResult, size_t predictedAlt, bool fullCtx)\n  : DecisionEventInfo(decision, nullptr, input, startIndex, stopIndex, fullCtx),\n    semctx(std::move(semctx)), predictedAlt(predictedAlt), evalResult(evalResult) {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredicateEvalInfo.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/DecisionEventInfo.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// This class represents profiling event information for semantic predicate\n  /// evaluations which occur during prediction.\n  /// </summary>\n  /// <seealso cref= ParserATNSimulator#evalSemanticContext\n  ///\n  /// @since 4.3 </seealso>\n  class ANTLR4CPP_PUBLIC PredicateEvalInfo : public DecisionEventInfo {\n  public:\n    /// The semantic context which was evaluated.\n    const Ref<const SemanticContext> semctx;\n\n    /// <summary>\n    /// The alternative number for the decision which is guarded by the semantic\n    /// context <seealso cref=\"#semctx\"/>. Note that other ATN\n    /// configurations may predict the same alternative which are guarded by\n    /// other semantic contexts and/or <seealso cref=\"SemanticContext#NONE\"/>.\n    /// </summary>\n    const size_t predictedAlt;\n\n    /// The result of evaluating the semantic context <seealso cref=\"#semctx\"/>.\n    const bool evalResult;\n\n    /// <summary>\n    /// Constructs a new instance of the <seealso cref=\"PredicateEvalInfo\"/> class with the\n    /// specified detailed predicate evaluation information.\n    /// </summary>\n    /// <param name=\"decision\"> The decision number </param>\n    /// <param name=\"input\"> The input token stream </param>\n    /// <param name=\"startIndex\"> The start index for the current prediction </param>\n    /// <param name=\"stopIndex\"> The index at which the predicate evaluation was\n    /// triggered. Note that the input stream may be reset to other positions for\n    /// the actual evaluation of individual predicates. </param>\n    /// <param name=\"semctx\"> The semantic context which was evaluated </param>\n    /// <param name=\"evalResult\"> The results of evaluating the semantic context </param>\n    /// <param name=\"predictedAlt\"> The alternative number for the decision which is\n    /// guarded by the semantic context {@code semctx}. See <seealso cref=\"#predictedAlt\"/>\n    /// for more information. </param>\n    /// <param name=\"fullCtx\"> {@code true} if the semantic context was\n    /// evaluated during LL prediction; otherwise, {@code false} if the semantic\n    /// context was evaluated during SLL prediction\n    /// </param>\n    /// <seealso cref= ParserATNSimulator#evalSemanticContext(SemanticContext, ParserRuleContext, int, boolean) </seealso>\n    /// <seealso cref= SemanticContext#eval(Recognizer, RuleContext) </seealso>\n    PredicateEvalInfo(size_t decision, TokenStream *input, size_t startIndex, size_t stopIndex,\n                      Ref<const SemanticContext> semctx, bool evalResult, size_t predictedAlt, bool fullCtx);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredicateTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"atn/ATNState.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/PredicateTransition.h\"\n\nusing namespace antlr4::atn;\n\nPredicateTransition::PredicateTransition(ATNState *target, size_t ruleIndex, size_t predIndex, bool isCtxDependent)\n    : Transition(TransitionType::PREDICATE, target), _predicate(std::make_shared<SemanticContext::Predicate>(ruleIndex, predIndex, isCtxDependent)) {}\n\nbool PredicateTransition::isEpsilon() const {\n  return true;\n}\n\nbool PredicateTransition::matches(size_t /*symbol*/, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return false;\n}\n\nstd::string PredicateTransition::toString() const {\n  return \"PREDICATE \" + Transition::toString() + \" { ruleIndex: \" + std::to_string(getRuleIndex()) +\n    \", predIndex: \" + std::to_string(getPredIndex()) + \", isCtxDependent: \" + std::to_string(isCtxDependent()) + \" }\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredicateTransition.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"atn/Transition.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/SemanticContext.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// TODO: this is old comment:\n  ///  A tree of semantic predicates from the grammar AST if label==SEMPRED.\n  ///  In the ATN, labels will always be exactly one predicate, but the DFA\n  ///  may have to combine a bunch of them as it collects predicates from\n  ///  multiple ATN configurations into a single DFA state.\n  class ANTLR4CPP_PUBLIC PredicateTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::PREDICATE; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    PredicateTransition(ATNState *target, size_t ruleIndex, size_t predIndex, bool isCtxDependent);\n\n    size_t getRuleIndex() const {\n      return _predicate->ruleIndex;\n    }\n\n    size_t getPredIndex() const {\n      return _predicate->predIndex;\n    }\n\n    bool isCtxDependent() const {\n      return _predicate->isCtxDependent;\n    }\n\n    bool isEpsilon() const override;\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n    std::string toString() const override;\n\n    const Ref<const SemanticContext::Predicate>& getPredicate() const { return _predicate; }\n\n  private:\n    const std::shared_ptr<const SemanticContext::Predicate> _predicate;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContext.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <unordered_set>\n#include <unordered_map>\n#include <sstream>\n#include <cassert>\n#include <limits>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"atn/SingletonPredictionContext.h\"\n#include \"antlr4-common.h\"\n#include \"misc/MurmurHash.h\"\n#include \"atn/ArrayPredictionContext.h\"\n#include \"atn/PredictionContextCache.h\"\n#include \"atn/PredictionContextMergeCache.h\"\n#include \"RuleContext.h\"\n#include \"ParserRuleContext.h\"\n#include \"atn/RuleTransition.h\"\n#include \"support/Arrays.h\"\n#include \"support/CPPUtils.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/PredictionContext.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::misc;\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nnamespace {\n\n  void combineCommonParents(std::vector<Ref<const PredictionContext>> &parents) {\n    std::unordered_set<Ref<const PredictionContext>> uniqueParents;\n    uniqueParents.reserve(parents.size());\n    for (const auto &parent : parents) {\n      uniqueParents.insert(parent);\n    }\n    for (auto &parent : parents) {\n      parent = *uniqueParents.find(parent);\n    }\n  }\n\n  Ref<const PredictionContext> getCachedContextImpl(const Ref<const PredictionContext> &context,\n                                                    PredictionContextCache &contextCache,\n                                                    std::unordered_map<Ref<const PredictionContext>,\n                                                    Ref<const PredictionContext>> &visited) {\n    if (context->isEmpty()) {\n      return context;\n    }\n\n    {\n      auto iterator = visited.find(context);\n      if (iterator != visited.end()) {\n        return iterator->second; // Not necessarly the same as context.\n      }\n    }\n\n    auto cached = contextCache.get(context);\n    if (cached) {\n      visited[context] = cached;\n      return cached;\n    }\n\n    bool changed = false;\n\n    std::vector<Ref<const PredictionContext>> parents(context->size());\n    for (size_t i = 0; i < parents.size(); i++) {\n      auto parent = getCachedContextImpl(context->getParent(i), contextCache, visited);\n      if (changed || parent != context->getParent(i)) {\n        if (!changed) {\n          parents.clear();\n          for (size_t j = 0; j < context->size(); j++) {\n            parents.push_back(context->getParent(j));\n          }\n\n          changed = true;\n        }\n\n        parents[i] = std::move(parent);\n      }\n    }\n\n    if (!changed) {\n      visited[context] = context;\n      contextCache.put(context);\n      return context;\n    }\n\n    Ref<const PredictionContext> updated;\n    if (parents.empty()) {\n      updated = PredictionContext::EMPTY;\n    } else if (parents.size() == 1) {\n      updated = SingletonPredictionContext::create(std::move(parents[0]), context->getReturnState(0));\n      contextCache.put(updated);\n    } else {\n      updated = std::make_shared<ArrayPredictionContext>(std::move(parents), downCast<const ArrayPredictionContext*>(context.get())->returnStates);\n      contextCache.put(updated);\n    }\n\n    visited[updated] = updated;\n    visited[context] = updated;\n\n    return updated;\n  }\n\n  void getAllContextNodesImpl(const Ref<const PredictionContext> &context,\n                              std::vector<Ref<const PredictionContext>> &nodes,\n                              std::unordered_set<const PredictionContext*> &visited) {\n\n    if (visited.find(context.get()) != visited.end()) {\n      return; // Already done.\n    }\n\n    visited.insert(context.get());\n    nodes.push_back(context);\n\n    for (size_t i = 0; i < context->size(); i++) {\n      getAllContextNodesImpl(context->getParent(i), nodes, visited);\n    }\n  }\n\n  size_t insertOrAssignNodeId(std::unordered_map<const PredictionContext*, size_t> &nodeIds, size_t &nodeId, const PredictionContext *node) {\n    auto existing = nodeIds.find(node);\n    if (existing != nodeIds.end()) {\n      return existing->second;\n    }\n    return nodeIds.insert({node, nodeId++}).first->second;\n  }\n\n}\n\nconst Ref<const PredictionContext> PredictionContext::EMPTY = std::make_shared<SingletonPredictionContext>(nullptr, PredictionContext::EMPTY_RETURN_STATE);\n\n//----------------- PredictionContext ----------------------------------------------------------------------------------\n\nPredictionContext::PredictionContext(PredictionContextType contextType) : _contextType(contextType), _hashCode(0) {}\n\nPredictionContext::PredictionContext(PredictionContext&& other) : _contextType(other._contextType), _hashCode(other._hashCode.exchange(0, std::memory_order_relaxed)) {}\n\nRef<const PredictionContext> PredictionContext::fromRuleContext(const ATN &atn, RuleContext *outerContext) {\n  if (outerContext == nullptr) {\n    return PredictionContext::EMPTY;\n  }\n\n  // if we are in RuleContext of start rule, s, then PredictionContext\n  // is EMPTY. Nobody called us. (if we are empty, return empty)\n  if (outerContext->parent == nullptr || outerContext == &ParserRuleContext::EMPTY) {\n    return PredictionContext::EMPTY;\n  }\n\n  // If we have a parent, convert it to a PredictionContext graph\n  auto parent = PredictionContext::fromRuleContext(atn, RuleContext::is(outerContext->parent) ? downCast<RuleContext*>(outerContext->parent) : nullptr);\n  const auto *transition = downCast<const RuleTransition*>(atn.states[outerContext->invokingState]->transitions[0].get());\n  return SingletonPredictionContext::create(std::move(parent), transition->followState->stateNumber);\n}\n\nbool PredictionContext::hasEmptyPath() const {\n  // since EMPTY_RETURN_STATE can only appear in the last position, we check last one\n  return getReturnState(size() - 1) == EMPTY_RETURN_STATE;\n}\n\nsize_t PredictionContext::hashCode() const {\n  auto hash = cachedHashCode();\n  if (hash == 0) {\n    hash = hashCodeImpl();\n    if (hash == 0) {\n      hash = std::numeric_limits<size_t>::max();\n    }\n    _hashCode.store(hash, std::memory_order_relaxed);\n  }\n  return hash;\n}\n\nRef<const PredictionContext> PredictionContext::merge(Ref<const PredictionContext> a, Ref<const PredictionContext> b,\n                                                      bool rootIsWildcard, PredictionContextMergeCache *mergeCache) {\n  assert(a && b);\n\n  // share same graph if both same\n  if (a == b || *a == *b) {\n    return a;\n  }\n\n  const auto aType = a->getContextType();\n  const auto bType = b->getContextType();\n\n  if (aType == PredictionContextType::SINGLETON && bType == PredictionContextType::SINGLETON) {\n    return mergeSingletons(std::static_pointer_cast<const SingletonPredictionContext>(std::move(a)),\n                           std::static_pointer_cast<const SingletonPredictionContext>(std::move(b)), rootIsWildcard, mergeCache);\n  }\n\n  // At least one of a or b is array.\n  // If one is $ and rootIsWildcard, return $ as * wildcard.\n  if (rootIsWildcard) {\n    if (a == PredictionContext::EMPTY) {\n      return a;\n    }\n    if (b == PredictionContext::EMPTY) {\n      return b;\n    }\n  }\n\n  // convert singleton so both are arrays to normalize\n  Ref<const ArrayPredictionContext> left;\n  if (aType == PredictionContextType::SINGLETON) {\n    left = std::make_shared<ArrayPredictionContext>(downCast<const SingletonPredictionContext&>(*a));\n  } else {\n    left = std::static_pointer_cast<const ArrayPredictionContext>(std::move(a));\n  }\n  Ref<const ArrayPredictionContext> right;\n  if (bType == PredictionContextType::SINGLETON) {\n    right = std::make_shared<ArrayPredictionContext>(downCast<const SingletonPredictionContext&>(*b));\n  } else {\n    right = std::static_pointer_cast<const ArrayPredictionContext>(std::move(b));\n  }\n  return mergeArrays(std::move(left), std::move(right), rootIsWildcard, mergeCache);\n}\n\nRef<const PredictionContext> PredictionContext::mergeSingletons(Ref<const SingletonPredictionContext> a, Ref<const SingletonPredictionContext> b,\n                                                                bool rootIsWildcard, PredictionContextMergeCache *mergeCache) {\n\n  if (mergeCache) {\n    auto existing = mergeCache->get(a, b);\n    if (existing) {\n      return existing;\n    }\n    existing = mergeCache->get(b, a);\n    if (existing) {\n      return existing;\n    }\n  }\n\n  auto rootMerge = mergeRoot(a, b, rootIsWildcard);\n  if (rootMerge) {\n    if (mergeCache) {\n      return mergeCache->put(a, b, std::move(rootMerge));\n    }\n    return rootMerge;\n  }\n\n  const auto& parentA = a->parent;\n  const auto& parentB = b->parent;\n  if (a->returnState == b->returnState) { // a == b\n    auto parent = merge(parentA, parentB, rootIsWildcard, mergeCache);\n\n    // If parent is same as existing a or b parent or reduced to a parent, return it.\n    if (parent == parentA) { // ax + bx = ax, if a=b\n      return a;\n    }\n    if (parent == parentB) { // ax + bx = bx, if a=b\n      return b;\n    }\n\n    // else: ax + ay = a'[x,y]\n    // merge parents x and y, giving array node with x,y then remainders\n    // of those graphs.  dup a, a' points at merged array\n    // new joined parent so create new singleton pointing to it, a'\n    auto c = SingletonPredictionContext::create(std::move(parent), a->returnState);\n    if (mergeCache) {\n      return mergeCache->put(a, b, std::move(c));\n    }\n    return c;\n  }\n  // a != b payloads differ\n  // see if we can collapse parents due to $+x parents if local ctx\n  Ref<const PredictionContext> singleParent;\n  if (a == b || (*parentA == *parentB)) { // ax + bx = [a,b]x\n    singleParent = parentA;\n  }\n  if (singleParent) { // parents are same, sort payloads and use same parent\n    std::vector<size_t> payloads = { a->returnState, b->returnState };\n    if (a->returnState > b->returnState) {\n      payloads[0] = b->returnState;\n      payloads[1] = a->returnState;\n    }\n    std::vector<Ref<const PredictionContext>> parents = { singleParent, singleParent };\n    auto c = std::make_shared<ArrayPredictionContext>(std::move(parents), std::move(payloads));\n    if (mergeCache) {\n      return mergeCache->put(a, b, std::move(c));\n    }\n    return c;\n  }\n\n  // parents differ and can't merge them. Just pack together\n  // into array; can't merge.\n  // ax + by = [ax,by]\n  if (a->returnState > b->returnState) { // sort by payload\n    std::vector<size_t> payloads = { b->returnState, a->returnState };\n    std::vector<Ref<const PredictionContext>> parents = { b->parent, a->parent };\n    auto c = std::make_shared<ArrayPredictionContext>(std::move(parents), std::move(payloads));\n    if (mergeCache) {\n      return mergeCache->put(a, b, std::move(c));\n    }\n    return c;\n  }\n  std::vector<size_t> payloads = {a->returnState, b->returnState};\n  std::vector<Ref<const PredictionContext>> parents = { a->parent, b->parent };\n  auto c = std::make_shared<ArrayPredictionContext>(std::move(parents), std::move(payloads));\n  if (mergeCache) {\n    return mergeCache->put(a, b, std::move(c));\n  }\n  return c;\n}\n\nRef<const PredictionContext> PredictionContext::mergeRoot(Ref<const SingletonPredictionContext> a, Ref<const SingletonPredictionContext> b,\n                                                          bool rootIsWildcard) {\n  if (rootIsWildcard) {\n    if (a == EMPTY) { // * + b = *\n      return EMPTY;\n    }\n    if (b == EMPTY) { // a + * = *\n      return EMPTY;\n    }\n  } else {\n    if (a == EMPTY && b == EMPTY) { // $ + $ = $\n      return EMPTY;\n    }\n    if (a == EMPTY) { // $ + x = [$,x]\n      std::vector<size_t> payloads = { b->returnState, EMPTY_RETURN_STATE };\n      std::vector<Ref<const PredictionContext>> parents = { b->parent, nullptr };\n      return std::make_shared<ArrayPredictionContext>(std::move(parents), std::move(payloads));\n    }\n    if (b == EMPTY) { // x + $ = [$,x] ($ is always first if present)\n      std::vector<size_t> payloads = { a->returnState, EMPTY_RETURN_STATE };\n      std::vector<Ref<const PredictionContext>> parents = { a->parent, nullptr };\n      return std::make_shared<ArrayPredictionContext>(std::move(parents), std::move(payloads));\n    }\n  }\n  return nullptr;\n}\n\nRef<const PredictionContext> PredictionContext::mergeArrays(Ref<const ArrayPredictionContext> a, Ref<const ArrayPredictionContext> b,\n                                                            bool rootIsWildcard, PredictionContextMergeCache *mergeCache) {\n  if (mergeCache) {\n    auto existing = mergeCache->get(a, b);\n    if (existing) {\n#if TRACE_ATN_SIM == 1\n      std::cout << \"mergeArrays a=\" << a->toString() << \",b=\" << b->toString() << \" -> previous\" << std::endl;\n#endif\n      return existing;\n    }\n    existing = mergeCache->get(b, a);\n    if (existing) {\n#if TRACE_ATN_SIM == 1\n        std::cout << \"mergeArrays a=\" << a->toString() << \",b=\" << b->toString() << \" -> previous\" << std::endl;\n#endif\n      return existing;\n    }\n  }\n\n  // merge sorted payloads a + b => M\n  size_t i = 0; // walks a\n  size_t j = 0; // walks b\n  size_t k = 0; // walks target M array\n\n  std::vector<size_t> mergedReturnStates(a->returnStates.size() + b->returnStates.size());\n  std::vector<Ref<const PredictionContext>> mergedParents(a->returnStates.size() + b->returnStates.size());\n\n  // walk and merge to yield mergedParents, mergedReturnStates\n  while (i < a->returnStates.size() && j < b->returnStates.size()) {\n    const auto& parentA = a->parents[i];\n    const auto& parentB = b->parents[j];\n    if (a->returnStates[i] == b->returnStates[j]) {\n      // same payload (stack tops are equal), must yield merged singleton\n      size_t payload = a->returnStates[i];\n      // $+$ = $\n      bool both$ = payload == EMPTY_RETURN_STATE && !parentA && !parentB;\n      bool ax_ax = (parentA && parentB) && *parentA == *parentB; // ax+ax -> ax\n      if (both$ || ax_ax) {\n        mergedParents[k] = parentA; // choose left\n        mergedReturnStates[k] = payload;\n      } else { // ax+ay -> a'[x,y]\n        mergedParents[k] = merge(parentA, parentB, rootIsWildcard, mergeCache);\n        mergedReturnStates[k] = payload;\n      }\n      i++; // hop over left one as usual\n      j++; // but also skip one in right side since we merge\n    } else if (a->returnStates[i] < b->returnStates[j]) { // copy a[i] to M\n      mergedParents[k] = parentA;\n      mergedReturnStates[k] = a->returnStates[i];\n      i++;\n    } else { // b > a, copy b[j] to M\n      mergedParents[k] = parentB;\n      mergedReturnStates[k] = b->returnStates[j];\n      j++;\n    }\n    k++;\n  }\n\n  // copy over any payloads remaining in either array\n  if (i < a->returnStates.size()) {\n    for (auto p = i; p < a->returnStates.size(); p++) {\n      mergedParents[k] = a->parents[p];\n      mergedReturnStates[k] = a->returnStates[p];\n      k++;\n    }\n  } else {\n    for (auto p = j; p < b->returnStates.size(); p++) {\n      mergedParents[k] = b->parents[p];\n      mergedReturnStates[k] = b->returnStates[p];\n      k++;\n    }\n  }\n\n  // trim merged if we combined a few that had same stack tops\n  if (k < mergedParents.size()) { // write index < last position; trim\n    if (k == 1) { // for just one merged element, return singleton top\n      auto c = SingletonPredictionContext::create(std::move(mergedParents[0]), mergedReturnStates[0]);\n      if (mergeCache) {\n        return mergeCache->put(a, b, std::move(c));\n      }\n      return c;\n    }\n    mergedParents.resize(k);\n    mergedReturnStates.resize(k);\n  }\n\n  ArrayPredictionContext m(std::move(mergedParents), std::move(mergedReturnStates));\n\n  // if we created same array as a or b, return that instead\n  // TODO: track whether this is possible above during merge sort for speed\n  if (m == *a) {\n    if (mergeCache) {\n#if TRACE_ATN_SIM == 1\n      std::cout << \"mergeArrays a=\" << a->toString() << \",b=\" << b->toString() << \" -> a\" << std::endl;\n#endif\n      return mergeCache->put(a, b, a);\n    }\n#if TRACE_ATN_SIM == 1\n    std::cout << \"mergeArrays a=\" << a->toString() << \",b=\" << b->toString() << \" -> a\" << std::endl;\n#endif\n    return a;\n  }\n  if (m == *b) {\n    if (mergeCache) {\n#if TRACE_ATN_SIM == 1\n        std::cout << \"mergeArrays a=\" << a->toString() << \",b=\" << b->toString() << \" -> b\" << std::endl;\n#endif\n      return mergeCache->put(a, b, b);\n    }\n#if TRACE_ATN_SIM == 1\n      std::cout << \"mergeArrays a=\" << a->toString() << \",b=\" << b->toString() << \" -> b\" << std::endl;\n#endif\n    return b;\n  }\n\n  combineCommonParents(m.parents);\n  auto c = std::make_shared<ArrayPredictionContext>(std::move(m));\n\n#if TRACE_ATN_SIM == 1\n    std::cout << \"mergeArrays a=\" << a->toString() << \",b=\" << b->toString() << \" -> \" << c->toString() << std::endl;\n#endif\n\n  if (mergeCache) {\n    return mergeCache->put(a, b, std::move(c));\n  }\n  return c;\n}\n\nstd::string PredictionContext::toDOTString(const Ref<const PredictionContext> &context) {\n  if (context == nullptr) {\n    return \"\";\n  }\n\n  std::stringstream ss;\n  ss << \"digraph G {\\n\" << \"rankdir=LR;\\n\";\n\n  std::vector<Ref<const PredictionContext>> nodes = getAllContextNodes(context);\n  std::unordered_map<const PredictionContext*, size_t> nodeIds;\n  size_t nodeId = 0;\n\n  for (const auto &current : nodes) {\n    if (current->getContextType() == PredictionContextType::SINGLETON) {\n      std::string s = std::to_string(insertOrAssignNodeId(nodeIds, nodeId, current.get()));\n      ss << \"  s\" << s;\n      std::string returnState = std::to_string(current->getReturnState(0));\n      if (current == PredictionContext::EMPTY) {\n        returnState = \"$\";\n      }\n      ss << \" [label=\\\"\" << returnState << \"\\\"];\\n\";\n      continue;\n    }\n    Ref<const ArrayPredictionContext> arr = std::static_pointer_cast<const ArrayPredictionContext>(current);\n    ss << \"  s\" << insertOrAssignNodeId(nodeIds, nodeId, arr.get()) << \" [shape=box, label=\\\"\" << \"[\";\n    bool first = true;\n    for (auto inv : arr->returnStates) {\n      if (!first) {\n       ss << \", \";\n      }\n      if (inv == EMPTY_RETURN_STATE) {\n        ss << \"$\";\n      } else {\n        ss << inv;\n      }\n      first = false;\n    }\n    ss << \"]\";\n    ss << \"\\\"];\\n\";\n  }\n\n  for (const auto &current : nodes) {\n    if (current == EMPTY) {\n      continue;\n    }\n    for (size_t i = 0; i < current->size(); i++) {\n      if (!current->getParent(i)) {\n        continue;\n      }\n      ss << \"  s\" << insertOrAssignNodeId(nodeIds, nodeId, current.get()) << \"->\" << \"s\" << insertOrAssignNodeId(nodeIds, nodeId, current->getParent(i).get());\n      if (current->size() > 1) {\n        ss << \" [label=\\\"parent[\" << i << \"]\\\"];\\n\";\n      } else {\n        ss << \";\\n\";\n      }\n    }\n  }\n\n  ss << \"}\\n\";\n  return ss.str();\n}\n\n// The \"visited\" map is just a temporary structure to control the retrieval process (which is recursive).\nRef<const PredictionContext> PredictionContext::getCachedContext(const Ref<const PredictionContext> &context,\n                                                                 PredictionContextCache &contextCache) {\n  std::unordered_map<Ref<const PredictionContext>, Ref<const PredictionContext>> visited;\n  return getCachedContextImpl(context, contextCache, visited);\n}\n\nstd::vector<Ref<const PredictionContext>> PredictionContext::getAllContextNodes(const Ref<const PredictionContext> &context) {\n  std::vector<Ref<const PredictionContext>> nodes;\n  std::unordered_set<const PredictionContext*> visited;\n  getAllContextNodesImpl(context, nodes, visited);\n  return nodes;\n}\n\nstd::vector<std::string> PredictionContext::toStrings(Recognizer *recognizer, int currentState) const {\n  return toStrings(recognizer, EMPTY, currentState);\n}\n\nstd::vector<std::string> PredictionContext::toStrings(Recognizer *recognizer, const Ref<const PredictionContext> &stop, int currentState) const {\n\n  std::vector<std::string> result;\n\n  for (size_t perm = 0; ; perm++) {\n    size_t offset = 0;\n    bool last = true;\n    const PredictionContext *p = this;\n    size_t stateNumber = currentState;\n\n    std::stringstream ss;\n    ss << \"[\";\n    bool outerContinue = false;\n    while (!p->isEmpty() && p != stop.get()) {\n      size_t index = 0;\n      if (p->size() > 0) {\n        size_t bits = 1;\n        while ((1ULL << bits) < p->size()) {\n          bits++;\n        }\n\n        size_t mask = (1 << bits) - 1;\n        index = (perm >> offset) & mask;\n        last &= index >= p->size() - 1;\n        if (index >= p->size()) {\n          outerContinue = true;\n          break;\n        }\n        offset += bits;\n      }\n\n      if (recognizer != nullptr) {\n        if (ss.tellp() > 1) {\n          // first char is '[', if more than that this isn't the first rule\n          ss << ' ';\n        }\n\n        const ATN &atn = recognizer->getATN();\n        ATNState *s = atn.states[stateNumber];\n        std::string ruleName = recognizer->getRuleNames()[s->ruleIndex];\n        ss << ruleName;\n      } else if (p->getReturnState(index) != EMPTY_RETURN_STATE) {\n        if (!p->isEmpty()) {\n          if (ss.tellp() > 1) {\n            // first char is '[', if more than that this isn't the first rule\n            ss << ' ';\n          }\n\n          ss << p->getReturnState(index);\n        }\n      }\n      stateNumber = p->getReturnState(index);\n      p = p->getParent(index).get();\n    }\n\n    if (outerContinue)\n      continue;\n\n    ss << \"]\";\n    result.push_back(ss.str());\n\n    if (last) {\n      break;\n    }\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContext.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <limits>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include <atomic>\n\n#include \"Recognizer.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATN.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/PredictionContextType.h\"\n\nnamespace antlr4 {\n\n  class RuleContext;\n\nnamespace atn {\n\n  class ATN;\n  class ArrayPredictionContext;\n  class SingletonPredictionContext;\n  class PredictionContextCache;\n  class PredictionContextMergeCache;\n\n  class ANTLR4CPP_PUBLIC PredictionContext {\n  public:\n    /// Represents $ in local context prediction, which means wildcard.\n    /// *+x = *.\n    static const Ref<const PredictionContext> EMPTY;\n\n    /// Represents $ in an array in full context mode, when $\n    /// doesn't mean wildcard: $ + x = [$,x]. Here,\n    /// $ = EMPTY_RETURN_STATE.\n    // ml: originally Integer.MAX_VALUE, which would be -1 for us, but this is already used in places where\n    //     -1 is converted to unsigned, so we use a different value here. Any value does the job provided it doesn't\n    //     conflict with real return states.\n    static constexpr size_t EMPTY_RETURN_STATE = std::numeric_limits<size_t>::max() - 9;\n\n    // dispatch\n    static Ref<const PredictionContext> merge(Ref<const PredictionContext> a,\n                                              Ref<const PredictionContext> b,\n                                              bool rootIsWildcard,\n                                              PredictionContextMergeCache *mergeCache);\n\n    /// <summary>\n    /// Merge two <seealso cref=\"SingletonPredictionContext\"/> instances.\n    ///\n    /// <p/>\n    ///\n    /// Stack tops equal, parents merge is same; return left graph.<br/>\n    /// <embed src=\"images/SingletonMerge_SameRootSamePar.svg\" type=\"image/svg+xml\"/>\n    ///\n    /// <p/>\n    ///\n    /// Same stack top, parents differ; merge parents giving array node, then\n    /// remainders of those graphs. A new root node is created to point to the\n    /// merged parents.<br/>\n    /// <embed src=\"images/SingletonMerge_SameRootDiffPar.svg\" type=\"image/svg+xml\"/>\n    ///\n    /// <p/>\n    ///\n    /// Different stack tops pointing to same parent. Make array node for the\n    /// root where both element in the root point to the same (original)\n    /// parent.<br/>\n    /// <embed src=\"images/SingletonMerge_DiffRootSamePar.svg\" type=\"image/svg+xml\"/>\n    ///\n    /// <p/>\n    ///\n    /// Different stack tops pointing to different parents. Make array node for\n    /// the root where each element points to the corresponding original\n    /// parent.<br/>\n    /// <embed src=\"images/SingletonMerge_DiffRootDiffPar.svg\" type=\"image/svg+xml\"/>\n    /// </summary>\n    /// <param name=\"a\"> the first <seealso cref=\"SingletonPredictionContext\"/> </param>\n    /// <param name=\"b\"> the second <seealso cref=\"SingletonPredictionContext\"/> </param>\n    /// <param name=\"rootIsWildcard\"> {@code true} if this is a local-context merge,\n    /// otherwise false to indicate a full-context merge </param>\n    /// <param name=\"mergeCache\"> </param>\n    static Ref<const PredictionContext> mergeSingletons(Ref<const SingletonPredictionContext> a,\n                                                        Ref<const SingletonPredictionContext> b,\n                                                        bool rootIsWildcard,\n                                                        PredictionContextMergeCache *mergeCache);\n\n    /**\n     * Handle case where at least one of {@code a} or {@code b} is\n     * {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used\n     * to represent {@link #EMPTY}.\n     *\n     * <h2>Local-Context Merges</h2>\n     *\n     * <p>These local-context merge operations are used when {@code rootIsWildcard}\n     * is true.</p>\n     *\n     * <p>{@link #EMPTY} is superset of any graph; return {@link #EMPTY}.<br>\n     * <embed src=\"images/LocalMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p>{@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is\n     * {@code #EMPTY}; return left graph.<br>\n     * <embed src=\"images/LocalMerge_EmptyParent.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p>Special case of last merge if local context.<br>\n     * <embed src=\"images/LocalMerge_DiffRoots.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <h2>Full-Context Merges</h2>\n     *\n     * <p>These full-context merge operations are used when {@code rootIsWildcard}\n     * is false.</p>\n     *\n     * <p><embed src=\"images/FullMerge_EmptyRoots.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p>Must keep all contexts; {@link #EMPTY} in array is a special value (and\n     * null parent).<br>\n     * <embed src=\"images/FullMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p><embed src=\"images/FullMerge_SameRoot.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * @param a the first {@link SingletonPredictionContext}\n     * @param b the second {@link SingletonPredictionContext}\n     * @param rootIsWildcard {@code true} if this is a local-context merge,\n     * otherwise false to indicate a full-context merge\n     */\n    static Ref<const PredictionContext> mergeRoot(Ref<const SingletonPredictionContext> a,\n                                                  Ref<const SingletonPredictionContext> b,\n                                                  bool rootIsWildcard);\n\n    /**\n     * Merge two {@link ArrayPredictionContext} instances.\n     *\n     * <p>Different tops, different parents.<br>\n     * <embed src=\"images/ArrayMerge_DiffTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p>Shared top, same parents.<br>\n     * <embed src=\"images/ArrayMerge_ShareTopSamePar.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p>Shared top, different parents.<br>\n     * <embed src=\"images/ArrayMerge_ShareTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p>Shared top, all shared parents.<br>\n     * <embed src=\"images/ArrayMerge_ShareTopSharePar.svg\" type=\"image/svg+xml\"/></p>\n     *\n     * <p>Equal tops, merge parents and reduce top to\n     * {@link SingletonPredictionContext}.<br>\n     * <embed src=\"images/ArrayMerge_EqualTop.svg\" type=\"image/svg+xml\"/></p>\n     */\n    static Ref<const PredictionContext> mergeArrays(Ref<const ArrayPredictionContext> a,\n                                                    Ref<const ArrayPredictionContext> b,\n                                                    bool rootIsWildcard,\n                                                    PredictionContextMergeCache *mergeCache);\n\n    static std::string toDOTString(const Ref<const PredictionContext> &context);\n\n    static Ref<const PredictionContext> getCachedContext(const Ref<const PredictionContext> &context,\n                                                         PredictionContextCache &contextCache);\n\n    static std::vector<Ref<const PredictionContext>> getAllContextNodes(const Ref<const PredictionContext> &context);\n\n    /// Convert a RuleContext tree to a PredictionContext graph.\n    /// Return EMPTY if outerContext is empty.\n    static Ref<const PredictionContext> fromRuleContext(const ATN &atn, RuleContext *outerContext);\n\n    PredictionContext(const PredictionContext&) = delete;\n\n    virtual ~PredictionContext() = default;\n\n    PredictionContext& operator=(const PredictionContext&) = delete;\n    PredictionContext& operator=(PredictionContext&&) = delete;\n\n    PredictionContextType getContextType() const { return _contextType; }\n\n    virtual size_t size() const = 0;\n    virtual const Ref<const PredictionContext>& getParent(size_t index) const = 0;\n    virtual size_t getReturnState(size_t index) const = 0;\n\n    /// This means only the EMPTY (wildcard? not sure) context is in set.\n    virtual bool isEmpty() const = 0;\n    bool hasEmptyPath() const;\n\n    size_t hashCode() const;\n\n    virtual bool equals(const PredictionContext &other) const = 0;\n\n    virtual std::string toString() const = 0;\n\n    std::vector<std::string> toStrings(Recognizer *recognizer, int currentState) const;\n    std::vector<std::string> toStrings(Recognizer *recognizer,\n                                       const Ref<const PredictionContext> &stop,\n                                       int currentState) const;\n\n  protected:\n    explicit PredictionContext(PredictionContextType contextType);\n\n    PredictionContext(PredictionContext&& other);\n\n    virtual size_t hashCodeImpl() const = 0;\n\n    size_t cachedHashCode() const { return _hashCode.load(std::memory_order_relaxed); }\n\n  private:\n    const PredictionContextType _contextType;\n    mutable std::atomic<size_t> _hashCode;\n  };\n\n  inline bool operator==(const PredictionContext &lhs, const PredictionContext &rhs) {\n    return lhs.equals(rhs);\n  }\n\n  inline bool operator!=(const PredictionContext &lhs, const PredictionContext &rhs) {\n    return !operator==(lhs, rhs);\n  }\n\n}  // namespace atn\n}  // namespace antlr4\n\nnamespace std {\n\n  template <>\n  struct hash<::antlr4::atn::PredictionContext> {\n    size_t operator()(const ::antlr4::atn::PredictionContext &predictionContext) const {\n      return predictionContext.hashCode();\n    }\n  };\n\n}  // namespace std\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContextCache.cpp",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <cassert>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContextCache.h\"\n\nusing namespace antlr4::atn;\n\nvoid PredictionContextCache::put(const Ref<const PredictionContext> &value) {\n  assert(value);\n\n  _data.insert(value);\n}\n\nRef<const PredictionContext> PredictionContextCache::get(\n    const Ref<const PredictionContext> &value) const {\n  assert(value);\n\n  auto iterator = _data.find(value);\n  if (iterator == _data.end()) {\n    return nullptr;\n  }\n  return *iterator;\n}\n\nsize_t PredictionContextCache::PredictionContextHasher::operator()(\n    const Ref<const PredictionContext> &predictionContext) const {\n  return predictionContext->hashCode();\n}\n\nbool PredictionContextCache::PredictionContextComparer::operator()(\n    const Ref<const PredictionContext> &lhs,\n    const Ref<const PredictionContext> &rhs) const {\n  return *lhs == *rhs;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContextCache.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include <cstddef>\n#include \"atn/PredictionContext.h\"\n#include \"antlr4-common.h\"\n#include \"FlatHashSet.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC PredictionContextCache final {\n  public:\n    PredictionContextCache() = default;\n\n    PredictionContextCache(const PredictionContextCache&) = delete;\n    PredictionContextCache(PredictionContextCache&&) = delete;\n\n    PredictionContextCache& operator=(const PredictionContextCache&) = delete;\n    PredictionContextCache& operator=(PredictionContextCache&&) = delete;\n\n    void put(const Ref<const PredictionContext> &value);\n\n    Ref<const PredictionContext> get(const Ref<const PredictionContext> &value) const;\n\n  private:\n    struct ANTLR4CPP_PUBLIC PredictionContextHasher final {\n      size_t operator()(const Ref<const PredictionContext> &predictionContext) const;\n    };\n\n    struct ANTLR4CPP_PUBLIC PredictionContextComparer final {\n      bool operator()(const Ref<const PredictionContext> &lhs,\n                      const Ref<const PredictionContext> &rhs) const;\n    };\n\n    FlatHashSet<Ref<const PredictionContext>,\n                PredictionContextHasher, PredictionContextComparer> _data;\n  };\n\n}  // namespace atn\n}  // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContextMergeCache.cpp",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <cassert>\n#include <utility>\n#include <cstddef>\n#include \"atn/PredictionContextMergeCache.h\"\n\n#include \"antlr4-common.h\"\n#include \"misc/MurmurHash.h\"\n\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\n\nPredictionContextMergeCache::PredictionContextMergeCache(\n    const PredictionContextMergeCacheOptions &options) : _options(options) {}\n\nRef<const PredictionContext> PredictionContextMergeCache::put(\n    const Ref<const PredictionContext> &key1,\n    const Ref<const PredictionContext> &key2,\n    Ref<const PredictionContext> value) {\n  assert(key1);\n  assert(key2);\n\n  if (getOptions().getMaxSize() == 0) {\n    // Cache is effectively disabled.\n    return value;\n  }\n\n  auto [existing, inserted] = _entries.try_emplace(std::make_pair(key1.get(), key2.get()));\n  if (inserted) {\n    try {\n      existing->second.reset(new Entry());\n    } catch (...) {\n      _entries.erase(existing);\n      throw;\n    }\n    existing->second->key = std::make_pair(key1, key2);\n    existing->second->value = std::move(value);\n    pushToFront(existing->second.get());\n  } else {\n    if (existing->second->value != value) {\n      existing->second->value = std::move(value);\n    }\n    moveToFront(existing->second.get());\n  }\n  compact(existing->second.get());\n  return existing->second->value;\n}\n\nRef<const PredictionContext> PredictionContextMergeCache::get(\n    const Ref<const PredictionContext> &key1,\n    const Ref<const PredictionContext> &key2) const {\n  assert(key1);\n  assert(key2);\n\n  if (getOptions().getMaxSize() == 0) {\n    // Cache is effectively disabled.\n    return nullptr;\n  }\n\n  auto iterator = _entries.find(std::make_pair(key1.get(), key2.get()));\n  if (iterator == _entries.end()) {\n    return nullptr;\n  }\n  moveToFront(iterator->second.get());\n  return iterator->second->value;\n}\n\nvoid PredictionContextMergeCache::clear() {\n  Container().swap(_entries);\n  _head = _tail = nullptr;\n  _size = 0;\n}\n\nvoid PredictionContextMergeCache::moveToFront(Entry *entry) const {\n  if (entry->prev == nullptr) {\n    assert(entry == _head);\n    return;\n  }\n  entry->prev->next = entry->next;\n  if (entry->next != nullptr) {\n    entry->next->prev = entry->prev;\n  } else {\n    assert(entry == _tail);\n    _tail = entry->prev;\n  }\n  entry->prev = nullptr;\n  entry->next = _head;\n  _head->prev = entry;\n  _head = entry;\n  assert(entry->prev == nullptr);\n}\n\nvoid PredictionContextMergeCache::pushToFront(Entry *entry) {\n  ++_size;\n  entry->prev = nullptr;\n  entry->next = _head;\n  if (_head != nullptr) {\n    _head->prev = entry;\n    _head = entry;\n  } else {\n    assert(entry->next == nullptr);\n    _head = entry;\n    _tail = entry;\n  }\n  assert(entry->prev == nullptr);\n}\n\nvoid PredictionContextMergeCache::remove(Entry *entry) {\n  if (entry->prev != nullptr) {\n    entry->prev->next = entry->next;\n  } else {\n    assert(entry == _head);\n    _head = entry->next;\n  }\n  if (entry->next != nullptr) {\n    entry->next->prev = entry->prev;\n  } else {\n    assert(entry == _tail);\n    _tail = entry->prev;\n  }\n  --_size;\n  _entries.erase(std::make_pair(entry->key.first.get(), entry->key.second.get()));\n}\n\nvoid PredictionContextMergeCache::compact(const Entry *preserve) {\n  Entry *entry = _tail;\n  while (entry != nullptr && _size > getOptions().getMaxSize()) {\n    Entry *next = entry->prev;\n    if (entry != preserve) {\n      remove(entry);\n    }\n    entry = next;\n  }\n}\n\nsize_t PredictionContextMergeCache::PredictionContextHasher::operator()(\n    const PredictionContextPair &value) const {\n  size_t hash = MurmurHash::initialize();\n  hash = MurmurHash::update(hash, value.first->hashCode());\n  hash = MurmurHash::update(hash, value.second->hashCode());\n  return MurmurHash::finish(hash, 2);\n}\n\nbool PredictionContextMergeCache::PredictionContextComparer::operator()(\n    const PredictionContextPair &lhs, const PredictionContextPair &rhs) const {\n  return *lhs.first == *rhs.first && *lhs.second == *rhs.second;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContextMergeCache.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include <memory>\n#include <cstddef>\n#include <utility>\n\n#include \"atn/PredictionContext.h\"\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContextMergeCacheOptions.h\"\n#include \"FlatHashMap.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC PredictionContextMergeCache final {\n  public:\n    PredictionContextMergeCache()\n        : PredictionContextMergeCache(PredictionContextMergeCacheOptions()) {}\n\n    explicit PredictionContextMergeCache(const PredictionContextMergeCacheOptions &options);\n\n    PredictionContextMergeCache(const PredictionContextMergeCache&) = delete;\n    PredictionContextMergeCache(PredictionContextMergeCache&&) = delete;\n\n    PredictionContextMergeCache& operator=(const PredictionContextMergeCache&) = delete;\n    PredictionContextMergeCache& operator=(PredictionContextMergeCache&&) = delete;\n\n    Ref<const PredictionContext> put(const Ref<const PredictionContext> &key1,\n                                     const Ref<const PredictionContext> &key2,\n                                     Ref<const PredictionContext> value);\n\n    Ref<const PredictionContext> get(const Ref<const PredictionContext> &key1,\n                                     const Ref<const PredictionContext> &key2) const;\n\n    const PredictionContextMergeCacheOptions& getOptions() const { return _options; }\n\n    void clear();\n\n  private:\n    using PredictionContextPair = std::pair<const PredictionContext*, const PredictionContext*>;\n\n    struct ANTLR4CPP_PUBLIC PredictionContextHasher final {\n      size_t operator()(const PredictionContextPair &value) const;\n    };\n\n    struct ANTLR4CPP_PUBLIC PredictionContextComparer final {\n      bool operator()(const PredictionContextPair &lhs, const PredictionContextPair &rhs) const;\n    };\n\n    struct ANTLR4CPP_PUBLIC Entry final {\n      std::pair<Ref<const PredictionContext>, Ref<const PredictionContext>> key;\n      Ref<const PredictionContext> value;\n      Entry *prev = nullptr;\n      Entry *next = nullptr;\n    };\n\n    void moveToFront(Entry *entry) const;\n\n    void pushToFront(Entry *entry);\n\n    void remove(Entry *entry);\n\n    void compact(const Entry *preserve);\n\n    using Container = FlatHashMap<PredictionContextPair, std::unique_ptr<Entry>,\n                                  PredictionContextHasher, PredictionContextComparer>;\n\n    const PredictionContextMergeCacheOptions _options;\n\n    Container _entries;\n\n    mutable Entry *_head = nullptr;\n    mutable Entry *_tail = nullptr;\n\n    size_t _size = 0;\n  };\n\n}  // namespace atn\n}  // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContextMergeCacheOptions.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include <cstddef>\n#include <cstdint>\n#include <limits>\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC PredictionContextMergeCacheOptions final {\n  public:\n    PredictionContextMergeCacheOptions() = default;\n\n    size_t getMaxSize() const { return _maxSize; }\n\n    bool hasMaxSize() const { return getMaxSize() != std::numeric_limits<size_t>::max(); }\n\n    PredictionContextMergeCacheOptions& setMaxSize(size_t maxSize) {\n      _maxSize = maxSize;\n      return *this;\n    }\n\n    size_t getClearEveryN() const {\n      return _clearEveryN;\n    }\n\n    bool hasClearEveryN() const { return getClearEveryN() != 0; }\n\n    PredictionContextMergeCacheOptions& setClearEveryN(uint64_t clearEveryN) {\n      _clearEveryN = clearEveryN;\n      return *this;\n    }\n\n    PredictionContextMergeCacheOptions& neverClear() {\n      return setClearEveryN(0);\n    }\n\n  private:\n    size_t _maxSize = std::numeric_limits<size_t>::max();\n    uint64_t _clearEveryN = 1;\n  };\n\n}  // namespace atn\n}  // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionContextType.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  enum class PredictionContextType : size_t {\n    SINGLETON = 1,\n    ARRAY = 2,\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionMode.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <unordered_map>\n#include <memory>\n#include <vector>\n#include <cstddef>\n#include \"atn/RuleStopState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/ATNConfigSet.h\"\n#include \"atn/ATNConfig.h\"\n#include \"misc/MurmurHash.h\"\n#include \"SemanticContext.h\"\n\n#include \"PredictionMode.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nstruct AltAndContextConfigHasher\n{\n  /**\n   * The hash code is only a function of the {@link ATNState#stateNumber}\n   * and {@link ATNConfig#context}.\n   */\n  size_t operator () (ATNConfig *o) const {\n    size_t hashCode = misc::MurmurHash::initialize(7);\n    hashCode = misc::MurmurHash::update(hashCode, o->state->stateNumber);\n    hashCode = misc::MurmurHash::update(hashCode, o->context);\n    return misc::MurmurHash::finish(hashCode, 2);\n  }\n};\n\nstruct AltAndContextConfigComparer {\n  bool operator()(ATNConfig *a, ATNConfig *b) const\n  {\n    if (a == b) {\n      return true;\n    }\n    return a->state->stateNumber == b->state->stateNumber && *a->context == *b->context;\n  }\n};\n\nbool PredictionModeClass::hasSLLConflictTerminatingPrediction(PredictionMode mode, ATNConfigSet *configs) {\n  /* Configs in rule stop states indicate reaching the end of the decision\n   * rule (local context) or end of start rule (full context). If all\n   * configs meet this condition, then none of the configurations is able\n   * to match additional input so we terminate prediction.\n   */\n  if (allConfigsInRuleStopStates(configs)) {\n    return true;\n  }\n\n  bool heuristic;\n\n  // Pure SLL mode parsing or SLL+LL if:\n  // Don't bother with combining configs from different semantic\n  // contexts if we can fail over to full LL; costs more time\n  // since we'll often fail over anyway.\n  if (mode == PredictionMode::SLL || !configs->hasSemanticContext) {\n    std::vector<antlrcpp::BitSet> altsets = getConflictingAltSubsets(configs);\n    heuristic = hasConflictingAltSet(altsets) && !hasStateAssociatedWithOneAlt(configs);\n  } else {\n    // dup configs, tossing out semantic predicates\n    ATNConfigSet dup(true);\n    for (auto &config : configs->configs) {\n      Ref<ATNConfig> c = std::make_shared<ATNConfig>(*config, SemanticContext::Empty::Instance);\n      dup.add(c);\n    }\n    std::vector<antlrcpp::BitSet> altsets = getConflictingAltSubsets(&dup);\n    heuristic = hasConflictingAltSet(altsets) && !hasStateAssociatedWithOneAlt(&dup);\n  }\n\n  return heuristic;\n}\n\nbool PredictionModeClass::hasConfigInRuleStopState(ATNConfigSet *configs) {\n  for (const auto &config : configs->configs) {\n    if (RuleStopState::is(config->state)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nbool PredictionModeClass::allConfigsInRuleStopStates(ATNConfigSet *configs) {\n  for (const auto &config : configs->configs) {\n    if (!RuleStopState::is(config->state)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nsize_t PredictionModeClass::resolvesToJustOneViableAlt(const std::vector<antlrcpp::BitSet>& altsets) {\n  return getSingleViableAlt(altsets);\n}\n\nbool PredictionModeClass::allSubsetsConflict(const std::vector<antlrcpp::BitSet>& altsets) {\n  return !hasNonConflictingAltSet(altsets);\n}\n\nbool PredictionModeClass::hasNonConflictingAltSet(const std::vector<antlrcpp::BitSet>& altsets) {\n  for (antlrcpp::BitSet alts : altsets) {\n    if (alts.count() == 1) {\n      return true;\n    }\n  }\n  return false;\n}\n\nbool PredictionModeClass::hasConflictingAltSet(const std::vector<antlrcpp::BitSet>& altsets) {\n  for (antlrcpp::BitSet alts : altsets) {\n    if (alts.count() > 1) {\n      return true;\n    }\n  }\n  return false;\n}\n\nbool PredictionModeClass::allSubsetsEqual(const std::vector<antlrcpp::BitSet>& altsets) {\n  if (altsets.empty()) {\n    return true;\n  }\n\n  const antlrcpp::BitSet& first = *altsets.begin();\n  for (const antlrcpp::BitSet& alts : altsets) {\n    if (alts != first) {\n      return false;\n    }\n  }\n  return true;\n}\n\nsize_t PredictionModeClass::getUniqueAlt(const std::vector<antlrcpp::BitSet>& altsets) {\n  antlrcpp::BitSet all = getAlts(altsets);\n  if (all.count() == 1) {\n    return all.nextSetBit(0);\n  }\n  return ATN::INVALID_ALT_NUMBER;\n}\n\nantlrcpp::BitSet PredictionModeClass::getAlts(const std::vector<antlrcpp::BitSet>& altsets) {\n  antlrcpp::BitSet all;\n  for (const auto &alts : altsets) {\n    all |= alts;\n  }\n\n  return all;\n}\n\nantlrcpp::BitSet PredictionModeClass::getAlts(ATNConfigSet *configs) {\n  antlrcpp::BitSet alts;\n  for (const auto &config : configs->configs) {\n    alts.set(config->alt);\n  }\n  return alts;\n}\n\nstd::vector<antlrcpp::BitSet> PredictionModeClass::getConflictingAltSubsets(ATNConfigSet *configs) {\n  std::unordered_map<ATNConfig*, antlrcpp::BitSet, AltAndContextConfigHasher, AltAndContextConfigComparer> configToAlts;\n  for (auto &config : configs->configs) {\n    configToAlts[config.get()].set(config->alt);\n  }\n  std::vector<antlrcpp::BitSet> values;\n  values.reserve(configToAlts.size());\n  for (const auto &pair : configToAlts) {\n    values.push_back(pair.second);\n  }\n  return values;\n}\n\nstd::unordered_map<ATNState*, antlrcpp::BitSet> PredictionModeClass::getStateToAltMap(ATNConfigSet *configs) {\n  std::unordered_map<ATNState*, antlrcpp::BitSet> m;\n  for (const auto &c : configs->configs) {\n    m[c->state].set(c->alt);\n  }\n  return m;\n}\n\nbool PredictionModeClass::hasStateAssociatedWithOneAlt(ATNConfigSet *configs) {\n  auto x = getStateToAltMap(configs);\n  for (const auto &pair : x){\n    if (pair.second.count() == 1) return true;\n  }\n  return false;\n}\n\nsize_t PredictionModeClass::getSingleViableAlt(const std::vector<antlrcpp::BitSet>& altsets) {\n  antlrcpp::BitSet viableAlts;\n  for (const auto &alts : altsets) {\n    size_t minAlt = alts.nextSetBit(0);\n\n    viableAlts.set(minAlt);\n    if (viableAlts.count() > 1)  // more than 1 viable alt\n    {\n      return ATN::INVALID_ALT_NUMBER;\n    }\n  }\n\n  return viableAlts.nextSetBit(0);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/PredictionMode.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <unordered_map>\n#include <vector>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/ATNState.h\"\n#include \"support/BitSet.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /**\n   * This enumeration defines the prediction modes available in ANTLR 4 along with\n   * utility methods for analyzing configuration sets for conflicts and/or\n   * ambiguities.\n   */\n  enum class PredictionMode {\n    /**\n     * The SLL(*) prediction mode. This prediction mode ignores the current\n     * parser context when making predictions. This is the fastest prediction\n     * mode, and provides correct results for many grammars. This prediction\n     * mode is more powerful than the prediction mode provided by ANTLR 3, but\n     * may result in syntax errors for grammar and input combinations which are\n     * not SLL.\n     *\n     * <p>\n     * When using this prediction mode, the parser will either return a correct\n     * parse tree (i.e. the same parse tree that would be returned with the\n     * {@link #LL} prediction mode), or it will report a syntax error. If a\n     * syntax error is encountered when using the {@link #SLL} prediction mode,\n     * it may be due to either an actual syntax error in the input or indicate\n     * that the particular combination of grammar and input requires the more\n     * powerful {@link #LL} prediction abilities to complete successfully.</p>\n     *\n     * <p>\n     * This prediction mode does not provide any guarantees for prediction\n     * behavior for syntactically-incorrect inputs.</p>\n     */\n    SLL,\n\n    /**\n     * The LL(*) prediction mode. This prediction mode allows the current parser\n     * context to be used for resolving SLL conflicts that occur during\n     * prediction. This is the fastest prediction mode that guarantees correct\n     * parse results for all combinations of grammars with syntactically correct\n     * inputs.\n     *\n     * <p>\n     * When using this prediction mode, the parser will make correct decisions\n     * for all syntactically-correct grammar and input combinations. However, in\n     * cases where the grammar is truly ambiguous this prediction mode might not\n     * report a precise answer for <em>exactly which</em> alternatives are\n     * ambiguous.</p>\n     *\n     * <p>\n     * This prediction mode does not provide any guarantees for prediction\n     * behavior for syntactically-incorrect inputs.</p>\n     */\n    LL,\n\n    /**\n     * The LL(*) prediction mode with exact ambiguity detection. In addition to\n     * the correctness guarantees provided by the {@link #LL} prediction mode,\n     * this prediction mode instructs the prediction algorithm to determine the\n     * complete and exact set of ambiguous alternatives for every ambiguous\n     * decision encountered while parsing.\n     *\n     * <p>\n     * This prediction mode may be used for diagnosing ambiguities during\n     * grammar development. Due to the performance overhead of calculating sets\n     * of ambiguous alternatives, this prediction mode should be avoided when\n     * the exact results are not necessary.</p>\n     *\n     * <p>\n     * This prediction mode does not provide any guarantees for prediction\n     * behavior for syntactically-incorrect inputs.</p>\n     */\n    LL_EXACT_AMBIG_DETECTION\n  };\n\n  class ANTLR4CPP_PUBLIC PredictionModeClass {\n  public:\n    /**\n     * Computes the SLL prediction termination condition.\n     *\n     * <p>\n     * This method computes the SLL prediction termination condition for both of\n     * the following cases.</p>\n     *\n     * <ul>\n     * <li>The usual SLL+LL fallback upon SLL conflict</li>\n     * <li>Pure SLL without LL fallback</li>\n     * </ul>\n     *\n     * <p><strong>COMBINED SLL+LL PARSING</strong></p>\n     *\n     * <p>When LL-fallback is enabled upon SLL conflict, correct predictions are\n     * ensured regardless of how the termination condition is computed by this\n     * method. Due to the substantially higher cost of LL prediction, the\n     * prediction should only fall back to LL when the additional lookahead\n     * cannot lead to a unique SLL prediction.</p>\n     *\n     * <p>Assuming combined SLL+LL parsing, an SLL configuration set with only\n     * conflicting subsets should fall back to full LL, even if the\n     * configuration sets don't resolve to the same alternative (e.g.\n     * {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting\n     * configuration, SLL could continue with the hopes that more lookahead will\n     * resolve via one of those non-conflicting configurations.</p>\n     *\n     * <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n     * stops when it sees only conflicting configuration subsets. In contrast,\n     * full LL keeps going when there is uncertainty.</p>\n     *\n     * <p><strong>HEURISTIC</strong></p>\n     *\n     * <p>As a heuristic, we stop prediction when we see any conflicting subset\n     * unless we see a state that only has one alternative associated with it.\n     * The single-alt-state thing lets prediction continue upon rules like\n     * (otherwise, it would admit defeat too soon):</p>\n     *\n     * <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>\n     *\n     * <p>When the ATN simulation reaches the state before {@code ';'}, it has a\n     * DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally\n     * {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop\n     * processing this node because alternative to has another way to continue,\n     * via {@code [6|2|[]]}.</p>\n     *\n     * <p>It also let's us continue for this rule:</p>\n     *\n     * <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>\n     *\n     * <p>After matching input A, we reach the stop state for rule A, state 1.\n     * State 8 is the state right before B. Clearly alternatives 1 and 2\n     * conflict and no amount of further lookahead will separate the two.\n     * However, alternative 3 will be able to continue and so we do not stop\n     * working on this state. In the previous example, we're concerned with\n     * states associated with the conflicting alternatives. Here alt 3 is not\n     * associated with the conflicting configs, but since we can continue\n     * looking for input reasonably, don't declare the state done.</p>\n     *\n     * <p><strong>PURE SLL PARSING</strong></p>\n     *\n     * <p>To handle pure SLL parsing, all we have to do is make sure that we\n     * combine stack contexts for configurations that differ only by semantic\n     * predicate. From there, we can do the usual SLL termination heuristic.</p>\n     *\n     * <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>\n     *\n     * <p>SLL decisions don't evaluate predicates until after they reach DFA stop\n     * states because they need to create the DFA cache that works in all\n     * semantic situations. In contrast, full LL evaluates predicates collected\n     * during start state computation so it can ignore predicates thereafter.\n     * This means that SLL termination detection can totally ignore semantic\n     * predicates.</p>\n     *\n     * <p>Implementation-wise, {@link ATNConfigSet} combines stack contexts but not\n     * semantic predicate contexts so we might see two configurations like the\n     * following.</p>\n     *\n     * <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>\n     *\n     * <p>Before testing these configurations against others, we have to merge\n     * {@code x} and {@code x'} (without modifying the existing configurations).\n     * For example, we test {@code (x+x')==x''} when looking for conflicts in\n     * the following configurations.</p>\n     *\n     * <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>\n     *\n     * <p>If the configuration set has predicates (as indicated by\n     * {@link ATNConfigSet#hasSemanticContext}), this algorithm makes a copy of\n     * the configurations to strip out all of the predicates so that a standard\n     * {@link ATNConfigSet} will merge everything ignoring predicates.</p>\n     */\n    static bool hasSLLConflictTerminatingPrediction(PredictionMode mode, ATNConfigSet *configs);\n\n    /// <summary>\n    /// Checks if any configuration in {@code configs} is in a\n    /// <seealso cref=\"RuleStopState\"/>. Configurations meeting this condition have\n    /// reached\n    /// the end of the decision rule (local context) or end of start rule (full\n    /// context).\n    /// </summary>\n    /// <param name=\"configs\"> the configuration set to test </param>\n    /// <returns> {@code true} if any configuration in {@code configs} is in a\n    /// <seealso cref=\"RuleStopState\"/>, otherwise {@code false} </returns>\n    static bool hasConfigInRuleStopState(ATNConfigSet *configs);\n\n    /// <summary>\n    /// Checks if all configurations in {@code configs} are in a\n    /// <seealso cref=\"RuleStopState\"/>. Configurations meeting this condition have\n    /// reached\n    /// the end of the decision rule (local context) or end of start rule (full\n    /// context).\n    /// </summary>\n    /// <param name=\"configs\"> the configuration set to test </param>\n    /// <returns> {@code true} if all configurations in {@code configs} are in a\n    /// <seealso cref=\"RuleStopState\"/>, otherwise {@code false} </returns>\n    static bool allConfigsInRuleStopStates(ATNConfigSet *configs);\n\n    /**\n     * Full LL prediction termination.\n     *\n     * <p>Can we stop looking ahead during ATN simulation or is there some\n     * uncertainty as to which alternative we will ultimately pick, after\n     * consuming more input? Even if there are partial conflicts, we might know\n     * that everything is going to resolve to the same minimum alternative. That\n     * means we can stop since no more lookahead will change that fact. On the\n     * other hand, there might be multiple conflicts that resolve to different\n     * minimums. That means we need more look ahead to decide which of those\n     * alternatives we should predict.</p>\n     *\n     * <p>The basic idea is to split the set of configurations {@code C}, into\n     * conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with\n     * non-conflicting configurations. Two configurations conflict if they have\n     * identical {@link ATNConfig#state} and {@link ATNConfig#context} values\n     * but different {@link ATNConfig#alt} value, e.g. {@code (s, i, ctx, _)}\n     * and {@code (s, j, ctx, _)} for {@code i!=j}.</p>\n     *\n     * <p>Reduce these configuration subsets to the set of possible alternatives.\n     * You can compute the alternative subsets in one pass as follows:</p>\n     *\n     * <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in\n     * {@code C} holding {@code s} and {@code ctx} fixed.</p>\n     *\n     * <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>\n     *\n     * <pre>\n     * map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not\n     * alt and not pred\n     * </pre>\n     *\n     * <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>\n     *\n     * <p>If {@code |A_s,ctx|=1} then there is no conflict associated with\n     * {@code s} and {@code ctx}.</p>\n     *\n     * <p>Reduce the subsets to singletons by choosing a minimum of each subset. If\n     * the union of these alternative subsets is a singleton, then no amount of\n     * more lookahead will help us. We will always pick that alternative. If,\n     * however, there is more than one alternative, then we are uncertain which\n     * alternative to predict and must continue looking for resolution. We may\n     * or may not discover an ambiguity in the future, even if there are no\n     * conflicting subsets this round.</p>\n     *\n     * <p>The biggest sin is to terminate early because it means we've made a\n     * decision but were uncertain as to the eventual outcome. We haven't used\n     * enough lookahead. On the other hand, announcing a conflict too late is no\n     * big deal; you will still have the conflict. It's just inefficient. It\n     * might even look until the end of file.</p>\n     *\n     * <p>No special consideration for semantic predicates is required because\n     * predicates are evaluated on-the-fly for full LL prediction, ensuring that\n     * no configuration contains a semantic context during the termination\n     * check.</p>\n     *\n     * <p><strong>CONFLICTING CONFIGS</strong></p>\n     *\n     * <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict\n     * when {@code i!=j} but {@code x=x'}. Because we merge all\n     * {@code (s, i, _)} configurations together, that means that there are at\n     * most {@code n} configurations associated with state {@code s} for\n     * {@code n} possible alternatives in the decision. The merged stacks\n     * complicate the comparison of configuration contexts {@code x} and\n     * {@code x'}. Sam checks to see if one is a subset of the other by calling\n     * merge and checking to see if the merged result is either {@code x} or\n     * {@code x'}. If the {@code x} associated with lowest alternative {@code i}\n     * is the superset, then {@code i} is the only possible prediction since the\n     * others resolve to {@code min(i)} as well. However, if {@code x} is\n     * associated with {@code j>i} then at least one stack configuration for\n     * {@code j} is not in conflict with alternative {@code i}. The algorithm\n     * should keep going, looking for more lookahead due to the uncertainty.</p>\n     *\n     * <p>For simplicity, I'm doing a equality check between {@code x} and\n     * {@code x'} that lets the algorithm continue to consume lookahead longer\n     * than necessary. The reason I like the equality is of course the\n     * simplicity but also because that is the test you need to detect the\n     * alternatives that are actually in conflict.</p>\n     *\n     * <p><strong>CONTINUE/STOP RULE</strong></p>\n     *\n     * <p>Continue if union of resolved alternative sets from non-conflicting and\n     * conflicting alternative subsets has more than one alternative. We are\n     * uncertain about which alternative to predict.</p>\n     *\n     * <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which\n     * alternatives are still in the running for the amount of input we've\n     * consumed at this point. The conflicting sets let us to strip away\n     * configurations that won't lead to more states because we resolve\n     * conflicts to the configuration with a minimum alternate for the\n     * conflicting set.</p>\n     *\n     * <p><strong>CASES</strong></p>\n     *\n     * <ul>\n     *\n     * <li>no conflicts and more than 1 alternative in set =&gt; continue</li>\n     *\n     * <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},\n     * {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set\n     * {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n     * {@code {1,3}} =&gt; continue\n     * </li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n     * {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set\n     * {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n     * {@code {1}} =&gt; stop and predict 1</li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n     * {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U\n     * {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce\n     * ambiguity {@code {1,2}}</li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},\n     * {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U\n     * {@code {2}} = {@code {1,2}} =&gt; continue</li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},\n     * {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U\n     * {@code {3}} = {@code {1,3}} =&gt; continue</li>\n     *\n     * </ul>\n     *\n     * <p><strong>EXACT AMBIGUITY DETECTION</strong></p>\n     *\n     * <p>If all states report the same conflicting set of alternatives, then we\n     * know we have the exact ambiguity set.</p>\n     *\n     * <p><code>|A_<em>i</em>|&gt;1</code> and\n     * <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>\n     *\n     * <p>In other words, we continue examining lookahead until all {@code A_i}\n     * have more than one alternative and all {@code A_i} are the same. If\n     * {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate\n     * because the resolved set is {@code {1}}. To determine what the real\n     * ambiguity is, we have to know whether the ambiguity is between one and\n     * two or one and three so we keep going. We can only stop prediction when\n     * we need exact ambiguity detection when the sets look like\n     * {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>\n     */\n    static size_t resolvesToJustOneViableAlt(const std::vector<antlrcpp::BitSet> &altsets);\n\n    /// <summary>\n    /// Determines if every alternative subset in {@code altsets} contains more\n    /// than one alternative.\n    /// </summary>\n    /// <param name=\"altsets\"> a collection of alternative subsets </param>\n    /// <returns> {@code true} if every <seealso cref=\"BitSet\"/> in {@code altsets}\n    /// has\n    /// <seealso cref=\"BitSet#cardinality cardinality\"/> &gt; 1, otherwise {@code\n    /// false} </returns>\n    static bool allSubsetsConflict(const std::vector<antlrcpp::BitSet> &altsets);\n\n    /// <summary>\n    /// Determines if any single alternative subset in {@code altsets} contains\n    /// exactly one alternative.\n    /// </summary>\n    /// <param name=\"altsets\"> a collection of alternative subsets </param>\n    /// <returns> {@code true} if {@code altsets} contains a <seealso\n    /// cref=\"BitSet\"/> with\n    /// <seealso cref=\"BitSet#cardinality cardinality\"/> 1, otherwise {@code false}\n    /// </returns>\n    static bool hasNonConflictingAltSet(const std::vector<antlrcpp::BitSet> &altsets);\n\n    /// <summary>\n    /// Determines if any single alternative subset in {@code altsets} contains\n    /// more than one alternative.\n    /// </summary>\n    /// <param name=\"altsets\"> a collection of alternative subsets </param>\n    /// <returns> {@code true} if {@code altsets} contains a <seealso\n    /// cref=\"BitSet\"/> with\n    /// <seealso cref=\"BitSet#cardinality cardinality\"/> &gt; 1, otherwise {@code\n    /// false} </returns>\n    static bool hasConflictingAltSet(const std::vector<antlrcpp::BitSet> &altsets);\n\n    /// <summary>\n    /// Determines if every alternative subset in {@code altsets} is equivalent.\n    /// </summary>\n    /// <param name=\"altsets\"> a collection of alternative subsets </param>\n    /// <returns> {@code true} if every member of {@code altsets} is equal to the\n    /// others, otherwise {@code false} </returns>\n    static bool allSubsetsEqual(const std::vector<antlrcpp::BitSet> &altsets);\n\n    /// <summary>\n    /// Returns the unique alternative predicted by all alternative subsets in\n    /// {@code altsets}. If no such alternative exists, this method returns\n    /// <seealso cref=\"ATN#INVALID_ALT_NUMBER\"/>.\n    /// </summary>\n    /// <param name=\"altsets\"> a collection of alternative subsets </param>\n    static size_t getUniqueAlt(const std::vector<antlrcpp::BitSet> &altsets);\n\n    /// <summary>\n    /// Gets the complete set of represented alternatives for a collection of\n    /// alternative subsets. This method returns the union of each <seealso\n    /// cref=\"BitSet\"/>\n    /// in {@code altsets}.\n    /// </summary>\n    /// <param name=\"altsets\"> a collection of alternative subsets </param>\n    /// <returns> the set of represented alternatives in {@code altsets} </returns>\n    static antlrcpp::BitSet getAlts(const std::vector<antlrcpp::BitSet> &altsets);\n\n    /** Get union of all alts from configs. @since 4.5.1 */\n    static antlrcpp::BitSet getAlts(ATNConfigSet *configs);\n\n    /// <summary>\n    /// This function gets the conflicting alt subsets from a configuration set.\n    /// For each configuration {@code c} in {@code configs}:\n    ///\n    /// <pre>\n    /// map[c] U= c.<seealso cref=\"ATNConfig#alt alt\"/> # map hash/equals uses s and\n    /// x, not\n    /// alt and not pred\n    /// </pre>\n    /// </summary>\n    static std::vector<antlrcpp::BitSet> getConflictingAltSubsets(ATNConfigSet *configs);\n\n    /// <summary>\n    /// Get a map from state to alt subset from a configuration set. For each\n    /// configuration {@code c} in {@code configs}:\n    ///\n    /// <pre>\n    /// map[c.<seealso cref=\"ATNConfig#state state\"/>] U= c.<seealso\n    /// cref=\"ATNConfig#alt alt\"/>\n    /// </pre>\n    /// </summary>\n    static std::unordered_map<ATNState*, antlrcpp::BitSet> getStateToAltMap(ATNConfigSet *configs);\n\n    static bool hasStateAssociatedWithOneAlt(ATNConfigSet *configs);\n\n    static size_t getSingleViableAlt(const std::vector<antlrcpp::BitSet> &altsets);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ProfilingATNSimulator.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"atn/PredicateEvalInfo.h\"\n#include \"atn/LookaheadEventInfo.h\"\n#include \"Parser.h\"\n#include \"atn/ATNConfigSet.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"atn/ProfilingATNSimulator.h\"\n#include <memory>\n#include <vector>\n#include <cstddef>\n#include <chrono>\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlr4::dfa;\nusing namespace antlrcpp;\n\nusing namespace std::chrono;\n\nProfilingATNSimulator::ProfilingATNSimulator(Parser *parser)\n  : ParserATNSimulator(parser, parser->getInterpreter<ParserATNSimulator>()->atn,\n                       parser->getInterpreter<ParserATNSimulator>()->decisionToDFA,\n                       parser->getInterpreter<ParserATNSimulator>()->getSharedContextCache()) {\n  for (size_t i = 0; i < atn.decisionToState.size(); i++) {\n    _decisions.push_back(DecisionInfo(i));\n  }\n}\n\nsize_t ProfilingATNSimulator::adaptivePredict(TokenStream *input, size_t decision, ParserRuleContext *outerContext) {\n  auto onExit = finally([this](){\n    _currentDecision = 0; // Originally -1, but that makes no sense (index into a vector and init value is also 0).\n  });\n\n  _sllStopIndex = -1;\n  _llStopIndex = -1;\n  _currentDecision = decision;\n  high_resolution_clock::time_point start = high_resolution_clock::now();\n  size_t alt = ParserATNSimulator::adaptivePredict(input, decision, outerContext);\n  high_resolution_clock::time_point stop = high_resolution_clock::now();\n  _decisions[decision].timeInPrediction += duration_cast<nanoseconds>(stop - start).count();\n  _decisions[decision].invocations++;\n\n  long long SLL_k = _sllStopIndex - _startIndex + 1;\n  _decisions[decision].SLL_TotalLook += SLL_k;\n  _decisions[decision].SLL_MinLook = _decisions[decision].SLL_MinLook == 0 ? SLL_k : std::min(_decisions[decision].SLL_MinLook, SLL_k);\n  if (SLL_k > _decisions[decision].SLL_MaxLook) {\n    _decisions[decision].SLL_MaxLook = SLL_k;\n    _decisions[decision].SLL_MaxLookEvent = std::make_shared<LookaheadEventInfo>(decision, nullptr, alt, input, _startIndex, _sllStopIndex, false);\n  }\n\n  if (_llStopIndex >= 0) {\n    long long LL_k = _llStopIndex - _startIndex + 1;\n    _decisions[decision].LL_TotalLook += LL_k;\n    _decisions[decision].LL_MinLook = _decisions[decision].LL_MinLook == 0 ? LL_k : std::min(_decisions[decision].LL_MinLook, LL_k);\n    if (LL_k > _decisions[decision].LL_MaxLook) {\n      _decisions[decision].LL_MaxLook = LL_k;\n      _decisions[decision].LL_MaxLookEvent = std::make_shared<LookaheadEventInfo>(decision, nullptr, alt, input, _startIndex, _llStopIndex, true);\n    }\n  }\n\n  return alt;\n}\n\nDFAState* ProfilingATNSimulator::getExistingTargetState(DFAState *previousD, size_t t) {\n  // this method is called after each time the input position advances\n  // during SLL prediction\n  _sllStopIndex = (int)_input->index();\n\n  DFAState *existingTargetState = ParserATNSimulator::getExistingTargetState(previousD, t);\n  if (existingTargetState != nullptr) {\n    _decisions[_currentDecision].SLL_DFATransitions++; // count only if we transition over a DFA state\n    if (existingTargetState == ERROR.get()) {\n      _decisions[_currentDecision].errors.push_back(\n        ErrorInfo(_currentDecision, previousD->configs.get(), _input, _startIndex, _sllStopIndex, false)\n      );\n    }\n  }\n\n  _currentState = existingTargetState;\n  return existingTargetState;\n}\n\nDFAState* ProfilingATNSimulator::computeTargetState(DFA &dfa, DFAState *previousD, size_t t) {\n  DFAState *state = ParserATNSimulator::computeTargetState(dfa, previousD, t);\n  _currentState = state;\n  return state;\n}\n\nstd::unique_ptr<ATNConfigSet> ProfilingATNSimulator::computeReachSet(ATNConfigSet *closure, size_t t, bool fullCtx) {\n  if (fullCtx) {\n    // this method is called after each time the input position advances\n    // during full context prediction\n    _llStopIndex = (int)_input->index();\n  }\n\n  std::unique_ptr<ATNConfigSet> reachConfigs = ParserATNSimulator::computeReachSet(closure, t, fullCtx);\n  if (fullCtx) {\n    _decisions[_currentDecision].LL_ATNTransitions++; // count computation even if error\n    if (reachConfigs != nullptr) {\n    } else { // no reach on current lookahead symbol. ERROR.\n      // TODO: does not handle delayed errors per getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule()\n      _decisions[_currentDecision].errors.push_back(ErrorInfo(_currentDecision, closure, _input, _startIndex, _llStopIndex, true));\n    }\n  } else {\n    ++_decisions[_currentDecision].SLL_ATNTransitions;\n    if (reachConfigs != nullptr) {\n    } else { // no reach on current lookahead symbol. ERROR.\n      _decisions[_currentDecision].errors.push_back(ErrorInfo(_currentDecision, closure, _input, _startIndex, _sllStopIndex, false));\n    }\n  }\n  return reachConfigs;\n}\n\nbool ProfilingATNSimulator::evalSemanticContext(Ref<const SemanticContext> const& pred, ParserRuleContext *parserCallStack,\n                                                size_t alt, bool fullCtx) {\n  bool result = ParserATNSimulator::evalSemanticContext(pred, parserCallStack, alt, fullCtx);\n  if (!(std::dynamic_pointer_cast<const SemanticContext::PrecedencePredicate>(pred) != nullptr)) {\n    bool fullContext = _llStopIndex >= 0;\n    int stopIndex = fullContext ? _llStopIndex : _sllStopIndex;\n    _decisions[_currentDecision].predicateEvals.push_back(\n      PredicateEvalInfo(_currentDecision, _input, _startIndex, stopIndex, pred, result, alt, fullCtx));\n  }\n\n  return result;\n}\n\nvoid ProfilingATNSimulator::reportAttemptingFullContext(DFA &dfa, const BitSet &conflictingAlts, ATNConfigSet *configs,\n                                                        size_t startIndex, size_t stopIndex) {\n  if (conflictingAlts.count() > 0) {\n    conflictingAltResolvedBySLL = conflictingAlts.nextSetBit(0);\n  } else {\n    conflictingAltResolvedBySLL = configs->getAlts().nextSetBit(0);\n  }\n  _decisions[_currentDecision].LL_Fallback++;\n  ParserATNSimulator::reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex);\n}\n\nvoid ProfilingATNSimulator::reportContextSensitivity(DFA &dfa, size_t prediction, ATNConfigSet *configs,\n                                                     size_t startIndex, size_t stopIndex) {\n  if (prediction != conflictingAltResolvedBySLL) {\n    _decisions[_currentDecision].contextSensitivities.push_back(\n      ContextSensitivityInfo(_currentDecision, configs, _input, startIndex, stopIndex)\n    );\n  }\n  ParserATNSimulator::reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex);\n}\n\nvoid ProfilingATNSimulator::reportAmbiguity(DFA &dfa, DFAState *D, size_t startIndex, size_t stopIndex, bool exact,\n                                            const BitSet &ambigAlts, ATNConfigSet *configs) {\n  size_t prediction;\n  if (ambigAlts.count() > 0) {\n    prediction = ambigAlts.nextSetBit(0);\n  } else {\n    prediction = configs->getAlts().nextSetBit(0);\n  }\n  if (configs->fullCtx && prediction != conflictingAltResolvedBySLL) {\n    // Even though this is an ambiguity we are reporting, we can\n    // still detect some context sensitivities.  Both SLL and LL\n    // are showing a conflict, hence an ambiguity, but if they resolve\n    // to different minimum alternatives we have also identified a\n    // context sensitivity.\n    _decisions[_currentDecision].contextSensitivities.push_back(\n      ContextSensitivityInfo(_currentDecision, configs, _input, startIndex, stopIndex)\n    );\n  }\n  _decisions[_currentDecision].ambiguities.push_back(\n    AmbiguityInfo(_currentDecision, configs, ambigAlts, _input, startIndex, stopIndex, configs->fullCtx)\n  );\n  ParserATNSimulator::reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts, configs);\n}\n\nstd::vector<DecisionInfo> ProfilingATNSimulator::getDecisionInfo() const {\n  return _decisions;\n}\n\nDFAState* ProfilingATNSimulator::getCurrentState() const {\n  return _currentState;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/ProfilingATNSimulator.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <cstddef>\n#include \"atn/ParserATNSimulator.h\"\n#include \"antlr4-common.h\"\n#include \"atn/DecisionInfo.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC ProfilingATNSimulator : public ParserATNSimulator {\n  public:\n    explicit ProfilingATNSimulator(Parser *parser);\n\n    size_t adaptivePredict(TokenStream *input, size_t decision, ParserRuleContext *outerContext) override;\n\n    virtual std::vector<DecisionInfo> getDecisionInfo() const;\n    virtual dfa::DFAState* getCurrentState() const;\n\n  protected:\n    std::vector<DecisionInfo> _decisions;\n\n    int _sllStopIndex = 0;\n    int _llStopIndex = 0;\n\n    size_t _currentDecision = 0;\n    dfa::DFAState *_currentState;\n\n    /// <summary>\n    /// At the point of LL failover, we record how SLL would resolve the conflict so that\n    ///  we can determine whether or not a decision / input pair is context-sensitive.\n    ///  If LL gives a different result than SLL's predicted alternative, we have a\n    ///  context sensitivity for sure. The converse is not necessarily true, however.\n    ///  It's possible that after conflict resolution chooses minimum alternatives,\n    ///  SLL could get the same answer as LL. Regardless of whether or not the result indicates\n    ///  an ambiguity, it is not treated as a context sensitivity because LL prediction\n    ///  was not required in order to produce a correct prediction for this decision and input sequence.\n    ///  It may in fact still be a context sensitivity but we don't know by looking at the\n    ///  minimum alternatives for the current input.\n    /// </summary>\n    size_t conflictingAltResolvedBySLL = 0;\n\n    dfa::DFAState* getExistingTargetState(dfa::DFAState *previousD, size_t t) override;\n    dfa::DFAState* computeTargetState(dfa::DFA &dfa, dfa::DFAState *previousD, size_t t) override;\n    std::unique_ptr<ATNConfigSet> computeReachSet(ATNConfigSet *closure, size_t t, bool fullCtx) override;\n    bool evalSemanticContext(Ref<const SemanticContext> const& pred, ParserRuleContext *parserCallStack,\n                                     size_t alt, bool fullCtx) override;\n    void reportAttemptingFullContext(dfa::DFA &dfa, const antlrcpp::BitSet &conflictingAlts, ATNConfigSet *configs,\n                                             size_t startIndex, size_t stopIndex) override;\n    void reportContextSensitivity(dfa::DFA &dfa, size_t prediction, ATNConfigSet *configs,\n                                          size_t startIndex, size_t stopIndex) override;\n    void reportAmbiguity(dfa::DFA &dfa, dfa::DFAState *D, size_t startIndex, size_t stopIndex, bool exact,\n                                 const antlrcpp::BitSet &ambigAlts, ATNConfigSet *configs) override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/RangeTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"misc/IntervalSet.h\"\n\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/RangeTransition.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nRangeTransition::RangeTransition(ATNState *target, size_t from, size_t to) : Transition(TransitionType::RANGE, target), from(from), to(to) {\n}\n\nmisc::IntervalSet RangeTransition::label() const {\n  return misc::IntervalSet::of((int)from, (int)to);\n}\n\nbool RangeTransition::matches(size_t symbol, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return symbol >= from && symbol <= to;\n}\n\nstd::string RangeTransition::toString() const {\n  return \"RANGE \" + Transition::toString() + \" { from: \" + std::to_string(from) + \", to: \" + std::to_string(to) + \" }\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/RangeTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC RangeTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::RANGE; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    const size_t from;\n    const size_t to;\n\n    RangeTransition(ATNState *target, size_t from, size_t to);\n\n    misc::IntervalSet label() const override;\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/RuleStartState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC RuleStartState final : public ATNState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::RULE_START; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    RuleStopState *stopState = nullptr;\n    bool isLeftRecursiveRule = false;\n\n    RuleStartState() : ATNState(ATNStateType::RULE_START) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/RuleStopState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// The last node in the ATN for a rule, unless that rule is the start symbol.\n  /// In that case, there is one transition to EOF. Later, we might encode\n  /// references to all calls to this rule to compute FOLLOW sets for\n  /// error handling.\n  class ANTLR4CPP_PUBLIC RuleStopState final : public ATNState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::RULE_STOP; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    RuleStopState() : ATNState(ATNStateType::RULE_STOP) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/RuleTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <string>\n#include <cstddef>\n#include \"atn/RuleStartState.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/RuleTransition.h\"\n\nusing namespace antlr4::atn;\n\nRuleTransition::RuleTransition(RuleStartState *ruleStart, size_t ruleIndex, ATNState *followState)\n  : RuleTransition(ruleStart, ruleIndex, 0, followState) {\n}\n\nRuleTransition::RuleTransition(RuleStartState *ruleStart, size_t ruleIndex, int precedence, ATNState *followState)\n  : Transition(TransitionType::RULE, ruleStart), ruleIndex(ruleIndex), precedence(precedence) {\n  this->followState = followState;\n}\n\nbool RuleTransition::isEpsilon() const {\n  return true;\n}\n\nbool RuleTransition::matches(size_t /*symbol*/, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return false;\n}\n\nstd::string RuleTransition::toString() const {\n  std::stringstream ss;\n  ss << \"RULE \" << Transition::toString() << \" { ruleIndex: \" << ruleIndex << \", precedence: \" << precedence <<\n    \", followState: \" << std::hex << followState << \" }\";\n  return ss.str();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/RuleTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC RuleTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::RULE; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    /// Ptr to the rule definition object for this rule ref.\n    const size_t ruleIndex; // no Rule object at runtime\n\n    const int precedence;\n\n    /// What node to begin computations following ref to rule.\n    ATNState *followState;\n\n    /// @deprecated Use\n    /// <seealso cref=\"#RuleTransition(RuleStartState, size_t, int, ATNState)\"/> instead.\n    RuleTransition(RuleStartState *ruleStart, size_t ruleIndex, ATNState *followState);\n\n    RuleTransition(RuleStartState *ruleStart, size_t ruleIndex, int precedence, ATNState *followState);\n    RuleTransition(RuleTransition const&) = delete;\n    RuleTransition& operator=(RuleTransition const&) = delete;\n\n    bool isEpsilon() const override;\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SemanticContext.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include <functional>\n#include <unordered_set>\n\n#include \"misc/MurmurHash.h\"\n#include \"antlr4-common.h\"\n#include \"support/Casts.h\"\n#include \"support/CPPUtils.h\"\n#include \"support/Arrays.h\"\n\n#include \"SemanticContext.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nnamespace {\n\n  struct SemanticContextHasher final {\n    size_t operator()(const SemanticContext *semanticContext) const {\n      return semanticContext->hashCode();\n    }\n  };\n\n  struct SemanticContextComparer final {\n    bool operator()(const SemanticContext *lhs, const SemanticContext *rhs) const {\n      return *lhs == *rhs;\n    }\n  };\n\n  template <typename Comparer>\n  void insertSemanticContext(const Ref<const SemanticContext> &semanticContext,\n                             std::unordered_set<const SemanticContext*, SemanticContextHasher, SemanticContextComparer> &operandSet,\n                             std::vector<Ref<const SemanticContext>> &operandList,\n                             Ref<const SemanticContext::PrecedencePredicate> &precedencePredicate,\n                             Comparer comparer) {\n    if (semanticContext != nullptr) {\n      if (semanticContext->getContextType() == SemanticContextType::PRECEDENCE) {\n        if (precedencePredicate == nullptr || comparer(downCast<const SemanticContext::PrecedencePredicate*>(semanticContext.get())->precedence, precedencePredicate->precedence)) {\n          precedencePredicate = std::static_pointer_cast<const SemanticContext::PrecedencePredicate>(semanticContext);\n        }\n      } else {\n        auto [existing, inserted] = operandSet.insert(semanticContext.get());\n        if (inserted) {\n          operandList.push_back(semanticContext);\n        }\n      }\n    }\n  }\n\n  template <typename Comparer>\n  void insertSemanticContext(Ref<const SemanticContext> &&semanticContext,\n                             std::unordered_set<const SemanticContext*, SemanticContextHasher, SemanticContextComparer> &operandSet,\n                             std::vector<Ref<const SemanticContext>> &operandList,\n                             Ref<const SemanticContext::PrecedencePredicate> &precedencePredicate,\n                             Comparer comparer) {\n    if (semanticContext != nullptr) {\n      if (semanticContext->getContextType() == SemanticContextType::PRECEDENCE) {\n        if (precedencePredicate == nullptr || comparer(downCast<const SemanticContext::PrecedencePredicate*>(semanticContext.get())->precedence, precedencePredicate->precedence)) {\n          precedencePredicate = std::static_pointer_cast<const SemanticContext::PrecedencePredicate>(std::move(semanticContext));\n        }\n      } else {\n        auto [existing, inserted] = operandSet.insert(semanticContext.get());\n        if (inserted) {\n          operandList.push_back(std::move(semanticContext));\n        }\n      }\n    }\n  }\n\n  size_t predictOperandCapacity(const Ref<const SemanticContext> &x) {\n    switch (x->getContextType()) {\n      case SemanticContextType::AND:\n        return downCast<const SemanticContext::AND&>(*x).getOperands().size();\n      case SemanticContextType::OR:\n        return downCast<const SemanticContext::OR&>(*x).getOperands().size();\n      default:\n        return 1;\n    }\n  }\n\n  size_t predictOperandCapacity(const Ref<const SemanticContext> &a, const Ref<const SemanticContext> &b) {\n    return predictOperandCapacity(a) + predictOperandCapacity(b);\n  }\n\n}\n\n//------------------ Predicate -----------------------------------------------------------------------------------------\n\nSemanticContext::Predicate::Predicate(size_t ruleIndex, size_t predIndex, bool isCtxDependent)\n    : SemanticContext(SemanticContextType::PREDICATE), ruleIndex(ruleIndex), predIndex(predIndex), isCtxDependent(isCtxDependent) {}\n\nbool SemanticContext::Predicate::eval(Recognizer *parser, RuleContext *parserCallStack) const {\n  RuleContext *localctx = nullptr;\n  if (isCtxDependent) {\n    localctx = parserCallStack;\n  }\n  return parser->sempred(localctx, ruleIndex, predIndex);\n}\n\nsize_t SemanticContext::Predicate::hashCode() const {\n  size_t hashCode = misc::MurmurHash::initialize();\n  hashCode = misc::MurmurHash::update(hashCode, static_cast<size_t>(getContextType()));\n  hashCode = misc::MurmurHash::update(hashCode, ruleIndex);\n  hashCode = misc::MurmurHash::update(hashCode, predIndex);\n  hashCode = misc::MurmurHash::update(hashCode, isCtxDependent ? 1 : 0);\n  hashCode = misc::MurmurHash::finish(hashCode, 4);\n  return hashCode;\n}\n\nbool SemanticContext::Predicate::equals(const SemanticContext &other) const {\n  if (this == &other) {\n    return true;\n  }\n  if (getContextType() != other.getContextType()) {\n    return false;\n  }\n  const Predicate &p = downCast<const Predicate&>(other);\n  return ruleIndex == p.ruleIndex && predIndex == p.predIndex && isCtxDependent == p.isCtxDependent;\n}\n\nstd::string SemanticContext::Predicate::toString() const {\n  return std::string(\"{\") + std::to_string(ruleIndex) + std::string(\":\") + std::to_string(predIndex) + std::string(\"}?\");\n}\n\n//------------------ PrecedencePredicate -------------------------------------------------------------------------------\n\nSemanticContext::PrecedencePredicate::PrecedencePredicate(int precedence) : SemanticContext(SemanticContextType::PRECEDENCE), precedence(precedence) {}\n\nbool SemanticContext::PrecedencePredicate::eval(Recognizer *parser, RuleContext *parserCallStack) const {\n  return parser->precpred(parserCallStack, precedence);\n}\n\nRef<const SemanticContext> SemanticContext::PrecedencePredicate::evalPrecedence(Recognizer *parser,\n  RuleContext *parserCallStack) const {\n  if (parser->precpred(parserCallStack, precedence)) {\n    return SemanticContext::Empty::Instance;\n  }\n  return nullptr;\n}\n\nsize_t SemanticContext::PrecedencePredicate::hashCode() const {\n  size_t hashCode = misc::MurmurHash::initialize();\n  hashCode = misc::MurmurHash::update(hashCode, static_cast<size_t>(getContextType()));\n  hashCode = misc::MurmurHash::update(hashCode, static_cast<size_t>(precedence));\n  return misc::MurmurHash::finish(hashCode, 2);\n}\n\nbool SemanticContext::PrecedencePredicate::equals(const SemanticContext &other) const {\n  if (this == &other) {\n    return true;\n  }\n  if (getContextType() != other.getContextType()) {\n    return false;\n  }\n  const PrecedencePredicate &predicate = downCast<const PrecedencePredicate&>(other);\n  return precedence == predicate.precedence;\n}\n\nstd::string SemanticContext::PrecedencePredicate::toString() const {\n  return \"{\" + std::to_string(precedence) + \">=prec}?\";\n}\n\n//------------------ AND -----------------------------------------------------------------------------------------------\n\nSemanticContext::AND::AND(Ref<const SemanticContext> a, Ref<const SemanticContext> b) : Operator(SemanticContextType::AND) {\n  std::unordered_set<const SemanticContext*, SemanticContextHasher, SemanticContextComparer> operands;\n  Ref<const SemanticContext::PrecedencePredicate> precedencePredicate;\n\n  _opnds.reserve(predictOperandCapacity(a, b) + 1);\n\n  if (a->getContextType() == SemanticContextType::AND) {\n    for (const auto &operand : downCast<const AND*>(a.get())->getOperands()) {\n      insertSemanticContext(operand, operands, _opnds, precedencePredicate, std::less<int>{});\n    }\n  } else {\n    insertSemanticContext(std::move(a), operands, _opnds, precedencePredicate, std::less<int>{});\n  }\n\n  if (b->getContextType() == SemanticContextType::AND) {\n    for (const auto &operand : downCast<const AND*>(b.get())->getOperands()) {\n      insertSemanticContext(operand, operands, _opnds, precedencePredicate, std::less<int>{});\n    }\n  } else {\n    insertSemanticContext(std::move(b), operands, _opnds, precedencePredicate, std::less<int>{});\n  }\n\n  if (precedencePredicate != nullptr) {\n    // interested in the transition with the lowest precedence\n    auto [existing, inserted] = operands.insert(precedencePredicate.get());\n    if (inserted) {\n      _opnds.push_back(std::move(precedencePredicate));\n    }\n  }\n}\n\nconst std::vector<Ref<const SemanticContext>>& SemanticContext::AND::getOperands() const {\n  return _opnds;\n}\n\nbool SemanticContext::AND::equals(const SemanticContext &other) const {\n  if (this == &other) {\n    return true;\n  }\n  if (getContextType() != other.getContextType()) {\n    return false;\n  }\n  const AND &context = downCast<const AND&>(other);\n  return Arrays::equals(getOperands(), context.getOperands());\n}\n\nsize_t SemanticContext::AND::hashCode() const {\n  size_t hash = misc::MurmurHash::initialize();\n  hash = misc::MurmurHash::update(hash, static_cast<size_t>(getContextType()));\n  return misc::MurmurHash::hashCode(getOperands(), hash);\n}\n\nbool SemanticContext::AND::eval(Recognizer *parser, RuleContext *parserCallStack) const {\n  for (const auto &opnd : getOperands()) {\n    if (!opnd->eval(parser, parserCallStack)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nRef<const SemanticContext> SemanticContext::AND::evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) const {\n  bool differs = false;\n  std::vector<Ref<const SemanticContext>> operands;\n  for (const auto &context : getOperands()) {\n    auto evaluated = context->evalPrecedence(parser, parserCallStack);\n    differs |= (evaluated != context);\n    if (evaluated == nullptr) {\n      // The AND context is false if any element is false.\n      return nullptr;\n    }\n    if (evaluated != Empty::Instance) {\n      // Reduce the result by skipping true elements.\n      operands.push_back(std::move(evaluated));\n    }\n  }\n\n  if (!differs) {\n    return shared_from_this();\n  }\n\n  if (operands.empty()) {\n    // All elements were true, so the AND context is true.\n    return Empty::Instance;\n  }\n\n  Ref<const SemanticContext> result = std::move(operands[0]);\n  for (size_t i = 1; i < operands.size(); ++i) {\n    result = SemanticContext::And(std::move(result), std::move(operands[i]));\n  }\n\n  return result;\n}\n\nstd::string SemanticContext::AND::toString() const {\n  std::string tmp;\n  for (const auto &var : getOperands()) {\n    tmp += var->toString() + \" && \";\n  }\n  return tmp;\n}\n\n//------------------ OR ------------------------------------------------------------------------------------------------\n\nSemanticContext::OR::OR(Ref<const SemanticContext> a, Ref<const SemanticContext> b) : Operator(SemanticContextType::OR) {\n  std::unordered_set<const SemanticContext*, SemanticContextHasher, SemanticContextComparer> operands;\n  Ref<const SemanticContext::PrecedencePredicate> precedencePredicate;\n\n  _opnds.reserve(predictOperandCapacity(a, b) + 1);\n\n  if (a->getContextType() == SemanticContextType::OR) {\n    for (const auto &operand : downCast<const OR*>(a.get())->getOperands()) {\n      insertSemanticContext(operand, operands, _opnds, precedencePredicate, std::greater<int>{});\n    }\n  } else {\n    insertSemanticContext(std::move(a), operands, _opnds, precedencePredicate, std::greater<int>{});\n  }\n\n  if (b->getContextType() == SemanticContextType::OR) {\n    for (const auto &operand : downCast<const OR*>(b.get())->getOperands()) {\n      insertSemanticContext(operand, operands, _opnds, precedencePredicate, std::greater<int>{});\n    }\n  } else {\n    insertSemanticContext(std::move(b), operands, _opnds, precedencePredicate, std::greater<int>{});\n  }\n\n  if (precedencePredicate != nullptr) {\n    // interested in the transition with the highest precedence\n    auto [existing, inserted] = operands.insert(precedencePredicate.get());\n    if (inserted) {\n      _opnds.push_back(std::move(precedencePredicate));\n    }\n  }\n}\n\nconst std::vector<Ref<const SemanticContext>>& SemanticContext::OR::getOperands() const {\n  return _opnds;\n}\n\nbool SemanticContext::OR::equals(const SemanticContext &other) const {\n  if (this == &other) {\n    return true;\n  }\n  if (getContextType() != other.getContextType()) {\n    return false;\n  }\n  const OR &context = downCast<const OR&>(other);\n  return Arrays::equals(getOperands(), context.getOperands());\n}\n\nsize_t SemanticContext::OR::hashCode() const {\n  size_t hash = misc::MurmurHash::initialize();\n  hash = misc::MurmurHash::update(hash, static_cast<size_t>(getContextType()));\n  return misc::MurmurHash::hashCode(getOperands(), hash);\n}\n\nbool SemanticContext::OR::eval(Recognizer *parser, RuleContext *parserCallStack) const {\n  for (const auto &opnd : getOperands()) {\n    if (opnd->eval(parser, parserCallStack)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nRef<const SemanticContext> SemanticContext::OR::evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) const {\n  bool differs = false;\n  std::vector<Ref<const SemanticContext>> operands;\n  for (const auto &context : getOperands()) {\n    auto evaluated = context->evalPrecedence(parser, parserCallStack);\n    differs |= (evaluated != context);\n    if (evaluated == Empty::Instance) {\n      // The OR context is true if any element is true.\n      return Empty::Instance;\n    }\n    if (evaluated != nullptr) {\n      // Reduce the result by skipping false elements.\n      operands.push_back(std::move(evaluated));\n    }\n  }\n\n  if (!differs) {\n    return shared_from_this();\n  }\n\n  if (operands.empty()) {\n    // All elements were false, so the OR context is false.\n    return nullptr;\n  }\n\n  Ref<const SemanticContext> result = std::move(operands[0]);\n  for (size_t i = 1; i < operands.size(); ++i) {\n    result = SemanticContext::Or(std::move(result), std::move(operands[i]));\n  }\n\n  return result;\n}\n\nstd::string SemanticContext::OR::toString() const {\n  std::string tmp;\n  for(const auto &var : getOperands()) {\n    tmp += var->toString() + \" || \";\n  }\n  return tmp;\n}\n\n//------------------ SemanticContext -----------------------------------------------------------------------------------\n\nconst Ref<const SemanticContext> SemanticContext::Empty::Instance = std::make_shared<Predicate>(INVALID_INDEX, INVALID_INDEX, false);\n\nRef<const SemanticContext> SemanticContext::evalPrecedence(Recognizer * /*parser*/, RuleContext * /*parserCallStack*/) const {\n  return shared_from_this();\n}\n\nRef<const SemanticContext> SemanticContext::And(Ref<const SemanticContext> a, Ref<const SemanticContext> b) {\n  if (!a || a == Empty::Instance) {\n    return b;\n  }\n\n  if (!b || b == Empty::Instance) {\n    return a;\n  }\n\n  Ref<AND> result = std::make_shared<AND>(std::move(a), std::move(b));\n  if (result->getOperands().size() == 1) {\n    return result->getOperands()[0];\n  }\n\n  return result;\n}\n\nRef<const SemanticContext> SemanticContext::Or(Ref<const SemanticContext> a, Ref<const SemanticContext> b) {\n  if (!a) {\n    return b;\n  }\n  if (!b) {\n    return a;\n  }\n\n  if (a == Empty::Instance || b == Empty::Instance) {\n    return Empty::Instance;\n  }\n\n  Ref<OR> result = std::make_shared<OR>(std::move(a), std::move(b));\n  if (result->getOperands().size() == 1) {\n    return result->getOperands()[0];\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SemanticContext.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"Recognizer.h\"\n#include \"antlr4-common.h\"\n#include \"support/CPPUtils.h\"\n#include \"atn/SemanticContextType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// A tree structure used to record the semantic context in which\n  ///  an ATN configuration is valid.  It's either a single predicate,\n  ///  a conjunction \"p1 && p2\", or a sum of products \"p1||p2\".\n  ///\n  ///  I have scoped the AND, OR, and Predicate subclasses of\n  ///  SemanticContext within the scope of this outer class.\n  class ANTLR4CPP_PUBLIC SemanticContext : public std::enable_shared_from_this<SemanticContext> {\n  public:\n    virtual ~SemanticContext() = default;\n\n    SemanticContextType getContextType() const { return _contextType; }\n\n    /// <summary>\n    /// For context independent predicates, we evaluate them without a local\n    /// context (i.e., null context). That way, we can evaluate them without\n    /// having to create proper rule-specific context during prediction (as\n    /// opposed to the parser, which creates them naturally). In a practical\n    /// sense, this avoids a cast exception from RuleContext to myruleContext.\n    /// <p/>\n    /// For context dependent predicates, we must pass in a local context so that\n    /// references such as $arg evaluate properly as _localctx.arg. We only\n    /// capture context dependent predicates in the context in which we begin\n    /// prediction, so we passed in the outer context here in case of context\n    /// dependent predicate evaluation.\n    /// </summary>\n    virtual bool eval(Recognizer *parser, RuleContext *parserCallStack) const = 0;\n\n    /**\n     * Evaluate the precedence predicates for the context and reduce the result.\n     *\n     * @param parser The parser instance.\n     * @param parserCallStack\n     * @return The simplified semantic context after precedence predicates are\n     * evaluated, which will be one of the following values.\n     * <ul>\n     * <li>{@link #NONE}: if the predicate simplifies to {@code true} after\n     * precedence predicates are evaluated.</li>\n     * <li>{@code null}: if the predicate simplifies to {@code false} after\n     * precedence predicates are evaluated.</li>\n     * <li>{@code this}: if the semantic context is not changed as a result of\n     * precedence predicate evaluation.</li>\n     * <li>A non-{@code null} {@link SemanticContext}: the new simplified\n     * semantic context after precedence predicates are evaluated.</li>\n     * </ul>\n     */\n    virtual Ref<const SemanticContext> evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) const;\n\n    virtual size_t hashCode() const = 0;\n\n    virtual bool equals(const SemanticContext &other) const = 0;\n\n    virtual std::string toString() const = 0;\n\n    static Ref<const SemanticContext> And(Ref<const SemanticContext> a, Ref<const SemanticContext> b);\n\n    /// See also: ParserATNSimulator::getPredsForAmbigAlts.\n    static Ref<const SemanticContext> Or(Ref<const SemanticContext> a, Ref<const SemanticContext> b);\n\n    class Empty;\n    class Predicate;\n    class PrecedencePredicate;\n    class Operator;\n    class AND;\n    class OR;\n\n  protected:\n    explicit SemanticContext(SemanticContextType contextType) : _contextType(contextType) {}\n\n  private:\n    const SemanticContextType _contextType;\n  };\n\n  inline bool operator==(const SemanticContext &lhs, const SemanticContext &rhs) {\n    return lhs.equals(rhs);\n  }\n\n  inline bool operator!=(const SemanticContext &lhs, const SemanticContext &rhs) {\n    return !operator==(lhs, rhs);\n  }\n\n  class ANTLR4CPP_PUBLIC SemanticContext::Empty : public SemanticContext{\n  public:\n    /**\n     * The default {@link SemanticContext}, which is semantically equivalent to\n     * a predicate of the form {@code {true}?}.\n     */\n    static const Ref<const SemanticContext> Instance;\n  };\n\n  class ANTLR4CPP_PUBLIC SemanticContext::Predicate final : public SemanticContext {\n  public:\n    static bool is(const SemanticContext &semanticContext) { return semanticContext.getContextType() == SemanticContextType::PREDICATE; }\n\n    static bool is(const SemanticContext *semanticContext) { return semanticContext != nullptr && is(*semanticContext); }\n\n    const size_t ruleIndex;\n    const size_t predIndex;\n    const bool isCtxDependent; // e.g., $i ref in pred\n\n    Predicate(size_t ruleIndex, size_t predIndex, bool isCtxDependent);\n\n    bool eval(Recognizer *parser, RuleContext *parserCallStack) const override;\n    size_t hashCode() const override;\n    bool equals(const SemanticContext &other) const override;\n    std::string toString() const override;\n  };\n\n  class ANTLR4CPP_PUBLIC SemanticContext::PrecedencePredicate final : public SemanticContext {\n  public:\n    static bool is(const SemanticContext &semanticContext) { return semanticContext.getContextType() == SemanticContextType::PRECEDENCE; }\n\n    static bool is(const SemanticContext *semanticContext) { return semanticContext != nullptr && is(*semanticContext); }\n\n    const int precedence;\n\n    explicit PrecedencePredicate(int precedence);\n\n    bool eval(Recognizer *parser, RuleContext *parserCallStack) const override;\n    Ref<const SemanticContext> evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) const override;\n    size_t hashCode() const override;\n    bool equals(const SemanticContext &other) const override;\n    std::string toString() const override;\n  };\n\n  /**\n   * This is the base class for semantic context \"operators\", which operate on\n   * a collection of semantic context \"operands\".\n   *\n   * @since 4.3\n   */\n  class ANTLR4CPP_PUBLIC SemanticContext::Operator : public SemanticContext {\n  public:\n    static bool is(const SemanticContext &semanticContext) {\n      const auto contextType = semanticContext.getContextType();\n      return contextType == SemanticContextType::AND || contextType == SemanticContextType::OR;\n    }\n\n    static bool is(const SemanticContext *semanticContext) { return semanticContext != nullptr && is(*semanticContext); }\n\n    /**\n     * Gets the operands for the semantic context operator.\n     *\n     * @return a collection of {@link SemanticContext} operands for the\n     * operator.\n     *\n     * @since 4.3\n     */\n\n    virtual const std::vector<Ref<const SemanticContext>>& getOperands() const = 0;\n\n  protected:\n    using SemanticContext::SemanticContext;\n  };\n\n  /**\n   * A semantic context which is true whenever none of the contained contexts\n   * is false.\n   */\n  class ANTLR4CPP_PUBLIC SemanticContext::AND final : public SemanticContext::Operator {\n  public:\n    static bool is(const SemanticContext &semanticContext) { return semanticContext.getContextType() == SemanticContextType::AND; }\n\n    static bool is(const SemanticContext *semanticContext) { return semanticContext != nullptr && is(*semanticContext); }\n\n    AND(Ref<const SemanticContext> a, Ref<const SemanticContext> b) ;\n\n    const std::vector<Ref<const SemanticContext>>& getOperands() const override;\n\n    /**\n     * The evaluation of predicates by this context is short-circuiting, but\n     * unordered.</p>\n     */\n    bool eval(Recognizer *parser, RuleContext *parserCallStack) const override;\n    Ref<const SemanticContext> evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) const override;\n    size_t hashCode() const override;\n    bool equals(const SemanticContext &other) const override;\n    std::string toString() const override;\n\n  private:\n    std::vector<Ref<const SemanticContext>> _opnds;\n  };\n\n  /**\n   * A semantic context which is true whenever at least one of the contained\n   * contexts is true.\n   */\n  class ANTLR4CPP_PUBLIC SemanticContext::OR final : public SemanticContext::Operator {\n  public:\n    static bool is(const SemanticContext &semanticContext) { return semanticContext.getContextType() == SemanticContextType::OR; }\n\n    static bool is(const SemanticContext *semanticContext) { return semanticContext != nullptr && is(*semanticContext); }\n\n    OR(Ref<const SemanticContext> a, Ref<const SemanticContext> b);\n\n    const std::vector<Ref<const SemanticContext>>& getOperands() const override;\n\n    /**\n     * The evaluation of predicates by this context is short-circuiting, but\n     * unordered.\n     */\n    bool eval(Recognizer *parser, RuleContext *parserCallStack) const override;\n    Ref<const SemanticContext> evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) const override;\n    size_t hashCode() const override;\n    bool equals(const SemanticContext &other) const override;\n    std::string toString() const override;\n\n  private:\n    std::vector<Ref<const SemanticContext>> _opnds;\n  };\n\n}  // namespace atn\n}  // namespace antlr4\n\nnamespace std {\n\n  template <>\n  struct hash<::antlr4::atn::SemanticContext> {\n    size_t operator()(const ::antlr4::atn::SemanticContext &semanticContext) const {\n      return semanticContext.hashCode();\n    }\n  };\n\n}  // namespace std\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SemanticContextType.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  enum class SemanticContextType : size_t {\n    PREDICATE = 1,\n    PRECEDENCE = 2,\n    AND = 3,\n    OR = 4,\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SerializedATNView.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include <cstdint>\n#include <cstring>\n#include <iterator>\n#include <vector>\n\n#include \"antlr4-common.h\"\n#include \"misc/MurmurHash.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC SerializedATNView final {\n  public:\n    using value_type = int32_t;\n    using size_type = size_t;\n    using difference_type = ptrdiff_t;\n    using reference = int32_t&;\n    using const_reference = const int32_t&;\n    using pointer = int32_t*;\n    using const_pointer = const int32_t*;\n    using iterator = const_pointer;\n    using const_iterator = const_pointer;\n    using reverse_iterator = std::reverse_iterator<iterator>;\n    using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\n    SerializedATNView() = default;\n\n    SerializedATNView(const_pointer data, size_type size) : _data(data), _size(size) {}\n\n    SerializedATNView(const std::vector<int32_t> &serializedATN) : _data(serializedATN.data()), _size(serializedATN.size()) {}\n\n    SerializedATNView(const SerializedATNView&) = default;\n\n    SerializedATNView& operator=(const SerializedATNView&) = default;\n\n    const_iterator begin() const { return data(); }\n\n    const_iterator cbegin() const { return data(); }\n\n    const_iterator end() const { return data() + size(); }\n\n    const_iterator cend() const { return data() + size(); }\n\n    const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }\n\n    const_reverse_iterator crbegin() const { return const_reverse_iterator(cend()); }\n\n    const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }\n\n    const_reverse_iterator crend() const { return const_reverse_iterator(cbegin()); }\n\n    bool empty() const { return size() == 0; }\n\n    const_pointer data() const { return _data; }\n\n    size_type size() const { return _size; }\n\n    size_type size_bytes() const { return size() * sizeof(value_type); }\n\n    const_reference operator[](size_type index) const { return _data[index]; }\n\n  private:\n    const_pointer _data = nullptr;\n    size_type _size = 0;\n  };\n\n  inline bool operator==(const SerializedATNView &lhs, const SerializedATNView &rhs) {\n    return (lhs.data() == rhs.data() && lhs.size() == rhs.size()) ||\n           (lhs.size() == rhs.size() && std::memcmp(lhs.data(), rhs.data(), lhs.size_bytes()) == 0);\n  }\n\n  inline bool operator!=(const SerializedATNView &lhs, const SerializedATNView &rhs) {\n    return !operator==(lhs, rhs);\n  }\n\n  inline bool operator<(const SerializedATNView &lhs, const SerializedATNView &rhs) {\n    int diff = std::memcmp(lhs.data(), rhs.data(), std::min(lhs.size_bytes(), rhs.size_bytes()));\n    return diff < 0 || (diff == 0 && lhs.size() < rhs.size());\n  }\n\n}  // namespace atn\n}  // namespace antlr4\n\nnamespace std {\n\n  template <>\n  struct hash<::antlr4::atn::SerializedATNView> {\n    size_t operator()(const ::antlr4::atn::SerializedATNView &serializedATNView) const {\n      return ::antlr4::misc::MurmurHash::hashCode(serializedATNView.data(), serializedATNView.size());\n    }\n  };\n\n}  // namespace std\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SetTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"Token.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"misc/IntervalSet.h\"\n\n#include \"atn/SetTransition.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\n\nSetTransition::SetTransition(TransitionType transitionType, ATNState *target, misc::IntervalSet aSet)\n  : Transition(transitionType, target), set(aSet.isEmpty() ? misc::IntervalSet::of(Token::INVALID_TYPE) : std::move(aSet)) {\n}\n\nmisc::IntervalSet SetTransition::label() const {\n  return set;\n}\n\nbool SetTransition::matches(size_t symbol, size_t /*minVocabSymbol*/, size_t /*maxVocabSymbol*/) const {\n  return set.contains(symbol);\n}\n\nstd::string SetTransition::toString() const {\n  return \"SET \" + Transition::toString() + \" { set: \" + set.toString() + \"}\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SetTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// A transition containing a set of values. </summary>\n  class ANTLR4CPP_PUBLIC SetTransition : public Transition {\n  public:\n    static bool is(const Transition &transition) {\n      const auto transitionType = transition.getTransitionType();\n      return transitionType == TransitionType::SET || transitionType == TransitionType::NOT_SET;\n    }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    const misc::IntervalSet set;\n\n    SetTransition(ATNState *target, misc::IntervalSet set) : SetTransition(TransitionType::SET, target, std::move(set)) {}\n\n    misc::IntervalSet label() const override;\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n\n  protected:\n    SetTransition(TransitionType transitionType, ATNState *target, misc::IntervalSet set);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SingletonPredictionContext.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cassert>\n#include <memory>\n#include <utility>\n#include <string>\n#include <cstddef>\n#include \"atn/SingletonPredictionContext.h\"\n\n#include \"antlr4-common.h\"\n#include \"support/Casts.h\"\n#include \"misc/MurmurHash.h\"\n#include \"atn/HashUtils.h\"\n\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nSingletonPredictionContext::SingletonPredictionContext(Ref<const PredictionContext> parent, size_t returnState)\n    : PredictionContext(PredictionContextType::SINGLETON), parent(std::move(parent)), returnState(returnState) {\n  assert(returnState != ATNState::INVALID_STATE_NUMBER);\n}\n\nRef<const SingletonPredictionContext> SingletonPredictionContext::create(Ref<const PredictionContext> parent, size_t returnState) {\n  if (returnState == EMPTY_RETURN_STATE && parent == nullptr) {\n    // someone can pass in the bits of an array ctx that mean $\n    return std::dynamic_pointer_cast<const SingletonPredictionContext>(EMPTY);\n  }\n  return std::make_shared<SingletonPredictionContext>(std::move(parent), returnState);\n}\n\nbool SingletonPredictionContext::isEmpty() const {\n  return parent == nullptr && returnState == EMPTY_RETURN_STATE;\n}\n\nsize_t SingletonPredictionContext::size() const {\n  return 1;\n}\n\nconst Ref<const PredictionContext>& SingletonPredictionContext::getParent(size_t index) const {\n  assert(index == 0);\n  static_cast<void>(index);\n  return parent;\n}\n\nsize_t SingletonPredictionContext::getReturnState(size_t index) const {\n  assert(index == 0);\n  static_cast<void>(index);\n  return returnState;\n}\n\nsize_t SingletonPredictionContext::hashCodeImpl() const {\n  size_t hash = misc::MurmurHash::initialize();\n  hash = misc::MurmurHash::update(hash, static_cast<size_t>(getContextType()));\n  hash = misc::MurmurHash::update(hash, parent);\n  hash = misc::MurmurHash::update(hash, returnState);\n  return misc::MurmurHash::finish(hash, 3);\n}\n\nbool SingletonPredictionContext::equals(const PredictionContext &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  if (getContextType() != other.getContextType()) {\n    return false;\n  }\n  const auto &singleton = downCast<const SingletonPredictionContext&>(other);\n  return returnState == singleton.returnState &&\n         cachedHashCodeEqual(cachedHashCode(), singleton.cachedHashCode()) &&\n         (parent == singleton.parent || (parent != nullptr && singleton.parent != nullptr && *parent == *singleton.parent));\n}\n\nstd::string SingletonPredictionContext::toString() const {\n  //std::string up = !parent.expired() ? parent.lock()->toString() : \"\";\n  std::string up = parent != nullptr ? parent->toString() : \"\";\n  if (up.length() == 0) {\n    if (returnState == EMPTY_RETURN_STATE) {\n      return \"$\";\n    }\n    return std::to_string(returnState);\n  }\n  return std::to_string(returnState) + \" \" + up;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/SingletonPredictionContext.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/PredictionContext.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC SingletonPredictionContext final : public PredictionContext {\n  public:\n    static bool is(const PredictionContext &predictionContext) { return predictionContext.getContextType() == PredictionContextType::SINGLETON; }\n\n    static bool is(const PredictionContext *predictionContext) { return predictionContext != nullptr && is(*predictionContext); }\n\n    static Ref<const SingletonPredictionContext> create(Ref<const PredictionContext> parent, size_t returnState);\n\n    // Usually a parent is linked via a weak ptr. Not so here as we have kinda reverse reference chain.\n    // There are no child contexts stored here and often the parent context is left dangling when it's\n    // owning ATNState is released. In order to avoid having this context released as well (leaving all other contexts\n    // which got this one as parent with a null reference) we use a shared_ptr here instead, to keep those left alone\n    // parent contexts alive.\n    const Ref<const PredictionContext> parent;\n    const size_t returnState;\n\n    SingletonPredictionContext(Ref<const PredictionContext> parent, size_t returnState);\n\n    bool isEmpty() const override;\n    size_t size() const override;\n    const Ref<const PredictionContext>& getParent(size_t index) const override;\n    size_t getReturnState(size_t index) const override;\n    bool equals(const PredictionContext &other) const override;\n    std::string toString() const override;\n\n  protected:\n    size_t hashCodeImpl() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/StarBlockStartState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/BlockStartState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// The block that begins a closure loop.\n  class ANTLR4CPP_PUBLIC StarBlockStartState final : public BlockStartState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::STAR_BLOCK_START; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    StarBlockStartState() : BlockStartState(ATNStateType::STAR_BLOCK_START) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/StarLoopEntryState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/DecisionState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC StarLoopEntryState final : public DecisionState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::STAR_LOOP_ENTRY; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    /**\n     * Indicates whether this state can benefit from a precedence DFA during SLL\n     * decision making.\n     *\n     * <p>This is a computed property that is calculated during ATN deserialization\n     * and stored for use in {@link ParserATNSimulator} and\n     * {@link ParserInterpreter}.</p>\n     *\n     * @see DFA#isPrecedenceDfa()\n     */\n    bool isPrecedenceDecision = false;\n\n    StarLoopbackState *loopBackState = nullptr;\n\n    StarLoopEntryState() : DecisionState(ATNStateType::STAR_LOOP_ENTRY) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/StarLoopbackState.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"atn/StarLoopEntryState.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/Transition.h\"\n#include \"support/Casts.h\"\n\n#include \"atn/StarLoopbackState.h\"\n\nusing namespace antlr4::atn;\n\nStarLoopEntryState *StarLoopbackState::getLoopEntryState() const {\n  if (transitions[0]->target != nullptr && transitions[0]->target->getStateType() == ATNStateType::STAR_LOOP_ENTRY) {\n    return antlrcpp::downCast<StarLoopEntryState*>(transitions[0]->target);\n  }\n  return nullptr;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/StarLoopbackState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC StarLoopbackState final : public ATNState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::STAR_LOOP_BACK; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    StarLoopbackState() : ATNState(ATNStateType::STAR_LOOP_BACK) {}\n\n    StarLoopEntryState *getLoopEntryState() const;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/TokensStartState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"atn/ATNStateType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/DecisionState.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// The Tokens rule start state linking to each lexer rule start state.\n  class ANTLR4CPP_PUBLIC TokensStartState final : public DecisionState {\n  public:\n    static bool is(const ATNState &atnState) { return atnState.getStateType() == ATNStateType::TOKEN_START; }\n\n    static bool is(const ATNState *atnState) { return atnState != nullptr && is(*atnState); }\n\n    TokensStartState() : DecisionState(ATNStateType::TOKEN_START) {}\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/Transition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include \"Exceptions.h\"\n#include \"misc/IntervalSet.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"support/Arrays.h\"\n\n#include \"atn/Transition.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::atn;\nusing namespace antlrcpp;\n\nTransition::Transition(TransitionType transitionType, ATNState *target) : _transitionType(transitionType) {\n  if (target == nullptr) {\n    throw NullPointerException(\"target cannot be null.\");\n  }\n\n  this->target = target;\n}\n\nbool Transition::isEpsilon() const {\n  return false;\n}\n\nmisc::IntervalSet Transition::label() const {\n  return misc::IntervalSet::EMPTY_SET;\n}\n\nstd::string Transition::toString() const {\n  std::stringstream ss;\n  ss << \"(Transition \" << std::hex << this << \", target: \" << std::hex << target << ')';\n\n  return ss.str();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/Transition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <string>\n#include <cstddef>\n#include \"misc/IntervalSet.h\"\n#include \"atn/ATNState.h\"\n#include \"antlr4-common.h\"\n#include \"atn/TransitionType.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  /// <summary>\n  /// An ATN transition between any two ATN states.  Subclasses define\n  ///  atom, set, epsilon, action, predicate, rule transitions.\n  /// <p/>\n  ///  This is a one way link.  It emanates from a state (usually via a list of\n  ///  transitions) and has a target state.\n  /// <p/>\n  ///  Since we never have to change the ATN transitions once we construct it,\n  ///  we can fix these transitions as specific classes. The DFA transitions\n  ///  on the other hand need to update the labels as it adds transitions to\n  ///  the states. We'll use the term Edge for the DFA to distinguish them from\n  ///  ATN transitions.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC Transition {\n  public:\n    /// The target of this transition.\n    // ml: this is a reference into the ATN.\n    ATNState *target;\n\n    virtual ~Transition() = default;\n\n    TransitionType getTransitionType() const { return _transitionType; }\n\n    /**\n     * Determines if the transition is an \"epsilon\" transition.\n     *\n     * <p>The default implementation returns {@code false}.</p>\n     *\n     * @return {@code true} if traversing this transition in the ATN does not\n     * consume an input symbol; otherwise, {@code false} if traversing this\n     * transition consumes (matches) an input symbol.\n     */\n    virtual bool isEpsilon() const;\n    virtual misc::IntervalSet label() const;\n    virtual bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const = 0;\n\n    virtual std::string toString() const;\n\n    Transition(Transition const&) = delete;\n    Transition& operator=(Transition const&) = delete;\n\n  protected:\n    Transition(TransitionType transitionType, ATNState *target);\n\n  private:\n    const TransitionType _transitionType;\n  };\n\n  using ConstTransitionPtr = std::unique_ptr<const Transition>;\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/TransitionType.cpp",
    "content": "#include <string>\n#include \"atn/TransitionType.h\"\n\nstd::string antlr4::atn::transitionTypeName(TransitionType transitionType) {\n  switch (transitionType) {\n    case TransitionType::EPSILON:\n      return \"EPSILON\";\n    case TransitionType::RANGE:\n      return \"RANGE\";\n    case TransitionType::RULE:\n      return \"RULE\";\n    case TransitionType::PREDICATE:\n      return \"PREDICATE\";\n    case TransitionType::ATOM:\n      return \"ATOM\";\n    case TransitionType::ACTION:\n      return \"ACTION\";\n    case TransitionType::SET:\n      return \"SET\";\n    case TransitionType::NOT_SET:\n      return \"NOT_SET\";\n    case TransitionType::WILDCARD:\n      return \"WILDCARD\";\n    case TransitionType::PRECEDENCE:\n      return \"PRECEDENCE\";\n  }\n  return \"UNKNOWN\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/TransitionType.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n#include <string>\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  // Constants for transition serialization.\n  enum class TransitionType : size_t {\n    EPSILON = 1,\n    RANGE = 2,\n    RULE = 3,\n    PREDICATE = 4, // e.g., {isType(input.LT(1))}?\n    ATOM = 5,\n    ACTION = 6,\n    SET = 7, // ~(A|B) or ~atom, wildcard, which convert to next 2\n    NOT_SET = 8,\n    WILDCARD = 9,\n    PRECEDENCE = 10,\n  };\n\n  ANTLR4CPP_PUBLIC std::string transitionTypeName(TransitionType transitionType);\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/WildcardTransition.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"atn/ATNState.h\"\n\n#include \"atn/TransitionType.h\"\n#include \"atn/WildcardTransition.h\"\n\nusing namespace antlr4::atn;\n\nWildcardTransition::WildcardTransition(ATNState *target) : Transition(TransitionType::WILDCARD, target) {\n}\n\nbool WildcardTransition::matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const {\n  return symbol >= minVocabSymbol && symbol <= maxVocabSymbol;\n}\n\nstd::string WildcardTransition::toString() const {\n  return \"WILDCARD \" + Transition::toString() + \" {}\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/atn/WildcardTransition.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"atn/TransitionType.h\"\n#include \"atn/ATNState.h\"\n#include \"atn/Transition.h\"\n\nnamespace antlr4 {\nnamespace atn {\n\n  class ANTLR4CPP_PUBLIC WildcardTransition final : public Transition {\n  public:\n    static bool is(const Transition &transition) { return transition.getTransitionType() == TransitionType::WILDCARD; }\n\n    static bool is(const Transition *transition) { return transition != nullptr && is(*transition); }\n\n    explicit WildcardTransition(ATNState *target);\n\n    bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override;\n\n    std::string toString() const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/DFA.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cassert>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"dfa/DFASerializer.h\"\n#include \"dfa/LexerDFASerializer.h\"\n#include \"support/CPPUtils.h\"\n#include \"atn/StarLoopEntryState.h\"\n#include \"atn/ATNConfigSet.h\"\n#include \"support/Casts.h\"\n\n#include \"dfa/DFA.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::dfa;\nusing namespace antlrcpp;\n\nDFA::DFA(atn::DecisionState *atnStartState) : DFA(atnStartState, 0) {\n}\n\nDFA::DFA(atn::DecisionState *atnStartState, size_t decision)\n  : atnStartState(atnStartState), s0(nullptr), decision(decision) {\n\n  _precedenceDfa = false;\n  if (atn::StarLoopEntryState::is(atnStartState)) {\n    if (downCast<atn::StarLoopEntryState*>(atnStartState)->isPrecedenceDecision) {\n      _precedenceDfa = true;\n      s0 = new DFAState(std::unique_ptr<atn::ATNConfigSet>(new atn::ATNConfigSet()));\n      s0->isAcceptState = false;\n      s0->requiresFullContext = false;\n    }\n  }\n}\n\nDFA::DFA(DFA &&other) : atnStartState(other.atnStartState), s0(other.s0), decision(other.decision) {\n  // Source states are implicitly cleared by the move.\n  states = std::move(other.states);\n\n  other.atnStartState = nullptr;\n  other.decision = 0;\n  other.s0 = nullptr;\n  _precedenceDfa = other._precedenceDfa;\n  other._precedenceDfa = false;\n}\n\nDFA::~DFA() {\n  bool s0InList = (s0 == nullptr);\n  for (auto *state : states) {\n    if (state == s0)\n      s0InList = true;\n    delete state;\n  }\n\n  if (!s0InList) {\n    delete s0;\n  }\n}\n\nbool DFA::isPrecedenceDfa() const {\n  return _precedenceDfa;\n}\n\nDFAState* DFA::getPrecedenceStartState(int precedence) const {\n  assert(_precedenceDfa); // Only precedence DFAs may contain a precedence start state.\n\n  auto iterator = s0->edges.find(precedence);\n  if (iterator == s0->edges.end())\n    return nullptr;\n\n  return iterator->second;\n}\n\nvoid DFA::setPrecedenceStartState(int precedence, DFAState *startState) {\n  if (!isPrecedenceDfa()) {\n    throw IllegalStateException(\"Only precedence DFAs may contain a precedence start state.\");\n  }\n\n  if (precedence < 0) {\n    return;\n  }\n\n  s0->edges[precedence] = startState;\n}\n\nstd::vector<DFAState *> DFA::getStates() const {\n  std::vector<DFAState *> result;\n  for (auto *state : states)\n    result.push_back(state);\n\n  std::sort(result.begin(), result.end(), [](DFAState *o1, DFAState *o2) -> bool {\n    return o1->stateNumber < o2->stateNumber;\n  });\n\n  return result;\n}\n\nstd::string DFA::toString(const Vocabulary &vocabulary) const {\n  if (s0 == nullptr) {\n    return \"\";\n  }\n\n  DFASerializer serializer(this, vocabulary);\n  return serializer.toString();\n}\n\nstd::string DFA::toLexerString() const {\n  if (s0 == nullptr) {\n    return \"\";\n  }\n  LexerDFASerializer serializer(this);\n\n  return serializer.toString();\n}\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/DFA.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <unordered_set>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"dfa/DFAState.h\"\n\nnamespace antlr4 {\nnamespace dfa {\n\n  class ANTLR4CPP_PUBLIC DFA final {\n  private:\n    struct DFAStateHasher final {\n      size_t operator()(const DFAState *dfaState) const {\n        return dfaState->hashCode();\n      }\n    };\n\n    struct DFAStateComparer final {\n      bool operator()(const DFAState *lhs, const DFAState *rhs) const {\n        return lhs == rhs || *lhs == *rhs;\n      }\n    };\n\n  public:\n    /// A set of all DFA states. Use a map so we can get old state back.\n    /// Set only allows you to see if it's there.\n\n    /// From which ATN state did we create this DFA?\n    atn::DecisionState *atnStartState;\n    std::unordered_set<DFAState*, DFAStateHasher, DFAStateComparer> states; // States are owned by this class.\n    DFAState *s0;\n    size_t decision;\n\n    explicit DFA(atn::DecisionState *atnStartState);\n    DFA(atn::DecisionState *atnStartState, size_t decision);\n    DFA(const DFA &other) = delete;\n    DFA(DFA &&other);\n    ~DFA();\n\n    /**\n     * Gets whether this DFA is a precedence DFA. Precedence DFAs use a special\n     * start state {@link #s0} which is not stored in {@link #states}. The\n     * {@link DFAState#edges} array for this start state contains outgoing edges\n     * supplying individual start states corresponding to specific precedence\n     * values.\n     *\n     * @return {@code true} if this is a precedence DFA; otherwise,\n     * {@code false}.\n     * @see Parser#getPrecedence()\n     */\n    bool isPrecedenceDfa() const;\n\n    /**\n     * Get the start state for a specific precedence value.\n     *\n     * @param precedence The current precedence.\n     * @return The start state corresponding to the specified precedence, or\n     * {@code null} if no start state exists for the specified precedence.\n     *\n     * @throws IllegalStateException if this is not a precedence DFA.\n     * @see #isPrecedenceDfa()\n     */\n    DFAState* getPrecedenceStartState(int precedence) const;\n\n    /**\n     * Set the start state for a specific precedence value.\n     *\n     * @param precedence The current precedence.\n     * @param startState The start state corresponding to the specified\n     * precedence.\n     *\n     * @throws IllegalStateException if this is not a precedence DFA.\n     * @see #isPrecedenceDfa()\n     */\n    void setPrecedenceStartState(int precedence, DFAState *startState);\n\n    /// Return a list of all states in this DFA, ordered by state number.\n    std::vector<DFAState *> getStates() const;\n\n    std::string toString(const Vocabulary &vocabulary) const;\n\n    std::string toLexerString() const;\n\n  private:\n    /**\n     * {@code true} if this DFA is for a precedence decision; otherwise,\n     * {@code false}. This is the backing field for {@link #isPrecedenceDfa}.\n     */\n    bool _precedenceDfa;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/DFASerializer.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"dfa/DFA.h\"\n#include \"Vocabulary.h\"\n\n#include \"dfa/DFASerializer.h\"\n\nusing namespace antlr4::dfa;\n\nDFASerializer::DFASerializer(const DFA *dfa, const Vocabulary &vocabulary) : _dfa(dfa), _vocabulary(vocabulary) {\n}\n\nstd::string DFASerializer::toString() const {\n  if (_dfa->s0 == nullptr) {\n    return \"\";\n  }\n\n  std::stringstream ss;\n  std::vector<DFAState *> states = _dfa->getStates();\n  for (auto *s : states) {\n    for (size_t i = 0; i < s->edges.size(); i++) {\n      DFAState *t = s->edges[i];\n      if (t != nullptr && t->stateNumber != INT32_MAX) {\n        ss << getStateString(s);\n        std::string label = getEdgeLabel(i);\n        ss << \"-\" << label << \"->\" << getStateString(t) << \"\\n\";\n      }\n    }\n  }\n\n  return ss.str();\n}\n\nstd::string DFASerializer::getEdgeLabel(size_t i) const {\n  return _vocabulary.getDisplayName(i); // ml: no longer needed -1 as we use a map for edges, without offset.\n}\n\nstd::string DFASerializer::getStateString(DFAState *s) const {\n  size_t n = s->stateNumber;\n\n  const std::string baseStateStr = std::string(s->isAcceptState ? \":\" : \"\") + \"s\" + std::to_string(n) +\n    (s->requiresFullContext ? \"^\" : \"\");\n\n  if (s->isAcceptState) {\n    if (!s->predicates.empty()) {\n      std::string buf;\n      for (size_t i = 0; i < s->predicates.size(); i++) {\n        buf.append(s->predicates[i].toString());\n      }\n      return baseStateStr + \"=>\" + buf;\n    } else {\n      return baseStateStr + \"=>\" + std::to_string(s->prediction);\n    }\n  } else {\n    return baseStateStr;\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/DFASerializer.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Vocabulary.h\"\n\nnamespace antlr4 {\nnamespace dfa {\n\n  /// A DFA walker that knows how to dump them to serialized strings.\n  class ANTLR4CPP_PUBLIC DFASerializer {\n  public:\n    DFASerializer(const DFA *dfa, const Vocabulary &vocabulary);\n\n    virtual ~DFASerializer() = default;\n\n    std::string toString() const;\n\n  protected:\n    virtual std::string getEdgeLabel(size_t i) const;\n    std::string getStateString(DFAState *s) const;\n\n  private:\n    const DFA *_dfa;\n    const Vocabulary &_vocabulary;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/DFAState.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <sstream>\n#include <string>\n#include <cstddef>\n#include \"atn/ATNConfigSet.h\"\n#include \"atn/SemanticContext.h\"\n#include \"atn/ATNConfig.h\"\n#include \"misc/MurmurHash.h\"\n\n#include \"dfa/DFAState.h\"\n\nusing namespace antlr4::dfa;\nusing namespace antlr4::atn;\n\nstd::string DFAState::PredPrediction::toString() const {\n  return std::string(\"(\") + pred->toString() + \", \" + std::to_string(alt) + \")\";\n}\n\nstd::set<size_t> DFAState::getAltSet() const {\n  std::set<size_t> alts;\n  if (configs != nullptr) {\n    for (size_t i = 0; i < configs->size(); i++) {\n      alts.insert(configs->get(i)->alt);\n    }\n  }\n  return alts;\n}\n\nsize_t DFAState::hashCode() const {\n  return configs != nullptr ? configs->hashCode() : 0;\n}\n\nbool DFAState::equals(const DFAState &other) const {\n  if (this == std::addressof(other)) {\n    return true;\n  }\n  return configs == other.configs ||\n         (configs != nullptr && other.configs != nullptr && *configs == *other.configs);\n}\n\nstd::string DFAState::toString() const {\n  std::stringstream ss;\n  ss << stateNumber;\n  if (configs) {\n    ss << \":\" << configs->toString();\n  }\n  if (isAcceptState) {\n    ss << \"=>\";\n    if (!predicates.empty()) {\n      for (size_t i = 0; i < predicates.size(); i++) {\n        ss << predicates[i].toString();\n      }\n    } else {\n      ss << prediction;\n    }\n  }\n  return ss.str();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/DFAState.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\n#include \"atn/ATNConfigSet.h\"\n#include \"FlatHashMap.h\"\n\nnamespace antlr4 {\nnamespace dfa {\n\n  /// <summary>\n  /// A DFA state represents a set of possible ATN configurations.\n  ///  As Aho, Sethi, Ullman p. 117 says \"The DFA uses its state\n  ///  to keep track of all possible states the ATN can be in after\n  ///  reading each input symbol.  That is to say, after reading\n  ///  input a1a2..an, the DFA is in a state that represents the\n  ///  subset T of the states of the ATN that are reachable from the\n  ///  ATN's start state along some path labeled a1a2..an.\"\n  ///  In conventional NFA->DFA conversion, therefore, the subset T\n  ///  would be a bitset representing the set of states the\n  ///  ATN could be in.  We need to track the alt predicted by each\n  ///  state as well, however.  More importantly, we need to maintain\n  ///  a stack of states, tracking the closure operations as they\n  ///  jump from rule to rule, emulating rule invocations (method calls).\n  ///  I have to add a stack to simulate the proper lookahead sequences for\n  ///  the underlying LL grammar from which the ATN was derived.\n  /// <p/>\n  ///  I use a set of ATNConfig objects not simple states.  An ATNConfig\n  ///  is both a state (ala normal conversion) and a RuleContext describing\n  ///  the chain of rules (if any) followed to arrive at that state.\n  /// <p/>\n  ///  A DFA state may have multiple references to a particular state,\n  ///  but with different ATN contexts (with same or different alts)\n  ///  meaning that state was reached via a different set of rule invocations.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC DFAState final {\n  public:\n    struct ANTLR4CPP_PUBLIC PredPrediction final {\n    public:\n      Ref<const atn::SemanticContext> pred; // never null; at least SemanticContext.NONE\n      int alt;\n\n      PredPrediction() = delete;\n\n      PredPrediction(const PredPrediction&) = default;\n      PredPrediction(PredPrediction&&) = default;\n\n      PredPrediction(Ref<const atn::SemanticContext> pred, int alt) : pred(std::move(pred)), alt(alt) {}\n\n      PredPrediction& operator=(const PredPrediction&) = default;\n      PredPrediction& operator=(PredPrediction&&) = default;\n\n      std::string toString() const;\n    };\n\n    std::unique_ptr<atn::ATNConfigSet> configs;\n\n    /// {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)\n    ///  <seealso cref=\"Token#EOF\"/> maps to {@code edges[0]}.\n    // ml: this is a sparse list, so we use a map instead of a vector.\n    //     Watch out: we no longer have the -1 offset, as it isn't needed anymore.\n    FlatHashMap<size_t, DFAState*> edges;\n\n    /// if accept state, what ttype do we match or alt do we predict?\n    /// This is set to <seealso cref=\"ATN#INVALID_ALT_NUMBER\"/> when <seealso cref=\"#predicates\"/>{@code !=null} or\n    /// <seealso cref=\"#requiresFullContext\"/>.\n    size_t prediction = 0;\n\n    Ref<const atn::LexerActionExecutor> lexerActionExecutor;\n\n    /// <summary>\n    /// During SLL parsing, this is a list of predicates associated with the\n    ///  ATN configurations of the DFA state. When we have predicates,\n    ///  <seealso cref=\"#requiresFullContext\"/> is {@code false} since full context prediction evaluates predicates\n    ///  on-the-fly. If this is not null, then <seealso cref=\"#prediction\"/> is\n    ///  <seealso cref=\"ATN#INVALID_ALT_NUMBER\"/>.\n    /// <p/>\n    ///  We only use these for non-<seealso cref=\"#requiresFullContext\"/> but conflicting states. That\n    ///  means we know from the context (it's $ or we don't dip into outer\n    ///  context) that it's an ambiguity not a conflict.\n    /// <p/>\n    ///  This list is computed by <seealso cref=\"ParserATNSimulator#predicateDFAState\"/>.\n    /// </summary>\n    std::vector<PredPrediction> predicates;\n\n    int stateNumber = -1;\n\n    bool isAcceptState = false;\n\n    /// <summary>\n    /// Indicates that this state was created during SLL prediction that\n    /// discovered a conflict between the configurations in the state. Future\n    /// <seealso cref=\"ParserATNSimulator#execATN\"/> invocations immediately jumped doing\n    /// full context prediction if this field is true.\n    /// </summary>\n    bool requiresFullContext = false;\n\n    /// Map a predicate to a predicted alternative.\n    DFAState() = default;\n\n    explicit DFAState(int stateNumber) : stateNumber(stateNumber) {}\n\n    explicit DFAState(std::unique_ptr<atn::ATNConfigSet> configs) : configs(std::move(configs)) {}\n\n    /// <summary>\n    /// Get the set of all alts mentioned by all ATN configurations in this\n    ///  DFA state.\n    /// </summary>\n    std::set<size_t> getAltSet() const;\n\n    size_t hashCode() const;\n\n    /// Two DFAState instances are equal if their ATN configuration sets\n    /// are the same. This method is used to see if a state already exists.\n    ///\n    /// Because the number of alternatives and number of ATN configurations are\n    /// finite, there is a finite number of DFA states that can be processed.\n    /// This is necessary to show that the algorithm terminates.\n    ///\n    /// Cannot test the DFA state numbers here because in\n    /// ParserATNSimulator#addDFAState we need to know if any other state\n    /// exists that has this exact set of ATN configurations. The\n    /// stateNumber is irrelevant.\n    bool equals(const DFAState &other) const;\n\n    std::string toString() const;\n  };\n\n  inline bool operator==(const DFAState &lhs, const DFAState &rhs) {\n    return lhs.equals(rhs);\n  }\n\n  inline bool operator!=(const DFAState &lhs, const DFAState &rhs) {\n    return !operator==(lhs, rhs);\n  }\n\n}  // namespace dfa\n}  // namespace antlr4\n\nnamespace std {\n\n  template <>\n  struct hash<::antlr4::dfa::DFAState> {\n    size_t operator()(const ::antlr4::dfa::DFAState &dfaState) const {\n      return dfaState.hashCode();\n    }\n  };\n\n}  // namespace std\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/LexerDFASerializer.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"Vocabulary.h\"\n\n#include \"dfa/LexerDFASerializer.h\"\n\nusing namespace antlr4::dfa;\n\nLexerDFASerializer::LexerDFASerializer(const DFA *dfa) : DFASerializer(dfa, Vocabulary()) {\n}\n\nstd::string LexerDFASerializer::getEdgeLabel(size_t i) const {\n  return std::string(\"'\") + static_cast<char>(i) + \"'\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/dfa/LexerDFASerializer.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"dfa/DFASerializer.h\"\n\nnamespace antlr4 {\nnamespace dfa {\n\n  class ANTLR4CPP_PUBLIC LexerDFASerializer final : public DFASerializer {\n  public:\n    explicit LexerDFASerializer(const DFA *dfa);\n\n  protected:\n    std::string getEdgeLabel(size_t i) const override;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/internal/Synchronization.cpp",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"antlr4-common.h\"\n#include \"internal/Synchronization.h\"\n\nusing namespace antlr4::internal;\n\nvoid Mutex::lock() {\n#if ANTLR4CPP_USING_ABSEIL\n  _impl.Lock();\n#else\n  _impl.lock();\n#endif\n}\n\nbool Mutex::try_lock() {\n#if ANTLR4CPP_USING_ABSEIL\n  return _impl.TryLock();\n#else\n  return _impl.try_lock();\n#endif\n}\n\nvoid Mutex::unlock() {\n#if ANTLR4CPP_USING_ABSEIL\n  _impl.Unlock();\n#else\n  _impl.unlock();\n#endif\n}\n\nvoid SharedMutex::lock() {\n#if ANTLR4CPP_USING_ABSEIL\n  _impl.WriterLock();\n#else\n  _impl.lock();\n#endif\n}\n\nbool SharedMutex::try_lock() {\n#if ANTLR4CPP_USING_ABSEIL\n  return _impl.WriterTryLock();\n#else\n  return _impl.try_lock();\n#endif\n}\n\nvoid SharedMutex::unlock() {\n#if ANTLR4CPP_USING_ABSEIL\n  _impl.WriterUnlock();\n#else\n  _impl.unlock();\n#endif\n}\n\nvoid SharedMutex::lock_shared() {\n#if ANTLR4CPP_USING_ABSEIL\n  _impl.ReaderLock();\n#else\n  _impl.lock_shared();\n#endif\n}\n\nbool SharedMutex::try_lock_shared() {\n#if ANTLR4CPP_USING_ABSEIL\n  return _impl.ReaderTryLock();\n#else\n  return _impl.try_lock_shared();\n#endif\n}\n\nvoid SharedMutex::unlock_shared() {\n#if ANTLR4CPP_USING_ABSEIL\n  _impl.ReaderUnlock();\n#else\n  _impl.unlock_shared();\n#endif\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/internal/Synchronization.h",
    "content": "// Copyright 2012-2022 The ANTLR Project\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\n#include <mutex>\n#include <shared_mutex>\n#include <utility>\n\n#if ANTLR4CPP_USING_ABSEIL\n#include \"absl/base/call_once.h\"\n#include \"absl/base/thread_annotations.h\"\n#include \"absl/synchronization/mutex.h\"\n#define ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS ABSL_NO_THREAD_SAFETY_ANALYSIS\n#else\n#define ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS\n#endif\n\n// By default ANTLRv4 uses synchronization primitives provided by the C++ standard library. In most\n// deployments this is fine, however in some using custom synchronization primitives may be\n// preferred. This header allows that by optionally supporting some alternative implementations and\n// allowing for more easier patching of other alternatives.\n\nnamespace antlr4::internal {\n\n  // Must be compatible with C++ standard library Mutex requirement.\n  class ANTLR4CPP_PUBLIC Mutex final {\n  public:\n    Mutex() = default;\n\n    // No copying or moving, we are as strict as possible to support other implementations.\n    Mutex(const Mutex&) = delete;\n    Mutex(Mutex&&) = delete;\n\n    // No copying or moving, we are as strict as possible to support other implementations.\n    Mutex& operator=(const Mutex&) = delete;\n    Mutex& operator=(Mutex&&) = delete;\n\n    void lock() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n    bool try_lock() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n    void unlock() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n  private:\n#if ANTLR4CPP_USING_ABSEIL\n    absl::Mutex _impl;\n#else\n    std::mutex _impl;\n#endif\n  };\n\n  template <typename Mutex>\n  using UniqueLock = std::unique_lock<Mutex>;\n\n  // Must be compatible with C++ standard library SharedMutex requirement.\n  class ANTLR4CPP_PUBLIC SharedMutex final {\n  public:\n    SharedMutex() = default;\n\n    // No copying or moving, we are as strict as possible to support other implementations.\n    SharedMutex(const SharedMutex&) = delete;\n    SharedMutex(SharedMutex&&) = delete;\n\n    // No copying or moving, we are as strict as possible to support other implementations.\n    SharedMutex& operator=(const SharedMutex&) = delete;\n    SharedMutex& operator=(SharedMutex&&) = delete;\n\n    void lock() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n    bool try_lock() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n    void unlock() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n    void lock_shared() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n    bool try_lock_shared() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n    void unlock_shared() ANTLR4CPP_NO_THREAD_SAFTEY_ANALYSIS;\n\n  private:\n#if ANTLR4CPP_USING_ABSEIL\n    absl::Mutex _impl;\n#else\n    std::shared_mutex _impl;\n#endif\n  };\n\n  template <typename Mutex>\n  using SharedLock = std::shared_lock<Mutex>;\n\n  class OnceFlag;\n\n  template <typename Callable, typename... Args>\n  void call_once(OnceFlag &onceFlag, Callable &&callable, Args&&... args);\n\n  // Must be compatible with std::once_flag.\n  class ANTLR4CPP_PUBLIC OnceFlag final {\n  public:\n    constexpr OnceFlag() = default;\n\n    // No copying or moving, we are as strict as possible to support other implementations.\n    OnceFlag(const OnceFlag&) = delete;\n    OnceFlag(OnceFlag&&) = delete;\n\n    // No copying or moving, we are as strict as possible to support other implementations.\n    OnceFlag& operator=(const OnceFlag&) = delete;\n    OnceFlag& operator=(OnceFlag&&) = delete;\n\n  private:\n    template <typename Callable, typename... Args>\n    friend void call_once(OnceFlag &onceFlag, Callable &&callable, Args&&... args);\n\n#if ANTLR4CPP_USING_ABSEIL\n    absl::once_flag _impl;\n#else\n    std::once_flag _impl;\n#endif\n  };\n\n  template <typename Callable, typename... Args>\n  void call_once(OnceFlag &onceFlag, Callable &&callable, Args&&... args) {\n#if ANTLR4CPP_USING_ABSEIL\n    absl::call_once(onceFlag._impl, std::forward<Callable>(callable), std::forward<Args>(args)...);\n#else\n    std::call_once(onceFlag._impl, std::forward<Callable>(callable), std::forward<Args>(args)...);\n#endif\n  }\n\n}  // namespace antlr4::internal\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/InterpreterDataReader.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <cassert>\n#include <vector>\n#include <string>\n#include \"atn/ATN.h\"\n#include \"atn/ATNDeserializer.h\"\n#include \"Vocabulary.h\"\n\n#include \"misc/InterpreterDataReader.h\"\n\nusing namespace antlr4::dfa;\nusing namespace antlr4::atn;\nusing namespace antlr4::misc;\n\nInterpreterData::InterpreterData(std::vector<std::string> const& literalNames, std::vector<std::string> const& symbolicNames)\n: vocabulary(literalNames, symbolicNames) {\n}\n\nInterpreterData InterpreterDataReader::parseFile(std::string const& fileName) {\n  // The structure of the data file is very simple. Everything is line based with empty lines\n  // separating the different parts. For lexers the layout is:\n  // token literal names:\n  // ...\n  //\n  // token symbolic names:\n  // ...\n  //\n  // rule names:\n  // ...\n  //\n  // channel names:\n  // ...\n  //\n  // mode names:\n  // ...\n  //\n  // atn:\n  // <a single line with comma separated int values> enclosed in a pair of squared brackets.\n  //\n  // Data for a parser does not contain channel and mode names.\n\n  std::ifstream input(fileName);\n  if (!input.good())\n    return {};\n\n  std::vector<std::string> literalNames;\n  std::vector<std::string> symbolicNames;\n\n  std::string line;\n\n  std::getline(input, line, '\\n');\n  assert(line == \"token literal names:\");\n  while (true) {\n    std::getline(input, line, '\\n');\n    if (line.empty())\n      break;\n\n    literalNames.push_back(line == \"null\" ? \"\" : line);\n  };\n\n  std::getline(input, line, '\\n');\n  assert(line == \"token symbolic names:\");\n  while (true) {\n    std::getline(input, line, '\\n');\n    if (line.empty())\n      break;\n\n    symbolicNames.push_back(line == \"null\" ? \"\" : line);\n  };\n  InterpreterData result(literalNames, symbolicNames);\n\n  std::getline(input, line, '\\n');\n  assert(line == \"rule names:\");\n  while (true) {\n    std::getline(input, line, '\\n');\n    if (line.empty())\n      break;\n\n    result.ruleNames.push_back(line);\n  };\n\n  std::getline(input, line, '\\n');\n  if (line == \"channel names:\") {\n    while (true) {\n      std::getline(input, line, '\\n');\n      if (line.empty())\n        break;\n\n      result.channels.push_back(line);\n    };\n\n    std::getline(input, line, '\\n');\n    assert(line == \"mode names:\");\n    while (true) {\n      std::getline(input, line, '\\n');\n      if (line.empty())\n        break;\n\n      result.modes.push_back(line);\n    };\n  }\n\n  std::vector<int32_t> serializedATN;\n\n  std::getline(input, line, '\\n');\n  assert(line == \"atn:\");\n  std::getline(input, line, '\\n');\n  std::stringstream tokenizer(line);\n  std::string value;\n  while (tokenizer.good()) {\n    std::getline(tokenizer, value, ',');\n    unsigned long number;\n    if (value[0] == '[')\n      number = std::strtoul(&value[1], nullptr, 10);\n    else\n      number = std::strtoul(value.c_str(), nullptr, 10);\n    serializedATN.push_back(static_cast<int32_t>(number));\n  }\n\n  ATNDeserializer deserializer;\n  result.atn = deserializer.deserialize(serializedATN);\n  return result;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/InterpreterDataReader.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <string>\n#include \"antlr4-common.h\"\n#include \"atn/ATN.h\"\n#include \"Vocabulary.h\"\n\nnamespace antlr4 {\nnamespace misc {\n\n  struct InterpreterData {\n    std::unique_ptr<atn::ATN> atn;\n    dfa::Vocabulary vocabulary;\n    std::vector<std::string> ruleNames;\n    std::vector<std::string> channels; // Only valid for lexer grammars.\n    std::vector<std::string> modes; // ditto\n\n    InterpreterData() {}; // For invalid content.\n    InterpreterData(std::vector<std::string> const& literalNames, std::vector<std::string> const& symbolicNames);\n  };\n\n  // A class to read plain text interpreter data produced by ANTLR.\n  class ANTLR4CPP_PUBLIC InterpreterDataReader {\n  public:\n    static InterpreterData parseFile(std::string const& fileName);\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/Interval.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"misc/Interval.h\"\n\nusing namespace antlr4::misc;\n\nconst Interval Interval::INVALID;\n\nsize_t Interval::hashCode() const {\n  size_t hash = 23;\n  hash = hash * 31 + static_cast<size_t>(a);\n  hash = hash * 31 + static_cast<size_t>(b);\n  return hash;\n}\n\nbool Interval::startsBeforeDisjoint(const Interval &other) const {\n  return a < other.a && b < other.a;\n}\n\nbool Interval::startsBeforeNonDisjoint(const Interval &other) const {\n  return a <= other.a && b >= other.a;\n}\n\nbool Interval::startsAfter(const Interval &other) const {\n  return a > other.a;\n}\n\nbool Interval::startsAfterDisjoint(const Interval &other) const {\n  return a > other.b;\n}\n\nbool Interval::startsAfterNonDisjoint(const Interval &other) const {\n  return a > other.a && a <= other.b; // b >= other.b implied\n}\n\nbool Interval::disjoint(const Interval &other) const {\n  return startsBeforeDisjoint(other) || startsAfterDisjoint(other);\n}\n\nbool Interval::adjacent(const Interval &other) const {\n  return a == other.b + 1 || b == other.a - 1;\n}\n\nbool Interval::properlyContains(const Interval &other) const {\n  return other.a >= a && other.b <= b;\n}\n\nInterval Interval::Union(const Interval &other) const {\n  return Interval(std::min(a, other.a), std::max(b, other.b));\n}\n\nInterval Interval::intersection(const Interval &other) const {\n  return Interval(std::max(a, other.a), std::min(b, other.b));\n}\n\nstd::string Interval::toString() const {\n  return std::to_string(a) + \"..\" + std::to_string(b);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/Interval.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace misc {\n\n  // Helpers to convert certain unsigned symbols (e.g. Token::EOF) to their original numeric value (e.g. -1)\n  // and vice versa. This is needed mostly for intervals to keep their original order and for toString()\n  // methods to print the original numeric value (e.g. for tests).\n  constexpr size_t numericToSymbol(ssize_t v) { return static_cast<size_t>(v); }\n  constexpr ssize_t symbolToNumeric(size_t v) { return static_cast<ssize_t>(v); }\n\n  /// An immutable inclusive interval a..b\n  class ANTLR4CPP_PUBLIC Interval final {\n  public:\n    static const Interval INVALID;\n\n    // Must stay signed to guarantee the correct sort order.\n    ssize_t a;\n    ssize_t b;\n\n    constexpr Interval() : Interval(static_cast<ssize_t>(-1), static_cast<ssize_t>(-2)) {}\n\n    constexpr explicit Interval(size_t a_, size_t b_) : Interval(symbolToNumeric(a_), symbolToNumeric(b_)) {}\n\n    constexpr Interval(ssize_t a_, ssize_t b_) : a(a_), b(b_) {}\n\n    /// return number of elements between a and b inclusively. x..x is length 1.\n    ///  if b < a, then length is 0.  9..10 has length 2.\n    constexpr size_t length() const { return b >= a ? static_cast<size_t>(b - a + 1) : 0; }\n\n    constexpr bool operator==(const Interval &other) const { return a == other.a && b == other.b; }\n\n    size_t hashCode() const;\n\n    /// <summary>\n    /// Does this start completely before other? Disjoint </summary>\n    bool startsBeforeDisjoint(const Interval &other) const;\n\n    /// <summary>\n    /// Does this start at or before other? Nondisjoint </summary>\n    bool startsBeforeNonDisjoint(const Interval &other) const;\n\n    /// <summary>\n    /// Does this.a start after other.b? May or may not be disjoint </summary>\n    bool startsAfter(const Interval &other) const;\n\n    /// <summary>\n    /// Does this start completely after other? Disjoint </summary>\n    bool startsAfterDisjoint(const Interval &other) const;\n\n    /// <summary>\n    /// Does this start after other? NonDisjoint </summary>\n    bool startsAfterNonDisjoint(const Interval &other) const;\n\n    /// <summary>\n    /// Are both ranges disjoint? I.e., no overlap? </summary>\n    bool disjoint(const Interval &other) const;\n\n    /// <summary>\n    /// Are two intervals adjacent such as 0..41 and 42..42? </summary>\n    bool adjacent(const Interval &other) const;\n\n    bool properlyContains(const Interval &other) const;\n\n    /// <summary>\n    /// Return the interval computed from combining this and other </summary>\n    Interval Union(const Interval &other) const;\n\n    /// <summary>\n    /// Return the interval in common between this and o </summary>\n    Interval intersection(const Interval &other) const;\n\n    std::string toString() const;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/IntervalSet.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"misc/MurmurHash.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"Lexer.h\"\n#include \"Exceptions.h\"\n#include \"Vocabulary.h\"\n\n#include \"misc/IntervalSet.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::misc;\n\nIntervalSet const IntervalSet::COMPLETE_CHAR_SET =\n    IntervalSet::of(Lexer::MIN_CHAR_VALUE, Lexer::MAX_CHAR_VALUE);\n\nIntervalSet const IntervalSet::EMPTY_SET;\n\nIntervalSet::IntervalSet() : _intervals() {\n}\n\nIntervalSet::IntervalSet(const IntervalSet &set) : IntervalSet() {\n  _intervals = set._intervals;\n}\n\nIntervalSet::IntervalSet(IntervalSet&& set) : IntervalSet(std::move(set._intervals)) {\n}\n\nIntervalSet::IntervalSet(std::vector<Interval>&& intervals) : _intervals(std::move(intervals)) {\n}\n\nIntervalSet& IntervalSet::operator=(const IntervalSet& other) {\n  _intervals = other._intervals;\n  return *this;\n}\n\nIntervalSet& IntervalSet::operator=(IntervalSet&& other) {\n  _intervals = std::move(other._intervals);\n  return *this;\n}\n\nIntervalSet IntervalSet::of(ssize_t a) {\n  return IntervalSet({ Interval(a, a) });\n}\n\nIntervalSet IntervalSet::of(ssize_t a, ssize_t b) {\n  return IntervalSet({ Interval(a, b) });\n}\n\nvoid IntervalSet::clear() {\n  _intervals.clear();\n}\n\nvoid IntervalSet::add(ssize_t el) {\n  add(el, el);\n}\n\nvoid IntervalSet::add(ssize_t a, ssize_t b) {\n  add(Interval(a, b));\n}\n\nvoid IntervalSet::add(const Interval &addition) {\n  if (addition.b < addition.a) {\n    return;\n  }\n\n  // find position in list\n  for (auto iterator = _intervals.begin(); iterator != _intervals.end(); ++iterator) {\n    Interval r = *iterator;\n    if (addition == r) {\n      return;\n    }\n\n    if (addition.adjacent(r) || !addition.disjoint(r)) {\n      // next to each other, make a single larger interval\n      Interval bigger = addition.Union(r);\n      *iterator = bigger;\n\n      // make sure we didn't just create an interval that\n      // should be merged with next interval in list\n      while (iterator + 1 != _intervals.end()) {\n        Interval next = *++iterator;\n        if (!bigger.adjacent(next) && bigger.disjoint(next)) {\n          break;\n        }\n\n        // if we bump up against or overlap next, merge\n        iterator = _intervals.erase(iterator);// remove this one\n        --iterator; // move backwards to what we just set\n        *iterator = bigger.Union(next); // set to 3 merged ones\n        // ml: no need to advance iterator, we do that in the next round anyway. ++iterator; // first call to next after previous duplicates the result\n      }\n      return;\n    }\n\n    if (addition.startsBeforeDisjoint(r)) {\n      // insert before r\n      //--iterator;\n      _intervals.insert(iterator, addition);\n      return;\n    }\n\n    // if disjoint and after r, a future iteration will handle it\n  }\n\n  // ok, must be after last interval (and disjoint from last interval)\n  // just add it\n  _intervals.push_back(addition);\n}\n\nIntervalSet IntervalSet::Or(const std::vector<IntervalSet> &sets) {\n  IntervalSet result;\n  for (const auto &s : sets) {\n    result.addAll(s);\n  }\n  return result;\n}\n\nIntervalSet& IntervalSet::addAll(const IntervalSet &set) {\n  // walk set and add each interval\n  for (auto const& interval : set._intervals) {\n    add(interval);\n  }\n  return *this;\n}\n\nIntervalSet IntervalSet::complement(ssize_t minElement, ssize_t maxElement) const {\n  return complement(IntervalSet::of(minElement, maxElement));\n}\n\nIntervalSet IntervalSet::complement(const IntervalSet &vocabulary) const {\n  return vocabulary.subtract(*this);\n}\n\nIntervalSet IntervalSet::subtract(const IntervalSet &other) const {\n  return subtract(*this, other);\n}\n\nIntervalSet IntervalSet::subtract(const IntervalSet &left, const IntervalSet &right) {\n  if (left.isEmpty()) {\n    return IntervalSet();\n  }\n\n  if (right.isEmpty()) {\n    // right set has no elements; just return the copy of the current set\n    return left;\n  }\n\n  IntervalSet result(left);\n  size_t resultI = 0;\n  size_t rightI = 0;\n  while (resultI < result._intervals.size() && rightI < right._intervals.size()) {\n    Interval &resultInterval = result._intervals[resultI];\n    const Interval &rightInterval = right._intervals[rightI];\n\n    // operation: (resultInterval - rightInterval) and update indexes\n\n    if (rightInterval.b < resultInterval.a) {\n      rightI++;\n      continue;\n    }\n\n    if (rightInterval.a > resultInterval.b) {\n      resultI++;\n      continue;\n    }\n\n    Interval beforeCurrent;\n    Interval afterCurrent;\n    if (rightInterval.a > resultInterval.a) {\n      beforeCurrent = Interval(resultInterval.a, rightInterval.a - 1);\n    }\n\n    if (rightInterval.b < resultInterval.b) {\n      afterCurrent = Interval(rightInterval.b + 1, resultInterval.b);\n    }\n\n    if (beforeCurrent.a > -1) { // -1 is the default value\n      if (afterCurrent.a > -1) {\n        // split the current interval into two\n        result._intervals[resultI] = beforeCurrent;\n        result._intervals.insert(result._intervals.begin() + resultI + 1, afterCurrent);\n        resultI++;\n        rightI++;\n      } else {\n        // replace the current interval\n        result._intervals[resultI] = beforeCurrent;\n        resultI++;\n      }\n    } else {\n      if (afterCurrent.a > -1) {\n        // replace the current interval\n        result._intervals[resultI] = afterCurrent;\n        rightI++;\n      } else {\n        // remove the current interval (thus no need to increment resultI)\n        result._intervals.erase(result._intervals.begin() + resultI);\n      }\n    }\n  }\n\n  // If rightI reached right.intervals.size(), no more intervals to subtract from result.\n  // If resultI reached result.intervals.size(), we would be subtracting from an empty set.\n  // Either way, we are done.\n  return result;\n}\n\nIntervalSet IntervalSet::Or(const IntervalSet &a) const {\n  IntervalSet result;\n  result.addAll(*this);\n  result.addAll(a);\n  return result;\n}\n\nIntervalSet IntervalSet::And(const IntervalSet &other) const {\n  IntervalSet intersection;\n  size_t i = 0;\n  size_t j = 0;\n\n  // iterate down both interval lists looking for nondisjoint intervals\n  while (i < _intervals.size() && j < other._intervals.size()) {\n    Interval mine = _intervals[i];\n    Interval theirs = other._intervals[j];\n\n    if (mine.startsBeforeDisjoint(theirs)) {\n      // move this iterator looking for interval that might overlap\n      i++;\n    } else if (theirs.startsBeforeDisjoint(mine)) {\n      // move other iterator looking for interval that might overlap\n      j++;\n    } else if (mine.properlyContains(theirs)) {\n      // overlap, add intersection, get next theirs\n      intersection.add(mine.intersection(theirs));\n      j++;\n    } else if (theirs.properlyContains(mine)) {\n      // overlap, add intersection, get next mine\n      intersection.add(mine.intersection(theirs));\n      i++;\n    } else if (!mine.disjoint(theirs)) {\n      // overlap, add intersection\n      intersection.add(mine.intersection(theirs));\n\n      // Move the iterator of lower range [a..b], but not\n      // the upper range as it may contain elements that will collide\n      // with the next iterator. So, if mine=[0..115] and\n      // theirs=[115..200], then intersection is 115 and move mine\n      // but not theirs as theirs may collide with the next range\n      // in thisIter.\n      // move both iterators to next ranges\n      if (mine.startsAfterNonDisjoint(theirs)) {\n        j++;\n      } else if (theirs.startsAfterNonDisjoint(mine)) {\n        i++;\n      }\n    }\n  }\n\n  return intersection;\n}\n\nbool IntervalSet::contains(size_t el) const {\n  return contains(symbolToNumeric(el));\n}\n\nbool IntervalSet::contains(ssize_t el) const {\n  if (_intervals.empty() || el < _intervals.front().a || el > _intervals.back().b) {\n    return false;\n  }\n\n  return std::binary_search(_intervals.begin(), _intervals.end(), Interval(el, el), [](const Interval &lhs, const Interval &rhs) {\n    return lhs.b < rhs.a;\n  });\n}\n\nbool IntervalSet::isEmpty() const {\n  return _intervals.empty();\n}\n\nssize_t IntervalSet::getSingleElement() const {\n  if (_intervals.size() == 1) {\n    if (_intervals[0].a == _intervals[0].b) {\n      return _intervals[0].a;\n    }\n  }\n\n  return Token::INVALID_TYPE; // XXX: this value is 0, but 0 is a valid interval range, how can that work?\n}\n\nssize_t IntervalSet::getMaxElement() const {\n  if (_intervals.empty()) {\n    return Token::INVALID_TYPE;\n  }\n\n  return _intervals.back().b;\n}\n\nssize_t IntervalSet::getMinElement() const {\n  if (_intervals.empty()) {\n    return Token::INVALID_TYPE;\n  }\n\n  return _intervals.front().a;\n}\n\nstd::vector<Interval> const& IntervalSet::getIntervals() const {\n  return _intervals;\n}\n\nsize_t IntervalSet::hashCode() const {\n  size_t hash = MurmurHash::initialize();\n  for (const auto &interval : _intervals) {\n    hash = MurmurHash::update(hash, interval.a);\n    hash = MurmurHash::update(hash, interval.b);\n  }\n\n  return MurmurHash::finish(hash, _intervals.size() * 2);\n}\n\nbool IntervalSet::operator == (const IntervalSet &other) const {\n  if (_intervals.empty() && other._intervals.empty())\n    return true;\n\n  if (_intervals.size() != other._intervals.size())\n    return false;\n\n  return std::equal(_intervals.begin(), _intervals.end(), other._intervals.begin());\n}\n\nstd::string IntervalSet::toString() const {\n  return toString(false);\n}\n\nstd::string IntervalSet::toString(bool elemAreChar) const {\n  if (_intervals.empty()) {\n    return \"{}\";\n  }\n\n  std::stringstream ss;\n  size_t effectiveSize = size();\n  if (effectiveSize > 1) {\n    ss << \"{\";\n  }\n\n  bool firstEntry = true;\n  for (const auto &interval : _intervals) {\n    if (!firstEntry)\n      ss << \", \";\n    firstEntry = false;\n\n    ssize_t a = interval.a;\n    ssize_t b = interval.b;\n    if (a == b) {\n      if (a == -1) {\n        ss << \"<EOF>\";\n      } else if (elemAreChar) {\n        ss << \"'\" << static_cast<char>(a) << \"'\";\n      } else {\n        ss << a;\n      }\n    } else {\n      if (elemAreChar) {\n        ss << \"'\" << static_cast<char>(a) << \"'..'\" << static_cast<char>(b) << \"'\";\n      } else {\n        ss << a << \"..\" << b;\n      }\n    }\n  }\n  if (effectiveSize > 1) {\n    ss << \"}\";\n  }\n\n  return ss.str();\n}\n\nstd::string IntervalSet::toString(const dfa::Vocabulary &vocabulary) const {\n  if (_intervals.empty()) {\n    return \"{}\";\n  }\n\n  std::stringstream ss;\n  size_t effectiveSize = size();\n  if (effectiveSize > 1) {\n    ss << \"{\";\n  }\n\n  bool firstEntry = true;\n  for (const auto &interval : _intervals) {\n    if (!firstEntry)\n      ss << \", \";\n    firstEntry = false;\n\n    ssize_t a = interval.a;\n    ssize_t b = interval.b;\n    if (a == b) {\n      ss << elementName(vocabulary, a);\n    } else {\n      for (ssize_t i = a; i <= b; i++) {\n        if (i > a) {\n          ss << \", \";\n        }\n        ss << elementName(vocabulary, i);\n      }\n    }\n  }\n  if (effectiveSize > 1) {\n    ss << \"}\";\n  }\n\n  return ss.str();\n}\n\nstd::string IntervalSet::elementName(const dfa::Vocabulary &vocabulary, ssize_t a) const {\n  if (a == -1) {\n    return \"<EOF>\";\n  } else if (a == -2) {\n    return \"<EPSILON>\";\n  } else {\n    return vocabulary.getDisplayName(a);\n  }\n}\n\nsize_t IntervalSet::size() const {\n  size_t result = 0;\n  for (const auto &interval : _intervals) {\n    result += size_t(interval.b - interval.a + 1);\n  }\n  return result;\n}\n\nstd::vector<ssize_t> IntervalSet::toList() const {\n  std::vector<ssize_t> result;\n  for (const auto &interval : _intervals) {\n    ssize_t a = interval.a;\n    ssize_t b = interval.b;\n    for (ssize_t v = a; v <= b; v++) {\n      result.push_back(v);\n    }\n  }\n  return result;\n}\n\nstd::set<ssize_t> IntervalSet::toSet() const {\n  std::set<ssize_t> result;\n  for (const auto &interval : _intervals) {\n    ssize_t a = interval.a;\n    ssize_t b = interval.b;\n    for (ssize_t v = a; v <= b; v++) {\n      result.insert(v);\n    }\n  }\n  return result;\n}\n\nssize_t IntervalSet::get(size_t i) const {\n  size_t index = 0;\n  for (const auto &interval : _intervals) {\n    ssize_t a = interval.a;\n    ssize_t b = interval.b;\n    for (ssize_t v = a; v <= b; v++) {\n      if (index == i) {\n        return v;\n      }\n      index++;\n    }\n  }\n  return -1;\n}\n\nvoid IntervalSet::remove(size_t el) {\n  remove(symbolToNumeric(el));\n}\n\nvoid IntervalSet::remove(ssize_t el) {\n  for (size_t i = 0; i < _intervals.size(); ++i) {\n    Interval &interval = _intervals[i];\n    ssize_t a = interval.a;\n    ssize_t b = interval.b;\n    if (el < a) {\n      break; // list is sorted and el is before this interval; not here\n    }\n\n    // if whole interval x..x, rm\n    if (el == a && el == b) {\n      _intervals.erase(_intervals.begin() + (long)i);\n      break;\n    }\n    // if on left edge x..b, adjust left\n    if (el == a) {\n      interval.a++;\n      break;\n    }\n    // if on right edge a..x, adjust right\n    if (el == b) {\n      interval.b--;\n      break;\n    }\n    // if in middle a..x..b, split interval\n    if (el > a && el < b) { // found in this interval\n      ssize_t oldb = interval.b;\n      interval.b = el - 1; // [a..x-1]\n      add(el + 1, oldb); // add [x+1..b]\n\n      break; // ml: not in the Java code but I believe we also should stop searching here, as we found x.\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/IntervalSet.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"misc/Interval.h\"\n#include \"antlr4-common.h\"\n#include \"Exceptions.h\"\n\nnamespace antlr4 {\nnamespace misc {\n\n  /**\n   * This class implements the {@link IntSet} backed by a sorted array of\n   * non-overlapping intervals. It is particularly efficient for representing\n   * large collections of numbers, where the majority of elements appear as part\n   * of a sequential range of numbers that are all part of the set. For example,\n   * the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }.\n   *\n   * <p>\n   * This class is able to represent sets containing any combination of values in\n   * the range {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE}\n   * (inclusive).</p>\n   */\n  class ANTLR4CPP_PUBLIC IntervalSet final {\n  public:\n    static IntervalSet const COMPLETE_CHAR_SET;\n    static IntervalSet const EMPTY_SET;\n\n  private:\n    /// The list of sorted, disjoint intervals.\n    std::vector<Interval> _intervals;\n\n    explicit IntervalSet(std::vector<Interval>&& intervals);\n\n  public:\n    IntervalSet();\n    IntervalSet(IntervalSet const& set);\n    IntervalSet(IntervalSet&& set);\n\n    template<typename T1, typename... T_NEXT>\n    IntervalSet(int, T1 t1, T_NEXT&&... next) : IntervalSet() {\n      // The first int argument is an ignored count for compatibility\n      // with the previous varargs based interface.\n      addItems(t1, std::forward<T_NEXT>(next)...);\n    }\n\n    IntervalSet& operator=(IntervalSet const& set);\n    IntervalSet& operator=(IntervalSet&& set);\n\n    /// Create a set with a single element, el.\n    static IntervalSet of(ssize_t a);\n\n    /// Create a set with all ints within range [a..b] (inclusive)\n    static IntervalSet of(ssize_t a, ssize_t b);\n\n    void clear();\n\n    /// Add a single element to the set.  An isolated element is stored\n    /// as a range el..el.\n    void add(ssize_t el);\n\n    /// Add interval; i.e., add all integers from a to b to set.\n    /// If b<a, do nothing.\n    /// Keep list in sorted order (by left range value).\n    /// If overlap, combine ranges.  For example,\n    /// If this is {1..5, 10..20}, adding 6..7 yields\n    /// {1..5, 6..7, 10..20}.  Adding 4..8 yields {1..8, 10..20}.\n    void add(ssize_t a, ssize_t b);\n\n    /// combine all sets in the array returned the or'd value\n    static IntervalSet Or(const std::vector<IntervalSet> &sets);\n\n    // Copy on write so we can cache a..a intervals and sets of that.\n    void add(const Interval &addition);\n    IntervalSet& addAll(const IntervalSet &set);\n\n    template<typename T1, typename... T_NEXT>\n    void addItems(T1 t1, T_NEXT&&... next) {\n      add(t1);\n      addItems(std::forward<T_NEXT>(next)...);\n    }\n\n    IntervalSet complement(ssize_t minElement, ssize_t maxElement) const;\n\n    /// Given the set of possible values (rather than, say UNICODE or MAXINT),\n    /// return a new set containing all elements in vocabulary, but not in\n    /// this.  The computation is (vocabulary - this).\n    ///\n    /// 'this' is assumed to be either a subset or equal to vocabulary.\n    IntervalSet complement(const IntervalSet &vocabulary) const;\n\n    /// Compute this-other via this&~other.\n    /// Return a new set containing all elements in this but not in other.\n    /// other is assumed to be a subset of this;\n    /// anything that is in other but not in this will be ignored.\n    IntervalSet subtract(const IntervalSet &other) const;\n\n    /**\n     * Compute the set difference between two interval sets. The specific\n     * operation is {@code left - right}. If either of the input sets is\n     * {@code null}, it is treated as though it was an empty set.\n     */\n    static IntervalSet subtract(const IntervalSet &left, const IntervalSet &right);\n\n    IntervalSet Or(const IntervalSet &a) const;\n\n    /// Return a new set with the intersection of this set with other.  Because\n    /// the intervals are sorted, we can use an iterator for each list and\n    /// just walk them together.  This is roughly O(min(n,m)) for interval\n    /// list lengths n and m.\n    IntervalSet And(const IntervalSet &other) const;\n\n    /// Is el in any range of this set?\n    bool contains(size_t el) const; // For mapping of e.g. Token::EOF to -1 etc.\n    bool contains(ssize_t el) const;\n\n    /// return true if this set has no members\n    bool isEmpty() const;\n\n    /// If this set is a single integer, return it otherwise Token.INVALID_TYPE.\n    ssize_t getSingleElement() const;\n\n    /**\n     * Returns the maximum value contained in the set.\n     *\n     * @return the maximum value contained in the set. If the set is empty, this\n     * method returns {@link Token#INVALID_TYPE}.\n     */\n    ssize_t getMaxElement() const;\n\n    /**\n     * Returns the minimum value contained in the set.\n     *\n     * @return the minimum value contained in the set. If the set is empty, this\n     * method returns {@link Token#INVALID_TYPE}.\n     */\n    ssize_t getMinElement() const;\n\n    /// <summary>\n    /// Return a list of Interval objects. </summary>\n    std::vector<Interval> const& getIntervals() const;\n\n    size_t hashCode() const;\n\n    /// Are two IntervalSets equal?  Because all intervals are sorted\n    ///  and disjoint, equals is a simple linear walk over both lists\n    ///  to make sure they are the same.\n    bool operator == (const IntervalSet &other) const;\n    std::string toString() const;\n    std::string toString(bool elemAreChar) const;\n\n    std::string toString(const dfa::Vocabulary &vocabulary) const;\n\n  protected:\n    std::string elementName(const dfa::Vocabulary &vocabulary, ssize_t a) const;\n\n  public:\n    size_t size() const;\n    std::vector<ssize_t> toList() const;\n    std::set<ssize_t> toSet() const;\n\n    /// Get the ith element of ordered set.  Used only by RandomPhrase so\n    /// don't bother to implement if you're not doing that for a new\n    /// ANTLR code gen target.\n    ssize_t get(size_t i) const;\n    void remove(size_t el); // For mapping of e.g. Token::EOF to -1 etc.\n    void remove(ssize_t el);\n\n  private:\n    void addItems() { /* No-op */ }\n  };\n\n} // namespace atn\n} // namespace antlr4\n\n// Hash function for IntervalSet.\n\nnamespace std {\n  using antlr4::misc::IntervalSet;\n\n  template <> struct hash<IntervalSet>\n  {\n    size_t operator() (const IntervalSet &x) const\n    {\n      return x.hashCode();\n    }\n  };\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/MurmurHash.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <cstddef>\n#include <cstdint>\n#include <cstring>\n\n#include \"antlr4-common.h\"\n#include \"misc/MurmurHash.h\"\n\nusing namespace antlr4::misc;\n\n// A variation of the MurmurHash3 implementation (https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp)\n// Here we unrolled the loop used there into individual calls to update(), as we usually hash object fields\n// instead of entire buffers.\n\n// Platform-specific functions and macros\n\n// Microsoft Visual Studio\n\n#if defined(_MSC_VER)\n\n#include <stdlib.h>\n\n#define ROTL32(x,y)\t_rotl(x,y)\n#define ROTL64(x,y)\t_rotl64(x,y)\n\n#elif ANTLR4CPP_HAVE_BUILTIN(__builtin_rotateleft32) && ANTLR4CPP_HAVE_BUILTIN(__builtin_rotateleft64)\n\n#define ROTL32(x, y) __builtin_rotateleft32(x, y)\n#define ROTL64(x, y) __builtin_rotateleft64(x, y)\n\n#else\t// defined(_MSC_VER)\n\n// Other compilers\n\nnamespace {\n\nconstexpr uint32_t ROTL32(uint32_t x, int r) {\n  return (x << r) | (x >> (32 - r));\n}\nconstexpr uint64_t ROTL64(uint64_t x, int r) {\n  return (x << r) | (x >> (64 - r));\n}\n\n}\n\n#endif // !defined(_MSC_VER)\n\n#if SIZE_MAX == UINT64_MAX\n\nsize_t MurmurHash::update(size_t hash, size_t value) {\n  size_t k1 = value;\n  k1 *= UINT64_C(0x87c37b91114253d5);\n  k1 = ROTL64(k1, 31);\n  k1 *= UINT64_C(0x4cf5ad432745937f);\n\n  hash ^= k1;\n  hash = ROTL64(hash, 27);\n  hash = hash * 5 + UINT64_C(0x52dce729);\n\n  return hash;\n}\n\nsize_t MurmurHash::finish(size_t hash, size_t entryCount) {\n  hash ^= entryCount * 8;\n  hash ^= hash >> 33;\n  hash *= UINT64_C(0xff51afd7ed558ccd);\n  hash ^= hash >> 33;\n  hash *= UINT64_C(0xc4ceb9fe1a85ec53);\n  hash ^= hash >> 33;\n  return hash;\n}\n\n#elif SIZE_MAX == UINT32_MAX\n\nsize_t MurmurHash::update(size_t hash, size_t value) {\n  size_t k1 = value;\n  k1 *= UINT32_C(0xCC9E2D51);\n  k1 = ROTL32(k1, 15);\n  k1 *= UINT32_C(0x1B873593);\n\n  hash ^= k1;\n  hash = ROTL32(hash, 13);\n  hash = hash * 5 + UINT32_C(0xE6546B64);\n\n  return hash;\n}\n\nsize_t MurmurHash::finish(size_t hash, size_t entryCount) {\n  hash ^= entryCount * 4;\n  hash ^= hash >> 16;\n  hash *= UINT32_C(0x85EBCA6B);\n  hash ^= hash >> 13;\n  hash *= UINT32_C(0xC2B2AE35);\n  hash ^= hash >> 16;\n  return hash;\n}\n\n#else\n#error \"Expected sizeof(size_t) to be 4 or 8.\"\n#endif\n\nsize_t MurmurHash::update(size_t hash, const void *data, size_t size) {\n  size_t value;\n  const uint8_t *bytes = static_cast<const uint8_t*>(data);\n  while (size >= sizeof(size_t)) {\n    std::memcpy(&value, bytes, sizeof(size_t));\n    hash = update(hash, value);\n    bytes += sizeof(size_t);\n    size -= sizeof(size_t);\n  }\n  if (size != 0) {\n    value = 0;\n    std::memcpy(&value, bytes, size);\n    hash = update(hash, value);\n  }\n  return hash;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/MurmurHash.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <cstddef>\n#include <cstdint>\n#include <type_traits>\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace misc {\n\n  class ANTLR4CPP_PUBLIC MurmurHash final {\n  private:\n    static constexpr size_t DEFAULT_SEED = 0;\n\n    /// Initialize the hash using the default seed value.\n    /// Returns the intermediate hash value.\n  public:\n    static size_t initialize() { return initialize(DEFAULT_SEED); }\n\n    /// Initialize the hash using the specified seed.\n    static size_t initialize(size_t seed) { return seed; }\n\n    /// Update the intermediate hash value for the next input {@code value}.\n    /// <param name=\"hash\"> the intermediate hash value </param>\n    /// <param name=\"value\"> the value to add to the current hash </param>\n    /// Returns the updated intermediate hash value.\n    static size_t update(size_t hash, size_t value);\n\n    /**\n     * Update the intermediate hash value for the next input {@code value}.\n     *\n     * @param hash the intermediate hash value\n     * @param value the value to add to the current hash\n     * @return the updated intermediate hash value\n     */\n    template <class T>\n    static size_t update(size_t hash, Ref<T> const& value) {\n      return update(hash, value != nullptr ? value->hashCode() : 0);\n    }\n\n    template <class T>\n    static size_t update(size_t hash, T *value) {\n      return update(hash, value != nullptr ? value->hashCode() : 0);\n    }\n\n    static size_t update(size_t hash, const void *data, size_t size);\n\n    template <typename T>\n    static size_t update(size_t hash, const T *data, size_t size) {\n      return update(hash, static_cast<const void*>(data), size * sizeof(std::remove_reference_t<T>));\n    }\n\n    /// <summary>\n    /// Apply the final computation steps to the intermediate value {@code hash}\n    /// to form the final result of the MurmurHash 3 hash function.\n    /// </summary>\n    /// <param name=\"hash\"> the intermediate hash value </param>\n    /// <param name=\"entryCount\"> the number of calls to update() before calling finish() </param>\n    /// <returns> the final hash result </returns>\n    static size_t finish(size_t hash, size_t entryCount);\n\n    /// Utility function to compute the hash code of an array using the MurmurHash3 algorithm.\n    ///\n    /// @param <T> the array element type </param>\n    /// <param name=\"data\"> the array data </param>\n    /// <param name=\"seed\"> the seed for the MurmurHash algorithm </param>\n    /// <returns> the hash code of the data </returns>\n    template<typename T> // where T is C array type\n    static size_t hashCode(const std::vector<Ref<T>> &data, size_t seed = DEFAULT_SEED) {\n      size_t hash = initialize(seed);\n      for (auto &entry : data) {\n        hash = update(hash, entry);\n      }\n      return finish(hash, data.size());\n    }\n\n    static size_t hashCode(const void *data, size_t size, size_t seed = DEFAULT_SEED) {\n      size_t hash = initialize(seed);\n      hash = update(hash, data, size);\n      return finish(hash, size);\n    }\n\n    template <typename T>\n    static size_t hashCode(const T *data, size_t size, size_t seed = DEFAULT_SEED) {\n      return hashCode(static_cast<const void*>(data), size * sizeof(std::remove_reference_t<T>), seed);\n    }\n\n  private:\n    MurmurHash() = delete;\n\n    MurmurHash(const MurmurHash&) = delete;\n\n    MurmurHash& operator=(const MurmurHash&) = delete;\n  };\n\n} // namespace atn\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/Predicate.cpp",
    "content": "#include \"misc/Predicate.h\"\n\nantlr4::misc::Predicate::~Predicate() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/misc/Predicate.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace misc {\n\n  class ANTLR4CPP_PUBLIC Predicate {\n  public:\n    virtual ~Predicate();\n\n    virtual bool test(tree::ParseTree *t) = 0;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Any.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"Any.h\"\n\nusing namespace antlrcpp;\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Any.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n// A standard C++ class loosely modeled after boost::Any.\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlrcpp {\n\n  using Any = std::any;\n\n} // namespace antlrcpp\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Arrays.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <vector>\n#include <string>\n#include \"tree/ParseTree.h\"\n#include \"Exceptions.h\"\n\n#include \"support/Arrays.h\"\n\nusing namespace antlrcpp;\n\nstd::string Arrays::listToString(const std::vector<std::string> &list, const std::string &separator)\n{\n  std::stringstream ss;\n  bool firstEntry = true;\n\n  ss << '[';\n  for (const auto &entry : list) {\n    ss << entry;\n    if (firstEntry) {\n      ss << separator;\n      firstEntry = false;\n    }\n  }\n\n  ss << ']';\n  return ss.str();\n}\n\ntemplate <>\nstd::string Arrays::toString(const std::vector<antlr4::tree::ParseTree*> &source) {\n  std::string result = \"[\";\n  bool firstEntry = true;\n  for (auto *value : source) {\n    result += value->toStringTree();\n    if (firstEntry) {\n      result += \", \";\n      firstEntry = false;\n    }\n  }\n  return result + \"]\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Arrays.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlrcpp {\n\n  class ANTLR4CPP_PUBLIC Arrays {\n  public:\n\n    static std::string listToString(const std::vector<std::string> &list, const std::string &separator);\n\n    template <typename T>\n    static bool equals(const std::vector<T> &a, const std::vector<T> &b) {\n      if (a.size() != b.size())\n        return false;\n\n      for (size_t i = 0; i < a.size(); ++i)\n        if (!(a[i] == b[i]))\n          return false;\n\n      return true;\n    }\n\n    template <typename T>\n    static bool equals(const std::vector<T *> &a, const std::vector<T *> &b) {\n      if (a.size() != b.size())\n        return false;\n\n      for (size_t i = 0; i < a.size(); ++i) {\n        if (!a[i] && !b[i])\n          continue;\n        if (!a[i] || !b[i])\n          return false;\n        if (a[i] == b[i])\n          continue;\n\n        if (!(*a[i] == *b[i]))\n          return false;\n      }\n\n      return true;\n    }\n\n    template <typename T>\n    static bool equals(const std::vector<Ref<T>> &a, const std::vector<Ref<T>> &b) {\n      if (a.size() != b.size())\n        return false;\n\n      for (size_t i = 0; i < a.size(); ++i) {\n        if (!a[i] && !b[i])\n          continue;\n        if (!a[i] || !b[i])\n          return false;\n        if (a[i] == b[i])\n          continue;\n\n        if (!(*a[i] == *b[i]))\n          return false;\n      }\n\n      return true;\n    }\n\n    template <typename T>\n    static bool equals(const std::vector<std::unique_ptr<T>> &a, const std::vector<std::unique_ptr<T>> &b) {\n      if (a.size() != b.size())\n        return false;\n\n      for (size_t i = 0; i < a.size(); ++i) {\n        if (!a[i] && !b[i])\n          continue;\n        if (!a[i] || !b[i])\n          return false;\n        if (a[i] == b[i])\n          continue;\n\n        if (!(*a[i] == *b[i]))\n          return false;\n      }\n\n      return true;\n    }\n\n    template <typename T>\n    static std::string toString(const std::vector<T> &source) {\n      std::string result = \"[\";\n      bool firstEntry = true;\n      for (auto &value : source) {\n        result += value.toString();\n        if (firstEntry) {\n          result += \", \";\n          firstEntry = false;\n        }\n      }\n      return result + \"]\";\n    }\n\n    template <typename T>\n    static std::string toString(const std::vector<Ref<T>> &source) {\n      std::string result = \"[\";\n      bool firstEntry = true;\n      for (auto &value : source) {\n        result += value->toString();\n        if (firstEntry) {\n          result += \", \";\n          firstEntry = false;\n        }\n      }\n      return result + \"]\";\n    }\n\n    template <typename T>\n    static std::string toString(const std::vector<std::unique_ptr<T>> &source) {\n      std::string result = \"[\";\n      bool firstEntry = true;\n      for (auto &value : source) {\n        result += value->toString();\n        if (firstEntry) {\n          result += \", \";\n          firstEntry = false;\n        }\n      }\n      return result + \"]\";\n    }\n\n    template <typename T>\n    static std::string toString(const std::vector<T *> &source) {\n      std::string result = \"[\";\n      bool firstEntry = true;\n      for (auto value : source) {\n        result += value->toString();\n        if (firstEntry) {\n          result += \", \";\n          firstEntry = false;\n        }\n      }\n      return result + \"]\";\n    }\n\n  };\n\n  template <>\n  std::string Arrays::toString(const std::vector<antlr4::tree::ParseTree *> &source);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/BitSet.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <sstream>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlrcpp {\n\n  class ANTLR4CPP_PUBLIC BitSet : public std::bitset<2048> {\n  public:\n    size_t nextSetBit(size_t pos) const {\n      for (size_t i = pos; i < size(); i++){\n        if (test(i)) {\n          return i;\n        }\n      }\n\n      return INVALID_INDEX;\n    }\n\n    // Prints a list of every index for which the bitset contains a bit in true.\n    friend std::wostream& operator << (std::wostream& os, const BitSet& obj)\n    {\n      os << \"{\";\n      size_t total = obj.count();\n      for (size_t i = 0; i < obj.size(); i++){\n        if (obj.test(i)){\n          os << i;\n          --total;\n          if (total > 1){\n            os << \", \";\n          }\n        }\n      }\n\n      os << \"}\";\n      return os;\n    }\n\n    static std::string subStringRepresentation(const std::vector<BitSet>::iterator &begin,\n                                                const std::vector<BitSet>::iterator &end) {\n      std::string result;\n      std::vector<BitSet>::iterator vectorIterator;\n\n      for (vectorIterator = begin; vectorIterator != end; vectorIterator++) {\n        result += vectorIterator->toString();\n      }\n      // Grab the end\n      result += end->toString();\n\n      return result;\n    }\n\n    std::string toString() const {\n      std::stringstream stream;\n      stream << \"{\";\n      bool valueAdded = false;\n      for (size_t i = 0; i < size(); ++i){\n        if (test(i)){\n          if (valueAdded) {\n            stream << \", \";\n          }\n          stream << i;\n          valueAdded = true;\n        }\n      }\n\n      stream << \"}\";\n      return stream.str();\n    }\n\n  };\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/CPPUtils.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <sstream>\n#include <map>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"support/CPPUtils.h\"\n\nnamespace antlrcpp {\n\n  std::string join(const std::vector<std::string> &strings, const std::string &separator) {\n    std::string str;\n    bool firstItem = true;\n    for (const std::string &s : strings) {\n      if (!firstItem) {\n        str.append(separator);\n      }\n      firstItem = false;\n      str.append(s);\n    }\n    return str;\n  }\n\n  std::map<std::string, size_t> toMap(const std::vector<std::string> &keys) {\n    std::map<std::string, size_t> result;\n    for (size_t i = 0; i < keys.size(); ++i) {\n      result.insert({ keys[i], i });\n    }\n    return result;\n  }\n\n  std::string escapeWhitespace(std::string str, bool escapeSpaces) {\n    std::string result;\n    for (auto c : str) {\n      switch (c) {\n        case '\\n':\n          result += \"\\\\n\";\n          break;\n\n        case '\\r':\n          result += \"\\\\r\";\n          break;\n\n        case '\\t':\n          result += \"\\\\t\";\n          break;\n\n        case ' ':\n          if (escapeSpaces) {\n            result += \"\\u00B7\";\n            break;\n          }\n          result += c;\n          break;\n\n        default:\n          result += c;\n          break;\n      }\n    }\n\n    return result;\n  }\n\n  std::string toHexString(const int t) {\n    std::stringstream stream;\n    stream << std::uppercase << std::hex << t;\n    return stream.str();\n  }\n\n  std::string arrayToString(const std::vector<std::string> &data) {\n    std::string answer;\n    size_t toReserve = 0;\n    for (const auto &sub : data) {\n      toReserve += sub.size();\n    }\n    answer.reserve(toReserve);\n    for (const auto &sub: data) {\n      answer.append(sub);\n    }\n    return answer;\n  }\n\n  std::string replaceString(const std::string &s, const std::string &from, const std::string &to) {\n    std::string::size_type p;\n    std::string ss, res;\n\n    ss = s;\n    p = ss.find(from);\n    while (p != std::string::npos) {\n      if (p > 0)\n        res.append(ss.substr(0, p)).append(to);\n      else\n        res.append(to);\n      ss = ss.substr(p + from.size());\n      p = ss.find(from);\n    }\n    res.append(ss);\n\n    return res;\n  }\n\n  std::vector<std::string> split(const std::string &s, const std::string &sep, int count) {\n    std::vector<std::string> parts;\n    std::string ss = s;\n\n    std::string::size_type p;\n\n    if (s.empty())\n      return parts;\n\n    if (count == 0)\n      count= -1;\n\n    p = ss.find(sep);\n    while (!ss.empty() && p != std::string::npos && (count < 0 || count > 0)) {\n      parts.push_back(ss.substr(0, p));\n      ss = ss.substr(p+sep.size());\n\n      --count;\n      p = ss.find(sep);\n    }\n    parts.push_back(ss);\n\n    return parts;\n  }\n\n  //--------------------------------------------------------------------------------------------------\n\n  // Debugging helper. Adds indentation to all lines in the given string.\n  std::string indent(const std::string &s, const std::string &indentation, bool includingFirst) {\n    std::vector<std::string> parts = split(s, \"\\n\", -1);\n    for (size_t i = 0; i < parts.size(); ++i) {\n      if (i == 0 && !includingFirst)\n        continue;\n      parts[i].insert(0, indentation);\n    }\n\n    return join(parts, \"\\n\");\n  }\n\n  //--------------------------------------------------------------------------------------------------\n\n  // Recursively get the error from a, possibly nested, exception.\n#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026\n  // No nested exceptions before VS 2015.\n  template <typename T>\n  std::exception_ptr get_nested(const T &/*e*/) {\n    try {\n      return nullptr;\n    }\n    catch (const std::bad_cast &) {\n      return nullptr;\n    }\n  }\n#else\n  template <typename T>\n  std::exception_ptr get_nested(const T &e) {\n    try {\n      auto nested = dynamic_cast<const std::nested_exception&>(e);\n      return nested.nested_ptr();\n    }\n    catch (const std::bad_cast &) {\n      return nullptr;\n    }\n  }\n#endif\n\n  std::string what(std::exception_ptr eptr) {\n    if (!eptr) {\n      throw std::bad_exception();\n    }\n\n    std::string result;\n    std::size_t nestCount = 0;\n\n    next: {\n      try {\n        std::exception_ptr yeptr;\n        std::swap(eptr, yeptr);\n        std::rethrow_exception(yeptr);\n      }\n      catch (const std::exception &e) {\n        result += e.what();\n        eptr = get_nested(e);\n      }\n      catch (const std::string &e) {\n        result += e;\n      }\n      catch (const char *e) {\n        result += e;\n      }\n      catch (...) {\n        result += \"cannot be determined\";\n      }\n\n      if (eptr) {\n        result += \" (\";\n        ++nestCount;\n        goto next;\n      }\n    }\n\n    result += std::string(nestCount, ')');\n    return result;\n  }\n\n} // namespace antlrcpp\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/CPPUtils.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <sstream>\n#include <map>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n\nnamespace antlrcpp {\n\n  ANTLR4CPP_PUBLIC std::string join(const std::vector<std::string> &strings, const std::string &separator);\n  ANTLR4CPP_PUBLIC std::map<std::string, size_t> toMap(const std::vector<std::string> &keys);\n  ANTLR4CPP_PUBLIC std::string escapeWhitespace(std::string str, bool escapeSpaces);\n  ANTLR4CPP_PUBLIC std::string toHexString(const int t);\n  ANTLR4CPP_PUBLIC std::string arrayToString(const std::vector<std::string> &data);\n  ANTLR4CPP_PUBLIC std::string replaceString(const std::string &s, const std::string &from, const std::string &to);\n  ANTLR4CPP_PUBLIC std::vector<std::string> split(const std::string &s, const std::string &sep, int count);\n  ANTLR4CPP_PUBLIC std::string indent(const std::string &s, const std::string &indentation, bool includingFirst = true);\n\n  // Using RAII + a lambda to implement a \"finally\" replacement.\n  template <typename OnEnd>\n  struct FinalAction {\n    FinalAction(OnEnd f) : _cleanUp { std::move(f) } {}\n    FinalAction(FinalAction &&other) :\n\t_cleanUp(std::move(other._cleanUp)), _enabled(other._enabled) {\n      other._enabled = false; // Don't trigger the lambda after ownership has moved.\n    }\n    ~FinalAction() { if (_enabled) _cleanUp(); }\n\n    void disable() { _enabled = false; }\n  private:\n    OnEnd _cleanUp;\n    bool _enabled {true};\n  };\n\n  template <typename OnEnd>\n  FinalAction<OnEnd> finally(OnEnd f) {\n    return FinalAction<OnEnd>(std::move(f));\n  }\n\n  // Convenience functions to avoid lengthy dynamic_cast() != nullptr checks in many places.\n  template <typename T1, typename T2>\n  inline bool is(T2 *obj) { // For pointer types.\n    return dynamic_cast<typename std::add_const<T1>::type>(obj) != nullptr;\n  }\n\n  template <typename T1, typename T2>\n  inline bool is(Ref<T2> const& obj) { // For shared pointers.\n    return dynamic_cast<T1 *>(obj.get()) != nullptr;\n  }\n\n  template <typename T>\n  std::string toString(const T &o) {\n    std::stringstream ss;\n    // typeid gives the mangled class name, but that's all what's possible\n    // in a portable way.\n    ss << typeid(o).name() << \"@\" << std::hex << reinterpret_cast<uintptr_t>(&o);\n    return ss.str();\n  }\n\n  // Get the error text from an exception pointer or the current exception.\n  ANTLR4CPP_PUBLIC std::string what(std::exception_ptr eptr = std::current_exception());\n\n} // namespace antlrcpp\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Casts.h",
    "content": "/* Copyright (c) 2012-2021 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cassert>\n#include <memory>\n#include <type_traits>\n\nnamespace antlrcpp {\n\n  template <typename To, typename From>\n  To downCast(From* from) {\n    static_assert(std::is_pointer_v<To>, \"Target type not a pointer.\");\n    static_assert(std::is_base_of_v<From, std::remove_pointer_t<To>>, \"Target type not derived from source type.\");\n  #if !defined(__GNUC__) || defined(__GXX_RTTI)\n    assert(from == nullptr || dynamic_cast<To>(from) != nullptr);\n  #endif\n    return static_cast<To>(from);\n  }\n\n  template <typename To, typename From>\n  To downCast(From& from) {\n    static_assert(std::is_lvalue_reference_v<To>, \"Target type not a lvalue reference.\");\n    static_assert(std::is_base_of_v<From, std::remove_reference_t<To>>, \"Target type not derived from source type.\");\n  #if !defined(__GNUC__) || defined(__GXX_RTTI)\n    assert(dynamic_cast<std::add_pointer_t<std::remove_reference_t<To>>>(std::addressof(from)) != nullptr);\n  #endif\n    return static_cast<To>(from);\n  }\n\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Declarations.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\nnamespace antlr4 {\n  class ANTLRErrorListener;\n  class ANTLRErrorStrategy;\n  class ANTLRFileStream;\n  class ANTLRInputStream;\n  class BailErrorStrategy;\n  class BaseErrorListener;\n  class BufferedTokenStream;\n  class CharStream;\n  class CommonToken;\n  class CommonTokenFactory;\n  class CommonTokenStream;\n  class ConsoleErrorListener;\n  class DefaultErrorStrategy;\n  class DiagnosticErrorListener;\n  class EmptyStackException;\n  class FailedPredicateException;\n  class IllegalArgumentException;\n  class IllegalStateException;\n  class InputMismatchException;\n  class IntStream;\n  class InterpreterRuleContext;\n  class Lexer;\n  class LexerInterpreter;\n  class LexerNoViableAltException;\n  class ListTokenSource;\n  class NoSuchElementException;\n  class NoViableAltException;\n  class NullPointerException;\n  class ParseCancellationException;\n  class Parser;\n  class ParserInterpreter;\n  class ParserRuleContext;\n  class ProxyErrorListener;\n  class RecognitionException;\n  class Recognizer;\n  class RuleContext;\n  class Token;\n  template<typename Symbol> class TokenFactory;\n  class TokenSource;\n  class TokenStream;\n  class TokenStreamRewriter;\n  class UnbufferedCharStream;\n  class UnbufferedTokenStream;\n  class WritableToken;\n\n  namespace misc {\n    class InterpreterDataReader;\n    class Interval;\n    class IntervalSet;\n    class MurmurHash;\n    class Utils;\n    class Predicate;\n  }\n  namespace atn {\n    class ATN;\n    class ATNConfig;\n    class ATNConfigSet;\n    class ATNDeserializationOptions;\n    class ATNDeserializer;\n    class ATNSerializer;\n    class ATNSimulator;\n    class ATNState;\n    enum class ATNType;\n    class ActionTransition;\n    class ArrayPredictionContext;\n    class AtomTransition;\n    class BasicBlockStartState;\n    class BasicState;\n    class BlockEndState;\n    class BlockStartState;\n    class DecisionState;\n    class EpsilonTransition;\n    class LL1Analyzer;\n    class LexerAction;\n    class LexerActionExecutor;\n    class LexerATNConfig;\n    class LexerATNSimulator;\n    class LexerMoreAction;\n    class LexerPopModeAction;\n    class LexerSkipAction;\n    class LookaheadEventInfo;\n    class LoopEndState;\n    class NotSetTransition;\n    class OrderedATNConfigSet;\n    class ParseInfo;\n    class ParserATNSimulator;\n    class PlusBlockStartState;\n    class PlusLoopbackState;\n    class PrecedencePredicateTransition;\n    class PredicateTransition;\n    class PredictionContext;\n    enum class PredictionMode;\n    class PredictionModeClass;\n    class RangeTransition;\n    class RuleStartState;\n    class RuleStopState;\n    class RuleTransition;\n    class SemanticContext;\n    class SetTransition;\n    class SingletonPredictionContext;\n    class StarBlockStartState;\n    class StarLoopEntryState;\n    class StarLoopbackState;\n    class TokensStartState;\n    class Transition;\n    class WildcardTransition;\n  }\n  namespace dfa {\n    class DFA;\n    class DFASerializer;\n    class DFAState;\n    class LexerDFASerializer;\n    class Vocabulary;\n  }\n  namespace tree {\n    class AbstractParseTreeVisitor;\n    class ErrorNode;\n    class ErrorNodeImpl;\n    class ParseTree;\n    class ParseTreeListener;\n    template<typename T> class ParseTreeProperty;\n    class ParseTreeVisitor;\n    class ParseTreeWalker;\n    class SyntaxTree;\n    class TerminalNode;\n    class TerminalNodeImpl;\n    class Tree;\n    class Trees;\n\n    namespace pattern {\n      class Chunk;\n      class ParseTreeMatch;\n      class ParseTreePattern;\n      class ParseTreePatternMatcher;\n      class RuleTagToken;\n      class TagChunk;\n      class TextChunk;\n      class TokenTagToken;\n    }\n\n    namespace xpath {\n      class XPath;\n      class XPathElement;\n      class XPathLexerErrorListener;\n      class XPathRuleAnywhereElement;\n      class XPathRuleElement;\n      class XPathTokenAnywhereElement;\n      class XPathTokenElement;\n      class XPathWildcardAnywhereElement;\n      class XPathWildcardElement;\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/StringUtils.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string_view>\n#include <string>\n#include \"support/StringUtils.h\"\n\nnamespace antlrcpp {\n\n  std::string escapeWhitespace(std::string_view in) {\n    std::string out;\n    escapeWhitespace(out, in);\n    out.shrink_to_fit();\n    return out;\n  }\n\n  std::string& escapeWhitespace(std::string& out, std::string_view in) {\n    out.reserve(in.size());  // Best case, no escaping.\n    for (const auto &c : in) {\n      switch (c) {\n        case '\\t':\n          out.append(\"\\\\t\");\n          break;\n        case '\\r':\n          out.append(\"\\\\r\");\n          break;\n        case '\\n':\n          out.append(\"\\\\n\");\n          break;\n        default:\n          out.push_back(c);\n          break;\n      }\n    }\n    return out;\n  }\n\n} // namespace antrlcpp\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/StringUtils.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string_view>\n#include <string>\n#include \"antlr4-common.h\"\n\nnamespace antlrcpp {\n\n  ANTLR4CPP_PUBLIC std::string escapeWhitespace(std::string_view in);\n\n  ANTLR4CPP_PUBLIC std::string& escapeWhitespace(std::string& out, std::string_view in);\n\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Unicode.h",
    "content": "/* Copyright (c) 2021 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlrcpp {\n\n  class ANTLR4CPP_PUBLIC Unicode final {\n  public:\n    static constexpr char32_t REPLACEMENT_CHARACTER = 0xfffd;\n\n    static constexpr bool isValid(char32_t codePoint) {\n      return codePoint < 0xd800 || (codePoint > 0xdfff && codePoint <= 0x10ffff);\n    }\n\n  private:\n    Unicode() = delete;\n    Unicode(const Unicode&) = delete;\n    Unicode(Unicode&&) = delete;\n    Unicode& operator=(const Unicode&) = delete;\n    Unicode& operator=(Unicode&&) = delete;\n  };\n\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Utf8.cpp",
    "content": "/* Copyright (c) 2021 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string_view>\n#include <utility>\n#include <string>\n#include <cstddef>\n#include <cassert>\n#include <cstdint>\n\n#include \"support/Utf8.h\"\n#include \"support/Unicode.h\"\n\n// The below implementation is based off of https://github.com/google/cel-cpp/internal/utf8.cc,\n// which is itself based off of https://go.googlesource.com/go/+/refs/heads/master/src/unicode/utf8/utf8.go.\n// If for some reason you feel the need to copy this implementation, please retain a comment\n// referencing the two source files and giving credit, as well as maintaining any and all\n// obligations required by the BSD 3-clause license that governs this file.\n\nnamespace antlrcpp {\n\nnamespace {\n\n#undef SELF\n  constexpr uint8_t SELF = 0x80;\n\n#undef LOW\n  constexpr uint8_t LOW = 0x80;\n#undef HIGH\n  constexpr uint8_t HIGH = 0xbf;\n\n#undef MASKX\n  constexpr uint8_t MASKX = 0x3f;\n#undef MASK2\n  constexpr uint8_t MASK2 = 0x1f;\n#undef MASK3\n  constexpr uint8_t MASK3 = 0xf;\n#undef MASK4\n  constexpr uint8_t MASK4 = 0x7;\n\n#undef TX\n  constexpr uint8_t TX = 0x80;\n#undef T2\n  constexpr uint8_t T2 = 0xc0;\n#undef T3\n  constexpr uint8_t T3 = 0xe0;\n#undef T4\n  constexpr uint8_t T4 = 0xf0;\n\n#undef XX\n  constexpr uint8_t XX = 0xf1;\n#undef AS\n  constexpr uint8_t AS = 0xf0;\n#undef S1\n  constexpr uint8_t S1 = 0x02;\n#undef S2\n  constexpr uint8_t S2 = 0x13;\n#undef S3\n  constexpr uint8_t S3 = 0x03;\n#undef S4\n  constexpr uint8_t S4 = 0x23;\n#undef S5\n  constexpr uint8_t S5 = 0x34;\n#undef S6\n  constexpr uint8_t S6 = 0x04;\n#undef S7\n  constexpr uint8_t S7 = 0x44;\n\n  // NOLINTBEGIN\n  // clang-format off\n#undef LEADING\n  constexpr uint8_t LEADING[256] = {\n    //   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x00-0x0F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x10-0x1F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x20-0x2F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x30-0x3F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x40-0x4F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x50-0x5F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x60-0x6F\n    AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x70-0x7F\n    //   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F\n    XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0x80-0x8F\n    XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0x90-0x9F\n    XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0xA0-0xAF\n    XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0xB0-0xBF\n    XX, XX, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, // 0xC0-0xCF\n    S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, // 0xD0-0xDF\n    S2, S3, S3, S3, S3, S3, S3, S3, S3, S3, S3, S3, S3, S4, S3, S3, // 0xE0-0xEF\n    S5, S6, S6, S6, S7, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0xF0-0xFF\n  };\n  // clang-format on\n  // NOLINTEND\n\n#undef ACCEPT\n  constexpr std::pair<uint8_t, uint8_t> ACCEPT[16] = {\n      {LOW, HIGH}, {0xa0, HIGH}, {LOW, 0x9f}, {0x90, HIGH},\n      {LOW, 0x8f}, {0x0, 0x0},   {0x0, 0x0},  {0x0, 0x0},\n      {0x0, 0x0},  {0x0, 0x0},   {0x0, 0x0},  {0x0, 0x0},\n      {0x0, 0x0},  {0x0, 0x0},   {0x0, 0x0},  {0x0, 0x0},\n  };\n\n}  // namespace\n\n  std::pair<char32_t, size_t> Utf8::decode(std::string_view input) {\n    assert(!input.empty());\n    const auto b = static_cast<uint8_t>(input.front());\n    input.remove_prefix(1);\n    if (b < SELF) {\n      return {static_cast<char32_t>(b), 1};\n    }\n    const auto leading = LEADING[b];\n    if (leading == XX) {\n      return {Unicode::REPLACEMENT_CHARACTER, 1};\n    }\n    auto size = static_cast<size_t>(leading & 7) - 1;\n    if (size > input.size()) {\n      return {Unicode::REPLACEMENT_CHARACTER, 1};\n    }\n    const auto& accept = ACCEPT[leading >> 4];\n    const auto b1 = static_cast<uint8_t>(input.front());\n    input.remove_prefix(1);\n    if (b1 < accept.first || b1 > accept.second) {\n      return {Unicode::REPLACEMENT_CHARACTER, 1};\n    }\n    if (size <= 1) {\n      return {(static_cast<char32_t>(b & MASK2) << 6) |\n                  static_cast<char32_t>(b1 & MASKX),\n              2};\n    }\n    const auto b2 = static_cast<uint8_t>(input.front());\n    input.remove_prefix(1);\n    if (b2 < LOW || b2 > HIGH) {\n      return {Unicode::REPLACEMENT_CHARACTER, 1};\n    }\n    if (size <= 2) {\n      return {(static_cast<char32_t>(b & MASK3) << 12) |\n                  (static_cast<char32_t>(b1 & MASKX) << 6) |\n                  static_cast<char32_t>(b2 & MASKX),\n              3};\n    }\n    const auto b3 = static_cast<uint8_t>(input.front());\n    input.remove_prefix(1);\n    if (b3 < LOW || b3 > HIGH) {\n      return {Unicode::REPLACEMENT_CHARACTER, 1};\n    }\n    return {(static_cast<char32_t>(b & MASK4) << 18) |\n                (static_cast<char32_t>(b1 & MASKX) << 12) |\n                (static_cast<char32_t>(b2 & MASKX) << 6) |\n                static_cast<char32_t>(b3 & MASKX),\n            4};\n  }\n\n  std::optional<std::u32string> Utf8::strictDecode(std::string_view input) {\n    std::u32string output;\n    char32_t codePoint;\n    size_t codeUnits;\n    output.reserve(input.size());  // Worst case is each byte is a single Unicode code point.\n    for (size_t index = 0; index < input.size(); index += codeUnits) {\n      std::tie(codePoint, codeUnits) = Utf8::decode(input.substr(index));\n      if (codePoint == Unicode::REPLACEMENT_CHARACTER && codeUnits == 1) {\n        // Condition is only met when an illegal byte sequence is encountered. See Utf8::decode.\n        return std::nullopt;\n      }\n      output.push_back(codePoint);\n    }\n    output.shrink_to_fit();\n    return output;\n  }\n\n  std::u32string Utf8::lenientDecode(std::string_view input) {\n    std::u32string output;\n    char32_t codePoint;\n    size_t codeUnits;\n    output.reserve(input.size());  // Worst case is each byte is a single Unicode code point.\n    for (size_t index = 0; index < input.size(); index += codeUnits) {\n      std::tie(codePoint, codeUnits) = Utf8::decode(input.substr(index));\n      output.push_back(codePoint);\n    }\n    output.shrink_to_fit();\n    return output;\n  }\n\n  std::string& Utf8::encode(std::string* buffer, char32_t codePoint) {\n    assert(buffer != nullptr);\n    if (!Unicode::isValid(codePoint)) {\n      codePoint = Unicode::REPLACEMENT_CHARACTER;\n    }\n    if (codePoint <= 0x7f) {\n      buffer->push_back(static_cast<char>(static_cast<uint8_t>(codePoint)));\n    } else if (codePoint <= 0x7ff) {\n      buffer->push_back(\n          static_cast<char>(T2 | static_cast<uint8_t>(codePoint >> 6)));\n      buffer->push_back(\n          static_cast<char>(TX | (static_cast<uint8_t>(codePoint) & MASKX)));\n    } else if (codePoint <= 0xffff) {\n      buffer->push_back(\n          static_cast<char>(T3 | static_cast<uint8_t>(codePoint >> 12)));\n      buffer->push_back(static_cast<char>(\n          TX | (static_cast<uint8_t>(codePoint >> 6) & MASKX)));\n      buffer->push_back(\n          static_cast<char>(TX | (static_cast<uint8_t>(codePoint) & MASKX)));\n    } else {\n      buffer->push_back(\n          static_cast<char>(T4 | static_cast<uint8_t>(codePoint >> 18)));\n      buffer->push_back(static_cast<char>(\n          TX | (static_cast<uint8_t>(codePoint >> 12) & MASKX)));\n      buffer->push_back(static_cast<char>(\n          TX | (static_cast<uint8_t>(codePoint >> 6) & MASKX)));\n      buffer->push_back(\n          static_cast<char>(TX | (static_cast<uint8_t>(codePoint) & MASKX)));\n    }\n    return *buffer;\n  }\n\n  std::optional<std::string> Utf8::strictEncode(std::u32string_view input) {\n    std::string output;\n    output.reserve(input.size() * 4);  // Worst case is each Unicode code point encodes to 4 bytes.\n    for (size_t index = 0; index < input.size(); index++) {\n      char32_t codePoint = input[index];\n      if (!Unicode::isValid(codePoint)) {\n        return std::nullopt;\n      }\n      Utf8::encode(&output, codePoint);\n    }\n    output.shrink_to_fit();\n    return output;\n  }\n\n  std::string Utf8::lenientEncode(std::u32string_view input) {\n    std::string output;\n    output.reserve(input.size() * 4);  // Worst case is each Unicode code point encodes to 4 bytes.\n    for (size_t index = 0; index < input.size(); index++) {\n      char32_t codePoint = input[index];\n      if (!Unicode::isValid(codePoint)) {\n        codePoint = Unicode::REPLACEMENT_CHARACTER;\n      }\n      Utf8::encode(&output, codePoint);\n    }\n    output.shrink_to_fit();\n    return output;\n  }\n\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/support/Utf8.h",
    "content": "/* Copyright (c) 2021 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <cstddef>\n#include <optional>\n#include <string>\n#include <string_view>\n#include <tuple>\n\n#include \"antlr4-common.h\"\n\nnamespace antlrcpp {\n\n  class ANTLR4CPP_PUBLIC Utf8 final {\n  public:\n    // Decodes the next code point, returning the decoded code point and the number\n    // of code units (a.k.a. bytes) consumed. In the event that an invalid code unit\n    // sequence is returned the replacement character, U+FFFD, is returned with a\n    // code unit count of 1. As U+FFFD requires 3 code units when encoded, this can\n    // be used to differentiate valid input from malformed input.\n    static std::pair<char32_t, size_t> decode(std::string_view input);\n\n    // Decodes the given UTF-8 encoded input into a string of code points.\n    static std::optional<std::u32string> strictDecode(std::string_view input);\n\n    // Decodes the given UTF-8 encoded input into a string of code points. Unlike strictDecode(),\n    // each byte in an illegal byte sequence is replaced with the Unicode replacement character,\n    // U+FFFD.\n    static std::u32string lenientDecode(std::string_view input);\n\n    // Encodes the given code point and appends it to the buffer. If the code point\n    // is an unpaired surrogate or outside of the valid Unicode range it is replaced\n    // with the replacement character, U+FFFD.\n    static std::string& encode(std::string *buffer, char32_t codePoint);\n\n    // Encodes the given Unicode code point string as UTF-8.\n    static std::optional<std::string> strictEncode(std::u32string_view input);\n\n    // Encodes the given Unicode code point string as UTF-8. Unlike strictEncode(),\n    // each invalid Unicode code point is replaced with the Unicode replacement character, U+FFFD.\n    static std::string lenientEncode(std::u32string_view input);\n\n  private:\n    Utf8() = delete;\n    Utf8(const Utf8&) = delete;\n    Utf8(Utf8&&) = delete;\n    Utf8& operator=(const Utf8&) = delete;\n    Utf8& operator=(Utf8&&) = delete;\n  };\n\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/AbstractParseTreeVisitor.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <utility>\n#include <cstddef>\n#include \"tree/ParseTree.h\"\n#include \"antlr4-common.h\"\n#include \"tree/ParseTreeVisitor.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  class ANTLR4CPP_PUBLIC AbstractParseTreeVisitor : public ParseTreeVisitor {\n  public:\n    /// The default implementation calls <seealso cref=\"ParseTree#accept\"/> on the\n    /// specified tree.\n    std::any visit(ParseTree *tree) override {\n      return tree->accept(this);\n    }\n\n    /**\n     * <p>The default implementation initializes the aggregate result to\n     * {@link #defaultResult defaultResult()}. Before visiting each child, it\n     * calls {@link #shouldVisitNextChild shouldVisitNextChild}; if the result\n     * is {@code false} no more children are visited and the current aggregate\n     * result is returned. After visiting a child, the aggregate result is\n     * updated by calling {@link #aggregateResult aggregateResult} with the\n     * previous aggregate result and the result of visiting the child.</p>\n     *\n     * <p>The default implementation is not safe for use in visitors that modify\n     * the tree structure. Visitors that modify the tree should override this\n     * method to behave properly in respect to the specific algorithm in use.</p>\n     */\n    std::any visitChildren(ParseTree *node) override {\n      std::any result = defaultResult();\n      size_t n = node->children.size();\n      for (size_t i = 0; i < n; i++) {\n        if (!shouldVisitNextChild(node, result)) {\n          break;\n        }\n\n        std::any childResult = node->children[i]->accept(this);\n        result = aggregateResult(std::move(result), std::move(childResult));\n      }\n\n      return result;\n    }\n\n    /// The default implementation returns the result of\n    /// <seealso cref=\"#defaultResult defaultResult\"/>.\n    std::any visitTerminal(TerminalNode * /*node*/) override {\n      return defaultResult();\n    }\n\n    /// The default implementation returns the result of\n    /// <seealso cref=\"#defaultResult defaultResult\"/>.\n    std::any visitErrorNode(ErrorNode * /*node*/) override {\n      return defaultResult();\n    }\n\n  protected:\n    /// <summary>\n    /// Gets the default value returned by visitor methods. This value is\n    /// returned by the default implementations of\n    /// <seealso cref=\"#visitTerminal visitTerminal\"/>, <seealso cref=\"#visitErrorNode visitErrorNode\"/>.\n    /// The default implementation of <seealso cref=\"#visitChildren visitChildren\"/>\n    /// initializes its aggregate result to this value.\n    /// <p/>\n    /// The base implementation returns {@code std::any()}.\n    /// </summary>\n    /// <returns> The default value returned by visitor methods. </returns>\n    virtual std::any defaultResult() {\n      return std::any();\n    }\n\n    /// <summary>\n    /// Aggregates the results of visiting multiple children of a node. After\n    /// either all children are visited or <seealso cref=\"#shouldVisitNextChild\"/> returns\n    /// {@code false}, the aggregate value is returned as the result of\n    /// <seealso cref=\"#visitChildren\"/>.\n    /// <p/>\n    /// The default implementation returns {@code nextResult}, meaning\n    /// <seealso cref=\"#visitChildren\"/> will return the result of the last child visited\n    /// (or return the initial value if the node has no children).\n    /// </summary>\n    /// <param name=\"aggregate\"> The previous aggregate value. In the default\n    /// implementation, the aggregate value is initialized to\n    /// <seealso cref=\"#defaultResult\"/>, which is passed as the {@code aggregate} argument\n    /// to this method after the first child node is visited. </param>\n    /// <param name=\"nextResult\"> The result of the immediately preceeding call to visit\n    /// a child node.\n    /// </param>\n    /// <returns> The updated aggregate result. </returns>\n    virtual std::any aggregateResult(std::any /*aggregate*/, std::any nextResult) {\n      return nextResult;\n    }\n\n    /// <summary>\n    /// This method is called after visiting each child in\n    /// <seealso cref=\"#visitChildren\"/>. This method is first called before the first\n    /// child is visited; at that point {@code currentResult} will be the initial\n    /// value (in the default implementation, the initial value is returned by a\n    /// call to <seealso cref=\"#defaultResult\"/>. This method is not called after the last\n    /// child is visited.\n    /// <p/>\n    /// The default implementation always returns {@code true}, indicating that\n    /// {@code visitChildren} should only return after all children are visited.\n    /// One reason to override this method is to provide a \"short circuit\"\n    /// evaluation option for situations where the result of visiting a single\n    /// child has the potential to determine the result of the visit operation as\n    /// a whole.\n    /// </summary>\n    /// <param name=\"node\"> The <seealso cref=\"ParseTree\"/> whose children are currently being\n    /// visited. </param>\n    /// <param name=\"currentResult\"> The current aggregate result of the children visited\n    /// to the current point.\n    /// </param>\n    /// <returns> {@code true} to continue visiting children. Otherwise return\n    /// {@code false} to stop visiting children and immediately return the\n    /// current aggregate result from <seealso cref=\"#visitChildren\"/>. </returns>\n    virtual bool shouldVisitNextChild(ParseTree * /*node*/, const std::any &/*currentResult*/) {\n      return true;\n    }\n\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ErrorNode.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"tree/ParseTreeType.h\"\n#include \"tree/TerminalNode.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  class ANTLR4CPP_PUBLIC ErrorNode : public TerminalNode {\n  public:\n    static bool is(const tree::ParseTree &parseTree) { return parseTree.getTreeType() == tree::ParseTreeType::ERROR; }\n\n    static bool is(const tree::ParseTree *parseTree) { return parseTree != nullptr && is(*parseTree); }\n\n  protected:\n    using TerminalNode::TerminalNode;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ErrorNodeImpl.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"RuleContext.h\"\n#include \"tree/ParseTreeVisitor.h\"\n\n#include \"tree/ErrorNodeImpl.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::tree;\n\nToken* ErrorNodeImpl::getSymbol() const {\n  return symbol;\n}\n\nvoid ErrorNodeImpl::setParent(RuleContext *parent_) {\n  this->parent = parent_;\n}\n\nmisc::Interval ErrorNodeImpl::getSourceInterval() {\n  if (symbol == nullptr) {\n    return misc::Interval::INVALID;\n  }\n\n  size_t tokenIndex = symbol->getTokenIndex();\n  return misc::Interval(tokenIndex, tokenIndex);\n}\n\nstd::any ErrorNodeImpl::accept(ParseTreeVisitor *visitor) {\n  return visitor->visitErrorNode(this);\n}\n\nstd::string ErrorNodeImpl::getText() {\n  return symbol->getText();\n}\n\nstd::string ErrorNodeImpl::toStringTree(Parser * /*parser*/, bool /*pretty*/) {\n  return toString();\n}\n\nstd::string ErrorNodeImpl::toString() {\n  if (symbol->getType() == Token::EOF) {\n    return \"<EOF>\";\n  }\n  return symbol->getText();\n}\n\nstd::string ErrorNodeImpl::toStringTree(bool /*pretty*/) {\n  return toString();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ErrorNodeImpl.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"tree/ErrorNode.h\"\n#include \"tree/ParseTreeType.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"tree/TerminalNodeImpl.h\"\n#include \"misc/Interval.h\"\n\n#include \"support/Any.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  /// <summary>\n  /// Represents a token that was consumed during resynchronization\n  ///  rather than during a valid match operation. For example,\n  ///  we will create this kind of a node during single token insertion\n  ///  and deletion as well as during \"consume until error recovery set\"\n  ///  upon no viable alternative exceptions.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC ErrorNodeImpl : public ErrorNode {\n  public:\n    Token *symbol;\n\n    explicit ErrorNodeImpl(Token *symbol) : ErrorNode(ParseTreeType::ERROR), symbol(symbol) {}\n\n    Token* getSymbol() const override;\n    void setParent(RuleContext *parent) override;\n    misc::Interval getSourceInterval() override;\n\n    std::any accept(ParseTreeVisitor *visitor) override;\n\n    std::string getText() override;\n    std::string toStringTree(Parser *parser, bool pretty = false) override;\n    std::string toString() override;\n    std::string toStringTree(bool pretty = false) override;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/IterativeParseTreeWalker.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"support/CPPUtils.h\"\n#include \"support/Casts.h\"\n\n#include \"tree/ParseTreeListener.h\"\n#include \"tree/ParseTree.h\"\n#include \"tree/ErrorNode.h\"\n\n#include \"IterativeParseTreeWalker.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlrcpp;\n\nvoid IterativeParseTreeWalker::walk(ParseTreeListener *listener, ParseTree *t) const {\n  std::vector<std::pair<ParseTree*, size_t>> stack;\n  ParseTree *currentNode = t;\n  size_t currentIndex = 0;\n\n  while (currentNode != nullptr) {\n    // pre-order visit\n    if (ErrorNode::is(*currentNode)) {\n      listener->visitErrorNode(downCast<ErrorNode*>(currentNode));\n    } else if (TerminalNode::is(*currentNode)) {\n      listener->visitTerminal(downCast<TerminalNode*>(currentNode));\n    } else {\n      enterRule(listener, currentNode);\n    }\n\n    // Move down to first child, if it exists.\n    if (!currentNode->children.empty()) {\n      stack.push_back(std::make_pair(currentNode, currentIndex));\n      currentIndex = 0;\n      currentNode = currentNode->children[0];\n      continue;\n    }\n\n    // No child nodes, so walk tree.\n    do {\n      // post-order visit\n      if (!TerminalNode::is(*currentNode)) {\n        exitRule(listener, currentNode);\n      }\n\n      // No parent, so no siblings.\n      if (stack.empty()) {\n        currentNode = nullptr;\n        currentIndex = 0;\n        break;\n      }\n\n      // Move to next sibling if possible.\n      if (stack.back().first->children.size() > ++currentIndex) {\n        currentNode = stack.back().first->children[currentIndex];\n        break;\n      }\n\n      // No next sibling, so move up.\n      std::tie(currentNode, currentIndex) = stack.back();\n      stack.pop_back();\n    } while (currentNode != nullptr);\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/IterativeParseTreeWalker.h",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012 Terence Parr\n *  Copyright (c) 2012 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\n#include \"tree/ParseTreeWalker.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  class ParseTreeListener;\n  \n  /**\n   * An iterative (read: non-recursive) pre-order and post-order tree walker that\n   * doesn't use the thread stack but heap-based stacks. Makes it possible to\n   * process deeply nested parse trees.\n   */\n  class ANTLR4CPP_PUBLIC IterativeParseTreeWalker : public ParseTreeWalker {\n  public:\n    void walk(ParseTreeListener *listener, ParseTree *t) const override;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTree.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"tree/ParseTree.h\"\n\nusing namespace antlr4::tree;\n\nbool ParseTree::operator == (const ParseTree &other) const {\n  return &other == this;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTree.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include \"support/Any.h\"\n#include \"misc/Interval.h\"\n#include \"antlr4-common.h\"\n#include \"tree/ParseTreeType.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  /// An interface to access the tree of <seealso cref=\"RuleContext\"/> objects created\n  /// during a parse that makes the data structure look like a simple parse tree.\n  /// This node represents both internal nodes, rule invocations,\n  /// and leaf nodes, token matches.\n  ///\n  /// The payload is either a <seealso cref=\"Token\"/> or a <seealso cref=\"RuleContext\"/> object.\n  // ml: This class unites 4 Java classes: RuleNode, ParseTree, SyntaxTree and Tree.\n  class ANTLR4CPP_PUBLIC ParseTree {\n  public:\n    ParseTree(ParseTree const&) = delete;\n\n    virtual ~ParseTree() = default;\n\n    ParseTree& operator=(ParseTree const&) = delete;\n\n    /// The parent of this node. If the return value is null, then this\n    /// node is the root of the tree.\n    ParseTree *parent = nullptr;\n\n    /// If we are debugging or building a parse tree for a visitor,\n    /// we need to track all of the tokens and rule invocations associated\n    /// with this rule's context. This is empty for parsing w/o tree constr.\n    /// operation because we don't the need to track the details about\n    /// how we parse this rule.\n    // ml: memory is not managed here, but by the owning class. This is just for the structure.\n    std::vector<ParseTree *> children;\n\n    /// Print out a whole tree, not just a node, in LISP format\n    /// {@code (root child1 .. childN)}. Print just a node if this is a leaf.\n    virtual std::string toStringTree(bool pretty = false) = 0;\n    virtual std::string toString() = 0;\n\n    /// Specialize toStringTree so that it can print out more information\n    /// based upon the parser.\n    virtual std::string toStringTree(Parser *parser, bool pretty = false) = 0;\n\n    virtual bool operator == (const ParseTree &other) const;\n\n    /// The <seealso cref=\"ParseTreeVisitor\"/> needs a double dispatch method.\n    // ml: This has been changed to use Any instead of a template parameter, to avoid the need of a virtual template function.\n    virtual std::any accept(ParseTreeVisitor *visitor) = 0;\n\n    /// Return the combined text of all leaf nodes. Does not get any\n    /// off-channel tokens (if any) so won't return whitespace and\n    /// comments if they are sent to parser on hidden channel.\n    virtual std::string getText() = 0;\n\n    /**\n     * Return an {@link Interval} indicating the index in the\n     * {@link TokenStream} of the first and last token associated with this\n     * subtree. If this node is a leaf, then the interval represents a single\n     * token and has interval i..i for token index i.\n     *\n     * <p>An interval of i..i-1 indicates an empty interval at position\n     * i in the input stream, where 0 &lt;= i &lt;= the size of the input\n     * token stream.  Currently, the code base can only have i=0..n-1 but\n     * in concept one could have an empty interval after EOF. </p>\n     *\n     * <p>If source interval is unknown, this returns {@link Interval#INVALID}.</p>\n     *\n     * <p>As a weird special case, the source interval for rules matched after\n     * EOF is unspecified.</p>\n     */\n    virtual misc::Interval getSourceInterval() = 0;\n\n    ParseTreeType getTreeType() const { return _treeType; }\n\n  protected:\n    explicit ParseTree(ParseTreeType treeType) : _treeType(treeType) {}\n\n  private:\n    const ParseTreeType _treeType;\n  };\n\n  // A class to help managing ParseTree instances without the need of a shared_ptr.\n  class ANTLR4CPP_PUBLIC ParseTreeTracker {\n  public:\n    template<typename T, typename ... Args>\n    T* createInstance(Args&& ... args) {\n      static_assert(std::is_base_of<ParseTree, T>::value, \"Argument must be a parse tree type\");\n      T* result = new T(args...);\n      _allocated.push_back(result);\n      return result;\n    }\n\n    void reset() {\n      for (auto * entry : _allocated)\n        delete entry;\n      _allocated.clear();\n    }\n\n  private:\n    std::vector<ParseTree *> _allocated;\n  };\n\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeListener.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"ParseTreeListener.h\"\n\nantlr4::tree::ParseTreeListener::~ParseTreeListener() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeListener.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  /** This interface describes the minimal core of methods triggered\n   *  by {@link ParseTreeWalker}. E.g.,\n   *\n   *  \tParseTreeWalker walker = new ParseTreeWalker();\n   *\t\twalker.walk(myParseTreeListener, myParseTree); <-- triggers events in your listener\n   *\n   *  If you want to trigger events in multiple listeners during a single\n   *  tree walk, you can use the ParseTreeDispatcher object available at\n   *\n   * \t\thttps://github.com/antlr/antlr4/issues/841\n   */\n  class ANTLR4CPP_PUBLIC ParseTreeListener {\n  public:\n    virtual ~ParseTreeListener();\n\n    virtual void visitTerminal(TerminalNode *node) = 0;\n    virtual void visitErrorNode(ErrorNode *node) = 0;\n    virtual void enterEveryRule(ParserRuleContext *ctx) = 0;\n    virtual void exitEveryRule(ParserRuleContext *ctx) = 0;\n\n    bool operator == (const ParseTreeListener &other) {\n      return this == &other;\n    }\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeProperty.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  /// <summary>\n  /// Associate a property with a parse tree node. Useful with parse tree listeners\n  /// that need to associate values with particular tree nodes, kind of like\n  /// specifying a return value for the listener event method that visited a\n  /// particular node. Example:\n  ///\n  /// <pre>\n  /// ParseTreeProperty&lt;Integer&gt; values = new ParseTreeProperty&lt;Integer&gt;();\n  /// values.put(tree, 36);\n  /// int x = values.get(tree);\n  /// values.removeFrom(tree);\n  /// </pre>\n  ///\n  /// You would make one decl (values here) in the listener and use lots of times\n  /// in your event methods.\n  /// </summary>\n  template<typename V>\n  class ANTLR4CPP_PUBLIC ParseTreeProperty {\n  public:\n    virtual ~ParseTreeProperty() {}\n    virtual V get(ParseTree *node) {\n      return _annotations[node];\n    }\n    virtual void put(ParseTree *node, V value) {\n      _annotations[node] = value;\n    }\n    virtual V removeFrom(ParseTree *node) {\n      auto value = _annotations[node];\n      _annotations.erase(node);\n      return value;\n    }\n\n  protected:\n    std::map<ParseTree*, V> _annotations;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeType.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <cstddef>\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  enum class ParseTreeType : size_t {\n    TERMINAL = 1,\n    ERROR = 2,\n    RULE = 3,\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeVisitor.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"ParseTreeVisitor.h\"\n\nantlr4::tree::ParseTreeVisitor::~ParseTreeVisitor() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeVisitor.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"support/Any.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  /// <summary>\n  /// This interface defines the basic notion of a parse tree visitor. Generated\n  /// visitors implement this interface and the {@code XVisitor} interface for\n  /// grammar {@code X}.\n  /// </summary>\n  /// @param <T> The return type of the visit operation. Use <seealso cref=\"Void\"/> for\n  /// operations with no return type. </param>\n  // ml: no template parameter here, to avoid the need for virtual template functions. Instead we have our Any class.\n  class ANTLR4CPP_PUBLIC ParseTreeVisitor {\n  public:\n    virtual ~ParseTreeVisitor();\n\n    /// <summary>\n    /// Visit a parse tree, and return a user-defined result of the operation.\n    /// </summary>\n    /// <param name=\"tree\"> The <seealso cref=\"ParseTree\"/> to visit. </param>\n    /// <returns> The result of visiting the parse tree. </returns>\n    virtual std::any visit(ParseTree *tree) = 0;\n\n    /// <summary>\n    /// Visit the children of a node, and return a user-defined result of the\n    /// operation.\n    /// </summary>\n    /// <param name=\"node\"> The <seealso cref=\"ParseTree\"/> whose children should be visited. </param>\n    /// <returns> The result of visiting the children of the node. </returns>\n    virtual std::any visitChildren(ParseTree *node) = 0;\n\n    /// <summary>\n    /// Visit a terminal node, and return a user-defined result of the operation.\n    /// </summary>\n    /// <param name=\"node\"> The <seealso cref=\"TerminalNode\"/> to visit. </param>\n    /// <returns> The result of visiting the node. </returns>\n    virtual std::any visitTerminal(TerminalNode *node) = 0;\n\n    /// <summary>\n    /// Visit an error node, and return a user-defined result of the operation.\n    /// </summary>\n    /// <param name=\"node\"> The <seealso cref=\"ErrorNode\"/> to visit. </param>\n    /// <returns> The result of visiting the node. </returns>\n    virtual std::any visitErrorNode(ErrorNode *node) = 0;\n\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeWalker.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"tree/ErrorNode.h\"\n#include \"ParserRuleContext.h\"\n#include \"tree/ParseTreeListener.h\"\n#include \"support/CPPUtils.h\"\n#include \"support/Casts.h\"\n\n#include \"tree/IterativeParseTreeWalker.h\"\n#include \"tree/ParseTreeWalker.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlrcpp;\n\nstatic IterativeParseTreeWalker defaultWalker;\nParseTreeWalker &ParseTreeWalker::DEFAULT = defaultWalker;\n\nvoid ParseTreeWalker::walk(ParseTreeListener *listener, ParseTree *t) const {\n  if (ErrorNode::is(*t)) {\n    listener->visitErrorNode(downCast<ErrorNode*>(t));\n    return;\n  }\n  if (TerminalNode::is(*t)) {\n    listener->visitTerminal(downCast<TerminalNode*>(t));\n    return;\n  }\n\n  enterRule(listener, t);\n  for (auto &child : t->children) {\n    walk(listener, child);\n  }\n  exitRule(listener, t);\n}\n\nvoid ParseTreeWalker::enterRule(ParseTreeListener *listener, ParseTree *r) const {\n  auto *ctx = downCast<ParserRuleContext*>(r);\n  listener->enterEveryRule(ctx);\n  ctx->enterRule(listener);\n}\n\nvoid ParseTreeWalker::exitRule(ParseTreeListener *listener, ParseTree *r) const {\n  auto *ctx = downCast<ParserRuleContext*>(r);\n  ctx->exitRule(listener);\n  listener->exitEveryRule(ctx);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/ParseTreeWalker.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  class ANTLR4CPP_PUBLIC ParseTreeWalker {\n  public:\n    static ParseTreeWalker &DEFAULT;\n\n    virtual ~ParseTreeWalker() = default;\n\n    /**\n    * <summary>\n    * Performs a walk on the given parse tree starting at the root and going down recursively\n\t* with depth-first search. On each node, <seealso cref=\"ParseTreeWalker#enterRule\"/> is called before\n    * recursively walking down into child nodes, then\n    * <seealso cref=\"ParseTreeWalker#exitRule\"/> is called after the recursive call to wind up.\n\t* </summary>\n    * <param name='listener'> The listener used by the walker to process grammar rules </param>\n\t* <param name='t'> The parse tree to be walked on </param>\n    */\n    virtual void walk(ParseTreeListener *listener, ParseTree *t) const;\n\n  protected:\n\n    /**\n    * <summary>\n    * Enters a grammar rule by first triggering the generic event <seealso cref=\"ParseTreeListener#enterEveryRule\"/>\n\t* then by triggering the event specific to the given parse tree node\n\t* </summary>\n    * <param name='listener'> The listener responding to the trigger events </param>\n\t* <param name='r'> The grammar rule containing the rule context </param>\n    */\n    virtual void enterRule(ParseTreeListener *listener, ParseTree *r) const;\n\n    /**\n    * <summary>\n    * Exits a grammar rule by first triggering the event specific to the given parse tree node\n\t* then by triggering the generic event <seealso cref=\"ParseTreeListener#exitEveryRule\"/>\n\t* </summary>\n    * <param name='listener'> The listener responding to the trigger events </param>\n\t* <param name='r'> The grammar rule containing the rule context </param>\n    */\n    virtual void exitRule(ParseTreeListener *listener, ParseTree *r) const;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/TerminalNode.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include \"antlr4-common.h\"\n#include \"tree/ParseTreeType.h\"\n#include \"Token.h\"\n#include \"tree/ParseTree.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  class ANTLR4CPP_PUBLIC TerminalNode : public ParseTree {\n  public:\n    static bool is(const tree::ParseTree &parseTree) {\n      const auto treeType = parseTree.getTreeType();\n      return treeType == ParseTreeType::TERMINAL || treeType == ParseTreeType::ERROR;\n    }\n\n    static bool is(const tree::ParseTree *parseTree) { return parseTree != nullptr && is(*parseTree); }\n\n    virtual Token* getSymbol() const = 0;\n\n    /** Set the parent for this leaf node.\n     *\n     *  Technically, this is not backward compatible as it changes\n     *  the interface but no one was able to create custom\n     *  TerminalNodes anyway so I'm adding as it improves internal\n     *  code quality.\n     *\n     *  @since 4.7\n     */\n    virtual void setParent(RuleContext *parent) = 0;\n\n  protected:\n    using ParseTree::ParseTree;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/TerminalNodeImpl.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"RuleContext.h\"\n#include \"tree/ParseTreeVisitor.h\"\n\n#include \"tree/TerminalNodeImpl.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::tree;\n\nToken* TerminalNodeImpl::getSymbol() const {\n  return symbol;\n}\n\nvoid TerminalNodeImpl::setParent(RuleContext *parent_) {\n  this->parent = parent_;\n}\n\nmisc::Interval TerminalNodeImpl::getSourceInterval() {\n  if (symbol == nullptr) {\n    return misc::Interval::INVALID;\n  }\n\n  size_t tokenIndex = symbol->getTokenIndex();\n  return misc::Interval(tokenIndex, tokenIndex);\n}\n\nstd::any TerminalNodeImpl::accept(ParseTreeVisitor *visitor) {\n  return visitor->visitTerminal(this);\n}\n\nstd::string TerminalNodeImpl::getText() {\n  return symbol->getText();\n}\n\nstd::string TerminalNodeImpl::toStringTree(Parser * /*parser*/, bool /*pretty*/) {\n  return toString();\n}\n\nstd::string TerminalNodeImpl::toString() {\n  if (symbol->getType() == Token::EOF) {\n    return \"<EOF>\";\n  }\n  return symbol->getText();\n}\n\nstd::string TerminalNodeImpl::toStringTree(bool /*pretty*/) {\n  return toString();\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/TerminalNodeImpl.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"antlr4-common.h\"\n#include \"tree/ParseTreeType.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"tree/TerminalNode.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  class ANTLR4CPP_PUBLIC TerminalNodeImpl : public TerminalNode {\n  public:\n    Token *symbol;\n\n    explicit TerminalNodeImpl(Token *symbol) : TerminalNode(ParseTreeType::TERMINAL), symbol(symbol) {}\n\n    Token* getSymbol() const override;\n    void setParent(RuleContext *parent) override;\n    misc::Interval getSourceInterval() override;\n\n    std::any accept(ParseTreeVisitor *visitor) override;\n\n    std::string getText() override;\n    std::string toStringTree(Parser *parser, bool pretty = false) override;\n    std::string toString() override;\n    std::string toStringTree(bool pretty = false) override;\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/Trees.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <sstream>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"tree/ErrorNode.h\"\n#include \"antlr4-common.h\"\n#include \"Parser.h\"\n#include \"ParserRuleContext.h\"\n#include \"support/CPPUtils.h\"\n#include \"tree/TerminalNodeImpl.h\"\n#include \"atn/ATN.h\"\n#include \"misc/Interval.h\"\n#include \"Token.h\"\n#include \"CommonToken.h\"\n#include \"misc/Predicate.h\"\n\n#include \"tree/Trees.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::misc;\nusing namespace antlr4::tree;\n\nusing namespace antlrcpp;\n\nTrees::Trees() {\n}\n\nstd::string Trees::toStringTree(ParseTree *t, bool pretty) {\n  return toStringTree(t, nullptr, pretty);\n}\n\nstd::string Trees::toStringTree(ParseTree *t, Parser *recog, bool pretty) {\n  if (recog == nullptr)\n    return toStringTree(t, std::vector<std::string>(), pretty);\n  return toStringTree(t, recog->getRuleNames(), pretty);\n}\n\nstd::string Trees::toStringTree(ParseTree *t, const std::vector<std::string> &ruleNames, bool pretty) {\n  std::string temp = antlrcpp::escapeWhitespace(Trees::getNodeText(t, ruleNames), false);\n  if (t->children.empty()) {\n    return temp;\n  }\n\n  std::stringstream ss;\n  ss << \"(\" << temp << ' ';\n\n  // Implement the recursive walk as iteration to avoid trouble with deep nesting.\n  std::stack<size_t> stack;\n  size_t childIndex = 0;\n  ParseTree *run = t;\n  size_t indentationLevel = 1;\n  while (childIndex < run->children.size()) {\n    if (childIndex > 0) {\n      ss << ' ';\n    }\n    ParseTree *child = run->children[childIndex];\n    temp = antlrcpp::escapeWhitespace(Trees::getNodeText(child, ruleNames), false);\n    if (!child->children.empty()) {\n      // Go deeper one level.\n      stack.push(childIndex);\n      run = child;\n      childIndex = 0;\n      if (pretty) {\n        ++indentationLevel;\n        ss << std::endl;\n        for (size_t i = 0; i < indentationLevel; ++i) {\n          ss << \"    \";\n        }\n      }\n      ss << \"(\" << temp << \" \";\n    } else {\n      ss << temp;\n      while (++childIndex == run->children.size()) {\n        if (stack.size() > 0) {\n          // Reached the end of the current level. See if we can step up from here.\n          childIndex = stack.top();\n          stack.pop();\n          run = run->parent;\n          if (pretty) {\n            --indentationLevel;\n          }\n          ss << \")\";\n        } else {\n          break;\n        }\n      }\n    }\n  }\n\n  ss << \")\";\n  return ss.str();\n}\n\nstd::string Trees::getNodeText(ParseTree *t, Parser *recog) {\n  return getNodeText(t, recog->getRuleNames());\n}\n\nstd::string Trees::getNodeText(ParseTree *t, const std::vector<std::string> &ruleNames) {\n  if (ruleNames.size() > 0) {\n    if (is<RuleContext *>(t)) {\n      size_t ruleIndex = dynamic_cast<RuleContext *>(t)->getRuleIndex();\n      std::string ruleName = ruleNames[ruleIndex];\n      size_t altNumber = dynamic_cast<RuleContext *>(t)->getAltNumber();\n      if (altNumber != atn::ATN::INVALID_ALT_NUMBER) {\n        return ruleName + \":\" + std::to_string(altNumber);\n      }\n      return ruleName;\n    } else if (is<ErrorNode *>(t)) {\n      return t->toString();\n    } else if (is<TerminalNode *>(t)) {\n      Token *symbol = dynamic_cast<TerminalNode *>(t)->getSymbol();\n      if (symbol != nullptr) {\n        std::string s = symbol->getText();\n        return s;\n      }\n    }\n  }\n  // no recog for rule names\n  if (is<RuleContext *>(t)) {\n    return dynamic_cast<RuleContext *>(t)->getText();\n  }\n\n  if (is<TerminalNodeImpl *>(t)) {\n    return dynamic_cast<TerminalNodeImpl *>(t)->getSymbol()->getText();\n  }\n\n  return \"\";\n}\n\nstd::vector<ParseTree *> Trees::getAncestors(ParseTree *t) {\n  std::vector<ParseTree *> ancestors;\n  ParseTree *parent = t->parent;\n  while (parent != nullptr) {\n    ancestors.insert(ancestors.begin(), parent); // insert at start\n    parent = parent->parent;\n  }\n  return ancestors;\n}\n\ntemplate<typename T>\nstatic void _findAllNodes(ParseTree *t, size_t index, bool findTokens, std::vector<T> &nodes) {\n  // check this node (the root) first\n  if (findTokens && is<TerminalNode *>(t)) {\n    TerminalNode *tnode = dynamic_cast<TerminalNode *>(t);\n    if (tnode->getSymbol()->getType() == index) {\n      nodes.push_back(t);\n    }\n  } else if (!findTokens && is<ParserRuleContext *>(t)) {\n    ParserRuleContext *ctx = dynamic_cast<ParserRuleContext *>(t);\n    if (ctx->getRuleIndex() == index) {\n      nodes.push_back(t);\n    }\n  }\n  // check children\n  for (size_t i = 0; i < t->children.size(); i++) {\n    _findAllNodes(t->children[i], index, findTokens, nodes);\n  }\n}\n\nbool Trees::isAncestorOf(ParseTree *t, ParseTree *u) {\n  if (t == nullptr || u == nullptr || t->parent == nullptr) {\n    return false;\n  }\n\n  ParseTree *p = u->parent;\n  while (p != nullptr) {\n    if (t == p) {\n      return true;\n    }\n    p = p->parent;\n  }\n  return false;\n}\n\nstd::vector<ParseTree *> Trees::findAllTokenNodes(ParseTree *t, size_t ttype) {\n  return findAllNodes(t, ttype, true);\n}\n\nstd::vector<ParseTree *> Trees::findAllRuleNodes(ParseTree *t, size_t ruleIndex) {\n  return findAllNodes(t, ruleIndex, false);\n}\n\nstd::vector<ParseTree *> Trees::findAllNodes(ParseTree *t, size_t index, bool findTokens) {\n  std::vector<ParseTree *> nodes;\n  _findAllNodes<ParseTree *>(t, index, findTokens, nodes);\n  return nodes;\n}\n\nstd::vector<ParseTree *> Trees::getDescendants(ParseTree *t) {\n  std::vector<ParseTree *> nodes;\n  nodes.push_back(t);\n  std::size_t n = t->children.size();\n  for (size_t i = 0 ; i < n ; i++) {\n    auto descentants = getDescendants(t->children[i]);\n    for (auto *entry: descentants) {\n      nodes.push_back(entry);\n    }\n  }\n  return nodes;\n}\n\nstd::vector<ParseTree *> Trees::descendants(ParseTree *t) {\n  return getDescendants(t);\n}\n\nParserRuleContext* Trees::getRootOfSubtreeEnclosingRegion(ParseTree *t, size_t startTokenIndex, size_t stopTokenIndex) {\n  size_t n = t->children.size();\n  for (size_t i = 0; i < n; i++) {\n    ParserRuleContext *r = getRootOfSubtreeEnclosingRegion(t->children[i], startTokenIndex, stopTokenIndex);\n    if (r != nullptr) {\n      return r;\n    }\n  }\n\n  if (is<ParserRuleContext *>(t)) {\n    ParserRuleContext *r = dynamic_cast<ParserRuleContext *>(t);\n    if (startTokenIndex >= r->getStart()->getTokenIndex() && // is range fully contained in t?\n        (r->getStop() == nullptr || stopTokenIndex <= r->getStop()->getTokenIndex())) {\n      // note: r.getStop()==null likely implies that we bailed out of parser and there's nothing to the right\n      return r;\n    }\n  }\n  return nullptr;\n}\n\nParseTree * Trees::findNodeSuchThat(ParseTree *t, Ref<Predicate> const& pred) {\n  if (pred->test(t)) {\n    return t;\n  }\n\n  size_t n = t->children.size();\n  for (size_t i = 0 ; i < n ; ++i) {\n    ParseTree *u = findNodeSuchThat(t->children[i], pred);\n    if (u != nullptr) {\n      return u;\n    }\n  }\n\n  return nullptr;\n}\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/Trees.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"tree/TerminalNode.h\"\n#include \"antlr4-common.h\"\n#include \"ParserRuleContext.h\"\n#include \"Recognizer.h\"\n\nnamespace antlr4 {\nnamespace tree {\n\n  /// A set of utility routines useful for all kinds of ANTLR trees.\n  class ANTLR4CPP_PUBLIC Trees {\n  public:\n    /// Print out a whole tree in LISP form. getNodeText is used on the\n    /// node payloads to get the text for the nodes.  Detect\n    /// parse trees and extract data appropriately.\n    static std::string toStringTree(ParseTree *t, bool pretty = false);\n\n    /// Print out a whole tree in LISP form. getNodeText is used on the\n    ///  node payloads to get the text for the nodes.  Detect\n    ///  parse trees and extract data appropriately.\n    static std::string toStringTree(ParseTree *t, Parser *recog, bool pretty = false);\n\n    /// Print out a whole tree in LISP form. getNodeText is used on the\n    /// node payloads to get the text for the nodes.  Detect\n    /// parse trees and extract data appropriately.\n    static std::string toStringTree(ParseTree *t, const std::vector<std::string> &ruleNames, bool pretty = false);\n    static std::string getNodeText(ParseTree *t, Parser *recog);\n    static std::string getNodeText(ParseTree *t, const std::vector<std::string> &ruleNames);\n\n    /// Return a list of all ancestors of this node.  The first node of\n    ///  list is the root and the last is the parent of this node.\n    static std::vector<ParseTree *> getAncestors(ParseTree *t);\n\n    /** Return true if t is u's parent or a node on path to root from u.\n     *  Use == not equals().\n     *\n     *  @since 4.5.1\n     */\n    static bool isAncestorOf(ParseTree *t, ParseTree *u);\n    static std::vector<ParseTree *> findAllTokenNodes(ParseTree *t, size_t ttype);\n    static std::vector<ParseTree *> findAllRuleNodes(ParseTree *t, size_t ruleIndex);\n    static std::vector<ParseTree *> findAllNodes(ParseTree *t, size_t index, bool findTokens);\n\n    /** Get all descendents; includes t itself.\n     *\n     * @since 4.5.1\n     */\n    static std::vector<ParseTree *> getDescendants(ParseTree *t);\n\n    /** @deprecated */\n    static std::vector<ParseTree *> descendants(ParseTree *t);\n\n    /** Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex\n     *  inclusively using postorder traversal.  Recursive depth-first-search.\n     *\n     *  @since 4.5.1\n     */\n    static ParserRuleContext* getRootOfSubtreeEnclosingRegion(ParseTree *t,\n                                                              size_t startTokenIndex, // inclusive\n                                                              size_t stopTokenIndex); // inclusive\n\n    /** Return first node satisfying the pred\n     *\n     *  @since 4.5.1\n     */\n    static ParseTree* findNodeSuchThat(ParseTree *t, Ref<misc::Predicate> const& pred);\n\n  private:\n    Trees();\n  };\n\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/Chunk.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include \"tree/pattern/Chunk.h\"\n\nantlr4::tree::pattern::Chunk::~Chunk() {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/Chunk.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// <summary>\n  /// A chunk is either a token tag, a rule tag, or a span of literal text within a\n  /// tree pattern.\n  /// <p/>\n  /// The method <seealso cref=\"ParseTreePatternMatcher#split(String)\"/> returns a list of\n  /// chunks in preparation for creating a token stream by\n  /// <seealso cref=\"ParseTreePatternMatcher#tokenize(String)\"/>. From there, we get a parse\n  /// tree from with <seealso cref=\"ParseTreePatternMatcher#compile(String, int)\"/>. These\n  /// chunks are converted to <seealso cref=\"RuleTagToken\"/>, <seealso cref=\"TokenTagToken\"/>, or the\n  /// regular tokens of the text surrounding the tags.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC Chunk {\n  public:\n    Chunk() = default;\n    Chunk(Chunk const&) = default;\n    virtual ~Chunk();\n\n    Chunk& operator=(Chunk const&) = default;\n\n    /// This method returns a text representation of the tag chunk. Labeled tags\n    /// are returned in the form {@code label:tag}, and unlabeled tags are\n    /// returned as just the tag name.\n    virtual std::string toString() {\n      std::string str;\n      return str;\n    }\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/ParseTreeMatch.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <map>\n#include <vector>\n#include <string>\n#include \"Exceptions.h\"\n\n#include \"tree/pattern/ParseTreeMatch.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::pattern;\n\nParseTreeMatch::ParseTreeMatch(ParseTree *tree, const ParseTreePattern &pattern,\n                               const std::map<std::string, std::vector<ParseTree *>> &labels,\n                               ParseTree *mismatchedNode)\n  : _tree(tree), _pattern(pattern), _labels(labels), _mismatchedNode(mismatchedNode) {\n  if (tree == nullptr) {\n    throw IllegalArgumentException(\"tree cannot be nul\");\n  }\n}\n\nParseTreeMatch::~ParseTreeMatch() {\n}\n\nParseTree* ParseTreeMatch::get(const std::string &label) {\n  auto iterator = _labels.find(label);\n  if (iterator == _labels.end() || iterator->second.empty()) {\n    return nullptr;\n  }\n\n  return iterator->second.back(); // return last if multiple\n}\n\nstd::vector<ParseTree *> ParseTreeMatch::getAll(const std::string &label) {\n  auto iterator = _labels.find(label);\n  if (iterator == _labels.end()) {\n    return {};\n  }\n\n  return iterator->second;\n}\n\nstd::map<std::string, std::vector<ParseTree *>>& ParseTreeMatch::getLabels() {\n  return _labels;\n}\n\nParseTree *ParseTreeMatch::getMismatchedNode() {\n  return _mismatchedNode;\n}\n\nbool ParseTreeMatch::succeeded() {\n  return _mismatchedNode == nullptr;\n}\n\nconst ParseTreePattern& ParseTreeMatch::getPattern() {\n  return _pattern;\n}\n\nParseTree * ParseTreeMatch::getTree() {\n  return _tree;\n}\n\nstd::string ParseTreeMatch::toString() {\n  if (succeeded()) {\n    return \"Match succeeded; found \" + std::to_string(_labels.size()) + \" labels\";\n  } else {\n    return \"Match failed; found \" + std::to_string(_labels.size()) + \" labels\";\n  }\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/ParseTreeMatch.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <map>\n#include <vector>\n#include <string>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// Represents the result of matching a ParseTree against a tree pattern.\n  class ANTLR4CPP_PUBLIC ParseTreeMatch {\n  private:\n    /// This is the backing field for getTree().\n    ParseTree *_tree;\n\n    /// This is the backing field for getPattern().\n    const ParseTreePattern &_pattern;\n\n    /// This is the backing field for getLabels().\n    std::map<std::string, std::vector<ParseTree *>> _labels;\n\n    /// This is the backing field for getMismatchedNode().\n    ParseTree *_mismatchedNode;\n\n  public:\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"ParseTreeMatch\"/> from the specified\n    /// parse tree and pattern.\n    /// </summary>\n    /// <param name=\"tree\"> The parse tree to match against the pattern. </param>\n    /// <param name=\"pattern\"> The parse tree pattern. </param>\n    /// <param name=\"labels\"> A mapping from label names to collections of\n    /// <seealso cref=\"ParseTree\"/> objects located by the tree pattern matching process. </param>\n    /// <param name=\"mismatchedNode\"> The first node which failed to match the tree\n    /// pattern during the matching process.\n    /// </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code tree} is {@code null} </exception>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code pattern} is {@code null} </exception>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code labels} is {@code null} </exception>\n    ParseTreeMatch(ParseTree *tree, ParseTreePattern const& pattern,\n                   const std::map<std::string, std::vector<ParseTree *>> &labels, ParseTree *mismatchedNode);\n    ParseTreeMatch(ParseTreeMatch const&) = default;\n    virtual ~ParseTreeMatch();\n\n    /// <summary>\n    /// Get the last node associated with a specific {@code label}.\n    /// <p/>\n    /// For example, for pattern {@code <id:ID>}, {@code get(\"id\")} returns the\n    /// node matched for that {@code ID}. If more than one node\n    /// matched the specified label, only the last is returned. If there is\n    /// no node associated with the label, this returns {@code null}.\n    /// <p/>\n    /// Pattern tags like {@code <ID>} and {@code <expr>} without labels are\n    /// considered to be labeled with {@code ID} and {@code expr}, respectively.\n    /// </summary>\n    /// <param name=\"labe\"> The label to check.\n    /// </param>\n    /// <returns> The last <seealso cref=\"ParseTree\"/> to match a tag with the specified\n    /// label, or {@code null} if no parse tree matched a tag with the label. </returns>\n    virtual ParseTree* get(const std::string &label);\n\n    /// <summary>\n    /// Return all nodes matching a rule or token tag with the specified label.\n    /// <p/>\n    /// If the {@code label} is the name of a parser rule or token in the\n    /// grammar, the resulting list will contain both the parse trees matching\n    /// rule or tags explicitly labeled with the label and the complete set of\n    /// parse trees matching the labeled and unlabeled tags in the pattern for\n    /// the parser rule or token. For example, if {@code label} is {@code \"foo\"},\n    /// the result will contain <em>all</em> of the following.\n    ///\n    /// <ul>\n    /// <li>Parse tree nodes matching tags of the form {@code <foo:anyRuleName>} and\n    /// {@code <foo:AnyTokenName>}.</li>\n    /// <li>Parse tree nodes matching tags of the form {@code <anyLabel:foo>}.</li>\n    /// <li>Parse tree nodes matching tags of the form {@code <foo>}.</li>\n    /// </ul>\n    /// </summary>\n    /// <param name=\"labe\"> The label.\n    /// </param>\n    /// <returns> A collection of all <seealso cref=\"ParseTree\"/> nodes matching tags with\n    /// the specified {@code label}. If no nodes matched the label, an empty list\n    /// is returned. </returns>\n    virtual std::vector<ParseTree *> getAll(const std::string &label);\n\n    /// <summary>\n    /// Return a mapping from label &rarr; [list of nodes].\n    /// <p/>\n    /// The map includes special entries corresponding to the names of rules and\n    /// tokens referenced in tags in the original pattern. For additional\n    /// information, see the description of <seealso cref=\"#getAll(String)\"/>.\n    /// </summary>\n    /// <returns> A mapping from labels to parse tree nodes. If the parse tree\n    /// pattern did not contain any rule or token tags, this map will be empty. </returns>\n    virtual std::map<std::string, std::vector<ParseTree *>>& getLabels();\n\n    /// <summary>\n    /// Get the node at which we first detected a mismatch.\n    /// </summary>\n    /// <returns> the node at which we first detected a mismatch, or {@code null}\n    /// if the match was successful. </returns>\n    virtual ParseTree* getMismatchedNode();\n\n    /// <summary>\n    /// Gets a value indicating whether the match operation succeeded.\n    /// </summary>\n    /// <returns> {@code true} if the match operation succeeded; otherwise,\n    /// {@code false}. </returns>\n    virtual bool succeeded();\n\n    /// <summary>\n    /// Get the tree pattern we are matching against.\n    /// </summary>\n    /// <returns> The tree pattern we are matching against. </returns>\n    virtual const ParseTreePattern& getPattern();\n\n    /// <summary>\n    /// Get the parse tree we are trying to match to a pattern.\n    /// </summary>\n    /// <returns> The <seealso cref=\"ParseTree\"/> we are trying to match to a pattern. </returns>\n    virtual ParseTree* getTree();\n\n    virtual std::string toString();\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/ParseTreePattern.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include \"tree/ParseTree.h\"\n#include \"tree/pattern/ParseTreePatternMatcher.h\"\n#include \"tree/pattern/ParseTreeMatch.h\"\n\n#include \"tree/xpath/XPath.h\"\n#include \"tree/xpath/XPathElement.h\"\n\n#include \"tree/pattern/ParseTreePattern.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::pattern;\n\nusing namespace antlrcpp;\n\nParseTreePattern::ParseTreePattern(ParseTreePatternMatcher *matcher, const std::string &pattern, int patternRuleIndex_,\n                                   ParseTree *patternTree)\n  : patternRuleIndex(patternRuleIndex_), _pattern(pattern), _patternTree(patternTree), _matcher(matcher) {\n}\n\nParseTreePattern::~ParseTreePattern() {\n}\n\nParseTreeMatch ParseTreePattern::match(ParseTree *tree) {\n  return _matcher->match(tree, *this);\n}\n\nbool ParseTreePattern::matches(ParseTree *tree) {\n  return _matcher->match(tree, *this).succeeded();\n}\n\nstd::vector<ParseTreeMatch> ParseTreePattern::findAll(ParseTree *tree, const std::string &xpath) {\n  xpath::XPath finder(_matcher->getParser(), xpath);\n  std::vector<ParseTree *> subtrees = finder.evaluate(tree);\n  std::vector<ParseTreeMatch> matches;\n  for (auto *t : subtrees) {\n    ParseTreeMatch aMatch = match(t);\n    if (aMatch.succeeded()) {\n      matches.push_back(aMatch);\n    }\n  }\n  return matches;\n}\n\n\nParseTreePatternMatcher *ParseTreePattern::getMatcher() const {\n  return _matcher;\n}\n\nstd::string ParseTreePattern::getPattern() const {\n  return _pattern;\n}\n\nint ParseTreePattern::getPatternRuleIndex() const {\n  return patternRuleIndex;\n}\n\nParseTree* ParseTreePattern::getPatternTree() const {\n  return _patternTree;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/ParseTreePattern.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// <summary>\n  /// A pattern like {@code <ID> = <expr>;} converted to a <seealso cref=\"ParseTree\"/> by\n  /// <seealso cref=\"ParseTreePatternMatcher#compile(String, int)\"/>.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC ParseTreePattern {\n  public:\n    /// <summary>\n    /// Construct a new instance of the <seealso cref=\"ParseTreePattern\"/> class.\n    /// </summary>\n    /// <param name=\"matcher\"> The <seealso cref=\"ParseTreePatternMatcher\"/> which created this\n    /// tree pattern. </param>\n    /// <param name=\"pattern\"> The tree pattern in concrete syntax form. </param>\n    /// <param name=\"patternRuleIndex\"> The parser rule which serves as the root of the\n    /// tree pattern. </param>\n    /// <param name=\"patternTree\"> The tree pattern in <seealso cref=\"ParseTree\"/> form. </param>\n    ParseTreePattern(ParseTreePatternMatcher *matcher, const std::string &pattern, int patternRuleIndex,\n                     ParseTree *patternTree);\n    ParseTreePattern(ParseTreePattern const&) = default;\n    virtual ~ParseTreePattern();\n\n    /// <summary>\n    /// Match a specific parse tree against this tree pattern.\n    /// </summary>\n    /// <param name=\"tree\"> The parse tree to match against this tree pattern. </param>\n    /// <returns> A <seealso cref=\"ParseTreeMatch\"/> object describing the result of the\n    /// match operation. The <seealso cref=\"ParseTreeMatch#succeeded()\"/> method can be\n    /// used to determine whether or not the match was successful. </returns>\n    virtual ParseTreeMatch match(ParseTree *tree);\n\n    /// <summary>\n    /// Determine whether or not a parse tree matches this tree pattern.\n    /// </summary>\n    /// <param name=\"tree\"> The parse tree to match against this tree pattern. </param>\n    /// <returns> {@code true} if {@code tree} is a match for the current tree\n    /// pattern; otherwise, {@code false}. </returns>\n    virtual bool matches(ParseTree *tree);\n\n    /// Find all nodes using XPath and then try to match those subtrees against\n    /// this tree pattern.\n    /// @param tree The ParseTree to match against this pattern.\n    /// @param xpath An expression matching the nodes\n    ///\n    /// @returns A collection of ParseTreeMatch objects describing the\n    /// successful matches. Unsuccessful matches are omitted from the result,\n    /// regardless of the reason for the failure.\n    virtual std::vector<ParseTreeMatch> findAll(ParseTree *tree, const std::string &xpath);\n\n    /// <summary>\n    /// Get the <seealso cref=\"ParseTreePatternMatcher\"/> which created this tree pattern.\n    /// </summary>\n    /// <returns> The <seealso cref=\"ParseTreePatternMatcher\"/> which created this tree\n    /// pattern. </returns>\n    virtual ParseTreePatternMatcher *getMatcher() const;\n\n    /// <summary>\n    /// Get the tree pattern in concrete syntax form.\n    /// </summary>\n    /// <returns> The tree pattern in concrete syntax form. </returns>\n    virtual std::string getPattern() const;\n\n    /// <summary>\n    /// Get the parser rule which serves as the outermost rule for the tree\n    /// pattern.\n    /// </summary>\n    /// <returns> The parser rule which serves as the outermost rule for the tree\n    /// pattern. </returns>\n    virtual int getPatternRuleIndex() const;\n\n    /// <summary>\n    /// Get the tree pattern as a <seealso cref=\"ParseTree\"/>. The rule and token tags from\n    /// the pattern are present in the parse tree as terminal nodes with a symbol\n    /// of type <seealso cref=\"RuleTagToken\"/> or <seealso cref=\"TokenTagToken\"/>.\n    /// </summary>\n    /// <returns> The tree pattern as a <seealso cref=\"ParseTree\"/>. </returns>\n    virtual ParseTree* getPatternTree() const;\n\n  private:\n    const int patternRuleIndex;\n\n    /// This is the backing field for <seealso cref=\"#getPattern()\"/>.\n    const std::string _pattern;\n\n    /// This is the backing field for <seealso cref=\"#getPatternTree()\"/>.\n    ParseTree *_patternTree;\n\n    /// This is the backing field for <seealso cref=\"#getMatcher()\"/>.\n    ParseTreePatternMatcher *const _matcher;\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/ParseTreePatternMatcher.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <cstddef>\n#include \"tree/pattern/ParseTreePattern.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"tree/pattern/ParseTreeMatch.h\"\n#include \"tree/TerminalNode.h\"\n#include \"CommonTokenStream.h\"\n#include \"ParserInterpreter.h\"\n#include \"tree/pattern/TokenTagToken.h\"\n#include \"ParserRuleContext.h\"\n#include \"tree/pattern/RuleTagToken.h\"\n#include \"tree/pattern/TagChunk.h\"\n#include \"atn/ATN.h\"\n#include \"Lexer.h\"\n#include \"BailErrorStrategy.h\"\n\n#include \"ListTokenSource.h\"\n#include \"tree/pattern/TextChunk.h\"\n#include \"ANTLRInputStream.h\"\n#include \"support/Arrays.h\"\n#include \"Exceptions.h\"\n#include \"support/CPPUtils.h\"\n\n#include \"tree/pattern/ParseTreePatternMatcher.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::pattern;\nusing namespace antlrcpp;\n\nParseTreePatternMatcher::CannotInvokeStartRule::CannotInvokeStartRule(const RuntimeException &e) : RuntimeException(e.what()) {\n}\n\nParseTreePatternMatcher::CannotInvokeStartRule::~CannotInvokeStartRule() {\n}\n\nParseTreePatternMatcher::StartRuleDoesNotConsumeFullPattern::~StartRuleDoesNotConsumeFullPattern() {\n}\n\nParseTreePatternMatcher::ParseTreePatternMatcher(Lexer *lexer, Parser *parser) : _lexer(lexer), _parser(parser) {\n  InitializeInstanceFields();\n}\n\nParseTreePatternMatcher::~ParseTreePatternMatcher() {\n}\n\nvoid ParseTreePatternMatcher::setDelimiters(const std::string &start, const std::string &stop, const std::string &escapeLeft) {\n  if (start.empty()) {\n    throw IllegalArgumentException(\"start cannot be null or empty\");\n  }\n\n  if (stop.empty()) {\n    throw IllegalArgumentException(\"stop cannot be null or empty\");\n  }\n\n _start = start;\n  _stop = stop;\n  _escape = escapeLeft;\n}\n\nbool ParseTreePatternMatcher::matches(ParseTree *tree, const std::string &pattern, int patternRuleIndex) {\n  ParseTreePattern p = compile(pattern, patternRuleIndex);\n  return matches(tree, p);\n}\n\nbool ParseTreePatternMatcher::matches(ParseTree *tree, const ParseTreePattern &pattern) {\n  std::map<std::string, std::vector<ParseTree *>> labels;\n  ParseTree *mismatchedNode = matchImpl(tree, pattern.getPatternTree(), labels);\n  return mismatchedNode == nullptr;\n}\n\nParseTreeMatch ParseTreePatternMatcher::match(ParseTree *tree, const std::string &pattern, int patternRuleIndex) {\n  ParseTreePattern p = compile(pattern, patternRuleIndex);\n  return match(tree, p);\n}\n\nParseTreeMatch ParseTreePatternMatcher::match(ParseTree *tree, const ParseTreePattern &pattern) {\n  std::map<std::string, std::vector<ParseTree *>> labels;\n  tree::ParseTree *mismatchedNode = matchImpl(tree, pattern.getPatternTree(), labels);\n  return ParseTreeMatch(tree, pattern, labels, mismatchedNode);\n}\n\nParseTreePattern ParseTreePatternMatcher::compile(const std::string &pattern, int patternRuleIndex) {\n  ListTokenSource tokenSrc(tokenize(pattern));\n  CommonTokenStream tokens(&tokenSrc);\n\n  ParserInterpreter parserInterp(_parser->getGrammarFileName(), _parser->getVocabulary(),\n                                 _parser->getRuleNames(), _parser->getATNWithBypassAlts(), &tokens);\n\n  ParserRuleContext *tree = nullptr;\n  try {\n    parserInterp.setErrorHandler(std::make_shared<BailErrorStrategy>());\n    tree = parserInterp.parse(patternRuleIndex);\n  } catch (ParseCancellationException &e) {\n#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026\n    // rethrow_if_nested is not available before VS 2015.\n    throw e;\n#else\n    std::rethrow_if_nested(e); // Unwrap the nested exception.\n#endif\n  } catch (RecognitionException &re) {\n    throw re;\n#if defined(_MSC_FULL_VER) && _MSC_FULL_VER < 190023026\n  } catch (std::exception &e) {\n    // throw_with_nested is not available before VS 2015.\n    throw e;\n#else\n  } catch (std::exception & /*e*/) {\n    std::throw_with_nested(RuntimeException(\"Cannot invoke start rule\")); // Wrap any other exception.\n#endif\n  }\n\n  // Make sure tree pattern compilation checks for a complete parse\n  if (tokens.LA(1) != Token::EOF) {\n    throw StartRuleDoesNotConsumeFullPattern();\n  }\n\n  return ParseTreePattern(this, pattern, patternRuleIndex, tree);\n}\n\nLexer* ParseTreePatternMatcher::getLexer() {\n  return _lexer;\n}\n\nParser* ParseTreePatternMatcher::getParser() {\n  return _parser;\n}\n\nParseTree* ParseTreePatternMatcher::matchImpl(ParseTree *tree, ParseTree *patternTree,\n                                              std::map<std::string, std::vector<ParseTree *>> &labels) {\n  if (tree == nullptr) {\n    throw IllegalArgumentException(\"tree cannot be nul\");\n  }\n\n  if (patternTree == nullptr) {\n    throw IllegalArgumentException(\"patternTree cannot be nul\");\n  }\n\n  // x and <ID>, x and y, or x and x; or could be mismatched types\n  if (is<TerminalNode *>(tree) && is<TerminalNode *>(patternTree)) {\n    TerminalNode *t1 = dynamic_cast<TerminalNode *>(tree);\n    TerminalNode *t2 = dynamic_cast<TerminalNode *>(patternTree);\n\n    ParseTree *mismatchedNode = nullptr;\n    // both are tokens and they have same type\n    if (t1->getSymbol()->getType() == t2->getSymbol()->getType()) {\n      if (is<TokenTagToken *>(t2->getSymbol())) { // x and <ID>\n        TokenTagToken *tokenTagToken = dynamic_cast<TokenTagToken *>(t2->getSymbol());\n\n        // track label->list-of-nodes for both token name and label (if any)\n        labels[tokenTagToken->getTokenName()].push_back(tree);\n        if (tokenTagToken->getLabel() != \"\") {\n          labels[tokenTagToken->getLabel()].push_back(tree);\n        }\n      } else if (t1->getText() == t2->getText()) {\n        // x and x\n      } else {\n        // x and y\n        if (mismatchedNode == nullptr) {\n          mismatchedNode = t1;\n        }\n      }\n    } else {\n      if (mismatchedNode == nullptr) {\n        mismatchedNode = t1;\n      }\n    }\n\n    return mismatchedNode;\n  }\n\n  if (is<ParserRuleContext *>(tree) && is<ParserRuleContext *>(patternTree)) {\n    ParserRuleContext *r1 = dynamic_cast<ParserRuleContext *>(tree);\n    ParserRuleContext *r2 = dynamic_cast<ParserRuleContext *>(patternTree);\n    ParseTree *mismatchedNode = nullptr;\n\n    // (expr ...) and <expr>\n    RuleTagToken *ruleTagToken = getRuleTagToken(r2);\n    if (ruleTagToken != nullptr) {\n      //ParseTreeMatch *m = nullptr; // unused?\n      if (r1->getRuleIndex() == r2->getRuleIndex()) {\n        // track label->list-of-nodes for both rule name and label (if any)\n        labels[ruleTagToken->getRuleName()].push_back(tree);\n        if (ruleTagToken->getLabel() != \"\") {\n          labels[ruleTagToken->getLabel()].push_back(tree);\n        }\n      } else {\n        if (!mismatchedNode) {\n          mismatchedNode = r1;\n        }\n      }\n\n      return mismatchedNode;\n    }\n\n    // (expr ...) and (expr ...)\n    if (r1->children.size() != r2->children.size()) {\n      if (mismatchedNode == nullptr) {\n        mismatchedNode = r1;\n      }\n\n      return mismatchedNode;\n    }\n\n    std::size_t n = r1->children.size();\n    for (size_t i = 0; i < n; i++) {\n      ParseTree *childMatch = matchImpl(r1->children[i], patternTree->children[i], labels);\n      if (childMatch) {\n        return childMatch;\n      }\n    }\n\n    return mismatchedNode;\n  }\n\n  // if nodes aren't both tokens or both rule nodes, can't match\n  return tree;\n}\n\nRuleTagToken* ParseTreePatternMatcher::getRuleTagToken(ParseTree *t) {\n  if (t->children.size() == 1 && is<TerminalNode *>(t->children[0])) {\n    TerminalNode *c = dynamic_cast<TerminalNode *>(t->children[0]);\n    if (is<RuleTagToken *>(c->getSymbol())) {\n      return dynamic_cast<RuleTagToken *>(c->getSymbol());\n    }\n  }\n  return nullptr;\n}\n\nstd::vector<std::unique_ptr<Token>> ParseTreePatternMatcher::tokenize(const std::string &pattern) {\n  // split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)\n  std::vector<Chunk> chunks = split(pattern);\n\n  // create token stream from text and tags\n  std::vector<std::unique_ptr<Token>> tokens;\n  for (auto chunk : chunks) {\n    if (is<TagChunk *>(&chunk)) {\n      TagChunk &tagChunk = (TagChunk&)chunk;\n      // add special rule token or conjure up new token from name\n      if (isupper(tagChunk.getTag()[0])) {\n        size_t ttype = _parser->getTokenType(tagChunk.getTag());\n        if (ttype == Token::INVALID_TYPE) {\n          throw IllegalArgumentException(\"Unknown token \" + tagChunk.getTag() + \" in pattern: \" + pattern);\n        }\n        tokens.emplace_back(new TokenTagToken(tagChunk.getTag(), (int)ttype, tagChunk.getLabel()));\n      } else if (islower(tagChunk.getTag()[0])) {\n        size_t ruleIndex = _parser->getRuleIndex(tagChunk.getTag());\n        if (ruleIndex == INVALID_INDEX) {\n          throw IllegalArgumentException(\"Unknown rule \" + tagChunk.getTag() + \" in pattern: \" + pattern);\n        }\n        size_t ruleImaginaryTokenType = _parser->getATNWithBypassAlts().ruleToTokenType[ruleIndex];\n        tokens.emplace_back(new RuleTagToken(tagChunk.getTag(), ruleImaginaryTokenType, tagChunk.getLabel()));\n      } else {\n        throw IllegalArgumentException(\"invalid tag: \" + tagChunk.getTag() + \" in pattern: \" + pattern);\n      }\n    } else {\n      TextChunk &textChunk = (TextChunk&)chunk;\n      ANTLRInputStream input(textChunk.getText());\n      _lexer->setInputStream(&input);\n      std::unique_ptr<Token> t(_lexer->nextToken());\n      while (t->getType() != Token::EOF) {\n        tokens.push_back(std::move(t));\n        t = _lexer->nextToken();\n      }\n      _lexer->setInputStream(nullptr);\n    }\n  }\n\n  return tokens;\n}\n\nstd::vector<Chunk> ParseTreePatternMatcher::split(const std::string &pattern) {\n  size_t p = 0;\n  size_t n = pattern.length();\n  std::vector<Chunk> chunks;\n\n  // find all start and stop indexes first, then collect\n  std::vector<size_t> starts;\n  std::vector<size_t> stops;\n  while (p < n) {\n    if (p == pattern.find(_escape + _start,p)) {\n      p += _escape.length() + _start.length();\n    } else if (p == pattern.find(_escape + _stop,p)) {\n      p += _escape.length() + _stop.length();\n    } else if (p == pattern.find(_start,p)) {\n      starts.push_back(p);\n      p += _start.length();\n    } else if (p == pattern.find(_stop,p)) {\n      stops.push_back(p);\n      p += _stop.length();\n    } else {\n      p++;\n    }\n  }\n\n  if (starts.size() > stops.size()) {\n    throw IllegalArgumentException(\"unterminated tag in pattern: \" + pattern);\n  }\n\n  if (starts.size() < stops.size()) {\n    throw IllegalArgumentException(\"missing start tag in pattern: \" + pattern);\n  }\n\n  size_t ntags = starts.size();\n  for (size_t i = 0; i < ntags; i++) {\n    if (starts[i] >= stops[i]) {\n      throw IllegalArgumentException(\"tag delimiters out of order in pattern: \" + pattern);\n    }\n  }\n\n  // collect into chunks now\n  if (ntags == 0) {\n    std::string text = pattern.substr(0, n);\n    chunks.push_back(TextChunk(text));\n  }\n\n  if (ntags > 0 && starts[0] > 0) { // copy text up to first tag into chunks\n    std::string text = pattern.substr(0, starts[0]);\n    chunks.push_back(TextChunk(text));\n  }\n\n  for (size_t i = 0; i < ntags; i++) {\n    // copy inside of <tag>\n    std::string tag = pattern.substr(starts[i] + _start.length(), stops[i] - (starts[i] + _start.length()));\n    std::string ruleOrToken = tag;\n    std::string label = \"\";\n    size_t colon = tag.find(':');\n    if (colon != std::string::npos) {\n      label = tag.substr(0,colon);\n      ruleOrToken = tag.substr(colon + 1, tag.length() - (colon + 1));\n    }\n    chunks.push_back(TagChunk(label, ruleOrToken));\n    if (i + 1 < ntags) {\n      // copy from end of <tag> to start of next\n      std::string text = pattern.substr(stops[i] + _stop.length(), starts[i + 1] - (stops[i] + _stop.length()));\n      chunks.push_back(TextChunk(text));\n    }\n  }\n\n  if (ntags > 0) {\n    size_t afterLastTag = stops[ntags - 1] + _stop.length();\n    if (afterLastTag < n) { // copy text from end of last tag to end\n      std::string text = pattern.substr(afterLastTag, n - afterLastTag);\n      chunks.push_back(TextChunk(text));\n    }\n  }\n\n  // strip out all backslashes from text chunks but not tags\n  for (size_t i = 0; i < chunks.size(); i++) {\n    Chunk &c = chunks[i];\n    if (is<TextChunk *>(&c)) {\n      TextChunk &tc = (TextChunk&)c;\n      std::string unescaped = tc.getText();\n      unescaped.erase(std::remove(unescaped.begin(), unescaped.end(), '\\\\'), unescaped.end());\n      if (unescaped.length() < tc.getText().length()) {\n        chunks[i] = TextChunk(unescaped);\n      }\n    }\n  }\n\n  return chunks;\n}\n\nvoid ParseTreePatternMatcher::InitializeInstanceFields() {\n  _start = \"<\";\n  _stop = \">\";\n  _escape = \"\\\\\";\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/ParseTreePatternMatcher.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <map>\n#include <memory>\n#include <vector>\n#include <string>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"Exceptions.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// <summary>\n  /// A tree pattern matching mechanism for ANTLR <seealso cref=\"ParseTree\"/>s.\n  /// <p/>\n  /// Patterns are strings of source input text with special tags representing\n  /// token or rule references such as:\n  /// <p/>\n  /// {@code <ID> = <expr>;}\n  /// <p/>\n  /// Given a pattern start rule such as {@code statement}, this object constructs\n  /// a <seealso cref=\"ParseTree\"/> with placeholders for the {@code ID} and {@code expr}\n  /// subtree. Then the <seealso cref=\"#match\"/> routines can compare an actual\n  /// <seealso cref=\"ParseTree\"/> from a parse with this pattern. Tag {@code <ID>} matches\n  /// any {@code ID} token and tag {@code <expr>} references the result of the\n  /// {@code expr} rule (generally an instance of {@code ExprContext}.\n  /// <p/>\n  /// Pattern {@code x = 0;} is a similar pattern that matches the same pattern\n  /// except that it requires the identifier to be {@code x} and the expression to\n  /// be {@code 0}.\n  /// <p/>\n  /// The <seealso cref=\"#matches\"/> routines return {@code true} or {@code false} based\n  /// upon a match for the tree rooted at the parameter sent in. The\n  /// <seealso cref=\"#match\"/> routines return a <seealso cref=\"ParseTreeMatch\"/> object that\n  /// contains the parse tree, the parse tree pattern, and a map from tag name to\n  /// matched nodes (more below). A subtree that fails to match, returns with\n  /// <seealso cref=\"ParseTreeMatch#mismatchedNode\"/> set to the first tree node that did not\n  /// match.\n  /// <p/>\n  /// For efficiency, you can compile a tree pattern in string form to a\n  /// <seealso cref=\"ParseTreePattern\"/> object.\n  /// <p/>\n  /// See {@code TestParseTreeMatcher} for lots of examples.\n  /// <seealso cref=\"ParseTreePattern\"/> has two static helper methods:\n  /// <seealso cref=\"ParseTreePattern#findAll\"/> and <seealso cref=\"ParseTreePattern#match\"/> that\n  /// are easy to use but not super efficient because they create new\n  /// <seealso cref=\"ParseTreePatternMatcher\"/> objects each time and have to compile the\n  /// pattern in string form before using it.\n  /// <p/>\n  /// The lexer and parser that you pass into the <seealso cref=\"ParseTreePatternMatcher\"/>\n  /// constructor are used to parse the pattern in string form. The lexer converts\n  /// the {@code <ID> = <expr>;} into a sequence of four tokens (assuming lexer\n  /// throws out whitespace or puts it on a hidden channel). Be aware that the\n  /// input stream is reset for the lexer (but not the parser; a\n  /// <seealso cref=\"ParserInterpreter\"/> is created to parse the input.). Any user-defined\n  /// fields you have put into the lexer might get changed when this mechanism asks\n  /// it to scan the pattern string.\n  /// <p/>\n  /// Normally a parser does not accept token {@code <expr>} as a valid\n  /// {@code expr} but, from the parser passed in, we create a special version of\n  /// the underlying grammar representation (an <seealso cref=\"ATN\"/>) that allows imaginary\n  /// tokens representing rules ({@code <expr>}) to match entire rules. We call\n  /// these <em>bypass alternatives</em>.\n  /// <p/>\n  /// Delimiters are {@code <} and {@code >}, with {@code \\} as the escape string\n  /// by default, but you can set them to whatever you want using\n  /// <seealso cref=\"#setDelimiters\"/>. You must escape both start and stop strings\n  /// {@code \\<} and {@code \\>}.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC ParseTreePatternMatcher {\n  public:\n    class CannotInvokeStartRule : public RuntimeException {\n    public:\n      CannotInvokeStartRule(const RuntimeException &e);\n      ~CannotInvokeStartRule() override;\n    };\n\n    // Fixes https://github.com/antlr/antlr4/issues/413\n    // \"Tree pattern compilation doesn't check for a complete parse\"\n    class StartRuleDoesNotConsumeFullPattern : public RuntimeException {\n    public:\n      StartRuleDoesNotConsumeFullPattern() = default;\n      StartRuleDoesNotConsumeFullPattern(StartRuleDoesNotConsumeFullPattern const&) = default;\n      ~StartRuleDoesNotConsumeFullPattern() override;\n\n      StartRuleDoesNotConsumeFullPattern& operator=(StartRuleDoesNotConsumeFullPattern const&) = default;\n    };\n\n    /// Constructs a <seealso cref=\"ParseTreePatternMatcher\"/> or from a <seealso cref=\"Lexer\"/> and\n    /// <seealso cref=\"Parser\"/> object. The lexer input stream is altered for tokenizing\n    /// the tree patterns. The parser is used as a convenient mechanism to get\n    /// the grammar name, plus token, rule names.\n    ParseTreePatternMatcher(Lexer *lexer, Parser *parser);\n    virtual ~ParseTreePatternMatcher();\n\n    /// <summary>\n    /// Set the delimiters used for marking rule and token tags within concrete\n    /// syntax used by the tree pattern parser.\n    /// </summary>\n    /// <param name=\"start\"> The start delimiter. </param>\n    /// <param name=\"stop\"> The stop delimiter. </param>\n    /// <param name=\"escapeLeft\"> The escape sequence to use for escaping a start or stop delimiter.\n    /// </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code start} is {@code null} or empty. </exception>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code stop} is {@code null} or empty. </exception>\n    virtual void setDelimiters(const std::string &start, const std::string &stop, const std::string &escapeLeft);\n\n    /// <summary>\n    /// Does {@code pattern} matched as rule {@code patternRuleIndex} match {@code tree}? </summary>\n    virtual bool matches(ParseTree *tree, const std::string &pattern, int patternRuleIndex);\n\n    /// <summary>\n    /// Does {@code pattern} matched as rule patternRuleIndex match tree? Pass in a\n    ///  compiled pattern instead of a string representation of a tree pattern.\n    /// </summary>\n    virtual bool matches(ParseTree *tree, const ParseTreePattern &pattern);\n\n    /// <summary>\n    /// Compare {@code pattern} matched as rule {@code patternRuleIndex} against\n    /// {@code tree} and return a <seealso cref=\"ParseTreeMatch\"/> object that contains the\n    /// matched elements, or the node at which the match failed.\n    /// </summary>\n    virtual ParseTreeMatch match(ParseTree *tree, const std::string &pattern, int patternRuleIndex);\n\n    /// <summary>\n    /// Compare {@code pattern} matched against {@code tree} and return a\n    /// <seealso cref=\"ParseTreeMatch\"/> object that contains the matched elements, or the\n    /// node at which the match failed. Pass in a compiled pattern instead of a\n    /// string representation of a tree pattern.\n    /// </summary>\n    virtual ParseTreeMatch match(ParseTree *tree, const ParseTreePattern &pattern);\n\n    /// <summary>\n    /// For repeated use of a tree pattern, compile it to a\n    /// <seealso cref=\"ParseTreePattern\"/> using this method.\n    /// </summary>\n    virtual ParseTreePattern compile(const std::string &pattern, int patternRuleIndex);\n\n    /// <summary>\n    /// Used to convert the tree pattern string into a series of tokens. The\n    /// input stream is reset.\n    /// </summary>\n    virtual Lexer* getLexer();\n\n    /// <summary>\n    /// Used to collect to the grammar file name, token names, rule names for\n    /// used to parse the pattern into a parse tree.\n    /// </summary>\n    virtual Parser* getParser();\n\n    // ---- SUPPORT CODE ----\n\n    virtual std::vector<std::unique_ptr<Token>> tokenize(const std::string &pattern);\n\n    /// Split \"<ID> = <e:expr>;\" into 4 chunks for tokenizing by tokenize().\n    virtual std::vector<Chunk> split(const std::string &pattern);\n\n  protected:\n    std::string _start;\n    std::string _stop;\n    std::string _escape; // e.g., \\< and \\> must escape BOTH!\n\n    /// Recursively walk {@code tree} against {@code patternTree}, filling\n    /// {@code match.}<seealso cref=\"ParseTreeMatch#labels labels\"/>.\n    ///\n    /// <returns> the first node encountered in {@code tree} which does not match\n    /// a corresponding node in {@code patternTree}, or {@code null} if the match\n    /// was successful. The specific node returned depends on the matching\n    /// algorithm used by the implementation, and may be overridden. </returns>\n    virtual ParseTree* matchImpl(ParseTree *tree, ParseTree *patternTree, std::map<std::string, std::vector<ParseTree *>> &labels);\n\n    /// Is t <expr> subtree?\n    virtual RuleTagToken* getRuleTagToken(ParseTree *t);\n\n  private:\n    Lexer *_lexer;\n    Parser *_parser;\n\n    void InitializeInstanceFields();\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/RuleTagToken.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include <cstddef>\n#include \"Exceptions.h\"\n\n#include \"antlr4-common.h\"\n#include \"tree/pattern/RuleTagToken.h\"\n\nusing namespace antlr4::tree::pattern;\n\nRuleTagToken::RuleTagToken(const std::string &/*ruleName*/, int _bypassTokenType) : bypassTokenType(_bypassTokenType) {\n}\n\nRuleTagToken::RuleTagToken(const std::string &ruleName, size_t bypassTokenType, const std::string &label)\n  : ruleName(ruleName), bypassTokenType(bypassTokenType), label(label) {\n  if (ruleName.empty()) {\n    throw IllegalArgumentException(\"ruleName cannot be null or empty.\");\n  }\n\n}\n\nstd::string RuleTagToken::getRuleName() const {\n  return ruleName;\n}\n\nstd::string RuleTagToken::getLabel() const {\n  return label;\n}\n\nsize_t RuleTagToken::getChannel() const {\n  return DEFAULT_CHANNEL;\n}\n\nstd::string RuleTagToken::getText() const {\n  if (label != \"\") {\n    return std::string(\"<\") + label + std::string(\":\") + ruleName + std::string(\">\");\n  }\n\n  return std::string(\"<\") + ruleName + std::string(\">\");\n}\n\nsize_t RuleTagToken::getType() const {\n  return bypassTokenType;\n}\n\nsize_t RuleTagToken::getLine() const {\n  return 0;\n}\n\nsize_t RuleTagToken::getCharPositionInLine() const {\n  return INVALID_INDEX;\n}\n\nsize_t RuleTagToken::getTokenIndex() const {\n  return INVALID_INDEX;\n}\n\nsize_t RuleTagToken::getStartIndex() const {\n  return INVALID_INDEX;\n}\n\nsize_t RuleTagToken::getStopIndex() const {\n  return INVALID_INDEX;\n}\n\nantlr4::TokenSource *RuleTagToken::getTokenSource() const {\n  return nullptr;\n}\n\nantlr4::CharStream *RuleTagToken::getInputStream() const {\n  return nullptr;\n}\n\nstd::string RuleTagToken::toString() const {\n  return ruleName + \":\" + std::to_string(bypassTokenType);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/RuleTagToken.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// <summary>\n  /// A <seealso cref=\"Token\"/> object representing an entire subtree matched by a parser\n  /// rule; e.g., {@code <expr>}. These tokens are created for <seealso cref=\"TagChunk\"/>\n  /// chunks where the tag corresponds to a parser rule.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC RuleTagToken : public Token {\n    /// <summary>\n    /// This is the backing field for <seealso cref=\"#getRuleName\"/>.\n    /// </summary>\n  private:\n    const std::string ruleName;\n\n    /// The token type for the current token. This is the token type assigned to\n    /// the bypass alternative for the rule during ATN deserialization.\n    const size_t bypassTokenType;\n\n    /// This is the backing field for <seealso cref=\"#getLabe\"/>.\n    const std::string label;\n\n  public:\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"RuleTagToken\"/> with the specified rule\n    /// name and bypass token type and no label.\n    /// </summary>\n    /// <param name=\"ruleName\"> The name of the parser rule this rule tag matches. </param>\n    /// <param name=\"bypassTokenType\"> The bypass token type assigned to the parser rule.\n    /// </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code ruleName} is {@code null}\n    /// or empty. </exception>\n    RuleTagToken(const std::string &ruleName, int bypassTokenType); //this(ruleName, bypassTokenType, nullptr);\n\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"RuleTagToken\"/> with the specified rule\n    /// name, bypass token type, and label.\n    /// </summary>\n    /// <param name=\"ruleName\"> The name of the parser rule this rule tag matches. </param>\n    /// <param name=\"bypassTokenType\"> The bypass token type assigned to the parser rule. </param>\n    /// <param name=\"label\"> The label associated with the rule tag, or {@code null} if\n    /// the rule tag is unlabeled.\n    /// </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code ruleName} is {@code null}\n    /// or empty. </exception>\n    RuleTagToken(const std::string &ruleName, size_t bypassTokenType, const std::string &label);\n\n    /// <summary>\n    /// Gets the name of the rule associated with this rule tag.\n    /// </summary>\n    /// <returns> The name of the parser rule associated with this rule tag. </returns>\n    std::string getRuleName() const;\n\n    /// <summary>\n    /// Gets the label associated with the rule tag.\n    /// </summary>\n    /// <returns> The name of the label associated with the rule tag, or\n    /// {@code null} if this is an unlabeled rule tag. </returns>\n    std::string getLabel() const;\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// Rule tag tokens are always placed on the <seealso cref=\"#DEFAULT_CHANNE\"/>.\n    /// </summary>\n    size_t getChannel() const override;\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// This method returns the rule tag formatted with {@code <} and {@code >}\n    /// delimiters.\n    /// </summary>\n    std::string getText() const override;\n\n    /// Rule tag tokens have types assigned according to the rule bypass\n    /// transitions created during ATN deserialization.\n    size_t getType() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> always returns 0.\n    size_t getLine() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> always returns INVALID_INDEX.\n    size_t getCharPositionInLine() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> always returns INVALID_INDEX.\n    size_t getTokenIndex() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> always returns INVALID_INDEX.\n    size_t getStartIndex() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> always returns INVALID_INDEX.\n    size_t getStopIndex() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> always returns {@code null}.\n    TokenSource *getTokenSource() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> always returns {@code null}.\n    CharStream *getInputStream() const override;\n\n    /// The implementation for <seealso cref=\"RuleTagToken\"/> returns a string of the form {@code ruleName:bypassTokenType}.\n    std::string toString() const override;\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/TagChunk.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include \"Exceptions.h\"\n\n#include \"tree/pattern/TagChunk.h\"\n\nusing namespace antlr4::tree::pattern;\n\nTagChunk::TagChunk(const std::string &tag) : TagChunk(\"\", tag) {\n}\n\nTagChunk::TagChunk(const std::string &label, const std::string &tag) : _tag(tag), _label(label) {\n  if (tag.empty()) {\n    throw IllegalArgumentException(\"tag cannot be null or empty\");\n  }\n\n}\n\nTagChunk::~TagChunk() {\n}\n\nstd::string TagChunk::getTag() {\n  return _tag;\n}\n\nstd::string TagChunk::getLabel() {\n  return _label;\n}\n\nstd::string TagChunk::toString() {\n  if (!_label.empty()) {\n    return _label + \":\" + _tag;\n  }\n\n  return _tag;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/TagChunk.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"antlr4-common.h\"\n#include \"Chunk.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// <summary>\n  /// Represents a placeholder tag in a tree pattern. A tag can have any of the\n  /// following forms.\n  ///\n  /// <ul>\n  /// <li>{@code expr}: An unlabeled placeholder for a parser rule {@code expr}.</li>\n  /// <li>{@code ID}: An unlabeled placeholder for a token of type {@code ID}.</li>\n  /// <li>{@code e:expr}: A labeled placeholder for a parser rule {@code expr}.</li>\n  /// <li>{@code id:ID}: A labeled placeholder for a token of type {@code ID}.</li>\n  /// </ul>\n  ///\n  /// This class does not perform any validation on the tag or label names aside\n  /// from ensuring that the tag is a non-null, non-empty string.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC TagChunk : public Chunk {\n  public:\n    /// <summary>\n    /// Construct a new instance of <seealso cref=\"TagChunk\"/> using the specified tag and\n    /// no label.\n    /// </summary>\n    /// <param name=\"tag\"> The tag, which should be the name of a parser rule or token\n    /// type.\n    /// </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code tag} is {@code null} or\n    /// empty. </exception>\n    TagChunk(const std::string &tag);\n    ~TagChunk() override;\n\n    /// <summary>\n    /// Construct a new instance of <seealso cref=\"TagChunk\"/> using the specified label\n    /// and tag.\n    /// </summary>\n    /// <param name=\"label\"> The label for the tag. If this is {@code null}, the\n    /// <seealso cref=\"TagChunk\"/> represents an unlabeled tag. </param>\n    /// <param name=\"tag\"> The tag, which should be the name of a parser rule or token\n    /// type.\n    /// </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code tag} is {@code null} or\n    /// empty. </exception>\n    TagChunk(const std::string &label, const std::string &tag);\n\n    /// <summary>\n    /// Get the tag for this chunk.\n    /// </summary>\n    /// <returns> The tag for the chunk. </returns>\n    std::string getTag();\n\n    /// <summary>\n    /// Get the label, if any, assigned to this chunk.\n    /// </summary>\n    /// <returns> The label assigned to this chunk, or {@code null} if no label is\n    /// assigned to the chunk. </returns>\n    std::string getLabel();\n\n    /// <summary>\n    /// This method returns a text representation of the tag chunk. Labeled tags\n    /// are returned in the form {@code label:tag}, and unlabeled tags are\n    /// returned as just the tag name.\n    /// </summary>\n    std::string toString() override;\n\n  private:\n    /// This is the backing field for <seealso cref=\"#getTag\"/>.\n    const std::string _tag;\n    /// <summary>\n    /// This is the backing field for <seealso cref=\"#getLabe\"/>.\n    /// </summary>\n    const std::string _label;\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/TextChunk.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include \"Exceptions.h\"\n\n#include \"tree/pattern/TextChunk.h\"\n\nusing namespace antlr4::tree::pattern;\n\nTextChunk::TextChunk(const std::string &text) : text(text) {\n  if (text == \"\") {\n    throw IllegalArgumentException(\"text cannot be nul\");\n  }\n\n}\n\nTextChunk::~TextChunk() {\n}\n\nstd::string TextChunk::getText() {\n  return text;\n}\n\nstd::string TextChunk::toString() {\n  return std::string(\"'\") + text + std::string(\"'\");\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/TextChunk.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"antlr4-common.h\"\n#include \"Chunk.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// <summary>\n  /// Represents a span of raw text (concrete syntax) between tags in a tree\n  /// pattern string.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC TextChunk : public Chunk {\n  private:\n    /// <summary>\n    /// This is the backing field for <seealso cref=\"#getText\"/>.\n    /// </summary>\n    const std::string text;\n\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"TextChunk\"/> with the specified text.\n    /// </summary>\n    /// <param name=\"text\"> The text of this chunk. </param>\n    /// <exception cref=\"IllegalArgumentException\"> if {@code text} is {@code null}. </exception>\n  public:\n    TextChunk(const std::string &text);\n    ~TextChunk() override;\n\n    /// <summary>\n    /// Gets the raw text of this chunk.\n    /// </summary>\n    /// <returns> The text of the chunk. </returns>\n    std::string getText();\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// The implementation for <seealso cref=\"TextChunk\"/> returns the result of\n    /// <seealso cref=\"#getText()\"/> in single quotes.\n    /// </summary>\n    std::string toString() override;\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/TokenTagToken.cpp",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <string>\n#include \"tree/pattern/TokenTagToken.h\"\n\nusing namespace antlr4::tree::pattern;\n\nTokenTagToken::TokenTagToken(const std::string &/*tokenName*/, int type)\n  : CommonToken(type), tokenName(\"\"), label(\"\") {\n}\n\nTokenTagToken::TokenTagToken(const std::string &tokenName, int type, const std::string &label)\n  : CommonToken(type), tokenName(tokenName), label(label) {\n}\n\nstd::string TokenTagToken::getTokenName() const {\n  return tokenName;\n}\n\nstd::string TokenTagToken::getLabel() const {\n  return label;\n}\n\nstd::string TokenTagToken::getText() const {\n  if (!label.empty()) {\n    return \"<\" + label + \":\" + tokenName + \">\";\n  }\n\n  return \"<\" + tokenName + \">\";\n}\n\nstd::string TokenTagToken::toString() const {\n  return tokenName + \":\" + std::to_string(_type);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/pattern/TokenTagToken.h",
    "content": "﻿/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <string>\n#include \"antlr4-common.h\"\n#include \"CommonToken.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace pattern {\n\n  /// <summary>\n  /// A <seealso cref=\"Token\"/> object representing a token of a particular type; e.g.,\n  /// {@code <ID>}. These tokens are created for <seealso cref=\"TagChunk\"/> chunks where the\n  /// tag corresponds to a lexer rule or token type.\n  /// </summary>\n  class ANTLR4CPP_PUBLIC TokenTagToken : public CommonToken {\n    /// <summary>\n    /// This is the backing field for <seealso cref=\"#getTokenName\"/>.\n    /// </summary>\n  private:\n    const std::string tokenName;\n    /// <summary>\n    /// This is the backing field for <seealso cref=\"#getLabe\"/>.\n    /// </summary>\n    const std::string label;\n\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"TokenTagToken\"/> for an unlabeled tag\n    /// with the specified token name and type.\n    /// </summary>\n    /// <param name=\"tokenName\"> The token name. </param>\n    /// <param name=\"type\"> The token type. </param>\n  public:\n    TokenTagToken(const std::string &tokenName, int type); //this(tokenName, type, nullptr);\n\n    /// <summary>\n    /// Constructs a new instance of <seealso cref=\"TokenTagToken\"/> with the specified\n    /// token name, type, and label.\n    /// </summary>\n    /// <param name=\"tokenName\"> The token name. </param>\n    /// <param name=\"type\"> The token type. </param>\n    /// <param name=\"label\"> The label associated with the token tag, or {@code null} if\n    /// the token tag is unlabeled. </param>\n    TokenTagToken(const std::string &tokenName, int type, const std::string &label);\n\n    /// <summary>\n    /// Gets the token name. </summary>\n    /// <returns> The token name. </returns>\n    std::string getTokenName() const;\n\n    /// <summary>\n    /// Gets the label associated with the rule tag.\n    /// </summary>\n    /// <returns> The name of the label associated with the rule tag, or\n    /// {@code null} if this is an unlabeled rule tag. </returns>\n    std::string getLabel() const;\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// The implementation for <seealso cref=\"TokenTagToken\"/> returns the token tag\n    /// formatted with {@code <} and {@code >} delimiters.\n    /// </summary>\n    std::string getText() const override;\n\n    /// <summary>\n    /// {@inheritDoc}\n    /// <p/>\n    /// The implementation for <seealso cref=\"TokenTagToken\"/> returns a string of the form\n    /// {@code tokenName:type}.\n    /// </summary>\n    std::string toString() const override;\n  };\n\n} // namespace pattern\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPath.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <memory>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"XPathLexer.h\"\n#include \"ANTLRInputStream.h\"\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n#include \"XPathLexerErrorListener.h\"\n#include \"XPathElement.h\"\n#include \"XPathWildcardAnywhereElement.h\"\n#include \"XPathWildcardElement.h\"\n#include \"XPathTokenAnywhereElement.h\"\n#include \"XPathTokenElement.h\"\n#include \"XPathRuleAnywhereElement.h\"\n#include \"XPathRuleElement.h\"\n\n#include \"XPath.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nconst std::string XPath::WILDCARD = \"*\";\nconst std::string XPath::NOT = \"!\";\n\nXPath::XPath(Parser *parser, const std::string &path) {\n  _parser = parser;\n  _path = path;\n}\n\nstd::vector<std::unique_ptr<XPathElement>> XPath::split(const std::string &path) {\n  ANTLRInputStream in(path);\n  XPathLexer lexer(&in);\n  lexer.removeErrorListeners();\n  XPathLexerErrorListener listener;\n  lexer.addErrorListener(&listener);\n  CommonTokenStream tokenStream(&lexer);\n  try {\n    tokenStream.fill();\n  } catch (LexerNoViableAltException &) {\n    size_t pos = lexer.getCharPositionInLine();\n    std::string msg = \"Invalid tokens or characters at index \" + std::to_string(pos) + \" in path '\" + path + \"'\";\n    throw IllegalArgumentException(msg);\n  }\n\n  std::vector<Token *> tokens = tokenStream.getTokens();\n  std::vector<std::unique_ptr<XPathElement>> elements;\n  size_t n = tokens.size();\n  size_t i = 0;\n  bool done = false;\n  while (!done && i < n) {\n    Token *el = tokens[i];\n    Token *next = nullptr;\n    switch (el->getType()) {\n      case XPathLexer::ROOT:\n      case XPathLexer::ANYWHERE: {\n        bool anywhere = el->getType() == XPathLexer::ANYWHERE;\n        i++;\n        next = tokens[i];\n        bool invert = next->getType() == XPathLexer::BANG;\n        if (invert) {\n          i++;\n          next = tokens[i];\n        }\n        std::unique_ptr<XPathElement> pathElement = getXPathElement(next, anywhere);\n        pathElement->setInvert(invert);\n        elements.push_back(std::move(pathElement));\n        i++;\n        break;\n\n      }\n      case XPathLexer::TOKEN_REF:\n      case XPathLexer::RULE_REF:\n      case XPathLexer::WILDCARD:\n        elements.push_back(getXPathElement(el, false));\n        i++;\n        break;\n\n      case Token::EOF:\n        done = true;\n        break;\n\n      default :\n        throw IllegalArgumentException(\"Unknown path element \" + el->toString());\n    }\n  }\n\n  return elements;\n}\n\nstd::unique_ptr<XPathElement> XPath::getXPathElement(Token *wordToken, bool anywhere) {\n  if (wordToken->getType() == Token::EOF) {\n    throw IllegalArgumentException(\"Missing path element at end of path\");\n  }\n\n  std::string word = wordToken->getText();\n  size_t ttype = _parser->getTokenType(word);\n  ssize_t ruleIndex = _parser->getRuleIndex(word);\n  switch (wordToken->getType()) {\n    case XPathLexer::WILDCARD :\n      if (anywhere)\n        return std::unique_ptr<XPathWildcardAnywhereElement>(new XPathWildcardAnywhereElement());\n      return std::unique_ptr<XPathWildcardElement>(new XPathWildcardElement());\n\n    case XPathLexer::TOKEN_REF:\n    case XPathLexer::STRING :\n      if (ttype == Token::INVALID_TYPE) {\n        throw IllegalArgumentException(word + \" at index \" + std::to_string(wordToken->getStartIndex()) + \" isn't a valid token name\");\n      }\n      if (anywhere)\n        return std::unique_ptr<XPathTokenAnywhereElement>(new XPathTokenAnywhereElement(word, (int)ttype));\n      return std::unique_ptr<XPathTokenElement>(new XPathTokenElement(word, (int)ttype));\n\n    default :\n      if (ruleIndex == -1) {\n        throw IllegalArgumentException(word + \" at index \" + std::to_string(wordToken->getStartIndex()) + \" isn't a valid rule name\");\n      }\n      if (anywhere)\n        return std::unique_ptr<XPathRuleAnywhereElement>(new XPathRuleAnywhereElement(word, (int)ruleIndex));\n      return std::unique_ptr<XPathRuleElement>(new XPathRuleElement(word, (int)ruleIndex));\n  }\n}\n\nstatic ParserRuleContext dummyRoot;\n\nstd::vector<ParseTree *> XPath::findAll(ParseTree *tree, std::string const& xpath, Parser *parser) {\n  XPath p(parser, xpath);\n  return p.evaluate(tree);\n}\n\nstd::vector<ParseTree *> XPath::evaluate(ParseTree *t) {\n  dummyRoot.children = { t }; // don't set t's parent.\n\n  std::vector<ParseTree *> work = { &dummyRoot };\n\n  size_t i = 0;\n  std::vector<std::unique_ptr<XPathElement>> elements = split(_path);\n\n  while (i < elements.size()) {\n    std::vector<ParseTree *> next;\n    for (auto *node : work) {\n      if (!node->children.empty()) {\n        // only try to match next element if it has children\n        // e.g., //func/*/stat might have a token node for which\n        // we can't go looking for stat nodes.\n        auto matching = elements[i]->evaluate(node);\n        next.insert(next.end(), matching.begin(), matching.end());\n      }\n    }\n    i++;\n    work = next;\n  }\n\n  return work;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPath.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <string>\n#include \"Token.h\"\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  /// Represent a subset of XPath XML path syntax for use in identifying nodes in\n  /// parse trees.\n  ///\n  /// <para>\n  /// Split path into words and separators {@code /} and {@code //} via ANTLR\n  /// itself then walk path elements from left to right. At each separator-word\n  /// pair, find set of nodes. Next stage uses those as work list.</para>\n  ///\n  /// <para>\n  /// The basic interface is\n  /// <seealso cref=\"XPath#findAll ParseTree.findAll\"/>{@code (tree, pathString, parser)}.\n  /// But that is just shorthand for:</para>\n  ///\n  /// <pre>\n  /// <seealso cref=\"XPath\"/> p = new <seealso cref=\"XPath#XPath XPath\"/>(parser, pathString);\n  /// return p.<seealso cref=\"#evaluate evaluate\"/>(tree);\n  /// </pre>\n  ///\n  /// <para>\n  /// See {@code org.antlr.v4.test.TestXPath} for descriptions. In short, this\n  /// allows operators:</para>\n  ///\n  /// <dl>\n  /// <dt>/</dt> <dd>root</dd>\n  /// <dt>//</dt> <dd>anywhere</dd>\n  /// <dt>!</dt> <dd>invert; this must appear directly after root or anywhere\n  /// operator</dd>\n  /// </dl>\n  ///\n  /// <para>\n  /// and path elements:</para>\n  ///\n  /// <dl>\n  /// <dt>ID</dt> <dd>token name</dd>\n  /// <dt>'string'</dt> <dd>any string literal token from the grammar</dd>\n  /// <dt>expr</dt> <dd>rule name</dd>\n  /// <dt>*</dt> <dd>wildcard matching any node</dd>\n  /// </dl>\n  ///\n  /// <para>\n  /// Whitespace is not allowed.</para>\n\n  class ANTLR4CPP_PUBLIC XPath {\n  public:\n    static const std::string WILDCARD; // word not operator/separator\n    static const std::string NOT; // word for invert operator\n\n    XPath(Parser *parser, const std::string &path);\n    virtual ~XPath() {}\n\n    // TODO: check for invalid token/rule names, bad syntax\n    virtual std::vector<std::unique_ptr<XPathElement>> split(const std::string &path);\n\n    static std::vector<ParseTree *> findAll(ParseTree *tree, std::string const& xpath, Parser *parser);\n\n    /// Return a list of all nodes starting at {@code t} as root that satisfy the\n    /// path. The root {@code /} is relative to the node passed to\n    /// <seealso cref=\"#evaluate\"/>.\n    virtual std::vector<ParseTree *> evaluate(ParseTree *t);\n\n  protected:\n    std::string _path;\n    Parser *_parser;\n\n    /// Convert word like {@code *} or {@code ID} or {@code expr} to a path\n    /// element. {@code anywhere} is {@code true} if {@code //} precedes the\n    /// word.\n    virtual std::unique_ptr<XPathElement> getXPathElement(Token *wordToken, bool anywhere);\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathElement.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include \"support/CPPUtils.h\"\n\n#include \"XPathElement.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nXPathElement::XPathElement(const std::string &nodeName) {\n  _nodeName = nodeName;\n}\n\nXPathElement::~XPathElement() {\n}\n\nstd::vector<ParseTree *> XPathElement::evaluate(ParseTree * /*t*/) {\n  return {};\n}\n\nstd::string XPathElement::toString() const {\n  std::string inv = _invert ? \"!\" : \"\";\n  return antlrcpp::toString(*this) + \"[\" + inv + _nodeName + \"]\";\n}\n\nvoid XPathElement::setInvert(bool value) {\n  _invert = value;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathElement.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include \"antlr4-common.h\"\n\nnamespace antlr4 {\nnamespace tree {\n  class ParseTree;\n\nnamespace xpath {\n\n  class ANTLR4CPP_PUBLIC XPathElement {\n  public:\n    /// Construct element like {@code /ID} or {@code ID} or {@code /*} etc...\n    ///  op is null if just node\n    XPathElement(const std::string &nodeName);\n    XPathElement(XPathElement const&) = default;\n    virtual ~XPathElement();\n\n    XPathElement& operator=(XPathElement const&) = default;\n\n    /// Given tree rooted at {@code t} return all nodes matched by this path\n    /// element.\n    virtual std::vector<ParseTree *> evaluate(ParseTree *t);\n    virtual std::string toString() const;\n\n    void setInvert(bool value);\n\n  protected:\n    std::string _nodeName;\n    bool _invert = false;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathLexer.cpp",
    "content": "\n// Generated from XPathLexer.g4 by ANTLR 4.13.1\n\n\n#include <cassert>\n#include <memory>\n#include <utility>\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"XPathLexer.h\"\n\n\nusing namespace antlr4;\n\n\n\nusing namespace antlr4;\n\nnamespace {\n\nstruct XPathLexerStaticData final {\n  XPathLexerStaticData(std::vector<std::string> ruleNames,\n                          std::vector<std::string> channelNames,\n                          std::vector<std::string> modeNames,\n                          std::vector<std::string> literalNames,\n                          std::vector<std::string> symbolicNames)\n      : ruleNames(std::move(ruleNames)), channelNames(std::move(channelNames)),\n        modeNames(std::move(modeNames)), literalNames(std::move(literalNames)),\n        symbolicNames(std::move(symbolicNames)),\n        vocabulary(this->literalNames, this->symbolicNames) {}\n\n  XPathLexerStaticData(const XPathLexerStaticData&) = delete;\n  XPathLexerStaticData(XPathLexerStaticData&&) = delete;\n  XPathLexerStaticData& operator=(const XPathLexerStaticData&) = delete;\n  XPathLexerStaticData& operator=(XPathLexerStaticData&&) = delete;\n\n  std::vector<antlr4::dfa::DFA> decisionToDFA;\n  antlr4::atn::PredictionContextCache sharedContextCache;\n  const std::vector<std::string> ruleNames;\n  const std::vector<std::string> channelNames;\n  const std::vector<std::string> modeNames;\n  const std::vector<std::string> literalNames;\n  const std::vector<std::string> symbolicNames;\n  const antlr4::dfa::Vocabulary vocabulary;\n  antlr4::atn::SerializedATNView serializedATN;\n  std::unique_ptr<antlr4::atn::ATN> atn;\n};\n\n::antlr4::internal::OnceFlag xpathlexerLexerOnceFlag;\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\nstatic thread_local\n#endif\nstd::unique_ptr<XPathLexerStaticData> xpathlexerLexerStaticData = nullptr;\n\nvoid xpathlexerLexerInitialize() {\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\n  if (xpathlexerLexerStaticData != nullptr) {\n    return;\n  }\n#else\n  assert(xpathlexerLexerStaticData == nullptr);\n#endif\n  auto staticData = std::make_unique<XPathLexerStaticData>(\n    std::vector<std::string>{\n      \"ANYWHERE\", \"ROOT\", \"WILDCARD\", \"BANG\", \"ID\", \"NameChar\", \"NameStartChar\", \n      \"STRING\"\n    },\n    std::vector<std::string>{\n      \"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"\n    },\n    std::vector<std::string>{\n      \"DEFAULT_MODE\"\n    },\n    std::vector<std::string>{\n      \"\", \"\", \"\", \"'//'\", \"'/'\", \"'*'\", \"'!'\"\n    },\n    std::vector<std::string>{\n      \"\", \"TOKEN_REF\", \"RULE_REF\", \"ANYWHERE\", \"ROOT\", \"WILDCARD\", \"BANG\", \n      \"ID\", \"STRING\"\n    }\n  );\n  static const int32_t serializedATNSegment[] = {\n  \t4,0,8,50,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,\n  \t2,7,7,7,1,0,1,0,1,0,1,1,1,1,1,2,1,2,1,3,1,3,1,4,1,4,5,4,29,8,4,10,4,12,\n  \t4,32,9,4,1,4,1,4,1,5,1,5,3,5,38,8,5,1,6,1,6,1,7,1,7,5,7,44,8,7,10,7,12,\n  \t7,47,9,7,1,7,1,7,1,45,0,8,1,3,3,4,5,5,7,6,9,7,11,0,13,0,15,8,1,0,2,5,\n  \t0,48,57,95,95,183,183,768,879,8255,8256,13,0,65,90,97,122,192,214,216,\n  \t246,248,767,880,893,895,8191,8204,8205,8304,8591,11264,12271,12289,55295,\n  \t63744,64975,65008,65535,50,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,\n  \t0,0,0,0,9,1,0,0,0,0,15,1,0,0,0,1,17,1,0,0,0,3,20,1,0,0,0,5,22,1,0,0,0,\n  \t7,24,1,0,0,0,9,26,1,0,0,0,11,37,1,0,0,0,13,39,1,0,0,0,15,41,1,0,0,0,17,\n  \t18,5,47,0,0,18,19,5,47,0,0,19,2,1,0,0,0,20,21,5,47,0,0,21,4,1,0,0,0,22,\n  \t23,5,42,0,0,23,6,1,0,0,0,24,25,5,33,0,0,25,8,1,0,0,0,26,30,3,13,6,0,27,\n  \t29,3,11,5,0,28,27,1,0,0,0,29,32,1,0,0,0,30,28,1,0,0,0,30,31,1,0,0,0,31,\n  \t33,1,0,0,0,32,30,1,0,0,0,33,34,6,4,0,0,34,10,1,0,0,0,35,38,3,13,6,0,36,\n  \t38,7,0,0,0,37,35,1,0,0,0,37,36,1,0,0,0,38,12,1,0,0,0,39,40,7,1,0,0,40,\n  \t14,1,0,0,0,41,45,5,39,0,0,42,44,9,0,0,0,43,42,1,0,0,0,44,47,1,0,0,0,45,\n  \t46,1,0,0,0,45,43,1,0,0,0,46,48,1,0,0,0,47,45,1,0,0,0,48,49,5,39,0,0,49,\n  \t16,1,0,0,0,4,0,30,37,45,1,1,4,0\n  };\n  staticData->serializedATN = antlr4::atn::SerializedATNView(serializedATNSegment, sizeof(serializedATNSegment) / sizeof(serializedATNSegment[0]));\n\n  antlr4::atn::ATNDeserializer deserializer;\n  staticData->atn = deserializer.deserialize(staticData->serializedATN);\n\n  const size_t count = staticData->atn->getNumberOfDecisions();\n  staticData->decisionToDFA.reserve(count);\n  for (size_t i = 0; i < count; i++) { \n    staticData->decisionToDFA.emplace_back(staticData->atn->getDecisionState(i), i);\n  }\n  xpathlexerLexerStaticData = std::move(staticData);\n}\n\n}\n\nXPathLexer::XPathLexer(CharStream *input) : Lexer(input) {\n  XPathLexer::initialize();\n  _interpreter = new atn::LexerATNSimulator(this, *xpathlexerLexerStaticData->atn, xpathlexerLexerStaticData->decisionToDFA, xpathlexerLexerStaticData->sharedContextCache);\n}\n\nXPathLexer::~XPathLexer() {\n  delete _interpreter;\n}\n\nstd::string XPathLexer::getGrammarFileName() const {\n  return \"XPathLexer.g4\";\n}\n\nconst std::vector<std::string>& XPathLexer::getRuleNames() const {\n  return xpathlexerLexerStaticData->ruleNames;\n}\n\nconst std::vector<std::string>& XPathLexer::getChannelNames() const {\n  return xpathlexerLexerStaticData->channelNames;\n}\n\nconst std::vector<std::string>& XPathLexer::getModeNames() const {\n  return xpathlexerLexerStaticData->modeNames;\n}\n\nconst dfa::Vocabulary& XPathLexer::getVocabulary() const {\n  return xpathlexerLexerStaticData->vocabulary;\n}\n\nantlr4::atn::SerializedATNView XPathLexer::getSerializedATN() const {\n  return xpathlexerLexerStaticData->serializedATN;\n}\n\nconst atn::ATN& XPathLexer::getATN() const {\n  return *xpathlexerLexerStaticData->atn;\n}\n\n\nvoid XPathLexer::action(RuleContext *context, size_t ruleIndex, size_t actionIndex) {\n  switch (ruleIndex) {\n    case 4: IDAction(antlrcpp::downCast<antlr4::RuleContext *>(context), actionIndex); break;\n\n  default:\n    break;\n  }\n}\n\nvoid XPathLexer::IDAction(antlr4::RuleContext *context, size_t actionIndex) {\n  switch (actionIndex) {\n    case 0: \n    \t\t\t\tif (isupper(getText()[0]))\n    \t\t\t\t  setType(TOKEN_REF);\n    \t\t\t\telse\n    \t\t\t\t  setType(RULE_REF);\n    \t\t\t\t break;\n\n  default:\n    break;\n  }\n}\n\n\n\nvoid XPathLexer::initialize() {\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\n  xpathlexerLexerInitialize();\n#else\n  ::antlr4::internal::call_once(xpathlexerLexerOnceFlag, xpathlexerLexerInitialize);\n#endif\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathLexer.g4",
    "content": "lexer grammar XPathLexer;\n\ntokens { TOKEN_REF, RULE_REF }\n\n/*\npath : separator? word (separator word)* EOF ;\n\nseparator\n\t:\t'/'  '!'\n\t|\t'//' '!'\n\t|\t'/'\n\t|\t'//'\n\t;\n\nword:\tTOKEN_REF\n\t|\tRULE_REF\n\t|\tSTRING\n\t|\t'*'\n\t;\n*/\n\nANYWHERE : '//' ;\nROOT\t : '/' ;\nWILDCARD : '*' ;\nBANG\t : '!' ;\n\nID\t\t\t:\tNameStartChar NameChar*\n\t\t\t\t{\n\t\t\t\tif (isupper(getText()[0]))\n\t\t\t\t  setType(TOKEN_REF);\n\t\t\t\telse\n\t\t\t\t  setType(RULE_REF);\n\t\t\t\t}\n\t\t\t;\n\nfragment\nNameChar    :   NameStartChar\n            |   '0'..'9'\n            |   '_'\n            |   '\\u00B7'\n            |   '\\u0300'..'\\u036F'\n            |   '\\u203F'..'\\u2040'\n            ;\n\nfragment\nNameStartChar\n            :   'A'..'Z' | 'a'..'z'\n            |   '\\u00C0'..'\\u00D6'\n            |   '\\u00D8'..'\\u00F6'\n            |   '\\u00F8'..'\\u02FF'\n            |   '\\u0370'..'\\u037D'\n            |   '\\u037F'..'\\u1FFF'\n            |   '\\u200C'..'\\u200D'\n            |   '\\u2070'..'\\u218F'\n            |   '\\u2C00'..'\\u2FEF'\n            |   '\\u3001'..'\\uD7FF'\n            |   '\\uF900'..'\\uFDCF'\n            |   '\\uFDF0'..'\\uFFFF' // implicitly includes ['\\u10000-'\\uEFFFF]\n            ;\n\nSTRING : '\\'' .*? '\\'';\n\n//WS : [ \\t\\r\\n]+ -> skip ;\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathLexer.h",
    "content": "\n// Generated from XPathLexer.g4 by ANTLR 4.13.1\n\n#pragma once\n\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-runtime.h\"\n\n\n\n\nclass  XPathLexer : public antlr4::Lexer {\npublic:\n  enum {\n    TOKEN_REF = 1, RULE_REF = 2, ANYWHERE = 3, ROOT = 4, WILDCARD = 5, BANG = 6, \n    ID = 7, STRING = 8\n  };\n\n  explicit XPathLexer(antlr4::CharStream *input);\n\n  ~XPathLexer() override;\n\n\n  std::string getGrammarFileName() const override;\n\n  const std::vector<std::string>& getRuleNames() const override;\n\n  const std::vector<std::string>& getChannelNames() const override;\n\n  const std::vector<std::string>& getModeNames() const override;\n\n  const antlr4::dfa::Vocabulary& getVocabulary() const override;\n\n  antlr4::atn::SerializedATNView getSerializedATN() const override;\n\n  const antlr4::atn::ATN& getATN() const override;\n\n  void action(antlr4::RuleContext *context, size_t ruleIndex, size_t actionIndex) override;\n\n  // By default the static state used to implement the lexer is lazily initialized during the first\n  // call to the constructor. You can call this function if you wish to initialize the static state\n  // ahead of time.\n  static void initialize();\n\nprivate:\n\n  // Individual action functions triggered by action() above.\n  void IDAction(antlr4::RuleContext *context, size_t actionIndex);\n\n  // Individual semantic predicate functions triggered by sempred() above.\n\n};\n\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathLexer.tokens",
    "content": "TOKEN_REF=1\nRULE_REF=2\nANYWHERE=3\nROOT=4\nWILDCARD=5\nBANG=6\nID=7\nSTRING=8\n'//'=3\n'/'=4\n'*'=5\n'!'=6\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathLexerErrorListener.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"Token.h\"\n#include \"XPathLexerErrorListener.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::tree::xpath;\n\nvoid XPathLexerErrorListener::syntaxError(Recognizer * /*recognizer*/, Token * /*offendingSymbol*/,\n  size_t /*line*/, size_t /*charPositionInLine*/, const std::string &/*msg*/, std::exception_ptr /*e*/) {\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathLexerErrorListener.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <exception>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"Token.h\"\n#include \"BaseErrorListener.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  class ANTLR4CPP_PUBLIC XPathLexerErrorListener : public BaseErrorListener {\n  public:\n    void syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line,\n      size_t charPositionInLine, const std::string &msg, std::exception_ptr e) override;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathRuleAnywhereElement.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include \"tree/ParseTree.h\"\n#include \"tree/Trees.h\"\n\n#include \"tree/xpath/XPathRuleAnywhereElement.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nXPathRuleAnywhereElement::XPathRuleAnywhereElement(const std::string &ruleName, int ruleIndex) : XPathElement(ruleName) {\n  _ruleIndex = ruleIndex;\n}\n\nstd::vector<ParseTree *> XPathRuleAnywhereElement::evaluate(ParseTree *t) {\n  return Trees::findAllRuleNodes(t, _ruleIndex);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathRuleAnywhereElement.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include \"antlr4-common.h\"\n#include \"XPathElement.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  /// Either {@code ID} at start of path or {@code ...//ID} in middle of path.\n  class ANTLR4CPP_PUBLIC XPathRuleAnywhereElement : public XPathElement {\n  public:\n    XPathRuleAnywhereElement(const std::string &ruleName, int ruleIndex);\n\n    std::vector<ParseTree *> evaluate(ParseTree *t) override;\n\n  protected:\n    int _ruleIndex = 0;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathRuleElement.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"tree/ParseTree.h\"\n#include \"tree/Trees.h\"\n\n#include \"XPathRuleElement.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nXPathRuleElement::XPathRuleElement(const std::string &ruleName, size_t ruleIndex) : XPathElement(ruleName) {\n  _ruleIndex = ruleIndex;\n}\n\nstd::vector<ParseTree *> XPathRuleElement::evaluate(ParseTree *t) {\n  // return all children of t that match nodeName\n  std::vector<ParseTree *> nodes;\n  for (auto *c : t->children) {\n    if (antlrcpp::is<ParserRuleContext *>(c)) {\n      ParserRuleContext *ctx = dynamic_cast<ParserRuleContext *>(c);\n      if ((ctx->getRuleIndex() == _ruleIndex && !_invert) || (ctx->getRuleIndex() != _ruleIndex && _invert)) {\n        nodes.push_back(ctx);\n      }\n    }\n  }\n  return nodes;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathRuleElement.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"XPathElement.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  class ANTLR4CPP_PUBLIC XPathRuleElement : public XPathElement {\n  public:\n    XPathRuleElement(const std::string &ruleName, size_t ruleIndex);\n\n    std::vector<ParseTree *> evaluate(ParseTree *t) override;\n\n  protected:\n    size_t _ruleIndex = 0;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathTokenAnywhereElement.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include \"tree/ParseTree.h\"\n#include \"tree/Trees.h\"\n\n#include \"XPathTokenAnywhereElement.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nXPathTokenAnywhereElement::XPathTokenAnywhereElement(const std::string &tokenName, int tokenType) : XPathElement(tokenName) {\n  this->tokenType = tokenType;\n}\n\nstd::vector<ParseTree *> XPathTokenAnywhereElement::evaluate(ParseTree *t) {\n  return Trees::findAllTokenNodes(t, tokenType);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathTokenAnywhereElement.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include \"antlr4-common.h\"\n#include \"XPathElement.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  class ANTLR4CPP_PUBLIC XPathTokenAnywhereElement : public XPathElement {\n  protected:\n    int tokenType = 0;\n  public:\n    XPathTokenAnywhereElement(const std::string &tokenName, int tokenType);\n\n    std::vector<ParseTree *> evaluate(ParseTree *t) override;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathTokenElement.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"tree/ParseTree.h\"\n#include \"tree/Trees.h\"\n#include \"support/CPPUtils.h\"\n#include \"Token.h\"\n\n#include \"XPathTokenElement.h\"\n\nusing namespace antlr4;\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nXPathTokenElement::XPathTokenElement(const std::string &tokenName, size_t tokenType) : XPathElement(tokenName) {\n  _tokenType = tokenType;\n}\n\nstd::vector<ParseTree *> XPathTokenElement::evaluate(ParseTree *t) {\n  // return all children of t that match nodeName\n  std::vector<ParseTree *> nodes;\n  for (auto *c : t->children) {\n    if (antlrcpp::is<TerminalNode *>(c)) {\n      TerminalNode *tnode = dynamic_cast<TerminalNode *>(c);\n      if ((tnode->getSymbol()->getType() == _tokenType && !_invert) || (tnode->getSymbol()->getType() != _tokenType && _invert)) {\n        nodes.push_back(tnode);\n      }\n    }\n  }\n  return nodes;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathTokenElement.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include <string>\n#include <cstddef>\n#include \"antlr4-common.h\"\n#include \"XPathElement.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  class ANTLR4CPP_PUBLIC XPathTokenElement : public XPathElement {\n  public:\n    XPathTokenElement(const std::string &tokenName, size_t tokenType);\n\n    std::vector<ParseTree *> evaluate(ParseTree *t) override;\n\n  protected:\n    size_t _tokenType = 0;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathWildcardAnywhereElement.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include \"XPath.h\"\n#include \"tree/ParseTree.h\"\n#include \"tree/Trees.h\"\n\n#include \"XPathWildcardAnywhereElement.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nXPathWildcardAnywhereElement::XPathWildcardAnywhereElement() : XPathElement(XPath::WILDCARD) {\n}\n\nstd::vector<ParseTree *> XPathWildcardAnywhereElement::evaluate(ParseTree *t) {\n  if (_invert) {\n    return {}; // !* is weird but valid (empty)\n  }\n  return Trees::getDescendants(t);\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathWildcardAnywhereElement.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include \"antlr4-common.h\"\n#include \"XPathElement.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  class ANTLR4CPP_PUBLIC XPathWildcardAnywhereElement : public XPathElement {\n  public:\n    XPathWildcardAnywhereElement();\n\n    std::vector<ParseTree *> evaluate(ParseTree *t) override;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathWildcardElement.cpp",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#include <vector>\n#include \"XPath.h\"\n#include \"tree/ParseTree.h\"\n#include \"tree/Trees.h\"\n\n#include \"XPathWildcardElement.h\"\n\nusing namespace antlr4::tree;\nusing namespace antlr4::tree::xpath;\n\nXPathWildcardElement::XPathWildcardElement() : XPathElement(XPath::WILDCARD) {\n}\n\nstd::vector<ParseTree *> XPathWildcardElement::evaluate(ParseTree *t) {\n  if (_invert) {\n    return {}; // !* is weird but valid (empty)\n  }\n\n  return t->children;\n}\n"
  },
  {
    "path": "runtime/Cpp/runtime/src/tree/xpath/XPathWildcardElement.h",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n#pragma once\n\n#include <vector>\n#include \"antlr4-common.h\"\n#include \"XPathElement.h\"\n\nnamespace antlr4 {\nnamespace tree {\nnamespace xpath {\n\n  class ANTLR4CPP_PUBLIC XPathWildcardElement : public XPathElement {\n  public:\n    XPathWildcardElement();\n\n    std::vector<ParseTree *> evaluate(ParseTree *t) override;\n  };\n\n} // namespace xpath\n} // namespace tree\n} // namespace antlr4\n"
  },
  {
    "path": "runtime/Cpp/runtime/tests/Utf8Test.cpp",
    "content": "#include <string>\n#include <string_view>\n\n#include \"gtest/gtest.h\"\n#include \"support/Utf8.h\"\n\nnamespace antlrcpp {\nnamespace {\n\n  struct Utf8EncodeTestCase final {\n    char32_t code_point;\n    std::string_view code_units;\n  };\n\n  using Utf8EncodeTest = testing::TestWithParam<Utf8EncodeTestCase>;\n\n  TEST_P(Utf8EncodeTest, Compliance) {\n    const Utf8EncodeTestCase& test_case = GetParam();\n    std::string result;\n    EXPECT_EQ(Utf8::encode(&result, test_case.code_point), test_case.code_units);\n  }\n\n  INSTANTIATE_TEST_SUITE_P(Utf8EncodeTest, Utf8EncodeTest,\n                          testing::ValuesIn<Utf8EncodeTestCase>({\n                              {0x0000, std::string_view(\"\\x00\", 1)},\n                              {0x0001, \"\\x01\"},\n                              {0x007e, \"\\x7e\"},\n                              {0x007f, \"\\x7f\"},\n                              {0x0080, \"\\xc2\\x80\"},\n                              {0x0081, \"\\xc2\\x81\"},\n                              {0x00bf, \"\\xc2\\xbf\"},\n                              {0x00c0, \"\\xc3\\x80\"},\n                              {0x00c1, \"\\xc3\\x81\"},\n                              {0x00c8, \"\\xc3\\x88\"},\n                              {0x00d0, \"\\xc3\\x90\"},\n                              {0x00e0, \"\\xc3\\xa0\"},\n                              {0x00f0, \"\\xc3\\xb0\"},\n                              {0x00f8, \"\\xc3\\xb8\"},\n                              {0x00ff, \"\\xc3\\xbf\"},\n                              {0x0100, \"\\xc4\\x80\"},\n                              {0x07ff, \"\\xdf\\xbf\"},\n                              {0x0400, \"\\xd0\\x80\"},\n                              {0x0800, \"\\xe0\\xa0\\x80\"},\n                              {0x0801, \"\\xe0\\xa0\\x81\"},\n                              {0x1000, \"\\xe1\\x80\\x80\"},\n                              {0xd000, \"\\xed\\x80\\x80\"},\n                              {0xd7ff, \"\\xed\\x9f\\xbf\"},\n                              {0xe000, \"\\xee\\x80\\x80\"},\n                              {0xfffe, \"\\xef\\xbf\\xbe\"},\n                              {0xffff, \"\\xef\\xbf\\xbf\"},\n                              {0x10000, \"\\xf0\\x90\\x80\\x80\"},\n                              {0x10001, \"\\xf0\\x90\\x80\\x81\"},\n                              {0x40000, \"\\xf1\\x80\\x80\\x80\"},\n                              {0x10fffe, \"\\xf4\\x8f\\xbf\\xbe\"},\n                              {0x10ffff, \"\\xf4\\x8f\\xbf\\xbf\"},\n                              {0xFFFD, \"\\xef\\xbf\\xbd\"},\n                          }));\n\n  struct Utf8DecodeTestCase final {\n    char32_t code_point;\n    std::string_view code_units;\n  };\n\n  using Utf8DecodeTest = testing::TestWithParam<Utf8DecodeTestCase>;\n\n  TEST_P(Utf8DecodeTest, Compliance) {\n    const Utf8DecodeTestCase& test_case = GetParam();\n    auto [code_point, code_units] = Utf8::decode(test_case.code_units);\n    EXPECT_EQ(code_units, test_case.code_units.size());\n    EXPECT_EQ(code_point, test_case.code_point);\n  }\n\n  INSTANTIATE_TEST_SUITE_P(Utf8DecodeTest, Utf8DecodeTest,\n                          testing::ValuesIn<Utf8DecodeTestCase>({\n                              {0x0000, std::string_view(\"\\x00\", 1)},\n                              {0x0001, \"\\x01\"},\n                              {0x007e, \"\\x7e\"},\n                              {0x007f, \"\\x7f\"},\n                              {0x0080, \"\\xc2\\x80\"},\n                              {0x0081, \"\\xc2\\x81\"},\n                              {0x00bf, \"\\xc2\\xbf\"},\n                              {0x00c0, \"\\xc3\\x80\"},\n                              {0x00c1, \"\\xc3\\x81\"},\n                              {0x00c8, \"\\xc3\\x88\"},\n                              {0x00d0, \"\\xc3\\x90\"},\n                              {0x00e0, \"\\xc3\\xa0\"},\n                              {0x00f0, \"\\xc3\\xb0\"},\n                              {0x00f8, \"\\xc3\\xb8\"},\n                              {0x00ff, \"\\xc3\\xbf\"},\n                              {0x0100, \"\\xc4\\x80\"},\n                              {0x07ff, \"\\xdf\\xbf\"},\n                              {0x0400, \"\\xd0\\x80\"},\n                              {0x0800, \"\\xe0\\xa0\\x80\"},\n                              {0x0801, \"\\xe0\\xa0\\x81\"},\n                              {0x1000, \"\\xe1\\x80\\x80\"},\n                              {0xd000, \"\\xed\\x80\\x80\"},\n                              {0xd7ff, \"\\xed\\x9f\\xbf\"},\n                              {0xe000, \"\\xee\\x80\\x80\"},\n                              {0xfffe, \"\\xef\\xbf\\xbe\"},\n                              {0xffff, \"\\xef\\xbf\\xbf\"},\n                              {0x10000, \"\\xf0\\x90\\x80\\x80\"},\n                              {0x10001, \"\\xf0\\x90\\x80\\x81\"},\n                              {0x40000, \"\\xf1\\x80\\x80\\x80\"},\n                              {0x10fffe, \"\\xf4\\x8f\\xbf\\xbe\"},\n                              {0x10ffff, \"\\xf4\\x8f\\xbf\\xbf\"},\n                              {0xFFFD, \"\\xef\\xbf\\xbd\"},\n                          }));\n\n}\n}\n"
  },
  {
    "path": "runtime/Dart/.gitignore",
    "content": "!lib\n\n# See https://www.dartlang.org/guides/libraries/private-files\n\n# Files and directories created by pub\n.dart_tool/\n.packages\nbuild/\n# If you're building an application, you may want to check-in your pubspec.lock\npubspec.lock\n\n# Directory created by dartdoc\n# If you don't generate documentation locally you can remove this line.\ndoc/api/\n\n# Avoid committing generated Javascript files:\n*.dart.js\n*.info.json      # Produced by the --dump-info flag.\n*.js             # When generated by dart2js. Don't specify *.js if your\n                 # project includes source files written in JavaScript.\n*.js_\n*.js.deps\n*.js.map"
  },
  {
    "path": "runtime/Dart/LICENSE",
    "content": "[The \"BSD 3-clause license\"]\nCopyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. Neither the name of the copyright holder nor the names of its contributors\n    may be used to endorse or promote products derived from this software\n    without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\nTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=====\n\nMIT License for codepointat.js from https://git.io/codepointat\nMIT License for fromcodepoint.js from https://git.io/vDW1m\n\nCopyright Mathias Bynens <https://mathiasbynens.be/>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "runtime/Dart/README.md",
    "content": "# Dart target for ANTLR 4\n\nDart runtime libraries for ANTLR 4\n\nThis runtime is available through [pub](https://pub.dev). The package name is 'antlr4'.\n\nSee www.antlr.org for more information on ANTLR.\n\nSee https://github.com/antlr/antlr4/blob/master/doc/dart-target.md for more information on using ANTLR in Dart.\n\n\n"
  },
  {
    "path": "runtime/Dart/analysis_options.yaml",
    "content": "include: package:pedantic/analysis_options.yaml\n"
  },
  {
    "path": "runtime/Dart/benchmark/src/util/bit_set.dart",
    "content": "import 'package:antlr4/src/util/bit_set.dart';\nimport 'package:benchmark_harness/benchmark_harness.dart';\n\nclass TemplateBenchmark extends BenchmarkBase {\n  BitSet bs = BitSet();\n\n  TemplateBenchmark() : super('BitSet common operations');\n\n  static void main() {\n    TemplateBenchmark().report();\n  }\n\n  // The benchmark code.\n  @override\n  void run() {\n    bs.set(32);\n    bs.set(59);\n    bs.set(256);\n    bs.get(128);\n    bs.get(256);\n    bs.nextset(0);\n    bs.nextset(60);\n    bs.cardinality;\n    bs.hashCode;\n  }\n\n  // Not measured setup code executed prior to the benchmark runs.\n  @override\n  void setup() { }\n\n  // Not measured teardown code executed after the benchmark runs.\n  @override\n  void teardown() { }\n}\n\nvoid main() {\n  // Run TemplateBenchmark\n  TemplateBenchmark.main();\n}\n"
  },
  {
    "path": "runtime/Dart/lib/antlr4.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nlibrary antlr4;\n\nexport 'src/atn/atn.dart';\nexport 'src/dfa/dfa.dart';\nexport 'src/error/error.dart';\nexport 'src/misc/misc.dart';\nexport 'src/tree/tree.dart';\n\nexport 'src/input_stream.dart';\nexport 'src/interval_set.dart';\nexport 'src/lexer.dart';\nexport 'src/parser.dart';\nexport 'src/parser_rule_context.dart';\nexport 'src/prediction_context.dart';\nexport 'src/recognizer.dart';\nexport 'src/rule_context.dart';\nexport 'src/runtime_meta_data.dart';\nexport 'src/token.dart';\nexport 'src/token_factory.dart';\nexport 'src/token_source.dart';\nexport 'src/token_stream.dart';\nexport 'src/vocabulary.dart';\n\nimport 'src/util/platform_stub.dart'\n    if (dart.library.io) 'src/util/platform_io.dart';\n\n/// Hack to workaround not being able to access stdout in tests.\nvoid TEST_platformStdoutWrite(Object? object) => stdoutWrite(object);\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/atn.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport 'src/atn.dart';\nexport 'src/atn_config.dart';\nexport 'src/atn_config_set.dart';\nexport 'src/atn_deserializer.dart';\nexport 'src/atn_simulator.dart';\nexport 'src/atn_state.dart';\nexport 'src/info.dart';\nexport 'src/lexer_action_executor.dart';\nexport 'src/lexer_atn_simulator.dart';\nexport 'src/parser_atn_simulator.dart';\nexport 'src/profiling_atn_simulator.dart';\nexport 'src/semantic_context.dart';\nexport 'src/transition.dart';\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/atn.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../interval_set.dart';\nimport '../../ll1_analyzer.dart';\nimport '../../rule_context.dart';\nimport '../../token.dart';\nimport 'atn_state.dart';\nimport 'atn_type.dart';\nimport 'lexer_action.dart';\nimport 'transition.dart';\n\nclass ATN {\n  static final INVALID_ALT_NUMBER = 0;\n\n  List<ATNState?> states = [];\n\n  /// Each subrule/rule is a decision point and we must track them so we\n  ///  can go back later and build DFA predictors for them.  This includes\n  ///  all the rules, subrules, optional blocks, ()+, ()* etc...\n  List<DecisionState> decisionToState = [];\n\n  /// Maps from rule index to starting state number.\n  List<RuleStartState> ruleToStartState = <RuleStartState>[];\n\n  /// Maps from rule index to stop state number.\n  late List<RuleStopState> ruleToStopState;\n\n  Map<String, TokensStartState> modeNameToStartState = {};\n\n  /// The type of the ATN.\n  final ATNType grammarType;\n\n  /// The maximum value for any symbol recognized by a transition in the ATN.\n  final int maxTokenType;\n\n  /// For lexer ATNs, this maps the rule index to the resulting token type.\n  /// For parser ATNs, this maps the rule index to the generated bypass token\n  /// type if the\n  /// {@link ATNDeserializationOptions#isGenerateRuleBypassTransitions}\n  /// deserialization option was specified; otherwise, this is null.\n  late List<int> ruleToTokenType;\n\n  /// For lexer ATNs, this is an array of [LexerAction] objects which may\n  /// be referenced by action transitions in the ATN.\n  List<LexerAction>? lexerActions;\n\n  List<TokensStartState> modeToStartState = [];\n\n  /// Used for runtime deserialization of ATNs from strings */\n  ATN(this.grammarType, this.maxTokenType);\n\n  /// TODO merge doc comment\n  /// Compute the set of valid tokens that can occur starting in state [s].\n  ///  If [ctx] is null, the set of tokens will not include what can follow\n  ///  the rule surrounding [s]. In other words, the set will be\n  ///  restricted to tokens reachable staying within [s]'s rule.\n  ///\n  ///  Compute the set of valid tokens that can occur starting in [s] and\n  ///  staying in same rule. {@link Token#EPSILON} is in set if we reach end of\n  ///  rule.\n  IntervalSet nextTokens(ATNState s, [RuleContext? ctx]) {\n    if (ctx != null) {\n      return LL1Analyzer(this).LOOK(s, ctx);\n    }\n    if (s.nextTokenWithinRule != null) return s.nextTokenWithinRule!;\n    s.nextTokenWithinRule = LL1Analyzer(this).LOOK(s, null);\n    s.nextTokenWithinRule!.setReadonly(true);\n    return s.nextTokenWithinRule!;\n  }\n\n  void addState(ATNState? state) {\n    if (state != null) {\n      state.atn = this;\n      state.stateNumber = states.length;\n    }\n\n    states.add(state);\n  }\n\n  void removeState(ATNState state) {\n    states[state.stateNumber] =\n        null; // just free mem, don't shift states in list\n  }\n\n  int defineDecisionState(DecisionState s) {\n    decisionToState.add(s);\n    s.decision = decisionToState.length - 1;\n    return s.decision;\n  }\n\n  DecisionState? getDecisionState(int? decision) {\n    if (decisionToState.isNotEmpty || decision != null) {\n      return decisionToState[decision!];\n    }\n    return null;\n  }\n\n  int get numberOfDecisions {\n    return decisionToState.length;\n  }\n\n  /// Computes the set of input symbols which could follow ATN state number\n  /// [stateNumber] in the specified full [context]. This method\n  /// considers the complete parser context, but does not evaluate semantic\n  /// predicates (i.e. all predicates encountered during the calculation are\n  /// assumed true). If a path in the ATN exists from the starting state to the\n  /// [RuleStopState] of the outermost context without matching any\n  /// symbols, {@link Token#EOF} is added to the returned set.\n  ///\n  /// <p>If [context] is null, it is treated as {@link ParserRuleContext#EMPTY}.</p>\n  ///\n  /// Note that this does NOT give you the set of all tokens that could\n  /// appear at a given token position in the input phrase.  In other words,\n  /// it does not answer:\n  ///\n  ///   \"Given a specific partial input phrase, return the set of all tokens\n  ///    that can follow the last token in the input phrase.\"\n  ///\n  /// The big difference is that with just the input, the parser could\n  /// land right in the middle of a lookahead decision. Getting\n  /// all *possible* tokens given a partial input stream is a separate\n  /// computation. See https://github.com/antlr/antlr4/issues/1428\n  ///\n  /// For this function, we are specifying an ATN state and call stack to compute\n  /// what token(s) can come next and specifically: outside of a lookahead decision.\n  /// That is what you want for error reporting and recovery upon parse error.\n  ///\n  /// @param stateNumber the ATN state number\n  /// @param context the full parse context\n  /// @return The set of potentially valid input symbols which could follow the\n  /// specified state in the specified context.\n  /// @throws IllegalArgumentException if the ATN does not contain a state with\n  /// number [stateNumber]\n  IntervalSet getExpectedTokens(int stateNumber, RuleContext? context) {\n    if (stateNumber < 0 || stateNumber >= states.length) {\n      throw RangeError.index(stateNumber, states, 'stateNumber');\n    }\n\n    var ctx = context;\n    final s = states[stateNumber]!;\n    var following = nextTokens(s);\n    if (!following.contains(Token.EPSILON)) {\n      return following;\n    }\n\n    final expected = IntervalSet();\n    expected.addAll(following);\n    expected.remove(Token.EPSILON);\n    while (ctx != null &&\n        ctx.invokingState >= 0 &&\n        following.contains(Token.EPSILON)) {\n      final invokingState = states[ctx.invokingState]!;\n\n      final rt = invokingState.transition(0) as RuleTransition;\n      following = nextTokens(rt.followState);\n      expected.addAll(following);\n      expected.remove(Token.EPSILON);\n      ctx = ctx.parent;\n    }\n\n    if (following.contains(Token.EPSILON)) {\n      expected.addOne(Token.EOF);\n    }\n\n    return expected;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/atn_config.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../prediction_context.dart';\nimport '../../util/murmur_hash.dart';\nimport 'atn_state.dart';\nimport 'lexer_action_executor.dart';\nimport 'semantic_context.dart';\n\nMap<String, dynamic> checkParams(params, isCfg) {\n  if (params == null) {\n    final result = <String, dynamic>{\n      'state': null,\n      'alt': null,\n      'context': null,\n      'semanticContext': null\n    };\n    if (isCfg) {\n      result['reachesIntoOuterContext'] = 0;\n    }\n    return result;\n  } else {\n    final props = <String, dynamic>{};\n    props['state'] = params.state;\n    props['alt'] = (params.alt == null) ? null : params.alt;\n    props['context'] = params.context;\n    props['semanticContext'] = params.semanticContext;\n    if (isCfg) {\n      props['reachesIntoOuterContext'] = params.reachesIntoOuterContext ?? 0;\n      props['precedenceFilterSuppressed'] =\n          params.precedenceFilterSuppressed ?? false;\n    }\n    return props;\n  }\n}\n\n/// A tuple: (ATN state, predicted alt, syntactic, semantic context).\n///  The syntactic context is a graph-structured stack node whose\n///  path(s) to the root is the rule invocation(s)\n///  chain used to arrive at the state.  The semantic context is\n///  the tree of semantic predicates encountered before reaching\n///  an ATN state.\nclass ATNConfig {\n  /// This field stores the bit mask for implementing the\n  /// {@link #isPrecedenceFilterSuppressed} property as a bit within the\n  /// existing {@link #reachesIntoOuterContext} field.\n  static final int SUPPRESS_PRECEDENCE_FILTER = 0x40000000;\n\n  /// The ATN state associated with this configuration */\n  ATNState state;\n\n  /// What alt (or lexer rule) is predicted by this configuration */\n  int alt;\n\n  /// The stack of invoking states leading to the rule/states associated\n  ///  with this config.  We track only those contexts pushed during\n  ///  execution of the ATN simulator.\n  PredictionContext? context;\n\n  /// We cannot execute predicates dependent upon local context unless\n  /// we know for sure we are in the correct context. Because there is\n  /// no way to do this efficiently, we simply cannot evaluate\n  /// dependent predicates unless we are in the rule that initially\n  /// invokes the ATN simulator.\n  ///\n  /// <p>\n  /// closure() tracks the depth of how far we dip into the outer context:\n  /// depth &gt; 0.  Note that it may not be totally accurate depth since I\n  /// don't ever decrement. TODO: make it a bool then</p>\n  ///\n  /// <p>\n  /// For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method\n  /// is also backed by this field. Since the field is ly accessible, the\n  /// highest bit which would not cause the value to become negative is used to\n  /// store this field. This choice minimizes the risk that code which only\n  /// compares this value to 0 would be affected by the new purpose of the\n  /// flag. It also ensures the performance of the existing [ATNConfig]\n  /// constructors as well as certain operations like\n  /// {@link ATNConfigSet#add(ATNConfig, DoubleKeyMap)} method are\n  /// <em>completely</em> unaffected by the change.</p>\n  int reachesIntoOuterContext;\n\n  SemanticContext semanticContext;\n\n  ATNConfig(\n    this.state,\n    this.alt,\n    this.context, [\n    this.semanticContext = EmptySemanticContext.Instance,\n  ]) : reachesIntoOuterContext = 0;\n\n  ATNConfig.dup(\n    ATNConfig c, {\n    ATNState? state,\n    int? alt,\n    PredictionContext? context,\n    SemanticContext? semanticContext,\n  })  : state = state ?? c.state,\n        alt = alt ?? c.alt,\n        context = context ?? c.context,\n        semanticContext = semanticContext ?? c.semanticContext,\n        reachesIntoOuterContext = c.reachesIntoOuterContext;\n\n  /// This method gets the value of the {@link #reachesIntoOuterContext} field\n  /// as it existed prior to the introduction of the\n  /// {@link #isPrecedenceFilterSuppressed} method.\n  int get outerContextDepth {\n    return reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER;\n  }\n\n  bool isPrecedenceFilterSuppressed() {\n    return (reachesIntoOuterContext & SUPPRESS_PRECEDENCE_FILTER) != 0;\n  }\n\n  void setPrecedenceFilterSuppressed(bool value) {\n    if (value) {\n      reachesIntoOuterContext |= 0x40000000;\n    } else {\n      reachesIntoOuterContext &= ~SUPPRESS_PRECEDENCE_FILTER;\n    }\n  }\n\n  /// An ATN configuration is equal to another if both have\n  ///  the same state, they predict the same alternative, and\n  ///  syntactic/semantic contexts are the same.\n  @override\n  bool operator ==(Object other) {\n    if (other is ATNConfig) {\n      return state.stateNumber == other.state.stateNumber &&\n          alt == other.alt &&\n          (context == other.context ||\n              (context != null && context == other.context)) &&\n          semanticContext == other.semanticContext &&\n          isPrecedenceFilterSuppressed() ==\n              other.isPrecedenceFilterSuppressed();\n    }\n    return false;\n  }\n\n  @override\n  int get hashCode {\n    var hashCode = MurmurHash.initialize(7);\n    hashCode = MurmurHash.update(hashCode, state.stateNumber);\n    hashCode = MurmurHash.update(hashCode, alt);\n    hashCode = MurmurHash.update(hashCode, context);\n    hashCode = MurmurHash.update(hashCode, semanticContext);\n    hashCode = MurmurHash.finish(hashCode, 4);\n    return hashCode;\n  }\n\n  @override\n  String toString([_, bool showAlt = true]) {\n    final buf = StringBuffer();\n    // if ( state.ruleIndex>=0 ) {\n    //  if ( recog!=null ) buf.write(recog.ruleNames[state.ruleIndex]+\":\");\n    //  else buf.write(state.ruleIndex+\":\");\n    // }\n    buf.write('(');\n    buf.write(state);\n    if (showAlt) {\n      buf.write(',');\n      buf.write(alt);\n    }\n    if (context != null) {\n      buf.write(',[');\n      buf.write(context.toString());\n      buf.write(']');\n    }\n    if (semanticContext != EmptySemanticContext.Instance) {\n      buf.write(',');\n      buf.write(semanticContext);\n    }\n    if (outerContextDepth > 0) {\n      buf.write(',up=');\n      buf.write(outerContextDepth);\n    }\n    buf.write(')');\n    return buf.toString();\n  }\n}\n\nclass LexerATNConfig extends ATNConfig {\n  /// Gets the [LexerActionExecutor] capable of executing the embedded\n  /// action(s) for the current configuration.\n  LexerActionExecutor? lexerActionExecutor;\n\n  bool passedThroughNonGreedyDecision = false;\n\n  LexerATNConfig(\n    ATNState state,\n    int alt,\n    PredictionContext context, [\n    this.lexerActionExecutor,\n  ]) : super(state, alt, context, EmptySemanticContext.Instance) {\n    passedThroughNonGreedyDecision = false;\n  }\n\n  LexerATNConfig.dup(\n    LexerATNConfig c,\n    ATNState state, {\n    this.lexerActionExecutor,\n    PredictionContext? context,\n  }) : super.dup(c, state: state, context: context) {\n    lexerActionExecutor = lexerActionExecutor ?? c.lexerActionExecutor;\n    passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state);\n  }\n\n  bool hasPassedThroughNonGreedyDecision() {\n    return passedThroughNonGreedyDecision;\n  }\n\n  @override\n  int get hashCode {\n    var hashCode = MurmurHash.initialize(7);\n    hashCode = MurmurHash.update(hashCode, state.stateNumber);\n    hashCode = MurmurHash.update(hashCode, alt);\n    hashCode = MurmurHash.update(hashCode, context);\n    hashCode = MurmurHash.update(hashCode, semanticContext);\n    hashCode =\n        MurmurHash.update(hashCode, passedThroughNonGreedyDecision ? 1 : 0);\n    hashCode = MurmurHash.update(hashCode, lexerActionExecutor);\n    hashCode = MurmurHash.finish(hashCode, 6);\n    return hashCode;\n  }\n\n  @override\n  bool operator ==(Object other) {\n    if (identical(this, other)) {\n      return true;\n    } else if (other is LexerATNConfig) {\n      final lexerOther = other;\n      if (passedThroughNonGreedyDecision !=\n          lexerOther.passedThroughNonGreedyDecision) {\n        return false;\n      }\n\n      if (lexerActionExecutor != lexerOther.lexerActionExecutor) {\n        return false;\n      }\n\n      return super == other;\n    }\n    return false;\n  }\n\n  static bool checkNonGreedyDecision(LexerATNConfig source, ATNState target) {\n    return source.passedThroughNonGreedyDecision ||\n        target is DecisionState && target.nonGreedy;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/atn_config_set.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:collection';\nimport 'dart:math';\n\nimport 'package:collection/collection.dart';\n\nimport '../../misc/misc.dart';\nimport '../../prediction_context.dart';\nimport '../../util/bit_set.dart';\nimport '../../util/utils.dart';\nimport 'atn.dart';\nimport 'atn_config.dart';\nimport 'atn_state.dart';\nimport 'semantic_context.dart';\n\nfinal defaultConfigLookup = () => HashSet<ATNConfig>(equals: (a, b) {\n      return a.state.stateNumber == b.state.stateNumber &&\n          a.alt == b.alt &&\n          a.semanticContext == b.semanticContext;\n    }, hashCode: (ATNConfig o) {\n      var hashCode = 7;\n      hashCode = 31 * hashCode + o.state.stateNumber;\n      hashCode = 31 * hashCode + o.alt;\n      hashCode = 31 * hashCode + o.semanticContext.hashCode;\n      return hashCode;\n    });\n\nclass ATNConfigSet extends Iterable<ATNConfig> {\n  /// Indicates that the set of configurations is read-only. Do not\n  ///  allow any code to manipulate the set; DFA states will point at\n  ///  the sets and they must not change. This does not protect the other\n  ///  fields; in particular, conflictingAlts is set after\n  ///  we've made this readonly.\n  bool _readOnly = false;\n\n  bool get readOnly => _readOnly;\n\n  set readOnly(bool readOnly) {\n    _readOnly = readOnly;\n    if (readOnly) {\n      configLookup = null; // can't mod, no need for lookup cache\n    } else {\n      configLookup = defaultConfigLookup();\n    }\n  }\n\n  /// The reason that we need this is because we don't want the hash map to use\n  /// the standard hash code and equals. We need all configurations with the same\n  /// {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles\n  /// the number of objects associated with ATNConfigs. The other solution is to\n  /// use a hash table that lets us specify the equals/hashcode operation.\n  ///\n  /// All configs but hashed by (s, i, _, pi) not including context. Wiped out\n  /// when we go readonly as this set becomes a DFA state.\n  Set<ATNConfig>? configLookup = defaultConfigLookup();\n\n  /// Track the elements as they are added to the set; supports get(i) */\n  final List<ATNConfig> configs = [];\n\n  // TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation\n  // TODO: can we track conflicts as they are added to save scanning configs later?\n  int uniqueAlt = 0;\n\n  /// Currently this is only used when we detect SLL conflict; this does\n  ///  not necessarily represent the ambiguous alternatives. In fact,\n  ///  I should also point out that this seems to include predicated alternatives\n  ///  that have predicates that evaluate to false. Computed in computeTargetState().\n  BitSet? conflictingAlts;\n\n  // Used in parser and lexer. In lexer, it indicates we hit a pred\n  // while computing a closure operation.  Don't make a DFA state from this.\n  bool hasSemanticContext = false;\n  bool dipsIntoOuterContext = false;\n\n  /// Indicates that this configuration set is part of a full context\n  ///  LL prediction. It will be used to determine how to merge $. With SLL\n  ///  it's a wildcard whereas it is not for LL context merge.\n  bool fullCtx;\n\n  int cachedHashCode = -1;\n\n  ATNConfigSet([this.fullCtx = true]);\n\n  ATNConfigSet.dup(ATNConfigSet old)\n      : fullCtx = old.fullCtx,\n        uniqueAlt = old.uniqueAlt,\n        conflictingAlts = old.conflictingAlts,\n        hasSemanticContext = old.hasSemanticContext,\n        dipsIntoOuterContext = old.dipsIntoOuterContext {\n    addAll(old);\n  }\n\n  /// Adding a new config means merging contexts with existing configs for\n  /// {@code (s, i, pi, _)}, where [s] is the\n  /// {@link ATNConfig#state}, [i] is the {@link ATNConfig#alt}, and\n  /// [pi] is the {@link ATNConfig#semanticContext}. We use\n  /// {@code (s,i,pi)} as key.\n  ///\n  /// <p>This method updates {@link #dipsIntoOuterContext} and\n  /// {@link #hasSemanticContext} when necessary.</p>\n  bool add(\n    ATNConfig config, [\n    Map<Pair<PredictionContext, PredictionContext>, PredictionContext>?\n        mergeCache,\n  ]) {\n    if (readOnly) throw StateError('This set is readonly');\n    if (config.semanticContext != EmptySemanticContext.Instance) {\n      hasSemanticContext = true;\n    }\n    if (config.outerContextDepth > 0) {\n      dipsIntoOuterContext = true;\n    }\n    final existing = configLookup!.lookup(config) ?? config;\n    if (identical(existing, config)) {\n      // we added this new one\n      cachedHashCode = -1;\n      configLookup!.add(config);\n      configs.add(config); // track order here\n      return true;\n    }\n    // a previous (s,i,pi,_), merge with it and save result\n    final rootIsWildcard = !fullCtx;\n    final merged = PredictionContext.merge(\n      existing.context!,\n      config.context!,\n      rootIsWildcard,\n      mergeCache,\n    );\n    // no need to check for existing.context, config.context in cache\n    // since only way to create new graphs is \"call rule\" and here. We\n    // cache at both places.\n    existing.reachesIntoOuterContext =\n        max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext);\n\n    // make sure to preserve the precedence filter suppression during the merge\n    if (config.isPrecedenceFilterSuppressed()) {\n      existing.setPrecedenceFilterSuppressed(true);\n    }\n\n    existing.context = merged; // replace context; no need to alt mapping\n    return true;\n  }\n\n  /// Return a List holding list of configs */\n  List<ATNConfig> get elements {\n    return configs;\n  }\n\n  Set<ATNState> get states {\n    final states = <ATNState>{};\n    for (var i = 0; i < configs.length; i++) {\n      states.add(configs[i].state);\n    }\n    return states;\n  }\n\n  /// Gets the complete set of represented alternatives for the configuration\n  /// set.\n  ///\n  /// @return the set of represented alternatives in this configuration set\n  ///\n  /// @since 4.3\n  BitSet get alts {\n    final alts = BitSet();\n    for (var config in configs) {\n      alts.set(config.alt);\n    }\n    return alts;\n  }\n\n  List<SemanticContext?> get predicates {\n    final preds = <SemanticContext?>[];\n    for (var c in configs) {\n      if (c.semanticContext != EmptySemanticContext.Instance) {\n        preds.add(c.semanticContext);\n      }\n    }\n    return preds;\n  }\n\n  ATNConfig get(int i) {\n    return configs[i];\n  }\n\n  void optimizeConfigs(interpreter) {\n    if (readOnly) throw StateError('This set is readonly');\n\n    if (configLookup!.isEmpty) return;\n\n    for (var config in configs) {\n//\t\t\tint before = PredictionContext.getAllContextNodes(config.context).length;\n      config.context = interpreter!.getCachedContext(config.context);\n//\t\t\tint after = PredictionContext.getAllContextNodes(config.context).length;\n//\t\t\tSystem.out.println(\"configs \"+before+\"->\"+after);\n    }\n  }\n\n  bool addAll(coll) {\n    for (ATNConfig c in coll) {\n      add(c);\n    }\n    return false;\n  }\n\n  @override\n  bool operator ==(other) {\n    return identical(this, other) ||\n        (other is ATNConfigSet &&\n            ListEquality().equals(configs, other.configs) &&\n            fullCtx == other.fullCtx &&\n            uniqueAlt == other.uniqueAlt &&\n            conflictingAlts == other.conflictingAlts &&\n            hasSemanticContext == other.hasSemanticContext &&\n            dipsIntoOuterContext == other.dipsIntoOuterContext);\n  }\n\n  @override\n  int get hashCode {\n    if (readOnly) {\n      if (cachedHashCode == -1) {\n        cachedHashCode = ListEquality().hash(configs);\n      }\n\n      return cachedHashCode;\n    }\n\n    return ListEquality().hash(configs);\n  }\n\n  @override\n  int get length {\n    return configs.length;\n  }\n\n  @override\n  bool get isEmpty => configs.isEmpty;\n\n  void updateHashCode(hash) {\n    if (readOnly) {\n      if (cachedHashCode == -1) {\n        cachedHashCode = hashCode;\n      }\n      hash.update(cachedHashCode);\n    } else {\n      hash.update(hashCode);\n    }\n  }\n\n  @override\n  bool contains(Object? o) {\n    if (configLookup == null) {\n      throw UnsupportedError(\n          'This method is not implemented for readonly sets.');\n    }\n\n    return configLookup!.contains(o);\n  }\n\n  @override\n  Iterator<ATNConfig> get iterator => configs.iterator;\n\n  void clear() {\n    if (readOnly) throw StateError('This set is readonly');\n    configs.clear();\n    cachedHashCode = -1;\n    configLookup!.clear();\n  }\n\n  @override\n  String toString() {\n    final buf = StringBuffer();\n    buf.write(arrayToString(elements));\n    if (hasSemanticContext) {\n      buf.write(',hasSemanticContext=$hasSemanticContext');\n    }\n    if (uniqueAlt != ATN.INVALID_ALT_NUMBER) buf.write(',uniqueAlt=$uniqueAlt');\n    if (conflictingAlts != null) buf.write(',conflictingAlts=$conflictingAlts');\n    if (dipsIntoOuterContext) buf.write(',dipsIntoOuterContext');\n    return buf.toString();\n  }\n}\n\nclass OrderedATNConfigSet extends ATNConfigSet {\n  @override\n  final configLookup = <ATNConfig>{};\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/atn_deserializer.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../interval_set.dart';\nimport '../../misc/misc.dart';\nimport '../../token.dart';\nimport 'atn.dart';\nimport 'atn_state.dart';\nimport 'atn_type.dart';\nimport 'lexer_action.dart';\nimport 'transition.dart';\n\nclass ATNDeserializationOptions {\n  static late final ATNDeserializationOptions defaultOptions =\n      ATNDeserializationOptions(true);\n\n  bool readOnly;\n  late bool verifyATN;\n  late bool generateRuleBypassTransitions;\n\n  ATNDeserializationOptions(this.readOnly,\n      [ATNDeserializationOptions? options]) {\n    if (options == null) {\n      verifyATN = true;\n      generateRuleBypassTransitions = false;\n    } else {\n      verifyATN = options.verifyATN;\n      generateRuleBypassTransitions = options.generateRuleBypassTransitions;\n    }\n  }\n\n  bool isReadOnly() {\n    return readOnly;\n  }\n\n  void makeReadOnly() {\n    readOnly = true;\n  }\n\n  bool isVerifyATN() {\n    return verifyATN;\n  }\n\n  void setVerifyATN(bool verifyATN) {\n    throwIfReadOnly();\n    this.verifyATN = verifyATN;\n  }\n\n  bool isGenerateRuleBypassTransitions() {\n    return generateRuleBypassTransitions;\n  }\n\n  void setGenerateRuleBypassTransitions(bool generateRuleBypassTransitions) {\n    throwIfReadOnly();\n    this.generateRuleBypassTransitions = generateRuleBypassTransitions;\n  }\n\n  void throwIfReadOnly() {\n    if (isReadOnly()) {\n      throw StateError('The object is read only.');\n    }\n  }\n}\n\nclass ATNDeserializer {\n  static final SERIALIZED_VERSION = 4;\n\n  late final ATNDeserializationOptions deserializationOptions;\n  late List<int> data;\n  int pos = 0;\n\n  ATNDeserializer([ATNDeserializationOptions? options]) {\n    deserializationOptions =\n        options ?? ATNDeserializationOptions.defaultOptions;\n  }\n\n  ATN deserialize(List<int> data) {\n    this.data = data;\n    this.pos = 0;\n    checkVersion();\n    final atn = readATN();\n    readStates(atn);\n    readRules(atn);\n    readModes(atn);\n    final sets = <IntervalSet>[];\n    readSets(atn, sets);\n    readEdges(atn, sets);\n    readDecisions(atn);\n    readLexerActions(atn);\n    markPrecedenceDecisions(atn);\n    verifyATN(atn);\n    if (deserializationOptions.generateRuleBypassTransitions &&\n        atn.grammarType == ATNType.PARSER) {\n      generateRuleBypassTransitions(atn);\n      // re-verify after modification\n      verifyATN(atn);\n    }\n    return atn;\n  }\n\n  void checkVersion() {\n    final version = readInt();\n    if (version != SERIALIZED_VERSION) {\n      throw ('Could not deserialize ATN with version $version (expected $SERIALIZED_VERSION).');\n    }\n  }\n\n  ATN readATN() {\n    final grammarType = readInt();\n    final maxTokenType = readInt();\n    return ATN(ATNType.values[grammarType], maxTokenType);\n  }\n\n  void readStates(ATN atn) {\n    final loopBackStateNumbers = <Pair<LoopEndState, int>>[];\n    final endStateNumbers = <Pair<BlockStartState, int>>[];\n    final nstates = readInt();\n    for (var i = 0; i < nstates; i++) {\n      final stype = StateType.values[readInt()];\n      // ignore bad type of states\n      if (stype == StateType.INVALID_TYPE) {\n        atn.addState(null);\n        continue;\n      }\n\n      var ruleIndex = readInt();\n\n      final s = stateFactory(stype, ruleIndex);\n      if (s is LoopEndState) {\n        // special case\n        final loopBackStateNumber = readInt();\n        loopBackStateNumbers.add(Pair(s, loopBackStateNumber));\n      } else if (s is BlockStartState) {\n        final endStateNumber = readInt();\n        endStateNumbers.add(Pair(s, endStateNumber));\n      }\n      atn.addState(s);\n    }\n\n    // delay the assignment of loop back and end states until we know all the state instances have been initialized\n    for (final pair in loopBackStateNumbers) {\n      pair.a.loopBackState = atn.states[pair.b];\n    }\n\n    for (final pair in endStateNumbers) {\n      pair.a.endState = atn.states[pair.b] as BlockEndState;\n    }\n\n    final numNonGreedyStates = readInt();\n    for (var i = 0; i < numNonGreedyStates; i++) {\n      final stateNumber = readInt();\n      (atn.states[stateNumber] as DecisionState).nonGreedy = true;\n    }\n\n    final numPrecedenceStates = readInt();\n    for (var i = 0; i < numPrecedenceStates; i++) {\n      final stateNumber = readInt();\n      (atn.states[stateNumber] as RuleStartState).isLeftRecursiveRule = true;\n    }\n  }\n\n  void readRules(ATN atn) {\n    final nrules = readInt();\n    if (atn.grammarType == ATNType.LEXER) {\n      atn.ruleToTokenType = <int>[];\n    }\n\n    for (var i = 0; i < nrules; i++) {\n      final s = readInt();\n      final startState = atn.states[s] as RuleStartState;\n      atn.ruleToStartState.add(startState);\n      if (atn.grammarType == ATNType.LEXER) {\n        var tokenType = readInt();\n\n        atn.ruleToTokenType.add(tokenType);\n      }\n    }\n\n    atn.ruleToStopState = List<RuleStopState>.generate(\n        nrules, (int index) => RuleStopState(index));\n\n    for (var state in atn.states) {\n      if (state is! RuleStopState) {\n        continue;\n      }\n      atn.ruleToStopState[state.ruleIndex] = state;\n      atn.ruleToStartState[state.ruleIndex].stopState = state;\n    }\n  }\n\n  void readModes(ATN atn) {\n    final nmodes = readInt();\n    for (var i = 0; i < nmodes; i++) {\n      final s = readInt();\n      atn.modeToStartState.add(atn.states[s] as TokensStartState);\n    }\n  }\n\n  void readSets(ATN atn, List<IntervalSet> sets) {\n    final nsets = readInt();\n    for (var i = 0; i < nsets; i++) {\n      final nintervals = readInt();\n      final set = IntervalSet();\n      sets.add(set);\n\n      final containsEof = readInt() != 0;\n      if (containsEof) {\n        set.addOne(-1);\n      }\n\n      for (var j = 0; j < nintervals; j++) {\n        int a = readInt();\n        int b = readInt();\n        set.addRange(a, b);\n      }\n    }\n  }\n\n  void readEdges(ATN atn, sets) {\n    final nedges = readInt();\n    for (var i = 0; i < nedges; i++) {\n      final src = readInt();\n      final trg = readInt();\n      final ttype = TransitionType.values[readInt()];\n      final arg1 = readInt();\n      final arg2 = readInt();\n      final arg3 = readInt();\n      final trans = edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);\n//\t\t\tSystem.out.println(\"EDGE \"+trans.getClass().getSimpleName()+\" \"+\n//\t\t\t\t\t\t\t   src+\"->\"+trg+\n//\t\t\t\t\t   \" \"+Transition.serializationNames[ttype]+\n//\t\t\t\t\t   \" \"+arg1+\",\"+arg2+\",\"+arg3);\n      final srcState = atn.states[src]!;\n      srcState.addTransition(trans);\n    }\n\n    // edges for rule stop states can be derived, so they aren't serialized\n    for (var state in atn.states) {\n      if (state == null) {\n        continue;\n      }\n      for (var i = 0; i < state.numberOfTransitions; i++) {\n        final t = state.transition(i);\n        if (t is RuleTransition) {\n          final ruleTransition = t;\n          var outermostPrecedenceReturn = -1;\n          if (atn.ruleToStartState[ruleTransition.target.ruleIndex]\n              .isLeftRecursiveRule) {\n            if (ruleTransition.precedence == 0) {\n              outermostPrecedenceReturn = ruleTransition.target.ruleIndex;\n            }\n          }\n\n          final returnTransition = EpsilonTransition(\n              ruleTransition.followState, outermostPrecedenceReturn);\n          atn.ruleToStopState[ruleTransition.target.ruleIndex]\n              .addTransition(returnTransition);\n        }\n      }\n    }\n\n    for (var state in atn.states) {\n      if (state is BlockStartState) {\n        // we need to know the end state to set its start state\n        if (state.endState == null) {\n          throw StateError('');\n        }\n\n        // block end states can only be associated to a single block start state\n        if (state.endState!.startState != null) {\n          throw StateError('');\n        }\n\n        state.endState!.startState = state;\n      }\n\n      if (state is PlusLoopbackState) {\n        final loopbackState = state;\n        for (var i = 0; i < loopbackState.numberOfTransitions; i++) {\n          final target = loopbackState.transition(i).target;\n          if (target is PlusBlockStartState) {\n            target.loopBackState = loopbackState;\n          }\n        }\n      } else if (state is StarLoopbackState) {\n        final loopbackState = state;\n        for (var i = 0; i < loopbackState.numberOfTransitions; i++) {\n          final target = loopbackState.transition(i).target;\n          if (target is StarLoopEntryState) {\n            target.loopBackState = loopbackState;\n          }\n        }\n      }\n    }\n  }\n\n  void readDecisions(ATN atn) {\n    final ndecisions = readInt();\n    for (var i = 1; i <= ndecisions; i++) {\n      final s = readInt();\n      final decState = atn.states[s] as DecisionState;\n      atn.decisionToState.add(decState);\n      decState.decision = i - 1;\n    }\n  }\n\n  void readLexerActions(ATN atn) {\n    if (atn.grammarType == ATNType.LEXER) {\n      atn.lexerActions = List<LexerAction>.generate(readInt(), (index) {\n        final actionType = LexerActionType.values[readInt()];\n        var data1 = readInt();\n        var data2 = readInt();\n        final lexerAction = lexerActionFactory(actionType, data1, data2);\n\n        return lexerAction;\n      });\n    }\n  }\n\n  void generateRuleBypassTransitions(ATN atn) {\n    final length = atn.ruleToStartState.length;\n    atn.ruleToTokenType =\n        List<int>.generate(length, (index) => atn.maxTokenType + index + 1);\n\n    for (var i = 0; i < atn.ruleToStartState.length; i++) {\n      generateRuleBypassTransition(atn, i);\n    }\n  }\n\n  void generateRuleBypassTransition(ATN atn, int idx) {\n    final bypassStart = BasicBlockStartState(idx);\n    atn.addState(bypassStart);\n\n    final bypassStop = BlockEndState(idx);\n    atn.addState(bypassStop);\n\n    bypassStart.endState = bypassStop;\n    atn.defineDecisionState(bypassStart);\n\n    bypassStop.startState = bypassStart;\n\n    ATNState? endState;\n    Transition? excludeTransition;\n    if (atn.ruleToStartState[idx].isLeftRecursiveRule) {\n      // wrap from the beginning of the rule to the StarLoopEntryState\n      endState = null;\n      for (var state in atn.states) {\n        if (state == null) {\n          continue;\n        }\n        if (state.ruleIndex != idx) {\n          continue;\n        }\n\n        if (state is! StarLoopEntryState) {\n          continue;\n        }\n\n        final maybeLoopEndState =\n            state.transition(state.numberOfTransitions - 1).target;\n        if (maybeLoopEndState is! LoopEndState) {\n          continue;\n        }\n\n        if (maybeLoopEndState.epsilonOnlyTransitions &&\n            maybeLoopEndState.transition(0).target is RuleStopState) {\n          endState = state;\n          break;\n        }\n      }\n\n      if (endState == null) {\n        throw UnsupportedError(\n          \"Couldn't identify final state of the precedence rule prefix section.\",\n        );\n      }\n\n      excludeTransition =\n          (endState as StarLoopEntryState).loopBackState!.transition(0);\n    } else {\n      endState = atn.ruleToStopState[idx];\n    }\n\n    // all non-excluded transitions that currently target end state need to target blockEnd instead\n    for (var state in atn.states) {\n      if (state == null) {\n        continue;\n      }\n      for (var transition in state.transitions) {\n        if (transition == excludeTransition) {\n          continue;\n        }\n\n        if (transition.target == endState) {\n          transition.target = bypassStop;\n        }\n      }\n    }\n\n    // all transitions leaving the rule start state need to leave blockStart instead\n    while (atn.ruleToStartState[idx].numberOfTransitions > 0) {\n      final transition = atn.ruleToStartState[idx]\n          .removeTransition(atn.ruleToStartState[idx].numberOfTransitions - 1);\n      bypassStart.addTransition(transition);\n    }\n\n    // link the new states\n    atn.ruleToStartState[idx].addTransition(EpsilonTransition(bypassStart));\n    bypassStop.addTransition(EpsilonTransition(endState));\n\n    ATNState matchState = BasicState(idx);\n    atn.addState(matchState);\n\n    matchState.addTransition(AtomTransition(\n      bypassStop,\n      atn.ruleToTokenType[idx],\n    ));\n    bypassStart.addTransition(EpsilonTransition(matchState));\n  }\n\n  /// Analyze the [StarLoopEntryState] states in the specified ATN to set\n  /// the {@link StarLoopEntryState#isPrecedenceDecision} field to the\n  /// correct value.\n  ///\n  /// @param atn The ATN.\n  void markPrecedenceDecisions(ATN atn) {\n    for (var state in atn.states) {\n      if (state is StarLoopEntryState) {\n        /* We analyze the ATN to determine if this ATN decision state is the\n\t\t\t * decision for the closure block that determines whether a\n\t\t\t * precedence rule should continue or complete.\n\t\t\t */\n        if (atn.ruleToStartState[state.ruleIndex].isLeftRecursiveRule) {\n          final maybeLoopEndState =\n              state.transition(state.numberOfTransitions - 1).target;\n          if (maybeLoopEndState is LoopEndState) {\n            if (maybeLoopEndState.epsilonOnlyTransitions &&\n                maybeLoopEndState.transition(0).target is RuleStopState) {\n              state.isPrecedenceDecision = true;\n            }\n          }\n        }\n      }\n    }\n  }\n\n  void verifyATN(ATN atn) {\n    // verify assumptions\n    for (var state in atn.states) {\n      if (state == null) {\n        continue;\n      }\n\n      checkCondition(\n          state.onlyHasEpsilonTransitions() || state.numberOfTransitions <= 1);\n\n      if (state is PlusBlockStartState) {\n        checkCondition(state.loopBackState != null);\n      }\n\n      if (state is StarLoopEntryState) {\n        final starLoopEntryState = state;\n        checkCondition(starLoopEntryState.loopBackState != null);\n        checkCondition(starLoopEntryState.numberOfTransitions == 2);\n\n        if (starLoopEntryState.transition(0).target is StarBlockStartState) {\n          checkCondition(\n              starLoopEntryState.transition(1).target is LoopEndState);\n          checkCondition(!starLoopEntryState.nonGreedy);\n        } else if (starLoopEntryState.transition(0).target is LoopEndState) {\n          checkCondition(\n              starLoopEntryState.transition(1).target is StarBlockStartState);\n          checkCondition(starLoopEntryState.nonGreedy);\n        } else {\n          throw StateError('');\n        }\n      }\n\n      if (state is StarLoopbackState) {\n        checkCondition(state.numberOfTransitions == 1);\n        checkCondition(state.transition(0).target is StarLoopEntryState);\n      }\n\n      if (state is LoopEndState) {\n        checkCondition(state.loopBackState != null);\n      }\n\n      if (state is RuleStartState) {\n        checkCondition(state.stopState != null);\n      }\n\n      if (state is BlockStartState) {\n        checkCondition(state.endState != null);\n      }\n\n      if (state is BlockEndState) {\n        checkCondition(state.startState != null);\n      }\n\n      if (state is DecisionState) {\n        final decisionState = state;\n        checkCondition(decisionState.numberOfTransitions <= 1 ||\n            decisionState.decision >= 0);\n      } else {\n        checkCondition(\n            state.numberOfTransitions <= 1 || state is RuleStopState);\n      }\n    }\n  }\n\n  void checkCondition(bool condition, [String message = '']) {\n    if (!condition) {\n      throw StateError(message);\n    }\n  }\n\n  int readInt() {\n    return data[pos++];\n  }\n\n  Transition edgeFactory(\n    ATN atn,\n    TransitionType type,\n    int src,\n    int trg,\n    int arg1,\n    int arg2,\n    int arg3,\n    List<IntervalSet> sets,\n  ) {\n    final target = atn.states[trg]!;\n    switch (type) {\n      case TransitionType.EPSILON:\n        return EpsilonTransition(target);\n      case TransitionType.RANGE:\n        return arg3 != 0\n            ? RangeTransition(target, Token.EOF, arg2)\n            : RangeTransition(target, arg1, arg2);\n      case TransitionType.RULE:\n        final rt = RuleTransition(\n            atn.states[arg1] as RuleStartState, arg2, arg3, target);\n        return rt;\n      case TransitionType.PREDICATE:\n        final pt = PredicateTransition(target, arg1, arg2, arg3 != 0);\n        return pt;\n      case TransitionType.PRECEDENCE:\n        return PrecedencePredicateTransition(target, arg1);\n      case TransitionType.ATOM:\n        return arg3 != 0\n            ? AtomTransition(target, Token.EOF)\n            : AtomTransition(target, arg1);\n      case TransitionType.ACTION:\n        final a = ActionTransition(target, arg1, arg2, arg3 != 0);\n        return a;\n      case TransitionType.SET:\n        return SetTransition(target, sets[arg1]);\n      case TransitionType.NOT_SET:\n        return NotSetTransition(target, sets[arg1]);\n      case TransitionType.WILDCARD:\n        return WildcardTransition(target);\n      case TransitionType.INVALID:\n        throw ArgumentError.value(type, 'transition type', 'not valid.');\n      default:\n        throw ArgumentError.value(type, 'transition type', 'not valid.');\n    }\n  }\n\n  ATNState? stateFactory(StateType type, int ruleIndex) {\n    ATNState s;\n    switch (type) {\n      case StateType.INVALID_TYPE:\n        return null;\n      case StateType.BASIC:\n        s = BasicState(ruleIndex);\n        break;\n      case StateType.RULE_START:\n        s = RuleStartState(ruleIndex);\n        break;\n      case StateType.BLOCK_START:\n        s = BasicBlockStartState(ruleIndex);\n        break;\n      case StateType.PLUS_BLOCK_START:\n        s = PlusBlockStartState(ruleIndex);\n        break;\n      case StateType.STAR_BLOCK_START:\n        s = StarBlockStartState(ruleIndex);\n        break;\n      case StateType.TOKEN_START:\n        s = TokensStartState(ruleIndex);\n        break;\n      case StateType.RULE_STOP:\n        s = RuleStopState(ruleIndex);\n        break;\n      case StateType.BLOCK_END:\n        s = BlockEndState(ruleIndex);\n        break;\n      case StateType.STAR_LOOP_BACK:\n        s = StarLoopbackState(ruleIndex);\n        break;\n      case StateType.STAR_LOOP_ENTRY:\n        s = StarLoopEntryState(ruleIndex);\n        break;\n      case StateType.PLUS_LOOP_BACK:\n        s = PlusLoopbackState(ruleIndex);\n        break;\n      case StateType.LOOP_END:\n        s = LoopEndState(ruleIndex);\n        break;\n      default:\n        throw ArgumentError.value(type, 'state type', 'not valid.');\n    }\n\n    return s;\n  }\n\n  LexerAction lexerActionFactory(LexerActionType type, int data1, int data2) {\n    switch (type) {\n      case LexerActionType.CHANNEL:\n        return LexerChannelAction(data1);\n\n      case LexerActionType.CUSTOM:\n        return LexerCustomAction(data1, data2);\n\n      case LexerActionType.MODE:\n        return LexerModeAction(data1);\n\n      case LexerActionType.MORE:\n        return LexerMoreAction.INSTANCE;\n\n      case LexerActionType.POP_MODE:\n        return LexerPopModeAction.INSTANCE;\n\n      case LexerActionType.PUSH_MODE:\n        return LexerPushModeAction(data1);\n\n      case LexerActionType.SKIP:\n        return LexerSkipAction.INSTANCE;\n\n      case LexerActionType.TYPE:\n        return LexerTypeAction(data1);\n      default:\n        throw ArgumentError.value(type, 'lexer action type', 'not valid.');\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/atn_simulator.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../dfa/dfa.dart';\nimport '../../prediction_context.dart';\nimport 'atn.dart';\nimport 'atn_config_set.dart';\n\nabstract class ATNSimulator {\n  /// Must distinguish between missing edge and edge we know leads nowhere */\n\n  static final DFAState ERROR = DFAState(\n    stateNumber: 0x7FFFFFFF,\n    configs: ATNConfigSet(),\n  );\n\n  final ATN atn;\n\n  /// The context cache maps all PredictionContext objects that are equals()\n  ///  to a single cached copy. This cache is shared across all contexts\n  ///  in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet\n  ///  to use only cached nodes/graphs in addDFAState(). We don't want to\n  ///  fill this during closure() since there are lots of contexts that\n  ///  pop up but are not used ever again. It also greatly slows down closure().\n  ///\n  ///  <p>This cache makes a huge difference in memory and a little bit in speed.\n  ///  For the Java grammar on java.*, it dropped the memory requirements\n  ///  at the end from 25M to 16M. We don't store any of the full context\n  ///  graphs in the DFA because they are limited to local context only,\n  ///  but apparently there's a lot of repetition there as well. We optimize\n  ///  the config contexts before storing the config set in the DFA states\n  ///  by literally rebuilding them with cached subgraphs only.</p>\n  ///\n  ///  <p>I tried a cache for use during closure operations, that was\n  ///  whacked after each adaptivePredict(). It cost a little bit\n  ///  more time I think and doesn't save on the overall footprint\n  ///  so it's not worth the complexity.</p>\n  final PredictionContextCache? sharedContextCache;\n\n  ATNSimulator(this.atn, this.sharedContextCache);\n\n  void reset();\n\n  /// Clear the DFA cache used by the current instance. Since the DFA cache may\n  /// be shared by multiple ATN simulators, this method may affect the\n  /// performance (but not accuracy) of other parsers which are being used\n  /// concurrently.\n  ///\n  /// @throws UnsupportedOperationException if the current instance does not\n  /// support clearing the DFA.\n  ///\n  /// @since 4.3\n  void clearDFA() {\n    throw UnsupportedError(\n        'This ATN simulator does not support clearing the DFA.');\n  }\n\n  PredictionContext getCachedContext(PredictionContext context) {\n    if (sharedContextCache == null) return context;\n\n    final visited = <PredictionContext, PredictionContext>{};\n    return PredictionContext.getCachedContext(\n        context, sharedContextCache!, visited);\n  }\n}\n\n/// Used to cache [PredictionContext] objects. Its used for the shared\n///  context cash associated with contexts in DFA states. This cache\n///  can be used for both lexers and parsers.\nclass PredictionContextCache {\n  final cache = <PredictionContext, PredictionContext>{};\n\n  /// Add a context to the cache and return it. If the context already exists,\n  ///  return that one instead and do not add a new context to the cache.\n  ///  Protect shared cache from unsafe thread access.\n  PredictionContext add(PredictionContext ctx) {\n    if (ctx == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance;\n    final existing = cache[ctx];\n    if (existing != null) {\n//\t\t\tSystem.out.println(name+\" reuses \"+existing);\n      return existing;\n    }\n    cache[ctx] = ctx;\n    return ctx;\n  }\n\n  PredictionContext? operator [](PredictionContext ctx) {\n    return cache[ctx];\n  }\n\n  int get length {\n    return cache.length;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/atn_state.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:developer';\n\nimport 'package:logging/logging.dart';\n\nimport '../../interval_set.dart';\nimport 'atn.dart';\nimport 'transition.dart';\n\nvar INITIAL_NUM_TRANSITIONS = 4;\n\nenum StateType {\n  INVALID_TYPE,\n  BASIC,\n  RULE_START,\n  BLOCK_START,\n  PLUS_BLOCK_START,\n  STAR_BLOCK_START,\n  TOKEN_START,\n  RULE_STOP,\n  BLOCK_END,\n  STAR_LOOP_BACK,\n  STAR_LOOP_ENTRY,\n  PLUS_LOOP_BACK,\n  LOOP_END,\n}\n\n/// The following images show the relation of states and\n/// {@link ATNState#transitions} for various grammar constructs.\n///\n/// <ul>\n///\n/// <li>Solid edges marked with an &#0949; indicate a required\n/// [EpsilonTransition].</li>\n///\n/// <li>Dashed edges indicate locations where any transition derived from\n/// [Transition] might appear.</li>\n///\n/// <li>Dashed nodes are place holders for either a sequence of linked\n/// [BasicState] states or the inclusion of a block representing a nested\n/// construct in one of the forms below.</li>\n///\n/// <li>Nodes showing multiple outgoing alternatives with a {@code ...} support\n/// any number of alternatives (one or more). Nodes without the {@code ...} only\n/// support the exact number of alternatives shown in the diagram.</li>\n///\n/// </ul>\n///\n/// <h2>Basic Blocks</h2>\n///\n/// <h3>Rule</h3>\n///\n/// <embed src=\"images/Rule.svg\" type=\"image/svg+xml\"/>\n///\n/// <h3>Block of 1 or more alternatives</h3>\n///\n/// <embed src=\"images/Block.svg\" type=\"image/svg+xml\"/>\n///\n/// <h2>Greedy Loops</h2>\n///\n/// <h3>Greedy Closure: {@code (...)*}</h3>\n///\n/// <embed src=\"images/ClosureGreedy.svg\" type=\"image/svg+xml\"/>\n///\n/// <h3>Greedy Positive Closure: {@code (...)+}</h3>\n///\n/// <embed src=\"images/PositiveClosureGreedy.svg\" type=\"image/svg+xml\"/>\n///\n/// <h3>Greedy Optional: {@code (...)?}</h3>\n///\n/// <embed src=\"images/OptionalGreedy.svg\" type=\"image/svg+xml\"/>\n///\n/// <h2>Non-Greedy Loops</h2>\n///\n/// <h3>Non-Greedy Closure: {@code (...)*?}</h3>\n///\n/// <embed src=\"images/ClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n///\n/// <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>\n///\n/// <embed src=\"images/PositiveClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n///\n/// <h3>Non-Greedy Optional: {@code (...)??}</h3>\n///\n/// <embed src=\"images/OptionalNonGreedy.svg\" type=\"image/svg+xml\"/>\nabstract class ATNState {\n  static final int INITIAL_NUM_TRANSITIONS = 4;\n\n  static final int INVALID_STATE_NUMBER = -1;\n\n  /// Which ATN are we in? */\n  late ATN atn;\n\n  int stateNumber = INVALID_STATE_NUMBER;\n\n  int ruleIndex; // at runtime, we don't have Rule objects\n\n  bool epsilonOnlyTransitions = false;\n\n  /// Track the transitions emanating from this ATN state. */\n  List<Transition> transitions = [];\n\n  /// Used to cache lookahead during parsing, not used during construction */\n  IntervalSet? nextTokenWithinRule;\n\n  ATNState(this.ruleIndex);\n\n  @override\n  int get hashCode {\n    return stateNumber;\n  }\n\n  @override\n  bool operator ==(Object o) {\n    // are these states same object?\n    if (o is ATNState) return stateNumber == o.stateNumber;\n    return false;\n  }\n\n  bool isNonGreedyExitState() {\n    return false;\n  }\n\n  @override\n  String toString() {\n    return stateNumber.toString();\n  }\n\n  int get numberOfTransitions {\n    return transitions.length;\n  }\n\n  void addTransition(Transition e) {\n    addTransitionAt(transitions.length, e);\n  }\n\n  void addTransitionAt(int index, Transition e) {\n    if (transitions.isEmpty) {\n      epsilonOnlyTransitions = e.isEpsilon;\n    } else if (epsilonOnlyTransitions != e.isEpsilon) {\n      log('ATN state $stateNumber has both epsilon and non-epsilon transitions.\\n',\n          level: Level.SEVERE.value);\n      epsilonOnlyTransitions = false;\n    }\n\n    var alreadyPresent = false;\n    for (var t in transitions) {\n      if (t.target.stateNumber == e.target.stateNumber) {\n        if (t.label != null && e.label != null && t.label == e.label) {\n//\t\t\t\t\tSystem.err.println(\"Repeated transition upon \"+e.label()+\" from \"+stateNumber+\"->\"+t.target.stateNumber);\n          alreadyPresent = true;\n          break;\n        } else if (t.isEpsilon && e.isEpsilon) {\n//\t\t\t\t\tSystem.err.println(\"Repeated epsilon transition from \"+stateNumber+\"->\"+t.target.stateNumber);\n          alreadyPresent = true;\n          break;\n        }\n      }\n    }\n    if (!alreadyPresent) {\n      transitions.insert(index, e);\n    }\n  }\n\n  Transition transition(int i) {\n    return transitions[i];\n  }\n\n  void setTransition(int i, Transition e) {\n    transitions[i] = e;\n  }\n\n  Transition removeTransition(int index) {\n    return transitions.removeAt(index);\n  }\n\n  StateType get stateType;\n\n  bool onlyHasEpsilonTransitions() => epsilonOnlyTransitions;\n\n  void setRuleIndex(int ruleIndex) {\n    this.ruleIndex = ruleIndex;\n  }\n}\n\nclass BasicState extends ATNState {\n  BasicState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.BASIC;\n}\n\nclass RuleStartState extends ATNState {\n  RuleStopState? stopState;\n  bool isLeftRecursiveRule = false;\n\n  RuleStartState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.RULE_START;\n}\n\nabstract class DecisionState extends ATNState {\n  int decision = 0;\n  bool nonGreedy = false;\n\n  DecisionState(int ruleIndex) : super(ruleIndex);\n}\n\n//  The start of a regular {@code (...)} block.\nabstract class BlockStartState extends DecisionState {\n  BlockEndState? endState;\n\n  BlockStartState(int ruleIndex) : super(ruleIndex);\n}\n\nclass BasicBlockStartState extends BlockStartState {\n  BasicBlockStartState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.BLOCK_START;\n}\n\n/// Start of {@code (A|B|...)+} loop. Technically a decision state, but\n///  we don't use for code generation; somebody might need it, so I'm defining\n///  it for completeness. In reality, the [PlusLoopbackState] node is the\n///  real decision-making note for {@code A+}.\nclass PlusBlockStartState extends BlockStartState {\n  PlusLoopbackState? loopBackState;\n\n  PlusBlockStartState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.PLUS_BLOCK_START;\n}\n\n/// The block that begins a closure loop.\nclass StarBlockStartState extends BlockStartState {\n  StarBlockStartState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.STAR_BLOCK_START;\n}\n\n/// The Tokens rule start state linking to each lexer rule start state */\nclass TokensStartState extends DecisionState {\n  TokensStartState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.TOKEN_START;\n}\n\n/// The last node in the ATN for a rule, unless that rule is the start symbol.\n///  In that case, there is one transition to EOF. Later, we might encode\n///  references to all calls to this rule to compute FOLLOW sets for\n///  error handling.\nclass RuleStopState extends ATNState {\n  RuleStopState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.RULE_STOP;\n}\n\n/// Terminal node of a simple {@code (a|b|c)} block.\nclass BlockEndState extends ATNState {\n  BlockStartState? startState;\n\n  BlockEndState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.BLOCK_END;\n}\n\nclass StarLoopbackState extends ATNState {\n  StarLoopbackState(int ruleIndex) : super(ruleIndex);\n\n  StarLoopEntryState get loopEntryState {\n    return transition(0).target as StarLoopEntryState;\n  }\n\n  @override\n  StateType get stateType => StateType.STAR_LOOP_BACK;\n}\n\nclass StarLoopEntryState extends DecisionState {\n  StarLoopbackState? loopBackState;\n\n  /// Indicates whether this state can benefit from a precedence DFA during SLL\n  /// decision making.\n  ///\n  /// <p>This is a computed property that is calculated during ATN deserialization\n  /// and stored for use in [ParserATNSimulator] and\n  /// [ParserInterpreter].</p>\n  ///\n  /// @see DFA#isPrecedenceDfa()\n  bool isPrecedenceDecision = false;\n\n  StarLoopEntryState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.STAR_LOOP_ENTRY;\n}\n\n/// Decision state for {@code A+} and {@code (A|B)+}.  It has two transitions:\n///  one to the loop back to start of the block and one to exit.\nclass PlusLoopbackState extends DecisionState {\n  PlusLoopbackState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.PLUS_LOOP_BACK;\n}\n\n/// Mark the end of a * or + loop.\nclass LoopEndState extends ATNState {\n  ATNState? loopBackState;\n\n  LoopEndState(int ruleIndex) : super(ruleIndex);\n\n  @override\n  StateType get stateType => StateType.LOOP_END;\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/atn_type.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/// Represents the type of recognizer an ATN applies to.\nenum ATNType {\n  /// A lexer grammar.\n  LEXER,\n\n  /// A parser grammar.\n  PARSER\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/info.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../token_stream.dart';\nimport '../../util/bit_set.dart';\nimport 'atn_config_set.dart';\nimport 'profiling_atn_simulator.dart';\nimport 'semantic_context.dart';\n\n/// This class represents profiling event information for a context sensitivity.\n/// Context sensitivities are decisions where a particular input resulted in an\n/// SLL conflict, but LL prediction produced a single unique alternative.\n///\n/// <p>\n/// In some cases, the unique alternative identified by LL prediction is not\n/// equal to the minimum represented alternative in the conflicting SLL\n/// configuration set. Grammars and inputs which result in this scenario are\n/// unable to use {@link PredictionMode#SLL}, which in turn means they cannot use\n/// the two-stage parsing strategy to improve parsing performance for that\n/// input.</p>\n///\n/// @see ParserATNSimulator#reportContextSensitivity\n/// @see ANTLRErrorListener#reportContextSensitivity\n///\n/// @since 4.3\nclass ContextSensitivityInfo extends DecisionEventInfo {\n  /// Constructs a new instance of the [ContextSensitivityInfo] class\n  /// with the specified detailed context sensitivity information.\n  ///\n  /// @param decision The decision number\n  /// @param configs The final configuration set containing the unique\n  /// alternative identified by full-context prediction\n  /// @param input The input token stream\n  /// @param startIndex The start index for the current prediction\n  /// @param stopIndex The index at which the context sensitivity was\n  /// identified during full-context prediction\n  ContextSensitivityInfo(int decision, ATNConfigSet configs, TokenStream input,\n      int startIndex, int stopIndex)\n      : super(decision, configs, input, startIndex, stopIndex, true);\n}\n\n/// This is the base class for gathering detailed information about prediction\n/// events which occur during parsing.\n///\n/// Note that we could record the parser call stack at the time this event\n/// occurred but in the presence of left recursive rules, the stack is kind of\n/// meaningless. It's better to look at the individual configurations for their\n/// individual stacks. Of course that is a [PredictionContext] object\n/// not a parse tree node and so it does not have information about the extent\n/// (start...stop) of the various subtrees. Examining the stack tops of all\n/// configurations provide the return states for the rule invocations.\n/// From there you can get the enclosing rule.\n///\n/// @since 4.3\nclass DecisionEventInfo {\n  /// The invoked decision number which this event is related to.\n  ///\n  /// @see ATN#decisionToState\n  final int decision;\n\n  /// The configuration set containing additional information relevant to the\n  /// prediction state when the current event occurred, or null if no\n  /// additional information is relevant or available.\n  final ATNConfigSet? configs;\n\n  /// The input token stream which is being parsed.\n  final TokenStream input;\n\n  /// The token index in the input stream at which the current prediction was\n  /// originally invoked.\n  final int startIndex;\n\n  /// The token index in the input stream at which the current event occurred.\n  final int stopIndex;\n\n  /// [true] if the current event occurred during LL prediction;\n  /// otherwise, [false] if the input occurred during SLL prediction.\n  final bool fullCtx;\n\n  DecisionEventInfo(\n    this.decision,\n    this.configs,\n    this.input,\n    this.startIndex,\n    this.stopIndex,\n    this.fullCtx,\n  );\n}\n\n/// This class contains profiling gathered for a particular decision.\n///\n/// <p>\n/// Parsing performance in ANTLR 4 is heavily influenced by both static factors\n/// (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the\n/// choice of input and the state of the DFA cache at the time profiling\n/// operations are started). For best results, gather and use aggregate\n/// statistics from a large sample of inputs representing the inputs expected in\n/// production before using the results to make changes in the grammar.</p>\n///\n/// @since 4.3\nclass DecisionInfo {\n  /// The decision number, which is an index into {@link ATN#decisionToState}.\n  final int decision;\n\n  /// The total number of times {@link ParserATNSimulator#adaptivePredict} was\n  /// invoked for this decision.\n  int invocations = 0;\n\n  /// The total time spent in {@link ParserATNSimulator#adaptivePredict} for\n  /// this decision, in nanoseconds.\n  ///\n  /// <p>\n  /// The value of this field contains the sum of differential results obtained\n  /// by {@link System#nanoTime()}, and is not adjusted to compensate for JIT\n  /// and/or garbage collection overhead. For best accuracy, use a modern JVM\n  /// implementation that provides precise results from\n  /// {@link System#nanoTime()}, and perform profiling in a separate process\n  /// which is warmed up by parsing the input prior to profiling. If desired,\n  /// call {@link ATNSimulator#clearDFA} to reset the DFA cache to its initial\n  /// state before starting the profiling measurement pass.</p>\n  int timeInPrediction = 0;\n\n  /// The sum of the lookahead required for SLL prediction for this decision.\n  /// Note that SLL prediction is used before LL prediction for performance\n  /// reasons even when {@link PredictionMode#LL} or\n  /// {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used.\n  int SLL_TotalLook = 0;\n\n  /// Gets the minimum lookahead required for any single SLL prediction to\n  /// complete for this decision, by reaching a unique prediction, reaching an\n  /// SLL conflict state, or encountering a syntax error.\n  int SLL_MinLook = 0;\n\n  /// Gets the maximum lookahead required for any single SLL prediction to\n  /// complete for this decision, by reaching a unique prediction, reaching an\n  /// SLL conflict state, or encountering a syntax error.\n  int SLL_MaxLook = 0;\n\n  /// Gets the [LookaheadEventInfo] associated with the event where the\n  /// {@link #SLL_MaxLook} value was set.\n  LookaheadEventInfo? SLL_MaxLookEvent;\n\n  /// The sum of the lookahead required for LL prediction for this decision.\n  /// Note that LL prediction is only used when SLL prediction reaches a\n  /// conflict state.\n  int LL_TotalLook = 0;\n\n  /// Gets the minimum lookahead required for any single LL prediction to\n  /// complete for this decision. An LL prediction completes when the algorithm\n  /// reaches a unique prediction, a conflict state (for\n  /// {@link PredictionMode#LL}, an ambiguity state (for\n  /// {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error.\n  int LL_MinLook = 0;\n\n  /// Gets the maximum lookahead required for any single LL prediction to\n  /// complete for this decision. An LL prediction completes when the algorithm\n  /// reaches a unique prediction, a conflict state (for\n  /// {@link PredictionMode#LL}, an ambiguity state (for\n  /// {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error.\n  int LL_MaxLook = 0;\n\n  /// Gets the [LookaheadEventInfo] associated with the event where the\n  /// {@link #LL_MaxLook} value was set.\n  LookaheadEventInfo? LL_MaxLookEvent;\n\n  /// A collection of [ContextSensitivityInfo] instances describing the\n  /// context sensitivities encountered during LL prediction for this decision.\n  ///\n  /// @see ContextSensitivityInfo\n  final List<ContextSensitivityInfo> contextSensitivities = [];\n\n  /// A collection of [ErrorInfo] instances describing the parse errors\n  /// identified during calls to {@link ParserATNSimulator#adaptivePredict} for\n  /// this decision.\n  ///\n  /// @see ErrorInfo\n  final List<ErrorInfo> errors = [];\n\n  /// A collection of [AmbiguityInfo] instances describing the\n  /// ambiguities encountered during LL prediction for this decision.\n  ///\n  /// @see AmbiguityInfo\n  final List<AmbiguityInfo> ambiguities = [];\n\n  /// A collection of [PredicateEvalInfo] instances describing the\n  /// results of evaluating individual predicates during prediction for this\n  /// decision.\n  ///\n  /// @see PredicateEvalInfo\n  final List<PredicateEvalInfo> predicateEvals = [];\n\n  /// The total number of ATN transitions required during SLL prediction for\n  /// this decision. An ATN transition is determined by the number of times the\n  /// DFA does not contain an edge that is required for prediction, resulting\n  /// in on-the-fly computation of that edge.\n  ///\n  /// <p>\n  /// If DFA caching of SLL transitions is employed by the implementation, ATN\n  /// computation may cache the computed edge for efficient lookup during\n  /// future parsing of this decision. Otherwise, the SLL parsing algorithm\n  /// will use ATN transitions exclusively.</p>\n  ///\n  /// @see #SLL_ATNTransitions\n  /// @see ParserATNSimulator#computeTargetState\n  /// @see LexerATNSimulator#computeTargetState\n  int SLL_ATNTransitions = 0;\n\n  /// The total number of DFA transitions required during SLL prediction for\n  /// this decision.\n  ///\n  /// <p>If the ATN simulator implementation does not use DFA caching for SLL\n  /// transitions, this value will be 0.</p>\n  ///\n  /// @see ParserATNSimulator#getExistingTargetState\n  /// @see LexerATNSimulator#getExistingTargetState\n  int SLL_DFATransitions = 0;\n\n  /// Gets the total number of times SLL prediction completed in a conflict\n  /// state, resulting in fallback to LL prediction.\n  ///\n  /// <p>Note that this value is not related to whether or not\n  /// {@link PredictionMode#SLL} may be used successfully with a particular\n  /// grammar. If the ambiguity resolution algorithm applied to the SLL\n  /// conflicts for this decision produce the same result as LL prediction for\n  /// this decision, {@link PredictionMode#SLL} would produce the same overall\n  /// parsing result as {@link PredictionMode#LL}.</p>\n  int LL_Fallback = 0;\n\n  /// The total number of ATN transitions required during LL prediction for\n  /// this decision. An ATN transition is determined by the number of times the\n  /// DFA does not contain an edge that is required for prediction, resulting\n  /// in on-the-fly computation of that edge.\n  ///\n  /// <p>\n  /// If DFA caching of LL transitions is employed by the implementation, ATN\n  /// computation may cache the computed edge for efficient lookup during\n  /// future parsing of this decision. Otherwise, the LL parsing algorithm will\n  /// use ATN transitions exclusively.</p>\n  ///\n  /// @see #LL_DFATransitions\n  /// @see ParserATNSimulator#computeTargetState\n  /// @see LexerATNSimulator#computeTargetState\n  int LL_ATNTransitions = 0;\n\n  /// The total number of DFA transitions required during LL prediction for\n  /// this decision.\n  ///\n  /// <p>If the ATN simulator implementation does not use DFA caching for LL\n  /// transitions, this value will be 0.</p>\n  ///\n  /// @see ParserATNSimulator#getExistingTargetState\n  /// @see LexerATNSimulator#getExistingTargetState\n  int LL_DFATransitions = 0;\n\n  /// Constructs a new instance of the [DecisionInfo] class to contain\n  /// statistics for a particular decision.\n  ///\n  /// @param decision The decision number\n  DecisionInfo(this.decision);\n\n  @override\n  String toString() {\n    return '{'\n        'decision=$decision'\n        ', contextSensitivities=${contextSensitivities.length}'\n        ', errors=${errors.length}'\n        ', ambiguities=${ambiguities.length}'\n        ', SLL_lookahead=$SLL_TotalLook'\n        ', SLL_ATNTransitions=$SLL_ATNTransitions, SLL_DFATransitions=$SLL_DFATransitions, LL_Fallback=$LL_Fallback, LL_lookahead=$LL_TotalLook, LL_ATNTransitions=$LL_ATNTransitions}';\n  }\n}\n\n/// This class represents profiling event information for an ambiguity.\n/// Ambiguities are decisions where a particular input resulted in an SLL\n/// conflict, followed by LL prediction also reaching a conflict state\n/// (indicating a true ambiguity in the grammar).\n///\n/// <p>\n/// This event may be reported during SLL prediction in cases where the\n/// conflicting SLL configuration set provides sufficient information to\n/// determine that the SLL conflict is truly an ambiguity. For example, if none\n/// of the ATN configurations in the conflicting SLL configuration set have\n/// traversed a global follow transition (i.e.\n/// {@link ATNConfig#reachesIntoOuterContext} is 0 for all configurations), then\n/// the result of SLL prediction for that input is known to be equivalent to the\n/// result of LL prediction for that input.</p>\n///\n/// <p>\n/// In some cases, the minimum represented alternative in the conflicting LL\n/// configuration set is not equal to the minimum represented alternative in the\n/// conflicting SLL configuration set. Grammars and inputs which result in this\n/// scenario are unable to use {@link PredictionMode#SLL}, which in turn means\n/// they cannot use the two-stage parsing strategy to improve parsing performance\n/// for that input.</p>\n///\n/// @see ParserATNSimulator#reportAmbiguity\n/// @see ANTLRErrorListener#reportAmbiguity\n///\n/// @since 4.3\nclass AmbiguityInfo extends DecisionEventInfo {\n  /// The set of alternative numbers for this decision event that lead to a valid parse. */\n  BitSet? ambigAlts;\n\n  /// Constructs a new instance of the [AmbiguityInfo] class with the\n  /// specified detailed ambiguity information.\n  ///\n  /// @param decision The decision number\n  /// @param configs The final configuration set identifying the ambiguous\n  /// alternatives for the current input\n  /// @param ambigAlts The set of alternatives in the decision that lead to a valid parse.\n  ///                  The predicted alt is the min(ambigAlts)\n  /// @param input The input token stream\n  /// @param startIndex The start index for the current prediction\n  /// @param stopIndex The index at which the ambiguity was identified during\n  /// prediction\n  /// @param fullCtx [true] if the ambiguity was identified during LL\n  /// prediction; otherwise, [false] if the ambiguity was identified\n  /// during SLL prediction\n  AmbiguityInfo(int decision, ATNConfigSet configs, this.ambigAlts,\n      TokenStream input, int startIndex, int stopIndex, bool fullCtx)\n      : super(decision, configs, input, startIndex, stopIndex, fullCtx);\n}\n\n/// This class represents profiling event information for a syntax error\n/// identified during prediction. Syntax errors occur when the prediction\n/// algorithm is unable to identify an alternative which would lead to a\n/// successful parse.\n///\n/// @see Parser#notifyErrorListeners(Token, String, RecognitionException)\n/// @see ANTLRErrorListener#syntaxError\n///\n/// @since 4.3\nclass ErrorInfo extends DecisionEventInfo {\n  /// Constructs a new instance of the [ErrorInfo] class with the\n  /// specified detailed syntax error information.\n  ///\n  /// @param decision The decision number\n  /// @param configs The final configuration set reached during prediction\n  /// prior to reaching the {@link ATNSimulator#ERROR} state\n  /// @param input The input token stream\n  /// @param startIndex The start index for the current prediction\n  /// @param stopIndex The index at which the syntax error was identified\n  /// @param fullCtx [true] if the syntax error was identified during LL\n  /// prediction; otherwise, [false] if the syntax error was identified\n  /// during SLL prediction\n  ErrorInfo(\n    int decision,\n    ATNConfigSet? configs,\n    TokenStream input,\n    int startIndex,\n    int stopIndex,\n    bool fullCtx,\n  ) : super(decision, configs, input, startIndex, stopIndex, fullCtx);\n}\n\n/// This class represents profiling event information for tracking the lookahead\n/// depth required in order to make a prediction.\n///\n/// @since 4.3\nclass LookaheadEventInfo extends DecisionEventInfo {\n  /// The alternative chosen by adaptivePredict(), not necessarily\n  ///  the outermost alt shown for a rule; left-recursive rules have\n  ///  user-level alts that differ from the rewritten rule with a (...) block\n  ///  and a (..)* loop.\n  int predictedAlt;\n\n  /// Constructs a new instance of the [LookaheadEventInfo] class with\n  /// the specified detailed lookahead information.\n  ///\n  /// @param decision The decision number\n  /// @param configs The final configuration set containing the necessary\n  /// information to determine the result of a prediction, or null if\n  /// the final configuration set is not available\n  /// @param input The input token stream\n  /// @param startIndex The start index for the current prediction\n  /// @param stopIndex The index at which the prediction was finally made\n  /// @param fullCtx [true] if the current lookahead is part of an LL\n  /// prediction; otherwise, [false] if the current lookahead is part of\n  /// an SLL prediction\n  LookaheadEventInfo(\n    int decision,\n    ATNConfigSet? configs,\n    this.predictedAlt,\n    TokenStream input,\n    int startIndex,\n    int stopIndex,\n    bool fullCtx,\n  ) : super(decision, configs, input, startIndex, stopIndex, fullCtx);\n}\n\n/// This class represents profiling event information for semantic predicate\n/// evaluations which occur during prediction.\n///\n/// @see ParserATNSimulator#evalSemanticContext\n///\n/// @since 4.3\nclass PredicateEvalInfo extends DecisionEventInfo {\n  /// The semantic context which was evaluated.\n  final SemanticContext semctx;\n\n  /// The alternative number for the decision which is guarded by the semantic\n  /// context {@link #semctx}. Note that other ATN\n  /// configurations may predict the same alternative which are guarded by\n  /// other semantic contexts and/or {@link SemanticContext#NONE}.\n  final int predictedAlt;\n\n  /// The result of evaluating the semantic context {@link #semctx}.\n  final bool evalResult;\n\n  /// Constructs a new instance of the [PredicateEvalInfo] class with the\n  /// specified detailed predicate evaluation information.\n  ///\n  /// @param decision The decision number\n  /// @param input The input token stream\n  /// @param startIndex The start index for the current prediction\n  /// @param stopIndex The index at which the predicate evaluation was\n  /// triggered. Note that the input stream may be reset to other positions for\n  /// the actual evaluation of individual predicates.\n  /// @param semctx The semantic context which was evaluated\n  /// @param evalResult The results of evaluating the semantic context\n  /// @param predictedAlt The alternative number for the decision which is\n  /// guarded by the semantic context [semctx]. See {@link #predictedAlt}\n  /// for more information.\n  /// @param fullCtx [true] if the semantic context was\n  /// evaluated during LL prediction; otherwise, [false] if the semantic\n  /// context was evaluated during SLL prediction\n  ///\n  /// @see ParserATNSimulator#evalSemanticContext(SemanticContext, ParserRuleContext, int, boolean)\n  /// @see SemanticContext#eval(Recognizer, RuleContext)\n  PredicateEvalInfo(\n      int decision,\n      TokenStream input,\n      int startIndex,\n      int stopIndex,\n      this.semctx,\n      this.evalResult,\n      this.predictedAlt,\n      bool fullCtx)\n      : super(decision, ATNConfigSet(), input, startIndex, stopIndex, fullCtx);\n}\n\n/// This class provides access to specific and aggregate statistics gathered\n/// during profiling of a parser.\n///\n/// @since 4.3\nclass ParseInfo {\n  final ProfilingATNSimulator atnSimulator;\n\n  ParseInfo(this.atnSimulator);\n\n  /// Gets an array of [DecisionInfo] instances containing the profiling\n  /// information gathered for each decision in the ATN.\n  ///\n  /// @return An array of [DecisionInfo] instances, indexed by decision\n  /// number.\n  List<DecisionInfo> get decisionInfo {\n    return atnSimulator.decisionInfo;\n  }\n\n  /// Gets the decision numbers for decisions that required one or more\n  /// full-context predictions during parsing. These are decisions for which\n  /// {@link DecisionInfo#LL_Fallback} is non-zero.\n  ///\n  /// @return A list of decision numbers which required one or more\n  /// full-context predictions during parsing.\n  List<int> get llDecisions {\n    final decisions = atnSimulator.decisionInfo;\n    final LL = <int>[];\n    for (var i = 0; i < decisions.length; i++) {\n      final fallBack = decisions[i].LL_Fallback;\n      if (fallBack > 0) LL.add(i);\n    }\n    return LL;\n  }\n\n  /// Gets the total time spent during prediction across all decisions made\n  /// during parsing. This value is the sum of\n  /// {@link DecisionInfo#timeInPrediction} for all decisions.\n  int get totalTimeInPrediction {\n    final decisions = atnSimulator.decisionInfo;\n    var t = 0;\n    for (var i = 0; i < decisions.length; i++) {\n      t += decisions[i].timeInPrediction;\n    }\n    return t;\n  }\n\n  /// Gets the total number of SLL lookahead operations across all decisions\n  /// made during parsing. This value is the sum of\n  /// {@link DecisionInfo#SLL_TotalLook} for all decisions.\n  int get totalSLLLookaheadOps {\n    final decisions = atnSimulator.decisionInfo;\n    var k = 0;\n    for (var i = 0; i < decisions.length; i++) {\n      k += decisions[i].SLL_TotalLook;\n    }\n    return k;\n  }\n\n  /// Gets the total number of LL lookahead operations across all decisions\n  /// made during parsing. This value is the sum of\n  /// {@link DecisionInfo#LL_TotalLook} for all decisions.\n  int get totalLLLookaheadOps {\n    final decisions = atnSimulator.decisionInfo;\n    var k = 0;\n    for (var i = 0; i < decisions.length; i++) {\n      k += decisions[i].LL_TotalLook;\n    }\n    return k;\n  }\n\n  /// Gets the total number of ATN lookahead operations for SLL prediction\n  /// across all decisions made during parsing.\n  int get totalSLLATNLookaheadOps {\n    final decisions = atnSimulator.decisionInfo;\n    var k = 0;\n    for (var i = 0; i < decisions.length; i++) {\n      k += decisions[i].SLL_ATNTransitions;\n    }\n    return k;\n  }\n\n  /// Gets the total number of ATN lookahead operations for LL prediction\n  /// across all decisions made during parsing.\n  int get totalLLATNLookaheadOps {\n    final decisions = atnSimulator.decisionInfo;\n    var k = 0;\n    for (var i = 0; i < decisions.length; i++) {\n      k += decisions[i].LL_ATNTransitions;\n    }\n    return k;\n  }\n\n  /// Gets the total number of ATN lookahead operations for SLL and LL\n  /// prediction across all decisions made during parsing.\n  ///\n  /// <p>\n  /// This value is the sum of {@link #getTotalSLLATNLookaheadOps} and\n  /// {@link #getTotalLLATNLookaheadOps}.</p>\n  int get totalATNLookaheadOps {\n    final decisions = atnSimulator.decisionInfo;\n    var k = 0;\n    for (var i = 0; i < decisions.length; i++) {\n      k += decisions[i].SLL_ATNTransitions;\n      k += decisions[i].LL_ATNTransitions;\n    }\n    return k;\n  }\n\n  /// Gets the total number of DFA states stored in the DFA cache for all\n  /// decisions in the ATN.\n  int get dfaSize {\n    var n = 0;\n    final decisionToDFA = atnSimulator.decisionToDFA;\n    for (var i = 0; i < decisionToDFA.length; i++) {\n      n += getDFASizeAt(i);\n    }\n    return n;\n  }\n\n  /// Gets the total number of DFA states stored in the DFA cache for a\n  /// particular decision.\n  int getDFASizeAt(int decision) {\n    final decisionToDFA = atnSimulator.decisionToDFA[decision];\n    return decisionToDFA.states.length;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/lexer_action.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../lexer.dart';\nimport '../../util/murmur_hash.dart';\n\n/// Represents the serialization type of a [LexerAction].\n///\n/// @since 4.2\nenum LexerActionType {\n  /// The type of a [LexerChannelAction] action.\n  CHANNEL,\n\n  /// The type of a [LexerCustomAction] action.\n  CUSTOM,\n\n  /// The type of a [LexerModeAction] action.\n  MODE,\n\n  /// The type of a [LexerMoreAction] action.\n  MORE,\n\n  /// The type of a [LexerPopModeAction] action.\n  POP_MODE,\n\n  /// The type of a [LexerPushModeAction] action.\n  PUSH_MODE,\n\n  /// The type of a [LexerSkipAction] action.\n  SKIP,\n\n  /// The type of a [LexerTypeAction] action.\n  TYPE,\n}\n\n/// Represents a single action which can be executed following the successful\n/// match of a lexer rule. Lexer actions are used for both embedded action syntax\n/// and ANTLR 4's new lexer command syntax.\n///\n/// @since 4.2\nabstract class LexerAction {\n  /// Gets the serialization type of the lexer action.\n  ///\n  /// @return The serialization type of the lexer action.\n  LexerActionType get actionType;\n\n  /// Gets whether the lexer action is position-dependent. Position-dependent\n  /// actions may have different semantics depending on the [CharStream]\n  /// index at the time the action is executed.\n  ///\n  /// <p>Many lexer commands, including [type], [skip], and\n  /// [more], do not check the input index during their execution.\n  /// Actions like this are position-independent, and may be stored more\n  /// efficiently as part of the {@link LexerATNConfig#lexerActionExecutor}.</p>\n  ///\n  /// @return [true] if the lexer action semantics can be affected by the\n  /// position of the input [CharStream] at the time it is executed;\n  /// otherwise, [false].\n  bool get isPositionDependent;\n\n  /// Execute the lexer action in the context of the specified [Lexer].\n  ///\n  /// <p>For position-dependent actions, the input stream must already be\n  /// positioned correctly prior to calling this method.</p>\n  ///\n  /// @param lexer The lexer instance.\n  void execute(Lexer lexer);\n}\n\n/// Implements the [channel] lexer action by calling\n/// {@link Lexer#setChannel} with the assigned channel.\n///\n/// @since 4.2\nclass LexerChannelAction implements LexerAction {\n  /// Gets the channel to use for the [Token] created by the lexer.\n  ///\n  /// @return The channel to use for the [Token] created by the lexer.\n  final int channel;\n\n  /// Constructs a new [channel] action with the specified channel value.\n  /// @param channel The channel value to pass to {@link Lexer#setChannel}.\n  LexerChannelAction(this.channel);\n\n  @override\n  LexerActionType get actionType => LexerActionType.CHANNEL;\n\n  @override\n  bool get isPositionDependent => false;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This action is implemented by calling {@link Lexer#setChannel} with the\n  /// value provided by {@link #getChannel}.</p>\n  @override\n  void execute(Lexer lexer) {\n    lexer.channel = channel;\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    hash = MurmurHash.update(hash, channel);\n    return MurmurHash.finish(hash, 2);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    if (identical(obj, this)) {\n      return true;\n    } else if (obj is LexerChannelAction) {\n      return channel == obj.channel;\n    }\n\n    return false;\n  }\n\n  @override\n  String toString() {\n    return 'channel($channel)';\n  }\n}\n\n/// Executes a custom lexer action by calling {@link Recognizer#action} with the\n/// rule and action indexes assigned to the custom action. The implementation of\n/// a custom action is added to the generated code for the lexer in an override\n/// of {@link Recognizer#action} when the grammar is compiled.\n///\n/// <p>This class may represent embedded actions created with the <code>{...}</code>\n/// syntax in ANTLR 4, as well as actions created for lexer commands where the\n/// command argument could not be evaluated when the grammar was compiled.</p>\n///\n/// @since 4.2\nclass LexerCustomAction implements LexerAction {\n  /// Gets the rule index to use for calls to {@link Recognizer#action}.\n  ///\n  /// @return The rule index for the custom action.\n  final int ruleIndex;\n\n  /// Gets the action index to use for calls to {@link Recognizer#action}.\n  ///\n  /// @return The action index for the custom action.\n  final int actionIndex;\n\n  /// Constructs a custom lexer action with the specified rule and action\n  /// indexes.\n  ///\n  /// @param ruleIndex The rule index to use for calls to\n  /// {@link Recognizer#action}.\n  /// @param actionIndex The action index to use for calls to\n  /// {@link Recognizer#action}.\n  LexerCustomAction(this.ruleIndex, this.actionIndex);\n\n  /// {@inheritDoc}\n  ///\n  /// @return This method returns {@link LexerActionType#CUSTOM}.\n\n  @override\n  LexerActionType get actionType => LexerActionType.CUSTOM;\n\n  /// Gets whether the lexer action is position-dependent. Position-dependent\n  /// actions may have different semantics depending on the [CharStream]\n  /// index at the time the action is executed.\n  ///\n  /// <p>Custom actions are position-dependent since they may represent a\n  /// user-defined embedded action which makes calls to methods like\n  /// {@link Lexer#getText}.</p>\n  ///\n  /// @return This method returns [true].\n\n  @override\n  bool get isPositionDependent => true;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>Custom actions are implemented by calling {@link Lexer#action} with the\n  /// appropriate rule and action indexes.</p>\n\n  @override\n  void execute(Lexer lexer) {\n    lexer.action(null, ruleIndex, actionIndex);\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    hash = MurmurHash.update(hash, ruleIndex);\n    hash = MurmurHash.update(hash, actionIndex);\n    return MurmurHash.finish(hash, 3);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    if (identical(obj, this)) {\n      return true;\n    } else if (obj is LexerCustomAction) {\n      return ruleIndex == obj.ruleIndex && actionIndex == obj.actionIndex;\n    }\n    return false;\n  }\n}\n\n/// Implements the [mode] lexer action by calling {@link Lexer#mode} with\n/// the assigned mode.\n///\n/// @since 4.2\nclass LexerModeAction implements LexerAction {\n  /// Get the lexer mode this action should transition the lexer to.\n  ///\n  /// @return The lexer mode for this [mode] command.\n  final int mode;\n\n  /// Constructs a new [mode] action with the specified mode value.\n  /// @param mode The mode value to pass to {@link Lexer#mode}.\n  LexerModeAction(this.mode);\n\n  /// {@inheritDoc}\n  /// @return This method returns {@link LexerActionType#MODE}.\n\n  @override\n  LexerActionType get actionType => LexerActionType.MODE;\n\n  /// {@inheritDoc}\n  /// @return This method returns [false].\n\n  @override\n  bool get isPositionDependent => false;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This action is implemented by calling {@link Lexer#mode} with the\n  /// value provided by {@link #getMode}.</p>\n\n  @override\n  void execute(Lexer lexer) {\n    lexer.mode(mode);\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    hash = MurmurHash.update(hash, mode);\n    return MurmurHash.finish(hash, 2);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    if (identical(obj, this)) {\n      return true;\n    } else if (obj is LexerModeAction) {\n      return mode == obj.mode;\n    }\n    return false;\n  }\n\n  @override\n  String toString() {\n    return 'mode($mode)';\n  }\n}\n\n/// Implements the [more] lexer action by calling {@link Lexer#more}.\n///\n/// <p>The [more] command does not have any parameters, so this action is\n/// implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\n///\n/// @since 4.2\nclass LexerMoreAction implements LexerAction {\n  /// Provides a singleton instance of this parameterless lexer action.\n  static final LexerMoreAction INSTANCE = LexerMoreAction();\n\n  /// {@inheritDoc}\n  /// @return This method returns {@link LexerActionType#MORE}.\n  @override\n  LexerActionType get actionType => LexerActionType.MORE;\n\n  /// {@inheritDoc}\n  /// @return This method returns [false].\n\n  @override\n  bool get isPositionDependent => false;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This action is implemented by calling {@link Lexer#more}.</p>\n\n  @override\n  void execute(Lexer lexer) {\n    lexer.more();\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    return MurmurHash.finish(hash, 1);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    return identical(obj, this);\n  }\n\n  @override\n  String toString() {\n    return 'more';\n  }\n}\n\n/// Implements the [popMode] lexer action by calling {@link Lexer#popMode}.\n///\n/// <p>The [popMode] command does not have any parameters, so this action is\n/// implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\n///\n/// @since 4.2\nclass LexerPopModeAction implements LexerAction {\n  /// Provides a singleton instance of this parameterless lexer action.\n  static final LexerPopModeAction INSTANCE = LexerPopModeAction();\n\n  /// {@inheritDoc}\n  /// @return This method returns {@link LexerActionType#POP_MODE}.\n\n  @override\n  LexerActionType get actionType => LexerActionType.POP_MODE;\n\n  /// {@inheritDoc}\n  /// @return This method returns [false].\n\n  @override\n  bool get isPositionDependent => false;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This action is implemented by calling {@link Lexer#popMode}.</p>\n\n  @override\n  void execute(Lexer lexer) {\n    lexer.popMode();\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    return MurmurHash.finish(hash, 1);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    return identical(obj, this);\n  }\n\n  @override\n  String toString() {\n    return 'popMode';\n  }\n}\n\n/// Implements the [pushMode] lexer action by calling\n/// {@link Lexer#pushMode} with the assigned mode.\n///\n/// @since 4.2\nclass LexerPushModeAction implements LexerAction {\n  /// Get the lexer mode this action should transition the lexer to.\n  ///\n  /// @return The lexer mode for this [pushMode] command.\n  final int mode;\n\n  /// Constructs a new [pushMode] action with the specified mode value.\n  /// @param mode The mode value to pass to {@link Lexer#pushMode}.\n  LexerPushModeAction(this.mode);\n\n  /// {@inheritDoc}\n  /// @return This method returns {@link LexerActionType#PUSH_MODE}.\n\n  @override\n  LexerActionType get actionType => LexerActionType.PUSH_MODE;\n\n  /// {@inheritDoc}\n  /// @return This method returns [false].\n\n  @override\n  bool get isPositionDependent => false;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This action is implemented by calling {@link Lexer#pushMode} with the\n  /// value provided by {@link #getMode}.</p>\n\n  @override\n  void execute(Lexer lexer) {\n    lexer.pushMode(mode);\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    hash = MurmurHash.update(hash, mode);\n    return MurmurHash.finish(hash, 2);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    if (identical(obj, this)) {\n      return true;\n    } else if (obj is LexerPushModeAction) {\n      return mode == obj.mode;\n    }\n    return false;\n  }\n\n  @override\n  String toString() {\n    return 'pushMode($mode)';\n  }\n}\n\n/// Implements the [skip] lexer action by calling {@link Lexer#skip}.\n///\n/// <p>The [skip] command does not have any parameters, so this action is\n/// implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\n///\n/// @since 4.2\nclass LexerSkipAction implements LexerAction {\n  /// Provides a singleton instance of this parameterless lexer action.\n  static final LexerSkipAction INSTANCE = LexerSkipAction();\n\n  /// {@inheritDoc}\n  /// @return This method returns {@link LexerActionType#SKIP}.\n\n  @override\n  LexerActionType get actionType => LexerActionType.SKIP;\n\n  /// {@inheritDoc}\n  /// @return This method returns [false].\n\n  @override\n  bool get isPositionDependent => false;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This action is implemented by calling {@link Lexer#skip}.</p>\n  @override\n  void execute(Lexer lexer) {\n    lexer.skip();\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    return MurmurHash.finish(hash, 1);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    return identical(obj, this);\n  }\n\n  @override\n  String toString() {\n    return 'skip';\n  }\n}\n\n/// Implements the [type] lexer action by calling {@link Lexer#setType}\n/// with the assigned type.\n///\n/// @since 4.2\nclass LexerTypeAction implements LexerAction {\n  /// Gets the type to assign to a token created by the lexer.\n  /// @return The type to assign to a token created by the lexer.\n  final int type;\n\n  /// Constructs a new [type] action with the specified token type value.\n  /// @param type The type to assign to the token using {@link Lexer#setType}.\n  LexerTypeAction(this.type);\n\n  /// {@inheritDoc}\n  /// @return This method returns {@link LexerActionType#TYPE}.\n  @override\n  LexerActionType get actionType => LexerActionType.TYPE;\n\n  /// {@inheritDoc}\n  /// @return This method returns [false].\n\n  @override\n  bool get isPositionDependent => false;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This action is implemented by calling {@link Lexer#setType} with the\n  /// value provided by {@link #getType}.</p>\n\n  @override\n  void execute(Lexer lexer) {\n    lexer.type = type;\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, actionType.index);\n    hash = MurmurHash.update(hash, type);\n    return MurmurHash.finish(hash, 2);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    if (identical(obj, this)) {\n      return true;\n    } else if (obj is LexerTypeAction) {\n      return type == obj.type;\n    }\n    return false;\n  }\n\n  @override\n  String toString() {\n    return 'type($type)';\n  }\n}\n\n/// This implementation of [LexerAction] is used for tracking input offsets\n/// for position-dependent actions within a [LexerActionExecutor].\n///\n/// <p>This action is not serialized as part of the ATN, and is only required for\n/// position-dependent lexer actions which appear at a location other than the\n/// end of a rule. For more information about DFA optimizations employed for\n/// lexer actions, see {@link LexerActionExecutor#append} and\n/// {@link LexerActionExecutor#fixOffsetBeforeMatch}.</p>\n///\n/// @since 4.2\nclass LexerIndexedCustomAction implements LexerAction {\n  /// Gets the location in the input [CharStream] at which the lexer\n  /// action should be executed. The value is interpreted as an offset relative\n  /// to the token start index.\n  ///\n  /// @return The location in the input [CharStream] at which the lexer\n  /// action should be executed.\n  final int offset;\n\n  /// Gets the lexer action to execute.\n  ///\n  /// @return A [LexerAction] object which executes the lexer action.\n  final LexerAction action;\n\n  /// Constructs a new indexed custom action by associating a character offset\n  /// with a [LexerAction].\n  ///\n  /// <p>Note: This class is only required for lexer actions for which\n  /// {@link LexerAction#isPositionDependent} returns [true].</p>\n  ///\n  /// @param offset The offset into the input [CharStream], relative to\n  /// the token start index, at which the specified lexer action should be\n  /// executed.\n  /// @param action The lexer action to execute at a particular offset in the\n  /// input [CharStream].\n  LexerIndexedCustomAction(this.offset, this.action);\n\n  /// {@inheritDoc}\n  ///\n  /// @return This method returns the result of calling {@link #getActionType}\n  /// on the [LexerAction] returned by {@link #getAction}.\n  @override\n  LexerActionType get actionType => action.actionType;\n\n  /// {@inheritDoc}\n  /// @return This method returns [true].\n\n  @override\n  bool get isPositionDependent => true;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This method calls {@link #execute} on the result of {@link #getAction}\n  /// using the provided [lexer].</p>\n\n  @override\n  void execute(Lexer lexer) {\n// assume the input stream position was properly set by the calling code\n    action.execute(lexer);\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, offset);\n    hash = MurmurHash.update(hash, action);\n    return MurmurHash.finish(hash, 2);\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    if (obj == this) {\n      return true;\n    } else if (obj is LexerIndexedCustomAction) {\n      return offset == obj.offset && action == obj.action;\n    }\n    return false;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/lexer_action_executor.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'package:collection/collection.dart';\n\nimport '../../input_stream.dart';\nimport '../../lexer.dart';\nimport '../../util/murmur_hash.dart';\nimport 'lexer_action.dart';\n\n/// Represents an executor for a sequence of lexer actions which traversed during\n/// the matching operation of a lexer rule (token).\n///\n/// <p>The executor tracks position information for position-dependent lexer actions\n/// efficiently, ensuring that actions appearing only at the end of the rule do\n/// not cause bloating of the [DFA] created for the lexer.</p>\n///\n/// @since 4.2\nclass LexerActionExecutor {\n  /// Gets the lexer actions to be executed by this executor.\n  /// @return The lexer actions to be executed by this executor.\n  final List<LexerAction> lexerActions;\n\n  /// Caches the result of {@link #hashCode} since the hash code is an element\n  /// of the performance-critical {@link LexerATNConfig#hashCode} operation.\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    for (var lexerAction in lexerActions) {\n      hash = MurmurHash.update(hash, lexerAction);\n    }\n\n    return MurmurHash.finish(hash, lexerActions.length);\n  }\n\n  /// Constructs an executor for a sequence of [LexerAction] actions.\n  /// @param lexerActions The lexer actions to execute.\n  LexerActionExecutor(this.lexerActions);\n\n  /// Creates a [LexerActionExecutor] which executes the actions for\n  /// the input [lexerActionExecutor] followed by a specified\n  /// [lexerAction].\n  ///\n  /// @param lexerActionExecutor The executor for actions already traversed by\n  /// the lexer while matching a token within a particular\n  /// [LexerATNConfig]. If this is null, the method behaves as\n  /// though it were an empty executor.\n  /// @param lexerAction The lexer action to execute after the actions\n  /// specified in [lexerActionExecutor].\n  ///\n  /// @return A [LexerActionExecutor] for executing the combine actions\n  /// of [lexerActionExecutor] and [lexerAction].\n  static LexerActionExecutor append(\n    LexerActionExecutor? lexerActionExecutor,\n    LexerAction lexerAction,\n  ) {\n    if (lexerActionExecutor == null) {\n      return LexerActionExecutor([lexerAction]);\n    }\n\n    final lexerActions =\n        List<LexerAction>.from(lexerActionExecutor.lexerActions);\n    lexerActions.add(lexerAction);\n    return LexerActionExecutor(lexerActions);\n  }\n\n  /// Creates a [LexerActionExecutor] which encodes the current offset\n  /// for position-dependent lexer actions.\n  ///\n  /// <p>Normally, when the executor encounters lexer actions where\n  /// {@link LexerAction#isPositionDependent} returns [true], it calls\n  /// {@link IntStream#seek} on the input [CharStream] to set the input\n  /// position to the <em>end</em> of the current token. This behavior provides\n  /// for efficient DFA representation of lexer actions which appear at the end\n  /// of a lexer rule, even when the lexer rule matches a variable number of\n  /// characters.</p>\n  ///\n  /// <p>Prior to traversing a match transition in the ATN, the current offset\n  /// from the token start index is assigned to all position-dependent lexer\n  /// actions which have not already been assigned a fixed offset. By storing\n  /// the offsets relative to the token start index, the DFA representation of\n  /// lexer actions which appear in the middle of tokens remains efficient due\n  /// to sharing among tokens of the same length, regardless of their absolute\n  /// position in the input stream.</p>\n  ///\n  /// <p>If the current executor already has offsets assigned to all\n  /// position-dependent lexer actions, the method returns [this].</p>\n  ///\n  /// @param offset The current offset to assign to all position-dependent\n  /// lexer actions which do not already have offsets assigned.\n  ///\n  /// @return A [LexerActionExecutor] which stores input stream offsets\n  /// for all position-dependent lexer actions.\n  LexerActionExecutor fixOffsetBeforeMatch(int offset) {\n    List<LexerAction>? updatedLexerActions;\n    for (var i = 0; i < lexerActions.length; i++) {\n      if (lexerActions[i].isPositionDependent &&\n          lexerActions[i] is! LexerIndexedCustomAction) {\n        updatedLexerActions ??= List.from(lexerActions);\n\n        updatedLexerActions[i] =\n            LexerIndexedCustomAction(offset, lexerActions[i]);\n      }\n    }\n\n    if (updatedLexerActions == null) {\n      return this;\n    }\n\n    return LexerActionExecutor(updatedLexerActions);\n  }\n\n  /// Execute the actions encapsulated by this executor within the context of a\n  /// particular [Lexer].\n  ///\n  /// <p>This method calls {@link IntStream#seek} to set the position of the\n  /// [input] [CharStream] prior to calling\n  /// {@link LexerAction#execute} on a position-dependent action. Before the\n  /// method returns, the input position will be restored to the same position\n  /// it was in when the method was invoked.</p>\n  ///\n  /// @param lexer The lexer instance.\n  /// @param input The input stream which is the source for the current token.\n  /// When this method is called, the current {@link IntStream#index} for\n  /// [input] should be the start of the following token, i.e. 1\n  /// character past the end of the current token.\n  /// @param startIndex The token start index. This value may be passed to\n  /// {@link IntStream#seek} to set the [input] position to the beginning\n  /// of the token.\n  void execute(Lexer lexer, CharStream input, int startIndex) {\n    var requiresSeek = false;\n    final stopIndex = input.index;\n    try {\n      for (var lexerAction in lexerActions) {\n        if (lexerAction is LexerIndexedCustomAction) {\n          final offset = lexerAction.offset;\n          input.seek(startIndex + offset);\n          lexerAction = lexerAction.action;\n          requiresSeek = (startIndex + offset) != stopIndex;\n        } else if (lexerAction.isPositionDependent) {\n          input.seek(stopIndex);\n          requiresSeek = false;\n        }\n\n        lexerAction.execute(lexer);\n      }\n    } finally {\n      if (requiresSeek) {\n        input.seek(stopIndex);\n      }\n    }\n  }\n\n  @override\n  bool operator ==(Object other) {\n    if (identical(other, this)) {\n      return true;\n    } else if (other is! LexerActionExecutor) {\n      return false;\n    }\n\n    return hashCode == other.hashCode &&\n        ListEquality().equals(\n          lexerActions,\n          other.lexerActions,\n        );\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/lexer_atn_simulator.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:developer';\n\nimport 'package:logging/logging.dart';\n\nimport '../../dfa/dfa.dart';\nimport '../../error/error.dart';\nimport '../../input_stream.dart';\nimport '../../interval_set.dart';\nimport '../../lexer.dart';\nimport '../../prediction_context.dart';\nimport '../../token.dart';\nimport 'atn.dart';\nimport 'atn_config.dart';\nimport 'atn_config_set.dart';\nimport 'atn_simulator.dart';\nimport 'atn_state.dart';\nimport 'lexer_action_executor.dart';\nimport 'transition.dart';\n\n/// When we hit an accept state in either the DFA or the ATN, we\n///  have to notify the character stream to start buffering characters\n///  via {@link IntStream#mark} and record the current state. The current sim state\n///  includes the current index into the input, the current line,\n///  and current character position in that line. Note that the Lexer is\n///  tracking the starting line and characterization of the token. These\n///  variables track the \"state\" of the simulator when it hits an accept state.\n///\n///  <p>We track these variables separately for the DFA and ATN simulation\n///  because the DFA simulation often has to fail over to the ATN\n///  simulation. If the ATN simulation fails, we need the DFA to fall\n///  back to its previously accepted state, if any. If the ATN succeeds,\n///  then the ATN does the accept and the DFA simulator that invoked it\n///  can simply return the predicted token type.</p>\nclass SimState {\n  int index = -1;\n  int line = 0;\n  int charPos = -1;\n\n  DFAState? dfaState;\n\n  void reset() {\n    index = -1;\n    line = 0;\n    charPos = -1;\n    dfaState = null;\n  }\n}\n\n/// \"dup\" of ParserInterpreter */\nclass LexerATNSimulator extends ATNSimulator {\n  static const bool debug = bool.fromEnvironment(\n    'ANTLR_LEXER_DEBUG',\n    defaultValue: false,\n  );\n  static const bool dfa_debug = bool.fromEnvironment(\n    'ANTLR_LEXER_DFA_DEBUG',\n    defaultValue: false,\n  );\n\n  static const int MIN_DFA_EDGE = 0;\n  static const int MAX_DFA_EDGE = 127; // forces unicode to stay in ATN\n\n  final Lexer recog;\n\n  /// The current token's starting index into the character stream.\n  ///  Shared across DFA to ATN simulation in case the ATN fails and the\n  ///  DFA did not have a previous accept state. In this case, we use the\n  ///  ATN-generated exception object.\n  int startIndex = -1;\n\n  /// line number 1..n within the input */\n  int line = 1;\n\n  /// The index of the character relative to the beginning of the line 0..n-1 */\n  int charPositionInLine = 0;\n\n  List<DFA> decisionToDFA;\n  int mode = Lexer.DEFAULT_MODE;\n\n  /// Used during DFA/ATN exec to record the most recent accept configuration info */\n\n  final SimState prevAccept = SimState();\n\n  LexerATNSimulator(\n    ATN atn,\n    this.decisionToDFA,\n    PredictionContextCache sharedContextCache, {\n    required this.recog,\n  }) : super(atn, sharedContextCache);\n\n  void copyState(LexerATNSimulator simulator) {\n    charPositionInLine = simulator.charPositionInLine;\n    line = simulator.line;\n    mode = simulator.mode;\n    startIndex = simulator.startIndex;\n  }\n\n  int match(CharStream input, int mode) {\n    this.mode = mode;\n    final mark = input.mark();\n    try {\n      startIndex = input.index;\n      prevAccept.reset();\n      final dfa = decisionToDFA[mode];\n      if (dfa.s0 == null) {\n        return matchATN(input);\n      } else {\n        return execATN(input, dfa.s0!);\n      }\n    } finally {\n      input.release(mark);\n    }\n  }\n\n  @override\n  void reset() {\n    prevAccept.reset();\n    startIndex = -1;\n    line = 1;\n    charPositionInLine = 0;\n    mode = Lexer.DEFAULT_MODE;\n  }\n\n  @override\n  void clearDFA() {\n    for (var d = 0; d < decisionToDFA.length; d++) {\n      decisionToDFA[d] = DFA(atn.getDecisionState(d)!, d);\n    }\n  }\n\n  int matchATN(CharStream input) {\n    ATNState startState = atn.modeToStartState[mode];\n\n    if (debug) {\n      log('matchATN mode $mode start: $startState\\n', level: Level.FINE.value);\n    }\n\n    final old_mode = mode;\n\n    final s0_closure = computeStartState(input, startState);\n    final suppressEdge = s0_closure.hasSemanticContext;\n    s0_closure.hasSemanticContext = false;\n\n    final next = addDFAState(s0_closure);\n    if (!suppressEdge) {\n      decisionToDFA[mode].s0 = next;\n    }\n\n    final predict = execATN(input, next);\n\n    if (debug) {\n      log('DFA after matchATN: ${decisionToDFA[old_mode].toLexerString()}\\n',\n          level: Level.FINE.value);\n    }\n\n    return predict;\n  }\n\n  int execATN(CharStream input, DFAState ds0) {\n    //log(\"enter exec index \"+input.index()+\" from \"+ds0.configs, level: Level.FINE.value);\n    if (debug) {\n      log('start state closure=${ds0.configs}\\n', level: Level.FINE.value);\n    }\n\n    if (ds0.isAcceptState) {\n      // allow zero-length tokens\n      captureSimState(prevAccept, input, ds0);\n    }\n\n    var t = input.LA(1)!;\n\n    var s = ds0; // s is current/from DFA state\n\n    while (true) {\n      // while more work\n      if (debug) {\n        log('execATN loop starting closure: ${s.configs}\\n',\n            level: Level.FINE.value);\n      }\n\n      // As we move src->trg, src->trg, we keep track of the previous trg to\n      // avoid looking up the DFA state again, which is expensive.\n      // If the previous target was already part of the DFA, we might\n      // be able to avoid doing a reach operation upon t. If s!=null,\n      // it means that semantic predicates didn't prevent us from\n      // creating a DFA state. Once we know s!=null, we check to see if\n      // the DFA state has an edge already for t. If so, we can just reuse\n      // it's configuration set; there's no point in re-computing it.\n      // This is kind of like doing DFA simulation within the ATN\n      // simulation because DFA simulation is really just a way to avoid\n      // computing reach/closure sets. Technically, once we know that\n      // we have a previously added DFA state, we could jump over to\n      // the DFA simulator. But, that would mean popping back and forth\n      // a lot and making things more complicated algorithmically.\n      // This optimization makes a lot of sense for loops within DFA.\n      // A character will take us back to an existing DFA state\n      // that already has lots of edges out of it. e.g., .* in comments.\n      var target = getExistingTargetState(s, t);\n      target ??= computeTargetState(input, s, t);\n\n      if (target == ATNSimulator.ERROR) {\n        break;\n      }\n\n      // If this is a consumable input element, make sure to consume before\n      // capturing the accept state so the input index, line, and char\n      // position accurately reflect the state of the interpreter at the\n      // end of the token.\n      if (t != IntStream.EOF) {\n        consume(input);\n      }\n\n      if (target.isAcceptState) {\n        captureSimState(prevAccept, input, target);\n        if (t == IntStream.EOF) {\n          break;\n        }\n      }\n\n      t = input.LA(1)!;\n      s = target; // flip; current DFA target becomes new src/from state\n    }\n\n    return failOrAccept(prevAccept, input, s.configs, t);\n  }\n\n  /// Get an existing target state for an edge in the DFA. If the target state\n  /// for the edge has not yet been computed or is otherwise not available,\n  /// this method returns null.\n  ///\n  /// @param s The current DFA state\n  /// @param t The next input symbol\n  /// @return The existing target DFA state for the given input symbol\n  /// [t], or null if the target state for this edge is not\n  /// already cached\n\n  DFAState? getExistingTargetState(DFAState s, int t) {\n    if (s.edges == null || t < MIN_DFA_EDGE || t > MAX_DFA_EDGE) {\n      return null;\n    }\n\n    final target = s.edges![t - MIN_DFA_EDGE];\n    if (debug && target != null) {\n      log('reuse state ${s.stateNumber} edge to ${target.stateNumber}',\n          level: Level.FINE.value);\n    }\n\n    return target;\n  }\n\n  /// Compute a target state for an edge in the DFA, and attempt to add the\n  /// computed state and corresponding edge to the DFA.\n  ///\n  /// @param input The input stream\n  /// @param s The current DFA state\n  /// @param t The next input symbol\n  ///\n  /// @return The computed target DFA state for the given input symbol\n  /// [t]. If [t] does not lead to a valid DFA state, this method\n  /// returns {@link #ERROR}.\n\n  DFAState computeTargetState(CharStream input, DFAState s, int t) {\n    ATNConfigSet reach = OrderedATNConfigSet();\n\n    // if we don't find an existing DFA state\n    // Fill reach starting from closure, following t transitions\n    getReachableConfigSet(input, s.configs, reach, t);\n\n    if (reach.isEmpty) {\n      // we got nowhere on t from s\n      if (!reach.hasSemanticContext) {\n        // we got nowhere on t, don't throw out this knowledge; it'd\n        // cause a failover from DFA later.\n        addDFAEdge(s, t, ATNSimulator.ERROR);\n      }\n\n      // stop when we can't match any more char\n      return ATNSimulator.ERROR;\n    }\n\n    // Add an edge from s to target DFA found/created for reach\n    return addDFAEdgeByConfig(s, t, reach);\n  }\n\n  int failOrAccept(\n    SimState prevAccept,\n    CharStream input,\n    ATNConfigSet reach,\n    int t,\n  ) {\n    if (prevAccept.dfaState != null) {\n      final lexerActionExecutor = prevAccept.dfaState!.lexerActionExecutor;\n      accept(\n        input,\n        lexerActionExecutor,\n        startIndex,\n        prevAccept.index,\n        prevAccept.line,\n        prevAccept.charPos,\n      );\n      return prevAccept.dfaState!.prediction;\n    } else {\n      // if no accept and EOF is first char, return EOF\n      if (t == IntStream.EOF && input.index == startIndex) {\n        return Token.EOF;\n      }\n\n      throw LexerNoViableAltException(recog, input, startIndex, reach);\n    }\n  }\n\n  /// Given a starting configuration set, figure out all ATN configurations\n  ///  we can reach upon input [t]. Parameter [reach] is a return\n  ///  parameter.\n  void getReachableConfigSet(\n    CharStream input,\n    ATNConfigSet configs,\n    ATNConfigSet reach,\n    int t,\n  ) {\n    // this is used to skip processing for configs which have a lower priority\n    // than a config that already reached an accept state for the same rule\n    var skipAlt = ATN.INVALID_ALT_NUMBER;\n    for (var c in configs) {\n      final currentAltReachedAcceptState = c.alt == skipAlt;\n      if (currentAltReachedAcceptState &&\n          (c as LexerATNConfig).hasPassedThroughNonGreedyDecision()) {\n        continue;\n      }\n\n      if (debug) {\n        log('testing ${getTokenName(t)} at ${c.toString(recog, true)}\\n',\n            level: Level.FINE.value);\n      }\n\n      final n = c.state.numberOfTransitions;\n      for (var ti = 0; ti < n; ti++) {\n        // for each transition\n        final trans = c.state.transition(ti);\n        final target = getReachableTarget(trans, t);\n        if (target != null) {\n          var lexerActionExecutor = (c as LexerATNConfig).lexerActionExecutor;\n          if (lexerActionExecutor != null) {\n            lexerActionExecutor = lexerActionExecutor\n                .fixOffsetBeforeMatch(input.index - startIndex);\n          }\n\n          final treatEofAsEpsilon = t == IntStream.EOF;\n          if (closure(\n              input,\n              LexerATNConfig.dup(c, target,\n                  lexerActionExecutor: lexerActionExecutor),\n              reach,\n              currentAltReachedAcceptState,\n              true,\n              treatEofAsEpsilon)) {\n            // any remaining configs for this alt have a lower priority than\n            // the one that just reached an accept state.\n            skipAlt = c.alt;\n            break;\n          }\n        }\n      }\n    }\n  }\n\n  void accept(\n    CharStream input,\n    LexerActionExecutor? lexerActionExecutor,\n    int startIndex,\n    int index,\n    int line,\n    int charPos,\n  ) {\n    if (debug) {\n      log('ACTION $lexerActionExecutor\\n', level: Level.FINE.value);\n    }\n\n    // seek to after last char in token\n    input.seek(index);\n    this.line = line;\n    charPositionInLine = charPos;\n\n    if (lexerActionExecutor != null) {\n      lexerActionExecutor.execute(recog, input, startIndex);\n    }\n  }\n\n  ATNState? getReachableTarget(Transition trans, int t) {\n    if (trans.matches(t, Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE)) {\n      return trans.target;\n    }\n\n    return null;\n  }\n\n  ATNConfigSet computeStartState(CharStream input, ATNState p) {\n    PredictionContext initialContext = EmptyPredictionContext.Instance;\n    ATNConfigSet configs = OrderedATNConfigSet();\n    for (var i = 0; i < p.numberOfTransitions; i++) {\n      final target = p.transition(i).target;\n      final c = LexerATNConfig(target, i + 1, initialContext);\n      closure(input, c, configs, false, false, false);\n    }\n    return configs;\n  }\n\n  /// Since the alternatives within any lexer decision are ordered by\n  /// preference, this method stops pursuing the closure as soon as an accept\n  /// state is reached. After the first accept state is reached by depth-first\n  /// search from [config], all other (potentially reachable) states for\n  /// this rule would have a lower priority.\n  ///\n  /// @return [true] if an accept state is reached, otherwise\n  /// [false].\n  bool closure(\n      CharStream input,\n      LexerATNConfig config,\n      ATNConfigSet configs,\n      bool currentAltReachedAcceptState,\n      bool speculative,\n      bool treatEofAsEpsilon) {\n    if (debug) {\n      log('closure(' + config.toString(recog, true) + ')',\n          level: Level.FINE.value);\n    }\n\n    if (config.state is RuleStopState) {\n      if (debug) {\n        log('closure at ${recog.ruleNames[config.state.ruleIndex]} rule stop $config\\n',\n            level: Level.FINE.value);\n      }\n\n      if (config.context == null || config.context!.hasEmptyPath()) {\n        if (config.context == null || config.context!.isEmpty) {\n          configs.add(config);\n          return true;\n        } else {\n          configs.add(LexerATNConfig.dup(\n            config,\n            config.state,\n            context: EmptyPredictionContext.Instance,\n          ));\n          currentAltReachedAcceptState = true;\n        }\n      }\n\n      if (config.context != null && !config.context!.isEmpty) {\n        for (var i = 0; i < config.context!.length; i++) {\n          if (config.context!.getReturnState(i) !=\n              PredictionContext.EMPTY_RETURN_STATE) {\n            final newContext =\n                config.context!.getParent(i); // \"pop\" return state\n            final returnState = atn.states[config.context!.getReturnState(i)]!;\n            final c =\n                LexerATNConfig.dup(config, returnState, context: newContext);\n            currentAltReachedAcceptState = closure(\n              input,\n              c,\n              configs,\n              currentAltReachedAcceptState,\n              speculative,\n              treatEofAsEpsilon,\n            );\n          }\n        }\n      }\n\n      return currentAltReachedAcceptState;\n    }\n\n    // optimization\n    if (!config.state.onlyHasEpsilonTransitions()) {\n      if (!currentAltReachedAcceptState ||\n          !config.hasPassedThroughNonGreedyDecision()) {\n        configs.add(config);\n      }\n    }\n\n    final p = config.state;\n    for (var i = 0; i < p.numberOfTransitions; i++) {\n      final t = p.transition(i);\n      final c = getEpsilonTarget(\n        input,\n        config,\n        t,\n        configs,\n        speculative,\n        treatEofAsEpsilon,\n      );\n      if (c != null) {\n        currentAltReachedAcceptState = closure(input, c, configs,\n            currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n      }\n    }\n\n    return currentAltReachedAcceptState;\n  }\n\n  // side-effect: can alter configs.hasSemanticContext\n\n  LexerATNConfig? getEpsilonTarget(\n    CharStream input,\n    LexerATNConfig config,\n    Transition t,\n    ATNConfigSet configs,\n    bool speculative,\n    bool treatEofAsEpsilon,\n  ) {\n    LexerATNConfig? c;\n    switch (t.type) {\n      case TransitionType.RULE:\n        final ruleTransition = t as RuleTransition;\n        PredictionContext newContext = SingletonPredictionContext.create(\n          config.context!,\n          ruleTransition.followState.stateNumber,\n        );\n        c = LexerATNConfig.dup(config, t.target, context: newContext);\n        break;\n\n      case TransitionType.PRECEDENCE:\n        throw UnsupportedError(\n            'Precedence predicates are not supported in lexers.');\n      case TransitionType.PREDICATE:\n        /*  Track traversing semantic predicates. If we traverse,\n\t\t\t\t we cannot add a DFA state for this \"reach\" computation\n\t\t\t\t because the DFA would not test the predicate again in the\n\t\t\t\t future. Rather than creating collections of semantic predicates\n\t\t\t\t like v3 and testing them on prediction, v4 will test them on the\n\t\t\t\t fly all the time using the ATN not the DFA. This is slower but\n\t\t\t\t semantically it's not used that often. One of the key elements to\n\t\t\t\t this predicate mechanism is not adding DFA states that see\n\t\t\t\t predicates immediately afterwards in the ATN. For example,\n\n\t\t\t\t a : ID {p1}? | ID {p2}? ;\n\n\t\t\t\t should create the start state for rule 'a' (to save start state\n\t\t\t\t competition), but should not create target of ID state. The\n\t\t\t\t collection of ATN states the following ID references includes\n\t\t\t\t states reached by traversing predicates. Since this is when we\n\t\t\t\t test them, we cannot cash the DFA state target of ID.\n\t\t\t */\n        final pt = t as PredicateTransition;\n        if (debug) {\n          log('EVAL rule ${pt.ruleIndex}:${pt.predIndex}',\n              level: Level.FINE.value);\n        }\n        configs.hasSemanticContext = true;\n        if (evaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative)) {\n          c = LexerATNConfig.dup(config, t.target);\n        }\n        break;\n      case TransitionType.ACTION:\n        if (config.context == null || config.context!.hasEmptyPath()) {\n          // execute actions anywhere in the start rule for a token.\n          //\n          // TODO: if the entry rule is invoked recursively, some\n          // actions may be executed during the recursive call. The\n          // problem can appear when hasEmptyPath() is true but\n          // isEmpty is false. In this case, the config needs to be\n          // split into two contexts - one with just the empty path\n          // and another with everything but the empty path.\n          // Unfortunately, the current algorithm does not allow\n          // getEpsilonTarget to return two configurations, so\n          // additional modifications are needed before we can support\n          // the split operation.\n          final lexerActionExecutor = LexerActionExecutor.append(\n            config.lexerActionExecutor,\n            atn.lexerActions![(t as ActionTransition).actionIndex],\n          );\n          c = LexerATNConfig.dup(config, t.target,\n              lexerActionExecutor: lexerActionExecutor);\n        } else {\n          // ignore actions in referenced rules\n          c = LexerATNConfig.dup(config, t.target);\n        }\n        break;\n\n      case TransitionType.EPSILON:\n        c = LexerATNConfig.dup(config, t.target);\n        break;\n\n      case TransitionType.ATOM:\n      case TransitionType.RANGE:\n      case TransitionType.SET:\n        if (treatEofAsEpsilon) {\n          if (t.matches(\n              IntStream.EOF, Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE)) {\n            c = LexerATNConfig.dup(config, t.target);\n            break;\n          }\n        }\n        break;\n      case TransitionType.NOT_SET:\n        break;\n      case TransitionType.WILDCARD:\n        break;\n      case TransitionType.INVALID:\n        throw ArgumentError.value(t.type, 'TransitionType');\n    }\n\n    return c;\n  }\n\n  /// Evaluate a predicate specified in the lexer.\n  ///\n  /// <p>If [speculative] is [true], this method was called before\n  /// {@link #consume} for the matched character. This method should call\n  /// {@link #consume} before evaluating the predicate to ensure position\n  /// sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine},\n  /// and {@link Lexer#getCharPositionInLine}, properly reflect the current\n  /// lexer state. This method should restore [input] and the simulator\n  /// to the original state before returning (i.e. undo the actions made by the\n  /// call to {@link #consume}.</p>\n  ///\n  /// @param input The input stream.\n  /// @param ruleIndex The rule containing the predicate.\n  /// @param predIndex The index of the predicate within the rule.\n  /// @param speculative [true] if the current index in [input] is\n  /// one character before the predicate's location.\n  ///\n  /// @return [true] if the specified predicate evaluates to\n  /// [true].\n  bool evaluatePredicate(\n    CharStream input,\n    int ruleIndex,\n    int predIndex,\n    bool speculative,\n  ) {\n    if (!speculative) {\n      return recog.sempred(null, ruleIndex, predIndex);\n    }\n\n    final savedCharPositionInLine = charPositionInLine;\n    final savedLine = line;\n    final index = input.index;\n    final marker = input.mark();\n    try {\n      consume(input);\n      return recog.sempred(null, ruleIndex, predIndex);\n    } finally {\n      charPositionInLine = savedCharPositionInLine;\n      line = savedLine;\n      input.seek(index);\n      input.release(marker);\n    }\n  }\n\n  void captureSimState(SimState settings, CharStream input, DFAState dfaState) {\n    settings.index = input.index;\n    settings.line = line;\n    settings.charPos = charPositionInLine;\n    settings.dfaState = dfaState;\n  }\n\n  DFAState addDFAEdgeByConfig(DFAState from, int t, ATNConfigSet q) {\n    /* leading to this call, ATNConfigSet.hasSemanticContext is used as a\n\t\t * marker indicating dynamic predicate evaluation makes this edge\n\t\t * dependent on the specific input sequence, so the static edge in the\n\t\t * DFA should be omitted. The target DFAState is still created since\n\t\t * execATN has the ability to resynchronize with the DFA state cache\n\t\t * following the predicate evaluation step.\n\t\t *\n\t\t * TJP notes: next time through the DFA, we see a pred again and eval.\n\t\t * If that gets us to a previously created (but dangling) DFA\n\t\t * state, we can continue in pure DFA mode from there.\n\t\t */\n    final suppressEdge = q.hasSemanticContext;\n    q.hasSemanticContext = false;\n\n    final to = addDFAState(q);\n\n    if (suppressEdge) {\n      return to;\n    }\n\n    addDFAEdge(from, t, to);\n    return to;\n  }\n\n  void addDFAEdge(DFAState p, int t, DFAState q) {\n    if (t < MIN_DFA_EDGE || t > MAX_DFA_EDGE) {\n      // Only track edges within the DFA bounds\n      return;\n    }\n\n    if (debug) {\n      log('EDGE $p -> $q upon ${String.fromCharCode(t)}',\n          level: Level.FINE.value);\n    }\n\n    p.edges ??= List<DFAState?>.filled(MAX_DFA_EDGE - MIN_DFA_EDGE + 1, null);\n    p.edges![t - MIN_DFA_EDGE] = q; // connect\n  }\n\n  /// Add a new DFA state if there isn't one with this set of\n  /// configurations already. This method also detects the first\n  /// configuration containing an ATN rule stop state. Later, when\n  /// traversing the DFA, we will know which rule to accept.\n  DFAState addDFAState(ATNConfigSet configs) {\n    /* the lexer evaluates predicates on-the-fly; by this point configs\n\t\t * should not contain any configurations with unevaluated predicates.\n\t\t */\n    assert(!configs.hasSemanticContext);\n\n    final proposed = DFAState(configs: configs);\n    ATNConfig? firstConfigWithRuleStopState;\n    for (var c in configs) {\n      if (c.state is RuleStopState) {\n        firstConfigWithRuleStopState = c;\n        break;\n      }\n    }\n\n    if (firstConfigWithRuleStopState != null) {\n      proposed.isAcceptState = true;\n      proposed.lexerActionExecutor =\n          (firstConfigWithRuleStopState as LexerATNConfig).lexerActionExecutor;\n      proposed.prediction =\n          atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex];\n    }\n\n    final dfa = decisionToDFA[mode];\n    final existing = dfa.states[proposed];\n    if (existing != null) return existing;\n\n    final newState = proposed;\n\n    newState.stateNumber = dfa.states.length;\n    configs.readOnly = true;\n    newState.configs = configs;\n    dfa.states[newState] = newState;\n    return newState;\n  }\n\n  DFA getDFA(int mode) {\n    return decisionToDFA[mode];\n  }\n\n  /// Get the text matched so far for the current token.\n\n  String getText(CharStream input) {\n    // index is first lookahead char, don't include.\n    return input.getText(Interval.of(startIndex, input.index - 1));\n  }\n\n  void consume(CharStream input) {\n    final curChar = input.LA(1);\n    if (curChar == 10) {\n      // Is new line\n      line++;\n      charPositionInLine = 0;\n    } else {\n      charPositionInLine++;\n    }\n    input.consume();\n  }\n\n  String getTokenName(int t) {\n    if (t == -1) return 'EOF';\n    //if ( atn.g!=null ) return atn.g.getTokenDisplayName(t);\n    return \"'${String.fromCharCode(t)}'\";\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/parser_atn_simulator.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:collection';\nimport 'dart:developer';\n\nimport 'package:logging/logging.dart';\n\nimport '../../dfa/dfa.dart';\nimport '../../error/error.dart';\nimport '../../input_stream.dart';\nimport '../../interval_set.dart';\nimport '../../misc/misc.dart';\nimport '../../parser.dart';\nimport '../../parser_rule_context.dart';\nimport '../../prediction_context.dart';\nimport '../../rule_context.dart';\nimport '../../token.dart';\nimport '../../token_stream.dart';\nimport '../../util/bit_set.dart';\nimport '../../util/murmur_hash.dart';\nimport 'atn.dart';\nimport 'atn_config.dart';\nimport 'atn_config_set.dart';\nimport 'atn_simulator.dart';\nimport 'atn_state.dart';\nimport 'semantic_context.dart';\nimport 'transition.dart';\n\n/// The embodiment of the adaptive LL(*), ALL(*), parsing strategy.\n///\n/// <p>\n/// The basic complexity of the adaptive strategy makes it harder to understand.\n/// We begin with ATN simulation to build paths in a DFA. Subsequent prediction\n/// requests go through the DFA first. If they reach a state without an edge for\n/// the current symbol, the algorithm fails over to the ATN simulation to\n/// complete the DFA path for the current input (until it finds a conflict state\n/// or uniquely predicting state).</p>\n///\n/// <p>\n/// All of that is done without using the outer context because we want to create\n/// a DFA that is not dependent upon the rule invocation stack when we do a\n/// prediction. One DFA works in all contexts. We avoid using context not\n/// necessarily because it's slower, although it can be, but because of the DFA\n/// caching problem. The closure routine only considers the rule invocation stack\n/// created during prediction beginning in the decision rule. For example, if\n/// prediction occurs without invoking another rule's ATN, there are no context\n/// stacks in the configurations. When lack of context leads to a conflict, we\n/// don't know if it's an ambiguity or a weakness in the strong LL(*) parsing\n/// strategy (versus full LL(*)).</p>\n///\n/// <p>\n/// When SLL yields a configuration set with conflict, we rewind the input and\n/// retry the ATN simulation, this time using full outer context without adding\n/// to the DFA. Configuration context stacks will be the full invocation stacks\n/// from the start rule. If we get a conflict using full context, then we can\n/// definitively say we have a true ambiguity for that input sequence. If we\n/// don't get a conflict, it implies that the decision is sensitive to the outer\n/// context. (It is not context-sensitive in the sense of context-sensitive\n/// grammars.)</p>\n///\n/// <p>\n/// The next time we reach this DFA state with an SLL conflict, through DFA\n/// simulation, we will again retry the ATN simulation using full context mode.\n/// This is slow because we can't save the results and have to \"interpret\" the\n/// ATN each time we get that input.</p>\n///\n/// <p>\n/// <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>\n///\n/// <p>\n/// We could cache results from full context to predicted alternative easily and\n/// that saves a lot of time but doesn't work in presence of predicates. The set\n/// of visible predicates from the ATN start state changes depending on the\n/// context, because closure can fall off the end of a rule. I tried to cache\n/// tuples (stack context, semantic context, predicted alt) but it was slower\n/// than interpreting and much more complicated. Also required a huge amount of\n/// memory. The goal is not to create the world's fastest parser anyway. I'd like\n/// to keep this algorithm simple. By launching multiple threads, we can improve\n/// the speed of parsing across a large number of files.</p>\n///\n/// <p>\n/// There is no strict ordering between the amount of input used by SLL vs LL,\n/// which makes it really hard to build a cache for full context. Let's say that\n/// we have input A B C that leads to an SLL conflict with full context X. That\n/// implies that using X we might only use A B but we could also use A B C D to\n/// resolve conflict. Input A B C D could predict alternative 1 in one position\n/// in the input and A B C E could predict alternative 2 in another position in\n/// input. The conflicting SLL configurations could still be non-unique in the\n/// full context prediction, which would lead us to requiring more input than the\n/// original A B C.\tTo make a\tprediction cache work, we have to track\tthe exact\n/// input\tused during the previous prediction. That amounts to a cache that maps\n/// X to a specific DFA for that context.</p>\n///\n/// <p>\n/// Something should be done for left-recursive expression predictions. They are\n/// likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry\n/// with full LL thing Sam does.</p>\n///\n/// <p>\n/// <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>\n///\n/// <p>\n/// We avoid doing full context retry when the outer context is empty, we did not\n/// dip into the outer context by falling off the end of the decision state rule,\n/// or when we force SLL mode.</p>\n///\n/// <p>\n/// As an example of the not dip into outer context case, consider as super\n/// constructor calls versus function calls. One grammar might look like\n/// this:</p>\n///\n/// <pre>\n/// ctorBody\n///   : '{' superCall? stat* '}'\n///   ;\n/// </pre>\n///\n/// <p>\n/// Or, you might see something like</p>\n///\n/// <pre>\n/// stat\n///   : superCall ';'\n///   | expression ';'\n///   | ...\n///   ;\n/// </pre>\n///\n/// <p>\n/// In both cases I believe that no closure operations will dip into the outer\n/// context. In the first case ctorBody in the worst case will stop at the '}'.\n/// In the 2nd case it should stop at the ';'. Both cases should stay within the\n/// entry rule and not dip into the outer context.</p>\n///\n/// <p>\n/// <strong>PREDICATES</strong></p>\n///\n/// <p>\n/// Predicates are always evaluated if present in either SLL or LL both. SLL and\n/// LL simulation deals with predicates differently. SLL collects predicates as\n/// it performs closure operations like ANTLR v3 did. It delays predicate\n/// evaluation until it reaches and accept state. This allows us to cache the SLL\n/// ATN simulation whereas, if we had evaluated predicates on-the-fly during\n/// closure, the DFA state configuration sets would be different and we couldn't\n/// build up a suitable DFA.</p>\n///\n/// <p>\n/// When building a DFA accept state during ATN simulation, we evaluate any\n/// predicates and return the sole semantically valid alternative. If there is\n/// more than 1 alternative, we report an ambiguity. If there are 0 alternatives,\n/// we throw an exception. Alternatives without predicates act like they have\n/// true predicates. The simple way to think about it is to strip away all\n/// alternatives with false predicates and choose the minimum alternative that\n/// remains.</p>\n///\n/// <p>\n/// When we start in the DFA and reach an accept state that's predicated, we test\n/// those and return the minimum semantically viable alternative. If no\n/// alternatives are viable, we throw an exception.</p>\n///\n/// <p>\n/// During full LL ATN simulation, closure always evaluates predicates and\n/// on-the-fly. This is crucial to reducing the configuration set size during\n/// closure. It hits a landmine when parsing with the Java grammar, for example,\n/// without this on-the-fly evaluation.</p>\n///\n/// <p>\n/// <strong>SHARING DFA</strong></p>\n///\n/// <p>\n/// All instances of the same parser share the same decision DFAs through a\n/// static field. Each instance gets its own ATN simulator but they share the\n/// same {@link #decisionToDFA} field. They also share a\n/// [PredictionContextCache] object that makes sure that all\n/// [PredictionContext] objects are shared among the DFA states. This makes\n/// a big size difference.</p>\n///\n/// <p>\n/// <strong>THREAD SAFETY</strong></p>\n///\n/// <p>\n/// The [ParserATNSimulator] locks on the {@link #decisionToDFA} field when\n/// it adds a new DFA object to that array. {@link #addDFAEdge}\n/// locks on the DFA for the current decision when setting the\n/// {@link DFAState#edges} field. {@link #addDFAState} locks on\n/// the DFA for the current decision when looking up a DFA state to see if it\n/// already exists. We must make sure that all requests to add DFA states that\n/// are equivalent result in the same shared DFA object. This is because lots of\n/// threads will be trying to update the DFA at once. The\n/// {@link #addDFAState} method also locks inside the DFA lock\n/// but this time on the shared context cache when it rebuilds the\n/// configurations' [PredictionContext] objects using cached\n/// subgraphs/nodes. No other locking occurs, even during DFA simulation. This is\n/// safe as long as we can guarantee that all threads referencing\n/// {@code s.edge[t]} get the same physical target [DFAState], or\n/// null. Once into the DFA, the DFA simulation does not reference the\n/// {@link DFA#states} map. It follows the {@link DFAState#edges} field to new\n/// targets. The DFA simulator will either find {@link DFAState#edges} to be\n/// null, to be non-null and {@code dfa.edges[t]} null, or\n/// {@code dfa.edges[t]} to be non-null. The\n/// {@link #addDFAEdge} method could be racing to set the field\n/// but in either case the DFA simulator works; if null, and requests ATN\n/// simulation. It could also race trying to get {@code dfa.edges[t]}, but either\n/// way it will work because it's not doing a test and set operation.</p>\n///\n/// <p>\n/// <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage\n/// Parsing)</strong></p>\n///\n/// <p>\n/// Sam pointed out that if SLL does not give a syntax error, then there is no\n/// point in doing full LL, which is slower. We only have to try LL if we get a\n/// syntax error. For maximum speed, Sam starts the parser set to pure SLL\n/// mode with the [BailErrorStrategy]:</p>\n///\n/// <pre>\n/// parser.{@link Parser#interpreter interpreter}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};\n/// parser.{@link Parser#setErrorHandler setErrorHandler}(new [BailErrorStrategy]());\n/// </pre>\n///\n/// <p>\n/// If it does not get a syntax error, then we're done. If it does get a syntax\n/// error, we need to retry with the combined SLL/LL strategy.</p>\n///\n/// <p>\n/// The reason this works is as follows. If there are no SLL conflicts, then the\n/// grammar is SLL (at least for that input set). If there is an SLL conflict,\n/// the full LL analysis must yield a set of viable alternatives which is a\n/// subset of the alternatives reported by SLL. If the LL set is a singleton,\n/// then the grammar is LL but not SLL. If the LL set is the same size as the SLL\n/// set, the decision is SLL. If the LL set has size &gt; 1, then that decision\n/// is truly ambiguous on the current input. If the LL set is smaller, then the\n/// SLL conflict resolution might choose an alternative that the full LL would\n/// rule out as a possibility based upon better context information. If that's\n/// the case, then the SLL parse will definitely get an error because the full LL\n/// analysis says it's not viable. If SLL conflict resolution chooses an\n/// alternative within the LL set, them both SLL and LL would choose the same\n/// alternative because they both choose the minimum of multiple conflicting\n/// alternatives.</p>\n///\n/// <p>\n/// Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and\n/// a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL\n/// parsing will get an error because SLL will pursue alternative 1. If\n/// <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will\n/// choose the same alternative because alternative one is the minimum of either\n/// set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax\n/// error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>\n///\n/// <p>\n/// Of course, if the input is invalid, then we will get an error for sure in\n/// both SLL and LL parsing. Erroneous input will therefore require 2 passes over\n/// the input.</p>\nclass ParserATNSimulator extends ATNSimulator {\n  static const bool debug = bool.fromEnvironment(\n    'ANTLR_PARSER_DEBUG',\n    defaultValue: false,\n  );\n  static const bool trace_atn_sim = bool.fromEnvironment(\n    'ANTLR_PARSER_LIST_ATN_DECISIONS_DEBUG',\n    defaultValue: false,\n  );\n  static const bool dfa_debug = bool.fromEnvironment(\n    'ANTLR_PARSER_DFA_DEBUG',\n    defaultValue: false,\n  );\n  static const bool retry_debug = bool.fromEnvironment(\n    'ANTLR_PARSER_RETRY_DEBUG',\n    defaultValue: false,\n  );\n\n  /// Just in case this optimization is bad, add an ENV variable to turn it off */\n  static const bool TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT =\n      bool.fromEnvironment('TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT');\n\n  final Parser parser;\n\n  final List<DFA> decisionToDFA;\n\n  /// SLL, LL, or LL + exact ambig detection? */\n\n  PredictionMode predictionMode = PredictionMode.LL;\n\n  /// Each prediction operation uses a cache for merge of prediction contexts.\n  ///  Don't keep around as it wastes huge amounts of memory. DoubleKeyMap\n  ///  isn't synchronized but we're ok since two threads shouldn't reuse same\n  ///  parser/atnsim object because it can only handle one input at a time.\n  ///  This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid\n  ///  the merge if we ever see a and b again.  Note that (b,a)&rarr;c should\n  ///  also be examined during cache lookup.\n  Map<Pair<PredictionContext, PredictionContext>, PredictionContext>?\n      mergeCache;\n\n  // LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n  late TokenStream input;\n  int startIndex = 0;\n  ParserRuleContext? _outerContext;\n  DFA? _dfa;\n\n  ParserATNSimulator(\n    this.parser,\n    ATN atn,\n    this.decisionToDFA,\n    PredictionContextCache? sharedContextCache,\n  ) : super(atn, sharedContextCache);\n\n  @override\n  void reset() {}\n\n  @override\n  void clearDFA() {\n    for (var d = 0; d < decisionToDFA.length; d++) {\n      decisionToDFA[d] = DFA(atn.getDecisionState(d), d);\n    }\n  }\n\n  int adaptivePredict(\n    TokenStream input_,\n    int decision,\n    ParserRuleContext? outerContext,\n  ) {\n    if (debug || trace_atn_sim) {\n      log('adaptivePredict decision $decision' ' exec LA(1)==' +\n          getLookaheadName(input_) +\n          ' line ${input_.LT(1)!.line}:${input_.LT(1)!.charPositionInLine}');\n    }\n\n    input = input_;\n    startIndex = input_.index;\n    _outerContext = outerContext;\n    final dfa = decisionToDFA[decision];\n    _dfa = dfa;\n\n    final m = input_.mark();\n    final index = startIndex;\n\n    // Now we are certain to have a specific decision's DFA\n    // But, do we still need an initial state?\n    try {\n      DFAState? s0;\n      if (dfa.isPrecedenceDfa()) {\n        // the start state for a precedence DFA depends on the current\n        // parser precedence, and is provided by a DFA method.\n        s0 = dfa.getPrecedenceStartState(parser.precedence);\n      } else {\n        // the start state for a \"regular\" DFA is just s0\n        s0 = dfa.s0;\n      }\n\n      if (s0 == null) {\n        outerContext ??= ParserRuleContext.EMPTY;\n        if (debug || trace_atn_sim) {\n          log('predictATN decision ${dfa.decision}' ' exec LA(1)==' +\n              getLookaheadName(input_) +\n              ', outerContext=' +\n              outerContext.toString(recog: parser));\n        }\n\n        final fullCtx = false;\n        var s0_closure = computeStartState(\n          dfa.atnStartState!,\n          ParserRuleContext.EMPTY,\n          fullCtx,\n        );\n\n        if (dfa.isPrecedenceDfa()) {\n          /* If this is a precedence DFA, we use applyPrecedenceFilter\n\t\t\t\t\t * to convert the computed start state to a precedence start\n\t\t\t\t\t * state. We then use DFA.setPrecedenceStartState to set the\n\t\t\t\t\t * appropriate start state for the precedence level rather\n\t\t\t\t\t * than simply setting DFA.s0.\n\t\t\t\t\t */\n          // not used for prediction but useful to know start configs anyway\n          dfa.s0!.configs = s0_closure;\n          s0_closure = applyPrecedenceFilter(s0_closure);\n          s0 = addDFAState(dfa, DFAState(configs: s0_closure));\n          dfa.setPrecedenceStartState(parser.precedence, s0);\n        } else {\n          s0 = addDFAState(dfa, DFAState(configs: s0_closure));\n          dfa.s0 = s0;\n        }\n      }\n\n      final alt = execATN(dfa, s0, input_, index, outerContext!);\n      if (debug) {\n        log('DFA after predictATN: ' + dfa.toString(parser.vocabulary));\n      }\n      return alt;\n    } finally {\n      mergeCache = null; // wack cache after each prediction\n      _dfa = null;\n      input_.seek(index);\n      input_.release(m);\n    }\n  }\n\n  /// Performs ATN simulation to compute a predicted alternative based\n  /// upon the remaining input, but also updates the DFA cache to avoid\n  /// having to traverse the ATN again for the same input sequence.\n  ///\n  /// There are some key conditions we're looking for after computing a new\n  /// set of ATN configs (proposed DFA state):\n  /// if the set is empty, there is no viable alternative for current symbol\n  /// does the state uniquely predict an alternative?\n  /// does the state have a conflict that would prevent us from\n  /// putting it on the work list?\n  ///\n  /// We also have some key operations to do:\n  /// add an edge from previous DFA state to potentially new DFA state, D,\n  ///  upon current symbol but only if adding to work list, which means in all\n  ///  cases except no viable alternative (and possibly non-greedy decisions?)\n  /// collecting predicates and adding semantic context to DFA accept states\n  /// adding rule context to context-sensitive DFA accept states\n  /// consuming an input symbol\n  /// reporting a conflict\n  /// reporting an ambiguity\n  /// reporting a context sensitivity\n  /// reporting insufficient predicates\n  ///\n  /// cover these cases:\n  /// dead end\n  /// single alt\n  /// single alt + preds\n  /// conflict\n  /// conflict + preds\n  ///\n  int execATN(DFA dfa, DFAState s0, TokenStream input, int startIndex,\n      ParserRuleContext outerContext) {\n    if (debug || trace_atn_sim) {\n      log('execATN decision ${dfa.decision}' ' exec LA(1)==' +\n          getLookaheadName(input) +\n          ' line ${input.LT(1)!.line}' +\n          ':${input.LT(1)!.charPositionInLine}');\n    }\n\n    var previousD = s0;\n\n    if (debug) log('s0 = $s0');\n\n    var t = input.LA(1)!;\n\n    while (true) {\n      // while more work\n      var D = getExistingTargetState(previousD, t);\n      D ??= computeTargetState(dfa, previousD, t);\n      D = D as DFAState;\n      if (D == ATNSimulator.ERROR) {\n        // if any configs in previous dipped into outer context, that\n        // means that input up to t actually finished entry rule\n        // at least for SLL decision. Full LL doesn't dip into outer\n        // so don't need special case.\n        // We will get an error no matter what so delay until after\n        // decision; better error message. Also, no reachable target\n        // ATN states in SLL implies LL will also get nowhere.\n        // If conflict in states that dip out, choose min since we\n        // will get error no matter what.\n        final e = noViableAlt(\n          input,\n          outerContext,\n          previousD.configs,\n          startIndex,\n        );\n        input.seek(startIndex);\n        final alt = getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(\n            previousD.configs, outerContext);\n        if (alt != ATN.INVALID_ALT_NUMBER) {\n          return alt;\n        }\n        throw e;\n      }\n\n      if (D.requiresFullContext && predictionMode != PredictionMode.SLL) {\n        // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n        var conflictingAlts = D.configs.conflictingAlts;\n        if (D.predicates != null) {\n          if (debug) log('DFA state has preds in DFA sim LL failover');\n          final conflictIndex = input.index;\n          if (conflictIndex != startIndex) {\n            input.seek(startIndex);\n          }\n\n          conflictingAlts =\n              evalSemanticContext(D.predicates!, outerContext, true);\n          if (conflictingAlts.cardinality == 1) {\n            if (debug) log('Full LL avoided');\n            return conflictingAlts.nextset(0);\n          }\n\n          if (conflictIndex != startIndex) {\n            // restore the index so reporting the fallback to full\n            // context occurs with the index at the correct spot\n            input.seek(conflictIndex);\n          }\n        }\n\n        if (dfa_debug) log('ctx sensitive state $outerContext in $D');\n        final fullCtx = true;\n        final s0_closure = computeStartState(\n          dfa.atnStartState!,\n          outerContext,\n          fullCtx,\n        );\n        reportAttemptingFullContext(\n          dfa,\n          conflictingAlts,\n          D.configs,\n          startIndex,\n          input.index,\n        );\n        final alt = execATNWithFullContext(\n          dfa,\n          D,\n          s0_closure,\n          input,\n          startIndex,\n          outerContext,\n        );\n        return alt;\n      }\n\n      if (D.isAcceptState) {\n        if (D.predicates == null) {\n          return D.prediction;\n        }\n\n        final stopIndex = input.index;\n        input.seek(startIndex);\n        final alts = evalSemanticContext(D.predicates!, outerContext, true);\n        switch (alts.cardinality) {\n          case 0:\n            throw noViableAlt(input, outerContext, D.configs, startIndex);\n\n          case 1:\n            return alts.nextset(0);\n\n          default:\n            // report ambiguity after predicate evaluation to make sure the correct\n            // set of ambig alts is reported.\n            reportAmbiguity(\n              dfa,\n              D,\n              startIndex,\n              stopIndex,\n              false,\n              alts,\n              D.configs,\n            );\n            return alts.nextset(0);\n        }\n      }\n\n      previousD = D;\n\n      if (t != IntStream.EOF) {\n        input.consume();\n        t = input.LA(1)!;\n      }\n    }\n  }\n\n  /// Get an existing target state for an edge in the DFA. If the target state\n  /// for the edge has not yet been computed or is otherwise not available,\n  /// this method returns null.\n  ///\n  /// @param previousD The current DFA state\n  /// @param t The next input symbol\n  /// @return The existing target DFA state for the given input symbol\n  /// [t], or null if the target state for this edge is not\n  /// already cached\n  DFAState? getExistingTargetState(DFAState previousD, int t) {\n    final edges = previousD.edges;\n    if (edges == null || t + 1 < 0 || t + 1 >= edges.length) {\n      return null;\n    }\n\n    return edges[t + 1];\n  }\n\n  /// Compute a target state for an edge in the DFA, and attempt to add the\n  /// computed state and corresponding edge to the DFA.\n  ///\n  /// @param dfa The DFA\n  /// @param previousD The current DFA state\n  /// @param t The next input symbol\n  ///\n  /// @return The computed target DFA state for the given input symbol\n  /// [t]. If [t] does not lead to a valid DFA state, this method\n  /// returns {@link #ERROR}.\n  DFAState? computeTargetState(DFA dfa, DFAState previousD, int t) {\n    final reach = computeReachSet(previousD.configs, t, false);\n    if (reach == null) {\n      addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR);\n      return ATNSimulator.ERROR;\n    }\n\n    // create new target state; we'll add to DFA after it's complete\n    DFAState? D = DFAState(configs: reach);\n\n    final predictedAlt = getUniqueAlt(reach);\n\n    if (debug) {\n      final altSubSets =\n          PredictionModeExtension.getConflictingAltSubsets(reach);\n      log('SLL altSubSets=$altSubSets'\n          ', configs=$reach'\n          ', predict=$predictedAlt, allSubsetsConflict=${PredictionModeExtension.allSubsetsConflict(altSubSets)}, conflictingAlts=${getConflictingAlts(reach)}');\n    }\n\n    if (predictedAlt != ATN.INVALID_ALT_NUMBER) {\n      // NO CONFLICT, UNIQUELY PREDICTED ALT\n      D.isAcceptState = true;\n      D.configs.uniqueAlt = predictedAlt;\n      D.prediction = predictedAlt;\n    } else if (PredictionModeExtension.hasSLLConflictTerminatingPrediction(\n        predictionMode, reach)) {\n      // MORE THAN ONE VIABLE ALTERNATIVE\n      D.configs.conflictingAlts = getConflictingAlts(reach);\n      D.requiresFullContext = true;\n      // in SLL-only mode, we will stop at this state and return the minimum alt\n      D.isAcceptState = true;\n      D.prediction = D.configs.conflictingAlts!.nextset(0);\n    }\n\n    if (D.isAcceptState && D.configs.hasSemanticContext) {\n      predicateDFAState(D, atn.getDecisionState(dfa.decision));\n      if (D.predicates != null) {\n        D.prediction = ATN.INVALID_ALT_NUMBER;\n      }\n    }\n\n    // all adds to dfa are done after we've created full D state\n    D = addDFAEdge(dfa, previousD, t, D);\n    return D;\n  }\n\n  void predicateDFAState(DFAState dfaState, DecisionState? decisionState) {\n    // Todo: this if was added due to a possible null pointer error\n    if (decisionState == null) return;\n\n    // We need to test all predicates, even in DFA states that\n    // uniquely predict alternative.\n    final nalts = decisionState.numberOfTransitions;\n    // Update DFA so reach becomes accept state with (predicate,alt)\n    // pairs if preds found for conflicting alts\n    final altsToCollectPredsFrom = getConflictingAltsOrUniqueAlt(\n      dfaState.configs,\n    );\n    final altToPred = getPredsForAmbigAlts(\n      altsToCollectPredsFrom,\n      dfaState.configs,\n      nalts,\n    );\n    if (altToPred != null) {\n      dfaState.predicates =\n          getPredicatePredictions(altsToCollectPredsFrom, altToPred);\n      dfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds\n    } else {\n      // There are preds in configs but they might go away\n      // when OR'd together like {p}? || NONE == NONE. If neither\n      // alt has preds, resolve to min alt\n      dfaState.prediction = altsToCollectPredsFrom.nextset(0);\n    }\n  }\n\n  // comes back with reach.uniqueAlt set to a valid alt\n  int execATNWithFullContext(\n      DFA dfa,\n      DFAState D, // how far we got in SLL DFA before failing over\n      ATNConfigSet s0,\n      TokenStream input,\n      int startIndex,\n      ParserRuleContext outerContext) {\n    if (debug || trace_atn_sim) {\n      log('execATNWithFullContext $s0');\n    }\n    final fullCtx = true;\n    var foundExactAmbig = false;\n    ATNConfigSet? reach;\n    var previous = s0;\n    input.seek(startIndex);\n    var t = input.LA(1)!;\n    int predictedAlt;\n    while (true) {\n      // while more work\n//\t\t\tlog(\"LL REACH \"+getLookaheadName(input)+\n//\t\t\t\t\t\t\t   \" from configs.size=\"+previous.length+\n//\t\t\t\t\t\t\t   \" line \"+input.LT(1).getLine()+\":\"+input.LT(1).getCharPositionInLine());\n      reach = computeReachSet(previous, t, fullCtx);\n      if (reach == null) {\n        // if any configs in previous dipped into outer context, that\n        // means that input up to t actually finished entry rule\n        // at least for LL decision. Full LL doesn't dip into outer\n        // so don't need special case.\n        // We will get an error no matter what so delay until after\n        // decision; better error message. Also, no reachable target\n        // ATN states in SLL implies LL will also get nowhere.\n        // If conflict in states that dip out, choose min since we\n        // will get error no matter what.\n        final e = noViableAlt(input, outerContext, previous, startIndex);\n        input.seek(startIndex);\n        final alt = getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(\n          previous,\n          outerContext,\n        );\n        if (alt != ATN.INVALID_ALT_NUMBER) {\n          return alt;\n        }\n        throw e;\n      }\n\n      final altSubSets =\n          PredictionModeExtension.getConflictingAltSubsets(reach);\n      if (debug) {\n        log('LL altSubSets=$altSubSets'\n            ', predict=${PredictionModeExtension.getUniqueAlt(altSubSets)}'\n            ', resolvesToJustOneViableAlt=${PredictionModeExtension.resolvesToJustOneViableAlt(altSubSets)}');\n      }\n\n//\t\t\tlog(\"altSubSets: \"+altSubSets);\n//\t\t\tlog(\"reach=\"+reach+\", \"+reach.conflictingAlts, level: Level.SEVERE.value);\n      reach.uniqueAlt = getUniqueAlt(reach);\n      // unique prediction?\n      if (reach.uniqueAlt != ATN.INVALID_ALT_NUMBER) {\n        predictedAlt = reach.uniqueAlt;\n        break;\n      }\n      if (predictionMode != PredictionMode.LL_EXACT_AMBIG_DETECTION) {\n        predictedAlt =\n            PredictionModeExtension.resolvesToJustOneViableAlt(altSubSets);\n        if (predictedAlt != ATN.INVALID_ALT_NUMBER) {\n          break;\n        }\n      } else {\n        // In exact ambiguity mode, we never try to terminate early.\n        // Just keeps scarfing until we know what the conflict is\n        if (PredictionModeExtension.allSubsetsConflict(altSubSets) &&\n            PredictionModeExtension.allSubsetsEqual(altSubSets)) {\n          foundExactAmbig = true;\n          predictedAlt = PredictionModeExtension.getSingleViableAlt(altSubSets);\n          break;\n        }\n        // else there are multiple non-conflicting subsets or\n        // we're not sure what the ambiguity is yet.\n        // So, keep going.\n      }\n\n      previous = reach;\n      if (t != IntStream.EOF) {\n        input.consume();\n        t = input.LA(1)!;\n      }\n    }\n\n    // If the configuration set uniquely predicts an alternative,\n    // without conflict, then we know that it's a full LL decision\n    // not SLL.\n    if (reach.uniqueAlt != ATN.INVALID_ALT_NUMBER) {\n      reportContextSensitivity(\n          dfa, predictedAlt, reach, startIndex, input.index);\n      return predictedAlt;\n    }\n\n    // We do not check predicates here because we have checked them\n    // on-the-fly when doing full context prediction.\n\n    /*\n\t\tIn non-exact ambiguity detection mode, we might\tactually be able to\n\t\tdetect an exact ambiguity, but I'm not going to spend the cycles\n\t\tneeded to check. We only emit ambiguity warnings in exact ambiguity\n\t\tmode.\n\n\t\tFor example, we might know that we have conflicting configurations.\n\t\tBut, that does not mean that there is no way forward without a\n\t\tconflict. It's possible to have nonconflicting alt subsets as in:\n\n\t\t   LL altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n\n\t\tfrom\n\n\t\t   [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n\t\t\t(13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n\n\t\tIn this case, (17,1,[5 $]) indicates there is some next sequence that\n\t\twould resolve this without conflict to alternative 1. Any other viable\n\t\tnext sequence, however, is associated with a conflict.  We stop\n\t\tlooking for input because no amount of further lookahead will alter\n\t\tthe fact that we should predict alternative 1.  We just can't say for\n\t\tsure that there is an ambiguity without looking further.\n\t\t*/\n    reportAmbiguity(\n        dfa, D, startIndex, input.index, foundExactAmbig, reach.alts, reach);\n\n    return predictedAlt;\n  }\n\n  ATNConfigSet? computeReachSet(ATNConfigSet config, int t, bool fullCtx) {\n    if (debug) log('in computeReachSet, starting closure: $config');\n\n    mergeCache ??= {};\n\n    final intermediate = ATNConfigSet(fullCtx);\n\n    /* Configurations already in a rule stop state indicate reaching the end\n\t\t * of the decision rule (local context) or end of the start rule (full\n\t\t * context). Once reached, these configurations are never updated by a\n\t\t * closure operation, so they are handled separately for the performance\n\t\t * advantage of having a smaller intermediate set when calling closure.\n\t\t *\n\t\t * For full-context reach operations, separate handling is required to\n\t\t * ensure that the alternative matching the longest overall sequence is\n\t\t * chosen when multiple such configurations can match the input.\n\t\t */\n    List<ATNConfig>? skippedStopStates;\n\n    // First figure out where we can reach on input t\n    for (var c in config) {\n      if (debug) log('testing ' + getTokenName(t) + ' at ' + c.toString());\n\n      if (c.state is RuleStopState) {\n        assert(c.context!.isEmpty);\n        if (fullCtx || t == IntStream.EOF) {\n          skippedStopStates ??= [];\n\n          skippedStopStates.add(c);\n        }\n\n        continue;\n      }\n\n      final n = c.state.numberOfTransitions;\n      for (var ti = 0; ti < n; ti++) {\n        // for each transition\n        final trans = c.state.transition(ti);\n        final target = getReachableTarget(trans, t);\n        if (target != null) {\n          intermediate.add(ATNConfig.dup(c, state: target), mergeCache);\n        }\n      }\n    }\n\n    // Now figure out where the reach operation can take us...\n\n    ATNConfigSet? reach;\n\n    /* This block optimizes the reach operation for intermediate sets which\n\t\t * trivially indicate a termination state for the overall\n\t\t * adaptivePredict operation.\n\t\t *\n\t\t * The conditions assume that intermediate\n\t\t * contains all configurations relevant to the reach set, but this\n\t\t * condition is not true when one or more configurations have been\n\t\t * withheld in skippedStopStates, or when the current symbol is EOF.\n\t\t */\n    if (skippedStopStates == null && t != Token.EOF) {\n      if (intermediate.length == 1) {\n        // Don't pursue the closure if there is just one state.\n        // It can only have one alternative; just add to result\n        // Also don't pursue the closure if there is unique alternative\n        // among the configurations.\n        reach = intermediate;\n      } else if (getUniqueAlt(intermediate) != ATN.INVALID_ALT_NUMBER) {\n        // Also don't pursue the closure if there is unique alternative\n        // among the configurations.\n        reach = intermediate;\n      }\n    }\n\n    /* If the reach set could not be trivially determined, perform a closure\n\t\t * operation on the intermediate set to compute its initial value.\n\t\t */\n    if (reach == null) {\n      reach = ATNConfigSet(fullCtx);\n      final closureBusy = <ATNConfig>{};\n      final treatEofAsEpsilon = t == Token.EOF;\n      for (var c in intermediate) {\n        closure(c, reach, closureBusy, false, fullCtx, treatEofAsEpsilon);\n      }\n    }\n\n    if (t == IntStream.EOF) {\n      /* After consuming EOF no additional input is possible, so we are\n\t\t\t * only interested in configurations which reached the end of the\n\t\t\t * decision rule (local context) or end of the start rule (full\n\t\t\t * context). Update reach to contain only these configurations. This\n\t\t\t * handles both explicit EOF transitions in the grammar and implicit\n\t\t\t * EOF transitions following the end of the decision or start rule.\n\t\t\t *\n\t\t\t * When reach==intermediate, no closure operation was performed. In\n\t\t\t * this case, removeAllConfigsNotInRuleStopState needs to check for\n\t\t\t * reachable rule stop states as well as configurations already in\n\t\t\t * a rule stop state.\n\t\t\t *\n\t\t\t * This is handled before the configurations in skippedStopStates,\n\t\t\t * because any configurations potentially added from that list are\n\t\t\t * already guaranteed to meet this condition whether or not it's\n\t\t\t * required.\n\t\t\t */\n      reach = removeAllConfigsNotInRuleStopState(reach, reach == intermediate);\n    }\n\n    /* If skippedStopStates is not null, then it contains at least one\n\t\t * configuration. For full-context reach operations, these\n\t\t * configurations reached the end of the start rule, in which case we\n\t\t * only add them back to reach if no configuration during the current\n\t\t * closure operation reached such a state. This ensures adaptivePredict\n\t\t * chooses an alternative matching the longest overall sequence when\n\t\t * multiple alternatives are viable.\n\t\t */\n    if (skippedStopStates != null &&\n        (!fullCtx ||\n            !PredictionModeExtension.hasConfigInRuleStopState(reach))) {\n      assert(skippedStopStates.isNotEmpty);\n      for (var c in skippedStopStates) {\n        reach.add(c, mergeCache);\n      }\n    }\n\n    if (reach.isEmpty) return null;\n    return reach;\n  }\n\n  /// Return a configuration set containing only the configurations from\n  /// [configs] which are in a [RuleStopState]. If all\n  /// configurations in [configs] are already in a rule stop state, this\n  /// method simply returns [configs].\n  ///\n  /// <p>When [lookToEndOfRule] is true, this method uses\n  /// {@link ATN#nextTokens} for each configuration in [configs] which is\n  /// not already in a rule stop state to see if a rule stop state is reachable\n  /// from the configuration via epsilon-only transitions.</p>\n  ///\n  /// @param configs the configuration set to update\n  /// @param lookToEndOfRule when true, this method checks for rule stop states\n  /// reachable by epsilon-only transitions from each configuration in\n  /// [configs].\n  ///\n  /// @return [configs] if all configurations in [configs] are in a\n  /// rule stop state, otherwise return a new configuration set containing only\n  /// the configurations from [configs] which are in a rule stop state\n  ATNConfigSet removeAllConfigsNotInRuleStopState(\n      ATNConfigSet configs, bool lookToEndOfRule) {\n    if (PredictionModeExtension.allConfigsInRuleStopStates(configs)) {\n      return configs;\n    }\n\n    final result = ATNConfigSet(configs.fullCtx);\n    for (var config in configs) {\n      if (config.state is RuleStopState) {\n        result.add(config, mergeCache);\n        continue;\n      }\n\n      if (lookToEndOfRule && config.state.onlyHasEpsilonTransitions()) {\n        final nextTokens = atn.nextTokens(config.state);\n        if (nextTokens.contains(Token.EPSILON)) {\n          ATNState endOfRuleState = atn.ruleToStopState[config.state.ruleIndex];\n          result.add(ATNConfig.dup(config, state: endOfRuleState), mergeCache);\n        }\n      }\n    }\n\n    return result;\n  }\n\n  ATNConfigSet computeStartState(ATNState p, RuleContext ctx, bool fullCtx) {\n    // always at least the implicit call to start rule\n    final initialContext = PredictionContext.fromRuleContext(atn, ctx);\n    final configs = ATNConfigSet(fullCtx);\n\n    for (var i = 0; i < p.numberOfTransitions; i++) {\n      final target = p.transition(i).target;\n      final c = ATNConfig(target, i + 1, initialContext);\n      final closureBusy = <ATNConfig>{};\n      closure(c, configs, closureBusy, true, fullCtx, false);\n    }\n\n    return configs;\n  }\n\n  /* parrt internal source braindump that doesn't mess up\n\t * external API spec.\n\t\tcontext-sensitive in that they can only be properly evaluated\n\t\tin the context of the proper prec argument. Without pruning,\n\t\tthese predicates are normal predicates evaluated when we reach\n\t\tconflict state (or unique prediction). As we cannot evaluate\n\t\tthese predicates out of context, the resulting conflict leads\n\t\tto full LL evaluation and nonlinear prediction which shows up\n\t\tvery clearly with fairly large expressions.\n\n\t\tExample grammar:\n\n\t\te : e '*' e\n\t\t  | e '+' e\n\t\t  | INT\n\t\t  ;\n\n\t\tWe convert that to the following:\n\n\t\te[int prec]\n\t\t\t:   INT\n\t\t\t\t( {3>=prec}? '*' e[4]\n\t\t\t\t| {2>=prec}? '+' e[3]\n\t\t\t\t)*\n\t\t\t;\n\n\t\tThe (..)* loop has a decision for the inner block as well as\n\t\tan enter or exit decision, which is what concerns us here. At\n\t\tthe 1st + of input 1+2+3, the loop entry sees both predicates\n\t\tand the loop exit also sees both predicates by falling off the\n\t\tedge of e.  This is because we have no stack information with\n\t\tSLL and find the follow of e, which will hit the return states\n\t\tinside the loop after e[4] and e[3], which brings it back to\n\t\tthe enter or exit decision. In this case, we know that we\n\t\tcannot evaluate those predicates because we have fallen off\n\t\tthe edge of the stack and will in general not know which prec\n\t\tparameter is the right one to use in the predicate.\n\n\t\tBecause we have special information, that these are precedence\n\t\tpredicates, we can resolve them without failing over to full\n\t\tLL despite their context sensitive nature. We make an\n\t\tassumption that prec[-1] <= prec[0], meaning that the current\n\t\tprecedence level is greater than or equal to the precedence\n\t\tlevel of recursive invocations above us in the stack. For\n\t\texample, if predicate {3>=prec}? is true of the current prec,\n\t\tthen one option is to enter the loop to match it now. The\n\t\tother option is to exit the loop and the left recursive rule\n\t\tto match the current operator in rule invocation further up\n\t\tthe stack. But, we know that all of those prec are lower or\n\t\tthe same value and so we can decide to enter the loop instead\n\t\tof matching it later. That means we can strip out the other\n\t\tconfiguration for the exit branch.\n\n\t\tSo imagine we have (14,1,$,{2>=prec}?) and then\n\t\t(14,2,$-dipsIntoOuterContext,{2>=prec}?). The optimization\n\t\tallows us to collapse these two configurations. We know that\n\t\tif {2>=prec}? is true for the current prec parameter, it will\n\t\talso be true for any prec from an invoking e call, indicated\n\t\tby dipsIntoOuterContext. As the predicates are both true, we\n\t\thave the option to evaluate them early in the decision start\n\t\tstate. We do this by stripping both predicates and choosing to\n\t\tenter the loop as it is consistent with the notion of operator\n\t\tprecedence. It's also how the full LL conflict resolution\n\t\twould work.\n\n\t\tThe solution requires a different DFA start state for each\n\t\tprecedence level.\n\n\t\tThe basic filter mechanism is to remove configurations of the\n\t\tform (p, 2, pi) if (p, 1, pi) exists for the same p and pi. In\n\t\tother words, for the same ATN state and predicate context,\n\t\tremove any configuration associated with an exit branch if\n\t\tthere is a configuration associated with the enter branch.\n\n\t\tIt's also the case that the filter evaluates precedence\n\t\tpredicates and resolves conflicts according to precedence\n\t\tlevels. For example, for input 1+2+3 at the first +, we see\n\t\tprediction filtering\n\n\t\t[(11,1,[$],{3>=prec}?), (14,1,[$],{2>=prec}?), (5,2,[$],up=1),\n\t\t (11,2,[$],up=1), (14,2,[$],up=1)],hasSemanticContext=true,dipsIntoOuterContext\n\n\t\tto\n\n\t\t[(11,1,[$]), (14,1,[$]), (5,2,[$],up=1)],dipsIntoOuterContext\n\n\t\tThis filters because {3>=prec}? evals to true and collapses\n\t\t(11,1,[$],{3>=prec}?) and (11,2,[$],up=1) since early conflict\n\t\tresolution based upon rules of operator precedence fits with\n\t\tour usual match first alt upon conflict.\n\n\t\tWe noticed a problem where a recursive call resets precedence\n\t\tto 0. Sam's fix: each config has flag indicating if it has\n\t\treturned from an expr[0] call. then just don't filter any\n\t\tconfig with that flag set. flag is carried along in\n\t\tclosure(). so to avoid adding field, set bit just under sign\n\t\tbit of dipsIntoOuterContext (SUPPRESS_PRECEDENCE_FILTER).\n\t\tWith the change you filter \"unless (p, 2, pi) was reached\n\t\tafter leaving the rule stop state of the LR rule containing\n\t\tstate p, corresponding to a rule invocation with precedence\n\t\tlevel 0\"\n\t */\n\n  /// This method transforms the start state computed by\n  /// {@link #computeStartState} to the special start state used by a\n  /// precedence DFA for a particular precedence value. The transformation\n  /// process applies the following changes to the start state's configuration\n  /// set.\n  ///\n  /// <ol>\n  /// <li>Evaluate the precedence predicates for each configuration using\n  /// {@link SemanticContext#evalPrecedence}.</li>\n  /// <li>When {@link ATNConfig#isPrecedenceFilterSuppressed} is [false],\n  /// remove all configurations which predict an alternative greater than 1,\n  /// for which another configuration that predicts alternative 1 is in the\n  /// same ATN state with the same prediction context. This transformation is\n  /// valid for the following reasons:\n  /// <ul>\n  /// <li>The closure block cannot contain any epsilon transitions which bypass\n  /// the body of the closure, so all states reachable via alternative 1 are\n  /// part of the precedence alternatives of the transformed left-recursive\n  /// rule.</li>\n  /// <li>The \"primary\" portion of a left recursive rule cannot contain an\n  /// epsilon transition, so the only way an alternative other than 1 can exist\n  /// in a state that is also reachable via alternative 1 is by nesting calls\n  /// to the left-recursive rule, with the outer calls not being at the\n  /// preferred precedence level. The\n  /// {@link ATNConfig#isPrecedenceFilterSuppressed} property marks ATN\n  /// configurations which do not meet this condition, and therefore are not\n  /// eligible for elimination during the filtering process.</li>\n  /// </ul>\n  /// </li>\n  /// </ol>\n  ///\n  /// <p>\n  /// The prediction context must be considered by this filter to address\n  /// situations like the following.\n  /// </p>\n  /// <code>\n  /// <pre>\n  /// grammar TA;\n  /// prog: statement* EOF;\n  /// statement: letterA | statement letterA 'b' ;\n  /// letterA: 'a';\n  /// </pre>\n  /// </code>\n  /// <p>\n  /// If the above grammar, the ATN state immediately before the token\n  /// reference {@code 'a'} in [letterA] is reachable from the left edge\n  /// of both the primary and closure blocks of the left-recursive rule\n  /// [statement]. The prediction context associated with each of these\n  /// configurations distinguishes between them, and prevents the alternative\n  /// which stepped out to [prog] (and then back in to [statement]\n  /// from being eliminated by the filter.\n  /// </p>\n  ///\n  /// @param configs The configuration set computed by\n  /// {@link #computeStartState} as the start state for the DFA.\n  /// @return The transformed configuration set representing the start state\n  /// for a precedence DFA at a particular precedence level (determined by\n  /// calling {@link Parser#getPrecedence}).\n  ATNConfigSet applyPrecedenceFilter(ATNConfigSet configs) {\n    final statesFromAlt1 = <int, PredictionContext>{};\n    final configSet = ATNConfigSet(configs.fullCtx);\n    for (var config in configs) {\n      // handle alt 1 first\n      if (config.alt != 1) {\n        continue;\n      }\n\n      final updatedContext = config.semanticContext.evalPrecedence(\n        parser,\n        _outerContext,\n      );\n      if (updatedContext == null) {\n        // the configuration was eliminated\n        continue;\n      }\n      assert(config.context != null);\n      final configContext = config.context!;\n\n      statesFromAlt1[config.state.stateNumber] = configContext;\n      if (updatedContext != config.semanticContext) {\n        configSet.add(\n            ATNConfig.dup(config, semanticContext: updatedContext), mergeCache);\n      } else {\n        configSet.add(config, mergeCache);\n      }\n    }\n\n    for (var config in configs) {\n      if (config.alt == 1) {\n        // already handled\n        continue;\n      }\n\n      if (!config.isPrecedenceFilterSuppressed()) {\n        /* In the future, this elimination step could be updated to also\n\t\t\t\t * filter the prediction context for alternatives predicting alt>1\n\t\t\t\t * (basically a graph subtraction algorithm).\n\t\t\t\t */\n        assert(config.context != null);\n        final configContext = config.context!;\n        final context = statesFromAlt1[config.state.stateNumber];\n        if (context != null && context == configContext) {\n          // eliminated\n          continue;\n        }\n      }\n\n      configSet.add(config, mergeCache);\n    }\n\n    return configSet;\n  }\n\n  ATNState? getReachableTarget(Transition trans, int ttype) {\n    if (trans.matches(ttype, 0, atn.maxTokenType)) {\n      return trans.target;\n    }\n\n    return null;\n  }\n\n  List<SemanticContext?>? getPredsForAmbigAlts(\n    BitSet ambigAlts,\n    ATNConfigSet configs,\n    int nalts,\n  ) {\n    // REACH=[1|1|[]|0:0, 1|2|[]|0:1]\n    /* altToPred starts as an array of all null contexts. The entry at index i\n\t\t * corresponds to alternative i. altToPred[i] may have one of three values:\n\t\t *   1. null: no ATNConfig c is found such that c.alt==i\n\t\t *   2. SemanticContext.NONE: At least one ATNConfig c exists such that\n\t\t *      c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,\n\t\t *      alt i has at least one unpredicated config.\n\t\t *   3. Non-NONE Semantic Context: There exists at least one, and for all\n\t\t *      ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.\n\t\t *\n\t\t * From this, it is clear that NONE||anything==NONE.\n\t\t */\n    final altToPred = List<SemanticContext?>.filled(nalts + 1, null);\n\n    for (var c in configs) {\n      if (ambigAlts[c.alt]) {\n        altToPred[c.alt] =\n            SemanticContext.or(altToPred[c.alt], c.semanticContext);\n      }\n    }\n\n    var nPredAlts = 0;\n    for (var i = 1; i <= nalts; i++) {\n      if (altToPred[i] == null) {\n        altToPred[i] = EmptySemanticContext.Instance;\n      } else if (altToPred[i] != EmptySemanticContext.Instance) {\n        nPredAlts++;\n      }\n    }\n\n//\t\t// Optimize away p||p and p&&p TODO: optimize() was a no-op\n//\t\tfor (int i = 0; i < altToPred.length; i++) {\n//\t\t\taltToPred[i] = altToPred[i].optimize();\n//\t\t}\n\n    if (debug) log('getPredsForAmbigAlts result $altToPred');\n    // nonambig alts are null in altToPred\n    if (nPredAlts == 0) return null;\n    return altToPred;\n  }\n\n  List<PredPrediction>? getPredicatePredictions(\n    BitSet? ambigAlts,\n    List<SemanticContext?> altToPred,\n  ) {\n    final pairs = <PredPrediction>[];\n    var containsPredicate = false;\n    for (var i = 1; i < altToPred.length; i++) {\n      final pred = altToPred[i];\n\n      // unpredicated is indicated by SemanticContext.NONE\n      assert(pred != null);\n\n      if (ambigAlts != null && ambigAlts[i]) {\n        pairs.add(PredPrediction(pred!, i));\n      }\n      if (pred != EmptySemanticContext.Instance) containsPredicate = true;\n    }\n\n    if (!containsPredicate) {\n      return null;\n    }\n\n//\t\tlog(Arrays.toString(altToPred)+\"->\"+pairs);\n    return pairs;\n  }\n\n  /// This method is used to improve the localization of error messages by\n  /// choosing an alternative rather than throwing a\n  /// [NoViableAltException] in particular prediction scenarios where the\n  /// {@link #ERROR} state was reached during ATN simulation.\n  ///\n  /// <p>\n  /// The default implementation of this method uses the following\n  /// algorithm to identify an ATN configuration which successfully parsed the\n  /// decision entry rule. Choosing such an alternative ensures that the\n  /// [ParserRuleContext] returned by the calling rule will be complete\n  /// and valid, and the syntax error will be reported later at a more\n  /// localized location.</p>\n  ///\n  /// <ul>\n  /// <li>If a syntactically valid path or paths reach the end of the decision rule and\n  /// they are semantically valid if predicated, return the min associated alt.</li>\n  /// <li>Else, if a semantically invalid but syntactically valid path exist\n  /// or paths exist, return the minimum associated alt.\n  /// </li>\n  /// <li>Otherwise, return {@link ATN#INVALID_ALT_NUMBER}.</li>\n  /// </ul>\n  ///\n  /// <p>\n  /// In some scenarios, the algorithm described above could predict an\n  /// alternative which will result in a [FailedPredicateException] in\n  /// the parser. Specifically, this could occur if the <em>only</em> configuration\n  /// capable of successfully parsing to the end of the decision rule is\n  /// blocked by a semantic predicate. By choosing this alternative within\n  /// {@link #adaptivePredict} instead of throwing a\n  /// [NoViableAltException], the resulting\n  /// [FailedPredicateException] in the parser will identify the specific\n  /// predicate which is preventing the parser from successfully parsing the\n  /// decision rule, which helps developers identify and correct logic errors\n  /// in semantic predicates.\n  /// </p>\n  ///\n  /// @param configs The ATN configurations which were valid immediately before\n  /// the {@link #ERROR} state was reached\n  /// @param outerContext The is the \\gamma_0 initial parser context from the paper\n  /// or the parser stack at the instant before prediction commences.\n  ///\n  /// @return The value to return from {@link #adaptivePredict}, or\n  /// {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not\n  /// identified and {@link #adaptivePredict} should report an error instead.\n  int getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(\n      ATNConfigSet configs, ParserRuleContext outerContext) {\n    final sets = splitAccordingToSemanticValidity(configs, outerContext);\n    final semValidConfigs = sets.a;\n    final semInvalidConfigs = sets.b;\n    var alt = getAltThatFinishedDecisionEntryRule(semValidConfigs);\n    if (alt != ATN.INVALID_ALT_NUMBER) {\n      // semantically/syntactically viable path exists\n      return alt;\n    }\n    // Is there a syntactically valid path with a failed pred?\n    if (semInvalidConfigs.isNotEmpty) {\n      alt = getAltThatFinishedDecisionEntryRule(semInvalidConfigs);\n      if (alt != ATN.INVALID_ALT_NUMBER) {\n        // syntactically viable path exists\n        return alt;\n      }\n    }\n    return ATN.INVALID_ALT_NUMBER;\n  }\n\n  int getAltThatFinishedDecisionEntryRule(ATNConfigSet configs) {\n    final alts = IntervalSet();\n    for (var c in configs) {\n      assert(c.context != null);\n      if (c.outerContextDepth > 0 ||\n          (c.state is RuleStopState && c.context!.hasEmptyPath())) {\n        alts.addOne(c.alt);\n      }\n    }\n    if (alts.length == 0) return ATN.INVALID_ALT_NUMBER;\n    return alts.minElement;\n  }\n\n  /// Walk the list of configurations and split them according to\n  ///  those that have preds evaluating to true/false.  If no pred, assume\n  ///  true pred and include in succeeded set.  Returns Pair of sets.\n  ///\n  ///  Create a new set so as not to alter the incoming parameter.\n  ///\n  ///  Assumption: the input stream has been restored to the starting point\n  ///  prediction, which is where predicates need to evaluate.\n  Pair<ATNConfigSet, ATNConfigSet> splitAccordingToSemanticValidity(\n    ATNConfigSet configs,\n    ParserRuleContext outerContext,\n  ) {\n    final succeeded = ATNConfigSet(configs.fullCtx);\n    final failed = ATNConfigSet(configs.fullCtx);\n    for (var c in configs) {\n      if (c.semanticContext != EmptySemanticContext.Instance) {\n        final predicateEvaluationResult = evalSemanticContextOne(\n          c.semanticContext,\n          outerContext,\n          c.alt,\n          configs.fullCtx,\n        );\n        if (predicateEvaluationResult) {\n          succeeded.add(c);\n        } else {\n          failed.add(c);\n        }\n      } else {\n        succeeded.add(c);\n      }\n    }\n    return Pair<ATNConfigSet, ATNConfigSet>(succeeded, failed);\n  }\n\n  /// Look through a list of predicate/alt pairs, returning alts for the\n  ///  pairs that win. A [Instance] predicate indicates an alt containing an\n  ///  unpredicated config which behaves as \"always true.\" If !complete\n  ///  then we stop at the first predicate that evaluates to true. This\n  ///  includes pairs with null predicates.\n  BitSet evalSemanticContext(\n    List<PredPrediction> predPredictions,\n    ParserRuleContext outerContext,\n    bool complete,\n  ) {\n    final predictions = BitSet();\n    for (var pair in predPredictions) {\n      if (pair.pred == EmptySemanticContext.Instance) {\n        predictions.set(pair.alt);\n        if (!complete) {\n          break;\n        }\n        continue;\n      }\n\n      final fullCtx = false; // in dfa\n      final predicateEvaluationResult =\n          evalSemanticContextOne(pair.pred, outerContext, pair.alt, fullCtx);\n      if (debug || dfa_debug) {\n        log('eval pred $pair=$predicateEvaluationResult');\n      }\n\n      if (predicateEvaluationResult) {\n        if (debug || dfa_debug) log('PREDICT ' + pair.alt.toString());\n        predictions.set(pair.alt);\n        if (!complete) {\n          break;\n        }\n      }\n    }\n\n    return predictions;\n  }\n\n  /// Evaluate a semantic context within a specific parser context.\n  ///\n  /// <p>\n  /// This method might not be called for every semantic context evaluated\n  /// during the prediction process. In particular, we currently do not\n  /// evaluate the following but it may change in the future:</p>\n  ///\n  /// <ul>\n  /// <li>Precedence predicates (represented by\n  /// {@link SemanticContext.PrecedencePredicate}) are not currently evaluated\n  /// through this method.</li>\n  /// <li>Operator predicates (represented by {@link SemanticContext.AND} and\n  /// {@link SemanticContext.OR}) are evaluated as a single semantic\n  /// context, rather than evaluating the operands individually.\n  /// Implementations which require evaluation results from individual\n  /// predicates should override this method to explicitly handle evaluation of\n  /// the operands within operator predicates.</li>\n  /// </ul>\n  ///\n  /// @param pred The semantic context to evaluate\n  /// @param parserCallStack The parser context in which to evaluate the\n  /// semantic context\n  /// @param alt The alternative which is guarded by [pred]\n  /// @param fullCtx [true] if the evaluation is occurring during LL\n  /// prediction; otherwise, [false] if the evaluation is occurring\n  /// during SLL prediction\n  ///\n  /// @since 4.3\n  bool evalSemanticContextOne(\n    SemanticContext pred,\n    ParserRuleContext? parserCallStack,\n    int alt,\n    bool fullCtx,\n  ) {\n    return pred.eval(parser, parserCallStack);\n  }\n\n  /* TODO: If we are doing predicates, there is no point in pursuing\n\t\t closure operations if we reach a DFA state that uniquely predicts\n\t\t alternative. We will not be caching that DFA state and it is a\n\t\t waste to pursue the closure. Might have to advance when we do\n\t\t ambig detection thought :(\n\t\t  */\n\n  void closure(\n      ATNConfig config,\n      ATNConfigSet configs,\n      Set<ATNConfig> closureBusy,\n      bool collectPredicates,\n      bool fullCtx,\n      bool treatEofAsEpsilon) {\n    final initialDepth = 0;\n    closureCheckingStopState(config, configs, closureBusy, collectPredicates,\n        fullCtx, initialDepth, treatEofAsEpsilon);\n    assert(!fullCtx || !configs.dipsIntoOuterContext);\n  }\n\n  void closureCheckingStopState(\n      ATNConfig config,\n      ATNConfigSet configs,\n      Set<ATNConfig> closureBusy,\n      bool collectPredicates,\n      bool fullCtx,\n      int depth,\n      bool treatEofAsEpsilon) {\n    if (debug) log('closure(' + config.toString(parser, true) + ')');\n\n    assert(config.context != null);\n\n    final configContext = config.context!;\n\n    if (config.state is RuleStopState) {\n      // We hit rule end. If we have context info, use it\n      // run thru all possible stack tops in ctx\n      if (!configContext.isEmpty) {\n        for (var i = 0; i < configContext.length; i++) {\n          if (configContext.getReturnState(i) ==\n              PredictionContext.EMPTY_RETURN_STATE) {\n            if (fullCtx) {\n              configs.add(\n                  ATNConfig.dup(\n                    config,\n                    state: config.state,\n                    context: EmptyPredictionContext.Instance,\n                  ),\n                  mergeCache);\n              continue;\n            } else {\n              // we have no context info, just chase follow links (if greedy)\n              if (debug) {\n                log('FALLING off rule ' + getRuleName(config.state.ruleIndex));\n              }\n              closure_(\n                config,\n                configs,\n                closureBusy,\n                collectPredicates,\n                fullCtx,\n                depth,\n                treatEofAsEpsilon,\n              );\n            }\n            continue;\n          }\n          final returnState = atn.states[configContext.getReturnState(i)]!;\n          final newContext = configContext.getParent(i); // \"pop\" return state\n          final c = ATNConfig(\n            returnState,\n            config.alt,\n            newContext,\n            config.semanticContext,\n          );\n          // While we have context to pop back from, we may have\n          // gotten that context AFTER having falling off a rule.\n          // Make sure we track that we are now out of context.\n          //\n          // This assignment also propagates the\n          // isPrecedenceFilterSuppressed() value to the new\n          // configuration.\n          c.reachesIntoOuterContext = config.reachesIntoOuterContext;\n//          assert(depth > int.MIN_VALUE);\n          closureCheckingStopState(c, configs, closureBusy, collectPredicates,\n              fullCtx, depth - 1, treatEofAsEpsilon);\n        }\n        return;\n      } else if (fullCtx) {\n        // reached end of start rule\n        configs.add(config, mergeCache);\n        return;\n      } else {\n        // else if we have no context info, just chase follow links (if greedy)\n        if (debug) {\n          log('FALLING off rule ' + getRuleName(config.state.ruleIndex));\n        }\n      }\n    }\n\n    closure_(\n      config,\n      configs,\n      closureBusy,\n      collectPredicates,\n      fullCtx,\n      depth,\n      treatEofAsEpsilon,\n    );\n  }\n\n  /// Do the actual work of walking epsilon edges */\n  void closure_(\n      ATNConfig config,\n      ATNConfigSet configs,\n      Set<ATNConfig> closureBusy,\n      bool collectPredicates,\n      bool fullCtx,\n      int depth,\n      bool treatEofAsEpsilon) {\n    final p = config.state;\n    // optimization\n    if (!p.onlyHasEpsilonTransitions()) {\n      configs.add(config, mergeCache);\n      // make sure to not return here, because EOF transitions can act as\n      // both epsilon transitions and non-epsilon transitions.\n//            if ( debug ) log(\"added config \"+configs);\n    }\n\n    for (var i = 0; i < p.numberOfTransitions; i++) {\n      if (i == 0 && canDropLoopEntryEdgeInLeftRecursiveRule(config)) continue;\n\n      final t = p.transition(i);\n      final continueCollecting = (t is! ActionTransition) && collectPredicates;\n      final c = getEpsilonTarget(config, t, continueCollecting, depth == 0,\n          fullCtx, treatEofAsEpsilon);\n      if (c != null) {\n        var newDepth = depth;\n        if (config.state is RuleStopState) {\n          assert(!fullCtx);\n          // target fell off end of rule; mark resulting c as having dipped into outer context\n          // We can't get here if incoming config was rule stop and we had context\n          // track how far we dip into outer context.  Might\n          // come in handy and we avoid evaluating context dependent\n          // preds if this is > 0.\n\n          if (_dfa != null && _dfa!.isPrecedenceDfa()) {\n            final outermostPrecedenceReturn =\n                (t as EpsilonTransition).outermostPrecedenceReturn;\n            if (outermostPrecedenceReturn == _dfa!.atnStartState!.ruleIndex) {\n              c.setPrecedenceFilterSuppressed(true);\n            }\n          }\n\n          c.reachesIntoOuterContext++;\n\n          if (!closureBusy.add(c)) {\n            // avoid infinite recursion for right-recursive rules\n            continue;\n          }\n\n          // TODO: can remove? only care when we add to set per middle of this method\n          configs.dipsIntoOuterContext = true;\n//          assert(newDepth > int.MIN_VALUE);\n          newDepth--;\n          if (debug) log('dips into outer ctx: $c');\n        } else {\n          if (!t.isEpsilon && !closureBusy.add(c)) {\n            // avoid infinite recursion for EOF* and EOF+\n            continue;\n          }\n\n          if (t is RuleTransition) {\n            // latch when newDepth goes negative - once we step out of the entry context we can't return\n            if (newDepth >= 0) {\n              newDepth++;\n            }\n          }\n        }\n\n        closureCheckingStopState(\n          c,\n          configs,\n          closureBusy,\n          continueCollecting,\n          fullCtx,\n          newDepth,\n          treatEofAsEpsilon,\n        );\n      }\n    }\n  }\n\n  /// Implements first-edge (loop entry) elimination as an optimization\n  ///  during closure operations.  See antlr/antlr4#1398.\n  ///\n  /// The optimization is to avoid adding the loop entry config when\n  /// the exit path can only lead back to the same\n  /// StarLoopEntryState after popping context at the rule end state\n  /// (traversing only epsilon edges, so we're still in closure, in\n  /// this same rule).\n  ///\n  /// We need to detect any state that can reach loop entry on\n  /// epsilon w/o exiting rule. We don't have to look at FOLLOW\n  /// links, just ensure that all stack tops for config refer to key\n  /// states in LR rule.\n  ///\n  /// To verify we are in the right situation we must first check\n  /// closure is at a StarLoopEntryState generated during LR removal.\n  /// Then we check that each stack top of context is a return state\n  /// from one of these cases:\n  ///\n  ///   1. 'not' expr, '(' type ')' expr. The return state points at loop entry state\n  ///   2. expr op expr. The return state is the block end of internal block of (...)*\n  ///   3. 'between' expr 'and' expr. The return state of 2nd expr reference.\n  ///      That state points at block end of internal block of (...)*.\n  ///   4. expr '?' expr ':' expr. The return state points at block end,\n  ///      which points at loop entry state.\n  ///\n  /// If any is true for each stack top, then closure does not add a\n  /// config to the current config set for edge[0], the loop entry branch.\n  ///\n  ///  Conditions fail if any context for the current config is:\n  ///\n  ///   a. empty (we'd fall out of expr to do a global FOLLOW which could\n  ///      even be to some weird spot in expr) or,\n  ///   b. lies outside of expr or,\n  ///   c. lies within expr but at a state not the BlockEndState\n  ///   generated during LR removal\n  ///\n  /// Do we need to evaluate predicates ever in closure for this case?\n  ///\n  /// No. Predicates, including precedence predicates, are only\n  /// evaluated when computing a DFA start state. I.e., only before\n  /// the lookahead (but not parser) consumes a token.\n  ///\n  /// There are no epsilon edges allowed in LR rule alt blocks or in\n  /// the \"primary\" part (ID here). If closure is in\n  /// StarLoopEntryState any lookahead operation will have consumed a\n  /// token as there are no epsilon-paths that lead to\n  /// StarLoopEntryState. We do not have to evaluate predicates\n  /// therefore if we are in the generated StarLoopEntryState of a LR\n  /// rule. Note that when making a prediction starting at that\n  /// decision point, decision d=2, compute-start-state performs\n  /// closure starting at edges[0], edges[1] emanating from\n  /// StarLoopEntryState. That means it is not performing closure on\n  /// StarLoopEntryState during compute-start-state.\n  ///\n  /// How do we know this always gives same prediction answer?\n  ///\n  /// Without predicates, loop entry and exit paths are ambiguous\n  /// upon remaining input +b (in, say, a+b). Either paths lead to\n  /// valid parses. Closure can lead to consuming + immediately or by\n  /// falling out of this call to expr back into expr and loop back\n  /// again to StarLoopEntryState to match +b. In this special case,\n  /// we choose the more efficient path, which is to take the bypass\n  /// path.\n  ///\n  /// The lookahead language has not changed because closure chooses\n  /// one path over the other. Both paths lead to consuming the same\n  /// remaining input during a lookahead operation. If the next token\n  /// is an operator, lookahead will enter the choice block with\n  /// operators. If it is not, lookahead will exit expr. Same as if\n  /// closure had chosen to enter the choice block immediately.\n  ///\n  /// Closure is examining one config (some loopentrystate, some alt,\n  /// context) which means it is considering exactly one alt. Closure\n  /// always copies the same alt to any derived configs.\n  ///\n  /// How do we know this optimization doesn't mess up precedence in\n  /// our parse trees?\n  ///\n  /// Looking through expr from left edge of stat only has to confirm\n  /// that an input, say, a+b+c; begins with any valid interpretation\n  /// of an expression. The precedence actually doesn't matter when\n  /// making a decision in stat seeing through expr. It is only when\n  /// parsing rule expr that we must use the precedence to get the\n  /// right interpretation and, hence, parse tree.\n  ///\n  /// @since 4.6\n  bool canDropLoopEntryEdgeInLeftRecursiveRule(ATNConfig config) {\n    if (TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT) return false;\n    final p = config.state;\n\n    assert(config.context != null);\n    // First check to see if we are in StarLoopEntryState generated during\n    // left-recursion elimination. For efficiency, also check if\n    // the context has an empty stack case. If so, it would mean\n    // global FOLLOW so we can't perform optimization\n    if (p.stateType != StateType.STAR_LOOP_ENTRY ||\n        !(p as StarLoopEntryState)\n            .isPrecedenceDecision || // Are we the special loop entry/exit state?\n        config.context!.isEmpty || // If SLL wildcard\n        config.context!.hasEmptyPath()) {\n      return false;\n    }\n\n    final configContext = config.context!;\n\n    // Require all return states to return back to the same rule\n    // that p is in.\n    final numCtxs = configContext.length;\n    for (var i = 0; i < numCtxs; i++) {\n      // for each stack context\n      final returnState = atn.states[configContext.getReturnState(i)]!;\n      if (returnState.ruleIndex != p.ruleIndex) return false;\n    }\n\n    final decisionStartState = p.transition(0).target as BlockStartState;\n    final blockEndStateNum = decisionStartState.endState!.stateNumber;\n    final blockEndState = atn.states[blockEndStateNum] as BlockEndState;\n\n    // Verify that the top of each stack context leads to loop entry/exit\n    // state through epsilon edges and w/o leaving rule.\n    for (var i = 0; i < numCtxs; i++) {\n      // for each stack context\n      final returnStateNumber = configContext.getReturnState(i);\n      final returnState = atn.states[returnStateNumber]!;\n      // all states must have single outgoing epsilon edge\n      if (returnState.numberOfTransitions != 1 ||\n          !returnState.transition(0).isEpsilon) {\n        return false;\n      }\n      // Look for prefix op case like 'not expr', (' type ')' expr\n      final returnStateTarget = returnState.transition(0).target;\n      if (returnState.stateType == StateType.BLOCK_END &&\n          returnStateTarget == p) {\n        continue;\n      }\n      // Look for 'expr op expr' or case where expr's return state is block end\n      // of (...)* internal block; the block end points to loop back\n      // which points to p but we don't need to check that\n      if (returnState == blockEndState) {\n        continue;\n      }\n      // Look for ternary expr ? expr : expr. The return state points at block end,\n      // which points at loop entry state\n      if (returnStateTarget == blockEndState) {\n        continue;\n      }\n      // Look for complex prefix 'between expr and expr' case where 2nd expr's\n      // return state points at block end state of (...)* internal block\n      if (returnStateTarget.stateType == StateType.BLOCK_END &&\n          returnStateTarget.numberOfTransitions == 1 &&\n          returnStateTarget.transition(0).isEpsilon &&\n          returnStateTarget.transition(0).target == p) {\n        continue;\n      }\n\n      // anything else ain't conforming\n      return false;\n    }\n\n    return true;\n  }\n\n  String getRuleName(int index) {\n    if (index >= 0) return parser.ruleNames[index];\n    return '<rule $index>';\n  }\n\n  ATNConfig? getEpsilonTarget(\n      ATNConfig config,\n      Transition t,\n      bool collectPredicates,\n      bool inContext,\n      bool fullCtx,\n      bool treatEofAsEpsilon) {\n    switch (t.type) {\n      case TransitionType.RULE:\n        return ruleTransition(config, t as RuleTransition);\n\n      case TransitionType.PRECEDENCE:\n        return precedenceTransition(\n          config,\n          t as PrecedencePredicateTransition,\n          collectPredicates,\n          inContext,\n          fullCtx,\n        );\n\n      case TransitionType.PREDICATE:\n        return predTransition(\n          config,\n          t as PredicateTransition,\n          collectPredicates,\n          inContext,\n          fullCtx,\n        );\n      case TransitionType.ACTION:\n        return actionTransition(config, t as ActionTransition);\n\n      case TransitionType.EPSILON:\n        return ATNConfig.dup(config, state: t.target);\n\n      case TransitionType.ATOM:\n      case TransitionType.RANGE:\n      case TransitionType.SET:\n        // EOF transitions act like epsilon transitions after the first EOF\n        // transition is traversed\n        if (treatEofAsEpsilon) {\n          if (t.matches(Token.EOF, 0, 1)) {\n            return ATNConfig.dup(config, state: t.target);\n          }\n        }\n\n        return null;\n\n      default:\n        return null;\n    }\n  }\n\n  ATNConfig actionTransition(ATNConfig config, ActionTransition t) {\n    if (debug) log('ACTION edge ${t.ruleIndex}:${t.actionIndex}');\n    return ATNConfig.dup(config, state: t.target);\n  }\n\n  ATNConfig? precedenceTransition(\n      ATNConfig config,\n      PrecedencePredicateTransition pt,\n      bool collectPredicates,\n      bool inContext,\n      bool fullCtx) {\n    if (debug) {\n      log('PRED (collectPredicates=$collectPredicates) ${pt.precedence}>=_p, ctx dependent=true');\n\n      log('context surrounding pred is ${parser.getRuleInvocationStack()}');\n    }\n\n    ATNConfig? c;\n    if (collectPredicates && inContext) {\n      if (fullCtx) {\n        // In full context mode, we can evaluate predicates on-the-fly\n        // during closure, which dramatically reduces the size of\n        // the config sets. It also obviates the need to test predicates\n        // later during conflict resolution.\n        final currentPosition = input.index;\n        input.seek(startIndex);\n        final predSucceeds = evalSemanticContextOne(\n            pt.predicate, _outerContext, config.alt, fullCtx);\n        input.seek(currentPosition);\n        if (predSucceeds) {\n          c = ATNConfig.dup(config, state: pt.target); // no pred context\n        }\n      } else {\n        final newSemCtx = SemanticContext.and(\n          config.semanticContext,\n          pt.predicate,\n        );\n        c = ATNConfig.dup(config, state: pt.target, semanticContext: newSemCtx);\n      }\n    } else {\n      c = ATNConfig.dup(config, state: pt.target);\n    }\n\n    if (debug) log('config from pred transition=$c');\n    return c;\n  }\n\n  ATNConfig? predTransition(\n    ATNConfig config,\n    PredicateTransition pt,\n    bool collectPredicates,\n    bool inContext,\n    bool fullCtx,\n  ) {\n    if (debug) {\n      log('PRED (collectPredicates=$collectPredicates) '\n          '${pt.ruleIndex}:${pt.predIndex}'\n          ', ctx dependent=${pt.isCtxDependent}');\n\n      log('context surrounding pred is ${parser.getRuleInvocationStack()}');\n    }\n\n    ATNConfig? c;\n    if (collectPredicates &&\n        (!pt.isCtxDependent || (pt.isCtxDependent && inContext))) {\n      if (fullCtx) {\n        // In full context mode, we can evaluate predicates on-the-fly\n        // during closure, which dramatically reduces the size of\n        // the config sets. It also obviates the need to test predicates\n        // later during conflict resolution.\n        final currentPosition = input.index;\n        input.seek(startIndex);\n        final predSucceeds = evalSemanticContextOne(\n          pt.predicate,\n          _outerContext,\n          config.alt,\n          fullCtx,\n        );\n        input.seek(currentPosition);\n        if (predSucceeds) {\n          c = ATNConfig.dup(config, state: pt.target); // no pred context\n        }\n      } else {\n        final newSemCtx =\n            SemanticContext.and(config.semanticContext, pt.predicate);\n        c = ATNConfig.dup(config, state: pt.target, semanticContext: newSemCtx);\n      }\n    } else {\n      c = ATNConfig.dup(config, state: pt.target);\n    }\n\n    if (debug) log('config from pred transition=$c');\n    return c;\n  }\n\n  ATNConfig ruleTransition(ATNConfig config, RuleTransition t) {\n    if (debug) {\n      log('CALL rule ' +\n          getRuleName(t.target.ruleIndex) +\n          ', ctx=${config.context}');\n    }\n\n    final returnState = t.followState;\n    PredictionContext newContext = SingletonPredictionContext.create(\n        config.context, returnState.stateNumber);\n    return ATNConfig.dup(config, state: t.target, context: newContext);\n  }\n\n  /// Gets a [BitSet] containing the alternatives in [configs]\n  /// which are part of one or more conflicting alternative subsets.\n  ///\n  /// @param configs The [ATNConfigSet] to analyze.\n  /// @return The alternatives in [configs] which are part of one or more\n  /// conflicting alternative subsets. If [configs] does not contain any\n  /// conflicting subsets, this method returns an empty [BitSet].\n  BitSet getConflictingAlts(ATNConfigSet configs) {\n    final altsets = PredictionModeExtension.getConflictingAltSubsets(configs);\n    return PredictionModeExtension.getAlts(altsets);\n  }\n\n  /// Sam pointed out a problem with the previous definition, v3, of\n  /// ambiguous states. If we have another state associated with conflicting\n  /// alternatives, we should keep going. For example, the following grammar\n  ///\n  /// s : (ID | ID ID?) ';' ;\n  ///\n  /// When the ATN simulation reaches the state before ';', it has a DFA\n  /// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally\n  /// 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node\n  /// because alternative to has another way to continue, via [6|2|[]].\n  /// The key is that we have a single state that has config's only associated\n  /// with a single alternative, 2, and crucially the state transitions\n  /// among the configurations are all non-epsilon transitions. That means\n  /// we don't consider any conflicts that include alternative 2. So, we\n  /// ignore the conflict between alts 1 and 2. We ignore a set of\n  /// conflicting alts when there is an intersection with an alternative\n  /// associated with a single alt state in the state&rarr;config-list map.\n  ///\n  /// It's also the case that we might have two conflicting configurations but\n  /// also a 3rd nonconflicting configuration for a different alternative:\n  /// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:\n  ///\n  /// a : A | A | A B ;\n  ///\n  /// After matching input A, we reach the stop state for rule A, state 1.\n  /// State 8 is the state right before B. Clearly alternatives 1 and 2\n  /// conflict and no amount of further lookahead will separate the two.\n  /// However, alternative 3 will be able to continue and so we do not\n  /// stop working on this state. In the previous example, we're concerned\n  /// with states associated with the conflicting alternatives. Here alt\n  /// 3 is not associated with the conflicting configs, but since we can continue\n  /// looking for input reasonably, I don't declare the state done. We\n  /// ignore a set of conflicting alts when we have an alternative\n  /// that we still need to pursue.\n  BitSet getConflictingAltsOrUniqueAlt(ATNConfigSet configs) {\n    BitSet? conflictingAlts;\n    if (configs.uniqueAlt != ATN.INVALID_ALT_NUMBER) {\n      conflictingAlts = BitSet();\n      conflictingAlts.set(configs.uniqueAlt);\n    } else {\n      conflictingAlts = configs.conflictingAlts;\n    }\n    return conflictingAlts!;\n  }\n\n  String getTokenName(int t) {\n    if (t == Token.EOF) {\n      return 'EOF';\n    }\n\n    final vocabulary = parser.vocabulary;\n    final displayName = vocabulary.getDisplayName(t);\n    if (displayName == t.toString()) {\n      return displayName;\n    }\n\n    return displayName + '<$t>';\n  }\n\n  String getLookaheadName(TokenStream input) {\n    return getTokenName(input.LA(1)!);\n  }\n\n  /// Used for debugging in adaptivePredict around execATN but I cut\n  ///  it out for clarity now that alg. works well. We can leave this\n  ///  \"dead\" code for a bit.\n  void dumpDeadEndConfigs(NoViableAltException nvae) {\n    log('dead end configs: ', level: Level.SEVERE.value);\n    for (var c in nvae.deadEndConfigs!) {\n      var trans = 'no edges';\n      if (c.state.numberOfTransitions > 0) {\n        final t = c.state.transition(0);\n        if (t is AtomTransition) {\n          final at = t;\n          trans = 'Atom ' + getTokenName(at.atomLabel);\n        } else if (t is SetTransition) {\n          final st = t;\n          final not = st is NotSetTransition;\n          trans = (not ? '~' : '') + 'Set ' + st.label.toString();\n        }\n      }\n      log(c.toString(parser, true) + ':' + trans, level: Level.SEVERE.value);\n    }\n  }\n\n  NoViableAltException noViableAlt(\n    TokenStream input,\n    ParserRuleContext outerContext,\n    ATNConfigSet configs,\n    int startIndex,\n  ) {\n    return NoViableAltException(\n      parser,\n      input,\n      input.get(startIndex),\n      input.LT(1),\n      configs,\n      outerContext,\n    );\n  }\n\n  static int getUniqueAlt(ATNConfigSet configs) {\n    var alt = ATN.INVALID_ALT_NUMBER;\n    for (var c in configs) {\n      if (alt == ATN.INVALID_ALT_NUMBER) {\n        alt = c.alt; // found first alt\n      } else if (c.alt != alt) {\n        return ATN.INVALID_ALT_NUMBER;\n      }\n    }\n    return alt;\n  }\n\n  /// Add an edge to the DFA, if possible. This method calls\n  /// {@link #addDFAState} to ensure the [to] state is present in the\n  /// DFA. If [from] is null, or if [t] is outside the\n  /// range of edges that can be represented in the DFA tables, this method\n  /// returns without adding the edge to the DFA.\n  ///\n  /// <p>If [to] is null, this method returns null.\n  /// Otherwise, this method returns the [DFAState] returned by calling\n  /// {@link #addDFAState} for the [to] state.</p>\n  ///\n  /// @param dfa The DFA\n  /// @param from The source state for the edge\n  /// @param t The input symbol\n  /// @param to The target state for the edge\n  ///\n  /// @return If [to] is null, this method returns null;\n  /// otherwise this method returns the result of calling {@link #addDFAState}\n  /// on [to]\n  DFAState? addDFAEdge(DFA dfa, DFAState? from, int t, DFAState to) {\n    if (debug) {\n      log('EDGE $from -> $to upon ' + getTokenName(t));\n    }\n\n    to = addDFAState(dfa, to); // used existing if possible not incoming\n    if (from == null || t < -1 || t > atn.maxTokenType) {\n      return to;\n    }\n\n    from.edges ??= List.filled(atn.maxTokenType + 1 + 1, null);\n\n    from.edges![t + 1] = to; // connect\n\n    if (debug) {\n      log('DFA=\\n' + dfa.toString(parser.vocabulary));\n    }\n\n    return to;\n  }\n\n  /// Add state [D] to the DFA if it is not already present, and return\n  /// the actual instance stored in the DFA. If a state equivalent to [D]\n  /// is already in the DFA, the existing state is returned. Otherwise this\n  /// method returns [D] after adding it to the DFA.\n  ///\n  /// <p>If [D] is {@link #ERROR}, this method returns {@link #ERROR} and\n  /// does not change the DFA.</p>\n  ///\n  /// @param dfa The dfa\n  /// @param D The DFA state to add\n  /// @return The state stored in the DFA. This will be either the existing\n  /// state if [D] is already in the DFA, or [D] itself if the\n  /// state was not already present.\n  DFAState addDFAState(DFA dfa, DFAState D) {\n    if (D == ATNSimulator.ERROR) {\n      return D;\n    }\n\n    final existing = dfa.states[D];\n    if (existing != null) return existing;\n\n    D.stateNumber = dfa.states.length;\n    if (!D.configs.readOnly) {\n      D.configs.optimizeConfigs(this);\n      D.configs.readOnly = true;\n    }\n    dfa.states[D] = D;\n    if (debug) log('adding new DFA state: $D');\n    return D;\n  }\n\n  void reportAttemptingFullContext(\n    DFA dfa,\n    BitSet? conflictingAlts,\n    ATNConfigSet configs,\n    int startIndex,\n    int stopIndex,\n  ) {\n    if (debug || retry_debug) {\n      final interval = Interval.of(startIndex, stopIndex);\n      log(\n        'reportAttemptingFullContext decision=${dfa.decision}:$configs'\n                ', input=' +\n            parser.tokenStream.getText(interval),\n      );\n    }\n\n    parser.errorListenerDispatch.reportAttemptingFullContext(\n      parser,\n      dfa,\n      startIndex,\n      stopIndex,\n      conflictingAlts,\n      configs,\n    );\n  }\n\n  void reportContextSensitivity(DFA dfa, int prediction, ATNConfigSet configs,\n      int startIndex, int stopIndex) {\n    if (debug || retry_debug) {\n      final interval = Interval.of(startIndex, stopIndex);\n      log(\n        'reportContextSensitivity decision=${dfa.decision}:$configs'\n                ', input=' +\n            parser.tokenStream.getText(interval),\n      );\n    }\n\n    parser.errorListenerDispatch.reportContextSensitivity(\n      parser,\n      dfa,\n      startIndex,\n      stopIndex,\n      prediction,\n      configs,\n    );\n  }\n\n  /// If context sensitive parsing, we know it's ambiguity not conflict */\n  void reportAmbiguity(\n    DFA dfa,\n    DFAState D, // the DFA state from execATN() that had SLL conflicts\n    int startIndex,\n    int stopIndex,\n    bool exact,\n    BitSet? ambigAlts,\n    ATNConfigSet configs,\n  ) // configs that LL not SLL considered conflicting\n  {\n    if (debug || retry_debug) {\n      final interval = Interval.of(startIndex, stopIndex);\n      log(\n        'reportAmbiguity $ambigAlts:$configs' ', input=' +\n            parser.tokenStream.getText(interval),\n      );\n    }\n\n    parser.errorListenerDispatch.reportAmbiguity(\n      parser,\n      dfa,\n      startIndex,\n      stopIndex,\n      exact,\n      ambigAlts,\n      configs,\n    );\n  }\n}\n\n/// This enumeration defines the prediction modes available in ANTLR 4 along with\n/// utility methods for analyzing configuration sets for conflicts and/or\n/// ambiguities.\nenum PredictionMode {\n  /// The SLL(*) prediction mode. This prediction mode ignores the current\n  /// parser context when making predictions. This is the fastest prediction\n  /// mode, and provides correct results for many grammars. This prediction\n  /// mode is more powerful than the prediction mode provided by ANTLR 3, but\n  /// may result in syntax errors for grammar and input combinations which are\n  /// not SLL.\n  ///\n  /// <p>\n  /// When using this prediction mode, the parser will either return a correct\n  /// parse tree (i.e. the same parse tree that would be returned with the\n  /// {@link #LL} prediction mode), or it will report a syntax error. If a\n  /// syntax error is encountered when using the {@link #SLL} prediction mode,\n  /// it may be due to either an actual syntax error in the input or indicate\n  /// that the particular combination of grammar and input requires the more\n  /// powerful {@link #LL} prediction abilities to complete successfully.</p>\n  ///\n  /// <p>\n  /// This prediction mode does not provide any guarantees for prediction\n  /// behavior for syntactically-incorrect inputs.</p>\n  SLL,\n\n  /// The LL(*) prediction mode. This prediction mode allows the current parser\n  /// context to be used for resolving SLL conflicts that occur during\n  /// prediction. This is the fastest prediction mode that guarantees correct\n  /// parse results for all combinations of grammars with syntactically correct\n  /// inputs.\n  ///\n  /// <p>\n  /// When using this prediction mode, the parser will make correct decisions\n  /// for all syntactically-correct grammar and input combinations. However, in\n  /// cases where the grammar is truly ambiguous this prediction mode might not\n  /// report a precise answer for <em>exactly which</em> alternatives are\n  /// ambiguous.</p>\n  ///\n  /// <p>\n  /// This prediction mode does not provide any guarantees for prediction\n  /// behavior for syntactically-incorrect inputs.</p>\n  LL,\n\n  /// The LL(*) prediction mode with exact ambiguity detection. In addition to\n  /// the correctness guarantees provided by the {@link #LL} prediction mode,\n  /// this prediction mode instructs the prediction algorithm to determine the\n  /// complete and exact set of ambiguous alternatives for every ambiguous\n  /// decision encountered while parsing.\n  ///\n  /// <p>\n  /// This prediction mode may be used for diagnosing ambiguities during\n  /// grammar development. Due to the performance overhead of calculating sets\n  /// of ambiguous alternatives, this prediction mode should be avoided when\n  /// the exact results are not necessary.</p>\n  ///\n  /// <p>\n  /// This prediction mode does not provide any guarantees for prediction\n  /// behavior for syntactically-incorrect inputs.</p>\n  LL_EXACT_AMBIG_DETECTION,\n}\n\nextension PredictionModeExtension on PredictionMode {\n  /// Computes the SLL prediction termination condition.\n  ///\n  /// <p>\n  /// This method computes the SLL prediction termination condition for both of\n  /// the following cases.</p>\n  ///\n  /// <ul>\n  /// <li>The usual SLL+LL fallback upon SLL conflict</li>\n  /// <li>Pure SLL without LL fallback</li>\n  /// </ul>\n  ///\n  /// <p><strong>COMBINED SLL+LL PARSING</strong></p>\n  ///\n  /// <p>When LL-fallback is enabled upon SLL conflict, correct predictions are\n  /// ensured regardless of how the termination condition is computed by this\n  /// method. Due to the substantially higher cost of LL prediction, the\n  /// prediction should only fall back to LL when the additional lookahead\n  /// cannot lead to a unique SLL prediction.</p>\n  ///\n  /// <p>Assuming combined SLL+LL parsing, an SLL configuration set with only\n  /// conflicting subsets should fall back to full LL, even if the\n  /// configuration sets don't resolve to the same alternative (e.g.\n  /// {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting\n  /// configuration, SLL could continue with the hopes that more lookahead will\n  /// resolve via one of those non-conflicting configurations.</p>\n  ///\n  /// <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n  /// stops when it sees only conflicting configuration subsets. In contrast,\n  /// full LL keeps going when there is uncertainty.</p>\n  ///\n  /// <p><strong>HEURISTIC</strong></p>\n  ///\n  /// <p>As a heuristic, we stop prediction when we see any conflicting subset\n  /// unless we see a state that only has one alternative associated with it.\n  /// The single-alt-state thing lets prediction continue upon rules like\n  /// (otherwise, it would admit defeat too soon):</p>\n  ///\n  /// <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>\n  ///\n  /// <p>When the ATN simulation reaches the state before {@code ';'}, it has a\n  /// DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally\n  /// {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop\n  /// processing this node because alternative to has another way to continue,\n  /// via {@code [6|2|[]]}.</p>\n  ///\n  /// <p>It also let's us continue for this rule:</p>\n  ///\n  /// <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>\n  ///\n  /// <p>After matching input A, we reach the stop state for rule A, state 1.\n  /// State 8 is the state right before B. Clearly alternatives 1 and 2\n  /// conflict and no amount of further lookahead will separate the two.\n  /// However, alternative 3 will be able to continue and so we do not stop\n  /// working on this state. In the previous example, we're concerned with\n  /// states associated with the conflicting alternatives. Here alt 3 is not\n  /// associated with the conflicting configs, but since we can continue\n  /// looking for input reasonably, don't declare the state done.</p>\n  ///\n  /// <p><strong>PURE SLL PARSING</strong></p>\n  ///\n  /// <p>To handle pure SLL parsing, all we have to do is make sure that we\n  /// combine stack contexts for configurations that differ only by semantic\n  /// predicate. From there, we can do the usual SLL termination heuristic.</p>\n  ///\n  /// <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>\n  ///\n  /// <p>SLL decisions don't evaluate predicates until after they reach DFA stop\n  /// states because they need to create the DFA cache that works in all\n  /// semantic situations. In contrast, full LL evaluates predicates collected\n  /// during start state computation so it can ignore predicates thereafter.\n  /// This means that SLL termination detection can totally ignore semantic\n  /// predicates.</p>\n  ///\n  /// <p>Implementation-wise, [ATNConfigSet] combines stack contexts but not\n  /// semantic predicate contexts so we might see two configurations like the\n  /// following.</p>\n  ///\n  /// <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>\n  ///\n  /// <p>Before testing these configurations against others, we have to merge\n  /// [x] and {@code x'} (without modifying the existing configurations).\n  /// For example, we test {@code (x+x')==x''} when looking for conflicts in\n  /// the following configurations.</p>\n  ///\n  /// <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>\n  ///\n  /// <p>If the configuration set has predicates (as indicated by\n  /// {@link ATNConfigSet#hasSemanticContext}), this algorithm makes a copy of\n  /// the configurations to strip out all of the predicates so that a standard\n  /// [ATNConfigSet] will merge everything ignoring predicates.</p>\n  static bool hasSLLConflictTerminatingPrediction(\n      PredictionMode mode, ATNConfigSet configs) {\n/* Configs in rule stop states indicate reaching the end of the decision\n\t\t * rule (local context) or end of start rule (full context). If all\n\t\t * configs meet this condition, then none of the configurations is able\n\t\t * to match additional input so we terminate prediction.\n\t\t */\n    if (allConfigsInRuleStopStates(configs)) {\n      return true;\n    }\n\n// pure SLL mode parsing\n    if (mode == PredictionMode.SLL) {\n// Don't bother with combining configs from different semantic\n// contexts if we can fail over to full LL; costs more time\n// since we'll often fail over anyway.\n      if (configs.hasSemanticContext) {\n// dup configs, tossing out semantic predicates\n        final dup = ATNConfigSet();\n        for (var c in configs) {\n          c = ATNConfig.dup(c, semanticContext: EmptySemanticContext.Instance);\n          dup.add(c);\n        }\n        configs = dup;\n      }\n// now we have combined contexts for configs with dissimilar preds\n    }\n\n// pure SLL or combined SLL+LL mode parsing\n\n    final altsets = getConflictingAltSubsets(configs);\n    final heuristic =\n        hasConflictingAltSet(altsets) && !hasStateAssociatedWithOneAlt(configs);\n    return heuristic;\n  }\n\n  /// Checks if any configuration in [configs] is in a\n  /// [RuleStopState]. Configurations meeting this condition have reached\n  /// the end of the decision rule (local context) or end of start rule (full\n  /// context).\n  ///\n  /// @param configs the configuration set to test\n  /// @return [true] if any configuration in [configs] is in a\n  /// [RuleStopState], otherwise [false]\n  static bool hasConfigInRuleStopState(ATNConfigSet configs) {\n    for (var c in configs) {\n      if (c.state is RuleStopState) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  /// Checks if all configurations in [configs] are in a\n  /// [RuleStopState]. Configurations meeting this condition have reached\n  /// the end of the decision rule (local context) or end of start rule (full\n  /// context).\n  ///\n  /// @param configs the configuration set to test\n  /// @return [true] if all configurations in [configs] are in a\n  /// [RuleStopState], otherwise [false]\n  static bool allConfigsInRuleStopStates(ATNConfigSet configs) {\n    for (var config in configs) {\n      if (config.state is! RuleStopState) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  /// Full LL prediction termination.\n  ///\n  /// <p>Can we stop looking ahead during ATN simulation or is there some\n  /// uncertainty as to which alternative we will ultimately pick, after\n  /// consuming more input? Even if there are partial conflicts, we might know\n  /// that everything is going to resolve to the same minimum alternative. That\n  /// means we can stop since no more lookahead will change that fact. On the\n  /// other hand, there might be multiple conflicts that resolve to different\n  /// minimums. That means we need more look ahead to decide which of those\n  /// alternatives we should predict.</p>\n  ///\n  /// <p>The basic idea is to split the set of configurations [C], into\n  /// conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with\n  /// non-conflicting configurations. Two configurations conflict if they have\n  /// identical {@link ATNConfig#state} and {@link ATNConfig#context} values\n  /// but different {@link ATNConfig#alt} value, e.g. {@code (s, i, ctx, _)}\n  /// and {@code (s, j, ctx, _)} for {@code i!=j}.</p>\n  ///\n  /// <p>Reduce these configuration subsets to the set of possible alternatives.\n  /// You can compute the alternative subsets in one pass as follows:</p>\n  ///\n  /// <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in\n  /// [C] holding [s] and [ctx] fixed.</p>\n  ///\n  /// <p>Or in pseudo-code, for each configuration [c] in [C]:</p>\n  ///\n  /// <pre>\n  /// map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not\n  /// alt and not pred\n  /// </pre>\n  ///\n  /// <p>The values in [map] are the set of {@code A_s,ctx} sets.</p>\n  ///\n  /// <p>If {@code |A_s,ctx|=1} then there is no conflict associated with\n  /// [s] and [ctx].</p>\n  ///\n  /// <p>Reduce the subsets to singletons by choosing a minimum of each subset. If\n  /// the union of these alternative subsets is a singleton, then no amount of\n  /// more lookahead will help us. We will always pick that alternative. If,\n  /// however, there is more than one alternative, then we are uncertain which\n  /// alternative to predict and must continue looking for resolution. We may\n  /// or may not discover an ambiguity in the future, even if there are no\n  /// conflicting subsets this round.</p>\n  ///\n  /// <p>The biggest sin is to terminate early because it means we've made a\n  /// decision but were uncertain as to the eventual outcome. We haven't used\n  /// enough lookahead. On the other hand, announcing a conflict too late is no\n  /// big deal; you will still have the conflict. It's just inefficient. It\n  /// might even look until the end of file.</p>\n  ///\n  /// <p>No special consideration for semantic predicates is required because\n  /// predicates are evaluated on-the-fly for full LL prediction, ensuring that\n  /// no configuration contains a semantic context during the termination\n  /// check.</p>\n  ///\n  /// <p><strong>CONFLICTING CONFIGS</strong></p>\n  ///\n  /// <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict\n  /// when {@code i!=j} but {@code x=x'}. Because we merge all\n  /// {@code (s, i, _)} configurations together, that means that there are at\n  /// most [n] configurations associated with state [s] for\n  /// [n] possible alternatives in the decision. The merged stacks\n  /// complicate the comparison of configuration contexts [x] and\n  /// {@code x'}. Sam checks to see if one is a subset of the other by calling\n  /// merge and checking to see if the merged result is either [x] or\n  /// {@code x'}. If the [x] associated with lowest alternative [i]\n  /// is the superset, then [i] is the only possible prediction since the\n  /// others resolve to {@code min(i)} as well. However, if [x] is\n  /// associated with {@code j>i} then at least one stack configuration for\n  /// [j] is not in conflict with alternative [i]. The algorithm\n  /// should keep going, looking for more lookahead due to the uncertainty.</p>\n  ///\n  /// <p>For simplicity, I'm doing a equality check between [x] and\n  /// {@code x'} that lets the algorithm continue to consume lookahead longer\n  /// than necessary. The reason I like the equality is of course the\n  /// simplicity but also because that is the test you need to detect the\n  /// alternatives that are actually in conflict.</p>\n  ///\n  /// <p><strong>CONTINUE/STOP RULE</strong></p>\n  ///\n  /// <p>Continue if union of resolved alternative sets from non-conflicting and\n  /// conflicting alternative subsets has more than one alternative. We are\n  /// uncertain about which alternative to predict.</p>\n  ///\n  /// <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which\n  /// alternatives are still in the running for the amount of input we've\n  /// consumed at this point. The conflicting sets let us to strip away\n  /// configurations that won't lead to more states because we resolve\n  /// conflicts to the configuration with a minimum alternate for the\n  /// conflicting set.</p>\n  ///\n  /// <p><strong>CASES</strong></p>\n  ///\n  /// <ul>\n  ///\n  /// <li>no conflicts and more than 1 alternative in set =&gt; continue</li>\n  ///\n  /// <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},\n  /// {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set\n  /// {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n  /// {@code {1,3}} =&gt; continue\n  /// </li>\n  ///\n  /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n  /// {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set\n  /// {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n  /// {@code {1}} =&gt; stop and predict 1</li>\n  ///\n  /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n  /// {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U\n  /// {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce\n  /// ambiguity {@code {1,2}}</li>\n  ///\n  /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},\n  /// {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U\n  /// {@code {2}} = {@code {1,2}} =&gt; continue</li>\n  ///\n  /// <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},\n  /// {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U\n  /// {@code {3}} = {@code {1,3}} =&gt; continue</li>\n  ///\n  /// </ul>\n  ///\n  /// <p><strong>EXACT AMBIGUITY DETECTION</strong></p>\n  ///\n  /// <p>If all states report the same conflicting set of alternatives, then we\n  /// know we have the exact ambiguity set.</p>\n  ///\n  /// <p><code>|A_<em>i</em>|&gt;1</code> and\n  /// <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>\n  ///\n  /// <p>In other words, we continue examining lookahead until all {@code A_i}\n  /// have more than one alternative and all {@code A_i} are the same. If\n  /// {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate\n  /// because the resolved set is {@code {1}}. To determine what the real\n  /// ambiguity is, we have to know whether the ambiguity is between one and\n  /// two or one and three so we keep going. We can only stop prediction when\n  /// we need exact ambiguity detection when the sets look like\n  /// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>\n  static int resolvesToJustOneViableAlt(List<BitSet> altsets) {\n    return getSingleViableAlt(altsets);\n  }\n\n  /// Determines if every alternative subset in [altsets] contains more\n  /// than one alternative.\n  ///\n  /// @param altsets a collection of alternative subsets\n  /// @return [true] if every [BitSet] in [altsets] has\n  /// {@link BitSet#cardinality cardinality} &gt; 1, otherwise [false]\n  static bool allSubsetsConflict(List<BitSet> altsets) {\n    return !hasNonConflictingAltSet(altsets);\n  }\n\n  /// Determines if any single alternative subset in [altsets] contains\n  /// exactly one alternative.\n  ///\n  /// @param altsets a collection of alternative subsets\n  /// @return [true] if [altsets] contains a [BitSet] with\n  /// {@link BitSet#cardinality cardinality} 1, otherwise [false]\n  static bool hasNonConflictingAltSet(List<BitSet> altsets) {\n    for (var alts in altsets) {\n      if (alts.cardinality == 1) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /// Determines if any single alternative subset in [altsets] contains\n  /// more than one alternative.\n  ///\n  /// @param altsets a collection of alternative subsets\n  /// @return [true] if [altsets] contains a [BitSet] with\n  /// {@link BitSet#cardinality cardinality} &gt; 1, otherwise [false]\n  static bool hasConflictingAltSet(List<BitSet> altsets) {\n    for (var alts in altsets) {\n      if (alts.cardinality > 1) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /// Determines if every alternative subset in [altsets] is equivalent.\n  ///\n  /// @param altsets a collection of alternative subsets\n  /// @return [true] if every member of [altsets] is equal to the\n  /// others, otherwise [false]\n  static bool allSubsetsEqual(List<BitSet> altsets) {\n    final first = altsets.first;\n    return altsets.every((e) => e == first);\n  }\n\n  /// Returns the unique alternative predicted by all alternative subsets in\n  /// [altsets]. If no such alternative exists, this method returns\n  /// {@link ATN#INVALID_ALT_NUMBER}.\n  ///\n  /// @param altsets a collection of alternative subsets\n  static int getUniqueAlt(List<BitSet> altsets) {\n    final all = getAlts(altsets);\n    if (all.cardinality == 1) return all.nextset(0);\n    return ATN.INVALID_ALT_NUMBER;\n  }\n\n  /// Gets the complete set of represented alternatives for a collection of\n  /// alternative subsets. This method returns the union of each [BitSet]\n  /// in [altsets].\n  ///\n  /// @param altsets a collection of alternative subsets\n  /// @return the set of represented alternatives in [altsets]\n  static BitSet getAlts(List<BitSet> altsets) {\n    final all = BitSet();\n    for (var alts in altsets) {\n      all.or(alts);\n    }\n    return all;\n  }\n\n  /// Get union of all alts from configs.\n  ///\n  /// @since 4.5.1\n  static BitSet getAltsFromConfigs(ATNConfigSet configs) {\n    final alts = BitSet();\n    for (var config in configs) {\n      alts.set(config.alt);\n    }\n    return alts;\n  }\n\n  /// This function gets the conflicting alt subsets from a configuration set.\n  /// For each configuration [c] in [configs]:\n  ///\n  /// <pre>\n  /// map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not\n  /// alt and not pred\n  /// </pre>\n  static List<BitSet> getConflictingAltSubsets(ATNConfigSet configs) {\n    final configToAlts =\n        HashMap<ATNConfig, BitSet>(equals: (ATNConfig? a, ATNConfig? b) {\n      if (identical(a, b)) return true;\n      if (a == null || b == null) return false;\n      return a.state.stateNumber == b.state.stateNumber &&\n          a.context == b.context;\n    }, hashCode: (ATNConfig o) {\n      /**\n       * The hash code is only a function of the {@link ATNState#stateNumber}\n       * and {@link ATNConfig#context}.\n       */\n      var hashCode = MurmurHash.initialize(7);\n      hashCode = MurmurHash.update(hashCode, o.state.stateNumber);\n      hashCode = MurmurHash.update(hashCode, o.context);\n      hashCode = MurmurHash.finish(hashCode, 2);\n      return hashCode;\n    });\n    for (var c in configs) {\n      var alts = configToAlts[c];\n      if (alts == null) {\n        alts = BitSet();\n        configToAlts[c] = alts;\n      }\n      alts.set(c.alt);\n    }\n    return configToAlts.values.toList();\n  }\n\n  /// Get a map from state to alt subset from a configuration set. For each\n  /// configuration [c] in [configs]:\n  ///\n  /// <pre>\n  /// map[c.{@link ATNConfig#state state}] U= c.{@link ATNConfig#alt alt}\n  /// </pre>\n  static Map<ATNState, BitSet> getStateToAltMap(ATNConfigSet configs) {\n    final m = <ATNState, BitSet>{};\n    for (var c in configs) {\n      var alts = m[c.state];\n      if (alts == null) {\n        alts = BitSet();\n        m[c.state] = alts;\n      }\n      alts.set(c.alt);\n    }\n    return m;\n  }\n\n  static bool hasStateAssociatedWithOneAlt(ATNConfigSet configs) {\n    final x = getStateToAltMap(configs);\n    for (var alts in x.values) {\n      if (alts.cardinality == 1) return true;\n    }\n    return false;\n  }\n\n  static int getSingleViableAlt(List<BitSet> altsets) {\n    final viableAlts = BitSet();\n    for (var alts in altsets) {\n      final minAlt = alts.nextset(0);\n      viableAlts.set(minAlt);\n      if (viableAlts.cardinality > 1) {\n        // more than 1 viable alt\n        return ATN.INVALID_ALT_NUMBER;\n      }\n    }\n    return viableAlts.nextset(0);\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/profiling_atn_simulator.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:math';\n\nimport '../../dfa/dfa.dart';\nimport '../../parser.dart';\nimport '../../parser_rule_context.dart';\nimport '../../token_stream.dart';\nimport '../../util/bit_set.dart';\nimport 'atn_config_set.dart';\nimport 'atn_simulator.dart';\nimport 'info.dart';\nimport 'parser_atn_simulator.dart';\nimport 'semantic_context.dart';\n\nclass ProfilingATNSimulator extends ParserATNSimulator {\n  late List<DecisionInfo> decisions;\n  late int numDecisions;\n\n  late int _sllStopIndex;\n  late int _llStopIndex;\n\n  late int currentDecision;\n  DFAState? currentState;\n\n  /// At the point of LL failover, we record how SLL would resolve the conflict so that\n  ///  we can determine whether or not a decision / input pair is context-sensitive.\n  ///  If LL gives a different result than SLL's predicted alternative, we have a\n  ///  context sensitivity for sure. The converse is not necessarily true, however.\n  ///  It's possible that after conflict resolution chooses minimum alternatives,\n  ///  SLL could get the same answer as LL. Regardless of whether or not the result indicates\n  ///  an ambiguity, it is not treated as a context sensitivity because LL prediction\n  ///  was not required in order to produce a correct prediction for this decision and input sequence.\n  ///  It may in fact still be a context sensitivity but we don't know by looking at the\n  ///  minimum alternatives for the current input.\n  int? conflictingAltResolvedBySLL;\n\n  ProfilingATNSimulator(Parser parser)\n      : super(\n          parser,\n          parser.interpreter!.atn,\n          parser.interpreter!.decisionToDFA,\n          parser.interpreter!.sharedContextCache,\n        ) {\n    numDecisions = atn.decisionToState.length;\n    decisions = List<DecisionInfo>.generate(\n      numDecisions,\n      (index) => DecisionInfo(index),\n    );\n  }\n\n  @override\n  int adaptivePredict(\n    TokenStream input,\n    int decision,\n    ParserRuleContext? outerContext,\n  ) {\n    try {\n      _sllStopIndex = -1;\n      _llStopIndex = -1;\n      currentDecision = decision;\n\n      final start =\n          DateTime.now(); // TODO get nano seconds expensive but useful info\n      final alt = super.adaptivePredict(input, decision, outerContext);\n      final stop = DateTime.now();\n      decisions[decision].timeInPrediction +=\n          (stop.difference(start)).inMicroseconds;\n      decisions[decision].invocations++;\n\n      final SLL_k = _sllStopIndex - startIndex + 1;\n      decisions[decision].SLL_TotalLook += SLL_k;\n      decisions[decision].SLL_MinLook = decisions[decision].SLL_MinLook == 0\n          ? SLL_k\n          : min(decisions[decision].SLL_MinLook, SLL_k);\n      if (SLL_k > decisions[decision].SLL_MaxLook) {\n        decisions[decision].SLL_MaxLook = SLL_k;\n        decisions[decision].SLL_MaxLookEvent = LookaheadEventInfo(\n          decision,\n          null,\n          alt,\n          input,\n          startIndex,\n          _sllStopIndex,\n          false,\n        );\n      }\n\n      if (_llStopIndex >= 0) {\n        final LL_k = _llStopIndex - startIndex + 1;\n        decisions[decision].LL_TotalLook += LL_k;\n        decisions[decision].LL_MinLook = decisions[decision].LL_MinLook == 0\n            ? LL_k\n            : min(decisions[decision].LL_MinLook, LL_k);\n        if (LL_k > decisions[decision].LL_MaxLook) {\n          decisions[decision].LL_MaxLook = LL_k;\n          decisions[decision].LL_MaxLookEvent = LookaheadEventInfo(\n              decision, null, alt, input, startIndex, _llStopIndex, true);\n        }\n      }\n\n      return alt;\n    } finally {\n      currentDecision = -1;\n    }\n  }\n\n  @override\n  DFAState? getExistingTargetState(DFAState previousD, int t) {\n    // this method is called after each time the input position advances\n    // during SLL prediction\n    _sllStopIndex = input.index;\n\n    final existingTargetState = super.getExistingTargetState(previousD, t);\n    if (existingTargetState != null) {\n      // count only if we transition over a DFA state\n      decisions[currentDecision].SLL_DFATransitions += 1;\n      if (existingTargetState == ATNSimulator.ERROR) {\n        decisions[currentDecision].errors.add(\n              ErrorInfo(\n                currentDecision,\n                previousD.configs,\n                input,\n                startIndex,\n                _sllStopIndex,\n                false,\n              ),\n            );\n      }\n    }\n\n    currentState = existingTargetState;\n    return existingTargetState;\n  }\n\n  @override\n  DFAState? computeTargetState(DFA dfa, DFAState previousD, int t) {\n    final state = super.computeTargetState(dfa, previousD, t);\n    currentState = state;\n    return state;\n  }\n\n  @override\n  ATNConfigSet? computeReachSet(ATNConfigSet closure, int t, bool fullCtx) {\n    if (fullCtx) {\n      // this method is called after each time the input position advances\n      // during full context prediction\n      _llStopIndex = input.index;\n    }\n\n    final reachConfigs = super.computeReachSet(closure, t, fullCtx);\n    if (fullCtx) {\n      // count computation even if error\n      decisions[currentDecision].LL_ATNTransitions += 1;\n      if (reachConfigs != null) {\n      } else {\n        // no reach on current lookahead symbol. ERROR.\n        // TODO: does not handle delayed errors per getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule()\n        decisions[currentDecision].errors.add(\n              ErrorInfo(\n                currentDecision,\n                closure,\n                input,\n                startIndex,\n                _llStopIndex,\n                true,\n              ),\n            );\n      }\n    } else {\n      decisions[currentDecision].SLL_ATNTransitions += 1;\n      if (reachConfigs != null) {\n      } else {\n        // no reach on current lookahead symbol. ERROR.\n        decisions[currentDecision].errors.add(ErrorInfo(\n              currentDecision,\n              closure,\n              input,\n              startIndex,\n              _sllStopIndex,\n              false,\n            ));\n      }\n    }\n    return reachConfigs;\n  }\n\n  @override\n  bool evalSemanticContextOne(\n    SemanticContext pred,\n    ParserRuleContext? parserCallStack,\n    int alt,\n    bool fullCtx,\n  ) {\n    final result = super.evalSemanticContextOne(\n      pred,\n      parserCallStack,\n      alt,\n      fullCtx,\n    );\n    if (pred is! PrecedencePredicate) {\n      final fullContext = _llStopIndex >= 0;\n      final stopIndex = fullContext ? _llStopIndex : _sllStopIndex;\n      decisions[currentDecision].predicateEvals.add(PredicateEvalInfo(\n          currentDecision,\n          input,\n          startIndex,\n          stopIndex,\n          pred,\n          result,\n          alt,\n          fullCtx));\n    }\n\n    return result;\n  }\n\n  @override\n  void reportAttemptingFullContext(\n    DFA dfa,\n    BitSet? conflictingAlts,\n    ATNConfigSet configs,\n    int startIndex,\n    int stopIndex,\n  ) {\n    if (conflictingAlts != null) {\n      conflictingAltResolvedBySLL = conflictingAlts.nextset(0);\n    } else {\n      conflictingAltResolvedBySLL = configs.alts.nextset(0);\n    }\n\n    decisions[currentDecision].LL_Fallback += 1;\n\n    super.reportAttemptingFullContext(\n      dfa,\n      conflictingAlts,\n      configs,\n      startIndex,\n      stopIndex,\n    );\n  }\n\n  @override\n  void reportContextSensitivity(DFA dfa, int prediction, ATNConfigSet configs,\n      int startIndex, int stopIndex) {\n    if (prediction != conflictingAltResolvedBySLL) {\n      decisions[currentDecision].contextSensitivities.add(\n          ContextSensitivityInfo(\n              currentDecision, configs, input, startIndex, stopIndex));\n    }\n    super.reportContextSensitivity(\n        dfa, prediction, configs, startIndex, stopIndex);\n  }\n\n  @override\n  void reportAmbiguity(\n    DFA dfa,\n    DFAState D,\n    int startIndex,\n    int stopIndex,\n    bool exact,\n    BitSet? ambigAlts,\n    ATNConfigSet configs,\n  ) {\n    final prediction =\n        ambigAlts != null ? ambigAlts.nextset(0) : configs.alts.nextset(0);\n    if (configs.fullCtx && prediction != conflictingAltResolvedBySLL) {\n      // Even though this is an ambiguity we are reporting, we can\n      // still detect some context sensitivities.  Both SLL and LL\n      // are showing a conflict, hence an ambiguity, but if they resolve\n      // to different minimum alternatives we have also identified a\n      // context sensitivity.\n      decisions[currentDecision].contextSensitivities.add(\n            ContextSensitivityInfo(\n              currentDecision,\n              configs,\n              input,\n              startIndex,\n              stopIndex,\n            ),\n          );\n    }\n    decisions[currentDecision].ambiguities.add(\n          AmbiguityInfo(\n            currentDecision,\n            configs,\n            ambigAlts,\n            input,\n            startIndex,\n            stopIndex,\n            configs.fullCtx,\n          ),\n        );\n    super.reportAmbiguity(\n      dfa,\n      D,\n      startIndex,\n      stopIndex,\n      exact,\n      ambigAlts,\n      configs,\n    );\n  }\n\n  // ---------------------------------------------------------------------\n\n  List<DecisionInfo> get decisionInfo {\n    return decisions;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/semantic_context.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'package:antlr4/src/atn/src/atn_simulator.dart';\nimport 'package:collection/collection.dart';\n\nimport '../../recognizer.dart';\nimport '../../rule_context.dart';\nimport '../../util/murmur_hash.dart';\n\n/// A tree structure used to record the semantic context in which\n///  an ATN configuration is valid.  It's either a single predicate,\n///  a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.\n///\n///  <p>I have scoped the [AND], [OR], and [Predicate] subclasses of\n///  [SemanticContext] within the scope of this outer class.</p>\nabstract class SemanticContext {\n  const SemanticContext();\n\n  /// For context independent predicates, we evaluate them without a local\n  /// context (i.e., null context). That way, we can evaluate them without\n  /// having to create proper rule-specific context during prediction (as\n  /// opposed to the parser, which creates them naturally). In a practical\n  /// sense, this avoids a cast exception from RuleContext to myruleContext.\n  ///\n  /// <p>For context dependent predicates, we must pass in a local context so that\n  /// references such as $arg evaluate properly as _localctx.arg. We only\n  /// capture context dependent predicates in the context in which we begin\n  /// prediction, so we passed in the outer context here in case of context\n  /// dependent predicate evaluation.</p>\n  bool eval(Recognizer parser, RuleContext? parserCallStack);\n\n  /// Evaluate the precedence predicates for the context and reduce the result.\n  ///\n  /// @param parser The parser instance.\n  /// @param parserCallStack\n  /// @return The simplified semantic context after precedence predicates are\n  /// evaluated, which will be one of the following values.\n  /// <ul>\n  /// <li>{@link #NONE}in if the predicate simplifies to [true] after\n  /// precedence predicates are evaluated.</li>\n  /// <li>nullin if the predicate simplifies to [false] after\n  /// precedence predicates are evaluated.</li>\n  /// <li>[this]in if the semantic context is not changed as a result of\n  /// precedence predicate evaluation.</li>\n  /// <li>A non-null [SemanticContext]in the new simplified\n  /// semantic context after precedence predicates are evaluated.</li>\n  /// </ul>\n  SemanticContext? evalPrecedence(\n    Recognizer parser,\n    RuleContext? parserCallStack,\n  ) {\n    return this;\n  }\n\n  static SemanticContext? and(SemanticContext? a, SemanticContext? b) {\n    if (a == null || a == EmptySemanticContext.Instance) return b;\n    if (b == null || b == EmptySemanticContext.Instance) return a;\n    final result = AND(a, b);\n    if (result.opnds.length == 1) {\n      return result.opnds[0];\n    }\n\n    return result;\n  }\n\n  ///\n  ///  @see ParserATNSimulator#getPredsForAmbigAlts\n  static SemanticContext? or(SemanticContext? a, SemanticContext? b) {\n    if (a == null) return b;\n    if (b == null) return a;\n    if (a == EmptySemanticContext.Instance || b == EmptySemanticContext.Instance) return EmptySemanticContext.Instance;\n    final result = OR(a, b);\n    if (result.opnds.length == 1) {\n      return result.opnds[0];\n    }\n\n    return result;\n  }\n\n  static Iterable<PrecedencePredicate> filterPrecedencePredicates(\n      Iterable<SemanticContext> collection) {\n    return collection.whereType<PrecedencePredicate>();\n  }\n\n  static Iterable<SemanticContext> filterNonPrecedencePredicates(\n      Iterable<SemanticContext> collection) {\n    return collection.where((e) => e is! PrecedencePredicate);\n  }\n}\n\nclass EmptySemanticContext extends SemanticContext {\n  /// The default [SemanticContext], which is semantically equivalent to\n  /// a predicate of the form {@code {true}?}.\n  static const SemanticContext Instance = Predicate();\n\n  @override\n  bool eval(Recognizer<ATNSimulator> parser, RuleContext? parserCallStack) {\n    return false;\n  }\n}\n\nclass Predicate extends SemanticContext {\n  final int ruleIndex;\n  final int predIndex;\n  final bool isCtxDependent; // e.g., $i ref in pred\n\n  const Predicate(\n      [this.ruleIndex = -1, this.predIndex = -1, this.isCtxDependent = false]);\n\n  @override\n  bool eval(Recognizer parser, RuleContext? parserCallStack) {\n    final localctx = isCtxDependent ? parserCallStack : null;\n    return parser.sempred(localctx, ruleIndex, predIndex);\n  }\n\n  @override\n  int get hashCode {\n    var hashCode = MurmurHash.initialize();\n    hashCode = MurmurHash.update(hashCode, ruleIndex);\n    hashCode = MurmurHash.update(hashCode, predIndex);\n    hashCode = MurmurHash.update(hashCode, isCtxDependent ? 1 : 0);\n    hashCode = MurmurHash.finish(hashCode, 3);\n    return hashCode;\n  }\n\n  @override\n  bool operator ==(Object obj) {\n    return obj is Predicate &&\n        ruleIndex == obj.ruleIndex &&\n        predIndex == obj.predIndex &&\n        isCtxDependent == obj.isCtxDependent;\n  }\n\n  @override\n  String toString() {\n    return '{$ruleIndex:$predIndex}?';\n  }\n}\n\nclass PrecedencePredicate extends SemanticContext\n    implements Comparable<PrecedencePredicate> {\n  final int precedence;\n\n  PrecedencePredicate([this.precedence = 0]);\n\n  @override\n  bool eval(Recognizer parser, RuleContext? parserCallStack) {\n    return parser.precpred(parserCallStack, precedence);\n  }\n\n  @override\n  SemanticContext? evalPrecedence(\n    Recognizer parser,\n    RuleContext? parserCallStack,\n  ) {\n    if (parser.precpred(parserCallStack, precedence)) {\n      return EmptySemanticContext.Instance;\n    } else {\n      return null;\n    }\n  }\n\n  @override\n  int compareTo(PrecedencePredicate o) {\n    return precedence - o.precedence;\n  }\n\n  @override\n  int get hashCode {\n    var hashCode = 1;\n    hashCode = 31 * hashCode + precedence;\n    return hashCode;\n  }\n\n  @override\n  bool operator ==(Object other) {\n    if (other is! PrecedencePredicate) {\n      return false;\n    }\n    return precedence == other.precedence;\n  }\n\n// precedence >= _precedenceStack.peek()\n  @override\n  String toString() {\n    return '{$precedence>=prec}?';\n  }\n}\n\n/// This is the base class for semantic context \"operators\", which operate on\n/// a collection of semantic context \"operands\".\n///\n/// @since 4.3\nabstract class Operator extends SemanticContext {\n  /// Gets the operands for the semantic context operator.\n  ///\n  /// @return a collection of [SemanticContext] operands for the\n  /// operator.\n  ///\n  /// @since 4.3\n  List<SemanticContext> get operands;\n}\n\n/// A semantic context which is true whenever none of the contained contexts\n/// is false.\n\nclass AND extends Operator {\n  late final List<SemanticContext> opnds;\n\n  AND(SemanticContext a, SemanticContext b) {\n    var operands = <SemanticContext>{};\n    if (a is AND) {\n      operands.addAll(a.opnds);\n    } else {\n      operands.add(a);\n    }\n    if (b is AND) {\n      operands.addAll(b.opnds);\n    } else {\n      operands.add(b);\n    }\n\n    final precedencePredicates =\n        SemanticContext.filterPrecedencePredicates(operands);\n\n    operands = SemanticContext.filterNonPrecedencePredicates(operands).toSet();\n    if (precedencePredicates.isNotEmpty) {\n      // interested in the transition with the lowest precedence\n      final reduced =\n          precedencePredicates.reduce((a, b) => a.compareTo(b) <= 0 ? a : b);\n      operands.add(reduced);\n    }\n\n    opnds = operands.toList();\n  }\n\n  @override\n  List<SemanticContext> get operands {\n    return opnds;\n  }\n\n  @override\n  bool operator ==(Object other) {\n    if (other is! AND) return false;\n    return ListEquality().equals(opnds, other.opnds);\n  }\n\n  @override\n  int get hashCode {\n    return MurmurHash.getHashCode(opnds, runtimeType.hashCode);\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>\n  /// The evaluation of predicates by this context is short-circuiting, but\n  /// unordered.</p>\n\n  @override\n  bool eval(Recognizer parser, RuleContext? parserCallStack) {\n    for (var opnd in opnds) {\n      if (!opnd.eval(parser, parserCallStack)) return false;\n    }\n    return true;\n  }\n\n  @override\n  SemanticContext? evalPrecedence(\n    Recognizer parser,\n    RuleContext? parserCallStack,\n  ) {\n    var differs = false;\n    final operands = <SemanticContext>[];\n    for (var context in opnds) {\n      final evaluated = context.evalPrecedence(parser, parserCallStack);\n      differs |= (evaluated != context);\n      if (evaluated == null) {\n        // The AND context is false if any element is false\n        return null;\n      } else if (evaluated != EmptySemanticContext.Instance) {\n        // Reduce the result by skipping true elements\n        operands.add(evaluated);\n      }\n    }\n\n    if (!differs) {\n      return this;\n    }\n\n    if (operands.isEmpty) {\n      // all elements were true, so the AND context is true\n      return EmptySemanticContext.Instance;\n    }\n\n    SemanticContext? result = operands[0];\n    for (var i = 1; i < operands.length; i++) {\n      result = SemanticContext.and(result, operands[i]);\n    }\n\n    return result;\n  }\n\n  @override\n  String toString() {\n    return opnds.join('&&');\n  }\n}\n\n/// A semantic context which is true whenever at least one of the contained\n/// contexts is true.\nclass OR extends Operator {\n  late final List<SemanticContext> opnds;\n\n  OR(SemanticContext a, SemanticContext b) {\n    var operands = <SemanticContext>{};\n    if (a is OR) {\n      operands.addAll(a.opnds);\n    } else {\n      operands.add(a);\n    }\n    if (b is OR) {\n      operands.addAll(b.opnds);\n    } else {\n      operands.add(b);\n    }\n\n    final precedencePredicates =\n        SemanticContext.filterPrecedencePredicates(operands);\n\n    operands = SemanticContext.filterNonPrecedencePredicates(operands).toSet();\n    if (precedencePredicates.isNotEmpty) {\n      // interested in the transition with the highest precedence\n      final reduced =\n          precedencePredicates.reduce((a, b) => a.compareTo(b) >= 0 ? a : b);\n      operands.add(reduced);\n    }\n\n    opnds = operands.toList();\n  }\n\n  @override\n  List<SemanticContext> get operands {\n    return opnds;\n  }\n\n  @override\n  bool operator ==(Object other) {\n    if (other is! OR) return false;\n    return ListEquality().equals(opnds, other.opnds);\n  }\n\n  @override\n  int get hashCode {\n    return MurmurHash.getHashCode(opnds, runtimeType.hashCode);\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>\n  /// The evaluation of predicates by this context is short-circuiting, but\n  /// unordered.</p>\n\n  @override\n  bool eval(Recognizer parser, RuleContext? parserCallStack) {\n    for (var opnd in opnds) {\n      if (opnd.eval(parser, parserCallStack)) return true;\n    }\n    return false;\n  }\n\n  @override\n  SemanticContext? evalPrecedence(\n    Recognizer parser,\n    RuleContext? parserCallStack,\n  ) {\n    var differs = false;\n    final operands = <SemanticContext>[];\n    for (var context in opnds) {\n      final evaluated = context.evalPrecedence(parser, parserCallStack);\n      differs |= (evaluated != context);\n      if (evaluated == EmptySemanticContext.Instance) {\n        // The OR context is true if any element is true\n        return EmptySemanticContext.Instance;\n      } else if (evaluated != null) {\n        // Reduce the result by skipping false elements\n        operands.add(evaluated);\n      }\n    }\n\n    if (!differs) {\n      return this;\n    }\n\n    if (operands.isEmpty) {\n      // all elements were false, so the OR context is false\n      return null;\n    }\n\n    SemanticContext? result = operands[0];\n    for (var i = 1; i < operands.length; i++) {\n      result = SemanticContext.or(result, operands[i]);\n    }\n\n    return result;\n  }\n\n  @override\n  String toString() {\n    return opnds.join('||');\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/atn/src/transition.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../interval_set.dart';\nimport '../../token.dart';\nimport 'atn_state.dart';\nimport 'semantic_context.dart';\n\nenum TransitionType {\n  INVALID, // 0 is not used\n  EPSILON,\n  RANGE,\n  RULE,\n  PREDICATE, // e.g., {isType(input.LT(1))}?\n  ATOM,\n  ACTION,\n  SET, // ~(A|B) or ~atom, wildcard, which convert to next 2\n  NOT_SET,\n  WILDCARD,\n  PRECEDENCE,\n}\n\n/// An ATN transition between any two ATN states.  Subclasses define\n///  atom, set, epsilon, action, predicate, rule transitions.\n///\n///  <p>This is a one way link.  It emanates from a state (usually via a list of\n///  transitions) and has a target state.</p>\n///\n///  <p>Since we never have to change the ATN transitions once we construct it,\n///  we can fix these transitions as specific classes. The DFA transitions\n///  on the other hand need to update the labels as it adds transitions to\n///  the states. We'll use the term Edge for the DFA to distinguish them from\n///  ATN transitions.</p>\nabstract class Transition {\n  /// The target of this transition. */\n  ATNState target;\n\n  Transition(this.target);\n\n  TransitionType get type;\n\n  /// Determines if the transition is an \"epsilon\" transition.\n  ///\n  /// <p>The default implementation returns [false].</p>\n  ///\n  /// @return [true] if traversing this transition in the ATN does not\n  /// consume an input symbol; otherwise, [false] if traversing this\n  /// transition consumes (matches) an input symbol.\n  bool get isEpsilon => false;\n\n  IntervalSet? get label => null;\n\n  bool matches(int symbol, int minVocabSymbol, int maxVocabSymbol);\n}\n\nclass EpsilonTransition extends Transition {\n  /// @return the rule index of a precedence rule for which this transition is\n  /// returning from, where the precedence value is 0; otherwise, -1.\n  ///\n  /// @see ATNConfig#isPrecedenceFilterSuppressed()\n  /// @see ParserATNSimulator#applyPrecedenceFilter(ATNConfigSet)\n  /// @since 4.4.1\n  final int outermostPrecedenceReturn;\n\n  EpsilonTransition(ATNState target, [this.outermostPrecedenceReturn = -1])\n      : super(target);\n\n  @override\n  bool get isEpsilon => true;\n\n  @override\n  bool matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n    return false;\n  }\n\n  @override\n  String toString() {\n    return 'epsilon';\n  }\n\n  @override\n  TransitionType get type => TransitionType.EPSILON;\n}\n\nclass RangeTransition extends Transition {\n  final int from;\n  final int to;\n\n  RangeTransition(ATNState target, this.from, this.to) : super(target);\n\n  @override\n  IntervalSet get label {\n    return IntervalSet.ofRange(from, to);\n  }\n\n  @override\n  bool matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n    return symbol >= from && symbol <= to;\n  }\n\n  @override\n  String toString() {\n    return \"'$from..$to'\";\n  }\n\n  @override\n  TransitionType get type => TransitionType.RANGE;\n}\n\nclass RuleTransition extends Transition {\n  /// Ptr to the rule definition object for this rule ref */\n  final int ruleIndex; // no Rule object at runtime\n\n  final int precedence;\n\n  /// What node to begin computations following ref to rule */\n  ATNState followState;\n\n  RuleTransition(\n    RuleStartState ruleStart,\n    this.ruleIndex,\n    this.precedence,\n    this.followState,\n  ) : super(ruleStart);\n\n  @override\n  bool get isEpsilon => true;\n\n  @override\n  bool matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n    return false;\n  }\n\n  @override\n  TransitionType get type => TransitionType.RULE;\n}\n\nabstract class AbstractPredicateTransition extends Transition {\n  AbstractPredicateTransition(ATNState target) : super(target);\n}\n\nclass PredicateTransition extends AbstractPredicateTransition {\n  final int ruleIndex;\n  final int predIndex;\n  final bool isCtxDependent; // e.g., $i ref in pred\n\n  PredicateTransition(\n      target, this.ruleIndex, this.predIndex, this.isCtxDependent)\n      : super(target);\n\n  @override\n  bool get isEpsilon => true;\n\n  @override\n  bool matches(symbol, minVocabSymbol, maxVocabSymbol) {\n    return false;\n  }\n\n  Predicate get predicate => Predicate(ruleIndex, predIndex, isCtxDependent);\n\n  @override\n  String toString() {\n    return 'pred_$ruleIndex:$predIndex';\n  }\n\n  @override\n  TransitionType get type => TransitionType.PREDICATE;\n}\n\n/// TODO: make all transitions sets? no, should remove set edges */\nclass AtomTransition extends Transition {\n  /// The token type or character value; or, signifies special label. */\n  final int atomLabel;\n\n  AtomTransition(ATNState target, this.atomLabel) : super(target);\n\n  @override\n  IntervalSet get label {\n    return IntervalSet.ofOne(atomLabel);\n  }\n\n  @override\n  bool matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n    return atomLabel == symbol;\n  }\n\n  @override\n  String toString() {\n    return label.toString();\n  }\n\n  @override\n  TransitionType get type => TransitionType.ATOM;\n}\n\nclass ActionTransition extends Transition {\n  final int ruleIndex;\n  final int actionIndex;\n  final bool isCtxDependent; // e.g., $i ref in pred\n\n  ActionTransition(target, this.ruleIndex,\n      [this.actionIndex = -1, this.isCtxDependent = false])\n      : super(target);\n\n  @override\n  bool get isEpsilon =>\n      true; // we are to be ignored by analysis 'cept for predicates\n\n  @override\n  bool matches(symbol, minVocabSymbol, maxVocabSymbol) => false;\n\n  @override\n  String toString() {\n    return 'action_$ruleIndex:$actionIndex';\n  }\n\n  @override\n  TransitionType get type => TransitionType.ACTION;\n}\n\n// A transition containing a set of values.\nclass SetTransition extends Transition {\n  @override\n  late IntervalSet label;\n\n  SetTransition(ATNState target, [IntervalSet? st]) : super(target) {\n    label = st ?? IntervalSet.ofOne(Token.INVALID_TYPE);\n  }\n\n  @override\n  bool matches(symbol, minVocabSymbol, maxVocabSymbol) {\n    return label.contains(symbol);\n  }\n\n  @override\n  String toString() {\n    return label.toString();\n  }\n\n  @override\n  TransitionType get type => TransitionType.SET;\n}\n\nclass NotSetTransition extends SetTransition {\n  NotSetTransition(target, st) : super(target, st);\n\n  @override\n  bool matches(symbol, minVocabSymbol, maxVocabSymbol) {\n    return symbol >= minVocabSymbol &&\n        symbol <= maxVocabSymbol &&\n        !super.matches(symbol, minVocabSymbol, maxVocabSymbol);\n  }\n\n  @override\n  String toString() {\n    return '~' + super.toString();\n  }\n\n  @override\n  TransitionType get type => TransitionType.NOT_SET;\n}\n\nclass WildcardTransition extends Transition {\n  WildcardTransition(target) : super(target);\n\n  @override\n  bool matches(symbol, minVocabSymbol, maxVocabSymbol) {\n    return symbol >= minVocabSymbol && symbol <= maxVocabSymbol;\n  }\n\n  @override\n  String toString() {\n    return '.';\n  }\n\n  @override\n  TransitionType get type => TransitionType.WILDCARD;\n}\n\nclass PrecedencePredicateTransition extends AbstractPredicateTransition {\n  final int precedence;\n\n  PrecedencePredicateTransition(target, this.precedence) : super(target);\n\n  @override\n  bool get isEpsilon => true;\n\n  @override\n  bool matches(symbol, minVocabSymbol, maxVocabSymbol) => false;\n\n  PrecedencePredicate get predicate {\n    return PrecedencePredicate(precedence);\n  }\n\n  @override\n  String toString() => '$precedence >= _p';\n\n  @override\n  TransitionType get type => TransitionType.PRECEDENCE;\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/dfa/dfa.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport 'src/dfa.dart';\nexport 'src/dfa_state.dart';\n"
  },
  {
    "path": "runtime/Dart/lib/src/dfa/src/dfa.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../vocabulary.dart';\nimport '../../atn/atn.dart';\nimport 'dfa_serializer.dart';\nimport 'dfa_state.dart';\n\nclass DFA {\n  /// A set of all DFA states. Use [Map] so we can get old state back\n  ///  ([Set] only allows you to see if it's there).\n\n  Map<DFAState, DFAState> states = {};\n\n  DFAState? s0;\n\n  final int? decision;\n\n  /// From which ATN state did we create this DFA? */\n\n  DecisionState? atnStartState;\n\n  /// [true] if this DFA is for a precedence decision; otherwise,\n  /// [false]. This is the backing field for [isPrecedenceDfa].\n  late bool precedenceDfa;\n\n  DFA(this.atnStartState, [this.decision]) {\n    var precedenceDfa = false;\n    if (atnStartState is StarLoopEntryState) {\n      if ((atnStartState as StarLoopEntryState).isPrecedenceDecision) {\n        precedenceDfa = true;\n        final precedenceState = DFAState(configs: ATNConfigSet());\n        precedenceState.edges = [];\n        precedenceState.isAcceptState = false;\n        precedenceState.requiresFullContext = false;\n        s0 = precedenceState;\n      }\n    }\n\n    this.precedenceDfa = precedenceDfa;\n  }\n\n  /// Gets whether this DFA is a precedence DFA. Precedence DFAs use a special\n  /// start state {@link #s0} which is not stored in [states]. The\n  /// [DFAState.edges] array for this start state contains outgoing edges\n  /// supplying individual start states corresponding to specific precedence\n  /// values.\n  ///\n  /// @return [true] if this is a precedence DFA; otherwise,\n  /// [false].\n  /// @see Parser#getPrecedence()\n  bool isPrecedenceDfa() {\n    return precedenceDfa;\n  }\n\n  /// Get the start state for a specific precedence value.\n  ///\n  /// @param precedence The current precedence.\n  /// @return The start state corresponding to the specified precedence, or\n  /// null if no start state exists for the specified precedence.\n  ///\n  /// @throws IllegalStateException if this is not a precedence DFA.\n  /// @see #isPrecedenceDfa()\n  DFAState? getPrecedenceStartState(int precedence) {\n    if (!isPrecedenceDfa()) {\n      throw StateError(\n          'Only precedence DFAs may contain a precedence start state.');\n    }\n\n    // s0.edges is never null for a precedence DFA\n    if (precedence < 0 || precedence >= s0!.edges!.length) {\n      return null;\n    }\n\n    return s0!.edges![precedence];\n  }\n\n  /// Set the start state for a specific precedence value.\n  ///\n  /// @param precedence The current precedence.\n  /// @param startState The start state corresponding to the specified\n  /// precedence.\n  ///\n  /// @throws IllegalStateException if this is not a precedence DFA.\n  /// @see #isPrecedenceDfa()\n  void setPrecedenceStartState(int precedence, DFAState startState) {\n    if (!isPrecedenceDfa()) {\n      throw StateError(\n          'Only precedence DFAs may contain a precedence start state.');\n    }\n\n    if (precedence < 0) {\n      return;\n    }\n\n    // synchronization on s0 here is ok. when the DFA is turned into a\n    // precedence DFA, s0 will be initialized once and not updated again\n    // s0.edges is never null for a precedence DFA\n    if (precedence >= s0!.edges!.length) {\n      final original = s0!.edges!;\n      s0!.edges = List.filled(precedence + 1, null);\n      List.copyRange(s0!.edges!, 0, original);\n    }\n\n    s0!.edges![precedence] = startState;\n  }\n\n  /// Return a list of all states in this DFA, ordered by state number.\n\n  List<DFAState> getStates() {\n    final result = states.keys.toList();\n    result.sort((DFAState o1, DFAState o2) {\n      return o1.stateNumber - o2.stateNumber;\n    });\n\n    return result;\n  }\n\n  @override\n  String toString([Vocabulary? vocabulary]) {\n    vocabulary = vocabulary ?? VocabularyImpl.EMPTY_VOCABULARY;\n    if (s0 == null) {\n      return '';\n    }\n\n    final serializer = DFASerializer(this, vocabulary);\n    return serializer.toString();\n  }\n\n  String toLexerString() {\n    if (s0 == null) return '';\n    DFASerializer serializer = LexerDFASerializer(this);\n    return serializer.toString();\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/dfa/src/dfa_serializer.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../util/utils.dart';\nimport '../../vocabulary.dart';\nimport 'dfa.dart';\nimport 'dfa_state.dart';\n\n/// A DFA walker that knows how to dump them to serialized strings. */\nclass DFASerializer {\n  final DFA dfa;\n\n  final Vocabulary vocabulary;\n\n  DFASerializer(this.dfa, this.vocabulary);\n\n  @override\n  String toString() {\n    if (dfa.s0 == null) return 'null';\n    final buf = StringBuffer();\n    final states = dfa.getStates();\n    for (var s in states) {\n      var n = 0;\n      if (s.edges != null) n = s.edges!.length;\n      for (var i = 0; i < n; i++) {\n        final t = s.edges![i];\n        if (t != null && t.stateNumber != 0x7FFFFFFF) {\n          buf.write(getStateString(s));\n          final label = getEdgeLabel(i);\n          buf.write('-');\n          buf.write(label);\n          buf.write('->');\n          buf.write(getStateString(t));\n          buf.write('\\n');\n        }\n      }\n    }\n\n    final output = buf.toString();\n    if (output.isEmpty) return 'null';\n    //return Utils.sortLinesInString(output);\n    return output;\n  }\n\n  String getEdgeLabel(int i) {\n    return vocabulary.getDisplayName(i - 1);\n  }\n\n  String getStateString(DFAState s) {\n    final n = s.stateNumber;\n    final baseStateStr = (s.isAcceptState ? ':' : '') +\n        's$n' +\n        (s.requiresFullContext ? '^' : '');\n    if (s.isAcceptState) {\n      if (s.predicates != null) {\n        return baseStateStr + '=>${arrayToString(s.predicates)}';\n      } else {\n        return baseStateStr + '=>${s.prediction}';\n      }\n    } else {\n      return baseStateStr;\n    }\n  }\n}\n\nclass LexerDFASerializer extends DFASerializer {\n  LexerDFASerializer(dfa) : super(dfa, VocabularyImpl.EMPTY_VOCABULARY);\n\n  @override\n  String getEdgeLabel(i) {\n    return \"'\" + String.fromCharCode(i) + \"'\";\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/dfa/src/dfa_state.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../atn/atn.dart';\nimport '../../util/murmur_hash.dart';\nimport '../../util/utils.dart';\n\n/// Map a predicate to a predicted alternative. */\nclass PredPrediction {\n  final SemanticContext pred;\n  final int alt;\n\n  PredPrediction(this.pred, this.alt);\n\n  @override\n  String toString() {\n    return '($pred, $alt)';\n  }\n}\n\n/// A DFA state represents a set of possible ATN configurations.\n///  As Aho, Sethi, Ullman p. 117 says \"The DFA uses its state\n///  to keep track of all possible states the ATN can be in after\n///  reading each input symbol.  That is to say, after reading\n///  input a1a2..an, the DFA is in a state that represents the\n///  subset T of the states of the ATN that are reachable from the\n///  ATN's start state along some path labeled a1a2..an.\"\n///  In conventional NFA&rarr;DFA conversion, therefore, the subset T\n///  would be a bitset representing the set of states the\n///  ATN could be in.  We need to track the alt predicted by each\n///  state as well, however.  More importantly, we need to maintain\n///  a stack of states, tracking the closure operations as they\n///  jump from rule to rule, emulating rule invocations (method calls).\n///  I have to add a stack to simulate the proper lookahead sequences for\n///  the underlying LL grammar from which the ATN was derived.\n///\n///  <p>I use a set of ATNConfig objects not simple states.  An ATNConfig\n///  is both a state (ala normal conversion) and a RuleContext describing\n///  the chain of rules (if any) followed to arrive at that state.</p>\n///\n///  <p>A DFA state may have multiple references to a particular state,\n///  but with different ATN contexts (with same or different alts)\n///  meaning that state was reached via a different set of rule invocations.</p>\nclass DFAState {\n  int stateNumber;\n\n  ATNConfigSet configs = ATNConfigSet();\n\n  /// {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)\n  ///  {@link Token#EOF} maps to {@code edges[0]}.\n\n  List<DFAState?>? edges;\n\n  bool isAcceptState = false;\n\n  /// if accept state, what ttype do we match or alt do we predict?\n  ///  This is set to {@link ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or\n  ///  {@link #requiresFullContext}.\n  int prediction = 0;\n\n  LexerActionExecutor? lexerActionExecutor;\n\n  /// Indicates that this state was created during SLL prediction that\n  /// discovered a conflict between the configurations in the state. Future\n  /// {@link ParserATNSimulator#execATN} invocations immediately jumped doing\n  /// full context prediction if this field is true.\n  bool requiresFullContext = false;\n\n  /// During SLL parsing, this is a list of predicates associated with the\n  ///  ATN configurations of the DFA state. When we have predicates,\n  ///  {@link #requiresFullContext} is [false] since full context prediction evaluates predicates\n  ///  on-the-fly. If this is not null, then {@link #prediction} is\n  ///  {@link ATN#INVALID_ALT_NUMBER}.\n  ///\n  ///  <p>We only use these for non-{@link #requiresFullContext} but conflicting states. That\n  ///  means we know from the context (it's $ or we don't dip into outer\n  ///  context) that it's an ambiguity not a conflict.</p>\n  ///\n  ///  <p>This list is computed by {@link ParserATNSimulator#predicateDFAState}.</p>\n\n  List<PredPrediction>? predicates;\n\n  DFAState({this.stateNumber = -1, required this.configs});\n\n  /// Get the set of all alts mentioned by all ATN configurations in this\n  ///  DFA state.\n  Set<int>? get altSet {\n    final alts = <int>{};\n\n    for (var c in configs) {\n      alts.add(c.alt);\n    }\n\n    if (alts.isEmpty) return null;\n    return alts;\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize(7);\n    hash = MurmurHash.update(hash, configs.hashCode);\n    hash = MurmurHash.finish(hash, 1);\n    return hash;\n  }\n\n  /// Two [DFAState] instances are equal if their ATN configuration sets\n  /// are the same. This method is used to see if a state already exists.\n  ///\n  /// <p>Because the number of alternatives and number of ATN configurations are\n  /// finite, there is a finite number of DFA states that can be processed.\n  /// This is necessary to show that the algorithm terminates.</p>\n  ///\n  /// <p>Cannot test the DFA state numbers here because in\n  /// {@link ParserATNSimulator#addDFAState} we need to know if any other state\n  /// exists that has this exact set of ATN configurations. The\n  /// {@link #stateNumber} is irrelevant.</p>\n\n  @override\n  bool operator ==(Object other) {\n    // compare set of ATN configurations in this set with other\n    if (identical(this, other)) return true;\n\n    if (other is! DFAState) {\n      return false;\n    }\n\n    return configs == other.configs;\n  }\n\n  @override\n  String toString() {\n    final buf = StringBuffer();\n    buf.write('$stateNumber:$configs');\n    if (isAcceptState) {\n      buf.write('=>');\n      if (predicates != null) {\n        buf.write(arrayToString(predicates));\n      } else {\n        buf.write(prediction);\n      }\n    }\n    return buf.toString();\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/error/error.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport 'src/diagnostic_error_listener.dart';\nexport 'src/error_listener.dart';\nexport 'src/error_strategy.dart';\nexport 'src/errors.dart';\n"
  },
  {
    "path": "runtime/Dart/lib/src/error/src/diagnostic_error_listener.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../atn/atn.dart';\nimport '../../dfa/dfa.dart';\nimport '../../interval_set.dart';\nimport '../../parser.dart';\nimport '../../util/bit_set.dart';\nimport 'error_listener.dart';\n\n/// This implementation of [ANTLRErrorListener] can be used to identify\n/// certain potential correctness and performance problems in grammars. \"Reports\"\n/// are made by calling {@link Parser#notifyErrorListeners} with the appropriate\n/// message.\n///\n/// <ul>\n/// <li><b>Ambiguities</b>: These are cases where more than one path through the\n/// grammar can match the input.</li>\n/// <li><b>Weak context sensitivity</b>: These are cases where full-context\n/// prediction resolved an SLL conflict to a unique alternative which equaled the\n/// minimum alternative of the SLL conflict.</li>\n/// <li><b>Strong (forced) context sensitivity</b>: These are cases where the\n/// full-context prediction resolved an SLL conflict to a unique alternative,\n/// <em>and</em> the minimum alternative of the SLL conflict was found to not be\n/// a truly viable alternative. Two-stage parsing cannot be used for inputs where\n/// this situation occurs.</li>\n/// </ul>\nclass DiagnosticErrorListener extends BaseErrorListener {\n  /// When [true], only exactly known ambiguities are reported.\n  final bool exactOnly;\n\n  /// Initializes a new instance of [DiagnosticErrorListener], specifying\n  /// whether all ambiguities or only exact ambiguities are reported.\n  ///\n  /// @param exactOnly [true] to report only exact ambiguities, otherwise\n  /// [false] to report all ambiguities.\n  DiagnosticErrorListener([this.exactOnly = true]);\n\n  @override\n  void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex,\n      int stopIndex, bool exact, BitSet? ambigAlts, ATNConfigSet configs) {\n    if (exactOnly && !exact) {\n      return;\n    }\n\n    final decision = getDecisionDescription(recognizer, dfa);\n    final conflictingAlts = getConflictingAlts(ambigAlts, configs);\n    final text =\n        recognizer.tokenStream.getText(Interval.of(startIndex, stopIndex));\n    final message =\n        \"reportAmbiguity d=$decision: ambigAlts=$conflictingAlts, input='$text'\";\n    recognizer.notifyErrorListeners(message);\n  }\n\n  @override\n  void reportAttemptingFullContext(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    BitSet? conflictingAlts,\n    ATNConfigSet configs,\n  ) {\n    final decision = getDecisionDescription(recognizer, dfa);\n    final text = recognizer.tokenStream.getText(\n      Interval.of(startIndex, stopIndex),\n    );\n    final message = \"reportAttemptingFullContext d=$decision, input='$text'\";\n    recognizer.notifyErrorListeners(message);\n  }\n\n  @override\n  void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex,\n      int stopIndex, int prediction, ATNConfigSet configs) {\n    final decision = getDecisionDescription(recognizer, dfa);\n    final text =\n        recognizer.tokenStream.getText(Interval.of(startIndex, stopIndex));\n    final message = \"reportContextSensitivity d=$decision, input='$text'\";\n    recognizer.notifyErrorListeners(message);\n  }\n\n  String getDecisionDescription(Parser recognizer, DFA dfa) {\n    final decision = dfa.decision;\n    final ruleIndex = dfa.atnStartState?.ruleIndex;\n\n    final ruleNames = recognizer.ruleNames;\n    if (ruleIndex == null || ruleIndex < 0 || ruleIndex >= ruleNames.length) {\n      return decision.toString();\n    }\n\n    final ruleName = ruleNames[ruleIndex];\n    if (ruleName.isEmpty) {\n      return decision.toString();\n    }\n\n    return '$decision ($ruleName)';\n  }\n\n  /// Computes the set of conflicting or ambiguous alternatives from a\n  /// configuration set, if that information was not already provided by the\n  /// parser.\n  ///\n  /// @param reportedAlts The set of conflicting or ambiguous alternatives, as\n  /// reported by the parser.\n  /// @param configs The conflicting or ambiguous configuration set.\n  /// @return Returns [reportedAlts] if it is not null, otherwise\n  /// returns the set of alternatives represented in [configs].\n  BitSet getConflictingAlts(BitSet? reportedAlts, ATNConfigSet configs) {\n    if (reportedAlts != null) {\n      return reportedAlts;\n    }\n\n    final result = BitSet();\n    for (var config in configs) {\n      result.set(config.alt);\n    }\n\n    return result;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/error/src/error_listener.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../atn/atn.dart';\nimport '../../dfa/dfa.dart';\nimport '../../parser.dart';\nimport '../../recognizer.dart';\nimport '../../util/bit_set.dart';\nimport 'errors.dart';\n\nimport '../../util/platform_stub.dart'\n    if (dart.library.io) '../../util/platform_io.dart'\n    if (dart.library.html) '../../util/platform_html.dart';\n\nabstract class ErrorListener {\n  /// Upon syntax error, notify any interested parties. This is not how to\n  /// recover from errors or compute error messages. [ANTLRErrorStrategy]\n  /// specifies how to recover from syntax errors and how to compute error\n  /// messages. This listener's job is simply to emit a computed message,\n  /// though it has enough information to create its own message in many cases.\n  ///\n  /// <p>The [RecognitionException] is non-null for all syntax errors except\n  /// when we discover mismatched token errors that we can recover from\n  /// in-line, without returning from the surrounding rule (via the single\n  /// token insertion and deletion mechanism).</p>\n  ///\n  /// @param recognizer\n  ///        What parser got the error. From this\n  /// \t\t  object, you can access the context as well\n  /// \t\t  as the input stream.\n  /// @param offendingSymbol\n  ///        The offending token in the input token\n  /// \t\t  stream, unless recognizer is a lexer (then it's null). If\n  /// \t\t  no viable alternative error, [e] has token at which we\n  /// \t\t  started production for the decision.\n  /// @param line\n  /// \t\t  The line number in the input where the error occurred.\n  /// @param charPositionInLine\n  /// \t\t  The character position within that line where the error occurred.\n  /// @param msg\n  /// \t\t  The message to emit.\n  /// @param e\n  ///        The exception generated by the parser that led to\n  ///        the reporting of an error. It is null in the case where\n  ///        the parser was able to recover in line without exiting the\n  ///        surrounding rule.\n  void syntaxError(\n    Recognizer recognizer,\n    Object? offendingSymbol,\n    int? line,\n    int charPositionInLine,\n    String msg,\n    RecognitionException? e,\n  );\n\n  /// This method is called by the parser when a full-context prediction\n  /// results in an ambiguity.\n  ///\n  /// <p>Each full-context prediction which does not result in a syntax error\n  /// will call either {@link #reportContextSensitivity} or\n  /// {@link #reportAmbiguity}.</p>\n  ///\n  /// <p>When [ambigAlts] is not null, it contains the set of potentially\n  /// viable alternatives identified by the prediction algorithm. When\n  /// [ambigAlts] is null, use {@link ATNConfigSet#getAlts} to obtain the\n  /// represented alternatives from the [configs] argument.</p>\n  ///\n  /// <p>When [exact] is [true], <em>all</em> of the potentially\n  /// viable alternatives are truly viable, i.e. this is reporting an exact\n  /// ambiguity. When [exact] is [false], <em>at least two</em> of\n  /// the potentially viable alternatives are viable for the current input, but\n  /// the prediction algorithm terminated as soon as it determined that at\n  /// least the <em>minimum</em> potentially viable alternative is truly\n  /// viable.</p>\n  ///\n  /// <p>When the {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} prediction\n  /// mode is used, the parser is required to identify exact ambiguities so\n  /// [exact] will always be [true].</p>\n  ///\n  /// <p>This method is not used by lexers.</p>\n  ///\n  /// @param recognizer the parser instance\n  /// @param dfa the DFA for the current decision\n  /// @param startIndex the input index where the decision started\n  /// @param stopIndex the input input where the ambiguity was identified\n  /// @param exact [true] if the ambiguity is exactly known, otherwise\n  /// [false]. This is always [true] when\n  /// {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used.\n  /// @param ambigAlts the potentially ambiguous alternatives, or null\n  /// to indicate that the potentially ambiguous alternatives are the complete\n  /// set of represented alternatives in [configs]\n  /// @param configs the ATN configuration set where the ambiguity was\n  /// identified\n  void reportAmbiguity(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    bool exact,\n    BitSet? ambigAlts,\n    ATNConfigSet configs,\n  );\n\n  /// This method is called when an SLL conflict occurs and the parser is about\n  /// to use the full context information to make an LL decision.\n  ///\n  /// <p>If one or more configurations in [configs] contains a semantic\n  /// predicate, the predicates are evaluated before this method is called. The\n  /// subset of alternatives which are still viable after predicates are\n  /// evaluated is reported in [conflictingAlts].</p>\n  ///\n  /// <p>This method is not used by lexers.</p>\n  ///\n  /// @param recognizer the parser instance\n  /// @param dfa the DFA for the current decision\n  /// @param startIndex the input index where the decision started\n  /// @param stopIndex the input index where the SLL conflict occurred\n  /// @param conflictingAlts The specific conflicting alternatives. If this is\n  /// null, the conflicting alternatives are all alternatives\n  /// represented in [configs]. At the moment, conflictingAlts is non-null\n  /// (for the reference implementation, but Sam's optimized version can see this\n  /// as null).\n  /// @param configs the ATN configuration set where the SLL conflict was\n  /// detected\n  void reportAttemptingFullContext(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    BitSet? conflictingAlts,\n    ATNConfigSet configs,\n  );\n\n  /// This method is called by the parser when a full-context prediction has a\n  /// unique result.\n  ///\n  /// <p>Each full-context prediction which does not result in a syntax error\n  /// will call either {@link #reportContextSensitivity} or\n  /// {@link #reportAmbiguity}.</p>\n  ///\n  /// <p>For prediction implementations that only evaluate full-context\n  /// predictions when an SLL conflict is found (including the default\n  /// [ParserATNSimulator] implementation), this method reports cases\n  /// where SLL conflicts were resolved to unique full-context predictions,\n  /// i.e. the decision was context-sensitive. This report does not necessarily\n  /// indicate a problem, and it may appear even in completely unambiguous\n  /// grammars.</p>\n  ///\n  /// <p>[configs] may have more than one represented alternative if the\n  /// full-context prediction algorithm does not evaluate predicates before\n  /// beginning the full-context prediction. In all cases, the final prediction\n  /// is passed as the [prediction] argument.</p>\n  ///\n  /// <p>Note that the definition of \"context sensitivity\" in this method\n  /// differs from the concept in {@link DecisionInfo#contextSensitivities}.\n  /// This method reports all instances where an SLL conflict occurred but LL\n  /// parsing produced a unique result, whether or not that unique result\n  /// matches the minimum alternative in the SLL conflicting set.</p>\n  ///\n  /// <p>This method is not used by lexers.</p>\n  ///\n  /// @param recognizer the parser instance\n  /// @param dfa the DFA for the current decision\n  /// @param startIndex the input index where the decision started\n  /// @param stopIndex the input index where the context sensitivity was\n  /// finally determined\n  /// @param prediction the unambiguous result of the full-context prediction\n  /// @param configs the ATN configuration set where the unambiguous prediction\n  /// was determined\n  void reportContextSensitivity(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    int prediction,\n    ATNConfigSet configs,\n  );\n}\n\nclass BaseErrorListener extends ErrorListener {\n  @override\n  void reportAmbiguity(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    bool exact,\n    BitSet? ambigAlts,\n    ATNConfigSet configs,\n  ) {}\n\n  @override\n  void reportAttemptingFullContext(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    BitSet? conflictingAlts,\n    ATNConfigSet configs,\n  ) {}\n\n  @override\n  void reportContextSensitivity(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    int prediction,\n    ATNConfigSet configs,\n  ) {}\n\n  @override\n  void syntaxError(\n    Recognizer<ATNSimulator> recognizer,\n    Object? offendingSymbol,\n    int? line,\n    int charPositionInLine,\n    String msg,\n    RecognitionException? e,\n  ) {}\n}\n\nclass ConsoleErrorListener extends BaseErrorListener {\n  /// Provides a default instance of [ConsoleErrorListener].\n  static final INSTANCE = ConsoleErrorListener();\n\n  /// {@inheritDoc}\n  ///\n  /// <p>\n  /// This implementation prints messages to {@link System//err} containing the\n  /// values of [line], [charPositionInLine], and [msg] using\n  /// the following format.</p>\n  ///\n  /// <pre>\n  /// line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>\n  /// </pre>\n  @override\n  void syntaxError(recognizer, offendingSymbol, line, column, msg, e) {\n    stderrWriteln('line $line:$column $msg');\n  }\n}\n\n/// This implementation of [ErrorListener] dispatches all calls to a\n/// collection of delegate listeners. This reduces the effort required to support multiple\n/// listeners.\nclass ProxyErrorListener implements ErrorListener {\n  final List<ErrorListener> delegates;\n\n  ProxyErrorListener(this.delegates) {\n    // ignore: unnecessary_null_comparison\n    if (delegates == null) {\n      throw ArgumentError.notNull('delegates');\n    }\n  }\n\n  @override\n  void syntaxError(\n    Recognizer recognizer,\n    Object? offendingSymbol,\n    int? line,\n    int charPositionInLine,\n    String msg,\n    RecognitionException? e,\n  ) {\n    for (final listener in delegates) {\n      listener.syntaxError(\n        recognizer,\n        offendingSymbol,\n        line,\n        charPositionInLine,\n        msg,\n        e,\n      );\n    }\n  }\n\n  @override\n  void reportAmbiguity(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    bool exact,\n    BitSet? ambigAlts,\n    ATNConfigSet configs,\n  ) {\n    for (final listener in delegates) {\n      listener.reportAmbiguity(\n          recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs);\n    }\n  }\n\n  @override\n  void reportAttemptingFullContext(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    BitSet? conflictingAlts,\n    ATNConfigSet configs,\n  ) {\n    for (final listener in delegates) {\n      listener.reportAttemptingFullContext(\n        recognizer,\n        dfa,\n        startIndex,\n        stopIndex,\n        conflictingAlts,\n        configs,\n      );\n    }\n  }\n\n  @override\n  void reportContextSensitivity(\n    Parser recognizer,\n    DFA dfa,\n    int startIndex,\n    int stopIndex,\n    int prediction,\n    ATNConfigSet configs,\n  ) {\n    for (final listener in delegates) {\n      listener.reportContextSensitivity(\n        recognizer,\n        dfa,\n        startIndex,\n        stopIndex,\n        prediction,\n        configs,\n      );\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/error/src/error_strategy.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:developer';\n\nimport 'package:logging/logging.dart';\n\nimport '../../atn/atn.dart';\nimport '../../interval_set.dart';\nimport '../../misc/misc.dart';\nimport '../../parser.dart';\nimport '../../parser_rule_context.dart';\nimport '../../rule_context.dart';\nimport '../../token.dart';\nimport '../../tree/tree.dart';\nimport 'errors.dart';\n\n/// The interface for defining strategies to deal with syntax errors encountered\n/// during a parse by ANTLR-generated parsers. We distinguish between three\n/// different kinds of errors:\n///\n/// <ul>\n/// <li>The parser could not figure out which path to take in the ATN (none of\n/// the available alternatives could possibly match)</li>\n/// <li>The current input does not match what we were looking for</li>\n/// <li>A predicate evaluated to false</li>\n/// </ul>\n///\n/// Implementations of this interface report syntax errors by calling\n/// {@link Parser#notifyErrorListeners}.\n///\n/// <p>TODO: what to do about lexers</p>\nabstract class ErrorStrategy {\n  /// Reset the error handler state for the specified [recognizer].\n  /// @param recognizer the parser instance\n  void reset(Parser recognizer);\n\n  /// This method is called when an unexpected symbol is encountered during an\n  /// inline match operation, such as {@link Parser#match}. If the error\n  /// strategy successfully recovers from the match failure, this method\n  /// returns the [Token] instance which should be treated as the\n  /// successful result of the match.\n  ///\n  /// <p>This method handles the consumption of any tokens - the caller should\n  /// <b>not</b> call {@link Parser#consume} after a successful recovery.</p>\n  ///\n  /// <p>Note that the calling code will not report an error if this method\n  /// returns successfully. The error strategy implementation is responsible\n  /// for calling {@link Parser#notifyErrorListeners} as appropriate.</p>\n  ///\n  /// @param recognizer the parser instance\n  /// @ if the error strategy was not able to\n  /// recover from the unexpected input symbol\n  Token recoverInline(Parser recognizer);\n\n  /// This method is called to recover from exception [e]. This method is\n  /// called after {@link #reportError} by the default exception handler\n  /// generated for a rule method.\n  ///\n  /// @see #reportError\n  ///\n  /// @param recognizer the parser instance\n  /// @param e the recognition exception to recover from\n  /// @ if the error strategy could not recover from\n  /// the recognition exception\n  void recover(Parser recognizer, RecognitionException e);\n\n  /// This method provides the error handler with an opportunity to handle\n  /// syntactic or semantic errors in the input stream before they result in a\n  /// [RecognitionException].\n  ///\n  /// <p>The generated code currently contains calls to {@link #sync} after\n  /// entering the decision state of a closure block ({@code (...)*} or\n  /// {@code (...)+}).</p>\n  ///\n  /// <p>For an implementation based on Jim Idle's \"magic sync\" mechanism, see\n  /// {@link DefaultErrorStrategy#sync}.</p>\n  ///\n  /// @see DefaultErrorStrategy#sync\n  ///\n  /// @param recognizer the parser instance\n  /// @ if an error is detected by the error\n  /// strategy but cannot be automatically recovered at the current state in\n  /// the parsing process\n  void sync(Parser recognizer);\n\n  /// Tests whether or not [recognizer] is in the process of recovering\n  /// from an error. In error recovery mode, {@link Parser#consume} adds\n  /// symbols to the parse tree by calling\n  /// {@link Parser#createErrorNode(ParserRuleContext, Token)} then\n  /// {@link ParserRuleContext#addErrorNode(ErrorNode)} instead of\n  /// {@link Parser#createTerminalNode(ParserRuleContext, Token)}.\n  ///\n  /// @param recognizer the parser instance\n  /// @return [true] if the parser is currently recovering from a parse\n  /// error, otherwise [false]\n  bool inErrorRecoveryMode(Parser recognizer);\n\n  /// This method is called by when the parser successfully matches an input\n  /// symbol.\n  ///\n  /// @param recognizer the parser instance\n  void reportMatch(Parser recognizer);\n\n  /// Report any kind of [RecognitionException]. This method is called by\n  /// the default exception handler generated for a rule method.\n  ///\n  /// @param recognizer the parser instance\n  /// @param e the recognition exception to report\n  void reportError(Parser recognizer, RecognitionException e);\n}\n\n/// This is the default implementation of [ANTLRErrorStrategy] used for\n/// error reporting and recovery in ANTLR parsers.\nclass DefaultErrorStrategy implements ErrorStrategy {\n  /// Indicates whether the error strategy is currently \"recovering from an\n  /// error\". This is used to suppress reporting multiple error messages while\n  /// attempting to recover from a detected syntax error.\n  ///\n  /// @see #inErrorRecoveryMode\n  bool errorRecoveryMode = false;\n\n  /// The index into the input stream where the last error occurred.\n  /// \tThis is used to prevent infinite loops where an error is found\n  ///  but no token is consumed during recovery...another error is found,\n  ///  ad nauseum.  This is a failsafe mechanism to guarantee that at least\n  ///  one token/tree node is consumed for two errors.\n  int lastErrorIndex = -1;\n\n  IntervalSet? lastErrorStates;\n\n  /// This field is used to propagate information about the lookahead following\n  /// the previous match. Since prediction prefers completing the current rule\n  /// to error recovery efforts, error reporting may occur later than the\n  /// original point where it was discoverable. The original context is used to\n  /// compute the true expected sets as though the reporting occurred as early\n  /// as possible.\n  ParserRuleContext? nextTokensContext;\n\n  /// @see #nextTokensContext\n  int? nextTokensState;\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation simply calls {@link #endErrorCondition} to\n  /// ensure that the handler is not in error recovery mode.</p>\n\n  @override\n  void reset(Parser recognizer) {\n    endErrorCondition(recognizer);\n  }\n\n  /// This method is called to enter error recovery mode when a recognition\n  /// exception is reported.\n  ///\n  /// @param recognizer the parser instance\n  void beginErrorCondition(Parser recognizer) {\n    errorRecoveryMode = true;\n  }\n\n  /// {@inheritDoc}\n\n  @override\n  bool inErrorRecoveryMode(Parser recognizer) {\n    return errorRecoveryMode;\n  }\n\n  /// This method is called to leave error recovery mode after recovering from\n  /// a recognition exception.\n  ///\n  /// @param recognizer\n  void endErrorCondition(Parser recognizer) {\n    errorRecoveryMode = false;\n    lastErrorStates = null;\n    lastErrorIndex = -1;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation simply calls {@link #endErrorCondition}.</p>\n\n  @override\n  void reportMatch(Parser recognizer) {\n    endErrorCondition(recognizer);\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation returns immediately if the handler is already\n  /// in error recovery mode. Otherwise, it calls {@link #beginErrorCondition}\n  /// and dispatches the reporting task based on the runtime type of [e]\n  /// according to the following table.</p>\n  ///\n  /// <ul>\n  /// <li>[NoViableAltException]: Dispatches the call to\n  /// {@link #reportNoViableAlternative}</li>\n  /// <li>[InputMismatchException]: Dispatches the call to\n  /// {@link #reportInputMismatch}</li>\n  /// <li>[FailedPredicateException]: Dispatches the call to\n  /// {@link #reportFailedPredicate}</li>\n  /// <li>All other types: calls {@link Parser#notifyErrorListeners} to report\n  /// the exception</li>\n  /// </ul>\n\n  @override\n  void reportError(Parser recognizer, RecognitionException e) {\n    // if we've already reported an error and have not matched a token\n    // yet successfully, don't report any errors.\n    if (inErrorRecoveryMode(recognizer)) {\n//\t\t\tSystem.err.print(\"[SPURIOUS] \");\n      return; // don't report spurious errors\n    }\n    beginErrorCondition(recognizer);\n    if (e is NoViableAltException) {\n      reportNoViableAlternative(recognizer, e);\n    } else if (e is InputMismatchException) {\n      reportInputMismatch(recognizer, e);\n    } else if (e is FailedPredicateException) {\n      reportFailedPredicate(recognizer, e);\n    } else {\n      log('unknown recognition error type: ${e.runtimeType}',\n          level: Level.SEVERE.value);\n      recognizer.notifyErrorListeners(e.message, e.offendingToken, e);\n    }\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation resynchronizes the parser by consuming tokens\n  /// until we find one in the resynchronization set--loosely the set of tokens\n  /// that can follow the current rule.</p>\n\n  @override\n  void recover(Parser recognizer, RecognitionException e) {\n//\t\tSystem.out.println(\"recover in \"+recognizer.getRuleInvocationStack()+\n//\t\t\t\t\t\t   \" index=\"+recognizer.inputStream.index()+\n//\t\t\t\t\t\t   \", lastErrorIndex=\"+\n//\t\t\t\t\t\t   lastErrorIndex+\n//\t\t\t\t\t\t   \", states=\"+lastErrorStates);\n    if (lastErrorIndex == recognizer.inputStream.index &&\n        lastErrorStates != null &&\n        lastErrorStates!.contains(recognizer.state)) {\n      // uh oh, another error at same token index and previously-visited\n      // state in ATN; must be a case where LT(1) is in the recovery\n      // token set so nothing got consumed. Consume a single token\n      // at least to prevent an infinite loop; this is a failsafe.\n//\t\t\tlog(\"seen error condition before index=, level: Level.SEVERE.value\"+\n//\t\t\t\t\t\t\t   lastErrorIndex+\", states=\"+lastErrorStates);\n//\t\t\tlog(\"FAILSAFE consumes \"+recognizer.getTokenNames()[recognizer.inputStream.LA(1)], level: Level.SEVERE.value);\n      recognizer.consume();\n    }\n    lastErrorIndex = recognizer.inputStream.index;\n    lastErrorStates ??= IntervalSet();\n    lastErrorStates!.addOne(recognizer.state);\n    final followSet = getErrorRecoverySet(recognizer);\n    consumeUntil(recognizer, followSet);\n  }\n\n  /// The default implementation of {@link ANTLRErrorStrategy#sync} makes sure\n  /// that the current lookahead symbol is consistent with what were expecting\n  /// at this point in the ATN. You can call this anytime but ANTLR only\n  /// generates code to check before subrules/loops and each iteration.\n  ///\n  /// <p>Implements Jim Idle's magic sync mechanism in closures and optional\n  /// subrules. E.g.,</p>\n  ///\n  /// <pre>\n  /// a : sync ( stuff sync )* ;\n  /// sync : {consume to what can follow sync} ;\n  /// </pre>\n  ///\n  /// At the start of a sub rule upon error, {@link #sync} performs single\n  /// token deletion, if possible. If it can't do that, it bails on the current\n  /// rule and uses the default error recovery, which consumes until the\n  /// resynchronization set of the current rule.\n  ///\n  /// <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block\n  /// with an empty alternative), then the expected set includes what follows\n  /// the subrule.</p>\n  ///\n  /// <p>During loop iteration, it consumes until it sees a token that can start a\n  /// sub rule or what follows loop. Yes, that is pretty aggressive. We opt to\n  /// stay in the loop as long as possible.</p>\n  ///\n  /// <p><strong>ORIGINS</strong></p>\n  ///\n  /// <p>Previous versions of ANTLR did a poor job of their recovery within loops.\n  /// A single mismatch token or missing token would force the parser to bail\n  /// out of the entire rules surrounding the loop. So, for rule</p>\n  ///\n  /// <pre>\n  /// classDef : 'class' ID '{' member* '}'\n  /// </pre>\n  ///\n  /// input with an extra token between members would force the parser to\n  /// consume until it found the next class definition rather than the next\n  /// member definition of the current class.\n  ///\n  /// <p>This functionality cost a little bit of effort because the parser has to\n  /// compare token set at the start of the loop and at each iteration. If for\n  /// some reason speed is suffering for you, you can turn off this\n  /// functionality by simply overriding this method as a blank { }.</p>\n\n  @override\n  void sync(Parser recognizer) {\n    final s = recognizer.interpreter!.atn.states[recognizer.state]!;\n//\t\tlog(\"sync @ \"+s.stateNumber+\"=\"+s.getClass().getSimpleName(), level: Level.SEVERE.value);\n    // If already recovering, don't try to sync\n    if (inErrorRecoveryMode(recognizer)) {\n      return;\n    }\n\n    final tokens = recognizer.inputStream;\n    final la = tokens.LA(1)!;\n\n    // try cheaper subset first; might get lucky. seems to shave a wee bit off\n    final nextTokens = recognizer.getATN().nextTokens(s);\n    if (nextTokens.contains(la)) {\n      // We are sure the token matches\n      nextTokensContext = null;\n      nextTokensState = ATNState.INVALID_STATE_NUMBER;\n      return;\n    }\n\n    if (nextTokens.contains(Token.EPSILON)) {\n      if (nextTokensContext == null) {\n        // It's possible the next token won't match; information tracked\n        // by sync is restricted for performance.\n        nextTokensContext = recognizer.context;\n        nextTokensState = recognizer.state;\n      }\n      return;\n    }\n\n    switch (s.stateType) {\n      case StateType.BLOCK_START:\n      case StateType.STAR_BLOCK_START:\n      case StateType.PLUS_BLOCK_START:\n      case StateType.STAR_LOOP_ENTRY:\n        // report error and recover if possible\n        if (singleTokenDeletion(recognizer) != null) {\n          return;\n        }\n\n        throw InputMismatchException(recognizer);\n\n      case StateType.PLUS_LOOP_BACK:\n      case StateType.STAR_LOOP_BACK:\n//\t\t\tlog(\"at loop back: \"+s.getClass().getSimpleName(), level: Level.SEVERE.value);\n        reportUnwantedToken(recognizer);\n        final expecting = recognizer.expectedTokens;\n        final whatFollowsLoopIterationOrRule =\n            expecting | getErrorRecoverySet(recognizer);\n        consumeUntil(recognizer, whatFollowsLoopIterationOrRule);\n        break;\n\n      default:\n        // do nothing if we can't identify the exact kind of ATN state\n        break;\n    }\n  }\n\n  /// This is called by {@link #reportError} when the exception is a\n  /// [NoViableAltException].\n  ///\n  /// @see #reportError\n  ///\n  /// @param recognizer the parser instance\n  /// @param e the recognition exception\n  void reportNoViableAlternative(Parser recognizer, NoViableAltException e) {\n    final tokens = recognizer.inputStream;\n    String input;\n\n    if (e.startToken.type == Token.EOF) {\n      input = '<EOF>';\n    } else {\n      input = tokens.getTextRange(e.startToken, e.offendingToken);\n    }\n\n    final msg = 'no viable alternative at input ' + escapeWSAndQuote(input);\n    recognizer.notifyErrorListeners(msg, e.offendingToken, e);\n  }\n\n  /// This is called by {@link #reportError} when the exception is an\n  /// [InputMismatchException].\n  ///\n  /// @see #reportError\n  ///\n  /// @param recognizer the parser instance\n  /// @param e the recognition exception\n  void reportInputMismatch(Parser recognizer, InputMismatchException e) {\n    final msg = 'mismatched input ' +\n        getTokenErrorDisplay(e.offendingToken) +\n        ' expecting ' +\n        e.expectedTokens!.toString(vocabulary: recognizer.vocabulary);\n    recognizer.notifyErrorListeners(msg, e.offendingToken, e);\n  }\n\n  /// This is called by {@link #reportError} when the exception is a\n  /// [FailedPredicateException].\n  ///\n  /// @see #reportError\n  ///\n  /// @param recognizer the parser instance\n  /// @param e the recognition exception\n  void reportFailedPredicate(Parser recognizer, FailedPredicateException e) {\n    final ruleIndex = recognizer.context?.ruleIndex;\n    final ruleName = ruleIndex != null ? recognizer.ruleNames[ruleIndex] : '';\n    final msg = 'rule ' + ruleName + ' ' + e.message;\n    recognizer.notifyErrorListeners(msg, e.offendingToken, e);\n  }\n\n  /// This method is called to report a syntax error which requires the removal\n  /// of a token from the input stream. At the time this method is called, the\n  /// erroneous symbol is current {@code LT(1)} symbol and has not yet been\n  /// removed from the input stream. When this method returns,\n  /// [recognizer] is in error recovery mode.\n  ///\n  /// <p>This method is called when {@link #singleTokenDeletion} identifies\n  /// single-token deletion as a viable recovery strategy for a mismatched\n  /// input error.</p>\n  ///\n  /// <p>The default implementation simply returns if the handler is already in\n  /// error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n  /// enter error recovery mode, followed by calling\n  /// {@link Parser#notifyErrorListeners}.</p>\n  ///\n  /// @param recognizer the parser instance\n  void reportUnwantedToken(Parser recognizer) {\n    if (inErrorRecoveryMode(recognizer)) {\n      return;\n    }\n\n    beginErrorCondition(recognizer);\n\n    final t = recognizer.currentToken;\n    final tokenName = getTokenErrorDisplay(t);\n    final expecting = getExpectedTokens(recognizer);\n    final msg = 'extraneous input ' +\n        tokenName +\n        ' expecting ' +\n        expecting.toString(vocabulary: recognizer.vocabulary);\n    recognizer.notifyErrorListeners(msg, t, null);\n  }\n\n  /// This method is called to report a syntax error which requires the\n  /// insertion of a missing token into the input stream. At the time this\n  /// method is called, the missing token has not yet been inserted. When this\n  /// method returns, [recognizer] is in error recovery mode.\n  ///\n  /// <p>This method is called when {@link #singleTokenInsertion} identifies\n  /// single-token insertion as a viable recovery strategy for a mismatched\n  /// input error.</p>\n  ///\n  /// <p>The default implementation simply returns if the handler is already in\n  /// error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n  /// enter error recovery mode, followed by calling\n  /// {@link Parser#notifyErrorListeners}.</p>\n  ///\n  /// @param recognizer the parser instance\n  void reportMissingToken(Parser recognizer) {\n    if (inErrorRecoveryMode(recognizer)) {\n      return;\n    }\n\n    beginErrorCondition(recognizer);\n\n    final t = recognizer.currentToken;\n    final expecting = getExpectedTokens(recognizer);\n    final msg = 'missing ' +\n        expecting.toString(vocabulary: recognizer.vocabulary) +\n        ' at ' +\n        getTokenErrorDisplay(t);\n\n    recognizer.notifyErrorListeners(msg, t, null);\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation attempts to recover from the mismatched input\n  /// by using single token insertion and deletion as described below. If the\n  /// recovery attempt fails, this method throws an\n  /// [InputMismatchException].</p>\n  ///\n  /// <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>\n  ///\n  /// <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the\n  /// right token, however, then assume {@code LA(1)} is some extra spurious\n  /// token and delete it. Then consume and return the next token (which was\n  /// the {@code LA(2)} token) as the successful result of the match operation.</p>\n  ///\n  /// <p>This recovery strategy is implemented by {@link #singleTokenDeletion}.</p>\n  ///\n  /// <p><strong>MISSING TOKEN</strong> (single token insertion)</p>\n  ///\n  /// <p>If current token (at {@code LA(1)}) is consistent with what could come\n  /// after the expected {@code LA(1)} token, then assume the token is missing\n  /// and use the parser's [TokenFactory] to create it on the fly. The\n  /// \"insertion\" is performed by returning the created token as the successful\n  /// result of the match operation.</p>\n  ///\n  /// <p>This recovery strategy is implemented by {@link #singleTokenInsertion}.</p>\n  ///\n  /// <p><strong>EXAMPLE</strong></p>\n  ///\n  /// <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When\n  /// the parser returns from the nested call to [expr], it will have\n  /// call chain:</p>\n  ///\n  /// <pre>\n  /// stat &rarr; expr &rarr; atom\n  /// </pre>\n  ///\n  /// and it will be trying to match the {@code ')'} at this point in the\n  /// derivation:\n  ///\n  /// <pre>\n  /// =&gt; ID '=' '(' INT ')' ('+' atom)* ';'\n  ///                    ^\n  /// </pre>\n  ///\n  /// The attempt to match {@code ')'} will fail when it sees {@code ';'} and\n  /// call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'}\n  /// is in the set of tokens that can follow the {@code ')'} token reference\n  /// in rule [atom]. It can assume that you forgot the {@code ')'}.\n\n  @override\n  Token recoverInline(Parser recognizer) {\n// SINGLE TOKEN DELETION\n    final matchedSymbol = singleTokenDeletion(recognizer);\n    if (matchedSymbol != null) {\n// we have deleted the extra token.\n// now, move past ttype token as if all were ok\n      recognizer.consume();\n      return matchedSymbol;\n    }\n\n// SINGLE TOKEN INSERTION\n    if (singleTokenInsertion(recognizer)) {\n      return getMissingSymbol(recognizer);\n    }\n\n// even that didn't work; must throw the exception\n    InputMismatchException e;\n    if (nextTokensContext == null) {\n      e = InputMismatchException(recognizer);\n    } else {\n      e = InputMismatchException(\n        recognizer,\n        nextTokensState!,\n        nextTokensContext,\n      );\n    }\n\n    throw e;\n  }\n\n  /// This method implements the single-token insertion inline error recovery\n  /// strategy. It is called by {@link #recoverInline} if the single-token\n  /// deletion strategy fails to recover from the mismatched input. If this\n  /// method returns [true], [recognizer] will be in error recovery\n  /// mode.\n  ///\n  /// <p>This method determines whether or not single-token insertion is viable by\n  /// checking if the {@code LA(1)} input symbol could be successfully matched\n  /// if it were instead the {@code LA(2)} symbol. If this method returns\n  /// [true], the caller is responsible for creating and inserting a\n  /// token with the correct type to produce this behavior.</p>\n  ///\n  /// @param recognizer the parser instance\n  /// @return [true] if single-token insertion is a viable recovery\n  /// strategy for the current mismatched input, otherwise [false]\n  bool singleTokenInsertion(Parser recognizer) {\n    final currentSymbolType = recognizer.inputStream.LA(1)!;\n    // if current token is consistent with what could come after current\n    // ATN state, then we know we're missing a token; error recovery\n    // is free to conjure up and insert the missing token\n    final currentState = recognizer.interpreter!.atn.states[recognizer.state]!;\n    final next = currentState.transition(0).target;\n    final atn = recognizer.interpreter!.atn;\n    final expectingAtLL2 = atn.nextTokens(next, recognizer.context);\n//\t\tSystem.out.println(\"LT(2) set=\"+expectingAtLL2.toString(recognizer.getTokenNames()));\n    if (expectingAtLL2.contains(currentSymbolType)) {\n      reportMissingToken(recognizer);\n      return true;\n    }\n    return false;\n  }\n\n  /// This method implements the single-token deletion inline error recovery\n  /// strategy. It is called by {@link #recoverInline} to attempt to recover\n  /// from mismatched input. If this method returns null, the parser and error\n  /// handler state will not have changed. If this method returns non-null,\n  /// [recognizer] will <em>not</em> be in error recovery mode since the\n  /// returned token was a successful match.\n  ///\n  /// <p>If the single-token deletion is successful, this method calls\n  /// {@link #reportUnwantedToken} to report the error, followed by\n  /// {@link Parser#consume} to actually \"delete\" the extraneous token. Then,\n  /// before returning {@link #reportMatch} is called to signal a successful\n  /// match.</p>\n  ///\n  /// @param recognizer the parser instance\n  /// @return the successfully matched [Token] instance if single-token\n  /// deletion successfully recovers from the mismatched input, otherwise\n  /// null\n  Token? singleTokenDeletion(Parser recognizer) {\n    final nextTokenType = recognizer.inputStream.LA(2)!;\n    final expecting = getExpectedTokens(recognizer);\n    if (expecting.contains(nextTokenType)) {\n      reportUnwantedToken(recognizer);\n      /*\n\t\t\tlog(\"recoverFromMismatchedToken deleting , level: Level.SEVERE.value\"+\n\t\t\t\t\t\t\t   ((TokenStream)recognizer.inputStream).LT(1)+\n\t\t\t\t\t\t\t   \" since \"+((TokenStream)recognizer.inputStream).LT(2)+\n\t\t\t\t\t\t\t   \" is what we want\");\n\t\t\t*/\n      recognizer.consume(); // simply delete extra token\n      // we want to return the token we're actually matching\n      final matchedSymbol = recognizer.currentToken;\n      reportMatch(recognizer); // we know current token is correct\n      return matchedSymbol;\n    }\n    return null;\n  }\n\n  /// Conjure up a missing token during error recovery.\n  ///\n  ///  The recognizer attempts to recover from single missing\n  ///  symbols. But, actions might refer to that missing symbol.\n  ///  For example, x=ID {f($x);}. The action clearly assumes\n  ///  that there has been an identifier matched previously and that\n  ///  $x points at that token. If that token is missing, but\n  ///  the next token in the stream is what we want we assume that\n  ///  this token is missing and we keep going. Because we\n  ///  have to return some token to replace the missing token,\n  ///  we have to conjure one up. This method gives the user control\n  ///  over the tokens returned for missing tokens. Mostly,\n  ///  you will want to create something special for identifier\n  ///  tokens. For literals such as '{' and ',', the default\n  ///  action in the parser or tree parser works. It simply creates\n  ///  a CommonToken of the appropriate type. The text will be the token.\n  ///  If you change what tokens must be created by the lexer,\n  ///  override this method to create the appropriate tokens.\n  Token getMissingSymbol(Parser recognizer) {\n    final currentSymbol = recognizer.currentToken;\n    final expecting = getExpectedTokens(recognizer);\n    var expectedTokenType = Token.INVALID_TYPE;\n    if (!expecting.isNil) {\n      expectedTokenType = expecting.minElement; // get any element\n    }\n    String tokenText;\n    if (expectedTokenType == Token.EOF) {\n      tokenText = '<missing EOF>';\n    } else {\n      tokenText = '<missing ' +\n          recognizer.vocabulary.getDisplayName(expectedTokenType) +\n          '>';\n    }\n    var current = currentSymbol;\n    final lookback = recognizer.inputStream.LT(-1);\n    if (current.type == Token.EOF && lookback != null) {\n      current = lookback;\n    }\n    return recognizer.tokenFactory.create(\n      expectedTokenType,\n      tokenText,\n      Pair(current.tokenSource, current.tokenSource?.inputStream),\n      Token.DEFAULT_CHANNEL,\n      -1,\n      -1,\n      current.line,\n      current.charPositionInLine,\n    );\n  }\n\n  IntervalSet getExpectedTokens(Parser recognizer) {\n    return recognizer.expectedTokens;\n  }\n\n  /// How should a token be displayed in an error message? The default\n  ///  is to display just the text, but during development you might\n  ///  want to have a lot of information spit out.  Override in that case\n  ///  to use t.toString() (which, for CommonToken, dumps everything about\n  ///  the token). This is better than forcing you to override a method in\n  ///  your token objects because you don't have to go modify your lexer\n  ///  so that it creates a new Java type.\n  String getTokenErrorDisplay(Token? t) {\n    if (t == null) return '<no token>';\n    var s = getSymbolText(t);\n    if (s == null) {\n      if (getSymbolType(t) == Token.EOF) {\n        s = '<EOF>';\n      } else {\n        s = '<${getSymbolType(t)}>';\n      }\n    }\n    return escapeWSAndQuote(s);\n  }\n\n  String? getSymbolText(Token symbol) {\n    return symbol.text;\n  }\n\n  int getSymbolType(Token symbol) {\n    return symbol.type;\n  }\n\n  String escapeWSAndQuote(String s) {\n//\t\tif ( s==null ) return s;\n    s = s.replaceAll('\\n', r'\\n');\n    s = s.replaceAll('\\r', r'\\r');\n    s = s.replaceAll('\\t', r'\\t');\n    return \"'\" + s + \"'\";\n  }\n\n/*  Compute the error recovery set for the current rule.  During\n\t *  rule invocation, the parser pushes the set of tokens that can\n\t *  follow that rule reference on the stack; this amounts to\n\t *  computing FIRST of what follows the rule reference in the\n\t *  enclosing rule. See LinearApproximator.FIRST().\n\t *  This local follow set only includes tokens\n\t *  from within the rule; i.e., the FIRST computation done by\n\t *  ANTLR stops at the end of a rule.\n\t *\n\t *  EXAMPLE\n\t *\n\t *  When you find a \"no viable alt exception\", the input is not\n\t *  consistent with any of the alternatives for rule r.  The best\n\t *  thing to do is to consume tokens until you see something that\n\t *  can legally follow a call to r *or* any rule that called r.\n\t *  You don't want the exact set of viable next tokens because the\n\t *  input might just be missing a token--you might consume the\n\t *  rest of the input looking for one of the missing tokens.\n\t *\n\t *  Consider grammar:\n\t *\n\t *  a : '[' b ']'\n\t *    | '(' b ')'\n\t *    ;\n\t *  b : c '^' INT ;\n\t *  c : ID\n\t *    | INT\n\t *    ;\n\t *\n\t *  At each rule invocation, the set of tokens that could follow\n\t *  that rule is pushed on a stack.  Here are the various\n\t *  context-sensitive follow sets:\n\t *\n\t *  FOLLOW(b1_in_a) = FIRST(']') = ']'\n\t *  FOLLOW(b2_in_a) = FIRST(')') = ')'\n\t *  FOLLOW(c_in_b) = FIRST('^') = '^'\n\t *\n\t *  Upon erroneous input \"[]\", the call chain is\n\t *\n\t *  a -> b -> c\n\t *\n\t *  and, hence, the follow context stack is:\n\t *\n\t *  depth     follow set       start of rule execution\n\t *    0         <EOF>                    a (from main())\n\t *    1          ']'                     b\n\t *    2          '^'                     c\n\t *\n\t *  Notice that ')' is not included, because b would have to have\n\t *  been called from a different context in rule a for ')' to be\n\t *  included.\n\t *\n\t *  For error recovery, we cannot consider FOLLOW(c)\n\t *  (context-sensitive or otherwise).  We need the combined set of\n\t *  all context-sensitive FOLLOW sets--the set of all tokens that\n\t *  could follow any reference in the call chain.  We need to\n\t *  resync to one of those tokens.  Note that FOLLOW(c)='^' and if\n\t *  we resync'd to that token, we'd consume until EOF.  We need to\n\t *  sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.\n\t *  In this case, for input \"[]\", LA(1) is ']' and in the set, so we would\n\t *  not consume anything. After printing an error, rule c would\n\t *  return normally.  Rule b would not find the required '^' though.\n\t *  At this point, it gets a mismatched token error and throws an\n\t *  exception (since LA(1) is not in the viable following token\n\t *  set).  The rule exception handler tries to recover, but finds\n\t *  the same recovery set and doesn't consume anything.  Rule b\n\t *  exits normally returning to rule a.  Now it finds the ']' (and\n\t *  with the successful match exits errorRecovery mode).\n\t *\n\t *  So, you can see that the parser walks up the call chain looking\n\t *  for the token that was a member of the recovery set.\n\t *\n\t *  Errors are not generated in errorRecovery mode.\n\t *\n\t *  ANTLR's error recovery mechanism is based upon original ideas:\n\t *\n\t *  \"Algorithms + Data Structures = Programs\" by Niklaus Wirth\n\t *\n\t *  and\n\t *\n\t *  \"A note on error recovery in recursive descent parsers\":\n\t *  http://portal.acm.org/citation.cfm?id=947902.947905\n\t *\n\t *  Later, Josef Grosch had some good ideas:\n\t *\n\t *  \"Efficient and Comfortable Error Recovery in Recursive Descent\n\t *  Parsers\":\n\t *  ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip\n\t *\n\t *  Like Grosch I implement context-sensitive FOLLOW sets that are combined\n\t *  at run-time upon error to avoid overhead during parsing.\n\t */\n  IntervalSet getErrorRecoverySet(Parser recognizer) {\n    final atn = recognizer.interpreter!.atn;\n    RuleContext? ctx = recognizer.context;\n    final recoverSet = IntervalSet();\n    while (ctx != null && ctx.invokingState >= 0) {\n      // compute what follows who invoked us\n      final invokingState = atn.states[ctx.invokingState]!;\n      final rt = invokingState.transition(0) as RuleTransition;\n      final follow = atn.nextTokens(rt.followState);\n      recoverSet.addAll(follow);\n      ctx = ctx.parent;\n    }\n    recoverSet.remove(Token.EPSILON);\n    return recoverSet;\n  }\n\n  /// Consume tokens until one matches the given token set. */\n  void consumeUntil(Parser recognizer, IntervalSet set) {\n//\t\tlog(\"consumeUntil(\"+set.toString(recognizer.getTokenNames())+\")\", level: Level.SEVERE.value);\n    var ttype = recognizer.inputStream.LA(1)!;\n    while (ttype != Token.EOF && !set.contains(ttype)) {\n      //System.out.println(\"consume during recover LA(1)=\"+getTokenNames()[input.LA(1)]);\n//\t\t\trecognizer.inputStream.consume();\n      recognizer.consume();\n      ttype = recognizer.inputStream.LA(1)!;\n    }\n  }\n}\n\n/// This implementation of [ANTLRErrorStrategy] responds to syntax errors\n/// by immediately canceling the parse operation with a\n/// [ParseCancellationException]. The implementation ensures that the\n/// {@link ParserRuleContext#exception} field is set for all parse tree nodes\n/// that were not completed prior to encountering the error.\n///\n/// <p>\n/// This error strategy is useful in the following scenarios.</p>\n///\n/// <ul>\n/// <li><strong>Two-stage parsing:</strong> This error strategy allows the first\n/// stage of two-stage parsing to immediately terminate if an error is\n/// encountered, and immediately fall back to the second stage. In addition to\n/// avoiding wasted work by attempting to recover from errors here, the empty\n/// implementation of {@link BailErrorStrategy#sync} improves the performance of\n/// the first stage.</li>\n/// <li><strong>Silent validation:</strong> When syntax errors are not being\n/// reported or logged, and the parse result is simply ignored if errors occur,\n/// the [BailErrorStrategy] avoids wasting work on recovering from errors\n/// when the result will be ignored either way.</li>\n/// </ul>\n///\n/// <p>\n/// {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>\n///\n/// @see Parser#setErrorHandler(ANTLRErrorStrategy)\nclass BailErrorStrategy extends DefaultErrorStrategy {\n  /// Instead of recovering from exception [e], re-throw it wrapped\n  ///  in a [ParseCancellationException] so it is not caught by the\n  ///  rule function catches.  Use {@link Exception#getCause()} to get the\n  ///  original [RecognitionException].\n\n  @override\n  void recover(Parser recognizer, RecognitionException e) {\n    for (var context = recognizer.context;\n        context != null;\n        context = context.parent) {\n      context.exception = e;\n    }\n\n    throw ParseCancellationException(e.message);\n  }\n\n  /// Make sure we don't attempt to recover inline; if the parser\n  ///  successfully recovers, it won't throw an exception.\n\n  @override\n  Token recoverInline(Parser recognizer) {\n    final e = InputMismatchException(recognizer);\n    for (var context = recognizer.context;\n        context != null;\n        context = context.parent) {\n      context.exception = e;\n    }\n\n    throw ParseCancellationException(e.message);\n  }\n\n  /// Make sure we don't attempt to recover from problems in subrules. */\n\n  @override\n  void sync(Parser recognizer) {}\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/error/src/errors.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../atn/atn.dart';\nimport '../../input_stream.dart';\nimport '../../interval_set.dart';\nimport '../../lexer.dart';\nimport '../../parser.dart';\nimport '../../parser_rule_context.dart';\nimport '../../recognizer.dart';\nimport '../../rule_context.dart';\nimport '../../token.dart';\nimport '../../token_stream.dart';\nimport '../../util/utils.dart';\n\n/// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n///  3 kinds of errors: prediction errors, failed predicate errors, and\n///  mismatched input errors. In each case, the parser knows where it is\n///  in the input, where it is in the ATN, the rule invocation stack,\n///  and what kind of problem occurred.\nclass RecognitionException<StreamType extends IntStream> extends StateError {\n  /// Gets the [Recognizer] where this exception occurred.\n  ///\n  /// <p>If the recognizer is not available, this method returns null.</p>\n  ///\n  /// @return The recognizer where this exception occurred, or null if\n  /// the recognizer is not available.\n  final Recognizer? recognizer;\n\n  /// Gets the [RuleContext] at the time this exception was thrown.\n  ///\n  /// <p>If the context is not available, this method returns null.</p>\n  ///\n  /// @return The [RuleContext] at the time this exception was thrown.\n  /// If the context is not available, this method returns null.\n  final RuleContext? ctx;\n\n  /// Gets the input stream which is the symbol source for the recognizer where\n  /// this exception was thrown.\n  ///\n  /// <p>If the input stream is not available, this method returns null.</p>\n  ///\n  /// @return The input stream which is the symbol source for the recognizer\n  /// where this exception was thrown, or null if the stream is not\n  /// available.\n  final StreamType inputStream;\n\n  /// The current [Token] when an error occurred. Since not all streams\n  /// support accessing symbols by index, we have to track the [Token]\n  /// instance itself.\n  late Token offendingToken;\n\n  /// Get the ATN state number the parser was in at the time the error\n  /// occurred. For [NoViableAltException] and\n  /// [LexerNoViableAltException] exceptions, this is the\n  /// [DecisionState] number. For others, it is the state whose outgoing\n  /// edge we couldn't match.\n  ///\n  /// <p>If the state number is not known, this method returns -1.</p>\n  int offendingState = -1;\n\n  RecognitionException(\n    this.recognizer,\n    this.inputStream,\n    this.ctx, [\n    String message = '',\n  ]) : super(message) {\n    if (recognizer != null) offendingState = recognizer!.state;\n  }\n\n  /// Gets the set of input symbols which could potentially follow the\n  /// previously matched symbol at the time this exception was thrown.\n  ///\n  /// <p>If the set of expected tokens is not known and could not be computed,\n  /// this method returns null.</p>\n  ///\n  /// @return The set of token types that could potentially follow the current\n  /// state in the ATN, or null if the information is not available.\n  IntervalSet? get expectedTokens {\n    if (recognizer != null) {\n      return recognizer!.getATN().getExpectedTokens(offendingState, ctx);\n    }\n    return null;\n  }\n}\n\nclass LexerNoViableAltException extends RecognitionException<CharStream> {\n  /// Matching attempted at what input index? */\n  final int startIndex;\n\n  /// Which configurations did we try at input.index() that couldn't match input.LA(1)? */\n  final ATNConfigSet deadEndConfigs;\n\n  LexerNoViableAltException(\n    Lexer? lexer,\n    CharStream input,\n    this.startIndex,\n    this.deadEndConfigs,\n  ) : super(lexer, input, null);\n\n  @override\n  String toString() {\n    var symbol = '';\n    if (startIndex >= 0 && startIndex < inputStream.size) {\n      symbol = inputStream.getText(Interval.of(startIndex, startIndex));\n      symbol = escapeWhitespace(symbol);\n    }\n\n    return \"$LexerNoViableAltException('$symbol')\";\n  }\n}\n\n/// Indicates that the parser could not decide which of two or more paths\n///  to take based upon the remaining input. It tracks the starting token\n///  of the offending input and also knows where the parser was\n///  in the various paths when the error. Reported by reportNoViableAlternative()\nclass NoViableAltException extends RecognitionException {\n  /// Which configurations did we try at input.index() that couldn't match input.LT(1)? */\n\n  final ATNConfigSet? deadEndConfigs;\n\n  /// The token object at the start index; the input stream might\n  /// \tnot be buffering tokens so get a reference to it. (At the\n  ///  time the error occurred, of course the stream needs to keep a\n  ///  buffer all of the tokens but later we might not have access to those.)\n\n  final Token startToken;\n\n//   NoViableAltException(Parser recognizer) { // LL(1) error\n//    this(recognizer,\n//        recognizer.inputStream,\n//        recognizer.getCurrentToken(),\n//        recognizer.getCurrentToken(),\n//        null,\n//        recognizer._ctx);\n//  }\n\n  NoViableAltException._(\n    Parser recognizer,\n    TokenStream input,\n    this.startToken,\n    Token offendingToken,\n    this.deadEndConfigs,\n    ParserRuleContext? ctx,\n  ) : super(recognizer, input, ctx) {\n    this.offendingToken = offendingToken;\n  }\n\n  NoViableAltException(\n    Parser recognizer, [\n    TokenStream? input,\n    Token? startToken,\n    Token? offendingToken,\n    ATNConfigSet? deadEndConfigs,\n    ParserRuleContext? ctx,\n  ]) : this._(\n          recognizer,\n          input ?? recognizer.inputStream,\n          startToken ?? recognizer.currentToken,\n          offendingToken ?? recognizer.currentToken,\n          deadEndConfigs,\n          ctx ?? recognizer.context,\n        );\n}\n\n/// This signifies any kind of mismatched input exceptions such as\n///  when the current input does not match the expected token.\nclass InputMismatchException extends RecognitionException {\n  InputMismatchException(\n    Parser recognizer, [\n    int state = -1,\n    ParserRuleContext? ctx,\n  ]) : super(recognizer, recognizer.inputStream, ctx ?? recognizer.context) {\n    if (state != -1 && ctx != null) {\n      offendingState = state;\n    }\n    offendingToken = recognizer.currentToken;\n  }\n}\n\n/// A semantic predicate failed during validation.  Validation of predicates\n///  occurs when normally parsing the alternative just like matching a token.\n///  Disambiguating predicate evaluation occurs when we test a predicate during\n///  prediction.\nclass FailedPredicateException extends RecognitionException {\n  int? ruleIndex;\n  int? predIndex;\n  final String? predicate;\n\n  FailedPredicateException(\n    Parser recognizer, [\n    this.predicate,\n    String? message,\n  ]) : super(\n          recognizer,\n          recognizer.inputStream,\n          recognizer.context,\n          formatMessage(predicate, message),\n        ) {\n    final s = recognizer.interpreter!.atn.states[recognizer.state]!;\n\n    final trans = s.transition(0) as AbstractPredicateTransition;\n    if (trans is PredicateTransition) {\n      ruleIndex = trans.ruleIndex;\n      predIndex = trans.predIndex;\n    }\n    offendingToken = recognizer.currentToken;\n  }\n\n  static String formatMessage(String? predicate, String? message) {\n    if (message != null) {\n      return message;\n    }\n\n    return 'failed predicate: {$predicate}?';\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/input_stream.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:async';\nimport 'dart:convert';\nimport 'dart:math';\n\nimport 'interval_set.dart';\nimport 'token.dart';\n\nimport 'util/platform_stub.dart' if (dart.library.io) 'util/platform_io.dart';\n\n/// A simple stream of symbols whose values are represented as integers. This\n/// interface provides <em>marked ranges</em> with support for a minimum level\n/// of buffering necessary to implement arbitrary lookahead during prediction.\n/// For more information on marked ranges, see {@link #mark}.\n///\n/// <p><strong>Initializing Methods:</strong> Some methods in this interface have\n/// unspecified behavior if no call to an initializing method has occurred after\n/// the stream was constructed. The following is a list of initializing methods:</p>\n///\n/// <ul>\n///   <li>{@link #LA}</li>\n///   <li>{@link #consume}</li>\n///   <li>{@link #size}</li>\n/// </ul>\nabstract class IntStream {\n  /// The value returned by {@link #LA LA()} when the end of the stream is\n  /// reached.\n  static const int EOF = -1;\n\n  /// The value returned by {@link #getSourceName} when the actual name of the\n  /// underlying source is not known.\n  static const UNKNOWN_SOURCE_NAME = '<unknown>';\n\n  /// Consumes the current symbol in the stream. This method has the following\n  /// effects:\n  ///\n  /// <ul>\n  ///   <li><strong>Forward movement:</strong> The value of {@link #index index()}\n  ///\t\tbefore calling this method is less than the value of {@code index()}\n  ///\t\tafter calling this method.</li>\n  ///   <li><strong>Ordered lookahead:</strong> The value of {@code LA(1)} before\n  ///\t\tcalling this method becomes the value of {@code LA(-1)} after calling\n  ///\t\tthis method.</li>\n  /// </ul>\n  ///\n  /// Note that calling this method does not guarantee that {@code index()} is\n  /// incremented by exactly 1, as that would preclude the ability to implement\n  /// filtering streams (e.g. [CommonTokenStream] which distinguishes\n  /// between \"on-channel\" and \"off-channel\" tokens).\n  ///\n  /// @throws IllegalStateException if an attempt is made to consume the\n  /// end of the stream (i.e. if {@code LA(1)==}{@link #EOF EOF} before calling\n  /// [consume]).\n  void consume();\n\n  /// Gets the value of the symbol at offset [i] from the current\n  /// position. When {@code i==1}, this method returns the value of the current\n  /// symbol in the stream (which is the next symbol to be consumed). When\n  /// {@code i==-1}, this method returns the value of the previously read\n  /// symbol in the stream. It is not valid to call this method with\n  /// {@code i==0}, but the specific behavior is unspecified because this\n  /// method is frequently called from performance-critical code.\n  ///\n  /// <p>This method is guaranteed to succeed if any of the following are true:</p>\n  ///\n  /// <ul>\n  ///   <li>{@code i>0}</li>\n  ///   <li>{@code i==-1} and {@link #index index()} returns a value greater\n  ///     than the value of {@code index()} after the stream was constructed\n  ///     and {@code LA(1)} was called in that order. Specifying the current\n  ///     {@code index()} relative to the index after the stream was created\n  ///     allows for filtering implementations that do not return every symbol\n  ///     from the underlying source. Specifying the call to {@code LA(1)}\n  ///     allows for lazily initialized streams.</li>\n  ///   <li>{@code LA(i)} refers to a symbol consumed within a marked region\n  ///     that has not yet been released.</li>\n  /// </ul>\n  ///\n  /// <p>If [i] represents a position at or beyond the end of the stream,\n  /// this method returns {@link #EOF}.</p>\n  ///\n  /// <p>The return value is unspecified if {@code i<0} and fewer than {@code -i}\n  /// calls to {@link #consume consume()} have occurred from the beginning of\n  /// the stream before calling this method.</p>\n  ///\n  /// @throws UnsupportedOperationException if the stream does not support\n  /// retrieving the value of the specified symbol\n  int? LA(int i);\n\n  /// A mark provides a guarantee that {@link #seek seek()} operations will be\n  /// valid over a \"marked range\" extending from the index where {@code mark()}\n  /// was called to the current {@link #index index()}. This allows the use of\n  /// streaming input sources by specifying the minimum buffering requirements\n  /// to support arbitrary lookahead during prediction.\n  ///\n  /// <p>The returned mark is an opaque handle (type [int]) which is passed\n  /// to {@link #release release()} when the guarantees provided by the marked\n  /// range are no longer necessary. When calls to\n  /// {@code mark()}/{@code release()} are nested, the marks must be released\n  /// in reverse order of which they were obtained. Since marked regions are\n  /// used during performance-critical sections of prediction, the specific\n  /// behavior of invalid usage is unspecified (i.e. a mark is not released, or\n  /// a mark is released twice, or marks are not released in reverse order from\n  /// which they were created).</p>\n  ///\n  /// <p>The behavior of this method is unspecified if no call to an\n  /// {@link IntStream initializing method} has occurred after this stream was\n  /// constructed.</p>\n  ///\n  /// <p>This method does not change the current position in the input stream.</p>\n  ///\n  /// <p>The following example shows the use of {@link #mark mark()},\n  /// {@link #release release(mark)}, {@link #index index()}, and\n  /// {@link #seek seek(index)} as part of an operation to safely work within a\n  /// marked region, then restore the stream position to its original value and\n  /// release the mark.</p>\n  /// <pre>\n  /// IntStream stream = ...;\n  /// int index = -1;\n  /// int mark = stream.mark();\n  /// try {\n  ///   index = stream.index();\n  ///   // perform work here...\n  /// } finally {\n  ///   if (index != -1) {\n  ///     stream.seek(index);\n  ///   }\n  ///   stream.release(mark);\n  /// }\n  /// </pre>\n  ///\n  /// @return An opaque marker which should be passed to\n  /// {@link #release release()} when the marked range is no longer required.\n  int mark();\n\n  /// This method releases a marked range created by a call to\n  /// {@link #mark mark()}. Calls to {@code release()} must appear in the\n  /// reverse order of the corresponding calls to {@code mark()}. If a mark is\n  /// released twice, or if marks are not released in reverse order of the\n  /// corresponding calls to {@code mark()}, the behavior is unspecified.\n  ///\n  /// <p>For more information and an example, see {@link #mark}.</p>\n  ///\n  /// @param marker A marker returned by a call to {@code mark()}.\n  /// @see #mark\n  void release(int marker);\n\n  /// Return the index into the stream of the input symbol referred to by\n  /// {@code LA(1)}.\n  ///\n  /// <p>The behavior of this method is unspecified if no call to an\n  /// {@link IntStream initializing method} has occurred after this stream was\n  /// constructed.</p>\n  int get index;\n\n  /// Set the input cursor to the position indicated by [index]. If the\n  /// specified index lies past the end of the stream, the operation behaves as\n  /// though [index] was the index of the EOF symbol. After this method\n  /// returns without throwing an exception, then at least one of the following\n  /// will be true.\n  ///\n  /// <ul>\n  ///   <li>{@link #index index()} will return the index of the first symbol\n  ///     appearing at or after the specified [index]. Specifically,\n  ///     implementations which filter their sources should automatically\n  ///     adjust [index] forward the minimum amount required for the\n  ///     operation to target a non-ignored symbol.</li>\n  ///   <li>{@code LA(1)} returns {@link #EOF}</li>\n  /// </ul>\n  ///\n  /// This operation is guaranteed to not throw an exception if [index]\n  /// lies within a marked region. For more information on marked regions, see\n  /// {@link #mark}. The behavior of this method is unspecified if no call to\n  /// an {@link IntStream initializing method} has occurred after this stream\n  /// was constructed.\n  ///\n  /// @param index The absolute index to seek to.\n  ///\n  /// @throws IllegalArgumentException if [index] is less than 0\n  /// @throws UnsupportedOperationException if the stream does not support\n  /// seeking to the specified index\n  void seek(int index);\n\n  /// Returns the total number of symbols in the stream, including a single EOF\n  /// symbol.\n  ///\n  /// @throws UnsupportedOperationException if the size of the stream is\n  /// unknown.\n  int get size;\n\n  /// Gets the name of the underlying symbol source. This method returns a\n  /// non-null, non-empty string. If such a name is not known, this method\n  /// returns {@link #UNKNOWN_SOURCE_NAME}.\n\n  String get sourceName;\n}\n\n/// A source of characters for an ANTLR lexer. */\nabstract class CharStream extends IntStream {\n  /// This method returns the text for a range of characters within this input\n  /// stream. This method is guaranteed to not throw an exception if the\n  /// specified [interval] lies entirely within a marked range. For more\n  /// information about marked ranges, see {@link IntStream#mark}.\n  ///\n  /// @param interval an interval within the stream\n  /// @return the text of the specified interval\n  ///\n  /// @throws NullPointerException if [interval] is null\n  /// @throws IllegalArgumentException if {@code interval.a < 0}, or if\n  /// {@code interval.b < interval.a - 1}, or if {@code interval.b} lies at or\n  /// past the end of the stream\n  /// @throws UnsupportedOperationException if the stream does not support\n  /// getting the text of the specified interval\n  String getText(Interval interval);\n}\n\n// Vacuum all input from a string and then treat it like a buffer.\nclass InputStream extends CharStream {\n  final name = '<empty>';\n  late List<int> data;\n  int _index = 0;\n  bool decodeToUnicodeCodePoints = false;\n\n  InputStream(List<int> data) {\n    this.data = data;\n  }\n\n  InputStream.fromString(String data) {\n    this.data = data.runes.toList(growable: false);\n  }\n\n  static Future<InputStream> fromStringStream(Stream<String> stream) async {\n    final data = StringBuffer();\n    await stream.listen((buf) {\n      data.write(buf);\n    }).asFuture();\n    return InputStream.fromString(data.toString());\n  }\n\n  static Future<InputStream> fromStream(Stream<List<int>> stream,\n      {Encoding encoding = utf8}) {\n    final data = stream.transform(encoding.decoder);\n    return fromStringStream(data);\n  }\n\n  static Future<InputStream> fromPath(String path, {Encoding encoding = utf8}) {\n    return fromStream(readStream(path), encoding: encoding);\n  }\n\n  @override\n  int get index {\n    return _index;\n  }\n\n  @override\n  int get size {\n    return data.length;\n  }\n\n  /// Reset the stream so that it's in the same state it was\n  /// when the object was created *except* the data array is not\n  /// touched.\n  void reset() {\n    _index = 0;\n  }\n\n  @override\n  void consume() {\n    if (_index >= size) {\n      // assert this.LA(1) == Token.EOF\n      throw ('cannot consume EOF');\n    }\n    _index += 1;\n  }\n\n  @override\n  int LA(int offset) {\n    if (offset == 0) {\n      return 0; // undefined\n    }\n    if (offset < 0) {\n      offset += 1; // e.g., translate LA(-1) to use offset=0\n    }\n    final pos = _index + offset - 1;\n    if (pos < 0 || pos >= size) {\n      // invalid\n      return Token.EOF;\n    }\n    return data[pos];\n  }\n\n  /// mark/release do nothing; we have entire buffer\n  @override\n  int mark() {\n    return -1;\n  }\n\n  @override\n  void release(int marker) {}\n\n  /// consume() ahead until p==_index; can't just set p=_index as we must\n  /// update line and column. If we seek backwards, just set p\n  @override\n  void seek(int _index) {\n    if (_index <= this._index) {\n      this._index = _index; // just jump; don't update stream state (line,\n      // ...)\n      return;\n    }\n    // seek forward\n    this._index = min(_index, size);\n  }\n\n  @override\n  String getText(Interval interval) {\n    final startIdx = min(interval.a, size);\n    final len = min(interval.b - interval.a + 1, size - startIdx);\n    return String.fromCharCodes(data, startIdx, startIdx + len);\n  }\n\n  @override\n  String toString() {\n    return String.fromCharCodes(data);\n  }\n\n  @override\n  String get sourceName {\n    // TODO: implement getSourceName\n    return IntStream.UNKNOWN_SOURCE_NAME;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/interval_set.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:math';\n\nimport 'package:collection/collection.dart';\n\nimport 'lexer.dart';\nimport 'token.dart';\nimport 'util/murmur_hash.dart';\nimport 'vocabulary.dart';\n\n/// An immutable inclusive interval a..b */\nclass Interval {\n  static final int INTERVAL_POOL_MAX_VALUE = 1000;\n\n  static final Interval INVALID = Interval(-1, -2);\n\n  static List<Interval?> cache =\n      List<Interval?>.filled(INTERVAL_POOL_MAX_VALUE + 1, null);\n\n  int a;\n  int b;\n\n  static int creates = 0;\n  static int misses = 0;\n  static int hits = 0;\n  static int outOfRange = 0;\n\n  Interval(this.a, this.b);\n\n  /// Interval objects are used readonly so share all with the\n  ///  same single value a==b up to some max size.  Use an array as a perfect hash.\n  ///  Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new\n  ///  Interval object with a..a in it.  On Java.g4, 218623 IntervalSets\n  ///  have a..a (set with 1 element).\n  static Interval of(int a, int b) {\n    // cache just a..a\n    if (a != b || a < 0 || a > INTERVAL_POOL_MAX_VALUE) {\n      return Interval(a, b);\n    }\n    if (cache[a] == null) {\n      cache[a] = Interval(a, a);\n    }\n    return cache[a]!;\n  }\n\n  /// return number of elements between a and b inclusively. x..x is length 1.\n  ///  if b &lt; a, then length is 0.  9..10 has length 2.\n  int get length {\n    if (b < a) return 0;\n    return b - a + 1;\n  }\n\n  @override\n  bool operator ==(Object other) {\n    if (other is! Interval) {\n      return false;\n    }\n    return a == other.a && b == other.b;\n  }\n\n  @override\n  int get hashCode {\n    var hash = 23;\n    hash = hash * 31 + a;\n    hash = hash * 31 + b;\n    return hash;\n  }\n\n  /// Does this start completely before other? Disjoint */\n  bool startsBeforeDisjoint(Interval other) {\n    return a < other.a && b < other.a;\n  }\n\n  /// Does this start at or before other? Nondisjoint */\n  bool startsBeforeNonDisjoint(Interval other) {\n    return a <= other.a && b >= other.a;\n  }\n\n  /// Does this.a start after other.b? May or may not be disjoint */\n  bool startsAfter(Interval other) {\n    return a > other.a;\n  }\n\n  /// Does this start completely after other? Disjoint */\n  bool startsAfterDisjoint(Interval other) {\n    return a > other.b;\n  }\n\n  /// Does this start after other? NonDisjoint */\n  bool startsAfterNonDisjoint(Interval other) {\n    return a > other.a && a <= other.b; // this.b>=other.b implied\n  }\n\n  /// Are both ranges disjoint? I.e., no overlap? */\n  bool disjoint(Interval other) {\n    return startsBeforeDisjoint(other) || startsAfterDisjoint(other);\n  }\n\n  /// Are two intervals adjacent such as 0..41 and 42..42? */\n  bool adjacent(Interval other) {\n    return a == other.b + 1 || b == other.a - 1;\n  }\n\n  bool properlyContains(Interval other) {\n    return other.a >= a && other.b <= b;\n  }\n\n  /// Return the interval computed from combining this and other */\n  Interval union(Interval other) {\n    return Interval.of(min(a, other.a), max(b, other.b));\n  }\n\n  /// Return the interval in common between this and o */\n  Interval intersection(Interval other) {\n    return Interval.of(max(a, other.a), min(b, other.b));\n  }\n\n  /// Return the interval with elements from this not in other;\n  ///  other must not be totally enclosed (properly contained)\n  ///  within this, which would result in two disjoint intervals\n  ///  instead of the single one returned by this method.\n  Interval? differenceNotProperlyContained(Interval other) {\n    Interval? diff;\n    // other.a to left of this.a (or same)\n    if (other.startsBeforeNonDisjoint(this)) {\n      diff = Interval.of(max(a, other.b + 1), b);\n    }\n\n    // other.a to right of this.a\n    else if (other.startsAfterNonDisjoint(this)) {\n      diff = Interval.of(a, other.a - 1);\n    }\n    return diff;\n  }\n\n  @override\n  String toString() {\n    return '$a..$b';\n  }\n}\n\n/// This class implements the [IntervalSet] backed by a sorted array of\n/// non-overlapping intervals. It is particularly efficient for representing\n/// large collections of numbers, where the majority of elements appear as part\n/// of a sequential range of numbers that are all part of the set. For example,\n/// the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }.\n///\n/// <p>\n/// This class is able to represent sets containing any combination of values in\n/// the range {@link int#MIN_VALUE} to {@link int#MAX_VALUE}\n/// (inclusive).</p>\nclass IntervalSet {\n  static final IntervalSet COMPLETE_CHAR_SET =\n      IntervalSet.ofRange(Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE)\n        ..setReadonly(true);\n\n  static final IntervalSet EMPTY_SET = IntervalSet([])..setReadonly(true);\n\n  /// The list of sorted, disjoint intervals. */\n  List<Interval> intervals = [];\n\n  bool readonly = false;\n\n  IntervalSet([List<Interval>? intervals]) {\n    this.intervals = intervals ?? [];\n  }\n\n  IntervalSet.ofSet(IntervalSet set) {\n    addAll(set);\n  }\n\n// TODO\n// IntervalSet(int... els) {\n//if ( els==null ) {\n//intervals = new ArrayList<Interval>(2); // most sets are 1 or 2 elements\n//}\n//else {\n//intervals = new ArrayList<Interval>(els.length);\n//for (int e : els) add(e);\n//}\n//}\n\n  /// Create a set with a single element, el. */\n\n  IntervalSet.ofOne(int a) {\n    addOne(a);\n  }\n\n  /// Create a set with all ints within range [a..b] (inclusive) */\n  static IntervalSet ofRange(int a, int b) {\n    final s = IntervalSet();\n    s.addRange(a, b);\n    return s;\n  }\n\n  void clear() {\n    if (readonly) throw StateError(\"can't alter readonly IntervalSet\");\n    intervals.clear();\n  }\n\n  /// Add a single element to the set.  An isolated element is stored\n  ///  as a range el..el.\n\n  void addOne(int el) {\n    if (readonly) throw StateError(\"can't alter readonly IntervalSet\");\n    addRange(el, el);\n  }\n\n  /// Add interval; i.e., add all integers from a to b to set.\n  ///  If b&lt;a, do nothing.\n  ///  Keep list in sorted order (by left range value).\n  ///  If overlap, combine ranges.  For example,\n  ///  If this is {1..5, 10..20}, adding 6..7 yields\n  ///  {1..5, 6..7, 10..20}.  Adding 4..8 yields {1..8, 10..20}.\n  void addRange(int a, int b) {\n    add(Interval.of(a, b));\n  }\n\n  // copy on write so we can cache a..a intervals and sets of that\n  void add(Interval addition) {\n    if (readonly) throw StateError(\"can't alter readonly IntervalSet\");\n    //System.out.println(\"add \"+addition+\" to \"+intervals.toString());\n    if (addition.b < addition.a) {\n      return;\n    }\n    for (var i = 0; i < intervals.length; i++) {\n      final r = intervals[i];\n      if (addition == r) {\n        return;\n      }\n      if (addition.adjacent(r) || !addition.disjoint(r)) {\n        // next to each other, make a single larger interval\n        final bigger = addition.union(r);\n        intervals[i] = bigger;\n\n        // make sure we didn't just create an interval that\n        // should be merged with next interval in list\n        for (i++; i < intervals.length; i++) {\n          final next = intervals[i];\n          if (!bigger.adjacent(next) && bigger.disjoint(next)) {\n            break;\n          }\n\n          // if we bump up against or overlap next, merge\n          intervals.removeAt(i); // remove this one\n          intervals[i - 1] =\n              bigger.union(next); // set previous to 3 merged ones\n        }\n        return;\n      }\n      if (addition.startsBeforeDisjoint(r)) {\n        // insert before r\n        intervals.insert(i, addition);\n        return;\n      }\n      // if disjoint and after r, a future iteration will handle it\n\n    }\n    // ok, must be after last interval (and disjoint from last interval)\n    // just add it\n    intervals.add(addition);\n  }\n\n  /// combine all sets in the array returned the or'd value */\n  static IntervalSet or(List<IntervalSet> sets) {\n    final r = IntervalSet();\n    for (final s in sets) {\n      r.addAll(s);\n    }\n    return r;\n  }\n\n  IntervalSet operator |(IntervalSet a) {\n    final o = IntervalSet();\n    o.addAll(this);\n    o.addAll(a);\n    return o;\n  }\n\n  IntervalSet addAll(IntervalSet? set) {\n    if (set == null) {\n      return this;\n    }\n\n    final other = set;\n    // walk set and add each interval\n    final n = other.intervals.length;\n    for (var i = 0; i < n; i++) {\n      final I = other.intervals[i];\n      addRange(I.a, I.b);\n    }\n\n    return this;\n  }\n\n  IntervalSet? complementRange(int minElement, int maxElement) {\n    return complement(IntervalSet.ofRange(minElement, maxElement));\n  }\n\n  /// {@inheritDoc} */\n  IntervalSet? complement(IntervalSet? vocabulary) {\n    if (vocabulary == null || vocabulary.isNil) {\n      return null; // nothing in common with null set\n    }\n    return vocabulary - this;\n  }\n\n  IntervalSet operator -(IntervalSet a) {\n    if (a.isNil) {\n      return IntervalSet.ofSet(this);\n    }\n    return subtract(this, a);\n  }\n\n  /// Compute the set difference between two interval sets. The specific\n  /// operation is {@code left - right}. If either of the input sets is\n  /// null, it is treated as though it was an empty set.\n  static IntervalSet subtract(IntervalSet left, IntervalSet right) {\n    if (left.isNil) {\n      return IntervalSet();\n    }\n\n    final result = IntervalSet.ofSet(left);\n    if (right.isNil) {\n      // right set has no elements; just return the copy of the current set\n      return result;\n    }\n\n    var resultI = 0;\n    var rightI = 0;\n    while (\n        resultI < result.intervals.length && rightI < right.intervals.length) {\n      final resultInterval = result.intervals[resultI];\n      final rightInterval = right.intervals[rightI];\n\n// operation: (resultInterval - rightInterval) and update indexes\n\n      if (rightInterval.b < resultInterval.a) {\n        rightI++;\n        continue;\n      }\n\n      if (rightInterval.a > resultInterval.b) {\n        resultI++;\n        continue;\n      }\n\n      Interval? beforeCurrent;\n      Interval? afterCurrent;\n      if (rightInterval.a > resultInterval.a) {\n        beforeCurrent = Interval(resultInterval.a, rightInterval.a - 1);\n      }\n\n      if (rightInterval.b < resultInterval.b) {\n        afterCurrent = Interval(rightInterval.b + 1, resultInterval.b);\n      }\n\n      if (beforeCurrent != null) {\n        if (afterCurrent != null) {\n// split the current interval into two\n          result.intervals[resultI] = beforeCurrent;\n          result.intervals.insert(resultI + 1, afterCurrent);\n          resultI++;\n          rightI++;\n          continue;\n        } else {\n// replace the current interval\n          result.intervals[resultI] = beforeCurrent;\n          resultI++;\n          continue;\n        }\n      } else {\n        if (afterCurrent != null) {\n// replace the current interval\n          result.intervals[resultI] = afterCurrent;\n          rightI++;\n          continue;\n        } else {\n// remove the current interval (thus no need to increment resultI)\n          result.intervals.removeAt(resultI);\n          continue;\n        }\n      }\n    }\n\n// If rightI reached right.intervals.length, no more intervals to subtract from result.\n// If resultI reached result.intervals.length, we would be subtracting from an empty set.\n// Either way, we are done.\n    return result;\n  }\n\n  /// {@inheritDoc} */\n  IntervalSet operator +(IntervalSet other) {\n    final myIntervals = intervals;\n    final theirIntervals = (other).intervals;\n    IntervalSet? intersection;\n    final mySize = myIntervals.length;\n    final theirSize = theirIntervals.length;\n    var i = 0;\n    var j = 0;\n// iterate down both interval lists looking for nondisjoint intervals\n    while (i < mySize && j < theirSize) {\n      final mine = myIntervals[i];\n      final theirs = theirIntervals[j];\n//System.out.println(\"mine=\"+mine+\" and theirs=\"+theirs);\n      if (mine.startsBeforeDisjoint(theirs)) {\n// move this iterator looking for interval that might overlap\n        i++;\n      } else if (theirs.startsBeforeDisjoint(mine)) {\n// move other iterator looking for interval that might overlap\n        j++;\n      } else if (mine.properlyContains(theirs)) {\n// overlap, add intersection, get next theirs\n        intersection ??= IntervalSet();\n        intersection.add(mine.intersection(theirs));\n        j++;\n      } else if (theirs.properlyContains(mine)) {\n// overlap, add intersection, get next mine\n        intersection ??= IntervalSet();\n        intersection.add(mine.intersection(theirs));\n        i++;\n      } else if (!mine.disjoint(theirs)) {\n// overlap, add intersection\n        intersection ??= IntervalSet();\n        intersection.add(mine.intersection(theirs));\n// Move the iterator of lower range [a..b], but not\n// the upper range as it may contain elements that will collide\n// with the next iterator. So, if mine=[0..115] and\n// theirs=[115..200], then intersection is 115 and move mine\n// but not theirs as theirs may collide with the next range\n// in thisIter.\n// move both iterators to next ranges\n        if (mine.startsAfterNonDisjoint(theirs)) {\n          j++;\n        } else if (theirs.startsAfterNonDisjoint(mine)) {\n          i++;\n        }\n      }\n    }\n    if (intersection == null) {\n      return IntervalSet();\n    }\n    return intersection;\n  }\n\n  /// {@inheritDoc} */\n\n  bool contains(int el) {\n    final n = intervals.length;\n    var l = 0;\n    var r = n - 1;\n// Binary search for the element in the (sorted,\n// disjoint) array of intervals.\n    while (l <= r) {\n      final m = ((l + r) / 2).floor();\n      final I = intervals[m];\n      final a = I.a;\n      final b = I.b;\n      if (b < el) {\n        l = m + 1;\n      } else if (a > el) {\n        r = m - 1;\n      } else {\n        // el >= a && el <= b\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /// {@inheritDoc} */\n\n  bool get isNil {\n    return intervals.isEmpty;\n  }\n\n  /// Returns the maximum value contained in the set if not isNil().\n  ///\n  /// @return the maximum value contained in the set.\n  /// @throws RuntimeException if set is empty\n  int get maxElement {\n    if (isNil) {\n      throw StateError('set is empty');\n    }\n    return intervals.last.b;\n  }\n\n  /// Returns the minimum value contained in the set if not isNil().\n  ///\n  /// @return the minimum value contained in the set.\n  /// @throws RuntimeException if set is empty\n  int get minElement {\n    if (isNil) {\n      throw StateError('set is empty');\n    }\n\n    return intervals.first.a;\n  }\n\n  @override\n  int get hashCode {\n    var hash = MurmurHash.initialize();\n    for (final I in intervals) {\n      hash = MurmurHash.update(hash, I.a);\n      hash = MurmurHash.update(hash, I.b);\n    }\n\n    hash = MurmurHash.finish(hash, intervals.length * 2);\n    return hash;\n  }\n\n  /// Are two IntervalSets equal?  Because all intervals are sorted\n  ///  and disjoint, equals is a simple linear walk over both lists\n  ///  to make sure they are the same.  Interval.equals() is used\n  ///  by the List.equals() method to check the ranges.\n\n  @override\n  bool operator ==(Object obj) {\n    if (obj is! IntervalSet) {\n      return false;\n    }\n    return ListEquality().equals(intervals, obj.intervals);\n  }\n\n  @override\n  String toString({bool elemAreChar = false, Vocabulary? vocabulary}) {\n    if (intervals.isEmpty) {\n      return '{}';\n    }\n\n    final elemStr = intervals.map((Interval I) {\n      final buf = StringBuffer();\n      final a = I.a;\n      final b = I.b;\n      if (a == b) {\n        if (vocabulary != null) {\n          buf.write(elementName(vocabulary, a));\n        } else {\n          if (a == Token.EOF) {\n            buf.write('<EOF>');\n          } else if (elemAreChar) {\n            buf.write(\"'\");\n            buf.writeCharCode(a);\n            buf.write(\"'\");\n          } else {\n            buf.write(a);\n          }\n        }\n      } else {\n        if (vocabulary != null) {\n          for (var i = a; i <= b; i++) {\n            if (i > a) buf.write(', ');\n            buf.write(elementName(vocabulary, i));\n          }\n        } else {\n          if (elemAreChar) {\n            buf.write(\"'\");\n            buf.writeCharCode(a);\n            buf.write(\"'..'\");\n            buf.writeCharCode(b);\n            buf.write(\"'\");\n          } else {\n            buf.write(a);\n            buf.write('..');\n            buf.write(b);\n          }\n        }\n      }\n      return buf;\n    }).join(', ');\n    if (length > 1) {\n      return '{$elemStr}';\n    }\n    return elemStr;\n  }\n\n  String elementName(Vocabulary vocabulary, int a) {\n    if (a == Token.EOF) {\n      return '<EOF>';\n    } else if (a == Token.EPSILON) {\n      return '<EPSILON>';\n    } else {\n      return vocabulary.getDisplayName(a);\n    }\n  }\n\n  int get length {\n    var n = 0;\n    final numIntervals = intervals.length;\n    if (numIntervals == 1) {\n      final firstInterval = intervals[0];\n      return firstInterval.b - firstInterval.a + 1;\n    }\n    for (var i = 0; i < numIntervals; i++) {\n      final I = intervals[i];\n      n += (I.b - I.a + 1);\n    }\n    return n;\n  }\n\n  List<int> toIntegerList() {\n    final values = <int>[];\n    final n = intervals.length;\n    for (var i = 0; i < n; i++) {\n      final I = intervals[i];\n      final a = I.a;\n      final b = I.b;\n      for (var v = a; v <= b; v++) {\n        values.add(v);\n      }\n    }\n    return values;\n  }\n\n  List<int> toList() {\n    final values = <int>[];\n    final n = intervals.length;\n    for (var i = 0; i < n; i++) {\n      final I = intervals[i];\n      final a = I.a;\n      final b = I.b;\n      for (var v = a; v <= b; v++) {\n        values.add(v);\n      }\n    }\n    return values;\n  }\n\n  Set<int> toSet() {\n    final s = <int>{};\n    for (final I in intervals) {\n      final a = I.a;\n      final b = I.b;\n      for (var v = a; v <= b; v++) {\n        s.add(v);\n      }\n    }\n    return s;\n  }\n\n  /// Get the ith element of ordered set.  Used only by RandomPhrase so\n  ///  don't bother to implement if you're not doing that for a new\n  ///  ANTLR code gen target.\n  int get(int i) {\n    final n = intervals.length;\n    var index = 0;\n    for (var j = 0; j < n; j++) {\n      final I = intervals[j];\n      final a = I.a;\n      final b = I.b;\n      for (var v = a; v <= b; v++) {\n        if (index == i) {\n          return v;\n        }\n        index++;\n      }\n    }\n    return -1;\n  }\n\n  void remove(int el) {\n    if (readonly) throw StateError(\"can't alter readonly IntervalSet\");\n    final n = intervals.length;\n    for (var i = 0; i < n; i++) {\n      final I = intervals[i];\n      final a = I.a;\n      final b = I.b;\n      if (el < a) {\n        break; // list is sorted and el is before this interval; not here\n      }\n// if whole interval x..x, rm\n      if (el == a && el == b) {\n        intervals.removeAt(i);\n        break;\n      }\n// if on left edge x..b, adjust left\n      if (el == a) {\n        I.a++;\n        break;\n      }\n// if on right edge a..x, adjust right\n      if (el == b) {\n        I.b--;\n        break;\n      }\n// if in middle a..x..b, split interval\n      if (el > a && el < b) {\n        // found in this interval\n        final oldb = I.b;\n        I.b = el - 1; // [a..x-1]\n        addRange(el + 1, oldb); // add [x+1..b]\n      }\n    }\n  }\n\n  bool isReadonly() {\n    return readonly;\n  }\n\n  void setReadonly(bool readonly) {\n    if (this.readonly && !readonly) {\n      throw StateError(\"can't alter readonly IntervalSet\");\n    }\n    this.readonly = readonly;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/lexer.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:developer';\n\nimport 'atn/atn.dart';\nimport 'error/error.dart';\nimport 'input_stream.dart';\nimport 'interval_set.dart';\nimport 'misc/misc.dart';\nimport 'recognizer.dart';\nimport 'token.dart';\nimport 'token_factory.dart';\nimport 'token_source.dart';\nimport 'util/utils.dart';\n\nabstract class Lexer extends Recognizer<LexerATNSimulator>\n    implements TokenSource {\n  static final DEFAULT_MODE = 0;\n  static final MORE = -2;\n  static final SKIP = -3;\n\n  static final DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL;\n  static final HIDDEN = Token.HIDDEN_CHANNEL;\n  static final MIN_CHAR_VALUE = 0x0000;\n  static final MAX_CHAR_VALUE = 0x10FFFF;\n\n  CharStream _input;\n\n  late Pair<TokenSource, CharStream?> _tokenFactorySourcePair;\n\n  @override\n  TokenFactory get tokenFactory {\n    return _factory;\n  }\n\n  @override\n  set tokenFactory(TokenFactory factory) {\n    _factory = factory;\n  }\n\n  TokenFactory _factory = CommonTokenFactory.DEFAULT;\n\n  /// The goal of all lexer rules/methods is to create a token object.\n  /// this is an instance variable as multiple rules may collaborate to\n  /// create a single token. nextToken will return this object after\n  /// matching lexer rule(s). If you subclass to allow multiple token\n  /// emissions, then set this to the last token to be matched or\n  /// something nonnull so that the auto token emit mechanism will not\n  /// emit another token.\n  Token? _token;\n\n  /// What character index in the stream did the current token start at?\n  /// Needed, for example, to get the text for current token. Set at\n  /// the start of nextToken.\n  int tokenStartCharIndex = -1;\n\n  /// The line on which the first character of the token resides\n  int tokenStartLine = -1;\n\n  /// The character position of first character within the line\n  int tokenStartCharPositionInLine = -1;\n\n  /// Once we see EOF on char stream, next token will be EOF.\n  /// If you have DONE : EOF ; then you see DONE EOF.\n  bool _hitEOF = false;\n\n  /// The channel number for the current token\n  int channel = Token.DEFAULT_CHANNEL;\n\n  /// The token type for the current token\n  int type = Token.INVALID_TYPE;\n\n  final List<int> _modeStack = [];\n  int mode_ = Lexer.DEFAULT_MODE;\n\n  /// You can set the text for the current token to override what is in\n  /// the input char buffer. Use setText() or can set this instance var.\n  String? _text;\n\n  Lexer(CharStream input) : _input = input {\n    _tokenFactorySourcePair = Pair(this, input);\n  }\n\n  void reset([bool resetInput = false]) {\n    // wacky Lexer state variables\n    if (resetInput) {\n      _input.seek(0); // rewind the input\n    }\n    _token = null;\n    type = Token.INVALID_TYPE;\n    channel = Token.DEFAULT_CHANNEL;\n    tokenStartCharIndex = -1;\n    tokenStartCharPositionInLine = -1;\n    tokenStartLine = -1;\n    _text = null;\n\n    _hitEOF = false;\n    mode_ = Lexer.DEFAULT_MODE;\n    _modeStack.clear();\n\n    interpreter?.reset();\n  }\n\n  /// Return a token from this source; i.e., match a token on the char stream.\n  @override\n  Token nextToken() {\n    // Mark start location in char stream so unbuffered streams are\n    // guaranteed at least have text of current token\n    final tokenStartMarker = _input.mark();\n    try {\n      outer:\n      while (true) {\n        if (_hitEOF) {\n          emitEOF();\n          return _token!;\n        }\n\n        _token = null;\n        channel = Token.DEFAULT_CHANNEL;\n        tokenStartCharIndex = _input.index;\n        tokenStartCharPositionInLine = interpreter!.charPositionInLine;\n        tokenStartLine = interpreter!.line;\n        _text = null;\n        do {\n          type = Token.INVALID_TYPE;\n//\t\t\t\tSystem.out.println(\"nextToken line \"+tokenStartLine+\" at \"+((char)input.LA(1))+\n//\t\t\t\t\t\t\t\t   \" in mode \"+mode+\n//\t\t\t\t\t\t\t\t   \" at index \"+input.index());\n          late int ttype;\n          try {\n            ttype = interpreter!.match(_input, mode_);\n          } on LexerNoViableAltException catch (e) {\n            notifyListeners(e); // report error\n            recover(e);\n            ttype = SKIP;\n          }\n          if (_input.LA(1) == IntStream.EOF) {\n            _hitEOF = true;\n          }\n          if (type == Token.INVALID_TYPE) type = ttype;\n          if (type == SKIP) {\n            continue outer;\n          }\n        } while (type == MORE);\n        if (_token == null) emit();\n        return _token!;\n      }\n    } finally {\n      // make sure we release marker after match or\n      // unbuffered char stream will keep buffering\n      _input.release(tokenStartMarker);\n    }\n  }\n\n  /// Instruct the lexer to skip creating a token for current lexer rule\n  /// and look for another token. nextToken() knows to keep looking when\n  /// a lexer rule finishes with token set to SKIP_TOKEN. Recall that\n  /// if token==null at end of any token rule, it creates one for you\n  /// and emits it.\n  void skip() {\n    type = Lexer.SKIP;\n  }\n\n  void more() {\n    type = Lexer.MORE;\n  }\n\n  void mode(int m) {\n    mode_ = m;\n  }\n\n  void pushMode(int m) {\n    if (LexerATNSimulator.debug) {\n      log('pushMode $m');\n    }\n    _modeStack.add(mode_);\n    mode(m);\n  }\n\n  int popMode() {\n    if (_modeStack.isEmpty) throw StateError('');\n    if (LexerATNSimulator.debug) log('popMode back to ${_modeStack.last}');\n    mode(_modeStack.removeLast());\n    return mode_;\n  }\n\n  /// Set the char stream and reset the lexer\n  @override\n  set inputStream(CharStream input) {\n    _tokenFactorySourcePair = Pair(this, null);\n    reset(false);\n    _input = input;\n    _tokenFactorySourcePair = Pair(this, _input);\n  }\n\n  @override\n  String get sourceName {\n    return _input.sourceName;\n  }\n\n  @override\n  CharStream get inputStream {\n    return _input;\n  }\n\n  /// By default does not support multiple emits per nextToken invocation\n  ///  for efficiency reasons.  Subclass and override this method, nextToken,\n  ///  and getToken (to push tokens into a list and pull from that list\n  ///  rather than a single variable as this implementation does).\n  void emitToken(Token token) {\n    //System.err.println(\"emit \"+token);\n    _token = token;\n  }\n\n  /// The standard method called to automatically emit a token at the\n  ///  outermost lexical rule.  The token object should point into the\n  ///  char buffer start..stop.  If there is a text override in 'text',\n  ///  use that to set the token's text.  Override this method to emit\n  ///  custom Token objects or provide a new factory.\n  Token emit() {\n    final t = tokenFactory.create(\n        type,\n        _text,\n        _tokenFactorySourcePair,\n        channel,\n        tokenStartCharIndex,\n        charIndex - 1,\n        tokenStartLine,\n        tokenStartCharPositionInLine);\n    emitToken(t);\n    return t;\n  }\n\n  Token emitEOF() {\n    final cpos = charPositionInLine;\n    final eof = tokenFactory.create(\n      Token.EOF,\n      null,\n      _tokenFactorySourcePair,\n      Token.DEFAULT_CHANNEL,\n      _input.index,\n      _input.index - 1,\n      line,\n      cpos,\n    );\n    emitToken(eof);\n    return eof;\n  }\n\n  @override\n  int get charPositionInLine {\n    return interpreter!.charPositionInLine;\n  }\n\n  @override\n  int get line {\n    return interpreter!.line;\n  }\n\n  set line(int line) {\n    interpreter!.line = line;\n  }\n\n  set charPositionInLine(int charPositionInLine) {\n    interpreter!.charPositionInLine = charPositionInLine;\n  }\n\n  /// What is the index of the current character of lookahead?\n  int get charIndex {\n    return _input.index;\n  }\n\n  /// Return the text matched so far for the current token or any\n  ///  text override.\n  String get text {\n    if (_text != null) {\n      return _text!;\n    }\n    return interpreter!.getText(_input);\n  }\n\n  /// Set the complete text of this token; it wipes any previous\n  ///  changes to the text.\n  set text(String text) {\n    _text = text;\n  }\n\n  /// Override if emitting multiple tokens.\n  Token? get token {\n    return _token;\n  }\n\n  void setToken(Token _token) {\n    this._token = _token;\n  }\n\n  List<String>? get channelNames => null;\n\n  List<String>? get modeNames => null;\n\n  /// Return a list of all Token objects in input char stream.\n  ///  Forces load of all tokens. Does not include EOF token.\n  List<Token> get allTokens {\n    final tokens = <Token>[];\n    var t = nextToken();\n    while (t.type != Token.EOF) {\n      tokens.add(t);\n      t = nextToken();\n    }\n    return tokens;\n  }\n\n  void notifyListeners(LexerNoViableAltException e) {\n    final text = _input.getText(Interval.of(tokenStartCharIndex, _input.index));\n    final msg = \"token recognition error at: '\" + getErrorDisplay(text) + \"'\";\n\n    final listener = errorListenerDispatch;\n    listener.syntaxError(\n      this,\n      null,\n      tokenStartLine,\n      tokenStartCharPositionInLine,\n      msg,\n      e,\n    );\n  }\n\n  String getErrorDisplay(String s) {\n    return escapeWhitespace(s);\n  }\n\n  String getCharErrorDisplay(int c) {\n    final s = getErrorDisplay(String.fromCharCode(c));\n    return \"'$s'\";\n  }\n\n  /// Lexers can normally match any char in it's vocabulary after matching\n  ///  a token, so do the easy thing and just kill a character and hope\n  ///  it all works out.  You can instead use the rule invocation stack\n  ///  to do sophisticated error recovery if you are in a fragment rule.\n  void recover(RecognitionException re) {\n    if (re is LexerNoViableAltException) {\n      if (_input.LA(1) != IntStream.EOF) {\n        // skip a char and try again\n        interpreter!.consume(_input);\n      }\n    } else {\n      //System.out.println(\"consuming char \"+(char)input.LA(1)+\" during recovery\");\n      //re.printStackTrace();\n      // TODO: Do we lose character or line position information?\n      _input.consume();\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/ll1_analyzer.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport './util/bit_set.dart';\nimport 'atn/atn.dart';\nimport 'interval_set.dart';\nimport 'prediction_context.dart';\nimport 'rule_context.dart';\nimport 'token.dart';\nimport 'util/bit_set.dart';\n\nclass LL1Analyzer {\n  /// Special value added to the lookahead sets to indicate that we hit\n  ///  a predicate during analysis if {@code seeThruPreds==false}.\n  static final int HIT_PRED = Token.INVALID_TYPE;\n\n  final ATN atn;\n\n  LL1Analyzer(this.atn);\n\n  /// Calculates the SLL(1) expected lookahead set for each outgoing transition\n  /// of an [ATNState]. The returned array has one element for each\n  /// outgoing transition in [s]. If the closure from transition\n  /// <em>i</em> leads to a semantic predicate before matching a symbol, the\n  /// element at index <em>i</em> of the result will be null.\n  ///\n  /// @param s the ATN state\n  /// @return the expected symbols for each outgoing transition of [s].\n  List<IntervalSet?> getDecisionLookahead(ATNState s) {\n//\t\tSystem.out.println(\"LOOK(\"+s.stateNumber+\")\");\n    return List<IntervalSet?>.generate(s.numberOfTransitions, (n) {\n      final lookAlt = IntervalSet();\n      final lookBusy = <ATNConfig>{};\n      final seeThruPreds = false; // fail to get lookahead upon pred\n      _LOOK(\n        s.transition(n).target,\n        null,\n        EmptyPredictionContext.Instance,\n        lookAlt,\n        lookBusy,\n        BitSet(),\n        seeThruPreds,\n        false,\n      );\n\n      // Wipe out lookahead for this alternative if we found nothing\n      // or we had a predicate when we !seeThruPreds\n      if (lookAlt.length == 0 || lookAlt.contains(HIT_PRED)) {\n        return null;\n      }\n      return lookAlt;\n    });\n  }\n\n  /// Compute set of tokens that can follow [s] in the ATN in the\n  /// specified [ctx].\n  ///\n  /// <p>If [ctx] is null and the end of the rule containing\n  /// [s] is reached, {@link Token#EPSILON} is added to the result set.\n  /// If [ctx] is not null and the end of the outermost rule is\n  /// reached, {@link Token#EOF} is added to the result set.</p>\n  ///\n  /// @param s the ATN state\n  /// @param stopState the ATN state to stop at. This can be a\n  /// [BlockEndState] to detect epsilon paths through a closure.\n  /// @param ctx the complete parser context, or null if the context\n  /// should be ignored\n  ///\n  /// @return The set of tokens that can follow [s] in the ATN in the\n  /// specified [ctx].\n\n  IntervalSet LOOK(\n    ATNState s,\n    RuleContext? ctx, [\n    ATNState? stopState,\n  ]) {\n    final r = IntervalSet();\n    final seeThruPreds = true; // ignore preds; get all lookahead\n    final lookContext =\n        ctx != null ? PredictionContext.fromRuleContext(s.atn, ctx) : null;\n    _LOOK(\n      s,\n      stopState,\n      lookContext,\n      r,\n      <ATNConfig>{},\n      BitSet(),\n      seeThruPreds,\n      true,\n    );\n    return r;\n  }\n\n  /// Compute set of tokens that can follow [s] in the ATN in the\n  /// specified [ctx].\n  ///\n  /// <p>If [ctx] is null and [stopState] or the end of the\n  /// rule containing [s] is reached, {@link Token#EPSILON} is added to\n  /// the result set. If [ctx] is not null and [addEOF] is\n  /// [true] and [stopState] or the end of the outermost rule is\n  /// reached, {@link Token#EOF} is added to the result set.</p>\n  ///\n  /// @param s the ATN state.\n  /// @param stopState the ATN state to stop at. This can be a\n  /// [BlockEndState] to detect epsilon paths through a closure.\n  /// @param ctx The outer context, or null if the outer context should\n  /// not be used.\n  /// @param look The result lookahead set.\n  /// @param lookBusy A set used for preventing epsilon closures in the ATN\n  /// from causing a stack overflow. Outside code should pass\n  /// {@code new HashSet<ATNConfig>} for this argument.\n  /// @param calledRuleStack A set used for preventing left recursion in the\n  /// ATN from causing a stack overflow. Outside code should pass\n  /// {@code new BitSet()} for this argument.\n  /// @param seeThruPreds [true] to true semantic predicates as\n  /// implicitly [true] and \"see through them\", otherwise [false]\n  /// to treat semantic predicates as opaque and add {@link #HIT_PRED} to the\n  /// result if one is encountered.\n  /// @param addEOF Add {@link Token#EOF} to the result if the end of the\n  /// outermost context is reached. This parameter has no effect if [ctx]\n  /// is null.\n  void _LOOK(\n      ATNState s,\n      ATNState? stopState,\n      PredictionContext? ctx,\n      IntervalSet look,\n      Set<ATNConfig> lookBusy,\n      BitSet calledRuleStack,\n      bool seeThruPreds,\n      bool addEOF) {\n//\t\tSystem.out.println(\"_LOOK(\"+s.stateNumber+\", ctx=\"+ctx);\n    final c = ATNConfig(s, 0, ctx);\n    if (!lookBusy.add(c)) return;\n\n    if (s == stopState) {\n      if (ctx == null) {\n        look.addOne(Token.EPSILON);\n        return;\n      } else if (ctx.isEmpty && addEOF) {\n        look.addOne(Token.EOF);\n        return;\n      }\n    }\n\n    if (s is RuleStopState) {\n      if (ctx == null) {\n        look.addOne(Token.EPSILON);\n        return;\n      } else if (ctx.isEmpty && addEOF) {\n        look.addOne(Token.EOF);\n        return;\n      }\n\n      if (ctx != EmptyPredictionContext.Instance) {\n        // run thru all possible stack tops in ctx\n        final removed = calledRuleStack[s.ruleIndex];\n        try {\n          calledRuleStack.clear(s.ruleIndex);\n          for (var i = 0; i < ctx.length; i++) {\n            final returnState = atn.states[ctx.getReturnState(i)]!;\n//\t\t\t\t\t    System.out.println(\"popping back to \"+retState);\n            _LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy,\n                calledRuleStack, seeThruPreds, addEOF);\n          }\n        } finally {\n          if (removed) {\n            calledRuleStack.set(s.ruleIndex);\n          }\n        }\n        return;\n      }\n    }\n\n    for (var i = 0; i < s.numberOfTransitions; i++) {\n      final t = s.transition(i);\n      if (t is RuleTransition) {\n        if (calledRuleStack[t.target.ruleIndex]) {\n          continue;\n        }\n\n        PredictionContext newContext = SingletonPredictionContext.create(\n          ctx,\n          t.followState.stateNumber,\n        );\n\n        try {\n          calledRuleStack.set(t.target.ruleIndex);\n          _LOOK(t.target, stopState, newContext, look, lookBusy,\n              calledRuleStack, seeThruPreds, addEOF);\n        } finally {\n          calledRuleStack.clear(t.target.ruleIndex);\n        }\n      } else if (t is AbstractPredicateTransition) {\n        if (seeThruPreds) {\n          _LOOK(\n            t.target,\n            stopState,\n            ctx,\n            look,\n            lookBusy,\n            calledRuleStack,\n            seeThruPreds,\n            addEOF,\n          );\n        } else {\n          look.addOne(HIT_PRED);\n        }\n      } else if (t.isEpsilon) {\n        _LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack,\n            seeThruPreds, addEOF);\n      } else if (t is WildcardTransition) {\n        look.addAll(\n          IntervalSet.ofRange(Token.MIN_USER_TOKEN_TYPE, atn.maxTokenType),\n        );\n      } else {\n//\t\t\t\tSystem.out.println(\"adding \"+ t);\n        var set = t.label;\n        if (set != null) {\n          if (t is NotSetTransition) {\n            set = set.complement(\n              IntervalSet.ofRange(Token.MIN_USER_TOKEN_TYPE, atn.maxTokenType),\n            );\n          }\n          look.addAll(set);\n        }\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/misc/misc.dart",
    "content": "/*\n * Copyright (c) 2012-2023 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport 'src/multi_map.dart';\nexport 'src/pair.dart';\n"
  },
  {
    "path": "runtime/Dart/lib/src/misc/src/multi_map.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'package:collection/collection.dart';\n\nimport 'pair.dart';\n\nclass MultiMap<K, V> extends DelegatingMap<K, List<V>> {\n  MultiMap() : super({});\n\n  void put(K key, V value) {\n    var elementsForKey = this[key];\n    if (elementsForKey == null) {\n      elementsForKey = [];\n      this[key] = elementsForKey;\n    }\n    elementsForKey.add(value);\n  }\n\n  List<Pair<K, V>> get pairs {\n    final pairs = <Pair<K, V>>[];\n    for (var key in keys) {\n      for (var value in this[key]!) {\n        pairs.add(Pair<K, V>(key, value));\n      }\n    }\n    return pairs;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/misc/src/pair.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../util/murmur_hash.dart';\n\nclass Pair<A, B> {\n  final A a;\n  final B b;\n\n  const Pair(this.a, this.b);\n\n  @override\n  bool operator ==(other) {\n    return identical(this, other) ||\n        other is Pair && a == other.a && b == other.b;\n  }\n\n  @override\n  String toString() {\n    return '($a, $b)';\n  }\n\n  @override\n  int get hashCode {\n    MurmurHash.initialize();\n\n    var hash = MurmurHash.initialize();\n    hash = MurmurHash.update(hash, a);\n    hash = MurmurHash.update(hash, b);\n    return MurmurHash.finish(hash, 2);\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/parser.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'atn/atn.dart';\nimport 'error/error.dart';\nimport 'input_stream.dart';\nimport 'interval_set.dart';\nimport 'lexer.dart';\nimport 'parser_rule_context.dart';\nimport 'recognizer.dart';\nimport 'rule_context.dart';\nimport 'token.dart';\nimport 'token_factory.dart';\nimport 'token_stream.dart';\nimport 'tree/tree.dart';\n\nimport 'util/platform_stub.dart'\n    if (dart.library.io) 'util/platform_io.dart'\n    if (dart.library.html) 'util/platform_html.dart';\n\n/// This is all the parsing support code essentially; most of it is error recovery stuff. */\nabstract class Parser extends Recognizer<ParserATNSimulator> {\n  /// This field maps from the serialized ATN string to the deserialized [ATN] with\n  /// bypass alternatives.\n  ///\n  /// @see ATNDeserializationOptions#isGenerateRuleBypassTransitions()\n  ATN? bypassAltsAtnCache;\n\n  /// The error handling strategy for the parser. The default value is a new\n  /// instance of [DefaultErrorStrategy].\n  ///\n  /// @see #getErrorHandler\n  /// @see #setErrorHandler\n\n  ErrorStrategy errorHandler = DefaultErrorStrategy();\n\n  /// The input stream.\n  ///\n  /// @see #getInputStream\n  /// @see #setInputStream\n  TokenStream _input;\n\n  final List<int> _precedenceStack = [0];\n\n  /// The [ParserRuleContext] object for the currently executing rule.\n  /// This is always non-null during the parsing process.\n  ParserRuleContext? context;\n\n  /// Specifies whether or not the parser should construct a parse tree during\n  /// the parsing process. The default value is [true].\n  bool buildParseTree = true;\n\n  /// When {@link #setTrace}{@code (true)} is called, a reference to the\n  /// [TraceListener] is stored here so it can be easily removed in a\n  /// later call to {@link #setTrace}{@code (false)}. The listener itself is\n  /// implemented as a parser listener so this field is not directly used by\n  /// other parser methods.\n  TraceListener? _tracer;\n\n  /// The list of [ParseTreeListener] listeners registered to receive\n  /// events during the parse.\n  ///\n  /// @see #addParseListener\n  List<ParseTreeListener>? _parseListeners;\n\n  /// The number of syntax errors reported during parsing. This value is\n  /// incremented each time {@link #notifyErrorListeners} is called.\n  int _syntaxErrors = 0;\n\n  /// Indicates parser has match()ed EOF token. See {@link #exitRule()}. */\n  bool matchedEOF = false;\n\n  Parser(this._input) {\n    reset(false);\n  }\n\n  /// reset the parser's state */\n  void reset([bool resetInput = true]) {\n    if (resetInput) inputStream.seek(0);\n    errorHandler.reset(this);\n    context = null;\n    _syntaxErrors = 0;\n    matchedEOF = false;\n    setTrace(false);\n    _precedenceStack.clear();\n    _precedenceStack.add(0);\n    interpreter?.reset();\n  }\n\n  /// Match current input symbol against [ttype]. If the symbol type\n  /// matches, {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are\n  /// called to complete the match process.\n  ///\n  /// <p>If the symbol type does not match,\n  /// {@link ANTLRErrorStrategy#recoverInline} is called on the current error\n  /// strategy to attempt recovery. If {@link #getBuildParseTree} is\n  /// [true] and the token index of the symbol returned by\n  /// {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to\n  /// the parse tree by calling {@link #createErrorNode(ParserRuleContext, Token)} then\n  /// {@link ParserRuleContext#addErrorNode(ErrorNode)}.</p>\n  ///\n  /// @param ttype the token type to match\n  /// @return the matched symbol\n  /// @throws RecognitionException if the current input symbol did not match\n  /// [ttype] and the error strategy could not recover from the\n  /// mismatched symbol\n  Token match(int ttype) {\n    var t = currentToken;\n    if (t.type == ttype) {\n      if (ttype == Token.EOF) {\n        matchedEOF = true;\n      }\n      errorHandler.reportMatch(this);\n      consume();\n    } else {\n      t = errorHandler.recoverInline(this);\n      if (buildParseTree && t.tokenIndex == -1) {\n        // we must have conjured up a new token during single token insertion\n        // if it's not the current symbol\n        context!.addErrorNode(createErrorNode(context!, t));\n      }\n    }\n    return t;\n  }\n\n  /// Match current input symbol as a wildcard. If the symbol type matches\n  /// (i.e. has a value greater than 0), {@link ANTLRErrorStrategy#reportMatch}\n  /// and {@link #consume} are called to complete the match process.\n  ///\n  /// <p>If the symbol type does not match,\n  /// {@link ANTLRErrorStrategy#recoverInline} is called on the current error\n  /// strategy to attempt recovery. If {@link #getBuildParseTree} is\n  /// [true] and the token index of the symbol returned by\n  /// {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to\n  /// the parse tree by calling {@link Parser#createErrorNode(ParserRuleContext, Token)}. then\n  /// {@link ParserRuleContext#addErrorNode(ErrorNode)}</p>\n  ///\n  /// @return the matched symbol\n  /// @throws RecognitionException if the current input symbol did not match\n  /// a wildcard and the error strategy could not recover from the mismatched\n  /// symbol\n  Token matchWildcard() {\n    var t = currentToken;\n    if (t.type > 0) {\n      errorHandler.reportMatch(this);\n      consume();\n    } else {\n      t = errorHandler.recoverInline(this);\n      if (buildParseTree && t.tokenIndex == -1) {\n        // we must have conjured up a new token during single token insertion\n        // if it's not the current symbol\n        context!.addErrorNode(createErrorNode(context!, t));\n      }\n    }\n\n    return t;\n  }\n\n  /// Trim the internal lists of the parse tree during parsing to conserve memory.\n  /// This property is set to [false] by default for a newly constructed parser.\n  ///\n  /// @param trimParseTrees [true] to trim the capacity of the {@link ParserRuleContext#children}\n  /// list to its size after a rule is parsed.\n  set trimParseTree(bool trimParseTrees) {\n    if (trimParseTrees) {\n      if (trimParseTree) return;\n      addParseListener(TrimToSizeListener.INSTANCE);\n    } else {\n      removeParseListener(TrimToSizeListener.INSTANCE);\n    }\n  }\n\n  /// @return [true] if the {@link ParserRuleContext#children} list is trimmed\n  /// using the default {@link Parser.TrimToSizeListener} during the parse process.\n  bool get trimParseTree {\n    return parseListeners?.contains(TrimToSizeListener.INSTANCE) ?? false;\n  }\n\n  List<ParseTreeListener>? get parseListeners => _parseListeners;\n\n  /// Registers [listener] to receive events during the parsing process.\n  ///\n  /// <p>To support output-preserving grammar transformations (including but not\n  /// limited to left-recursion removal, automated left-factoring, and\n  /// optimized code generation), calls to listener methods during the parse\n  /// may differ substantially from calls made by\n  /// {@link ParseTreeWalker#DEFAULT} used after the parse is complete. In\n  /// particular, rule entry and exit events may occur in a different order\n  /// during the parse than after the parser. In addition, calls to certain\n  /// rule entry methods may be omitted.</p>\n  ///\n  /// <p>With the following specific exceptions, calls to listener events are\n  /// <em>deterministic</em>, i.e. for identical input the calls to listener\n  /// methods will be the same.</p>\n  ///\n  /// <ul>\n  /// <li>Alterations to the grammar used to generate code may change the\n  /// behavior of the listener calls.</li>\n  /// <li>Alterations to the command line options passed to ANTLR 4 when\n  /// generating the parser may change the behavior of the listener calls.</li>\n  /// <li>Changing the version of the ANTLR Tool used to generate the parser\n  /// may change the behavior of the listener calls.</li>\n  /// </ul>\n  ///\n  /// @param listener the listener to add\n  ///\n  /// @throws NullPointerException if {@code} listener is null\n  void addParseListener(\n    ParseTreeListener listener,\n  ) {\n    _parseListeners ??= [];\n\n    _parseListeners!.add(listener);\n  }\n\n  /// Remove [listener] from the list of parse listeners.\n  ///\n  /// <p>If [listener] is null or has not been added as a parse\n  /// listener, this method does nothing.</p>\n  ///\n  /// @see #addParseListener\n  ///\n  /// @param listener the listener to remove\n  void removeParseListener(ParseTreeListener? listener) {\n    if (_parseListeners != null) {\n      if (_parseListeners!.remove(listener)) {\n        if (_parseListeners!.isEmpty) {\n          _parseListeners = null;\n        }\n      }\n    }\n  }\n\n  /// Remove all parse listeners.\n  ///\n  /// @see #addParseListener\n  void removeParseListeners() {\n    _parseListeners = null;\n  }\n\n  /// Notify any parse listeners of an enter rule event.\n  ///\n  /// @see #addParseListener\n  void triggerEnterRuleEvent() {\n    if (_parseListeners == null) return;\n    for (var listener in _parseListeners!) {\n      listener.enterEveryRule(context!);\n      context!.enterRule(listener);\n    }\n  }\n\n  /// Notify any parse listeners of an exit rule event.\n  ///\n  /// @see #addParseListener\n  void triggerExitRuleEvent() {\n    if (_parseListeners == null) return;\n    // reverse order walk of listeners\n    for (var i = _parseListeners!.length - 1; i >= 0; i--) {\n      final listener = _parseListeners![i];\n      context!.exitRule(listener);\n      listener.exitEveryRule(context!);\n    }\n  }\n\n  /// Gets the number of syntax errors reported during parsing. This value is\n  /// incremented each time {@link #notifyErrorListeners} is called.\n  ///\n  /// @see #notifyErrorListeners\n  int get numberOfSyntaxErrors {\n    return _syntaxErrors;\n  }\n\n  @override\n  TokenFactory get tokenFactory {\n    return _input.tokenSource.tokenFactory;\n  }\n\n  /// Tell our token source and error strategy about a new way to create tokens. */\n  @override\n  set tokenFactory(TokenFactory factory) {\n    _input.tokenSource.tokenFactory = factory;\n  }\n\n  /// The ATN with bypass alternatives is expensive to create so we create it\n  /// lazily.\n  ///\n  /// @throws UnsupportedOperationException if the current parser does not\n  /// implement the {@link #getSerializedATN()} method.\n  ATN get ATNWithBypassAlts {\n    if (serializedATN == null) {\n      throw UnsupportedError(\n          'The current parser does not support an ATN with bypass alternatives.');\n    }\n\n    if (bypassAltsAtnCache == null) {\n      final deserializationOptions = ATNDeserializationOptions(false);\n      deserializationOptions.setGenerateRuleBypassTransitions(true);\n      bypassAltsAtnCache = ATNDeserializer(deserializationOptions).deserialize(serializedATN);\n    }\n\n    return bypassAltsAtnCache!;\n  }\n\n  /// The preferred method of getting a tree pattern. For example, here's a\n  /// sample use:\n  ///\n  /// <pre>\n  /// ParseTree t = parser.expr();\n  /// ParseTreePattern p = parser.compileParseTreePattern(\"&lt;ID&gt;+0\", MyParser.RULE_expr);\n  /// ParseTreeMatch m = p.match(t);\n  /// String id = m.get(\"ID\");\n  /// </pre>\n  ParseTreePattern compileParseTreePattern(\n    String pattern,\n    int patternRuleIndex, [\n    Lexer? lexer,\n  ]) {\n    if (lexer == null) {\n      final tokenSource = tokenStream.tokenSource;\n      if (tokenSource is! Lexer) {\n        throw UnsupportedError(\"Parser can't discover a lexer to use\");\n      }\n      lexer = tokenSource;\n    }\n\n    final m = ParseTreePatternMatcher(lexer, this);\n    return m.compile(pattern, patternRuleIndex);\n  }\n\n  @override\n  TokenStream get inputStream => tokenStream;\n\n  @override\n  set inputStream(TokenStream input) {\n    setTokenStream(input);\n  }\n\n  TokenStream get tokenStream => _input;\n\n  /// Set the token stream and reset the parser. */\n  void setTokenStream(TokenStream input) {\n    reset(false);\n    _input = input;\n  }\n\n  /// Match needs to return the current input symbol, which gets put\n  ///  into the label for the associated token ref; e.g., x=ID.\n\n  Token get currentToken {\n    return _input.LT(1)!;\n  }\n\n  void notifyErrorListeners(\n    String msg, [\n    Token? offendingToken,\n    RecognitionException? e,\n  ]) {\n    offendingToken = offendingToken ?? currentToken;\n    _syntaxErrors++;\n    int? line = -1;\n    var charPositionInLine = -1;\n    line = offendingToken.line;\n    charPositionInLine = offendingToken.charPositionInLine;\n\n    final listener = errorListenerDispatch;\n    listener.syntaxError(\n      this,\n      offendingToken,\n      line,\n      charPositionInLine,\n      msg,\n      e,\n    );\n  }\n\n  /// Consume and return the {@linkplain #getCurrentToken current symbol}.\n  ///\n  /// <p>E.g., given the following input with [A] being the current\n  /// lookahead symbol, this function moves the cursor to [B] and returns\n  /// [A].</p>\n  ///\n  /// <pre>\n  ///  A B\n  ///  ^\n  /// </pre>\n  ///\n  /// If the parser is not in error recovery mode, the consumed symbol is added\n  /// to the parse tree using {@link ParserRuleContext#addChild}, and\n  /// {@link ParseTreeListener#visitTerminal} is called on any parse listeners.\n  /// If the parser <em>is</em> in error recovery mode, the consumed symbol is\n  /// added to the parse tree using {@link #createErrorNode(ParserRuleContext, Token)} then\n  /// {@link ParserRuleContext#addErrorNode(ErrorNode)} and\n  /// {@link ParseTreeListener#visitErrorNode} is called on any parse\n  /// listeners.\n  Token consume() {\n    final o = currentToken;\n    if (o.type != IntStream.EOF) {\n      inputStream.consume();\n    }\n    final hasListener = _parseListeners != null && _parseListeners!.isNotEmpty;\n    if (buildParseTree || hasListener) {\n      if (errorHandler.inErrorRecoveryMode(this)) {\n        final node = context!.addErrorNode(createErrorNode(context!, o));\n        if (_parseListeners != null) {\n          for (var listener in _parseListeners!) {\n            listener.visitErrorNode(node);\n          }\n        }\n      } else {\n        final node = context!.addChild(createTerminalNode(context!, o));\n        if (_parseListeners != null) {\n          for (var listener in _parseListeners!) {\n            listener.visitTerminal(node);\n          }\n        }\n      }\n    }\n    return o;\n  }\n\n  /// How to create a token leaf node associated with a parent.\n  ///  Typically, the terminal node to create is not a function of the parent.\n  ///\n  /// @since 4.7\n  TerminalNode createTerminalNode(ParserRuleContext parent, Token t) {\n    return TerminalNodeImpl(t);\n  }\n\n  /// How to create an error node, given a token, associated with a parent.\n  ///  Typically, the error node to create is not a function of the parent.\n  ///\n  /// @since 4.7\n  ErrorNode createErrorNode(ParserRuleContext parent, Token t) {\n    return ErrorNodeImpl(t);\n  }\n\n  void addContextToParseTree() {\n    final parent = context?.parent;\n    // add current context to parent if we have a parent\n    if (parent != null) {\n      parent.addAnyChild(context!);\n    }\n  }\n\n  /// Always called by generated parsers upon entry to a rule. Access field\n  /// {@link #_ctx} get the current context.\n  void enterRule(ParserRuleContext localctx, int state, int ruleIndex) {\n    this.state = state;\n    context = localctx;\n    context!.start = _input.LT(1)!;\n    if (buildParseTree) addContextToParseTree();\n    if (_parseListeners != null) triggerEnterRuleEvent();\n  }\n\n  void exitRule() {\n    assert(context != null);\n    if (matchedEOF) {\n      // if we have matched EOF, it cannot consume past EOF so we use LT(1) here\n      context!.stop = _input.LT(1); // LT(1) will be end of file\n    } else {\n      context!.stop = _input.LT(-1); // stop node is what we just matched\n    }\n    // trigger event on _ctx, before it reverts to parent\n    if (_parseListeners != null) triggerExitRuleEvent();\n    state = context!.invokingState;\n    context = context?.parent;\n  }\n\n  void enterOuterAlt(ParserRuleContext localctx, int altNum) {\n    assert(context != null);\n    localctx.altNumber = altNum;\n    // if we have new localctx, make sure we replace existing ctx\n    // that is previous child of parse tree\n    if (buildParseTree && context != localctx) {\n      final parent = context!.parent;\n      if (parent != null) {\n        parent.removeLastChild();\n        parent.addAnyChild(localctx);\n      }\n    }\n    context = localctx;\n  }\n\n  /// Get the precedence level for the top-most precedence rule.\n  ///\n  /// @return The precedence level for the top-most precedence rule, or -1 if\n  /// the parser context is not nested within a precedence rule.\n  int get precedence {\n    if (_precedenceStack.isEmpty) {\n      return -1;\n    }\n\n    return _precedenceStack.last;\n  }\n\n  void enterRecursionRule(\n      ParserRuleContext localctx, int state, int ruleIndex, int precedence) {\n    this.state = state;\n    _precedenceStack.add(precedence);\n    context = localctx;\n    context!.start = _input.LT(1)!;\n    if (_parseListeners != null) {\n      triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n    }\n  }\n\n  /// Like {@link #enterRule} but for recursive rules.\n  ///  Make the current context the child of the incoming localctx.\n  void pushNewRecursionContext(\n    ParserRuleContext localctx,\n    int state,\n    int? ruleIndex,\n  ) {\n    assert(context != null);\n    final previous = context!;\n    previous.parent = localctx;\n    previous.invokingState = state;\n    previous.stop = _input.LT(-1);\n\n    context = localctx;\n    context!.start = previous.start;\n    if (buildParseTree) {\n      context!.addAnyChild(previous);\n    }\n\n    if (_parseListeners != null) {\n      triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n    }\n  }\n\n  void unrollRecursionContexts(ParserRuleContext? _parentctx) {\n    assert(context != null);\n    _precedenceStack.removeLast();\n    context!.stop = _input.LT(-1);\n    final retctx = context!; // save current ctx (return value)\n\n    // unroll so _ctx is as it was before call to recursive method\n    if (_parseListeners != null) {\n      while (context != _parentctx) {\n        triggerExitRuleEvent();\n        context = context!.parent;\n      }\n    } else {\n      context = _parentctx;\n    }\n\n    // hook into tree\n    retctx.parent = _parentctx;\n\n    if (buildParseTree && _parentctx != null) {\n      // add return ctx into invoking rule's tree\n      _parentctx.addAnyChild(retctx);\n    }\n  }\n\n  ParserRuleContext? getInvokingContext(int ruleIndex) {\n    var p = context;\n    while (p != null) {\n      if (p.ruleIndex == ruleIndex) return p;\n      p = p.parent;\n    }\n    return null;\n  }\n\n  @override\n  bool precpred(RuleContext? localctx, int precedence) {\n    return precedence >= _precedenceStack.last;\n  }\n\n  bool inContext(String context) {\n    // TODO: useful in parser?\n    return false;\n  }\n\n  /// Checks whether or not [symbol] can follow the current state in the\n  /// ATN. The behavior of this method is equivalent to the following, but is\n  /// implemented such that the complete context-sensitive follow set does not\n  /// need to be explicitly constructed.\n  ///\n  /// <pre>\n  /// return expectedTokens.contains(symbol);\n  /// </pre>\n  ///\n  /// @param symbol the symbol type to check\n  /// @return [true] if [symbol] can follow the current state in\n  /// the ATN, otherwise [false].\n  bool isExpectedToken(int symbol) {\n//   \t\treturn interpreter!.atn.nextTokens(_ctx);\n    final atn = interpreter!.atn;\n    var ctx = context;\n    final s = atn.states[state];\n    var following = atn.nextTokens(s!);\n    if (following.contains(symbol)) {\n      return true;\n    }\n//        log(\"following \"+s+\"=\"+following);\n    if (!following.contains(Token.EPSILON)) return false;\n\n    while (ctx != null &&\n        ctx.invokingState >= 0 &&\n        following.contains(Token.EPSILON)) {\n      final invokingState = atn.states[ctx.invokingState]!;\n      final rt = invokingState.transition(0) as RuleTransition;\n      following = atn.nextTokens(rt.followState);\n      if (following.contains(symbol)) {\n        return true;\n      }\n\n      ctx = ctx.parent;\n    }\n\n    if (following.contains(Token.EPSILON) && symbol == Token.EOF) {\n      return true;\n    }\n\n    return false;\n  }\n\n  bool isMatchedEOF() {\n    return matchedEOF;\n  }\n\n  /// Computes the set of input symbols which could follow the current parser\n  /// state and context, as given by {@link #getState} and {@link #getContext},\n  /// respectively.\n  ///\n  /// @see ATN#getExpectedTokens(int, RuleContext)\n  IntervalSet get expectedTokens {\n    return getATN().getExpectedTokens(state, context);\n  }\n\n  IntervalSet get expectedTokensWithinCurrentRule {\n    final atn = interpreter!.atn;\n    final s = atn.states[state]!;\n    return atn.nextTokens(s);\n  }\n\n  /// Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found. */\n  int getRuleIndex(String ruleName) {\n    final ruleIndex = ruleIndexMap[ruleName];\n    if (ruleIndex != null) return ruleIndex;\n    return -1;\n  }\n\n  ParserRuleContext get ruleContext {\n    assert(context != null);\n    return context!;\n  }\n\n  List<String> get ruleInvocationStack => getRuleInvocationStack();\n\n  /// Return List&lt;String&gt; of the rule names in your parser instance\n  ///  leading up to a call to the current rule.  You could override if\n  ///  you want more details such as the file/line info of where\n  ///  in the ATN a rule is invoked.\n  ///\n  ///  This is very useful for error messages.\n  List<String> getRuleInvocationStack([RuleContext? p]) {\n    p = p ?? context;\n    final _ruleNames = ruleNames;\n    final stack = <String>[];\n    while (p != null) {\n      // compute what follows who invoked us\n      final ruleIndex = p.ruleIndex;\n      if (ruleIndex < 0) {\n        stack.add('n/a');\n      } else {\n        stack.add(_ruleNames[ruleIndex]);\n      }\n      p = p.parent;\n    }\n    return stack;\n  }\n\n  /// For debugging and other purposes. */\n  List<String> get dfaStrings {\n    final s = <String>[];\n    for (var d = 0; d < interpreter!.decisionToDFA.length; d++) {\n      final dfa = interpreter!.decisionToDFA[d];\n      s.add(dfa.toString(vocabulary));\n    }\n    return s;\n  }\n\n  /// For debugging and other purposes. */\n  void dumpDFA() {\n    var seenOne = false;\n    for (var d = 0; d < interpreter!.decisionToDFA.length; d++) {\n      final dfa = interpreter!.decisionToDFA[d];\n      if (dfa.states.isNotEmpty) {\n        if (seenOne) print('');\n        print('Decision ${dfa.decision}:');\n        stdoutWrite(dfa.toString(vocabulary));\n        seenOne = true;\n      }\n    }\n  }\n\n  String get sourceName {\n    return _input.sourceName;\n  }\n\n  @override\n  ParseInfo? get parseInfo {\n    final interp = interpreter;\n    if (interp is ProfilingATNSimulator) {\n      return ParseInfo(interp);\n    }\n    return null;\n  }\n\n  /// @since 4.3\n  void setProfile(bool profile) {\n    final interp = interpreter!;\n    final saveMode = interp.predictionMode;\n    if (profile) {\n      if (interp is! ProfilingATNSimulator) {\n        interpreter = ProfilingATNSimulator(this);\n      }\n    } else if (interp is ProfilingATNSimulator) {\n      final sim = ParserATNSimulator(\n        this,\n        getATN(),\n        interp.decisionToDFA,\n        interp.sharedContextCache,\n      );\n      interpreter = sim;\n    }\n    interpreter!.predictionMode = saveMode;\n  }\n\n  /// During a parse is sometimes useful to listen in on the rule entry and exit\n  ///  events as well as token matches. This is for quick and dirty debugging.\n  void setTrace(bool trace) {\n    if (!trace) {\n      removeParseListener(_tracer);\n      _tracer = null;\n    } else {\n      if (_tracer != null) {\n        removeParseListener(_tracer);\n      } else {\n        _tracer = TraceListener(this);\n      }\n      addParseListener(_tracer!);\n    }\n  }\n\n  /// Gets whether a [TraceListener] is registered as a parse listener\n  /// for the parser.\n  ///\n  /// @see #setTrace(bool)\n  bool isTrace() {\n    return _tracer != null;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/parser_interpreter.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:collection';\n\nimport 'atn/atn.dart';\nimport 'dfa/dfa.dart';\nimport 'error/error.dart';\nimport 'misc/misc.dart';\nimport 'parser.dart';\nimport 'parser_rule_context.dart';\nimport 'token.dart';\nimport 'token_stream.dart';\nimport 'vocabulary.dart';\n\n/// A parser simulator that mimics what ANTLR's generated\n///  parser code does. A ParserATNSimulator is used to make\n///  predictions via adaptivePredict but this class moves a pointer through the\n///  ATN to simulate parsing. ParserATNSimulator just\n///  makes us efficient rather than having to backtrack, for example.\n///\n///  This properly creates parse trees even for left recursive rules.\n///\n///  We rely on the left recursive rule invocation and special predicate\n///  transitions to make left recursive rules work.\n///\n///  See TestParserInterpreter for examples.\nclass ParserInterpreter extends Parser {\n  @override\n  final String grammarFileName;\n  final ATN atn;\n\n  late List<DFA> decisionToDFA; // not shared like it is for generated parsers\n  final PredictionContextCache sharedContextCache = PredictionContextCache();\n\n  @override\n  final List<String> ruleNames;\n\n  @override\n  final Vocabulary vocabulary;\n\n  /// This stack corresponds to the _parentctx, _parentState pair of locals\n  ///  that would exist on call stack frames with a recursive descent parser;\n  ///  in the generated function for a left-recursive rule you'd see:\n  ///\n  ///   EContext e(int _p) throws RecognitionException {\n  ///      ParserRuleContext _parentctx = context;    // Pair.a\n  ///      int _parentState = state;          // Pair.b\n  ///      ...\n  ///  }\n  ///\n  ///  Those values are used to create new recursive rule invocation contexts\n  ///  associated with left operand of an alt like \"expr '*' expr\".\n  final DoubleLinkedQueue<Pair<ParserRuleContext?, int>> _parentContextStack =\n      DoubleLinkedQueue();\n\n  /// We need a map from (decision,inputIndex)->forced alt for computing ambiguous\n  ///  parse trees. For now, we allow exactly one override.\n  int overrideDecision = -1;\n  int overrideDecisionInputIndex = -1;\n  int overrideDecisionAlt = -1;\n  bool overrideDecisionReached =\n      false; // latch and only override once; error might trigger infinite loop\n\n  /// What is the current context when we override a decisions?  This tells\n  ///  us what the root of the parse tree is when using override\n  ///  for an ambiguity/lookahead check.\n  InterpreterRuleContext? overrideDecisionRoot;\n\n  /// Return the root of the parse, which can be useful if the parser\n  ///  bails out. You still can access the top node. Note that,\n  ///  because of the way left recursive rules add children, it's possible\n  ///  that the root will not have any children if the start rule immediately\n  ///  called and left recursive rule that fails.\n  ///\n  /// @since 4.5.1\n  late InterpreterRuleContext rootContext;\n\n  ParserInterpreter(\n    this.grammarFileName,\n    this.vocabulary,\n    this.ruleNames,\n    this.atn,\n    TokenStream input,\n  ) : super(input) {\n    // init decision DFA\n    final numberOfDecisions = atn.numberOfDecisions;\n    decisionToDFA = List<DFA>.generate(numberOfDecisions, (n) {\n      final decisionState = atn.getDecisionState(n);\n      return DFA(decisionState, n);\n    });\n\n    // get atn simulator that knows how to do predictions\n    interpreter = ParserATNSimulator(\n      this,\n      atn,\n      decisionToDFA,\n      sharedContextCache,\n    );\n  }\n\n  @override\n  void reset([bool resetInput = true]) {\n    super.reset(resetInput);\n    overrideDecisionReached = false;\n    overrideDecisionRoot = null;\n  }\n\n  @override\n  ATN getATN() {\n    return atn;\n  }\n\n  /// Begin parsing at startRuleIndex */\n  ParserRuleContext parse(int startRuleIndex) {\n    final startRuleStartState = atn.ruleToStartState[startRuleIndex];\n\n    rootContext = createInterpreterRuleContext(\n      null,\n      ATNState.INVALID_STATE_NUMBER,\n      startRuleIndex,\n    );\n    if (startRuleStartState.isLeftRecursiveRule) {\n      enterRecursionRule(\n          rootContext, startRuleStartState.stateNumber, startRuleIndex, 0);\n    } else {\n      enterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex);\n    }\n\n    while (true) {\n      final p = atnState;\n      switch (p.stateType) {\n        case StateType.RULE_STOP:\n          // pop; return from rule\n          if (context!.isEmpty) {\n            if (startRuleStartState.isLeftRecursiveRule) {\n              final result = context!;\n              final parentContext = _parentContextStack.removeLast();\n              unrollRecursionContexts(parentContext.a);\n              return result;\n            } else {\n              exitRule();\n              return rootContext;\n            }\n          }\n\n          visitRuleStopState(p);\n          break;\n\n        default:\n          try {\n            visitState(p);\n          } on RecognitionException catch (e) {\n            state = atn.ruleToStopState[p.ruleIndex].stateNumber;\n            context!.exception = e;\n            errorHandler.reportError(this, e);\n            recover(e);\n          }\n\n          break;\n      }\n    }\n  }\n\n  @override\n  void enterRecursionRule(\n    ParserRuleContext localctx,\n    int state,\n    int ruleIndex,\n    int precedence,\n  ) {\n    final pair = Pair<ParserRuleContext?, int>(context, localctx.invokingState);\n    _parentContextStack.add(pair);\n    super.enterRecursionRule(localctx, state, ruleIndex, precedence);\n  }\n\n  ATNState get atnState {\n    return atn.states[state]!;\n  }\n\n  void visitState(ATNState p) {\n    assert(context != null);\n//\t\tSystem.out.println(\"visitState \"+p.stateNumber);\n    var predictedAlt = 1;\n    if (p is DecisionState) {\n      predictedAlt = visitDecisionState(p);\n    }\n\n    final transition = p.transition(predictedAlt - 1);\n    switch (transition.type) {\n      case TransitionType.EPSILON:\n        if (p.stateType == StateType.STAR_LOOP_ENTRY &&\n            (p as StarLoopEntryState).isPrecedenceDecision &&\n            (transition.target is! LoopEndState)) {\n          // We are at the start of a left recursive rule's (...)* loop\n          // and we're not taking the exit branch of loop.\n          final localctx = createInterpreterRuleContext(\n            _parentContextStack.last.a,\n            _parentContextStack.last.b,\n            context!.ruleIndex,\n          );\n          pushNewRecursionContext(\n            localctx,\n            atn.ruleToStartState[p.ruleIndex].stateNumber,\n            context!.ruleIndex,\n          );\n        }\n        break;\n\n      case TransitionType.ATOM:\n        match((transition as AtomTransition).atomLabel);\n        break;\n\n      case TransitionType.RANGE:\n      case TransitionType.SET:\n      case TransitionType.NOT_SET:\n        if (!transition.matches(\n          inputStream.LA(1)!,\n          Token.MIN_USER_TOKEN_TYPE,\n          65535,\n        )) {\n          recoverInline();\n        }\n        matchWildcard();\n        break;\n\n      case TransitionType.WILDCARD:\n        matchWildcard();\n        break;\n\n      case TransitionType.RULE:\n        final ruleStartState = transition.target as RuleStartState;\n        final ruleIndex = ruleStartState.ruleIndex;\n        final newctx =\n            createInterpreterRuleContext(context, p.stateNumber, ruleIndex);\n        if (ruleStartState.isLeftRecursiveRule) {\n          enterRecursionRule(newctx, ruleStartState.stateNumber, ruleIndex,\n              (transition as RuleTransition).precedence);\n        } else {\n          enterRule(newctx, transition.target.stateNumber, ruleIndex);\n        }\n        break;\n\n      case TransitionType.PREDICATE:\n        final predicateTransition = transition as PredicateTransition;\n        if (!sempred(context, predicateTransition.ruleIndex,\n            predicateTransition.predIndex)) {\n          throw FailedPredicateException(this);\n        }\n\n        break;\n\n      case TransitionType.ACTION:\n        final actionTransition = transition as ActionTransition;\n        action(\n          context,\n          actionTransition.ruleIndex,\n          actionTransition.actionIndex,\n        );\n        break;\n\n      case TransitionType.PRECEDENCE:\n        if (!precpred(\n          context,\n          (transition as PrecedencePredicateTransition).precedence,\n        )) {\n          throw FailedPredicateException(\n              this, 'precpred(context, ${(transition).precedence})');\n        }\n        break;\n\n      default:\n        throw UnsupportedError('Unrecognized ATN transition type.');\n    }\n\n    state = transition.target.stateNumber;\n  }\n\n  /// Method visitDecisionState() is called when the interpreter reaches\n  ///  a decision state (instance of DecisionState). It gives an opportunity\n  ///  for subclasses to track interesting things.\n  int visitDecisionState(DecisionState p) {\n    var predictedAlt = 1;\n    assert(context != null);\n    if (p.numberOfTransitions > 1) {\n      errorHandler.sync(this);\n      final decision = p.decision;\n      if (decision == overrideDecision &&\n          inputStream.index == overrideDecisionInputIndex &&\n          !overrideDecisionReached) {\n        predictedAlt = overrideDecisionAlt;\n        overrideDecisionReached = true;\n      } else {\n        predictedAlt = interpreter!.adaptivePredict(\n          inputStream,\n          decision,\n          context!,\n        );\n      }\n    }\n    return predictedAlt;\n  }\n\n  /// Provide simple \"factory\" for InterpreterRuleContext's.\n  ///  @since 4.5.1\n  InterpreterRuleContext createInterpreterRuleContext(\n    ParserRuleContext? parent,\n    int invokingStateNumber,\n    int ruleIndex,\n  ) {\n    return InterpreterRuleContext(parent, invokingStateNumber, ruleIndex);\n  }\n\n  void visitRuleStopState(ATNState p) {\n    final ruleStartState = atn.ruleToStartState[p.ruleIndex];\n    if (ruleStartState.isLeftRecursiveRule) {\n      final parentContext = _parentContextStack.removeLast();\n      unrollRecursionContexts(parentContext.a);\n      state = parentContext.b;\n    } else {\n      exitRule();\n    }\n\n    final ruleTransition = atn.states[state]!.transition(0) as RuleTransition;\n    state = ruleTransition.followState.stateNumber;\n  }\n\n  /// Override this parser interpreters normal decision-making process\n  ///  at a particular decision and input token index. Instead of\n  ///  allowing the adaptive prediction mechanism to choose the\n  ///  first alternative within a block that leads to a successful parse,\n  ///  force it to take the alternative, 1..n for n alternatives.\n  ///\n  ///  As an implementation limitation right now, you can only specify one\n  ///  override. This is sufficient to allow construction of different\n  ///  parse trees for ambiguous input. It means re-parsing the entire input\n  ///  in general because you're never sure where an ambiguous sequence would\n  ///  live in the various parse trees. For example, in one interpretation,\n  ///  an ambiguous input sequence would be matched completely in expression\n  ///  but in another it could match all the way back to the root.\n  ///\n  ///  s : e '!'? ;\n  ///  e : ID\n  ///    | ID '!'\n  ///    ;\n  ///\n  ///  Here, x! can be matched as (s (e ID) !) or (s (e ID !)). In the first\n  ///  case, the ambiguous sequence is fully contained only by the root.\n  ///  In the second case, the ambiguous sequences fully contained within just\n  ///  e, as in: (e ID !).\n  ///\n  ///  Rather than trying to optimize this and make\n  ///  some intelligent decisions for optimization purposes, I settled on\n  ///  just re-parsing the whole input and then using\n  ///  {link Trees#getRootOfSubtreeEnclosingRegion} to find the minimal\n  ///  subtree that contains the ambiguous sequence. I originally tried to\n  ///  record the call stack at the point the parser detected and ambiguity but\n  ///  left recursive rules create a parse tree stack that does not reflect\n  ///  the actual call stack. That impedance mismatch was enough to make\n  ///  it it challenging to restart the parser at a deeply nested rule\n  ///  invocation.\n  ///\n  ///  Only parser interpreters can override decisions so as to avoid inserting\n  ///  override checking code in the critical ALL(*) prediction execution path.\n  ///\n  ///  @since 4.5.1\n  void addDecisionOverride(int decision, int tokenIndex, int forcedAlt) {\n    overrideDecision = decision;\n    overrideDecisionInputIndex = tokenIndex;\n    overrideDecisionAlt = forcedAlt;\n  }\n\n  /// Rely on the error handler for this parser but, if no tokens are consumed\n  ///  to recover, add an error node. Otherwise, nothing is seen in the parse\n  ///  tree.\n  void recover(RecognitionException e) {\n    final i = inputStream.index;\n    errorHandler.recover(this, e);\n    assert(this.context != null);\n    final context = this.context as ParserRuleContext;\n    if (inputStream.index == i) {\n      // no input consumed, better add an error node\n      if (e is InputMismatchException) {\n        final ime = e;\n        final tok = e.offendingToken;\n        var expectedTokenType = Token.INVALID_TYPE;\n        if (ime.expectedTokens != null && !ime.expectedTokens!.isNil) {\n          expectedTokenType = ime.expectedTokens!.minElement; // get any element\n        }\n        final errToken = tokenFactory.create(\n          expectedTokenType,\n          tok.text,\n          Pair(tok.tokenSource, tok.tokenSource?.inputStream),\n          Token.DEFAULT_CHANNEL,\n          -1,\n          -1,\n          // invalid start/stop\n          tok.line,\n          tok.charPositionInLine,\n        );\n        context.addErrorNode(createErrorNode(context, errToken));\n      } else {\n        // NoViableAlt\n        final tok = e.offendingToken;\n        final errToken = tokenFactory.create(\n          Token.INVALID_TYPE,\n          tok.text,\n          Pair(tok.tokenSource, tok.tokenSource?.inputStream),\n          Token.DEFAULT_CHANNEL,\n          -1,\n          -1,\n          // invalid start/stop\n          tok.line,\n          tok.charPositionInLine,\n        );\n        context.addErrorNode(createErrorNode(context, errToken));\n      }\n    }\n  }\n\n  Token recoverInline() {\n    return errorHandler.recoverInline(this);\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/parser_rule_context.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'error/error.dart';\nimport 'interval_set.dart';\nimport 'parser.dart';\nimport 'rule_context.dart';\nimport 'token.dart';\nimport 'tree/tree.dart';\n\n/// A rule invocation record for parsing.\n///\n///  Contains all of the information about the current rule not stored in the\n///  RuleContext. It handles parse tree children list, Any ATN state\n///  tracing, and the default values available for rule invocations:\n///  start, stop, rule index, current alt number.\n///\n///  Subclasses made for each rule and grammar track the parameters,\n///  return values, locals, and labels specific to that rule. These\n///  are the objects that are returned from rules.\n///\n///  Note text is not an actual field of a rule return value; it is computed\n///  from start and stop using the input stream's toString() method.  I\n///  could add a ctor to this so that we can pass in and store the input\n///  stream, but I'm not sure we want to do that.  It would seem to be undefined\n///  to get the .text property anyway if the rule matches tokens from multiple\n///  input streams.\n///\n///  I do not use getters for fields of objects that are used simply to\n///  group values such as this aggregate.  The getters/setters are there to\n///  satisfy the superclass interface.\nclass ParserRuleContext extends RuleContext {\n  /// If we are debugging or building a parse tree for a visitor,\n  ///  we need to track all of the tokens and rule invocations associated\n  ///  with this rule's context. This is empty for parsing w/o tree constr.\n  ///  operation because we don't the need to track the details about\n  ///  how we parse this rule.\n  List<ParseTree>? children;\n\n  /// Get the initial/final token in this context.\n  /// Note that the range from start to stop is inclusive, so for rules that do not consume anything\n  /// (for example, zero length or error productions) this token may exceed stop.\n  Token? start, stop;\n\n  /// The exception that forced this rule to return. If the rule successfully\n  /// completed, this is null.\n  RecognitionException? exception;\n\n  ParserRuleContext([RuleContext? parent, int? invokingStateNumber])\n      : super(parent: parent, invokingState: invokingStateNumber);\n\n  /// COPY a ctx (I'm deliberately not using copy constructor) to avoid\n  ///  confusion with creating node with parent. Does not copy children\n  ///  (except error leaves).\n  ///\n  ///  This is used in the generated parser code to flip a generic XContext\n  ///  node for rule X to a YContext for alt label Y. In that sense, it is\n  ///  not really a generic copy function.\n  ///\n  ///  If we do an error sync() at start of a rule, we might add error nodes\n  ///  to the generic XContext so this function must copy those nodes to\n  ///  the YContext as well else they are lost!\n  void copyFrom(ParserRuleContext ctx) {\n    parent = ctx.parent;\n    invokingState = ctx.invokingState;\n\n    start = ctx.start;\n    stop = ctx.stop;\n\n    // copy any error nodes to alt label node\n    if (ctx.children != null) {\n      children = [];\n      // reset parent pointer for any error nodes\n      for (var child in ctx.children!) {\n        if (child is ErrorNode) {\n          addChild(child);\n        }\n      }\n    }\n  }\n\n  // Double dispatch methods for listeners\n\n  void enterRule(ParseTreeListener listener) {}\n\n  void exitRule(ParseTreeListener listener) {}\n\n  /// Add a parse tree node to this as a child.  Works for\n  ///  internal and leaf nodes. Does not set parent link;\n  ///  other add methods must do that. Other addChild methods\n  ///  call this.\n  ///\n  ///  We cannot set the parent pointer of the incoming node\n  ///  because the existing interfaces do not have a setParent()\n  ///  method and I don't want to break backward compatibility for this.\n  ///\n  ///  @since 4.7\n  T addAnyChild<T extends ParseTree>(T t) {\n    children ??= [];\n    children!.add(t);\n    return t;\n  }\n\n  /// Add a token leaf node child and force its parent to be this node. */\n  TerminalNode addChild(TerminalNode t) {\n    t.parent = this;\n    return addAnyChild(t);\n  }\n\n  /// Add an error node child and force its parent to be this node.\n  ///\n  /// @since 4.7\n  ErrorNode addErrorNode(ErrorNode errorNode) {\n    errorNode.parent = this;\n    return addAnyChild(errorNode);\n  }\n\n  /// Used by enterOuterAlt to toss out a RuleContext previously added as\n  ///  we entered a rule. If we have # label, we will need to remove\n  ///  generic ruleContext object.\n  void removeLastChild() {\n    if (children != null) {\n      children!.removeLast();\n    }\n  }\n\n  // Override to make type more specific\n  @override\n  ParserRuleContext? get parent {\n    return super.parent as ParserRuleContext?;\n  }\n\n  @override\n  ParseTree? getChild<T>(int i) {\n    if (children == null || i < 0 || i >= children!.length) {\n      return null;\n    }\n    if (T == dynamic) {\n      return children![i];\n    }\n    var j = -1; // what element have we found with ctxType?\n    for (var o in children!) {\n      if (o is T) {\n        j++;\n        if (j == i) {\n          return o;\n        }\n      }\n    }\n    return null;\n  }\n\n  TerminalNode? getToken(int ttype, int i) {\n    if (children == null || i < 0 || i >= children!.length) {\n      return null;\n    }\n\n    var j = -1; // what token with ttype have we found?\n    for (var o in children!) {\n      if (o is TerminalNode) {\n        final tnode = o;\n        final symbol = tnode.symbol;\n        if (symbol.type == ttype) {\n          j++;\n          if (j == i) {\n            return tnode;\n          }\n        }\n      }\n    }\n\n    return null;\n  }\n\n  List<TerminalNode> getTokens(int ttype) {\n    if (children == null) {\n      return [];\n    }\n\n    var tokens = <TerminalNode>[];\n    for (var o in children!) {\n      if (o is TerminalNode) {\n        final tnode = o;\n        final symbol = tnode.symbol;\n        if (symbol.type == ttype) {\n          tokens.add(tnode);\n        }\n      }\n    }\n\n    return tokens;\n  }\n\n  T? getRuleContext<T extends ParserRuleContext>(int i) {\n    return getChild<T>(i) as T?;\n  }\n\n  List<T> getRuleContexts<T extends ParserRuleContext>() {\n    if (children == null) {\n      return [];\n    }\n\n    var contexts = <T>[];\n    for (var o in children!) {\n      if (o is T) {\n        contexts.add(o);\n      }\n    }\n\n    return contexts;\n  }\n\n  @override\n  int get childCount => children?.length ?? 0;\n\n  @override\n  Interval get sourceInterval {\n    if (stop == null || stop!.tokenIndex < start!.tokenIndex) {\n      return Interval(start!.tokenIndex, start!.tokenIndex - 1); // empty\n    }\n    return Interval(start!.tokenIndex, stop!.tokenIndex);\n  }\n\n  /// Used for rule context info debugging during parse-time, not so much for ATN debugging */\n  String toInfoString(Parser recognizer) {\n    final rules = recognizer.getRuleInvocationStack(this);\n\n    return \"ParserRuleContext${rules.reversed}{start=$start, stop=$stop}'\";\n  }\n\n  static final EMPTY = ParserRuleContext();\n}\n\n/// This class extends [ParserRuleContext] by allowing the value of\n/// {@link #getRuleIndex} to be explicitly set for the context.\n///\n/// <p>\n/// [ParserRuleContext] does not include field storage for the rule index\n/// since the context classes created by the code generator override the\n/// {@link #getRuleIndex} method to return the correct value for that context.\n/// Since the parser interpreter does not use the context classes generated for a\n/// parser, this class (with slightly more memory overhead per node) is used to\n/// provide equivalent functionality.</p>\nclass InterpreterRuleContext extends ParserRuleContext {\n  @override\n  int ruleIndex = -1;\n\n  /// Constructs a new [InterpreterRuleContext] with the specified\n  /// parent, invoking state, and rule index.\n  ///\n  /// @param parent The parent context.\n  /// @param invokingStateNumber The invoking state number.\n  /// @param ruleIndex The rule index for the current context.\n  InterpreterRuleContext(\n    ParserRuleContext? parent,\n    int invokingStateNumber,\n    this.ruleIndex,\n  ) : super(parent, invokingStateNumber);\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/prediction_context.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'package:collection/collection.dart';\n\nimport 'atn/atn.dart';\nimport 'misc/misc.dart';\nimport 'recognizer.dart';\nimport 'rule_context.dart';\nimport 'util/murmur_hash.dart';\n\nabstract class PredictionContext {\n  /// Represents {@code $} in an array in full context mode, when {@code $}\n  /// doesn't mean wildcard: {@code $ + x = [$,x]}. Here,\n  /// {@code $} = {@link #EMPTY_RETURN_STATE}.\n  static final int EMPTY_RETURN_STATE = 0x7FFFFFFF;\n\n  static final int INITIAL_HASH = 1;\n\n  static int globalNodeCount = 0;\n  int id = globalNodeCount++;\n\n  /// Stores the computed hash code of this [PredictionContext]. The hash\n  /// code is computed in parts to match the following reference algorithm.\n  ///\n  /// <pre>\n  ///   int referenceHashCode() {\n  ///      int hash = {@link MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH});\n  ///\n  ///      for (int i = 0; i &lt; {@link #size()}; i++) {\n  ///          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i));\n  ///      }\n  ///\n  ///      for (int i = 0; i &lt; {@link #size()}; i++) {\n  ///          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getReturnState getReturnState}(i));\n  ///      }\n  ///\n  ///      hash = {@link MurmurHash#finish MurmurHash.finish}(hash, 2 * {@link #size()});\n  ///      return hash;\n  ///  }\n  /// </pre>\n  final int cachedHashCode;\n\n  PredictionContext(this.cachedHashCode);\n\n  /// Convert a [RuleContext] tree to a [PredictionContext] graph.\n  ///  Return {@link #EMPTY} if [outerContext] is empty or null.\n  static PredictionContext fromRuleContext(ATN atn, RuleContext? outerContext) {\n    outerContext ??= RuleContext.EMPTY;\n\n    // if we are in RuleContext of start rule, s, then PredictionContext\n    // is EMPTY. Nobody called us. (if we are empty, return empty)\n    if (outerContext.parent == null || outerContext == RuleContext.EMPTY) {\n      return EmptyPredictionContext.Instance;\n    }\n\n    // If we have a parent, convert it to a PredictionContext graph\n    PredictionContext parent = EmptyPredictionContext.Instance;\n    parent = PredictionContext.fromRuleContext(atn, outerContext.parent);\n\n    final state = atn.states[outerContext.invokingState]!;\n    final transition = state.transition(0) as RuleTransition;\n    return SingletonPredictionContext.create(\n      parent,\n      transition.followState.stateNumber,\n    );\n  }\n\n  int get length;\n\n  PredictionContext? getParent(int index);\n\n  int getReturnState(int index);\n\n  /// This means only the {@link #EMPTY} (wildcard? not sure) context is in set. */\n  bool get isEmpty {\n    return this == EmptyPredictionContext.Instance;\n  }\n\n  bool hasEmptyPath() {\n    // since EMPTY_RETURN_STATE can only appear in the last position, we check last one\n    return getReturnState(length - 1) == EMPTY_RETURN_STATE;\n  }\n\n  @override\n  int get hashCode {\n    return cachedHashCode;\n  }\n\n  @override\n  bool operator ==(Object obj);\n\n  static int calculateEmptyHashCode() {\n    var hash = MurmurHash.initialize(INITIAL_HASH);\n    hash = MurmurHash.finish(hash, 0);\n    return hash;\n  }\n\n  static int calculateHashCode(\n      List<PredictionContext?> parents, List<int> returnStates) {\n    var hash = MurmurHash.initialize(INITIAL_HASH);\n\n    for (var parent in parents) {\n      hash = MurmurHash.update(hash, parent);\n    }\n\n    for (var returnState in returnStates) {\n      hash = MurmurHash.update(hash, returnState);\n    }\n\n    hash = MurmurHash.finish(hash, 2 * parents.length);\n    return hash;\n  }\n\n  // dispatch\n  static PredictionContext merge(\n    PredictionContext a,\n    PredictionContext b,\n    bool rootIsWildcard,\n    Map<Pair<PredictionContext, PredictionContext>, PredictionContext>?\n        mergeCache,\n  ) {\n    // share same graph if both same\n    if (a == b || a == b) return a;\n\n    if (a is SingletonPredictionContext && b is SingletonPredictionContext) {\n      return mergeSingletons(a, b, rootIsWildcard, mergeCache);\n    }\n\n    // At least one of a or b is array\n    // If one is $ and rootIsWildcard, return $ as * wildcard\n    if (rootIsWildcard) {\n      if (a is EmptyPredictionContext) return a;\n      if (b is EmptyPredictionContext) return b;\n    }\n\n    // convert singleton so both are arrays to normalize\n    if (a is SingletonPredictionContext) {\n      a = ArrayPredictionContext.of(a);\n    }\n    if (b is SingletonPredictionContext) {\n      b = ArrayPredictionContext.of(b);\n    }\n    return mergeArrays(\n      a as ArrayPredictionContext,\n      b as ArrayPredictionContext,\n      rootIsWildcard,\n      mergeCache,\n    );\n  }\n\n  /// Merge two [SingletonPredictionContext] instances.\n  ///\n  /// <p>Stack tops equal, parents merge is same; return left graph.<br>\n  /// <embed src=\"images/SingletonMerge_SameRootSamePar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Same stack top, parents differ; merge parents giving array node, then\n  /// remainders of those graphs. A new root node is created to point to the\n  /// merged parents.<br>\n  /// <embed src=\"images/SingletonMerge_SameRootDiffPar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Different stack tops pointing to same parent. Make array node for the\n  /// root where both element in the root point to the same (original)\n  /// parent.<br>\n  /// <embed src=\"images/SingletonMerge_DiffRootSamePar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Different stack tops pointing to different parents. Make array node for\n  /// the root where each element points to the corresponding original\n  /// parent.<br>\n  /// <embed src=\"images/SingletonMerge_DiffRootDiffPar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// @param a the first [SingletonPredictionContext]\n  /// @param b the second [SingletonPredictionContext]\n  /// @param rootIsWildcard [true] if this is a local-context merge,\n  /// otherwise false to indicate a full-context merge\n  /// @param mergeCache\n  static PredictionContext mergeSingletons(\n    SingletonPredictionContext a,\n    SingletonPredictionContext b,\n    bool rootIsWildcard,\n    Map<Pair<PredictionContext, PredictionContext>, PredictionContext>?\n        mergeCache,\n  ) {\n    if (mergeCache != null) {\n      var previous = mergeCache[Pair(a, b)];\n      if (previous != null) return previous;\n      previous = mergeCache[Pair(b, a)];\n      if (previous != null) return previous;\n    }\n\n    final rootMerge = mergeRoot(a, b, rootIsWildcard);\n    if (rootMerge != null) {\n      if (mergeCache != null) mergeCache[Pair(a, b)] = rootMerge;\n      return rootMerge;\n    }\n\n    if (a.returnState == b.returnState) {\n      assert(a.parent != null &&\n          b.parent != null); // must be empty context, never null\n\n      // a == b\n      final parent = merge(a.parent!, b.parent!, rootIsWildcard, mergeCache);\n      // if parent is same as existing a or b parent or reduced to a parent, return it\n      if (parent == a.parent) return a; // ax + bx = ax, if a=b\n      if (parent == b.parent) return b; // ax + bx = bx, if a=b\n      // else: ax + ay = a'[x,y]\n      // merge parents x and y, giving array node with x,y then remainders\n      // of those graphs.  dup a, a' points at merged array\n      // new joined parent so create new singleton pointing to it, a'\n      PredictionContext a_ =\n          SingletonPredictionContext.create(parent, a.returnState);\n      if (mergeCache != null) mergeCache[Pair(a, b)] = a_;\n      return a_;\n    } else {\n      // a != b payloads differ\n      // see if we can collapse parents due to $+x parents if local ctx\n      PredictionContext? singleParent;\n      if (a == b || (a.parent != null && a.parent == b.parent)) {\n        // ax + bx = [a,b]x\n        singleParent = a.parent;\n      }\n      if (singleParent != null) {\n        // parents are same\n        // sort payloads and use same parent\n        final payloads = <int>[a.returnState, b.returnState];\n        if (a.returnState > b.returnState) {\n          payloads[0] = b.returnState;\n          payloads[1] = a.returnState;\n        }\n        final parents = <PredictionContext>[singleParent, singleParent];\n        PredictionContext a_ = ArrayPredictionContext(parents, payloads);\n        if (mergeCache != null) mergeCache[Pair(a, b)] = a_;\n        return a_;\n      }\n      // parents differ and can't merge them. Just pack together\n      // into array; can't merge.\n      // ax + by = [ax,by]\n      final payloads = <int>[a.returnState, b.returnState];\n      var parents = <PredictionContext?>[a.parent, b.parent];\n      if (a.returnState > b.returnState) {\n        // sort by payload\n        payloads[0] = b.returnState;\n        payloads[1] = a.returnState;\n        parents = [b.parent, a.parent];\n      }\n      PredictionContext a_ = ArrayPredictionContext(parents, payloads);\n      if (mergeCache != null) mergeCache[Pair(a, b)] = a_;\n      return a_;\n    }\n  }\n\n  /// Handle case where at least one of [a] or [b] is\n  /// {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used\n  /// to represent {@link #EMPTY}.\n  ///\n  /// <h2>Local-Context Merges</h2>\n  ///\n  /// <p>These local-context merge operations are used when [rootIsWildcard]\n  /// is true.</p>\n  ///\n  /// <p>{@link #EMPTY} is superset of any graph; return {@link #EMPTY}.<br>\n  /// <embed src=\"images/LocalMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>{@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is\n  /// {@code #EMPTY}; return left graph.<br>\n  /// <embed src=\"images/LocalMerge_EmptyParent.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Special case of last merge if local context.<br>\n  /// <embed src=\"images/LocalMerge_DiffRoots.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <h2>Full-Context Merges</h2>\n  ///\n  /// <p>These full-context merge operations are used when [rootIsWildcard]\n  /// is false.</p>\n  ///\n  /// <p><embed src=\"images/FullMerge_EmptyRoots.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Must keep all contexts; {@link #EMPTY} in array is a special value (and\n  /// null parent).<br>\n  /// <embed src=\"images/FullMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p><embed src=\"images/FullMerge_SameRoot.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// @param a the first [SingletonPredictionContext]\n  /// @param b the second [SingletonPredictionContext]\n  /// @param rootIsWildcard [true] if this is a local-context merge,\n  /// otherwise false to indicate a full-context merge\n  static PredictionContext? mergeRoot(\n    SingletonPredictionContext a,\n    SingletonPredictionContext b,\n    bool rootIsWildcard,\n  ) {\n    if (rootIsWildcard) {\n      if (a == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance; // * + b = *\n      if (b == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance; // a + * = *\n    } else {\n      if (a == EmptyPredictionContext.Instance && b == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance; // $ + $ = $\n      if (a == EmptyPredictionContext.Instance) {\n        // $ + x = [x,$]\n        final payloads = <int>[b.returnState, EMPTY_RETURN_STATE];\n        final parents = <PredictionContext?>[b.parent, null];\n        PredictionContext joined = ArrayPredictionContext(parents, payloads);\n        return joined;\n      }\n      if (b == EmptyPredictionContext.Instance) {\n        // x + $ = [x,$] ($ is always last if present)\n        final payloads = <int>[a.returnState, EMPTY_RETURN_STATE];\n        final parents = [a.parent, null];\n        PredictionContext joined = ArrayPredictionContext(parents, payloads);\n        return joined;\n      }\n    }\n    return null;\n  }\n\n  /// Merge two [ArrayPredictionContext] instances.\n  ///\n  /// <p>Different tops, different parents.<br>\n  /// <embed src=\"images/ArrayMerge_DiffTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Shared top, same parents.<br>\n  /// <embed src=\"images/ArrayMerge_ShareTopSamePar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Shared top, different parents.<br>\n  /// <embed src=\"images/ArrayMerge_ShareTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Shared top, all shared parents.<br>\n  /// <embed src=\"images/ArrayMerge_ShareTopSharePar.svg\" type=\"image/svg+xml\"/></p>\n  ///\n  /// <p>Equal tops, merge parents and reduce top to\n  /// [SingletonPredictionContext].<br>\n  /// <embed src=\"images/ArrayMerge_EqualTop.svg\" type=\"image/svg+xml\"/></p>\n  static PredictionContext mergeArrays(\n    ArrayPredictionContext a,\n    ArrayPredictionContext b,\n    bool rootIsWildcard,\n    Map<Pair<PredictionContext, PredictionContext>, PredictionContext>?\n        mergeCache,\n  ) {\n    if (mergeCache != null) {\n      var previous = mergeCache[Pair(a, b)];\n      if (previous != null) return previous;\n      previous = mergeCache[Pair(b, a)];\n      if (previous != null) return previous;\n    }\n\n    // merge sorted payloads a + b => M\n    var i = 0; // walks a\n    var j = 0; // walks b\n    var k = 0; // walks target M array\n\n    var mergedReturnStates = List<int>.filled(\n      a.returnStates.length + b.returnStates.length,\n      0,\n    ); // TODO Will it grow?\n    var mergedParents = List<PredictionContext?>.filled(\n      a.returnStates.length + b.returnStates.length,\n      null,\n    ); // TODO Will it grow?\n    // walk and merge to yield mergedParents, mergedReturnStates\n    while (i < a.returnStates.length && j < b.returnStates.length) {\n      final a_parent = a.parents[i];\n      final b_parent = b.parents[j];\n      if (a.returnStates[i] == b.returnStates[j]) {\n        // same payload (stack tops are equal), must yield merged singleton\n        final payload = a.returnStates[i];\n        // $+$ = $\n        final both$ = payload == EMPTY_RETURN_STATE &&\n            a_parent == null &&\n            b_parent == null;\n        final ax_ax = (a_parent != null && b_parent != null) &&\n            a_parent == b_parent; // ax+ax -> ax\n        if (both$ || ax_ax) {\n          mergedParents[k] = a_parent; // choose left\n          mergedReturnStates[k] = payload;\n        } else {\n          // ax+ay -> a'[x,y]\n          final mergedParent =\n              merge(a_parent!, b_parent!, rootIsWildcard, mergeCache);\n          mergedParents[k] = mergedParent;\n          mergedReturnStates[k] = payload;\n        }\n        i++; // hop over left one as usual\n        j++; // but also skip one in right side since we merge\n      } else if (a.returnStates[i] < b.returnStates[j]) {\n        // copy a[i] to M\n        mergedParents[k] = a_parent;\n        mergedReturnStates[k] = a.returnStates[i];\n        i++;\n      } else {\n        // b > a, copy b[j] to M\n        mergedParents[k] = b_parent;\n        mergedReturnStates[k] = b.returnStates[j];\n        j++;\n      }\n      k++;\n    }\n\n    // copy over any payloads remaining in either array\n    if (i < a.returnStates.length) {\n      for (var p = i; p < a.returnStates.length; p++) {\n        mergedParents[k] = a.parents[p];\n        mergedReturnStates[k] = a.returnStates[p];\n        k++;\n      }\n    } else {\n      for (var p = j; p < b.returnStates.length; p++) {\n        mergedParents[k] = b.parents[p];\n        mergedReturnStates[k] = b.returnStates[p];\n        k++;\n      }\n    }\n\n    // trim merged if we combined a few that had same stack tops\n    if (k < mergedParents.length) {\n      // write index < last position; trim\n      if (k == 1) {\n        // for just one merged element, return singleton top\n        PredictionContext a_ = SingletonPredictionContext.create(\n          mergedParents[0]!,\n          mergedReturnStates[0],\n        );\n        if (mergeCache != null) mergeCache[Pair(a, b)] = a_;\n        return a_;\n      }\n\n      mergedParents = List.generate(k, (n) => mergedParents[n]);\n      mergedReturnStates = List.generate(k, (n) => mergedReturnStates[n]);\n    }\n\n    PredictionContext M = ArrayPredictionContext(\n      mergedParents,\n      mergedReturnStates,\n    );\n\n    // if we created same array as a or b, return that instead\n    // TODO: track whether this is possible above during merge sort for speed\n    if (M == a) {\n      if (mergeCache != null) mergeCache[Pair(a, b)] = a;\n      return a;\n    }\n    if (M == b) {\n      if (mergeCache != null) mergeCache[Pair(a, b)] = b;\n      return b;\n    }\n\n    combineCommonParents(mergedParents);\n\n    if (mergeCache != null) mergeCache[Pair(a, b)] = M;\n    return M;\n  }\n\n  /// Make pass over all <em>M</em> [parents]; merge any {@code equals()}\n  /// ones.\n  static void combineCommonParents(List<PredictionContext?> parents) {\n    final uniqueParents = <PredictionContext, PredictionContext>{};\n\n    for (var p = 0; p < parents.length; p++) {\n      final parent = parents[p];\n      if (parent != null && !uniqueParents.containsKey(parent)) {\n        // don't replace\n        uniqueParents[parent] = parent;\n      }\n    }\n\n    for (var p = 0; p < parents.length; p++) {\n      parents[p] = uniqueParents[parents[p]]!;\n    }\n  }\n\n  static String toDOTString(PredictionContext? context) {\n    if (context == null) return '';\n    final buf = StringBuffer();\n    buf.write('digraph G {\\n');\n    buf.write('rankdir=LR;\\n');\n\n    final nodes = getAllContextNodes(context);\n    nodes.sort((PredictionContext o1, PredictionContext o2) {\n      return o1.id - o2.id;\n    });\n\n    for (var current in nodes) {\n      if (current is SingletonPredictionContext) {\n        final s = current.id.toString();\n        buf.write('  s');\n        buf.write(s);\n        var returnState = current.getReturnState(0).toString();\n        if (current is EmptyPredictionContext) returnState = r'$';\n        buf.write(' [label=\\\"');\n        buf.write(returnState);\n        buf.write('\\\"];\\n');\n        continue;\n      }\n      final arr = current as ArrayPredictionContext;\n      buf.write('  s');\n      buf.write(arr.id);\n      buf.write(' [shape=box, label=\\\"');\n      buf.write('[');\n      var first = true;\n      for (var inv in arr.returnStates) {\n        if (!first) buf.write(', ');\n        if (inv == EMPTY_RETURN_STATE) {\n          buf.write(r'$');\n        } else {\n          buf.write(inv);\n        }\n        first = false;\n      }\n      buf.write(']');\n      buf.write('\\\"];\\n');\n    }\n\n    for (var current in nodes) {\n      if (current == EmptyPredictionContext.Instance) continue;\n      for (var i = 0; i < current.length; i++) {\n        if (current.getParent(i) == null) continue;\n        final s = current.id.toString();\n        buf.write('  s');\n        buf.write(s);\n        buf.write('->');\n        buf.write('s');\n        buf.write(current.getParent(i)?.id);\n        if (current.length > 1) {\n          buf.write(' [label=\\\"parent[$i]\\\"];\\n');\n        } else {\n          buf.write(';\\n');\n        }\n      }\n    }\n\n    buf.write('}\\n');\n    return buf.toString();\n  }\n\n  // From Sam\n  static PredictionContext getCachedContext(\n    PredictionContext context,\n    PredictionContextCache contextCache,\n    Map<PredictionContext, PredictionContext> visited,\n  ) {\n    if (context.isEmpty) {\n      return context;\n    }\n\n    var existing = visited[context];\n    if (existing != null) {\n      return existing;\n    }\n\n    existing = contextCache[context];\n    if (existing != null) {\n      visited[context] = existing;\n      return existing;\n    }\n\n    var changed = false;\n    var parents = <PredictionContext>[];\n    for (var i = 0; i < parents.length; i++) {\n      final parent = getCachedContext(\n        context.getParent(i)!,\n        contextCache,\n        visited,\n      );\n      if (changed || parent != context.getParent(i)) {\n        if (!changed) {\n          parents = <PredictionContext>[];\n          for (var j = 0; j < context.length; j++) {\n            parents.add(context.getParent(j)!);\n          }\n\n          changed = true;\n        }\n\n        parents[i] = parent;\n      }\n    }\n\n    if (!changed) {\n      contextCache.add(context);\n      visited[context] = context;\n      return context;\n    }\n\n    PredictionContext updated;\n    if (parents.isEmpty) {\n      updated = EmptyPredictionContext.Instance;\n    } else if (parents.length == 1) {\n      updated = SingletonPredictionContext.create(\n          parents[0], context.getReturnState(0));\n    } else {\n      final arrayPredictionContext = context as ArrayPredictionContext;\n      updated = ArrayPredictionContext(\n        parents,\n        arrayPredictionContext.returnStates,\n      );\n    }\n\n    contextCache.add(updated);\n    visited[updated] = updated;\n    visited[context] = updated;\n\n    return updated;\n  }\n\n//\t// extra structures, but cut/paste/morphed works, so leave it.\n//\t// seems to do a breadth-first walk\n//\t static List<PredictionContext> getAllNodes(PredictionContext context) {\n//\t\tMap<PredictionContext, PredictionContext> visited =\n//\t\t\tnew IdentityHashMap<PredictionContext, PredictionContext>();\n//\t\tDeque<PredictionContext> workList = new ArrayDeque<PredictionContext>();\n//\t\tworkList.add(context);\n//\t\tvisited.put(context, context);\n//\t\tList<PredictionContext> nodes = new ArrayList<PredictionContext>();\n//\t\twhile (!workList.isEmpty) {\n//\t\t\tPredictionContext current = workList.pop();\n//\t\t\tnodes.add(current);\n//\t\t\tfor (int i = 0; i < current.length; i++) {\n//\t\t\t\tPredictionContext parent = current.getParent(i);\n//\t\t\t\tif ( parent!=null && visited.put(parent, parent) == null) {\n//\t\t\t\t\tworkList.push(parent);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\treturn nodes;\n//\t}\n\n  // ter's recursive version of Sam's getAllNodes()\n  static List<PredictionContext> getAllContextNodes(PredictionContext context) {\n    final nodes = <PredictionContext>[];\n    final visited = <PredictionContext, PredictionContext>{};\n    getAllContextNodes_(context, nodes, visited);\n    return nodes;\n  }\n\n  static void getAllContextNodes_(\n    PredictionContext? context,\n    List<PredictionContext> nodes,\n    Map<PredictionContext, PredictionContext> visited,\n  ) {\n    if (context == null || visited.containsKey(context)) return;\n    visited[context] = context;\n    nodes.add(context);\n    for (var i = 0; i < context.length; i++) {\n      getAllContextNodes_(context.getParent(i), nodes, visited);\n    }\n  }\n\n  // FROM SAM\n  List<String> toStrings(\n    Recognizer? recognizer,\n    PredictionContext stop,\n    int currentState,\n  ) {\n    final result = <String>[];\n\n    outer:\n    for (var perm = 0;; perm++) {\n      var offset = 0;\n      var last = true;\n      var p = this;\n      var stateNumber = currentState;\n      final localBuffer = StringBuffer();\n      localBuffer.write('[');\n      while (!p.isEmpty && p != stop) {\n        var index = 0;\n        if (p.length > 0) {\n          var bits = 1;\n          while ((1 << bits) < p.length) {\n            bits++;\n          }\n\n          final mask = (1 << bits) - 1;\n          index = (perm >> offset) & mask;\n          last &= index >= p.length - 1;\n          if (index >= p.length) {\n            continue outer;\n          }\n          offset += bits;\n        }\n\n        if (recognizer != null) {\n          if (localBuffer.length > 1) {\n            // first char is '[', if more than that this isn't the first rule\n            localBuffer.write(' ');\n          }\n\n          final atn = recognizer.getATN();\n          final s = atn.states[stateNumber]!;\n          final ruleName = recognizer.ruleNames[s.ruleIndex];\n          localBuffer.write(ruleName);\n        } else if (p.getReturnState(index) != EMPTY_RETURN_STATE) {\n          if (!p.isEmpty) {\n            if (localBuffer.length > 1) {\n              // first char is '[', if more than that this isn't the first rule\n              localBuffer.write(' ');\n            }\n\n            localBuffer.write(p.getReturnState(index));\n          }\n        }\n        stateNumber = p.getReturnState(index);\n        p = p.getParent(index) ?? EmptyPredictionContext.Instance;\n      }\n      localBuffer.write(']');\n      result.add(localBuffer.toString());\n\n      if (last) {\n        break;\n      }\n    }\n\n    return result;\n  }\n}\n\nclass SingletonPredictionContext extends PredictionContext {\n  final PredictionContext? parent;\n  final int returnState;\n\n  SingletonPredictionContext(this.parent, this.returnState)\n      : super(parent != null\n            ? PredictionContext.calculateHashCode([parent], [returnState])\n            : PredictionContext.calculateEmptyHashCode()) {\n    assert(returnState != ATNState.INVALID_STATE_NUMBER);\n  }\n\n  static SingletonPredictionContext create(\n    PredictionContext? parent,\n    int returnState,\n  ) {\n    if (returnState == PredictionContext.EMPTY_RETURN_STATE && parent == null) {\n      // someone can pass in the bits of an array ctx that mean $\n      return EmptyPredictionContext.Instance;\n    }\n    return SingletonPredictionContext(parent, returnState);\n  }\n\n  @override\n  int get length {\n    return 1;\n  }\n\n  @override\n  PredictionContext? getParent(int index) {\n    assert(index == 0);\n    return parent;\n  }\n\n  @override\n  int getReturnState(int index) {\n    assert(index == 0);\n    return returnState;\n  }\n\n  @override\n  bool operator ==(Object o) {\n    if (identical(this, o)) {\n      return true;\n    } else if (o is SingletonPredictionContext) {\n      if (hashCode != o.hashCode) {\n        return false; // can't be same if hash is different\n      }\n\n      final s = o;\n      return returnState == s.returnState &&\n          (parent != null && parent == s.parent);\n    }\n    return false;\n  }\n\n  @override\n  String toString() {\n    final up = parent != null ? parent.toString() : '';\n    if (up.isEmpty) {\n      if (returnState == PredictionContext.EMPTY_RETURN_STATE) {\n        return r'$';\n      }\n      return returnState.toString();\n    }\n    return '$returnState $up';\n  }\n}\n\nclass EmptyPredictionContext extends SingletonPredictionContext {\n  /// Represents {@code $} in local context prediction, which means wildcard.\n  /// {@code *+x = *}.\n  static final EmptyPredictionContext Instance = EmptyPredictionContext();\n\n  EmptyPredictionContext() : super(null, PredictionContext.EMPTY_RETURN_STATE);\n\n  @override\n  bool get isEmpty {\n    return true;\n  }\n\n  @override\n  int get length {\n    return 1;\n  }\n\n  @override\n  PredictionContext? getParent(int index) {\n    return null;\n  }\n\n  @override\n  int getReturnState(int index) {\n    return returnState;\n  }\n\n  @override\n  String toString() {\n    return r'$';\n  }\n}\n\nclass ArrayPredictionContext extends PredictionContext {\n  /// Parent can be null only if full ctx mode and we make an array\n  ///  from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and\n  ///  returnState == {@link #EMPTY_RETURN_STATE}.\n  List<PredictionContext?> parents;\n\n  /// Sorted for merge, no duplicates; if present,\n  ///  {@link #EMPTY_RETURN_STATE} is always last.\n  List<int> returnStates;\n\n  ArrayPredictionContext.of(SingletonPredictionContext a)\n      : this([a.parent], [a.returnState]);\n\n  ArrayPredictionContext(\n    // Todo: this generic should be null this wont change\n    this.parents,\n    this.returnStates,\n  )   : assert(parents.isNotEmpty),\n        assert(returnStates.isNotEmpty),\n        super(PredictionContext.calculateHashCode(parents, returnStates));\n\n  @override\n  bool get isEmpty {\n    // since EMPTY_RETURN_STATE can only appear in the last position, we\n    // don't need to verify that size==1\n    return returnStates[0] == PredictionContext.EMPTY_RETURN_STATE;\n  }\n\n  @override\n  int get length {\n    return returnStates.length;\n  }\n\n  @override\n  PredictionContext? getParent(int index) {\n    return parents[index];\n  }\n\n  @override\n  int getReturnState(int index) {\n    return returnStates[index];\n  }\n\n//\t int findReturnState(int returnState) {\n//\t\treturn Arrays.binarySearch(returnStates, returnState);\n//\t}\n\n  @override\n  bool operator ==(Object o) {\n    if (identical(this, o)) {\n      return true;\n    } else if (o is ArrayPredictionContext) {\n      if (hashCode != o.hashCode) {\n        return false; // can't be same if hash is different\n      }\n\n      final a = o;\n      return ListEquality().equals(returnStates, a.returnStates) &&\n          ListEquality().equals(parents, a.parents);\n    }\n    return false;\n  }\n\n  @override\n  String toString() {\n    if (isEmpty) return '[]';\n    final buf = StringBuffer();\n    buf.write('[');\n    for (var i = 0; i < returnStates.length; i++) {\n      if (i > 0) buf.write(', ');\n      if (returnStates[i] == PredictionContext.EMPTY_RETURN_STATE) {\n        buf.write(r'$');\n        continue;\n      }\n      buf.write(returnStates[i]);\n      if (parents[i] != null) {\n        buf.write(' ');\n        buf.write(parents[i].toString());\n      } else {\n        buf.write('null');\n      }\n    }\n    buf.write(']');\n    return buf.toString();\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/recognizer.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'vocabulary.dart';\nimport 'atn/atn.dart';\nimport 'error/error.dart';\nimport 'input_stream.dart';\nimport 'rule_context.dart';\nimport 'token.dart';\nimport 'token_factory.dart';\nimport 'util/utils.dart';\n\nabstract class Recognizer<ATNInterpreter extends ATNSimulator> {\n  static const EOF = -1;\n\n  static final Map<Vocabulary, Map<String, int>> tokenTypeMapCache = {};\n  static final Map<List<String>, Map<String, int>> ruleIndexMapCache = {};\n  final List<ErrorListener> _listeners = [ConsoleErrorListener.INSTANCE];\n\n  /// The ATN interpreter used by the recognizer for prediction.\n  ATNInterpreter? interpreter;\n  int state = -1;\n\n  List<String> get ruleNames;\n\n  /// Get the vocabulary used by the recognizer.\n  ///\n  /// @return A [Vocabulary] instance providing information about the\n  /// vocabulary used by the grammar.\n  Vocabulary get vocabulary;\n\n  /// Get a map from token names to token types.\n  ///\n  /// <p>Used for XPath and tree pattern compilation.</p>\n  Map<String, int> get tokenTypeMap {\n    final _vocabulary = vocabulary;\n\n    var result = tokenTypeMapCache[_vocabulary];\n    if (result == null) {\n      result = {};\n      for (var i = 0; i <= getATN().maxTokenType; i++) {\n        final literalName = _vocabulary.getLiteralName(i);\n        if (literalName != null) {\n          result[literalName] = i;\n        }\n\n        final symbolicName = _vocabulary.getSymbolicName(i);\n        if (symbolicName != null) {\n          result[symbolicName] = i;\n        }\n      }\n\n      result['EOF'] = Token.EOF;\n      result = Map.unmodifiable(result);\n      tokenTypeMapCache[_vocabulary] = result;\n    }\n\n    return result;\n  }\n\n  /// Get a map from rule names to rule indexes.\n  ///\n  /// <p>Used for XPath and tree pattern compilation.</p>\n  Map<String, int> get ruleIndexMap {\n    var result = ruleIndexMapCache[ruleNames];\n    if (result == null) {\n      result = Map.unmodifiable(toMap(ruleNames));\n      ruleIndexMapCache[ruleNames] = result;\n    }\n\n    return result;\n  }\n\n  int getTokenType(String tokenName) {\n    final ttype = tokenTypeMap[tokenName];\n    if (ttype != null) return ttype;\n    return Token.INVALID_TYPE;\n  }\n\n  /// If this recognizer was generated, it will have a serialized ATN\n  /// representation of the grammar.\n  ///\n  /// <p>For interpreters, we don't know their serialized ATN despite having\n  /// created the interpreter from it.</p>\n  List<int> get serializedATN {\n    throw UnsupportedError('there is no serialized ATN');\n  }\n\n  /// For debugging and other purposes, might want the grammar name.\n  ///  Have ANTLR generate an implementation for this method.\n  String get grammarFileName;\n\n  /// Get the [ATN] used by the recognizer for prediction.\n  ///\n  /// @return The [ATN] used by the recognizer for prediction.\n  ATN getATN();\n\n  /// If profiling during the parse/lex, this will return DecisionInfo records\n  ///  for each decision in recognizer in a ParseInfo object.\n  ///\n  /// @since 4.3\n  ParseInfo? get parseInfo {\n    return null;\n  }\n\n  /// What is the error header, normally line/character position information? */\n  String getErrorHeader(RecognitionException e) {\n    final line = e.offendingToken.line;\n    final charPositionInLine = e.offendingToken.charPositionInLine;\n    return 'line $line:$charPositionInLine';\n  }\n\n  void addErrorListener(\n    ErrorListener listener,\n  ) {\n    _listeners.add(listener);\n  }\n\n  void removeErrorListener(ErrorListener listener) {\n    _listeners.remove(listener);\n  }\n\n  void removeErrorListeners() {\n    _listeners.clear();\n  }\n\n  List<ErrorListener> get errorListeners {\n    return _listeners;\n  }\n\n  ErrorListener get errorListenerDispatch {\n    return ProxyErrorListener(errorListeners);\n  }\n\n  // subclass needs to override these if there are sempreds or actions\n  // that the ATN interp needs to execute\n  bool sempred(RuleContext? _localctx, int ruleIndex, int actionIndex) {\n    return true;\n  }\n\n  bool precpred(RuleContext? localctx, int precedence) {\n    return true;\n  }\n\n  void action(RuleContext? _localctx, int ruleIndex, int actionIndex) {}\n\n  IntStream get inputStream;\n\n  set inputStream(covariant IntStream input);\n\n  TokenFactory get tokenFactory;\n\n  set tokenFactory(TokenFactory input);\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/rule_context.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'atn/atn.dart';\nimport 'interval_set.dart';\nimport 'parser.dart';\nimport 'parser_rule_context.dart';\nimport 'recognizer.dart';\nimport 'tree/tree.dart';\n\n/// A rule context is a record of a single rule invocation.\n///\n///  We form a stack of these context objects using the parent\n///  pointer. A parent pointer of null indicates that the current\n///  context is the bottom of the stack. The ParserRuleContext subclass\n///  as a children list so that we can turn this data structure into a\n///  tree.\n///\n///  The root node always has a null pointer and invokingState of -1.\n///\n///  Upon entry to parsing, the first invoked rule function creates a\n///  context object (a subclass specialized for that rule such as\n///  SContext) and makes it the root of a parse tree, recorded by field\n///  Parser._ctx.\n///\n///  public final SContext s() throws RecognitionException {\n///      SContext _localctx = new SContext(_ctx, getState()); <-- create new node\n///      enterRule(_localctx, 0, RULE_s);                     <-- push it\n///      ...\n///      exitRule();                                          <-- pop back to _localctx\n///      return _localctx;\n///  }\n///\n///  A subsequent rule invocation of r from the start rule s pushes a\n///  new context object for r whose parent points at s and use invoking\n///  state is the state with r emanating as edge label.\n///\n///  The invokingState fields from a context object to the root\n///  together form a stack of rule indication states where the root\n///  (bottom of the stack) has a -1 sentinel value. If we invoke start\n///  symbol s then call r1, which calls r2, the  would look like\n///  this:\n///\n///     SContext[-1]   <- root node (bottom of the stack)\n///     R1Context[p]   <- p in rule s called r1\n///     R2Context[q]   <- q in rule r1 called r2\n///\n///  So the top of the stack, _ctx, represents a call to the current\n///  rule and it holds the return address from another rule that invoke\n///  to this rule. To invoke a rule, we must always have a current context.\n///\n///  The parent contexts are useful for computing lookahead sets and\n///  getting error information.\n///\n///  These objects are used during parsing and prediction.\n///  For the special case of parsers, we use the subclass\n///  ParserRuleContext.\n///\n///  @see ParserRuleContext\nabstract class RuleContext extends RuleNode {\n  /// What context invoked this rule?\n  RuleContext? _parent;\n\n  /// What state invoked the rule associated with this context?\n  /// The \"return address\" is the followState of invokingState\n  /// If parent is null, this should be -1.\n  int invokingState;\n\n  RuleContext({RuleContext? parent, int? invokingState})\n      : _parent=parent, invokingState = invokingState ?? -1;\n\n  int depth() {\n    var n = 0;\n    RuleContext? p = this;\n    while (p != null) {\n      p = p.parent;\n      n++;\n    }\n    return n;\n  }\n\n  @override\n  // Work around for https://github.com/antlr/antlr4/issues/3248\n  // ignore: unnecessary_getters_setters\n  RuleContext? get parent => _parent;\n\n  @override\n  // Work around for https://github.com/antlr/antlr4/issues/3248\n  // ignore: unnecessary_getters_setters\n  set parent(RuleContext? parent) {\n    _parent = parent;\n  }\n\n  /// A context is empty if there is no invoking state; meaning nobody call\n  /// current context.\n  bool get isEmpty => invokingState == -1;\n\n  /// satisfy the ParseTree / SyntaxTree interface\n  @override\n  Interval get sourceInterval => Interval.INVALID;\n\n  @override\n  RuleContext get ruleContext => this;\n\n  @override\n  RuleContext get payload => this;\n\n  /// Return the combined text of all child nodes. This method only considers\n  ///  tokens which have been added to the parse tree.\n  ///  <p>\n  ///  Since tokens on hidden channels (e.g. whitespace or comments) are not\n  ///  added to the parse trees, they will not appear in the output of this\n  ///  method.\n  @override\n  String get text {\n    if (childCount == 0) {\n      return '';\n    }\n\n    final builder = StringBuffer();\n    for (var i = 0; i < childCount; i++) {\n      builder.write(getChild(i)!.text);\n    }\n\n    return builder.toString();\n  }\n\n  int get ruleIndex => -1;\n\n  /// For rule associated with this parse tree internal node, return\n  /// the outer alternative number used to match the input. Default\n  /// implementation does not compute nor store this alt num. Create\n  /// a subclass of ParserRuleContext with backing field and set\n  /// option contextSuperClass.\n  /// to set it.\n  int get altNumber => ATN.INVALID_ALT_NUMBER;\n\n  /// Set the outer alternative number for this context node. Default\n  /// implementation does nothing to avoid backing field overhead for\n  /// trees that don't need it.  Create\n  /// a subclass of ParserRuleContext with backing field and set\n  /// option contextSuperClass.\n  set altNumber(int altNumber) {}\n\n  @override\n  ParseTree? getChild<T>(int i) {\n    return null;\n  }\n\n  @override\n  int get childCount => 0;\n\n  @override\n  T? accept<T>(ParseTreeVisitor<T> visitor) {\n    return visitor.visitChildren(this);\n  }\n\n  /// Print out a whole tree, not just a node, in LISP format\n  /// (root child1 .. childN). Print just a node if this is a leaf.\n  ///\n  @override\n  String toStringTree({List<String>? ruleNames, Parser? parser}) {\n    return Trees.toStringTree(this, ruleNames: ruleNames, recog: parser);\n  }\n\n  @override\n  String toString({\n    List<String>? ruleNames,\n    Recognizer? recog,\n    RuleContext? stop,\n  }) {\n    ruleNames = ruleNames ?? recog?.ruleNames;\n    final buf = StringBuffer();\n    RuleContext? p = this;\n    buf.write('[');\n    while (p != null && p != stop) {\n      if (ruleNames == null) {\n        if (!p.isEmpty) {\n          buf.write(p.invokingState);\n        }\n      } else {\n        final ruleIndex = p.ruleIndex;\n        final ruleName = ruleIndex >= 0 && ruleIndex < ruleNames.length\n            ? ruleNames[ruleIndex]\n            : ruleIndex.toString();\n        buf.write(ruleName);\n      }\n\n      if (p.parent != null && (ruleNames != null || !p.parent!.isEmpty)) {\n        buf.write(' ');\n      }\n\n      p = p.parent;\n    }\n\n    buf.write(']');\n    return buf.toString();\n  }\n\n  static final EMPTY = ParserRuleContext();\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/runtime_meta_data.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:developer';\nimport 'dart:math' as math;\n\nimport 'package:logging/logging.dart';\n\n/// This class provides access to the current version of the ANTLR 4 runtime\n/// library as compile-time and runtime constants, along with methods for\n/// checking for matching version numbers and notifying listeners in the case\n/// where a version mismatch is detected.\n///\n/// <p>\n/// The runtime version information is provided by {@link #VERSION} and\n/// {@link #getRuntimeVersion()}. Detailed information about these values is\n/// provided in the documentation for each member.</p>\n///\n/// <p>\n/// The runtime version check is implemented by {@link #checkVersion}. Detailed\n/// information about incorporating this call into user code, as well as its use\n/// in generated code, is provided in the documentation for the method.</p>\n///\n/// <p>\n/// Version strings x.y and x.y.z are considered \"compatible\" and no error\n/// would be generated. Likewise, version strings x.y-SNAPSHOT and x.y.z are\n/// considered \"compatible\" because the major and minor components x.y\n/// are the same in each.</p>\n///\n/// <p>\n/// To trap any error messages issued by this code, use System.setErr()\n/// in your main() startup code.\n/// </p>\n///\n/// @since 4.3\nclass RuntimeMetaData {\n  /// A compile-time constant containing the current version of the ANTLR 4\n  /// runtime library.\n  ///\n  /// <p>\n  /// This compile-time constant value allows generated parsers and other\n  /// libraries to include a literal reference to the version of the ANTLR 4\n  /// runtime library the code was compiled against. At each release, we\n  /// change this value.</p>\n  ///\n  /// <p>Version numbers are assumed to have the form\n  ///\n  /// <em>major</em>.<em>minor</em>.<em>patch</em>.<em>revision</em>-<em>suffix</em>,\n  ///\n  /// with the individual components defined as follows.</p>\n  ///\n  /// <ul>\n  /// <li><em>major</em> is a required non-negative integer, and is equal to\n  /// {@code 4} for ANTLR 4.</li>\n  /// <li><em>minor</em> is a required non-negative integer.</li>\n  /// <li><em>patch</em> is an optional non-negative integer. When\n  /// <em>patch</em> is omitted, the {@code .} (dot) appearing before it is\n  /// also omitted.</li>\n  /// <li><em>revision</em> is an optional non-negative integer, and may only\n  /// be included when <em>patch</em> is also included. When <em>revision</em>\n  /// is omitted, the {@code .} (dot) appearing before it is also omitted.</li>\n  /// <li><em>suffix</em> is an optional string. When <em>suffix</em> is\n  /// omitted, the {@code -} (hyphen-minus) appearing before it is also\n  /// omitted.</li>\n  /// </ul>\n  static final String VERSION = '4.13.2';\n\n  /// Gets the currently executing version of the ANTLR 4 runtime library.\n  ///\n  /// <p>\n  /// This method provides runtime access to the [VERSION] field, as\n  /// opposed to directly referencing the field as a compile-time constant.</p>\n  ///\n  /// @return The currently executing version of the ANTLR 4 library\n  static String get runtimeVersion {\n    return VERSION;\n  }\n\n  /// This method provides the ability to detect mismatches between the version\n  /// of ANTLR 4 used to generate a parser, the version of the ANTLR runtime a\n  /// parser was compiled against, and the version of the ANTLR runtime which\n  /// is currently executing.\n  ///\n  /// <p>\n  /// The version check is designed to detect the following two specific\n  /// scenarios.</p>\n  ///\n  /// <ul>\n  /// <li>The ANTLR Tool version used for code generation does not match the\n  /// currently executing runtime version.</li>\n  /// <li>The ANTLR Runtime version referenced at the time a parser was\n  /// compiled does not match the currently executing runtime version.</li>\n  /// </ul>\n  ///\n  /// <p>\n  /// Starting with ANTLR 4.3, the code generator emits a call to this method\n  /// using two constants in each generated lexer and parser: a hard-coded\n  /// constant indicating the version of the tool used to generate the parser\n  /// and a reference to the compile-time constant {@link #VERSION}. At\n  /// runtime, this method is called during the initialization of the generated\n  /// parser to detect mismatched versions, and notify the registered listeners\n  /// prior to creating instances of the parser.</p>\n  ///\n  /// <p>\n  /// This method does not perform any detection or filtering of semantic\n  /// changes between tool and runtime versions. It simply checks for a\n  /// version match and emits an error to stderr if a difference\n  /// is detected.</p>\n  ///\n  /// <p>\n  /// Note that some breaking changes between releases could result in other\n  /// types of runtime exceptions, such as a [LinkageError], prior to\n  /// calling this method. In these cases, the underlying version mismatch will\n  /// not be reported here. This method is primarily intended to\n  /// notify users of potential semantic changes between releases that do not\n  /// result in binary compatibility problems which would be detected by the\n  /// class loader. As with semantic changes, changes that break binary\n  /// compatibility between releases are mentioned in the release notes\n  /// accompanying the affected release.</p>\n  ///\n  /// <p>\n  /// <strong>Additional note for target developers:</strong> The version check\n  /// implemented by this class is designed to address specific compatibility\n  /// concerns that may arise during the execution of Java applications. Other\n  /// targets should consider the implementation of this method in the context\n  /// of that target's known execution environment, which may or may not\n  /// resemble the design provided for the Java target.</p>\n  ///\n  /// @param generatingToolVersion The version of the tool used to generate a parser.\n  /// This value may be null when called from user code that was not generated\n  /// by, and does not reference, the ANTLR 4 Tool itself.\n  /// @param compileTimeVersion The version of the runtime the parser was\n  /// compiled against. This should always be passed using a direct reference\n  /// to [VERSION].\n  static void checkVersion(\n    String? generatingToolVersion,\n    String compileTimeVersion,\n  ) {\n    final runtimeVersion = VERSION;\n    var runtimeConflictsWithGeneratingTool = false;\n    var runtimeConflictsWithCompileTimeTool = false;\n\n    if (generatingToolVersion != null) {\n      runtimeConflictsWithGeneratingTool =\n          !(runtimeVersion == generatingToolVersion) &&\n              !(getMajorMinorVersion(runtimeVersion) ==\n                  getMajorMinorVersion(generatingToolVersion));\n    }\n\n    runtimeConflictsWithCompileTimeTool =\n        !(runtimeVersion == compileTimeVersion) &&\n            !(getMajorMinorVersion(runtimeVersion) ==\n                getMajorMinorVersion(compileTimeVersion));\n\n    if (runtimeConflictsWithGeneratingTool) {\n      log('ANTLR Tool version $generatingToolVersion used for code generation does not match the current runtime version $runtimeVersion',\n          level: Level.SEVERE.value);\n    }\n    if (runtimeConflictsWithCompileTimeTool) {\n      log('ANTLR Runtime version $compileTimeVersion used for parser compilation does not match the current runtime version $runtimeVersion',\n          level: Level.SEVERE.value);\n    }\n  }\n\n  /// Gets the major and minor version numbers from a version string. For\n  /// details about the syntax of the input [version].\n  /// E.g., from x.y.z return x.y.\n  ///\n  /// @param version The complete version string.\n  /// @return A string of the form <em>major</em>.<em>minor</em> containing\n  /// only the major and minor components of the version string.\n  static String getMajorMinorVersion(String version) {\n    final firstDot = version.indexOf('.');\n    final secondDot = firstDot >= 0 ? version.indexOf('.', firstDot + 1) : -1;\n    final firstDash = version.indexOf('-');\n    var referenceLength = version.length;\n    if (secondDot >= 0) {\n      referenceLength = math.min(referenceLength, secondDot);\n    }\n\n    if (firstDash >= 0) {\n      referenceLength = math.min(referenceLength, firstDash);\n    }\n\n    return version.substring(0, referenceLength);\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/token.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'input_stream.dart';\nimport 'interval_set.dart';\nimport 'misc/misc.dart';\nimport 'token_source.dart';\n\n/// A token has properties: text, type, line, character position in the line\n///  (so we can ignore tabs), token channel, index, and source from which\n///  we obtained this token.\nabstract class Token {\n  static const int INVALID_TYPE = 0;\n\n  /// During lookahead operations, this \"token\" signifies we hit rule end ATN state\n  ///  and did not follow it despite needing to.\n  static const int EPSILON = -2;\n\n  static const int MIN_USER_TOKEN_TYPE = 1;\n\n  static const int EOF = IntStream.EOF;\n\n  /// All tokens go to the parser (unless skip() is called in that rule)\n  ///  on a particular \"channel\".  The parser tunes to a particular channel\n  ///  so that whitespace etc... can go to the parser on a \"hidden\" channel.\n  static const int DEFAULT_CHANNEL = 0;\n\n  /// Anything on different channel than DEFAULT_CHANNEL is not parsed\n  ///  by parser.\n  static const int HIDDEN_CHANNEL = 1;\n\n  /// This is the minimum constant value which can be assigned to a\n  /// user-defined token channel.\n  ///\n  /// <p>\n  /// The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are\n  /// assigned to the predefined channels {@link #DEFAULT_CHANNEL} and\n  /// {@link #HIDDEN_CHANNEL}.</p>\n  ///\n  /// @see Token#getChannel()\n  static const int MIN_USER_CHANNEL_VALUE = 2;\n\n  /// Get the text of the token.\n  String? get text;\n\n  /// Get the token type of the token */\n  int get type;\n\n  /// The line number on which the 1st character of this token was matched,\n  ///  line=1..n\n  int? get line;\n\n  /// The index of the first character of this token relative to the\n  ///  beginning of the line at which it occurs, 0..n-1\n  int get charPositionInLine;\n\n  /// Return the channel this token. Each token can arrive at the parser\n  ///  on a different channel, but the parser only \"tunes\" to a single channel.\n  ///  The parser ignores everything not on DEFAULT_CHANNEL.\n  int get channel;\n\n  /// An index from 0..n-1 of the token object in the input stream.\n  ///  This must be valid in order to print token streams and\n  ///  use TokenRewriteStream.\n  ///\n  ///  Return -1 to indicate that this token was conjured up since\n  ///  it doesn't have a valid index.\n  int get tokenIndex;\n\n  /// The starting character index of the token\n  ///  This method is optional; return -1 if not implemented.\n  int get startIndex;\n\n  /// The last character index of the token.\n  ///  This method is optional; return -1 if not implemented.\n  int get stopIndex;\n\n  /// Gets the [TokenSource] which created this token.\n  TokenSource? get tokenSource;\n\n  /// Gets the [CharStream] from which this token was derived.\n  CharStream? get inputStream;\n}\n\nabstract class WritableToken extends Token {\n  set text(String? text);\n\n  set type(int ttype);\n\n  set line(int? line);\n\n  set charPositionInLine(int pos);\n\n  set channel(int channel);\n\n  set tokenIndex(int index);\n}\n\nclass CommonToken extends WritableToken {\n  /// An empty [Pair] which is used as the default value of\n  /// {@link #source} for tokens that do not have a source.\n  static const EMPTY_SOURCE = Pair<TokenSource?, CharStream?>(null, null);\n\n  @override\n  int type;\n\n  @override\n  int? line;\n\n  @override\n  int charPositionInLine = -1; // set to invalid position\n\n  @override\n  int channel = Token.DEFAULT_CHANNEL;\n\n  /// These properties share a field to reduce the memory footprint of\n  /// [CommonToken]. Tokens created by a [CommonTokenFactory] from\n  /// the same source and input stream share a reference to the same\n  /// [Pair] containing these values.</p>\n  late Pair<TokenSource?, CharStream?> source;\n\n  /// This is the backing field for {@link #getText} when the token text is\n  /// explicitly set in the constructor or via {@link #setText}.\n  ///\n  /// @see #getText()\n  String? _text;\n\n  @override\n  int tokenIndex = -1;\n\n  @override\n  int startIndex;\n\n  @override\n  int stopIndex;\n\n  /// Constructs a new [CommonToken] with the specified token type and\n  /// text.\n  ///\n  /// @param type The token type.\n  /// @param text The text of the token.\n  CommonToken(\n    this.type, {\n    this.source = EMPTY_SOURCE,\n    this.channel = Token.DEFAULT_CHANNEL,\n    this.startIndex = -1,\n    this.stopIndex = -1,\n    text,\n  }) {\n    _text = text;\n    if (source.a != null) {\n      line = source.a!.line;\n      charPositionInLine = source.a!.charPositionInLine;\n    }\n  }\n\n  /// Constructs a new [CommonToken] as a copy of another [Token].\n  ///\n  /// <p>\n  /// If [oldToken] is also a [CommonToken] instance, the newly\n  /// constructed token will share a reference to the {@link #text} field and\n  /// the [Pair] stored in {@link #source}. Otherwise, {@link #text} will\n  /// be assigned the result of calling {@link #getText}, and {@link #source}\n  /// will be constructed from the result of {@link Token#getTokenSource} and\n  /// {@link Token#getInputStream}.</p>\n  ///\n  /// @param oldToken The token to copy.\n  CommonToken.copy(Token oldToken)\n      : type = oldToken.type,\n        line = oldToken.line,\n        tokenIndex = oldToken.tokenIndex,\n        charPositionInLine = oldToken.charPositionInLine,\n        channel = oldToken.channel,\n        startIndex = oldToken.startIndex,\n        stopIndex = oldToken.stopIndex {\n    if (oldToken is CommonToken) {\n      _text = oldToken.text;\n      source = oldToken.source;\n    } else {\n      _text = oldToken.text;\n      source = Pair<TokenSource?, CharStream?>(\n        oldToken.tokenSource,\n        oldToken.inputStream,\n      );\n    }\n  }\n\n  @override\n  String? get text {\n    if (_text != null) {\n      return _text;\n    }\n\n    final input = inputStream;\n    if (input == null) return null;\n    final n = input.size;\n\n    if (startIndex < n && stopIndex < n) {\n      return input.getText(Interval.of(startIndex, stopIndex));\n    } else {\n      return '<EOF>';\n    }\n  }\n\n  /// Explicitly set the text for this token. If {code text} is not\n  /// null, then {@link #getText} will return this value rather than\n  /// extracting the text from the input.\n  ///\n  /// @param text The explicit text of the token, or null if the text\n  /// should be obtained from the input along with the start and stop indexes\n  /// of the token.\n  @override\n  set text(String? text) {\n    _text = text;\n  }\n\n  @override\n  TokenSource? get tokenSource {\n    return source.a;\n  }\n\n  @override\n  CharStream? get inputStream {\n    return source.b;\n  }\n\n  @override\n  String toString([void _]) {\n    var txt = text;\n    if (txt != null) {\n      txt = txt\n          .replaceAll('\\n', r'\\n')\n          .replaceAll('\\r', r'\\r')\n          .replaceAll('\\t', r'\\t');\n    } else {\n      txt = '<no text>';\n    }\n    return \"[@$tokenIndex,$startIndex:$stopIndex='$txt',<$type>\" +\n        (channel > 0 ? ',channel=$channel' : '') +\n        ',$line:$charPositionInLine]';\n  }\n}\n\n/// A [Token] object representing an entire subtree matched by a parser\n/// rule; e.g., {@code <expr>}. These tokens are created for [TagChunk]\n/// chunks where the tag corresponds to a parser rule.\nclass RuleTagToken implements Token {\n  /// Gets the name of the rule associated with this rule tag.\n  ///\n  /// @return The name of the parser rule associated with this rule tag.\n  final String ruleName;\n\n  /// The token type for the current token. This is the token type assigned to\n  /// the bypass alternative for the rule during ATN deserialization.\n  final int bypassTokenType;\n\n  /// Gets the label associated with the rule tag.\n  ///\n  /// @return The name of the label associated with the rule tag, or\n  /// null if this is an unlabeled rule tag.\n  final String? label;\n\n  /// Constructs a new instance of [RuleTagToken] with the specified rule\n  /// name, bypass token type, and label.\n  ///\n  /// @param ruleName The name of the parser rule this rule tag matches.\n  /// @param bypassTokenType The bypass token type assigned to the parser rule.\n  /// @param label The label associated with the rule tag, or null if\n  /// the rule tag is unlabeled.\n  ///\n  /// @exception ArgumentError.value(value) if [ruleName] is null\n  /// or empty.\n  RuleTagToken(this.ruleName, this.bypassTokenType, [this.label]) {\n    if (ruleName.isEmpty) {\n      throw ArgumentError.value(\n        ruleName,\n        'ruleName',\n        'cannot be empty.',\n      );\n    }\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>Rule tag tokens are always placed on the {@link #DEFAULT_CHANNEL}.</p>\n\n  @override\n  int get channel {\n    return Token.DEFAULT_CHANNEL;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>This method returns the rule tag formatted with {@code <} and {@code >}\n  /// delimiters.</p>\n\n  @override\n  String get text {\n    if (label != null) {\n      return '<' + label! + ':' + ruleName + '>';\n    }\n\n    return '<' + ruleName + '>';\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>Rule tag tokens have types assigned according to the rule bypass\n  /// transitions created during ATN deserialization.</p>\n\n  @override\n  int get type {\n    return bypassTokenType;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] always returns 0.</p>\n\n  @override\n  int get line {\n    return 0;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] always returns -1.</p>\n  @override\n  int get charPositionInLine {\n    return -1;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] always returns -1.</p>\n  @override\n  int get tokenIndex {\n    return -1;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] always returns -1.</p>\n  @override\n  int get startIndex {\n    return -1;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] always returns -1.</p>\n\n  @override\n  int get stopIndex {\n    return -1;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] always returns null.</p>\n\n  @override\n  TokenSource? get tokenSource {\n    return null;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] always returns null.</p>\n\n  @override\n  CharStream? get inputStream {\n    return null;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [RuleTagToken] returns a string of the form\n  /// {@code ruleName:bypassTokenType}.</p>\n\n  @override\n  String toString() {\n    return ruleName + ':$bypassTokenType';\n  }\n}\n\n/// A [Token] object representing a token of a particular type; e.g.,\n/// {@code <ID>}. These tokens are created for [TagChunk] chunks where the\n/// tag corresponds to a lexer rule or token type.\nclass TokenTagToken extends CommonToken {\n  /// Gets the token name.\n  /// @return The token name.\n  final String tokenName;\n\n  /// Gets the label associated with the rule tag.\n  ///\n  /// @return The name of the label associated with the rule tag, or\n  /// null if this is an unlabeled rule tag.\n  final String? label;\n\n  /// Constructs a new instance of [TokenTagToken] with the specified\n  /// token name, type, and label.\n  ///\n  /// @param tokenName The token name.\n  /// @param type The token type.\n  /// @param label The label associated with the token tag, or null if\n  /// the token tag is unlabeled.\n  TokenTagToken(this.tokenName, type, [this.label]) : super(type);\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [TokenTagToken] returns the token tag\n  /// formatted with {@code <} and {@code >} delimiters.</p>\n\n  @override\n  String get text {\n    if (label != null) {\n      return '<' + label! + ':' + tokenName + '>';\n    }\n\n    return '<' + tokenName + '>';\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [TokenTagToken] returns a string of the form\n  /// {@code tokenName:type}.</p>\n\n  @override\n  String toString([void _]) {\n    return tokenName + ':$type';\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/token_factory.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'input_stream.dart';\nimport 'interval_set.dart';\nimport 'misc/misc.dart';\nimport 'token.dart';\nimport 'token_source.dart';\n\n/// The default mechanism for creating tokens. It's used by default in Lexer and\n///  the error handling strategy (to create missing tokens).  Notifying the parser\n///  of a new factory means that it notifies its token source and error strategy.\nabstract class TokenFactory<Symbol extends Token> {\n  /// This is the method used to create tokens in the lexer and in the\n  ///  error handling strategy. If text!=null, than the start and stop positions\n  ///  are wiped to -1 in the text override is set in the CommonToken.\n  Symbol create(\n    int type,\n    String? text,\n    Pair<TokenSource?, CharStream?> source,\n    int channel,\n    int start,\n    int stop,\n    int? line,\n    int charPositionInLine,\n  );\n}\n\n/// This default implementation of [TokenFactory] creates\n/// [CommonToken] objects.\nclass CommonTokenFactory implements TokenFactory<CommonToken> {\n  /// The default [CommonTokenFactory] instance.\n  ///\n  /// <p>\n  /// This token factory does not explicitly copy token text when constructing\n  /// tokens.</p>\n  static final TokenFactory<CommonToken> DEFAULT = CommonTokenFactory();\n\n  /// Indicates whether {@link CommonToken#setText} should be called after\n  /// constructing tokens to explicitly set the text. This is useful for cases\n  /// where the input stream might not be able to provide arbitrary substrings\n  /// of text from the input after the lexer creates a token (e.g. the\n  /// implementation of {@link CharStream#getText} in\n  /// [UnbufferedCharStream] throws an\n  /// [UnsupportedOperationException]). Explicitly setting the token text\n  /// allows {@link Token#getText} to be called at any time regardless of the\n  /// input stream implementation.\n  ///\n  /// <p>\n  /// The default value is [false] to avoid the performance and memory\n  /// overhead of copying text for every token unless explicitly requested.</p>\n  final bool copyText;\n\n  /// Constructs a [CommonTokenFactory] with the specified value for\n  /// {@link #copyText}.\n  ///\n  /// <p>\n  /// When [copyText] is [false], the {@link #DEFAULT} instance\n  /// should be used instead of constructing a new instance.</p>\n  ///\n  /// @param copyText The value for {@link #copyText}.\n  CommonTokenFactory([this.copyText = false]);\n\n  @override\n  CommonToken create(\n    int type,\n    String? text,\n    Pair<TokenSource?, CharStream?>? source,\n    int channel,\n    int start,\n    int stop,\n    int? line,\n    int charPositionInLine,\n  ) {\n    if (source == null) {\n      return CommonToken(type, text: text);\n    }\n\n    final t = CommonToken(\n      type,\n      source: source,\n      channel: channel,\n      startIndex: start,\n      stopIndex: stop,\n    );\n    t.line = line;\n    t.charPositionInLine = charPositionInLine;\n    if (text != null) {\n      t.text = text;\n    } else if (copyText && source.b != null) {\n      t.text = source.b!.getText(Interval.of(start, stop));\n    }\n\n    return t;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/token_source.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:math';\n\nimport 'input_stream.dart';\nimport 'misc/misc.dart';\nimport 'token.dart';\nimport 'token_factory.dart';\n\n/// A source of tokens must provide a sequence of tokens via {@link #nextToken()}\n/// and also must reveal it's source of characters; [CommonToken]'s text is\n/// computed from a [CharStream]; it only store indices into the char\n/// stream.\n///\n/// <p>Errors from the lexer are never passed to the parser. Either you want to keep\n/// going or you do not upon token recognition error. If you do not want to\n/// continue lexing then you do not want to continue parsing. Just throw an\n/// exception not under [RecognitionException] and Java will naturally toss\n/// you all the way out of the recognizers. If you want to continue lexing then\n/// you should not throw an exception to the parser--it has already requested a\n/// token. Keep lexing until you get a valid one. Just report errors and keep\n/// going, looking for a valid token.</p>\nabstract class TokenSource {\n  /// Return a [Token] object from your input stream (usually a\n  /// [CharStream]). Do not fail/return upon lexing error; keep chewing\n  /// on the characters until you get a good one; errors are not passed through\n  /// to the parser.\n  Token nextToken();\n\n  /// Get the line number for the current position in the input stream. The\n  /// first line in the input is line 1.\n  ///\n  /// @return The line number for the current position in the input stream, or\n  /// 0 if the current token source does not track line numbers.\n  int? get line;\n\n  /// Get the index into the current line for the current position in the input\n  /// stream. The first character on a line has position 0.\n  ///\n  /// @return The line number for the current position in the input stream, or\n  /// -1 if the current token source does not track character positions.\n  int get charPositionInLine;\n\n  /// Get the [CharStream] from which this token source is currently\n  /// providing tokens.\n  ///\n  /// @return The [CharStream] associated with the current position in\n  /// the input, or null if no input stream is available for the token\n  /// source.\n  CharStream? get inputStream;\n\n  /// Gets the name of the underlying input source. This method returns a\n  /// non-null, non-empty string. If such a name is not known, this method\n  /// returns {@link IntStream#UNKNOWN_SOURCE_NAME}.\n  String get sourceName;\n\n  /// Set the [TokenFactory] this token source should use for creating\n  /// [Token] objects from the input.\n  ///\n  /// @param factory The [TokenFactory] to use for creating tokens.\n  set tokenFactory(TokenFactory factory);\n\n  /// Gets the [TokenFactory] this token source is currently using for\n  /// creating [Token] objects from the input.\n  ///\n  /// @return The [TokenFactory] currently used by this token source.\n  TokenFactory get tokenFactory;\n}\n\n/// Provides an implementation of [TokenSource] as a wrapper around a list\n/// of [Token] objects.\n///\n/// <p>If the final token in the list is an {@link Token#EOF} token, it will be used\n/// as the EOF token for every call to {@link #nextToken} after the end of the\n/// list is reached. Otherwise, an EOF token will be created.</p>\nclass ListTokenSource implements TokenSource {\n  /// The wrapped collection of [Token] objects to return.\n  final List<Token> tokens;\n\n  final String? _sourceName;\n\n  /// The index into {@link #tokens} of token to return by the next call to\n  /// {@link #nextToken}. The end of the input is indicated by this value\n  /// being greater than or equal to the number of items in {@link #tokens}.\n  late int i; // todo: uncertain\n\n  /// This field caches the EOF token for the token source.\n  Token? eofToken;\n\n  /// This is the backing field for {@link #getTokenFactory} and\n  /// [setTokenFactory].\n  @override\n  TokenFactory tokenFactory = CommonTokenFactory.DEFAULT;\n\n  /**\n   * Constructs a new [ListTokenSource] instance from the specified\n   * collection of [Token] objects.\n   *\n   * @param tokens The collection of [Token] objects to provide as a\n   * [TokenSource].\n   * @exception NullPointerException if [tokens] is null\n   */\n\n  /// Constructs a new [ListTokenSource] instance from the specified\n  /// collection of [Token] objects and source name.\n  ///\n  /// @param tokens The collection of [Token] objects to provide as a\n  /// [TokenSource].\n  /// @param sourceName The name of the [TokenSource]. If this value is\n  /// null, {@link #getSourceName} will attempt to infer the name from\n  /// the next [Token] (or the previous token if the end of the input has\n  /// been reached).\n  ///\n  /// @exception NullPointerException if [tokens] is null\n  ListTokenSource(this.tokens, [this._sourceName]);\n\n  /// {@inheritDoc}\n\n  @override\n  int get charPositionInLine {\n    if (i < tokens.length) {\n      return tokens[i].charPositionInLine;\n    } else if (eofToken != null) {\n      return eofToken!.charPositionInLine;\n    } else if (tokens.isNotEmpty) {\n      // have to calculate the result from the line/column of the previous\n      // token, along with the text of the token.\n      final lastToken = tokens[tokens.length - 1];\n      final tokenText = lastToken.text;\n      if (tokenText != null) {\n        final lastNewLine = tokenText.lastIndexOf('\\n');\n        if (lastNewLine >= 0) {\n          return tokenText.length - lastNewLine - 1;\n        }\n      }\n\n      return lastToken.charPositionInLine +\n          lastToken.stopIndex -\n          lastToken.startIndex +\n          1;\n    }\n\n    // only reach this if tokens is empty, meaning EOF occurs at the first\n    // position in the input\n    return 0;\n  }\n\n  /// {@inheritDoc}\n\n  @override\n  Token nextToken() {\n    if (i >= tokens.length) {\n      if (eofToken == null) {\n        var start = -1;\n        if (tokens.isNotEmpty) {\n          final previousStop = tokens[tokens.length - 1].stopIndex;\n          if (previousStop != -1) {\n            start = previousStop + 1;\n          }\n        }\n\n        final stop = max(-1, start - 1);\n        eofToken = tokenFactory.create(\n          Token.EOF,\n          'EOF',\n          Pair(this, inputStream),\n          Token.DEFAULT_CHANNEL,\n          start,\n          stop,\n          line,\n          charPositionInLine,\n        );\n      }\n\n      return eofToken!;\n    }\n\n    final t = tokens[i];\n    if (i == tokens.length - 1 && t.type == Token.EOF) {\n      eofToken = t;\n    }\n\n    i++;\n    return t;\n  }\n\n  /// {@inheritDoc}\n\n  @override\n  int? get line {\n    if (i < tokens.length) {\n      return tokens[i].line;\n    } else if (eofToken != null) {\n      return eofToken!.line;\n    } else if (tokens.isNotEmpty) {\n      // have to calculate the result from the line/column of the previous\n      // token, along with the text of the token.\n      final lastToken = tokens[tokens.length - 1];\n      var line = lastToken.line ?? 0;\n\n      final tokenText = lastToken.text;\n      if (tokenText != null) {\n        for (var i = 0; i < tokenText.length; i++) {\n          if (tokenText[i] == '\\n') {\n            line++;\n          }\n        }\n      }\n\n      // if no text is available, assume the token did not contain any newline characters.\n      return line;\n    }\n\n    // only reach this if tokens is empty, meaning EOF occurs at the first\n    // position in the input\n    return 1;\n  }\n\n  /// {@inheritDoc}\n\n  @override\n  CharStream? get inputStream {\n    if (i < tokens.length) {\n      return tokens[i].inputStream;\n    } else if (eofToken != null) {\n      return eofToken!.inputStream;\n    } else if (tokens.isNotEmpty) {\n      return tokens[tokens.length - 1].inputStream;\n    }\n\n    // no input stream information is available\n    return null;\n  }\n\n  /// The name of the input source. If this value is null, a call to\n  /// {@link #getSourceName} should return the source name used to create the\n  /// the next token in {@link #tokens} (or the previous token if the end of\n  /// the input has been reached).\n  @override\n  String get sourceName => _sourceName ?? inputStream?.sourceName ?? 'List';\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/token_stream.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport 'input_stream.dart';\nimport 'interval_set.dart';\nimport 'lexer.dart';\nimport 'rule_context.dart';\nimport 'token.dart';\nimport 'token_source.dart';\n\n/// An [IntStream] whose symbols are [Token] instances.\nabstract class TokenStream extends IntStream {\n  /// Get the [Token] instance associated with the value returned by\n  /// [LA]. This method has the same pre- and post-conditions as\n  /// [IntStream.LA]. In addition, when the preconditions of this method\n  /// are met, the return value is non-null and the value of\n  /// `LT(k).getType()==LA(k)`.\n  ///\n  /// TODO: in this doc it says that is non-null, but the implementation says\n  /// otherwise\n  ///\n  /// Se also:\n  /// ntStream.LA\n  Token? LT(int k);\n\n  /// Gets the [Token] at the specified [index] in the stream. When\n  /// the preconditions of this method are met, the return value is non-null.\n  ///\n  /// <p>The preconditions for this method are the same as the preconditions of\n  /// {@link IntStream#seek}. If the behavior of {@code seek(index)} is\n  /// unspecified for the current state and given [index], then the\n  /// behavior of this method is also unspecified.</p>\n  ///\n  /// <p>The symbol referred to by [index] differs from {@code seek()} only\n  /// in the case of filtering streams where [index] lies before the end\n  /// of the stream. Unlike {@code seek()}, this method does not adjust\n  /// [index] to point to a non-ignored symbol.</p>\n  ///\n  /// @throws IllegalArgumentException if {code index} is less than 0\n  /// @throws UnsupportedOperationException if the stream does not support\n  /// retrieving the token at the specified index\n  Token get(int index);\n\n  /// Gets the underlying [TokenSource] which provides tokens for this\n  /// stream.\n  TokenSource get tokenSource;\n\n  /// Return the text of all tokens within the specified [interval]. This\n  /// method behaves like the following code (including potential exceptions\n  /// for violating preconditions of {@link #get}, but may be optimized by the\n  /// specific implementation.\n  ///\n  /// <pre>\n  /// TokenStream stream = ...;\n  /// String text = \"\";\n  /// for (int i = interval.a; i &lt;= interval.b; i++) {\n  ///   text += stream.get(i).getText();\n  /// }\n  /// </pre>\n  ///\n  /// <pre>\n  /// TokenStream stream = ...;\n  /// String text = stream.getText(new Interval(0, stream.length));\n  /// </pre>\n  ///\n  /// <pre>\n  /// TokenStream stream = ...;\n  /// String text = stream.getText(ctx.getSourceInterval());\n  /// </pre>\n  ///\n  /// @param interval The interval of tokens within this stream to get text\n  /// for.\n  /// @return The text of all tokens / within the specified interval in this\n  /// stream.\n  String getText([Interval interval]);\n\n  String get text;\n\n  /// Return the text of all tokens in the source interval of the specified\n  /// context. This method behaves like the following code, including potential\n  /// exceptions from the call to {@link #getText(Interval)}, but may be\n  /// optimized by the specific implementation.\n  ///\n  /// <p>If {@code ctx.getSourceInterval()} does not return a valid interval of\n  /// tokens provided by this stream, the behavior is unspecified.</p>\n  ///\n  /// @param ctx The context providing the source interval of tokens to get\n  /// text for.\n  /// @return The text of all tokens within the source interval of [ctx].\n  String getTextFromCtx(RuleContext ctx);\n\n  /// Return the text of all tokens in this stream between [start] and\n  /// [stop] (inclusive).\n  ///\n  /// <p>If the specified [start] or [stop] token was not provided by\n  /// this stream, or if the [stop] occurred before the [start]\n  /// token, the behavior is unspecified.</p>\n  ///\n  /// <p>For streams which ensure that the {@link Token#getTokenIndex} method is\n  /// accurate for all of its provided tokens, this method behaves like the\n  /// following code. Other streams may implement this method in other ways\n  /// provided the behavior is consistent with this at a high level.</p>\n  ///\n  /// <pre>\n  /// TokenStream stream = ...;\n  /// String text = \"\";\n  /// for (int i = start.getTokenIndex(); i &lt;= stop.getTokenIndex(); i++) {\n  ///   text += stream.get(i).getText();\n  /// }\n  /// </pre>\n  ///\n  /// @param start The first token in the interval to get text for.\n  /// @param stop The last token in the interval to get text for (inclusive).\n  /// @return The text of all tokens lying between the specified [start]\n  /// and [stop] tokens.\n  ///\n  /// @throws UnsupportedOperationException if this stream does not support\n  /// this method for the specified tokens\n  String getTextRange(Token? start, Token? stop);\n}\n\n/// This implementation of [TokenStream] loads tokens from a\n/// [TokenSource] on-demand, and places the tokens in a buffer to provide\n/// access to any previous token by index.\n///\n/// <p>\n/// This token stream ignores the value of {@link Token#getChannel}. If your\n/// parser requires the token stream filter tokens to only those on a particular\n/// channel, such as {@link Token#DEFAULT_CHANNEL} or\n/// {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a\n/// [CommonTokenStream].</p>\nclass BufferedTokenStream implements TokenStream {\n  /// The [TokenSource] from which tokens for this stream are fetched.\n  TokenSource _tokenSource;\n\n  /// A collection of all tokens fetched from the token source. The list is\n  /// considered a complete view of the input once {@link #fetchedEOF} is set\n  /// to [true].\n  List<Token> tokens = <Token>[];\n\n  /// The index into [tokens] of the current token (next token to [consume]).\n  /// [tokens][p] should be [LT(1)].\n  ///\n  /// <p>This field is set to -1 when the stream is first constructed or when\n  /// [tokenSource] is set, indicating that the first token has\n  /// not yet been fetched from the token source. For additional information,\n  /// see the documentation of [IntStream] for a description of\n  /// Initializing Methods.</p>\n  int p = -1;\n\n  /// Indicates whether the [Token.EOF] token has been fetched from\n  /// [tokenSource] and added to [tokens]. This field improves\n  /// performance for the following cases:\n  ///\n  /// <ul>\n  /// <li>{@link #consume}: The lookahead check in {@link #consume} to prevent\n  /// consuming the EOF symbol is optimized by checking the values of\n  /// {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li>\n  /// <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into\n  /// [{@link #]tokens} is trivial with this field.</li>\n  /// <ul>\n  bool fetchedEOF = false;\n\n  BufferedTokenStream(this._tokenSource);\n\n  @override\n  int get index => p;\n\n  @override\n  int mark() {\n    return 0;\n  }\n\n  @override\n  void release(int marker) {\n    // no resources to release\n  }\n\n  @override\n  void seek(int index) {\n    lazyInit();\n    p = adjustSeekIndex(index);\n  }\n\n  @override\n  int get size {\n    return tokens.length;\n  }\n\n  @override\n  void consume() {\n    bool skipEofCheck;\n    if (p >= 0) {\n      if (fetchedEOF) {\n        // the last token in tokens is EOF. skip check if p indexes any\n        // fetched token except the last.\n        skipEofCheck = p < tokens.length - 1;\n      } else {\n        // no EOF token in tokens. skip check if p indexes a fetched token.\n        skipEofCheck = p < tokens.length;\n      }\n    } else {\n      // not yet initialized\n      skipEofCheck = false;\n    }\n\n    if (!skipEofCheck && LA(1) == IntStream.EOF) {\n      throw StateError('cannot consume EOF');\n    }\n\n    if (sync(p + 1)) {\n      p = adjustSeekIndex(p + 1);\n    }\n  }\n\n  /// Make sure index [i] in tokens has a token.\n  ///\n  /// @return [true] if a token is located at index [i], otherwise\n  ///    [false].\n  /// @see #get(int i)\n  bool sync(int i) {\n    assert(i >= 0);\n    final n = i - tokens.length + 1; // how many more elements we need?\n    //System.out.println(\"sync(\"+i+\") needs \"+n);\n    if (n > 0) {\n      final fetched = fetch(n);\n      return fetched >= n;\n    }\n\n    return true;\n  }\n\n  /// Add [n] elements to buffer.\n  ///\n  /// @return The actual number of elements added to the buffer.\n  int fetch(int n) {\n    if (fetchedEOF) {\n      return 0;\n    }\n\n    for (var i = 0; i < n; i++) {\n      final t = tokenSource.nextToken();\n      if (t is WritableToken) {\n        t.tokenIndex = tokens.length;\n      }\n      tokens.add(t);\n      if (t.type == Token.EOF) {\n        fetchedEOF = true;\n        return i + 1;\n      }\n    }\n\n    return n;\n  }\n\n  @override\n  Token get(int i) {\n    if (i < 0 || i >= tokens.length) {\n      throw RangeError.index(i, tokens);\n    }\n    return tokens[i];\n  }\n\n  /// Get all tokens from start..stop inclusively */\n  List<Token>? getRange(int start, [int? stop]) {\n    stop = stop ?? start;\n    if (start < 0 || stop < 0) return null;\n    lazyInit();\n    final subset = <Token>[];\n    if (stop >= tokens.length) stop = tokens.length - 1;\n    for (var i = start; i <= stop; i++) {\n      final t = tokens[i];\n      if (t.type == Token.EOF) break;\n      subset.add(t);\n    }\n    return subset;\n  }\n\n  @override\n  int? LA(int i) {\n    return LT(i)?.type;\n  }\n\n  Token? LB(int k) {\n    if ((p - k) < 0) return null;\n    return tokens[p - k];\n  }\n\n  @override\n  Token? LT(int k) {\n    lazyInit();\n    if (k == 0) return null;\n    if (k < 0) return LB(-k);\n\n    final i = p + k - 1;\n    sync(i);\n    if (i >= tokens.length) {\n      // return EOF token\n      // EOF must be last token\n      return tokens.last;\n    }\n//\t\tif ( i>range ) range = i;\n    return tokens[i];\n  }\n\n  /// Allowed derived classes to modify the behavior of operations which change\n  /// the current stream position by adjusting the target token index of a seek\n  /// operation. The default implementation simply returns [i]. If an\n  /// exception is thrown in this method, the current stream index should not be\n  /// changed.\n  ///\n  /// <p>For example, [CommonTokenStream] overrides this method to ensure that\n  /// the seek target is always an on-channel token.</p>\n  ///\n  /// @param i The target token index.\n  /// @return The adjusted target token index.\n  int adjustSeekIndex(int i) {\n    return i;\n  }\n\n  void lazyInit() {\n    if (p == -1) {\n      setup();\n    }\n  }\n\n  void setup() {\n    sync(0);\n    p = adjustSeekIndex(0);\n  }\n\n  @override\n  TokenSource get tokenSource => _tokenSource;\n\n  /// Reset this token stream by setting its token source. */\n  set tokenSource(TokenSource tokenSource) {\n    _tokenSource = tokenSource;\n    tokens.clear();\n    p = -1;\n    fetchedEOF = false;\n  }\n\n  /// Given a start and stop index, return a List of all tokens in\n  ///  the token type BitSet.  Return null if no tokens were found.  This\n  ///  method looks at both on and off channel tokens.\n  List<Token>? getTokens([\n    int? start,\n    int? stop,\n    Set<int>? types,\n  ]) {\n    if (start == null && stop == null) {\n      return tokens;\n    }\n    start = start!;\n    stop = stop!;\n    lazyInit();\n    if (start < 0 || start >= tokens.length) {\n      throw RangeError.index(start, tokens);\n    } else if (stop < 0 || stop >= tokens.length) {\n      throw RangeError.index(stop, tokens);\n    }\n    if (start > stop) return null;\n\n    // list = tokens[start:stop]:{T t, t.getType() in types}\n    List<Token>? filteredTokens = <Token>[];\n    for (var i = start; i <= stop; i++) {\n      final t = tokens[i];\n      if (types == null || types.contains(t.type)) {\n        filteredTokens.add(t);\n      }\n    }\n    if (filteredTokens.isEmpty) {\n      filteredTokens = null;\n    }\n    return filteredTokens;\n  }\n\n  /// Given a starting index, return the index of the next token on channel.\n  /// Return [i] if {@code tokens[i]} is on channel. Return the index of\n  /// the EOF token if there are no tokens on channel between [i] and\n  /// EOF.\n  int nextTokenOnChannel(int i, int channel) {\n    sync(i);\n    if (i >= size) {\n      return size - 1;\n    }\n\n    var token = tokens[i];\n    while (token.channel != channel) {\n      if (token.type == Token.EOF) {\n        return i;\n      }\n\n      i++;\n      sync(i);\n      token = tokens[i];\n    }\n\n    return i;\n  }\n\n  /// Given a starting index, return the index of the previous token on\n  /// channel. Return [i] if {@code tokens[i]} is on channel. Return -1\n  /// if there are no tokens on channel between [i] and 0.\n  ///\n  /// <p>\n  /// If [i] specifies an index at or after the EOF token, the EOF token\n  /// index is returned. This is due to the fact that the EOF token is treated\n  /// as though it were on every channel.</p>\n  int previousTokenOnChannel(int i, int channel) {\n    sync(i);\n    if (i >= size) {\n      // the EOF token is on every channel\n      return size - 1;\n    }\n\n    while (i >= 0) {\n      final token = tokens[i];\n      if (token.type == Token.EOF || token.channel == channel) {\n        return i;\n      }\n\n      i--;\n    }\n\n    return i;\n  }\n\n  /// Collect all tokens on specified channel to the right of\n  ///  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or\n  ///  EOF. If channel is -1, find any non default channel token.\n  List<Token>? getHiddenTokensToRight(int tokenIndex, [int channel = -1]) {\n    lazyInit();\n    if (tokenIndex < 0 || tokenIndex >= tokens.length) {\n      throw RangeError.index(tokenIndex, tokens);\n    }\n\n    final nextOnChannel =\n        nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL);\n    // if none onchannel to right, nextOnChannel=-1 so set to = last token\n    final to = nextOnChannel == -1 ? size - 1 : nextOnChannel;\n    final from = tokenIndex + 1;\n\n    return filterForChannel(from, to, channel);\n  }\n\n  /// Collect all tokens on specified channel to the left of\n  ///  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n  ///  If channel is -1, find any non default channel token.\n  List<Token>? getHiddenTokensToLeft(int tokenIndex, [int channel = -1]) {\n    lazyInit();\n    if (tokenIndex < 0 || tokenIndex >= tokens.length) {\n      throw RangeError.index(tokenIndex, tokens);\n    }\n\n    if (tokenIndex == 0) {\n      // obviously no tokens can appear before the first token\n      return null;\n    }\n\n    final prevOnChannel = previousTokenOnChannel(\n      tokenIndex - 1,\n      Lexer.DEFAULT_TOKEN_CHANNEL,\n    );\n    if (prevOnChannel == tokenIndex - 1) return null;\n    // if none onchannel to left, prevOnChannel=-1 then from=0\n    final from = prevOnChannel + 1;\n    final to = tokenIndex - 1;\n\n    return filterForChannel(from, to, channel);\n  }\n\n  List<Token>? filterForChannel(int from, int to, int channel) {\n    final hidden = <Token>[];\n    for (var i = from; i <= to; i++) {\n      final t = tokens[i];\n      if (channel == -1) {\n        if (t.channel != Lexer.DEFAULT_TOKEN_CHANNEL) hidden.add(t);\n      } else {\n        if (t.channel == channel) hidden.add(t);\n      }\n    }\n    if (hidden.isEmpty) return null;\n    return hidden;\n  }\n\n  @override\n  String get sourceName => tokenSource.sourceName;\n\n  @override\n  String get text => getText();\n\n  @override\n  String getText([Interval? interval]) {\n    interval = interval ??\n        Interval.of(0, size - 1); // Get the text of all tokens in this buffer.\n    final start = interval.a;\n    var stop = interval.b;\n    if (start < 0 || stop < 0) return '';\n    fill();\n    if (stop >= tokens.length) stop = tokens.length - 1;\n\n    final buf = StringBuffer();\n    for (var i = start; i <= stop; i++) {\n      final t = tokens[i];\n      if (t.type == Token.EOF) break;\n      buf.write(t.text);\n    }\n    return buf.toString();\n  }\n\n  @override\n  String getTextFromCtx(RuleContext ctx) {\n    return getText(ctx.sourceInterval);\n  }\n\n  @override\n  String getTextRange(Token? start, Token? stop) {\n    if (start != null && stop != null) {\n      return getText(Interval.of(start.tokenIndex, stop.tokenIndex));\n    }\n\n    return '';\n  }\n\n  /// Get all tokens from lexer until EOF */\n  void fill() {\n    lazyInit();\n    final blockSize = 1000;\n    while (true) {\n      final fetched = fetch(blockSize);\n      if (fetched < blockSize) {\n        return;\n      }\n    }\n  }\n}\n\n/// This class extends [BufferedTokenStream] with functionality to filter\n/// token streams to tokens on a particular channel (tokens where\n/// {@link Token#getChannel} returns a particular value).\n///\n/// <p>\n/// This token stream provides access to all tokens by index or when calling\n/// methods like {@link #getText}. The channel filtering is only used for code\n/// accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and\n/// {@link #LB}.</p>\n///\n/// <p>\n/// By default, tokens are placed on the default channel\n/// ({@link Token#DEFAULT_CHANNEL}), but may be reassigned by using the\n/// {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to\n/// call {@link Lexer#setChannel}.\n/// </p>\n///\n/// <p>\n/// Note: lexer rules which use the {@code ->skip} lexer command or call\n/// {@link Lexer#skip} do not produce tokens at all, so input text matched by\n/// such a rule will not be available as part of the token stream, regardless of\n/// channel.</p>we\nclass CommonTokenStream extends BufferedTokenStream {\n  /// Specifies the channel to use for filtering tokens.\n  ///\n  /// <p>\n  /// The default value is {@link Token#DEFAULT_CHANNEL}, which matches the\n  /// default channel assigned to tokens created by the lexer.</p>\n  int channel;\n\n  /// Constructs a new [CommonTokenStream] using the specified token\n  /// source and filtering tokens to the specified channel. Only tokens whose\n  /// {@link Token#getChannel} matches [channel] or have the\n  /// {@link Token#getType} equal to {@link Token#EOF} will be returned by the\n  /// token stream lookahead methods.\n  ///\n  /// @param tokenSource The token source.\n  /// @param channel The channel to use for filtering tokens.\n  CommonTokenStream(TokenSource tokenSource,\n      [this.channel = Token.DEFAULT_CHANNEL])\n      : super(tokenSource);\n\n  @override\n  int adjustSeekIndex(int i) {\n    return nextTokenOnChannel(i, channel);\n  }\n\n  @override\n  Token? LB(int k) {\n    if (k == 0 || (p - k) < 0) return null;\n\n    var i = p;\n    var n = 1;\n    // find k good tokens looking backwards\n    while (n <= k && i > 0) {\n      // skip off-channel tokens\n      i = previousTokenOnChannel(i - 1, channel);\n      n++;\n    }\n    if (i < 0) return null;\n    return tokens[i];\n  }\n\n  @override\n  Token? LT(int k) {\n    //System.out.println(\"enter LT(\"+k+\")\");\n    lazyInit();\n    if (k == 0) return null;\n    if (k < 0) return LB(-k);\n    var i = p;\n    var n = 1; // we know tokens[p] is a good one\n    // find k good tokens\n    while (n < k) {\n      // skip off-channel tokens, but make sure to not look past EOF\n      if (sync(i + 1)) {\n        i = nextTokenOnChannel(i + 1, channel);\n      }\n      n++;\n    }\n//\t\tif ( i>range ) range = i;\n    return tokens[i];\n  }\n\n  /// Count EOF just once. */\n  int get numberOfOnChannelTokens {\n    var n = 0;\n    fill();\n    for (var i = 0; i < tokens.length; i++) {\n      final t = tokens[i];\n      if (t.channel == channel) n++;\n      if (t.type == Token.EOF) break;\n    }\n    return n;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/tree/src/pattern/chunk.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/// A chunk is either a token tag, a rule tag, or a span of literal text within a\n/// tree pattern.\n///\n/// <p>The method {@link ParseTreePatternMatcher#split(String)} returns a list of\n/// chunks in preparation for creating a token stream by\n/// {@link ParseTreePatternMatcher#tokenize(String)}. From there, we get a parse\n/// tree from with {@link ParseTreePatternMatcher#compile(String, int)}. These\n/// chunks are converted to [RuleTagToken], [TokenTagToken], or the\n/// regular tokens of the text surrounding the tags.</p>\nabstract class Chunk {}\n\n/// Represents a placeholder tag in a tree pattern. A tag can have any of the\n/// following forms.\n///\n/// <ul>\n/// <li>[expr]: An unlabeled placeholder for a parser rule [expr].</li>\n/// <li>[ID]: An unlabeled placeholder for a token of type [ID].</li>\n/// <li>{@code e:expr}: A labeled placeholder for a parser rule [expr].</li>\n/// <li>{@code id:ID}: A labeled placeholder for a token of type [ID].</li>\n/// </ul>\n///\n/// This class does not perform any validation on the tag or label names aside\n/// from ensuring that the tag is a non-null, non-empty string.\nclass TagChunk extends Chunk {\n  /// The tag for the chunk.\n  final String tag;\n\n  /// The label assigned to this chunk, or null if no label is\n  /// assigned to the chunk.\n  final String? label;\n\n  /// Construct a new instance of [TagChunk] using the specified label\n  /// and tag.\n  ///\n  /// @param label The label for the tag. If this is null, the\n  /// [TagChunk] represents an unlabeled tag.\n  /// @param tag The tag, which should be the name of a parser rule or token\n  /// type.\n  ///\n  /// @exception ArgumentError if [tag] is null or empty.\n  TagChunk(this.tag, {this.label}) {\n    if (tag.isEmpty) {\n      throw ArgumentError.value(tag, 'tag', 'cannot be empty');\n    }\n  }\n\n  /// This method returns a text representation of the tag chunk. Labeled tags\n  /// are returned in the form {@code label:tag}, and unlabeled tags are\n  /// returned as just the tag name.\n  @override\n  String toString() {\n    if (label != null) {\n      return label! + ':' + tag;\n    }\n\n    return tag;\n  }\n}\n\n/// Represents a span of raw text (concrete syntax) between tags in a tree\n/// pattern string.\nclass TextChunk extends Chunk {\n  /// The text of the chunk.\n  final String text;\n\n  /// Constructs a new instance of [TextChunk] with the specified text.\n  ///\n  /// @param text The text of this chunk.\n  /// @exception IllegalArgumentException if [text] is null.\n  TextChunk(this.text);\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The implementation for [TextChunk] returns the result of\n  /// {@link #getText()} in single quotes.</p>\n  @override\n  String toString() {\n    return \"'\" + text + \"'\";\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/tree/src/pattern/parse_tree_match.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport '../../../error/error.dart';\nimport '../../../input_stream.dart';\nimport '../../../lexer.dart';\nimport '../../../misc/misc.dart';\nimport '../../../parser.dart';\nimport '../../../parser_interpreter.dart';\nimport '../../../parser_rule_context.dart';\nimport '../../../token.dart';\nimport '../../../token_source.dart';\nimport '../../../token_stream.dart';\nimport '../../../util/utils.dart';\nimport '../tree.dart';\nimport 'chunk.dart';\n\n/// Represents the result of matching a [ParseTree] against a tree pattern.\nclass ParseTreeMatch {\n  /// Get the parse tree we are trying to match to a pattern.\n  ///\n  /// @return The [ParseTree] we are trying to match to a pattern.\n  final ParseTree tree;\n\n  /// Get the tree pattern we are matching against.\n  ///\n  /// @return The tree pattern we are matching against.\n  final ParseTreePattern pattern;\n\n  /// Return a mapping from label &rarr; [list of nodes].\n  ///\n  /// <p>The map includes special entries corresponding to the names of rules and\n  /// tokens referenced in tags in the original pattern. For additional\n  /// information, see the description of {@link #getAll(String)}.</p>\n  ///\n  /// @return A mapping from labels to parse tree nodes. If the parse tree\n  /// pattern did not contain any rule or token tags, this map will be empty.\n  final MultiMap<String, ParseTree> labels;\n\n  /// Get the node at which we first detected a mismatch.\n  ///\n  /// @return the node at which we first detected a mismatch, or null\n  /// if the match was successful.\n  final ParseTree? mismatchedNode;\n\n  /// Constructs a new instance of [ParseTreeMatch] from the specified\n  /// parse tree and pattern.\n  ///\n  /// @param tree The parse tree to match against the pattern.\n  /// @param pattern The parse tree pattern.\n  /// @param labels A mapping from label names to collections of\n  /// [ParseTree] objects located by the tree pattern matching process.\n  /// @param mismatchedNode The first node which failed to match the tree\n  /// pattern during the matching process.\n  ///\n  ParseTreeMatch(this.tree, this.pattern, this.labels, this.mismatchedNode);\n\n  /// Get the last node associated with a specific [label].\n  ///\n  /// <p>For example, for pattern {@code <id:ID>}, {@code get(\"id\")} returns the\n  /// node matched for that [ID]. If more than one node\n  /// matched the specified label, only the last is returned. If there is\n  /// no node associated with the label, this returns null.</p>\n  ///\n  /// <p>Pattern tags like {@code <ID>} and {@code <expr>} without labels are\n  /// considered to be labeled with [ID] and [expr], respectively.</p>\n  ///\n  /// @param label The label to check.\n  ///\n  /// @return The last [ParseTree] to match a tag with the specified\n  /// label, or null if no parse tree matched a tag with the label.\n\n  ParseTree? get(String label) {\n    final parseTrees = labels[label];\n    if (parseTrees == null || parseTrees.isEmpty) {\n      return null;\n    }\n\n    return parseTrees[parseTrees.length - 1]; // return last if multiple\n  }\n\n  /// Return all nodes matching a rule or token tag with the specified label.\n  ///\n  /// <p>If the [label] is the name of a parser rule or token in the\n  /// grammar, the resulting list will contain both the parse trees matching\n  /// rule or tags explicitly labeled with the label and the complete set of\n  /// parse trees matching the labeled and unlabeled tags in the pattern for\n  /// the parser rule or token. For example, if [label] is {@code \"foo\"},\n  /// the result will contain <em>all</em> of the following.</p>\n  ///\n  /// <ul>\n  /// <li>Parse tree nodes matching tags of the form {@code <foo:anyRuleName>} and\n  /// {@code <foo:AnyTokenName>}.</li>\n  /// <li>Parse tree nodes matching tags of the form {@code <anyLabel:foo>}.</li>\n  /// <li>Parse tree nodes matching tags of the form {@code <foo>}.</li>\n  /// </ul>\n  ///\n  /// @param label The label.\n  ///\n  /// @return A collection of all [ParseTree] nodes matching tags with\n  /// the specified [label]. If no nodes matched the label, an empty list\n  /// is returned.\n\n  List<ParseTree> getAll(String label) {\n    final nodes = labels[label];\n    if (nodes == null) {\n      return [];\n    }\n\n    return nodes;\n  }\n\n  /// Gets a value indicating whether the match operation succeeded.\n  ///\n  /// @return [true] if the match operation succeeded; otherwise,\n  /// [false].\n  bool get succeeded => mismatchedNode == null;\n\n  /// {@inheritDoc}\n  @override\n  String toString() {\n    return \"Match ${succeeded ? \"succeeded\" : \"failed\"}; found ${labels.length} labels\";\n  }\n}\n\n/// A pattern like {@code <ID> = <expr>;} converted to a [ParseTree] by\n/// {@link ParseTreePatternMatcher#compile(String, int)}.\nclass ParseTreePattern {\n  /// Get the parser rule which serves as the outermost rule for the tree\n  /// pattern.\n  ///\n  /// @return The parser rule which serves as the outermost rule for the tree\n  /// pattern.\n  final int patternRuleIndex;\n\n  /// Get the tree pattern in concrete syntax form.\n  ///\n  /// @return The tree pattern in concrete syntax form.\n  final String pattern;\n\n  /// Get the tree pattern as a [ParseTree]. The rule and token tags from\n  /// the pattern are present in the parse tree as terminal nodes with a symbol\n  /// of type [RuleTagToken] or [TokenTagToken].\n  ///\n  /// @return The tree pattern as a [ParseTree].\n  final ParseTree patternTree;\n\n  /// Get the [ParseTreePatternMatcher] which created this tree pattern.\n  ///\n  /// @return The [ParseTreePatternMatcher] which created this tree\n  /// pattern.\n  final ParseTreePatternMatcher matcher;\n\n  /// Construct a new instance of the [ParseTreePattern] class.\n  ///\n  /// @param matcher The [ParseTreePatternMatcher] which created this\n  /// tree pattern.\n  /// @param pattern The tree pattern in concrete syntax form.\n  /// @param patternRuleIndex The parser rule which serves as the root of the\n  /// tree pattern.\n  /// @param patternTree The tree pattern in [ParseTree] form.\n  ParseTreePattern(\n    this.matcher,\n    this.pattern,\n    this.patternRuleIndex,\n    this.patternTree,\n  );\n\n  /// Match a specific parse tree against this tree pattern.\n  ///\n  /// @param tree The parse tree to match against this tree pattern.\n  /// @return A [ParseTreeMatch] object describing the result of the\n  /// match operation. The {@link ParseTreeMatch#succeeded()} method can be\n  /// used to determine whether or not the match was successful.\n\n  ParseTreeMatch match(ParseTree tree) {\n    return matcher.match(tree, pattern: this);\n  }\n\n  /// Determine whether or not a parse tree matches this tree pattern.\n  ///\n  /// @param tree The parse tree to match against this tree pattern.\n  /// @return [true] if [tree] is a match for the current tree\n  /// pattern; otherwise, [false].\n  bool matches(ParseTree tree) {\n    return matcher.match(tree, pattern: this).succeeded;\n  }\n}\n\n/// A tree pattern matching mechanism for ANTLR [ParseTree]s.\n///\n/// <p>Patterns are strings of source input text with special tags representing\n/// token or rule references such as:</p>\n///\n/// <p>{@code <ID> = <expr>;}</p>\n///\n/// <p>Given a pattern start rule such as [statement], this object constructs\n/// a [ParseTree] with placeholders for the [ID] and [expr]\n/// subtree. Then the {@link #match} routines can compare an actual\n/// [ParseTree] from a parse with this pattern. Tag {@code <ID>} matches\n/// any [ID] token and tag {@code <expr>} references the result of the\n/// [expr] rule (generally an instance of [ExprContext].</p>\n///\n/// <p>Pattern {@code x = 0;} is a similar pattern that matches the same pattern\n/// except that it requires the identifier to be [x] and the expression to\n/// be {@code 0}.</p>\n///\n/// <p>The {@link #matches} routines return [true] or [false] based\n/// upon a match for the tree rooted at the parameter sent in. The\n/// {@link #match} routines return a [ParseTreeMatch] object that\n/// contains the parse tree, the parse tree pattern, and a map from tag name to\n/// matched nodes (more below). A subtree that fails to match, returns with\n/// {@link ParseTreeMatch#mismatchedNode} set to the first tree node that did not\n/// match.</p>\n///\n/// <p>For efficiency, you can compile a tree pattern in string form to a\n/// [ParseTreePattern] object.</p>\n///\n/// <p>See [TestParseTreeMatcher] for lots of examples.\n/// [ParseTreePattern] has two static helper methods:\n/// {@link ParseTreePattern#findAll} and {@link ParseTreePattern#match} that\n/// are easy to use but not super efficient because they create new\n/// [ParseTreePatternMatcher] objects each time and have to compile the\n/// pattern in string form before using it.</p>\n///\n/// <p>The lexer and parser that you pass into the [ParseTreePatternMatcher]\n/// constructor are used to parse the pattern in string form. The lexer converts\n/// the {@code <ID> = <expr>;} into a sequence of four tokens (assuming lexer\n/// throws out whitespace or puts it on a hidden channel). Be aware that the\n/// input stream is reset for the lexer (but not the parser; a\n/// [ParserInterpreter] is created to parse the input.). Any user-defined\n/// fields you have put into the lexer might get changed when this mechanism asks\n/// it to scan the pattern string.</p>\n///\n/// <p>Normally a parser does not accept token {@code <expr>} as a valid\n/// [expr] but, from the parser passed in, we create a special version of\n/// the underlying grammar representation (an [ATN]) that allows imaginary\n/// tokens representing rules ({@code <expr>}) to match entire rules. We call\n/// these <em>bypass alternatives</em>.</p>\n///\n/// <p>Delimiters are {@code <} and {@code >}, with {@code \\} as the escape string\n/// by default, but you can set them to whatever you want using\n/// {@link #setDelimiters}. You must escape both start and stop strings\n/// {@code \\<} and {@code \\>}.</p>\nclass ParseTreePatternMatcher {\n  /// Used to convert the tree pattern string into a series of tokens. The\n  /// input stream is reset.\n  final Lexer lexer;\n\n  /// Used to collect to the grammar file name, token names, rule names for\n  /// used to parse the pattern into a parse tree.\n  final Parser parser;\n\n  String start = '<';\n  String stop = '>';\n  String escape = '\\\\'; // e.g., \\< and \\> must escape BOTH!\n\n  /// Constructs a [ParseTreePatternMatcher] or from a [Lexer] and\n  /// [Parser] object. The lexer input stream is altered for tokenizing\n  /// the tree patterns. The parser is used as a convenient mechanism to get\n  /// the grammar name, plus token, rule names.\n  ParseTreePatternMatcher(this.lexer, this.parser);\n\n  /// Set the delimiters used for marking rule and token tags within concrete\n  /// syntax used by the tree pattern parser.\n  ///\n  /// @param start The start delimiter.\n  /// @param stop The stop delimiter.\n  /// @param escapeLeft The escape sequence to use for escaping a start or stop delimiter.\n  ///\n  /// @exception ArgumentError if [start] is null or empty.\n  /// @exception ArgumentError if [stop] is null or empty.\n  void setDelimiters(String start, String stop, String escapeLeft) {\n    if (start.isEmpty) {\n      throw ArgumentError.value(start, 'start', 'cannot be empty');\n    }\n\n    if (stop.isEmpty) {\n      throw ArgumentError.value(stop, 'stop', 'cannot be empty');\n    }\n\n    this.start = start;\n    this.stop = stop;\n    escape = escapeLeft;\n  }\n\n  /// Does [pattern] matched as rule patternRuleIndex match tree? Pass in a\n  ///  compiled pattern instead of a string representation of a tree pattern.\n  bool matches(\n    ParseTree tree, {\n    ParseTreePattern? pattern,\n    String? patternStr,\n    int? patternRuleIndex,\n  }) {\n    assert(pattern != null || patternStr != null && patternRuleIndex != null);\n    pattern ??= compile(patternStr!, patternRuleIndex!);\n\n    final labels = MultiMap<String, ParseTree>();\n    final mismatchedNode = matchImpl(tree, pattern.patternTree, labels);\n    return mismatchedNode == null;\n  }\n\n  /// Compare [pattern] matched against [tree] and return a\n  /// [ParseTreeMatch] object that contains the matched elements, or the\n  /// node at which the match failed. Pass in a compiled pattern instead of a\n  /// string representation of a tree pattern.\n\n  ParseTreeMatch match(\n    ParseTree tree, {\n    ParseTreePattern? pattern,\n    String? patternStr,\n    int? patternRuleIndex,\n  }) {\n    assert(pattern != null || patternStr != null && patternRuleIndex != null);\n    pattern ??= compile(patternStr!, patternRuleIndex!);\n\n    final labels = MultiMap<String, ParseTree>();\n    final mismatchedNode = matchImpl(tree, pattern.patternTree, labels);\n    return ParseTreeMatch(tree, pattern, labels, mismatchedNode);\n  }\n\n  /// For repeated use of a tree pattern, compile it to a\n  /// [ParseTreePattern] using this method.\n  ParseTreePattern compile(String pattern, int patternRuleIndex) {\n    final tokenList = tokenize(pattern);\n    final tokenSrc = ListTokenSource(tokenList);\n    final tokens = CommonTokenStream(tokenSrc);\n\n    final parserInterp = ParserInterpreter(\n      parser.grammarFileName,\n      parser.vocabulary,\n      parser.ruleNames,\n      parser.ATNWithBypassAlts,\n      tokens,\n    );\n\n    ParseTree tree;\n    try {\n      parserInterp.errorHandler = BailErrorStrategy();\n      tree = parserInterp.parse(patternRuleIndex);\n//\t\t\tSystem.out.println(\"pattern tree = \"+tree.toStringTree(parserInterp));\n    } on ParseCancellationException {\n      rethrow;\n    } on RecognitionException {\n      rethrow;\n    } catch (e) {\n      throw CannotInvokeStartRule(e.toString());\n    }\n\n    // Make sure tree pattern compilation checks for a complete parse\n    if (tokens.LA(1) != Token.EOF) {\n      throw StartRuleDoesNotConsumeFullPattern();\n    }\n\n    return ParseTreePattern(this, pattern, patternRuleIndex, tree);\n  }\n\n  // ---- SUPPORT CODE ----\n\n  /// Recursively walk [tree] against [patternTree], filling\n  /// {@code match.}{@link ParseTreeMatch#labels labels}.\n  ///\n  /// @return the first node encountered in [tree] which does not match\n  /// a corresponding node in [patternTree], or null if the match\n  /// was successful. The specific node returned depends on the matching\n  /// algorithm used by the implementation, and may be overridden.\n\n  ParseTree? matchImpl(\n    ParseTree tree,\n    ParseTree patternTree,\n    MultiMap<String, ParseTree> labels,\n  ) {\n    // x and <ID>, x and y, or x and x; or could be mismatched types\n    if (tree is TerminalNode && patternTree is TerminalNode) {\n      final t1 = tree;\n      final t2 = patternTree;\n      late final ParseTree mismatchedNode;\n      // both are tokens and they have same type\n      if (t1.symbol.type == t2.symbol.type) {\n        if (t2.symbol is TokenTagToken) {\n          // x and <ID>\n          final tokenTagToken = t2.symbol as TokenTagToken;\n          // track label->list-of-nodes for both token name and label (if any)\n          labels.put(tokenTagToken.tokenName, tree);\n          if (tokenTagToken.label != null) {\n            labels.put(tokenTagToken.label!, tree);\n          }\n        } else if (t1.text == t2.text) {\n          // x and x\n        } else {\n          // x and y\n          mismatchedNode = t1;\n        }\n      } else {\n        mismatchedNode = t1;\n      }\n\n      return mismatchedNode;\n    }\n\n    if (tree is ParserRuleContext && patternTree is ParserRuleContext) {\n      final r1 = tree;\n      final r2 = patternTree;\n      late final ParseTree mismatchedNode;\n      // (expr ...) and <expr>\n      final ruleTagToken = getRuleTagToken(r2);\n      if (ruleTagToken != null) {\n        if (r1.ruleContext.ruleIndex == r2.ruleContext.ruleIndex) {\n          // track label->list-of-nodes for both rule name and label (if any)\n          labels.put(ruleTagToken.ruleName, tree);\n          if (ruleTagToken.label != null) {\n            labels.put(ruleTagToken.label!, tree);\n          }\n        } else {\n          mismatchedNode = r1;\n        }\n\n        return mismatchedNode;\n      }\n\n      // (expr ...) and (expr ...)\n      if (r1.childCount != r2.childCount) {\n        mismatchedNode = r1;\n\n        return mismatchedNode;\n      }\n\n      final n = r1.childCount;\n      for (var i = 0; i < n; i++) {\n        final childMatch =\n            matchImpl(r1.getChild(i)!, patternTree.getChild(i)!, labels);\n        if (childMatch != null) {\n          return childMatch;\n        }\n      }\n\n      return null;\n    }\n\n    // if nodes aren't both tokens or both rule nodes, can't match\n    return tree;\n  }\n\n  /// Is [t] {@code (expr <expr>)} subtree? */\n  RuleTagToken? getRuleTagToken(ParseTree t) {\n    if (t is RuleNode) {\n      final r = t;\n      if (r.childCount == 1 && r.getChild(0) is TerminalNode) {\n        final c = r.getChild<TerminalNode>(0)! as TerminalNode;\n        if (c.symbol is RuleTagToken) {\n          return c.symbol as RuleTagToken;\n        }\n      }\n    }\n    return null;\n  }\n\n  List<Token> tokenize(String pattern) {\n    // split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)\n    final chunks = split(pattern);\n\n    // create token stream from text and tags\n    final tokens = <Token>[];\n    for (var chunk in chunks) {\n      if (chunk is TagChunk) {\n        final tagChunk = chunk;\n        // add special rule token or conjure up new token from name\n        if (isUpperCase(tagChunk.tag[0])) {\n          final ttype = parser.getTokenType(tagChunk.tag);\n          if (ttype == Token.INVALID_TYPE) {\n            throw ArgumentError(\n                'Unknown token ' + tagChunk.tag + ' in pattern: ' + pattern);\n          }\n          final t = TokenTagToken(tagChunk.tag, ttype, tagChunk.label);\n          tokens.add(t);\n        } else if (isLowerCase(tagChunk.tag[0])) {\n          final ruleIndex = parser.getRuleIndex(tagChunk.tag);\n          if (ruleIndex == -1) {\n            throw ArgumentError(\n                'Unknown rule ' + tagChunk.tag + ' in pattern: ' + pattern);\n          }\n          final ruleImaginaryTokenType =\n              parser.ATNWithBypassAlts.ruleToTokenType[ruleIndex];\n          tokens.add(RuleTagToken(\n              tagChunk.tag, ruleImaginaryTokenType, tagChunk.label));\n        } else {\n          throw ArgumentError(\n              'invalid tag: ' + tagChunk.tag + ' in pattern: ' + pattern);\n        }\n      } else {\n        final textChunk = chunk as TextChunk;\n        final inputStream = InputStream.fromString(textChunk.text);\n        lexer.inputStream = inputStream;\n        var t = lexer.nextToken();\n        while (t.type != Token.EOF) {\n          tokens.add(t);\n          t = lexer.nextToken();\n        }\n      }\n    }\n\n//\t\tSystem.out.println(\"tokens=\"+tokens);\n    return tokens;\n  }\n\n  /// Split {@code <ID> = <e:expr> ;} into 4 chunks for tokenizing by {@link #tokenize}. */\n  List<Chunk> split(String pattern) {\n    var p = 0;\n    final n = pattern.length;\n    final chunks = <Chunk>[];\n    // find all start and stop indexes first, then collect\n    final starts = <int>[];\n    final stops = <int>[];\n    while (p < n) {\n      if (p == pattern.indexOf(escape + start, p)) {\n        p += escape.length + start.length;\n      } else if (p == pattern.indexOf(escape + stop, p)) {\n        p += escape.length + stop.length;\n      } else if (p == pattern.indexOf(start, p)) {\n        starts.add(p);\n        p += start.length;\n      } else if (p == pattern.indexOf(stop, p)) {\n        stops.add(p);\n        p += stop.length;\n      } else {\n        p++;\n      }\n    }\n\n//\t\tSystem.out.println(\"\");\n//\t\tSystem.out.println(starts);\n//\t\tSystem.out.println(stops);\n    if (starts.length > stops.length) {\n      throw ArgumentError('unterminated tag in pattern: ' + pattern);\n    }\n\n    if (starts.length < stops.length) {\n      throw ArgumentError('missing start tag in pattern: ' + pattern);\n    }\n\n    final ntags = starts.length;\n    for (var i = 0; i < ntags; i++) {\n      if (starts[i] >= stops[i]) {\n        throw ArgumentError(\n            'tag delimiters out of order in pattern: ' + pattern);\n      }\n    }\n\n    // collect into chunks now\n    if (ntags == 0) {\n      final text = pattern.substring(0, n);\n      chunks.add(TextChunk(text));\n    }\n\n    if (ntags > 0 && starts[0] > 0) {\n      // copy text up to first tag into chunks\n      final text = pattern.substring(0, starts[0]);\n      chunks.add(TextChunk(text));\n    }\n    for (var i = 0; i < ntags; i++) {\n      // copy inside of <tag>\n      final tag = pattern.substring(starts[i] + start.length, stops[i]);\n      var ruleOrToken = tag;\n      String? label;\n      final colon = tag.indexOf(':');\n      if (colon >= 0) {\n        label = tag.substring(0, colon);\n        ruleOrToken = tag.substring(colon + 1, tag.length);\n      }\n      chunks.add(TagChunk(ruleOrToken, label: label));\n      if (i + 1 < ntags) {\n        // copy from end of <tag> to start of next\n        final text = pattern.substring(stops[i] + stop.length, starts[i + 1]);\n        chunks.add(TextChunk(text));\n      }\n    }\n    if (ntags > 0) {\n      final afterLastTag = stops[ntags - 1] + stop.length;\n      if (afterLastTag < n) {\n        // copy text from end of last tag to end\n        final text = pattern.substring(afterLastTag, n);\n        chunks.add(TextChunk(text));\n      }\n    }\n\n    // strip out the escape sequences from text chunks but not tags\n    for (var i = 0; i < chunks.length; i++) {\n      final c = chunks[i];\n      if (c is TextChunk) {\n        final tc = c;\n        final unescaped = tc.text.replaceAll(escape, '');\n        if (unescaped.length < tc.text.length) {\n          chunks[i] = TextChunk(unescaped);\n        }\n      }\n    }\n\n    return chunks;\n  }\n}\n\nclass CannotInvokeStartRule extends StateError {\n  CannotInvokeStartRule(String message) : super(message);\n}\n\n// Fixes https://github.com/antlr/antlr4/issues/413\n// \"Tree pattern compilation doesn't check for a complete parse\"\nclass StartRuleDoesNotConsumeFullPattern extends Error {}\n\n/// This exception is thrown to cancel a parsing operation. This exception does\n/// not extend [RecognitionException], allowing it to bypass the standard\n/// error recovery mechanisms. [BailErrorStrategy] throws this exception in\n/// response to a parse error.\nclass ParseCancellationException extends StateError {\n  ParseCancellationException(String message) : super(message);\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/tree/src/tree.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:developer';\n\nimport '../../interval_set.dart';\nimport '../../parser.dart';\nimport '../../parser_rule_context.dart';\nimport '../../rule_context.dart';\nimport '../../token.dart';\n\n/// The basic notion of a tree has a parent, a payload, and a list of children.\n///  It is the most abstract interface for all the trees used by ANTLR.\nabstract class Tree {\n  Tree? get parent;\n\n  dynamic get payload;\n\n  Tree? getChild<T>(int i);\n\n  int get childCount;\n\n  String toStringTree();\n}\n\nabstract class SyntaxTree extends Tree {\n  /// Return an [Interval] indicating the index in the\n  /// [TokenStream] of the first and last token associated with this\n  /// subtree. If this node is a leaf, then the interval represents a single\n  /// token and has interval i..i for token index i.\n  ///\n  /// <p>An interval of i..i-1 indicates an empty interval at position\n  /// i in the input stream, where 0 &lt;= i &lt;= the size of the input\n  /// token stream.  Currently, the code base can only have i=0..n-1 but\n  /// in concept one could have an empty interval after EOF. </p>\n  ///\n  /// <p>If source interval is unknown, this returns {@link Interval#INVALID}.</p>\n  ///\n  /// <p>As a weird special case, the source interval for rules matched after\n  /// EOF is unspecified.</p>\n  Interval get sourceInterval;\n}\n\nabstract class ParseTree extends SyntaxTree {\n  // the following methods narrow the return type; they are not additional methods\n  @override\n  ParseTree? get parent;\n\n  @override\n  ParseTree? getChild<T>(int i);\n\n  /// Set the parent for this node.\n  ///\n  ///  This is not backward compatible as it changes\n  ///  the interface but no one was able to create custom\n  ///  nodes anyway so I'm adding as it improves internal\n  ///  code quality.\n  ///\n  ///  One could argue for a restructuring of\n  ///  the class/interface hierarchy so that\n  ///  setParent, addChild are moved up to Tree\n  ///  but that's a major change. So I'll do the\n  ///  minimal change, which is to add this method.\n  ///\n  ///  @since 4.7\n  set parent(covariant ParseTree? parent);\n\n  /// The [ParseTreeVisitor] needs a double dispatch method. */\n  T? accept<T>(ParseTreeVisitor<T> visitor);\n\n  /// Return the combined text of all leaf nodes. Does not get any\n  ///  off-channel tokens (if any) so won't return whitespace and\n  ///  comments if they are sent to parser on hidden channel.\n  String? get text;\n\n  /// Specialize toStringTree so that it can print out more information\n  /// \tbased upon the parser.\n  @override\n  String toStringTree({Parser parser});\n}\n\nabstract class RuleNode extends ParseTree {\n  RuleContext get ruleContext;\n}\n\nabstract class TerminalNode extends ParseTree {\n  Token get symbol;\n}\n\nabstract class ErrorNode extends TerminalNode {}\n\nabstract class ParseTreeVisitor<T> {\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation calls {@link ParseTree#accept} on the\n  /// specified tree.</p>\n  T? visit(ParseTree tree) {\n    return tree.accept(this);\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation initializes the aggregate result to\n  /// {@link #defaultResult defaultResult()}. Before visiting each child, it\n  /// calls {@link #shouldVisitNextChild shouldVisitNextChild}; if the result\n  /// is [false] no more children are visited and the current aggregate\n  /// result is returned. After visiting a child, the aggregate result is\n  /// updated by calling {@link #aggregateResult aggregateResult} with the\n  /// previous aggregate result and the result of visiting the child.</p>\n  ///\n  /// <p>The default implementation is not safe for use in visitors that modify\n  /// the tree structure. Visitors that modify the tree should override this\n  /// method to behave properly in respect to the specific algorithm in use.</p>\n  T? visitChildren(RuleNode node) {\n    var result = defaultResult();\n    final n = node.childCount;\n    for (var i = 0; i < n; i++) {\n      if (!shouldVisitNextChild(node, result)) {\n        break;\n      }\n\n      final c = node.getChild(i)!;\n      final childResult = c.accept(this);\n      result = aggregateResult(result, childResult);\n    }\n\n    return result;\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation returns the result of\n  /// {@link #defaultResult defaultResult}.</p>\n\n  T? visitTerminal(TerminalNode node) {\n    return defaultResult();\n  }\n\n  /// {@inheritDoc}\n  ///\n  /// <p>The default implementation returns the result of\n  /// {@link #defaultResult defaultResult}.</p>\n\n  T? visitErrorNode(ErrorNode node) {\n    return defaultResult();\n  }\n\n  /// Gets the default value returned by visitor methods. This value is\n  /// returned by the default implementations of\n  /// {@link #visitTerminal visitTerminal}, {@link #visitErrorNode visitErrorNode}.\n  /// The default implementation of {@link #visitChildren visitChildren}\n  /// initializes its aggregate result to this value.\n  ///\n  /// <p>The base implementation returns null.</p>\n  ///\n  /// @return The default value returned by visitor methods.\n  T? defaultResult() {\n    return null;\n  }\n\n  /// Aggregates the results of visiting multiple children of a node. After\n  /// either all children are visited or {@link #shouldVisitNextChild} returns\n  /// [false], the aggregate value is returned as the result of\n  /// {@link #visitChildren}.\n  ///\n  /// <p>The default implementation returns [nextResult], meaning\n  /// {@link #visitChildren} will return the result of the last child visited\n  /// (or return the initial value if the node has no children).</p>\n  ///\n  /// @param aggregate The previous aggregate value. In the default\n  /// implementation, the aggregate value is initialized to\n  /// {@link #defaultResult}, which is passed as the [aggregate] argument\n  /// to this method after the first child node is visited.\n  /// @param nextResult The result of the immediately preceeding call to visit\n  /// a child node.\n  ///\n  /// @return The updated aggregate result.\n  T? aggregateResult(T? aggregate, T? nextResult) => nextResult;\n\n  /// This method is called after visiting each child in\n  /// {@link #visitChildren}. This method is first called before the first\n  /// child is visited; at that point [currentResult] will be the initial\n  /// value (in the default implementation, the initial value is returned by a\n  /// call to {@link #defaultResult}. This method is not called after the last\n  /// child is visited.\n  ///\n  /// <p>The default implementation always returns [true], indicating that\n  /// [visitChildren] should only return after all children are visited.\n  /// One reason to override this method is to provide a \"short circuit\"\n  /// evaluation option for situations where the result of visiting a single\n  /// child has the potential to determine the result of the visit operation as\n  /// a whole.</p>\n  ///\n  /// @param node The [RuleNode] whose children are currently being\n  /// visited.\n  /// @param currentResult The current aggregate result of the children visited\n  /// to the current point.\n  ///\n  /// @return [true] to continue visiting children. Otherwise return\n  /// [false] to stop visiting children and immediately return the\n  /// current aggregate result from {@link #visitChildren}.\n  bool shouldVisitNextChild(RuleNode node, T? currentResult) => true;\n}\n\nabstract class ParseTreeListener {\n  void visitTerminal(TerminalNode node);\n\n  void visitErrorNode(ErrorNode node);\n\n  void enterEveryRule(ParserRuleContext node);\n\n  void exitEveryRule(ParserRuleContext node);\n}\n\nclass TraceListener implements ParseTreeListener {\n  final Parser parser;\n\n  TraceListener(this.parser);\n\n  @override\n  void enterEveryRule(ParserRuleContext ctx) {\n    log('enter   ' +\n        parser.ruleNames[ctx.ruleIndex] +\n        ', LT(1)=${parser.inputStream.LT(1)?.text}');\n  }\n\n  @override\n  void visitTerminal(TerminalNode node) {\n    log('consume ${node.symbol} rule ' +\n        parser.ruleNames[parser.context!.ruleIndex]);\n  }\n\n  @override\n  void visitErrorNode(ErrorNode node) {}\n\n  @override\n  void exitEveryRule(ParserRuleContext ctx) {\n    log('exit    ${parser.ruleNames[ctx.ruleIndex]}' ', LT(1)=' +\n        (parser.inputStream.LT(1)?.text ?? ''));\n  }\n}\n\nclass TrimToSizeListener implements ParseTreeListener {\n  static final TrimToSizeListener INSTANCE = TrimToSizeListener();\n\n  @override\n  void enterEveryRule(ParserRuleContext ctx) {}\n\n  @override\n  void visitTerminal(TerminalNode node) {}\n\n  @override\n  void visitErrorNode(ErrorNode node) {}\n\n  @override\n  void exitEveryRule(ParserRuleContext ctx) {\n    // TODO trim dart List's size\n//    if (ctx.children is List) {\n//      (ctx.children).trimToSize();\n//    }\n  }\n}\n\nclass TerminalNodeImpl extends TerminalNode {\n  @override\n  Token symbol;\n  @override\n  ParseTree? parent;\n\n  TerminalNodeImpl(this.symbol);\n\n  @override\n  ParseTree? getChild<T>(i) {\n    return null;\n  }\n\n  @override\n  Token? get payload => symbol;\n\n  @override\n  Interval get sourceInterval {\n    //if (symbol == null) return Interval.INVALID; Todo: review this nullability that nobody kind of defines, change here or change on to String\n\n    final tokenIndex = symbol.tokenIndex;\n    return Interval(tokenIndex, tokenIndex);\n  }\n\n  @override\n  int get childCount {\n    return 0;\n  }\n\n  @override\n  T? accept<T>(ParseTreeVisitor<T> visitor) {\n    return visitor.visitTerminal(this);\n  }\n\n  @override\n  String? get text {\n    return symbol.text;\n  }\n\n  @override\n  String toStringTree({Parser? parser}) {\n    return toString();\n  }\n\n  @override\n  String toString() {\n    if (symbol.type == Token.EOF) return '<EOF>';\n    return symbol.text ?? '';\n  }\n}\n\n/// Represents a token that was consumed during resynchronization\n/// rather than during a valid match operation. For example,\n/// we will create this kind of a node during single token insertion\n/// and deletion as well as during \"consume until error recovery set\"\n/// upon no viable alternative exceptions.\nclass ErrorNodeImpl extends TerminalNodeImpl implements ErrorNode {\n  ErrorNodeImpl(token) : super(token);\n\n  bool isErrorNode() => true;\n\n  @override\n  T? accept<T>(ParseTreeVisitor<T> visitor) {\n    return visitor.visitErrorNode(this);\n  }\n}\n\nclass ParseTreeWalker {\n  void walk(ParseTreeListener listener, ParseTree t) {\n    if (t is ErrorNode) {\n      listener.visitErrorNode(t);\n      return;\n    } else if (t is TerminalNode) {\n      listener.visitTerminal(t);\n      return;\n    }\n    final r = t as RuleNode;\n    enterRule(listener, r);\n    for (var i = 0; i < r.childCount; i++) {\n      walk(listener, r.getChild(i)!);\n    }\n    exitRule(listener, r);\n  }\n\n  /// The discovery of a rule node, involves sending two events: the generic\n  /// {@link ParseTreeListener#enterEveryRule} and a\n  /// [RuleContext]-specific event. First we trigger the generic and then\n  /// the rule specific. We to them in reverse order upon finishing the node.\n  void enterRule(ParseTreeListener listener, RuleNode r) {\n    var ctx = r.ruleContext\n        as ParserRuleContext; // Todo: review this cast: we have a confusion between RuleNode and ParseTree on this class\n    listener.enterEveryRule(ctx);\n    ctx.enterRule(listener);\n  }\n\n  void exitRule(ParseTreeListener listener, RuleNode r) {\n    var ctx = r.ruleContext\n        as ParserRuleContext; // Todo: review this cast: we have a confusion between RuleNode and ParseTree on this class\n    ctx.exitRule(listener);\n    listener.exitEveryRule(ctx);\n  }\n\n  static final DEFAULT = ParseTreeWalker();\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/tree/src/trees.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:core';\n\nimport '../../atn/atn.dart';\nimport '../../parser.dart';\nimport '../../parser_rule_context.dart';\nimport '../../rule_context.dart';\nimport '../../token.dart';\nimport '../../util/utils.dart';\nimport 'tree.dart';\n\n/// A set of utility routines useful for all kinds of ANTLR trees. */\nclass Trees {\n  /// Print out a whole tree in LISP form. {@link #getNodeText} is used on the\n  ///  node payloads to get the text for the nodes.  Detect\n  ///  parse trees and extract data appropriately.\n  static String toStringTree(\n    Tree? t, {\n    Parser? recog,\n    List<String>? ruleNames,\n  }) {\n    if (t == null) return 'null';\n    ruleNames ??= recog?.ruleNames;\n    var s = escapeWhitespace(getNodeText(t, ruleNames: ruleNames), false);\n    if (t.childCount == 0) return s;\n    final buf = StringBuffer();\n    buf.write('(');\n    s = escapeWhitespace(getNodeText(t, ruleNames: ruleNames), false);\n    buf.write(s);\n    buf.write(' ');\n    for (var i = 0; i < t.childCount; i++) {\n      if (i > 0) buf.write(' ');\n      buf.write(toStringTree(t.getChild(i), ruleNames: ruleNames));\n    }\n    buf.write(')');\n    return buf.toString();\n  }\n\n  static String getNodeText(\n    Tree t, {\n    Parser? recog,\n    List<String>? ruleNames,\n  }) {\n    ruleNames ??= recog?.ruleNames;\n    if (ruleNames != null) {\n      if (t is RuleContext) {\n        final ruleIndex = t.ruleContext.ruleIndex;\n        final ruleName = ruleNames[ruleIndex];\n        final altNumber = t.altNumber;\n        if (altNumber != ATN.INVALID_ALT_NUMBER) {\n          return ruleName + ':$altNumber';\n        }\n        return ruleName;\n      } else if (t is ErrorNode) {\n        return t.toString();\n      } else if (t is TerminalNode) {\n        final symbol = (t).symbol;\n        final s = symbol.text;\n        return s ?? '';\n      }\n    }\n    // no recog for rule names\n    Object payload = t.payload;\n    if (payload is Token) {\n      return payload.text ?? '';\n    }\n    return t.payload.toString();\n  }\n\n  /// Return ordered list of all children of this node */\n  static List<Tree> getChildren(Tree t) {\n    final kids = <Tree>[];\n    for (var i = 0; i < t.childCount; i++) {\n      kids.add(t.getChild(i)!);\n    }\n    return kids;\n  }\n\n  /// Return a list of all ancestors of this node.  The first node of\n  ///  list is the root and the last is the parent of this node.\n  ///\n  ///  @since 4.5.1\n  static List<Tree> getAncestors(Tree t) {\n    if (t.parent == null) return [];\n    var walker = t.parent;\n    final ancestors = <Tree>[];\n    while (walker != null) {\n      ancestors.insert(0, walker); // insert at start\n      walker = walker.parent;\n    }\n    return ancestors;\n  }\n\n  /// Return true if t is u's parent or a node on path to root from u.\n  ///  Use == not equals().\n  ///\n  ///  @since 4.5.1\n  static bool isAncestorOf(Tree? t, Tree? u) {\n    if (t == null || u == null || t.parent == null) return false;\n    var p = u.parent;\n    while (p != null) {\n      if (t == p) return true;\n      p = p.parent;\n    }\n    return false;\n  }\n\n  static List<ParseTree> findAllTokenNodes(ParseTree t, int ttype) {\n    return findAllNodes(t, ttype, true);\n  }\n\n  static List<ParseTree> findAllRuleNodes(ParseTree t, int ruleIndex) {\n    return findAllNodes(t, ruleIndex, false);\n  }\n\n  static List<ParseTree> findAllNodes(ParseTree t, int index, bool findTokens) {\n    final nodes = <ParseTree>[];\n    _findAllNodes(t, index, findTokens, nodes);\n    return nodes;\n  }\n\n  static void _findAllNodes(\n    ParseTree t,\n    int index,\n    bool findTokens,\n    List<ParseTree> nodes,\n  ) {\n    // check this node (the root) first\n    if (findTokens && t is TerminalNode) {\n      final tnode = t;\n      if (tnode.symbol.type == index) nodes.add(t);\n    } else if (!findTokens && t is ParserRuleContext) {\n      final ctx = t;\n      if (ctx.ruleIndex == index) nodes.add(t);\n    }\n    // check children\n    for (var i = 0; i < t.childCount; i++) {\n      _findAllNodes(t.getChild(i)!, index, findTokens, nodes);\n    }\n  }\n\n  /// Get all descendents; includes t itself.\n  ///\n  /// @since 4.5.1\n  static List<ParseTree> getDescendants(ParseTree t) {\n    final nodes = <ParseTree>[];\n    nodes.add(t);\n\n    final n = t.childCount;\n    for (var i = 0; i < n; i++) {\n      nodes.addAll(getDescendants(t.getChild(i)!));\n    }\n    return nodes;\n  }\n\n  /// @deprecated */\n  static List<ParseTree> descendants(ParseTree t) {\n    return getDescendants(t);\n  }\n\n  /// Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex\n  ///  inclusively using postorder traversal.  Recursive depth-first-search.\n  ///\n  ///  @since 4.5.1\n  static ParserRuleContext? getRootOfSubtreeEnclosingRegion(\n    ParseTree t,\n    int startTokenIndex, // inclusive\n    int stopTokenIndex, // inclusive\n  ) {\n    final n = t.childCount;\n    for (var i = 0; i < n; i++) {\n      final child = t.getChild(i)!;\n      final r = getRootOfSubtreeEnclosingRegion(\n        child,\n        startTokenIndex,\n        stopTokenIndex,\n      );\n      if (r != null) return r;\n    }\n    if (t is ParserRuleContext) {\n      // is range fully contained in t?\n      final start = t.start != null && startTokenIndex >= t.start!.tokenIndex;\n      final end = t.stop == null || stopTokenIndex <= t.stop!.tokenIndex;\n      if (start && end) {\n        return t;\n      }\n    }\n    return null;\n  }\n\n  /// Replace any subtree siblings of root that are completely to left\n  ///  or right of lookahead range with a CommonToken(Token.INVALID_TYPE,\"...\")\n  ///  node. The source interval for t is not altered to suit smaller range!\n  ///\n  ///  WARNING: destructive to t.\n  ///\n  ///  @since 4.5.1\n  static void stripChildrenOutOfRange(\n    ParserRuleContext? t,\n    ParserRuleContext root,\n    int startIndex,\n    int stopIndex,\n  ) {\n    if (t == null) return;\n    for (var i = 0; i < t.childCount; i++) {\n      final child = t.getChild(i)!;\n      final range = child.sourceInterval;\n      if (child is ParserRuleContext &&\n          (range.b < startIndex || range.a > stopIndex)) {\n        if (isAncestorOf(child, root)) {\n          // replace only if subtree doesn't have displayed root\n          final abbrev = CommonToken(Token.INVALID_TYPE, text: '...');\n          t.children![i] = TerminalNodeImpl(abbrev);\n        }\n      }\n    }\n  }\n\n  /// Return first node satisfying the pred\n  ///\n  ///  @since 4.5.1\n  static Tree? findNodeSuchThat(Tree? t, bool Function(Tree?) pred) {\n    if (pred(t)) return t;\n\n    if (t == null) return null;\n\n    final n = t.childCount;\n    for (var i = 0; i < n; i++) {\n      final u = findNodeSuchThat(t.getChild(i), pred);\n      if (u != null) return u;\n    }\n    return null;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/tree/tree.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport 'src/pattern/chunk.dart';\nexport 'src/pattern/parse_tree_match.dart';\nexport 'src/tree.dart';\nexport 'src/trees.dart';\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/bit_operation_util.dart",
    "content": "import 'dart:typed_data';\n\nint getBitCount(Uint32List value) {\n  var data = 0;\n  final size = value.length;\n  const m1 = 0x5555555555555555;\n  const m2 = 0x3333333333333333;\n  const m4 = 0x0F0F0F0F0F0F0F0F;\n  const m8 = 0x00FF00FF00FF00FF;\n  const m16 = 0x0000FFFF0000FFFF;\n  const h01 = 0x0101010101010101;\n\n  var bitCount = 0;\n  final limit30 = size - size % 30;\n\n  // 64-bit tree merging (merging3)\n  for (var i = 0; i < limit30; i += 30, data += 30) {\n    var acc = 0;\n    for (var j = 0; j < 30; j += 3) {\n      var count1 = value[data + j];\n      var count2 = value[data + j + 1];\n      var half1 = value[data + j + 2];\n      var half2 = half1;\n      half1 &= m1;\n      half2 = (half2 >> 1) & m1;\n      count1 -= (count1 >> 1) & m1;\n      count2 -= (count2 >> 1) & m1;\n      count1 += half1;\n      count2 += half2;\n      count1 = (count1 & m2) + ((count1 >> 2) & m2);\n      count1 += (count2 & m2) + ((count2 >> 2) & m2);\n      acc += (count1 & m4) + ((count1 >> 4) & m4);\n    }\n\n    acc = (acc & m8) + ((acc >> 8) & m8);\n    acc = (acc + (acc >> 16)) & m16;\n    acc = acc + (acc >> 32);\n    bitCount += acc;\n  }\n\n  // count the bits of the remaining bytes (MAX 29*8) using\n  // \"Counting bits set, in parallel\" from the \"Bit Twiddling Hacks\",\n  // the code uses wikipedia's 64-bit popcount_3() implementation:\n  // http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation\n  for (var i = 0; i < size - limit30; i++) {\n    var x = value[data + i];\n    x = x - ((x >> 1) & m1);\n    x = (x & m2) + ((x >> 2) & m2);\n    x = (x + (x >> 4)) & m4;\n    bitCount += ((x * h01) >> 56);\n  }\n\n  return bitCount;\n}\n\nfinal List<int> index64 = [\n  0,\n  47,\n  1,\n  56,\n  48,\n  27,\n  2,\n  60,\n  57,\n  49,\n  41,\n  37,\n  28,\n  16,\n  3,\n  61,\n  54,\n  58,\n  35,\n  52,\n  50,\n  42,\n  21,\n  44,\n  38,\n  32,\n  29,\n  23,\n  17,\n  11,\n  4,\n  62,\n  46,\n  55,\n  26,\n  59,\n  40,\n  36,\n  15,\n  53,\n  34,\n  51,\n  20,\n  43,\n  31,\n  22,\n  10,\n  45,\n  25,\n  39,\n  14,\n  33,\n  19,\n  30,\n  9,\n  24,\n  13,\n  18,\n  8,\n  12,\n  7,\n  6,\n  5,\n  63\n];\n\nint BitScanForward(int value) {\n  if (value == 0) return -1;\n\n  const debruijn64 = 0x03f79d71b4cb0a89;\n  return index64[(((value ^ (value - 1)) * debruijn64) >> 58) % 64];\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/bit_operation_util_html.dart",
    "content": "import 'dart:typed_data';\n\n/// Dart2JS does not support int64; use the alternatives.\n/// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel\n\nint getBitCount(Uint32List value) {\n  var bitCount = 0;\n  for (var v in value) {\n    v -= ((v >> 1) & 0x55555555);\n    v = (v & 0x33333333) + ((v >> 2) & 0x33333333);\n    bitCount += (((v + (v >> 4) & 0xf0f0f0f) * 0x1010101) >> 24);\n  }\n  return bitCount;\n}\n\nfinal List<int> index32 = [\n  0,\n  9,\n  1,\n  10,\n  13,\n  21,\n  2,\n  29,\n  11,\n  14,\n  16,\n  18,\n  22,\n  25,\n  3,\n  30,\n  8,\n  12,\n  20,\n  28,\n  15,\n  17,\n  24,\n  7,\n  19,\n  27,\n  23,\n  6,\n  26,\n  5,\n  4,\n  31\n];\n\nint BitScanForward(int value) {\n  if (value == 0) return -1;\n\n  const debruijn32 = 0x07c4acdd;\n  return index32[((value ^ (value - 1)) * debruijn32) >> 27];\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/bit_set.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:math';\nimport 'dart:typed_data';\n\nimport 'bit_operation_util.dart'\n    if (dart.library.html) 'bit_operation_util_html.dart' as util;\n\nclass BitSet {\n  static final Uint32List EmptyBits = Uint32List(0);\n  static const BitsPerElement = 32;\n\n  Uint32List _data = EmptyBits;\n\n  BitSet([int nbits = 0]) {\n    if (nbits == 0) {\n      return;\n    }\n    if (nbits < 0) throw RangeError('nbits');\n\n    if (nbits > 0) {\n      final length = ((nbits + BitsPerElement - 1) / BitsPerElement).floor();\n      _data = Uint32List(length);\n    }\n  }\n\n  BitSet clone() {\n    final result = BitSet();\n    result._data = Uint32List.fromList(_data);\n    return result;\n  }\n\n  void clear(int index) {\n    if (index < 0) throw RangeError('index');\n\n    final element = (index / BitsPerElement).floor();\n    if (element >= _data.length) return;\n\n    _data[element] &= ~(1 << (index % BitsPerElement));\n  }\n\n  bool operator [](int index) {\n    return get(index);\n  }\n\n  bool get(int index) {\n    if (index < 0) throw RangeError.value(index, 'index');\n\n    final element = (index / BitsPerElement).floor();\n    if (element >= _data.length) return false;\n\n    return (_data[element] & (1 << (index % BitsPerElement))) != 0;\n  }\n\n  void set(int index) {\n    if (index < 0) throw RangeError.value(index, 'index');\n\n    final element = (index / BitsPerElement).floor();\n    if (element >= _data.length) {\n      final newList = Uint32List(max(_data.length * 2, element + 1))\n        ..setRange(0, _data.length, _data);\n      _data = newList;\n    }\n    _data[element] |= 1 << (index % BitsPerElement);\n  }\n\n  bool get isEmpty {\n    for (var i = 0; i < _data.length; i++) {\n      if (_data[i] != 0) return false;\n    }\n\n    return true;\n  }\n\n  int get cardinality {\n    return util.getBitCount(_data);\n  }\n\n  int nextset(int fromIndex) {\n    if (fromIndex < 0) throw RangeError('fromIndex');\n\n    if (isEmpty) return -1;\n\n    var i = (fromIndex / BitsPerElement).floor();\n    if (i >= _data.length) return -1;\n\n    var current = _data[i] & ~((1 << (fromIndex % BitsPerElement)) - 1);\n\n    while (true) {\n      final bit = util.BitScanForward(current);\n      if (bit >= 0) return bit + i * BitsPerElement;\n\n      i++;\n      if (i >= _data.length) break;\n\n      current = _data[i];\n    }\n\n    return -1;\n  }\n\n  void and(BitSet set) {\n    final length = min(_data.length, set._data.length);\n    for (var i = 0; i < length; i++) {\n      _data[i] &= set._data[i];\n    }\n\n    for (var i = length; i < _data.length; i++) {\n      _data[i] = 0;\n    }\n  }\n\n  void or(BitSet set) {\n    if (set._data.length > _data.length) {\n      final newList = Uint32List(set._data.length)\n        ..setRange(0, _data.length, _data);\n      _data = newList;\n    }\n\n    for (var i = 0; i < set._data.length; i++) {\n      _data[i] |= set._data[i];\n    }\n  }\n\n  @override\n  bool operator ==(obj) {\n    final other = obj as BitSet;\n\n    if (isEmpty) return other.isEmpty;\n\n    final minlength = min(_data.length, other._data.length);\n    for (var i = 0; i < minlength; i++) {\n      if (_data[i] != other._data[i]) return false;\n    }\n\n    for (var i = minlength; i < _data.length; i++) {\n      if (_data[i] != 0) return false;\n    }\n\n    for (var i = minlength; i < other._data.length; i++) {\n      if (other._data[i] != 0) return false;\n    }\n\n    return true;\n  }\n\n  @override\n  int get hashCode {\n    var result = 1;\n    for (var i = 0; i < _data.length; i++) {\n      if (_data[i] != 0) {\n        result = result * 31 ^ i;\n        result = result * 31 ^ _data[i];\n      }\n    }\n\n    return result.hashCode;\n  }\n\n  @override\n  String toString() {\n    final builder = StringBuffer();\n    builder.write('{');\n\n    for (var i = nextset(0); i >= 0; i = nextset(i + 1)) {\n      if (builder.length > 1) builder.write(', ');\n\n      builder.write(i);\n    }\n\n    builder.write('}');\n    return builder.toString();\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/murmur_hash.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nclass MurmurHash {\n  static final int DEFAULT_SEED = 0;\n\n  /// Initialize the hash using the specified [seed].\n  ///\n  /// @param seed the seed\n  /// @return the intermediate hash value\n  static int initialize([int? seed]) {\n    return seed ?? DEFAULT_SEED;\n  }\n\n  /// Update the intermediate hash value for the next input [value].\n  ///\n  /// @param hash the intermediate hash value\n  /// @param value the value to add to the current hash\n  /// @return the updated intermediate hash value\n  static int update(int hash, [value]) {\n    final c1 = 0xCC9E2D51;\n    final c2 = 0x1B873593;\n    final r1 = 15;\n    final r2 = 13;\n    final m = 5;\n    final n = 0xE6546B64;\n\n    var k = value is int ? value : value?.hashCode ?? 0;\n\n    k = k * c1;\n    k = (k << r1) | (k >> (32 - r1));\n    k = k * c2;\n\n    hash = hash ^ k;\n    hash = (hash << r2) | (hash >> (32 - r2));\n    hash = hash * m + n;\n\n    return hash;\n  }\n\n  /// Apply the final computation steps to the intermediate value [hash]\n  /// to form the final result of the MurmurHash 3 hash function.\n  ///\n  /// @param hash the intermediate hash value\n  /// @param numberOfWords the number of integer values added to the hash\n  /// @return the final hash result\n  static int finish(int hash, int numberOfWords) {\n    hash = hash ^ (numberOfWords * 4);\n    hash = hash ^ (hash >> 16);\n    hash = hash * 0x85EBCA6B;\n    hash = hash ^ (hash >> 13);\n    hash = hash * 0xC2B2AE35;\n    hash = hash ^ (hash >> 16);\n    return hash;\n  }\n\n  /// Utility function to compute the hash code of an array using the\n  /// MurmurHash algorithm.\n  ///\n  /// @param <T> the array element type\n  /// @param data the array data\n  /// @param seed the seed for the MurmurHash algorithm\n  /// @return the hash code of the data\n  static int getHashCode<T>(List<T> data, int seed) {\n    var hash = initialize(seed);\n\n    for (var value in data) {\n      hash = update(hash, value);\n    }\n\n    hash = finish(hash, data.length);\n    return hash;\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/platform_html.dart",
    "content": "import 'dart:html';\n\n/// Creates a new independent [Stream] for the contents of the file on [path].\nStream<List<int>> readStream(String path) => throw UnsupportedError(\n    'dart:html does not support read stream from a file');\n\n/// Prints a string representation of the object.\nvoid stdoutWrite(Object? object) => throw UnsupportedError(\n    'dart:html does not support write without a newline');\n\n/// Prints a string representation of the [object] to the error stream.\n///\n/// Each call appends an additional newline to the object's string\n/// representation.\nvoid stderrWriteln(Object? object) => window.console.error(object);\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/platform_io.dart",
    "content": "import 'dart:io';\n\n/// Creates a new independent [Stream] for the contents of the file on [path].\nStream<List<int>> readStream(String path) => File(path).openRead();\n\n/// Prints a string representation of the object.\nvoid stdoutWrite(Object? object) => stdout.write(object);\n\n/// Prints a string representation of the [object] to the error stream.\n///\n/// Each call appends an additional newline to the object's string\n/// representation.\nvoid stderrWriteln(Object? object) => stderr.writeln(object);\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/platform_stub.dart",
    "content": "/// Creates a new independent [Stream] for the contents of the file on [path].\nStream<List<int>> readStream(String path) =>\n    throw UnsupportedError('Cannot read a file stream without dart:io');\n\n/// Prints a string representation of the object.\nvoid stdoutWrite(Object? object) =>\n    throw UnsupportedError('Cannot do stdout#write without dart:io');\n\n/// Prints a string representation of the [object] to the error stream.\n///\n/// Each call appends an additional newline to the object's string\n/// representation.\nvoid stderrWriteln(Object? object) => throw UnsupportedError(\n    'Cannot do writeln to the error stream without dart:io or dart:html');\n"
  },
  {
    "path": "runtime/Dart/lib/src/util/utils.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/// Convert array of strings to string&rarr;index map. Useful for\n///  converting rulenames to name&rarr;ruleindex map.\nMap<String, int> toMap(List<String> keys) {\n  final m = <String, int>{};\n  for (var i = 0; i < keys.length; i++) {\n    m[keys[i]] = i;\n  }\n  return m;\n}\n\nString arrayToString(a) {\n  return '[' + a.join(', ') + ']';\n}\n\nString escapeWhitespace(String s, [bool escapeSpaces = false]) {\n  if (escapeSpaces) s = s.replaceAll(' ', '\\u00B7');\n  s = s.replaceAll('\\n', r'\\n');\n  s = s.replaceAll('\\r', r'\\r');\n  s = s.replaceAll('\\t', r'\\t');\n  return s;\n}\n\nbool isLowerCase(String s) => s.toLowerCase() == s;\n\nbool isUpperCase(String s) => s.toUpperCase() == s;\n"
  },
  {
    "path": "runtime/Dart/lib/src/vocabulary.dart",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport 'dart:math';\n\nimport 'token.dart';\n\n/// This interface provides information about the vocabulary used by a\n/// recognizer.\n///\n/// @see Recognizer#getVocabulary()\nabstract class Vocabulary {\n  /// Returns the highest token type value. It can be used to iterate from\n  /// zero to that number, inclusively, thus querying all stored entries.\n  /// @return the highest token type value\n  int get maxTokenType;\n\n  /// Gets the string literal associated with a token type. The string returned\n  /// by this method, when not null, can be used unaltered in a parser\n  /// grammar to represent this token type.\n  ///\n  /// <p>The following table shows examples of lexer rules and the literal\n  /// names assigned to the corresponding token types.</p>\n  ///\n  /// <table>\n  ///  <tr>\n  ///   <th>Rule</th>\n  ///   <th>Literal Name</th>\n  ///   <th>Java String Literal</th>\n  ///  </tr>\n  ///  <tr>\n  ///   <td>{@code THIS : 'this';}</td>\n  ///   <td>{@code 'this'}</td>\n  ///   <td>{@code \"'this'\"}</td>\n  ///  </tr>\n  ///  <tr>\n  ///   <td>{@code SQUOTE : '\\'';}</td>\n  ///   <td>{@code '\\''}</td>\n  ///   <td>{@code \"'\\\\''\"}</td>\n  ///  </tr>\n  ///  <tr>\n  ///   <td>{@code ID : [A-Z]+;}</td>\n  ///   <td>n/a</td>\n  ///   <td>null</td>\n  ///  </tr>\n  /// </table>\n  ///\n  /// @param tokenType The token type.\n  ///\n  /// @return The string literal associated with the specified token type, or\n  /// null if no string literal is associated with the type.\n  String? getLiteralName(int tokenType);\n\n  /// Gets the symbolic name associated with a token type. The string returned\n  /// by this method, when not null, can be used unaltered in a parser\n  /// grammar to represent this token type.\n  ///\n  /// <p>This method supports token types defined by any of the following\n  /// methods:</p>\n  ///\n  /// <ul>\n  ///  <li>Tokens created by lexer rules.</li>\n  ///  <li>Tokens defined in a <code>tokens{}</code> block in a lexer or parser\n  ///  grammar.</li>\n  ///  <li>The implicitly defined [EOF] token, which has the token type\n  ///  {@link Token#EOF}.</li>\n  /// </ul>\n  ///\n  /// <p>The following table shows examples of lexer rules and the literal\n  /// names assigned to the corresponding token types.</p>\n  ///\n  /// <table>\n  ///  <tr>\n  ///   <th>Rule</th>\n  ///   <th>Symbolic Name</th>\n  ///  </tr>\n  ///  <tr>\n  ///   <td>{@code THIS : 'this';}</td>\n  ///   <td>[THIS]</td>\n  ///  </tr>\n  ///  <tr>\n  ///   <td>{@code SQUOTE : '\\'';}</td>\n  ///   <td>[SQUOTE]</td>\n  ///  </tr>\n  ///  <tr>\n  ///   <td>{@code ID : [A-Z]+;}</td>\n  ///   <td>[ID]</td>\n  ///  </tr>\n  /// </table>\n  ///\n  /// @param tokenType The token type.\n  ///\n  /// @return The symbolic name associated with the specified token type, or\n  /// null if no symbolic name is associated with the type.\n  String? getSymbolicName(int tokenType);\n\n  /// Gets the display name of a token type.\n  ///\n  /// <p>ANTLR provides a default implementation of this method, but\n  /// applications are free to override the behavior in any manner which makes\n  /// sense for the application. The default implementation returns the first\n  /// result from the following list which produces a non-null\n  /// result.</p>\n  ///\n  /// <ol>\n  ///  <li>The result of {@link #getLiteralName}</li>\n  ///  <li>The result of {@link #getSymbolicName}</li>\n  ///  <li>The result of {@link Integer#toString}</li>\n  /// </ol>\n  ///\n  /// @param tokenType The token type.\n  ///\n  /// @return The display name of the token type, for use in error reporting or\n  /// other user-visible messages which reference specific token types.\n  String getDisplayName(int tokenType);\n}\n\n/// This class provides a default implementation of the [Vocabulary]\n/// interface.\nclass VocabularyImpl implements Vocabulary {\n  static const List<String> EMPTY_NAMES = [];\n\n  /// Gets an empty [Vocabulary] instance.\n  ///\n  /// <p>\n  /// No literal or symbol names are assigned to token types, so\n  /// {@link #getDisplayName(int)} returns the numeric value for all tokens\n  /// except {@link Token#EOF}.</p>\n  static final VocabularyImpl EMPTY_VOCABULARY =\n      VocabularyImpl(EMPTY_NAMES, EMPTY_NAMES, EMPTY_NAMES);\n\n  final List<String?> literalNames;\n\n  final List<String?> symbolicNames;\n\n  final List<String?> displayNames;\n\n  @override\n  late int maxTokenType;\n\n  /// Constructs a new instance of [VocabularyImpl] from the specified\n  /// literal, symbolic, and display token names.\n  ///\n  /// @param literalNames The literal names assigned to tokens, or null\n  /// if no literal names are assigned.\n  /// @param symbolicNames The symbolic names assigned to tokens, or\n  /// null if no symbolic names are assigned.\n  /// @param displayNames The display names assigned to tokens, or null\n  /// to use the values in [literalNames] and [symbolicNames] as\n  /// the source of display names, as described in\n  /// {@link #getDisplayName(int)}.\n  ///\n  /// @see #getLiteralName(int)\n  /// @see #getSymbolicName(int)\n  /// @see #getDisplayName(int)\n  VocabularyImpl(\n    this.literalNames,\n    this.symbolicNames, [\n    this.displayNames = EMPTY_NAMES,\n  ]) {\n    // See note here on -1 part: https://github.com/antlr/antlr4/pull/1146\n    maxTokenType = max(displayNames.length,\n            max(literalNames.length, symbolicNames.length)) -\n        1;\n  }\n\n  /// Returns a [VocabularyImpl] instance from the specified set of token\n  /// names. This method acts as a compatibility layer for the single\n  /// [tokenNames] array generated by previous releases of ANTLR.\n  ///\n  /// <p>The resulting vocabulary instance returns null for\n  /// {@link #getLiteralName(int)} and {@link #getSymbolicName(int)}, and the\n  /// value from [tokenNames] for the display names.</p>\n  ///\n  /// @param tokenNames The token names, or null if no token names are\n  /// available.\n  /// @return A [Vocabulary] instance which uses [tokenNames] for\n  /// the display names of tokens.\n  static Vocabulary fromTokenNames(List<String?>? tokenNames) {\n    if (tokenNames == null || tokenNames.isEmpty) {\n      return EMPTY_VOCABULARY;\n    }\n\n    final literalNames = List<String?>.from(tokenNames);\n    final symbolicNames = List<String?>.from(tokenNames);\n    for (var i = 0; i < tokenNames.length; i++) {\n      final tokenName = tokenNames[i];\n      if (tokenName == null) {\n        continue;\n      }\n\n      if (tokenName.isNotEmpty) {\n        final firstChar = tokenName[0];\n        if (firstChar == '\\'') {\n          symbolicNames[i] = null;\n          continue;\n        } else if (firstChar.toUpperCase() == firstChar) {\n          literalNames[i] = null;\n          continue;\n        }\n      }\n\n      // wasn't a literal or symbolic name\n      literalNames[i] = null;\n      symbolicNames[i] = null;\n    }\n\n    return VocabularyImpl(literalNames, symbolicNames, tokenNames);\n  }\n\n  @override\n  String? getLiteralName(int tokenType) {\n    if (tokenType >= 0 && tokenType < literalNames.length) {\n      return literalNames[tokenType];\n    }\n\n    return null;\n  }\n\n  @override\n  String? getSymbolicName(int tokenType) {\n    if (tokenType >= 0 && tokenType < symbolicNames.length) {\n      return symbolicNames[tokenType];\n    }\n\n    if (tokenType == Token.EOF) {\n      return 'EOF';\n    }\n\n    return null;\n  }\n\n  @override\n  String getDisplayName(int tokenType) {\n    if (tokenType >= 0 && tokenType < displayNames.length) {\n      final displayName = displayNames[tokenType];\n      if (displayName != null) {\n        return displayName;\n      }\n    }\n\n    final literalName = getLiteralName(tokenType);\n    if (literalName != null) {\n      return literalName;\n    }\n\n    final symbolicName = getSymbolicName(tokenType);\n    if (symbolicName != null) {\n      return symbolicName;\n    }\n\n    return tokenType.toString();\n  }\n}\n"
  },
  {
    "path": "runtime/Dart/pubspec.yaml",
    "content": "name: \"antlr4\"\nversion: \"4.13.2\"\ndescription: \"New Dart runtime for ANTLR4.\"\nhomepage: \"https://github.com/antlr/antlr4\"\nlicense: \"BSD-3-Clause\"\ndependencies: \n  logging: ^1.0.0\n  collection: ^1.15.0\ndev_dependencies:\n  pedantic: ^1.11.0\n  test: ^1.17.10\n  benchmark_harness: ^2.0.0\n\nenvironment:\n  sdk: \">=2.12.0 <3.0.0\"\n"
  },
  {
    "path": "runtime/Dart/test/src/util/bit_set_test.dart",
    "content": "// Import the test package and Counter class\nimport 'package:test/test.dart';\nimport 'package:antlr4/src/util/bit_set.dart';\n\nvoid main() {\n  void _testBitSetBasicSet(int value) {\n    test('Gets $value after setting position', () {\n      var bs = BitSet();\n      bs.set(value);\n      expect(bs.toString(), '{$value}');\n    });\n  }\n  _testBitSetBasicSet(15);\n  _testBitSetBasicSet(31);\n  _testBitSetBasicSet(32);\n  _testBitSetBasicSet(57);\n  _testBitSetBasicSet(63);\n  _testBitSetBasicSet(64);\n  _testBitSetBasicSet(128);\n  _testBitSetBasicSet(256);\n}\n"
  },
  {
    "path": "runtime/Go/antlr/README.adoc",
    "content": "= Migration to v4\n\n== If you are using `GOPATH` and not modules\n\nPlease note that the source code that was previously located in this directory is now located in the official release repository at: github.com/antlr4-go/antlr please use the code in that repo if you have a reason not to use modules.\n\n== If you are using modules\n\nYour driver code etc. should now be importing from the new release only repo for the runtime:\n\n```go\nimport (\n\t\"github.com/antlr4-go/antlr\"\n)\n```\n\nPlease consult\n"
  },
  {
    "path": "runtime/Go/antlr/v4/LICENSE",
    "content": "Copyright (c) 2012-2023 The ANTLR Project. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n1. Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and/or other materials provided with the distribution.\n\n3. Neither name of copyright holders nor the names of its contributors\nmay be used to endorse or promote products derived from this software\nwithout specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "runtime/Go/antlr/v4/antlrdoc.go",
    "content": "/*\nPackage antlr implements the Go version of the ANTLR 4 runtime.\n\n# The ANTLR Tool\n\nANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing,\nor translating structured text or binary files. It's widely used to build languages, tools, and frameworks.\nFrom a grammar, ANTLR generates a parser that can build parse trees and also generates a listener interface\n(or visitor) that makes it easy to respond to the recognition of phrases of interest.\n\n# Go Runtime\n\nAt version 4.11.x and prior, the Go runtime was not properly versioned for go modules. After this point, the runtime\nsource code to be imported was held in the `runtime/Go/antlr/v4` directory, and the go.mod file was updated to reflect the version of\nANTLR4 that it is compatible with (I.E. uses the /v4 path).\n\nHowever, this was found to be problematic, as it meant that with the runtime embedded so far underneath the root\nof the repo, the `go get` and related commands could not properly resolve the location of the go runtime source code.\nThis meant that the reference to the runtime in your `go.mod` file would refer to the correct source code, but would not\nlist the release tag such as @4.13.2 - this was confusing, to say the least.\n\nAs of 4.13.0, the runtime is now available as a go module in its own repo, and can be imported as `github.com/antlr4-go/antlr`\n(the go get command should also be used with this path). See the main documentation for the ANTLR4 project for more information,\nwhich is available at [ANTLR docs]. The documentation for using the Go runtime is available at [Go runtime docs].\n\nThis means that if you are using the source code without modules, you should also use the source code in the [new repo].\nThough we highly recommend that you use go modules, as they are now idiomatic for Go.\n\nI am aware that this change will prove Hyrum's Law, but am prepared to live with it for the common good.\n\nGo runtime author: [Jim Idle] jimi@idle.ws\n\n# Code Generation\n\nANTLR supports the generation of code in a number of [target languages], and the generated code is supported by a\nruntime library, written specifically to support the generated code in the target language. This library is the\nruntime for the Go target.\n\nTo generate code for the go target, it is generally recommended to place the source grammar files in a package of\ntheir own, and use the `.sh` script method of generating code, using the go generate directive. In that same directory\nit is usual, though not required, to place the antlr tool that should be used to generate the code. That does mean\nthat the antlr tool JAR file will be checked in to your source code control though, so you are, of course, free to use any other\nway of specifying the version of the ANTLR tool to use, such as aliasing in `.zshrc` or equivalent, or a profile in\nyour IDE, or configuration in your CI system. Checking in the jar does mean that it is easy to reproduce the build as\nit was at any point in its history.\n\nHere is a general/recommended template for an ANTLR based recognizer in Go:\n\n\t.\n\t├── parser\n\t│     ├── mygrammar.g4\n\t│     ├── antlr-4.13.2-complete.jar\n\t│     ├── generate.go\n\t│     └── generate.sh\n\t├── parsing   - generated code goes here\n\t│     └── error_listeners.go\n\t├── go.mod\n\t├── go.sum\n\t├── main.go\n\t└── main_test.go\n\nMake sure that the package statement in your grammar file(s) reflects the go package the generated code will exist in.\n\nThe generate.go file then looks like this:\n\n\tpackage parser\n\n\t//go:generate ./generate.sh\n\nAnd the generate.sh file will look similar to this:\n\n\t#!/bin/sh\n\n\talias antlr4='java -Xmx500M -cp \"./antlr4-4.13.2-complete.jar:$CLASSPATH\" org.antlr.v4.Tool'\n\tantlr4 -Dlanguage=Go -no-visitor -package parsing *.g4\n\ndepending on whether you want visitors or listeners or any other ANTLR options. Not that another option here\nis to generate the code into a\n\nFrom the command line at the root of your source package (location of go.mo)d) you can then simply issue the command:\n\n\tgo generate ./...\n\nWhich will generate the code for the parser, and place it in the parsing package. You can then use the generated code\nby importing the parsing package.\n\nThere are no hard and fast rules on this. It is just a recommendation. You can generate the code in any way and to anywhere you like.\n\n# Copyright Notice\n\nCopyright (c) 2012-2023 The ANTLR Project. All rights reserved.\n\nUse of this file is governed by the BSD 3-clause license, which can be found in the [LICENSE.txt] file in the project root.\n\n[target languages]: https://github.com/antlr/antlr4/tree/master/runtime\n[LICENSE.txt]: https://github.com/antlr/antlr4/blob/master/LICENSE.txt\n[ANTLR docs]: https://github.com/antlr/antlr4/blob/master/doc/index.md\n[new repo]: https://github.com/antlr4-go/antlr\n[Jim Idle]: https://github.com/jimidle\n[Go runtime docs]: https://github.com/antlr/antlr4/blob/master/doc/go-target.md\n*/\npackage antlr\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// ATNInvalidAltNumber is used to represent an ALT number that has yet to be calculated or\n// which is invalid for a particular struct such as [*antlr.BaseRuleContext]\nvar ATNInvalidAltNumber int\n\n// ATN represents an “[Augmented Transition Network]”, though general in ANTLR the term\n// “Augmented Recursive Transition Network” though there are some descriptions of “[Recursive Transition Network]”\n// in existence.\n//\n// ATNs represent the main networks in the system and are serialized by the code generator and support [ALL(*)].\n//\n// [Augmented Transition Network]: https://en.wikipedia.org/wiki/Augmented_transition_network\n// [ALL(*)]: https://www.antlr.org/papers/allstar-techreport.pdf\n// [Recursive Transition Network]: https://en.wikipedia.org/wiki/Recursive_transition_network\ntype ATN struct {\n\n\t// DecisionToState is the decision points for all rules, sub-rules, optional\n\t// blocks, ()+, ()*, etc. Each sub-rule/rule is a decision point, and we must track them, so we\n\t// can go back later and build DFA predictors for them.  This includes\n\t// all the rules, sub-rules, optional blocks, ()+, ()* etc...\n\tDecisionToState []DecisionState\n\n\t// grammarType is the ATN type and is used for deserializing ATNs from strings.\n\tgrammarType int\n\n\t// lexerActions is referenced by action transitions in the ATN for lexer ATNs.\n\tlexerActions []LexerAction\n\n\t// maxTokenType is the maximum value for any symbol recognized by a transition in the ATN.\n\tmaxTokenType int\n\n\tmodeNameToStartState map[string]*TokensStartState\n\n\tmodeToStartState []*TokensStartState\n\n\t// ruleToStartState maps from rule index to starting state number.\n\truleToStartState []*RuleStartState\n\n\t// ruleToStopState maps from rule index to stop state number.\n\truleToStopState []*RuleStopState\n\n\t// ruleToTokenType maps the rule index to the resulting token type for lexer\n\t// ATNs. For parser ATNs, it maps the rule index to the generated bypass token\n\t// type if ATNDeserializationOptions.isGenerateRuleBypassTransitions was\n\t// specified, and otherwise is nil.\n\truleToTokenType []int\n\n\t// ATNStates is a list of all states in the ATN, ordered by state number.\n\t//\n\tstates []ATNState\n\n\tmu      Mutex\n\tstateMu RWMutex\n\tedgeMu  RWMutex\n}\n\n// NewATN returns a new ATN struct representing the given grammarType and is used\n// for runtime deserialization of ATNs from the code generated by the ANTLR tool\nfunc NewATN(grammarType int, maxTokenType int) *ATN {\n\treturn &ATN{\n\t\tgrammarType:          grammarType,\n\t\tmaxTokenType:         maxTokenType,\n\t\tmodeNameToStartState: make(map[string]*TokensStartState),\n\t}\n}\n\n// NextTokensInContext computes and returns the set of valid tokens that can occur starting\n// in state s. If ctx is nil, the set of tokens will not include what can follow\n// the rule surrounding s. In other words, the set will be restricted to tokens\n// reachable staying within the rule of s.\nfunc (a *ATN) NextTokensInContext(s ATNState, ctx RuleContext) *IntervalSet {\n\treturn NewLL1Analyzer(a).Look(s, nil, ctx)\n}\n\n// NextTokensNoContext computes and returns the set of valid tokens that can occur starting\n// in state s and staying in same rule. [antlr.Token.EPSILON] is in set if we reach end of\n// rule.\nfunc (a *ATN) NextTokensNoContext(s ATNState) *IntervalSet {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\tiset := s.GetNextTokenWithinRule()\n\tif iset == nil {\n\t\tiset = a.NextTokensInContext(s, nil)\n\t\tiset.readOnly = true\n\t\ts.SetNextTokenWithinRule(iset)\n\t}\n\treturn iset\n}\n\n// NextTokens computes and returns the set of valid tokens starting in state s, by\n// calling either [NextTokensNoContext] (ctx == nil)  or [NextTokensInContext] (ctx != nil).\nfunc (a *ATN) NextTokens(s ATNState, ctx RuleContext) *IntervalSet {\n\tif ctx == nil {\n\t\treturn a.NextTokensNoContext(s)\n\t}\n\n\treturn a.NextTokensInContext(s, ctx)\n}\n\nfunc (a *ATN) addState(state ATNState) {\n\tif state != nil {\n\t\tstate.SetATN(a)\n\t\tstate.SetStateNumber(len(a.states))\n\t}\n\n\ta.states = append(a.states, state)\n}\n\nfunc (a *ATN) removeState(state ATNState) {\n\ta.states[state.GetStateNumber()] = nil // Just free the memory; don't shift states in the slice\n}\n\nfunc (a *ATN) defineDecisionState(s DecisionState) int {\n\ta.DecisionToState = append(a.DecisionToState, s)\n\ts.setDecision(len(a.DecisionToState) - 1)\n\n\treturn s.getDecision()\n}\n\nfunc (a *ATN) getDecisionState(decision int) DecisionState {\n\tif len(a.DecisionToState) == 0 {\n\t\treturn nil\n\t}\n\n\treturn a.DecisionToState[decision]\n}\n\n// getExpectedTokens computes the set of input symbols which could follow ATN\n// state number stateNumber in the specified full parse context ctx and returns\n// the set of potentially valid input symbols which could follow the specified\n// state in the specified context. This method considers the complete parser\n// context, but does not evaluate semantic predicates (i.e. all predicates\n// encountered during the calculation are assumed true). If a path in the ATN\n// exists from the starting state to the RuleStopState of the outermost context\n// without Matching any symbols, Token.EOF is added to the returned set.\n//\n// A nil ctx defaults to ParserRuleContext.EMPTY.\n//\n// It panics if the ATN does not contain state stateNumber.\nfunc (a *ATN) getExpectedTokens(stateNumber int, ctx RuleContext) *IntervalSet {\n\tif stateNumber < 0 || stateNumber >= len(a.states) {\n\t\tpanic(\"Invalid state number.\")\n\t}\n\n\ts := a.states[stateNumber]\n\tfollowing := a.NextTokens(s, nil)\n\n\tif !following.contains(TokenEpsilon) {\n\t\treturn following\n\t}\n\n\texpected := NewIntervalSet()\n\n\texpected.addSet(following)\n\texpected.removeOne(TokenEpsilon)\n\n\tfor ctx != nil && ctx.GetInvokingState() >= 0 && following.contains(TokenEpsilon) {\n\t\tinvokingState := a.states[ctx.GetInvokingState()]\n\t\trt := invokingState.GetTransitions()[0]\n\n\t\tfollowing = a.NextTokens(rt.(*RuleTransition).followState, nil)\n\t\texpected.addSet(following)\n\t\texpected.removeOne(TokenEpsilon)\n\t\tctx = ctx.GetParent().(RuleContext)\n\t}\n\n\tif following.contains(TokenEpsilon) {\n\t\texpected.addOne(TokenEOF)\n\t}\n\n\treturn expected\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn_config.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n)\n\nconst (\n\tlexerConfig  = iota // Indicates that this ATNConfig is for a lexer\n\tparserConfig        // Indicates that this ATNConfig is for a parser\n)\n\n// ATNConfig is a tuple: (ATN state, predicted alt, syntactic, semantic\n// context). The syntactic context is a graph-structured stack node whose\n// path(s) to the root is the rule invocation(s) chain used to arrive in the\n// state. The semantic context is the tree of semantic predicates encountered\n// before reaching an ATN state.\ntype ATNConfig struct {\n\tprecedenceFilterSuppressed     bool\n\tstate                          ATNState\n\talt                            int\n\tcontext                        *PredictionContext\n\tsemanticContext                SemanticContext\n\treachesIntoOuterContext        int\n\tcType                          int // lexerConfig or parserConfig\n\tlexerActionExecutor            *LexerActionExecutor\n\tpassedThroughNonGreedyDecision bool\n}\n\n// NewATNConfig6 creates a new ATNConfig instance given a state, alt and context only\nfunc NewATNConfig6(state ATNState, alt int, context *PredictionContext) *ATNConfig {\n\treturn NewATNConfig5(state, alt, context, SemanticContextNone)\n}\n\n// NewATNConfig5 creates a new ATNConfig instance given a state, alt, context and semantic context\nfunc NewATNConfig5(state ATNState, alt int, context *PredictionContext, semanticContext SemanticContext) *ATNConfig {\n\tif semanticContext == nil {\n\t\tpanic(\"semanticContext cannot be nil\") // TODO: Necessary?\n\t}\n\n\tpac := &ATNConfig{}\n\tpac.state = state\n\tpac.alt = alt\n\tpac.context = context\n\tpac.semanticContext = semanticContext\n\tpac.cType = parserConfig\n\treturn pac\n}\n\n// NewATNConfig4 creates a new ATNConfig instance given an existing config, and a state only\nfunc NewATNConfig4(c *ATNConfig, state ATNState) *ATNConfig {\n\treturn NewATNConfig(c, state, c.GetContext(), c.GetSemanticContext())\n}\n\n// NewATNConfig3 creates a new ATNConfig instance given an existing config, a state and a semantic context\nfunc NewATNConfig3(c *ATNConfig, state ATNState, semanticContext SemanticContext) *ATNConfig {\n\treturn NewATNConfig(c, state, c.GetContext(), semanticContext)\n}\n\n// NewATNConfig2 creates a new ATNConfig instance given an existing config, and a context only\nfunc NewATNConfig2(c *ATNConfig, semanticContext SemanticContext) *ATNConfig {\n\treturn NewATNConfig(c, c.GetState(), c.GetContext(), semanticContext)\n}\n\n// NewATNConfig1 creates a new ATNConfig instance given an existing config, a state, and a context only\nfunc NewATNConfig1(c *ATNConfig, state ATNState, context *PredictionContext) *ATNConfig {\n\treturn NewATNConfig(c, state, context, c.GetSemanticContext())\n}\n\n// NewATNConfig creates a new ATNConfig instance given an existing config, a state, a context and a semantic context, other 'constructors'\n// are just wrappers around this one.\nfunc NewATNConfig(c *ATNConfig, state ATNState, context *PredictionContext, semanticContext SemanticContext) *ATNConfig {\n\tb := &ATNConfig{}\n\tb.InitATNConfig(c, state, c.GetAlt(), context, semanticContext)\n\tb.cType = parserConfig\n\treturn b\n}\n\nfunc (a *ATNConfig) InitATNConfig(c *ATNConfig, state ATNState, alt int, context *PredictionContext, semanticContext SemanticContext) {\n\n\ta.state = state\n\ta.alt = alt\n\ta.context = context\n\ta.semanticContext = semanticContext\n\ta.reachesIntoOuterContext = c.GetReachesIntoOuterContext()\n\ta.precedenceFilterSuppressed = c.getPrecedenceFilterSuppressed()\n}\n\nfunc (a *ATNConfig) getPrecedenceFilterSuppressed() bool {\n\treturn a.precedenceFilterSuppressed\n}\n\nfunc (a *ATNConfig) setPrecedenceFilterSuppressed(v bool) {\n\ta.precedenceFilterSuppressed = v\n}\n\n// GetState returns the ATN state associated with this configuration\nfunc (a *ATNConfig) GetState() ATNState {\n\treturn a.state\n}\n\n// GetAlt returns the alternative associated with this configuration\nfunc (a *ATNConfig) GetAlt() int {\n\treturn a.alt\n}\n\n// SetContext sets the rule invocation stack associated with this configuration\nfunc (a *ATNConfig) SetContext(v *PredictionContext) {\n\ta.context = v\n}\n\n// GetContext returns the rule invocation stack associated with this configuration\nfunc (a *ATNConfig) GetContext() *PredictionContext {\n\treturn a.context\n}\n\n// GetSemanticContext returns the semantic context associated with this configuration\nfunc (a *ATNConfig) GetSemanticContext() SemanticContext {\n\treturn a.semanticContext\n}\n\n// GetReachesIntoOuterContext returns the count of references to an outer context from this configuration\nfunc (a *ATNConfig) GetReachesIntoOuterContext() int {\n\treturn a.reachesIntoOuterContext\n}\n\n// SetReachesIntoOuterContext sets the count of references to an outer context from this configuration\nfunc (a *ATNConfig) SetReachesIntoOuterContext(v int) {\n\ta.reachesIntoOuterContext = v\n}\n\n// Equals is the default comparison function for an ATNConfig when no specialist implementation is required\n// for a collection.\n//\n// An ATN configuration is equal to another if both have the same state, they\n// predict the same alternative, and syntactic/semantic contexts are the same.\nfunc (a *ATNConfig) Equals(o Collectable[*ATNConfig]) bool {\n\tswitch a.cType {\n\tcase lexerConfig:\n\t\treturn a.LEquals(o)\n\tcase parserConfig:\n\t\treturn a.PEquals(o)\n\tdefault:\n\t\tpanic(\"Invalid ATNConfig type\")\n\t}\n}\n\n// PEquals is the default comparison function for a Parser ATNConfig when no specialist implementation is required\n// for a collection.\n//\n// An ATN configuration is equal to another if both have the same state, they\n// predict the same alternative, and syntactic/semantic contexts are the same.\nfunc (a *ATNConfig) PEquals(o Collectable[*ATNConfig]) bool {\n\tvar other, ok = o.(*ATNConfig)\n\n\tif !ok {\n\t\treturn false\n\t}\n\tif a == other {\n\t\treturn true\n\t} else if other == nil {\n\t\treturn false\n\t}\n\n\tvar equal bool\n\n\tif a.context == nil {\n\t\tequal = other.context == nil\n\t} else {\n\t\tequal = a.context.Equals(other.context)\n\t}\n\n\tvar (\n\t\tnums = a.state.GetStateNumber() == other.state.GetStateNumber()\n\t\talts = a.alt == other.alt\n\t\tcons = a.semanticContext.Equals(other.semanticContext)\n\t\tsups = a.precedenceFilterSuppressed == other.precedenceFilterSuppressed\n\t)\n\n\treturn nums && alts && cons && sups && equal\n}\n\n// Hash is the default hash function for a parser ATNConfig, when no specialist hash function\n// is required for a collection\nfunc (a *ATNConfig) Hash() int {\n\tswitch a.cType {\n\tcase lexerConfig:\n\t\treturn a.LHash()\n\tcase parserConfig:\n\t\treturn a.PHash()\n\tdefault:\n\t\tpanic(\"Invalid ATNConfig type\")\n\t}\n}\n\n// PHash is the default hash function for a parser ATNConfig, when no specialist hash function\n// is required for a collection\nfunc (a *ATNConfig) PHash() int {\n\tvar c int\n\tif a.context != nil {\n\t\tc = a.context.Hash()\n\t}\n\n\th := murmurInit(7)\n\th = murmurUpdate(h, a.state.GetStateNumber())\n\th = murmurUpdate(h, a.alt)\n\th = murmurUpdate(h, c)\n\th = murmurUpdate(h, a.semanticContext.Hash())\n\treturn murmurFinish(h, 4)\n}\n\n// String returns a string representation of the ATNConfig, usually used for debugging purposes\nfunc (a *ATNConfig) String() string {\n\tvar s1, s2, s3 string\n\n\tif a.context != nil {\n\t\ts1 = \",[\" + fmt.Sprint(a.context) + \"]\"\n\t}\n\n\tif a.semanticContext != SemanticContextNone {\n\t\ts2 = \",\" + fmt.Sprint(a.semanticContext)\n\t}\n\n\tif a.reachesIntoOuterContext > 0 {\n\t\ts3 = \",up=\" + fmt.Sprint(a.reachesIntoOuterContext)\n\t}\n\n\treturn fmt.Sprintf(\"(%v,%v%v%v%v)\", a.state, a.alt, s1, s2, s3)\n}\n\nfunc NewLexerATNConfig6(state ATNState, alt int, context *PredictionContext) *ATNConfig {\n\tlac := &ATNConfig{}\n\tlac.state = state\n\tlac.alt = alt\n\tlac.context = context\n\tlac.semanticContext = SemanticContextNone\n\tlac.cType = lexerConfig\n\treturn lac\n}\n\nfunc NewLexerATNConfig4(c *ATNConfig, state ATNState) *ATNConfig {\n\tlac := &ATNConfig{}\n\tlac.lexerActionExecutor = c.lexerActionExecutor\n\tlac.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state)\n\tlac.InitATNConfig(c, state, c.GetAlt(), c.GetContext(), c.GetSemanticContext())\n\tlac.cType = lexerConfig\n\treturn lac\n}\n\nfunc NewLexerATNConfig3(c *ATNConfig, state ATNState, lexerActionExecutor *LexerActionExecutor) *ATNConfig {\n\tlac := &ATNConfig{}\n\tlac.lexerActionExecutor = lexerActionExecutor\n\tlac.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state)\n\tlac.InitATNConfig(c, state, c.GetAlt(), c.GetContext(), c.GetSemanticContext())\n\tlac.cType = lexerConfig\n\treturn lac\n}\n\nfunc NewLexerATNConfig2(c *ATNConfig, state ATNState, context *PredictionContext) *ATNConfig {\n\tlac := &ATNConfig{}\n\tlac.lexerActionExecutor = c.lexerActionExecutor\n\tlac.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state)\n\tlac.InitATNConfig(c, state, c.GetAlt(), context, c.GetSemanticContext())\n\tlac.cType = lexerConfig\n\treturn lac\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewLexerATNConfig1(state ATNState, alt int, context *PredictionContext) *ATNConfig {\n\tlac := &ATNConfig{}\n\tlac.state = state\n\tlac.alt = alt\n\tlac.context = context\n\tlac.semanticContext = SemanticContextNone\n\tlac.cType = lexerConfig\n\treturn lac\n}\n\n// LHash is the default hash function for Lexer ATNConfig objects, it can be used directly or via\n// the default comparator [ObjEqComparator].\nfunc (a *ATNConfig) LHash() int {\n\tvar f int\n\tif a.passedThroughNonGreedyDecision {\n\t\tf = 1\n\t} else {\n\t\tf = 0\n\t}\n\th := murmurInit(7)\n\th = murmurUpdate(h, a.state.GetStateNumber())\n\th = murmurUpdate(h, a.alt)\n\th = murmurUpdate(h, a.context.Hash())\n\th = murmurUpdate(h, a.semanticContext.Hash())\n\th = murmurUpdate(h, f)\n\th = murmurUpdate(h, a.lexerActionExecutor.Hash())\n\th = murmurFinish(h, 6)\n\treturn h\n}\n\n// LEquals is the default comparison function for Lexer ATNConfig objects, it can be used directly or via\n// the default comparator [ObjEqComparator].\nfunc (a *ATNConfig) LEquals(other Collectable[*ATNConfig]) bool {\n\tvar otherT, ok = other.(*ATNConfig)\n\tif !ok {\n\t\treturn false\n\t} else if a == otherT {\n\t\treturn true\n\t} else if a.passedThroughNonGreedyDecision != otherT.passedThroughNonGreedyDecision {\n\t\treturn false\n\t}\n\n\tswitch {\n\tcase a.lexerActionExecutor == nil && otherT.lexerActionExecutor == nil:\n\t\treturn true\n\tcase a.lexerActionExecutor != nil && otherT.lexerActionExecutor != nil:\n\t\tif !a.lexerActionExecutor.Equals(otherT.lexerActionExecutor) {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\treturn false // One but not both, are nil\n\t}\n\n\treturn a.PEquals(otherT)\n}\n\nfunc checkNonGreedyDecision(source *ATNConfig, target ATNState) bool {\n\tvar ds, ok = target.(DecisionState)\n\n\treturn source.passedThroughNonGreedyDecision || (ok && ds.getNonGreedy())\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn_config_set.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n)\n\n// ATNConfigSet is a specialized set of ATNConfig that tracks information\n// about its elements and can combine similar configurations using a\n// graph-structured stack.\ntype ATNConfigSet struct {\n\tcachedHash int\n\n\t// configLookup is used to determine whether two ATNConfigSets are equal. We\n\t// need all configurations with the same (s, i, _, semctx) to be equal. A key\n\t// effectively doubles the number of objects associated with ATNConfigs. All\n\t// keys are hashed by (s, i, _, pi), not including the context. Wiped out when\n\t// read-only because a set becomes a DFA state.\n\tconfigLookup *JStore[*ATNConfig, Comparator[*ATNConfig]]\n\n\t// configs is the added elements that did not match an existing key in configLookup\n\tconfigs []*ATNConfig\n\n\t// TODO: These fields make me pretty uncomfortable, but it is nice to pack up\n\t// info together because it saves re-computation. Can we track conflicts as they\n\t// are added to save scanning configs later?\n\tconflictingAlts *BitSet\n\n\t// dipsIntoOuterContext is used by parsers and lexers. In a lexer, it indicates\n\t// we hit a pred while computing a closure operation. Do not make a DFA state\n\t// from the ATNConfigSet in this case. TODO: How is this used by parsers?\n\tdipsIntoOuterContext bool\n\n\t// fullCtx is whether it is part of a full context LL prediction. Used to\n\t// determine how to merge $. It is a wildcard with SLL, but not for an LL\n\t// context merge.\n\tfullCtx bool\n\n\t// Used in parser and lexer. In lexer, it indicates we hit a pred\n\t// while computing a closure operation. Don't make a DFA state from this set.\n\thasSemanticContext bool\n\n\t// readOnly is whether it is read-only. Do not\n\t// allow any code to manipulate the set if true because DFA states will point at\n\t// sets and those must not change. It not, protect other fields; conflictingAlts\n\t// in particular, which is assigned after readOnly.\n\treadOnly bool\n\n\t// TODO: These fields make me pretty uncomfortable, but it is nice to pack up\n\t// info together because it saves re-computation. Can we track conflicts as they\n\t// are added to save scanning configs later?\n\tuniqueAlt int\n}\n\n// Alts returns the combined set of alts for all the configurations in this set.\nfunc (b *ATNConfigSet) Alts() *BitSet {\n\talts := NewBitSet()\n\tfor _, it := range b.configs {\n\t\talts.add(it.GetAlt())\n\t}\n\treturn alts\n}\n\n// NewATNConfigSet creates a new ATNConfigSet instance.\nfunc NewATNConfigSet(fullCtx bool) *ATNConfigSet {\n\treturn &ATNConfigSet{\n\t\tcachedHash:   -1,\n\t\tconfigLookup: NewJStore[*ATNConfig, Comparator[*ATNConfig]](aConfCompInst, ATNConfigLookupCollection, \"NewATNConfigSet()\"),\n\t\tfullCtx:      fullCtx,\n\t}\n}\n\n// Add merges contexts with existing configs for (s, i, pi, _),\n// where 's' is the ATNConfig.state, 'i' is the ATNConfig.alt, and\n// 'pi' is the [ATNConfig].semanticContext.\n//\n// We use (s,i,pi) as the key.\n// Updates dipsIntoOuterContext and hasSemanticContext when necessary.\nfunc (b *ATNConfigSet) Add(config *ATNConfig, mergeCache *JPCMap) bool {\n\tif b.readOnly {\n\t\tpanic(\"set is read-only\")\n\t}\n\n\tif config.GetSemanticContext() != SemanticContextNone {\n\t\tb.hasSemanticContext = true\n\t}\n\n\tif config.GetReachesIntoOuterContext() > 0 {\n\t\tb.dipsIntoOuterContext = true\n\t}\n\n\texisting, present := b.configLookup.Put(config)\n\n\t// The config was not already in the set\n\t//\n\tif !present {\n\t\tb.cachedHash = -1\n\t\tb.configs = append(b.configs, config) // Track order here\n\t\treturn true\n\t}\n\n\t// Merge a previous (s, i, pi, _) with it and save the result\n\trootIsWildcard := !b.fullCtx\n\tmerged := merge(existing.GetContext(), config.GetContext(), rootIsWildcard, mergeCache)\n\n\t// No need to check for existing.context because config.context is in the cache,\n\t// since the only way to create new graphs is the \"call rule\" and here. We cache\n\t// at both places.\n\texisting.SetReachesIntoOuterContext(intMax(existing.GetReachesIntoOuterContext(), config.GetReachesIntoOuterContext()))\n\n\t// Preserve the precedence filter suppression during the merge\n\tif config.getPrecedenceFilterSuppressed() {\n\t\texisting.setPrecedenceFilterSuppressed(true)\n\t}\n\n\t// Replace the context because there is no need to do alt mapping\n\texisting.SetContext(merged)\n\n\treturn true\n}\n\n// GetStates returns the set of states represented by all configurations in this config set\nfunc (b *ATNConfigSet) GetStates() *JStore[ATNState, Comparator[ATNState]] {\n\n\t// states uses the standard comparator and Hash() provided by the ATNState instance\n\t//\n\tstates := NewJStore[ATNState, Comparator[ATNState]](aStateEqInst, ATNStateCollection, \"ATNConfigSet.GetStates()\")\n\n\tfor i := 0; i < len(b.configs); i++ {\n\t\tstates.Put(b.configs[i].GetState())\n\t}\n\n\treturn states\n}\n\nfunc (b *ATNConfigSet) GetPredicates() []SemanticContext {\n\tpredicates := make([]SemanticContext, 0)\n\n\tfor i := 0; i < len(b.configs); i++ {\n\t\tc := b.configs[i].GetSemanticContext()\n\n\t\tif c != SemanticContextNone {\n\t\t\tpredicates = append(predicates, c)\n\t\t}\n\t}\n\n\treturn predicates\n}\n\nfunc (b *ATNConfigSet) OptimizeConfigs(interpreter *BaseATNSimulator) {\n\tif b.readOnly {\n\t\tpanic(\"set is read-only\")\n\t}\n\n\t// Empty indicate no optimization is possible\n\tif b.configLookup == nil || b.configLookup.Len() == 0 {\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(b.configs); i++ {\n\t\tconfig := b.configs[i]\n\t\tconfig.SetContext(interpreter.getCachedContext(config.GetContext()))\n\t}\n}\n\nfunc (b *ATNConfigSet) AddAll(coll []*ATNConfig) bool {\n\tfor i := 0; i < len(coll); i++ {\n\t\tb.Add(coll[i], nil)\n\t}\n\n\treturn false\n}\n\n// Compare The configs are only equal if they are in the same order and their Equals function returns true.\n// Java uses ArrayList.equals(), which requires the same order.\nfunc (b *ATNConfigSet) Compare(bs *ATNConfigSet) bool {\n\tif len(b.configs) != len(bs.configs) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(b.configs); i++ {\n\t\tif !b.configs[i].Equals(bs.configs[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (b *ATNConfigSet) Equals(other Collectable[ATNConfig]) bool {\n\tif b == other {\n\t\treturn true\n\t} else if _, ok := other.(*ATNConfigSet); !ok {\n\t\treturn false\n\t}\n\n\tother2 := other.(*ATNConfigSet)\n\tvar eca bool\n\tswitch {\n\tcase b.conflictingAlts == nil && other2.conflictingAlts == nil:\n\t\teca = true\n\tcase b.conflictingAlts != nil && other2.conflictingAlts != nil:\n\t\teca = b.conflictingAlts.equals(other2.conflictingAlts)\n\t}\n\treturn b.configs != nil &&\n\t\tb.fullCtx == other2.fullCtx &&\n\t\tb.uniqueAlt == other2.uniqueAlt &&\n\t\teca &&\n\t\tb.hasSemanticContext == other2.hasSemanticContext &&\n\t\tb.dipsIntoOuterContext == other2.dipsIntoOuterContext &&\n\t\tb.Compare(other2)\n}\n\nfunc (b *ATNConfigSet) Hash() int {\n\tif b.readOnly {\n\t\tif b.cachedHash == -1 {\n\t\t\tb.cachedHash = b.hashCodeConfigs()\n\t\t}\n\n\t\treturn b.cachedHash\n\t}\n\n\treturn b.hashCodeConfigs()\n}\n\nfunc (b *ATNConfigSet) hashCodeConfigs() int {\n\th := 1\n\tfor _, config := range b.configs {\n\t\th = 31*h + config.Hash()\n\t}\n\treturn h\n}\n\nfunc (b *ATNConfigSet) Contains(item *ATNConfig) bool {\n\tif b.readOnly {\n\t\tpanic(\"not implemented for read-only sets\")\n\t}\n\tif b.configLookup == nil {\n\t\treturn false\n\t}\n\treturn b.configLookup.Contains(item)\n}\n\nfunc (b *ATNConfigSet) ContainsFast(item *ATNConfig) bool {\n\treturn b.Contains(item)\n}\n\nfunc (b *ATNConfigSet) Clear() {\n\tif b.readOnly {\n\t\tpanic(\"set is read-only\")\n\t}\n\tb.configs = make([]*ATNConfig, 0)\n\tb.cachedHash = -1\n\tb.configLookup = NewJStore[*ATNConfig, Comparator[*ATNConfig]](aConfCompInst, ATNConfigLookupCollection, \"NewATNConfigSet()\")\n}\n\nfunc (b *ATNConfigSet) String() string {\n\n\ts := \"[\"\n\n\tfor i, c := range b.configs {\n\t\ts += c.String()\n\n\t\tif i != len(b.configs)-1 {\n\t\t\ts += \", \"\n\t\t}\n\t}\n\n\ts += \"]\"\n\n\tif b.hasSemanticContext {\n\t\ts += \",hasSemanticContext=\" + fmt.Sprint(b.hasSemanticContext)\n\t}\n\n\tif b.uniqueAlt != ATNInvalidAltNumber {\n\t\ts += \",uniqueAlt=\" + fmt.Sprint(b.uniqueAlt)\n\t}\n\n\tif b.conflictingAlts != nil {\n\t\ts += \",conflictingAlts=\" + b.conflictingAlts.String()\n\t}\n\n\tif b.dipsIntoOuterContext {\n\t\ts += \",dipsIntoOuterContext\"\n\t}\n\n\treturn s\n}\n\n// NewOrderedATNConfigSet creates a config set with a slightly different Hash/Equal pair\n// for use in lexers.\nfunc NewOrderedATNConfigSet() *ATNConfigSet {\n\treturn &ATNConfigSet{\n\t\tcachedHash: -1,\n\t\t// This set uses the standard Hash() and Equals() from ATNConfig\n\t\tconfigLookup: NewJStore[*ATNConfig, Comparator[*ATNConfig]](aConfEqInst, ATNConfigCollection, \"ATNConfigSet.NewOrderedATNConfigSet()\"),\n\t\tfullCtx:      false,\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn_deserialization_options.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport \"errors\"\n\nvar defaultATNDeserializationOptions = ATNDeserializationOptions{true, true, false}\n\ntype ATNDeserializationOptions struct {\n\treadOnly                      bool\n\tverifyATN                     bool\n\tgenerateRuleBypassTransitions bool\n}\n\nfunc (opts *ATNDeserializationOptions) ReadOnly() bool {\n\treturn opts.readOnly\n}\n\nfunc (opts *ATNDeserializationOptions) SetReadOnly(readOnly bool) {\n\tif opts.readOnly {\n\t\tpanic(errors.New(\"cannot mutate read only ATNDeserializationOptions\"))\n\t}\n\topts.readOnly = readOnly\n}\n\nfunc (opts *ATNDeserializationOptions) VerifyATN() bool {\n\treturn opts.verifyATN\n}\n\nfunc (opts *ATNDeserializationOptions) SetVerifyATN(verifyATN bool) {\n\tif opts.readOnly {\n\t\tpanic(errors.New(\"cannot mutate read only ATNDeserializationOptions\"))\n\t}\n\topts.verifyATN = verifyATN\n}\n\nfunc (opts *ATNDeserializationOptions) GenerateRuleBypassTransitions() bool {\n\treturn opts.generateRuleBypassTransitions\n}\n\nfunc (opts *ATNDeserializationOptions) SetGenerateRuleBypassTransitions(generateRuleBypassTransitions bool) {\n\tif opts.readOnly {\n\t\tpanic(errors.New(\"cannot mutate read only ATNDeserializationOptions\"))\n\t}\n\topts.generateRuleBypassTransitions = generateRuleBypassTransitions\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc DefaultATNDeserializationOptions() *ATNDeserializationOptions {\n\treturn NewATNDeserializationOptions(&defaultATNDeserializationOptions)\n}\n\nfunc NewATNDeserializationOptions(other *ATNDeserializationOptions) *ATNDeserializationOptions {\n\to := new(ATNDeserializationOptions)\n\tif other != nil {\n\t\t*o = *other\n\t\to.readOnly = false\n\t}\n\treturn o\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn_deserializer.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nconst serializedVersion = 4\n\ntype loopEndStateIntPair struct {\n\titem0 *LoopEndState\n\titem1 int\n}\n\ntype blockStartStateIntPair struct {\n\titem0 BlockStartState\n\titem1 int\n}\n\ntype ATNDeserializer struct {\n\toptions *ATNDeserializationOptions\n\tdata    []int32\n\tpos     int\n}\n\nfunc NewATNDeserializer(options *ATNDeserializationOptions) *ATNDeserializer {\n\tif options == nil {\n\t\toptions = &defaultATNDeserializationOptions\n\t}\n\n\treturn &ATNDeserializer{options: options}\n}\n\n//goland:noinspection GoUnusedFunction\nfunc stringInSlice(a string, list []string) int {\n\tfor i, b := range list {\n\t\tif b == a {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}\n\nfunc (a *ATNDeserializer) Deserialize(data []int32) *ATN {\n\ta.data = data\n\ta.pos = 0\n\ta.checkVersion()\n\n\tatn := a.readATN()\n\n\ta.readStates(atn)\n\ta.readRules(atn)\n\ta.readModes(atn)\n\n\tsets := a.readSets(atn, nil)\n\n\ta.readEdges(atn, sets)\n\ta.readDecisions(atn)\n\ta.readLexerActions(atn)\n\ta.markPrecedenceDecisions(atn)\n\ta.verifyATN(atn)\n\n\tif a.options.GenerateRuleBypassTransitions() && atn.grammarType == ATNTypeParser {\n\t\ta.generateRuleBypassTransitions(atn)\n\t\t// Re-verify after modification\n\t\ta.verifyATN(atn)\n\t}\n\n\treturn atn\n\n}\n\nfunc (a *ATNDeserializer) checkVersion() {\n\tversion := a.readInt()\n\n\tif version != serializedVersion {\n\t\tpanic(\"Could not deserialize ATN with version \" + strconv.Itoa(version) + \" (expected \" + strconv.Itoa(serializedVersion) + \").\")\n\t}\n}\n\nfunc (a *ATNDeserializer) readATN() *ATN {\n\tgrammarType := a.readInt()\n\tmaxTokenType := a.readInt()\n\n\treturn NewATN(grammarType, maxTokenType)\n}\n\nfunc (a *ATNDeserializer) readStates(atn *ATN) {\n\tnstates := a.readInt()\n\n\t// Allocate worst case size.\n\tloopBackStateNumbers := make([]loopEndStateIntPair, 0, nstates)\n\tendStateNumbers := make([]blockStartStateIntPair, 0, nstates)\n\n\t// Preallocate states slice.\n\tatn.states = make([]ATNState, 0, nstates)\n\n\tfor i := 0; i < nstates; i++ {\n\t\tstype := a.readInt()\n\n\t\t// Ignore bad types of states\n\t\tif stype == ATNStateInvalidType {\n\t\t\tatn.addState(nil)\n\t\t\tcontinue\n\t\t}\n\n\t\truleIndex := a.readInt()\n\n\t\ts := a.stateFactory(stype, ruleIndex)\n\n\t\tif stype == ATNStateLoopEnd {\n\t\t\tloopBackStateNumber := a.readInt()\n\n\t\t\tloopBackStateNumbers = append(loopBackStateNumbers, loopEndStateIntPair{s.(*LoopEndState), loopBackStateNumber})\n\t\t} else if s2, ok := s.(BlockStartState); ok {\n\t\t\tendStateNumber := a.readInt()\n\n\t\t\tendStateNumbers = append(endStateNumbers, blockStartStateIntPair{s2, endStateNumber})\n\t\t}\n\n\t\tatn.addState(s)\n\t}\n\n\t// Delay the assignment of loop back and end states until we know all the state\n\t// instances have been initialized\n\tfor _, pair := range loopBackStateNumbers {\n\t\tpair.item0.loopBackState = atn.states[pair.item1]\n\t}\n\n\tfor _, pair := range endStateNumbers {\n\t\tpair.item0.setEndState(atn.states[pair.item1].(*BlockEndState))\n\t}\n\n\tnumNonGreedyStates := a.readInt()\n\tfor j := 0; j < numNonGreedyStates; j++ {\n\t\tstateNumber := a.readInt()\n\n\t\tatn.states[stateNumber].(DecisionState).setNonGreedy(true)\n\t}\n\n\tnumPrecedenceStates := a.readInt()\n\tfor j := 0; j < numPrecedenceStates; j++ {\n\t\tstateNumber := a.readInt()\n\n\t\tatn.states[stateNumber].(*RuleStartState).isPrecedenceRule = true\n\t}\n}\n\nfunc (a *ATNDeserializer) readRules(atn *ATN) {\n\tnrules := a.readInt()\n\n\tif atn.grammarType == ATNTypeLexer {\n\t\tatn.ruleToTokenType = make([]int, nrules)\n\t}\n\n\tatn.ruleToStartState = make([]*RuleStartState, nrules)\n\n\tfor i := range atn.ruleToStartState {\n\t\ts := a.readInt()\n\t\tstartState := atn.states[s].(*RuleStartState)\n\n\t\tatn.ruleToStartState[i] = startState\n\n\t\tif atn.grammarType == ATNTypeLexer {\n\t\t\ttokenType := a.readInt()\n\n\t\t\tatn.ruleToTokenType[i] = tokenType\n\t\t}\n\t}\n\n\tatn.ruleToStopState = make([]*RuleStopState, nrules)\n\n\tfor _, state := range atn.states {\n\t\tif s2, ok := state.(*RuleStopState); ok {\n\t\t\tatn.ruleToStopState[s2.ruleIndex] = s2\n\t\t\tatn.ruleToStartState[s2.ruleIndex].stopState = s2\n\t\t}\n\t}\n}\n\nfunc (a *ATNDeserializer) readModes(atn *ATN) {\n\tnmodes := a.readInt()\n\tatn.modeToStartState = make([]*TokensStartState, nmodes)\n\n\tfor i := range atn.modeToStartState {\n\t\ts := a.readInt()\n\n\t\tatn.modeToStartState[i] = atn.states[s].(*TokensStartState)\n\t}\n}\n\nfunc (a *ATNDeserializer) readSets(_ *ATN, sets []*IntervalSet) []*IntervalSet {\n\tm := a.readInt()\n\n\t// Preallocate the needed capacity.\n\tif cap(sets)-len(sets) < m {\n\t\tisets := make([]*IntervalSet, len(sets), len(sets)+m)\n\t\tcopy(isets, sets)\n\t\tsets = isets\n\t}\n\n\tfor i := 0; i < m; i++ {\n\t\tiset := NewIntervalSet()\n\n\t\tsets = append(sets, iset)\n\n\t\tn := a.readInt()\n\t\tcontainsEOF := a.readInt()\n\n\t\tif containsEOF != 0 {\n\t\t\tiset.addOne(-1)\n\t\t}\n\n\t\tfor j := 0; j < n; j++ {\n\t\t\ti1 := a.readInt()\n\t\t\ti2 := a.readInt()\n\n\t\t\tiset.addRange(i1, i2)\n\t\t}\n\t}\n\n\treturn sets\n}\n\nfunc (a *ATNDeserializer) readEdges(atn *ATN, sets []*IntervalSet) {\n\tnedges := a.readInt()\n\n\tfor i := 0; i < nedges; i++ {\n\t\tvar (\n\t\t\tsrc      = a.readInt()\n\t\t\ttrg      = a.readInt()\n\t\t\tttype    = a.readInt()\n\t\t\targ1     = a.readInt()\n\t\t\targ2     = a.readInt()\n\t\t\targ3     = a.readInt()\n\t\t\ttrans    = a.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets)\n\t\t\tsrcState = atn.states[src]\n\t\t)\n\n\t\tsrcState.AddTransition(trans, -1)\n\t}\n\n\t// Edges for rule stop states can be derived, so they are not serialized\n\tfor _, state := range atn.states {\n\t\tfor _, t := range state.GetTransitions() {\n\t\t\tvar rt, ok = t.(*RuleTransition)\n\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\toutermostPrecedenceReturn := -1\n\n\t\t\tif atn.ruleToStartState[rt.getTarget().GetRuleIndex()].isPrecedenceRule {\n\t\t\t\tif rt.precedence == 0 {\n\t\t\t\t\toutermostPrecedenceReturn = rt.getTarget().GetRuleIndex()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttrans := NewEpsilonTransition(rt.followState, outermostPrecedenceReturn)\n\n\t\t\tatn.ruleToStopState[rt.getTarget().GetRuleIndex()].AddTransition(trans, -1)\n\t\t}\n\t}\n\n\tfor _, state := range atn.states {\n\t\tif s2, ok := state.(BlockStartState); ok {\n\t\t\t// We need to know the end state to set its start state\n\t\t\tif s2.getEndState() == nil {\n\t\t\t\tpanic(\"IllegalState\")\n\t\t\t}\n\n\t\t\t// Block end states can only be associated to a single block start state\n\t\t\tif s2.getEndState().startState != nil {\n\t\t\t\tpanic(\"IllegalState\")\n\t\t\t}\n\n\t\t\ts2.getEndState().startState = state\n\t\t}\n\n\t\tif s2, ok := state.(*PlusLoopbackState); ok {\n\t\t\tfor _, t := range s2.GetTransitions() {\n\t\t\t\tif t2, ok := t.getTarget().(*PlusBlockStartState); ok {\n\t\t\t\t\tt2.loopBackState = state\n\t\t\t\t}\n\t\t\t}\n\t\t} else if s2, ok := state.(*StarLoopbackState); ok {\n\t\t\tfor _, t := range s2.GetTransitions() {\n\t\t\t\tif t2, ok := t.getTarget().(*StarLoopEntryState); ok {\n\t\t\t\t\tt2.loopBackState = state\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (a *ATNDeserializer) readDecisions(atn *ATN) {\n\tndecisions := a.readInt()\n\n\tfor i := 0; i < ndecisions; i++ {\n\t\ts := a.readInt()\n\t\tdecState := atn.states[s].(DecisionState)\n\n\t\tatn.DecisionToState = append(atn.DecisionToState, decState)\n\t\tdecState.setDecision(i)\n\t}\n}\n\nfunc (a *ATNDeserializer) readLexerActions(atn *ATN) {\n\tif atn.grammarType == ATNTypeLexer {\n\t\tcount := a.readInt()\n\n\t\tatn.lexerActions = make([]LexerAction, count)\n\n\t\tfor i := range atn.lexerActions {\n\t\t\tactionType := a.readInt()\n\t\t\tdata1 := a.readInt()\n\t\t\tdata2 := a.readInt()\n\t\t\tatn.lexerActions[i] = a.lexerActionFactory(actionType, data1, data2)\n\t\t}\n\t}\n}\n\nfunc (a *ATNDeserializer) generateRuleBypassTransitions(atn *ATN) {\n\tcount := len(atn.ruleToStartState)\n\n\tfor i := 0; i < count; i++ {\n\t\tatn.ruleToTokenType[i] = atn.maxTokenType + i + 1\n\t}\n\n\tfor i := 0; i < count; i++ {\n\t\ta.generateRuleBypassTransition(atn, i)\n\t}\n}\n\nfunc (a *ATNDeserializer) generateRuleBypassTransition(atn *ATN, idx int) {\n\tbypassStart := NewBasicBlockStartState()\n\n\tbypassStart.ruleIndex = idx\n\tatn.addState(bypassStart)\n\n\tbypassStop := NewBlockEndState()\n\n\tbypassStop.ruleIndex = idx\n\tatn.addState(bypassStop)\n\n\tbypassStart.endState = bypassStop\n\n\tatn.defineDecisionState(&bypassStart.BaseDecisionState)\n\n\tbypassStop.startState = bypassStart\n\n\tvar excludeTransition Transition\n\tvar endState ATNState\n\n\tif atn.ruleToStartState[idx].isPrecedenceRule {\n\t\t// Wrap from the beginning of the rule to the StarLoopEntryState\n\t\tendState = nil\n\n\t\tfor i := 0; i < len(atn.states); i++ {\n\t\t\tstate := atn.states[i]\n\n\t\t\tif a.stateIsEndStateFor(state, idx) != nil {\n\t\t\t\tendState = state\n\t\t\t\texcludeTransition = state.(*StarLoopEntryState).loopBackState.GetTransitions()[0]\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif excludeTransition == nil {\n\t\t\tpanic(\"Couldn't identify final state of the precedence rule prefix section.\")\n\t\t}\n\t} else {\n\t\tendState = atn.ruleToStopState[idx]\n\t}\n\n\t// All non-excluded transitions that currently target end state need to target\n\t// blockEnd instead\n\tfor i := 0; i < len(atn.states); i++ {\n\t\tstate := atn.states[i]\n\n\t\tfor j := 0; j < len(state.GetTransitions()); j++ {\n\t\t\ttransition := state.GetTransitions()[j]\n\n\t\t\tif transition == excludeTransition {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif transition.getTarget() == endState {\n\t\t\t\ttransition.setTarget(bypassStop)\n\t\t\t}\n\t\t}\n\t}\n\n\t// All transitions leaving the rule start state need to leave blockStart instead\n\truleToStartState := atn.ruleToStartState[idx]\n\tcount := len(ruleToStartState.GetTransitions())\n\n\tfor count > 0 {\n\t\tbypassStart.AddTransition(ruleToStartState.GetTransitions()[count-1], -1)\n\t\truleToStartState.SetTransitions([]Transition{ruleToStartState.GetTransitions()[len(ruleToStartState.GetTransitions())-1]})\n\t}\n\n\t// Link the new states\n\tatn.ruleToStartState[idx].AddTransition(NewEpsilonTransition(bypassStart, -1), -1)\n\tbypassStop.AddTransition(NewEpsilonTransition(endState, -1), -1)\n\n\tMatchState := NewBasicState()\n\n\tatn.addState(MatchState)\n\tMatchState.AddTransition(NewAtomTransition(bypassStop, atn.ruleToTokenType[idx]), -1)\n\tbypassStart.AddTransition(NewEpsilonTransition(MatchState, -1), -1)\n}\n\nfunc (a *ATNDeserializer) stateIsEndStateFor(state ATNState, idx int) ATNState {\n\tif state.GetRuleIndex() != idx {\n\t\treturn nil\n\t}\n\n\tif _, ok := state.(*StarLoopEntryState); !ok {\n\t\treturn nil\n\t}\n\n\tmaybeLoopEndState := state.GetTransitions()[len(state.GetTransitions())-1].getTarget()\n\n\tif _, ok := maybeLoopEndState.(*LoopEndState); !ok {\n\t\treturn nil\n\t}\n\n\tvar _, ok = maybeLoopEndState.GetTransitions()[0].getTarget().(*RuleStopState)\n\n\tif maybeLoopEndState.(*LoopEndState).epsilonOnlyTransitions && ok {\n\t\treturn state\n\t}\n\n\treturn nil\n}\n\n// markPrecedenceDecisions analyzes the StarLoopEntryState states in the\n// specified ATN to set the StarLoopEntryState.precedenceRuleDecision field to\n// the correct value.\nfunc (a *ATNDeserializer) markPrecedenceDecisions(atn *ATN) {\n\tfor _, state := range atn.states {\n\t\tif _, ok := state.(*StarLoopEntryState); !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We analyze the [ATN] to determine if an ATN decision state is the\n\t\t// decision for the closure block that determines whether a\n\t\t// precedence rule should continue or complete.\n\t\tif atn.ruleToStartState[state.GetRuleIndex()].isPrecedenceRule {\n\t\t\tmaybeLoopEndState := state.GetTransitions()[len(state.GetTransitions())-1].getTarget()\n\n\t\t\tif s3, ok := maybeLoopEndState.(*LoopEndState); ok {\n\t\t\t\tvar _, ok2 = maybeLoopEndState.GetTransitions()[0].getTarget().(*RuleStopState)\n\n\t\t\t\tif s3.epsilonOnlyTransitions && ok2 {\n\t\t\t\t\tstate.(*StarLoopEntryState).precedenceRuleDecision = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (a *ATNDeserializer) verifyATN(atn *ATN) {\n\tif !a.options.VerifyATN() {\n\t\treturn\n\t}\n\n\t// Verify assumptions\n\tfor _, state := range atn.states {\n\t\tif state == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ta.checkCondition(state.GetEpsilonOnlyTransitions() || len(state.GetTransitions()) <= 1, \"\")\n\n\t\tswitch s2 := state.(type) {\n\t\tcase *PlusBlockStartState:\n\t\t\ta.checkCondition(s2.loopBackState != nil, \"\")\n\n\t\tcase *StarLoopEntryState:\n\t\t\ta.checkCondition(s2.loopBackState != nil, \"\")\n\t\t\ta.checkCondition(len(s2.GetTransitions()) == 2, \"\")\n\n\t\t\tswitch s2.transitions[0].getTarget().(type) {\n\t\t\tcase *StarBlockStartState:\n\t\t\t\t_, ok := s2.transitions[1].getTarget().(*LoopEndState)\n\n\t\t\t\ta.checkCondition(ok, \"\")\n\t\t\t\ta.checkCondition(!s2.nonGreedy, \"\")\n\n\t\t\tcase *LoopEndState:\n\t\t\t\tvar _, ok = s2.transitions[1].getTarget().(*StarBlockStartState)\n\n\t\t\t\ta.checkCondition(ok, \"\")\n\t\t\t\ta.checkCondition(s2.nonGreedy, \"\")\n\n\t\t\tdefault:\n\t\t\t\tpanic(\"IllegalState\")\n\t\t\t}\n\n\t\tcase *StarLoopbackState:\n\t\t\ta.checkCondition(len(state.GetTransitions()) == 1, \"\")\n\n\t\t\tvar _, ok = state.GetTransitions()[0].getTarget().(*StarLoopEntryState)\n\n\t\t\ta.checkCondition(ok, \"\")\n\n\t\tcase *LoopEndState:\n\t\t\ta.checkCondition(s2.loopBackState != nil, \"\")\n\n\t\tcase *RuleStartState:\n\t\t\ta.checkCondition(s2.stopState != nil, \"\")\n\n\t\tcase BlockStartState:\n\t\t\ta.checkCondition(s2.getEndState() != nil, \"\")\n\n\t\tcase *BlockEndState:\n\t\t\ta.checkCondition(s2.startState != nil, \"\")\n\n\t\tcase DecisionState:\n\t\t\ta.checkCondition(len(s2.GetTransitions()) <= 1 || s2.getDecision() >= 0, \"\")\n\n\t\tdefault:\n\t\t\tvar _, ok = s2.(*RuleStopState)\n\n\t\t\ta.checkCondition(len(s2.GetTransitions()) <= 1 || ok, \"\")\n\t\t}\n\t}\n}\n\nfunc (a *ATNDeserializer) checkCondition(condition bool, message string) {\n\tif !condition {\n\t\tif message == \"\" {\n\t\t\tmessage = \"IllegalState\"\n\t\t}\n\n\t\tpanic(message)\n\t}\n}\n\nfunc (a *ATNDeserializer) readInt() int {\n\tv := a.data[a.pos]\n\n\ta.pos++\n\n\treturn int(v) // data is 32 bits but int is at least that big\n}\n\nfunc (a *ATNDeserializer) edgeFactory(atn *ATN, typeIndex, _, trg, arg1, arg2, arg3 int, sets []*IntervalSet) Transition {\n\ttarget := atn.states[trg]\n\n\tswitch typeIndex {\n\tcase TransitionEPSILON:\n\t\treturn NewEpsilonTransition(target, -1)\n\n\tcase TransitionRANGE:\n\t\tif arg3 != 0 {\n\t\t\treturn NewRangeTransition(target, TokenEOF, arg2)\n\t\t}\n\n\t\treturn NewRangeTransition(target, arg1, arg2)\n\n\tcase TransitionRULE:\n\t\treturn NewRuleTransition(atn.states[arg1], arg2, arg3, target)\n\n\tcase TransitionPREDICATE:\n\t\treturn NewPredicateTransition(target, arg1, arg2, arg3 != 0)\n\n\tcase TransitionPRECEDENCE:\n\t\treturn NewPrecedencePredicateTransition(target, arg1)\n\n\tcase TransitionATOM:\n\t\tif arg3 != 0 {\n\t\t\treturn NewAtomTransition(target, TokenEOF)\n\t\t}\n\n\t\treturn NewAtomTransition(target, arg1)\n\n\tcase TransitionACTION:\n\t\treturn NewActionTransition(target, arg1, arg2, arg3 != 0)\n\n\tcase TransitionSET:\n\t\treturn NewSetTransition(target, sets[arg1])\n\n\tcase TransitionNOTSET:\n\t\treturn NewNotSetTransition(target, sets[arg1])\n\n\tcase TransitionWILDCARD:\n\t\treturn NewWildcardTransition(target)\n\t}\n\n\tpanic(\"The specified transition type is not valid.\")\n}\n\nfunc (a *ATNDeserializer) stateFactory(typeIndex, ruleIndex int) ATNState {\n\tvar s ATNState\n\n\tswitch typeIndex {\n\tcase ATNStateInvalidType:\n\t\treturn nil\n\n\tcase ATNStateBasic:\n\t\ts = NewBasicState()\n\n\tcase ATNStateRuleStart:\n\t\ts = NewRuleStartState()\n\n\tcase ATNStateBlockStart:\n\t\ts = NewBasicBlockStartState()\n\n\tcase ATNStatePlusBlockStart:\n\t\ts = NewPlusBlockStartState()\n\n\tcase ATNStateStarBlockStart:\n\t\ts = NewStarBlockStartState()\n\n\tcase ATNStateTokenStart:\n\t\ts = NewTokensStartState()\n\n\tcase ATNStateRuleStop:\n\t\ts = NewRuleStopState()\n\n\tcase ATNStateBlockEnd:\n\t\ts = NewBlockEndState()\n\n\tcase ATNStateStarLoopBack:\n\t\ts = NewStarLoopbackState()\n\n\tcase ATNStateStarLoopEntry:\n\t\ts = NewStarLoopEntryState()\n\n\tcase ATNStatePlusLoopBack:\n\t\ts = NewPlusLoopbackState()\n\n\tcase ATNStateLoopEnd:\n\t\ts = NewLoopEndState()\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"state type %d is invalid\", typeIndex))\n\t}\n\n\ts.SetRuleIndex(ruleIndex)\n\n\treturn s\n}\n\nfunc (a *ATNDeserializer) lexerActionFactory(typeIndex, data1, data2 int) LexerAction {\n\tswitch typeIndex {\n\tcase LexerActionTypeChannel:\n\t\treturn NewLexerChannelAction(data1)\n\n\tcase LexerActionTypeCustom:\n\t\treturn NewLexerCustomAction(data1, data2)\n\n\tcase LexerActionTypeMode:\n\t\treturn NewLexerModeAction(data1)\n\n\tcase LexerActionTypeMore:\n\t\treturn LexerMoreActionINSTANCE\n\n\tcase LexerActionTypePopMode:\n\t\treturn LexerPopModeActionINSTANCE\n\n\tcase LexerActionTypePushMode:\n\t\treturn NewLexerPushModeAction(data1)\n\n\tcase LexerActionTypeSkip:\n\t\treturn LexerSkipActionINSTANCE\n\n\tcase LexerActionTypeType:\n\t\treturn NewLexerTypeAction(data1)\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"lexer action %d is invalid\", typeIndex))\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn_simulator.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nvar ATNSimulatorError = NewDFAState(0x7FFFFFFF, NewATNConfigSet(false))\n\ntype IATNSimulator interface {\n\tSharedContextCache() *PredictionContextCache\n\tATN() *ATN\n\tDecisionToDFA() []*DFA\n}\n\ntype BaseATNSimulator struct {\n\tatn                *ATN\n\tsharedContextCache *PredictionContextCache\n\tdecisionToDFA      []*DFA\n}\n\nfunc (b *BaseATNSimulator) getCachedContext(context *PredictionContext) *PredictionContext {\n\tif b.sharedContextCache == nil {\n\t\treturn context\n\t}\n\n\t//visited := NewJMap[*PredictionContext, *PredictionContext, Comparator[*PredictionContext]](pContextEqInst, PredictionVisitedCollection, \"Visit map in getCachedContext()\")\n\tvisited := NewVisitRecord()\n\treturn getCachedBasePredictionContext(context, b.sharedContextCache, visited)\n}\n\nfunc (b *BaseATNSimulator) SharedContextCache() *PredictionContextCache {\n\treturn b.sharedContextCache\n}\n\nfunc (b *BaseATNSimulator) ATN() *ATN {\n\treturn b.atn\n}\n\nfunc (b *BaseATNSimulator) DecisionToDFA() []*DFA {\n\treturn b.decisionToDFA\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn_state.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n)\n\n// Constants for serialization.\nconst (\n\tATNStateInvalidType    = 0\n\tATNStateBasic          = 1\n\tATNStateRuleStart      = 2\n\tATNStateBlockStart     = 3\n\tATNStatePlusBlockStart = 4\n\tATNStateStarBlockStart = 5\n\tATNStateTokenStart     = 6\n\tATNStateRuleStop       = 7\n\tATNStateBlockEnd       = 8\n\tATNStateStarLoopBack   = 9\n\tATNStateStarLoopEntry  = 10\n\tATNStatePlusLoopBack   = 11\n\tATNStateLoopEnd        = 12\n\n\tATNStateInvalidStateNumber = -1\n)\n\n//goland:noinspection GoUnusedGlobalVariable\nvar ATNStateInitialNumTransitions = 4\n\ntype ATNState interface {\n\tGetEpsilonOnlyTransitions() bool\n\n\tGetRuleIndex() int\n\tSetRuleIndex(int)\n\n\tGetNextTokenWithinRule() *IntervalSet\n\tSetNextTokenWithinRule(*IntervalSet)\n\n\tGetATN() *ATN\n\tSetATN(*ATN)\n\n\tGetStateType() int\n\n\tGetStateNumber() int\n\tSetStateNumber(int)\n\n\tGetTransitions() []Transition\n\tSetTransitions([]Transition)\n\tAddTransition(Transition, int)\n\n\tString() string\n\tHash() int\n\tEquals(Collectable[ATNState]) bool\n}\n\ntype BaseATNState struct {\n\t// NextTokenWithinRule caches lookahead during parsing. Not used during construction.\n\tNextTokenWithinRule *IntervalSet\n\n\t// atn is the current ATN.\n\tatn *ATN\n\n\tepsilonOnlyTransitions bool\n\n\t// ruleIndex tracks the Rule index because there are no Rule objects at runtime.\n\truleIndex int\n\n\tstateNumber int\n\n\tstateType int\n\n\t// Track the transitions emanating from this ATN state.\n\ttransitions []Transition\n}\n\nfunc NewATNState() *BaseATNState {\n\treturn &BaseATNState{stateNumber: ATNStateInvalidStateNumber, stateType: ATNStateInvalidType}\n}\n\nfunc (as *BaseATNState) GetRuleIndex() int {\n\treturn as.ruleIndex\n}\n\nfunc (as *BaseATNState) SetRuleIndex(v int) {\n\tas.ruleIndex = v\n}\nfunc (as *BaseATNState) GetEpsilonOnlyTransitions() bool {\n\treturn as.epsilonOnlyTransitions\n}\n\nfunc (as *BaseATNState) GetATN() *ATN {\n\treturn as.atn\n}\n\nfunc (as *BaseATNState) SetATN(atn *ATN) {\n\tas.atn = atn\n}\n\nfunc (as *BaseATNState) GetTransitions() []Transition {\n\treturn as.transitions\n}\n\nfunc (as *BaseATNState) SetTransitions(t []Transition) {\n\tas.transitions = t\n}\n\nfunc (as *BaseATNState) GetStateType() int {\n\treturn as.stateType\n}\n\nfunc (as *BaseATNState) GetStateNumber() int {\n\treturn as.stateNumber\n}\n\nfunc (as *BaseATNState) SetStateNumber(stateNumber int) {\n\tas.stateNumber = stateNumber\n}\n\nfunc (as *BaseATNState) GetNextTokenWithinRule() *IntervalSet {\n\treturn as.NextTokenWithinRule\n}\n\nfunc (as *BaseATNState) SetNextTokenWithinRule(v *IntervalSet) {\n\tas.NextTokenWithinRule = v\n}\n\nfunc (as *BaseATNState) Hash() int {\n\treturn as.stateNumber\n}\n\nfunc (as *BaseATNState) String() string {\n\treturn strconv.Itoa(as.stateNumber)\n}\n\nfunc (as *BaseATNState) Equals(other Collectable[ATNState]) bool {\n\tif ot, ok := other.(ATNState); ok {\n\t\treturn as.stateNumber == ot.GetStateNumber()\n\t}\n\n\treturn false\n}\n\nfunc (as *BaseATNState) isNonGreedyExitState() bool {\n\treturn false\n}\n\nfunc (as *BaseATNState) AddTransition(trans Transition, index int) {\n\tif len(as.transitions) == 0 {\n\t\tas.epsilonOnlyTransitions = trans.getIsEpsilon()\n\t} else if as.epsilonOnlyTransitions != trans.getIsEpsilon() {\n\t\t_, _ = fmt.Fprintf(os.Stdin, \"ATN state %d has both epsilon and non-epsilon transitions.\\n\", as.stateNumber)\n\t\tas.epsilonOnlyTransitions = false\n\t}\n\n\t// TODO: Check code for already present compared to the Java equivalent\n\t//alreadyPresent := false\n\t//for _, t := range as.transitions {\n\t//\tif t.getTarget().GetStateNumber() == trans.getTarget().GetStateNumber() {\n\t//\t\tif t.getLabel() != nil && trans.getLabel() != nil && trans.getLabel().Equals(t.getLabel()) {\n\t//\t\t\talreadyPresent = true\n\t//\t\t\tbreak\n\t//\t\t}\n\t//\t} else if t.getIsEpsilon() && trans.getIsEpsilon() {\n\t//\t\talreadyPresent = true\n\t//\t\tbreak\n\t//\t}\n\t//}\n\t//if !alreadyPresent {\n\tif index == -1 {\n\t\tas.transitions = append(as.transitions, trans)\n\t} else {\n\t\tas.transitions = append(as.transitions[:index], append([]Transition{trans}, as.transitions[index:]...)...)\n\t\t// TODO: as.transitions.splice(index, 1, trans)\n\t}\n\t//} else {\n\t//\t_, _ = fmt.Fprintf(os.Stderr, \"Transition already present in state %d\\n\", as.stateNumber)\n\t//}\n}\n\ntype BasicState struct {\n\tBaseATNState\n}\n\nfunc NewBasicState() *BasicState {\n\treturn &BasicState{\n\t\tBaseATNState: BaseATNState{\n\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\tstateType:   ATNStateBasic,\n\t\t},\n\t}\n}\n\ntype DecisionState interface {\n\tATNState\n\n\tgetDecision() int\n\tsetDecision(int)\n\n\tgetNonGreedy() bool\n\tsetNonGreedy(bool)\n}\n\ntype BaseDecisionState struct {\n\tBaseATNState\n\tdecision  int\n\tnonGreedy bool\n}\n\nfunc NewBaseDecisionState() *BaseDecisionState {\n\treturn &BaseDecisionState{\n\t\tBaseATNState: BaseATNState{\n\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\tstateType:   ATNStateBasic,\n\t\t},\n\t\tdecision: -1,\n\t}\n}\n\nfunc (s *BaseDecisionState) getDecision() int {\n\treturn s.decision\n}\n\nfunc (s *BaseDecisionState) setDecision(b int) {\n\ts.decision = b\n}\n\nfunc (s *BaseDecisionState) getNonGreedy() bool {\n\treturn s.nonGreedy\n}\n\nfunc (s *BaseDecisionState) setNonGreedy(b bool) {\n\ts.nonGreedy = b\n}\n\ntype BlockStartState interface {\n\tDecisionState\n\n\tgetEndState() *BlockEndState\n\tsetEndState(*BlockEndState)\n}\n\n// BaseBlockStartState is the start of a regular (...) block.\ntype BaseBlockStartState struct {\n\tBaseDecisionState\n\tendState *BlockEndState\n}\n\nfunc NewBlockStartState() *BaseBlockStartState {\n\treturn &BaseBlockStartState{\n\t\tBaseDecisionState: BaseDecisionState{\n\t\t\tBaseATNState: BaseATNState{\n\t\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\t\tstateType:   ATNStateBasic,\n\t\t\t},\n\t\t\tdecision: -1,\n\t\t},\n\t}\n}\n\nfunc (s *BaseBlockStartState) getEndState() *BlockEndState {\n\treturn s.endState\n}\n\nfunc (s *BaseBlockStartState) setEndState(b *BlockEndState) {\n\ts.endState = b\n}\n\ntype BasicBlockStartState struct {\n\tBaseBlockStartState\n}\n\nfunc NewBasicBlockStartState() *BasicBlockStartState {\n\treturn &BasicBlockStartState{\n\t\tBaseBlockStartState: BaseBlockStartState{\n\t\t\tBaseDecisionState: BaseDecisionState{\n\t\t\t\tBaseATNState: BaseATNState{\n\t\t\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\t\t\tstateType:   ATNStateBlockStart,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nvar _ BlockStartState = &BasicBlockStartState{}\n\n// BlockEndState is a terminal node of a simple (a|b|c) block.\ntype BlockEndState struct {\n\tBaseATNState\n\tstartState ATNState\n}\n\nfunc NewBlockEndState() *BlockEndState {\n\treturn &BlockEndState{\n\t\tBaseATNState: BaseATNState{\n\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\tstateType:   ATNStateBlockEnd,\n\t\t},\n\t\tstartState: nil,\n\t}\n}\n\n// RuleStopState is the last node in the ATN for a rule, unless that rule is the\n// start symbol. In that case, there is one transition to EOF. Later, we might\n// encode references to all calls to this rule to compute FOLLOW sets for error\n// handling.\ntype RuleStopState struct {\n\tBaseATNState\n}\n\nfunc NewRuleStopState() *RuleStopState {\n\treturn &RuleStopState{\n\t\tBaseATNState: BaseATNState{\n\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\tstateType:   ATNStateRuleStop,\n\t\t},\n\t}\n}\n\ntype RuleStartState struct {\n\tBaseATNState\n\tstopState        ATNState\n\tisPrecedenceRule bool\n}\n\nfunc NewRuleStartState() *RuleStartState {\n\treturn &RuleStartState{\n\t\tBaseATNState: BaseATNState{\n\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\tstateType:   ATNStateRuleStart,\n\t\t},\n\t}\n}\n\n// PlusLoopbackState is a decision state for A+ and (A|B)+. It has two\n// transitions: one to the loop back to start of the block, and one to exit.\ntype PlusLoopbackState struct {\n\tBaseDecisionState\n}\n\nfunc NewPlusLoopbackState() *PlusLoopbackState {\n\treturn &PlusLoopbackState{\n\t\tBaseDecisionState: BaseDecisionState{\n\t\t\tBaseATNState: BaseATNState{\n\t\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\t\tstateType:   ATNStatePlusLoopBack,\n\t\t\t},\n\t\t},\n\t}\n}\n\n// PlusBlockStartState is the start of a (A|B|...)+ loop. Technically it is a\n// decision state; we don't use it for code generation. Somebody might need it,\n// it is included for completeness. In reality, PlusLoopbackState is the real\n// decision-making node for A+.\ntype PlusBlockStartState struct {\n\tBaseBlockStartState\n\tloopBackState ATNState\n}\n\nfunc NewPlusBlockStartState() *PlusBlockStartState {\n\treturn &PlusBlockStartState{\n\t\tBaseBlockStartState: BaseBlockStartState{\n\t\t\tBaseDecisionState: BaseDecisionState{\n\t\t\t\tBaseATNState: BaseATNState{\n\t\t\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\t\t\tstateType:   ATNStatePlusBlockStart,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nvar _ BlockStartState = &PlusBlockStartState{}\n\n// StarBlockStartState is the block that begins a closure loop.\ntype StarBlockStartState struct {\n\tBaseBlockStartState\n}\n\nfunc NewStarBlockStartState() *StarBlockStartState {\n\treturn &StarBlockStartState{\n\t\tBaseBlockStartState: BaseBlockStartState{\n\t\t\tBaseDecisionState: BaseDecisionState{\n\t\t\t\tBaseATNState: BaseATNState{\n\t\t\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\t\t\tstateType:   ATNStateStarBlockStart,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nvar _ BlockStartState = &StarBlockStartState{}\n\ntype StarLoopbackState struct {\n\tBaseATNState\n}\n\nfunc NewStarLoopbackState() *StarLoopbackState {\n\treturn &StarLoopbackState{\n\t\tBaseATNState: BaseATNState{\n\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\tstateType:   ATNStateStarLoopBack,\n\t\t},\n\t}\n}\n\ntype StarLoopEntryState struct {\n\tBaseDecisionState\n\tloopBackState          ATNState\n\tprecedenceRuleDecision bool\n}\n\nfunc NewStarLoopEntryState() *StarLoopEntryState {\n\t// False precedenceRuleDecision indicates whether s state can benefit from a precedence DFA during SLL decision making.\n\treturn &StarLoopEntryState{\n\t\tBaseDecisionState: BaseDecisionState{\n\t\t\tBaseATNState: BaseATNState{\n\t\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\t\tstateType:   ATNStateStarLoopEntry,\n\t\t\t},\n\t\t},\n\t}\n}\n\n// LoopEndState marks the end of a * or + loop.\ntype LoopEndState struct {\n\tBaseATNState\n\tloopBackState ATNState\n}\n\nfunc NewLoopEndState() *LoopEndState {\n\treturn &LoopEndState{\n\t\tBaseATNState: BaseATNState{\n\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\tstateType:   ATNStateLoopEnd,\n\t\t},\n\t}\n}\n\n// TokensStartState is the Tokens rule start state linking to each lexer rule start state.\ntype TokensStartState struct {\n\tBaseDecisionState\n}\n\nfunc NewTokensStartState() *TokensStartState {\n\treturn &TokensStartState{\n\t\tBaseDecisionState: BaseDecisionState{\n\t\t\tBaseATNState: BaseATNState{\n\t\t\t\tstateNumber: ATNStateInvalidStateNumber,\n\t\t\t\tstateType:   ATNStateTokenStart,\n\t\t\t},\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/atn_type.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// Represent the type of recognizer an ATN applies to.\nconst (\n\tATNTypeLexer  = 0\n\tATNTypeParser = 1\n)\n"
  },
  {
    "path": "runtime/Go/antlr/v4/char_stream.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\ntype CharStream interface {\n\tIntStream\n\tGetText(int, int) string\n\tGetTextFromTokens(start, end Token) string\n\tGetTextFromInterval(Interval) string\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/common_token_factory.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// TokenFactory creates CommonToken objects.\ntype TokenFactory interface {\n\tCreate(source *TokenSourceCharStreamPair, ttype int, text string, channel, start, stop, line, column int) Token\n}\n\n// CommonTokenFactory is the default TokenFactory implementation.\ntype CommonTokenFactory struct {\n\t// copyText indicates whether CommonToken.setText should be called after\n\t// constructing tokens to explicitly set the text. This is useful for cases\n\t// where the input stream might not be able to provide arbitrary substrings of\n\t// text from the input after the lexer creates a token (e.g. the\n\t// implementation of CharStream.GetText in UnbufferedCharStream panics an\n\t// UnsupportedOperationException). Explicitly setting the token text allows\n\t// Token.GetText to be called at any time regardless of the input stream\n\t// implementation.\n\t//\n\t// The default value is false to avoid the performance and memory overhead of\n\t// copying text for every token unless explicitly requested.\n\tcopyText bool\n}\n\nfunc NewCommonTokenFactory(copyText bool) *CommonTokenFactory {\n\treturn &CommonTokenFactory{copyText: copyText}\n}\n\n// CommonTokenFactoryDEFAULT is the default CommonTokenFactory. It does not\n// explicitly copy token text when constructing tokens.\nvar CommonTokenFactoryDEFAULT = NewCommonTokenFactory(false)\n\nfunc (c *CommonTokenFactory) Create(source *TokenSourceCharStreamPair, ttype int, text string, channel, start, stop, line, column int) Token {\n\tt := NewCommonToken(source, ttype, channel, start, stop)\n\n\tt.line = line\n\tt.column = column\n\n\tif text != \"\" {\n\t\tt.SetText(text)\n\t} else if c.copyText && source.charStream != nil {\n\t\tt.SetText(source.charStream.GetTextFromInterval(NewInterval(start, stop)))\n\t}\n\n\treturn t\n}\n\nfunc (c *CommonTokenFactory) createThin(ttype int, text string) Token {\n\tt := NewCommonToken(nil, ttype, TokenDefaultChannel, -1, -1)\n\tt.SetText(text)\n\n\treturn t\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/common_token_stream.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"strconv\"\n)\n\n// CommonTokenStream is an implementation of TokenStream that loads tokens from\n// a TokenSource on-demand and places the tokens in a buffer to provide access\n// to any previous token by index. This token stream ignores the value of\n// Token.getChannel. If your parser requires the token stream filter tokens to\n// only those on a particular channel, such as Token.DEFAULT_CHANNEL or\n// Token.HIDDEN_CHANNEL, use a filtering token stream such a CommonTokenStream.\ntype CommonTokenStream struct {\n\tchannel int\n\n\t// fetchedEOF indicates whether the Token.EOF token has been fetched from\n\t// tokenSource and added to tokens. This field improves performance for the\n\t// following cases:\n\t//\n\t// consume: The lookahead check in consume to preven consuming the EOF symbol is\n\t// optimized by checking the values of fetchedEOF and p instead of calling LA.\n\t//\n\t// fetch: The check to prevent adding multiple EOF symbols into tokens is\n\t// trivial with bt field.\n\tfetchedEOF bool\n\n\t// index into [tokens] of the current token (next token to consume).\n\t// tokens[p] should be LT(1). It is set to -1 when the stream is first\n\t// constructed or when SetTokenSource is called, indicating that the first token\n\t// has not yet been fetched from the token source. For additional information,\n\t// see the documentation of [IntStream] for a description of initializing methods.\n\tindex int\n\n\t// tokenSource is the [TokenSource] from which tokens for the bt stream are\n\t// fetched.\n\ttokenSource TokenSource\n\n\t// tokens contains all tokens fetched from the token source. The list is considered a\n\t// complete view of the input once fetchedEOF is set to true.\n\ttokens []Token\n}\n\n// NewCommonTokenStream creates a new CommonTokenStream instance using the supplied lexer to produce\n// tokens and will pull tokens from the given lexer channel.\nfunc NewCommonTokenStream(lexer Lexer, channel int) *CommonTokenStream {\n\treturn &CommonTokenStream{\n\t\tchannel:     channel,\n\t\tindex:       -1,\n\t\ttokenSource: lexer,\n\t\ttokens:      make([]Token, 0),\n\t}\n}\n\n// GetAllTokens returns all tokens currently pulled from the token source.\nfunc (c *CommonTokenStream) GetAllTokens() []Token {\n\treturn c.tokens\n}\n\nfunc (c *CommonTokenStream) Mark() int {\n\treturn 0\n}\n\nfunc (c *CommonTokenStream) Release(_ int) {}\n\nfunc (c *CommonTokenStream) Reset() {\n\tc.fetchedEOF = false\n\tc.tokens = make([]Token, 0)\n\tc.Seek(0)\n}\n\nfunc (c *CommonTokenStream) Seek(index int) {\n\tc.lazyInit()\n\tc.index = c.adjustSeekIndex(index)\n}\n\nfunc (c *CommonTokenStream) Get(index int) Token {\n\tc.lazyInit()\n\n\treturn c.tokens[index]\n}\n\nfunc (c *CommonTokenStream) Consume() {\n\tSkipEOFCheck := false\n\n\tif c.index >= 0 {\n\t\tif c.fetchedEOF {\n\t\t\t// The last token in tokens is EOF. Skip the check if p indexes any fetched.\n\t\t\t// token except the last.\n\t\t\tSkipEOFCheck = c.index < len(c.tokens)-1\n\t\t} else {\n\t\t\t// No EOF token in tokens. Skip the check if p indexes a fetched token.\n\t\t\tSkipEOFCheck = c.index < len(c.tokens)\n\t\t}\n\t} else {\n\t\t// Not yet initialized\n\t\tSkipEOFCheck = false\n\t}\n\n\tif !SkipEOFCheck && c.LA(1) == TokenEOF {\n\t\tpanic(\"cannot consume EOF\")\n\t}\n\n\tif c.Sync(c.index + 1) {\n\t\tc.index = c.adjustSeekIndex(c.index + 1)\n\t}\n}\n\n// Sync makes sure index i in tokens has a token and returns true if a token is\n// located at index i and otherwise false.\nfunc (c *CommonTokenStream) Sync(i int) bool {\n\tn := i - len(c.tokens) + 1 // How many more elements do we need?\n\n\tif n > 0 {\n\t\tfetched := c.fetch(n)\n\t\treturn fetched >= n\n\t}\n\n\treturn true\n}\n\n// fetch adds n elements to buffer and returns the actual number of elements\n// added to the buffer.\nfunc (c *CommonTokenStream) fetch(n int) int {\n\tif c.fetchedEOF {\n\t\treturn 0\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tt := c.tokenSource.NextToken()\n\n\t\tt.SetTokenIndex(len(c.tokens))\n\t\tc.tokens = append(c.tokens, t)\n\n\t\tif t.GetTokenType() == TokenEOF {\n\t\t\tc.fetchedEOF = true\n\n\t\t\treturn i + 1\n\t\t}\n\t}\n\n\treturn n\n}\n\n// GetTokens gets all tokens from start to stop inclusive.\nfunc (c *CommonTokenStream) GetTokens(start int, stop int, types *IntervalSet) []Token {\n\tif start < 0 || stop < 0 {\n\t\treturn nil\n\t}\n\n\tc.lazyInit()\n\n\tsubset := make([]Token, 0)\n\n\tif stop >= len(c.tokens) {\n\t\tstop = len(c.tokens) - 1\n\t}\n\n\tfor i := start; i < stop; i++ {\n\t\tt := c.tokens[i]\n\n\t\tif t.GetTokenType() == TokenEOF {\n\t\t\tbreak\n\t\t}\n\n\t\tif types == nil || types.contains(t.GetTokenType()) {\n\t\t\tsubset = append(subset, t)\n\t\t}\n\t}\n\n\treturn subset\n}\n\nfunc (c *CommonTokenStream) LA(i int) int {\n\treturn c.LT(i).GetTokenType()\n}\n\nfunc (c *CommonTokenStream) lazyInit() {\n\tif c.index == -1 {\n\t\tc.setup()\n\t}\n}\n\nfunc (c *CommonTokenStream) setup() {\n\tc.Sync(0)\n\tc.index = c.adjustSeekIndex(0)\n}\n\nfunc (c *CommonTokenStream) GetTokenSource() TokenSource {\n\treturn c.tokenSource\n}\n\n// SetTokenSource resets the c token stream by setting its token source.\nfunc (c *CommonTokenStream) SetTokenSource(tokenSource TokenSource) {\n\tc.tokenSource = tokenSource\n\tc.tokens = make([]Token, 0)\n\tc.index = -1\n\tc.fetchedEOF = false\n}\n\n// NextTokenOnChannel returns the index of the next token on channel given a\n// starting index. Returns i if tokens[i] is on channel. Returns -1 if there are\n// no tokens on channel between 'i' and [TokenEOF].\nfunc (c *CommonTokenStream) NextTokenOnChannel(i, _ int) int {\n\tc.Sync(i)\n\n\tif i >= len(c.tokens) {\n\t\treturn -1\n\t}\n\n\ttoken := c.tokens[i]\n\n\tfor token.GetChannel() != c.channel {\n\t\tif token.GetTokenType() == TokenEOF {\n\t\t\treturn -1\n\t\t}\n\n\t\ti++\n\t\tc.Sync(i)\n\t\ttoken = c.tokens[i]\n\t}\n\n\treturn i\n}\n\n// previousTokenOnChannel returns the index of the previous token on channel\n// given a starting index. Returns i if tokens[i] is on channel. Returns -1 if\n// there are no tokens on channel between i and 0.\nfunc (c *CommonTokenStream) previousTokenOnChannel(i, channel int) int {\n\tfor i >= 0 && c.tokens[i].GetChannel() != channel {\n\t\ti--\n\t}\n\n\treturn i\n}\n\n// GetHiddenTokensToRight collects all tokens on a specified channel to the\n// right of the current token up until we see a token on DEFAULT_TOKEN_CHANNEL\n// or EOF. If channel is -1, it finds any non-default channel token.\nfunc (c *CommonTokenStream) GetHiddenTokensToRight(tokenIndex, channel int) []Token {\n\tc.lazyInit()\n\n\tif tokenIndex < 0 || tokenIndex >= len(c.tokens) {\n\t\tpanic(strconv.Itoa(tokenIndex) + \" not in 0..\" + strconv.Itoa(len(c.tokens)-1))\n\t}\n\n\tnextOnChannel := c.NextTokenOnChannel(tokenIndex+1, LexerDefaultTokenChannel)\n\tfrom := tokenIndex + 1\n\n\t// If no onChannel to the right, then nextOnChannel == -1, so set 'to' to the last token\n\tvar to int\n\n\tif nextOnChannel == -1 {\n\t\tto = len(c.tokens) - 1\n\t} else {\n\t\tto = nextOnChannel\n\t}\n\n\treturn c.filterForChannel(from, to, channel)\n}\n\n// GetHiddenTokensToLeft collects all tokens on channel to the left of the\n// current token until we see a token on DEFAULT_TOKEN_CHANNEL. If channel is\n// -1, it finds any non default channel token.\nfunc (c *CommonTokenStream) GetHiddenTokensToLeft(tokenIndex, channel int) []Token {\n\tc.lazyInit()\n\n\tif tokenIndex < 0 || tokenIndex >= len(c.tokens) {\n\t\tpanic(strconv.Itoa(tokenIndex) + \" not in 0..\" + strconv.Itoa(len(c.tokens)-1))\n\t}\n\n\tprevOnChannel := c.previousTokenOnChannel(tokenIndex-1, LexerDefaultTokenChannel)\n\n\tif prevOnChannel == tokenIndex-1 {\n\t\treturn nil\n\t}\n\n\t// If there are none on channel to the left and prevOnChannel == -1 then from = 0\n\tfrom := prevOnChannel + 1\n\tto := tokenIndex - 1\n\n\treturn c.filterForChannel(from, to, channel)\n}\n\nfunc (c *CommonTokenStream) filterForChannel(left, right, channel int) []Token {\n\thidden := make([]Token, 0)\n\n\tfor i := left; i < right+1; i++ {\n\t\tt := c.tokens[i]\n\n\t\tif channel == -1 {\n\t\t\tif t.GetChannel() != LexerDefaultTokenChannel {\n\t\t\t\thidden = append(hidden, t)\n\t\t\t}\n\t\t} else if t.GetChannel() == channel {\n\t\t\thidden = append(hidden, t)\n\t\t}\n\t}\n\n\tif len(hidden) == 0 {\n\t\treturn nil\n\t}\n\n\treturn hidden\n}\n\nfunc (c *CommonTokenStream) GetSourceName() string {\n\treturn c.tokenSource.GetSourceName()\n}\n\nfunc (c *CommonTokenStream) Size() int {\n\treturn len(c.tokens)\n}\n\nfunc (c *CommonTokenStream) Index() int {\n\treturn c.index\n}\n\nfunc (c *CommonTokenStream) GetAllText() string {\n\tc.Fill()\n\treturn c.GetTextFromInterval(NewInterval(0, len(c.tokens)-1))\n}\n\nfunc (c *CommonTokenStream) GetTextFromTokens(start, end Token) string {\n\tif start == nil || end == nil {\n\t\treturn \"\"\n\t}\n\n\treturn c.GetTextFromInterval(NewInterval(start.GetTokenIndex(), end.GetTokenIndex()))\n}\n\nfunc (c *CommonTokenStream) GetTextFromRuleContext(interval RuleContext) string {\n\treturn c.GetTextFromInterval(interval.GetSourceInterval())\n}\n\nfunc (c *CommonTokenStream) GetTextFromInterval(interval Interval) string {\n\tc.lazyInit()\n\tc.Sync(interval.Stop)\n\n\tstart := interval.Start\n\tstop := interval.Stop\n\n\tif start < 0 || stop < 0 {\n\t\treturn \"\"\n\t}\n\n\tif stop >= len(c.tokens) {\n\t\tstop = len(c.tokens) - 1\n\t}\n\n\ts := \"\"\n\n\tfor i := start; i < stop+1; i++ {\n\t\tt := c.tokens[i]\n\n\t\tif t.GetTokenType() == TokenEOF {\n\t\t\tbreak\n\t\t}\n\n\t\ts += t.GetText()\n\t}\n\n\treturn s\n}\n\n// Fill gets all tokens from the lexer until EOF.\nfunc (c *CommonTokenStream) Fill() {\n\tc.lazyInit()\n\n\tfor c.fetch(1000) == 1000 {\n\t\tcontinue\n\t}\n}\n\nfunc (c *CommonTokenStream) adjustSeekIndex(i int) int {\n\treturn c.NextTokenOnChannel(i, c.channel)\n}\n\nfunc (c *CommonTokenStream) LB(k int) Token {\n\tif k == 0 || c.index-k < 0 {\n\t\treturn nil\n\t}\n\n\ti := c.index\n\tn := 1\n\n\t// Find k good tokens looking backward\n\tfor n <= k {\n\t\t// Skip off-channel tokens\n\t\ti = c.previousTokenOnChannel(i-1, c.channel)\n\t\tn++\n\t}\n\n\tif i < 0 {\n\t\treturn nil\n\t}\n\n\treturn c.tokens[i]\n}\n\nfunc (c *CommonTokenStream) LT(k int) Token {\n\tc.lazyInit()\n\n\tif k == 0 {\n\t\treturn nil\n\t}\n\n\tif k < 0 {\n\t\treturn c.LB(-k)\n\t}\n\n\ti := c.index\n\tn := 1 // We know tokens[n] is valid\n\n\t// Find k good tokens\n\tfor n < k {\n\t\t// Skip off-channel tokens, but make sure to not look past EOF\n\t\tif c.Sync(i + 1) {\n\t\t\ti = c.NextTokenOnChannel(i+1, c.channel)\n\t\t}\n\n\t\tn++\n\t}\n\n\treturn c.tokens[i]\n}\n\n// getNumberOfOnChannelTokens counts EOF once.\nfunc (c *CommonTokenStream) getNumberOfOnChannelTokens() int {\n\tvar n int\n\n\tc.Fill()\n\n\tfor i := 0; i < len(c.tokens); i++ {\n\t\tt := c.tokens[i]\n\n\t\tif t.GetChannel() == c.channel {\n\t\t\tn++\n\t\t}\n\n\t\tif t.GetTokenType() == TokenEOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn n\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/comparators.go",
    "content": "package antlr\n\n// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\n// This file contains all the implementations of custom comparators used for generic collections when the\n// Hash() and Equals() funcs supplied by the struct objects themselves need to be overridden. Normally, we would\n// put the comparators in the source file for the struct themselves, but given the organization of this code is\n// sorta kinda based upon the Java code, I found it confusing trying to find out which comparator was where and used by\n// which instantiation of a collection. For instance, an Array2DHashSet in the Java source, when used with ATNConfig\n// collections requires three different comparators depending on what the collection is being used for. Collecting - pun intended -\n// all the comparators here, makes it much easier to see which implementation of hash and equals is used by which collection.\n// It also makes it easy to verify that the Hash() and Equals() functions marry up with the Java implementations.\n\n// ObjEqComparator is the equivalent of the Java ObjectEqualityComparator, which is the default instance of\n// Equality comparator. We do not have inheritance in Go, only interfaces, so we use generics to enforce some\n// type safety and avoid having to implement this for every type that we want to perform comparison on.\n//\n// This comparator works by using the standard Hash() and Equals() methods of the type T that is being compared. Which\n// allows us to use it in any collection instance that does not require a special hash or equals implementation.\ntype ObjEqComparator[T Collectable[T]] struct{}\n\nvar (\n\taStateEqInst = &ObjEqComparator[ATNState]{}\n\taConfEqInst  = &ObjEqComparator[*ATNConfig]{}\n\n\t// aConfCompInst is the comparator used for the ATNConfigSet for the configLookup cache\n\taConfCompInst   = &ATNConfigComparator[*ATNConfig]{}\n\tatnConfCompInst = &BaseATNConfigComparator[*ATNConfig]{}\n\tdfaStateEqInst  = &ObjEqComparator[*DFAState]{}\n\tsemctxEqInst    = &ObjEqComparator[SemanticContext]{}\n\tatnAltCfgEqInst = &ATNAltConfigComparator[*ATNConfig]{}\n\tpContextEqInst  = &ObjEqComparator[*PredictionContext]{}\n)\n\n// Equals2 delegates to the Equals() method of type T\nfunc (c *ObjEqComparator[T]) Equals2(o1, o2 T) bool {\n\treturn o1.Equals(o2)\n}\n\n// Hash1 delegates to the Hash() method of type T\nfunc (c *ObjEqComparator[T]) Hash1(o T) int {\n\n\treturn o.Hash()\n}\n\ntype SemCComparator[T Collectable[T]] struct{}\n\n// ATNConfigComparator is used as the comparator for the configLookup field of an ATNConfigSet\n// and has a custom Equals() and Hash() implementation, because equality is not based on the\n// standard Hash() and Equals() methods of the ATNConfig type.\ntype ATNConfigComparator[T Collectable[T]] struct {\n}\n\n// Equals2 is a custom comparator for ATNConfigs specifically for configLookup\nfunc (c *ATNConfigComparator[T]) Equals2(o1, o2 *ATNConfig) bool {\n\n\t// Same pointer, must be equal, even if both nil\n\t//\n\tif o1 == o2 {\n\t\treturn true\n\n\t}\n\n\t// If either are nil, but not both, then the result is false\n\t//\n\tif o1 == nil || o2 == nil {\n\t\treturn false\n\t}\n\n\treturn o1.GetState().GetStateNumber() == o2.GetState().GetStateNumber() &&\n\t\to1.GetAlt() == o2.GetAlt() &&\n\t\to1.GetSemanticContext().Equals(o2.GetSemanticContext())\n}\n\n// Hash1 is custom hash implementation for ATNConfigs specifically for configLookup\nfunc (c *ATNConfigComparator[T]) Hash1(o *ATNConfig) int {\n\n\thash := 7\n\thash = 31*hash + o.GetState().GetStateNumber()\n\thash = 31*hash + o.GetAlt()\n\thash = 31*hash + o.GetSemanticContext().Hash()\n\treturn hash\n}\n\n// ATNAltConfigComparator is used as the comparator for mapping configs to Alt Bitsets\ntype ATNAltConfigComparator[T Collectable[T]] struct {\n}\n\n// Equals2 is a custom comparator for ATNConfigs specifically for configLookup\nfunc (c *ATNAltConfigComparator[T]) Equals2(o1, o2 *ATNConfig) bool {\n\n\t// Same pointer, must be equal, even if both nil\n\t//\n\tif o1 == o2 {\n\t\treturn true\n\n\t}\n\n\t// If either are nil, but not both, then the result is false\n\t//\n\tif o1 == nil || o2 == nil {\n\t\treturn false\n\t}\n\n\treturn o1.GetState().GetStateNumber() == o2.GetState().GetStateNumber() &&\n\t\to1.GetContext().Equals(o2.GetContext())\n}\n\n// Hash1 is custom hash implementation for ATNConfigs specifically for configLookup\nfunc (c *ATNAltConfigComparator[T]) Hash1(o *ATNConfig) int {\n\th := murmurInit(7)\n\th = murmurUpdate(h, o.GetState().GetStateNumber())\n\th = murmurUpdate(h, o.GetContext().Hash())\n\treturn murmurFinish(h, 2)\n}\n\n// BaseATNConfigComparator is used as the comparator for the configLookup field of a ATNConfigSet\n// and has a custom Equals() and Hash() implementation, because equality is not based on the\n// standard Hash() and Equals() methods of the ATNConfig type.\ntype BaseATNConfigComparator[T Collectable[T]] struct {\n}\n\n// Equals2 is a custom comparator for ATNConfigs specifically for baseATNConfigSet\nfunc (c *BaseATNConfigComparator[T]) Equals2(o1, o2 *ATNConfig) bool {\n\n\t// Same pointer, must be equal, even if both nil\n\t//\n\tif o1 == o2 {\n\t\treturn true\n\n\t}\n\n\t// If either are nil, but not both, then the result is false\n\t//\n\tif o1 == nil || o2 == nil {\n\t\treturn false\n\t}\n\n\treturn o1.GetState().GetStateNumber() == o2.GetState().GetStateNumber() &&\n\t\to1.GetAlt() == o2.GetAlt() &&\n\t\to1.GetSemanticContext().Equals(o2.GetSemanticContext())\n}\n\n// Hash1 is custom hash implementation for ATNConfigs specifically for configLookup, but in fact just\n// delegates to the standard Hash() method of the ATNConfig type.\nfunc (c *BaseATNConfigComparator[T]) Hash1(o *ATNConfig) int {\n\treturn o.Hash()\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/configuration.go",
    "content": "package antlr\n\ntype runtimeConfiguration struct {\n\tstatsTraceStacks              bool\n\tlexerATNSimulatorDebug        bool\n\tlexerATNSimulatorDFADebug     bool\n\tparserATNSimulatorDebug       bool\n\tparserATNSimulatorTraceATNSim bool\n\tparserATNSimulatorDFADebug    bool\n\tparserATNSimulatorRetryDebug  bool\n\tlRLoopEntryBranchOpt          bool\n\tmemoryManager                 bool\n}\n\n// Global runtime configuration\nvar runtimeConfig = runtimeConfiguration{\n\tlRLoopEntryBranchOpt: true,\n}\n\ntype runtimeOption func(*runtimeConfiguration) error\n\n// ConfigureRuntime allows the runtime to be configured globally setting things like trace and statistics options.\n// It uses the functional options pattern for go. This is a package global function as it operates on the runtime\n// configuration regardless of the instantiation of anything higher up such as a parser or lexer. Generally this is\n// used for debugging/tracing/statistics options, which are usually used by the runtime maintainers (or rather the\n// only maintainer). However, it is possible that you might want to use this to set a global option concerning the\n// memory allocation type used by the runtime such as sync.Pool or not.\n//\n// The options are applied in the order they are passed in, so the last option will override any previous options.\n//\n// For example, if you want to turn on the collection create point stack flag to true, you can do:\n//\n//\tantlr.ConfigureRuntime(antlr.WithStatsTraceStacks(true))\n//\n// If you want to turn it off, you can do:\n//\n//\tantlr.ConfigureRuntime(antlr.WithStatsTraceStacks(false))\nfunc ConfigureRuntime(options ...runtimeOption) error {\n\tfor _, option := range options {\n\t\terr := option(&runtimeConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// WithStatsTraceStacks sets the global flag indicating whether to collect stack traces at the create-point of\n// certain structs, such as collections, or the use point of certain methods such as Put().\n// Because this can be expensive, it is turned off by default. However, it\n// can be useful to track down exactly where memory is being created and used.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithStatsTraceStacks(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithStatsTraceStacks(false))\nfunc WithStatsTraceStacks(trace bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.statsTraceStacks = trace\n\t\treturn nil\n\t}\n}\n\n// WithLexerATNSimulatorDebug sets the global flag indicating whether to log debug information from the lexer [ATN]\n// simulator. This is useful for debugging lexer issues by comparing the output with the Java runtime. Only useful\n// to the runtime maintainers.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithLexerATNSimulatorDebug(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithLexerATNSimulatorDebug(false))\nfunc WithLexerATNSimulatorDebug(debug bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.lexerATNSimulatorDebug = debug\n\t\treturn nil\n\t}\n}\n\n// WithLexerATNSimulatorDFADebug sets the global flag indicating whether to log debug information from the lexer [ATN] [DFA]\n// simulator. This is useful for debugging lexer issues by comparing the output with the Java runtime. Only useful\n// to the runtime maintainers.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithLexerATNSimulatorDFADebug(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithLexerATNSimulatorDFADebug(false))\nfunc WithLexerATNSimulatorDFADebug(debug bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.lexerATNSimulatorDFADebug = debug\n\t\treturn nil\n\t}\n}\n\n// WithParserATNSimulatorDebug sets the global flag indicating whether to log debug information from the parser [ATN]\n// simulator. This is useful for debugging parser issues by comparing the output with the Java runtime. Only useful\n// to the runtime maintainers.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorDebug(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorDebug(false))\nfunc WithParserATNSimulatorDebug(debug bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.parserATNSimulatorDebug = debug\n\t\treturn nil\n\t}\n}\n\n// WithParserATNSimulatorTraceATNSim sets the global flag indicating whether to log trace information from the parser [ATN] simulator\n// [DFA]. This is useful for debugging parser issues by comparing the output with the Java runtime. Only useful\n// to the runtime maintainers.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorTraceATNSim(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorTraceATNSim(false))\nfunc WithParserATNSimulatorTraceATNSim(trace bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.parserATNSimulatorTraceATNSim = trace\n\t\treturn nil\n\t}\n}\n\n// WithParserATNSimulatorDFADebug sets the global flag indicating whether to log debug information from the parser [ATN] [DFA]\n// simulator. This is useful for debugging parser issues by comparing the output with the Java runtime. Only useful\n// to the runtime maintainers.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorDFADebug(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorDFADebug(false))\nfunc WithParserATNSimulatorDFADebug(debug bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.parserATNSimulatorDFADebug = debug\n\t\treturn nil\n\t}\n}\n\n// WithParserATNSimulatorRetryDebug sets the global flag indicating whether to log debug information from the parser [ATN] [DFA]\n// simulator when retrying a decision. This is useful for debugging parser issues by comparing the output with the Java runtime.\n// Only useful to the runtime maintainers.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorRetryDebug(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithParserATNSimulatorRetryDebug(false))\nfunc WithParserATNSimulatorRetryDebug(debug bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.parserATNSimulatorRetryDebug = debug\n\t\treturn nil\n\t}\n}\n\n// WithLRLoopEntryBranchOpt sets the global flag indicating whether let recursive loop operations should be\n// optimized or not. This is useful for debugging parser issues by comparing the output with the Java runtime.\n// It turns off the functionality of [canDropLoopEntryEdgeInLeftRecursiveRule] in [ParserATNSimulator].\n//\n// Note that default is to use this optimization.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithLRLoopEntryBranchOpt(true))\n//\n// You can turn it off at any time using:\n//\n//\tantlr.ConfigureRuntime(antlr.WithLRLoopEntryBranchOpt(false))\nfunc WithLRLoopEntryBranchOpt(off bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.lRLoopEntryBranchOpt = off\n\t\treturn nil\n\t}\n}\n\n// WithMemoryManager sets the global flag indicating whether to use the memory manager or not. This is useful\n// for poorly constructed grammars that create a lot of garbage. It turns on the functionality of [memoryManager], which\n// will intercept garbage collection and cause available memory to be reused. At the end of the day, this is no substitute\n// for fixing your grammar by ridding yourself of extreme ambiguity. BUt if you are just trying to reuse an opensource\n// grammar, this may help make it more practical.\n//\n// Note that default is to use normal Go memory allocation and not pool memory.\n//\n// Use:\n//\n//\tantlr.ConfigureRuntime(antlr.WithMemoryManager(true))\n//\n// Note that if you turn this on, you should probably leave it on. You should use only one memory strategy or the other\n// and should remember to nil out any references to the parser or lexer when you are done with them.\nfunc WithMemoryManager(use bool) runtimeOption {\n\treturn func(config *runtimeConfiguration) error {\n\t\tconfig.memoryManager = use\n\t\treturn nil\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/dfa.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// DFA represents the Deterministic Finite Automaton used by the recognizer, including all the states it can\n// reach and the transitions between them.\ntype DFA struct {\n\t// atnStartState is the ATN state in which this was created\n\tatnStartState DecisionState\n\n\tdecision int\n\n\t// states is all the DFA states. Use Map to get the old state back; Set can only\n\t// indicate whether it is there. Go maps implement key hash collisions and so on and are very\n\t// good, but the DFAState is an object and can't be used directly as the key as it can in say Java\n\t// amd C#, whereby if the hashcode is the same for two objects, then Equals() is called against them\n\t// to see if they really are the same object. Hence, we have our own map storage.\n\t//\n\tstates *JStore[*DFAState, *ObjEqComparator[*DFAState]]\n\n\tnumstates int\n\n\ts0 *DFAState\n\n\t// precedenceDfa is the backing field for isPrecedenceDfa and setPrecedenceDfa.\n\t// True if the DFA is for a precedence decision and false otherwise.\n\tprecedenceDfa bool\n}\n\nfunc NewDFA(atnStartState DecisionState, decision int) *DFA {\n\tdfa := &DFA{\n\t\tatnStartState: atnStartState,\n\t\tdecision:      decision,\n\t\tstates:        nil, // Lazy initialize\n\t}\n\tif s, ok := atnStartState.(*StarLoopEntryState); ok && s.precedenceRuleDecision {\n\t\tdfa.precedenceDfa = true\n\t\tdfa.s0 = NewDFAState(-1, NewATNConfigSet(false))\n\t\tdfa.s0.isAcceptState = false\n\t\tdfa.s0.requiresFullContext = false\n\t}\n\treturn dfa\n}\n\n// getPrecedenceStartState gets the start state for the current precedence and\n// returns the start state corresponding to the specified precedence if a start\n// state exists for the specified precedence and nil otherwise. d must be a\n// precedence DFA. See also isPrecedenceDfa.\nfunc (d *DFA) getPrecedenceStartState(precedence int) *DFAState {\n\tif !d.getPrecedenceDfa() {\n\t\tpanic(\"only precedence DFAs may contain a precedence start state\")\n\t}\n\n\t// s0.edges is never nil for a precedence DFA\n\tif precedence < 0 || precedence >= len(d.getS0().getEdges()) {\n\t\treturn nil\n\t}\n\n\treturn d.getS0().getIthEdge(precedence)\n}\n\n// setPrecedenceStartState sets the start state for the current precedence. d\n// must be a precedence DFA. See also isPrecedenceDfa.\nfunc (d *DFA) setPrecedenceStartState(precedence int, startState *DFAState) {\n\tif !d.getPrecedenceDfa() {\n\t\tpanic(\"only precedence DFAs may contain a precedence start state\")\n\t}\n\n\tif precedence < 0 {\n\t\treturn\n\t}\n\n\t// Synchronization on s0 here is ok. When the DFA is turned into a\n\t// precedence DFA, s0 will be initialized once and not updated again. s0.edges\n\t// is never nil for a precedence DFA.\n\ts0 := d.getS0()\n\tif precedence >= s0.numEdges() {\n\t\tedges := append(s0.getEdges(), make([]*DFAState, precedence+1-s0.numEdges())...)\n\t\ts0.setEdges(edges)\n\t\td.setS0(s0)\n\t}\n\n\ts0.setIthEdge(precedence, startState)\n}\n\nfunc (d *DFA) getPrecedenceDfa() bool {\n\treturn d.precedenceDfa\n}\n\n// setPrecedenceDfa sets whether d is a precedence DFA. If precedenceDfa differs\n// from the current DFA configuration, then d.states is cleared, the initial\n// state s0 is set to a new DFAState with an empty outgoing DFAState.edges to\n// store the start states for individual precedence values if precedenceDfa is\n// true or nil otherwise, and d.precedenceDfa is updated.\nfunc (d *DFA) setPrecedenceDfa(precedenceDfa bool) {\n\tif d.getPrecedenceDfa() != precedenceDfa {\n\t\td.states = nil // Lazy initialize\n\t\td.numstates = 0\n\n\t\tif precedenceDfa {\n\t\t\tprecedenceState := NewDFAState(-1, NewATNConfigSet(false))\n\t\t\tprecedenceState.setEdges(make([]*DFAState, 0))\n\t\t\tprecedenceState.isAcceptState = false\n\t\t\tprecedenceState.requiresFullContext = false\n\t\t\td.setS0(precedenceState)\n\t\t} else {\n\t\t\td.setS0(nil)\n\t\t}\n\n\t\td.precedenceDfa = precedenceDfa\n\t}\n}\n\n// Len returns the number of states in d. We use this instead of accessing states directly so that we can implement lazy\n// instantiation of the states JMap.\nfunc (d *DFA) Len() int {\n\tif d.states == nil {\n\t\treturn 0\n\t}\n\treturn d.states.Len()\n}\n\n// Get returns a state that matches s if it is present in the DFA state set. We defer to this\n// function instead of accessing states directly so that we can implement lazy instantiation of the states JMap.\nfunc (d *DFA) Get(s *DFAState) (*DFAState, bool) {\n\tif d.states == nil {\n\t\treturn nil, false\n\t}\n\treturn d.states.Get(s)\n}\n\nfunc (d *DFA) Put(s *DFAState) (*DFAState, bool) {\n\tif d.states == nil {\n\t\td.states = NewJStore[*DFAState, *ObjEqComparator[*DFAState]](dfaStateEqInst, DFAStateCollection, \"DFA via DFA.Put\")\n\t}\n\treturn d.states.Put(s)\n}\n\nfunc (d *DFA) getS0() *DFAState {\n\treturn d.s0\n}\n\nfunc (d *DFA) setS0(s *DFAState) {\n\td.s0 = s\n}\n\n// sortedStates returns the states in d sorted by their state number, or an empty set if d.states is nil.\nfunc (d *DFA) sortedStates() []*DFAState {\n\tif d.states == nil {\n\t\treturn []*DFAState{}\n\t}\n\tvs := d.states.SortedSlice(func(i, j *DFAState) bool {\n\t\treturn i.stateNumber < j.stateNumber\n\t})\n\n\treturn vs\n}\n\nfunc (d *DFA) String(literalNames []string, symbolicNames []string) string {\n\tif d.getS0() == nil {\n\t\treturn \"\"\n\t}\n\n\treturn NewDFASerializer(d, literalNames, symbolicNames).String()\n}\n\nfunc (d *DFA) ToLexerString() string {\n\tif d.getS0() == nil {\n\t\treturn \"\"\n\t}\n\n\treturn NewLexerDFASerializer(d).String()\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/dfa_serializer.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// DFASerializer is a DFA walker that knows how to dump the DFA states to serialized\n// strings.\ntype DFASerializer struct {\n\tdfa           *DFA\n\tliteralNames  []string\n\tsymbolicNames []string\n}\n\nfunc NewDFASerializer(dfa *DFA, literalNames, symbolicNames []string) *DFASerializer {\n\tif literalNames == nil {\n\t\tliteralNames = make([]string, 0)\n\t}\n\n\tif symbolicNames == nil {\n\t\tsymbolicNames = make([]string, 0)\n\t}\n\n\treturn &DFASerializer{\n\t\tdfa:           dfa,\n\t\tliteralNames:  literalNames,\n\t\tsymbolicNames: symbolicNames,\n\t}\n}\n\nfunc (d *DFASerializer) String() string {\n\tif d.dfa.getS0() == nil {\n\t\treturn \"\"\n\t}\n\n\tbuf := \"\"\n\tstates := d.dfa.sortedStates()\n\n\tfor _, s := range states {\n\t\tif s.edges != nil {\n\t\t\tn := len(s.edges)\n\n\t\t\tfor j := 0; j < n; j++ {\n\t\t\t\tt := s.edges[j]\n\n\t\t\t\tif t != nil && t.stateNumber != 0x7FFFFFFF {\n\t\t\t\t\tbuf += d.GetStateString(s)\n\t\t\t\t\tbuf += \"-\"\n\t\t\t\t\tbuf += d.getEdgeLabel(j)\n\t\t\t\t\tbuf += \"->\"\n\t\t\t\t\tbuf += d.GetStateString(t)\n\t\t\t\t\tbuf += \"\\n\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(buf) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn buf\n}\n\nfunc (d *DFASerializer) getEdgeLabel(i int) string {\n\tif i == 0 {\n\t\treturn \"EOF\"\n\t} else if d.literalNames != nil && i-1 < len(d.literalNames) {\n\t\treturn d.literalNames[i-1]\n\t} else if d.symbolicNames != nil && i-1 < len(d.symbolicNames) {\n\t\treturn d.symbolicNames[i-1]\n\t}\n\n\treturn strconv.Itoa(i - 1)\n}\n\nfunc (d *DFASerializer) GetStateString(s *DFAState) string {\n\tvar a, b string\n\n\tif s.isAcceptState {\n\t\ta = \":\"\n\t}\n\n\tif s.requiresFullContext {\n\t\tb = \"^\"\n\t}\n\n\tbaseStateStr := a + \"s\" + strconv.Itoa(s.stateNumber) + b\n\n\tif s.isAcceptState {\n\t\tif s.predicates != nil {\n\t\t\treturn baseStateStr + \"=>\" + fmt.Sprint(s.predicates)\n\t\t}\n\n\t\treturn baseStateStr + \"=>\" + fmt.Sprint(s.prediction)\n\t}\n\n\treturn baseStateStr\n}\n\ntype LexerDFASerializer struct {\n\t*DFASerializer\n}\n\nfunc NewLexerDFASerializer(dfa *DFA) *LexerDFASerializer {\n\treturn &LexerDFASerializer{DFASerializer: NewDFASerializer(dfa, nil, nil)}\n}\n\nfunc (l *LexerDFASerializer) getEdgeLabel(i int) string {\n\tvar sb strings.Builder\n\tsb.Grow(6)\n\tsb.WriteByte('\\'')\n\tsb.WriteRune(rune(i))\n\tsb.WriteByte('\\'')\n\treturn sb.String()\n}\n\nfunc (l *LexerDFASerializer) String() string {\n\tif l.dfa.getS0() == nil {\n\t\treturn \"\"\n\t}\n\n\tbuf := \"\"\n\tstates := l.dfa.sortedStates()\n\n\tfor i := 0; i < len(states); i++ {\n\t\ts := states[i]\n\n\t\tif s.edges != nil {\n\t\t\tn := len(s.edges)\n\n\t\t\tfor j := 0; j < n; j++ {\n\t\t\t\tt := s.edges[j]\n\n\t\t\t\tif t != nil && t.stateNumber != 0x7FFFFFFF {\n\t\t\t\t\tbuf += l.GetStateString(s)\n\t\t\t\t\tbuf += \"-\"\n\t\t\t\t\tbuf += l.getEdgeLabel(j)\n\t\t\t\t\tbuf += \"->\"\n\t\t\t\t\tbuf += l.GetStateString(t)\n\t\t\t\t\tbuf += \"\\n\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(buf) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn buf\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/dfa_state.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n)\n\n// PredPrediction maps a predicate to a predicted alternative.\ntype PredPrediction struct {\n\talt  int\n\tpred SemanticContext\n}\n\nfunc NewPredPrediction(pred SemanticContext, alt int) *PredPrediction {\n\treturn &PredPrediction{alt: alt, pred: pred}\n}\n\nfunc (p *PredPrediction) String() string {\n\treturn \"(\" + fmt.Sprint(p.pred) + \", \" + fmt.Sprint(p.alt) + \")\"\n}\n\n// DFAState represents a set of possible [ATN] configurations. As Aho, Sethi,\n// Ullman p. 117 says: \"The DFA uses its state to keep track of all possible\n// states the ATN can be in after reading each input symbol. That is to say,\n// after reading input a1, a2,..an, the DFA is in a state that represents the\n// subset T of the states of the ATN that are reachable from the ATN's start\n// state along some path labeled a1a2..an.\"\n//\n// In conventional NFA-to-DFA conversion, therefore, the subset T would be a bitset representing the set of\n// states the [ATN] could be in. We need to track the alt predicted by each state\n// as well, however. More importantly, we need to maintain a stack of states,\n// tracking the closure operations as they jump from rule to rule, emulating\n// rule invocations (method calls). I have to add a stack to simulate the proper\n// lookahead sequences for the underlying LL grammar from which the ATN was\n// derived.\n//\n// I use a set of [ATNConfig] objects, not simple states. An [ATNConfig] is both a\n// state (ala normal conversion) and a [RuleContext] describing the chain of rules\n// (if any) followed to arrive at that state.\n//\n// A [DFAState] may have multiple references to a particular state, but with\n// different [ATN] contexts (with same or different alts) meaning that state was\n// reached via a different set of rule invocations.\ntype DFAState struct {\n\tstateNumber int\n\tconfigs     *ATNConfigSet\n\n\t// edges elements point to the target of the symbol. Shift up by 1 so (-1)\n\t// Token.EOF maps to the first element.\n\tedges []*DFAState\n\n\tisAcceptState bool\n\n\t// prediction is the 'ttype' we match or alt we predict if the state is 'accept'.\n\t// Set to ATN.INVALID_ALT_NUMBER when predicates != nil or\n\t// requiresFullContext.\n\tprediction int\n\n\tlexerActionExecutor *LexerActionExecutor\n\n\t// requiresFullContext indicates it was created during an SLL prediction that\n\t// discovered a conflict between the configurations in the state. Future\n\t// ParserATNSimulator.execATN invocations immediately jump doing\n\t// full context prediction if true.\n\trequiresFullContext bool\n\n\t// predicates is the predicates associated with the ATN configurations of the\n\t// DFA state during SLL parsing. When we have predicates, requiresFullContext\n\t// is false, since full context prediction evaluates predicates on-the-fly. If\n\t// d is\n\t// not nil, then prediction is ATN.INVALID_ALT_NUMBER.\n\t//\n\t// We only use these for non-requiresFullContext but conflicting states. That\n\t// means we know from the context (it's $ or we don't dip into outer context)\n\t// that it's an ambiguity not a conflict.\n\t//\n\t// This list is computed by\n\t// ParserATNSimulator.predicateDFAState.\n\tpredicates []*PredPrediction\n}\n\nfunc NewDFAState(stateNumber int, configs *ATNConfigSet) *DFAState {\n\tif configs == nil {\n\t\tconfigs = NewATNConfigSet(false)\n\t}\n\n\treturn &DFAState{configs: configs, stateNumber: stateNumber}\n}\n\n// GetAltSet gets the set of all alts mentioned by all ATN configurations in d.\nfunc (d *DFAState) GetAltSet() []int {\n\tvar alts []int\n\n\tif d.configs != nil {\n\t\tfor _, c := range d.configs.configs {\n\t\t\talts = append(alts, c.GetAlt())\n\t\t}\n\t}\n\n\tif len(alts) == 0 {\n\t\treturn nil\n\t}\n\n\treturn alts\n}\n\nfunc (d *DFAState) getEdges() []*DFAState {\n\treturn d.edges\n}\n\nfunc (d *DFAState) numEdges() int {\n\treturn len(d.edges)\n}\n\nfunc (d *DFAState) getIthEdge(i int) *DFAState {\n\treturn d.edges[i]\n}\n\nfunc (d *DFAState) setEdges(newEdges []*DFAState) {\n\td.edges = newEdges\n}\n\nfunc (d *DFAState) setIthEdge(i int, edge *DFAState) {\n\td.edges[i] = edge\n}\n\nfunc (d *DFAState) setPrediction(v int) {\n\td.prediction = v\n}\n\nfunc (d *DFAState) String() string {\n\tvar s string\n\tif d.isAcceptState {\n\t\tif d.predicates != nil {\n\t\t\ts = \"=>\" + fmt.Sprint(d.predicates)\n\t\t} else {\n\t\t\ts = \"=>\" + fmt.Sprint(d.prediction)\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%d:%s%s\", d.stateNumber, fmt.Sprint(d.configs), s)\n}\n\nfunc (d *DFAState) Hash() int {\n\th := murmurInit(7)\n\th = murmurUpdate(h, d.configs.Hash())\n\treturn murmurFinish(h, 1)\n}\n\n// Equals returns whether d equals other. Two DFAStates are equal if their ATN\n// configuration sets are the same. This method is used to see if a state\n// already exists.\n//\n// Because the number of alternatives and number of ATN configurations are\n// finite, there is a finite number of DFA states that can be processed. This is\n// necessary to show that the algorithm terminates.\n//\n// Cannot test the DFA state numbers here because in\n// ParserATNSimulator.addDFAState we need to know if any other state exists that\n// has d exact set of ATN configurations. The stateNumber is irrelevant.\nfunc (d *DFAState) Equals(o Collectable[*DFAState]) bool {\n\tif d == o {\n\t\treturn true\n\t}\n\n\treturn d.configs.Equals(o.(*DFAState).configs)\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/diagnostic_error_listener.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"strconv\"\n)\n\n//\n// This implementation of {@link ANTLRErrorListener} can be used to identify\n// certain potential correctness and performance problems in grammars. \"reports\"\n// are made by calling {@link Parser//NotifyErrorListeners} with the appropriate\n// message.\n//\n// <ul>\n// <li><b>Ambiguities</b>: These are cases where more than one path through the\n// grammar can Match the input.</li>\n// <li><b>Weak context sensitivity</b>: These are cases where full-context\n// prediction resolved an SLL conflict to a unique alternative which equaled the\n// minimum alternative of the SLL conflict.</li>\n// <li><b>Strong (forced) context sensitivity</b>: These are cases where the\n// full-context prediction resolved an SLL conflict to a unique alternative,\n// <em>and</em> the minimum alternative of the SLL conflict was found to not be\n// a truly viable alternative. Two-stage parsing cannot be used for inputs where\n// d situation occurs.</li>\n// </ul>\n\ntype DiagnosticErrorListener struct {\n\t*DefaultErrorListener\n\n\texactOnly bool\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewDiagnosticErrorListener(exactOnly bool) *DiagnosticErrorListener {\n\n\tn := new(DiagnosticErrorListener)\n\n\t// whether all ambiguities or only exact ambiguities are Reported.\n\tn.exactOnly = exactOnly\n\treturn n\n}\n\nfunc (d *DiagnosticErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {\n\tif d.exactOnly && !exact {\n\t\treturn\n\t}\n\tmsg := \"reportAmbiguity d=\" +\n\t\td.getDecisionDescription(recognizer, dfa) +\n\t\t\": ambigAlts=\" +\n\t\td.getConflictingAlts(ambigAlts, configs).String() +\n\t\t\", input='\" +\n\t\trecognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + \"'\"\n\trecognizer.NotifyErrorListeners(msg, nil, nil)\n}\n\nfunc (d *DiagnosticErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, _ *BitSet, _ *ATNConfigSet) {\n\n\tmsg := \"reportAttemptingFullContext d=\" +\n\t\td.getDecisionDescription(recognizer, dfa) +\n\t\t\", input='\" +\n\t\trecognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + \"'\"\n\trecognizer.NotifyErrorListeners(msg, nil, nil)\n}\n\nfunc (d *DiagnosticErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, _ int, _ *ATNConfigSet) {\n\tmsg := \"reportContextSensitivity d=\" +\n\t\td.getDecisionDescription(recognizer, dfa) +\n\t\t\", input='\" +\n\t\trecognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + \"'\"\n\trecognizer.NotifyErrorListeners(msg, nil, nil)\n}\n\nfunc (d *DiagnosticErrorListener) getDecisionDescription(recognizer Parser, dfa *DFA) string {\n\tdecision := dfa.decision\n\truleIndex := dfa.atnStartState.GetRuleIndex()\n\n\truleNames := recognizer.GetRuleNames()\n\tif ruleIndex < 0 || ruleIndex >= len(ruleNames) {\n\t\treturn strconv.Itoa(decision)\n\t}\n\truleName := ruleNames[ruleIndex]\n\tif ruleName == \"\" {\n\t\treturn strconv.Itoa(decision)\n\t}\n\treturn strconv.Itoa(decision) + \" (\" + ruleName + \")\"\n}\n\n// Computes the set of conflicting or ambiguous alternatives from a\n// configuration set, if that information was not already provided by the\n// parser.\n//\n// @param ReportedAlts The set of conflicting or ambiguous alternatives, as\n// Reported by the parser.\n// @param configs The conflicting or ambiguous configuration set.\n// @return Returns {@code ReportedAlts} if it is not {@code nil}, otherwise\n// returns the set of alternatives represented in {@code configs}.\nfunc (d *DiagnosticErrorListener) getConflictingAlts(ReportedAlts *BitSet, set *ATNConfigSet) *BitSet {\n\tif ReportedAlts != nil {\n\t\treturn ReportedAlts\n\t}\n\tresult := NewBitSet()\n\tfor _, c := range set.configs {\n\t\tresult.add(c.GetAlt())\n\t}\n\n\treturn result\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/error_listener.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n)\n\n// Provides an empty default implementation of {@link ANTLRErrorListener}. The\n// default implementation of each method does nothing, but can be overridden as\n// necessary.\n\ntype ErrorListener interface {\n\tSyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException)\n\tReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet)\n\tReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet)\n\tReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet)\n}\n\ntype DefaultErrorListener struct {\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewDefaultErrorListener() *DefaultErrorListener {\n\treturn new(DefaultErrorListener)\n}\n\nfunc (d *DefaultErrorListener) SyntaxError(_ Recognizer, _ interface{}, _, _ int, _ string, _ RecognitionException) {\n}\n\nfunc (d *DefaultErrorListener) ReportAmbiguity(_ Parser, _ *DFA, _, _ int, _ bool, _ *BitSet, _ *ATNConfigSet) {\n}\n\nfunc (d *DefaultErrorListener) ReportAttemptingFullContext(_ Parser, _ *DFA, _, _ int, _ *BitSet, _ *ATNConfigSet) {\n}\n\nfunc (d *DefaultErrorListener) ReportContextSensitivity(_ Parser, _ *DFA, _, _, _ int, _ *ATNConfigSet) {\n}\n\ntype ConsoleErrorListener struct {\n\t*DefaultErrorListener\n}\n\nfunc NewConsoleErrorListener() *ConsoleErrorListener {\n\treturn new(ConsoleErrorListener)\n}\n\n// ConsoleErrorListenerINSTANCE provides a default instance of {@link ConsoleErrorListener}.\nvar ConsoleErrorListenerINSTANCE = NewConsoleErrorListener()\n\n// SyntaxError prints messages to System.err containing the\n// values of line, charPositionInLine, and msg using\n// the following format:\n//\n//\tline <line>:<charPositionInLine> <msg>\nfunc (c *ConsoleErrorListener) SyntaxError(_ Recognizer, _ interface{}, line, column int, msg string, _ RecognitionException) {\n\t_, _ = fmt.Fprintln(os.Stderr, \"line \"+strconv.Itoa(line)+\":\"+strconv.Itoa(column)+\" \"+msg)\n}\n\ntype ProxyErrorListener struct {\n\t*DefaultErrorListener\n\tdelegates []ErrorListener\n}\n\nfunc NewProxyErrorListener(delegates []ErrorListener) *ProxyErrorListener {\n\tif delegates == nil {\n\t\tpanic(\"delegates is not provided\")\n\t}\n\tl := new(ProxyErrorListener)\n\tl.delegates = delegates\n\treturn l\n}\n\nfunc (p *ProxyErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) {\n\tfor _, d := range p.delegates {\n\t\td.SyntaxError(recognizer, offendingSymbol, line, column, msg, e)\n\t}\n}\n\nfunc (p *ProxyErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs *ATNConfigSet) {\n\tfor _, d := range p.delegates {\n\t\td.ReportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs)\n\t}\n}\n\nfunc (p *ProxyErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs *ATNConfigSet) {\n\tfor _, d := range p.delegates {\n\t\td.ReportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs)\n\t}\n}\n\nfunc (p *ProxyErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs *ATNConfigSet) {\n\tfor _, d := range p.delegates {\n\t\td.ReportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs)\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/error_strategy.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype ErrorStrategy interface {\n\treset(Parser)\n\tRecoverInline(Parser) Token\n\tRecover(Parser, RecognitionException)\n\tSync(Parser)\n\tInErrorRecoveryMode(Parser) bool\n\tReportError(Parser, RecognitionException)\n\tReportMatch(Parser)\n}\n\n// DefaultErrorStrategy is the default implementation of ANTLRErrorStrategy used for\n// error reporting and recovery in ANTLR parsers.\ntype DefaultErrorStrategy struct {\n\terrorRecoveryMode bool\n\tlastErrorIndex    int\n\tlastErrorStates   *IntervalSet\n}\n\nvar _ ErrorStrategy = &DefaultErrorStrategy{}\n\nfunc NewDefaultErrorStrategy() *DefaultErrorStrategy {\n\n\td := new(DefaultErrorStrategy)\n\n\t// Indicates whether the error strategy is currently \"recovering from an\n\t// error\". This is used to suppress Reporting multiple error messages while\n\t// attempting to recover from a detected syntax error.\n\t//\n\t// @see //InErrorRecoveryMode\n\t//\n\td.errorRecoveryMode = false\n\n\t// The index into the input stream where the last error occurred.\n\t// This is used to prevent infinite loops where an error is found\n\t// but no token is consumed during recovery...another error is found,\n\t// ad nauseam. This is a failsafe mechanism to guarantee that at least\n\t// one token/tree node is consumed for two errors.\n\t//\n\td.lastErrorIndex = -1\n\td.lastErrorStates = nil\n\treturn d\n}\n\n// <p>The default implementation simply calls {@link //endErrorCondition} to\n// ensure that the handler is not in error recovery mode.</p>\nfunc (d *DefaultErrorStrategy) reset(recognizer Parser) {\n\td.endErrorCondition(recognizer)\n}\n\n// This method is called to enter error recovery mode when a recognition\n// exception is Reported.\nfunc (d *DefaultErrorStrategy) beginErrorCondition(_ Parser) {\n\td.errorRecoveryMode = true\n}\n\nfunc (d *DefaultErrorStrategy) InErrorRecoveryMode(_ Parser) bool {\n\treturn d.errorRecoveryMode\n}\n\n// This method is called to leave error recovery mode after recovering from\n// a recognition exception.\nfunc (d *DefaultErrorStrategy) endErrorCondition(_ Parser) {\n\td.errorRecoveryMode = false\n\td.lastErrorStates = nil\n\td.lastErrorIndex = -1\n}\n\n// ReportMatch is the default implementation of error matching and simply calls endErrorCondition.\nfunc (d *DefaultErrorStrategy) ReportMatch(recognizer Parser) {\n\td.endErrorCondition(recognizer)\n}\n\n// ReportError is the default implementation of error reporting.\n// It returns immediately if the handler is already\n// in error recovery mode. Otherwise, it calls [beginErrorCondition]\n// and dispatches the Reporting task based on the runtime type of e\n// according to the following table.\n//\n//\t\t [NoViableAltException]     : Dispatches the call to [ReportNoViableAlternative]\n//\t\t [InputMisMatchException]   : Dispatches the call to [ReportInputMisMatch]\n//\t  [FailedPredicateException] : Dispatches the call to [ReportFailedPredicate]\n//\t  All other types            : Calls [NotifyErrorListeners] to Report the exception\nfunc (d *DefaultErrorStrategy) ReportError(recognizer Parser, e RecognitionException) {\n\t// if we've already Reported an error and have not Matched a token\n\t// yet successfully, don't Report any errors.\n\tif d.InErrorRecoveryMode(recognizer) {\n\t\treturn // don't Report spurious errors\n\t}\n\td.beginErrorCondition(recognizer)\n\n\tswitch t := e.(type) {\n\tdefault:\n\t\tfmt.Println(\"unknown recognition error type: \" + reflect.TypeOf(e).Name())\n\t\t//            fmt.Println(e.stack)\n\t\trecognizer.NotifyErrorListeners(e.GetMessage(), e.GetOffendingToken(), e)\n\tcase *NoViableAltException:\n\t\td.ReportNoViableAlternative(recognizer, t)\n\tcase *InputMisMatchException:\n\t\td.ReportInputMisMatch(recognizer, t)\n\tcase *FailedPredicateException:\n\t\td.ReportFailedPredicate(recognizer, t)\n\t}\n}\n\n// Recover is the default recovery implementation.\n// It reSynchronizes the parser by consuming tokens until we find one in the reSynchronization set -\n// loosely the set of tokens that can follow the current rule.\nfunc (d *DefaultErrorStrategy) Recover(recognizer Parser, _ RecognitionException) {\n\n\tif d.lastErrorIndex == recognizer.GetInputStream().Index() &&\n\t\td.lastErrorStates != nil && d.lastErrorStates.contains(recognizer.GetState()) {\n\t\t// uh oh, another error at same token index and previously-Visited\n\t\t// state in ATN must be a case where LT(1) is in the recovery\n\t\t// token set so nothing got consumed. Consume a single token\n\t\t// at least to prevent an infinite loop d is a failsafe.\n\t\trecognizer.Consume()\n\t}\n\td.lastErrorIndex = recognizer.GetInputStream().Index()\n\tif d.lastErrorStates == nil {\n\t\td.lastErrorStates = NewIntervalSet()\n\t}\n\td.lastErrorStates.addOne(recognizer.GetState())\n\tfollowSet := d.GetErrorRecoverySet(recognizer)\n\td.consumeUntil(recognizer, followSet)\n}\n\n// Sync is the default implementation of error strategy synchronization.\n//\n// This Sync makes sure that the current lookahead symbol is consistent with what were expecting\n// at this point in the [ATN]. You can call this anytime but ANTLR only\n// generates code to check before sub-rules/loops and each iteration.\n//\n// Implements [Jim Idle]'s magic Sync mechanism in closures and optional\n// sub-rules. E.g.:\n//\n//\ta    : Sync ( stuff Sync )*\n//\tSync : {consume to what can follow Sync}\n//\n// At the start of a sub-rule upon error, Sync performs single\n// token deletion, if possible. If it can't do that, it bails on the current\n// rule and uses the default error recovery, which consumes until the\n// reSynchronization set of the current rule.\n//\n// If the sub-rule is optional\n//\n//\t({@code (...)?}, {@code (...)*},\n//\n// or a block with an empty alternative), then the expected set includes what follows\n// the sub-rule.\n//\n// During loop iteration, it consumes until it sees a token that can start a\n// sub-rule or what follows loop. Yes, that is pretty aggressive. We opt to\n// stay in the loop as long as possible.\n//\n// # Origins\n//\n// Previous versions of ANTLR did a poor job of their recovery within loops.\n// A single mismatch token or missing token would force the parser to bail\n// out of the entire rules surrounding the loop. So, for rule:\n//\n//\tclassfunc : 'class' ID '{' member* '}'\n//\n// input with an extra token between members would force the parser to\n// consume until it found the next class definition rather than the next\n// member definition of the current class.\n//\n// This functionality cost a bit of effort because the parser has to\n// compare the token set at the start of the loop and at each iteration. If for\n// some reason speed is suffering for you, you can turn off this\n// functionality by simply overriding this method as empty:\n//\n//\t{ }\n//\n// [Jim Idle]: https://github.com/jimidle\nfunc (d *DefaultErrorStrategy) Sync(recognizer Parser) {\n\t// If already recovering, don't try to Sync\n\tif d.InErrorRecoveryMode(recognizer) {\n\t\treturn\n\t}\n\n\ts := recognizer.GetInterpreter().atn.states[recognizer.GetState()]\n\tla := recognizer.GetTokenStream().LA(1)\n\n\t// try cheaper subset first might get lucky. seems to shave a wee bit off\n\tnextTokens := recognizer.GetATN().NextTokens(s, nil)\n\tif nextTokens.contains(TokenEpsilon) || nextTokens.contains(la) {\n\t\treturn\n\t}\n\n\tswitch s.GetStateType() {\n\tcase ATNStateBlockStart, ATNStateStarBlockStart, ATNStatePlusBlockStart, ATNStateStarLoopEntry:\n\t\t// Report error and recover if possible\n\t\tif d.SingleTokenDeletion(recognizer) != nil {\n\t\t\treturn\n\t\t}\n\t\trecognizer.SetError(NewInputMisMatchException(recognizer))\n\tcase ATNStatePlusLoopBack, ATNStateStarLoopBack:\n\t\td.ReportUnwantedToken(recognizer)\n\t\texpecting := NewIntervalSet()\n\t\texpecting.addSet(recognizer.GetExpectedTokens())\n\t\twhatFollowsLoopIterationOrRule := expecting.addSet(d.GetErrorRecoverySet(recognizer))\n\t\td.consumeUntil(recognizer, whatFollowsLoopIterationOrRule)\n\tdefault:\n\t\t// do nothing if we can't identify the exact kind of ATN state\n\t}\n}\n\n// ReportNoViableAlternative is called by [ReportError] when the exception is a [NoViableAltException].\n//\n// See also [ReportError]\nfunc (d *DefaultErrorStrategy) ReportNoViableAlternative(recognizer Parser, e *NoViableAltException) {\n\ttokens := recognizer.GetTokenStream()\n\tvar input string\n\tif tokens != nil {\n\t\tif e.startToken.GetTokenType() == TokenEOF {\n\t\t\tinput = \"<EOF>\"\n\t\t} else {\n\t\t\tinput = tokens.GetTextFromTokens(e.startToken, e.offendingToken)\n\t\t}\n\t} else {\n\t\tinput = \"<unknown input>\"\n\t}\n\tmsg := \"no viable alternative at input \" + d.escapeWSAndQuote(input)\n\trecognizer.NotifyErrorListeners(msg, e.offendingToken, e)\n}\n\n// ReportInputMisMatch is called by [ReportError] when the exception is an [InputMisMatchException]\n//\n// See also: [ReportError]\nfunc (d *DefaultErrorStrategy) ReportInputMisMatch(recognizer Parser, e *InputMisMatchException) {\n\tmsg := \"mismatched input \" + d.GetTokenErrorDisplay(e.offendingToken) +\n\t\t\" expecting \" + e.getExpectedTokens().StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false)\n\trecognizer.NotifyErrorListeners(msg, e.offendingToken, e)\n}\n\n// ReportFailedPredicate is called by [ReportError] when the exception is a [FailedPredicateException].\n//\n// See also: [ReportError]\nfunc (d *DefaultErrorStrategy) ReportFailedPredicate(recognizer Parser, e *FailedPredicateException) {\n\truleName := recognizer.GetRuleNames()[recognizer.GetParserRuleContext().GetRuleIndex()]\n\tmsg := \"rule \" + ruleName + \" \" + e.message\n\trecognizer.NotifyErrorListeners(msg, e.offendingToken, e)\n}\n\n// ReportUnwantedToken is called to report a syntax error that requires the removal\n// of a token from the input stream. At the time d method is called, the\n// erroneous symbol is the current LT(1) symbol and has not yet been\n// removed from the input stream. When this method returns,\n// recognizer is in error recovery mode.\n//\n// This method is called when singleTokenDeletion identifies\n// single-token deletion as a viable recovery strategy for a mismatched\n// input error.\n//\n// The default implementation simply returns if the handler is already in\n// error recovery mode. Otherwise, it calls beginErrorCondition to\n// enter error recovery mode, followed by calling\n// [NotifyErrorListeners]\nfunc (d *DefaultErrorStrategy) ReportUnwantedToken(recognizer Parser) {\n\tif d.InErrorRecoveryMode(recognizer) {\n\t\treturn\n\t}\n\td.beginErrorCondition(recognizer)\n\tt := recognizer.GetCurrentToken()\n\ttokenName := d.GetTokenErrorDisplay(t)\n\texpecting := d.GetExpectedTokens(recognizer)\n\tmsg := \"extraneous input \" + tokenName + \" expecting \" +\n\t\texpecting.StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false)\n\trecognizer.NotifyErrorListeners(msg, t, nil)\n}\n\n// ReportMissingToken is called to report a syntax error which requires the\n// insertion of a missing token into the input stream. At the time this\n// method is called, the missing token has not yet been inserted. When this\n// method returns, recognizer is in error recovery mode.\n//\n// This method is called when singleTokenInsertion identifies\n// single-token insertion as a viable recovery strategy for a mismatched\n// input error.\n//\n// The default implementation simply returns if the handler is already in\n// error recovery mode. Otherwise, it calls beginErrorCondition to\n// enter error recovery mode, followed by calling [NotifyErrorListeners]\nfunc (d *DefaultErrorStrategy) ReportMissingToken(recognizer Parser) {\n\tif d.InErrorRecoveryMode(recognizer) {\n\t\treturn\n\t}\n\td.beginErrorCondition(recognizer)\n\tt := recognizer.GetCurrentToken()\n\texpecting := d.GetExpectedTokens(recognizer)\n\tmsg := \"missing \" + expecting.StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false) +\n\t\t\" at \" + d.GetTokenErrorDisplay(t)\n\trecognizer.NotifyErrorListeners(msg, t, nil)\n}\n\n// The RecoverInline default implementation attempts to recover from the mismatched input\n// by using single token insertion and deletion as described below. If the\n// recovery attempt fails, this method panics with [InputMisMatchException}.\n// TODO: Not sure that panic() is the right thing to do here - JI\n//\n// # EXTRA TOKEN (single token deletion)\n//\n// LA(1) is not what we are looking for. If LA(2) has the\n// right token, however, then assume LA(1) is some extra spurious\n// token and delete it. Then consume and return the next token (which was\n// the LA(2) token) as the successful result of the Match operation.\n//\n// # This recovery strategy is implemented by singleTokenDeletion\n//\n// # MISSING TOKEN (single token insertion)\n//\n// If current token  -at LA(1) - is consistent with what could come\n// after the expected LA(1) token, then assume the token is missing\n// and use the parser's [TokenFactory] to create it on the fly. The\n// “insertion” is performed by returning the created token as the successful\n// result of the Match operation.\n//\n// This recovery strategy is implemented by [SingleTokenInsertion].\n//\n// # Example\n//\n// For example, Input i=(3 is clearly missing the ')'. When\n// the parser returns from the nested call to expr, it will have\n// call the chain:\n//\n//\tstat → expr → atom\n//\n// and it will be trying to Match the ')' at this point in the\n// derivation:\n//\n//\t  : ID '=' '(' INT ')' ('+' atom)* ';'\n//\t\t                ^\n//\n// The attempt to [Match] ')' will fail when it sees ';' and\n// call [RecoverInline]. To recover, it sees that LA(1)==';'\n// is in the set of tokens that can follow the ')' token reference\n// in rule atom. It can assume that you forgot the ')'.\nfunc (d *DefaultErrorStrategy) RecoverInline(recognizer Parser) Token {\n\t// SINGLE TOKEN DELETION\n\tMatchedSymbol := d.SingleTokenDeletion(recognizer)\n\tif MatchedSymbol != nil {\n\t\t// we have deleted the extra token.\n\t\t// now, move past ttype token as if all were ok\n\t\trecognizer.Consume()\n\t\treturn MatchedSymbol\n\t}\n\t// SINGLE TOKEN INSERTION\n\tif d.SingleTokenInsertion(recognizer) {\n\t\treturn d.GetMissingSymbol(recognizer)\n\t}\n\t// even that didn't work must panic the exception\n\trecognizer.SetError(NewInputMisMatchException(recognizer))\n\treturn nil\n}\n\n// SingleTokenInsertion implements the single-token insertion inline error recovery\n// strategy. It is called by [RecoverInline] if the single-token\n// deletion strategy fails to recover from the mismatched input. If this\n// method returns {@code true}, {@code recognizer} will be in error recovery\n// mode.\n//\n// This method determines whether single-token insertion is viable by\n// checking if the LA(1) input symbol could be successfully Matched\n// if it were instead the LA(2) symbol. If this method returns\n// {@code true}, the caller is responsible for creating and inserting a\n// token with the correct type to produce this behavior.</p>\n//\n// This func returns true if single-token insertion is a viable recovery\n// strategy for the current mismatched input.\nfunc (d *DefaultErrorStrategy) SingleTokenInsertion(recognizer Parser) bool {\n\tcurrentSymbolType := recognizer.GetTokenStream().LA(1)\n\t// if current token is consistent with what could come after current\n\t// ATN state, then we know we're missing a token error recovery\n\t// is free to conjure up and insert the missing token\n\tatn := recognizer.GetInterpreter().atn\n\tcurrentState := atn.states[recognizer.GetState()]\n\tnext := currentState.GetTransitions()[0].getTarget()\n\texpectingAtLL2 := atn.NextTokens(next, recognizer.GetParserRuleContext())\n\tif expectingAtLL2.contains(currentSymbolType) {\n\t\td.ReportMissingToken(recognizer)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// SingleTokenDeletion implements the single-token deletion inline error recovery\n// strategy. It is called by [RecoverInline] to attempt to recover\n// from mismatched input. If this method returns nil, the parser and error\n// handler state will not have changed. If this method returns non-nil,\n// recognizer will not be in error recovery mode since the\n// returned token was a successful Match.\n//\n// If the single-token deletion is successful, this method calls\n// [ReportUnwantedToken] to Report the error, followed by\n// [Consume] to actually “delete” the extraneous token. Then,\n// before returning, [ReportMatch] is called to signal a successful\n// Match.\n//\n// The func returns the successfully Matched [Token] instance if single-token\n// deletion successfully recovers from the mismatched input, otherwise nil.\nfunc (d *DefaultErrorStrategy) SingleTokenDeletion(recognizer Parser) Token {\n\tNextTokenType := recognizer.GetTokenStream().LA(2)\n\texpecting := d.GetExpectedTokens(recognizer)\n\tif expecting.contains(NextTokenType) {\n\t\td.ReportUnwantedToken(recognizer)\n\t\t// print(\"recoverFromMisMatchedToken deleting \" \\\n\t\t// + str(recognizer.GetTokenStream().LT(1)) \\\n\t\t// + \" since \" + str(recognizer.GetTokenStream().LT(2)) \\\n\t\t// + \" is what we want\", file=sys.stderr)\n\t\trecognizer.Consume() // simply delete extra token\n\t\t// we want to return the token we're actually Matching\n\t\tMatchedSymbol := recognizer.GetCurrentToken()\n\t\td.ReportMatch(recognizer) // we know current token is correct\n\t\treturn MatchedSymbol\n\t}\n\n\treturn nil\n}\n\n// GetMissingSymbol conjures up a missing token during error recovery.\n//\n// The recognizer attempts to recover from single missing\n// symbols. But, actions might refer to that missing symbol.\n// For example:\n//\n//\tx=ID {f($x)}.\n//\n// The action clearly assumes\n// that there has been an identifier Matched previously and that\n// $x points at that token. If that token is missing, but\n// the next token in the stream is what we want we assume that\n// this token is missing, and we keep going. Because we\n// have to return some token to replace the missing token,\n// we have to conjure one up. This method gives the user control\n// over the tokens returned for missing tokens. Mostly,\n// you will want to create something special for identifier\n// tokens. For literals such as '{' and ',', the default\n// action in the parser or tree parser works. It simply creates\n// a [CommonToken] of the appropriate type. The text will be the token name.\n// If you need to change which tokens must be created by the lexer,\n// override this method to create the appropriate tokens.\nfunc (d *DefaultErrorStrategy) GetMissingSymbol(recognizer Parser) Token {\n\tcurrentSymbol := recognizer.GetCurrentToken()\n\texpecting := d.GetExpectedTokens(recognizer)\n\texpectedTokenType := expecting.first()\n\tvar tokenText string\n\n\tif expectedTokenType == TokenEOF {\n\t\ttokenText = \"<missing EOF>\"\n\t} else {\n\t\tln := recognizer.GetLiteralNames()\n\t\tif expectedTokenType > 0 && expectedTokenType < len(ln) {\n\t\t\ttokenText = \"<missing \" + recognizer.GetLiteralNames()[expectedTokenType] + \">\"\n\t\t} else {\n\t\t\ttokenText = \"<missing undefined>\" // TODO: matches the JS impl\n\t\t}\n\t}\n\tcurrent := currentSymbol\n\tlookback := recognizer.GetTokenStream().LT(-1)\n\tif current.GetTokenType() == TokenEOF && lookback != nil {\n\t\tcurrent = lookback\n\t}\n\n\ttf := recognizer.GetTokenFactory()\n\n\treturn tf.Create(current.GetSource(), expectedTokenType, tokenText, TokenDefaultChannel, -1, -1, current.GetLine(), current.GetColumn())\n}\n\nfunc (d *DefaultErrorStrategy) GetExpectedTokens(recognizer Parser) *IntervalSet {\n\treturn recognizer.GetExpectedTokens()\n}\n\n// GetTokenErrorDisplay determines how  a token should be displayed in an error message.\n// The default is to display just the text, but during development you might\n// want to have a lot of information spit out. Override this func in that case\n// to use t.String() (which, for [CommonToken], dumps everything about\n// the token). This is better than forcing you to override a method in\n// your token objects because you don't have to go modify your lexer\n// so that it creates a new type.\nfunc (d *DefaultErrorStrategy) GetTokenErrorDisplay(t Token) string {\n\tif t == nil {\n\t\treturn \"<no token>\"\n\t}\n\ts := t.GetText()\n\tif s == \"\" {\n\t\tif t.GetTokenType() == TokenEOF {\n\t\t\ts = \"<EOF>\"\n\t\t} else {\n\t\t\ts = \"<\" + strconv.Itoa(t.GetTokenType()) + \">\"\n\t\t}\n\t}\n\treturn d.escapeWSAndQuote(s)\n}\n\nfunc (d *DefaultErrorStrategy) escapeWSAndQuote(s string) string {\n\ts = strings.Replace(s, \"\\t\", \"\\\\t\", -1)\n\ts = strings.Replace(s, \"\\n\", \"\\\\n\", -1)\n\ts = strings.Replace(s, \"\\r\", \"\\\\r\", -1)\n\treturn \"'\" + s + \"'\"\n}\n\n// GetErrorRecoverySet computes the error recovery set for the current rule. During\n// rule invocation, the parser pushes the set of tokens that can\n// follow that rule reference on the stack. This amounts to\n// computing FIRST of what follows the rule reference in the\n// enclosing rule. See LinearApproximator.FIRST().\n//\n// This local follow set only includes tokens\n// from within the rule i.e., the FIRST computation done by\n// ANTLR stops at the end of a rule.\n//\n// # Example\n//\n// When you find a \"no viable alt exception\", the input is not\n// consistent with any of the alternatives for rule r. The best\n// thing to do is to consume tokens until you see something that\n// can legally follow a call to r or any rule that called r.\n// You don't want the exact set of viable next tokens because the\n// input might just be missing a token--you might consume the\n// rest of the input looking for one of the missing tokens.\n//\n// Consider the grammar:\n//\n//\t\ta : '[' b ']'\n//\t\t  | '(' b ')'\n//\t\t  ;\n//\n//\t\tb : c '^' INT\n//\t      ;\n//\n//\t\tc : ID\n//\t\t  | INT\n//\t\t  ;\n//\n// At each rule invocation, the set of tokens that could follow\n// that rule is pushed on a stack. Here are the various\n// context-sensitive follow sets:\n//\n//\tFOLLOW(b1_in_a) = FIRST(']') = ']'\n//\tFOLLOW(b2_in_a) = FIRST(')') = ')'\n//\tFOLLOW(c_in_b)  = FIRST('^') = '^'\n//\n// Upon erroneous input “[]”, the call chain is\n//\n//\ta → b → c\n//\n// and, hence, the follow context stack is:\n//\n//\tDepth Follow set   Start of rule execution\n//\t  0   <EOF>        a (from main())\n//\t  1   ']'          b\n//\t  2   '^'          c\n//\n// Notice that ')' is not included, because b would have to have\n// been called from a different context in rule a for ')' to be\n// included.\n//\n// For error recovery, we cannot consider FOLLOW(c)\n// (context-sensitive or otherwise). We need the combined set of\n// all context-sensitive FOLLOW sets - the set of all tokens that\n// could follow any reference in the call chain. We need to\n// reSync to one of those tokens. Note that FOLLOW(c)='^' and if\n// we reSync'd to that token, we'd consume until EOF. We need to\n// Sync to context-sensitive FOLLOWs for a, b, and c:\n//\n//\t{']','^'}\n//\n// In this case, for input \"[]\", LA(1) is ']' and in the set, so we would\n// not consume anything. After printing an error, rule c would\n// return normally. Rule b would not find the required '^' though.\n// At this point, it gets a mismatched token error and panics an\n// exception (since LA(1) is not in the viable following token\n// set). The rule exception handler tries to recover, but finds\n// the same recovery set and doesn't consume anything. Rule b\n// exits normally returning to rule a. Now it finds the ']' (and\n// with the successful Match exits errorRecovery mode).\n//\n// So, you can see that the parser walks up the call chain looking\n// for the token that was a member of the recovery set.\n//\n// Errors are not generated in errorRecovery mode.\n//\n// ANTLR's error recovery mechanism is based upon original ideas:\n//\n// [Algorithms + Data Structures = Programs] by Niklaus Wirth and\n// [A note on error recovery in recursive descent parsers].\n//\n// Later, Josef Grosch had some good ideas in [Efficient and Comfortable Error Recovery in Recursive Descent\n// Parsers]\n//\n// Like Grosch I implement context-sensitive FOLLOW sets that are combined  at run-time upon error to avoid overhead\n// during parsing. Later, the runtime Sync was improved for loops/sub-rules see [Sync] docs\n//\n// [A note on error recovery in recursive descent parsers]: http://portal.acm.org/citation.cfm?id=947902.947905\n// [Algorithms + Data Structures = Programs]: https://t.ly/5QzgE\n// [Efficient and Comfortable Error Recovery in Recursive Descent Parsers]: ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip\nfunc (d *DefaultErrorStrategy) GetErrorRecoverySet(recognizer Parser) *IntervalSet {\n\tatn := recognizer.GetInterpreter().atn\n\tctx := recognizer.GetParserRuleContext()\n\trecoverSet := NewIntervalSet()\n\tfor ctx != nil && ctx.GetInvokingState() >= 0 {\n\t\t// compute what follows who invoked us\n\t\tinvokingState := atn.states[ctx.GetInvokingState()]\n\t\trt := invokingState.GetTransitions()[0]\n\t\tfollow := atn.NextTokens(rt.(*RuleTransition).followState, nil)\n\t\trecoverSet.addSet(follow)\n\t\tctx = ctx.GetParent().(ParserRuleContext)\n\t}\n\trecoverSet.removeOne(TokenEpsilon)\n\treturn recoverSet\n}\n\n// Consume tokens until one Matches the given token set.//\nfunc (d *DefaultErrorStrategy) consumeUntil(recognizer Parser, set *IntervalSet) {\n\tttype := recognizer.GetTokenStream().LA(1)\n\tfor ttype != TokenEOF && !set.contains(ttype) {\n\t\trecognizer.Consume()\n\t\tttype = recognizer.GetTokenStream().LA(1)\n\t}\n}\n\n// The BailErrorStrategy implementation of ANTLRErrorStrategy responds to syntax errors\n// by immediately canceling the parse operation with a\n// [ParseCancellationException]. The implementation ensures that the\n// [ParserRuleContext//exception] field is set for all parse tree nodes\n// that were not completed prior to encountering the error.\n//\n// This error strategy is useful in the following scenarios.\n//\n//   - Two-stage parsing: This error strategy allows the first\n//     stage of two-stage parsing to immediately terminate if an error is\n//     encountered, and immediately fall back to the second stage. In addition to\n//     avoiding wasted work by attempting to recover from errors here, the empty\n//     implementation of [BailErrorStrategy.Sync] improves the performance of\n//     the first stage.\n//\n//   - Silent validation: When syntax errors are not being\n//     Reported or logged, and the parse result is simply ignored if errors occur,\n//     the [BailErrorStrategy] avoids wasting work on recovering from errors\n//     when the result will be ignored either way.\n//\n//     myparser.SetErrorHandler(NewBailErrorStrategy())\n//\n// See also: [Parser.SetErrorHandler(ANTLRErrorStrategy)]\ntype BailErrorStrategy struct {\n\t*DefaultErrorStrategy\n}\n\nvar _ ErrorStrategy = &BailErrorStrategy{}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewBailErrorStrategy() *BailErrorStrategy {\n\n\tb := new(BailErrorStrategy)\n\n\tb.DefaultErrorStrategy = NewDefaultErrorStrategy()\n\n\treturn b\n}\n\n// Recover Instead of recovering from exception e, re-panic it wrapped\n// in a [ParseCancellationException] so it is not caught by the\n// rule func catches. Use Exception.GetCause() to get the\n// original [RecognitionException].\nfunc (b *BailErrorStrategy) Recover(recognizer Parser, e RecognitionException) {\n\tcontext := recognizer.GetParserRuleContext()\n\tfor context != nil {\n\t\tcontext.SetException(e)\n\t\tif parent, ok := context.GetParent().(ParserRuleContext); ok {\n\t\t\tcontext = parent\n\t\t} else {\n\t\t\tcontext = nil\n\t\t}\n\t}\n\trecognizer.SetError(NewParseCancellationException()) // TODO: we don't emit e properly\n}\n\n// RecoverInline makes sure we don't attempt to recover inline if the parser\n// successfully recovers, it won't panic an exception.\nfunc (b *BailErrorStrategy) RecoverInline(recognizer Parser) Token {\n\tb.Recover(recognizer, NewInputMisMatchException(recognizer))\n\n\treturn nil\n}\n\n// Sync makes sure we don't attempt to recover from problems in sub-rules.\nfunc (b *BailErrorStrategy) Sync(_ Parser) {\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/errors.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n//  3 kinds of errors: prediction errors, failed predicate errors, and\n//  mismatched input errors. In each case, the parser knows where it is\n//  in the input, where it is in the ATN, the rule invocation stack,\n//  and what kind of problem occurred.\n\ntype RecognitionException interface {\n\tGetOffendingToken() Token\n\tGetMessage() string\n\tGetInputStream() IntStream\n}\n\ntype BaseRecognitionException struct {\n\tmessage        string\n\trecognizer     Recognizer\n\toffendingToken Token\n\toffendingState int\n\tctx            RuleContext\n\tinput          IntStream\n}\n\nfunc NewBaseRecognitionException(message string, recognizer Recognizer, input IntStream, ctx RuleContext) *BaseRecognitionException {\n\n\t// todo\n\t//\tError.call(this)\n\t//\n\t//\tif (!!Error.captureStackTrace) {\n\t//        Error.captureStackTrace(this, RecognitionException)\n\t//\t} else {\n\t//\t\tstack := NewError().stack\n\t//\t}\n\t// TODO: may be able to use - \"runtime\" func Stack(buf []byte, all bool) int\n\n\tt := new(BaseRecognitionException)\n\n\tt.message = message\n\tt.recognizer = recognizer\n\tt.input = input\n\tt.ctx = ctx\n\n\t// The current Token when an error occurred. Since not all streams\n\t// support accessing symbols by index, we have to track the {@link Token}\n\t// instance itself.\n\t//\n\tt.offendingToken = nil\n\n\t// Get the ATN state number the parser was in at the time the error\n\t// occurred. For NoViableAltException and LexerNoViableAltException exceptions, this is the\n\t// DecisionState number. For others, it is the state whose outgoing edge we couldn't Match.\n\t//\n\tt.offendingState = -1\n\tif t.recognizer != nil {\n\t\tt.offendingState = t.recognizer.GetState()\n\t}\n\n\treturn t\n}\n\nfunc (b *BaseRecognitionException) GetMessage() string {\n\treturn b.message\n}\n\nfunc (b *BaseRecognitionException) GetOffendingToken() Token {\n\treturn b.offendingToken\n}\n\nfunc (b *BaseRecognitionException) GetInputStream() IntStream {\n\treturn b.input\n}\n\n// <p>If the state number is not known, b method returns -1.</p>\n\n// getExpectedTokens gets the set of input symbols which could potentially follow the\n// previously Matched symbol at the time this exception was raised.\n//\n// If the set of expected tokens is not known and could not be computed,\n// this method returns nil.\n//\n// The func returns the set of token types that could potentially follow the current\n// state in the {ATN}, or nil if the information is not available.\n\nfunc (b *BaseRecognitionException) getExpectedTokens() *IntervalSet {\n\tif b.recognizer != nil {\n\t\treturn b.recognizer.GetATN().getExpectedTokens(b.offendingState, b.ctx)\n\t}\n\n\treturn nil\n}\n\nfunc (b *BaseRecognitionException) String() string {\n\treturn b.message\n}\n\ntype LexerNoViableAltException struct {\n\t*BaseRecognitionException\n\n\tstartIndex     int\n\tdeadEndConfigs *ATNConfigSet\n}\n\nfunc NewLexerNoViableAltException(lexer Lexer, input CharStream, startIndex int, deadEndConfigs *ATNConfigSet) *LexerNoViableAltException {\n\n\tl := new(LexerNoViableAltException)\n\n\tl.BaseRecognitionException = NewBaseRecognitionException(\"\", lexer, input, nil)\n\n\tl.startIndex = startIndex\n\tl.deadEndConfigs = deadEndConfigs\n\n\treturn l\n}\n\nfunc (l *LexerNoViableAltException) String() string {\n\tsymbol := \"\"\n\tif l.startIndex >= 0 && l.startIndex < l.input.Size() {\n\t\tsymbol = l.input.(CharStream).GetTextFromInterval(NewInterval(l.startIndex, l.startIndex))\n\t}\n\treturn \"LexerNoViableAltException\" + symbol\n}\n\ntype NoViableAltException struct {\n\t*BaseRecognitionException\n\n\tstartToken     Token\n\toffendingToken Token\n\tctx            ParserRuleContext\n\tdeadEndConfigs *ATNConfigSet\n}\n\n// NewNoViableAltException creates an exception indicating that the parser could not decide which of two or more paths\n// to take based upon the remaining input. It tracks the starting token\n// of the offending input and also knows where the parser was\n// in the various paths when the error.\n//\n// Reported by [ReportNoViableAlternative]\nfunc NewNoViableAltException(recognizer Parser, input TokenStream, startToken Token, offendingToken Token, deadEndConfigs *ATNConfigSet, ctx ParserRuleContext) *NoViableAltException {\n\n\tif ctx == nil {\n\t\tctx = recognizer.GetParserRuleContext()\n\t}\n\n\tif offendingToken == nil {\n\t\toffendingToken = recognizer.GetCurrentToken()\n\t}\n\n\tif startToken == nil {\n\t\tstartToken = recognizer.GetCurrentToken()\n\t}\n\n\tif input == nil {\n\t\tinput = recognizer.GetInputStream().(TokenStream)\n\t}\n\n\tn := new(NoViableAltException)\n\tn.BaseRecognitionException = NewBaseRecognitionException(\"\", recognizer, input, ctx)\n\n\t// Which configurations did we try at input.Index() that couldn't Match\n\t// input.LT(1)\n\tn.deadEndConfigs = deadEndConfigs\n\n\t// The token object at the start index the input stream might\n\t// not be buffering tokens so get a reference to it.\n\t//\n\t// At the time the error occurred, of course the stream needs to keep a\n\t// buffer of all the tokens, but later we might not have access to those.\n\tn.startToken = startToken\n\tn.offendingToken = offendingToken\n\n\treturn n\n}\n\ntype InputMisMatchException struct {\n\t*BaseRecognitionException\n}\n\n// NewInputMisMatchException creates an exception that signifies any kind of mismatched input exceptions such as\n// when the current input does not Match the expected token.\nfunc NewInputMisMatchException(recognizer Parser) *InputMisMatchException {\n\n\ti := new(InputMisMatchException)\n\ti.BaseRecognitionException = NewBaseRecognitionException(\"\", recognizer, recognizer.GetInputStream(), recognizer.GetParserRuleContext())\n\n\ti.offendingToken = recognizer.GetCurrentToken()\n\n\treturn i\n\n}\n\n// FailedPredicateException indicates that a semantic predicate failed during validation. Validation of predicates\n// occurs when normally parsing the alternative just like Matching a token.\n// Disambiguating predicate evaluation occurs when we test a predicate during\n// prediction.\ntype FailedPredicateException struct {\n\t*BaseRecognitionException\n\n\truleIndex      int\n\tpredicateIndex int\n\tpredicate      string\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewFailedPredicateException(recognizer Parser, predicate string, message string) *FailedPredicateException {\n\n\tf := new(FailedPredicateException)\n\n\tf.BaseRecognitionException = NewBaseRecognitionException(f.formatMessage(predicate, message), recognizer, recognizer.GetInputStream(), recognizer.GetParserRuleContext())\n\n\ts := recognizer.GetInterpreter().atn.states[recognizer.GetState()]\n\ttrans := s.GetTransitions()[0]\n\tif trans2, ok := trans.(*PredicateTransition); ok {\n\t\tf.ruleIndex = trans2.ruleIndex\n\t\tf.predicateIndex = trans2.predIndex\n\t} else {\n\t\tf.ruleIndex = 0\n\t\tf.predicateIndex = 0\n\t}\n\tf.predicate = predicate\n\tf.offendingToken = recognizer.GetCurrentToken()\n\n\treturn f\n}\n\nfunc (f *FailedPredicateException) formatMessage(predicate, message string) string {\n\tif message != \"\" {\n\t\treturn message\n\t}\n\n\treturn \"failed predicate: {\" + predicate + \"}?\"\n}\n\ntype ParseCancellationException struct {\n}\n\nfunc (p ParseCancellationException) GetOffendingToken() Token {\n\t//TODO implement me\n\tpanic(\"implement me\")\n}\n\nfunc (p ParseCancellationException) GetMessage() string {\n\t//TODO implement me\n\tpanic(\"implement me\")\n}\n\nfunc (p ParseCancellationException) GetInputStream() IntStream {\n\t//TODO implement me\n\tpanic(\"implement me\")\n}\n\nfunc NewParseCancellationException() *ParseCancellationException {\n\t//\tError.call(this)\n\t//\tError.captureStackTrace(this, ParseCancellationException)\n\treturn new(ParseCancellationException)\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/file_stream.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"bufio\"\n\t\"os\"\n)\n\n//  This is an InputStream that is loaded from a file all at once\n//  when you construct the object.\n\ntype FileStream struct {\n\tInputStream\n\tfilename string\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewFileStream(fileName string) (*FileStream, error) {\n\n\tf, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func(f *os.File) {\n\t\terrF := f.Close()\n\t\tif errF != nil {\n\t\t}\n\t}(f)\n\n\treader := bufio.NewReader(f)\n\tfInfo, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfs := &FileStream{\n\t\tInputStream: InputStream{\n\t\t\tindex: 0,\n\t\t\tname:  fileName,\n\t\t},\n\t\tfilename: fileName,\n\t}\n\n\t// Pre-build the buffer and read runes efficiently\n\t//\n\tfs.data = make([]rune, 0, fInfo.Size())\n\tfor {\n\t\tr, _, err := reader.ReadRune()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tfs.data = append(fs.data, r)\n\t}\n\tfs.size = len(fs.data) // Size in runes\n\n\t// All done.\n\t//\n\treturn fs, nil\n}\n\nfunc (f *FileStream) GetSourceName() string {\n\treturn f.filename\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/go.mod",
    "content": "module github.com/antlr4-go/antlr/v4\n\ngo 1.20\n\nrequire golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc\n"
  },
  {
    "path": "runtime/Go/antlr/v4/go.sum",
    "content": "golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=\ngolang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=\ngolang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc h1:mCRnTeVUjcrhlRmO0VK8a6k6Rrf6TF9htwo2pJVSjIU=\ngolang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=\n"
  },
  {
    "path": "runtime/Go/antlr/v4/input_stream.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"bufio\"\n\t\"io\"\n)\n\ntype InputStream struct {\n\tname  string\n\tindex int\n\tdata  []rune\n\tsize  int\n}\n\n// NewIoStream creates a new input stream from the given io.Reader reader.\n// Note that the reader is read completely into memory and so it must actually\n// have a stopping point - you cannot pass in a reader on an open-ended source such\n// as a socket for instance.\nfunc NewIoStream(reader io.Reader) *InputStream {\n\n\trReader := bufio.NewReader(reader)\n\n\tis := &InputStream{\n\t\tname:  \"<empty>\",\n\t\tindex: 0,\n\t}\n\n\t// Pre-build the buffer and read runes reasonably efficiently given that\n\t// we don't exactly know how big the input is.\n\t//\n\tis.data = make([]rune, 0, 512)\n\tfor {\n\t\tr, _, err := rReader.ReadRune()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tis.data = append(is.data, r)\n\t}\n\tis.size = len(is.data) // number of runes\n\treturn is\n}\n\n// NewInputStream creates a new input stream from the given string\nfunc NewInputStream(data string) *InputStream {\n\n\tis := &InputStream{\n\t\tname:  \"<empty>\",\n\t\tindex: 0,\n\t\tdata:  []rune(data), // This is actually the most efficient way\n\t}\n\tis.size = len(is.data) // number of runes, but we could also use len(data), which is efficient too\n\treturn is\n}\n\nfunc (is *InputStream) reset() {\n\tis.index = 0\n}\n\n// Consume moves the input pointer to the next character in the input stream\nfunc (is *InputStream) Consume() {\n\tif is.index >= is.size {\n\t\t// assert is.LA(1) == TokenEOF\n\t\tpanic(\"cannot consume EOF\")\n\t}\n\tis.index++\n}\n\n// LA returns the character at the given offset from the start of the input stream\nfunc (is *InputStream) LA(offset int) int {\n\n\tif offset == 0 {\n\t\treturn 0 // nil\n\t}\n\tif offset < 0 {\n\t\toffset++ // e.g., translate LA(-1) to use offset=0\n\t}\n\tpos := is.index + offset - 1\n\n\tif pos < 0 || pos >= is.size { // invalid\n\t\treturn TokenEOF\n\t}\n\n\treturn int(is.data[pos])\n}\n\n// LT returns the character at the given offset from the start of the input stream\nfunc (is *InputStream) LT(offset int) int {\n\treturn is.LA(offset)\n}\n\n// Index returns the current offset in to the input stream\nfunc (is *InputStream) Index() int {\n\treturn is.index\n}\n\n// Size returns the total number of characters in the input stream\nfunc (is *InputStream) Size() int {\n\treturn is.size\n}\n\n// Mark does nothing here as we have entire buffer\nfunc (is *InputStream) Mark() int {\n\treturn -1\n}\n\n// Release does nothing here as we have entire buffer\nfunc (is *InputStream) Release(_ int) {\n}\n\n// Seek the input point to the provided index offset\nfunc (is *InputStream) Seek(index int) {\n\tif index <= is.index {\n\t\tis.index = index // just jump don't update stream state (line,...)\n\t\treturn\n\t}\n\t// seek forward\n\tis.index = intMin(index, is.size)\n}\n\n// GetText returns the text from the input stream from the start to the stop index\nfunc (is *InputStream) GetText(start int, stop int) string {\n\tif stop >= is.size {\n\t\tstop = is.size - 1\n\t}\n\tif start >= is.size {\n\t\treturn \"\"\n\t}\n\n\treturn string(is.data[start : stop+1])\n}\n\n// GetTextFromTokens returns the text from the input stream from the first character of the start token to the last\n// character of the stop token\nfunc (is *InputStream) GetTextFromTokens(start, stop Token) string {\n\tif start != nil && stop != nil {\n\t\treturn is.GetTextFromInterval(NewInterval(start.GetTokenIndex(), stop.GetTokenIndex()))\n\t}\n\n\treturn \"\"\n}\n\nfunc (is *InputStream) GetTextFromInterval(i Interval) string {\n\treturn is.GetText(i.Start, i.Stop)\n}\n\nfunc (*InputStream) GetSourceName() string {\n\treturn \"Obtained from string\"\n}\n\n// String returns the entire input stream as a string\nfunc (is *InputStream) String() string {\n\treturn string(is.data)\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/int_stream.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\ntype IntStream interface {\n\tConsume()\n\tLA(int) int\n\tMark() int\n\tRelease(marker int)\n\tIndex() int\n\tSeek(index int)\n\tSize() int\n\tGetSourceName() string\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/interval_set.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype Interval struct {\n\tStart int\n\tStop  int\n}\n\n// NewInterval creates a new interval with the given start and stop values.\nfunc NewInterval(start, stop int) Interval {\n\treturn Interval{\n\t\tStart: start,\n\t\tStop:  stop,\n\t}\n}\n\n// Contains returns true if the given item is contained within the interval.\nfunc (i Interval) Contains(item int) bool {\n\treturn item >= i.Start && item < i.Stop\n}\n\n// String generates a string representation of the interval.\nfunc (i Interval) String() string {\n\tif i.Start == i.Stop-1 {\n\t\treturn strconv.Itoa(i.Start)\n\t}\n\n\treturn strconv.Itoa(i.Start) + \"..\" + strconv.Itoa(i.Stop-1)\n}\n\n// Length returns the length of the interval.\nfunc (i Interval) Length() int {\n\treturn i.Stop - i.Start\n}\n\n// IntervalSet represents a collection of [Intervals], which may be read-only.\ntype IntervalSet struct {\n\tintervals []Interval\n\treadOnly  bool\n}\n\n// NewIntervalSet creates a new empty, writable, interval set.\nfunc NewIntervalSet() *IntervalSet {\n\n\ti := new(IntervalSet)\n\n\ti.intervals = nil\n\ti.readOnly = false\n\n\treturn i\n}\n\nfunc (i *IntervalSet) Equals(other *IntervalSet) bool {\n\tif len(i.intervals) != len(other.intervals) {\n\t\treturn false\n\t}\n\n\tfor k, v := range i.intervals {\n\t\tif v.Start != other.intervals[k].Start || v.Stop != other.intervals[k].Stop {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (i *IntervalSet) first() int {\n\tif len(i.intervals) == 0 {\n\t\treturn TokenInvalidType\n\t}\n\n\treturn i.intervals[0].Start\n}\n\nfunc (i *IntervalSet) addOne(v int) {\n\ti.addInterval(NewInterval(v, v+1))\n}\n\nfunc (i *IntervalSet) addRange(l, h int) {\n\ti.addInterval(NewInterval(l, h+1))\n}\n\nfunc (i *IntervalSet) addInterval(v Interval) {\n\tif i.intervals == nil {\n\t\ti.intervals = make([]Interval, 0)\n\t\ti.intervals = append(i.intervals, v)\n\t} else {\n\t\t// find insert pos\n\t\tfor k, interval := range i.intervals {\n\t\t\t// distinct range -> insert\n\t\t\tif v.Stop < interval.Start {\n\t\t\t\ti.intervals = append(i.intervals[0:k], append([]Interval{v}, i.intervals[k:]...)...)\n\t\t\t\treturn\n\t\t\t} else if v.Stop == interval.Start {\n\t\t\t\ti.intervals[k].Start = v.Start\n\t\t\t\treturn\n\t\t\t} else if v.Start <= interval.Stop {\n\t\t\t\ti.intervals[k] = NewInterval(intMin(interval.Start, v.Start), intMax(interval.Stop, v.Stop))\n\n\t\t\t\t// if not applying to end, merge potential overlaps\n\t\t\t\tif k < len(i.intervals)-1 {\n\t\t\t\t\tl := i.intervals[k]\n\t\t\t\t\tr := i.intervals[k+1]\n\t\t\t\t\t// if r contained in l\n\t\t\t\t\tif l.Stop >= r.Stop {\n\t\t\t\t\t\ti.intervals = append(i.intervals[0:k+1], i.intervals[k+2:]...)\n\t\t\t\t\t} else if l.Stop >= r.Start { // partial overlap\n\t\t\t\t\t\ti.intervals[k] = NewInterval(l.Start, r.Stop)\n\t\t\t\t\t\ti.intervals = append(i.intervals[0:k+1], i.intervals[k+2:]...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// greater than any exiting\n\t\ti.intervals = append(i.intervals, v)\n\t}\n}\n\nfunc (i *IntervalSet) addSet(other *IntervalSet) *IntervalSet {\n\tif other.intervals != nil {\n\t\tfor k := 0; k < len(other.intervals); k++ {\n\t\t\ti2 := other.intervals[k]\n\t\t\ti.addInterval(NewInterval(i2.Start, i2.Stop))\n\t\t}\n\t}\n\treturn i\n}\n\nfunc (i *IntervalSet) complement(start int, stop int) *IntervalSet {\n\tresult := NewIntervalSet()\n\tresult.addInterval(NewInterval(start, stop+1))\n\tfor j := 0; j < len(i.intervals); j++ {\n\t\tresult.removeRange(i.intervals[j])\n\t}\n\treturn result\n}\n\nfunc (i *IntervalSet) contains(item int) bool {\n\tif i.intervals == nil {\n\t\treturn false\n\t}\n\tfor k := 0; k < len(i.intervals); k++ {\n\t\tif i.intervals[k].Contains(item) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (i *IntervalSet) length() int {\n\tiLen := 0\n\n\tfor _, v := range i.intervals {\n\t\tiLen += v.Length()\n\t}\n\n\treturn iLen\n}\n\nfunc (i *IntervalSet) removeRange(v Interval) {\n\tif v.Start == v.Stop-1 {\n\t\ti.removeOne(v.Start)\n\t} else if i.intervals != nil {\n\t\tk := 0\n\t\tfor n := 0; n < len(i.intervals); n++ {\n\t\t\tni := i.intervals[k]\n\t\t\t// intervals are ordered\n\t\t\tif v.Stop <= ni.Start {\n\t\t\t\treturn\n\t\t\t} else if v.Start > ni.Start && v.Stop < ni.Stop {\n\t\t\t\ti.intervals[k] = NewInterval(ni.Start, v.Start)\n\t\t\t\tx := NewInterval(v.Stop, ni.Stop)\n\t\t\t\t// i.intervals.splice(k, 0, x)\n\t\t\t\ti.intervals = append(i.intervals[0:k], append([]Interval{x}, i.intervals[k:]...)...)\n\t\t\t\treturn\n\t\t\t} else if v.Start <= ni.Start && v.Stop >= ni.Stop {\n\t\t\t\t//                i.intervals.splice(k, 1)\n\t\t\t\ti.intervals = append(i.intervals[0:k], i.intervals[k+1:]...)\n\t\t\t\tk = k - 1 // need another pass\n\t\t\t} else if v.Start < ni.Stop {\n\t\t\t\ti.intervals[k] = NewInterval(ni.Start, v.Start)\n\t\t\t} else if v.Stop < ni.Stop {\n\t\t\t\ti.intervals[k] = NewInterval(v.Stop, ni.Stop)\n\t\t\t}\n\t\t\tk++\n\t\t}\n\t}\n}\n\nfunc (i *IntervalSet) removeOne(v int) {\n\tif i.intervals != nil {\n\t\tfor k := 0; k < len(i.intervals); k++ {\n\t\t\tki := i.intervals[k]\n\t\t\t// intervals i ordered\n\t\t\tif v < ki.Start {\n\t\t\t\treturn\n\t\t\t} else if v == ki.Start && v == ki.Stop-1 {\n\t\t\t\t//\t\t\t\ti.intervals.splice(k, 1)\n\t\t\t\ti.intervals = append(i.intervals[0:k], i.intervals[k+1:]...)\n\t\t\t\treturn\n\t\t\t} else if v == ki.Start {\n\t\t\t\ti.intervals[k] = NewInterval(ki.Start+1, ki.Stop)\n\t\t\t\treturn\n\t\t\t} else if v == ki.Stop-1 {\n\t\t\t\ti.intervals[k] = NewInterval(ki.Start, ki.Stop-1)\n\t\t\t\treturn\n\t\t\t} else if v < ki.Stop-1 {\n\t\t\t\tx := NewInterval(ki.Start, v)\n\t\t\t\tki.Start = v + 1\n\t\t\t\t//\t\t\t\ti.intervals.splice(k, 0, x)\n\t\t\t\ti.intervals = append(i.intervals[0:k], append([]Interval{x}, i.intervals[k:]...)...)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (i *IntervalSet) String() string {\n\treturn i.StringVerbose(nil, nil, false)\n}\n\nfunc (i *IntervalSet) StringVerbose(literalNames []string, symbolicNames []string, elemsAreChar bool) string {\n\n\tif i.intervals == nil {\n\t\treturn \"{}\"\n\t} else if literalNames != nil || symbolicNames != nil {\n\t\treturn i.toTokenString(literalNames, symbolicNames)\n\t} else if elemsAreChar {\n\t\treturn i.toCharString()\n\t}\n\n\treturn i.toIndexString()\n}\n\nfunc (i *IntervalSet) GetIntervals() []Interval {\n\treturn i.intervals\n}\n\nfunc (i *IntervalSet) toCharString() string {\n\tnames := make([]string, len(i.intervals))\n\n\tvar sb strings.Builder\n\n\tfor j := 0; j < len(i.intervals); j++ {\n\t\tv := i.intervals[j]\n\t\tif v.Stop == v.Start+1 {\n\t\t\tif v.Start == TokenEOF {\n\t\t\t\tnames = append(names, \"<EOF>\")\n\t\t\t} else {\n\t\t\t\tsb.WriteByte('\\'')\n\t\t\t\tsb.WriteRune(rune(v.Start))\n\t\t\t\tsb.WriteByte('\\'')\n\t\t\t\tnames = append(names, sb.String())\n\t\t\t\tsb.Reset()\n\t\t\t}\n\t\t} else {\n\t\t\tsb.WriteByte('\\'')\n\t\t\tsb.WriteRune(rune(v.Start))\n\t\t\tsb.WriteString(\"'..'\")\n\t\t\tsb.WriteRune(rune(v.Stop - 1))\n\t\t\tsb.WriteByte('\\'')\n\t\t\tnames = append(names, sb.String())\n\t\t\tsb.Reset()\n\t\t}\n\t}\n\tif len(names) > 1 {\n\t\treturn \"{\" + strings.Join(names, \", \") + \"}\"\n\t}\n\n\treturn names[0]\n}\n\nfunc (i *IntervalSet) toIndexString() string {\n\n\tnames := make([]string, 0)\n\tfor j := 0; j < len(i.intervals); j++ {\n\t\tv := i.intervals[j]\n\t\tif v.Stop == v.Start+1 {\n\t\t\tif v.Start == TokenEOF {\n\t\t\t\tnames = append(names, \"<EOF>\")\n\t\t\t} else {\n\t\t\t\tnames = append(names, strconv.Itoa(v.Start))\n\t\t\t}\n\t\t} else {\n\t\t\tnames = append(names, strconv.Itoa(v.Start)+\"..\"+strconv.Itoa(v.Stop-1))\n\t\t}\n\t}\n\tif len(names) > 1 {\n\t\treturn \"{\" + strings.Join(names, \", \") + \"}\"\n\t}\n\n\treturn names[0]\n}\n\nfunc (i *IntervalSet) toTokenString(literalNames []string, symbolicNames []string) string {\n\tnames := make([]string, 0)\n\tfor _, v := range i.intervals {\n\t\tfor j := v.Start; j < v.Stop; j++ {\n\t\t\tnames = append(names, i.elementName(literalNames, symbolicNames, j))\n\t\t}\n\t}\n\tif len(names) > 1 {\n\t\treturn \"{\" + strings.Join(names, \", \") + \"}\"\n\t}\n\n\treturn names[0]\n}\n\nfunc (i *IntervalSet) elementName(literalNames []string, symbolicNames []string, a int) string {\n\tif a == TokenEOF {\n\t\treturn \"<EOF>\"\n\t} else if a == TokenEpsilon {\n\t\treturn \"<EPSILON>\"\n\t} else {\n\t\tif a < len(literalNames) && literalNames[a] != \"\" {\n\t\t\treturn literalNames[a]\n\t\t}\n\n\t\treturn symbolicNames[a]\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/jcollect.go",
    "content": "package antlr\n\n// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\nimport (\n\t\"container/list\"\n\t\"runtime/debug\"\n\t\"sort\"\n)\n\n// Collectable is an interface that a struct should implement if it is to be\n// usable as a key in these collections.\ntype Collectable[T any] interface {\n\tHash() int\n\tEquals(other Collectable[T]) bool\n}\n\ntype Comparator[T any] interface {\n\tHash1(o T) int\n\tEquals2(T, T) bool\n}\n\ntype CollectionSource int\ntype CollectionDescriptor struct {\n\tSybolicName string\n\tDescription string\n}\n\nconst (\n\tUnknownCollection CollectionSource = iota\n\tATNConfigLookupCollection\n\tATNStateCollection\n\tDFAStateCollection\n\tATNConfigCollection\n\tPredictionContextCollection\n\tSemanticContextCollection\n\tClosureBusyCollection\n\tPredictionVisitedCollection\n\tMergeCacheCollection\n\tPredictionContextCacheCollection\n\tAltSetCollection\n\tReachSetCollection\n)\n\nvar CollectionDescriptors = map[CollectionSource]CollectionDescriptor{\n\tUnknownCollection: {\n\t\tSybolicName: \"UnknownCollection\",\n\t\tDescription: \"Unknown collection type. Only used if the target author thought it was an unimportant collection.\",\n\t},\n\tATNConfigCollection: {\n\t\tSybolicName: \"ATNConfigCollection\",\n\t\tDescription: \"ATNConfig collection. Used to store the ATNConfigs for a particular state in the ATN.\" +\n\t\t\t\"For instance, it is used to store the results of the closure() operation in the ATN.\",\n\t},\n\tATNConfigLookupCollection: {\n\t\tSybolicName: \"ATNConfigLookupCollection\",\n\t\tDescription: \"ATNConfigLookup collection. Used to store the ATNConfigs for a particular state in the ATN.\" +\n\t\t\t\"This is used to prevent duplicating equivalent states in an ATNConfigurationSet.\",\n\t},\n\tATNStateCollection: {\n\t\tSybolicName: \"ATNStateCollection\",\n\t\tDescription: \"ATNState collection. This is used to store the states of the ATN.\",\n\t},\n\tDFAStateCollection: {\n\t\tSybolicName: \"DFAStateCollection\",\n\t\tDescription: \"DFAState collection. This is used to store the states of the DFA.\",\n\t},\n\tPredictionContextCollection: {\n\t\tSybolicName: \"PredictionContextCollection\",\n\t\tDescription: \"PredictionContext collection. This is used to store the prediction contexts of the ATN and cache computes.\",\n\t},\n\tSemanticContextCollection: {\n\t\tSybolicName: \"SemanticContextCollection\",\n\t\tDescription: \"SemanticContext collection. This is used to store the semantic contexts of the ATN.\",\n\t},\n\tClosureBusyCollection: {\n\t\tSybolicName: \"ClosureBusyCollection\",\n\t\tDescription: \"ClosureBusy collection. This is used to check and prevent infinite recursion right recursive rules.\" +\n\t\t\t\"It stores ATNConfigs that are currently being processed in the closure() operation.\",\n\t},\n\tPredictionVisitedCollection: {\n\t\tSybolicName: \"PredictionVisitedCollection\",\n\t\tDescription: \"A map that records whether we have visited a particular context when searching through cached entries.\",\n\t},\n\tMergeCacheCollection: {\n\t\tSybolicName: \"MergeCacheCollection\",\n\t\tDescription: \"A map that records whether we have already merged two particular contexts and can save effort by not repeating it.\",\n\t},\n\tPredictionContextCacheCollection: {\n\t\tSybolicName: \"PredictionContextCacheCollection\",\n\t\tDescription: \"A map that records whether we have already created a particular context and can save effort by not computing it again.\",\n\t},\n\tAltSetCollection: {\n\t\tSybolicName: \"AltSetCollection\",\n\t\tDescription: \"Used to eliminate duplicate alternatives in an ATN config set.\",\n\t},\n\tReachSetCollection: {\n\t\tSybolicName: \"ReachSetCollection\",\n\t\tDescription: \"Used as merge cache to prevent us needing to compute the merge of two states if we have already done it.\",\n\t},\n}\n\n// JStore implements a container that allows the use of a struct to calculate the key\n// for a collection of values akin to map. This is not meant to be a full-blown HashMap but just\n// serve the needs of the ANTLR Go runtime.\n//\n// For ease of porting the logic of the runtime from the master target (Java), this collection\n// operates in a similar way to Java, in that it can use any struct that supplies a Hash() and Equals()\n// function as the key. The values are stored in a standard go map which internally is a form of hashmap\n// itself, the key for the go map is the hash supplied by the key object. The collection is able to deal with\n// hash conflicts by using a simple slice of values associated with the hash code indexed bucket. That isn't\n// particularly efficient, but it is simple, and it works. As this is specifically for the ANTLR runtime, and\n// we understand the requirements, then this is fine - this is not a general purpose collection.\ntype JStore[T any, C Comparator[T]] struct {\n\tstore      map[int][]T\n\tlen        int\n\tcomparator Comparator[T]\n\tstats      *JStatRec\n}\n\nfunc NewJStore[T any, C Comparator[T]](comparator Comparator[T], cType CollectionSource, desc string) *JStore[T, C] {\n\n\tif comparator == nil {\n\t\tpanic(\"comparator cannot be nil\")\n\t}\n\n\ts := &JStore[T, C]{\n\t\tstore:      make(map[int][]T, 1),\n\t\tcomparator: comparator,\n\t}\n\tif collectStats {\n\t\ts.stats = &JStatRec{\n\t\t\tSource:      cType,\n\t\t\tDescription: desc,\n\t\t}\n\n\t\t// Track where we created it from  if we are being asked to do so\n\t\tif runtimeConfig.statsTraceStacks {\n\t\t\ts.stats.CreateStack = debug.Stack()\n\t\t}\n\t\tStatistics.AddJStatRec(s.stats)\n\t}\n\treturn s\n}\n\n// Put will store given value in the collection. Note that the key for storage is generated from\n// the value itself - this is specifically because that is what ANTLR needs - this would not be useful\n// as any kind of general collection.\n//\n// If the key has a hash conflict, then the value will be added to the slice of values associated with the\n// hash, unless the value is already in the slice, in which case the existing value is returned. Value equivalence is\n// tested by calling the equals() method on the key.\n//\n// # If the given value is already present in the store, then the existing value is returned as v and exists is set to true\n//\n// If the given value is not present in the store, then the value is added to the store and returned as v and exists is set to false.\nfunc (s *JStore[T, C]) Put(value T) (v T, exists bool) {\n\n\tif collectStats {\n\t\ts.stats.Puts++\n\t}\n\tkh := s.comparator.Hash1(value)\n\n\tvar hClash bool\n\tfor _, v1 := range s.store[kh] {\n\t\thClash = true\n\t\tif s.comparator.Equals2(value, v1) {\n\t\t\tif collectStats {\n\t\t\t\ts.stats.PutHits++\n\t\t\t\ts.stats.PutHashConflicts++\n\t\t\t}\n\t\t\treturn v1, true\n\t\t}\n\t\tif collectStats {\n\t\t\ts.stats.PutMisses++\n\t\t}\n\t}\n\tif collectStats && hClash {\n\t\ts.stats.PutHashConflicts++\n\t}\n\ts.store[kh] = append(s.store[kh], value)\n\n\tif collectStats {\n\t\tif len(s.store[kh]) > s.stats.MaxSlotSize {\n\t\t\ts.stats.MaxSlotSize = len(s.store[kh])\n\t\t}\n\t}\n\ts.len++\n\tif collectStats {\n\t\ts.stats.CurSize = s.len\n\t\tif s.len > s.stats.MaxSize {\n\t\t\ts.stats.MaxSize = s.len\n\t\t}\n\t}\n\treturn value, false\n}\n\n// Get will return the value associated with the key - the type of the key is the same type as the value\n// which would not generally be useful, but this is a specific thing for ANTLR where the key is\n// generated using the object we are going to store.\nfunc (s *JStore[T, C]) Get(key T) (T, bool) {\n\tif collectStats {\n\t\ts.stats.Gets++\n\t}\n\tkh := s.comparator.Hash1(key)\n\tvar hClash bool\n\tfor _, v := range s.store[kh] {\n\t\thClash = true\n\t\tif s.comparator.Equals2(key, v) {\n\t\t\tif collectStats {\n\t\t\t\ts.stats.GetHits++\n\t\t\t\ts.stats.GetHashConflicts++\n\t\t\t}\n\t\t\treturn v, true\n\t\t}\n\t\tif collectStats {\n\t\t\ts.stats.GetMisses++\n\t\t}\n\t}\n\tif collectStats {\n\t\tif hClash {\n\t\t\ts.stats.GetHashConflicts++\n\t\t}\n\t\ts.stats.GetNoEnt++\n\t}\n\treturn key, false\n}\n\n// Contains returns true if the given key is present in the store\nfunc (s *JStore[T, C]) Contains(key T) bool {\n\t_, present := s.Get(key)\n\treturn present\n}\n\nfunc (s *JStore[T, C]) SortedSlice(less func(i, j T) bool) []T {\n\tvs := make([]T, 0, len(s.store))\n\tfor _, v := range s.store {\n\t\tvs = append(vs, v...)\n\t}\n\tsort.Slice(vs, func(i, j int) bool {\n\t\treturn less(vs[i], vs[j])\n\t})\n\n\treturn vs\n}\n\nfunc (s *JStore[T, C]) Each(f func(T) bool) {\n\tfor _, e := range s.store {\n\t\tfor _, v := range e {\n\t\t\tf(v)\n\t\t}\n\t}\n}\n\nfunc (s *JStore[T, C]) Len() int {\n\treturn s.len\n}\n\nfunc (s *JStore[T, C]) Values() []T {\n\tvs := make([]T, 0, len(s.store))\n\tfor _, e := range s.store {\n\t\tvs = append(vs, e...)\n\t}\n\treturn vs\n}\n\ntype entry[K, V any] struct {\n\tkey K\n\tval V\n}\n\ntype JMap[K, V any, C Comparator[K]] struct {\n\tstore      map[int][]*entry[K, V]\n\tlen        int\n\tcomparator Comparator[K]\n\tstats      *JStatRec\n}\n\nfunc NewJMap[K, V any, C Comparator[K]](comparator Comparator[K], cType CollectionSource, desc string) *JMap[K, V, C] {\n\tm := &JMap[K, V, C]{\n\t\tstore:      make(map[int][]*entry[K, V], 1),\n\t\tcomparator: comparator,\n\t}\n\tif collectStats {\n\t\tm.stats = &JStatRec{\n\t\t\tSource:      cType,\n\t\t\tDescription: desc,\n\t\t}\n\t\t// Track where we created it from  if we are being asked to do so\n\t\tif runtimeConfig.statsTraceStacks {\n\t\t\tm.stats.CreateStack = debug.Stack()\n\t\t}\n\t\tStatistics.AddJStatRec(m.stats)\n\t}\n\treturn m\n}\n\nfunc (m *JMap[K, V, C]) Put(key K, val V) (V, bool) {\n\tif collectStats {\n\t\tm.stats.Puts++\n\t}\n\tkh := m.comparator.Hash1(key)\n\n\tvar hClash bool\n\tfor _, e := range m.store[kh] {\n\t\thClash = true\n\t\tif m.comparator.Equals2(e.key, key) {\n\t\t\tif collectStats {\n\t\t\t\tm.stats.PutHits++\n\t\t\t\tm.stats.PutHashConflicts++\n\t\t\t}\n\t\t\treturn e.val, true\n\t\t}\n\t\tif collectStats {\n\t\t\tm.stats.PutMisses++\n\t\t}\n\t}\n\tif collectStats {\n\t\tif hClash {\n\t\t\tm.stats.PutHashConflicts++\n\t\t}\n\t}\n\tm.store[kh] = append(m.store[kh], &entry[K, V]{key, val})\n\tif collectStats {\n\t\tif len(m.store[kh]) > m.stats.MaxSlotSize {\n\t\t\tm.stats.MaxSlotSize = len(m.store[kh])\n\t\t}\n\t}\n\tm.len++\n\tif collectStats {\n\t\tm.stats.CurSize = m.len\n\t\tif m.len > m.stats.MaxSize {\n\t\t\tm.stats.MaxSize = m.len\n\t\t}\n\t}\n\treturn val, false\n}\n\nfunc (m *JMap[K, V, C]) Values() []V {\n\tvs := make([]V, 0, len(m.store))\n\tfor _, e := range m.store {\n\t\tfor _, v := range e {\n\t\t\tvs = append(vs, v.val)\n\t\t}\n\t}\n\treturn vs\n}\n\nfunc (m *JMap[K, V, C]) Get(key K) (V, bool) {\n\tif collectStats {\n\t\tm.stats.Gets++\n\t}\n\tvar none V\n\tkh := m.comparator.Hash1(key)\n\tvar hClash bool\n\tfor _, e := range m.store[kh] {\n\t\thClash = true\n\t\tif m.comparator.Equals2(e.key, key) {\n\t\t\tif collectStats {\n\t\t\t\tm.stats.GetHits++\n\t\t\t\tm.stats.GetHashConflicts++\n\t\t\t}\n\t\t\treturn e.val, true\n\t\t}\n\t\tif collectStats {\n\t\t\tm.stats.GetMisses++\n\t\t}\n\t}\n\tif collectStats {\n\t\tif hClash {\n\t\t\tm.stats.GetHashConflicts++\n\t\t}\n\t\tm.stats.GetNoEnt++\n\t}\n\treturn none, false\n}\n\nfunc (m *JMap[K, V, C]) Len() int {\n\treturn m.len\n}\n\nfunc (m *JMap[K, V, C]) Delete(key K) {\n\tkh := m.comparator.Hash1(key)\n\tfor i, e := range m.store[kh] {\n\t\tif m.comparator.Equals2(e.key, key) {\n\t\t\tm.store[kh] = append(m.store[kh][:i], m.store[kh][i+1:]...)\n\t\t\tm.len--\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (m *JMap[K, V, C]) Clear() {\n\tm.store = make(map[int][]*entry[K, V])\n}\n\ntype JPCMap struct {\n\tstore *JMap[*PredictionContext, *JMap[*PredictionContext, *PredictionContext, *ObjEqComparator[*PredictionContext]], *ObjEqComparator[*PredictionContext]]\n\tsize  int\n\tstats *JStatRec\n}\n\nfunc NewJPCMap(cType CollectionSource, desc string) *JPCMap {\n\tm := &JPCMap{\n\t\tstore: NewJMap[*PredictionContext, *JMap[*PredictionContext, *PredictionContext, *ObjEqComparator[*PredictionContext]], *ObjEqComparator[*PredictionContext]](pContextEqInst, cType, desc),\n\t}\n\tif collectStats {\n\t\tm.stats = &JStatRec{\n\t\t\tSource:      cType,\n\t\t\tDescription: desc,\n\t\t}\n\t\t// Track where we created it from  if we are being asked to do so\n\t\tif runtimeConfig.statsTraceStacks {\n\t\t\tm.stats.CreateStack = debug.Stack()\n\t\t}\n\t\tStatistics.AddJStatRec(m.stats)\n\t}\n\treturn m\n}\n\nfunc (pcm *JPCMap) Get(k1, k2 *PredictionContext) (*PredictionContext, bool) {\n\tif collectStats {\n\t\tpcm.stats.Gets++\n\t}\n\t// Do we have a map stored by k1?\n\t//\n\tm2, present := pcm.store.Get(k1)\n\tif present {\n\t\tif collectStats {\n\t\t\tpcm.stats.GetHits++\n\t\t}\n\t\t// We found a map of values corresponding to k1, so now we need to look up k2 in that map\n\t\t//\n\t\treturn m2.Get(k2)\n\t}\n\tif collectStats {\n\t\tpcm.stats.GetMisses++\n\t}\n\treturn nil, false\n}\n\nfunc (pcm *JPCMap) Put(k1, k2, v *PredictionContext) {\n\n\tif collectStats {\n\t\tpcm.stats.Puts++\n\t}\n\t// First does a map already exist for k1?\n\t//\n\tif m2, present := pcm.store.Get(k1); present {\n\t\tif collectStats {\n\t\t\tpcm.stats.PutHits++\n\t\t}\n\t\t_, present = m2.Put(k2, v)\n\t\tif !present {\n\t\t\tpcm.size++\n\t\t\tif collectStats {\n\t\t\t\tpcm.stats.CurSize = pcm.size\n\t\t\t\tif pcm.size > pcm.stats.MaxSize {\n\t\t\t\t\tpcm.stats.MaxSize = pcm.size\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// No map found for k1, so we create it, add in our value, then store is\n\t\t//\n\t\tif collectStats {\n\t\t\tpcm.stats.PutMisses++\n\t\t\tm2 = NewJMap[*PredictionContext, *PredictionContext, *ObjEqComparator[*PredictionContext]](pContextEqInst, pcm.stats.Source, pcm.stats.Description+\" map entry\")\n\t\t} else {\n\t\t\tm2 = NewJMap[*PredictionContext, *PredictionContext, *ObjEqComparator[*PredictionContext]](pContextEqInst, PredictionContextCacheCollection, \"map entry\")\n\t\t}\n\n\t\tm2.Put(k2, v)\n\t\tpcm.store.Put(k1, m2)\n\t\tpcm.size++\n\t}\n}\n\ntype JPCMap2 struct {\n\tstore map[int][]JPCEntry\n\tsize  int\n\tstats *JStatRec\n}\n\ntype JPCEntry struct {\n\tk1, k2, v *PredictionContext\n}\n\nfunc NewJPCMap2(cType CollectionSource, desc string) *JPCMap2 {\n\tm := &JPCMap2{\n\t\tstore: make(map[int][]JPCEntry, 1000),\n\t}\n\tif collectStats {\n\t\tm.stats = &JStatRec{\n\t\t\tSource:      cType,\n\t\t\tDescription: desc,\n\t\t}\n\t\t// Track where we created it from  if we are being asked to do so\n\t\tif runtimeConfig.statsTraceStacks {\n\t\t\tm.stats.CreateStack = debug.Stack()\n\t\t}\n\t\tStatistics.AddJStatRec(m.stats)\n\t}\n\treturn m\n}\n\nfunc dHash(k1, k2 *PredictionContext) int {\n\treturn k1.cachedHash*31 + k2.cachedHash\n}\n\nfunc (pcm *JPCMap2) Get(k1, k2 *PredictionContext) (*PredictionContext, bool) {\n\tif collectStats {\n\t\tpcm.stats.Gets++\n\t}\n\n\th := dHash(k1, k2)\n\tvar hClash bool\n\tfor _, e := range pcm.store[h] {\n\t\thClash = true\n\t\tif e.k1.Equals(k1) && e.k2.Equals(k2) {\n\t\t\tif collectStats {\n\t\t\t\tpcm.stats.GetHits++\n\t\t\t\tpcm.stats.GetHashConflicts++\n\t\t\t}\n\t\t\treturn e.v, true\n\t\t}\n\t\tif collectStats {\n\t\t\tpcm.stats.GetMisses++\n\t\t}\n\t}\n\tif collectStats {\n\t\tif hClash {\n\t\t\tpcm.stats.GetHashConflicts++\n\t\t}\n\t\tpcm.stats.GetNoEnt++\n\t}\n\treturn nil, false\n}\n\nfunc (pcm *JPCMap2) Put(k1, k2, v *PredictionContext) (*PredictionContext, bool) {\n\tif collectStats {\n\t\tpcm.stats.Puts++\n\t}\n\th := dHash(k1, k2)\n\tvar hClash bool\n\tfor _, e := range pcm.store[h] {\n\t\thClash = true\n\t\tif e.k1.Equals(k1) && e.k2.Equals(k2) {\n\t\t\tif collectStats {\n\t\t\t\tpcm.stats.PutHits++\n\t\t\t\tpcm.stats.PutHashConflicts++\n\t\t\t}\n\t\t\treturn e.v, true\n\t\t}\n\t\tif collectStats {\n\t\t\tpcm.stats.PutMisses++\n\t\t}\n\t}\n\tif collectStats {\n\t\tif hClash {\n\t\t\tpcm.stats.PutHashConflicts++\n\t\t}\n\t}\n\tpcm.store[h] = append(pcm.store[h], JPCEntry{k1, k2, v})\n\tpcm.size++\n\tif collectStats {\n\t\tpcm.stats.CurSize = pcm.size\n\t\tif pcm.size > pcm.stats.MaxSize {\n\t\t\tpcm.stats.MaxSize = pcm.size\n\t\t}\n\t}\n\treturn nil, false\n}\n\ntype VisitEntry struct {\n\tk *PredictionContext\n\tv *PredictionContext\n}\ntype VisitRecord struct {\n\tstore map[*PredictionContext]*PredictionContext\n\tlen   int\n\tstats *JStatRec\n}\n\ntype VisitList struct {\n\tcache *list.List\n\tlock  RWMutex\n}\n\nvar visitListPool = VisitList{\n\tcache: list.New(),\n\tlock:  RWMutex{},\n}\n\n// NewVisitRecord returns a new VisitRecord instance from the pool if available.\n// Note that this \"map\" uses a pointer as a key because we are emulating the behavior of\n// IdentityHashMap in Java, which uses the `==` operator to compare whether the keys are equal,\n// which means is the key the same reference to an object rather than is it .equals() to another\n// object.\nfunc NewVisitRecord() *VisitRecord {\n\tvisitListPool.lock.Lock()\n\tel := visitListPool.cache.Front()\n\tdefer visitListPool.lock.Unlock()\n\tvar vr *VisitRecord\n\tif el == nil {\n\t\tvr = &VisitRecord{\n\t\t\tstore: make(map[*PredictionContext]*PredictionContext),\n\t\t}\n\t\tif collectStats {\n\t\t\tvr.stats = &JStatRec{\n\t\t\t\tSource:      PredictionContextCacheCollection,\n\t\t\t\tDescription: \"VisitRecord\",\n\t\t\t}\n\t\t\t// Track where we created it from  if we are being asked to do so\n\t\t\tif runtimeConfig.statsTraceStacks {\n\t\t\t\tvr.stats.CreateStack = debug.Stack()\n\t\t\t}\n\t\t}\n\t} else {\n\t\tvr = el.Value.(*VisitRecord)\n\t\tvisitListPool.cache.Remove(el)\n\t\tvr.store = make(map[*PredictionContext]*PredictionContext)\n\t}\n\tif collectStats {\n\t\tStatistics.AddJStatRec(vr.stats)\n\t}\n\treturn vr\n}\n\nfunc (vr *VisitRecord) Release() {\n\tvr.len = 0\n\tvr.store = nil\n\tif collectStats {\n\t\tvr.stats.MaxSize = 0\n\t\tvr.stats.CurSize = 0\n\t\tvr.stats.Gets = 0\n\t\tvr.stats.GetHits = 0\n\t\tvr.stats.GetMisses = 0\n\t\tvr.stats.GetHashConflicts = 0\n\t\tvr.stats.GetNoEnt = 0\n\t\tvr.stats.Puts = 0\n\t\tvr.stats.PutHits = 0\n\t\tvr.stats.PutMisses = 0\n\t\tvr.stats.PutHashConflicts = 0\n\t\tvr.stats.MaxSlotSize = 0\n\t}\n\tvisitListPool.lock.Lock()\n\tvisitListPool.cache.PushBack(vr)\n\tvisitListPool.lock.Unlock()\n}\n\nfunc (vr *VisitRecord) Get(k *PredictionContext) (*PredictionContext, bool) {\n\tif collectStats {\n\t\tvr.stats.Gets++\n\t}\n\tv := vr.store[k]\n\tif v != nil {\n\t\tif collectStats {\n\t\t\tvr.stats.GetHits++\n\t\t}\n\t\treturn v, true\n\t}\n\tif collectStats {\n\t\tvr.stats.GetNoEnt++\n\t}\n\treturn nil, false\n}\n\nfunc (vr *VisitRecord) Put(k, v *PredictionContext) (*PredictionContext, bool) {\n\tif collectStats {\n\t\tvr.stats.Puts++\n\t}\n\tvr.store[k] = v\n\tvr.len++\n\tif collectStats {\n\t\tvr.stats.CurSize = vr.len\n\t\tif vr.len > vr.stats.MaxSize {\n\t\t\tvr.stats.MaxSize = vr.len\n\t\t}\n\t}\n\treturn v, false\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/lexer.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n// A lexer is recognizer that draws input symbols from a character stream.\n//  lexer grammars result in a subclass of this object. A Lexer object\n//  uses simplified Match() and error recovery mechanisms in the interest\n//  of speed.\n///\n\ntype Lexer interface {\n\tTokenSource\n\tRecognizer\n\n\tEmit() Token\n\n\tSetChannel(int)\n\tPushMode(int)\n\tPopMode() int\n\tSetType(int)\n\tSetMode(int)\n}\n\ntype BaseLexer struct {\n\t*BaseRecognizer\n\n\tInterpreter         ILexerATNSimulator\n\tTokenStartCharIndex int\n\tTokenStartLine      int\n\tTokenStartColumn    int\n\tActionType          int\n\tVirt                Lexer // The most derived lexer implementation. Allows virtual method calls.\n\n\tinput                  CharStream\n\tfactory                TokenFactory\n\ttokenFactorySourcePair *TokenSourceCharStreamPair\n\ttoken                  Token\n\thitEOF                 bool\n\tchannel                int\n\tthetype                int\n\tmodeStack              IntStack\n\tmode                   int\n\ttext                   string\n}\n\nfunc NewBaseLexer(input CharStream) *BaseLexer {\n\n\tlexer := new(BaseLexer)\n\n\tlexer.BaseRecognizer = NewBaseRecognizer()\n\n\tlexer.input = input\n\tlexer.factory = CommonTokenFactoryDEFAULT\n\tlexer.tokenFactorySourcePair = &TokenSourceCharStreamPair{lexer, input}\n\n\tlexer.Virt = lexer\n\n\tlexer.Interpreter = nil // child classes must populate it\n\n\t// The goal of all lexer rules/methods is to create a token object.\n\t// l is an instance variable as multiple rules may collaborate to\n\t// create a single token. NextToken will return l object after\n\t// Matching lexer rule(s). If you subclass to allow multiple token\n\t// emissions, then set l to the last token to be Matched or\n\t// something non nil so that the auto token emit mechanism will not\n\t// emit another token.\n\tlexer.token = nil\n\n\t// What character index in the stream did the current token start at?\n\t// Needed, for example, to get the text for current token. Set at\n\t// the start of NextToken.\n\tlexer.TokenStartCharIndex = -1\n\n\t// The line on which the first character of the token resides///\n\tlexer.TokenStartLine = -1\n\n\t// The character position of first character within the line///\n\tlexer.TokenStartColumn = -1\n\n\t// Once we see EOF on char stream, next token will be EOF.\n\t// If you have DONE : EOF  then you see DONE EOF.\n\tlexer.hitEOF = false\n\n\t// The channel number for the current token///\n\tlexer.channel = TokenDefaultChannel\n\n\t// The token type for the current token///\n\tlexer.thetype = TokenInvalidType\n\n\tlexer.modeStack = make([]int, 0)\n\tlexer.mode = LexerDefaultMode\n\n\t// You can set the text for the current token to override what is in\n\t// the input char buffer. Use setText() or can set l instance var.\n\t// /\n\tlexer.text = \"\"\n\n\treturn lexer\n}\n\nconst (\n\tLexerDefaultMode = 0\n\tLexerMore        = -2\n\tLexerSkip        = -3\n)\n\n//goland:noinspection GoUnusedConst\nconst (\n\tLexerDefaultTokenChannel = TokenDefaultChannel\n\tLexerHidden              = TokenHiddenChannel\n\tLexerMinCharValue        = 0x0000\n\tLexerMaxCharValue        = 0x10FFFF\n)\n\nfunc (b *BaseLexer) Reset() {\n\t// wack Lexer state variables\n\tif b.input != nil {\n\t\tb.input.Seek(0) // rewind the input\n\t}\n\tb.token = nil\n\tb.thetype = TokenInvalidType\n\tb.channel = TokenDefaultChannel\n\tb.TokenStartCharIndex = -1\n\tb.TokenStartColumn = -1\n\tb.TokenStartLine = -1\n\tb.text = \"\"\n\n\tb.hitEOF = false\n\tb.mode = LexerDefaultMode\n\tb.modeStack = make([]int, 0)\n\n\tb.Interpreter.reset()\n}\n\nfunc (b *BaseLexer) GetInterpreter() ILexerATNSimulator {\n\treturn b.Interpreter\n}\n\nfunc (b *BaseLexer) GetInputStream() CharStream {\n\treturn b.input\n}\n\nfunc (b *BaseLexer) GetSourceName() string {\n\treturn b.GrammarFileName\n}\n\nfunc (b *BaseLexer) SetChannel(v int) {\n\tb.channel = v\n}\n\nfunc (b *BaseLexer) GetTokenFactory() TokenFactory {\n\treturn b.factory\n}\n\nfunc (b *BaseLexer) setTokenFactory(f TokenFactory) {\n\tb.factory = f\n}\n\nfunc (b *BaseLexer) safeMatch() (ret int) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif re, ok := e.(RecognitionException); ok {\n\t\t\t\tb.notifyListeners(re) // Report error\n\t\t\t\tb.Recover(re)\n\t\t\t\tret = LexerSkip // default\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn b.Interpreter.Match(b.input, b.mode)\n}\n\n// NextToken returns a token from the lexer input source i.e., Match a token on the source char stream.\nfunc (b *BaseLexer) NextToken() Token {\n\tif b.input == nil {\n\t\tpanic(\"NextToken requires a non-nil input stream.\")\n\t}\n\n\ttokenStartMarker := b.input.Mark()\n\n\t// previously in finally block\n\tdefer func() {\n\t\t// make sure we release marker after Match or\n\t\t// unbuffered char stream will keep buffering\n\t\tb.input.Release(tokenStartMarker)\n\t}()\n\n\tfor {\n\t\tif b.hitEOF {\n\t\t\tb.EmitEOF()\n\t\t\treturn b.token\n\t\t}\n\t\tb.token = nil\n\t\tb.channel = TokenDefaultChannel\n\t\tb.TokenStartCharIndex = b.input.Index()\n\t\tb.TokenStartColumn = b.Interpreter.GetCharPositionInLine()\n\t\tb.TokenStartLine = b.Interpreter.GetLine()\n\t\tb.text = \"\"\n\t\tcontinueOuter := false\n\t\tfor {\n\t\t\tb.thetype = TokenInvalidType\n\n\t\t\tttype := b.safeMatch() // Defaults to LexerSkip\n\n\t\t\tif b.input.LA(1) == TokenEOF {\n\t\t\t\tb.hitEOF = true\n\t\t\t}\n\t\t\tif b.thetype == TokenInvalidType {\n\t\t\t\tb.thetype = ttype\n\t\t\t}\n\t\t\tif b.thetype == LexerSkip {\n\t\t\t\tcontinueOuter = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif b.thetype != LexerMore {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif continueOuter {\n\t\t\tcontinue\n\t\t}\n\t\tif b.token == nil {\n\t\t\tb.Virt.Emit()\n\t\t}\n\t\treturn b.token\n\t}\n}\n\n// Skip instructs the lexer to Skip creating a token for current lexer rule\n// and look for another token. [NextToken] knows to keep looking when\n// a lexer rule finishes with token set to [SKIPTOKEN]. Recall that\n// if token==nil at end of any token rule, it creates one for you\n// and emits it.\nfunc (b *BaseLexer) Skip() {\n\tb.thetype = LexerSkip\n}\n\nfunc (b *BaseLexer) More() {\n\tb.thetype = LexerMore\n}\n\n// SetMode changes the lexer to a new mode. The lexer will use this mode from hereon in and the rules for that mode\n// will be in force.\nfunc (b *BaseLexer) SetMode(m int) {\n\tb.mode = m\n}\n\n// PushMode saves the current lexer mode so that it can be restored later. See [PopMode], then sets the\n// current lexer mode to the supplied mode m.\nfunc (b *BaseLexer) PushMode(m int) {\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Println(\"pushMode \" + strconv.Itoa(m))\n\t}\n\tb.modeStack.Push(b.mode)\n\tb.mode = m\n}\n\n// PopMode restores the lexer mode saved by a call to [PushMode]. It is a panic error if there is no saved mode to\n// return to.\nfunc (b *BaseLexer) PopMode() int {\n\tif len(b.modeStack) == 0 {\n\t\tpanic(\"Empty Stack\")\n\t}\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Println(\"popMode back to \" + fmt.Sprint(b.modeStack[0:len(b.modeStack)-1]))\n\t}\n\ti, _ := b.modeStack.Pop()\n\tb.mode = i\n\treturn b.mode\n}\n\nfunc (b *BaseLexer) inputStream() CharStream {\n\treturn b.input\n}\n\n// SetInputStream resets the lexer input stream and associated lexer state.\nfunc (b *BaseLexer) SetInputStream(input CharStream) {\n\tb.input = nil\n\tb.tokenFactorySourcePair = &TokenSourceCharStreamPair{b, b.input}\n\tb.Reset()\n\tb.input = input\n\tb.tokenFactorySourcePair = &TokenSourceCharStreamPair{b, b.input}\n}\n\nfunc (b *BaseLexer) GetTokenSourceCharStreamPair() *TokenSourceCharStreamPair {\n\treturn b.tokenFactorySourcePair\n}\n\n// EmitToken by default does not support multiple emits per [NextToken] invocation\n// for efficiency reasons. Subclass and override this func, [NextToken],\n// and [GetToken] (to push tokens into a list and pull from that list\n// rather than a single variable as this implementation does).\nfunc (b *BaseLexer) EmitToken(token Token) {\n\tb.token = token\n}\n\n// Emit is the standard method called to automatically emit a token at the\n// outermost lexical rule. The token object should point into the\n// char buffer start..stop. If there is a text override in 'text',\n// use that to set the token's text. Override this method to emit\n// custom [Token] objects or provide a new factory.\n// /\nfunc (b *BaseLexer) Emit() Token {\n\tt := b.factory.Create(b.tokenFactorySourcePair, b.thetype, b.text, b.channel, b.TokenStartCharIndex, b.GetCharIndex()-1, b.TokenStartLine, b.TokenStartColumn)\n\tb.EmitToken(t)\n\treturn t\n}\n\n// EmitEOF emits an EOF token. By default, this is the last token emitted\nfunc (b *BaseLexer) EmitEOF() Token {\n\tcpos := b.GetCharPositionInLine()\n\tlpos := b.GetLine()\n\teof := b.factory.Create(b.tokenFactorySourcePair, TokenEOF, \"\", TokenDefaultChannel, b.input.Index(), b.input.Index()-1, lpos, cpos)\n\tb.EmitToken(eof)\n\treturn eof\n}\n\n// GetCharPositionInLine returns the current position in the current line as far as the lexer is concerned.\nfunc (b *BaseLexer) GetCharPositionInLine() int {\n\treturn b.Interpreter.GetCharPositionInLine()\n}\n\nfunc (b *BaseLexer) GetLine() int {\n\treturn b.Interpreter.GetLine()\n}\n\nfunc (b *BaseLexer) GetType() int {\n\treturn b.thetype\n}\n\nfunc (b *BaseLexer) SetType(t int) {\n\tb.thetype = t\n}\n\n// GetCharIndex returns the index of the current character of lookahead\nfunc (b *BaseLexer) GetCharIndex() int {\n\treturn b.input.Index()\n}\n\n// GetText returns the text Matched so far for the current token or any text override.\nfunc (b *BaseLexer) GetText() string {\n\tif b.text != \"\" {\n\t\treturn b.text\n\t}\n\n\treturn b.Interpreter.GetText(b.input)\n}\n\n// SetText sets the complete text of this token; it wipes any previous changes to the text.\nfunc (b *BaseLexer) SetText(text string) {\n\tb.text = text\n}\n\n// GetATN returns the ATN used by the lexer.\nfunc (b *BaseLexer) GetATN() *ATN {\n\treturn b.Interpreter.ATN()\n}\n\n// GetAllTokens returns a list of all [Token] objects in input char stream.\n// Forces a load of all tokens that can be made from the input char stream.\n//\n// Does not include EOF token.\nfunc (b *BaseLexer) GetAllTokens() []Token {\n\tvl := b.Virt\n\ttokens := make([]Token, 0)\n\tt := vl.NextToken()\n\tfor t.GetTokenType() != TokenEOF {\n\t\ttokens = append(tokens, t)\n\t\tt = vl.NextToken()\n\t}\n\treturn tokens\n}\n\nfunc (b *BaseLexer) notifyListeners(e RecognitionException) {\n\tstart := b.TokenStartCharIndex\n\tstop := b.input.Index()\n\ttext := b.input.GetTextFromInterval(NewInterval(start, stop))\n\tmsg := \"token recognition error at: '\" + text + \"'\"\n\tlistener := b.GetErrorListenerDispatch()\n\tlistener.SyntaxError(b, nil, b.TokenStartLine, b.TokenStartColumn, msg, e)\n}\n\nfunc (b *BaseLexer) getErrorDisplayForChar(c rune) string {\n\tif c == TokenEOF {\n\t\treturn \"<EOF>\"\n\t} else if c == '\\n' {\n\t\treturn \"\\\\n\"\n\t} else if c == '\\t' {\n\t\treturn \"\\\\t\"\n\t} else if c == '\\r' {\n\t\treturn \"\\\\r\"\n\t} else {\n\t\treturn string(c)\n\t}\n}\n\nfunc (b *BaseLexer) getCharErrorDisplay(c rune) string {\n\treturn \"'\" + b.getErrorDisplayForChar(c) + \"'\"\n}\n\n// Recover can normally Match any char in its vocabulary after Matching\n// a token, so here we do the easy thing and just kill a character and hope\n// it all works out. You can instead use the rule invocation stack\n// to do sophisticated error recovery if you are in a fragment rule.\n//\n// In general, lexers should not need to recover and should have rules that cover any eventuality, such as\n// a character that makes no sense to the recognizer.\nfunc (b *BaseLexer) Recover(re RecognitionException) {\n\tif b.input.LA(1) != TokenEOF {\n\t\tif _, ok := re.(*LexerNoViableAltException); ok {\n\t\t\t// Skip a char and try again\n\t\t\tb.Interpreter.Consume(b.input)\n\t\t} else {\n\t\t\t// TODO: Do we lose character or line position information?\n\t\t\tb.input.Consume()\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/lexer_action.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport \"strconv\"\n\nconst (\n\t// LexerActionTypeChannel represents a [LexerChannelAction] action.\n\tLexerActionTypeChannel = 0\n\n\t// LexerActionTypeCustom represents a [LexerCustomAction] action.\n\tLexerActionTypeCustom = 1\n\n\t// LexerActionTypeMode represents a [LexerModeAction] action.\n\tLexerActionTypeMode = 2\n\n\t// LexerActionTypeMore represents a [LexerMoreAction] action.\n\tLexerActionTypeMore = 3\n\n\t// LexerActionTypePopMode represents a [LexerPopModeAction] action.\n\tLexerActionTypePopMode = 4\n\n\t// LexerActionTypePushMode represents a [LexerPushModeAction] action.\n\tLexerActionTypePushMode = 5\n\n\t// LexerActionTypeSkip represents a [LexerSkipAction] action.\n\tLexerActionTypeSkip = 6\n\n\t// LexerActionTypeType represents a [LexerTypeAction] action.\n\tLexerActionTypeType = 7\n)\n\ntype LexerAction interface {\n\tgetActionType() int\n\tgetIsPositionDependent() bool\n\texecute(lexer Lexer)\n\tHash() int\n\tEquals(other LexerAction) bool\n}\n\ntype BaseLexerAction struct {\n\tactionType          int\n\tisPositionDependent bool\n}\n\nfunc NewBaseLexerAction(action int) *BaseLexerAction {\n\tla := new(BaseLexerAction)\n\n\tla.actionType = action\n\tla.isPositionDependent = false\n\n\treturn la\n}\n\nfunc (b *BaseLexerAction) execute(_ Lexer) {\n\tpanic(\"Not implemented\")\n}\n\nfunc (b *BaseLexerAction) getActionType() int {\n\treturn b.actionType\n}\n\nfunc (b *BaseLexerAction) getIsPositionDependent() bool {\n\treturn b.isPositionDependent\n}\n\nfunc (b *BaseLexerAction) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, b.actionType)\n\treturn murmurFinish(h, 1)\n}\n\nfunc (b *BaseLexerAction) Equals(other LexerAction) bool {\n\treturn b.actionType == other.getActionType()\n}\n\n// LexerSkipAction implements the [BaseLexerAction.Skip] lexer action by calling [Lexer.Skip].\n//\n// The Skip command does not have any parameters, so this action is\n// implemented as a singleton instance exposed by the [LexerSkipActionINSTANCE].\ntype LexerSkipAction struct {\n\t*BaseLexerAction\n}\n\nfunc NewLexerSkipAction() *LexerSkipAction {\n\tla := new(LexerSkipAction)\n\tla.BaseLexerAction = NewBaseLexerAction(LexerActionTypeSkip)\n\treturn la\n}\n\n// LexerSkipActionINSTANCE provides a singleton instance of this parameterless lexer action.\nvar LexerSkipActionINSTANCE = NewLexerSkipAction()\n\nfunc (l *LexerSkipAction) execute(lexer Lexer) {\n\tlexer.Skip()\n}\n\n// String returns a string representation of the current [LexerSkipAction].\nfunc (l *LexerSkipAction) String() string {\n\treturn \"skip\"\n}\n\nfunc (b *LexerSkipAction) Equals(other LexerAction) bool {\n\treturn other.getActionType() == LexerActionTypeSkip\n}\n\n//\tImplements the {@code type} lexer action by calling {@link Lexer//setType}\n//\n// with the assigned type.\ntype LexerTypeAction struct {\n\t*BaseLexerAction\n\n\tthetype int\n}\n\nfunc NewLexerTypeAction(thetype int) *LexerTypeAction {\n\tl := new(LexerTypeAction)\n\tl.BaseLexerAction = NewBaseLexerAction(LexerActionTypeType)\n\tl.thetype = thetype\n\treturn l\n}\n\nfunc (l *LexerTypeAction) execute(lexer Lexer) {\n\tlexer.SetType(l.thetype)\n}\n\nfunc (l *LexerTypeAction) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, l.actionType)\n\th = murmurUpdate(h, l.thetype)\n\treturn murmurFinish(h, 2)\n}\n\nfunc (l *LexerTypeAction) Equals(other LexerAction) bool {\n\tif l == other {\n\t\treturn true\n\t} else if _, ok := other.(*LexerTypeAction); !ok {\n\t\treturn false\n\t} else {\n\t\treturn l.thetype == other.(*LexerTypeAction).thetype\n\t}\n}\n\nfunc (l *LexerTypeAction) String() string {\n\treturn \"actionType(\" + strconv.Itoa(l.thetype) + \")\"\n}\n\n// LexerPushModeAction implements the pushMode lexer action by calling\n// [Lexer.pushMode] with the assigned mode.\ntype LexerPushModeAction struct {\n\t*BaseLexerAction\n\tmode int\n}\n\nfunc NewLexerPushModeAction(mode int) *LexerPushModeAction {\n\n\tl := new(LexerPushModeAction)\n\tl.BaseLexerAction = NewBaseLexerAction(LexerActionTypePushMode)\n\n\tl.mode = mode\n\treturn l\n}\n\n// <p>This action is implemented by calling {@link Lexer//pushMode} with the\n// value provided by {@link //getMode}.</p>\nfunc (l *LexerPushModeAction) execute(lexer Lexer) {\n\tlexer.PushMode(l.mode)\n}\n\nfunc (l *LexerPushModeAction) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, l.actionType)\n\th = murmurUpdate(h, l.mode)\n\treturn murmurFinish(h, 2)\n}\n\nfunc (l *LexerPushModeAction) Equals(other LexerAction) bool {\n\tif l == other {\n\t\treturn true\n\t} else if _, ok := other.(*LexerPushModeAction); !ok {\n\t\treturn false\n\t} else {\n\t\treturn l.mode == other.(*LexerPushModeAction).mode\n\t}\n}\n\nfunc (l *LexerPushModeAction) String() string {\n\treturn \"pushMode(\" + strconv.Itoa(l.mode) + \")\"\n}\n\n// LexerPopModeAction implements the popMode lexer action by calling [Lexer.popMode].\n//\n// The popMode command does not have any parameters, so this action is\n// implemented as a singleton instance exposed by [LexerPopModeActionINSTANCE]\ntype LexerPopModeAction struct {\n\t*BaseLexerAction\n}\n\nfunc NewLexerPopModeAction() *LexerPopModeAction {\n\n\tl := new(LexerPopModeAction)\n\n\tl.BaseLexerAction = NewBaseLexerAction(LexerActionTypePopMode)\n\n\treturn l\n}\n\nvar LexerPopModeActionINSTANCE = NewLexerPopModeAction()\n\n// <p>This action is implemented by calling {@link Lexer//popMode}.</p>\nfunc (l *LexerPopModeAction) execute(lexer Lexer) {\n\tlexer.PopMode()\n}\n\nfunc (l *LexerPopModeAction) String() string {\n\treturn \"popMode\"\n}\n\n// Implements the {@code more} lexer action by calling {@link Lexer//more}.\n//\n// <p>The {@code more} command does not have any parameters, so l action is\n// implemented as a singleton instance exposed by {@link //INSTANCE}.</p>\n\ntype LexerMoreAction struct {\n\t*BaseLexerAction\n}\n\nfunc NewLexerMoreAction() *LexerMoreAction {\n\tl := new(LexerMoreAction)\n\tl.BaseLexerAction = NewBaseLexerAction(LexerActionTypeMore)\n\n\treturn l\n}\n\nvar LexerMoreActionINSTANCE = NewLexerMoreAction()\n\n// <p>This action is implemented by calling {@link Lexer//popMode}.</p>\nfunc (l *LexerMoreAction) execute(lexer Lexer) {\n\tlexer.More()\n}\n\nfunc (l *LexerMoreAction) String() string {\n\treturn \"more\"\n}\n\n// LexerModeAction implements the mode lexer action by calling [Lexer.mode] with\n// the assigned mode.\ntype LexerModeAction struct {\n\t*BaseLexerAction\n\tmode int\n}\n\nfunc NewLexerModeAction(mode int) *LexerModeAction {\n\tl := new(LexerModeAction)\n\tl.BaseLexerAction = NewBaseLexerAction(LexerActionTypeMode)\n\tl.mode = mode\n\treturn l\n}\n\n// <p>This action is implemented by calling {@link Lexer//mode} with the\n// value provided by {@link //getMode}.</p>\nfunc (l *LexerModeAction) execute(lexer Lexer) {\n\tlexer.SetMode(l.mode)\n}\n\nfunc (l *LexerModeAction) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, l.actionType)\n\th = murmurUpdate(h, l.mode)\n\treturn murmurFinish(h, 2)\n}\n\nfunc (l *LexerModeAction) Equals(other LexerAction) bool {\n\tif l == other {\n\t\treturn true\n\t} else if _, ok := other.(*LexerModeAction); !ok {\n\t\treturn false\n\t} else {\n\t\treturn l.mode == other.(*LexerModeAction).mode\n\t}\n}\n\nfunc (l *LexerModeAction) String() string {\n\treturn \"mode(\" + strconv.Itoa(l.mode) + \")\"\n}\n\n// Executes a custom lexer action by calling {@link Recognizer//action} with the\n// rule and action indexes assigned to the custom action. The implementation of\n// a custom action is added to the generated code for the lexer in an override\n// of {@link Recognizer//action} when the grammar is compiled.\n//\n// <p>This class may represent embedded actions created with the <code>{...}</code>\n// syntax in ANTLR 4, as well as actions created for lexer commands where the\n// command argument could not be evaluated when the grammar was compiled.</p>\n\n// Constructs a custom lexer action with the specified rule and action\n// indexes.\n//\n// @param ruleIndex The rule index to use for calls to\n// {@link Recognizer//action}.\n// @param actionIndex The action index to use for calls to\n// {@link Recognizer//action}.\n\ntype LexerCustomAction struct {\n\t*BaseLexerAction\n\truleIndex, actionIndex int\n}\n\nfunc NewLexerCustomAction(ruleIndex, actionIndex int) *LexerCustomAction {\n\tl := new(LexerCustomAction)\n\tl.BaseLexerAction = NewBaseLexerAction(LexerActionTypeCustom)\n\tl.ruleIndex = ruleIndex\n\tl.actionIndex = actionIndex\n\tl.isPositionDependent = true\n\treturn l\n}\n\n// <p>Custom actions are implemented by calling {@link Lexer//action} with the\n// appropriate rule and action indexes.</p>\nfunc (l *LexerCustomAction) execute(lexer Lexer) {\n\tlexer.Action(nil, l.ruleIndex, l.actionIndex)\n}\n\nfunc (l *LexerCustomAction) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, l.actionType)\n\th = murmurUpdate(h, l.ruleIndex)\n\th = murmurUpdate(h, l.actionIndex)\n\treturn murmurFinish(h, 3)\n}\n\nfunc (l *LexerCustomAction) Equals(other LexerAction) bool {\n\tif l == other {\n\t\treturn true\n\t} else if _, ok := other.(*LexerCustomAction); !ok {\n\t\treturn false\n\t} else {\n\t\treturn l.ruleIndex == other.(*LexerCustomAction).ruleIndex &&\n\t\t\tl.actionIndex == other.(*LexerCustomAction).actionIndex\n\t}\n}\n\n// LexerChannelAction implements the channel lexer action by calling\n// [Lexer.setChannel] with the assigned channel.\n//\n// Constructs a new channel action with the specified channel value.\ntype LexerChannelAction struct {\n\t*BaseLexerAction\n\tchannel int\n}\n\n// NewLexerChannelAction creates a channel lexer action by calling\n// [Lexer.setChannel] with the assigned channel.\n//\n// Constructs a new channel action with the specified channel value.\nfunc NewLexerChannelAction(channel int) *LexerChannelAction {\n\tl := new(LexerChannelAction)\n\tl.BaseLexerAction = NewBaseLexerAction(LexerActionTypeChannel)\n\tl.channel = channel\n\treturn l\n}\n\n// <p>This action is implemented by calling {@link Lexer//setChannel} with the\n// value provided by {@link //getChannel}.</p>\nfunc (l *LexerChannelAction) execute(lexer Lexer) {\n\tlexer.SetChannel(l.channel)\n}\n\nfunc (l *LexerChannelAction) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, l.actionType)\n\th = murmurUpdate(h, l.channel)\n\treturn murmurFinish(h, 2)\n}\n\nfunc (l *LexerChannelAction) Equals(other LexerAction) bool {\n\tif l == other {\n\t\treturn true\n\t} else if _, ok := other.(*LexerChannelAction); !ok {\n\t\treturn false\n\t} else {\n\t\treturn l.channel == other.(*LexerChannelAction).channel\n\t}\n}\n\nfunc (l *LexerChannelAction) String() string {\n\treturn \"channel(\" + strconv.Itoa(l.channel) + \")\"\n}\n\n// This implementation of {@link LexerAction} is used for tracking input offsets\n// for position-dependent actions within a {@link LexerActionExecutor}.\n//\n// <p>This action is not serialized as part of the ATN, and is only required for\n// position-dependent lexer actions which appear at a location other than the\n// end of a rule. For more information about DFA optimizations employed for\n// lexer actions, see {@link LexerActionExecutor//append} and\n// {@link LexerActionExecutor//fixOffsetBeforeMatch}.</p>\n\ntype LexerIndexedCustomAction struct {\n\t*BaseLexerAction\n\toffset              int\n\tlexerAction         LexerAction\n\tisPositionDependent bool\n}\n\n// NewLexerIndexedCustomAction constructs a new indexed custom action by associating a character offset\n// with a [LexerAction].\n//\n// Note: This class is only required for lexer actions for which\n// [LexerAction.isPositionDependent] returns true.\n//\n// The offset points into the input [CharStream], relative to\n// the token start index, at which the specified lexerAction should be\n// executed.\nfunc NewLexerIndexedCustomAction(offset int, lexerAction LexerAction) *LexerIndexedCustomAction {\n\n\tl := new(LexerIndexedCustomAction)\n\tl.BaseLexerAction = NewBaseLexerAction(lexerAction.getActionType())\n\n\tl.offset = offset\n\tl.lexerAction = lexerAction\n\tl.isPositionDependent = true\n\n\treturn l\n}\n\n// <p>This method calls {@link //execute} on the result of {@link //getAction}\n// using the provided {@code lexer}.</p>\nfunc (l *LexerIndexedCustomAction) execute(lexer Lexer) {\n\t// assume the input stream position was properly set by the calling code\n\tl.lexerAction.execute(lexer)\n}\n\nfunc (l *LexerIndexedCustomAction) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, l.offset)\n\th = murmurUpdate(h, l.lexerAction.Hash())\n\treturn murmurFinish(h, 2)\n}\n\nfunc (l *LexerIndexedCustomAction) equals(other LexerAction) bool {\n\tif l == other {\n\t\treturn true\n\t} else if _, ok := other.(*LexerIndexedCustomAction); !ok {\n\t\treturn false\n\t} else {\n\t\treturn l.offset == other.(*LexerIndexedCustomAction).offset &&\n\t\t\tl.lexerAction.Equals(other.(*LexerIndexedCustomAction).lexerAction)\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/lexer_action_executor.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport \"golang.org/x/exp/slices\"\n\n// Represents an executor for a sequence of lexer actions which traversed during\n// the Matching operation of a lexer rule (token).\n//\n// <p>The executor tracks position information for position-dependent lexer actions\n// efficiently, ensuring that actions appearing only at the end of the rule do\n// not cause bloating of the {@link DFA} created for the lexer.</p>\n\ntype LexerActionExecutor struct {\n\tlexerActions []LexerAction\n\tcachedHash   int\n}\n\nfunc NewLexerActionExecutor(lexerActions []LexerAction) *LexerActionExecutor {\n\n\tif lexerActions == nil {\n\t\tlexerActions = make([]LexerAction, 0)\n\t}\n\n\tl := new(LexerActionExecutor)\n\n\tl.lexerActions = lexerActions\n\n\t// Caches the result of {@link //hashCode} since the hash code is an element\n\t// of the performance-critical {@link ATNConfig//hashCode} operation.\n\tl.cachedHash = murmurInit(0)\n\tfor _, a := range lexerActions {\n\t\tl.cachedHash = murmurUpdate(l.cachedHash, a.Hash())\n\t}\n\tl.cachedHash = murmurFinish(l.cachedHash, len(lexerActions))\n\n\treturn l\n}\n\n// LexerActionExecutorappend creates a [LexerActionExecutor] which executes the actions for\n// the input [LexerActionExecutor] followed by a specified\n// [LexerAction].\n// TODO: This does not match the Java code\nfunc LexerActionExecutorappend(lexerActionExecutor *LexerActionExecutor, lexerAction LexerAction) *LexerActionExecutor {\n\tif lexerActionExecutor == nil {\n\t\treturn NewLexerActionExecutor([]LexerAction{lexerAction})\n\t}\n\n\treturn NewLexerActionExecutor(append(lexerActionExecutor.lexerActions, lexerAction))\n}\n\n// fixOffsetBeforeMatch creates a [LexerActionExecutor] which encodes the current offset\n// for position-dependent lexer actions.\n//\n// Normally, when the executor encounters lexer actions where\n// [LexerAction.isPositionDependent] returns true, it calls\n// [IntStream.Seek] on the input [CharStream] to set the input\n// position to the end of the current token. This behavior provides\n// for efficient [DFA] representation of lexer actions which appear at the end\n// of a lexer rule, even when the lexer rule Matches a variable number of\n// characters.\n//\n// Prior to traversing a Match transition in the [ATN], the current offset\n// from the token start index is assigned to all position-dependent lexer\n// actions which have not already been assigned a fixed offset. By storing\n// the offsets relative to the token start index, the [DFA] representation of\n// lexer actions which appear in the middle of tokens remains efficient due\n// to sharing among tokens of the same Length, regardless of their absolute\n// position in the input stream.\n//\n// If the current executor already has offsets assigned to all\n// position-dependent lexer actions, the method returns this instance.\n//\n// The offset is assigned to all position-dependent\n// lexer actions which do not already have offsets assigned.\n//\n// The func returns a [LexerActionExecutor] that stores input stream offsets\n// for all position-dependent lexer actions.\nfunc (l *LexerActionExecutor) fixOffsetBeforeMatch(offset int) *LexerActionExecutor {\n\tvar updatedLexerActions []LexerAction\n\tfor i := 0; i < len(l.lexerActions); i++ {\n\t\t_, ok := l.lexerActions[i].(*LexerIndexedCustomAction)\n\t\tif l.lexerActions[i].getIsPositionDependent() && !ok {\n\t\t\tif updatedLexerActions == nil {\n\t\t\t\tupdatedLexerActions = make([]LexerAction, 0, len(l.lexerActions))\n\t\t\t\tupdatedLexerActions = append(updatedLexerActions, l.lexerActions...)\n\t\t\t}\n\t\t\tupdatedLexerActions[i] = NewLexerIndexedCustomAction(offset, l.lexerActions[i])\n\t\t}\n\t}\n\tif updatedLexerActions == nil {\n\t\treturn l\n\t}\n\n\treturn NewLexerActionExecutor(updatedLexerActions)\n}\n\n// Execute the actions encapsulated by l executor within the context of a\n// particular {@link Lexer}.\n//\n// <p>This method calls {@link IntStream//seek} to set the position of the\n// {@code input} {@link CharStream} prior to calling\n// {@link LexerAction//execute} on a position-dependent action. Before the\n// method returns, the input position will be restored to the same position\n// it was in when the method was invoked.</p>\n//\n// @param lexer The lexer instance.\n// @param input The input stream which is the source for the current token.\n// When l method is called, the current {@link IntStream//index} for\n// {@code input} should be the start of the following token, i.e. 1\n// character past the end of the current token.\n// @param startIndex The token start index. This value may be passed to\n// {@link IntStream//seek} to set the {@code input} position to the beginning\n// of the token.\n// /\nfunc (l *LexerActionExecutor) execute(lexer Lexer, input CharStream, startIndex int) {\n\trequiresSeek := false\n\tstopIndex := input.Index()\n\n\tdefer func() {\n\t\tif requiresSeek {\n\t\t\tinput.Seek(stopIndex)\n\t\t}\n\t}()\n\n\tfor i := 0; i < len(l.lexerActions); i++ {\n\t\tlexerAction := l.lexerActions[i]\n\t\tif la, ok := lexerAction.(*LexerIndexedCustomAction); ok {\n\t\t\toffset := la.offset\n\t\t\tinput.Seek(startIndex + offset)\n\t\t\tlexerAction = la.lexerAction\n\t\t\trequiresSeek = (startIndex + offset) != stopIndex\n\t\t} else if lexerAction.getIsPositionDependent() {\n\t\t\tinput.Seek(stopIndex)\n\t\t\trequiresSeek = false\n\t\t}\n\t\tlexerAction.execute(lexer)\n\t}\n}\n\nfunc (l *LexerActionExecutor) Hash() int {\n\tif l == nil {\n\t\t// TODO: Why is this here? l should not be nil\n\t\treturn 61\n\t}\n\n\t// TODO: This is created from the action itself when the struct is created - will this be an issue at some point? Java uses the runtime assign hashcode\n\treturn l.cachedHash\n}\n\nfunc (l *LexerActionExecutor) Equals(other interface{}) bool {\n\tif l == other {\n\t\treturn true\n\t}\n\tothert, ok := other.(*LexerActionExecutor)\n\tif !ok {\n\t\treturn false\n\t}\n\tif othert == nil {\n\t\treturn false\n\t}\n\tif l.cachedHash != othert.cachedHash {\n\t\treturn false\n\t}\n\tif len(l.lexerActions) != len(othert.lexerActions) {\n\t\treturn false\n\t}\n\treturn slices.EqualFunc(l.lexerActions, othert.lexerActions, func(i, j LexerAction) bool {\n\t\treturn i.Equals(j)\n\t})\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/lexer_atn_simulator.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n//goland:noinspection GoUnusedGlobalVariable\nvar (\n\tLexerATNSimulatorMinDFAEdge = 0\n\tLexerATNSimulatorMaxDFAEdge = 127 // forces unicode to stay in ATN\n\n\tLexerATNSimulatorMatchCalls = 0\n)\n\ntype ILexerATNSimulator interface {\n\tIATNSimulator\n\n\treset()\n\tMatch(input CharStream, mode int) int\n\tGetCharPositionInLine() int\n\tGetLine() int\n\tGetText(input CharStream) string\n\tConsume(input CharStream)\n}\n\ntype LexerATNSimulator struct {\n\tBaseATNSimulator\n\n\trecog              Lexer\n\tpredictionMode     int\n\tmergeCache         *JPCMap2\n\tstartIndex         int\n\tLine               int\n\tCharPositionInLine int\n\tmode               int\n\tprevAccept         *SimState\n\tMatchCalls         int\n}\n\nfunc NewLexerATNSimulator(recog Lexer, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) *LexerATNSimulator {\n\tl := &LexerATNSimulator{\n\t\tBaseATNSimulator: BaseATNSimulator{\n\t\t\tatn:                atn,\n\t\t\tsharedContextCache: sharedContextCache,\n\t\t},\n\t}\n\n\tl.decisionToDFA = decisionToDFA\n\tl.recog = recog\n\n\t// The current token's starting index into the character stream.\n\t// Shared across DFA to ATN simulation in case the ATN fails and the\n\t// DFA did not have a previous accept state. In l case, we use the\n\t// ATN-generated exception object.\n\tl.startIndex = -1\n\n\t// line number 1..n within the input\n\tl.Line = 1\n\n\t// The index of the character relative to the beginning of the line\n\t// 0..n-1\n\tl.CharPositionInLine = 0\n\n\tl.mode = LexerDefaultMode\n\n\t// Used during DFA/ATN exec to record the most recent accept configuration\n\t// info\n\tl.prevAccept = NewSimState()\n\n\treturn l\n}\n\nfunc (l *LexerATNSimulator) copyState(simulator *LexerATNSimulator) {\n\tl.CharPositionInLine = simulator.CharPositionInLine\n\tl.Line = simulator.Line\n\tl.mode = simulator.mode\n\tl.startIndex = simulator.startIndex\n}\n\nfunc (l *LexerATNSimulator) Match(input CharStream, mode int) int {\n\tl.MatchCalls++\n\tl.mode = mode\n\tmark := input.Mark()\n\n\tdefer func() {\n\t\tinput.Release(mark)\n\t}()\n\n\tl.startIndex = input.Index()\n\tl.prevAccept.reset()\n\n\tdfa := l.decisionToDFA[mode]\n\n\tvar s0 *DFAState\n\tl.atn.stateMu.RLock()\n\ts0 = dfa.getS0()\n\tl.atn.stateMu.RUnlock()\n\n\tif s0 == nil {\n\t\treturn l.MatchATN(input)\n\t}\n\n\treturn l.execATN(input, s0)\n}\n\nfunc (l *LexerATNSimulator) reset() {\n\tl.prevAccept.reset()\n\tl.startIndex = -1\n\tl.Line = 1\n\tl.CharPositionInLine = 0\n\tl.mode = LexerDefaultMode\n}\n\nfunc (l *LexerATNSimulator) MatchATN(input CharStream) int {\n\tstartState := l.atn.modeToStartState[l.mode]\n\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Println(\"MatchATN mode \" + strconv.Itoa(l.mode) + \" start: \" + startState.String())\n\t}\n\toldMode := l.mode\n\ts0Closure := l.computeStartState(input, startState)\n\tsuppressEdge := s0Closure.hasSemanticContext\n\ts0Closure.hasSemanticContext = false\n\n\tnext := l.addDFAState(s0Closure, suppressEdge)\n\n\tpredict := l.execATN(input, next)\n\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Println(\"DFA after MatchATN: \" + l.decisionToDFA[oldMode].ToLexerString())\n\t}\n\treturn predict\n}\n\nfunc (l *LexerATNSimulator) execATN(input CharStream, ds0 *DFAState) int {\n\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Println(\"start state closure=\" + ds0.configs.String())\n\t}\n\tif ds0.isAcceptState {\n\t\t// allow zero-Length tokens\n\t\tl.captureSimState(l.prevAccept, input, ds0)\n\t}\n\tt := input.LA(1)\n\ts := ds0 // s is current/from DFA state\n\n\tfor { // while more work\n\t\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\t\tfmt.Println(\"execATN loop starting closure: \" + s.configs.String())\n\t\t}\n\n\t\t// As we move src->trg, src->trg, we keep track of the previous trg to\n\t\t// avoid looking up the DFA state again, which is expensive.\n\t\t// If the previous target was already part of the DFA, we might\n\t\t// be able to avoid doing a reach operation upon t. If s!=nil,\n\t\t// it means that semantic predicates didn't prevent us from\n\t\t// creating a DFA state. Once we know s!=nil, we check to see if\n\t\t// the DFA state has an edge already for t. If so, we can just reuse\n\t\t// it's configuration set there's no point in re-computing it.\n\t\t// This is kind of like doing DFA simulation within the ATN\n\t\t// simulation because DFA simulation is really just a way to avoid\n\t\t// computing reach/closure sets. Technically, once we know that\n\t\t// we have a previously added DFA state, we could jump over to\n\t\t// the DFA simulator. But, that would mean popping back and forth\n\t\t// a lot and making things more complicated algorithmically.\n\t\t// This optimization makes a lot of sense for loops within DFA.\n\t\t// A character will take us back to an existing DFA state\n\t\t// that already has lots of edges out of it. e.g., .* in comments.\n\t\ttarget := l.getExistingTargetState(s, t)\n\t\tif target == nil {\n\t\t\ttarget = l.computeTargetState(input, s, t)\n\t\t\t// print(\"Computed:\" + str(target))\n\t\t}\n\t\tif target == ATNSimulatorError {\n\t\t\tbreak\n\t\t}\n\t\t// If l is a consumable input element, make sure to consume before\n\t\t// capturing the accept state so the input index, line, and char\n\t\t// position accurately reflect the state of the interpreter at the\n\t\t// end of the token.\n\t\tif t != TokenEOF {\n\t\t\tl.Consume(input)\n\t\t}\n\t\tif target.isAcceptState {\n\t\t\tl.captureSimState(l.prevAccept, input, target)\n\t\t\tif t == TokenEOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tt = input.LA(1)\n\t\ts = target // flip current DFA target becomes new src/from state\n\t}\n\n\treturn l.failOrAccept(l.prevAccept, input, s.configs, t)\n}\n\n// Get an existing target state for an edge in the DFA. If the target state\n// for the edge has not yet been computed or is otherwise not available,\n// l method returns {@code nil}.\n//\n// @param s The current DFA state\n// @param t The next input symbol\n// @return The existing target DFA state for the given input symbol\n// {@code t}, or {@code nil} if the target state for l edge is not\n// already cached\nfunc (l *LexerATNSimulator) getExistingTargetState(s *DFAState, t int) *DFAState {\n\tif t < LexerATNSimulatorMinDFAEdge || t > LexerATNSimulatorMaxDFAEdge {\n\t\treturn nil\n\t}\n\n\tl.atn.edgeMu.RLock()\n\tdefer l.atn.edgeMu.RUnlock()\n\tif s.getEdges() == nil {\n\t\treturn nil\n\t}\n\ttarget := s.getIthEdge(t - LexerATNSimulatorMinDFAEdge)\n\tif runtimeConfig.lexerATNSimulatorDebug && target != nil {\n\t\tfmt.Println(\"reuse state \" + strconv.Itoa(s.stateNumber) + \" edge to \" + strconv.Itoa(target.stateNumber))\n\t}\n\treturn target\n}\n\n// computeTargetState computes a target state for an edge in the [DFA], and attempt to add the\n// computed state and corresponding edge to the [DFA].\n//\n// The func returns the computed target [DFA] state for the given input symbol t.\n// If this does not lead to a valid [DFA] state, this method\n// returns ATNSimulatorError.\nfunc (l *LexerATNSimulator) computeTargetState(input CharStream, s *DFAState, t int) *DFAState {\n\treach := NewOrderedATNConfigSet()\n\n\t// if we don't find an existing DFA state\n\t// Fill reach starting from closure, following t transitions\n\tl.getReachableConfigSet(input, s.configs, reach, t)\n\n\tif len(reach.configs) == 0 { // we got nowhere on t from s\n\t\tif !reach.hasSemanticContext {\n\t\t\t// we got nowhere on t, don't panic out l knowledge it'd\n\t\t\t// cause a fail-over from DFA later.\n\t\t\tl.addDFAEdge(s, t, ATNSimulatorError, nil)\n\t\t}\n\t\t// stop when we can't Match any more char\n\t\treturn ATNSimulatorError\n\t}\n\t// Add an edge from s to target DFA found/created for reach\n\treturn l.addDFAEdge(s, t, nil, reach)\n}\n\nfunc (l *LexerATNSimulator) failOrAccept(prevAccept *SimState, input CharStream, reach *ATNConfigSet, t int) int {\n\tif l.prevAccept.dfaState != nil {\n\t\tlexerActionExecutor := prevAccept.dfaState.lexerActionExecutor\n\t\tl.accept(input, lexerActionExecutor, l.startIndex, prevAccept.index, prevAccept.line, prevAccept.column)\n\t\treturn prevAccept.dfaState.prediction\n\t}\n\n\t// if no accept and EOF is first char, return EOF\n\tif t == TokenEOF && input.Index() == l.startIndex {\n\t\treturn TokenEOF\n\t}\n\n\tpanic(NewLexerNoViableAltException(l.recog, input, l.startIndex, reach))\n}\n\n// getReachableConfigSet when given a starting configuration set, figures out all [ATN] configurations\n// we can reach upon input t.\n//\n// Parameter reach is a return parameter.\nfunc (l *LexerATNSimulator) getReachableConfigSet(input CharStream, closure *ATNConfigSet, reach *ATNConfigSet, t int) {\n\t// l is used to Skip processing for configs which have a lower priority\n\t// than a runtimeConfig that already reached an accept state for the same rule\n\tSkipAlt := ATNInvalidAltNumber\n\n\tfor _, cfg := range closure.configs {\n\t\tcurrentAltReachedAcceptState := cfg.GetAlt() == SkipAlt\n\t\tif currentAltReachedAcceptState && cfg.passedThroughNonGreedyDecision {\n\t\t\tcontinue\n\t\t}\n\n\t\tif runtimeConfig.lexerATNSimulatorDebug {\n\n\t\t\tfmt.Printf(\"testing %s at %s\\n\", l.GetTokenName(t), cfg.String())\n\t\t}\n\n\t\tfor _, trans := range cfg.GetState().GetTransitions() {\n\t\t\ttarget := l.getReachableTarget(trans, t)\n\t\t\tif target != nil {\n\t\t\t\tlexerActionExecutor := cfg.lexerActionExecutor\n\t\t\t\tif lexerActionExecutor != nil {\n\t\t\t\t\tlexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.Index() - l.startIndex)\n\t\t\t\t}\n\t\t\t\ttreatEOFAsEpsilon := t == TokenEOF\n\t\t\t\tconfig := NewLexerATNConfig3(cfg, target, lexerActionExecutor)\n\t\t\t\tif l.closure(input, config, reach,\n\t\t\t\t\tcurrentAltReachedAcceptState, true, treatEOFAsEpsilon) {\n\t\t\t\t\t// any remaining configs for l alt have a lower priority\n\t\t\t\t\t// than the one that just reached an accept state.\n\t\t\t\t\tSkipAlt = cfg.GetAlt()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *LexerATNSimulator) accept(input CharStream, lexerActionExecutor *LexerActionExecutor, startIndex, index, line, charPos int) {\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Printf(\"ACTION %v\\n\", lexerActionExecutor)\n\t}\n\t// seek to after last char in token\n\tinput.Seek(index)\n\tl.Line = line\n\tl.CharPositionInLine = charPos\n\tif lexerActionExecutor != nil && l.recog != nil {\n\t\tlexerActionExecutor.execute(l.recog, input, startIndex)\n\t}\n}\n\nfunc (l *LexerATNSimulator) getReachableTarget(trans Transition, t int) ATNState {\n\tif trans.Matches(t, 0, LexerMaxCharValue) {\n\t\treturn trans.getTarget()\n\t}\n\n\treturn nil\n}\n\nfunc (l *LexerATNSimulator) computeStartState(input CharStream, p ATNState) *ATNConfigSet {\n\tconfigs := NewOrderedATNConfigSet()\n\tfor i := 0; i < len(p.GetTransitions()); i++ {\n\t\ttarget := p.GetTransitions()[i].getTarget()\n\t\tcfg := NewLexerATNConfig6(target, i+1, BasePredictionContextEMPTY)\n\t\tl.closure(input, cfg, configs, false, false, false)\n\t}\n\n\treturn configs\n}\n\n// closure since the alternatives within any lexer decision are ordered by\n// preference, this method stops pursuing the closure as soon as an accept\n// state is reached. After the first accept state is reached by depth-first\n// search from runtimeConfig, all other (potentially reachable) states for\n// this rule would have a lower priority.\n//\n// The func returns true if an accept state is reached.\nfunc (l *LexerATNSimulator) closure(input CharStream, config *ATNConfig, configs *ATNConfigSet,\n\tcurrentAltReachedAcceptState, speculative, treatEOFAsEpsilon bool) bool {\n\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Println(\"closure(\" + config.String() + \")\")\n\t}\n\n\t_, ok := config.state.(*RuleStopState)\n\tif ok {\n\n\t\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\t\tif l.recog != nil {\n\t\t\t\tfmt.Printf(\"closure at %s rule stop %s\\n\", l.recog.GetRuleNames()[config.state.GetRuleIndex()], config)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"closure at rule stop %s\\n\", config)\n\t\t\t}\n\t\t}\n\n\t\tif config.context == nil || config.context.hasEmptyPath() {\n\t\t\tif config.context == nil || config.context.isEmpty() {\n\t\t\t\tconfigs.Add(config, nil)\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tconfigs.Add(NewLexerATNConfig2(config, config.state, BasePredictionContextEMPTY), nil)\n\t\t\tcurrentAltReachedAcceptState = true\n\t\t}\n\t\tif config.context != nil && !config.context.isEmpty() {\n\t\t\tfor i := 0; i < config.context.length(); i++ {\n\t\t\t\tif config.context.getReturnState(i) != BasePredictionContextEmptyReturnState {\n\t\t\t\t\tnewContext := config.context.GetParent(i) // \"pop\" return state\n\t\t\t\t\treturnState := l.atn.states[config.context.getReturnState(i)]\n\t\t\t\t\tcfg := NewLexerATNConfig2(config, returnState, newContext)\n\t\t\t\t\tcurrentAltReachedAcceptState = l.closure(input, cfg, configs, currentAltReachedAcceptState, speculative, treatEOFAsEpsilon)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentAltReachedAcceptState\n\t}\n\t// optimization\n\tif !config.state.GetEpsilonOnlyTransitions() {\n\t\tif !currentAltReachedAcceptState || !config.passedThroughNonGreedyDecision {\n\t\t\tconfigs.Add(config, nil)\n\t\t}\n\t}\n\tfor j := 0; j < len(config.state.GetTransitions()); j++ {\n\t\ttrans := config.state.GetTransitions()[j]\n\t\tcfg := l.getEpsilonTarget(input, config, trans, configs, speculative, treatEOFAsEpsilon)\n\t\tif cfg != nil {\n\t\t\tcurrentAltReachedAcceptState = l.closure(input, cfg, configs,\n\t\t\t\tcurrentAltReachedAcceptState, speculative, treatEOFAsEpsilon)\n\t\t}\n\t}\n\treturn currentAltReachedAcceptState\n}\n\n// side-effect: can alter configs.hasSemanticContext\nfunc (l *LexerATNSimulator) getEpsilonTarget(input CharStream, config *ATNConfig, trans Transition,\n\tconfigs *ATNConfigSet, speculative, treatEOFAsEpsilon bool) *ATNConfig {\n\n\tvar cfg *ATNConfig\n\n\tif trans.getSerializationType() == TransitionRULE {\n\n\t\trt := trans.(*RuleTransition)\n\t\tnewContext := SingletonBasePredictionContextCreate(config.context, rt.followState.GetStateNumber())\n\t\tcfg = NewLexerATNConfig2(config, trans.getTarget(), newContext)\n\n\t} else if trans.getSerializationType() == TransitionPRECEDENCE {\n\t\tpanic(\"Precedence predicates are not supported in lexers.\")\n\t} else if trans.getSerializationType() == TransitionPREDICATE {\n\t\t// Track traversing semantic predicates. If we traverse,\n\t\t// we cannot add a DFA state for l \"reach\" computation\n\t\t// because the DFA would not test the predicate again in the\n\t\t// future. Rather than creating collections of semantic predicates\n\t\t// like v3 and testing them on prediction, v4 will test them on the\n\t\t// fly all the time using the ATN not the DFA. This is slower but\n\t\t// semantically it's not used that often. One of the key elements to\n\t\t// l predicate mechanism is not adding DFA states that see\n\t\t// predicates immediately afterwards in the ATN. For example,\n\n\t\t// a : ID {p1}? | ID {p2}?\n\n\t\t// should create the start state for rule 'a' (to save start state\n\t\t// competition), but should not create target of ID state. The\n\t\t// collection of ATN states the following ID references includes\n\t\t// states reached by traversing predicates. Since l is when we\n\t\t// test them, we cannot cash the DFA state target of ID.\n\n\t\tpt := trans.(*PredicateTransition)\n\n\t\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\t\tfmt.Println(\"EVAL rule \" + strconv.Itoa(trans.(*PredicateTransition).ruleIndex) + \":\" + strconv.Itoa(pt.predIndex))\n\t\t}\n\t\tconfigs.hasSemanticContext = true\n\t\tif l.evaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative) {\n\t\t\tcfg = NewLexerATNConfig4(config, trans.getTarget())\n\t\t}\n\t} else if trans.getSerializationType() == TransitionACTION {\n\t\tif config.context == nil || config.context.hasEmptyPath() {\n\t\t\t// execute actions anywhere in the start rule for a token.\n\t\t\t//\n\t\t\t// TODO: if the entry rule is invoked recursively, some\n\t\t\t// actions may be executed during the recursive call. The\n\t\t\t// problem can appear when hasEmptyPath() is true but\n\t\t\t// isEmpty() is false. In this case, the config needs to be\n\t\t\t// split into two contexts - one with just the empty path\n\t\t\t// and another with everything but the empty path.\n\t\t\t// Unfortunately, the current algorithm does not allow\n\t\t\t// getEpsilonTarget to return two configurations, so\n\t\t\t// additional modifications are needed before we can support\n\t\t\t// the split operation.\n\t\t\tlexerActionExecutor := LexerActionExecutorappend(config.lexerActionExecutor, l.atn.lexerActions[trans.(*ActionTransition).actionIndex])\n\t\t\tcfg = NewLexerATNConfig3(config, trans.getTarget(), lexerActionExecutor)\n\t\t} else {\n\t\t\t// ignore actions in referenced rules\n\t\t\tcfg = NewLexerATNConfig4(config, trans.getTarget())\n\t\t}\n\t} else if trans.getSerializationType() == TransitionEPSILON {\n\t\tcfg = NewLexerATNConfig4(config, trans.getTarget())\n\t} else if trans.getSerializationType() == TransitionATOM ||\n\t\ttrans.getSerializationType() == TransitionRANGE ||\n\t\ttrans.getSerializationType() == TransitionSET {\n\t\tif treatEOFAsEpsilon {\n\t\t\tif trans.Matches(TokenEOF, 0, LexerMaxCharValue) {\n\t\t\t\tcfg = NewLexerATNConfig4(config, trans.getTarget())\n\t\t\t}\n\t\t}\n\t}\n\treturn cfg\n}\n\n// evaluatePredicate eEvaluates a predicate specified in the lexer.\n//\n// If speculative is true, this method was called before\n// [consume] for the Matched character. This method should call\n// [consume] before evaluating the predicate to ensure position\n// sensitive values, including [GetText], [GetLine],\n// and [GetColumn], properly reflect the current\n// lexer state. This method should restore input and the simulator\n// to the original state before returning, i.e. undo the actions made by the\n// call to [Consume].\n//\n// The func returns true if the specified predicate evaluates to true.\nfunc (l *LexerATNSimulator) evaluatePredicate(input CharStream, ruleIndex, predIndex int, speculative bool) bool {\n\t// assume true if no recognizer was provided\n\tif l.recog == nil {\n\t\treturn true\n\t}\n\tif !speculative {\n\t\treturn l.recog.Sempred(nil, ruleIndex, predIndex)\n\t}\n\tsavedcolumn := l.CharPositionInLine\n\tsavedLine := l.Line\n\tindex := input.Index()\n\tmarker := input.Mark()\n\n\tdefer func() {\n\t\tl.CharPositionInLine = savedcolumn\n\t\tl.Line = savedLine\n\t\tinput.Seek(index)\n\t\tinput.Release(marker)\n\t}()\n\n\tl.Consume(input)\n\treturn l.recog.Sempred(nil, ruleIndex, predIndex)\n}\n\nfunc (l *LexerATNSimulator) captureSimState(settings *SimState, input CharStream, dfaState *DFAState) {\n\tsettings.index = input.Index()\n\tsettings.line = l.Line\n\tsettings.column = l.CharPositionInLine\n\tsettings.dfaState = dfaState\n}\n\nfunc (l *LexerATNSimulator) addDFAEdge(from *DFAState, tk int, to *DFAState, cfgs *ATNConfigSet) *DFAState {\n\tif to == nil && cfgs != nil {\n\t\t// leading to l call, ATNConfigSet.hasSemanticContext is used as a\n\t\t// marker indicating dynamic predicate evaluation makes l edge\n\t\t// dependent on the specific input sequence, so the static edge in the\n\t\t// DFA should be omitted. The target DFAState is still created since\n\t\t// execATN has the ability to reSynchronize with the DFA state cache\n\t\t// following the predicate evaluation step.\n\t\t//\n\t\t// TJP notes: next time through the DFA, we see a pred again and eval.\n\t\t// If that gets us to a previously created (but dangling) DFA\n\t\t// state, we can continue in pure DFA mode from there.\n\t\t//\n\t\tsuppressEdge := cfgs.hasSemanticContext\n\t\tcfgs.hasSemanticContext = false\n\t\tto = l.addDFAState(cfgs, true)\n\n\t\tif suppressEdge {\n\t\t\treturn to\n\t\t}\n\t}\n\t// add the edge\n\tif tk < LexerATNSimulatorMinDFAEdge || tk > LexerATNSimulatorMaxDFAEdge {\n\t\t// Only track edges within the DFA bounds\n\t\treturn to\n\t}\n\tif runtimeConfig.lexerATNSimulatorDebug {\n\t\tfmt.Println(\"EDGE \" + from.String() + \" -> \" + to.String() + \" upon \" + strconv.Itoa(tk))\n\t}\n\tl.atn.edgeMu.Lock()\n\tdefer l.atn.edgeMu.Unlock()\n\tif from.getEdges() == nil {\n\t\t// make room for tokens 1..n and -1 masquerading as index 0\n\t\tfrom.setEdges(make([]*DFAState, LexerATNSimulatorMaxDFAEdge-LexerATNSimulatorMinDFAEdge+1))\n\t}\n\tfrom.setIthEdge(tk-LexerATNSimulatorMinDFAEdge, to) // connect\n\n\treturn to\n}\n\n// Add a NewDFA state if there isn't one with l set of\n// configurations already. This method also detects the first\n// configuration containing an ATN rule stop state. Later, when\n// traversing the DFA, we will know which rule to accept.\nfunc (l *LexerATNSimulator) addDFAState(configs *ATNConfigSet, suppressEdge bool) *DFAState {\n\n\tproposed := NewDFAState(-1, configs)\n\tvar firstConfigWithRuleStopState *ATNConfig\n\n\tfor _, cfg := range configs.configs {\n\t\t_, ok := cfg.GetState().(*RuleStopState)\n\n\t\tif ok {\n\t\t\tfirstConfigWithRuleStopState = cfg\n\t\t\tbreak\n\t\t}\n\t}\n\tif firstConfigWithRuleStopState != nil {\n\t\tproposed.isAcceptState = true\n\t\tproposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor\n\t\tproposed.setPrediction(l.atn.ruleToTokenType[firstConfigWithRuleStopState.GetState().GetRuleIndex()])\n\t}\n\tdfa := l.decisionToDFA[l.mode]\n\n\tl.atn.stateMu.Lock()\n\tdefer l.atn.stateMu.Unlock()\n\texisting, present := dfa.Get(proposed)\n\tif present {\n\n\t\t// This state was already present, so just return it.\n\t\t//\n\t\tproposed = existing\n\t} else {\n\n\t\t// We need to add the new state\n\t\t//\n\t\tproposed.stateNumber = dfa.Len()\n\t\tconfigs.readOnly = true\n\t\tconfigs.configLookup = nil // Not needed now\n\t\tproposed.configs = configs\n\t\tdfa.Put(proposed)\n\t}\n\tif !suppressEdge {\n\t\tdfa.setS0(proposed)\n\t}\n\treturn proposed\n}\n\nfunc (l *LexerATNSimulator) getDFA(mode int) *DFA {\n\treturn l.decisionToDFA[mode]\n}\n\n// GetText returns the text [Match]ed so far for the current token.\nfunc (l *LexerATNSimulator) GetText(input CharStream) string {\n\t// index is first lookahead char, don't include.\n\treturn input.GetTextFromInterval(NewInterval(l.startIndex, input.Index()-1))\n}\n\nfunc (l *LexerATNSimulator) Consume(input CharStream) {\n\tcurChar := input.LA(1)\n\tif curChar == int('\\n') {\n\t\tl.Line++\n\t\tl.CharPositionInLine = 0\n\t} else {\n\t\tl.CharPositionInLine++\n\t}\n\tinput.Consume()\n}\n\nfunc (l *LexerATNSimulator) GetCharPositionInLine() int {\n\treturn l.CharPositionInLine\n}\n\nfunc (l *LexerATNSimulator) GetLine() int {\n\treturn l.Line\n}\n\nfunc (l *LexerATNSimulator) GetTokenName(tt int) string {\n\tif tt == -1 {\n\t\treturn \"EOF\"\n\t}\n\n\tvar sb strings.Builder\n\tsb.Grow(6)\n\tsb.WriteByte('\\'')\n\tsb.WriteRune(rune(tt))\n\tsb.WriteByte('\\'')\n\n\treturn sb.String()\n}\n\nfunc resetSimState(sim *SimState) {\n\tsim.index = -1\n\tsim.line = 0\n\tsim.column = -1\n\tsim.dfaState = nil\n}\n\ntype SimState struct {\n\tindex    int\n\tline     int\n\tcolumn   int\n\tdfaState *DFAState\n}\n\nfunc NewSimState() *SimState {\n\ts := new(SimState)\n\tresetSimState(s)\n\treturn s\n}\n\nfunc (s *SimState) reset() {\n\tresetSimState(s)\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/ll1_analyzer.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\ntype LL1Analyzer struct {\n\tatn *ATN\n}\n\nfunc NewLL1Analyzer(atn *ATN) *LL1Analyzer {\n\tla := new(LL1Analyzer)\n\tla.atn = atn\n\treturn la\n}\n\nconst (\n\t// LL1AnalyzerHitPred is a special value added to the lookahead sets to indicate that we hit\n\t// a predicate during analysis if\n\t//\n\t//   seeThruPreds==false\n\tLL1AnalyzerHitPred = TokenInvalidType\n)\n\n// *\n// Calculates the SLL(1) expected lookahead set for each outgoing transition\n// of an {@link ATNState}. The returned array has one element for each\n// outgoing transition in {@code s}. If the closure from transition\n// <em>i</em> leads to a semantic predicate before Matching a symbol, the\n// element at index <em>i</em> of the result will be {@code nil}.\n//\n// @param s the ATN state\n// @return the expected symbols for each outgoing transition of {@code s}.\nfunc (la *LL1Analyzer) getDecisionLookahead(s ATNState) []*IntervalSet {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tcount := len(s.GetTransitions())\n\tlook := make([]*IntervalSet, count)\n\tfor alt := 0; alt < count; alt++ {\n\n\t\tlook[alt] = NewIntervalSet()\n\t\t// TODO: This is one of the reasons that ATNConfigs are allocated and freed all the time - fix this tomorrow jim!\n\t\tlookBusy := NewJStore[*ATNConfig, Comparator[*ATNConfig]](aConfEqInst, ClosureBusyCollection, \"LL1Analyzer.getDecisionLookahead for lookBusy\")\n\t\tla.look1(s.GetTransitions()[alt].getTarget(), nil, BasePredictionContextEMPTY, look[alt], lookBusy, NewBitSet(), false, false)\n\n\t\t// Wipe out lookahead for la alternative if we found nothing,\n\t\t// or we had a predicate when we !seeThruPreds\n\t\tif look[alt].length() == 0 || look[alt].contains(LL1AnalyzerHitPred) {\n\t\t\tlook[alt] = nil\n\t\t}\n\t}\n\treturn look\n}\n\n// Look computes the set of tokens that can follow s in the [ATN] in the\n// specified ctx.\n//\n// If ctx is nil and the end of the rule containing\n// s is reached, [EPSILON] is added to the result set.\n//\n// If ctx is not nil and the end of the outermost rule is\n// reached, [EOF] is added to the result set.\n//\n// Parameter s the ATN state, and stopState is the ATN state to stop at. This can be a\n// [BlockEndState] to detect epsilon paths through a closure.\n//\n// Parameter ctx is the complete parser context, or nil if the context\n// should be ignored\n//\n// The func returns the set of tokens that can follow s in the [ATN] in the\n// specified ctx.\nfunc (la *LL1Analyzer) Look(s, stopState ATNState, ctx RuleContext) *IntervalSet {\n\tr := NewIntervalSet()\n\tvar lookContext *PredictionContext\n\tif ctx != nil {\n\t\tlookContext = predictionContextFromRuleContext(s.GetATN(), ctx)\n\t}\n\tla.look1(s, stopState, lookContext, r, NewJStore[*ATNConfig, Comparator[*ATNConfig]](aConfEqInst, ClosureBusyCollection, \"LL1Analyzer.Look for la.look1()\"),\n\t\tNewBitSet(), true, true)\n\treturn r\n}\n\n//*\n// Compute set of tokens that can follow {@code s} in the ATN in the\n// specified {@code ctx}.\n//\n// <p>If {@code ctx} is {@code nil} and {@code stopState} or the end of the\n// rule containing {@code s} is reached, {@link Token//EPSILON} is added to\n// the result set. If {@code ctx} is not {@code nil} and {@code addEOF} is\n// {@code true} and {@code stopState} or the end of the outermost rule is\n// reached, {@link Token//EOF} is added to the result set.</p>\n//\n// @param s the ATN state.\n// @param stopState the ATN state to stop at. This can be a\n// {@link BlockEndState} to detect epsilon paths through a closure.\n// @param ctx The outer context, or {@code nil} if the outer context should\n// not be used.\n// @param look The result lookahead set.\n// @param lookBusy A set used for preventing epsilon closures in the ATN\n// from causing a stack overflow. Outside code should pass\n// {@code NewSet<ATNConfig>} for la argument.\n// @param calledRuleStack A set used for preventing left recursion in the\n// ATN from causing a stack overflow. Outside code should pass\n// {@code NewBitSet()} for la argument.\n// @param seeThruPreds {@code true} to true semantic predicates as\n// implicitly {@code true} and \"see through them\", otherwise {@code false}\n// to treat semantic predicates as opaque and add {@link //HitPred} to the\n// result if one is encountered.\n// @param addEOF Add {@link Token//EOF} to the result if the end of the\n// outermost context is reached. This parameter has no effect if {@code ctx}\n// is {@code nil}.\n\nfunc (la *LL1Analyzer) look2(_, stopState ATNState, ctx *PredictionContext, look *IntervalSet, lookBusy *JStore[*ATNConfig, Comparator[*ATNConfig]],\n\tcalledRuleStack *BitSet, seeThruPreds, addEOF bool, i int) {\n\n\treturnState := la.atn.states[ctx.getReturnState(i)]\n\tla.look1(returnState, stopState, ctx.GetParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n\n}\n\nfunc (la *LL1Analyzer) look1(s, stopState ATNState, ctx *PredictionContext, look *IntervalSet, lookBusy *JStore[*ATNConfig, Comparator[*ATNConfig]], calledRuleStack *BitSet, seeThruPreds, addEOF bool) {\n\n\tc := NewATNConfig6(s, 0, ctx)\n\n\tif lookBusy.Contains(c) {\n\t\treturn\n\t}\n\n\t_, present := lookBusy.Put(c)\n\tif present {\n\t\treturn\n\n\t}\n\tif s == stopState {\n\t\tif ctx == nil {\n\t\t\tlook.addOne(TokenEpsilon)\n\t\t\treturn\n\t\t} else if ctx.isEmpty() && addEOF {\n\t\t\tlook.addOne(TokenEOF)\n\t\t\treturn\n\t\t}\n\t}\n\n\t_, ok := s.(*RuleStopState)\n\n\tif ok {\n\t\tif ctx == nil {\n\t\t\tlook.addOne(TokenEpsilon)\n\t\t\treturn\n\t\t} else if ctx.isEmpty() && addEOF {\n\t\t\tlook.addOne(TokenEOF)\n\t\t\treturn\n\t\t}\n\n\t\tif ctx.pcType != PredictionContextEmpty {\n\t\t\tremoved := calledRuleStack.contains(s.GetRuleIndex())\n\t\t\tdefer func() {\n\t\t\t\tif removed {\n\t\t\t\t\tcalledRuleStack.add(s.GetRuleIndex())\n\t\t\t\t}\n\t\t\t}()\n\t\t\tcalledRuleStack.remove(s.GetRuleIndex())\n\t\t\t// run thru all possible stack tops in ctx\n\t\t\tfor i := 0; i < ctx.length(); i++ {\n\t\t\t\treturnState := la.atn.states[ctx.getReturnState(i)]\n\t\t\t\tla.look2(returnState, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF, i)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\n\tn := len(s.GetTransitions())\n\n\tfor i := 0; i < n; i++ {\n\t\tt := s.GetTransitions()[i]\n\n\t\tif t1, ok := t.(*RuleTransition); ok {\n\t\t\tif calledRuleStack.contains(t1.getTarget().GetRuleIndex()) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnewContext := SingletonBasePredictionContextCreate(ctx, t1.followState.GetStateNumber())\n\t\t\tla.look3(stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF, t1)\n\t\t} else if t2, ok := t.(AbstractPredicateTransition); ok {\n\t\t\tif seeThruPreds {\n\t\t\t\tla.look1(t2.getTarget(), stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n\t\t\t} else {\n\t\t\t\tlook.addOne(LL1AnalyzerHitPred)\n\t\t\t}\n\t\t} else if t.getIsEpsilon() {\n\t\t\tla.look1(t.getTarget(), stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n\t\t} else if _, ok := t.(*WildcardTransition); ok {\n\t\t\tlook.addRange(TokenMinUserTokenType, la.atn.maxTokenType)\n\t\t} else {\n\t\t\tset := t.getLabel()\n\t\t\tif set != nil {\n\t\t\t\tif _, ok := t.(*NotSetTransition); ok {\n\t\t\t\t\tset = set.complement(TokenMinUserTokenType, la.atn.maxTokenType)\n\t\t\t\t}\n\t\t\t\tlook.addSet(set)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (la *LL1Analyzer) look3(stopState ATNState, ctx *PredictionContext, look *IntervalSet, lookBusy *JStore[*ATNConfig, Comparator[*ATNConfig]],\n\tcalledRuleStack *BitSet, seeThruPreds, addEOF bool, t1 *RuleTransition) {\n\n\tnewContext := SingletonBasePredictionContextCreate(ctx, t1.followState.GetStateNumber())\n\n\tdefer func() {\n\t\tcalledRuleStack.remove(t1.getTarget().GetRuleIndex())\n\t}()\n\n\tcalledRuleStack.add(t1.getTarget().GetRuleIndex())\n\tla.look1(t1.getTarget(), stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/mutex.go",
    "content": "//go:build !antlr.nomutex\n// +build !antlr.nomutex\n\npackage antlr\n\nimport \"sync\"\n\n// Mutex is a simple mutex implementation which just delegates to sync.Mutex, it\n// is used to provide a mutex implementation for the antlr package, which users\n// can turn off with the build tag -tags antlr.nomutex\ntype Mutex struct {\n\tmu sync.Mutex\n}\n\nfunc (m *Mutex) Lock() {\n\tm.mu.Lock()\n}\n\nfunc (m *Mutex) Unlock() {\n\tm.mu.Unlock()\n}\n\ntype RWMutex struct {\n\tmu sync.RWMutex\n}\n\nfunc (m *RWMutex) Lock() {\n\tm.mu.Lock()\n}\n\nfunc (m *RWMutex) Unlock() {\n\tm.mu.Unlock()\n}\n\nfunc (m *RWMutex) RLock() {\n\tm.mu.RLock()\n}\n\nfunc (m *RWMutex) RUnlock() {\n\tm.mu.RUnlock()\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/mutex_nomutex.go",
    "content": "// +build antlr.nomutex\n\npackage antlr\n\ntype Mutex struct{}\n\nfunc (m *Mutex) Lock() {\n\t// No-op\n}\n\nfunc (m *Mutex) Unlock() {\n\t// No-op\n}\n\ntype RWMutex struct{}\n\nfunc (m *RWMutex) Lock() {\n\t// No-op\n}\n\nfunc (m *RWMutex) Unlock() {\n\t// No-op\n}\n\nfunc (m *RWMutex) RLock() {\n\t// No-op\n}\n\nfunc (m *RWMutex) RUnlock() {\n\t// No-op\n}"
  },
  {
    "path": "runtime/Go/antlr/v4/nostatistics.go",
    "content": "//go:build !antlr.stats\n\npackage antlr\n\n// This file is compiled when the build configuration antlr.stats is not enabled.\n// which then allows the compiler to optimize out all the code that is not used.\nconst collectStats = false\n\n// goRunStats is a dummy struct used when build configuration antlr.stats is not enabled.\ntype goRunStats struct {\n}\n\nvar Statistics = &goRunStats{}\n\nfunc (s *goRunStats) AddJStatRec(_ *JStatRec) {\n\t// Do nothing - compiler will optimize this out (hopefully)\n}\n\nfunc (s *goRunStats) CollectionAnomalies() {\n\t// Do nothing - compiler will optimize this out (hopefully)\n}\n\nfunc (s *goRunStats) Reset() {\n\t// Do nothing - compiler will optimize this out (hopefully)\n}\n\nfunc (s *goRunStats) Report(dir string, prefix string) error {\n\t// Do nothing - compiler will optimize this out (hopefully)\n\treturn nil\n}\n\nfunc (s *goRunStats) Analyze() {\n\t// Do nothing - compiler will optimize this out (hopefully)\n}\n\ntype statsOption func(*goRunStats) error\n\nfunc (s *goRunStats) Configure(options ...statsOption) error {\n\t// Do nothing - compiler will optimize this out (hopefully)\n\treturn nil\n}\n\nfunc WithTopN(topN int) statsOption {\n\treturn func(s *goRunStats) error {\n\t\treturn nil\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/parser.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\ntype Parser interface {\n\tRecognizer\n\n\tGetInterpreter() *ParserATNSimulator\n\n\tGetTokenStream() TokenStream\n\tGetTokenFactory() TokenFactory\n\tGetParserRuleContext() ParserRuleContext\n\tSetParserRuleContext(ParserRuleContext)\n\tConsume() Token\n\tGetParseListeners() []ParseTreeListener\n\n\tGetErrorHandler() ErrorStrategy\n\tSetErrorHandler(ErrorStrategy)\n\tGetInputStream() IntStream\n\tGetCurrentToken() Token\n\tGetExpectedTokens() *IntervalSet\n\tNotifyErrorListeners(string, Token, RecognitionException)\n\tIsExpectedToken(int) bool\n\tGetPrecedence() int\n\tGetRuleInvocationStack(ParserRuleContext) []string\n}\n\ntype BaseParser struct {\n\t*BaseRecognizer\n\n\tInterpreter     *ParserATNSimulator\n\tBuildParseTrees bool\n\n\tinput           TokenStream\n\terrHandler      ErrorStrategy\n\tprecedenceStack IntStack\n\tctx             ParserRuleContext\n\n\ttracer         *TraceListener\n\tparseListeners []ParseTreeListener\n\t_SyntaxErrors  int\n}\n\n// NewBaseParser contains all the parsing support code to embed in parsers. Essentially most of it is error\n// recovery stuff.\n//\n//goland:noinspection GoUnusedExportedFunction\nfunc NewBaseParser(input TokenStream) *BaseParser {\n\n\tp := new(BaseParser)\n\n\tp.BaseRecognizer = NewBaseRecognizer()\n\n\t// The input stream.\n\tp.input = nil\n\n\t// The error handling strategy for the parser. The default value is a new\n\t// instance of {@link DefaultErrorStrategy}.\n\tp.errHandler = NewDefaultErrorStrategy()\n\tp.precedenceStack = make([]int, 0)\n\tp.precedenceStack.Push(0)\n\n\t// The ParserRuleContext object for the currently executing rule.\n\t// p.is always non-nil during the parsing process.\n\tp.ctx = nil\n\n\t// Specifies whether the parser should construct a parse tree during\n\t// the parsing process. The default value is {@code true}.\n\tp.BuildParseTrees = true\n\n\t// When setTrace(true) is called, a reference to the\n\t// TraceListener is stored here, so it can be easily removed in a\n\t// later call to setTrace(false). The listener itself is\n\t// implemented as a parser listener so p.field is not directly used by\n\t// other parser methods.\n\tp.tracer = nil\n\n\t// The list of ParseTreeListener listeners registered to receive\n\t// events during the parse.\n\tp.parseListeners = nil\n\n\t// The number of syntax errors Reported during parsing. p.value is\n\t// incremented each time NotifyErrorListeners is called.\n\tp._SyntaxErrors = 0\n\tp.SetInputStream(input)\n\n\treturn p\n}\n\n// This field maps from the serialized ATN string to the deserialized [ATN] with\n// bypass alternatives.\n//\n// [ATNDeserializationOptions.isGenerateRuleBypassTransitions]\n//\n//goland:noinspection GoUnusedGlobalVariable\nvar bypassAltsAtnCache = make(map[string]int)\n\n// reset the parser's state//\nfunc (p *BaseParser) reset() {\n\tif p.input != nil {\n\t\tp.input.Seek(0)\n\t}\n\tp.errHandler.reset(p)\n\tp.ctx = nil\n\tp._SyntaxErrors = 0\n\tp.SetTrace(nil)\n\tp.precedenceStack = make([]int, 0)\n\tp.precedenceStack.Push(0)\n\tif p.Interpreter != nil {\n\t\tp.Interpreter.reset()\n\t}\n}\n\nfunc (p *BaseParser) GetErrorHandler() ErrorStrategy {\n\treturn p.errHandler\n}\n\nfunc (p *BaseParser) SetErrorHandler(e ErrorStrategy) {\n\tp.errHandler = e\n}\n\n// Match current input symbol against {@code ttype}. If the symbol type\n// Matches, {@link ANTLRErrorStrategy//ReportMatch} and {@link //consume} are\n// called to complete the Match process.\n//\n// <p>If the symbol type does not Match,\n// {@link ANTLRErrorStrategy//recoverInline} is called on the current error\n// strategy to attempt recovery. If {@link //getBuildParseTree} is\n// {@code true} and the token index of the symbol returned by\n// {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to\n// the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>\n//\n// @param ttype the token type to Match\n// @return the Matched symbol\n// @panics RecognitionException if the current input symbol did not Match\n// {@code ttype} and the error strategy could not recover from the\n// mismatched symbol\n\nfunc (p *BaseParser) Match(ttype int) Token {\n\n\tt := p.GetCurrentToken()\n\n\tif t.GetTokenType() == ttype {\n\t\tp.errHandler.ReportMatch(p)\n\t\tp.Consume()\n\t} else {\n\t\tt = p.errHandler.RecoverInline(p)\n\t\tif p.HasError() {\n\t\t\treturn nil\n\t\t}\n\t\tif p.BuildParseTrees && t.GetTokenIndex() == -1 {\n\n\t\t\t// we must have conjured up a new token during single token\n\t\t\t// insertion if it's not the current symbol\n\t\t\tp.ctx.AddErrorNode(t)\n\t\t}\n\t}\n\n\treturn t\n}\n\n// Match current input symbol as a wildcard. If the symbol type Matches\n// (i.e. has a value greater than 0), {@link ANTLRErrorStrategy//ReportMatch}\n// and {@link //consume} are called to complete the Match process.\n//\n// <p>If the symbol type does not Match,\n// {@link ANTLRErrorStrategy//recoverInline} is called on the current error\n// strategy to attempt recovery. If {@link //getBuildParseTree} is\n// {@code true} and the token index of the symbol returned by\n// {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to\n// the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>\n//\n// @return the Matched symbol\n// @panics RecognitionException if the current input symbol did not Match\n// a wildcard and the error strategy could not recover from the mismatched\n// symbol\n\nfunc (p *BaseParser) MatchWildcard() Token {\n\tt := p.GetCurrentToken()\n\tif t.GetTokenType() > 0 {\n\t\tp.errHandler.ReportMatch(p)\n\t\tp.Consume()\n\t} else {\n\t\tt = p.errHandler.RecoverInline(p)\n\t\tif p.BuildParseTrees && t.GetTokenIndex() == -1 {\n\t\t\t// we must have conjured up a new token during single token\n\t\t\t// insertion if it's not the current symbol\n\t\t\tp.ctx.AddErrorNode(t)\n\t\t}\n\t}\n\treturn t\n}\n\nfunc (p *BaseParser) GetParserRuleContext() ParserRuleContext {\n\treturn p.ctx\n}\n\nfunc (p *BaseParser) SetParserRuleContext(v ParserRuleContext) {\n\tp.ctx = v\n}\n\nfunc (p *BaseParser) GetParseListeners() []ParseTreeListener {\n\tif p.parseListeners == nil {\n\t\treturn make([]ParseTreeListener, 0)\n\t}\n\treturn p.parseListeners\n}\n\n// AddParseListener registers listener to receive events during the parsing process.\n//\n// To support output-preserving grammar transformations (including but not\n// limited to left-recursion removal, automated left-factoring, and\n// optimized code generation), calls to listener methods during the parse\n// may differ substantially from calls made by\n// [ParseTreeWalker.DEFAULT] used after the parse is complete. In\n// particular, rule entry and exit events may occur in a different order\n// during the parse than after the parser. In addition, calls to certain\n// rule entry methods may be omitted.\n//\n// With the following specific exceptions, calls to listener events are\n// deterministic, i.e. for identical input the calls to listener\n// methods will be the same.\n//\n//   - Alterations to the grammar used to generate code may change the\n//     behavior of the listener calls.\n//   - Alterations to the command line options passed to ANTLR 4 when\n//     generating the parser may change the behavior of the listener calls.\n//   - Changing the version of the ANTLR Tool used to generate the parser\n//     may change the behavior of the listener calls.\nfunc (p *BaseParser) AddParseListener(listener ParseTreeListener) {\n\tif listener == nil {\n\t\tpanic(\"listener\")\n\t}\n\tif p.parseListeners == nil {\n\t\tp.parseListeners = make([]ParseTreeListener, 0)\n\t}\n\tp.parseListeners = append(p.parseListeners, listener)\n}\n\n// RemoveParseListener removes listener from the list of parse listeners.\n//\n// If listener is nil or has not been added as a parse\n// listener, this func does nothing.\nfunc (p *BaseParser) RemoveParseListener(listener ParseTreeListener) {\n\n\tif p.parseListeners != nil {\n\n\t\tidx := -1\n\t\tfor i, v := range p.parseListeners {\n\t\t\tif v == listener {\n\t\t\t\tidx = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif idx == -1 {\n\t\t\treturn\n\t\t}\n\n\t\t// remove the listener from the slice\n\t\tp.parseListeners = append(p.parseListeners[0:idx], p.parseListeners[idx+1:]...)\n\n\t\tif len(p.parseListeners) == 0 {\n\t\t\tp.parseListeners = nil\n\t\t}\n\t}\n}\n\n// Remove all parse listeners.\nfunc (p *BaseParser) removeParseListeners() {\n\tp.parseListeners = nil\n}\n\n// TriggerEnterRuleEvent notifies all parse listeners of an enter rule event.\nfunc (p *BaseParser) TriggerEnterRuleEvent() {\n\tif p.parseListeners != nil {\n\t\tctx := p.ctx\n\t\tfor _, listener := range p.parseListeners {\n\t\t\tlistener.EnterEveryRule(ctx)\n\t\t\tctx.EnterRule(listener)\n\t\t}\n\t}\n}\n\n// TriggerExitRuleEvent notifies any parse listeners of an exit rule event.\nfunc (p *BaseParser) TriggerExitRuleEvent() {\n\tif p.parseListeners != nil {\n\t\t// reverse order walk of listeners\n\t\tctx := p.ctx\n\t\tl := len(p.parseListeners) - 1\n\n\t\tfor i := range p.parseListeners {\n\t\t\tlistener := p.parseListeners[l-i]\n\t\t\tctx.ExitRule(listener)\n\t\t\tlistener.ExitEveryRule(ctx)\n\t\t}\n\t}\n}\n\nfunc (p *BaseParser) GetInterpreter() *ParserATNSimulator {\n\treturn p.Interpreter\n}\n\nfunc (p *BaseParser) GetATN() *ATN {\n\treturn p.Interpreter.atn\n}\n\nfunc (p *BaseParser) GetTokenFactory() TokenFactory {\n\treturn p.input.GetTokenSource().GetTokenFactory()\n}\n\n// setTokenFactory is used to tell our token source and error strategy about a new way to create tokens.\nfunc (p *BaseParser) setTokenFactory(factory TokenFactory) {\n\tp.input.GetTokenSource().setTokenFactory(factory)\n}\n\n// GetATNWithBypassAlts - the ATN with bypass alternatives is expensive to create, so we create it\n// lazily.\nfunc (p *BaseParser) GetATNWithBypassAlts() {\n\n\t// TODO - Implement this?\n\tpanic(\"Not implemented!\")\n\n\t//\tserializedAtn := p.getSerializedATN()\n\t//\tif (serializedAtn == nil) {\n\t//\t\tpanic(\"The current parser does not support an ATN with bypass alternatives.\")\n\t//\t}\n\t//\tresult := p.bypassAltsAtnCache[serializedAtn]\n\t//\tif (result == nil) {\n\t//\t\tdeserializationOptions := NewATNDeserializationOptions(nil)\n\t//\t\tdeserializationOptions.generateRuleBypassTransitions = true\n\t//\t\tresult = NewATNDeserializer(deserializationOptions).deserialize(serializedAtn)\n\t//\t\tp.bypassAltsAtnCache[serializedAtn] = result\n\t//\t}\n\t//\treturn result\n}\n\n// The preferred method of getting a tree pattern. For example, here's a\n// sample use:\n//\n// <pre>\n// ParseTree t = parser.expr()\n// ParseTreePattern p = parser.compileParseTreePattern(\"&ltID&gt+0\",\n// MyParser.RULE_expr)\n// ParseTreeMatch m = p.Match(t)\n// String id = m.Get(\"ID\")\n// </pre>\n\n//goland:noinspection GoUnusedParameter\nfunc (p *BaseParser) compileParseTreePattern(pattern, patternRuleIndex, lexer Lexer) {\n\n\tpanic(\"NewParseTreePatternMatcher not implemented!\")\n\t//\n\t//\tif (lexer == nil) {\n\t//\t\tif (p.GetTokenStream() != nil) {\n\t//\t\t\ttokenSource := p.GetTokenStream().GetTokenSource()\n\t//\t\t\tif _, ok := tokenSource.(ILexer); ok {\n\t//\t\t\t\tlexer = tokenSource\n\t//\t\t\t}\n\t//\t\t}\n\t//\t}\n\t//\tif (lexer == nil) {\n\t//\t\tpanic(\"Parser can't discover a lexer to use\")\n\t//\t}\n\n\t//\tm := NewParseTreePatternMatcher(lexer, p)\n\t//\treturn m.compile(pattern, patternRuleIndex)\n}\n\nfunc (p *BaseParser) GetInputStream() IntStream {\n\treturn p.GetTokenStream()\n}\n\nfunc (p *BaseParser) SetInputStream(input TokenStream) {\n\tp.SetTokenStream(input)\n}\n\nfunc (p *BaseParser) GetTokenStream() TokenStream {\n\treturn p.input\n}\n\n// SetTokenStream installs input as the token stream and resets the parser.\nfunc (p *BaseParser) SetTokenStream(input TokenStream) {\n\tp.input = nil\n\tp.reset()\n\tp.input = input\n}\n\n// GetCurrentToken returns the current token at LT(1).\n//\n// [Match] needs to return the current input symbol, which gets put\n// into the label for the associated token ref e.g., x=ID.\nfunc (p *BaseParser) GetCurrentToken() Token {\n\treturn p.input.LT(1)\n}\n\nfunc (p *BaseParser) NotifyErrorListeners(msg string, offendingToken Token, err RecognitionException) {\n\tif offendingToken == nil {\n\t\toffendingToken = p.GetCurrentToken()\n\t}\n\tp._SyntaxErrors++\n\tline := offendingToken.GetLine()\n\tcolumn := offendingToken.GetColumn()\n\tlistener := p.GetErrorListenerDispatch()\n\tlistener.SyntaxError(p, offendingToken, line, column, msg, err)\n}\n\nfunc (p *BaseParser) Consume() Token {\n\to := p.GetCurrentToken()\n\tif o.GetTokenType() != TokenEOF {\n\t\tp.GetInputStream().Consume()\n\t}\n\thasListener := p.parseListeners != nil && len(p.parseListeners) > 0\n\tif p.BuildParseTrees || hasListener {\n\t\tif p.errHandler.InErrorRecoveryMode(p) {\n\t\t\tnode := p.ctx.AddErrorNode(o)\n\t\t\tif p.parseListeners != nil {\n\t\t\t\tfor _, l := range p.parseListeners {\n\t\t\t\t\tl.VisitErrorNode(node)\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tnode := p.ctx.AddTokenNode(o)\n\t\t\tif p.parseListeners != nil {\n\t\t\t\tfor _, l := range p.parseListeners {\n\t\t\t\t\tl.VisitTerminal(node)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//        node.invokingState = p.state\n\t}\n\n\treturn o\n}\n\nfunc (p *BaseParser) addContextToParseTree() {\n\t// add current context to parent if we have a parent\n\tif p.ctx.GetParent() != nil {\n\t\tp.ctx.GetParent().(ParserRuleContext).AddChild(p.ctx)\n\t}\n}\n\nfunc (p *BaseParser) EnterRule(localctx ParserRuleContext, state, _ int) {\n\tp.SetState(state)\n\tp.ctx = localctx\n\tp.ctx.SetStart(p.input.LT(1))\n\tif p.BuildParseTrees {\n\t\tp.addContextToParseTree()\n\t}\n\tif p.parseListeners != nil {\n\t\tp.TriggerEnterRuleEvent()\n\t}\n}\n\nfunc (p *BaseParser) ExitRule() {\n\tp.ctx.SetStop(p.input.LT(-1))\n\t// trigger event on ctx, before it reverts to parent\n\tif p.parseListeners != nil {\n\t\tp.TriggerExitRuleEvent()\n\t}\n\tp.SetState(p.ctx.GetInvokingState())\n\tif p.ctx.GetParent() != nil {\n\t\tp.ctx = p.ctx.GetParent().(ParserRuleContext)\n\t} else {\n\t\tp.ctx = nil\n\t}\n}\n\nfunc (p *BaseParser) EnterOuterAlt(localctx ParserRuleContext, altNum int) {\n\tlocalctx.SetAltNumber(altNum)\n\t// if we have a new localctx, make sure we replace existing ctx\n\t// that is previous child of parse tree\n\tif p.BuildParseTrees && p.ctx != localctx {\n\t\tif p.ctx.GetParent() != nil {\n\t\t\tp.ctx.GetParent().(ParserRuleContext).RemoveLastChild()\n\t\t\tp.ctx.GetParent().(ParserRuleContext).AddChild(localctx)\n\t\t}\n\t}\n\tp.ctx = localctx\n}\n\n// Get the precedence level for the top-most precedence rule.\n//\n// @return The precedence level for the top-most precedence rule, or -1 if\n// the parser context is not nested within a precedence rule.\n\nfunc (p *BaseParser) GetPrecedence() int {\n\tif len(p.precedenceStack) == 0 {\n\t\treturn -1\n\t}\n\n\treturn p.precedenceStack[len(p.precedenceStack)-1]\n}\n\nfunc (p *BaseParser) EnterRecursionRule(localctx ParserRuleContext, state, _, precedence int) {\n\tp.SetState(state)\n\tp.precedenceStack.Push(precedence)\n\tp.ctx = localctx\n\tp.ctx.SetStart(p.input.LT(1))\n\tif p.parseListeners != nil {\n\t\tp.TriggerEnterRuleEvent() // simulates rule entry for\n\t\t// left-recursive rules\n\t}\n}\n\n//\n// Like {@link //EnterRule} but for recursive rules.\n\nfunc (p *BaseParser) PushNewRecursionContext(localctx ParserRuleContext, state, _ int) {\n\tprevious := p.ctx\n\tprevious.SetParent(localctx)\n\tprevious.SetInvokingState(state)\n\tprevious.SetStop(p.input.LT(-1))\n\n\tp.ctx = localctx\n\tp.ctx.SetStart(previous.GetStart())\n\tif p.BuildParseTrees {\n\t\tp.ctx.AddChild(previous)\n\t}\n\tif p.parseListeners != nil {\n\t\tp.TriggerEnterRuleEvent() // simulates rule entry for\n\t\t// left-recursive rules\n\t}\n}\n\nfunc (p *BaseParser) UnrollRecursionContexts(parentCtx ParserRuleContext) {\n\t_, _ = p.precedenceStack.Pop()\n\tp.ctx.SetStop(p.input.LT(-1))\n\tretCtx := p.ctx // save current ctx (return value)\n\t// unroll so ctx is as it was before call to recursive method\n\tif p.parseListeners != nil {\n\t\tfor p.ctx != parentCtx {\n\t\t\tp.TriggerExitRuleEvent()\n\t\t\tp.ctx = p.ctx.GetParent().(ParserRuleContext)\n\t\t}\n\t} else {\n\t\tp.ctx = parentCtx\n\t}\n\t// hook into tree\n\tretCtx.SetParent(parentCtx)\n\tif p.BuildParseTrees && parentCtx != nil {\n\t\t// add return ctx into invoking rule's tree\n\t\tparentCtx.AddChild(retCtx)\n\t}\n}\n\nfunc (p *BaseParser) GetInvokingContext(ruleIndex int) ParserRuleContext {\n\tctx := p.ctx\n\tfor ctx != nil {\n\t\tif ctx.GetRuleIndex() == ruleIndex {\n\t\t\treturn ctx\n\t\t}\n\t\tctx = ctx.GetParent().(ParserRuleContext)\n\t}\n\treturn nil\n}\n\nfunc (p *BaseParser) Precpred(_ RuleContext, precedence int) bool {\n\treturn precedence >= p.precedenceStack[len(p.precedenceStack)-1]\n}\n\n//goland:noinspection GoUnusedParameter\nfunc (p *BaseParser) inContext(context ParserRuleContext) bool {\n\t// TODO: useful in parser?\n\treturn false\n}\n\n// IsExpectedToken checks whether symbol can follow the current state in the\n// {ATN}. The behavior of p.method is equivalent to the following, but is\n// implemented such that the complete context-sensitive follow set does not\n// need to be explicitly constructed.\n//\n//\treturn getExpectedTokens().contains(symbol)\nfunc (p *BaseParser) IsExpectedToken(symbol int) bool {\n\tatn := p.Interpreter.atn\n\tctx := p.ctx\n\ts := atn.states[p.state]\n\tfollowing := atn.NextTokens(s, nil)\n\tif following.contains(symbol) {\n\t\treturn true\n\t}\n\tif !following.contains(TokenEpsilon) {\n\t\treturn false\n\t}\n\tfor ctx != nil && ctx.GetInvokingState() >= 0 && following.contains(TokenEpsilon) {\n\t\tinvokingState := atn.states[ctx.GetInvokingState()]\n\t\trt := invokingState.GetTransitions()[0]\n\t\tfollowing = atn.NextTokens(rt.(*RuleTransition).followState, nil)\n\t\tif following.contains(symbol) {\n\t\t\treturn true\n\t\t}\n\t\tctx = ctx.GetParent().(ParserRuleContext)\n\t}\n\tif following.contains(TokenEpsilon) && symbol == TokenEOF {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// GetExpectedTokens and returns the set of input symbols which could follow the current parser\n// state and context, as given by [GetState] and [GetContext],\n// respectively.\nfunc (p *BaseParser) GetExpectedTokens() *IntervalSet {\n\treturn p.Interpreter.atn.getExpectedTokens(p.state, p.ctx)\n}\n\nfunc (p *BaseParser) GetExpectedTokensWithinCurrentRule() *IntervalSet {\n\tatn := p.Interpreter.atn\n\ts := atn.states[p.state]\n\treturn atn.NextTokens(s, nil)\n}\n\n// GetRuleIndex get a rule's index (i.e., RULE_ruleName field) or -1 if not found.\nfunc (p *BaseParser) GetRuleIndex(ruleName string) int {\n\tvar ruleIndex, ok = p.GetRuleIndexMap()[ruleName]\n\tif ok {\n\t\treturn ruleIndex\n\t}\n\n\treturn -1\n}\n\n// GetRuleInvocationStack returns a list of the rule names in your parser instance\n// leading up to a call to the current rule. You could override if\n// you want more details such as the file/line info of where\n// in the ATN a rule is invoked.\nfunc (p *BaseParser) GetRuleInvocationStack(c ParserRuleContext) []string {\n\tif c == nil {\n\t\tc = p.ctx\n\t}\n\tstack := make([]string, 0)\n\tfor c != nil {\n\t\t// compute what follows who invoked us\n\t\truleIndex := c.GetRuleIndex()\n\t\tif ruleIndex < 0 {\n\t\t\tstack = append(stack, \"n/a\")\n\t\t} else {\n\t\t\tstack = append(stack, p.GetRuleNames()[ruleIndex])\n\t\t}\n\n\t\tvp := c.GetParent()\n\n\t\tif vp == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tc = vp.(ParserRuleContext)\n\t}\n\treturn stack\n}\n\n// GetDFAStrings returns a list of all DFA states used for debugging purposes\nfunc (p *BaseParser) GetDFAStrings() string {\n\treturn fmt.Sprint(p.Interpreter.decisionToDFA)\n}\n\n// DumpDFA prints the whole of the DFA for debugging\nfunc (p *BaseParser) DumpDFA() {\n\tseenOne := false\n\tfor _, dfa := range p.Interpreter.decisionToDFA {\n\t\tif dfa.Len() > 0 {\n\t\t\tif seenOne {\n\t\t\t\tfmt.Println()\n\t\t\t}\n\t\t\tfmt.Println(\"Decision \" + strconv.Itoa(dfa.decision) + \":\")\n\t\t\tfmt.Print(dfa.String(p.LiteralNames, p.SymbolicNames))\n\t\t\tseenOne = true\n\t\t}\n\t}\n}\n\nfunc (p *BaseParser) GetSourceName() string {\n\treturn p.GrammarFileName\n}\n\n// SetTrace installs a trace listener for the parse.\n//\n// During a parse it is sometimes useful to listen in on the rule entry and exit\n// events as well as token Matches. This is for quick and dirty debugging.\nfunc (p *BaseParser) SetTrace(trace *TraceListener) {\n\tif trace == nil {\n\t\tp.RemoveParseListener(p.tracer)\n\t\tp.tracer = nil\n\t} else {\n\t\tif p.tracer != nil {\n\t\t\tp.RemoveParseListener(p.tracer)\n\t\t}\n\t\tp.tracer = NewTraceListener(p)\n\t\tp.AddParseListener(p.tracer)\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/parser_atn_simulator.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// ClosureBusy is a store of ATNConfigs and is a tiny abstraction layer over\n// a standard JStore so that we can use Lazy instantiation of the JStore, mostly\n// to avoid polluting the stats module with a ton of JStore instances with nothing in them.\ntype ClosureBusy struct {\n\tbMap *JStore[*ATNConfig, Comparator[*ATNConfig]]\n\tdesc string\n}\n\n// NewClosureBusy creates a new ClosureBusy instance used to avoid infinite recursion for right-recursive rules\nfunc NewClosureBusy(desc string) *ClosureBusy {\n\treturn &ClosureBusy{\n\t\tdesc: desc,\n\t}\n}\n\nfunc (c *ClosureBusy) Put(config *ATNConfig) (*ATNConfig, bool) {\n\tif c.bMap == nil {\n\t\tc.bMap = NewJStore[*ATNConfig, Comparator[*ATNConfig]](aConfEqInst, ClosureBusyCollection, c.desc)\n\t}\n\treturn c.bMap.Put(config)\n}\n\ntype ParserATNSimulator struct {\n\tBaseATNSimulator\n\n\tparser         Parser\n\tpredictionMode int\n\tinput          TokenStream\n\tstartIndex     int\n\tdfa            *DFA\n\tmergeCache     *JPCMap\n\touterContext   ParserRuleContext\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewParserATNSimulator(parser Parser, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) *ParserATNSimulator {\n\n\tp := &ParserATNSimulator{\n\t\tBaseATNSimulator: BaseATNSimulator{\n\t\t\tatn:                atn,\n\t\t\tsharedContextCache: sharedContextCache,\n\t\t},\n\t}\n\n\tp.parser = parser\n\tp.decisionToDFA = decisionToDFA\n\t// SLL, LL, or LL + exact ambig detection?//\n\tp.predictionMode = PredictionModeLL\n\t// LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n\tp.input = nil\n\tp.startIndex = 0\n\tp.outerContext = nil\n\tp.dfa = nil\n\t// Each prediction operation uses a cache for merge of prediction contexts.\n\t// Don't keep around as it wastes huge amounts of memory. [JPCMap]\n\t// isn't Synchronized, but we're ok since two threads shouldn't reuse same\n\t// parser/atn-simulator object because it can only handle one input at a time.\n\t// This maps graphs a and b to merged result c. (a,b) -> c. We can avoid\n\t// the merge if we ever see a and b again.  Note that (b,a) -> c should\n\t// also be examined during cache lookup.\n\t//\n\tp.mergeCache = nil\n\n\treturn p\n}\n\nfunc (p *ParserATNSimulator) GetPredictionMode() int {\n\treturn p.predictionMode\n}\n\nfunc (p *ParserATNSimulator) SetPredictionMode(v int) {\n\tp.predictionMode = v\n}\n\nfunc (p *ParserATNSimulator) reset() {\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) AdaptivePredict(parser *BaseParser, input TokenStream, decision int, outerContext ParserRuleContext) int {\n\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"adaptivePredict decision \" + strconv.Itoa(decision) +\n\t\t\t\" exec LA(1)==\" + p.getLookaheadName(input) +\n\t\t\t\" line \" + strconv.Itoa(input.LT(1).GetLine()) + \":\" +\n\t\t\tstrconv.Itoa(input.LT(1).GetColumn()))\n\t}\n\tp.input = input\n\tp.startIndex = input.Index()\n\tp.outerContext = outerContext\n\n\tdfa := p.decisionToDFA[decision]\n\tp.dfa = dfa\n\tm := input.Mark()\n\tindex := input.Index()\n\n\tdefer func() {\n\t\tp.dfa = nil\n\t\tp.mergeCache = nil // whack cache after each prediction\n\t\t// Do not attempt to run a GC now that we're done with the cache as makes the\n\t\t// GC overhead terrible for badly formed grammars and has little effect on well formed\n\t\t// grammars.\n\t\t// I have made some extra effort to try and reduce memory pressure by reusing allocations when\n\t\t// possible. However, it can only have a limited effect. The real solution is to encourage grammar\n\t\t// authors to think more carefully about their grammar and to use the new antlr.stats tag to inspect\n\t\t// what is happening at runtime, along with using the error listener to report ambiguities.\n\n\t\tinput.Seek(index)\n\t\tinput.Release(m)\n\t}()\n\n\t// Now we are certain to have a specific decision's DFA\n\t// But, do we still need an initial state?\n\tvar s0 *DFAState\n\tp.atn.stateMu.RLock()\n\tif dfa.getPrecedenceDfa() {\n\t\tp.atn.edgeMu.RLock()\n\t\t// the start state for a precedence DFA depends on the current\n\t\t// parser precedence, and is provided by a DFA method.\n\t\ts0 = dfa.getPrecedenceStartState(p.parser.GetPrecedence())\n\t\tp.atn.edgeMu.RUnlock()\n\t} else {\n\t\t// the start state for a \"regular\" DFA is just s0\n\t\ts0 = dfa.getS0()\n\t}\n\tp.atn.stateMu.RUnlock()\n\n\tif s0 == nil {\n\t\tif outerContext == nil {\n\t\t\touterContext = ParserRuleContextEmpty\n\t\t}\n\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\tfmt.Println(\"predictATN decision \" + strconv.Itoa(dfa.decision) +\n\t\t\t\t\" exec LA(1)==\" + p.getLookaheadName(input) +\n\t\t\t\t\", outerContext=\" + outerContext.String(p.parser.GetRuleNames(), nil))\n\t\t}\n\t\tfullCtx := false\n\t\ts0Closure := p.computeStartState(dfa.atnStartState, ParserRuleContextEmpty, fullCtx)\n\n\t\tp.atn.stateMu.Lock()\n\t\tif dfa.getPrecedenceDfa() {\n\t\t\t// If p is a precedence DFA, we use applyPrecedenceFilter\n\t\t\t// to convert the computed start state to a precedence start\n\t\t\t// state. We then use DFA.setPrecedenceStartState to set the\n\t\t\t// appropriate start state for the precedence level rather\n\t\t\t// than simply setting DFA.s0.\n\t\t\t//\n\t\t\tdfa.s0.configs = s0Closure\n\t\t\ts0Closure = p.applyPrecedenceFilter(s0Closure)\n\t\t\ts0 = p.addDFAState(dfa, NewDFAState(-1, s0Closure))\n\t\t\tp.atn.edgeMu.Lock()\n\t\t\tdfa.setPrecedenceStartState(p.parser.GetPrecedence(), s0)\n\t\t\tp.atn.edgeMu.Unlock()\n\t\t} else {\n\t\t\ts0 = p.addDFAState(dfa, NewDFAState(-1, s0Closure))\n\t\t\tdfa.setS0(s0)\n\t\t}\n\t\tp.atn.stateMu.Unlock()\n\t}\n\n\talt, re := p.execATN(dfa, s0, input, index, outerContext)\n\tparser.SetError(re)\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"DFA after predictATN: \" + dfa.String(p.parser.GetLiteralNames(), nil))\n\t}\n\treturn alt\n\n}\n\n// execATN performs ATN simulation to compute a predicted alternative based\n// upon the remaining input, but also updates the DFA cache to avoid\n// having to traverse the ATN again for the same input sequence.\n//\n// There are some key conditions we're looking for after computing a new\n// set of ATN configs (proposed DFA state):\n//\n//   - If the set is empty, there is no viable alternative for current symbol\n//   - Does the state uniquely predict an alternative?\n//   - Does the state have a conflict that would prevent us from\n//     putting it on the work list?\n//\n// We also have some key operations to do:\n//\n//   - Add an edge from previous DFA state to potentially NewDFA state, D,\n//   - Upon current symbol but only if adding to work list, which means in all\n//     cases except no viable alternative (and possibly non-greedy decisions?)\n//   - Collecting predicates and adding semantic context to DFA accept states\n//   - adding rule context to context-sensitive DFA accept states\n//   - Consuming an input symbol\n//   - Reporting a conflict\n//   - Reporting an ambiguity\n//   - Reporting a context sensitivity\n//   - Reporting insufficient predicates\n//\n// Cover these cases:\n//\n//   - dead end\n//   - single alt\n//   - single alt + predicates\n//   - conflict\n//   - conflict + predicates\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) execATN(dfa *DFA, s0 *DFAState, input TokenStream, startIndex int, outerContext ParserRuleContext) (int, RecognitionException) {\n\n\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"execATN decision \" + strconv.Itoa(dfa.decision) +\n\t\t\t\", DFA state \" + s0.String() +\n\t\t\t\", LA(1)==\" + p.getLookaheadName(input) +\n\t\t\t\" line \" + strconv.Itoa(input.LT(1).GetLine()) + \":\" + strconv.Itoa(input.LT(1).GetColumn()))\n\t}\n\n\tpreviousD := s0\n\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"s0 = \" + s0.String())\n\t}\n\tt := input.LA(1)\n\tfor { // for more work\n\t\tD := p.getExistingTargetState(previousD, t)\n\t\tif D == nil {\n\t\t\tD = p.computeTargetState(dfa, previousD, t)\n\t\t}\n\t\tif D == ATNSimulatorError {\n\t\t\t// if any configs in previous dipped into outer context, that\n\t\t\t// means that input up to t actually finished entry rule\n\t\t\t// at least for SLL decision. Full LL doesn't dip into outer\n\t\t\t// so don't need special case.\n\t\t\t// We will get an error no matter what so delay until after\n\t\t\t// decision better error message. Also, no reachable target\n\t\t\t// ATN states in SLL implies LL will also get nowhere.\n\t\t\t// If conflict in states that dip out, choose min since we\n\t\t\t// will get error no matter what.\n\t\t\te := p.noViableAlt(input, outerContext, previousD.configs, startIndex)\n\t\t\tinput.Seek(startIndex)\n\t\t\talt := p.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext)\n\t\t\tif alt != ATNInvalidAltNumber {\n\t\t\t\treturn alt, nil\n\t\t\t}\n\t\t\tp.parser.SetError(e)\n\t\t\treturn ATNInvalidAltNumber, e\n\t\t}\n\t\tif D.requiresFullContext && p.predictionMode != PredictionModeSLL {\n\t\t\t// IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n\t\t\tconflictingAlts := D.configs.conflictingAlts\n\t\t\tif D.predicates != nil {\n\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\tfmt.Println(\"DFA state has preds in DFA sim LL fail-over\")\n\t\t\t\t}\n\t\t\t\tconflictIndex := input.Index()\n\t\t\t\tif conflictIndex != startIndex {\n\t\t\t\t\tinput.Seek(startIndex)\n\t\t\t\t}\n\t\t\t\tconflictingAlts = p.evalSemanticContext(D.predicates, outerContext, true)\n\t\t\t\tif conflictingAlts.length() == 1 {\n\t\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\t\tfmt.Println(\"Full LL avoided\")\n\t\t\t\t\t}\n\t\t\t\t\treturn conflictingAlts.minValue(), nil\n\t\t\t\t}\n\t\t\t\tif conflictIndex != startIndex {\n\t\t\t\t\t// restore the index so Reporting the fallback to full\n\t\t\t\t\t// context occurs with the index at the correct spot\n\t\t\t\t\tinput.Seek(conflictIndex)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif runtimeConfig.parserATNSimulatorDFADebug {\n\t\t\t\tfmt.Println(\"ctx sensitive state \" + outerContext.String(nil, nil) + \" in \" + D.String())\n\t\t\t}\n\t\t\tfullCtx := true\n\t\t\ts0Closure := p.computeStartState(dfa.atnStartState, outerContext, fullCtx)\n\t\t\tp.ReportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.Index())\n\t\t\talt, re := p.execATNWithFullContext(dfa, D, s0Closure, input, startIndex, outerContext)\n\t\t\treturn alt, re\n\t\t}\n\t\tif D.isAcceptState {\n\t\t\tif D.predicates == nil {\n\t\t\t\treturn D.prediction, nil\n\t\t\t}\n\t\t\tstopIndex := input.Index()\n\t\t\tinput.Seek(startIndex)\n\t\t\talts := p.evalSemanticContext(D.predicates, outerContext, true)\n\n\t\t\tswitch alts.length() {\n\t\t\tcase 0:\n\t\t\t\treturn ATNInvalidAltNumber, p.noViableAlt(input, outerContext, D.configs, startIndex)\n\t\t\tcase 1:\n\t\t\t\treturn alts.minValue(), nil\n\t\t\tdefault:\n\t\t\t\t// Report ambiguity after predicate evaluation to make sure the correct set of ambig alts is Reported.\n\t\t\t\tp.ReportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs)\n\t\t\t\treturn alts.minValue(), nil\n\t\t\t}\n\t\t}\n\t\tpreviousD = D\n\n\t\tif t != TokenEOF {\n\t\t\tinput.Consume()\n\t\t\tt = input.LA(1)\n\t\t}\n\t}\n}\n\n// Get an existing target state for an edge in the DFA. If the target state\n// for the edge has not yet been computed or is otherwise not available,\n// p method returns {@code nil}.\n//\n// @param previousD The current DFA state\n// @param t The next input symbol\n// @return The existing target DFA state for the given input symbol\n// {@code t}, or {@code nil} if the target state for p edge is not\n// already cached\n\nfunc (p *ParserATNSimulator) getExistingTargetState(previousD *DFAState, t int) *DFAState {\n\tif t+1 < 0 {\n\t\treturn nil\n\t}\n\n\tp.atn.edgeMu.RLock()\n\tdefer p.atn.edgeMu.RUnlock()\n\tedges := previousD.getEdges()\n\tif edges == nil || t+1 >= len(edges) {\n\t\treturn nil\n\t}\n\treturn previousD.getIthEdge(t + 1)\n}\n\n// Compute a target state for an edge in the DFA, and attempt to add the\n// computed state and corresponding edge to the DFA.\n//\n// @param dfa The DFA\n// @param previousD The current DFA state\n// @param t The next input symbol\n//\n// @return The computed target DFA state for the given input symbol\n// {@code t}. If {@code t} does not lead to a valid DFA state, p method\n// returns {@link //ERROR}.\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) computeTargetState(dfa *DFA, previousD *DFAState, t int) *DFAState {\n\treach := p.computeReachSet(previousD.configs, t, false)\n\n\tif reach == nil {\n\t\tp.addDFAEdge(dfa, previousD, t, ATNSimulatorError)\n\t\treturn ATNSimulatorError\n\t}\n\t// create new target state we'll add to DFA after it's complete\n\tD := NewDFAState(-1, reach)\n\n\tpredictedAlt := p.getUniqueAlt(reach)\n\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\taltSubSets := PredictionModegetConflictingAltSubsets(reach)\n\t\tfmt.Println(\"SLL altSubSets=\" + fmt.Sprint(altSubSets) +\n\t\t\t\", previous=\" + previousD.configs.String() +\n\t\t\t\", configs=\" + reach.String() +\n\t\t\t\", predict=\" + strconv.Itoa(predictedAlt) +\n\t\t\t\", allSubsetsConflict=\" +\n\t\t\tfmt.Sprint(PredictionModeallSubsetsConflict(altSubSets)) +\n\t\t\t\", conflictingAlts=\" + p.getConflictingAlts(reach).String())\n\t}\n\tif predictedAlt != ATNInvalidAltNumber {\n\t\t// NO CONFLICT, UNIQUELY PREDICTED ALT\n\t\tD.isAcceptState = true\n\t\tD.configs.uniqueAlt = predictedAlt\n\t\tD.setPrediction(predictedAlt)\n\t} else if PredictionModehasSLLConflictTerminatingPrediction(p.predictionMode, reach) {\n\t\t// MORE THAN ONE VIABLE ALTERNATIVE\n\t\tD.configs.conflictingAlts = p.getConflictingAlts(reach)\n\t\tD.requiresFullContext = true\n\t\t// in SLL-only mode, we will stop at p state and return the minimum alt\n\t\tD.isAcceptState = true\n\t\tD.setPrediction(D.configs.conflictingAlts.minValue())\n\t}\n\tif D.isAcceptState && D.configs.hasSemanticContext {\n\t\tp.predicateDFAState(D, p.atn.getDecisionState(dfa.decision))\n\t\tif D.predicates != nil {\n\t\t\tD.setPrediction(ATNInvalidAltNumber)\n\t\t}\n\t}\n\t// all adds to dfa are done after we've created full D state\n\tD = p.addDFAEdge(dfa, previousD, t, D)\n\treturn D\n}\n\nfunc (p *ParserATNSimulator) predicateDFAState(dfaState *DFAState, decisionState DecisionState) {\n\t// We need to test all predicates, even in DFA states that\n\t// uniquely predict alternative.\n\tnalts := len(decisionState.GetTransitions())\n\t// Update DFA so reach becomes accept state with (predicate,alt)\n\t// pairs if preds found for conflicting alts\n\taltsToCollectPredsFrom := p.getConflictingAltsOrUniqueAlt(dfaState.configs)\n\taltToPred := p.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts)\n\tif altToPred != nil {\n\t\tdfaState.predicates = p.getPredicatePredictions(altsToCollectPredsFrom, altToPred)\n\t\tdfaState.setPrediction(ATNInvalidAltNumber) // make sure we use preds\n\t} else {\n\t\t// There are preds in configs but they might go away\n\t\t// when OR'd together like {p}? || NONE == NONE. If neither\n\t\t// alt has preds, resolve to min alt\n\t\tdfaState.setPrediction(altsToCollectPredsFrom.minValue())\n\t}\n}\n\n// comes back with reach.uniqueAlt set to a valid alt\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0 *ATNConfigSet, input TokenStream, startIndex int, outerContext ParserRuleContext) (int, RecognitionException) {\n\n\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"execATNWithFullContext \" + s0.String())\n\t}\n\n\tfullCtx := true\n\tfoundExactAmbig := false\n\tvar reach *ATNConfigSet\n\tprevious := s0\n\tinput.Seek(startIndex)\n\tt := input.LA(1)\n\tpredictedAlt := -1\n\n\tfor { // for more work\n\t\treach = p.computeReachSet(previous, t, fullCtx)\n\t\tif reach == nil {\n\t\t\t// if any configs in previous dipped into outer context, that\n\t\t\t// means that input up to t actually finished entry rule\n\t\t\t// at least for LL decision. Full LL doesn't dip into outer\n\t\t\t// so don't need special case.\n\t\t\t// We will get an error no matter what so delay until after\n\t\t\t// decision better error message. Also, no reachable target\n\t\t\t// ATN states in SLL implies LL will also get nowhere.\n\t\t\t// If conflict in states that dip out, choose min since we\n\t\t\t// will get error no matter what.\n\t\t\tinput.Seek(startIndex)\n\t\t\talt := p.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext)\n\t\t\tif alt != ATNInvalidAltNumber {\n\t\t\t\treturn alt, nil\n\t\t\t}\n\t\t\treturn alt, p.noViableAlt(input, outerContext, previous, startIndex)\n\t\t}\n\t\taltSubSets := PredictionModegetConflictingAltSubsets(reach)\n\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\tfmt.Println(\"LL altSubSets=\" + fmt.Sprint(altSubSets) + \", predict=\" +\n\t\t\t\tstrconv.Itoa(PredictionModegetUniqueAlt(altSubSets)) + \", resolvesToJustOneViableAlt=\" +\n\t\t\t\tfmt.Sprint(PredictionModeresolvesToJustOneViableAlt(altSubSets)))\n\t\t}\n\t\treach.uniqueAlt = p.getUniqueAlt(reach)\n\t\t// unique prediction?\n\t\tif reach.uniqueAlt != ATNInvalidAltNumber {\n\t\t\tpredictedAlt = reach.uniqueAlt\n\t\t\tbreak\n\t\t}\n\t\tif p.predictionMode != PredictionModeLLExactAmbigDetection {\n\t\t\tpredictedAlt = PredictionModeresolvesToJustOneViableAlt(altSubSets)\n\t\t\tif predictedAlt != ATNInvalidAltNumber {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\t// In exact ambiguity mode, we never try to terminate early.\n\t\t\t// Just keeps scarfing until we know what the conflict is\n\t\t\tif PredictionModeallSubsetsConflict(altSubSets) && PredictionModeallSubsetsEqual(altSubSets) {\n\t\t\t\tfoundExactAmbig = true\n\t\t\t\tpredictedAlt = PredictionModegetSingleViableAlt(altSubSets)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// else there are multiple non-conflicting subsets or\n\t\t\t// we're not sure what the ambiguity is yet.\n\t\t\t// So, keep going.\n\t\t}\n\t\tprevious = reach\n\t\tif t != TokenEOF {\n\t\t\tinput.Consume()\n\t\t\tt = input.LA(1)\n\t\t}\n\t}\n\t// If the configuration set uniquely predicts an alternative,\n\t// without conflict, then we know that it's a full LL decision\n\t// not SLL.\n\tif reach.uniqueAlt != ATNInvalidAltNumber {\n\t\tp.ReportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.Index())\n\t\treturn predictedAlt, nil\n\t}\n\t// We do not check predicates here because we have checked them\n\t// on-the-fly when doing full context prediction.\n\n\t//\n\t// In non-exact ambiguity detection mode, we might\tactually be able to\n\t// detect an exact ambiguity, but I'm not going to spend the cycles\n\t// needed to check. We only emit ambiguity warnings in exact ambiguity\n\t// mode.\n\t//\n\t// For example, we might know that we have conflicting configurations.\n\t// But, that does not mean that there is no way forward without a\n\t// conflict. It's possible to have non-conflicting alt subsets as in:\n\t//\n\t// altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n\t//\n\t// from\n\t//\n\t//    [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n\t//     (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n\t//\n\t// In p case, (17,1,[5 $]) indicates there is some next sequence that\n\t// would resolve p without conflict to alternative 1. Any other viable\n\t// next sequence, however, is associated with a conflict.  We stop\n\t// looking for input because no amount of further lookahead will alter\n\t// the fact that we should predict alternative 1.  We just can't say for\n\t// sure that there is an ambiguity without looking further.\n\n\tp.ReportAmbiguity(dfa, D, startIndex, input.Index(), foundExactAmbig, reach.Alts(), reach)\n\n\treturn predictedAlt, nil\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) computeReachSet(closure *ATNConfigSet, t int, fullCtx bool) *ATNConfigSet {\n\tif p.mergeCache == nil {\n\t\tp.mergeCache = NewJPCMap(ReachSetCollection, \"Merge cache for computeReachSet()\")\n\t}\n\tintermediate := NewATNConfigSet(fullCtx)\n\n\t// Configurations already in a rule stop state indicate reaching the end\n\t// of the decision rule (local context) or end of the start rule (full\n\t// context). Once reached, these configurations are never updated by a\n\t// closure operation, so they are handled separately for the performance\n\t// advantage of having a smaller intermediate set when calling closure.\n\t//\n\t// For full-context reach operations, separate handling is required to\n\t// ensure that the alternative Matching the longest overall sequence is\n\t// chosen when multiple such configurations can Match the input.\n\n\tvar skippedStopStates []*ATNConfig\n\n\t// First figure out where we can reach on input t\n\tfor _, c := range closure.configs {\n\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\tfmt.Println(\"testing \" + p.GetTokenName(t) + \" at \" + c.String())\n\t\t}\n\n\t\tif _, ok := c.GetState().(*RuleStopState); ok {\n\t\t\tif fullCtx || t == TokenEOF {\n\t\t\t\tskippedStopStates = append(skippedStopStates, c)\n\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\tfmt.Println(\"added \" + c.String() + \" to SkippedStopStates\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, trans := range c.GetState().GetTransitions() {\n\t\t\ttarget := p.getReachableTarget(trans, t)\n\t\t\tif target != nil {\n\t\t\t\tcfg := NewATNConfig4(c, target)\n\t\t\t\tintermediate.Add(cfg, p.mergeCache)\n\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\tfmt.Println(\"added \" + cfg.String() + \" to intermediate\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now figure out where the reach operation can take us...\n\tvar reach *ATNConfigSet\n\n\t// This block optimizes the reach operation for intermediate sets which\n\t// trivially indicate a termination state for the overall\n\t// AdaptivePredict operation.\n\t//\n\t// The conditions assume that intermediate\n\t// contains all configurations relevant to the reach set, but p\n\t// condition is not true when one or more configurations have been\n\t// withheld in SkippedStopStates, or when the current symbol is EOF.\n\t//\n\tif skippedStopStates == nil && t != TokenEOF {\n\t\tif len(intermediate.configs) == 1 {\n\t\t\t// Don't pursue the closure if there is just one state.\n\t\t\t// It can only have one alternative just add to result\n\t\t\t// Also don't pursue the closure if there is unique alternative\n\t\t\t// among the configurations.\n\t\t\treach = intermediate\n\t\t} else if p.getUniqueAlt(intermediate) != ATNInvalidAltNumber {\n\t\t\t// Also don't pursue the closure if there is unique alternative\n\t\t\t// among the configurations.\n\t\t\treach = intermediate\n\t\t}\n\t}\n\t// If the reach set could not be trivially determined, perform a closure\n\t// operation on the intermediate set to compute its initial value.\n\t//\n\tif reach == nil {\n\t\treach = NewATNConfigSet(fullCtx)\n\t\tclosureBusy := NewClosureBusy(\"ParserATNSimulator.computeReachSet() make a closureBusy\")\n\t\ttreatEOFAsEpsilon := t == TokenEOF\n\t\tamount := len(intermediate.configs)\n\t\tfor k := 0; k < amount; k++ {\n\t\t\tp.closure(intermediate.configs[k], reach, closureBusy, false, fullCtx, treatEOFAsEpsilon)\n\t\t}\n\t}\n\tif t == TokenEOF {\n\t\t// After consuming EOF no additional input is possible, so we are\n\t\t// only interested in configurations which reached the end of the\n\t\t// decision rule (local context) or end of the start rule (full\n\t\t// context). Update reach to contain only these configurations. This\n\t\t// handles both explicit EOF transitions in the grammar and implicit\n\t\t// EOF transitions following the end of the decision or start rule.\n\t\t//\n\t\t// When reach==intermediate, no closure operation was performed. In\n\t\t// p case, removeAllConfigsNotInRuleStopState needs to check for\n\t\t// reachable rule stop states as well as configurations already in\n\t\t// a rule stop state.\n\t\t//\n\t\t// This is handled before the configurations in SkippedStopStates,\n\t\t// because any configurations potentially added from that list are\n\t\t// already guaranteed to meet this condition whether it's\n\t\t// required.\n\t\t//\n\t\treach = p.removeAllConfigsNotInRuleStopState(reach, reach.Equals(intermediate))\n\t}\n\t// If SkippedStopStates!=nil, then it contains at least one\n\t// configuration. For full-context reach operations, these\n\t// configurations reached the end of the start rule, in which case we\n\t// only add them back to reach if no configuration during the current\n\t// closure operation reached such a state. This ensures AdaptivePredict\n\t// chooses an alternative Matching the longest overall sequence when\n\t// multiple alternatives are viable.\n\t//\n\tif skippedStopStates != nil && ((!fullCtx) || (!PredictionModehasConfigInRuleStopState(reach))) {\n\t\tfor l := 0; l < len(skippedStopStates); l++ {\n\t\t\treach.Add(skippedStopStates[l], p.mergeCache)\n\t\t}\n\t}\n\n\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"computeReachSet \" + closure.String() + \" -> \" + reach.String())\n\t}\n\n\tif len(reach.configs) == 0 {\n\t\treturn nil\n\t}\n\n\treturn reach\n}\n\n// removeAllConfigsNotInRuleStopState returns a configuration set containing only the configurations from\n// configs which are in a [RuleStopState]. If all\n// configurations in configs are already in a rule stop state, this\n// method simply returns configs.\n//\n// When lookToEndOfRule is true, this method uses\n// [ATN].[NextTokens] for each configuration in configs which is\n// not already in a rule stop state to see if a rule stop state is reachable\n// from the configuration via epsilon-only transitions.\n//\n// When lookToEndOfRule is true, this method checks for rule stop states\n// reachable by epsilon-only transitions from each configuration in\n// configs.\n//\n// The func returns configs if all configurations in configs are in a\n// rule stop state, otherwise it returns a new configuration set containing only\n// the configurations from configs which are in a rule stop state\nfunc (p *ParserATNSimulator) removeAllConfigsNotInRuleStopState(configs *ATNConfigSet, lookToEndOfRule bool) *ATNConfigSet {\n\tif PredictionModeallConfigsInRuleStopStates(configs) {\n\t\treturn configs\n\t}\n\tresult := NewATNConfigSet(configs.fullCtx)\n\tfor _, config := range configs.configs {\n\t\tif _, ok := config.GetState().(*RuleStopState); ok {\n\t\t\tresult.Add(config, p.mergeCache)\n\t\t\tcontinue\n\t\t}\n\t\tif lookToEndOfRule && config.GetState().GetEpsilonOnlyTransitions() {\n\t\t\tNextTokens := p.atn.NextTokens(config.GetState(), nil)\n\t\t\tif NextTokens.contains(TokenEpsilon) {\n\t\t\t\tendOfRuleState := p.atn.ruleToStopState[config.GetState().GetRuleIndex()]\n\t\t\t\tresult.Add(NewATNConfig4(config, endOfRuleState), p.mergeCache)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) computeStartState(a ATNState, ctx RuleContext, fullCtx bool) *ATNConfigSet {\n\t// always at least the implicit call to start rule\n\tinitialContext := predictionContextFromRuleContext(p.atn, ctx)\n\tconfigs := NewATNConfigSet(fullCtx)\n\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"computeStartState from ATN state \" + a.String() +\n\t\t\t\" initialContext=\" + initialContext.String())\n\t}\n\n\tfor i := 0; i < len(a.GetTransitions()); i++ {\n\t\ttarget := a.GetTransitions()[i].getTarget()\n\t\tc := NewATNConfig6(target, i+1, initialContext)\n\t\tclosureBusy := NewClosureBusy(\"ParserATNSimulator.computeStartState() make a closureBusy\")\n\t\tp.closure(c, configs, closureBusy, true, fullCtx, false)\n\t}\n\treturn configs\n}\n\n// applyPrecedenceFilter transforms the start state computed by\n// [computeStartState] to the special start state used by a\n// precedence [DFA] for a particular precedence value. The transformation\n// process applies the following changes to the start state's configuration\n// set.\n//\n//  1. Evaluate the precedence predicates for each configuration using\n//     [SemanticContext].evalPrecedence.\n//  2. Remove all configurations which predict an alternative greater than\n//     1, for which another configuration that predicts alternative 1 is in the\n//     same ATN state with the same prediction context.\n//\n// Transformation 2 is valid for the following reasons:\n//\n//   - The closure block cannot contain any epsilon transitions which bypass\n//     the body of the closure, so all states reachable via alternative 1 are\n//     part of the precedence alternatives of the transformed left-recursive\n//     rule.\n//   - The \"primary\" portion of a left recursive rule cannot contain an\n//     epsilon transition, so the only way an alternative other than 1 can exist\n//     in a state that is also reachable via alternative 1 is by nesting calls\n//     to the left-recursive rule, with the outer calls not being at the\n//     preferred precedence level.\n//\n// The prediction context must be considered by this filter to address\n// situations like the following:\n//\n//\tgrammar TA\n//\tprog: statement* EOF\n//\tstatement: letterA | statement letterA 'b'\n//\tletterA: 'a'\n//\n// In the above grammar, the [ATN] state immediately before the token\n// reference 'a' in letterA is reachable from the left edge\n// of both the primary and closure blocks of the left-recursive rule\n// statement. The prediction context associated with each of these\n// configurations distinguishes between them, and prevents the alternative\n// which stepped out to prog, and then back in to statement\n// from being eliminated by the filter.\n//\n// The func returns the transformed configuration set representing the start state\n// for a precedence [DFA] at a particular precedence level (determined by\n// calling [Parser].getPrecedence).\nfunc (p *ParserATNSimulator) applyPrecedenceFilter(configs *ATNConfigSet) *ATNConfigSet {\n\n\tstatesFromAlt1 := make(map[int]*PredictionContext)\n\tconfigSet := NewATNConfigSet(configs.fullCtx)\n\n\tfor _, config := range configs.configs {\n\t\t// handle alt 1 first\n\t\tif config.GetAlt() != 1 {\n\t\t\tcontinue\n\t\t}\n\t\tupdatedContext := config.GetSemanticContext().evalPrecedence(p.parser, p.outerContext)\n\t\tif updatedContext == nil {\n\t\t\t// the configuration was eliminated\n\t\t\tcontinue\n\t\t}\n\t\tstatesFromAlt1[config.GetState().GetStateNumber()] = config.GetContext()\n\t\tif updatedContext != config.GetSemanticContext() {\n\t\t\tconfigSet.Add(NewATNConfig2(config, updatedContext), p.mergeCache)\n\t\t} else {\n\t\t\tconfigSet.Add(config, p.mergeCache)\n\t\t}\n\t}\n\tfor _, config := range configs.configs {\n\n\t\tif config.GetAlt() == 1 {\n\t\t\t// already handled\n\t\t\tcontinue\n\t\t}\n\t\t// In the future, p elimination step could be updated to also\n\t\t// filter the prediction context for alternatives predicting alt>1\n\t\t// (basically a graph subtraction algorithm).\n\t\tif !config.getPrecedenceFilterSuppressed() {\n\t\t\tcontext := statesFromAlt1[config.GetState().GetStateNumber()]\n\t\t\tif context != nil && context.Equals(config.GetContext()) {\n\t\t\t\t// eliminated\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tconfigSet.Add(config, p.mergeCache)\n\t}\n\treturn configSet\n}\n\nfunc (p *ParserATNSimulator) getReachableTarget(trans Transition, ttype int) ATNState {\n\tif trans.Matches(ttype, 0, p.atn.maxTokenType) {\n\t\treturn trans.getTarget()\n\t}\n\n\treturn nil\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) getPredsForAmbigAlts(ambigAlts *BitSet, configs *ATNConfigSet, nalts int) []SemanticContext {\n\n\taltToPred := make([]SemanticContext, nalts+1)\n\tfor _, c := range configs.configs {\n\t\tif ambigAlts.contains(c.GetAlt()) {\n\t\t\taltToPred[c.GetAlt()] = SemanticContextorContext(altToPred[c.GetAlt()], c.GetSemanticContext())\n\t\t}\n\t}\n\tnPredAlts := 0\n\tfor i := 1; i <= nalts; i++ {\n\t\tpred := altToPred[i]\n\t\tif pred == nil {\n\t\t\taltToPred[i] = SemanticContextNone\n\t\t} else if pred != SemanticContextNone {\n\t\t\tnPredAlts++\n\t\t}\n\t}\n\t// unambiguous alts are nil in altToPred\n\tif nPredAlts == 0 {\n\t\taltToPred = nil\n\t}\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"getPredsForAmbigAlts result \" + fmt.Sprint(altToPred))\n\t}\n\treturn altToPred\n}\n\nfunc (p *ParserATNSimulator) getPredicatePredictions(ambigAlts *BitSet, altToPred []SemanticContext) []*PredPrediction {\n\tpairs := make([]*PredPrediction, 0)\n\tcontainsPredicate := false\n\tfor i := 1; i < len(altToPred); i++ {\n\t\tpred := altToPred[i]\n\t\t// un-predicated is indicated by SemanticContextNONE\n\t\tif ambigAlts != nil && ambigAlts.contains(i) {\n\t\t\tpairs = append(pairs, NewPredPrediction(pred, i))\n\t\t}\n\t\tif pred != SemanticContextNone {\n\t\t\tcontainsPredicate = true\n\t\t}\n\t}\n\tif !containsPredicate {\n\t\treturn nil\n\t}\n\treturn pairs\n}\n\n// getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule is used to improve the localization of error messages by\n// choosing an alternative rather than panic a NoViableAltException in particular prediction scenarios where the\n// Error state was reached during [ATN] simulation.\n//\n// The default implementation of this method uses the following\n// algorithm to identify an [ATN] configuration which successfully parsed the\n// decision entry rule. Choosing such an alternative ensures that the\n// [ParserRuleContext] returned by the calling rule will be complete\n// and valid, and the syntax error will be Reported later at a more\n// localized location.\n//\n//   - If a syntactically valid path or paths reach the end of the decision rule, and\n//     they are semantically valid if predicated, return the min associated alt.\n//   - Else, if a semantically invalid but syntactically valid path exist\n//     or paths exist, return the minimum associated alt.\n//   - Otherwise, return [ATNInvalidAltNumber].\n//\n// In some scenarios, the algorithm described above could predict an\n// alternative which will result in a [FailedPredicateException] in\n// the parser. Specifically, this could occur if the only configuration\n// capable of successfully parsing to the end of the decision rule is\n// blocked by a semantic predicate. By choosing this alternative within\n// [AdaptivePredict] instead of panic a [NoViableAltException], the resulting\n// [FailedPredicateException] in the parser will identify the specific\n// predicate which is preventing the parser from successfully parsing the\n// decision rule, which helps developers identify and correct logic errors\n// in semantic predicates.\n//\n// pass in the configs holding ATN configurations which were valid immediately before\n// the ERROR state was reached, outerContext as the initial parser context from the paper\n// or the parser stack at the instant before prediction commences.\n//\n// The func returns the value to return from [AdaptivePredict], or\n// [ATNInvalidAltNumber] if a suitable alternative was not\n// identified and [AdaptivePredict] should report an error instead.\nfunc (p *ParserATNSimulator) getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(configs *ATNConfigSet, outerContext ParserRuleContext) int {\n\tcfgs := p.splitAccordingToSemanticValidity(configs, outerContext)\n\tsemValidConfigs := cfgs[0]\n\tsemInvalidConfigs := cfgs[1]\n\talt := p.GetAltThatFinishedDecisionEntryRule(semValidConfigs)\n\tif alt != ATNInvalidAltNumber { // semantically/syntactically viable path exists\n\t\treturn alt\n\t}\n\t// Is there a syntactically valid path with a failed pred?\n\tif len(semInvalidConfigs.configs) > 0 {\n\t\talt = p.GetAltThatFinishedDecisionEntryRule(semInvalidConfigs)\n\t\tif alt != ATNInvalidAltNumber { // syntactically viable path exists\n\t\t\treturn alt\n\t\t}\n\t}\n\treturn ATNInvalidAltNumber\n}\n\nfunc (p *ParserATNSimulator) GetAltThatFinishedDecisionEntryRule(configs *ATNConfigSet) int {\n\talts := NewIntervalSet()\n\n\tfor _, c := range configs.configs {\n\t\t_, ok := c.GetState().(*RuleStopState)\n\n\t\tif c.GetReachesIntoOuterContext() > 0 || (ok && c.GetContext().hasEmptyPath()) {\n\t\t\talts.addOne(c.GetAlt())\n\t\t}\n\t}\n\tif alts.length() == 0 {\n\t\treturn ATNInvalidAltNumber\n\t}\n\n\treturn alts.first()\n}\n\n// Walk the list of configurations and split them according to\n//  those that have preds evaluating to true/false.  If no pred, assume\n//  true pred and include in succeeded set.  Returns Pair of sets.\n//\n//  Create a NewSet so as not to alter the incoming parameter.\n//\n//  Assumption: the input stream has been restored to the starting point\n//  prediction, which is where predicates need to evaluate.\n\ntype ATNConfigSetPair struct {\n\titem0, item1 *ATNConfigSet\n}\n\nfunc (p *ParserATNSimulator) splitAccordingToSemanticValidity(configs *ATNConfigSet, outerContext ParserRuleContext) []*ATNConfigSet {\n\tsucceeded := NewATNConfigSet(configs.fullCtx)\n\tfailed := NewATNConfigSet(configs.fullCtx)\n\n\tfor _, c := range configs.configs {\n\t\tif c.GetSemanticContext() != SemanticContextNone {\n\t\t\tpredicateEvaluationResult := c.GetSemanticContext().evaluate(p.parser, outerContext)\n\t\t\tif predicateEvaluationResult {\n\t\t\t\tsucceeded.Add(c, nil)\n\t\t\t} else {\n\t\t\t\tfailed.Add(c, nil)\n\t\t\t}\n\t\t} else {\n\t\t\tsucceeded.Add(c, nil)\n\t\t}\n\t}\n\treturn []*ATNConfigSet{succeeded, failed}\n}\n\n// evalSemanticContext looks through a list of predicate/alt pairs, returning alts for the\n// pairs that win. A [SemanticContextNone] predicate indicates an alt containing an\n// un-predicated runtimeConfig which behaves as \"always true.\" If !complete\n// then we stop at the first predicate that evaluates to true. This\n// includes pairs with nil predicates.\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) evalSemanticContext(predPredictions []*PredPrediction, outerContext ParserRuleContext, complete bool) *BitSet {\n\tpredictions := NewBitSet()\n\tfor i := 0; i < len(predPredictions); i++ {\n\t\tpair := predPredictions[i]\n\t\tif pair.pred == SemanticContextNone {\n\t\t\tpredictions.add(pair.alt)\n\t\t\tif !complete {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpredicateEvaluationResult := pair.pred.evaluate(p.parser, outerContext)\n\t\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorDFADebug {\n\t\t\tfmt.Println(\"eval pred \" + pair.String() + \"=\" + fmt.Sprint(predicateEvaluationResult))\n\t\t}\n\t\tif predicateEvaluationResult {\n\t\t\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorDFADebug {\n\t\t\t\tfmt.Println(\"PREDICT \" + fmt.Sprint(pair.alt))\n\t\t\t}\n\t\t\tpredictions.add(pair.alt)\n\t\t\tif !complete {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn predictions\n}\n\nfunc (p *ParserATNSimulator) closure(config *ATNConfig, configs *ATNConfigSet, closureBusy *ClosureBusy, collectPredicates, fullCtx, treatEOFAsEpsilon bool) {\n\tinitialDepth := 0\n\tp.closureCheckingStopState(config, configs, closureBusy, collectPredicates,\n\t\tfullCtx, initialDepth, treatEOFAsEpsilon)\n}\n\nfunc (p *ParserATNSimulator) closureCheckingStopState(config *ATNConfig, configs *ATNConfigSet, closureBusy *ClosureBusy, collectPredicates, fullCtx bool, depth int, treatEOFAsEpsilon bool) {\n\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"closure(\" + config.String() + \")\")\n\t}\n\n\tvar stack []*ATNConfig\n\tvisited := make(map[*ATNConfig]bool)\n\n\tstack = append(stack, config)\n\n\tfor len(stack) > 0 {\n\t\tcurrConfig := stack[len(stack)-1]\n\t\tstack = stack[:len(stack)-1]\n\n\t\tif _, ok := visited[currConfig]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tvisited[currConfig] = true\n\n\t\tif _, ok := currConfig.GetState().(*RuleStopState); ok {\n\t\t\t// We hit rule end. If we have context info, use it\n\t\t\t// run thru all possible stack tops in ctx\n\t\t\tif !currConfig.GetContext().isEmpty() {\n\t\t\t\tfor i := 0; i < currConfig.GetContext().length(); i++ {\n\t\t\t\t\tif currConfig.GetContext().getReturnState(i) == BasePredictionContextEmptyReturnState {\n\t\t\t\t\t\tif fullCtx {\n\t\t\t\t\t\t\tnb := NewATNConfig1(currConfig, currConfig.GetState(), BasePredictionContextEMPTY)\n\t\t\t\t\t\t\tconfigs.Add(nb, p.mergeCache)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// we have no context info, just chase follow links (if greedy)\n\t\t\t\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\t\t\t\tfmt.Println(\"FALLING off rule \" + p.getRuleName(currConfig.GetState().GetRuleIndex()))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tp.closureWork(currConfig, configs, closureBusy, collectPredicates, fullCtx, depth, treatEOFAsEpsilon)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturnState := p.atn.states[currConfig.GetContext().getReturnState(i)]\n\t\t\t\t\tnewContext := currConfig.GetContext().GetParent(i) // \"pop\" return state\n\n\t\t\t\t\tc := NewATNConfig5(returnState, currConfig.GetAlt(), newContext, currConfig.GetSemanticContext())\n\t\t\t\t\t// While we have context to pop back from, we may have\n\t\t\t\t\t// gotten that context AFTER having falling off a rule.\n\t\t\t\t\t// Make sure we track that we are now out of context.\n\t\t\t\t\tc.SetReachesIntoOuterContext(currConfig.GetReachesIntoOuterContext())\n\n\t\t\t\t\tstack = append(stack, c)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else if fullCtx {\n\t\t\t\t// reached end of start rule\n\t\t\t\tconfigs.Add(currConfig, p.mergeCache)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t// else if we have no context info, just chase follow links (if greedy)\n\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\tfmt.Println(\"FALLING off rule \" + p.getRuleName(currConfig.GetState().GetRuleIndex()))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tp.closureWork(currConfig, configs, closureBusy, collectPredicates, fullCtx, depth, treatEOFAsEpsilon)\n\t}\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) closureCheckingStopStateRecursive(config *ATNConfig, configs *ATNConfigSet, closureBusy *ClosureBusy, collectPredicates, fullCtx bool, depth int, treatEOFAsEpsilon bool) {\n\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"closure(\" + config.String() + \")\")\n\t}\n\n\tif _, ok := config.GetState().(*RuleStopState); ok {\n\t\t// We hit rule end. If we have context info, use it\n\t\t// run thru all possible stack tops in ctx\n\t\tif !config.GetContext().isEmpty() {\n\t\t\tfor i := 0; i < config.GetContext().length(); i++ {\n\t\t\t\tif config.GetContext().getReturnState(i) == BasePredictionContextEmptyReturnState {\n\t\t\t\t\tif fullCtx {\n\t\t\t\t\t\tnb := NewATNConfig1(config, config.GetState(), BasePredictionContextEMPTY)\n\t\t\t\t\t\tconfigs.Add(nb, p.mergeCache)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// we have no context info, just chase follow links (if greedy)\n\t\t\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\t\t\tfmt.Println(\"FALLING off rule \" + p.getRuleName(config.GetState().GetRuleIndex()))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp.closureWork(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEOFAsEpsilon)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturnState := p.atn.states[config.GetContext().getReturnState(i)]\n\t\t\t\tnewContext := config.GetContext().GetParent(i) // \"pop\" return state\n\n\t\t\t\tc := NewATNConfig5(returnState, config.GetAlt(), newContext, config.GetSemanticContext())\n\t\t\t\t// While we have context to pop back from, we may have\n\t\t\t\t// gotten that context AFTER having falling off a rule.\n\t\t\t\t// Make sure we track that we are now out of context.\n\t\t\t\tc.SetReachesIntoOuterContext(config.GetReachesIntoOuterContext())\n\t\t\t\tp.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth-1, treatEOFAsEpsilon)\n\t\t\t}\n\t\t\treturn\n\t\t} else if fullCtx {\n\t\t\t// reached end of start rule\n\t\t\tconfigs.Add(config, p.mergeCache)\n\t\t\treturn\n\t\t} else {\n\t\t\t// else if we have no context info, just chase follow links (if greedy)\n\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\tfmt.Println(\"FALLING off rule \" + p.getRuleName(config.GetState().GetRuleIndex()))\n\t\t\t}\n\t\t}\n\t}\n\tp.closureWork(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEOFAsEpsilon)\n}\n\n// Do the actual work of walking epsilon edges\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) closureWork(config *ATNConfig, configs *ATNConfigSet, closureBusy *ClosureBusy, collectPredicates, fullCtx bool, depth int, treatEOFAsEpsilon bool) {\n\tstate := config.GetState()\n\t// optimization\n\tif !state.GetEpsilonOnlyTransitions() {\n\t\tconfigs.Add(config, p.mergeCache)\n\t\t// make sure to not return here, because EOF transitions can act as\n\t\t// both epsilon transitions and non-epsilon transitions.\n\t}\n\tfor i := 0; i < len(state.GetTransitions()); i++ {\n\t\tif i == 0 && p.canDropLoopEntryEdgeInLeftRecursiveRule(config) {\n\t\t\tcontinue\n\t\t}\n\n\t\tt := state.GetTransitions()[i]\n\t\t_, ok := t.(*ActionTransition)\n\t\tcontinueCollecting := collectPredicates && !ok\n\t\tc := p.getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEOFAsEpsilon)\n\t\tif c != nil {\n\t\t\tnewDepth := depth\n\n\t\t\tif _, ok := config.GetState().(*RuleStopState); ok {\n\t\t\t\t// target fell off end of rule mark resulting c as having dipped into outer context\n\t\t\t\t// We can't get here if incoming config was rule stop and we had context\n\t\t\t\t// track how far we dip into outer context.  Might\n\t\t\t\t// come in handy and we avoid evaluating context dependent\n\t\t\t\t// preds if this is > 0.\n\n\t\t\t\tif p.dfa != nil && p.dfa.getPrecedenceDfa() {\n\t\t\t\t\tif t.(*EpsilonTransition).outermostPrecedenceReturn == p.dfa.atnStartState.GetRuleIndex() {\n\t\t\t\t\t\tc.setPrecedenceFilterSuppressed(true)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tc.SetReachesIntoOuterContext(c.GetReachesIntoOuterContext() + 1)\n\n\t\t\t\t_, present := closureBusy.Put(c)\n\t\t\t\tif present {\n\t\t\t\t\t// avoid infinite recursion for right-recursive rules\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconfigs.dipsIntoOuterContext = true // TODO: can remove? only care when we add to set per middle of this method\n\t\t\t\tnewDepth--\n\t\t\t\tif runtimeConfig.parserATNSimulatorDebug {\n\t\t\t\t\tfmt.Println(\"dips into outer ctx: \" + c.String())\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\tif !t.getIsEpsilon() {\n\t\t\t\t\t_, present := closureBusy.Put(c)\n\t\t\t\t\tif present {\n\t\t\t\t\t\t// avoid infinite recursion for EOF* and EOF+\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif _, ok := t.(*RuleTransition); ok {\n\t\t\t\t\t// latch when newDepth goes negative - once we step out of the entry context we can't return\n\t\t\t\t\tif newDepth >= 0 {\n\t\t\t\t\t\tnewDepth++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEOFAsEpsilon)\n\t\t}\n\t}\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) canDropLoopEntryEdgeInLeftRecursiveRule(config *ATNConfig) bool {\n\tif !runtimeConfig.lRLoopEntryBranchOpt {\n\t\treturn false\n\t}\n\n\t_p := config.GetState()\n\n\t// First check to see if we are in StarLoopEntryState generated during\n\t// left-recursion elimination. For efficiency, also check if\n\t// the context has an empty stack case. If so, it would mean\n\t// global FOLLOW so we can't perform optimization\n\tif _p.GetStateType() != ATNStateStarLoopEntry {\n\t\treturn false\n\t}\n\tstartLoop, ok := _p.(*StarLoopEntryState)\n\tif !ok {\n\t\treturn false\n\t}\n\tif !startLoop.precedenceRuleDecision ||\n\t\tconfig.GetContext().isEmpty() ||\n\t\tconfig.GetContext().hasEmptyPath() {\n\t\treturn false\n\t}\n\n\t// Require all return states to return back to the same rule\n\t// that p is in.\n\tnumCtxs := config.GetContext().length()\n\tfor i := 0; i < numCtxs; i++ {\n\t\treturnState := p.atn.states[config.GetContext().getReturnState(i)]\n\t\tif returnState.GetRuleIndex() != _p.GetRuleIndex() {\n\t\t\treturn false\n\t\t}\n\t}\n\tx := _p.GetTransitions()[0].getTarget()\n\tdecisionStartState := x.(BlockStartState)\n\tblockEndStateNum := decisionStartState.getEndState().stateNumber\n\tblockEndState := p.atn.states[blockEndStateNum].(*BlockEndState)\n\n\t// Verify that the top of each stack context leads to loop entry/exit\n\t// state through epsilon edges and w/o leaving rule.\n\n\tfor i := 0; i < numCtxs; i++ { // for each stack context\n\t\treturnStateNumber := config.GetContext().getReturnState(i)\n\t\treturnState := p.atn.states[returnStateNumber]\n\n\t\t// all states must have single outgoing epsilon edge\n\t\tif len(returnState.GetTransitions()) != 1 || !returnState.GetTransitions()[0].getIsEpsilon() {\n\t\t\treturn false\n\t\t}\n\n\t\t// Look for prefix op case like 'not expr', (' type ')' expr\n\t\treturnStateTarget := returnState.GetTransitions()[0].getTarget()\n\t\tif returnState.GetStateType() == ATNStateBlockEnd && returnStateTarget == _p {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Look for 'expr op expr' or case where expr's return state is block end\n\t\t// of (...)* internal block; the block end points to loop back\n\t\t// which points to p but we don't need to check that\n\t\tif returnState == blockEndState {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Look for ternary expr ? expr : expr. The return state points at block end,\n\t\t// which points at loop entry state\n\t\tif returnStateTarget == blockEndState {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Look for complex prefix 'between expr and expr' case where 2nd expr's\n\t\t// return state points at block end state of (...)* internal block\n\t\tif returnStateTarget.GetStateType() == ATNStateBlockEnd &&\n\t\t\tlen(returnStateTarget.GetTransitions()) == 1 &&\n\t\t\treturnStateTarget.GetTransitions()[0].getIsEpsilon() &&\n\t\t\treturnStateTarget.GetTransitions()[0].getTarget() == _p {\n\t\t\tcontinue\n\t\t}\n\n\t\t// anything else ain't conforming\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (p *ParserATNSimulator) getRuleName(index int) string {\n\tif p.parser != nil && index >= 0 {\n\t\treturn p.parser.GetRuleNames()[index]\n\t}\n\tvar sb strings.Builder\n\tsb.Grow(32)\n\n\tsb.WriteString(\"<rule \")\n\tsb.WriteString(strconv.FormatInt(int64(index), 10))\n\tsb.WriteByte('>')\n\treturn sb.String()\n}\n\nfunc (p *ParserATNSimulator) getEpsilonTarget(config *ATNConfig, t Transition, collectPredicates, inContext, fullCtx, treatEOFAsEpsilon bool) *ATNConfig {\n\n\tswitch t.getSerializationType() {\n\tcase TransitionRULE:\n\t\treturn p.ruleTransition(config, t.(*RuleTransition))\n\tcase TransitionPRECEDENCE:\n\t\treturn p.precedenceTransition(config, t.(*PrecedencePredicateTransition), collectPredicates, inContext, fullCtx)\n\tcase TransitionPREDICATE:\n\t\treturn p.predTransition(config, t.(*PredicateTransition), collectPredicates, inContext, fullCtx)\n\tcase TransitionACTION:\n\t\treturn p.actionTransition(config, t.(*ActionTransition))\n\tcase TransitionEPSILON:\n\t\treturn NewATNConfig4(config, t.getTarget())\n\tcase TransitionATOM, TransitionRANGE, TransitionSET:\n\t\t// EOF transitions act like epsilon transitions after the first EOF\n\t\t// transition is traversed\n\t\tif treatEOFAsEpsilon {\n\t\t\tif t.Matches(TokenEOF, 0, 1) {\n\t\t\t\treturn NewATNConfig4(config, t.getTarget())\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn nil\n\t}\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) actionTransition(config *ATNConfig, t *ActionTransition) *ATNConfig {\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"ACTION edge \" + strconv.Itoa(t.ruleIndex) + \":\" + strconv.Itoa(t.actionIndex))\n\t}\n\treturn NewATNConfig4(config, t.getTarget())\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) precedenceTransition(config *ATNConfig,\n\tpt *PrecedencePredicateTransition, collectPredicates, inContext, fullCtx bool) *ATNConfig {\n\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"PRED (collectPredicates=\" + fmt.Sprint(collectPredicates) + \") \" +\n\t\t\tstrconv.Itoa(pt.precedence) + \">=_p, ctx dependent=true\")\n\t\tif p.parser != nil {\n\t\t\tfmt.Println(\"context surrounding pred is \" + fmt.Sprint(p.parser.GetRuleInvocationStack(nil)))\n\t\t}\n\t}\n\tvar c *ATNConfig\n\tif collectPredicates && inContext {\n\t\tif fullCtx {\n\t\t\t// In full context mode, we can evaluate predicates on-the-fly\n\t\t\t// during closure, which dramatically reduces the size of\n\t\t\t// the runtimeConfig sets. It also obviates the need to test predicates\n\t\t\t// later during conflict resolution.\n\t\t\tcurrentPosition := p.input.Index()\n\t\t\tp.input.Seek(p.startIndex)\n\t\t\tpredSucceeds := pt.getPredicate().evaluate(p.parser, p.outerContext)\n\t\t\tp.input.Seek(currentPosition)\n\t\t\tif predSucceeds {\n\t\t\t\tc = NewATNConfig4(config, pt.getTarget()) // no pred context\n\t\t\t}\n\t\t} else {\n\t\t\tnewSemCtx := SemanticContextandContext(config.GetSemanticContext(), pt.getPredicate())\n\t\t\tc = NewATNConfig3(config, pt.getTarget(), newSemCtx)\n\t\t}\n\t} else {\n\t\tc = NewATNConfig4(config, pt.getTarget())\n\t}\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"runtimeConfig from pred transition=\" + c.String())\n\t}\n\treturn c\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) predTransition(config *ATNConfig, pt *PredicateTransition, collectPredicates, inContext, fullCtx bool) *ATNConfig {\n\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"PRED (collectPredicates=\" + fmt.Sprint(collectPredicates) + \") \" + strconv.Itoa(pt.ruleIndex) +\n\t\t\t\":\" + strconv.Itoa(pt.predIndex) + \", ctx dependent=\" + fmt.Sprint(pt.isCtxDependent))\n\t\tif p.parser != nil {\n\t\t\tfmt.Println(\"context surrounding pred is \" + fmt.Sprint(p.parser.GetRuleInvocationStack(nil)))\n\t\t}\n\t}\n\tvar c *ATNConfig\n\tif collectPredicates && (!pt.isCtxDependent || inContext) {\n\t\tif fullCtx {\n\t\t\t// In full context mode, we can evaluate predicates on-the-fly\n\t\t\t// during closure, which dramatically reduces the size of\n\t\t\t// the config sets. It also obviates the need to test predicates\n\t\t\t// later during conflict resolution.\n\t\t\tcurrentPosition := p.input.Index()\n\t\t\tp.input.Seek(p.startIndex)\n\t\t\tpredSucceeds := pt.getPredicate().evaluate(p.parser, p.outerContext)\n\t\t\tp.input.Seek(currentPosition)\n\t\t\tif predSucceeds {\n\t\t\t\tc = NewATNConfig4(config, pt.getTarget()) // no pred context\n\t\t\t}\n\t\t} else {\n\t\t\tnewSemCtx := SemanticContextandContext(config.GetSemanticContext(), pt.getPredicate())\n\t\t\tc = NewATNConfig3(config, pt.getTarget(), newSemCtx)\n\t\t}\n\t} else {\n\t\tc = NewATNConfig4(config, pt.getTarget())\n\t}\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"config from pred transition=\" + c.String())\n\t}\n\treturn c\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) ruleTransition(config *ATNConfig, t *RuleTransition) *ATNConfig {\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"CALL rule \" + p.getRuleName(t.getTarget().GetRuleIndex()) + \", ctx=\" + config.GetContext().String())\n\t}\n\treturnState := t.followState\n\tnewContext := SingletonBasePredictionContextCreate(config.GetContext(), returnState.GetStateNumber())\n\treturn NewATNConfig1(config, t.getTarget(), newContext)\n}\n\nfunc (p *ParserATNSimulator) getConflictingAlts(configs *ATNConfigSet) *BitSet {\n\taltsets := PredictionModegetConflictingAltSubsets(configs)\n\treturn PredictionModeGetAlts(altsets)\n}\n\n// getConflictingAltsOrUniqueAlt Sam pointed out a problem with the previous definition, v3, of\n// ambiguous states. If we have another state associated with conflicting\n// alternatives, we should keep going. For example, the following grammar\n//\n//\ts : (ID | ID ID?) ;\n//\n// When the [ATN] simulation reaches the state before ;, it has a [DFA]\n// state that looks like:\n//\n//\t[12|1|[], 6|2|[], 12|2|[]].\n//\n// Naturally\n//\n//\t12|1|[] and 12|2|[]\n//\n// conflict, but we cannot stop processing this node\n// because alternative to has another way to continue, via\n//\n//\t[6|2|[]].\n//\n// The key is that we have a single state that has config's only associated\n// with a single alternative, 2, and crucially the state transitions\n// among the configurations are all non-epsilon transitions. That means\n// we don't consider any conflicts that include alternative 2. So, we\n// ignore the conflict between alts 1 and 2. We ignore a set of\n// conflicting alts when there is an intersection with an alternative\n// associated with a single alt state in the state config-list map.\n//\n// It's also the case that we might have two conflicting configurations but\n// also a 3rd non-conflicting configuration for a different alternative:\n//\n//\t[1|1|[], 1|2|[], 8|3|[]].\n//\n// This can come about from grammar:\n//\n//\ta : A | A | A B\n//\n// After Matching input A, we reach the stop state for rule A, state 1.\n// State 8 is the state right before B. Clearly alternatives 1 and 2\n// conflict and no amount of further lookahead will separate the two.\n// However, alternative 3 will be able to continue, so we do not\n// stop working on this state.\n//\n// In the previous example, we're concerned\n// with states associated with the conflicting alternatives. Here alt\n// 3 is not associated with the conflicting configs, but since we can continue\n// looking for input reasonably, I don't declare the state done. We\n// ignore a set of conflicting alts when we have an alternative\n// that we still need to pursue.\nfunc (p *ParserATNSimulator) getConflictingAltsOrUniqueAlt(configs *ATNConfigSet) *BitSet {\n\tvar conflictingAlts *BitSet\n\tif configs.uniqueAlt != ATNInvalidAltNumber {\n\t\tconflictingAlts = NewBitSet()\n\t\tconflictingAlts.add(configs.uniqueAlt)\n\t} else {\n\t\tconflictingAlts = configs.conflictingAlts\n\t}\n\treturn conflictingAlts\n}\n\nfunc (p *ParserATNSimulator) GetTokenName(t int) string {\n\tif t == TokenEOF {\n\t\treturn \"EOF\"\n\t}\n\n\tif p.parser != nil && p.parser.GetLiteralNames() != nil && t < len(p.parser.GetLiteralNames()) {\n\t\treturn p.parser.GetLiteralNames()[t] + \"<\" + strconv.Itoa(t) + \">\"\n\t}\n\n\tif p.parser != nil && p.parser.GetLiteralNames() != nil && t < len(p.parser.GetSymbolicNames()) {\n\t\treturn p.parser.GetSymbolicNames()[t] + \"<\" + strconv.Itoa(t) + \">\"\n\t}\n\n\treturn strconv.Itoa(t)\n}\n\nfunc (p *ParserATNSimulator) getLookaheadName(input TokenStream) string {\n\treturn p.GetTokenName(input.LA(1))\n}\n\n// Used for debugging in [AdaptivePredict] around [execATN], but I cut\n// it out for clarity now that alg. works well. We can leave this\n// \"dead\" code for a bit.\nfunc (p *ParserATNSimulator) dumpDeadEndConfigs(_ *NoViableAltException) {\n\n\tpanic(\"Not implemented\")\n\n\t//    fmt.Println(\"dead end configs: \")\n\t//    var decs = nvae.deadEndConfigs\n\t//\n\t//    for i:=0; i<len(decs); i++ {\n\t//\n\t//    \tc := decs[i]\n\t//        var trans = \"no edges\"\n\t//        if (len(c.state.GetTransitions())>0) {\n\t//            var t = c.state.GetTransitions()[0]\n\t//            if t2, ok := t.(*AtomTransition); ok {\n\t//                trans = \"Atom \"+ p.GetTokenName(t2.label)\n\t//            } else if t3, ok := t.(SetTransition); ok {\n\t//                _, ok := t.(*NotSetTransition)\n\t//\n\t//                var s string\n\t//                if (ok){\n\t//                    s = \"~\"\n\t//                }\n\t//\n\t//                trans = s + \"Set \" + t3.set\n\t//            }\n\t//        }\n\t//        fmt.Errorf(c.String(p.parser, true) + \":\" + trans)\n\t//    }\n}\n\nfunc (p *ParserATNSimulator) noViableAlt(input TokenStream, outerContext ParserRuleContext, configs *ATNConfigSet, startIndex int) *NoViableAltException {\n\treturn NewNoViableAltException(p.parser, input, input.Get(startIndex), input.LT(1), configs, outerContext)\n}\n\nfunc (p *ParserATNSimulator) getUniqueAlt(configs *ATNConfigSet) int {\n\talt := ATNInvalidAltNumber\n\tfor _, c := range configs.configs {\n\t\tif alt == ATNInvalidAltNumber {\n\t\t\talt = c.GetAlt() // found first alt\n\t\t} else if c.GetAlt() != alt {\n\t\t\treturn ATNInvalidAltNumber\n\t\t}\n\t}\n\treturn alt\n}\n\n// Add an edge to the DFA, if possible. This method calls\n// {@link //addDFAState} to ensure the {@code to} state is present in the\n// DFA. If {@code from} is {@code nil}, or if {@code t} is outside the\n// range of edges that can be represented in the DFA tables, p method\n// returns without adding the edge to the DFA.\n//\n// <p>If {@code to} is {@code nil}, p method returns {@code nil}.\n// Otherwise, p method returns the {@link DFAState} returned by calling\n// {@link //addDFAState} for the {@code to} state.</p>\n//\n// @param dfa The DFA\n// @param from The source state for the edge\n// @param t The input symbol\n// @param to The target state for the edge\n//\n// @return If {@code to} is {@code nil}, p method returns {@code nil}\n// otherwise p method returns the result of calling {@link //addDFAState}\n// on {@code to}\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) addDFAEdge(dfa *DFA, from *DFAState, t int, to *DFAState) *DFAState {\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tfmt.Println(\"EDGE \" + from.String() + \" -> \" + to.String() + \" upon \" + p.GetTokenName(t))\n\t}\n\tif to == nil {\n\t\treturn nil\n\t}\n\tp.atn.stateMu.Lock()\n\tto = p.addDFAState(dfa, to) // used existing if possible not incoming\n\tp.atn.stateMu.Unlock()\n\tif from == nil || t < -1 || t > p.atn.maxTokenType {\n\t\treturn to\n\t}\n\tp.atn.edgeMu.Lock()\n\tif from.getEdges() == nil {\n\t\tfrom.setEdges(make([]*DFAState, p.atn.maxTokenType+1+1))\n\t}\n\tfrom.setIthEdge(t+1, to) // connect\n\tp.atn.edgeMu.Unlock()\n\n\tif runtimeConfig.parserATNSimulatorDebug {\n\t\tvar names []string\n\t\tif p.parser != nil {\n\t\t\tnames = p.parser.GetLiteralNames()\n\t\t}\n\n\t\tfmt.Println(\"DFA=\\n\" + dfa.String(names, nil))\n\t}\n\treturn to\n}\n\n// addDFAState adds state D to the [DFA] if it is not already present, and returns\n// the actual instance stored in the [DFA]. If a state equivalent to D\n// is already in the [DFA], the existing state is returned. Otherwise, this\n// method returns D after adding it to the [DFA].\n//\n// If D is [ATNSimulatorError], this method returns [ATNSimulatorError] and\n// does not change the DFA.\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) addDFAState(dfa *DFA, d *DFAState) *DFAState {\n\tif d == ATNSimulatorError {\n\t\treturn d\n\t}\n\n\texisting, present := dfa.Get(d)\n\tif present {\n\t\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\t\tfmt.Print(\"addDFAState \" + d.String() + \" exists\")\n\t\t}\n\t\treturn existing\n\t}\n\n\t// The state will be added if not already there or we will be given back the existing state struct\n\t// if it is present.\n\t//\n\td.stateNumber = dfa.Len()\n\tif !d.configs.readOnly {\n\t\td.configs.OptimizeConfigs(&p.BaseATNSimulator)\n\t\td.configs.readOnly = true\n\t\td.configs.configLookup = nil\n\t}\n\tdfa.Put(d)\n\n\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"addDFAState new \" + d.String())\n\t}\n\n\treturn d\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) ReportAttemptingFullContext(dfa *DFA, conflictingAlts *BitSet, configs *ATNConfigSet, startIndex, stopIndex int) {\n\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorRetryDebug {\n\t\tinterval := NewInterval(startIndex, stopIndex+1)\n\t\tfmt.Println(\"ReportAttemptingFullContext decision=\" + strconv.Itoa(dfa.decision) + \":\" + configs.String() +\n\t\t\t\", input=\" + p.parser.GetTokenStream().GetTextFromInterval(interval))\n\t}\n\tif p.parser != nil {\n\t\tp.parser.GetErrorListenerDispatch().ReportAttemptingFullContext(p.parser, dfa, startIndex, stopIndex, conflictingAlts, configs)\n\t}\n}\n\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) ReportContextSensitivity(dfa *DFA, prediction int, configs *ATNConfigSet, startIndex, stopIndex int) {\n\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorRetryDebug {\n\t\tinterval := NewInterval(startIndex, stopIndex+1)\n\t\tfmt.Println(\"ReportContextSensitivity decision=\" + strconv.Itoa(dfa.decision) + \":\" + configs.String() +\n\t\t\t\", input=\" + p.parser.GetTokenStream().GetTextFromInterval(interval))\n\t}\n\tif p.parser != nil {\n\t\tp.parser.GetErrorListenerDispatch().ReportContextSensitivity(p.parser, dfa, startIndex, stopIndex, prediction, configs)\n\t}\n}\n\n// ReportAmbiguity reports and ambiguity in the parse, which shows that the parser will explore a different route.\n//\n// If context-sensitive parsing, we know it's an ambiguity not a conflict or error, but we can report it to the developer\n// so that they can see that this is happening and can take action if they want to.\n//\n//goland:noinspection GoBoolExpressions\nfunc (p *ParserATNSimulator) ReportAmbiguity(dfa *DFA, _ *DFAState, startIndex, stopIndex int,\n\texact bool, ambigAlts *BitSet, configs *ATNConfigSet) {\n\tif runtimeConfig.parserATNSimulatorDebug || runtimeConfig.parserATNSimulatorRetryDebug {\n\t\tinterval := NewInterval(startIndex, stopIndex+1)\n\t\tfmt.Println(\"ReportAmbiguity \" + ambigAlts.String() + \":\" + configs.String() +\n\t\t\t\", input=\" + p.parser.GetTokenStream().GetTextFromInterval(interval))\n\t}\n\tif p.parser != nil {\n\t\tp.parser.GetErrorListenerDispatch().ReportAmbiguity(p.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs)\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/parser_rule_context.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"reflect\"\n\t\"strconv\"\n)\n\ntype ParserRuleContext interface {\n\tRuleContext\n\n\tSetException(RecognitionException)\n\n\tAddTokenNode(token Token) *TerminalNodeImpl\n\tAddErrorNode(badToken Token) *ErrorNodeImpl\n\n\tEnterRule(listener ParseTreeListener)\n\tExitRule(listener ParseTreeListener)\n\n\tSetStart(Token)\n\tGetStart() Token\n\n\tSetStop(Token)\n\tGetStop() Token\n\n\tAddChild(child RuleContext) RuleContext\n\tRemoveLastChild()\n}\n\ntype BaseParserRuleContext struct {\n\tparentCtx     RuleContext\n\tinvokingState int\n\tRuleIndex     int\n\n\tstart, stop Token\n\texception   RecognitionException\n\tchildren    []Tree\n}\n\nfunc NewBaseParserRuleContext(parent ParserRuleContext, invokingStateNumber int) *BaseParserRuleContext {\n\tprc := new(BaseParserRuleContext)\n\tInitBaseParserRuleContext(prc, parent, invokingStateNumber)\n\treturn prc\n}\n\nfunc InitBaseParserRuleContext(prc *BaseParserRuleContext, parent ParserRuleContext, invokingStateNumber int) {\n\t// What context invoked b rule?\n\tprc.parentCtx = parent\n\n\t// What state invoked the rule associated with b context?\n\t// The \"return address\" is the followState of invokingState\n\t// If parent is nil, b should be -1.\n\tif parent == nil {\n\t\tprc.invokingState = -1\n\t} else {\n\t\tprc.invokingState = invokingStateNumber\n\t}\n\n\tprc.RuleIndex = -1\n\t// * If we are debugging or building a parse tree for a Visitor,\n\t// we need to track all of the tokens and rule invocations associated\n\t// with prc rule's context. This is empty for parsing w/o tree constr.\n\t// operation because we don't the need to track the details about\n\t// how we parse prc rule.\n\t// /\n\tprc.children = nil\n\tprc.start = nil\n\tprc.stop = nil\n\t// The exception that forced prc rule to return. If the rule successfully\n\t// completed, prc is {@code nil}.\n\tprc.exception = nil\n}\n\nfunc (prc *BaseParserRuleContext) SetException(e RecognitionException) {\n\tprc.exception = e\n}\n\nfunc (prc *BaseParserRuleContext) GetChildren() []Tree {\n\treturn prc.children\n}\n\nfunc (prc *BaseParserRuleContext) CopyFrom(ctx *BaseParserRuleContext) {\n\t// from RuleContext\n\tprc.parentCtx = ctx.parentCtx\n\tprc.invokingState = ctx.invokingState\n\tprc.children = nil\n\tprc.start = ctx.start\n\tprc.stop = ctx.stop\n}\n\nfunc (prc *BaseParserRuleContext) GetText() string {\n\tif prc.GetChildCount() == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar s string\n\tfor _, child := range prc.children {\n\t\ts += child.(ParseTree).GetText()\n\t}\n\n\treturn s\n}\n\n// EnterRule is called when any rule is entered.\nfunc (prc *BaseParserRuleContext) EnterRule(_ ParseTreeListener) {\n}\n\n// ExitRule is called when any rule is exited.\nfunc (prc *BaseParserRuleContext) ExitRule(_ ParseTreeListener) {\n}\n\n// * Does not set parent link other add methods do that\nfunc (prc *BaseParserRuleContext) addTerminalNodeChild(child TerminalNode) TerminalNode {\n\tif prc.children == nil {\n\t\tprc.children = make([]Tree, 0)\n\t}\n\tif child == nil {\n\t\tpanic(\"Child may not be null\")\n\t}\n\tprc.children = append(prc.children, child)\n\treturn child\n}\n\nfunc (prc *BaseParserRuleContext) AddChild(child RuleContext) RuleContext {\n\tif prc.children == nil {\n\t\tprc.children = make([]Tree, 0)\n\t}\n\tif child == nil {\n\t\tpanic(\"Child may not be null\")\n\t}\n\tprc.children = append(prc.children, child)\n\treturn child\n}\n\n// RemoveLastChild is used by [EnterOuterAlt] to toss out a [RuleContext] previously added as\n// we entered a rule. If we have a label, we will need to remove\n// the generic ruleContext object.\nfunc (prc *BaseParserRuleContext) RemoveLastChild() {\n\tif prc.children != nil && len(prc.children) > 0 {\n\t\tprc.children = prc.children[0 : len(prc.children)-1]\n\t}\n}\n\nfunc (prc *BaseParserRuleContext) AddTokenNode(token Token) *TerminalNodeImpl {\n\n\tnode := NewTerminalNodeImpl(token)\n\tprc.addTerminalNodeChild(node)\n\tnode.parentCtx = prc\n\treturn node\n\n}\n\nfunc (prc *BaseParserRuleContext) AddErrorNode(badToken Token) *ErrorNodeImpl {\n\tnode := NewErrorNodeImpl(badToken)\n\tprc.addTerminalNodeChild(node)\n\tnode.parentCtx = prc\n\treturn node\n}\n\nfunc (prc *BaseParserRuleContext) GetChild(i int) Tree {\n\tif prc.children != nil && len(prc.children) >= i {\n\t\treturn prc.children[i]\n\t}\n\n\treturn nil\n}\n\nfunc (prc *BaseParserRuleContext) GetChildOfType(i int, childType reflect.Type) RuleContext {\n\tif childType == nil {\n\t\treturn prc.GetChild(i).(RuleContext)\n\t}\n\n\tfor j := 0; j < len(prc.children); j++ {\n\t\tchild := prc.children[j]\n\t\tif reflect.TypeOf(child) == childType {\n\t\t\tif i == 0 {\n\t\t\t\treturn child.(RuleContext)\n\t\t\t}\n\n\t\t\ti--\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (prc *BaseParserRuleContext) ToStringTree(ruleNames []string, recog Recognizer) string {\n\treturn TreesStringTree(prc, ruleNames, recog)\n}\n\nfunc (prc *BaseParserRuleContext) GetRuleContext() RuleContext {\n\treturn prc\n}\n\nfunc (prc *BaseParserRuleContext) Accept(visitor ParseTreeVisitor) interface{} {\n\treturn visitor.VisitChildren(prc)\n}\n\nfunc (prc *BaseParserRuleContext) SetStart(t Token) {\n\tprc.start = t\n}\n\nfunc (prc *BaseParserRuleContext) GetStart() Token {\n\treturn prc.start\n}\n\nfunc (prc *BaseParserRuleContext) SetStop(t Token) {\n\tprc.stop = t\n}\n\nfunc (prc *BaseParserRuleContext) GetStop() Token {\n\treturn prc.stop\n}\n\nfunc (prc *BaseParserRuleContext) GetToken(ttype int, i int) TerminalNode {\n\n\tfor j := 0; j < len(prc.children); j++ {\n\t\tchild := prc.children[j]\n\t\tif c2, ok := child.(TerminalNode); ok {\n\t\t\tif c2.GetSymbol().GetTokenType() == ttype {\n\t\t\t\tif i == 0 {\n\t\t\t\t\treturn c2\n\t\t\t\t}\n\n\t\t\t\ti--\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (prc *BaseParserRuleContext) GetTokens(ttype int) []TerminalNode {\n\tif prc.children == nil {\n\t\treturn make([]TerminalNode, 0)\n\t}\n\n\ttokens := make([]TerminalNode, 0)\n\n\tfor j := 0; j < len(prc.children); j++ {\n\t\tchild := prc.children[j]\n\t\tif tchild, ok := child.(TerminalNode); ok {\n\t\t\tif tchild.GetSymbol().GetTokenType() == ttype {\n\t\t\t\ttokens = append(tokens, tchild)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tokens\n}\n\nfunc (prc *BaseParserRuleContext) GetPayload() interface{} {\n\treturn prc\n}\n\nfunc (prc *BaseParserRuleContext) getChild(ctxType reflect.Type, i int) RuleContext {\n\tif prc.children == nil || i < 0 || i >= len(prc.children) {\n\t\treturn nil\n\t}\n\n\tj := -1 // what element have we found with ctxType?\n\tfor _, o := range prc.children {\n\n\t\tchildType := reflect.TypeOf(o)\n\n\t\tif childType.Implements(ctxType) {\n\t\t\tj++\n\t\t\tif j == i {\n\t\t\t\treturn o.(RuleContext)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// Go lacks generics, so it's not possible for us to return the child with the correct type, but we do\n// check for convertibility\n\nfunc (prc *BaseParserRuleContext) GetTypedRuleContext(ctxType reflect.Type, i int) RuleContext {\n\treturn prc.getChild(ctxType, i)\n}\n\nfunc (prc *BaseParserRuleContext) GetTypedRuleContexts(ctxType reflect.Type) []RuleContext {\n\tif prc.children == nil {\n\t\treturn make([]RuleContext, 0)\n\t}\n\n\tcontexts := make([]RuleContext, 0)\n\n\tfor _, child := range prc.children {\n\t\tchildType := reflect.TypeOf(child)\n\n\t\tif childType.ConvertibleTo(ctxType) {\n\t\t\tcontexts = append(contexts, child.(RuleContext))\n\t\t}\n\t}\n\treturn contexts\n}\n\nfunc (prc *BaseParserRuleContext) GetChildCount() int {\n\tif prc.children == nil {\n\t\treturn 0\n\t}\n\n\treturn len(prc.children)\n}\n\nfunc (prc *BaseParserRuleContext) GetSourceInterval() Interval {\n\tif prc.start == nil || prc.stop == nil {\n\t\treturn TreeInvalidInterval\n\t}\n\n\treturn NewInterval(prc.start.GetTokenIndex(), prc.stop.GetTokenIndex())\n}\n\n//need to manage circular dependencies, so export now\n\n// Print out a whole tree, not just a node, in LISP format\n// (root child1 .. childN). Print just a node if b is a leaf.\n//\n\nfunc (prc *BaseParserRuleContext) String(ruleNames []string, stop RuleContext) string {\n\n\tvar p ParserRuleContext = prc\n\ts := \"[\"\n\tfor p != nil && p != stop {\n\t\tif ruleNames == nil {\n\t\t\tif !p.IsEmpty() {\n\t\t\t\ts += strconv.Itoa(p.GetInvokingState())\n\t\t\t}\n\t\t} else {\n\t\t\tri := p.GetRuleIndex()\n\t\t\tvar ruleName string\n\t\t\tif ri >= 0 && ri < len(ruleNames) {\n\t\t\t\truleName = ruleNames[ri]\n\t\t\t} else {\n\t\t\t\truleName = strconv.Itoa(ri)\n\t\t\t}\n\t\t\ts += ruleName\n\t\t}\n\t\tif p.GetParent() != nil && (ruleNames != nil || !p.GetParent().(ParserRuleContext).IsEmpty()) {\n\t\t\ts += \" \"\n\t\t}\n\t\tpi := p.GetParent()\n\t\tif pi != nil {\n\t\t\tp = pi.(ParserRuleContext)\n\t\t} else {\n\t\t\tp = nil\n\t\t}\n\t}\n\ts += \"]\"\n\treturn s\n}\n\nfunc (prc *BaseParserRuleContext) SetParent(v Tree) {\n\tif v == nil {\n\t\tprc.parentCtx = nil\n\t} else {\n\t\tprc.parentCtx = v.(RuleContext)\n\t}\n}\n\nfunc (prc *BaseParserRuleContext) GetInvokingState() int {\n\treturn prc.invokingState\n}\n\nfunc (prc *BaseParserRuleContext) SetInvokingState(t int) {\n\tprc.invokingState = t\n}\n\nfunc (prc *BaseParserRuleContext) GetRuleIndex() int {\n\treturn prc.RuleIndex\n}\n\nfunc (prc *BaseParserRuleContext) GetAltNumber() int {\n\treturn ATNInvalidAltNumber\n}\n\nfunc (prc *BaseParserRuleContext) SetAltNumber(_ int) {}\n\n// IsEmpty returns true if the context of b is empty.\n//\n// A context is empty if there is no invoking state, meaning nobody calls\n// current context.\nfunc (prc *BaseParserRuleContext) IsEmpty() bool {\n\treturn prc.invokingState == -1\n}\n\n// GetParent returns the combined text of all child nodes. This method only considers\n// tokens which have been added to the parse tree.\n//\n// Since tokens on hidden channels (e.g. whitespace or comments) are not\n// added to the parse trees, they will not appear in the output of this\n// method.\nfunc (prc *BaseParserRuleContext) GetParent() Tree {\n\treturn prc.parentCtx\n}\n\nvar ParserRuleContextEmpty = NewBaseParserRuleContext(nil, -1)\n\ntype InterpreterRuleContext interface {\n\tParserRuleContext\n}\n\ntype BaseInterpreterRuleContext struct {\n\t*BaseParserRuleContext\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewBaseInterpreterRuleContext(parent BaseInterpreterRuleContext, invokingStateNumber, ruleIndex int) *BaseInterpreterRuleContext {\n\n\tprc := new(BaseInterpreterRuleContext)\n\n\tprc.BaseParserRuleContext = NewBaseParserRuleContext(parent, invokingStateNumber)\n\n\tprc.RuleIndex = ruleIndex\n\n\treturn prc\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/prediction_context.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nvar _emptyPredictionContextHash int\n\nfunc init() {\n\t_emptyPredictionContextHash = murmurInit(1)\n\t_emptyPredictionContextHash = murmurFinish(_emptyPredictionContextHash, 0)\n}\n\nfunc calculateEmptyHash() int {\n\treturn _emptyPredictionContextHash\n}\n\nconst (\n\t// BasePredictionContextEmptyReturnState represents {@code $} in an array in full context mode, $\n\t// doesn't mean wildcard:\n\t//\n\t//   $ + x = [$,x]\n\t//\n\t// Here,\n\t//\n\t//   $ = EmptyReturnState\n\tBasePredictionContextEmptyReturnState = 0x7FFFFFFF\n)\n\n// TODO: JI These are meant to be atomics - this does not seem to match the Java runtime here\n//\n//goland:noinspection GoUnusedGlobalVariable\nvar (\n\tBasePredictionContextglobalNodeCount = 1\n\tBasePredictionContextid              = BasePredictionContextglobalNodeCount\n)\n\nconst (\n\tPredictionContextEmpty = iota\n\tPredictionContextSingleton\n\tPredictionContextArray\n)\n\n// PredictionContext is a go idiomatic implementation of PredictionContext that does not rty to\n// emulate inheritance from Java, and can be used without an interface definition. An interface\n// is not required because no user code will ever need to implement this interface.\ntype PredictionContext struct {\n\tcachedHash   int\n\tpcType       int\n\tparentCtx    *PredictionContext\n\treturnState  int\n\tparents      []*PredictionContext\n\treturnStates []int\n}\n\nfunc NewEmptyPredictionContext() *PredictionContext {\n\tnep := &PredictionContext{}\n\tnep.cachedHash = calculateEmptyHash()\n\tnep.pcType = PredictionContextEmpty\n\tnep.returnState = BasePredictionContextEmptyReturnState\n\treturn nep\n}\n\nfunc NewBaseSingletonPredictionContext(parent *PredictionContext, returnState int) *PredictionContext {\n\tpc := &PredictionContext{}\n\tpc.pcType = PredictionContextSingleton\n\tpc.returnState = returnState\n\tpc.parentCtx = parent\n\tif parent != nil {\n\t\tpc.cachedHash = calculateHash(parent, returnState)\n\t} else {\n\t\tpc.cachedHash = calculateEmptyHash()\n\t}\n\treturn pc\n}\n\nfunc SingletonBasePredictionContextCreate(parent *PredictionContext, returnState int) *PredictionContext {\n\tif returnState == BasePredictionContextEmptyReturnState && parent == nil {\n\t\t// someone can pass in the bits of an array ctx that mean $\n\t\treturn BasePredictionContextEMPTY\n\t}\n\treturn NewBaseSingletonPredictionContext(parent, returnState)\n}\n\nfunc NewArrayPredictionContext(parents []*PredictionContext, returnStates []int) *PredictionContext {\n\t// Parent can be nil only if full ctx mode and we make an array\n\t// from {@link //EMPTY} and non-empty. We merge {@link //EMPTY} by using\n\t// nil parent and\n\t// returnState == {@link //EmptyReturnState}.\n\thash := murmurInit(1)\n\tfor _, parent := range parents {\n\t\thash = murmurUpdate(hash, parent.Hash())\n\t}\n\tfor _, returnState := range returnStates {\n\t\thash = murmurUpdate(hash, returnState)\n\t}\n\thash = murmurFinish(hash, len(parents)<<1)\n\n\tnec := &PredictionContext{}\n\tnec.cachedHash = hash\n\tnec.pcType = PredictionContextArray\n\tnec.parents = parents\n\tnec.returnStates = returnStates\n\treturn nec\n}\n\nfunc (p *PredictionContext) Hash() int {\n\treturn p.cachedHash\n}\n\nfunc (p *PredictionContext) Equals(other Collectable[*PredictionContext]) bool {\n\tif p == other {\n\t\treturn true\n\t}\n\tswitch p.pcType {\n\tcase PredictionContextEmpty:\n\t\totherP := other.(*PredictionContext)\n\t\treturn other == nil || otherP == nil || otherP.isEmpty()\n\tcase PredictionContextSingleton:\n\t\treturn p.SingletonEquals(other)\n\tcase PredictionContextArray:\n\t\treturn p.ArrayEquals(other)\n\t}\n\treturn false\n}\n\nfunc (p *PredictionContext) ArrayEquals(o Collectable[*PredictionContext]) bool {\n\tif o == nil {\n\t\treturn false\n\t}\n\tother := o.(*PredictionContext)\n\tif other == nil || other.pcType != PredictionContextArray {\n\t\treturn false\n\t}\n\tif p.cachedHash != other.Hash() {\n\t\treturn false // can't be same if hash is different\n\t}\n\n\t// Must compare the actual array elements and not just the array address\n\t//\n\treturn intSlicesEqual(p.returnStates, other.returnStates) &&\n\t\tpcSliceEqual(p.parents, other.parents)\n}\n\nfunc (p *PredictionContext) SingletonEquals(other Collectable[*PredictionContext]) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\totherP := other.(*PredictionContext)\n\tif otherP == nil || otherP.pcType != PredictionContextSingleton {\n\t\treturn false\n\t}\n\n\tif p.cachedHash != otherP.Hash() {\n\t\treturn false // Can't be same if hash is different\n\t}\n\n\tif p.returnState != otherP.getReturnState(0) {\n\t\treturn false\n\t}\n\n\t// Both parents must be nil if one is\n\tif p.parentCtx == nil {\n\t\treturn otherP.parentCtx == nil\n\t}\n\n\treturn p.parentCtx.Equals(otherP.parentCtx)\n}\n\nfunc (p *PredictionContext) GetParent(i int) *PredictionContext {\n\tswitch p.pcType {\n\tcase PredictionContextEmpty:\n\t\treturn nil\n\tcase PredictionContextSingleton:\n\t\treturn p.parentCtx\n\tcase PredictionContextArray:\n\t\treturn p.parents[i]\n\t}\n\treturn nil\n}\n\nfunc (p *PredictionContext) getReturnState(i int) int {\n\tswitch p.pcType {\n\tcase PredictionContextArray:\n\t\treturn p.returnStates[i]\n\tdefault:\n\t\treturn p.returnState\n\t}\n}\n\nfunc (p *PredictionContext) GetReturnStates() []int {\n\tswitch p.pcType {\n\tcase PredictionContextArray:\n\t\treturn p.returnStates\n\tdefault:\n\t\treturn []int{p.returnState}\n\t}\n}\n\nfunc (p *PredictionContext) length() int {\n\tswitch p.pcType {\n\tcase PredictionContextArray:\n\t\treturn len(p.returnStates)\n\tdefault:\n\t\treturn 1\n\t}\n}\n\nfunc (p *PredictionContext) hasEmptyPath() bool {\n\tswitch p.pcType {\n\tcase PredictionContextSingleton:\n\t\treturn p.returnState == BasePredictionContextEmptyReturnState\n\t}\n\treturn p.getReturnState(p.length()-1) == BasePredictionContextEmptyReturnState\n}\n\nfunc (p *PredictionContext) String() string {\n\tswitch p.pcType {\n\tcase PredictionContextEmpty:\n\t\treturn \"$\"\n\tcase PredictionContextSingleton:\n\t\tvar up string\n\n\t\tif p.parentCtx == nil {\n\t\t\tup = \"\"\n\t\t} else {\n\t\t\tup = p.parentCtx.String()\n\t\t}\n\n\t\tif len(up) == 0 {\n\t\t\tif p.returnState == BasePredictionContextEmptyReturnState {\n\t\t\t\treturn \"$\"\n\t\t\t}\n\n\t\t\treturn strconv.Itoa(p.returnState)\n\t\t}\n\n\t\treturn strconv.Itoa(p.returnState) + \" \" + up\n\tcase PredictionContextArray:\n\t\tif p.isEmpty() {\n\t\t\treturn \"[]\"\n\t\t}\n\n\t\ts := \"[\"\n\t\tfor i := 0; i < len(p.returnStates); i++ {\n\t\t\tif i > 0 {\n\t\t\t\ts = s + \", \"\n\t\t\t}\n\t\t\tif p.returnStates[i] == BasePredictionContextEmptyReturnState {\n\t\t\t\ts = s + \"$\"\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts = s + strconv.Itoa(p.returnStates[i])\n\t\t\tif !p.parents[i].isEmpty() {\n\t\t\t\ts = s + \" \" + p.parents[i].String()\n\t\t\t} else {\n\t\t\t\ts = s + \"nil\"\n\t\t\t}\n\t\t}\n\t\treturn s + \"]\"\n\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc (p *PredictionContext) isEmpty() bool {\n\tswitch p.pcType {\n\tcase PredictionContextEmpty:\n\t\treturn true\n\tcase PredictionContextArray:\n\t\t// since EmptyReturnState can only appear in the last position, we\n\t\t// don't need to verify that size==1\n\t\treturn p.returnStates[0] == BasePredictionContextEmptyReturnState\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (p *PredictionContext) Type() int {\n\treturn p.pcType\n}\n\nfunc calculateHash(parent *PredictionContext, returnState int) int {\n\th := murmurInit(1)\n\th = murmurUpdate(h, parent.Hash())\n\th = murmurUpdate(h, returnState)\n\treturn murmurFinish(h, 2)\n}\n\n// Convert a {@link RuleContext} tree to a {@link BasePredictionContext} graph.\n// Return {@link //EMPTY} if {@code outerContext} is empty or nil.\n// /\nfunc predictionContextFromRuleContext(a *ATN, outerContext RuleContext) *PredictionContext {\n\tif outerContext == nil {\n\t\touterContext = ParserRuleContextEmpty\n\t}\n\t// if we are in RuleContext of start rule, s, then BasePredictionContext\n\t// is EMPTY. Nobody called us. (if we are empty, return empty)\n\tif outerContext.GetParent() == nil || outerContext == ParserRuleContextEmpty {\n\t\treturn BasePredictionContextEMPTY\n\t}\n\t// If we have a parent, convert it to a BasePredictionContext graph\n\tparent := predictionContextFromRuleContext(a, outerContext.GetParent().(RuleContext))\n\tstate := a.states[outerContext.GetInvokingState()]\n\ttransition := state.GetTransitions()[0]\n\n\treturn SingletonBasePredictionContextCreate(parent, transition.(*RuleTransition).followState.GetStateNumber())\n}\n\nfunc merge(a, b *PredictionContext, rootIsWildcard bool, mergeCache *JPCMap) *PredictionContext {\n\n\t// Share same graph if both same\n\t//\n\tif a == b || a.Equals(b) {\n\t\treturn a\n\t}\n\n\tif a.pcType == PredictionContextSingleton && b.pcType == PredictionContextSingleton {\n\t\treturn mergeSingletons(a, b, rootIsWildcard, mergeCache)\n\t}\n\t// At least one of a or b is array\n\t// If one is $ and rootIsWildcard, return $ as wildcard\n\tif rootIsWildcard {\n\t\tif a.isEmpty() {\n\t\t\treturn a\n\t\t}\n\t\tif b.isEmpty() {\n\t\t\treturn b\n\t\t}\n\t}\n\n\t// Convert either Singleton or Empty to arrays, so that we can merge them\n\t//\n\tara := convertToArray(a)\n\tarb := convertToArray(b)\n\treturn mergeArrays(ara, arb, rootIsWildcard, mergeCache)\n}\n\nfunc convertToArray(pc *PredictionContext) *PredictionContext {\n\tswitch pc.Type() {\n\tcase PredictionContextEmpty:\n\t\treturn NewArrayPredictionContext([]*PredictionContext{}, []int{})\n\tcase PredictionContextSingleton:\n\t\treturn NewArrayPredictionContext([]*PredictionContext{pc.GetParent(0)}, []int{pc.getReturnState(0)})\n\tdefault:\n\t\t// Already an array\n\t}\n\treturn pc\n}\n\n// mergeSingletons merges two Singleton [PredictionContext] instances.\n//\n// Stack tops equal, parents merge is same return left graph.\n// <embed src=\"images/SingletonMerge_SameRootSamePar.svg\"\n// type=\"image/svg+xml\"/></p>\n//\n// <p>Same stack top, parents differ merge parents giving array node, then\n// remainders of those graphs. A new root node is created to point to the\n// merged parents.<br>\n// <embed src=\"images/SingletonMerge_SameRootDiffPar.svg\"\n// type=\"image/svg+xml\"/></p>\n//\n// <p>Different stack tops pointing to same parent. Make array node for the\n// root where both element in the root point to the same (original)\n// parent.<br>\n// <embed src=\"images/SingletonMerge_DiffRootSamePar.svg\"\n// type=\"image/svg+xml\"/></p>\n//\n// <p>Different stack tops pointing to different parents. Make array node for\n// the root where each element points to the corresponding original\n// parent.<br>\n// <embed src=\"images/SingletonMerge_DiffRootDiffPar.svg\"\n// type=\"image/svg+xml\"/></p>\n//\n// @param a the first {@link SingletonBasePredictionContext}\n// @param b the second {@link SingletonBasePredictionContext}\n// @param rootIsWildcard {@code true} if this is a local-context merge,\n// otherwise false to indicate a full-context merge\n// @param mergeCache\n// /\nfunc mergeSingletons(a, b *PredictionContext, rootIsWildcard bool, mergeCache *JPCMap) *PredictionContext {\n\tif mergeCache != nil {\n\t\tprevious, present := mergeCache.Get(a, b)\n\t\tif present {\n\t\t\treturn previous\n\t\t}\n\t\tprevious, present = mergeCache.Get(b, a)\n\t\tif present {\n\t\t\treturn previous\n\t\t}\n\t}\n\n\trootMerge := mergeRoot(a, b, rootIsWildcard)\n\tif rootMerge != nil {\n\t\tif mergeCache != nil {\n\t\t\tmergeCache.Put(a, b, rootMerge)\n\t\t}\n\t\treturn rootMerge\n\t}\n\tif a.returnState == b.returnState {\n\t\tparent := merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache)\n\t\t// if parent is same as existing a or b parent or reduced to a parent,\n\t\t// return it\n\t\tif parent.Equals(a.parentCtx) {\n\t\t\treturn a // ax + bx = ax, if a=b\n\t\t}\n\t\tif parent.Equals(b.parentCtx) {\n\t\t\treturn b // ax + bx = bx, if a=b\n\t\t}\n\t\t// else: ax + ay = a'[x,y]\n\t\t// merge parents x and y, giving array node with x,y then remainders\n\t\t// of those graphs. dup a, a' points at merged array.\n\t\t// New joined parent so create a new singleton pointing to it, a'\n\t\tspc := SingletonBasePredictionContextCreate(parent, a.returnState)\n\t\tif mergeCache != nil {\n\t\t\tmergeCache.Put(a, b, spc)\n\t\t}\n\t\treturn spc\n\t}\n\t// a != b payloads differ\n\t// see if we can collapse parents due to $+x parents if local ctx\n\tvar singleParent *PredictionContext\n\tif a.Equals(b) || (a.parentCtx != nil && a.parentCtx.Equals(b.parentCtx)) { // ax +\n\t\t// bx =\n\t\t// [a,b]x\n\t\tsingleParent = a.parentCtx\n\t}\n\tif singleParent != nil { // parents are same\n\t\t// sort payloads and use same parent\n\t\tpayloads := []int{a.returnState, b.returnState}\n\t\tif a.returnState > b.returnState {\n\t\t\tpayloads[0] = b.returnState\n\t\t\tpayloads[1] = a.returnState\n\t\t}\n\t\tparents := []*PredictionContext{singleParent, singleParent}\n\t\tapc := NewArrayPredictionContext(parents, payloads)\n\t\tif mergeCache != nil {\n\t\t\tmergeCache.Put(a, b, apc)\n\t\t}\n\t\treturn apc\n\t}\n\t// parents differ and can't merge them. Just pack together\n\t// into array can't merge.\n\t// ax + by = [ax,by]\n\tpayloads := []int{a.returnState, b.returnState}\n\tparents := []*PredictionContext{a.parentCtx, b.parentCtx}\n\tif a.returnState > b.returnState { // sort by payload\n\t\tpayloads[0] = b.returnState\n\t\tpayloads[1] = a.returnState\n\t\tparents = []*PredictionContext{b.parentCtx, a.parentCtx}\n\t}\n\tapc := NewArrayPredictionContext(parents, payloads)\n\tif mergeCache != nil {\n\t\tmergeCache.Put(a, b, apc)\n\t}\n\treturn apc\n}\n\n// Handle case where at least one of {@code a} or {@code b} is\n// {@link //EMPTY}. In the following diagrams, the symbol {@code $} is used\n// to represent {@link //EMPTY}.\n//\n// <h2>Local-Context Merges</h2>\n//\n// <p>These local-context merge operations are used when {@code rootIsWildcard}\n// is true.</p>\n//\n// <p>{@link //EMPTY} is superset of any graph return {@link //EMPTY}.<br>\n// <embed src=\"images/LocalMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n//\n// <p>{@link //EMPTY} and anything is {@code //EMPTY}, so merged parent is\n// {@code //EMPTY} return left graph.<br>\n// <embed src=\"images/LocalMerge_EmptyParent.svg\" type=\"image/svg+xml\"/></p>\n//\n// <p>Special case of last merge if local context.<br>\n// <embed src=\"images/LocalMerge_DiffRoots.svg\" type=\"image/svg+xml\"/></p>\n//\n// <h2>Full-Context Merges</h2>\n//\n// <p>These full-context merge operations are used when {@code rootIsWildcard}\n// is false.</p>\n//\n// <p><embed src=\"images/FullMerge_EmptyRoots.svg\" type=\"image/svg+xml\"/></p>\n//\n// <p>Must keep all contexts {@link //EMPTY} in array is a special value (and\n// nil parent).<br>\n// <embed src=\"images/FullMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n//\n// <p><embed src=\"images/FullMerge_SameRoot.svg\" type=\"image/svg+xml\"/></p>\n//\n// @param a the first {@link SingletonBasePredictionContext}\n// @param b the second {@link SingletonBasePredictionContext}\n// @param rootIsWildcard {@code true} if this is a local-context merge,\n// otherwise false to indicate a full-context merge\n// /\nfunc mergeRoot(a, b *PredictionContext, rootIsWildcard bool) *PredictionContext {\n\tif rootIsWildcard {\n\t\tif a.pcType == PredictionContextEmpty {\n\t\t\treturn BasePredictionContextEMPTY // // + b =//\n\t\t}\n\t\tif b.pcType == PredictionContextEmpty {\n\t\t\treturn BasePredictionContextEMPTY // a +// =//\n\t\t}\n\t} else {\n\t\tif a.isEmpty() && b.isEmpty() {\n\t\t\treturn BasePredictionContextEMPTY // $ + $ = $\n\t\t} else if a.isEmpty() { // $ + x = [$,x]\n\t\t\tpayloads := []int{b.getReturnState(-1), BasePredictionContextEmptyReturnState}\n\t\t\tparents := []*PredictionContext{b.GetParent(-1), nil}\n\t\t\treturn NewArrayPredictionContext(parents, payloads)\n\t\t} else if b.isEmpty() { // x + $ = [$,x] ($ is always first if present)\n\t\t\tpayloads := []int{a.getReturnState(-1), BasePredictionContextEmptyReturnState}\n\t\t\tparents := []*PredictionContext{a.GetParent(-1), nil}\n\t\t\treturn NewArrayPredictionContext(parents, payloads)\n\t\t}\n\t}\n\treturn nil\n}\n\n// Merge two {@link ArrayBasePredictionContext} instances.\n//\n// <p>Different tops, different parents.<br>\n// <embed src=\"images/ArrayMerge_DiffTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n//\n// <p>Shared top, same parents.<br>\n// <embed src=\"images/ArrayMerge_ShareTopSamePar.svg\" type=\"image/svg+xml\"/></p>\n//\n// <p>Shared top, different parents.<br>\n// <embed src=\"images/ArrayMerge_ShareTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n//\n// <p>Shared top, all shared parents.<br>\n// <embed src=\"images/ArrayMerge_ShareTopSharePar.svg\"\n// type=\"image/svg+xml\"/></p>\n//\n// <p>Equal tops, merge parents and reduce top to\n// {@link SingletonBasePredictionContext}.<br>\n// <embed src=\"images/ArrayMerge_EqualTop.svg\" type=\"image/svg+xml\"/></p>\n//\n//goland:noinspection GoBoolExpressions\nfunc mergeArrays(a, b *PredictionContext, rootIsWildcard bool, mergeCache *JPCMap) *PredictionContext {\n\tif mergeCache != nil {\n\t\tprevious, present := mergeCache.Get(a, b)\n\t\tif present {\n\t\t\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\t\t\tfmt.Println(\"mergeArrays a=\" + a.String() + \",b=\" + b.String() + \" -> previous\")\n\t\t\t}\n\t\t\treturn previous\n\t\t}\n\t\tprevious, present = mergeCache.Get(b, a)\n\t\tif present {\n\t\t\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\t\t\tfmt.Println(\"mergeArrays a=\" + a.String() + \",b=\" + b.String() + \" -> previous\")\n\t\t\t}\n\t\t\treturn previous\n\t\t}\n\t}\n\t// merge sorted payloads a + b => M\n\ti := 0 // walks a\n\tj := 0 // walks b\n\tk := 0 // walks target M array\n\n\tmergedReturnStates := make([]int, len(a.returnStates)+len(b.returnStates))\n\tmergedParents := make([]*PredictionContext, len(a.returnStates)+len(b.returnStates))\n\t// walk and merge to yield mergedParents, mergedReturnStates\n\tfor i < len(a.returnStates) && j < len(b.returnStates) {\n\t\taParent := a.parents[i]\n\t\tbParent := b.parents[j]\n\t\tif a.returnStates[i] == b.returnStates[j] {\n\t\t\t// same payload (stack tops are equal), must yield merged singleton\n\t\t\tpayload := a.returnStates[i]\n\t\t\t// $+$ = $\n\t\t\tbothDollars := payload == BasePredictionContextEmptyReturnState && aParent == nil && bParent == nil\n\t\t\taxAX := aParent != nil && bParent != nil && aParent.Equals(bParent) // ax+ax\n\t\t\t// ->\n\t\t\t// ax\n\t\t\tif bothDollars || axAX {\n\t\t\t\tmergedParents[k] = aParent // choose left\n\t\t\t\tmergedReturnStates[k] = payload\n\t\t\t} else { // ax+ay -> a'[x,y]\n\t\t\t\tmergedParent := merge(aParent, bParent, rootIsWildcard, mergeCache)\n\t\t\t\tmergedParents[k] = mergedParent\n\t\t\t\tmergedReturnStates[k] = payload\n\t\t\t}\n\t\t\ti++ // hop over left one as usual\n\t\t\tj++ // but also Skip one in right side since we merge\n\t\t} else if a.returnStates[i] < b.returnStates[j] { // copy a[i] to M\n\t\t\tmergedParents[k] = aParent\n\t\t\tmergedReturnStates[k] = a.returnStates[i]\n\t\t\ti++\n\t\t} else { // b > a, copy b[j] to M\n\t\t\tmergedParents[k] = bParent\n\t\t\tmergedReturnStates[k] = b.returnStates[j]\n\t\t\tj++\n\t\t}\n\t\tk++\n\t}\n\t// copy over any payloads remaining in either array\n\tif i < len(a.returnStates) {\n\t\tfor p := i; p < len(a.returnStates); p++ {\n\t\t\tmergedParents[k] = a.parents[p]\n\t\t\tmergedReturnStates[k] = a.returnStates[p]\n\t\t\tk++\n\t\t}\n\t} else {\n\t\tfor p := j; p < len(b.returnStates); p++ {\n\t\t\tmergedParents[k] = b.parents[p]\n\t\t\tmergedReturnStates[k] = b.returnStates[p]\n\t\t\tk++\n\t\t}\n\t}\n\t// trim merged if we combined a few that had same stack tops\n\tif k < len(mergedParents) { // write index < last position trim\n\t\tif k == 1 { // for just one merged element, return singleton top\n\t\t\tpc := SingletonBasePredictionContextCreate(mergedParents[0], mergedReturnStates[0])\n\t\t\tif mergeCache != nil {\n\t\t\t\tmergeCache.Put(a, b, pc)\n\t\t\t}\n\t\t\treturn pc\n\t\t}\n\t\tmergedParents = mergedParents[0:k]\n\t\tmergedReturnStates = mergedReturnStates[0:k]\n\t}\n\n\tM := NewArrayPredictionContext(mergedParents, mergedReturnStates)\n\n\t// if we created same array as a or b, return that instead\n\t// TODO: JI track whether this is possible above during merge sort for speed and possibly avoid an allocation\n\tif M.Equals(a) {\n\t\tif mergeCache != nil {\n\t\t\tmergeCache.Put(a, b, a)\n\t\t}\n\t\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\t\tfmt.Println(\"mergeArrays a=\" + a.String() + \",b=\" + b.String() + \" -> a\")\n\t\t}\n\t\treturn a\n\t}\n\tif M.Equals(b) {\n\t\tif mergeCache != nil {\n\t\t\tmergeCache.Put(a, b, b)\n\t\t}\n\t\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\t\tfmt.Println(\"mergeArrays a=\" + a.String() + \",b=\" + b.String() + \" -> b\")\n\t\t}\n\t\treturn b\n\t}\n\tcombineCommonParents(&mergedParents)\n\n\tif mergeCache != nil {\n\t\tmergeCache.Put(a, b, M)\n\t}\n\tif runtimeConfig.parserATNSimulatorTraceATNSim {\n\t\tfmt.Println(\"mergeArrays a=\" + a.String() + \",b=\" + b.String() + \" -> \" + M.String())\n\t}\n\treturn M\n}\n\n// Make pass over all M parents and merge any Equals() ones.\n// Note that we pass a pointer to the slice as we want to modify it in place.\n//\n//goland:noinspection GoUnusedFunction\nfunc combineCommonParents(parents *[]*PredictionContext) {\n\tuniqueParents := NewJStore[*PredictionContext, Comparator[*PredictionContext]](pContextEqInst, PredictionContextCollection, \"combineCommonParents for PredictionContext\")\n\n\tfor p := 0; p < len(*parents); p++ {\n\t\tparent := (*parents)[p]\n\t\t_, _ = uniqueParents.Put(parent)\n\t}\n\tfor q := 0; q < len(*parents); q++ {\n\t\tpc, _ := uniqueParents.Get((*parents)[q])\n\t\t(*parents)[q] = pc\n\t}\n}\n\nfunc getCachedBasePredictionContext(context *PredictionContext, contextCache *PredictionContextCache, visited *VisitRecord) *PredictionContext {\n\tif context.isEmpty() {\n\t\treturn context\n\t}\n\texisting, present := visited.Get(context)\n\tif present {\n\t\treturn existing\n\t}\n\n\texisting, present = contextCache.Get(context)\n\tif present {\n\t\tvisited.Put(context, existing)\n\t\treturn existing\n\t}\n\tchanged := false\n\tparents := make([]*PredictionContext, context.length())\n\tfor i := 0; i < len(parents); i++ {\n\t\tparent := getCachedBasePredictionContext(context.GetParent(i), contextCache, visited)\n\t\tif changed || !parent.Equals(context.GetParent(i)) {\n\t\t\tif !changed {\n\t\t\t\tparents = make([]*PredictionContext, context.length())\n\t\t\t\tfor j := 0; j < context.length(); j++ {\n\t\t\t\t\tparents[j] = context.GetParent(j)\n\t\t\t\t}\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t\tparents[i] = parent\n\t\t}\n\t}\n\tif !changed {\n\t\tcontextCache.add(context)\n\t\tvisited.Put(context, context)\n\t\treturn context\n\t}\n\tvar updated *PredictionContext\n\tif len(parents) == 0 {\n\t\tupdated = BasePredictionContextEMPTY\n\t} else if len(parents) == 1 {\n\t\tupdated = SingletonBasePredictionContextCreate(parents[0], context.getReturnState(0))\n\t} else {\n\t\tupdated = NewArrayPredictionContext(parents, context.GetReturnStates())\n\t}\n\tcontextCache.add(updated)\n\tvisited.Put(updated, updated)\n\tvisited.Put(context, updated)\n\n\treturn updated\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/prediction_context_cache.go",
    "content": "package antlr\n\nvar BasePredictionContextEMPTY = &PredictionContext{\n\tcachedHash:  calculateEmptyHash(),\n\tpcType:      PredictionContextEmpty,\n\treturnState: BasePredictionContextEmptyReturnState,\n}\n\n// PredictionContextCache is Used to cache [PredictionContext] objects. It is used for the shared\n// context cash associated with contexts in DFA states. This cache\n// can be used for both lexers and parsers.\ntype PredictionContextCache struct {\n\tcache *JMap[*PredictionContext, *PredictionContext, Comparator[*PredictionContext]]\n}\n\nfunc NewPredictionContextCache() *PredictionContextCache {\n\treturn &PredictionContextCache{\n\t\tcache: NewJMap[*PredictionContext, *PredictionContext, Comparator[*PredictionContext]](pContextEqInst, PredictionContextCacheCollection, \"NewPredictionContextCache()\"),\n\t}\n}\n\n// Add a context to the cache and return it. If the context already exists,\n// return that one instead and do not add a new context to the cache.\n// Protect shared cache from unsafe thread access.\nfunc (p *PredictionContextCache) add(ctx *PredictionContext) *PredictionContext {\n\tif ctx.isEmpty() {\n\t\treturn BasePredictionContextEMPTY\n\t}\n\n\t// Put will return the existing entry if it is present (note this is done via Equals, not whether it is\n\t// the same pointer), otherwise it will add the new entry and return that.\n\t//\n\texisting, present := p.cache.Get(ctx)\n\tif present {\n\t\treturn existing\n\t}\n\tp.cache.Put(ctx, ctx)\n\treturn ctx\n}\n\nfunc (p *PredictionContextCache) Get(ctx *PredictionContext) (*PredictionContext, bool) {\n\tpc, exists := p.cache.Get(ctx)\n\treturn pc, exists\n}\n\nfunc (p *PredictionContextCache) length() int {\n\treturn p.cache.Len()\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/prediction_mode.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// This enumeration defines the prediction modes available in ANTLR 4 along with\n// utility methods for analyzing configuration sets for conflicts and/or\n// ambiguities.\n\nconst (\n\t// PredictionModeSLL represents the SLL(*) prediction mode.\n\t// This prediction mode ignores the current\n\t// parser context when making predictions. This is the fastest prediction\n\t// mode, and provides correct results for many grammars. This prediction\n\t// mode is more powerful than the prediction mode provided by ANTLR 3, but\n\t// may result in syntax errors for grammar and input combinations which are\n\t// not SLL.\n\t//\n\t// When using this prediction mode, the parser will either return a correct\n\t// parse tree (i.e. the same parse tree that would be returned with the\n\t// [PredictionModeLL] prediction mode), or it will Report a syntax error. If a\n\t// syntax error is encountered when using the SLL prediction mode,\n\t// it may be due to either an actual syntax error in the input or indicate\n\t// that the particular combination of grammar and input requires the more\n\t// powerful LL prediction abilities to complete successfully.\n\t//\n\t// This prediction mode does not provide any guarantees for prediction\n\t// behavior for syntactically-incorrect inputs.\n\t//\n\tPredictionModeSLL = 0\n\n\t// PredictionModeLL represents the LL(*) prediction mode.\n\t// This prediction mode allows the current parser\n\t// context to be used for resolving SLL conflicts that occur during\n\t// prediction. This is the fastest prediction mode that guarantees correct\n\t// parse results for all combinations of grammars with syntactically correct\n\t// inputs.\n\t//\n\t// When using this prediction mode, the parser will make correct decisions\n\t// for all syntactically-correct grammar and input combinations. However, in\n\t// cases where the grammar is truly ambiguous this prediction mode might not\n\t// report a precise answer for exactly which alternatives are\n\t// ambiguous.\n\t//\n\t// This prediction mode does not provide any guarantees for prediction\n\t// behavior for syntactically-incorrect inputs.\n\t//\n\tPredictionModeLL = 1\n\n\t// PredictionModeLLExactAmbigDetection represents the LL(*) prediction mode\n\t// with exact ambiguity detection.\n\t//\n\t// In addition to the correctness guarantees provided by the [PredictionModeLL] prediction mode,\n\t// this prediction mode instructs the prediction algorithm to determine the\n\t// complete and exact set of ambiguous alternatives for every ambiguous\n\t// decision encountered while parsing.\n\t//\n\t// This prediction mode may be used for diagnosing ambiguities during\n\t// grammar development. Due to the performance overhead of calculating sets\n\t// of ambiguous alternatives, this prediction mode should be avoided when\n\t// the exact results are not necessary.\n\t//\n\t// This prediction mode does not provide any guarantees for prediction\n\t// behavior for syntactically-incorrect inputs.\n\t//\n\tPredictionModeLLExactAmbigDetection = 2\n)\n\n// PredictionModehasSLLConflictTerminatingPrediction computes the SLL prediction termination condition.\n//\n// This method computes the SLL prediction termination condition for both of\n// the following cases:\n//\n//   - The usual SLL+LL fallback upon SLL conflict\n//   - Pure SLL without LL fallback\n//\n// # Combined SLL+LL Parsing\n//\n// When LL-fallback is enabled upon SLL conflict, correct predictions are\n// ensured regardless of how the termination condition is computed by this\n// method. Due to the substantially higher cost of LL prediction, the\n// prediction should only fall back to LL when the additional lookahead\n// cannot lead to a unique SLL prediction.\n//\n// Assuming combined SLL+LL parsing, an SLL configuration set with only\n// conflicting subsets should fall back to full LL, even if the\n// configuration sets don't resolve to the same alternative, e.g.\n//\n//\t{1,2} and {3,4}\n//\n// If there is at least one non-conflicting\n// configuration, SLL could continue with the hopes that more lookahead will\n// resolve via one of those non-conflicting configurations.\n//\n// Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n// stops when it sees only conflicting configuration subsets. In contrast,\n// full LL keeps going when there is uncertainty.\n//\n// # Heuristic\n//\n// As a heuristic, we stop prediction when we see any conflicting subset\n// unless we see a state that only has one alternative associated with it.\n// The single-alt-state thing lets prediction continue upon rules like\n// (otherwise, it would admit defeat too soon):\n//\n//\t[12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ;\n//\n// When the [ATN] simulation reaches the state before ';', it has a\n// [DFA] state that looks like:\n//\n//\t[12|1|[], 6|2|[], 12|2|[]]\n//\n// Naturally\n//\n//\t12|1|[] and  12|2|[]\n//\n// conflict, but we cannot stop processing this node because alternative to has another way to continue,\n// via\n//\n//\t[6|2|[]]\n//\n// It also let's us continue for this rule:\n//\n//\t[1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;\n//\n// After Matching input A, we reach the stop state for rule A, state 1.\n// State 8 is the state immediately before B. Clearly alternatives 1 and 2\n// conflict and no amount of further lookahead will separate the two.\n// However, alternative 3 will be able to continue, and so we do not stop\n// working on this state. In the previous example, we're concerned with\n// states associated with the conflicting alternatives. Here alt 3 is not\n// associated with the conflicting configs, but since we can continue\n// looking for input reasonably, don't declare the state done.\n//\n// # Pure SLL Parsing\n//\n// To handle pure SLL parsing, all we have to do is make sure that we\n// combine stack contexts for configurations that differ only by semantic\n// predicate. From there, we can do the usual SLL termination heuristic.\n//\n// # Predicates in SLL+LL Parsing\n//\n// SLL decisions don't evaluate predicates until after they reach [DFA] stop\n// states because they need to create the [DFA] cache that works in all\n// semantic situations. In contrast, full LL evaluates predicates collected\n// during start state computation, so it can ignore predicates thereafter.\n// This means that SLL termination detection can totally ignore semantic\n// predicates.\n//\n// Implementation-wise, [ATNConfigSet] combines stack contexts but not\n// semantic predicate contexts, so we might see two configurations like the\n// following:\n//\n//\t(s, 1, x, {}), (s, 1, x', {p})\n//\n// Before testing these configurations against others, we have to merge\n// x and x' (without modifying the existing configurations).\n// For example, we test (x+x')==x” when looking for conflicts in\n// the following configurations:\n//\n//\t(s, 1, x, {}), (s, 1, x', {p}), (s, 2, x”, {})\n//\n// If the configuration set has predicates (as indicated by\n// [ATNConfigSet.hasSemanticContext]), this algorithm makes a copy of\n// the configurations to strip out all the predicates so that a standard\n// [ATNConfigSet] will merge everything ignoring predicates.\nfunc PredictionModehasSLLConflictTerminatingPrediction(mode int, configs *ATNConfigSet) bool {\n\n\t// Configs in rule stop states indicate reaching the end of the decision\n\t// rule (local context) or end of start rule (full context). If all\n\t// configs meet this condition, then none of the configurations is able\n\t// to Match additional input, so we terminate prediction.\n\t//\n\tif PredictionModeallConfigsInRuleStopStates(configs) {\n\t\treturn true\n\t}\n\n\t// pure SLL mode parsing\n\tif mode == PredictionModeSLL {\n\t\t// Don't bother with combining configs from different semantic\n\t\t// contexts if we can fail over to full LL costs more time\n\t\t// since we'll often fail over anyway.\n\t\tif configs.hasSemanticContext {\n\t\t\t// dup configs, tossing out semantic predicates\n\t\t\tdup := NewATNConfigSet(false)\n\t\t\tfor _, c := range configs.configs {\n\n\t\t\t\t//\t\t\t\tNewATNConfig({semanticContext:}, c)\n\t\t\t\tc = NewATNConfig2(c, SemanticContextNone)\n\t\t\t\tdup.Add(c, nil)\n\t\t\t}\n\t\t\tconfigs = dup\n\t\t}\n\t\t// now we have combined contexts for configs with dissimilar predicates\n\t}\n\t// pure SLL or combined SLL+LL mode parsing\n\taltsets := PredictionModegetConflictingAltSubsets(configs)\n\treturn PredictionModehasConflictingAltSet(altsets) && !PredictionModehasStateAssociatedWithOneAlt(configs)\n}\n\n// PredictionModehasConfigInRuleStopState checks if any configuration in the given configs is in a\n// [RuleStopState]. Configurations meeting this condition have reached\n// the end of the decision rule (local context) or end of start rule (full\n// context).\n//\n// The func returns true if any configuration in the supplied configs is in a [RuleStopState]\nfunc PredictionModehasConfigInRuleStopState(configs *ATNConfigSet) bool {\n\tfor _, c := range configs.configs {\n\t\tif _, ok := c.GetState().(*RuleStopState); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// PredictionModeallConfigsInRuleStopStates checks if all configurations in configs are in a\n// [RuleStopState]. Configurations meeting this condition have reached\n// the end of the decision rule (local context) or end of start rule (full\n// context).\n//\n// the func returns true if all configurations in configs are in a\n// [RuleStopState]\nfunc PredictionModeallConfigsInRuleStopStates(configs *ATNConfigSet) bool {\n\n\tfor _, c := range configs.configs {\n\t\tif _, ok := c.GetState().(*RuleStopState); !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// PredictionModeresolvesToJustOneViableAlt checks full LL prediction termination.\n//\n// Can we stop looking ahead during [ATN] simulation or is there some\n// uncertainty as to which alternative we will ultimately pick, after\n// consuming more input? Even if there are partial conflicts, we might know\n// that everything is going to resolve to the same minimum alternative. That\n// means we can stop since no more lookahead will change that fact. On the\n// other hand, there might be multiple conflicts that resolve to different\n// minimums. That means we need more look ahead to decide which of those\n// alternatives we should predict.\n//\n// The basic idea is to split the set of configurations 'C', into\n// conflicting subsets (s, _, ctx, _) and singleton subsets with\n// non-conflicting configurations. Two configurations conflict if they have\n// identical [ATNConfig].state and [ATNConfig].context values\n// but a different [ATNConfig].alt value, e.g.\n//\n//\t(s, i, ctx, _)\n//\n// and\n//\n//\t(s, j, ctx, _) ; for i != j\n//\n// Reduce these configuration subsets to the set of possible alternatives.\n// You can compute the alternative subsets in one pass as follows:\n//\n//\tA_s,ctx = {i | (s, i, ctx, _)}\n//\n// for each configuration in C holding s and ctx fixed.\n//\n// Or in pseudo-code:\n//\n//\t for each configuration c in  C:\n//\t\t  map[c] U = c.ATNConfig.alt alt  // map hash/equals uses s and x, not alt and not pred\n//\n// The values in map are the set of\n//\n//\tA_s,ctx\n//\n// sets.\n//\n// If\n//\n//\t|A_s,ctx| = 1\n//\n// then there is no conflict associated with s and ctx.\n//\n// Reduce the subsets to singletons by choosing a minimum of each subset. If\n// the union of these alternative subsets is a singleton, then no amount of\n// further lookahead will help us. We will always pick that alternative. If,\n// however, there is more than one alternative, then we are uncertain which\n// alternative to predict and must continue looking for resolution. We may\n// or may not discover an ambiguity in the future, even if there are no\n// conflicting subsets this round.\n//\n// The biggest sin is to terminate early because it means we've made a\n// decision but were uncertain as to the eventual outcome. We haven't used\n// enough lookahead. On the other hand, announcing a conflict too late is no\n// big deal; you will still have the conflict. It's just inefficient. It\n// might even look until the end of file.\n//\n// No special consideration for semantic predicates is required because\n// predicates are evaluated on-the-fly for full LL prediction, ensuring that\n// no configuration contains a semantic context during the termination\n// check.\n//\n// # Conflicting Configs\n//\n// Two configurations:\n//\n//\t(s, i, x) and (s, j, x')\n//\n// conflict when i != j  but x = x'. Because we merge all\n// (s, i, _) configurations together, that means that there are at\n// most n configurations associated with state s for\n// n possible alternatives in the decision. The merged stacks\n// complicate the comparison of configuration contexts x and x'.\n//\n// Sam checks to see if one is a subset of the other by calling\n// merge and checking to see if the merged result is either x or x'.\n// If the x associated with lowest alternative i\n// is the superset, then i is the only possible prediction since the\n// others resolve to min(i) as well. However, if x is\n// associated with j > i then at least one stack configuration for\n// j is not in conflict with alternative i. The algorithm\n// should keep going, looking for more lookahead due to the uncertainty.\n//\n// For simplicity, I'm doing an equality check between x and\n// x', which lets the algorithm continue to consume lookahead longer\n// than necessary. The reason I like the equality is of course the\n// simplicity but also because that is the test you need to detect the\n// alternatives that are actually in conflict.\n//\n// # Continue/Stop Rule\n//\n// Continue if the union of resolved alternative sets from non-conflicting and\n// conflicting alternative subsets has more than one alternative. We are\n// uncertain about which alternative to predict.\n//\n// The complete set of alternatives,\n//\n//\t[i for (_, i, _)]\n//\n// tells us which alternatives are still in the running for the amount of input we've\n// consumed at this point. The conflicting sets let us to strip away\n// configurations that won't lead to more states because we resolve\n// conflicts to the configuration with a minimum alternate for the\n// conflicting set.\n//\n// Cases\n//\n//   - no conflicts and more than 1 alternative in set => continue\n//   - (s, 1, x), (s, 2, x), (s, 3, z), (s', 1, y), (s', 2, y) yields non-conflicting set\n//     {3} ∪ conflicting sets min({1,2}) ∪ min({1,2}) = {1,3} => continue\n//   - (s, 1, x), (s, 2, x), (s', 1, y), (s', 2, y), (s”, 1, z) yields non-conflicting set\n//     {1} ∪ conflicting sets min({1,2}) ∪ min({1,2}) = {1} => stop and predict 1\n//   - (s, 1, x), (s, 2, x), (s', 1, y), (s', 2, y) yields conflicting, reduced sets\n//     {1} ∪ {1} = {1} => stop and predict 1, can announce ambiguity {1,2}\n//   - (s, 1, x), (s, 2, x), (s', 2, y), (s', 3, y) yields conflicting, reduced sets\n//     {1} ∪ {2} = {1,2} => continue\n//   - (s, 1, x), (s, 2, x), (s', 2, y), (s', 3, y) yields conflicting, reduced sets\n//     {1} ∪ {2} = {1,2} => continue\n//   - (s, 1, x), (s, 2, x), (s', 3, y), (s', 4, y) yields conflicting, reduced sets\n//     {1} ∪ {3} = {1,3} => continue\n//\n// # Exact Ambiguity Detection\n//\n// If all states report the same conflicting set of alternatives, then we\n// know we have the exact ambiguity set:\n//\n//\t|A_i| > 1\n//\n// and\n//\n//\tA_i = A_j ; for all i, j\n//\n// In other words, we continue examining lookahead until all A_i\n// have more than one alternative and all A_i are the same. If\n//\n//\tA={{1,2}, {1,3}}\n//\n// then regular LL prediction would terminate because the resolved set is {1}.\n// To determine what the real ambiguity is, we have to know whether the ambiguity is between one and\n// two or one and three so we keep going. We can only stop prediction when\n// we need exact ambiguity detection when the sets look like:\n//\n//\tA={{1,2}}\n//\n// or\n//\n//\t{{1,2},{1,2}}, etc...\nfunc PredictionModeresolvesToJustOneViableAlt(altsets []*BitSet) int {\n\treturn PredictionModegetSingleViableAlt(altsets)\n}\n\n// PredictionModeallSubsetsConflict determines if every alternative subset in altsets contains more\n// than one alternative.\n//\n// The func returns true if every [BitSet] in altsets has\n// [BitSet].cardinality cardinality > 1\nfunc PredictionModeallSubsetsConflict(altsets []*BitSet) bool {\n\treturn !PredictionModehasNonConflictingAltSet(altsets)\n}\n\n// PredictionModehasNonConflictingAltSet determines if any single alternative subset in altsets contains\n// exactly one alternative.\n//\n// The func returns true if altsets contains at least one [BitSet] with\n// [BitSet].cardinality cardinality 1\nfunc PredictionModehasNonConflictingAltSet(altsets []*BitSet) bool {\n\tfor i := 0; i < len(altsets); i++ {\n\t\talts := altsets[i]\n\t\tif alts.length() == 1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// PredictionModehasConflictingAltSet determines if any single alternative subset in altsets contains\n// more than one alternative.\n//\n// The func returns true if altsets contains a [BitSet] with\n// [BitSet].cardinality cardinality > 1, otherwise false\nfunc PredictionModehasConflictingAltSet(altsets []*BitSet) bool {\n\tfor i := 0; i < len(altsets); i++ {\n\t\talts := altsets[i]\n\t\tif alts.length() > 1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// PredictionModeallSubsetsEqual determines if every alternative subset in altsets is equivalent.\n//\n// The func returns true if every member of altsets is equal to the others.\nfunc PredictionModeallSubsetsEqual(altsets []*BitSet) bool {\n\tvar first *BitSet\n\n\tfor i := 0; i < len(altsets); i++ {\n\t\talts := altsets[i]\n\t\tif first == nil {\n\t\t\tfirst = alts\n\t\t} else if alts != first {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n// PredictionModegetUniqueAlt returns the unique alternative predicted by all alternative subsets in\n// altsets. If no such alternative exists, this method returns\n// [ATNInvalidAltNumber].\n//\n// @param altsets a collection of alternative subsets\nfunc PredictionModegetUniqueAlt(altsets []*BitSet) int {\n\tall := PredictionModeGetAlts(altsets)\n\tif all.length() == 1 {\n\t\treturn all.minValue()\n\t}\n\n\treturn ATNInvalidAltNumber\n}\n\n// PredictionModeGetAlts returns the complete set of represented alternatives for a collection of\n// alternative subsets. This method returns the union of each [BitSet]\n// in altsets, being the set of represented alternatives in altsets.\nfunc PredictionModeGetAlts(altsets []*BitSet) *BitSet {\n\tall := NewBitSet()\n\tfor _, alts := range altsets {\n\t\tall.or(alts)\n\t}\n\treturn all\n}\n\n// PredictionModegetConflictingAltSubsets gets the conflicting alt subsets from a configuration set.\n//\n//\tfor each configuration c in configs:\n//\t   map[c] U= c.ATNConfig.alt // map hash/equals uses s and x, not alt and not pred\nfunc PredictionModegetConflictingAltSubsets(configs *ATNConfigSet) []*BitSet {\n\tconfigToAlts := NewJMap[*ATNConfig, *BitSet, *ATNAltConfigComparator[*ATNConfig]](atnAltCfgEqInst, AltSetCollection, \"PredictionModegetConflictingAltSubsets()\")\n\n\tfor _, c := range configs.configs {\n\n\t\talts, ok := configToAlts.Get(c)\n\t\tif !ok {\n\t\t\talts = NewBitSet()\n\t\t\tconfigToAlts.Put(c, alts)\n\t\t}\n\t\talts.add(c.GetAlt())\n\t}\n\n\treturn configToAlts.Values()\n}\n\n// PredictionModeGetStateToAltMap gets a map from state to alt subset from a configuration set.\n//\n//\tfor each configuration c in configs:\n//\t   map[c.ATNConfig.state] U= c.ATNConfig.alt}\nfunc PredictionModeGetStateToAltMap(configs *ATNConfigSet) *AltDict {\n\tm := NewAltDict()\n\n\tfor _, c := range configs.configs {\n\t\talts := m.Get(c.GetState().String())\n\t\tif alts == nil {\n\t\t\talts = NewBitSet()\n\t\t\tm.put(c.GetState().String(), alts)\n\t\t}\n\t\talts.(*BitSet).add(c.GetAlt())\n\t}\n\treturn m\n}\n\nfunc PredictionModehasStateAssociatedWithOneAlt(configs *ATNConfigSet) bool {\n\tvalues := PredictionModeGetStateToAltMap(configs).values()\n\tfor i := 0; i < len(values); i++ {\n\t\tif values[i].(*BitSet).length() == 1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// PredictionModegetSingleViableAlt gets the single alternative predicted by all alternative subsets in altsets\n// if there is one.\n//\n// TODO: JI - Review this code - it does not seem to do the same thing as the Java code - maybe because [BitSet] is not like the Java utils BitSet\nfunc PredictionModegetSingleViableAlt(altsets []*BitSet) int {\n\tresult := ATNInvalidAltNumber\n\n\tfor i := 0; i < len(altsets); i++ {\n\t\talts := altsets[i]\n\t\tminAlt := alts.minValue()\n\t\tif result == ATNInvalidAltNumber {\n\t\t\tresult = minAlt\n\t\t} else if result != minAlt { // more than 1 viable alt\n\t\t\treturn ATNInvalidAltNumber\n\t\t}\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/recognizer.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"strconv\"\n)\n\ntype Recognizer interface {\n\tGetLiteralNames() []string\n\tGetSymbolicNames() []string\n\tGetRuleNames() []string\n\n\tSempred(RuleContext, int, int) bool\n\tPrecpred(RuleContext, int) bool\n\n\tGetState() int\n\tSetState(int)\n\tAction(RuleContext, int, int)\n\tAddErrorListener(ErrorListener)\n\tRemoveErrorListeners()\n\tGetATN() *ATN\n\tGetErrorListenerDispatch() ErrorListener\n\tHasError() bool\n\tGetError() RecognitionException\n\tSetError(RecognitionException)\n}\n\ntype BaseRecognizer struct {\n\tlisteners []ErrorListener\n\tstate     int\n\n\tRuleNames       []string\n\tLiteralNames    []string\n\tSymbolicNames   []string\n\tGrammarFileName string\n\tSynErr          RecognitionException\n}\n\nfunc NewBaseRecognizer() *BaseRecognizer {\n\trec := new(BaseRecognizer)\n\trec.listeners = []ErrorListener{ConsoleErrorListenerINSTANCE}\n\trec.state = -1\n\treturn rec\n}\n\n//goland:noinspection GoUnusedGlobalVariable\nvar tokenTypeMapCache = make(map[string]int)\n\n//goland:noinspection GoUnusedGlobalVariable\nvar ruleIndexMapCache = make(map[string]int)\n\nfunc (b *BaseRecognizer) checkVersion(toolVersion string) {\n\truntimeVersion := \"4.13.2\"\n\tif runtimeVersion != toolVersion {\n\t\tfmt.Println(\"ANTLR runtime and generated code versions disagree: \" + runtimeVersion + \"!=\" + toolVersion)\n\t}\n}\n\nfunc (b *BaseRecognizer) SetError(err RecognitionException) {\n\tb.SynErr = err\n}\n\nfunc (b *BaseRecognizer) HasError() bool {\n\treturn b.SynErr != nil\n}\n\nfunc (b *BaseRecognizer) GetError() RecognitionException {\n\treturn b.SynErr\n}\n\nfunc (b *BaseRecognizer) Action(_ RuleContext, _, _ int) {\n\tpanic(\"action not implemented on Recognizer!\")\n}\n\nfunc (b *BaseRecognizer) AddErrorListener(listener ErrorListener) {\n\tb.listeners = append(b.listeners, listener)\n}\n\nfunc (b *BaseRecognizer) RemoveErrorListeners() {\n\tb.listeners = make([]ErrorListener, 0)\n}\n\nfunc (b *BaseRecognizer) GetRuleNames() []string {\n\treturn b.RuleNames\n}\n\nfunc (b *BaseRecognizer) GetTokenNames() []string {\n\treturn b.LiteralNames\n}\n\nfunc (b *BaseRecognizer) GetSymbolicNames() []string {\n\treturn b.SymbolicNames\n}\n\nfunc (b *BaseRecognizer) GetLiteralNames() []string {\n\treturn b.LiteralNames\n}\n\nfunc (b *BaseRecognizer) GetState() int {\n\treturn b.state\n}\n\nfunc (b *BaseRecognizer) SetState(v int) {\n\tb.state = v\n}\n\n//func (b *Recognizer) GetTokenTypeMap() {\n//    var tokenNames = b.GetTokenNames()\n//    if (tokenNames==nil) {\n//        panic(\"The current recognizer does not provide a list of token names.\")\n//    }\n//    var result = tokenTypeMapCache[tokenNames]\n//    if(result==nil) {\n//        result = tokenNames.reduce(function(o, k, i) { o[k] = i })\n//        result.EOF = TokenEOF\n//        tokenTypeMapCache[tokenNames] = result\n//    }\n//    return result\n//}\n\n// GetRuleIndexMap Get a map from rule names to rule indexes.\n//\n// Used for XPath and tree pattern compilation.\n//\n// TODO: JI This is not yet implemented in the Go runtime. Maybe not needed.\nfunc (b *BaseRecognizer) GetRuleIndexMap() map[string]int {\n\n\tpanic(\"Method not defined!\")\n\t//    var ruleNames = b.GetRuleNames()\n\t//    if (ruleNames==nil) {\n\t//        panic(\"The current recognizer does not provide a list of rule names.\")\n\t//    }\n\t//\n\t//    var result = ruleIndexMapCache[ruleNames]\n\t//    if(result==nil) {\n\t//        result = ruleNames.reduce(function(o, k, i) { o[k] = i })\n\t//        ruleIndexMapCache[ruleNames] = result\n\t//    }\n\t//    return result\n}\n\n// GetTokenType get the token type based upon its name\nfunc (b *BaseRecognizer) GetTokenType(_ string) int {\n\tpanic(\"Method not defined!\")\n\t//    var ttype = b.GetTokenTypeMap()[tokenName]\n\t//    if (ttype !=nil) {\n\t//        return ttype\n\t//    } else {\n\t//        return TokenInvalidType\n\t//    }\n}\n\n//func (b *Recognizer) GetTokenTypeMap() map[string]int {\n//    Vocabulary vocabulary = getVocabulary()\n//\n//    Synchronized (tokenTypeMapCache) {\n//        Map<String, Integer> result = tokenTypeMapCache.Get(vocabulary)\n//        if (result == null) {\n//            result = new HashMap<String, Integer>()\n//            for (int i = 0; i < GetATN().maxTokenType; i++) {\n//                String literalName = vocabulary.getLiteralName(i)\n//                if (literalName != null) {\n//                    result.put(literalName, i)\n//                }\n//\n//                String symbolicName = vocabulary.GetSymbolicName(i)\n//                if (symbolicName != null) {\n//                    result.put(symbolicName, i)\n//                }\n//            }\n//\n//            result.put(\"EOF\", Token.EOF)\n//            result = Collections.unmodifiableMap(result)\n//            tokenTypeMapCache.put(vocabulary, result)\n//        }\n//\n//        return result\n//    }\n//}\n\n// GetErrorHeader returns the error header, normally line/character position information.\n//\n// Can be overridden in sub structs embedding BaseRecognizer.\nfunc (b *BaseRecognizer) GetErrorHeader(e RecognitionException) string {\n\tline := e.GetOffendingToken().GetLine()\n\tcolumn := e.GetOffendingToken().GetColumn()\n\treturn \"line \" + strconv.Itoa(line) + \":\" + strconv.Itoa(column)\n}\n\n// GetTokenErrorDisplay shows how a token should be displayed in an error message.\n//\n// The default is to display just the text, but during development you might\n// want to have a lot of information spit out.  Override in that case\n// to use t.String() (which, for CommonToken, dumps everything about\n// the token). This is better than forcing you to override a method in\n// your token objects because you don't have to go modify your lexer\n// so that it creates a NewJava type.\n//\n// Deprecated: This method is not called by the ANTLR 4 Runtime. Specific\n// implementations of [ANTLRErrorStrategy] may provide a similar\n// feature when necessary. For example, see [DefaultErrorStrategy].GetTokenErrorDisplay()\nfunc (b *BaseRecognizer) GetTokenErrorDisplay(t Token) string {\n\tif t == nil {\n\t\treturn \"<no token>\"\n\t}\n\ts := t.GetText()\n\tif s == \"\" {\n\t\tif t.GetTokenType() == TokenEOF {\n\t\t\ts = \"<EOF>\"\n\t\t} else {\n\t\t\ts = \"<\" + strconv.Itoa(t.GetTokenType()) + \">\"\n\t\t}\n\t}\n\ts = strings.Replace(s, \"\\t\", \"\\\\t\", -1)\n\ts = strings.Replace(s, \"\\n\", \"\\\\n\", -1)\n\ts = strings.Replace(s, \"\\r\", \"\\\\r\", -1)\n\n\treturn \"'\" + s + \"'\"\n}\n\nfunc (b *BaseRecognizer) GetErrorListenerDispatch() ErrorListener {\n\treturn NewProxyErrorListener(b.listeners)\n}\n\n// Sempred embedding structs need to override this if there are sempreds or actions\n// that the ATN interpreter needs to execute\nfunc (b *BaseRecognizer) Sempred(_ RuleContext, _ int, _ int) bool {\n\treturn true\n}\n\n// Precpred embedding structs need to override this if there are preceding predicates\n// that the ATN interpreter needs to execute\nfunc (b *BaseRecognizer) Precpred(_ RuleContext, _ int) bool {\n\treturn true\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/rule_context.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// RuleContext is a record of a single rule invocation. It knows\n// which context invoked it, if any. If there is no parent context, then\n// naturally the invoking state is not valid.  The parent link\n// provides a chain upwards from the current rule invocation to the root\n// of the invocation tree, forming a stack.\n//\n// We actually carry no information about the rule associated with this context (except\n// when parsing). We keep only the state number of the invoking state from\n// the [ATN] submachine that invoked this. Contrast this with the s\n// pointer inside [ParserRuleContext] that tracks the current state\n// being \"executed\" for the current rule.\n//\n// The parent contexts are useful for computing lookahead sets and\n// getting error information.\n//\n// These objects are used during parsing and prediction.\n// For the special case of parsers, we use the struct\n// [ParserRuleContext], which embeds a RuleContext.\n//\n// @see ParserRuleContext\ntype RuleContext interface {\n\tRuleNode\n\n\tGetInvokingState() int\n\tSetInvokingState(int)\n\n\tGetRuleIndex() int\n\tIsEmpty() bool\n\n\tGetAltNumber() int\n\tSetAltNumber(altNumber int)\n\n\tString([]string, RuleContext) string\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/semantic_context.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\n// SemanticContext is a tree structure used to record the semantic context in which\n//\n//\tan ATN configuration is valid.  It's either a single predicate,\n//\ta conjunction p1 && p2, or a sum of products p1 || p2.\n//\n//\tI have scoped the AND, OR, and Predicate subclasses of\n//\t[SemanticContext] within the scope of this outer ``class''\ntype SemanticContext interface {\n\tEquals(other Collectable[SemanticContext]) bool\n\tHash() int\n\n\tevaluate(parser Recognizer, outerContext RuleContext) bool\n\tevalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext\n\n\tString() string\n}\n\nfunc SemanticContextandContext(a, b SemanticContext) SemanticContext {\n\tif a == nil || a == SemanticContextNone {\n\t\treturn b\n\t}\n\tif b == nil || b == SemanticContextNone {\n\t\treturn a\n\t}\n\tresult := NewAND(a, b)\n\tif len(result.opnds) == 1 {\n\t\treturn result.opnds[0]\n\t}\n\n\treturn result\n}\n\nfunc SemanticContextorContext(a, b SemanticContext) SemanticContext {\n\tif a == nil {\n\t\treturn b\n\t}\n\tif b == nil {\n\t\treturn a\n\t}\n\tif a == SemanticContextNone || b == SemanticContextNone {\n\t\treturn SemanticContextNone\n\t}\n\tresult := NewOR(a, b)\n\tif len(result.opnds) == 1 {\n\t\treturn result.opnds[0]\n\t}\n\n\treturn result\n}\n\ntype Predicate struct {\n\truleIndex      int\n\tpredIndex      int\n\tisCtxDependent bool\n}\n\nfunc NewPredicate(ruleIndex, predIndex int, isCtxDependent bool) *Predicate {\n\tp := new(Predicate)\n\n\tp.ruleIndex = ruleIndex\n\tp.predIndex = predIndex\n\tp.isCtxDependent = isCtxDependent // e.g., $i ref in pred\n\treturn p\n}\n\n//The default {@link SemanticContext}, which is semantically equivalent to\n//a predicate of the form {@code {true}?}.\n\nvar SemanticContextNone = NewPredicate(-1, -1, false)\n\nfunc (p *Predicate) evalPrecedence(_ Recognizer, _ RuleContext) SemanticContext {\n\treturn p\n}\n\nfunc (p *Predicate) evaluate(parser Recognizer, outerContext RuleContext) bool {\n\n\tvar localctx RuleContext\n\n\tif p.isCtxDependent {\n\t\tlocalctx = outerContext\n\t}\n\n\treturn parser.Sempred(localctx, p.ruleIndex, p.predIndex)\n}\n\nfunc (p *Predicate) Equals(other Collectable[SemanticContext]) bool {\n\tif p == other {\n\t\treturn true\n\t} else if _, ok := other.(*Predicate); !ok {\n\t\treturn false\n\t} else {\n\t\treturn p.ruleIndex == other.(*Predicate).ruleIndex &&\n\t\t\tp.predIndex == other.(*Predicate).predIndex &&\n\t\t\tp.isCtxDependent == other.(*Predicate).isCtxDependent\n\t}\n}\n\nfunc (p *Predicate) Hash() int {\n\th := murmurInit(0)\n\th = murmurUpdate(h, p.ruleIndex)\n\th = murmurUpdate(h, p.predIndex)\n\tif p.isCtxDependent {\n\t\th = murmurUpdate(h, 1)\n\t} else {\n\t\th = murmurUpdate(h, 0)\n\t}\n\treturn murmurFinish(h, 3)\n}\n\nfunc (p *Predicate) String() string {\n\treturn \"{\" + strconv.Itoa(p.ruleIndex) + \":\" + strconv.Itoa(p.predIndex) + \"}?\"\n}\n\ntype PrecedencePredicate struct {\n\tprecedence int\n}\n\nfunc NewPrecedencePredicate(precedence int) *PrecedencePredicate {\n\n\tp := new(PrecedencePredicate)\n\tp.precedence = precedence\n\n\treturn p\n}\n\nfunc (p *PrecedencePredicate) evaluate(parser Recognizer, outerContext RuleContext) bool {\n\treturn parser.Precpred(outerContext, p.precedence)\n}\n\nfunc (p *PrecedencePredicate) evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext {\n\tif parser.Precpred(outerContext, p.precedence) {\n\t\treturn SemanticContextNone\n\t}\n\n\treturn nil\n}\n\nfunc (p *PrecedencePredicate) compareTo(other *PrecedencePredicate) int {\n\treturn p.precedence - other.precedence\n}\n\nfunc (p *PrecedencePredicate) Equals(other Collectable[SemanticContext]) bool {\n\n\tvar op *PrecedencePredicate\n\tvar ok bool\n\tif op, ok = other.(*PrecedencePredicate); !ok {\n\t\treturn false\n\t}\n\n\tif p == op {\n\t\treturn true\n\t}\n\n\treturn p.precedence == other.(*PrecedencePredicate).precedence\n}\n\nfunc (p *PrecedencePredicate) Hash() int {\n\th := uint32(1)\n\th = 31*h + uint32(p.precedence)\n\treturn int(h)\n}\n\nfunc (p *PrecedencePredicate) String() string {\n\treturn \"{\" + strconv.Itoa(p.precedence) + \">=prec}?\"\n}\n\nfunc PrecedencePredicatefilterPrecedencePredicates(set *JStore[SemanticContext, Comparator[SemanticContext]]) []*PrecedencePredicate {\n\tresult := make([]*PrecedencePredicate, 0)\n\n\tset.Each(func(v SemanticContext) bool {\n\t\tif c2, ok := v.(*PrecedencePredicate); ok {\n\t\t\tresult = append(result, c2)\n\t\t}\n\t\treturn true\n\t})\n\n\treturn result\n}\n\n// A semantic context which is true whenever none of the contained contexts\n// is false.`\n\ntype AND struct {\n\topnds []SemanticContext\n}\n\nfunc NewAND(a, b SemanticContext) *AND {\n\n\toperands := NewJStore[SemanticContext, Comparator[SemanticContext]](semctxEqInst, SemanticContextCollection, \"NewAND() operands\")\n\tif aa, ok := a.(*AND); ok {\n\t\tfor _, o := range aa.opnds {\n\t\t\toperands.Put(o)\n\t\t}\n\t} else {\n\t\toperands.Put(a)\n\t}\n\n\tif ba, ok := b.(*AND); ok {\n\t\tfor _, o := range ba.opnds {\n\t\t\toperands.Put(o)\n\t\t}\n\t} else {\n\t\toperands.Put(b)\n\t}\n\tprecedencePredicates := PrecedencePredicatefilterPrecedencePredicates(operands)\n\tif len(precedencePredicates) > 0 {\n\t\t// interested in the transition with the lowest precedence\n\t\tvar reduced *PrecedencePredicate\n\n\t\tfor _, p := range precedencePredicates {\n\t\t\tif reduced == nil || p.precedence < reduced.precedence {\n\t\t\t\treduced = p\n\t\t\t}\n\t\t}\n\n\t\toperands.Put(reduced)\n\t}\n\n\tvs := operands.Values()\n\topnds := make([]SemanticContext, len(vs))\n\tcopy(opnds, vs)\n\n\tand := new(AND)\n\tand.opnds = opnds\n\n\treturn and\n}\n\nfunc (a *AND) Equals(other Collectable[SemanticContext]) bool {\n\tif a == other {\n\t\treturn true\n\t}\n\tif _, ok := other.(*AND); !ok {\n\t\treturn false\n\t} else {\n\t\tfor i, v := range other.(*AND).opnds {\n\t\t\tif !a.opnds[i].Equals(v) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n\n// {@inheritDoc}\n//\n// <p>\n// The evaluation of predicates by a context is short-circuiting, but\n// unordered.</p>\nfunc (a *AND) evaluate(parser Recognizer, outerContext RuleContext) bool {\n\tfor i := 0; i < len(a.opnds); i++ {\n\t\tif !a.opnds[i].evaluate(parser, outerContext) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (a *AND) evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext {\n\tdiffers := false\n\toperands := make([]SemanticContext, 0)\n\n\tfor i := 0; i < len(a.opnds); i++ {\n\t\tcontext := a.opnds[i]\n\t\tevaluated := context.evalPrecedence(parser, outerContext)\n\t\tdiffers = differs || (evaluated != context)\n\t\tif evaluated == nil {\n\t\t\t// The AND context is false if any element is false\n\t\t\treturn nil\n\t\t} else if evaluated != SemanticContextNone {\n\t\t\t// Reduce the result by Skipping true elements\n\t\t\toperands = append(operands, evaluated)\n\t\t}\n\t}\n\tif !differs {\n\t\treturn a\n\t}\n\n\tif len(operands) == 0 {\n\t\t// all elements were true, so the AND context is true\n\t\treturn SemanticContextNone\n\t}\n\n\tvar result SemanticContext\n\n\tfor _, o := range operands {\n\t\tif result == nil {\n\t\t\tresult = o\n\t\t} else {\n\t\t\tresult = SemanticContextandContext(result, o)\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc (a *AND) Hash() int {\n\th := murmurInit(37) // Init with a value different from OR\n\tfor _, op := range a.opnds {\n\t\th = murmurUpdate(h, op.Hash())\n\t}\n\treturn murmurFinish(h, len(a.opnds))\n}\n\nfunc (o *OR) Hash() int {\n\th := murmurInit(41) // Init with o value different from AND\n\tfor _, op := range o.opnds {\n\t\th = murmurUpdate(h, op.Hash())\n\t}\n\treturn murmurFinish(h, len(o.opnds))\n}\n\nfunc (a *AND) String() string {\n\ts := \"\"\n\n\tfor _, o := range a.opnds {\n\t\ts += \"&& \" + fmt.Sprint(o)\n\t}\n\n\tif len(s) > 3 {\n\t\treturn s[0:3]\n\t}\n\n\treturn s\n}\n\n//\n// A semantic context which is true whenever at least one of the contained\n// contexts is true.\n//\n\ntype OR struct {\n\topnds []SemanticContext\n}\n\nfunc NewOR(a, b SemanticContext) *OR {\n\n\toperands := NewJStore[SemanticContext, Comparator[SemanticContext]](semctxEqInst, SemanticContextCollection, \"NewOR() operands\")\n\tif aa, ok := a.(*OR); ok {\n\t\tfor _, o := range aa.opnds {\n\t\t\toperands.Put(o)\n\t\t}\n\t} else {\n\t\toperands.Put(a)\n\t}\n\n\tif ba, ok := b.(*OR); ok {\n\t\tfor _, o := range ba.opnds {\n\t\t\toperands.Put(o)\n\t\t}\n\t} else {\n\t\toperands.Put(b)\n\t}\n\tprecedencePredicates := PrecedencePredicatefilterPrecedencePredicates(operands)\n\tif len(precedencePredicates) > 0 {\n\t\t// interested in the transition with the lowest precedence\n\t\tvar reduced *PrecedencePredicate\n\n\t\tfor _, p := range precedencePredicates {\n\t\t\tif reduced == nil || p.precedence > reduced.precedence {\n\t\t\t\treduced = p\n\t\t\t}\n\t\t}\n\n\t\toperands.Put(reduced)\n\t}\n\n\tvs := operands.Values()\n\n\topnds := make([]SemanticContext, len(vs))\n\tcopy(opnds, vs)\n\n\to := new(OR)\n\to.opnds = opnds\n\n\treturn o\n}\n\nfunc (o *OR) Equals(other Collectable[SemanticContext]) bool {\n\tif o == other {\n\t\treturn true\n\t} else if _, ok := other.(*OR); !ok {\n\t\treturn false\n\t} else {\n\t\tfor i, v := range other.(*OR).opnds {\n\t\t\tif !o.opnds[i].Equals(v) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n\n// <p>\n// The evaluation of predicates by o context is short-circuiting, but\n// unordered.</p>\nfunc (o *OR) evaluate(parser Recognizer, outerContext RuleContext) bool {\n\tfor i := 0; i < len(o.opnds); i++ {\n\t\tif o.opnds[i].evaluate(parser, outerContext) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (o *OR) evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext {\n\tdiffers := false\n\toperands := make([]SemanticContext, 0)\n\tfor i := 0; i < len(o.opnds); i++ {\n\t\tcontext := o.opnds[i]\n\t\tevaluated := context.evalPrecedence(parser, outerContext)\n\t\tdiffers = differs || (evaluated != context)\n\t\tif evaluated == SemanticContextNone {\n\t\t\t// The OR context is true if any element is true\n\t\t\treturn SemanticContextNone\n\t\t} else if evaluated != nil {\n\t\t\t// Reduce the result by Skipping false elements\n\t\t\toperands = append(operands, evaluated)\n\t\t}\n\t}\n\tif !differs {\n\t\treturn o\n\t}\n\tif len(operands) == 0 {\n\t\t// all elements were false, so the OR context is false\n\t\treturn nil\n\t}\n\tvar result SemanticContext\n\n\tfor _, o := range operands {\n\t\tif result == nil {\n\t\t\tresult = o\n\t\t} else {\n\t\t\tresult = SemanticContextorContext(result, o)\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc (o *OR) String() string {\n\ts := \"\"\n\n\tfor _, o := range o.opnds {\n\t\ts += \"|| \" + fmt.Sprint(o)\n\t}\n\n\tif len(s) > 3 {\n\t\treturn s[0:3]\n\t}\n\n\treturn s\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/statistics.go",
    "content": "//go:build antlr.stats\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strconv\"\n)\n\n// This file allows the user to collect statistics about the runtime of the ANTLR runtime. It is not enabled by default\n// and so incurs no time penalty. To enable it, you must build the runtime with the antlr.stats build tag.\n//\n\n// Tells various components to collect statistics - because it is only true when this file is included, it will\n// allow the compiler to completely eliminate all the code that is only used when collecting statistics.\nconst collectStats = true\n\n// goRunStats is a collection of all the various data the ANTLR runtime has collected about a particular run.\n// It is exported so that it can be used by others to look for things that are not already looked for in the\n// runtime statistics.\ntype goRunStats struct {\n\n\t// jStats is a slice of all the [JStatRec] records that have been created, which is one for EVERY collection created\n\t// during a run. It is exported so that it can be used by others to look for things that are not already looked for\n\t// within this package.\n\t//\n\tjStats            []*JStatRec\n\tjStatsLock        RWMutex\n\ttopN              int\n\ttopNByMax         []*JStatRec\n\ttopNByUsed        []*JStatRec\n\tunusedCollections map[CollectionSource]int\n\tcounts            map[CollectionSource]int\n}\n\nconst (\n\tcollectionsFile = \"collections\"\n)\n\nvar (\n\tStatistics = &goRunStats{\n\t\ttopN: 10,\n\t}\n)\n\ntype statsOption func(*goRunStats) error\n\n// Configure allows the statistics system to be configured as the user wants and override the defaults\nfunc (s *goRunStats) Configure(options ...statsOption) error {\n\tfor _, option := range options {\n\t\terr := option(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// WithTopN sets the number of things to list in the report when we are concerned with the top N things.\n//\n// For example, if you want to see the top 20 collections by size, you can do:\n//\n//\tantlr.Statistics.Configure(antlr.WithTopN(20))\nfunc WithTopN(topN int) statsOption {\n\treturn func(s *goRunStats) error {\n\t\ts.topN = topN\n\t\treturn nil\n\t}\n}\n\n// Analyze looks through all the statistical records and computes all the outputs that might be useful to the user.\n//\n// The function gathers and analyzes a number of statistics about any particular run of\n// an ANTLR generated recognizer. In the vast majority of cases, the statistics are only\n// useful to maintainers of ANTLR itself, but they can be useful to users as well. They may be\n// especially useful in tracking down bugs or performance problems when an ANTLR user could\n// supply the output from this package, but cannot supply the grammar file(s) they are using, even\n// privately to the maintainers.\n//\n// The statistics are gathered by the runtime itself, and are not gathered by the parser or lexer, but the user\n// must call this function their selves to analyze the statistics. This is because none of the infrastructure is\n// extant unless the calling program is built with the antlr.stats tag like so:\n//\n// go build -tags antlr.stats .\n//\n// When a program is built with the antlr.stats tag, the Statistics object is created and available outside\n// the package. The user can then call the [Statistics.Analyze] function to analyze the statistics and then call the\n// [Statistics.Report] function to report the statistics.\n//\n// Please forward any questions about this package to the ANTLR discussion groups on GitHub or send to them to\n// me [Jim Idle] directly at jimi@idle.ws\n//\n// [Jim Idle]: https:://github.com/jim-idle\nfunc (s *goRunStats) Analyze() {\n\n\t// Look for anything that looks strange and record it in our local maps etc for the report to present it\n\t//\n\ts.CollectionAnomalies()\n\ts.TopNCollections()\n}\n\n// TopNCollections looks through all the statistical records and gathers the top ten collections by size.\nfunc (s *goRunStats) TopNCollections() {\n\n\t// Let's sort the stat records by MaxSize\n\t//\n\tsort.Slice(s.jStats, func(i, j int) bool {\n\t\treturn s.jStats[i].MaxSize > s.jStats[j].MaxSize\n\t})\n\n\tfor i := 0; i < len(s.jStats) && i < s.topN; i++ {\n\t\ts.topNByMax = append(s.topNByMax, s.jStats[i])\n\t}\n\n\t// Sort by the number of times used\n\t//\n\tsort.Slice(s.jStats, func(i, j int) bool {\n\t\treturn s.jStats[i].Gets+s.jStats[i].Puts > s.jStats[j].Gets+s.jStats[j].Puts\n\t})\n\tfor i := 0; i < len(s.jStats) && i < s.topN; i++ {\n\t\ts.topNByUsed = append(s.topNByUsed, s.jStats[i])\n\t}\n}\n\n// Report dumps a markdown formatted report of all the statistics collected during a run to the given dir output\n// path, which should represent a directory. Generated files will be prefixed with the given prefix and will be\n// given a type name such as `anomalies` and a time stamp such as `2021-09-01T12:34:56` and a .md suffix.\nfunc (s *goRunStats) Report(dir string, prefix string) error {\n\n\tisDir, err := isDirectory(dir)\n\tswitch {\n\tcase err != nil:\n\t\treturn err\n\tcase !isDir:\n\t\treturn fmt.Errorf(\"output directory `%s` is not a directory\", dir)\n\t}\n\ts.reportCollections(dir, prefix)\n\n\t// Clean out any old data in case the user forgets\n\t//\n\ts.Reset()\n\treturn nil\n}\n\nfunc (s *goRunStats) Reset() {\n\ts.jStats = nil\n\ts.topNByUsed = nil\n\ts.topNByMax = nil\n}\n\nfunc (s *goRunStats) reportCollections(dir, prefix string) {\n\tcname := filepath.Join(dir, \".asciidoctor\")\n\t// If the file doesn't exist, create it, or append to the file\n\tf, err := os.OpenFile(cname, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t_, _ = f.WriteString(`// .asciidoctorconfig\n++++\n<style>\nbody {\nfont-family: \"Quicksand\", \"Montserrat\", \"Helvetica\";\nbackground-color: black;\n}\n</style>\n++++`)\n\t_ = f.Close()\n\n\tfname := filepath.Join(dir, prefix+\"_\"+\"_\"+collectionsFile+\"_\"+\".adoc\")\n\t// If the file doesn't exist, create it, or append to the file\n\tf, err = os.OpenFile(fname, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer func(f *os.File) {\n\t\terr := f.Close()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}(f)\n\t_, _ = f.WriteString(\"= Collections for \" + prefix + \"\\n\\n\")\n\n\t_, _ = f.WriteString(\"== Summary\\n\")\n\n\tif s.unusedCollections != nil {\n\t\t_, _ = f.WriteString(\"=== Unused Collections\\n\")\n\t\t_, _ = f.WriteString(\"Unused collections incur a penalty for allocation that makes them a candidate for either\\n\")\n\t\t_, _ = f.WriteString(\" removal or optimization. If you are using a collection that is not used, you should\\n\")\n\t\t_, _ = f.WriteString(\" consider removing it. If you are using a collection that is used, but not very often,\\n\")\n\t\t_, _ = f.WriteString(\" you should consider using lazy initialization to defer the allocation until it is\\n\")\n\t\t_, _ = f.WriteString(\" actually needed.\\n\\n\")\n\n\t\t_, _ = f.WriteString(\"\\n.Unused collections\\n\")\n\t\t_, _ = f.WriteString(`[cols=\"<3,>1\"]` + \"\\n\\n\")\n\t\t_, _ = f.WriteString(\"|===\\n\")\n\t\t_, _ = f.WriteString(\"| Type | Count\\n\")\n\n\t\tfor k, v := range s.unusedCollections {\n\t\t\t_, _ = f.WriteString(\"| \" + CollectionDescriptors[k].SybolicName + \" | \" + strconv.Itoa(v) + \"\\n\")\n\t\t}\n\t\tf.WriteString(\"|===\\n\\n\")\n\t}\n\n\t_, _ = f.WriteString(\"\\n.Summary of Collections\\n\")\n\t_, _ = f.WriteString(`[cols=\"<3,>1\"]` + \"\\n\\n\")\n\t_, _ = f.WriteString(\"|===\\n\")\n\t_, _ = f.WriteString(\"| Type | Count\\n\")\n\tfor k, v := range s.counts {\n\t\t_, _ = f.WriteString(\"| \" + CollectionDescriptors[k].SybolicName + \" | \" + strconv.Itoa(v) + \"\\n\")\n\t}\n\t_, _ = f.WriteString(\"| Total | \" + strconv.Itoa(len(s.jStats)) + \"\\n\")\n\t_, _ = f.WriteString(\"|===\\n\\n\")\n\n\t_, _ = f.WriteString(\"\\n.Summary of Top \" + strconv.Itoa(s.topN) + \" Collections by MaxSize\\n\")\n\t_, _ = f.WriteString(`[cols=\"<1,<3,>1,>1,>1,>1\"]` + \"\\n\\n\")\n\t_, _ = f.WriteString(\"|===\\n\")\n\t_, _ = f.WriteString(\"| Source | Description | MaxSize | EndSize | Puts | Gets\\n\")\n\tfor _, c := range s.topNByMax {\n\t\t_, _ = f.WriteString(\"| \" + CollectionDescriptors[c.Source].SybolicName + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + c.Description + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.MaxSize) + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.CurSize) + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.Puts) + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.Gets) + \"\\n\")\n\t\t_, _ = f.WriteString(\"\\n\")\n\t}\n\t_, _ = f.WriteString(\"|===\\n\\n\")\n\n\t_, _ = f.WriteString(\"\\n.Summary of Top \" + strconv.Itoa(s.topN) + \" Collections by Access\\n\")\n\t_, _ = f.WriteString(`[cols=\"<1,<3,>1,>1,>1,>1,>1\"]` + \"\\n\\n\")\n\t_, _ = f.WriteString(\"|===\\n\")\n\t_, _ = f.WriteString(\"| Source | Description | MaxSize | EndSize | Puts | Gets | P+G\\n\")\n\tfor _, c := range s.topNByUsed {\n\t\t_, _ = f.WriteString(\"| \" + CollectionDescriptors[c.Source].SybolicName + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + c.Description + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.MaxSize) + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.CurSize) + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.Puts) + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.Gets) + \"\\n\")\n\t\t_, _ = f.WriteString(\"| \" + strconv.Itoa(c.Gets+c.Puts) + \"\\n\")\n\t\t_, _ = f.WriteString(\"\\n\")\n\t}\n\t_, _ = f.WriteString(\"|===\\n\\n\")\n}\n\n// AddJStatRec adds a [JStatRec] record to the [goRunStats] collection when build runtimeConfig antlr.stats is enabled.\nfunc (s *goRunStats) AddJStatRec(rec *JStatRec) {\n\ts.jStatsLock.Lock()\n\tdefer s.jStatsLock.Unlock()\n\ts.jStats = append(s.jStats, rec)\n}\n\n// CollectionAnomalies looks through all the statistical records and gathers any anomalies that have been found.\nfunc (s *goRunStats) CollectionAnomalies() {\n\ts.jStatsLock.RLock()\n\tdefer s.jStatsLock.RUnlock()\n\ts.counts = make(map[CollectionSource]int, len(s.jStats))\n\tfor _, c := range s.jStats {\n\n\t\t// Accumlate raw counts\n\t\t//\n\t\ts.counts[c.Source]++\n\n\t\t// Look for allocated but unused collections and count them\n\t\tif c.MaxSize == 0 && c.Puts == 0 {\n\t\t\tif s.unusedCollections == nil {\n\t\t\t\ts.unusedCollections = make(map[CollectionSource]int)\n\t\t\t}\n\t\t\ts.unusedCollections[c.Source]++\n\t\t}\n\t\tif c.MaxSize > 6000 {\n\t\t\tfmt.Println(\"Collection \", c.Description, \"accumulated a max size of \", c.MaxSize, \" - this is probably too large and indicates a poorly formed grammar\")\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/stats_data.go",
    "content": "package antlr\n\n// A JStatRec is a record of a particular use of a [JStore], [JMap] or JPCMap] collection. Typically, it will be\n// used to look for unused collections that wre allocated anyway, problems with hash bucket clashes, and anomalies\n// such as huge numbers of Gets with no entries found GetNoEnt. You can refer to the CollectionAnomalies() function\n// for ideas on what can be gleaned from these statistics about collections.\ntype JStatRec struct {\n\tSource           CollectionSource\n\tMaxSize          int\n\tCurSize          int\n\tGets             int\n\tGetHits          int\n\tGetMisses        int\n\tGetHashConflicts int\n\tGetNoEnt         int\n\tPuts             int\n\tPutHits          int\n\tPutMisses        int\n\tPutHashConflicts int\n\tMaxSlotSize      int\n\tDescription      string\n\tCreateStack      []byte\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/token.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype TokenSourceCharStreamPair struct {\n\ttokenSource TokenSource\n\tcharStream  CharStream\n}\n\n// A token has properties: text, type, line, character position in the line\n// (so we can ignore tabs), token channel, index, and source from which\n// we obtained this token.\n\ntype Token interface {\n\tGetSource() *TokenSourceCharStreamPair\n\tGetTokenType() int\n\tGetChannel() int\n\tGetStart() int\n\tGetStop() int\n\tGetLine() int\n\tGetColumn() int\n\n\tGetText() string\n\tSetText(s string)\n\n\tGetTokenIndex() int\n\tSetTokenIndex(v int)\n\n\tGetTokenSource() TokenSource\n\tGetInputStream() CharStream\n\n\tString() string\n}\n\ntype BaseToken struct {\n\tsource     *TokenSourceCharStreamPair\n\ttokenType  int    // token type of the token\n\tchannel    int    // The parser ignores everything not on DEFAULT_CHANNEL\n\tstart      int    // optional return -1 if not implemented.\n\tstop       int    // optional return -1 if not implemented.\n\ttokenIndex int    // from 0..n-1 of the token object in the input stream\n\tline       int    // line=1..n of the 1st character\n\tcolumn     int    // beginning of the line at which it occurs, 0..n-1\n\ttext       string // text of the token.\n\treadOnly   bool\n}\n\nconst (\n\tTokenInvalidType = 0\n\n\t// TokenEpsilon  - during lookahead operations, this \"token\" signifies we hit the rule end [ATN] state\n\t// and did not follow it despite needing to.\n\tTokenEpsilon = -2\n\n\tTokenMinUserTokenType = 1\n\n\tTokenEOF = -1\n\n\t// TokenDefaultChannel is the default channel upon which tokens are sent to the parser.\n\t//\n\t// All tokens go to the parser (unless [Skip] is called in the lexer rule)\n\t// on a particular \"channel\". The parser tunes to a particular channel\n\t// so that whitespace etc... can go to the parser on a \"hidden\" channel.\n\tTokenDefaultChannel = 0\n\n\t// TokenHiddenChannel defines the normal hidden channel - the parser wil not see tokens that are not on [TokenDefaultChannel].\n\t//\n\t// Anything on a different channel than TokenDefaultChannel is not parsed by parser.\n\tTokenHiddenChannel = 1\n)\n\nfunc (b *BaseToken) GetChannel() int {\n\treturn b.channel\n}\n\nfunc (b *BaseToken) GetStart() int {\n\treturn b.start\n}\n\nfunc (b *BaseToken) GetStop() int {\n\treturn b.stop\n}\n\nfunc (b *BaseToken) GetLine() int {\n\treturn b.line\n}\n\nfunc (b *BaseToken) GetColumn() int {\n\treturn b.column\n}\n\nfunc (b *BaseToken) GetTokenType() int {\n\treturn b.tokenType\n}\n\nfunc (b *BaseToken) GetSource() *TokenSourceCharStreamPair {\n\treturn b.source\n}\n\nfunc (b *BaseToken) GetText() string {\n\tif b.text != \"\" {\n\t\treturn b.text\n\t}\n\tinput := b.GetInputStream()\n\tif input == nil {\n\t\treturn \"\"\n\t}\n\tn := input.Size()\n\tif b.GetStart() < n && b.GetStop() < n {\n\t\treturn input.GetTextFromInterval(NewInterval(b.GetStart(), b.GetStop()))\n\t}\n\treturn \"<EOF>\"\n}\n\nfunc (b *BaseToken) SetText(text string) {\n\tb.text = text\n}\n\nfunc (b *BaseToken) GetTokenIndex() int {\n\treturn b.tokenIndex\n}\n\nfunc (b *BaseToken) SetTokenIndex(v int) {\n\tb.tokenIndex = v\n}\n\nfunc (b *BaseToken) GetTokenSource() TokenSource {\n\treturn b.source.tokenSource\n}\n\nfunc (b *BaseToken) GetInputStream() CharStream {\n\treturn b.source.charStream\n}\n\nfunc (b *BaseToken) String() string {\n\ttxt := b.GetText()\n\tif txt != \"\" {\n\t\ttxt = strings.Replace(txt, \"\\n\", \"\\\\n\", -1)\n\t\ttxt = strings.Replace(txt, \"\\r\", \"\\\\r\", -1)\n\t\ttxt = strings.Replace(txt, \"\\t\", \"\\\\t\", -1)\n\t} else {\n\t\ttxt = \"<no text>\"\n\t}\n\n\tvar ch string\n\tif b.GetChannel() > 0 {\n\t\tch = \",channel=\" + strconv.Itoa(b.GetChannel())\n\t} else {\n\t\tch = \"\"\n\t}\n\n\treturn \"[@\" + strconv.Itoa(b.GetTokenIndex()) + \",\" + strconv.Itoa(b.GetStart()) + \":\" + strconv.Itoa(b.GetStop()) + \"='\" +\n\t\ttxt + \"',<\" + strconv.Itoa(b.GetTokenType()) + \">\" +\n\t\tch + \",\" + strconv.Itoa(b.GetLine()) + \":\" + strconv.Itoa(b.GetColumn()) + \"]\"\n}\n\ntype CommonToken struct {\n\tBaseToken\n}\n\nfunc NewCommonToken(source *TokenSourceCharStreamPair, tokenType, channel, start, stop int) *CommonToken {\n\n\tt := &CommonToken{\n\t\tBaseToken: BaseToken{\n\t\t\tsource:     source,\n\t\t\ttokenType:  tokenType,\n\t\t\tchannel:    channel,\n\t\t\tstart:      start,\n\t\t\tstop:       stop,\n\t\t\ttokenIndex: -1,\n\t\t},\n\t}\n\n\tif t.source.tokenSource != nil {\n\t\tt.line = source.tokenSource.GetLine()\n\t\tt.column = source.tokenSource.GetCharPositionInLine()\n\t} else {\n\t\tt.column = -1\n\t}\n\treturn t\n}\n\n// An empty {@link Pair} which is used as the default value of\n// {@link //source} for tokens that do not have a source.\n\n//CommonToken.EMPTY_SOURCE = [ nil, nil ]\n\n// Constructs a New{@link CommonToken} as a copy of another {@link Token}.\n//\n// <p>\n// If {@code oldToken} is also a {@link CommonToken} instance, the newly\n// constructed token will share a reference to the {@link //text} field and\n// the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will\n// be assigned the result of calling {@link //GetText}, and {@link //source}\n// will be constructed from the result of {@link Token//GetTokenSource} and\n// {@link Token//GetInputStream}.</p>\n//\n// @param oldToken The token to copy.\nfunc (c *CommonToken) clone() *CommonToken {\n\tt := NewCommonToken(c.source, c.tokenType, c.channel, c.start, c.stop)\n\tt.tokenIndex = c.GetTokenIndex()\n\tt.line = c.GetLine()\n\tt.column = c.GetColumn()\n\tt.text = c.GetText()\n\treturn t\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/token_source.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\ntype TokenSource interface {\n\tNextToken() Token\n\tSkip()\n\tMore()\n\tGetLine() int\n\tGetCharPositionInLine() int\n\tGetInputStream() CharStream\n\tGetSourceName() string\n\tsetTokenFactory(factory TokenFactory)\n\tGetTokenFactory() TokenFactory\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/token_stream.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\ntype TokenStream interface {\n\tIntStream\n\n\tLT(k int) Token\n\tReset()\n\n\tGet(index int) Token\n\tGetTokenSource() TokenSource\n\tSetTokenSource(TokenSource)\n\n\tGetAllText() string\n\tGetTextFromInterval(Interval) string\n\tGetTextFromRuleContext(RuleContext) string\n\tGetTextFromTokens(Token, Token) string\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/tokenstream_rewriter.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n//\n// Useful for rewriting out a buffered input token stream after doing some\n// augmentation or other manipulations on it.\n\n// <p>\n// You can insert stuff, replace, and delete chunks. Note that the operations\n// are done lazily--only if you convert the buffer to a {@link String} with\n// {@link TokenStream#getText()}. This is very efficient because you are not\n// moving data around all the time. As the buffer of tokens is converted to\n// strings, the {@link #getText()} method(s) scan the input token stream and\n// check to see if there is an operation at the current index. If so, the\n// operation is done and then normal {@link String} rendering continues on the\n// buffer. This is like having multiple Turing machine instruction streams\n// (programs) operating on a single input tape. :)</p>\n// <p>\n\n// This rewriter makes no modifications to the token stream. It does not ask the\n// stream to fill itself up nor does it advance the input cursor. The token\n// stream {@link TokenStream#index()} will return the same value before and\n// after any {@link #getText()} call.</p>\n\n// <p>\n// The rewriter only works on tokens that you have in the buffer and ignores the\n// current input cursor. If you are buffering tokens on-demand, calling\n// {@link #getText()} halfway through the input will only do rewrites for those\n// tokens in the first half of the file.</p>\n\n// <p>\n// Since the operations are done lazily at {@link #getText}-time, operations do\n// not screw up the token index values. That is, an insert operation at token\n// index {@code i} does not change the index values for tokens\n// {@code i}+1..n-1.</p>\n\n// <p>\n// Because operations never actually alter the buffer, you may always get the\n// original token stream back without undoing anything. Since the instructions\n// are queued up, you can easily simulate transactions and roll back any changes\n// if there is an error just by removing instructions. For example,</p>\n\n// <pre>\n// CharStream input = new ANTLRFileStream(\"input\");\n// TLexer lex = new TLexer(input);\n// CommonTokenStream tokens = new CommonTokenStream(lex);\n// T parser = new T(tokens);\n// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);\n// parser.startRule();\n// </pre>\n\n// <p>\n// Then in the rules, you can execute (assuming rewriter is visible):</p>\n\n// <pre>\n// Token t,u;\n// ...\n// rewriter.insertAfter(t, \"text to put after t\");}\n// rewriter.insertAfter(u, \"text after u\");}\n// System.out.println(rewriter.getText());\n// </pre>\n\n// <p>\n// You can also have multiple \"instruction streams\" and get multiple rewrites\n// from a single pass over the input. Just name the instruction streams and use\n// that name again when printing the buffer. This could be useful for generating\n// a C file and also its header file--all from the same buffer:</p>\n\n// <pre>\n// rewriter.insertAfter(\"pass1\", t, \"text to put after t\");}\n// rewriter.insertAfter(\"pass2\", u, \"text after u\");}\n// System.out.println(rewriter.getText(\"pass1\"));\n// System.out.println(rewriter.getText(\"pass2\"));\n// </pre>\n\n// <p>\n// If you don't use named rewrite streams, a \"default\" stream is used as the\n// first example shows.</p>\n\nconst (\n\tDefaultProgramName = \"default\"\n\tProgramInitSize    = 100\n\tMinTokenIndex      = 0\n)\n\n// Define the rewrite operation hierarchy\n\ntype RewriteOperation interface {\n\n\t// Execute the rewrite operation by possibly adding to the buffer.\n\t// Return the index of the next token to operate on.\n\tExecute(buffer *bytes.Buffer) int\n\tString() string\n\tGetInstructionIndex() int\n\tGetIndex() int\n\tGetText() string\n\tGetOpName() string\n\tGetTokens() TokenStream\n\tSetInstructionIndex(val int)\n\tSetIndex(int)\n\tSetText(string)\n\tSetOpName(string)\n\tSetTokens(TokenStream)\n}\n\ntype BaseRewriteOperation struct {\n\t//Current index of rewrites list\n\tinstructionIndex int\n\t//Token buffer index\n\tindex int\n\t//Substitution text\n\ttext string\n\t//Actual operation name\n\topName string\n\t//Pointer to token steam\n\ttokens TokenStream\n}\n\nfunc (op *BaseRewriteOperation) GetInstructionIndex() int {\n\treturn op.instructionIndex\n}\n\nfunc (op *BaseRewriteOperation) GetIndex() int {\n\treturn op.index\n}\n\nfunc (op *BaseRewriteOperation) GetText() string {\n\treturn op.text\n}\n\nfunc (op *BaseRewriteOperation) GetOpName() string {\n\treturn op.opName\n}\n\nfunc (op *BaseRewriteOperation) GetTokens() TokenStream {\n\treturn op.tokens\n}\n\nfunc (op *BaseRewriteOperation) SetInstructionIndex(val int) {\n\top.instructionIndex = val\n}\n\nfunc (op *BaseRewriteOperation) SetIndex(val int) {\n\top.index = val\n}\n\nfunc (op *BaseRewriteOperation) SetText(val string) {\n\top.text = val\n}\n\nfunc (op *BaseRewriteOperation) SetOpName(val string) {\n\top.opName = val\n}\n\nfunc (op *BaseRewriteOperation) SetTokens(val TokenStream) {\n\top.tokens = val\n}\n\nfunc (op *BaseRewriteOperation) Execute(_ *bytes.Buffer) int {\n\treturn op.index\n}\n\nfunc (op *BaseRewriteOperation) String() string {\n\treturn fmt.Sprintf(\"<%s@%d:\\\"%s\\\">\",\n\t\top.opName,\n\t\top.tokens.Get(op.GetIndex()),\n\t\top.text,\n\t)\n\n}\n\ntype InsertBeforeOp struct {\n\tBaseRewriteOperation\n}\n\nfunc NewInsertBeforeOp(index int, text string, stream TokenStream) *InsertBeforeOp {\n\treturn &InsertBeforeOp{BaseRewriteOperation: BaseRewriteOperation{\n\t\tindex:  index,\n\t\ttext:   text,\n\t\topName: \"InsertBeforeOp\",\n\t\ttokens: stream,\n\t}}\n}\n\nfunc (op *InsertBeforeOp) Execute(buffer *bytes.Buffer) int {\n\tbuffer.WriteString(op.text)\n\tif op.tokens.Get(op.index).GetTokenType() != TokenEOF {\n\t\tbuffer.WriteString(op.tokens.Get(op.index).GetText())\n\t}\n\treturn op.index + 1\n}\n\nfunc (op *InsertBeforeOp) String() string {\n\treturn op.BaseRewriteOperation.String()\n}\n\n// InsertAfterOp distinguishes between insert after/before to do the \"insert after\" instructions\n// first and then the \"insert before\" instructions at same index. Implementation\n// of \"insert after\" is \"insert before index+1\".\ntype InsertAfterOp struct {\n\tBaseRewriteOperation\n}\n\nfunc NewInsertAfterOp(index int, text string, stream TokenStream) *InsertAfterOp {\n\treturn &InsertAfterOp{\n\t\tBaseRewriteOperation: BaseRewriteOperation{\n\t\t\tindex:  index + 1,\n\t\t\ttext:   text,\n\t\t\ttokens: stream,\n\t\t},\n\t}\n}\n\nfunc (op *InsertAfterOp) Execute(buffer *bytes.Buffer) int {\n\tbuffer.WriteString(op.text)\n\tif op.tokens.Get(op.index).GetTokenType() != TokenEOF {\n\t\tbuffer.WriteString(op.tokens.Get(op.index).GetText())\n\t}\n\treturn op.index + 1\n}\n\nfunc (op *InsertAfterOp) String() string {\n\treturn op.BaseRewriteOperation.String()\n}\n\n// ReplaceOp tries to replace range from x..y with (y-x)+1 ReplaceOp\n// instructions.\ntype ReplaceOp struct {\n\tBaseRewriteOperation\n\tLastIndex int\n}\n\nfunc NewReplaceOp(from, to int, text string, stream TokenStream) *ReplaceOp {\n\treturn &ReplaceOp{\n\t\tBaseRewriteOperation: BaseRewriteOperation{\n\t\t\tindex:  from,\n\t\t\ttext:   text,\n\t\t\topName: \"ReplaceOp\",\n\t\t\ttokens: stream,\n\t\t},\n\t\tLastIndex: to,\n\t}\n}\n\nfunc (op *ReplaceOp) Execute(buffer *bytes.Buffer) int {\n\tif op.text != \"\" {\n\t\tbuffer.WriteString(op.text)\n\t}\n\treturn op.LastIndex + 1\n}\n\nfunc (op *ReplaceOp) String() string {\n\tif op.text == \"\" {\n\t\treturn fmt.Sprintf(\"<DeleteOP@%d..%d>\",\n\t\t\top.tokens.Get(op.index), op.tokens.Get(op.LastIndex))\n\t}\n\treturn fmt.Sprintf(\"<ReplaceOp@%d..%d:\\\"%s\\\">\",\n\t\top.tokens.Get(op.index), op.tokens.Get(op.LastIndex), op.text)\n}\n\ntype TokenStreamRewriter struct {\n\t//Our source stream\n\ttokens TokenStream\n\t// You may have multiple, named streams of rewrite operations.\n\t//  I'm calling these things \"programs.\"\n\t//  Maps String (name) &rarr; rewrite (List)\n\tprograms                map[string][]RewriteOperation\n\tlastRewriteTokenIndexes map[string]int\n}\n\nfunc NewTokenStreamRewriter(tokens TokenStream) *TokenStreamRewriter {\n\treturn &TokenStreamRewriter{\n\t\ttokens: tokens,\n\t\tprograms: map[string][]RewriteOperation{\n\t\t\tDefaultProgramName: make([]RewriteOperation, 0, ProgramInitSize),\n\t\t},\n\t\tlastRewriteTokenIndexes: map[string]int{},\n\t}\n}\n\nfunc (tsr *TokenStreamRewriter) GetTokenStream() TokenStream {\n\treturn tsr.tokens\n}\n\n// Rollback the instruction stream for a program so that\n// the indicated instruction (via instructionIndex) is no\n// longer in the stream. UNTESTED!\nfunc (tsr *TokenStreamRewriter) Rollback(programName string, instructionIndex int) {\n\tis, ok := tsr.programs[programName]\n\tif ok {\n\t\ttsr.programs[programName] = is[MinTokenIndex:instructionIndex]\n\t}\n}\n\nfunc (tsr *TokenStreamRewriter) RollbackDefault(instructionIndex int) {\n\ttsr.Rollback(DefaultProgramName, instructionIndex)\n}\n\n// DeleteProgram Reset the program so that no instructions exist\nfunc (tsr *TokenStreamRewriter) DeleteProgram(programName string) {\n\ttsr.Rollback(programName, MinTokenIndex) //TODO: double test on that cause lower bound is not included\n}\n\nfunc (tsr *TokenStreamRewriter) DeleteProgramDefault() {\n\ttsr.DeleteProgram(DefaultProgramName)\n}\n\nfunc (tsr *TokenStreamRewriter) InsertAfter(programName string, index int, text string) {\n\t// to insert after, just insert before next index (even if past end)\n\tvar op RewriteOperation = NewInsertAfterOp(index, text, tsr.tokens)\n\trewrites := tsr.GetProgram(programName)\n\top.SetInstructionIndex(len(rewrites))\n\ttsr.AddToProgram(programName, op)\n}\n\nfunc (tsr *TokenStreamRewriter) InsertAfterDefault(index int, text string) {\n\ttsr.InsertAfter(DefaultProgramName, index, text)\n}\n\nfunc (tsr *TokenStreamRewriter) InsertAfterToken(programName string, token Token, text string) {\n\ttsr.InsertAfter(programName, token.GetTokenIndex(), text)\n}\n\nfunc (tsr *TokenStreamRewriter) InsertBefore(programName string, index int, text string) {\n\tvar op RewriteOperation = NewInsertBeforeOp(index, text, tsr.tokens)\n\trewrites := tsr.GetProgram(programName)\n\top.SetInstructionIndex(len(rewrites))\n\ttsr.AddToProgram(programName, op)\n}\n\nfunc (tsr *TokenStreamRewriter) InsertBeforeDefault(index int, text string) {\n\ttsr.InsertBefore(DefaultProgramName, index, text)\n}\n\nfunc (tsr *TokenStreamRewriter) InsertBeforeToken(programName string, token Token, text string) {\n\ttsr.InsertBefore(programName, token.GetTokenIndex(), text)\n}\n\nfunc (tsr *TokenStreamRewriter) Replace(programName string, from, to int, text string) {\n\tif from > to || from < 0 || to < 0 || to >= tsr.tokens.Size() {\n\t\tpanic(fmt.Sprintf(\"replace: range invalid: %d..%d(size=%d)\",\n\t\t\tfrom, to, tsr.tokens.Size()))\n\t}\n\tvar op RewriteOperation = NewReplaceOp(from, to, text, tsr.tokens)\n\trewrites := tsr.GetProgram(programName)\n\top.SetInstructionIndex(len(rewrites))\n\ttsr.AddToProgram(programName, op)\n}\n\nfunc (tsr *TokenStreamRewriter) ReplaceDefault(from, to int, text string) {\n\ttsr.Replace(DefaultProgramName, from, to, text)\n}\n\nfunc (tsr *TokenStreamRewriter) ReplaceDefaultPos(index int, text string) {\n\ttsr.ReplaceDefault(index, index, text)\n}\n\nfunc (tsr *TokenStreamRewriter) ReplaceToken(programName string, from, to Token, text string) {\n\ttsr.Replace(programName, from.GetTokenIndex(), to.GetTokenIndex(), text)\n}\n\nfunc (tsr *TokenStreamRewriter) ReplaceTokenDefault(from, to Token, text string) {\n\ttsr.ReplaceToken(DefaultProgramName, from, to, text)\n}\n\nfunc (tsr *TokenStreamRewriter) ReplaceTokenDefaultPos(index Token, text string) {\n\ttsr.ReplaceTokenDefault(index, index, text)\n}\n\nfunc (tsr *TokenStreamRewriter) Delete(programName string, from, to int) {\n\ttsr.Replace(programName, from, to, \"\")\n}\n\nfunc (tsr *TokenStreamRewriter) DeleteDefault(from, to int) {\n\ttsr.Delete(DefaultProgramName, from, to)\n}\n\nfunc (tsr *TokenStreamRewriter) DeleteDefaultPos(index int) {\n\ttsr.DeleteDefault(index, index)\n}\n\nfunc (tsr *TokenStreamRewriter) DeleteToken(programName string, from, to Token) {\n\ttsr.ReplaceToken(programName, from, to, \"\")\n}\n\nfunc (tsr *TokenStreamRewriter) DeleteTokenDefault(from, to Token) {\n\ttsr.DeleteToken(DefaultProgramName, from, to)\n}\n\nfunc (tsr *TokenStreamRewriter) GetLastRewriteTokenIndex(programName string) int {\n\ti, ok := tsr.lastRewriteTokenIndexes[programName]\n\tif !ok {\n\t\treturn -1\n\t}\n\treturn i\n}\n\nfunc (tsr *TokenStreamRewriter) GetLastRewriteTokenIndexDefault() int {\n\treturn tsr.GetLastRewriteTokenIndex(DefaultProgramName)\n}\n\nfunc (tsr *TokenStreamRewriter) SetLastRewriteTokenIndex(programName string, i int) {\n\ttsr.lastRewriteTokenIndexes[programName] = i\n}\n\nfunc (tsr *TokenStreamRewriter) InitializeProgram(name string) []RewriteOperation {\n\tis := make([]RewriteOperation, 0, ProgramInitSize)\n\ttsr.programs[name] = is\n\treturn is\n}\n\nfunc (tsr *TokenStreamRewriter) AddToProgram(name string, op RewriteOperation) {\n\tis := tsr.GetProgram(name)\n\tis = append(is, op)\n\ttsr.programs[name] = is\n}\n\nfunc (tsr *TokenStreamRewriter) GetProgram(name string) []RewriteOperation {\n\tis, ok := tsr.programs[name]\n\tif !ok {\n\t\tis = tsr.InitializeProgram(name)\n\t}\n\treturn is\n}\n\n// GetTextDefault returns the text from the original tokens altered per the\n// instructions given to this rewriter.\nfunc (tsr *TokenStreamRewriter) GetTextDefault() string {\n\treturn tsr.GetText(\n\t\tDefaultProgramName,\n\t\tNewInterval(0, tsr.tokens.Size()-1))\n}\n\n// GetText returns the text from the original tokens altered per the\n// instructions given to this rewriter.\nfunc (tsr *TokenStreamRewriter) GetText(programName string, interval Interval) string {\n\trewrites := tsr.programs[programName]\n\tstart := interval.Start\n\tstop := interval.Stop\n\t// ensure start/end are in range\n\tstop = min(stop, tsr.tokens.Size()-1)\n\tstart = max(start, 0)\n\tif len(rewrites) == 0 {\n\t\treturn tsr.tokens.GetTextFromInterval(interval) // no instructions to execute\n\t}\n\tbuf := bytes.Buffer{}\n\t// First, optimize instruction stream\n\tindexToOp := reduceToSingleOperationPerIndex(rewrites)\n\t// Walk buffer, executing instructions and emitting tokens\n\tfor i := start; i <= stop && i < tsr.tokens.Size(); {\n\t\top := indexToOp[i]\n\t\tdelete(indexToOp, i) // remove so any left have index size-1\n\t\tt := tsr.tokens.Get(i)\n\t\tif op == nil {\n\t\t\t// no operation at that index, just dump token\n\t\t\tif t.GetTokenType() != TokenEOF {\n\t\t\t\tbuf.WriteString(t.GetText())\n\t\t\t}\n\t\t\ti++ // move to next token\n\t\t} else {\n\t\t\ti = op.Execute(&buf) // execute operation and skip\n\t\t}\n\t}\n\t// include stuff after end if it's last index in buffer\n\t// So, if they did an insertAfter(lastValidIndex, \"foo\"), include\n\t// foo if end==lastValidIndex.\n\tif stop == tsr.tokens.Size()-1 {\n\t\t// Scan any remaining operations after last token\n\t\t// should be included (they will be inserts).\n\t\tfor _, op := range indexToOp {\n\t\t\tif op.GetIndex() >= tsr.tokens.Size()-1 {\n\t\t\t\tbuf.WriteString(op.GetText())\n\t\t\t}\n\t\t}\n\t}\n\treturn buf.String()\n}\n\n// reduceToSingleOperationPerIndex combines operations and report invalid operations (like\n// overlapping replaces that are not completed nested). Inserts to\n// same index need to be combined etc...\n//\n// Here are the cases:\n//\n//\t I.i.u I.j.v\t\t\t\t\t\t\t\tleave alone, non-overlapping\n//\t I.i.u I.i.v\t\t\t\t\t\t\t\tcombine: Iivu\n//\n//\t R.i-j.u R.x-y.v\t| i-j in x-y\t\t\tdelete first R\n//\t R.i-j.u R.i-j.v\t\t\t\t\t\t\tdelete first R\n//\t R.i-j.u R.x-y.v\t| x-y in i-j\t\t\tERROR\n//\t R.i-j.u R.x-y.v\t| boundaries overlap\tERROR\n//\n//\t Delete special case of replace (text==null):\n//\t D.i-j.u D.x-y.v\t| boundaries overlap\tcombine to max(min)..max(right)\n//\n//\t I.i.u R.x-y.v | i in (x+1)-y\t\t\tdelete I (since insert before\n//\t\t\t\t\t\t\t\t\t\t\t\t\twe're not deleting i)\n//\t I.i.u R.x-y.v | i not in (x+1)-y\t\tleave alone, non-overlapping\n//\t R.x-y.v I.i.u | i in x-y\t\t\t\tERROR\n//\t R.x-y.v I.x.u \t\t\t\t\t\t\tR.x-y.uv (combine, delete I)\n//\t R.x-y.v I.i.u | i not in x-y\t\t\tleave alone, non-overlapping\n//\n//\t I.i.u = insert u before op @ index i\n//\t R.x-y.u = replace x-y indexed tokens with u\n//\n// First we need to examine replaces. For any replace op:\n//\n//  1. wipe out any insertions before op within that range.\n//  2. Drop any replace op before that is contained completely within\n//     that range.\n//  3. Throw exception upon boundary overlap with any previous replace.\n//\n// Then we can deal with inserts:\n//\n//  1. for any inserts to same index, combine even if not adjacent.\n//  2. for any prior replace with same left boundary, combine this\n//     insert with replace and delete this 'replace'.\n//  3. throw exception if index in same range as previous replace\n//\n// Don't actually delete; make op null in list. Easier to walk list.\n// Later we can throw as we add to index &rarr; op map.\n//\n// Note that I.2 R.2-2 will wipe out I.2 even though, technically, the\n// inserted stuff would be before the 'replace' range. But, if you\n// add tokens in front of a method body '{' and then delete the method\n// body, I think the stuff before the '{' you added should disappear too.\n//\n// The func returns a map from token index to operation.\nfunc reduceToSingleOperationPerIndex(rewrites []RewriteOperation) map[int]RewriteOperation {\n\t// WALK REPLACES\n\tfor i := 0; i < len(rewrites); i++ {\n\t\top := rewrites[i]\n\t\tif op == nil {\n\t\t\tcontinue\n\t\t}\n\t\trop, ok := op.(*ReplaceOp)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\t// Wipe prior inserts within range\n\t\tfor j := 0; j < i && j < len(rewrites); j++ {\n\t\t\tif iop, ok := rewrites[j].(*InsertBeforeOp); ok {\n\t\t\t\tif iop.index == rop.index {\n\t\t\t\t\t// E.g., insert before 2, delete 2..2; update replace\n\t\t\t\t\t// text to include insert before, kill insert\n\t\t\t\t\trewrites[iop.instructionIndex] = nil\n\t\t\t\t\tif rop.text != \"\" {\n\t\t\t\t\t\trop.text = iop.text + rop.text\n\t\t\t\t\t} else {\n\t\t\t\t\t\trop.text = iop.text\n\t\t\t\t\t}\n\t\t\t\t} else if iop.index > rop.index && iop.index <= rop.LastIndex {\n\t\t\t\t\t// delete insert as it's a no-op.\n\t\t\t\t\trewrites[iop.instructionIndex] = nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Drop any prior replaces contained within\n\t\tfor j := 0; j < i && j < len(rewrites); j++ {\n\t\t\tif prevop, ok := rewrites[j].(*ReplaceOp); ok {\n\t\t\t\tif prevop.index >= rop.index && prevop.LastIndex <= rop.LastIndex {\n\t\t\t\t\t// delete replace as it's a no-op.\n\t\t\t\t\trewrites[prevop.instructionIndex] = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// throw exception unless disjoint or identical\n\t\t\t\tdisjoint := prevop.LastIndex < rop.index || prevop.index > rop.LastIndex\n\t\t\t\t// Delete special case of replace (text==null):\n\t\t\t\t// D.i-j.u D.x-y.v\t| boundaries overlap\tcombine to max(min)..max(right)\n\t\t\t\tif prevop.text == \"\" && rop.text == \"\" && !disjoint {\n\t\t\t\t\trewrites[prevop.instructionIndex] = nil\n\t\t\t\t\trop.index = min(prevop.index, rop.index)\n\t\t\t\t\trop.LastIndex = max(prevop.LastIndex, rop.LastIndex)\n\t\t\t\t} else if !disjoint {\n\t\t\t\t\tpanic(\"replace op boundaries of \" + rop.String() + \" overlap with previous \" + prevop.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// WALK INSERTS\n\tfor i := 0; i < len(rewrites); i++ {\n\t\top := rewrites[i]\n\t\tif op == nil {\n\t\t\tcontinue\n\t\t}\n\t\t//hack to replicate inheritance in composition\n\t\t_, iok := rewrites[i].(*InsertBeforeOp)\n\t\t_, aok := rewrites[i].(*InsertAfterOp)\n\t\tif !iok && !aok {\n\t\t\tcontinue\n\t\t}\n\t\tiop := rewrites[i]\n\t\t// combine current insert with prior if any at same index\n\t\t// deviating a bit from TokenStreamRewriter.java - hard to incorporate inheritance logic\n\t\tfor j := 0; j < i && j < len(rewrites); j++ {\n\t\t\tif nextIop, ok := rewrites[j].(*InsertAfterOp); ok {\n\t\t\t\tif nextIop.index == iop.GetIndex() {\n\t\t\t\t\tiop.SetText(nextIop.text + iop.GetText())\n\t\t\t\t\trewrites[j] = nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tif prevIop, ok := rewrites[j].(*InsertBeforeOp); ok {\n\t\t\t\tif prevIop.index == iop.GetIndex() {\n\t\t\t\t\tiop.SetText(iop.GetText() + prevIop.text)\n\t\t\t\t\trewrites[prevIop.instructionIndex] = nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// look for replaces where iop.index is in range; error\n\t\tfor j := 0; j < i && j < len(rewrites); j++ {\n\t\t\tif rop, ok := rewrites[j].(*ReplaceOp); ok {\n\t\t\t\tif iop.GetIndex() == rop.index {\n\t\t\t\t\trop.text = iop.GetText() + rop.text\n\t\t\t\t\trewrites[i] = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif iop.GetIndex() >= rop.index && iop.GetIndex() <= rop.LastIndex {\n\t\t\t\t\tpanic(\"insert op \" + iop.String() + \" within boundaries of previous \" + rop.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tm := map[int]RewriteOperation{}\n\tfor i := 0; i < len(rewrites); i++ {\n\t\top := rewrites[i]\n\t\tif op == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := m[op.GetIndex()]; ok {\n\t\t\tpanic(\"should only be one op per index\")\n\t\t}\n\t\tm[op.GetIndex()] = op\n\t}\n\treturn m\n}\n\n/*\n\tQuick fixing Go lack of overloads\n*/\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/trace_listener.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport \"fmt\"\n\ntype TraceListener struct {\n\tparser *BaseParser\n}\n\nfunc NewTraceListener(parser *BaseParser) *TraceListener {\n\ttl := new(TraceListener)\n\ttl.parser = parser\n\treturn tl\n}\n\nfunc (t *TraceListener) VisitErrorNode(_ ErrorNode) {\n}\n\nfunc (t *TraceListener) EnterEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"enter   \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n\nfunc (t *TraceListener) VisitTerminal(node TerminalNode) {\n\tfmt.Println(\"consume \" + fmt.Sprint(node.GetSymbol()) + \" rule \" + t.parser.GetRuleNames()[t.parser.ctx.GetRuleIndex()])\n}\n\nfunc (t *TraceListener) ExitEveryRule(ctx ParserRuleContext) {\n\tfmt.Println(\"exit    \" + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + \", LT(1)=\" + t.parser.input.LT(1).GetText())\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/transition.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n//  atom, set, epsilon, action, predicate, rule transitions.\n//\n//  <p>This is a one way link.  It emanates from a state (usually via a list of\n//  transitions) and has a target state.</p>\n//\n//  <p>Since we never have to change the ATN transitions once we construct it,\n//  the states. We'll use the term Edge for the DFA to distinguish them from\n//  ATN transitions.</p>\n\ntype Transition interface {\n\tgetTarget() ATNState\n\tsetTarget(ATNState)\n\tgetIsEpsilon() bool\n\tgetLabel() *IntervalSet\n\tgetSerializationType() int\n\tMatches(int, int, int) bool\n}\n\ntype BaseTransition struct {\n\ttarget            ATNState\n\tisEpsilon         bool\n\tlabel             int\n\tintervalSet       *IntervalSet\n\tserializationType int\n}\n\nfunc NewBaseTransition(target ATNState) *BaseTransition {\n\n\tif target == nil {\n\t\tpanic(\"target cannot be nil.\")\n\t}\n\n\tt := new(BaseTransition)\n\n\tt.target = target\n\t// Are we epsilon, action, sempred?\n\tt.isEpsilon = false\n\tt.intervalSet = nil\n\n\treturn t\n}\n\nfunc (t *BaseTransition) getTarget() ATNState {\n\treturn t.target\n}\n\nfunc (t *BaseTransition) setTarget(s ATNState) {\n\tt.target = s\n}\n\nfunc (t *BaseTransition) getIsEpsilon() bool {\n\treturn t.isEpsilon\n}\n\nfunc (t *BaseTransition) getLabel() *IntervalSet {\n\treturn t.intervalSet\n}\n\nfunc (t *BaseTransition) getSerializationType() int {\n\treturn t.serializationType\n}\n\nfunc (t *BaseTransition) Matches(_, _, _ int) bool {\n\tpanic(\"Not implemented\")\n}\n\nconst (\n\tTransitionEPSILON    = 1\n\tTransitionRANGE      = 2\n\tTransitionRULE       = 3\n\tTransitionPREDICATE  = 4 // e.g., {isType(input.LT(1))}?\n\tTransitionATOM       = 5\n\tTransitionACTION     = 6\n\tTransitionSET        = 7 // ~(A|B) or ~atom, wildcard, which convert to next 2\n\tTransitionNOTSET     = 8\n\tTransitionWILDCARD   = 9\n\tTransitionPRECEDENCE = 10\n)\n\n//goland:noinspection GoUnusedGlobalVariable\nvar TransitionserializationNames = []string{\n\t\"INVALID\",\n\t\"EPSILON\",\n\t\"RANGE\",\n\t\"RULE\",\n\t\"PREDICATE\",\n\t\"ATOM\",\n\t\"ACTION\",\n\t\"SET\",\n\t\"NOT_SET\",\n\t\"WILDCARD\",\n\t\"PRECEDENCE\",\n}\n\n//var TransitionserializationTypes struct {\n//\tEpsilonTransition int\n//\tRangeTransition int\n//\tRuleTransition int\n//\tPredicateTransition int\n//\tAtomTransition int\n//\tActionTransition int\n//\tSetTransition int\n//\tNotSetTransition int\n//\tWildcardTransition int\n//\tPrecedencePredicateTransition int\n//}{\n//\tTransitionEPSILON,\n//\tTransitionRANGE,\n//\tTransitionRULE,\n//\tTransitionPREDICATE,\n//\tTransitionATOM,\n//\tTransitionACTION,\n//\tTransitionSET,\n//\tTransitionNOTSET,\n//\tTransitionWILDCARD,\n//\tTransitionPRECEDENCE\n//}\n\n// AtomTransition\n// TODO: make all transitions sets? no, should remove set edges\ntype AtomTransition struct {\n\tBaseTransition\n}\n\nfunc NewAtomTransition(target ATNState, intervalSet int) *AtomTransition {\n\tt := &AtomTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget:            target,\n\t\t\tserializationType: TransitionATOM,\n\t\t\tlabel:             intervalSet,\n\t\t\tisEpsilon:         false,\n\t\t},\n\t}\n\tt.intervalSet = t.makeLabel()\n\n\treturn t\n}\n\nfunc (t *AtomTransition) makeLabel() *IntervalSet {\n\ts := NewIntervalSet()\n\ts.addOne(t.label)\n\treturn s\n}\n\nfunc (t *AtomTransition) Matches(symbol, _, _ int) bool {\n\treturn t.label == symbol\n}\n\nfunc (t *AtomTransition) String() string {\n\treturn strconv.Itoa(t.label)\n}\n\ntype RuleTransition struct {\n\tBaseTransition\n\tfollowState           ATNState\n\truleIndex, precedence int\n}\n\nfunc NewRuleTransition(ruleStart ATNState, ruleIndex, precedence int, followState ATNState) *RuleTransition {\n\treturn &RuleTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget:            ruleStart,\n\t\t\tisEpsilon:         true,\n\t\t\tserializationType: TransitionRULE,\n\t\t},\n\t\truleIndex:   ruleIndex,\n\t\tprecedence:  precedence,\n\t\tfollowState: followState,\n\t}\n}\n\nfunc (t *RuleTransition) Matches(_, _, _ int) bool {\n\treturn false\n}\n\ntype EpsilonTransition struct {\n\tBaseTransition\n\toutermostPrecedenceReturn int\n}\n\nfunc NewEpsilonTransition(target ATNState, outermostPrecedenceReturn int) *EpsilonTransition {\n\treturn &EpsilonTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget:            target,\n\t\t\tserializationType: TransitionEPSILON,\n\t\t\tisEpsilon:         true,\n\t\t},\n\t\toutermostPrecedenceReturn: outermostPrecedenceReturn,\n\t}\n}\n\nfunc (t *EpsilonTransition) Matches(_, _, _ int) bool {\n\treturn false\n}\n\nfunc (t *EpsilonTransition) String() string {\n\treturn \"epsilon\"\n}\n\ntype RangeTransition struct {\n\tBaseTransition\n\tstart, stop int\n}\n\nfunc NewRangeTransition(target ATNState, start, stop int) *RangeTransition {\n\tt := &RangeTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget:            target,\n\t\t\tserializationType: TransitionRANGE,\n\t\t\tisEpsilon:         false,\n\t\t},\n\t\tstart: start,\n\t\tstop:  stop,\n\t}\n\tt.intervalSet = t.makeLabel()\n\treturn t\n}\n\nfunc (t *RangeTransition) makeLabel() *IntervalSet {\n\ts := NewIntervalSet()\n\ts.addRange(t.start, t.stop)\n\treturn s\n}\n\nfunc (t *RangeTransition) Matches(symbol, _, _ int) bool {\n\treturn symbol >= t.start && symbol <= t.stop\n}\n\nfunc (t *RangeTransition) String() string {\n\tvar sb strings.Builder\n\tsb.WriteByte('\\'')\n\tsb.WriteRune(rune(t.start))\n\tsb.WriteString(\"'..'\")\n\tsb.WriteRune(rune(t.stop))\n\tsb.WriteByte('\\'')\n\treturn sb.String()\n}\n\ntype AbstractPredicateTransition interface {\n\tTransition\n\tIAbstractPredicateTransitionFoo()\n}\n\ntype BaseAbstractPredicateTransition struct {\n\tBaseTransition\n}\n\nfunc NewBasePredicateTransition(target ATNState) *BaseAbstractPredicateTransition {\n\treturn &BaseAbstractPredicateTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget: target,\n\t\t},\n\t}\n}\n\nfunc (a *BaseAbstractPredicateTransition) IAbstractPredicateTransitionFoo() {}\n\ntype PredicateTransition struct {\n\tBaseAbstractPredicateTransition\n\tisCtxDependent       bool\n\truleIndex, predIndex int\n}\n\nfunc NewPredicateTransition(target ATNState, ruleIndex, predIndex int, isCtxDependent bool) *PredicateTransition {\n\treturn &PredicateTransition{\n\t\tBaseAbstractPredicateTransition: BaseAbstractPredicateTransition{\n\t\t\tBaseTransition: BaseTransition{\n\t\t\t\ttarget:            target,\n\t\t\t\tserializationType: TransitionPREDICATE,\n\t\t\t\tisEpsilon:         true,\n\t\t\t},\n\t\t},\n\t\tisCtxDependent: isCtxDependent,\n\t\truleIndex:      ruleIndex,\n\t\tpredIndex:      predIndex,\n\t}\n}\n\nfunc (t *PredicateTransition) Matches(_, _, _ int) bool {\n\treturn false\n}\n\nfunc (t *PredicateTransition) getPredicate() *Predicate {\n\treturn NewPredicate(t.ruleIndex, t.predIndex, t.isCtxDependent)\n}\n\nfunc (t *PredicateTransition) String() string {\n\treturn \"pred_\" + strconv.Itoa(t.ruleIndex) + \":\" + strconv.Itoa(t.predIndex)\n}\n\ntype ActionTransition struct {\n\tBaseTransition\n\tisCtxDependent                    bool\n\truleIndex, actionIndex, predIndex int\n}\n\nfunc NewActionTransition(target ATNState, ruleIndex, actionIndex int, isCtxDependent bool) *ActionTransition {\n\treturn &ActionTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget:            target,\n\t\t\tserializationType: TransitionACTION,\n\t\t\tisEpsilon:         true,\n\t\t},\n\t\tisCtxDependent: isCtxDependent,\n\t\truleIndex:      ruleIndex,\n\t\tactionIndex:    actionIndex,\n\t}\n}\n\nfunc (t *ActionTransition) Matches(_, _, _ int) bool {\n\treturn false\n}\n\nfunc (t *ActionTransition) String() string {\n\treturn \"action_\" + strconv.Itoa(t.ruleIndex) + \":\" + strconv.Itoa(t.actionIndex)\n}\n\ntype SetTransition struct {\n\tBaseTransition\n}\n\nfunc NewSetTransition(target ATNState, set *IntervalSet) *SetTransition {\n\tt := &SetTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget:            target,\n\t\t\tserializationType: TransitionSET,\n\t\t},\n\t}\n\n\tif set != nil {\n\t\tt.intervalSet = set\n\t} else {\n\t\tt.intervalSet = NewIntervalSet()\n\t\tt.intervalSet.addOne(TokenInvalidType)\n\t}\n\treturn t\n}\n\nfunc (t *SetTransition) Matches(symbol, _, _ int) bool {\n\treturn t.intervalSet.contains(symbol)\n}\n\nfunc (t *SetTransition) String() string {\n\treturn t.intervalSet.String()\n}\n\ntype NotSetTransition struct {\n\tSetTransition\n}\n\nfunc NewNotSetTransition(target ATNState, set *IntervalSet) *NotSetTransition {\n\tt := &NotSetTransition{\n\t\tSetTransition: SetTransition{\n\t\t\tBaseTransition: BaseTransition{\n\t\t\t\ttarget:            target,\n\t\t\t\tserializationType: TransitionNOTSET,\n\t\t\t},\n\t\t},\n\t}\n\tif set != nil {\n\t\tt.intervalSet = set\n\t} else {\n\t\tt.intervalSet = NewIntervalSet()\n\t\tt.intervalSet.addOne(TokenInvalidType)\n\t}\n\n\treturn t\n}\n\nfunc (t *NotSetTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {\n\treturn symbol >= minVocabSymbol && symbol <= maxVocabSymbol && !t.intervalSet.contains(symbol)\n}\n\nfunc (t *NotSetTransition) String() string {\n\treturn \"~\" + t.intervalSet.String()\n}\n\ntype WildcardTransition struct {\n\tBaseTransition\n}\n\nfunc NewWildcardTransition(target ATNState) *WildcardTransition {\n\treturn &WildcardTransition{\n\t\tBaseTransition: BaseTransition{\n\t\t\ttarget:            target,\n\t\t\tserializationType: TransitionWILDCARD,\n\t\t},\n\t}\n}\n\nfunc (t *WildcardTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {\n\treturn symbol >= minVocabSymbol && symbol <= maxVocabSymbol\n}\n\nfunc (t *WildcardTransition) String() string {\n\treturn \".\"\n}\n\ntype PrecedencePredicateTransition struct {\n\tBaseAbstractPredicateTransition\n\tprecedence int\n}\n\nfunc NewPrecedencePredicateTransition(target ATNState, precedence int) *PrecedencePredicateTransition {\n\treturn &PrecedencePredicateTransition{\n\t\tBaseAbstractPredicateTransition: BaseAbstractPredicateTransition{\n\t\t\tBaseTransition: BaseTransition{\n\t\t\t\ttarget:            target,\n\t\t\t\tserializationType: TransitionPRECEDENCE,\n\t\t\t\tisEpsilon:         true,\n\t\t\t},\n\t\t},\n\t\tprecedence: precedence,\n\t}\n}\n\nfunc (t *PrecedencePredicateTransition) Matches(_, _, _ int) bool {\n\treturn false\n}\n\nfunc (t *PrecedencePredicateTransition) getPredicate() *PrecedencePredicate {\n\treturn NewPrecedencePredicate(t.precedence)\n}\n\nfunc (t *PrecedencePredicateTransition) String() string {\n\treturn fmt.Sprint(t.precedence) + \" >= _p\"\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/tree.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\n// The basic notion of a tree has a parent, a payload, and a list of children.\n//  It is the most abstract interface for all the trees used by ANTLR.\n///\n\nvar TreeInvalidInterval = NewInterval(-1, -2)\n\ntype Tree interface {\n\tGetParent() Tree\n\tSetParent(Tree)\n\tGetPayload() interface{}\n\tGetChild(i int) Tree\n\tGetChildCount() int\n\tGetChildren() []Tree\n}\n\ntype SyntaxTree interface {\n\tTree\n\tGetSourceInterval() Interval\n}\n\ntype ParseTree interface {\n\tSyntaxTree\n\tAccept(Visitor ParseTreeVisitor) interface{}\n\tGetText() string\n\tToStringTree([]string, Recognizer) string\n}\n\ntype RuleNode interface {\n\tParseTree\n\tGetRuleContext() RuleContext\n}\n\ntype TerminalNode interface {\n\tParseTree\n\tGetSymbol() Token\n}\n\ntype ErrorNode interface {\n\tTerminalNode\n\n\terrorNode()\n}\n\ntype ParseTreeVisitor interface {\n\tVisit(tree ParseTree) interface{}\n\tVisitChildren(node RuleNode) interface{}\n\tVisitTerminal(node TerminalNode) interface{}\n\tVisitErrorNode(node ErrorNode) interface{}\n}\n\ntype BaseParseTreeVisitor struct{}\n\nvar _ ParseTreeVisitor = &BaseParseTreeVisitor{}\n\nfunc (v *BaseParseTreeVisitor) Visit(tree ParseTree) interface{}         { return tree.Accept(v) }\nfunc (v *BaseParseTreeVisitor) VisitChildren(_ RuleNode) interface{}     { return nil }\nfunc (v *BaseParseTreeVisitor) VisitTerminal(_ TerminalNode) interface{} { return nil }\nfunc (v *BaseParseTreeVisitor) VisitErrorNode(_ ErrorNode) interface{}   { return nil }\n\n// TODO: Implement this?\n//func (this ParseTreeVisitor) Visit(ctx) {\n//\tif (Utils.isArray(ctx)) {\n//\t\tself := this\n//\t\treturn ctx.map(function(child) { return VisitAtom(self, child)})\n//\t} else {\n//\t\treturn VisitAtom(this, ctx)\n//\t}\n//}\n//\n//func VisitAtom(Visitor, ctx) {\n//\tif (ctx.parser == nil) { //is terminal\n//\t\treturn\n//\t}\n//\n//\tname := ctx.parser.ruleNames[ctx.ruleIndex]\n//\tfuncName := \"Visit\" + Utils.titleCase(name)\n//\n//\treturn Visitor[funcName](ctx)\n//}\n\ntype ParseTreeListener interface {\n\tVisitTerminal(node TerminalNode)\n\tVisitErrorNode(node ErrorNode)\n\tEnterEveryRule(ctx ParserRuleContext)\n\tExitEveryRule(ctx ParserRuleContext)\n}\n\ntype BaseParseTreeListener struct{}\n\nvar _ ParseTreeListener = &BaseParseTreeListener{}\n\nfunc (l *BaseParseTreeListener) VisitTerminal(_ TerminalNode)       {}\nfunc (l *BaseParseTreeListener) VisitErrorNode(_ ErrorNode)         {}\nfunc (l *BaseParseTreeListener) EnterEveryRule(_ ParserRuleContext) {}\nfunc (l *BaseParseTreeListener) ExitEveryRule(_ ParserRuleContext)  {}\n\ntype TerminalNodeImpl struct {\n\tparentCtx RuleContext\n\tsymbol    Token\n}\n\nvar _ TerminalNode = &TerminalNodeImpl{}\n\nfunc NewTerminalNodeImpl(symbol Token) *TerminalNodeImpl {\n\ttn := new(TerminalNodeImpl)\n\n\ttn.parentCtx = nil\n\ttn.symbol = symbol\n\n\treturn tn\n}\n\nfunc (t *TerminalNodeImpl) GetChild(_ int) Tree {\n\treturn nil\n}\n\nfunc (t *TerminalNodeImpl) GetChildren() []Tree {\n\treturn nil\n}\n\nfunc (t *TerminalNodeImpl) SetChildren(_ []Tree) {\n\tpanic(\"Cannot set children on terminal node\")\n}\n\nfunc (t *TerminalNodeImpl) GetSymbol() Token {\n\treturn t.symbol\n}\n\nfunc (t *TerminalNodeImpl) GetParent() Tree {\n\treturn t.parentCtx\n}\n\nfunc (t *TerminalNodeImpl) SetParent(tree Tree) {\n\tt.parentCtx = tree.(RuleContext)\n}\n\nfunc (t *TerminalNodeImpl) GetPayload() interface{} {\n\treturn t.symbol\n}\n\nfunc (t *TerminalNodeImpl) GetSourceInterval() Interval {\n\tif t.symbol == nil {\n\t\treturn TreeInvalidInterval\n\t}\n\ttokenIndex := t.symbol.GetTokenIndex()\n\treturn NewInterval(tokenIndex, tokenIndex)\n}\n\nfunc (t *TerminalNodeImpl) GetChildCount() int {\n\treturn 0\n}\n\nfunc (t *TerminalNodeImpl) Accept(v ParseTreeVisitor) interface{} {\n\treturn v.VisitTerminal(t)\n}\n\nfunc (t *TerminalNodeImpl) GetText() string {\n\treturn t.symbol.GetText()\n}\n\nfunc (t *TerminalNodeImpl) String() string {\n\tif t.symbol.GetTokenType() == TokenEOF {\n\t\treturn \"<EOF>\"\n\t}\n\n\treturn t.symbol.GetText()\n}\n\nfunc (t *TerminalNodeImpl) ToStringTree(_ []string, _ Recognizer) string {\n\treturn t.String()\n}\n\n// Represents a token that was consumed during reSynchronization\n// rather than during a valid Match operation. For example,\n// we will create this kind of a node during single token insertion\n// and deletion as well as during \"consume until error recovery set\"\n// upon no viable alternative exceptions.\n\ntype ErrorNodeImpl struct {\n\t*TerminalNodeImpl\n}\n\nvar _ ErrorNode = &ErrorNodeImpl{}\n\nfunc NewErrorNodeImpl(token Token) *ErrorNodeImpl {\n\ten := new(ErrorNodeImpl)\n\ten.TerminalNodeImpl = NewTerminalNodeImpl(token)\n\treturn en\n}\n\nfunc (e *ErrorNodeImpl) errorNode() {}\n\nfunc (e *ErrorNodeImpl) Accept(v ParseTreeVisitor) interface{} {\n\treturn v.VisitErrorNode(e)\n}\n\ntype ParseTreeWalker struct {\n}\n\nfunc NewParseTreeWalker() *ParseTreeWalker {\n\treturn new(ParseTreeWalker)\n}\n\n// Walk performs a walk on the given parse tree starting at the root and going down recursively\n// with depth-first search. On each node, [EnterRule] is called before\n// recursively walking down into child nodes, then [ExitRule] is called after the recursive call to wind up.\nfunc (p *ParseTreeWalker) Walk(listener ParseTreeListener, t Tree) {\n\tswitch tt := t.(type) {\n\tcase ErrorNode:\n\t\tlistener.VisitErrorNode(tt)\n\tcase TerminalNode:\n\t\tlistener.VisitTerminal(tt)\n\tdefault:\n\t\tp.EnterRule(listener, t.(RuleNode))\n\t\tfor i := 0; i < t.GetChildCount(); i++ {\n\t\t\tchild := t.GetChild(i)\n\t\t\tp.Walk(listener, child)\n\t\t}\n\t\tp.ExitRule(listener, t.(RuleNode))\n\t}\n}\n\n// EnterRule enters a grammar rule by first triggering the generic event [ParseTreeListener].[EnterEveryRule]\n// then by triggering the event specific to the given parse tree node\nfunc (p *ParseTreeWalker) EnterRule(listener ParseTreeListener, r RuleNode) {\n\tctx := r.GetRuleContext().(ParserRuleContext)\n\tlistener.EnterEveryRule(ctx)\n\tctx.EnterRule(listener)\n}\n\n// ExitRule exits a grammar rule by first triggering the event specific to the given parse tree node\n// then by triggering the generic event [ParseTreeListener].ExitEveryRule\nfunc (p *ParseTreeWalker) ExitRule(listener ParseTreeListener, r RuleNode) {\n\tctx := r.GetRuleContext().(ParserRuleContext)\n\tctx.ExitRule(listener)\n\tlistener.ExitEveryRule(ctx)\n}\n\n//goland:noinspection GoUnusedGlobalVariable\nvar ParseTreeWalkerDefault = NewParseTreeWalker()\n\ntype IterativeParseTreeWalker struct {\n\t*ParseTreeWalker\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc NewIterativeParseTreeWalker() *IterativeParseTreeWalker {\n\treturn new(IterativeParseTreeWalker)\n}\n\nfunc (i *IterativeParseTreeWalker) Walk(listener ParseTreeListener, t Tree) {\n\tvar stack []Tree\n\tvar indexStack []int\n\tcurrentNode := t\n\tcurrentIndex := 0\n\n\tfor currentNode != nil {\n\t\t// pre-order visit\n\t\tswitch tt := currentNode.(type) {\n\t\tcase ErrorNode:\n\t\t\tlistener.VisitErrorNode(tt)\n\t\tcase TerminalNode:\n\t\t\tlistener.VisitTerminal(tt)\n\t\tdefault:\n\t\t\ti.EnterRule(listener, currentNode.(RuleNode))\n\t\t}\n\t\t// Move down to first child, if exists\n\t\tif currentNode.GetChildCount() > 0 {\n\t\t\tstack = append(stack, currentNode)\n\t\t\tindexStack = append(indexStack, currentIndex)\n\t\t\tcurrentIndex = 0\n\t\t\tcurrentNode = currentNode.GetChild(0)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor {\n\t\t\t// post-order visit\n\t\t\tif ruleNode, ok := currentNode.(RuleNode); ok {\n\t\t\t\ti.ExitRule(listener, ruleNode)\n\t\t\t}\n\t\t\t// No parent, so no siblings\n\t\t\tif len(stack) == 0 {\n\t\t\t\tcurrentNode = nil\n\t\t\t\tcurrentIndex = 0\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Move to next sibling if possible\n\t\t\tcurrentIndex++\n\t\t\tif stack[len(stack)-1].GetChildCount() > currentIndex {\n\t\t\t\tcurrentNode = stack[len(stack)-1].GetChild(currentIndex)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// No next, sibling, so move up\n\t\t\tcurrentNode, stack = stack[len(stack)-1], stack[:len(stack)-1]\n\t\t\tcurrentIndex, indexStack = indexStack[len(indexStack)-1], indexStack[:len(indexStack)-1]\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/trees.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport \"fmt\"\n\n/** A set of utility routines useful for all kinds of ANTLR trees. */\n\n// TreesStringTree prints out a whole tree in LISP form. [getNodeText] is used on the\n// node payloads to get the text for the nodes. Detects parse trees and extracts data appropriately.\nfunc TreesStringTree(tree Tree, ruleNames []string, recog Recognizer) string {\n\n\tif recog != nil {\n\t\truleNames = recog.GetRuleNames()\n\t}\n\n\ts := TreesGetNodeText(tree, ruleNames, nil)\n\n\ts = EscapeWhitespace(s, false)\n\tc := tree.GetChildCount()\n\tif c == 0 {\n\t\treturn s\n\t}\n\tres := \"(\" + s + \" \"\n\tif c > 0 {\n\t\ts = TreesStringTree(tree.GetChild(0), ruleNames, nil)\n\t\tres += s\n\t}\n\tfor i := 1; i < c; i++ {\n\t\ts = TreesStringTree(tree.GetChild(i), ruleNames, nil)\n\t\tres += \" \" + s\n\t}\n\tres += \")\"\n\treturn res\n}\n\nfunc TreesGetNodeText(t Tree, ruleNames []string, recog Parser) string {\n\tif recog != nil {\n\t\truleNames = recog.GetRuleNames()\n\t}\n\n\tif ruleNames != nil {\n\t\tswitch t2 := t.(type) {\n\t\tcase RuleNode:\n\t\t\tt3 := t2.GetRuleContext()\n\t\t\taltNumber := t3.GetAltNumber()\n\n\t\t\tif altNumber != ATNInvalidAltNumber {\n\t\t\t\treturn fmt.Sprintf(\"%s:%d\", ruleNames[t3.GetRuleIndex()], altNumber)\n\t\t\t}\n\t\t\treturn ruleNames[t3.GetRuleIndex()]\n\t\tcase ErrorNode:\n\t\t\treturn fmt.Sprint(t2)\n\t\tcase TerminalNode:\n\t\t\tif t2.GetSymbol() != nil {\n\t\t\t\treturn t2.GetSymbol().GetText()\n\t\t\t}\n\t\t}\n\t}\n\n\t// no recognition for rule names\n\tpayload := t.GetPayload()\n\tif p2, ok := payload.(Token); ok {\n\t\treturn p2.GetText()\n\t}\n\n\treturn fmt.Sprint(t.GetPayload())\n}\n\n// TreesGetChildren returns am ordered list of all children of this node\n//\n//goland:noinspection GoUnusedExportedFunction\nfunc TreesGetChildren(t Tree) []Tree {\n\tlist := make([]Tree, 0)\n\tfor i := 0; i < t.GetChildCount(); i++ {\n\t\tlist = append(list, t.GetChild(i))\n\t}\n\treturn list\n}\n\n// TreesgetAncestors returns a list of all ancestors of this node.  The first node of list is the root\n// and the last node is the parent of this node.\n//\n//goland:noinspection GoUnusedExportedFunction\nfunc TreesgetAncestors(t Tree) []Tree {\n\tancestors := make([]Tree, 0)\n\tt = t.GetParent()\n\tfor t != nil {\n\t\tf := []Tree{t}\n\t\tancestors = append(f, ancestors...)\n\t\tt = t.GetParent()\n\t}\n\treturn ancestors\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc TreesFindAllTokenNodes(t ParseTree, ttype int) []ParseTree {\n\treturn TreesfindAllNodes(t, ttype, true)\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc TreesfindAllRuleNodes(t ParseTree, ruleIndex int) []ParseTree {\n\treturn TreesfindAllNodes(t, ruleIndex, false)\n}\n\nfunc TreesfindAllNodes(t ParseTree, index int, findTokens bool) []ParseTree {\n\tnodes := make([]ParseTree, 0)\n\ttreesFindAllNodes(t, index, findTokens, &nodes)\n\treturn nodes\n}\n\nfunc treesFindAllNodes(t ParseTree, index int, findTokens bool, nodes *[]ParseTree) {\n\t// check this node (the root) first\n\n\tt2, ok := t.(TerminalNode)\n\tt3, ok2 := t.(ParserRuleContext)\n\n\tif findTokens && ok {\n\t\tif t2.GetSymbol().GetTokenType() == index {\n\t\t\t*nodes = append(*nodes, t2)\n\t\t}\n\t} else if !findTokens && ok2 {\n\t\tif t3.GetRuleIndex() == index {\n\t\t\t*nodes = append(*nodes, t3)\n\t\t}\n\t}\n\t// check children\n\tfor i := 0; i < t.GetChildCount(); i++ {\n\t\ttreesFindAllNodes(t.GetChild(i).(ParseTree), index, findTokens, nodes)\n\t}\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc TreesDescendants(t ParseTree) []ParseTree {\n\tnodes := []ParseTree{t}\n\tfor i := 0; i < t.GetChildCount(); i++ {\n\t\tnodes = append(nodes, TreesDescendants(t.GetChild(i).(ParseTree))...)\n\t}\n\treturn nodes\n}\n"
  },
  {
    "path": "runtime/Go/antlr/v4/utils.go",
    "content": "// Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n// Use of this file is governed by the BSD 3-clause license that\n// can be found in the LICENSE.txt file in the project root.\n\npackage antlr\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math/bits\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nfunc intMin(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc intMax(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n// A simple integer stack\n\ntype IntStack []int\n\nvar ErrEmptyStack = errors.New(\"stack is empty\")\n\nfunc (s *IntStack) Pop() (int, error) {\n\tl := len(*s) - 1\n\tif l < 0 {\n\t\treturn 0, ErrEmptyStack\n\t}\n\tv := (*s)[l]\n\t*s = (*s)[0:l]\n\treturn v, nil\n}\n\nfunc (s *IntStack) Push(e int) {\n\t*s = append(*s, e)\n}\n\nconst bitsPerWord = 64\n\nfunc indexForBit(bit int) int {\n\treturn bit / bitsPerWord\n}\n\n//goland:noinspection GoUnusedExportedFunction,GoUnusedFunction\nfunc wordForBit(data []uint64, bit int) uint64 {\n\tidx := indexForBit(bit)\n\tif idx >= len(data) {\n\t\treturn 0\n\t}\n\treturn data[idx]\n}\n\nfunc maskForBit(bit int) uint64 {\n\treturn uint64(1) << (bit % bitsPerWord)\n}\n\nfunc wordsNeeded(bit int) int {\n\treturn indexForBit(bit) + 1\n}\n\ntype BitSet struct {\n\tdata []uint64\n}\n\n// NewBitSet creates a new bitwise set\n// TODO: See if we can replace with the standard library's BitSet\nfunc NewBitSet() *BitSet {\n\treturn &BitSet{}\n}\n\nfunc (b *BitSet) add(value int) {\n\tidx := indexForBit(value)\n\tif idx >= len(b.data) {\n\t\tsize := wordsNeeded(value)\n\t\tdata := make([]uint64, size)\n\t\tcopy(data, b.data)\n\t\tb.data = data\n\t}\n\tb.data[idx] |= maskForBit(value)\n}\n\nfunc (b *BitSet) clear(index int) {\n\tidx := indexForBit(index)\n\tif idx >= len(b.data) {\n\t\treturn\n\t}\n\tb.data[idx] &= ^maskForBit(index)\n}\n\nfunc (b *BitSet) or(set *BitSet) {\n\t// Get min size necessary to represent the bits in both sets.\n\tbLen := b.minLen()\n\tsetLen := set.minLen()\n\tmaxLen := intMax(bLen, setLen)\n\tif maxLen > len(b.data) {\n\t\t// Increase the size of len(b.data) to represent the bits in both sets.\n\t\tdata := make([]uint64, maxLen)\n\t\tcopy(data, b.data)\n\t\tb.data = data\n\t}\n\t// len(b.data) is at least setLen.\n\tfor i := 0; i < setLen; i++ {\n\t\tb.data[i] |= set.data[i]\n\t}\n}\n\nfunc (b *BitSet) remove(value int) {\n\tb.clear(value)\n}\n\nfunc (b *BitSet) contains(value int) bool {\n\tidx := indexForBit(value)\n\tif idx >= len(b.data) {\n\t\treturn false\n\t}\n\treturn (b.data[idx] & maskForBit(value)) != 0\n}\n\nfunc (b *BitSet) minValue() int {\n\tfor i, v := range b.data {\n\t\tif v == 0 {\n\t\t\tcontinue\n\t\t}\n\t\treturn i*bitsPerWord + bits.TrailingZeros64(v)\n\t}\n\treturn 2147483647\n}\n\nfunc (b *BitSet) equals(other interface{}) bool {\n\totherBitSet, ok := other.(*BitSet)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif b == otherBitSet {\n\t\treturn true\n\t}\n\n\t// We only compare set bits, so we cannot rely on the two slices having the same size. Its\n\t// possible for two BitSets to have different slice lengths but the same set bits. So we only\n\t// compare the relevant words and ignore the trailing zeros.\n\tbLen := b.minLen()\n\totherLen := otherBitSet.minLen()\n\n\tif bLen != otherLen {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < bLen; i++ {\n\t\tif b.data[i] != otherBitSet.data[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (b *BitSet) minLen() int {\n\tfor i := len(b.data); i > 0; i-- {\n\t\tif b.data[i-1] != 0 {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}\n\nfunc (b *BitSet) length() int {\n\tcnt := 0\n\tfor _, val := range b.data {\n\t\tcnt += bits.OnesCount64(val)\n\t}\n\treturn cnt\n}\n\nfunc (b *BitSet) String() string {\n\tvals := make([]string, 0, b.length())\n\n\tfor i, v := range b.data {\n\t\tfor v != 0 {\n\t\t\tn := bits.TrailingZeros64(v)\n\t\t\tvals = append(vals, strconv.Itoa(i*bitsPerWord+n))\n\t\t\tv &= ^(uint64(1) << n)\n\t\t}\n\t}\n\n\treturn \"{\" + strings.Join(vals, \", \") + \"}\"\n}\n\ntype AltDict struct {\n\tdata map[string]interface{}\n}\n\nfunc NewAltDict() *AltDict {\n\td := new(AltDict)\n\td.data = make(map[string]interface{})\n\treturn d\n}\n\nfunc (a *AltDict) Get(key string) interface{} {\n\tkey = \"k-\" + key\n\treturn a.data[key]\n}\n\nfunc (a *AltDict) put(key string, value interface{}) {\n\tkey = \"k-\" + key\n\ta.data[key] = value\n}\n\nfunc (a *AltDict) values() []interface{} {\n\tvs := make([]interface{}, len(a.data))\n\ti := 0\n\tfor _, v := range a.data {\n\t\tvs[i] = v\n\t\ti++\n\t}\n\treturn vs\n}\n\nfunc EscapeWhitespace(s string, escapeSpaces bool) string {\n\n\ts = strings.Replace(s, \"\\t\", \"\\\\t\", -1)\n\ts = strings.Replace(s, \"\\n\", \"\\\\n\", -1)\n\ts = strings.Replace(s, \"\\r\", \"\\\\r\", -1)\n\tif escapeSpaces {\n\t\ts = strings.Replace(s, \" \", \"\\u00B7\", -1)\n\t}\n\treturn s\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc TerminalNodeToStringArray(sa []TerminalNode) []string {\n\tst := make([]string, len(sa))\n\n\tfor i, s := range sa {\n\t\tst[i] = fmt.Sprintf(\"%v\", s)\n\t}\n\n\treturn st\n}\n\n//goland:noinspection GoUnusedExportedFunction\nfunc PrintArrayJavaStyle(sa []string) string {\n\tvar buffer bytes.Buffer\n\n\tbuffer.WriteString(\"[\")\n\n\tfor i, s := range sa {\n\t\tbuffer.WriteString(s)\n\t\tif i != len(sa)-1 {\n\t\t\tbuffer.WriteString(\", \")\n\t\t}\n\t}\n\n\tbuffer.WriteString(\"]\")\n\n\treturn buffer.String()\n}\n\n// murmur hash\nfunc murmurInit(seed int) int {\n\treturn seed\n}\n\nfunc murmurUpdate(h int, value int) int {\n\tconst c1 uint32 = 0xCC9E2D51\n\tconst c2 uint32 = 0x1B873593\n\tconst r1 uint32 = 15\n\tconst r2 uint32 = 13\n\tconst m uint32 = 5\n\tconst n uint32 = 0xE6546B64\n\n\tk := uint32(value)\n\tk *= c1\n\tk = (k << r1) | (k >> (32 - r1))\n\tk *= c2\n\n\thash := uint32(h) ^ k\n\thash = (hash << r2) | (hash >> (32 - r2))\n\thash = hash*m + n\n\treturn int(hash)\n}\n\nfunc murmurFinish(h int, numberOfWords int) int {\n\tvar hash = uint32(h)\n\thash ^= uint32(numberOfWords) << 2\n\thash ^= hash >> 16\n\thash *= 0x85ebca6b\n\thash ^= hash >> 13\n\thash *= 0xc2b2ae35\n\thash ^= hash >> 16\n\n\treturn int(hash)\n}\n\nfunc isDirectory(dir string) (bool, error) {\n\tfileInfo, err := os.Stat(dir)\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, syscall.ENOENT):\n\t\t\t// The given directory does not exist, so we will try to create it\n\t\t\t//\n\t\t\terr = os.MkdirAll(dir, 0755)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\treturn true, nil\n\t\tcase err != nil:\n\t\t\treturn false, err\n\t\tdefault:\n\t\t}\n\t}\n\treturn fileInfo.IsDir(), err\n}\n\n// intSlicesEqual returns true if the two slices of ints are equal, and is a little\n// faster than slices.Equal.\nfunc intSlicesEqual(s1, s2 []int) bool {\n\tif s1 == nil && s2 == nil {\n\t\treturn true\n\t}\n\tif s1 == nil || s2 == nil {\n\t\treturn false\n\t}\n\tif len(s1) == 0 && len(s2) == 0 {\n\t\treturn true\n\t}\n\n\tif len(s1) == 0 || len(s2) == 0 || len(s1) != len(s2) {\n\t\treturn false\n\t}\n\t// If the slices are using the same memory, then they are the same slice\n\tif &s1[0] == &s2[0] {\n\t\treturn true\n\t}\n\tfor i, v := range s1 {\n\t\tif v != s2[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc pcSliceEqual(s1, s2 []*PredictionContext) bool {\n\tif s1 == nil && s2 == nil {\n\t\treturn true\n\t}\n\tif s1 == nil || s2 == nil {\n\t\treturn false\n\t}\n\tif len(s1) == 0 && len(s2) == 0 {\n\t\treturn true\n\t}\n\tif len(s1) == 0 || len(s2) == 0 || len(s1) != len(s2) {\n\t\treturn false\n\t}\n\t// If the slices are using the same memory, then they are the same slice\n\tif &s1[0] == &s2[0] {\n\t\treturn true\n\t}\n\tfor i, v := range s1 {\n\t\tif !v.Equals(s2[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"
  },
  {
    "path": "runtime/Java/doxyfile",
    "content": "# Doxyfile 1.5.2\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\nDOXYFILE_ENCODING      = UTF-8\nPROJECT_NAME           = \"ANTLR v4 API\"\nPROJECT_NUMBER         = 4.0\nOUTPUT_DIRECTORY       = api/Java\nCREATE_SUBDIRS         = NO\nOUTPUT_LANGUAGE        = English\nBRIEF_MEMBER_DESC      = YES\nREPEAT_BRIEF           = YES\nABBREVIATE_BRIEF       = \"The $name class\" \\\n                         \"The $name widget\" \\\n                         \"The $name file\" \\\n                         is \\\n                         provides \\\n                         specifies \\\n                         contains \\\n                         represents \\\n                         a \\\n                         an \\\n                         the\nALWAYS_DETAILED_SEC    = YES\nINLINE_INHERITED_MEMB  = NO\nFULL_PATH_NAMES        = YES\nSTRIP_FROM_PATH        = /Applications/\nSTRIP_FROM_INC_PATH    =\nSHORT_NAMES            = NO\nJAVADOC_AUTOBRIEF      = NO\nMULTILINE_CPP_IS_BRIEF = NO\nDETAILS_AT_TOP         = NO\nINHERIT_DOCS           = YES\nSEPARATE_MEMBER_PAGES  = NO\nTAB_SIZE               = 4\nALIASES                =\nOPTIMIZE_OUTPUT_FOR_C  = NO\nOPTIMIZE_OUTPUT_JAVA   = YES\nBUILTIN_STL_SUPPORT    = NO\nCPP_CLI_SUPPORT        = NO\nDISTRIBUTE_GROUP_DOC   = NO\nSUBGROUPING            = YES\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\nEXTRACT_ALL            = YES\nEXTRACT_PRIVATE        = YES\nEXTRACT_STATIC         = YES\nEXTRACT_LOCAL_CLASSES  = YES\nEXTRACT_LOCAL_METHODS  = NO\nHIDE_UNDOC_MEMBERS     = NO\nHIDE_UNDOC_CLASSES     = NO\nHIDE_FRIEND_COMPOUNDS  = NO\nHIDE_IN_BODY_DOCS      = NO\nINTERNAL_DOCS          = NO\nCASE_SENSE_NAMES       = NO\nHIDE_SCOPE_NAMES       = NO\nSHOW_INCLUDE_FILES     = YES\nINLINE_INFO            = YES\nSORT_MEMBER_DOCS       = YES\nSORT_BRIEF_DOCS        = NO\nSORT_BY_SCOPE_NAME     = NO\nGENERATE_TODOLIST      = YES\nGENERATE_TESTLIST      = NO\nGENERATE_BUGLIST       = NO\nGENERATE_DEPRECATEDLIST= NO\nENABLED_SECTIONS       =\nMAX_INITIALIZER_LINES  = 30\nSHOW_USED_FILES        = YES\nSHOW_DIRECTORIES       = NO\nFILE_VERSION_FILTER    =\n#---------------------------------------------------------------------------\n# configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\nQUIET                  = NO\nWARNINGS               = YES\nWARN_IF_UNDOCUMENTED   = YES\nWARN_IF_DOC_ERROR      = YES\nWARN_NO_PARAMDOC       = NO\nWARN_FORMAT            = \"$file:$line: $text\"\nWARN_LOGFILE           =\n#---------------------------------------------------------------------------\n# configuration options related to the input files\n#---------------------------------------------------------------------------\nINPUT                  = /Users/parrt/antlr/code/antlr4/runtime/Java/src\nINPUT_ENCODING         = UTF-8\nFILE_PATTERNS          = *.java\nRECURSIVE              = YES\nEXCLUDE                =\nEXCLUDE_SYMLINKS       = NO\nEXCLUDE_PATTERNS       =\nEXCLUDE_SYMBOLS        = java::util \\\n                         java::io\nEXAMPLE_PATH           =\nEXAMPLE_PATTERNS       = *\nEXAMPLE_RECURSIVE      = NO\nIMAGE_PATH             =\nINPUT_FILTER           =\nFILTER_PATTERNS        =\nFILTER_SOURCE_FILES    = NO\n#---------------------------------------------------------------------------\n# configuration options related to source browsing\n#---------------------------------------------------------------------------\nSOURCE_BROWSER         = YES\nINLINE_SOURCES         = NO\nSTRIP_CODE_COMMENTS    = YES\nREFERENCED_BY_RELATION = NO\nREFERENCES_RELATION    = NO\nREFERENCES_LINK_SOURCE = YES\nUSE_HTAGS              = NO\nVERBATIM_HEADERS       = YES\n#---------------------------------------------------------------------------\n# configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\nALPHABETICAL_INDEX     = YES\nCOLS_IN_ALPHA_INDEX    = 5\nIGNORE_PREFIX          =\n#---------------------------------------------------------------------------\n# configuration options related to the HTML output\n#---------------------------------------------------------------------------\nGENERATE_HTML          = YES\nHTML_OUTPUT            = .\nHTML_FILE_EXTENSION    = .html\nHTML_HEADER            =\nHTML_FOOTER            =\nHTML_STYLESHEET        =\nHTML_ALIGN_MEMBERS     = YES\nHTML_DYNAMIC_SECTIONS  = YES\nGENERATE_HTMLHELP      = NO\nCHM_FILE               =\nHHC_LOCATION           =\nGENERATE_CHI           = NO\nBINARY_TOC             = NO\nTOC_EXPAND             = NO\nDISABLE_INDEX          = NO\nENUM_VALUES_PER_LINE   = 4\nGENERATE_TREEVIEW      = YES\nTREEVIEW_WIDTH         = 210\n#---------------------------------------------------------------------------\n# configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\nGENERATE_LATEX         = NO\nLATEX_OUTPUT           = latex\nLATEX_CMD_NAME         = latex\nMAKEINDEX_CMD_NAME     = makeindex\nCOMPACT_LATEX          = NO\nPAPER_TYPE             = a4wide\nEXTRA_PACKAGES         =\nLATEX_HEADER           =\nPDF_HYPERLINKS         = NO\nUSE_PDFLATEX           = YES\nLATEX_BATCHMODE        = NO\nLATEX_HIDE_INDICES     = NO\n#---------------------------------------------------------------------------\n# configuration options related to the RTF output\n#---------------------------------------------------------------------------\nGENERATE_RTF           = NO\nRTF_OUTPUT             = rtf\nCOMPACT_RTF            = NO\nRTF_HYPERLINKS         = NO\nRTF_STYLESHEET_FILE    =\nRTF_EXTENSIONS_FILE    =\n#---------------------------------------------------------------------------\n# configuration options related to the man page output\n#---------------------------------------------------------------------------\nGENERATE_MAN           = NO\nMAN_OUTPUT             = man\nMAN_EXTENSION          = .3\nMAN_LINKS              = NO\n#---------------------------------------------------------------------------\n# configuration options related to the XML output\n#---------------------------------------------------------------------------\nGENERATE_XML           = NO\nXML_OUTPUT             = xml\nXML_SCHEMA             =\nXML_DTD                =\nXML_PROGRAMLISTING     = YES\n#---------------------------------------------------------------------------\n# configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\nGENERATE_AUTOGEN_DEF   = NO\n#---------------------------------------------------------------------------\n# configuration options related to the Perl module output\n#---------------------------------------------------------------------------\nGENERATE_PERLMOD       = NO\nPERLMOD_LATEX          = NO\nPERLMOD_PRETTY         = YES\nPERLMOD_MAKEVAR_PREFIX =\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\nENABLE_PREPROCESSING   = YES\nMACRO_EXPANSION        = NO\nEXPAND_ONLY_PREDEF     = NO\nSEARCH_INCLUDES        = YES\nINCLUDE_PATH           =\nINCLUDE_FILE_PATTERNS  =\nPREDEFINED             =\nEXPAND_AS_DEFINED      =\nSKIP_FUNCTION_MACROS   = YES\n#---------------------------------------------------------------------------\n# Configuration::additions related to external references\n#---------------------------------------------------------------------------\nTAGFILES               =\nGENERATE_TAGFILE       =\nALLEXTERNALS           = NO\nEXTERNAL_GROUPS        = YES\nPERL_PATH              = /usr/bin/perl\n#---------------------------------------------------------------------------\n# Configuration options related to the dot tool\n#---------------------------------------------------------------------------\nCLASS_DIAGRAMS         = NO\nMSCGEN_PATH            = /Applications/Doxygen.app/Contents/Resources/\nHIDE_UNDOC_RELATIONS   = YES\nHAVE_DOT               = YES\nCLASS_GRAPH            = YES\nCOLLABORATION_GRAPH    = NO\nGROUP_GRAPHS           = NO\nUML_LOOK               = NO\nTEMPLATE_RELATIONS     = NO\nINCLUDE_GRAPH          = YES\nINCLUDED_BY_GRAPH      = YES\nCALL_GRAPH             = NO\nCALLER_GRAPH           = NO\nGRAPHICAL_HIERARCHY    = YES\nDIRECTORY_GRAPH        = YES\nDOT_IMAGE_FORMAT       = png\nDOT_PATH               = /Applications/Doxygen.app/Contents/Resources/\nDOTFILE_DIRS           =\nDOT_GRAPH_MAX_NODES    = 50\nDOT_TRANSPARENT        = NO\nDOT_MULTI_TARGETS      = NO\nGENERATE_LEGEND        = YES\nDOT_CLEANUP            = YES\n#---------------------------------------------------------------------------\n# Configuration::additions related to the search engine\n#---------------------------------------------------------------------------\nSEARCHENGINE           = YES\n"
  },
  {
    "path": "runtime/Java/nb-configuration.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project-shared-configuration>\n    <!--\nThis file contains additional configuration written by modules in the NetBeans IDE.\nThe configuration is intended to be shared among all the users of project and\ntherefore it is assumed to be part of version control checkout.\nWithout this configuration present, some functionality in the IDE may be limited or fail altogether.\n-->\n    <spellchecker-wordlist xmlns=\"http://www.netbeans.org/ns/spellchecker-wordlist/1\">\n        <word>rule's</word>\n        <word>validator</word>\n    </spellchecker-wordlist>\n    <properties xmlns=\"http://www.netbeans.org/ns/maven-properties-data/1\">\n        <!--\nProperties that influence various parts of the IDE, especially code formatting and the like.\nYou can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.\nThat way multiple projects can share the same settings (useful for formatting rules for example).\nAny value defined here will override the pom.xml file value but is only applicable to the current project.\n-->\n        <org-netbeans-modules-editor-indent.CodeStyle.usedProfile>project</org-netbeans-modules-editor-indent.CodeStyle.usedProfile>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs>true</org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-line-wrap>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.continuationIndentSize>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.continuationIndentSize>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>*;javax;java</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>\n        <netbeans.compile.on.save>test</netbeans.compile.on.save>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast>\n    </properties>\n</project-shared-configuration>\n"
  },
  {
    "path": "runtime/Java/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<groupId>org.antlr</groupId>\n\t\t<artifactId>antlr4-master</artifactId>\n\t\t<version>4.13.3-SNAPSHOT</version>\n\t\t<relativePath>../../pom.xml</relativePath>\n\t</parent>\n\t<artifactId>antlr4-runtime</artifactId>\n\t<name>ANTLR 4 Runtime</name>\n\t<description>The ANTLR 4 Runtime</description>\n\n    <prerequisites>\n        <maven>3.8</maven>\n    </prerequisites>\n\n\t<properties>\n\t\t<!-- Assumes dot is in the system path, or specified for the build. -->\n\t\t<dot.path>dot</dot.path>\n\t</properties>\n\n\t<build>\n\t\t<sourceDirectory>src</sourceDirectory>\n\t\t<plugins>\n\t\t\t<plugin> <!-- create src jar -->\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-source-plugin</artifactId>\n\t\t\t\t<version>3.2.1</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin> <!-- run dot on the images used by PredictionContext.java -->\n\t\t\t\t<groupId>us.bryon</groupId>\n\t\t\t\t<artifactId>graphviz-maven-plugin</artifactId>\n\t\t\t\t<version>1.0</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>dot</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<dot>${dot.path}</dot>\n\t\t\t\t\t\t\t<destdir>${project.build.directory}/apidocs</destdir>\n\t\t\t\t\t\t\t<output>svg</output>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin> <!-- create javadoc jar -->\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t<version>3.3.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<javadocVersion>1.8</javadocVersion>\n\t\t\t\t\t<failOnError>false</failOnError>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>javadoc</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.felix</groupId>\n\t\t\t\t<artifactId>maven-bundle-plugin</artifactId>\n\t\t\t\t<version>5.1.9</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>bundle-manifest</id>\n\t\t\t\t\t\t<phase>process-classes</phase>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<instructions>\n\t\t\t\t\t\t\t\t<Automatic-Module-Name>org.antlr.antlr4.runtime</Automatic-Module-Name>\n\t\t\t\t\t\t\t\t<Bundle-SymbolicName>org.antlr.antlr4-runtime</Bundle-SymbolicName>\n\t\t\t\t\t\t\t\t<Import-Package>org.antlr.v4.gui;resolution:=optional, *</Import-Package>\n\t\t\t\t\t\t\t</instructions>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>manifest</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>3.2.0</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<archive>\n\t\t\t\t\t\t<manifest>\n\t\t\t\t\t\t\t<addDefaultImplementationEntries>true</addDefaultImplementationEntries>\n\t\t\t\t\t\t</manifest>\n\t\t\t\t\t\t<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>\n\t\t\t\t\t</archive>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.8.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<release>8</release>\n\t\t\t\t\t<source>1.8</source>\n\t\t\t\t\t<target>1.8</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/ArrayMerge_DiffTopDiffPar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph clusterA {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u1[label=\"u\"];\n            A_v1[label=\"v\"];\n        }\n\n        A_left[shape=\"record\";label=\"{<a> | a} | {<b> | b}\"];\n\n        {   edge[dir=\"back\"];\n            A_u1:s -> A_left:a:n;\n            A_v1:s -> A_left:b:n;\n        }\n    }\n\n    subgraph AB {\n        temp0[color=\"invis\";shape=\"point\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n        temp0 -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph clusterB {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_w1[label=\"w\"];\n            A_x1[label=\"x\"];\n        }\n\n        A_right[shape=\"record\";label=\"{<c> | c} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_w1:s -> A_right:c:n;\n            A_x1:s -> A_right:d:n;\n        }\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterC {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u2[label=\"u\"];\n            A_v2[label=\"v\"];\n            A_w2[label=\"w\"];\n            A_x2[label=\"x\"];\n        }\n\n        A_result[shape=\"record\";label=\"{<a> | a} | {<b> | b} | {<c> | c} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_u2:s -> A_result:a:n;\n            A_v2:s -> A_result:b:n;\n            A_w2:s -> A_result:c:n;\n            A_x2:s -> A_result:d:n;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/ArrayMerge_EqualTop.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph clusterA {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u1[label=\"x\"];\n        }\n\n        A_left[shape=\"record\";label=\"{<a> | a}\"];\n\n        {   edge[dir=\"back\"];\n            A_u1:s -> A_left:a:n;\n        }\n    }\n\n    subgraph AB {\n        temp0[color=\"invis\";shape=\"point\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n        temp0 -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph clusterB {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_w1[label=\"y\"];\n        }\n\n        A_right[shape=\"record\";label=\"{<a> | a}\"];\n\n        {   edge[dir=\"back\"];\n            A_w1:s -> A_right:a:n;\n        }\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterC {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u2[label=\"\"];\n            A_v2[label=\"\"];\n        }\n\n        A_result[shape=\"record\";label=\"{<x> | x} | {<y> | y}\"];\n\n        A_ap[label=\"a'\";shape=\"none\"];\n\n        {   edge[dir=\"back\"];\n            A_u2:s -> A_result:x:n;\n            A_v2:s -> A_result:y:n;\n            A_result:s -> A_ap:n;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/ArrayMerge_ShareTopDiffPar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph clusterA {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u1[label=\"u\"];\n            A_v1[label=\"v\"];\n        }\n\n        A_left[shape=\"record\";label=\"{<a> | a} | {<b> | b}\"];\n\n        {   edge[dir=\"back\"];\n            A_u1:s -> A_left:a:n;\n            A_v1:s -> A_left:b:n;\n        }\n    }\n\n    subgraph AB {\n        temp0[color=\"invis\";shape=\"point\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n        temp0 -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph clusterB {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_w1[label=\"w\"];\n            A_x1[label=\"x\"];\n        }\n\n        A_right[shape=\"record\";label=\"{<b> | b} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_w1:s -> A_right:b:n;\n            A_x1:s -> A_right:d:n;\n        }\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterC {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u2[label=\"u\"];\n            A_vw[shape=\"record\";label=\"{<v> | v} | {<w> | w}\"];\n            A_x2[label=\"x\"];\n        }\n\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_vp[label=\"\"];\n            A_wp[label=\"\"];\n        }\n\n        A_result[shape=\"record\";label=\"{<a> | a} | {<b> | b'} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_u2:s -> A_result:a:n;\n            A_vw:s -> A_result:b:n;\n            A_x2:s -> A_result:d:n;\n            A_vp:s -> A_vw:v:n;\n            A_wp:s -> A_vw:w:n;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/ArrayMerge_ShareTopSamePar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph clusterA {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u1[label=\"u\"];\n            A_v1[label=\"v\"];\n        }\n\n        A_left[shape=\"record\";label=\"{<a> | a} | {<b> | b}\"];\n\n        {   edge[dir=\"back\"];\n            A_u1:s -> A_left:a:n;\n            A_v1:s -> A_left:b:n;\n        }\n    }\n\n    subgraph AB {\n        temp0[color=\"invis\";shape=\"point\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n        temp0 -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph clusterB {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_w1[label=\"v\"];\n            A_x1[label=\"x\"];\n        }\n\n        A_right[shape=\"record\";label=\"{<b> | b} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_w1:s -> A_right:b:n;\n            A_x1:s -> A_right:d:n;\n        }\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterC {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u2[label=\"u\"];\n            A_v2[label=\"v\"];\n            A_x2[label=\"x\"];\n        }\n\n        A_result[shape=\"record\";label=\"{<a> | a} | {<b> | b} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_u2:s -> A_result:a:n;\n            A_v2:s -> A_result:b:n;\n            A_x2:s -> A_result:d:n;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/ArrayMerge_ShareTopSharePar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph clusterA {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u1[label=\"u\"];\n            A_v1[label=\"v\"];\n        }\n\n        A_left[shape=\"record\";label=\"{<a> | a} | {<b> | b}\"];\n\n        {   edge[dir=\"back\"];\n            A_u1:s -> A_left:a:n;\n            A_v1:s -> A_left:b:n;\n        }\n    }\n\n    subgraph AB {\n        temp0[color=\"invis\";shape=\"point\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n        temp0 -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph clusterB {\n        label=\"\";\n        color=\"invis\";\n        {   rank=\"same\";\n            node[shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_w1[label=\"v\"];\n            A_x1[label=\"u\"];\n        }\n\n        A_right[shape=\"record\";label=\"{<b> | b} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_w1:s -> A_right:b:n;\n            A_x1:s -> A_right:d:n;\n        }\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterC {\n        label=\"\";\n        color=\"invis\";\n        subgraph clusterSubC {\n            node[group=\"\";shape=\"invtriangle\";margin=\"0.01,0.01\"];\n            A_u2[label=\"u\"];\n            {   rank=\"same\";\n                A_ut1[color=\"invis\";shape=\"point\";width=\"0.00000001\"];\n                A_v2[label=\"v\"];\n                A_ut2[color=\"invis\";shape=\"point\";width=\"0.00000001\"];\n            }\n\n            A_ut1 -> A_v2 -> A_ut2[style=\"invisible\",dir=\"none\"];\n            A_u2 -> A_v2[style=\"invisible\",dir=\"none\"];\n        }\n\n        A_result[shape=\"record\";label=\"{<a> | a} | {<b> | b} | {<d> | d}\"];\n\n        {   edge[dir=\"back\"];\n            A_u2:sw -> A_ut1:n;\n            A_v2:s -> A_result:b:n;\n            A_u2:se -> A_ut2:n;\n            A_v2:s -> A_result:n[style=\"invisible\",dir=\"none\"];\n        }\n\n        {   edge[dir=\"none\";constraint=\"false\"];\n            A_ut1:s -> A_result:a:n;\n            A_ut2:s -> A_result:d:n;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/Block.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    subgraph clusterA {\n        color=\"invis\";\n        {   node[shape=\"record\"];\n            BasicBlockStartState[URL=\"../BasicBlockStartState.html\";label=\"{BasicBlockStartState | {<alt1> alt 1 |<alt2> alt 2 | &#0183;\\n&#0183;\\n&#0183; |<altn> alt n}}\"];\n            BlockEndState[URL=\"../BlockEndState.html\"];\n        }\n\n        {   node[style=\"dashed\"];\n            content1[label=\"alt 1\"];\n            content2[label=\"alt 2\"];\n            more[label=\"alt n\"];\n        }\n    }\n\n    {   node[style=\"dashed\"];\n        begin;\n        end;\n    }\n\n    begin -> BasicBlockStartState[style=\"dashed\"];\n    BlockEndState -> end[label=\"&#0949;\"];\n\n    BasicBlockStartState:alt1 -> content1[label=\"&#0949;\"];\n    content1 -> BlockEndState[style=\"dashed\"];\n\n    BasicBlockStartState:alt2 -> content2[label=\"&#0949;\"];\n    content2 -> BlockEndState[style=\"dashed\"];\n\n    BasicBlockStartState:altn -> more[label=\"&#0949;\"];\n    more -> BlockEndState[style=\"dashed\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/ClosureGreedy.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    subgraph cluster0 {\n        color=\"invis\";\n        {   node[shape=\"record\"];\n            StarLoopEntryState[URL=\"../StarLoopEntryState.html\";label=\"{StarLoopEntryState | {<alt1> alt 1 |<alt2> alt 2}}\"];\n            StarLoopbackState[URL=\"../StarLoopbackState.html\"];\n            StarBlockStartState[URL=\"../StarBlockStartState.html\";label=\"{StarBlockStartState | {<alt1> alt 1 |<alt2> alt 2 | &#0183;\\n&#0183;\\n&#0183; |<altn> alt n}}\"];\n            BlockEndState[URL=\"../BlockEndState.html\"];\n\n            {   rank=\"sink\";\n                LoopEndState[URL=\"../LoopEndState.html\";rank=\"max\"];\n            }\n        }\n\n        {   node[style=\"dashed\"];\n            content1[label=\"alt 1\"];\n            content2[label=\"alt 2\"];\n            more[label=\"alt n\"];\n        }\n    }\n\n    {   node[style=\"dashed\"];\n        begin;\n        end;\n    }\n\n    begin -> StarLoopEntryState[style=\"dashed\"];\n    LoopEndState -> end[label=\"&#0949;\"];\n\n    StarBlockStartState:alt1 -> content1[label=\"&#0949;\"];\n    content1 -> BlockEndState[style=\"dashed\"];\n\n    StarBlockStartState:alt2 -> content2[label=\"&#0949;\"];\n    content2 -> BlockEndState[style=\"dashed\"];\n\n    StarBlockStartState:altn -> more[label=\"&#0949;\"];\n    more -> BlockEndState[style=\"dashed\"];\n\n    BlockEndState:e -> StarLoopbackState:w[label=\"&#0949;\"];\n    StarLoopEntryState:alt1 -> StarBlockStartState[label=\"&#0949;\"];\n    StarLoopEntryState:alt2 -> LoopEndState[label=\"&#0949;\"];\n    StarLoopbackState:n -> StarLoopEntryState:n[label=\"&#0949;\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/ClosureNonGreedy.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    subgraph cluster0 {\n        color=\"invis\";\n        {   node[shape=\"record\"];\n            StarLoopEntryState[URL=\"../StarLoopEntryState.html\";label=\"{StarLoopEntryState | {<alt1> alt 1 |<alt2> alt 2}}\"];\n            StarLoopbackState[URL=\"../StarLoopbackState.html\"];\n            StarBlockStartState[URL=\"../StarBlockStartState.html\";label=\"{StarBlockStartState | {<alt1> alt 1 |<alt2> alt 2 | &#0183;\\n&#0183;\\n&#0183; |<altn> alt n}}\"];\n            BlockEndState[URL=\"../BlockEndState.html\"];\n\n            {   rank=\"sink\";\n                LoopEndState[URL=\"../LoopEndState.html\";rank=\"max\"];\n            }\n        }\n\n        {   node[style=\"dashed\"];\n            content1[label=\"alt 1\"];\n            content2[label=\"alt 2\"];\n            more[label=\"alt n\"];\n        }\n    }\n\n    {   node[style=\"dashed\"];\n        begin;\n        end;\n    }\n\n    begin -> StarLoopEntryState[style=\"dashed\"];\n    LoopEndState -> end[label=\"&#0949;\"];\n\n    StarBlockStartState:alt1 -> content1[label=\"&#0949;\"];\n    content1 -> BlockEndState[style=\"dashed\"];\n\n    StarBlockStartState:alt2 -> content2[label=\"&#0949;\"];\n    content2 -> BlockEndState[style=\"dashed\"];\n\n    StarBlockStartState:altn -> more[label=\"&#0949;\"];\n    more -> BlockEndState[style=\"dashed\"];\n\n    BlockEndState:e -> StarLoopbackState:w[label=\"&#0949;\"];\n    StarLoopEntryState:alt2 -> StarBlockStartState[label=\"&#0949;\"];\n    StarLoopEntryState:alt1 -> LoopEndState[label=\"&#0949;\"];\n    StarLoopbackState:s -> StarLoopEntryState:s[label=\"&#0949;\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/FullMerge_EmptyRoot.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        lefttree[label=\"\"];\n        left[label=\"$\"];\n\n        lefttree -> left[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph AB {\n        optree[shape=\"none\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n\n        optree -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph R {\n        righttree[shape=\"none\";label=\"\"];\n        right[shape=\"invtriangle\";label=\"x\"];\n\n        righttree -> right[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph Res {\n        node[shape=\"none\"];\n        resulttree[shape=\"invtriangle\";label=\"\"];\n        result[shape=\"record\";label=\"{ | $} | {<x> | x}\"];\n\n        resulttree -> result:x:n[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/FullMerge_EmptyRoots.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        left[shape=\"none\";label=\"$\"];\n    }\n\n    subgraph AB {\n        temp1[shape=\"none\";label=\"+\"];\n    }\n\n    subgraph R {\n        right[shape=\"none\";label=\"$\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2b;\n        temp2c;\n\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph Res {\n        result[shape=\"none\";label=\"$\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/FullMerge_SameRoot.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        lefttree[label=\"\"];\n        left[label=\"$\"];\n        leftroot[label=\"a\"];\n\n        lefttree -> left[style=\"invisible\";dir=\"none\"];\n        left -> leftroot[dir=\"back\"];\n    }\n\n    subgraph AB {\n        optree[shape=\"none\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n\n        optree -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph R {\n        righttree[shape=\"none\";label=\"\"];\n        right[shape=\"invtriangle\";label=\"x\"];\n        rightroot[shape=\"none\";label=\"a\"];\n\n        righttree -> right[style=\"invisible\";dir=\"none\"];\n        right -> rightroot[dir=\"back\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph Res {\n        node[shape=\"none\"];\n        resulttree[shape=\"invtriangle\";label=\"\"];\n        result[shape=\"record\";label=\"{ | $} | {<x> | x}\"];\n        resultroot[label=\"a'\"];\n\n        resulttree -> result:x:n[dir=\"back\"];\n        result -> resultroot[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/LocalMerge_DiffRoots.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        left[label=\"$\"];\n        leftroot[label=\"a\"];\n\n        left -> leftroot[dir=\"back\"];\n    }\n\n    subgraph AB {\n        temp1[shape=\"none\";label=\"+\"];\n    }\n\n    subgraph R {\n        right[shape=\"invtriangle\";label=\"x\"];\n        rightroot[shape=\"none\";label=\"b\"];\n\n        right -> rightroot[dir=\"back\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2b;\n        temp2c;\n\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph Res {\n        node[shape=\"none\"];\n        result[label=\"$\"];\n        resultroot[shape=\"record\";label=\"{<a> | a} | {<b> | b}\"];\n\n        result -> resultroot:a:n[dir=\"back\"];\n        result -> resultroot:b:n[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/LocalMerge_EmptyParent.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        left[label=\"$\"];\n        leftroot[label=\"a\"];\n\n        left -> leftroot[dir=\"back\"];\n    }\n\n    subgraph AB {\n        temp1[shape=\"none\";label=\"+\"];\n    }\n\n    subgraph R {\n        right[shape=\"invtriangle\";label=\"x\"];\n        rightroot[shape=\"none\";label=\"a\"];\n\n        right -> rightroot[dir=\"back\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2b;\n        temp2c;\n\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph Res {\n        node[shape=\"none\"];\n        result[label=\"$\"];\n        resultroot[label=\"a\"];\n\n        result -> resultroot[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/LocalMerge_EmptyRoot.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        left[shape=\"none\";label=\"$\"];\n    }\n\n    subgraph AB {\n        temp1[shape=\"none\";label=\"+\"];\n    }\n\n    subgraph R {\n        right[shape=\"invtriangle\";label=\"x\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2b;\n        temp2c;\n\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph Res {\n        result[shape=\"none\";label=\"$\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/OptionalGreedy.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    subgraph cluster0 {\n        color=\"invis\";\n        {   node[shape=\"record\"];\n            BasicBlockStartState[URL=\"../BasicBlockStartState.html\";label=\"{BasicBlockStartState | {<alt1> alt 1 |<alt2> alt 2}}\"];\n            BlockEndState[URL=\"../BlockEndState.html\"];\n        }\n\n        {   node[style=\"dashed\"];\n            content[label=\"alt\"];\n        }\n    }\n\n    {   node[style=\"dashed\"];\n        begin;\n        end;\n    }\n\n    begin -> BasicBlockStartState[style=\"dashed\"];\n    BlockEndState -> end[label=\"&#0949;\"];\n\n    BasicBlockStartState:alt1 -> content[label=\"&#0949;\"];\n    content -> BlockEndState[style=\"dashed\"];\n\n    BasicBlockStartState:alt2 -> BlockEndState[label=\"&#0949;\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/OptionalNonGreedy.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    subgraph cluster0 {\n        color=\"invis\";\n        {   node[shape=\"record\"];\n            BasicBlockStartState[URL=\"../BasicBlockStartState.html\";label=\"{BasicBlockStartState | {<alt1> alt 1 |<alt2> alt 2}}\"];\n            BlockEndState[URL=\"../BlockEndState.html\"];\n        }\n\n        {   node[style=\"dashed\"];\n            content[label=\"alt\"];\n        }\n    }\n\n    {   node[style=\"dashed\"];\n        begin;\n        end;\n    }\n\n    begin -> BasicBlockStartState[style=\"dashed\"];\n    BlockEndState -> end[label=\"&#0949;\"];\n\n    BasicBlockStartState:alt2 -> content[label=\"&#0949;\"];\n    content -> BlockEndState[style=\"dashed\"];\n\n    BasicBlockStartState:alt1 -> BlockEndState[label=\"&#0949;\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/PositiveClosureGreedy.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    subgraph cluster0 {\n        color=\"invis\";\n        {   node[shape=\"record\"];\n            {   rank=\"source\";\n                PlusBlockStartState[URL=\"../PlusBlockStartState.html\";label=\"{PlusBlockStartState | {<alt1> alt 1 |<alt2> alt 2 | &#0183;\\n&#0183;\\n&#0183; |<altn> alt n}}\"];\n            }\n\n            PlusLoopbackState[URL=\"../PlusLoopbackState.html\";label=\"{PlusLoopbackState | {<alt1> alt 1 |<alt2> alt 2}}\"];\n            BlockEndState[URL=\"../BlockEndState.html\"];\n\n            {   rank=\"sink\";\n                LoopEndState[URL=\"../LoopEndState.html\"];\n            }\n        }\n\n        {   node[style=\"dashed\"];\n            content1[label=\"alt 1\"];\n            content2[label=\"alt 2\"];\n            more[label=\"alt n\"];\n        }\n    }\n\n    {   node[style=\"dashed\"];\n        begin;\n        end;\n    }\n\n    begin -> PlusBlockStartState[style=\"dashed\"];\n    LoopEndState -> end[label=\"&#0949;\"];\n\n    PlusBlockStartState:alt1 -> content1[label=\"&#0949;\"];\n    content1 -> BlockEndState[style=\"dashed\"];\n\n    PlusBlockStartState:alt2 -> content2[label=\"&#0949;\"];\n    content2 -> BlockEndState[style=\"dashed\"];\n\n    PlusBlockStartState:altn -> more[label=\"&#0949;\"];\n    more -> BlockEndState[style=\"dashed\"];\n\n    BlockEndState -> PlusLoopbackState[label=\"&#0949;\"];\n    PlusLoopbackState:alt1:n -> PlusBlockStartState:n[label=\"&#0949;\"];\n    PlusLoopbackState:alt2 -> LoopEndState[label=\"&#0949;\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/PositiveClosureNonGreedy.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    subgraph cluster0 {\n        color=\"invis\";\n        {   node[shape=\"record\"];\n            {   rank=\"source\";\n                PlusBlockStartState[URL=\"../PlusBlockStartState.html\";label=\"{PlusBlockStartState | {<alt1> alt 1 |<alt2> alt 2 | &#0183;\\n&#0183;\\n&#0183; |<altn> alt n}}\"];\n            }\n\n            PlusLoopbackState[URL=\"../PlusLoopbackState.html\";label=\"{PlusLoopbackState | {<alt1> alt 1 |<alt2> alt 2}}\"];\n            BlockEndState[URL=\"../BlockEndState.html\"];\n\n            {   rank=\"sink\";\n                LoopEndState[URL=\"../LoopEndState.html\"];\n            }\n        }\n\n        {   node[style=\"dashed\"];\n            content1[label=\"alt 1\"];\n            content2[label=\"alt 2\"];\n            more[label=\"alt n\"];\n        }\n    }\n\n    {   node[style=\"dashed\"];\n        begin;\n        end;\n    }\n\n    begin -> PlusBlockStartState[style=\"dashed\"];\n    LoopEndState -> end[label=\"&#0949;\"];\n\n    PlusBlockStartState:alt1 -> content1[label=\"&#0949;\"];\n    content1 -> BlockEndState[style=\"dashed\"];\n\n    PlusBlockStartState:alt2 -> content2[label=\"&#0949;\"];\n    content2 -> BlockEndState[style=\"dashed\"];\n\n    PlusBlockStartState:altn -> more[label=\"&#0949;\"];\n    more -> BlockEndState[style=\"dashed\"];\n\n    BlockEndState -> PlusLoopbackState[label=\"&#0949;\"];\n    PlusLoopbackState:alt2:s -> PlusBlockStartState:s[label=\"&#0949;\"];\n    PlusLoopbackState:alt1 -> LoopEndState[label=\"&#0949;\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/Rule.dot",
    "content": "digraph \"\" {\n    graph[fontname=\"CourierNew\";rankdir=\"LR\";pad=\"0.25\"];\n    node[fontname=\"CourierNew\";target=\"_parent\"];\n    edge[fontname=\"CourierNew\"];\n    {   node[shape=\"box\"];\n        RuleStartState[URL=\"../RuleStartState.html\"];\n        RuleStopState[URL=\"../RuleStopState.html\"];\n    }\n    {   node[style=\"dashed\"];\n        content;\n    }\n\n    RuleStartState -> content[label=\"&#0949;\"];\n    content -> RuleStopState[style=\"dashed\"];\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/SingletonMerge_DiffRootDiffPar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        left[shape=\"invtriangle\";label=\"x\"];\n        leftroot[label=\"a\"];\n\n        left -> leftroot[dir=\"back\"];\n    }\n\n    subgraph AB {\n        temp1[shape=\"none\";label=\"+\"];\n    }\n\n    subgraph R {\n        right[shape=\"invtriangle\";label=\"y\"];\n        rightroot[shape=\"none\";label=\"b\"];\n\n        right -> rightroot[dir=\"back\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2b;\n        temp2c;\n\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterRes {\n        color=\"invis\";\n        resulttree1[shape=\"invtriangle\";label=\"x\"];\n        resulttree2[shape=\"invtriangle\";label=\"y\"];\n        result[shape=\"record\";label=\"{<a> | a} | {<b> | b}\"];\n\n        resulttree1:s -> result:a:n[dir=\"back\"];\n        resulttree2:s -> result:b:n[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/SingletonMerge_DiffRootSamePar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        left[shape=\"invtriangle\";label=\"x\"];\n        leftroot[label=\"a\"];\n\n        left -> leftroot[dir=\"back\"];\n    }\n\n    subgraph AB {\n        temp1[shape=\"none\";label=\"+\"];\n    }\n\n    subgraph R {\n        right[shape=\"invtriangle\";label=\"x\"];\n        rightroot[shape=\"none\";label=\"b\"];\n\n        right -> rightroot[dir=\"back\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2b;\n        temp2c;\n\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterRes {\n        color=\"invis\";\n        resulttree[shape=\"invtriangle\";label=\"x\"];\n        result[shape=\"record\";label=\"{<a> | a} | {<b> | b}\"];\n\n        resulttree -> result:a:n[dir=\"back\"];\n        resulttree -> result:b:n[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/SingletonMerge_SameRootDiffPar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        lefttree[label=\"\"];\n        left[shape=\"invtriangle\";label=\"x\"];\n        leftroot[label=\"a\"];\n\n        lefttree -> left[style=\"invisible\";dir=\"none\"];\n        left -> leftroot[dir=\"back\"];\n    }\n\n    subgraph AB {\n        optree[shape=\"none\";label=\"\"];\n        temp1[shape=\"none\";label=\"+\"];\n\n        optree -> temp1[style=\"invisible\";dir=\"none\"];\n    }\n\n    subgraph R {\n        righttree[shape=\"none\";label=\"\"];\n        right[shape=\"invtriangle\";label=\"y\"];\n        rightroot[shape=\"none\";label=\"a\"];\n\n        righttree -> right[style=\"invisible\";dir=\"none\"];\n        right -> rightroot[dir=\"back\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2a;\n        {   rank=\"same\";\n            temp2b;\n            temp2c;\n        }\n\n        temp2a -> temp2b[style=\"invisible\";dir=\"none\"];\n        temp2a -> temp2c[style=\"invisible\";dir=\"none\"];\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterRes {\n        color=\"invis\";\n        resulttree1[shape=\"invtriangle\";label=\"\"];\n        resulttree2[shape=\"invtriangle\";label=\"\"];\n        result[shape=\"record\";label=\"{<x> | x} | {<y> | y}\"];\n        resultroot[shape=\"none\";label=\"a'\"];\n\n        resulttree1:s -> result:x:n[dir=\"back\"];\n        resulttree2:s -> result:y:n[dir=\"back\"];\n        result -> resultroot[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/main/dot/org/antlr/v4/runtime/atn/images/SingletonMerge_SameRootSamePar.dot",
    "content": "digraph \"\" {\n    graph[dpi=\"60\";compound=\"true\"];\n\n    subgraph L {\n        node[shape=\"none\"];\n        left[shape=\"invtriangle\";label=\"x\"];\n        leftroot[label=\"a\"];\n\n        left -> leftroot[dir=\"back\"];\n    }\n\n    subgraph AB {\n        temp1[shape=\"none\";label=\"+\"];\n    }\n\n    subgraph R {\n        right[shape=\"invtriangle\";label=\"x\"];\n        rightroot[shape=\"none\";label=\"a\"];\n\n        right -> rightroot[dir=\"back\"];\n    }\n\n    subgraph BC {\n        node[color=\"invis\";shape=\"point\"];\n        temp2b;\n        temp2c;\n\n        temp2b -> temp2c[constraint=\"false\";label=\"wwwwwww\";fontcolor=\"invis\"];\n    }\n\n    subgraph clusterRes {\n        color=\"invis\";\n        result[shape=\"invtriangle\";label=\"x\"];\n        resultroot[shape=\"none\";label=\"a\"];\n\n        result -> resultroot[dir=\"back\"];\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ANTLRErrorListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.atn.DecisionInfo;\nimport org.antlr.v4.runtime.atn.ParserATNSimulator;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.dfa.DFA;\n\nimport java.util.BitSet;\n\n/** How to emit recognition errors. */\npublic interface ANTLRErrorListener {\n\t/**\n\t * Upon syntax error, notify any interested parties. This is not how to\n\t * recover from errors or compute error messages. {@link ANTLRErrorStrategy}\n\t * specifies how to recover from syntax errors and how to compute error\n\t * messages. This listener's job is simply to emit a computed message,\n\t * though it has enough information to create its own message in many cases.\n\t *\n\t * <p>The {@link RecognitionException} is non-null for all syntax errors except\n\t * when we discover mismatched token errors that we can recover from\n\t * in-line, without returning from the surrounding rule (via the single\n\t * token insertion and deletion mechanism).</p>\n\t *\n\t * @param recognizer\n     *        What parser got the error. From this\n\t * \t\t  object, you can access the context as well\n\t * \t\t  as the input stream.\n\t * @param offendingSymbol\n\t *        The offending token in the input token\n\t * \t\t  stream, unless recognizer is a lexer (then it's null). If\n\t * \t\t  no viable alternative error, {@code e} has token at which we\n\t * \t\t  started production for the decision.\n\t * @param line\n\t * \t\t  The line number in the input where the error occurred.\n\t * @param charPositionInLine\n\t * \t\t  The character position within that line where the error occurred.\n\t * @param msg\n\t * \t\t  The message to emit.\n\t * @param e\n\t *        The exception generated by the parser that led to\n\t *        the reporting of an error. It is null in the case where\n\t *        the parser was able to recover in line without exiting the\n\t *        surrounding rule.\n\t */\n\tpublic void syntaxError(Recognizer<?, ?> recognizer,\n\t\t\t\t\t\t\tObject offendingSymbol,\n\t\t\t\t\t\t\tint line,\n\t\t\t\t\t\t\tint charPositionInLine,\n\t\t\t\t\t\t\tString msg,\n\t\t\t\t\t\t\tRecognitionException e);\n\n\t/**\n\t * This method is called by the parser when a full-context prediction\n\t * results in an ambiguity.\n\t *\n\t * <p>Each full-context prediction which does not result in a syntax error\n\t * will call either {@link #reportContextSensitivity} or\n\t * {@link #reportAmbiguity}.</p>\n\t *\n\t * <p>When {@code ambigAlts} is not null, it contains the set of potentially\n\t * viable alternatives identified by the prediction algorithm. When\n\t * {@code ambigAlts} is null, use {@link ATNConfigSet#getAlts} to obtain the\n\t * represented alternatives from the {@code configs} argument.</p>\n\t *\n\t * <p>When {@code exact} is {@code true}, <em>all</em> of the potentially\n\t * viable alternatives are truly viable, i.e. this is reporting an exact\n\t * ambiguity. When {@code exact} is {@code false}, <em>at least two</em> of\n\t * the potentially viable alternatives are viable for the current input, but\n\t * the prediction algorithm terminated as soon as it determined that at\n\t * least the <em>minimum</em> potentially viable alternative is truly\n\t * viable.</p>\n\t *\n\t * <p>When the {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} prediction\n\t * mode is used, the parser is required to identify exact ambiguities so\n\t * {@code exact} will always be {@code true}.</p>\n\t *\n\t * <p>This method is not used by lexers.</p>\n\t *\n\t * @param recognizer the parser instance\n\t * @param dfa the DFA for the current decision\n\t * @param startIndex the input index where the decision started\n\t * @param stopIndex the input input where the ambiguity was identified\n\t * @param exact {@code true} if the ambiguity is exactly known, otherwise\n\t * {@code false}. This is always {@code true} when\n\t * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used.\n\t * @param ambigAlts the potentially ambiguous alternatives, or {@code null}\n\t * to indicate that the potentially ambiguous alternatives are the complete\n\t * set of represented alternatives in {@code configs}\n\t * @param configs the ATN configuration set where the ambiguity was\n\t * identified\n\t */\n\tvoid reportAmbiguity(Parser recognizer,\n\t\t\t\t\t\t DFA dfa,\n\t\t\t\t\t\t int startIndex,\n\t\t\t\t\t\t int stopIndex,\n\t\t\t\t\t\t boolean exact,\n\t\t\t\t\t\t BitSet ambigAlts,\n\t\t\t\t\t\t ATNConfigSet configs);\n\n\t/**\n\t * This method is called when an SLL conflict occurs and the parser is about\n\t * to use the full context information to make an LL decision.\n\t *\n\t * <p>If one or more configurations in {@code configs} contains a semantic\n\t * predicate, the predicates are evaluated before this method is called. The\n\t * subset of alternatives which are still viable after predicates are\n\t * evaluated is reported in {@code conflictingAlts}.</p>\n\t *\n\t * <p>This method is not used by lexers.</p>\n\t *\n\t * @param recognizer the parser instance\n\t * @param dfa the DFA for the current decision\n\t * @param startIndex the input index where the decision started\n\t * @param stopIndex the input index where the SLL conflict occurred\n\t * @param conflictingAlts The specific conflicting alternatives. If this is\n\t * {@code null}, the conflicting alternatives are all alternatives\n\t * represented in {@code configs}. At the moment, conflictingAlts is non-null\n\t * (for the reference implementation, but Sam's optimized version can see this\n\t * as null).\n\t * @param configs the ATN configuration set where the SLL conflict was\n\t * detected\n\t */\n\tvoid reportAttemptingFullContext(Parser recognizer,\n\t\t\t\t\t\t\t\t\t DFA dfa,\n\t\t\t\t\t\t\t\t\t int startIndex,\n\t\t\t\t\t\t\t\t\t int stopIndex,\n\t\t\t\t\t\t\t\t\t BitSet conflictingAlts,\n\t\t\t\t\t\t\t\t\t ATNConfigSet configs);\n\n\t/**\n\t * This method is called by the parser when a full-context prediction has a\n\t * unique result.\n\t *\n\t * <p>Each full-context prediction which does not result in a syntax error\n\t * will call either {@link #reportContextSensitivity} or\n\t * {@link #reportAmbiguity}.</p>\n\t *\n\t * <p>For prediction implementations that only evaluate full-context\n\t * predictions when an SLL conflict is found (including the default\n\t * {@link ParserATNSimulator} implementation), this method reports cases\n\t * where SLL conflicts were resolved to unique full-context predictions,\n\t * i.e. the decision was context-sensitive. This report does not necessarily\n\t * indicate a problem, and it may appear even in completely unambiguous\n\t * grammars.</p>\n\t *\n\t * <p>{@code configs} may have more than one represented alternative if the\n\t * full-context prediction algorithm does not evaluate predicates before\n\t * beginning the full-context prediction. In all cases, the final prediction\n\t * is passed as the {@code prediction} argument.</p>\n\t *\n\t * <p>Note that the definition of \"context sensitivity\" in this method\n\t * differs from the concept in {@link DecisionInfo#contextSensitivities}.\n\t * This method reports all instances where an SLL conflict occurred but LL\n\t * parsing produced a unique result, whether or not that unique result\n\t * matches the minimum alternative in the SLL conflicting set.</p>\n\t *\n\t * <p>This method is not used by lexers.</p>\n\t *\n\t * @param recognizer the parser instance\n\t * @param dfa the DFA for the current decision\n\t * @param startIndex the input index where the decision started\n\t * @param stopIndex the input index where the context sensitivity was\n\t * finally determined\n\t * @param prediction the unambiguous result of the full-context prediction\n\t * @param configs the ATN configuration set where the unambiguous prediction\n\t * was determined\n\t */\n\tvoid reportContextSensitivity(Parser recognizer,\n\t\t\t\t\t\t\t\t  DFA dfa,\n\t\t\t\t\t\t\t\t  int startIndex,\n\t\t\t\t\t\t\t\t  int stopIndex,\n\t\t\t\t\t\t\t\t  int prediction,\n\t\t\t\t\t\t\t\t  ATNConfigSet configs);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ANTLRErrorStrategy.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.tree.ErrorNode;\n\n/**\n * The interface for defining strategies to deal with syntax errors encountered\n * during a parse by ANTLR-generated parsers. We distinguish between three\n * different kinds of errors:\n *\n * <ul>\n * <li>The parser could not figure out which path to take in the ATN (none of\n * the available alternatives could possibly match)</li>\n * <li>The current input does not match what we were looking for</li>\n * <li>A predicate evaluated to false</li>\n * </ul>\n *\n * Implementations of this interface report syntax errors by calling\n * {@link Parser#notifyErrorListeners}.\n *\n * <p>TODO: what to do about lexers</p>\n */\npublic interface ANTLRErrorStrategy {\n\t/**\n\t * Reset the error handler state for the specified {@code recognizer}.\n\t * @param recognizer the parser instance\n\t */\n\tvoid reset(Parser recognizer);\n\n\t/**\n\t * This method is called when an unexpected symbol is encountered during an\n\t * inline match operation, such as {@link Parser#match}. If the error\n\t * strategy successfully recovers from the match failure, this method\n\t * returns the {@link Token} instance which should be treated as the\n\t * successful result of the match.\n\t *\n   * <p>This method handles the consumption of any tokens - the caller should\n\t * <b>not</b> call {@link Parser#consume} after a successful recovery.</p>\n\t *\n\t * <p>Note that the calling code will not report an error if this method\n\t * returns successfully. The error strategy implementation is responsible\n\t * for calling {@link Parser#notifyErrorListeners} as appropriate.</p>\n\t *\n\t * @param recognizer the parser instance\n\t * @throws RecognitionException if the error strategy was not able to\n\t * recover from the unexpected input symbol\n\t */\n\tToken recoverInline(Parser recognizer) throws RecognitionException;\n\n\t/**\n\t * This method is called to recover from exception {@code e}. This method is\n\t * called after {@link #reportError} by the default exception handler\n\t * generated for a rule method.\n\t *\n\t * @see #reportError\n\t *\n\t * @param recognizer the parser instance\n\t * @param e the recognition exception to recover from\n\t * @throws RecognitionException if the error strategy could not recover from\n\t * the recognition exception\n\t */\n\tvoid recover(Parser recognizer, RecognitionException e) throws RecognitionException;\n\n\t/**\n\t * This method provides the error handler with an opportunity to handle\n\t * syntactic or semantic errors in the input stream before they result in a\n\t * {@link RecognitionException}.\n\t *\n\t * <p>The generated code currently contains calls to {@link #sync} after\n\t * entering the decision state of a closure block ({@code (...)*} or\n\t * {@code (...)+}).</p>\n\t *\n\t * <p>For an implementation based on Jim Idle's \"magic sync\" mechanism, see\n\t * {@link DefaultErrorStrategy#sync}.</p>\n\t *\n\t * @see DefaultErrorStrategy#sync\n\t *\n\t * @param recognizer the parser instance\n\t * @throws RecognitionException if an error is detected by the error\n\t * strategy but cannot be automatically recovered at the current state in\n\t * the parsing process\n\t */\n\tvoid sync(Parser recognizer) throws RecognitionException;\n\n\t/**\n\t * Tests whether or not {@code recognizer} is in the process of recovering\n\t * from an error. In error recovery mode, {@link Parser#consume} adds\n\t * symbols to the parse tree by calling\n\t * {@link Parser#createErrorNode(ParserRuleContext, Token)} then\n\t * {@link ParserRuleContext#addErrorNode(ErrorNode)} instead of\n\t * {@link Parser#createTerminalNode(ParserRuleContext, Token)}.\n\t *\n\t * @param recognizer the parser instance\n\t * @return {@code true} if the parser is currently recovering from a parse\n\t * error, otherwise {@code false}\n\t */\n\tboolean inErrorRecoveryMode(Parser recognizer);\n\n\t/**\n\t * This method is called by when the parser successfully matches an input\n\t * symbol.\n\t *\n\t * @param recognizer the parser instance\n\t */\n\tvoid reportMatch(Parser recognizer);\n\n\t/**\n\t * Report any kind of {@link RecognitionException}. This method is called by\n\t * the default exception handler generated for a rule method.\n\t *\n\t * @param recognizer the parser instance\n\t * @param e the recognition exception to report\n\t */\n\tvoid reportError(Parser recognizer, RecognitionException e);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ANTLRFileStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Utils;\n\nimport java.io.IOException;\n\n/**\n * This is an {@link ANTLRInputStream} that is loaded from a file all at once\n * when you construct the object.\n *\n * @deprecated as of 4.7 Please use {@link CharStreams} interface.\n */\n@Deprecated\npublic class ANTLRFileStream extends ANTLRInputStream {\n\tprotected String fileName;\n\n\tpublic ANTLRFileStream(String fileName) throws IOException {\n\t\tthis(fileName, null);\n\t}\n\n\tpublic ANTLRFileStream(String fileName, String encoding) throws IOException {\n\t\tthis.fileName = fileName;\n\t\tload(fileName, encoding);\n\t}\n\n\tpublic void load(String fileName, String encoding)\n\t\tthrows IOException\n\t{\n\t\tdata = Utils.readFile(fileName, encoding);\n\t\tthis.n = data.length;\n\t}\n\n\t@Override\n\tpublic String getSourceName() {\n\t\treturn fileName;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ANTLRInputStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.util.Arrays;\n\n/**\n * Vacuum all input from a {@link Reader}/{@link InputStream} and then treat it\n * like a {@code char[]} buffer. Can also pass in a {@link String} or\n * {@code char[]} to use.\n *\n * <p>If you need encoding, pass in stream/reader with correct encoding.</p>\n *\n * @deprecated as of 4.7 Please use {@link CharStreams} interface.\n */\n@Deprecated\npublic class ANTLRInputStream implements CharStream {\n    public static final int READ_BUFFER_SIZE = 1024;\n   \tpublic static final int INITIAL_BUFFER_SIZE = 1024;\n\n\t/** The data being scanned */\n\tprotected char[] data;\n\n\t/** How many characters are actually in the buffer */\n\tprotected int n;\n\n\t/** 0..n-1 index into string of next char */\n\tprotected int p=0;\n\n\t/** What is name or source of this char stream? */\n\tpublic String name;\n\n    public ANTLRInputStream() { }\n\n\t/** Copy data in string to a local char array */\n\tpublic ANTLRInputStream(String input) {\n\t\tthis.data = input.toCharArray();\n\t\tthis.n = input.length();\n\t}\n\n\t/** This is the preferred constructor for strings as no data is copied */\n\tpublic ANTLRInputStream(char[] data, int numberOfActualCharsInArray) {\n\t\tthis.data = data;\n\t\tthis.n = numberOfActualCharsInArray;\n\t}\n\n    public ANTLRInputStream(Reader r) throws IOException {\n        this(r, INITIAL_BUFFER_SIZE, READ_BUFFER_SIZE);\n    }\n\n    public ANTLRInputStream(Reader r, int initialSize) throws IOException {\n        this(r, initialSize, READ_BUFFER_SIZE);\n    }\n\n    public ANTLRInputStream(Reader r, int initialSize, int readChunkSize) throws IOException {\n        load(r, initialSize, readChunkSize);\n    }\n\n\tpublic ANTLRInputStream(InputStream input) throws IOException {\n\t\tthis(new InputStreamReader(input), INITIAL_BUFFER_SIZE);\n\t}\n\n\tpublic ANTLRInputStream(InputStream input, int initialSize) throws IOException {\n\t\tthis(new InputStreamReader(input), initialSize);\n\t}\n\n\tpublic ANTLRInputStream(InputStream input, int initialSize, int readChunkSize) throws IOException {\n\t\tthis(new InputStreamReader(input), initialSize, readChunkSize);\n\t}\n\n\tpublic void load(Reader r, int size, int readChunkSize)\n\t\tthrows IOException\n\t{\n\t\tif ( r==null ) {\n\t\t\treturn;\n\t\t}\n\t\tif ( size<=0 ) {\n\t\t\tsize = INITIAL_BUFFER_SIZE;\n\t\t}\n\t\tif ( readChunkSize<=0 ) {\n\t\t\treadChunkSize = READ_BUFFER_SIZE;\n   \t\t}\n   \t\t// System.out.println(\"load \"+size+\" in chunks of \"+readChunkSize);\n   \t\ttry {\n   \t\t\t// alloc initial buffer size.\n   \t\t\tdata = new char[size];\n   \t\t\t// read all the data in chunks of readChunkSize\n   \t\t\tint numRead=0;\n   \t\t\tint p = 0;\n   \t\t\tdo {\n   \t\t\t\tif ( p+readChunkSize > data.length ) { // overflow?\n   \t\t\t\t\t// System.out.println(\"### overflow p=\"+p+\", data.length=\"+data.length);\n   \t\t\t\t\tdata = Arrays.copyOf(data, data.length * 2);\n   \t\t\t\t}\n   \t\t\t\tnumRead = r.read(data, p, readChunkSize);\n   \t\t\t\t// System.out.println(\"read \"+numRead+\" chars; p was \"+p+\" is now \"+(p+numRead));\n   \t\t\t\tp += numRead;\n   \t\t\t} while (numRead!=-1); // while not EOF\n   \t\t\t// set the actual size of the data available;\n   \t\t\t// EOF subtracted one above in p+=numRead; add one back\n   \t\t\tn = p+1;\n   \t\t\t//System.out.println(\"n=\"+n);\n   \t\t}\n   \t\tfinally {\n   \t\t\tr.close();\n   \t\t}\n   \t}\n\n\t/** Reset the stream so that it's in the same state it was\n\t *  when the object was created *except* the data array is not\n\t *  touched.\n\t */\n\tpublic void reset() {\n\t\tp = 0;\n\t}\n\n    @Override\n    public void consume() {\n\t\tif (p >= n) {\n\t\t\tassert LA(1) == IntStream.EOF;\n\t\t\tthrow new IllegalStateException(\"cannot consume EOF\");\n\t\t}\n\n\t\t//System.out.println(\"prev p=\"+p+\", c=\"+(char)data[p]);\n        if ( p < n ) {\n            p++;\n\t\t\t//System.out.println(\"p moves to \"+p+\" (c='\"+(char)data[p]+\"')\");\n        }\n    }\n\n    @Override\n    public int LA(int i) {\n\t\tif ( i==0 ) {\n\t\t\treturn 0; // undefined\n\t\t}\n\t\tif ( i<0 ) {\n\t\t\ti++; // e.g., translate LA(-1) to use offset i=0; then data[p+0-1]\n\t\t\tif ( (p+i-1) < 0 ) {\n\t\t\t\treturn IntStream.EOF; // invalid; no char before first char\n\t\t\t}\n\t\t}\n\n\t\tif ( (p+i-1) >= n ) {\n            //System.out.println(\"char LA(\"+i+\")=EOF; p=\"+p);\n            return IntStream.EOF;\n        }\n        //System.out.println(\"char LA(\"+i+\")=\"+(char)data[p+i-1]+\"; p=\"+p);\n\t\t//System.out.println(\"LA(\"+i+\"); p=\"+p+\" n=\"+n+\" data.length=\"+data.length);\n\t\treturn data[p+i-1];\n    }\n\n\tpublic int LT(int i) {\n\t\treturn LA(i);\n\t}\n\n\t/** Return the current input symbol index 0..n where n indicates the\n     *  last symbol has been read.  The index is the index of char to\n\t *  be returned from LA(1).\n     */\n    @Override\n    public int index() {\n        return p;\n    }\n\n\t@Override\n\tpublic int size() {\n\t\treturn n;\n\t}\n\n    /** mark/release do nothing; we have entire buffer */\n\t@Override\n\tpublic int mark() {\n\t\treturn -1;\n    }\n\n\t@Override\n\tpublic void release(int marker) {\n\t}\n\n\t/** consume() ahead until p==index; can't just set p=index as we must\n\t *  update line and charPositionInLine. If we seek backwards, just set p\n\t */\n\t@Override\n\tpublic void seek(int index) {\n\t\tif ( index<=p ) {\n\t\t\tp = index; // just jump; don't update stream state (line, ...)\n\t\t\treturn;\n\t\t}\n\t\t// seek forward, consume until p hits index or n (whichever comes first)\n\t\tindex = Math.min(index, n);\n\t\twhile ( p<index ) {\n\t\t\tconsume();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getText(Interval interval) {\n\t\tint start = interval.a;\n\t\tint stop = interval.b;\n\t\tif ( stop >= n ) stop = n-1;\n\t\tint count = stop - start + 1;\n\t\tif ( start >= n ) return \"\";\n//\t\tSystem.err.println(\"data: \"+Arrays.toString(data)+\", n=\"+n+\n//\t\t\t\t\t\t   \", start=\"+start+\n//\t\t\t\t\t\t   \", stop=\"+stop);\n\t\treturn new String(data, start, count);\n\t}\n\n\t@Override\n\tpublic String getSourceName() {\n\t\tif (name == null || name.isEmpty()) {\n\t\t\treturn UNKNOWN_SOURCE_NAME;\n\t\t}\n\n\t\treturn name;\n\t}\n\n    @Override\n    public String toString() { return new String(data); }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/BailErrorStrategy.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.ParseCancellationException;\n\n/**\n * This implementation of {@link ANTLRErrorStrategy} responds to syntax errors\n * by immediately canceling the parse operation with a\n * {@link ParseCancellationException}. The implementation ensures that the\n * {@link ParserRuleContext#exception} field is set for all parse tree nodes\n * that were not completed prior to encountering the error.\n *\n * <p>\n * This error strategy is useful in the following scenarios.</p>\n *\n * <ul>\n * <li><strong>Two-stage parsing:</strong> This error strategy allows the first\n * stage of two-stage parsing to immediately terminate if an error is\n * encountered, and immediately fall back to the second stage. In addition to\n * avoiding wasted work by attempting to recover from errors here, the empty\n * implementation of {@link BailErrorStrategy#sync} improves the performance of\n * the first stage.</li>\n * <li><strong>Silent validation:</strong> When syntax errors are not being\n * reported or logged, and the parse result is simply ignored if errors occur,\n * the {@link BailErrorStrategy} avoids wasting work on recovering from errors\n * when the result will be ignored either way.</li>\n * </ul>\n *\n * <p>\n * {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>\n *\n * @see Parser#setErrorHandler(ANTLRErrorStrategy)\n */\npublic class BailErrorStrategy extends DefaultErrorStrategy {\n    /** Instead of recovering from exception {@code e}, re-throw it wrapped\n     *  in a {@link ParseCancellationException} so it is not caught by the\n     *  rule function catches.  Use {@link Exception#getCause()} to get the\n\t *  original {@link RecognitionException}.\n     */\n    @Override\n    public void recover(Parser recognizer, RecognitionException e) {\n\t\tfor (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {\n\t\t\tcontext.exception = e;\n\t\t}\n\n        throw new ParseCancellationException(e);\n    }\n\n    /** Make sure we don't attempt to recover inline; if the parser\n     *  successfully recovers, it won't throw an exception.\n     */\n    @Override\n    public Token recoverInline(Parser recognizer)\n        throws RecognitionException\n    {\n\t\tInputMismatchException e = new InputMismatchException(recognizer);\n\t\tfor (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {\n\t\t\tcontext.exception = e;\n\t\t}\n\n        throw new ParseCancellationException(e);\n    }\n\n    /** Make sure we don't attempt to recover from problems in subrules. */\n    @Override\n    public void sync(Parser recognizer) { }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/BaseErrorListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.dfa.DFA;\n\nimport java.util.BitSet;\n\n/**\n * Provides an empty default implementation of {@link ANTLRErrorListener}. The\n * default implementation of each method does nothing, but can be overridden as\n * necessary.\n *\n * @author Sam Harwell\n */\npublic class BaseErrorListener implements ANTLRErrorListener {\n\t@Override\n\tpublic void syntaxError(Recognizer<?, ?> recognizer,\n\t\t\t\t\t\t\tObject offendingSymbol,\n\t\t\t\t\t\t\tint line,\n\t\t\t\t\t\t\tint charPositionInLine,\n\t\t\t\t\t\t\tString msg,\n\t\t\t\t\t\t\tRecognitionException e)\n\t{\n\t}\n\n\t@Override\n\tpublic void reportAmbiguity(Parser recognizer,\n\t\t\t\t\t\t\t\tDFA dfa,\n\t\t\t\t\t\t\t\tint startIndex,\n\t\t\t\t\t\t\t\tint stopIndex,\n\t\t\t\t\t\t\t\tboolean exact,\n\t\t\t\t\t\t\t\tBitSet ambigAlts,\n\t\t\t\t\t\t\t\tATNConfigSet configs)\n\t{\n\t}\n\n\t@Override\n\tpublic void reportAttemptingFullContext(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t\tDFA dfa,\n\t\t\t\t\t\t\t\t\t\t\tint startIndex,\n\t\t\t\t\t\t\t\t\t\t\tint stopIndex,\n\t\t\t\t\t\t\t\t\t\t\tBitSet conflictingAlts,\n\t\t\t\t\t\t\t\t\t\t\tATNConfigSet configs)\n\t{\n\t}\n\n\t@Override\n\tpublic void reportContextSensitivity(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t DFA dfa,\n\t\t\t\t\t\t\t\t\t\t int startIndex,\n\t\t\t\t\t\t\t\t\t\t int stopIndex,\n\t\t\t\t\t\t\t\t\t\t int prediction,\n\t\t\t\t\t\t\t\t\t\t ATNConfigSet configs)\n\t{\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/BufferedTokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * This implementation of {@link TokenStream} loads tokens from a\n * {@link TokenSource} on-demand, and places the tokens in a buffer to provide\n * access to any previous token by index.\n *\n * <p>\n * This token stream ignores the value of {@link Token#getChannel}. If your\n * parser requires the token stream filter tokens to only those on a particular\n * channel, such as {@link Token#DEFAULT_CHANNEL} or\n * {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a\n * {@link CommonTokenStream}.</p>\n */\npublic class BufferedTokenStream implements TokenStream {\n\t/**\n\t * The {@link TokenSource} from which tokens for this stream are fetched.\n\t */\n    protected TokenSource tokenSource;\n\n\t/**\n\t * A collection of all tokens fetched from the token source. The list is\n\t * considered a complete view of the input once {@link #fetchedEOF} is set\n\t * to {@code true}.\n\t */\n    protected List<Token> tokens = new ArrayList<Token>(100);\n\n\t/**\n\t * The index into {@link #tokens} of the current token (next token to\n\t * {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be\n\t * {@link #LT LT(1)}.\n\t *\n\t * <p>This field is set to -1 when the stream is first constructed or when\n\t * {@link #setTokenSource} is called, indicating that the first token has\n\t * not yet been fetched from the token source. For additional information,\n\t * see the documentation of {@link IntStream} for a description of\n\t * Initializing Methods.</p>\n\t */\n    protected int p = -1;\n\n\t/**\n\t * Indicates whether the {@link Token#EOF} token has been fetched from\n\t * {@link #tokenSource} and added to {@link #tokens}. This field improves\n\t * performance for the following cases:\n\t *\n\t * <ul>\n\t * <li>{@link #consume}: The lookahead check in {@link #consume} to prevent\n\t * consuming the EOF symbol is optimized by checking the values of\n\t * {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li>\n\t * <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into\n\t * {@link #tokens} is trivial with this field.</li>\n\t * <ul>\n\t */\n\tprotected boolean fetchedEOF;\n\n    public BufferedTokenStream(TokenSource tokenSource) {\n\t\tif (tokenSource == null) {\n\t\t\tthrow new NullPointerException(\"tokenSource cannot be null\");\n\t\t}\n        this.tokenSource = tokenSource;\n    }\n\n    @Override\n    public TokenSource getTokenSource() { return tokenSource; }\n\n\t@Override\n\tpublic int index() { return p; }\n\n    @Override\n    public int mark() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic void release(int marker) {\n\t\t// no resources to release\n\t}\n\n\t/**\n\t * This method resets the token stream back to the first token in the\n\t * buffer. It is equivalent to calling {@link #seek}{@code (0)}.\n\t *\n\t * @see #setTokenSource(TokenSource)\n\t * @deprecated Use {@code seek(0)} instead.\n\t */\n\t@Deprecated\n    public void reset() {\n        seek(0);\n    }\n\n    @Override\n    public void seek(int index) {\n        lazyInit();\n        p = adjustSeekIndex(index);\n    }\n\n    @Override\n    public int size() { return tokens.size(); }\n\n    @Override\n    public void consume() {\n\t\tboolean skipEofCheck;\n\t\tif (p >= 0) {\n\t\t\tif (fetchedEOF) {\n\t\t\t\t// the last token in tokens is EOF. skip check if p indexes any\n\t\t\t\t// fetched token except the last.\n\t\t\t\tskipEofCheck = p < tokens.size() - 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// no EOF token in tokens. skip check if p indexes a fetched token.\n\t\t\t\tskipEofCheck = p < tokens.size();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// not yet initialized\n\t\t\tskipEofCheck = false;\n\t\t}\n\n\t\tif (!skipEofCheck && LA(1) == EOF) {\n\t\t\tthrow new IllegalStateException(\"cannot consume EOF\");\n\t\t}\n\n\t\tif (sync(p + 1)) {\n\t\t\tp = adjustSeekIndex(p + 1);\n\t\t}\n    }\n\n    /** Make sure index {@code i} in tokens has a token.\n\t *\n\t * @return {@code true} if a token is located at index {@code i}, otherwise\n\t *    {@code false}.\n\t * @see #get(int i)\n\t */\n    protected boolean sync(int i) {\n\t\tassert i >= 0;\n        int n = i - tokens.size() + 1; // how many more elements we need?\n        //System.out.println(\"sync(\"+i+\") needs \"+n);\n        if ( n > 0 ) {\n\t\t\tint fetched = fetch(n);\n\t\t\treturn fetched >= n;\n\t\t}\n\n\t\treturn true;\n    }\n\n    /** Add {@code n} elements to buffer.\n\t *\n\t * @return The actual number of elements added to the buffer.\n\t */\n    protected int fetch(int n) {\n\t\tif (fetchedEOF) {\n\t\t\treturn 0;\n\t\t}\n\n        for (int i = 0; i < n; i++) {\n            Token t = tokenSource.nextToken();\n            if ( t instanceof WritableToken ) {\n                ((WritableToken)t).setTokenIndex(tokens.size());\n            }\n            tokens.add(t);\n            if ( t.getType()==Token.EOF ) {\n\t\t\t\tfetchedEOF = true;\n\t\t\t\treturn i + 1;\n\t\t\t}\n        }\n\n\t\treturn n;\n    }\n\n    @Override\n    public Token get(int i) {\n        if ( i < 0 || i >= tokens.size() ) {\n            throw new IndexOutOfBoundsException(\"token index \"+i+\" out of range 0..\"+(tokens.size()-1));\n        }\n        return tokens.get(i);\n    }\n\n\t/** Get all tokens from start..stop inclusively */\n\tpublic List<Token> get(int start, int stop) {\n\t\tif ( start<0 || stop<0 ) return null;\n\t\tlazyInit();\n\t\tList<Token> subset = new ArrayList<Token>();\n\t\tif ( stop>=tokens.size() ) stop = tokens.size()-1;\n\t\tfor (int i = start; i <= stop; i++) {\n\t\t\tToken t = tokens.get(i);\n\t\t\tif ( t.getType()==Token.EOF ) break;\n\t\t\tsubset.add(t);\n\t\t}\n\t\treturn subset;\n\t}\n\n\t@Override\n\tpublic int LA(int i) { return LT(i).getType(); }\n\n    protected Token LB(int k) {\n        if ( (p-k)<0 ) return null;\n        return tokens.get(p-k);\n    }\n\n\n    @Override\n    public Token LT(int k) {\n        lazyInit();\n        if ( k==0 ) return null;\n        if ( k < 0 ) return LB(-k);\n\n\t\tint i = p + k - 1;\n\t\tsync(i);\n        if ( i >= tokens.size() ) { // return EOF token\n            // EOF must be last token\n            return tokens.get(tokens.size()-1);\n        }\n//\t\tif ( i>range ) range = i;\n        return tokens.get(i);\n    }\n\n\t/**\n\t * Allowed derived classes to modify the behavior of operations which change\n\t * the current stream position by adjusting the target token index of a seek\n\t * operation. The default implementation simply returns {@code i}. If an\n\t * exception is thrown in this method, the current stream index should not be\n\t * changed.\n\t *\n\t * <p>For example, {@link CommonTokenStream} overrides this method to ensure that\n\t * the seek target is always an on-channel token.</p>\n\t *\n\t * @param i The target token index.\n\t * @return The adjusted target token index.\n\t */\n\tprotected int adjustSeekIndex(int i) {\n\t\treturn i;\n\t}\n\n\tprotected final void lazyInit() {\n\t\tif (p == -1) {\n\t\t\tsetup();\n\t\t}\n\t}\n\n    protected void setup() {\n\t\tsync(0);\n\t\tp = adjustSeekIndex(0);\n\t}\n\n    /** Reset this token stream by setting its token source. */\n    public void setTokenSource(TokenSource tokenSource) {\n        this.tokenSource = tokenSource;\n        tokens.clear();\n        p = -1;\n        fetchedEOF = false;\n    }\n\n    public List<Token> getTokens() { return tokens; }\n\n    public List<Token> getTokens(int start, int stop) {\n        return getTokens(start, stop, null);\n    }\n\n    /** Given a start and stop index, return a List of all tokens in\n     *  the token type BitSet.  Return null if no tokens were found.  This\n     *  method looks at both on and off channel tokens.\n     */\n    public List<Token> getTokens(int start, int stop, Set<Integer> types) {\n        lazyInit();\n\t\tif ( start<0 || stop>=tokens.size() ||\n\t\t\t stop<0  || start>=tokens.size() )\n\t\t{\n\t\t\tthrow new IndexOutOfBoundsException(\"start \"+start+\" or stop \"+stop+\n\t\t\t\t\t\t\t\t\t\t\t\t\" not in 0..\"+(tokens.size()-1));\n\t\t}\n        if ( start>stop ) return null;\n\n        // list = tokens[start:stop]:{T t, t.getType() in types}\n        List<Token> filteredTokens = new ArrayList<Token>();\n        for (int i=start; i<=stop; i++) {\n            Token t = tokens.get(i);\n            if ( types==null || types.contains(t.getType()) ) {\n                filteredTokens.add(t);\n            }\n        }\n        if ( filteredTokens.isEmpty() ) {\n            filteredTokens = null;\n        }\n        return filteredTokens;\n    }\n\n    public List<Token> getTokens(int start, int stop, int ttype) {\n\t\tHashSet<Integer> s = new HashSet<Integer>(ttype);\n\t\ts.add(ttype);\n\t\treturn getTokens(start,stop, s);\n    }\n\n\t/**\n\t * Given a starting index, return the index of the next token on channel.\n\t * Return {@code i} if {@code tokens[i]} is on channel. Return the index of\n\t * the EOF token if there are no tokens on channel between {@code i} and\n\t * EOF.\n\t */\n\tprotected int nextTokenOnChannel(int i, int channel) {\n\t\tsync(i);\n\t\tif (i >= size()) {\n\t\t\treturn size() - 1;\n\t\t}\n\n\t\tToken token = tokens.get(i);\n\t\twhile ( token.getChannel()!=channel ) {\n\t\t\tif ( token.getType()==Token.EOF ) {\n\t\t\t\treturn i;\n\t\t\t}\n\n\t\t\ti++;\n\t\t\tsync(i);\n\t\t\ttoken = tokens.get(i);\n\t\t}\n\n\t\treturn i;\n\t}\n\n\t/**\n\t * Given a starting index, return the index of the previous token on\n\t * channel. Return {@code i} if {@code tokens[i]} is on channel. Return -1\n\t * if there are no tokens on channel between {@code i} and 0.\n\t *\n\t * <p>\n\t * If {@code i} specifies an index at or after the EOF token, the EOF token\n\t * index is returned. This is due to the fact that the EOF token is treated\n\t * as though it were on every channel.</p>\n\t */\n\tprotected int previousTokenOnChannel(int i, int channel) {\n\t\tsync(i);\n\t\tif (i >= size()) {\n\t\t\t// the EOF token is on every channel\n\t\t\treturn size() - 1;\n\t\t}\n\n\t\twhile (i >= 0) {\n\t\t\tToken token = tokens.get(i);\n\t\t\tif (token.getType() == Token.EOF || token.getChannel() == channel) {\n\t\t\t\treturn i;\n\t\t\t}\n\n\t\t\ti--;\n\t\t}\n\n\t\treturn i;\n\t}\n\n\t/** Collect all tokens on specified channel to the right of\n\t *  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or\n\t *  EOF. If channel is -1, find any non default channel token.\n\t */\n\tpublic List<Token> getHiddenTokensToRight(int tokenIndex, int channel) {\n\t\tlazyInit();\n\t\tif ( tokenIndex<0 || tokenIndex>=tokens.size() ) {\n\t\t\tthrow new IndexOutOfBoundsException(tokenIndex+\" not in 0..\"+(tokens.size()-1));\n\t\t}\n\n\t\tint nextOnChannel =\n\t\t\tnextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL);\n\t\tint to;\n\t\tint from = tokenIndex+1;\n\t\t// if none onchannel to right, nextOnChannel=-1 so set to = last token\n\t\tif ( nextOnChannel == -1 ) to = size()-1;\n\t\telse to = nextOnChannel;\n\n\t\treturn filterForChannel(from, to, channel);\n\t}\n\n\t/** Collect all hidden tokens (any off-default channel) to the right of\n\t *  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL\n\t *  or EOF.\n\t */\n\tpublic List<Token> getHiddenTokensToRight(int tokenIndex) {\n\t\treturn getHiddenTokensToRight(tokenIndex, -1);\n\t}\n\n\t/** Collect all tokens on specified channel to the left of\n\t *  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n\t *  If channel is -1, find any non default channel token.\n\t */\n\tpublic List<Token> getHiddenTokensToLeft(int tokenIndex, int channel) {\n\t\tlazyInit();\n\t\tif ( tokenIndex<0 || tokenIndex>=tokens.size() ) {\n\t\t\tthrow new IndexOutOfBoundsException(tokenIndex+\" not in 0..\"+(tokens.size()-1));\n\t\t}\n\n\t\tif (tokenIndex == 0) {\n\t\t\t// obviously no tokens can appear before the first token\n\t\t\treturn null;\n\t\t}\n\n\t\tint prevOnChannel =\n\t\t\tpreviousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL);\n\t\tif ( prevOnChannel == tokenIndex - 1 ) return null;\n\t\t// if none onchannel to left, prevOnChannel=-1 then from=0\n\t\tint from = prevOnChannel+1;\n\t\tint to = tokenIndex-1;\n\n\t\treturn filterForChannel(from, to, channel);\n\t}\n\n\t/** Collect all hidden tokens (any off-default channel) to the left of\n\t *  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n\t */\n\tpublic List<Token> getHiddenTokensToLeft(int tokenIndex) {\n\t\treturn getHiddenTokensToLeft(tokenIndex, -1);\n\t}\n\n\tprotected List<Token> filterForChannel(int from, int to, int channel) {\n\t\tList<Token> hidden = new ArrayList<Token>();\n\t\tfor (int i=from; i<=to; i++) {\n\t\t\tToken t = tokens.get(i);\n\t\t\tif ( channel==-1 ) {\n\t\t\t\tif ( t.getChannel()!= Lexer.DEFAULT_TOKEN_CHANNEL ) hidden.add(t);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ( t.getChannel()==channel ) hidden.add(t);\n\t\t\t}\n\t\t}\n\t\tif ( hidden.size()==0 ) return null;\n\t\treturn hidden;\n\t}\n\n\t@Override\n    public String getSourceName() {\treturn tokenSource.getSourceName();\t}\n\n\t/** Get the text of all tokens in this buffer. */\n\n\t@Override\n\tpublic String getText() {\n\t\treturn getText(Interval.of(0,size()-1));\n\t}\n\n\t@Override\n\tpublic String getText(Interval interval) {\n\t\tint start = interval.a;\n\t\tint stop = interval.b;\n\t\tif ( start<0 || stop<0 ) return \"\";\n\t\tsync(stop);\n        if ( stop>=tokens.size() ) stop = tokens.size()-1;\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (int i = start; i <= stop; i++) {\n\t\t\tToken t = tokens.get(i);\n\t\t\tif ( t.getType()==Token.EOF ) break;\n\t\t\tbuf.append(t.getText());\n\t\t}\n\t\treturn buf.toString();\n    }\n\n\n\t@Override\n\tpublic String getText(RuleContext ctx) {\n\t\treturn getText(ctx.getSourceInterval());\n\t}\n\n\n    @Override\n    public String getText(Token start, Token stop) {\n        if ( start!=null && stop!=null ) {\n            return getText(Interval.of(start.getTokenIndex(), stop.getTokenIndex()));\n        }\n\n\t\treturn \"\";\n    }\n\n    /** Get all tokens from lexer until EOF */\n    public void fill() {\n        lazyInit();\n\t\tfinal int blockSize = 1000;\n\t\twhile (true) {\n\t\t\tint fetched = fetch(blockSize);\n\t\t\tif (fetched < blockSize) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/CharStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\n/** A source of characters for an ANTLR lexer. */\npublic interface CharStream extends IntStream {\n\t/**\n\t * This method returns the text for a range of characters within this input\n\t * stream. This method is guaranteed to not throw an exception if the\n\t * specified {@code interval} lies entirely within a marked range. For more\n\t * information about marked ranges, see {@link IntStream#mark}.\n\t *\n\t * @param interval an interval within the stream\n\t * @return the text of the specified interval\n\t *\n\t * @throws NullPointerException if {@code interval} is {@code null}\n\t * @throws IllegalArgumentException if {@code interval.a < 0}, or if\n\t * {@code interval.b < interval.a - 1}, or if {@code interval.b} lies at or\n\t * past the end of the stream\n\t * @throws UnsupportedOperationException if the stream does not support\n\t * getting the text of the specified interval\n\t */\n\tpublic String getText(Interval interval);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/CharStreams.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.Reader;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.channels.Channels;\nimport java.nio.channels.ReadableByteChannel;\nimport java.nio.charset.Charset;\nimport java.nio.charset.CharsetDecoder;\nimport java.nio.charset.CoderResult;\nimport java.nio.charset.CodingErrorAction;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\n/** This class represents the primary interface for creating {@link CharStream}s\n *  from a variety of sources as of 4.7.  The motivation was to support\n *  Unicode code points > U+FFFF.  {@link ANTLRInputStream} and\n *  {@link ANTLRFileStream} are now deprecated in favor of the streams created\n *  by this interface.\n *\n *  DEPRECATED: {@code new ANTLRFileStream(\"myinputfile\")}\n *  NEW:        {@code CharStreams.fromFileName(\"myinputfile\")}\n *\n *  WARNING: If you use both the deprecated and the new streams, you will see\n *  a nontrivial performance degradation. This speed hit is because the\n *  {@link Lexer}'s internal code goes from a monomorphic to megamorphic\n *  dynamic dispatch to get characters from the input stream. Java's\n *  on-the-fly compiler (JIT) is unable to perform the same optimizations\n *  so stick with either the old or the new streams, if performance is\n *  a primary concern. See the extreme debugging and spelunking\n *  needed to identify this issue in our timing rig:\n *\n *      https://github.com/antlr/antlr4/pull/1781\n *\n *  The ANTLR character streams still buffer all the input when you create\n *  the stream, as they have done for ~20 years. If you need unbuffered\n *  access, please note that it becomes challenging to create\n *  parse trees. The parse tree has to point to tokens which will either\n *  point into a stale location in an unbuffered stream or you have to copy\n *  the characters out of the buffer into the token. That defeats the purpose\n *  of unbuffered input. Per the ANTLR book, unbuffered streams are primarily\n *  useful for processing infinite streams *during the parse.*\n *\n *  The new streams also use 8-bit buffers when possible so this new\n *  interface supports character streams that use half as much memory\n *  as the old {@link ANTLRFileStream}, which assumed 16-bit characters.\n *\n *  A big shout out to Ben Hamilton (github bhamiltoncx) for his superhuman\n *  efforts across all targets to get true Unicode 3.1 support for U+10FFFF.\n *\n *  @since 4.7\n */\npublic final class CharStreams {\n\tprivate static final int DEFAULT_BUFFER_SIZE = 4096;\n\n\t// Utility class; do not construct.\n\tprivate CharStreams() { }\n\n\t/**\n\t * Creates a {@link CharStream} given a path to a UTF-8\n\t * encoded file on disk.\n\t *\n\t * Reads the entire contents of the file into the result before returning.\n\t */\n\tpublic static CharStream fromPath(Path path) throws IOException {\n\t\treturn fromPath(path, StandardCharsets.UTF_8);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given a path to a file on disk and the\n\t * charset of the bytes contained in the file.\n\t *\n\t * Reads the entire contents of the file into the result before returning.\n\t */\n\tpublic static CharStream fromPath(Path path, Charset charset) throws IOException {\n\t\tlong size = Files.size(path);\n\t\ttry (ReadableByteChannel channel = Files.newByteChannel(path)) {\n\t\t\treturn fromChannel(\n\t\t\t\tchannel,\n\t\t\t\tcharset,\n\t\t\t\tDEFAULT_BUFFER_SIZE,\n\t\t\t\tCodingErrorAction.REPLACE,\n\t\t\t\tpath.toString(),\n\t\t\t\tsize);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given a string containing a\n\t * path to a UTF-8 file on disk.\n\t *\n\t * Reads the entire contents of the file into the result before returning.\n\t */\n\tpublic static CharStream fromFileName(String fileName) throws IOException {\n\t\treturn fromPath(Paths.get(fileName), StandardCharsets.UTF_8);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given a string containing a\n\t * path to a file on disk and the charset of the bytes\n\t * contained in the file.\n\t *\n\t * Reads the entire contents of the file into the result before returning.\n\t */\n\tpublic static CharStream fromFileName(String fileName, Charset charset) throws IOException {\n\t\treturn fromPath(Paths.get(fileName), charset);\n\t}\n\n\n\t/**\n\t * Creates a {@link CharStream} given an opened {@link InputStream}\n\t * containing UTF-8 bytes.\n\t *\n\t * Reads the entire contents of the {@code InputStream} into\n\t * the result before returning, then closes the {@code InputStream}.\n\t */\n\tpublic static CharStream fromStream(InputStream is) throws IOException {\n\t\treturn fromStream(is, StandardCharsets.UTF_8);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given an opened {@link InputStream} and the\n\t * charset of the bytes contained in the stream.\n\t *\n\t * Reads the entire contents of the {@code InputStream} into\n\t * the result before returning, then closes the {@code InputStream}.\n\t */\n\tpublic static CharStream fromStream(InputStream is, Charset charset) throws IOException {\n\t\treturn fromStream(is, charset, -1);\n\t}\n\n\tpublic static CharStream fromStream(InputStream is, Charset charset, long inputSize) throws IOException {\n\t\ttry (ReadableByteChannel channel = Channels.newChannel(is)) {\n\t\t\treturn fromChannel(\n\t\t\t\tchannel,\n\t\t\t\tcharset,\n\t\t\t\tDEFAULT_BUFFER_SIZE,\n\t\t\t\tCodingErrorAction.REPLACE,\n\t\t\t\tIntStream.UNKNOWN_SOURCE_NAME,\n\t\t\t\tinputSize);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given an opened {@link ReadableByteChannel}\n\t * containing UTF-8 bytes.\n\t *\n\t * Reads the entire contents of the {@code channel} into\n\t * the result before returning, then closes the {@code channel}.\n\t */\n\tpublic static CharStream fromChannel(ReadableByteChannel channel) throws IOException {\n\t\treturn fromChannel(channel, StandardCharsets.UTF_8);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given an opened {@link ReadableByteChannel} and the\n\t * charset of the bytes contained in the channel.\n\t *\n\t * Reads the entire contents of the {@code channel} into\n\t * the result before returning, then closes the {@code channel}.\n\t */\n\tpublic static CharStream fromChannel(ReadableByteChannel channel, Charset charset) throws IOException {\n\t\treturn fromChannel(\n\t\t\tchannel,\n\t\t\tDEFAULT_BUFFER_SIZE,\n\t\t\tCodingErrorAction.REPLACE,\n\t\t\tIntStream.UNKNOWN_SOURCE_NAME);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given a {@link Reader}. Closes\n\t * the reader before returning.\n\t */\n\tpublic static CodePointCharStream fromReader(Reader r) throws IOException {\n\t\treturn fromReader(r, IntStream.UNKNOWN_SOURCE_NAME);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given a {@link Reader} and its\n\t * source name. Closes the reader before returning.\n\t */\n\tpublic static CodePointCharStream fromReader(Reader r, String sourceName) throws IOException {\n\t\ttry {\n\t\t\tCodePointBuffer.Builder codePointBufferBuilder = CodePointBuffer.builder(DEFAULT_BUFFER_SIZE);\n\t\t\tCharBuffer charBuffer = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);\n\t\t\twhile ((r.read(charBuffer)) != -1) {\n\t\t\t\tcharBuffer.flip();\n\t\t\t\tcodePointBufferBuilder.append(charBuffer);\n\t\t\t\tcharBuffer.compact();\n\t\t\t}\n\t\t\treturn CodePointCharStream.fromBuffer(codePointBufferBuilder.build(), sourceName);\n\t\t}\n\t\tfinally {\n\t\t\tr.close();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given a {@link String}.\n\t */\n\tpublic static CodePointCharStream fromString(String s) {\n\t\treturn fromString(s, IntStream.UNKNOWN_SOURCE_NAME);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given a {@link String} and the {@code sourceName}\n\t * from which it came.\n\t */\n\tpublic static CodePointCharStream fromString(String s, String sourceName) {\n\t\t// Initial guess assumes no code points > U+FFFF: one code\n\t\t// point for each code unit in the string\n\t\tCodePointBuffer.Builder codePointBufferBuilder = CodePointBuffer.builder(s.length());\n\t\t// TODO: CharBuffer.wrap(String) rightfully returns a read-only buffer\n\t\t// which doesn't expose its array, so we make a copy.\n\t\tCharBuffer cb = CharBuffer.allocate(s.length());\n\t\tcb.put(s);\n\t\tcb.flip();\n\t\tcodePointBufferBuilder.append(cb);\n\t\treturn CodePointCharStream.fromBuffer(codePointBufferBuilder.build(), sourceName);\n\t}\n\n\t/**\n\t * Creates a {@link CharStream} given an opened {@link ReadableByteChannel}\n\t * containing UTF-8 bytes.\n\t *\n\t * Reads the entire contents of the {@code channel} into\n\t * the result before returning, then closes the {@code channel}.\n\t */\n\tpublic static CodePointCharStream fromChannel(\n\t\tReadableByteChannel channel,\n\t\tint bufferSize,\n\t\tCodingErrorAction decodingErrorAction,\n\t\tString sourceName)\n\t\tthrows IOException\n\t{\n\t\treturn fromChannel(channel, StandardCharsets.UTF_8, bufferSize, decodingErrorAction, sourceName, -1);\n\t}\n\n\tpublic static CodePointCharStream fromChannel(\n\t\tReadableByteChannel channel,\n\t\tCharset charset,\n\t\tint bufferSize,\n\t\tCodingErrorAction decodingErrorAction,\n\t\tString sourceName,\n\t\tlong inputSize)\n\t\tthrows IOException\n\t{\n\t\ttry {\n\t\t\tByteBuffer utf8BytesIn = ByteBuffer.allocate(bufferSize);\n\t\t\tCharBuffer utf16CodeUnitsOut = CharBuffer.allocate(bufferSize);\n\t\t\tif (inputSize == -1) {\n\t\t\t\tinputSize = bufferSize;\n\t\t\t} else if (inputSize > Integer.MAX_VALUE) {\n\t\t\t\t// ByteBuffer et al don't support long sizes\n\t\t\t\tthrow new IOException(String.format(\"inputSize %d larger than max %d\", inputSize, Integer.MAX_VALUE));\n\t\t\t}\n\t\t\tCodePointBuffer.Builder codePointBufferBuilder = CodePointBuffer.builder((int) inputSize);\n\t\t\tCharsetDecoder decoder = charset\n\t\t\t\t\t.newDecoder()\n\t\t\t\t\t.onMalformedInput(decodingErrorAction)\n\t\t\t\t\t.onUnmappableCharacter(decodingErrorAction);\n\n\t\t\tboolean endOfInput = false;\n\t\t\twhile (!endOfInput) {\n\t\t\t\tint bytesRead = channel.read(utf8BytesIn);\n\t\t\t\tendOfInput = (bytesRead == -1);\n\t\t\t\tutf8BytesIn.flip();\n\t\t\t\tCoderResult result = decoder.decode(\n\t\t\t\t\tutf8BytesIn,\n\t\t\t\t\tutf16CodeUnitsOut,\n\t\t\t\t\tendOfInput);\n\t\t\t\tif (result.isError() && decodingErrorAction.equals(CodingErrorAction.REPORT)) {\n\t\t\t\t\tresult.throwException();\n\t\t\t\t}\n\t\t\t\tutf16CodeUnitsOut.flip();\n\t\t\t\tcodePointBufferBuilder.append(utf16CodeUnitsOut);\n\t\t\t\tutf8BytesIn.compact();\n\t\t\t\tutf16CodeUnitsOut.compact();\n\t\t\t}\n\t\t\t// Handle any bytes at the end of the file which need to\n\t\t\t// be represented as errors or substitution characters.\n\t\t\tCoderResult flushResult = decoder.flush(utf16CodeUnitsOut);\n\t\t\tif (flushResult.isError() && decodingErrorAction.equals(CodingErrorAction.REPORT)) {\n\t\t\t\tflushResult.throwException();\n\t\t\t}\n\t\t\tutf16CodeUnitsOut.flip();\n\t\t\tcodePointBufferBuilder.append(utf16CodeUnitsOut);\n\n\t\t\tCodePointBuffer codePointBuffer = codePointBufferBuilder.build();\n\t\t\treturn CodePointCharStream.fromBuffer(codePointBuffer, sourceName);\n\t\t}\n\t\tfinally {\n\t\t\tchannel.close();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/CodePointBuffer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.IntBuffer;\n\n/**\n * Wrapper for {@link ByteBuffer} / {@link CharBuffer} / {@link IntBuffer}.\n *\n * Because Java lacks generics on primitive types, these three types\n * do not share an interface, so we have to write one manually.\n */\npublic class CodePointBuffer {\n\tpublic enum Type {\n\t\t\tBYTE,\n\t\t\tCHAR,\n\t\t\tINT\n\t}\n\tprivate final Type type;\n\tprivate final ByteBuffer byteBuffer;\n\tprivate final CharBuffer charBuffer;\n\tprivate final IntBuffer intBuffer;\n\n\tprivate CodePointBuffer(Type type, ByteBuffer byteBuffer, CharBuffer charBuffer, IntBuffer intBuffer) {\n\t\tthis.type = type;\n\t\tthis.byteBuffer = byteBuffer;\n\t\tthis.charBuffer = charBuffer;\n\t\tthis.intBuffer = intBuffer;\n\t}\n\n\tpublic static CodePointBuffer withBytes(ByteBuffer byteBuffer) {\n\t\treturn new CodePointBuffer(Type.BYTE, byteBuffer, null, null);\n\t}\n\n\tpublic static CodePointBuffer withChars(CharBuffer charBuffer) {\n\t\treturn new CodePointBuffer(Type.CHAR, null, charBuffer, null);\n\t}\n\n\tpublic static CodePointBuffer withInts(IntBuffer intBuffer) {\n\t\treturn new CodePointBuffer(Type.INT, null, null, intBuffer);\n\t}\n\n\tpublic int position() {\n\t\tswitch (type) {\n\t\t\tcase BYTE:\n\t\t\t\treturn byteBuffer.position();\n\t\t\tcase CHAR:\n\t\t\t\treturn charBuffer.position();\n\t\t\tcase INT:\n\t\t\t\treturn intBuffer.position();\n\t\t}\n\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t}\n\n\tpublic void position(int newPosition) {\n\t\tswitch (type) {\n\t\t\tcase BYTE:\n\t\t\t\tbyteBuffer.position(newPosition);\n\t\t\t\tbreak;\n\t\t\tcase CHAR:\n\t\t\t\tcharBuffer.position(newPosition);\n\t\t\t\tbreak;\n\t\t\tcase INT:\n\t\t\t\tintBuffer.position(newPosition);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpublic int remaining() {\n\t\tswitch (type) {\n\t\t\tcase BYTE:\n\t\t\t\treturn byteBuffer.remaining();\n\t\t\tcase CHAR:\n\t\t\t\treturn charBuffer.remaining();\n\t\t\tcase INT:\n\t\t\t\treturn intBuffer.remaining();\n\t\t}\n\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t}\n\n\tpublic int get(int offset) {\n\t\tswitch (type) {\n\t\t\tcase BYTE:\n\t\t\t\treturn byteBuffer.get(offset);\n\t\t\tcase CHAR:\n\t\t\t\treturn charBuffer.get(offset);\n\t\t\tcase INT:\n\t\t\t\treturn intBuffer.get(offset);\n\t\t}\n\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t}\n\n\tType getType() {\n\t\treturn type;\n\t}\n\n\tint arrayOffset() {\n\t\tswitch (type) {\n\t\t\tcase BYTE:\n\t\t\t\treturn byteBuffer.arrayOffset();\n\t\t\tcase CHAR:\n\t\t\t\treturn charBuffer.arrayOffset();\n\t\t\tcase INT:\n\t\t\t\treturn intBuffer.arrayOffset();\n\t\t}\n\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t}\n\n\tbyte[] byteArray() {\n\t\tassert type == Type.BYTE;\n\t\treturn byteBuffer.array();\n\t}\n\n\tchar[] charArray() {\n\t\tassert type == Type.CHAR;\n\t\treturn charBuffer.array();\n\t}\n\n\tint[] intArray() {\n\t\tassert type == Type.INT;\n\t\treturn intBuffer.array();\n\t}\n\n\tpublic static Builder builder(int initialBufferSize) {\n\t\treturn new Builder(initialBufferSize);\n\t}\n\n\tpublic static class Builder {\n\t\tprivate Type type;\n\t\tprivate ByteBuffer byteBuffer;\n\t\tprivate CharBuffer charBuffer;\n\t\tprivate IntBuffer intBuffer;\n\t\tprivate int prevHighSurrogate;\n\n\t\tprivate Builder(int initialBufferSize) {\n\t\t\ttype = Type.BYTE;\n\t\t\tbyteBuffer = ByteBuffer.allocate(initialBufferSize);\n\t\t\tcharBuffer = null;\n\t\t\tintBuffer = null;\n\t\t\tprevHighSurrogate = -1;\n\t\t}\n\n\t\tType getType() {\n\t\t\treturn type;\n\t\t}\n\n\t\tByteBuffer getByteBuffer() {\n\t\t\treturn byteBuffer;\n\t\t}\n\n\t\tCharBuffer getCharBuffer() {\n\t\t\treturn charBuffer;\n\t\t}\n\n\t\tIntBuffer getIntBuffer() {\n\t\t\treturn intBuffer;\n\t\t}\n\n\t\tpublic CodePointBuffer build() {\n\t\t\tswitch (type) {\n\t\t\t\tcase BYTE:\n\t\t\t\t\tbyteBuffer.flip();\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHAR:\n\t\t\t\t\tcharBuffer.flip();\n\t\t\t\t\tbreak;\n\t\t\t\tcase INT:\n\t\t\t\t\tintBuffer.flip();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn new CodePointBuffer(type, byteBuffer, charBuffer, intBuffer);\n\t\t}\n\n\t\tprivate static int roundUpToNextPowerOfTwo(int i) {\n\t\t\tint nextPowerOfTwo = 32 - Integer.numberOfLeadingZeros(i - 1);\n\t\t\treturn (int) Math.pow(2, nextPowerOfTwo);\n\t\t}\n\n\t\tpublic void ensureRemaining(int remainingNeeded) {\n\t\t\tswitch (type) {\n\t\t\t\tcase BYTE:\n\t\t\t\t\tif (byteBuffer.remaining() < remainingNeeded) {\n\t\t\t\t\t\tint newCapacity = roundUpToNextPowerOfTwo(byteBuffer.capacity() + remainingNeeded);\n\t\t\t\t\t\tByteBuffer newBuffer = ByteBuffer.allocate(newCapacity);\n\t\t\t\t\t\tbyteBuffer.flip();\n\t\t\t\t\t\tnewBuffer.put(byteBuffer);\n\t\t\t\t\t\tbyteBuffer = newBuffer;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHAR:\n\t\t\t\t\tif (charBuffer.remaining() < remainingNeeded) {\n\t\t\t\t\t\tint newCapacity = roundUpToNextPowerOfTwo(charBuffer.capacity() + remainingNeeded);\n\t\t\t\t\t\tCharBuffer newBuffer = CharBuffer.allocate(newCapacity);\n\t\t\t\t\t\tcharBuffer.flip();\n\t\t\t\t\t\tnewBuffer.put(charBuffer);\n\t\t\t\t\t\tcharBuffer = newBuffer;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase INT:\n\t\t\t\t\tif (intBuffer.remaining() < remainingNeeded) {\n\t\t\t\t\t\tint newCapacity = roundUpToNextPowerOfTwo(intBuffer.capacity() + remainingNeeded);\n\t\t\t\t\t\tIntBuffer newBuffer = IntBuffer.allocate(newCapacity);\n\t\t\t\t\t\tintBuffer.flip();\n\t\t\t\t\t\tnewBuffer.put(intBuffer);\n\t\t\t\t\t\tintBuffer = newBuffer;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tpublic void append(CharBuffer utf16In) {\n\t\t\tensureRemaining(utf16In.remaining());\n\t\t\tif (utf16In.hasArray()) {\n\t\t\t\tappendArray(utf16In);\n\t\t\t} else {\n\t\t\t\t// TODO\n\t\t\t\tthrow new UnsupportedOperationException(\"TODO\");\n\t\t\t}\n\t\t}\n\n\t\tprivate void appendArray(CharBuffer utf16In) {\n\t\t\tassert utf16In.hasArray();\n\n\t\t\tswitch (type) {\n\t\t\t\tcase BYTE:\n\t\t\t\t\tappendArrayByte(utf16In);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHAR:\n\t\t\t\t\tappendArrayChar(utf16In);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INT:\n\t\t\t\t\tappendArrayInt(utf16In);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tprivate void appendArrayByte(CharBuffer utf16In) {\n\t\t\tassert prevHighSurrogate == -1;\n\n\t\t\tchar[] in = utf16In.array();\n\t\t\tint inOffset = utf16In.arrayOffset() + utf16In.position();\n\t\t\tint inLimit = utf16In.arrayOffset() + utf16In.limit();\n\n\t\t\tbyte[] outByte = byteBuffer.array();\n\t\t\tint outOffset = byteBuffer.arrayOffset() + byteBuffer.position();\n\n\t\t\twhile (inOffset < inLimit) {\n\t\t\t\tchar c = in[inOffset];\n\t\t\t\tif (c <= 0xFF) {\n\t\t\t\t\toutByte[outOffset] = (byte)(c & 0xFF);\n\t\t\t\t} else {\n\t\t\t\t\tutf16In.position(inOffset - utf16In.arrayOffset());\n\t\t\t\t\tbyteBuffer.position(outOffset - byteBuffer.arrayOffset());\n\t\t\t\t\tif (!Character.isHighSurrogate(c)) {\n\t\t\t\t\t\tbyteToCharBuffer(utf16In.remaining());\n\t\t\t\t\t\tappendArrayChar(utf16In);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbyteToIntBuffer(utf16In.remaining());\n\t\t\t\t\t\tappendArrayInt(utf16In);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinOffset++;\n\t\t\t\toutOffset++;\n\t\t\t}\n\n\t\t\tutf16In.position(inOffset - utf16In.arrayOffset());\n\t\t\tbyteBuffer.position(outOffset - byteBuffer.arrayOffset());\n\t\t}\n\n\t\tprivate void appendArrayChar(CharBuffer utf16In) {\n\t\t\tassert prevHighSurrogate == -1;\n\n\t\t\tchar[] in = utf16In.array();\n\t\t\tint inOffset = utf16In.arrayOffset() + utf16In.position();\n\t\t\tint inLimit = utf16In.arrayOffset() + utf16In.limit();\n\n\t\t\tchar[] outChar = charBuffer.array();\n\t\t\tint outOffset = charBuffer.arrayOffset() + charBuffer.position();\n\n\t\t\twhile (inOffset < inLimit) {\n\t\t\t\tchar c = in[inOffset];\n\t\t\t\tif (!Character.isHighSurrogate(c)) {\n\t\t\t\t\toutChar[outOffset] = c;\n\t\t\t\t} else {\n\t\t\t\t\tutf16In.position(inOffset - utf16In.arrayOffset());\n\t\t\t\t\tcharBuffer.position(outOffset - charBuffer.arrayOffset());\n\t\t\t\t\tcharToIntBuffer(utf16In.remaining());\n\t\t\t\t\tappendArrayInt(utf16In);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tinOffset++;\n\t\t\t\toutOffset++;\n\t\t\t}\n\n\t\t\tutf16In.position(inOffset - utf16In.arrayOffset());\n\t\t\tcharBuffer.position(outOffset - charBuffer.arrayOffset());\n\t\t}\n\n\t\tprivate void appendArrayInt(CharBuffer utf16In) {\n\t\t\tchar[] in = utf16In.array();\n\t\t\tint inOffset = utf16In.arrayOffset() + utf16In.position();\n\t\t\tint inLimit = utf16In.arrayOffset() + utf16In.limit();\n\n\t\t\tint[] outInt = intBuffer.array();\n\t\t\tint outOffset = intBuffer.arrayOffset() + intBuffer.position();\n\n\t\t\twhile (inOffset < inLimit) {\n\t\t\t\tchar c = in[inOffset];\n\t\t\t\tinOffset++;\n\t\t\t\tif (prevHighSurrogate != -1) {\n\t\t\t\t\tif (Character.isLowSurrogate(c)) {\n\t\t\t\t\t\toutInt[outOffset] = Character.toCodePoint((char) prevHighSurrogate, c);\n\t\t\t\t\t\toutOffset++;\n\t\t\t\t\t\tprevHighSurrogate = -1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Dangling high surrogate\n\t\t\t\t\t\toutInt[outOffset] = prevHighSurrogate;\n\t\t\t\t\t\toutOffset++;\n\t\t\t\t\t\tif (Character.isHighSurrogate(c)) {\n\t\t\t\t\t\t\tprevHighSurrogate = c & 0xFFFF;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\toutInt[outOffset] = c & 0xFFFF;\n\t\t\t\t\t\t\toutOffset++;\n\t\t\t\t\t\t\tprevHighSurrogate = -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (Character.isHighSurrogate(c)) {\n\t\t\t\t\tprevHighSurrogate = c & 0xFFFF;\n\t\t\t\t} else {\n\t\t\t\t\toutInt[outOffset] = c & 0xFFFF;\n\t\t\t\t\toutOffset++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (prevHighSurrogate != -1) {\n\t\t\t\t// Dangling high surrogate\n\t\t\t\toutInt[outOffset] = prevHighSurrogate & 0xFFFF;\n\t\t\t\toutOffset++;\n\t\t\t}\n\n\t\t\tutf16In.position(inOffset - utf16In.arrayOffset());\n\t\t\tintBuffer.position(outOffset - intBuffer.arrayOffset());\n\t\t}\n\n\t\tprivate void byteToCharBuffer(int toAppend) {\n\t\t\tbyteBuffer.flip();\n\t\t\t// CharBuffers hold twice as much per unit as ByteBuffers, so start with half the capacity.\n\t\t\tCharBuffer newBuffer = CharBuffer.allocate(Math.max(byteBuffer.remaining() + toAppend, byteBuffer.capacity() / 2));\n\t\t\twhile (byteBuffer.hasRemaining()) {\n\t\t\t\tnewBuffer.put((char) (byteBuffer.get() & 0xFF));\n\t\t\t}\n\t\t\ttype = Type.CHAR;\n\t\t\tbyteBuffer = null;\n\t\t\tcharBuffer = newBuffer;\n\t\t}\n\n\t\tprivate void byteToIntBuffer(int toAppend) {\n\t\t\tbyteBuffer.flip();\n\t\t\t// IntBuffers hold four times as much per unit as ByteBuffers, so start with one quarter the capacity.\n\t\t\tIntBuffer newBuffer = IntBuffer.allocate(Math.max(byteBuffer.remaining() + toAppend, byteBuffer.capacity() / 4));\n\t\t\twhile (byteBuffer.hasRemaining()) {\n\t\t\t\tnewBuffer.put(byteBuffer.get() & 0xFF);\n\t\t\t}\n\t\t\ttype = Type.INT;\n\t\t\tbyteBuffer = null;\n\t\t\tintBuffer = newBuffer;\n\t\t}\n\n\t\tprivate void charToIntBuffer(int toAppend) {\n\t\t\tcharBuffer.flip();\n\t\t\t// IntBuffers hold two times as much per unit as ByteBuffers, so start with one half the capacity.\n\t\t\tIntBuffer newBuffer = IntBuffer.allocate(Math.max(charBuffer.remaining() + toAppend, charBuffer.capacity() / 2));\n\t\t\twhile (charBuffer.hasRemaining()) {\n\t\t\t\tnewBuffer.put(charBuffer.get() & 0xFFFF);\n\t\t\t}\n\t\t\ttype = Type.INT;\n\t\t\tcharBuffer = null;\n\t\t\tintBuffer = newBuffer;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/CodePointCharStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.nio.charset.StandardCharsets;\n\n/**\n * Alternative to {@link ANTLRInputStream} which treats the input\n * as a series of Unicode code points, instead of a series of UTF-16\n * code units.\n *\n * Use this if you need to parse input which potentially contains\n * Unicode values > U+FFFF.\n */\npublic abstract class CodePointCharStream implements CharStream {\n\tprotected final int size;\n\tprotected final String name;\n\n\t// To avoid lots of virtual method calls, we directly access\n\t// the state of the underlying code points in the\n\t// CodePointBuffer.\n\tprotected int position;\n\n\t// Use the factory method {@link #fromBuffer(CodePointBuffer)} to\n\t// construct instances of this type.\n\tprivate CodePointCharStream(int position, int remaining, String name) {\n\t\t// TODO\n\t\tassert position == 0;\n\t\tthis.size = remaining;\n\t\tthis.name = name;\n\t\tthis.position = 0;\n\t}\n\n\t// Visible for testing.\n\tabstract Object getInternalStorage();\n\n\t/**\n\t * Constructs a {@link CodePointCharStream} which provides access\n\t * to the Unicode code points stored in {@code codePointBuffer}.\n\t */\n\tpublic static CodePointCharStream fromBuffer(CodePointBuffer codePointBuffer) {\n\t\treturn fromBuffer(codePointBuffer, UNKNOWN_SOURCE_NAME);\n\t}\n\n\t/**\n\t * Constructs a named {@link CodePointCharStream} which provides access\n\t * to the Unicode code points stored in {@code codePointBuffer}.\n\t */\n\tpublic static CodePointCharStream fromBuffer(CodePointBuffer codePointBuffer, String name) {\n\t\t// Java lacks generics on primitive types.\n\t\t//\n\t\t// To avoid lots of calls to virtual methods in the\n\t\t// very hot codepath of LA() below, we construct one\n\t\t// of three concrete subclasses.\n\t\t//\n\t\t// The concrete subclasses directly access the code\n\t\t// points stored in the underlying array (byte[],\n\t\t// char[], or int[]), so we can avoid lots of virtual\n\t\t// method calls to ByteBuffer.get(offset).\n\t\tswitch (codePointBuffer.getType()) {\n\t\t\tcase BYTE:\n\t\t\t\treturn new CodePoint8BitCharStream(\n\t\t\t\t\t\tcodePointBuffer.position(),\n\t\t\t\t\t\tcodePointBuffer.remaining(),\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tcodePointBuffer.byteArray(),\n\t\t\t\t\t\tcodePointBuffer.arrayOffset());\n\t\t\tcase CHAR:\n\t\t\t\treturn new CodePoint16BitCharStream(\n\t\t\t\t\t\tcodePointBuffer.position(),\n\t\t\t\t\t\tcodePointBuffer.remaining(),\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tcodePointBuffer.charArray(),\n\t\t\t\t\t\tcodePointBuffer.arrayOffset());\n\t\t\tcase INT:\n\t\t\t\treturn new CodePoint32BitCharStream(\n\t\t\t\t\t\tcodePointBuffer.position(),\n\t\t\t\t\t\tcodePointBuffer.remaining(),\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tcodePointBuffer.intArray(),\n\t\t\t\t\t\tcodePointBuffer.arrayOffset());\n\t\t}\n\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t}\n\n\t@Override\n\tpublic final void consume() {\n\t\tif (size - position == 0) {\n\t\t\tassert LA(1) == IntStream.EOF;\n\t\t\tthrow new IllegalStateException(\"cannot consume EOF\");\n\t\t}\n\t\tposition = position + 1;\n\t}\n\n\t@Override\n\tpublic final int index() {\n\t\treturn position;\n\t}\n\n\t@Override\n\tpublic final int size() {\n\t\treturn size;\n\t}\n\n\t/** mark/release do nothing; we have entire buffer */\n\t@Override\n\tpublic final int mark() {\n\t\treturn -1;\n\t}\n\n\t@Override\n\tpublic final void release(int marker) {\n\t}\n\n\t@Override\n\tpublic final void seek(int index) {\n\t\tposition = index;\n\t}\n\n\t@Override\n\tpublic final String getSourceName() {\n\t\tif (name == null || name.isEmpty()) {\n\t\t\treturn UNKNOWN_SOURCE_NAME;\n\t\t}\n\n\t\treturn name;\n\t}\n\n\t@Override\n\tpublic final String toString() {\n\t\treturn getText(Interval.of(0, size - 1));\n\t}\n\n\t// 8-bit storage for code points <= U+00FF.\n\tprivate static final class CodePoint8BitCharStream extends CodePointCharStream {\n\t\tprivate final byte[] byteArray;\n\n\t\tprivate CodePoint8BitCharStream(int position, int remaining, String name, byte[] byteArray, int arrayOffset) {\n\t\t\tsuper(position, remaining, name);\n\t\t\t// TODO\n\t\t\tassert arrayOffset == 0;\n\t\t\tthis.byteArray = byteArray;\n\t\t}\n\n\t\t/** Return the UTF-16 encoded string for the given interval */\n\t\t@Override\n\t\tpublic String getText(Interval interval) {\n\t\t\tint startIdx = Math.min(interval.a, size);\n\t\t\tint len = Math.min(interval.b - interval.a + 1, size - startIdx);\n\n\t\t\t// We know the maximum code point in byteArray is U+00FF,\n\t\t\t// so we can treat this as if it were ISO-8859-1, aka Latin-1,\n\t\t\t// which shares the same code points up to 0xFF.\n\t\t\treturn new String(byteArray, startIdx, len, StandardCharsets.ISO_8859_1);\n\t\t}\n\n\t\t@Override\n\t\tpublic int LA(int i) {\n\t\t\tint offset;\n\t\t\tswitch (Integer.signum(i)) {\n\t\t\t\tcase -1:\n\t\t\t\t\toffset = position + i;\n\t\t\t\t\tif (offset < 0) {\n\t\t\t\t\t\treturn IntStream.EOF;\n\t\t\t\t\t}\n\t\t\t\t\treturn byteArray[offset] & 0xFF;\n\t\t\t\tcase 0:\n\t\t\t\t\t// Undefined\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 1:\n\t\t\t\t\toffset = position + i - 1;\n\t\t\t\t\tif (offset >= size) {\n\t\t\t\t\t\treturn IntStream.EOF;\n\t\t\t\t\t}\n\t\t\t\t\treturn byteArray[offset] & 0xFF;\n\t\t\t}\n\t\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t\t}\n\n\t\t@Override\n\t\tObject getInternalStorage() {\n\t\t\treturn byteArray;\n\t\t}\n\t}\n\n\t// 16-bit internal storage for code points between U+0100 and U+FFFF.\n\tprivate static final class CodePoint16BitCharStream extends CodePointCharStream {\n\t\tprivate final char[] charArray;\n\n\t\tprivate CodePoint16BitCharStream(int position, int remaining, String name, char[] charArray, int arrayOffset) {\n\t\t\tsuper(position, remaining, name);\n\t\t\tthis.charArray = charArray;\n\t\t\t// TODO\n\t\t\tassert arrayOffset == 0;\n\t\t}\n\n\t\t/** Return the UTF-16 encoded string for the given interval */\n\t\t@Override\n\t\tpublic String getText(Interval interval) {\n\t\t\tint startIdx = Math.min(interval.a, size);\n\t\t\tint len = Math.min(interval.b - interval.a + 1, size - startIdx);\n\n\t\t\t// We know there are no surrogates in this\n\t\t\t// array, since otherwise we would be given a\n\t\t\t// 32-bit int[] array.\n\t\t\t//\n\t\t\t// So, it's safe to treat this as if it were\n\t\t\t// UTF-16.\n\t\t\treturn new String(charArray, startIdx, len);\n\t\t}\n\n\t\t@Override\n\t\tpublic int LA(int i) {\n\t\t\tint offset;\n\t\t\tswitch (Integer.signum(i)) {\n\t\t\t\tcase -1:\n\t\t\t\t\toffset = position + i;\n\t\t\t\t\tif (offset < 0) {\n\t\t\t\t\t\treturn IntStream.EOF;\n\t\t\t\t\t}\n\t\t\t\t\treturn charArray[offset] & 0xFFFF;\n\t\t\t\tcase 0:\n\t\t\t\t\t// Undefined\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 1:\n\t\t\t\t\toffset = position + i - 1;\n\t\t\t\t\tif (offset >= size) {\n\t\t\t\t\t\treturn IntStream.EOF;\n\t\t\t\t\t}\n\t\t\t\t\treturn charArray[offset] & 0xFFFF;\n\t\t\t}\n\t\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t\t}\n\n\t\t@Override\n\t\tObject getInternalStorage() {\n\t\t\treturn charArray;\n\t\t}\n\t}\n\n\t// 32-bit internal storage for code points between U+10000 and U+10FFFF.\n\tprivate static final class CodePoint32BitCharStream extends CodePointCharStream {\n\t\tprivate final int[] intArray;\n\n\t\tprivate CodePoint32BitCharStream(int position, int remaining, String name, int[] intArray, int arrayOffset) {\n\t\t\tsuper(position, remaining, name);\n\t\t\tthis.intArray = intArray;\n\t\t\t// TODO\n\t\t\tassert arrayOffset == 0;\n\t\t}\n\n\t\t/** Return the UTF-16 encoded string for the given interval */\n\t\t@Override\n\t\tpublic String getText(Interval interval) {\n\t\t\tint startIdx = Math.min(interval.a, size);\n\t\t\tint len = Math.min(interval.b - interval.a + 1, size - startIdx);\n\n\t\t\t// Note that we pass the int[] code points to the String constructor --\n\t\t\t// this is supported, and the constructor will convert to UTF-16 internally.\n\t\t\treturn new String(intArray, startIdx, len);\n\t\t}\n\n\t\t@Override\n\t\tpublic int LA(int i) {\n\t\t\tint offset;\n\t\t\tswitch (Integer.signum(i)) {\n\t\t\t\tcase -1:\n\t\t\t\t\toffset = position + i;\n\t\t\t\t\tif (offset < 0) {\n\t\t\t\t\t\treturn IntStream.EOF;\n\t\t\t\t\t}\n\t\t\t\t\treturn intArray[offset];\n\t\t\t\tcase 0:\n\t\t\t\t\t// Undefined\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 1:\n\t\t\t\t\toffset = position + i - 1;\n\t\t\t\t\tif (offset >= size) {\n\t\t\t\t\t\treturn IntStream.EOF;\n\t\t\t\t\t}\n\t\t\t\t\treturn intArray[offset];\n\t\t\t}\n\t\t\tthrow new UnsupportedOperationException(\"Not reached\");\n\t\t}\n\n\t\t@Override\n\t\tObject getInternalStorage() {\n\t\t\treturn intArray;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/CommonToken.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.io.Serializable;\n\npublic class CommonToken implements WritableToken, Serializable {\n\t/**\n\t * An empty {@link Pair} which is used as the default value of\n\t * {@link #source} for tokens that do not have a source.\n\t */\n\tprotected static final Pair<TokenSource, CharStream> EMPTY_SOURCE =\n\t\tnew Pair<TokenSource, CharStream>(null, null);\n\n\t/**\n\t * This is the backing field for {@link #getType} and {@link #setType}.\n\t */\n\tprotected int type;\n\n\t/**\n\t * This is the backing field for {@link #getLine} and {@link #setLine}.\n\t */\n\tprotected int line;\n\n\t/**\n\t * This is the backing field for {@link #getCharPositionInLine} and\n\t * {@link #setCharPositionInLine}.\n\t */\n\tprotected int charPositionInLine = -1; // set to invalid position\n\n\t/**\n\t * This is the backing field for {@link #getChannel} and\n\t * {@link #setChannel}.\n\t */\n\tprotected int channel=DEFAULT_CHANNEL;\n\n\t/**\n\t * This is the backing field for {@link #getTokenSource} and\n\t * {@link #getInputStream}.\n\t *\n\t * <p>\n\t * These properties share a field to reduce the memory footprint of\n\t * {@link CommonToken}. Tokens created by a {@link CommonTokenFactory} from\n\t * the same source and input stream share a reference to the same\n\t * {@link Pair} containing these values.</p>\n\t */\n\n\tprotected Pair<TokenSource, CharStream> source;\n\n\t/**\n\t * This is the backing field for {@link #getText} when the token text is\n\t * explicitly set in the constructor or via {@link #setText}.\n\t *\n\t * @see #getText()\n\t */\n\tprotected String text;\n\n\t/**\n\t * This is the backing field for {@link #getTokenIndex} and\n\t * {@link #setTokenIndex}.\n\t */\n\tprotected int index = -1;\n\n\t/**\n\t * This is the backing field for {@link #getStartIndex} and\n\t * {@link #setStartIndex}.\n\t */\n\tprotected int start;\n\n\t/**\n\t * This is the backing field for {@link #getStopIndex} and\n\t * {@link #setStopIndex}.\n\t */\n\tprotected int stop;\n\n\t/**\n\t * Constructs a new {@link CommonToken} with the specified token type.\n\t *\n\t * @param type The token type.\n\t */\n\tpublic CommonToken(int type) {\n\t\tthis.type = type;\n\t\tthis.source = EMPTY_SOURCE;\n\t}\n\n\tpublic CommonToken(Pair<TokenSource, CharStream> source, int type, int channel, int start, int stop) {\n\t\tthis.source = source;\n\t\tthis.type = type;\n\t\tthis.channel = channel;\n\t\tthis.start = start;\n\t\tthis.stop = stop;\n\t\tif (source.a != null) {\n\t\t\tthis.line = source.a.getLine();\n\t\t\tthis.charPositionInLine = source.a.getCharPositionInLine();\n\t\t}\n\t}\n\n\t/**\n\t * Constructs a new {@link CommonToken} with the specified token type and\n\t * text.\n\t *\n\t * @param type The token type.\n\t * @param text The text of the token.\n\t */\n\tpublic CommonToken(int type, String text) {\n\t\tthis.type = type;\n\t\tthis.channel = DEFAULT_CHANNEL;\n\t\tthis.text = text;\n\t\tthis.source = EMPTY_SOURCE;\n\t}\n\n\t/**\n\t * Constructs a new {@link CommonToken} as a copy of another {@link Token}.\n\t *\n\t * <p>\n\t * If {@code oldToken} is also a {@link CommonToken} instance, the newly\n\t * constructed token will share a reference to the {@link #text} field and\n\t * the {@link Pair} stored in {@link #source}. Otherwise, {@link #text} will\n\t * be assigned the result of calling {@link #getText}, and {@link #source}\n\t * will be constructed from the result of {@link Token#getTokenSource} and\n\t * {@link Token#getInputStream}.</p>\n\t *\n\t * @param oldToken The token to copy.\n\t */\n\tpublic CommonToken(Token oldToken) {\n\t\ttype = oldToken.getType();\n\t\tline = oldToken.getLine();\n\t\tindex = oldToken.getTokenIndex();\n\t\tcharPositionInLine = oldToken.getCharPositionInLine();\n\t\tchannel = oldToken.getChannel();\n\t\tstart = oldToken.getStartIndex();\n\t\tstop = oldToken.getStopIndex();\n\n\t\tif (oldToken instanceof CommonToken) {\n\t\t\ttext = ((CommonToken)oldToken).text;\n\t\t\tsource = ((CommonToken)oldToken).source;\n\t\t}\n\t\telse {\n\t\t\ttext = oldToken.getText();\n\t\t\tsource = new Pair<TokenSource, CharStream>(oldToken.getTokenSource(), oldToken.getInputStream());\n\t\t}\n\t}\n\n\t@Override\n\tpublic int getType() {\n\t\treturn type;\n\t}\n\n\t@Override\n\tpublic void setLine(int line) {\n\t\tthis.line = line;\n\t}\n\n\t@Override\n\tpublic String getText() {\n\t\tif ( text!=null ) {\n\t\t\treturn text;\n\t\t}\n\n\t\tCharStream input = getInputStream();\n\t\tif ( input==null ) return null;\n\t\tint n = input.size();\n\t\tif ( start<n && stop<n) {\n\t\t\treturn input.getText(Interval.of(start,stop));\n\t\t}\n\t\telse {\n\t\t\treturn \"<EOF>\";\n\t\t}\n\t}\n\n\t/**\n\t * Explicitly set the text for this token. If {code text} is not\n\t * {@code null}, then {@link #getText} will return this value rather than\n\t * extracting the text from the input.\n\t *\n\t * @param text The explicit text of the token, or {@code null} if the text\n\t * should be obtained from the input along with the start and stop indexes\n\t * of the token.\n\t */\n\t@Override\n\tpublic void setText(String text) {\n\t\tthis.text = text;\n\t}\n\n\t@Override\n\tpublic int getLine() {\n\t\treturn line;\n\t}\n\n\t@Override\n\tpublic int getCharPositionInLine() {\n\t\treturn charPositionInLine;\n\t}\n\n\t@Override\n\tpublic void setCharPositionInLine(int charPositionInLine) {\n\t\tthis.charPositionInLine = charPositionInLine;\n\t}\n\n\t@Override\n\tpublic int getChannel() {\n\t\treturn channel;\n\t}\n\n\t@Override\n\tpublic void setChannel(int channel) {\n\t\tthis.channel = channel;\n\t}\n\n\t@Override\n\tpublic void setType(int type) {\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic int getStartIndex() {\n\t\treturn start;\n\t}\n\n\tpublic void setStartIndex(int start) {\n\t\tthis.start = start;\n\t}\n\n\t@Override\n\tpublic int getStopIndex() {\n\t\treturn stop;\n\t}\n\n\tpublic void setStopIndex(int stop) {\n\t\tthis.stop = stop;\n\t}\n\n\t@Override\n\tpublic int getTokenIndex() {\n\t\treturn index;\n\t}\n\n\t@Override\n\tpublic void setTokenIndex(int index) {\n\t\tthis.index = index;\n\t}\n\n\t@Override\n\tpublic TokenSource getTokenSource() {\n\t\treturn source.a;\n\t}\n\n\t@Override\n\tpublic CharStream getInputStream() {\n\t\treturn source.b;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(null);\n\t}\n\n\tpublic String toString(Recognizer<?, ?> r) {\n\t\tString channelStr = \"\";\n\t\tif ( channel>0 ) {\n\t\t\tchannelStr=\",channel=\"+channel;\n\t\t}\n\t\tString txt = getText();\n\t\tif ( txt!=null ) {\n\t\t\ttxt = txt.replace(\"\\n\",\"\\\\n\");\n\t\t\ttxt = txt.replace(\"\\r\",\"\\\\r\");\n\t\t\ttxt = txt.replace(\"\\t\",\"\\\\t\");\n\t\t}\n\t\telse {\n\t\t\ttxt = \"<no text>\";\n\t\t}\n\t\tString typeString = String.valueOf(type);\n\t\tif ( r!=null ) {\n\t\t\ttypeString = r.getVocabulary().getDisplayName(type);\n\t\t}\n\t\treturn \"[@\"+getTokenIndex()+\",\"+start+\":\"+stop+\"='\"+txt+\"',<\"+typeString+\">\"+channelStr+\",\"+line+\":\"+getCharPositionInLine()+\"]\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/CommonTokenFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.Pair;\n\n/**\n * This default implementation of {@link TokenFactory} creates\n * {@link CommonToken} objects.\n */\npublic class CommonTokenFactory implements TokenFactory<CommonToken> {\n\t/**\n\t * The default {@link CommonTokenFactory} instance.\n\t *\n\t * <p>\n\t * This token factory does not explicitly copy token text when constructing\n\t * tokens.</p>\n\t */\n\tpublic static final TokenFactory<CommonToken> DEFAULT = new CommonTokenFactory();\n\n\t/**\n\t * Indicates whether {@link CommonToken#setText} should be called after\n\t * constructing tokens to explicitly set the text. This is useful for cases\n\t * where the input stream might not be able to provide arbitrary substrings\n\t * of text from the input after the lexer creates a token (e.g. the\n\t * implementation of {@link CharStream#getText} in\n\t * {@link UnbufferedCharStream} throws an\n\t * {@link UnsupportedOperationException}). Explicitly setting the token text\n\t * allows {@link Token#getText} to be called at any time regardless of the\n\t * input stream implementation.\n\t *\n\t * <p>\n\t * The default value is {@code false} to avoid the performance and memory\n\t * overhead of copying text for every token unless explicitly requested.</p>\n\t */\n\tprotected final boolean copyText;\n\n\t/**\n\t * Constructs a {@link CommonTokenFactory} with the specified value for\n\t * {@link #copyText}.\n\t *\n\t * <p>\n\t * When {@code copyText} is {@code false}, the {@link #DEFAULT} instance\n\t * should be used instead of constructing a new instance.</p>\n\t *\n\t * @param copyText The value for {@link #copyText}.\n\t */\n\tpublic CommonTokenFactory(boolean copyText) { this.copyText = copyText; }\n\n\t/**\n\t * Constructs a {@link CommonTokenFactory} with {@link #copyText} set to\n\t * {@code false}.\n\t *\n\t * <p>\n\t * The {@link #DEFAULT} instance should be used instead of calling this\n\t * directly.</p>\n\t */\n\tpublic CommonTokenFactory() { this(false); }\n\n\t@Override\n\tpublic CommonToken create(Pair<TokenSource, CharStream> source, int type, String text,\n\t\t\t\t\t\t\t  int channel, int start, int stop,\n\t\t\t\t\t\t\t  int line, int charPositionInLine)\n\t{\n\t\tCommonToken t = new CommonToken(source, type, channel, start, stop);\n\t\tt.setLine(line);\n\t\tt.setCharPositionInLine(charPositionInLine);\n\t\tif ( text!=null ) {\n\t\t\tt.setText(text);\n\t\t}\n\t\telse if ( copyText && source.b != null ) {\n\t\t\tt.setText(source.b.getText(Interval.of(start,stop)));\n\t\t}\n\n\t\treturn t;\n\t}\n\n\t@Override\n\tpublic CommonToken create(int type, String text) {\n\t\treturn new CommonToken(type, text);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/CommonTokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\n/**\n * This class extends {@link BufferedTokenStream} with functionality to filter\n * token streams to tokens on a particular channel (tokens where\n * {@link Token#getChannel} returns a particular value).\n *\n * <p>\n * This token stream provides access to all tokens by index or when calling\n * methods like {@link #getText}. The channel filtering is only used for code\n * accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and\n * {@link #LB}.</p>\n *\n * <p>\n * By default, tokens are placed on the default channel\n * ({@link Token#DEFAULT_CHANNEL}), but may be reassigned by using the\n * {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to\n * call {@link Lexer#setChannel}.\n * </p>\n *\n * <p>\n * Note: lexer rules which use the {@code ->skip} lexer command or call\n * {@link Lexer#skip} do not produce tokens at all, so input text matched by\n * such a rule will not be available as part of the token stream, regardless of\n * channel.</p>we\n */\npublic class CommonTokenStream extends BufferedTokenStream {\n\t/**\n\t * Specifies the channel to use for filtering tokens.\n\t *\n\t * <p>\n\t * The default value is {@link Token#DEFAULT_CHANNEL}, which matches the\n\t * default channel assigned to tokens created by the lexer.</p>\n\t */\n    protected int channel = Token.DEFAULT_CHANNEL;\n\n\t/**\n\t * Constructs a new {@link CommonTokenStream} using the specified token\n\t * source and the default token channel ({@link Token#DEFAULT_CHANNEL}).\n\t *\n\t * @param tokenSource The token source.\n\t */\n    public CommonTokenStream(TokenSource tokenSource) {\n        super(tokenSource);\n    }\n\n\t/**\n\t * Constructs a new {@link CommonTokenStream} using the specified token\n\t * source and filtering tokens to the specified channel. Only tokens whose\n\t * {@link Token#getChannel} matches {@code channel} or have the\n\t * {@link Token#getType} equal to {@link Token#EOF} will be returned by the\n\t * token stream lookahead methods.\n\t *\n\t * @param tokenSource The token source.\n\t * @param channel The channel to use for filtering tokens.\n\t */\n    public CommonTokenStream(TokenSource tokenSource, int channel) {\n        this(tokenSource);\n        this.channel = channel;\n    }\n\n\t@Override\n\tprotected int adjustSeekIndex(int i) {\n\t\treturn nextTokenOnChannel(i, channel);\n\t}\n\n    @Override\n    protected Token LB(int k) {\n        if ( k==0 || (p-k)<0 ) return null;\n\n        int i = p;\n        int n = 1;\n        // find k good tokens looking backwards\n        while ( n<=k && i>0 ) {\n            // skip off-channel tokens\n            i = previousTokenOnChannel(i - 1, channel);\n            n++;\n        }\n        if ( i<0 ) return null;\n        return tokens.get(i);\n    }\n\n    @Override\n    public Token LT(int k) {\n        //System.out.println(\"enter LT(\"+k+\")\");\n        lazyInit();\n        if ( k == 0 ) return null;\n        if ( k < 0 ) return LB(-k);\n        int i = p;\n        int n = 1; // we know tokens[p] is a good one\n        // find k good tokens\n        while ( n<k ) {\n            // skip off-channel tokens, but make sure to not look past EOF\n\t\t\tif (sync(i + 1)) {\n\t\t\t\ti = nextTokenOnChannel(i + 1, channel);\n\t\t\t}\n            n++;\n        }\n//\t\tif ( i>range ) range = i;\n        return tokens.get(i);\n    }\n\n\t/** Count EOF just once. */\n\tpublic int getNumberOfOnChannelTokens() {\n\t\tint n = 0;\n\t\tfill();\n\t\tfor (int i = 0; i < tokens.size(); i++) {\n\t\t\tToken t = tokens.get(i);\n\t\t\tif ( t.getChannel()==channel ) n++;\n\t\t\tif ( t.getType()==Token.EOF ) break;\n\t\t}\n\t\treturn n;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ConsoleErrorListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class ConsoleErrorListener extends BaseErrorListener {\n\t/**\n\t * Provides a default instance of {@link ConsoleErrorListener}.\n\t */\n\tpublic static final ConsoleErrorListener INSTANCE = new ConsoleErrorListener();\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>\n\t * This implementation prints messages to {@link System#err} containing the\n\t * values of {@code line}, {@code charPositionInLine}, and {@code msg} using\n\t * the following format.</p>\n\t *\n\t * <pre>\n\t * line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>\n\t * </pre>\n\t */\n\t@Override\n\tpublic void syntaxError(Recognizer<?, ?> recognizer,\n\t\t\t\t\t\t\tObject offendingSymbol,\n\t\t\t\t\t\t\tint line,\n\t\t\t\t\t\t\tint charPositionInLine,\n\t\t\t\t\t\t\tString msg,\n\t\t\t\t\t\t\tRecognitionException e)\n\t{\n\t\tSystem.err.println(\"line \" + line + \":\" + charPositionInLine + \" \" + msg);\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/DefaultErrorStrategy.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.misc.Pair;\n\n/**\n * This is the default implementation of {@link ANTLRErrorStrategy} used for\n * error reporting and recovery in ANTLR parsers.\n */\npublic class DefaultErrorStrategy implements ANTLRErrorStrategy {\n\t/**\n\t * Indicates whether the error strategy is currently \"recovering from an\n\t * error\". This is used to suppress reporting multiple error messages while\n\t * attempting to recover from a detected syntax error.\n\t *\n\t * @see #inErrorRecoveryMode\n\t */\n\tprotected boolean errorRecoveryMode = false;\n\n\t/** The index into the input stream where the last error occurred.\n\t * \tThis is used to prevent infinite loops where an error is found\n\t *  but no token is consumed during recovery...another error is found,\n\t *  ad nauseum.  This is a failsafe mechanism to guarantee that at least\n\t *  one token/tree node is consumed for two errors.\n\t */\n\tprotected int lastErrorIndex = -1;\n\n\tprotected IntervalSet lastErrorStates;\n\n\t/**\n\t * This field is used to propagate information about the lookahead following\n\t * the previous match. Since prediction prefers completing the current rule\n\t * to error recovery efforts, error reporting may occur later than the\n\t * original point where it was discoverable. The original context is used to\n\t * compute the true expected sets as though the reporting occurred as early\n\t * as possible.\n\t */\n\tprotected ParserRuleContext nextTokensContext;\n\n\t/**\n\t * @see #nextTokensContext\n\t */\n\tprotected int nextTokensState;\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation simply calls {@link #endErrorCondition} to\n\t * ensure that the handler is not in error recovery mode.</p>\n\t */\n\t@Override\n\tpublic void reset(Parser recognizer) {\n\t\tendErrorCondition(recognizer);\n\t}\n\n\t/**\n\t * This method is called to enter error recovery mode when a recognition\n\t * exception is reported.\n\t *\n\t * @param recognizer the parser instance\n\t */\n\tprotected void beginErrorCondition(Parser recognizer) {\n\t\terrorRecoveryMode = true;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic boolean inErrorRecoveryMode(Parser recognizer) {\n\t\treturn errorRecoveryMode;\n\t}\n\n\t/**\n\t * This method is called to leave error recovery mode after recovering from\n\t * a recognition exception.\n\t *\n\t * @param recognizer\n\t */\n\tprotected void endErrorCondition(Parser recognizer) {\n\t\terrorRecoveryMode = false;\n\t\tlastErrorStates = null;\n\t\tlastErrorIndex = -1;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation simply calls {@link #endErrorCondition}.</p>\n\t */\n\t@Override\n\tpublic void reportMatch(Parser recognizer) {\n\t\tendErrorCondition(recognizer);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns immediately if the handler is already\n\t * in error recovery mode. Otherwise, it calls {@link #beginErrorCondition}\n\t * and dispatches the reporting task based on the runtime type of {@code e}\n\t * according to the following table.</p>\n\t *\n\t * <ul>\n\t * <li>{@link NoViableAltException}: Dispatches the call to\n\t * {@link #reportNoViableAlternative}</li>\n\t * <li>{@link InputMismatchException}: Dispatches the call to\n\t * {@link #reportInputMismatch}</li>\n\t * <li>{@link FailedPredicateException}: Dispatches the call to\n\t * {@link #reportFailedPredicate}</li>\n\t * <li>All other types: calls {@link Parser#notifyErrorListeners} to report\n\t * the exception</li>\n\t * </ul>\n\t */\n\t@Override\n\tpublic void reportError(Parser recognizer,\n\t\t\t\t\t\t\tRecognitionException e)\n\t{\n\t\t// if we've already reported an error and have not matched a token\n\t\t// yet successfully, don't report any errors.\n\t\tif (inErrorRecoveryMode(recognizer)) {\n//\t\t\tSystem.err.print(\"[SPURIOUS] \");\n\t\t\treturn; // don't report spurious errors\n\t\t}\n\t\tbeginErrorCondition(recognizer);\n\t\tif ( e instanceof NoViableAltException ) {\n\t\t\treportNoViableAlternative(recognizer, (NoViableAltException) e);\n\t\t}\n\t\telse if ( e instanceof InputMismatchException ) {\n\t\t\treportInputMismatch(recognizer, (InputMismatchException)e);\n\t\t}\n\t\telse if ( e instanceof FailedPredicateException ) {\n\t\t\treportFailedPredicate(recognizer, (FailedPredicateException)e);\n\t\t}\n\t\telse {\n\t\t\tSystem.err.println(\"unknown recognition error type: \"+e.getClass().getName());\n\t\t\trecognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation resynchronizes the parser by consuming tokens\n\t * until we find one in the resynchronization set--loosely the set of tokens\n\t * that can follow the current rule.</p>\n\t */\n\t@Override\n\tpublic void recover(Parser recognizer, RecognitionException e) {\n//\t\tSystem.out.println(\"recover in \"+recognizer.getRuleInvocationStack()+\n//\t\t\t\t\t\t   \" index=\"+recognizer.getInputStream().index()+\n//\t\t\t\t\t\t   \", lastErrorIndex=\"+\n//\t\t\t\t\t\t   lastErrorIndex+\n//\t\t\t\t\t\t   \", states=\"+lastErrorStates);\n\t\tif ( lastErrorIndex==recognizer.getInputStream().index() &&\n\t\t\tlastErrorStates != null &&\n\t\t\tlastErrorStates.contains(recognizer.getState()) ) {\n\t\t\t// uh oh, another error at same token index and previously-visited\n\t\t\t// state in ATN; must be a case where LT(1) is in the recovery\n\t\t\t// token set so nothing got consumed. Consume a single token\n\t\t\t// at least to prevent an infinite loop; this is a failsafe.\n//\t\t\tSystem.err.println(\"seen error condition before index=\"+\n//\t\t\t\t\t\t\t   lastErrorIndex+\", states=\"+lastErrorStates);\n//\t\t\tSystem.err.println(\"FAILSAFE consumes \"+recognizer.getTokenNames()[recognizer.getInputStream().LA(1)]);\n\t\t\trecognizer.consume();\n\t\t}\n\t\tlastErrorIndex = recognizer.getInputStream().index();\n\t\tif ( lastErrorStates==null ) lastErrorStates = new IntervalSet();\n\t\tlastErrorStates.add(recognizer.getState());\n\t\tIntervalSet followSet = getErrorRecoverySet(recognizer);\n\t\tconsumeUntil(recognizer, followSet);\n\t}\n\n\t/**\n\t * The default implementation of {@link ANTLRErrorStrategy#sync} makes sure\n\t * that the current lookahead symbol is consistent with what were expecting\n\t * at this point in the ATN. You can call this anytime but ANTLR only\n\t * generates code to check before subrules/loops and each iteration.\n\t *\n\t * <p>Implements Jim Idle's magic sync mechanism in closures and optional\n\t * subrules. E.g.,</p>\n\t *\n\t * <pre>\n\t * a : sync ( stuff sync )* ;\n\t * sync : {consume to what can follow sync} ;\n\t * </pre>\n\t *\n\t * At the start of a sub rule upon error, {@link #sync} performs single\n\t * token deletion, if possible. If it can't do that, it bails on the current\n\t * rule and uses the default error recovery, which consumes until the\n\t * resynchronization set of the current rule.\n\t *\n\t * <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block\n\t * with an empty alternative), then the expected set includes what follows\n\t * the subrule.</p>\n\t *\n\t * <p>During loop iteration, it consumes until it sees a token that can start a\n\t * sub rule or what follows loop. Yes, that is pretty aggressive. We opt to\n\t * stay in the loop as long as possible.</p>\n\t *\n\t * <p><strong>ORIGINS</strong></p>\n\t *\n\t * <p>Previous versions of ANTLR did a poor job of their recovery within loops.\n\t * A single mismatch token or missing token would force the parser to bail\n\t * out of the entire rules surrounding the loop. So, for rule</p>\n\t *\n\t * <pre>\n\t * classDef : 'class' ID '{' member* '}'\n\t * </pre>\n\t *\n\t * input with an extra token between members would force the parser to\n\t * consume until it found the next class definition rather than the next\n\t * member definition of the current class.\n\t *\n\t * <p>This functionality cost a little bit of effort because the parser has to\n\t * compare token set at the start of the loop and at each iteration. If for\n\t * some reason speed is suffering for you, you can turn off this\n\t * functionality by simply overriding this method as a blank { }.</p>\n\t */\n\t@Override\n\tpublic void sync(Parser recognizer) throws RecognitionException {\n\t\tATNState s = recognizer.getInterpreter().atn.states.get(recognizer.getState());\n//\t\tSystem.err.println(\"sync @ \"+s.stateNumber+\"=\"+s.getClass().getSimpleName());\n\t\t// If already recovering, don't try to sync\n\t\tif (inErrorRecoveryMode(recognizer)) {\n\t\t\treturn;\n\t\t}\n\n        TokenStream tokens = recognizer.getInputStream();\n        int la = tokens.LA(1);\n\n        // try cheaper subset first; might get lucky. seems to shave a wee bit off\n\t\tIntervalSet nextTokens = recognizer.getATN().nextTokens(s);\n\t\tif (nextTokens.contains(la)) {\n\t\t\t// We are sure the token matches\n\t\t\tnextTokensContext = null;\n\t\t\tnextTokensState = ATNState.INVALID_STATE_NUMBER;\n\t\t\treturn;\n\t\t}\n\n\t\tif (nextTokens.contains(Token.EPSILON)) {\n\t\t\tif (nextTokensContext == null) {\n\t\t\t\t// It's possible the next token won't match; information tracked\n\t\t\t\t// by sync is restricted for performance.\n\t\t\t\tnextTokensContext = recognizer.getContext();\n\t\t\t\tnextTokensState = recognizer.getState();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (s.getStateType()) {\n\t\tcase ATNState.BLOCK_START:\n\t\tcase ATNState.STAR_BLOCK_START:\n\t\tcase ATNState.PLUS_BLOCK_START:\n\t\tcase ATNState.STAR_LOOP_ENTRY:\n\t\t\t// report error and recover if possible\n\t\t\tif ( singleTokenDeletion(recognizer)!=null ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new InputMismatchException(recognizer);\n\n\t\tcase ATNState.PLUS_LOOP_BACK:\n\t\tcase ATNState.STAR_LOOP_BACK:\n//\t\t\tSystem.err.println(\"at loop back: \"+s.getClass().getSimpleName());\n\t\t\treportUnwantedToken(recognizer);\n\t\t\tIntervalSet expecting = recognizer.getExpectedTokens();\n\t\t\tIntervalSet whatFollowsLoopIterationOrRule =\n\t\t\t\texpecting.or(getErrorRecoverySet(recognizer));\n\t\t\tconsumeUntil(recognizer, whatFollowsLoopIterationOrRule);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t// do nothing if we can't identify the exact kind of ATN state\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n\t * This is called by {@link #reportError} when the exception is a\n\t * {@link NoViableAltException}.\n\t *\n\t * @see #reportError\n\t *\n\t * @param recognizer the parser instance\n\t * @param e the recognition exception\n\t */\n\tprotected void reportNoViableAlternative(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t\t NoViableAltException e)\n\t{\n\t\tTokenStream tokens = recognizer.getInputStream();\n\t\tString input;\n\t\tif ( tokens!=null ) {\n\t\t\tif ( e.getStartToken().getType()==Token.EOF ) input = \"<EOF>\";\n\t\t\telse input = tokens.getText(e.getStartToken(), e.getOffendingToken());\n\t\t}\n\t\telse {\n\t\t\tinput = \"<unknown input>\";\n\t\t}\n\t\tString msg = \"no viable alternative at input \"+escapeWSAndQuote(input);\n\t\trecognizer.notifyErrorListeners(e.getOffendingToken(), msg, e);\n\t}\n\n\t/**\n\t * This is called by {@link #reportError} when the exception is an\n\t * {@link InputMismatchException}.\n\t *\n\t * @see #reportError\n\t *\n\t * @param recognizer the parser instance\n\t * @param e the recognition exception\n\t */\n\tprotected void reportInputMismatch(Parser recognizer,\n\t\t\t\t\t\t\t\t\t   InputMismatchException e)\n\t{\n\t\tString msg = \"mismatched input \"+getTokenErrorDisplay(e.getOffendingToken())+\n\t\t\" expecting \"+e.getExpectedTokens().toString(recognizer.getVocabulary());\n\t\trecognizer.notifyErrorListeners(e.getOffendingToken(), msg, e);\n\t}\n\n\t/**\n\t * This is called by {@link #reportError} when the exception is a\n\t * {@link FailedPredicateException}.\n\t *\n\t * @see #reportError\n\t *\n\t * @param recognizer the parser instance\n\t * @param e the recognition exception\n\t */\n\tprotected void reportFailedPredicate(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t FailedPredicateException e)\n\t{\n\t\tString ruleName = recognizer.getRuleNames()[recognizer._ctx.getRuleIndex()];\n\t\tString msg = \"rule \"+ruleName+\" \"+e.getMessage();\n\t\trecognizer.notifyErrorListeners(e.getOffendingToken(), msg, e);\n\t}\n\n\t/**\n\t * This method is called to report a syntax error which requires the removal\n\t * of a token from the input stream. At the time this method is called, the\n\t * erroneous symbol is current {@code LT(1)} symbol and has not yet been\n\t * removed from the input stream. When this method returns,\n\t * {@code recognizer} is in error recovery mode.\n\t *\n\t * <p>This method is called when {@link #singleTokenDeletion} identifies\n\t * single-token deletion as a viable recovery strategy for a mismatched\n\t * input error.</p>\n\t *\n\t * <p>The default implementation simply returns if the handler is already in\n\t * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n\t * enter error recovery mode, followed by calling\n\t * {@link Parser#notifyErrorListeners}.</p>\n\t *\n\t * @param recognizer the parser instance\n\t */\n\tprotected void reportUnwantedToken(Parser recognizer) {\n\t\tif (inErrorRecoveryMode(recognizer)) {\n\t\t\treturn;\n\t\t}\n\n\t\tbeginErrorCondition(recognizer);\n\n\t\tToken t = recognizer.getCurrentToken();\n\t\tString tokenName = getTokenErrorDisplay(t);\n\t\tIntervalSet expecting = getExpectedTokens(recognizer);\n\t\tString msg = \"extraneous input \"+tokenName+\" expecting \"+\n\t\t\texpecting.toString(recognizer.getVocabulary());\n\t\trecognizer.notifyErrorListeners(t, msg, null);\n\t}\n\n\t/**\n\t * This method is called to report a syntax error which requires the\n\t * insertion of a missing token into the input stream. At the time this\n\t * method is called, the missing token has not yet been inserted. When this\n\t * method returns, {@code recognizer} is in error recovery mode.\n\t *\n\t * <p>This method is called when {@link #singleTokenInsertion} identifies\n\t * single-token insertion as a viable recovery strategy for a mismatched\n\t * input error.</p>\n\t *\n\t * <p>The default implementation simply returns if the handler is already in\n\t * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n\t * enter error recovery mode, followed by calling\n\t * {@link Parser#notifyErrorListeners}.</p>\n\t *\n\t * @param recognizer the parser instance\n\t */\n\tprotected void reportMissingToken(Parser recognizer) {\n\t\tif (inErrorRecoveryMode(recognizer)) {\n\t\t\treturn;\n\t\t}\n\n\t\tbeginErrorCondition(recognizer);\n\n\t\tToken t = recognizer.getCurrentToken();\n\t\tIntervalSet expecting = getExpectedTokens(recognizer);\n\t\tString msg = \"missing \"+expecting.toString(recognizer.getVocabulary())+\n\t\t\t\" at \"+getTokenErrorDisplay(t);\n\n\t\trecognizer.notifyErrorListeners(t, msg, null);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation attempts to recover from the mismatched input\n\t * by using single token insertion and deletion as described below. If the\n\t * recovery attempt fails, this method throws an\n\t * {@link InputMismatchException}.</p>\n\t *\n\t * <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>\n\t *\n\t * <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the\n\t * right token, however, then assume {@code LA(1)} is some extra spurious\n\t * token and delete it. Then consume and return the next token (which was\n\t * the {@code LA(2)} token) as the successful result of the match operation.</p>\n\t *\n\t * <p>This recovery strategy is implemented by {@link #singleTokenDeletion}.</p>\n\t *\n\t * <p><strong>MISSING TOKEN</strong> (single token insertion)</p>\n\t *\n\t * <p>If current token (at {@code LA(1)}) is consistent with what could come\n\t * after the expected {@code LA(1)} token, then assume the token is missing\n\t * and use the parser's {@link TokenFactory} to create it on the fly. The\n\t * \"insertion\" is performed by returning the created token as the successful\n\t * result of the match operation.</p>\n\t *\n\t * <p>This recovery strategy is implemented by {@link #singleTokenInsertion}.</p>\n\t *\n\t * <p><strong>EXAMPLE</strong></p>\n\t *\n\t * <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When\n\t * the parser returns from the nested call to {@code expr}, it will have\n\t * call chain:</p>\n\t *\n\t * <pre>\n\t * stat &rarr; expr &rarr; atom\n\t * </pre>\n\t *\n\t * and it will be trying to match the {@code ')'} at this point in the\n\t * derivation:\n\t *\n\t * <pre>\n\t * =&gt; ID '=' '(' INT ')' ('+' atom)* ';'\n\t *                    ^\n\t * </pre>\n\t *\n\t * The attempt to match {@code ')'} will fail when it sees {@code ';'} and\n\t * call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'}\n\t * is in the set of tokens that can follow the {@code ')'} token reference\n\t * in rule {@code atom}. It can assume that you forgot the {@code ')'}.\n\t */\n\t@Override\n\tpublic Token recoverInline(Parser recognizer)\n\t\tthrows RecognitionException\n\t{\n\t\t// SINGLE TOKEN DELETION\n\t\tToken matchedSymbol = singleTokenDeletion(recognizer);\n\t\tif ( matchedSymbol!=null ) {\n\t\t\t// we have deleted the extra token.\n\t\t\t// now, move past ttype token as if all were ok\n\t\t\trecognizer.consume();\n\t\t\treturn matchedSymbol;\n\t\t}\n\n\t\t// SINGLE TOKEN INSERTION\n\t\tif ( singleTokenInsertion(recognizer) ) {\n\t\t\treturn getMissingSymbol(recognizer);\n\t\t}\n\n\t\t// even that didn't work; must throw the exception\n\t\tInputMismatchException e;\n\t\tif (nextTokensContext == null) {\n\t\t\te = new InputMismatchException(recognizer);\n\t\t} else {\n\t\t\te = new InputMismatchException(recognizer, nextTokensState, nextTokensContext);\n\t\t}\n\n\t\tthrow e;\n\t}\n\n\t/**\n\t * This method implements the single-token insertion inline error recovery\n\t * strategy. It is called by {@link #recoverInline} if the single-token\n\t * deletion strategy fails to recover from the mismatched input. If this\n\t * method returns {@code true}, {@code recognizer} will be in error recovery\n\t * mode.\n\t *\n\t * <p>This method determines whether or not single-token insertion is viable by\n\t * checking if the {@code LA(1)} input symbol could be successfully matched\n\t * if it were instead the {@code LA(2)} symbol. If this method returns\n\t * {@code true}, the caller is responsible for creating and inserting a\n\t * token with the correct type to produce this behavior.</p>\n\t *\n\t * @param recognizer the parser instance\n\t * @return {@code true} if single-token insertion is a viable recovery\n\t * strategy for the current mismatched input, otherwise {@code false}\n\t */\n\tprotected boolean singleTokenInsertion(Parser recognizer) {\n\t\tint currentSymbolType = recognizer.getInputStream().LA(1);\n\t\t// if current token is consistent with what could come after current\n\t\t// ATN state, then we know we're missing a token; error recovery\n\t\t// is free to conjure up and insert the missing token\n\t\tATNState currentState = recognizer.getInterpreter().atn.states.get(recognizer.getState());\n\t\tATNState next = currentState.transition(0).target;\n\t\tATN atn = recognizer.getInterpreter().atn;\n\t\tIntervalSet expectingAtLL2 = atn.nextTokens(next, recognizer._ctx);\n//\t\tSystem.out.println(\"LT(2) set=\"+expectingAtLL2.toString(recognizer.getTokenNames()));\n\t\tif ( expectingAtLL2.contains(currentSymbolType) ) {\n\t\t\treportMissingToken(recognizer);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * This method implements the single-token deletion inline error recovery\n\t * strategy. It is called by {@link #recoverInline} to attempt to recover\n\t * from mismatched input. If this method returns null, the parser and error\n\t * handler state will not have changed. If this method returns non-null,\n\t * {@code recognizer} will <em>not</em> be in error recovery mode since the\n\t * returned token was a successful match.\n\t *\n\t * <p>If the single-token deletion is successful, this method calls\n\t * {@link #reportUnwantedToken} to report the error, followed by\n\t * {@link Parser#consume} to actually \"delete\" the extraneous token. Then,\n\t * before returning {@link #reportMatch} is called to signal a successful\n\t * match.</p>\n\t *\n\t * @param recognizer the parser instance\n\t * @return the successfully matched {@link Token} instance if single-token\n\t * deletion successfully recovers from the mismatched input, otherwise\n\t * {@code null}\n\t */\n\tprotected Token singleTokenDeletion(Parser recognizer) {\n\t\tint nextTokenType = recognizer.getInputStream().LA(2);\n\t\tIntervalSet expecting = getExpectedTokens(recognizer);\n\t\tif ( expecting.contains(nextTokenType) ) {\n\t\t\treportUnwantedToken(recognizer);\n\t\t\t/*\n\t\t\tSystem.err.println(\"recoverFromMismatchedToken deleting \"+\n\t\t\t\t\t\t\t   ((TokenStream)recognizer.getInputStream()).LT(1)+\n\t\t\t\t\t\t\t   \" since \"+((TokenStream)recognizer.getInputStream()).LT(2)+\n\t\t\t\t\t\t\t   \" is what we want\");\n\t\t\t*/\n\t\t\trecognizer.consume(); // simply delete extra token\n\t\t\t// we want to return the token we're actually matching\n\t\t\tToken matchedSymbol = recognizer.getCurrentToken();\n\t\t\treportMatch(recognizer);  // we know current token is correct\n\t\t\treturn matchedSymbol;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Conjure up a missing token during error recovery.\n\t *\n\t *  The recognizer attempts to recover from single missing\n\t *  symbols. But, actions might refer to that missing symbol.\n\t *  For example, x=ID {f($x);}. The action clearly assumes\n\t *  that there has been an identifier matched previously and that\n\t *  $x points at that token. If that token is missing, but\n\t *  the next token in the stream is what we want we assume that\n\t *  this token is missing and we keep going. Because we\n\t *  have to return some token to replace the missing token,\n\t *  we have to conjure one up. This method gives the user control\n\t *  over the tokens returned for missing tokens. Mostly,\n\t *  you will want to create something special for identifier\n\t *  tokens. For literals such as '{' and ',', the default\n\t *  action in the parser or tree parser works. It simply creates\n\t *  a CommonToken of the appropriate type. The text will be the token.\n\t *  If you change what tokens must be created by the lexer,\n\t *  override this method to create the appropriate tokens.\n\t */\n\tprotected Token getMissingSymbol(Parser recognizer) {\n\t\tToken currentSymbol = recognizer.getCurrentToken();\n\t\tIntervalSet expecting = getExpectedTokens(recognizer);\n\t\tint expectedTokenType = Token.INVALID_TYPE;\n\t\tif ( !expecting.isNil() ) {\n\t\t\texpectedTokenType = expecting.getMinElement(); // get any element\n\t\t}\n\t\tString tokenText;\n\t\tif ( expectedTokenType== Token.EOF ) tokenText = \"<missing EOF>\";\n\t\telse tokenText = \"<missing \"+recognizer.getVocabulary().getDisplayName(expectedTokenType)+\">\";\n\t\tToken current = currentSymbol;\n\t\tToken lookback = recognizer.getInputStream().LT(-1);\n\t\tif ( current.getType() == Token.EOF && lookback!=null ) {\n\t\t\tcurrent = lookback;\n\t\t}\n\t\treturn\n\t\t\trecognizer.getTokenFactory().create(new Pair<TokenSource, CharStream>(current.getTokenSource(), current.getTokenSource().getInputStream()), expectedTokenType, tokenText,\n\t\t\t\t\t\t\tToken.DEFAULT_CHANNEL,\n\t\t\t\t\t\t\t-1, -1,\n\t\t\t\t\t\t\tcurrent.getLine(), current.getCharPositionInLine());\n\t}\n\n\n\tprotected IntervalSet getExpectedTokens(Parser recognizer) {\n\t\treturn recognizer.getExpectedTokens();\n\t}\n\n\t/** How should a token be displayed in an error message? The default\n\t *  is to display just the text, but during development you might\n\t *  want to have a lot of information spit out.  Override in that case\n\t *  to use t.toString() (which, for CommonToken, dumps everything about\n\t *  the token). This is better than forcing you to override a method in\n\t *  your token objects because you don't have to go modify your lexer\n\t *  so that it creates a new Java type.\n\t */\n\tprotected String getTokenErrorDisplay(Token t) {\n\t\tif ( t==null ) return \"<no token>\";\n\t\tString s = getSymbolText(t);\n\t\tif ( s==null ) {\n\t\t\tif ( getSymbolType(t)==Token.EOF ) {\n\t\t\t\ts = \"<EOF>\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\ts = \"<\"+getSymbolType(t)+\">\";\n\t\t\t}\n\t\t}\n\t\treturn escapeWSAndQuote(s);\n\t}\n\n\tprotected String getSymbolText(Token symbol) {\n\t\treturn symbol.getText();\n\t}\n\n\tprotected int getSymbolType(Token symbol) {\n\t\treturn symbol.getType();\n\t}\n\n\n\tprotected String escapeWSAndQuote(String s) {\n//\t\tif ( s==null ) return s;\n\t\ts = s.replace(\"\\n\",\"\\\\n\");\n\t\ts = s.replace(\"\\r\",\"\\\\r\");\n\t\ts = s.replace(\"\\t\",\"\\\\t\");\n\t\treturn \"'\"+s+\"'\";\n\t}\n\n\t/*  Compute the error recovery set for the current rule.  During\n\t *  rule invocation, the parser pushes the set of tokens that can\n\t *  follow that rule reference on the stack; this amounts to\n\t *  computing FIRST of what follows the rule reference in the\n\t *  enclosing rule. See LinearApproximator.FIRST().\n\t *  This local follow set only includes tokens\n\t *  from within the rule; i.e., the FIRST computation done by\n\t *  ANTLR stops at the end of a rule.\n\t *\n\t *  EXAMPLE\n\t *\n\t *  When you find a \"no viable alt exception\", the input is not\n\t *  consistent with any of the alternatives for rule r.  The best\n\t *  thing to do is to consume tokens until you see something that\n\t *  can legally follow a call to r *or* any rule that called r.\n\t *  You don't want the exact set of viable next tokens because the\n\t *  input might just be missing a token--you might consume the\n\t *  rest of the input looking for one of the missing tokens.\n\t *\n\t *  Consider grammar:\n\t *\n\t *  a : '[' b ']'\n\t *    | '(' b ')'\n\t *    ;\n\t *  b : c '^' INT ;\n\t *  c : ID\n\t *    | INT\n\t *    ;\n\t *\n\t *  At each rule invocation, the set of tokens that could follow\n\t *  that rule is pushed on a stack.  Here are the various\n\t *  context-sensitive follow sets:\n\t *\n\t *  FOLLOW(b1_in_a) = FIRST(']') = ']'\n\t *  FOLLOW(b2_in_a) = FIRST(')') = ')'\n\t *  FOLLOW(c_in_b) = FIRST('^') = '^'\n\t *\n\t *  Upon erroneous input \"[]\", the call chain is\n\t *\n\t *  a -> b -> c\n\t *\n\t *  and, hence, the follow context stack is:\n\t *\n\t *  depth     follow set       start of rule execution\n\t *    0         <EOF>                    a (from main())\n\t *    1          ']'                     b\n\t *    2          '^'                     c\n\t *\n\t *  Notice that ')' is not included, because b would have to have\n\t *  been called from a different context in rule a for ')' to be\n\t *  included.\n\t *\n\t *  For error recovery, we cannot consider FOLLOW(c)\n\t *  (context-sensitive or otherwise).  We need the combined set of\n\t *  all context-sensitive FOLLOW sets--the set of all tokens that\n\t *  could follow any reference in the call chain.  We need to\n\t *  resync to one of those tokens.  Note that FOLLOW(c)='^' and if\n\t *  we resync'd to that token, we'd consume until EOF.  We need to\n\t *  sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.\n\t *  In this case, for input \"[]\", LA(1) is ']' and in the set, so we would\n\t *  not consume anything. After printing an error, rule c would\n\t *  return normally.  Rule b would not find the required '^' though.\n\t *  At this point, it gets a mismatched token error and throws an\n\t *  exception (since LA(1) is not in the viable following token\n\t *  set).  The rule exception handler tries to recover, but finds\n\t *  the same recovery set and doesn't consume anything.  Rule b\n\t *  exits normally returning to rule a.  Now it finds the ']' (and\n\t *  with the successful match exits errorRecovery mode).\n\t *\n\t *  So, you can see that the parser walks up the call chain looking\n\t *  for the token that was a member of the recovery set.\n\t *\n\t *  Errors are not generated in errorRecovery mode.\n\t *\n\t *  ANTLR's error recovery mechanism is based upon original ideas:\n\t *\n\t *  \"Algorithms + Data Structures = Programs\" by Niklaus Wirth\n\t *\n\t *  and\n\t *\n\t *  \"A note on error recovery in recursive descent parsers\":\n\t *  http://portal.acm.org/citation.cfm?id=947902.947905\n\t *\n\t *  Later, Josef Grosch had some good ideas:\n\t *\n\t *  \"Efficient and Comfortable Error Recovery in Recursive Descent\n\t *  Parsers\":\n\t *  ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip\n\t *\n\t *  Like Grosch I implement context-sensitive FOLLOW sets that are combined\n\t *  at run-time upon error to avoid overhead during parsing.\n\t */\n\tprotected IntervalSet getErrorRecoverySet(Parser recognizer) {\n\t\tATN atn = recognizer.getInterpreter().atn;\n\t\tRuleContext ctx = recognizer._ctx;\n\t\tIntervalSet recoverSet = new IntervalSet();\n\t\twhile ( ctx!=null && ctx.invokingState>=0 ) {\n\t\t\t// compute what follows who invoked us\n\t\t\tATNState invokingState = atn.states.get(ctx.invokingState);\n\t\t\tRuleTransition rt = (RuleTransition)invokingState.transition(0);\n\t\t\tIntervalSet follow = atn.nextTokens(rt.followState);\n\t\t\trecoverSet.addAll(follow);\n\t\t\tctx = ctx.parent;\n\t\t}\n        recoverSet.remove(Token.EPSILON);\n//\t\tSystem.out.println(\"recover set \"+recoverSet.toString(recognizer.getTokenNames()));\n\t\treturn recoverSet;\n\t}\n\n\t/** Consume tokens until one matches the given token set. */\n\tprotected void consumeUntil(Parser recognizer, IntervalSet set) {\n//\t\tSystem.err.println(\"consumeUntil(\"+set.toString(recognizer.getTokenNames())+\")\");\n\t\tint ttype = recognizer.getInputStream().LA(1);\n\t\twhile (ttype != Token.EOF && !set.contains(ttype) ) {\n            //System.out.println(\"consume during recover LA(1)=\"+getTokenNames()[input.LA(1)]);\n//\t\t\trecognizer.getInputStream().consume();\n            recognizer.consume();\n            ttype = recognizer.getInputStream().LA(1);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/DiagnosticErrorListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATNConfig;\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.util.BitSet;\n\n/**\n * This implementation of {@link ANTLRErrorListener} can be used to identify\n * certain potential correctness and performance problems in grammars. \"Reports\"\n * are made by calling {@link Parser#notifyErrorListeners} with the appropriate\n * message.\n *\n * <ul>\n * <li><b>Ambiguities</b>: These are cases where more than one path through the\n * grammar can match the input.</li>\n * <li><b>Weak context sensitivity</b>: These are cases where full-context\n * prediction resolved an SLL conflict to a unique alternative which equaled the\n * minimum alternative of the SLL conflict.</li>\n * <li><b>Strong (forced) context sensitivity</b>: These are cases where the\n * full-context prediction resolved an SLL conflict to a unique alternative,\n * <em>and</em> the minimum alternative of the SLL conflict was found to not be\n * a truly viable alternative. Two-stage parsing cannot be used for inputs where\n * this situation occurs.</li>\n * </ul>\n *\n * @author Sam Harwell\n */\npublic class DiagnosticErrorListener extends BaseErrorListener {\n\t/**\n\t * When {@code true}, only exactly known ambiguities are reported.\n\t */\n\tprotected final boolean exactOnly;\n\n\t/**\n\t * Initializes a new instance of {@link DiagnosticErrorListener} which only\n\t * reports exact ambiguities.\n\t */\n\tpublic DiagnosticErrorListener() {\n\t\tthis(true);\n\t}\n\n\t/**\n\t * Initializes a new instance of {@link DiagnosticErrorListener}, specifying\n\t * whether all ambiguities or only exact ambiguities are reported.\n\t *\n\t * @param exactOnly {@code true} to report only exact ambiguities, otherwise\n\t * {@code false} to report all ambiguities.\n\t */\n\tpublic DiagnosticErrorListener(boolean exactOnly) {\n\t\tthis.exactOnly = exactOnly;\n\t}\n\n\t@Override\n\tpublic void reportAmbiguity(Parser recognizer,\n\t\t\t\t\t\t\t\tDFA dfa,\n\t\t\t\t\t\t\t\tint startIndex,\n\t\t\t\t\t\t\t\tint stopIndex,\n\t\t\t\t\t\t\t\tboolean exact,\n\t\t\t\t\t\t\t\tBitSet ambigAlts,\n\t\t\t\t\t\t\t\tATNConfigSet configs)\n\t{\n\t\tif (exactOnly && !exact) {\n\t\t\treturn;\n\t\t}\n\n\t\tString format = \"reportAmbiguity d=%s: ambigAlts=%s, input='%s'\";\n\t\tString decision = getDecisionDescription(recognizer, dfa);\n\t\tBitSet conflictingAlts = getConflictingAlts(ambigAlts, configs);\n\t\tString text = recognizer.getTokenStream().getText(Interval.of(startIndex, stopIndex));\n\t\tString message = String.format(format, decision, conflictingAlts, text);\n\t\trecognizer.notifyErrorListeners(message);\n\t}\n\n\t@Override\n\tpublic void reportAttemptingFullContext(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t\tDFA dfa,\n\t\t\t\t\t\t\t\t\t\t\tint startIndex,\n\t\t\t\t\t\t\t\t\t\t\tint stopIndex,\n\t\t\t\t\t\t\t\t\t\t\tBitSet conflictingAlts,\n\t\t\t\t\t\t\t\t\t\t\tATNConfigSet configs)\n\t{\n\t\tString format = \"reportAttemptingFullContext d=%s, input='%s'\";\n\t\tString decision = getDecisionDescription(recognizer, dfa);\n\t\tString text = recognizer.getTokenStream().getText(Interval.of(startIndex, stopIndex));\n\t\tString message = String.format(format, decision, text);\n\t\trecognizer.notifyErrorListeners(message);\n\t}\n\n\t@Override\n\tpublic void reportContextSensitivity(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t DFA dfa,\n\t\t\t\t\t\t\t\t\t\t int startIndex,\n\t\t\t\t\t\t\t\t\t\t int stopIndex,\n\t\t\t\t\t\t\t\t\t\t int prediction,\n\t\t\t\t\t\t\t\t\t\t ATNConfigSet configs)\n\t{\n\t\tString format = \"reportContextSensitivity d=%s, input='%s'\";\n\t\tString decision = getDecisionDescription(recognizer, dfa);\n\t\tString text = recognizer.getTokenStream().getText(Interval.of(startIndex, stopIndex));\n\t\tString message = String.format(format, decision, text);\n\t\trecognizer.notifyErrorListeners(message);\n\t}\n\n\tprotected String getDecisionDescription(Parser recognizer, DFA dfa) {\n\t\tint decision = dfa.decision;\n\t\tint ruleIndex = dfa.atnStartState.ruleIndex;\n\n\t\tString[] ruleNames = recognizer.getRuleNames();\n\t\tif (ruleIndex < 0 || ruleIndex >= ruleNames.length) {\n\t\t\treturn String.valueOf(decision);\n\t\t}\n\n\t\tString ruleName = ruleNames[ruleIndex];\n\t\tif (ruleName == null || ruleName.isEmpty()) {\n\t\t\treturn String.valueOf(decision);\n\t\t}\n\n\t\treturn String.format(\"%d (%s)\", decision, ruleName);\n\t}\n\n\t/**\n\t * Computes the set of conflicting or ambiguous alternatives from a\n\t * configuration set, if that information was not already provided by the\n\t * parser.\n\t *\n\t * @param reportedAlts The set of conflicting or ambiguous alternatives, as\n\t * reported by the parser.\n\t * @param configs The conflicting or ambiguous configuration set.\n\t * @return Returns {@code reportedAlts} if it is not {@code null}, otherwise\n\t * returns the set of alternatives represented in {@code configs}.\n\t */\n\tprotected BitSet getConflictingAlts(BitSet reportedAlts, ATNConfigSet configs) {\n\t\tif (reportedAlts != null) {\n\t\t\treturn reportedAlts;\n\t\t}\n\n\t\tBitSet result = new BitSet();\n\t\tfor (ATNConfig config : configs) {\n\t\t\tresult.set(config.alt);\n\t\t}\n\n\t\treturn result;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/FailedPredicateException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.AbstractPredicateTransition;\nimport org.antlr.v4.runtime.atn.PredicateTransition;\n\nimport java.util.Locale;\n\n/** A semantic predicate failed during validation.  Validation of predicates\n *  occurs when normally parsing the alternative just like matching a token.\n *  Disambiguating predicate evaluation occurs when we test a predicate during\n *  prediction.\n */\npublic class FailedPredicateException extends RecognitionException {\n\tprivate final int ruleIndex;\n\tprivate final int predicateIndex;\n\tprivate final String predicate;\n\n\tpublic FailedPredicateException(Parser recognizer) {\n\t\tthis(recognizer, null);\n\t}\n\n\tpublic FailedPredicateException(Parser recognizer, String predicate) {\n\t\tthis(recognizer, predicate, null);\n\t}\n\n\tpublic FailedPredicateException(Parser recognizer,\n\t\t\t\t\t\t\t\t\tString predicate,\n\t\t\t\t\t\t\t\t\tString message)\n\t{\n\t\tsuper(formatMessage(predicate, message), recognizer, recognizer.getInputStream(), recognizer._ctx);\n\t\tATNState s = recognizer.getInterpreter().atn.states.get(recognizer.getState());\n\n\t\tAbstractPredicateTransition trans = (AbstractPredicateTransition)s.transition(0);\n\t\tif (trans instanceof PredicateTransition) {\n\t\t\tthis.ruleIndex = ((PredicateTransition)trans).ruleIndex;\n\t\t\tthis.predicateIndex = ((PredicateTransition)trans).predIndex;\n\t\t}\n\t\telse {\n\t\t\tthis.ruleIndex = 0;\n\t\t\tthis.predicateIndex = 0;\n\t\t}\n\n\t\tthis.predicate = predicate;\n\t\tthis.setOffendingToken(recognizer.getCurrentToken());\n\t}\n\n\tpublic int getRuleIndex() {\n\t\treturn ruleIndex;\n\t}\n\n\tpublic int getPredIndex() {\n\t\treturn predicateIndex;\n\t}\n\n\n\tpublic String getPredicate() {\n\t\treturn predicate;\n\t}\n\n\n\tprivate static String formatMessage(String predicate, String message) {\n\t\tif (message != null) {\n\t\t\treturn message;\n\t\t}\n\n\t\treturn String.format(Locale.getDefault(), \"failed predicate: {%s}?\", predicate);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/InputMismatchException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\n/** This signifies any kind of mismatched input exceptions such as\n *  when the current input does not match the expected token.\n */\npublic class InputMismatchException extends RecognitionException {\n\tpublic InputMismatchException(Parser recognizer) {\n\t\tsuper(recognizer, recognizer.getInputStream(), recognizer._ctx);\n\t\tthis.setOffendingToken(recognizer.getCurrentToken());\n\t}\n\n\tpublic InputMismatchException(Parser recognizer, int state, ParserRuleContext ctx) {\n\t\tsuper(recognizer, recognizer.getInputStream(), ctx);\n\t\tthis.setOffendingState(state);\n\t\tthis.setOffendingToken(recognizer.getCurrentToken());\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/IntStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\n/**\n * A simple stream of symbols whose values are represented as integers. This\n * interface provides <em>marked ranges</em> with support for a minimum level\n * of buffering necessary to implement arbitrary lookahead during prediction.\n * For more information on marked ranges, see {@link #mark}.\n *\n * <p><strong>Initializing Methods:</strong> Some methods in this interface have\n * unspecified behavior if no call to an initializing method has occurred after\n * the stream was constructed. The following is a list of initializing methods:</p>\n *\n * <ul>\n *   <li>{@link #LA}</li>\n *   <li>{@link #consume}</li>\n *   <li>{@link #size}</li>\n * </ul>\n */\npublic interface IntStream {\n\t/**\n\t * The value returned by {@link #LA LA()} when the end of the stream is\n\t * reached.\n\t */\n\tpublic static final int EOF = -1;\n\n\t/**\n\t * The value returned by {@link #getSourceName} when the actual name of the\n\t * underlying source is not known.\n\t */\n\tpublic static final String UNKNOWN_SOURCE_NAME = \"<unknown>\";\n\n\t/**\n\t * Consumes the current symbol in the stream. This method has the following\n\t * effects:\n\t *\n\t * <ul>\n\t *   <li><strong>Forward movement:</strong> The value of {@link #index index()}\n\t *\t\tbefore calling this method is less than the value of {@code index()}\n\t *\t\tafter calling this method.</li>\n\t *   <li><strong>Ordered lookahead:</strong> The value of {@code LA(1)} before\n\t *\t\tcalling this method becomes the value of {@code LA(-1)} after calling\n\t *\t\tthis method.</li>\n\t * </ul>\n\t *\n\t * Note that calling this method does not guarantee that {@code index()} is\n\t * incremented by exactly 1, as that would preclude the ability to implement\n\t * filtering streams (e.g. {@link CommonTokenStream} which distinguishes\n\t * between \"on-channel\" and \"off-channel\" tokens).\n\t *\n\t * @throws IllegalStateException if an attempt is made to consume the\n\t * end of the stream (i.e. if {@code LA(1)==}{@link #EOF EOF} before calling\n\t * {@code consume}).\n\t */\n\tvoid consume();\n\n\t/**\n\t * Gets the value of the symbol at offset {@code i} from the current\n\t * position. When {@code i==1}, this method returns the value of the current\n\t * symbol in the stream (which is the next symbol to be consumed). When\n\t * {@code i==-1}, this method returns the value of the previously read\n\t * symbol in the stream. It is not valid to call this method with\n\t * {@code i==0}, but the specific behavior is unspecified because this\n\t * method is frequently called from performance-critical code.\n\t *\n\t * <p>This method is guaranteed to succeed if any of the following are true:</p>\n\t *\n\t * <ul>\n\t *   <li>{@code i>0}</li>\n\t *   <li>{@code i==-1} and {@link #index index()} returns a value greater\n\t *     than the value of {@code index()} after the stream was constructed\n\t *     and {@code LA(1)} was called in that order. Specifying the current\n\t *     {@code index()} relative to the index after the stream was created\n\t *     allows for filtering implementations that do not return every symbol\n\t *     from the underlying source. Specifying the call to {@code LA(1)}\n\t *     allows for lazily initialized streams.</li>\n\t *   <li>{@code LA(i)} refers to a symbol consumed within a marked region\n\t *     that has not yet been released.</li>\n\t * </ul>\n\t *\n\t * <p>If {@code i} represents a position at or beyond the end of the stream,\n\t * this method returns {@link #EOF}.</p>\n\t *\n\t * <p>The return value is unspecified if {@code i<0} and fewer than {@code -i}\n\t * calls to {@link #consume consume()} have occurred from the beginning of\n\t * the stream before calling this method.</p>\n\t *\n\t * @throws UnsupportedOperationException if the stream does not support\n\t * retrieving the value of the specified symbol\n\t */\n\tint LA(int i);\n\n\t/**\n\t * A mark provides a guarantee that {@link #seek seek()} operations will be\n\t * valid over a \"marked range\" extending from the index where {@code mark()}\n\t * was called to the current {@link #index index()}. This allows the use of\n\t * streaming input sources by specifying the minimum buffering requirements\n\t * to support arbitrary lookahead during prediction.\n\t *\n\t * <p>The returned mark is an opaque handle (type {@code int}) which is passed\n\t * to {@link #release release()} when the guarantees provided by the marked\n\t * range are no longer necessary. When calls to\n\t * {@code mark()}/{@code release()} are nested, the marks must be released\n\t * in reverse order of which they were obtained. Since marked regions are\n\t * used during performance-critical sections of prediction, the specific\n\t * behavior of invalid usage is unspecified (i.e. a mark is not released, or\n\t * a mark is released twice, or marks are not released in reverse order from\n\t * which they were created).</p>\n\t *\n\t * <p>The behavior of this method is unspecified if no call to an\n\t * {@link IntStream initializing method} has occurred after this stream was\n\t * constructed.</p>\n\t *\n\t * <p>This method does not change the current position in the input stream.</p>\n\t *\n\t * <p>The following example shows the use of {@link #mark mark()},\n\t * {@link #release release(mark)}, {@link #index index()}, and\n\t * {@link #seek seek(index)} as part of an operation to safely work within a\n\t * marked region, then restore the stream position to its original value and\n\t * release the mark.</p>\n\t * <pre>\n\t * IntStream stream = ...;\n\t * int index = -1;\n\t * int mark = stream.mark();\n\t * try {\n\t *   index = stream.index();\n\t *   // perform work here...\n\t * } finally {\n\t *   if (index != -1) {\n\t *     stream.seek(index);\n\t *   }\n\t *   stream.release(mark);\n\t * }\n\t * </pre>\n\t *\n\t * @return An opaque marker which should be passed to\n\t * {@link #release release()} when the marked range is no longer required.\n\t */\n\tint mark();\n\n\t/**\n\t * This method releases a marked range created by a call to\n\t * {@link #mark mark()}. Calls to {@code release()} must appear in the\n\t * reverse order of the corresponding calls to {@code mark()}. If a mark is\n\t * released twice, or if marks are not released in reverse order of the\n\t * corresponding calls to {@code mark()}, the behavior is unspecified.\n\t *\n\t * <p>For more information and an example, see {@link #mark}.</p>\n\t *\n\t * @param marker A marker returned by a call to {@code mark()}.\n\t * @see #mark\n\t */\n\tvoid release(int marker);\n\n\t/**\n\t * Return the index into the stream of the input symbol referred to by\n\t * {@code LA(1)}.\n\t *\n\t * <p>The behavior of this method is unspecified if no call to an\n\t * {@link IntStream initializing method} has occurred after this stream was\n\t * constructed.</p>\n\t */\n\tint index();\n\n\t/**\n\t * Set the input cursor to the position indicated by {@code index}. If the\n\t * specified index lies past the end of the stream, the operation behaves as\n\t * though {@code index} was the index of the EOF symbol. After this method\n\t * returns without throwing an exception, then at least one of the following\n\t * will be true.\n\t *\n\t * <ul>\n\t *   <li>{@link #index index()} will return the index of the first symbol\n\t *     appearing at or after the specified {@code index}. Specifically,\n\t *     implementations which filter their sources should automatically\n\t *     adjust {@code index} forward the minimum amount required for the\n\t *     operation to target a non-ignored symbol.</li>\n\t *   <li>{@code LA(1)} returns {@link #EOF}</li>\n\t * </ul>\n\t *\n\t * This operation is guaranteed to not throw an exception if {@code index}\n\t * lies within a marked region. For more information on marked regions, see\n\t * {@link #mark}. The behavior of this method is unspecified if no call to\n\t * an {@link IntStream initializing method} has occurred after this stream\n\t * was constructed.\n\t *\n\t * @param index The absolute index to seek to.\n\t *\n\t * @throws IllegalArgumentException if {@code index} is less than 0\n\t * @throws UnsupportedOperationException if the stream does not support\n\t * seeking to the specified index\n\t */\n\tvoid seek(int index);\n\n\t/**\n\t * Returns the total number of symbols in the stream, including a single EOF\n\t * symbol.\n\t *\n\t * @throws UnsupportedOperationException if the size of the stream is\n\t * unknown.\n\t */\n\tint size();\n\n\t/**\n\t * Gets the name of the underlying symbol source. This method returns a\n\t * non-null, non-empty string. If such a name is not known, this method\n\t * returns {@link #UNKNOWN_SOURCE_NAME}.\n\t */\n\n\tpublic String getSourceName();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/InterpreterRuleContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\n/**\n * This class extends {@link ParserRuleContext} by allowing the value of\n * {@link #getRuleIndex} to be explicitly set for the context.\n *\n * <p>\n * {@link ParserRuleContext} does not include field storage for the rule index\n * since the context classes created by the code generator override the\n * {@link #getRuleIndex} method to return the correct value for that context.\n * Since the parser interpreter does not use the context classes generated for a\n * parser, this class (with slightly more memory overhead per node) is used to\n * provide equivalent functionality.</p>\n */\npublic class InterpreterRuleContext extends ParserRuleContext {\n\t/** This is the backing field for {@link #getRuleIndex}. */\n\tprotected int ruleIndex = -1;\n\n\tpublic InterpreterRuleContext() { }\n\n\t/**\n\t * Constructs a new {@link InterpreterRuleContext} with the specified\n\t * parent, invoking state, and rule index.\n\t *\n\t * @param parent The parent context.\n\t * @param invokingStateNumber The invoking state number.\n\t * @param ruleIndex The rule index for the current context.\n\t */\n\tpublic InterpreterRuleContext(ParserRuleContext parent,\n\t\t\t\t\t\t\t\t  int invokingStateNumber,\n\t\t\t\t\t\t\t\t  int ruleIndex)\n\t{\n\t\tsuper(parent, invokingStateNumber);\n\t\tthis.ruleIndex = ruleIndex;\n\t}\n\n\t@Override\n\tpublic int getRuleIndex() {\n\t\treturn ruleIndex;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/Lexer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.LexerATNSimulator;\nimport org.antlr.v4.runtime.misc.IntegerStack;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.util.ArrayList;\nimport java.util.EmptyStackException;\nimport java.util.List;\n\n/** A lexer is recognizer that draws input symbols from a character stream.\n *  lexer grammars result in a subclass of this object. A Lexer object\n *  uses simplified match() and error recovery mechanisms in the interest\n *  of speed.\n */\npublic abstract class Lexer extends Recognizer<Integer, LexerATNSimulator>\n\timplements TokenSource\n{\n\tpublic static final int DEFAULT_MODE = 0;\n\tpublic static final int MORE = -2;\n\tpublic static final int SKIP = -3;\n\n\tpublic static final int DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL;\n\tpublic static final int HIDDEN = Token.HIDDEN_CHANNEL;\n\tpublic static final int MIN_CHAR_VALUE = 0x0000;\n\tpublic static final int MAX_CHAR_VALUE = 0x10FFFF;\n\n\tpublic CharStream _input;\n\tprotected Pair<TokenSource, CharStream> _tokenFactorySourcePair;\n\n\t/** How to create token objects */\n\tprotected TokenFactory<?> _factory = CommonTokenFactory.DEFAULT;\n\n\t/** The goal of all lexer rules/methods is to create a token object.\n\t *  This is an instance variable as multiple rules may collaborate to\n\t *  create a single token.  nextToken will return this object after\n\t *  matching lexer rule(s).  If you subclass to allow multiple token\n\t *  emissions, then set this to the last token to be matched or\n\t *  something nonnull so that the auto token emit mechanism will not\n\t *  emit another token.\n\t */\n\tpublic Token _token;\n\n\t/** What character index in the stream did the current token start at?\n\t *  Needed, for example, to get the text for current token.  Set at\n\t *  the start of nextToken.\n\t */\n\tpublic int _tokenStartCharIndex = -1;\n\n\t/** The line on which the first character of the token resides */\n\tpublic int _tokenStartLine;\n\n\t/** The character position of first character within the line */\n\tpublic int _tokenStartCharPositionInLine;\n\n\t/** Once we see EOF on char stream, next token will be EOF.\n\t *  If you have DONE : EOF ; then you see DONE EOF.\n\t */\n\tpublic boolean _hitEOF;\n\n\t/** The channel number for the current token */\n\tpublic int _channel;\n\n\t/** The token type for the current token */\n\tpublic int _type;\n\n\tpublic final IntegerStack _modeStack = new IntegerStack();\n\tpublic int _mode = Lexer.DEFAULT_MODE;\n\n\t/** You can set the text for the current token to override what is in\n\t *  the input char buffer.  Use setText() or can set this instance var.\n\t */\n\tpublic String _text;\n\n\tpublic Lexer() { }\n\n\tpublic Lexer(CharStream input) {\n\t\tthis._input = input;\n\t\tthis._tokenFactorySourcePair = new Pair<TokenSource, CharStream>(this, input);\n\t}\n\n\tpublic void reset() {\n\t\t// wack Lexer state variables\n\t\tif ( _input !=null ) {\n\t\t\t_input.seek(0); // rewind the input\n\t\t}\n\t\t_token = null;\n\t\t_type = Token.INVALID_TYPE;\n\t\t_channel = Token.DEFAULT_CHANNEL;\n\t\t_tokenStartCharIndex = -1;\n\t\t_tokenStartCharPositionInLine = -1;\n\t\t_tokenStartLine = -1;\n\t\t_text = null;\n\n\t\t_hitEOF = false;\n\t\t_mode = Lexer.DEFAULT_MODE;\n\t\t_modeStack.clear();\n\n\t\tgetInterpreter().reset();\n\t}\n\n\t/** Return a token from this source; i.e., match a token on the char\n\t *  stream.\n\t */\n\t@Override\n\tpublic Token nextToken() {\n\t\tif (_input == null) {\n\t\t\tthrow new IllegalStateException(\"nextToken requires a non-null input stream.\");\n\t\t}\n\n\t\t// Mark start location in char stream so unbuffered streams are\n\t\t// guaranteed at least have text of current token\n\t\tint tokenStartMarker = _input.mark();\n\t\ttry{\n\t\t\touter:\n\t\t\twhile (true) {\n\t\t\t\tif (_hitEOF) {\n\t\t\t\t\temitEOF();\n\t\t\t\t\treturn _token;\n\t\t\t\t}\n\n\t\t\t\t_token = null;\n\t\t\t\t_channel = Token.DEFAULT_CHANNEL;\n\t\t\t\t_tokenStartCharIndex = _input.index();\n\t\t\t\t_tokenStartCharPositionInLine = getInterpreter().getCharPositionInLine();\n\t\t\t\t_tokenStartLine = getInterpreter().getLine();\n\t\t\t\t_text = null;\n\t\t\t\tdo {\n\t\t\t\t\t_type = Token.INVALID_TYPE;\n//\t\t\t\tSystem.out.println(\"nextToken line \"+tokenStartLine+\" at \"+((char)input.LA(1))+\n//\t\t\t\t\t\t\t\t   \" in mode \"+mode+\n//\t\t\t\t\t\t\t\t   \" at index \"+input.index());\n\t\t\t\t\tint ttype;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tttype = getInterpreter().match(_input, _mode);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (LexerNoViableAltException e) {\n\t\t\t\t\t\tnotifyListeners(e);\t\t// report error\n\t\t\t\t\t\trecover(e);\n\t\t\t\t\t\tttype = SKIP;\n\t\t\t\t\t}\n\t\t\t\t\tif ( _input.LA(1)==IntStream.EOF ) {\n\t\t\t\t\t\t_hitEOF = true;\n\t\t\t\t\t}\n\t\t\t\t\tif ( _type == Token.INVALID_TYPE ) _type = ttype;\n\t\t\t\t\tif ( _type ==SKIP ) {\n\t\t\t\t\t\tcontinue outer;\n\t\t\t\t\t}\n\t\t\t\t} while ( _type ==MORE );\n\t\t\t\tif ( _token == null ) emit();\n\t\t\t\treturn _token;\n\t\t\t}\n\t\t}\n\t\tfinally {\n\t\t\t// make sure we release marker after match or\n\t\t\t// unbuffered char stream will keep buffering\n\t\t\t_input.release(tokenStartMarker);\n\t\t}\n\t}\n\n\t/** Instruct the lexer to skip creating a token for current lexer rule\n\t *  and look for another token.  nextToken() knows to keep looking when\n\t *  a lexer rule finishes with token set to SKIP_TOKEN.  Recall that\n\t *  if token==null at end of any token rule, it creates one for you\n\t *  and emits it.\n\t */\n\tpublic void skip() {\n\t\t_type = SKIP;\n\t}\n\n\tpublic void more() {\n\t\t_type = MORE;\n\t}\n\n\tpublic void mode(int m) {\n\t\t_mode = m;\n\t}\n\n\tpublic void pushMode(int m) {\n\t\tif ( LexerATNSimulator.debug ) System.out.println(\"pushMode \"+m);\n\t\t_modeStack.push(_mode);\n\t\tmode(m);\n\t}\n\n\tpublic int popMode() {\n\t\tif ( _modeStack.isEmpty() ) throw new EmptyStackException();\n\t\tif ( LexerATNSimulator.debug ) System.out.println(\"popMode back to \"+ _modeStack.peek());\n\t\tmode( _modeStack.pop() );\n\t\treturn _mode;\n\t}\n\n\t@Override\n\tpublic void setTokenFactory(TokenFactory<?> factory) {\n\t\tthis._factory = factory;\n\t}\n\n\t@Override\n\tpublic TokenFactory<? extends Token> getTokenFactory() {\n\t\treturn _factory;\n\t}\n\n\t/** Set the char stream and reset the lexer */\n\t@Override\n\tpublic void setInputStream(IntStream input) {\n\t\tthis._input = null;\n\t\tthis._tokenFactorySourcePair = new Pair<TokenSource, CharStream>(this, _input);\n\t\treset();\n\t\tthis._input = (CharStream)input;\n\t\tthis._tokenFactorySourcePair = new Pair<TokenSource, CharStream>(this, _input);\n\t}\n\n\t@Override\n\tpublic String getSourceName() {\n\t\treturn _input.getSourceName();\n\t}\n\n\t@Override\n\tpublic CharStream getInputStream() {\n\t\treturn _input;\n\t}\n\n\t/** By default does not support multiple emits per nextToken invocation\n\t *  for efficiency reasons.  Subclass and override this method, nextToken,\n\t *  and getToken (to push tokens into a list and pull from that list\n\t *  rather than a single variable as this implementation does).\n\t */\n\tpublic void emit(Token token) {\n\t\t//System.err.println(\"emit \"+token);\n\t\tthis._token = token;\n\t}\n\n\t/** The standard method called to automatically emit a token at the\n\t *  outermost lexical rule.  The token object should point into the\n\t *  char buffer start..stop.  If there is a text override in 'text',\n\t *  use that to set the token's text.  Override this method to emit\n\t *  custom Token objects or provide a new factory.\n\t */\n\tpublic Token emit() {\n\t\tToken t = _factory.create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, getCharIndex()-1,\n\t\t\t\t\t\t\t\t  _tokenStartLine, _tokenStartCharPositionInLine);\n\t\temit(t);\n\t\treturn t;\n\t}\n\n\tpublic Token emitEOF() {\n\t\tint cpos = getCharPositionInLine();\n\t\tint line = getLine();\n\t\tToken eof = _factory.create(_tokenFactorySourcePair, Token.EOF, null, Token.DEFAULT_CHANNEL, _input.index(), _input.index()-1,\n\t\t\t\t\t\t\t\t\tline, cpos);\n\t\temit(eof);\n\t\treturn eof;\n\t}\n\n\t@Override\n\tpublic int getLine() {\n\t\treturn getInterpreter().getLine();\n\t}\n\n\t@Override\n\tpublic int getCharPositionInLine() {\n\t\treturn getInterpreter().getCharPositionInLine();\n\t}\n\n\tpublic void setLine(int line) {\n\t\tgetInterpreter().setLine(line);\n\t}\n\n\tpublic void setCharPositionInLine(int charPositionInLine) {\n\t\tgetInterpreter().setCharPositionInLine(charPositionInLine);\n\t}\n\n\t/** What is the index of the current character of lookahead? */\n\tpublic int getCharIndex() {\n\t\treturn _input.index();\n\t}\n\n\t/** Return the text matched so far for the current token or any\n\t *  text override.\n\t */\n\tpublic String getText() {\n\t\tif ( _text !=null ) {\n\t\t\treturn _text;\n\t\t}\n\t\treturn getInterpreter().getText(_input);\n\t}\n\n\t/** Set the complete text of this token; it wipes any previous\n\t *  changes to the text.\n\t */\n\tpublic void setText(String text) {\n\t\tthis._text = text;\n\t}\n\n\t/** Override if emitting multiple tokens. */\n\tpublic Token getToken() { return _token; }\n\n\tpublic void setToken(Token _token) {\n\t\tthis._token = _token;\n\t}\n\n\tpublic void setType(int ttype) {\n\t\t_type = ttype;\n\t}\n\n\tpublic int getType() {\n\t\treturn _type;\n\t}\n\n\tpublic void setChannel(int channel) {\n\t\t_channel = channel;\n\t}\n\n\tpublic int getChannel() {\n\t\treturn _channel;\n\t}\n\n\tpublic String[] getChannelNames() { return null; }\n\n\tpublic String[] getModeNames() {\n\t\treturn null;\n\t}\n\n\t/** Used to print out token names like ID during debugging and\n\t *  error reporting.  The generated parsers implement a method\n\t *  that overrides this to point to their String[] tokenNames.\n\t */\n\t@Override\n\t@Deprecated\n\tpublic String[] getTokenNames() {\n\t\treturn null;\n\t}\n\n\t/** Return a list of all Token objects in input char stream.\n\t *  Forces load of all tokens. Does not include EOF token.\n\t */\n\tpublic List<? extends Token> getAllTokens() {\n\t\tList<Token> tokens = new ArrayList<Token>();\n\t\tToken t = nextToken();\n\t\twhile ( t.getType()!=Token.EOF ) {\n\t\t\ttokens.add(t);\n\t\t\tt = nextToken();\n\t\t}\n\t\treturn tokens;\n\t}\n\n\tpublic void recover(LexerNoViableAltException e) {\n\t\tif (_input.LA(1) != IntStream.EOF) {\n\t\t\t// skip a char and try again\n\t\t\tgetInterpreter().consume(_input);\n\t\t}\n\t}\n\n\tpublic void notifyListeners(LexerNoViableAltException e) {\n\t\tString text = _input.getText(Interval.of(_tokenStartCharIndex, _input.index()));\n\t\tString msg = \"token recognition error at: '\"+ getErrorDisplay(text) + \"'\";\n\n\t\tANTLRErrorListener listener = getErrorListenerDispatch();\n\t\tlistener.syntaxError(this, null, _tokenStartLine, _tokenStartCharPositionInLine, msg, e);\n\t}\n\n\tpublic String getErrorDisplay(String s) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (char c : s.toCharArray()) {\n\t\t\tbuf.append(getErrorDisplay(c));\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic String getErrorDisplay(int c) {\n\t\tString s = String.valueOf((char)c);\n\t\tswitch ( c ) {\n\t\t\tcase Token.EOF :\n\t\t\t\ts = \"<EOF>\";\n\t\t\t\tbreak;\n\t\t\tcase '\\n' :\n\t\t\t\ts = \"\\\\n\";\n\t\t\t\tbreak;\n\t\t\tcase '\\t' :\n\t\t\t\ts = \"\\\\t\";\n\t\t\t\tbreak;\n\t\t\tcase '\\r' :\n\t\t\t\ts = \"\\\\r\";\n\t\t\t\tbreak;\n\t\t}\n\t\treturn s;\n\t}\n\n\tpublic String getCharErrorDisplay(int c) {\n\t\tString s = getErrorDisplay(c);\n\t\treturn \"'\"+s+\"'\";\n\t}\n\n\t/** Lexers can normally match any char in it's vocabulary after matching\n\t *  a token, so do the easy thing and just kill a character and hope\n\t *  it all works out.  You can instead use the rule invocation stack\n\t *  to do sophisticated error recovery if you are in a fragment rule.\n\t */\n\tpublic void recover(RecognitionException re) {\n\t\t//System.out.println(\"consuming char \"+(char)input.LA(1)+\" during recovery\");\n\t\t//re.printStackTrace();\n\t\t// TODO: Do we lose character or line position information?\n\t\t_input.consume();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/LexerInterpreter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNType;\nimport org.antlr.v4.runtime.atn.LexerATNSimulator;\nimport org.antlr.v4.runtime.atn.PredictionContextCache;\nimport org.antlr.v4.runtime.dfa.DFA;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\npublic class LexerInterpreter extends Lexer {\n\tprotected final String grammarFileName;\n\tprotected final ATN atn;\n\n\t@Deprecated\n\tprotected final String[] tokenNames;\n\tprotected final String[] ruleNames;\n\tprotected final String[] channelNames;\n\tprotected final String[] modeNames;\n\n\n\tprivate final Vocabulary vocabulary;\n\n\tprotected final DFA[] _decisionToDFA;\n\tprotected final PredictionContextCache _sharedContextCache =\n\t\tnew PredictionContextCache();\n\n\t@Deprecated\n\tpublic LexerInterpreter(String grammarFileName, Collection<String> tokenNames, Collection<String> ruleNames, Collection<String> modeNames, ATN atn, CharStream input) {\n\t\tthis(grammarFileName, VocabularyImpl.fromTokenNames(tokenNames.toArray(new String[0])), ruleNames, new ArrayList<String>(), modeNames, atn, input);\n\t}\n\n\t@Deprecated\n\tpublic LexerInterpreter(String grammarFileName, Vocabulary vocabulary, Collection<String> ruleNames, Collection<String> modeNames, ATN atn, CharStream input) {\n\t\tthis(grammarFileName, vocabulary, ruleNames, new ArrayList<String>(), modeNames, atn, input);\n\t}\n\n\tpublic LexerInterpreter(String grammarFileName, Vocabulary vocabulary, Collection<String> ruleNames, Collection<String> channelNames, Collection<String> modeNames, ATN atn, CharStream input) {\n\t\tsuper(input);\n\n\t\tif (atn.grammarType != ATNType.LEXER) {\n\t\t\tthrow new IllegalArgumentException(\"The ATN must be a lexer ATN.\");\n\t\t}\n\n\t\tthis.grammarFileName = grammarFileName;\n\t\tthis.atn = atn;\n\t\tthis.tokenNames = new String[atn.maxTokenType];\n\t\tfor (int i = 0; i < tokenNames.length; i++) {\n\t\t\ttokenNames[i] = vocabulary.getDisplayName(i);\n\t\t}\n\n\t\tthis.ruleNames = ruleNames.toArray(new String[0]);\n\t\tthis.channelNames = channelNames.toArray(new String[0]);\n\t\tthis.modeNames = modeNames.toArray(new String[0]);\n\t\tthis.vocabulary = vocabulary;\n\n\t\tthis._decisionToDFA = new DFA[atn.getNumberOfDecisions()];\n\t\tfor (int i = 0; i < _decisionToDFA.length; i++) {\n\t\t\t_decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);\n\t\t}\n\t\tthis._interp = new LexerATNSimulator(this,atn,_decisionToDFA,_sharedContextCache);\n\t}\n\n\t@Override\n\tpublic ATN getATN() {\n\t\treturn atn;\n\t}\n\n\t@Override\n\tpublic String getGrammarFileName() {\n\t\treturn grammarFileName;\n\t}\n\n\t@Override\n\t@Deprecated\n\tpublic String[] getTokenNames() {\n\t\treturn tokenNames;\n\t}\n\n\t@Override\n\tpublic String[] getRuleNames() {\n\t\treturn ruleNames;\n\t}\n\n\t@Override\n\tpublic String[] getChannelNames() {\n\t\treturn channelNames;\n\t}\n\n\t@Override\n\tpublic String[] getModeNames() {\n\t\treturn modeNames;\n\t}\n\n\t@Override\n\tpublic Vocabulary getVocabulary() {\n\t\tif (vocabulary != null) {\n\t\t\treturn vocabulary;\n\t\t}\n\n\t\treturn super.getVocabulary();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/LexerNoViableAltException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.Utils;\n\nimport java.util.Locale;\n\npublic class LexerNoViableAltException extends RecognitionException {\n\t/** Matching attempted at what input index? */\n\tprivate final int startIndex;\n\n\t/** Which configurations did we try at input.index() that couldn't match input.LA(1)? */\n\tprivate final ATNConfigSet deadEndConfigs;\n\n\tpublic LexerNoViableAltException(Lexer lexer,\n\t\t\t\t\t\t\t\t\t CharStream input,\n\t\t\t\t\t\t\t\t\t int startIndex,\n\t\t\t\t\t\t\t\t\t ATNConfigSet deadEndConfigs) {\n\t\tsuper(lexer, input, null);\n\t\tthis.startIndex = startIndex;\n\t\tthis.deadEndConfigs = deadEndConfigs;\n\t}\n\n\tpublic int getStartIndex() {\n\t\treturn startIndex;\n\t}\n\n\n\tpublic ATNConfigSet getDeadEndConfigs() {\n\t\treturn deadEndConfigs;\n\t}\n\n\t@Override\n\tpublic CharStream getInputStream() {\n\t\treturn (CharStream)super.getInputStream();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString symbol = \"\";\n\t\tif (startIndex >= 0 && startIndex < getInputStream().size()) {\n\t\t\tsymbol = getInputStream().getText(Interval.of(startIndex,startIndex));\n\t\t\tsymbol = Utils.escapeWhitespace(symbol, false);\n\t\t}\n\n\t\treturn String.format(Locale.getDefault(), \"%s('%s')\", LexerNoViableAltException.class.getSimpleName(), symbol);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ListTokenSource.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.util.List;\n\n/**\n * Provides an implementation of {@link TokenSource} as a wrapper around a list\n * of {@link Token} objects.\n *\n * <p>If the final token in the list is an {@link Token#EOF} token, it will be used\n * as the EOF token for every call to {@link #nextToken} after the end of the\n * list is reached. Otherwise, an EOF token will be created.</p>\n */\npublic class ListTokenSource implements TokenSource {\n\t/**\n\t * The wrapped collection of {@link Token} objects to return.\n\t */\n\tprotected final List<? extends Token> tokens;\n\n\t/**\n\t * The name of the input source. If this value is {@code null}, a call to\n\t * {@link #getSourceName} should return the source name used to create the\n\t * the next token in {@link #tokens} (or the previous token if the end of\n\t * the input has been reached).\n\t */\n\tprivate final String sourceName;\n\n\t/**\n\t * The index into {@link #tokens} of token to return by the next call to\n\t * {@link #nextToken}. The end of the input is indicated by this value\n\t * being greater than or equal to the number of items in {@link #tokens}.\n\t */\n\tprotected int i;\n\n\t/**\n\t * This field caches the EOF token for the token source.\n\t */\n\tprotected Token eofToken;\n\n\t/**\n\t * This is the backing field for {@link #getTokenFactory} and\n\t * {@link setTokenFactory}.\n\t */\n\tprivate TokenFactory<?> _factory = CommonTokenFactory.DEFAULT;\n\n\t/**\n\t * Constructs a new {@link ListTokenSource} instance from the specified\n\t * collection of {@link Token} objects.\n\t *\n\t * @param tokens The collection of {@link Token} objects to provide as a\n\t * {@link TokenSource}.\n\t * @exception NullPointerException if {@code tokens} is {@code null}\n\t */\n\tpublic ListTokenSource(List<? extends Token> tokens) {\n\t\tthis(tokens, null);\n\t}\n\n\t/**\n\t * Constructs a new {@link ListTokenSource} instance from the specified\n\t * collection of {@link Token} objects and source name.\n\t *\n\t * @param tokens The collection of {@link Token} objects to provide as a\n\t * {@link TokenSource}.\n\t * @param sourceName The name of the {@link TokenSource}. If this value is\n\t * {@code null}, {@link #getSourceName} will attempt to infer the name from\n\t * the next {@link Token} (or the previous token if the end of the input has\n\t * been reached).\n\t *\n\t * @exception NullPointerException if {@code tokens} is {@code null}\n\t */\n\tpublic ListTokenSource(List<? extends Token> tokens, String sourceName) {\n\t\tif (tokens == null) {\n\t\t\tthrow new NullPointerException(\"tokens cannot be null\");\n\t\t}\n\n\t\tthis.tokens = tokens;\n\t\tthis.sourceName = sourceName;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic int getCharPositionInLine() {\n\t\tif (i < tokens.size()) {\n\t\t\treturn tokens.get(i).getCharPositionInLine();\n\t\t}\n\t\telse if (eofToken != null) {\n\t\t\treturn eofToken.getCharPositionInLine();\n\t\t}\n\t\telse if (tokens.size() > 0) {\n\t\t\t// have to calculate the result from the line/column of the previous\n\t\t\t// token, along with the text of the token.\n\t\t\tToken lastToken = tokens.get(tokens.size() - 1);\n\t\t\tString tokenText = lastToken.getText();\n\t\t\tif (tokenText != null) {\n\t\t\t\tint lastNewLine = tokenText.lastIndexOf('\\n');\n\t\t\t\tif (lastNewLine >= 0) {\n\t\t\t\t\treturn tokenText.length() - lastNewLine - 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn lastToken.getCharPositionInLine() + lastToken.getStopIndex() - lastToken.getStartIndex() + 1;\n\t\t}\n\n\t\t// only reach this if tokens is empty, meaning EOF occurs at the first\n\t\t// position in the input\n\t\treturn 0;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Token nextToken() {\n\t\tif (i >= tokens.size()) {\n\t\t\tif (eofToken == null) {\n\t\t\t\tint start = -1;\n\t\t\t\tif (tokens.size() > 0) {\n\t\t\t\t\tint previousStop = tokens.get(tokens.size() - 1).getStopIndex();\n\t\t\t\t\tif (previousStop != -1) {\n\t\t\t\t\t\tstart = previousStop + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tint stop = Math.max(-1, start - 1);\n\t\t\t\teofToken = _factory.create(new Pair<TokenSource, CharStream>(this, getInputStream()), Token.EOF, \"EOF\", Token.DEFAULT_CHANNEL, start, stop, getLine(), getCharPositionInLine());\n\t\t\t}\n\n\t\t\treturn eofToken;\n\t\t}\n\n\t\tToken t = tokens.get(i);\n\t\tif (i == tokens.size() - 1 && t.getType() == Token.EOF) {\n\t\t\teofToken = t;\n\t\t}\n\n\t\ti++;\n\t\treturn t;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic int getLine() {\n\t\tif (i < tokens.size()) {\n\t\t\treturn tokens.get(i).getLine();\n\t\t}\n\t\telse if (eofToken != null) {\n\t\t\treturn eofToken.getLine();\n\t\t}\n\t\telse if (tokens.size() > 0) {\n\t\t\t// have to calculate the result from the line/column of the previous\n\t\t\t// token, along with the text of the token.\n\t\t\tToken lastToken = tokens.get(tokens.size() - 1);\n\t\t\tint line = lastToken.getLine();\n\n\t\t\tString tokenText = lastToken.getText();\n\t\t\tif (tokenText != null) {\n\t\t\t\tfor (int i = 0; i < tokenText.length(); i++) {\n\t\t\t\t\tif (tokenText.charAt(i) == '\\n') {\n\t\t\t\t\t\tline++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if no text is available, assume the token did not contain any newline characters.\n\t\t\treturn line;\n\t\t}\n\n\t\t// only reach this if tokens is empty, meaning EOF occurs at the first\n\t\t// position in the input\n\t\treturn 1;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic CharStream getInputStream() {\n\t\tif (i < tokens.size()) {\n\t\t\treturn tokens.get(i).getInputStream();\n\t\t}\n\t\telse if (eofToken != null) {\n\t\t\treturn eofToken.getInputStream();\n\t\t}\n\t\telse if (tokens.size() > 0) {\n\t\t\treturn tokens.get(tokens.size() - 1).getInputStream();\n\t\t}\n\n\t\t// no input stream information is available\n\t\treturn null;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic String getSourceName() {\n\t\tif (sourceName != null) {\n\t\t\treturn sourceName;\n\t\t}\n\n\t\tCharStream inputStream = getInputStream();\n\t\tif (inputStream != null) {\n\t\t\treturn inputStream.getSourceName();\n\t\t}\n\n\t\treturn \"List\";\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic void setTokenFactory(TokenFactory<?> factory) {\n\t\tthis._factory = factory;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic TokenFactory<?> getTokenFactory() {\n\t\treturn _factory;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/NoViableAltException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\n\n/** Indicates that the parser could not decide which of two or more paths\n *  to take based upon the remaining input. It tracks the starting token\n *  of the offending input and also knows where the parser was\n *  in the various paths when the error. Reported by reportNoViableAlternative()\n */\npublic class NoViableAltException extends RecognitionException {\n\t/** Which configurations did we try at input.index() that couldn't match input.LT(1)? */\n\n\tprivate final ATNConfigSet deadEndConfigs;\n\n\t/** The token object at the start index; the input stream might\n\t * \tnot be buffering tokens so get a reference to it. (At the\n\t *  time the error occurred, of course the stream needs to keep a\n\t *  buffer all of the tokens but later we might not have access to those.)\n\t */\n\n\tprivate final Token startToken;\n\n\tpublic NoViableAltException(Parser recognizer) { // LL(1) error\n\t\tthis(recognizer,\n\t\t\t recognizer.getInputStream(),\n\t\t\t recognizer.getCurrentToken(),\n\t\t\t recognizer.getCurrentToken(),\n\t\t\t null,\n\t\t\t recognizer._ctx);\n\t}\n\n\tpublic NoViableAltException(Parser recognizer,\n\t\t\t\t\t\t\t\tTokenStream input,\n\t\t\t\t\t\t\t\tToken startToken,\n\t\t\t\t\t\t\t\tToken offendingToken,\n\t\t\t\t\t\t\t\tATNConfigSet deadEndConfigs,\n\t\t\t\t\t\t\t\tParserRuleContext ctx)\n\t{\n\t\tsuper(recognizer, input, ctx);\n\t\tthis.deadEndConfigs = deadEndConfigs;\n\t\tthis.startToken = startToken;\n\t\tthis.setOffendingToken(offendingToken);\n\t}\n\n\n\tpublic Token getStartToken() {\n\t\treturn startToken;\n\t}\n\n\n\tpublic ATNConfigSet getDeadEndConfigs() {\n\t\treturn deadEndConfigs;\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/Parser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializationOptions;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNSimulator;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.ParseInfo;\nimport org.antlr.v4.runtime.atn.ParserATNSimulator;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.atn.ProfilingATNSimulator;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.IntegerStack;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.ErrorNodeImpl;\nimport org.antlr.v4.runtime.tree.ParseTreeListener;\nimport org.antlr.v4.runtime.tree.ParseTreeWalker;\nimport org.antlr.v4.runtime.tree.TerminalNode;\nimport org.antlr.v4.runtime.tree.TerminalNodeImpl;\nimport org.antlr.v4.runtime.tree.pattern.ParseTreePattern;\nimport org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher;\n\nimport java.io.PrintStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/** This is all the parsing support code essentially; most of it is error recovery stuff. */\npublic abstract class Parser extends Recognizer<Token, ParserATNSimulator> {\n\tpublic class TraceListener implements ParseTreeListener {\n\t\t@Override\n\t\tpublic void enterEveryRule(ParserRuleContext ctx) {\n\t\t\tSystem.out.println(\"enter   \" + getRuleNames()[ctx.getRuleIndex()] +\n\t\t\t\t\t\t\t   \", LT(1)=\" + _input.LT(1).getText());\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitTerminal(TerminalNode node) {\n\t\t\tSystem.out.println(\"consume \"+node.getSymbol()+\" rule \"+\n\t\t\t\t\t\t\t   getRuleNames()[_ctx.getRuleIndex()]);\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitErrorNode(ErrorNode node) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void exitEveryRule(ParserRuleContext ctx) {\n\t\t\tSystem.out.println(\"exit    \"+getRuleNames()[ctx.getRuleIndex()]+\n\t\t\t\t\t\t\t   \", LT(1)=\"+_input.LT(1).getText());\n\t\t}\n\t}\n\n\tpublic static class TrimToSizeListener implements ParseTreeListener {\n\t\tpublic static final TrimToSizeListener INSTANCE = new TrimToSizeListener();\n\n\t\t@Override\n\t\tpublic void enterEveryRule(ParserRuleContext ctx) { }\n\n\t\t@Override\n\t\tpublic void visitTerminal(TerminalNode node) { }\n\n\t\t@Override\n\t\tpublic void visitErrorNode(ErrorNode node) {\t}\n\n\t\t@Override\n\t\tpublic void exitEveryRule(ParserRuleContext ctx) {\n\t\t\tif (ctx.children instanceof ArrayList) {\n\t\t\t\t((ArrayList<?>)ctx.children).trimToSize();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * This field holds the deserialized {@link ATN} with bypass alternatives, created\n\t * lazily upon first demand. In 4.10 I changed from map<serializedATNstring, ATN>\n\t * since we only need one per parser object and also it complicates other targets\n\t * that don't use ATN strings.\n\t *\n\t * @see ATNDeserializationOptions#isGenerateRuleBypassTransitions()\n\t */\n\tprivate ATN bypassAltsAtnCache;\n\n\t/**\n\t * The error handling strategy for the parser. The default value is a new\n\t * instance of {@link DefaultErrorStrategy}.\n\t *\n\t * @see #getErrorHandler\n\t * @see #setErrorHandler\n\t */\n\n\tprotected ANTLRErrorStrategy _errHandler = new DefaultErrorStrategy();\n\n\t/**\n\t * The input stream.\n\t *\n\t * @see #getInputStream\n\t * @see #setInputStream\n\t */\n\tprotected TokenStream _input;\n\n\tprotected final IntegerStack _precedenceStack;\n\t{\n\t\t_precedenceStack = new IntegerStack();\n\t\t_precedenceStack.push(0);\n\t}\n\n\t/**\n\t * The {@link ParserRuleContext} object for the currently executing rule.\n\t * This is always non-null during the parsing process.\n\t */\n\tprotected ParserRuleContext _ctx;\n\n\t/**\n\t * Specifies whether or not the parser should construct a parse tree during\n\t * the parsing process. The default value is {@code true}.\n\t *\n\t * @see #getBuildParseTree\n\t * @see #setBuildParseTree\n\t */\n\tprotected boolean _buildParseTrees = true;\n\n\n\t/**\n\t * When {@link #setTrace}{@code (true)} is called, a reference to the\n\t * {@link TraceListener} is stored here so it can be easily removed in a\n\t * later call to {@link #setTrace}{@code (false)}. The listener itself is\n\t * implemented as a parser listener so this field is not directly used by\n\t * other parser methods.\n\t */\n\tprivate TraceListener _tracer;\n\n\t/**\n\t * The list of {@link ParseTreeListener} listeners registered to receive\n\t * events during the parse.\n\t *\n\t * @see #addParseListener\n\t */\n\tprotected List<ParseTreeListener> _parseListeners;\n\n\t/**\n\t * The number of syntax errors reported during parsing. This value is\n\t * incremented each time {@link #notifyErrorListeners} is called.\n\t */\n\tprotected int _syntaxErrors;\n\n\t/** Indicates parser has match()ed EOF token. See {@link #exitRule()}. */\n\tprotected boolean matchedEOF;\n\n\tpublic Parser(TokenStream input) {\n\t\tsetInputStream(input);\n\t}\n\n\t/** reset the parser's state */\n\tpublic void reset() {\n\t\tif ( getInputStream()!=null ) getInputStream().seek(0);\n\t\t_errHandler.reset(this);\n\t\t_ctx = null;\n\t\t_syntaxErrors = 0;\n\t\tmatchedEOF = false;\n\t\tsetTrace(false);\n\t\t_precedenceStack.clear();\n\t\t_precedenceStack.push(0);\n\t\tATNSimulator interpreter = getInterpreter();\n\t\tif (interpreter != null) {\n\t\t\tinterpreter.reset();\n\t\t}\n\t}\n\n\t/**\n\t * Match current input symbol against {@code ttype}. If the symbol type\n\t * matches, {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are\n\t * called to complete the match process.\n\t *\n\t * <p>If the symbol type does not match,\n\t * {@link ANTLRErrorStrategy#recoverInline} is called on the current error\n\t * strategy to attempt recovery. If {@link #getBuildParseTree} is\n\t * {@code true} and the token index of the symbol returned by\n\t * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to\n\t * the parse tree by calling {@link #createErrorNode(ParserRuleContext, Token)} then\n\t * {@link ParserRuleContext#addErrorNode(ErrorNode)}.</p>\n\t *\n\t * @param ttype the token type to match\n\t * @return the matched symbol\n\t * @throws RecognitionException if the current input symbol did not match\n\t * {@code ttype} and the error strategy could not recover from the\n\t * mismatched symbol\n\t */\n\tpublic Token match(int ttype) throws RecognitionException {\n\t\tToken t = getCurrentToken();\n\t\tif ( t.getType()==ttype ) {\n\t\t\tif ( ttype==Token.EOF ) {\n\t\t\t\tmatchedEOF = true;\n\t\t\t}\n\t\t\t_errHandler.reportMatch(this);\n\t\t\tconsume();\n\t\t}\n\t\telse {\n\t\t\tt = _errHandler.recoverInline(this);\n\t\t\tif ( _buildParseTrees && t.getTokenIndex()==-1 ) {\n\t\t\t\t// we must have conjured up a new token during single token insertion\n\t\t\t\t// if it's not the current symbol\n\t\t\t\t_ctx.addErrorNode(createErrorNode(_ctx,t));\n\t\t\t}\n\t\t}\n\t\treturn t;\n\t}\n\n\t/**\n\t * Match current input symbol as a wildcard. If the symbol type matches\n\t * (i.e. has a value greater than 0), {@link ANTLRErrorStrategy#reportMatch}\n\t * and {@link #consume} are called to complete the match process.\n\t *\n\t * <p>If the symbol type does not match,\n\t * {@link ANTLRErrorStrategy#recoverInline} is called on the current error\n\t * strategy to attempt recovery. If {@link #getBuildParseTree} is\n\t * {@code true} and the token index of the symbol returned by\n\t * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to\n\t * the parse tree by calling {@link Parser#createErrorNode(ParserRuleContext, Token)}. then\n     * {@link ParserRuleContext#addErrorNode(ErrorNode)}</p>\n\t *\n\t * @return the matched symbol\n\t * @throws RecognitionException if the current input symbol did not match\n\t * a wildcard and the error strategy could not recover from the mismatched\n\t * symbol\n\t */\n\tpublic Token matchWildcard() throws RecognitionException {\n\t\tToken t = getCurrentToken();\n\t\tif (t.getType() > 0) {\n\t\t\t_errHandler.reportMatch(this);\n\t\t\tconsume();\n\t\t}\n\t\telse {\n\t\t\tt = _errHandler.recoverInline(this);\n\t\t\tif (_buildParseTrees && t.getTokenIndex() == -1) {\n\t\t\t\t// we must have conjured up a new token during single token insertion\n\t\t\t\t// if it's not the current symbol\n\t\t\t\t_ctx.addErrorNode(createErrorNode(_ctx,t));\n\t\t\t}\n\t\t}\n\n\t\treturn t;\n\t}\n\n\t/**\n\t * Track the {@link ParserRuleContext} objects during the parse and hook\n\t * them up using the {@link ParserRuleContext#children} list so that it\n\t * forms a parse tree. The {@link ParserRuleContext} returned from the start\n\t * rule represents the root of the parse tree.\n\t *\n\t * <p>Note that if we are not building parse trees, rule contexts only point\n\t * upwards. When a rule exits, it returns the context but that gets garbage\n\t * collected if nobody holds a reference. It points upwards but nobody\n\t * points at it.</p>\n\t *\n\t * <p>When we build parse trees, we are adding all of these contexts to\n\t * {@link ParserRuleContext#children} list. Contexts are then not candidates\n\t * for garbage collection.</p>\n\t */\n\tpublic void setBuildParseTree(boolean buildParseTrees) {\n\t\tthis._buildParseTrees = buildParseTrees;\n\t}\n\n\t/**\n\t * Gets whether or not a complete parse tree will be constructed while\n\t * parsing. This property is {@code true} for a newly constructed parser.\n\t *\n\t * @return {@code true} if a complete parse tree will be constructed while\n\t * parsing, otherwise {@code false}\n\t */\n\tpublic boolean getBuildParseTree() {\n\t\treturn _buildParseTrees;\n\t}\n\n\t/**\n\t * Trim the internal lists of the parse tree during parsing to conserve memory.\n\t * This property is set to {@code false} by default for a newly constructed parser.\n\t *\n\t * @param trimParseTrees {@code true} to trim the capacity of the {@link ParserRuleContext#children}\n\t * list to its size after a rule is parsed.\n\t */\n\tpublic void setTrimParseTree(boolean trimParseTrees) {\n\t\tif (trimParseTrees) {\n\t\t\tif (getTrimParseTree()) return;\n\t\t\taddParseListener(TrimToSizeListener.INSTANCE);\n\t\t}\n\t\telse {\n\t\t\tremoveParseListener(TrimToSizeListener.INSTANCE);\n\t\t}\n\t}\n\n\t/**\n\t * @return {@code true} if the {@link ParserRuleContext#children} list is trimmed\n\t * using the default {@link Parser.TrimToSizeListener} during the parse process.\n\t */\n\tpublic boolean getTrimParseTree() {\n\t\treturn getParseListeners().contains(TrimToSizeListener.INSTANCE);\n\t}\n\n\n\tpublic List<ParseTreeListener> getParseListeners() {\n\t\tList<ParseTreeListener> listeners = _parseListeners;\n\t\tif (listeners == null) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\treturn listeners;\n\t}\n\n\t/**\n\t * Registers {@code listener} to receive events during the parsing process.\n\t *\n\t * <p>To support output-preserving grammar transformations (including but not\n\t * limited to left-recursion removal, automated left-factoring, and\n\t * optimized code generation), calls to listener methods during the parse\n\t * may differ substantially from calls made by\n\t * {@link ParseTreeWalker#DEFAULT} used after the parse is complete. In\n\t * particular, rule entry and exit events may occur in a different order\n\t * during the parse than after the parser. In addition, calls to certain\n\t * rule entry methods may be omitted.</p>\n\t *\n\t * <p>With the following specific exceptions, calls to listener events are\n\t * <em>deterministic</em>, i.e. for identical input the calls to listener\n\t * methods will be the same.</p>\n\t *\n\t * <ul>\n\t * <li>Alterations to the grammar used to generate code may change the\n\t * behavior of the listener calls.</li>\n\t * <li>Alterations to the command line options passed to ANTLR 4 when\n\t * generating the parser may change the behavior of the listener calls.</li>\n\t * <li>Changing the version of the ANTLR Tool used to generate the parser\n\t * may change the behavior of the listener calls.</li>\n\t * </ul>\n\t *\n\t * @param listener the listener to add\n\t *\n\t * @throws NullPointerException if {@code} listener is {@code null}\n\t */\n\tpublic void addParseListener(ParseTreeListener listener) {\n\t\tif (listener == null) {\n\t\t\tthrow new NullPointerException(\"listener\");\n\t\t}\n\n\t\tif (_parseListeners == null) {\n\t\t\t_parseListeners = new ArrayList<ParseTreeListener>();\n\t\t}\n\n\t\tthis._parseListeners.add(listener);\n\t}\n\n\t/**\n\t * Remove {@code listener} from the list of parse listeners.\n\t *\n\t * <p>If {@code listener} is {@code null} or has not been added as a parse\n\t * listener, this method does nothing.</p>\n\t *\n\t * @see #addParseListener\n\t *\n\t * @param listener the listener to remove\n\t */\n\tpublic void removeParseListener(ParseTreeListener listener) {\n\t\tif (_parseListeners != null) {\n\t\t\tif (_parseListeners.remove(listener)) {\n\t\t\t\tif (_parseListeners.isEmpty()) {\n\t\t\t\t\t_parseListeners = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Remove all parse listeners.\n\t *\n\t * @see #addParseListener\n\t */\n\tpublic void removeParseListeners() {\n\t\t_parseListeners = null;\n\t}\n\n\t/**\n\t * Notify any parse listeners of an enter rule event.\n\t *\n\t * @see #addParseListener\n\t */\n\tprotected void triggerEnterRuleEvent() {\n\t\tfor (ParseTreeListener listener : _parseListeners) {\n\t\t\tlistener.enterEveryRule(_ctx);\n\t\t\t_ctx.enterRule(listener);\n\t\t}\n\t}\n\n\t/**\n\t * Notify any parse listeners of an exit rule event.\n\t *\n\t * @see #addParseListener\n\t */\n\tprotected void triggerExitRuleEvent() {\n\t\t// reverse order walk of listeners\n\t\tfor (int i = _parseListeners.size()-1; i >= 0; i--) {\n\t\t\tParseTreeListener listener = _parseListeners.get(i);\n\t\t\t_ctx.exitRule(listener);\n\t\t\tlistener.exitEveryRule(_ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Gets the number of syntax errors reported during parsing. This value is\n\t * incremented each time {@link #notifyErrorListeners} is called.\n\t *\n\t * @see #notifyErrorListeners\n\t */\n\tpublic int getNumberOfSyntaxErrors() {\n\t\treturn _syntaxErrors;\n\t}\n\n\t@Override\n\tpublic TokenFactory<?> getTokenFactory() {\n\t\treturn _input.getTokenSource().getTokenFactory();\n\t}\n\n\t/** Tell our token source and error strategy about a new way to create tokens. */\n\t@Override\n\tpublic void setTokenFactory(TokenFactory<?> factory) {\n\t\t_input.getTokenSource().setTokenFactory(factory);\n\t}\n\n\t/**\n\t * The ATN with bypass alternatives is expensive to create so we create it\n\t * lazily.\n\t *\n\t * @throws UnsupportedOperationException if the current parser does not\n\t * implement the {@link #getSerializedATN()} method.\n\t */\n\n\tpublic ATN getATNWithBypassAlts() {\n\t\tString serializedAtn = getSerializedATN();\n\t\tif (serializedAtn == null) {\n\t\t\tthrow new UnsupportedOperationException(\"The current parser does not support an ATN with bypass alternatives.\");\n\t\t}\n\n\t\tsynchronized (this) {\n\t\t\tif ( bypassAltsAtnCache!=null ) {\n\t\t\t\treturn bypassAltsAtnCache;\n\t\t\t}\n\t\t\tATNDeserializationOptions deserializationOptions = new ATNDeserializationOptions();\n\t\t\tdeserializationOptions.setGenerateRuleBypassTransitions(true);\n\t\t\tbypassAltsAtnCache = new ATNDeserializer(deserializationOptions).deserialize(serializedAtn.toCharArray());\n\t\t\treturn bypassAltsAtnCache;\n\t\t}\n\t}\n\n\t/**\n\t * The preferred method of getting a tree pattern. For example, here's a\n\t * sample use:\n\t *\n\t * <pre>\n\t * ParseTree t = parser.expr();\n\t * ParseTreePattern p = parser.compileParseTreePattern(\"&lt;ID&gt;+0\", MyParser.RULE_expr);\n\t * ParseTreeMatch m = p.match(t);\n\t * String id = m.get(\"ID\");\n\t * </pre>\n\t */\n\tpublic ParseTreePattern compileParseTreePattern(String pattern, int patternRuleIndex) {\n\t\tif ( getTokenStream()!=null ) {\n\t\t\tTokenSource tokenSource = getTokenStream().getTokenSource();\n\t\t\tif ( tokenSource instanceof Lexer ) {\n\t\t\t\tLexer lexer = (Lexer)tokenSource;\n\t\t\t\treturn compileParseTreePattern(pattern, patternRuleIndex, lexer);\n\t\t\t}\n\t\t}\n\t\tthrow new UnsupportedOperationException(\"Parser can't discover a lexer to use\");\n\t}\n\n\t/**\n\t * The same as {@link #compileParseTreePattern(String, int)} but specify a\n\t * {@link Lexer} rather than trying to deduce it from this parser.\n\t */\n\tpublic ParseTreePattern compileParseTreePattern(String pattern, int patternRuleIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\tLexer lexer)\n\t{\n\t\tParseTreePatternMatcher m = new ParseTreePatternMatcher(lexer, this);\n\t\treturn m.compile(pattern, patternRuleIndex);\n\t}\n\n\n\tpublic ANTLRErrorStrategy getErrorHandler() {\n\t\treturn _errHandler;\n\t}\n\n\tpublic void setErrorHandler(ANTLRErrorStrategy handler) {\n\t\tthis._errHandler = handler;\n\t}\n\n\t@Override\n\tpublic TokenStream getInputStream() { return getTokenStream(); }\n\n\t@Override\n\tpublic final void setInputStream(IntStream input) {\n\t\tsetTokenStream((TokenStream)input);\n\t}\n\n\tpublic TokenStream getTokenStream() {\n\t\treturn _input;\n\t}\n\n\t/** Set the token stream and reset the parser. */\n\tpublic void setTokenStream(TokenStream input) {\n\t\tthis._input = null;\n\t\treset();\n\t\tthis._input = input;\n\t}\n\n    /** Match needs to return the current input symbol, which gets put\n     *  into the label for the associated token ref; e.g., x=ID.\n     */\n\n    public Token getCurrentToken() {\n\t\treturn _input.LT(1);\n\t}\n\n\tpublic final void notifyErrorListeners(String msg)\t{\n\t\tnotifyErrorListeners(getCurrentToken(), msg, null);\n\t}\n\n\tpublic void notifyErrorListeners(Token offendingToken, String msg,\n\t\t\t\t\t\t\t\t\t RecognitionException e)\n\t{\n\t\t_syntaxErrors++;\n\t\tint line = -1;\n\t\tint charPositionInLine = -1;\n\t\tline = offendingToken.getLine();\n\t\tcharPositionInLine = offendingToken.getCharPositionInLine();\n\n\t\tANTLRErrorListener listener = getErrorListenerDispatch();\n\t\tlistener.syntaxError(this, offendingToken, line, charPositionInLine, msg, e);\n\t}\n\n\t/**\n\t * Consume and return the {@linkplain #getCurrentToken current symbol}.\n\t *\n\t * <p>E.g., given the following input with {@code A} being the current\n\t * lookahead symbol, this function moves the cursor to {@code B} and returns\n\t * {@code A}.</p>\n\t *\n\t * <pre>\n\t *  A B\n\t *  ^\n\t * </pre>\n\t *\n\t * If the parser is not in error recovery mode, the consumed symbol is added\n\t * to the parse tree using {@link ParserRuleContext#addChild(TerminalNode)}, and\n\t * {@link ParseTreeListener#visitTerminal} is called on any parse listeners.\n\t * If the parser <em>is</em> in error recovery mode, the consumed symbol is\n\t * added to the parse tree using {@link #createErrorNode(ParserRuleContext, Token)} then\n     * {@link ParserRuleContext#addErrorNode(ErrorNode)} and\n\t * {@link ParseTreeListener#visitErrorNode} is called on any parse\n\t * listeners.\n\t */\n\tpublic Token consume() {\n\t\tToken o = getCurrentToken();\n\t\tif (o.getType() != EOF) {\n\t\t\tgetInputStream().consume();\n\t\t}\n\t\tboolean hasListener = _parseListeners != null && !_parseListeners.isEmpty();\n\t\tif (_buildParseTrees || hasListener) {\n\t\t\tif ( _errHandler.inErrorRecoveryMode(this) ) {\n\t\t\t\tErrorNode node = _ctx.addErrorNode(createErrorNode(_ctx,o));\n\t\t\t\tif (_parseListeners != null) {\n\t\t\t\t\tfor (ParseTreeListener listener : _parseListeners) {\n\t\t\t\t\t\tlistener.visitErrorNode(node);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tTerminalNode node = _ctx.addChild(createTerminalNode(_ctx,o));\n\t\t\t\tif (_parseListeners != null) {\n\t\t\t\t\tfor (ParseTreeListener listener : _parseListeners) {\n\t\t\t\t\t\tlistener.visitTerminal(node);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn o;\n\t}\n\n\t/** How to create a token leaf node associated with a parent.\n\t *  Typically, the terminal node to create is not a function of the parent.\n\t *\n\t * @since 4.7\n\t */\n\tpublic TerminalNode createTerminalNode(ParserRuleContext parent, Token t) {\n\t\treturn new TerminalNodeImpl(t);\n\t}\n\n\t/** How to create an error node, given a token, associated with a parent.\n\t *  Typically, the error node to create is not a function of the parent.\n\t *\n\t * @since 4.7\n\t */\n\tpublic ErrorNode createErrorNode(ParserRuleContext parent, Token t) {\n\t\treturn new ErrorNodeImpl(t);\n\t}\n\n\tprotected void addContextToParseTree() {\n\t\tParserRuleContext parent = (ParserRuleContext)_ctx.parent;\n\t\t// add current context to parent if we have a parent\n\t\tif ( parent!=null )\t{\n\t\t\tparent.addChild(_ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Always called by generated parsers upon entry to a rule. Access field\n\t * {@link #_ctx} get the current context.\n\t */\n\tpublic void enterRule(ParserRuleContext localctx, int state, int ruleIndex) {\n\t\tsetState(state);\n\t\t_ctx = localctx;\n\t\t_ctx.start = _input.LT(1);\n\t\tif (_buildParseTrees) addContextToParseTree();\n        if ( _parseListeners != null) triggerEnterRuleEvent();\n\t}\n\n    public void exitRule() {\n\t\tif ( matchedEOF ) {\n\t\t\t// if we have matched EOF, it cannot consume past EOF so we use LT(1) here\n\t\t\t_ctx.stop = _input.LT(1); // LT(1) will be end of file\n\t\t}\n\t\telse {\n\t\t\t_ctx.stop = _input.LT(-1); // stop node is what we just matched\n\t\t}\n        // trigger event on _ctx, before it reverts to parent\n        if ( _parseListeners != null) triggerExitRuleEvent();\n\t\tsetState(_ctx.invokingState);\n\t\t_ctx = (ParserRuleContext)_ctx.parent;\n    }\n\n\tpublic void enterOuterAlt(ParserRuleContext localctx, int altNum) {\n\t\tlocalctx.setAltNumber(altNum);\n\t\t// if we have new localctx, make sure we replace existing ctx\n\t\t// that is previous child of parse tree\n\t\tif ( _buildParseTrees && _ctx != localctx ) {\n\t\t\tParserRuleContext parent = (ParserRuleContext)_ctx.parent;\n\t\t\tif ( parent!=null )\t{\n\t\t\t\tparent.removeLastChild();\n\t\t\t\tparent.addChild(localctx);\n\t\t\t}\n\t\t}\n\t\t_ctx = localctx;\n\t}\n\n\t/**\n\t * Get the precedence level for the top-most precedence rule.\n\t *\n\t * @return The precedence level for the top-most precedence rule, or -1 if\n\t * the parser context is not nested within a precedence rule.\n\t */\n\tpublic final int getPrecedence() {\n\t\tif (_precedenceStack.isEmpty()) {\n\t\t\treturn -1;\n\t\t}\n\n\t\treturn _precedenceStack.peek();\n\t}\n\n\t/**\n\t * @deprecated Use\n\t * {@link #enterRecursionRule(ParserRuleContext, int, int, int)} instead.\n\t */\n\t@Deprecated\n\tpublic void enterRecursionRule(ParserRuleContext localctx, int ruleIndex) {\n\t\tenterRecursionRule(localctx, getATN().ruleToStartState[ruleIndex].stateNumber, ruleIndex, 0);\n\t}\n\n\tpublic void enterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence) {\n\t\tsetState(state);\n\t\t_precedenceStack.push(precedence);\n\t\t_ctx = localctx;\n\t\t_ctx.start = _input.LT(1);\n\t\tif (_parseListeners != null) {\n\t\t\ttriggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n\t\t}\n\t}\n\n\t/** Like {@link #enterRule} but for recursive rules.\n\t *  Make the current context the child of the incoming localctx.\n\t */\n\tpublic void pushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex) {\n\t\tParserRuleContext previous = _ctx;\n\t\tprevious.parent = localctx;\n\t\tprevious.invokingState = state;\n\t\tprevious.stop = _input.LT(-1);\n\n\t\t_ctx = localctx;\n\t\t_ctx.start = previous.start;\n\t\tif (_buildParseTrees) {\n\t\t\t_ctx.addChild(previous);\n\t\t}\n\n\t\tif ( _parseListeners != null ) {\n\t\t\ttriggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n\t\t}\n\t}\n\n\tpublic void unrollRecursionContexts(ParserRuleContext _parentctx) {\n\t\t_precedenceStack.pop();\n\t\t_ctx.stop = _input.LT(-1);\n\t\tParserRuleContext retctx = _ctx; // save current ctx (return value)\n\n\t\t// unroll so _ctx is as it was before call to recursive method\n\t\tif ( _parseListeners != null ) {\n\t\t\twhile ( _ctx != _parentctx ) {\n\t\t\t\ttriggerExitRuleEvent();\n\t\t\t\t_ctx = (ParserRuleContext)_ctx.parent;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t_ctx = _parentctx;\n\t\t}\n\n\t\t// hook into tree\n\t\tretctx.parent = _parentctx;\n\n\t\tif (_buildParseTrees && _parentctx != null) {\n\t\t\t// add return ctx into invoking rule's tree\n\t\t\t_parentctx.addChild(retctx);\n\t\t}\n\t}\n\n\tpublic ParserRuleContext getInvokingContext(int ruleIndex) {\n\t\tParserRuleContext p = _ctx;\n\t\twhile ( p!=null ) {\n\t\t\tif ( p.getRuleIndex() == ruleIndex ) return p;\n\t\t\tp = (ParserRuleContext)p.parent;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic ParserRuleContext getContext() {\n\t\treturn _ctx;\n\t}\n\n\tpublic void setContext(ParserRuleContext ctx) {\n\t\t_ctx = ctx;\n\t}\n\n\t@Override\n\tpublic boolean precpred(RuleContext localctx, int precedence) {\n\t\treturn precedence >= _precedenceStack.peek();\n\t}\n\n\tpublic boolean inContext(String context) {\n\t\t// TODO: useful in parser?\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks whether or not {@code symbol} can follow the current state in the\n\t * ATN. The behavior of this method is equivalent to the following, but is\n\t * implemented such that the complete context-sensitive follow set does not\n\t * need to be explicitly constructed.\n\t *\n\t * <pre>\n\t * return getExpectedTokens().contains(symbol);\n\t * </pre>\n\t *\n\t * @param symbol the symbol type to check\n\t * @return {@code true} if {@code symbol} can follow the current state in\n\t * the ATN, otherwise {@code false}.\n\t */\n    public boolean isExpectedToken(int symbol) {\n//   \t\treturn getInterpreter().atn.nextTokens(_ctx);\n        ATN atn = getInterpreter().atn;\n\t\tParserRuleContext ctx = _ctx;\n        ATNState s = atn.states.get(getState());\n        IntervalSet following = atn.nextTokens(s);\n        if (following.contains(symbol)) {\n            return true;\n        }\n//        System.out.println(\"following \"+s+\"=\"+following);\n        if ( !following.contains(Token.EPSILON) ) return false;\n\n        while ( ctx!=null && ctx.invokingState>=0 && following.contains(Token.EPSILON) ) {\n            ATNState invokingState = atn.states.get(ctx.invokingState);\n            RuleTransition rt = (RuleTransition)invokingState.transition(0);\n            following = atn.nextTokens(rt.followState);\n            if (following.contains(symbol)) {\n                return true;\n            }\n\n            ctx = (ParserRuleContext)ctx.parent;\n        }\n\n        if ( following.contains(Token.EPSILON) && symbol == Token.EOF ) {\n            return true;\n        }\n\n        return false;\n    }\n\n\tpublic boolean isMatchedEOF() {\n\t\treturn matchedEOF;\n\t}\n\n\t/**\n\t * Computes the set of input symbols which could follow the current parser\n\t * state and context, as given by {@link #getState} and {@link #getContext},\n\t * respectively.\n\t *\n\t * @see ATN#getExpectedTokens(int, RuleContext)\n\t */\n\tpublic IntervalSet getExpectedTokens() {\n\t\treturn getATN().getExpectedTokens(getState(), getContext());\n\t}\n\n\n    public IntervalSet getExpectedTokensWithinCurrentRule() {\n        ATN atn = getInterpreter().atn;\n        ATNState s = atn.states.get(getState());\n   \t\treturn atn.nextTokens(s);\n   \t}\n\n\t/** Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found. */\n\tpublic int getRuleIndex(String ruleName) {\n\t\tInteger ruleIndex = getRuleIndexMap().get(ruleName);\n\t\tif ( ruleIndex!=null ) return ruleIndex;\n\t\treturn -1;\n\t}\n\n\tpublic ParserRuleContext getRuleContext() { return _ctx; }\n\n\t/** Return List&lt;String&gt; of the rule names in your parser instance\n\t *  leading up to a call to the current rule.  You could override if\n\t *  you want more details such as the file/line info of where\n\t *  in the ATN a rule is invoked.\n\t *\n\t *  This is very useful for error messages.\n\t */\n\tpublic List<String> getRuleInvocationStack() {\n\t\treturn getRuleInvocationStack(_ctx);\n\t}\n\n\tpublic List<String> getRuleInvocationStack(RuleContext p) {\n\t\tString[] ruleNames = getRuleNames();\n\t\tList<String> stack = new ArrayList<String>();\n\t\twhile ( p!=null ) {\n\t\t\t// compute what follows who invoked us\n\t\t\tint ruleIndex = p.getRuleIndex();\n\t\t\tif ( ruleIndex<0 ) stack.add(\"n/a\");\n\t\t\telse stack.add(ruleNames[ruleIndex]);\n\t\t\tp = p.parent;\n\t\t}\n\t\treturn stack;\n\t}\n\n\t/** For debugging and other purposes. */\n\tpublic List<String> getDFAStrings() {\n\t\tsynchronized (_interp.decisionToDFA) {\n\t\t\tList<String> s = new ArrayList<String>();\n\t\t\tfor (int d = 0; d < _interp.decisionToDFA.length; d++) {\n\t\t\t\tDFA dfa = _interp.decisionToDFA[d];\n\t\t\t\ts.add( dfa.toString(getVocabulary()) );\n\t\t\t}\n\t\t\treturn s;\n\t\t}\n    }\n\n\tpublic void dumpDFA() {\n\t\tdumpDFA(System.out);\n\t}\n\n\t/** For debugging and other purposes. */\n\tpublic void dumpDFA(PrintStream dumpStream) {\n\t\tsynchronized (_interp.decisionToDFA) {\n\t\t\tboolean seenOne = false;\n\t\t\tfor (int d = 0; d < _interp.decisionToDFA.length; d++) {\n\t\t\t\tDFA dfa = _interp.decisionToDFA[d];\n\t\t\t\tif ( !dfa.states.isEmpty() ) {\n\t\t\t\t\tif ( seenOne ) dumpStream.println();\n\t\t\t\t\tdumpStream.println(\"Decision \" + dfa.decision + \":\");\n\t\t\t\t\tdumpStream.print(dfa.toString(getVocabulary()));\n\t\t\t\t\tseenOne = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n    }\n\n\tpublic String getSourceName() {\n\t\treturn _input.getSourceName();\n\t}\n\n\t@Override\n\tpublic ParseInfo getParseInfo() {\n\t\tParserATNSimulator interp = getInterpreter();\n\t\tif (interp instanceof ProfilingATNSimulator) {\n\t\t\treturn new ParseInfo((ProfilingATNSimulator)interp);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * @since 4.3\n\t */\n\tpublic void setProfile(boolean profile) {\n\t\tParserATNSimulator interp = getInterpreter();\n\t\tPredictionMode saveMode = interp.getPredictionMode();\n\t\tif ( profile ) {\n\t\t\tif ( !(interp instanceof ProfilingATNSimulator) ) {\n\t\t\t\tsetInterpreter(new ProfilingATNSimulator(this));\n\t\t\t}\n\t\t}\n\t\telse if ( interp instanceof ProfilingATNSimulator ) {\n\t\t\tParserATNSimulator sim =\n\t\t\t\tnew ParserATNSimulator(this, getATN(), interp.decisionToDFA, interp.getSharedContextCache());\n\t\t\tsetInterpreter(sim);\n\t\t}\n\t\tgetInterpreter().setPredictionMode(saveMode);\n\t}\n\n\t/** During a parse is sometimes useful to listen in on the rule entry and exit\n\t *  events as well as token matches. This is for quick and dirty debugging.\n\t */\n\tpublic void setTrace(boolean trace) {\n\t\tif ( !trace ) {\n\t\t\tremoveParseListener(_tracer);\n\t\t\t_tracer = null;\n\t\t}\n\t\telse {\n\t\t\tif ( _tracer!=null ) removeParseListener(_tracer);\n\t\t\telse _tracer = new TraceListener();\n\t\t\taddParseListener(_tracer);\n\t\t}\n\t}\n\n\t/**\n\t * Gets whether a {@link TraceListener} is registered as a parse listener\n\t * for the parser.\n\t *\n\t * @see #setTrace(boolean)\n\t */\n\tpublic boolean isTrace() {\n\t\treturn _tracer != null;\n\t}\n}\n\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ParserInterpreter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.ActionTransition;\nimport org.antlr.v4.runtime.atn.AtomTransition;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.LoopEndState;\nimport org.antlr.v4.runtime.atn.ParserATNSimulator;\nimport org.antlr.v4.runtime.atn.PrecedencePredicateTransition;\nimport org.antlr.v4.runtime.atn.PredicateTransition;\nimport org.antlr.v4.runtime.atn.PredictionContextCache;\nimport org.antlr.v4.runtime.atn.RuleStartState;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.util.ArrayDeque;\nimport java.util.Collection;\nimport java.util.Deque;\n\n/** A parser simulator that mimics what ANTLR's generated\n *  parser code does. A ParserATNSimulator is used to make\n *  predictions via adaptivePredict but this class moves a pointer through the\n *  ATN to simulate parsing. ParserATNSimulator just\n *  makes us efficient rather than having to backtrack, for example.\n *\n *  This properly creates parse trees even for left recursive rules.\n *\n *  We rely on the left recursive rule invocation and special predicate\n *  transitions to make left recursive rules work.\n *\n *  See TestParserInterpreter for examples.\n */\npublic class ParserInterpreter extends Parser {\n\tprotected final String grammarFileName;\n\tprotected final ATN atn;\n\n\tprotected final DFA[] decisionToDFA; // not shared like it is for generated parsers\n\tprotected final PredictionContextCache sharedContextCache = new PredictionContextCache();\n\n\t@Deprecated\n\tprotected final String[] tokenNames;\n\tprotected final String[] ruleNames;\n\n\tprivate final Vocabulary vocabulary;\n\n\t/** This stack corresponds to the _parentctx, _parentState pair of locals\n\t *  that would exist on call stack frames with a recursive descent parser;\n\t *  in the generated function for a left-recursive rule you'd see:\n\t *\n\t *  private EContext e(int _p) throws RecognitionException {\n\t *      ParserRuleContext _parentctx = _ctx;    // Pair.a\n\t *      int _parentState = getState();          // Pair.b\n\t *      ...\n\t *  }\n\t *\n\t *  Those values are used to create new recursive rule invocation contexts\n\t *  associated with left operand of an alt like \"expr '*' expr\".\n\t */\n\tprotected final Deque<Pair<ParserRuleContext, Integer>> _parentContextStack =\n\t\tnew ArrayDeque<Pair<ParserRuleContext, Integer>>();\n\n\t/** We need a map from (decision,inputIndex)->forced alt for computing ambiguous\n\t *  parse trees. For now, we allow exactly one override.\n\t */\n\tprotected int overrideDecision = -1;\n\tprotected int overrideDecisionInputIndex = -1;\n\tprotected int overrideDecisionAlt = -1;\n\tprotected boolean overrideDecisionReached = false; // latch and only override once; error might trigger infinite loop\n\n\t/** What is the current context when we override a decisions?  This tells\n\t *  us what the root of the parse tree is when using override\n\t *  for an ambiguity/lookahead check.\n\t */\n\tprotected InterpreterRuleContext overrideDecisionRoot = null;\n\n\n\tprotected InterpreterRuleContext rootContext;\n\n\t/**\n\t * @deprecated Use {@link #ParserInterpreter(String, Vocabulary, Collection, ATN, TokenStream)} instead.\n\t */\n\t@Deprecated\n\tpublic ParserInterpreter(String grammarFileName, Collection<String> tokenNames,\n\t\t\t\t\t\t\t Collection<String> ruleNames, ATN atn, TokenStream input) {\n\t\tthis(grammarFileName, VocabularyImpl.fromTokenNames(tokenNames.toArray(new String[0])), ruleNames, atn, input);\n\t}\n\n\tpublic ParserInterpreter(String grammarFileName, Vocabulary vocabulary,\n\t\t\t\t\t\t\t Collection<String> ruleNames, ATN atn, TokenStream input)\n\t{\n\t\tsuper(input);\n\t\tthis.grammarFileName = grammarFileName;\n\t\tthis.atn = atn;\n\t\tthis.tokenNames = new String[atn.maxTokenType];\n\t\tfor (int i = 0; i < tokenNames.length; i++) {\n\t\t\ttokenNames[i] = vocabulary.getDisplayName(i);\n\t\t}\n\n\t\tthis.ruleNames = ruleNames.toArray(new String[0]);\n\t\tthis.vocabulary = vocabulary;\n\n\t\t// init decision DFA\n\t\tint numberOfDecisions = atn.getNumberOfDecisions();\n\t\tthis.decisionToDFA = new DFA[numberOfDecisions];\n\t\tfor (int i = 0; i < numberOfDecisions; i++) {\n\t\t\tDecisionState decisionState = atn.getDecisionState(i);\n\t\t\tdecisionToDFA[i] = new DFA(decisionState, i);\n\t\t}\n\n\t\t// get atn simulator that knows how to do predictions\n\t\tsetInterpreter(new ParserATNSimulator(this, atn,\n\t\t\t\t\t\t\t\t\t\t\t  decisionToDFA,\n\t\t\t\t\t\t\t\t\t\t\t  sharedContextCache));\n\t}\n\n\t@Override\n\tpublic void reset() {\n\t\tsuper.reset();\n\t\toverrideDecisionReached = false;\n\t\toverrideDecisionRoot = null;\n\t}\n\n\t@Override\n\tpublic ATN getATN() {\n\t\treturn atn;\n\t}\n\n\t@Override\n\t@Deprecated\n\tpublic String[] getTokenNames() {\n\t\treturn tokenNames;\n\t}\n\n\t@Override\n\tpublic Vocabulary getVocabulary() {\n\t\treturn vocabulary;\n\t}\n\n\t@Override\n\tpublic String[] getRuleNames() {\n\t\treturn ruleNames;\n\t}\n\n\t@Override\n\tpublic String getGrammarFileName() {\n\t\treturn grammarFileName;\n\t}\n\n\t/** Begin parsing at startRuleIndex */\n\tpublic ParserRuleContext parse(int startRuleIndex) {\n\t\tRuleStartState startRuleStartState = atn.ruleToStartState[startRuleIndex];\n\n\t\trootContext = createInterpreterRuleContext(null, ATNState.INVALID_STATE_NUMBER, startRuleIndex);\n\t\tif (startRuleStartState.isLeftRecursiveRule) {\n\t\t\tenterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0);\n\t\t}\n\t\telse {\n\t\t\tenterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex);\n\t\t}\n\n\t\twhile ( true ) {\n\t\t\tATNState p = getATNState();\n\t\t\tswitch ( p.getStateType() ) {\n\t\t\tcase ATNState.RULE_STOP :\n\t\t\t\t// pop; return from rule\n\t\t\t\tif ( _ctx.isEmpty() ) {\n\t\t\t\t\tif (startRuleStartState.isLeftRecursiveRule) {\n\t\t\t\t\t\tParserRuleContext result = _ctx;\n\t\t\t\t\t\tPair<ParserRuleContext, Integer> parentContext = _parentContextStack.pop();\n\t\t\t\t\t\tunrollRecursionContexts(parentContext.a);\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\texitRule();\n\t\t\t\t\t\treturn rootContext;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvisitRuleStopState(p);\n\t\t\t\tbreak;\n\n\t\t\tdefault :\n\t\t\t\ttry {\n\t\t\t\t\tvisitState(p);\n\t\t\t\t}\n\t\t\t\tcatch (RecognitionException e) {\n\t\t\t\t\tsetState(atn.ruleToStopState[p.ruleIndex].stateNumber);\n\t\t\t\t\tgetContext().exception = e;\n\t\t\t\t\tgetErrorHandler().reportError(this, e);\n\t\t\t\t\trecover(e);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void enterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence) {\n\t\tPair<ParserRuleContext, Integer> pair = new Pair<ParserRuleContext, Integer>(_ctx, localctx.invokingState);\n\t\t_parentContextStack.push(pair);\n\t\tsuper.enterRecursionRule(localctx, state, ruleIndex, precedence);\n\t}\n\n\tprotected ATNState getATNState() {\n\t\treturn atn.states.get(getState());\n\t}\n\n\tprotected void visitState(ATNState p) {\n//\t\tSystem.out.println(\"visitState \"+p.stateNumber);\n\t\tint predictedAlt = 1;\n\t\tif ( p instanceof DecisionState ) {\n\t\t\tpredictedAlt = visitDecisionState((DecisionState) p);\n\t\t}\n\n\t\tTransition transition = p.transition(predictedAlt - 1);\n\t\tswitch (transition.getSerializationType()) {\n\t\t\tcase Transition.EPSILON:\n\t\t\t\tif ( p.getStateType()==ATNState.STAR_LOOP_ENTRY &&\n\t\t\t\t\t ((StarLoopEntryState)p).isPrecedenceDecision &&\n\t\t\t\t\t !(transition.target instanceof LoopEndState))\n\t\t\t\t{\n\t\t\t\t\t// We are at the start of a left recursive rule's (...)* loop\n\t\t\t\t\t// and we're not taking the exit branch of loop.\n\t\t\t\t\tInterpreterRuleContext localctx =\n\t\t\t\t\t\tcreateInterpreterRuleContext(_parentContextStack.peek().a,\n\t\t\t\t\t\t\t\t\t\t\t\t\t _parentContextStack.peek().b,\n\t\t\t\t\t\t\t\t\t\t\t\t\t _ctx.getRuleIndex());\n\t\t\t\t\tpushNewRecursionContext(localctx,\n\t\t\t\t\t\t\t\t\t\t\tatn.ruleToStartState[p.ruleIndex].stateNumber,\n\t\t\t\t\t\t\t\t\t\t\t_ctx.getRuleIndex());\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.ATOM:\n\t\t\t\tmatch(((AtomTransition)transition).label);\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.RANGE:\n\t\t\tcase Transition.SET:\n\t\t\tcase Transition.NOT_SET:\n\t\t\t\tif (!transition.matches(_input.LA(1), Token.MIN_USER_TOKEN_TYPE, 65535)) {\n\t\t\t\t\trecoverInline();\n\t\t\t\t}\n\t\t\t\tmatchWildcard();\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.WILDCARD:\n\t\t\t\tmatchWildcard();\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.RULE:\n\t\t\t\tRuleStartState ruleStartState = (RuleStartState)transition.target;\n\t\t\t\tint ruleIndex = ruleStartState.ruleIndex;\n\t\t\t\tInterpreterRuleContext newctx = createInterpreterRuleContext(_ctx, p.stateNumber, ruleIndex);\n\t\t\t\tif (ruleStartState.isLeftRecursiveRule) {\n\t\t\t\t\tenterRecursionRule(newctx, ruleStartState.stateNumber, ruleIndex, ((RuleTransition)transition).precedence);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tenterRule(newctx, transition.target.stateNumber, ruleIndex);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.PREDICATE:\n\t\t\t\tPredicateTransition predicateTransition = (PredicateTransition)transition;\n\t\t\t\tif (!sempred(_ctx, predicateTransition.ruleIndex, predicateTransition.predIndex)) {\n\t\t\t\t\tthrow new FailedPredicateException(this);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.ACTION:\n\t\t\t\tActionTransition actionTransition = (ActionTransition)transition;\n\t\t\t\taction(_ctx, actionTransition.ruleIndex, actionTransition.actionIndex);\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.PRECEDENCE:\n\t\t\t\tif (!precpred(_ctx, ((PrecedencePredicateTransition)transition).precedence)) {\n\t\t\t\t\tthrow new FailedPredicateException(this, String.format(\"precpred(_ctx, %d)\", ((PrecedencePredicateTransition)transition).precedence));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow new UnsupportedOperationException(\"Unrecognized ATN transition type.\");\n\t\t}\n\n\t\tsetState(transition.target.stateNumber);\n\t}\n\n\t/** Method visitDecisionState() is called when the interpreter reaches\n\t *  a decision state (instance of DecisionState). It gives an opportunity\n\t *  for subclasses to track interesting things.\n\t */\n\tprotected int visitDecisionState(DecisionState p) {\n\t\tint predictedAlt = 1;\n\t\tif ( p.getNumberOfTransitions()>1 ) {\n\t\t\tgetErrorHandler().sync(this);\n\t\t\tint decision = p.decision;\n\t\t\tif ( decision == overrideDecision && _input.index() == overrideDecisionInputIndex &&\n\t\t\t     !overrideDecisionReached )\n\t\t\t{\n\t\t\t\tpredictedAlt = overrideDecisionAlt;\n\t\t\t\toverrideDecisionReached = true;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpredictedAlt = getInterpreter().adaptivePredict(_input, decision, _ctx);\n\t\t\t}\n\t\t}\n\t\treturn predictedAlt;\n\t}\n\n\t/** Provide simple \"factory\" for InterpreterRuleContext's.\n\t *  @since 4.5.1\n\t */\n\tprotected InterpreterRuleContext createInterpreterRuleContext(\n\t\tParserRuleContext parent,\n\t\tint invokingStateNumber,\n\t\tint ruleIndex)\n\t{\n\t\treturn new InterpreterRuleContext(parent, invokingStateNumber, ruleIndex);\n\t}\n\n\tprotected void visitRuleStopState(ATNState p) {\n\t\tRuleStartState ruleStartState = atn.ruleToStartState[p.ruleIndex];\n\t\tif (ruleStartState.isLeftRecursiveRule) {\n\t\t\tPair<ParserRuleContext, Integer> parentContext = _parentContextStack.pop();\n\t\t\tunrollRecursionContexts(parentContext.a);\n\t\t\tsetState(parentContext.b);\n\t\t}\n\t\telse {\n\t\t\texitRule();\n\t\t}\n\n\t\tRuleTransition ruleTransition = (RuleTransition)atn.states.get(getState()).transition(0);\n\t\tsetState(ruleTransition.followState.stateNumber);\n\t}\n\n\t/** Override this parser interpreters normal decision-making process\n\t *  at a particular decision and input token index. Instead of\n\t *  allowing the adaptive prediction mechanism to choose the\n\t *  first alternative within a block that leads to a successful parse,\n\t *  force it to take the alternative, 1..n for n alternatives.\n\t *\n\t *  As an implementation limitation right now, you can only specify one\n\t *  override. This is sufficient to allow construction of different\n\t *  parse trees for ambiguous input. It means re-parsing the entire input\n\t *  in general because you're never sure where an ambiguous sequence would\n\t *  live in the various parse trees. For example, in one interpretation,\n\t *  an ambiguous input sequence would be matched completely in expression\n\t *  but in another it could match all the way back to the root.\n\t *\n\t *  s : e '!'? ;\n\t *  e : ID\n\t *    | ID '!'\n\t *    ;\n\t *\n\t *  Here, x! can be matched as (s (e ID) !) or (s (e ID !)). In the first\n\t *  case, the ambiguous sequence is fully contained only by the root.\n\t *  In the second case, the ambiguous sequences fully contained within just\n\t *  e, as in: (e ID !).\n\t *\n\t *  Rather than trying to optimize this and make\n\t *  some intelligent decisions for optimization purposes, I settled on\n\t *  just re-parsing the whole input and then using\n\t *  {link Trees#getRootOfSubtreeEnclosingRegion} to find the minimal\n\t *  subtree that contains the ambiguous sequence. I originally tried to\n\t *  record the call stack at the point the parser detected and ambiguity but\n\t *  left recursive rules create a parse tree stack that does not reflect\n\t *  the actual call stack. That impedance mismatch was enough to make\n\t *  it it challenging to restart the parser at a deeply nested rule\n\t *  invocation.\n\t *\n\t *  Only parser interpreters can override decisions so as to avoid inserting\n\t *  override checking code in the critical ALL(*) prediction execution path.\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic void addDecisionOverride(int decision, int tokenIndex, int forcedAlt) {\n\t\toverrideDecision = decision;\n\t\toverrideDecisionInputIndex = tokenIndex;\n\t\toverrideDecisionAlt = forcedAlt;\n\t}\n\n\tpublic InterpreterRuleContext getOverrideDecisionRoot() {\n\t\treturn overrideDecisionRoot;\n\t}\n\n\t/** Rely on the error handler for this parser but, if no tokens are consumed\n\t *  to recover, add an error node. Otherwise, nothing is seen in the parse\n\t *  tree.\n\t */\n\tprotected void recover(RecognitionException e) {\n\t\tint i = _input.index();\n\t\tgetErrorHandler().recover(this, e);\n\t\tif ( _input.index()==i ) {\n\t\t\t// no input consumed, better add an error node\n\t\t\tif ( e instanceof InputMismatchException ) {\n\t\t\t\tInputMismatchException ime = (InputMismatchException)e;\n\t\t\t\tToken tok = e.getOffendingToken();\n\t\t\t\tint expectedTokenType = Token.INVALID_TYPE;\n\t\t\t\tif ( !ime.getExpectedTokens().isNil() ) {\n\t\t\t\t\texpectedTokenType = ime.getExpectedTokens().getMinElement(); // get any element\n\t\t\t\t}\n\t\t\t\tToken errToken =\n\t\t\t\t\tgetTokenFactory().create(new Pair<TokenSource, CharStream>(tok.getTokenSource(), tok.getTokenSource().getInputStream()),\n\t\t\t\t                             expectedTokenType, tok.getText(),\n\t\t\t\t                             Token.DEFAULT_CHANNEL,\n\t\t\t\t                            -1, -1, // invalid start/stop\n\t\t\t\t                             tok.getLine(), tok.getCharPositionInLine());\n\t\t\t\t_ctx.addErrorNode(createErrorNode(_ctx,errToken));\n\t\t\t}\n\t\t\telse { // NoViableAlt\n\t\t\t\tToken tok = e.getOffendingToken();\n\t\t\t\tToken errToken =\n\t\t\t\t\tgetTokenFactory().create(new Pair<TokenSource, CharStream>(tok.getTokenSource(), tok.getTokenSource().getInputStream()),\n\t\t\t\t                             Token.INVALID_TYPE, tok.getText(),\n\t\t\t\t                             Token.DEFAULT_CHANNEL,\n\t\t\t\t                            -1, -1, // invalid start/stop\n\t\t\t\t                             tok.getLine(), tok.getCharPositionInLine());\n\t\t\t\t_ctx.addErrorNode(createErrorNode(_ctx,errToken));\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected Token recoverInline() {\n\t\treturn _errHandler.recoverInline(this);\n\t}\n\n\t/** Return the root of the parse, which can be useful if the parser\n\t *  bails out. You still can access the top node. Note that,\n\t *  because of the way left recursive rules add children, it's possible\n\t *  that the root will not have any children if the start rule immediately\n\t *  called and left recursive rule that fails.\n\t *\n\t * @since 4.5.1\n\t */\n\tpublic InterpreterRuleContext getRootContext() {\n\t\treturn rootContext;\n\t}\n}\n\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ParserRuleContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.ErrorNodeImpl;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.ParseTreeListener;\nimport org.antlr.v4.runtime.tree.TerminalNode;\nimport org.antlr.v4.runtime.tree.TerminalNodeImpl;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\n/** A rule invocation record for parsing.\n *\n *  Contains all of the information about the current rule not stored in the\n *  RuleContext. It handles parse tree children list, Any ATN state\n *  tracing, and the default values available for rule invocations:\n *  start, stop, rule index, current alt number.\n *\n *  Subclasses made for each rule and grammar track the parameters,\n *  return values, locals, and labels specific to that rule. These\n *  are the objects that are returned from rules.\n *\n *  Note text is not an actual field of a rule return value; it is computed\n *  from start and stop using the input stream's toString() method.  I\n *  could add a ctor to this so that we can pass in and store the input\n *  stream, but I'm not sure we want to do that.  It would seem to be undefined\n *  to get the .text property anyway if the rule matches tokens from multiple\n *  input streams.\n *\n *  I do not use getters for fields of objects that are used simply to\n *  group values such as this aggregate.  The getters/setters are there to\n *  satisfy the superclass interface.\n */\npublic class ParserRuleContext extends RuleContext {\n\tpublic static final ParserRuleContext EMPTY = new ParserRuleContext();\n\n\t/** If we are debugging or building a parse tree for a visitor,\n\t *  we need to track all of the tokens and rule invocations associated\n\t *  with this rule's context. This is empty for parsing w/o tree constr.\n\t *  operation because we don't the need to track the details about\n\t *  how we parse this rule.\n\t */\n\tpublic List<ParseTree> children;\n\n\t/** For debugging/tracing purposes, we want to track all of the nodes in\n\t *  the ATN traversed by the parser for a particular rule.\n\t *  This list indicates the sequence of ATN nodes used to match\n\t *  the elements of the children list. This list does not include\n\t *  ATN nodes and other rules used to match rule invocations. It\n\t *  traces the rule invocation node itself but nothing inside that\n\t *  other rule's ATN submachine.\n\t *\n\t *  There is NOT a one-to-one correspondence between the children and\n\t *  states list. There are typically many nodes in the ATN traversed\n\t *  for each element in the children list. For example, for a rule\n\t *  invocation there is the invoking state and the following state.\n\t *\n\t *  The parser setState() method updates field s and adds it to this list\n\t *  if we are debugging/tracing.\n\t *\n\t *  This does not trace states visited during prediction.\n\t */\n//\tpublic List<Integer> states;\n\n\tpublic Token start, stop;\n\n\t/**\n\t * The exception that forced this rule to return. If the rule successfully\n\t * completed, this is {@code null}.\n\t */\n\tpublic RecognitionException exception;\n\n\tpublic ParserRuleContext() { }\n\n\t/** COPY a ctx (I'm deliberately not using copy constructor) to avoid\n\t *  confusion with creating node with parent. Does not copy children\n\t *  (except error leaves).\n\t *\n\t *  This is used in the generated parser code to flip a generic XContext\n\t *  node for rule X to a YContext for alt label Y. In that sense, it is\n\t *  not really a generic copy function.\n\t *\n\t *  If we do an error sync() at start of a rule, we might add error nodes\n\t *  to the generic XContext so this function must copy those nodes to\n\t *  the YContext as well else they are lost!\n\t */\n\tpublic void copyFrom(ParserRuleContext ctx) {\n\t\tthis.parent = ctx.parent;\n\t\tthis.invokingState = ctx.invokingState;\n\n\t\tthis.start = ctx.start;\n\t\tthis.stop = ctx.stop;\n\n\t\t// copy any error nodes to alt label node\n\t\tif ( ctx.children!=null ) {\n\t\t\tthis.children = new ArrayList<>();\n\t\t\t// reset parent pointer for any error nodes\n\t\t\tfor (ParseTree child : ctx.children) {\n\t\t\t\tif ( child instanceof ErrorNode ) {\n\t\t\t\t\taddChild((ErrorNode)child);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ParserRuleContext(ParserRuleContext parent, int invokingStateNumber) {\n\t\tsuper(parent, invokingStateNumber);\n\t}\n\n\t// Double dispatch methods for listeners\n\n\tpublic void enterRule(ParseTreeListener listener) { }\n\tpublic void exitRule(ParseTreeListener listener) { }\n\n\t/** Add a parse tree node to this as a child.  Works for\n\t *  internal and leaf nodes. Does not set parent link;\n\t *  other add methods must do that. Other addChild methods\n\t *  call this.\n\t *\n\t *  We cannot set the parent pointer of the incoming node\n\t *  because the existing interfaces do not have a setParent()\n\t *  method and I don't want to break backward compatibility for this.\n\t *\n\t *  @since 4.7\n\t */\n\tpublic <T extends ParseTree> T addAnyChild(T t) {\n\t\tif ( children==null ) children = new ArrayList<>();\n\t\tchildren.add(t);\n\t\treturn t;\n\t}\n\n\tpublic RuleContext addChild(RuleContext ruleInvocation) {\n\t\treturn addAnyChild(ruleInvocation);\n\t}\n\n\t/** Add a token leaf node child and force its parent to be this node. */\n\tpublic TerminalNode addChild(TerminalNode t) {\n\t\tt.setParent(this);\n\t\treturn addAnyChild(t);\n\t}\n\n\t/** Add an error node child and force its parent to be this node.\n\t *\n\t * @since 4.7\n\t */\n\tpublic ErrorNode addErrorNode(ErrorNode errorNode) {\n\t\terrorNode.setParent(this);\n\t\treturn addAnyChild(errorNode);\n\t}\n\n\t/** Add a child to this node based upon matchedToken. It\n\t *  creates a TerminalNodeImpl rather than using\n\t *  {@link Parser#createTerminalNode(ParserRuleContext, Token)}. I'm leaving this\n     *  in for compatibility but the parser doesn't use this anymore.\n\t */\n\t@Deprecated\n\tpublic TerminalNode addChild(Token matchedToken) {\n\t\tTerminalNodeImpl t = new TerminalNodeImpl(matchedToken);\n\t\taddAnyChild(t);\n\t\tt.setParent(this);\n\t\treturn t;\n\t}\n\n\t/** Add a child to this node based upon badToken.  It\n\t *  creates a ErrorNodeImpl rather than using\n\t *  {@link Parser#createErrorNode(ParserRuleContext, Token)}. I'm leaving this\n\t *  in for compatibility but the parser doesn't use this anymore.\n\t */\n\t@Deprecated\n\tpublic ErrorNode addErrorNode(Token badToken) {\n\t\tErrorNodeImpl t = new ErrorNodeImpl(badToken);\n\t\taddAnyChild(t);\n\t\tt.setParent(this);\n\t\treturn t;\n\t}\n\n//\tpublic void trace(int s) {\n//\t\tif ( states==null ) states = new ArrayList<Integer>();\n//\t\tstates.add(s);\n//\t}\n\n\t/** Used by enterOuterAlt to toss out a RuleContext previously added as\n\t *  we entered a rule. If we have # label, we will need to remove\n\t *  generic ruleContext object.\n\t */\n\tpublic void removeLastChild() {\n\t\tif ( children!=null ) {\n\t\t\tchildren.remove(children.size()-1);\n\t\t}\n\t}\n\n\t@Override\n\t/** Override to make type more specific */\n\tpublic ParserRuleContext getParent() {\n\t\treturn (ParserRuleContext)super.getParent();\n\t}\n\n\t@Override\n\tpublic ParseTree getChild(int i) {\n\t\treturn children!=null && i>=0 && i<children.size() ? children.get(i) : null;\n\t}\n\n\tpublic <T extends ParseTree> T getChild(Class<? extends T> ctxType, int i) {\n\t\tif ( children==null || i < 0 || i >= children.size() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tint j = -1; // what element have we found with ctxType?\n\t\tfor (ParseTree o : children) {\n\t\t\tif ( ctxType.isInstance(o) ) {\n\t\t\t\tj++;\n\t\t\t\tif ( j == i ) {\n\t\t\t\t\treturn ctxType.cast(o);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic TerminalNode getToken(int ttype, int i) {\n\t\tif ( children==null || i < 0 || i >= children.size() ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tint j = -1; // what token with ttype have we found?\n\t\tfor (ParseTree o : children) {\n\t\t\tif ( o instanceof TerminalNode ) {\n\t\t\t\tTerminalNode tnode = (TerminalNode)o;\n\t\t\t\tToken symbol = tnode.getSymbol();\n\t\t\t\tif ( symbol.getType()==ttype ) {\n\t\t\t\t\tj++;\n\t\t\t\t\tif ( j == i ) {\n\t\t\t\t\t\treturn tnode;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic List<TerminalNode> getTokens(int ttype) {\n\t\tif ( children==null ) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<TerminalNode> tokens = null;\n\t\tfor (ParseTree o : children) {\n\t\t\tif ( o instanceof TerminalNode ) {\n\t\t\t\tTerminalNode tnode = (TerminalNode)o;\n\t\t\t\tToken symbol = tnode.getSymbol();\n\t\t\t\tif ( symbol.getType()==ttype ) {\n\t\t\t\t\tif ( tokens==null ) {\n\t\t\t\t\t\ttokens = new ArrayList<TerminalNode>();\n\t\t\t\t\t}\n\t\t\t\t\ttokens.add(tnode);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ( tokens==null ) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\treturn tokens;\n\t}\n\n\tpublic <T extends ParserRuleContext> T getRuleContext(Class<? extends T> ctxType, int i) {\n\t\treturn getChild(ctxType, i);\n\t}\n\n\tpublic <T extends ParserRuleContext> List<T> getRuleContexts(Class<? extends T> ctxType) {\n\t\tif ( children==null ) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tList<T> contexts = null;\n\t\tfor (ParseTree o : children) {\n\t\t\tif ( ctxType.isInstance(o) ) {\n\t\t\t\tif ( contexts==null ) {\n\t\t\t\t\tcontexts = new ArrayList<T>();\n\t\t\t\t}\n\n\t\t\t\tcontexts.add(ctxType.cast(o));\n\t\t\t}\n\t\t}\n\n\t\tif ( contexts==null ) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\treturn contexts;\n\t}\n\n\t@Override\n\tpublic int getChildCount() { return children!=null ? children.size() : 0; }\n\n\t@Override\n\tpublic Interval getSourceInterval() {\n\t\tif ( start == null ) {\n\t\t\treturn Interval.INVALID;\n\t\t}\n\t\tif ( stop==null || stop.getTokenIndex()<start.getTokenIndex() ) {\n\t\t\treturn Interval.of(start.getTokenIndex(), start.getTokenIndex()-1); // empty\n\t\t}\n\t\treturn Interval.of(start.getTokenIndex(), stop.getTokenIndex());\n\t}\n\n\t/**\n\t * Get the initial token in this context.\n\t * Note that the range from start to stop is inclusive, so for rules that do not consume anything\n\t * (for example, zero length or error productions) this token may exceed stop.\n\t */\n\tpublic Token getStart() { return start; }\n\t/**\n\t * Get the final token in this context.\n\t * Note that the range from start to stop is inclusive, so for rules that do not consume anything\n\t * (for example, zero length or error productions) this token may precede start.\n\t */\n\tpublic Token getStop() { return stop; }\n\n\t/** Used for rule context info debugging during parse-time, not so much for ATN debugging */\n\tpublic String toInfoString(Parser recognizer) {\n\t\tList<String> rules = recognizer.getRuleInvocationStack(this);\n\t\tCollections.reverse(rules);\n\t\treturn \"ParserRuleContext\"+rules+\"{\" +\n\t\t\t\"start=\" + start +\n\t\t\t\", stop=\" + stop +\n\t\t\t'}';\n\t}\n}\n\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/ProxyErrorListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.dfa.DFA;\n\nimport java.util.BitSet;\nimport java.util.Collection;\n\n/**\n * This implementation of {@link ANTLRErrorListener} dispatches all calls to a\n * collection of delegate listeners. This reduces the effort required to support multiple\n * listeners.\n *\n * @author Sam Harwell\n */\npublic class ProxyErrorListener implements ANTLRErrorListener {\n\tprivate final Collection<? extends ANTLRErrorListener> delegates;\n\n\tpublic ProxyErrorListener(Collection<? extends ANTLRErrorListener> delegates) {\n\t\tif (delegates == null) {\n\t\t\tthrow new NullPointerException(\"delegates\");\n\t\t}\n\n\t\tthis.delegates = delegates;\n\t}\n\n\t@Override\n\tpublic void syntaxError(Recognizer<?, ?> recognizer,\n\t\t\t\t\t\t\tObject offendingSymbol,\n\t\t\t\t\t\t\tint line,\n\t\t\t\t\t\t\tint charPositionInLine,\n\t\t\t\t\t\t\tString msg,\n\t\t\t\t\t\t\tRecognitionException e)\n\t{\n\t\tfor (ANTLRErrorListener listener : delegates) {\n\t\t\tlistener.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void reportAmbiguity(Parser recognizer,\n\t\t\t\t\t\t\t\tDFA dfa,\n\t\t\t\t\t\t\t\tint startIndex,\n\t\t\t\t\t\t\t\tint stopIndex,\n\t\t\t\t\t\t\t\tboolean exact,\n\t\t\t\t\t\t\t\tBitSet ambigAlts,\n\t\t\t\t\t\t\t\tATNConfigSet configs)\n\t{\n\t\tfor (ANTLRErrorListener listener : delegates) {\n\t\t\tlistener.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void reportAttemptingFullContext(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t\tDFA dfa,\n\t\t\t\t\t\t\t\t\t\t\tint startIndex,\n\t\t\t\t\t\t\t\t\t\t\tint stopIndex,\n\t\t\t\t\t\t\t\t\t\t\tBitSet conflictingAlts,\n\t\t\t\t\t\t\t\t\t\t\tATNConfigSet configs)\n\t{\n\t\tfor (ANTLRErrorListener listener : delegates) {\n\t\t\tlistener.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void reportContextSensitivity(Parser recognizer,\n\t\t\t\t\t\t\t\t\t\t DFA dfa,\n\t\t\t\t\t\t\t\t\t\t int startIndex,\n\t\t\t\t\t\t\t\t\t\t int stopIndex,\n\t\t\t\t\t\t\t\t\t\t int prediction,\n\t\t\t\t\t\t\t\t\t\t ATNConfigSet configs)\n\t{\n\t\tfor (ANTLRErrorListener listener : delegates) {\n\t\t\tlistener.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/RecognitionException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\n/** The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n *  3 kinds of errors: prediction errors, failed predicate errors, and\n *  mismatched input errors. In each case, the parser knows where it is\n *  in the input, where it is in the ATN, the rule invocation stack,\n *  and what kind of problem occurred.\n */\npublic class RecognitionException extends RuntimeException {\n\t/** The {@link Recognizer} where this exception originated. */\n\tprivate final Recognizer<?, ?> recognizer;\n\n\tprivate final RuleContext ctx;\n\n\tprivate final IntStream input;\n\n\t/**\n\t * The current {@link Token} when an error occurred. Since not all streams\n\t * support accessing symbols by index, we have to track the {@link Token}\n\t * instance itself.\n\t */\n\tprivate Token offendingToken;\n\n\tprivate int offendingState = -1;\n\n\tpublic RecognitionException(Recognizer<?, ?> recognizer,\n\t\t\t\t\t\t\t\tIntStream input,\n\t\t\t\t\t\t\t\tParserRuleContext ctx)\n\t{\n\t\tthis.recognizer = recognizer;\n\t\tthis.input = input;\n\t\tthis.ctx = ctx;\n\t\tif ( recognizer!=null ) this.offendingState = recognizer.getState();\n\t}\n\n\tpublic RecognitionException(String message,\n\t\t\t\t\t\t\t\tRecognizer<?, ?> recognizer,\n\t\t\t\t\t\t\t\tIntStream input,\n\t\t\t\t\t\t\t\tParserRuleContext ctx)\n\t{\n\t\tsuper(message);\n\t\tthis.recognizer = recognizer;\n\t\tthis.input = input;\n\t\tthis.ctx = ctx;\n\t\tif ( recognizer!=null ) this.offendingState = recognizer.getState();\n\t}\n\n\t/**\n\t * Get the ATN state number the parser was in at the time the error\n\t * occurred. For {@link NoViableAltException} and\n\t * {@link LexerNoViableAltException} exceptions, this is the\n\t * {@link DecisionState} number. For others, it is the state whose outgoing\n\t * edge we couldn't match.\n\t *\n\t * <p>If the state number is not known, this method returns -1.</p>\n\t */\n\tpublic int getOffendingState() {\n\t\treturn offendingState;\n\t}\n\n\tprotected final void setOffendingState(int offendingState) {\n\t\tthis.offendingState = offendingState;\n\t}\n\n\t/**\n\t * Gets the set of input symbols which could potentially follow the\n\t * previously matched symbol at the time this exception was thrown.\n\t *\n\t * <p>If the set of expected tokens is not known and could not be computed,\n\t * this method returns {@code null}.</p>\n\t *\n\t * @return The set of token types that could potentially follow the current\n\t * state in the ATN, or {@code null} if the information is not available.\n\t */\n\tpublic IntervalSet getExpectedTokens() {\n\t\tif (recognizer != null) {\n\t\t\treturn recognizer.getATN().getExpectedTokens(offendingState, ctx);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Gets the {@link RuleContext} at the time this exception was thrown.\n\t *\n\t * <p>If the context is not available, this method returns {@code null}.</p>\n\t *\n\t * @return The {@link RuleContext} at the time this exception was thrown.\n\t * If the context is not available, this method returns {@code null}.\n\t */\n\tpublic RuleContext getCtx() {\n\t\treturn ctx;\n\t}\n\n\t/**\n\t * Gets the input stream which is the symbol source for the recognizer where\n\t * this exception was thrown.\n\t *\n\t * <p>If the input stream is not available, this method returns {@code null}.</p>\n\t *\n\t * @return The input stream which is the symbol source for the recognizer\n\t * where this exception was thrown, or {@code null} if the stream is not\n\t * available.\n\t */\n\tpublic IntStream getInputStream() {\n\t\treturn input;\n\t}\n\n\n\tpublic Token getOffendingToken() {\n\t\treturn offendingToken;\n\t}\n\n\tprotected final void setOffendingToken(Token offendingToken) {\n\t\tthis.offendingToken = offendingToken;\n\t}\n\n\t/**\n\t * Gets the {@link Recognizer} where this exception occurred.\n\t *\n\t * <p>If the recognizer is not available, this method returns {@code null}.</p>\n\t *\n\t * @return The recognizer where this exception occurred, or {@code null} if\n\t * the recognizer is not available.\n\t */\n\tpublic Recognizer<?, ?> getRecognizer() {\n\t\treturn recognizer;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/Recognizer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNSimulator;\nimport org.antlr.v4.runtime.atn.ParseInfo;\nimport org.antlr.v4.runtime.misc.Utils;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.WeakHashMap;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\npublic abstract class Recognizer<Symbol, ATNInterpreter extends ATNSimulator> {\n\tpublic static final int EOF=-1;\n\n\tprivate static final Map<Vocabulary, Map<String, Integer>> tokenTypeMapCache =\n\t\tnew WeakHashMap<Vocabulary, Map<String, Integer>>();\n\tprivate static final Map<String[], Map<String, Integer>> ruleIndexMapCache =\n\t\tnew WeakHashMap<String[], Map<String, Integer>>();\n\n\n\tprivate List<ANTLRErrorListener> _listeners =\n\t\tnew CopyOnWriteArrayList<ANTLRErrorListener>() {{\n\t\t\tadd(ConsoleErrorListener.INSTANCE);\n\t\t}};\n\n\tprotected ATNInterpreter _interp;\n\n\tprivate int _stateNumber = -1;\n\n\t/** Used to print out token names like ID during debugging and\n\t *  error reporting.  The generated parsers implement a method\n\t *  that overrides this to point to their String[] tokenNames.\n\t *\n\t * @deprecated Use {@link #getVocabulary()} instead.\n\t */\n\t@Deprecated\n\tpublic abstract String[] getTokenNames();\n\n\tpublic abstract String[] getRuleNames();\n\n\t/**\n\t * Get the vocabulary used by the recognizer.\n\t *\n\t * @return A {@link Vocabulary} instance providing information about the\n\t * vocabulary used by the grammar.\n\t */\n\t@SuppressWarnings(\"deprecation\")\n\tpublic Vocabulary getVocabulary() {\n\t\treturn VocabularyImpl.fromTokenNames(getTokenNames());\n\t}\n\n\t/**\n\t * Get a map from token names to token types.\n\t *\n\t * <p>Used for XPath and tree pattern compilation.</p>\n\t */\n\tpublic Map<String, Integer> getTokenTypeMap() {\n\t\tVocabulary vocabulary = getVocabulary();\n\t\tsynchronized (tokenTypeMapCache) {\n\t\t\tMap<String, Integer> result = tokenTypeMapCache.get(vocabulary);\n\t\t\tif (result == null) {\n\t\t\t\tresult = new HashMap<String, Integer>();\n\t\t\t\tfor (int i = 0; i <= getATN().maxTokenType; i++) {\n\t\t\t\t\tString literalName = vocabulary.getLiteralName(i);\n\t\t\t\t\tif (literalName != null) {\n\t\t\t\t\t\tresult.put(literalName, i);\n\t\t\t\t\t}\n\n\t\t\t\t\tString symbolicName = vocabulary.getSymbolicName(i);\n\t\t\t\t\tif (symbolicName != null) {\n\t\t\t\t\t\tresult.put(symbolicName, i);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresult.put(\"EOF\", Token.EOF);\n\t\t\t\tresult = Collections.unmodifiableMap(result);\n\t\t\t\ttokenTypeMapCache.put(vocabulary, result);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t/**\n\t * Get a map from rule names to rule indexes.\n\t *\n\t * <p>Used for XPath and tree pattern compilation.</p>\n\t */\n\tpublic Map<String, Integer> getRuleIndexMap() {\n\t\tString[] ruleNames = getRuleNames();\n\t\tif (ruleNames == null) {\n\t\t\tthrow new UnsupportedOperationException(\"The current recognizer does not provide a list of rule names.\");\n\t\t}\n\n\t\tsynchronized (ruleIndexMapCache) {\n\t\t\tMap<String, Integer> result = ruleIndexMapCache.get(ruleNames);\n\t\t\tif (result == null) {\n\t\t\t\tresult = Collections.unmodifiableMap(Utils.toMap(ruleNames));\n\t\t\t\truleIndexMapCache.put(ruleNames, result);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tpublic int getTokenType(String tokenName) {\n\t\tInteger ttype = getTokenTypeMap().get(tokenName);\n\t\tif ( ttype!=null ) return ttype;\n\t\treturn Token.INVALID_TYPE;\n\t}\n\n\t/**\n\t * If this recognizer was generated, it will have a serialized ATN\n\t * representation of the grammar.\n\t *\n\t * <p>For interpreters, we don't know their serialized ATN despite having\n\t * created the interpreter from it.</p>\n\t */\n\tpublic String getSerializedATN() {\n\t\tthrow new UnsupportedOperationException(\"there is no serialized ATN\");\n\t}\n\n\t/** For debugging and other purposes, might want the grammar name.\n\t *  Have ANTLR generate an implementation for this method.\n\t */\n\tpublic abstract String getGrammarFileName();\n\n\t/**\n\t * Get the {@link ATN} used by the recognizer for prediction.\n\t *\n\t * @return The {@link ATN} used by the recognizer for prediction.\n\t */\n\tpublic abstract ATN getATN();\n\n\t/**\n\t * Get the ATN interpreter used by the recognizer for prediction.\n\t *\n\t * @return The ATN interpreter used by the recognizer for prediction.\n\t */\n\tpublic ATNInterpreter getInterpreter() {\n\t\treturn _interp;\n\t}\n\n\t/** If profiling during the parse/lex, this will return DecisionInfo records\n\t *  for each decision in recognizer in a ParseInfo object.\n\t *\n\t * @since 4.3\n\t */\n\tpublic ParseInfo getParseInfo() {\n\t\treturn null;\n\t}\n\n\t/**\n\t * Set the ATN interpreter used by the recognizer for prediction.\n\t *\n\t * @param interpreter The ATN interpreter used by the recognizer for\n\t * prediction.\n\t */\n\tpublic void setInterpreter(ATNInterpreter interpreter) {\n\t\t_interp = interpreter;\n\t}\n\n\t/** What is the error header, normally line/character position information? */\n\tpublic String getErrorHeader(RecognitionException e) {\n\t\tint line = e.getOffendingToken().getLine();\n\t\tint charPositionInLine = e.getOffendingToken().getCharPositionInLine();\n\t\treturn \"line \"+line+\":\"+charPositionInLine;\n\t}\n\n\t/** How should a token be displayed in an error message? The default\n\t *  is to display just the text, but during development you might\n\t *  want to have a lot of information spit out.  Override in that case\n\t *  to use t.toString() (which, for CommonToken, dumps everything about\n\t *  the token). This is better than forcing you to override a method in\n\t *  your token objects because you don't have to go modify your lexer\n\t *  so that it creates a new Java type.\n\t *\n\t * @deprecated This method is not called by the ANTLR 4 Runtime. Specific\n\t * implementations of {@link ANTLRErrorStrategy} may provide a similar\n\t * feature when necessary. For example, see\n\t * {@link DefaultErrorStrategy#getTokenErrorDisplay}.\n\t */\n\t@Deprecated\n\tpublic String getTokenErrorDisplay(Token t) {\n\t\tif ( t==null ) return \"<no token>\";\n\t\tString s = t.getText();\n\t\tif ( s==null ) {\n\t\t\tif ( t.getType()==Token.EOF ) {\n\t\t\t\ts = \"<EOF>\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\ts = \"<\"+t.getType()+\">\";\n\t\t\t}\n\t\t}\n\t\ts = s.replace(\"\\n\",\"\\\\n\");\n\t\ts = s.replace(\"\\r\",\"\\\\r\");\n\t\ts = s.replace(\"\\t\",\"\\\\t\");\n\t\treturn \"'\"+s+\"'\";\n\t}\n\n\t/**\n\t * @exception NullPointerException if {@code listener} is {@code null}.\n\t */\n\tpublic void addErrorListener(ANTLRErrorListener listener) {\n\t\tif (listener == null) {\n\t\t\tthrow new NullPointerException(\"listener cannot be null.\");\n\t\t}\n\n\t\t_listeners.add(listener);\n\t}\n\n\tpublic void removeErrorListener(ANTLRErrorListener listener) {\n\t\t_listeners.remove(listener);\n\t}\n\n\tpublic void removeErrorListeners() {\n\t\t_listeners.clear();\n\t}\n\n\n\tpublic List<? extends ANTLRErrorListener> getErrorListeners() {\n\t\treturn _listeners;\n\t}\n\n\tpublic ANTLRErrorListener getErrorListenerDispatch() {\n\t\treturn new ProxyErrorListener(getErrorListeners());\n\t}\n\n\t// subclass needs to override these if there are sempreds or actions\n\t// that the ATN interp needs to execute\n\tpublic boolean sempred(RuleContext _localctx, int ruleIndex, int actionIndex) {\n\t\treturn true;\n\t}\n\n\tpublic boolean precpred(RuleContext localctx, int precedence) {\n\t\treturn true;\n\t}\n\n\tpublic void action(RuleContext _localctx, int ruleIndex, int actionIndex) {\n\t}\n\n\tpublic final int getState() {\n\t\treturn _stateNumber;\n\t}\n\n\t/** Indicate that the recognizer has changed internal state that is\n\t *  consistent with the ATN state passed in.  This way we always know\n\t *  where we are in the ATN as the parser goes along. The rule\n\t *  context objects form a stack that lets us see the stack of\n\t *  invoking rules. Combine this and we have complete ATN\n\t *  configuration information.\n\t */\n\tpublic final void setState(int atnState) {\n//\t\tSystem.err.println(\"setState \"+atnState);\n\t\t_stateNumber = atnState;\n//\t\tif ( traceATNStates ) _ctx.trace(atnState);\n\t}\n\n\tpublic abstract IntStream getInputStream();\n\n\tpublic abstract void setInputStream(IntStream input);\n\n\n\tpublic abstract TokenFactory<?> getTokenFactory();\n\n\tpublic abstract void setTokenFactory(TokenFactory<?> input);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/RuleContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.ParseTreeVisitor;\nimport org.antlr.v4.runtime.tree.RuleNode;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.Arrays;\nimport java.util.List;\n\n/** A rule context is a record of a single rule invocation.\n *\n *  We form a stack of these context objects using the parent\n *  pointer. A parent pointer of null indicates that the current\n *  context is the bottom of the stack. The ParserRuleContext subclass\n *  as a children list so that we can turn this data structure into a\n *  tree.\n *\n *  The root node always has a null pointer and invokingState of -1.\n *\n *  Upon entry to parsing, the first invoked rule function creates a\n *  context object (a subclass specialized for that rule such as\n *  SContext) and makes it the root of a parse tree, recorded by field\n *  Parser._ctx.\n *\n *  public final SContext s() throws RecognitionException {\n *      SContext _localctx = new SContext(_ctx, getState()); <-- create new node\n *      enterRule(_localctx, 0, RULE_s);                     <-- push it\n *      ...\n *      exitRule();                                          <-- pop back to _localctx\n *      return _localctx;\n *  }\n *\n *  A subsequent rule invocation of r from the start rule s pushes a\n *  new context object for r whose parent points at s and use invoking\n *  state is the state with r emanating as edge label.\n *\n *  The invokingState fields from a context object to the root\n *  together form a stack of rule indication states where the root\n *  (bottom of the stack) has a -1 sentinel value. If we invoke start\n *  symbol s then call r1, which calls r2, the  would look like\n *  this:\n *\n *     SContext[-1]   <- root node (bottom of the stack)\n *     R1Context[p]   <- p in rule s called r1\n *     R2Context[q]   <- q in rule r1 called r2\n *\n *  So the top of the stack, _ctx, represents a call to the current\n *  rule and it holds the return address from another rule that invoke\n *  to this rule. To invoke a rule, we must always have a current context.\n *\n *  The parent contexts are useful for computing lookahead sets and\n *  getting error information.\n *\n *  These objects are used during parsing and prediction.\n *  For the special case of parsers, we use the subclass\n *  ParserRuleContext.\n *\n *  @see ParserRuleContext\n */\npublic class RuleContext implements RuleNode {\n\t/** What context invoked this rule? */\n\tpublic RuleContext parent;\n\n\t/** What state invoked the rule associated with this context?\n\t *  The \"return address\" is the followState of invokingState\n\t *  If parent is null, this should be -1 this context object represents\n\t *  the start rule.\n\t */\n\tpublic int invokingState = -1;\n\n\tpublic RuleContext() {}\n\n\tpublic RuleContext(RuleContext parent, int invokingState) {\n\t\tthis.parent = parent;\n\t\t//if ( parent!=null ) System.out.println(\"invoke \"+stateNumber+\" from \"+parent);\n\t\tthis.invokingState = invokingState;\n\t}\n\n\tpublic int depth() {\n\t\tint n = 0;\n\t\tRuleContext p = this;\n\t\twhile ( p!=null ) {\n\t\t\tp = p.parent;\n\t\t\tn++;\n\t\t}\n\t\treturn n;\n\t}\n\n\t/** A context is empty if there is no invoking state; meaning nobody called\n\t *  current context.\n\t */\n\tpublic boolean isEmpty() {\n\t\treturn invokingState == -1;\n\t}\n\n\t// satisfy the ParseTree / SyntaxTree interface\n\n\t@Override\n\tpublic Interval getSourceInterval() {\n\t\treturn Interval.INVALID;\n\t}\n\n\t@Override\n\tpublic RuleContext getRuleContext() { return this; }\n\n\t@Override\n\tpublic RuleContext getParent() { return parent; }\n\n\t@Override\n\tpublic RuleContext getPayload() { return this; }\n\n\t/** Return the combined text of all child nodes. This method only considers\n\t *  tokens which have been added to the parse tree.\n\t *  <p>\n\t *  Since tokens on hidden channels (e.g. whitespace or comments) are not\n\t *  added to the parse trees, they will not appear in the output of this\n\t *  method.\n\t */\n\t@Override\n\tpublic String getText() {\n\t\tif (getChildCount() == 0) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < getChildCount(); i++) {\n\t\t\tbuilder.append(getChild(i).getText());\n\t\t}\n\n\t\treturn builder.toString();\n\t}\n\n\tpublic int getRuleIndex() { return -1; }\n\n\t/** For rule associated with this parse tree internal node, return\n\t *  the outer alternative number used to match the input. Default\n\t *  implementation does not compute nor store this alt num. Create\n\t *  a subclass of ParserRuleContext with backing field and set\n\t *  option contextSuperClass.\n\t *  to set it.\n\t *\n\t *  @since 4.5.3\n\t */\n\tpublic int getAltNumber() { return ATN.INVALID_ALT_NUMBER; }\n\n\t/** Set the outer alternative number for this context node. Default\n\t *  implementation does nothing to avoid backing field overhead for\n\t *  trees that don't need it.  Create\n     *  a subclass of ParserRuleContext with backing field and set\n     *  option contextSuperClass.\n\t *\n\t *  @since 4.5.3\n\t */\n\tpublic void setAltNumber(int altNumber) { }\n\n\t/** @since 4.7. {@see ParseTree#setParent} comment */\n\t@Override\n\tpublic void setParent(RuleContext parent) {\n\t\tthis.parent = parent;\n\t}\n\n\t@Override\n\tpublic ParseTree getChild(int i) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic int getChildCount() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic <T> T accept(ParseTreeVisitor<? extends T> visitor) { return visitor.visitChildren(this); }\n\n\t/** Print out a whole tree, not just a node, in LISP format\n\t *  (root child1 .. childN). Print just a node if this is a leaf.\n\t *  We have to know the recognizer so we can get rule names.\n\t */\n\t@Override\n\tpublic String toStringTree(Parser recog) {\n\t\treturn Trees.toStringTree(this, recog);\n\t}\n\n\t/** Print out a whole tree, not just a node, in LISP format\n\t *  (root child1 .. childN). Print just a node if this is a leaf.\n\t */\n\tpublic String toStringTree(List<String> ruleNames) {\n\t\treturn Trees.toStringTree(this, ruleNames);\n\t}\n\n\t@Override\n\tpublic String toStringTree() {\n\t\treturn toStringTree((List<String>)null);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString((List<String>)null, (RuleContext)null);\n\t}\n\n\tpublic final String toString(Recognizer<?,?> recog) {\n\t\treturn toString(recog, ParserRuleContext.EMPTY);\n\t}\n\n\tpublic final String toString(List<String> ruleNames) {\n\t\treturn toString(ruleNames, null);\n\t}\n\n\t// recog null unless ParserRuleContext, in which case we use subclass toString(...)\n\tpublic String toString(Recognizer<?,?> recog, RuleContext stop) {\n\t\tString[] ruleNames = recog != null ? recog.getRuleNames() : null;\n\t\tList<String> ruleNamesList = ruleNames != null ? Arrays.asList(ruleNames) : null;\n\t\treturn toString(ruleNamesList, stop);\n\t}\n\n\tpublic String toString(List<String> ruleNames, RuleContext stop) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tRuleContext p = this;\n\t\tbuf.append(\"[\");\n\t\twhile (p != null && p != stop) {\n\t\t\tif (ruleNames == null) {\n\t\t\t\tif (!p.isEmpty()) {\n\t\t\t\t\tbuf.append(p.invokingState);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tint ruleIndex = p.getRuleIndex();\n\t\t\t\tString ruleName = ruleIndex >= 0 && ruleIndex < ruleNames.size() ? ruleNames.get(ruleIndex) : Integer.toString(ruleIndex);\n\t\t\t\tbuf.append(ruleName);\n\t\t\t}\n\n\t\t\tif (p.parent != null && (ruleNames != null || !p.parent.isEmpty())) {\n\t\t\t\tbuf.append(\" \");\n\t\t\t}\n\n\t\t\tp = p.parent;\n\t\t}\n\n\t\tbuf.append(\"]\");\n\t\treturn buf.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/RuleContextWithAltNum.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.atn.ATN;\n\n/** A handy class for use with\n *\n *  options {contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum;}\n *\n *  that provides a backing field / impl for the outer alternative number\n *  matched for an internal parse tree node.\n *\n *  I'm only putting into Java runtime as I'm certain I'm the only one that\n *  will really every use this.\n */\npublic class RuleContextWithAltNum extends ParserRuleContext {\n\tpublic int altNum;\n\tpublic RuleContextWithAltNum() { altNum = ATN.INVALID_ALT_NUMBER; }\n\n\tpublic RuleContextWithAltNum(ParserRuleContext parent, int invokingStateNumber) {\n\t\tsuper(parent, invokingStateNumber);\n\t}\n\t@Override public int getAltNumber() { return altNum; }\n\t@Override public void setAltNumber(int altNum) { this.altNum = altNum; }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/RuntimeMetaData.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\n/**\n * This class provides access to the current version of the ANTLR 4 runtime\n * library as compile-time and runtime constants, along with methods for\n * checking for matching version numbers and notifying listeners in the case\n * where a version mismatch is detected.\n *\n * <p>\n * The runtime version information is provided by {@link #VERSION} and\n * {@link #getRuntimeVersion()}. Detailed information about these values is\n * provided in the documentation for each member.</p>\n *\n * <p>\n * The runtime version check is implemented by {@link #checkVersion}. Detailed\n * information about incorporating this call into user code, as well as its use\n * in generated code, is provided in the documentation for the method.</p>\n *\n * <p>\n * Version strings x.y and x.y.z are considered \"compatible\" and no error\n * would be generated. Likewise, version strings x.y-SNAPSHOT and x.y.z are\n * considered \"compatible\" because the major and minor components x.y\n * are the same in each.</p>\n *\n * <p>\n * To trap any error messages issued by this code, use System.setErr()\n * in your main() startup code.\n * </p>\n *\n * @since 4.3\n */\npublic class RuntimeMetaData {\n\t/**\n\t * A compile-time constant containing the current version of the ANTLR 4\n\t * runtime library.\n\t *\n\t * <p>\n\t * This compile-time constant value allows generated parsers and other\n\t * libraries to include a literal reference to the version of the ANTLR 4\n\t * runtime library the code was compiled against. At each release, we\n\t * change this value.</p>\n\t *\n\t * <p>Version numbers are assumed to have the form\n\t *\n\t * <em>major</em>.<em>minor</em>.<em>patch</em>.<em>revision</em>-<em>suffix</em>,\n\t *\n\t * with the individual components defined as follows.</p>\n\t *\n\t * <ul>\n\t * <li><em>major</em> is a required non-negative integer, and is equal to\n\t * {@code 4} for ANTLR 4.</li>\n\t * <li><em>minor</em> is a required non-negative integer.</li>\n\t * <li><em>patch</em> is an optional non-negative integer. When\n\t * <em>patch</em> is omitted, the {@code .} (dot) appearing before it is\n\t * also omitted.</li>\n\t * <li><em>revision</em> is an optional non-negative integer, and may only\n\t * be included when <em>patch</em> is also included. When <em>revision</em>\n\t * is omitted, the {@code .} (dot) appearing before it is also omitted.</li>\n\t * <li><em>suffix</em> is an optional string. When <em>suffix</em> is\n\t * omitted, the {@code -} (hyphen-minus) appearing before it is also\n\t * omitted.</li>\n\t * </ul>\n\t */\n\tpublic static final String VERSION = \"4.13.2\";\n\n\t/**\n\t * Gets the currently executing version of the ANTLR 4 runtime library.\n\t *\n\t * <p>\n\t * This method provides runtime access to the {@link #VERSION} field, as\n\t * opposed to directly referencing the field as a compile-time constant.</p>\n\t *\n\t * @return The currently executing version of the ANTLR 4 library\n\t */\n\n\tpublic static String getRuntimeVersion() {\n\t\treturn VERSION;\n\t}\n\n\t/**\n\t * This method provides the ability to detect mismatches between the version\n\t * of ANTLR 4 used to generate a parser, the version of the ANTLR runtime a\n\t * parser was compiled against, and the version of the ANTLR runtime which\n\t * is currently executing.\n\t *\n\t * <p>\n\t * The version check is designed to detect the following two specific\n\t * scenarios.</p>\n\t *\n\t * <ul>\n\t * <li>The ANTLR Tool version used for code generation does not match the\n\t * currently executing runtime version.</li>\n\t * <li>The ANTLR Runtime version referenced at the time a parser was\n\t * compiled does not match the currently executing runtime version.</li>\n\t * </ul>\n\t *\n\t * <p>\n\t * Starting with ANTLR 4.3, the code generator emits a call to this method\n\t * using two constants in each generated lexer and parser: a hard-coded\n\t * constant indicating the version of the tool used to generate the parser\n\t * and a reference to the compile-time constant {@link #VERSION}. At\n\t * runtime, this method is called during the initialization of the generated\n\t * parser to detect mismatched versions, and notify the registered listeners\n\t * prior to creating instances of the parser.</p>\n\t *\n\t * <p>\n\t * This method does not perform any detection or filtering of semantic\n\t * changes between tool and runtime versions. It simply checks for a\n\t * version match and emits an error to stderr if a difference\n\t * is detected.</p>\n\t *\n\t * <p>\n\t * Note that some breaking changes between releases could result in other\n\t * types of runtime exceptions, such as a {@link LinkageError}, prior to\n\t * calling this method. In these cases, the underlying version mismatch will\n\t * not be reported here. This method is primarily intended to\n\t * notify users of potential semantic changes between releases that do not\n\t * result in binary compatibility problems which would be detected by the\n\t * class loader. As with semantic changes, changes that break binary\n\t * compatibility between releases are mentioned in the release notes\n\t * accompanying the affected release.</p>\n\t *\n\t * <p>\n\t * <strong>Additional note for target developers:</strong> The version check\n\t * implemented by this class is designed to address specific compatibility\n\t * concerns that may arise during the execution of Java applications. Other\n\t * targets should consider the implementation of this method in the context\n\t * of that target's known execution environment, which may or may not\n\t * resemble the design provided for the Java target.</p>\n\t *\n\t * @param generatingToolVersion The version of the tool used to generate a parser.\n\t * This value may be null when called from user code that was not generated\n\t * by, and does not reference, the ANTLR 4 Tool itself.\n\t * @param compileTimeVersion The version of the runtime the parser was\n\t * compiled against. This should always be passed using a direct reference\n\t * to {@link #VERSION}.\n\t */\n\tpublic static void checkVersion(String generatingToolVersion, String compileTimeVersion) {\n\t\tString runtimeVersion = VERSION;\n\t\tboolean runtimeConflictsWithGeneratingTool = false;\n\t\tboolean runtimeConflictsWithCompileTimeTool = false;\n\n\t\tif ( generatingToolVersion!=null ) {\n\t\t\truntimeConflictsWithGeneratingTool =\n\t\t\t\t!runtimeVersion.equals(generatingToolVersion) &&\n\t\t\t\t!getMajorMinorVersion(runtimeVersion).equals(getMajorMinorVersion(generatingToolVersion));\n\t\t}\n\n\t\truntimeConflictsWithCompileTimeTool =\n\t\t\t!runtimeVersion.equals(compileTimeVersion) &&\n\t\t\t!getMajorMinorVersion(runtimeVersion).equals(getMajorMinorVersion(compileTimeVersion));\n\n\t\tif ( runtimeConflictsWithGeneratingTool ) {\n\t\t\tSystem.err.printf(\"ANTLR Tool version %s used for code generation does not match the current runtime version %s%n\",\n\t\t\t\t\t\t\t  generatingToolVersion, runtimeVersion);\n\t\t}\n\t\tif ( runtimeConflictsWithCompileTimeTool ) {\n\t\t\tSystem.err.printf(\"ANTLR Runtime version %s used for parser compilation does not match the current runtime version %s%n\",\n\t\t\t\t\t\t\t  compileTimeVersion, runtimeVersion);\n\t\t}\n\t}\n\n\t/**\n\t * Gets the major and minor version numbers from a version string. For\n\t * details about the syntax of the input {@code version}.\n\t * E.g., from x.y.z return x.y.\n\t *\n\t * @param version The complete version string.\n\t * @return A string of the form <em>major</em>.<em>minor</em> containing\n\t * only the major and minor components of the version string.\n\t */\n\tpublic static String getMajorMinorVersion(String version) {\n\t\tint firstDot = version.indexOf('.');\n\t\tint secondDot = firstDot >= 0 ? version.indexOf('.', firstDot + 1) : -1;\n\t\tint firstDash = version.indexOf('-');\n\t\tint referenceLength = version.length();\n\t\tif (secondDot >= 0) {\n\t\t\treferenceLength = Math.min(referenceLength, secondDot);\n\t\t}\n\n\t\tif (firstDash >= 0) {\n\t\t\treferenceLength = Math.min(referenceLength, firstDash);\n\t\t}\n\n\t\treturn version.substring(0, referenceLength);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/Token.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\n/** A token has properties: text, type, line, character position in the line\n *  (so we can ignore tabs), token channel, index, and source from which\n *  we obtained this token.\n */\npublic interface Token {\n\tpublic static final int INVALID_TYPE = 0;\n\n    /** During lookahead operations, this \"token\" signifies we hit rule end ATN state\n     *  and did not follow it despite needing to.\n     */\n    public static final int EPSILON = -2;\n\n\tpublic static final int MIN_USER_TOKEN_TYPE = 1;\n\n    public static final int EOF = IntStream.EOF;\n\n\t/** All tokens go to the parser (unless skip() is called in that rule)\n\t *  on a particular \"channel\".  The parser tunes to a particular channel\n\t *  so that whitespace etc... can go to the parser on a \"hidden\" channel.\n\t */\n\tpublic static final int DEFAULT_CHANNEL = 0;\n\n\t/** Anything on different channel than DEFAULT_CHANNEL is not parsed\n\t *  by parser.\n\t */\n\tpublic static final int HIDDEN_CHANNEL = 1;\n\n\t/**\n\t * This is the minimum constant value which can be assigned to a\n\t * user-defined token channel.\n\t *\n\t * <p>\n\t * The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are\n\t * assigned to the predefined channels {@link #DEFAULT_CHANNEL} and\n\t * {@link #HIDDEN_CHANNEL}.</p>\n\t *\n\t * @see Token#getChannel()\n\t */\n\tpublic static final int MIN_USER_CHANNEL_VALUE = 2;\n\n\t/**\n\t * Get the text of the token.\n\t */\n\tString getText();\n\n\t/** Get the token type of the token */\n\tint getType();\n\n\t/** The line number on which the 1st character of this token was matched,\n\t *  line=1..n\n\t */\n\tint getLine();\n\n\t/** The index of the first character of this token relative to the\n\t *  beginning of the line at which it occurs, 0..n-1\n\t */\n\tint getCharPositionInLine();\n\n\t/** Return the channel this token. Each token can arrive at the parser\n\t *  on a different channel, but the parser only \"tunes\" to a single channel.\n\t *  The parser ignores everything not on DEFAULT_CHANNEL.\n\t */\n\tint getChannel();\n\n\t/** An index from 0..n-1 of the token object in the input stream.\n\t *  This must be valid in order to print token streams and\n\t *  use TokenRewriteStream.\n\t *\n\t *  Return -1 to indicate that this token was conjured up since\n\t *  it doesn't have a valid index.\n\t */\n\tint getTokenIndex();\n\n\t/** The starting character index of the token\n\t *  This method is optional; return -1 if not implemented.\n\t */\n\tint getStartIndex();\n\n\t/** The last character index of the token.\n\t *  This method is optional; return -1 if not implemented.\n\t */\n\tint getStopIndex();\n\n\t/** Gets the {@link TokenSource} which created this token.\n\t */\n\tTokenSource getTokenSource();\n\n\t/**\n\t * Gets the {@link CharStream} from which this token was derived.\n\t */\n\tCharStream getInputStream();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/TokenFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Pair;\n\n/** The default mechanism for creating tokens. It's used by default in Lexer and\n *  the error handling strategy (to create missing tokens).  Notifying the parser\n *  of a new factory means that it notifies its token source and error strategy.\n */\npublic interface TokenFactory<Symbol extends Token> {\n\t/** This is the method used to create tokens in the lexer and in the\n\t *  error handling strategy. If text!=null, than the start and stop positions\n\t *  are wiped to -1 in the text override is set in the CommonToken.\n\t */\n\tSymbol create(Pair<TokenSource, CharStream> source, int type, String text,\n\t\t\t\t  int channel, int start, int stop,\n\t\t\t\t  int line, int charPositionInLine);\n\n\t/** Generically useful */\n\tSymbol create(int type, String text);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/TokenSource.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\n/**\n * A source of tokens must provide a sequence of tokens via {@link #nextToken()}\n * and also must reveal it's source of characters; {@link CommonToken}'s text is\n * computed from a {@link CharStream}; it only store indices into the char\n * stream.\n *\n * <p>Errors from the lexer are never passed to the parser. Either you want to keep\n * going or you do not upon token recognition error. If you do not want to\n * continue lexing then you do not want to continue parsing. Just throw an\n * exception not under {@link RecognitionException} and Java will naturally toss\n * you all the way out of the recognizers. If you want to continue lexing then\n * you should not throw an exception to the parser--it has already requested a\n * token. Keep lexing until you get a valid one. Just report errors and keep\n * going, looking for a valid token.</p>\n */\npublic interface TokenSource {\n\t/**\n\t * Return a {@link Token} object from your input stream (usually a\n\t * {@link CharStream}). Do not fail/return upon lexing error; keep chewing\n\t * on the characters until you get a good one; errors are not passed through\n\t * to the parser.\n\t */\n\tpublic Token nextToken();\n\n\t/**\n\t * Get the line number for the current position in the input stream. The\n\t * first line in the input is line 1.\n\t *\n\t * @return The line number for the current position in the input stream, or\n\t * 0 if the current token source does not track line numbers.\n\t */\n\tpublic int getLine();\n\n\t/**\n\t * Get the index into the current line for the current position in the input\n\t * stream. The first character on a line has position 0.\n\t *\n\t * @return The line number for the current position in the input stream, or\n\t * -1 if the current token source does not track character positions.\n\t */\n\tpublic int getCharPositionInLine();\n\n\t/**\n\t * Get the {@link CharStream} from which this token source is currently\n\t * providing tokens.\n\t *\n\t * @return The {@link CharStream} associated with the current position in\n\t * the input, or {@code null} if no input stream is available for the token\n\t * source.\n\t */\n\tpublic CharStream getInputStream();\n\n\t/**\n\t * Gets the name of the underlying input source. This method returns a\n\t * non-null, non-empty string. If such a name is not known, this method\n\t * returns {@link IntStream#UNKNOWN_SOURCE_NAME}.\n\t */\n\tpublic String getSourceName();\n\n\t/**\n\t * Set the {@link TokenFactory} this token source should use for creating\n\t * {@link Token} objects from the input.\n\t *\n\t * @param factory The {@link TokenFactory} to use for creating tokens.\n\t */\n\tpublic void setTokenFactory(TokenFactory<?> factory);\n\n\t/**\n\t * Gets the {@link TokenFactory} this token source is currently using for\n\t * creating {@link Token} objects from the input.\n\t *\n\t * @return The {@link TokenFactory} currently used by this token source.\n\t */\n\tpublic TokenFactory<?> getTokenFactory();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/TokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\n/**\n * An {@link IntStream} whose symbols are {@link Token} instances.\n */\npublic interface TokenStream extends IntStream {\n\t/**\n\t * Get the {@link Token} instance associated with the value returned by\n\t * {@link #LA LA(k)}. This method has the same pre- and post-conditions as\n\t * {@link IntStream#LA}. In addition, when the preconditions of this method\n\t * are met, the return value is non-null and the value of\n\t * {@code LT(k).getType()==LA(k)}.\n\t *\n\t * @see IntStream#LA\n\t */\n\tpublic Token LT(int k);\n\n\t/**\n\t * Gets the {@link Token} at the specified {@code index} in the stream. When\n\t * the preconditions of this method are met, the return value is non-null.\n\t *\n\t * <p>The preconditions for this method are the same as the preconditions of\n\t * {@link IntStream#seek}. If the behavior of {@code seek(index)} is\n\t * unspecified for the current state and given {@code index}, then the\n\t * behavior of this method is also unspecified.</p>\n\t *\n\t * <p>The symbol referred to by {@code index} differs from {@code seek()} only\n\t * in the case of filtering streams where {@code index} lies before the end\n\t * of the stream. Unlike {@code seek()}, this method does not adjust\n\t * {@code index} to point to a non-ignored symbol.</p>\n\t *\n\t * @throws IllegalArgumentException if {code index} is less than 0\n\t * @throws UnsupportedOperationException if the stream does not support\n\t * retrieving the token at the specified index\n\t */\n\tpublic Token get(int index);\n\n\t/**\n\t * Gets the underlying {@link TokenSource} which provides tokens for this\n\t * stream.\n\t */\n\tpublic TokenSource getTokenSource();\n\n\t/**\n\t * Return the text of all tokens within the specified {@code interval}. This\n\t * method behaves like the following code (including potential exceptions\n\t * for violating preconditions of {@link #get}, but may be optimized by the\n\t * specific implementation.\n\t *\n\t * <pre>\n\t * TokenStream stream = ...;\n\t * String text = \"\";\n\t * for (int i = interval.a; i &lt;= interval.b; i++) {\n\t *   text += stream.get(i).getText();\n\t * }\n\t * </pre>\n\t *\n\t * @param interval The interval of tokens within this stream to get text\n\t * for.\n\t * @return The text of all tokens within the specified interval in this\n\t * stream.\n\t *\n\t * @throws NullPointerException if {@code interval} is {@code null}\n\t */\n\tpublic String getText(Interval interval);\n\n\t/**\n\t * Return the text of all tokens in the stream. This method behaves like the\n\t * following code, including potential exceptions from the calls to\n\t * {@link IntStream#size} and {@link #getText(Interval)}, but may be\n\t * optimized by the specific implementation.\n\t *\n\t * <pre>\n\t * TokenStream stream = ...;\n\t * String text = stream.getText(new Interval(0, stream.size()));\n\t * </pre>\n\t *\n\t * @return The text of all tokens in the stream.\n\t */\n\tpublic String getText();\n\n\t/**\n\t * Return the text of all tokens in the source interval of the specified\n\t * context. This method behaves like the following code, including potential\n\t * exceptions from the call to {@link #getText(Interval)}, but may be\n\t * optimized by the specific implementation.\n\t *\n\t * <p>If {@code ctx.getSourceInterval()} does not return a valid interval of\n\t * tokens provided by this stream, the behavior is unspecified.</p>\n\t *\n\t * <pre>\n\t * TokenStream stream = ...;\n\t * String text = stream.getText(ctx.getSourceInterval());\n\t * </pre>\n\t *\n\t * @param ctx The context providing the source interval of tokens to get\n\t * text for.\n\t * @return The text of all tokens within the source interval of {@code ctx}.\n\t */\n\tpublic String getText(RuleContext ctx);\n\n\t/**\n\t * Return the text of all tokens in this stream between {@code start} and\n\t * {@code stop} (inclusive).\n\t *\n\t * <p>If the specified {@code start} or {@code stop} token was not provided by\n\t * this stream, or if the {@code stop} occurred before the {@code start}\n\t * token, the behavior is unspecified.</p>\n\t *\n\t * <p>For streams which ensure that the {@link Token#getTokenIndex} method is\n\t * accurate for all of its provided tokens, this method behaves like the\n\t * following code. Other streams may implement this method in other ways\n\t * provided the behavior is consistent with this at a high level.</p>\n\t *\n\t * <pre>\n\t * TokenStream stream = ...;\n\t * String text = \"\";\n\t * for (int i = start.getTokenIndex(); i &lt;= stop.getTokenIndex(); i++) {\n\t *   text += stream.get(i).getText();\n\t * }\n\t * </pre>\n\t *\n\t * @param start The first token in the interval to get text for.\n\t * @param stop The last token in the interval to get text for (inclusive).\n\t * @return The text of all tokens lying between the specified {@code start}\n\t * and {@code stop} tokens.\n\t *\n\t * @throws UnsupportedOperationException if this stream does not support\n\t * this method for the specified tokens\n\t */\n\tpublic String getText(Token start, Token stop);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/TokenStreamRewriter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Useful for rewriting out a buffered input token stream after doing some\n * augmentation or other manipulations on it.\n *\n * <p>\n * You can insert stuff, replace, and delete chunks. Note that the operations\n * are done lazily--only if you convert the buffer to a {@link String} with\n * {@link TokenStream#getText()}. This is very efficient because you are not\n * moving data around all the time. As the buffer of tokens is converted to\n * strings, the {@link #getText()} method(s) scan the input token stream and\n * check to see if there is an operation at the current index. If so, the\n * operation is done and then normal {@link String} rendering continues on the\n * buffer. This is like having multiple Turing machine instruction streams\n * (programs) operating on a single input tape. :)</p>\n *\n * <p>\n * This rewriter makes no modifications to the token stream. It does not ask the\n * stream to fill itself up nor does it advance the input cursor. The token\n * stream {@link TokenStream#index()} will return the same value before and\n * after any {@link #getText()} call.</p>\n *\n * <p>\n * The rewriter only works on tokens that you have in the buffer and ignores the\n * current input cursor. If you are buffering tokens on-demand, calling\n * {@link #getText()} halfway through the input will only do rewrites for those\n * tokens in the first half of the file.</p>\n *\n * <p>\n * Since the operations are done lazily at {@link #getText}-time, operations do\n * not screw up the token index values. That is, an insert operation at token\n * index {@code i} does not change the index values for tokens\n * {@code i}+1..n-1.</p>\n *\n * <p>\n * Because operations never actually alter the buffer, you may always get the\n * original token stream back without undoing anything. Since the instructions\n * are queued up, you can easily simulate transactions and roll back any changes\n * if there is an error just by removing instructions. For example,</p>\n *\n * <pre>\n * CharStream input = new ANTLRFileStream(\"input\");\n * TLexer lex = new TLexer(input);\n * CommonTokenStream tokens = new CommonTokenStream(lex);\n * T parser = new T(tokens);\n * TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);\n * parser.startRule();\n * </pre>\n *\n * <p>\n * Then in the rules, you can execute (assuming rewriter is visible):</p>\n *\n * <pre>\n * Token t,u;\n * ...\n * rewriter.insertAfter(t, \"text to put after t\");}\n * rewriter.insertAfter(u, \"text after u\");}\n * System.out.println(rewriter.getText());\n * </pre>\n *\n * <p>\n * You can also have multiple \"instruction streams\" and get multiple rewrites\n * from a single pass over the input. Just name the instruction streams and use\n * that name again when printing the buffer. This could be useful for generating\n * a C file and also its header file--all from the same buffer:</p>\n *\n * <pre>\n * rewriter.insertAfter(\"pass1\", t, \"text to put after t\");}\n * rewriter.insertAfter(\"pass2\", u, \"text after u\");}\n * System.out.println(rewriter.getText(\"pass1\"));\n * System.out.println(rewriter.getText(\"pass2\"));\n * </pre>\n *\n * <p>\n * If you don't use named rewrite streams, a \"default\" stream is used as the\n * first example shows.</p>\n */\npublic class TokenStreamRewriter {\n\tpublic static final String DEFAULT_PROGRAM_NAME = \"default\";\n\tpublic static final int PROGRAM_INIT_SIZE = 100;\n\tpublic static final int MIN_TOKEN_INDEX = 0;\n\n\t// Define the rewrite operation hierarchy\n\n\tpublic class RewriteOperation {\n\t\t/** What index into rewrites List are we? */\n\t\tprotected int instructionIndex;\n\t\t/** Token buffer index. */\n\t\tprotected int index;\n\t\tprotected Object text;\n\n\t\tprotected RewriteOperation(int index) {\n\t\t\tthis.index = index;\n\t\t}\n\n\t\tprotected RewriteOperation(int index, Object text) {\n\t\t\tthis.index = index;\n\t\t\tthis.text = text;\n\t\t}\n\t\t/** Execute the rewrite operation by possibly adding to the buffer.\n\t\t *  Return the index of the next token to operate on.\n\t\t */\n\t\tpublic int execute(StringBuilder buf) {\n\t\t\treturn index;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tString opName = getClass().getName();\n\t\t\tint $index = opName.indexOf('$');\n\t\t\topName = opName.substring($index+1, opName.length());\n\t\t\treturn \"<\"+opName+\"@\"+tokens.get(index)+\n\t\t\t\t\t\":\\\"\"+text+\"\\\">\";\n\t\t}\n\t}\n\n\tclass InsertBeforeOp extends RewriteOperation {\n\t\tpublic InsertBeforeOp(int index, Object text) {\n\t\t\tsuper(index,text);\n\t\t}\n\n\t\t@Override\n\t\tpublic int execute(StringBuilder buf) {\n\t\t\tbuf.append(text);\n\t\t\tif ( tokens.get(index).getType()!=Token.EOF ) {\n\t\t\t\tbuf.append(tokens.get(index).getText());\n\t\t\t}\n\t\t\treturn index+1;\n\t\t}\n\t}\n\n\t/** Distinguish between insert after/before to do the \"insert afters\"\n\t *  first and then the \"insert befores\" at same index. Implementation\n\t *  of \"insert after\" is \"insert before index+1\".\n\t */\n    class InsertAfterOp extends InsertBeforeOp {\n        public InsertAfterOp(int index, Object text) {\n            super(index+1, text); // insert after is insert before index+1\n        }\n    }\n\n\t/** I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp\n\t *  instructions.\n\t */\n\tclass ReplaceOp extends RewriteOperation {\n\t\tprotected int lastIndex;\n\t\tpublic ReplaceOp(int from, int to, Object text) {\n\t\t\tsuper(from,text);\n\t\t\tlastIndex = to;\n\t\t}\n\t\t@Override\n\t\tpublic int execute(StringBuilder buf) {\n\t\t\tif ( text!=null ) {\n\t\t\t\tbuf.append(text);\n\t\t\t}\n\t\t\treturn lastIndex+1;\n\t\t}\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tif ( text==null ) {\n\t\t\t\treturn \"<DeleteOp@\"+tokens.get(index)+\n\t\t\t\t\t\t\"..\"+tokens.get(lastIndex)+\">\";\n\t\t\t}\n\t\t\treturn \"<ReplaceOp@\"+tokens.get(index)+\n\t\t\t\t\t\"..\"+tokens.get(lastIndex)+\":\\\"\"+text+\"\\\">\";\n\t\t}\n\t}\n\n\t/** Our source stream */\n\tprotected final TokenStream tokens;\n\n\t/** You may have multiple, named streams of rewrite operations.\n\t *  I'm calling these things \"programs.\"\n\t *  Maps String (name) &rarr; rewrite (List)\n\t */\n\tprotected final Map<String, List<RewriteOperation>> programs;\n\n\t/** Map String (program name) &rarr; Integer index */\n\tprotected final Map<String, Integer> lastRewriteTokenIndexes;\n\n\tpublic TokenStreamRewriter(TokenStream tokens) {\n\t\tthis.tokens = tokens;\n\t\tprograms = new HashMap<String, List<RewriteOperation>>();\n\t\tprograms.put(DEFAULT_PROGRAM_NAME,\n\t\t\t\t\t new ArrayList<RewriteOperation>(PROGRAM_INIT_SIZE));\n\t\tlastRewriteTokenIndexes = new HashMap<String, Integer>();\n\t}\n\n\tpublic final TokenStream getTokenStream() {\n\t\treturn tokens;\n\t}\n\n\tpublic void rollback(int instructionIndex) {\n\t\trollback(DEFAULT_PROGRAM_NAME, instructionIndex);\n\t}\n\n\t/** Rollback the instruction stream for a program so that\n\t *  the indicated instruction (via instructionIndex) is no\n\t *  longer in the stream. UNTESTED!\n\t */\n\tpublic void rollback(String programName, int instructionIndex) {\n\t\tList<RewriteOperation> is = programs.get(programName);\n\t\tif ( is!=null ) {\n\t\t\tprograms.put(programName, is.subList(MIN_TOKEN_INDEX,instructionIndex));\n\t\t}\n\t}\n\n\tpublic void deleteProgram() {\n\t\tdeleteProgram(DEFAULT_PROGRAM_NAME);\n\t}\n\n\t/** Reset the program so that no instructions exist */\n\tpublic void deleteProgram(String programName) {\n\t\trollback(programName, MIN_TOKEN_INDEX);\n\t}\n\n\tpublic void insertAfter(Token t, Object text) {\n\t\tinsertAfter(DEFAULT_PROGRAM_NAME, t, text);\n\t}\n\n\tpublic void insertAfter(int index, Object text) {\n\t\tinsertAfter(DEFAULT_PROGRAM_NAME, index, text);\n\t}\n\n\tpublic void insertAfter(String programName, Token t, Object text) {\n\t\tinsertAfter(programName,t.getTokenIndex(), text);\n\t}\n\n\tpublic void insertAfter(String programName, int index, Object text) {\n\t\t// to insert after, just insert before next index (even if past end)\n        RewriteOperation op = new InsertAfterOp(index, text);\n        List<RewriteOperation> rewrites = getProgram(programName);\n        op.instructionIndex = rewrites.size();\n        rewrites.add(op);\n\t}\n\n\tpublic void insertBefore(Token t, Object text) {\n\t\tinsertBefore(DEFAULT_PROGRAM_NAME, t, text);\n\t}\n\n\tpublic void insertBefore(int index, Object text) {\n\t\tinsertBefore(DEFAULT_PROGRAM_NAME, index, text);\n\t}\n\n\tpublic void insertBefore(String programName, Token t, Object text) {\n\t\tinsertBefore(programName, t.getTokenIndex(), text);\n\t}\n\n\tpublic void insertBefore(String programName, int index, Object text) {\n\t\tRewriteOperation op = new InsertBeforeOp(index,text);\n\t\tList<RewriteOperation> rewrites = getProgram(programName);\n\t\top.instructionIndex = rewrites.size();\n\t\trewrites.add(op);\n\t}\n\n\tpublic void replace(int index, Object text) {\n\t\treplace(DEFAULT_PROGRAM_NAME, index, index, text);\n\t}\n\n\tpublic void replace(int from, int to, Object text) {\n\t\treplace(DEFAULT_PROGRAM_NAME, from, to, text);\n\t}\n\n\tpublic void replace(Token indexT, Object text) {\n\t\treplace(DEFAULT_PROGRAM_NAME, indexT, indexT, text);\n\t}\n\n\tpublic void replace(Token from, Token to, Object text) {\n\t\treplace(DEFAULT_PROGRAM_NAME, from, to, text);\n\t}\n\n\tpublic void replace(String programName, int from, int to, Object text) {\n\t\tif ( from > to || from<0 || to<0 || to >= tokens.size() ) {\n\t\t\tthrow new IllegalArgumentException(\"replace: range invalid: \"+from+\"..\"+to+\"(size=\"+tokens.size()+\")\");\n\t\t}\n\t\tRewriteOperation op = new ReplaceOp(from, to, text);\n\t\tList<RewriteOperation> rewrites = getProgram(programName);\n\t\top.instructionIndex = rewrites.size();\n\t\trewrites.add(op);\n\t}\n\n\tpublic void replace(String programName, Token from, Token to, Object text) {\n\t\treplace(programName,\n\t\t\t\tfrom.getTokenIndex(),\n\t\t\t\tto.getTokenIndex(),\n\t\t\t\ttext);\n\t}\n\n\tpublic void delete(int index) {\n\t\tdelete(DEFAULT_PROGRAM_NAME, index, index);\n\t}\n\n\tpublic void delete(int from, int to) {\n\t\tdelete(DEFAULT_PROGRAM_NAME, from, to);\n\t}\n\n\tpublic void delete(Token indexT) {\n\t\tdelete(DEFAULT_PROGRAM_NAME, indexT, indexT);\n\t}\n\n\tpublic void delete(Token from, Token to) {\n\t\tdelete(DEFAULT_PROGRAM_NAME, from, to);\n\t}\n\n\tpublic void delete(String programName, int from, int to) {\n\t\treplace(programName,from,to,null);\n\t}\n\n\tpublic void delete(String programName, Token from, Token to) {\n\t\treplace(programName,from,to,null);\n\t}\n\n\tpublic int getLastRewriteTokenIndex() {\n\t\treturn getLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME);\n\t}\n\n\tprotected int getLastRewriteTokenIndex(String programName) {\n\t\tInteger I = lastRewriteTokenIndexes.get(programName);\n\t\tif ( I==null ) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn I;\n\t}\n\n\tprotected void setLastRewriteTokenIndex(String programName, int i) {\n\t\tlastRewriteTokenIndexes.put(programName, i);\n\t}\n\n\tprotected List<RewriteOperation> getProgram(String name) {\n\t\tList<RewriteOperation> is = programs.get(name);\n\t\tif ( is==null ) {\n\t\t\tis = initializeProgram(name);\n\t\t}\n\t\treturn is;\n\t}\n\n\tprivate List<RewriteOperation> initializeProgram(String name) {\n\t\tList<RewriteOperation> is = new ArrayList<RewriteOperation>(PROGRAM_INIT_SIZE);\n\t\tprograms.put(name, is);\n\t\treturn is;\n\t}\n\n\t/** Return the text from the original tokens altered per the\n\t *  instructions given to this rewriter.\n \t */\n\tpublic String getText() {\n\t\treturn getText(DEFAULT_PROGRAM_NAME, Interval.of(0,tokens.size()-1));\n\t}\n\n\t/** Return the text from the original tokens altered per the\n\t *  instructions given to this rewriter in programName.\n \t */\n\tpublic String getText(String programName) {\n\t\treturn getText(programName, Interval.of(0,tokens.size()-1));\n\t}\n\n\t/** Return the text associated with the tokens in the interval from the\n\t *  original token stream but with the alterations given to this rewriter.\n\t *  The interval refers to the indexes in the original token stream.\n\t *  We do not alter the token stream in any way, so the indexes\n\t *  and intervals are still consistent. Includes any operations done\n\t *  to the first and last token in the interval. So, if you did an\n\t *  insertBefore on the first token, you would get that insertion.\n\t *  The same is true if you do an insertAfter the stop token.\n \t */\n\tpublic String getText(Interval interval) {\n\t\treturn getText(DEFAULT_PROGRAM_NAME, interval);\n\t}\n\n\tpublic String getText(String programName, Interval interval) {\n\t\tList<RewriteOperation> rewrites = programs.get(programName);\n\t\tint start = interval.a;\n\t\tint stop = interval.b;\n\n\t\t// ensure start/end are in range\n\t\tif ( stop>tokens.size()-1 ) stop = tokens.size()-1;\n\t\tif ( start<0 ) start = 0;\n\n\t\tif ( rewrites==null || rewrites.isEmpty() ) {\n\t\t\treturn tokens.getText(interval); // no instructions to execute\n\t\t}\n\t\tStringBuilder buf = new StringBuilder();\n\n\t\t// First, optimize instruction stream\n\t\tMap<Integer, RewriteOperation> indexToOp = reduceToSingleOperationPerIndex(rewrites);\n\n\t\t// Walk buffer, executing instructions and emitting tokens\n\t\tint i = start;\n\t\twhile ( i <= stop && i < tokens.size() ) {\n\t\t\tRewriteOperation op = indexToOp.get(i);\n\t\t\tindexToOp.remove(i); // remove so any left have index size-1\n\t\t\tToken t = tokens.get(i);\n\t\t\tif ( op==null ) {\n\t\t\t\t// no operation at that index, just dump token\n\t\t\t\tif ( t.getType()!=Token.EOF ) buf.append(t.getText());\n\t\t\t\ti++; // move to next token\n\t\t\t}\n\t\t\telse {\n\t\t\t\ti = op.execute(buf); // execute operation and skip\n\t\t\t}\n\t\t}\n\n\t\t// include stuff after end if it's last index in buffer\n\t\t// So, if they did an insertAfter(lastValidIndex, \"foo\"), include\n\t\t// foo if end==lastValidIndex.\n\t\tif ( stop==tokens.size()-1 ) {\n\t\t\t// Scan any remaining operations after last token\n\t\t\t// should be included (they will be inserts).\n\t\t\tfor (RewriteOperation op : indexToOp.values()) {\n\t\t\t\tif ( op.index >= tokens.size()-1 ) buf.append(op.text);\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\t/** We need to combine operations and report invalid operations (like\n\t *  overlapping replaces that are not completed nested). Inserts to\n\t *  same index need to be combined etc...  Here are the cases:\n\t *\n\t *  I.i.u I.j.v\t\t\t\t\t\t\t\tleave alone, nonoverlapping\n\t *  I.i.u I.i.v\t\t\t\t\t\t\t\tcombine: Iivu\n\t *\n\t *  R.i-j.u R.x-y.v\t| i-j in x-y\t\t\tdelete first R\n\t *  R.i-j.u R.i-j.v\t\t\t\t\t\t\tdelete first R\n\t *  R.i-j.u R.x-y.v\t| x-y in i-j\t\t\tERROR\n\t *  R.i-j.u R.x-y.v\t| boundaries overlap\tERROR\n\t *\n\t *  Delete special case of replace (text==null):\n\t *  D.i-j.u D.x-y.v\t| boundaries overlap\tcombine to max(min)..max(right)\n\t *\n\t *  I.i.u R.x-y.v | i in (x+1)-y\t\t\tdelete I (since insert before\n\t *\t\t\t\t\t\t\t\t\t\t\twe're not deleting i)\n\t *  I.i.u R.x-y.v | i not in (x+1)-y\t\tleave alone, nonoverlapping\n\t *  R.x-y.v I.i.u | i in x-y\t\t\t\tERROR\n\t *  R.x-y.v I.x.u \t\t\t\t\t\t\tR.x-y.uv (combine, delete I)\n\t *  R.x-y.v I.i.u | i not in x-y\t\t\tleave alone, nonoverlapping\n\t *\n\t *  I.i.u = insert u before op @ index i\n\t *  R.x-y.u = replace x-y indexed tokens with u\n\t *\n\t *  First we need to examine replaces. For any replace op:\n\t *\n\t * \t\t1. wipe out any insertions before op within that range.\n\t *\t\t2. Drop any replace op before that is contained completely within\n\t *\t that range.\n\t *\t\t3. Throw exception upon boundary overlap with any previous replace.\n\t *\n\t *  Then we can deal with inserts:\n\t *\n\t * \t\t1. for any inserts to same index, combine even if not adjacent.\n\t * \t\t2. for any prior replace with same left boundary, combine this\n\t *\t insert with replace and delete this replace.\n\t * \t\t3. throw exception if index in same range as previous replace\n\t *\n\t *  Don't actually delete; make op null in list. Easier to walk list.\n\t *  Later we can throw as we add to index &rarr; op map.\n\t *\n\t *  Note that I.2 R.2-2 will wipe out I.2 even though, technically, the\n\t *  inserted stuff would be before the replace range. But, if you\n\t *  add tokens in front of a method body '{' and then delete the method\n\t *  body, I think the stuff before the '{' you added should disappear too.\n\t *\n\t *  Return a map from token index to operation.\n\t */\n\tprotected Map<Integer, RewriteOperation> reduceToSingleOperationPerIndex(List<RewriteOperation> rewrites) {\n//\t\tSystem.out.println(\"rewrites=\"+rewrites);\n\n\t\t// WALK REPLACES\n\t\tfor (int i = 0; i < rewrites.size(); i++) {\n\t\t\tRewriteOperation op = rewrites.get(i);\n\t\t\tif ( op==null ) continue;\n\t\t\tif ( !(op instanceof ReplaceOp) ) continue;\n\t\t\tReplaceOp rop = (ReplaceOp)rewrites.get(i);\n\t\t\t// Wipe prior inserts within range\n\t\t\tList<? extends InsertBeforeOp> inserts = getKindOfOps(rewrites, InsertBeforeOp.class, i);\n\t\t\tfor (InsertBeforeOp iop : inserts) {\n\t\t\t\tif ( iop.index == rop.index ) {\n\t\t\t\t\t// E.g., insert before 2, delete 2..2; update replace\n\t\t\t\t\t// text to include insert before, kill insert\n\t\t\t\t\trewrites.set(iop.instructionIndex, null);\n\t\t\t\t\trop.text = iop.text.toString() + (rop.text!=null?rop.text.toString():\"\");\n\t\t\t\t}\n\t\t\t\telse if ( iop.index > rop.index && iop.index <= rop.lastIndex ) {\n\t\t\t\t\t// delete insert as it's a no-op.\n\t\t\t\t\trewrites.set(iop.instructionIndex, null);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Drop any prior replaces contained within\n\t\t\tList<? extends ReplaceOp> prevReplaces = getKindOfOps(rewrites, ReplaceOp.class, i);\n\t\t\tfor (ReplaceOp prevRop : prevReplaces) {\n\t\t\t\tif ( prevRop.index>=rop.index && prevRop.lastIndex <= rop.lastIndex ) {\n\t\t\t\t\t// delete replace as it's a no-op.\n\t\t\t\t\trewrites.set(prevRop.instructionIndex, null);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// throw exception unless disjoint or identical\n\t\t\t\tboolean disjoint =\n\t\t\t\t\tprevRop.lastIndex<rop.index || prevRop.index > rop.lastIndex;\n\t\t\t\t// Delete special case of replace (text==null):\n\t\t\t\t// D.i-j.u D.x-y.v\t| boundaries overlap\tcombine to max(min)..max(right)\n\t\t\t\tif ( prevRop.text==null && rop.text==null && !disjoint ) {\n\t\t\t\t\t//System.out.println(\"overlapping deletes: \"+prevRop+\", \"+rop);\n\t\t\t\t\trewrites.set(prevRop.instructionIndex, null); // kill first delete\n\t\t\t\t\trop.index = Math.min(prevRop.index, rop.index);\n\t\t\t\t\trop.lastIndex = Math.max(prevRop.lastIndex, rop.lastIndex);\n\t\t\t\t\tSystem.out.println(\"new rop \"+rop);\n\t\t\t\t}\n\t\t\t\telse if ( !disjoint ) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"replace op boundaries of \"+rop+\" overlap with previous \"+prevRop);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// WALK INSERTS\n\t\tfor (int i = 0; i < rewrites.size(); i++) {\n\t\t\tRewriteOperation op = rewrites.get(i);\n\t\t\tif ( op==null ) continue;\n\t\t\tif ( !(op instanceof InsertBeforeOp) ) continue;\n\t\t\tInsertBeforeOp iop = (InsertBeforeOp)rewrites.get(i);\n\t\t\t// combine current insert with prior if any at same index\n\t\t\tList<? extends InsertBeforeOp> prevInserts = getKindOfOps(rewrites, InsertBeforeOp.class, i);\n\t\t\tfor (InsertBeforeOp prevIop : prevInserts) {\n\t\t\t\tif ( prevIop.index==iop.index ) {\n\t\t\t\t\tif ( InsertAfterOp.class.isInstance(prevIop) ) {\n\t\t\t\t\t\tiop.text = catOpText(prevIop.text, iop.text);\n\t\t\t\t\t\trewrites.set(prevIop.instructionIndex, null);\n\t\t\t\t\t}\n\t\t\t\t\telse if ( InsertBeforeOp.class.isInstance(prevIop) ) { // combine objects\n\t\t\t\t\t\t// convert to strings...we're in process of toString'ing\n\t\t\t\t\t\t// whole token buffer so no lazy eval issue with any templates\n\t\t\t\t\t\tiop.text = catOpText(iop.text, prevIop.text);\n\t\t\t\t\t\t// delete redundant prior insert\n\t\t\t\t\t\trewrites.set(prevIop.instructionIndex, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// look for replaces where iop.index is in range; error\n\t\t\tList<? extends ReplaceOp> prevReplaces = getKindOfOps(rewrites, ReplaceOp.class, i);\n\t\t\tfor (ReplaceOp rop : prevReplaces) {\n\t\t\t\tif ( iop.index == rop.index ) {\n\t\t\t\t\trop.text = catOpText(iop.text,rop.text);\n\t\t\t\t\trewrites.set(i, null);\t// delete current insert\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif ( iop.index >= rop.index && iop.index <= rop.lastIndex ) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"insert op \"+iop+\" within boundaries of previous \"+rop);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// System.out.println(\"rewrites after=\"+rewrites);\n\t\tMap<Integer, RewriteOperation> m = new HashMap<Integer, RewriteOperation>();\n\t\tfor (int i = 0; i < rewrites.size(); i++) {\n\t\t\tRewriteOperation op = rewrites.get(i);\n\t\t\tif ( op==null ) continue; // ignore deleted ops\n\t\t\tif ( m.get(op.index)!=null ) {\n\t\t\t\tthrow new Error(\"should only be one op per index\");\n\t\t\t}\n\t\t\tm.put(op.index, op);\n\t\t}\n\t\t//System.out.println(\"index to op: \"+m);\n\t\treturn m;\n\t}\n\n\tprotected String catOpText(Object a, Object b) {\n\t\tString x = \"\";\n\t\tString y = \"\";\n\t\tif ( a!=null ) x = a.toString();\n\t\tif ( b!=null ) y = b.toString();\n\t\treturn x+y;\n\t}\n\n\t/** Get all operations before an index of a particular kind */\n\tprotected <T extends RewriteOperation> List<? extends T> getKindOfOps(List<? extends RewriteOperation> rewrites, Class<T> kind, int before) {\n\t\tList<T> ops = new ArrayList<T>();\n\t\tfor (int i=0; i<before && i<rewrites.size(); i++) {\n\t\t\tRewriteOperation op = rewrites.get(i);\n\t\t\tif ( op==null ) continue; // ignore deleted\n\t\t\tif ( kind.isInstance(op) ) {\n\t\t\t\tops.add(kind.cast(op));\n\t\t\t}\n\t\t}\n\t\treturn ops;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/UnbufferedCharStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Arrays;\n\n/** Do not buffer up the entire char stream. It does keep a small buffer\n *  for efficiency and also buffers while a mark exists (set by the\n *  lookahead prediction in parser). \"Unbuffered\" here refers to fact\n *  that it doesn't buffer all data, not that's it's on demand loading of char.\n *\n *  Before 4.7, this class used the default environment encoding to convert\n *  bytes to UTF-16, and held the UTF-16 bytes in the buffer as chars.\n *\n *  As of 4.7, the class uses UTF-8 by default, and the buffer holds Unicode\n *  code points in the buffer as ints.\n */\npublic class UnbufferedCharStream implements CharStream {\n\t/**\n\t * A moving window buffer of the data being scanned. While there's a marker,\n\t * we keep adding to buffer. Otherwise, {@link #consume consume()} resets so\n\t * we start filling at index 0 again.\n\t */\n\tprotected int[] data;\n\n\t/**\n\t * The number of characters currently in {@link #data data}.\n\t *\n\t * <p>This is not the buffer capacity, that's {@code data.length}.</p>\n\t */\n   \tprotected int n;\n\n\t/**\n\t * 0..n-1 index into {@link #data data} of next character.\n\t *\n\t * <p>The {@code LA(1)} character is {@code data[p]}. If {@code p == n}, we are\n\t * out of buffered characters.</p>\n\t */\n   \tprotected int p=0;\n\n\t/**\n\t * Count up with {@link #mark mark()} and down with\n\t * {@link #release release()}. When we {@code release()} the last mark,\n\t * {@code numMarkers} reaches 0 and we reset the buffer. Copy\n\t * {@code data[p]..data[n-1]} to {@code data[0]..data[(n-1)-p]}.\n\t */\n\tprotected int numMarkers = 0;\n\n\t/**\n\t * This is the {@code LA(-1)} character for the current position.\n\t */\n\tprotected int lastChar = -1;\n\n\t/**\n\t * When {@code numMarkers > 0}, this is the {@code LA(-1)} character for the\n\t * first character in {@link #data data}. Otherwise, this is unspecified.\n\t */\n\tprotected int lastCharBufferStart;\n\n\t/**\n\t * Absolute character index. It's the index of the character about to be\n\t * read via {@code LA(1)}. Goes from 0 to the number of characters in the\n\t * entire stream, although the stream size is unknown before the end is\n\t * reached.\n\t */\n    protected int currentCharIndex = 0;\n\n    protected Reader input;\n\n\t/** The name or source of this char stream. */\n\tpublic String name;\n\n\t/** Useful for subclasses that pull char from other than this.input. */\n\tpublic UnbufferedCharStream() {\n\t\tthis(256);\n\t}\n\n\t/** Useful for subclasses that pull char from other than this.input. */\n\tpublic UnbufferedCharStream(int bufferSize) {\n\t\tn = 0;\n\t\tdata = new int[bufferSize];\n\t}\n\n\tpublic UnbufferedCharStream(InputStream input) {\n\t\tthis(input, 256);\n\t}\n\n\tpublic UnbufferedCharStream(Reader input) {\n\t\tthis(input, 256);\n\t}\n\n\tpublic UnbufferedCharStream(InputStream input, int bufferSize) {\n\t\tthis(input, bufferSize, StandardCharsets.UTF_8);\n\t}\n\n\tpublic UnbufferedCharStream(InputStream input, int bufferSize, Charset charset) {\n\t\tthis(bufferSize);\n\t\tthis.input = new InputStreamReader(input, charset);\n\t\tfill(1); // prime\n\t}\n\n\tpublic UnbufferedCharStream(Reader input, int bufferSize) {\n\t\tthis(bufferSize);\n\t\tthis.input = input;\n\t\tfill(1); // prime\n\t}\n\n\t@Override\n\tpublic void consume() {\n\t\tif (LA(1) == IntStream.EOF) {\n\t\t\tthrow new IllegalStateException(\"cannot consume EOF\");\n\t\t}\n\n\t\t// buf always has at least data[p==0] in this method due to ctor\n\t\tlastChar = data[p];   // track last char for LA(-1)\n\n\t\tif (p == n-1 && numMarkers==0) {\n\t\t\tn = 0;\n\t\t\tp = -1; // p++ will leave this at 0\n\t\t\tlastCharBufferStart = lastChar;\n\t\t}\n\n\t\tp++;\n\t\tcurrentCharIndex++;\n\t\tsync(1);\n\t}\n\n\t/**\n\t * Make sure we have 'need' elements from current position {@link #p p}.\n\t * Last valid {@code p} index is {@code data.length-1}. {@code p+need-1} is\n\t * the char index 'need' elements ahead. If we need 1 element,\n\t * {@code (p+1-1)==p} must be less than {@code data.length}.\n\t */\n\tprotected void sync(int want) {\n\t\tint need = (p+want-1) - n + 1; // how many more elements we need?\n\t\tif ( need > 0 ) {\n\t\t\tfill(need);\n\t\t}\n\t}\n\n\t/**\n\t * Add {@code n} characters to the buffer. Returns the number of characters\n\t * actually added to the buffer. If the return value is less than {@code n},\n\t * then EOF was reached before {@code n} characters could be added.\n\t */\n\tprotected int fill(int n) {\n\t\tfor (int i=0; i<n; i++) {\n\t\t\tif (this.n > 0 && data[this.n - 1] == IntStream.EOF) {\n\t\t\t\treturn i;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tint c = nextChar();\n\t\t\t\tif (c > Character.MAX_VALUE || c == IntStream.EOF) {\n\t\t\t\t\tadd(c);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tchar ch = (char) c;\n\t\t\t\t\tif (Character.isLowSurrogate(ch)) {\n\t\t\t\t\t\tthrow new RuntimeException(\"Invalid UTF-16 (low surrogate with no preceding high surrogate)\");\n\t\t\t\t\t}\n\t\t\t\t\telse if (Character.isHighSurrogate(ch)) {\n\t\t\t\t\t\tint lowSurrogate = nextChar();\n\t\t\t\t\t\tif (lowSurrogate > Character.MAX_VALUE) {\n\t\t\t\t\t\t\tthrow new RuntimeException(\"Invalid UTF-16 (high surrogate followed by code point > U+FFFF\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (lowSurrogate == IntStream.EOF) {\n\t\t\t\t\t\t\tthrow new RuntimeException(\"Invalid UTF-16 (dangling high surrogate at end of file)\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tchar lowSurrogateChar = (char) lowSurrogate;\n\t\t\t\t\t\t\tif (Character.isLowSurrogate(lowSurrogateChar)) {\n\t\t\t\t\t\t\t\tadd(Character.toCodePoint(ch, lowSurrogateChar));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tthrow new RuntimeException(\"Invalid UTF-16 (dangling high surrogate\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tadd(c);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (IOException ioe) {\n\t\t\t\tthrow new RuntimeException(ioe);\n\t\t\t}\n\t\t}\n\n\t\treturn n;\n\t}\n\n\t/**\n\t * Override to provide different source of characters than\n\t * {@link #input input}.\n\t */\n\tprotected int nextChar() throws IOException {\n\t\treturn input.read();\n\t}\n\n\tprotected void add(int c) {\n\t\tif ( n>=data.length ) {\n\t\t\tdata = Arrays.copyOf(data, data.length * 2);\n        }\n        data[n++] = c;\n    }\n\n    @Override\n    public int LA(int i) {\n\t\tif ( i==-1 ) return lastChar; // special case\n        sync(i);\n        int index = p + i - 1;\n        if ( index < 0 ) throw new IndexOutOfBoundsException();\n\t\tif ( index >= n ) return IntStream.EOF;\n        return data[index];\n    }\n\n\t/**\n\t * Return a marker that we can release later.\n\t *\n\t * <p>The specific marker value used for this class allows for some level of\n\t * protection against misuse where {@code seek()} is called on a mark or\n\t * {@code release()} is called in the wrong order.</p>\n\t */\n    @Override\n    public int mark() {\n\t\tif (numMarkers == 0) {\n\t\t\tlastCharBufferStart = lastChar;\n\t\t}\n\n\t\tint mark = -numMarkers - 1;\n\t\tnumMarkers++;\n\t\treturn mark;\n    }\n\n\t/** Decrement number of markers, resetting buffer if we hit 0.\n\t * @param marker\n\t */\n    @Override\n    public void release(int marker) {\n\t\tint expectedMark = -numMarkers;\n\t\tif ( marker!=expectedMark ) {\n\t\t\tthrow new IllegalStateException(\"release() called with an invalid marker.\");\n\t\t}\n\n\t\tnumMarkers--;\n\t\tif ( numMarkers==0 && p > 0 ) { // release buffer when we can, but don't do unnecessary work\n\t\t\t// Copy data[p]..data[n-1] to data[0]..data[(n-1)-p], reset ptrs\n\t\t\t// p is last valid char; move nothing if p==n as we have no valid char\n\t\t\tSystem.arraycopy(data, p, data, 0, n - p); // shift n-p char from p to 0\n\t\t\tn = n - p;\n\t\t\tp = 0;\n\t\t\tlastCharBufferStart = lastChar;\n\t\t}\n    }\n\n    @Override\n    public int index() {\n\t\treturn currentCharIndex;\n    }\n\n\t/** Seek to absolute character index, which might not be in the current\n\t *  sliding window.  Move {@code p} to {@code index-bufferStartIndex}.\n\t */\n    @Override\n    public void seek(int index) {\n\t\tif (index == currentCharIndex) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (index > currentCharIndex) {\n\t\t\tsync(index - currentCharIndex);\n\t\t\tindex = Math.min(index, getBufferStartIndex() + n - 1);\n\t\t}\n\n        // index == to bufferStartIndex should set p to 0\n        int i = index - getBufferStartIndex();\n        if ( i < 0 ) {\n\t\t\tthrow new IllegalArgumentException(\"cannot seek to negative index \" + index);\n\t\t}\n\t\telse if (i >= n) {\n            throw new UnsupportedOperationException(\"seek to index outside buffer: \"+\n                    index+\" not in \"+getBufferStartIndex()+\"..\"+(getBufferStartIndex()+n));\n        }\n\n\t\tp = i;\n\t\tcurrentCharIndex = index;\n\t\tif (p == 0) {\n\t\t\tlastChar = lastCharBufferStart;\n\t\t}\n\t\telse {\n\t\t\tlastChar = data[p-1];\n\t\t}\n    }\n\n    @Override\n    public int size() {\n        throw new UnsupportedOperationException(\"Unbuffered stream cannot know its size\");\n    }\n\n    @Override\n    public String getSourceName() {\n\t\tif (name == null || name.isEmpty()) {\n\t\t\treturn UNKNOWN_SOURCE_NAME;\n\t\t}\n\n\t\treturn name;\n\t}\n\n\t@Override\n\tpublic String getText(Interval interval) {\n\t\tif (interval.a < 0 || interval.b < interval.a - 1) {\n\t\t\tthrow new IllegalArgumentException(\"invalid interval\");\n\t\t}\n\n\t\tint bufferStartIndex = getBufferStartIndex();\n\t\tif (n > 0 && data[n - 1] == Character.MAX_VALUE) {\n\t\t\tif (interval.a + interval.length() > bufferStartIndex + n) {\n\t\t\t\tthrow new IllegalArgumentException(\"the interval extends past the end of the stream\");\n\t\t\t}\n\t\t}\n\n\t\tif (interval.a < bufferStartIndex || interval.b >= bufferStartIndex + n) {\n\t\t\tthrow new UnsupportedOperationException(\"interval \"+interval+\" outside buffer: \"+\n\t\t\t                    bufferStartIndex+\"..\"+(bufferStartIndex+n-1));\n\t\t}\n\t\t// convert from absolute to local index\n\t\tint i = interval.a - bufferStartIndex;\n\t\treturn new String(data, i, interval.length());\n\t}\n\n\tprotected final int getBufferStartIndex() {\n\t\treturn currentCharIndex - p;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/UnbufferedTokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.util.Arrays;\n\npublic class UnbufferedTokenStream<T extends Token> implements TokenStream {\n\tprotected TokenSource tokenSource;\n\n\t/**\n\t * A moving window buffer of the data being scanned. While there's a marker,\n\t * we keep adding to buffer. Otherwise, {@link #consume consume()} resets so\n\t * we start filling at index 0 again.\n\t */\n\tprotected Token[] tokens;\n\n\t/**\n\t * The number of tokens currently in {@link #tokens tokens}.\n\t *\n\t * <p>This is not the buffer capacity, that's {@code tokens.length}.</p>\n\t */\n\tprotected int n;\n\n\t/**\n\t * 0..n-1 index into {@link #tokens tokens} of next token.\n\t *\n\t * <p>The {@code LT(1)} token is {@code tokens[p]}. If {@code p == n}, we are\n\t * out of buffered tokens.</p>\n\t */\n\tprotected int p=0;\n\n\t/**\n\t * Count up with {@link #mark mark()} and down with\n\t * {@link #release release()}. When we {@code release()} the last mark,\n\t * {@code numMarkers} reaches 0 and we reset the buffer. Copy\n\t * {@code tokens[p]..tokens[n-1]} to {@code tokens[0]..tokens[(n-1)-p]}.\n\t */\n\tprotected int numMarkers = 0;\n\n\t/**\n\t * This is the {@code LT(-1)} token for the current position.\n\t */\n\tprotected Token lastToken;\n\n\t/**\n\t * When {@code numMarkers > 0}, this is the {@code LT(-1)} token for the\n\t * first token in {@link #tokens}. Otherwise, this is {@code null}.\n\t */\n\tprotected Token lastTokenBufferStart;\n\n\t/**\n\t * Absolute token index. It's the index of the token about to be read via\n\t * {@code LT(1)}. Goes from 0 to the number of tokens in the entire stream,\n\t * although the stream size is unknown before the end is reached.\n\t *\n\t * <p>This value is used to set the token indexes if the stream provides tokens\n\t * that implement {@link WritableToken}.</p>\n\t */\n\tprotected int currentTokenIndex = 0;\n\n\tpublic UnbufferedTokenStream(TokenSource tokenSource) {\n\t\tthis(tokenSource, 256);\n\t}\n\n\tpublic UnbufferedTokenStream(TokenSource tokenSource, int bufferSize) {\n\t\tthis.tokenSource = tokenSource;\n\t\ttokens = new Token[bufferSize];\n\t\tn = 0;\n\t\tfill(1); // prime the pump\n\t}\n\n\t@Override\n\tpublic Token get(int i) { // get absolute index\n\t\tint bufferStartIndex = getBufferStartIndex();\n\t\tif (i < bufferStartIndex || i >= bufferStartIndex + n) {\n\t\t\tthrow new IndexOutOfBoundsException(\"get(\"+i+\") outside buffer: \"+\n\t\t\t                    bufferStartIndex+\"..\"+(bufferStartIndex+n));\n\t\t}\n\t\treturn tokens[i - bufferStartIndex];\n\t}\n\n\t@Override\n\tpublic Token LT(int i) {\n\t\tif ( i==-1 ) {\n\t\t\treturn lastToken;\n\t\t}\n\n\t\tsync(i);\n        int index = p + i - 1;\n        if ( index < 0 ) {\n\t\t\tthrow new IndexOutOfBoundsException(\"LT(\"+i+\") gives negative index\");\n\t\t}\n\n\t\tif ( index >= n ) {\n\t\t\tassert n > 0 && tokens[n-1].getType() == Token.EOF;\n\t\t\treturn tokens[n-1];\n\t\t}\n\n\t\treturn tokens[index];\n\t}\n\n\t@Override\n\tpublic int LA(int i) {\n\t\treturn LT(i).getType();\n\t}\n\n\t@Override\n\tpublic TokenSource getTokenSource() {\n\t\treturn tokenSource;\n\t}\n\n\n\t@Override\n\tpublic String getText() {\n\t\treturn \"\";\n\t}\n\n\n\t@Override\n\tpublic String getText(RuleContext ctx) {\n\t\treturn getText(ctx.getSourceInterval());\n\t}\n\n\n\t@Override\n\tpublic String getText(Token start, Token stop) {\n\t\treturn getText(Interval.of(start.getTokenIndex(), stop.getTokenIndex()));\n\t}\n\n\t@Override\n\tpublic void consume() {\n\t\tif (LA(1) == Token.EOF) {\n\t\t\tthrow new IllegalStateException(\"cannot consume EOF\");\n\t\t}\n\n\t\t// buf always has at least tokens[p==0] in this method due to ctor\n\t\tlastToken = tokens[p];   // track last token for LT(-1)\n\n\t\t// if we're at last token and no markers, opportunity to flush buffer\n\t\tif ( p == n-1 && numMarkers==0 ) {\n\t\t\tn = 0;\n\t\t\tp = -1; // p++ will leave this at 0\n\t\t\tlastTokenBufferStart = lastToken;\n\t\t}\n\n\t\tp++;\n\t\tcurrentTokenIndex++;\n\t\tsync(1);\n\t}\n\n\t/** Make sure we have 'need' elements from current position {@link #p p}. Last valid\n\t *  {@code p} index is {@code tokens.length-1}.  {@code p+need-1} is the tokens index 'need' elements\n\t *  ahead.  If we need 1 element, {@code (p+1-1)==p} must be less than {@code tokens.length}.\n\t */\n\tprotected void sync(int want) {\n\t\tint need = (p+want-1) - n + 1; // how many more elements we need?\n\t\tif ( need > 0 ) {\n\t\t\tfill(need);\n\t\t}\n\t}\n\n\t/**\n\t * Add {@code n} elements to the buffer. Returns the number of tokens\n\t * actually added to the buffer. If the return value is less than {@code n},\n\t * then EOF was reached before {@code n} tokens could be added.\n\t */\n\tprotected int fill(int n) {\n\t\tfor (int i=0; i<n; i++) {\n\t\t\tif (this.n > 0 && tokens[this.n-1].getType() == Token.EOF) {\n\t\t\t\treturn i;\n\t\t\t}\n\n\t\t\tToken t = tokenSource.nextToken();\n\t\t\tadd(t);\n\t\t}\n\n\t\treturn n;\n\t}\n\n\tprotected void add(Token t) {\n\t\tif ( n>=tokens.length ) {\n\t\t\ttokens = Arrays.copyOf(tokens, tokens.length * 2);\n\t\t}\n\n\t\tif (t instanceof WritableToken) {\n\t\t\t((WritableToken)t).setTokenIndex(getBufferStartIndex() + n);\n\t\t}\n\n\t\ttokens[n++] = t;\n\t}\n\n\t/**\n\t * Return a marker that we can release later.\n\t *\n\t * <p>The specific marker value used for this class allows for some level of\n\t * protection against misuse where {@code seek()} is called on a mark or\n\t * {@code release()} is called in the wrong order.</p>\n\t */\n\t@Override\n\tpublic int mark() {\n\t\tif (numMarkers == 0) {\n\t\t\tlastTokenBufferStart = lastToken;\n\t\t}\n\n\t\tint mark = -numMarkers - 1;\n\t\tnumMarkers++;\n\t\treturn mark;\n\t}\n\n\t@Override\n\tpublic void release(int marker) {\n\t\tint expectedMark = -numMarkers;\n\t\tif ( marker!=expectedMark ) {\n\t\t\tthrow new IllegalStateException(\"release() called with an invalid marker.\");\n\t\t}\n\n\t\tnumMarkers--;\n\t\tif ( numMarkers==0 ) { // can we release buffer?\n\t\t\tif (p > 0) {\n\t\t\t\t// Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs\n\t\t\t\t// p is last valid token; move nothing if p==n as we have no valid char\n\t\t\t\tSystem.arraycopy(tokens, p, tokens, 0, n - p); // shift n-p tokens from p to 0\n\t\t\t\tn = n - p;\n\t\t\t\tp = 0;\n\t\t\t}\n\n\t\t\tlastTokenBufferStart = lastToken;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int index() {\n\t\treturn currentTokenIndex;\n\t}\n\n\t@Override\n\tpublic void seek(int index) { // seek to absolute index\n\t\tif (index == currentTokenIndex) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (index > currentTokenIndex) {\n\t\t\tsync(index - currentTokenIndex);\n\t\t\tindex = Math.min(index, getBufferStartIndex() + n - 1);\n\t\t}\n\n\t\tint bufferStartIndex = getBufferStartIndex();\n\t\tint i = index - bufferStartIndex;\n\t\tif ( i < 0 ) {\n\t\t\tthrow new IllegalArgumentException(\"cannot seek to negative index \" + index);\n\t\t}\n\t\telse if (i >= n) {\n\t\t\tthrow new UnsupportedOperationException(\"seek to index outside buffer: \"+\n\t\t\t\t\t\t\t\t\t\t\t\t\tindex+\" not in \"+ bufferStartIndex +\"..\"+(bufferStartIndex +n));\n\t\t}\n\n\t\tp = i;\n\t\tcurrentTokenIndex = index;\n\t\tif (p == 0) {\n\t\t\tlastToken = lastTokenBufferStart;\n\t\t}\n\t\telse {\n\t\t\tlastToken = tokens[p-1];\n\t\t}\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\tthrow new UnsupportedOperationException(\"Unbuffered stream cannot know its size\");\n\t}\n\n\t@Override\n\tpublic String getSourceName() {\n\t\treturn tokenSource.getSourceName();\n\t}\n\n\n\t@Override\n\tpublic String getText(Interval interval) {\n\t\tint bufferStartIndex = getBufferStartIndex();\n\t\tint bufferStopIndex = bufferStartIndex + tokens.length - 1;\n\n\t\tint start = interval.a;\n\t\tint stop = interval.b;\n\t\tif (start < bufferStartIndex || stop > bufferStopIndex) {\n\t\t\tthrow new UnsupportedOperationException(\"interval \"+interval+\" not in token buffer window: \"+\n\t\t\t\t\t\t\t\t\t\t\t\t\tbufferStartIndex+\"..\"+bufferStopIndex);\n\t\t}\n\n\t\tint a = start - bufferStartIndex;\n\t\tint b = stop - bufferStartIndex;\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (int i = a; i <= b; i++) {\n\t\t\tToken t = tokens[i];\n\t\t\tbuf.append(t.getText());\n\t\t}\n\n\t\treturn buf.toString();\n\t}\n\n\tprotected final int getBufferStartIndex() {\n\t\treturn currentTokenIndex - p;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/Vocabulary.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\n/**\n * This interface provides information about the vocabulary used by a\n * recognizer.\n *\n * @see Recognizer#getVocabulary()\n * @author Sam Harwell\n */\npublic interface Vocabulary {\n\t/**\n\t * Returns the highest token type value. It can be used to iterate from\n\t * zero to that number, inclusively, thus querying all stored entries.\n\t * @return the highest token type value\n\t */\n\tint getMaxTokenType();\n\n\t/**\n\t * Gets the string literal associated with a token type. The string returned\n\t * by this method, when not {@code null}, can be used unaltered in a parser\n\t * grammar to represent this token type.\n\t *\n\t * <p>The following table shows examples of lexer rules and the literal\n\t * names assigned to the corresponding token types.</p>\n\t *\n\t * <table>\n\t *  <tr>\n\t *   <th>Rule</th>\n\t *   <th>Literal Name</th>\n\t *   <th>Java String Literal</th>\n\t *  </tr>\n\t *  <tr>\n\t *   <td>{@code THIS : 'this';}</td>\n\t *   <td>{@code 'this'}</td>\n\t *   <td>{@code \"'this'\"}</td>\n\t *  </tr>\n\t *  <tr>\n\t *   <td>{@code SQUOTE : '\\'';}</td>\n\t *   <td>{@code '\\''}</td>\n\t *   <td>{@code \"'\\\\''\"}</td>\n\t *  </tr>\n\t *  <tr>\n\t *   <td>{@code ID : [A-Z]+;}</td>\n\t *   <td>n/a</td>\n\t *   <td>{@code null}</td>\n\t *  </tr>\n\t * </table>\n\t *\n\t * @param tokenType The token type.\n\t *\n\t * @return The string literal associated with the specified token type, or\n\t * {@code null} if no string literal is associated with the type.\n\t */\n\tString getLiteralName(int tokenType);\n\n\t/**\n\t * Gets the symbolic name associated with a token type. The string returned\n\t * by this method, when not {@code null}, can be used unaltered in a parser\n\t * grammar to represent this token type.\n\t *\n\t * <p>This method supports token types defined by any of the following\n\t * methods:</p>\n\t *\n\t * <ul>\n\t *  <li>Tokens created by lexer rules.</li>\n\t *  <li>Tokens defined in a <code>tokens{}</code> block in a lexer or parser\n\t *  grammar.</li>\n\t *  <li>The implicitly defined {@code EOF} token, which has the token type\n\t *  {@link Token#EOF}.</li>\n\t * </ul>\n\t *\n\t * <p>The following table shows examples of lexer rules and the literal\n\t * names assigned to the corresponding token types.</p>\n\t *\n\t * <table>\n\t *  <tr>\n\t *   <th>Rule</th>\n\t *   <th>Symbolic Name</th>\n\t *  </tr>\n\t *  <tr>\n\t *   <td>{@code THIS : 'this';}</td>\n\t *   <td>{@code THIS}</td>\n\t *  </tr>\n\t *  <tr>\n\t *   <td>{@code SQUOTE : '\\'';}</td>\n\t *   <td>{@code SQUOTE}</td>\n\t *  </tr>\n\t *  <tr>\n\t *   <td>{@code ID : [A-Z]+;}</td>\n\t *   <td>{@code ID}</td>\n\t *  </tr>\n\t * </table>\n\t *\n\t * @param tokenType The token type.\n\t *\n\t * @return The symbolic name associated with the specified token type, or\n\t * {@code null} if no symbolic name is associated with the type.\n\t */\n\tString getSymbolicName(int tokenType);\n\n\t/**\n\t * Gets the display name of a token type.\n\t *\n\t * <p>ANTLR provides a default implementation of this method, but\n\t * applications are free to override the behavior in any manner which makes\n\t * sense for the application. The default implementation returns the first\n\t * result from the following list which produces a non-{@code null}\n\t * result.</p>\n\t *\n\t * <ol>\n\t *  <li>The result of {@link #getLiteralName}</li>\n\t *  <li>The result of {@link #getSymbolicName}</li>\n\t *  <li>The result of {@link Integer#toString}</li>\n\t * </ol>\n\t *\n\t * @param tokenType The token type.\n\t *\n\t * @return The display name of the token type, for use in error reporting or\n\t * other user-visible messages which reference specific token types.\n\t */\n\tString getDisplayName(int tokenType);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/VocabularyImpl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime;\n\nimport java.util.Arrays;\n\n/**\n * This class provides a default implementation of the {@link Vocabulary}\n * interface.\n *\n * @author Sam Harwell\n */\npublic class VocabularyImpl implements Vocabulary {\n\tprivate static final String[] EMPTY_NAMES = new String[0];\n\n\t/**\n\t * Gets an empty {@link Vocabulary} instance.\n\t *\n\t * <p>\n\t * No literal or symbol names are assigned to token types, so\n\t * {@link #getDisplayName(int)} returns the numeric value for all tokens\n\t * except {@link Token#EOF}.</p>\n\t */\n\tpublic static final VocabularyImpl EMPTY_VOCABULARY = new VocabularyImpl(EMPTY_NAMES, EMPTY_NAMES, EMPTY_NAMES);\n\n\n\tprivate final String[] literalNames;\n\n\tprivate final String[] symbolicNames;\n\n\tprivate final String[] displayNames;\n\n\tprivate final int maxTokenType;\n\n\t/**\n\t * Constructs a new instance of {@link VocabularyImpl} from the specified\n\t * literal and symbolic token names.\n\t *\n\t * @param literalNames The literal names assigned to tokens, or {@code null}\n\t * if no literal names are assigned.\n\t * @param symbolicNames The symbolic names assigned to tokens, or\n\t * {@code null} if no symbolic names are assigned.\n\t *\n\t * @see #getLiteralName(int)\n\t * @see #getSymbolicName(int)\n\t */\n\tpublic VocabularyImpl(String[] literalNames, String[] symbolicNames) {\n\t\tthis(literalNames, symbolicNames, null);\n\t}\n\n\t/**\n\t * Constructs a new instance of {@link VocabularyImpl} from the specified\n\t * literal, symbolic, and display token names.\n\t *\n\t * @param literalNames The literal names assigned to tokens, or {@code null}\n\t * if no literal names are assigned.\n\t * @param symbolicNames The symbolic names assigned to tokens, or\n\t * {@code null} if no symbolic names are assigned.\n\t * @param displayNames The display names assigned to tokens, or {@code null}\n\t * to use the values in {@code literalNames} and {@code symbolicNames} as\n\t * the source of display names, as described in\n\t * {@link #getDisplayName(int)}.\n\t *\n\t * @see #getLiteralName(int)\n\t * @see #getSymbolicName(int)\n\t * @see #getDisplayName(int)\n\t */\n\tpublic VocabularyImpl(String[] literalNames, String[] symbolicNames, String[] displayNames) {\n\t\tthis.literalNames = literalNames != null ? literalNames : EMPTY_NAMES;\n\t\tthis.symbolicNames = symbolicNames != null ? symbolicNames : EMPTY_NAMES;\n\t\tthis.displayNames = displayNames != null ? displayNames : EMPTY_NAMES;\n\t\t// See note here on -1 part: https://github.com/antlr/antlr4/pull/1146\n\t\tthis.maxTokenType =\n\t\t\tMath.max(this.displayNames.length,\n\t\t\t\t\t Math.max(this.literalNames.length, this.symbolicNames.length)) - 1;\n\t}\n\n\t/**\n\t * Returns a {@link VocabularyImpl} instance from the specified set of token\n\t * names. This method acts as a compatibility layer for the single\n\t * {@code tokenNames} array generated by previous releases of ANTLR.\n\t *\n\t * <p>The resulting vocabulary instance returns {@code null} for\n\t * {@link #getLiteralName(int)} and {@link #getSymbolicName(int)}, and the\n\t * value from {@code tokenNames} for the display names.</p>\n\t *\n\t * @param tokenNames The token names, or {@code null} if no token names are\n\t * available.\n\t * @return A {@link Vocabulary} instance which uses {@code tokenNames} for\n\t * the display names of tokens.\n\t */\n\tpublic static Vocabulary fromTokenNames(String[] tokenNames) {\n\t\tif (tokenNames == null || tokenNames.length == 0) {\n\t\t\treturn EMPTY_VOCABULARY;\n\t\t}\n\n\t\tString[] literalNames = Arrays.copyOf(tokenNames, tokenNames.length);\n\t\tString[] symbolicNames = Arrays.copyOf(tokenNames, tokenNames.length);\n\t\tfor (int i = 0; i < tokenNames.length; i++) {\n\t\t\tString tokenName = tokenNames[i];\n\t\t\tif (tokenName == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!tokenName.isEmpty()) {\n\t\t\t\tchar firstChar = tokenName.charAt(0);\n\t\t\t\tif (firstChar == '\\'') {\n\t\t\t\t\tsymbolicNames[i] = null;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse if (Character.isUpperCase(firstChar)) {\n\t\t\t\t\tliteralNames[i] = null;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// wasn't a literal or symbolic name\n\t\t\tliteralNames[i] = null;\n\t\t\tsymbolicNames[i] = null;\n\t\t}\n\n\t\treturn new VocabularyImpl(literalNames, symbolicNames, tokenNames);\n\t}\n\n\t@Override\n\tpublic int getMaxTokenType() {\n\t\treturn maxTokenType;\n\t}\n\n\t@Override\n\tpublic String getLiteralName(int tokenType) {\n\t\tif (tokenType >= 0 && tokenType < literalNames.length) {\n\t\t\treturn literalNames[tokenType];\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getSymbolicName(int tokenType) {\n\t\tif (tokenType >= 0 && tokenType < symbolicNames.length) {\n\t\t\treturn symbolicNames[tokenType];\n\t\t}\n\n\t\tif (tokenType == Token.EOF) {\n\t\t\treturn \"EOF\";\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getDisplayName(int tokenType) {\n\t\tif (tokenType >= 0 && tokenType < displayNames.length) {\n\t\t\tString displayName = displayNames[tokenType];\n\t\t\tif (displayName != null) {\n\t\t\t\treturn displayName;\n\t\t\t}\n\t\t}\n\n\t\tString literalName = getLiteralName(tokenType);\n\t\tif (literalName != null) {\n\t\t\treturn literalName;\n\t\t}\n\n\t\tString symbolicName = getSymbolicName(tokenType);\n\t\tif (symbolicName != null) {\n\t\t\treturn symbolicName;\n\t\t}\n\n\t\treturn Integer.toString(tokenType);\n\t}\n\n\t// Because this is an actual implementation object, we can provide access methods for vocabulary symbols\n\n\tpublic String[] getLiteralNames() {\n\t\treturn literalNames;\n\t}\n\n\tpublic String[] getSymbolicNames() {\n\t\treturn symbolicNames;\n\t}\n\n\tpublic String[] getDisplayNames() {\n\t\treturn displayNames;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/WritableToken.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\npublic interface WritableToken extends Token {\n\tpublic void setText(String text);\n\n\tpublic void setType(int ttype);\n\n\tpublic void setLine(int line);\n\n\tpublic void setCharPositionInLine(int pos);\n\n\tpublic void setChannel(int channel);\n\n\tpublic void setTokenIndex(int index);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATN.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** */\npublic class ATN {\n\tpublic static final int INVALID_ALT_NUMBER = 0;\n\n\n\tpublic final List<ATNState> states = new ArrayList<ATNState>();\n\n\t/** Each subrule/rule is a decision point and we must track them so we\n\t *  can go back later and build DFA predictors for them.  This includes\n\t *  all the rules, subrules, optional blocks, ()+, ()* etc...\n\t */\n\tpublic final List<DecisionState> decisionToState = new ArrayList<DecisionState>();\n\n\t/**\n\t * Maps from rule index to starting state number.\n\t */\n\tpublic RuleStartState[] ruleToStartState;\n\n\t/**\n\t * Maps from rule index to stop state number.\n\t */\n\tpublic RuleStopState[] ruleToStopState;\n\n\n\tpublic final Map<String, TokensStartState> modeNameToStartState =\n\t\tnew LinkedHashMap<String, TokensStartState>();\n\n\t/**\n\t * The type of the ATN.\n\t */\n\tpublic final ATNType grammarType;\n\n\t/**\n\t * The maximum value for any symbol recognized by a transition in the ATN.\n\t */\n\tpublic final int maxTokenType;\n\n\t/**\n\t * For lexer ATNs, this maps the rule index to the resulting token type.\n\t * For parser ATNs, this maps the rule index to the generated bypass token\n\t * type if the\n\t * {@link ATNDeserializationOptions#isGenerateRuleBypassTransitions}\n\t * deserialization option was specified; otherwise, this is {@code null}.\n\t */\n\tpublic int[] ruleToTokenType;\n\n\t/**\n\t * For lexer ATNs, this is an array of {@link LexerAction} objects which may\n\t * be referenced by action transitions in the ATN.\n\t */\n\tpublic LexerAction[] lexerActions;\n\n\tpublic final List<TokensStartState> modeToStartState = new ArrayList<TokensStartState>();\n\n\t/** Used for runtime deserialization of ATNs from strings */\n\tpublic ATN(ATNType grammarType, int maxTokenType) {\n\t\tthis.grammarType = grammarType;\n\t\tthis.maxTokenType = maxTokenType;\n\t}\n\n\t/** Compute the set of valid tokens that can occur starting in state {@code s}.\n\t *  If {@code ctx} is null, the set of tokens will not include what can follow\n\t *  the rule surrounding {@code s}. In other words, the set will be\n\t *  restricted to tokens reachable staying within {@code s}'s rule.\n\t */\n\tpublic IntervalSet nextTokens(ATNState s, RuleContext ctx) {\n\t\tLL1Analyzer anal = new LL1Analyzer(this);\n\t\tIntervalSet next = anal.LOOK(s, ctx);\n\t\treturn next;\n\t}\n\n    /**\n\t * Compute the set of valid tokens that can occur starting in {@code s} and\n\t * staying in same rule. {@link Token#EPSILON} is in set if we reach end of\n\t * rule.\n     */\n    public IntervalSet nextTokens(ATNState s) {\n        if ( s.nextTokenWithinRule != null ) return s.nextTokenWithinRule;\n        s.nextTokenWithinRule = nextTokens(s, null);\n        s.nextTokenWithinRule.setReadonly(true);\n        return s.nextTokenWithinRule;\n    }\n\n\tpublic void addState(ATNState state) {\n\t\tif (state != null) {\n\t\t\tstate.atn = this;\n\t\t\tstate.stateNumber = states.size();\n\t\t}\n\n\t\tstates.add(state);\n\t}\n\n\tpublic void removeState(ATNState state) {\n\t\tstates.set(state.stateNumber, null); // just free mem, don't shift states in list\n\t}\n\n\tpublic int defineDecisionState(DecisionState s) {\n\t\tdecisionToState.add(s);\n\t\ts.decision = decisionToState.size()-1;\n\t\treturn s.decision;\n\t}\n\n    public DecisionState getDecisionState(int decision) {\n        if ( !decisionToState.isEmpty() ) {\n            return decisionToState.get(decision);\n        }\n        return null;\n    }\n\n\tpublic int getNumberOfDecisions() {\n\t\treturn decisionToState.size();\n\t}\n\n\t/**\n\t * Computes the set of input symbols which could follow ATN state number\n\t * {@code stateNumber} in the specified full {@code context}. This method\n\t * considers the complete parser context, but does not evaluate semantic\n\t * predicates (i.e. all predicates encountered during the calculation are\n\t * assumed true). If a path in the ATN exists from the starting state to the\n\t * {@link RuleStopState} of the outermost context without matching any\n\t * symbols, {@link Token#EOF} is added to the returned set.\n\t *\n\t * <p>If {@code context} is {@code null}, it is treated as {@link ParserRuleContext#EMPTY}.</p>\n\t *\n\t * Note that this does NOT give you the set of all tokens that could\n\t * appear at a given token position in the input phrase.  In other words,\n\t * it does not answer:\n\t *\n\t *   \"Given a specific partial input phrase, return the set of all tokens\n\t *    that can follow the last token in the input phrase.\"\n\t *\n\t * The big difference is that with just the input, the parser could\n\t * land right in the middle of a lookahead decision. Getting\n     * all *possible* tokens given a partial input stream is a separate\n     * computation. See https://github.com/antlr/antlr4/issues/1428\n\t *\n\t * For this function, we are specifying an ATN state and call stack to compute\n\t * what token(s) can come next and specifically: outside of a lookahead decision.\n\t * That is what you want for error reporting and recovery upon parse error.\n\t *\n\t * @param stateNumber the ATN state number\n\t * @param context the full parse context\n\t * @return The set of potentially valid input symbols which could follow the\n\t * specified state in the specified context.\n\t * @throws IllegalArgumentException if the ATN does not contain a state with\n\t * number {@code stateNumber}\n\t */\n\tpublic IntervalSet getExpectedTokens(int stateNumber, RuleContext context) {\n\t\tif (stateNumber < 0 || stateNumber >= states.size()) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid state number.\");\n\t\t}\n\n\t\tRuleContext ctx = context;\n\t\tATNState s = states.get(stateNumber);\n\t\tIntervalSet following = nextTokens(s);\n\t\tif (!following.contains(Token.EPSILON)) {\n\t\t\treturn following;\n\t\t}\n\n\t\tIntervalSet expected = new IntervalSet();\n\t\texpected.addAll(following);\n\t\texpected.remove(Token.EPSILON);\n\t\twhile (ctx != null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {\n\t\t\tATNState invokingState = states.get(ctx.invokingState);\n\t\t\tRuleTransition rt = (RuleTransition)invokingState.transition(0);\n\t\t\tfollowing = nextTokens(rt.followState);\n\t\t\texpected.addAll(following);\n\t\t\texpected.remove(Token.EPSILON);\n\t\t\tctx = ctx.parent;\n\t\t}\n\n\t\tif (following.contains(Token.EPSILON)) {\n\t\t\texpected.add(Token.EOF);\n\t\t}\n\n\t\treturn expected;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNConfig.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Recognizer;\nimport org.antlr.v4.runtime.misc.DoubleKeyMap;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\nimport java.util.Objects;\n\n/** A tuple: (ATN state, predicted alt, syntactic, semantic context).\n *  The syntactic context is a graph-structured stack node whose\n *  path(s) to the root is the rule invocation(s)\n *  chain used to arrive at the state.  The semantic context is\n *  the tree of semantic predicates encountered before reaching\n *  an ATN state.\n */\npublic class ATNConfig {\n\t/**\n\t * This field stores the bit mask for implementing the\n\t * {@link #isPrecedenceFilterSuppressed} property as a bit within the\n\t * existing {@link #reachesIntoOuterContext} field.\n\t */\n\tprivate static final int SUPPRESS_PRECEDENCE_FILTER = 0x40000000;\n\n\t/** The ATN state associated with this configuration */\n\tpublic final ATNState state;\n\n\t/** What alt (or lexer rule) is predicted by this configuration */\n\tpublic final int alt;\n\n\t/** The stack of invoking states leading to the rule/states associated\n\t *  with this config.  We track only those contexts pushed during\n\t *  execution of the ATN simulator.\n\t */\n\tpublic PredictionContext context;\n\n\t/**\n\t * We cannot execute predicates dependent upon local context unless\n\t * we know for sure we are in the correct context. Because there is\n\t * no way to do this efficiently, we simply cannot evaluate\n\t * dependent predicates unless we are in the rule that initially\n\t * invokes the ATN simulator.\n\t *\n\t * <p>\n\t * closure() tracks the depth of how far we dip into the outer context:\n\t * depth &gt; 0.  Note that it may not be totally accurate depth since I\n\t * don't ever decrement. TODO: make it a boolean then</p>\n\t *\n\t * <p>\n\t * For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method\n\t * is also backed by this field. Since the field is publicly accessible, the\n\t * highest bit which would not cause the value to become negative is used to\n\t * store this field. This choice minimizes the risk that code which only\n\t * compares this value to 0 would be affected by the new purpose of the\n\t * flag. It also ensures the performance of the existing {@link ATNConfig}\n\t * constructors as well as certain operations like\n\t * {@link ATNConfigSet#add(ATNConfig, DoubleKeyMap)} method are\n\t * <em>completely</em> unaffected by the change.</p>\n\t */\n\tpublic int reachesIntoOuterContext;\n\n\n    public final SemanticContext semanticContext;\n\n\tpublic ATNConfig(ATNConfig old) { // dup\n\t\tthis.state = old.state;\n\t\tthis.alt = old.alt;\n\t\tthis.context = old.context;\n\t\tthis.semanticContext = old.semanticContext;\n\t\tthis.reachesIntoOuterContext = old.reachesIntoOuterContext;\n\t}\n\n\tpublic ATNConfig(ATNState state,\n\t\t\t\t\t int alt,\n\t\t\t\t\t PredictionContext context)\n\t{\n\t\tthis(state, alt, context, SemanticContext.Empty.Instance);\n\t}\n\n\tpublic ATNConfig(ATNState state,\n\t\t\t\t\t int alt,\n\t\t\t\t\t PredictionContext context,\n\t\t\t\t\t SemanticContext semanticContext)\n\t{\n\t\tthis.state = state;\n\t\tthis.alt = alt;\n\t\tthis.context = context;\n\t\tthis.semanticContext = semanticContext;\n\t}\n\n    public ATNConfig(ATNConfig c, ATNState state) {\n   \t\tthis(c, state, c.context, c.semanticContext);\n   \t}\n\n\tpublic ATNConfig(ATNConfig c, ATNState state,\n\t\t SemanticContext semanticContext)\n{\n\t\tthis(c, state, c.context, semanticContext);\n\t}\n\n\tpublic ATNConfig(ATNConfig c,\n\t\t\t\t\t SemanticContext semanticContext)\n\t{\n\t\tthis(c, c.state, c.context, semanticContext);\n\t}\n\n    public ATNConfig(ATNConfig c, ATNState state,\n\t\t\t\t\t PredictionContext context)\n\t{\n        this(c, state, context, c.semanticContext);\n    }\n\n\tpublic ATNConfig(ATNConfig c, ATNState state,\n\t\t\t\t\t PredictionContext context,\n                     SemanticContext semanticContext)\n    {\n\t\tthis.state = state;\n\t\tthis.alt = c.alt;\n\t\tthis.context = context;\n\t\tthis.semanticContext = semanticContext;\n\t\tthis.reachesIntoOuterContext = c.reachesIntoOuterContext;\n\t}\n\n\t/**\n\t * This method gets the value of the {@link #reachesIntoOuterContext} field\n\t * as it existed prior to the introduction of the\n\t * {@link #isPrecedenceFilterSuppressed} method.\n\t */\n\tpublic final int getOuterContextDepth() {\n\t\treturn reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER;\n\t}\n\n\tpublic final boolean isPrecedenceFilterSuppressed() {\n\t\treturn (reachesIntoOuterContext & SUPPRESS_PRECEDENCE_FILTER) != 0;\n\t}\n\n\tpublic final void setPrecedenceFilterSuppressed(boolean value) {\n\t\tif (value) {\n\t\t\tthis.reachesIntoOuterContext |= 0x40000000;\n\t\t}\n\t\telse {\n\t\t\tthis.reachesIntoOuterContext &= ~SUPPRESS_PRECEDENCE_FILTER;\n\t\t}\n\t}\n\n\t/** An ATN configuration is equal to another if both have\n     *  the same state, they predict the same alternative, and\n     *  syntactic/semantic contexts are the same.\n     */\n    @Override\n    public boolean equals(Object o) {\n\t\tif (!(o instanceof ATNConfig)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn this.equals((ATNConfig)o);\n\t}\n\n\tpublic boolean equals(ATNConfig other) {\n\t\tif (this == other) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (other == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn this.state.stateNumber==other.state.stateNumber\n\t\t\t&& this.alt==other.alt\n\t\t\t&& Objects.equals(this.context, other.context)\n\t\t\t&& this.semanticContext.equals(other.semanticContext)\n\t\t\t&& this.isPrecedenceFilterSuppressed() == other.isPrecedenceFilterSuppressed();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hashCode = MurmurHash.initialize(7);\n\t\thashCode = MurmurHash.update(hashCode, state.stateNumber);\n\t\thashCode = MurmurHash.update(hashCode, alt);\n\t\thashCode = MurmurHash.update(hashCode, context);\n\t\thashCode = MurmurHash.update(hashCode, semanticContext);\n\t\thashCode = MurmurHash.finish(hashCode, 4);\n\t\treturn hashCode;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(null, true);\n\t}\n\n\tpublic String toString(Recognizer<?, ?> recog, boolean showAlt) {\n\t\tStringBuilder buf = new StringBuilder();\n//\t\tif ( state.ruleIndex>=0 ) {\n//\t\t\tif ( recog!=null ) buf.append(recog.getRuleNames()[state.ruleIndex]+\":\");\n//\t\t\telse buf.append(state.ruleIndex+\":\");\n//\t\t}\n\t\tbuf.append('(');\n\t\tbuf.append(state);\n\t\tif ( showAlt ) {\n            buf.append(\",\");\n            buf.append(alt);\n        }\n        if ( context!=null ) {\n            buf.append(\",[\");\n            buf.append(context.toString());\n\t\t\tbuf.append(\"]\");\n        }\n        if ( semanticContext!=null && semanticContext != SemanticContext.Empty.Instance ) {\n            buf.append(\",\");\n            buf.append(semanticContext);\n        }\n        if ( getOuterContextDepth()>0 ) {\n            buf.append(\",up=\").append(getOuterContextDepth());\n        }\n\t\tbuf.append(')');\n\t\treturn buf.toString();\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNConfigSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.AbstractEqualityComparator;\nimport org.antlr.v4.runtime.misc.Array2DHashSet;\nimport org.antlr.v4.runtime.misc.DoubleKeyMap;\n\nimport java.util.ArrayList;\nimport java.util.BitSet;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track\n * info about the set, with support for combining similar configurations using a\n * graph-structured stack.\n */\npublic class ATNConfigSet implements Set<ATNConfig> {\n\t/**\n\t * The reason that we need this is because we don't want the hash map to use\n\t * the standard hash code and equals. We need all configurations with the same\n\t * {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles\n\t * the number of objects associated with ATNConfigs. The other solution is to\n\t * use a hash table that lets us specify the equals/hashcode operation.\n\t */\n\tpublic static class ConfigHashSet extends AbstractConfigHashSet {\n\t\tpublic ConfigHashSet() {\n\t\t\tsuper(ConfigEqualityComparator.INSTANCE);\n\t\t}\n\t}\n\n\tpublic static final class ConfigEqualityComparator extends AbstractEqualityComparator<ATNConfig> {\n\t\tpublic static final ConfigEqualityComparator INSTANCE = new ConfigEqualityComparator();\n\n\t\tprivate ConfigEqualityComparator() {\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode(ATNConfig o) {\n\t\t\tint hashCode = 7;\n\t\t\thashCode = 31 * hashCode + o.state.stateNumber;\n\t\t\thashCode = 31 * hashCode + o.alt;\n\t\t\thashCode = 31 * hashCode + o.semanticContext.hashCode();\n\t        return hashCode;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(ATNConfig a, ATNConfig b) {\n\t\t\tif ( a==b ) return true;\n\t\t\tif ( a==null || b==null ) return false;\n\t\t\treturn a.state.stateNumber==b.state.stateNumber\n\t\t\t\t&& a.alt==b.alt\n\t\t\t\t&& a.semanticContext.equals(b.semanticContext);\n\t\t}\n\t}\n\n\t/** Indicates that the set of configurations is read-only. Do not\n\t *  allow any code to manipulate the set; DFA states will point at\n\t *  the sets and they must not change. This does not protect the other\n\t *  fields; in particular, conflictingAlts is set after\n\t *  we've made this readonly.\n \t */\n\tprotected boolean readonly = false;\n\n\t/**\n\t * All configs but hashed by (s, i, _, pi) not including context. Wiped out\n\t * when we go readonly as this set becomes a DFA state.\n\t */\n\tpublic AbstractConfigHashSet configLookup;\n\n\t/** Track the elements as they are added to the set; supports get(i) */\n\tpublic final ArrayList<ATNConfig> configs = new ArrayList<ATNConfig>(7);\n\n\t// TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation\n\t// TODO: can we track conflicts as they are added to save scanning configs later?\n\tpublic int uniqueAlt;\n\t/** Currently this is only used when we detect SLL conflict; this does\n\t *  not necessarily represent the ambiguous alternatives. In fact,\n\t *  I should also point out that this seems to include predicated alternatives\n\t *  that have predicates that evaluate to false. Computed in computeTargetState().\n \t */\n\tprotected BitSet conflictingAlts;\n\n\t// Used in parser and lexer. In lexer, it indicates we hit a pred\n\t// while computing a closure operation.  Don't make a DFA state from this.\n\tpublic boolean hasSemanticContext;\n\tpublic boolean dipsIntoOuterContext;\n\n\t/** Indicates that this configuration set is part of a full context\n\t *  LL prediction. It will be used to determine how to merge $. With SLL\n\t *  it's a wildcard whereas it is not for LL context merge.\n\t */\n\tpublic final boolean fullCtx;\n\n\tprivate int cachedHashCode = -1;\n\n\tpublic ATNConfigSet(boolean fullCtx) {\n\t\tconfigLookup = new ConfigHashSet();\n\t\tthis.fullCtx = fullCtx;\n\t}\n\tpublic ATNConfigSet() { this(true); }\n\n\tpublic ATNConfigSet(ATNConfigSet old) {\n\t\tthis(old.fullCtx);\n\t\taddAll(old);\n\t\tthis.uniqueAlt = old.uniqueAlt;\n\t\tthis.conflictingAlts = old.conflictingAlts;\n\t\tthis.hasSemanticContext = old.hasSemanticContext;\n\t\tthis.dipsIntoOuterContext = old.dipsIntoOuterContext;\n\t}\n\n\t@Override\n\tpublic boolean add(ATNConfig config) {\n\t\treturn add(config, null);\n\t}\n\n\t/**\n\t * Adding a new config means merging contexts with existing configs for\n\t * {@code (s, i, pi, _)}, where {@code s} is the\n\t * {@link ATNConfig#state}, {@code i} is the {@link ATNConfig#alt}, and\n\t * {@code pi} is the {@link ATNConfig#semanticContext}. We use\n\t * {@code (s,i,pi)} as key.\n\t *\n\t * <p>This method updates {@link #dipsIntoOuterContext} and\n\t * {@link #hasSemanticContext} when necessary.</p>\n\t */\n\tpublic boolean add(\n\t\tATNConfig config,\n\t\tDoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)\n\t{\n\t\tif ( readonly ) throw new IllegalStateException(\"This set is readonly\");\n\t\tif ( config.semanticContext != SemanticContext.Empty.Instance ) {\n\t\t\thasSemanticContext = true;\n\t\t}\n\t\tif (config.getOuterContextDepth() > 0) {\n\t\t\tdipsIntoOuterContext = true;\n\t\t}\n\t\tATNConfig existing = configLookup.getOrAdd(config);\n\t\tif ( existing==config ) { // we added this new one\n\t\t\tcachedHashCode = -1;\n\t\t\tconfigs.add(config);  // track order here\n\t\t\treturn true;\n\t\t}\n\t\t// a previous (s,i,pi,_), merge with it and save result\n\t\tboolean rootIsWildcard = !fullCtx;\n\t\tPredictionContext merged =\n\t\t\tPredictionContext.merge(existing.context, config.context, rootIsWildcard, mergeCache);\n\t\t// no need to check for existing.context, config.context in cache\n\t\t// since only way to create new graphs is \"call rule\" and here. We\n\t\t// cache at both places.\n\t\texisting.reachesIntoOuterContext =\n\t\t\tMath.max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext);\n\n\t\t// make sure to preserve the precedence filter suppression during the merge\n\t\tif (config.isPrecedenceFilterSuppressed()) {\n\t\t\texisting.setPrecedenceFilterSuppressed(true);\n\t\t}\n\n\t\texisting.context = merged; // replace context; no need to alt mapping\n\t\treturn true;\n\t}\n\n\t/** Return a List holding list of configs */\n    public List<ATNConfig> elements() { return configs; }\n\n\tpublic Set<ATNState> getStates() {\n\t\tSet<ATNState> states = new HashSet<ATNState>();\n\t\tfor (ATNConfig c : configs) {\n\t\t\tstates.add(c.state);\n\t\t}\n\t\treturn states;\n\t}\n\n\t/**\n\t * Gets the complete set of represented alternatives for the configuration\n\t * set.\n\t *\n\t * @return the set of represented alternatives in this configuration set\n\t *\n\t * @since 4.3\n\t */\n\n\tpublic BitSet getAlts() {\n\t\tBitSet alts = new BitSet();\n\t\tfor (ATNConfig config : configs) {\n\t\t\talts.set(config.alt);\n\t\t}\n\t\treturn alts;\n\t}\n\n\tpublic List<SemanticContext> getPredicates() {\n\t\tList<SemanticContext> preds = new ArrayList<SemanticContext>();\n\t\tfor (ATNConfig c : configs) {\n\t\t\tif ( c.semanticContext!=SemanticContext.Empty.Instance ) {\n\t\t\t\tpreds.add(c.semanticContext);\n\t\t\t}\n\t\t}\n\t\treturn preds;\n\t}\n\n\tpublic ATNConfig get(int i) { return configs.get(i); }\n\n\tpublic void optimizeConfigs(ATNSimulator interpreter) {\n\t\tif ( readonly ) throw new IllegalStateException(\"This set is readonly\");\n\t\tif ( configLookup.isEmpty() ) return;\n\n\t\tfor (ATNConfig config : configs) {\n//\t\t\tint before = PredictionContext.getAllContextNodes(config.context).size();\n\t\t\tconfig.context = interpreter.getCachedContext(config.context);\n//\t\t\tint after = PredictionContext.getAllContextNodes(config.context).size();\n//\t\t\tSystem.out.println(\"configs \"+before+\"->\"+after);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean addAll(Collection<? extends ATNConfig> coll) {\n\t\tfor (ATNConfig c : coll) add(c);\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(o instanceof ATNConfigSet)) {\n\t\t\treturn false;\n\t\t}\n\n//\t\tSystem.out.print(\"equals \" + this + \", \" + o+\" = \");\n\t\tATNConfigSet other = (ATNConfigSet)o;\n\t\tboolean same = configs!=null &&\n\t\t\tconfigs.equals(other.configs) &&  // includes stack context\n\t\t\tthis.fullCtx == other.fullCtx &&\n\t\t\tthis.uniqueAlt == other.uniqueAlt &&\n\t\t\tthis.conflictingAlts == other.conflictingAlts &&\n\t\t\tthis.hasSemanticContext == other.hasSemanticContext &&\n\t\t\tthis.dipsIntoOuterContext == other.dipsIntoOuterContext;\n\n//\t\tSystem.out.println(same);\n\t\treturn same;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tif (isReadonly()) {\n\t\t\tif (cachedHashCode == -1) {\n\t\t\t\tcachedHashCode = configs.hashCode();\n\t\t\t}\n\n\t\t\treturn cachedHashCode;\n\t\t}\n\n\t\treturn configs.hashCode();\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn configs.size();\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn configs.isEmpty();\n\t}\n\n\t@Override\n\tpublic boolean contains(Object o) {\n\t\tif (configLookup == null) {\n\t\t\tthrow new UnsupportedOperationException(\"This method is not implemented for readonly sets.\");\n\t\t}\n\n\t\treturn configLookup.contains(o);\n\t}\n\n\tpublic boolean containsFast(ATNConfig obj) {\n\t\tif (configLookup == null) {\n\t\t\tthrow new UnsupportedOperationException(\"This method is not implemented for readonly sets.\");\n\t\t}\n\n\t\treturn configLookup.containsFast(obj);\n\t}\n\n\t@Override\n\tpublic Iterator<ATNConfig> iterator() {\n\t\treturn configs.iterator();\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tif ( readonly ) throw new IllegalStateException(\"This set is readonly\");\n\t\tconfigs.clear();\n\t\tcachedHashCode = -1;\n\t\tconfigLookup.clear();\n\t}\n\n\tpublic boolean isReadonly() {\n\t\treturn readonly;\n\t}\n\n\tpublic void setReadonly(boolean readonly) {\n\t\tthis.readonly = readonly;\n\t\tconfigLookup = null; // can't mod, no need for lookup cache\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append(elements().toString());\n\t\tif ( hasSemanticContext ) buf.append(\",hasSemanticContext=\").append(hasSemanticContext);\n\t\tif ( uniqueAlt!=ATN.INVALID_ALT_NUMBER ) buf.append(\",uniqueAlt=\").append(uniqueAlt);\n\t\tif ( conflictingAlts!=null ) buf.append(\",conflictingAlts=\").append(conflictingAlts);\n\t\tif ( dipsIntoOuterContext ) buf.append(\",dipsIntoOuterContext\");\n\t\treturn buf.toString();\n\t}\n\n\t// satisfy interface\n\n\t@Override\n\tpublic ATNConfig[] toArray() {\n\t\treturn configLookup.toArray();\n\t}\n\n\t@Override\n\tpublic <T> T[] toArray(T[] a) {\n\t\treturn configLookup.toArray(a);\n\t}\n\n\t@Override\n\tpublic boolean remove(Object o) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic boolean containsAll(Collection<?> c) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic boolean retainAll(Collection<?> c) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic boolean removeAll(Collection<?> c) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\tpublic static abstract class AbstractConfigHashSet extends Array2DHashSet<ATNConfig> {\n\n\t\tpublic AbstractConfigHashSet(AbstractEqualityComparator<? super ATNConfig> comparator) {\n\t\t\tthis(comparator, 16, 2);\n\t\t}\n\n\t\tpublic AbstractConfigHashSet(AbstractEqualityComparator<? super ATNConfig> comparator, int initialCapacity, int initialBucketCapacity) {\n\t\t\tsuper(comparator, initialCapacity, initialBucketCapacity);\n\t\t}\n\n\t\t@Override\n\t\tprotected final ATNConfig asElementType(Object o) {\n\t\t\tif (!(o instanceof ATNConfig)) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn (ATNConfig)o;\n\t\t}\n\n\t\t@Override\n\t\tprotected final ATNConfig[][] createBuckets(int capacity) {\n\t\t\treturn new ATNConfig[capacity][];\n\t\t}\n\n\t\t@Override\n\t\tprotected final ATNConfig[] createBucket(int capacity) {\n\t\t\treturn new ATNConfig[capacity];\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNDeserializationOptions.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class ATNDeserializationOptions {\n\tprivate static final ATNDeserializationOptions defaultOptions;\n\tstatic {\n\t\tdefaultOptions = new ATNDeserializationOptions();\n\t\tdefaultOptions.makeReadOnly();\n\t}\n\n\tprivate boolean readOnly;\n\tprivate boolean verifyATN;\n\tprivate boolean generateRuleBypassTransitions;\n\n\tpublic ATNDeserializationOptions() {\n\t\tthis.verifyATN = true;\n\t\tthis.generateRuleBypassTransitions = false;\n\t}\n\n\tpublic ATNDeserializationOptions(ATNDeserializationOptions options) {\n\t\tthis.verifyATN = options.verifyATN;\n\t\tthis.generateRuleBypassTransitions = options.generateRuleBypassTransitions;\n\t}\n\n\n\tpublic static ATNDeserializationOptions getDefaultOptions() {\n\t\treturn defaultOptions;\n\t}\n\n\tpublic final boolean isReadOnly() {\n\t\treturn readOnly;\n\t}\n\n\tpublic final void makeReadOnly() {\n\t\treadOnly = true;\n\t}\n\n\tpublic final boolean isVerifyATN() {\n\t\treturn verifyATN;\n\t}\n\n\tpublic final void setVerifyATN(boolean verifyATN) {\n\t\tthrowIfReadOnly();\n\t\tthis.verifyATN = verifyATN;\n\t}\n\n\tpublic final boolean isGenerateRuleBypassTransitions() {\n\t\treturn generateRuleBypassTransitions;\n\t}\n\n\tpublic final void setGenerateRuleBypassTransitions(boolean generateRuleBypassTransitions) {\n\t\tthrowIfReadOnly();\n\t\tthis.generateRuleBypassTransitions = generateRuleBypassTransitions;\n\t}\n\n\tprotected void throwIfReadOnly() {\n\t\tif (isReadOnly()) {\n\t\t\tthrow new IllegalStateException(\"The object is read only.\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNDeserializer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.io.InvalidClassException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\n\n/** Deserialize ATNs for JavaTarget; it's complicated by the fact that java requires\n *  that we serialize the list of integers as 16 bit characters in a string. Other\n *  targets will have an array of ints generated and can simply decode the ints\n *  back into an ATN.\n *\n * @author Sam Harwell\n */\npublic class ATNDeserializer {\n\tpublic static final int SERIALIZED_VERSION;\n\tstatic {\n\t\tSERIALIZED_VERSION = 4;\n\t}\n\n\tprivate final ATNDeserializationOptions deserializationOptions;\n\n\tpublic ATNDeserializer() {\n\t\tthis(ATNDeserializationOptions.getDefaultOptions());\n\t}\n\n\tpublic ATNDeserializer(ATNDeserializationOptions deserializationOptions) {\n\t\tif (deserializationOptions == null) {\n\t\t\tdeserializationOptions = ATNDeserializationOptions.getDefaultOptions();\n\t\t}\n\n\t\tthis.deserializationOptions = deserializationOptions;\n\t}\n\n\tpublic ATN deserialize(char[] data) {\n\t\treturn deserialize(decodeIntsEncodedAs16BitWords(data));\n\t}\n\n\tpublic ATN deserialize(int[] data) {\n\t\tint p = 0;\n\t\tint version = data[p++];\n\t\tif (version != SERIALIZED_VERSION) {\n\t\t\tString reason = String.format(Locale.getDefault(), \"Could not deserialize ATN with version %d (expected %d).\", version, SERIALIZED_VERSION);\n\t\t\tthrow new UnsupportedOperationException(new InvalidClassException(ATN.class.getName(), reason));\n\t\t}\n\n\t\tATNType grammarType = ATNType.values()[data[p++]];\n\t\tint maxTokenType = data[p++];\n\t\tATN atn = new ATN(grammarType, maxTokenType);\n\n\t\t//\n\t\t// STATES\n\t\t//\n\t\tList<Pair<LoopEndState, Integer>> loopBackStateNumbers = new ArrayList<Pair<LoopEndState, Integer>>();\n\t\tList<Pair<BlockStartState, Integer>> endStateNumbers = new ArrayList<Pair<BlockStartState, Integer>>();\n\t\tint nstates = data[p++];\n\t\tfor (int i=0; i<nstates; i++) {\n\t\t\tint stype = data[p++];\n\t\t\t// ignore bad type of states\n\t\t\tif ( stype==ATNState.INVALID_TYPE ) {\n\t\t\t\tatn.addState(null);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint ruleIndex = data[p++];\n\t\t\tATNState s = stateFactory(stype, ruleIndex);\n\t\t\tif ( stype == ATNState.LOOP_END ) { // special case\n\t\t\t\tint loopBackStateNumber = data[p++];\n\t\t\t\tloopBackStateNumbers.add(new Pair<LoopEndState, Integer>((LoopEndState)s, loopBackStateNumber));\n\t\t\t}\n\t\t\telse if (s instanceof BlockStartState) {\n\t\t\t\tint endStateNumber = data[p++];\n\t\t\t\tendStateNumbers.add(new Pair<BlockStartState, Integer>((BlockStartState)s, endStateNumber));\n\t\t\t}\n\t\t\tatn.addState(s);\n\t\t}\n\n\t\t// delay the assignment of loop back and end states until we know all the state instances have been initialized\n\t\tfor (Pair<LoopEndState, Integer> pair : loopBackStateNumbers) {\n\t\t\tpair.a.loopBackState = atn.states.get(pair.b);\n\t\t}\n\n\t\tfor (Pair<BlockStartState, Integer> pair : endStateNumbers) {\n\t\t\tpair.a.endState = (BlockEndState)atn.states.get(pair.b);\n\t\t}\n\n\t\tint numNonGreedyStates = data[p++];\n\t\tfor (int i = 0; i < numNonGreedyStates; i++) {\n\t\t\tint stateNumber = data[p++];\n\t\t\t((DecisionState)atn.states.get(stateNumber)).nonGreedy = true;\n\t\t}\n\n\t\tint numPrecedenceStates = data[p++];\n\t\tfor (int i = 0; i < numPrecedenceStates; i++) {\n\t\t\tint stateNumber = data[p++];\n\t\t\t((RuleStartState)atn.states.get(stateNumber)).isLeftRecursiveRule = true;\n\t\t}\n\n\t\t//\n\t\t// RULES\n\t\t//\n\t\tint nrules = data[p++];\n\t\tif ( atn.grammarType == ATNType.LEXER ) {\n\t\t\tatn.ruleToTokenType = new int[nrules];\n\t\t}\n\n\t\tatn.ruleToStartState = new RuleStartState[nrules];\n\t\tfor (int i=0; i<nrules; i++) {\n\t\t\tint s = data[p++];\n\t\t\tRuleStartState startState = (RuleStartState)atn.states.get(s);\n\t\t\tatn.ruleToStartState[i] = startState;\n\t\t\tif ( atn.grammarType == ATNType.LEXER ) {\n\t\t\t\tint tokenType = data[p++];\n\t\t\t\tatn.ruleToTokenType[i] = tokenType;\n\t\t\t}\n\t\t}\n\n\t\tatn.ruleToStopState = new RuleStopState[nrules];\n\t\tfor (ATNState state : atn.states) {\n\t\t\tif (!(state instanceof RuleStopState)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tRuleStopState stopState = (RuleStopState)state;\n\t\t\tatn.ruleToStopState[state.ruleIndex] = stopState;\n\t\t\tatn.ruleToStartState[state.ruleIndex].stopState = stopState;\n\t\t}\n\n\t\t//\n\t\t// MODES\n\t\t//\n\t\tint nmodes = data[p++];\n\t\tfor (int i=0; i<nmodes; i++) {\n\t\t\tint s = data[p++];\n\t\t\tatn.modeToStartState.add((TokensStartState)atn.states.get(s));\n\t\t}\n\n\t\t//\n\t\t// SETS\n\t\t//\n\t\tList<IntervalSet> sets = new ArrayList<IntervalSet>();\n\t\tp = deserializeSets(data, p, sets);\n\n\t\t//\n\t\t// EDGES\n\t\t//\n\t\tint nedges = data[p++];\n\t\tfor (int i=0; i<nedges; i++) {\n\t\t\tint src = data[p];\n\t\t\tint trg = data[p+1];\n\t\t\tint ttype = data[p+2];\n\t\t\tint arg1 = data[p+3];\n\t\t\tint arg2 = data[p+4];\n\t\t\tint arg3 = data[p+5];\n\t\t\tTransition trans = edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);\n//\t\t\tSystem.out.println(\"EDGE \"+trans.getClass().getSimpleName()+\" \"+\n//\t\t\t\t\t\t\t   src+\"->\"+trg+\n//\t\t\t\t\t   \" \"+Transition.serializationNames[ttype]+\n//\t\t\t\t\t   \" \"+arg1+\",\"+arg2+\",\"+arg3);\n\t\t\tATNState srcState = atn.states.get(src);\n\t\t\tsrcState.addTransition(trans);\n\t\t\tp += 6;\n\t\t}\n\n\t\t// edges for rule stop states can be derived, so they aren't serialized\n\t\tfor (ATNState state : atn.states) {\n\t\t\tfor (int i = 0; i < state.getNumberOfTransitions(); i++) {\n\t\t\t\tTransition t = state.transition(i);\n\t\t\t\tif (!(t instanceof RuleTransition)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tRuleTransition ruleTransition = (RuleTransition)t;\n\t\t\t\tint outermostPrecedenceReturn = -1;\n\t\t\t\tif (atn.ruleToStartState[ruleTransition.target.ruleIndex].isLeftRecursiveRule) {\n\t\t\t\t\tif (ruleTransition.precedence == 0) {\n\t\t\t\t\t\toutermostPrecedenceReturn = ruleTransition.target.ruleIndex;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tEpsilonTransition returnTransition = new EpsilonTransition(ruleTransition.followState, outermostPrecedenceReturn);\n\t\t\t\tatn.ruleToStopState[ruleTransition.target.ruleIndex].addTransition(returnTransition);\n\t\t\t}\n\t\t}\n\n\t\tfor (ATNState state : atn.states) {\n\t\t\tif (state instanceof BlockStartState) {\n\t\t\t\t// we need to know the end state to set its start state\n\t\t\t\tif (((BlockStartState)state).endState == null) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\n\t\t\t\t// block end states can only be associated to a single block start state\n\t\t\t\tif (((BlockStartState)state).endState.startState != null) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\n\t\t\t\t((BlockStartState)state).endState.startState = (BlockStartState)state;\n\t\t\t}\n\n\t\t\tif (state instanceof PlusLoopbackState) {\n\t\t\t\tPlusLoopbackState loopbackState = (PlusLoopbackState)state;\n\t\t\t\tfor (int i = 0; i < loopbackState.getNumberOfTransitions(); i++) {\n\t\t\t\t\tATNState target = loopbackState.transition(i).target;\n\t\t\t\t\tif (target instanceof PlusBlockStartState) {\n\t\t\t\t\t\t((PlusBlockStartState)target).loopBackState = loopbackState;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (state instanceof StarLoopbackState) {\n\t\t\t\tStarLoopbackState loopbackState = (StarLoopbackState)state;\n\t\t\t\tfor (int i = 0; i < loopbackState.getNumberOfTransitions(); i++) {\n\t\t\t\t\tATNState target = loopbackState.transition(i).target;\n\t\t\t\t\tif (target instanceof StarLoopEntryState) {\n\t\t\t\t\t\t((StarLoopEntryState)target).loopBackState = loopbackState;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//\n\t\t// DECISIONS\n\t\t//\n\t\tint ndecisions = data[p++];\n\t\tfor (int i=1; i<=ndecisions; i++) {\n\t\t\tint s = data[p++];\n\t\t\tDecisionState decState = (DecisionState)atn.states.get(s);\n\t\t\tatn.decisionToState.add(decState);\n\t\t\tdecState.decision = i-1;\n\t\t}\n\n\t\t//\n\t\t// LEXER ACTIONS\n\t\t//\n\t\tif (atn.grammarType == ATNType.LEXER) {\n\t\t\tatn.lexerActions = new LexerAction[data[p++]];\n\t\t\tfor (int i = 0; i < atn.lexerActions.length; i++) {\n\t\t\t\tLexerActionType actionType = LexerActionType.values()[data[p++]];\n\t\t\t\tint data1 = data[p++];\n\t\t\t\tint data2 = data[p++];\n\n\t\t\t\tLexerAction lexerAction = lexerActionFactory(actionType, data1, data2);\n\n\t\t\t\tatn.lexerActions[i] = lexerAction;\n\t\t\t}\n\t\t}\n\n\t\tmarkPrecedenceDecisions(atn);\n\n\t\tif (deserializationOptions.isVerifyATN()) {\n\t\t\tverifyATN(atn);\n\t\t}\n\n\t\tif (deserializationOptions.isGenerateRuleBypassTransitions() && atn.grammarType == ATNType.PARSER) {\n\t\t\tatn.ruleToTokenType = new int[atn.ruleToStartState.length];\n\t\t\tfor (int i = 0; i < atn.ruleToStartState.length; i++) {\n\t\t\t\tatn.ruleToTokenType[i] = atn.maxTokenType + i + 1;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < atn.ruleToStartState.length; i++) {\n\t\t\t\tBasicBlockStartState bypassStart = new BasicBlockStartState();\n\t\t\t\tbypassStart.ruleIndex = i;\n\t\t\t\tatn.addState(bypassStart);\n\n\t\t\t\tBlockEndState bypassStop = new BlockEndState();\n\t\t\t\tbypassStop.ruleIndex = i;\n\t\t\t\tatn.addState(bypassStop);\n\n\t\t\t\tbypassStart.endState = bypassStop;\n\t\t\t\tatn.defineDecisionState(bypassStart);\n\n\t\t\t\tbypassStop.startState = bypassStart;\n\n\t\t\t\tATNState endState;\n\t\t\t\tTransition excludeTransition = null;\n\t\t\t\tif (atn.ruleToStartState[i].isLeftRecursiveRule) {\n\t\t\t\t\t// wrap from the beginning of the rule to the StarLoopEntryState\n\t\t\t\t\tendState = null;\n\t\t\t\t\tfor (ATNState state : atn.states) {\n\t\t\t\t\t\tif (state.ruleIndex != i) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!(state instanceof StarLoopEntryState)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tATNState maybeLoopEndState = state.transition(state.getNumberOfTransitions() - 1).target;\n\t\t\t\t\t\tif (!(maybeLoopEndState instanceof LoopEndState)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transition(0).target instanceof RuleStopState) {\n\t\t\t\t\t\t\tendState = state;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (endState == null) {\n\t\t\t\t\t\tthrow new UnsupportedOperationException(\"Couldn't identify final state of the precedence rule prefix section.\");\n\t\t\t\t\t}\n\n\t\t\t\t\texcludeTransition = ((StarLoopEntryState)endState).loopBackState.transition(0);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tendState = atn.ruleToStopState[i];\n\t\t\t\t}\n\n\t\t\t\t// all non-excluded transitions that currently target end state need to target blockEnd instead\n\t\t\t\tfor (ATNState state : atn.states) {\n\t\t\t\t\tfor (Transition transition : state.transitions) {\n\t\t\t\t\t\tif (transition == excludeTransition) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (transition.target == endState) {\n\t\t\t\t\t\t\ttransition.target = bypassStop;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// all transitions leaving the rule start state need to leave blockStart instead\n\t\t\t\twhile (atn.ruleToStartState[i].getNumberOfTransitions() > 0) {\n\t\t\t\t\tTransition transition = atn.ruleToStartState[i].removeTransition(atn.ruleToStartState[i].getNumberOfTransitions() - 1);\n\t\t\t\t\tbypassStart.addTransition(transition);\n\t\t\t\t}\n\n\t\t\t\t// link the new states\n\t\t\t\tatn.ruleToStartState[i].addTransition(new EpsilonTransition(bypassStart));\n\t\t\t\tbypassStop.addTransition(new EpsilonTransition(endState));\n\n\t\t\t\tATNState matchState = new BasicState();\n\t\t\t\tatn.addState(matchState);\n\t\t\t\tmatchState.addTransition(new AtomTransition(bypassStop, atn.ruleToTokenType[i]));\n\t\t\t\tbypassStart.addTransition(new EpsilonTransition(matchState));\n\t\t\t}\n\n\t\t\tif (deserializationOptions.isVerifyATN()) {\n\t\t\t\t// reverify after modification\n\t\t\t\tverifyATN(atn);\n\t\t\t}\n\t\t}\n\n\t\treturn atn;\n\t}\n\n\tprivate int deserializeSets(int[] data, int p, List<IntervalSet> sets) {\n\t\tint nsets = data[p++];\n\t\tfor (int i=0; i<nsets; i++) {\n\t\t\tint nintervals = data[p];\n\t\t\tp++;\n\t\t\tIntervalSet set = new IntervalSet();\n\t\t\tsets.add(set);\n\n\t\t\tboolean containsEof = data[p++] != 0;\n\t\t\tif (containsEof) {\n\t\t\t\tset.add(-1);\n\t\t\t}\n\n\t\t\tfor (int j=0; j<nintervals; j++) {\n\t\t\t\tint a = data[p++];\n\t\t\t\tint b = data[p++];\n\t\t\t\tset.add(a, b);\n\t\t\t}\n\t\t}\n\t\treturn p;\n\t}\n\n\t/**\n\t * Analyze the {@link StarLoopEntryState} states in the specified ATN to set\n\t * the {@link StarLoopEntryState#isPrecedenceDecision} field to the\n\t * correct value.\n\t *\n\t * @param atn The ATN.\n\t */\n\tprotected void markPrecedenceDecisions(ATN atn) {\n\t\tfor (ATNState state : atn.states) {\n\t\t\tif (!(state instanceof StarLoopEntryState)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* We analyze the ATN to determine if this ATN decision state is the\n\t\t\t * decision for the closure block that determines whether a\n\t\t\t * precedence rule should continue or complete.\n\t\t\t */\n\t\t\tif (atn.ruleToStartState[state.ruleIndex].isLeftRecursiveRule) {\n\t\t\t\tATNState maybeLoopEndState = state.transition(state.getNumberOfTransitions() - 1).target;\n\t\t\t\tif (maybeLoopEndState instanceof LoopEndState) {\n\t\t\t\t\tif (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transition(0).target instanceof RuleStopState) {\n\t\t\t\t\t\t((StarLoopEntryState)state).isPrecedenceDecision = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void verifyATN(ATN atn) {\n\t\t// verify assumptions\n\t\tfor (ATNState state : atn.states) {\n\t\t\tif (state == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcheckCondition(state.onlyHasEpsilonTransitions() || state.getNumberOfTransitions() <= 1);\n\n\t\t\tif (state instanceof PlusBlockStartState) {\n\t\t\t\tcheckCondition(((PlusBlockStartState)state).loopBackState != null);\n\t\t\t}\n\n\t\t\tif (state instanceof StarLoopEntryState) {\n\t\t\t\tStarLoopEntryState starLoopEntryState = (StarLoopEntryState)state;\n\t\t\t\tcheckCondition(starLoopEntryState.loopBackState != null);\n\t\t\t\tcheckCondition(starLoopEntryState.getNumberOfTransitions() == 2);\n\n\t\t\t\tif (starLoopEntryState.transition(0).target instanceof StarBlockStartState) {\n\t\t\t\t\tcheckCondition(starLoopEntryState.transition(1).target instanceof LoopEndState);\n\t\t\t\t\tcheckCondition(!starLoopEntryState.nonGreedy);\n\t\t\t\t}\n\t\t\t\telse if (starLoopEntryState.transition(0).target instanceof LoopEndState) {\n\t\t\t\t\tcheckCondition(starLoopEntryState.transition(1).target instanceof StarBlockStartState);\n\t\t\t\t\tcheckCondition(starLoopEntryState.nonGreedy);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (state instanceof StarLoopbackState) {\n\t\t\t\tcheckCondition(state.getNumberOfTransitions() == 1);\n\t\t\t\tcheckCondition(state.transition(0).target instanceof StarLoopEntryState);\n\t\t\t}\n\n\t\t\tif (state instanceof LoopEndState) {\n\t\t\t\tcheckCondition(((LoopEndState)state).loopBackState != null);\n\t\t\t}\n\n\t\t\tif (state instanceof RuleStartState) {\n\t\t\t\tcheckCondition(((RuleStartState)state).stopState != null);\n\t\t\t}\n\n\t\t\tif (state instanceof BlockStartState) {\n\t\t\t\tcheckCondition(((BlockStartState)state).endState != null);\n\t\t\t}\n\n\t\t\tif (state instanceof BlockEndState) {\n\t\t\t\tcheckCondition(((BlockEndState)state).startState != null);\n\t\t\t}\n\n\t\t\tif (state instanceof DecisionState) {\n\t\t\t\tDecisionState decisionState = (DecisionState)state;\n\t\t\t\tcheckCondition(decisionState.getNumberOfTransitions() <= 1 || decisionState.decision >= 0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcheckCondition(state.getNumberOfTransitions() <= 1 || state instanceof RuleStopState);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void checkCondition(boolean condition) {\n\t\tcheckCondition(condition, null);\n\t}\n\n\tprotected void checkCondition(boolean condition, String message) {\n\t\tif (!condition) {\n\t\t\tthrow new IllegalStateException(message);\n\t\t}\n\t}\n\n\tprotected static int toInt(char c) {\n\t\treturn c;\n\t}\n\n\tprotected static int toInt32(char[] data, int offset) {\n\t\treturn (int)data[offset] | ((int)data[offset + 1] << 16);\n\t}\n\n\tprotected static int toInt32(int[] data, int offset) {\n\t\treturn data[offset] | (data[offset + 1] << 16);\n\t}\n\n\tprotected Transition edgeFactory(ATN atn,\n\t\t\t\t\t\t\t\t\t\t int type, int src, int trg,\n\t\t\t\t\t\t\t\t\t\t int arg1, int arg2, int arg3,\n\t\t\t\t\t\t\t\t\t\t List<IntervalSet> sets)\n\t{\n\t\tATNState target = atn.states.get(trg);\n\t\tswitch (type) {\n\t\t\tcase Transition.EPSILON : return new EpsilonTransition(target);\n\t\t\tcase Transition.RANGE :\n\t\t\t\tif (arg3 != 0) {\n\t\t\t\t\treturn new RangeTransition(target, Token.EOF, arg2);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn new RangeTransition(target, arg1, arg2);\n\t\t\t\t}\n\t\t\tcase Transition.RULE :\n\t\t\t\tRuleTransition rt = new RuleTransition((RuleStartState)atn.states.get(arg1), arg2, arg3, target);\n\t\t\t\treturn rt;\n\t\t\tcase Transition.PREDICATE :\n\t\t\t\tPredicateTransition pt = new PredicateTransition(target, arg1, arg2, arg3 != 0);\n\t\t\t\treturn pt;\n\t\t\tcase Transition.PRECEDENCE:\n\t\t\t\treturn new PrecedencePredicateTransition(target, arg1);\n\t\t\tcase Transition.ATOM :\n\t\t\t\tif (arg3 != 0) {\n\t\t\t\t\treturn new AtomTransition(target, Token.EOF);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn new AtomTransition(target, arg1);\n\t\t\t\t}\n\t\t\tcase Transition.ACTION :\n\t\t\t\tActionTransition a = new ActionTransition(target, arg1, arg2, arg3 != 0);\n\t\t\t\treturn a;\n\t\t\tcase Transition.SET : return new SetTransition(target, sets.get(arg1));\n\t\t\tcase Transition.NOT_SET : return new NotSetTransition(target, sets.get(arg1));\n\t\t\tcase Transition.WILDCARD : return new WildcardTransition(target);\n\t\t}\n\n\t\tthrow new IllegalArgumentException(\"The specified transition type is not valid.\");\n\t}\n\n\tprotected ATNState stateFactory(int type, int ruleIndex) {\n\t\tATNState s;\n\t\tswitch (type) {\n\t\t\tcase ATNState.INVALID_TYPE: return null;\n\t\t\tcase ATNState.BASIC : s = new BasicState(); break;\n\t\t\tcase ATNState.RULE_START : s = new RuleStartState(); break;\n\t\t\tcase ATNState.BLOCK_START : s = new BasicBlockStartState(); break;\n\t\t\tcase ATNState.PLUS_BLOCK_START : s = new PlusBlockStartState(); break;\n\t\t\tcase ATNState.STAR_BLOCK_START : s = new StarBlockStartState(); break;\n\t\t\tcase ATNState.TOKEN_START : s = new TokensStartState(); break;\n\t\t\tcase ATNState.RULE_STOP : s = new RuleStopState(); break;\n\t\t\tcase ATNState.BLOCK_END : s = new BlockEndState(); break;\n\t\t\tcase ATNState.STAR_LOOP_BACK : s = new StarLoopbackState(); break;\n\t\t\tcase ATNState.STAR_LOOP_ENTRY : s = new StarLoopEntryState(); break;\n\t\t\tcase ATNState.PLUS_LOOP_BACK : s = new PlusLoopbackState(); break;\n\t\t\tcase ATNState.LOOP_END : s = new LoopEndState(); break;\n\t\t\tdefault :\n\t\t\t\tString message = String.format(Locale.getDefault(), \"The specified state type %d is not valid.\", type);\n\t\t\t\tthrow new IllegalArgumentException(message);\n\t\t}\n\n\t\ts.ruleIndex = ruleIndex;\n\t\treturn s;\n\t}\n\n\tprotected LexerAction lexerActionFactory(LexerActionType type, int data1, int data2) {\n\t\tswitch (type) {\n\t\tcase CHANNEL:\n\t\t\treturn new LexerChannelAction(data1);\n\n\t\tcase CUSTOM:\n\t\t\treturn new LexerCustomAction(data1, data2);\n\n\t\tcase MODE:\n\t\t\treturn new LexerModeAction(data1);\n\n\t\tcase MORE:\n\t\t\treturn LexerMoreAction.INSTANCE;\n\n\t\tcase POP_MODE:\n\t\t\treturn LexerPopModeAction.INSTANCE;\n\n\t\tcase PUSH_MODE:\n\t\t\treturn new LexerPushModeAction(data1);\n\n\t\tcase SKIP:\n\t\t\treturn LexerSkipAction.INSTANCE;\n\n\t\tcase TYPE:\n\t\t\treturn new LexerTypeAction(data1);\n\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException(String.format(Locale.getDefault(), \"The specified lexer action type %s is not valid.\", type));\n\t\t}\n\t}\n\n\t/** Given a list of integers representing a serialized ATN, encode values too large to fit into 15 bits\n\t *  as two 16bit values. We use the high bit (0x8000_0000) to indicate values requiring two 16 bit words.\n\t *  If the high bit is set, we grab the next value and combine them to get a 31-bit value. The possible\n\t *  input int values are [-1,0x7FFF_FFFF].\n\t *\n\t * \t\t| compression/encoding                         | uint16 count | type            |\n\t * \t\t| -------------------------------------------- | ------------ | --------------- |\n\t * \t\t| 0xxxxxxx xxxxxxxx                            | 1            | uint (15 bit)   |\n\t * \t\t| 1xxxxxxx xxxxxxxx yyyyyyyy yyyyyyyy          | 2            | uint (16+ bits) |\n\t * \t\t| 11111111 11111111 11111111 11111111          | 2            | int value -1    |\n\t *\n\t * \tThis is only used (other than for testing) by {@link org.antlr.v4.codegen.model.SerializedJavaATN}\n\t * \tto encode ints as char values for the java target, but it is convenient to combine it with the\n\t * \t#decodeIntsEncodedAs16BitWords that follows as they are a pair (I did not want to introduce a new class\n\t * \tinto the runtime). Used only for Java Target.\n\t */\n\tpublic static IntegerList encodeIntsWith16BitWords(IntegerList data) {\n\t\tIntegerList data16 = new IntegerList((int)(data.size()*1.5));\n\t\tfor (int i = 0; i < data.size(); i++) {\n\t\t\tint v = data.get(i);\n\t\t\tif ( v==-1 ) { // use two max uint16 for -1\n\t\t\t\tdata16.add(0xFFFF);\n\t\t\t\tdata16.add(0xFFFF);\n\t\t\t}\n\t\t\telse if (v <= 0x7FFF) {\n\t\t\t\tdata16.add(v);\n\t\t\t}\n\t\t\telse { // v > 0x7FFF\n\t\t\t\tif ( v>=0x7FFF_FFFF ) { // too big to fit in 15 bits + 16 bits? (+1 would be 8000_0000 which is bad encoding)\n\t\t\t\t\tthrow new UnsupportedOperationException(\"Serialized ATN data element[\"+i+\"] = \"+v+\" doesn't fit in 31 bits\");\n\t\t\t\t}\n\t\t\t\tv = v & 0x7FFF_FFFF;\t\t\t\t\t// strip high bit (sentinel) if set\n\t\t\t\tdata16.add((v >> 16) | 0x8000);   // store high 15-bit word first and set high bit to say word follows\n\t\t\t\tdata16.add((v & 0xFFFF)); \t\t// then store lower 16-bit word\n\t\t\t}\n\t\t}\n\t\treturn data16;\n\t}\n\n\tpublic static int[] decodeIntsEncodedAs16BitWords(char[] data16) {\n\t\treturn decodeIntsEncodedAs16BitWords(data16, false);\n\t}\n\n\t/** Convert a list of chars (16 uint) that represent a serialized and compressed list of ints for an ATN.\n\t *  This method pairs with {@link #encodeIntsWith16BitWords(IntegerList)} above. Used only for Java Target.\n\t */\n\tpublic static int[] decodeIntsEncodedAs16BitWords(char[] data16, boolean trimToSize) {\n\t\t// will be strictly smaller but we waste bit of space to avoid copying during initialization of parsers\n\t\tint[] data = new int[data16.length];\n\t\tint i = 0;\n\t\tint i2 = 0;\n\t\twhile ( i < data16.length ) {\n\t\t\tchar v = data16[i++];\n\t\t\tif ( (v & 0x8000) == 0 ) { // hi bit not set? Implies 1-word value\n\t\t\t\tdata[i2++] = v; // 7 bit int\n\t\t\t}\n\t\t\telse { // hi bit set. Implies 2-word value\n\t\t\t\tchar vnext = data16[i++];\n\t\t\t\tif ( v==0xFFFF && vnext == 0xFFFF ) { // is it -1?\n\t\t\t\t\tdata[i2++] = -1;\n\t\t\t\t}\n\t\t\t\telse { // 31-bit int\n\t\t\t\t\tdata[i2++] = (v & 0x7FFF) << 16 | (vnext & 0xFFFF);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( trimToSize ) {\n\t\t\treturn Arrays.copyOf(data, i2);\n\t\t}\n\t\treturn data;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNSerializer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.Locale;\nimport java.util.Map;\n\n/** This class represents a target neutral serializer for ATNs. An ATN is converted to a list of integers\n *  that can be converted back to and ATN. We compute the list of integers and then generate an array\n *  into the target language for a particular lexer or parser.  Java is a special case where we must\n *  generate strings instead of arrays, but that is handled outside of this class.\n *  See {@link ATNDeserializer#encodeIntsWith16BitWords(IntegerList)} and\n *  {@link org.antlr.v4.codegen.model.SerializedJavaATN}.\n */\npublic class ATNSerializer {\n\tpublic ATN atn;\n\n\tprivate final IntegerList data = new IntegerList();\n\t/** Note that we use a LinkedHashMap as a set to mainintain insertion order while deduplicating\n\t    entries with the same key. */\n\tprivate final Map<IntervalSet, Boolean> sets = new LinkedHashMap<>();\n\tprivate final IntegerList nonGreedyStates = new IntegerList();\n\tprivate final IntegerList precedenceStates = new IntegerList();\n\n\tpublic ATNSerializer(ATN atn) {\n\t\tassert atn.grammarType != null;\n\t\tthis.atn = atn;\n\t}\n\n\t/** Serialize state descriptors, edge descriptors, and decision&rarr;state map\n\t *  into list of ints.  Likely out of date, but keeping as it could be helpful:\n\t *\n\t *      SERIALIZED_VERSION\n\t *      UUID (2 longs)\n\t * \t\tgrammar-type, (ANTLRParser.LEXER, ...)\n\t *  \tmax token type,\n\t *  \tnum states,\n\t *  \tstate-0-type ruleIndex, state-1-type ruleIndex, ... state-i-type ruleIndex optional-arg ...\n\t *  \tnum rules,\n\t *  \trule-1-start-state rule-1-args, rule-2-start-state  rule-2-args, ...\n\t *  \t(args are token type,actionIndex in lexer else 0,0)\n\t *      num modes,\n\t *      mode-0-start-state, mode-1-start-state, ... (parser has 0 modes)\n\t *      num unicode-bmp-sets\n\t *      bmp-set-0-interval-count intervals, bmp-set-1-interval-count intervals, ...\n\t *      num unicode-smp-sets\n\t *      smp-set-0-interval-count intervals, smp-set-1-interval-count intervals, ...\n\t *\tnum total edges,\n\t *      src, trg, edge-type, edge arg1, optional edge arg2 (present always), ...\n\t *      num decisions,\n\t *      decision-0-start-state, decision-1-start-state, ...\n\t *\n\t *  Convenient to pack into unsigned shorts to make as Java string.\n\t */\n\tpublic IntegerList serialize() {\n\t\taddPreamble();\n\t\tint nedges = addEdges();\n\t\taddNonGreedyStates();\n\t\taddPrecedenceStates();\n\t\taddRuleStatesAndLexerTokenTypes();\n\t\taddModeStartStates();\n\t\tMap<IntervalSet, Integer> setIndices = null;\n\t\tsetIndices = addSets();\n\t\taddEdges(nedges, setIndices);\n\t\taddDecisionStartStates();\n\t\taddLexerActions();\n\n\t\treturn data;\n\t}\n\n\tprivate void addPreamble() {\n\t\tdata.add(ATNDeserializer.SERIALIZED_VERSION);\n\n\t\t// convert grammar type to ATN const to avoid dependence on ANTLRParser\n\t\tdata.add(atn.grammarType.ordinal());\n\t\tdata.add(atn.maxTokenType);\n\t}\n\n\tprivate void addLexerActions() {\n\t\tif (atn.grammarType == ATNType.LEXER) {\n\t\t\tdata.add(atn.lexerActions.length);\n\t\t\tfor (LexerAction action : atn.lexerActions) {\n\t\t\t\tdata.add(action.getActionType().ordinal());\n\t\t\t\tswitch (action.getActionType()) {\n\t\t\t\tcase CHANNEL:\n\t\t\t\t\tint channel = ((LexerChannelAction)action).getChannel();\n\t\t\t\t\tdata.add(channel);\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase CUSTOM:\n\t\t\t\t\tint ruleIndex = ((LexerCustomAction)action).getRuleIndex();\n\t\t\t\t\tint actionIndex = ((LexerCustomAction)action).getActionIndex();\n\t\t\t\t\tdata.add(ruleIndex);\n\t\t\t\t\tdata.add(actionIndex);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MODE:\n\t\t\t\t\tint mode = ((LexerModeAction)action).getMode();\n\t\t\t\t\tdata.add(mode);\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MORE:\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase POP_MODE:\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PUSH_MODE:\n\t\t\t\t\tmode = ((LexerPushModeAction)action).getMode();\n\t\t\t\t\tdata.add(mode);\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase SKIP:\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TYPE:\n\t\t\t\t\tint type = ((LexerTypeAction)action).getType();\n\t\t\t\t\tdata.add(type);\n\t\t\t\t\tdata.add(0);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tString message = String.format(Locale.getDefault(), \"The specified lexer action type %s is not valid.\", action.getActionType());\n\t\t\t\t\tthrow new IllegalArgumentException(message);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void addDecisionStartStates() {\n\t\tint ndecisions = atn.decisionToState.size();\n\t\tdata.add(ndecisions);\n\t\tfor (DecisionState decStartState : atn.decisionToState) {\n\t\t\tdata.add(decStartState.stateNumber);\n\t\t}\n\t}\n\n\tprivate void addEdges(int nedges, Map<IntervalSet, Integer> setIndices) {\n\t\tdata.add(nedges);\n\t\tfor (ATNState s : atn.states) {\n\t\t\tif ( s==null ) {\n\t\t\t\t// might be optimized away\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (s.getStateType() == ATNState.RULE_STOP) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int i=0; i<s.getNumberOfTransitions(); i++) {\n\t\t\t\tTransition t = s.transition(i);\n\n\t\t\t\tif (atn.states.get(t.target.stateNumber) == null) {\n\t\t\t\t\tthrow new IllegalStateException(\"Cannot serialize a transition to a removed state.\");\n\t\t\t\t}\n\n\t\t\t\tint src = s.stateNumber;\n\t\t\t\tint trg = t.target.stateNumber;\n\t\t\t\tint edgeType = Transition.serializationTypes.get(t.getClass());\n\t\t\t\tint arg1 = 0;\n\t\t\t\tint arg2 = 0;\n\t\t\t\tint arg3 = 0;\n\t\t\t\tswitch ( edgeType ) {\n\t\t\t\t\tcase Transition.RULE :\n\t\t\t\t\t\ttrg = ((RuleTransition)t).followState.stateNumber;\n\t\t\t\t\t\targ1 = ((RuleTransition)t).target.stateNumber;\n\t\t\t\t\t\targ2 = ((RuleTransition)t).ruleIndex;\n\t\t\t\t\t\targ3 = ((RuleTransition)t).precedence;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.PRECEDENCE:\n\t\t\t\t\t\tPrecedencePredicateTransition ppt = (PrecedencePredicateTransition)t;\n\t\t\t\t\t\targ1 = ppt.precedence;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.PREDICATE :\n\t\t\t\t\t\tPredicateTransition pt = (PredicateTransition)t;\n\t\t\t\t\t\targ1 = pt.ruleIndex;\n\t\t\t\t\t\targ2 = pt.predIndex;\n\t\t\t\t\t\targ3 = pt.isCtxDependent ? 1 : 0 ;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.RANGE :\n\t\t\t\t\t\targ1 = ((RangeTransition)t).from;\n\t\t\t\t\t\targ2 = ((RangeTransition)t).to;\n\t\t\t\t\t\tif (arg1 == Token.EOF) {\n\t\t\t\t\t\t\targ1 = 0;\n\t\t\t\t\t\t\targ3 = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.ATOM :\n\t\t\t\t\t\targ1 = ((AtomTransition)t).label;\n\t\t\t\t\t\tif (arg1 == Token.EOF) {\n\t\t\t\t\t\t\targ1 = 0;\n\t\t\t\t\t\t\targ3 = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.ACTION :\n\t\t\t\t\t\tActionTransition at = (ActionTransition)t;\n\t\t\t\t\t\targ1 = at.ruleIndex;\n\t\t\t\t\t\targ2 = at.actionIndex;\n\t\t\t\t\t\targ3 = at.isCtxDependent ? 1 : 0 ;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.SET :\n\t\t\t\t\t\targ1 = setIndices.get(((SetTransition)t).set);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.NOT_SET :\n\t\t\t\t\t\targ1 = setIndices.get(((SetTransition)t).set);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Transition.WILDCARD :\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdata.add(src);\n\t\t\t\tdata.add(trg);\n\t\t\t\tdata.add(edgeType);\n\t\t\t\tdata.add(arg1);\n\t\t\t\tdata.add(arg2);\n\t\t\t\tdata.add(arg3);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate Map<IntervalSet, Integer> addSets() {\n\t\tserializeSets(data,\tsets.keySet());\n\t\tMap<IntervalSet, Integer> setIndices = new HashMap<>();\n\t\tint setIndex = 0;\n\t\tfor (IntervalSet s : sets.keySet()) {\n\t\t\tsetIndices.put(s, setIndex++);\n\t\t}\n\t\treturn setIndices;\n\t}\n\n\tprivate void addModeStartStates() {\n\t\tint nmodes = atn.modeToStartState.size();\n\t\tdata.add(nmodes);\n\t\tif ( nmodes>0 ) {\n\t\t\tfor (ATNState modeStartState : atn.modeToStartState) {\n\t\t\t\tdata.add(modeStartState.stateNumber);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void addRuleStatesAndLexerTokenTypes() {\n\t\tint nrules = atn.ruleToStartState.length;\n\t\tdata.add(nrules);\n\t\tfor (int r=0; r<nrules; r++) {\n\t\t\tATNState ruleStartState = atn.ruleToStartState[r];\n\t\t\tdata.add(ruleStartState.stateNumber);\n\t\t\tif (atn.grammarType == ATNType.LEXER) {\n\t\t\t\tassert atn.ruleToTokenType[r]>=0; // 0 implies fragment rule, other token types > 0\n\t\t\t\tdata.add(atn.ruleToTokenType[r]);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void addPrecedenceStates() {\n\t\tdata.add(precedenceStates.size());\n\t\tfor (int i = 0; i < precedenceStates.size(); i++) {\n\t\t\tdata.add(precedenceStates.get(i));\n\t\t}\n\t}\n\n\tprivate void addNonGreedyStates() {\n\t\tdata.add(nonGreedyStates.size());\n\t\tfor (int i = 0; i < nonGreedyStates.size(); i++) {\n\t\t\tdata.add(nonGreedyStates.get(i));\n\t\t}\n\t}\n\n\tprivate int addEdges() {\n\t\tint nedges = 0;\n\t\tdata.add(atn.states.size());\n\t\tfor (ATNState s : atn.states) {\n\t\t\tif ( s==null ) { // might be optimized away\n\t\t\t\tdata.add(ATNState.INVALID_TYPE);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint stateType = s.getStateType();\n\t\t\tif (s instanceof DecisionState && ((DecisionState)s).nonGreedy) {\n\t\t\t\tnonGreedyStates.add(s.stateNumber);\n\t\t\t}\n\n\t\t\tif (s instanceof RuleStartState && ((RuleStartState)s).isLeftRecursiveRule) {\n\t\t\t\tprecedenceStates.add(s.stateNumber);\n\t\t\t}\n\n\t\t\tdata.add(stateType);\n\n\t\t\tdata.add(s.ruleIndex);\n\n\t\t\tif ( s.getStateType() == ATNState.LOOP_END ) {\n\t\t\t\tdata.add(((LoopEndState)s).loopBackState.stateNumber);\n\t\t\t}\n\t\t\telse if ( s instanceof BlockStartState ) {\n\t\t\t\tdata.add(((BlockStartState)s).endState.stateNumber);\n\t\t\t}\n\n\t\t\tif (s.getStateType() != ATNState.RULE_STOP) {\n\t\t\t\t// the deserializer can trivially derive these edges, so there's no need to serialize them\n\t\t\t\tnedges += s.getNumberOfTransitions();\n\t\t\t}\n\n\t\t\tfor (int i=0; i<s.getNumberOfTransitions(); i++) {\n\t\t\t\tTransition t = s.transition(i);\n\t\t\t\tint edgeType = Transition.serializationTypes.get(t.getClass());\n\t\t\t\tif ( edgeType == Transition.SET || edgeType == Transition.NOT_SET ) {\n\t\t\t\t\tSetTransition st = (SetTransition)t;\n\t\t\t\t\tsets.put(st.set, true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nedges;\n\t}\n\n\tprivate static void serializeSets(IntegerList data, Collection<IntervalSet> sets) {\n\t\tint nSets = sets.size();\n\t\tdata.add(nSets);\n\n\t\tfor (IntervalSet set : sets) {\n\t\t\tboolean containsEof = set.contains(Token.EOF);\n\t\t\tif (containsEof && set.getIntervals().get(0).b == Token.EOF) {\n\t\t\t\tdata.add(set.getIntervals().size() - 1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdata.add(set.getIntervals().size());\n\t\t\t}\n\n\t\t\tdata.add(containsEof ? 1 : 0);\n\t\t\tfor (Interval I : set.getIntervals()) {\n\t\t\t\tif (I.a == Token.EOF) {\n\t\t\t\t\tif (I.b == Token.EOF) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdata.add(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tdata.add(I.a);\n\t\t\t\t}\n\t\t\t\tdata.add(I.b);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static IntegerList getSerialized(ATN atn) {\n\t\treturn new ATNSerializer(atn).serialize();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNSimulator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.dfa.DFAState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.IdentityHashMap;\nimport java.util.List;\n\npublic abstract class ATNSimulator {\n\t/** Must distinguish between missing edge and edge we know leads nowhere */\n\n\tpublic static final DFAState ERROR;\n\n\tpublic final ATN atn;\n\n\t/** The context cache maps all PredictionContext objects that are equals()\n\t *  to a single cached copy. This cache is shared across all contexts\n\t *  in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet\n\t *  to use only cached nodes/graphs in addDFAState(). We don't want to\n\t *  fill this during closure() since there are lots of contexts that\n\t *  pop up but are not used ever again. It also greatly slows down closure().\n\t *\n\t *  <p>This cache makes a huge difference in memory and a little bit in speed.\n\t *  For the Java grammar on java.*, it dropped the memory requirements\n\t *  at the end from 25M to 16M. We don't store any of the full context\n\t *  graphs in the DFA because they are limited to local context only,\n\t *  but apparently there's a lot of repetition there as well. We optimize\n\t *  the config contexts before storing the config set in the DFA states\n\t *  by literally rebuilding them with cached subgraphs only.</p>\n\t *\n\t *  <p>I tried a cache for use during closure operations, that was\n\t *  whacked after each adaptivePredict(). It cost a little bit\n\t *  more time I think and doesn't save on the overall footprint\n\t *  so it's not worth the complexity.</p>\n \t */\n\tprotected final PredictionContextCache sharedContextCache;\n\n\tstatic {\n\t\tERROR = new DFAState(new ATNConfigSet());\n\t\tERROR.stateNumber = Integer.MAX_VALUE;\n\t}\n\n\tpublic ATNSimulator(ATN atn,\n\t\t\t\t\t\tPredictionContextCache sharedContextCache)\n\t{\n\t\tthis.atn = atn;\n\t\tthis.sharedContextCache = sharedContextCache;\n\t}\n\n\tpublic abstract void reset();\n\n\t/**\n\t * Clear the DFA cache used by the current instance. Since the DFA cache may\n\t * be shared by multiple ATN simulators, this method may affect the\n\t * performance (but not accuracy) of other parsers which are being used\n\t * concurrently.\n\t *\n\t * @throws UnsupportedOperationException if the current instance does not\n\t * support clearing the DFA.\n\t *\n\t * @since 4.3\n\t */\n\tpublic void clearDFA() {\n\t\tthrow new UnsupportedOperationException(\"This ATN simulator does not support clearing the DFA.\");\n\t}\n\n\tpublic PredictionContextCache getSharedContextCache() {\n\t\treturn sharedContextCache;\n\t}\n\n\tpublic PredictionContext getCachedContext(PredictionContext context) {\n\t\tif ( sharedContextCache==null ) return context;\n\n\t\tsynchronized (sharedContextCache) {\n\t\t\tIdentityHashMap<PredictionContext, PredictionContext> visited =\n\t\t\t\tnew IdentityHashMap<PredictionContext, PredictionContext>();\n\t\t\treturn PredictionContext.getCachedContext(context,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  sharedContextCache,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  visited);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n * The following images show the relation of states and\n * {@link ATNState#transitions} for various grammar constructs.\n *\n * <ul>\n *\n * <li>Solid edges marked with an &#0949; indicate a required\n * {@link EpsilonTransition}.</li>\n *\n * <li>Dashed edges indicate locations where any transition derived from\n * {@link Transition} might appear.</li>\n *\n * <li>Dashed nodes are place holders for either a sequence of linked\n * {@link BasicState} states or the inclusion of a block representing a nested\n * construct in one of the forms below.</li>\n *\n * <li>Nodes showing multiple outgoing alternatives with a {@code ...} support\n * any number of alternatives (one or more). Nodes without the {@code ...} only\n * support the exact number of alternatives shown in the diagram.</li>\n *\n * </ul>\n *\n * <h2>Basic Blocks</h2>\n *\n * <h3>Rule</h3>\n *\n * <embed src=\"images/Rule.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Block of 1 or more alternatives</h3>\n *\n * <embed src=\"images/Block.svg\" type=\"image/svg+xml\"/>\n *\n * <h2>Greedy Loops</h2>\n *\n * <h3>Greedy Closure: {@code (...)*}</h3>\n *\n * <embed src=\"images/ClosureGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Greedy Positive Closure: {@code (...)+}</h3>\n *\n * <embed src=\"images/PositiveClosureGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Greedy Optional: {@code (...)?}</h3>\n *\n * <embed src=\"images/OptionalGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h2>Non-Greedy Loops</h2>\n *\n * <h3>Non-Greedy Closure: {@code (...)*?}</h3>\n *\n * <embed src=\"images/ClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>\n *\n * <embed src=\"images/PositiveClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Non-Greedy Optional: {@code (...)??}</h3>\n *\n * <embed src=\"images/OptionalNonGreedy.svg\" type=\"image/svg+xml\"/>\n */\npublic abstract class ATNState {\n\tpublic static final int INITIAL_NUM_TRANSITIONS = 4;\n\n\t// constants for serialization\n\tpublic static final int INVALID_TYPE = 0;\n\tpublic static final int BASIC = 1;\n\tpublic static final int RULE_START = 2;\n\tpublic static final int BLOCK_START = 3;\n\tpublic static final int PLUS_BLOCK_START = 4;\n\tpublic static final int STAR_BLOCK_START = 5;\n\tpublic static final int TOKEN_START = 6;\n\tpublic static final int RULE_STOP = 7;\n\tpublic static final int BLOCK_END = 8;\n\tpublic static final int STAR_LOOP_BACK = 9;\n\tpublic static final int STAR_LOOP_ENTRY = 10;\n\tpublic static final int PLUS_LOOP_BACK = 11;\n\tpublic static final int LOOP_END = 12;\n\n\tpublic static final List<String> serializationNames =\n\t\tCollections.unmodifiableList(Arrays.asList(\n\t\t\t\"INVALID\",\n\t\t\t\"BASIC\",\n\t\t\t\"RULE_START\",\n\t\t\t\"BLOCK_START\",\n\t\t\t\"PLUS_BLOCK_START\",\n\t\t\t\"STAR_BLOCK_START\",\n\t\t\t\"TOKEN_START\",\n\t\t\t\"RULE_STOP\",\n\t\t\t\"BLOCK_END\",\n\t\t\t\"STAR_LOOP_BACK\",\n\t\t\t\"STAR_LOOP_ENTRY\",\n\t\t\t\"PLUS_LOOP_BACK\",\n\t\t\t\"LOOP_END\"\n\t\t));\n\n\tpublic static final int INVALID_STATE_NUMBER = -1;\n\n    /** Which ATN are we in? */\n   \tpublic ATN atn = null;\n\n\tpublic int stateNumber = INVALID_STATE_NUMBER;\n\n\tpublic int ruleIndex; // at runtime, we don't have Rule objects\n\n\tpublic boolean epsilonOnlyTransitions = false;\n\n\t/** Track the transitions emanating from this ATN state. */\n\tprotected final List<Transition> transitions =\n\t\tnew ArrayList<Transition>(INITIAL_NUM_TRANSITIONS);\n\n\t/** Used to cache lookahead during parsing, not used during construction */\n    public IntervalSet nextTokenWithinRule;\n\n\t@Override\n\tpublic int hashCode() { return stateNumber; }\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\t// are these states same object?\n\t\tif ( o instanceof ATNState ) return stateNumber==((ATNState)o).stateNumber;\n\t\treturn false;\n\t}\n\n\tpublic boolean isNonGreedyExitState() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.valueOf(stateNumber);\n\t}\n\n\tpublic Transition[] getTransitions() {\n\t\treturn transitions.toArray(new Transition[0]);\n\t}\n\n\tpublic int getNumberOfTransitions() {\n\t\treturn transitions.size();\n\t}\n\n\tpublic void addTransition(Transition e) {\n\t\taddTransition(transitions.size(), e);\n\t}\n\n\tpublic void addTransition(int index, Transition e) {\n\t\tif (transitions.isEmpty()) {\n\t\t\tepsilonOnlyTransitions = e.isEpsilon();\n\t\t}\n\t\telse if (epsilonOnlyTransitions != e.isEpsilon()) {\n\t\t\tSystem.err.format(Locale.getDefault(), \"ATN state %d has both epsilon and non-epsilon transitions.\\n\", stateNumber);\n\t\t\tepsilonOnlyTransitions = false;\n\t\t}\n\n\t\tboolean alreadyPresent = false;\n\t\tfor (Transition t : transitions) {\n\t\t\tif ( t.target.stateNumber == e.target.stateNumber ) {\n\t\t\t\tif ( t.label()!=null && e.label()!=null && t.label().equals(e.label()) ) {\n//\t\t\t\t\tSystem.err.println(\"Repeated transition upon \"+e.label()+\" from \"+stateNumber+\"->\"+t.target.stateNumber);\n\t\t\t\t\talreadyPresent = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if ( t.isEpsilon() && e.isEpsilon() ) {\n//\t\t\t\t\tSystem.err.println(\"Repeated epsilon transition from \"+stateNumber+\"->\"+t.target.stateNumber);\n\t\t\t\t\talreadyPresent = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( !alreadyPresent ) {\n\t\t\ttransitions.add(index, e);\n\t\t}\n\t}\n\n\tpublic Transition transition(int i) { return transitions.get(i); }\n\n\tpublic void setTransition(int i, Transition e) {\n\t\ttransitions.set(i, e);\n\t}\n\n\tpublic Transition removeTransition(int index) {\n\t\treturn transitions.remove(index);\n\t}\n\n\tpublic abstract int getStateType();\n\n\tpublic final boolean onlyHasEpsilonTransitions() {\n\t\treturn epsilonOnlyTransitions;\n\t}\n\n\tpublic void setRuleIndex(int ruleIndex) { this.ruleIndex = ruleIndex; }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ATNType.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n * Represents the type of recognizer an ATN applies to.\n *\n * @author Sam Harwell\n */\npublic enum ATNType {\n\n\t/**\n\t * A lexer grammar.\n\t */\n\tLEXER,\n\n\t/**\n\t * A parser grammar.\n\t */\n\tPARSER,\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/AbstractPredicateTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n *\n * @author Sam Harwell\n */\npublic abstract class AbstractPredicateTransition extends Transition {\n\n\tpublic AbstractPredicateTransition(ATNState target) {\n\t\tsuper(target);\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ActionTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic final class ActionTransition extends Transition {\n\tpublic final int ruleIndex;\n\tpublic final int actionIndex;\n\tpublic final boolean isCtxDependent; // e.g., $i ref in action\n\n\tpublic ActionTransition(ATNState target, int ruleIndex) {\n\t\tthis(target, ruleIndex, -1, false);\n\t}\n\n\tpublic ActionTransition(ATNState target, int ruleIndex, int actionIndex, boolean isCtxDependent) {\n\t\tsuper(target);\n\t\tthis.ruleIndex = ruleIndex;\n\t\tthis.actionIndex = actionIndex;\n\t\tthis.isCtxDependent = isCtxDependent;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn ACTION;\n\t}\n\n\t@Override\n\tpublic boolean isEpsilon() {\n\t\treturn true; // we are to be ignored by analysis 'cept for predicates\n\t}\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"action_\"+ruleIndex+\":\"+actionIndex;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/AmbiguityInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.ANTLRErrorListener;\nimport org.antlr.v4.runtime.TokenStream;\n\nimport java.util.BitSet;\n\n/**\n * This class represents profiling event information for an ambiguity.\n * Ambiguities are decisions where a particular input resulted in an SLL\n * conflict, followed by LL prediction also reaching a conflict state\n * (indicating a true ambiguity in the grammar).\n *\n * <p>\n * This event may be reported during SLL prediction in cases where the\n * conflicting SLL configuration set provides sufficient information to\n * determine that the SLL conflict is truly an ambiguity. For example, if none\n * of the ATN configurations in the conflicting SLL configuration set have\n * traversed a global follow transition (i.e.\n * {@link ATNConfig#reachesIntoOuterContext} is 0 for all configurations), then\n * the result of SLL prediction for that input is known to be equivalent to the\n * result of LL prediction for that input.</p>\n *\n * <p>\n * In some cases, the minimum represented alternative in the conflicting LL\n * configuration set is not equal to the minimum represented alternative in the\n * conflicting SLL configuration set. Grammars and inputs which result in this\n * scenario are unable to use {@link PredictionMode#SLL}, which in turn means\n * they cannot use the two-stage parsing strategy to improve parsing performance\n * for that input.</p>\n *\n * @see ParserATNSimulator#reportAmbiguity\n * @see ANTLRErrorListener#reportAmbiguity\n *\n * @since 4.3\n */\npublic class AmbiguityInfo extends DecisionEventInfo {\n\t/** The set of alternative numbers for this decision event that lead to a valid parse. */\n\tpublic BitSet ambigAlts;\n\n\t/**\n\t * Constructs a new instance of the {@link AmbiguityInfo} class with the\n\t * specified detailed ambiguity information.\n\t *\n\t * @param decision The decision number\n\t * @param configs The final configuration set identifying the ambiguous\n\t * alternatives for the current input\n\t * @param ambigAlts The set of alternatives in the decision that lead to a valid parse.\n\t *                  The predicted alt is the min(ambigAlts)\n\t * @param input The input token stream\n\t * @param startIndex The start index for the current prediction\n\t * @param stopIndex The index at which the ambiguity was identified during\n\t * prediction\n\t * @param fullCtx {@code true} if the ambiguity was identified during LL\n\t * prediction; otherwise, {@code false} if the ambiguity was identified\n\t * during SLL prediction\n\t */\n\tpublic AmbiguityInfo(int decision,\n\t\t\t\t\t\t ATNConfigSet configs,\n\t\t\t\t\t\t BitSet ambigAlts,\n\t\t\t\t\t\t TokenStream input, int startIndex, int stopIndex,\n\t\t\t\t\t\t boolean fullCtx)\n\t{\n\t\tsuper(decision, configs, input, startIndex, stopIndex, fullCtx);\n\t\tthis.ambigAlts = ambigAlts;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ArrayPredictionContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport java.util.Arrays;\n\npublic class ArrayPredictionContext extends PredictionContext {\n\t/** Parent can be null only if full ctx mode and we make an array\n\t *  from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and\n\t *  returnState == {@link #EMPTY_RETURN_STATE}.\n\t */\n\tpublic final PredictionContext[] parents;\n\n\t/** Sorted for merge, no duplicates; if present,\n\t *  {@link #EMPTY_RETURN_STATE} is always last.\n \t */\n\tpublic final int[] returnStates;\n\n\tpublic ArrayPredictionContext(SingletonPredictionContext a) {\n\t\tthis(new PredictionContext[] {a.parent}, new int[] {a.returnState});\n\t}\n\n\tpublic ArrayPredictionContext(PredictionContext[] parents, int[] returnStates) {\n\t\tsuper(calculateHashCode(parents, returnStates));\n\t\tassert parents!=null && parents.length>0;\n\t\tassert returnStates!=null && returnStates.length>0;\n//\t\tSystem.err.println(\"CREATE ARRAY: \"+Arrays.toString(parents)+\", \"+Arrays.toString(returnStates));\n\t\tthis.parents = parents;\n\t\tthis.returnStates = returnStates;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\t// since EMPTY_RETURN_STATE can only appear in the last position, we\n\t\t// don't need to verify that size==1\n\t\treturn returnStates[0]==EMPTY_RETURN_STATE;\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn returnStates.length;\n\t}\n\n\t@Override\n\tpublic PredictionContext getParent(int index) {\n\t\treturn parents[index];\n\t}\n\n\t@Override\n\tpublic int getReturnState(int index) {\n\t\treturn returnStates[index];\n\t}\n\n//\t@Override\n//\tpublic int findReturnState(int returnState) {\n//\t\treturn Arrays.binarySearch(returnStates, returnState);\n//\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\telse if ( !(o instanceof ArrayPredictionContext) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( this.hashCode() != o.hashCode() ) {\n\t\t\treturn false; // can't be same if hash is different\n\t\t}\n\n\t\tArrayPredictionContext a = (ArrayPredictionContext)o;\n\t\treturn Arrays.equals(returnStates, a.returnStates) &&\n\t\t       Arrays.equals(parents, a.parents);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tif ( isEmpty() ) return \"[]\";\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append(\"[\");\n\t\tfor (int i=0; i<returnStates.length; i++) {\n\t\t\tif ( i>0 ) buf.append(\", \");\n\t\t\tif ( returnStates[i]==EMPTY_RETURN_STATE ) {\n\t\t\t\tbuf.append(\"$\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbuf.append(returnStates[i]);\n\t\t\tif ( parents[i]!=null ) {\n\t\t\t\tbuf.append(' ');\n\t\t\t\tbuf.append(parents[i].toString());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbuf.append(\"null\");\n\t\t\t}\n\t\t}\n\t\tbuf.append(\"]\");\n\t\treturn buf.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/AtomTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\n/** TODO: make all transitions sets? no, should remove set edges */\npublic final class AtomTransition extends Transition {\n\t/** The token type or character value; or, signifies special label. */\n\tpublic final int label;\n\n\tpublic AtomTransition(ATNState target, int label) {\n\t\tsuper(target);\n\t\tthis.label = label;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn ATOM;\n\t}\n\n\t@Override\n\n\tpublic IntervalSet label() { return IntervalSet.of(label); }\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn label == symbol;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.valueOf(label);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/BasicBlockStartState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n *\n * @author Sam Harwell\n */\npublic final class BasicBlockStartState extends BlockStartState {\n\t@Override\n\tpublic int getStateType() {\n\t\treturn BLOCK_START;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/BasicState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n *\n * @author Sam Harwell\n */\npublic final class BasicState extends ATNState {\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn BASIC;\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/BlockEndState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** Terminal node of a simple {@code (a|b|c)} block. */\npublic final class BlockEndState extends ATNState {\n\tpublic BlockStartState startState;\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn BLOCK_END;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/BlockStartState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**  The start of a regular {@code (...)} block. */\npublic abstract class BlockStartState extends DecisionState {\n\tpublic BlockEndState endState;\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/CodePointTransitions.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n * Utility class to create {@link AtomTransition}, {@link RangeTransition},\n * and {@link SetTransition} appropriately based on the range of the input.\n *\n * Previously, we distinguished between atom and range transitions for\n * Unicode code points <= U+FFFF and those above. We used a set\n * transition for a Unicode code point > U+FFFF. Now that we can serialize\n * 32-bit int/chars in the ATN serialization, this is no longer necessary.\n */\npublic abstract class CodePointTransitions {\n\t/** Return new {@link AtomTransition} */\n\tpublic static Transition createWithCodePoint(ATNState target, int codePoint) {\n\t\treturn createWithCodePointRange(target, codePoint, codePoint);\n\t}\n\n\t/** Return new {@link AtomTransition} if range represents one atom else {@link SetTransition}. */\n\tpublic static Transition createWithCodePointRange(ATNState target, int codePointFrom, int codePointTo) {\n\t\treturn codePointFrom == codePointTo\n\t\t\t\t? new AtomTransition(target, codePointFrom)\n\t\t\t\t: new RangeTransition(target, codePointFrom, codePointTo);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ContextSensitivityInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.ANTLRErrorListener;\nimport org.antlr.v4.runtime.TokenStream;\n\n/**\n * This class represents profiling event information for a context sensitivity.\n * Context sensitivities are decisions where a particular input resulted in an\n * SLL conflict, but LL prediction produced a single unique alternative.\n *\n * <p>\n * In some cases, the unique alternative identified by LL prediction is not\n * equal to the minimum represented alternative in the conflicting SLL\n * configuration set. Grammars and inputs which result in this scenario are\n * unable to use {@link PredictionMode#SLL}, which in turn means they cannot use\n * the two-stage parsing strategy to improve parsing performance for that\n * input.</p>\n *\n * @see ParserATNSimulator#reportContextSensitivity\n * @see ANTLRErrorListener#reportContextSensitivity\n *\n * @since 4.3\n */\npublic class ContextSensitivityInfo extends DecisionEventInfo {\n\t/**\n\t * Constructs a new instance of the {@link ContextSensitivityInfo} class\n\t * with the specified detailed context sensitivity information.\n\t *\n\t * @param decision The decision number\n\t * @param configs The final configuration set containing the unique\n\t * alternative identified by full-context prediction\n\t * @param input The input token stream\n\t * @param startIndex The start index for the current prediction\n\t * @param stopIndex The index at which the context sensitivity was\n\t * identified during full-context prediction\n\t */\n\tpublic ContextSensitivityInfo(int decision,\n\t\t\t\t\t\t\t\t  ATNConfigSet configs,\n\t\t\t\t\t\t\t\t  TokenStream input, int startIndex, int stopIndex)\n\t{\n\t\tsuper( decision, configs, input, startIndex, stopIndex, true);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/DecisionEventInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.TokenStream;\n\n/**\n * This is the base class for gathering detailed information about prediction\n * events which occur during parsing.\n *\n * Note that we could record the parser call stack at the time this event\n * occurred but in the presence of left recursive rules, the stack is kind of\n * meaningless. It's better to look at the individual configurations for their\n * individual stacks. Of course that is a {@link PredictionContext} object\n * not a parse tree node and so it does not have information about the extent\n * (start...stop) of the various subtrees. Examining the stack tops of all\n * configurations provide the return states for the rule invocations.\n * From there you can get the enclosing rule.\n *\n * @since 4.3\n */\npublic class DecisionEventInfo {\n\t/**\n\t * The invoked decision number which this event is related to.\n\t *\n\t * @see ATN#decisionToState\n\t */\n\tpublic final int decision;\n\n\t/**\n\t * The configuration set containing additional information relevant to the\n\t * prediction state when the current event occurred, or {@code null} if no\n\t * additional information is relevant or available.\n\t */\n\tpublic final ATNConfigSet configs;\n\n\t/**\n\t * The input token stream which is being parsed.\n\t */\n\tpublic final TokenStream input;\n\n\t/**\n\t * The token index in the input stream at which the current prediction was\n\t * originally invoked.\n\t */\n\tpublic final int startIndex;\n\n\t/**\n\t * The token index in the input stream at which the current event occurred.\n\t */\n\tpublic final int stopIndex;\n\n\t/**\n\t * {@code true} if the current event occurred during LL prediction;\n\t * otherwise, {@code false} if the input occurred during SLL prediction.\n\t */\n\tpublic final boolean fullCtx;\n\n\tpublic DecisionEventInfo(int decision,\n\t\t\t\t\t\t\t ATNConfigSet configs,\n\t\t\t\t\t\t\t TokenStream input, int startIndex, int stopIndex,\n\t\t\t\t\t\t\t boolean fullCtx)\n\t{\n\t\tthis.decision = decision;\n\t\tthis.fullCtx = fullCtx;\n\t\tthis.stopIndex = stopIndex;\n\t\tthis.input = input;\n\t\tthis.startIndex = startIndex;\n\t\tthis.configs = configs;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/DecisionInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * This class contains profiling gathered for a particular decision.\n *\n * <p>\n * Parsing performance in ANTLR 4 is heavily influenced by both static factors\n * (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the\n * choice of input and the state of the DFA cache at the time profiling\n * operations are started). For best results, gather and use aggregate\n * statistics from a large sample of inputs representing the inputs expected in\n * production before using the results to make changes in the grammar.</p>\n *\n * @since 4.3\n */\npublic class DecisionInfo {\n\t/**\n\t * The decision number, which is an index into {@link ATN#decisionToState}.\n\t */\n\tpublic final int decision;\n\n\t/**\n\t * The total number of times {@link ParserATNSimulator#adaptivePredict} was\n\t * invoked for this decision.\n\t */\n\tpublic long invocations;\n\n\t/**\n\t * The total time spent in {@link ParserATNSimulator#adaptivePredict} for\n\t * this decision, in nanoseconds.\n\t *\n\t * <p>\n\t * The value of this field contains the sum of differential results obtained\n\t * by {@link System#nanoTime()}, and is not adjusted to compensate for JIT\n\t * and/or garbage collection overhead. For best accuracy, use a modern JVM\n\t * implementation that provides precise results from\n\t * {@link System#nanoTime()}, and perform profiling in a separate process\n\t * which is warmed up by parsing the input prior to profiling. If desired,\n\t * call {@link ATNSimulator#clearDFA} to reset the DFA cache to its initial\n\t * state before starting the profiling measurement pass.</p>\n\t */\n\tpublic long timeInPrediction;\n\n\t/**\n\t * The sum of the lookahead required for SLL prediction for this decision.\n\t * Note that SLL prediction is used before LL prediction for performance\n\t * reasons even when {@link PredictionMode#LL} or\n\t * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used.\n\t */\n\tpublic long SLL_TotalLook;\n\n\t/**\n\t * Gets the minimum lookahead required for any single SLL prediction to\n\t * complete for this decision, by reaching a unique prediction, reaching an\n\t * SLL conflict state, or encountering a syntax error.\n\t */\n\tpublic long SLL_MinLook;\n\n\t/**\n\t * Gets the maximum lookahead required for any single SLL prediction to\n\t * complete for this decision, by reaching a unique prediction, reaching an\n\t * SLL conflict state, or encountering a syntax error.\n\t */\n\tpublic long SLL_MaxLook;\n\n\t/**\n\t * Gets the {@link LookaheadEventInfo} associated with the event where the\n\t * {@link #SLL_MaxLook} value was set.\n\t */\n\tpublic LookaheadEventInfo SLL_MaxLookEvent;\n\n\t/**\n\t * The sum of the lookahead required for LL prediction for this decision.\n\t * Note that LL prediction is only used when SLL prediction reaches a\n\t * conflict state.\n\t */\n\tpublic long LL_TotalLook;\n\n\t/**\n\t * Gets the minimum lookahead required for any single LL prediction to\n\t * complete for this decision. An LL prediction completes when the algorithm\n\t * reaches a unique prediction, a conflict state (for\n\t * {@link PredictionMode#LL}, an ambiguity state (for\n\t * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error.\n\t */\n\tpublic long LL_MinLook;\n\n\t/**\n\t * Gets the maximum lookahead required for any single LL prediction to\n\t * complete for this decision. An LL prediction completes when the algorithm\n\t * reaches a unique prediction, a conflict state (for\n\t * {@link PredictionMode#LL}, an ambiguity state (for\n\t * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error.\n\t */\n\tpublic long LL_MaxLook;\n\n\t/**\n\t * Gets the {@link LookaheadEventInfo} associated with the event where the\n\t * {@link #LL_MaxLook} value was set.\n\t */\n\tpublic LookaheadEventInfo LL_MaxLookEvent;\n\n\t/**\n\t * A collection of {@link ContextSensitivityInfo} instances describing the\n\t * context sensitivities encountered during LL prediction for this decision.\n\t *\n\t * @see ContextSensitivityInfo\n\t */\n\tpublic final List<ContextSensitivityInfo> contextSensitivities = new ArrayList<ContextSensitivityInfo>();\n\n\t/**\n\t * A collection of {@link ErrorInfo} instances describing the parse errors\n\t * identified during calls to {@link ParserATNSimulator#adaptivePredict} for\n\t * this decision.\n\t *\n\t * @see ErrorInfo\n\t */\n\tpublic final List<ErrorInfo> errors = new ArrayList<ErrorInfo>();\n\n\t/**\n\t * A collection of {@link AmbiguityInfo} instances describing the\n\t * ambiguities encountered during LL prediction for this decision.\n\t *\n\t * @see AmbiguityInfo\n\t */\n\tpublic final List<AmbiguityInfo> ambiguities = new ArrayList<AmbiguityInfo>();\n\n\t/**\n\t * A collection of {@link PredicateEvalInfo} instances describing the\n\t * results of evaluating individual predicates during prediction for this\n\t * decision.\n\t *\n\t * @see PredicateEvalInfo\n\t */\n\tpublic final List<PredicateEvalInfo> predicateEvals = new ArrayList<PredicateEvalInfo>();\n\n\t/**\n\t * The total number of ATN transitions required during SLL prediction for\n\t * this decision. An ATN transition is determined by the number of times the\n\t * DFA does not contain an edge that is required for prediction, resulting\n\t * in on-the-fly computation of that edge.\n\t *\n\t * <p>\n\t * If DFA caching of SLL transitions is employed by the implementation, ATN\n\t * computation may cache the computed edge for efficient lookup during\n\t * future parsing of this decision. Otherwise, the SLL parsing algorithm\n\t * will use ATN transitions exclusively.</p>\n\t *\n\t * @see #SLL_ATNTransitions\n\t * @see ParserATNSimulator#computeTargetState\n\t * @see LexerATNSimulator#computeTargetState\n\t */\n\tpublic long SLL_ATNTransitions;\n\n\t/**\n\t * The total number of DFA transitions required during SLL prediction for\n\t * this decision.\n\t *\n\t * <p>If the ATN simulator implementation does not use DFA caching for SLL\n\t * transitions, this value will be 0.</p>\n\t *\n\t * @see ParserATNSimulator#getExistingTargetState\n\t * @see LexerATNSimulator#getExistingTargetState\n\t */\n\tpublic long SLL_DFATransitions;\n\n\t/**\n\t * Gets the total number of times SLL prediction completed in a conflict\n\t * state, resulting in fallback to LL prediction.\n\t *\n\t * <p>Note that this value is not related to whether or not\n\t * {@link PredictionMode#SLL} may be used successfully with a particular\n\t * grammar. If the ambiguity resolution algorithm applied to the SLL\n\t * conflicts for this decision produce the same result as LL prediction for\n\t * this decision, {@link PredictionMode#SLL} would produce the same overall\n\t * parsing result as {@link PredictionMode#LL}.</p>\n\t */\n\tpublic long LL_Fallback;\n\n\t/**\n\t * The total number of ATN transitions required during LL prediction for\n\t * this decision. An ATN transition is determined by the number of times the\n\t * DFA does not contain an edge that is required for prediction, resulting\n\t * in on-the-fly computation of that edge.\n\t *\n\t * <p>\n\t * If DFA caching of LL transitions is employed by the implementation, ATN\n\t * computation may cache the computed edge for efficient lookup during\n\t * future parsing of this decision. Otherwise, the LL parsing algorithm will\n\t * use ATN transitions exclusively.</p>\n\t *\n\t * @see #LL_DFATransitions\n\t * @see ParserATNSimulator#computeTargetState\n\t * @see LexerATNSimulator#computeTargetState\n\t */\n\tpublic long LL_ATNTransitions;\n\n\t/**\n\t * The total number of DFA transitions required during LL prediction for\n\t * this decision.\n\t *\n\t * <p>If the ATN simulator implementation does not use DFA caching for LL\n\t * transitions, this value will be 0.</p>\n\t *\n\t * @see ParserATNSimulator#getExistingTargetState\n\t * @see LexerATNSimulator#getExistingTargetState\n\t */\n\tpublic long LL_DFATransitions;\n\n\t/**\n\t * Constructs a new instance of the {@link DecisionInfo} class to contain\n\t * statistics for a particular decision.\n\t *\n\t * @param decision The decision number\n\t */\n\tpublic DecisionInfo(int decision) {\n\t\tthis.decision = decision;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"{\" +\n\t\t\t   \"decision=\" + decision +\n\t\t\t   \", contextSensitivities=\" + contextSensitivities.size() +\n\t\t\t   \", errors=\" + errors.size() +\n\t\t\t   \", ambiguities=\" + ambiguities.size() +\n\t\t\t   \", SLL_lookahead=\" + SLL_TotalLook +\n\t\t\t   \", SLL_ATNTransitions=\" + SLL_ATNTransitions +\n\t\t\t   \", SLL_DFATransitions=\" + SLL_DFATransitions +\n\t\t\t   \", LL_Fallback=\" + LL_Fallback +\n\t\t\t   \", LL_lookahead=\" + LL_TotalLook +\n\t\t\t   \", LL_ATNTransitions=\" + LL_ATNTransitions +\n\t\t\t   '}';\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/DecisionState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic abstract class DecisionState extends ATNState {\n\tpublic int decision = -1;\n\tpublic boolean nonGreedy;\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/EmptyPredictionContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic class EmptyPredictionContext extends SingletonPredictionContext {\n\t/**\n\t * Represents {@code $} in local context prediction, which means wildcard.\n\t * {@code *+x = *}.\n\t */\n\tpublic static final EmptyPredictionContext Instance = new EmptyPredictionContext();\n\n\tprivate EmptyPredictionContext() {\n\t\tsuper(null, EMPTY_RETURN_STATE);\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() { return true; }\n\n\t@Override\n\tpublic int size() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic PredictionContext getParent(int index) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic int getReturnState(int index) {\n\t\treturn returnState;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\treturn this == o;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"$\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/EpsilonTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic final class EpsilonTransition extends Transition {\n\n\tprivate final int outermostPrecedenceReturn;\n\n\tpublic EpsilonTransition(ATNState target) {\n\t\tthis(target, -1);\n\t}\n\n\tpublic EpsilonTransition(ATNState target, int outermostPrecedenceReturn) {\n\t\tsuper(target);\n\t\tthis.outermostPrecedenceReturn = outermostPrecedenceReturn;\n\t}\n\n\t/**\n\t * @return the rule index of a precedence rule for which this transition is\n\t * returning from, where the precedence value is 0; otherwise, -1.\n\t *\n\t * @see ATNConfig#isPrecedenceFilterSuppressed()\n\t * @see ParserATNSimulator#applyPrecedenceFilter(ATNConfigSet)\n\t * @since 4.4.1\n\t */\n\tpublic int outermostPrecedenceReturn() {\n\t\treturn outermostPrecedenceReturn;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn EPSILON;\n\t}\n\n\t@Override\n\tpublic boolean isEpsilon() { return true; }\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn false;\n\t}\n\n\t@Override\n\n\tpublic String toString() {\n\t\treturn \"epsilon\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ErrorInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.ANTLRErrorListener;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.RecognitionException;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\n\n/**\n * This class represents profiling event information for a syntax error\n * identified during prediction. Syntax errors occur when the prediction\n * algorithm is unable to identify an alternative which would lead to a\n * successful parse.\n *\n * @see Parser#notifyErrorListeners(Token, String, RecognitionException)\n * @see ANTLRErrorListener#syntaxError\n *\n * @since 4.3\n */\npublic class ErrorInfo extends DecisionEventInfo {\n\t/**\n\t * Constructs a new instance of the {@link ErrorInfo} class with the\n\t * specified detailed syntax error information.\n\t *\n\t * @param decision The decision number\n\t * @param configs The final configuration set reached during prediction\n\t * prior to reaching the {@link ATNSimulator#ERROR} state\n\t * @param input The input token stream\n\t * @param startIndex The start index for the current prediction\n\t * @param stopIndex The index at which the syntax error was identified\n\t * @param fullCtx {@code true} if the syntax error was identified during LL\n\t * prediction; otherwise, {@code false} if the syntax error was identified\n\t * during SLL prediction\n\t */\n\tpublic ErrorInfo(int decision,\n\t\t\t\t\t ATNConfigSet configs,\n\t\t\t\t\t TokenStream input, int startIndex, int stopIndex,\n\t\t\t\t\t boolean fullCtx)\n\t{\n\t\tsuper(decision, configs, input, startIndex, stopIndex, fullCtx);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LL1Analyzer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.BitSet;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class LL1Analyzer {\n\t/** Special value added to the lookahead sets to indicate that we hit\n\t *  a predicate during analysis if {@code seeThruPreds==false}.\n\t */\n\tpublic static final int HIT_PRED = Token.INVALID_TYPE;\n\n\tpublic final ATN atn;\n\n\tpublic LL1Analyzer(ATN atn) { this.atn = atn; }\n\n\t/**\n\t * Calculates the SLL(1) expected lookahead set for each outgoing transition\n\t * of an {@link ATNState}. The returned array has one element for each\n\t * outgoing transition in {@code s}. If the closure from transition\n\t * <em>i</em> leads to a semantic predicate before matching a symbol, the\n\t * element at index <em>i</em> of the result will be {@code null}.\n\t *\n\t * @param s the ATN state\n\t * @return the expected symbols for each outgoing transition of {@code s}.\n\t */\n\tpublic IntervalSet[] getDecisionLookahead(ATNState s) {\n//\t\tSystem.out.println(\"LOOK(\"+s.stateNumber+\")\");\n\t\tif ( s==null ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tIntervalSet[] look = new IntervalSet[s.getNumberOfTransitions()];\n\t\tfor (int alt = 0; alt < s.getNumberOfTransitions(); alt++) {\n\t\t\tlook[alt] = new IntervalSet();\n\t\t\tSet<ATNConfig> lookBusy = new HashSet<ATNConfig>();\n\t\t\tboolean seeThruPreds = false; // fail to get lookahead upon pred\n\t\t\t_LOOK(s.transition(alt).target, null, EmptyPredictionContext.Instance,\n\t\t\t\t  look[alt], lookBusy, new BitSet(), seeThruPreds, false);\n\t\t\t// Wipe out lookahead for this alternative if we found nothing\n\t\t\t// or we had a predicate when we !seeThruPreds\n\t\t\tif ( look[alt].size()==0 || look[alt].contains(HIT_PRED) ) {\n\t\t\t\tlook[alt] = null;\n\t\t\t}\n\t\t}\n\t\treturn look;\n\t}\n\n\t/**\n\t * Compute set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t *\n\t * <p>If {@code ctx} is {@code null} and the end of the rule containing\n\t * {@code s} is reached, {@link Token#EPSILON} is added to the result set.\n\t * If {@code ctx} is not {@code null} and the end of the outermost rule is\n\t * reached, {@link Token#EOF} is added to the result set.</p>\n\t *\n\t * @param s the ATN state\n\t * @param ctx the complete parser context, or {@code null} if the context\n\t * should be ignored\n\t *\n\t * @return The set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t */\n   \tpublic IntervalSet LOOK(ATNState s, RuleContext ctx) {\n\t\treturn LOOK(s, null, ctx);\n   \t}\n\n\t/**\n\t * Compute set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t *\n\t * <p>If {@code ctx} is {@code null} and the end of the rule containing\n\t * {@code s} is reached, {@link Token#EPSILON} is added to the result set.\n\t * If {@code ctx} is not {@code null} and the end of the outermost rule is\n\t * reached, {@link Token#EOF} is added to the result set.</p>\n\t *\n\t * @param s the ATN state\n\t * @param stopState the ATN state to stop at. This can be a\n\t * {@link BlockEndState} to detect epsilon paths through a closure.\n\t * @param ctx the complete parser context, or {@code null} if the context\n\t * should be ignored\n\t *\n\t * @return The set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t */\n\n   \tpublic IntervalSet LOOK(ATNState s, ATNState stopState, RuleContext ctx) {\n   \t\tIntervalSet r = new IntervalSet();\n\t\tboolean seeThruPreds = true; // ignore preds; get all lookahead\n\t\tPredictionContext lookContext = ctx != null ? PredictionContext.fromRuleContext(s.atn, ctx) : null;\n   \t\t_LOOK(s, stopState, lookContext,\n\t\t\t  r, new HashSet<ATNConfig>(), new BitSet(), seeThruPreds, true);\n   \t\treturn r;\n   \t}\n\n\t/**\n\t * Compute set of tokens that can follow {@code s} in the ATN in the\n\t * specified {@code ctx}.\n\t *\n\t * <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the\n\t * rule containing {@code s} is reached, {@link Token#EPSILON} is added to\n\t * the result set. If {@code ctx} is not {@code null} and {@code addEOF} is\n\t * {@code true} and {@code stopState} or the end of the outermost rule is\n\t * reached, {@link Token#EOF} is added to the result set.</p>\n\t *\n\t * @param s the ATN state.\n\t * @param stopState the ATN state to stop at. This can be a\n\t * {@link BlockEndState} to detect epsilon paths through a closure.\n\t * @param ctx The outer context, or {@code null} if the outer context should\n\t * not be used.\n\t * @param look The result lookahead set.\n\t * @param lookBusy A set used for preventing epsilon closures in the ATN\n\t * from causing a stack overflow. Outside code should pass\n\t * {@code new HashSet<ATNConfig>} for this argument.\n\t * @param calledRuleStack A set used for preventing left recursion in the\n\t * ATN from causing a stack overflow. Outside code should pass\n\t * {@code new BitSet()} for this argument.\n\t * @param seeThruPreds {@code true} to true semantic predicates as\n\t * implicitly {@code true} and \"see through them\", otherwise {@code false}\n\t * to treat semantic predicates as opaque and add {@link #HIT_PRED} to the\n\t * result if one is encountered.\n\t * @param addEOF Add {@link Token#EOF} to the result if the end of the\n\t * outermost context is reached. This parameter has no effect if {@code ctx}\n\t * is {@code null}.\n\t */\n    protected void _LOOK(ATNState s,\n\t\t\t\t\t\t ATNState stopState,\n\t\t\t\t\t\t PredictionContext ctx,\n\t\t\t\t\t\t IntervalSet look,\n                         Set<ATNConfig> lookBusy,\n\t\t\t\t\t\t BitSet calledRuleStack,\n\t\t\t\t\t\t boolean seeThruPreds, boolean addEOF)\n\t{\n//\t\tSystem.out.println(\"_LOOK(\"+s.stateNumber+\", ctx=\"+ctx);\n        ATNConfig c = new ATNConfig(s, 0, ctx);\n        if ( !lookBusy.add(c) ) return;\n\n\t\tif (s == stopState) {\n\t\t\tif (ctx == null) {\n\t\t\t\tlook.add(Token.EPSILON);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (ctx.isEmpty() && addEOF) {\n\t\t\t\tlook.add(Token.EOF);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n        if ( s instanceof RuleStopState ) {\n            if ( ctx==null ) {\n                look.add(Token.EPSILON);\n                return;\n            }\n            else if (ctx.isEmpty() && addEOF) {\n\t\t\t\tlook.add(Token.EOF);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif ( ctx != EmptyPredictionContext.Instance ) {\n\t\t\t\t// run thru all possible stack tops in ctx\n\t\t\t\tboolean removed = calledRuleStack.get(s.ruleIndex);\n\t\t\t\ttry {\n\t\t\t\t\tcalledRuleStack.clear(s.ruleIndex);\n\t\t\t\t\tfor (int i = 0; i < ctx.size(); i++) {\n\t\t\t\t\t\tATNState returnState = atn.states.get(ctx.getReturnState(i));\n//\t\t\t\t\t    System.out.println(\"popping back to \"+retState);\n\t\t\t\t\t\t_LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tif (removed) {\n\t\t\t\t\t\tcalledRuleStack.set(s.ruleIndex);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n        }\n\n        int n = s.getNumberOfTransitions();\n        for (int i=0; i<n; i++) {\n\t\t\tTransition t = s.transition(i);\n\t\t\tif ( t.getClass() == RuleTransition.class ) {\n\t\t\t\tif (calledRuleStack.get(((RuleTransition)t).target.ruleIndex)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tPredictionContext newContext =\n\t\t\t\t\tSingletonPredictionContext.create(ctx, ((RuleTransition)t).followState.stateNumber);\n\n\t\t\t\ttry {\n\t\t\t\t\tcalledRuleStack.set(((RuleTransition)t).target.ruleIndex);\n\t\t\t\t\t_LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tcalledRuleStack.clear(((RuleTransition)t).target.ruleIndex);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( t instanceof AbstractPredicateTransition ) {\n\t\t\t\tif ( seeThruPreds ) {\n\t\t\t\t\t_LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlook.add(HIT_PRED);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( t.isEpsilon() ) {\n\t\t\t\t_LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n\t\t\t}\n\t\t\telse if ( t.getClass() == WildcardTransition.class ) {\n\t\t\t\tlook.addAll( IntervalSet.of(Token.MIN_USER_TOKEN_TYPE, atn.maxTokenType) );\n\t\t\t}\n\t\t\telse {\n//\t\t\t\tSystem.out.println(\"adding \"+ t);\n\t\t\t\tIntervalSet set = t.label();\n\t\t\t\tif (set != null) {\n\t\t\t\t\tif (t instanceof NotSetTransition) {\n\t\t\t\t\t\tset = set.complement(IntervalSet.of(Token.MIN_USER_TOKEN_TYPE, atn.maxTokenType));\n\t\t\t\t\t}\n\t\t\t\t\tlook.addAll(set);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNConfig.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.MurmurHash;\nimport org.antlr.v4.runtime.misc.ObjectEqualityComparator;\n\npublic class LexerATNConfig extends ATNConfig {\n\t/**\n\t * This is the backing field for {@link #getLexerActionExecutor}.\n\t */\n\tprivate final LexerActionExecutor lexerActionExecutor;\n\n\tprivate final boolean passedThroughNonGreedyDecision;\n\n\tpublic LexerATNConfig(ATNState state,\n\t\t\t\t\t\t  int alt,\n\t\t\t\t\t\t  PredictionContext context)\n\t{\n\t\tsuper(state, alt, context, SemanticContext.Empty.Instance);\n\t\tthis.passedThroughNonGreedyDecision = false;\n\t\tthis.lexerActionExecutor = null;\n\t}\n\n\tpublic LexerATNConfig(ATNState state,\n\t\t\t\t\t\t  int alt,\n\t\t\t\t\t\t  PredictionContext context,\n\t\t\t\t\t\t  LexerActionExecutor lexerActionExecutor)\n\t{\n\t\tsuper(state, alt, context, SemanticContext.Empty.Instance);\n\t\tthis.lexerActionExecutor = lexerActionExecutor;\n\t\tthis.passedThroughNonGreedyDecision = false;\n\t}\n\n\tpublic LexerATNConfig(LexerATNConfig c, ATNState state) {\n\t\tsuper(c, state, c.context, c.semanticContext);\n\t\tthis.lexerActionExecutor = c.lexerActionExecutor;\n\t\tthis.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state);\n\t}\n\n\tpublic LexerATNConfig(LexerATNConfig c, ATNState state,\n\t\t\t\t\t\t  LexerActionExecutor lexerActionExecutor)\n\t{\n\t\tsuper(c, state, c.context, c.semanticContext);\n\t\tthis.lexerActionExecutor = lexerActionExecutor;\n\t\tthis.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state);\n\t}\n\n\tpublic LexerATNConfig(LexerATNConfig c, ATNState state,\n\t\t\t\t\t\t  PredictionContext context) {\n\t\tsuper(c, state, context, c.semanticContext);\n\t\tthis.lexerActionExecutor = c.lexerActionExecutor;\n\t\tthis.passedThroughNonGreedyDecision = checkNonGreedyDecision(c, state);\n\t}\n\n\t/**\n\t * Gets the {@link LexerActionExecutor} capable of executing the embedded\n\t * action(s) for the current configuration.\n\t */\n\tpublic final LexerActionExecutor getLexerActionExecutor() {\n\t\treturn lexerActionExecutor;\n\t}\n\n\tpublic final boolean hasPassedThroughNonGreedyDecision() {\n\t\treturn passedThroughNonGreedyDecision;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hashCode = MurmurHash.initialize(7);\n\t\thashCode = MurmurHash.update(hashCode, state.stateNumber);\n\t\thashCode = MurmurHash.update(hashCode, alt);\n\t\thashCode = MurmurHash.update(hashCode, context);\n\t\thashCode = MurmurHash.update(hashCode, semanticContext);\n\t\thashCode = MurmurHash.update(hashCode, passedThroughNonGreedyDecision ? 1 : 0);\n\t\thashCode = MurmurHash.update(hashCode, lexerActionExecutor);\n\t\thashCode = MurmurHash.finish(hashCode, 6);\n\t\treturn hashCode;\n\t}\n\n\t@Override\n\tpublic boolean equals(ATNConfig other) {\n\t\tif (this == other) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(other instanceof LexerATNConfig)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tLexerATNConfig lexerOther = (LexerATNConfig)other;\n\t\tif (passedThroughNonGreedyDecision != lexerOther.passedThroughNonGreedyDecision) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!ObjectEqualityComparator.INSTANCE.equals(lexerActionExecutor, lexerOther.lexerActionExecutor)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn super.equals(other);\n\t}\n\n\tprivate static boolean checkNonGreedyDecision(LexerATNConfig source, ATNState target) {\n\t\treturn source.passedThroughNonGreedyDecision\n\t\t\t|| target instanceof DecisionState && ((DecisionState)target).nonGreedy;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.IntStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.LexerNoViableAltException;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.dfa.DFAState;\nimport org.antlr.v4.runtime.misc.Interval;\n\nimport java.util.Locale;\n\n/** \"dup\" of ParserInterpreter */\npublic class LexerATNSimulator extends ATNSimulator {\n\tpublic static final boolean debug = false;\n\tpublic static final boolean dfa_debug = false;\n\n\tpublic static final int MIN_DFA_EDGE = 0;\n\tpublic static final int MAX_DFA_EDGE = 127; // forces unicode to stay in ATN\n\n\t/** When we hit an accept state in either the DFA or the ATN, we\n\t *  have to notify the character stream to start buffering characters\n\t *  via {@link IntStream#mark} and record the current state. The current sim state\n\t *  includes the current index into the input, the current line,\n\t *  and current character position in that line. Note that the Lexer is\n\t *  tracking the starting line and characterization of the token. These\n\t *  variables track the \"state\" of the simulator when it hits an accept state.\n\t *\n\t *  <p>We track these variables separately for the DFA and ATN simulation\n\t *  because the DFA simulation often has to fail over to the ATN\n\t *  simulation. If the ATN simulation fails, we need the DFA to fall\n\t *  back to its previously accepted state, if any. If the ATN succeeds,\n\t *  then the ATN does the accept and the DFA simulator that invoked it\n\t *  can simply return the predicted token type.</p>\n\t */\n\tprotected static class SimState {\n\t\tprotected int index = -1;\n\t\tprotected int line = 0;\n\t\tprotected int charPos = -1;\n\t\tprotected DFAState dfaState;\n\n\t\tprotected void reset() {\n\t\t\tindex = -1;\n\t\t\tline = 0;\n\t\t\tcharPos = -1;\n\t\t\tdfaState = null;\n\t\t}\n\t}\n\n\n\tprotected final Lexer recog;\n\n\t/** The current token's starting index into the character stream.\n\t *  Shared across DFA to ATN simulation in case the ATN fails and the\n\t *  DFA did not have a previous accept state. In this case, we use the\n\t *  ATN-generated exception object.\n\t */\n\tprotected int startIndex = -1;\n\n\t/** line number 1..n within the input */\n\tprotected int line = 1;\n\n\t/** The index of the character relative to the beginning of the line 0..n-1 */\n\tprotected int charPositionInLine = 0;\n\n\n\tpublic final DFA[] decisionToDFA;\n\tprotected int mode = Lexer.DEFAULT_MODE;\n\n\t/** Used during DFA/ATN exec to record the most recent accept configuration info */\n\n\tprotected final SimState prevAccept = new SimState();\n\n\tpublic LexerATNSimulator(ATN atn, DFA[] decisionToDFA,\n\t\t\t\t\t\t\t PredictionContextCache sharedContextCache)\n\t{\n\t\tthis(null, atn, decisionToDFA,sharedContextCache);\n\t}\n\n\tpublic LexerATNSimulator(Lexer recog, ATN atn,\n\t\t\t\t\t\t\t DFA[] decisionToDFA,\n\t\t\t\t\t\t\t PredictionContextCache sharedContextCache)\n\t{\n\t\tsuper(atn,sharedContextCache);\n\t\tthis.decisionToDFA = decisionToDFA;\n\t\tthis.recog = recog;\n\t}\n\n\tpublic void copyState(LexerATNSimulator simulator) {\n\t\tthis.charPositionInLine = simulator.charPositionInLine;\n\t\tthis.line = simulator.line;\n\t\tthis.mode = simulator.mode;\n\t\tthis.startIndex = simulator.startIndex;\n\t}\n\n\tpublic int match(CharStream input, int mode) {\n\t\tthis.mode = mode;\n\t\tint mark = input.mark();\n\t\ttry {\n\t\t\tthis.startIndex = input.index();\n\t\t\tthis.prevAccept.reset();\n\t\t\tDFA dfa = decisionToDFA[mode];\n\t\t\tif ( dfa.s0==null ) {\n\t\t\t\treturn matchATN(input);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn execATN(input, dfa.s0);\n\t\t\t}\n\t\t}\n\t\tfinally {\n\t\t\tinput.release(mark);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void reset() {\n\t\tprevAccept.reset();\n\t\tstartIndex = -1;\n\t\tline = 1;\n\t\tcharPositionInLine = 0;\n\t\tmode = Lexer.DEFAULT_MODE;\n\t}\n\n\t@Override\n\tpublic void clearDFA() {\n\t\tfor (int d = 0; d < decisionToDFA.length; d++) {\n\t\t\tdecisionToDFA[d] = new DFA(atn.getDecisionState(d), d);\n\t\t}\n\t}\n\n\tprotected int matchATN(CharStream input) {\n\t\tATNState startState = atn.modeToStartState.get(mode);\n\n\t\tif ( debug ) {\n\t\t\tSystem.out.format(Locale.getDefault(), \"matchATN mode %d start: %s\\n\", mode, startState);\n\t\t}\n\n\t\tint old_mode = mode;\n\n\t\tATNConfigSet s0_closure = computeStartState(input, startState);\n\t\tboolean suppressEdge = s0_closure.hasSemanticContext;\n\t\ts0_closure.hasSemanticContext = false;\n\n\t\tDFAState next = addDFAState(s0_closure);\n\t\tif (!suppressEdge) {\n\t\t\tdecisionToDFA[mode].s0 = next;\n\t\t}\n\n\t\tint predict = execATN(input, next);\n\n\t\tif ( debug ) {\n\t\t\tSystem.out.format(Locale.getDefault(), \"DFA after matchATN: %s\\n\", decisionToDFA[old_mode].toLexerString());\n\t\t}\n\n\t\treturn predict;\n\t}\n\n\tprotected int execATN(CharStream input, DFAState ds0) {\n\t\t//System.out.println(\"enter exec index \"+input.index()+\" from \"+ds0.configs);\n\t\tif ( debug ) {\n\t\t\tSystem.out.format(Locale.getDefault(), \"start state closure=%s\\n\", ds0.configs);\n\t\t}\n\n\t\tif (ds0.isAcceptState) {\n\t\t\t// allow zero-length tokens\n\t\t\tcaptureSimState(prevAccept, input, ds0);\n\t\t}\n\n\t\tint t = input.LA(1);\n\n\t\tDFAState s = ds0; // s is current/from DFA state\n\n\t\twhile ( true ) { // while more work\n\t\t\tif ( debug ) {\n\t\t\t\tSystem.out.format(Locale.getDefault(), \"execATN loop starting closure: %s\\n\", s.configs);\n\t\t\t}\n\n\t\t\t// As we move src->trg, src->trg, we keep track of the previous trg to\n\t\t\t// avoid looking up the DFA state again, which is expensive.\n\t\t\t// If the previous target was already part of the DFA, we might\n\t\t\t// be able to avoid doing a reach operation upon t. If s!=null,\n\t\t\t// it means that semantic predicates didn't prevent us from\n\t\t\t// creating a DFA state. Once we know s!=null, we check to see if\n\t\t\t// the DFA state has an edge already for t. If so, we can just reuse\n\t\t\t// it's configuration set; there's no point in re-computing it.\n\t\t\t// This is kind of like doing DFA simulation within the ATN\n\t\t\t// simulation because DFA simulation is really just a way to avoid\n\t\t\t// computing reach/closure sets. Technically, once we know that\n\t\t\t// we have a previously added DFA state, we could jump over to\n\t\t\t// the DFA simulator. But, that would mean popping back and forth\n\t\t\t// a lot and making things more complicated algorithmically.\n\t\t\t// This optimization makes a lot of sense for loops within DFA.\n\t\t\t// A character will take us back to an existing DFA state\n\t\t\t// that already has lots of edges out of it. e.g., .* in comments.\n\t\t\tDFAState target = getExistingTargetState(s, t);\n\t\t\tif (target == null) {\n\t\t\t\ttarget = computeTargetState(input, s, t);\n\t\t\t}\n\n\t\t\tif (target == ERROR) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// If this is a consumable input element, make sure to consume before\n\t\t\t// capturing the accept state so the input index, line, and char\n\t\t\t// position accurately reflect the state of the interpreter at the\n\t\t\t// end of the token.\n\t\t\tif (t != IntStream.EOF) {\n\t\t\t\tconsume(input);\n\t\t\t}\n\n\t\t\tif (target.isAcceptState) {\n\t\t\t\tcaptureSimState(prevAccept, input, target);\n\t\t\t\tif (t == IntStream.EOF) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tt = input.LA(1);\n\t\t\ts = target; // flip; current DFA target becomes new src/from state\n\t\t}\n\n\t\treturn failOrAccept(prevAccept, input, s.configs, t);\n\t}\n\n\t/**\n\t * Get an existing target state for an edge in the DFA. If the target state\n\t * for the edge has not yet been computed or is otherwise not available,\n\t * this method returns {@code null}.\n\t *\n\t * @param s The current DFA state\n\t * @param t The next input symbol\n\t * @return The existing target DFA state for the given input symbol\n\t * {@code t}, or {@code null} if the target state for this edge is not\n\t * already cached\n\t */\n\n\tprotected DFAState getExistingTargetState(DFAState s, int t) {\n\t\tif (s.edges == null || t < MIN_DFA_EDGE || t > MAX_DFA_EDGE) {\n\t\t\treturn null;\n\t\t}\n\n\t\tDFAState target = s.edges[t - MIN_DFA_EDGE];\n\t\tif (debug && target != null) {\n\t\t\tSystem.out.println(\"reuse state \"+s.stateNumber+\n\t\t\t\t\t\t\t   \" edge to \"+target.stateNumber);\n\t\t}\n\n\t\treturn target;\n\t}\n\n\t/**\n\t * Compute a target state for an edge in the DFA, and attempt to add the\n\t * computed state and corresponding edge to the DFA.\n\t *\n\t * @param input The input stream\n\t * @param s The current DFA state\n\t * @param t The next input symbol\n\t *\n\t * @return The computed target DFA state for the given input symbol\n\t * {@code t}. If {@code t} does not lead to a valid DFA state, this method\n\t * returns {@link #ERROR}.\n\t */\n\n\tprotected DFAState computeTargetState(CharStream input, DFAState s, int t) {\n\t\tATNConfigSet reach = new OrderedATNConfigSet();\n\n\t\t// if we don't find an existing DFA state\n\t\t// Fill reach starting from closure, following t transitions\n\t\tgetReachableConfigSet(input, s.configs, reach, t);\n\n\t\tif ( reach.isEmpty() ) { // we got nowhere on t from s\n\t\t\tif (!reach.hasSemanticContext) {\n\t\t\t\t// we got nowhere on t, don't throw out this knowledge; it'd\n\t\t\t\t// cause a failover from DFA later.\n\t\t\t\taddDFAEdge(s, t, ERROR);\n\t\t\t}\n\n\t\t\t// stop when we can't match any more char\n\t\t\treturn ERROR;\n\t\t}\n\n\t\t// Add an edge from s to target DFA found/created for reach\n\t\treturn addDFAEdge(s, t, reach);\n\t}\n\n\tprotected int failOrAccept(SimState prevAccept, CharStream input,\n\t\t\t\t\t\t\t   ATNConfigSet reach, int t)\n\t{\n\t\tif (prevAccept.dfaState != null) {\n\t\t\tLexerActionExecutor lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor;\n\t\t\taccept(input, lexerActionExecutor, startIndex,\n\t\t\t\tprevAccept.index, prevAccept.line, prevAccept.charPos);\n\t\t\treturn prevAccept.dfaState.prediction;\n\t\t}\n\t\telse {\n\t\t\t// if no accept and EOF is first char, return EOF\n\t\t\tif ( t==IntStream.EOF && input.index()==startIndex ) {\n\t\t\t\treturn Token.EOF;\n\t\t\t}\n\n\t\t\tthrow new LexerNoViableAltException(recog, input, startIndex, reach);\n\t\t}\n\t}\n\n\t/** Given a starting configuration set, figure out all ATN configurations\n\t *  we can reach upon input {@code t}. Parameter {@code reach} is a return\n\t *  parameter.\n\t */\n\tprotected void getReachableConfigSet(CharStream input, ATNConfigSet closure, ATNConfigSet reach, int t) {\n\t\t// this is used to skip processing for configs which have a lower priority\n\t\t// than a config that already reached an accept state for the same rule\n\t\tint skipAlt = ATN.INVALID_ALT_NUMBER;\n\t\tfor (ATNConfig c : closure) {\n\t\t\tboolean currentAltReachedAcceptState = c.alt == skipAlt;\n\t\t\tif (currentAltReachedAcceptState && ((LexerATNConfig)c).hasPassedThroughNonGreedyDecision()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ( debug ) {\n\t\t\t\tSystem.out.format(Locale.getDefault(), \"testing %s at %s\\n\", getTokenName(t), c.toString(recog, true));\n\t\t\t}\n\n\t\t\tint n = c.state.getNumberOfTransitions();\n\t\t\tfor (int ti=0; ti<n; ti++) {               // for each transition\n\t\t\t\tTransition trans = c.state.transition(ti);\n\t\t\t\tATNState target = getReachableTarget(trans, t);\n\t\t\t\tif ( target!=null ) {\n\t\t\t\t\tLexerActionExecutor lexerActionExecutor = ((LexerATNConfig)c).getLexerActionExecutor();\n\t\t\t\t\tif (lexerActionExecutor != null) {\n\t\t\t\t\t\tlexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index() - startIndex);\n\t\t\t\t\t}\n\n\t\t\t\t\tboolean treatEofAsEpsilon = t == CharStream.EOF;\n\t\t\t\t\tif (closure(input, new LexerATNConfig((LexerATNConfig)c, target, lexerActionExecutor), reach, currentAltReachedAcceptState, true, treatEofAsEpsilon)) {\n\t\t\t\t\t\t// any remaining configs for this alt have a lower priority than\n\t\t\t\t\t\t// the one that just reached an accept state.\n\t\t\t\t\t\tskipAlt = c.alt;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void accept(CharStream input, LexerActionExecutor lexerActionExecutor,\n\t\t\t\t\t\t  int startIndex, int index, int line, int charPos)\n\t{\n\t\tif ( debug ) {\n\t\t\tSystem.out.format(Locale.getDefault(), \"ACTION %s\\n\", lexerActionExecutor);\n\t\t}\n\n\t\t// seek to after last char in token\n\t\tinput.seek(index);\n\t\tthis.line = line;\n\t\tthis.charPositionInLine = charPos;\n\n\t\tif (lexerActionExecutor != null && recog != null) {\n\t\t\tlexerActionExecutor.execute(recog, input, startIndex);\n\t\t}\n\t}\n\n\n\tprotected ATNState getReachableTarget(Transition trans, int t) {\n\t\tif (trans.matches(t, Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE)) {\n\t\t\treturn trans.target;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\tprotected ATNConfigSet computeStartState(CharStream input,\n\t\t\t\t\t\t\t\t\t\t\t ATNState p)\n\t{\n\t\tPredictionContext initialContext = EmptyPredictionContext.Instance;\n\t\tATNConfigSet configs = new OrderedATNConfigSet();\n\t\tfor (int i=0; i<p.getNumberOfTransitions(); i++) {\n\t\t\tATNState target = p.transition(i).target;\n\t\t\tLexerATNConfig c = new LexerATNConfig(target, i+1, initialContext);\n\t\t\tclosure(input, c, configs, false, false, false);\n\t\t}\n\t\treturn configs;\n\t}\n\n\t/**\n\t * Since the alternatives within any lexer decision are ordered by\n\t * preference, this method stops pursuing the closure as soon as an accept\n\t * state is reached. After the first accept state is reached by depth-first\n\t * search from {@code config}, all other (potentially reachable) states for\n\t * this rule would have a lower priority.\n\t *\n\t * @return {@code true} if an accept state is reached, otherwise\n\t * {@code false}.\n\t */\n\tprotected boolean closure(CharStream input, LexerATNConfig config, ATNConfigSet configs, boolean currentAltReachedAcceptState, boolean speculative, boolean treatEofAsEpsilon) {\n\t\tif ( debug ) {\n\t\t\tSystem.out.println(\"closure(\"+config.toString(recog, true)+\")\");\n\t\t}\n\n\t\tif ( config.state instanceof RuleStopState ) {\n\t\t\tif ( debug ) {\n\t\t\t\tif ( recog!=null ) {\n\t\t\t\t\tSystem.out.format(Locale.getDefault(), \"closure at %s rule stop %s\\n\", recog.getRuleNames()[config.state.ruleIndex], config);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.format(Locale.getDefault(), \"closure at rule stop %s\\n\", config);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( config.context == null || config.context.hasEmptyPath() ) {\n\t\t\t\tif (config.context == null || config.context.isEmpty()) {\n\t\t\t\t\tconfigs.add(config);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconfigs.add(new LexerATNConfig(config, config.state, EmptyPredictionContext.Instance));\n\t\t\t\t\tcurrentAltReachedAcceptState = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( config.context!=null && !config.context.isEmpty() ) {\n\t\t\t\tfor (int i = 0; i < config.context.size(); i++) {\n\t\t\t\t\tif (config.context.getReturnState(i) != PredictionContext.EMPTY_RETURN_STATE) {\n\t\t\t\t\t\tPredictionContext newContext = config.context.getParent(i); // \"pop\" return state\n\t\t\t\t\t\tATNState returnState = atn.states.get(config.context.getReturnState(i));\n\t\t\t\t\t\tLexerATNConfig c = new LexerATNConfig(config, returnState, newContext);\n\t\t\t\t\t\tcurrentAltReachedAcceptState = closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn currentAltReachedAcceptState;\n\t\t}\n\n\t\t// optimization\n\t\tif ( !config.state.onlyHasEpsilonTransitions() ) {\n\t\t\tif (!currentAltReachedAcceptState || !config.hasPassedThroughNonGreedyDecision()) {\n\t\t\t\tconfigs.add(config);\n\t\t\t}\n\t\t}\n\n\t\tATNState p = config.state;\n\t\tfor (int i=0; i<p.getNumberOfTransitions(); i++) {\n\t\t\tTransition t = p.transition(i);\n\t\t\tLexerATNConfig c = getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon);\n\t\t\tif ( c!=null ) {\n\t\t\t\tcurrentAltReachedAcceptState = closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n\t\t\t}\n\t\t}\n\n\t\treturn currentAltReachedAcceptState;\n\t}\n\n\t// side-effect: can alter configs.hasSemanticContext\n\n\tprotected LexerATNConfig getEpsilonTarget(CharStream input,\n\t\t\t\t\t\t\t\t\t\t   LexerATNConfig config,\n\t\t\t\t\t\t\t\t\t\t   Transition t,\n\t\t\t\t\t\t\t\t\t\t   ATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t   boolean speculative,\n\t\t\t\t\t\t\t\t\t\t   boolean treatEofAsEpsilon)\n\t{\n\t\tLexerATNConfig c = null;\n\t\tswitch (t.getSerializationType()) {\n\t\t\tcase Transition.RULE:\n\t\t\t\tRuleTransition ruleTransition = (RuleTransition)t;\n\t\t\t\tPredictionContext newContext =\n\t\t\t\t\tSingletonPredictionContext.create(config.context, ruleTransition.followState.stateNumber);\n\t\t\t\tc = new LexerATNConfig(config, t.target, newContext);\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.PRECEDENCE:\n\t\t\t\tthrow new UnsupportedOperationException(\"Precedence predicates are not supported in lexers.\");\n\n\t\t\tcase Transition.PREDICATE:\n\t\t\t\t/*  Track traversing semantic predicates. If we traverse,\n\t\t\t\t we cannot add a DFA state for this \"reach\" computation\n\t\t\t\t because the DFA would not test the predicate again in the\n\t\t\t\t future. Rather than creating collections of semantic predicates\n\t\t\t\t like v3 and testing them on prediction, v4 will test them on the\n\t\t\t\t fly all the time using the ATN not the DFA. This is slower but\n\t\t\t\t semantically it's not used that often. One of the key elements to\n\t\t\t\t this predicate mechanism is not adding DFA states that see\n\t\t\t\t predicates immediately afterwards in the ATN. For example,\n\n\t\t\t\t a : ID {p1}? | ID {p2}? ;\n\n\t\t\t\t should create the start state for rule 'a' (to save start state\n\t\t\t\t competition), but should not create target of ID state. The\n\t\t\t\t collection of ATN states the following ID references includes\n\t\t\t\t states reached by traversing predicates. Since this is when we\n\t\t\t\t test them, we cannot cash the DFA state target of ID.\n\t\t\t */\n\t\t\t\tPredicateTransition pt = (PredicateTransition)t;\n\t\t\t\tif ( debug ) {\n\t\t\t\t\tSystem.out.println(\"EVAL rule \"+pt.ruleIndex+\":\"+pt.predIndex);\n\t\t\t\t}\n\t\t\t\tconfigs.hasSemanticContext = true;\n\t\t\t\tif (evaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative)) {\n\t\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.ACTION:\n\t\t\t\tif (config.context == null || config.context.hasEmptyPath()) {\n\t\t\t\t\t// execute actions anywhere in the start rule for a token.\n\t\t\t\t\t//\n\t\t\t\t\t// TODO: if the entry rule is invoked recursively, some\n\t\t\t\t\t// actions may be executed during the recursive call. The\n\t\t\t\t\t// problem can appear when hasEmptyPath() is true but\n\t\t\t\t\t// isEmpty() is false. In this case, the config needs to be\n\t\t\t\t\t// split into two contexts - one with just the empty path\n\t\t\t\t\t// and another with everything but the empty path.\n\t\t\t\t\t// Unfortunately, the current algorithm does not allow\n\t\t\t\t\t// getEpsilonTarget to return two configurations, so\n\t\t\t\t\t// additional modifications are needed before we can support\n\t\t\t\t\t// the split operation.\n\t\t\t\t\tLexerActionExecutor lexerActionExecutor = LexerActionExecutor.append(config.getLexerActionExecutor(), atn.lexerActions[((ActionTransition)t).actionIndex]);\n\t\t\t\t\tc = new LexerATNConfig(config, t.target, lexerActionExecutor);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// ignore actions in referenced rules\n\t\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tcase Transition.EPSILON:\n\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\tbreak;\n\n\t\t\tcase Transition.ATOM:\n\t\t\tcase Transition.RANGE:\n\t\t\tcase Transition.SET:\n\t\t\t\tif (treatEofAsEpsilon) {\n\t\t\t\t\tif (t.matches(CharStream.EOF, Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE)) {\n\t\t\t\t\t\tc = new LexerATNConfig(config, t.target);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn c;\n\t}\n\n\t/**\n\t * Evaluate a predicate specified in the lexer.\n\t *\n\t * <p>If {@code speculative} is {@code true}, this method was called before\n\t * {@link #consume} for the matched character. This method should call\n\t * {@link #consume} before evaluating the predicate to ensure position\n\t * sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine},\n\t * and {@link Lexer#getCharPositionInLine}, properly reflect the current\n\t * lexer state. This method should restore {@code input} and the simulator\n\t * to the original state before returning (i.e. undo the actions made by the\n\t * call to {@link #consume}.</p>\n\t *\n\t * @param input The input stream.\n\t * @param ruleIndex The rule containing the predicate.\n\t * @param predIndex The index of the predicate within the rule.\n\t * @param speculative {@code true} if the current index in {@code input} is\n\t * one character before the predicate's location.\n\t *\n\t * @return {@code true} if the specified predicate evaluates to\n\t * {@code true}.\n\t */\n\tprotected boolean evaluatePredicate(CharStream input, int ruleIndex, int predIndex, boolean speculative) {\n\t\t// assume true if no recognizer was provided\n\t\tif (recog == null) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!speculative) {\n\t\t\treturn recog.sempred(null, ruleIndex, predIndex);\n\t\t}\n\n\t\tint savedCharPositionInLine = charPositionInLine;\n\t\tint savedLine = line;\n\t\tint index = input.index();\n\t\tint marker = input.mark();\n\t\ttry {\n\t\t\tconsume(input);\n\t\t\treturn recog.sempred(null, ruleIndex, predIndex);\n\t\t}\n\t\tfinally {\n\t\t\tcharPositionInLine = savedCharPositionInLine;\n\t\t\tline = savedLine;\n\t\t\tinput.seek(index);\n\t\t\tinput.release(marker);\n\t\t}\n\t}\n\n\tprotected void captureSimState(SimState settings,\n\t\t\t\t\t\t\t\t   CharStream input,\n\t\t\t\t\t\t\t\t   DFAState dfaState)\n\t{\n\t\tsettings.index = input.index();\n\t\tsettings.line = line;\n\t\tsettings.charPos = charPositionInLine;\n\t\tsettings.dfaState = dfaState;\n\t}\n\n\n\tprotected DFAState addDFAEdge(DFAState from,\n\t\t\t\t\t\t\t\t  int t,\n\t\t\t\t\t\t\t\t  ATNConfigSet q)\n\t{\n\t\t/* leading to this call, ATNConfigSet.hasSemanticContext is used as a\n\t\t * marker indicating dynamic predicate evaluation makes this edge\n\t\t * dependent on the specific input sequence, so the static edge in the\n\t\t * DFA should be omitted. The target DFAState is still created since\n\t\t * execATN has the ability to resynchronize with the DFA state cache\n\t\t * following the predicate evaluation step.\n\t\t *\n\t\t * TJP notes: next time through the DFA, we see a pred again and eval.\n\t\t * If that gets us to a previously created (but dangling) DFA\n\t\t * state, we can continue in pure DFA mode from there.\n\t\t */\n\t\tboolean suppressEdge = q.hasSemanticContext;\n\t\tq.hasSemanticContext = false;\n\n\n\t\tDFAState to = addDFAState(q);\n\n\t\tif (suppressEdge) {\n\t\t\treturn to;\n\t\t}\n\n\t\taddDFAEdge(from, t, to);\n\t\treturn to;\n\t}\n\n\tprotected void addDFAEdge(DFAState p, int t, DFAState q) {\n\t\tif (t < MIN_DFA_EDGE || t > MAX_DFA_EDGE) {\n\t\t\t// Only track edges within the DFA bounds\n\t\t\treturn;\n\t\t}\n\n\t\tif ( debug ) {\n\t\t\tSystem.out.println(\"EDGE \"+p+\" -> \"+q+\" upon \"+((char)t));\n\t\t}\n\n\t\tsynchronized (p) {\n\t\t\tif ( p.edges==null ) {\n\t\t\t\t//  make room for tokens 1..n and -1 masquerading as index 0\n\t\t\t\tp.edges = new DFAState[MAX_DFA_EDGE-MIN_DFA_EDGE+1];\n\t\t\t}\n\t\t\tp.edges[t - MIN_DFA_EDGE] = q; // connect\n\t\t}\n\t}\n\n\t/** Add a new DFA state if there isn't one with this set of\n\t\tconfigurations already. This method also detects the first\n\t\tconfiguration containing an ATN rule stop state. Later, when\n\t\ttraversing the DFA, we will know which rule to accept.\n\t */\n\n\tprotected DFAState addDFAState(ATNConfigSet configs) {\n\t\t/* the lexer evaluates predicates on-the-fly; by this point configs\n\t\t * should not contain any configurations with unevaluated predicates.\n\t\t */\n\t\tassert !configs.hasSemanticContext;\n\n\t\tDFAState proposed = new DFAState(configs);\n\t\tATNConfig firstConfigWithRuleStopState = null;\n\t\tfor (ATNConfig c : configs) {\n\t\t\tif ( c.state instanceof RuleStopState )\t{\n\t\t\t\tfirstConfigWithRuleStopState = c;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif ( firstConfigWithRuleStopState!=null ) {\n\t\t\tproposed.isAcceptState = true;\n\t\t\tproposed.lexerActionExecutor = ((LexerATNConfig)firstConfigWithRuleStopState).getLexerActionExecutor();\n\t\t\tproposed.prediction = atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex];\n\t\t}\n\n\t\tDFA dfa = decisionToDFA[mode];\n\t\tsynchronized (dfa.states) {\n\t\t\tDFAState existing = dfa.states.get(proposed);\n\t\t\tif ( existing!=null ) return existing;\n\n\t\t\tDFAState newState = proposed;\n\n\t\t\tnewState.stateNumber = dfa.states.size();\n\t\t\tconfigs.setReadonly(true);\n\t\t\tnewState.configs = configs;\n\t\t\tdfa.states.put(newState, newState);\n\t\t\treturn newState;\n\t\t}\n\t}\n\n\n\tpublic final DFA getDFA(int mode) {\n\t\treturn decisionToDFA[mode];\n\t}\n\n\t/** Get the text matched so far for the current token.\n\t */\n\n\tpublic String getText(CharStream input) {\n\t\t// index is first lookahead char, don't include.\n\t\treturn input.getText(Interval.of(startIndex, input.index()-1));\n\t}\n\n\tpublic int getLine() {\n\t\treturn line;\n\t}\n\n\tpublic void setLine(int line) {\n\t\tthis.line = line;\n\t}\n\n\tpublic int getCharPositionInLine() {\n\t\treturn charPositionInLine;\n\t}\n\n\tpublic void setCharPositionInLine(int charPositionInLine) {\n\t\tthis.charPositionInLine = charPositionInLine;\n\t}\n\n\tpublic void consume(CharStream input) {\n\t\tint curChar = input.LA(1);\n\t\tif ( curChar=='\\n' ) {\n\t\t\tline++;\n\t\t\tcharPositionInLine=0;\n\t\t}\n\t\telse {\n\t\t\tcharPositionInLine++;\n\t\t}\n\t\tinput.consume();\n\t}\n\n\n\tpublic String getTokenName(int t) {\n\t\tif ( t==-1 ) return \"EOF\";\n\t\t//if ( atn.g!=null ) return atn.g.getTokenDisplayName(t);\n\t\treturn \"'\"+(char)t+\"'\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Lexer;\n\n/**\n * Represents a single action which can be executed following the successful\n * match of a lexer rule. Lexer actions are used for both embedded action syntax\n * and ANTLR 4's new lexer command syntax.\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic interface LexerAction {\n\t/**\n\t * Gets the serialization type of the lexer action.\n\t *\n\t * @return The serialization type of the lexer action.\n\t */\n\tLexerActionType getActionType();\n\n\t/**\n\t * Gets whether the lexer action is position-dependent. Position-dependent\n\t * actions may have different semantics depending on the {@link CharStream}\n\t * index at the time the action is executed.\n\t *\n\t * <p>Many lexer commands, including {@code type}, {@code skip}, and\n\t * {@code more}, do not check the input index during their execution.\n\t * Actions like this are position-independent, and may be stored more\n\t * efficiently as part of the {@link LexerATNConfig#lexerActionExecutor}.</p>\n\t *\n\t * @return {@code true} if the lexer action semantics can be affected by the\n\t * position of the input {@link CharStream} at the time it is executed;\n\t * otherwise, {@code false}.\n\t */\n\tboolean isPositionDependent();\n\n\t/**\n\t * Execute the lexer action in the context of the specified {@link Lexer}.\n\t *\n\t * <p>For position-dependent actions, the input stream must already be\n\t * positioned correctly prior to calling this method.</p>\n\t *\n\t * @param lexer The lexer instance.\n\t */\n\tvoid execute(Lexer lexer);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerActionExecutor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.IntStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\nimport java.util.Arrays;\n\n/**\n * Represents an executor for a sequence of lexer actions which traversed during\n * the matching operation of a lexer rule (token).\n *\n * <p>The executor tracks position information for position-dependent lexer actions\n * efficiently, ensuring that actions appearing only at the end of the rule do\n * not cause bloating of the {@link DFA} created for the lexer.</p>\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic class LexerActionExecutor {\n\n\tprivate final LexerAction[] lexerActions;\n\t/**\n\t * Caches the result of {@link #hashCode} since the hash code is an element\n\t * of the performance-critical {@link LexerATNConfig#hashCode} operation.\n\t */\n\tprivate final int hashCode;\n\n\t/**\n\t * Constructs an executor for a sequence of {@link LexerAction} actions.\n\t * @param lexerActions The lexer actions to execute.\n\t */\n\tpublic LexerActionExecutor(LexerAction[] lexerActions) {\n\t\tthis.lexerActions = lexerActions;\n\n\t\tint hash = MurmurHash.initialize();\n\t\tfor (LexerAction lexerAction : lexerActions) {\n\t\t\thash = MurmurHash.update(hash, lexerAction);\n\t\t}\n\n\t\tthis.hashCode = MurmurHash.finish(hash, lexerActions.length);\n\t}\n\n\t/**\n\t * Creates a {@link LexerActionExecutor} which executes the actions for\n\t * the input {@code lexerActionExecutor} followed by a specified\n\t * {@code lexerAction}.\n\t *\n\t * @param lexerActionExecutor The executor for actions already traversed by\n\t * the lexer while matching a token within a particular\n\t * {@link LexerATNConfig}. If this is {@code null}, the method behaves as\n\t * though it were an empty executor.\n\t * @param lexerAction The lexer action to execute after the actions\n\t * specified in {@code lexerActionExecutor}.\n\t *\n\t * @return A {@link LexerActionExecutor} for executing the combine actions\n\t * of {@code lexerActionExecutor} and {@code lexerAction}.\n\t */\n\tpublic static LexerActionExecutor append(LexerActionExecutor lexerActionExecutor, LexerAction lexerAction) {\n\t\tif (lexerActionExecutor == null) {\n\t\t\treturn new LexerActionExecutor(new LexerAction[] { lexerAction });\n\t\t}\n\n\t\tLexerAction[] lexerActions = Arrays.copyOf(lexerActionExecutor.lexerActions, lexerActionExecutor.lexerActions.length + 1);\n\t\tlexerActions[lexerActions.length - 1] = lexerAction;\n\t\treturn new LexerActionExecutor(lexerActions);\n\t}\n\n\t/**\n\t * Creates a {@link LexerActionExecutor} which encodes the current offset\n\t * for position-dependent lexer actions.\n\t *\n\t * <p>Normally, when the executor encounters lexer actions where\n\t * {@link LexerAction#isPositionDependent} returns {@code true}, it calls\n\t * {@link IntStream#seek} on the input {@link CharStream} to set the input\n\t * position to the <em>end</em> of the current token. This behavior provides\n\t * for efficient DFA representation of lexer actions which appear at the end\n\t * of a lexer rule, even when the lexer rule matches a variable number of\n\t * characters.</p>\n\t *\n\t * <p>Prior to traversing a match transition in the ATN, the current offset\n\t * from the token start index is assigned to all position-dependent lexer\n\t * actions which have not already been assigned a fixed offset. By storing\n\t * the offsets relative to the token start index, the DFA representation of\n\t * lexer actions which appear in the middle of tokens remains efficient due\n\t * to sharing among tokens of the same length, regardless of their absolute\n\t * position in the input stream.</p>\n\t *\n\t * <p>If the current executor already has offsets assigned to all\n\t * position-dependent lexer actions, the method returns {@code this}.</p>\n\t *\n\t * @param offset The current offset to assign to all position-dependent\n\t * lexer actions which do not already have offsets assigned.\n\t *\n\t * @return A {@link LexerActionExecutor} which stores input stream offsets\n\t * for all position-dependent lexer actions.\n\t */\n\tpublic LexerActionExecutor fixOffsetBeforeMatch(int offset) {\n\t\tLexerAction[] updatedLexerActions = null;\n\t\tfor (int i = 0; i < lexerActions.length; i++) {\n\t\t\tif (lexerActions[i].isPositionDependent() && !(lexerActions[i] instanceof LexerIndexedCustomAction)) {\n\t\t\t\tif (updatedLexerActions == null) {\n\t\t\t\t\tupdatedLexerActions = lexerActions.clone();\n\t\t\t\t}\n\n\t\t\t\tupdatedLexerActions[i] = new LexerIndexedCustomAction(offset, lexerActions[i]);\n\t\t\t}\n\t\t}\n\n\t\tif (updatedLexerActions == null) {\n\t\t\treturn this;\n\t\t}\n\n\t\treturn new LexerActionExecutor(updatedLexerActions);\n\t}\n\n\t/**\n\t * Gets the lexer actions to be executed by this executor.\n\t * @return The lexer actions to be executed by this executor.\n\t */\n\tpublic LexerAction[] getLexerActions() {\n\t\treturn lexerActions;\n\t}\n\n\t/**\n\t * Execute the actions encapsulated by this executor within the context of a\n\t * particular {@link Lexer}.\n\t *\n\t * <p>This method calls {@link IntStream#seek} to set the position of the\n\t * {@code input} {@link CharStream} prior to calling\n\t * {@link LexerAction#execute} on a position-dependent action. Before the\n\t * method returns, the input position will be restored to the same position\n\t * it was in when the method was invoked.</p>\n\t *\n\t * @param lexer The lexer instance.\n\t * @param input The input stream which is the source for the current token.\n\t * When this method is called, the current {@link IntStream#index} for\n\t * {@code input} should be the start of the following token, i.e. 1\n\t * character past the end of the current token.\n\t * @param startIndex The token start index. This value may be passed to\n\t * {@link IntStream#seek} to set the {@code input} position to the beginning\n\t * of the token.\n\t */\n\tpublic void execute(Lexer lexer, CharStream input, int startIndex) {\n\t\tboolean requiresSeek = false;\n\t\tint stopIndex = input.index();\n\t\ttry {\n\t\t\tfor (LexerAction lexerAction : lexerActions) {\n\t\t\t\tif (lexerAction instanceof LexerIndexedCustomAction) {\n\t\t\t\t\tint offset = ((LexerIndexedCustomAction)lexerAction).getOffset();\n\t\t\t\t\tinput.seek(startIndex + offset);\n\t\t\t\t\tlexerAction = ((LexerIndexedCustomAction)lexerAction).getAction();\n\t\t\t\t\trequiresSeek = (startIndex + offset) != stopIndex;\n\t\t\t\t}\n\t\t\t\telse if (lexerAction.isPositionDependent()) {\n\t\t\t\t\tinput.seek(stopIndex);\n\t\t\t\t\trequiresSeek = false;\n\t\t\t\t}\n\n\t\t\t\tlexerAction.execute(lexer);\n\t\t\t}\n\t\t}\n\t\tfinally {\n\t\t\tif (requiresSeek) {\n\t\t\t\tinput.seek(stopIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn this.hashCode;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof LexerActionExecutor)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tLexerActionExecutor other = (LexerActionExecutor)obj;\n\t\treturn hashCode == other.hashCode\n\t\t\t&& Arrays.equals(lexerActions, other.lexerActions);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerActionType.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n * Represents the serialization type of a {@link LexerAction}.\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic enum LexerActionType {\n\t/**\n\t * The type of a {@link LexerChannelAction} action.\n\t */\n\tCHANNEL,\n\t/**\n\t * The type of a {@link LexerCustomAction} action.\n\t */\n\tCUSTOM,\n\t/**\n\t * The type of a {@link LexerModeAction} action.\n\t */\n\tMODE,\n\t/**\n\t * The type of a {@link LexerMoreAction} action.\n\t */\n\tMORE,\n\t/**\n\t * The type of a {@link LexerPopModeAction} action.\n\t */\n\tPOP_MODE,\n\t/**\n\t * The type of a {@link LexerPushModeAction} action.\n\t */\n\tPUSH_MODE,\n\t/**\n\t * The type of a {@link LexerSkipAction} action.\n\t */\n\tSKIP,\n\t/**\n\t * The type of a {@link LexerTypeAction} action.\n\t */\n\tTYPE,\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerChannelAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Implements the {@code channel} lexer action by calling\n * {@link Lexer#setChannel} with the assigned channel.\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerChannelAction implements LexerAction {\n\tprivate final int channel;\n\n\t/**\n\t * Constructs a new {@code channel} action with the specified channel value.\n\t * @param channel The channel value to pass to {@link Lexer#setChannel}.\n\t */\n\tpublic LexerChannelAction(int channel) {\n\t\tthis.channel = channel;\n\t}\n\n\t/**\n\t * Gets the channel to use for the {@link Token} created by the lexer.\n\t *\n\t * @return The channel to use for the {@link Token} created by the lexer.\n\t */\n\tpublic int getChannel() {\n\t\treturn channel;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@link LexerActionType#CHANNEL}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.CHANNEL;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code false}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This action is implemented by calling {@link Lexer#setChannel} with the\n\t * value provided by {@link #getChannel}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.setChannel(channel);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\thash = MurmurHash.update(hash, channel);\n\t\treturn MurmurHash.finish(hash, 2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof LexerChannelAction)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn channel == ((LexerChannelAction)obj).channel;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"channel(%d)\", channel);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerCustomAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Recognizer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Executes a custom lexer action by calling {@link Recognizer#action} with the\n * rule and action indexes assigned to the custom action. The implementation of\n * a custom action is added to the generated code for the lexer in an override\n * of {@link Recognizer#action} when the grammar is compiled.\n *\n * <p>This class may represent embedded actions created with the <code>{...}</code>\n * syntax in ANTLR 4, as well as actions created for lexer commands where the\n * command argument could not be evaluated when the grammar was compiled.</p>\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerCustomAction implements LexerAction {\n\tprivate final int ruleIndex;\n\tprivate final int actionIndex;\n\n\t/**\n\t * Constructs a custom lexer action with the specified rule and action\n\t * indexes.\n\t *\n\t * @param ruleIndex The rule index to use for calls to\n\t * {@link Recognizer#action}.\n\t * @param actionIndex The action index to use for calls to\n\t * {@link Recognizer#action}.\n\t */\n\tpublic LexerCustomAction(int ruleIndex, int actionIndex) {\n\t\tthis.ruleIndex = ruleIndex;\n\t\tthis.actionIndex = actionIndex;\n\t}\n\n\t/**\n\t * Gets the rule index to use for calls to {@link Recognizer#action}.\n\t *\n\t * @return The rule index for the custom action.\n\t */\n\tpublic int getRuleIndex() {\n\t\treturn ruleIndex;\n\t}\n\n\t/**\n\t * Gets the action index to use for calls to {@link Recognizer#action}.\n\t *\n\t * @return The action index for the custom action.\n\t */\n\tpublic int getActionIndex() {\n\t\treturn actionIndex;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * @return This method returns {@link LexerActionType#CUSTOM}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.CUSTOM;\n\t}\n\n\t/**\n\t * Gets whether the lexer action is position-dependent. Position-dependent\n\t * actions may have different semantics depending on the {@link CharStream}\n\t * index at the time the action is executed.\n\t *\n\t * <p>Custom actions are position-dependent since they may represent a\n\t * user-defined embedded action which makes calls to methods like\n\t * {@link Lexer#getText}.</p>\n\t *\n\t * @return This method returns {@code true}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn true;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>Custom actions are implemented by calling {@link Lexer#action} with the\n\t * appropriate rule and action indexes.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.action(null, ruleIndex, actionIndex);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\thash = MurmurHash.update(hash, ruleIndex);\n\t\thash = MurmurHash.update(hash, actionIndex);\n\t\treturn MurmurHash.finish(hash, 3);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof LexerCustomAction)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tLexerCustomAction other = (LexerCustomAction)obj;\n\t\treturn ruleIndex == other.ruleIndex\n\t\t\t&& actionIndex == other.actionIndex;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerIndexedCustomAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * This implementation of {@link LexerAction} is used for tracking input offsets\n * for position-dependent actions within a {@link LexerActionExecutor}.\n *\n * <p>This action is not serialized as part of the ATN, and is only required for\n * position-dependent lexer actions which appear at a location other than the\n * end of a rule. For more information about DFA optimizations employed for\n * lexer actions, see {@link LexerActionExecutor#append} and\n * {@link LexerActionExecutor#fixOffsetBeforeMatch}.</p>\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerIndexedCustomAction implements LexerAction {\n\tprivate final int offset;\n\tprivate final LexerAction action;\n\n\t/**\n\t * Constructs a new indexed custom action by associating a character offset\n\t * with a {@link LexerAction}.\n\t *\n\t * <p>Note: This class is only required for lexer actions for which\n\t * {@link LexerAction#isPositionDependent} returns {@code true}.</p>\n\t *\n\t * @param offset The offset into the input {@link CharStream}, relative to\n\t * the token start index, at which the specified lexer action should be\n\t * executed.\n\t * @param action The lexer action to execute at a particular offset in the\n\t * input {@link CharStream}.\n\t */\n\tpublic LexerIndexedCustomAction(int offset, LexerAction action) {\n\t\tthis.offset = offset;\n\t\tthis.action = action;\n\t}\n\n\t/**\n\t * Gets the location in the input {@link CharStream} at which the lexer\n\t * action should be executed. The value is interpreted as an offset relative\n\t * to the token start index.\n\t *\n\t * @return The location in the input {@link CharStream} at which the lexer\n\t * action should be executed.\n\t */\n\tpublic int getOffset() {\n\t\treturn offset;\n\t}\n\n\t/**\n\t * Gets the lexer action to execute.\n\t *\n\t * @return A {@link LexerAction} object which executes the lexer action.\n\t */\n\tpublic LexerAction getAction() {\n\t\treturn action;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * @return This method returns the result of calling {@link #getActionType}\n\t * on the {@link LexerAction} returned by {@link #getAction}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn action.getActionType();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code true}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn true;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This method calls {@link #execute} on the result of {@link #getAction}\n\t * using the provided {@code lexer}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\t// assume the input stream position was properly set by the calling code\n\t\taction.execute(lexer);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, offset);\n\t\thash = MurmurHash.update(hash, action);\n\t\treturn MurmurHash.finish(hash, 2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof LexerIndexedCustomAction)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tLexerIndexedCustomAction other = (LexerIndexedCustomAction)obj;\n\t\treturn offset == other.offset\n\t\t\t&& action.equals(other.action);\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerModeAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Implements the {@code mode} lexer action by calling {@link Lexer#mode} with\n * the assigned mode.\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerModeAction implements LexerAction {\n\tprivate final int mode;\n\n\t/**\n\t * Constructs a new {@code mode} action with the specified mode value.\n\t * @param mode The mode value to pass to {@link Lexer#mode}.\n\t */\n\tpublic LexerModeAction(int mode) {\n\t\tthis.mode = mode;\n\t}\n\n\t/**\n\t * Get the lexer mode this action should transition the lexer to.\n\t *\n\t * @return The lexer mode for this {@code mode} command.\n\t */\n\tpublic int getMode() {\n\t\treturn mode;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@link LexerActionType#MODE}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.MODE;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code false}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This action is implemented by calling {@link Lexer#mode} with the\n\t * value provided by {@link #getMode}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.mode(mode);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\thash = MurmurHash.update(hash, mode);\n\t\treturn MurmurHash.finish(hash, 2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof LexerModeAction)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn mode == ((LexerModeAction)obj).mode;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"mode(%d)\", mode);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerMoreAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Implements the {@code more} lexer action by calling {@link Lexer#more}.\n *\n * <p>The {@code more} command does not have any parameters, so this action is\n * implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerMoreAction implements LexerAction {\n\t/**\n\t * Provides a singleton instance of this parameterless lexer action.\n\t */\n\tpublic static final LexerMoreAction INSTANCE = new LexerMoreAction();\n\n\t/**\n\t * Constructs the singleton instance of the lexer {@code more} command.\n\t */\n\tprivate LexerMoreAction() {\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@link LexerActionType#MORE}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.MORE;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code false}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This action is implemented by calling {@link Lexer#more}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.more();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\treturn MurmurHash.finish(hash, 1);\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"EqualsWhichDoesntCheckParameterClass\")\n\tpublic boolean equals(Object obj) {\n\t\treturn obj == this;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"more\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerPopModeAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Implements the {@code popMode} lexer action by calling {@link Lexer#popMode}.\n *\n * <p>The {@code popMode} command does not have any parameters, so this action is\n * implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerPopModeAction implements LexerAction {\n\t/**\n\t * Provides a singleton instance of this parameterless lexer action.\n\t */\n\tpublic static final LexerPopModeAction INSTANCE = new LexerPopModeAction();\n\n\t/**\n\t * Constructs the singleton instance of the lexer {@code popMode} command.\n\t */\n\tprivate LexerPopModeAction() {\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@link LexerActionType#POP_MODE}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.POP_MODE;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code false}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This action is implemented by calling {@link Lexer#popMode}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.popMode();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\treturn MurmurHash.finish(hash, 1);\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"EqualsWhichDoesntCheckParameterClass\")\n\tpublic boolean equals(Object obj) {\n\t\treturn obj == this;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"popMode\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerPushModeAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Implements the {@code pushMode} lexer action by calling\n * {@link Lexer#pushMode} with the assigned mode.\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerPushModeAction implements LexerAction {\n\tprivate final int mode;\n\n\t/**\n\t * Constructs a new {@code pushMode} action with the specified mode value.\n\t * @param mode The mode value to pass to {@link Lexer#pushMode}.\n\t */\n\tpublic LexerPushModeAction(int mode) {\n\t\tthis.mode = mode;\n\t}\n\n\t/**\n\t * Get the lexer mode this action should transition the lexer to.\n\t *\n\t * @return The lexer mode for this {@code pushMode} command.\n\t */\n\tpublic int getMode() {\n\t\treturn mode;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@link LexerActionType#PUSH_MODE}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.PUSH_MODE;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code false}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This action is implemented by calling {@link Lexer#pushMode} with the\n\t * value provided by {@link #getMode}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.pushMode(mode);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\thash = MurmurHash.update(hash, mode);\n\t\treturn MurmurHash.finish(hash, 2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof LexerPushModeAction)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn mode == ((LexerPushModeAction)obj).mode;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"pushMode(%d)\", mode);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerSkipAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Implements the {@code skip} lexer action by calling {@link Lexer#skip}.\n *\n * <p>The {@code skip} command does not have any parameters, so this action is\n * implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic final class LexerSkipAction implements LexerAction {\n\t/**\n\t * Provides a singleton instance of this parameterless lexer action.\n\t */\n\tpublic static final LexerSkipAction INSTANCE = new LexerSkipAction();\n\n\t/**\n\t * Constructs the singleton instance of the lexer {@code skip} command.\n\t */\n\tprivate LexerSkipAction() {\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@link LexerActionType#SKIP}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.SKIP;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code false}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This action is implemented by calling {@link Lexer#skip}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.skip();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\treturn MurmurHash.finish(hash, 1);\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"EqualsWhichDoesntCheckParameterClass\")\n\tpublic boolean equals(Object obj) {\n\t\treturn obj == this;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"skip\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LexerTypeAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\n/**\n * Implements the {@code type} lexer action by calling {@link Lexer#setType}\n * with the assigned type.\n *\n * @author Sam Harwell\n * @since 4.2\n */\npublic class LexerTypeAction implements LexerAction {\n\tprivate final int type;\n\n\t/**\n\t * Constructs a new {@code type} action with the specified token type value.\n\t * @param type The type to assign to the token using {@link Lexer#setType}.\n\t */\n\tpublic LexerTypeAction(int type) {\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * Gets the type to assign to a token created by the lexer.\n\t * @return The type to assign to a token created by the lexer.\n\t */\n\tpublic int getType() {\n\t\treturn type;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@link LexerActionType#TYPE}.\n\t */\n\t@Override\n\tpublic LexerActionType getActionType() {\n\t\treturn LexerActionType.TYPE;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @return This method returns {@code false}.\n\t */\n\t@Override\n\tpublic boolean isPositionDependent() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This action is implemented by calling {@link Lexer#setType} with the\n\t * value provided by {@link #getType}.</p>\n\t */\n\t@Override\n\tpublic void execute(Lexer lexer) {\n\t\tlexer.setType(type);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, getActionType().ordinal());\n\t\thash = MurmurHash.update(hash, type);\n\t\treturn MurmurHash.finish(hash, 2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof LexerTypeAction)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn type == ((LexerTypeAction)obj).type;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"type(%d)\", type);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LookaheadEventInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.TokenStream;\n\n/**\n * This class represents profiling event information for tracking the lookahead\n * depth required in order to make a prediction.\n *\n * @since 4.3\n */\npublic class LookaheadEventInfo extends DecisionEventInfo {\n\t/** The alternative chosen by adaptivePredict(), not necessarily\n\t *  the outermost alt shown for a rule; left-recursive rules have\n\t *  user-level alts that differ from the rewritten rule with a (...) block\n\t *  and a (..)* loop.\n\t */\n\tpublic int predictedAlt;\n\n\t/**\n\t * Constructs a new instance of the {@link LookaheadEventInfo} class with\n\t * the specified detailed lookahead information.\n\t *\n\t * @param decision The decision number\n\t * @param configs The final configuration set containing the necessary\n\t * information to determine the result of a prediction, or {@code null} if\n\t * the final configuration set is not available\n\t * @param input The input token stream\n\t * @param startIndex The start index for the current prediction\n\t * @param stopIndex The index at which the prediction was finally made\n\t * @param fullCtx {@code true} if the current lookahead is part of an LL\n\t * prediction; otherwise, {@code false} if the current lookahead is part of\n\t * an SLL prediction\n\t */\n\tpublic LookaheadEventInfo(int decision,\n\t\t\t\t\t\t\t  ATNConfigSet configs,\n\t\t\t\t\t\t\t  int predictedAlt,\n\t\t\t\t\t\t\t  TokenStream input, int startIndex, int stopIndex,\n\t\t\t\t\t\t\t  boolean fullCtx)\n\t{\n\t\tsuper(decision, configs, input, startIndex, stopIndex, fullCtx);\n\t\tthis.predictedAlt = predictedAlt;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/LoopEndState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** Mark the end of a * or + loop. */\npublic final class LoopEndState extends ATNState {\n\tpublic ATNState loopBackState;\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn LOOP_END;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/NotSetTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\npublic final class NotSetTransition extends SetTransition {\n\tpublic NotSetTransition(ATNState target, IntervalSet set) {\n\t\tsuper(target, set);\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn NOT_SET;\n\t}\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn symbol >= minVocabSymbol\n\t\t\t&& symbol <= maxVocabSymbol\n\t\t\t&& !super.matches(symbol, minVocabSymbol, maxVocabSymbol);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn '~'+super.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/OrderedATNConfigSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.ObjectEqualityComparator;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class OrderedATNConfigSet extends ATNConfigSet {\n\n\tpublic OrderedATNConfigSet() {\n\t\tthis.configLookup = new LexerConfigHashSet();\n\t}\n\n\tpublic static class LexerConfigHashSet extends AbstractConfigHashSet {\n\t\tpublic LexerConfigHashSet() {\n\t\t\tsuper(ObjectEqualityComparator.INSTANCE);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ParseInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.dfa.DFA;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * This class provides access to specific and aggregate statistics gathered\n * during profiling of a parser.\n *\n * @since 4.3\n */\npublic class ParseInfo {\n\tprotected final ProfilingATNSimulator atnSimulator;\n\n\tpublic ParseInfo(ProfilingATNSimulator atnSimulator) {\n\t\tthis.atnSimulator = atnSimulator;\n\t}\n\n\t/**\n\t * Gets an array of {@link DecisionInfo} instances containing the profiling\n\t * information gathered for each decision in the ATN.\n\t *\n\t * @return An array of {@link DecisionInfo} instances, indexed by decision\n\t * number.\n\t */\n\tpublic DecisionInfo[] getDecisionInfo() {\n\t\treturn atnSimulator.getDecisionInfo();\n\t}\n\n\t/**\n\t * Gets the decision numbers for decisions that required one or more\n\t * full-context predictions during parsing. These are decisions for which\n\t * {@link DecisionInfo#LL_Fallback} is non-zero.\n\t *\n\t * @return A list of decision numbers which required one or more\n\t * full-context predictions during parsing.\n\t */\n\tpublic List<Integer> getLLDecisions() {\n\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\tList<Integer> LL = new ArrayList<Integer>();\n\t\tfor (int i=0; i<decisions.length; i++) {\n\t\t\tlong fallBack = decisions[i].LL_Fallback;\n\t\t\tif ( fallBack>0 ) LL.add(i);\n\t\t}\n\t\treturn LL;\n\t}\n\n\t/**\n\t * Gets the total time spent during prediction across all decisions made\n\t * during parsing. This value is the sum of\n\t * {@link DecisionInfo#timeInPrediction} for all decisions.\n\t */\n\tpublic long getTotalTimeInPrediction() {\n\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\tlong t = 0;\n\t\tfor (int i=0; i<decisions.length; i++) {\n\t\t\tt += decisions[i].timeInPrediction;\n\t\t}\n\t\treturn t;\n\t}\n\n\t/**\n\t * Gets the total number of SLL lookahead operations across all decisions\n\t * made during parsing. This value is the sum of\n\t * {@link DecisionInfo#SLL_TotalLook} for all decisions.\n\t */\n\tpublic long getTotalSLLLookaheadOps() {\n\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\tlong k = 0;\n\t\tfor (int i = 0; i < decisions.length; i++) {\n\t\t\tk += decisions[i].SLL_TotalLook;\n\t\t}\n\t\treturn k;\n\t}\n\n\t/**\n\t * Gets the total number of LL lookahead operations across all decisions\n\t * made during parsing. This value is the sum of\n\t * {@link DecisionInfo#LL_TotalLook} for all decisions.\n\t */\n\tpublic long getTotalLLLookaheadOps() {\n\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\tlong k = 0;\n\t\tfor (int i = 0; i < decisions.length; i++) {\n\t\t\tk += decisions[i].LL_TotalLook;\n\t\t}\n\t\treturn k;\n\t}\n\n\t/**\n\t * Gets the total number of ATN lookahead operations for SLL prediction\n\t * across all decisions made during parsing.\n\t */\n\tpublic long getTotalSLLATNLookaheadOps() {\n\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\tlong k = 0;\n\t\tfor (int i = 0; i < decisions.length; i++) {\n\t\t\tk += decisions[i].SLL_ATNTransitions;\n\t\t}\n\t\treturn k;\n\t}\n\n\t/**\n\t * Gets the total number of ATN lookahead operations for LL prediction\n\t * across all decisions made during parsing.\n\t */\n\tpublic long getTotalLLATNLookaheadOps() {\n\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\tlong k = 0;\n\t\tfor (int i = 0; i < decisions.length; i++) {\n\t\t\tk += decisions[i].LL_ATNTransitions;\n\t\t}\n\t\treturn k;\n\t}\n\n\t/**\n\t * Gets the total number of ATN lookahead operations for SLL and LL\n\t * prediction across all decisions made during parsing.\n\t *\n\t * <p>\n\t * This value is the sum of {@link #getTotalSLLATNLookaheadOps} and\n\t * {@link #getTotalLLATNLookaheadOps}.</p>\n\t */\n\tpublic long getTotalATNLookaheadOps() {\n\t\tDecisionInfo[] decisions = atnSimulator.getDecisionInfo();\n\t\tlong k = 0;\n\t\tfor (int i = 0; i < decisions.length; i++) {\n\t\t\tk += decisions[i].SLL_ATNTransitions;\n\t\t\tk += decisions[i].LL_ATNTransitions;\n\t\t}\n\t\treturn k;\n\t}\n\n\t/**\n\t * Gets the total number of DFA states stored in the DFA cache for all\n\t * decisions in the ATN.\n\t */\n\tpublic int getDFASize() {\n\t\tint n = 0;\n\t\tDFA[] decisionToDFA = atnSimulator.decisionToDFA;\n\t\tfor (int i = 0; i < decisionToDFA.length; i++) {\n\t\t\tn += getDFASize(i);\n\t\t}\n\t\treturn n;\n\t}\n\n\t/**\n\t * Gets the total number of DFA states stored in the DFA cache for a\n\t * particular decision.\n\t */\n\tpublic int getDFASize(int decision) {\n\t\tDFA decisionToDFA = atnSimulator.decisionToDFA[decision];\n\t\treturn decisionToDFA.states.size();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ParserATNSimulator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.dfa.DFAState;\nimport org.antlr.v4.runtime.misc.DoubleKeyMap;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.security.AccessController;\nimport java.security.PrivilegedAction;\nimport java.util.*;\n\nimport static org.antlr.v4.runtime.atn.ATNState.BLOCK_END;\n\n/**\n * The embodiment of the adaptive LL(*), ALL(*), parsing strategy.\n *\n * <p>\n * The basic complexity of the adaptive strategy makes it harder to understand.\n * We begin with ATN simulation to build paths in a DFA. Subsequent prediction\n * requests go through the DFA first. If they reach a state without an edge for\n * the current symbol, the algorithm fails over to the ATN simulation to\n * complete the DFA path for the current input (until it finds a conflict state\n * or uniquely predicting state).</p>\n *\n * <p>\n * All of that is done without using the outer context because we want to create\n * a DFA that is not dependent upon the rule invocation stack when we do a\n * prediction. One DFA works in all contexts. We avoid using context not\n * necessarily because it's slower, although it can be, but because of the DFA\n * caching problem. The closure routine only considers the rule invocation stack\n * created during prediction beginning in the decision rule. For example, if\n * prediction occurs without invoking another rule's ATN, there are no context\n * stacks in the configurations. When lack of context leads to a conflict, we\n * don't know if it's an ambiguity or a weakness in the strong LL(*) parsing\n * strategy (versus full LL(*)).</p>\n *\n * <p>\n * When SLL yields a configuration set with conflict, we rewind the input and\n * retry the ATN simulation, this time using full outer context without adding\n * to the DFA. Configuration context stacks will be the full invocation stacks\n * from the start rule. If we get a conflict using full context, then we can\n * definitively say we have a true ambiguity for that input sequence. If we\n * don't get a conflict, it implies that the decision is sensitive to the outer\n * context. (It is not context-sensitive in the sense of context-sensitive\n * grammars.)</p>\n *\n * <p>\n * The next time we reach this DFA state with an SLL conflict, through DFA\n * simulation, we will again retry the ATN simulation using full context mode.\n * This is slow because we can't save the results and have to \"interpret\" the\n * ATN each time we get that input.</p>\n *\n * <p>\n * <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>\n *\n * <p>\n * We could cache results from full context to predicted alternative easily and\n * that saves a lot of time but doesn't work in presence of predicates. The set\n * of visible predicates from the ATN start state changes depending on the\n * context, because closure can fall off the end of a rule. I tried to cache\n * tuples (stack context, semantic context, predicted alt) but it was slower\n * than interpreting and much more complicated. Also required a huge amount of\n * memory. The goal is not to create the world's fastest parser anyway. I'd like\n * to keep this algorithm simple. By launching multiple threads, we can improve\n * the speed of parsing across a large number of files.</p>\n *\n * <p>\n * There is no strict ordering between the amount of input used by SLL vs LL,\n * which makes it really hard to build a cache for full context. Let's say that\n * we have input A B C that leads to an SLL conflict with full context X. That\n * implies that using X we might only use A B but we could also use A B C D to\n * resolve conflict. Input A B C D could predict alternative 1 in one position\n * in the input and A B C E could predict alternative 2 in another position in\n * input. The conflicting SLL configurations could still be non-unique in the\n * full context prediction, which would lead us to requiring more input than the\n * original A B C.\tTo make a\tprediction cache work, we have to track\tthe exact\n * input\tused during the previous prediction. That amounts to a cache that maps\n * X to a specific DFA for that context.</p>\n *\n * <p>\n * Something should be done for left-recursive expression predictions. They are\n * likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry\n * with full LL thing Sam does.</p>\n *\n * <p>\n * <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>\n *\n * <p>\n * We avoid doing full context retry when the outer context is empty, we did not\n * dip into the outer context by falling off the end of the decision state rule,\n * or when we force SLL mode.</p>\n *\n * <p>\n * As an example of the not dip into outer context case, consider as super\n * constructor calls versus function calls. One grammar might look like\n * this:</p>\n *\n * <pre>\n * ctorBody\n *   : '{' superCall? stat* '}'\n *   ;\n * </pre>\n *\n * <p>\n * Or, you might see something like</p>\n *\n * <pre>\n * stat\n *   : superCall ';'\n *   | expression ';'\n *   | ...\n *   ;\n * </pre>\n *\n * <p>\n * In both cases I believe that no closure operations will dip into the outer\n * context. In the first case ctorBody in the worst case will stop at the '}'.\n * In the 2nd case it should stop at the ';'. Both cases should stay within the\n * entry rule and not dip into the outer context.</p>\n *\n * <p>\n * <strong>PREDICATES</strong></p>\n *\n * <p>\n * Predicates are always evaluated if present in either SLL or LL both. SLL and\n * LL simulation deals with predicates differently. SLL collects predicates as\n * it performs closure operations like ANTLR v3 did. It delays predicate\n * evaluation until it reaches and accept state. This allows us to cache the SLL\n * ATN simulation whereas, if we had evaluated predicates on-the-fly during\n * closure, the DFA state configuration sets would be different and we couldn't\n * build up a suitable DFA.</p>\n *\n * <p>\n * When building a DFA accept state during ATN simulation, we evaluate any\n * predicates and return the sole semantically valid alternative. If there is\n * more than 1 alternative, we report an ambiguity. If there are 0 alternatives,\n * we throw an exception. Alternatives without predicates act like they have\n * true predicates. The simple way to think about it is to strip away all\n * alternatives with false predicates and choose the minimum alternative that\n * remains.</p>\n *\n * <p>\n * When we start in the DFA and reach an accept state that's predicated, we test\n * those and return the minimum semantically viable alternative. If no\n * alternatives are viable, we throw an exception.</p>\n *\n * <p>\n * During full LL ATN simulation, closure always evaluates predicates and\n * on-the-fly. This is crucial to reducing the configuration set size during\n * closure. It hits a landmine when parsing with the Java grammar, for example,\n * without this on-the-fly evaluation.</p>\n *\n * <p>\n * <strong>SHARING DFA</strong></p>\n *\n * <p>\n * All instances of the same parser share the same decision DFAs through a\n * static field. Each instance gets its own ATN simulator but they share the\n * same {@link #decisionToDFA} field. They also share a\n * {@link PredictionContextCache} object that makes sure that all\n * {@link PredictionContext} objects are shared among the DFA states. This makes\n * a big size difference.</p>\n *\n * <p>\n * <strong>THREAD SAFETY</strong></p>\n *\n * <p>\n * The {@link ParserATNSimulator} locks on the {@link #decisionToDFA} field when\n * it adds a new DFA object to that array. {@link #addDFAEdge}\n * locks on the DFA for the current decision when setting the\n * {@link DFAState#edges} field. {@link #addDFAState} locks on\n * the DFA for the current decision when looking up a DFA state to see if it\n * already exists. We must make sure that all requests to add DFA states that\n * are equivalent result in the same shared DFA object. This is because lots of\n * threads will be trying to update the DFA at once. The\n * {@link #addDFAState} method also locks inside the DFA lock\n * but this time on the shared context cache when it rebuilds the\n * configurations' {@link PredictionContext} objects using cached\n * subgraphs/nodes. No other locking occurs, even during DFA simulation. This is\n * safe as long as we can guarantee that all threads referencing\n * {@code s.edge[t]} get the same physical target {@link DFAState}, or\n * {@code null}. Once into the DFA, the DFA simulation does not reference the\n * {@link DFA#states} map. It follows the {@link DFAState#edges} field to new\n * targets. The DFA simulator will either find {@link DFAState#edges} to be\n * {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or\n * {@code dfa.edges[t]} to be non-null. The\n * {@link #addDFAEdge} method could be racing to set the field\n * but in either case the DFA simulator works; if {@code null}, and requests ATN\n * simulation. It could also race trying to get {@code dfa.edges[t]}, but either\n * way it will work because it's not doing a test and set operation.</p>\n *\n * <p>\n * <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage\n * Parsing)</strong></p>\n *\n * <p>\n * Sam pointed out that if SLL does not give a syntax error, then there is no\n * point in doing full LL, which is slower. We only have to try LL if we get a\n * syntax error. For maximum speed, Sam starts the parser set to pure SLL\n * mode with the {@link BailErrorStrategy}:</p>\n *\n * <pre>\n * parser.{@link Parser#getInterpreter() getInterpreter()}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};\n * parser.{@link Parser#setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());\n * </pre>\n *\n * <p>\n * If it does not get a syntax error, then we're done. If it does get a syntax\n * error, we need to retry with the combined SLL/LL strategy.</p>\n *\n * <p>\n * The reason this works is as follows. If there are no SLL conflicts, then the\n * grammar is SLL (at least for that input set). If there is an SLL conflict,\n * the full LL analysis must yield a set of viable alternatives which is a\n * subset of the alternatives reported by SLL. If the LL set is a singleton,\n * then the grammar is LL but not SLL. If the LL set is the same size as the SLL\n * set, the decision is SLL. If the LL set has size &gt; 1, then that decision\n * is truly ambiguous on the current input. If the LL set is smaller, then the\n * SLL conflict resolution might choose an alternative that the full LL would\n * rule out as a possibility based upon better context information. If that's\n * the case, then the SLL parse will definitely get an error because the full LL\n * analysis says it's not viable. If SLL conflict resolution chooses an\n * alternative within the LL set, them both SLL and LL would choose the same\n * alternative because they both choose the minimum of multiple conflicting\n * alternatives.</p>\n *\n * <p>\n * Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and\n * a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL\n * parsing will get an error because SLL will pursue alternative 1. If\n * <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will\n * choose the same alternative because alternative one is the minimum of either\n * set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax\n * error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>\n *\n * <p>\n * Of course, if the input is invalid, then we will get an error for sure in\n * both SLL and LL parsing. Erroneous input will therefore require 2 passes over\n * the input.</p>\n */\npublic class ParserATNSimulator extends ATNSimulator {\n\tpublic static boolean debug = false;\n\tpublic static boolean trace_atn_sim = false;\n\tpublic static boolean dfa_debug = false;\n\tpublic static boolean retry_debug = false;\n\n\t/** Just in case this optimization is bad, add an ENV variable to turn it off */\n\tpublic static final boolean TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT = Boolean.parseBoolean(getSafeEnv(\"TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT\"));\n\n\tprotected final Parser parser;\n\n\tpublic final DFA[] decisionToDFA;\n\n\t/** SLL, LL, or LL + exact ambig detection? */\n\n\tprivate PredictionMode mode = PredictionMode.LL;\n\n\t/** Each prediction operation uses a cache for merge of prediction contexts.\n\t *  Don't keep around as it wastes huge amounts of memory. DoubleKeyMap\n\t *  isn't synchronized but we're ok since two threads shouldn't reuse same\n\t *  parser/atnsim object because it can only handle one input at a time.\n\t *  This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid\n\t *  the merge if we ever see a and b again.  Note that (b,a)&rarr;c should\n\t *  also be examined during cache lookup.\n\t */\n\tprotected DoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache;\n\n\t// LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n\tprotected TokenStream _input;\n\tprotected int _startIndex;\n\tprotected ParserRuleContext _outerContext;\n\tprotected DFA _dfa;\n\n\t/** Testing only! */\n\tpublic ParserATNSimulator(ATN atn, DFA[] decisionToDFA,\n\t\t\t\t\t\t\t  PredictionContextCache sharedContextCache)\n\t{\n\t\tthis(null, atn, decisionToDFA, sharedContextCache);\n\t}\n\n\tpublic ParserATNSimulator(Parser parser, ATN atn,\n\t\t\t\t\t\t\t  DFA[] decisionToDFA,\n\t\t\t\t\t\t\t  PredictionContextCache sharedContextCache)\n\t{\n\t\tsuper(atn, sharedContextCache);\n\t\tthis.parser = parser;\n\t\tthis.decisionToDFA = decisionToDFA;\n\t\t//\t\tDOTGenerator dot = new DOTGenerator(null);\n\t\t//\t\tSystem.out.println(dot.getDOT(atn.rules.get(0), parser.getRuleNames()));\n\t\t//\t\tSystem.out.println(dot.getDOT(atn.rules.get(1), parser.getRuleNames()));\n\t}\n\n\t@Override\n\tpublic void reset() {\n\t}\n\n\t@Override\n\tpublic void clearDFA() {\n\t\tfor (int d = 0; d < decisionToDFA.length; d++) {\n\t\t\tdecisionToDFA[d] = new DFA(atn.getDecisionState(d), d);\n\t\t}\n\t}\n\n\tpublic int adaptivePredict(TokenStream input, int decision,\n\t\t\t\t\t\t\t   ParserRuleContext outerContext)\n\t{\n\t\tif ( debug || trace_atn_sim )  {\n\t\t\tSystem.out.println(\"adaptivePredict decision \"+decision+\n\t\t\t\t\t\t\t\t   \" exec LA(1)==\"+ getLookaheadName(input)+\n\t\t\t\t\t\t\t\t   \" line \"+input.LT(1).getLine()+\":\"+input.LT(1).getCharPositionInLine());\n\t\t}\n\n\t\t_input = input;\n\t\t_startIndex = input.index();\n\t\t_outerContext = outerContext;\n\t\tDFA dfa = decisionToDFA[decision];\n\t\t_dfa = dfa;\n\n\t\tint m = input.mark();\n\t\tint index = _startIndex;\n\n\t\t// Now we are certain to have a specific decision's DFA\n\t\t// But, do we still need an initial state?\n\t\ttry {\n\t\t\tDFAState s0;\n\t\t\tif (dfa.isPrecedenceDfa()) {\n\t\t\t\t// the start state for a precedence DFA depends on the current\n\t\t\t\t// parser precedence, and is provided by a DFA method.\n\t\t\t\ts0 = dfa.getPrecedenceStartState(parser.getPrecedence());\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// the start state for a \"regular\" DFA is just s0\n\t\t\t\ts0 = dfa.s0;\n\t\t\t}\n\n\t\t\tif (s0 == null) {\n\t\t\t\tif ( outerContext ==null ) outerContext = ParserRuleContext.EMPTY;\n\t\t\t\tboolean fullCtx = false;\n\t\t\t\tATNConfigSet s0_closure =\n\t\t\t\t\tcomputeStartState(dfa.atnStartState,\n\t\t\t\t\t\t\t\t\t  ParserRuleContext.EMPTY,\n\t\t\t\t\t\t\t\t\t  fullCtx);\n\n\t\t\t\tif (dfa.isPrecedenceDfa()) {\n\t\t\t\t\t/* If this is a precedence DFA, we use applyPrecedenceFilter\n\t\t\t\t\t * to convert the computed start state to a precedence start\n\t\t\t\t\t * state. We then use DFA.setPrecedenceStartState to set the\n\t\t\t\t\t * appropriate start state for the precedence level rather\n\t\t\t\t\t * than simply setting DFA.s0.\n\t\t\t\t\t */\n\t\t\t\t\tdfa.s0.configs = s0_closure; // not used for prediction but useful to know start configs anyway\n\t\t\t\t\ts0_closure = applyPrecedenceFilter(s0_closure);\n\t\t\t\t\ts0 = addDFAState(dfa, new DFAState(s0_closure));\n\t\t\t\t\tdfa.setPrecedenceStartState(parser.getPrecedence(), s0);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ts0 = addDFAState(dfa, new DFAState(s0_closure));\n\t\t\t\t\tdfa.s0 = s0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint alt = execATN(dfa, s0, input, index, outerContext);\n\t\t\tif ( debug ) System.out.println(\"DFA after predictATN: \"+ dfa.toString(parser.getVocabulary()));\n\t\t\treturn alt;\n\t\t}\n\t\tfinally {\n\t\t\tmergeCache = null; // wack cache after each prediction\n\t\t\t_dfa = null;\n\t\t\tinput.seek(index);\n\t\t\tinput.release(m);\n\t\t}\n\t}\n\n\t/** Performs ATN simulation to compute a predicted alternative based\n\t *  upon the remaining input, but also updates the DFA cache to avoid\n\t *  having to traverse the ATN again for the same input sequence.\n\n\t There are some key conditions we're looking for after computing a new\n\t set of ATN configs (proposed DFA state):\n\t       * if the set is empty, there is no viable alternative for current symbol\n\t       * does the state uniquely predict an alternative?\n\t       * does the state have a conflict that would prevent us from\n\t         putting it on the work list?\n\n\t We also have some key operations to do:\n\t       * add an edge from previous DFA state to potentially new DFA state, D,\n\t         upon current symbol but only if adding to work list, which means in all\n\t         cases except no viable alternative (and possibly non-greedy decisions?)\n\t       * collecting predicates and adding semantic context to DFA accept states\n\t       * adding rule context to context-sensitive DFA accept states\n\t       * consuming an input symbol\n\t       * reporting a conflict\n\t       * reporting an ambiguity\n\t       * reporting a context sensitivity\n\t       * reporting insufficient predicates\n\n\t cover these cases:\n\t    dead end\n\t    single alt\n\t    single alt + preds\n\t    conflict\n\t    conflict + preds\n\t */\n\tprotected int execATN(DFA dfa, DFAState s0,\n\t\t\t\t\t   TokenStream input, int startIndex,\n\t\t\t\t\t   ParserRuleContext outerContext)\n\t{\n\t\tif ( debug || trace_atn_sim ) {\n\t\t\tSystem.out.println(\"execATN decision \"+dfa.decision+\n\t\t\t\t\t\t\t   \", DFA state \"+s0+\n\t\t\t\t\t\t\t   \", LA(1)==\"+ getLookaheadName(input)+\n\t\t\t\t\t\t\t   \" line \"+input.LT(1).getLine()+\":\"+input.LT(1).getCharPositionInLine());\n\n\t\t}\n\n\t\tDFAState previousD = s0;\n\n\t\tint t = input.LA(1);\n\n\t\twhile (true) { // while more work\n\t\t\tDFAState D = getExistingTargetState(previousD, t);\n\t\t\tif (D == null) {\n\t\t\t\tD = computeTargetState(dfa, previousD, t);\n\t\t\t}\n\n\t\t\tif (D == ERROR) {\n\t\t\t\t// if any configs in previous dipped into outer context, that\n\t\t\t\t// means that input up to t actually finished entry rule\n\t\t\t\t// at least for SLL decision. Full LL doesn't dip into outer\n\t\t\t\t// so don't need special case.\n\t\t\t\t// We will get an error no matter what so delay until after\n\t\t\t\t// decision; better error message. Also, no reachable target\n\t\t\t\t// ATN states in SLL implies LL will also get nowhere.\n\t\t\t\t// If conflict in states that dip out, choose min since we\n\t\t\t\t// will get error no matter what.\n\t\t\t\tNoViableAltException e = noViableAlt(input, outerContext, previousD.configs, startIndex);\n\t\t\t\tinput.seek(startIndex);\n\t\t\t\tint alt = getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);\n\t\t\t\tif ( alt!=ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\t\treturn alt;\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\n\t\t\tif ( D.requiresFullContext && mode != PredictionMode.SLL ) {\n\t\t\t\t// IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n\t\t\t\tBitSet conflictingAlts = D.configs.conflictingAlts;\n\t\t\t\tif ( D.predicates!=null ) {\n\t\t\t\t\tif ( debug ) System.out.println(\"DFA state has preds in DFA sim LL failover\");\n\t\t\t\t\tint conflictIndex = input.index();\n\t\t\t\t\tif (conflictIndex != startIndex) {\n\t\t\t\t\t\tinput.seek(startIndex);\n\t\t\t\t\t}\n\n\t\t\t\t\tconflictingAlts = evalSemanticContext(D.predicates, outerContext, true);\n\t\t\t\t\tif ( conflictingAlts.cardinality()==1 ) {\n\t\t\t\t\t\tif ( debug ) System.out.println(\"Full LL avoided\");\n\t\t\t\t\t\treturn conflictingAlts.nextSetBit(0);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (conflictIndex != startIndex) {\n\t\t\t\t\t\t// restore the index so reporting the fallback to full\n\t\t\t\t\t\t// context occurs with the index at the correct spot\n\t\t\t\t\t\tinput.seek(conflictIndex);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( dfa_debug ) System.out.println(\"ctx sensitive state \"+outerContext+\" in \"+D);\n\t\t\t\tboolean fullCtx = true;\n\t\t\t\tATNConfigSet s0_closure =\n\t\t\t\t\tcomputeStartState(dfa.atnStartState, outerContext,\n\t\t\t\t\t\t\t\t\t  fullCtx);\n\t\t\t\treportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index());\n\t\t\t\tint alt = execATNWithFullContext(dfa, D, s0_closure,\n\t\t\t\t\t\t\t\t\t\t\t\t input, startIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t outerContext);\n\t\t\t\treturn alt;\n\t\t\t}\n\n\t\t\tif ( D.isAcceptState ) {\n\t\t\t\tif (D.predicates == null) {\n\t\t\t\t\treturn D.prediction;\n\t\t\t\t}\n\n\t\t\t\tint stopIndex = input.index();\n\t\t\t\tinput.seek(startIndex);\n\t\t\t\tBitSet alts = evalSemanticContext(D.predicates, outerContext, true);\n\t\t\t\tswitch (alts.cardinality()) {\n\t\t\t\tcase 0:\n\t\t\t\t\tthrow noViableAlt(input, outerContext, D.configs, startIndex);\n\n\t\t\t\tcase 1:\n\t\t\t\t\treturn alts.nextSetBit(0);\n\n\t\t\t\tdefault:\n\t\t\t\t\t// report ambiguity after predicate evaluation to make sure the correct\n\t\t\t\t\t// set of ambig alts is reported.\n\t\t\t\t\treportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);\n\t\t\t\t\treturn alts.nextSetBit(0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpreviousD = D;\n\n\t\t\tif (t != IntStream.EOF) {\n\t\t\t\tinput.consume();\n\t\t\t\tt = input.LA(1);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get an existing target state for an edge in the DFA. If the target state\n\t * for the edge has not yet been computed or is otherwise not available,\n\t * this method returns {@code null}.\n\t *\n\t * @param previousD The current DFA state\n\t * @param t The next input symbol\n\t * @return The existing target DFA state for the given input symbol\n\t * {@code t}, or {@code null} if the target state for this edge is not\n\t * already cached\n\t */\n\tprotected DFAState getExistingTargetState(DFAState previousD, int t) {\n\t\tDFAState[] edges = previousD.edges;\n\t\tif (edges == null || t + 1 < 0 || t + 1 >= edges.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn edges[t + 1];\n\t}\n\n\t/**\n\t * Compute a target state for an edge in the DFA, and attempt to add the\n\t * computed state and corresponding edge to the DFA.\n\t *\n\t * @param dfa The DFA\n\t * @param previousD The current DFA state\n\t * @param t The next input symbol\n\t *\n\t * @return The computed target DFA state for the given input symbol\n\t * {@code t}. If {@code t} does not lead to a valid DFA state, this method\n\t * returns {@link #ERROR}.\n\t */\n\tprotected DFAState computeTargetState(DFA dfa, DFAState previousD, int t) {\n\t\tATNConfigSet reach = computeReachSet(previousD.configs, t, false);\n\t\tif ( reach==null ) {\n\t\t\taddDFAEdge(dfa, previousD, t, ERROR);\n\t\t\treturn ERROR;\n\t\t}\n\n\t\t// create new target state; we'll add to DFA after it's complete\n\t\tDFAState D = new DFAState(reach);\n\n\t\tint predictedAlt = getUniqueAlt(reach);\n\n\t\tif ( debug ) {\n\t\t\tCollection<BitSet> altSubSets = PredictionMode.getConflictingAltSubsets(reach);\n\t\t\tSystem.out.println(\"SLL altSubSets=\"+altSubSets+\n\t\t\t\t\t\t\t   \", configs=\"+reach+\n\t\t\t\t\t\t\t   \", predict=\"+predictedAlt+\", allSubsetsConflict=\"+\n\t\t\t\t\t\t\t\t   PredictionMode.allSubsetsConflict(altSubSets)+\", conflictingAlts=\"+\n\t\t\t\t\t\t\t   getConflictingAlts(reach));\n\t\t}\n\n\t\tif ( predictedAlt!=ATN.INVALID_ALT_NUMBER ) {\n\t\t\t// NO CONFLICT, UNIQUELY PREDICTED ALT\n\t\t\tD.isAcceptState = true;\n\t\t\tD.configs.uniqueAlt = predictedAlt;\n\t\t\tD.prediction = predictedAlt;\n\t\t}\n\t\telse if ( PredictionMode.hasSLLConflictTerminatingPrediction(mode, reach) ) {\n\t\t\t// MORE THAN ONE VIABLE ALTERNATIVE\n\t\t\tD.configs.conflictingAlts = getConflictingAlts(reach);\n\t\t\tD.requiresFullContext = true;\n\t\t\t// in SLL-only mode, we will stop at this state and return the minimum alt\n\t\t\tD.isAcceptState = true;\n\t\t\tD.prediction = D.configs.conflictingAlts.nextSetBit(0);\n\t\t}\n\n\t\tif ( D.isAcceptState && D.configs.hasSemanticContext ) {\n\t\t\tpredicateDFAState(D, atn.getDecisionState(dfa.decision));\n\t\t\tif (D.predicates != null) {\n\t\t\t\tD.prediction = ATN.INVALID_ALT_NUMBER;\n\t\t\t}\n\t\t}\n\n\t\t// all adds to dfa are done after we've created full D state\n\t\tD = addDFAEdge(dfa, previousD, t, D);\n\t\treturn D;\n\t}\n\n\tprotected void predicateDFAState(DFAState dfaState, DecisionState decisionState) {\n\t\t// We need to test all predicates, even in DFA states that\n\t\t// uniquely predict alternative.\n\t\tint nalts = decisionState.getNumberOfTransitions();\n\t\t// Update DFA so reach becomes accept state with (predicate,alt)\n\t\t// pairs if preds found for conflicting alts\n\t\tBitSet altsToCollectPredsFrom = getConflictingAltsOrUniqueAlt(dfaState.configs);\n\t\tSemanticContext[] altToPred = getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts);\n\t\tif ( altToPred!=null ) {\n\t\t\tdfaState.predicates = getPredicatePredictions(altsToCollectPredsFrom, altToPred);\n\t\t\tdfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds\n\t\t}\n\t\telse {\n\t\t\t// There are preds in configs but they might go away\n\t\t\t// when OR'd together like {p}? || NONE == NONE. If neither\n\t\t\t// alt has preds, resolve to min alt\n\t\t\tdfaState.prediction = altsToCollectPredsFrom.nextSetBit(0);\n\t\t}\n\t}\n\n\t// comes back with reach.uniqueAlt set to a valid alt\n\tprotected int execATNWithFullContext(DFA dfa,\n\t\t\t\t\t\t\t\t\t\t DFAState D, // how far we got in SLL DFA before failing over\n\t\t\t\t\t\t\t\t\t\t ATNConfigSet s0,\n\t\t\t\t\t\t\t\t\t\t TokenStream input, int startIndex,\n\t\t\t\t\t\t\t\t\t\t ParserRuleContext outerContext)\n\t{\n\t\tif ( debug || trace_atn_sim ) {\n\t\t\tSystem.out.println(\"execATNWithFullContext \"+s0);\n\t\t}\n\t\tboolean fullCtx = true;\n\t\tboolean foundExactAmbig = false;\n\t\tATNConfigSet reach = null;\n\t\tATNConfigSet previous = s0;\n\t\tinput.seek(startIndex);\n\t\tint t = input.LA(1);\n\t\tint predictedAlt;\n\t\twhile (true) { // while more work\n//\t\t\tSystem.out.println(\"LL REACH \"+getLookaheadName(input)+\n//\t\t\t\t\t\t\t   \" from configs.size=\"+previous.size()+\n//\t\t\t\t\t\t\t   \" line \"+input.LT(1).getLine()+\":\"+input.LT(1).getCharPositionInLine());\n\t\t\treach = computeReachSet(previous, t, fullCtx);\n\t\t\tif ( reach==null ) {\n\t\t\t\t// if any configs in previous dipped into outer context, that\n\t\t\t\t// means that input up to t actually finished entry rule\n\t\t\t\t// at least for LL decision. Full LL doesn't dip into outer\n\t\t\t\t// so don't need special case.\n\t\t\t\t// We will get an error no matter what so delay until after\n\t\t\t\t// decision; better error message. Also, no reachable target\n\t\t\t\t// ATN states in SLL implies LL will also get nowhere.\n\t\t\t\t// If conflict in states that dip out, choose min since we\n\t\t\t\t// will get error no matter what.\n\t\t\t\tNoViableAltException e = noViableAlt(input, outerContext, previous, startIndex);\n\t\t\t\tinput.seek(startIndex);\n\t\t\t\tint alt = getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);\n\t\t\t\tif ( alt!=ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\t\treturn alt;\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\n\t\t\tCollection<BitSet> altSubSets = PredictionMode.getConflictingAltSubsets(reach);\n\t\t\tif ( debug ) {\n\t\t\t\tSystem.out.println(\"LL altSubSets=\"+altSubSets+\n\t\t\t\t\t\t\t\t   \", predict=\"+PredictionMode.getUniqueAlt(altSubSets)+\n\t\t\t\t\t\t\t\t   \", resolvesToJustOneViableAlt=\"+\n\t\t\t\t\t\t\t\t\t   PredictionMode.resolvesToJustOneViableAlt(altSubSets));\n\t\t\t}\n\n//\t\t\tSystem.out.println(\"altSubSets: \"+altSubSets);\n//\t\t\tSystem.err.println(\"reach=\"+reach+\", \"+reach.conflictingAlts);\n\t\t\treach.uniqueAlt = getUniqueAlt(reach);\n\t\t\t// unique prediction?\n\t\t\tif ( reach.uniqueAlt!=ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\tpredictedAlt = reach.uniqueAlt;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ( mode != PredictionMode.LL_EXACT_AMBIG_DETECTION ) {\n\t\t\t\tpredictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets);\n\t\t\t\tif ( predictedAlt != ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// In exact ambiguity mode, we never try to terminate early.\n\t\t\t\t// Just keeps scarfing until we know what the conflict is\n\t\t\t\tif ( PredictionMode.allSubsetsConflict(altSubSets) &&\n\t\t\t\t\t PredictionMode.allSubsetsEqual(altSubSets) )\n\t\t\t\t{\n\t\t\t\t\tfoundExactAmbig = true;\n\t\t\t\t\tpredictedAlt = PredictionMode.getSingleViableAlt(altSubSets);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// else there are multiple non-conflicting subsets or\n\t\t\t\t// we're not sure what the ambiguity is yet.\n\t\t\t\t// So, keep going.\n\t\t\t}\n\n\t\t\tprevious = reach;\n\t\t\tif (t != IntStream.EOF) {\n\t\t\t\tinput.consume();\n\t\t\t\tt = input.LA(1);\n\t\t\t}\n\t\t}\n\n\t\t// If the configuration set uniquely predicts an alternative,\n\t\t// without conflict, then we know that it's a full LL decision\n\t\t// not SLL.\n\t\tif ( reach.uniqueAlt != ATN.INVALID_ALT_NUMBER ) {\n\t\t\treportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index());\n\t\t\treturn predictedAlt;\n\t\t}\n\n\t\t// We do not check predicates here because we have checked them\n\t\t// on-the-fly when doing full context prediction.\n\n\t\t/*\n\t\tIn non-exact ambiguity detection mode, we might\tactually be able to\n\t\tdetect an exact ambiguity, but I'm not going to spend the cycles\n\t\tneeded to check. We only emit ambiguity warnings in exact ambiguity\n\t\tmode.\n\n\t\tFor example, we might know that we have conflicting configurations.\n\t\tBut, that does not mean that there is no way forward without a\n\t\tconflict. It's possible to have nonconflicting alt subsets as in:\n\n\t\t   LL altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n\n\t\tfrom\n\n\t\t   [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n\t\t\t(13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n\n\t\tIn this case, (17,1,[5 $]) indicates there is some next sequence that\n\t\twould resolve this without conflict to alternative 1. Any other viable\n\t\tnext sequence, however, is associated with a conflict.  We stop\n\t\tlooking for input because no amount of further lookahead will alter\n\t\tthe fact that we should predict alternative 1.  We just can't say for\n\t\tsure that there is an ambiguity without looking further.\n\t\t*/\n\t\treportAmbiguity(dfa, D, startIndex, input.index(), foundExactAmbig,\n\t\t\t\t\t\treach.getAlts(), reach);\n\n\t\treturn predictedAlt;\n\t}\n\n\tprotected ATNConfigSet computeReachSet(ATNConfigSet closure, int t,\n\t\t\t\t\t\t\t\t\t\t   boolean fullCtx)\n\t{\n\t\tif ( debug )\n\t\t\tSystem.out.println(\"in computeReachSet, starting closure: \" + closure);\n\n\t\tif (mergeCache == null) {\n\t\t\tmergeCache = new DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>();\n\t\t}\n\n\t\tATNConfigSet intermediate = new ATNConfigSet(fullCtx);\n\n\t\t/* Configurations already in a rule stop state indicate reaching the end\n\t\t * of the decision rule (local context) or end of the start rule (full\n\t\t * context). Once reached, these configurations are never updated by a\n\t\t * closure operation, so they are handled separately for the performance\n\t\t * advantage of having a smaller intermediate set when calling closure.\n\t\t *\n\t\t * For full-context reach operations, separate handling is required to\n\t\t * ensure that the alternative matching the longest overall sequence is\n\t\t * chosen when multiple such configurations can match the input.\n\t\t */\n\t\tList<ATNConfig> skippedStopStates = null;\n\n\t\t// First figure out where we can reach on input t\n\t\tfor (ATNConfig c : closure) {\n\t\t\tif ( debug ) System.out.println(\"testing \"+getTokenName(t)+\" at \"+c.toString());\n\n\t\t\tif (c.state instanceof RuleStopState) {\n\t\t\t\tassert c.context.isEmpty();\n\t\t\t\tif (fullCtx || t == IntStream.EOF) {\n\t\t\t\t\tif (skippedStopStates == null) {\n\t\t\t\t\t\tskippedStopStates = new ArrayList<ATNConfig>();\n\t\t\t\t\t}\n\n\t\t\t\t\tskippedStopStates.add(c);\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint n = c.state.getNumberOfTransitions();\n\t\t\tfor (int ti=0; ti<n; ti++) {               // for each transition\n\t\t\t\tTransition trans = c.state.transition(ti);\n\t\t\t\tATNState target = getReachableTarget(trans, t);\n\t\t\t\tif ( target!=null ) {\n\t\t\t\t\tintermediate.add(new ATNConfig(c, target), mergeCache);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Now figure out where the reach operation can take us...\n\n\t\tATNConfigSet reach = null;\n\n\t\t/* This block optimizes the reach operation for intermediate sets which\n\t\t * trivially indicate a termination state for the overall\n\t\t * adaptivePredict operation.\n\t\t *\n\t\t * The conditions assume that intermediate\n\t\t * contains all configurations relevant to the reach set, but this\n\t\t * condition is not true when one or more configurations have been\n\t\t * withheld in skippedStopStates, or when the current symbol is EOF.\n\t\t */\n\t\tif (skippedStopStates == null && t != Token.EOF) {\n\t\t\tif ( intermediate.size()==1 ) {\n\t\t\t\t// Don't pursue the closure if there is just one state.\n\t\t\t\t// It can only have one alternative; just add to result\n\t\t\t\t// Also don't pursue the closure if there is unique alternative\n\t\t\t\t// among the configurations.\n\t\t\t\treach = intermediate;\n\t\t\t}\n\t\t\telse if ( getUniqueAlt(intermediate)!=ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\t// Also don't pursue the closure if there is unique alternative\n\t\t\t\t// among the configurations.\n\t\t\t\treach = intermediate;\n\t\t\t}\n\t\t}\n\n\t\t/* If the reach set could not be trivially determined, perform a closure\n\t\t * operation on the intermediate set to compute its initial value.\n\t\t */\n\t\tif (reach == null) {\n\t\t\treach = new ATNConfigSet(fullCtx);\n\t\t\tSet<ATNConfig> closureBusy = new HashSet<ATNConfig>();\n\t\t\tboolean treatEofAsEpsilon = t == Token.EOF;\n\t\t\tfor (ATNConfig c : intermediate) {\n\t\t\t\tclosure(c, reach, closureBusy, false, fullCtx, treatEofAsEpsilon);\n\t\t\t}\n\t\t}\n\n\t\tif (t == IntStream.EOF) {\n\t\t\t/* After consuming EOF no additional input is possible, so we are\n\t\t\t * only interested in configurations which reached the end of the\n\t\t\t * decision rule (local context) or end of the start rule (full\n\t\t\t * context). Update reach to contain only these configurations. This\n\t\t\t * handles both explicit EOF transitions in the grammar and implicit\n\t\t\t * EOF transitions following the end of the decision or start rule.\n\t\t\t *\n\t\t\t * When reach==intermediate, no closure operation was performed. In\n\t\t\t * this case, removeAllConfigsNotInRuleStopState needs to check for\n\t\t\t * reachable rule stop states as well as configurations already in\n\t\t\t * a rule stop state.\n\t\t\t *\n\t\t\t * This is handled before the configurations in skippedStopStates,\n\t\t\t * because any configurations potentially added from that list are\n\t\t\t * already guaranteed to meet this condition whether or not it's\n\t\t\t * required.\n\t\t\t */\n\t\t\treach = removeAllConfigsNotInRuleStopState(reach, reach == intermediate);\n\t\t}\n\n\t\t/* If skippedStopStates is not null, then it contains at least one\n\t\t * configuration. For full-context reach operations, these\n\t\t * configurations reached the end of the start rule, in which case we\n\t\t * only add them back to reach if no configuration during the current\n\t\t * closure operation reached such a state. This ensures adaptivePredict\n\t\t * chooses an alternative matching the longest overall sequence when\n\t\t * multiple alternatives are viable.\n\t\t */\n\t\tif (skippedStopStates != null && (!fullCtx || !PredictionMode.hasConfigInRuleStopState(reach))) {\n\t\t\tassert !skippedStopStates.isEmpty();\n\t\t\tfor (ATNConfig c : skippedStopStates) {\n\t\t\t\treach.add(c, mergeCache);\n\t\t\t}\n\t\t}\n\n\t\tif ( trace_atn_sim ) {\n\t\t\tSystem.out.println(\"computeReachSet \"+closure+\" -> \"+reach);\n\t\t}\n\n\t\tif ( reach.isEmpty() ) return null;\n\t\treturn reach;\n\t}\n\n\t/**\n\t * Return a configuration set containing only the configurations from\n\t * {@code configs} which are in a {@link RuleStopState}. If all\n\t * configurations in {@code configs} are already in a rule stop state, this\n\t * method simply returns {@code configs}.\n\t *\n\t * <p>When {@code lookToEndOfRule} is true, this method uses\n\t * {@link ATN#nextTokens} for each configuration in {@code configs} which is\n\t * not already in a rule stop state to see if a rule stop state is reachable\n\t * from the configuration via epsilon-only transitions.</p>\n\t *\n\t * @param configs the configuration set to update\n\t * @param lookToEndOfRule when true, this method checks for rule stop states\n\t * reachable by epsilon-only transitions from each configuration in\n\t * {@code configs}.\n\t *\n\t * @return {@code configs} if all configurations in {@code configs} are in a\n\t * rule stop state, otherwise return a new configuration set containing only\n\t * the configurations from {@code configs} which are in a rule stop state\n\t */\n\tprotected ATNConfigSet removeAllConfigsNotInRuleStopState(ATNConfigSet configs, boolean lookToEndOfRule) {\n\t\tif (PredictionMode.allConfigsInRuleStopStates(configs)) {\n\t\t\treturn configs;\n\t\t}\n\n\t\tATNConfigSet result = new ATNConfigSet(configs.fullCtx);\n\t\tfor (ATNConfig config : configs) {\n\t\t\tif (config.state instanceof RuleStopState) {\n\t\t\t\tresult.add(config, mergeCache);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (lookToEndOfRule && config.state.onlyHasEpsilonTransitions()) {\n\t\t\t\tIntervalSet nextTokens = atn.nextTokens(config.state);\n\t\t\t\tif (nextTokens.contains(Token.EPSILON)) {\n\t\t\t\t\tATNState endOfRuleState = atn.ruleToStopState[config.state.ruleIndex];\n\t\t\t\t\tresult.add(new ATNConfig(config, endOfRuleState), mergeCache);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\n\tprotected ATNConfigSet computeStartState(ATNState p,\n\t\t\t\t\t\t\t\t\t\t     RuleContext ctx,\n\t\t\t\t\t\t\t\t\t\t     boolean fullCtx)\n\t{\n\t\t// always at least the implicit call to start rule\n\t\tPredictionContext initialContext = PredictionContext.fromRuleContext(atn, ctx);\n\t\tATNConfigSet configs = new ATNConfigSet(fullCtx);\n\n\t\tif ( trace_atn_sim )  {\n\t\t\tSystem.out.println(\"computeStartState from ATN state \"+p+\" initialContext=\"+initialContext.toString(parser));\n\t\t}\n\n\t\tfor (int i=0; i<p.getNumberOfTransitions(); i++) {\n\t\t\tATNState target = p.transition(i).target;\n\t\t\tATNConfig c = new ATNConfig(target, i+1, initialContext);\n\t\t\tSet<ATNConfig> closureBusy = new HashSet<ATNConfig>();\n\t\t\tclosure(c, configs, closureBusy, true, fullCtx, false);\n\t\t}\n\n\t\treturn configs;\n\t}\n\n\t/* parrt internal source braindump that doesn't mess up\n\t * external API spec.\n\t\tcontext-sensitive in that they can only be properly evaluated\n\t\tin the context of the proper prec argument. Without pruning,\n\t\tthese predicates are normal predicates evaluated when we reach\n\t\tconflict state (or unique prediction). As we cannot evaluate\n\t\tthese predicates out of context, the resulting conflict leads\n\t\tto full LL evaluation and nonlinear prediction which shows up\n\t\tvery clearly with fairly large expressions.\n\n\t\tExample grammar:\n\n\t\te : e '*' e\n\t\t  | e '+' e\n\t\t  | INT\n\t\t  ;\n\n\t\tWe convert that to the following:\n\n\t\te[int prec]\n\t\t\t:   INT\n\t\t\t\t( {3>=prec}? '*' e[4]\n\t\t\t\t| {2>=prec}? '+' e[3]\n\t\t\t\t)*\n\t\t\t;\n\n\t\tThe (..)* loop has a decision for the inner block as well as\n\t\tan enter or exit decision, which is what concerns us here. At\n\t\tthe 1st + of input 1+2+3, the loop entry sees both predicates\n\t\tand the loop exit also sees both predicates by falling off the\n\t\tedge of e.  This is because we have no stack information with\n\t\tSLL and find the follow of e, which will hit the return states\n\t\tinside the loop after e[4] and e[3], which brings it back to\n\t\tthe enter or exit decision. In this case, we know that we\n\t\tcannot evaluate those predicates because we have fallen off\n\t\tthe edge of the stack and will in general not know which prec\n\t\tparameter is the right one to use in the predicate.\n\n\t\tBecause we have special information, that these are precedence\n\t\tpredicates, we can resolve them without failing over to full\n\t\tLL despite their context sensitive nature. We make an\n\t\tassumption that prec[-1] <= prec[0], meaning that the current\n\t\tprecedence level is greater than or equal to the precedence\n\t\tlevel of recursive invocations above us in the stack. For\n\t\texample, if predicate {3>=prec}? is true of the current prec,\n\t\tthen one option is to enter the loop to match it now. The\n\t\tother option is to exit the loop and the left recursive rule\n\t\tto match the current operator in rule invocation further up\n\t\tthe stack. But, we know that all of those prec are lower or\n\t\tthe same value and so we can decide to enter the loop instead\n\t\tof matching it later. That means we can strip out the other\n\t\tconfiguration for the exit branch.\n\n\t\tSo imagine we have (14,1,$,{2>=prec}?) and then\n\t\t(14,2,$-dipsIntoOuterContext,{2>=prec}?). The optimization\n\t\tallows us to collapse these two configurations. We know that\n\t\tif {2>=prec}? is true for the current prec parameter, it will\n\t\talso be true for any prec from an invoking e call, indicated\n\t\tby dipsIntoOuterContext. As the predicates are both true, we\n\t\thave the option to evaluate them early in the decision start\n\t\tstate. We do this by stripping both predicates and choosing to\n\t\tenter the loop as it is consistent with the notion of operator\n\t\tprecedence. It's also how the full LL conflict resolution\n\t\twould work.\n\n\t\tThe solution requires a different DFA start state for each\n\t\tprecedence level.\n\n\t\tThe basic filter mechanism is to remove configurations of the\n\t\tform (p, 2, pi) if (p, 1, pi) exists for the same p and pi. In\n\t\tother words, for the same ATN state and predicate context,\n\t\tremove any configuration associated with an exit branch if\n\t\tthere is a configuration associated with the enter branch.\n\n\t\tIt's also the case that the filter evaluates precedence\n\t\tpredicates and resolves conflicts according to precedence\n\t\tlevels. For example, for input 1+2+3 at the first +, we see\n\t\tprediction filtering\n\n\t\t[(11,1,[$],{3>=prec}?), (14,1,[$],{2>=prec}?), (5,2,[$],up=1),\n\t\t (11,2,[$],up=1), (14,2,[$],up=1)],hasSemanticContext=true,dipsIntoOuterContext\n\n\t\tto\n\n\t\t[(11,1,[$]), (14,1,[$]), (5,2,[$],up=1)],dipsIntoOuterContext\n\n\t\tThis filters because {3>=prec}? evals to true and collapses\n\t\t(11,1,[$],{3>=prec}?) and (11,2,[$],up=1) since early conflict\n\t\tresolution based upon rules of operator precedence fits with\n\t\tour usual match first alt upon conflict.\n\n\t\tWe noticed a problem where a recursive call resets precedence\n\t\tto 0. Sam's fix: each config has flag indicating if it has\n\t\treturned from an expr[0] call. then just don't filter any\n\t\tconfig with that flag set. flag is carried along in\n\t\tclosure(). so to avoid adding field, set bit just under sign\n\t\tbit of dipsIntoOuterContext (SUPPRESS_PRECEDENCE_FILTER).\n\t\tWith the change you filter \"unless (p, 2, pi) was reached\n\t\tafter leaving the rule stop state of the LR rule containing\n\t\tstate p, corresponding to a rule invocation with precedence\n\t\tlevel 0\"\n\t */\n\n\t/**\n\t * This method transforms the start state computed by\n\t * {@link #computeStartState} to the special start state used by a\n\t * precedence DFA for a particular precedence value. The transformation\n\t * process applies the following changes to the start state's configuration\n\t * set.\n\t *\n\t * <ol>\n\t * <li>Evaluate the precedence predicates for each configuration using\n\t * {@link SemanticContext#evalPrecedence}.</li>\n\t * <li>When {@link ATNConfig#isPrecedenceFilterSuppressed} is {@code false},\n\t * remove all configurations which predict an alternative greater than 1,\n\t * for which another configuration that predicts alternative 1 is in the\n\t * same ATN state with the same prediction context. This transformation is\n\t * valid for the following reasons:\n\t * <ul>\n\t * <li>The closure block cannot contain any epsilon transitions which bypass\n\t * the body of the closure, so all states reachable via alternative 1 are\n\t * part of the precedence alternatives of the transformed left-recursive\n\t * rule.</li>\n\t * <li>The \"primary\" portion of a left recursive rule cannot contain an\n\t * epsilon transition, so the only way an alternative other than 1 can exist\n\t * in a state that is also reachable via alternative 1 is by nesting calls\n\t * to the left-recursive rule, with the outer calls not being at the\n\t * preferred precedence level. The\n\t * {@link ATNConfig#isPrecedenceFilterSuppressed} property marks ATN\n\t * configurations which do not meet this condition, and therefore are not\n\t * eligible for elimination during the filtering process.</li>\n\t * </ul>\n\t * </li>\n\t * </ol>\n\t *\n\t * <p>\n\t * The prediction context must be considered by this filter to address\n\t * situations like the following.\n\t * </p>\n\t * <code>\n\t * <pre>\n\t * grammar TA;\n\t * prog: statement* EOF;\n\t * statement: letterA | statement letterA 'b' ;\n\t * letterA: 'a';\n\t * </pre>\n\t * </code>\n\t * <p>\n\t * If the above grammar, the ATN state immediately before the token\n\t * reference {@code 'a'} in {@code letterA} is reachable from the left edge\n\t * of both the primary and closure blocks of the left-recursive rule\n\t * {@code statement}. The prediction context associated with each of these\n\t * configurations distinguishes between them, and prevents the alternative\n\t * which stepped out to {@code prog} (and then back in to {@code statement}\n\t * from being eliminated by the filter.\n\t * </p>\n\t *\n\t * @param configs The configuration set computed by\n\t * {@link #computeStartState} as the start state for the DFA.\n\t * @return The transformed configuration set representing the start state\n\t * for a precedence DFA at a particular precedence level (determined by\n\t * calling {@link Parser#getPrecedence}).\n\t */\n\tprotected ATNConfigSet applyPrecedenceFilter(ATNConfigSet configs) {\n\t\tMap<Integer, PredictionContext> statesFromAlt1 = new HashMap<Integer, PredictionContext>();\n\t\tATNConfigSet configSet = new ATNConfigSet(configs.fullCtx);\n\t\tfor (ATNConfig config : configs) {\n\t\t\t// handle alt 1 first\n\t\t\tif (config.alt != 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tSemanticContext updatedContext = config.semanticContext.evalPrecedence(parser, _outerContext);\n\t\t\tif (updatedContext == null) {\n\t\t\t\t// the configuration was eliminated\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstatesFromAlt1.put(config.state.stateNumber, config.context);\n\t\t\tif (updatedContext != config.semanticContext) {\n\t\t\t\tconfigSet.add(new ATNConfig(config, updatedContext), mergeCache);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconfigSet.add(config, mergeCache);\n\t\t\t}\n\t\t}\n\n\t\tfor (ATNConfig config : configs) {\n\t\t\tif (config.alt == 1) {\n\t\t\t\t// already handled\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!config.isPrecedenceFilterSuppressed()) {\n\t\t\t\t/* In the future, this elimination step could be updated to also\n\t\t\t\t * filter the prediction context for alternatives predicting alt>1\n\t\t\t\t * (basically a graph subtraction algorithm).\n\t\t\t\t */\n\t\t\t\tPredictionContext context = statesFromAlt1.get(config.state.stateNumber);\n\t\t\t\tif (context != null && context.equals(config.context)) {\n\t\t\t\t\t// eliminated\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconfigSet.add(config, mergeCache);\n\t\t}\n\n\t\treturn configSet;\n\t}\n\n\tprotected ATNState getReachableTarget(Transition trans, int ttype) {\n\t\tif (trans.matches(ttype, 0, atn.maxTokenType)) {\n\t\t\treturn trans.target;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprotected SemanticContext[] getPredsForAmbigAlts(BitSet ambigAlts,\n\t\t\t\t\t\t\t\t\t\t\t\t  ATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t\t\t  int nalts)\n\t{\n\t\t// REACH=[1|1|[]|0:0, 1|2|[]|0:1]\n\t\t/* altToPred starts as an array of all null contexts. The entry at index i\n\t\t * corresponds to alternative i. altToPred[i] may have one of three values:\n\t\t *   1. null: no ATNConfig c is found such that c.alt==i\n\t\t *   2. SemanticContext.NONE: At least one ATNConfig c exists such that\n\t\t *      c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,\n\t\t *      alt i has at least one unpredicated config.\n\t\t *   3. Non-NONE Semantic Context: There exists at least one, and for all\n\t\t *      ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.\n\t\t *\n\t\t * From this, it is clear that NONE||anything==NONE.\n\t\t */\n\t\tSemanticContext[] altToPred = new SemanticContext[nalts + 1];\n\t\tfor (ATNConfig c : configs) {\n\t\t\tif ( ambigAlts.get(c.alt) ) {\n\t\t\t\taltToPred[c.alt] = SemanticContext.or(altToPred[c.alt], c.semanticContext);\n\t\t\t}\n\t\t}\n\n\t\tint nPredAlts = 0;\n\t\tfor (int i = 1; i <= nalts; i++) {\n\t\t\tif (altToPred[i] == null) {\n\t\t\t\taltToPred[i] = SemanticContext.Empty.Instance;\n\t\t\t}\n\t\t\telse if (altToPred[i] != SemanticContext.Empty.Instance) {\n\t\t\t\tnPredAlts++;\n\t\t\t}\n\t\t}\n\n//\t\t// Optimize away p||p and p&&p TODO: optimize() was a no-op\n//\t\tfor (int i = 0; i < altToPred.length; i++) {\n//\t\t\taltToPred[i] = altToPred[i].optimize();\n//\t\t}\n\n\t\t// nonambig alts are null in altToPred\n\t\tif ( nPredAlts==0 ) altToPred = null;\n\t\tif ( debug ) System.out.println(\"getPredsForAmbigAlts result \"+Arrays.toString(altToPred));\n\t\treturn altToPred;\n\t}\n\n\tprotected DFAState.PredPrediction[] getPredicatePredictions(BitSet ambigAlts,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SemanticContext[] altToPred)\n\t{\n\t\tList<DFAState.PredPrediction> pairs = new ArrayList<DFAState.PredPrediction>();\n\t\tboolean containsPredicate = false;\n\t\tfor (int i = 1; i < altToPred.length; i++) {\n\t\t\tSemanticContext pred = altToPred[i];\n\n\t\t\t// unpredicated is indicated by SemanticContext.NONE\n\t\t\tassert pred != null;\n\n\t\t\tif (ambigAlts!=null && ambigAlts.get(i)) {\n\t\t\t\tpairs.add(new DFAState.PredPrediction(pred, i));\n\t\t\t}\n\t\t\tif ( pred!=SemanticContext.Empty.Instance ) containsPredicate = true;\n\t\t}\n\n\t\tif ( !containsPredicate ) {\n\t\t\treturn null;\n\t\t}\n\n//\t\tSystem.out.println(Arrays.toString(altToPred)+\"->\"+pairs);\n\t\treturn pairs.toArray(new DFAState.PredPrediction[0]);\n\t}\n\n\t/**\n\t * This method is used to improve the localization of error messages by\n\t * choosing an alternative rather than throwing a\n\t * {@link NoViableAltException} in particular prediction scenarios where the\n\t * {@link #ERROR} state was reached during ATN simulation.\n\t *\n\t * <p>\n\t * The default implementation of this method uses the following\n\t * algorithm to identify an ATN configuration which successfully parsed the\n\t * decision entry rule. Choosing such an alternative ensures that the\n\t * {@link ParserRuleContext} returned by the calling rule will be complete\n\t * and valid, and the syntax error will be reported later at a more\n\t * localized location.</p>\n\t *\n\t * <ul>\n\t * <li>If a syntactically valid path or paths reach the end of the decision rule and\n\t * they are semantically valid if predicated, return the min associated alt.</li>\n\t * <li>Else, if a semantically invalid but syntactically valid path exist\n\t * or paths exist, return the minimum associated alt.\n\t * </li>\n\t * <li>Otherwise, return {@link ATN#INVALID_ALT_NUMBER}.</li>\n\t * </ul>\n\t *\n\t * <p>\n\t * In some scenarios, the algorithm described above could predict an\n\t * alternative which will result in a {@link FailedPredicateException} in\n\t * the parser. Specifically, this could occur if the <em>only</em> configuration\n\t * capable of successfully parsing to the end of the decision rule is\n\t * blocked by a semantic predicate. By choosing this alternative within\n\t * {@link #adaptivePredict} instead of throwing a\n\t * {@link NoViableAltException}, the resulting\n\t * {@link FailedPredicateException} in the parser will identify the specific\n\t * predicate which is preventing the parser from successfully parsing the\n\t * decision rule, which helps developers identify and correct logic errors\n\t * in semantic predicates.\n\t * </p>\n\t *\n\t * @param configs The ATN configurations which were valid immediately before\n\t * the {@link #ERROR} state was reached\n\t * @param outerContext The is the \\gamma_0 initial parser context from the paper\n\t * or the parser stack at the instant before prediction commences.\n\t *\n\t * @return The value to return from {@link #adaptivePredict}, or\n\t * {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not\n\t * identified and {@link #adaptivePredict} should report an error instead.\n\t */\n\tprotected int getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(ATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  ParserRuleContext outerContext)\n\t{\n\t\tPair<ATNConfigSet,ATNConfigSet> sets =\n\t\t\tsplitAccordingToSemanticValidity(configs, outerContext);\n\t\tATNConfigSet semValidConfigs = sets.a;\n\t\tATNConfigSet semInvalidConfigs = sets.b;\n\t\tint alt = getAltThatFinishedDecisionEntryRule(semValidConfigs);\n\t\tif ( alt!=ATN.INVALID_ALT_NUMBER ) { // semantically/syntactically viable path exists\n\t\t\treturn alt;\n\t\t}\n\t\t// Is there a syntactically valid path with a failed pred?\n\t\tif ( semInvalidConfigs.size()>0 ) {\n\t\t\talt = getAltThatFinishedDecisionEntryRule(semInvalidConfigs);\n\t\t\tif ( alt!=ATN.INVALID_ALT_NUMBER ) { // syntactically viable path exists\n\t\t\t\treturn alt;\n\t\t\t}\n\t\t}\n\t\treturn ATN.INVALID_ALT_NUMBER;\n\t}\n\n\tprotected int getAltThatFinishedDecisionEntryRule(ATNConfigSet configs) {\n\t\tIntervalSet alts = new IntervalSet();\n\t\tfor (ATNConfig c : configs) {\n\t\t\tif ( c.getOuterContextDepth()>0 || (c.state instanceof RuleStopState && c.context.hasEmptyPath()) ) {\n\t\t\t\talts.add(c.alt);\n\t\t\t}\n\t\t}\n\t\tif ( alts.size()==0 ) return ATN.INVALID_ALT_NUMBER;\n\t\treturn alts.getMinElement();\n\t}\n\n\t/** Walk the list of configurations and split them according to\n\t *  those that have preds evaluating to true/false.  If no pred, assume\n\t *  true pred and include in succeeded set.  Returns Pair of sets.\n\t *\n\t *  Create a new set so as not to alter the incoming parameter.\n\t *\n\t *  Assumption: the input stream has been restored to the starting point\n\t *  prediction, which is where predicates need to evaluate.\n \t */\n\tprotected Pair<ATNConfigSet,ATNConfigSet> splitAccordingToSemanticValidity(\n\t\tATNConfigSet configs,\n\t\tParserRuleContext outerContext)\n\t{\n\t\tATNConfigSet succeeded = new ATNConfigSet(configs.fullCtx);\n\t\tATNConfigSet failed = new ATNConfigSet(configs.fullCtx);\n\t\tfor (ATNConfig c : configs) {\n\t\t\tif ( c.semanticContext!=SemanticContext.Empty.Instance ) {\n\t\t\t\tboolean predicateEvaluationResult = evalSemanticContext(c.semanticContext, outerContext, c.alt, configs.fullCtx);\n\t\t\t\tif ( predicateEvaluationResult ) {\n\t\t\t\t\tsucceeded.add(c);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfailed.add(c);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsucceeded.add(c);\n\t\t\t}\n\t\t}\n\t\treturn new Pair<ATNConfigSet, ATNConfigSet>(succeeded,failed);\n\t}\n\n\t/** Look through a list of predicate/alt pairs, returning alts for the\n\t *  pairs that win. A {@code NONE} predicate indicates an alt containing an\n\t *  unpredicated config which behaves as \"always true.\" If !complete\n\t *  then we stop at the first predicate that evaluates to true. This\n\t *  includes pairs with null predicates.\n\t */\n\tprotected BitSet evalSemanticContext(DFAState.PredPrediction[] predPredictions,\n\t\t\t\t\t\t\t\t\t  ParserRuleContext outerContext,\n\t\t\t\t\t\t\t\t\t  boolean complete)\n\t{\n\t\tBitSet predictions = new BitSet();\n\t\tfor (DFAState.PredPrediction pair : predPredictions) {\n\t\t\tif ( pair.pred==SemanticContext.Empty.Instance ) {\n\t\t\t\tpredictions.set(pair.alt);\n\t\t\t\tif (!complete) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tboolean fullCtx = false; // in dfa\n\t\t\tboolean predicateEvaluationResult = evalSemanticContext(pair.pred, outerContext, pair.alt, fullCtx);\n\t\t\tif ( debug || dfa_debug ) {\n\t\t\t\tSystem.out.println(\"eval pred \"+pair+\"=\"+predicateEvaluationResult);\n\t\t\t}\n\n\t\t\tif ( predicateEvaluationResult ) {\n\t\t\t\tif ( debug || dfa_debug ) System.out.println(\"PREDICT \"+pair.alt);\n\t\t\t\tpredictions.set(pair.alt);\n\t\t\t\tif (!complete) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn predictions;\n\t}\n\n\t/**\n\t * Evaluate a semantic context within a specific parser context.\n\t *\n\t * <p>\n\t * This method might not be called for every semantic context evaluated\n\t * during the prediction process. In particular, we currently do not\n\t * evaluate the following but it may change in the future:</p>\n\t *\n\t * <ul>\n\t * <li>Precedence predicates (represented by\n\t * {@link SemanticContext.PrecedencePredicate}) are not currently evaluated\n\t * through this method.</li>\n\t * <li>Operator predicates (represented by {@link SemanticContext.AND} and\n\t * {@link SemanticContext.OR}) are evaluated as a single semantic\n\t * context, rather than evaluating the operands individually.\n\t * Implementations which require evaluation results from individual\n\t * predicates should override this method to explicitly handle evaluation of\n\t * the operands within operator predicates.</li>\n\t * </ul>\n\t *\n\t * @param pred The semantic context to evaluate\n\t * @param parserCallStack The parser context in which to evaluate the\n\t * semantic context\n\t * @param alt The alternative which is guarded by {@code pred}\n\t * @param fullCtx {@code true} if the evaluation is occurring during LL\n\t * prediction; otherwise, {@code false} if the evaluation is occurring\n\t * during SLL prediction\n\t *\n\t * @since 4.3\n\t */\n\tprotected boolean evalSemanticContext(SemanticContext pred, ParserRuleContext parserCallStack, int alt, boolean fullCtx) {\n\t\treturn pred.eval(parser, parserCallStack);\n\t}\n\n\t/* TODO: If we are doing predicates, there is no point in pursuing\n\t\t closure operations if we reach a DFA state that uniquely predicts\n\t\t alternative. We will not be caching that DFA state and it is a\n\t\t waste to pursue the closure. Might have to advance when we do\n\t\t ambig detection thought :(\n\t\t  */\n\n\tprotected void closure(ATNConfig config,\n\t\t\t\t\t\t   ATNConfigSet configs,\n\t\t\t\t\t\t   Set<ATNConfig> closureBusy,\n\t\t\t\t\t\t   boolean collectPredicates,\n\t\t\t\t\t\t   boolean fullCtx,\n\t\t\t\t\t\t   boolean treatEofAsEpsilon)\n\t{\n\t\tfinal int initialDepth = 0;\n\t\tclosureCheckingStopState(config, configs, closureBusy, collectPredicates,\n\t\t\t\t\t\t\t\t fullCtx,\n\t\t\t\t\t\t\t\t initialDepth, treatEofAsEpsilon);\n\t\tassert !fullCtx || !configs.dipsIntoOuterContext;\n\t}\n\n\tprotected void closureCheckingStopState(ATNConfig config,\n\t\t\t\t\t\t\t\t\t\t\tATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t\tSet<ATNConfig> closureBusy,\n\t\t\t\t\t\t\t\t\t\t\tboolean collectPredicates,\n\t\t\t\t\t\t\t\t\t\t\tboolean fullCtx,\n\t\t\t\t\t\t\t\t\t\t\tint depth,\n\t\t\t\t\t\t\t\t\t\t\tboolean treatEofAsEpsilon)\n\t{\n\t\tif ( trace_atn_sim ) System.out.println(\"closure(\"+config.toString(parser,true)+\")\");\n\n\t\tif ( config.state instanceof RuleStopState ) {\n\t\t\t// We hit rule end. If we have context info, use it\n\t\t\t// run thru all possible stack tops in ctx\n\t\t\tif ( !config.context.isEmpty() ) {\n\t\t\t\tfor (int i = 0; i < config.context.size(); i++) {\n\t\t\t\t\tif ( config.context.getReturnState(i)==PredictionContext.EMPTY_RETURN_STATE ) {\n\t\t\t\t\t\tif (fullCtx) {\n\t\t\t\t\t\t\tconfigs.add(new ATNConfig(config, config.state, EmptyPredictionContext.Instance), mergeCache);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t// we have no context info, just chase follow links (if greedy)\n\t\t\t\t\t\t\tif ( debug ) System.out.println(\"FALLING off rule \"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgetRuleName(config.state.ruleIndex));\n\t\t\t\t\t\t\tclosure_(config, configs, closureBusy, collectPredicates,\n\t\t\t\t\t\t\t\t\t fullCtx, depth, treatEofAsEpsilon);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tATNState returnState = atn.states.get(config.context.getReturnState(i));\n\t\t\t\t\tPredictionContext newContext = config.context.getParent(i); // \"pop\" return state\n\t\t\t\t\tATNConfig c = new ATNConfig(returnState, config.alt, newContext,\n\t\t\t\t\t\t\t\t\t\t\t\tconfig.semanticContext);\n\t\t\t\t\t// While we have context to pop back from, we may have\n\t\t\t\t\t// gotten that context AFTER having falling off a rule.\n\t\t\t\t\t// Make sure we track that we are now out of context.\n\t\t\t\t\t//\n\t\t\t\t\t// This assignment also propagates the\n\t\t\t\t\t// isPrecedenceFilterSuppressed() value to the new\n\t\t\t\t\t// configuration.\n\t\t\t\t\tc.reachesIntoOuterContext = config.reachesIntoOuterContext;\n\t\t\t\t\tassert depth > Integer.MIN_VALUE;\n\t\t\t\t\tclosureCheckingStopState(c, configs, closureBusy, collectPredicates,\n\t\t\t\t\t\t\t\t\t\t\t fullCtx, depth - 1, treatEofAsEpsilon);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (fullCtx) {\n\t\t\t\t// reached end of start rule\n\t\t\t\tconfigs.add(config, mergeCache);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// else if we have no context info, just chase follow links (if greedy)\n\t\t\t\tif ( debug ) System.out.println(\"FALLING off rule \"+\n\t\t\t\t\t\t\t\t\t\t\t\tgetRuleName(config.state.ruleIndex));\n\t\t\t}\n\t\t}\n\n\t\tclosure_(config, configs, closureBusy, collectPredicates,\n\t\t\t\t fullCtx, depth, treatEofAsEpsilon);\n\t}\n\n\t/** Do the actual work of walking epsilon edges */\n\tprotected void closure_(ATNConfig config,\n\t\t\t\t\t\t\tATNConfigSet configs,\n\t\t\t\t\t\t\tSet<ATNConfig> closureBusy,\n\t\t\t\t\t\t\tboolean collectPredicates,\n\t\t\t\t\t\t\tboolean fullCtx,\n\t\t\t\t\t\t\tint depth,\n\t\t\t\t\t\t\tboolean treatEofAsEpsilon)\n\t{\n\t\tATNState p = config.state;\n\t\t// optimization\n\t\tif ( !p.onlyHasEpsilonTransitions() ) {\n            configs.add(config, mergeCache);\n\t\t\t// make sure to not return here, because EOF transitions can act as\n\t\t\t// both epsilon transitions and non-epsilon transitions.\n//            if ( debug ) System.out.println(\"added config \"+configs);\n        }\n\n\t\tfor (int i=0; i<p.getNumberOfTransitions(); i++) {\n\t\t\tif ( i==0 && canDropLoopEntryEdgeInLeftRecursiveRule(config) ) continue;\n\n\t\t\tTransition t = p.transition(i);\n\t\t\tboolean continueCollecting =\n\t\t\t\t!(t instanceof ActionTransition) && collectPredicates;\n\t\t\tATNConfig c = getEpsilonTarget(config, t, continueCollecting,\n\t\t\t\t\t\t\t\t\t\t   depth == 0, fullCtx, treatEofAsEpsilon);\n\t\t\tif ( c!=null ) {\n\t\t\t\tint newDepth = depth;\n\t\t\t\tif ( config.state instanceof RuleStopState) {\n\t\t\t\t\tassert !fullCtx;\n\t\t\t\t\t// target fell off end of rule; mark resulting c as having dipped into outer context\n\t\t\t\t\t// We can't get here if incoming config was rule stop and we had context\n\t\t\t\t\t// track how far we dip into outer context.  Might\n\t\t\t\t\t// come in handy and we avoid evaluating context dependent\n\t\t\t\t\t// preds if this is > 0.\n\n\t\t\t\t\tif (_dfa != null && _dfa.isPrecedenceDfa()) {\n\t\t\t\t\t\tint outermostPrecedenceReturn = ((EpsilonTransition)t).outermostPrecedenceReturn();\n\t\t\t\t\t\tif (outermostPrecedenceReturn == _dfa.atnStartState.ruleIndex) {\n\t\t\t\t\t\t\tc.setPrecedenceFilterSuppressed(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tc.reachesIntoOuterContext++;\n\n\t\t\t\t\tif (!closureBusy.add(c)) {\n\t\t\t\t\t\t// avoid infinite recursion for right-recursive rules\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconfigs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method\n\t\t\t\t\tassert newDepth > Integer.MIN_VALUE;\n\t\t\t\t\tnewDepth--;\n\t\t\t\t\tif ( debug ) System.out.println(\"dips into outer ctx: \"+c);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!t.isEpsilon() && !closureBusy.add(c)) {\n\t\t\t\t\t\t// avoid infinite recursion for EOF* and EOF+\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (t instanceof RuleTransition) {\n\t\t\t\t\t\t// latch when newDepth goes negative - once we step out of the entry context we can't return\n\t\t\t\t\t\tif (newDepth >= 0) {\n\t\t\t\t\t\t\tnewDepth++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tclosureCheckingStopState(c, configs, closureBusy, continueCollecting,\n\t\t\t\t\t\t\t\t\t\t fullCtx, newDepth, treatEofAsEpsilon);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Implements first-edge (loop entry) elimination as an optimization\n\t *  during closure operations.  See antlr/antlr4#1398.\n\t *\n\t * The optimization is to avoid adding the loop entry config when\n\t * the exit path can only lead back to the same\n\t * StarLoopEntryState after popping context at the rule end state\n\t * (traversing only epsilon edges, so we're still in closure, in\n\t * this same rule).\n\t *\n\t * We need to detect any state that can reach loop entry on\n\t * epsilon w/o exiting rule. We don't have to look at FOLLOW\n\t * links, just ensure that all stack tops for config refer to key\n\t * states in LR rule.\n\t *\n\t * To verify we are in the right situation we must first check\n\t * closure is at a StarLoopEntryState generated during LR removal.\n\t * Then we check that each stack top of context is a return state\n\t * from one of these cases:\n\t *\n\t *   1. 'not' expr, '(' type ')' expr. The return state points at loop entry state\n\t *   2. expr op expr. The return state is the block end of internal block of (...)*\n\t *   3. 'between' expr 'and' expr. The return state of 2nd expr reference.\n\t *      That state points at block end of internal block of (...)*.\n\t *   4. expr '?' expr ':' expr. The return state points at block end,\n\t *      which points at loop entry state.\n\t *\n\t * If any is true for each stack top, then closure does not add a\n\t * config to the current config set for edge[0], the loop entry branch.\n\t *\n\t *  Conditions fail if any context for the current config is:\n\t *\n\t *   a. empty (we'd fall out of expr to do a global FOLLOW which could\n\t *      even be to some weird spot in expr) or,\n\t *   b. lies outside of expr or,\n\t *   c. lies within expr but at a state not the BlockEndState\n\t *   generated during LR removal\n\t *\n\t * Do we need to evaluate predicates ever in closure for this case?\n\t *\n\t * No. Predicates, including precedence predicates, are only\n\t * evaluated when computing a DFA start state. I.e., only before\n\t * the lookahead (but not parser) consumes a token.\n\t *\n\t * There are no epsilon edges allowed in LR rule alt blocks or in\n\t * the \"primary\" part (ID here). If closure is in\n\t * StarLoopEntryState any lookahead operation will have consumed a\n\t * token as there are no epsilon-paths that lead to\n\t * StarLoopEntryState. We do not have to evaluate predicates\n\t * therefore if we are in the generated StarLoopEntryState of a LR\n\t * rule. Note that when making a prediction starting at that\n\t * decision point, decision d=2, compute-start-state performs\n\t * closure starting at edges[0], edges[1] emanating from\n\t * StarLoopEntryState. That means it is not performing closure on\n\t * StarLoopEntryState during compute-start-state.\n\t *\n\t * How do we know this always gives same prediction answer?\n\t *\n\t * Without predicates, loop entry and exit paths are ambiguous\n\t * upon remaining input +b (in, say, a+b). Either paths lead to\n\t * valid parses. Closure can lead to consuming + immediately or by\n\t * falling out of this call to expr back into expr and loop back\n\t * again to StarLoopEntryState to match +b. In this special case,\n\t * we choose the more efficient path, which is to take the bypass\n\t * path.\n\t *\n\t * The lookahead language has not changed because closure chooses\n\t * one path over the other. Both paths lead to consuming the same\n\t * remaining input during a lookahead operation. If the next token\n\t * is an operator, lookahead will enter the choice block with\n\t * operators. If it is not, lookahead will exit expr. Same as if\n\t * closure had chosen to enter the choice block immediately.\n\t *\n\t * Closure is examining one config (some loopentrystate, some alt,\n\t * context) which means it is considering exactly one alt. Closure\n\t * always copies the same alt to any derived configs.\n\t *\n\t * How do we know this optimization doesn't mess up precedence in\n\t * our parse trees?\n\t *\n\t * Looking through expr from left edge of stat only has to confirm\n\t * that an input, say, a+b+c; begins with any valid interpretation\n\t * of an expression. The precedence actually doesn't matter when\n\t * making a decision in stat seeing through expr. It is only when\n\t * parsing rule expr that we must use the precedence to get the\n\t * right interpretation and, hence, parse tree.\n\t *\n\t * @since 4.6\n\t */\n\tprotected boolean canDropLoopEntryEdgeInLeftRecursiveRule(ATNConfig config) {\n\t\tif ( TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT ) return false;\n\t\tATNState p = config.state;\n\t\t// First check to see if we are in StarLoopEntryState generated during\n\t\t// left-recursion elimination. For efficiency, also check if\n\t\t// the context has an empty stack case. If so, it would mean\n\t\t// global FOLLOW so we can't perform optimization\n\t\tif ( p.getStateType() != ATNState.STAR_LOOP_ENTRY ||\n\t\t\t !((StarLoopEntryState)p).isPrecedenceDecision || // Are we the special loop entry/exit state?\n\t\t\t config.context.isEmpty() ||                      // If SLL wildcard\n\t\t\t config.context.hasEmptyPath())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\t// Require all return states to return back to the same rule\n\t\t// that p is in.\n\t\tint numCtxs = config.context.size();\n\t\tfor (int i = 0; i < numCtxs; i++) { // for each stack context\n\t\t\tATNState returnState = atn.states.get(config.context.getReturnState(i));\n\t\t\tif ( returnState.ruleIndex != p.ruleIndex ) return false;\n\t\t}\n\n\t\tBlockStartState decisionStartState = (BlockStartState)p.transition(0).target;\n\t\tint blockEndStateNum = decisionStartState.endState.stateNumber;\n\t\tBlockEndState blockEndState = (BlockEndState)atn.states.get(blockEndStateNum);\n\n\t\t// Verify that the top of each stack context leads to loop entry/exit\n\t\t// state through epsilon edges and w/o leaving rule.\n\t\tfor (int i = 0; i < numCtxs; i++) {                           // for each stack context\n\t\t\tint returnStateNumber = config.context.getReturnState(i);\n\t\t\tATNState returnState = atn.states.get(returnStateNumber);\n\t\t\t// all states must have single outgoing epsilon edge\n\t\t\tif ( returnState.getNumberOfTransitions()!=1 ||\n\t\t\t\t !returnState.transition(0).isEpsilon() )\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t// Look for prefix op case like 'not expr', (' type ')' expr\n\t\t\tATNState returnStateTarget = returnState.transition(0).target;\n\t\t\tif ( returnState.getStateType()==BLOCK_END && returnStateTarget==p ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Look for 'expr op expr' or case where expr's return state is block end\n\t\t\t// of (...)* internal block; the block end points to loop back\n\t\t\t// which points to p but we don't need to check that\n\t\t\tif ( returnState==blockEndState ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Look for ternary expr ? expr : expr. The return state points at block end,\n\t\t\t// which points at loop entry state\n\t\t\tif ( returnStateTarget==blockEndState ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Look for complex prefix 'between expr and expr' case where 2nd expr's\n\t\t\t// return state points at block end state of (...)* internal block\n\t\t\tif ( returnStateTarget.getStateType() == BLOCK_END &&\n\t\t\t\t returnStateTarget.getNumberOfTransitions()==1 &&\n\t\t\t\t returnStateTarget.transition(0).isEpsilon() &&\n\t\t\t\t returnStateTarget.transition(0).target == p )\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// anything else ain't conforming\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\tpublic String getRuleName(int index) {\n\t\tif ( parser!=null && index>=0 ) return parser.getRuleNames()[index];\n\t\treturn \"<rule \"+index+\">\";\n\t}\n\n\n\tprotected ATNConfig getEpsilonTarget(ATNConfig config,\n\t\t\t\t\t\t\t\t\t  Transition t,\n\t\t\t\t\t\t\t\t\t  boolean collectPredicates,\n\t\t\t\t\t\t\t\t\t  boolean inContext,\n\t\t\t\t\t\t\t\t\t  boolean fullCtx,\n\t\t\t\t\t\t\t\t\t  boolean treatEofAsEpsilon)\n\t{\n\t\tswitch (t.getSerializationType()) {\n\t\tcase Transition.RULE:\n\t\t\treturn ruleTransition(config, (RuleTransition)t);\n\n\t\tcase Transition.PRECEDENCE:\n\t\t\treturn precedenceTransition(config, (PrecedencePredicateTransition)t, collectPredicates, inContext, fullCtx);\n\n\t\tcase Transition.PREDICATE:\n\t\t\treturn predTransition(config, (PredicateTransition)t,\n\t\t\t\t\t\t\t\t  collectPredicates,\n\t\t\t\t\t\t\t\t  inContext,\n\t\t\t\t\t\t\t\t  fullCtx);\n\n\t\tcase Transition.ACTION:\n\t\t\treturn actionTransition(config, (ActionTransition)t);\n\n\t\tcase Transition.EPSILON:\n\t\t\treturn new ATNConfig(config, t.target);\n\n\t\tcase Transition.ATOM:\n\t\tcase Transition.RANGE:\n\t\tcase Transition.SET:\n\t\t\t// EOF transitions act like epsilon transitions after the first EOF\n\t\t\t// transition is traversed\n\t\t\tif (treatEofAsEpsilon) {\n\t\t\t\tif (t.matches(Token.EOF, 0, 1)) {\n\t\t\t\t\treturn new ATNConfig(config, t.target);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn null;\n\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}\n\n\n\tprotected ATNConfig actionTransition(ATNConfig config, ActionTransition t) {\n\t\tif ( debug ) System.out.println(\"ACTION edge \"+t.ruleIndex+\":\"+t.actionIndex);\n\t\treturn new ATNConfig(config, t.target);\n\t}\n\n\n\tpublic ATNConfig precedenceTransition(ATNConfig config,\n\t\t\t\t\t\t\t\t\tPrecedencePredicateTransition pt,\n\t\t\t\t\t\t\t\t\tboolean collectPredicates,\n\t\t\t\t\t\t\t\t\tboolean inContext,\n\t\t\t\t\t\t\t\t\tboolean fullCtx)\n\t{\n\t\tif ( debug ) {\n\t\t\tSystem.out.println(\"PRED (collectPredicates=\"+collectPredicates+\") \"+\n                    pt.precedence+\">=_p\"+\n\t\t\t\t\t\", ctx dependent=true\");\n\t\t\tif ( parser != null ) {\n                System.out.println(\"context surrounding pred is \"+\n                                   parser.getRuleInvocationStack());\n            }\n\t\t}\n\n        ATNConfig c = null;\n        if (collectPredicates && inContext) {\n\t\t\tif ( fullCtx ) {\n\t\t\t\t// In full context mode, we can evaluate predicates on-the-fly\n\t\t\t\t// during closure, which dramatically reduces the size of\n\t\t\t\t// the config sets. It also obviates the need to test predicates\n\t\t\t\t// later during conflict resolution.\n\t\t\t\tint currentPosition = _input.index();\n\t\t\t\t_input.seek(_startIndex);\n\t\t\t\tboolean predSucceeds = evalSemanticContext(pt.getPredicate(), _outerContext, config.alt, fullCtx);\n\t\t\t\t_input.seek(currentPosition);\n\t\t\t\tif ( predSucceeds ) {\n\t\t\t\t\tc = new ATNConfig(config, pt.target); // no pred context\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSemanticContext newSemCtx =\n\t\t\t\t\tSemanticContext.and(config.semanticContext, pt.getPredicate());\n\t\t\t\tc = new ATNConfig(config, pt.target, newSemCtx);\n\t\t\t}\n        }\n\t\telse {\n\t\t\tc = new ATNConfig(config, pt.target);\n\t\t}\n\n\t\tif ( debug ) System.out.println(\"config from pred transition=\"+c);\n        return c;\n\t}\n\n\n\tprotected ATNConfig predTransition(ATNConfig config,\n\t\t\t\t\t\t\t\t\tPredicateTransition pt,\n\t\t\t\t\t\t\t\t\tboolean collectPredicates,\n\t\t\t\t\t\t\t\t\tboolean inContext,\n\t\t\t\t\t\t\t\t\tboolean fullCtx)\n\t{\n\t\tif ( debug ) {\n\t\t\tSystem.out.println(\"PRED (collectPredicates=\"+collectPredicates+\") \"+\n                    pt.ruleIndex+\":\"+pt.predIndex+\n\t\t\t\t\t\", ctx dependent=\"+pt.isCtxDependent);\n\t\t\tif ( parser != null ) {\n                System.out.println(\"context surrounding pred is \"+\n                                   parser.getRuleInvocationStack());\n            }\n\t\t}\n\n\t\tATNConfig c = null;\n\t\tif ( collectPredicates &&\n\t\t\t (!pt.isCtxDependent || (pt.isCtxDependent&&inContext)) )\n\t\t{\n\t\t\tif ( fullCtx ) {\n\t\t\t\t// In full context mode, we can evaluate predicates on-the-fly\n\t\t\t\t// during closure, which dramatically reduces the size of\n\t\t\t\t// the config sets. It also obviates the need to test predicates\n\t\t\t\t// later during conflict resolution.\n\t\t\t\tint currentPosition = _input.index();\n\t\t\t\t_input.seek(_startIndex);\n\t\t\t\tboolean predSucceeds = evalSemanticContext(pt.getPredicate(), _outerContext, config.alt, fullCtx);\n\t\t\t\t_input.seek(currentPosition);\n\t\t\t\tif ( predSucceeds ) {\n\t\t\t\t\tc = new ATNConfig(config, pt.target); // no pred context\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSemanticContext newSemCtx =\n\t\t\t\t\tSemanticContext.and(config.semanticContext, pt.getPredicate());\n\t\t\t\tc = new ATNConfig(config, pt.target, newSemCtx);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tc = new ATNConfig(config, pt.target);\n\t\t}\n\n\t\tif ( debug ) System.out.println(\"config from pred transition=\"+c);\n        return c;\n\t}\n\n\n\tprotected ATNConfig ruleTransition(ATNConfig config, RuleTransition t) {\n\t\tif ( debug ) {\n\t\t\tSystem.out.println(\"CALL rule \"+getRuleName(t.target.ruleIndex)+\n\t\t\t\t\t\t\t   \", ctx=\"+config.context);\n\t\t}\n\n\t\tATNState returnState = t.followState;\n\t\tPredictionContext newContext =\n\t\t\tSingletonPredictionContext.create(config.context, returnState.stateNumber);\n\t\treturn new ATNConfig(config, t.target, newContext);\n\t}\n\n\t/**\n\t * Gets a {@link BitSet} containing the alternatives in {@code configs}\n\t * which are part of one or more conflicting alternative subsets.\n\t *\n\t * @param configs The {@link ATNConfigSet} to analyze.\n\t * @return The alternatives in {@code configs} which are part of one or more\n\t * conflicting alternative subsets. If {@code configs} does not contain any\n\t * conflicting subsets, this method returns an empty {@link BitSet}.\n\t */\n\tprotected BitSet getConflictingAlts(ATNConfigSet configs) {\n\t\tCollection<BitSet> altsets = PredictionMode.getConflictingAltSubsets(configs);\n\t\treturn PredictionMode.getAlts(altsets);\n\t}\n\n\t/**\n\t Sam pointed out a problem with the previous definition, v3, of\n\t ambiguous states. If we have another state associated with conflicting\n\t alternatives, we should keep going. For example, the following grammar\n\n\t s : (ID | ID ID?) ';' ;\n\n\t When the ATN simulation reaches the state before ';', it has a DFA\n\t state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally\n\t 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node\n\t because alternative to has another way to continue, via [6|2|[]].\n\t The key is that we have a single state that has config's only associated\n\t with a single alternative, 2, and crucially the state transitions\n\t among the configurations are all non-epsilon transitions. That means\n\t we don't consider any conflicts that include alternative 2. So, we\n\t ignore the conflict between alts 1 and 2. We ignore a set of\n\t conflicting alts when there is an intersection with an alternative\n\t associated with a single alt state in the state&rarr;config-list map.\n\n\t It's also the case that we might have two conflicting configurations but\n\t also a 3rd nonconflicting configuration for a different alternative:\n\t [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:\n\n\t a : A | A | A B ;\n\n\t After matching input A, we reach the stop state for rule A, state 1.\n\t State 8 is the state right before B. Clearly alternatives 1 and 2\n\t conflict and no amount of further lookahead will separate the two.\n\t However, alternative 3 will be able to continue and so we do not\n\t stop working on this state. In the previous example, we're concerned\n\t with states associated with the conflicting alternatives. Here alt\n\t 3 is not associated with the conflicting configs, but since we can continue\n\t looking for input reasonably, I don't declare the state done. We\n\t ignore a set of conflicting alts when we have an alternative\n\t that we still need to pursue.\n\t */\n\tprotected BitSet getConflictingAltsOrUniqueAlt(ATNConfigSet configs) {\n\t\tBitSet conflictingAlts;\n\t\tif ( configs.uniqueAlt!= ATN.INVALID_ALT_NUMBER ) {\n\t\t\tconflictingAlts = new BitSet();\n\t\t\tconflictingAlts.set(configs.uniqueAlt);\n\t\t}\n\t\telse {\n\t\t\tconflictingAlts = configs.conflictingAlts;\n\t\t}\n\t\treturn conflictingAlts;\n\t}\n\n\n\tpublic String getTokenName(int t) {\n\t\tif (t == Token.EOF) {\n\t\t\treturn \"EOF\";\n\t\t}\n\n\t\tVocabulary vocabulary = parser != null ? parser.getVocabulary() : VocabularyImpl.EMPTY_VOCABULARY;\n\t\tString displayName = vocabulary.getDisplayName(t);\n\t\tif (displayName.equals(Integer.toString(t))) {\n\t\t\treturn displayName;\n\t\t}\n\n\t\treturn displayName + \"<\" + t + \">\";\n\t}\n\n\tpublic String getLookaheadName(TokenStream input) {\n\t\treturn getTokenName(input.LA(1));\n\t}\n\n\t/** Used for debugging in adaptivePredict around execATN but I cut\n\t *  it out for clarity now that alg. works well. We can leave this\n\t *  \"dead\" code for a bit.\n\t */\n\tpublic void dumpDeadEndConfigs(NoViableAltException nvae) {\n\t\tSystem.err.println(\"dead end configs: \");\n\t\tfor (ATNConfig c : nvae.getDeadEndConfigs()) {\n\t\t\tString trans = \"no edges\";\n\t\t\tif ( c.state.getNumberOfTransitions()>0 ) {\n\t\t\t\tTransition t = c.state.transition(0);\n\t\t\t\tif ( t instanceof AtomTransition) {\n\t\t\t\t\tAtomTransition at = (AtomTransition)t;\n\t\t\t\t\ttrans = \"Atom \"+getTokenName(at.label);\n\t\t\t\t}\n\t\t\t\telse if ( t instanceof SetTransition ) {\n\t\t\t\t\tSetTransition st = (SetTransition)t;\n\t\t\t\t\tboolean not = st instanceof NotSetTransition;\n\t\t\t\t\ttrans = (not?\"~\":\"\")+\"Set \"+st.set.toString();\n\t\t\t\t}\n\t\t\t}\n\t\t\tSystem.err.println(c.toString(parser, true)+\":\"+trans);\n\t\t}\n\t}\n\n\n\tprotected NoViableAltException noViableAlt(TokenStream input,\n\t\t\t\t\t\t\t\t\t\t\tParserRuleContext outerContext,\n\t\t\t\t\t\t\t\t\t\t\tATNConfigSet configs,\n\t\t\t\t\t\t\t\t\t\t\tint startIndex)\n\t{\n\t\treturn new NoViableAltException(parser, input,\n\t\t\t\t\t\t\t\t\t\t\tinput.get(startIndex),\n\t\t\t\t\t\t\t\t\t\t\tinput.LT(1),\n\t\t\t\t\t\t\t\t\t\t\tconfigs, outerContext);\n\t}\n\n\tprotected static int getUniqueAlt(ATNConfigSet configs) {\n\t\tint alt = ATN.INVALID_ALT_NUMBER;\n\t\tfor (ATNConfig c : configs) {\n\t\t\tif ( alt == ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\talt = c.alt; // found first alt\n\t\t\t}\n\t\t\telse if ( c.alt!=alt ) {\n\t\t\t\treturn ATN.INVALID_ALT_NUMBER;\n\t\t\t}\n\t\t}\n\t\treturn alt;\n\t}\n\n\t/**\n\t * Add an edge to the DFA, if possible. This method calls\n\t * {@link #addDFAState} to ensure the {@code to} state is present in the\n\t * DFA. If {@code from} is {@code null}, or if {@code t} is outside the\n\t * range of edges that can be represented in the DFA tables, this method\n\t * returns without adding the edge to the DFA.\n\t *\n\t * <p>If {@code to} is {@code null}, this method returns {@code null}.\n\t * Otherwise, this method returns the {@link DFAState} returned by calling\n\t * {@link #addDFAState} for the {@code to} state.</p>\n\t *\n\t * @param dfa The DFA\n\t * @param from The source state for the edge\n\t * @param t The input symbol\n\t * @param to The target state for the edge\n\t *\n\t * @return If {@code to} is {@code null}, this method returns {@code null};\n\t * otherwise this method returns the result of calling {@link #addDFAState}\n\t * on {@code to}\n\t */\n\tprotected DFAState addDFAEdge(DFA dfa,\n\t\t\t\t\t\t\t\t  DFAState from,\n\t\t\t\t\t\t\t\t  int t,\n\t\t\t\t\t\t\t\t  DFAState to)\n\t{\n\t\tif ( debug ) {\n\t\t\tSystem.out.println(\"EDGE \"+from+\" -> \"+to+\" upon \"+getTokenName(t));\n\t\t}\n\n\t\tif (to == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tto = addDFAState(dfa, to); // used existing if possible not incoming\n\t\tif (from == null || t < -1 || t > atn.maxTokenType) {\n\t\t\treturn to;\n\t\t}\n\n\t\tsynchronized (from) {\n\t\t\tif ( from.edges==null ) {\n\t\t\t\tfrom.edges = new DFAState[atn.maxTokenType+1+1];\n\t\t\t}\n\n\t\t\tfrom.edges[t+1] = to; // connect\n\t\t}\n\n\t\tif ( debug ) {\n\t\t\tSystem.out.println(\"DFA=\\n\"+dfa.toString(parser!=null?parser.getVocabulary():VocabularyImpl.EMPTY_VOCABULARY));\n\t\t}\n\n\t\treturn to;\n\t}\n\n\t/**\n\t * Add state {@code D} to the DFA if it is not already present, and return\n\t * the actual instance stored in the DFA. If a state equivalent to {@code D}\n\t * is already in the DFA, the existing state is returned. Otherwise this\n\t * method returns {@code D} after adding it to the DFA.\n\t *\n\t * <p>If {@code D} is {@link #ERROR}, this method returns {@link #ERROR} and\n\t * does not change the DFA.</p>\n\t *\n\t * @param dfa The dfa\n\t * @param D The DFA state to add\n\t * @return The state stored in the DFA. This will be either the existing\n\t * state if {@code D} is already in the DFA, or {@code D} itself if the\n\t * state was not already present.\n\t */\n\tprotected DFAState addDFAState(DFA dfa, DFAState D) {\n\t\tif (D == ERROR) {\n\t\t\treturn D;\n\t\t}\n\n\t\tsynchronized (dfa.states) {\n\t\t\tDFAState existing = dfa.states.get(D);\n\n\t\t\tif ( existing!=null ) {\n\t\t\t\tif ( trace_atn_sim ) System.out.println(\"addDFAState \" + D + \" exists\");\n\t\t\t\treturn existing;\n\t\t\t}\n\n\t\t\tD.stateNumber = dfa.states.size();\n\n\t\t\tif (!D.configs.isReadonly()) {\n\t\t\t\tD.configs.optimizeConfigs(this);\n\t\t\t\tD.configs.setReadonly(true);\n\t\t\t}\n\n\t\t\tif ( trace_atn_sim ) System.out.println(\"addDFAState new \"+D);\n\n\t\t\tdfa.states.put(D, D);\n\t\t\treturn D;\n\t\t}\n\t}\n\n\tprotected void reportAttemptingFullContext(DFA dfa, BitSet conflictingAlts, ATNConfigSet configs, int startIndex, int stopIndex) {\n        if ( debug || retry_debug ) {\n\t\t\tInterval interval = Interval.of(startIndex, stopIndex);\n\t\t\tSystem.out.println(\"reportAttemptingFullContext decision=\"+dfa.decision+\":\"+configs+\n                               \", input=\"+parser.getTokenStream().getText(interval));\n        }\n        if ( parser!=null ) parser.getErrorListenerDispatch().reportAttemptingFullContext(parser, dfa, startIndex, stopIndex, conflictingAlts, configs);\n    }\n\n\tprotected void reportContextSensitivity(DFA dfa, int prediction, ATNConfigSet configs, int startIndex, int stopIndex) {\n        if ( debug || retry_debug ) {\n\t\t\tInterval interval = Interval.of(startIndex, stopIndex);\n            System.out.println(\"reportContextSensitivity decision=\"+dfa.decision+\":\"+configs+\n                               \", input=\"+parser.getTokenStream().getText(interval));\n        }\n        if ( parser!=null ) parser.getErrorListenerDispatch().reportContextSensitivity(parser, dfa, startIndex, stopIndex, prediction, configs);\n    }\n\n    /** If context sensitive parsing, we know it's ambiguity not conflict */\n    protected void reportAmbiguity(DFA dfa,\n\t\t\t\t\t\t\t\t   DFAState D, // the DFA state from execATN() that had SLL conflicts\n\t\t\t\t\t\t\t\t   int startIndex, int stopIndex,\n\t\t\t\t\t\t\t\t   boolean exact,\n\t\t\t\t\t\t\t\t   BitSet ambigAlts,\n\t\t\t\t\t\t\t\t   ATNConfigSet configs) // configs that LL not SLL considered conflicting\n\t{\n\t\tif ( debug || retry_debug ) {\n\t\t\tInterval interval = Interval.of(startIndex, stopIndex);\n\t\t\tSystem.out.println(\"reportAmbiguity \"+\n\t\t\t\t\t\t\t   ambigAlts+\":\"+configs+\n                               \", input=\"+parser.getTokenStream().getText(interval));\n        }\n        if ( parser!=null ) parser.getErrorListenerDispatch().reportAmbiguity(parser, dfa, startIndex, stopIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  exact, ambigAlts, configs);\n    }\n\n\tpublic final void setPredictionMode(PredictionMode mode) {\n\t\tthis.mode = mode;\n\t}\n\n\n\tpublic final PredictionMode getPredictionMode() {\n\t\treturn mode;\n\t}\n\n\t/**\n\t * @since 4.3\n\t */\n\tpublic Parser getParser() {\n\t\treturn parser;\n\t}\n\n\tpublic static String getSafeEnv(String envName) {\n\t\ttry {\n\t\t\treturn AccessController.doPrivileged(new PrivilegedAction<String>() {\n\t\t\t\t@Override\n\t\t\t\tpublic String run() {\n\t\t\t\t\treturn System.getenv(envName);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (SecurityException e) { }\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PlusBlockStartState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** Start of {@code (A|B|...)+} loop. Technically a decision state, but\n *  we don't use for code generation; somebody might need it, so I'm defining\n *  it for completeness. In reality, the {@link PlusLoopbackState} node is the\n *  real decision-making note for {@code A+}.\n */\npublic final class PlusBlockStartState extends BlockStartState {\n\tpublic PlusLoopbackState loopBackState;\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn PLUS_BLOCK_START;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PlusLoopbackState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** Decision state for {@code A+} and {@code (A|B)+}.  It has two transitions:\n *  one to the loop back to start of the block and one to exit.\n */\npublic final class PlusLoopbackState extends DecisionState {\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn PLUS_LOOP_BACK;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PrecedencePredicateTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/**\n *\n * @author Sam Harwell\n */\npublic final class PrecedencePredicateTransition extends AbstractPredicateTransition {\n\tpublic final int precedence;\n\n\tpublic PrecedencePredicateTransition(ATNState target, int precedence) {\n\t\tsuper(target);\n\t\tthis.precedence = precedence;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn PRECEDENCE;\n\t}\n\n\t@Override\n\tpublic boolean isEpsilon() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn false;\n\t}\n\n\tpublic SemanticContext.PrecedencePredicate getPredicate() {\n\t\treturn new SemanticContext.PrecedencePredicate(precedence);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn precedence + \" >= _p\";\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PredicateEvalInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.Recognizer;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.TokenStream;\n\n/**\n * This class represents profiling event information for semantic predicate\n * evaluations which occur during prediction.\n *\n * @see ParserATNSimulator#evalSemanticContext\n *\n * @since 4.3\n */\npublic class PredicateEvalInfo extends DecisionEventInfo {\n\t/**\n\t * The semantic context which was evaluated.\n\t */\n\tpublic final SemanticContext semctx;\n\t/**\n\t * The alternative number for the decision which is guarded by the semantic\n\t * context {@link #semctx}. Note that other ATN\n\t * configurations may predict the same alternative which are guarded by\n\t * other semantic contexts and/or {@link SemanticContext#NONE}.\n\t */\n\tpublic final int predictedAlt;\n\t/**\n\t * The result of evaluating the semantic context {@link #semctx}.\n\t */\n\tpublic final boolean evalResult;\n\n\t/**\n\t * Constructs a new instance of the {@link PredicateEvalInfo} class with the\n\t * specified detailed predicate evaluation information.\n\t *\n\t * @param decision The decision number\n\t * @param input The input token stream\n\t * @param startIndex The start index for the current prediction\n\t * @param stopIndex The index at which the predicate evaluation was\n\t * triggered. Note that the input stream may be reset to other positions for\n\t * the actual evaluation of individual predicates.\n\t * @param semctx The semantic context which was evaluated\n\t * @param evalResult The results of evaluating the semantic context\n\t * @param predictedAlt The alternative number for the decision which is\n\t * guarded by the semantic context {@code semctx}. See {@link #predictedAlt}\n\t * for more information.\n\t * @param fullCtx {@code true} if the semantic context was\n\t * evaluated during LL prediction; otherwise, {@code false} if the semantic\n\t * context was evaluated during SLL prediction\n\t *\n\t * @see ParserATNSimulator#evalSemanticContext(SemanticContext, ParserRuleContext, int, boolean)\n\t * @see SemanticContext#eval(Recognizer, RuleContext)\n\t */\n\tpublic PredicateEvalInfo(int decision,\n\t\t\t\t\t\t\t TokenStream input, int startIndex, int stopIndex,\n\t\t\t\t\t\t\t SemanticContext semctx,\n\t\t\t\t\t\t\t boolean evalResult,\n\t\t\t\t\t\t\t int predictedAlt,\n\t\t\t\t\t\t\t boolean fullCtx)\n\t{\n\t\tsuper(decision, new ATNConfigSet(), input, startIndex, stopIndex, fullCtx);\n\t\tthis.semctx = semctx;\n\t\tthis.evalResult = evalResult;\n\t\tthis.predictedAlt = predictedAlt;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PredicateTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** TODO: this is old comment:\n *  A tree of semantic predicates from the grammar AST if label==SEMPRED.\n *  In the ATN, labels will always be exactly one predicate, but the DFA\n *  may have to combine a bunch of them as it collects predicates from\n *  multiple ATN configurations into a single DFA state.\n */\npublic final class PredicateTransition extends AbstractPredicateTransition {\n\tpublic final int ruleIndex;\n\tpublic final int predIndex;\n\tpublic final boolean isCtxDependent;  // e.g., $i ref in pred\n\n\tpublic PredicateTransition(ATNState target, int ruleIndex, int predIndex, boolean isCtxDependent) {\n\t\tsuper(target);\n\t\tthis.ruleIndex = ruleIndex;\n\t\tthis.predIndex = predIndex;\n\t\tthis.isCtxDependent = isCtxDependent;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn PREDICATE;\n\t}\n\n\t@Override\n\tpublic boolean isEpsilon() { return true; }\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn false;\n\t}\n\n    public SemanticContext.Predicate getPredicate() {\n   \t\treturn new SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent);\n   \t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"pred_\"+ruleIndex+\":\"+predIndex;\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PredictionContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.Recognizer;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.misc.DoubleKeyMap;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\nimport java.util.*;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic abstract class PredictionContext {\n\t/**\n\t * Represents {@code $} in an array in full context mode, when {@code $}\n\t * doesn't mean wildcard: {@code $ + x = [$,x]}. Here,\n\t * {@code $} = {@link #EMPTY_RETURN_STATE}.\n\t */\n\tpublic static final int EMPTY_RETURN_STATE = Integer.MAX_VALUE;\n\n\tprivate static final int INITIAL_HASH = 1;\n\n\tprivate static final AtomicInteger globalNodeCount = new AtomicInteger();\n\tpublic final int id = globalNodeCount.getAndIncrement();\n\n\t/**\n\t * Stores the computed hash code of this {@link PredictionContext}. The hash\n\t * code is computed in parts to match the following reference algorithm.\n\t *\n\t * <pre>\n\t *  private int referenceHashCode() {\n\t *      int hash = {@link MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH});\n\t *\n\t *      for (int i = 0; i &lt; {@link #size()}; i++) {\n\t *          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i));\n\t *      }\n\t *\n\t *      for (int i = 0; i &lt; {@link #size()}; i++) {\n\t *          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getReturnState getReturnState}(i));\n\t *      }\n\t *\n\t *      hash = {@link MurmurHash#finish MurmurHash.finish}(hash, 2 * {@link #size()});\n\t *      return hash;\n\t *  }\n\t * </pre>\n\t */\n\tpublic final int cachedHashCode;\n\n\tprotected PredictionContext(int cachedHashCode) {\n\t\tthis.cachedHashCode = cachedHashCode;\n\t}\n\n\t/** Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.\n\t *  Return {@link EmptyPredictionContext#Instance} if {@code outerContext} is empty or null.\n\t */\n\tpublic static PredictionContext fromRuleContext(ATN atn, RuleContext outerContext) {\n\t\tif ( outerContext==null ) outerContext = ParserRuleContext.EMPTY;\n\n\t\t// if we are in RuleContext of start rule, s, then PredictionContext\n\t\t// is EMPTY. Nobody called us. (if we are empty, return empty)\n\t\tif ( outerContext.parent==null || outerContext==ParserRuleContext.EMPTY ) {\n\t\t\treturn EmptyPredictionContext.Instance;\n\t\t}\n\n\t\t// If we have a parent, convert it to a PredictionContext graph\n\t\tPredictionContext parent = EmptyPredictionContext.Instance;\n\t\tparent = PredictionContext.fromRuleContext(atn, outerContext.parent);\n\n\t\tATNState state = atn.states.get(outerContext.invokingState);\n\t\tRuleTransition transition = (RuleTransition)state.transition(0);\n\t\treturn SingletonPredictionContext.create(parent, transition.followState.stateNumber);\n\t}\n\n\tpublic abstract int size();\n\n\tpublic abstract PredictionContext getParent(int index);\n\n\tpublic abstract int getReturnState(int index);\n\n\t/** This means only the {@link EmptyPredictionContext#Instance} (wildcard? not sure) context is in set. */\n\tpublic boolean isEmpty() {\n\t\treturn this == EmptyPredictionContext.Instance;\n\t}\n\n\tpublic boolean hasEmptyPath() {\n\t\t// since EMPTY_RETURN_STATE can only appear in the last position, we check last one\n\t\treturn getReturnState(size() - 1) == EMPTY_RETURN_STATE;\n\t}\n\n\t@Override\n\tpublic final int hashCode() {\n\t\treturn cachedHashCode;\n\t}\n\n\t@Override\n\tpublic abstract boolean equals(Object obj);\n\n\tprotected static int calculateEmptyHashCode() {\n\t\tint hash = MurmurHash.initialize(INITIAL_HASH);\n\t\thash = MurmurHash.finish(hash, 0);\n\t\treturn hash;\n\t}\n\n\tprotected static int calculateHashCode(PredictionContext parent, int returnState) {\n\t\tint hash = MurmurHash.initialize(INITIAL_HASH);\n\t\thash = MurmurHash.update(hash, parent);\n\t\thash = MurmurHash.update(hash, returnState);\n\t\thash = MurmurHash.finish(hash, 2);\n\t\treturn hash;\n\t}\n\n\tprotected static int calculateHashCode(PredictionContext[] parents, int[] returnStates) {\n\t\tint hash = MurmurHash.initialize(INITIAL_HASH);\n\n\t\tfor (PredictionContext parent : parents) {\n\t\t\thash = MurmurHash.update(hash, parent);\n\t\t}\n\n\t\tfor (int returnState : returnStates) {\n\t\t\thash = MurmurHash.update(hash, returnState);\n\t\t}\n\n\t\thash = MurmurHash.finish(hash, 2 * parents.length);\n\t\treturn hash;\n\t}\n\n\t// dispatch\n\tpublic static PredictionContext merge(\n\t\tPredictionContext a, PredictionContext b,\n\t\tboolean rootIsWildcard,\n\t\tDoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)\n\t{\n\t\tassert a!=null && b!=null; // must be empty context, never null\n\n\t\t// share same graph if both same\n\t\tif ( a==b || a.equals(b) ) return a;\n\n\t\tif ( a instanceof SingletonPredictionContext && b instanceof SingletonPredictionContext) {\n\t\t\treturn mergeSingletons((SingletonPredictionContext)a,\n\t\t\t\t\t\t\t\t   (SingletonPredictionContext)b,\n\t\t\t\t\t\t\t\t   rootIsWildcard, mergeCache);\n\t\t}\n\n\t\t// At least one of a or b is array\n\t\t// If one is $ and rootIsWildcard, return $ as * wildcard\n\t\tif ( rootIsWildcard ) {\n\t\t\tif ( a instanceof EmptyPredictionContext ) return a;\n\t\t\tif ( b instanceof EmptyPredictionContext ) return b;\n\t\t}\n\n\t\t// convert singleton so both are arrays to normalize\n\t\tif ( a instanceof SingletonPredictionContext ) {\n\t\t\ta = new ArrayPredictionContext((SingletonPredictionContext)a);\n\t\t}\n\t\tif ( b instanceof SingletonPredictionContext) {\n\t\t\tb = new ArrayPredictionContext((SingletonPredictionContext)b);\n\t\t}\n\t\treturn mergeArrays((ArrayPredictionContext) a, (ArrayPredictionContext) b,\n\t\t\t\t\t\t   rootIsWildcard, mergeCache);\n\t}\n\n\t/**\n\t * Merge two {@link SingletonPredictionContext} instances.\n\t *\n\t * <p>Stack tops equal, parents merge is same; return left graph.<br>\n\t * <embed src=\"images/SingletonMerge_SameRootSamePar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Same stack top, parents differ; merge parents giving array node, then\n\t * remainders of those graphs. A new root node is created to point to the\n\t * merged parents.<br>\n\t * <embed src=\"images/SingletonMerge_SameRootDiffPar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Different stack tops pointing to same parent. Make array node for the\n\t * root where both element in the root point to the same (original)\n\t * parent.<br>\n\t * <embed src=\"images/SingletonMerge_DiffRootSamePar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Different stack tops pointing to different parents. Make array node for\n\t * the root where each element points to the corresponding original\n\t * parent.<br>\n\t * <embed src=\"images/SingletonMerge_DiffRootDiffPar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * @param a the first {@link SingletonPredictionContext}\n\t * @param b the second {@link SingletonPredictionContext}\n\t * @param rootIsWildcard {@code true} if this is a local-context merge,\n\t * otherwise false to indicate a full-context merge\n\t * @param mergeCache\n\t */\n\tpublic static PredictionContext mergeSingletons(\n\t\tSingletonPredictionContext a,\n\t\tSingletonPredictionContext b,\n\t\tboolean rootIsWildcard,\n\t\tDoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)\n\t{\n\t\tif ( mergeCache!=null ) {\n\t\t\tPredictionContext previous = mergeCache.get(a,b);\n\t\t\tif ( previous!=null ) return previous;\n\t\t\tprevious = mergeCache.get(b,a);\n\t\t\tif ( previous!=null ) return previous;\n\t\t}\n\n\t\tPredictionContext rootMerge = mergeRoot(a, b, rootIsWildcard);\n\t\tif ( rootMerge!=null ) {\n\t\t\tif ( mergeCache!=null ) mergeCache.put(a, b, rootMerge);\n\t\t\treturn rootMerge;\n\t\t}\n\n\t\tif ( a.returnState==b.returnState ) { // a == b\n\t\t\tPredictionContext parent = merge(a.parent, b.parent, rootIsWildcard, mergeCache);\n\t\t\t// if parent is same as existing a or b parent or reduced to a parent, return it\n\t\t\tif ( parent == a.parent ) return a; // ax + bx = ax, if a=b\n\t\t\tif ( parent == b.parent ) return b; // ax + bx = bx, if a=b\n\t\t\t// else: ax + ay = a'[x,y]\n\t\t\t// merge parents x and y, giving array node with x,y then remainders\n\t\t\t// of those graphs.  dup a, a' points at merged array\n\t\t\t// new joined parent so create new singleton pointing to it, a'\n\t\t\tPredictionContext a_ = SingletonPredictionContext.create(parent, a.returnState);\n\t\t\tif ( mergeCache!=null ) mergeCache.put(a, b, a_);\n\t\t\treturn a_;\n\t\t}\n\t\telse { // a != b payloads differ\n\t\t\t// see if we can collapse parents due to $+x parents if local ctx\n\t\t\tPredictionContext singleParent = null;\n\t\t\tif ( a==b || (a.parent!=null && a.parent.equals(b.parent)) ) { // ax + bx = [a,b]x\n\t\t\t\tsingleParent = a.parent;\n\t\t\t}\n\t\t\tif ( singleParent!=null ) {\t// parents are same\n\t\t\t\t// sort payloads and use same parent\n\t\t\t\tint[] payloads = {a.returnState, b.returnState};\n\t\t\t\tif ( a.returnState > b.returnState ) {\n\t\t\t\t\tpayloads[0] = b.returnState;\n\t\t\t\t\tpayloads[1] = a.returnState;\n\t\t\t\t}\n\t\t\t\tPredictionContext[] parents = {singleParent, singleParent};\n\t\t\t\tPredictionContext a_ = new ArrayPredictionContext(parents, payloads);\n\t\t\t\tif ( mergeCache!=null ) mergeCache.put(a, b, a_);\n\t\t\t\treturn a_;\n\t\t\t}\n\t\t\t// parents differ and can't merge them. Just pack together\n\t\t\t// into array; can't merge.\n\t\t\t// ax + by = [ax,by]\n\t\t\tint[] payloads = {a.returnState, b.returnState};\n\t\t\tPredictionContext[] parents = {a.parent, b.parent};\n\t\t\tif ( a.returnState > b.returnState ) { // sort by payload\n\t\t\t\tpayloads[0] = b.returnState;\n\t\t\t\tpayloads[1] = a.returnState;\n\t\t\t\tparents = new PredictionContext[] {b.parent, a.parent};\n\t\t\t}\n\t\t\tPredictionContext a_ = new ArrayPredictionContext(parents, payloads);\n\t\t\tif ( mergeCache!=null ) mergeCache.put(a, b, a_);\n\t\t\treturn a_;\n\t\t}\n\t}\n\n\t/**\n\t * Handle case where at least one of {@code a} or {@code b} is\n\t * {@link EmptyPredictionContext#Instance}. In the following diagrams, the symbol {@code $} is used\n\t * to represent {@link EmptyPredictionContext#Instance}.\n\t *\n\t * <h2>Local-Context Merges</h2>\n\t *\n\t * <p>These local-context merge operations are used when {@code rootIsWildcard}\n\t * is true.</p>\n\t *\n\t * <p>{@link EmptyPredictionContext#Instance} is superset of any graph; return {@link EmptyPredictionContext#Instance}.<br>\n\t * <embed src=\"images/LocalMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>{@link EmptyPredictionContext#Instance} and anything is {@code #EMPTY}, so merged parent is\n\t * {@code #EMPTY}; return left graph.<br>\n\t * <embed src=\"images/LocalMerge_EmptyParent.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Special case of last merge if local context.<br>\n\t * <embed src=\"images/LocalMerge_DiffRoots.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <h2>Full-Context Merges</h2>\n\t *\n\t * <p>These full-context merge operations are used when {@code rootIsWildcard}\n\t * is false.</p>\n\t *\n\t * <p><embed src=\"images/FullMerge_EmptyRoots.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Must keep all contexts; {@link EmptyPredictionContext#Instance} in array is a special value (and\n\t * null parent).<br>\n\t * <embed src=\"images/FullMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p><embed src=\"images/FullMerge_SameRoot.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * @param a the first {@link SingletonPredictionContext}\n\t * @param b the second {@link SingletonPredictionContext}\n\t * @param rootIsWildcard {@code true} if this is a local-context merge,\n\t * otherwise false to indicate a full-context merge\n\t */\n\tpublic static PredictionContext mergeRoot(SingletonPredictionContext a,\n\t\t\t\t\t\t\t\t\t\t\t  SingletonPredictionContext b,\n\t\t\t\t\t\t\t\t\t\t\t  boolean rootIsWildcard)\n\t{\n\t\tif ( rootIsWildcard ) {\n\t\t\tif ( a == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance;  // * + b = *\n\t\t\tif ( b == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance;  // a + * = *\n\t\t}\n\t\telse {\n\t\t\tif ( a == EmptyPredictionContext.Instance && b == EmptyPredictionContext.Instance) return EmptyPredictionContext.Instance; // $ + $ = $\n\t\t\tif ( a == EmptyPredictionContext.Instance) { // $ + x = [x,$]\n\t\t\t\tint[] payloads = {b.returnState, EMPTY_RETURN_STATE};\n\t\t\t\tPredictionContext[] parents = {b.parent, null};\n\t\t\t\tPredictionContext joined =\n\t\t\t\t\tnew ArrayPredictionContext(parents, payloads);\n\t\t\t\treturn joined;\n\t\t\t}\n\t\t\tif ( b == EmptyPredictionContext.Instance) { // x + $ = [x,$] ($ is always last if present)\n\t\t\t\tint[] payloads = {a.returnState, EMPTY_RETURN_STATE};\n\t\t\t\tPredictionContext[] parents = {a.parent, null};\n\t\t\t\tPredictionContext joined =\n\t\t\t\t\tnew ArrayPredictionContext(parents, payloads);\n\t\t\t\treturn joined;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Merge two {@link ArrayPredictionContext} instances.\n\t *\n\t * <p>Different tops, different parents.<br>\n\t * <embed src=\"images/ArrayMerge_DiffTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Shared top, same parents.<br>\n\t * <embed src=\"images/ArrayMerge_ShareTopSamePar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Shared top, different parents.<br>\n\t * <embed src=\"images/ArrayMerge_ShareTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Shared top, all shared parents.<br>\n\t * <embed src=\"images/ArrayMerge_ShareTopSharePar.svg\" type=\"image/svg+xml\"/></p>\n\t *\n\t * <p>Equal tops, merge parents and reduce top to\n\t * {@link SingletonPredictionContext}.<br>\n\t * <embed src=\"images/ArrayMerge_EqualTop.svg\" type=\"image/svg+xml\"/></p>\n\t */\n\tpublic static PredictionContext mergeArrays(\n\t\tArrayPredictionContext a,\n\t\tArrayPredictionContext b,\n\t\tboolean rootIsWildcard,\n\t\tDoubleKeyMap<PredictionContext,PredictionContext,PredictionContext> mergeCache)\n\t{\n\t\tif ( mergeCache!=null ) {\n\t\t\tPredictionContext previous = mergeCache.get(a,b);\n\t\t\tif ( previous!=null ) {\n\t\t\t\tif ( ParserATNSimulator.trace_atn_sim ) System.out.println(\"mergeArrays a=\"+a+\",b=\"+b+\" -> previous\");\n\t\t\t\treturn previous;\n\t\t\t}\n\t\t\tprevious = mergeCache.get(b,a);\n\t\t\tif ( previous!=null ) {\n\t\t\t\tif ( ParserATNSimulator.trace_atn_sim ) System.out.println(\"mergeArrays a=\"+a+\",b=\"+b+\" -> previous\");\n\t\t\t\treturn previous;\n\t\t\t}\n\t\t}\n\n\t\t// merge sorted payloads a + b => M\n\t\tint i = 0; // walks a\n\t\tint j = 0; // walks b\n\t\tint k = 0; // walks target M array\n\n\t\tint[] mergedReturnStates =\n\t\t\tnew int[a.returnStates.length + b.returnStates.length];\n\t\tPredictionContext[] mergedParents =\n\t\t\tnew PredictionContext[a.returnStates.length + b.returnStates.length];\n\t\t// walk and merge to yield mergedParents, mergedReturnStates\n\t\twhile ( i<a.returnStates.length && j<b.returnStates.length ) {\n\t\t\tPredictionContext a_parent = a.parents[i];\n\t\t\tPredictionContext b_parent = b.parents[j];\n\t\t\tif ( a.returnStates[i]==b.returnStates[j] ) {\n\t\t\t\t// same payload (stack tops are equal), must yield merged singleton\n\t\t\t\tint payload = a.returnStates[i];\n\t\t\t\t// $+$ = $\n\t\t\t\tboolean both$ = payload == EMPTY_RETURN_STATE &&\n\t\t\t\t\t\t\t\ta_parent == null && b_parent == null;\n\t\t\t\tboolean ax_ax = (a_parent!=null && b_parent!=null) &&\n\t\t\t\t\t\t\t\ta_parent.equals(b_parent); // ax+ax -> ax\n\t\t\t\tif ( both$ || ax_ax ) {\n\t\t\t\t\tmergedParents[k] = a_parent; // choose left\n\t\t\t\t\tmergedReturnStates[k] = payload;\n\t\t\t\t}\n\t\t\t\telse { // ax+ay -> a'[x,y]\n\t\t\t\t\tPredictionContext mergedParent =\n\t\t\t\t\t\tmerge(a_parent, b_parent, rootIsWildcard, mergeCache);\n\t\t\t\t\tmergedParents[k] = mergedParent;\n\t\t\t\t\tmergedReturnStates[k] = payload;\n\t\t\t\t}\n\t\t\t\ti++; // hop over left one as usual\n\t\t\t\tj++; // but also skip one in right side since we merge\n\t\t\t}\n\t\t\telse if ( a.returnStates[i]<b.returnStates[j] ) { // copy a[i] to M\n\t\t\t\tmergedParents[k] = a_parent;\n\t\t\t\tmergedReturnStates[k] = a.returnStates[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse { // b > a, copy b[j] to M\n\t\t\t\tmergedParents[k] = b_parent;\n\t\t\t\tmergedReturnStates[k] = b.returnStates[j];\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tk++;\n\t\t}\n\n\t\t// copy over any payloads remaining in either array\n\t\tif (i < a.returnStates.length) {\n\t\t\tfor (int p = i; p < a.returnStates.length; p++) {\n\t\t\t\tmergedParents[k] = a.parents[p];\n\t\t\t\tmergedReturnStates[k] = a.returnStates[p];\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int p = j; p < b.returnStates.length; p++) {\n\t\t\t\tmergedParents[k] = b.parents[p];\n\t\t\t\tmergedReturnStates[k] = b.returnStates[p];\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\n\t\t// trim merged if we combined a few that had same stack tops\n\t\tif ( k < mergedParents.length ) { // write index < last position; trim\n\t\t\tif ( k == 1 ) { // for just one merged element, return singleton top\n\t\t\t\tPredictionContext a_ =\n\t\t\t\t\tSingletonPredictionContext.create(mergedParents[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t  mergedReturnStates[0]);\n\t\t\t\tif ( mergeCache!=null ) mergeCache.put(a,b,a_);\n\t\t\t\treturn a_;\n\t\t\t}\n\t\t\tmergedParents = Arrays.copyOf(mergedParents, k);\n\t\t\tmergedReturnStates = Arrays.copyOf(mergedReturnStates, k);\n\t\t}\n\n\t\tPredictionContext M =\n\t\t\tnew ArrayPredictionContext(mergedParents, mergedReturnStates);\n\n\t\t// if we created same array as a or b, return that instead\n\t\t// TODO: track whether this is possible above during merge sort for speed\n\t\tif ( M.equals(a) ) {\n\t\t\tif ( mergeCache!=null ) mergeCache.put(a,b,a);\n\t\t\tif ( ParserATNSimulator.trace_atn_sim ) System.out.println(\"mergeArrays a=\"+a+\",b=\"+b+\" -> a\");\n\t\t\treturn a;\n\t\t}\n\t\tif ( M.equals(b) ) {\n\t\t\tif ( mergeCache!=null ) mergeCache.put(a,b,b);\n\t\t\tif ( ParserATNSimulator.trace_atn_sim ) System.out.println(\"mergeArrays a=\"+a+\",b=\"+b+\" -> b\");\n\t\t\treturn b;\n\t\t}\n\n\t\tcombineCommonParents(mergedParents);\n\n\t\tif ( mergeCache!=null ) mergeCache.put(a,b,M);\n\n\t\tif ( ParserATNSimulator.trace_atn_sim ) {\n\t\t\tSystem.out.println(\"mergeArrays a=\"+a+\",b=\"+b+\" -> \"+M);\n\t\t}\n\n\t\treturn M;\n\t}\n\n\t/**\n\t * Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}\n\t * ones.\n\t */\n\tprotected static void combineCommonParents(PredictionContext[] parents) {\n\t\tMap<PredictionContext, PredictionContext> uniqueParents =\n\t\t\tnew HashMap<PredictionContext, PredictionContext>();\n\n\t\tfor (int p = 0; p < parents.length; p++) {\n\t\t\tPredictionContext parent = parents[p];\n\t\t\tif ( !uniqueParents.containsKey(parent) ) { // don't replace\n\t\t\t\tuniqueParents.put(parent, parent);\n\t\t\t}\n\t\t}\n\n\t\tfor (int p = 0; p < parents.length; p++) {\n\t\t\tparents[p] = uniqueParents.get(parents[p]);\n\t\t}\n\t}\n\n\tpublic static String toDOTString(PredictionContext context) {\n\t\tif ( context==null ) return \"\";\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append(\"digraph G {\\n\");\n\t\tbuf.append(\"rankdir=LR;\\n\");\n\n\t\tList<PredictionContext> nodes = getAllContextNodes(context);\n\t\tCollections.sort(nodes, new Comparator<PredictionContext>() {\n\t\t\t@Override\n\t\t\tpublic int compare(PredictionContext o1, PredictionContext o2) {\n\t\t\t\treturn o1.id - o2.id;\n\t\t\t}\n\t\t});\n\n\t\tfor (PredictionContext current : nodes) {\n\t\t\tif ( current instanceof SingletonPredictionContext ) {\n\t\t\t\tString s = String.valueOf(current.id);\n\t\t\t\tbuf.append(\"  s\").append(s);\n\t\t\t\tString returnState = String.valueOf(current.getReturnState(0));\n\t\t\t\tif ( current instanceof EmptyPredictionContext ) returnState = \"$\";\n\t\t\t\tbuf.append(\" [label=\\\"\").append(returnState).append(\"\\\"];\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tArrayPredictionContext arr = (ArrayPredictionContext)current;\n\t\t\tbuf.append(\"  s\").append(arr.id);\n\t\t\tbuf.append(\" [shape=box, label=\\\"\");\n\t\t\tbuf.append(\"[\");\n\t\t\tboolean first = true;\n\t\t\tfor (int inv : arr.returnStates) {\n\t\t\t\tif ( !first ) buf.append(\", \");\n\t\t\t\tif ( inv == EMPTY_RETURN_STATE ) buf.append(\"$\");\n\t\t\t\telse buf.append(inv);\n\t\t\t\tfirst = false;\n\t\t\t}\n\t\t\tbuf.append(\"]\");\n\t\t\tbuf.append(\"\\\"];\\n\");\n\t\t}\n\n\t\tfor (PredictionContext current : nodes) {\n\t\t\tif ( current== EmptyPredictionContext.Instance) continue;\n\t\t\tfor (int i = 0; i < current.size(); i++) {\n\t\t\t\tif ( current.getParent(i)==null ) continue;\n\t\t\t\tString s = String.valueOf(current.id);\n\t\t\t\tbuf.append(\"  s\").append(s);\n\t\t\t\tbuf.append(\"->\");\n\t\t\t\tbuf.append(\"s\");\n\t\t\t\tbuf.append(current.getParent(i).id);\n\t\t\t\tif ( current.size()>1 ) buf.append(\" [label=\\\"parent[\"+i+\"]\\\"];\\n\");\n\t\t\t\telse buf.append(\";\\n\");\n\t\t\t}\n\t\t}\n\n\t\tbuf.append(\"}\\n\");\n\t\treturn buf.toString();\n\t}\n\n\t// From Sam\n\tpublic static PredictionContext getCachedContext(\n\t\tPredictionContext context,\n\t\tPredictionContextCache contextCache,\n\t\tIdentityHashMap<PredictionContext, PredictionContext> visited)\n\t{\n\t\tif (context.isEmpty()) {\n\t\t\treturn context;\n\t\t}\n\n\t\tPredictionContext existing = visited.get(context);\n\t\tif (existing != null) {\n\t\t\treturn existing;\n\t\t}\n\n\t\texisting = contextCache.get(context);\n\t\tif (existing != null) {\n\t\t\tvisited.put(context, existing);\n\t\t\treturn existing;\n\t\t}\n\n\t\tboolean changed = false;\n\t\tPredictionContext[] parents = new PredictionContext[context.size()];\n\t\tfor (int i = 0; i < parents.length; i++) {\n\t\t\tPredictionContext parent = getCachedContext(context.getParent(i), contextCache, visited);\n\t\t\tif (changed || parent != context.getParent(i)) {\n\t\t\t\tif (!changed) {\n\t\t\t\t\tparents = new PredictionContext[context.size()];\n\t\t\t\t\tfor (int j = 0; j < context.size(); j++) {\n\t\t\t\t\t\tparents[j] = context.getParent(j);\n\t\t\t\t\t}\n\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\n\t\t\t\tparents[i] = parent;\n\t\t\t}\n\t\t}\n\n\t\tif (!changed) {\n\t\t\tcontextCache.add(context);\n\t\t\tvisited.put(context, context);\n\t\t\treturn context;\n\t\t}\n\n\t\tPredictionContext updated;\n\t\tif (parents.length == 0) {\n\t\t\tupdated = EmptyPredictionContext.Instance;\n\t\t}\n\t\telse if (parents.length == 1) {\n\t\t\tupdated = SingletonPredictionContext.create(parents[0], context.getReturnState(0));\n\t\t}\n\t\telse {\n\t\t\tArrayPredictionContext arrayPredictionContext = (ArrayPredictionContext)context;\n\t\t\tupdated = new ArrayPredictionContext(parents, arrayPredictionContext.returnStates);\n\t\t}\n\n\t\tcontextCache.add(updated);\n\t\tvisited.put(updated, updated);\n\t\tvisited.put(context, updated);\n\n\t\treturn updated;\n\t}\n\n//\t// extra structures, but cut/paste/morphed works, so leave it.\n//\t// seems to do a breadth-first walk\n//\tpublic static List<PredictionContext> getAllNodes(PredictionContext context) {\n//\t\tMap<PredictionContext, PredictionContext> visited =\n//\t\t\tnew IdentityHashMap<PredictionContext, PredictionContext>();\n//\t\tDeque<PredictionContext> workList = new ArrayDeque<PredictionContext>();\n//\t\tworkList.add(context);\n//\t\tvisited.put(context, context);\n//\t\tList<PredictionContext> nodes = new ArrayList<PredictionContext>();\n//\t\twhile (!workList.isEmpty()) {\n//\t\t\tPredictionContext current = workList.pop();\n//\t\t\tnodes.add(current);\n//\t\t\tfor (int i = 0; i < current.size(); i++) {\n//\t\t\t\tPredictionContext parent = current.getParent(i);\n//\t\t\t\tif ( parent!=null && visited.put(parent, parent) == null) {\n//\t\t\t\t\tworkList.push(parent);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\treturn nodes;\n//\t}\n\n\t// ter's recursive version of Sam's getAllNodes()\n\tpublic static List<PredictionContext> getAllContextNodes(PredictionContext context) {\n\t\tList<PredictionContext> nodes = new ArrayList<PredictionContext>();\n\t\tMap<PredictionContext, PredictionContext> visited =\n\t\t\tnew IdentityHashMap<PredictionContext, PredictionContext>();\n\t\tgetAllContextNodes_(context, nodes, visited);\n\t\treturn nodes;\n\t}\n\n\tpublic static void getAllContextNodes_(PredictionContext context,\n\t\t\t\t\t\t\t\t\t\t   List<PredictionContext> nodes,\n\t\t\t\t\t\t\t\t\t\t   Map<PredictionContext, PredictionContext> visited)\n\t{\n\t\tif ( context==null || visited.containsKey(context) ) return;\n\t\tvisited.put(context, context);\n\t\tnodes.add(context);\n\t\tfor (int i = 0; i < context.size(); i++) {\n\t\t\tgetAllContextNodes_(context.getParent(i), nodes, visited);\n\t\t}\n\t}\n\n\tpublic String toString(Recognizer<?,?> recog) {\n\t\treturn toString();\n//\t\treturn toString(recog, ParserRuleContext.EMPTY);\n\t}\n\n\tpublic String[] toStrings(Recognizer<?, ?> recognizer, int currentState) {\n\t\treturn toStrings(recognizer, EmptyPredictionContext.Instance, currentState);\n\t}\n\n\t// FROM SAM\n\tpublic String[] toStrings(Recognizer<?, ?> recognizer, PredictionContext stop, int currentState) {\n\t\tList<String> result = new ArrayList<String>();\n\n\t\touter:\n\t\tfor (int perm = 0; ; perm++) {\n\t\t\tint offset = 0;\n\t\t\tboolean last = true;\n\t\t\tPredictionContext p = this;\n\t\t\tint stateNumber = currentState;\n\t\t\tStringBuilder localBuffer = new StringBuilder();\n\t\t\tlocalBuffer.append(\"[\");\n\t\t\twhile ( !p.isEmpty() && p != stop ) {\n\t\t\t\tint index = 0;\n\t\t\t\tif (p.size() > 0) {\n\t\t\t\t\tint bits = 1;\n\t\t\t\t\twhile ((1 << bits) < p.size()) {\n\t\t\t\t\t\tbits++;\n\t\t\t\t\t}\n\n\t\t\t\t\tint mask = (1 << bits) - 1;\n\t\t\t\t\tindex = (perm >> offset) & mask;\n\t\t\t\t\tlast &= index >= p.size() - 1;\n\t\t\t\t\tif (index >= p.size()) {\n\t\t\t\t\t\tcontinue outer;\n\t\t\t\t\t}\n\t\t\t\t\toffset += bits;\n\t\t\t\t}\n\n\t\t\t\tif ( recognizer!=null ) {\n\t\t\t\t\tif (localBuffer.length() > 1) {\n\t\t\t\t\t\t// first char is '[', if more than that this isn't the first rule\n\t\t\t\t\t\tlocalBuffer.append(' ');\n\t\t\t\t\t}\n\n\t\t\t\t\tATN atn = recognizer.getATN();\n\t\t\t\t\tATNState s = atn.states.get(stateNumber);\n\t\t\t\t\tString ruleName = recognizer.getRuleNames()[s.ruleIndex];\n\t\t\t\t\tlocalBuffer.append(ruleName);\n\t\t\t\t}\n\t\t\t\telse if ( p.getReturnState(index)!= EMPTY_RETURN_STATE) {\n\t\t\t\t\tif ( !p.isEmpty() ) {\n\t\t\t\t\t\tif (localBuffer.length() > 1) {\n\t\t\t\t\t\t\t// first char is '[', if more than that this isn't the first rule\n\t\t\t\t\t\t\tlocalBuffer.append(' ');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlocalBuffer.append(p.getReturnState(index));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstateNumber = p.getReturnState(index);\n\t\t\t\tp = p.getParent(index);\n\t\t\t}\n\t\t\tlocalBuffer.append(\"]\");\n\t\t\tresult.add(localBuffer.toString());\n\n\t\t\tif (last) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn result.toArray(new String[0]);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PredictionContextCache.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/** Used to cache {@link PredictionContext} objects. Its used for the shared\n *  context cash associated with contexts in DFA states. This cache\n *  can be used for both lexers and parsers.\n */\npublic class PredictionContextCache {\n\tprotected final Map<PredictionContext, PredictionContext> cache =\n\t\tnew HashMap<PredictionContext, PredictionContext>();\n\n\t/** Add a context to the cache and return it. If the context already exists,\n\t *  return that one instead and do not add a new context to the cache.\n\t *  Protect shared cache from unsafe thread access.\n\t */\n\tpublic PredictionContext add(PredictionContext ctx) {\n\t\tif ( ctx==EmptyPredictionContext.Instance ) return EmptyPredictionContext.Instance;\n\t\tPredictionContext existing = cache.get(ctx);\n\t\tif ( existing!=null ) {\n//\t\t\tSystem.out.println(name+\" reuses \"+existing);\n\t\t\treturn existing;\n\t\t}\n\t\tcache.put(ctx, ctx);\n\t\treturn ctx;\n\t}\n\n\tpublic PredictionContext get(PredictionContext ctx) {\n\t\treturn cache.get(ctx);\n\t}\n\n\tpublic int size() {\n\t\treturn cache.size();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/PredictionMode.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.AbstractEqualityComparator;\nimport org.antlr.v4.runtime.misc.FlexibleHashMap;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\nimport java.util.BitSet;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\n\n/**\n * This enumeration defines the prediction modes available in ANTLR 4 along with\n * utility methods for analyzing configuration sets for conflicts and/or\n * ambiguities.\n */\npublic enum PredictionMode {\n\t/**\n\t * The SLL(*) prediction mode. This prediction mode ignores the current\n\t * parser context when making predictions. This is the fastest prediction\n\t * mode, and provides correct results for many grammars. This prediction\n\t * mode is more powerful than the prediction mode provided by ANTLR 3, but\n\t * may result in syntax errors for grammar and input combinations which are\n\t * not SLL.\n\t *\n\t * <p>\n\t * When using this prediction mode, the parser will either return a correct\n\t * parse tree (i.e. the same parse tree that would be returned with the\n\t * {@link #LL} prediction mode), or it will report a syntax error. If a\n\t * syntax error is encountered when using the {@link #SLL} prediction mode,\n\t * it may be due to either an actual syntax error in the input or indicate\n\t * that the particular combination of grammar and input requires the more\n\t * powerful {@link #LL} prediction abilities to complete successfully.</p>\n\t *\n\t * <p>\n\t * This prediction mode does not provide any guarantees for prediction\n\t * behavior for syntactically-incorrect inputs.</p>\n\t */\n\tSLL,\n\t/**\n\t * The LL(*) prediction mode. This prediction mode allows the current parser\n\t * context to be used for resolving SLL conflicts that occur during\n\t * prediction. This is the fastest prediction mode that guarantees correct\n\t * parse results for all combinations of grammars with syntactically correct\n\t * inputs.\n\t *\n\t * <p>\n\t * When using this prediction mode, the parser will make correct decisions\n\t * for all syntactically-correct grammar and input combinations. However, in\n\t * cases where the grammar is truly ambiguous this prediction mode might not\n\t * report a precise answer for <em>exactly which</em> alternatives are\n\t * ambiguous.</p>\n\t *\n\t * <p>\n\t * This prediction mode does not provide any guarantees for prediction\n\t * behavior for syntactically-incorrect inputs.</p>\n\t */\n\tLL,\n\t/**\n\t * The LL(*) prediction mode with exact ambiguity detection. In addition to\n\t * the correctness guarantees provided by the {@link #LL} prediction mode,\n\t * this prediction mode instructs the prediction algorithm to determine the\n\t * complete and exact set of ambiguous alternatives for every ambiguous\n\t * decision encountered while parsing.\n\t *\n\t * <p>\n\t * This prediction mode may be used for diagnosing ambiguities during\n\t * grammar development. Due to the performance overhead of calculating sets\n\t * of ambiguous alternatives, this prediction mode should be avoided when\n\t * the exact results are not necessary.</p>\n\t *\n\t * <p>\n\t * This prediction mode does not provide any guarantees for prediction\n\t * behavior for syntactically-incorrect inputs.</p>\n\t */\n\tLL_EXACT_AMBIG_DETECTION;\n\n\t/** A Map that uses just the state and the stack context as the key. */\n\tstatic class AltAndContextMap extends FlexibleHashMap<ATNConfig,BitSet> {\n\t\tpublic AltAndContextMap() {\n\t\t\tsuper(AltAndContextConfigEqualityComparator.INSTANCE);\n\t\t}\n\t}\n\n\tprivate static final class AltAndContextConfigEqualityComparator extends AbstractEqualityComparator<ATNConfig> {\n\t\tpublic static final AltAndContextConfigEqualityComparator INSTANCE = new AltAndContextConfigEqualityComparator();\n\n\t\tprivate AltAndContextConfigEqualityComparator() {\n\t\t}\n\n\t\t/**\n\t\t * The hash code is only a function of the {@link ATNState#stateNumber}\n\t\t * and {@link ATNConfig#context}.\n\t\t */\n\t\t@Override\n\t\tpublic int hashCode(ATNConfig o) {\n\t\t\tint hashCode = MurmurHash.initialize(7);\n\t\t\thashCode = MurmurHash.update(hashCode, o.state.stateNumber);\n\t\t\thashCode = MurmurHash.update(hashCode, o.context);\n\t\t\thashCode = MurmurHash.finish(hashCode, 2);\n\t        return hashCode;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(ATNConfig a, ATNConfig b) {\n\t\t\tif ( a==b ) return true;\n\t\t\tif ( a==null || b==null ) return false;\n\t\t\treturn a.state.stateNumber==b.state.stateNumber\n\t\t\t\t&& a.context.equals(b.context);\n\t\t}\n\t}\n\n\t/**\n\t * Computes the SLL prediction termination condition.\n\t *\n\t * <p>\n\t * This method computes the SLL prediction termination condition for both of\n\t * the following cases.</p>\n\t *\n\t * <ul>\n\t * <li>The usual SLL+LL fallback upon SLL conflict</li>\n\t * <li>Pure SLL without LL fallback</li>\n\t * </ul>\n\t *\n\t * <p><strong>COMBINED SLL+LL PARSING</strong></p>\n\t *\n\t * <p>When LL-fallback is enabled upon SLL conflict, correct predictions are\n\t * ensured regardless of how the termination condition is computed by this\n\t * method. Due to the substantially higher cost of LL prediction, the\n\t * prediction should only fall back to LL when the additional lookahead\n\t * cannot lead to a unique SLL prediction.</p>\n\t *\n\t * <p>Assuming combined SLL+LL parsing, an SLL configuration set with only\n\t * conflicting subsets should fall back to full LL, even if the\n\t * configuration sets don't resolve to the same alternative (e.g.\n\t * {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting\n\t * configuration, SLL could continue with the hopes that more lookahead will\n\t * resolve via one of those non-conflicting configurations.</p>\n\t *\n\t * <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n\t * stops when it sees only conflicting configuration subsets. In contrast,\n\t * full LL keeps going when there is uncertainty.</p>\n\t *\n\t * <p><strong>HEURISTIC</strong></p>\n\t *\n\t * <p>As a heuristic, we stop prediction when we see any conflicting subset\n\t * unless we see a state that only has one alternative associated with it.\n\t * The single-alt-state thing lets prediction continue upon rules like\n\t * (otherwise, it would admit defeat too soon):</p>\n\t *\n\t * <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>\n\t *\n\t * <p>When the ATN simulation reaches the state before {@code ';'}, it has a\n\t * DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally\n\t * {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop\n\t * processing this node because alternative to has another way to continue,\n\t * via {@code [6|2|[]]}.</p>\n\t *\n\t * <p>It also let's us continue for this rule:</p>\n\t *\n\t * <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>\n\t *\n\t * <p>After matching input A, we reach the stop state for rule A, state 1.\n\t * State 8 is the state right before B. Clearly alternatives 1 and 2\n\t * conflict and no amount of further lookahead will separate the two.\n\t * However, alternative 3 will be able to continue and so we do not stop\n\t * working on this state. In the previous example, we're concerned with\n\t * states associated with the conflicting alternatives. Here alt 3 is not\n\t * associated with the conflicting configs, but since we can continue\n\t * looking for input reasonably, don't declare the state done.</p>\n\t *\n\t * <p><strong>PURE SLL PARSING</strong></p>\n\t *\n\t * <p>To handle pure SLL parsing, all we have to do is make sure that we\n\t * combine stack contexts for configurations that differ only by semantic\n\t * predicate. From there, we can do the usual SLL termination heuristic.</p>\n\t *\n\t * <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>\n\t *\n\t * <p>SLL decisions don't evaluate predicates until after they reach DFA stop\n\t * states because they need to create the DFA cache that works in all\n\t * semantic situations. In contrast, full LL evaluates predicates collected\n\t * during start state computation so it can ignore predicates thereafter.\n\t * This means that SLL termination detection can totally ignore semantic\n\t * predicates.</p>\n\t *\n\t * <p>Implementation-wise, {@link ATNConfigSet} combines stack contexts but not\n\t * semantic predicate contexts so we might see two configurations like the\n\t * following.</p>\n\t *\n\t * <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>\n\t *\n\t * <p>Before testing these configurations against others, we have to merge\n\t * {@code x} and {@code x'} (without modifying the existing configurations).\n\t * For example, we test {@code (x+x')==x''} when looking for conflicts in\n\t * the following configurations.</p>\n\t *\n\t * <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>\n\t *\n\t * <p>If the configuration set has predicates (as indicated by\n\t * {@link ATNConfigSet#hasSemanticContext}), this algorithm makes a copy of\n\t * the configurations to strip out all of the predicates so that a standard\n\t * {@link ATNConfigSet} will merge everything ignoring predicates.</p>\n\t */\n\tpublic static boolean hasSLLConflictTerminatingPrediction(PredictionMode mode, ATNConfigSet configs) {\n\t\t/* Configs in rule stop states indicate reaching the end of the decision\n\t\t * rule (local context) or end of start rule (full context). If all\n\t\t * configs meet this condition, then none of the configurations is able\n\t\t * to match additional input so we terminate prediction.\n\t\t */\n\t\tif (allConfigsInRuleStopStates(configs)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// pure SLL mode parsing\n\t\tif ( mode == PredictionMode.SLL ) {\n\t\t\t// Don't bother with combining configs from different semantic\n\t\t\t// contexts if we can fail over to full LL; costs more time\n\t\t\t// since we'll often fail over anyway.\n\t\t\tif ( configs.hasSemanticContext ) {\n\t\t\t\t// dup configs, tossing out semantic predicates\n\t\t\t\tATNConfigSet dup = new ATNConfigSet();\n\t\t\t\tfor (ATNConfig c : configs) {\n\t\t\t\t\tc = new ATNConfig(c,SemanticContext.Empty.Instance);\n\t\t\t\t\tdup.add(c);\n\t\t\t\t}\n\t\t\t\tconfigs = dup;\n\t\t\t}\n\t\t\t// now we have combined contexts for configs with dissimilar preds\n\t\t}\n\n\t\t// pure SLL or combined SLL+LL mode parsing\n\n\t\tCollection<BitSet> altsets = getConflictingAltSubsets(configs);\n\t\tboolean heuristic =\n\t\t\thasConflictingAltSet(altsets) && !hasStateAssociatedWithOneAlt(configs);\n\t\treturn heuristic;\n\t}\n\n\t/**\n\t * Checks if any configuration in {@code configs} is in a\n\t * {@link RuleStopState}. Configurations meeting this condition have reached\n\t * the end of the decision rule (local context) or end of start rule (full\n\t * context).\n\t *\n\t * @param configs the configuration set to test\n\t * @return {@code true} if any configuration in {@code configs} is in a\n\t * {@link RuleStopState}, otherwise {@code false}\n\t */\n\tpublic static boolean hasConfigInRuleStopState(ATNConfigSet configs) {\n\t\tfor (ATNConfig c : configs) {\n\t\t\tif (c.state instanceof RuleStopState) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all configurations in {@code configs} are in a\n\t * {@link RuleStopState}. Configurations meeting this condition have reached\n\t * the end of the decision rule (local context) or end of start rule (full\n\t * context).\n\t *\n\t * @param configs the configuration set to test\n\t * @return {@code true} if all configurations in {@code configs} are in a\n\t * {@link RuleStopState}, otherwise {@code false}\n\t */\n\tpublic static boolean allConfigsInRuleStopStates(ATNConfigSet configs) {\n\t\tfor (ATNConfig config : configs) {\n\t\t\tif (!(config.state instanceof RuleStopState)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Full LL prediction termination.\n\t *\n\t * <p>Can we stop looking ahead during ATN simulation or is there some\n\t * uncertainty as to which alternative we will ultimately pick, after\n\t * consuming more input? Even if there are partial conflicts, we might know\n\t * that everything is going to resolve to the same minimum alternative. That\n\t * means we can stop since no more lookahead will change that fact. On the\n\t * other hand, there might be multiple conflicts that resolve to different\n\t * minimums. That means we need more look ahead to decide which of those\n\t * alternatives we should predict.</p>\n\t *\n\t * <p>The basic idea is to split the set of configurations {@code C}, into\n\t * conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with\n\t * non-conflicting configurations. Two configurations conflict if they have\n\t * identical {@link ATNConfig#state} and {@link ATNConfig#context} values\n\t * but different {@link ATNConfig#alt} value, e.g. {@code (s, i, ctx, _)}\n\t * and {@code (s, j, ctx, _)} for {@code i!=j}.</p>\n\t *\n\t * <p>Reduce these configuration subsets to the set of possible alternatives.\n\t * You can compute the alternative subsets in one pass as follows:</p>\n\t *\n\t * <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in\n\t * {@code C} holding {@code s} and {@code ctx} fixed.</p>\n\t *\n\t * <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>\n\t *\n\t * <pre>\n\t * map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not\n\t * alt and not pred\n\t * </pre>\n\t *\n\t * <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>\n\t *\n\t * <p>If {@code |A_s,ctx|=1} then there is no conflict associated with\n\t * {@code s} and {@code ctx}.</p>\n\t *\n\t * <p>Reduce the subsets to singletons by choosing a minimum of each subset. If\n\t * the union of these alternative subsets is a singleton, then no amount of\n\t * more lookahead will help us. We will always pick that alternative. If,\n\t * however, there is more than one alternative, then we are uncertain which\n\t * alternative to predict and must continue looking for resolution. We may\n\t * or may not discover an ambiguity in the future, even if there are no\n\t * conflicting subsets this round.</p>\n\t *\n\t * <p>The biggest sin is to terminate early because it means we've made a\n\t * decision but were uncertain as to the eventual outcome. We haven't used\n\t * enough lookahead. On the other hand, announcing a conflict too late is no\n\t * big deal; you will still have the conflict. It's just inefficient. It\n\t * might even look until the end of file.</p>\n\t *\n\t * <p>No special consideration for semantic predicates is required because\n\t * predicates are evaluated on-the-fly for full LL prediction, ensuring that\n\t * no configuration contains a semantic context during the termination\n\t * check.</p>\n\t *\n\t * <p><strong>CONFLICTING CONFIGS</strong></p>\n\t *\n\t * <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict\n\t * when {@code i!=j} but {@code x=x'}. Because we merge all\n\t * {@code (s, i, _)} configurations together, that means that there are at\n\t * most {@code n} configurations associated with state {@code s} for\n\t * {@code n} possible alternatives in the decision. The merged stacks\n\t * complicate the comparison of configuration contexts {@code x} and\n\t * {@code x'}. Sam checks to see if one is a subset of the other by calling\n\t * merge and checking to see if the merged result is either {@code x} or\n\t * {@code x'}. If the {@code x} associated with lowest alternative {@code i}\n\t * is the superset, then {@code i} is the only possible prediction since the\n\t * others resolve to {@code min(i)} as well. However, if {@code x} is\n\t * associated with {@code j>i} then at least one stack configuration for\n\t * {@code j} is not in conflict with alternative {@code i}. The algorithm\n\t * should keep going, looking for more lookahead due to the uncertainty.</p>\n\t *\n\t * <p>For simplicity, I'm doing a equality check between {@code x} and\n\t * {@code x'} that lets the algorithm continue to consume lookahead longer\n\t * than necessary. The reason I like the equality is of course the\n\t * simplicity but also because that is the test you need to detect the\n\t * alternatives that are actually in conflict.</p>\n\t *\n\t * <p><strong>CONTINUE/STOP RULE</strong></p>\n\t *\n\t * <p>Continue if union of resolved alternative sets from non-conflicting and\n\t * conflicting alternative subsets has more than one alternative. We are\n\t * uncertain about which alternative to predict.</p>\n\t *\n\t * <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which\n\t * alternatives are still in the running for the amount of input we've\n\t * consumed at this point. The conflicting sets let us to strip away\n\t * configurations that won't lead to more states because we resolve\n\t * conflicts to the configuration with a minimum alternate for the\n\t * conflicting set.</p>\n\t *\n\t * <p><strong>CASES</strong></p>\n\t *\n\t * <ul>\n\t *\n\t * <li>no conflicts and more than 1 alternative in set =&gt; continue</li>\n\t *\n\t * <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},\n\t * {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set\n\t * {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n\t * {@code {1,3}} =&gt; continue\n\t * </li>\n\t *\n\t * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n\t * {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set\n\t * {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n\t * {@code {1}} =&gt; stop and predict 1</li>\n\t *\n\t * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n\t * {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U\n\t * {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce\n\t * ambiguity {@code {1,2}}</li>\n\t *\n\t * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},\n\t * {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U\n\t * {@code {2}} = {@code {1,2}} =&gt; continue</li>\n\t *\n\t * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},\n\t * {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U\n\t * {@code {3}} = {@code {1,3}} =&gt; continue</li>\n\t *\n\t * </ul>\n\t *\n\t * <p><strong>EXACT AMBIGUITY DETECTION</strong></p>\n\t *\n\t * <p>If all states report the same conflicting set of alternatives, then we\n\t * know we have the exact ambiguity set.</p>\n\t *\n\t * <p><code>|A_<em>i</em>|&gt;1</code> and\n\t * <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>\n\t *\n\t * <p>In other words, we continue examining lookahead until all {@code A_i}\n\t * have more than one alternative and all {@code A_i} are the same. If\n\t * {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate\n\t * because the resolved set is {@code {1}}. To determine what the real\n\t * ambiguity is, we have to know whether the ambiguity is between one and\n\t * two or one and three so we keep going. We can only stop prediction when\n\t * we need exact ambiguity detection when the sets look like\n\t * {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>\n\t */\n\tpublic static int resolvesToJustOneViableAlt(Collection<BitSet> altsets) {\n\t\treturn getSingleViableAlt(altsets);\n\t}\n\n\t/**\n\t * Determines if every alternative subset in {@code altsets} contains more\n\t * than one alternative.\n\t *\n\t * @param altsets a collection of alternative subsets\n\t * @return {@code true} if every {@link BitSet} in {@code altsets} has\n\t * {@link BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}\n\t */\n\tpublic static boolean allSubsetsConflict(Collection<BitSet> altsets) {\n\t\treturn !hasNonConflictingAltSet(altsets);\n\t}\n\n\t/**\n\t * Determines if any single alternative subset in {@code altsets} contains\n\t * exactly one alternative.\n\t *\n\t * @param altsets a collection of alternative subsets\n\t * @return {@code true} if {@code altsets} contains a {@link BitSet} with\n\t * {@link BitSet#cardinality cardinality} 1, otherwise {@code false}\n\t */\n\tpublic static boolean hasNonConflictingAltSet(Collection<BitSet> altsets) {\n\t\tfor (BitSet alts : altsets) {\n\t\t\tif ( alts.cardinality()==1 ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Determines if any single alternative subset in {@code altsets} contains\n\t * more than one alternative.\n\t *\n\t * @param altsets a collection of alternative subsets\n\t * @return {@code true} if {@code altsets} contains a {@link BitSet} with\n\t * {@link BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}\n\t */\n\tpublic static boolean hasConflictingAltSet(Collection<BitSet> altsets) {\n\t\tfor (BitSet alts : altsets) {\n\t\t\tif ( alts.cardinality()>1 ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Determines if every alternative subset in {@code altsets} is equivalent.\n\t *\n\t * @param altsets a collection of alternative subsets\n\t * @return {@code true} if every member of {@code altsets} is equal to the\n\t * others, otherwise {@code false}\n\t */\n\tpublic static boolean allSubsetsEqual(Collection<BitSet> altsets) {\n\t\tIterator<BitSet> it = altsets.iterator();\n\t\tBitSet first = it.next();\n\t\twhile ( it.hasNext() ) {\n\t\t\tBitSet next = it.next();\n\t\t\tif ( !next.equals(first) ) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns the unique alternative predicted by all alternative subsets in\n\t * {@code altsets}. If no such alternative exists, this method returns\n\t * {@link ATN#INVALID_ALT_NUMBER}.\n\t *\n\t * @param altsets a collection of alternative subsets\n\t */\n\tpublic static int getUniqueAlt(Collection<BitSet> altsets) {\n\t\tBitSet all = getAlts(altsets);\n\t\tif ( all.cardinality()==1 ) return all.nextSetBit(0);\n\t\treturn ATN.INVALID_ALT_NUMBER;\n\t}\n\n\t/**\n\t * Gets the complete set of represented alternatives for a collection of\n\t * alternative subsets. This method returns the union of each {@link BitSet}\n\t * in {@code altsets}.\n\t *\n\t * @param altsets a collection of alternative subsets\n\t * @return the set of represented alternatives in {@code altsets}\n\t */\n\tpublic static BitSet getAlts(Collection<BitSet> altsets) {\n\t\tBitSet all = new BitSet();\n\t\tfor (BitSet alts : altsets) {\n\t\t\tall.or(alts);\n\t\t}\n\t\treturn all;\n\t}\n\n\t/**\n\t * Get union of all alts from configs.\n\t *\n\t * @since 4.5.1\n\t */\n\tpublic static BitSet getAlts(ATNConfigSet configs) {\n\t\tBitSet alts = new BitSet();\n\t\tfor (ATNConfig config : configs) {\n\t\t\talts.set(config.alt);\n\t\t}\n\t\treturn alts;\n\t}\n\n\t/**\n\t * This function gets the conflicting alt subsets from a configuration set.\n\t * For each configuration {@code c} in {@code configs}:\n\t *\n\t * <pre>\n\t * map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not\n\t * alt and not pred\n\t * </pre>\n\t */\n\tpublic static Collection<BitSet> getConflictingAltSubsets(ATNConfigSet configs) {\n\t\tAltAndContextMap configToAlts = new AltAndContextMap();\n\t\tfor (ATNConfig c : configs) {\n\t\t\tBitSet alts = configToAlts.get(c);\n\t\t\tif ( alts==null ) {\n\t\t\t\talts = new BitSet();\n\t\t\t\tconfigToAlts.put(c, alts);\n\t\t\t}\n\t\t\talts.set(c.alt);\n\t\t}\n\t\treturn configToAlts.values();\n\t}\n\n\t/**\n\t * Get a map from state to alt subset from a configuration set. For each\n\t * configuration {@code c} in {@code configs}:\n\t *\n\t * <pre>\n\t * map[c.{@link ATNConfig#state state}] U= c.{@link ATNConfig#alt alt}\n\t * </pre>\n\t */\n\tpublic static Map<ATNState, BitSet> getStateToAltMap(ATNConfigSet configs) {\n\t\tMap<ATNState, BitSet> m = new HashMap<ATNState, BitSet>();\n\t\tfor (ATNConfig c : configs) {\n\t\t\tBitSet alts = m.get(c.state);\n\t\t\tif ( alts==null ) {\n\t\t\t\talts = new BitSet();\n\t\t\t\tm.put(c.state, alts);\n\t\t\t}\n\t\t\talts.set(c.alt);\n\t\t}\n\t\treturn m;\n\t}\n\n\tpublic static boolean hasStateAssociatedWithOneAlt(ATNConfigSet configs) {\n\t\tMap<ATNState, BitSet> x = getStateToAltMap(configs);\n\t\tfor (BitSet alts : x.values()) {\n\t\t\tif ( alts.cardinality()==1 ) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic static int getSingleViableAlt(Collection<BitSet> altsets) {\n\t\tBitSet viableAlts = new BitSet();\n\t\tfor (BitSet alts : altsets) {\n\t\t\tint minAlt = alts.nextSetBit(0);\n\t\t\tviableAlts.set(minAlt);\n\t\t\tif ( viableAlts.cardinality()>1 ) { // more than 1 viable alt\n\t\t\t\treturn ATN.INVALID_ALT_NUMBER;\n\t\t\t}\n\t\t}\n\t\treturn viableAlts.nextSetBit(0);\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/ProfilingATNSimulator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.dfa.DFAState;\n\nimport java.util.BitSet;\n\n/**\n * @since 4.3\n */\npublic class ProfilingATNSimulator extends ParserATNSimulator {\n\tprotected final DecisionInfo[] decisions;\n\tprotected int numDecisions;\n\n\tprotected int _sllStopIndex;\n\tprotected int _llStopIndex;\n\n\tprotected int currentDecision;\n\tprotected DFAState currentState;\n\n \t/** At the point of LL failover, we record how SLL would resolve the conflict so that\n\t *  we can determine whether or not a decision / input pair is context-sensitive.\n\t *  If LL gives a different result than SLL's predicted alternative, we have a\n\t *  context sensitivity for sure. The converse is not necessarily true, however.\n\t *  It's possible that after conflict resolution chooses minimum alternatives,\n\t *  SLL could get the same answer as LL. Regardless of whether or not the result indicates\n\t *  an ambiguity, it is not treated as a context sensitivity because LL prediction\n\t *  was not required in order to produce a correct prediction for this decision and input sequence.\n\t *  It may in fact still be a context sensitivity but we don't know by looking at the\n\t *  minimum alternatives for the current input.\n \t */\n\tprotected int conflictingAltResolvedBySLL;\n\n\tpublic ProfilingATNSimulator(Parser parser) {\n\t\tsuper(parser,\n\t\t\t\tparser.getInterpreter().atn,\n\t\t\t\tparser.getInterpreter().decisionToDFA,\n\t\t\t\tparser.getInterpreter().sharedContextCache);\n\t\tnumDecisions = atn.decisionToState.size();\n\t\tdecisions = new DecisionInfo[numDecisions];\n\t\tfor (int i=0; i<numDecisions; i++) {\n\t\t\tdecisions[i] = new DecisionInfo(i);\n\t\t}\n\t}\n\n\t@Override\n\tpublic int adaptivePredict(TokenStream input, int decision, ParserRuleContext outerContext) {\n\t\ttry {\n\t\t\tthis._sllStopIndex = -1;\n\t\t\tthis._llStopIndex = -1;\n\t\t\tthis.currentDecision = decision;\n\t\t\tlong start = System.nanoTime(); // expensive but useful info\n\t\t\tint alt = super.adaptivePredict(input, decision, outerContext);\n\t\t\tlong stop = System.nanoTime();\n\t\t\tdecisions[decision].timeInPrediction += (stop-start);\n\t\t\tdecisions[decision].invocations++;\n\n\t\t\tint SLL_k = _sllStopIndex - _startIndex + 1;\n\t\t\tdecisions[decision].SLL_TotalLook += SLL_k;\n\t\t\tdecisions[decision].SLL_MinLook = decisions[decision].SLL_MinLook==0 ? SLL_k : Math.min(decisions[decision].SLL_MinLook, SLL_k);\n\t\t\tif ( SLL_k > decisions[decision].SLL_MaxLook ) {\n\t\t\t\tdecisions[decision].SLL_MaxLook = SLL_k;\n\t\t\t\tdecisions[decision].SLL_MaxLookEvent =\n\t\t\t\t\t\tnew LookaheadEventInfo(decision, null, alt, input, _startIndex, _sllStopIndex, false);\n\t\t\t}\n\n\t\t\tif (_llStopIndex >= 0) {\n\t\t\t\tint LL_k = _llStopIndex - _startIndex + 1;\n\t\t\t\tdecisions[decision].LL_TotalLook += LL_k;\n\t\t\t\tdecisions[decision].LL_MinLook = decisions[decision].LL_MinLook==0 ? LL_k : Math.min(decisions[decision].LL_MinLook, LL_k);\n\t\t\t\tif ( LL_k > decisions[decision].LL_MaxLook ) {\n\t\t\t\t\tdecisions[decision].LL_MaxLook = LL_k;\n\t\t\t\t\tdecisions[decision].LL_MaxLookEvent =\n\t\t\t\t\t\t\tnew LookaheadEventInfo(decision, null, alt, input, _startIndex, _llStopIndex, true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn alt;\n\t\t}\n\t\tfinally {\n\t\t\tthis.currentDecision = -1;\n\t\t}\n\t}\n\n\t@Override\n\tprotected DFAState getExistingTargetState(DFAState previousD, int t) {\n\t\t// this method is called after each time the input position advances\n\t\t// during SLL prediction\n\t\t_sllStopIndex = _input.index();\n\n\t\tDFAState existingTargetState = super.getExistingTargetState(previousD, t);\n\t\tif ( existingTargetState!=null ) {\n\t\t\tdecisions[currentDecision].SLL_DFATransitions++; // count only if we transition over a DFA state\n\t\t\tif ( existingTargetState==ERROR ) {\n\t\t\t\tdecisions[currentDecision].errors.add(\n\t\t\t\t\t\tnew ErrorInfo(currentDecision, previousD.configs, _input, _startIndex, _sllStopIndex, false)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tcurrentState = existingTargetState;\n\t\treturn existingTargetState;\n\t}\n\n\t@Override\n\tprotected DFAState computeTargetState(DFA dfa, DFAState previousD, int t) {\n\t\tDFAState state = super.computeTargetState(dfa, previousD, t);\n\t\tcurrentState = state;\n\t\treturn state;\n\t}\n\n\t@Override\n\tprotected ATNConfigSet computeReachSet(ATNConfigSet closure, int t, boolean fullCtx) {\n\t\tif (fullCtx) {\n\t\t\t// this method is called after each time the input position advances\n\t\t\t// during full context prediction\n\t\t\t_llStopIndex = _input.index();\n\t\t}\n\n\t\tATNConfigSet reachConfigs = super.computeReachSet(closure, t, fullCtx);\n\t\tif (fullCtx) {\n\t\t\tdecisions[currentDecision].LL_ATNTransitions++; // count computation even if error\n\t\t\tif ( reachConfigs!=null ) {\n\t\t\t}\n\t\t\telse { // no reach on current lookahead symbol. ERROR.\n\t\t\t\t// TODO: does not handle delayed errors per getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule()\n\t\t\t\tdecisions[currentDecision].errors.add(\n\t\t\t\t\tnew ErrorInfo(currentDecision, closure, _input, _startIndex, _llStopIndex, true)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tdecisions[currentDecision].SLL_ATNTransitions++;\n\t\t\tif ( reachConfigs!=null ) {\n\t\t\t}\n\t\t\telse { // no reach on current lookahead symbol. ERROR.\n\t\t\t\tdecisions[currentDecision].errors.add(\n\t\t\t\t\tnew ErrorInfo(currentDecision, closure, _input, _startIndex, _sllStopIndex, false)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn reachConfigs;\n\t}\n\n\t@Override\n\tprotected boolean evalSemanticContext(SemanticContext pred, ParserRuleContext parserCallStack, int alt, boolean fullCtx) {\n\t\tboolean result = super.evalSemanticContext(pred, parserCallStack, alt, fullCtx);\n\t\tif (!(pred instanceof SemanticContext.PrecedencePredicate)) {\n\t\t\tboolean fullContext = _llStopIndex >= 0;\n\t\t\tint stopIndex = fullContext ? _llStopIndex : _sllStopIndex;\n\t\t\tdecisions[currentDecision].predicateEvals.add(\n\t\t\t\tnew PredicateEvalInfo(currentDecision, _input, _startIndex, stopIndex, pred, result, alt, fullCtx)\n\t\t\t);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t@Override\n\tprotected void reportAttemptingFullContext(DFA dfa, BitSet conflictingAlts, ATNConfigSet configs, int startIndex, int stopIndex) {\n\t\tif ( conflictingAlts!=null ) {\n\t\t\tconflictingAltResolvedBySLL = conflictingAlts.nextSetBit(0);\n\t\t}\n\t\telse {\n\t\t\tconflictingAltResolvedBySLL = configs.getAlts().nextSetBit(0);\n\t\t}\n\t\tdecisions[currentDecision].LL_Fallback++;\n\t\tsuper.reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex);\n\t}\n\n\t@Override\n\tprotected void reportContextSensitivity(DFA dfa, int prediction, ATNConfigSet configs, int startIndex, int stopIndex) {\n\t\tif ( prediction != conflictingAltResolvedBySLL ) {\n\t\t\tdecisions[currentDecision].contextSensitivities.add(\n\t\t\t\t\tnew ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex)\n\t\t\t);\n\t\t}\n\t\tsuper.reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex);\n\t}\n\n\t@Override\n\tprotected void reportAmbiguity(DFA dfa, DFAState D, int startIndex, int stopIndex, boolean exact,\n\t\t\t\t\t\t\t\t   BitSet ambigAlts, ATNConfigSet configs)\n\t{\n\t\tint prediction;\n\t\tif ( ambigAlts!=null ) {\n\t\t\tprediction = ambigAlts.nextSetBit(0);\n\t\t}\n\t\telse {\n\t\t\tprediction = configs.getAlts().nextSetBit(0);\n\t\t}\n\t\tif ( configs.fullCtx && prediction != conflictingAltResolvedBySLL ) {\n\t\t\t// Even though this is an ambiguity we are reporting, we can\n\t\t\t// still detect some context sensitivities.  Both SLL and LL\n\t\t\t// are showing a conflict, hence an ambiguity, but if they resolve\n\t\t\t// to different minimum alternatives we have also identified a\n\t\t\t// context sensitivity.\n\t\t\tdecisions[currentDecision].contextSensitivities.add(\n\t\t\t\t\tnew ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex)\n\t\t\t);\n\t\t}\n\t\tdecisions[currentDecision].ambiguities.add(\n\t\t\tnew AmbiguityInfo(currentDecision, configs, ambigAlts,\n\t\t\t\t\t\t\t  _input, startIndex, stopIndex, configs.fullCtx)\n\t\t);\n\t\tsuper.reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts, configs);\n\t}\n\n\t// ---------------------------------------------------------------------\n\n\tpublic DecisionInfo[] getDecisionInfo() {\n\t\treturn decisions;\n\t}\n\n\tpublic DFAState getCurrentState() {\n\t\treturn currentState;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/RangeTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\npublic final class RangeTransition extends Transition {\n\tpublic final int from;\n\tpublic final int to;\n\n\tpublic RangeTransition(ATNState target, int from, int to) {\n\t\tsuper(target);\n\t\tthis.from = from;\n\t\tthis.to = to;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn RANGE;\n\t}\n\n\t@Override\n\n\tpublic IntervalSet label() { return IntervalSet.of(from, to); }\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn symbol >= from && symbol <= to;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new StringBuilder(\"'\")\n\t\t\t\t.appendCodePoint(from)\n\t\t\t\t.append(\"'..'\")\n\t\t\t\t.appendCodePoint(to)\n\t\t\t\t.append(\"'\")\n\t\t\t\t.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/RuleStartState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic final class RuleStartState extends ATNState {\n\tpublic RuleStopState stopState;\n\tpublic boolean isLeftRecursiveRule;\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn RULE_START;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/RuleStopState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** The last node in the ATN for a rule, unless that rule is the start symbol.\n *  In that case, there is one transition to EOF. Later, we might encode\n *  references to all calls to this rule to compute FOLLOW sets for\n *  error handling.\n */\npublic final class RuleStopState extends ATNState {\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn RULE_STOP;\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/RuleTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** */\npublic final class RuleTransition extends Transition {\n\t/** Ptr to the rule definition object for this rule ref */\n\tpublic final int ruleIndex;     // no Rule object at runtime\n\n\tpublic final int precedence;\n\n\t/** What node to begin computations following ref to rule */\n\tpublic ATNState followState;\n\n\t/**\n\t * @deprecated Use\n\t * {@link #RuleTransition(RuleStartState, int, int, ATNState)} instead.\n\t */\n\t@Deprecated\n\tpublic RuleTransition(RuleStartState ruleStart,\n\t\t\t\t\t\t  int ruleIndex,\n\t\t\t\t\t\t  ATNState followState)\n\t{\n\t\tthis(ruleStart, ruleIndex, 0, followState);\n\t}\n\n\tpublic RuleTransition(RuleStartState ruleStart,\n\t\t\t\t\t\t  int ruleIndex,\n\t\t\t\t\t\t  int precedence,\n\t\t\t\t\t\t  ATNState followState)\n\t{\n\t\tsuper(ruleStart);\n\t\tthis.ruleIndex = ruleIndex;\n\t\tthis.precedence = precedence;\n\t\tthis.followState = followState;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn RULE;\n\t}\n\n\t@Override\n\tpublic boolean isEpsilon() { return true; }\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn false;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/SemanticContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Recognizer;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.misc.MurmurHash;\nimport org.antlr.v4.runtime.misc.Utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\n\n/** A tree structure used to record the semantic context in which\n *  an ATN configuration is valid.  It's either a single predicate,\n *  a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.\n *\n *  <p>I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of\n *  {@link SemanticContext} within the scope of this outer class.</p>\n */\npublic abstract class SemanticContext {\n\t/**\n\t * For context independent predicates, we evaluate them without a local\n\t * context (i.e., null context). That way, we can evaluate them without\n\t * having to create proper rule-specific context during prediction (as\n\t * opposed to the parser, which creates them naturally). In a practical\n\t * sense, this avoids a cast exception from RuleContext to myruleContext.\n\t *\n\t * <p>For context dependent predicates, we must pass in a local context so that\n\t * references such as $arg evaluate properly as _localctx.arg. We only\n\t * capture context dependent predicates in the context in which we begin\n\t * prediction, so we passed in the outer context here in case of context\n\t * dependent predicate evaluation.</p>\n\t */\n    public abstract boolean eval(Recognizer<?,?> parser, RuleContext parserCallStack);\n\n\t/**\n\t * Evaluate the precedence predicates for the context and reduce the result.\n\t *\n\t * @param parser The parser instance.\n\t * @param parserCallStack\n\t * @return The simplified semantic context after precedence predicates are\n\t * evaluated, which will be one of the following values.\n\t * <ul>\n\t * <li>{@link Empty#Instance}: if the predicate simplifies to {@code true} after\n\t * precedence predicates are evaluated.</li>\n\t * <li>{@code null}: if the predicate simplifies to {@code false} after\n\t * precedence predicates are evaluated.</li>\n\t * <li>{@code this}: if the semantic context is not changed as a result of\n\t * precedence predicate evaluation.</li>\n\t * <li>A non-{@code null} {@link SemanticContext}: the new simplified\n\t * semantic context after precedence predicates are evaluated.</li>\n\t * </ul>\n\t */\n\tpublic SemanticContext evalPrecedence(Recognizer<?,?> parser, RuleContext parserCallStack) {\n\t\treturn this;\n\t}\n\n\tpublic static class Empty extends SemanticContext {\n\t\t/**\n\t\t * The default {@link SemanticContext}, which is semantically equivalent to\n\t\t * a predicate of the form {@code {true}?}.\n\t\t */\n\t\tpublic static final Empty Instance = new Empty();\n\n\t\t@Override\n\t\tpublic boolean eval(Recognizer<?, ?> parser, RuleContext parserCallStack) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n    public static class Predicate extends SemanticContext {\n        public final int ruleIndex;\n       \tpublic final int predIndex;\n       \tpublic final boolean isCtxDependent;  // e.g., $i ref in pred\n\n        protected Predicate() {\n            this.ruleIndex = -1;\n            this.predIndex = -1;\n            this.isCtxDependent = false;\n        }\n\n        public Predicate(int ruleIndex, int predIndex, boolean isCtxDependent) {\n            this.ruleIndex = ruleIndex;\n            this.predIndex = predIndex;\n            this.isCtxDependent = isCtxDependent;\n        }\n\n        @Override\n        public boolean eval(Recognizer<?,?> parser, RuleContext parserCallStack) {\n            RuleContext localctx = isCtxDependent ? parserCallStack : null;\n            return parser.sempred(localctx, ruleIndex, predIndex);\n        }\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint hashCode = MurmurHash.initialize();\n\t\t\thashCode = MurmurHash.update(hashCode, ruleIndex);\n\t\t\thashCode = MurmurHash.update(hashCode, predIndex);\n\t\t\thashCode = MurmurHash.update(hashCode, isCtxDependent ? 1 : 0);\n\t\t\thashCode = MurmurHash.finish(hashCode, 3);\n\t\t\treturn hashCode;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif ( !(obj instanceof Predicate) ) return false;\n\t\t\tif ( this == obj ) return true;\n\t\t\tPredicate p = (Predicate)obj;\n\t\t\treturn this.ruleIndex == p.ruleIndex &&\n\t\t\t\t   this.predIndex == p.predIndex &&\n\t\t\t\t   this.isCtxDependent == p.isCtxDependent;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n            return \"{\"+ruleIndex+\":\"+predIndex+\"}?\";\n        }\n    }\n\n\tpublic static class PrecedencePredicate extends SemanticContext implements Comparable<PrecedencePredicate> {\n\t\tpublic final int precedence;\n\n\t\tprotected PrecedencePredicate() {\n\t\t\tthis.precedence = 0;\n\t\t}\n\n\t\tpublic PrecedencePredicate(int precedence) {\n\t\t\tthis.precedence = precedence;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean eval(Recognizer<?, ?> parser, RuleContext parserCallStack) {\n\t\t\treturn parser.precpred(parserCallStack, precedence);\n\t\t}\n\n\t\t@Override\n\t\tpublic SemanticContext evalPrecedence(Recognizer<?, ?> parser, RuleContext parserCallStack) {\n\t\t\tif (parser.precpred(parserCallStack, precedence)) {\n\t\t\t\treturn Empty.Instance;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic int compareTo(PrecedencePredicate o) {\n\t\t\treturn precedence - o.precedence;\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tint hashCode = 1;\n\t\t\thashCode = 31 * hashCode + precedence;\n\t\t\treturn hashCode;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (!(obj instanceof PrecedencePredicate)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (this == obj) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tPrecedencePredicate other = (PrecedencePredicate)obj;\n\t\t\treturn this.precedence == other.precedence;\n\t\t}\n\n\t\t@Override\n\t\t// precedence >= _precedenceStack.peek()\n\t\tpublic String toString() {\n\t\t\treturn \"{\"+precedence+\">=prec}?\";\n\t\t}\n\t}\n\n\t/**\n\t * This is the base class for semantic context \"operators\", which operate on\n\t * a collection of semantic context \"operands\".\n\t *\n\t * @since 4.3\n\t */\n\tpublic static abstract class Operator extends SemanticContext {\n\t\t/**\n\t\t * Gets the operands for the semantic context operator.\n\t\t *\n\t\t * @return a collection of {@link SemanticContext} operands for the\n\t\t * operator.\n\t\t *\n\t\t * @since 4.3\n\t\t */\n\n\t\tpublic abstract Collection<SemanticContext> getOperands();\n\t}\n\n\t/**\n\t * A semantic context which is true whenever none of the contained contexts\n\t * is false.\n\t */\n    public static class AND extends Operator {\n\t\tpublic final SemanticContext[] opnds;\n\n\t\tpublic AND(SemanticContext a, SemanticContext b) {\n\t\t\tSet<SemanticContext> operands = new HashSet<SemanticContext>();\n\t\t\tif ( a instanceof AND ) operands.addAll(Arrays.asList(((AND)a).opnds));\n\t\t\telse operands.add(a);\n\t\t\tif ( b instanceof AND ) operands.addAll(Arrays.asList(((AND)b).opnds));\n\t\t\telse operands.add(b);\n\n\t\t\tList<PrecedencePredicate> precedencePredicates = filterPrecedencePredicates(operands);\n\t\t\tif (!precedencePredicates.isEmpty()) {\n\t\t\t\t// interested in the transition with the lowest precedence\n\t\t\t\tPrecedencePredicate reduced = Collections.min(precedencePredicates);\n\t\t\t\toperands.add(reduced);\n\t\t\t}\n\n\t\t\topnds = operands.toArray(new SemanticContext[0]);\n        }\n\n\t\t@Override\n\t\tpublic Collection<SemanticContext> getOperands() {\n\t\t\treturn Arrays.asList(opnds);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif ( this==obj ) return true;\n\t\t\tif ( !(obj instanceof AND) ) return false;\n\t\t\tAND other = (AND)obj;\n\t\t\treturn Arrays.equals(this.opnds, other.opnds);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn MurmurHash.hashCode(opnds, AND.class.hashCode());\n\t\t}\n\n\t\t/**\n\t\t * {@inheritDoc}\n\t\t *\n\t\t * <p>\n\t\t * The evaluation of predicates by this context is short-circuiting, but\n\t\t * unordered.</p>\n\t\t */\n\t\t@Override\n\t\tpublic boolean eval(Recognizer<?,?> parser, RuleContext parserCallStack) {\n\t\t\tfor (SemanticContext opnd : opnds) {\n\t\t\t\tif ( !opnd.eval(parser, parserCallStack) ) return false;\n\t\t\t}\n\t\t\treturn true;\n        }\n\n\t\t@Override\n\t\tpublic SemanticContext evalPrecedence(Recognizer<?, ?> parser, RuleContext parserCallStack) {\n\t\t\tboolean differs = false;\n\t\t\tList<SemanticContext> operands = new ArrayList<SemanticContext>();\n\t\t\tfor (SemanticContext context : opnds) {\n\t\t\t\tSemanticContext evaluated = context.evalPrecedence(parser, parserCallStack);\n\t\t\t\tdiffers |= (evaluated != context);\n\t\t\t\tif (evaluated == null) {\n\t\t\t\t\t// The AND context is false if any element is false\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse if (evaluated != Empty.Instance) {\n\t\t\t\t\t// Reduce the result by skipping true elements\n\t\t\t\t\toperands.add(evaluated);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!differs) {\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tif (operands.isEmpty()) {\n\t\t\t\t// all elements were true, so the AND context is true\n\t\t\t\treturn Empty.Instance;\n\t\t\t}\n\n\t\t\tSemanticContext result = operands.get(0);\n\t\t\tfor (int i = 1; i < operands.size(); i++) {\n\t\t\t\tresult = SemanticContext.and(result, operands.get(i));\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn Utils.join(Arrays.asList(opnds).iterator(), \"&&\");\n        }\n    }\n\n\t/**\n\t * A semantic context which is true whenever at least one of the contained\n\t * contexts is true.\n\t */\n    public static class OR extends Operator {\n\t\tpublic final SemanticContext[] opnds;\n\n\t\tpublic OR(SemanticContext a, SemanticContext b) {\n\t\t\tSet<SemanticContext> operands = new HashSet<SemanticContext>();\n\t\t\tif ( a instanceof OR ) operands.addAll(Arrays.asList(((OR)a).opnds));\n\t\t\telse operands.add(a);\n\t\t\tif ( b instanceof OR ) operands.addAll(Arrays.asList(((OR)b).opnds));\n\t\t\telse operands.add(b);\n\n\t\t\tList<PrecedencePredicate> precedencePredicates = filterPrecedencePredicates(operands);\n\t\t\tif (!precedencePredicates.isEmpty()) {\n\t\t\t\t// interested in the transition with the highest precedence\n\t\t\t\tPrecedencePredicate reduced = Collections.max(precedencePredicates);\n\t\t\t\toperands.add(reduced);\n\t\t\t}\n\n\t\t\tthis.opnds = operands.toArray(new SemanticContext[0]);\n        }\n\n\t\t@Override\n\t\tpublic Collection<SemanticContext> getOperands() {\n\t\t\treturn Arrays.asList(opnds);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif ( this==obj ) return true;\n\t\t\tif ( !(obj instanceof OR) ) return false;\n\t\t\tOR other = (OR)obj;\n\t\t\treturn Arrays.equals(this.opnds, other.opnds);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn MurmurHash.hashCode(opnds, OR.class.hashCode());\n\t\t}\n\n\t\t/**\n\t\t * {@inheritDoc}\n\t\t *\n\t\t * <p>\n\t\t * The evaluation of predicates by this context is short-circuiting, but\n\t\t * unordered.</p>\n\t\t */\n\t\t@Override\n        public boolean eval(Recognizer<?,?> parser, RuleContext parserCallStack) {\n\t\t\tfor (SemanticContext opnd : opnds) {\n\t\t\t\tif ( opnd.eval(parser, parserCallStack) ) return true;\n\t\t\t}\n\t\t\treturn false;\n        }\n\n\t\t@Override\n\t\tpublic SemanticContext evalPrecedence(Recognizer<?, ?> parser, RuleContext parserCallStack) {\n\t\t\tboolean differs = false;\n\t\t\tList<SemanticContext> operands = new ArrayList<SemanticContext>();\n\t\t\tfor (SemanticContext context : opnds) {\n\t\t\t\tSemanticContext evaluated = context.evalPrecedence(parser, parserCallStack);\n\t\t\t\tdiffers |= (evaluated != context);\n\t\t\t\tif (evaluated == Empty.Instance) {\n\t\t\t\t\t// The OR context is true if any element is true\n\t\t\t\t\treturn Empty.Instance;\n\t\t\t\t}\n\t\t\t\telse if (evaluated != null) {\n\t\t\t\t\t// Reduce the result by skipping false elements\n\t\t\t\t\toperands.add(evaluated);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!differs) {\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tif (operands.isEmpty()) {\n\t\t\t\t// all elements were false, so the OR context is false\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tSemanticContext result = operands.get(0);\n\t\t\tfor (int i = 1; i < operands.size(); i++) {\n\t\t\t\tresult = SemanticContext.or(result, operands.get(i));\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n        @Override\n        public String toString() {\n\t\t\treturn Utils.join(Arrays.asList(opnds).iterator(), \"||\");\n        }\n    }\n\n\tpublic static SemanticContext and(SemanticContext a, SemanticContext b) {\n\t\tif ( a == null || a == Empty.Instance ) return b;\n\t\tif ( b == null || b == Empty.Instance ) return a;\n\t\tAND result = new AND(a, b);\n\t\tif (result.opnds.length == 1) {\n\t\t\treturn result.opnds[0];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t *\n\t *  @see ParserATNSimulator#getPredsForAmbigAlts\n\t */\n\tpublic static SemanticContext or(SemanticContext a, SemanticContext b) {\n\t\tif ( a == null ) return b;\n\t\tif ( b == null ) return a;\n\t\tif ( a == Empty.Instance || b == Empty.Instance ) return Empty.Instance;\n\t\tOR result = new OR(a, b);\n\t\tif (result.opnds.length == 1) {\n\t\t\treturn result.opnds[0];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate static List<PrecedencePredicate> filterPrecedencePredicates(Collection<? extends SemanticContext> collection) {\n\t\tArrayList<PrecedencePredicate> result = null;\n\t\tfor (Iterator<? extends SemanticContext> iterator = collection.iterator(); iterator.hasNext(); ) {\n\t\t\tSemanticContext context = iterator.next();\n\t\t\tif (context instanceof PrecedencePredicate) {\n\t\t\t\tif (result == null) {\n\t\t\t\t\tresult = new ArrayList<PrecedencePredicate>();\n\t\t\t\t}\n\n\t\t\t\tresult.add((PrecedencePredicate)context);\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t}\n\n\t\tif (result == null) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\treturn result;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/SetTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\n/** A transition containing a set of values. */\npublic class SetTransition extends Transition {\n\tpublic final IntervalSet set;\n\n\t// TODO (sam): should we really allow null here?\n\tpublic SetTransition(ATNState target, IntervalSet set) {\n\t\tsuper(target);\n\t\tif ( set == null ) set = IntervalSet.of(Token.INVALID_TYPE);\n\t\tthis.set = set;\n\t}\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn SET;\n\t}\n\n\t@Override\n\n\tpublic IntervalSet label() { return set; }\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn set.contains(symbol);\n\t}\n\n\t@Override\n\n\tpublic String toString() {\n\t\treturn set.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/SingletonPredictionContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic class SingletonPredictionContext extends PredictionContext {\n\tpublic final PredictionContext parent;\n\tpublic final int returnState;\n\n\tSingletonPredictionContext(PredictionContext parent, int returnState) {\n\t\tsuper(parent != null ? calculateHashCode(parent, returnState) : calculateEmptyHashCode());\n\t\tassert returnState!=ATNState.INVALID_STATE_NUMBER;\n\t\tthis.parent = parent;\n\t\tthis.returnState = returnState;\n\t}\n\n\tpublic static SingletonPredictionContext create(PredictionContext parent, int returnState) {\n\t\tif ( returnState == EMPTY_RETURN_STATE && parent == null ) {\n\t\t\t// someone can pass in the bits of an array ctx that mean $\n\t\t\treturn EmptyPredictionContext.Instance;\n\t\t}\n\t\treturn new SingletonPredictionContext(parent, returnState);\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic PredictionContext getParent(int index) {\n\t\tassert index == 0;\n\t\treturn parent;\n\t}\n\n\t@Override\n\tpublic int getReturnState(int index) {\n\t\tassert index == 0;\n\t\treturn returnState;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\telse if ( !(o instanceof SingletonPredictionContext) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( this.hashCode() != o.hashCode() ) {\n\t\t\treturn false; // can't be same if hash is different\n\t\t}\n\n\t\tSingletonPredictionContext s = (SingletonPredictionContext)o;\n\t\treturn returnState == s.returnState &&\n\t\t\t(parent!=null && parent.equals(s.parent));\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString up = parent!=null ? parent.toString() : \"\";\n\t\tif ( up.length()==0 ) {\n\t\t\tif ( returnState == EMPTY_RETURN_STATE ) {\n\t\t\t\treturn \"$\";\n\t\t\t}\n\t\t\treturn String.valueOf(returnState);\n\t\t}\n\t\treturn String.valueOf(returnState)+\" \"+up;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/StarBlockStartState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** The block that begins a closure loop. */\npublic final class StarBlockStartState extends BlockStartState {\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn STAR_BLOCK_START;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/StarLoopEntryState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.dfa.DFA;\n\npublic final class StarLoopEntryState extends DecisionState {\n\tpublic StarLoopbackState loopBackState;\n\n\t/**\n\t * Indicates whether this state can benefit from a precedence DFA during SLL\n\t * decision making.\n\t *\n\t * <p>This is a computed property that is calculated during ATN deserialization\n\t * and stored for use in {@link ParserATNSimulator} and\n\t * {@link ParserInterpreter}.</p>\n\t *\n\t * @see DFA#isPrecedenceDfa()\n\t */\n\tpublic boolean isPrecedenceDecision;\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn STAR_LOOP_ENTRY;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/StarLoopbackState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic final class StarLoopbackState extends ATNState {\n\tpublic final StarLoopEntryState getLoopEntryState() {\n\t\treturn (StarLoopEntryState)transition(0).target;\n\t}\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn STAR_LOOP_BACK;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/TokensStartState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\n/** The Tokens rule start state linking to each lexer rule start state */\npublic final class TokensStartState extends DecisionState {\n\n\t@Override\n\tpublic int getStateType() {\n\t\treturn TOKEN_START;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/Transition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** An ATN transition between any two ATN states.  Subclasses define\n *  atom, set, epsilon, action, predicate, rule transitions.\n *\n *  <p>This is a one way link.  It emanates from a state (usually via a list of\n *  transitions) and has a target state.</p>\n *\n *  <p>Since we never have to change the ATN transitions once we construct it,\n *  we can fix these transitions as specific classes. The DFA transitions\n *  on the other hand need to update the labels as it adds transitions to\n *  the states. We'll use the term Edge for the DFA to distinguish them from\n *  ATN transitions.</p>\n */\npublic abstract class Transition {\n\t// constants for serialization\n\tpublic static final int EPSILON\t\t\t= 1;\n\tpublic static final int RANGE\t\t\t= 2;\n\tpublic static final int RULE\t\t\t= 3;\n\tpublic static final int PREDICATE\t\t= 4; // e.g., {isType(input.LT(1))}?\n\tpublic static final int ATOM\t\t\t= 5;\n\tpublic static final int ACTION\t\t\t= 6;\n\tpublic static final int SET\t\t\t\t= 7; // ~(A|B) or ~atom, wildcard, which convert to next 2\n\tpublic static final int NOT_SET\t\t\t= 8;\n\tpublic static final int WILDCARD\t\t= 9;\n\tpublic static final int PRECEDENCE\t\t= 10;\n\n\n\tpublic static final List<String> serializationNames =\n\t\tCollections.unmodifiableList(Arrays.asList(\n\t\t\t\"INVALID\",\n\t\t\t\"EPSILON\",\n\t\t\t\"RANGE\",\n\t\t\t\"RULE\",\n\t\t\t\"PREDICATE\",\n\t\t\t\"ATOM\",\n\t\t\t\"ACTION\",\n\t\t\t\"SET\",\n\t\t\t\"NOT_SET\",\n\t\t\t\"WILDCARD\",\n\t\t\t\"PRECEDENCE\"\n\t\t));\n\n\tpublic static final Map<Class<? extends Transition>, Integer> serializationTypes =\n\t\tCollections.unmodifiableMap(new HashMap<Class<? extends Transition>, Integer>() {{\n\t\t\tput(EpsilonTransition.class, EPSILON);\n\t\t\tput(RangeTransition.class, RANGE);\n\t\t\tput(RuleTransition.class, RULE);\n\t\t\tput(PredicateTransition.class, PREDICATE);\n\t\t\tput(AtomTransition.class, ATOM);\n\t\t\tput(ActionTransition.class, ACTION);\n\t\t\tput(SetTransition.class, SET);\n\t\t\tput(NotSetTransition.class, NOT_SET);\n\t\t\tput(WildcardTransition.class, WILDCARD);\n\t\t\tput(PrecedencePredicateTransition.class, PRECEDENCE);\n\t\t}});\n\n\t/** The target of this transition. */\n\n\tpublic ATNState target;\n\n\tprotected Transition(ATNState target) {\n\t\tif (target == null) {\n\t\t\tthrow new NullPointerException(\"target cannot be null.\");\n\t\t}\n\n\t\tthis.target = target;\n\t}\n\n\tpublic abstract int getSerializationType();\n\n\t/**\n\t * Determines if the transition is an \"epsilon\" transition.\n\t *\n\t * <p>The default implementation returns {@code false}.</p>\n\t *\n\t * @return {@code true} if traversing this transition in the ATN does not\n\t * consume an input symbol; otherwise, {@code false} if traversing this\n\t * transition consumes (matches) an input symbol.\n\t */\n\tpublic boolean isEpsilon() {\n\t\treturn false;\n\t}\n\n\n\tpublic IntervalSet label() { return null; }\n\n\tpublic abstract boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/atn/WildcardTransition.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.atn;\n\npublic final class WildcardTransition extends Transition {\n\tpublic WildcardTransition(ATNState target) { super(target); }\n\n\t@Override\n\tpublic int getSerializationType() {\n\t\treturn WILDCARD;\n\t}\n\n\t@Override\n\tpublic boolean matches(int symbol, int minVocabSymbol, int maxVocabSymbol) {\n\t\treturn symbol >= minVocabSymbol && symbol <= maxVocabSymbol;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \".\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/dfa/DFA.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.dfa;\n\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class DFA {\n\t/** A set of all DFA states. Use {@link Map} so we can get old state back\n\t *  ({@link Set} only allows you to see if it's there).\n     */\n\n\tpublic final Map<DFAState, DFAState> states = new HashMap<DFAState, DFAState>();\n\n\tpublic volatile DFAState s0;\n\n\tpublic final int decision;\n\n\t/** From which ATN state did we create this DFA? */\n\n\tpublic final DecisionState atnStartState;\n\n\t/**\n\t * {@code true} if this DFA is for a precedence decision; otherwise,\n\t * {@code false}. This is the backing field for {@link #isPrecedenceDfa}.\n\t */\n\tprivate final boolean precedenceDfa;\n\n\tpublic DFA(DecisionState atnStartState) {\n\t\tthis(atnStartState, 0);\n\t}\n\n\tpublic DFA(DecisionState atnStartState, int decision) {\n\t\tthis.atnStartState = atnStartState;\n\t\tthis.decision = decision;\n\n\t\tboolean precedenceDfa = false;\n\t\tif (atnStartState instanceof StarLoopEntryState) {\n\t\t\tif (((StarLoopEntryState)atnStartState).isPrecedenceDecision) {\n\t\t\t\tprecedenceDfa = true;\n\t\t\t\tDFAState precedenceState = new DFAState(new ATNConfigSet());\n\t\t\t\tprecedenceState.edges = new DFAState[0];\n\t\t\t\tprecedenceState.isAcceptState = false;\n\t\t\t\tprecedenceState.requiresFullContext = false;\n\t\t\t\tthis.s0 = precedenceState;\n\t\t\t}\n\t\t}\n\n\t\tthis.precedenceDfa = precedenceDfa;\n\t}\n\n\t/**\n\t * Gets whether this DFA is a precedence DFA. Precedence DFAs use a special\n\t * start state {@link #s0} which is not stored in {@link #states}. The\n\t * {@link DFAState#edges} array for this start state contains outgoing edges\n\t * supplying individual start states corresponding to specific precedence\n\t * values.\n\t *\n\t * @return {@code true} if this is a precedence DFA; otherwise,\n\t * {@code false}.\n\t * @see Parser#getPrecedence()\n\t */\n\tpublic final boolean isPrecedenceDfa() {\n\t\treturn precedenceDfa;\n\t}\n\n\t/**\n\t * Get the start state for a specific precedence value.\n\t *\n\t * @param precedence The current precedence.\n\t * @return The start state corresponding to the specified precedence, or\n\t * {@code null} if no start state exists for the specified precedence.\n\t *\n\t * @throws IllegalStateException if this is not a precedence DFA.\n\t * @see #isPrecedenceDfa()\n\t */\n\t@SuppressWarnings(\"null\")\n\tpublic final DFAState getPrecedenceStartState(int precedence) {\n\t\tif (!isPrecedenceDfa()) {\n\t\t\tthrow new IllegalStateException(\"Only precedence DFAs may contain a precedence start state.\");\n\t\t}\n\n\t\t// s0.edges is never null for a precedence DFA\n\t\tif (precedence < 0 || precedence >= s0.edges.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn s0.edges[precedence];\n\t}\n\n\t/**\n\t * Set the start state for a specific precedence value.\n\t *\n\t * @param precedence The current precedence.\n\t * @param startState The start state corresponding to the specified\n\t * precedence.\n\t *\n\t * @throws IllegalStateException if this is not a precedence DFA.\n\t * @see #isPrecedenceDfa()\n\t */\n\t@SuppressWarnings({\"SynchronizeOnNonFinalField\", \"null\"})\n\tpublic final void setPrecedenceStartState(int precedence, DFAState startState) {\n\t\tif (!isPrecedenceDfa()) {\n\t\t\tthrow new IllegalStateException(\"Only precedence DFAs may contain a precedence start state.\");\n\t\t}\n\n\t\tif (precedence < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// synchronization on s0 here is ok. when the DFA is turned into a\n\t\t// precedence DFA, s0 will be initialized once and not updated again\n\t\tsynchronized (s0) {\n\t\t\t// s0.edges is never null for a precedence DFA\n\t\t\tif (precedence >= s0.edges.length) {\n\t\t\t\ts0.edges = Arrays.copyOf(s0.edges, precedence + 1);\n\t\t\t}\n\n\t\t\ts0.edges[precedence] = startState;\n\t\t}\n\t}\n\n\t/**\n\t * Sets whether this is a precedence DFA.\n\t *\n\t * @param precedenceDfa {@code true} if this is a precedence DFA; otherwise,\n\t * {@code false}\n\t *\n\t * @throws UnsupportedOperationException if {@code precedenceDfa} does not\n\t * match the value of {@link #isPrecedenceDfa} for the current DFA.\n\t *\n\t * @deprecated This method no longer performs any action.\n\t */\n\t@Deprecated\n\tpublic final void setPrecedenceDfa(boolean precedenceDfa) {\n\t\tif (precedenceDfa != isPrecedenceDfa()) {\n\t\t\tthrow new UnsupportedOperationException(\"The precedenceDfa field cannot change after a DFA is constructed.\");\n\t\t}\n\t}\n\n\t/**\n\t * Return a list of all states in this DFA, ordered by state number.\n\t */\n\n\tpublic List<DFAState> getStates() {\n\t\tList<DFAState> result = new ArrayList<DFAState>(states.keySet());\n\t\tCollections.sort(result, new Comparator<DFAState>() {\n\t\t\t@Override\n\t\t\tpublic int compare(DFAState o1, DFAState o2) {\n\t\t\t\treturn o1.stateNumber - o2.stateNumber;\n\t\t\t}\n\t\t});\n\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic String toString() { return toString(VocabularyImpl.EMPTY_VOCABULARY); }\n\n\t/**\n\t * @deprecated Use {@link #toString(Vocabulary)} instead.\n\t */\n\t@Deprecated\n\tpublic String toString(String[] tokenNames) {\n\t\tif ( s0==null ) return \"\";\n\t\tDFASerializer serializer = new DFASerializer(this,tokenNames);\n\t\treturn serializer.toString();\n\t}\n\n\tpublic String toString(Vocabulary vocabulary) {\n\t\tif (s0 == null) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tDFASerializer serializer = new DFASerializer(this, vocabulary);\n\t\treturn serializer.toString();\n\t}\n\n\tpublic String toLexerString() {\n\t\tif ( s0==null ) return \"\";\n\t\tDFASerializer serializer = new LexerDFASerializer(this);\n\t\treturn serializer.toString();\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/dfa/DFASerializer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.dfa;\n\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\n\nimport java.util.Arrays;\nimport java.util.List;\n\n/** A DFA walker that knows how to dump them to serialized strings. */\npublic class DFASerializer {\n\n\tprivate final DFA dfa;\n\n\tprivate final Vocabulary vocabulary;\n\n\t/**\n\t * @deprecated Use {@link #DFASerializer(DFA, Vocabulary)} instead.\n\t */\n\t@Deprecated\n\tpublic DFASerializer(DFA dfa, String[] tokenNames) {\n\t\tthis(dfa, VocabularyImpl.fromTokenNames(tokenNames));\n\t}\n\n\tpublic DFASerializer(DFA dfa, Vocabulary vocabulary) {\n\t\tthis.dfa = dfa;\n\t\tthis.vocabulary = vocabulary;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tif ( dfa.s0==null ) return null;\n\t\tStringBuilder buf = new StringBuilder();\n\t\tList<DFAState> states = dfa.getStates();\n\t\tfor (DFAState s : states) {\n\t\t\tint n = 0;\n\t\t\tif ( s.edges!=null ) n = s.edges.length;\n\t\t\tfor (int i=0; i<n; i++) {\n\t\t\t\tDFAState t = s.edges[i];\n\t\t\t\tif ( t!=null && t.stateNumber != Integer.MAX_VALUE ) {\n\t\t\t\t\tbuf.append(getStateString(s));\n\t\t\t\t\tString label = getEdgeLabel(i);\n\t\t\t\t\tbuf.append(\"-\").append(label).append(\"->\").append(getStateString(t)).append('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tString output = buf.toString();\n\t\tif ( output.length()==0 ) return null;\n\t\t//return Utils.sortLinesInString(output);\n\t\treturn output;\n\t}\n\n\tprotected String getEdgeLabel(int i) {\n\t\treturn vocabulary.getDisplayName(i - 1);\n\t}\n\n\n\tprotected String getStateString(DFAState s) {\n\t\tint n = s.stateNumber;\n\t\tfinal String baseStateStr = (s.isAcceptState ? \":\" : \"\") + \"s\" + n + (s.requiresFullContext ? \"^\" : \"\");\n\t\tif ( s.isAcceptState ) {\n            if ( s.predicates!=null ) {\n                return baseStateStr + \"=>\" + Arrays.toString(s.predicates);\n            }\n            else {\n                return baseStateStr + \"=>\" + s.prediction;\n            }\n\t\t}\n\t\telse {\n\t\t\treturn baseStateStr;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/dfa/DFAState.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.dfa;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNConfig;\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.atn.LexerActionExecutor;\nimport org.antlr.v4.runtime.atn.ParserATNSimulator;\nimport org.antlr.v4.runtime.atn.SemanticContext;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\n/** A DFA state represents a set of possible ATN configurations.\n *  As Aho, Sethi, Ullman p. 117 says \"The DFA uses its state\n *  to keep track of all possible states the ATN can be in after\n *  reading each input symbol.  That is to say, after reading\n *  input a1a2..an, the DFA is in a state that represents the\n *  subset T of the states of the ATN that are reachable from the\n *  ATN's start state along some path labeled a1a2..an.\"\n *  In conventional NFA&rarr;DFA conversion, therefore, the subset T\n *  would be a bitset representing the set of states the\n *  ATN could be in.  We need to track the alt predicted by each\n *  state as well, however.  More importantly, we need to maintain\n *  a stack of states, tracking the closure operations as they\n *  jump from rule to rule, emulating rule invocations (method calls).\n *  I have to add a stack to simulate the proper lookahead sequences for\n *  the underlying LL grammar from which the ATN was derived.\n *\n *  <p>I use a set of ATNConfig objects not simple states.  An ATNConfig\n *  is both a state (ala normal conversion) and a RuleContext describing\n *  the chain of rules (if any) followed to arrive at that state.</p>\n *\n *  <p>A DFA state may have multiple references to a particular state,\n *  but with different ATN contexts (with same or different alts)\n *  meaning that state was reached via a different set of rule invocations.</p>\n */\npublic class DFAState {\n\tpublic int stateNumber = -1;\n\n\n\tpublic ATNConfigSet configs = new ATNConfigSet();\n\n\t/** {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)\n\t *  {@link Token#EOF} maps to {@code edges[0]}.\n\t */\n\n\tpublic DFAState[] edges;\n\n\tpublic boolean isAcceptState = false;\n\n\t/** if accept state, what ttype do we match or alt do we predict?\n\t *  This is set to {@link ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or\n\t *  {@link #requiresFullContext}.\n\t */\n\tpublic int prediction;\n\n\tpublic LexerActionExecutor lexerActionExecutor;\n\n\t/**\n\t * Indicates that this state was created during SLL prediction that\n\t * discovered a conflict between the configurations in the state. Future\n\t * {@link ParserATNSimulator#execATN} invocations immediately jumped doing\n\t * full context prediction if this field is true.\n\t */\n\tpublic boolean requiresFullContext;\n\n\t/** During SLL parsing, this is a list of predicates associated with the\n\t *  ATN configurations of the DFA state. When we have predicates,\n\t *  {@link #requiresFullContext} is {@code false} since full context prediction evaluates predicates\n\t *  on-the-fly. If this is not null, then {@link #prediction} is\n\t *  {@link ATN#INVALID_ALT_NUMBER}.\n\t *\n\t *  <p>We only use these for non-{@link #requiresFullContext} but conflicting states. That\n\t *  means we know from the context (it's $ or we don't dip into outer\n\t *  context) that it's an ambiguity not a conflict.</p>\n\t *\n\t *  <p>This list is computed by {@link ParserATNSimulator#predicateDFAState}.</p>\n\t */\n\n\tpublic PredPrediction[] predicates;\n\n\t/** Map a predicate to a predicted alternative. */\n\tpublic static class PredPrediction {\n\n\t\tpublic SemanticContext pred; // never null; at least SemanticContext.NONE\n\t\tpublic int alt;\n\t\tpublic PredPrediction(SemanticContext pred, int alt) {\n\t\t\tthis.alt = alt;\n\t\t\tthis.pred = pred;\n\t\t}\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"(\"+pred+\", \"+alt+ \")\";\n\t\t}\n\t}\n\n\tpublic DFAState() { }\n\n\tpublic DFAState(int stateNumber) { this.stateNumber = stateNumber; }\n\n\tpublic DFAState(ATNConfigSet configs) { this.configs = configs; }\n\n\t/** Get the set of all alts mentioned by all ATN configurations in this\n\t *  DFA state.\n\t */\n\tpublic Set<Integer> getAltSet() {\n\t\tSet<Integer> alts = new HashSet<Integer>();\n\t\tif ( configs!=null ) {\n\t\t\tfor (ATNConfig c : configs) {\n\t\t\t\talts.add(c.alt);\n\t\t\t}\n\t\t}\n\t\tif ( alts.isEmpty() ) return null;\n\t\treturn alts;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize(7);\n\t\thash = MurmurHash.update(hash, configs.hashCode());\n\t\thash = MurmurHash.finish(hash, 1);\n\t\treturn hash;\n\t}\n\n\t/**\n\t * Two {@link DFAState} instances are equal if their ATN configuration sets\n\t * are the same. This method is used to see if a state already exists.\n\t *\n\t * <p>Because the number of alternatives and number of ATN configurations are\n\t * finite, there is a finite number of DFA states that can be processed.\n\t * This is necessary to show that the algorithm terminates.</p>\n\t *\n\t * <p>Cannot test the DFA state numbers here because in\n\t * {@link ParserATNSimulator#addDFAState} we need to know if any other state\n\t * exists that has this exact set of ATN configurations. The\n\t * {@link #stateNumber} is irrelevant.</p>\n\t */\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\t// compare set of ATN configurations in this set with other\n\t\tif ( this==o ) return true;\n\n\t\tif (!(o instanceof DFAState)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tDFAState other = (DFAState)o;\n\t\t// TODO (sam): what to do when configs==null?\n\t\tboolean sameSet = this.configs.equals(other.configs);\n//\t\tSystem.out.println(\"DFAState.equals: \"+configs+(sameSet?\"==\":\"!=\")+other.configs);\n\t\treturn sameSet;\n\t}\n\n\t@Override\n\tpublic String toString() {\n        StringBuilder buf = new StringBuilder();\n        buf.append(stateNumber).append(\":\").append(configs);\n        if ( isAcceptState ) {\n            buf.append(\"=>\");\n            if ( predicates!=null ) {\n                buf.append(Arrays.toString(predicates));\n            }\n            else {\n                buf.append(prediction);\n            }\n        }\n\t\treturn buf.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/dfa/LexerDFASerializer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.dfa;\n\nimport org.antlr.v4.runtime.VocabularyImpl;\n\npublic class LexerDFASerializer extends DFASerializer {\n\tpublic LexerDFASerializer(DFA dfa) {\n\t\tsuper(dfa, VocabularyImpl.EMPTY_VOCABULARY);\n\t}\n\n\t@Override\n\n\tprotected String getEdgeLabel(int i) {\n\t\treturn new StringBuilder(\"'\")\n\t\t\t\t.appendCodePoint(i)\n\t\t\t\t.append(\"'\")\n\t\t\t\t.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/AbstractEqualityComparator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\n/**\n * This abstract base class is provided so performance-critical applications can\n * use virtual- instead of interface-dispatch when calling comparator methods.\n *\n * @author Sam Harwell\n */\npublic abstract class AbstractEqualityComparator<T> implements EqualityComparator<T> {\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/Array2DHashSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\n/** {@link Set} implementation with closed hashing (open addressing). */\npublic class Array2DHashSet<T> implements Set<T> {\n\tpublic static final int INITAL_CAPACITY = 16; // must be power of 2\n\tpublic static final int INITAL_BUCKET_CAPACITY = 8;\n\tpublic static final double LOAD_FACTOR = 0.75;\n\n\n\tprotected final AbstractEqualityComparator<? super T> comparator;\n\n\tprotected T[][] buckets;\n\n\t/** How many elements in set */\n\tprotected int n = 0;\n\n\tprotected int currentPrime = 1; // jump by 4 primes each expand or whatever\n\n\t/** when to expand */\n\tprotected int threshold;\n\tprotected final int initialCapacity;\n\tprotected final int initialBucketCapacity;\n\n\tpublic Array2DHashSet() {\n\t\tthis(null, INITAL_CAPACITY, INITAL_BUCKET_CAPACITY);\n\t}\n\n\tpublic Array2DHashSet(AbstractEqualityComparator<? super T> comparator) {\n\t\tthis(comparator, INITAL_CAPACITY, INITAL_BUCKET_CAPACITY);\n\t}\n\n\tpublic Array2DHashSet(AbstractEqualityComparator<? super T> comparator, int initialCapacity, int initialBucketCapacity) {\n\t\tif (comparator == null) {\n\t\t\tcomparator = ObjectEqualityComparator.INSTANCE;\n\t\t}\n\n\t\tthis.comparator = comparator;\n\t\tthis.initialCapacity = initialCapacity;\n\t\tthis.initialBucketCapacity = initialBucketCapacity;\n\t\tthis.buckets = createBuckets(initialCapacity);\n\t\tthis.threshold = (int)Math.floor(initialCapacity * LOAD_FACTOR);\n\t}\n\n\t/**\n\t * Add {@code o} to set if not there; return existing value if already\n\t * there. This method performs the same operation as {@link #add} aside from\n\t * the return value.\n\t */\n\tpublic final T getOrAdd(T o) {\n\t\tif ( n > threshold ) expand();\n\t\treturn getOrAddImpl(o);\n\t}\n\n\tprotected T getOrAddImpl(T o) {\n\t\tint b = getBucket(o);\n\t\tT[] bucket = buckets[b];\n\n\t\t// NEW BUCKET\n\t\tif ( bucket==null ) {\n\t\t\tbucket = createBucket(initialBucketCapacity);\n\t\t\tbucket[0] = o;\n\t\t\tbuckets[b] = bucket;\n\t\t\tn++;\n\t\t\treturn o;\n\t\t}\n\n\t\t// LOOK FOR IT IN BUCKET\n\t\tfor (int i=0; i<bucket.length; i++) {\n\t\t\tT existing = bucket[i];\n\t\t\tif ( existing==null ) { // empty slot; not there, add.\n\t\t\t\tbucket[i] = o;\n\t\t\t\tn++;\n\t\t\t\treturn o;\n\t\t\t}\n\t\t\tif ( comparator.equals(existing, o) ) return existing; // found existing, quit\n\t\t}\n\n\t\t// FULL BUCKET, expand and add to end\n\t\tint oldLength = bucket.length;\n\t\tbucket = Arrays.copyOf(bucket, bucket.length * 2);\n\t\tbuckets[b] = bucket;\n\t\tbucket[oldLength] = o; // add to end\n\t\tn++;\n\t\treturn o;\n\t}\n\n\tpublic T get(T o) {\n\t\tif ( o==null ) return o;\n\t\tint b = getBucket(o);\n\t\tT[] bucket = buckets[b];\n\t\tif ( bucket==null ) return null; // no bucket\n\t\tfor (T e : bucket) {\n\t\t\tif ( e==null ) return null; // empty slot; not there\n\t\t\tif ( comparator.equals(e, o) ) return e;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprotected final int getBucket(T o) {\n\t\tint hash = comparator.hashCode(o);\n\t\tint b = hash & (buckets.length-1); // assumes len is power of 2\n\t\treturn b;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\tfor (T[] bucket : buckets) {\n\t\t\tif ( bucket==null ) continue;\n\t\t\tfor (T o : bucket) {\n\t\t\t\tif ( o==null ) break;\n\t\t\t\thash = MurmurHash.update(hash, comparator.hashCode(o));\n\t\t\t}\n\t\t}\n\n\t\thash = MurmurHash.finish(hash, size());\n\t\treturn hash;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == this) return true;\n\t\tif ( !(o instanceof Array2DHashSet) ) return false;\n\t\tArray2DHashSet<?> other = (Array2DHashSet<?>)o;\n\t\tif ( other.size() != size() ) return false;\n\t\tboolean same = this.containsAll(other);\n\t\treturn same;\n\t}\n\n\tprotected void expand() {\n\t\tT[][] old = buckets;\n\t\tcurrentPrime += 4;\n\t\tint newCapacity = buckets.length * 2;\n\t\tT[][] newTable = createBuckets(newCapacity);\n\t\tint[] newBucketLengths = new int[newTable.length];\n\t\tbuckets = newTable;\n\t\tthreshold = (int)(newCapacity * LOAD_FACTOR);\n//\t\tSystem.out.println(\"new size=\"+newCapacity+\", thres=\"+threshold);\n\t\t// rehash all existing entries\n\t\tint oldSize = size();\n\t\tfor (T[] bucket : old) {\n\t\t\tif ( bucket==null ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (T o : bucket) {\n\t\t\t\tif ( o==null ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tint b = getBucket(o);\n\t\t\t\tint bucketLength = newBucketLengths[b];\n\t\t\t\tT[] newBucket;\n\t\t\t\tif (bucketLength == 0) {\n\t\t\t\t\t// new bucket\n\t\t\t\t\tnewBucket = createBucket(initialBucketCapacity);\n\t\t\t\t\tnewTable[b] = newBucket;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnewBucket = newTable[b];\n\t\t\t\t\tif (bucketLength == newBucket.length) {\n\t\t\t\t\t\t// expand\n\t\t\t\t\t\tnewBucket = Arrays.copyOf(newBucket, newBucket.length * 2);\n\t\t\t\t\t\tnewTable[b] = newBucket;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tnewBucket[bucketLength] = o;\n\t\t\t\tnewBucketLengths[b]++;\n\t\t\t}\n\t\t}\n\n\t\tassert n == oldSize;\n\t}\n\n\t@Override\n\tpublic final boolean add(T t) {\n\t\tT existing = getOrAdd(t);\n\t\treturn existing==t;\n\t}\n\n\t@Override\n\tpublic final int size() {\n\t\treturn n;\n\t}\n\n\t@Override\n\tpublic final boolean isEmpty() {\n\t\treturn n==0;\n\t}\n\n\t@Override\n\tpublic final boolean contains(Object o) {\n\t\treturn containsFast(asElementType(o));\n\t}\n\n\tpublic boolean containsFast(T obj) {\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn get(obj) != null;\n\t}\n\n\t@Override\n\tpublic Iterator<T> iterator() {\n\t\treturn new SetIterator(toArray());\n\t}\n\n\t@Override\n\tpublic T[] toArray() {\n\t\tT[] a = createBucket(size());\n\t\tint i = 0;\n\t\tfor (T[] bucket : buckets) {\n\t\t\tif ( bucket==null ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (T o : bucket) {\n\t\t\t\tif ( o==null ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\ta[i++] = o;\n\t\t\t}\n\t\t}\n\n\t\treturn a;\n\t}\n\n\t@Override\n\tpublic <U> U[] toArray(U[] a) {\n\t\tif (a.length < size()) {\n\t\t\ta = Arrays.copyOf(a, size());\n\t\t}\n\n\t\tint i = 0;\n\t\tfor (T[] bucket : buckets) {\n\t\t\tif ( bucket==null ) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (T o : bucket) {\n\t\t\t\tif ( o==null ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t@SuppressWarnings(\"unchecked\") // array store will check this\n\t\t\t\tU targetElement = (U)o;\n\t\t\t\ta[i++] = targetElement;\n\t\t\t}\n\t\t}\n\t\treturn a;\n\t}\n\n\t@Override\n\tpublic final boolean remove(Object o) {\n\t\treturn removeFast(asElementType(o));\n\t}\n\n\tpublic boolean removeFast(T obj) {\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tint b = getBucket(obj);\n\t\tT[] bucket = buckets[b];\n\t\tif ( bucket==null ) {\n\t\t\t// no bucket\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int i=0; i<bucket.length; i++) {\n\t\t\tT e = bucket[i];\n\t\t\tif ( e==null ) {\n\t\t\t\t// empty slot; not there\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ( comparator.equals(e, obj) ) {          // found it\n\t\t\t\t// shift all elements to the right down one\n\t\t\t\tSystem.arraycopy(bucket, i+1, bucket, i, bucket.length-i-1);\n\t\t\t\tbucket[bucket.length - 1] = null;\n\t\t\t\tn--;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean containsAll(Collection<?> collection) {\n\t\tif ( collection instanceof Array2DHashSet ) {\n\t\t\tArray2DHashSet<?> s = (Array2DHashSet<?>)collection;\n\t\t\tfor (Object[] bucket : s.buckets) {\n\t\t\t\tif ( bucket==null ) continue;\n\t\t\t\tfor (Object o : bucket) {\n\t\t\t\t\tif ( o==null ) break;\n\t\t\t\t\tif ( !this.containsFast(asElementType(o)) ) return false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (Object o : collection) {\n\t\t\t\tif ( !this.containsFast(asElementType(o)) ) return false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean addAll(Collection<? extends T> c) {\n\t\tboolean changed = false;\n\t\tfor (T o : c) {\n\t\t\tT existing = getOrAdd(o);\n\t\t\tif ( existing!=o ) changed=true;\n\t\t}\n\t\treturn changed;\n\t}\n\n\t@Override\n\tpublic boolean retainAll(Collection<?> c) {\n\t\tint newsize = 0;\n\t\tfor (T[] bucket : buckets) {\n\t\t\tif (bucket == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint i;\n\t\t\tint j;\n\t\t\tfor (i = 0, j = 0; i < bucket.length; i++) {\n\t\t\t\tif (bucket[i] == null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (!c.contains(bucket[i])) {\n\t\t\t\t\t// removed\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// keep\n\t\t\t\tif (i != j) {\n\t\t\t\t\tbucket[j] = bucket[i];\n\t\t\t\t}\n\n\t\t\t\tj++;\n\t\t\t\tnewsize++;\n\t\t\t}\n\n\t\t\tnewsize += j;\n\n\t\t\twhile (j < i) {\n\t\t\t\tbucket[j] = null;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\n\t\tboolean changed = newsize != n;\n\t\tn = newsize;\n\t\treturn changed;\n\t}\n\n\t@Override\n\tpublic boolean removeAll(Collection<?> c) {\n\t\tboolean changed = false;\n\t\tfor (Object o : c) {\n\t\t\tchanged |= removeFast(asElementType(o));\n\t\t}\n\n\t\treturn changed;\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tn = 0;\n\t\tbuckets = createBuckets(this.initialCapacity);\n\t\tthreshold = (int)Math.floor(this.initialCapacity * LOAD_FACTOR);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tif ( size()==0 ) return \"{}\";\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append('{');\n\t\tboolean first = true;\n\t\tfor (T[] bucket : buckets) {\n\t\t\tif ( bucket==null ) continue;\n\t\t\tfor (T o : bucket) {\n\t\t\t\tif ( o==null ) break;\n\t\t\t\tif ( first ) first=false;\n\t\t\t\telse buf.append(\", \");\n\t\t\t\tbuf.append(o.toString());\n\t\t\t}\n\t\t}\n\t\tbuf.append('}');\n\t\treturn buf.toString();\n\t}\n\n\tpublic String toTableString() {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (T[] bucket : buckets) {\n\t\t\tif ( bucket==null ) {\n\t\t\t\tbuf.append(\"null\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbuf.append('[');\n\t\t\tboolean first = true;\n\t\t\tfor (T o : bucket) {\n\t\t\t\tif ( first ) first=false;\n\t\t\t\telse buf.append(\" \");\n\t\t\t\tif ( o==null ) buf.append(\"_\");\n\t\t\t\telse buf.append(o.toString());\n\t\t\t}\n\t\t\tbuf.append(\"]\\n\");\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\t/**\n\t * Return {@code o} as an instance of the element type {@code T}. If\n\t * {@code o} is non-null but known to not be an instance of {@code T}, this\n\t * method returns {@code null}. The base implementation does not perform any\n\t * type checks; override this method to provide strong type checks for the\n\t * {@link #contains} and {@link #remove} methods to ensure the arguments to\n\t * the {@link EqualityComparator} for the set always have the expected\n\t * types.\n\t *\n\t * @param o the object to try and cast to the element type of the set\n\t * @return {@code o} if it could be an instance of {@code T}, otherwise\n\t * {@code null}.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T asElementType(Object o) {\n\t\treturn (T)o;\n\t}\n\n\t/**\n\t * Return an array of {@code T[]} with length {@code capacity}.\n\t *\n\t * @param capacity the length of the array to return\n\t * @return the newly constructed array\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T[][] createBuckets(int capacity) {\n\t\treturn (T[][])new Object[capacity][];\n\t}\n\n\t/**\n\t * Return an array of {@code T} with length {@code capacity}.\n\t *\n\t * @param capacity the length of the array to return\n\t * @return the newly constructed array\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprotected T[] createBucket(int capacity) {\n\t\treturn (T[])new Object[capacity];\n\t}\n\n\tprotected class SetIterator implements Iterator<T> {\n\t\tfinal T[] data;\n\t\tint nextIndex = 0;\n\t\tboolean removed = true;\n\n\t\tpublic SetIterator(T[] data) {\n\t\t\tthis.data = data;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\treturn nextIndex < data.length;\n\t\t}\n\n\t\t@Override\n\t\tpublic T next() {\n\t\t\tif (!hasNext()) {\n\t\t\t\tthrow new NoSuchElementException();\n\t\t\t}\n\n\t\t\tremoved = false;\n\t\t\treturn data[nextIndex++];\n\t\t}\n\n\t\t@Override\n\t\tpublic void remove() {\n\t\t\tif (removed) {\n\t\t\t\tthrow new IllegalStateException();\n\t\t\t}\n\n\t\t\tArray2DHashSet.this.remove(data[nextIndex - 1]);\n\t\t\tremoved = true;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/DoubleKeyMap.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.util.Collection;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.Set;\n\n/** Sometimes we need to map a key to a value but key is two pieces of data.\n *  This nested hash table saves creating a single key each time we access\n *  map; avoids mem creation.\n */\npublic class DoubleKeyMap<Key1, Key2, Value> {\n\tMap<Key1, Map<Key2, Value>> data = new LinkedHashMap<Key1, Map<Key2, Value>>();\n\n\tpublic Value put(Key1 k1, Key2 k2, Value v) {\n\t\tMap<Key2, Value> data2 = data.get(k1);\n\t\tValue prev = null;\n\t\tif ( data2==null ) {\n\t\t\tdata2 = new LinkedHashMap<Key2, Value>();\n\t\t\tdata.put(k1, data2);\n\t\t}\n\t\telse {\n\t\t\tprev = data2.get(k2);\n\t\t}\n\t\tdata2.put(k2, v);\n\t\treturn prev;\n\t}\n\n\tpublic Value get(Key1 k1, Key2 k2) {\n\t\tMap<Key2, Value> data2 = data.get(k1);\n\t\tif ( data2==null ) return null;\n\t\treturn data2.get(k2);\n\t}\n\n\tpublic Map<Key2, Value> get(Key1 k1) { return data.get(k1); }\n\n\t/** Get all values associated with primary key */\n\tpublic Collection<Value> values(Key1 k1) {\n\t\tMap<Key2, Value> data2 = data.get(k1);\n\t\tif ( data2==null ) return null;\n\t\treturn data2.values();\n\t}\n\n\t/** get all primary keys */\n\tpublic Set<Key1> keySet() {\n\t\treturn data.keySet();\n\t}\n\n\t/** get all secondary keys associated with a primary key */\n\tpublic Set<Key2> keySet(Key1 k1) {\n\t\tMap<Key2, Value> data2 = data.get(k1);\n\t\tif ( data2==null ) return null;\n\t\treturn data2.keySet();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/EqualityComparator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\n/**\n * This interface provides an abstract concept of object equality independent of\n * {@link Object#equals} (object equality) and the {@code ==} operator\n * (reference equality). It can be used to provide algorithm-specific unordered\n * comparisons without requiring changes to the object itself.\n *\n * @author Sam Harwell\n */\npublic interface EqualityComparator<T> {\n\n\t/**\n\t * This method returns a hash code for the specified object.\n\t *\n\t * @param obj The object.\n\t * @return The hash code for {@code obj}.\n\t */\n\tint hashCode(T obj);\n\n\t/**\n\t * This method tests if two objects are equal.\n\t *\n\t * @param a The first object to compare.\n\t * @param b The second object to compare.\n\t * @return {@code true} if {@code a} equals {@code b}, otherwise {@code false}.\n\t */\n\tboolean equals(T a, T b);\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/FlexibleHashMap.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n/** A limited map (many unsupported operations) that lets me use\n *  varying hashCode/equals.\n */\npublic class FlexibleHashMap<K,V> implements Map<K, V> {\n\tpublic static final int INITAL_CAPACITY = 16; // must be power of 2\n\tpublic static final int INITAL_BUCKET_CAPACITY = 8;\n\tpublic static final double LOAD_FACTOR = 0.75;\n\n\tpublic static class Entry<K, V> {\n\t\tpublic final K key;\n\t\tpublic V value;\n\n\t\tpublic Entry(K key, V value) { this.key = key; this.value = value; }\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn key.toString()+\":\"+value.toString();\n\t\t}\n\t}\n\n\n\tprotected final AbstractEqualityComparator<? super K> comparator;\n\n\tprotected LinkedList<Entry<K, V>>[] buckets;\n\n\t/** How many elements in set */\n\tprotected int n = 0;\n\n\tprotected int currentPrime = 1; // jump by 4 primes each expand or whatever\n\n\t/** when to expand */\n\tprotected int threshold;\n\tprotected final int initialCapacity;\n\tprotected final int initialBucketCapacity;\n\n\tpublic FlexibleHashMap() {\n\t\tthis(null, INITAL_CAPACITY, INITAL_BUCKET_CAPACITY);\n\t}\n\n\tpublic FlexibleHashMap(AbstractEqualityComparator<? super K> comparator) {\n\t\tthis(comparator, INITAL_CAPACITY, INITAL_BUCKET_CAPACITY);\n\t}\n\n\tpublic FlexibleHashMap(AbstractEqualityComparator<? super K> comparator, int initialCapacity, int initialBucketCapacity) {\n\t\tif (comparator == null) {\n\t\t\tcomparator = ObjectEqualityComparator.INSTANCE;\n\t\t}\n\n\t\tthis.comparator = comparator;\n\t\tthis.initialCapacity = initialCapacity;\n\t\tthis.initialBucketCapacity = initialBucketCapacity;\n\t\tthis.threshold = (int)Math.floor(initialCapacity * LOAD_FACTOR);\n\t\tthis.buckets = createEntryListArray(initialBucketCapacity);\n\t}\n\n\tprivate static <K, V> LinkedList<Entry<K, V>>[] createEntryListArray(int length) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tLinkedList<Entry<K, V>>[] result = (LinkedList<Entry<K, V>>[])new LinkedList<?>[length];\n\t\treturn result;\n\t}\n\n\tprotected int getBucket(K key) {\n\t\tint hash = comparator.hashCode(key);\n\t\tint b = hash & (buckets.length-1); // assumes len is power of 2\n\t\treturn b;\n\t}\n\n\t@Override\n\tpublic V get(Object key) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tK typedKey = (K)key;\n\t\tif ( key==null ) return null;\n\t\tint b = getBucket(typedKey);\n\t\tLinkedList<Entry<K, V>> bucket = buckets[b];\n\t\tif ( bucket==null ) return null; // no bucket\n\t\tfor (Entry<K, V> e : bucket) {\n\t\t\tif ( comparator.equals(e.key, typedKey) ) {\n\t\t\t\treturn e.value;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic V put(K key, V value) {\n\t\tif ( key==null ) return null;\n\t\tif ( n > threshold ) expand();\n\t\tint b = getBucket(key);\n\t\tLinkedList<Entry<K, V>> bucket = buckets[b];\n\t\tif ( bucket==null ) {\n\t\t\tbucket = buckets[b] = new LinkedList<Entry<K, V>>();\n\t\t}\n\t\tfor (Entry<K, V> e : bucket) {\n\t\t\tif ( comparator.equals(e.key, key) ) {\n\t\t\t\tV prev = e.value;\n\t\t\t\te.value = value;\n\t\t\t\tn++;\n\t\t\t\treturn prev;\n\t\t\t}\n\t\t}\n\t\t// not there\n\t\tbucket.add(new Entry<K, V>(key, value));\n\t\tn++;\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic V remove(Object key) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic void putAll(Map<? extends K, ? extends V> m) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic Set<K> keySet() {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic Collection<V> values() {\n\t\tList<V> a = new ArrayList<V>(size());\n\t\tfor (LinkedList<Entry<K, V>> bucket : buckets) {\n\t\t\tif ( bucket==null ) continue;\n\t\t\tfor (Entry<K, V> e : bucket) {\n\t\t\t\ta.add(e.value);\n\t\t\t}\n\t\t}\n\t\treturn a;\n\t}\n\n\t@Override\n\tpublic Set<Map.Entry<K, V>> entrySet() {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic boolean containsKey(Object key) {\n\t\treturn get(key)!=null;\n\t}\n\n\t@Override\n\tpublic boolean containsValue(Object value) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\tfor (LinkedList<Entry<K, V>> bucket : buckets) {\n\t\t\tif ( bucket==null ) continue;\n\t\t\tfor (Entry<K, V> e : bucket) {\n\t\t\t\tif ( e==null ) break;\n\t\t\t\thash = MurmurHash.update(hash, comparator.hashCode(e.key));\n\t\t\t}\n\t\t}\n\n\t\thash = MurmurHash.finish(hash, size());\n\t\treturn hash;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\tprotected void expand() {\n\t\tLinkedList<Entry<K, V>>[] old = buckets;\n\t\tcurrentPrime += 4;\n\t\tint newCapacity = buckets.length * 2;\n\t\tLinkedList<Entry<K, V>>[] newTable = createEntryListArray(newCapacity);\n\t\tbuckets = newTable;\n\t\tthreshold = (int)(newCapacity * LOAD_FACTOR);\n//\t\tSystem.out.println(\"new size=\"+newCapacity+\", thres=\"+threshold);\n\t\t// rehash all existing entries\n\t\tint oldSize = size();\n\t\tfor (LinkedList<Entry<K, V>> bucket : old) {\n\t\t\tif ( bucket==null ) continue;\n\t\t\tfor (Entry<K, V> e : bucket) {\n\t\t\t\tif ( e==null ) break;\n\t\t\t\tput(e.key, e.value);\n\t\t\t}\n\t\t}\n\t\tn = oldSize;\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn n;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn n==0;\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tbuckets = createEntryListArray(this.initialCapacity);\n\t\tn = 0;\n\t\tthreshold = (int)Math.floor(this.initialCapacity * LOAD_FACTOR);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tif ( size()==0 ) return \"{}\";\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append('{');\n\t\tboolean first = true;\n\t\tfor (LinkedList<Entry<K, V>> bucket : buckets) {\n\t\t\tif ( bucket==null ) continue;\n\t\t\tfor (Entry<K, V> e : bucket) {\n\t\t\t\tif ( e==null ) break;\n\t\t\t\tif ( first ) first=false;\n\t\t\t\telse buf.append(\", \");\n\t\t\t\tbuf.append(e.toString());\n\t\t\t}\n\t\t}\n\t\tbuf.append('}');\n\t\treturn buf.toString();\n\t}\n\n\tpublic String toTableString() {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (LinkedList<Entry<K, V>> bucket : buckets) {\n\t\t\tif ( bucket==null ) {\n\t\t\t\tbuf.append(\"null\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbuf.append('[');\n\t\t\tboolean first = true;\n\t\t\tfor (Entry<K, V> e : bucket) {\n\t\t\t\tif ( first ) first=false;\n\t\t\t\telse buf.append(\" \");\n\t\t\t\tif ( e==null ) buf.append(\"_\");\n\t\t\t\telse buf.append(e.toString());\n\t\t\t}\n\t\t\tbuf.append(\"]\\n\");\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tFlexibleHashMap<String,Integer> map = new FlexibleHashMap<String,Integer>();\n\t\tmap.put(\"hi\", 1);\n\t\tmap.put(\"mom\", 2);\n\t\tmap.put(\"foo\", 3);\n\t\tmap.put(\"ach\", 4);\n\t\tmap.put(\"cbba\", 5);\n\t\tmap.put(\"d\", 6);\n\t\tmap.put(\"edf\", 7);\n\t\tmap.put(\"mom\", 8);\n\t\tmap.put(\"hi\", 9);\n\t\tSystem.out.println(map);\n\t\tSystem.out.println(map.toTableString());\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/IntSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\n\nimport java.util.List;\n\n/**\n * A generic set of integers.\n *\n * @see IntervalSet\n */\npublic interface IntSet {\n\t/**\n\t * Adds the specified value to the current set.\n\t *\n\t * @param el the value to add\n\t *\n\t * @exception IllegalStateException if the current set is read-only\n\t */\n\tvoid add(int el);\n\n\t/**\n\t * Modify the current {@link IntSet} object to contain all elements that are\n\t * present in itself, the specified {@code set}, or both.\n\t *\n\t * @param set The set to add to the current set. A {@code null} argument is\n\t * treated as though it were an empty set.\n\t * @return {@code this} (to support chained calls)\n\t *\n\t * @exception IllegalStateException if the current set is read-only\n\t */\n\n\tIntSet addAll(IntSet set);\n\n\t/**\n\t * Return a new {@link IntSet} object containing all elements that are\n\t * present in both the current set and the specified set {@code a}.\n\t *\n\t * @param a The set to intersect with the current set. A {@code null}\n\t * argument is treated as though it were an empty set.\n\t * @return A new {@link IntSet} instance containing the intersection of the\n\t * current set and {@code a}. The value {@code null} may be returned in\n\t * place of an empty result set.\n\t */\n\n\tIntSet and(IntSet a);\n\n\t/**\n\t * Return a new {@link IntSet} object containing all elements that are\n\t * present in {@code elements} but not present in the current set. The\n\t * following expressions are equivalent for input non-null {@link IntSet}\n\t * instances {@code x} and {@code y}.\n\t *\n\t * <ul>\n\t * <li>{@code x.complement(y)}</li>\n\t * <li>{@code y.subtract(x)}</li>\n\t * </ul>\n\t *\n\t * @param elements The set to compare with the current set. A {@code null}\n\t * argument is treated as though it were an empty set.\n\t * @return A new {@link IntSet} instance containing the elements present in\n\t * {@code elements} but not present in the current set. The value\n\t * {@code null} may be returned in place of an empty result set.\n\t */\n\n\tIntSet complement(IntSet elements);\n\n\t/**\n\t * Return a new {@link IntSet} object containing all elements that are\n\t * present in the current set, the specified set {@code a}, or both.\n\t *\n\t * <p>\n\t * This method is similar to {@link #addAll(IntSet)}, but returns a new\n\t * {@link IntSet} instance instead of modifying the current set.</p>\n\t *\n\t * @param a The set to union with the current set. A {@code null} argument\n\t * is treated as though it were an empty set.\n\t * @return A new {@link IntSet} instance containing the union of the current\n\t * set and {@code a}. The value {@code null} may be returned in place of an\n\t * empty result set.\n\t */\n\n\tIntSet or(IntSet a);\n\n\t/**\n\t * Return a new {@link IntSet} object containing all elements that are\n\t * present in the current set but not present in the input set {@code a}.\n\t * The following expressions are equivalent for input non-null\n\t * {@link IntSet} instances {@code x} and {@code y}.\n\t *\n\t * <ul>\n\t * <li>{@code y.subtract(x)}</li>\n\t * <li>{@code x.complement(y)}</li>\n\t * </ul>\n\t *\n\t * @param a The set to compare with the current set. A {@code null}\n\t * argument is treated as though it were an empty set.\n\t * @return A new {@link IntSet} instance containing the elements present in\n\t * {@code elements} but not present in the current set. The value\n\t * {@code null} may be returned in place of an empty result set.\n\t */\n\n\tIntSet subtract(IntSet a);\n\n\t/**\n\t * Return the total number of elements represented by the current set.\n\t *\n\t * @return the total number of elements represented by the current set,\n\t * regardless of the manner in which the elements are stored.\n\t */\n\tint size();\n\n\t/**\n\t * Returns {@code true} if this set contains no elements.\n\t *\n\t * @return {@code true} if the current set contains no elements; otherwise,\n\t * {@code false}.\n\t */\n\tboolean isNil();\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tboolean equals(Object obj);\n\n\t/**\n\t * Returns {@code true} if the set contains the specified element.\n\t *\n\t * @param el The element to check for.\n\t * @return {@code true} if the set contains {@code el}; otherwise {@code false}.\n\t */\n\tboolean contains(int el);\n\n\t/**\n\t * Removes the specified value from the current set. If the current set does\n\t * not contain the element, no changes are made.\n\t *\n\t * @param el the value to remove\n\t *\n\t * @exception IllegalStateException if the current set is read-only\n\t */\n\tvoid remove(int el);\n\n\t/**\n\t * Return a list containing the elements represented by the current set. The\n\t * list is returned in ascending numerical order.\n\t *\n\t * @return A list containing all element present in the current set, sorted\n\t * in ascending numerical order.\n\t */\n\n\tList<Integer> toList();\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tString toString();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/IntegerList.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.*;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class IntegerList {\n\n\tprivate final static int[] EMPTY_DATA = new int[0];\n\n\tprivate static final int INITIAL_SIZE = 4;\n\tprivate static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;\n\n\n\tprivate int[] _data;\n\n\tprivate int _size;\n\n\tpublic IntegerList() {\n\t\t_data = EMPTY_DATA;\n\t}\n\n\tpublic IntegerList(int capacity) {\n\t\tif (capacity < 0) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\n\t\tif (capacity == 0) {\n\t\t\t_data = EMPTY_DATA;\n\t\t}\n\t\telse {\n\t\t\t_data = new int[capacity];\n\t\t}\n\t}\n\n\tpublic IntegerList(IntegerList list) {\n\t\t_data = list._data.clone();\n\t\t_size = list._size;\n\t}\n\n\tpublic IntegerList(Collection<Integer> list) {\n\t\tthis(list.size());\n\t\tfor (Integer value : list) {\n\t\t\tadd(value);\n\t\t}\n\t}\n\n\tpublic final void add(int value) {\n\t\tif (_data.length == _size) {\n\t\t\tensureCapacity(_size + 1);\n\t\t}\n\n\t\t_data[_size] = value;\n\t\t_size++;\n\t}\n\n\tpublic final void addAll(int[] array) {\n\t\tensureCapacity(_size + array.length);\n\t\tSystem.arraycopy(array, 0, _data, _size, array.length);\n\t\t_size += array.length;\n\t}\n\n\tpublic final void addAll(IntegerList list) {\n\t\tensureCapacity(_size + list._size);\n\t\tSystem.arraycopy(list._data, 0, _data, _size, list._size);\n\t\t_size += list._size;\n\t}\n\n\tpublic final void addAll(Collection<Integer> list) {\n\t\tensureCapacity(_size + list.size());\n\t\tint current = 0;\n    \t\tfor (int x : list) {\n      \t\t\t_data[_size + current] = x;\n      \t\t\tcurrent++;\n    \t\t}\n    \t\t_size += list.size();\n\t}\n\n\tpublic final int get(int index) {\n\t\tif (index < 0 || index >= _size) {\n\t\t\tthrow new IndexOutOfBoundsException();\n\t\t}\n\n\t\treturn _data[index];\n\t}\n\n\tpublic final boolean contains(int value) {\n\t\tfor (int i = 0; i < _size; i++) {\n\t\t\tif (_data[i] == value) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic final int set(int index, int value) {\n\t\tif (index < 0 || index >= _size) {\n\t\t\tthrow new IndexOutOfBoundsException();\n\t\t}\n\n\t\tint previous = _data[index];\n\t\t_data[index] = value;\n\t\treturn previous;\n\t}\n\n\tpublic final int removeAt(int index) {\n\t\tint value = get(index);\n\t\tSystem.arraycopy(_data, index + 1, _data, index, _size - index - 1);\n\t\t_data[_size - 1] = 0;\n\t\t_size--;\n\t\treturn value;\n\t}\n\n\tpublic final void removeRange(int fromIndex, int toIndex) {\n\t\tif (fromIndex < 0 || toIndex < 0 || fromIndex > _size || toIndex > _size) {\n\t\t\tthrow new IndexOutOfBoundsException();\n\t\t}\n\t\tif (fromIndex > toIndex) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\n\t\tSystem.arraycopy(_data, toIndex, _data, fromIndex, _size - toIndex);\n\t\tArrays.fill(_data, _size - (toIndex - fromIndex), _size, 0);\n\t\t_size -= (toIndex - fromIndex);\n\t}\n\n\tpublic final boolean isEmpty() {\n\t\treturn _size == 0;\n\t}\n\n\tpublic final int size() {\n\t\treturn _size;\n\t}\n\n\tpublic final void trimToSize() {\n\t\tif (_data.length == _size) {\n\t\t\treturn;\n\t\t}\n\n\t\t_data = Arrays.copyOf(_data, _size);\n\t}\n\n\tpublic final void clear() {\n\t\tArrays.fill(_data, 0, _size, 0);\n\t\t_size = 0;\n\t}\n\n\tpublic final int[] toArray() {\n\t\tif (_size == 0) {\n\t\t\treturn EMPTY_DATA;\n\t\t}\n\n\t\treturn Arrays.copyOf(_data, _size);\n\t}\n\n\tpublic final void sort() {\n\t\tArrays.sort(_data, 0, _size);\n\t}\n\n\t/**\n\t * Compares the specified object with this list for equality.  Returns\n\t * {@code true} if and only if the specified object is also an {@link IntegerList},\n\t * both lists have the same size, and all corresponding pairs of elements in\n\t * the two lists are equal.  In other words, two lists are defined to be\n\t * equal if they contain the same elements in the same order.\n\t * <p>\n\t * This implementation first checks if the specified object is this\n\t * list. If so, it returns {@code true}; if not, it checks if the\n\t * specified object is an {@link IntegerList}. If not, it returns {@code false};\n\t * if so, it checks the size of both lists. If the lists are not the same size,\n\t * it returns {@code false}; otherwise it iterates over both lists, comparing\n\t * corresponding pairs of elements.  If any comparison returns {@code false},\n\t * this method returns {@code false}.\n\t *\n\t * @param o the object to be compared for equality with this list\n\t * @return {@code true} if the specified object is equal to this list\n\t */\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == this) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!(o instanceof IntegerList)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tIntegerList other = (IntegerList)o;\n\t\tif (_size != other._size) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int i = 0; i < _size; i++) {\n\t\t\tif (_data[i] != other._data[i]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns the hash code value for this list.\n\t *\n\t * <p>This implementation uses exactly the code that is used to define the\n\t * list hash function in the documentation for the {@link List#hashCode}\n\t * method.</p>\n\t *\n\t * @return the hash code value for this list\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\tint hashCode = 1;\n\t\tfor (int i = 0; i < _size; i++) {\n\t\t\thashCode = 31*hashCode + _data[i];\n\t\t}\n\n\t\treturn hashCode;\n\t}\n\n\t/**\n\t * Returns a string representation of this list.\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn Arrays.toString(toArray());\n\t}\n\n\tpublic final int binarySearch(int key) {\n\t\treturn Arrays.binarySearch(_data, 0, _size, key);\n\t}\n\n\tpublic final int binarySearch(int fromIndex, int toIndex, int key) {\n\t\tif (fromIndex < 0 || toIndex < 0 || fromIndex > _size || toIndex > _size) {\n\t\t\tthrow new IndexOutOfBoundsException();\n\t\t}\n\t\tif (fromIndex > toIndex) {\n        \t\tthrow new IllegalArgumentException();\n\t\t}\n\n\t\treturn Arrays.binarySearch(_data, fromIndex, toIndex, key);\n\t}\n\n\tprivate void ensureCapacity(int capacity) {\n\t\tif (capacity < 0 || capacity > MAX_ARRAY_SIZE) {\n\t\t\tthrow new OutOfMemoryError();\n\t\t}\n\n\t\tint newLength;\n\t\tif (_data.length == 0) {\n\t\t\tnewLength = INITIAL_SIZE;\n\t\t}\n\t\telse {\n\t\t\tnewLength = _data.length;\n\t\t}\n\n\t\twhile (newLength < capacity) {\n\t\t\tnewLength = newLength * 2;\n\t\t\tif (newLength < 0 || newLength > MAX_ARRAY_SIZE) {\n\t\t\t\tnewLength = MAX_ARRAY_SIZE;\n\t\t\t}\n\t\t}\n\n\t\t_data = Arrays.copyOf(_data, newLength);\n\t}\n\n\t/** Convert the int list to a char array where values > 0x7FFFF take 2 bytes. TODO?????\n\t *  If all values are less\n\t *  than the 0x7FFF 16-bit code point limit (1 bit taken to indicatethen this is just a char array\n\t *  of 16-bit char as usual. For values in the supplementary range, encode\n\t * them as two UTF-16 code units.\n\t */\n\tpublic final char[] toCharArray() {\n\t\t// Optimize for the common case (all data values are\n\t\t// < 0xFFFF) to avoid an extra scan\n\t\tchar[] resultArray = new char[_size];\n\t\tint resultIdx = 0;\n\t\tboolean calculatedPreciseResultSize = false;\n\t\tfor (int i = 0; i < _size; i++) {\n\t\t\tint codePoint = _data[i];\n\t\t\t// Calculate the precise result size if we encounter\n\t\t\t// a code point > 0xFFFF\n\t\t\tif (!calculatedPreciseResultSize &&\n\t\t\t    Character.isSupplementaryCodePoint(codePoint)) {\n\t\t\t\tresultArray = Arrays.copyOf(resultArray, charArraySize());\n\t\t\t\tcalculatedPreciseResultSize = true;\n\t\t\t}\n\t\t\t// This will throw IllegalArgumentException if\n\t\t\t// the code point is not a valid Unicode code point\n\t\t\tint charsWritten = Character.toChars(codePoint, resultArray, resultIdx);\n\t\t\tresultIdx += charsWritten;\n\t\t}\n\t\treturn resultArray;\n\t}\n\n\tprivate int charArraySize() {\n\t\tint result = 0;\n\t\tfor (int i = 0; i < _size; i++) {\n\t\t\tresult += Character.charCount(_data[i]);\n\t\t}\n\t\treturn result;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/IntegerStack.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class IntegerStack extends IntegerList {\n\n\tpublic IntegerStack() {\n\t}\n\n\tpublic IntegerStack(int capacity) {\n\t\tsuper(capacity);\n\t}\n\n\tpublic IntegerStack(IntegerStack list) {\n\t\tsuper(list);\n\t}\n\n\tpublic final void push(int value) {\n\t\tadd(value);\n\t}\n\n\tpublic final int pop() {\n\t\treturn removeAt(size() - 1);\n\t}\n\n\tpublic final int peek() {\n\t\treturn get(size() - 1);\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/InterpreterDataReader.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.dfa.DFA;\n\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.io.BufferedReader;\nimport java.io.FileReader;\n\n// A class to read plain text interpreter data produced by ANTLR.\npublic class InterpreterDataReader {\n\n\tpublic static class InterpreterData {\n\t  ATN atn;\n\t  Vocabulary vocabulary;\n\t  List<String> ruleNames;\n\t  List<String> channels; // Only valid for lexer grammars.\n\t  List<String> modes; // ditto\n\t};\n\n\t/**\n\t * The structure of the data file is very simple. Everything is line based with empty lines\n\t * separating the different parts. For lexers the layout is:\n\t * token literal names:\n\t * ...\n\t *\n\t * token symbolic names:\n\t * ...\n\t *\n\t * rule names:\n\t * ...\n\t *\n\t * channel names:\n\t * ...\n\t *\n\t * mode names:\n\t * ...\n\t *\n\t * atn:\n\t * <a single line with comma separated int values> enclosed in a pair of squared brackets.\n\t *\n\t * Data for a parser does not contain channel and mode names.\n\t */\n\tpublic static InterpreterData parseFile(String fileName) {\n\t\tInterpreterData result = new InterpreterData();\n\t\tresult.ruleNames = new ArrayList<String>();\n\n\t\ttry (BufferedReader br = new BufferedReader(new FileReader(fileName))) {\n\t\t    String line;\n\t\t  \tList<String> literalNames = new ArrayList<String>();\n\t\t  \tList<String> symbolicNames = new ArrayList<String>();\n\n\t\t\tline = br.readLine();\n\t\t\tif ( !line.equals(\"token literal names:\") )\n\t\t\t\tthrow new RuntimeException(\"Unexpected data entry\");\n\t\t    while ((line = br.readLine()) != null) {\n\t\t       if ( line.isEmpty() )\n\t\t\t\t\tbreak;\n\t\t\t\tliteralNames.add(line.equals(\"null\") ? \"\" : line);\n\t\t    }\n\n\t\t\tline = br.readLine();\n\t\t\tif ( !line.equals(\"token symbolic names:\") )\n\t\t\t\tthrow new RuntimeException(\"Unexpected data entry\");\n\t\t    while ((line = br.readLine()) != null) {\n\t\t       if ( line.isEmpty() )\n\t\t\t\t\tbreak;\n\t\t\t\tsymbolicNames.add(line.equals(\"null\") ? \"\" : line);\n\t\t    }\n\n\t\t  \tresult.vocabulary = new VocabularyImpl(literalNames.toArray(new String[0]), symbolicNames.toArray(new String[0]));\n\n\t\t\tline = br.readLine();\n\t\t\tif ( !line.equals(\"rule names:\") )\n\t\t\t\tthrow new RuntimeException(\"Unexpected data entry\");\n\t\t    while ((line = br.readLine()) != null) {\n\t\t       if ( line.isEmpty() )\n\t\t\t\t\tbreak;\n\t\t\t\tresult.ruleNames.add(line);\n\t\t    }\n\n\t\t\tline = br.readLine();\n\t\t\tif ( line.equals(\"channel names:\") ) { // Additional lexer data.\n\t\t\t\tresult.channels = new ArrayList<String>();\n\t\t\t    while ((line = br.readLine()) != null) {\n\t\t\t       if ( line.isEmpty() )\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tresult.channels.add(line);\n\t\t\t    }\n\n\t\t\t\tline = br.readLine();\n\t\t\t\tif ( !line.equals(\"mode names:\") )\n\t\t\t\t\tthrow new RuntimeException(\"Unexpected data entry\");\n\t\t\t\tresult.modes = new ArrayList<String>();\n\t\t\t    while ((line = br.readLine()) != null) {\n\t\t\t       if ( line.isEmpty() )\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tresult.modes.add(line);\n\t\t\t    }\n\t\t\t}\n\n\t\t  \tline = br.readLine();\n\t\t  \tif ( !line.equals(\"atn:\") )\n\t\t  \t\tthrow new RuntimeException(\"Unexpected data entry\");\n\t\t\tline = br.readLine();\n\t\t\tString[] elements = line.substring(1,line.length()-1).split(\",\");\n\t  \t\tint[] serializedATN = new int[elements.length];\n\n\t\t\tfor (int i = 0; i < elements.length; ++i) { // ignore [...] on ends\n\t\t\t\tserializedATN[i] = Integer.parseInt(elements[i].trim());\n\t\t\t}\n\n\t\t  \tATNDeserializer deserializer = new ATNDeserializer();\n\t\t  \tresult.atn = deserializer.deserialize(serializedATN);\n\t\t}\n\t\tcatch (java.io.IOException e) {\n\t\t\t// We just swallow the error and return empty objects instead.\n\t\t}\n\n\t\treturn result;\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/Interval.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\n/** An immutable inclusive interval a..b */\npublic class Interval {\n\tpublic static final Interval INVALID = new Interval(-1,-2);\n\n\tpublic final int a;\n\tpublic final int b;\n\n\tpublic Interval(int a, int b) { this.a=a; this.b=b; }\n\n\t/** Interval objects are used readonly so share all with the\n\t *  same single value a==b up to some max size.  Use an array as a perfect hash.\n\t *  Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new\n\t *  Interval object with a..a in it.  On Java.g4, 218623 IntervalSets\n\t *  have a..a (set with 1 element).\n\t */\n\tpublic static Interval of(int a, int b) {\n\t\treturn new Interval(a,b);\n\t}\n\n\t/** return number of elements between a and b inclusively. x..x is length 1.\n\t *  if b &lt; a, then length is 0.  9..10 has length 2.\n\t */\n\tpublic int length() {\n\t\tif ( b<a ) return 0;\n\t\treturn b-a+1;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif ( o==null || !(o instanceof Interval) ) {\n\t\t\treturn false;\n\t\t}\n\t\tInterval other = (Interval)o;\n\t\treturn this.a==other.a && this.b==other.b;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = 23;\n\t\thash = hash * 31 + a;\n\t\thash = hash * 31 + b;\n\t\treturn hash;\n\t}\n\n\t/** Does this start completely before other? Disjoint */\n\tpublic boolean startsBeforeDisjoint(Interval other) {\n\t\treturn this.a<other.a && this.b<other.a;\n\t}\n\n\t/** Does this start at or before other? Nondisjoint */\n\tpublic boolean startsBeforeNonDisjoint(Interval other) {\n\t\treturn this.a<=other.a && this.b>=other.a;\n\t}\n\n\t/** Does this.a start after other.b? May or may not be disjoint */\n\tpublic boolean startsAfter(Interval other) { return this.a>other.a; }\n\n\t/** Does this start completely after other? Disjoint */\n\tpublic boolean startsAfterDisjoint(Interval other) {\n\t\treturn this.a>other.b;\n\t}\n\n\t/** Does this start after other? NonDisjoint */\n\tpublic boolean startsAfterNonDisjoint(Interval other) {\n\t\treturn this.a>other.a && this.a<=other.b; // this.b>=other.b implied\n\t}\n\n\t/** Are both ranges disjoint? I.e., no overlap? */\n\tpublic boolean disjoint(Interval other) {\n\t\treturn startsBeforeDisjoint(other) || startsAfterDisjoint(other);\n\t}\n\n\t/** Are two intervals adjacent such as 0..41 and 42..42? */\n\tpublic boolean adjacent(Interval other) {\n\t\treturn this.a == other.b+1 || this.b == other.a-1;\n\t}\n\n\tpublic boolean properlyContains(Interval other) {\n\t\treturn other.a >= this.a && other.b <= this.b;\n\t}\n\n\t/** Return the interval computed from combining this and other */\n\tpublic Interval union(Interval other) {\n\t\treturn Interval.of(Math.min(a, other.a), Math.max(b, other.b));\n\t}\n\n\t/** Return the interval in common between this and o */\n\tpublic Interval intersection(Interval other) {\n\t\treturn Interval.of(Math.max(a, other.a), Math.min(b, other.b));\n\t}\n\n\t/** Return the interval with elements from this not in other;\n\t *  other must not be totally enclosed (properly contained)\n\t *  within this, which would result in two disjoint intervals\n\t *  instead of the single one returned by this method.\n\t */\n\tpublic Interval differenceNotProperlyContained(Interval other) {\n\t\tInterval diff = null;\n\t\t// other.a to left of this.a (or same)\n\t\tif ( other.startsBeforeNonDisjoint(this) ) {\n\t\t\tdiff = Interval.of(Math.max(this.a, other.b + 1),\n\t\t\t\t\t\t\t   this.b);\n\t\t}\n\n\t\t// other.a to right of this.a\n\t\telse if ( other.startsAfterNonDisjoint(this) ) {\n\t\t\tdiff = Interval.of(this.a, other.a - 1);\n\t\t}\n\t\treturn diff;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn a+\"..\"+b;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/IntervalSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\nimport java.util.Set;\n\n/**\n * This class implements the {@link IntSet} backed by a sorted array of\n * non-overlapping intervals. It is particularly efficient for representing\n * large collections of numbers, where the majority of elements appear as part\n * of a sequential range of numbers that are all part of the set. For example,\n * the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }.\n *\n * <p>\n * This class is able to represent sets containing any combination of values in\n * the range {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE}\n * (inclusive).</p>\n */\npublic class IntervalSet implements IntSet {\n\tpublic static final IntervalSet COMPLETE_CHAR_SET = IntervalSet.of(Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE);\n\tstatic {\n\t\tCOMPLETE_CHAR_SET.setReadonly(true);\n\t}\n\n\tpublic static final IntervalSet EMPTY_SET = new IntervalSet();\n\tstatic {\n\t\tEMPTY_SET.setReadonly(true);\n\t}\n\n\t/** The list of sorted, disjoint intervals. */\n    protected List<Interval> intervals;\n\n    protected boolean readonly;\n\n\tpublic IntervalSet(List<Interval> intervals) {\n\t\tthis.intervals = intervals;\n\t}\n\n\tpublic IntervalSet(IntervalSet set) {\n\t\tthis();\n\t\taddAll(set);\n\t}\n\n\tpublic IntervalSet(int... els) {\n\t\tif ( els==null ) {\n\t\t\tintervals = new ArrayList<Interval>(2); // most sets are 1 or 2 elements\n\t\t}\n\t\telse {\n\t\t\tintervals = new ArrayList<Interval>(els.length);\n\t\t\tfor (int e : els) add(e);\n\t\t}\n\t}\n\n\t/** Create a set with a single element, el. */\n\n    public static IntervalSet of(int a) {\n\t\tIntervalSet s = new IntervalSet();\n        s.add(a);\n        return s;\n    }\n\n    /** Create a set with all ints within range [a..b] (inclusive) */\n\tpublic static IntervalSet of(int a, int b) {\n\t\tIntervalSet s = new IntervalSet();\n\t\ts.add(a,b);\n\t\treturn s;\n\t}\n\n\tpublic void clear() {\n        if ( readonly ) throw new IllegalStateException(\"can't alter readonly IntervalSet\");\n\t\tintervals.clear();\n\t}\n\n    /** Add a single element to the set.  An isolated element is stored\n     *  as a range el..el.\n     */\n    @Override\n    public void add(int el) {\n        if ( readonly ) throw new IllegalStateException(\"can't alter readonly IntervalSet\");\n        add(el,el);\n    }\n\n    /** Add interval; i.e., add all integers from a to b to set.\n     *  If b&lt;a, do nothing.\n     *  Keep list in sorted order (by left range value).\n     *  If overlap, combine ranges.  For example,\n     *  If this is {1..5, 10..20}, adding 6..7 yields\n     *  {1..5, 6..7, 10..20}.  Adding 4..8 yields {1..8, 10..20}.\n     */\n    public void add(int a, int b) {\n        add(Interval.of(a, b));\n    }\n\n\t// copy on write so we can cache a..a intervals and sets of that\n\tprotected void add(Interval addition) {\n        if ( readonly ) throw new IllegalStateException(\"can't alter readonly IntervalSet\");\n\t\t//System.out.println(\"add \"+addition+\" to \"+intervals.toString());\n\t\tif ( addition.b<addition.a ) {\n\t\t\treturn;\n\t\t}\n\t\t// find position in list\n\t\t// Use iterators as we modify list in place\n\t\tfor (ListIterator<Interval> iter = intervals.listIterator(); iter.hasNext();) {\n\t\t\tInterval r = iter.next();\n\t\t\tif ( addition.equals(r) ) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ( addition.adjacent(r) || !addition.disjoint(r) ) {\n\t\t\t\t// next to each other, make a single larger interval\n\t\t\t\tInterval bigger = addition.union(r);\n\t\t\t\titer.set(bigger);\n\t\t\t\t// make sure we didn't just create an interval that\n\t\t\t\t// should be merged with next interval in list\n\t\t\t\twhile ( iter.hasNext() ) {\n\t\t\t\t\tInterval next = iter.next();\n\t\t\t\t\tif ( !bigger.adjacent(next) && bigger.disjoint(next) ) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t// if we bump up against or overlap next, merge\n\t\t\t\t\titer.remove();   // remove this one\n\t\t\t\t\titer.previous(); // move backwards to what we just set\n\t\t\t\t\titer.set(bigger.union(next)); // set to 3 merged ones\n\t\t\t\t\titer.next(); // first call to next after previous duplicates the result\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ( addition.startsBeforeDisjoint(r) ) {\n\t\t\t\t// insert before r\n\t\t\t\titer.previous();\n\t\t\t\titer.add(addition);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// if disjoint and after r, a future iteration will handle it\n\t\t}\n\t\t// ok, must be after last interval (and disjoint from last interval)\n\t\t// just add it\n\t\tintervals.add(addition);\n\t}\n\n\t/** combine all sets in the array returned the or'd value */\n\tpublic static IntervalSet or(IntervalSet[] sets) {\n\t\tIntervalSet r = new IntervalSet();\n\t\tfor (IntervalSet s : sets) r.addAll(s);\n\t\treturn r;\n\t}\n\n\t@Override\n\tpublic IntervalSet addAll(IntSet set) {\n\t\tif ( set==null ) {\n\t\t\treturn this;\n\t\t}\n\n\t\tif (set instanceof IntervalSet) {\n\t\t\tIntervalSet other = (IntervalSet)set;\n\t\t\t// walk set and add each interval\n\t\t\tint n = other.intervals.size();\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tInterval I = other.intervals.get(i);\n\t\t\t\tthis.add(I.a,I.b);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int value : set.toList()) {\n\t\t\t\tadd(value);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n    }\n\n    public IntervalSet complement(int minElement, int maxElement) {\n        return this.complement(IntervalSet.of(minElement,maxElement));\n    }\n\n    /** {@inheritDoc} */\n    @Override\n    public IntervalSet complement(IntSet vocabulary) {\n\t\tif ( vocabulary==null || vocabulary.isNil() ) {\n\t\t\treturn null; // nothing in common with null set\n\t\t}\n\n\t\tIntervalSet vocabularyIS;\n\t\tif (vocabulary instanceof IntervalSet) {\n\t\t\tvocabularyIS = (IntervalSet)vocabulary;\n\t\t}\n\t\telse {\n\t\t\tvocabularyIS = new IntervalSet();\n\t\t\tvocabularyIS.addAll(vocabulary);\n\t\t}\n\n\t\treturn vocabularyIS.subtract(this);\n    }\n\n\t@Override\n\tpublic IntervalSet subtract(IntSet a) {\n\t\tif (a == null || a.isNil()) {\n\t\t\treturn new IntervalSet(this);\n\t\t}\n\n\t\tif (a instanceof IntervalSet) {\n\t\t\treturn subtract(this, (IntervalSet)a);\n\t\t}\n\n\t\tIntervalSet other = new IntervalSet();\n\t\tother.addAll(a);\n\t\treturn subtract(this, other);\n\t}\n\n\t/**\n\t * Compute the set difference between two interval sets. The specific\n\t * operation is {@code left - right}. If either of the input sets is\n\t * {@code null}, it is treated as though it was an empty set.\n\t */\n\n\tpublic static IntervalSet subtract(IntervalSet left, IntervalSet right) {\n\t\tif (left == null || left.isNil()) {\n\t\t\treturn new IntervalSet();\n\t\t}\n\n\t\tIntervalSet result = new IntervalSet(left);\n\t\tif (right == null || right.isNil()) {\n\t\t\t// right set has no elements; just return the copy of the current set\n\t\t\treturn result;\n\t\t}\n\n\t\tint resultI = 0;\n\t\tint rightI = 0;\n\t\twhile (resultI < result.intervals.size() && rightI < right.intervals.size()) {\n\t\t\tInterval resultInterval = result.intervals.get(resultI);\n\t\t\tInterval rightInterval = right.intervals.get(rightI);\n\n\t\t\t// operation: (resultInterval - rightInterval) and update indexes\n\n\t\t\tif (rightInterval.b < resultInterval.a) {\n\t\t\t\trightI++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (rightInterval.a > resultInterval.b) {\n\t\t\t\tresultI++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tInterval beforeCurrent = null;\n\t\t\tInterval afterCurrent = null;\n\t\t\tif (rightInterval.a > resultInterval.a) {\n\t\t\t\tbeforeCurrent = new Interval(resultInterval.a, rightInterval.a - 1);\n\t\t\t}\n\n\t\t\tif (rightInterval.b < resultInterval.b) {\n\t\t\t\tafterCurrent = new Interval(rightInterval.b + 1, resultInterval.b);\n\t\t\t}\n\n\t\t\tif (beforeCurrent != null) {\n\t\t\t\tif (afterCurrent != null) {\n\t\t\t\t\t// split the current interval into two\n\t\t\t\t\tresult.intervals.set(resultI, beforeCurrent);\n\t\t\t\t\tresult.intervals.add(resultI + 1, afterCurrent);\n\t\t\t\t\tresultI++;\n\t\t\t\t\trightI++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// replace the current interval\n\t\t\t\t\tresult.intervals.set(resultI, beforeCurrent);\n\t\t\t\t\tresultI++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (afterCurrent != null) {\n\t\t\t\t\t// replace the current interval\n\t\t\t\t\tresult.intervals.set(resultI, afterCurrent);\n\t\t\t\t\trightI++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// remove the current interval (thus no need to increment resultI)\n\t\t\t\t\tresult.intervals.remove(resultI);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If rightI reached right.intervals.size(), no more intervals to subtract from result.\n\t\t// If resultI reached result.intervals.size(), we would be subtracting from an empty set.\n\t\t// Either way, we are done.\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic IntervalSet or(IntSet a) {\n\t\tIntervalSet o = new IntervalSet();\n\t\to.addAll(this);\n\t\to.addAll(a);\n\t\treturn o;\n\t}\n\n    /** {@inheritDoc} */\n\t@Override\n\tpublic IntervalSet and(IntSet other) {\n\t\tif ( other==null ) { //|| !(other instanceof IntervalSet) ) {\n\t\t\treturn null; // nothing in common with null set\n\t\t}\n\n\t\tList<Interval> myIntervals = this.intervals;\n\t\tList<Interval> theirIntervals = ((IntervalSet)other).intervals;\n\t\tIntervalSet intersection = null;\n\t\tint mySize = myIntervals.size();\n\t\tint theirSize = theirIntervals.size();\n\t\tint i = 0;\n\t\tint j = 0;\n\t\t// iterate down both interval lists looking for nondisjoint intervals\n\t\twhile ( i<mySize && j<theirSize ) {\n\t\t\tInterval mine = myIntervals.get(i);\n\t\t\tInterval theirs = theirIntervals.get(j);\n\t\t\t//System.out.println(\"mine=\"+mine+\" and theirs=\"+theirs);\n\t\t\tif ( mine.startsBeforeDisjoint(theirs) ) {\n\t\t\t\t// move this iterator looking for interval that might overlap\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse if ( theirs.startsBeforeDisjoint(mine) ) {\n\t\t\t\t// move other iterator looking for interval that might overlap\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse if ( mine.properlyContains(theirs) ) {\n\t\t\t\t// overlap, add intersection, get next theirs\n\t\t\t\tif ( intersection==null ) {\n\t\t\t\t\tintersection = new IntervalSet();\n\t\t\t\t}\n\t\t\t\tintersection.add(mine.intersection(theirs));\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse if ( theirs.properlyContains(mine) ) {\n\t\t\t\t// overlap, add intersection, get next mine\n\t\t\t\tif ( intersection==null ) {\n\t\t\t\t\tintersection = new IntervalSet();\n\t\t\t\t}\n\t\t\t\tintersection.add(mine.intersection(theirs));\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse if ( !mine.disjoint(theirs) ) {\n\t\t\t\t// overlap, add intersection\n\t\t\t\tif ( intersection==null ) {\n\t\t\t\t\tintersection = new IntervalSet();\n\t\t\t\t}\n\t\t\t\tintersection.add(mine.intersection(theirs));\n\t\t\t\t// Move the iterator of lower range [a..b], but not\n\t\t\t\t// the upper range as it may contain elements that will collide\n\t\t\t\t// with the next iterator. So, if mine=[0..115] and\n\t\t\t\t// theirs=[115..200], then intersection is 115 and move mine\n\t\t\t\t// but not theirs as theirs may collide with the next range\n\t\t\t\t// in thisIter.\n\t\t\t\t// move both iterators to next ranges\n\t\t\t\tif ( mine.startsAfterNonDisjoint(theirs) ) {\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t\telse if ( theirs.startsAfterNonDisjoint(mine) ) {\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( intersection==null ) {\n\t\t\treturn new IntervalSet();\n\t\t}\n\t\treturn intersection;\n\t}\n\n    /** {@inheritDoc} */\n    @Override\n    public boolean contains(int el) {\n\t\tint n = intervals.size();\n\t\tint l = 0;\n\t\tint r = n - 1;\n\t\t// Binary search for the element in the (sorted,\n\t\t// disjoint) array of intervals.\n\t\twhile (l <= r) {\n\t\t\tint m = (l + r) / 2;\n\t\t\tInterval I = intervals.get(m);\n\t\t\tint a = I.a;\n\t\t\tint b = I.b;\n\t\t\tif ( b<el ) {\n\t\t\t\tl = m + 1;\n\t\t\t} else if ( a>el ) {\n\t\t\t\tr = m - 1;\n\t\t\t} else { // el >= a && el <= b\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n    }\n\n    /** {@inheritDoc} */\n    @Override\n    public boolean isNil() {\n        return intervals==null || intervals.isEmpty();\n    }\n\n\t/**\n\t * Returns the maximum value contained in the set if not isNil().\n\t *\n\t * @return the maximum value contained in the set.\n\t * @throws RuntimeException if set is empty\n\t */\n\tpublic int getMaxElement() {\n\t\tif ( isNil() ) {\n\t\t\tthrow new RuntimeException(\"set is empty\");\n\t\t}\n\t\tInterval last = intervals.get(intervals.size()-1);\n\t\treturn last.b;\n\t}\n\n\t/**\n\t * Returns the minimum value contained in the set if not isNil().\n\t *\n\t * @return the minimum value contained in the set.\n\t * @throws RuntimeException if set is empty\n\t */\n\tpublic int getMinElement() {\n\t\tif ( isNil() ) {\n\t\t\tthrow new RuntimeException(\"set is empty\");\n\t\t}\n\n\t\treturn intervals.get(0).a;\n\t}\n\n    /** Return a list of Interval objects. */\n    public List<Interval> getIntervals() {\n        return intervals;\n    }\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\tfor (Interval I : intervals) {\n\t\t\thash = MurmurHash.update(hash, I.a);\n\t\t\thash = MurmurHash.update(hash, I.b);\n\t\t}\n\n\t\thash = MurmurHash.finish(hash, intervals.size() * 2);\n\t\treturn hash;\n\t}\n\n\t/** Are two IntervalSets equal?  Because all intervals are sorted\n     *  and disjoint, equals is a simple linear walk over both lists\n     *  to make sure they are the same.  Interval.equals() is used\n     *  by the List.equals() method to check the ranges.\n     */\n    @Override\n    public boolean equals(Object obj) {\n        if ( obj==null || !(obj instanceof IntervalSet) ) {\n            return false;\n        }\n        IntervalSet other = (IntervalSet)obj;\n\t\treturn this.intervals.equals(other.intervals);\n\t}\n\n\t@Override\n\tpublic String toString() { return toString(false); }\n\n\tpublic String toString(boolean elemAreChar) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tif ( this.intervals==null || this.intervals.isEmpty() ) {\n\t\t\treturn \"{}\";\n\t\t}\n\t\tif ( this.size()>1 ) {\n\t\t\tbuf.append(\"{\");\n\t\t}\n\t\tIterator<Interval> iter = this.intervals.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tInterval I = iter.next();\n\t\t\tint a = I.a;\n\t\t\tint b = I.b;\n\t\t\tif ( a==b ) {\n\t\t\t\tif ( a==Token.EOF ) buf.append(\"<EOF>\");\n\t\t\t\telse if ( elemAreChar ) buf.append(\"'\").appendCodePoint(a).append(\"'\");\n\t\t\t\telse buf.append(a);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ( elemAreChar ) buf.append(\"'\").appendCodePoint(a).append(\"'..'\").appendCodePoint(b).append(\"'\");\n\t\t\t\telse buf.append(a).append(\"..\").append(b);\n\t\t\t}\n\t\t\tif ( iter.hasNext() ) {\n\t\t\t\tbuf.append(\", \");\n\t\t\t}\n\t\t}\n\t\tif ( this.size()>1 ) {\n\t\t\tbuf.append(\"}\");\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\t/**\n\t * @deprecated Use {@link #toString(Vocabulary)} instead.\n\t */\n\t@Deprecated\n\tpublic String toString(String[] tokenNames) {\n\t\treturn toString(VocabularyImpl.fromTokenNames(tokenNames));\n\t}\n\n\tpublic String toString(Vocabulary vocabulary) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tif ( this.intervals==null || this.intervals.isEmpty() ) {\n\t\t\treturn \"{}\";\n\t\t}\n\t\tif ( this.size()>1 ) {\n\t\t\tbuf.append(\"{\");\n\t\t}\n\t\tIterator<Interval> iter = this.intervals.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tInterval I = iter.next();\n\t\t\tint a = I.a;\n\t\t\tint b = I.b;\n\t\t\tif ( a==b ) {\n\t\t\t\tbuf.append(elementName(vocabulary, a));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (int i=a; i<=b; i++) {\n\t\t\t\t\tif ( i>a ) buf.append(\", \");\n                    buf.append(elementName(vocabulary, i));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( iter.hasNext() ) {\n\t\t\t\tbuf.append(\", \");\n\t\t\t}\n\t\t}\n\t\tif ( this.size()>1 ) {\n\t\t\tbuf.append(\"}\");\n\t\t}\n        return buf.toString();\n    }\n\n\t/**\n\t * @deprecated Use {@link #elementName(Vocabulary, int)} instead.\n\t */\n\t@Deprecated\n\tprotected String elementName(String[] tokenNames, int a) {\n\t\treturn elementName(VocabularyImpl.fromTokenNames(tokenNames), a);\n\t}\n\n\n\tprotected String elementName(Vocabulary vocabulary, int a) {\n\t\tif (a == Token.EOF) {\n\t\t\treturn \"<EOF>\";\n\t\t}\n\t\telse if (a == Token.EPSILON) {\n\t\t\treturn \"<EPSILON>\";\n\t\t}\n\t\telse {\n\t\t\treturn vocabulary.getDisplayName(a);\n\t\t}\n\t}\n\n    @Override\n    public int size() {\n\t\tint n = 0;\n\t\tint numIntervals = intervals.size();\n\t\tif ( numIntervals==1 ) {\n\t\t\tInterval firstInterval = this.intervals.get(0);\n\t\t\treturn firstInterval.b-firstInterval.a+1;\n\t\t}\n\t\tfor (int i = 0; i < numIntervals; i++) {\n\t\t\tInterval I = intervals.get(i);\n\t\t\tn += (I.b-I.a+1);\n\t\t}\n\t\treturn n;\n    }\n\n\tpublic IntegerList toIntegerList() {\n\t\tIntegerList values = new IntegerList(size());\n\t\tint n = intervals.size();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tInterval I = intervals.get(i);\n\t\t\tint a = I.a;\n\t\t\tint b = I.b;\n\t\t\tfor (int v=a; v<=b; v++) {\n\t\t\t\tvalues.add(v);\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}\n\n    @Override\n    public List<Integer> toList() {\n\t\tList<Integer> values = new ArrayList<Integer>();\n\t\tint n = intervals.size();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tInterval I = intervals.get(i);\n\t\t\tint a = I.a;\n\t\t\tint b = I.b;\n\t\t\tfor (int v=a; v<=b; v++) {\n\t\t\t\tvalues.add(v);\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}\n\n\tpublic Set<Integer> toSet() {\n\t\tSet<Integer> s = new HashSet<Integer>();\n\t\tfor (Interval I : intervals) {\n\t\t\tint a = I.a;\n\t\t\tint b = I.b;\n\t\t\tfor (int v=a; v<=b; v++) {\n\t\t\t\ts.add(v);\n\t\t\t}\n\t\t}\n\t\treturn s;\n\t}\n\n\t/** Get the ith element of ordered set.  Used only by RandomPhrase so\n\t *  don't bother to implement if you're not doing that for a new\n\t *  ANTLR code gen target.\n\t */\n\tpublic int get(int i) {\n\t\tint n = intervals.size();\n\t\tint index = 0;\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tInterval I = intervals.get(j);\n\t\t\tint a = I.a;\n\t\t\tint b = I.b;\n\t\t\tfor (int v=a; v<=b; v++) {\n\t\t\t\tif ( index==i ) {\n\t\t\t\t\treturn v;\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic int[] toArray() {\n\t\treturn toIntegerList().toArray();\n\t}\n\n\t@Override\n\tpublic void remove(int el) {\n        if ( readonly ) throw new IllegalStateException(\"can't alter readonly IntervalSet\");\n        int n = intervals.size();\n        for (int i = 0; i < n; i++) {\n            Interval I = intervals.get(i);\n            int a = I.a;\n            int b = I.b;\n            if ( el<a ) {\n                break; // list is sorted and el is before this interval; not here\n            }\n            // if whole interval x..x, rm\n            if ( el==a && el==b ) {\n                intervals.remove(i);\n                break;\n            }\n            // if on left edge x..b, adjust left\n            if ( el==a ) {\n                I = Interval.of(a+1, b);\n                intervals.set(i, I);\n                break;\n            }\n            // if on right edge a..x, adjust right\n            if ( el==b ) {\n                I = Interval.of(a, b-1);\n                intervals.set(i, I);\n                break;\n            }\n            // if in middle a..x..b, split interval\n            if ( el>a && el<b ) { // found in this interval\n                int oldb = I.b;\n                I = Interval.of(a, el-1); // [a..x-1]\n                intervals.set(i, I);\n                add(el+1, oldb); // add [x+1..b]\n            }\n        }\n    }\n\n    public boolean isReadonly() {\n        return readonly;\n    }\n\n    public void setReadonly(boolean readonly) {\n        if ( this.readonly && !readonly ) throw new IllegalStateException(\"can't alter readonly IntervalSet\");\n        this.readonly = readonly;\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/LogManager.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\npublic class LogManager {\n    protected static class Record {\n\t\tlong timestamp;\n\t\tStackTraceElement location;\n\t\tString component;\n\t\tString msg;\n\t\tpublic Record() {\n\t\t\ttimestamp = System.currentTimeMillis();\n\t\t\tlocation = new Throwable().getStackTrace()[0];\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n            StringBuilder buf = new StringBuilder();\n            buf.append(new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss:SSS\").format(new Date(timestamp)));\n            buf.append(\" \");\n            buf.append(component);\n            buf.append(\" \");\n            buf.append(location.getFileName());\n            buf.append(\":\");\n            buf.append(location.getLineNumber());\n            buf.append(\" \");\n            buf.append(msg);\n            return buf.toString();\n\t\t}\n\t}\n\n\tprotected List<Record> records;\n\n\tpublic void log(String component, String msg) {\n\t\tRecord r = new Record();\n\t\tr.component = component;\n\t\tr.msg = msg;\n\t\tif ( records==null ) {\n\t\t\trecords = new ArrayList<Record>();\n\t\t}\n\t\trecords.add(r);\n\t}\n\n    public void log(String msg) { log(null, msg); }\n\n    public void save(String filename) throws IOException {\n        FileWriter fw = new FileWriter(filename);\n        BufferedWriter bw = new BufferedWriter(fw);\n        try {\n            bw.write(toString());\n        }\n        finally {\n            bw.close();\n        }\n    }\n\n    public String save() throws IOException {\n        //String dir = System.getProperty(\"java.io.tmpdir\");\n        String dir = \".\";\n        String defaultFilename =\n            dir + \"/antlr-\" +\n            new SimpleDateFormat(\"yyyy-MM-dd-HH.mm.ss\").format(new Date()) + \".log\";\n        save(defaultFilename);\n        return defaultFilename;\n    }\n\n    @Override\n    public String toString() {\n        if ( records==null ) return \"\";\n        String nl = System.getProperty(\"line.separator\");\n        StringBuilder buf = new StringBuilder();\n        for (Record r : records) {\n            buf.append(r);\n            buf.append(nl);\n        }\n        return buf.toString();\n    }\n\n    public static void main(String[] args) throws IOException {\n        LogManager mgr = new LogManager();\n        mgr.log(\"atn\", \"test msg\");\n        mgr.log(\"dfa\", \"test msg 2\");\n        System.out.println(mgr);\n        mgr.save();\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/MultiMap.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\npublic class MultiMap<K, V> extends LinkedHashMap<K, List<V>> {\n\tpublic void map(K key, V value) {\n\t\tList<V> elementsForKey = get(key);\n\t\tif ( elementsForKey==null ) {\n\t\t\telementsForKey = new ArrayList<V>();\n\t\t\tsuper.put(key, elementsForKey);\n\t\t}\n\t\telementsForKey.add(value);\n\t}\n\n\tpublic List<Pair<K,V>> getPairs() {\n\t\tList<Pair<K,V>> pairs = new ArrayList<Pair<K,V>>();\n\t\tfor (K key : keySet()) {\n\t\t\tfor (V value : get(key)) {\n\t\t\t\tpairs.add(new Pair<K,V>(key, value));\n\t\t\t}\n\t\t}\n\t\treturn pairs;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/MurmurHash.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\n/**\n *\n * @author Sam Harwell\n */\npublic final class MurmurHash {\n\n\tprivate static final int DEFAULT_SEED = 0;\n\n\t/**\n\t * Initialize the hash using the default seed value.\n\t *\n\t * @return the intermediate hash value\n\t */\n\tpublic static int initialize() {\n\t\treturn initialize(DEFAULT_SEED);\n\t}\n\n\t/**\n\t * Initialize the hash using the specified {@code seed}.\n\t *\n\t * @param seed the seed\n\t * @return the intermediate hash value\n\t */\n\tpublic static int initialize(int seed) {\n\t\treturn seed;\n\t}\n\n\t/**\n\t * Update the intermediate hash value for the next input {@code value}.\n\t *\n\t * @param hash the intermediate hash value\n\t * @param value the value to add to the current hash\n\t * @return the updated intermediate hash value\n\t */\n\tpublic static int update(int hash, int value) {\n\t\tfinal int c1 = 0xCC9E2D51;\n\t\tfinal int c2 = 0x1B873593;\n\t\tfinal int r1 = 15;\n\t\tfinal int r2 = 13;\n\t\tfinal int m = 5;\n\t\tfinal int n = 0xE6546B64;\n\n\t\tint k = value;\n\t\tk = k * c1;\n\t\tk = (k << r1) | (k >>> (32 - r1));\n\t\tk = k * c2;\n\n\t\thash = hash ^ k;\n\t\thash = (hash << r2) | (hash >>> (32 - r2));\n\t\thash = hash * m + n;\n\n\t\treturn hash;\n\t}\n\n\t/**\n\t * Update the intermediate hash value for the next input {@code value}.\n\t *\n\t * @param hash the intermediate hash value\n\t * @param value the value to add to the current hash\n\t * @return the updated intermediate hash value\n\t */\n\tpublic static int update(int hash, Object value) {\n\t\treturn update(hash, value != null ? value.hashCode() : 0);\n\t}\n\n\t/**\n\t * Apply the final computation steps to the intermediate value {@code hash}\n\t * to form the final result of the MurmurHash 3 hash function.\n\t *\n\t * @param hash the intermediate hash value\n\t * @param numberOfWords the number of integer values added to the hash\n\t * @return the final hash result\n\t */\n\tpublic static int finish(int hash, int numberOfWords) {\n\t\thash = hash ^ (numberOfWords * 4);\n\t\thash = hash ^ (hash >>> 16);\n\t\thash = hash * 0x85EBCA6B;\n\t\thash = hash ^ (hash >>> 13);\n\t\thash = hash * 0xC2B2AE35;\n\t\thash = hash ^ (hash >>> 16);\n\t\treturn hash;\n\t}\n\n\t/**\n\t * Utility function to compute the hash code of an array using the\n\t * MurmurHash algorithm.\n\t *\n\t * @param <T> the array element type\n\t * @param data the array data\n\t * @param seed the seed for the MurmurHash algorithm\n\t * @return the hash code of the data\n\t */\n\tpublic static <T> int hashCode(T[] data, int seed) {\n\t\tint hash = initialize(seed);\n\t\tfor (T value : data) {\n\t\t\thash = update(hash, value);\n\t\t}\n\n\t\thash = finish(hash, data.length);\n\t\treturn hash;\n\t}\n\n\tprivate MurmurHash() {\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/NotNull.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/** @deprecated THIS IS HERE FOR BACKWARD COMPATIBILITY WITH 4.5 ONLY.  It will\n *  disappear in 4.6+\n */\n@Documented\n@Retention(RetentionPolicy.CLASS)\n@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})\n@Deprecated\npublic @interface NotNull {\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/ObjectEqualityComparator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.misc;\n\n/**\n * This default implementation of {@link EqualityComparator} uses object equality\n * for comparisons by calling {@link Object#hashCode} and {@link Object#equals}.\n *\n * @author Sam Harwell\n */\npublic final class ObjectEqualityComparator extends AbstractEqualityComparator<Object> {\n\tpublic static final ObjectEqualityComparator INSTANCE = new ObjectEqualityComparator();\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This implementation returns\n\t * {@code obj.}{@link Object#hashCode hashCode()}.</p>\n\t */\n\t@Override\n\tpublic int hashCode(Object obj) {\n\t\tif (obj == null) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn obj.hashCode();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This implementation relies on object equality. If both objects are\n\t * {@code null}, this method returns {@code true}. Otherwise if only\n\t * {@code a} is {@code null}, this method returns {@code false}. Otherwise,\n\t * this method returns the result of\n\t * {@code a.}{@link Object#equals equals}{@code (b)}.</p>\n\t */\n\t@Override\n\tpublic boolean equals(Object a, Object b) {\n\t\tif (a == null) {\n\t\t\treturn b == null;\n\t\t}\n\n\t\treturn a.equals(b);\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/OrderedHashSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\nimport java.util.List;\n\n/** A HashMap that remembers the order that the elements were added.\n *  You can alter the ith element with set(i,value) too :)  Unique list.\n *  I need the replace/set-element-i functionality so I'm subclassing\n *  LinkedHashSet.\n */\npublic class OrderedHashSet<T> extends LinkedHashSet<T> {\n    /** Track the elements as they are added to the set */\n    protected ArrayList<T> elements = new ArrayList<T>();\n\n    public T get(int i) {\n        return elements.get(i);\n    }\n\n    /** Replace an existing value with a new value; updates the element\n     *  list and the hash table, but not the key as that has not changed.\n     */\n    public T set(int i, T value) {\n        T oldElement = elements.get(i);\n        elements.set(i,value); // update list\n        super.remove(oldElement); // now update the set: remove/add\n        super.add(value);\n        return oldElement;\n    }\n\n\tpublic boolean remove(int i) {\n\t\tT o = elements.remove(i);\n        return super.remove(o);\n\t}\n\n    /** Add a value to list; keep in hashtable for consistency also;\n     *  Key is object itself.  Good for say asking if a certain string is in\n     *  a list of strings.\n     */\n    @Override\n    public boolean add(T value) {\n        boolean result = super.add(value);\n\t\tif ( result ) {  // only track if new element not in set\n\t\t\telements.add(value);\n\t\t}\n\t\treturn result;\n    }\n\n\t@Override\n\tpublic boolean remove(Object o) {\n\t\tthrow new UnsupportedOperationException();\n    }\n\n\t@Override\n\tpublic void clear() {\n        elements.clear();\n        super.clear();\n    }\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn elements.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!(o instanceof OrderedHashSet<?>)) {\n\t\t\treturn false;\n\t\t}\n\n//\t\tSystem.out.print(\"equals \" + this + \", \" + o+\" = \");\n\t\tboolean same = elements!=null && elements.equals(((OrderedHashSet<?>)o).elements);\n//\t\tSystem.out.println(same);\n\t\treturn same;\n\t}\n\n\t@Override\n\tpublic Iterator<T> iterator() {\n\t\treturn elements.iterator();\n\t}\n\n\t/** Return the List holding list of table elements.  Note that you are\n     *  NOT getting a copy so don't write to the list.\n     */\n    public List<T> elements() {\n        return elements;\n    }\n\n    @Override\n    public Object clone() {\n        @SuppressWarnings(\"unchecked\") // safe (result of clone)\n        OrderedHashSet<T> dup = (OrderedHashSet<T>)super.clone();\n        dup.elements = new ArrayList<T>(this.elements);\n        return dup;\n    }\n\n    @Override\n\tpublic Object[] toArray() {\n\t\treturn elements.toArray();\n\t}\n\n\t@Override\n\tpublic String toString() {\n        return elements.toString();\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/Pair.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.io.Serializable;\n\npublic class Pair<A,B> implements Serializable {\n\tpublic final A a;\n\tpublic final B b;\n\n\tpublic Pair(A a, B b) {\n\t\tthis.a = a;\n\t\tthis.b = b;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof Pair<?, ?>)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tPair<?, ?> other = (Pair<?, ?>)obj;\n\t\treturn ObjectEqualityComparator.INSTANCE.equals(a, other.a)\n\t\t\t&& ObjectEqualityComparator.INSTANCE.equals(b, other.b);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, a);\n\t\thash = MurmurHash.update(hash, b);\n\t\treturn MurmurHash.finish(hash, 2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"(%s, %s)\", a, b);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/ParseCancellationException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport org.antlr.v4.runtime.BailErrorStrategy;\nimport org.antlr.v4.runtime.RecognitionException;\n\nimport java.util.concurrent.CancellationException;\n\n/**\n * This exception is thrown to cancel a parsing operation. This exception does\n * not extend {@link RecognitionException}, allowing it to bypass the standard\n * error recovery mechanisms. {@link BailErrorStrategy} throws this exception in\n * response to a parse error.\n *\n * @author Sam Harwell\n */\npublic class ParseCancellationException extends CancellationException {\n\n\tpublic ParseCancellationException() {\n\t}\n\n\tpublic ParseCancellationException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic ParseCancellationException(Throwable cause) {\n\t\tinitCause(cause);\n\t}\n\n\tpublic ParseCancellationException(String message, Throwable cause) {\n\t\tsuper(message);\n\t\tinitCause(cause);\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/Predicate.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\npublic interface Predicate<T> {\n\tboolean test(T t);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/TestRig.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.lang.reflect.Method;\n\n/** A proxy for the real org.antlr.v4.gui.TestRig that we moved to tool\n *  artifact from runtime.\n *\n *  @deprecated\n *  @since 4.5.1\n */\n@Deprecated\npublic class TestRig {\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tClass<?> testRigClass = Class.forName(\"org.antlr.v4.gui.TestRig\");\n\t\t\tSystem.err.println(\"Warning: TestRig moved to org.antlr.v4.gui.TestRig; calling automatically\");\n\t\t\ttry {\n\t\t\t\tMethod mainMethod = testRigClass.getMethod(\"main\", String[].class);\n\t\t\t\tmainMethod.invoke(null, (Object)args);\n\t\t\t}\n\t\t\tcatch (Exception nsme) {\n\t\t\t\tSystem.err.println(\"Problems calling org.antlr.v4.gui.TestRig.main(args)\");\n\t\t\t}\n\t\t}\n\t\tcatch (ClassNotFoundException cnfe) {\n\t\t\tSystem.err.println(\"Use of TestRig now requires the use of the tool jar, antlr-4.X-complete.jar\");\n\t\t\tSystem.err.println(\"Maven users need group ID org.antlr and artifact ID antlr4\");\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/Triple.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\npublic class Triple<A,B,C> {\n\tpublic final A a;\n\tpublic final B b;\n\tpublic final C c;\n\n\tpublic Triple(A a, B b, C c) {\n\t\tthis.a = a;\n\t\tthis.b = b;\n\t\tthis.c = c;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj == this) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (!(obj instanceof Triple<?, ?, ?>)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tTriple<?, ?, ?> other = (Triple<?, ?, ?>)obj;\n\t\treturn ObjectEqualityComparator.INSTANCE.equals(a, other.a)\n\t\t\t&& ObjectEqualityComparator.INSTANCE.equals(b, other.b)\n\t\t\t&& ObjectEqualityComparator.INSTANCE.equals(c, other.c);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, a);\n\t\thash = MurmurHash.update(hash, b);\n\t\thash = MurmurHash.update(hash, c);\n\t\treturn MurmurHash.finish(hash, 3);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"(%s, %s, %s)\", a, b, c);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/misc/Utils.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.misc;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.util.Arrays;\nimport java.util.BitSet;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\n\npublic class Utils {\n    // Seriously: why isn't this built in to java? ugh!\n    public static <T> String join(Iterator<T> iter, String separator) {\n        StringBuilder buf = new StringBuilder();\n        while ( iter.hasNext() ) {\n            buf.append(iter.next());\n            if ( iter.hasNext() ) {\n                buf.append(separator);\n            }\n        }\n        return buf.toString();\n    }\n\n\tpublic static <T> String join(T[] array, String separator) {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (int i = 0; i < array.length; i++) {\n\t\t\tbuilder.append(array[i]);\n\t\t\tif (i < array.length - 1) {\n\t\t\t\tbuilder.append(separator);\n\t\t\t}\n\t\t}\n\n\t\treturn builder.toString();\n\t}\n\n\tpublic static int numNonnull(Object[] data) {\n\t\tint n = 0;\n\t\tif ( data == null ) return n;\n\t\tfor (Object o : data) {\n\t\t\tif ( o!=null ) n++;\n\t\t}\n\t\treturn n;\n\t}\n\n\tpublic  static <T> void removeAllElements(Collection<T> data, T value) {\n\t\tif ( data==null ) return;\n\t\twhile ( data.contains(value) ) data.remove(value);\n\t}\n\n\tpublic static String escapeWhitespace(String s, boolean escapeSpaces) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (char c : s.toCharArray()) {\n\t\t\tif ( c==' ' && escapeSpaces ) buf.append('\\u00B7');\n\t\t\telse if ( c=='\\t' ) buf.append(\"\\\\t\");\n\t\t\telse if ( c=='\\n' ) buf.append(\"\\\\n\");\n\t\t\telse if ( c=='\\r' ) buf.append(\"\\\\r\");\n\t\t\telse buf.append(c);\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic static void writeFile(String fileName, String content) throws IOException {\n\t\twriteFile(fileName, content, null);\n\t}\n\n\tpublic static void writeFile(String fileName, String content, String encoding) throws IOException {\n\t\tFile f = new File(fileName);\n\t\tFileOutputStream fos = new FileOutputStream(f);\n\t\tOutputStreamWriter osw;\n\t\tif (encoding != null) {\n\t\t\tosw = new OutputStreamWriter(fos, encoding);\n\t\t}\n\t\telse {\n\t\t\tosw = new OutputStreamWriter(fos);\n\t\t}\n\n\t\ttry {\n\t\t\tosw.write(content);\n\t\t}\n\t\tfinally {\n\t\t\tosw.close();\n\t\t}\n\t}\n\n\n\tpublic static char[] readFile(String fileName) throws IOException {\n\t\treturn readFile(fileName, null);\n\t}\n\n\n\tpublic static char[] readFile(String fileName, String encoding) throws IOException {\n\t\tFile f = new File(fileName);\n\t\tint size = (int)f.length();\n\t\tInputStreamReader isr;\n\t\tFileInputStream fis = new FileInputStream(fileName);\n\t\tif ( encoding!=null ) {\n\t\t\tisr = new InputStreamReader(fis, encoding);\n\t\t}\n\t\telse {\n\t\t\tisr = new InputStreamReader(fis);\n\t\t}\n\t\tchar[] data = null;\n\t\ttry {\n\t\t\tdata = new char[size];\n\t\t\tint n = isr.read(data);\n\t\t\tif (n < data.length) {\n\t\t\t\tdata = Arrays.copyOf(data, n);\n\t\t\t}\n\t\t}\n\t\tfinally {\n\t\t\tisr.close();\n\t\t}\n\t\treturn data;\n\t}\n\n\t/** Convert array of strings to string&rarr;index map. Useful for\n\t *  converting rulenames to name&rarr;ruleindex map.\n\t */\n\tpublic static Map<String, Integer> toMap(String[] keys) {\n\t\tMap<String, Integer> m = new HashMap<String, Integer>();\n\t\tfor (int i=0; i<keys.length; i++) {\n\t\t\tm.put(keys[i], i);\n\t\t}\n\t\treturn m;\n\t}\n\n\tpublic static char[] toCharArray(IntegerList data) {\n\t\tif ( data==null ) return null;\n\t\treturn data.toCharArray();\n\t}\n\n\tpublic static IntervalSet toSet(BitSet bits) {\n\t\tIntervalSet s = new IntervalSet();\n\t\tint i = bits.nextSetBit(0);\n\t\twhile ( i >= 0 ) {\n\t\t\ts.add(i);\n\t\t\ti = bits.nextSetBit(i+1);\n\t\t}\n\t\treturn s;\n\t}\n\n\t/** @since 4.6 */\n\tpublic static String expandTabs(String s, int tabSize) {\n\t\tif ( s==null ) return null;\n\t\tStringBuilder buf = new StringBuilder();\n\t\tint col = 0;\n\t\tfor (int i = 0; i<s.length(); i++) {\n\t\t\tchar c = s.charAt(i);\n\t\t\tswitch ( c ) {\n\t\t\t\tcase '\\n' :\n\t\t\t\t\tcol = 0;\n\t\t\t\t\tbuf.append(c);\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\t' :\n\t\t\t\t\tint n = tabSize-col%tabSize;\n\t\t\t\t\tcol+=n;\n\t\t\t\t\tbuf.append(spaces(n));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault :\n\t\t\t\t\tcol++;\n\t\t\t\t\tbuf.append(c);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\t/** @since 4.6 */\n\tpublic static String spaces(int n) {\n\t\treturn sequence(n, \" \");\n\t}\n\n\t/** @since 4.6 */\n\tpublic static String newlines(int n) {\n\t\treturn sequence(n, \"\\n\");\n\t}\n\n\t/** @since 4.6 */\n\tpublic static String sequence(int n, String s) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (int sp=1; sp<=n; sp++) buf.append(s);\n\t\treturn buf.toString();\n\t}\n\n\t/** @since 4.6 */\n\tpublic static int count(String s, char x) {\n\t\tint n = 0;\n\t\tfor (int i = 0; i<s.length(); i++) {\n\t\t\tif ( s.charAt(i)==x ) {\n\t\t\t\tn++;\n\t\t\t}\n\t\t}\n\t\treturn n;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/AbstractParseTreeVisitor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\npublic abstract class AbstractParseTreeVisitor<T> implements ParseTreeVisitor<T> {\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation calls {@link ParseTree#accept} on the\n\t * specified tree.</p>\n\t */\n\t@Override\n\tpublic T visit(ParseTree tree) {\n\t\treturn tree.accept(this);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation initializes the aggregate result to\n\t * {@link #defaultResult defaultResult()}. Before visiting each child, it\n\t * calls {@link #shouldVisitNextChild shouldVisitNextChild}; if the result\n\t * is {@code false} no more children are visited and the current aggregate\n\t * result is returned. After visiting a child, the aggregate result is\n\t * updated by calling {@link #aggregateResult aggregateResult} with the\n\t * previous aggregate result and the result of visiting the child.</p>\n\t *\n\t * <p>The default implementation is not safe for use in visitors that modify\n\t * the tree structure. Visitors that modify the tree should override this\n\t * method to behave properly in respect to the specific algorithm in use.</p>\n\t */\n\t@Override\n\tpublic T visitChildren(RuleNode node) {\n\t\tT result = defaultResult();\n\t\tint n = node.getChildCount();\n\t\tfor (int i=0; i<n; i++) {\n\t\t\tif (!shouldVisitNextChild(node, result)) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tParseTree c = node.getChild(i);\n\t\t\tT childResult = c.accept(this);\n\t\t\tresult = aggregateResult(result, childResult);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of\n\t * {@link #defaultResult defaultResult}.</p>\n\t */\n\t@Override\n\tpublic T visitTerminal(TerminalNode node) {\n\t\treturn defaultResult();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of\n\t * {@link #defaultResult defaultResult}.</p>\n\t */\n\t@Override\n\tpublic T visitErrorNode(ErrorNode node) {\n\t\treturn defaultResult();\n\t}\n\n\t/**\n\t * Gets the default value returned by visitor methods. This value is\n\t * returned by the default implementations of\n\t * {@link #visitTerminal visitTerminal}, {@link #visitErrorNode visitErrorNode}.\n\t * The default implementation of {@link #visitChildren visitChildren}\n\t * initializes its aggregate result to this value.\n\t *\n\t * <p>The base implementation returns {@code null}.</p>\n\t *\n\t * @return The default value returned by visitor methods.\n\t */\n\tprotected T defaultResult() {\n\t\treturn null;\n\t}\n\n\t/**\n\t * Aggregates the results of visiting multiple children of a node. After\n\t * either all children are visited or {@link #shouldVisitNextChild} returns\n\t * {@code false}, the aggregate value is returned as the result of\n\t * {@link #visitChildren}.\n\t *\n\t * <p>The default implementation returns {@code nextResult}, meaning\n\t * {@link #visitChildren} will return the result of the last child visited\n\t * (or return the initial value if the node has no children).</p>\n\t *\n\t * @param aggregate The previous aggregate value. In the default\n\t * implementation, the aggregate value is initialized to\n\t * {@link #defaultResult}, which is passed as the {@code aggregate} argument\n\t * to this method after the first child node is visited.\n\t * @param nextResult The result of the immediately preceeding call to visit\n\t * a child node.\n\t *\n\t * @return The updated aggregate result.\n\t */\n\tprotected T aggregateResult(T aggregate, T nextResult) {\n\t\treturn nextResult;\n\t}\n\n\t/**\n\t * This method is called after visiting each child in\n\t * {@link #visitChildren}. This method is first called before the first\n\t * child is visited; at that point {@code currentResult} will be the initial\n\t * value (in the default implementation, the initial value is returned by a\n\t * call to {@link #defaultResult}. This method is not called after the last\n\t * child is visited.\n\t *\n\t * <p>The default implementation always returns {@code true}, indicating that\n\t * {@code visitChildren} should only return after all children are visited.\n\t * One reason to override this method is to provide a \"short circuit\"\n\t * evaluation option for situations where the result of visiting a single\n\t * child has the potential to determine the result of the visit operation as\n\t * a whole.</p>\n\t *\n\t * @param node The {@link RuleNode} whose children are currently being\n\t * visited.\n\t * @param currentResult The current aggregate result of the children visited\n\t * to the current point.\n\t *\n\t * @return {@code true} to continue visiting children. Otherwise return\n\t * {@code false} to stop visiting children and immediately return the\n\t * current aggregate result from {@link #visitChildren}.\n\t */\n\tprotected boolean shouldVisitNextChild(RuleNode node, T currentResult) {\n\t\treturn true;\n\t}\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/ErrorNode.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\npublic interface ErrorNode extends TerminalNode {\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/ErrorNodeImpl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.Token;\n\n/** Represents a token that was consumed during resynchronization\n *  rather than during a valid match operation. For example,\n *  we will create this kind of a node during single token insertion\n *  and deletion as well as during \"consume until error recovery set\"\n *  upon no viable alternative exceptions.\n */\npublic class ErrorNodeImpl extends TerminalNodeImpl implements ErrorNode {\n\tpublic ErrorNodeImpl(Token token) {\n\t\tsuper(token);\n\t}\n\n\t@Override\n\tpublic <T> T accept(ParseTreeVisitor<? extends T> visitor) {\n\t\treturn visitor.visitErrorNode(this);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/IterativeParseTreeWalker.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.misc.IntegerStack;\n\nimport java.util.ArrayDeque;\nimport java.util.Deque;\n\n/**\n * An iterative (read: non-recursive) pre-order and post-order tree walker that\n * doesn't use the thread stack but heap-based stacks. Makes it possible to\n * process deeply nested parse trees.\n */\npublic class IterativeParseTreeWalker extends ParseTreeWalker {\n\n\t@Override\n\tpublic void walk(ParseTreeListener listener, ParseTree t) {\n\n\t\tfinal Deque<ParseTree> nodeStack = new ArrayDeque<ParseTree>();\n\t\tfinal IntegerStack indexStack = new IntegerStack();\n\n\t\tParseTree currentNode = t;\n\t\tint currentIndex = 0;\n\n\t\twhile (currentNode != null) {\n\n\t\t\t// pre-order visit\n\t\t\tif (currentNode instanceof ErrorNode) {\n\t\t\t\tlistener.visitErrorNode((ErrorNode) currentNode);\n\t\t\t}\n\t\t\telse if (currentNode instanceof TerminalNode) {\n\t\t\t\tlistener.visitTerminal((TerminalNode) currentNode);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfinal RuleNode r = (RuleNode) currentNode;\n\t\t\t\tenterRule(listener, r);\n\t\t\t}\n\n\t\t\t// Move down to first child, if exists\n\t\t\tif (currentNode.getChildCount() > 0) {\n\t\t\t\tnodeStack.push(currentNode);\n\t\t\t\tindexStack.push(currentIndex);\n\t\t\t\tcurrentIndex = 0;\n\t\t\t\tcurrentNode = currentNode.getChild(0);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// No child nodes, so walk tree\n\t\t\tdo {\n\n\t\t\t\t// post-order visit\n\t\t\t\tif (currentNode instanceof RuleNode) {\n\t\t\t\t\texitRule(listener, (RuleNode) currentNode);\n\t\t\t\t}\n\n\t\t\t\t// No parent, so no siblings\n\t\t\t\tif (nodeStack.isEmpty()) {\n\t\t\t\t\tcurrentNode = null;\n\t\t\t\t\tcurrentIndex = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Move to next sibling if possible\n\t\t\t\tcurrentNode = nodeStack.peek().getChild(++currentIndex);\n\t\t\t\tif (currentNode != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// No next, sibling, so move up\n\t\t\t\tcurrentNode = nodeStack.pop();\n\t\t\t\tcurrentIndex = indexStack.pop();\n\n\t\t\t} while (currentNode != null);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/ParseTree.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.Token;\n\n/** An interface to access the tree of {@link RuleContext} objects created\n *  during a parse that makes the data structure look like a simple parse tree.\n *  This node represents both internal nodes, rule invocations,\n *  and leaf nodes, token matches.\n *\n *  <p>The payload is either a {@link Token} or a {@link RuleContext} object.</p>\n */\npublic interface ParseTree extends SyntaxTree {\n\t// the following methods narrow the return type; they are not additional methods\n\t@Override\n\tParseTree getParent();\n\t@Override\n\tParseTree getChild(int i);\n\n\n\t/** Set the parent for this node.\n\t *\n\t *  This is not backward compatible as it changes\n\t *  the interface but no one was able to create custom\n\t *  nodes anyway so I'm adding as it improves internal\n\t *  code quality.\n\t *\n\t *  One could argue for a restructuring of\n\t *  the class/interface hierarchy so that\n\t *  setParent, addChild are moved up to Tree\n\t *  but that's a major change. So I'll do the\n\t *  minimal change, which is to add this method.\n\t *\n\t *  @since 4.7\n\t */\n\tvoid setParent(RuleContext parent);\n\n\t/** The {@link ParseTreeVisitor} needs a double dispatch method. */\n\t<T> T accept(ParseTreeVisitor<? extends T> visitor);\n\n\t/** Return the combined text of all leaf nodes. Does not get any\n\t *  off-channel tokens (if any) so won't return whitespace and\n\t *  comments if they are sent to parser on hidden channel.\n\t */\n\tString getText();\n\n\t/** Specialize toStringTree so that it can print out more information\n\t * \tbased upon the parser.\n\t */\n\tString toStringTree(Parser parser);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/ParseTreeListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\n\n/** This interface describes the minimal core of methods triggered\n *  by {@link ParseTreeWalker}. E.g.,\n *\n *  \tParseTreeWalker walker = new ParseTreeWalker();\n *\t\twalker.walk(myParseTreeListener, myParseTree); <-- triggers events in your listener\n *\n *  If you want to trigger events in multiple listeners during a single\n *  tree walk, you can use the ParseTreeDispatcher object available at\n *\n * \t\thttps://github.com/antlr/antlr4/issues/841\n */\npublic interface ParseTreeListener {\n\tvoid visitTerminal(TerminalNode node);\n\tvoid visitErrorNode(ErrorNode node);\n    void enterEveryRule(ParserRuleContext ctx);\n    void exitEveryRule(ParserRuleContext ctx);\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/ParseTreeProperty.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport java.util.IdentityHashMap;\nimport java.util.Map;\n\n/**\n * Associate a property with a parse tree node. Useful with parse tree listeners\n * that need to associate values with particular tree nodes, kind of like\n * specifying a return value for the listener event method that visited a\n * particular node. Example:\n *\n * <pre>\n * ParseTreeProperty&lt;Integer&gt; values = new ParseTreeProperty&lt;Integer&gt;();\n * values.put(tree, 36);\n * int x = values.get(tree);\n * values.removeFrom(tree);\n * </pre>\n *\n * You would make one decl (values here) in the listener and use lots of times\n * in your event methods.\n */\npublic class ParseTreeProperty<V> {\n\tprotected Map<ParseTree, V> annotations = new IdentityHashMap<ParseTree, V>();\n\n\tpublic V get(ParseTree node) { return annotations.get(node); }\n\tpublic void put(ParseTree node, V value) { annotations.put(node, value); }\n\tpublic V removeFrom(ParseTree node) { return annotations.remove(node); }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/ParseTreeVisitor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\n/**\n * This interface defines the basic notion of a parse tree visitor. Generated\n * visitors implement this interface and the {@code XVisitor} interface for\n * grammar {@code X}.\n *\n * @param <T> The return type of the visit operation. Use {@link Void} for\n * operations with no return type.\n */\npublic interface ParseTreeVisitor<T> {\n\n\t/**\n\t * Visit a parse tree, and return a user-defined result of the operation.\n\t *\n\t * @param tree The {@link ParseTree} to visit.\n\t * @return The result of visiting the parse tree.\n\t */\n\tT visit(ParseTree tree);\n\n\t/**\n\t * Visit the children of a node, and return a user-defined result of the\n\t * operation.\n\t *\n\t * @param node The {@link RuleNode} whose children should be visited.\n\t * @return The result of visiting the children of the node.\n\t */\n\tT visitChildren(RuleNode node);\n\n\t/**\n\t * Visit a terminal node, and return a user-defined result of the operation.\n\t *\n\t * @param node The {@link TerminalNode} to visit.\n\t * @return The result of visiting the node.\n\t */\n\tT visitTerminal(TerminalNode node);\n\n\t/**\n\t * Visit an error node, and return a user-defined result of the operation.\n\t *\n\t * @param node The {@link ErrorNode} to visit.\n\t * @return The result of visiting the node.\n\t */\n\tT visitErrorNode(ErrorNode node);\n\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/ParseTreeWalker.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\n\npublic class ParseTreeWalker {\n    public static final ParseTreeWalker DEFAULT = new ParseTreeWalker();\n\n\n\t/**\n\t * Performs a walk on the given parse tree starting at the root and going down recursively\n\t * with depth-first search. On each node, {@link ParseTreeWalker#enterRule} is called before\n\t * recursively walking down into child nodes, then\n\t * {@link ParseTreeWalker#exitRule} is called after the recursive call to wind up.\n\t * @param listener The listener used by the walker to process grammar rules\n\t * @param t The parse tree to be walked on\n\t */\n\tpublic void walk(ParseTreeListener listener, ParseTree t) {\n\t\tif ( t instanceof ErrorNode) {\n\t\t\tlistener.visitErrorNode((ErrorNode)t);\n\t\t\treturn;\n\t\t}\n\t\telse if ( t instanceof TerminalNode) {\n\t\t\tlistener.visitTerminal((TerminalNode)t);\n\t\t\treturn;\n\t\t}\n\t\tRuleNode r = (RuleNode)t;\n        enterRule(listener, r);\n        int n = r.getChildCount();\n        for (int i = 0; i<n; i++) {\n            walk(listener, r.getChild(i));\n        }\n\t\texitRule(listener, r);\n    }\n\n\t/**\n\t * Enters a grammar rule by first triggering the generic event {@link ParseTreeListener#enterEveryRule}\n\t * then by triggering the event specific to the given parse tree node\n\t * @param listener The listener responding to the trigger events\n\t * @param r The grammar rule containing the rule context\n\t */\n    protected void enterRule(ParseTreeListener listener, RuleNode r) {\n\t\tParserRuleContext ctx = (ParserRuleContext)r.getRuleContext();\n\t\tlistener.enterEveryRule(ctx);\n\t\tctx.enterRule(listener);\n    }\n\n\n\t/**\n\t * Exits a grammar rule by first triggering the event specific to the given parse tree node\n\t * then by triggering the generic event {@link ParseTreeListener#exitEveryRule}\n\t * @param listener The listener responding to the trigger events\n\t * @param r The grammar rule containing the rule context\n\t */\n\tprotected void exitRule(ParseTreeListener listener, RuleNode r) {\n\t\tParserRuleContext ctx = (ParserRuleContext)r.getRuleContext();\n\t\tctx.exitRule(listener);\n\t\tlistener.exitEveryRule(ctx);\n    }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/RuleNode.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.RuleContext;\n\npublic interface RuleNode extends ParseTree {\n\tRuleContext getRuleContext();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/SyntaxTree.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.misc.Interval;\n\n/** A tree that knows about an interval in a token stream\n *  is some kind of syntax tree. Subinterfaces distinguish\n *  between parse trees and other kinds of syntax trees we might want to create.\n */\npublic interface SyntaxTree extends Tree {\n\t/**\n\t * Return an {@link Interval} indicating the index in the\n\t * {@link TokenStream} of the first and last token associated with this\n\t * subtree. If this node is a leaf, then the interval represents a single\n\t * token and has interval i..i for token index i.\n\t *\n\t * <p>An interval of i..i-1 indicates an empty interval at position\n\t * i in the input stream, where 0 &lt;= i &lt;= the size of the input\n\t * token stream.  Currently, the code base can only have i=0..n-1 but\n\t * in concept one could have an empty interval after EOF. </p>\n\t *\n\t * <p>If source interval is unknown, this returns {@link Interval#INVALID}.</p>\n\t *\n\t * <p>As a weird special case, the source interval for rules matched after\n\t * EOF is unspecified.</p>\n\t */\n\tInterval getSourceInterval();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/TerminalNode.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.Token;\n\npublic interface TerminalNode extends ParseTree {\n\tToken getSymbol();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/TerminalNodeImpl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.Interval;\n\npublic class TerminalNodeImpl implements TerminalNode {\n\tpublic Token symbol;\n\tpublic ParseTree parent;\n\n\tpublic TerminalNodeImpl(Token symbol) {\tthis.symbol = symbol;\t}\n\n\t@Override\n\tpublic ParseTree getChild(int i) {return null;}\n\n\t@Override\n\tpublic Token getSymbol() {return symbol;}\n\n\t@Override\n\tpublic ParseTree getParent() { return parent; }\n\n\t@Override\n\tpublic void setParent(RuleContext parent) {\n\t\tthis.parent = parent;\n\t}\n\n\t@Override\n\tpublic Token getPayload() { return symbol; }\n\n\t@Override\n\tpublic Interval getSourceInterval() {\n\t\tif ( symbol ==null ) return Interval.INVALID;\n\n\t\tint tokenIndex = symbol.getTokenIndex();\n\t\treturn new Interval(tokenIndex, tokenIndex);\n\t}\n\n\t@Override\n\tpublic int getChildCount() { return 0; }\n\n\t@Override\n\tpublic <T> T accept(ParseTreeVisitor<? extends T> visitor) {\n\t\treturn visitor.visitTerminal(this);\n\t}\n\n\t@Override\n\tpublic String getText() { return symbol.getText(); }\n\n\t@Override\n\tpublic String toStringTree(Parser parser) {\n\t\treturn toString();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\t\tif ( symbol.getType() == Token.EOF ) return \"<EOF>\";\n\t\t\treturn symbol.getText();\n\t}\n\n\t@Override\n\tpublic String toStringTree() {\n\t\treturn toString();\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/Tree.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.Token;\n\n/** The basic notion of a tree has a parent, a payload, and a list of children.\n *  It is the most abstract interface for all the trees used by ANTLR.\n */\npublic interface Tree {\n\t/** The parent of this node. If the return value is null, then this\n\t *  node is the root of the tree.\n\t */\n\tTree getParent();\n\n\t/**\n\t * This method returns whatever object represents the data at this node. For\n\t * example, for parse trees, the payload can be a {@link Token} representing\n\t * a leaf node or a {@link RuleContext} object representing a rule\n\t * invocation. For abstract syntax trees (ASTs), this is a {@link Token}\n\t * object.\n\t */\n\tObject getPayload();\n\n\t/** If there are children, get the {@code i}th value indexed from 0. */\n\tTree getChild(int i);\n\n\t/** How many children are there? If there is none, then this\n\t *  node represents a leaf node.\n\t */\n\tint getChildCount();\n\n\t/** Print out a whole tree, not just a node, in LISP format\n\t *  {@code (root child1 .. childN)}. Print just a node if this is a leaf.\n\t */\n\tString toStringTree();\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/Trees.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree;\n\nimport org.antlr.v4.runtime.CommonToken;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.Predicate;\nimport org.antlr.v4.runtime.misc.Utils;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\n\n/** A set of utility routines useful for all kinds of ANTLR trees. */\npublic class Trees {\n\t/** Print out a whole tree in LISP form. {@link #getNodeText} is used on the\n\t *  node payloads to get the text for the nodes.  Detect\n\t *  parse trees and extract data appropriately.\n\t */\n\tpublic static String toStringTree(Tree t) {\n\t\treturn toStringTree(t, (List<String>)null);\n\t}\n\n\t/** Print out a whole tree in LISP form. {@link #getNodeText} is used on the\n\t *  node payloads to get the text for the nodes.  Detect\n\t *  parse trees and extract data appropriately.\n\t */\n\tpublic static String toStringTree(Tree t, Parser recog) {\n\t\tString[] ruleNames = recog != null ? recog.getRuleNames() : null;\n\t\tList<String> ruleNamesList = ruleNames != null ? Arrays.asList(ruleNames) : null;\n\t\treturn toStringTree(t, ruleNamesList);\n\t}\n\n\t/** Print out a whole tree in LISP form. {@link #getNodeText} is used on the\n\t *  node payloads to get the text for the nodes.\n\t */\n\tpublic static String toStringTree(final Tree t, final List<String> ruleNames) {\n\t\tString s = Utils.escapeWhitespace(getNodeText(t, ruleNames), false);\n\t\tif ( t.getChildCount()==0 ) return s;\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append(\"(\");\n\t\ts = Utils.escapeWhitespace(getNodeText(t, ruleNames), false);\n\t\tbuf.append(s);\n\t\tbuf.append(' ');\n\t\tfor (int i = 0; i<t.getChildCount(); i++) {\n\t\t\tif ( i>0 ) buf.append(' ');\n\t\t\tbuf.append(toStringTree(t.getChild(i), ruleNames));\n\t\t}\n\t\tbuf.append(\")\");\n\t\treturn buf.toString();\n\t}\n\n\tpublic static String getNodeText(Tree t, Parser recog) {\n\t\tString[] ruleNames = recog != null ? recog.getRuleNames() : null;\n\t\tList<String> ruleNamesList = ruleNames != null ? Arrays.asList(ruleNames) : null;\n\t\treturn getNodeText(t, ruleNamesList);\n\t}\n\n\tpublic static String getNodeText(Tree t, List<String> ruleNames) {\n\t\tif ( ruleNames!=null ) {\n\t\t\tif ( t instanceof RuleContext ) {\n\t\t\t\tint ruleIndex = ((RuleContext)t).getRuleContext().getRuleIndex();\n\t\t\t\tString ruleName = ruleNames.get(ruleIndex);\n\t\t\t\tint altNumber = ((RuleContext) t).getAltNumber();\n\t\t\t\tif ( altNumber!=ATN.INVALID_ALT_NUMBER ) {\n\t\t\t\t\treturn ruleName+\":\"+altNumber;\n\t\t\t\t}\n\t\t\t\treturn ruleName;\n\t\t\t}\n\t\t\telse if ( t instanceof ErrorNode) {\n\t\t\t\treturn t.toString();\n\t\t\t}\n\t\t\telse if ( t instanceof TerminalNode) {\n\t\t\t\tToken symbol = ((TerminalNode)t).getSymbol();\n\t\t\t\tif (symbol != null) {\n\t\t\t\t\tString s = symbol.getText();\n\t\t\t\t\treturn s;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// no recog for rule names\n\t\tObject payload = t.getPayload();\n\t\tif ( payload instanceof Token ) {\n\t\t\treturn ((Token)payload).getText();\n\t\t}\n\t\treturn t.getPayload().toString();\n\t}\n\n\t/** Return ordered list of all children of this node */\n\tpublic static List<Tree> getChildren(Tree t) {\n\t\tList<Tree> kids = new ArrayList<Tree>();\n\t\tfor (int i=0; i<t.getChildCount(); i++) {\n\t\t\tkids.add(t.getChild(i));\n\t\t}\n\t\treturn kids;\n\t}\n\n\t/** Return a list of all ancestors of this node.  The first node of\n\t *  list is the root and the last is the parent of this node.\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic static List<? extends Tree> getAncestors(Tree t) {\n\t\tif ( t.getParent()==null ) return Collections.emptyList();\n\t\tList<Tree> ancestors = new ArrayList<Tree>();\n\t\tt = t.getParent();\n\t\twhile ( t!=null ) {\n\t\t\tancestors.add(0, t); // insert at start\n\t\t\tt = t.getParent();\n\t\t}\n\t\treturn ancestors;\n\t}\n\n\t/** Return true if t is u's parent or a node on path to root from u.\n\t *  Use == not equals().\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic static boolean isAncestorOf(Tree t, Tree u) {\n\t\tif ( t==null || u==null || t.getParent()==null ) return false;\n\t\tTree p = u.getParent();\n\t\twhile ( p!=null ) {\n\t\t\tif ( t==p ) return true;\n\t\t\tp = p.getParent();\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic static Collection<ParseTree> findAllTokenNodes(ParseTree t, int ttype) {\n\t\treturn findAllNodes(t, ttype, true);\n\t}\n\n\tpublic static Collection<ParseTree> findAllRuleNodes(ParseTree t, int ruleIndex) {\n\t\treturn findAllNodes(t, ruleIndex, false);\n\t}\n\n\tpublic static List<ParseTree> findAllNodes(ParseTree t, int index, boolean findTokens) {\n\t\tList<ParseTree> nodes = new ArrayList<ParseTree>();\n\t\t_findAllNodes(t, index, findTokens, nodes);\n\t\treturn nodes;\n\t}\n\n\tpublic static void _findAllNodes(ParseTree t, int index, boolean findTokens,\n\t\t\t\t\t\t\t\t\t List<? super ParseTree> nodes)\n\t{\n\t\t// check this node (the root) first\n\t\tif ( findTokens && t instanceof TerminalNode ) {\n\t\t\tTerminalNode tnode = (TerminalNode)t;\n\t\t\tif ( tnode.getSymbol().getType()==index ) nodes.add(t);\n\t\t}\n\t\telse if ( !findTokens && t instanceof ParserRuleContext ) {\n\t\t\tParserRuleContext ctx = (ParserRuleContext)t;\n\t\t\tif ( ctx.getRuleIndex() == index ) nodes.add(t);\n\t\t}\n\t\t// check children\n\t\tfor (int i = 0; i < t.getChildCount(); i++){\n\t\t\t_findAllNodes(t.getChild(i), index, findTokens, nodes);\n\t\t}\n\t}\n\n\t/** Get all descendents; includes t itself.\n\t *\n\t * @since 4.5.1\n \t */\n\tpublic static List<ParseTree> getDescendants(ParseTree t) {\n\t\tList<ParseTree> nodes = new ArrayList<ParseTree>();\n\t\tnodes.add(t);\n\n\t\tint n = t.getChildCount();\n\t\tfor (int i = 0 ; i < n ; i++){\n\t\t\tnodes.addAll(getDescendants(t.getChild(i)));\n\t\t}\n\t\treturn nodes;\n\t}\n\n\t/** @deprecated */\n  @Deprecated\n\tpublic static List<ParseTree> descendants(ParseTree t) {\n\t\treturn getDescendants(t);\n\t}\n\n\t/** Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex\n\t *  inclusively using postorder traversal.  Recursive depth-first-search.\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic static ParserRuleContext getRootOfSubtreeEnclosingRegion(ParseTree t,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint startTokenIndex, // inclusive\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tint stopTokenIndex)  // inclusive\n\t{\n\t\tint n = t.getChildCount();\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\tParseTree child = t.getChild(i);\n\t\t\tParserRuleContext r = getRootOfSubtreeEnclosingRegion(child, startTokenIndex, stopTokenIndex);\n\t\t\tif ( r!=null ) return r;\n\t\t}\n\t\tif ( t instanceof ParserRuleContext ) {\n\t\t\tParserRuleContext r = (ParserRuleContext) t;\n\t\t\tif ( startTokenIndex>=r.getStart().getTokenIndex() && // is range fully contained in t?\n\t\t\t\t (r.getStop()==null || stopTokenIndex<=r.getStop().getTokenIndex()) )\n\t\t\t{\n\t\t\t\t// note: r.getStop()==null likely implies that we bailed out of parser and there's nothing to the right\n\t\t\t\treturn r;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Replace any subtree siblings of root that are completely to left\n\t *  or right of lookahead range with a CommonToken(Token.INVALID_TYPE,\"...\")\n\t *  node. The source interval for t is not altered to suit smaller range!\n\t *\n\t *  WARNING: destructive to t.\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic static void stripChildrenOutOfRange(ParserRuleContext t,\n\t\t\t\t\t\t\t\t\t\t\t   ParserRuleContext root,\n\t\t\t\t\t\t\t\t\t\t\t   int startIndex,\n\t\t\t\t\t\t\t\t\t\t\t   int stopIndex)\n\t{\n\t\tif ( t==null ) return;\n\t\tfor (int i = 0; i < t.getChildCount(); i++) {\n\t\t\tParseTree child = t.getChild(i);\n\t\t\tInterval range = child.getSourceInterval();\n\t\t\tif ( child instanceof ParserRuleContext && (range.b < startIndex || range.a > stopIndex) ) {\n\t\t\t\tif ( isAncestorOf(child, root) ) { // replace only if subtree doesn't have displayed root\n\t\t\t\t\tCommonToken abbrev = new CommonToken(Token.INVALID_TYPE, \"...\");\n\t\t\t\t\tt.children.set(i, new TerminalNodeImpl(abbrev));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Return first node satisfying the pred\n\t *\n \t *  @since 4.5.1\n\t */\n\tpublic static Tree findNodeSuchThat(Tree t, Predicate<Tree> pred) {\n\t\tif ( pred.test(t) ) return t;\n\n\t\tif ( t==null ) return null;\n\n\t\tint n = t.getChildCount();\n\t\tfor (int i = 0 ; i < n ; i++){\n\t\t\tTree u = findNodeSuchThat(t.getChild(i), pred);\n\t\t\tif ( u!=null ) return u;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate Trees() {\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/Chunk.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\n/**\n * A chunk is either a token tag, a rule tag, or a span of literal text within a\n * tree pattern.\n *\n * <p>The method {@link ParseTreePatternMatcher#split(String)} returns a list of\n * chunks in preparation for creating a token stream by\n * {@link ParseTreePatternMatcher#tokenize(String)}. From there, we get a parse\n * tree from with {@link ParseTreePatternMatcher#compile(String, int)}. These\n * chunks are converted to {@link RuleTagToken}, {@link TokenTagToken}, or the\n * regular tokens of the text surrounding the tags.</p>\n */\nabstract class Chunk {\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/ParseTreeMatch.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\nimport org.antlr.v4.runtime.misc.MultiMap;\nimport org.antlr.v4.runtime.tree.ParseTree;\n\nimport java.util.Collections;\nimport java.util.List;\n\n/**\n * Represents the result of matching a {@link ParseTree} against a tree pattern.\n */\npublic class ParseTreeMatch {\n\t/**\n\t * This is the backing field for {@link #getTree()}.\n\t */\n\tprivate final ParseTree tree;\n\n\t/**\n\t * This is the backing field for {@link #getPattern()}.\n\t */\n\tprivate final ParseTreePattern pattern;\n\n\t/**\n\t * This is the backing field for {@link #getLabels()}.\n\t */\n\tprivate final MultiMap<String, ParseTree> labels;\n\n\t/**\n\t * This is the backing field for {@link #getMismatchedNode()}.\n\t */\n\tprivate final ParseTree mismatchedNode;\n\n\t/**\n\t * Constructs a new instance of {@link ParseTreeMatch} from the specified\n\t * parse tree and pattern.\n\t *\n\t * @param tree The parse tree to match against the pattern.\n\t * @param pattern The parse tree pattern.\n\t * @param labels A mapping from label names to collections of\n\t * {@link ParseTree} objects located by the tree pattern matching process.\n\t * @param mismatchedNode The first node which failed to match the tree\n\t * pattern during the matching process.\n\t *\n\t * @exception IllegalArgumentException if {@code tree} is {@code null}\n\t * @exception IllegalArgumentException if {@code pattern} is {@code null}\n\t * @exception IllegalArgumentException if {@code labels} is {@code null}\n\t */\n\tpublic ParseTreeMatch(ParseTree tree, ParseTreePattern pattern, MultiMap<String, ParseTree> labels, ParseTree mismatchedNode) {\n\t\tif (tree == null) {\n\t\t\tthrow new IllegalArgumentException(\"tree cannot be null\");\n\t\t}\n\n\t\tif (pattern == null) {\n\t\t\tthrow new IllegalArgumentException(\"pattern cannot be null\");\n\t\t}\n\n\t\tif (labels == null) {\n\t\t\tthrow new IllegalArgumentException(\"labels cannot be null\");\n\t\t}\n\n\t\tthis.tree = tree;\n\t\tthis.pattern = pattern;\n\t\tthis.labels = labels;\n\t\tthis.mismatchedNode = mismatchedNode;\n\t}\n\n\t/**\n\t * Get the last node associated with a specific {@code label}.\n\t *\n\t * <p>For example, for pattern {@code <id:ID>}, {@code get(\"id\")} returns the\n\t * node matched for that {@code ID}. If more than one node\n\t * matched the specified label, only the last is returned. If there is\n\t * no node associated with the label, this returns {@code null}.</p>\n\t *\n\t * <p>Pattern tags like {@code <ID>} and {@code <expr>} without labels are\n\t * considered to be labeled with {@code ID} and {@code expr}, respectively.</p>\n\t *\n\t * @param label The label to check.\n\t *\n\t * @return The last {@link ParseTree} to match a tag with the specified\n\t * label, or {@code null} if no parse tree matched a tag with the label.\n\t */\n\n\tpublic ParseTree get(String label) {\n\t\tList<ParseTree> parseTrees = labels.get(label);\n\t\tif ( parseTrees==null || parseTrees.size()==0 ) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn parseTrees.get( parseTrees.size()-1 ); // return last if multiple\n\t}\n\n\t/**\n\t * Return all nodes matching a rule or token tag with the specified label.\n\t *\n\t * <p>If the {@code label} is the name of a parser rule or token in the\n\t * grammar, the resulting list will contain both the parse trees matching\n\t * rule or tags explicitly labeled with the label and the complete set of\n\t * parse trees matching the labeled and unlabeled tags in the pattern for\n\t * the parser rule or token. For example, if {@code label} is {@code \"foo\"},\n\t * the result will contain <em>all</em> of the following.</p>\n\t *\n\t * <ul>\n\t * <li>Parse tree nodes matching tags of the form {@code <foo:anyRuleName>} and\n\t * {@code <foo:AnyTokenName>}.</li>\n\t * <li>Parse tree nodes matching tags of the form {@code <anyLabel:foo>}.</li>\n\t * <li>Parse tree nodes matching tags of the form {@code <foo>}.</li>\n\t * </ul>\n\t *\n\t * @param label The label.\n\t *\n\t * @return A collection of all {@link ParseTree} nodes matching tags with\n\t * the specified {@code label}. If no nodes matched the label, an empty list\n\t * is returned.\n\t */\n\n\tpublic List<ParseTree> getAll(String label) {\n\t\tList<ParseTree> nodes = labels.get(label);\n\t\tif ( nodes==null ) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\treturn nodes;\n\t}\n\n\t/**\n\t * Return a mapping from label &rarr; [list of nodes].\n\t *\n\t * <p>The map includes special entries corresponding to the names of rules and\n\t * tokens referenced in tags in the original pattern. For additional\n\t * information, see the description of {@link #getAll(String)}.</p>\n\t *\n\t * @return A mapping from labels to parse tree nodes. If the parse tree\n\t * pattern did not contain any rule or token tags, this map will be empty.\n\t */\n\n\tpublic MultiMap<String, ParseTree> getLabels() {\n\t\treturn labels;\n\t}\n\n\t/**\n\t * Get the node at which we first detected a mismatch.\n\t *\n\t * @return the node at which we first detected a mismatch, or {@code null}\n\t * if the match was successful.\n\t */\n\n\tpublic ParseTree getMismatchedNode() {\n\t\treturn mismatchedNode;\n\t}\n\n\t/**\n\t * Gets a value indicating whether the match operation succeeded.\n\t *\n\t * @return {@code true} if the match operation succeeded; otherwise,\n\t * {@code false}.\n\t */\n\tpublic boolean succeeded() {\n\t\treturn mismatchedNode == null;\n\t}\n\n\t/**\n\t * Get the tree pattern we are matching against.\n\t *\n\t * @return The tree pattern we are matching against.\n\t */\n\n\tpublic ParseTreePattern getPattern() {\n\t\treturn pattern;\n\t}\n\n\t/**\n\t * Get the parse tree we are trying to match to a pattern.\n\t *\n\t * @return The {@link ParseTree} we are trying to match to a pattern.\n\t */\n\n\tpublic ParseTree getTree() {\n\t\treturn tree;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\n\t\t\t\"Match %s; found %d labels\",\n\t\t\tsucceeded() ? \"succeeded\" : \"failed\",\n\t\t\tgetLabels().size());\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/ParseTreePattern.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.xpath.XPath;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\n/**\n * A pattern like {@code <ID> = <expr>;} converted to a {@link ParseTree} by\n * {@link ParseTreePatternMatcher#compile(String, int)}.\n */\npublic class ParseTreePattern {\n\t/**\n\t * This is the backing field for {@link #getPatternRuleIndex()}.\n\t */\n\tprivate final int patternRuleIndex;\n\n\t/**\n\t * This is the backing field for {@link #getPattern()}.\n\t */\n\n\tprivate final String pattern;\n\n\t/**\n\t * This is the backing field for {@link #getPatternTree()}.\n\t */\n\n\tprivate final ParseTree patternTree;\n\n\t/**\n\t * This is the backing field for {@link #getMatcher()}.\n\t */\n\n\tprivate final ParseTreePatternMatcher matcher;\n\n\t/**\n\t * Construct a new instance of the {@link ParseTreePattern} class.\n\t *\n\t * @param matcher The {@link ParseTreePatternMatcher} which created this\n\t * tree pattern.\n\t * @param pattern The tree pattern in concrete syntax form.\n\t * @param patternRuleIndex The parser rule which serves as the root of the\n\t * tree pattern.\n\t * @param patternTree The tree pattern in {@link ParseTree} form.\n\t */\n\tpublic ParseTreePattern(ParseTreePatternMatcher matcher,\n\t\t\t\t\t\t\tString pattern, int patternRuleIndex, ParseTree patternTree)\n\t{\n\t\tthis.matcher = matcher;\n\t\tthis.patternRuleIndex = patternRuleIndex;\n\t\tthis.pattern = pattern;\n\t\tthis.patternTree = patternTree;\n\t}\n\n\t/**\n\t * Match a specific parse tree against this tree pattern.\n\t *\n\t * @param tree The parse tree to match against this tree pattern.\n\t * @return A {@link ParseTreeMatch} object describing the result of the\n\t * match operation. The {@link ParseTreeMatch#succeeded()} method can be\n\t * used to determine whether or not the match was successful.\n\t */\n\n\tpublic ParseTreeMatch match(ParseTree tree) {\n\t\treturn matcher.match(tree, this);\n\t}\n\n\t/**\n\t * Determine whether or not a parse tree matches this tree pattern.\n\t *\n\t * @param tree The parse tree to match against this tree pattern.\n\t * @return {@code true} if {@code tree} is a match for the current tree\n\t * pattern; otherwise, {@code false}.\n\t */\n\tpublic boolean matches(ParseTree tree) {\n\t\treturn matcher.match(tree, this).succeeded();\n\t}\n\n\t/**\n\t * Find all nodes using XPath and then try to match those subtrees against\n\t * this tree pattern.\n\t *\n\t * @param tree The {@link ParseTree} to match against this pattern.\n\t * @param xpath An expression matching the nodes\n\t *\n\t * @return A collection of {@link ParseTreeMatch} objects describing the\n\t * successful matches. Unsuccessful matches are omitted from the result,\n\t * regardless of the reason for the failure.\n\t */\n\n\tpublic List<ParseTreeMatch> findAll(ParseTree tree, String xpath) {\n\t\tCollection<ParseTree> subtrees = XPath.findAll(tree, xpath, matcher.getParser());\n\t\tList<ParseTreeMatch> matches = new ArrayList<ParseTreeMatch>();\n\t\tfor (ParseTree t : subtrees) {\n\t\t\tParseTreeMatch match = match(t);\n\t\t\tif ( match.succeeded() ) {\n\t\t\t\tmatches.add(match);\n\t\t\t}\n\t\t}\n\t\treturn matches;\n\t}\n\n\t/**\n\t * Get the {@link ParseTreePatternMatcher} which created this tree pattern.\n\t *\n\t * @return The {@link ParseTreePatternMatcher} which created this tree\n\t * pattern.\n\t */\n\n\tpublic ParseTreePatternMatcher getMatcher() {\n\t\treturn matcher;\n\t}\n\n\t/**\n\t * Get the tree pattern in concrete syntax form.\n\t *\n\t * @return The tree pattern in concrete syntax form.\n\t */\n\n\tpublic String getPattern() {\n\t\treturn pattern;\n\t}\n\n\t/**\n\t * Get the parser rule which serves as the outermost rule for the tree\n\t * pattern.\n\t *\n\t * @return The parser rule which serves as the outermost rule for the tree\n\t * pattern.\n\t */\n\tpublic int getPatternRuleIndex() {\n\t\treturn patternRuleIndex;\n\t}\n\n\t/**\n\t * Get the tree pattern as a {@link ParseTree}. The rule and token tags from\n\t * the pattern are present in the parse tree as terminal nodes with a symbol\n\t * of type {@link RuleTagToken} or {@link TokenTagToken}.\n\t *\n\t * @return The tree pattern as a {@link ParseTree}.\n\t */\n\n\tpublic ParseTree getPatternTree() {\n\t\treturn patternTree;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/ParseTreePatternMatcher.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.BailErrorStrategy;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.ListTokenSource;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.RecognitionException;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.misc.MultiMap;\nimport org.antlr.v4.runtime.misc.ParseCancellationException;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.RuleNode;\nimport org.antlr.v4.runtime.tree.TerminalNode;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * A tree pattern matching mechanism for ANTLR {@link ParseTree}s.\n *\n * <p>Patterns are strings of source input text with special tags representing\n * token or rule references such as:</p>\n *\n * <p>{@code <ID> = <expr>;}</p>\n *\n * <p>Given a pattern start rule such as {@code statement}, this object constructs\n * a {@link ParseTree} with placeholders for the {@code ID} and {@code expr}\n * subtree. Then the {@link #match} routines can compare an actual\n * {@link ParseTree} from a parse with this pattern. Tag {@code <ID>} matches\n * any {@code ID} token and tag {@code <expr>} references the result of the\n * {@code expr} rule (generally an instance of {@code ExprContext}.</p>\n *\n * <p>Pattern {@code x = 0;} is a similar pattern that matches the same pattern\n * except that it requires the identifier to be {@code x} and the expression to\n * be {@code 0}.</p>\n *\n * <p>The {@link #matches} routines return {@code true} or {@code false} based\n * upon a match for the tree rooted at the parameter sent in. The\n * {@link #match} routines return a {@link ParseTreeMatch} object that\n * contains the parse tree, the parse tree pattern, and a map from tag name to\n * matched nodes (more below). A subtree that fails to match, returns with\n * {@link ParseTreeMatch#mismatchedNode} set to the first tree node that did not\n * match.</p>\n *\n * <p>For efficiency, you can compile a tree pattern in string form to a\n * {@link ParseTreePattern} object.</p>\n *\n * <p>See {@code TestParseTreeMatcher} for lots of examples.\n * {@link ParseTreePattern} has two static helper methods:\n * {@link ParseTreePattern#findAll} and {@link ParseTreePattern#match} that\n * are easy to use but not super efficient because they create new\n * {@link ParseTreePatternMatcher} objects each time and have to compile the\n * pattern in string form before using it.</p>\n *\n * <p>The lexer and parser that you pass into the {@link ParseTreePatternMatcher}\n * constructor are used to parse the pattern in string form. The lexer converts\n * the {@code <ID> = <expr>;} into a sequence of four tokens (assuming lexer\n * throws out whitespace or puts it on a hidden channel). Be aware that the\n * input stream is reset for the lexer (but not the parser; a\n * {@link ParserInterpreter} is created to parse the input.). Any user-defined\n * fields you have put into the lexer might get changed when this mechanism asks\n * it to scan the pattern string.</p>\n *\n * <p>Normally a parser does not accept token {@code <expr>} as a valid\n * {@code expr} but, from the parser passed in, we create a special version of\n * the underlying grammar representation (an {@link ATN}) that allows imaginary\n * tokens representing rules ({@code <expr>}) to match entire rules. We call\n * these <em>bypass alternatives</em>.</p>\n *\n * <p>Delimiters are {@code <} and {@code >}, with {@code \\} as the escape string\n * by default, but you can set them to whatever you want using\n * {@link #setDelimiters}. You must escape both start and stop strings\n * {@code \\<} and {@code \\>}.</p>\n */\npublic class ParseTreePatternMatcher {\n\tpublic static class CannotInvokeStartRule extends RuntimeException {\n\t\tpublic CannotInvokeStartRule(Throwable e) {\n\t\t\tsuper(e);\n\t\t}\n\t}\n\n\t// Fixes https://github.com/antlr/antlr4/issues/413\n\t// \"Tree pattern compilation doesn't check for a complete parse\"\n\tpublic static class StartRuleDoesNotConsumeFullPattern extends RuntimeException {\n\t}\n\n\t/**\n\t * This is the backing field for {@link #getLexer()}.\n\t */\n\tprivate final Lexer lexer;\n\n\t/**\n\t * This is the backing field for {@link #getParser()}.\n\t */\n\tprivate final Parser parser;\n\n\tprotected String start = \"<\";\n\tprotected String stop = \">\";\n\tprotected String escape = \"\\\\\"; // e.g., \\< and \\> must escape BOTH!\n\n\t/**\n\t * Constructs a {@link ParseTreePatternMatcher} or from a {@link Lexer} and\n\t * {@link Parser} object. The lexer input stream is altered for tokenizing\n\t * the tree patterns. The parser is used as a convenient mechanism to get\n\t * the grammar name, plus token, rule names.\n\t */\n\tpublic ParseTreePatternMatcher(Lexer lexer, Parser parser) {\n\t\tthis.lexer = lexer;\n\t\tthis.parser = parser;\n\t}\n\n\t/**\n\t * Set the delimiters used for marking rule and token tags within concrete\n\t * syntax used by the tree pattern parser.\n\t *\n\t * @param start The start delimiter.\n\t * @param stop The stop delimiter.\n\t * @param escapeLeft The escape sequence to use for escaping a start or stop delimiter.\n\t *\n\t * @exception IllegalArgumentException if {@code start} is {@code null} or empty.\n\t * @exception IllegalArgumentException if {@code stop} is {@code null} or empty.\n\t */\n\tpublic void setDelimiters(String start, String stop, String escapeLeft) {\n\t\tif (start == null || start.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"start cannot be null or empty\");\n\t\t}\n\n\t\tif (stop == null || stop.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"stop cannot be null or empty\");\n\t\t}\n\n\t\tthis.start = start;\n\t\tthis.stop = stop;\n\t\tthis.escape = escapeLeft;\n\t}\n\n\t/** Does {@code pattern} matched as rule {@code patternRuleIndex} match {@code tree}? */\n\tpublic boolean matches(ParseTree tree, String pattern, int patternRuleIndex) {\n\t\tParseTreePattern p = compile(pattern, patternRuleIndex);\n\t\treturn matches(tree, p);\n\t}\n\n\t/** Does {@code pattern} matched as rule patternRuleIndex match tree? Pass in a\n\t *  compiled pattern instead of a string representation of a tree pattern.\n\t */\n\tpublic boolean matches(ParseTree tree, ParseTreePattern pattern) {\n\t\tMultiMap<String, ParseTree> labels = new MultiMap<String, ParseTree>();\n\t\tParseTree mismatchedNode = matchImpl(tree, pattern.getPatternTree(), labels);\n\t\treturn mismatchedNode == null;\n\t}\n\n\t/**\n\t * Compare {@code pattern} matched as rule {@code patternRuleIndex} against\n\t * {@code tree} and return a {@link ParseTreeMatch} object that contains the\n\t * matched elements, or the node at which the match failed.\n\t */\n\tpublic ParseTreeMatch match(ParseTree tree, String pattern, int patternRuleIndex) {\n\t\tParseTreePattern p = compile(pattern, patternRuleIndex);\n\t\treturn match(tree, p);\n\t}\n\n\t/**\n\t * Compare {@code pattern} matched against {@code tree} and return a\n\t * {@link ParseTreeMatch} object that contains the matched elements, or the\n\t * node at which the match failed. Pass in a compiled pattern instead of a\n\t * string representation of a tree pattern.\n\t */\n\n\tpublic ParseTreeMatch match(ParseTree tree, ParseTreePattern pattern) {\n\t\tMultiMap<String, ParseTree> labels = new MultiMap<String, ParseTree>();\n\t\tParseTree mismatchedNode = matchImpl(tree, pattern.getPatternTree(), labels);\n\t\treturn new ParseTreeMatch(tree, pattern, labels, mismatchedNode);\n\t}\n\n\t/**\n\t * For repeated use of a tree pattern, compile it to a\n\t * {@link ParseTreePattern} using this method.\n\t */\n\tpublic ParseTreePattern compile(String pattern, int patternRuleIndex) {\n\t\tList<? extends Token> tokenList = tokenize(pattern);\n\t\tListTokenSource tokenSrc = new ListTokenSource(tokenList);\n\t\tCommonTokenStream tokens = new CommonTokenStream(tokenSrc);\n\n\t\tParserInterpreter parserInterp = new ParserInterpreter(parser.getGrammarFileName(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   parser.getVocabulary(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   Arrays.asList(parser.getRuleNames()),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   parser.getATNWithBypassAlts(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   tokens);\n\n\t\tParseTree tree = null;\n\t\ttry {\n\t\t\tparserInterp.setErrorHandler(new BailErrorStrategy());\n\t\t\ttree = parserInterp.parse(patternRuleIndex);\n//\t\t\tSystem.out.println(\"pattern tree = \"+tree.toStringTree(parserInterp));\n\t\t}\n\t\tcatch (ParseCancellationException e) {\n\t\t\tthrow (RecognitionException)e.getCause();\n\t\t}\n\t\tcatch (RecognitionException re) {\n\t\t\tthrow re;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new CannotInvokeStartRule(e);\n\t\t}\n\n\t\t// Make sure tree pattern compilation checks for a complete parse\n\t\tif ( tokens.LA(1)!=Token.EOF ) {\n\t\t\tthrow new StartRuleDoesNotConsumeFullPattern();\n\t\t}\n\n\t\treturn new ParseTreePattern(this, pattern, patternRuleIndex, tree);\n\t}\n\n\t/**\n\t * Used to convert the tree pattern string into a series of tokens. The\n\t * input stream is reset.\n\t */\n\n\tpublic Lexer getLexer() {\n\t\treturn lexer;\n\t}\n\n\t/**\n\t * Used to collect to the grammar file name, token names, rule names for\n\t * used to parse the pattern into a parse tree.\n\t */\n\n\tpublic Parser getParser() {\n\t\treturn parser;\n\t}\n\n\t// ---- SUPPORT CODE ----\n\n\t/**\n\t * Recursively walk {@code tree} against {@code patternTree}, filling\n\t * {@code match.}{@link ParseTreeMatch#labels labels}.\n\t *\n\t * @return the first node encountered in {@code tree} which does not match\n\t * a corresponding node in {@code patternTree}, or {@code null} if the match\n\t * was successful. The specific node returned depends on the matching\n\t * algorithm used by the implementation, and may be overridden.\n\t */\n\n\tprotected ParseTree matchImpl(ParseTree tree,\n\t\t\t\t\t\t\t\t  ParseTree patternTree,\n\t\t\t\t\t\t\t\t  MultiMap<String, ParseTree> labels)\n\t{\n\t\tif (tree == null) {\n\t\t\tthrow new IllegalArgumentException(\"tree cannot be null\");\n\t\t}\n\n\t\tif (patternTree == null) {\n\t\t\tthrow new IllegalArgumentException(\"patternTree cannot be null\");\n\t\t}\n\n\t\t// x and <ID>, x and y, or x and x; or could be mismatched types\n\t\tif ( tree instanceof TerminalNode && patternTree instanceof TerminalNode ) {\n\t\t\tTerminalNode t1 = (TerminalNode)tree;\n\t\t\tTerminalNode t2 = (TerminalNode)patternTree;\n\t\t\tParseTree mismatchedNode = null;\n\t\t\t// both are tokens and they have same type\n\t\t\tif ( t1.getSymbol().getType() == t2.getSymbol().getType() ) {\n\t\t\t\tif ( t2.getSymbol() instanceof TokenTagToken ) { // x and <ID>\n\t\t\t\t\tTokenTagToken tokenTagToken = (TokenTagToken)t2.getSymbol();\n\t\t\t\t\t// track label->list-of-nodes for both token name and label (if any)\n\t\t\t\t\tlabels.map(tokenTagToken.getTokenName(), tree);\n\t\t\t\t\tif ( tokenTagToken.getLabel()!=null ) {\n\t\t\t\t\t\tlabels.map(tokenTagToken.getLabel(), tree);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( t1.getText().equals(t2.getText()) ) {\n\t\t\t\t\t// x and x\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// x and y\n\t\t\t\t\tif (mismatchedNode == null) {\n\t\t\t\t\t\tmismatchedNode = t1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (mismatchedNode == null) {\n\t\t\t\t\tmismatchedNode = t1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn mismatchedNode;\n\t\t}\n\n\t\tif ( tree instanceof ParserRuleContext && patternTree instanceof ParserRuleContext ) {\n\t\t\tParserRuleContext r1 = (ParserRuleContext)tree;\n\t\t\tParserRuleContext r2 = (ParserRuleContext)patternTree;\n\t\t\tParseTree mismatchedNode = null;\n\t\t\t// (expr ...) and <expr>\n\t\t\tRuleTagToken ruleTagToken = getRuleTagToken(r2);\n\t\t\tif ( ruleTagToken!=null ) {\n\t\t\t\tParseTreeMatch m = null;\n\t\t\t\tif ( r1.getRuleContext().getRuleIndex() == r2.getRuleContext().getRuleIndex() ) {\n\t\t\t\t\t// track label->list-of-nodes for both rule name and label (if any)\n\t\t\t\t\tlabels.map(ruleTagToken.getRuleName(), tree);\n\t\t\t\t\tif ( ruleTagToken.getLabel()!=null ) {\n\t\t\t\t\t\tlabels.map(ruleTagToken.getLabel(), tree);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (mismatchedNode == null) {\n\t\t\t\t\t\tmismatchedNode = r1;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn mismatchedNode;\n\t\t\t}\n\n\t\t\t// (expr ...) and (expr ...)\n\t\t\tif ( r1.getChildCount()!=r2.getChildCount() ) {\n\t\t\t\tif (mismatchedNode == null) {\n\t\t\t\t\tmismatchedNode = r1;\n\t\t\t\t}\n\n\t\t\t\treturn mismatchedNode;\n\t\t\t}\n\n\t\t\tint n = r1.getChildCount();\n\t\t\tfor (int i = 0; i<n; i++) {\n\t\t\t\tParseTree childMatch = matchImpl(r1.getChild(i), patternTree.getChild(i), labels);\n\t\t\t\tif ( childMatch != null ) {\n\t\t\t\t\treturn childMatch;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn mismatchedNode;\n\t\t}\n\n\t\t// if nodes aren't both tokens or both rule nodes, can't match\n\t\treturn tree;\n\t}\n\n\t/** Is {@code t} {@code (expr <expr>)} subtree? */\n\tprotected RuleTagToken getRuleTagToken(ParseTree t) {\n\t\tif ( t instanceof RuleNode ) {\n\t\t\tRuleNode r = (RuleNode)t;\n\t\t\tif ( r.getChildCount()==1 && r.getChild(0) instanceof TerminalNode ) {\n\t\t\t\tTerminalNode c = (TerminalNode)r.getChild(0);\n\t\t\t\tif ( c.getSymbol() instanceof RuleTagToken ) {\n//\t\t\t\t\tSystem.out.println(\"rule tag subtree \"+t.toStringTree(parser));\n\t\t\t\t\treturn (RuleTagToken)c.getSymbol();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic List<? extends Token> tokenize(String pattern) {\n\t\t// split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)\n\t\tList<Chunk> chunks = split(pattern);\n\n\t\t// create token stream from text and tags\n\t\tList<Token> tokens = new ArrayList<Token>();\n\t\tfor (Chunk chunk : chunks) {\n\t\t\tif ( chunk instanceof TagChunk ) {\n\t\t\t\tTagChunk tagChunk = (TagChunk)chunk;\n\t\t\t\t// add special rule token or conjure up new token from name\n\t\t\t\tif ( Character.isUpperCase(tagChunk.getTag().charAt(0)) ) {\n\t\t\t\t\tInteger ttype = parser.getTokenType(tagChunk.getTag());\n\t\t\t\t\tif ( ttype==Token.INVALID_TYPE ) {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown token \"+tagChunk.getTag()+\" in pattern: \"+pattern);\n\t\t\t\t\t}\n\t\t\t\t\tTokenTagToken t = new TokenTagToken(tagChunk.getTag(), ttype, tagChunk.getLabel());\n\t\t\t\t\ttokens.add(t);\n\t\t\t\t}\n\t\t\t\telse if ( Character.isLowerCase(tagChunk.getTag().charAt(0)) ) {\n\t\t\t\t\tint ruleIndex = parser.getRuleIndex(tagChunk.getTag());\n\t\t\t\t\tif ( ruleIndex==-1 ) {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown rule \"+tagChunk.getTag()+\" in pattern: \"+pattern);\n\t\t\t\t\t}\n\t\t\t\t\tint ruleImaginaryTokenType = parser.getATNWithBypassAlts().ruleToTokenType[ruleIndex];\n\t\t\t\t\ttokens.add(new RuleTagToken(tagChunk.getTag(), ruleImaginaryTokenType, tagChunk.getLabel()));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid tag: \"+tagChunk.getTag()+\" in pattern: \"+pattern);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tTextChunk textChunk = (TextChunk)chunk;\n\t\t\t\tANTLRInputStream in = new ANTLRInputStream(textChunk.getText());\n\t\t\t\tlexer.setInputStream(in);\n\t\t\t\tToken t = lexer.nextToken();\n\t\t\t\twhile ( t.getType()!=Token.EOF ) {\n\t\t\t\t\ttokens.add(t);\n\t\t\t\t\tt = lexer.nextToken();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n//\t\tSystem.out.println(\"tokens=\"+tokens);\n\t\treturn tokens;\n\t}\n\n\t/** Split {@code <ID> = <e:expr> ;} into 4 chunks for tokenizing by {@link #tokenize}. */\n\tpublic List<Chunk> split(String pattern) {\n\t\tint p = 0;\n\t\tint n = pattern.length();\n\t\tList<Chunk> chunks = new ArrayList<Chunk>();\n\t\tStringBuilder buf = new StringBuilder();\n\t\t// find all start and stop indexes first, then collect\n\t\tList<Integer> starts = new ArrayList<Integer>();\n\t\tList<Integer> stops = new ArrayList<Integer>();\n\t\twhile ( p<n ) {\n\t\t\tif ( p == pattern.indexOf(escape+start,p) ) {\n\t\t\t\tp += escape.length() + start.length();\n\t\t\t}\n\t\t\telse if ( p == pattern.indexOf(escape+stop,p) ) {\n\t\t\t\tp += escape.length() + stop.length();\n\t\t\t}\n\t\t\telse if ( p == pattern.indexOf(start,p) ) {\n\t\t\t\tstarts.add(p);\n\t\t\t\tp += start.length();\n\t\t\t}\n\t\t\telse if ( p == pattern.indexOf(stop,p) ) {\n\t\t\t\tstops.add(p);\n\t\t\t\tp += stop.length();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp++;\n\t\t\t}\n\t\t}\n\n//\t\tSystem.out.println(\"\");\n//\t\tSystem.out.println(starts);\n//\t\tSystem.out.println(stops);\n\t\tif ( starts.size() > stops.size() ) {\n\t\t\tthrow new IllegalArgumentException(\"unterminated tag in pattern: \"+pattern);\n\t\t}\n\n\t\tif ( starts.size() < stops.size() ) {\n\t\t\tthrow new IllegalArgumentException(\"missing start tag in pattern: \"+pattern);\n\t\t}\n\n\t\tint ntags = starts.size();\n\t\tfor (int i=0; i<ntags; i++) {\n\t\t\tif ( starts.get(i)>=stops.get(i) ) {\n\t\t\t\tthrow new IllegalArgumentException(\"tag delimiters out of order in pattern: \"+pattern);\n\t\t\t}\n\t\t}\n\n\t\t// collect into chunks now\n\t\tif ( ntags==0 ) {\n\t\t\tString text = pattern.substring(0, n);\n\t\t\tchunks.add(new TextChunk(text));\n\t\t}\n\n\t\tif ( ntags>0 && starts.get(0)>0 ) { // copy text up to first tag into chunks\n\t\t\tString text = pattern.substring(0, starts.get(0));\n\t\t\tchunks.add(new TextChunk(text));\n\t\t}\n\t\tfor (int i=0; i<ntags; i++) {\n\t\t\t// copy inside of <tag>\n\t\t\tString tag = pattern.substring(starts.get(i) + start.length(), stops.get(i));\n\t\t\tString ruleOrToken = tag;\n\t\t\tString label = null;\n\t\t\tint colon = tag.indexOf(':');\n\t\t\tif ( colon >= 0 ) {\n\t\t\t\tlabel = tag.substring(0,colon);\n\t\t\t\truleOrToken = tag.substring(colon+1, tag.length());\n\t\t\t}\n\t\t\tchunks.add(new TagChunk(label, ruleOrToken));\n\t\t\tif ( i+1 < ntags ) {\n\t\t\t\t// copy from end of <tag> to start of next\n\t\t\t\tString text = pattern.substring(stops.get(i) + stop.length(), starts.get(i + 1));\n\t\t\t\tchunks.add(new TextChunk(text));\n\t\t\t}\n\t\t}\n\t\tif ( ntags>0 ) {\n\t\t\tint afterLastTag = stops.get(ntags - 1) + stop.length();\n\t\t\tif ( afterLastTag < n ) { // copy text from end of last tag to end\n\t\t\t\tString text = pattern.substring(afterLastTag, n);\n\t\t\t\tchunks.add(new TextChunk(text));\n\t\t\t}\n\t\t}\n\n\t\t// strip out the escape sequences from text chunks but not tags\n\t\tfor (int i = 0; i < chunks.size(); i++) {\n\t\t\tChunk c = chunks.get(i);\n\t\t\tif ( c instanceof TextChunk ) {\n\t\t\t\tTextChunk tc = (TextChunk)c;\n\t\t\t\tString unescaped = tc.getText().replace(escape, \"\");\n\t\t\t\tif (unescaped.length() < tc.getText().length()) {\n\t\t\t\t\tchunks.set(i, new TextChunk(unescaped));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn chunks;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/RuleTagToken.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenSource;\n\n/**\n * A {@link Token} object representing an entire subtree matched by a parser\n * rule; e.g., {@code <expr>}. These tokens are created for {@link TagChunk}\n * chunks where the tag corresponds to a parser rule.\n */\npublic class RuleTagToken implements Token {\n\t/**\n\t * This is the backing field for {@link #getRuleName}.\n\t */\n\tprivate final String ruleName;\n\t/**\n\t * The token type for the current token. This is the token type assigned to\n\t * the bypass alternative for the rule during ATN deserialization.\n\t */\n\tprivate final int bypassTokenType;\n\t/**\n\t * This is the backing field for {@link #getLabel}.\n\t */\n\tprivate final String label;\n\n\t/**\n\t * Constructs a new instance of {@link RuleTagToken} with the specified rule\n\t * name and bypass token type and no label.\n\t *\n\t * @param ruleName The name of the parser rule this rule tag matches.\n\t * @param bypassTokenType The bypass token type assigned to the parser rule.\n\t *\n\t * @exception IllegalArgumentException if {@code ruleName} is {@code null}\n\t * or empty.\n\t */\n\tpublic RuleTagToken(String ruleName, int bypassTokenType) {\n\t\tthis(ruleName, bypassTokenType, null);\n\t}\n\n\t/**\n\t * Constructs a new instance of {@link RuleTagToken} with the specified rule\n\t * name, bypass token type, and label.\n\t *\n\t * @param ruleName The name of the parser rule this rule tag matches.\n\t * @param bypassTokenType The bypass token type assigned to the parser rule.\n\t * @param label The label associated with the rule tag, or {@code null} if\n\t * the rule tag is unlabeled.\n\t *\n\t * @exception IllegalArgumentException if {@code ruleName} is {@code null}\n\t * or empty.\n\t */\n\tpublic RuleTagToken(String ruleName, int bypassTokenType, String label) {\n\t\tif (ruleName == null || ruleName.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"ruleName cannot be null or empty.\");\n\t\t}\n\n\t\tthis.ruleName = ruleName;\n\t\tthis.bypassTokenType = bypassTokenType;\n\t\tthis.label = label;\n\t}\n\n\t/**\n\t * Gets the name of the rule associated with this rule tag.\n\t *\n\t * @return The name of the parser rule associated with this rule tag.\n\t */\n\n\tpublic final String getRuleName() {\n\t\treturn ruleName;\n\t}\n\n\t/**\n\t * Gets the label associated with the rule tag.\n\t *\n\t * @return The name of the label associated with the rule tag, or\n\t * {@code null} if this is an unlabeled rule tag.\n\t */\n\n\tpublic final String getLabel() {\n\t\treturn label;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>Rule tag tokens are always placed on the {@link #DEFAULT_CHANNEL}.</p>\n\t */\n\t@Override\n\tpublic int getChannel() {\n\t\treturn DEFAULT_CHANNEL;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>This method returns the rule tag formatted with {@code <} and {@code >}\n\t * delimiters.</p>\n\t */\n\t@Override\n\tpublic String getText() {\n\t\tif (label != null) {\n\t\t\treturn \"<\" + label + \":\" + ruleName + \">\";\n\t\t}\n\n\t\treturn \"<\" + ruleName + \">\";\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>Rule tag tokens have types assigned according to the rule bypass\n\t * transitions created during ATN deserialization.</p>\n\t */\n\t@Override\n\tpublic int getType() {\n\t\treturn bypassTokenType;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} always returns 0.</p>\n\t */\n\t@Override\n\tpublic int getLine() {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} always returns -1.</p>\n\t */\n\t@Override\n\tpublic int getCharPositionInLine() {\n\t\treturn -1;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} always returns -1.</p>\n\t */\n\t@Override\n\tpublic int getTokenIndex() {\n\t\treturn -1;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} always returns -1.</p>\n\t */\n\t@Override\n\tpublic int getStartIndex() {\n\t\treturn -1;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} always returns -1.</p>\n\t */\n\t@Override\n\tpublic int getStopIndex() {\n\t\treturn -1;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} always returns {@code null}.</p>\n\t */\n\t@Override\n\tpublic TokenSource getTokenSource() {\n\t\treturn null;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} always returns {@code null}.</p>\n\t */\n\t@Override\n\tpublic CharStream getInputStream() {\n\t\treturn null;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link RuleTagToken} returns a string of the form\n\t * {@code ruleName:bypassTokenType}.</p>\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn ruleName + \":\" + bypassTokenType;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/TagChunk.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\n/**\n * Represents a placeholder tag in a tree pattern. A tag can have any of the\n * following forms.\n *\n * <ul>\n * <li>{@code expr}: An unlabeled placeholder for a parser rule {@code expr}.</li>\n * <li>{@code ID}: An unlabeled placeholder for a token of type {@code ID}.</li>\n * <li>{@code e:expr}: A labeled placeholder for a parser rule {@code expr}.</li>\n * <li>{@code id:ID}: A labeled placeholder for a token of type {@code ID}.</li>\n * </ul>\n *\n * This class does not perform any validation on the tag or label names aside\n * from ensuring that the tag is a non-null, non-empty string.\n */\nclass TagChunk extends Chunk {\n\t/**\n\t * This is the backing field for {@link #getTag}.\n\t */\n\tprivate final String tag;\n\t/**\n\t * This is the backing field for {@link #getLabel}.\n\t */\n\tprivate final String label;\n\n\t/**\n\t * Construct a new instance of {@link TagChunk} using the specified tag and\n\t * no label.\n\t *\n\t * @param tag The tag, which should be the name of a parser rule or token\n\t * type.\n\t *\n\t * @exception IllegalArgumentException if {@code tag} is {@code null} or\n\t * empty.\n\t */\n\tpublic TagChunk(String tag) {\n\t\tthis(null, tag);\n\t}\n\n\t/**\n\t * Construct a new instance of {@link TagChunk} using the specified label\n\t * and tag.\n\t *\n\t * @param label The label for the tag. If this is {@code null}, the\n\t * {@link TagChunk} represents an unlabeled tag.\n\t * @param tag The tag, which should be the name of a parser rule or token\n\t * type.\n\t *\n\t * @exception IllegalArgumentException if {@code tag} is {@code null} or\n\t * empty.\n\t */\n\tpublic TagChunk(String label, String tag) {\n\t\tif (tag == null || tag.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"tag cannot be null or empty\");\n\t\t}\n\n\t\tthis.label = label;\n\t\tthis.tag = tag;\n\t}\n\n\t/**\n\t * Get the tag for this chunk.\n\t *\n\t * @return The tag for the chunk.\n\t */\n\n\tpublic final String getTag() {\n\t\treturn tag;\n\t}\n\n\t/**\n\t * Get the label, if any, assigned to this chunk.\n\t *\n\t * @return The label assigned to this chunk, or {@code null} if no label is\n\t * assigned to the chunk.\n\t */\n\n\tpublic final String getLabel() {\n\t\treturn label;\n\t}\n\n\t/**\n\t * This method returns a text representation of the tag chunk. Labeled tags\n\t * are returned in the form {@code label:tag}, and unlabeled tags are\n\t * returned as just the tag name.\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tif (label != null) {\n\t\t\treturn label + \":\" + tag;\n\t\t}\n\n\t\treturn tag;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/TextChunk.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\n/**\n * Represents a span of raw text (concrete syntax) between tags in a tree\n * pattern string.\n */\nclass TextChunk extends Chunk {\n\t/**\n\t * This is the backing field for {@link #getText}.\n\t */\n\n\tprivate final String text;\n\n\t/**\n\t * Constructs a new instance of {@link TextChunk} with the specified text.\n\t *\n\t * @param text The text of this chunk.\n\t * @exception IllegalArgumentException if {@code text} is {@code null}.\n\t */\n\tpublic TextChunk(String text) {\n\t\tif (text == null) {\n\t\t\tthrow new IllegalArgumentException(\"text cannot be null\");\n\t\t}\n\n\t\tthis.text = text;\n\t}\n\n\t/**\n\t * Gets the raw text of this chunk.\n\t *\n\t * @return The text of the chunk.\n\t */\n\n\tpublic final String getText() {\n\t\treturn text;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link TextChunk} returns the result of\n\t * {@link #getText()} in single quotes.</p>\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn \"'\"+text+\"'\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/pattern/TokenTagToken.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.pattern;\n\nimport org.antlr.v4.runtime.CommonToken;\nimport org.antlr.v4.runtime.Token;\n\n/**\n * A {@link Token} object representing a token of a particular type; e.g.,\n * {@code <ID>}. These tokens are created for {@link TagChunk} chunks where the\n * tag corresponds to a lexer rule or token type.\n */\npublic class TokenTagToken extends CommonToken {\n\t/**\n\t * This is the backing field for {@link #getTokenName}.\n\t */\n\n\tprivate final String tokenName;\n\t/**\n\t * This is the backing field for {@link #getLabel}.\n\t */\n\n\tprivate final String label;\n\n\t/**\n\t * Constructs a new instance of {@link TokenTagToken} for an unlabeled tag\n\t * with the specified token name and type.\n\t *\n\t * @param tokenName The token name.\n\t * @param type The token type.\n\t */\n\tpublic TokenTagToken(String tokenName, int type) {\n\t\tthis(tokenName, type, null);\n\t}\n\n\t/**\n\t * Constructs a new instance of {@link TokenTagToken} with the specified\n\t * token name, type, and label.\n\t *\n\t * @param tokenName The token name.\n\t * @param type The token type.\n\t * @param label The label associated with the token tag, or {@code null} if\n\t * the token tag is unlabeled.\n\t */\n\tpublic TokenTagToken(String tokenName, int type, String label) {\n\t\tsuper(type);\n\t\tthis.tokenName = tokenName;\n\t\tthis.label = label;\n\t}\n\n\t/**\n\t * Gets the token name.\n\t * @return The token name.\n\t */\n\n\tpublic final String getTokenName() {\n\t\treturn tokenName;\n\t}\n\n\t/**\n\t * Gets the label associated with the rule tag.\n\t *\n\t * @return The name of the label associated with the rule tag, or\n\t * {@code null} if this is an unlabeled rule tag.\n\t */\n\n\tpublic final String getLabel() {\n\t\treturn label;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link TokenTagToken} returns the token tag\n\t * formatted with {@code <} and {@code >} delimiters.</p>\n\t */\n\t@Override\n\tpublic String getText() {\n\t\tif (label != null) {\n\t\t\treturn \"<\" + label + \":\" + tokenName + \">\";\n\t\t}\n\n\t\treturn \"<\" + tokenName + \">\";\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The implementation for {@link TokenTagToken} returns a string of the form\n\t * {@code tokenName:type}.</p>\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn tokenName + \":\" + type;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPath.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.LexerNoViableAltException;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.tree.ParseTree;\n\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.LinkedHashSet;\nimport java.util.List;\n\n/**\n * Represent a subset of XPath XML path syntax for use in identifying nodes in\n * parse trees.\n *\n * <p>\n * Split path into words and separators {@code /} and {@code //} via ANTLR\n * itself then walk path elements from left to right. At each separator-word\n * pair, find set of nodes. Next stage uses those as work list.</p>\n *\n * <p>\n * The basic interface is\n * {@link XPath#findAll ParseTree.findAll}{@code (tree, pathString, parser)}.\n * But that is just shorthand for:</p>\n *\n * <pre>\n * {@link XPath} p = new {@link XPath#XPath XPath}(parser, pathString);\n * return p.{@link #evaluate evaluate}(tree);\n * </pre>\n *\n * <p>\n * See {@code org.antlr.v4.test.TestXPath} for descriptions. In short, this\n * allows operators:</p>\n *\n * <dl>\n * <dt>/</dt> <dd>root</dd>\n * <dt>//</dt> <dd>anywhere</dd>\n * <dt>!</dt> <dd>invert; this must appear directly after root or anywhere\n * operator</dd>\n * </dl>\n *\n * <p>\n * and path elements:</p>\n *\n * <dl>\n * <dt>ID</dt> <dd>token name</dd>\n * <dt>'string'</dt> <dd>any string literal token from the grammar</dd>\n * <dt>expr</dt> <dd>rule name</dd>\n * <dt>*</dt> <dd>wildcard matching any node</dd>\n * </dl>\n *\n * <p>\n * Whitespace is not allowed.</p>\n */\npublic class XPath {\n\tpublic static final String WILDCARD = \"*\"; // word not operator/separator\n\tpublic static final String NOT = \"!\"; \t   // word for invert operator\n\n\tprotected String path;\n\tprotected XPathElement[] elements;\n\tprotected Parser parser;\n\n\tpublic XPath(Parser parser, String path) {\n\t\tthis.parser = parser;\n\t\tthis.path = path;\n\t\telements = split(path);\n//\t\tSystem.out.println(Arrays.toString(elements));\n\t}\n\n\t// TODO: check for invalid token/rule names, bad syntax\n\n\tpublic XPathElement[] split(String path) {\n\t\tANTLRInputStream in;\n\t\ttry {\n\t\t\tin = new ANTLRInputStream(new StringReader(path));\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tthrow new IllegalArgumentException(\"Could not read path: \"+path, ioe);\n\t\t}\n\t\tXPathLexer lexer = new XPathLexer(in) {\n\t\t\t@Override\n\t\t\tpublic void recover(LexerNoViableAltException e) { throw e;\t}\n\t\t};\n\t\tlexer.removeErrorListeners();\n\t\tlexer.addErrorListener(new XPathLexerErrorListener());\n\t\tCommonTokenStream tokenStream = new CommonTokenStream(lexer);\n\t\ttry {\n\t\t\ttokenStream.fill();\n\t\t}\n\t\tcatch (LexerNoViableAltException e) {\n\t\t\tint pos = lexer.getCharPositionInLine();\n\t\t\tString msg = \"Invalid tokens or characters at index \"+pos+\" in path '\"+path+\"'\";\n\t\t\tthrow new IllegalArgumentException(msg, e);\n\t\t}\n\n\t\tList<Token> tokens = tokenStream.getTokens();\n//\t\tSystem.out.println(\"path=\"+path+\"=>\"+tokens);\n\t\tList<XPathElement> elements = new ArrayList<XPathElement>();\n\t\tint n = tokens.size();\n\t\tint i=0;\nloop:\n\t\twhile ( i<n ) {\n\t\t\tToken el = tokens.get(i);\n\t\t\tToken next = null;\n\t\t\tswitch ( el.getType() ) {\n\t\t\t\tcase XPathLexer.ROOT :\n\t\t\t\tcase XPathLexer.ANYWHERE :\n\t\t\t\t\tboolean anywhere = el.getType() == XPathLexer.ANYWHERE;\n\t\t\t\t\ti++;\n\t\t\t\t\tnext = tokens.get(i);\n\t\t\t\t\tboolean invert = next.getType()==XPathLexer.BANG;\n\t\t\t\t\tif ( invert ) {\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tnext = tokens.get(i);\n\t\t\t\t\t}\n\t\t\t\t\tXPathElement pathElement = getXPathElement(next, anywhere);\n\t\t\t\t\tpathElement.invert = invert;\n\t\t\t\t\telements.add(pathElement);\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase XPathLexer.TOKEN_REF :\n\t\t\t\tcase XPathLexer.RULE_REF :\n\t\t\t\tcase XPathLexer.WILDCARD :\n\t\t\t\t\telements.add( getXPathElement(el, false) );\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase Token.EOF :\n\t\t\t\t\tbreak loop;\n\n\t\t\t\tdefault :\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknowth path element \"+el);\n\t\t\t}\n\t\t}\n\t\treturn elements.toArray(new XPathElement[0]);\n\t}\n\n\t/**\n\t * Convert word like {@code *} or {@code ID} or {@code expr} to a path\n\t * element. {@code anywhere} is {@code true} if {@code //} precedes the\n\t * word.\n\t */\n\tprotected XPathElement getXPathElement(Token wordToken, boolean anywhere) {\n\t\tif ( wordToken.getType()==Token.EOF ) {\n\t\t\tthrow new IllegalArgumentException(\"Missing path element at end of path\");\n\t\t}\n\t\tString word = wordToken.getText();\n\t\tint ttype = parser.getTokenType(word);\n\t\tint ruleIndex = parser.getRuleIndex(word);\n\t\tswitch ( wordToken.getType() ) {\n\t\t\tcase XPathLexer.WILDCARD :\n\t\t\t\treturn anywhere ?\n\t\t\t\t\tnew XPathWildcardAnywhereElement() :\n\t\t\t\t\tnew XPathWildcardElement();\n\t\t\tcase XPathLexer.TOKEN_REF :\n\t\t\tcase XPathLexer.STRING :\n\t\t\t\tif ( ttype==Token.INVALID_TYPE ) {\n\t\t\t\t\tthrow new IllegalArgumentException(word+\n\t\t\t\t\t\t\t\t\t\t\t\t\t   \" at index \"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t   wordToken.getStartIndex()+\n\t\t\t\t\t\t\t\t\t\t\t\t\t   \" isn't a valid token name\");\n\t\t\t\t}\n\t\t\t\treturn anywhere ?\n\t\t\t\t\tnew XPathTokenAnywhereElement(word, ttype) :\n\t\t\t\t\tnew XPathTokenElement(word, ttype);\n\t\t\tdefault :\n\t\t\t\tif ( ruleIndex==-1 ) {\n\t\t\t\t\tthrow new IllegalArgumentException(word+\n\t\t\t\t\t\t\t\t\t\t\t\t\t   \" at index \"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t   wordToken.getStartIndex()+\n\t\t\t\t\t\t\t\t\t\t\t\t\t   \" isn't a valid rule name\");\n\t\t\t\t}\n\t\t\t\treturn anywhere ?\n\t\t\t\t\tnew XPathRuleAnywhereElement(word, ruleIndex) :\n\t\t\t\t\tnew XPathRuleElement(word, ruleIndex);\n\t\t}\n\t}\n\n\n\tpublic static Collection<ParseTree> findAll(ParseTree tree, String xpath, Parser parser) {\n\t\tXPath p = new XPath(parser, xpath);\n\t\treturn p.evaluate(tree);\n\t}\n\n\t/**\n\t * Return a list of all nodes starting at {@code t} as root that satisfy the\n\t * path. The root {@code /} is relative to the node passed to\n\t * {@link #evaluate}.\n\t */\n\tpublic Collection<ParseTree> evaluate(final ParseTree t) {\n\t\tParserRuleContext dummyRoot = new ParserRuleContext();\n\t\tdummyRoot.children = Collections.singletonList(t); // don't set t's parent.\n\n\t\tCollection<ParseTree> work = Collections.<ParseTree>singleton(dummyRoot);\n\n\t\tint i = 0;\n\t\twhile ( i < elements.length ) {\n\t\t\tCollection<ParseTree> next = new LinkedHashSet<ParseTree>();\n\t\t\tfor (ParseTree node : work) {\n\t\t\t\tif ( node.getChildCount()>0 ) {\n\t\t\t\t\t// only try to match next element if it has children\n\t\t\t\t\t// e.g., //func/*/stat might have a token node for which\n\t\t\t\t\t// we can't go looking for stat nodes.\n\t\t\t\t\tCollection<? extends ParseTree> matching = elements[i].evaluate(node);\n\t\t\t\t\tnext.addAll(matching);\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++;\n\t\t\twork = next;\n\t\t}\n\n\t\treturn work;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\n\nimport java.util.Collection;\n\npublic abstract class XPathElement {\n\tprotected String nodeName;\n\tprotected boolean invert;\n\n\t/** Construct element like {@code /ID} or {@code ID} or {@code /*} etc...\n\t *  op is null if just node\n\t */\n\tpublic XPathElement(String nodeName) {\n\t\tthis.nodeName = nodeName;\n\t}\n\n\t/**\n\t * Given tree rooted at {@code t} return all nodes matched by this path\n\t * element.\n\t */\n\tpublic abstract Collection<ParseTree> evaluate(ParseTree t);\n\n\t@Override\n\tpublic String toString() {\n\t\tString inv = invert ? \"!\" : \"\";\n\t\treturn getClass().getSimpleName()+\"[\"+inv+nodeName+\"]\";\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathLexer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CommonToken;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.LexerNoViableAltException;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.misc.Interval;\n\n/** Mimic the old XPathLexer from .g4 file */\npublic class XPathLexer extends Lexer {\n\tpublic static final int\n\t\tTOKEN_REF=1, RULE_REF=2, ANYWHERE=3, ROOT=4, WILDCARD=5, BANG=6, ID=7,\n\t\tSTRING=8;\n\tpublic final static String[] modeNames = {\n\t\t\"DEFAULT_MODE\"\n\t};\n\n\tpublic static final String[] ruleNames = {\n\t\t\"ANYWHERE\", \"ROOT\", \"WILDCARD\", \"BANG\", \"ID\", \"NameChar\", \"NameStartChar\",\n\t\t\"STRING\"\n\t};\n\n\tprivate static final String[] _LITERAL_NAMES = {\n\t\tnull, null, null, \"'//'\", \"'/'\", \"'*'\", \"'!'\"\n\t};\n\tprivate static final String[] _SYMBOLIC_NAMES = {\n\t\tnull, \"TOKEN_REF\", \"RULE_REF\", \"ANYWHERE\", \"ROOT\", \"WILDCARD\", \"BANG\",\n\t\t\"ID\", \"STRING\"\n\t};\n\tpublic static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);\n\n\t/**\n\t * @deprecated Use {@link #VOCABULARY} instead.\n\t */\n\t@Deprecated\n\tpublic static final String[] tokenNames;\n\tstatic {\n\t\ttokenNames = new String[_SYMBOLIC_NAMES.length];\n\t\tfor (int i = 0; i < tokenNames.length; i++) {\n\t\t\ttokenNames[i] = VOCABULARY.getLiteralName(i);\n\t\t\tif (tokenNames[i] == null) {\n\t\t\t\ttokenNames[i] = VOCABULARY.getSymbolicName(i);\n\t\t\t}\n\n\t\t\tif (tokenNames[i] == null) {\n\t\t\t\ttokenNames[i] = \"<INVALID>\";\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getGrammarFileName() { return \"XPathLexer.g4\"; }\n\n\t@Override\n\tpublic String[] getRuleNames() { return ruleNames; }\n\n\t@Override\n\tpublic String[] getModeNames() { return modeNames; }\n\n\t@Override\n\t@Deprecated\n\tpublic String[] getTokenNames() {\n\t\treturn tokenNames;\n\t}\n\n\t@Override\n\tpublic Vocabulary getVocabulary() {\n\t\treturn VOCABULARY;\n\t}\n\n\t@Override\n\tpublic ATN getATN() {\n\t\treturn null;\n\t}\n\n\tprotected int line = 1;\n\tprotected int charPositionInLine = 0;\n\n\tpublic XPathLexer(CharStream input) {\n\t\tsuper(input);\n\t}\n\n\t@Override\n\tpublic Token nextToken() {\n\t\t_tokenStartCharIndex = _input.index();\n\t\tCommonToken t = null;\n\t\twhile ( t==null ) {\n\t\t\tswitch ( _input.LA(1) ) {\n\t\t\t\tcase '/':\n\t\t\t\t\tconsume();\n\t\t\t\t\tif ( _input.LA(1)=='/' ) {\n\t\t\t\t\t\tconsume();\n\t\t\t\t\t\tt = new CommonToken(ANYWHERE, \"//\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tt = new CommonToken(ROOT, \"/\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase '*':\n\t\t\t\t\tconsume();\n\t\t\t\t\tt = new CommonToken(WILDCARD, \"*\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '!':\n\t\t\t\t\tconsume();\n\t\t\t\t\tt = new CommonToken(BANG, \"!\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\\'':\n\t\t\t\t\tString s = matchString();\n\t\t\t\t\tt = new CommonToken(STRING, s);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CharStream.EOF :\n\t\t\t\t\treturn new CommonToken(EOF, \"<EOF>\");\n\t\t\t\tdefault:\n\t\t\t\t\tif ( isNameStartChar(_input.LA(1)) ) {\n\t\t\t\t\t\tString id = matchID();\n\t\t\t\t\t\tif ( Character.isUpperCase(id.charAt(0)) ) t = new CommonToken(TOKEN_REF, id);\n\t\t\t\t\t\telse t = new CommonToken(RULE_REF, id);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tthrow new LexerNoViableAltException(this, _input, _tokenStartCharIndex, null);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tt.setStartIndex(_tokenStartCharIndex);\n\t\tt.setCharPositionInLine(_tokenStartCharIndex);\n\t\tt.setLine(line);\n\t\treturn t;\n\t}\n\n\tpublic void consume() {\n\t\tint curChar = _input.LA(1);\n\t\tif ( curChar=='\\n' ) {\n\t\t\tline++;\n\t\t\tcharPositionInLine=0;\n\t\t}\n\t\telse {\n\t\t\tcharPositionInLine++;\n\t\t}\n\t\t_input.consume();\n\t}\n\n\t@Override\n\tpublic int getCharPositionInLine() {\n\t\treturn charPositionInLine;\n\t}\n\n\tpublic String matchID() {\n\t\tint start = _input.index();\n\t\tconsume(); // drop start char\n\t\twhile ( isNameChar(_input.LA(1)) ) {\n\t\t\tconsume();\n\t\t}\n\t\treturn _input.getText(Interval.of(start,_input.index()-1));\n\t}\n\n\tpublic String matchString() {\n\t\tint start = _input.index();\n\t\tconsume(); // drop first quote\n\t\twhile ( _input.LA(1)!='\\'' ) {\n\t\t\tconsume();\n\t\t}\n\t\tconsume(); // drop last quote\n\t\treturn _input.getText(Interval.of(start,_input.index()-1));\n\t}\n\n\tpublic boolean isNameChar(int c) { return Character.isUnicodeIdentifierPart(c); }\n\n\tpublic boolean isNameStartChar(int c) { return Character.isUnicodeIdentifierStart(c); }\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathLexerErrorListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.BaseErrorListener;\nimport org.antlr.v4.runtime.RecognitionException;\nimport org.antlr.v4.runtime.Recognizer;\n\npublic class XPathLexerErrorListener extends BaseErrorListener {\n\t@Override\n\tpublic void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,\n\t\t\t\t\t\t\tint line, int charPositionInLine, String msg,\n\t\t\t\t\t\t\tRecognitionException e)\n\t{\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathRuleAnywhereElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.Collection;\n\n/**\n * Either {@code ID} at start of path or {@code ...//ID} in middle of path.\n */\npublic class XPathRuleAnywhereElement extends XPathElement {\n\tprotected int ruleIndex;\n\tpublic XPathRuleAnywhereElement(String ruleName, int ruleIndex) {\n\t\tsuper(ruleName);\n\t\tthis.ruleIndex = ruleIndex;\n\t}\n\n\t@Override\n\tpublic Collection<ParseTree> evaluate(ParseTree t) {\n\t\treturn Trees.findAllRuleNodes(t, ruleIndex);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathRuleElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.Tree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\npublic class XPathRuleElement extends XPathElement {\n\tprotected int ruleIndex;\n\tpublic XPathRuleElement(String ruleName, int ruleIndex) {\n\t\tsuper(ruleName);\n\t\tthis.ruleIndex = ruleIndex;\n\t}\n\n\t@Override\n\tpublic Collection<ParseTree> evaluate(ParseTree t) {\n\t\t\t\t// return all children of t that match nodeName\n\t\tList<ParseTree> nodes = new ArrayList<ParseTree>();\n\t\tfor (Tree c : Trees.getChildren(t)) {\n\t\t\tif ( c instanceof ParserRuleContext ) {\n\t\t\t\tParserRuleContext ctx = (ParserRuleContext)c;\n\t\t\t\tif ( (ctx.getRuleIndex() == ruleIndex && !invert) ||\n\t\t\t\t\t (ctx.getRuleIndex() != ruleIndex && invert) )\n\t\t\t\t{\n\t\t\t\t\tnodes.add(ctx);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nodes;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathTokenAnywhereElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.Collection;\n\npublic class XPathTokenAnywhereElement extends XPathElement {\n\tprotected int tokenType;\n\tpublic XPathTokenAnywhereElement(String tokenName, int tokenType) {\n\t\tsuper(tokenName);\n\t\tthis.tokenType = tokenType;\n\t}\n\n\t@Override\n\tpublic Collection<ParseTree> evaluate(ParseTree t) {\n\t\treturn Trees.findAllTokenNodes(t, tokenType);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathTokenElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.TerminalNode;\nimport org.antlr.v4.runtime.tree.Tree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\npublic class XPathTokenElement extends XPathElement {\n\tprotected int tokenType;\n\tpublic XPathTokenElement(String tokenName, int tokenType) {\n\t\tsuper(tokenName);\n\t\tthis.tokenType = tokenType;\n\t}\n\n\t@Override\n\tpublic Collection<ParseTree> evaluate(ParseTree t) {\n\t\t// return all children of t that match nodeName\n\t\tList<ParseTree> nodes = new ArrayList<ParseTree>();\n\t\tfor (Tree c : Trees.getChildren(t)) {\n\t\t\tif ( c instanceof TerminalNode ) {\n\t\t\t\tTerminalNode tnode = (TerminalNode)c;\n\t\t\t\tif ( (tnode.getSymbol().getType() == tokenType && !invert) ||\n\t\t\t\t\t (tnode.getSymbol().getType() != tokenType && invert) )\n\t\t\t\t{\n\t\t\t\t\tnodes.add(tnode);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nodes;\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathWildcardAnywhereElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\n\npublic class XPathWildcardAnywhereElement extends XPathElement {\n\tpublic XPathWildcardAnywhereElement() {\n\t\tsuper(XPath.WILDCARD);\n\t}\n\n\t@Override\n\tpublic Collection<ParseTree> evaluate(ParseTree t) {\n\t\tif ( invert ) return new ArrayList<ParseTree>(); // !* is weird but valid (empty)\n\t\treturn Trees.getDescendants(t);\n\t}\n}\n"
  },
  {
    "path": "runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathWildcardElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime.tree.xpath;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.Tree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\npublic class XPathWildcardElement extends XPathElement {\n\tpublic XPathWildcardElement() {\n\t\tsuper(XPath.WILDCARD);\n\t}\n\n\t@Override\n\tpublic Collection<ParseTree> evaluate(final ParseTree t) {\n\t\tif ( invert ) return new ArrayList<ParseTree>(); // !* is weird but valid (empty)\n\t\tList<ParseTree> kids = new ArrayList<ParseTree>();\n\t\tfor (Tree c : Trees.getChildren(t)) {\n\t\t\tkids.add((ParseTree)c);\n\t\t}\n\t\treturn kids;\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/.babelrc",
    "content": "{\n  \"presets\": [\"@babel/preset-env\"],\n  \"targets\": \"defaults\"\n}\n"
  },
  {
    "path": "runtime/JavaScript/.c8rc.json",
    "content": "{\n    \"all\": true,\n    \"include\": [\n        \"src/antlr4/**/*.js\"\n    ],\n    \"reporter\": [\n        \"text\",\n        \"lcov\"\n    ]\n}\n"
  },
  {
    "path": "runtime/JavaScript/.eslintignore",
    "content": ""
  },
  {
    "path": "runtime/JavaScript/.eslintrc.yml",
    "content": "env:\n  browser: true\n  node: true\n  es2016: true\n  amd: true\n  jasmine: true\nextends:\n  - eslint:recommended\nglobals:\n  Atomics: readonly\n  SharedArrayBuffer: readonly\n  Set: readonly\nparser: \"@babel/eslint-parser\"\nparserOptions:\n  sourceType: module\n  project: ['./tsconfig.json']\n  ecmaVersion: 2022\nrules:\n  no-unused-vars: [\"error\", { vars: \"all\", args: \"none\" }]\n  no-prototype-builtins: [\"off\"]\n  no-fallthrough: [\"error\", { \"commentPattern\": \"no-break\" }]\n"
  },
  {
    "path": "runtime/JavaScript/.gitignore",
    "content": "/dist/\n/node_modules\n"
  },
  {
    "path": "runtime/JavaScript/README.md",
    "content": "# JavaScript target for ANTLR 4\n\n[![npm version](https://img.shields.io/npm/v/antlr4)](https://www.npmjs.com/package/antlr4)\n[![Badge showing the supported LTS versions of Node.JS in the latest NPM release](https://img.shields.io/node/v-lts/antlr4)](https://www.npmjs.com/package/antlr4)\n[![npm type definitions](https://img.shields.io/npm/types/antlr4)](https://www.npmjs.com/package/antlr4)\n\nJavaScript runtime libraries for ANTLR 4\n\nThis runtime is available through npm. The package name is 'antlr4'.\n\nThis runtime has been tested in Node.js, Safari, Firefox, Chrome and IE.\n\nSee www.antlr.org for more information on ANTLR\n\nSee [Javascript Target](https://github.com/antlr/antlr4/blob/master/doc/javascript-target.md)\nfor more information on using ANTLR in JavaScript\n\nThis runtime requires node version >= 16.\n\nANTLR 4 runtime is available in 10 target languages, and favors consistency of versioning across targets.\nAs such it cannot follow recommended NPM semantic versioning.\nIf you install a specific version of antlr4, we strongly recommend you remove the corresponding ^ in your package.json.\n\n \n\n\n\n\n\n"
  },
  {
    "path": "runtime/JavaScript/package.json",
    "content": "{\n  \"name\": \"antlr4\",\n  \"version\": \"4.13.2\",\n  \"type\": \"module\",\n  \"description\": \"JavaScript runtime for ANTLR4\",\n  \"browser\": \"dist/antlr4.web.mjs\",\n  \"main\": \"dist/antlr4.node.cjs\",\n  \"module\": \"dist/antlr4.node.mjs\",\n  \"types\": \"src/antlr4/index.d.cts\",\n  \"repository\": \"antlr/antlr4.git\",\n  \"keywords\": [\n    \"lexer\",\n    \"parser\",\n    \"antlr\",\n    \"antlr4\",\n    \"grammar\"\n  ],\n  \"files\": [\n    \"dist\",\n    \"src/**/*.d.cts\",\n    \"src/**/*.d.ts\"\n  ],\n  \"license\": \"BSD-3-Clause\",\n  \"bugs\": {\n    \"url\": \"https://github.com/antlr/antlr4/issues\"\n  },\n  \"homepage\": \"https://github.com/antlr/antlr4\",\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.19.1\",\n    \"@babel/eslint-parser\": \"^7.19.1\",\n    \"@babel/preset-env\": \"^7.19.4\",\n    \"@types/node\": \"^18.7.23\",\n    \"babel-loader\": \"^8.2.5\",\n    \"c8\": \"^7.12.0\",\n    \"compression-webpack-plugin\": \"^10.0.0\",\n    \"eslint\": \"^8.23.1\",\n    \"eslint-webpack-plugin\": \"^3.2.0\",\n    \"glob-parent\": \"^6.0.2\",\n    \"jasmine\": \"^4.0.2\",\n    \"jasmine-spec-reporter\": \"^7.0.0\",\n    \"minimist\": \"^1.2.6\",\n    \"source-map-support\": \"^0.5.21\",\n    \"terser-webpack-plugin\": \"^5.3.6\",\n    \"typescript\": \"^4.8.3\",\n    \"webpack\": \"^5.76.0\",\n    \"webpack-cli\": \"^4.10.0\"\n  },\n  \"scripts\": {\n    \"build\": \"webpack\",\n    \"test\": \"jasmine && npm run test:builds\",\n    \"test:builds\": \"bash test-builds.sh\",\n    \"coverage\": \"c8 jasmine\",\n    \"lint\": \"eslint src/antlr4/\"\n  },\n  \"engines\": {\n    \"node\": \">=16\"\n  },\n  \"exports\": {\n    \".\": {\n      \"types\": \"./src/antlr4/index.d.cts\",\n      \"node\": {\n        \"import\": \"./dist/antlr4.node.mjs\",\n        \"require\": \"./dist/antlr4.node.cjs\",\n        \"default\": \"./dist/antlr4.node.mjs\"\n      },\n      \"browser\": {\n        \"import\": \"./dist/antlr4.web.mjs\",\n        \"require\": \"./dist/antlr4.web.cjs\",\n        \"default\": \"./dist/antlr4.web.mjs\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "runtime/JavaScript/spec/BitSetSpec.js",
    "content": "import BitSet from \"../src/antlr4/misc/BitSet.js\";\n\ndescribe('test BitSet', () => {\n\n    it(\"is empty\", () => {\n        const bs = new BitSet();\n        expect(bs.length).toEqual(0);\n    })\n\n    it(\"sets 1 value\", () => {\n        const bs = new BitSet();\n        bs.set(67);\n        expect(bs.length).toEqual(1);\n        expect(bs.get(67)).toBeTrue();\n    })\n\n    it(\"clears 1 value\", () => {\n        const bs = new BitSet();\n        bs.set(67);\n        bs.clear(67)\n        expect(bs.length).toEqual(0);\n        expect(bs.get(67)).toBeFalse();\n    })\n\n    it(\"sets 2 consecutive values\", () => {\n        const bs = new BitSet();\n        bs.set(67);\n        bs.set(68);\n        expect(bs.length).toEqual(2);\n        expect(bs.get(67)).toBeTrue();\n        expect(bs.get(68)).toBeTrue();\n    })\n\n    it(\"sets 2 close values\", () => {\n        const bs = new BitSet();\n        bs.set(67);\n        bs.set(70);\n        expect(bs.length).toEqual(2);\n        expect(bs.get(67)).toBeTrue();\n        expect(bs.get(70)).toBeTrue();\n    })\n\n    it(\"sets 2 distant values\", () => {\n        const bs = new BitSet();\n        bs.set(67);\n        bs.set(241);\n        expect(bs.length).toEqual(2);\n        expect(bs.get(67)).toBeTrue();\n        expect(bs.get(241)).toBeTrue();\n    })\n\n    it(\"combines 2 identical sets\", () => {\n        const bs1 = new BitSet();\n        bs1.set(67);\n        const bs2 = new BitSet();\n        bs2.set(67);\n        bs1.or(bs2);\n        expect(bs1.length).toEqual(1);\n        expect(bs1.get(67)).toBeTrue();\n    })\n\n    it(\"combines 2 distinct sets\", () => {\n        const bs1 = new BitSet();\n        bs1.set(67);\n        const bs2 = new BitSet();\n        bs2.set(69);\n        bs1.or(bs2);\n        expect(bs1.length).toEqual(2);\n        expect(bs1.get(67)).toBeTrue();\n        expect(bs1.get(69)).toBeTrue();\n    })\n\n    it(\"combines 2 overlapping sets\", () => {\n        const bs1 = new BitSet();\n        bs1.set(67);\n        bs1.set(69);\n        const bs2 = new BitSet();\n        bs2.set(69);\n        bs2.set(71);\n        bs1.or(bs2);\n        expect(bs1.length).toEqual(3);\n        expect(bs1.get(67)).toBeTrue();\n        expect(bs1.get(69)).toBeTrue();\n        expect(bs1.get(71)).toBeTrue();\n    })\n\n    it(\"returns values\", () => {\n        const bs = new BitSet();\n        bs.set(67);\n        bs.set(69);\n        const values = bs.values();\n        expect(values).toEqual([67, 69]);\n    })\n\n    it(\"counts bits\", () => {\n        for(let i= 0; i <= 0xFF; i++) {\n            // count bits the slow but easy to understand way (Kernighan method)\n            let count1 = 0;\n            let value = i;\n            while(value) {\n                if(value & 1)\n                    count1++;\n                value >>= 1;\n            }\n            // count bits the fast way\n            const count2 = BitSet._bitCount(i);\n            expect(count2).toEqual(count1);\n        }\n    })\n})\n"
  },
  {
    "path": "runtime/JavaScript/spec/HashMapSpec.js",
    "content": "import HashMap from \"../src/antlr4/misc/HashMap.js\";\nimport HashCode from \"../src/antlr4/misc/HashCode.js\";\n\nclass Thing {\n\n    value1 = Math.random();\n    value2 = Math.random();\n\n    hashCode() {\n        return HashCode.hashStuff(this.value1);\n    }\n\n    equals(other) {\n        return other instanceof Thing\n            && other.value1 === this.value1\n            && other.value2 === this.value2;\n    }\n}\n\ndescribe('test HashMap', () => {\n\n    it(\"sets a thing\", () => {\n        const t1 = new Thing();\n        const map = new HashMap();\n        map.set(\"abc\", t1);\n        expect(map.containsKey(\"abc\")).toBeTrue();\n        expect(map.containsKey(\"def\")).toBeFalse();\n        expect(map.length).toEqual(1);\n    })\n\n    it(\"gets a thing\", () => {\n        const t1 = new Thing();\n        const map = new HashMap();\n        map.set(\"abc\", t1);\n        const t2 = map.get(\"abc\");\n        expect(t2).toEqual(t1);\n    })\n\n    it(\"replaces a thing\", () => {\n        const t1 = new Thing();\n        const t2 = new Thing();\n        const map = new HashMap();\n        map.set(\"abc\", t1);\n        map.set(\"abc\", t2);\n        const t3 = map.get(\"abc\");\n        expect(t3).toEqual(t2);\n    })\n\n    it(\"returns correct length\", () => {\n        const t1 = new Thing();\n        const t2 = new Thing();\n        const map = new HashMap();\n        expect(map.length).toEqual(0);\n        map.set(\"abc\", t1);\n        expect(map.length).toEqual(1);\n        map.set(\"def\", t2);\n        expect(map.length).toEqual(2);\n    })\n\n});\n"
  },
  {
    "path": "runtime/JavaScript/spec/HashSetSpec.js",
    "content": "import HashSet from \"../src/antlr4/misc/HashSet.js\";\nimport HashCode from \"../src/antlr4/misc/HashCode.js\";\n\nclass Thing {\n\n    value1 = Math.random();\n    value2 = Math.random();\n\n    hashCode() {\n        return HashCode.hashStuff(this.value1);\n    }\n\n    equals(other) {\n        return other instanceof Thing\n            && other.value1 === this.value1\n            && other.value2 === this.value2;\n    }\n}\ndescribe('test HashSet', () => {\n\n    it(\"adds a thing\", () => {\n        const t1 = new Thing();\n        const t2 = new Thing();\n        const set = new HashSet();\n        set.add(t1);\n        expect(set.has(t1)).toBeTrue();\n        expect(set.has(t2)).toBeFalse();\n        expect(set.length).toEqual(1);\n    })\n\n    it(\"adds a thing once only\", () => {\n        const t1 = new Thing();\n        const set = new HashSet();\n        set.add(t1);\n        set.add(t1);\n        expect(set.has(t1)).toBeTrue();\n        expect(set.length).toEqual(1);\n    })\n\n    it(\"adds 2 things with same hash code\", () => {\n        const t1 = new Thing();\n        const t2 = new Thing();\n        t2.value1 = t1.value1;\n        const set = new HashSet();\n        set.add(t1);\n        set.add(t2);\n        expect(set.has(t1)).toBeTrue();\n        expect(set.has(t2)).toBeTrue();\n        expect(set.length).toEqual(2);\n    })\n\n})\n"
  },
  {
    "path": "runtime/JavaScript/spec/IntervalSetSpec.js",
    "content": "import IntervalSet from \"../src/antlr4/misc/IntervalSet.js\";\n\ndescribe('test IntervalSet', () => {\n  it(\"computes interval set length\", () => {\n      const s1 = new IntervalSet();\n      s1.addOne(20);\n      s1.addOne(154);\n      s1.addRange(169, 171);\n      expect(s1.length).toEqual(5);\n  });\n\n  it(\"merges simple interval sets\", () => {\n      const s1 = new IntervalSet();\n      s1.addOne(10);\n      expect(s1.toString()).toEqual(\"10\");\n      const s2 = new IntervalSet();\n      s2.addOne(12);\n      expect(s2.toString()).toEqual(\"12\");\n      const merged = new IntervalSet();\n      merged.addSet(s1);\n      expect(merged.toString()).toEqual(\"10\");\n      merged.addSet(s2);\n      expect(merged.toString()).toEqual(\"{10, 12}\");\n      let s3 = new IntervalSet();\n      s3.addOne(10);\n      merged.addSet(s3);\n      expect(merged.toString()).toEqual(\"{10, 12}\");\n      s3 = new IntervalSet();\n      s3.addOne(11);\n      merged.addSet(s3);\n      expect(merged.toString()).toEqual(\"10..12\");\n      s3 = new IntervalSet();\n      s3.addOne(12);\n      merged.addSet(s3);\n      expect(merged.toString()).toEqual(\"10..12\");\n\n  });\n\n  it(\"merges complex interval sets\", () => {\n      const s1 = new IntervalSet();\n      s1.addOne(20);\n      s1.addOne(141);\n      s1.addOne(144);\n      s1.addOne(154);\n      s1.addRange(169, 171);\n      s1.addOne(173);\n      expect(s1.toString()).toEqual(\"{20, 141, 144, 154, 169..171, 173}\");\n      const s2 = new IntervalSet();\n      s2.addRange(9, 14);\n      s2.addOne(53);\n      s2.addRange(55, 63);\n      s2.addRange(65, 72);\n      s2.addRange(74, 117);\n      s2.addRange(119, 152);\n      s2.addRange(154, 164);\n      expect(s2.toString()).toEqual(\"{9..14, 53, 55..63, 65..72, 74..117, 119..152, 154..164}\");\n      s1.addSet(s2);\n      expect(s1.toString()).toEqual(\"{9..14, 20, 53, 55..63, 65..72, 74..117, 119..152, 154..164, 169..171, 173}\");\n  });\n});\n"
  },
  {
    "path": "runtime/JavaScript/spec/helpers/Reporter.js",
    "content": "import { SpecReporter } from 'jasmine-spec-reporter';\n\njasmine.getEnv().clearReporters();\njasmine.getEnv().addReporter(\n  new SpecReporter({\n    spec: {\n      displayPending: true,\n    },\n  })\n);\n"
  },
  {
    "path": "runtime/JavaScript/spec/imports/NodeCommonJSImportSpec.cjs",
    "content": "\"use strict\";\n\nconst antlr4 = require(\"antlr4\");\ndescribe('Antlr4 Node CommonJs', () => {\n    it('should use the CommonJS module on Node.js', () => {\n        expect(antlr4).toBeDefined();\n    });\n});\n"
  },
  {
    "path": "runtime/JavaScript/spec/imports/NodeEsmImportSpec.mjs",
    "content": "import * as antlr4 from 'antlr4'\n\ndescribe('Antlr4 Node Esm', () => {\n    it('should use the Esm module on Node.js', () => {\n        expect(antlr4).toBeDefined();\n    });\n});\nexport {};\n"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-cjs-ts/.gitignore",
    "content": "/node_modules\n\npackage-lock.json"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-cjs-ts/index.ts",
    "content": "const { CharStream } = require(\"antlr4\");\n\nconst cs = new CharStream(\"OK\");\n\nconsole.log(cs.toString());"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-cjs-ts/package.json",
    "content": "{\n  \"name\": \"test-import-node-cjs-ts\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"type\": \"commonjs\",\n  \"scripts\": {\n    \"test\": \"bash test.sh\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"antlr4\": \"file:../../../..\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.4.3\"\n  }\n}\n"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-cjs-ts/test.sh",
    "content": "#!/usr/bin/env bash\n\ntsconfigFiles=(\n  \"tsconfig.node.commonjs.json\"\n)\n\nfailure=0\n\nfor tsconfig in \"${tsconfigFiles[@]}\"; do\n  echo -n \"$tsconfig \"\n\n  ./node_modules/.bin/tsc -p $tsconfig || { failure=1 ; echo \"FAIL tsc: $tsconfig\"; }\n  result=$(node ./tsOutput/index.js)\n  [[ $result == \"OK\" ]] && echo \"OK\"\n  [[ $result != \"OK\" ]] && { failure=1 ; echo \"FAIL loading runtime with config: $tsconfig\"; }\n  rm -rf ./tsOutput\ndone\n\nexit $failure"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-cjs-ts/tsconfig.node.commonjs.json",
    "content": "{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"skipLibCheck\": true,\n    \"outDir\": \"./tsOutput\",\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\"\n  },\n  \"include\": [\"index.ts\"],\n}\n"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-esm-ts/.gitignore",
    "content": "/node_modules\n\npackage-lock.json"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-esm-ts/index.ts",
    "content": "import { CharStream } from \"antlr4\";\n\nconst cs = new CharStream(\"OK\");\n\nconsole.log(cs.toString());"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-esm-ts/package.json",
    "content": "{\n  \"name\": \"test-import-node-esm-ts\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"test\": \"bash test.sh\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"antlr4\": \"file:../../../..\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.4.3\"\n  }\n}\n"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-esm-ts/test.sh",
    "content": "#!/usr/bin/env bash\n\ntsconfigFiles=(\n  \"tsconfig.node16.json\"\n  \"tsconfig.bundler.es2022.json\"\n)\n\nfailure=0\n\nfor tsconfig in \"${tsconfigFiles[@]}\"; do\n  echo -n \"$tsconfig \"\n\n  ./node_modules/.bin/tsc -p $tsconfig || { failure=1 ; echo \"FAIL tsc: $tsconfig\"; }\n  result=$(node ./tsOutput/index.js)\n  [[ $result == \"OK\" ]] && echo \"OK\"\n  [[ $result != \"OK\" ]] && { failure=1 ; echo \"FAIL loading runtime with config: $tsconfig\"; }\n  rm -rf ./tsOutput\ndone\n\nexit $failure"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-esm-ts/tsconfig.bundler.es2022.json",
    "content": "{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"skipLibCheck\": true,\n    \"outDir\": \"./tsOutput\",\n    \"module\": \"es2022\",\n    \"moduleResolution\": \"bundler\"\n  },\n  \"include\": [\"index.ts\"],\n}\n"
  },
  {
    "path": "runtime/JavaScript/spec/imports/builds/node-esm-ts/tsconfig.node16.json",
    "content": "{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"skipLibCheck\": true,\n    \"outDir\": \"./tsOutput\",\n    \"module\": \"node16\",\n    \"moduleResolution\": \"node16\"\n  },\n  \"include\": [\"index.ts\"],\n}\n"
  },
  {
    "path": "runtime/JavaScript/spec/rewriter/Makefile",
    "content": "ANTLR_VERSION = 4.13.2\nANTLR_JAR = .antlr/antlr-$(ANTLR_VERSION)-complete.jar\n\n.antlr:\n\tmkdir .antlr\n\n$(ANTLR_JAR): .antlr\n\tcurl https://www.antlr.org/download/antlr-$(ANTLR_VERSION)-complete.jar -o $(ANTLR_JAR)\n\nabc: abc.g4 $(ANTLR_JAR)\n\tjava -jar $(ANTLR_JAR) -Dlanguage=JavaScript -no-listener abc.g4 -o generatedCode/\n\tsed -i.bak \"s/import antlr4 from 'antlr4'/import antlr4 from '..\\/..\\/..\\/src\\/antlr4\\/index.node.js'/\" generatedCode/abc.js\n\ncalc: calc.g4 $(ANTLR_JAR)\n\tjava -jar $(ANTLR_JAR) -Dlanguage=JavaScript -no-listener calc.g4 -o generatedCode/\n\tsed -i.bak \"s/import antlr4 from 'antlr4'/import antlr4 from '..\\/..\\/..\\/src\\/antlr4\\/index.node.js'/\" generatedCode/calc.js\n"
  },
  {
    "path": "runtime/JavaScript/spec/rewriter/TokenStreamRewriterSpec.js",
    "content": "import antlr4 from \"../../src/antlr4/index.node.js\";\nimport abc from \"./generatedCode/abc.js\";\nimport calc from \"./generatedCode/calc.js\";\n\n/**\n * \n * @param {antlr4.Lexer} lexerClass \n * @param {string} input \n */\nfunction getRewriter(lexerClass, input) {\n    const chars = antlr4.CharStreams.fromString(input);\n    const lexer = new lexerClass(chars);\n    const tokens = new antlr4.CommonTokenStream(lexer);\n    tokens.fill();\n    return new antlr4.TokenStreamRewriter(tokens);\n}\n\ndescribe(\"TokenStreamRewriter\", () => {\n    it(\"inserts '0' before index 0\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(0, \"0\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"0abc\");\n    });\n    \n    it(\"inserts 'x' after last index\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertAfter(2, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abcx\");\n    });\n\n    it(\"inserts 'x' after the 'b' token\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n        const bToken = rewriter.tokens.get(1);\n    \n        // Act\n        rewriter.insertAfter(bToken, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abxc\");\n    });\n\n    it(\"inserts 'x' at the end if the index is out of bounds\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertAfter(100, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abcx\");\n    });\n\n    it(\"inserts 'x' before the 'b' token\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n        const bToken = rewriter.tokens.get(1);\n    \n        // Act\n        rewriter.insertBefore(bToken, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"axbc\");\n    });\n    \n    it(\"inserts 'x' before and after middle index\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(1, \"x\");\n        rewriter.insertAfter(1, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"axbxc\");\n    });\n    \n    it(\"replaces the first token with an 'x'\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replaceSingle(0, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"xbc\");\n    });\n    \n    it(\"replaces the last token with an 'x'\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replaceSingle(2, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abx\");\n    });\n    \n    it(\"replaces the middle token with an 'x'\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replaceSingle(1, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"axc\");\n    });\n    \n    it(\"calls getText() with different start/stop arguments (1 of 2)\", () => {\n        // Arrange\n        const rewriter = getRewriter(calc, \"x = 3 * 0;\");\n    \n        // Act\n        rewriter.replace(4, 8, \"0\"); // replace 3 * 0 with 0\n    \n        // Assert\n        expect(rewriter.getTokenStream().getText()).toEqual(\"x = 3 * 0;\");\n        expect(rewriter.getText()).toEqual(\"x = 0;\");\n        expect(rewriter.getText(new antlr4.Interval(0, 9))).toEqual(\"x = 0;\");\n        expect(rewriter.getText(new antlr4.Interval(4, 8))).toEqual(\"0\");\n    });\n    \n    it(\"calls getText() with different start/stop arguments (2 of 2)\", () => {\n        // Arrange\n        const rewriter = getRewriter(calc, \"x = 3 * 0 + 2 * 0;\");\n    \n        // Act/Assert\n        expect(rewriter.getTokenStream().getText()).toEqual(\"x = 3 * 0 + 2 * 0;\");\n    \n        rewriter.replace(4, 8, \"0\"); // replace 3 * 0 with 0\n    \n        expect(rewriter.getText()).toEqual(\"x = 0 + 2 * 0;\");\n        expect(rewriter.getText(new antlr4.Interval(0, 17))).toEqual(\"x = 0 + 2 * 0;\");\n        expect(rewriter.getText(new antlr4.Interval(4, 8))).toEqual(\"0\");\n        expect(rewriter.getText(new antlr4.Interval(0, 8))).toEqual(\"x = 0\");\n        expect(rewriter.getText(new antlr4.Interval(12, 16))).toEqual(\"2 * 0\");\n    \n        rewriter.insertAfter(17, \"// comment\");\n    \n        expect(rewriter.getText(new antlr4.Interval(12, 18))).toEqual(\"2 * 0;// comment\");\n        expect(rewriter.getText(new antlr4.Interval(0, 8))).toEqual(\"x = 0\");\n    });\n    \n    it(\"replaces the middle index, twice\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replaceSingle(1, \"x\");\n        rewriter.replaceSingle(1, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"ayc\");\n    });\n    \n    it(\"inserts '_' at the beginning and then replaces the middle token, twice\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(0, \"_\");\n        rewriter.replaceSingle(1, \"x\");\n        rewriter.replaceSingle(1, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"_ayc\");\n    });\n    \n    it(\"replaces, then deletes the middle index\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replaceSingle(1, \"x\");\n        rewriter.delete(1);\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"ac\");\n    });\n    \n    it(\"throws an error when inserting into a replaced segment\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replace(0, 2, \"x\");\n        rewriter.insertBefore(1, \"0\");\n    \n        // Assert\n        expect(() => rewriter.getText()).toThrowError(\n            \"insert op <InsertBeforeOp@[@1,1:1='b',<2>,1:1]:\\\"0\\\"> within boundaries of previous <ReplaceOp@[@0,0:0='a',<1>,1:0]..[@2,2:2='c',<3>,1:2]:\\\"x\\\">\"\n        );\n    });\n\n    it(\"throws an error when inserting into a deleted segment\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.delete(0, 2);\n        rewriter.insertBefore(1, \"0\");\n    \n        // Assert\n        expect(() => rewriter.getText()).toThrowError(\n            \"insert op <InsertBeforeOp@[@1,1:1='b',<2>,1:1]:\\\"0\\\"> within boundaries of previous <DeleteOp@[@0,0:0='a',<1>,1:0]..[@2,2:2='c',<3>,1:2]>\"\n        );\n    });\n    \n    it(\"inserts '0' before the first token and then replaces it with an 'x'\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(0, \"0\");\n        rewriter.replaceSingle(0, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"0xbc\");\n    });\n    \n    it(\"inserts texts in reverse order when multiple inserts occur at the same index\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(1, \"x\");\n        rewriter.insertBefore(1, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"ayxbc\");\n    });\n    \n    it(\"inserts 'y' and 'x' before the first index and then replaces it with 'z'\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(0, \"x\");\n        rewriter.insertBefore(0, \"y\");\n        rewriter.replaceSingle(0, \"z\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"yxzbc\");\n    });\n    \n    it(\"replaces the last index with an 'x' and then inserts 'y' before it\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replaceSingle(2, \"x\");\n        rewriter.insertBefore(2, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abyx\");\n    });\n    \n    it(\"replaces thte last index with an 'x' and then inserts 'y' after it\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replaceSingle(2, \"x\");\n        rewriter.insertAfter(2, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abxy\");\n    });\n    \n    it(\"replaces a range with an 'x' and then inserts 'y' before the left edge of the range\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcccba\");\n    \n        // Act\n        rewriter.replace(2, 4, \"x\");\n        rewriter.insertBefore(2, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abyxba\");\n    });\n    \n    it(\"throws an error if an attempt is made to insert a token before the right edge of a replaced range\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcccba\");\n    \n        // Act\n        rewriter.replace(2, 4, \"x\");\n        rewriter.insertBefore(4, \"y\");\n    \n        // Assert\n        expect(() => rewriter.getText()).toThrowError(\n            \"insert op <InsertBeforeOp@[@4,4:4='c',<3>,1:4]:\\\"y\\\"> within boundaries of previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"x\\\">\"\n        );\n    });\n    \n    it(\"replaces a range with an 'x' then inserts 'y' after the right edge of the range\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcccba\");\n    \n        // Act\n        rewriter.replace(2, 4, \"x\");\n        rewriter.insertAfter(4, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abxyba\");\n    });\n\n    it(\"replaces a token range\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcba\");\n        const bToken = rewriter.tokens.get(1);\n        const dToken = rewriter.tokens.get(3);\n        \n        // Act\n        rewriter.replace(bToken, dToken, \"x\");\n\n        // Assert\n        expect(rewriter.getText()).toEqual(\"axa\");\n    });\n\n    it(\"throws an error when replace is given an invalid range\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n        const badRanges = [\n            [1, 0],   // from > to\n            [-1, 1],  // from is negative\n            [1, -1],  // to is negative\n            [-2, -1], // both are negative\n            [1, 4]    // to is out of bounds\n        ];\n        \n        // Act/Assert\n        for (const [from, to] of badRanges) {\n            expect(() => rewriter.replace(from, to, \"x\")).toThrow();\n        }\n    });\n    \n    it(\"replaces all tokens with an 'x'\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcccba\");\n    \n        // Act\n        rewriter.replace(0, 6, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"x\");\n    });\n    \n    it(\"replaces the middle 'ccc' with 'xyz'\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcccba\");\n    \n        // Act\n        rewriter.replace(2, 4, \"xyz\");\n    \n        // Assert\n        expect(rewriter.getText(new antlr4.Interval(0, 6))).toEqual(\"abxyzba\");\n    });\n    \n    it(\"throws an error if second replace operation overlaps the first one on the right\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcccba\");\n    \n        // Act\n        rewriter.replace(2, 4, \"xyz\");\n        rewriter.replace(3, 5, \"foo\");\n    \n        // Assert\n        expect(() => rewriter.getText()).toThrowError(\n            \"replace op boundaries of <ReplaceOp@[@3,3:3='c',<3>,1:3]..[@5,5:5='b',<2>,1:5]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"xyz\\\">\"\n        );\n    });\n    \n    it(\"throws an error if second replace operation overlaps the first one on the left\", () => {\n        // Arrange\n        const chars = antlr4.CharStreams.fromString(\"abcccba\");\n        const lexer = new abc(chars);\n        const tokens = new antlr4.CommonTokenStream(lexer);\n        tokens.fill();\n        const rewriter = new antlr4.TokenStreamRewriter(tokens);\n    \n        // Act\n        rewriter.replace(2, 4, \"xyz\");\n        rewriter.replace(1, 3, \"foo\");\n    \n        // Assert\n        expect(() => rewriter.getText()).toThrowError(\n            \"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@3,3:3='c',<3>,1:3]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"xyz\\\">\"\n        );\n    });\n    \n    it(\"ignores first replace operation when the second one overlaps it on both sides (superset)\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcba\");\n    \n        // Act\n        rewriter.replace(2, 2, \"xyz\");\n        rewriter.replace(0, 3, \"foo\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"fooa\");\n    });\n    \n    it(\"inserts 'x' and 'y' before the first token\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(0, \"x\");\n        rewriter.insertBefore(0, \"y\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"yxabc\");\n    });\n    \n    it(\"performs 3 inserts at 2 locations\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(1, \"x\");\n        rewriter.insertBefore(0, \"y\");\n        rewriter.insertBefore(1, \"z\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"yazxbc\");\n    });\n    \n    it(\"replaces 'abc' with 'foo' and then inserts 'z' before it\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.replace(0, 2, \"foo\");\n        rewriter.insertBefore(0, \"z\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"zfoo\");\n    });\n    \n    it(\"deletes 'abc' and then inserts 'z' before it\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.delete(0, 2);\n        rewriter.insertBefore(0, \"z\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"z\");\n    });\n    \n    \n    it(\"makes 3 inserts at 3 locations\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(1, \"x\");\n        rewriter.insertBefore(2, \"y\");\n        rewriter.insertBefore(0, \"z\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"zaxbyc\");\n    });\n    \n    it(\"throws an error if second replace operation affects a subset of a previous one\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcc\");\n    \n        // Act\n        rewriter.replace(0, 3, \"bar\");\n        rewriter.replace(1, 2, \"foo\");\n    \n        // Assert\n        expect(() => rewriter.getText()).toThrowError(\n            \"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@2,2:2='c',<3>,1:2]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@0,0:0='a',<1>,1:0]..[@3,3:3='c',<3>,1:3]:\\\"bar\\\">\"\n        );\n    });\n    \n    it(\"ignores the first replace operation when the secone one extends it to the left\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcc\");\n    \n        // Act\n        rewriter.replace(1, 2, \"foo\");\n        rewriter.replace(0, 2, \"bar\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"barc\");\n    });\n    \n    it(\"ignores the first replace operation when the secone one extends it to the right\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcc\");\n    \n        // Act\n        rewriter.replace(1, 2, \"foo\");\n        rewriter.replace(1, 3, \"bar\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"abar\");\n    });\n    \n    it(\"only applies one replace operation when identical ones are given\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcc\");\n    \n        // Act\n        rewriter.replace(1, 2, \"foo\");\n        rewriter.replace(1, 2, \"foo\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"afooc\");\n    });\n    \n    it(\"drops the insert operation when it is covered by a subsequent replace operation\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(2, \"foo\");\n        rewriter.replace(1, 2, \"foo\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"afoo\");\n    });\n    \n    it(\"performs the insert operation when disjoint from the replace operation (1 of 2)\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcc\");\n    \n        // Act\n        rewriter.insertBefore(1, \"x\");\n        rewriter.replace(2, 3, \"foo\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"axbfoo\");\n    });\n    \n    it(\"performs the insert operation when disjoint from the replace operation (2 of 2)\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcc\");\n    \n        // Act\n        rewriter.replace(2, 3, \"foo\");\n        rewriter.insertBefore(1, \"x\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"axbfoo\");\n    });\n    \n    it(\"inserts 'y' before the last token, then deletes it\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(2, \"y\");\n        rewriter.delete(2);\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"aby\");\n    });\n\n    it(\"deletes the 'a' token\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n        const aToken = rewriter.tokens.get(0);\n    \n        // Act\n        rewriter.delete(aToken);\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"bc\");\n    });\n    \n    // Test for https://github.com/antlr/antlr4/issues/550\n    it(\"distinguishes between insertAfter and insertBefore to preserve order (1 of 2)\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"aa\");\n    \n        // Act\n        rewriter.insertBefore(0, \"<b>\");\n        rewriter.insertAfter(0, \"</b>\");\n        rewriter.insertBefore(1, \"<b>\");\n        rewriter.insertAfter(1, \"</b>\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"<b>a</b><b>a</b>\");\n    });\n    \n    it(\"distinguishes between insertAfter and insertBefore to preserve order (2 of 2)\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"aa\");\n    \n        // Act\n        rewriter.insertBefore(0, \"<p>\");\n        rewriter.insertBefore(0, \"<b>\");\n        rewriter.insertAfter(0, \"</p>\");\n        rewriter.insertAfter(0, \"</b>\");\n        rewriter.insertBefore(1, \"<b>\");\n        rewriter.insertAfter(1, \"</b>\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"<b><p>a</p></b><b>a</b>\");\n    });\n    \n    it(\"preserves the order of contiguous inserts\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"ab\");\n    \n        // Act\n        rewriter.insertBefore(0, \"<p>\");\n        rewriter.insertBefore(0, \"<b>\");\n        rewriter.insertBefore(0, \"<div>\");\n        rewriter.insertAfter(0, \"</p>\");\n        rewriter.insertAfter(0, \"</b>\");\n        rewriter.insertAfter(0, \"</div>\");\n        rewriter.insertBefore(1, \"!\");\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"<div><b><p>a</p></b></div>!b\");\n    });\n    \n    it(\"accepts different types as text\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(0, false);\n        rewriter.insertBefore(0, 0);\n        rewriter.insertBefore(0, {});\n        rewriter.insertBefore(0, []);\n        rewriter.insertBefore(0, \"\");\n        rewriter.insertBefore(0, null);\n    \n        // Assert\n        expect(rewriter.getText()).toEqual(\"[object Object]0falseabc\");\n    });\n\n    it(\"returns the original input if no rewrites have occurred\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        const result = rewriter.getText();\n    \n        // Assert\n        expect(result).toEqual(\"abc\");\n    });\n\n    it(\"segments operations by program name\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        rewriter.insertBefore(0, \"b\", \"P1\");\n        rewriter.insertAfter(0, \"c\", \"P2\");\n        rewriter.replaceSingle(2, \"b\", \"P2\");\n        \n        // Assert\n        expect(rewriter.getText(\"P1\")).toEqual(\"babc\");\n        expect(rewriter.getText(\"P2\")).toEqual(\"acbb\");\n    });\n\n    it(\"doesn't make a fuss if getText is supplied with an interval that exceeds the token range\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abc\");\n    \n        // Act\n        const unmodified = rewriter.getText(new antlr4.Interval(-1, 3));\n        rewriter.insertAfter(2, \"a\");\n        const modified = rewriter.getText(new antlr4.Interval(0, 200));\n        \n        // Assert\n        expect(unmodified).toEqual(\"abc\");\n        expect(modified).toEqual(\"abca\");\n    });\n\n    it(\"ignores inserts that occur within a removed range\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcba\");\n    \n        // Act\n        rewriter.insertAfter(2, \"c\");\n        rewriter.delete(2, 3);\n        \n        // Assert\n        expect(rewriter.getText()).toEqual(\"aba\");\n    });\n\n    it(\"handles overlapping delete ranges\", () => {\n        // Arrange\n        const rewriter = getRewriter(abc, \"abcba\");\n    \n        // Act\n        rewriter.delete(1, 3);\n        rewriter.delete(2, 4);\n        \n        // Assert\n        expect(rewriter.getText()).toEqual(\"a\");\n    });\n});\n"
  },
  {
    "path": "runtime/JavaScript/spec/rewriter/abc.g4",
    "content": "lexer grammar abc;\nA: 'a';\nB: 'b';\nC: 'c';"
  },
  {
    "path": "runtime/JavaScript/spec/rewriter/calc.g4",
    "content": "lexer grammar calc;\nID: 'a' ..'z'+;\nINT: '0' ..'9'+;\nSEMI: ';';\nPLUS: '+';\nMUL: '*';\nASSIGN: '=';\nWS: ' '+;\n"
  },
  {
    "path": "runtime/JavaScript/spec/rewriter/generatedCode/abc.js",
    "content": "// Generated from abc.g4 by ANTLR 4.12.0\n// jshint ignore: start\nimport antlr4 from '../../../src/antlr4/index.node.js';\n\n\nconst serializedATN = [4,0,3,13,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,1,0,1,0,1,1,\n1,1,1,2,1,2,0,0,3,1,1,3,2,5,3,1,0,0,12,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,\n0,1,7,1,0,0,0,3,9,1,0,0,0,5,11,1,0,0,0,7,8,5,97,0,0,8,2,1,0,0,0,9,10,5,98,\n0,0,10,4,1,0,0,0,11,12,5,99,0,0,12,6,1,0,0,0,1,0,0];\n\n\nconst atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);\n\nconst decisionsToDFA = atn.decisionToState.map( (ds, index) => new antlr4.dfa.DFA(ds, index) );\n\nexport default class abc extends antlr4.Lexer {\n\n    static grammarFileName = \"abc.g4\";\n    static channelNames = [ \"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\" ];\n\tstatic modeNames = [ \"DEFAULT_MODE\" ];\n\tstatic literalNames = [ null, \"'a'\", \"'b'\", \"'c'\" ];\n\tstatic symbolicNames = [ null, \"A\", \"B\", \"C\" ];\n\tstatic ruleNames = [ \"A\", \"B\", \"C\" ];\n\n    constructor(input) {\n        super(input)\n        this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.atn.PredictionContextCache());\n    }\n}\n\nabc.EOF = antlr4.Token.EOF;\nabc.A = 1;\nabc.B = 2;\nabc.C = 3;\n\n\n\n"
  },
  {
    "path": "runtime/JavaScript/spec/rewriter/generatedCode/calc.js",
    "content": "// Generated from calc.g4 by ANTLR 4.12.0\n// jshint ignore: start\nimport antlr4 from '../../../src/antlr4/index.node.js';\n\n\nconst serializedATN = [4,0,7,38,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,\n7,4,2,5,7,5,2,6,7,6,1,0,4,0,17,8,0,11,0,12,0,18,1,1,4,1,22,8,1,11,1,12,1,\n23,1,2,1,2,1,3,1,3,1,4,1,4,1,5,1,5,1,6,4,6,35,8,6,11,6,12,6,36,0,0,7,1,1,\n3,2,5,3,7,4,9,5,11,6,13,7,1,0,0,40,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,\n7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,1,16,1,0,0,0,3,21,1,0,0,\n0,5,25,1,0,0,0,7,27,1,0,0,0,9,29,1,0,0,0,11,31,1,0,0,0,13,34,1,0,0,0,15,\n17,2,97,122,0,16,15,1,0,0,0,17,18,1,0,0,0,18,16,1,0,0,0,18,19,1,0,0,0,19,\n2,1,0,0,0,20,22,2,48,57,0,21,20,1,0,0,0,22,23,1,0,0,0,23,21,1,0,0,0,23,24,\n1,0,0,0,24,4,1,0,0,0,25,26,5,59,0,0,26,6,1,0,0,0,27,28,5,43,0,0,28,8,1,0,\n0,0,29,30,5,42,0,0,30,10,1,0,0,0,31,32,5,61,0,0,32,12,1,0,0,0,33,35,5,32,\n0,0,34,33,1,0,0,0,35,36,1,0,0,0,36,34,1,0,0,0,36,37,1,0,0,0,37,14,1,0,0,\n0,4,0,18,23,36,0];\n\n\nconst atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);\n\nconst decisionsToDFA = atn.decisionToState.map( (ds, index) => new antlr4.dfa.DFA(ds, index) );\n\nexport default class calc extends antlr4.Lexer {\n\n    static grammarFileName = \"calc.g4\";\n    static channelNames = [ \"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\" ];\n\tstatic modeNames = [ \"DEFAULT_MODE\" ];\n\tstatic literalNames = [ null, null, null, \"';'\", \"'+'\", \"'*'\", \"'='\" ];\n\tstatic symbolicNames = [ null, \"ID\", \"INT\", \"SEMI\", \"PLUS\", \"MUL\", \"ASSIGN\", \n                          \"WS\" ];\n\tstatic ruleNames = [ \"ID\", \"INT\", \"SEMI\", \"PLUS\", \"MUL\", \"ASSIGN\", \"WS\" ];\n\n    constructor(input) {\n        super(input)\n        this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.atn.PredictionContextCache());\n    }\n}\n\ncalc.EOF = antlr4.Token.EOF;\ncalc.ID = 1;\ncalc.INT = 2;\ncalc.SEMI = 3;\ncalc.PLUS = 4;\ncalc.MUL = 5;\ncalc.ASSIGN = 6;\ncalc.WS = 7;\n\n\n\n"
  },
  {
    "path": "runtime/JavaScript/spec/support/jasmine.json",
    "content": "{\n  \"spec_dir\": \"spec\",\n  \"spec_files\": [\n    \"**/*Spec.[c|m]*js\",\n    \"**/*Spec.js\"\n  ],\n  \"helpers\": [\n    \"helpers/**/*.js\"\n  ],\n  \"env\": {\n    \"random\": false\n  }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/BufferedTokenStream.d.ts",
    "content": "import { TokenStream } from \"./TokenStream.js\";\nimport { Lexer } from \"./Lexer.js\";\n\nexport declare class BufferedTokenStream extends TokenStream {\n\n    tokenSource: Lexer;\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/BufferedTokenStream.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from './Token.js';\nimport Lexer from './Lexer.js';\nimport Interval from './misc/Interval.js';\nimport TokenStream from \"./TokenStream.js\";\n\n/**\n * This implementation of {@link TokenStream} loads tokens from a\n * {@link TokenSource} on-demand, and places the tokens in a buffer to provide\n * access to any previous token by index.\n *\n * <p>\n * This token stream ignores the value of {@link Token//getChannel}. If your\n * parser requires the token stream filter tokens to only those on a particular\n * channel, such as {@link Token//DEFAULT_CHANNEL} or\n * {@link Token//HIDDEN_CHANNEL}, use a filtering token stream such a\n * {@link CommonTokenStream}.</p>\n */\nexport default class BufferedTokenStream extends TokenStream {\n\tconstructor(tokenSource) {\n\n\t\tsuper();\n\t\t// The {@link TokenSource} from which tokens for this stream are fetched.\n\t\tthis.tokenSource = tokenSource;\n\t\t/**\n\t\t * A collection of all tokens fetched from the token source. The list is\n\t\t * considered a complete view of the input once {@link //fetchedEOF} is set\n\t\t * to {@code true}.\n\t\t */\n\t\tthis.tokens = [];\n\n\t\t/**\n\t\t * The index into {@link //tokens} of the current token (next token to\n\t\t * {@link //consume}). {@link //tokens}{@code [}{@link //p}{@code ]} should\n\t\t * be\n\t\t * {@link //LT LT(1)}.\n\t\t *\n\t\t * <p>This field is set to -1 when the stream is first constructed or when\n\t\t * {@link //setTokenSource} is called, indicating that the first token has\n\t\t * not yet been fetched from the token source. For additional information,\n\t\t * see the documentation of {@link IntStream} for a description of\n\t\t * Initializing Methods.</p>\n\t\t */\n\t\tthis.index = -1;\n\n\t\t/**\n\t\t * Indicates whether the {@link Token//EOF} token has been fetched from\n\t\t * {@link //tokenSource} and added to {@link //tokens}. This field improves\n\t\t * performance for the following cases:\n\t\t *\n\t\t * <ul>\n\t\t * <li>{@link //consume}: The lookahead check in {@link //consume} to\n\t\t * prevent\n\t\t * consuming the EOF symbol is optimized by checking the values of\n\t\t * {@link //fetchedEOF} and {@link //p} instead of calling {@link\n\t\t * //LA}.</li>\n\t\t * <li>{@link //fetch}: The check to prevent adding multiple EOF symbols\n\t\t * into\n\t\t * {@link //tokens} is trivial with this field.</li>\n\t\t * <ul>\n\t\t */\n\t\tthis.fetchedEOF = false;\n\t}\n\n\tmark() {\n\t\treturn 0;\n\t}\n\n\trelease(marker) {\n\t\t// no resources to release\n\t}\n\n\treset() {\n\t\tthis.seek(0);\n\t}\n\n\tseek(index) {\n\t\tthis.lazyInit();\n\t\tthis.index = this.adjustSeekIndex(index);\n\t}\n\n\tget size() {\n\t\treturn this.tokens.length;\n\t}\n\n\tget(index) {\n\t\tthis.lazyInit();\n\t\treturn this.tokens[index];\n\t}\n\n\tconsume() {\n\t\tlet skipEofCheck = false;\n\t\tif (this.index >= 0) {\n\t\t\tif (this.fetchedEOF) {\n\t\t\t\t// the last token in tokens is EOF. skip check if p indexes any\n\t\t\t\t// fetched token except the last.\n\t\t\t\tskipEofCheck = this.index < this.tokens.length - 1;\n\t\t\t} else {\n\t\t\t\t// no EOF token in tokens. skip check if p indexes a fetched token.\n\t\t\t\tskipEofCheck = this.index < this.tokens.length;\n\t\t\t}\n\t\t} else {\n\t\t\t// not yet initialized\n\t\t\tskipEofCheck = false;\n\t\t}\n\t\tif (!skipEofCheck && this.LA(1) === Token.EOF) {\n\t\t\tthrow \"cannot consume EOF\";\n\t\t}\n\t\tif (this.sync(this.index + 1)) {\n\t\t\tthis.index = this.adjustSeekIndex(this.index + 1);\n\t\t}\n\t}\n\n\t/**\n\t * Make sure index {@code i} in tokens has a token.\n\t *\n\t * @return {Boolean} {@code true} if a token is located at index {@code i}, otherwise\n\t * {@code false}.\n\t * @see //get(int i)\n\t */\n\tsync(i) {\n\t\tconst n = i - this.tokens.length + 1; // how many more elements we need?\n\t\tif (n > 0) {\n\t\t\tconst fetched = this.fetch(n);\n\t\t\treturn fetched >= n;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Add {@code n} elements to buffer.\n\t *\n\t * @return {Number} The actual number of elements added to the buffer.\n\t */\n\tfetch(n) {\n\t\tif (this.fetchedEOF) {\n\t\t\treturn 0;\n\t\t}\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst t = this.tokenSource.nextToken();\n\t\t\tt.tokenIndex = this.tokens.length;\n\t\t\tthis.tokens.push(t);\n\t\t\tif (t.type === Token.EOF) {\n\t\t\t\tthis.fetchedEOF = true;\n\t\t\t\treturn i + 1;\n\t\t\t}\n\t\t}\n\t\treturn n;\n\t}\n\n\t// Get all tokens from start..stop inclusively///\n\tgetTokens(start, stop, types) {\n\t\tif (types === undefined) {\n\t\t\ttypes = null;\n\t\t}\n\t\tif (start < 0 || stop < 0) {\n\t\t\treturn null;\n\t\t}\n\t\tthis.lazyInit();\n\t\tconst subset = [];\n\t\tif (stop >= this.tokens.length) {\n\t\t\tstop = this.tokens.length - 1;\n\t\t}\n\t\tfor (let i = start; i < stop; i++) {\n\t\t\tconst t = this.tokens[i];\n\t\t\tif (t.type === Token.EOF) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (types === null || types.contains(t.type)) {\n\t\t\t\tsubset.push(t);\n\t\t\t}\n\t\t}\n\t\treturn subset;\n\t}\n\n\tLA(i) {\n\t\treturn this.LT(i).type;\n\t}\n\n\tLB(k) {\n\t\tif (this.index - k < 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn this.tokens[this.index - k];\n\t}\n\n\tLT(k) {\n\t\tthis.lazyInit();\n\t\tif (k === 0) {\n\t\t\treturn null;\n\t\t}\n\t\tif (k < 0) {\n\t\t\treturn this.LB(-k);\n\t\t}\n\t\tconst i = this.index + k - 1;\n\t\tthis.sync(i);\n\t\tif (i >= this.tokens.length) { // return EOF token\n\t\t\t// EOF must be last token\n\t\t\treturn this.tokens[this.tokens.length - 1];\n\t\t}\n\t\treturn this.tokens[i];\n\t}\n\n\t/**\n\t * Allowed derived classes to modify the behavior of operations which change\n\t * the current stream position by adjusting the target token index of a seek\n\t * operation. The default implementation simply returns {@code i}. If an\n\t * exception is thrown in this method, the current stream index should not be\n\t * changed.\n\t *\n\t * <p>For example, {@link CommonTokenStream} overrides this method to ensure\n\t * that\n\t * the seek target is always an on-channel token.</p>\n\t *\n\t * @param {Number} i The target token index.\n\t * @return {Number} The adjusted target token index.\n\t */\n\tadjustSeekIndex(i) {\n\t\treturn i;\n\t}\n\n\tlazyInit() {\n\t\tif (this.index === -1) {\n\t\t\tthis.setup();\n\t\t}\n\t}\n\n\tsetup() {\n\t\tthis.sync(0);\n\t\tthis.index = this.adjustSeekIndex(0);\n\t}\n\n\t// Reset this token stream by setting its token source.///\n\tsetTokenSource(tokenSource) {\n\t\tthis.tokenSource = tokenSource;\n\t\tthis.tokens = [];\n\t\tthis.index = -1;\n\t\tthis.fetchedEOF = false;\n\t}\n\n\t/**\n\t * Given a starting index, return the index of the next token on channel.\n\t * Return i if tokens[i] is on channel. Return -1 if there are no tokens\n\t * on channel between i and EOF.\n\t */\n\tnextTokenOnChannel(i, channel) {\n\t\tthis.sync(i);\n\t\tif (i >= this.tokens.length) {\n\t\t\treturn -1;\n\t\t}\n\t\tlet token = this.tokens[i];\n\t\twhile (token.channel !== channel) {\n\t\t\tif (token.type === Token.EOF) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\ti += 1;\n\t\t\tthis.sync(i);\n\t\t\ttoken = this.tokens[i];\n\t\t}\n\t\treturn i;\n\t}\n\n\t/**\n\t * Given a starting index, return the index of the previous token on channel.\n\t * Return i if tokens[i] is on channel. Return -1 if there are no tokens\n\t * on channel between i and 0.\n\t */\n\tpreviousTokenOnChannel(i, channel) {\n\t\twhile (i >= 0 && this.tokens[i].channel !== channel) {\n\t\t\ti -= 1;\n\t\t}\n\t\treturn i;\n\t}\n\n\t/**\n\t * Collect all tokens on specified channel to the right of\n\t * the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or\n\t * EOF. If channel is -1, find any non default channel token.\n\t */\n\tgetHiddenTokensToRight(tokenIndex,\n\t\tchannel) {\n\t\tif (channel === undefined) {\n\t\t\tchannel = -1;\n\t\t}\n\t\tthis.lazyInit();\n\t\tif (tokenIndex < 0 || tokenIndex >= this.tokens.length) {\n\t\t\tthrow \"\" + tokenIndex + \" not in 0..\" + this.tokens.length - 1;\n\t\t}\n\t\tconst nextOnChannel = this.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL);\n\t\tconst from_ = tokenIndex + 1;\n\t\t// if none onchannel to right, nextOnChannel=-1 so set to = last token\n\t\tconst to = nextOnChannel === -1 ? this.tokens.length - 1 : nextOnChannel;\n\t\treturn this.filterForChannel(from_, to, channel);\n\t}\n\n\t/**\n\t * Collect all tokens on specified channel to the left of\n\t * the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n\t * If channel is -1, find any non default channel token.\n\t */\n\tgetHiddenTokensToLeft(tokenIndex,\n\t\tchannel) {\n\t\tif (channel === undefined) {\n\t\t\tchannel = -1;\n\t\t}\n\t\tthis.lazyInit();\n\t\tif (tokenIndex < 0 || tokenIndex >= this.tokens.length) {\n\t\t\tthrow \"\" + tokenIndex + \" not in 0..\" + this.tokens.length - 1;\n\t\t}\n\t\tconst prevOnChannel = this.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL);\n\t\tif (prevOnChannel === tokenIndex - 1) {\n\t\t\treturn null;\n\t\t}\n\t\t// if none on channel to left, prevOnChannel=-1 then from=0\n\t\tconst from_ = prevOnChannel + 1;\n\t\tconst to = tokenIndex - 1;\n\t\treturn this.filterForChannel(from_, to, channel);\n\t}\n\n\tfilterForChannel(left, right, channel) {\n\t\tconst hidden = [];\n\t\tfor (let i = left; i < right + 1; i++) {\n\t\t\tconst t = this.tokens[i];\n\t\t\tif (channel === -1) {\n\t\t\t\tif (t.channel !== Lexer.DEFAULT_TOKEN_CHANNEL) {\n\t\t\t\t\thidden.push(t);\n\t\t\t\t}\n\t\t\t} else if (t.channel === channel) {\n\t\t\t\thidden.push(t);\n\t\t\t}\n\t\t}\n\t\tif (hidden.length === 0) {\n\t\t\treturn null;\n\t\t}\n\t\treturn hidden;\n\t}\n\n\tgetSourceName() {\n\t\treturn this.tokenSource.getSourceName();\n\t}\n\n\t// Get the text of all tokens in this buffer.///\n\tgetText(interval) {\n\t\tthis.lazyInit();\n\t\tthis.fill();\n\t\tif (!interval) {\n\t\t\tinterval = new Interval(0, this.tokens.length - 1);\n\t\t}\n\t\tlet start = interval.start;\n\t\tif (start instanceof Token) {\n\t\t\tstart = start.tokenIndex;\n\t\t}\n\t\tlet stop = interval.stop;\n\t\tif (stop instanceof Token) {\n\t\t\tstop = stop.tokenIndex;\n\t\t}\n\t\tif (start === null || stop === null || start < 0 || stop < 0) {\n\t\t\treturn \"\";\n\t\t}\n\t\tif (stop >= this.tokens.length) {\n\t\t\tstop = this.tokens.length - 1;\n\t\t}\n\t\tlet s = \"\";\n\t\tfor (let i = start; i < stop + 1; i++) {\n\t\t\tconst t = this.tokens[i];\n\t\t\tif (t.type === Token.EOF) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ts = s + t.text;\n\t\t}\n\t\treturn s;\n\t}\n\n\t// Get all tokens from lexer until EOF///\n\tfill() {\n\t\tthis.lazyInit();\n\t\t// noinspection StatementWithEmptyBodyJS\n\t\twhile (this.fetch(1000) === 1000);\n\t}\n}\n\nObject.defineProperty(BufferedTokenStream, \"size\", {\n\tget: function() {\n\t\treturn this.tokens.length;\n\t}\n})\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CharStream.d.ts",
    "content": "export declare class CharStream {\n\n    index: number; // defined as property\n    size: number;// defined as property\n\n    constructor(data: string);\n    constructor(data: string, decodeToUnicodeCodePoints: boolean);\n    reset(): void;\n    consume(): void;\n    LA(offset: number): number;\n    LT(offset: number): number;\n    mark(): number;\n    release(marker: number): void;\n    seek(index: number): void;\n    getText(start: number, stop: number): string;\n    toString(): string;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CharStream.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from './Token.js';\n\n/**\n * If decodeToUnicodeCodePoints is true, the input is treated\n * as a series of Unicode code points.\n *\n * Otherwise, the input is treated as a series of 16-bit UTF-16 code\n * units.\n */\nexport default class CharStream {\n    constructor(data, decodeToUnicodeCodePoints) {\n        this.name = \"<empty>\";\n        this.strdata = data;\n        this.decodeToUnicodeCodePoints = decodeToUnicodeCodePoints || false;\n        // _loadString - Vacuum all input from a string and then treat it like a buffer.\n        this._index = 0;\n        this.data = [];\n        if (this.decodeToUnicodeCodePoints) {\n            for (let i = 0; i < this.strdata.length; ) {\n                const codePoint = this.strdata.codePointAt(i);\n                this.data.push(codePoint);\n                i += codePoint <= 0xFFFF ? 1 : 2;\n            }\n        } else {\n            this.data = new Array(this.strdata.length);\n            for (let i = 0; i < this.strdata.length; i++) {\n                this.data[i] = this.strdata.charCodeAt(i);\n            }\n        }\n        this._size = this.data.length;\n    }\n\n    /**\n     * Reset the stream so that it's in the same state it was\n     * when the object was created *except* the data array is not\n     * touched.\n     */\n    reset() {\n        this._index = 0;\n    }\n\n    consume() {\n        if (this._index >= this._size) {\n            // assert this.LA(1) == Token.EOF\n            throw (\"cannot consume EOF\");\n        }\n        this._index += 1;\n    }\n\n    LA(offset) {\n        if (offset === 0) {\n            return 0; // undefined\n        }\n        if (offset < 0) {\n            offset += 1; // e.g., translate LA(-1) to use offset=0\n        }\n        const pos = this._index + offset - 1;\n        if (pos < 0 || pos >= this._size) { // invalid\n            return Token.EOF;\n        }\n        return this.data[pos];\n    }\n\n    LT(offset) {\n        return this.LA(offset);\n    }\n\n// mark/release do nothing; we have entire buffer\n    mark() {\n        return -1;\n    }\n\n    release(marker) {\n    }\n\n    /**\n     * consume() ahead until p==_index; can't just set p=_index as we must\n     * update line and column. If we seek backwards, just set p\n     */\n    seek(_index) {\n        if (_index <= this._index) {\n            this._index = _index; // just jump; don't update stream state (line,\n            // ...)\n            return;\n        }\n        // seek forward\n        this._index = Math.min(_index, this._size);\n    }\n\n    getText(start, stop) {\n        if (stop >= this._size) {\n            stop = this._size - 1;\n        }\n        if (start >= this._size) {\n            return \"\";\n        } else {\n            if (this.decodeToUnicodeCodePoints) {\n                let result = \"\";\n                for (let i = start; i <= stop; i++) {\n                    result += String.fromCodePoint(this.data[i]);\n                }\n                return result;\n            } else {\n                return this.strdata.slice(start, stop + 1);\n            }\n        }\n    }\n\n    toString() {\n        return this.strdata;\n    }\n\n    get index(){\n        return this._index;\n    }\n\n    get size(){\n        return this._size;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CharStreams.d.ts",
    "content": "import {CharStream} from \"./CharStream.js\";\n\nexport declare class CharStreams {\n    static fromString(data: string, decodeToUnicodeCodePoints?: boolean): CharStream;\n    static fromBuffer(buffer: Buffer, encoding?: string): CharStream;\n    static fromBlob(blob: Blob, encoding: string, onLoad: (stream: CharStream) => void, onError: (error: Error) => void): void;\n    static fromPath(path: string, encoding: string, callback: (err: Error, stream: CharStream) => void): void;\n    static fromPathSync(path: string, encoding: string): CharStream;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CharStreams.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport CharStream from \"./CharStream.js\";\nimport FileStream from \"./FileStream.js\";\n\n/**\n * Utility functions to create InputStreams from various sources.\n *\n * All returned InputStreams support the full range of Unicode\n * up to U+10FFFF (the default behavior of InputStream only supports\n * code points up to U+FFFF).\n */\nexport default {\n  // Creates an InputStream from a string.\n  fromString: function(str) {\n    return new CharStream(str, true);\n  },\n\n  /**\n   * Asynchronously creates an InputStream from a blob given the\n   * encoding of the bytes in that blob (defaults to 'utf8' if\n   * encoding is null).\n   *\n   * Invokes onLoad(result) on success, onError(error) on\n   * failure.\n   */\n  fromBlob: function(blob, encoding, onLoad, onError) {\n    const reader = new window.FileReader();\n    reader.onload = function(e) {\n      const is = new CharStream(e.target.result, true);\n      onLoad(is);\n    };\n    reader.onerror = onError;\n    reader.readAsText(blob, encoding);\n  },\n\n  /**\n   * Creates an InputStream from a Buffer given the\n   * encoding of the bytes in that buffer (defaults to 'utf8' if\n   * encoding is null).\n   */\n  fromBuffer: function(buffer, encoding) {\n    return new CharStream(buffer.toString(encoding), true);\n  },\n\n  /** Asynchronously creates an InputStream from a file on disk given\n   * the encoding of the bytes in that file (defaults to 'utf8' if\n   * encoding is null).\n   *\n   * Invokes callback(error, result) on completion.\n   */\n  fromPath: function(path, encoding, callback) {\n    FileStream.fromPath(path, encoding, callback);\n  },\n\n  /**\n   * Synchronously creates an InputStream given a path to a file\n   * on disk and the encoding of the bytes in that file (defaults to\n   * 'utf8' if encoding is null).\n   */\n  fromPathSync: function(path, encoding) {\n    return new FileStream(path, encoding);\n  }\n};\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CommonToken.d.ts",
    "content": "import { Token } from \"./Token.js\";\nimport {InputStream} from \"./InputStream.js\";\nimport {TokenSource} from \"./TokenSource.js\";\n\nexport declare class CommonToken extends Token {\n    constructor(source: [ TokenSource, InputStream ], type: number, channel: number, start: number, stop: number);\n    clone(): CommonToken;\n    cloneWithType(type: number): CommonToken;\n    toString(): string;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CommonToken.js",
    "content": "import Token from \"./Token.js\";\n\nexport default class CommonToken extends Token {\n    constructor(source, type, channel, start, stop) {\n        super();\n        this.source = source !== undefined ? source : CommonToken.EMPTY_SOURCE;\n        this.type = type !== undefined ? type : null;\n        this.channel = channel !== undefined ? channel : Token.DEFAULT_CHANNEL;\n        this.start = start !== undefined ? start : -1;\n        this.stop = stop !== undefined ? stop : -1;\n        this.tokenIndex = -1;\n        if (this.source[0] !== null) {\n            this.line = source[0].line;\n            this.column = source[0].column;\n        } else {\n            this.column = -1;\n        }\n    }\n\n    /**\n     * Constructs a new {@link CommonToken} as a copy of another {@link Token}.\n     *\n     * <p>\n     * If {@code oldToken} is also a {@link CommonToken} instance, the newly\n     * constructed token will share a reference to the {@link //text} field and\n     * the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will\n     * be assigned the result of calling {@link //getText}, and {@link //source}\n     * will be constructed from the result of {@link Token//getTokenSource} and\n     * {@link Token//getInputStream}.</p>\n     *\n     * @param oldToken The token to copy.\n     */\n    clone() {\n        const t = new CommonToken(this.source, this.type, this.channel, this.start, this.stop);\n        t.tokenIndex = this.tokenIndex;\n        t.line = this.line;\n        t.column = this.column;\n        t.text = this.text;\n        return t;\n    }\n\n    cloneWithType(type) {\n        const t = new CommonToken(this.source, type, this.channel, this.start, this.stop);\n        t.tokenIndex = this.tokenIndex;\n        t.line = this.line;\n        t.column = this.column;\n        if (type === Token.EOF)\n            t.text = \"\";\n        return t;\n    }\n\n    toString() {\n        let txt = this.text;\n        if (txt !== null) {\n            txt = txt.replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\\\\r\").replace(/\\t/g, \"\\\\t\");\n        } else {\n            txt = \"<no text>\";\n        }\n        return \"[@\" + this.tokenIndex + \",\" + this.start + \":\" + this.stop + \"='\" +\n            txt + \"',<\" + this.type + \">\" +\n            (this.channel > 0 ? \",channel=\" + this.channel : \"\") + \",\" +\n            this.line + \":\" + this.column + \"]\";\n    }\n\n    get text(){\n        if (this._text !== null) {\n            return this._text;\n        }\n        const input = this.getInputStream();\n        if (input === null) {\n            return null;\n        }\n        const n = input.size;\n        if (this.start < n && this.stop < n) {\n            return input.getText(this.start, this.stop);\n        } else {\n            return \"<EOF>\";\n        }\n    }\n\n    set text(text) {\n        this._text = text;\n    }\n}\n\n/**\n * An empty {@link Pair} which is used as the default value of\n * {@link //source} for tokens that do not have a source.\n */\nCommonToken.EMPTY_SOURCE = [ null, null ];\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CommonTokenFactory.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport CommonToken from './CommonToken.js';\n\nclass TokenFactory {}\n\n/**\n * This default implementation of {@link TokenFactory} creates\n * {@link CommonToken} objects.\n */\nexport default class CommonTokenFactory extends TokenFactory {\n    constructor(copyText) {\n        super();\n        /**\n         * Indicates whether {@link CommonToken//setText} should be called after\n         * constructing tokens to explicitly set the text. This is useful for cases\n         * where the input stream might not be able to provide arbitrary substrings\n         * of text from the input after the lexer creates a token (e.g. the\n         * implementation of {@link CharStream//getText} in\n         * {@link UnbufferedCharStream} throws an\n         * {@link UnsupportedOperationException}). Explicitly setting the token text\n         * allows {@link Token//getText} to be called at any time regardless of the\n         * input stream implementation.\n         *\n         * <p>\n         * The default value is {@code false} to avoid the performance and memory\n         * overhead of copying text for every token unless explicitly requested.</p>\n         */\n        this.copyText = copyText===undefined ? false : copyText;\n    }\n\n    create(source, type, text, channel, start, stop, line, column) {\n        const t = new CommonToken(source, type, channel, start, stop);\n        t.line = line;\n        t.column = column;\n        if (text !==null) {\n            t.text = text;\n        } else if (this.copyText && source[1] !==null) {\n            t.text = source[1].getText(start,stop);\n        }\n        return t;\n    }\n\n    createThin(type, text) {\n        const t = new CommonToken(null, type);\n        t.text = text;\n        return t;\n    }\n}\n\n/**\n * The default {@link CommonTokenFactory} instance.\n *\n * <p>\n * This token factory does not explicitly copy token text when constructing\n * tokens.</p>\n */\nCommonTokenFactory.DEFAULT = new CommonTokenFactory();\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CommonTokenStream.d.ts",
    "content": "import {Lexer} from \"./Lexer.js\";\nimport {BufferedTokenStream} from \"./BufferedTokenStream.js\";\nimport {Token} from \"./Token.js\";\n\nexport declare class CommonTokenStream extends BufferedTokenStream {\n    // properties\n    tokens: Token[];\n    // methods\n    constructor(lexer: Lexer);\n    constructor(lexer: Lexer, channel: number);\n    fill(): void;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/CommonTokenStream.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\nimport Token from './Token.js';\nimport BufferedTokenStream from './BufferedTokenStream.js';\n\n/**\n * This class extends {@link BufferedTokenStream} with functionality to filter\n * token streams to tokens on a particular channel (tokens where\n * {@link Token//getChannel} returns a particular value).\n *\n * <p>\n * This token stream provides access to all tokens by index or when calling\n * methods like {@link //getText}. The channel filtering is only used for code\n * accessing tokens via the lookahead methods {@link //LA}, {@link //LT}, and\n * {@link //LB}.</p>\n *\n * <p>\n * By default, tokens are placed on the default channel\n * ({@link Token//DEFAULT_CHANNEL}), but may be reassigned by using the\n * {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to\n * call {@link Lexer//setChannel}.\n * </p>\n *\n * <p>\n * Note: lexer rules which use the {@code ->skip} lexer command or call\n * {@link Lexer//skip} do not produce tokens at all, so input text matched by\n * such a rule will not be available as part of the token stream, regardless of\n * channel.</p>\n */\nexport default class CommonTokenStream extends BufferedTokenStream {\n    constructor(lexer, channel) {\n        super(lexer);\n        this.channel = channel===undefined ? Token.DEFAULT_CHANNEL : channel;\n    }\n\n    adjustSeekIndex(i) {\n        return this.nextTokenOnChannel(i, this.channel);\n    }\n\n    LB(k) {\n        if (k===0 || this.index-k<0) {\n            return null;\n        }\n        let i = this.index;\n        let n = 1;\n        // find k good tokens looking backwards\n        while (n <= k) {\n            // skip off-channel tokens\n            i = this.previousTokenOnChannel(i - 1, this.channel);\n            n += 1;\n        }\n        if (i < 0) {\n            return null;\n        }\n        return this.tokens[i];\n    }\n\n    LT(k) {\n        this.lazyInit();\n        if (k === 0) {\n            return null;\n        }\n        if (k < 0) {\n            return this.LB(-k);\n        }\n        let i = this.index;\n        let n = 1; // we know tokens[pos] is a good one\n        // find k good tokens\n        while (n < k) {\n            // skip off-channel tokens, but make sure to not look past EOF\n            if (this.sync(i + 1)) {\n                i = this.nextTokenOnChannel(i + 1, this.channel);\n            }\n            n += 1;\n        }\n        return this.tokens[i];\n    }\n\n    // Count EOF just once.\n    getNumberOfOnChannelTokens() {\n        let n = 0;\n        this.fill();\n        for (let i =0; i< this.tokens.length;i++) {\n            const t = this.tokens[i];\n            if( t.channel===this.channel) {\n                n += 1;\n            }\n            if( t.type===Token.EOF) {\n                break;\n            }\n        }\n        return n;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/FileStream.d.ts",
    "content": "import {CharStream} from \"./CharStream.js\";\n\nexport declare class FileStream extends CharStream {\n\n    fileName: string;\n\n    constructor(fileName: string, encoding?: string, decodeToUnicodeCodePoints?: boolean);\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/FileStream.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport InputStream from './InputStream.js';\nimport CharStream from './CharStream.js';\nconst isNode =\n\ttypeof process !== \"undefined\" &&\n\tprocess.versions != null &&\n\tprocess.versions.node != null;\nimport fs from 'fs';\n\n/**\n * This is an InputStream that is loaded from a file all at once\n * when you construct the object.\n */\nexport default class FileStream extends InputStream {\n\n\tstatic fromPath(path, encoding, callback) {\n\t\tif(!isNode)\n\t\t\tthrow new Error(\"FileStream is only available when running in Node!\");\n\t\tfs.readFile(path, encoding, function(err, data) {\n\t\t\tlet is = null;\n\t\t\tif (data !== null) {\n\t\t\t\tis = new CharStream(data, true);\n\t\t\t}\n\t\t\tcallback(err, is);\n\t\t});\n\n\t}\n\n\tconstructor(fileName, encoding, decodeToUnicodeCodePoints) {\n\t\tif(!isNode)\n\t\t\tthrow new Error(\"FileStream is only available when running in Node!\");\n\t\tconst data = fs.readFileSync(fileName, encoding || \"utf-8\" );\n\t\tsuper(data, decodeToUnicodeCodePoints);\n\t\tthis.fileName = fileName;\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/InputStream.d.ts",
    "content": "export declare class InputStream {\n    constructor(data: string);\n    constructor(data: string, decodeToUnicodeCodePoints: boolean);\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/InputStream.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport CharStream from './CharStream.js';\n\n/**\n * @deprecated Use CharStream instead\n*/\nexport default class InputStream extends CharStream {\n\tconstructor(data, decodeToUnicodeCodePoints) {\n\t\tsuper(data, decodeToUnicodeCodePoints);\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Lexer.d.ts",
    "content": "import {Recognizer} from \"./Recognizer.js\";\nimport {LexerATNSimulator} from \"./atn/index.js\";\nimport {CharStream} from \"./CharStream.js\";\nimport {Token} from \"./Token.js\";\n\nexport declare class Lexer extends Recognizer<number> {\n\n    static DEFAULT_MODE: number;\n\n    _input: CharStream;\n    _interp: LexerATNSimulator;\n    text: string;\n    line: number;\n    column: number;\n    _tokenStartCharIndex: number;\n    _tokenStartLine: number;\n    _tokenStartColumn: number;\n    _type: number;\n\n    constructor(input: CharStream);\n    reset(): void;\n    nextToken(): Token;\n    skip(): void;\n    more(): void;\n    setMode(m: number): void;\n    getMode(): number;\n    getModeStack(): number[];\n    pushMode(m: number): void;\n    popMode(): number;\n    emitToken(token: Token): void;\n    emit(): Token;\n    emitEOF(): Token;\n    getAllTokens(): Token[];\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Lexer.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from './Token.js';\nimport Recognizer from './Recognizer.js';\nimport CommonTokenFactory from './CommonTokenFactory.js';\nimport RecognitionException from './error/RecognitionException.js';\nimport LexerNoViableAltException from './error/LexerNoViableAltException.js';\n\n/**\n * A lexer is recognizer that draws input symbols from a character stream.\n * lexer grammars result in a subclass of this object. A Lexer object\n * uses simplified match() and error recovery mechanisms in the interest of speed.\n */\nexport default class Lexer extends Recognizer {\n\tconstructor(input) {\n\t\tsuper();\n\t\tthis._input = input;\n\t\tthis._factory = CommonTokenFactory.DEFAULT;\n\t\tthis._tokenFactorySourcePair = [ this, input ];\n\n\t\tthis._interp = null; // child classes must populate this\n\n\t\t/**\n\t\t * The goal of all lexer rules/methods is to create a token object.\n\t\t * this is an instance variable as multiple rules may collaborate to\n\t\t * create a single token. nextToken will return this object after\n\t\t * matching lexer rule(s). If you subclass to allow multiple token\n\t\t * emissions, then set this to the last token to be matched or\n\t\t * something nonnull so that the auto token emit mechanism will not\n\t\t * emit another token.\n\t\t */\n\t\tthis._token = null;\n\n\t\t/**\n\t\t * What character index in the stream did the current token start at?\n\t\t * Needed, for example, to get the text for current token. Set at\n\t\t * the start of nextToken.\n\t\t */\n\t\tthis._tokenStartCharIndex = -1;\n\n\t\t// The line on which the first character of the token resides///\n\t\tthis._tokenStartLine = -1;\n\n\t\t// The character position of first character within the line///\n\t\tthis._tokenStartColumn = -1;\n\n\t\t// Once we see EOF on char stream, next token will be EOF.\n\t\t// If you have DONE : EOF ; then you see DONE EOF.\n\t\tthis._hitEOF = false;\n\n\t\t// The channel number for the current token///\n\t\tthis._channel = Token.DEFAULT_CHANNEL;\n\n\t\t// The token type for the current token///\n\t\tthis._type = Token.INVALID_TYPE;\n\n\t\tthis._modeStack = [];\n\t\tthis._mode = Lexer.DEFAULT_MODE;\n\n\t\t/**\n\t\t * You can set the text for the current token to override what is in\n\t\t * the input char buffer. Use setText() or can set this instance var.\n\t\t */\n\t\tthis._text = null;\n\t}\n\n\treset() {\n\t\t// wack Lexer state variables\n\t\tif (this._input !== null) {\n\t\t\tthis._input.seek(0); // rewind the input\n\t\t}\n\t\tthis._token = null;\n\t\tthis._type = Token.INVALID_TYPE;\n\t\tthis._channel = Token.DEFAULT_CHANNEL;\n\t\tthis._tokenStartCharIndex = -1;\n\t\tthis._tokenStartColumn = -1;\n\t\tthis._tokenStartLine = -1;\n\t\tthis._text = null;\n\n\t\tthis._hitEOF = false;\n\t\tthis._mode = Lexer.DEFAULT_MODE;\n\t\tthis._modeStack = [];\n\n\t\tthis._interp.reset();\n\t}\n\n// Return a token from this source; i.e., match a token on the char stream.\n\tnextToken() {\n\t\tif (this._input === null) {\n\t\t\tthrow \"nextToken requires a non-null input stream.\";\n\t\t}\n\n\t\t/**\n\t\t * Mark start location in char stream so unbuffered streams are\n\t\t * guaranteed at least have text of current token\n\t\t */\n\t\tconst tokenStartMarker = this._input.mark();\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tif (this._hitEOF) {\n\t\t\t\t\tthis.emitEOF();\n\t\t\t\t\treturn this._token;\n\t\t\t\t}\n\t\t\t\tthis._token = null;\n\t\t\t\tthis._channel = Token.DEFAULT_CHANNEL;\n\t\t\t\tthis._tokenStartCharIndex = this._input.index;\n\t\t\t\tthis._tokenStartColumn = this._interp.column;\n\t\t\t\tthis._tokenStartLine = this._interp.line;\n\t\t\t\tthis._text = null;\n\t\t\t\tlet continueOuter = false;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tthis._type = Token.INVALID_TYPE;\n\t\t\t\t\tlet ttype = Lexer.SKIP;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tttype = this._interp.match(this._input, this._mode);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif(e instanceof RecognitionException) {\n\t\t\t\t\t\t\tthis.notifyListeners(e); // report error\n\t\t\t\t\t\t\tthis.recover(e);\n\t\t\t\t\t\t} else {\n                            console.log(e.stack);\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (this._input.LA(1) === Token.EOF) {\n\t\t\t\t\t\tthis._hitEOF = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (this._type === Token.INVALID_TYPE) {\n\t\t\t\t\t\tthis._type = ttype;\n\t\t\t\t\t}\n\t\t\t\t\tif (this._type === Lexer.SKIP) {\n\t\t\t\t\t\tcontinueOuter = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (this._type !== Lexer.MORE) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (continueOuter) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (this._token === null) {\n\t\t\t\t\tthis.emit();\n\t\t\t\t}\n\t\t\t\treturn this._token;\n\t\t\t}\n\t\t} finally {\n\t\t\t// make sure we release marker after match or\n\t\t\t// unbuffered char stream will keep buffering\n\t\t\tthis._input.release(tokenStartMarker);\n\t\t}\n\t}\n\n\t/**\n\t * Instruct the lexer to skip creating a token for current lexer rule\n\t * and look for another token. nextToken() knows to keep looking when\n\t * a lexer rule finishes with token set to SKIP_TOKEN. Recall that\n\t * if token==null at end of any token rule, it creates one for you\n\t * and emits it.\n\t */\n\tskip() {\n\t\tthis._type = Lexer.SKIP;\n\t}\n\n\tmore() {\n\t\tthis._type = Lexer.MORE;\n\t}\n\n    /**\n     * @deprecated since ANTLR 4.13.2; use setMode instead\n     */\n\tmode(m) {\n\t\tconsole.warn(\"Calling deprecated method in Lexer class: mode(...)\");\n\t\tthis.setMode(m);\n\t}\n\n\tsetMode(m) {\n\t\tthis._mode = m;\n\t}\n\n\tgetMode() {\n\t\treturn this._mode;\n\t}\n\n\tgetModeStack() {\n\t\treturn this._modeStack;\n\t}\n\n\tpushMode(m) {\n\t\tif (this._interp.debug) {\n\t\t\tconsole.log(\"pushMode \" + m);\n\t\t}\n\t\tthis._modeStack.push(this._mode);\n\t\tthis.setMode(m);\n\t}\n\n\tpopMode() {\n\t\tif (this._modeStack.length === 0) {\n\t\t\tthrow \"Empty Stack\";\n\t\t}\n\t\tif (this._interp.debug) {\n\t\t\tconsole.log(\"popMode back to \" + this._modeStack.slice(0, -1));\n\t\t}\n\t\tthis.setMode(this._modeStack.pop());\n\t\treturn this._mode;\n\t}\n\n\t/**\n\t * By default does not support multiple emits per nextToken invocation\n\t * for efficiency reasons. Subclass and override this method, nextToken,\n\t * and getToken (to push tokens into a list and pull from that list\n\t * rather than a single variable as this implementation does).\n\t */\n\temitToken(token) {\n\t\tthis._token = token;\n\t}\n\n\t/**\n\t * The standard method called to automatically emit a token at the\n\t * outermost lexical rule. The token object should point into the\n\t * char buffer start..stop. If there is a text override in 'text',\n\t * use that to set the token's text. Override this method to emit\n\t * custom Token objects or provide a new factory.\n\t */\n\temit() {\n\t\tconst t = this._factory.create(this._tokenFactorySourcePair, this._type,\n\t\t\t\tthis._text, this._channel, this._tokenStartCharIndex, this\n\t\t\t\t\t\t.getCharIndex() - 1, this._tokenStartLine,\n\t\t\t\tthis._tokenStartColumn);\n\t\tthis.emitToken(t);\n\t\treturn t;\n\t}\n\n\temitEOF() {\n\t\tconst cpos = this.column;\n\t\tconst lpos = this.line;\n\t\tconst eof = this._factory.create(this._tokenFactorySourcePair, Token.EOF,\n\t\t\t\tnull, Token.DEFAULT_CHANNEL, this._input.index,\n\t\t\t\tthis._input.index - 1, lpos, cpos);\n\t\tthis.emitToken(eof);\n\t\treturn eof;\n\t}\n\n// What is the index of the current character of lookahead?///\n\tgetCharIndex() {\n\t\treturn this._input.index;\n\t}\n\n\t/**\n\t * Return a list of all Token objects in input char stream.\n\t * Forces load of all tokens. Does not include EOF token.\n\t */\n\tgetAllTokens() {\n\t\tconst tokens = [];\n\t\tlet t = this.nextToken();\n\t\twhile (t.type !== Token.EOF) {\n\t\t\ttokens.push(t);\n\t\t\tt = this.nextToken();\n\t\t}\n\t\treturn tokens;\n\t}\n\n\tnotifyListeners(e) {\n\t\tconst start = this._tokenStartCharIndex;\n\t\tconst stop = this._input.index;\n\t\tconst text = this._input.getText(start, stop);\n\t\tconst msg = \"token recognition error at: '\" + this.getErrorDisplay(text) + \"'\";\n\t\tconst listener = this.getErrorListener();\n\t\tlistener.syntaxError(this, null, this._tokenStartLine,\n\t\t\t\tthis._tokenStartColumn, msg, e);\n\t}\n\n\tgetErrorDisplay(s) {\n\t\tconst d = [];\n\t\tfor (let i = 0; i < s.length; i++) {\n\t\t\td.push(s[i]);\n\t\t}\n\t\treturn d.join('');\n\t}\n\n\tgetErrorDisplayForChar(c) {\n\t\tif (c.charCodeAt(0) === Token.EOF) {\n\t\t\treturn \"<EOF>\";\n\t\t} else if (c === '\\n') {\n\t\t\treturn \"\\\\n\";\n\t\t} else if (c === '\\t') {\n\t\t\treturn \"\\\\t\";\n\t\t} else if (c === '\\r') {\n\t\t\treturn \"\\\\r\";\n\t\t} else {\n\t\t\treturn c;\n\t\t}\n\t}\n\n\tgetCharErrorDisplay(c) {\n\t\treturn \"'\" + this.getErrorDisplayForChar(c) + \"'\";\n\t}\n\n\t/**\n\t * Lexers can normally match any char in it's vocabulary after matching\n\t * a token, so do the easy thing and just kill a character and hope\n\t * it all works out. You can instead use the rule invocation stack\n\t * to do sophisticated error recovery if you are in a fragment rule.\n\t */\n\trecover(re) {\n\t\tif (this._input.LA(1) !== Token.EOF) {\n\t\t\tif (re instanceof LexerNoViableAltException) {\n\t\t\t\t// skip a char and try again\n\t\t\t\tthis._interp.consume(this._input);\n\t\t\t} else {\n\t\t\t\t// TODO: Do we lose character or line position information?\n\t\t\t\tthis._input.consume();\n\t\t\t}\n\t\t}\n\t}\n\n\tget inputStream(){\n\t\treturn this._input;\n\t}\n\n\tset inputStream(input) {\n\t\tthis._input = null;\n\t\tthis._tokenFactorySourcePair = [ this, this._input ];\n\t\tthis.reset();\n\t\tthis._input = input;\n\t\tthis._tokenFactorySourcePair = [ this, this._input ];\n\t}\n\n\tget sourceName(){\n\t\treturn this._input.sourceName;\n\t}\n\n\tget type(){\n\t\treturn this._type;\n\t}\n\n\tset type(type) {\n\t\tthis._type = type;\n\t}\n\n\tget line(){\n\t\treturn this._interp.line;\n\t}\n\n\tset line(line) {\n\t\tthis._interp.line = line;\n\t}\n\n\tget column(){\n\t\treturn this._interp.column;\n\t}\n\n\tset column(column) {\n\t\tthis._interp.column = column;\n\t}\n\n\tget text(){\n\t\tif (this._text !== null) {\n\t\t\treturn this._text;\n\t\t} else {\n\t\t\treturn this._interp.getText(this._input);\n\t\t}\n\t}\n\n\tset text(text) {\n\t\tthis._text = text;\n\t}\n}\n\n\n\n\nLexer.DEFAULT_MODE = 0;\nLexer.MORE = -2;\nLexer.SKIP = -3;\n\nLexer.DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL;\nLexer.HIDDEN = Token.HIDDEN_CHANNEL;\nLexer.MIN_CHAR_VALUE = 0x0000;\nLexer.MAX_CHAR_VALUE = 0x10FFFF;\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Parser.d.ts",
    "content": "import {TokenStream} from \"./TokenStream.js\";\nimport {Recognizer} from \"./Recognizer.js\";\nimport {ErrorStrategy, RecognitionException} from \"./error/index.js\";\nimport {IntervalSet} from \"./misc/index.js\";\nimport {ParserATNSimulator} from \"./atn/index.js\";\nimport {Token} from \"./Token.js\";\nimport {ParserRuleContext} from \"./context/index.js\";\nimport {Printer} from \"./utils/index.js\";\nimport {ParseTreeListener} from \"./tree/index.js\";\n\nexport declare class Parser extends Recognizer<Token> {\n\n    static EOF: number;\n\n    _input: TokenStream;\n    _ctx: ParserRuleContext;\n    _interp: ParserATNSimulator;\n    _errHandler: ErrorStrategy;\n    _parseListeners?: any[];\n    matchedEOF: boolean;\n    buildParseTrees: boolean;\n    printer?: Printer;\n    syntaxErrorsCount: number;\n\n    constructor(input: TokenStream);\n    match(ttype: number): Token;\n    matchWildcard(): Token;\n    getParseListeners(): ParseTreeListener[];\n    addParseListener(listener: ParseTreeListener): void;\n    removeParseListener(listener: ParseTreeListener): void;\n    removeParseListeners(): void;\n    consume(): Token;\n    enterRule(localctx: ParserRuleContext, state: number, ruleIndex: number): void;\n    exitRule() : void;\n    triggerExitRuleEvent() : void;\n    enterOuterAlt(localctx: ParserRuleContext, altNum: number): void;\n    enterRecursionRule(localctx: ParserRuleContext, state: number, ruleIndex: number, precedence: number): void;\n    pushNewRecursionContext(localctx: ParserRuleContext, state: number, ruleIndex: number): void;\n    unrollRecursionContexts(parentCtx: ParserRuleContext): void;\n    precpred(localctx: ParserRuleContext, precedence: number): boolean;\n    getRuleInvocationStack(): string[];\n    dumpDFA(): void;\n    getExpectedTokens(): IntervalSet;\n    getTokenStream(): TokenStream;\n    reset(): void;\n    setTokenStream(input: TokenStream): void;\n    notifyErrorListeners(msg: string, offendingToken: Token, err: RecognitionException | undefined): void;\n    getCurrentToken(): Token;\n    getInvokingContext(ruleIndex: number): ParserRuleContext;\n    \n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Parser.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from './Token.js';\nimport TerminalNode from './tree/TerminalNode.js';\nimport ErrorNode from './tree/ErrorNode.js';\nimport Recognizer from './Recognizer.js';\nimport DefaultErrorStrategy from './error/DefaultErrorStrategy.js';\nimport ATNDeserializer from './atn/ATNDeserializer.js';\nimport ATNDeserializationOptions from './atn/ATNDeserializationOptions.js';\nimport TraceListener from \"./TraceListener.js\";\n\nexport default class Parser extends Recognizer {\n    /**\n     * this is all the parsing support code essentially; most of it is error\n     * recovery stuff.\n     */\n    constructor(input) {\n        super();\n        // The input stream.\n        this._input = null;\n        /**\n         * The error handling strategy for the parser. The default value is a new\n         * instance of {@link DefaultErrorStrategy}.\n         */\n        this._errHandler = new DefaultErrorStrategy();\n        this._precedenceStack = [];\n        this._precedenceStack.push(0);\n        /**\n         * The {@link ParserRuleContext} object for the currently executing rule.\n         * this is always non-null during the parsing process.\n         */\n        this._ctx = null;\n        /**\n         * Specifies whether or not the parser should construct a parse tree during\n         * the parsing process. The default value is {@code true}.\n         */\n        this.buildParseTrees = true;\n        /**\n         * When {@link //setTrace}{@code (true)} is called, a reference to the\n         * {@link TraceListener} is stored here so it can be easily removed in a\n         * later call to {@link //setTrace}{@code (false)}. The listener itself is\n         * implemented as a parser listener so this field is not directly used by\n         * other parser methods.\n         */\n        this._tracer = null;\n        /**\n         * The list of {@link ParseTreeListener} listeners registered to receive\n         * events during the parse.\n         */\n        this._parseListeners = null;\n        /**\n         * The number of syntax errors reported during parsing. this value is\n         * incremented each time {@link //notifyErrorListeners} is called.\n         */\n        this._syntaxErrors = 0;\n        this.setInputStream(input);\n    }\n\n    // reset the parser's state\n    reset() {\n        if (this._input !== null) {\n            this._input.seek(0);\n        }\n        this._errHandler.reset(this);\n        this._ctx = null;\n        this._syntaxErrors = 0;\n        this.setTrace(false);\n        this._precedenceStack = [];\n        this._precedenceStack.push(0);\n        if (this._interp !== null) {\n            this._interp.reset();\n        }\n    }\n\n    /**\n     * Match current input symbol against {@code ttype}. If the symbol type\n     * matches, {@link ANTLRErrorStrategy//reportMatch} and {@link //consume} are\n     * called to complete the match process.\n     *\n     * <p>If the symbol type does not match,\n     * {@link ANTLRErrorStrategy//recoverInline} is called on the current error\n     * strategy to attempt recovery. If {@link //buildParseTree} is\n     * {@code true} and the token index of the symbol returned by\n     * {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to\n     * the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>\n     *\n     * @param ttype the token type to match\n     * @return the matched symbol\n     * @throws RecognitionException if the current input symbol did not match\n     * {@code ttype} and the error strategy could not recover from the\n     * mismatched symbol\n     */\n    match(ttype) {\n        let t = this.getCurrentToken();\n        if (t.type === ttype) {\n            this._errHandler.reportMatch(this);\n            this.consume();\n        } else {\n            t = this._errHandler.recoverInline(this);\n            if (this.buildParseTrees && t.tokenIndex === -1) {\n                // we must have conjured up a new token during single token\n                // insertion\n                // if it's not the current symbol\n                this._ctx.addErrorNode(t);\n            }\n        }\n        return t;\n    }\n\n    /**\n     * Match current input symbol as a wildcard. If the symbol type matches\n     * (i.e. has a value greater than 0), {@link ANTLRErrorStrategy//reportMatch}\n     * and {@link //consume} are called to complete the match process.\n     *\n     * <p>If the symbol type does not match,\n     * {@link ANTLRErrorStrategy//recoverInline} is called on the current error\n     * strategy to attempt recovery. If {@link //buildParseTree} is\n     * {@code true} and the token index of the symbol returned by\n     * {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to\n     * the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>\n     *\n     * @return the matched symbol\n     * @throws RecognitionException if the current input symbol did not match\n     * a wildcard and the error strategy could not recover from the mismatched\n     * symbol\n     */\n    matchWildcard() {\n        let t = this.getCurrentToken();\n        if (t.type > 0) {\n            this._errHandler.reportMatch(this);\n            this.consume();\n        } else {\n            t = this._errHandler.recoverInline(this);\n            if (this.buildParseTrees && t.tokenIndex === -1) {\n                // we must have conjured up a new token during single token\n                // insertion\n                // if it's not the current symbol\n                this._ctx.addErrorNode(t);\n            }\n        }\n        return t;\n    }\n\n    getParseListeners() {\n        return this._parseListeners || [];\n    }\n\n    /**\n     * Registers {@code listener} to receive events during the parsing process.\n     *\n     * <p>To support output-preserving grammar transformations (including but not\n     * limited to left-recursion removal, automated left-factoring, and\n     * optimized code generation), calls to listener methods during the parse\n     * may differ substantially from calls made by\n     * {@link ParseTreeWalker//DEFAULT} used after the parse is complete. In\n     * particular, rule entry and exit events may occur in a different order\n     * during the parse than after the parser. In addition, calls to certain\n     * rule entry methods may be omitted.</p>\n     *\n     * <p>With the following specific exceptions, calls to listener events are\n     * <em>deterministic</em>, i.e. for identical input the calls to listener\n     * methods will be the same.</p>\n     *\n     * <ul>\n     * <li>Alterations to the grammar used to generate code may change the\n     * behavior of the listener calls.</li>\n     * <li>Alterations to the command line options passed to ANTLR 4 when\n     * generating the parser may change the behavior of the listener calls.</li>\n     * <li>Changing the version of the ANTLR Tool used to generate the parser\n     * may change the behavior of the listener calls.</li>\n     * </ul>\n     *\n     * @param listener the listener to add\n     *\n     * @throws NullPointerException if {@code} listener is {@code null}\n     */\n    addParseListener(listener) {\n        if (listener === null) {\n            throw \"listener\";\n        }\n        if (this._parseListeners === null) {\n            this._parseListeners = [];\n        }\n        this._parseListeners.push(listener);\n    }\n\n    /**\n     * Remove {@code listener} from the list of parse listeners.\n     *\n     * <p>If {@code listener} is {@code null} or has not been added as a parse\n     * listener, this method does nothing.</p>\n     * @param listener the listener to remove\n     */\n    removeParseListener(listener) {\n        if (this._parseListeners !== null) {\n            const idx = this._parseListeners.indexOf(listener);\n            if (idx >= 0) {\n                this._parseListeners.splice(idx, 1);\n            }\n            if (this._parseListeners.length === 0) {\n                this._parseListeners = null;\n            }\n        }\n    }\n\n    // Remove all parse listeners.\n    removeParseListeners() {\n        this._parseListeners = null;\n    }\n\n    // Notify any parse listeners of an enter rule event.\n    triggerEnterRuleEvent() {\n        if (this._parseListeners !== null) {\n            const ctx = this._ctx;\n            this._parseListeners.forEach(function (listener) {\n                listener.enterEveryRule(ctx);\n                ctx.enterRule(listener);\n            });\n        }\n    }\n\n    /**\n     * Notify any parse listeners of an exit rule event.\n     * @see //addParseListener\n     */\n    triggerExitRuleEvent() {\n        if (this._parseListeners !== null) {\n            // reverse order walk of listeners\n            const ctx = this._ctx;\n            this._parseListeners.slice(0).reverse().forEach(function (listener) {\n                ctx.exitRule(listener);\n                listener.exitEveryRule(ctx);\n            });\n        }\n    }\n\n    getTokenFactory() {\n        return this._input.tokenSource._factory;\n    }\n\n    // Tell our token source and error strategy about a new way to create tokens.\n    setTokenFactory(factory) {\n        this._input.tokenSource._factory = factory;\n    }\n\n    /**\n     * The ATN with bypass alternatives is expensive to create so we create it\n     * lazily.\n     *\n     * @throws UnsupportedOperationException if the current parser does not\n     * implement the {@link //getSerializedATN()} method.\n     */\n    getATNWithBypassAlts() {\n        const serializedAtn = this.getSerializedATN();\n        if (serializedAtn === null) {\n            throw \"The current parser does not support an ATN with bypass alternatives.\";\n        }\n        let result = this.bypassAltsAtnCache[serializedAtn];\n        if (result === null) {\n            const deserializationOptions = new ATNDeserializationOptions();\n            deserializationOptions.generateRuleBypassTransitions = true;\n            result = new ATNDeserializer(deserializationOptions)\n                .deserialize(serializedAtn);\n            this.bypassAltsAtnCache[serializedAtn] = result;\n        }\n        return result;\n    }\n\n    getInputStream() {\n        return this.getTokenStream();\n    }\n\n    setInputStream(input) {\n        this.setTokenStream(input);\n    }\n\n    getTokenStream() {\n        return this._input;\n    }\n\n    // Set the token stream and reset the parser.\n    setTokenStream(input) {\n        this._input = null;\n        this.reset();\n        this._input = input;\n    }\n\n    /**\n\t * Gets the number of syntax errors reported during parsing. This value is\n\t * incremented each time {@link //notifyErrorListeners} is called.\t \n\t */\n    get syntaxErrorsCount() {\n        return this._syntaxErrors;\n    }\n\n\n    /**\n     * Match needs to return the current input symbol, which gets put\n     * into the label for the associated token ref; e.g., x=ID.\n     */\n    getCurrentToken() {\n        return this._input.LT(1);\n    }\n\n    notifyErrorListeners(msg, offendingToken, err) {\n        offendingToken = offendingToken || null;\n        err = err || null;\n        if (offendingToken === null) {\n            offendingToken = this.getCurrentToken();\n        }\n        this._syntaxErrors += 1;\n        const line = offendingToken.line;\n        const column = offendingToken.column;\n        const listener = this.getErrorListener();\n        listener.syntaxError(this, offendingToken, line, column, msg, err);\n    }\n\n    /**\n     * Consume and return the {@linkplain //getCurrentToken current symbol}.\n     *\n     * <p>E.g., given the following input with {@code A} being the current\n     * lookahead symbol, this function moves the cursor to {@code B} and returns\n     * {@code A}.</p>\n     *\n     * <pre>\n     * A B\n     * ^\n     * </pre>\n     *\n     * If the parser is not in error recovery mode, the consumed symbol is added\n     * to the parse tree using {@link ParserRuleContext//addChild(Token)}, and\n     * {@link ParseTreeListener//visitTerminal} is called on any parse listeners.\n     * If the parser <em>is</em> in error recovery mode, the consumed symbol is\n     * added to the parse tree using\n     * {@link ParserRuleContext//addErrorNode(Token)}, and\n     * {@link ParseTreeListener//visitErrorNode} is called on any parse\n     * listeners.\n     */\n    consume() {\n        const o = this.getCurrentToken();\n        if (o.type !== Token.EOF) {\n            this.getInputStream().consume();\n        }\n        const hasListener = this._parseListeners !== null && this._parseListeners.length > 0;\n        if (this.buildParseTrees || hasListener) {\n            let node;\n            if (this._errHandler.inErrorRecoveryMode(this)) {\n                node = this._ctx.addErrorNode(o);\n            } else {\n                node = this._ctx.addTokenNode(o);\n            }\n            node.invokingState = this.state;\n            if (hasListener) {\n                this._parseListeners.forEach(function (listener) {\n                    if (node instanceof ErrorNode || (node.isErrorNode !== undefined && node.isErrorNode())) {\n                        listener.visitErrorNode(node);\n                    } else if (node instanceof TerminalNode) {\n                        listener.visitTerminal(node);\n                    }\n                });\n            }\n        }\n        return o;\n    }\n\n    addContextToParseTree() {\n        // add current context to parent if we have a parent\n        if (this._ctx.parentCtx !== null) {\n            this._ctx.parentCtx.addChild(this._ctx);\n        }\n    }\n\n    /**\n     * Always called by generated parsers upon entry to a rule. Access field\n     * {@link //_ctx} get the current context.\n     */\n    enterRule(localctx, state, ruleIndex) {\n        this.state = state;\n        this._ctx = localctx;\n        this._ctx.start = this._input.LT(1);\n        if (this.buildParseTrees) {\n            this.addContextToParseTree();\n        }\n        this.triggerEnterRuleEvent();\n    }\n\n    exitRule() {\n        this._ctx.stop = this._input.LT(-1);\n        // trigger event on _ctx, before it reverts to parent\n        this.triggerExitRuleEvent();\n        this.state = this._ctx.invokingState;\n        this._ctx = this._ctx.parentCtx;\n    }\n\n    enterOuterAlt(localctx, altNum) {\n        localctx.setAltNumber(altNum);\n        // if we have new localctx, make sure we replace existing ctx\n        // that is previous child of parse tree\n        if (this.buildParseTrees && this._ctx !== localctx) {\n            if (this._ctx.parentCtx !== null) {\n                this._ctx.parentCtx.removeLastChild();\n                this._ctx.parentCtx.addChild(localctx);\n            }\n        }\n        this._ctx = localctx;\n    }\n\n    /**\n     * Get the precedence level for the top-most precedence rule.\n     *\n     * @return The precedence level for the top-most precedence rule, or -1 if\n     * the parser context is not nested within a precedence rule.\n     */\n    getPrecedence() {\n        if (this._precedenceStack.length === 0) {\n            return -1;\n        } else {\n            return this._precedenceStack[this._precedenceStack.length - 1];\n        }\n    }\n\n    enterRecursionRule(localctx, state, ruleIndex, precedence) {\n        this.state = state;\n        this._precedenceStack.push(precedence);\n        this._ctx = localctx;\n        this._ctx.start = this._input.LT(1);\n        this.triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n    }\n\n    // Like {@link //enterRule} but for recursive rules.\n    pushNewRecursionContext(localctx, state, ruleIndex) {\n        const previous = this._ctx;\n        previous.parentCtx = localctx;\n        previous.invokingState = state;\n        previous.stop = this._input.LT(-1);\n\n        this._ctx = localctx;\n        this._ctx.start = previous.start;\n        if (this.buildParseTrees) {\n            this._ctx.addChild(previous);\n        }\n        this.triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules\n    }\n\n    unrollRecursionContexts(parentCtx) {\n        this._precedenceStack.pop();\n        this._ctx.stop = this._input.LT(-1);\n        const retCtx = this._ctx; // save current ctx (return value)\n        // unroll so _ctx is as it was before call to recursive method\n        const parseListeners = this.getParseListeners();\n        if (parseListeners !== null && parseListeners.length > 0) {\n            while (this._ctx !== parentCtx) {\n                this.triggerExitRuleEvent();\n                this._ctx = this._ctx.parentCtx;\n            }\n        } else {\n            this._ctx = parentCtx;\n        }\n        // hook into tree\n        retCtx.parentCtx = parentCtx;\n        if (this.buildParseTrees && parentCtx !== null) {\n            // add return ctx into invoking rule's tree\n            parentCtx.addChild(retCtx);\n        }\n    }\n\n    getInvokingContext(ruleIndex) {\n        let ctx = this._ctx;\n        while (ctx !== null) {\n            if (ctx.ruleIndex === ruleIndex) {\n                return ctx;\n            }\n            ctx = ctx.parentCtx;\n        }\n        return null;\n    }\n\n    precpred(localctx, precedence) {\n        return precedence >= this._precedenceStack[this._precedenceStack.length - 1];\n    }\n\n    inContext(context) {\n        // TODO: useful in parser?\n        return false;\n    }\n\n    /**\n     * Checks whether or not {@code symbol} can follow the current state in the\n     * ATN. The behavior of this method is equivalent to the following, but is\n     * implemented such that the complete context-sensitive follow set does not\n     * need to be explicitly constructed.\n     *\n     * <pre>\n     * return getExpectedTokens().contains(symbol);\n     * </pre>\n     *\n     * @param symbol the symbol type to check\n     * @return {@code true} if {@code symbol} can follow the current state in\n     * the ATN, otherwise {@code false}.\n     */\n    isExpectedToken(symbol) {\n        const atn = this._interp.atn;\n        let ctx = this._ctx;\n        const s = atn.states[this.state];\n        let following = atn.nextTokens(s);\n        if (following.contains(symbol)) {\n            return true;\n        }\n        if (!following.contains(Token.EPSILON)) {\n            return false;\n        }\n        while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {\n            const invokingState = atn.states[ctx.invokingState];\n            const rt = invokingState.transitions[0];\n            following = atn.nextTokens(rt.followState);\n            if (following.contains(symbol)) {\n                return true;\n            }\n            ctx = ctx.parentCtx;\n        }\n        if (following.contains(Token.EPSILON) && symbol === Token.EOF) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * Computes the set of input symbols which could follow the current parser\n     * state and context, as given by {@link //getState} and {@link //getContext},\n     * respectively.\n     *\n     * @see ATN//getExpectedTokens(int, RuleContext)\n     */\n    getExpectedTokens() {\n        return this._interp.atn.getExpectedTokens(this.state, this._ctx);\n    }\n\n    getExpectedTokensWithinCurrentRule() {\n        const atn = this._interp.atn;\n        const s = atn.states[this.state];\n        return atn.nextTokens(s);\n    }\n\n    // Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.\n    getRuleIndex(ruleName) {\n        const ruleIndex = this.getRuleIndexMap()[ruleName];\n        if (ruleIndex !== null) {\n            return ruleIndex;\n        } else {\n            return -1;\n        }\n    }\n\n    /**\n     * Return List&lt;String&gt; of the rule names in your parser instance\n     * leading up to a call to the current rule. You could override if\n     * you want more details such as the file/line info of where\n     * in the ATN a rule is invoked.\n     *\n     * this is very useful for error messages.\n     */\n    getRuleInvocationStack(p) {\n        p = p || null;\n        if (p === null) {\n            p = this._ctx;\n        }\n        const stack = [];\n        while (p !== null) {\n            // compute what follows who invoked us\n            const ruleIndex = p.ruleIndex;\n            if (ruleIndex < 0) {\n                stack.push(\"n/a\");\n            } else {\n                stack.push(this.ruleNames[ruleIndex]);\n            }\n            p = p.parentCtx;\n        }\n        return stack;\n    }\n\n    // For debugging and other purposes.\n    getDFAStrings() {\n        return this._interp.decisionToDFA.toString();\n    }\n\n    // For debugging and other purposes.\n    dumpDFA() {\n        let seenOne = false;\n        for (let i = 0; i < this._interp.decisionToDFA.length; i++) {\n            const dfa = this._interp.decisionToDFA[i];\n            if (dfa.states.length > 0) {\n                if (seenOne) {\n                    console.log();\n                }\n                this.printer.println(\"Decision \" + dfa.decision + \":\");\n                this.printer.print(dfa.toString(this.literalNames, this.symbolicNames));\n                seenOne = true;\n            }\n        }\n    }\n\n    getSourceName() {\n        return this._input.getSourceName();\n    }\n\n    /**\n     * During a parse is sometimes useful to listen in on the rule entry and exit\n     * events as well as token matches. this is for quick and dirty debugging.\n     */\n    setTrace(trace) {\n        if (!trace) {\n            this.removeParseListener(this._tracer);\n            this._tracer = null;\n        } else {\n            if (this._tracer !== null) {\n                this.removeParseListener(this._tracer);\n            }\n            this._tracer = new TraceListener(this);\n            this.addParseListener(this._tracer);\n        }\n    }\n}\n\n/**\n * this field maps from the serialized ATN string to the deserialized {@link\n    * ATN} with\n * bypass alternatives.\n *\n * @see ATNDeserializationOptions//isGenerateRuleBypassTransitions()\n */\nParser.bypassAltsAtnCache = {};\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Recognizer.d.ts",
    "content": "import {ErrorListener} from \"./error/index.js\";\n\nexport declare class Recognizer<TSymbol> {\n\n    state: number;\n\n    removeErrorListeners(): void;\n    addErrorListener(listener: ErrorListener<TSymbol>): void;\n    getErrorListener(): ErrorListener<TSymbol>;\n    getLiteralNames(): string[];\n    getSymbolicNames(): string[];\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Recognizer.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from './Token.js';\nimport ConsoleErrorListener from './error/ConsoleErrorListener.js';\nimport ProxyErrorListener from './error/ProxyErrorListener.js';\n\nexport default class Recognizer {\n    constructor() {\n        this._listeners = [ ConsoleErrorListener.INSTANCE ];\n        this._interp = null;\n        this._stateNumber = -1;\n    }\n\n    checkVersion(toolVersion) {\n        const runtimeVersion = \"4.13.2\";\n        if (runtimeVersion!==toolVersion) {\n            console.log(\"ANTLR runtime and generated code versions disagree: \"+runtimeVersion+\"!=\"+toolVersion);\n        }\n    }\n\n    addErrorListener(listener) {\n        this._listeners.push(listener);\n    }\n\n    removeErrorListeners() {\n        this._listeners = [];\n    }\n\n    getLiteralNames() {\n        return Object.getPrototypeOf(this).constructor.literalNames || [];\n    }\n\n    getSymbolicNames() {\n        return Object.getPrototypeOf(this).constructor.symbolicNames || [];\n    }\n\n    getTokenNames() {\n        if(!this.tokenNames) {\n            const literalNames = this.getLiteralNames();\n            const symbolicNames = this.getSymbolicNames();\n            const length = literalNames.length > symbolicNames.length ? literalNames.length : symbolicNames.length;\n            this.tokenNames = [];\n            for(let i=0; i<length; i++) {\n                this.tokenNames[i] = literalNames[i] || symbolicNames[i] || \"<INVALID\";\n            }\n        }\n        return this.tokenNames;\n    }\n\n    getTokenTypeMap() {\n        const tokenNames = this.getTokenNames();\n        if (tokenNames===null) {\n            throw(\"The current recognizer does not provide a list of token names.\");\n        }\n        let result = this.tokenTypeMapCache[tokenNames];\n        if(result===undefined) {\n            result = tokenNames.reduce(function(o, k, i) { o[k] = i; });\n            result.EOF = Token.EOF;\n            this.tokenTypeMapCache[tokenNames] = result;\n        }\n        return result;\n    }\n\n    /**\n     * Get a map from rule names to rule indexes.\n     * <p>Used for XPath and tree pattern compilation.</p>\n     */\n    getRuleIndexMap() {\n        const ruleNames = this.ruleNames;\n        if (ruleNames===null) {\n            throw(\"The current recognizer does not provide a list of rule names.\");\n        }\n        let result = this.ruleIndexMapCache[ruleNames]; // todo: should it be Recognizer.ruleIndexMapCache ?\n        if(result===undefined) {\n            result = ruleNames.reduce(function(o, k, i) { o[k] = i; });\n            this.ruleIndexMapCache[ruleNames] = result;\n        }\n        return result;\n    }\n\n    getTokenType(tokenName) {\n        const ttype = this.getTokenTypeMap()[tokenName];\n        if (ttype !==undefined) {\n            return ttype;\n        } else {\n            return Token.INVALID_TYPE;\n        }\n    }\n\n    // What is the error header, normally line/character position information?\n    getErrorHeader(e) {\n        const line = e.getOffendingToken().line;\n        const column = e.getOffendingToken().column;\n        return \"line \" + line + \":\" + column;\n    }\n\n    /**\n     * How should a token be displayed in an error message? The default\n     * is to display just the text, but during development you might\n     * want to have a lot of information spit out.  Override in that case\n     * to use t.toString() (which, for CommonToken, dumps everything about\n     * the token). This is better than forcing you to override a method in\n     * your token objects because you don't have to go modify your lexer\n     * so that it creates a new Java type.\n     *\n     * @deprecated This method is not called by the ANTLR 4 Runtime. Specific\n     * implementations of {@link ANTLRErrorStrategy} may provide a similar\n     * feature when necessary. For example, see\n     * {@link DefaultErrorStrategy//getTokenErrorDisplay}.*/\n    getTokenErrorDisplay(t) {\n        if (t===null) {\n            return \"<no token>\";\n        }\n        let s = t.text;\n        if (s===null) {\n            if (t.type===Token.EOF) {\n                s = \"<EOF>\";\n            } else {\n                s = \"<\" + t.type + \">\";\n            }\n        }\n        s = s.replace(\"\\n\",\"\\\\n\").replace(\"\\r\",\"\\\\r\").replace(\"\\t\",\"\\\\t\");\n        return \"'\" + s + \"'\";\n    }\n\n    /**\n     * @deprecated since ANTLR 4.13.2; use getErrorListener instead\n     */\n    getErrorListenerDispatch() {\n        console.warn(\"Calling deprecated method in Recognizer class: getErrorListenerDispatch()\");\n        return this.getErrorListener();\n    }\n\n    getErrorListener() {\n        return new ProxyErrorListener(this._listeners);\n    }\n\n    /**\n     * subclass needs to override these if there are sempreds or actions\n     * that the ATN interp needs to execute\n     */\n    sempred(localctx, ruleIndex, actionIndex) {\n        return true;\n    }\n\n    precpred(localctx , precedence) {\n        return true;\n    }\n\n    get atn() {\n        return this._interp.atn;\n    }\n\n    get state(){\n        return this._stateNumber;\n    }\n\n    set state(state) {\n        this._stateNumber = state;\n    }\n}\n\nRecognizer.tokenTypeMapCache = {};\nRecognizer.ruleIndexMapCache = {};\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Token.d.ts",
    "content": "import { TokenSource } from \"./TokenSource.js\";\nimport { CharStream } from \"./CharStream.js\";\n\nexport declare class Token {\n\n    static INVALID_TYPE: number;\n    static EOF: number;\n    static DEFAULT_CHANNEL: number;\n    static HIDDEN_CHANNEL: number;\n\n    tokenIndex: number;\n    line: number;\n    column: number;\n    channel: number;\n    text: string;\n    type: number;\n    start : number;\n    stop: number;\n\n    clone(): Token;\n    cloneWithType(type: number): Token;\n    getTokenSource(): TokenSource;\n    getInputStream(): CharStream;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/Token.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/**\n * A token has properties: text, type, line, character position in the line\n * (so we can ignore tabs), token channel, index, and source from which\n * we obtained this token.\n */\nexport default class Token {\n\n\tconstructor() {\n\t\tthis.source = null;\n\t\tthis.type = null; // token type of the token\n\t\tthis.channel = null; // The parser ignores everything not on DEFAULT_CHANNEL\n\t\tthis.start = null; // optional; return -1 if not implemented.\n\t\tthis.stop = null; // optional; return -1 if not implemented.\n\t\tthis.tokenIndex = null; // from 0..n-1 of the token object in the input stream\n\t\tthis.line = null; // line=1..n of the 1st character\n\t\tthis.column = null; // beginning of the line at which it occurs, 0..n-1\n\t\tthis._text = null; // text of the token.\n\t}\n\n\tgetTokenSource() {\n\t\treturn this.source[0];\n\t}\n\n\tgetInputStream() {\n\t\treturn this.source[1];\n\t}\n\n\tget text(){\n\t\treturn this._text;\n\t}\n\n\tset text(text) {\n\t\tthis._text = text;\n\t}\n}\n\nToken.INVALID_TYPE = 0;\n\n/**\n * During lookahead operations, this \"token\" signifies we hit rule end ATN state\n * and did not follow it despite needing to.\n */\nToken.EPSILON = -2;\n\nToken.MIN_USER_TOKEN_TYPE = 1;\n\nToken.EOF = -1;\n\n/**\n * All tokens go to the parser (unless skip() is called in that rule)\n * on a particular \"channel\". The parser tunes to a particular channel\n * so that whitespace etc... can go to the parser on a \"hidden\" channel.\n */\nToken.DEFAULT_CHANNEL = 0;\n\n/**\n * Anything on different channel than DEFAULT_CHANNEL is not parsed\n * by parser.\n */\nToken.HIDDEN_CHANNEL = 1;\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/TokenSource.d.ts",
    "content": "export declare class TokenSource {\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/TokenSource.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default class TokenSource {}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/TokenStream.d.ts",
    "content": "import {Interval} from \"./misc/index.js\";\nimport {Token} from \"./Token.js\";\n\nexport declare class TokenStream {\n\n    index: number;\n    size: number;\n\n    LA(i: number): number;\n    LT(k: number): Token;\n    getText(interval?: Interval): string;\n    // channelIndex can be retrieved using: lexer.channelNames().findIndex(channelName)\n    getHiddenTokensToLeft(tokenIndex: number, channelIndex?: number): Token[];\n    getHiddenTokensToRight(tokenIndex: number, channelIndex?: number): Token[];\n    get(idx: number): Token;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/TokenStream.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n// this is just to keep meaningful parameter types to Parser\nexport default class TokenStream {}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/TokenStreamRewriter.d.ts",
    "content": "import { CommonTokenStream } from \"./CommonTokenStream.js\";\nimport { Token } from \"./Token.js\";\nimport { Interval } from \"./misc/Interval.js\";\n\ntype Rewrites = Array<RewriteOperation | undefined>;\ntype Text = unknown;\n\nexport declare class TokenStreamRewriter {\n    static DEFAULT_PROGRAM_NAME: string;\n    constructor(tokens: CommonTokenStream);\n    getTokenStream(): CommonTokenStream;\n    insertAfter(token: Token, text: Text, programName?: string): void;\n    insertAfter(index: number, text: Text, programName?: string): void;\n    insertBefore(token: Token, text: Text, programName?: string): void;\n    insertBefore(index: number, text: Text, programName?: string): void;\n    replaceSingle(token: Token, text: Text, programName?: string): void;\n    replaceSingle(index: number, text: Text, programName?: string): void;\n    replace(from: Token | number, to: Token | number, text: Text, programName?: string): void;\n    delete(from: number | Token, to: number | Token, programName?: string): void;\n    getProgram(name: string): Rewrites;\n    initializeProgram(name: string): Rewrites;\n    getText(): string;\n    getText(program: string): string;\n    getText(interval: Interval, programName?: string): string;\n    reduceToSingleOperationPerIndex(rewrites: Rewrites): Map<number, RewriteOperation>;\n    catOpText(a: Text, b: Text): string;\n    getKindOfOps(rewrites: Rewrites, kind: any, before: number): RewriteOperation[];\n}\n\n\ndeclare class RewriteOperation {\n    constructor(tokens: CommonTokenStream, index: number, instructionIndex: number, text: Text);\n    tokens: CommonTokenStream;\n    instructionIndex: number;\n    index: number;\n    text: Text;\n    toString(): string;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/TokenStreamRewriter.js",
    "content": "import Token from \"./Token.js\";\nimport Interval from \"./misc/Interval.js\";\n\n/**\n * @typedef {import(\"./CommonTokenStream\").default} CommonTokenStream\n * @typedef {Array<RewriteOperation | undefined>} Rewrites\n * @typedef {unknown} Text\n */\n\nexport default class TokenStreamRewriter {\n    // eslint-disable-next-line no-undef\n    static DEFAULT_PROGRAM_NAME = \"default\";\n\n    /**\n     * @param {CommonTokenStream} tokens The token stream to modify\n     */\n    constructor(tokens) {\n        this.tokens = tokens;\n        /** @type {Map<string, Rewrites>} */\n        this.programs = new Map();\n    }\n\n    /**\n     * @returns {CommonTokenStream}\n     */\n    getTokenStream() {\n        return this.tokens;\n    }\n\n    /**\n     * Insert the supplied text after the specified token (or token index)\n     * @param {Token | number} tokenOrIndex\n     * @param {Text} text\n     * @param {string} [programName]\n     */\n    insertAfter(tokenOrIndex, text, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) {\n        /** @type {number} */\n        let index;\n        if (typeof tokenOrIndex === \"number\") {\n            index = tokenOrIndex;\n        } else {\n            index = tokenOrIndex.tokenIndex;\n        }\n\n        // to insert after, just insert before next index (even if past end)\n        let rewrites = this.getProgram(programName);\n        let op = new InsertAfterOp(this.tokens, index, rewrites.length, text);\n        rewrites.push(op);\n    }\n\n    /**\n     * Insert the supplied text before the specified token (or token index)\n     * @param {Token | number} tokenOrIndex\n     * @param {Text} text\n     * @param {string} [programName]\n     */\n    insertBefore(tokenOrIndex, text, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) {\n        /** @type {number} */\n        let index;\n        if (typeof tokenOrIndex === \"number\") {\n            index = tokenOrIndex;\n        } else {\n            index = tokenOrIndex.tokenIndex;\n        }\n\n        const rewrites = this.getProgram(programName);\n        const op = new InsertBeforeOp(this.tokens, index, rewrites.length, text);\n        rewrites.push(op);\n    }\n\n    /**\n     * Replace the specified token with the supplied text\n     * @param {Token | number} tokenOrIndex\n     * @param {Text} text\n     * @param {string} [programName]\n     */\n    replaceSingle(tokenOrIndex, text, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) {\n        this.replace(tokenOrIndex, tokenOrIndex, text, programName);\n    }\n\n    /**\n     * Replace the specified range of tokens with the supplied text\n     * @param {Token | number} from\n     * @param {Token | number} to\n     * @param {Text} text\n     * @param {string} [programName]\n     */\n    replace(from, to, text, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) {\n        if (typeof from !== \"number\") {\n            from = from.tokenIndex;\n        }\n        if (typeof to !== \"number\") {\n            to = to.tokenIndex;\n        }\n        if (from > to || from < 0 || to < 0 || to >= this.tokens.size) {\n            throw new RangeError(`replace: range invalid: ${from}..${to}(size=${this.tokens.size})`);\n        }\n        let rewrites = this.getProgram(programName);\n        let op = new ReplaceOp(this.tokens, from, to, rewrites.length, text);\n        rewrites.push(op);\n    }\n\n    /**\n     * Delete the specified range of tokens\n     * @param {number | Token} from\n     * @param {number | Token} to\n     * @param {string} [programName]\n     */\n    delete(from, to, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) {\n        if (typeof to === \"undefined\") {\n            to = from;\n        }\n        this.replace(from, to, null, programName);\n    }\n\n    /**\n     * @param {string} name\n     * @returns {Rewrites}\n     */\n    getProgram(name) {\n        let is = this.programs.get(name);\n        if (is == null) {\n            is = this.initializeProgram(name);\n        }\n        return is;\n    }\n\n    /**\n     * @param {string} name\n     * @returns {Rewrites}\n     */\n    initializeProgram(name) {\n        const is = [];\n        this.programs.set(name, is);\n        return is;\n    }\n\n    /**\n     * Return the text from the original tokens altered per the instructions given to this rewriter\n     * @param {Interval | string} [intervalOrProgram]\n     * @param {string} [programName]\n     * @returns {string}\n     */\n    getText(intervalOrProgram, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) {\n        let interval;\n        if (intervalOrProgram instanceof Interval) {\n            interval = intervalOrProgram;\n        } else {\n            interval = new Interval(0, this.tokens.size - 1);\n        }\n\n        if (typeof intervalOrProgram === \"string\") {\n            programName = intervalOrProgram;\n        }\n\n        const rewrites = this.programs.get(programName);\n        let start = interval.start;\n        let stop = interval.stop;\n\n        // ensure start/end are in range\n        if (stop > this.tokens.size - 1) {\n            stop = this.tokens.size - 1;\n        }\n        if (start < 0) {\n            start = 0;\n        }\n\n        if (rewrites == null || rewrites.length === 0) {\n            return this.tokens.getText(new Interval(start, stop)); // no instructions to execute\n        }\n\n        let buf = [];\n\n        // First, optimize instruction stream\n        let indexToOp = this.reduceToSingleOperationPerIndex(rewrites);\n\n        // Walk buffer, executing instructions and emitting tokens\n        let i = start;\n        while (i <= stop && i < this.tokens.size) {\n            let op = indexToOp.get(i);\n            indexToOp.delete(i); // remove so any left have index size-1\n            let t = this.tokens.get(i);\n            if (op == null) {\n                // no operation at that index, just dump token\n                if (t.type !== Token.EOF) {\n                    buf.push(String(t.text));\n                }\n                i++; // move to next token\n            }\n            else {\n                i = op.execute(buf); // execute operation and skip\n            }\n        }\n\n        // include stuff after end if it's last index in buffer\n        // So, if they did an insertAfter(lastValidIndex, \"foo\"), include\n        // foo if end==lastValidIndex.\n        if (stop === this.tokens.size - 1) {\n            // Scan any remaining operations after last token\n            // should be included (they will be inserts).\n            for (const op of indexToOp.values()) {\n                if (op.index >= this.tokens.size - 1) {\n                    buf.push(op.text.toString());\n                }\n            }\n        }\n\n        return buf.join(\"\");\n    }\n\n    /**\n     * @param {Rewrites} rewrites\n     * @returns {Map<number, RewriteOperation>} a map from token index to operation\n     */\n    reduceToSingleOperationPerIndex(rewrites) {\n        // WALK REPLACES\n        for (let i = 0; i < rewrites.length; i++) {\n            let op = rewrites[i];\n            if (op == null) {\n                continue;\n            }\n            if (!(op instanceof ReplaceOp)) {\n                continue;\n            }\n            let rop = op;\n            // Wipe prior inserts within range\n            let inserts = this.getKindOfOps(rewrites, InsertBeforeOp, i);\n            for (let iop of inserts) {\n                if (iop.index === rop.index) {\n                    // E.g., insert before 2, delete 2..2; update replace\n                    // text to include insert before, kill insert\n                    rewrites[iop.instructionIndex] = undefined;\n                    rop.text = iop.text.toString() + (rop.text != null ? rop.text.toString() : \"\");\n                }\n                else if (iop.index > rop.index && iop.index <= rop.lastIndex) {\n                    // delete insert as it's a no-op.\n                    rewrites[iop.instructionIndex] = undefined;\n                }\n            }\n            // Drop any prior replaces contained within\n            let prevReplaces = this.getKindOfOps(rewrites, ReplaceOp, i);\n            for (let prevRop of prevReplaces) {\n                if (prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex) {\n                    // delete replace as it's a no-op.\n                    rewrites[prevRop.instructionIndex] = undefined;\n                    continue;\n                }\n                // throw exception unless disjoint or identical\n                let disjoint =\n                    prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex;\n                // Delete special case of replace (text==null):\n                // D.i-j.u D.x-y.v\t| boundaries overlap\tcombine to max(min)..max(right)\n                if (prevRop.text == null && rop.text == null && !disjoint) {\n                    rewrites[prevRop.instructionIndex] = undefined; // kill first delete\n                    rop.index = Math.min(prevRop.index, rop.index);\n                    rop.lastIndex = Math.max(prevRop.lastIndex, rop.lastIndex);\n                }\n                else if (!disjoint) {\n                    throw new Error(`replace op boundaries of ${rop} overlap with previous ${prevRop}`);\n                }\n            }\n        }\n\n        // WALK INSERTS\n        for (let i = 0; i < rewrites.length; i++) {\n            let op = rewrites[i];\n            if (op == null) {\n                continue;\n            }\n            if (!(op instanceof InsertBeforeOp)) {\n                continue;\n            }\n            let iop = op;\n            // combine current insert with prior if any at same index\n            let prevInserts = this.getKindOfOps(rewrites, InsertBeforeOp, i);\n            for (let prevIop of prevInserts) {\n                if (prevIop.index === iop.index) {\n                    if (prevIop instanceof InsertAfterOp) {\n                        iop.text = this.catOpText(prevIop.text, iop.text);\n                        rewrites[prevIop.instructionIndex] = undefined;\n                    }\n                    else if (prevIop instanceof InsertBeforeOp) { // combine objects\n                        // convert to strings...we're in process of toString'ing\n                        // whole token buffer so no lazy eval issue with any templates\n                        iop.text = this.catOpText(iop.text, prevIop.text);\n                        // delete redundant prior insert\n                        rewrites[prevIop.instructionIndex] = undefined;\n                    }\n                }\n            }\n            // look for replaces where iop.index is in range; error\n            let prevReplaces = this.getKindOfOps(rewrites, ReplaceOp, i);\n            for (let rop of prevReplaces) {\n                if (iop.index === rop.index) {\n                    rop.text = this.catOpText(iop.text, rop.text);\n                    rewrites[i] = undefined;\t// delete current insert\n                    continue;\n                }\n                if (iop.index >= rop.index && iop.index <= rop.lastIndex) {\n                    throw new Error(`insert op ${iop} within boundaries of previous ${rop}`);\n                }\n            }\n        }\n\n        /** @type {Map<number, RewriteOperation>} */\n        let m = new Map();\n        for (let op of rewrites) {\n            if (op == null) {\n                // ignore deleted ops\n                continue;\n            }\n            if (m.get(op.index) != null) {\n                throw new Error(\"should only be one op per index\");\n            }\n            m.set(op.index, op);\n        }\n        return m;\n    }\n\n    /**\n     * @param {Text} a\n     * @param {Text} b\n     * @returns {string}\n     */\n    catOpText(a, b) {\n        let x = \"\";\n        let y = \"\";\n        if (a != null) {\n            x = a.toString();\n        }\n        if (b != null) {\n            y = b.toString();\n        }\n        return x + y;\n    }\n\n    /**\n     * Get all operations before an index of a particular kind\n     * @param {Rewrites} rewrites\n     * @param {any} kind\n     * @param {number} before\n     */\n    getKindOfOps(rewrites, kind, before) {\n        return rewrites.slice(0, before).filter(op => op && op instanceof kind);\n    }\n}\n\nclass RewriteOperation {\n    /**\n     * @param {CommonTokenStream} tokens\n     * @param {number} index\n     * @param {number} instructionIndex\n     * @param {Text} text\n     */\n    constructor(tokens, index, instructionIndex, text) {\n        this.tokens = tokens;\n        this.instructionIndex = instructionIndex;\n        this.index = index;\n        this.text = text === undefined ? \"\" : text;\n    }\n\n    toString() {\n        let opName = this.constructor.name;\n        const $index = opName.indexOf(\"$\");\n        opName = opName.substring($index + 1, opName.length);\n        return \"<\" + opName + \"@\" + this.tokens.get(this.index) +\n            \":\\\"\" + this.text + \"\\\">\";\n    }\n}\n\nclass InsertBeforeOp extends RewriteOperation {\n    /**\n     * @param {CommonTokenStream} tokens\n     * @param {number} index\n     * @param {number} instructionIndex\n     * @param {Text} text\n     */\n    constructor(tokens, index, instructionIndex, text) {\n        super(tokens, index, instructionIndex, text);\n    }\n\n    /**\n     * @param {string[]} buf\n     * @returns {number} the index of the next token to operate on\n     */\n    execute(buf) {\n        if (this.text) {\n            buf.push(this.text.toString());\n        }\n        \n        if (this.tokens.get(this.index).type !== Token.EOF) {\n            buf.push(String(this.tokens.get(this.index).text));\n        }\n        return this.index + 1;\n    }\n}\n\nclass InsertAfterOp extends InsertBeforeOp {\n    /**\n     * @param {CommonTokenStream} tokens\n     * @param {number} index\n     * @param {number} instructionIndex\n     * @param {Text} text\n     */\n    constructor(tokens, index, instructionIndex, text) {\n        super(tokens, index + 1, instructionIndex, text); // insert after is insert before index+1\n    }\n}\n\nclass ReplaceOp extends RewriteOperation {\n    /**\n     * @param {CommonTokenStream} tokens\n     * @param {number} from\n     * @param {number} to\n     * @param {number} instructionIndex\n     * @param {Text} text\n     */\n    constructor(tokens, from, to, instructionIndex, text) {\n        super(tokens, from, instructionIndex, text);\n        this.lastIndex = to;\n    }\n\n    /**\n     * @param {string[]} buf\n     * @returns {number} the index of the next token to operate on\n     */\n    execute(buf) {\n        if (this.text) {\n            buf.push(this.text.toString());\n        }\n        return this.lastIndex + 1;\n    }\n\n    toString() {\n        if (this.text == null) {\n            return \"<DeleteOp@\" + this.tokens.get(this.index) +\n                \"..\" + this.tokens.get(this.lastIndex) + \">\";\n        }\n        return \"<ReplaceOp@\" + this.tokens.get(this.index) +\n            \"..\" + this.tokens.get(this.lastIndex) + \":\\\"\" + this.text + \"\\\">\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/TraceListener.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ParseTreeListener from \"./tree/ParseTreeListener.js\";\n\nexport default class TraceListener extends ParseTreeListener {\n    constructor(parser) {\n        super();\n        this.parser = parser;\n    }\n\n    enterEveryRule(ctx) {\n        console.log(\"enter   \" + this.parser.ruleNames[ctx.ruleIndex] + \", LT(1)=\" + this.parser._input.LT(1).text);\n    }\n\n    visitTerminal(node) {\n        console.log(\"consume \" + node.symbol + \" rule \" + this.parser.ruleNames[this.parser._ctx.ruleIndex]);\n    }\n\n    exitEveryRule(ctx) {\n        console.log(\"exit    \" + this.parser.ruleNames[ctx.ruleIndex] + \", LT(1)=\" + this.parser._input.LT(1).text);\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport HashCode from \"../misc/HashCode.js\";\n\n/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\nexport default class LexerAction {\n    constructor(action) {\n        this.actionType = action;\n        this.isPositionDependent = false;\n    }\n\n    hashCode() {\n        const hash = new HashCode();\n        this.updateHashCode(hash);\n        return hash.finish()\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.actionType);\n    }\n\n    equals(other) {\n        return this === other;\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerChannelAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Implements the {@code channel} lexer action by calling\n * {@link Lexer//setChannel} with the assigned channel.\n * Constructs a new {@code channel} action with the specified channel value.\n * @param channel The channel value to pass to {@link Lexer//setChannel}\n */\nexport default class LexerChannelAction extends LexerAction {\n    constructor(channel) {\n        super(LexerActionType.CHANNEL);\n        this.channel = channel;\n    }\n\n    /**\n     * <p>This action is implemented by calling {@link Lexer//setChannel} with the\n     * value provided by {@link //getChannel}.</p>\n     */\n    execute(lexer) {\n        lexer._channel = this.channel;\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.actionType, this.channel);\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (! (other instanceof LexerChannelAction)) {\n            return false;\n        } else {\n            return this.channel === other.channel;\n        }\n    }\n\n    toString() {\n        return \"channel(\" + this.channel + \")\";\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerCustomAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Executes a custom lexer action by calling {@link Recognizer//action} with the\n * rule and action indexes assigned to the custom action. The implementation of\n * a custom action is added to the generated code for the lexer in an override\n * of {@link Recognizer//action} when the grammar is compiled.\n *\n * <p>This class may represent embedded actions created with the <code>{...}</code>\n * syntax in ANTLR 4, as well as actions created for lexer commands where the\n * command argument could not be evaluated when the grammar was compiled.</p>\n */\nexport default class LexerCustomAction extends LexerAction {\n    /**\n     * Constructs a custom lexer action with the specified rule and action\n     * indexes.\n     *\n     * @param ruleIndex The rule index to use for calls to\n     * {@link Recognizer//action}.\n     * @param actionIndex The action index to use for calls to\n     * {@link Recognizer//action}.\n     */\n    constructor(ruleIndex, actionIndex) {\n        super(LexerActionType.CUSTOM);\n        this.ruleIndex = ruleIndex;\n        this.actionIndex = actionIndex;\n        this.isPositionDependent = true;\n    }\n\n    /**\n     * <p>Custom actions are implemented by calling {@link Lexer//action} with the\n     * appropriate rule and action indexes.</p>\n     */\n    execute(lexer) {\n        lexer.action(null, this.ruleIndex, this.actionIndex);\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.actionType, this.ruleIndex, this.actionIndex);\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (! (other instanceof LexerCustomAction)) {\n            return false;\n        } else {\n            return this.ruleIndex === other.ruleIndex && this.actionIndex === other.actionIndex;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerIndexedCustomAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n/**\n * This implementation of {@link LexerAction} is used for tracking input offsets\n * for position-dependent actions within a {@link LexerActionExecutor}.\n *\n * <p>This action is not serialized as part of the ATN, and is only required for\n * position-dependent lexer actions which appear at a location other than the\n * end of a rule. For more information about DFA optimizations employed for\n * lexer actions, see {@link LexerActionExecutor//append} and\n * {@link LexerActionExecutor//fixOffsetBeforeMatch}.</p>\n *\n * Constructs a new indexed custom action by associating a character offset\n * with a {@link LexerAction}.\n *\n * <p>Note: This class is only required for lexer actions for which\n * {@link LexerAction//isPositionDependent} returns {@code true}.</p>\n *\n * @param offset The offset into the input {@link CharStream}, relative to\n * the token start index, at which the specified lexer action should be\n * executed.\n * @param action The lexer action to execute at a particular offset in the\n * input {@link CharStream}.\n */\nimport LexerAction from \"./LexerAction.js\";\n\n\nexport default class LexerIndexedCustomAction extends LexerAction {\n    constructor(offset, action) {\n        super(action.actionType);\n        this.offset = offset;\n        this.action = action;\n        this.isPositionDependent = true;\n    }\n\n    /**\n     * <p>This method calls {@link //execute} on the result of {@link //getAction}\n     * using the provided {@code lexer}.</p>\n     */\n    execute(lexer) {\n        // assume the input stream position was properly set by the calling code\n        this.action.execute(lexer);\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.actionType, this.offset, this.action);\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (! (other instanceof LexerIndexedCustomAction)) {\n            return false;\n        } else {\n            return this.offset === other.offset && this.action === other.action;\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerModeAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Implements the {@code mode} lexer action by calling {@link Lexer//mode} with\n * the assigned mode\n */\nexport default class LexerModeAction extends LexerAction {\n    constructor(mode) {\n        super(LexerActionType.MODE);\n        this.mode = mode;\n    }\n\n    /**\n     * <p>This action is implemented by calling {@link Lexer//mode} with the\n     * value provided by {@link //getMode}.</p>\n     */\n    execute(lexer) {\n        lexer.setMode(this.mode);\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.actionType, this.mode);\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (! (other instanceof LexerModeAction)) {\n            return false;\n        } else {\n            return this.mode === other.mode;\n        }\n    }\n\n    toString() {\n        return \"mode(\" + this.mode + \")\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerMoreAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Implements the {@code more} lexer action by calling {@link Lexer//more}.\n *\n * <p>The {@code more} command does not have any parameters, so this action is\n * implemented as a singleton instance exposed by {@link //INSTANCE}.</p>\n */\nexport default class LexerMoreAction extends LexerAction {\n    constructor() {\n        super(LexerActionType.MORE);\n    }\n\n    /**\n     * <p>This action is implemented by calling {@link Lexer//popMode}.</p>\n     */\n    execute(lexer) {\n        lexer.more();\n    }\n\n    toString() {\n        return \"more\";\n    }\n}\n\nLexerMoreAction.INSTANCE = new LexerMoreAction();\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerPopModeAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Implements the {@code popMode} lexer action by calling {@link Lexer//popMode}.\n *\n * <p>The {@code popMode} command does not have any parameters, so this action is\n * implemented as a singleton instance exposed by {@link //INSTANCE}.</p>\n */\nexport default class LexerPopModeAction extends LexerAction {\n    constructor() {\n        super(LexerActionType.POP_MODE);\n    }\n\n    /**\n     * <p>This action is implemented by calling {@link Lexer//popMode}.</p>\n     */\n    execute(lexer) {\n        lexer.popMode();\n    }\n\n    toString() {\n        return \"popMode\";\n    }\n}\n\nLexerPopModeAction.INSTANCE = new LexerPopModeAction();\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerPushModeAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Implements the {@code pushMode} lexer action by calling\n * {@link Lexer//pushMode} with the assigned mode\n */\nexport default class LexerPushModeAction extends LexerAction {\n    constructor(mode) {\n        super(LexerActionType.PUSH_MODE);\n        this.mode = mode;\n    }\n\n    /**\n     * <p>This action is implemented by calling {@link Lexer//pushMode} with the\n     * value provided by {@link //getMode}.</p>\n     */\n    execute(lexer) {\n        lexer.pushMode(this.mode);\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.actionType, this.mode);\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (! (other instanceof LexerPushModeAction)) {\n            return false;\n        } else {\n            return this.mode === other.mode;\n        }\n    }\n\n    toString() {\n        return \"pushMode(\" + this.mode + \")\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerSkipAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Implements the {@code skip} lexer action by calling {@link Lexer//skip}.\n *\n * <p>The {@code skip} command does not have any parameters, so this action is\n * implemented as a singleton instance exposed by {@link //INSTANCE}.</p>\n */\nexport default class LexerSkipAction extends LexerAction {\n    constructor() {\n        super(LexerActionType.SKIP);\n    }\n\n    execute(lexer) {\n        lexer.skip();\n    }\n\n    toString() {\n        return \"skip\";\n    }\n}\n\n// Provides a singleton instance of this parameterless lexer action.\nLexerSkipAction.INSTANCE = new LexerSkipAction();\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/action/LexerTypeAction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport {default as LexerActionType } from \"../atn/LexerActionType.js\";\nimport LexerAction from \"./LexerAction.js\";\n\n/**\n * Implements the {@code type} lexer action by calling {@link Lexer//setType}\n * with the assigned type\n */\n\nexport default class LexerTypeAction extends LexerAction {\n    constructor(type) {\n        super(LexerActionType.TYPE);\n        this.type = type;\n    }\n\n    execute(lexer) {\n        lexer.type = this.type;\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.actionType, this.type);\n    }\n\n    equals(other) {\n        if(this === other) {\n            return true;\n        } else if (! (other instanceof LexerTypeAction)) {\n            return false;\n        } else {\n            return this.type === other.type;\n        }\n    }\n\n    toString() {\n        return \"type(\" + this.type + \")\";\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATN.d.ts",
    "content": "import {IntervalSet} from \"../misc/index.js\";\nimport {RuleContext} from \"../context/index.js\";\nimport {ATNState, DecisionState, RuleStartState, RuleStopState} from \"../state.js\";\n\nexport declare class ATN {\n\n    static INVALID_ALT_NUMBER: number;\n\n    states: ATNState[];\n    decisionToState: DecisionState[];\n    ruleToStartState: RuleStartState[];\n    ruleToStopState: RuleStopState[];\n\n    getExpectedTokens(stateNumber: number, ctx: RuleContext ): IntervalSet;\n    nextTokens(atnState: ATNState, ctx?: RuleContext): IntervalSet;\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATN.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport LL1Analyzer from './LL1Analyzer.js';\nimport IntervalSet from '../misc/IntervalSet.js';\nimport Token from '../Token.js';\n\nexport default class ATN {\n\n    constructor(grammarType , maxTokenType) {\n        /**\n         * Used for runtime deserialization of ATNs from strings\n         * The type of the ATN.\n        */\n        this.grammarType = grammarType;\n        // The maximum value for any symbol recognized by a transition in the ATN.\n        this.maxTokenType = maxTokenType;\n        this.states = [];\n        /**\n         * Each subrule/rule is a decision point and we must track them so we\n         * can go back later and build DFA predictors for them.  This includes\n         * all the rules, subrules, optional blocks, ()+, ()* etc...\n         */\n        this.decisionToState = [];\n        // Maps from rule index to starting state number.\n        this.ruleToStartState = [];\n        // Maps from rule index to stop state number.\n        this.ruleToStopState = null;\n        this.modeNameToStartState = {};\n        /**\n         * For lexer ATNs, this maps the rule index to the resulting token type.\n         * For parser ATNs, this maps the rule index to the generated bypass token\n         * type if the {@link ATNDeserializationOptions//isGenerateRuleBypassTransitions}\n         * deserialization option was specified; otherwise, this is {@code null}\n         */\n        this.ruleToTokenType = null;\n        /**\n         * For lexer ATNs, this is an array of {@link LexerAction} objects which may\n         * be referenced by action transitions in the ATN\n         */\n        this.lexerActions = null;\n        this.modeToStartState = [];\n    }\n\n    /**\n     * Compute the set of valid tokens that can occur starting in state {@code s}.\n     * If {@code ctx} is null, the set of tokens will not include what can follow\n     * the rule surrounding {@code s}. In other words, the set will be\n     * restricted to tokens reachable staying within {@code s}'s rule\n     */\n    nextTokensInContext(s, ctx) {\n        const anal = new LL1Analyzer(this);\n        return anal.LOOK(s, null, ctx);\n    }\n\n    /**\n     * Compute the set of valid tokens that can occur starting in {@code s} and\n     * staying in same rule. {@link Token//EPSILON} is in set if we reach end of\n     * rule\n     */\n    nextTokensNoContext(s) {\n        if (s.nextTokenWithinRule !== null ) {\n            return s.nextTokenWithinRule;\n        }\n        s.nextTokenWithinRule = this.nextTokensInContext(s, null);\n        s.nextTokenWithinRule.readOnly = true;\n        return s.nextTokenWithinRule;\n    }\n\n    nextTokens(s, ctx) {\n        if ( ctx===undefined ) {\n            return this.nextTokensNoContext(s);\n        } else {\n            return this.nextTokensInContext(s, ctx);\n        }\n    }\n\n    addState(state) {\n        if ( state !== null ) {\n            state.atn = this;\n            state.stateNumber = this.states.length;\n        }\n        this.states.push(state);\n    }\n\n    removeState(state) {\n        this.states[state.stateNumber] = null; // just free mem, don't shift states in list\n    }\n\n    defineDecisionState(s) {\n        this.decisionToState.push(s);\n        s.decision = this.decisionToState.length-1;\n        return s.decision;\n    }\n\n    getDecisionState(decision) {\n        if (this.decisionToState.length===0) {\n            return null;\n        } else {\n            return this.decisionToState[decision];\n        }\n    }\n\n    /**\n     * Computes the set of input symbols which could follow ATN state number\n     * {@code stateNumber} in the specified full {@code context}. This method\n     * considers the complete parser context, but does not evaluate semantic\n     * predicates (i.e. all predicates encountered during the calculation are\n     * assumed true). If a path in the ATN exists from the starting state to the\n     * {@link RuleStopState} of the outermost context without matching any\n     * symbols, {@link Token//EOF} is added to the returned set.\n     *\n     * <p>If {@code context} is {@code null}, it is treated as\n     * {@link ParserRuleContext//EMPTY}.</p>\n     *\n     * @param stateNumber the ATN state number\n     * @param ctx the full parse context\n     *\n     * @return {IntervalSet} The set of potentially valid input symbols which could follow the\n     * specified state in the specified context.\n     *\n     * @throws IllegalArgumentException if the ATN does not contain a state with\n     * number {@code stateNumber}\n     */\n    getExpectedTokens(stateNumber, ctx ) {\n        if ( stateNumber < 0 || stateNumber >= this.states.length ) {\n            throw(\"Invalid state number.\");\n        }\n        const s = this.states[stateNumber];\n        let following = this.nextTokens(s);\n        if (!following.contains(Token.EPSILON)) {\n            return following;\n        }\n        const expected = new IntervalSet();\n        expected.addSet(following);\n        expected.removeOne(Token.EPSILON);\n        while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {\n            const invokingState = this.states[ctx.invokingState];\n            const rt = invokingState.transitions[0];\n            following = this.nextTokens(rt.followState);\n            expected.addSet(following);\n            expected.removeOne(Token.EPSILON);\n            ctx = ctx.parentCtx;\n        }\n        if (following.contains(Token.EPSILON)) {\n            expected.addOne(Token.EOF);\n        }\n        return expected;\n    }\n}\n\nATN.INVALID_ALT_NUMBER = 0;\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNConfig.d.ts",
    "content": "import { ATNState } from \"../state/index.js\";\n\nexport declare class ATNConfig {\n    state: ATNState;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNConfig.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport SemanticContext from './SemanticContext.js';\nimport HashCode from \"../misc/HashCode.js\";\n\nfunction checkParams(params, isCfg) {\n\tif(params===null) {\n\t\tconst result = { state:null, alt:null, context:null, semanticContext:null };\n\t\tif(isCfg) {\n\t\t\tresult.reachesIntoOuterContext = 0;\n\t\t}\n\t\treturn result;\n\t} else {\n\t\tconst props = {};\n\t\tprops.state = params.state || null;\n\t\tprops.alt = (params.alt === undefined) ? null : params.alt;\n\t\tprops.context = params.context || null;\n\t\tprops.semanticContext = params.semanticContext || null;\n\t\tif(isCfg) {\n\t\t\tprops.reachesIntoOuterContext = params.reachesIntoOuterContext || 0;\n\t\t\tprops.precedenceFilterSuppressed = params.precedenceFilterSuppressed || false;\n\t\t}\n\t\treturn props;\n\t}\n}\n\nexport default class ATNConfig {\n    /**\n     * @param {Object} params A tuple: (ATN state, predicted alt, syntactic, semantic context).\n     * The syntactic context is a graph-structured stack node whose\n     * path(s) to the root is the rule invocation(s)\n     * chain used to arrive at the state.  The semantic context is\n     * the tree of semantic predicates encountered before reaching\n     * an ATN state\n     */\n    constructor(params, config) {\n        this.checkContext(params, config);\n        params = checkParams(params);\n        config = checkParams(config, true);\n        // The ATN state associated with this configuration///\n        this.state = params.state!==null ? params.state : config.state;\n        // What alt (or lexer rule) is predicted by this configuration///\n        this.alt = params.alt!==null ? params.alt : config.alt;\n        /**\n         * The stack of invoking states leading to the rule/states associated\n         * with this config.  We track only those contexts pushed during\n         * execution of the ATN simulator\n         */\n        this.context = params.context!==null ? params.context : config.context;\n        this.semanticContext = params.semanticContext!==null ? params.semanticContext :\n            (config.semanticContext!==null ? config.semanticContext : SemanticContext.NONE);\n        // TODO: make it a boolean then\n        /**\n         * We cannot execute predicates dependent upon local context unless\n         * we know for sure we are in the correct context. Because there is\n         * no way to do this efficiently, we simply cannot evaluate\n         * dependent predicates unless we are in the rule that initially\n         * invokes the ATN simulator.\n         * closure() tracks the depth of how far we dip into the\n         * outer context: depth &gt; 0.  Note that it may not be totally\n         * accurate depth since I don't ever decrement\n         */\n        this.reachesIntoOuterContext = config.reachesIntoOuterContext;\n        this.precedenceFilterSuppressed = config.precedenceFilterSuppressed;\n    }\n\n    checkContext(params, config) {\n        if((params.context===null || params.context===undefined) &&\n                (config===null || config.context===null || config.context===undefined)) {\n            this.context = null;\n        }\n    }\n\n    hashCode() {\n        const hash = new HashCode();\n        this.updateHashCode(hash);\n        return hash.finish();\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext);\n    }\n\n    /**\n     * An ATN configuration is equal to another if both have\n     * the same state, they predict the same alternative, and\n     * syntactic/semantic contexts are the same\n     */\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (! (other instanceof ATNConfig)) {\n            return false;\n        } else {\n            return this.state.stateNumber===other.state.stateNumber &&\n                this.alt===other.alt &&\n                (this.context===null ? other.context===null : this.context.equals(other.context)) &&\n                this.semanticContext.equals(other.semanticContext) &&\n                this.precedenceFilterSuppressed===other.precedenceFilterSuppressed;\n        }\n    }\n\n    hashCodeForConfigSet() {\n        const hash = new HashCode();\n        hash.update(this.state.stateNumber, this.alt, this.semanticContext);\n        return hash.finish();\n    }\n\n    equalsForConfigSet(other) {\n        if (this === other) {\n            return true;\n        } else if (! (other instanceof ATNConfig)) {\n            return false;\n        } else {\n            return this.state.stateNumber===other.state.stateNumber &&\n                this.alt===other.alt &&\n                this.semanticContext.equals(other.semanticContext);\n        }\n    }\n\n    toString() {\n        return \"(\" + this.state + \",\" + this.alt +\n            (this.context!==null ? \",[\" + this.context.toString() + \"]\" : \"\") +\n            (this.semanticContext !== SemanticContext.NONE ?\n                    (\",\" + this.semanticContext.toString())\n                    : \"\") +\n            (this.reachesIntoOuterContext>0 ?\n                    (\",up=\" + this.reachesIntoOuterContext)\n                    : \"\") + \")\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNConfigSet.d.ts",
    "content": "import {ATNConfig} from \"./ATNConfig.js\";\n\nexport declare class ATNConfigSet {\n    configs: ATNConfig[];\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNConfigSet.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport ATN from './ATN.js';\nimport SemanticContext from './SemanticContext.js';\nimport { merge } from '../context/PredictionContextUtils.js';\nimport arrayToString from \"../utils/arrayToString.js\";\nimport HashSet from \"../misc/HashSet.js\";\nimport equalArrays from \"../utils/equalArrays.js\";\nimport HashCode from \"../misc/HashCode.js\";\n\nfunction hashATNConfig(c) {\n\treturn c.hashCodeForConfigSet();\n}\n\nfunction equalATNConfigs(a, b) {\n\tif ( a===b ) {\n\t\treturn true;\n\t} else if ( a===null || b===null ) {\n\t\treturn false;\n\t} else\n       return a.equalsForConfigSet(b);\n }\n\n/**\n * Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track\n * info about the set, with support for combining similar configurations using a\n * graph-structured stack\n */\nexport default class ATNConfigSet {\n\tconstructor(fullCtx) {\n\t\t/**\n\t\t * The reason that we need this is because we don't want the hash map to use\n\t\t * the standard hash code and equals. We need all configurations with the\n\t\t * same\n\t\t * {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively\n\t\t * doubles\n\t\t * the number of objects associated with ATNConfigs. The other solution is\n\t\t * to\n\t\t * use a hash table that lets us specify the equals/hashcode operation.\n\t\t * All configs but hashed by (s, i, _, pi) not including context. Wiped out\n\t\t * when we go readonly as this set becomes a DFA state\n\t\t */\n\t\tthis.configLookup = new HashSet(hashATNConfig, equalATNConfigs);\n\t\t/**\n\t\t * Indicates that this configuration set is part of a full context\n\t\t * LL prediction. It will be used to determine how to merge $. With SLL\n\t\t * it's a wildcard whereas it is not for LL context merge\n\t\t */\n\t\tthis.fullCtx = fullCtx === undefined ? true : fullCtx;\n\t\t/**\n\t\t * Indicates that the set of configurations is read-only. Do not\n\t\t * allow any code to manipulate the set; DFA states will point at\n\t\t * the sets and they must not change. This does not protect the other\n\t\t * fields; in particular, conflictingAlts is set after\n\t\t * we've made this readonly\n\t\t */\n\t\tthis.readOnly = false;\n\t\t// Track the elements as they are added to the set; supports get(i)///\n\t\tthis.configs = [];\n\n\t\t// TODO: these fields make me pretty uncomfortable but nice to pack up info\n\t\t// together, saves recomputation\n\t\t// TODO: can we track conflicts as they are added to save scanning configs\n\t\t// later?\n\t\tthis.uniqueAlt = 0;\n\t\tthis.conflictingAlts = null;\n\n\t\t/**\n\t\t * Used in parser and lexer. In lexer, it indicates we hit a pred\n\t\t * while computing a closure operation. Don't make a DFA state from this\n\t\t */\n\t\tthis.hasSemanticContext = false;\n\t\tthis.dipsIntoOuterContext = false;\n\n\t\tthis.cachedHashCode = -1;\n\t}\n\n\t/**\n\t * Adding a new config means merging contexts with existing configs for\n\t * {@code (s, i, pi, _)}, where {@code s} is the\n\t * {@link ATNConfig//state}, {@code i} is the {@link ATNConfig//alt}, and\n\t * {@code pi} is the {@link ATNConfig//semanticContext}. We use\n\t * {@code (s,i,pi)} as key.\n\t *\n\t * <p>This method updates {@link //dipsIntoOuterContext} and\n\t * {@link //hasSemanticContext} when necessary.</p>\n\t */\n\tadd(config, mergeCache) {\n\t\tif (mergeCache === undefined) {\n\t\t\tmergeCache = null;\n\t\t}\n\t\tif (this.readOnly) {\n\t\t\tthrow \"This set is readonly\";\n\t\t}\n\t\tif (config.semanticContext !== SemanticContext.NONE) {\n\t\t\tthis.hasSemanticContext = true;\n\t\t}\n\t\tif (config.reachesIntoOuterContext > 0) {\n\t\t\tthis.dipsIntoOuterContext = true;\n\t\t}\n\t\tconst existing = this.configLookup.getOrAdd(config);\n\t\tif (existing === config) {\n\t\t\tthis.cachedHashCode = -1;\n\t\t\tthis.configs.push(config); // track order here\n\t\t\treturn true;\n\t\t}\n\t\t// a previous (s,i,pi,_), merge with it and save result\n\t\tconst rootIsWildcard = !this.fullCtx;\n\t\tconst merged = merge(existing.context, config.context, rootIsWildcard, mergeCache);\n\t\t/**\n\t\t * no need to check for existing.context, config.context in cache\n\t\t * since only way to create new graphs is \"call rule\" and here. We\n\t\t * cache at both places\n\t\t */\n\t\texisting.reachesIntoOuterContext = Math.max( existing.reachesIntoOuterContext, config.reachesIntoOuterContext);\n\t\t// make sure to preserve the precedence filter suppression during the merge\n\t\tif (config.precedenceFilterSuppressed) {\n\t\t\texisting.precedenceFilterSuppressed = true;\n\t\t}\n\t\texisting.context = merged; // replace context; no need to alt mapping\n\t\treturn true;\n\t}\n\n\tgetStates() {\n\t\tconst states = new HashSet();\n\t\tfor (let i = 0; i < this.configs.length; i++) {\n\t\t\tstates.add(this.configs[i].state);\n\t\t}\n\t\treturn states;\n\t}\n\n\tgetPredicates() {\n\t\tconst preds = [];\n\t\tfor (let i = 0; i < this.configs.length; i++) {\n\t\t\tconst c = this.configs[i].semanticContext;\n\t\t\tif (c !== SemanticContext.NONE) {\n\t\t\t\tpreds.push(c.semanticContext);\n\t\t\t}\n\t\t}\n\t\treturn preds;\n\t}\n\n\toptimizeConfigs(interpreter) {\n\t\tif (this.readOnly) {\n\t\t\tthrow \"This set is readonly\";\n\t\t}\n\t\tif (this.configLookup.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tfor (let i = 0; i < this.configs.length; i++) {\n\t\t\tconst config = this.configs[i];\n\t\t\tconfig.context = interpreter.getCachedContext(config.context);\n\t\t}\n\t}\n\n\taddAll(coll) {\n\t\tfor (let i = 0; i < coll.length; i++) {\n\t\t\tthis.add(coll[i]);\n\t\t}\n\t\treturn false;\n\t}\n\n\tequals(other) {\n\t\treturn this === other ||\n\t\t\t(other instanceof ATNConfigSet &&\n\t\t\tequalArrays(this.configs, other.configs) &&\n\t\t\tthis.fullCtx === other.fullCtx &&\n\t\t\tthis.uniqueAlt === other.uniqueAlt &&\n\t\t\tthis.conflictingAlts === other.conflictingAlts &&\n\t\t\tthis.hasSemanticContext === other.hasSemanticContext &&\n\t\t\tthis.dipsIntoOuterContext === other.dipsIntoOuterContext);\n\t}\n\n\thashCode() {\n\t\tconst hash = new HashCode();\n\t\thash.update(this.configs);\n\t\treturn hash.finish();\n\t}\n\n\tupdateHashCode(hash) {\n\t\tif (this.readOnly) {\n\t\t\tif (this.cachedHashCode === -1) {\n\t\t\t\tthis.cachedHashCode = this.hashCode();\n\t\t\t}\n\t\t\thash.update(this.cachedHashCode);\n\t\t} else {\n\t\t\thash.update(this.hashCode());\n\t\t}\n\t}\n\n\tisEmpty() {\n\t\treturn this.configs.length === 0;\n\t}\n\n\tcontains(item) {\n\t\tif (this.configLookup === null) {\n\t\t\tthrow \"This method is not implemented for readonly sets.\";\n\t\t}\n\t\treturn this.configLookup.contains(item);\n\t}\n\n\tcontainsFast(item) {\n\t\tif (this.configLookup === null) {\n\t\t\tthrow \"This method is not implemented for readonly sets.\";\n\t\t}\n\t\treturn this.configLookup.containsFast(item);\n\t}\n\n\tclear() {\n\t\tif (this.readOnly) {\n\t\t\tthrow \"This set is readonly\";\n\t\t}\n\t\tthis.configs = [];\n\t\tthis.cachedHashCode = -1;\n\t\tthis.configLookup = new HashSet();\n\t}\n\n\tsetReadonly(readOnly) {\n\t\tthis.readOnly = readOnly;\n\t\tif (readOnly) {\n\t\t\tthis.configLookup = null; // can't mod, no need for lookup cache\n\t\t}\n\t}\n\n\ttoString() {\n\t\treturn arrayToString(this.configs) +\n\t\t\t(this.hasSemanticContext ? \",hasSemanticContext=\" + this.hasSemanticContext : \"\") +\n\t\t\t(this.uniqueAlt !== ATN.INVALID_ALT_NUMBER ? \",uniqueAlt=\" + this.uniqueAlt : \"\") +\n\t\t\t(this.conflictingAlts !== null ? \",conflictingAlts=\" + this.conflictingAlts : \"\") +\n\t\t\t(this.dipsIntoOuterContext ? \",dipsIntoOuterContext\" : \"\");\n\t}\n\n\tget items(){\n\t\treturn this.configs;\n\t}\n\n\tget length(){\n\t\treturn this.configs.length;\n\t}\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNDeserializationOptions.d.ts",
    "content": "export declare class ATNDeserializationOptions {\n    readOnly?: boolean;\n    verifyATN?: boolean;\n    generateRuleBypassTransitions?: boolean;\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNDeserializationOptions.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport default class ATNDeserializationOptions {\n\tconstructor(copyFrom) {\n\t\tif(copyFrom===undefined) {\n\t\t\tcopyFrom = null;\n\t\t}\n\t\tthis.readOnly = false;\n\t\tthis.verifyATN = copyFrom===null ? true : copyFrom.verifyATN;\n\t\tthis.generateRuleBypassTransitions = copyFrom===null ? false : copyFrom.generateRuleBypassTransitions;\n\t}\n}\n\nATNDeserializationOptions.defaultOptions = new ATNDeserializationOptions();\nATNDeserializationOptions.defaultOptions.readOnly = true;\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNDeserializer.d.ts",
    "content": "import {ATNDeserializationOptions} from \"./ATNDeserializationOptions.js\";\nimport {ATN} from \"./ATN.js\";\n\nexport declare class ATNDeserializer {\n    constructor(options?: ATNDeserializationOptions);\n    deserialize(data:  number[]) : ATN;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNDeserializer.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from '../Token.js';\nimport ATN from './ATN.js';\nimport ATNType from './ATNType.js';\n\nimport ATNState from '../state/ATNState.js';\nimport BasicState from '../state/BasicState.js';\nimport DecisionState from '../state/DecisionState.js';\nimport BlockStartState from '../state/BlockStartState.js';\nimport BlockEndState from '../state/BlockEndState.js';\nimport LoopEndState from '../state/LoopEndState.js';\nimport RuleStartState from '../state/RuleStartState.js';\nimport RuleStopState from '../state/RuleStopState.js';\nimport TokensStartState from '../state/TokensStartState.js';\nimport PlusLoopbackState from '../state/PlusLoopbackState.js';\nimport StarLoopbackState from '../state/StarLoopbackState.js';\nimport StarLoopEntryState from '../state/StarLoopEntryState.js';\nimport PlusBlockStartState from '../state/PlusBlockStartState.js';\nimport StarBlockStartState from '../state/StarBlockStartState.js';\nimport BasicBlockStartState from '../state/BasicBlockStartState.js';\n\nimport Transition from '../transition/Transition.js';\nimport AtomTransition from '../transition/AtomTransition.js';\nimport SetTransition from '../transition/SetTransition.js';\nimport NotSetTransition from '../transition/NotSetTransition.js';\nimport RuleTransition from '../transition/RuleTransition.js';\nimport RangeTransition from '../transition/RangeTransition.js';\nimport ActionTransition from '../transition/ActionTransition.js';\nimport EpsilonTransition from '../transition/EpsilonTransition.js';\nimport WildcardTransition from '../transition/WildcardTransition.js';\nimport PredicateTransition from '../transition/PredicateTransition.js';\nimport PrecedencePredicateTransition from '../transition/PrecedencePredicateTransition.js';\n\n\nimport IntervalSet from '../misc/IntervalSet.js';\nimport ATNDeserializationOptions from './ATNDeserializationOptions.js';\n\nimport LexerActionType from './LexerActionType.js';\nimport LexerSkipAction from '../action/LexerSkipAction.js';\nimport LexerChannelAction from '../action/LexerChannelAction.js';\nimport LexerCustomAction from '../action/LexerCustomAction.js';\nimport LexerMoreAction from '../action/LexerMoreAction.js';\nimport LexerTypeAction from '../action/LexerTypeAction.js';\nimport LexerPushModeAction from '../action/LexerPushModeAction.js';\nimport LexerPopModeAction from '../action/LexerPopModeAction.js';\nimport LexerModeAction from '../action/LexerModeAction.js';\n\nconst SERIALIZED_VERSION = 4;\n\nfunction initArray( length, value) {\n\tconst tmp = [];\n\ttmp[length-1] = value;\n\treturn tmp.map(function(i) {return value;});\n}\n\nexport default class ATNDeserializer {\n\n    constructor(options) {\n        if ( options=== undefined || options === null ) {\n            options = ATNDeserializationOptions.defaultOptions;\n        }\n        this.deserializationOptions = options;\n        this.stateFactories = null;\n        this.actionFactories = null;\n    }\n\n    deserialize(data) {\n        const legacy = this.reset(data);\n        this.checkVersion(legacy);\n        if(legacy)\n            this.skipUUID();\n        const atn = this.readATN();\n        this.readStates(atn, legacy);\n        this.readRules(atn, legacy);\n        this.readModes(atn);\n        const sets = [];\n        this.readSets(atn, sets, this.readInt.bind(this));\n        if(legacy)\n            this.readSets(atn, sets, this.readInt32.bind(this));\n        this.readEdges(atn, sets);\n        this.readDecisions(atn);\n        this.readLexerActions(atn, legacy);\n        this.markPrecedenceDecisions(atn);\n        this.verifyATN(atn);\n        if (this.deserializationOptions.generateRuleBypassTransitions && atn.grammarType === ATNType.PARSER ) {\n            this.generateRuleBypassTransitions(atn);\n            // re-verify after modification\n            this.verifyATN(atn);\n        }\n        return atn;\n    }\n\n    reset(data) {\n        const version = data.charCodeAt ? data.charCodeAt(0) : data[0];\n        if(version === SERIALIZED_VERSION - 1) {\n            const adjust = function (c) {\n                const v = c.charCodeAt(0);\n                return v > 1 ? v - 2 : v + 65534;\n            };\n            const temp = data.split(\"\").map(adjust);\n            // don't adjust the first value since that's the version number\n            temp[0] = data.charCodeAt(0);\n            this.data = temp;\n            this.pos = 0;\n            return true;\n        } else {\n            this.data = data\n            this.pos = 0;\n            return false;\n        }\n    }\n\n    skipUUID() {\n        let count = 0;\n        while(count++ < 8)\n            this.readInt();\n    }\n\n    checkVersion(legacy) {\n        const version = this.readInt();\n        if ( !legacy && version !== SERIALIZED_VERSION ) {\n            throw (\"Could not deserialize ATN with version \" + version + \" (expected \" + SERIALIZED_VERSION + \").\");\n        }\n    }\n\n    readATN() {\n        const grammarType = this.readInt();\n        const maxTokenType = this.readInt();\n        return new ATN(grammarType, maxTokenType);\n    }\n\n    readStates(atn, legacy) {\n        let j, pair, stateNumber;\n        const  loopBackStateNumbers = [];\n        const  endStateNumbers = [];\n        const  nstates = this.readInt();\n        for(let i=0; i<nstates; i++) {\n            const  stype = this.readInt();\n            // ignore bad type of states\n            if (stype===ATNState.INVALID_TYPE) {\n                atn.addState(null);\n                continue;\n            }\n            let ruleIndex = this.readInt();\n            if (legacy && ruleIndex === 0xFFFF) {\n                ruleIndex = -1;\n            }\n            const  s = this.stateFactory(stype, ruleIndex);\n            if (stype === ATNState.LOOP_END) { // special case\n                const  loopBackStateNumber = this.readInt();\n                loopBackStateNumbers.push([s, loopBackStateNumber]);\n            } else if(s instanceof BlockStartState) {\n                const  endStateNumber = this.readInt();\n                endStateNumbers.push([s, endStateNumber]);\n            }\n            atn.addState(s);\n        }\n        // delay the assignment of loop back and end states until we know all the\n        // state instances have been initialized\n        for (j=0; j<loopBackStateNumbers.length; j++) {\n            pair = loopBackStateNumbers[j];\n            pair[0].loopBackState = atn.states[pair[1]];\n        }\n\n        for (j=0; j<endStateNumbers.length; j++) {\n            pair = endStateNumbers[j];\n            pair[0].endState = atn.states[pair[1]];\n        }\n\n        let numNonGreedyStates = this.readInt();\n        for (j=0; j<numNonGreedyStates; j++) {\n            stateNumber = this.readInt();\n            atn.states[stateNumber].nonGreedy = true;\n        }\n\n        let numPrecedenceStates = this.readInt();\n        for (j=0; j<numPrecedenceStates; j++) {\n            stateNumber = this.readInt();\n            atn.states[stateNumber].isPrecedenceRule = true;\n        }\n    }\n\n    readRules(atn, legacy) {\n        let i;\n        const nrules = this.readInt();\n        if (atn.grammarType === ATNType.LEXER ) {\n            atn.ruleToTokenType = initArray(nrules, 0);\n        }\n        atn.ruleToStartState = initArray(nrules, 0);\n        for (i=0; i<nrules; i++) {\n            const s = this.readInt();\n            atn.ruleToStartState[i] = atn.states[s];\n            if ( atn.grammarType === ATNType.LEXER ) {\n                let tokenType = this.readInt();\n                if (legacy && tokenType === 0xFFFF) {\n                    tokenType = Token.EOF;\n                }\n                atn.ruleToTokenType[i] = tokenType;\n            }\n        }\n        atn.ruleToStopState = initArray(nrules, 0);\n        for (i=0; i<atn.states.length; i++) {\n            const state = atn.states[i];\n            if (!(state instanceof RuleStopState)) {\n                continue;\n            }\n            atn.ruleToStopState[state.ruleIndex] = state;\n            atn.ruleToStartState[state.ruleIndex].stopState = state;\n        }\n    }\n\n    readModes(atn) {\n        const nmodes = this.readInt();\n        for (let i=0; i<nmodes; i++) {\n            let s = this.readInt();\n            atn.modeToStartState.push(atn.states[s]);\n        }\n    }\n\n    readSets(atn, sets, reader) {\n        const m = this.readInt();\n        for (let i=0; i<m; i++) {\n            const iset = new IntervalSet();\n            sets.push(iset);\n            const n = this.readInt();\n            const containsEof = this.readInt();\n            if (containsEof!==0) {\n                iset.addOne(-1);\n            }\n            for (let j=0; j<n; j++) {\n                const i1 = reader();\n                const i2 = reader();\n                iset.addRange(i1, i2);\n            }\n        }\n    }\n\n    readEdges(atn, sets) {\n        let i, j, state, trans, target;\n        const nedges = this.readInt();\n        for (i=0; i<nedges; i++) {\n            const src = this.readInt();\n            const trg = this.readInt();\n            const ttype = this.readInt();\n            const arg1 = this.readInt();\n            const arg2 = this.readInt();\n            const arg3 = this.readInt();\n            trans = this.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);\n            const srcState = atn.states[src];\n            srcState.addTransition(trans);\n        }\n        // edges for rule stop states can be derived, so they aren't serialized\n        for (i=0; i<atn.states.length; i++) {\n            state = atn.states[i];\n            for (j=0; j<state.transitions.length; j++) {\n                const t = state.transitions[j];\n                if (!(t instanceof RuleTransition)) {\n                    continue;\n                }\n                let outermostPrecedenceReturn = -1;\n                if (atn.ruleToStartState[t.target.ruleIndex].isPrecedenceRule) {\n                    if (t.precedence === 0) {\n                        outermostPrecedenceReturn = t.target.ruleIndex;\n                    }\n                }\n\n                trans = new EpsilonTransition(t.followState, outermostPrecedenceReturn);\n                atn.ruleToStopState[t.target.ruleIndex].addTransition(trans);\n            }\n        }\n\n        for (i=0; i<atn.states.length; i++) {\n            state = atn.states[i];\n            if (state instanceof BlockStartState) {\n                // we need to know the end state to set its start state\n                if (state.endState === null) {\n                    throw (\"IllegalState\");\n                }\n                // block end states can only be associated to a single block start\n                // state\n                if ( state.endState.startState !== null) {\n                    throw (\"IllegalState\");\n                }\n                state.endState.startState = state;\n            }\n            if (state instanceof PlusLoopbackState) {\n                for (j=0; j<state.transitions.length; j++) {\n                    target = state.transitions[j].target;\n                    if (target instanceof PlusBlockStartState) {\n                        target.loopBackState = state;\n                    }\n                }\n            } else if (state instanceof StarLoopbackState) {\n                for (j=0; j<state.transitions.length; j++) {\n                    target = state.transitions[j].target;\n                    if (target instanceof StarLoopEntryState) {\n                        target.loopBackState = state;\n                    }\n                }\n            }\n        }\n    }\n\n    readDecisions(atn) {\n        const ndecisions = this.readInt();\n        for (let i=0; i<ndecisions; i++) {\n            const s = this.readInt();\n            const decState = atn.states[s];\n            atn.decisionToState.push(decState);\n            decState.decision = i;\n        }\n    }\n\n    readLexerActions(atn, legacy) {\n        if (atn.grammarType === ATNType.LEXER) {\n            const count = this.readInt();\n            atn.lexerActions = initArray(count, null);\n            for (let i=0; i<count; i++) {\n                const actionType = this.readInt();\n                let data1 = this.readInt();\n                if (legacy && data1 === 0xFFFF) {\n                    data1 = -1;\n                }\n                let data2 = this.readInt();\n                if (legacy && data2 === 0xFFFF) {\n                    data2 = -1;\n                }\n                atn.lexerActions[i] = this.lexerActionFactory(actionType, data1, data2);\n            }\n        }\n    }\n\n    generateRuleBypassTransitions(atn) {\n        let i;\n        const count = atn.ruleToStartState.length;\n        for(i=0; i<count; i++) {\n            atn.ruleToTokenType[i] = atn.maxTokenType + i + 1;\n        }\n        for(i=0; i<count; i++) {\n            this.generateRuleBypassTransition(atn, i);\n        }\n    }\n\n    generateRuleBypassTransition(atn, idx) {\n        let i, state;\n        const bypassStart = new BasicBlockStartState();\n        bypassStart.ruleIndex = idx;\n        atn.addState(bypassStart);\n\n        const bypassStop = new BlockEndState();\n        bypassStop.ruleIndex = idx;\n        atn.addState(bypassStop);\n\n        bypassStart.endState = bypassStop;\n        atn.defineDecisionState(bypassStart);\n\n        bypassStop.startState = bypassStart;\n\n        let excludeTransition = null;\n        let endState = null;\n\n        if (atn.ruleToStartState[idx].isPrecedenceRule) {\n            // wrap from the beginning of the rule to the StarLoopEntryState\n            endState = null;\n            for(i=0; i<atn.states.length; i++) {\n                state = atn.states[i];\n                if (this.stateIsEndStateFor(state, idx)) {\n                    endState = state;\n                    excludeTransition = state.loopBackState.transitions[0];\n                    break;\n                }\n            }\n            if (excludeTransition === null) {\n                throw (\"Couldn't identify final state of the precedence rule prefix section.\");\n            }\n        } else {\n            endState = atn.ruleToStopState[idx];\n        }\n\n        // all non-excluded transitions that currently target end state need to\n        // target blockEnd instead\n        for(i=0; i<atn.states.length; i++) {\n            state = atn.states[i];\n            for(let j=0; j<state.transitions.length; j++) {\n                const transition = state.transitions[j];\n                if (transition === excludeTransition) {\n                    continue;\n                }\n                if (transition.target === endState) {\n                    transition.target = bypassStop;\n                }\n            }\n        }\n\n        // all transitions leaving the rule start state need to leave blockStart\n        // instead\n        const ruleToStartState = atn.ruleToStartState[idx];\n        const count = ruleToStartState.transitions.length;\n        while ( count > 0) {\n            bypassStart.addTransition(ruleToStartState.transitions[count-1]);\n            ruleToStartState.transitions = ruleToStartState.transitions.slice(-1);\n        }\n        // link the new states\n        atn.ruleToStartState[idx].addTransition(new EpsilonTransition(bypassStart));\n        bypassStop.addTransition(new EpsilonTransition(endState));\n\n        const matchState = new BasicState();\n        atn.addState(matchState);\n        matchState.addTransition(new AtomTransition(bypassStop, atn.ruleToTokenType[idx]));\n        bypassStart.addTransition(new EpsilonTransition(matchState));\n    }\n\n    stateIsEndStateFor(state, idx) {\n        if ( state.ruleIndex !== idx) {\n            return null;\n        }\n        if (!( state instanceof StarLoopEntryState)) {\n            return null;\n        }\n        const maybeLoopEndState = state.transitions[state.transitions.length - 1].target;\n        if (!( maybeLoopEndState instanceof LoopEndState)) {\n            return null;\n        }\n        if (maybeLoopEndState.epsilonOnlyTransitions &&\n            (maybeLoopEndState.transitions[0].target instanceof RuleStopState)) {\n            return state;\n        } else {\n            return null;\n        }\n    }\n\n    /**\n     * Analyze the {@link StarLoopEntryState} states in the specified ATN to set\n     * the {@link StarLoopEntryState//isPrecedenceDecision} field to the\n     * correct value.\n     * @param atn The ATN.\n     */\n    markPrecedenceDecisions(atn) {\n        for(let i=0; i<atn.states.length; i++) {\n            const state = atn.states[i];\n            if (!( state instanceof StarLoopEntryState)) {\n                continue;\n            }\n            // We analyze the ATN to determine if this ATN decision state is the\n            // decision for the closure block that determines whether a\n            // precedence rule should continue or complete.\n            if ( atn.ruleToStartState[state.ruleIndex].isPrecedenceRule) {\n                const maybeLoopEndState = state.transitions[state.transitions.length - 1].target;\n                if (maybeLoopEndState instanceof LoopEndState) {\n                    if ( maybeLoopEndState.epsilonOnlyTransitions &&\n                            (maybeLoopEndState.transitions[0].target instanceof RuleStopState)) {\n                        state.isPrecedenceDecision = true;\n                    }\n                }\n            }\n        }\n    }\n\n    verifyATN(atn) {\n        if (!this.deserializationOptions.verifyATN) {\n            return;\n        }\n        // verify assumptions\n        for(let i=0; i<atn.states.length; i++) {\n            const state = atn.states[i];\n            if (state === null) {\n                continue;\n            }\n            this.checkCondition(state.epsilonOnlyTransitions || state.transitions.length <= 1);\n            if (state instanceof PlusBlockStartState) {\n                this.checkCondition(state.loopBackState !== null);\n            } else  if (state instanceof StarLoopEntryState) {\n                this.checkCondition(state.loopBackState !== null);\n                this.checkCondition(state.transitions.length === 2);\n                if (state.transitions[0].target instanceof StarBlockStartState) {\n                    this.checkCondition(state.transitions[1].target instanceof LoopEndState);\n                    this.checkCondition(!state.nonGreedy);\n                } else if (state.transitions[0].target instanceof LoopEndState) {\n                    this.checkCondition(state.transitions[1].target instanceof StarBlockStartState);\n                    this.checkCondition(state.nonGreedy);\n                } else {\n                    throw(\"IllegalState\");\n                }\n            } else if (state instanceof StarLoopbackState) {\n                this.checkCondition(state.transitions.length === 1);\n                this.checkCondition(state.transitions[0].target instanceof StarLoopEntryState);\n            } else if (state instanceof LoopEndState) {\n                this.checkCondition(state.loopBackState !== null);\n            } else if (state instanceof RuleStartState) {\n                this.checkCondition(state.stopState !== null);\n            } else if (state instanceof BlockStartState) {\n                this.checkCondition(state.endState !== null);\n            } else if (state instanceof BlockEndState) {\n                this.checkCondition(state.startState !== null);\n            } else if (state instanceof DecisionState) {\n                this.checkCondition(state.transitions.length <= 1 || state.decision >= 0);\n            } else {\n                this.checkCondition(state.transitions.length <= 1 || (state instanceof RuleStopState));\n            }\n        }\n    }\n\n    checkCondition(condition, message) {\n        if (!condition) {\n            if (message === undefined || message===null) {\n                message = \"IllegalState\";\n            }\n            throw (message);\n        }\n    }\n\n    readInt() {\n        return this.data[this.pos++];\n    }\n\n    readInt32() {\n        const low = this.readInt();\n        const high = this.readInt();\n        return low | (high << 16);\n    }\n\n    edgeFactory(atn, type, src, trg, arg1, arg2, arg3, sets) {\n        const target = atn.states[trg];\n        switch(type) {\n        case Transition.EPSILON:\n            return new EpsilonTransition(target);\n        case Transition.RANGE:\n            return arg3 !== 0 ? new RangeTransition(target, Token.EOF, arg2) : new RangeTransition(target, arg1, arg2);\n        case Transition.RULE:\n            return new RuleTransition(atn.states[arg1], arg2, arg3, target);\n        case Transition.PREDICATE:\n            return new PredicateTransition(target, arg1, arg2, arg3 !== 0);\n        case Transition.PRECEDENCE:\n            return new PrecedencePredicateTransition(target, arg1);\n        case Transition.ATOM:\n            return arg3 !== 0 ? new AtomTransition(target, Token.EOF) : new AtomTransition(target, arg1);\n        case Transition.ACTION:\n            return new ActionTransition(target, arg1, arg2, arg3 !== 0);\n        case Transition.SET:\n            return new SetTransition(target, sets[arg1]);\n        case Transition.NOT_SET:\n            return new NotSetTransition(target, sets[arg1]);\n        case Transition.WILDCARD:\n            return new WildcardTransition(target);\n        default:\n            throw \"The specified transition type: \" + type + \" is not valid.\";\n        }\n    }\n\n    stateFactory(type, ruleIndex) {\n        if (this.stateFactories === null) {\n            const sf = [];\n            sf[ATNState.INVALID_TYPE] = null;\n            sf[ATNState.BASIC] = () => new BasicState();\n            sf[ATNState.RULE_START] = () => new RuleStartState();\n            sf[ATNState.BLOCK_START] = () => new BasicBlockStartState();\n            sf[ATNState.PLUS_BLOCK_START] = () => new PlusBlockStartState();\n            sf[ATNState.STAR_BLOCK_START] = () => new StarBlockStartState();\n            sf[ATNState.TOKEN_START] = () => new TokensStartState();\n            sf[ATNState.RULE_STOP] = () => new RuleStopState();\n            sf[ATNState.BLOCK_END] = () => new BlockEndState();\n            sf[ATNState.STAR_LOOP_BACK] = () => new StarLoopbackState();\n            sf[ATNState.STAR_LOOP_ENTRY] = () => new StarLoopEntryState();\n            sf[ATNState.PLUS_LOOP_BACK] = () => new PlusLoopbackState();\n            sf[ATNState.LOOP_END] = () => new LoopEndState();\n            this.stateFactories = sf;\n        }\n        if (type>this.stateFactories.length || this.stateFactories[type] === null) {\n            throw(\"The specified state type \" + type + \" is not valid.\");\n        } else {\n            const s = this.stateFactories[type]();\n            if (s!==null) {\n                s.ruleIndex = ruleIndex;\n                return s;\n            }\n        }\n    }\n\n    lexerActionFactory(type, data1, data2) {\n        if (this.actionFactories === null) {\n            const af = [];\n            af[LexerActionType.CHANNEL] = (data1, data2) => new LexerChannelAction(data1);\n            af[LexerActionType.CUSTOM] = (data1, data2) => new LexerCustomAction(data1, data2);\n            af[LexerActionType.MODE] = (data1, data2) => new LexerModeAction(data1);\n            af[LexerActionType.MORE] = (data1, data2) => LexerMoreAction.INSTANCE;\n            af[LexerActionType.POP_MODE] = (data1, data2) => LexerPopModeAction.INSTANCE;\n            af[LexerActionType.PUSH_MODE] = (data1, data2) => new LexerPushModeAction(data1);\n            af[LexerActionType.SKIP] = (data1, data2) => LexerSkipAction.INSTANCE;\n            af[LexerActionType.TYPE] = (data1, data2) => new LexerTypeAction(data1);\n            this.actionFactories = af;\n        }\n        if (type>this.actionFactories.length || this.actionFactories[type] === null) {\n            throw(\"The specified lexer action type \" + type + \" is not valid.\");\n        } else {\n            return this.actionFactories[type](data1, data2);\n        }\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNSimulator.d.ts",
    "content": "export declare class ATNSimulator {\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNSimulator.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport DFAState from '../dfa/DFAState.js';\nimport ATNConfigSet from './ATNConfigSet.js';\nimport { getCachedPredictionContext } from '../context/PredictionContextUtils.js';\nimport HashMap from \"../misc/HashMap.js\";\n\nexport default class ATNSimulator {\n    constructor(atn, sharedContextCache) {\n        /**\n         * The context cache maps all PredictionContext objects that are ==\n         * to a single cached copy. This cache is shared across all contexts\n         * in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet\n         * to use only cached nodes/graphs in addDFAState(). We don't want to\n         * fill this during closure() since there are lots of contexts that\n         * pop up but are not used ever again. It also greatly slows down closure().\n         *\n         * <p>This cache makes a huge difference in memory and a little bit in speed.\n         * For the Java grammar on java.*, it dropped the memory requirements\n         * at the end from 25M to 16M. We don't store any of the full context\n         * graphs in the DFA because they are limited to local context only,\n         * but apparently there's a lot of repetition there as well. We optimize\n         * the config contexts before storing the config set in the DFA states\n         * by literally rebuilding them with cached subgraphs only.</p>\n         *\n         * <p>I tried a cache for use during closure operations, that was\n         * whacked after each adaptivePredict(). It cost a little bit\n         * more time I think and doesn't save on the overall footprint\n         * so it's not worth the complexity.</p>\n         */\n        this.atn = atn;\n        this.sharedContextCache = sharedContextCache;\n        return this;\n    }\n\n    getCachedContext(context) {\n        if (this.sharedContextCache ===null) {\n            return context;\n        }\n        const visited = new HashMap();\n        return getCachedPredictionContext(context, this.sharedContextCache, visited);\n    }\n}\n\n// Must distinguish between missing edge and edge we know leads nowhere///\nATNSimulator.ERROR = new DFAState(0x7FFFFFFF, new ATNConfigSet());\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ATNType.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/**\n * Represents the type of recognizer an ATN applies to\n */\nexport default {\n    LEXER: 0,\n    PARSER: 1\n};\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/AbstractPredicateTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Transition from \"../transition/Transition.js\";\n\nexport default class AbstractPredicateTransition extends Transition {\n    constructor(target) {\n        super(target);\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/LL1Analyzer.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from '../Token.js';\nimport ATNConfig from './ATNConfig.js';\nimport IntervalSet from '../misc/IntervalSet.js';\nimport RuleStopState from '../state/RuleStopState.js';\nimport RuleTransition from '../transition/RuleTransition.js';\nimport NotSetTransition from '../transition/NotSetTransition.js';\nimport WildcardTransition from '../transition/WildcardTransition.js';\nimport AbstractPredicateTransition from './AbstractPredicateTransition.js';\nimport { predictionContextFromRuleContext } from '../context/PredictionContextUtils.js';\nimport PredictionContext from '../context/PredictionContext.js';\nimport SingletonPredictionContext from '../context/SingletonPredictionContext.js';\nimport BitSet from \"../misc/BitSet.js\";\nimport HashSet from \"../misc/HashSet.js\";\n\nexport default class LL1Analyzer {\n    constructor(atn) {\n        this.atn = atn;\n    }\n\n    /**\n     * Calculates the SLL(1) expected lookahead set for each outgoing transition\n     * of an {@link ATNState}. The returned array has one element for each\n     * outgoing transition in {@code s}. If the closure from transition\n     * <em>i</em> leads to a semantic predicate before matching a symbol, the\n     * element at index <em>i</em> of the result will be {@code null}.\n     *\n     * @param s the ATN state\n     * @return the expected symbols for each outgoing transition of {@code s}.\n     */\n    getDecisionLookahead(s) {\n        if (s === null) {\n            return null;\n        }\n        const count = s.transitions.length;\n        const look = [];\n        for(let alt=0; alt< count; alt++) {\n            look[alt] = new IntervalSet();\n            const lookBusy = new HashSet();\n            const seeThruPreds = false; // fail to get lookahead upon pred\n            this._LOOK(s.transition(alt).target, null, PredictionContext.EMPTY,\n                  look[alt], lookBusy, new BitSet(), seeThruPreds, false);\n            // Wipe out lookahead for this alternative if we found nothing\n            // or we had a predicate when we !seeThruPreds\n            if (look[alt].length===0 || look[alt].contains(LL1Analyzer.HIT_PRED)) {\n                look[alt] = null;\n            }\n        }\n        return look;\n    }\n\n    /**\n     * Compute set of tokens that can follow {@code s} in the ATN in the\n     * specified {@code ctx}.\n     *\n     * <p>If {@code ctx} is {@code null} and the end of the rule containing\n     * {@code s} is reached, {@link Token//EPSILON} is added to the result set.\n     * If {@code ctx} is not {@code null} and the end of the outermost rule is\n     * reached, {@link Token//EOF} is added to the result set.</p>\n     *\n     * @param s the ATN state\n     * @param stopState the ATN state to stop at. This can be a\n     * {@link BlockEndState} to detect epsilon paths through a closure.\n     * @param ctx the complete parser context, or {@code null} if the context\n     * should be ignored\n     *\n     * @return The set of tokens that can follow {@code s} in the ATN in the\n     * specified {@code ctx}.\n     */\n    LOOK(s, stopState, ctx) {\n        const r = new IntervalSet();\n        const seeThruPreds = true; // ignore preds; get all lookahead\n        ctx = ctx || null;\n        const lookContext = ctx!==null ? predictionContextFromRuleContext(s.atn, ctx) : null;\n        this._LOOK(s, stopState, lookContext, r, new HashSet(), new BitSet(), seeThruPreds, true);\n        return r;\n    }\n\n    /**\n     * Compute set of tokens that can follow {@code s} in the ATN in the\n     * specified {@code ctx}.\n     *\n     * <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the\n     * rule containing {@code s} is reached, {@link Token//EPSILON} is added to\n     * the result set. If {@code ctx} is not {@code null} and {@code addEOF} is\n     * {@code true} and {@code stopState} or the end of the outermost rule is\n     * reached, {@link Token//EOF} is added to the result set.</p>\n     *\n     * @param s the ATN state.\n     * @param stopState the ATN state to stop at. This can be a\n     * {@link BlockEndState} to detect epsilon paths through a closure.\n     * @param ctx The outer context, or {@code null} if the outer context should\n     * not be used.\n     * @param look The result lookahead set.\n     * @param lookBusy A set used for preventing epsilon closures in the ATN\n     * from causing a stack overflow. Outside code should pass\n     * {@code new CustomizedSet<ATNConfig>} for this argument.\n     * @param calledRuleStack A set used for preventing left recursion in the\n     * ATN from causing a stack overflow. Outside code should pass\n     * {@code new BitSet()} for this argument.\n     * @param seeThruPreds {@code true} to true semantic predicates as\n     * implicitly {@code true} and \"see through them\", otherwise {@code false}\n     * to treat semantic predicates as opaque and add {@link //HIT_PRED} to the\n     * result if one is encountered.\n     * @param addEOF Add {@link Token//EOF} to the result if the end of the\n     * outermost context is reached. This parameter has no effect if {@code ctx}\n     * is {@code null}.\n     */\n    _LOOK(s, stopState , ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) {\n        const c = new ATNConfig({state:s, alt:0, context: ctx}, null);\n        if (lookBusy.has(c)) {\n            return;\n        }\n        lookBusy.add(c);\n        if (s === stopState) {\n            if (ctx ===null) {\n                look.addOne(Token.EPSILON);\n                return;\n            } else if (ctx.isEmpty() && addEOF) {\n                look.addOne(Token.EOF);\n                return;\n            }\n        }\n        if (s instanceof RuleStopState ) {\n            if (ctx ===null) {\n                look.addOne(Token.EPSILON);\n                return;\n            } else if (ctx.isEmpty() && addEOF) {\n                look.addOne(Token.EOF);\n                return;\n            }\n            if (ctx !== PredictionContext.EMPTY) {\n                const removed = calledRuleStack.get(s.ruleIndex);\n                try {\n                    calledRuleStack.clear(s.ruleIndex);\n                    // run thru all possible stack tops in ctx\n                    for (let i = 0; i < ctx.length; i++) {\n                        const returnState = this.atn.states[ctx.getReturnState(i)];\n                        this._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n                    }\n                }finally {\n                    if (removed) {\n                        calledRuleStack.set(s.ruleIndex);\n                    }\n                }\n                return;\n            }\n        }\n        for(let j=0; j<s.transitions.length; j++) {\n            const t = s.transitions[j];\n            if (t.constructor === RuleTransition) {\n                if (calledRuleStack.get(t.target.ruleIndex)) {\n                    continue;\n                }\n                const newContext = SingletonPredictionContext.create(ctx, t.followState.stateNumber);\n                try {\n                    calledRuleStack.set(t.target.ruleIndex);\n                    this._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n                } finally {\n                    calledRuleStack.clear(t.target.ruleIndex);\n                }\n            } else if (t instanceof AbstractPredicateTransition ) {\n                if (seeThruPreds) {\n                    this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n                } else {\n                    look.addOne(LL1Analyzer.HIT_PRED);\n                }\n            } else if( t.isEpsilon) {\n                this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);\n            } else if (t.constructor === WildcardTransition) {\n                look.addRange( Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType );\n            } else {\n                let set = t.label;\n                if (set !== null) {\n                    if (t instanceof NotSetTransition) {\n                        set = set.complement(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType);\n                    }\n                    look.addSet(set);\n                }\n            }\n        }\n    }\n}\n\n/**\n * Special value added to the lookahead sets to indicate that we hit\n * a predicate during analysis if {@code seeThruPreds==false}.\n */\nLL1Analyzer.HIT_PRED = Token.INVALID_TYPE;\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/LexerATNConfig.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport DecisionState from \"../state/DecisionState.js\";\nimport ATNConfig from \"./ATNConfig.js\";\n\nexport default class LexerATNConfig extends ATNConfig {\n    constructor(params, config) {\n        super(params, config);\n\n        // This is the backing field for {@link //getLexerActionExecutor}.\n        const lexerActionExecutor = params.lexerActionExecutor || null;\n        this.lexerActionExecutor = lexerActionExecutor || (config!==null ? config.lexerActionExecutor : null);\n        this.passedThroughNonGreedyDecision = config!==null ? this.checkNonGreedyDecision(config, this.state) : false;\n        this.hashCodeForConfigSet = LexerATNConfig.prototype.hashCode;\n        this.equalsForConfigSet = LexerATNConfig.prototype.equals;\n        return this;\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext, this.passedThroughNonGreedyDecision, this.lexerActionExecutor);\n    }\n\n    equals(other) {\n        return this === other ||\n            (other instanceof LexerATNConfig &&\n                this.passedThroughNonGreedyDecision === other.passedThroughNonGreedyDecision &&\n                (this.lexerActionExecutor ? this.lexerActionExecutor.equals(other.lexerActionExecutor) : !other.lexerActionExecutor) &&\n                super.equals(other));\n    }\n\n    checkNonGreedyDecision(source, target) {\n        return source.passedThroughNonGreedyDecision ||\n            (target instanceof DecisionState) && target.nonGreedy;\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/LexerATNSimulator.d.ts",
    "content": "import {Recognizer} from \"../Recognizer.js\";\nimport {ATNSimulator} from \"./ATNSimulator.js\";\nimport {ATN} from \"./ATN.js\";\nimport {PredictionContextCache} from \"./PredictionContextCache.js\";\nimport {DFA} from \"../dfa/index.js\";\nimport {CharStream} from \"../CharStream.js\";\n\nexport declare class LexerATNSimulator implements ATNSimulator {\n\n    decisionToDFA: DFA[];\n\n    constructor(recog: Recognizer<number>, atn: ATN, decisionToDFA: DFA[], sharedContextCache: PredictionContextCache);\n    consume(input: CharStream) : void;\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/LexerATNSimulator.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from '../Token.js';\nimport Lexer from './../Lexer.js';\nimport ATN from './ATN.js';\nimport ATNSimulator from './ATNSimulator.js';\nimport DFAState from '../dfa/DFAState.js';\nimport OrderedATNConfigSet from './OrderedATNConfigSet.js';\nimport PredictionContext from '../context/PredictionContext.js';\nimport SingletonPredictionContext from '../context/SingletonPredictionContext.js';\nimport RuleStopState from '../state/RuleStopState.js';\nimport LexerATNConfig from './LexerATNConfig.js';\nimport Transition from '../transition/Transition.js';\nimport LexerActionExecutor from './LexerActionExecutor.js';\nimport LexerNoViableAltException from '../error/LexerNoViableAltException.js';\n\nfunction resetSimState(sim) {\n    sim.index = -1;\n    sim.line = 0;\n    sim.column = -1;\n    sim.dfaState = null;\n}\n\nclass SimState {\n    constructor() {\n        resetSimState(this);\n    }\n\n    reset() {\n        resetSimState(this);\n    }\n}\n\nexport default class LexerATNSimulator extends ATNSimulator {\n    /**\n     * When we hit an accept state in either the DFA or the ATN, we\n     * have to notify the character stream to start buffering characters\n     * via {@link IntStream//mark} and record the current state. The current sim state\n     * includes the current index into the input, the current line,\n     * and current character position in that line. Note that the Lexer is\n     * tracking the starting line and characterization of the token. These\n     * variables track the \"state\" of the simulator when it hits an accept state.\n     *\n     * <p>We track these variables separately for the DFA and ATN simulation\n     * because the DFA simulation often has to fail over to the ATN\n     * simulation. If the ATN simulation fails, we need the DFA to fall\n     * back to its previously accepted state, if any. If the ATN succeeds,\n     * then the ATN does the accept and the DFA simulator that invoked it\n     * can simply return the predicted token type.</p>\n     */\n    constructor(recog, atn, decisionToDFA, sharedContextCache) {\n        super(atn, sharedContextCache);\n        this.decisionToDFA = decisionToDFA;\n        this.recog = recog;\n        /**\n         * The current token's starting index into the character stream.\n         * Shared across DFA to ATN simulation in case the ATN fails and the\n         * DFA did not have a previous accept state. In this case, we use the\n         * ATN-generated exception object\n         */\n        this.startIndex = -1;\n        // line number 1..n within the input///\n        this.line = 1;\n        /**\n         * The index of the character relative to the beginning of the line\n         * 0..n-1\n         */\n        this.column = 0;\n        this.mode = Lexer.DEFAULT_MODE;\n        /**\n         * Used during DFA/ATN exec to record the most recent accept configuration\n         * info\n         */\n        this.prevAccept = new SimState();\n    }\n\n    copyState(simulator) {\n        this.column = simulator.column;\n        this.line = simulator.line;\n        this.mode = simulator.mode;\n        this.startIndex = simulator.startIndex;\n    }\n\n    match(input, mode) {\n        this.mode = mode;\n        const mark = input.mark();\n        try {\n            this.startIndex = input.index;\n            this.prevAccept.reset();\n            const dfa = this.decisionToDFA[mode];\n            if (dfa.s0 === null) {\n                return this.matchATN(input);\n            } else {\n                return this.execATN(input, dfa.s0);\n            }\n        } finally {\n            input.release(mark);\n        }\n    }\n\n    reset() {\n        this.prevAccept.reset();\n        this.startIndex = -1;\n        this.line = 1;\n        this.column = 0;\n        this.mode = Lexer.DEFAULT_MODE;\n    }\n\n    matchATN(input) {\n        const startState = this.atn.modeToStartState[this.mode];\n\n        if (LexerATNSimulator.debug) {\n            console.log(\"matchATN mode \" + this.mode + \" start: \" + startState);\n        }\n        const old_mode = this.mode;\n        const s0_closure = this.computeStartState(input, startState);\n        const suppressEdge = s0_closure.hasSemanticContext;\n        s0_closure.hasSemanticContext = false;\n\n        const next = this.addDFAState(s0_closure);\n        if (!suppressEdge) {\n            this.decisionToDFA[this.mode].s0 = next;\n        }\n\n        const predict = this.execATN(input, next);\n\n        if (LexerATNSimulator.debug) {\n            console.log(\"DFA after matchATN: \" + this.decisionToDFA[old_mode].toLexerString());\n        }\n        return predict;\n    }\n\n    execATN(input, ds0) {\n        if (LexerATNSimulator.debug) {\n            console.log(\"start state closure=\" + ds0.configs);\n        }\n        if (ds0.isAcceptState) {\n            // allow zero-length tokens\n            this.captureSimState(this.prevAccept, input, ds0);\n        }\n        let t = input.LA(1);\n        let s = ds0; // s is current/from DFA state\n\n        for (; ;) { // while more work\n            if (LexerATNSimulator.debug) {\n                console.log(\"execATN loop starting closure: \" + s.configs);\n            }\n\n            /**\n             * As we move src->trg, src->trg, we keep track of the previous trg to\n             * avoid looking up the DFA state again, which is expensive.\n             * If the previous target was already part of the DFA, we might\n             * be able to avoid doing a reach operation upon t. If s!=null,\n             * it means that semantic predicates didn't prevent us from\n             * creating a DFA state. Once we know s!=null, we check to see if\n             * the DFA state has an edge already for t. If so, we can just reuse\n             * it's configuration set; there's no point in re-computing it.\n             * This is kind of like doing DFA simulation within the ATN\n             * simulation because DFA simulation is really just a way to avoid\n             * computing reach/closure sets. Technically, once we know that\n             * we have a previously added DFA state, we could jump over to\n             * the DFA simulator. But, that would mean popping back and forth\n             * a lot and making things more complicated algorithmically.\n             * This optimization makes a lot of sense for loops within DFA.\n             * A character will take us back to an existing DFA state\n             * that already has lots of edges out of it. e.g., .* in comments.\n             * print(\"Target for:\" + str(s) + \" and:\" + str(t))\n             */\n            let target = this.getExistingTargetState(s, t);\n            // print(\"Existing:\" + str(target))\n            if (target === null) {\n                target = this.computeTargetState(input, s, t);\n                // print(\"Computed:\" + str(target))\n            }\n            if (target === ATNSimulator.ERROR) {\n                break;\n            }\n            // If this is a consumable input element, make sure to consume before\n            // capturing the accept state so the input index, line, and char\n            // position accurately reflect the state of the interpreter at the\n            // end of the token.\n            if (t !== Token.EOF) {\n                this.consume(input);\n            }\n            if (target.isAcceptState) {\n                this.captureSimState(this.prevAccept, input, target);\n                if (t === Token.EOF) {\n                    break;\n                }\n            }\n            t = input.LA(1);\n            s = target; // flip; current DFA target becomes new src/from state\n        }\n        return this.failOrAccept(this.prevAccept, input, s.configs, t);\n    }\n\n    /**\n     * Get an existing target state for an edge in the DFA. If the target state\n     * for the edge has not yet been computed or is otherwise not available,\n     * this method returns {@code null}.\n     *\n     * @param s The current DFA state\n     * @param t The next input symbol\n     * @return The existing target DFA state for the given input symbol\n     * {@code t}, or {@code null} if the target state for this edge is not\n     * already cached\n     */\n    getExistingTargetState(s, t) {\n        if (s.edges === null || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE) {\n            return null;\n        }\n\n        let target = s.edges[t - LexerATNSimulator.MIN_DFA_EDGE];\n        if (target === undefined) {\n            target = null;\n        }\n        if (LexerATNSimulator.debug && target !== null) {\n            console.log(\"reuse state \" + s.stateNumber + \" edge to \" + target.stateNumber);\n        }\n        return target;\n    }\n\n    /**\n     * Compute a target state for an edge in the DFA, and attempt to add the\n     * computed state and corresponding edge to the DFA.\n     *\n     * @param input The input stream\n     * @param s The current DFA state\n     * @param t The next input symbol\n     *\n     * @return The computed target DFA state for the given input symbol\n     * {@code t}. If {@code t} does not lead to a valid DFA state, this method\n     * returns {@link //ERROR}.\n     */\n    computeTargetState(input, s, t) {\n        const reach = new OrderedATNConfigSet();\n        // if we don't find an existing DFA state\n        // Fill reach starting from closure, following t transitions\n        this.getReachableConfigSet(input, s.configs, reach, t);\n\n        if (reach.items.length === 0) { // we got nowhere on t from s\n            if (!reach.hasSemanticContext) {\n                // we got nowhere on t, don't throw out this knowledge; it'd\n                // cause a failover from DFA later.\n                this.addDFAEdge(s, t, ATNSimulator.ERROR);\n            }\n            // stop when we can't match any more char\n            return ATNSimulator.ERROR;\n        }\n        // Add an edge from s to target DFA found/created for reach\n        return this.addDFAEdge(s, t, null, reach);\n    }\n\n    failOrAccept(prevAccept, input, reach, t) {\n        if (this.prevAccept.dfaState !== null) {\n            const lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor;\n            this.accept(input, lexerActionExecutor, this.startIndex,\n                prevAccept.index, prevAccept.line, prevAccept.column);\n            return prevAccept.dfaState.prediction;\n        } else {\n            // if no accept and EOF is first char, return EOF\n            if (t === Token.EOF && input.index === this.startIndex) {\n                return Token.EOF;\n            }\n            throw new LexerNoViableAltException(this.recog, input, this.startIndex, reach);\n        }\n    }\n\n    /**\n     * Given a starting configuration set, figure out all ATN configurations\n     * we can reach upon input {@code t}. Parameter {@code reach} is a return\n     * parameter.\n     */\n    getReachableConfigSet(input, closure, reach, t) {\n        // this is used to skip processing for configs which have a lower priority\n        // than a config that already reached an accept state for the same rule\n        let skipAlt = ATN.INVALID_ALT_NUMBER;\n        for (let i = 0; i < closure.items.length; i++) {\n            const cfg = closure.items[i];\n            const currentAltReachedAcceptState = (cfg.alt === skipAlt);\n            if (currentAltReachedAcceptState && cfg.passedThroughNonGreedyDecision) {\n                continue;\n            }\n            if (LexerATNSimulator.debug) {\n                console.log(\"testing %s at %s\\n\", this.getTokenName(t), cfg\n                    .toString(this.recog, true));\n            }\n            for (let j = 0; j < cfg.state.transitions.length; j++) {\n                const trans = cfg.state.transitions[j]; // for each transition\n                const target = this.getReachableTarget(trans, t);\n                if (target !== null) {\n                    let lexerActionExecutor = cfg.lexerActionExecutor;\n                    if (lexerActionExecutor !== null) {\n                        lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - this.startIndex);\n                    }\n                    const treatEofAsEpsilon = (t === Token.EOF);\n                    const config = new LexerATNConfig({state: target, lexerActionExecutor: lexerActionExecutor}, cfg);\n                    if (this.closure(input, config, reach,\n                        currentAltReachedAcceptState, true, treatEofAsEpsilon)) {\n                        // any remaining configs for this alt have a lower priority\n                        // than the one that just reached an accept state.\n                        skipAlt = cfg.alt;\n                    }\n                }\n            }\n        }\n    }\n\n    accept(input, lexerActionExecutor, startIndex, index, line, charPos) {\n        if (LexerATNSimulator.debug) {\n            console.log(\"ACTION %s\\n\", lexerActionExecutor);\n        }\n        // seek to after last char in token\n        input.seek(index);\n        this.line = line;\n        this.column = charPos;\n        if (lexerActionExecutor !== null && this.recog !== null) {\n            lexerActionExecutor.execute(this.recog, input, startIndex);\n        }\n    }\n\n    getReachableTarget(trans, t) {\n        if (trans.matches(t, 0, Lexer.MAX_CHAR_VALUE)) {\n            return trans.target;\n        } else {\n            return null;\n        }\n    }\n\n    computeStartState(input, p) {\n        const initialContext = PredictionContext.EMPTY;\n        const configs = new OrderedATNConfigSet();\n        for (let i = 0; i < p.transitions.length; i++) {\n            const target = p.transitions[i].target;\n            const cfg = new LexerATNConfig({state: target, alt: i + 1, context: initialContext}, null);\n            this.closure(input, cfg, configs, false, false, false);\n        }\n        return configs;\n    }\n\n    /**\n     * Since the alternatives within any lexer decision are ordered by\n     * preference, this method stops pursuing the closure as soon as an accept\n     * state is reached. After the first accept state is reached by depth-first\n     * search from {@code config}, all other (potentially reachable) states for\n     * this rule would have a lower priority.\n     *\n     * @return {Boolean} {@code true} if an accept state is reached, otherwise\n     * {@code false}.\n     */\n    closure(input, config, configs,\n            currentAltReachedAcceptState, speculative, treatEofAsEpsilon) {\n        let cfg = null;\n        if (LexerATNSimulator.debug) {\n            console.log(\"closure(\" + config.toString(this.recog, true) + \")\");\n        }\n        if (config.state instanceof RuleStopState) {\n            if (LexerATNSimulator.debug) {\n                if (this.recog !== null) {\n                    console.log(\"closure at %s rule stop %s\\n\", this.recog.ruleNames[config.state.ruleIndex], config);\n                } else {\n                    console.log(\"closure at rule stop %s\\n\", config);\n                }\n            }\n            if (config.context === null || config.context.hasEmptyPath()) {\n                if (config.context === null || config.context.isEmpty()) {\n                    configs.add(config);\n                    return true;\n                } else {\n                    configs.add(new LexerATNConfig({state: config.state, context: PredictionContext.EMPTY}, config));\n                    currentAltReachedAcceptState = true;\n                }\n            }\n            if (config.context !== null && !config.context.isEmpty()) {\n                for (let i = 0; i < config.context.length; i++) {\n                    if (config.context.getReturnState(i) !== PredictionContext.EMPTY_RETURN_STATE) {\n                        const newContext = config.context.getParent(i); // \"pop\" return state\n                        const returnState = this.atn.states[config.context.getReturnState(i)];\n                        cfg = new LexerATNConfig({state: returnState, context: newContext}, config);\n                        currentAltReachedAcceptState = this.closure(input, cfg,\n                            configs, currentAltReachedAcceptState, speculative,\n                            treatEofAsEpsilon);\n                    }\n                }\n            }\n            return currentAltReachedAcceptState;\n        }\n        // optimization\n        if (!config.state.epsilonOnlyTransitions) {\n            if (!currentAltReachedAcceptState || !config.passedThroughNonGreedyDecision) {\n                configs.add(config);\n            }\n        }\n        for (let j = 0; j < config.state.transitions.length; j++) {\n            const trans = config.state.transitions[j];\n            cfg = this.getEpsilonTarget(input, config, trans, configs, speculative, treatEofAsEpsilon);\n            if (cfg !== null) {\n                currentAltReachedAcceptState = this.closure(input, cfg, configs,\n                    currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n            }\n        }\n        return currentAltReachedAcceptState;\n    }\n\n    // side-effect: can alter configs.hasSemanticContext\n    getEpsilonTarget(input, config, trans,\n                     configs, speculative, treatEofAsEpsilon) {\n        let cfg = null;\n        if (trans.serializationType === Transition.RULE) {\n            const newContext = SingletonPredictionContext.create(config.context, trans.followState.stateNumber);\n            cfg = new LexerATNConfig({state: trans.target, context: newContext}, config);\n        } else if (trans.serializationType === Transition.PRECEDENCE) {\n            throw \"Precedence predicates are not supported in lexers.\";\n        } else if (trans.serializationType === Transition.PREDICATE) {\n            // Track traversing semantic predicates. If we traverse,\n            // we cannot add a DFA state for this \"reach\" computation\n            // because the DFA would not test the predicate again in the\n            // future. Rather than creating collections of semantic predicates\n            // like v3 and testing them on prediction, v4 will test them on the\n            // fly all the time using the ATN not the DFA. This is slower but\n            // semantically it's not used that often. One of the key elements to\n            // this predicate mechanism is not adding DFA states that see\n            // predicates immediately afterwards in the ATN. For example,\n\n            // a : ID {p1}? | ID {p2}? ;\n\n            // should create the start state for rule 'a' (to save start state\n            // competition), but should not create target of ID state. The\n            // collection of ATN states the following ID references includes\n            // states reached by traversing predicates. Since this is when we\n            // test them, we cannot cash the DFA state target of ID.\n\n            if (LexerATNSimulator.debug) {\n                console.log(\"EVAL rule \" + trans.ruleIndex + \":\" + trans.predIndex);\n            }\n            configs.hasSemanticContext = true;\n            if (this.evaluatePredicate(input, trans.ruleIndex, trans.predIndex, speculative)) {\n                cfg = new LexerATNConfig({state: trans.target}, config);\n            }\n        } else if (trans.serializationType === Transition.ACTION) {\n            if (config.context === null || config.context.hasEmptyPath()) {\n                // execute actions anywhere in the start rule for a token.\n                //\n                // TODO: if the entry rule is invoked recursively, some\n                // actions may be executed during the recursive call. The\n                // problem can appear when hasEmptyPath() is true but\n                // isEmpty() is false. In this case, the config needs to be\n                // split into two contexts - one with just the empty path\n                // and another with everything but the empty path.\n                // Unfortunately, the current algorithm does not allow\n                // getEpsilonTarget to return two configurations, so\n                // additional modifications are needed before we can support\n                // the split operation.\n                const lexerActionExecutor = LexerActionExecutor.append(config.lexerActionExecutor,\n                    this.atn.lexerActions[trans.actionIndex]);\n                cfg = new LexerATNConfig({state: trans.target, lexerActionExecutor: lexerActionExecutor}, config);\n            } else {\n                // ignore actions in referenced rules\n                cfg = new LexerATNConfig({state: trans.target}, config);\n            }\n        } else if (trans.serializationType === Transition.EPSILON) {\n            cfg = new LexerATNConfig({state: trans.target}, config);\n        } else if (trans.serializationType === Transition.ATOM ||\n            trans.serializationType === Transition.RANGE ||\n            trans.serializationType === Transition.SET) {\n            if (treatEofAsEpsilon) {\n                if (trans.matches(Token.EOF, 0, Lexer.MAX_CHAR_VALUE)) {\n                    cfg = new LexerATNConfig({state: trans.target}, config);\n                }\n            }\n        }\n        return cfg;\n    }\n\n    /**\n     * Evaluate a predicate specified in the lexer.\n     *\n     * <p>If {@code speculative} is {@code true}, this method was called before\n     * {@link //consume} for the matched character. This method should call\n     * {@link //consume} before evaluating the predicate to ensure position\n     * sensitive values, including {@link Lexer//getText}, {@link Lexer//getLine},\n     * and {@link Lexer//getcolumn}, properly reflect the current\n     * lexer state. This method should restore {@code input} and the simulator\n     * to the original state before returning (i.e. undo the actions made by the\n     * call to {@link //consume}.</p>\n     *\n     * @param input The input stream.\n     * @param ruleIndex The rule containing the predicate.\n     * @param predIndex The index of the predicate within the rule.\n     * @param speculative {@code true} if the current index in {@code input} is\n     * one character before the predicate's location.\n     *\n     * @return {@code true} if the specified predicate evaluates to\n     * {@code true}.\n     */\n    evaluatePredicate(input, ruleIndex,\n                      predIndex, speculative) {\n        // assume true if no recognizer was provided\n        if (this.recog === null) {\n            return true;\n        }\n        if (!speculative) {\n            return this.recog.sempred(null, ruleIndex, predIndex);\n        }\n        const savedcolumn = this.column;\n        const savedLine = this.line;\n        const index = input.index;\n        const marker = input.mark();\n        try {\n            this.consume(input);\n            return this.recog.sempred(null, ruleIndex, predIndex);\n        } finally {\n            this.column = savedcolumn;\n            this.line = savedLine;\n            input.seek(index);\n            input.release(marker);\n        }\n    }\n\n    captureSimState(settings, input, dfaState) {\n        settings.index = input.index;\n        settings.line = this.line;\n        settings.column = this.column;\n        settings.dfaState = dfaState;\n    }\n\n    addDFAEdge(from_, tk, to, cfgs) {\n        if (to === undefined) {\n            to = null;\n        }\n        if (cfgs === undefined) {\n            cfgs = null;\n        }\n        if (to === null && cfgs !== null) {\n            // leading to this call, ATNConfigSet.hasSemanticContext is used as a\n            // marker indicating dynamic predicate evaluation makes this edge\n            // dependent on the specific input sequence, so the static edge in the\n            // DFA should be omitted. The target DFAState is still created since\n            // execATN has the ability to resynchronize with the DFA state cache\n            // following the predicate evaluation step.\n            //\n            // TJP notes: next time through the DFA, we see a pred again and eval.\n            // If that gets us to a previously created (but dangling) DFA\n            // state, we can continue in pure DFA mode from there.\n            // /\n            const suppressEdge = cfgs.hasSemanticContext;\n            cfgs.hasSemanticContext = false;\n\n            to = this.addDFAState(cfgs);\n\n            if (suppressEdge) {\n                return to;\n            }\n        }\n        // add the edge\n        if (tk < LexerATNSimulator.MIN_DFA_EDGE || tk > LexerATNSimulator.MAX_DFA_EDGE) {\n            // Only track edges within the DFA bounds\n            return to;\n        }\n        if (LexerATNSimulator.debug) {\n            console.log(\"EDGE \" + from_ + \" -> \" + to + \" upon \" + tk);\n        }\n        if (from_.edges === null) {\n            // make room for tokens 1..n and -1 masquerading as index 0\n            from_.edges = [];\n        }\n        from_.edges[tk - LexerATNSimulator.MIN_DFA_EDGE] = to; // connect\n\n        return to;\n    }\n\n    /**\n     * Add a new DFA state if there isn't one with this set of\n     * configurations already. This method also detects the first\n     * configuration containing an ATN rule stop state. Later, when\n     * traversing the DFA, we will know which rule to accept.\n     */\n    addDFAState(configs) {\n        const proposed = new DFAState(null, configs);\n        let firstConfigWithRuleStopState = null;\n        for (let i = 0; i < configs.items.length; i++) {\n            const cfg = configs.items[i];\n            if (cfg.state instanceof RuleStopState) {\n                firstConfigWithRuleStopState = cfg;\n                break;\n            }\n        }\n        if (firstConfigWithRuleStopState !== null) {\n            proposed.isAcceptState = true;\n            proposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor;\n            proposed.prediction = this.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex];\n        }\n        const dfa = this.decisionToDFA[this.mode];\n        const existing = dfa.states.get(proposed);\n        if (existing !== null) {\n            return existing;\n        }\n        const newState = proposed;\n        newState.stateNumber = dfa.states.length;\n        configs.setReadonly(true);\n        newState.configs = configs;\n        dfa.states.add(newState);\n        return newState;\n    }\n\n    getDFA(mode) {\n        return this.decisionToDFA[mode];\n    }\n\n// Get the text matched so far for the current token.\n    getText(input) {\n        // index is first lookahead char, don't include.\n        return input.getText(this.startIndex, input.index - 1);\n    }\n\n    consume(input) {\n        const curChar = input.LA(1);\n        if (curChar === \"\\n\".charCodeAt(0)) {\n            this.line += 1;\n            this.column = 0;\n        } else {\n            this.column += 1;\n        }\n        input.consume();\n    }\n\n    getTokenName(tt) {\n        if (tt === -1) {\n            return \"EOF\";\n        } else {\n            return \"'\" + String.fromCharCode(tt) + \"'\";\n        }\n    }\n}\n\nLexerATNSimulator.debug = false;\nLexerATNSimulator.dfa_debug = false;\n\nLexerATNSimulator.MIN_DFA_EDGE = 0;\nLexerATNSimulator.MAX_DFA_EDGE = 127; // forces unicode to stay in ATN\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/LexerActionExecutor.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport LexerIndexedCustomAction from '../action/LexerIndexedCustomAction.js';\nimport HashCode from \"../misc/HashCode.js\";\n\nexport default class LexerActionExecutor {\n\t/**\n\t * Represents an executor for a sequence of lexer actions which traversed during\n\t * the matching operation of a lexer rule (token).\n\t *\n\t * <p>The executor tracks position information for position-dependent lexer actions\n\t * efficiently, ensuring that actions appearing only at the end of the rule do\n\t * not cause bloating of the {@link DFA} created for the lexer.</p>\n\t */\n\tconstructor(lexerActions) {\n\t\tthis.lexerActions = lexerActions === null ? [] : lexerActions;\n\t\t/**\n\t\t * Caches the result of {@link //hashCode} since the hash code is an element\n\t\t * of the performance-critical {@link LexerATNConfig//hashCode} operation\n\t\t */\n\t\tthis.cachedHashCode = HashCode.hashStuff(lexerActions); // \"\".join([str(la) for la in\n\t\t// lexerActions]))\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates a {@link LexerActionExecutor} which encodes the current offset\n\t * for position-dependent lexer actions.\n\t *\n\t * <p>Normally, when the executor encounters lexer actions where\n\t * {@link LexerAction//isPositionDependent} returns {@code true}, it calls\n\t * {@link IntStream//seek} on the input {@link CharStream} to set the input\n\t * position to the <em>end</em> of the current token. This behavior provides\n\t * for efficient DFA representation of lexer actions which appear at the end\n\t * of a lexer rule, even when the lexer rule matches a variable number of\n\t * characters.</p>\n\t *\n\t * <p>Prior to traversing a match transition in the ATN, the current offset\n\t * from the token start index is assigned to all position-dependent lexer\n\t * actions which have not already been assigned a fixed offset. By storing\n\t * the offsets relative to the token start index, the DFA representation of\n\t * lexer actions which appear in the middle of tokens remains efficient due\n\t * to sharing among tokens of the same length, regardless of their absolute\n\t * position in the input stream.</p>\n\t *\n\t * <p>If the current executor already has offsets assigned to all\n\t * position-dependent lexer actions, the method returns {@code this}.</p>\n\t *\n\t * @param offset The current offset to assign to all position-dependent\n\t * lexer actions which do not already have offsets assigned.\n\t *\n\t * @return {LexerActionExecutor} A {@link LexerActionExecutor} which stores input stream offsets\n\t * for all position-dependent lexer actions.\n\t */\n\tfixOffsetBeforeMatch(offset) {\n\t\tlet updatedLexerActions = null;\n\t\tfor (let i = 0; i < this.lexerActions.length; i++) {\n\t\t\tif (this.lexerActions[i].isPositionDependent &&\n\t\t\t\t\t!(this.lexerActions[i] instanceof LexerIndexedCustomAction)) {\n\t\t\t\tif (updatedLexerActions === null) {\n\t\t\t\t\tupdatedLexerActions = this.lexerActions.concat([]);\n\t\t\t\t}\n\t\t\t\tupdatedLexerActions[i] = new LexerIndexedCustomAction(offset,\n\t\t\t\t\t\tthis.lexerActions[i]);\n\t\t\t}\n\t\t}\n\t\tif (updatedLexerActions === null) {\n\t\t\treturn this;\n\t\t} else {\n\t\t\treturn new LexerActionExecutor(updatedLexerActions);\n\t\t}\n\t}\n\n\t/**\n\t * Execute the actions encapsulated by this executor within the context of a\n\t * particular {@link Lexer}.\n\t *\n\t * <p>This method calls {@link IntStream//seek} to set the position of the\n\t * {@code input} {@link CharStream} prior to calling\n\t * {@link LexerAction//execute} on a position-dependent action. Before the\n\t * method returns, the input position will be restored to the same position\n\t * it was in when the method was invoked.</p>\n\t *\n\t * @param lexer The lexer instance.\n\t * @param input The input stream which is the source for the current token.\n\t * When this method is called, the current {@link IntStream//index} for\n\t * {@code input} should be the start of the following token, i.e. 1\n\t * character past the end of the current token.\n\t * @param startIndex The token start index. This value may be passed to\n\t * {@link IntStream//seek} to set the {@code input} position to the beginning\n\t * of the token.\n\t */\n\texecute(lexer, input, startIndex) {\n\t\tlet requiresSeek = false;\n\t\tconst stopIndex = input.index;\n\t\ttry {\n\t\t\tfor (let i = 0; i < this.lexerActions.length; i++) {\n\t\t\t\tlet lexerAction = this.lexerActions[i];\n\t\t\t\tif (lexerAction instanceof LexerIndexedCustomAction) {\n\t\t\t\t\tconst offset = lexerAction.offset;\n\t\t\t\t\tinput.seek(startIndex + offset);\n\t\t\t\t\tlexerAction = lexerAction.action;\n\t\t\t\t\trequiresSeek = (startIndex + offset) !== stopIndex;\n\t\t\t\t} else if (lexerAction.isPositionDependent) {\n\t\t\t\t\tinput.seek(stopIndex);\n\t\t\t\t\trequiresSeek = false;\n\t\t\t\t}\n\t\t\t\tlexerAction.execute(lexer);\n\t\t\t}\n\t\t} finally {\n\t\t\tif (requiresSeek) {\n\t\t\t\tinput.seek(stopIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\thashCode() {\n\t\treturn this.cachedHashCode;\n\t}\n\n\tupdateHashCode(hash) {\n\t\thash.update(this.cachedHashCode);\n\t}\n\n\tequals(other) {\n\t\tif (this === other) {\n\t\t\treturn true;\n\t\t} else if (!(other instanceof LexerActionExecutor)) {\n\t\t\treturn false;\n\t\t} else if (this.cachedHashCode != other.cachedHashCode) {\n\t\t\treturn false;\n\t\t} else if (this.lexerActions.length != other.lexerActions.length) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\tconst numActions = this.lexerActions.length\n\t\t\tfor (let idx = 0; idx < numActions; ++idx) {\n\t\t\t\tif (!this.lexerActions[idx].equals(other.lexerActions[idx])) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * Creates a {@link LexerActionExecutor} which executes the actions for\n\t * the input {@code lexerActionExecutor} followed by a specified\n\t * {@code lexerAction}.\n\t *\n\t * @param lexerActionExecutor The executor for actions already traversed by\n\t * the lexer while matching a token within a particular\n\t * {@link LexerATNConfig}. If this is {@code null}, the method behaves as\n\t * though it were an empty executor.\n\t * @param lexerAction The lexer action to execute after the actions\n\t * specified in {@code lexerActionExecutor}.\n\t *\n\t * @return {LexerActionExecutor} A {@link LexerActionExecutor} for executing the combine actions\n\t * of {@code lexerActionExecutor} and {@code lexerAction}.\n\t */\n\tstatic append(lexerActionExecutor, lexerAction) {\n\t\tif (lexerActionExecutor === null) {\n\t\t\treturn new LexerActionExecutor([ lexerAction ]);\n\t\t}\n\t\tconst lexerActions = lexerActionExecutor.lexerActions.concat([ lexerAction ]);\n\t\treturn new LexerActionExecutor(lexerActions);\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/LexerActionType.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default {\n    // The type of a {@link LexerChannelAction} action.\n    CHANNEL: 0,\n    // The type of a {@link LexerCustomAction} action\n    CUSTOM: 1,\n    // The type of a {@link LexerModeAction} action.\n    MODE: 2,\n    //The type of a {@link LexerMoreAction} action.\n    MORE: 3,\n    //The type of a {@link LexerPopModeAction} action.\n    POP_MODE: 4,\n    //The type of a {@link LexerPushModeAction} action.\n    PUSH_MODE: 5,\n    //The type of a {@link LexerSkipAction} action.\n    SKIP: 6,\n    //The type of a {@link LexerTypeAction} action.\n    TYPE: 7\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/OrderedATNConfigSet.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNConfigSet from \"./ATNConfigSet.js\";\nimport HashSet from \"../misc/HashSet.js\";\n\nexport default class OrderedATNConfigSet extends ATNConfigSet {\n    constructor() {\n        super();\n        this.configLookup = new HashSet();\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ParserATNSimulator.d.ts",
    "content": "import {ATNSimulator} from \"./ATNSimulator.js\";\nimport {ParserRuleContext} from \"../context/index.js\";\nimport {TokenStream} from \"../TokenStream.js\";\nimport {Recognizer} from \"../Recognizer.js\";\nimport {ATN} from \"./ATN.js\";\nimport {PredictionContextCache} from \"./PredictionContextCache.js\";\nimport {DFA} from \"../dfa/index.js\";\nimport {PredictionMode} from \"./PredictionMode.js\";\nimport {Token} from \"../Token.js\";\n\nexport declare class ParserATNSimulator extends ATNSimulator {\n\n    predictionMode: PredictionMode;\n    decisionToDFA: DFA[];\n    atn: ATN;\n    debug?: boolean;\n    trace_atn_sim?: boolean;\n\n    constructor(recog: Recognizer<Token>, atn: ATN, decisionToDFA: DFA[], sharedContextCache: PredictionContextCache);\n    adaptivePredict(input: TokenStream, decision: number, outerContext: ParserRuleContext) : number;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/ParserATNSimulator.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport ATN from './ATN.js';\nimport ATNState from '../state/ATNState.js';\nimport RuleStopState from '../state/RuleStopState.js';\nimport ATNConfig from './ATNConfig.js';\nimport ATNConfigSet from './ATNConfigSet.js';\nimport Token from '../Token.js';\nimport DFAState from '../dfa/DFAState.js';\nimport PredPrediction from '../dfa/PredPrediction.js';\nimport ATNSimulator from './ATNSimulator.js';\nimport PredictionMode from './PredictionMode.js';\nimport RuleContext from '../context/RuleContext.js';\nimport SemanticContext from './SemanticContext.js';\nimport PredictionContext from '../context/PredictionContext.js';\nimport Interval from '../misc/Interval.js';\nimport Transition from '../transition/Transition.js';\nimport SetTransition from '../transition/SetTransition.js';\nimport NotSetTransition from '../transition/NotSetTransition.js';\nimport RuleTransition from '../transition/RuleTransition.js';\nimport ActionTransition from '../transition/ActionTransition.js';\nimport NoViableAltException from '../error/NoViableAltException.js';\nimport SingletonPredictionContext from '../context/SingletonPredictionContext.js';\nimport {predictionContextFromRuleContext} from '../context/PredictionContextUtils.js';\nimport AtomTransition from \"../transition/AtomTransition.js\";\nimport arrayToString from \"../utils/arrayToString.js\";\nimport BitSet from \"../misc/BitSet.js\";\nimport DoubleDict from \"../utils/DoubleDict.js\";\nimport HashSet from \"../misc/HashSet.js\";\n\n/**\n * The embodiment of the adaptive LL(*), ALL(*), parsing strategy.\n *\n * <p>\n * The basic complexity of the adaptive strategy makes it harder to understand.\n * We begin with ATN simulation to build paths in a DFA. Subsequent prediction\n * requests go through the DFA first. If they reach a state without an edge for\n * the current symbol, the algorithm fails over to the ATN simulation to\n * complete the DFA path for the current input (until it finds a conflict state\n * or uniquely predicting state).</p>\n *\n * <p>\n * All of that is done without using the outer context because we want to create\n * a DFA that is not dependent upon the rule invocation stack when we do a\n * prediction. One DFA works in all contexts. We avoid using context not\n * necessarily because it's slower, although it can be, but because of the DFA\n * caching problem. The closure routine only considers the rule invocation stack\n * created during prediction beginning in the decision rule. For example, if\n * prediction occurs without invoking another rule's ATN, there are no context\n * stacks in the configurations. When lack of context leads to a conflict, we\n * don't know if it's an ambiguity or a weakness in the strong LL(*) parsing\n * strategy (versus full LL(*)).</p>\n *\n * <p>\n * When SLL yields a configuration set with conflict, we rewind the input and\n * retry the ATN simulation, this time using full outer context without adding\n * to the DFA. Configuration context stacks will be the full invocation stacks\n * from the start rule. If we get a conflict using full context, then we can\n * definitively say we have a true ambiguity for that input sequence. If we\n * don't get a conflict, it implies that the decision is sensitive to the outer\n * context. (It is not context-sensitive in the sense of context-sensitive\n * grammars.)</p>\n *\n * <p>\n * The next time we reach this DFA state with an SLL conflict, through DFA\n * simulation, we will again retry the ATN simulation using full context mode.\n * This is slow because we can't save the results and have to \"interpret\" the\n * ATN each time we get that input.</p>\n *\n * <p>\n * <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>\n *\n * <p>\n * We could cache results from full context to predicted alternative easily and\n * that saves a lot of time but doesn't work in presence of predicates. The set\n * of visible predicates from the ATN start state changes depending on the\n * context, because closure can fall off the end of a rule. I tried to cache\n * tuples (stack context, semantic context, predicted alt) but it was slower\n * than interpreting and much more complicated. Also required a huge amount of\n * memory. The goal is not to create the world's fastest parser anyway. I'd like\n * to keep this algorithm simple. By launching multiple threads, we can improve\n * the speed of parsing across a large number of files.</p>\n *\n * <p>\n * There is no strict ordering between the amount of input used by SLL vs LL,\n * which makes it really hard to build a cache for full context. Let's say that\n * we have input A B C that leads to an SLL conflict with full context X. That\n * implies that using X we might only use A B but we could also use A B C D to\n * resolve conflict. Input A B C D could predict alternative 1 in one position\n * in the input and A B C E could predict alternative 2 in another position in\n * input. The conflicting SLL configurations could still be non-unique in the\n * full context prediction, which would lead us to requiring more input than the\n * original A B C.\tTo make a\tprediction cache work, we have to track\tthe exact\n * input\tused during the previous prediction. That amounts to a cache that maps\n * X to a specific DFA for that context.</p>\n *\n * <p>\n * Something should be done for left-recursive expression predictions. They are\n * likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry\n * with full LL thing Sam does.</p>\n *\n * <p>\n * <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>\n *\n * <p>\n * We avoid doing full context retry when the outer context is empty, we did not\n * dip into the outer context by falling off the end of the decision state rule,\n * or when we force SLL mode.</p>\n *\n * <p>\n * As an example of the not dip into outer context case, consider as super\n * constructor calls versus function calls. One grammar might look like\n * this:</p>\n *\n * <pre>\n * ctorBody\n *   : '{' superCall? stat* '}'\n *   ;\n * </pre>\n *\n * <p>\n * Or, you might see something like</p>\n *\n * <pre>\n * stat\n *   : superCall ';'\n *   | expression ';'\n *   | ...\n *   ;\n * </pre>\n *\n * <p>\n * In both cases I believe that no closure operations will dip into the outer\n * context. In the first case ctorBody in the worst case will stop at the '}'.\n * In the 2nd case it should stop at the ';'. Both cases should stay within the\n * entry rule and not dip into the outer context.</p>\n *\n * <p>\n * <strong>PREDICATES</strong></p>\n *\n * <p>\n * Predicates are always evaluated if present in either SLL or LL both. SLL and\n * LL simulation deals with predicates differently. SLL collects predicates as\n * it performs closure operations like ANTLR v3 did. It delays predicate\n * evaluation until it reaches and accept state. This allows us to cache the SLL\n * ATN simulation whereas, if we had evaluated predicates on-the-fly during\n * closure, the DFA state configuration sets would be different and we couldn't\n * build up a suitable DFA.</p>\n *\n * <p>\n * When building a DFA accept state during ATN simulation, we evaluate any\n * predicates and return the sole semantically valid alternative. If there is\n * more than 1 alternative, we report an ambiguity. If there are 0 alternatives,\n * we throw an exception. Alternatives without predicates act like they have\n * true predicates. The simple way to think about it is to strip away all\n * alternatives with false predicates and choose the minimum alternative that\n * remains.</p>\n *\n * <p>\n * When we start in the DFA and reach an accept state that's predicated, we test\n * those and return the minimum semantically viable alternative. If no\n * alternatives are viable, we throw an exception.</p>\n *\n * <p>\n * During full LL ATN simulation, closure always evaluates predicates and\n * on-the-fly. This is crucial to reducing the configuration set size during\n * closure. It hits a landmine when parsing with the Java grammar, for example,\n * without this on-the-fly evaluation.</p>\n *\n * <p>\n * <strong>SHARING DFA</strong></p>\n *\n * <p>\n * All instances of the same parser share the same decision DFAs through a\n * static field. Each instance gets its own ATN simulator but they share the\n * same {@link //decisionToDFA} field. They also share a\n * {@link PredictionContextCache} object that makes sure that all\n * {@link PredictionContext} objects are shared among the DFA states. This makes\n * a big size difference.</p>\n *\n * <p>\n * <strong>THREAD SAFETY</strong></p>\n *\n * <p>\n * The {@link ParserATNSimulator} locks on the {@link //decisionToDFA} field when\n * it adds a new DFA object to that array. {@link //addDFAEdge}\n * locks on the DFA for the current decision when setting the\n * {@link DFAState//edges} field. {@link //addDFAState} locks on\n * the DFA for the current decision when looking up a DFA state to see if it\n * already exists. We must make sure that all requests to add DFA states that\n * are equivalent result in the same shared DFA object. This is because lots of\n * threads will be trying to update the DFA at once. The\n * {@link //addDFAState} method also locks inside the DFA lock\n * but this time on the shared context cache when it rebuilds the\n * configurations' {@link PredictionContext} objects using cached\n * subgraphs/nodes. No other locking occurs, even during DFA simulation. This is\n * safe as long as we can guarantee that all threads referencing\n * {@code s.edge[t]} get the same physical target {@link DFAState}, or\n * {@code null}. Once into the DFA, the DFA simulation does not reference the\n * {@link DFA//states} map. It follows the {@link DFAState//edges} field to new\n * targets. The DFA simulator will either find {@link DFAState//edges} to be\n * {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or\n * {@code dfa.edges[t]} to be non-null. The\n * {@link //addDFAEdge} method could be racing to set the field\n * but in either case the DFA simulator works; if {@code null}, and requests ATN\n * simulation. It could also race trying to get {@code dfa.edges[t]}, but either\n * way it will work because it's not doing a test and set operation.</p>\n *\n * <p>\n * <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage\n * Parsing)</strong></p>\n *\n * <p>\n * Sam pointed out that if SLL does not give a syntax error, then there is no\n * point in doing full LL, which is slower. We only have to try LL if we get a\n * syntax error. For maximum speed, Sam starts the parser set to pure SLL\n * mode with the {@link BailErrorStrategy}:</p>\n *\n * <pre>\n * parser.{@link Parser//getInterpreter() getInterpreter()}.{@link //setPredictionMode setPredictionMode}{@code (}{@link PredictionMode//SLL}{@code )};\n * parser.{@link Parser//setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());\n * </pre>\n *\n * <p>\n * If it does not get a syntax error, then we're done. If it does get a syntax\n * error, we need to retry with the combined SLL/LL strategy.</p>\n *\n * <p>\n * The reason this works is as follows. If there are no SLL conflicts, then the\n * grammar is SLL (at least for that input set). If there is an SLL conflict,\n * the full LL analysis must yield a set of viable alternatives which is a\n * subset of the alternatives reported by SLL. If the LL set is a singleton,\n * then the grammar is LL but not SLL. If the LL set is the same size as the SLL\n * set, the decision is SLL. If the LL set has size &gt; 1, then that decision\n * is truly ambiguous on the current input. If the LL set is smaller, then the\n * SLL conflict resolution might choose an alternative that the full LL would\n * rule out as a possibility based upon better context information. If that's\n * the case, then the SLL parse will definitely get an error because the full LL\n * analysis says it's not viable. If SLL conflict resolution chooses an\n * alternative within the LL set, them both SLL and LL would choose the same\n * alternative because they both choose the minimum of multiple conflicting\n * alternatives.</p>\n *\n * <p>\n * Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and\n * a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL\n * parsing will get an error because SLL will pursue alternative 1. If\n * <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will\n * choose the same alternative because alternative one is the minimum of either\n * set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax\n * error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>\n *\n * <p>\n * Of course, if the input is invalid, then we will get an error for sure in\n * both SLL and LL parsing. Erroneous input will therefore require 2 passes over\n * the input.</p>\n */\nexport default class ParserATNSimulator extends ATNSimulator {\n    constructor(parser, atn, decisionToDFA, sharedContextCache) {\n        super(atn, sharedContextCache);\n        this.parser = parser;\n        this.decisionToDFA = decisionToDFA;\n        // SLL, LL, or LL + exact ambig detection?//\n        this.predictionMode = PredictionMode.LL;\n        // LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n        this._input = null;\n        this._startIndex = 0;\n        this._outerContext = null;\n        this._dfa = null;\n        /**\n         * Each prediction operation uses a cache for merge of prediction contexts.\n         *  Don't keep around as it wastes huge amounts of memory. DoubleKeyMap\n         *  isn't synchronized but we're ok since two threads shouldn't reuse same\n         *  parser/atnsim object because it can only handle one input at a time.\n         *  This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid\n         *  the merge if we ever see a and b again.  Note that (b,a)&rarr;c should\n         *  also be examined during cache lookup.\n         */\n        this.mergeCache = null;\n        this.debug = false;\n        this.debug_closure = false;\n        this.debug_add = false;\n        this.trace_atn_sim = false;\n        this.dfa_debug = false;\n        this.retry_debug = false;\n    }\n\n    reset() {}\n\n    adaptivePredict(input, decision, outerContext) {\n        if (this.debug || this.trace_atn_sim) {\n            console.log(\"adaptivePredict decision \" + decision +\n                                   \" exec LA(1)==\" + this.getLookaheadName(input) +\n                                   \" line \" + input.LT(1).line + \":\" +\n                                   input.LT(1).column);\n        }\n        this._input = input;\n        this._startIndex = input.index;\n        this._outerContext = outerContext;\n\n        const dfa = this.decisionToDFA[decision];\n        this._dfa = dfa;\n        const m = input.mark();\n        const index = input.index;\n\n        // Now we are certain to have a specific decision's DFA\n        // But, do we still need an initial state?\n        try {\n            let s0;\n            if (dfa.precedenceDfa) {\n                // the start state for a precedence DFA depends on the current\n                // parser precedence, and is provided by a DFA method.\n                s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence());\n            } else {\n                // the start state for a \"regular\" DFA is just s0\n                s0 = dfa.s0;\n            }\n            if (s0===null) {\n                if (outerContext===null) {\n                    outerContext = RuleContext.EMPTY;\n                }\n                if (this.debug ) {\n                    console.log(\"predictATN decision \" + dfa.decision +\n                                       \" exec LA(1)==\" + this.getLookaheadName(input) +\n                                       \", outerContext=\" + outerContext.toString(this.parser.ruleNames));\n                }\n\n                const fullCtx = false;\n                let s0_closure = this.computeStartState(dfa.atnStartState, RuleContext.EMPTY, fullCtx);\n\n                if( dfa.precedenceDfa) {\n                    // If this is a precedence DFA, we use applyPrecedenceFilter\n                    // to convert the computed start state to a precedence start\n                    // state. We then use DFA.setPrecedenceStartState to set the\n                    // appropriate start state for the precedence level rather\n                    // than simply setting DFA.s0.\n                    //\n                    dfa.s0.configs = s0_closure; // not used for prediction but useful to know start configs anyway\n                    s0_closure = this.applyPrecedenceFilter(s0_closure);\n                    s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));\n                    dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0);\n                } else {\n                    s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));\n                    dfa.s0 = s0;\n                }\n            }\n            const alt = this.execATN(dfa, s0, input, index, outerContext);\n            if (this.debug) {\n                console.log(\"DFA after predictATN: \" + dfa.toString(this.parser.literalNames, this.parser.symbolicNames));\n            }\n            return alt;\n        } finally {\n            this._dfa = null;\n            this.mergeCache = null; // wack cache after each prediction\n            input.seek(index);\n            input.release(m);\n        }\n    }\n\n    /**\n     * Performs ATN simulation to compute a predicted alternative based\n     *  upon the remaining input, but also updates the DFA cache to avoid\n     *  having to traverse the ATN again for the same input sequence.\n     *\n     * There are some key conditions we're looking for after computing a new\n     * set of ATN configs (proposed DFA state):\n     *       if the set is empty, there is no viable alternative for current symbol\n     *       does the state uniquely predict an alternative?\n     *       does the state have a conflict that would prevent us from\n     *         putting it on the work list?\n     *\n     * We also have some key operations to do:\n     *       add an edge from previous DFA state to potentially new DFA state, D,\n     *         upon current symbol but only if adding to work list, which means in all\n     *         cases except no viable alternative (and possibly non-greedy decisions?)\n     *       collecting predicates and adding semantic context to DFA accept states\n     *       adding rule context to context-sensitive DFA accept states\n     *       consuming an input symbol\n     *       reporting a conflict\n     *       reporting an ambiguity\n     *       reporting a context sensitivity\n     *       reporting insufficient predicates\n     *\n     * cover these cases:\n     *    dead end\n     *    single alt\n     *    single alt + preds\n     *    conflict\n     *    conflict + preds\n     *\n     */\n    execATN(dfa, s0, input, startIndex, outerContext ) {\n        if (this.debug || this.trace_atn_sim) {\n            console.log(\"execATN decision \" + dfa.decision +\n                        \", DFA state \" + s0 +\n                        \", LA(1)==\" + this.getLookaheadName(input) +\n                        \" line \" + input.LT(1).line + \":\" + input.LT(1).column);\n        }\n        let alt;\n        let previousD = s0;\n\n        if (this.debug) {\n            console.log(\"s0 = \" + s0);\n        }\n        let t = input.LA(1);\n        for(;;) { // while more work\n            let D = this.getExistingTargetState(previousD, t);\n            if(D===null) {\n                D = this.computeTargetState(dfa, previousD, t);\n            }\n            if(D===ATNSimulator.ERROR) {\n                // if any configs in previous dipped into outer context, that\n                // means that input up to t actually finished entry rule\n                // at least for SLL decision. Full LL doesn't dip into outer\n                // so don't need special case.\n                // We will get an error no matter what so delay until after\n                // decision; better error message. Also, no reachable target\n                // ATN states in SLL implies LL will also get nowhere.\n                // If conflict in states that dip out, choose min since we\n                // will get error no matter what.\n                const e = this.noViableAlt(input, outerContext, previousD.configs, startIndex);\n                input.seek(startIndex);\n                alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);\n                if(alt!==ATN.INVALID_ALT_NUMBER) {\n                    return alt;\n                } else {\n                    throw e;\n                }\n            }\n            if(D.requiresFullContext && this.predictionMode !== PredictionMode.SLL) {\n                // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n                let conflictingAlts = null;\n                if (D.predicates!==null) {\n                    if (this.debug) {\n                        console.log(\"DFA state has preds in DFA sim LL failover\");\n                    }\n                    const conflictIndex = input.index;\n                    if(conflictIndex !== startIndex) {\n                        input.seek(startIndex);\n                    }\n                    conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true);\n                    if (conflictingAlts.length===1) {\n                        if(this.debug) {\n                            console.log(\"Full LL avoided\");\n                        }\n                        return conflictingAlts.minValue();\n                    }\n                    if (conflictIndex !== startIndex) {\n                        // restore the index so reporting the fallback to full\n                        // context occurs with the index at the correct spot\n                        input.seek(conflictIndex);\n                    }\n                }\n                if (this.dfa_debug) {\n                    console.log(\"ctx sensitive state \" + outerContext +\" in \" + D);\n                }\n                const fullCtx = true;\n                const s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx);\n                this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index);\n                alt = this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext);\n                return alt;\n            }\n            if (D.isAcceptState) {\n                if (D.predicates===null) {\n                    return D.prediction;\n                }\n                const stopIndex = input.index;\n                input.seek(startIndex);\n                const alts = this.evalSemanticContext(D.predicates, outerContext, true);\n                if (alts.length===0) {\n                    throw this.noViableAlt(input, outerContext, D.configs, startIndex);\n                } else if (alts.length===1) {\n                    return alts.minValue();\n                } else {\n                    // report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported.\n                    this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);\n                    return alts.minValue();\n                }\n            }\n            previousD = D;\n\n            if (t !== Token.EOF) {\n                input.consume();\n                t = input.LA(1);\n            }\n        }\n    }\n\n    /**\n     * Get an existing target state for an edge in the DFA. If the target state\n     * for the edge has not yet been computed or is otherwise not available,\n     * this method returns {@code null}.\n     *\n     * @param previousD The current DFA state\n     * @param t The next input symbol\n     * @return The existing target DFA state for the given input symbol\n     * {@code t}, or {@code null} if the target state for this edge is not\n     * already cached\n     */\n    getExistingTargetState(previousD, t) {\n        const edges = previousD.edges;\n        if (edges===null) {\n            return null;\n        } else {\n            return edges[t + 1] || null;\n        }\n    }\n\n    /**\n     * Compute a target state for an edge in the DFA, and attempt to add the\n     * computed state and corresponding edge to the DFA.\n     *\n     * @param dfa The DFA\n     * @param previousD The current DFA state\n     * @param t The next input symbol\n     *\n     * @return The computed target DFA state for the given input symbol\n     * {@code t}. If {@code t} does not lead to a valid DFA state, this method\n     * returns {@link //ERROR\n     */\n    computeTargetState(dfa, previousD, t) {\n       const reach = this.computeReachSet(previousD.configs, t, false);\n        if(reach===null) {\n            this.addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR);\n            return ATNSimulator.ERROR;\n        }\n        // create new target state; we'll add to DFA after it's complete\n        let D = new DFAState(null, reach);\n\n        const predictedAlt = this.getUniqueAlt(reach);\n\n        if (this.debug) {\n            const altSubSets = PredictionMode.getConflictingAltSubsets(reach);\n            console.log(\"SLL altSubSets=\" + arrayToString(altSubSets) +\n                        /*\", previous=\" + previousD.configs + */\n                        \", configs=\" + reach +\n                        \", predict=\" + predictedAlt +\n                        \", allSubsetsConflict=\" +\n                        PredictionMode.allSubsetsConflict(altSubSets) + \", conflictingAlts=\" +\n                        this.getConflictingAlts(reach));\n        }\n        if (predictedAlt!==ATN.INVALID_ALT_NUMBER) {\n            // NO CONFLICT, UNIQUELY PREDICTED ALT\n            D.isAcceptState = true;\n            D.configs.uniqueAlt = predictedAlt;\n            D.prediction = predictedAlt;\n        } else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) {\n            // MORE THAN ONE VIABLE ALTERNATIVE\n            D.configs.conflictingAlts = this.getConflictingAlts(reach);\n            D.requiresFullContext = true;\n            // in SLL-only mode, we will stop at this state and return the minimum alt\n            D.isAcceptState = true;\n            D.prediction = D.configs.conflictingAlts.minValue();\n        }\n        if (D.isAcceptState && D.configs.hasSemanticContext) {\n            this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision));\n            if( D.predicates!==null) {\n                D.prediction = ATN.INVALID_ALT_NUMBER;\n            }\n        }\n        // all adds to dfa are done after we've created full D state\n        D = this.addDFAEdge(dfa, previousD, t, D);\n        return D;\n    }\n\n    predicateDFAState(dfaState, decisionState) {\n        // We need to test all predicates, even in DFA states that\n        // uniquely predict alternative.\n        const nalts = decisionState.transitions.length;\n        // Update DFA so reach becomes accept state with (predicate,alt)\n        // pairs if preds found for conflicting alts\n        const altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs);\n        const altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts);\n        if (altToPred!==null) {\n            dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred);\n            dfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds\n        } else {\n            // There are preds in configs but they might go away\n            // when OR'd together like {p}? || NONE == NONE. If neither\n            // alt has preds, resolve to min alt\n            dfaState.prediction = altsToCollectPredsFrom.minValue();\n        }\n    }\n\n// comes back with reach.uniqueAlt set to a valid alt\n    execATNWithFullContext(dfa, D, // how far we got before failing over\n                                         s0,\n                                         input,\n                                         startIndex,\n                                         outerContext) {\n        if (this.debug || this.trace_atn_sim) {\n            console.log(\"execATNWithFullContext \"+s0);\n        }\n        const fullCtx = true;\n        let foundExactAmbig = false;\n        let reach;\n        let previous = s0;\n        input.seek(startIndex);\n        let t = input.LA(1);\n        let predictedAlt = -1;\n        for (;;) { // while more work\n            reach = this.computeReachSet(previous, t, fullCtx);\n            if (reach===null) {\n                // if any configs in previous dipped into outer context, that\n                // means that input up to t actually finished entry rule\n                // at least for LL decision. Full LL doesn't dip into outer\n                // so don't need special case.\n                // We will get an error no matter what so delay until after\n                // decision; better error message. Also, no reachable target\n                // ATN states in SLL implies LL will also get nowhere.\n                // If conflict in states that dip out, choose min since we\n                // will get error no matter what.\n                const e = this.noViableAlt(input, outerContext, previous, startIndex);\n                input.seek(startIndex);\n                const alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);\n                if(alt!==ATN.INVALID_ALT_NUMBER) {\n                    return alt;\n                } else {\n                    throw e;\n                }\n            }\n            const altSubSets = PredictionMode.getConflictingAltSubsets(reach);\n            if(this.debug) {\n                console.log(\"LL altSubSets=\" + altSubSets + \", predict=\" +\n                      PredictionMode.getUniqueAlt(altSubSets) + \", resolvesToJustOneViableAlt=\" +\n                      PredictionMode.resolvesToJustOneViableAlt(altSubSets));\n            }\n            reach.uniqueAlt = this.getUniqueAlt(reach);\n            // unique prediction?\n            if(reach.uniqueAlt!==ATN.INVALID_ALT_NUMBER) {\n                predictedAlt = reach.uniqueAlt;\n                break;\n            } else if (this.predictionMode !== PredictionMode.LL_EXACT_AMBIG_DETECTION) {\n                predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets);\n                if(predictedAlt !== ATN.INVALID_ALT_NUMBER) {\n                    break;\n                }\n            } else {\n                // In exact ambiguity mode, we never try to terminate early.\n                // Just keeps scarfing until we know what the conflict is\n                if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) {\n                    foundExactAmbig = true;\n                    predictedAlt = PredictionMode.getSingleViableAlt(altSubSets);\n                    break;\n                }\n                // else there are multiple non-conflicting subsets or\n                // we're not sure what the ambiguity is yet.\n                // So, keep going.\n            }\n            previous = reach;\n            if( t !== Token.EOF) {\n                input.consume();\n                t = input.LA(1);\n            }\n        }\n        // If the configuration set uniquely predicts an alternative,\n        // without conflict, then we know that it's a full LL decision\n        // not SLL.\n        if (reach.uniqueAlt !== ATN.INVALID_ALT_NUMBER ) {\n            this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index);\n            return predictedAlt;\n        }\n        // We do not check predicates here because we have checked them\n        // on-the-fly when doing full context prediction.\n\n        //\n        // In non-exact ambiguity detection mode, we might\tactually be able to\n        // detect an exact ambiguity, but I'm not going to spend the cycles\n        // needed to check. We only emit ambiguity warnings in exact ambiguity\n        // mode.\n        //\n        // For example, we might know that we have conflicting configurations.\n        // But, that does not mean that there is no way forward without a\n        // conflict. It's possible to have nonconflicting alt subsets as in:\n\n        // altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n\n        // from\n        //\n        //    [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n        //     (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n        //\n        // In this case, (17,1,[5 $]) indicates there is some next sequence that\n        // would resolve this without conflict to alternative 1. Any other viable\n        // next sequence, however, is associated with a conflict.  We stop\n        // looking for input because no amount of further lookahead will alter\n        // the fact that we should predict alternative 1.  We just can't say for\n        // sure that there is an ambiguity without looking further.\n\n        this.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, null, reach);\n\n        return predictedAlt;\n    }\n\n    computeReachSet(closure, t, fullCtx) {\n        if (this.debug) {\n            console.log(\"in computeReachSet, starting closure: \" + closure);\n        }\n        if( this.mergeCache===null) {\n            this.mergeCache = new DoubleDict();\n        }\n        const intermediate = new ATNConfigSet(fullCtx);\n\n        // Configurations already in a rule stop state indicate reaching the end\n        // of the decision rule (local context) or end of the start rule (full\n        // context). Once reached, these configurations are never updated by a\n        // closure operation, so they are handled separately for the performance\n        // advantage of having a smaller intermediate set when calling closure.\n        //\n        // For full-context reach operations, separate handling is required to\n        // ensure that the alternative matching the longest overall sequence is\n        // chosen when multiple such configurations can match the input.\n\n        let skippedStopStates = null;\n\n        // First figure out where we can reach on input t\n        for (let i=0; i<closure.items.length;i++) {\n            const c = closure.items[i];\n            if(this.debug) {\n                console.log(\"testing \" + this.getTokenName(t) + \" at \" + c);\n            }\n            if (c.state instanceof RuleStopState) {\n                if (fullCtx || t === Token.EOF) {\n                    if (skippedStopStates===null) {\n                        skippedStopStates = [];\n                    }\n                    skippedStopStates.push(c);\n                    if(this.debug_add) {\n                        console.log(\"added \" + c + \" to skippedStopStates\");\n                    }\n                }\n                continue;\n            }\n            for(let j=0;j<c.state.transitions.length;j++) {\n                const trans = c.state.transitions[j];\n                const target = this.getReachableTarget(trans, t);\n                if (target!==null) {\n                    const cfg = new ATNConfig({state:target}, c);\n                    intermediate.add(cfg, this.mergeCache);\n                    if(this.debug_add) {\n                        console.log(\"added \" + cfg + \" to intermediate\");\n                    }\n                }\n            }\n        }\n        // Now figure out where the reach operation can take us...\n        let reach = null;\n\n        // This block optimizes the reach operation for intermediate sets which\n        // trivially indicate a termination state for the overall\n        // adaptivePredict operation.\n        //\n        // The conditions assume that intermediate\n        // contains all configurations relevant to the reach set, but this\n        // condition is not true when one or more configurations have been\n        // withheld in skippedStopStates, or when the current symbol is EOF.\n        //\n        if (skippedStopStates===null && t!==Token.EOF) {\n            if (intermediate.items.length===1) {\n                // Don't pursue the closure if there is just one state.\n                // It can only have one alternative; just add to result\n                // Also don't pursue the closure if there is unique alternative\n                // among the configurations.\n                reach = intermediate;\n            } else if (this.getUniqueAlt(intermediate)!==ATN.INVALID_ALT_NUMBER) {\n                // Also don't pursue the closure if there is unique alternative\n                // among the configurations.\n                reach = intermediate;\n            }\n        }\n        // If the reach set could not be trivially determined, perform a closure\n        // operation on the intermediate set to compute its initial value.\n        //\n        if (reach===null) {\n            reach = new ATNConfigSet(fullCtx);\n            const closureBusy = new HashSet();\n            const treatEofAsEpsilon = t === Token.EOF;\n            for (let k=0; k<intermediate.items.length;k++) {\n                this.closure(intermediate.items[k], reach, closureBusy, false, fullCtx, treatEofAsEpsilon);\n            }\n        }\n        if (t === Token.EOF) {\n            // After consuming EOF no additional input is possible, so we are\n            // only interested in configurations which reached the end of the\n            // decision rule (local context) or end of the start rule (full\n            // context). Update reach to contain only these configurations. This\n            // handles both explicit EOF transitions in the grammar and implicit\n            // EOF transitions following the end of the decision or start rule.\n            //\n            // When reach==intermediate, no closure operation was performed. In\n            // this case, removeAllConfigsNotInRuleStopState needs to check for\n            // reachable rule stop states as well as configurations already in\n            // a rule stop state.\n            //\n            // This is handled before the configurations in skippedStopStates,\n            // because any configurations potentially added from that list are\n            // already guaranteed to meet this condition whether or not it's\n            // required.\n            //\n            reach = this.removeAllConfigsNotInRuleStopState(reach, reach === intermediate);\n        }\n        // If skippedStopStates!==null, then it contains at least one\n        // configuration. For full-context reach operations, these\n        // configurations reached the end of the start rule, in which case we\n        // only add them back to reach if no configuration during the current\n        // closure operation reached such a state. This ensures adaptivePredict\n        // chooses an alternative matching the longest overall sequence when\n        // multiple alternatives are viable.\n        //\n        if (skippedStopStates!==null && ( (! fullCtx) || (! PredictionMode.hasConfigInRuleStopState(reach)))) {\n            for (let l=0; l<skippedStopStates.length;l++) {\n                reach.add(skippedStopStates[l], this.mergeCache);\n            }\n        }\n\n        if ( this.trace_atn_sim ) {\n            console.log(\"computeReachSet \"+closure+\" -> \"+reach);\n        }\n\n        if (reach.items.length===0) {\n            return null;\n        } else {\n            return reach;\n        }\n    }\n\n    /**\n     * Return a configuration set containing only the configurations from\n     * {@code configs} which are in a {@link RuleStopState}. If all\n     * configurations in {@code configs} are already in a rule stop state, this\n     * method simply returns {@code configs}.\n     *\n     * <p>When {@code lookToEndOfRule} is true, this method uses\n     * {@link ATN//nextTokens} for each configuration in {@code configs} which is\n     * not already in a rule stop state to see if a rule stop state is reachable\n     * from the configuration via epsilon-only transitions.</p>\n     *\n     * @param configs the configuration set to update\n     * @param lookToEndOfRule when true, this method checks for rule stop states\n     * reachable by epsilon-only transitions from each configuration in\n     * {@code configs}.\n     *\n     * @return {@code configs} if all configurations in {@code configs} are in a\n     * rule stop state, otherwise return a new configuration set containing only\n     * the configurations from {@code configs} which are in a rule stop state\n     */\n    removeAllConfigsNotInRuleStopState(configs, lookToEndOfRule) {\n        if (PredictionMode.allConfigsInRuleStopStates(configs)) {\n            return configs;\n        }\n        const result = new ATNConfigSet(configs.fullCtx);\n        for(let i=0; i<configs.items.length;i++) {\n            const config = configs.items[i];\n            if (config.state instanceof RuleStopState) {\n                result.add(config, this.mergeCache);\n                continue;\n            }\n            if (lookToEndOfRule && config.state.epsilonOnlyTransitions) {\n                const nextTokens = this.atn.nextTokens(config.state);\n                if (nextTokens.contains(Token.EPSILON)) {\n                    const endOfRuleState = this.atn.ruleToStopState[config.state.ruleIndex];\n                    result.add(new ATNConfig({state:endOfRuleState}, config), this.mergeCache);\n                }\n            }\n        }\n        return result;\n    }\n\n    computeStartState(p, ctx, fullCtx) {\n        // always at least the implicit call to start rule\n        const initialContext = predictionContextFromRuleContext(this.atn, ctx);\n        const configs = new ATNConfigSet(fullCtx);\n\n        if ( this.trace_atn_sim ) {\n            console.log(\"computeStartState from ATN state \" + p + \" initialContext=\" + initialContext.toString(this.parser));\n        }\n\n        for(let i=0;i<p.transitions.length;i++) {\n            const target = p.transitions[i].target;\n            const c = new ATNConfig({ state:target, alt:i+1, context:initialContext }, null);\n            const closureBusy = new HashSet();\n            this.closure(c, configs, closureBusy, true, fullCtx, false);\n        }\n        return configs;\n    }\n\n    /**\n     * This method transforms the start state computed by\n     * {@link //computeStartState} to the special start state used by a\n     * precedence DFA for a particular precedence value. The transformation\n     * process applies the following changes to the start state's configuration\n     * set.\n     *\n     * <ol>\n     * <li>Evaluate the precedence predicates for each configuration using\n     * {@link SemanticContext//evalPrecedence}.</li>\n     * <li>Remove all configurations which predict an alternative greater than\n     * 1, for which another configuration that predicts alternative 1 is in the\n     * same ATN state with the same prediction context. This transformation is\n     * valid for the following reasons:\n     * <ul>\n     * <li>The closure block cannot contain any epsilon transitions which bypass\n     * the body of the closure, so all states reachable via alternative 1 are\n     * part of the precedence alternatives of the transformed left-recursive\n     * rule.</li>\n     * <li>The \"primary\" portion of a left recursive rule cannot contain an\n     * epsilon transition, so the only way an alternative other than 1 can exist\n     * in a state that is also reachable via alternative 1 is by nesting calls\n     * to the left-recursive rule, with the outer calls not being at the\n     * preferred precedence level.</li>\n     * </ul>\n     * </li>\n     * </ol>\n     *\n     * <p>\n     * The prediction context must be considered by this filter to address\n     * situations like the following.\n     * </p>\n     * <code>\n     * <pre>\n     * grammar TA;\n     * prog: statement* EOF;\n     * statement: letterA | statement letterA 'b' ;\n     * letterA: 'a';\n     * </pre>\n     * </code>\n     * <p>\n     * If the above grammar, the ATN state immediately before the token\n     * reference {@code 'a'} in {@code letterA} is reachable from the left edge\n     * of both the primary and closure blocks of the left-recursive rule\n     * {@code statement}. The prediction context associated with each of these\n     * configurations distinguishes between them, and prevents the alternative\n     * which stepped out to {@code prog} (and then back in to {@code statement}\n     * from being eliminated by the filter.\n     * </p>\n     *\n     * @param configs The configuration set computed by\n     * {@link //computeStartState} as the start state for the DFA.\n     * @return The transformed configuration set representing the start state\n     * for a precedence DFA at a particular precedence level (determined by\n     * calling {@link Parser//getPrecedence})\n     */\n    applyPrecedenceFilter(configs) {\n        let config;\n        const statesFromAlt1 = [];\n        const configSet = new ATNConfigSet(configs.fullCtx);\n        for(let i=0; i<configs.items.length; i++) {\n            config = configs.items[i];\n            // handle alt 1 first\n            if (config.alt !== 1) {\n                continue;\n            }\n            const updatedContext = config.semanticContext.evalPrecedence(this.parser, this._outerContext);\n            if (updatedContext===null) {\n                // the configuration was eliminated\n                continue;\n            }\n            statesFromAlt1[config.state.stateNumber] = config.context;\n            if (updatedContext !== config.semanticContext) {\n                configSet.add(new ATNConfig({semanticContext:updatedContext}, config), this.mergeCache);\n            } else {\n                configSet.add(config, this.mergeCache);\n            }\n        }\n        for(let i=0; i<configs.items.length; i++) {\n            config = configs.items[i];\n            if (config.alt === 1) {\n                // already handled\n                continue;\n            }\n            // In the future, this elimination step could be updated to also\n            // filter the prediction context for alternatives predicting alt>1\n            // (basically a graph subtraction algorithm).\n            if (!config.precedenceFilterSuppressed) {\n                const context = statesFromAlt1[config.state.stateNumber] || null;\n                if (context!==null && context.equals(config.context)) {\n                    // eliminated\n                    continue;\n                }\n            }\n            configSet.add(config, this.mergeCache);\n        }\n        return configSet;\n    }\n\n    getReachableTarget(trans, ttype) {\n        if (trans.matches(ttype, 0, this.atn.maxTokenType)) {\n            return trans.target;\n        } else {\n            return null;\n        }\n    }\n\n    getPredsForAmbigAlts(ambigAlts, configs, nalts) {\n        // REACH=[1|1|[]|0:0, 1|2|[]|0:1]\n        // altToPred starts as an array of all null contexts. The entry at index i\n        // corresponds to alternative i. altToPred[i] may have one of three values:\n        //   1. null: no ATNConfig c is found such that c.alt==i\n        //   2. SemanticContext.NONE: At least one ATNConfig c exists such that\n        //      c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,\n        //      alt i has at least one unpredicated config.\n        //   3. Non-NONE Semantic Context: There exists at least one, and for all\n        //      ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.\n        //\n        // From this, it is clear that NONE||anything==NONE.\n        //\n        let altToPred = [];\n        for(let i=0;i<configs.items.length;i++) {\n            const c = configs.items[i];\n            if(ambigAlts.get( c.alt )) {\n                altToPred[c.alt] = SemanticContext.orContext(altToPred[c.alt] || null, c.semanticContext);\n            }\n        }\n        let nPredAlts = 0;\n        for (let i =1;i< nalts+1;i++) {\n            const pred = altToPred[i] || null;\n            if (pred===null) {\n                altToPred[i] = SemanticContext.NONE;\n            } else if (pred !== SemanticContext.NONE) {\n                nPredAlts += 1;\n            }\n        }\n        // nonambig alts are null in altToPred\n        if (nPredAlts===0) {\n            altToPred = null;\n        }\n        if (this.debug) {\n            console.log(\"getPredsForAmbigAlts result \" + arrayToString(altToPred));\n        }\n        return altToPred;\n    }\n\n    getPredicatePredictions(ambigAlts, altToPred) {\n        const pairs = [];\n        let containsPredicate = false;\n        for (let i=1; i<altToPred.length;i++) {\n            const pred = altToPred[i];\n            // unpredicated is indicated by SemanticContext.NONE\n            if( ambigAlts!==null && ambigAlts.get( i )) {\n                pairs.push(new PredPrediction(pred, i));\n            }\n            if (pred !== SemanticContext.NONE) {\n                containsPredicate = true;\n            }\n        }\n        if (! containsPredicate) {\n            return null;\n        }\n        return pairs;\n    }\n\n    /**\n     * This method is used to improve the localization of error messages by\n     * choosing an alternative rather than throwing a\n     * {@link NoViableAltException} in particular prediction scenarios where the\n     * {@link //ERROR} state was reached during ATN simulation.\n     *\n     * <p>\n     * The default implementation of this method uses the following\n     * algorithm to identify an ATN configuration which successfully parsed the\n     * decision entry rule. Choosing such an alternative ensures that the\n     * {@link ParserRuleContext} returned by the calling rule will be complete\n     * and valid, and the syntax error will be reported later at a more\n     * localized location.</p>\n     *\n     * <ul>\n     * <li>If a syntactically valid path or paths reach the end of the decision rule and\n     * they are semantically valid if predicated, return the min associated alt.</li>\n     * <li>Else, if a semantically invalid but syntactically valid path exist\n     * or paths exist, return the minimum associated alt.\n     * </li>\n     * <li>Otherwise, return {@link ATN//INVALID_ALT_NUMBER}.</li>\n     * </ul>\n     *\n     * <p>\n     * In some scenarios, the algorithm described above could predict an\n     * alternative which will result in a {@link FailedPredicateException} in\n     * the parser. Specifically, this could occur if the <em>only</em> configuration\n     * capable of successfully parsing to the end of the decision rule is\n     * blocked by a semantic predicate. By choosing this alternative within\n     * {@link //adaptivePredict} instead of throwing a\n     * {@link NoViableAltException}, the resulting\n     * {@link FailedPredicateException} in the parser will identify the specific\n     * predicate which is preventing the parser from successfully parsing the\n     * decision rule, which helps developers identify and correct logic errors\n     * in semantic predicates.\n     * </p>\n     *\n     * @param configs The ATN configurations which were valid immediately before\n     * the {@link //ERROR} state was reached\n     * @param outerContext The is the \\gamma_0 initial parser context from the paper\n     * or the parser stack at the instant before prediction commences.\n     *\n     * @return The value to return from {@link //adaptivePredict}, or\n     * {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not\n     * identified and {@link //adaptivePredict} should report an error instead\n     */\n    getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(configs, outerContext) {\n        const cfgs = this.splitAccordingToSemanticValidity(configs, outerContext);\n        const semValidConfigs = cfgs[0];\n        const semInvalidConfigs = cfgs[1];\n        let alt = this.getAltThatFinishedDecisionEntryRule(semValidConfigs);\n        if (alt!==ATN.INVALID_ALT_NUMBER) { // semantically/syntactically viable path exists\n            return alt;\n        }\n        // Is there a syntactically valid path with a failed pred?\n        if (semInvalidConfigs.items.length>0) {\n            alt = this.getAltThatFinishedDecisionEntryRule(semInvalidConfigs);\n            if (alt!==ATN.INVALID_ALT_NUMBER) { // syntactically viable path exists\n                return alt;\n            }\n        }\n        return ATN.INVALID_ALT_NUMBER;\n    }\n\n    getAltThatFinishedDecisionEntryRule(configs) {\n        const alts = [];\n        for(let i=0;i<configs.items.length; i++) {\n            const c = configs.items[i];\n            if (c.reachesIntoOuterContext>0 || ((c.state instanceof RuleStopState) && c.context.hasEmptyPath())) {\n                if(alts.indexOf(c.alt)<0) {\n                    alts.push(c.alt);\n                }\n            }\n        }\n        if (alts.length===0) {\n            return ATN.INVALID_ALT_NUMBER;\n        } else {\n            return Math.min.apply(null, alts);\n        }\n    }\n\n    /**\n     * Walk the list of configurations and split them according to\n     * those that have preds evaluating to true/false.  If no pred, assume\n     * true pred and include in succeeded set.  Returns Pair of sets.\n     *\n     * Create a new set so as not to alter the incoming parameter.\n     *\n     * Assumption: the input stream has been restored to the starting point\n     * prediction, which is where predicates need to evaluate.*/\n    splitAccordingToSemanticValidity( configs, outerContext) {\n        const succeeded = new ATNConfigSet(configs.fullCtx);\n        const failed = new ATNConfigSet(configs.fullCtx);\n        for(let i=0;i<configs.items.length; i++) {\n            const c = configs.items[i];\n            if (c.semanticContext !== SemanticContext.NONE) {\n                const predicateEvaluationResult = c.semanticContext.evaluate(this.parser, outerContext);\n                if (predicateEvaluationResult) {\n                    succeeded.add(c);\n                } else {\n                    failed.add(c);\n                }\n            } else {\n                succeeded.add(c);\n            }\n        }\n        return [succeeded, failed];\n    }\n\n    /**\n     * Look through a list of predicate/alt pairs, returning alts for the\n     * pairs that win. A {@code NONE} predicate indicates an alt containing an\n     * unpredicated config which behaves as \"always true.\" If !complete\n     * then we stop at the first predicate that evaluates to true. This\n     * includes pairs with null predicates.\n     */\n    evalSemanticContext(predPredictions, outerContext, complete) {\n        const predictions = new BitSet();\n        for(let i=0;i<predPredictions.length;i++) {\n            const pair = predPredictions[i];\n            if (pair.pred === SemanticContext.NONE) {\n                predictions.set(pair.alt);\n                if (! complete) {\n                    break;\n                }\n                continue;\n            }\n            const predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext);\n            if (this.debug || this.dfa_debug) {\n                console.log(\"eval pred \" + pair + \"=\" + predicateEvaluationResult);\n            }\n            if (predicateEvaluationResult) {\n                if (this.debug || this.dfa_debug) {\n                    console.log(\"PREDICT \" + pair.alt);\n                }\n                predictions.set(pair.alt);\n                if (! complete) {\n                    break;\n                }\n            }\n        }\n        return predictions;\n    }\n\n// TODO: If we are doing predicates, there is no point in pursuing\n//     closure operations if we reach a DFA state that uniquely predicts\n//     alternative. We will not be caching that DFA state and it is a\n//     waste to pursue the closure. Might have to advance when we do\n//     ambig detection thought :(\n//\n    closure(config, configs, closureBusy, collectPredicates, fullCtx, treatEofAsEpsilon) {\n        const initialDepth = 0;\n        this.closureCheckingStopState(config, configs, closureBusy, collectPredicates,\n                                 fullCtx, initialDepth, treatEofAsEpsilon);\n    }\n\n    closureCheckingStopState(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {\n        if (this.trace_atn_sim || this.debug_closure) {\n            console.log(\"closure(\" + config.toString(this.parser,true) + \")\");\n        }\n        if (config.state instanceof RuleStopState) {\n            // We hit rule end. If we have context info, use it\n            // run thru all possible stack tops in ctx\n            if (! config.context.isEmpty()) {\n                for (let i =0; i<config.context.length; i++) {\n                    if (config.context.getReturnState(i) === PredictionContext.EMPTY_RETURN_STATE) {\n                        if (fullCtx) {\n                            configs.add(new ATNConfig({state:config.state, context:PredictionContext.EMPTY}, config), this.mergeCache);\n                            continue;\n                        } else {\n                            // we have no context info, just chase follow links (if greedy)\n                            if (this.debug) {\n                                console.log(\"FALLING off rule \" + this.getRuleName(config.state.ruleIndex));\n                            }\n                            this.closure_(config, configs, closureBusy, collectPredicates,\n                                     fullCtx, depth, treatEofAsEpsilon);\n                        }\n                        continue;\n                    }\n                    const returnState = this.atn.states[config.context.getReturnState(i)];\n                    const newContext = config.context.getParent(i); // \"pop\" return state\n                    const parms = {state:returnState, alt:config.alt, context:newContext, semanticContext:config.semanticContext};\n                    const c = new ATNConfig(parms, null);\n                    // While we have context to pop back from, we may have\n                    // gotten that context AFTER having falling off a rule.\n                    // Make sure we track that we are now out of context.\n                    c.reachesIntoOuterContext = config.reachesIntoOuterContext;\n                    this.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon);\n                }\n                return;\n            } else if( fullCtx) {\n                // reached end of start rule\n                configs.add(config, this.mergeCache);\n                return;\n            } else {\n                // else if we have no context info, just chase follow links (if greedy)\n                if (this.debug) {\n                    console.log(\"FALLING off rule \" + this.getRuleName(config.state.ruleIndex));\n                }\n            }\n        }\n        this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);\n    }\n\n    // Do the actual work of walking epsilon edges//\n    closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {\n        const p = config.state;\n        // optimization\n        if (! p.epsilonOnlyTransitions) {\n            configs.add(config, this.mergeCache);\n            // make sure to not return here, because EOF transitions can act as\n            // both epsilon transitions and non-epsilon transitions.\n        }\n        for(let i = 0;i<p.transitions.length; i++) {\n            if(i === 0 && this.canDropLoopEntryEdgeInLeftRecursiveRule(config))\n                continue;\n\n            const t = p.transitions[i];\n            const continueCollecting = collectPredicates && !(t instanceof ActionTransition);\n            const c = this.getEpsilonTarget(config, t, continueCollecting, depth === 0, fullCtx, treatEofAsEpsilon);\n            if (c!==null) {\n                let newDepth = depth;\n                if ( config.state instanceof RuleStopState) {\n                    // target fell off end of rule; mark resulting c as having dipped into outer context\n                    // We can't get here if incoming config was rule stop and we had context\n                    // track how far we dip into outer context.  Might\n                    // come in handy and we avoid evaluating context dependent\n                    // preds if this is > 0.\n                    if (this._dfa !== null && this._dfa.precedenceDfa) {\n                        if (t.outermostPrecedenceReturn === this._dfa.atnStartState.ruleIndex) {\n                            c.precedenceFilterSuppressed = true;\n                        }\n                    }\n\n                    c.reachesIntoOuterContext += 1;\n                    if (closureBusy.getOrAdd(c)!==c) {\n                        // avoid infinite recursion for right-recursive rules\n                        continue;\n                    }\n                    configs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method\n                    newDepth -= 1;\n                    if (this.debug) {\n                        console.log(\"dips into outer ctx: \" + c);\n                    }\n                } else {\n                    if (!t.isEpsilon && closureBusy.getOrAdd(c)!==c){\n                        // avoid infinite recursion for EOF* and EOF+\n                        continue;\n                    }\n                    if (t instanceof RuleTransition) {\n                        // latch when newDepth goes negative - once we step out of the entry context we can't return\n                        if (newDepth >= 0) {\n                            newDepth += 1;\n                        }\n                    }\n                }\n                this.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon);\n            }\n        }\n    }\n\n    canDropLoopEntryEdgeInLeftRecursiveRule(config) {\n        // return False\n        const p = config.state;\n        // First check to see if we are in StarLoopEntryState generated during\n        // left-recursion elimination. For efficiency, also check if\n        // the context has an empty stack case. If so, it would mean\n        // global FOLLOW so we can't perform optimization\n        // Are we the special loop entry/exit state? or SLL wildcard\n        if(p.stateType !== ATNState.STAR_LOOP_ENTRY)\n            return false;\n        if(p.stateType !== ATNState.STAR_LOOP_ENTRY || !p.isPrecedenceDecision ||\n               config.context.isEmpty() || config.context.hasEmptyPath())\n            return false;\n\n        // Require all return states to return back to the same rule that p is in.\n        const numCtxs = config.context.length;\n        for(let i=0; i<numCtxs; i++) { // for each stack context\n            const returnState = this.atn.states[config.context.getReturnState(i)];\n            if (returnState.ruleIndex !== p.ruleIndex)\n                return false;\n        }\n\n        const decisionStartState = p.transitions[0].target;\n        const blockEndStateNum = decisionStartState.endState.stateNumber;\n        const blockEndState = this.atn.states[blockEndStateNum];\n\n        // Verify that the top of each stack context leads to loop entry/exit\n        // state through epsilon edges and w/o leaving rule.\n        for(let i=0; i<numCtxs; i++) { // for each stack context\n            const returnStateNumber = config.context.getReturnState(i);\n            const returnState = this.atn.states[returnStateNumber];\n            // all states must have single outgoing epsilon edge\n            if (returnState.transitions.length !== 1 || !returnState.transitions[0].isEpsilon)\n                return false;\n\n            // Look for prefix op case like 'not expr', (' type ')' expr\n            const returnStateTarget = returnState.transitions[0].target;\n            if ( returnState.stateType === ATNState.BLOCK_END && returnStateTarget === p )\n                continue;\n\n            // Look for 'expr op expr' or case where expr's return state is block end\n            // of (...)* internal block; the block end points to loop back\n            // which points to p but we don't need to check that\n            if ( returnState === blockEndState )\n                continue;\n\n            // Look for ternary expr ? expr : expr. The return state points at block end,\n            // which points at loop entry state\n            if ( returnStateTarget === blockEndState )\n                continue;\n\n            // Look for complex prefix 'between expr and expr' case where 2nd expr's\n            // return state points at block end state of (...)* internal block\n            if (returnStateTarget.stateType === ATNState.BLOCK_END && returnStateTarget.transitions.length === 1\n                    && returnStateTarget.transitions[0].isEpsilon && returnStateTarget.transitions[0].target === p)\n                continue;\n\n            // anything else ain't conforming\n            return false;\n        }\n        return true;\n    }\n\n    getRuleName(index) {\n        if (this.parser!==null && index>=0) {\n            return this.parser.ruleNames[index];\n        } else {\n            return \"<rule \" + index + \">\";\n        }\n    }\n\n    getEpsilonTarget(config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon) {\n        switch(t.serializationType) {\n        case Transition.RULE:\n            return this.ruleTransition(config, t);\n        case Transition.PRECEDENCE:\n            return this.precedenceTransition(config, t, collectPredicates, inContext, fullCtx);\n        case Transition.PREDICATE:\n            return this.predTransition(config, t, collectPredicates, inContext, fullCtx);\n        case Transition.ACTION:\n            return this.actionTransition(config, t);\n        case Transition.EPSILON:\n            return new ATNConfig({state:t.target}, config);\n        case Transition.ATOM:\n        case Transition.RANGE:\n        case Transition.SET:\n            // EOF transitions act like epsilon transitions after the first EOF\n            // transition is traversed\n            if (treatEofAsEpsilon) {\n                if (t.matches(Token.EOF, 0, 1)) {\n                    return new ATNConfig({state: t.target}, config);\n                }\n            }\n            return null;\n        default:\n            return null;\n        }\n    }\n\n    actionTransition(config, t) {\n        if (this.debug) {\n            const index = t.actionIndex === -1 ? 65535 : t.actionIndex;\n            console.log(\"ACTION edge \" + t.ruleIndex + \":\" + index);\n        }\n        return new ATNConfig({state:t.target}, config);\n    }\n\n    precedenceTransition(config, pt, collectPredicates, inContext, fullCtx) {\n        if (this.debug) {\n            console.log(\"PRED (collectPredicates=\" + collectPredicates + \") \" +\n                    pt.precedence + \">=_p, ctx dependent=true\");\n            if (this.parser!==null) {\n                console.log(\"context surrounding pred is \" + arrayToString(this.parser.getRuleInvocationStack()));\n            }\n        }\n        let c = null;\n        if (collectPredicates && inContext) {\n            if (fullCtx) {\n                // In full context mode, we can evaluate predicates on-the-fly\n                // during closure, which dramatically reduces the size of\n                // the config sets. It also obviates the need to test predicates\n                // later during conflict resolution.\n                const currentPosition = this._input.index;\n                this._input.seek(this._startIndex);\n                const predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);\n                this._input.seek(currentPosition);\n                if (predSucceeds) {\n                    c = new ATNConfig({state:pt.target}, config); // no pred context\n                }\n            } else {\n                const newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());\n                c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);\n            }\n        } else {\n            c = new ATNConfig({state:pt.target}, config);\n        }\n        if (this.debug) {\n            console.log(\"config from pred transition=\" + c);\n        }\n        return c;\n    }\n\n    predTransition(config, pt, collectPredicates, inContext, fullCtx) {\n        if (this.debug) {\n            console.log(\"PRED (collectPredicates=\" + collectPredicates + \") \" + pt.ruleIndex +\n                    \":\" + pt.predIndex + \", ctx dependent=\" + pt.isCtxDependent);\n            if (this.parser!==null) {\n                console.log(\"context surrounding pred is \" + arrayToString(this.parser.getRuleInvocationStack()));\n            }\n        }\n        let c = null;\n        if (collectPredicates && ((pt.isCtxDependent && inContext) || ! pt.isCtxDependent)) {\n            if (fullCtx) {\n                // In full context mode, we can evaluate predicates on-the-fly\n                // during closure, which dramatically reduces the size of\n                // the config sets. It also obviates the need to test predicates\n                // later during conflict resolution.\n                const currentPosition = this._input.index;\n                this._input.seek(this._startIndex);\n                const predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);\n                this._input.seek(currentPosition);\n                if (predSucceeds) {\n                    c = new ATNConfig({state:pt.target}, config); // no pred context\n                }\n            } else {\n                const newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());\n                c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);\n            }\n        } else {\n            c = new ATNConfig({state:pt.target}, config);\n        }\n        if (this.debug) {\n            console.log(\"config from pred transition=\" + c);\n        }\n        return c;\n    }\n\n    ruleTransition(config, t) {\n        if (this.debug) {\n            console.log(\"CALL rule \" + this.getRuleName(t.target.ruleIndex) + \", ctx=\" + config.context);\n        }\n        const returnState = t.followState;\n        const newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber);\n        return new ATNConfig({state:t.target, context:newContext}, config );\n    }\n\n    getConflictingAlts(configs) {\n        const altsets = PredictionMode.getConflictingAltSubsets(configs);\n        return PredictionMode.getAlts(altsets);\n    }\n\n    /**\n     * Sam pointed out a problem with the previous definition, v3, of\n     * ambiguous states. If we have another state associated with conflicting\n     * alternatives, we should keep going. For example, the following grammar\n     *\n     * s : (ID | ID ID?) ';' ;\n     *\n     * When the ATN simulation reaches the state before ';', it has a DFA\n     * state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally\n     * 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node\n     * because alternative to has another way to continue, via [6|2|[]].\n     * The key is that we have a single state that has config's only associated\n     * with a single alternative, 2, and crucially the state transitions\n     * among the configurations are all non-epsilon transitions. That means\n     * we don't consider any conflicts that include alternative 2. So, we\n     * ignore the conflict between alts 1 and 2. We ignore a set of\n     * conflicting alts when there is an intersection with an alternative\n     * associated with a single alt state in the state&rarr;config-list map.\n     *\n     * It's also the case that we might have two conflicting configurations but\n     * also a 3rd nonconflicting configuration for a different alternative:\n     * [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:\n     *\n     * a : A | A | A B ;\n     *\n     * After matching input A, we reach the stop state for rule A, state 1.\n     * State 8 is the state right before B. Clearly alternatives 1 and 2\n     * conflict and no amount of further lookahead will separate the two.\n     * However, alternative 3 will be able to continue and so we do not\n     * stop working on this state. In the previous example, we're concerned\n     * with states associated with the conflicting alternatives. Here alt\n     * 3 is not associated with the conflicting configs, but since we can continue\n     * looking for input reasonably, I don't declare the state done. We\n     * ignore a set of conflicting alts when we have an alternative\n     * that we still need to pursue\n     */\n    getConflictingAltsOrUniqueAlt(configs) {\n        let conflictingAlts = null;\n        if (configs.uniqueAlt!== ATN.INVALID_ALT_NUMBER) {\n            conflictingAlts = new BitSet();\n            conflictingAlts.set(configs.uniqueAlt);\n        } else {\n            conflictingAlts = configs.conflictingAlts;\n        }\n        return conflictingAlts;\n    }\n\n    getTokenName(t) {\n        if (t===Token.EOF) {\n            return \"EOF\";\n        }\n        if( this.parser!==null && this.parser.literalNames!==null) {\n            if (t >= this.parser.literalNames.length && t >= this.parser.symbolicNames.length) {\n                console.log(\"\" + t + \" ttype out of range: \" + this.parser.literalNames);\n                console.log(\"\" + this.parser.getInputStream().getTokens());\n            } else {\n                const name = this.parser.literalNames[t] || this.parser.symbolicNames[t];\n                return name + \"<\" + t + \">\";\n            }\n        }\n        return \"\" + t;\n    }\n\n    getLookaheadName(input) {\n        return this.getTokenName(input.LA(1));\n    }\n\n    /**\n     * Used for debugging in adaptivePredict around execATN but I cut\n     * it out for clarity now that alg. works well. We can leave this\n     * \"dead\" code for a bit\n     */\n    dumpDeadEndConfigs(nvae) {\n        console.log(\"dead end configs: \");\n        const decs = nvae.getDeadEndConfigs();\n        for(let i=0; i<decs.length; i++) {\n            const c = decs[i];\n            let trans = \"no edges\";\n            if (c.state.transitions.length>0) {\n                const t = c.state.transitions[0];\n                if (t instanceof AtomTransition) {\n                    trans = \"Atom \"+ this.getTokenName(t.label);\n                } else if (t instanceof SetTransition) {\n                    const neg = (t instanceof NotSetTransition);\n                    trans = (neg ? \"~\" : \"\") + \"Set \" + t.set;\n                }\n            }\n            console.error(c.toString(this.parser, true) + \":\" + trans);\n        }\n    }\n\n    noViableAlt(input, outerContext, configs, startIndex) {\n        return new NoViableAltException(this.parser, input, input.get(startIndex), input.LT(1), configs, outerContext);\n    }\n\n    getUniqueAlt(configs) {\n        let alt = ATN.INVALID_ALT_NUMBER;\n        for(let i=0;i<configs.items.length;i++) {\n            const c = configs.items[i];\n            if (alt === ATN.INVALID_ALT_NUMBER) {\n                alt = c.alt // found first alt\n            } else if( c.alt!==alt) {\n                return ATN.INVALID_ALT_NUMBER;\n            }\n        }\n        return alt;\n    }\n\n    /**\n     * Add an edge to the DFA, if possible. This method calls\n     * {@link //addDFAState} to ensure the {@code to} state is present in the\n     * DFA. If {@code from} is {@code null}, or if {@code t} is outside the\n     * range of edges that can be represented in the DFA tables, this method\n     * returns without adding the edge to the DFA.\n     *\n     * <p>If {@code to} is {@code null}, this method returns {@code null}.\n     * Otherwise, this method returns the {@link DFAState} returned by calling\n     * {@link //addDFAState} for the {@code to} state.</p>\n     *\n     * @param dfa The DFA\n     * @param from_ The source state for the edge\n     * @param t The input symbol\n     * @param to The target state for the edge\n     *\n     * @return If {@code to} is {@code null}, this method returns {@code null};\n     * otherwise this method returns the result of calling {@link //addDFAState}\n     * on {@code to}\n     */\n    addDFAEdge(dfa, from_, t, to) {\n        if( this.debug) {\n            console.log(\"EDGE \" + from_ + \" -> \" + to + \" upon \" + this.getTokenName(t));\n        }\n        if (to===null) {\n            return null;\n        }\n        to = this.addDFAState(dfa, to); // used existing if possible not incoming\n        if (from_===null || t < -1 || t > this.atn.maxTokenType) {\n            return to;\n        }\n        if (from_.edges===null) {\n            from_.edges = [];\n        }\n        from_.edges[t+1] = to; // connect\n\n        if (this.debug) {\n            const literalNames = this.parser===null ? null : this.parser.literalNames;\n            const symbolicNames = this.parser===null ? null : this.parser.symbolicNames;\n            console.log(\"DFA=\\n\" + dfa.toString(literalNames, symbolicNames));\n        }\n        return to;\n    }\n\n    /**\n     * Add state {@code D} to the DFA if it is not already present, and return\n     * the actual instance stored in the DFA. If a state equivalent to {@code D}\n     * is already in the DFA, the existing state is returned. Otherwise this\n     * method returns {@code D} after adding it to the DFA.\n     *\n     * <p>If {@code D} is {@link //ERROR}, this method returns {@link //ERROR} and\n     * does not change the DFA.</p>\n     *\n     * @param dfa The dfa\n     * @param D The DFA state to add\n     * @return The state stored in the DFA. This will be either the existing\n     * state if {@code D} is already in the DFA, or {@code D} itself if the\n     * state was not already present\n     */\n    addDFAState(dfa, D) {\n        if (D === ATNSimulator.ERROR) {\n            return D;\n        }\n        const existing = dfa.states.get(D);\n        if(existing!==null) {\n            if ( this.trace_atn_sim ) console.log(\"addDFAState \" + D + \" exists\");\n            return existing;\n        }\n        D.stateNumber = dfa.states.length;\n        if (! D.configs.readOnly) {\n            D.configs.optimizeConfigs(this);\n            D.configs.setReadonly(true);\n        }\n\n        if ( this.trace_atn_sim ) console.log(\"addDFAState new \" + D);\n\n        dfa.states.add(D);\n        if (this.debug) {\n            console.log(\"adding new DFA state: \" + D);\n        }\n        return D;\n    }\n\n    reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex) {\n        if (this.debug || this.retry_debug) {\n            const interval = new Interval(startIndex, stopIndex + 1);\n            console.log(\"reportAttemptingFullContext decision=\" + dfa.decision + \":\" + configs +\n                               \", input=\" + this.parser.getTokenStream().getText(interval));\n        }\n        if (this.parser!==null) {\n            this.parser.getErrorListener().reportAttemptingFullContext(this.parser, dfa, startIndex, stopIndex, conflictingAlts, configs);\n        }\n    }\n\n    reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex) {\n        if (this.debug || this.retry_debug) {\n            const interval = new Interval(startIndex, stopIndex + 1);\n            console.log(\"reportContextSensitivity decision=\" + dfa.decision + \":\" + configs +\n                               \", input=\" + this.parser.getTokenStream().getText(interval));\n        }\n        if (this.parser!==null) {\n            this.parser.getErrorListener().reportContextSensitivity(this.parser, dfa, startIndex, stopIndex, prediction, configs);\n        }\n    }\n\n    // If context sensitive parsing, we know it's ambiguity not conflict//\n    reportAmbiguity(dfa, D, startIndex, stopIndex,\n                                   exact, ambigAlts, configs ) {\n        if (this.debug || this.retry_debug) {\n            const interval = new Interval(startIndex, stopIndex + 1);\n            console.log(\"reportAmbiguity \" + ambigAlts + \":\" + configs +\n                               \", input=\" + this.parser.getTokenStream().getText(interval));\n        }\n        if (this.parser!==null) {\n            this.parser.getErrorListener().reportAmbiguity(this.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs);\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/PrecedencePredicate.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport SemanticContext from \"./SemanticContext.js\";\n\nexport default class PrecedencePredicate extends SemanticContext {\n\n    constructor(precedence) {\n        super();\n        this.precedence = precedence === undefined ? 0 : precedence;\n    }\n\n    evaluate(parser, outerContext) {\n        return parser.precpred(outerContext, this.precedence);\n    }\n\n    evalPrecedence(parser, outerContext) {\n        if (parser.precpred(outerContext, this.precedence)) {\n            return SemanticContext.NONE;\n        } else {\n            return null;\n        }\n    }\n\n    compareTo(other) {\n        return this.precedence - other.precedence;\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.precedence);\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (!(other instanceof PrecedencePredicate)) {\n            return false;\n        } else {\n            return this.precedence === other.precedence;\n        }\n    }\n\n    toString() {\n        return \"{\" + this.precedence + \">=prec}?\";\n    }\n\n}\n\n// HORRIBLE workaround circular import, avoiding dynamic import\nSemanticContext.PrecedencePredicate = PrecedencePredicate;\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/Predicate.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport SemanticContext from \"./SemanticContext.js\";\n\nexport default class Predicate extends SemanticContext {\n\n    constructor(ruleIndex, predIndex, isCtxDependent) {\n        super();\n        this.ruleIndex = ruleIndex === undefined ? -1 : ruleIndex;\n        this.predIndex = predIndex === undefined ? -1 : predIndex;\n        this.isCtxDependent = isCtxDependent === undefined ? false : isCtxDependent; // e.g., $i ref in pred\n    }\n\n    evaluate(parser, outerContext) {\n        const localctx = this.isCtxDependent ? outerContext : null;\n        return parser.sempred(localctx, this.ruleIndex, this.predIndex);\n    }\n\n    updateHashCode(hash) {\n        hash.update(this.ruleIndex, this.predIndex, this.isCtxDependent);\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (!(other instanceof Predicate)) {\n            return false;\n        } else {\n            return this.ruleIndex === other.ruleIndex &&\n                this.predIndex === other.predIndex &&\n                this.isCtxDependent === other.isCtxDependent;\n        }\n    }\n\n    toString() {\n        return \"{\" + this.ruleIndex + \":\" + this.predIndex + \"}?\";\n    }\n}\n\n/**\n * The default {@link SemanticContext}, which is semantically equivalent to\n * a predicate of the form {@code {true}?}\n */\nSemanticContext.NONE = new Predicate();\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/PredictionContextCache.d.ts",
    "content": "export declare class PredictionContextCache {\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/PredictionContextCache.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport PredictionContext from \"../context/PredictionContext.js\";\nimport HashMap from \"../misc/HashMap.js\";\n\n/**\n * Used to cache {@link PredictionContext} objects. Its used for the shared\n * context cash associated with contexts in DFA states. This cache\n * can be used for both lexers and parsers.\n */\nexport default class PredictionContextCache {\n\n    constructor() {\n        this.cache = new HashMap();\n    }\n\n    /**\n     * Add a context to the cache and return it. If the context already exists,\n     * return that one instead and do not add a new context to the cache.\n     * Protect shared cache from unsafe thread access.\n     */\n    add(ctx) {\n        if (ctx === PredictionContext.EMPTY) {\n            return PredictionContext.EMPTY;\n        }\n        const existing = this.cache.get(ctx) || null;\n        if (existing !== null) {\n            return existing;\n        }\n        this.cache.set(ctx, ctx);\n        return ctx;\n    }\n\n    get(ctx) {\n        return this.cache.get(ctx) || null;\n    }\n\n    get length(){\n        return this.cache.length;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/PredictionMode.d.ts",
    "content": "export declare class PredictionMode {\n    static SLL: number;\n    static LL: number;\n    static LL_EXACT_AMBIG_DETECTION: number;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/PredictionMode.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport ATN from './ATN.js';\nimport RuleStopState from '../state/RuleStopState.js';\nimport ATNConfigSet from './ATNConfigSet.js';\nimport ATNConfig from './ATNConfig.js';\nimport SemanticContext from './SemanticContext.js';\nimport BitSet from \"../misc/BitSet.js\";\nimport AltDict from \"../misc/AltDict.js\";\nimport HashCode from \"../misc/HashCode.js\";\nimport HashMap from \"../misc/HashMap.js\";\n\n/**\n * This enumeration defines the prediction modes available in ANTLR 4 along with\n * utility methods for analyzing configuration sets for conflicts and/or\n * ambiguities.\n */\nconst PredictionMode = {\n    /**\n     * The SLL(*) prediction mode. This prediction mode ignores the current\n     * parser context when making predictions. This is the fastest prediction\n     * mode, and provides correct results for many grammars. This prediction\n     * mode is more powerful than the prediction mode provided by ANTLR 3, but\n     * may result in syntax errors for grammar and input combinations which are\n     * not SLL.\n     *\n     * <p>\n     * When using this prediction mode, the parser will either return a correct\n     * parse tree (i.e. the same parse tree that would be returned with the\n     * {@link //LL} prediction mode), or it will report a syntax error. If a\n     * syntax error is encountered when using the {@link //SLL} prediction mode,\n     * it may be due to either an actual syntax error in the input or indicate\n     * that the particular combination of grammar and input requires the more\n     * powerful {@link //LL} prediction abilities to complete successfully.</p>\n     *\n     * <p>\n     * This prediction mode does not provide any guarantees for prediction\n     * behavior for syntactically-incorrect inputs.</p>\n     */\n    SLL: 0,\n\n    /**\n     * The LL(*) prediction mode. This prediction mode allows the current parser\n     * context to be used for resolving SLL conflicts that occur during\n     * prediction. This is the fastest prediction mode that guarantees correct\n     * parse results for all combinations of grammars with syntactically correct\n     * inputs.\n     *\n     * <p>\n     * When using this prediction mode, the parser will make correct decisions\n     * for all syntactically-correct grammar and input combinations. However, in\n     * cases where the grammar is truly ambiguous this prediction mode might not\n     * report a precise answer for <em>exactly which</em> alternatives are\n     * ambiguous.</p>\n     *\n     * <p>\n     * This prediction mode does not provide any guarantees for prediction\n     * behavior for syntactically-incorrect inputs.</p>\n     */\n    LL: 1,\n\n    /**\n     *\n     * The LL(*) prediction mode with exact ambiguity detection. In addition to\n     * the correctness guarantees provided by the {@link //LL} prediction mode,\n     * this prediction mode instructs the prediction algorithm to determine the\n     * complete and exact set of ambiguous alternatives for every ambiguous\n     * decision encountered while parsing.\n     *\n     * <p>\n     * This prediction mode may be used for diagnosing ambiguities during\n     * grammar development. Due to the performance overhead of calculating sets\n     * of ambiguous alternatives, this prediction mode should be avoided when\n     * the exact results are not necessary.</p>\n     *\n     * <p>\n     * This prediction mode does not provide any guarantees for prediction\n     * behavior for syntactically-incorrect inputs.</p>\n     */\n    LL_EXACT_AMBIG_DETECTION: 2,\n\n    /**\n     *\n     * Computes the SLL prediction termination condition.\n     *\n     * <p>\n     * This method computes the SLL prediction termination condition for both of\n     * the following cases.</p>\n     *\n     * <ul>\n     * <li>The usual SLL+LL fallback upon SLL conflict</li>\n     * <li>Pure SLL without LL fallback</li>\n     * </ul>\n     *\n     * <p><strong>COMBINED SLL+LL PARSING</strong></p>\n     *\n     * <p>When LL-fallback is enabled upon SLL conflict, correct predictions are\n     * ensured regardless of how the termination condition is computed by this\n     * method. Due to the substantially higher cost of LL prediction, the\n     * prediction should only fall back to LL when the additional lookahead\n     * cannot lead to a unique SLL prediction.</p>\n     *\n     * <p>Assuming combined SLL+LL parsing, an SLL configuration set with only\n     * conflicting subsets should fall back to full LL, even if the\n     * configuration sets don't resolve to the same alternative (e.g.\n     * {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting\n     * configuration, SLL could continue with the hopes that more lookahead will\n     * resolve via one of those non-conflicting configurations.</p>\n     *\n     * <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n     * stops when it sees only conflicting configuration subsets. In contrast,\n     * full LL keeps going when there is uncertainty.</p>\n     *\n     * <p><strong>HEURISTIC</strong></p>\n     *\n     * <p>As a heuristic, we stop prediction when we see any conflicting subset\n     * unless we see a state that only has one alternative associated with it.\n     * The single-alt-state thing lets prediction continue upon rules like\n     * (otherwise, it would admit defeat too soon):</p>\n     *\n     * <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>\n     *\n     * <p>When the ATN simulation reaches the state before {@code ';'}, it has a\n     * DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally\n     * {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop\n     * processing this node because alternative to has another way to continue,\n     * via {@code [6|2|[]]}.</p>\n     *\n     * <p>It also let's us continue for this rule:</p>\n     *\n     * <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>\n     *\n     * <p>After matching input A, we reach the stop state for rule A, state 1.\n     * State 8 is the state right before B. Clearly alternatives 1 and 2\n     * conflict and no amount of further lookahead will separate the two.\n     * However, alternative 3 will be able to continue and so we do not stop\n     * working on this state. In the previous example, we're concerned with\n     * states associated with the conflicting alternatives. Here alt 3 is not\n     * associated with the conflicting configs, but since we can continue\n     * looking for input reasonably, don't declare the state done.</p>\n     *\n     * <p><strong>PURE SLL PARSING</strong></p>\n     *\n     * <p>To handle pure SLL parsing, all we have to do is make sure that we\n     * combine stack contexts for configurations that differ only by semantic\n     * predicate. From there, we can do the usual SLL termination heuristic.</p>\n     *\n     * <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>\n     *\n     * <p>SLL decisions don't evaluate predicates until after they reach DFA stop\n     * states because they need to create the DFA cache that works in all\n     * semantic situations. In contrast, full LL evaluates predicates collected\n     * during start state computation so it can ignore predicates thereafter.\n     * This means that SLL termination detection can totally ignore semantic\n     * predicates.</p>\n     *\n     * <p>Implementation-wise, {@link ATNConfigSet} combines stack contexts but not\n     * semantic predicate contexts so we might see two configurations like the\n     * following.</p>\n     *\n     * <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>\n     *\n     * <p>Before testing these configurations against others, we have to merge\n     * {@code x} and {@code x'} (without modifying the existing configurations).\n     * For example, we test {@code (x+x')==x''} when looking for conflicts in\n     * the following configurations.</p>\n     *\n     * <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>\n     *\n     * <p>If the configuration set has predicates (as indicated by\n     * {@link ATNConfigSet//hasSemanticContext}), this algorithm makes a copy of\n     * the configurations to strip out all of the predicates so that a standard\n     * {@link ATNConfigSet} will merge everything ignoring predicates.</p>\n     */\n    hasSLLConflictTerminatingPrediction: function( mode, configs) {\n        // Configs in rule stop states indicate reaching the end of the decision\n        // rule (local context) or end of start rule (full context). If all\n        // configs meet this condition, then none of the configurations is able\n        // to match additional input so we terminate prediction.\n        //\n        if (PredictionMode.allConfigsInRuleStopStates(configs)) {\n            return true;\n        }\n        // pure SLL mode parsing\n        if (mode === PredictionMode.SLL) {\n            // Don't bother with combining configs from different semantic\n            // contexts if we can fail over to full LL; costs more time\n            // since we'll often fail over anyway.\n            if (configs.hasSemanticContext) {\n                // dup configs, tossing out semantic predicates\n                const dup = new ATNConfigSet();\n                for(let i=0;i<configs.items.length;i++) {\n                    let c = configs.items[i];\n                    c = new ATNConfig({semanticContext:SemanticContext.NONE}, c);\n                    dup.add(c);\n                }\n                configs = dup;\n            }\n            // now we have combined contexts for configs with dissimilar preds\n        }\n        // pure SLL or combined SLL+LL mode parsing\n        const altsets = PredictionMode.getConflictingAltSubsets(configs);\n        return PredictionMode.hasConflictingAltSet(altsets) && !PredictionMode.hasStateAssociatedWithOneAlt(configs);\n    },\n\n    /**\n     * Checks if any configuration in {@code configs} is in a\n     * {@link RuleStopState}. Configurations meeting this condition have reached\n     * the end of the decision rule (local context) or end of start rule (full\n     * context).\n     *\n     * @param configs the configuration set to test\n     * @return {@code true} if any configuration in {@code configs} is in a\n     * {@link RuleStopState}, otherwise {@code false}\n     */\n    hasConfigInRuleStopState: function(configs) {\n        for(let i=0;i<configs.items.length;i++) {\n            const c = configs.items[i];\n            if (c.state instanceof RuleStopState) {\n                return true;\n            }\n        }\n        return false;\n    },\n\n    /**\n     * Checks if all configurations in {@code configs} are in a\n     * {@link RuleStopState}. Configurations meeting this condition have reached\n     * the end of the decision rule (local context) or end of start rule (full\n     * context).\n     *\n     * @param configs the configuration set to test\n     * @return {@code true} if all configurations in {@code configs} are in a\n     * {@link RuleStopState}, otherwise {@code false}\n     */\n    allConfigsInRuleStopStates: function(configs) {\n        for(let i=0;i<configs.items.length;i++) {\n            const c = configs.items[i];\n            if (!(c.state instanceof RuleStopState)) {\n                return false;\n            }\n        }\n        return true;\n    },\n\n    /**\n     *\n     * Full LL prediction termination.\n     *\n     * <p>Can we stop looking ahead during ATN simulation or is there some\n     * uncertainty as to which alternative we will ultimately pick, after\n     * consuming more input? Even if there are partial conflicts, we might know\n     * that everything is going to resolve to the same minimum alternative. That\n     * means we can stop since no more lookahead will change that fact. On the\n     * other hand, there might be multiple conflicts that resolve to different\n     * minimums. That means we need more look ahead to decide which of those\n     * alternatives we should predict.</p>\n     *\n     * <p>The basic idea is to split the set of configurations {@code C}, into\n     * conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with\n     * non-conflicting configurations. Two configurations conflict if they have\n     * identical {@link ATNConfig//state} and {@link ATNConfig//context} values\n     * but different {@link ATNConfig//alt} value, e.g. {@code (s, i, ctx, _)}\n     * and {@code (s, j, ctx, _)} for {@code i!=j}.</p>\n     *\n     * <p>Reduce these configuration subsets to the set of possible alternatives.\n     * You can compute the alternative subsets in one pass as follows:</p>\n     *\n     * <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in\n     * {@code C} holding {@code s} and {@code ctx} fixed.</p>\n     *\n     * <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>\n     *\n     * <pre>\n     * map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not\n     * alt and not pred\n     * </pre>\n     *\n     * <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>\n     *\n     * <p>If {@code |A_s,ctx|=1} then there is no conflict associated with\n     * {@code s} and {@code ctx}.</p>\n     *\n     * <p>Reduce the subsets to singletons by choosing a minimum of each subset. If\n     * the union of these alternative subsets is a singleton, then no amount of\n     * more lookahead will help us. We will always pick that alternative. If,\n     * however, there is more than one alternative, then we are uncertain which\n     * alternative to predict and must continue looking for resolution. We may\n     * or may not discover an ambiguity in the future, even if there are no\n     * conflicting subsets this round.</p>\n     *\n     * <p>The biggest sin is to terminate early because it means we've made a\n     * decision but were uncertain as to the eventual outcome. We haven't used\n     * enough lookahead. On the other hand, announcing a conflict too late is no\n     * big deal; you will still have the conflict. It's just inefficient. It\n     * might even look until the end of file.</p>\n     *\n     * <p>No special consideration for semantic predicates is required because\n     * predicates are evaluated on-the-fly for full LL prediction, ensuring that\n     * no configuration contains a semantic context during the termination\n     * check.</p>\n     *\n     * <p><strong>CONFLICTING CONFIGS</strong></p>\n     *\n     * <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict\n     * when {@code i!=j} but {@code x=x'}. Because we merge all\n     * {@code (s, i, _)} configurations together, that means that there are at\n     * most {@code n} configurations associated with state {@code s} for\n     * {@code n} possible alternatives in the decision. The merged stacks\n     * complicate the comparison of configuration contexts {@code x} and\n     * {@code x'}. Sam checks to see if one is a subset of the other by calling\n     * merge and checking to see if the merged result is either {@code x} or\n     * {@code x'}. If the {@code x} associated with lowest alternative {@code i}\n     * is the superset, then {@code i} is the only possible prediction since the\n     * others resolve to {@code min(i)} as well. However, if {@code x} is\n     * associated with {@code j>i} then at least one stack configuration for\n     * {@code j} is not in conflict with alternative {@code i}. The algorithm\n     * should keep going, looking for more lookahead due to the uncertainty.</p>\n     *\n     * <p>For simplicity, I'm doing a equality check between {@code x} and\n     * {@code x'} that lets the algorithm continue to consume lookahead longer\n     * than necessary. The reason I like the equality is of course the\n     * simplicity but also because that is the test you need to detect the\n     * alternatives that are actually in conflict.</p>\n     *\n     * <p><strong>CONTINUE/STOP RULE</strong></p>\n     *\n     * <p>Continue if union of resolved alternative sets from non-conflicting and\n     * conflicting alternative subsets has more than one alternative. We are\n     * uncertain about which alternative to predict.</p>\n     *\n     * <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which\n     * alternatives are still in the running for the amount of input we've\n     * consumed at this point. The conflicting sets let us to strip away\n     * configurations that won't lead to more states because we resolve\n     * conflicts to the configuration with a minimum alternate for the\n     * conflicting set.</p>\n     *\n     * <p><strong>CASES</strong></p>\n     *\n     * <ul>\n     *\n     * <li>no conflicts and more than 1 alternative in set =&gt; continue</li>\n     *\n     * <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},\n     * {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set\n     * {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n     * {@code {1,3}} =&gt; continue\n     * </li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n     * {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set\n     * {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n     * {@code {1}} =&gt; stop and predict 1</li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n     * {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U\n     * {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce\n     * ambiguity {@code {1,2}}</li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},\n     * {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U\n     * {@code {2}} = {@code {1,2}} =&gt; continue</li>\n     *\n     * <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},\n     * {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U\n     * {@code {3}} = {@code {1,3}} =&gt; continue</li>\n     *\n     * </ul>\n     *\n     * <p><strong>EXACT AMBIGUITY DETECTION</strong></p>\n     *\n     * <p>If all states report the same conflicting set of alternatives, then we\n     * know we have the exact ambiguity set.</p>\n     *\n     * <p><code>|A_<em>i</em>|&gt;1</code> and\n     * <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>\n     *\n     * <p>In other words, we continue examining lookahead until all {@code A_i}\n     * have more than one alternative and all {@code A_i} are the same. If\n     * {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate\n     * because the resolved set is {@code {1}}. To determine what the real\n     * ambiguity is, we have to know whether the ambiguity is between one and\n     * two or one and three so we keep going. We can only stop prediction when\n     * we need exact ambiguity detection when the sets look like\n     * {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>\n     */\n    resolvesToJustOneViableAlt: function(altsets) {\n        return PredictionMode.getSingleViableAlt(altsets);\n    },\n\n    /**\n     * Determines if every alternative subset in {@code altsets} contains more\n     * than one alternative.\n     *\n     * @param altsets a collection of alternative subsets\n     * @return {@code true} if every {@link BitSet} in {@code altsets} has\n     * {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}\n     */\n    allSubsetsConflict: function(altsets) {\n        return ! PredictionMode.hasNonConflictingAltSet(altsets);\n    },\n    /**\n     * Determines if any single alternative subset in {@code altsets} contains\n     * exactly one alternative.\n     *\n     * @param altsets a collection of alternative subsets\n     * @return {@code true} if {@code altsets} contains a {@link BitSet} with\n     * {@link BitSet//cardinality cardinality} 1, otherwise {@code false}\n     */\n    hasNonConflictingAltSet: function(altsets) {\n        for(let i=0;i<altsets.length;i++) {\n            const alts = altsets[i];\n            if (alts.length===1) {\n                return true;\n            }\n        }\n        return false;\n    },\n\n\n    /**\n     * Determines if any single alternative subset in {@code altsets} contains\n     * more than one alternative.\n     *\n     * @param altsets a collection of alternative subsets\n     * @return {@code true} if {@code altsets} contains a {@link BitSet} with\n     * {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}\n     */\n    hasConflictingAltSet: function(altsets) {\n        for(let i=0;i<altsets.length;i++) {\n            const alts = altsets[i];\n            if (alts.length>1) {\n                return true;\n            }\n        }\n        return false;\n    },\n\n\n    /**\n     * Determines if every alternative subset in {@code altsets} is equivalent.\n     *\n     * @param altsets a collection of alternative subsets\n     * @return {@code true} if every member of {@code altsets} is equal to the\n     * others, otherwise {@code false}\n     */\n    allSubsetsEqual: function(altsets) {\n        let first = null;\n        for(let i=0;i<altsets.length;i++) {\n            const alts = altsets[i];\n            if (first === null) {\n                first = alts;\n            } else if (alts!==first) {\n                return false;\n            }\n        }\n        return true;\n    },\n\n\n    /**\n     * Returns the unique alternative predicted by all alternative subsets in\n     * {@code altsets}. If no such alternative exists, this method returns\n     * {@link ATN//INVALID_ALT_NUMBER}.\n     *\n     * @param altsets a collection of alternative subsets\n     */\n    getUniqueAlt: function(altsets) {\n        const all = PredictionMode.getAlts(altsets);\n        if (all.length===1) {\n            return all.minValue();\n        } else {\n            return ATN.INVALID_ALT_NUMBER;\n        }\n    },\n\n    /**\n     * Gets the complete set of represented alternatives for a collection of\n     * alternative subsets. This method returns the union of each {@link BitSet}\n     * in {@code altsets}.\n     *\n     * @param altsets a collection of alternative subsets\n     * @return the set of represented alternatives in {@code altsets}\n     */\n    getAlts: function(altsets) {\n        const all = new BitSet();\n        altsets.map( function(alts) { all.or(alts); });\n        return all;\n    },\n\n    /**\n     * This function gets the conflicting alt subsets from a configuration set.\n     * For each configuration {@code c} in {@code configs}:\n     *\n     * <pre>\n     * map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not\n     * alt and not pred\n     * </pre>\n     */\n    getConflictingAltSubsets: function(configs) {\n        const configToAlts = new HashMap();\n        configToAlts.hashFunction = function(cfg) { HashCode.hashStuff(cfg.state.stateNumber, cfg.context); };\n        configToAlts.equalsFunction = function(c1, c2) { return c1.state.stateNumber === c2.state.stateNumber && c1.context.equals(c2.context);};\n        configs.items.map(function(cfg) {\n            let alts = configToAlts.get(cfg);\n            if (alts === null) {\n                alts = new BitSet();\n                configToAlts.set(cfg, alts);\n            }\n            alts.set(cfg.alt);\n        });\n        return configToAlts.getValues();\n    },\n\n    /**\n     * Get a map from state to alt subset from a configuration set. For each\n     * configuration {@code c} in {@code configs}:\n     *\n     * <pre>\n     * map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt}\n     * </pre>\n     */\n    getStateToAltMap: function(configs) {\n        const m = new AltDict();\n        configs.items.map(function(c) {\n            let alts = m.get(c.state);\n            if (alts === null) {\n                alts = new BitSet();\n                m.set(c.state, alts);\n            }\n            alts.set(c.alt);\n        });\n        return m;\n    },\n\n    hasStateAssociatedWithOneAlt: function(configs) {\n        const values = PredictionMode.getStateToAltMap(configs).values();\n        for(let i=0;i<values.length;i++) {\n            if (values[i].length===1) {\n                return true;\n            }\n        }\n        return false;\n    },\n\n    getSingleViableAlt: function(altsets) {\n        let result = null;\n        for(let i=0;i<altsets.length;i++) {\n            const alts = altsets[i];\n            const minAlt = alts.minValue();\n            if(result===null) {\n                result = minAlt;\n            } else if(result!==minAlt) { // more than 1 viable alt\n                return ATN.INVALID_ALT_NUMBER;\n            }\n        }\n        return result;\n    }\n};\n\nexport default PredictionMode;\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/SemanticContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport equalArrays from \"../utils/equalArrays.js\";\nimport HashCode from \"../misc/HashCode.js\";\nimport HashSet from \"../misc/HashSet.js\";\n\n/**\n * A tree structure used to record the semantic context in which\n * an ATN configuration is valid.  It's either a single predicate,\n * a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.\n *\n * <p>I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of\n * {@link SemanticContext} within the scope of this outer class.</p>\n */\nexport default class SemanticContext {\n\n\thashCode() {\n\t\tconst hash = new HashCode();\n\t\tthis.updateHashCode(hash);\n\t\treturn hash.finish();\n\t}\n\n\t/**\n\t * For context independent predicates, we evaluate them without a local\n\t * context (i.e., null context). That way, we can evaluate them without\n\t * having to create proper rule-specific context during prediction (as\n\t * opposed to the parser, which creates them naturally). In a practical\n\t * sense, this avoids a cast exception from RuleContext to myruleContext.\n\t *\n\t * <p>For context dependent predicates, we must pass in a local context so that\n\t * references such as $arg evaluate properly as _localctx.arg. We only\n\t * capture context dependent predicates in the context in which we begin\n\t * prediction, so we passed in the outer context here in case of context\n\t * dependent predicate evaluation.</p>\n\t */\n\tevaluate(parser, outerContext) {}\n\n\t/**\n\t * Evaluate the precedence predicates for the context and reduce the result.\n\t *\n\t * @param parser The parser instance.\n\t * @param outerContext The current parser context object.\n\t * @return The simplified semantic context after precedence predicates are\n\t * evaluated, which will be one of the following values.\n\t * <ul>\n\t * <li>{@link //NONE}: if the predicate simplifies to {@code true} after\n\t * precedence predicates are evaluated.</li>\n\t * <li>{@code null}: if the predicate simplifies to {@code false} after\n\t * precedence predicates are evaluated.</li>\n\t * <li>{@code this}: if the semantic context is not changed as a result of\n\t * precedence predicate evaluation.</li>\n\t * <li>A non-{@code null} {@link SemanticContext}: the new simplified\n\t * semantic context after precedence predicates are evaluated.</li>\n\t * </ul>\n\t */\n\tevalPrecedence(parser, outerContext) {\n\t\treturn this;\n\t}\n\n\tstatic andContext(a, b) {\n\t\tif (a === null || a === SemanticContext.NONE) {\n\t\t\treturn b;\n\t\t}\n\t\tif (b === null || b === SemanticContext.NONE) {\n\t\t\treturn a;\n\t\t}\n\t\tconst result = new AND(a, b);\n\t\tif (result.opnds.length === 1) {\n\t\t\treturn result.opnds[0];\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tstatic orContext(a, b) {\n\t\tif (a === null) {\n\t\t\treturn b;\n\t\t}\n\t\tif (b === null) {\n\t\t\treturn a;\n\t\t}\n\t\tif (a === SemanticContext.NONE || b === SemanticContext.NONE) {\n\t\t\treturn SemanticContext.NONE;\n\t\t}\n\t\tconst result = new OR(a, b);\n\t\tif (result.opnds.length === 1) {\n\t\t\treturn result.opnds[0];\n\t\t} else {\n\t\t\treturn result;\n\t\t}\n\t}\n}\n\n\n\nclass AND extends SemanticContext {\n\t/**\n\t * A semantic context which is true whenever none of the contained contexts\n\t * is false\n\t */\n\tconstructor(a, b) {\n\t\tsuper();\n\t\tconst operands = new HashSet();\n\t\tif (a instanceof AND) {\n\t\t\ta.opnds.map(function(o) {\n\t\t\t\toperands.add(o);\n\t\t\t});\n\t\t} else {\n\t\t\toperands.add(a);\n\t\t}\n\t\tif (b instanceof AND) {\n\t\t\tb.opnds.map(function(o) {\n\t\t\t\toperands.add(o);\n\t\t\t});\n\t\t} else {\n\t\t\toperands.add(b);\n\t\t}\n\t\tconst precedencePredicates = filterPrecedencePredicates(operands);\n\t\tif (precedencePredicates.length > 0) {\n\t\t\t// interested in the transition with the lowest precedence\n\t\t\tlet reduced = null;\n\t\t\tprecedencePredicates.map( function(p) {\n\t\t\t\tif(reduced===null || p.precedence<reduced.precedence) {\n\t\t\t\t\treduced = p;\n\t\t\t\t}\n\t\t\t});\n\t\t\toperands.add(reduced);\n\t\t}\n\t\tthis.opnds = Array.from(operands.values());\n\t}\n\n\tequals(other) {\n\t\tif (this === other) {\n\t\t\treturn true;\n\t\t} else if (!(other instanceof AND)) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn equalArrays(this.opnds, other.opnds);\n\t\t}\n\t}\n\n\tupdateHashCode(hash) {\n\t\thash.update(this.opnds, \"AND\");\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>\n\t * The evaluation of predicates by this context is short-circuiting, but\n\t * unordered.</p>\n\t */\n\tevaluate(parser, outerContext) {\n\t\tfor (let i = 0; i < this.opnds.length; i++) {\n\t\t\tif (!this.opnds[i].evaluate(parser, outerContext)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tevalPrecedence(parser, outerContext) {\n\t\tlet differs = false;\n\t\tconst operands = [];\n\t\tfor (let i = 0; i < this.opnds.length; i++) {\n\t\t\tconst context = this.opnds[i];\n\t\t\tconst evaluated = context.evalPrecedence(parser, outerContext);\n\t\t\tdiffers |= (evaluated !== context);\n\t\t\tif (evaluated === null) {\n\t\t\t\t// The AND context is false if any element is false\n\t\t\t\treturn null;\n\t\t\t} else if (evaluated !== SemanticContext.NONE) {\n\t\t\t\t// Reduce the result by skipping true elements\n\t\t\t\toperands.push(evaluated);\n\t\t\t}\n\t\t}\n\t\tif (!differs) {\n\t\t\treturn this;\n\t\t}\n\t\tif (operands.length === 0) {\n\t\t\t// all elements were true, so the AND context is true\n\t\t\treturn SemanticContext.NONE;\n\t\t}\n\t\tlet result = null;\n\t\toperands.map(function(o) {\n\t\t\tresult = result === null ? o : SemanticContext.andContext(result, o);\n\t\t});\n\t\treturn result;\n\t}\n\n\ttoString() {\n\t\tconst s = this.opnds.map(o => o.toString());\n\t\treturn (s.length > 3 ? s.slice(3) : s).join(\"&&\");\n\t}\n}\n\n\nclass OR extends SemanticContext {\n\t/**\n\t * A semantic context which is true whenever at least one of the contained\n\t * contexts is true\n\t */\n\tconstructor(a, b) {\n\t\tsuper();\n\t\tconst operands = new HashSet();\n\t\tif (a instanceof OR) {\n\t\t\ta.opnds.map(function(o) {\n\t\t\t\toperands.add(o);\n\t\t\t});\n\t\t} else {\n\t\t\toperands.add(a);\n\t\t}\n\t\tif (b instanceof OR) {\n\t\t\tb.opnds.map(function(o) {\n\t\t\t\toperands.add(o);\n\t\t\t});\n\t\t} else {\n\t\t\toperands.add(b);\n\t\t}\n\n\t\tconst precedencePredicates = filterPrecedencePredicates(operands);\n\t\tif (precedencePredicates.length > 0) {\n\t\t\t// interested in the transition with the highest precedence\n\t\t\tconst s = precedencePredicates.sort(function(a, b) {\n\t\t\t\treturn a.compareTo(b);\n\t\t\t});\n\t\t\tconst reduced = s[s.length-1];\n\t\t\toperands.add(reduced);\n\t\t}\n\t\tthis.opnds = Array.from(operands.values());\n\t}\n\n\tequals(other) {\n\t\tif (this === other) {\n\t\t\treturn true;\n\t\t} else if (!(other instanceof OR)) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn equalArrays(this.opnds, other.opnds);\n\t\t}\n\t}\n\n\tupdateHashCode(hash) {\n\t\thash.update(this.opnds, \"OR\");\n\t}\n\n\t/**\n\t * <p>\n\t * The evaluation of predicates by this context is short-circuiting, but\n\t * unordered.</p>\n\t */\n\tevaluate(parser, outerContext) {\n\t\tfor (let i = 0; i < this.opnds.length; i++) {\n\t\t\tif (this.opnds[i].evaluate(parser, outerContext)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tevalPrecedence(parser, outerContext) {\n\t\tlet differs = false;\n\t\tconst operands = [];\n\t\tfor (let i = 0; i < this.opnds.length; i++) {\n\t\t\tconst context = this.opnds[i];\n\t\t\tconst evaluated = context.evalPrecedence(parser, outerContext);\n\t\t\tdiffers |= (evaluated !== context);\n\t\t\tif (evaluated === SemanticContext.NONE) {\n\t\t\t\t// The OR context is true if any element is true\n\t\t\t\treturn SemanticContext.NONE;\n\t\t\t} else if (evaluated !== null) {\n\t\t\t\t// Reduce the result by skipping false elements\n\t\t\t\toperands.push(evaluated);\n\t\t\t}\n\t\t}\n\t\tif (!differs) {\n\t\t\treturn this;\n\t\t}\n\t\tif (operands.length === 0) {\n\t\t\t// all elements were false, so the OR context is false\n\t\t\treturn null;\n\t\t}\n\t\tconst result = null;\n\t\toperands.map(function(o) {\n\t\t\treturn result === null ? o : SemanticContext.orContext(result, o);\n\t\t});\n\t\treturn result;\n\t}\n\n\ttoString() {\n\t\tconst s = this.opnds.map(o => o.toString());\n\t\treturn (s.length > 3 ? s.slice(3) : s).join(\"||\");\n\t}\n}\n\nfunction filterPrecedencePredicates(set) {\n\tconst result = [];\n\tset.values().map( function(context) {\n\t\tif (context instanceof SemanticContext.PrecedencePredicate) {\n\t\t\tresult.push(context);\n\t\t}\n\t});\n\treturn result;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/index.d.ts",
    "content": "export * from \"./ATN.js\";\nexport * from \"./ATNConfig.js\";\nexport * from \"./ATNConfigSet.js\";\nexport * from \"./ATNDeserializer.js\";\nexport * from \"./LexerATNSimulator.js\";\nexport * from \"./ParserATNSimulator.js\";\nexport * from \"./PredictionMode.js\";\nexport * from \"./PredictionContextCache.js\";\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/atn/index.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport ATN from './ATN.js';\nimport ATNDeserializer from './ATNDeserializer.js';\nimport LexerATNSimulator from './LexerATNSimulator.js';\nimport ParserATNSimulator from './ParserATNSimulator.js';\nimport PredictionMode from './PredictionMode.js';\nimport PredictionContextCache from './PredictionContextCache.js';\n\nexport default { ATN, ATNDeserializer, LexerATNSimulator, ParserATNSimulator, PredictionMode, PredictionContextCache }\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/ArrayPredictionContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport PredictionContext from \"./PredictionContext.js\";\nimport equalArrays from \"../utils/equalArrays.js\";\nimport HashCode from \"../misc/HashCode.js\";\n\nexport default class ArrayPredictionContext extends PredictionContext {\n\n    constructor(parents, returnStates) {\n        /**\n         * Parent can be null only if full ctx mode and we make an array\n         * from {@link //EMPTY} and non-empty. We merge {@link //EMPTY} by using\n         * null parent and\n         * returnState == {@link //EMPTY_RETURN_STATE}.\n         */\n        const h = new HashCode();\n        h.update(parents, returnStates);\n        const hashCode = h.finish();\n        super(hashCode);\n        this.parents = parents;\n        this.returnStates = returnStates;\n        return this;\n    }\n\n    isEmpty() {\n        // since EMPTY_RETURN_STATE can only appear in the last position, we\n        // don't need to verify that size==1\n        return this.returnStates[0] === PredictionContext.EMPTY_RETURN_STATE;\n    }\n\n    getParent(index) {\n        return this.parents[index];\n    }\n\n    getReturnState(index) {\n        return this.returnStates[index];\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (!(other instanceof ArrayPredictionContext)) {\n            return false;\n        } else if (this.hashCode() !== other.hashCode()) {\n            return false; // can't be same if hash is different\n        } else {\n            return equalArrays(this.returnStates, other.returnStates) &&\n                equalArrays(this.parents, other.parents);\n        }\n    }\n\n    toString() {\n        if (this.isEmpty()) {\n            return \"[]\";\n        } else {\n            let s = \"[\";\n            for (let i = 0; i < this.returnStates.length; i++) {\n                if (i > 0) {\n                    s = s + \", \";\n                }\n                if (this.returnStates[i] === PredictionContext.EMPTY_RETURN_STATE) {\n                    s = s + \"$\";\n                    continue;\n                }\n                s = s + this.returnStates[i];\n                if (this.parents[i] !== null) {\n                    s = s + \" \" + this.parents[i];\n                } else {\n                    s = s + \"null\";\n                }\n            }\n            return s + \"]\";\n        }\n    }\n\n    get length(){\n        return this.returnStates.length;\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/EmptyPredictionContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport PredictionContext from \"./PredictionContext.js\";\nimport SingletonPredictionContext from \"./SingletonPredictionContext.js\";\n\nexport default class EmptyPredictionContext extends SingletonPredictionContext {\n\n    constructor() {\n        super(null, PredictionContext.EMPTY_RETURN_STATE);\n    }\n\n    isEmpty() {\n        return true;\n    }\n\n    getParent(index) {\n        return null;\n    }\n\n    getReturnState(index) {\n        return this.returnState;\n    }\n\n    equals(other) {\n        return this === other;\n    }\n\n    toString() {\n        return \"$\";\n    }\n}\n\n\nPredictionContext.EMPTY = new EmptyPredictionContext();\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/InterpreterRuleContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ParserRuleContext from \"./ParserRuleContext.js\";\n\nexport default class InterpreterRuleContext extends ParserRuleContext {\n    constructor(parent, invokingStateNumber, ruleIndex) {\n        super(parent, invokingStateNumber);\n        this.ruleIndex = ruleIndex;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/ParserRuleContext.d.ts",
    "content": "import {RuleContext} from \"./RuleContext.js\";\nimport {ParseTree, TerminalNode} from \"../tree/index.js\";\nimport {RecognitionException} from \"../error/index.js\";\nimport {Token} from \"../Token.js\";\nimport {Parser} from \"../Parser.js\";\n\nexport declare class ParserRuleContext extends RuleContext {\n    start: Token;\n    stop: Token | undefined;\n    children: ParseTree[] | null;\n    parentCtx: ParserRuleContext | undefined;\n    exception?: RecognitionException;\n    parser?: Parser;\n\n    constructor(parent?: ParserRuleContext, invokingStateNumber?: number);\n    copyFrom(ctx: ParserRuleContext): void;\n    getChildCount() : number;\n    getChild(i: number) : ParseTree;\n    getToken(ttype: number, i: number): TerminalNode;\n    getTokens(ttype: number): TerminalNode[];\n    getTypedRuleContext<T extends ParserRuleContext, P extends Parser>(ctxType: { new (parser?: P, parent?: ParserRuleContext, invokingState?: number, ...args: any[]) : T}, i: number): T;\n    getTypedRuleContexts<T extends ParserRuleContext, P extends Parser>(ctxType: { new (parser?: P, parent?: ParserRuleContext, invokingState?: number, ...args: any[]) : T}): T[];\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/ParserRuleContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport RuleContext from './RuleContext.js';\nimport TerminalNode from '../tree/TerminalNode.js';\nimport TerminalNodeImpl from '../tree/TerminalNodeImpl.js';\nimport ErrorNodeImpl from '../tree/ErrorNodeImpl.js';\nimport Interval from \"../misc/Interval.js\";\n\n/**\n * A rule invocation record for parsing.\n *\n *  Contains all of the information about the current rule not stored in the\n *  RuleContext. It handles parse tree children list, Any ATN state\n *  tracing, and the default values available for rule indications:\n *  start, stop, rule index, current alt number, current\n *  ATN state.\n *\n *  Subclasses made for each rule and grammar track the parameters,\n *  return values, locals, and labels specific to that rule. These\n *  are the objects that are returned from rules.\n *\n *  Note text is not an actual field of a rule return value; it is computed\n *  from start and stop using the input stream's toString() method.  I\n *  could add a ctor to this so that we can pass in and store the input\n *  stream, but I'm not sure we want to do that.  It would seem to be undefined\n *  to get the .text property anyway if the rule matches tokens from multiple\n *  input streams.\n *\n *  I do not use getters for fields of objects that are used simply to\n *  group values such as this aggregate.  The getters/setters are there to\n *  satisfy the superclass interface.\n */\nexport default class ParserRuleContext extends RuleContext {\n\n\tconstructor(parent, invokingStateNumber) {\n\t\tsuper(parent, invokingStateNumber);\n\t\t/**\n\t\t * If we are debugging or building a parse tree for a visitor,\n\t\t * we need to track all of the tokens and rule invocations associated\n\t\t * with this rule's context. This is empty for parsing w/o tree constr.\n\t\t * operation because we don't the need to track the details about\n\t\t * how we parse this rule.\n\t\t */\n\t\tthis.children = null;\n\t\tthis.start = null;\n\t\tthis.stop = null;\n\t\t/**\n\t\t * The exception that forced this rule to return. If the rule successfully\n\t\t * completed, this is {@code null}.\n\t\t */\n\t\tthis.exception = null;\n\t}\n\n\t// COPY a ctx (I'm deliberately not using copy constructor)\n\tcopyFrom(ctx) {\n\t\t// from RuleContext\n\t\tthis.parentCtx = ctx.parentCtx;\n\t\tthis.invokingState = ctx.invokingState;\n\t\tthis.children = null;\n\t\tthis.start = ctx.start;\n\t\tthis.stop = ctx.stop;\n\t\t// copy any error nodes to alt label node\n\t\tif(ctx.children) {\n\t\t\tthis.children = [];\n\t\t\t// reset parent pointer for any error nodes\n\t\t\tctx.children.map(function(child) {\n\t\t\t\tif (child instanceof ErrorNodeImpl) {\n\t\t\t\t\tthis.children.push(child);\n\t\t\t\t\tchild.parentCtx = this;\n\t\t\t\t}\n\t\t\t}, this);\n\t\t}\n\t}\n\n\t// Double dispatch methods for listeners\n\tenterRule(listener) {\n\t}\n\n\texitRule(listener) {\n\t}\n\n\t// Does not set parent link; other add methods do that\n\taddChild(child) {\n\t\tif (this.children === null) {\n\t\t\tthis.children = [];\n\t\t}\n\t\tthis.children.push(child);\n\t\treturn child;\n\t}\n\n\t/** Used by enterOuterAlt to toss out a RuleContext previously added as\n\t * we entered a rule. If we have // label, we will need to remove\n\t * generic ruleContext object.\n\t */\n\tremoveLastChild() {\n\t\tif (this.children !== null) {\n\t\t\tthis.children.pop();\n\t\t}\n\t}\n\n\taddTokenNode(token) {\n\t\tconst node = new TerminalNodeImpl(token);\n\t\tthis.addChild(node);\n\t\tnode.parentCtx = this;\n\t\treturn node;\n\t}\n\n\taddErrorNode(badToken) {\n\t\tconst node = new ErrorNodeImpl(badToken);\n\t\tthis.addChild(node);\n\t\tnode.parentCtx = this;\n\t\treturn node;\n\t}\n\n\tgetChild(i, type) {\n\t\ttype = type || null;\n\t\tif (this.children === null || i < 0 || i >= this.children.length) {\n\t\t\treturn null;\n\t\t}\n\t\tif (type === null) {\n\t\t\treturn this.children[i];\n\t\t} else {\n\t\t\tfor(let j=0; j<this.children.length; j++) {\n\t\t\t\tconst child = this.children[j];\n\t\t\t\tif(child instanceof type) {\n\t\t\t\t\tif(i===0) {\n\t\t\t\t\t\treturn child;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ti -= 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tgetToken(ttype, i) {\n\t\tif (this.children === null || i < 0 || i >= this.children.length) {\n\t\t\treturn null;\n\t\t}\n\t\tfor(let j=0; j<this.children.length; j++) {\n\t\t\tconst child = this.children[j];\n\t\t\tif (child instanceof TerminalNode) {\n\t\t\t\tif (child.symbol.type === ttype) {\n\t\t\t\t\tif(i===0) {\n\t\t\t\t\t\treturn child;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ti -= 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tgetTokens(ttype ) {\n\t\tif (this.children=== null) {\n\t\t\treturn [];\n\t\t} else {\n\t\t\tconst tokens = [];\n\t\t\tfor(let j=0; j<this.children.length; j++) {\n\t\t\t\tconst child = this.children[j];\n\t\t\t\tif (child instanceof TerminalNode) {\n\t\t\t\t\tif (child.symbol.type === ttype) {\n\t\t\t\t\t\ttokens.push(child);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tokens;\n\t\t}\n\t}\n\n\tgetTypedRuleContext(ctxType, i) {\n\t\treturn this.getChild(i, ctxType);\n\t}\n\n\tgetTypedRuleContexts(ctxType) {\n\t\tif (this.children=== null) {\n\t\t\treturn [];\n\t\t} else {\n\t\t\tconst contexts = [];\n\t\t\tfor(let j=0; j<this.children.length; j++) {\n\t\t\t\tconst child = this.children[j];\n\t\t\t\tif (child instanceof ctxType) {\n\t\t\t\t\tcontexts.push(child);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn contexts;\n\t\t}\n\t}\n\n\tgetChildCount() {\n\t\tif (this.children=== null) {\n\t\t\treturn 0;\n\t\t} else {\n\t\t\treturn this.children.length;\n\t\t}\n\t}\n\n\tgetSourceInterval() {\n\t\tif( this.start === null || this.stop === null) {\n\t\t\treturn Interval.INVALID_INTERVAL;\n\t\t} else {\n\t\t\treturn new Interval(this.start.tokenIndex, this.stop.tokenIndex);\n\t\t}\n\t}\n}\n\nRuleContext.EMPTY = new ParserRuleContext();\n\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/PredictionContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport default class PredictionContext {\n\n\tconstructor(cachedHashCode) {\n\t\tthis.cachedHashCode = cachedHashCode;\n\t}\n\n\t/**\n\t * Stores the computed hash code of this {@link PredictionContext}. The hash\n\t * code is computed in parts to match the following reference algorithm.\n\t *\n\t * <pre>\n\t * private int referenceHashCode() {\n\t * int hash = {@link MurmurHash//initialize MurmurHash.initialize}({@link\n\t * //INITIAL_HASH});\n\t *\n\t * for (int i = 0; i &lt; {@link //size()}; i++) {\n\t * hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link //getParent\n\t * getParent}(i));\n\t * }\n\t *\n\t * for (int i = 0; i &lt; {@link //size()}; i++) {\n\t * hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link\n\t * //getReturnState getReturnState}(i));\n\t * }\n\t *\n\t * hash = {@link MurmurHash//finish MurmurHash.finish}(hash, 2// {@link\n\t * //size()});\n\t * return hash;\n\t * }\n\t * </pre>\n\t * This means only the {@link //EMPTY} context is in set.\n\t */\n\tisEmpty() {\n\t\treturn this === PredictionContext.EMPTY;\n\t}\n\n\thasEmptyPath() {\n\t\treturn this.getReturnState(this.length - 1) === PredictionContext.EMPTY_RETURN_STATE;\n\t}\n\n\thashCode() {\n\t\treturn this.cachedHashCode;\n\t}\n\n\tupdateHashCode(hash) {\n\t\thash.update(this.cachedHashCode);\n\t}\n}\n\n/**\n * Represents {@code $} in local context prediction, which means wildcard.\n * {@code//+x =//}.\n */\nPredictionContext.EMPTY = null;\n\n/**\n * Represents {@code $} in an array in full context mode, when {@code $}\n * doesn't mean wildcard: {@code $ + x = [$,x]}. Here,\n * {@code $} = {@link //EMPTY_RETURN_STATE}.\n */\nPredictionContext.EMPTY_RETURN_STATE = 0x7FFFFFFF;\n\nPredictionContext.globalNodeCount = 1;\nPredictionContext.id = PredictionContext.globalNodeCount;\nPredictionContext.trace_atn_sim = false;"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/PredictionContextUtils.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport RuleContext from \"./RuleContext.js\";\nimport PredictionContext from \"./PredictionContext.js\";\nimport ArrayPredictionContext from \"./ArrayPredictionContext.js\";\nimport SingletonPredictionContext from \"./SingletonPredictionContext.js\";\nimport EmptyPredictionContext from \"./EmptyPredictionContext.js\";\nimport HashMap from \"../misc/HashMap.js\";\n\n/**\n * Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.\n * Return {@link //EMPTY} if {@code outerContext} is empty or null.\n */\nexport function predictionContextFromRuleContext(atn, outerContext) {\n    if (outerContext === undefined || outerContext === null) {\n        outerContext = RuleContext.EMPTY;\n    }\n    // if we are in RuleContext of start rule, s, then PredictionContext\n    // is EMPTY. Nobody called us. (if we are empty, return empty)\n    if (outerContext.parentCtx === null || outerContext === RuleContext.EMPTY) {\n        return PredictionContext.EMPTY;\n    }\n    // If we have a parent, convert it to a PredictionContext graph\n    const parent = predictionContextFromRuleContext(atn, outerContext.parentCtx);\n    const state = atn.states[outerContext.invokingState];\n    const transition = state.transitions[0];\n    return SingletonPredictionContext.create(parent, transition.followState.stateNumber);\n}\n\n\nexport function getCachedPredictionContext(context, contextCache, visited) {\n    if (context.isEmpty()) {\n        return context;\n    }\n    let existing = visited.get(context) || null;\n    if (existing !== null) {\n        return existing;\n    }\n    existing = contextCache.get(context);\n    if (existing !== null) {\n        visited.set(context, existing);\n        return existing;\n    }\n    let changed = false;\n    let parents = [];\n    for (let i = 0; i < parents.length; i++) {\n        const parent = getCachedPredictionContext(context.getParent(i), contextCache, visited);\n        if (changed || parent !== context.getParent(i)) {\n            if (!changed) {\n                parents = [];\n                for (let j = 0; j < context.length; j++) {\n                    parents[j] = context.getParent(j);\n                }\n                changed = true;\n            }\n            parents[i] = parent;\n        }\n    }\n    if (!changed) {\n        contextCache.add(context);\n        visited.set(context, context);\n        return context;\n    }\n    let updated = null;\n    if (parents.length === 0) {\n        updated = PredictionContext.EMPTY;\n    } else if (parents.length === 1) {\n        updated = SingletonPredictionContext.create(parents[0], context\n            .getReturnState(0));\n    } else {\n        updated = new ArrayPredictionContext(parents, context.returnStates);\n    }\n    contextCache.add(updated);\n    visited.set(updated, updated);\n    visited.set(context, updated);\n\n    return updated;\n}\n\nexport function merge(a, b, rootIsWildcard, mergeCache) {\n    // share same graph if both same\n    if (a === b) {\n        return a;\n    }\n    if (a instanceof SingletonPredictionContext && b instanceof SingletonPredictionContext) {\n        return mergeSingletons(a, b, rootIsWildcard, mergeCache);\n    }\n    // At least one of a or b is array\n    // If one is $ and rootIsWildcard, return $ as * wildcard\n    if (rootIsWildcard) {\n        if (a instanceof EmptyPredictionContext) {\n            return a;\n        }\n        if (b instanceof EmptyPredictionContext) {\n            return b;\n        }\n    }\n    // convert singleton so both are arrays to normalize\n    if (a instanceof SingletonPredictionContext) {\n        a = new ArrayPredictionContext([a.getParent()], [a.returnState]);\n    }\n    if (b instanceof SingletonPredictionContext) {\n        b = new ArrayPredictionContext([b.getParent()], [b.returnState]);\n    }\n    return mergeArrays(a, b, rootIsWildcard, mergeCache);\n}\n\n\n/**\n * Merge two {@link ArrayPredictionContext} instances.\n *\n * <p>Different tops, different parents.<br>\n * <embed src=\"images/ArrayMerge_DiffTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n *\n * <p>Shared top, same parents.<br>\n * <embed src=\"images/ArrayMerge_ShareTopSamePar.svg\" type=\"image/svg+xml\"/></p>\n *\n * <p>Shared top, different parents.<br>\n * <embed src=\"images/ArrayMerge_ShareTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n *\n * <p>Shared top, all shared parents.<br>\n * <embed src=\"images/ArrayMerge_ShareTopSharePar.svg\"\n * type=\"image/svg+xml\"/></p>\n *\n * <p>Equal tops, merge parents and reduce top to\n * {@link SingletonPredictionContext}.<br>\n * <embed src=\"images/ArrayMerge_EqualTop.svg\" type=\"image/svg+xml\"/></p>\n */\nfunction mergeArrays(a, b, rootIsWildcard, mergeCache) {\n    if (mergeCache !== null) {\n        let previous = mergeCache.get(a, b);\n        if (previous !== null) {\n            if ( PredictionContext.trace_atn_sim ) console.log(\"mergeArrays a=\"+a+\",b=\"+b+\" -> previous\");\n            return previous;\n        }\n        previous = mergeCache.get(b, a);\n        if (previous !== null) {\n            if ( PredictionContext.trace_atn_sim ) console.log(\"mergeArrays a=\"+a+\",b=\"+b+\" -> previous\");\n            return previous;\n        }\n    }\n    // merge sorted payloads a + b => M\n    let i = 0; // walks a\n    let j = 0; // walks b\n    let k = 0; // walks target M array\n\n    let mergedReturnStates = new Array(a.returnStates.length + b.returnStates.length).fill(0);\n    let mergedParents = new Array(a.returnStates.length + b.returnStates.length).fill(null);\n    // walk and merge to yield mergedParents, mergedReturnStates\n    while (i < a.returnStates.length && j < b.returnStates.length) {\n        const a_parent = a.parents[i];\n        const b_parent = b.parents[j];\n        if (a.returnStates[i] === b.returnStates[j]) {\n            // same payload (stack tops are equal), must yield merged singleton\n            const payload = a.returnStates[i];\n            // $+$ = $\n            const bothDollars = payload === PredictionContext.EMPTY_RETURN_STATE &&\n                a_parent === null && b_parent === null;\n            const ax_ax = (a_parent !== null && b_parent !== null && a_parent === b_parent); // ax+ax\n            // ->\n            // ax\n            if (bothDollars || ax_ax) {\n                mergedParents[k] = a_parent; // choose left\n                mergedReturnStates[k] = payload;\n            } else { // ax+ay -> a'[x,y]\n                mergedParents[k] = merge(a_parent, b_parent, rootIsWildcard, mergeCache);\n                mergedReturnStates[k] = payload;\n            }\n            i += 1; // hop over left one as usual\n            j += 1; // but also skip one in right side since we merge\n        } else if (a.returnStates[i] < b.returnStates[j]) { // copy a[i] to M\n            mergedParents[k] = a_parent;\n            mergedReturnStates[k] = a.returnStates[i];\n            i += 1;\n        } else { // b > a, copy b[j] to M\n            mergedParents[k] = b_parent;\n            mergedReturnStates[k] = b.returnStates[j];\n            j += 1;\n        }\n        k += 1;\n    }\n    // copy over any payloads remaining in either array\n    if (i < a.returnStates.length) {\n        for (let p = i; p < a.returnStates.length; p++) {\n            mergedParents[k] = a.parents[p];\n            mergedReturnStates[k] = a.returnStates[p];\n            k += 1;\n        }\n    } else {\n        for (let p = j; p < b.returnStates.length; p++) {\n            mergedParents[k] = b.parents[p];\n            mergedReturnStates[k] = b.returnStates[p];\n            k += 1;\n        }\n    }\n    // trim merged if we combined a few that had same stack tops\n    if (k < mergedParents.length) { // write index < last position; trim\n        if (k === 1) { // for just one merged element, return singleton top\n            const a_ = SingletonPredictionContext.create(mergedParents[0],\n                mergedReturnStates[0]);\n            if (mergeCache !== null) {\n                mergeCache.set(a, b, a_);\n            }\n            return a_;\n        }\n        mergedParents = mergedParents.slice(0, k);\n        mergedReturnStates = mergedReturnStates.slice(0, k);\n    }\n\n    const M = new ArrayPredictionContext(mergedParents, mergedReturnStates);\n\n    // if we created same array as a or b, return that instead\n    // TODO: track whether this is possible above during merge sort for speed\n    if (M.equals(a)) {\n        if (mergeCache !== null) {\n            mergeCache.set(a, b, a);\n        }\n        if ( PredictionContext.trace_atn_sim ) console.log(\"mergeArrays a=\"+a+\",b=\"+b+\" -> a\");\n        return a;\n    }\n    if (M.equals(b)) {\n        if (mergeCache !== null) {\n            mergeCache.set(a, b, b);\n        }\n        if ( PredictionContext.trace_atn_sim ) console.log(\"mergeArrays a=\"+a+\",b=\"+b+\" -> b\");\n        return b;\n    }\n    combineCommonParents(mergedParents);\n\n    if (mergeCache !== null) {\n        mergeCache.set(a, b, M);\n    }\n\n    if ( PredictionContext.trace_atn_sim ) console.log(\"mergeArrays a=\"+a+\",b=\"+b+\" -> \"+M);\n\n    return M;\n}\n\n\n/**\n * Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}\n * ones.\n */\nfunction combineCommonParents(parents) {\n    const uniqueParents = new HashMap();\n\n    for (let p = 0; p < parents.length; p++) {\n        const parent = parents[p];\n        if (!(uniqueParents.containsKey(parent))) {\n            uniqueParents.set(parent, parent);\n        }\n    }\n    for (let q = 0; q < parents.length; q++) {\n        parents[q] = uniqueParents.get(parents[q]);\n    }\n}\n\n\n/**\n * Merge two {@link SingletonPredictionContext} instances.\n *\n * <p>Stack tops equal, parents merge is same; return left graph.<br>\n * <embed src=\"images/SingletonMerge_SameRootSamePar.svg\"\n * type=\"image/svg+xml\"/></p>\n *\n * <p>Same stack top, parents differ; merge parents giving array node, then\n * remainders of those graphs. A new root node is created to point to the\n * merged parents.<br>\n * <embed src=\"images/SingletonMerge_SameRootDiffPar.svg\"\n * type=\"image/svg+xml\"/></p>\n *\n * <p>Different stack tops pointing to same parent. Make array node for the\n * root where both element in the root point to the same (original)\n * parent.<br>\n * <embed src=\"images/SingletonMerge_DiffRootSamePar.svg\"\n * type=\"image/svg+xml\"/></p>\n *\n * <p>Different stack tops pointing to different parents. Make array node for\n * the root where each element points to the corresponding original\n * parent.<br>\n * <embed src=\"images/SingletonMerge_DiffRootDiffPar.svg\"\n * type=\"image/svg+xml\"/></p>\n *\n * @param a the first {@link SingletonPredictionContext}\n * @param b the second {@link SingletonPredictionContext}\n * @param rootIsWildcard {@code true} if this is a local-context merge,\n * otherwise false to indicate a full-context merge\n * @param mergeCache\n */\nfunction mergeSingletons(a, b, rootIsWildcard, mergeCache) {\n    if (mergeCache !== null) {\n        let previous = mergeCache.get(a, b);\n        if (previous !== null) {\n            return previous;\n        }\n        previous = mergeCache.get(b, a);\n        if (previous !== null) {\n            return previous;\n        }\n    }\n\n    const rootMerge = mergeRoot(a, b, rootIsWildcard);\n    if (rootMerge !== null) {\n        if (mergeCache !== null) {\n            mergeCache.set(a, b, rootMerge);\n        }\n        return rootMerge;\n    }\n    if (a.returnState === b.returnState) {\n        const parent = merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache);\n        // if parent is same as existing a or b parent or reduced to a parent,\n        // return it\n        if (parent === a.parentCtx) {\n            return a; // ax + bx = ax, if a=b\n        }\n        if (parent === b.parentCtx) {\n            return b; // ax + bx = bx, if a=b\n        }\n        // else: ax + ay = a'[x,y]\n        // merge parents x and y, giving array node with x,y then remainders\n        // of those graphs. dup a, a' points at merged array\n        // new joined parent so create new singleton pointing to it, a'\n        const spc = SingletonPredictionContext.create(parent, a.returnState);\n        if (mergeCache !== null) {\n            mergeCache.set(a, b, spc);\n        }\n        return spc;\n    } else { // a != b payloads differ\n        // see if we can collapse parents due to $+x parents if local ctx\n        let singleParent = null;\n        if (a === b || (a.parentCtx !== null && a.parentCtx === b.parentCtx)) { // ax +\n            // bx =\n            // [a,b]x\n            singleParent = a.parentCtx;\n        }\n        if (singleParent !== null) { // parents are same\n            // sort payloads and use same parent\n            const payloads = [ a.returnState, b.returnState ];\n            if (a.returnState > b.returnState) {\n                payloads[0] = b.returnState;\n                payloads[1] = a.returnState;\n            }\n            const parents = [ singleParent, singleParent ];\n            const apc = new ArrayPredictionContext(parents, payloads);\n            if (mergeCache !== null) {\n                mergeCache.set(a, b, apc);\n            }\n            return apc;\n        }\n        // parents differ and can't merge them. Just pack together\n        // into array; can't merge.\n        // ax + by = [ax,by]\n        const payloads = [ a.returnState, b.returnState ];\n        let parents = [ a.parentCtx, b.parentCtx ];\n        if (a.returnState > b.returnState) { // sort by payload\n            payloads[0] = b.returnState;\n            payloads[1] = a.returnState;\n            parents = [ b.parentCtx, a.parentCtx ];\n        }\n        const a_ = new ArrayPredictionContext(parents, payloads);\n        if (mergeCache !== null) {\n            mergeCache.set(a, b, a_);\n        }\n        return a_;\n    }\n}\n\n\n/**\n * Handle case where at least one of {@code a} or {@code b} is\n * {@link //EMPTY}. In the following diagrams, the symbol {@code $} is used\n * to represent {@link //EMPTY}.\n *\n * <h2>Local-Context Merges</h2>\n *\n * <p>These local-context merge operations are used when {@code rootIsWildcard}\n * is true.</p>\n *\n * <p>{@link //EMPTY} is superset of any graph; return {@link //EMPTY}.<br>\n * <embed src=\"images/LocalMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n *\n * <p>{@link //EMPTY} and anything is {@code //EMPTY}, so merged parent is\n * {@code //EMPTY}; return left graph.<br>\n * <embed src=\"images/LocalMerge_EmptyParent.svg\" type=\"image/svg+xml\"/></p>\n *\n * <p>Special case of last merge if local context.<br>\n * <embed src=\"images/LocalMerge_DiffRoots.svg\" type=\"image/svg+xml\"/></p>\n *\n * <h2>Full-Context Merges</h2>\n *\n * <p>These full-context merge operations are used when {@code rootIsWildcard}\n * is false.</p>\n *\n * <p><embed src=\"images/FullMerge_EmptyRoots.svg\" type=\"image/svg+xml\"/></p>\n *\n * <p>Must keep all contexts; {@link //EMPTY} in array is a special value (and\n * null parent).<br>\n * <embed src=\"images/FullMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n *\n * <p><embed src=\"images/FullMerge_SameRoot.svg\" type=\"image/svg+xml\"/></p>\n *\n * @param a the first {@link SingletonPredictionContext}\n * @param b the second {@link SingletonPredictionContext}\n * @param rootIsWildcard {@code true} if this is a local-context merge,\n * otherwise false to indicate a full-context merge\n */\nfunction mergeRoot(a, b, rootIsWildcard) {\n    if (rootIsWildcard) {\n        if (a === PredictionContext.EMPTY) {\n            return PredictionContext.EMPTY; // // + b =//\n        }\n        if (b === PredictionContext.EMPTY) {\n            return PredictionContext.EMPTY; // a +// =//\n        }\n    } else {\n        if (a === PredictionContext.EMPTY && b === PredictionContext.EMPTY) {\n            return PredictionContext.EMPTY; // $ + $ = $\n        } else if (a === PredictionContext.EMPTY) { // $ + x = [$,x]\n            const payloads = [ b.returnState,\n                PredictionContext.EMPTY_RETURN_STATE ];\n            const parents = [ b.parentCtx, null ];\n            return new ArrayPredictionContext(parents, payloads);\n        } else if (b === PredictionContext.EMPTY) { // x + $ = [$,x] ($ is always first if present)\n            const payloads = [ a.returnState, PredictionContext.EMPTY_RETURN_STATE ];\n            const parents = [ a.parentCtx, null ];\n            return new ArrayPredictionContext(parents, payloads);\n        }\n    }\n    return null;\n}\n\n\n// ter's recursive version of Sam's getAllNodes()\nexport function getAllContextNodes(context, nodes, visited) {\n    if (nodes === null) {\n        nodes = [];\n        return getAllContextNodes(context, nodes, visited);\n    } else if (visited === null) {\n        visited = new HashMap();\n        return getAllContextNodes(context, nodes, visited);\n    } else {\n        if (context === null || visited.containsKey(context)) {\n            return nodes;\n        }\n        visited.set(context, context);\n        nodes.push(context);\n        for (let i = 0; i < context.length; i++) {\n            getAllContextNodes(context.getParent(i), nodes, visited);\n        }\n        return nodes;\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/RuleContext.d.ts",
    "content": "import {RuleNode} from \"../tree/index.js\";\nimport {Parser} from \"../Parser.js\";\n\nexport declare class RuleContext extends RuleNode {\n    parentCtx: RuleContext | undefined;\n    invokingState: number;\n\n    get ruleContext() : RuleContext;\n    toStringTree(ruleNames: string[] | null, recog: Parser) : string;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/RuleContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport RuleNode from '../tree/RuleNode.js';\nimport Interval from '../misc/Interval.js';\nimport Trees from '../tree/Trees.js';\n\nexport default class RuleContext extends RuleNode {\n    /** A rule context is a record of a single rule invocation. It knows\n     * which context invoked it, if any. If there is no parent context, then\n     * naturally the invoking state is not valid.  The parent link\n     * provides a chain upwards from the current rule invocation to the root\n     * of the invocation tree, forming a stack. We actually carry no\n     * information about the rule associated with this context (except\n     * when parsing). We keep only the state number of the invoking state from\n     * the ATN submachine that invoked this. Contrast this with the s\n     * pointer inside ParserRuleContext that tracks the current state\n     * being \"executed\" for the current rule.\n     *\n     * The parent contexts are useful for computing lookahead sets and\n     * getting error information.\n     *\n     * These objects are used during parsing and prediction.\n     * For the special case of parsers, we use the subclass\n     * ParserRuleContext.\n     *\n     * @see ParserRuleContext\n     */\n    constructor(parent, invokingState) {\n        // What context invoked this rule?\n        super();\n        this.parentCtx = parent || null;\n        /**\n         * What state invoked the rule associated with this context?\n         * The \"return address\" is the followState of invokingState\n         * If parent is null, this should be -1.\n         */\n        this.invokingState = invokingState || -1;\n    }\n\n    depth() {\n        let n = 0;\n        let p = this;\n        while (p !== null) {\n            p = p.parentCtx;\n            n += 1;\n        }\n        return n;\n    }\n\n    /**\n     * A context is empty if there is no invoking state; meaning nobody call\n     * current context.\n     */\n    isEmpty() {\n        return this.invokingState === -1;\n    }\n\n// satisfy the ParseTree / SyntaxTree interface\n    getSourceInterval() {\n        return Interval.INVALID_INTERVAL;\n    }\n\n    get ruleContext() {\n        return this;\n    }\n\n    getPayload() {\n        return this;\n    }\n\n    /**\n     * Return the combined text of all child nodes. This method only considers\n     * tokens which have been added to the parse tree.\n     * <p>\n     * Since tokens on hidden channels (e.g. whitespace or comments) are not\n     * added to the parse trees, they will not appear in the output of this\n     * method.\n     */\n    getText() {\n        if (this.getChildCount() === 0) {\n            return \"\";\n        } else {\n            return this.children.map(function (child) {\n                return child.getText();\n            }).join(\"\");\n        }\n    }\n\n    /**\n     * For rule associated with this parse tree internal node, return\n     * the outer alternative number used to match the input. Default\n     * implementation does not compute nor store this alt num. Create\n     * a subclass of ParserRuleContext with backing field and set\n     * option contextSuperClass.\n     * to set it.\n     */\n    getAltNumber() {\n        // use constant value of ATN.INVALID_ALT_NUMBER to avoid circular dependency\n        return 0;\n    }\n\n    /**\n     * Set the outer alternative number for this context node. Default\n     * implementation does nothing to avoid backing field overhead for\n     * trees that don't need it.  Create\n     * a subclass of ParserRuleContext with backing field and set\n     * option contextSuperClass.\n     */\n    setAltNumber(altNumber) {\n    }\n\n    getChild(i) {\n        return null;\n    }\n\n    getChildCount() {\n        return 0;\n    }\n\n    accept(visitor) {\n        return visitor.visitChildren(this);\n    }\n\n    /**\n     * Print out a whole tree, not just a node, in LISP format\n     * (root child1 .. childN). Print just a node if this is a leaf.\n     */\n    toStringTree(ruleNames, recog) {\n        return Trees.toStringTree(this, ruleNames, recog);\n    }\n\n    toString(ruleNames, stop) {\n        ruleNames = ruleNames || null;\n        stop = stop || null;\n        let p = this;\n        let s = \"[\";\n        while (p !== null && p !== stop) {\n            if (ruleNames === null) {\n                if (!p.isEmpty()) {\n                    s += p.invokingState;\n                }\n            } else {\n                const ri = p.ruleIndex;\n                const ruleName = (ri >= 0 && ri < ruleNames.length) ? ruleNames[ri]\n                    : \"\" + ri;\n                s += ruleName;\n            }\n            if (p.parentCtx !== null && (ruleNames !== null || !p.parentCtx.isEmpty())) {\n                s += \" \";\n            }\n            p = p.parentCtx;\n        }\n        s += \"]\";\n        return s;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/SingletonPredictionContext.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport PredictionContext from './PredictionContext.js';\nimport HashCode from \"../misc/HashCode.js\";\n\nexport default class SingletonPredictionContext extends PredictionContext {\n\n    constructor(parent, returnState) {\n        let hashCode = 0;\n        const hash = new HashCode();\n        if(parent !== null) {\n            hash.update(parent, returnState);\n        } else {\n            hash.update(1);\n        }\n        hashCode = hash.finish();\n        super(hashCode);\n        this.parentCtx = parent;\n        this.returnState = returnState;\n    }\n\n    getParent(index) {\n        return this.parentCtx;\n    }\n\n    getReturnState(index) {\n        return this.returnState;\n    }\n\n    equals(other) {\n        if (this === other) {\n            return true;\n        } else if (!(other instanceof SingletonPredictionContext)) {\n            return false;\n        } else if (this.hashCode() !== other.hashCode()) {\n            return false; // can't be same if hash is different\n        } else {\n            if(this.returnState !== other.returnState)\n                return false;\n            else if(this.parentCtx==null)\n                return other.parentCtx==null\n            else\n                return this.parentCtx.equals(other.parentCtx);\n        }\n    }\n\n    toString() {\n        const up = this.parentCtx === null ? \"\" : this.parentCtx.toString();\n        if (up.length === 0) {\n            if (this.returnState === PredictionContext.EMPTY_RETURN_STATE) {\n                return \"$\";\n            } else {\n                return \"\" + this.returnState;\n            }\n        } else {\n            return \"\" + this.returnState + \" \" + up;\n        }\n    }\n\n    get length(){\n        return 1;\n    }\n\n    static create(parent, returnState) {\n        if (returnState === PredictionContext.EMPTY_RETURN_STATE && parent === null) {\n            // someone can pass in the bits of an array ctx that mean $\n            return PredictionContext.EMPTY;\n        } else {\n            return new SingletonPredictionContext(parent, returnState);\n        }\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/index.d.ts",
    "content": "export * from \"./RuleContext.js\";\nexport * from \"./ParserRuleContext.js\";\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/context/index.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport PredictionContext from './PredictionContext.js';\n\nexport default { PredictionContext }\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/DFA.d.ts",
    "content": "export declare class DFA {\n    constructor(ds: any, index: number);\n    toLexerString(): string;\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/DFA.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport DFAState from './DFAState.js';\nimport StarLoopEntryState from '../state/StarLoopEntryState.js';\nimport ATNConfigSet from './../atn/ATNConfigSet.js';\nimport DFASerializer from './DFASerializer.js';\nimport LexerDFASerializer from './LexerDFASerializer.js';\nimport HashSet from \"../misc/HashSet.js\";\n\nexport default class DFA {\n\tconstructor(atnStartState, decision) {\n\t\tif (decision === undefined) {\n\t\t\tdecision = 0;\n\t\t}\n\t\t/**\n\t\t * From which ATN state did we create this DFA?\n\t\t */\n\t\tthis.atnStartState = atnStartState;\n\t\tthis.decision = decision;\n\t\t/**\n\t\t * A set of all DFA states. Use {@link Map} so we can get old state back\n\t\t * ({@link Set} only allows you to see if it's there).\n\t\t */\n\t\tthis._states = new HashSet();\n\t\tthis.s0 = null;\n\t\t/**\n\t\t * {@code true} if this DFA is for a precedence decision; otherwise,\n\t\t * {@code false}. This is the backing field for {@link //isPrecedenceDfa},\n\t\t * {@link //setPrecedenceDfa}\n\t\t */\n\t\tthis.precedenceDfa = false;\n\t\tif (atnStartState instanceof StarLoopEntryState)\n\t\t{\n\t\t\tif (atnStartState.isPrecedenceDecision) {\n\t\t\t\tthis.precedenceDfa = true;\n\t\t\t\tconst precedenceState = new DFAState(null, new ATNConfigSet());\n\t\t\t\tprecedenceState.edges = [];\n\t\t\t\tprecedenceState.isAcceptState = false;\n\t\t\t\tprecedenceState.requiresFullContext = false;\n\t\t\t\tthis.s0 = precedenceState;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the start state for a specific precedence value.\n\t *\n\t * @param precedence The current precedence.\n\t * @return The start state corresponding to the specified precedence, or\n\t * {@code null} if no start state exists for the specified precedence.\n\t *\n\t * @throws IllegalStateException if this is not a precedence DFA.\n\t * @see //isPrecedenceDfa()\n\t */\n\tgetPrecedenceStartState(precedence) {\n\t\tif (!(this.precedenceDfa)) {\n\t\t\tthrow (\"Only precedence DFAs may contain a precedence start state.\");\n\t\t}\n\t\t// s0.edges is never null for a precedence DFA\n\t\tif (precedence < 0 || precedence >= this.s0.edges.length) {\n\t\t\treturn null;\n\t\t}\n\t\treturn this.s0.edges[precedence] || null;\n\t}\n\n\t/**\n\t * Set the start state for a specific precedence value.\n\t *\n\t * @param precedence The current precedence.\n\t * @param startState The start state corresponding to the specified\n\t * precedence.\n\t *\n\t * @throws IllegalStateException if this is not a precedence DFA.\n\t * @see //isPrecedenceDfa()\n\t */\n\tsetPrecedenceStartState(precedence, startState) {\n\t\tif (!(this.precedenceDfa)) {\n\t\t\tthrow (\"Only precedence DFAs may contain a precedence start state.\");\n\t\t}\n\t\tif (precedence < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t/**\n\t\t * synchronization on s0 here is ok. when the DFA is turned into a\n\t\t * precedence DFA, s0 will be initialized once and not updated again\n\t\t * s0.edges is never null for a precedence DFA\n\t\t */\n\t\tthis.s0.edges[precedence] = startState;\n\t}\n\n\t/**\n\t * Sets whether this is a precedence DFA. If the specified value differs\n\t * from the current DFA configuration, the following actions are taken;\n\t * otherwise no changes are made to the current DFA.\n\t *\n\t * <ul>\n\t * <li>The {@link //states} map is cleared</li>\n\t * <li>If {@code precedenceDfa} is {@code false}, the initial state\n\t * {@link //s0} is set to {@code null}; otherwise, it is initialized to a new\n\t * {@link DFAState} with an empty outgoing {@link DFAState//edges} array to\n\t * store the start states for individual precedence values.</li>\n\t * <li>The {@link //precedenceDfa} field is updated</li>\n\t * </ul>\n\t *\n\t * @param precedenceDfa {@code true} if this is a precedence DFA; otherwise,\n\t * {@code false}\n\t */\n\tsetPrecedenceDfa(precedenceDfa) {\n\t\tif (this.precedenceDfa!==precedenceDfa) {\n\t\t\tthis._states = new HashSet();\n\t\t\tif (precedenceDfa) {\n\t\t\t\tconst precedenceState = new DFAState(null, new ATNConfigSet());\n\t\t\t\tprecedenceState.edges = [];\n\t\t\t\tprecedenceState.isAcceptState = false;\n\t\t\t\tprecedenceState.requiresFullContext = false;\n\t\t\t\tthis.s0 = precedenceState;\n\t\t\t} else {\n\t\t\t\tthis.s0 = null;\n\t\t\t}\n\t\t\tthis.precedenceDfa = precedenceDfa;\n\t\t}\n\t}\n\n\t/**\n\t * Return a list of all states in this DFA, ordered by state number.\n\t */\n\tsortedStates() {\n\t\tconst list = this._states.values();\n\t\treturn list.sort(function(a, b) {\n\t\t\treturn a.stateNumber - b.stateNumber;\n\t\t});\n\t}\n\n\ttoString(literalNames, symbolicNames) {\n\t\tliteralNames = literalNames || null;\n\t\tsymbolicNames = symbolicNames || null;\n\t\tif (this.s0 === null) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst serializer = new DFASerializer(this, literalNames, symbolicNames);\n\t\treturn serializer.toString();\n\t}\n\n\ttoLexerString() {\n\t\tif (this.s0 === null) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst serializer = new LexerDFASerializer(this);\n\t\treturn serializer.toString();\n\t}\n\n\tget states(){\n\t\treturn this._states;\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/DFASerializer.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\nimport arrayToString from \"../utils/arrayToString.js\";\n\n/**\n * A DFA walker that knows how to dump them to serialized strings.\n */\nexport default class DFASerializer {\n    constructor(dfa, literalNames, symbolicNames) {\n        this.dfa = dfa;\n        this.literalNames = literalNames || [];\n        this.symbolicNames = symbolicNames || [];\n    }\n\n    toString() {\n       if(this.dfa.s0 === null) {\n           return null;\n       }\n       let buf = \"\";\n       const states = this.dfa.sortedStates();\n       for(let i=0; i<states.length; i++) {\n           const s = states[i];\n           if(s.edges!==null) {\n                const n = s.edges.length;\n                for(let j=0;j<n;j++) {\n                    const t = s.edges[j] || null;\n                    if(t!==null && t.stateNumber !== 0x7FFFFFFF) {\n                        buf = buf.concat(this.getStateString(s));\n                        buf = buf.concat(\"-\");\n                        buf = buf.concat(this.getEdgeLabel(j));\n                        buf = buf.concat(\"->\");\n                        buf = buf.concat(this.getStateString(t));\n                        buf = buf.concat('\\n');\n                    }\n                }\n           }\n       }\n       return buf.length===0 ? null : buf;\n    }\n\n    getEdgeLabel(i) {\n        if (i===0) {\n            return \"EOF\";\n        } else if(this.literalNames !==null || this.symbolicNames!==null) {\n            return this.literalNames[i-1] || this.symbolicNames[i-1];\n        } else {\n            return String.fromCharCode(i-1);\n        }\n    }\n\n    getStateString(s) {\n        const baseStateStr = ( s.isAcceptState ? \":\" : \"\") + \"s\" + s.stateNumber + ( s.requiresFullContext ? \"^\" : \"\");\n        if(s.isAcceptState) {\n            if (s.predicates !== null) {\n                return baseStateStr + \"=>\" + arrayToString(s.predicates);\n            } else {\n                return baseStateStr + \"=>\" + s.prediction.toString();\n            }\n        } else {\n            return baseStateStr;\n        }\n    }\n}\n\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/DFAState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport ATNConfigSet from '../atn/ATNConfigSet.js';\nimport HashCode from \"../misc/HashCode.js\";\nimport HashSet from \"../misc/HashSet.js\";\n\n\n/**\n * A DFA state represents a set of possible ATN configurations.\n * As Aho, Sethi, Ullman p. 117 says \"The DFA uses its state\n * to keep track of all possible states the ATN can be in after\n * reading each input symbol. That is to say, after reading\n * input a1a2..an, the DFA is in a state that represents the\n * subset T of the states of the ATN that are reachable from the\n * ATN's start state along some path labeled a1a2..an.\"\n * In conventional NFA&rarr;DFA conversion, therefore, the subset T\n * would be a bitset representing the set of states the\n * ATN could be in. We need to track the alt predicted by each\n * state as well, however. More importantly, we need to maintain\n * a stack of states, tracking the closure operations as they\n * jump from rule to rule, emulating rule invocations (method calls).\n * I have to add a stack to simulate the proper lookahead sequences for\n * the underlying LL grammar from which the ATN was derived.\n *\n * <p>I use a set of ATNConfig objects not simple states. An ATNConfig\n * is both a state (ala normal conversion) and a RuleContext describing\n * the chain of rules (if any) followed to arrive at that state.</p>\n *\n * <p>A DFA state may have multiple references to a particular state,\n * but with different ATN contexts (with same or different alts)\n * meaning that state was reached via a different set of rule invocations.</p>\n */\nexport default class DFAState {\n\tconstructor(stateNumber, configs) {\n\t\tif (stateNumber === null) {\n\t\t\tstateNumber = -1;\n\t\t}\n\t\tif (configs === null) {\n\t\t\tconfigs = new ATNConfigSet();\n\t\t}\n\t\tthis.stateNumber = stateNumber;\n\t\tthis.configs = configs;\n\t\t/**\n\t\t * {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)\n\t\t * {@link Token//EOF} maps to {@code edges[0]}.\n\t\t */\n\t\tthis.edges = null;\n\t\tthis.isAcceptState = false;\n\t\t/**\n\t\t * if accept state, what ttype do we match or alt do we predict?\n\t\t * This is set to {@link ATN//INVALID_ALT_NUMBER} when {@link//predicates}\n\t\t * {@code !=null} or {@link //requiresFullContext}.\n\t\t */\n\t\tthis.prediction = 0;\n\t\tthis.lexerActionExecutor = null;\n\t\t/**\n\t\t * Indicates that this state was created during SLL prediction that\n\t\t * discovered a conflict between the configurations in the state. Future\n\t\t * {@link ParserATNSimulator//execATN} invocations immediately jumped doing\n\t\t * full context prediction if this field is true.\n\t\t */\n\t\tthis.requiresFullContext = false;\n\t\t/**\n\t\t * During SLL parsing, this is a list of predicates associated with the\n\t\t * ATN configurations of the DFA state. When we have predicates,\n\t\t * {@link //requiresFullContext} is {@code false} since full context\n\t\t * prediction evaluates predicates\n\t\t * on-the-fly. If this is not null, then {@link //prediction} is\n\t\t * {@link ATN//INVALID_ALT_NUMBER}.\n\t\t *\n\t\t * <p>We only use these for non-{@link //requiresFullContext} but\n\t\t * conflicting states. That\n\t\t * means we know from the context (it's $ or we don't dip into outer\n\t\t * context) that it's an ambiguity not a conflict.</p>\n\t\t *\n\t\t * <p>This list is computed by {@link\n\t\t * ParserATNSimulator//predicateDFAState}.</p>\n\t\t */\n\t\tthis.predicates = null;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the set of all alts mentioned by all ATN configurations in this\n\t * DFA state.\n\t */\n\tgetAltSet() {\n\t\tconst alts = new HashSet();\n\t\tif (this.configs !== null) {\n\t\t\tfor (let i = 0; i < this.configs.length; i++) {\n\t\t\t\tconst c = this.configs[i];\n\t\t\t\talts.add(c.alt);\n\t\t\t}\n\t\t}\n\t\tif (alts.length === 0) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn alts;\n\t\t}\n\t}\n\n\t/**\n\t * Two {@link DFAState} instances are equal if their ATN configuration sets\n\t * are the same. This method is used to see if a state already exists.\n\t *\n\t * <p>Because the number of alternatives and number of ATN configurations are\n\t * finite, there is a finite number of DFA states that can be processed.\n\t * This is necessary to show that the algorithm terminates.</p>\n\t *\n\t * <p>Cannot test the DFA state numbers here because in\n\t * {@link ParserATNSimulator//addDFAState} we need to know if any other state\n\t * exists that has this exact set of ATN configurations. The\n\t * {@link //stateNumber} is irrelevant.</p>\n\t */\n\tequals(other) {\n\t\t// compare set of ATN configurations in this set with other\n\t\treturn this === other ||\n\t\t\t\t(other instanceof DFAState &&\n\t\t\t\t\tthis.configs.equals(other.configs));\n\t}\n\n\ttoString() {\n\t\tlet s = \"\" + this.stateNumber + \":\" + this.configs;\n\t\tif(this.isAcceptState) {\n\t\t\ts = s + \"=>\";\n\t\t\tif (this.predicates !== null)\n\t\t\t\ts = s + this.predicates;\n\t\t\telse\n\t\t\t\ts = s + this.prediction;\n\t\t}\n\t\treturn s;\n\t}\n\n\thashCode() {\n\t\tconst hash = new HashCode();\n\t\thash.update(this.configs);\n\t\treturn hash.finish();\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/LexerDFASerializer.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport DFASerializer from \"./DFASerializer.js\";\n\nexport default class LexerDFASerializer extends DFASerializer {\n    constructor(dfa) {\n        super(dfa, null);\n    }\n\n    getEdgeLabel(i) {\n        return \"'\" + String.fromCharCode(i) + \"'\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/PredPrediction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n/**\n * Map a predicate to a predicted alternative.\n */\nexport default class PredPrediction {\n    constructor(pred, alt) {\n        this.alt = alt;\n        this.pred = pred;\n    }\n\n    toString() {\n        return \"(\" + this.pred + \", \" + this.alt + \")\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/index.d.ts",
    "content": "export * from \"./DFA.js\";\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/dfa/index.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport DFA from './DFA.js';\nimport DFASerializer from './DFASerializer.js';\nimport LexerDFASerializer from './LexerDFASerializer.js';\nimport PredPrediction from './PredPrediction.js';\n\nexport default { DFA, DFASerializer, LexerDFASerializer, PredPrediction };\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/BailErrorStrategy.d.ts",
    "content": "import {DefaultErrorStrategy} from \"./DefaultErrorStrategy.js\";\n\nexport declare class BailErrorStrategy extends DefaultErrorStrategy {\n\n    constructor();\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/BailErrorStrategy.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport InputMismatchException from \"./InputMismatchException.js\";\nimport ParseCancellationException from \"./ParseCancellationException.js\";\nimport DefaultErrorStrategy from \"./DefaultErrorStrategy.js\";\n\n/**\n * This implementation of {@link ANTLRErrorStrategy} responds to syntax errors\n * by immediately canceling the parse operation with a\n * {@link ParseCancellationException}. The implementation ensures that the\n * {@link ParserRuleContext//exception} field is set for all parse tree nodes\n * that were not completed prior to encountering the error.\n *\n * <p>\n * This error strategy is useful in the following scenarios.</p>\n *\n * <ul>\n * <li><strong>Two-stage parsing:</strong> This error strategy allows the first\n * stage of two-stage parsing to immediately terminate if an error is\n * encountered, and immediately fall back to the second stage. In addition to\n * avoiding wasted work by attempting to recover from errors here, the empty\n * implementation of {@link BailErrorStrategy//sync} improves the performance of\n * the first stage.</li>\n * <li><strong>Silent validation:</strong> When syntax errors are not being\n * reported or logged, and the parse result is simply ignored if errors occur,\n * the {@link BailErrorStrategy} avoids wasting work on recovering from errors\n * when the result will be ignored either way.</li>\n * </ul>\n *\n * <p>\n * {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>\n *\n * @see Parser//setErrorHandler(ANTLRErrorStrategy)\n * */\nexport default class BailErrorStrategy extends DefaultErrorStrategy {\n\n    constructor() {\n        super();\n    }\n\n    /**\n     * Instead of recovering from exception {@code e}, re-throw it wrapped\n     * in a {@link ParseCancellationException} so it is not caught by the\n     * rule function catches. Use {@link Exception//getCause()} to get the\n     * original {@link RecognitionException}.\n     */\n    recover(recognizer, e) {\n        let context = recognizer._ctx\n        while (context !== null) {\n            context.exception = e;\n            context = context.parentCtx;\n        }\n        throw new ParseCancellationException(e);\n    }\n\n    /**\n     * Make sure we don't attempt to recover inline; if the parser\n     * successfully recovers, it won't throw an exception.\n     */\n    recoverInline(recognizer) {\n        this.recover(recognizer, new InputMismatchException(recognizer));\n    }\n\n// Make sure we don't attempt to recover from problems in subrules.//\n    sync(recognizer) {\n        // pass\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/ConsoleErrorListener.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ErrorListener from \"./ErrorListener.js\";\n\n/**\n * {@inheritDoc}\n *\n * <p>\n * This implementation prints messages to {@link System//err} containing the\n * values of {@code line}, {@code charPositionInLine}, and {@code msg} using\n * the following format.</p>\n *\n * <pre>\n * line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>\n * </pre>\n *\n */\nexport default class ConsoleErrorListener extends ErrorListener {\n    constructor() {\n        super();\n    }\n\n    syntaxError(recognizer, offendingSymbol, line, column, msg, e) {\n        console.error(\"line \" + line + \":\" + column + \" \" + msg);\n    }\n}\n\n\n/**\n * Provides a default instance of {@link ConsoleErrorListener}.\n */\nConsoleErrorListener.INSTANCE = new ConsoleErrorListener();\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/DefaultErrorStrategy.d.ts",
    "content": "import {ErrorStrategy} from \"./ErrorStrategy.js\";\nimport {RecognitionException} from \"./RecognitionException.js\";\nimport {Parser} from \"../Parser.js\";\nimport {Token} from \"../Token.js\";\n\nexport declare class DefaultErrorStrategy implements ErrorStrategy {\n    recover(recognizer: Parser, e: RecognitionException): void;\n\n    recoverInline(recognizer: Parser): Token;\n\n    reportError(recognizer: Parser, e: RecognitionException): void;\n\n    reportMatch(recognizer: Parser): void;\n\n    reset(recognizer: Parser): void;\n\n    sync(recognizer: Parser): void;\n\n    inErrorRecoveryMode(recognizer: Parser): boolean;\n\n    beginErrorCondition(recognizer: Parser): void;\n\n    getMissingSymbol(recognizer: Parser): Token;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/DefaultErrorStrategy.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport FailedPredicateException from \"./FailedPredicateException.js\";\nimport InputMismatchException from \"./InputMismatchException.js\";\nimport NoViableAltException from \"./NoViableAltException.js\";\nimport ATNState from \"../state/ATNState.js\";\nimport Token from '../Token.js';\nimport Interval from \"../misc/Interval.js\";\nimport IntervalSet from \"../misc/IntervalSet.js\";\nimport ErrorStrategy from \"./ErrorStrategy.js\";\n\n/**\n * This is the default implementation of {@link ANTLRErrorStrategy} used for\n * error reporting and recovery in ANTLR parsers.\n */\nexport default class DefaultErrorStrategy extends ErrorStrategy {\n    constructor() {\n        super();\n        /**\n         * Indicates whether the error strategy is currently \"recovering from an\n         * error\". This is used to suppress reporting multiple error messages while\n         * attempting to recover from a detected syntax error.\n         *\n         * @see //inErrorRecoveryMode\n         */\n        this.errorRecoveryMode = false;\n\n        /**\n         * The index into the input stream where the last error occurred.\n         * This is used to prevent infinite loops where an error is found\n         * but no token is consumed during recovery...another error is found,\n         * ad nauseum. This is a failsafe mechanism to guarantee that at least\n         * one token/tree node is consumed for two errors.\n         */\n        this.lastErrorIndex = -1;\n        this.lastErrorStates = null;\n        this.nextTokensContext = null;\n        this.nextTokenState = 0;\n    }\n\n    /**\n     * <p>The default implementation simply calls {@link //endErrorCondition} to\n     * ensure that the handler is not in error recovery mode.</p>\n     */\n    reset(recognizer) {\n        this.endErrorCondition(recognizer);\n    }\n\n    /**\n     * This method is called to enter error recovery mode when a recognition\n     * exception is reported.\n     *\n     * @param recognizer the parser instance\n     */\n    beginErrorCondition(recognizer) {\n        this.errorRecoveryMode = true;\n    }\n\n    inErrorRecoveryMode(recognizer) {\n        return this.errorRecoveryMode;\n    }\n\n    /**\n     * This method is called to leave error recovery mode after recovering from\n     * a recognition exception.\n     * @param recognizer\n     */\n    endErrorCondition(recognizer) {\n        this.errorRecoveryMode = false;\n        this.lastErrorStates = null;\n        this.lastErrorIndex = -1;\n    }\n\n    /**\n     * {@inheritDoc}\n     * <p>The default implementation simply calls {@link //endErrorCondition}.</p>\n     */\n    reportMatch(recognizer) {\n        this.endErrorCondition(recognizer);\n    }\n\n    /**\n     * {@inheritDoc}\n     *\n     * <p>The default implementation returns immediately if the handler is already\n     * in error recovery mode. Otherwise, it calls {@link //beginErrorCondition}\n     * and dispatches the reporting task based on the runtime type of {@code e}\n     * according to the following table.</p>\n     *\n     * <ul>\n     * <li>{@link NoViableAltException}: Dispatches the call to\n     * {@link //reportNoViableAlternative}</li>\n     * <li>{@link InputMismatchException}: Dispatches the call to\n     * {@link //reportInputMismatch}</li>\n     * <li>{@link FailedPredicateException}: Dispatches the call to\n     * {@link //reportFailedPredicate}</li>\n     * <li>All other types: calls {@link Parser//notifyErrorListeners} to report\n     * the exception</li>\n     * </ul>\n     */\n    reportError(recognizer, e) {\n        // if we've already reported an error and have not matched a token\n        // yet successfully, don't report any errors.\n        if(this.inErrorRecoveryMode(recognizer)) {\n            return; // don't report spurious errors\n        }\n        this.beginErrorCondition(recognizer);\n        if ( e instanceof NoViableAltException ) {\n            this.reportNoViableAlternative(recognizer, e);\n        } else if ( e instanceof InputMismatchException ) {\n            this.reportInputMismatch(recognizer, e);\n        } else if ( e instanceof FailedPredicateException ) {\n            this.reportFailedPredicate(recognizer, e);\n        } else {\n            console.log(\"unknown recognition error type: \" + e.constructor.name);\n            console.log(e.stack);\n            recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);\n        }\n    }\n\n    /**\n     *\n     * {@inheritDoc}\n     *\n     * <p>The default implementation resynchronizes the parser by consuming tokens\n     * until we find one in the resynchronization set--loosely the set of tokens\n     * that can follow the current rule.</p>\n     *\n     */\n    recover(recognizer, e) {\n        if (this.lastErrorIndex===recognizer.getInputStream().index &&\n            this.lastErrorStates !== null && this.lastErrorStates.indexOf(recognizer.state)>=0) {\n            // uh oh, another error at same token index and previously-visited\n            // state in ATN; must be a case where LT(1) is in the recovery\n            // token set so nothing got consumed. Consume a single token\n            // at least to prevent an infinite loop; this is a failsafe.\n            recognizer.consume();\n        }\n        this.lastErrorIndex = recognizer._input.index;\n        if (this.lastErrorStates === null) {\n            this.lastErrorStates = [];\n        }\n        this.lastErrorStates.push(recognizer.state);\n        const followSet = this.getErrorRecoverySet(recognizer)\n        this.consumeUntil(recognizer, followSet);\n    }\n\n    /**\n     * The default implementation of {@link ANTLRErrorStrategy//sync} makes sure\n     * that the current lookahead symbol is consistent with what were expecting\n     * at this point in the ATN. You can call this anytime but ANTLR only\n     * generates code to check before subrules/loops and each iteration.\n     *\n     * <p>Implements Jim Idle's magic sync mechanism in closures and optional\n     * subrules. E.g.,</p>\n     *\n     * <pre>\n     * a : sync ( stuff sync )* ;\n     * sync : {consume to what can follow sync} ;\n     * </pre>\n     *\n     * At the start of a sub rule upon error, {@link //sync} performs single\n     * token deletion, if possible. If it can't do that, it bails on the current\n     * rule and uses the default error recovery, which consumes until the\n     * resynchronization set of the current rule.\n     *\n     * <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block\n     * with an empty alternative), then the expected set includes what follows\n     * the subrule.</p>\n     *\n     * <p>During loop iteration, it consumes until it sees a token that can start a\n     * sub rule or what follows loop. Yes, that is pretty aggressive. We opt to\n     * stay in the loop as long as possible.</p>\n     *\n     * <p><strong>ORIGINS</strong></p>\n     *\n     * <p>Previous versions of ANTLR did a poor job of their recovery within loops.\n     * A single mismatch token or missing token would force the parser to bail\n     * out of the entire rules surrounding the loop. So, for rule</p>\n     *\n     * <pre>\n     * classDef : 'class' ID '{' member* '}'\n     * </pre>\n     *\n     * input with an extra token between members would force the parser to\n     * consume until it found the next class definition rather than the next\n     * member definition of the current class.\n     *\n     * <p>This functionality cost a little bit of effort because the parser has to\n     * compare token set at the start of the loop and at each iteration. If for\n     * some reason speed is suffering for you, you can turn off this\n     * functionality by simply overriding this method as a blank { }.</p>\n     *\n     */\n    sync(recognizer) {\n        // If already recovering, don't try to sync\n        if (this.inErrorRecoveryMode(recognizer)) {\n            return;\n        }\n        const s = recognizer._interp.atn.states[recognizer.state];\n        const la = recognizer.getTokenStream().LA(1);\n        // try cheaper subset first; might get lucky. seems to shave a wee bit off\n        const nextTokens = recognizer.atn.nextTokens(s);\n        if(nextTokens.contains(la)) {\n            this.nextTokensContext = null;\n            this.nextTokenState = ATNState.INVALID_STATE_NUMBER;\n            return;\n        } else if (nextTokens.contains(Token.EPSILON)) {\n            if(this.nextTokensContext === null) {\n                // It's possible the next token won't match information tracked\n                // by sync is restricted for performance.\n                this.nextTokensContext = recognizer._ctx;\n                this.nextTokensState = recognizer._stateNumber;\n            }\n            return;\n        }\n        switch (s.stateType) {\n            case ATNState.BLOCK_START:\n            case ATNState.STAR_BLOCK_START:\n            case ATNState.PLUS_BLOCK_START:\n            case ATNState.STAR_LOOP_ENTRY:\n                // report error and recover if possible\n                if( this.singleTokenDeletion(recognizer) !== null) {\n                    return;\n                } else {\n                    throw new InputMismatchException(recognizer);\n                }\n            case ATNState.PLUS_LOOP_BACK:\n            case ATNState.STAR_LOOP_BACK:\n                {\n                this.reportUnwantedToken(recognizer);\n                const expecting = new IntervalSet();\n                expecting.addSet(recognizer.getExpectedTokens());\n                const whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer));\n                this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule);\n                }\n                break;\n            default:\n            // do nothing if we can't identify the exact kind of ATN state\n        }\n    }\n\n    /**\n     * This is called by {@link //reportError} when the exception is a\n     * {@link NoViableAltException}.\n     *\n     * @see //reportError\n     *\n     * @param recognizer the parser instance\n     * @param e the recognition exception\n     */\n    reportNoViableAlternative(recognizer, e) {\n        const tokens = recognizer.getTokenStream()\n        let input\n        if(tokens !== null) {\n            if (e.startToken.type===Token.EOF) {\n                input = \"<EOF>\";\n            } else {\n                input = tokens.getText(new Interval(e.startToken.tokenIndex, e.offendingToken.tokenIndex));\n            }\n        } else {\n            input = \"<unknown input>\";\n        }\n        const msg = \"no viable alternative at input \" + this.escapeWSAndQuote(input)\n        recognizer.notifyErrorListeners(msg, e.offendingToken, e);\n    }\n\n    /**\n     * This is called by {@link //reportError} when the exception is an\n     * {@link InputMismatchException}.\n     *\n     * @see //reportError\n     *\n     * @param recognizer the parser instance\n     * @param e the recognition exception\n     */\n    reportInputMismatch(recognizer, e) {\n        const msg = \"mismatched input \" + this.getTokenErrorDisplay(e.offendingToken) +\n            \" expecting \" + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames)\n        recognizer.notifyErrorListeners(msg, e.offendingToken, e);\n    }\n\n    /**\n     * This is called by {@link //reportError} when the exception is a\n     * {@link FailedPredicateException}.\n     *\n     * @see //reportError\n     *\n     * @param recognizer the parser instance\n     * @param e the recognition exception\n     */\n    reportFailedPredicate(recognizer, e) {\n        const ruleName = recognizer.ruleNames[recognizer._ctx.ruleIndex]\n        const msg = \"rule \" + ruleName + \" \" + e.message\n        recognizer.notifyErrorListeners(msg, e.offendingToken, e);\n    }\n\n    /**\n     * This method is called to report a syntax error which requires the removal\n     * of a token from the input stream. At the time this method is called, the\n     * erroneous symbol is current {@code LT(1)} symbol and has not yet been\n     * removed from the input stream. When this method returns,\n     * {@code recognizer} is in error recovery mode.\n     *\n     * <p>This method is called when {@link //singleTokenDeletion} identifies\n     * single-token deletion as a viable recovery strategy for a mismatched\n     * input error.</p>\n     *\n     * <p>The default implementation simply returns if the handler is already in\n     * error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to\n     * enter error recovery mode, followed by calling\n     * {@link Parser//notifyErrorListeners}.</p>\n     *\n     * @param recognizer the parser instance\n     *\n     */\n    reportUnwantedToken(recognizer) {\n        if (this.inErrorRecoveryMode(recognizer)) {\n            return;\n        }\n        this.beginErrorCondition(recognizer);\n        const t = recognizer.getCurrentToken()\n        const tokenName = this.getTokenErrorDisplay(t)\n        const expecting = this.getExpectedTokens(recognizer)\n        const msg = \"extraneous input \" + tokenName + \" expecting \" +\n            expecting.toString(recognizer.literalNames, recognizer.symbolicNames)\n        recognizer.notifyErrorListeners(msg, t, null);\n    }\n\n    /**\n     * This method is called to report a syntax error which requires the\n     * insertion of a missing token into the input stream. At the time this\n     * method is called, the missing token has not yet been inserted. When this\n     * method returns, {@code recognizer} is in error recovery mode.\n     *\n     * <p>This method is called when {@link //singleTokenInsertion} identifies\n     * single-token insertion as a viable recovery strategy for a mismatched\n     * input error.</p>\n     *\n     * <p>The default implementation simply returns if the handler is already in\n     * error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to\n     * enter error recovery mode, followed by calling\n     * {@link Parser//notifyErrorListeners}.</p>\n     *\n     * @param recognizer the parser instance\n     */\n    reportMissingToken(recognizer) {\n        if ( this.inErrorRecoveryMode(recognizer)) {\n            return;\n        }\n        this.beginErrorCondition(recognizer);\n        const t = recognizer.getCurrentToken()\n        const expecting = this.getExpectedTokens(recognizer)\n        const msg = \"missing \" + expecting.toString(recognizer.literalNames, recognizer.symbolicNames) +\n            \" at \" + this.getTokenErrorDisplay(t)\n        recognizer.notifyErrorListeners(msg, t, null);\n    }\n\n    /**\n     * <p>The default implementation attempts to recover from the mismatched input\n     * by using single token insertion and deletion as described below. If the\n     * recovery attempt fails, this method throws an\n     * {@link InputMismatchException}.</p>\n     *\n     * <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>\n     *\n     * <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the\n     * right token, however, then assume {@code LA(1)} is some extra spurious\n     * token and delete it. Then consume and return the next token (which was\n     * the {@code LA(2)} token) as the successful result of the match operation.</p>\n     *\n     * <p>This recovery strategy is implemented by {@link\n        * //singleTokenDeletion}.</p>\n     *\n     * <p><strong>MISSING TOKEN</strong> (single token insertion)</p>\n     *\n     * <p>If current token (at {@code LA(1)}) is consistent with what could come\n     * after the expected {@code LA(1)} token, then assume the token is missing\n     * and use the parser's {@link TokenFactory} to create it on the fly. The\n     * \"insertion\" is performed by returning the created token as the successful\n     * result of the match operation.</p>\n     *\n     * <p>This recovery strategy is implemented by {@link\n        * //singleTokenInsertion}.</p>\n     *\n     * <p><strong>EXAMPLE</strong></p>\n     *\n     * <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When\n     * the parser returns from the nested call to {@code expr}, it will have\n     * call chain:</p>\n     *\n     * <pre>\n     * stat &rarr; expr &rarr; atom\n     * </pre>\n     *\n     * and it will be trying to match the {@code ')'} at this point in the\n     * derivation:\n     *\n     * <pre>\n     * =&gt; ID '=' '(' INT ')' ('+' atom)* ';'\n     * ^\n     * </pre>\n     *\n     * The attempt to match {@code ')'} will fail when it sees {@code ';'} and\n     * call {@link //recoverInline}. To recover, it sees that {@code LA(1)==';'}\n     * is in the set of tokens that can follow the {@code ')'} token reference\n     * in rule {@code atom}. It can assume that you forgot the {@code ')'}.\n     */\n    recoverInline(recognizer) {\n        // SINGLE TOKEN DELETION\n        const matchedSymbol = this.singleTokenDeletion(recognizer)\n        if (matchedSymbol !== null) {\n            // we have deleted the extra token.\n            // now, move past ttype token as if all were ok\n            recognizer.consume();\n            return matchedSymbol;\n        }\n        // SINGLE TOKEN INSERTION\n        if (this.singleTokenInsertion(recognizer)) {\n            return this.getMissingSymbol(recognizer);\n        }\n        // even that didn't work; must throw the exception\n        throw new InputMismatchException(recognizer);\n    }\n\n    /**\n     * This method implements the single-token insertion inline error recovery\n     * strategy. It is called by {@link //recoverInline} if the single-token\n     * deletion strategy fails to recover from the mismatched input. If this\n     * method returns {@code true}, {@code recognizer} will be in error recovery\n     * mode.\n     *\n     * <p>This method determines whether or not single-token insertion is viable by\n     * checking if the {@code LA(1)} input symbol could be successfully matched\n     * if it were instead the {@code LA(2)} symbol. If this method returns\n     * {@code true}, the caller is responsible for creating and inserting a\n     * token with the correct type to produce this behavior.</p>\n     *\n     * @param recognizer the parser instance\n     * @return {@code true} if single-token insertion is a viable recovery\n     * strategy for the current mismatched input, otherwise {@code false}\n     */\n    singleTokenInsertion(recognizer) {\n        const currentSymbolType = recognizer.getTokenStream().LA(1)\n        // if current token is consistent with what could come after current\n        // ATN state, then we know we're missing a token; error recovery\n        // is free to conjure up and insert the missing token\n        const atn = recognizer._interp.atn\n        const currentState = atn.states[recognizer.state]\n        const next = currentState.transitions[0].target\n        const expectingAtLL2 = atn.nextTokens(next, recognizer._ctx)\n        if (expectingAtLL2.contains(currentSymbolType) ){\n            this.reportMissingToken(recognizer);\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * This method implements the single-token deletion inline error recovery\n     * strategy. It is called by {@link //recoverInline} to attempt to recover\n     * from mismatched input. If this method returns null, the parser and error\n     * handler state will not have changed. If this method returns non-null,\n     * {@code recognizer} will <em>not</em> be in error recovery mode since the\n     * returned token was a successful match.\n     *\n     * <p>If the single-token deletion is successful, this method calls\n     * {@link //reportUnwantedToken} to report the error, followed by\n     * {@link Parser//consume} to actually \"delete\" the extraneous token. Then,\n     * before returning {@link //reportMatch} is called to signal a successful\n     * match.</p>\n     *\n     * @param recognizer the parser instance\n     * @return the successfully matched {@link Token} instance if single-token\n     * deletion successfully recovers from the mismatched input, otherwise\n     * {@code null}\n     */\n    singleTokenDeletion(recognizer) {\n        const nextTokenType = recognizer.getTokenStream().LA(2)\n        const expecting = this.getExpectedTokens(recognizer)\n        if (expecting.contains(nextTokenType)) {\n            this.reportUnwantedToken(recognizer);\n            // print(\"recoverFromMismatchedToken deleting \" \\\n            // + str(recognizer.getTokenStream().LT(1)) \\\n            // + \" since \" + str(recognizer.getTokenStream().LT(2)) \\\n            // + \" is what we want\", file=sys.stderr)\n            recognizer.consume(); // simply delete extra token\n            // we want to return the token we're actually matching\n            const matchedSymbol = recognizer.getCurrentToken()\n            this.reportMatch(recognizer); // we know current token is correct\n            return matchedSymbol;\n        } else {\n            return null;\n        }\n    }\n\n    /**\n     * Conjure up a missing token during error recovery.\n     *\n     * The recognizer attempts to recover from single missing\n     * symbols. But, actions might refer to that missing symbol.\n     * For example, x=ID {f($x);}. The action clearly assumes\n     * that there has been an identifier matched previously and that\n     * $x points at that token. If that token is missing, but\n     * the next token in the stream is what we want we assume that\n     * this token is missing and we keep going. Because we\n     * have to return some token to replace the missing token,\n     * we have to conjure one up. This method gives the user control\n     * over the tokens returned for missing tokens. Mostly,\n     * you will want to create something special for identifier\n     * tokens. For literals such as '{' and ',', the default\n     * action in the parser or tree parser works. It simply creates\n     * a CommonToken of the appropriate type. The text will be the token.\n     * If you change what tokens must be created by the lexer,\n     * override this method to create the appropriate tokens.\n     *\n     */\n    getMissingSymbol(recognizer) {\n        const currentSymbol = recognizer.getCurrentToken()\n        const expecting = this.getExpectedTokens(recognizer)\n        const expectedTokenType = expecting.first() // get any element\n        let tokenText\n        if (expectedTokenType===Token.EOF) {\n            tokenText = \"<missing EOF>\";\n        } else {\n            tokenText = \"<missing \" + recognizer.literalNames[expectedTokenType] + \">\";\n        }\n        let current = currentSymbol\n        const lookback = recognizer.getTokenStream().LT(-1)\n        if (current.type===Token.EOF && lookback !== null) {\n            current = lookback;\n        }\n        return recognizer.getTokenFactory().create(current.source,\n            expectedTokenType, tokenText, Token.DEFAULT_CHANNEL,\n            -1, -1, current.line, current.column);\n    }\n\n    getExpectedTokens(recognizer) {\n        return recognizer.getExpectedTokens();\n    }\n\n    /**\n     * How should a token be displayed in an error message? The default\n     * is to display just the text, but during development you might\n     * want to have a lot of information spit out. Override in that case\n     * to use t.toString() (which, for CommonToken, dumps everything about\n     * the token). This is better than forcing you to override a method in\n     * your token objects because you don't have to go modify your lexer\n     * so that it creates a new Java type.\n     */\n    getTokenErrorDisplay(t) {\n        if (t === null) {\n            return \"<no token>\";\n        }\n        let s = t.text\n        if (s === null) {\n            if (t.type===Token.EOF) {\n                s = \"<EOF>\";\n            } else {\n                s = \"<\" + t.type + \">\";\n            }\n        }\n        return this.escapeWSAndQuote(s);\n    }\n\n    escapeWSAndQuote(s) {\n        s = s.replace(/\\n/g,\"\\\\n\");\n        s = s.replace(/\\r/g,\"\\\\r\");\n        s = s.replace(/\\t/g,\"\\\\t\");\n        return \"'\" + s + \"'\";\n    }\n\n    /**\n     * Compute the error recovery set for the current rule. During\n     * rule invocation, the parser pushes the set of tokens that can\n     * follow that rule reference on the stack; this amounts to\n     * computing FIRST of what follows the rule reference in the\n     * enclosing rule. See LinearApproximator.FIRST().\n     * This local follow set only includes tokens\n     * from within the rule; i.e., the FIRST computation done by\n     * ANTLR stops at the end of a rule.\n     *\n     * EXAMPLE\n     *\n     * When you find a \"no viable alt exception\", the input is not\n     * consistent with any of the alternatives for rule r. The best\n     * thing to do is to consume tokens until you see something that\n     * can legally follow a call to r//or* any rule that called r.\n     * You don't want the exact set of viable next tokens because the\n     * input might just be missing a token--you might consume the\n     * rest of the input looking for one of the missing tokens.\n     *\n     * Consider grammar:\n     *\n     * a : '[' b ']'\n     * | '(' b ')'\n     * ;\n     * b : c '^' INT ;\n     * c : ID\n     * | INT\n     * ;\n     *\n     * At each rule invocation, the set of tokens that could follow\n     * that rule is pushed on a stack. Here are the various\n     * context-sensitive follow sets:\n     *\n     * FOLLOW(b1_in_a) = FIRST(']') = ']'\n     * FOLLOW(b2_in_a) = FIRST(')') = ')'\n     * FOLLOW(c_in_b) = FIRST('^') = '^'\n     *\n     * Upon erroneous input \"[]\", the call chain is\n     *\n     * a -> b -> c\n     *\n     * and, hence, the follow context stack is:\n     *\n     * depth follow set start of rule execution\n     * 0 <EOF> a (from main())\n     * 1 ']' b\n     * 2 '^' c\n     *\n     * Notice that ')' is not included, because b would have to have\n     * been called from a different context in rule a for ')' to be\n     * included.\n     *\n     * For error recovery, we cannot consider FOLLOW(c)\n     * (context-sensitive or otherwise). We need the combined set of\n     * all context-sensitive FOLLOW sets--the set of all tokens that\n     * could follow any reference in the call chain. We need to\n     * resync to one of those tokens. Note that FOLLOW(c)='^' and if\n     * we resync'd to that token, we'd consume until EOF. We need to\n     * sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.\n     * In this case, for input \"[]\", LA(1) is ']' and in the set, so we would\n     * not consume anything. After printing an error, rule c would\n     * return normally. Rule b would not find the required '^' though.\n     * At this point, it gets a mismatched token error and throws an\n     * exception (since LA(1) is not in the viable following token\n     * set). The rule exception handler tries to recover, but finds\n     * the same recovery set and doesn't consume anything. Rule b\n     * exits normally returning to rule a. Now it finds the ']' (and\n     * with the successful match exits errorRecovery mode).\n     *\n     * So, you can see that the parser walks up the call chain looking\n     * for the token that was a member of the recovery set.\n     *\n     * Errors are not generated in errorRecovery mode.\n     *\n     * ANTLR's error recovery mechanism is based upon original ideas:\n     *\n     * \"Algorithms + Data Structures = Programs\" by Niklaus Wirth\n     *\n     * and\n     *\n     * \"A note on error recovery in recursive descent parsers\":\n     * http://portal.acm.org/citation.cfm?id=947902.947905\n     *\n     * Later, Josef Grosch had some good ideas:\n     *\n     * \"Efficient and Comfortable Error Recovery in Recursive Descent\n     * Parsers\":\n     * ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip\n     *\n     * Like Grosch I implement context-sensitive FOLLOW sets that are combined\n     * at run-time upon error to avoid overhead during parsing.\n     */\n    getErrorRecoverySet(recognizer) {\n        const atn = recognizer._interp.atn\n        let ctx = recognizer._ctx\n        const recoverSet = new IntervalSet()\n        while (ctx !== null && ctx.invokingState>=0) {\n            // compute what follows who invoked us\n            const invokingState = atn.states[ctx.invokingState]\n            const rt = invokingState.transitions[0]\n            const follow = atn.nextTokens(rt.followState)\n            recoverSet.addSet(follow);\n            ctx = ctx.parentCtx;\n        }\n        recoverSet.removeOne(Token.EPSILON);\n        return recoverSet;\n    }\n\n// Consume tokens until one matches the given token set.//\n    consumeUntil(recognizer, set) {\n        let ttype = recognizer.getTokenStream().LA(1)\n        while( ttype !== Token.EOF && !set.contains(ttype)) {\n            recognizer.consume();\n            ttype = recognizer.getTokenStream().LA(1);\n        }\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/DiagnosticErrorListener.d.ts",
    "content": "import {ErrorListener} from \"./ErrorListener.js\";\n\nexport declare class DiagnosticErrorListener<TSymbol> extends ErrorListener<TSymbol> {}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/DiagnosticErrorListener.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport ErrorListener from './ErrorListener.js';\nimport Interval from '../misc/Interval.js';\nimport BitSet from \"../misc/BitSet.js\";\n\n\n/**\n * This implementation of {@link ANTLRErrorListener} can be used to identify\n *  certain potential correctness and performance problems in grammars. \"Reports\"\n *  are made by calling {@link Parser//notifyErrorListeners} with the appropriate\n *  message.\n *\n *  <ul>\n *  <li><b>Ambiguities</b>: These are cases where more than one path through the\n *  grammar can match the input.</li>\n *  <li><b>Weak context sensitivity</b>: These are cases where full-context\n *  prediction resolved an SLL conflict to a unique alternative which equaled the\n *  minimum alternative of the SLL conflict.</li>\n *  <li><b>Strong (forced) context sensitivity</b>: These are cases where the\n *  full-context prediction resolved an SLL conflict to a unique alternative,\n *  <em>and</em> the minimum alternative of the SLL conflict was found to not be\n *  a truly viable alternative. Two-stage parsing cannot be used for inputs where\n *  this situation occurs.</li>\n *  </ul>\n */\nexport default class DiagnosticErrorListener extends ErrorListener {\n\tconstructor(exactOnly) {\n\t\tsuper();\n\t\texactOnly = exactOnly || true;\n\t\t// whether all ambiguities or only exact ambiguities are reported.\n\t\tthis.exactOnly = exactOnly;\n\t}\n\n\treportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {\n\t\tif (this.exactOnly && !exact) {\n\t\t\treturn;\n\t\t}\n\t\tconst msg = \"reportAmbiguity d=\" +\n\t\t\tthis.getDecisionDescription(recognizer, dfa) +\n\t\t\t\": ambigAlts=\" +\n\t\t\tthis.getConflictingAlts(ambigAlts, configs) +\n\t\t\t\", input='\" +\n\t\t\trecognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + \"'\"\n\t\trecognizer.notifyErrorListeners(msg);\n\t}\n\n\treportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {\n\t\tconst msg = \"reportAttemptingFullContext d=\" +\n\t\t\tthis.getDecisionDescription(recognizer, dfa) +\n\t\t\t\", input='\" +\n\t\t\trecognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + \"'\"\n\t\trecognizer.notifyErrorListeners(msg);\n\t}\n\n\treportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) {\n\t\tconst msg = \"reportContextSensitivity d=\" +\n\t\t\tthis.getDecisionDescription(recognizer, dfa) +\n\t\t\t\", input='\" +\n\t\t\trecognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + \"'\"\n\t\trecognizer.notifyErrorListeners(msg);\n\t}\n\n\tgetDecisionDescription(recognizer, dfa) {\n\t\tconst decision = dfa.decision\n\t\tconst ruleIndex = dfa.atnStartState.ruleIndex\n\n\t\tconst ruleNames = recognizer.ruleNames\n\t\tif (ruleIndex < 0 || ruleIndex >= ruleNames.length) {\n\t\t\treturn \"\" + decision;\n\t\t}\n\t\tconst ruleName = ruleNames[ruleIndex] || null\n\t\tif (ruleName === null || ruleName.length === 0) {\n\t\t\treturn \"\" + decision;\n\t\t}\n\t\treturn `${decision} (${ruleName})`;\n\t}\n\n\t/**\n\t * Computes the set of conflicting or ambiguous alternatives from a\n\t * configuration set, if that information was not already provided by the\n\t * parser.\n\t *\n\t * @param reportedAlts The set of conflicting or ambiguous alternatives, as\n\t * reported by the parser.\n\t * @param configs The conflicting or ambiguous configuration set.\n\t * @return Returns {@code reportedAlts} if it is not {@code null}, otherwise\n\t * returns the set of alternatives represented in {@code configs}.\n     */\n\tgetConflictingAlts(reportedAlts, configs) {\n\t\tif (reportedAlts !== null) {\n\t\t\treturn reportedAlts;\n\t\t}\n\t\tconst result = new BitSet()\n\t\tfor (let i = 0; i < configs.items.length; i++) {\n\t\t\tresult.set(configs.items[i].alt);\n\t\t}\n\t\treturn `{${result.values().join(\", \")}}`;\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/ErrorListener.d.ts",
    "content": "import { ATNConfigSet } from \"../atn/index.js\";\nimport { BitSet } from \"../misc/BitSet.js\";\nimport { DFA } from \"../dfa/index.js\";\nimport { Recognizer } from \"../Recognizer.js\";\nimport { RecognitionException } from \"./RecognitionException.js\";\n\nexport declare class ErrorListener<TSymbol> {\n    reportAmbiguity(recognizer: Recognizer<TSymbol>, dfa: DFA, startIndex: number, stopIndex: number, exact: boolean, ambigAlts: BitSet, configs: ATNConfigSet): void;\n    \n    reportAttemptingFullContext(recognizer: Recognizer<TSymbol>, dfa: DFA, startIndex: number, stopIndex: number, conflictingAlts: BitSet, configs: ATNConfigSet): void;\n    \n    reportContextSensitivity(recognizer: Recognizer<TSymbol>, dfa: DFA, startIndex: number, stopIndex: number, prediction: number, configs: ATNConfigSet): void;\n    \n    syntaxError(recognizer: Recognizer<TSymbol>, offendingSymbol: TSymbol, line: number, column: number, msg: string, e: RecognitionException | undefined): void;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/ErrorListener.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/**\n * Provides an empty default implementation of {@link ANTLRErrorListener}. The\n * default implementation of each method does nothing, but can be overridden as\n * necessary.\n */\nexport default class ErrorListener {\n    syntaxError(recognizer, offendingSymbol, line, column, msg, e) {\n    }\n\n    reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {\n    }\n\n    reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {\n    }\n\n    reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) {\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/ErrorStrategy.d.ts",
    "content": "import {RecognitionException} from \"./RecognitionException.js\";\nimport {Parser} from \"../Parser.js\";\nimport {Token} from \"../Token.js\";\n\nexport declare class ErrorStrategy {\n    reset(recognizer: Parser): void;\n    sync(recognizer: Parser): void;\n    recover(recognizer: Parser, e: RecognitionException): void;\n    recoverInline(recognizer: Parser): Token;\n    reportMatch(recognizer: Parser): void;\n    reportError(recognizer: Parser, e: RecognitionException): void;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/ErrorStrategy.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport default class ErrorStrategy {\n\n    reset(recognizer) {\n    }\n\n    recoverInline(recognizer) {\n    }\n\n    recover(recognizer, e) {\n    }\n\n    sync(recognizer) {\n    }\n\n    inErrorRecoveryMode(recognizer) {\n    }\n\n    reportError(recognizer) {\n    }\n}\n\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/FailedPredicateException.d.ts",
    "content": "import {RecognitionException} from \"./RecognitionException.js\";\nimport {Parser} from \"../Parser.js\";\n\nexport declare class FailedPredicateException extends RecognitionException {\n\n    constructor(recognizer: Parser, predicate: string | undefined, message: string | undefined);\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/FailedPredicateException.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport PredicateTransition from \"../transition/PredicateTransition.js\";\nimport RecognitionException from \"./RecognitionException.js\";\n\n/**\n * A semantic predicate failed during validation. Validation of predicates\n * occurs when normally parsing the alternative just like matching a token.\n * Disambiguating predicate evaluation occurs when we test a predicate during\n * prediction.\n */\nexport default class FailedPredicateException extends RecognitionException {\n\n    constructor(recognizer, predicate, message) {\n        super({\n            message: formatMessage(predicate, message || null),\n            recognizer: recognizer,\n            input: recognizer.getInputStream(), ctx: recognizer._ctx\n        });\n        const s = recognizer._interp.atn.states[recognizer.state]\n        const trans = s.transitions[0]\n        if (trans instanceof PredicateTransition) {\n            this.ruleIndex = trans.ruleIndex;\n            this.predicateIndex = trans.predIndex;\n        } else {\n            this.ruleIndex = 0;\n            this.predicateIndex = 0;\n        }\n        this.predicate = predicate;\n        this.offendingToken = recognizer.getCurrentToken();\n    }\n}\n\n\nfunction formatMessage(predicate, message) {\n    if (message !==null) {\n        return message;\n    } else {\n        return \"failed predicate: {\" + predicate + \"}?\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/InputMismatchException.d.ts",
    "content": "import {RecognitionException} from \"./RecognitionException.js\";\nimport {Parser} from \"../Parser.js\";\n\nexport declare class InputMismatchException extends RecognitionException {\n    constructor(recognizer: Parser);\n}"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/InputMismatchException.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport RecognitionException from \"./RecognitionException.js\";\n\n/**\n * This signifies any kind of mismatched input exceptions such as\n * when the current input does not match the expected token.\n */\nexport default class InputMismatchException extends RecognitionException {\n    constructor(recognizer) {\n        super({message: \"\", recognizer: recognizer, input: recognizer.getInputStream(), ctx: recognizer._ctx});\n        this.offendingToken = recognizer.getCurrentToken();\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/LexerNoViableAltException.d.ts",
    "content": "import {ATNConfigSet} from \"../atn/index.js\";\nimport {Recognizer} from \"../Recognizer.js\";\nimport { Token } from \"../Token.js\";\nimport {RecognitionException} from \"./RecognitionException.js\";\n\nexport declare class LexerNoViableAltException extends RecognitionException {\n\n    deadEndConfigs: ATNConfigSet;\n\n    constructor(recognizer: Recognizer<any>);\n\n    startIndex: number;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/LexerNoViableAltException.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Interval from \"../misc/Interval.js\";\nimport RecognitionException from \"./RecognitionException.js\";\n\nexport default class LexerNoViableAltException extends RecognitionException {\n    constructor(lexer, input, startIndex, deadEndConfigs) {\n        super({message: \"\", recognizer: lexer, input: input, ctx: null});\n        this.startIndex = startIndex;\n        this.deadEndConfigs = deadEndConfigs;\n    }\n\n    toString() {\n        let symbol = \"\";\n        if (this.startIndex >= 0 && this.startIndex < this.input.size) {\n            symbol = this.input.getText(new Interval(this.startIndex,this.startIndex));\n        }\n        return \"LexerNoViableAltException\" + symbol;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/NoViableAltException.d.ts",
    "content": "import {ATNConfigSet} from \"../atn/index.js\";\nimport {Recognizer} from \"../Recognizer.js\";\nimport { Token } from \"../Token.js\";\nimport {RecognitionException} from \"./RecognitionException.js\";\n\nexport declare class NoViableAltException extends RecognitionException {\n\n    deadEndConfigs: ATNConfigSet;\n\n    constructor(recognizer: Recognizer<any>);\n\n    startToken: Token;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/NoViableAltException.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport RecognitionException from \"./RecognitionException.js\";\n\n/**\n * Indicates that the parser could not decide which of two or more paths\n * to take based upon the remaining input. It tracks the starting token\n * of the offending input and also knows where the parser was\n * in the various paths when the error. Reported by reportNoViableAlternative()\n */\n\nexport default class NoViableAltException extends RecognitionException {\n    constructor(recognizer, input, startToken, offendingToken, deadEndConfigs, ctx) {\n        ctx = ctx || recognizer._ctx;\n        offendingToken = offendingToken || recognizer.getCurrentToken();\n        startToken = startToken || recognizer.getCurrentToken();\n        input = input || recognizer.getInputStream();\n        super({message: \"\", recognizer: recognizer, input: input, ctx: ctx});\n        // Which configurations did we try at input.index() that couldn't match\n        // input.LT(1)?//\n        this.deadEndConfigs = deadEndConfigs;\n        // The token object at the start index; the input stream might\n        // not be buffering tokens so get a reference to it. (At the\n        // time the error occurred, of course the stream needs to keep a\n        // buffer all of the tokens but later we might not have access to those.)\n        this.startToken = startToken;\n        this.offendingToken = offendingToken;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/ParseCancellationException.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default class ParseCancellationException extends Error {\n    constructor() {\n        super()\n        Error.captureStackTrace(this, ParseCancellationException);\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/ProxyErrorListener.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ErrorListener from \"./ErrorListener.js\";\n\nexport default class ProxyErrorListener extends ErrorListener {\n    constructor(delegates) {\n        super();\n        if (delegates===null) {\n            throw \"delegates\";\n        }\n        this.delegates = delegates;\n        return this;\n    }\n\n    syntaxError(recognizer, offendingSymbol, line, column, msg, e) {\n        this.delegates.map(d => d.syntaxError(recognizer, offendingSymbol, line, column, msg, e));\n    }\n\n    reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {\n        this.delegates.map(d => d.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs));\n    }\n\n    reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {\n        this.delegates.map(d => d.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs));\n    }\n\n    reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) {\n        this.delegates.map(d => d.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs));\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/RecognitionException.d.ts",
    "content": "import {ParserRuleContext, RuleContext} from \"../context/index.js\";\nimport {TokenStream} from \"../TokenStream.js\";\nimport {Recognizer} from \"../Recognizer.js\";\nimport {CharStream} from \"../CharStream.js\";\nimport {Token} from \"../Token.js\";\n\nexport interface ExceptionParams {\n    message: string;\n    recognizer?: Recognizer<never>;\n    input?: CharStream | TokenStream;\n    ctx?: ParserRuleContext;\n\n}\n\nexport declare class RecognitionException extends Error {\n    ctx: RuleContext;\n    offendingToken: Token | null;\n    constructor(params: ExceptionParams);\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/RecognitionException.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/**\n * The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n *  3 kinds of errors: prediction errors, failed predicate errors, and\n *  mismatched input errors. In each case, the parser knows where it is\n *  in the input, where it is in the ATN, the rule invocation stack,\n *  and what kind of problem occurred.\n */\n\nexport default class RecognitionException extends Error {\n\n    constructor(params) {\n        super(params.message);\n        if (Error.captureStackTrace)\n            Error.captureStackTrace(this, RecognitionException);\n        this.message = params.message;\n        this.recognizer = params.recognizer;\n        this.input = params.input;\n        this.ctx = params.ctx;\n        /**\n         * The current {@link Token} when an error occurred. Since not all streams\n         * support accessing symbols by index, we have to track the {@link Token}\n         * instance itself\n        */\n        this.offendingToken = null;\n        /**\n         * Get the ATN state number the parser was in at the time the error\n         * occurred. For {@link NoViableAltException} and\n         * {@link LexerNoViableAltException} exceptions, this is the\n         * {@link DecisionState} number. For others, it is the state whose outgoing\n         * edge we couldn't match.\n         */\n        this.offendingState = -1;\n        if (this.recognizer!==null) {\n            this.offendingState = this.recognizer.state;\n        }\n    }\n\n    /**\n     * Gets the set of input symbols which could potentially follow the\n     * previously matched symbol at the time this exception was thrown.\n     *\n     * <p>If the set of expected tokens is not known and could not be computed,\n     * this method returns {@code null}.</p>\n     *\n     * @return The set of token types that could potentially follow the current\n     * state in the ATN, or {@code null} if the information is not available.\n     */\n    getExpectedTokens() {\n        if (this.recognizer!==null) {\n            return this.recognizer.atn.getExpectedTokens(this.offendingState, this.ctx);\n        } else {\n            return null;\n        }\n    }\n\n    // <p>If the state number is not known, this method returns -1.</p>\n    toString() {\n        return this.message;\n    }\n}\n\n\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/index.d.ts",
    "content": "export * from \"./RecognitionException.js\";\nexport * from \"./LexerNoViableAltException.js\";\nexport * from \"./NoViableAltException.js\";\nexport * from \"./FailedPredicateException.js\";\nexport * from \"./InputMismatchException.js\";\nexport * from \"./ErrorStrategy.js\";\nexport * from \"./BailErrorStrategy.js\";\nexport * from \"./DefaultErrorStrategy.js\";\nexport * from \"./ErrorListener.js\";\nexport * from \"./DiagnosticErrorListener.js\";\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/error/index.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport RecognitionException from './RecognitionException.js';\nimport NoViableAltException from './NoViableAltException.js';\nimport LexerNoViableAltException from './LexerNoViableAltException.js';\nimport InputMismatchException from './InputMismatchException.js';\nimport FailedPredicateException from './FailedPredicateException.js';\nimport DiagnosticErrorListener from './DiagnosticErrorListener.js';\nimport BailErrorStrategy from './BailErrorStrategy.js';\nimport DefaultErrorStrategy from './DefaultErrorStrategy.js';\nimport ErrorListener from './ErrorListener.js';\n\nexport default {\n    RecognitionException, NoViableAltException, LexerNoViableAltException, InputMismatchException, FailedPredicateException,\n    DiagnosticErrorListener, BailErrorStrategy, DefaultErrorStrategy, ErrorListener\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/index.d.cts",
    "content": "export * from \"./InputStream\";\nexport * from \"./FileStream\";\nexport * from \"./CharStream\";\nexport * from \"./CharStreams\";\nexport * from \"./TokenStream\";\nexport * from \"./BufferedTokenStream\";\nexport * from \"./CommonToken\";\nexport * from \"./CommonTokenStream\";\nexport * from \"./Recognizer\";\nexport * from \"./Lexer\";\nexport * from \"./Parser\";\nexport * from \"./Token\";\nexport * from \"./atn\";\nexport * from \"./dfa\";\nexport * from \"./context\";\nexport * from \"./misc\";\nexport * from \"./tree\";\nexport * from \"./state\";\nexport * from \"./error\";\nexport * from \"./utils\";\nexport * from \"./TokenStreamRewriter\";\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/index.node.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport { default as atn } from './atn/index.js';\nimport { default as dfa } from './dfa/index.js';\nimport { default as context } from './context/index.js';\nimport { default as misc } from './misc/index.js';\nimport { default as tree } from './tree/index.js';\nimport { default as error } from './error/index.js';\nimport { default as CharStreams } from './CharStreams.js';\nimport { default as Utils } from './utils/index.js';\n\nimport Token from './Token.js';\nimport CommonToken from './CommonToken.js';\nimport InputStream from './InputStream.js';\nimport CharStream from './CharStream.js';\nimport FileStream from './FileStream.js';\nimport CommonTokenStream from './CommonTokenStream.js';\nimport Lexer from './Lexer.js';\nimport Parser from './Parser.js';\n\nimport RuleContext from './context/RuleContext.js';\nimport ParserRuleContext from './context/ParserRuleContext.js';\nimport ATN from './atn/ATN.js';\nimport PredictionMode from './atn/PredictionMode.js';\nimport LL1Analyzer from './atn/LL1Analyzer.js';\nimport ATNDeserializer from './atn/ATNDeserializer.js';\nimport LexerATNSimulator from './atn/LexerATNSimulator.js';\nimport ParserATNSimulator from './atn/ParserATNSimulator.js';\nimport PredictionContextCache from './atn/PredictionContextCache.js';\nimport DFA from \"./dfa/DFA.js\";\nimport RecognitionException from \"./error/RecognitionException.js\";\nimport FailedPredicateException from \"./error/FailedPredicateException.js\";\nimport NoViableAltException from \"./error/NoViableAltException.js\";\nimport BailErrorStrategy from \"./error/BailErrorStrategy.js\";\nimport DefaultErrorStrategy from \"./error/DefaultErrorStrategy.js\";\nimport Interval from './misc/Interval.js';\nimport IntervalSet from './misc/IntervalSet.js';\nimport ParseTreeListener from \"./tree/ParseTreeListener.js\";\nimport ParseTreeVisitor from \"./tree/ParseTreeVisitor.js\";\nimport ParseTreeWalker from \"./tree/ParseTreeWalker.js\";\nimport ErrorListener from \"./error/ErrorListener.js\"\nimport DiagnosticErrorListener from \"./error/DiagnosticErrorListener.js\"\nimport RuleNode from \"./tree/RuleNode.js\"\nimport TerminalNode from \"./tree/TerminalNode.js\"\nimport arrayToString from \"./utils/arrayToString.js\"\nimport TokenStreamRewriter from './TokenStreamRewriter.js';\nimport InputMismatchException from \"./error/InputMismatchException.js\"\n\nexport default {\n    atn, dfa, context, misc, tree, error, Token, CommonToken, CharStreams, CharStream, InputStream, FileStream, CommonTokenStream, Lexer, Parser,\n    ParserRuleContext, Interval, IntervalSet, LL1Analyzer, Utils, TokenStreamRewriter\n}\n\nexport {\n    Token, CommonToken, CharStreams, CharStream, InputStream, FileStream, CommonTokenStream, Lexer, Parser,\n    RuleNode, TerminalNode, ParseTreeWalker, RuleContext, ParserRuleContext, Interval, IntervalSet,\n    PredictionMode, LL1Analyzer, ParseTreeListener, ParseTreeVisitor, ATN, ATNDeserializer, PredictionContextCache, LexerATNSimulator, ParserATNSimulator, DFA,\n    RecognitionException, NoViableAltException, FailedPredicateException, ErrorListener, DiagnosticErrorListener, BailErrorStrategy, DefaultErrorStrategy,\n    arrayToString, TokenStreamRewriter, InputMismatchException\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/index.web.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport { default as atn } from './atn/index.js';\nimport { default as dfa } from './dfa/index.js';\nimport { default as context } from './context/index.js';\nimport { default as misc } from './misc/index.js';\nimport { default as tree } from './tree/index.js';\nimport { default as error } from './error/index.js';\nimport { default as CharStreams } from './CharStreams.js';\nimport { default as Utils } from './utils/index.js';\n\nimport Token from './Token.js';\nimport CommonToken from './CommonToken.js';\nimport InputStream from './InputStream.js';\nimport CharStream from './CharStream.js';\nimport CommonTokenStream from './CommonTokenStream.js';\nimport Lexer from './Lexer.js';\nimport Parser from './Parser.js';\n\nimport RuleContext from './context/RuleContext.js';\nimport ParserRuleContext from './context/ParserRuleContext.js';\nimport ATN from './atn/ATN.js';\nimport PredictionMode from './atn/PredictionMode.js';\nimport LL1Analyzer from './atn/LL1Analyzer.js';\nimport ATNDeserializer from './atn/ATNDeserializer.js';\nimport LexerATNSimulator from './atn/LexerATNSimulator.js';\nimport ParserATNSimulator from './atn/ParserATNSimulator.js';\nimport PredictionContextCache from './atn/PredictionContextCache.js';\nimport DFA from \"./dfa/DFA.js\";\nimport RecognitionException from \"./error/RecognitionException.js\";\nimport FailedPredicateException from \"./error/FailedPredicateException.js\";\nimport NoViableAltException from \"./error/NoViableAltException.js\";\nimport BailErrorStrategy from \"./error/BailErrorStrategy.js\";\nimport DefaultErrorStrategy from \"./error/DefaultErrorStrategy.js\";\nimport Interval from './misc/Interval.js';\nimport IntervalSet from './misc/IntervalSet.js';\nimport ParseTreeListener from \"./tree/ParseTreeListener.js\";\nimport ParseTreeVisitor from \"./tree/ParseTreeVisitor.js\";\nimport ParseTreeWalker from \"./tree/ParseTreeWalker.js\";\nimport ErrorListener from \"./error/ErrorListener.js\"\nimport DiagnosticErrorListener from \"./error/DiagnosticErrorListener.js\"\nimport RuleNode from \"./tree/RuleNode.js\"\nimport TerminalNode from \"./tree/TerminalNode.js\"\nimport arrayToString from \"./utils/arrayToString.js\"\nimport TokenStreamRewriter from './TokenStreamRewriter.js';\nimport InputMismatchException from \"./error/InputMismatchException.js\"\n\nexport default {\n    atn, dfa, context, misc, tree, error, Token, CommonToken, CharStreams, CharStream, InputStream, CommonTokenStream, Lexer, Parser,\n    ParserRuleContext, Interval, IntervalSet, LL1Analyzer, Utils, TokenStreamRewriter\n}\n\nexport {\n    Token, CommonToken, CharStreams, CharStream, InputStream, CommonTokenStream, Lexer, Parser,\n    RuleNode, TerminalNode, ParseTreeWalker, RuleContext, ParserRuleContext, Interval, IntervalSet,\n    PredictionMode, LL1Analyzer, ParseTreeListener, ParseTreeVisitor, ATN, ATNDeserializer, PredictionContextCache, LexerATNSimulator, ParserATNSimulator, DFA,\n    RecognitionException, NoViableAltException, FailedPredicateException, ErrorListener, DiagnosticErrorListener, BailErrorStrategy, DefaultErrorStrategy,\n    arrayToString, TokenStreamRewriter, InputMismatchException\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/AltDict.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default class AltDict {\n\n    constructor() {\n        this.data = {};\n    }\n\n    get(key) {\n        return this.data[\"k-\" + key] || null;\n    }\n\n    set(key, value) {\n        this.data[\"k-\" + key] = value;\n    }\n\n    values() {\n        return Object.keys(this.data).filter(key => key.startsWith(\"k-\")).map(key => this.data[key], this);\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/BitSet.d.ts",
    "content": "export declare class BitSet {\n    // write methods are not exposed based on this conversation https://github.com/antlr/antlr4/pull/4731#discussion_r1847139040\n    readonly length: number;\n\n    get(index: number): number;\n\n    values(): Array<number>;\n\n    minValue(): number;\n\n    hashCode(): number;\n\n    equals(): boolean;\n\n    toString(): string;\n\n    static _bitCount(l: number): number; \n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/BitSet.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport HashCode from \"./HashCode.js\";\nimport equalArrays from \"../utils/equalArrays.js\";\n\nexport default class BitSet {\n\n    constructor() {\n        this.data = new Uint32Array(1);\n    }\n\n    set(index) {\n        BitSet._checkIndex(index)\n        this._resize(index);\n        this.data[index >>> 5] |= 1 << index % 32;\n    }\n\n    get(index) {\n        BitSet._checkIndex(index)\n        const slot = index >>> 5;\n        if (slot >= this.data.length) {\n            return false;\n        }\n        return (this.data[slot] & 1 << index % 32) !== 0;\n    }\n\n    clear(index) {\n        BitSet._checkIndex(index)\n        const slot = index >>> 5;\n        if (slot < this.data.length) {\n            this.data[slot] &= ~(1 << index);\n        }\n    }\n\n    or(set) {\n        const minCount = Math.min(this.data.length, set.data.length);\n        for (let k = 0; k < minCount; ++k) {\n            this.data[k] |= set.data[k];\n        }\n        if (this.data.length < set.data.length) {\n            this._resize((set.data.length << 5) - 1);\n            const c = set.data.length;\n            for (let k = minCount; k < c; ++k) {\n                this.data[k] = set.data[k];\n            }\n        }\n    }\n\n    values() {\n        const result = new Array(this.length);\n        let pos = 0;\n        const length = this.data.length;\n        for (let k = 0; k < length; ++k) {\n            let l = this.data[k];\n            while (l !== 0) {\n                const t = l & -l;\n                result[pos++] = (k << 5) + BitSet._bitCount(t - 1);\n                l ^= t;\n            }\n        }\n        return result;\n    }\n\n    minValue() {\n        for (let k = 0; k < this.data.length; ++k) {\n            let l = this.data[k];\n            if (l !== 0) {\n                let result = 0;\n                while ((l & 1) === 0) {\n                    result++;\n                    l >>= 1;\n                }\n                return result + (32 * k);\n            }\n        }\n        return 0;\n    }\n\n    hashCode() {\n        return HashCode.hashStuff(this.values());\n    }\n\n    equals(other) {\n        return other instanceof BitSet && equalArrays(this.data, other.data);\n    }\n\n    toString() {\n        return \"{\" + this.values().join(\", \") + \"}\";\n    }\n\n    get length() {\n        return this.data.map(l => BitSet._bitCount(l)).reduce((s, v) => s + v, 0);\n    }\n\n    _resize(index) {\n        const count = index + 32 >>> 5;\n        if (count <= this.data.length) {\n            return;\n        }\n        const data = new Uint32Array(count);\n        data.set(this.data);\n        data.fill(0, this.data.length);\n        this.data = data;\n    }\n\n    static _checkIndex(index) {\n        if (index < 0)\n            throw new RangeError(\"index cannot be negative\");\n    }\n\n    static _bitCount(l) {\n        // see https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel\n        let count = 0;\n        l = l - ((l >> 1) & 0x55555555);\n        l = (l & 0x33333333) + ((l >> 2) & 0x33333333);\n        l = (l + (l >> 4)) & 0x0f0f0f0f;\n        l = l + (l >> 8);\n        l = l + (l >> 16);\n        return count + l & 0x3f;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/HashCode.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport { stringHashCode } from \"../utils/stringHashCode.js\";\n\nexport default class HashCode {\n\n    constructor() {\n        this.count = 0;\n        this.hash = 0;\n    }\n\n    update() {\n        for(let i=0;i<arguments.length;i++) {\n            const value = arguments[i];\n            if (value == null)\n                continue;\n            if(Array.isArray(value))\n                this.update.apply(this, value);\n            else {\n                let k = 0;\n                switch (typeof(value)) {\n                    case 'undefined':\n                    case 'function':\n                        continue;\n                    case 'number':\n                    case 'boolean':\n                        k = value;\n                        break;\n                    case 'string':\n                        k = stringHashCode(value);\n                        break;\n                    default:\n                        if(value.updateHashCode)\n                            value.updateHashCode(this);\n                        else\n                            console.log(\"No updateHashCode for \" + value.toString())\n                        continue;\n                }\n                k = k * 0xCC9E2D51;\n                k = (k << 15) | (k >>> (32 - 15));\n                k = k * 0x1B873593;\n                this.count = this.count + 1;\n                let hash = this.hash ^ k;\n                hash = (hash << 13) | (hash >>> (32 - 13));\n                hash = hash * 5 + 0xE6546B64;\n                this.hash = hash;\n            }\n        }\n    }\n\n    finish() {\n        let hash = this.hash ^ (this.count * 4);\n        hash = hash ^ (hash >>> 16);\n        hash = hash * 0x85EBCA6B;\n        hash = hash ^ (hash >>> 13);\n        hash = hash * 0xC2B2AE35;\n        hash = hash ^ (hash >>> 16);\n        return hash;\n    }\n\n    static hashStuff() {\n        const hash = new HashCode();\n        hash.update.apply(hash, arguments);\n        return hash.finish();\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/HashMap.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport standardEqualsFunction from \"../utils/standardEqualsFunction.js\";\nimport standardHashCodeFunction from \"../utils/standardHashCodeFunction.js\";\n\nconst DEFAULT_LOAD_FACTOR = 0.75;\nconst INITIAL_CAPACITY = 16\n\nexport default class HashMap {\n\n    constructor(hashFunction, equalsFunction) {\n        this.buckets = new Array(INITIAL_CAPACITY);\n        this.threshold = Math.floor(INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);\n        this.itemCount = 0;\n        this.hashFunction = hashFunction || standardHashCodeFunction;\n        this.equalsFunction = equalsFunction || standardEqualsFunction;\n    }\n\n    set(key, value) {\n        this._expand();\n        const slot = this._getSlot(key);\n        let bucket = this.buckets[slot];\n        if (!bucket) {\n            bucket = [[key, value]];\n            this.buckets[slot] = bucket;\n            this.itemCount++;\n            return value;\n        }\n        const existing = bucket.find(pair => this.equalsFunction(pair[0], key), this);\n        if(existing) {\n            const result = existing[1];\n            existing[1] = value;\n            return result;\n        } else {\n            bucket.push([key, value]);\n            this.itemCount++;\n            return value;\n        }\n    }\n\n    containsKey(key) {\n        const bucket = this._getBucket(key);\n        if(!bucket) {\n            return false;\n        }\n        const existing = bucket.find(pair => this.equalsFunction(pair[0], key), this);\n        return !!existing;\n    }\n\n    get(key) {\n        const bucket = this._getBucket(key);\n        if(!bucket) {\n            return null;\n        }\n        const existing = bucket.find(pair => this.equalsFunction(pair[0], key), this);\n        return existing ? existing[1] : null;\n    }\n\n    entries() {\n        return this.buckets.filter(b => b != null).flat(1);\n    }\n\n    getKeys() {\n        return this.entries().map(pair => pair[0]);\n    }\n\n    getValues() {\n        return this.entries().map(pair => pair[1]);\n    }\n\n    toString() {\n        const ss = this.entries().map(e => '{' + e[0] + ':' + e[1] + '}');\n        return '[' + ss.join(\", \") + ']';\n    }\n\n    get length() {\n        return this.itemCount;\n    }\n\n    _getSlot(key) {\n        const hash = this.hashFunction(key);\n        return hash & this.buckets.length - 1;\n    }\n    _getBucket(key) {\n        return this.buckets[this._getSlot(key)];\n    }\n\n    _expand() {\n        if (this.itemCount <= this.threshold) {\n            return;\n        }\n        const old_buckets = this.buckets;\n        const newCapacity = this.buckets.length * 2;\n        this.buckets = new Array(newCapacity);\n        this.threshold = Math.floor(newCapacity * DEFAULT_LOAD_FACTOR);\n        for (const bucket of old_buckets) {\n            if (!bucket) {\n                continue;\n            }\n            for (const pair of bucket) {\n                const slot = this._getSlot(pair[0]);\n                let newBucket = this.buckets[slot];\n                if (!newBucket) {\n                    newBucket = [];\n                    this.buckets[slot] = newBucket;\n                }\n                newBucket.push(pair);\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/HashSet.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport standardHashCodeFunction from \"../utils/standardHashCodeFunction.js\";\nimport standardEqualsFunction from \"../utils/standardEqualsFunction.js\";\nimport arrayToString from \"../utils/arrayToString.js\";\n\nconst DEFAULT_LOAD_FACTOR = 0.75;\nconst INITIAL_CAPACITY = 16\n\nexport default class HashSet {\n\n    constructor(hashFunction, equalsFunction) {\n        this.buckets = new Array(INITIAL_CAPACITY);\n        this.threshold = Math.floor(INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);\n        this.itemCount = 0;\n        this.hashFunction = hashFunction || standardHashCodeFunction;\n        this.equalsFunction = equalsFunction || standardEqualsFunction;\n    }\n\n    get(value) {\n        if(value == null) {\n            return value;\n        }\n        const bucket = this._getBucket(value)\n        if (!bucket) {\n            return null;\n        }\n        for (const e of bucket) {\n            if (this.equalsFunction(e, value)) {\n                return e;\n            }\n        }\n        return null;\n    }\n\n    add(value) {\n        const existing = this.getOrAdd(value);\n        return existing === value;\n    }\n\n    getOrAdd(value) {\n        this._expand();\n        const slot = this._getSlot(value);\n        let bucket = this.buckets[slot];\n        if (!bucket) {\n            bucket = [value];\n            this.buckets[slot] = bucket;\n            this.itemCount++;\n            return value;\n        }\n        for (const existing of bucket) {\n            if (this.equalsFunction(existing, value)) {\n                return existing;\n            }\n        }\n        bucket.push(value);\n        this.itemCount++;\n        return value;\n\n    }\n\n    has(value) {\n        return this.get(value) != null;\n    }\n\n\n    values() {\n        return this.buckets.filter(b => b != null).flat(1);\n    }\n\n    toString() {\n        return arrayToString(this.values());\n    }\n\n    get length() {\n        return this.itemCount;\n    }\n\n    _getSlot(value) {\n        const hash = this.hashFunction(value);\n        return hash & this.buckets.length - 1;\n    }\n    _getBucket(value) {\n        return this.buckets[this._getSlot(value)];\n    }\n\n    _expand() {\n        if (this.itemCount <= this.threshold) {\n            return;\n        }\n        const old_buckets = this.buckets;\n        const newCapacity = this.buckets.length * 2;\n        this.buckets = new Array(newCapacity);\n        this.threshold = Math.floor(newCapacity * DEFAULT_LOAD_FACTOR);\n        for (const bucket of old_buckets) {\n            if (!bucket) {\n                continue;\n            }\n            for (const o of bucket) {\n                const slot = this._getSlot(o);\n                let newBucket = this.buckets[slot];\n                if (!newBucket) {\n                    newBucket = [];\n                    this.buckets[slot] = newBucket;\n                }\n                newBucket.push(o);\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/Interval.d.ts",
    "content": "import {Token} from \"../Token.js\";\n\nexport declare class Interval {\n\n    start: number;\n    stop: number;\n\n    constructor(start: number, stop: number);\n    constructor(start: Token, stop: Token | undefined);\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/Interval.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n/* stop is not included! */\nexport default class Interval {\n\n    constructor(start, stop) {\n        this.start = start;\n        this.stop = stop;\n    }\n\n    clone() {\n        return new Interval(this.start, this.stop);\n    }\n\n    contains(item) {\n        return item >= this.start && item < this.stop;\n    }\n\n    toString() {\n        if(this.start===this.stop-1) {\n            return this.start.toString();\n        } else {\n            return this.start.toString() + \"..\" + (this.stop-1).toString();\n        }\n    }\n\n    get length(){\n        return this.stop - this.start;\n    }\n}\n\nInterval.INVALID_INTERVAL = new Interval(-1, -2);\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/IntervalSet.d.ts",
    "content": "import {Interval} from \"./Interval.js\";\n\nexport declare class IntervalSet {\n\n    isNil: boolean;\n    size: number;\n    minElement: number;\n    maxElement: number;\n    intervals: Interval[];\n\n    contains(i: number): boolean;\n    toString(literalNames?: (string | null)[], symbolicNames?: string[], elemsAreChar?: boolean): string;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/IntervalSet.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from '../Token.js';\nimport Interval from \"./Interval.js\";\n\nexport default class IntervalSet {\n\tconstructor() {\n\t\tthis.intervals = null;\n\t\tthis.readOnly = false;\n\t}\n\n\tfirst(v) {\n\t\tif (this.intervals === null || this.intervals.length===0) {\n\t\t\treturn Token.INVALID_TYPE;\n\t\t} else {\n\t\t\treturn this.intervals[0].start;\n\t\t}\n\t}\n\n\taddOne(v) {\n\t\tthis.addInterval(new Interval(v, v + 1));\n\t}\n\n\taddRange(l, h) {\n\t\tthis.addInterval(new Interval(l, h + 1));\n\t}\n\n\taddInterval(toAdd) {\n\t\tif (this.intervals === null) {\n\t\t\tthis.intervals = [];\n\t\t\tthis.intervals.push(toAdd.clone());\n\t\t} else {\n\t\t\t// find insert pos\n\t\t\tfor (let pos = 0; pos < this.intervals.length; pos++) {\n\t\t\t\tconst existing = this.intervals[pos];\n\t\t\t\t// distinct range -> insert\n\t\t\t\tif (toAdd.stop < existing.start) {\n\t\t\t\t\tthis.intervals.splice(pos, 0, toAdd);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// contiguous range -> adjust\n\t\t\t\telse if (toAdd.stop === existing.start) {\n\t\t\t\t\tthis.intervals[pos] = new Interval(toAdd.start, existing.stop)\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// overlapping range -> adjust and reduce\n\t\t\t\telse if (toAdd.start <= existing.stop) {\n\t\t\t\t\tthis.intervals[pos] = new Interval(Math.min(existing.start, toAdd.start), Math.max(existing.stop, toAdd.stop));\n\t\t\t\t\tthis.reduce(pos);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// greater than any existing\n\t\t\tthis.intervals.push(toAdd.clone());\n\t\t}\n\t}\n\n\taddSet(other) {\n\t\tif (other.intervals !== null) {\n\t\t\tother.intervals.forEach( toAdd => this.addInterval(toAdd), this);\n\t\t}\n\t\treturn this;\n\t}\n\n\treduce(pos) {\n\t\t// only need to reduce if pos is not the last\n\t\tif (pos < this.intervals.length - 1) {\n\t\t\tconst current = this.intervals[pos];\n\t\t\tconst next = this.intervals[pos + 1];\n\t\t\t// if next contained in current\n\t\t\tif (current.stop >= next.stop) {\n\t\t\t\tthis.intervals.splice(pos + 1, 1);\n\t\t\t\tthis.reduce(pos);\n\t\t\t} else if (current.stop >= next.start) {\n\t\t\t\tthis.intervals[pos] = new Interval(current.start, next.stop);\n\t\t\t\tthis.intervals.splice(pos + 1, 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tcomplement(start, stop) {\n\t\tconst result = new IntervalSet();\n\t\tresult.addInterval(new Interval(start, stop + 1));\n\t\tif(this.intervals !== null)\n\t\t\tthis.intervals.forEach(toRemove => result.removeRange(toRemove));\n\t\treturn result;\n\t}\n\n\tcontains(item) {\n\t\tif (this.intervals === null) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\tfor (let k = 0; k < this.intervals.length; k++) {\n\t\t\t\tif(this.intervals[k].contains(item)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tremoveRange(toRemove) {\n\t\tif(toRemove.start===toRemove.stop-1) {\n\t\t\tthis.removeOne(toRemove.start);\n\t\t} else if (this.intervals !== null) {\n\t\t\tlet pos = 0;\n\t\t\tfor(let n=0; n<this.intervals.length; n++) {\n\t\t\t\tconst existing = this.intervals[pos];\n\t\t\t\t// intervals are ordered\n\t\t\t\tif (toRemove.stop<=existing.start) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// check for including range, split it\n\t\t\t\telse if(toRemove.start>existing.start && toRemove.stop<existing.stop) {\n\t\t\t\t\tthis.intervals[pos] = new Interval(existing.start, toRemove.start);\n\t\t\t\t\tconst x = new Interval(toRemove.stop, existing.stop);\n\t\t\t\t\tthis.intervals.splice(pos, 0, x);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// check for included range, remove it\n\t\t\t\telse if(toRemove.start<=existing.start && toRemove.stop>=existing.stop) {\n\t\t\t\t\tthis.intervals.splice(pos, 1);\n\t\t\t\t\tpos = pos - 1; // need another pass\n\t\t\t\t}\n\t\t\t\t// check for lower boundary\n\t\t\t\telse if(toRemove.start<existing.stop) {\n\t\t\t\t\tthis.intervals[pos] = new Interval(existing.start, toRemove.start);\n\t\t\t\t}\n\t\t\t\t// check for upper boundary\n\t\t\t\telse if(toRemove.stop<existing.stop) {\n\t\t\t\t\tthis.intervals[pos] = new Interval(toRemove.stop, existing.stop);\n\t\t\t\t}\n\t\t\t\tpos += 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tremoveOne(value) {\n\t\tif (this.intervals !== null) {\n\t\t\tfor (let i = 0; i < this.intervals.length; i++) {\n\t\t\t\tconst existing = this.intervals[i];\n\t\t\t\t// intervals are ordered\n\t\t\t\tif (value < existing.start) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// check for single value range\n\t\t\t\telse if (value === existing.start && value === existing.stop - 1) {\n\t\t\t\t\tthis.intervals.splice(i, 1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// check for lower boundary\n\t\t\t\telse if (value === existing.start) {\n\t\t\t\t\tthis.intervals[i] = new Interval(existing.start + 1, existing.stop);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// check for upper boundary\n\t\t\t\telse if (value === existing.stop - 1) {\n\t\t\t\t\tthis.intervals[i] = new Interval(existing.start, existing.stop - 1);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// split existing range\n\t\t\t\telse if (value < existing.stop - 1) {\n\t\t\t\t\tconst replace = new Interval(existing.start, value);\n\t\t\t\t\texisting.start = value + 1;\n\t\t\t\t\tthis.intervals.splice(i, 0, replace);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttoString(literalNames, symbolicNames, elemsAreChar) {\n\t\tliteralNames = literalNames || null;\n\t\tsymbolicNames = symbolicNames || null;\n\t\telemsAreChar = elemsAreChar || false;\n\t\tif (this.intervals === null) {\n\t\t\treturn \"{}\";\n\t\t} else if(literalNames!==null || symbolicNames!==null) {\n\t\t\treturn this.toTokenString(literalNames, symbolicNames);\n\t\t} else if(elemsAreChar) {\n\t\t\treturn this.toCharString();\n\t\t} else {\n\t\t\treturn this.toIndexString();\n\t\t}\n\t}\n\n\ttoCharString() {\n\t\tconst names = [];\n\t\tfor (let i = 0; i < this.intervals.length; i++) {\n\t\t\tconst existing = this.intervals[i];\n\t\t\tif(existing.stop===existing.start+1) {\n\t\t\t\tif ( existing.start===Token.EOF ) {\n\t\t\t\t\tnames.push(\"<EOF>\");\n\t\t\t\t} else {\n\t\t\t\t\tnames.push(\"'\" + String.fromCharCode(existing.start) + \"'\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnames.push(\"'\" + String.fromCharCode(existing.start) + \"'..'\" + String.fromCharCode(existing.stop-1) + \"'\");\n\t\t\t}\n\t\t}\n\t\tif (names.length > 1) {\n\t\t\treturn \"{\" + names.join(\", \") + \"}\";\n\t\t} else {\n\t\t\treturn names[0];\n\t\t}\n\t}\n\n\ttoIndexString() {\n\t\tconst names = [];\n\t\tfor (let i = 0; i < this.intervals.length; i++) {\n\t\t\tconst existing = this.intervals[i];\n\t\t\tif(existing.stop===existing.start+1) {\n\t\t\t\tif ( existing.start===Token.EOF ) {\n\t\t\t\t\tnames.push(\"<EOF>\");\n\t\t\t\t} else {\n\t\t\t\t\tnames.push(existing.start.toString());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnames.push(existing.start.toString() + \"..\" + (existing.stop-1).toString());\n\t\t\t}\n\t\t}\n\t\tif (names.length > 1) {\n\t\t\treturn \"{\" + names.join(\", \") + \"}\";\n\t\t} else {\n\t\t\treturn names[0];\n\t\t}\n\t}\n\n\ttoTokenString(literalNames, symbolicNames) {\n\t\tconst names = [];\n\t\tfor (let i = 0; i < this.intervals.length; i++) {\n\t\t\tconst existing = this.intervals[i];\n\t\t\tfor (let j = existing.start; j < existing.stop; j++) {\n\t\t\t\tnames.push(this.elementName(literalNames, symbolicNames, j));\n\t\t\t}\n\t\t}\n\t\tif (names.length > 1) {\n\t\t\treturn \"{\" + names.join(\", \") + \"}\";\n\t\t} else {\n\t\t\treturn names[0];\n\t\t}\n\t}\n\n\telementName(literalNames, symbolicNames, token) {\n\t\tif (token === Token.EOF) {\n\t\t\treturn \"<EOF>\";\n\t\t} else if (token === Token.EPSILON) {\n\t\t\treturn \"<EPSILON>\";\n\t\t} else {\n\t\t\treturn literalNames[token] || symbolicNames[token];\n\t\t}\n\t}\n\n\tget length(){\n\t\treturn this.intervals.map( interval => interval.length ).reduce((acc, val) => acc + val);\n\t}\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/index.d.ts",
    "content": "export * from \"./BitSet.js\"\nexport * from \"./Interval.js\"\nexport * from \"./IntervalSet.js\";\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/misc/index.js",
    "content": "import BitSet from './BitSet.js';\nimport Interval from './Interval.js';\nimport IntervalSet from './IntervalSet.js';\n\nexport default { BitSet, Interval, IntervalSet }\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/ATNState.d.ts",
    "content": "import {ATN} from \"../atn/index.js\";\n\nexport declare class ATNState {\n    atn: ATN;\n    stateNumber: number;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/ATNState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/**\n * The following images show the relation of states and\n * {@link ATNState//transitions} for various grammar constructs.\n *\n * <ul>\n *\n * <li>Solid edges marked with an &//0949; indicate a required\n * {@link EpsilonTransition}.</li>\n *\n * <li>Dashed edges indicate locations where any transition derived from\n * {@link Transition} might appear.</li>\n *\n * <li>Dashed nodes are place holders for either a sequence of linked\n * {@link BasicState} states or the inclusion of a block representing a nested\n * construct in one of the forms below.</li>\n *\n * <li>Nodes showing multiple outgoing alternatives with a {@code ...} support\n * any number of alternatives (one or more). Nodes without the {@code ...} only\n * support the exact number of alternatives shown in the diagram.</li>\n *\n * </ul>\n *\n * <h2>Basic Blocks</h2>\n *\n * <h3>Rule</h3>\n *\n * <embed src=\"images/Rule.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Block of 1 or more alternatives</h3>\n *\n * <embed src=\"images/Block.svg\" type=\"image/svg+xml\"/>\n *\n * <h2>Greedy Loops</h2>\n *\n * <h3>Greedy Closure: {@code (...)*}</h3>\n *\n * <embed src=\"images/ClosureGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Greedy Positive Closure: {@code (...)+}</h3>\n *\n * <embed src=\"images/PositiveClosureGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Greedy Optional: {@code (...)?}</h3>\n *\n * <embed src=\"images/OptionalGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h2>Non-Greedy Loops</h2>\n *\n * <h3>Non-Greedy Closure: {@code (...)*?}</h3>\n *\n * <embed src=\"images/ClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>\n *\n * <embed src=\"images/PositiveClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n *\n * <h3>Non-Greedy Optional: {@code (...)??}</h3>\n *\n * <embed src=\"images/OptionalNonGreedy.svg\" type=\"image/svg+xml\"/>\n */\nexport default class ATNState {\n    constructor() {\n        // Which ATN are we in?\n        this.atn = null;\n        this.stateNumber = ATNState.INVALID_STATE_NUMBER;\n        this.stateType = null;\n        this.ruleIndex = 0; // at runtime, we don't have Rule objects\n        this.epsilonOnlyTransitions = false;\n        // Track the transitions emanating from this ATN state.\n        this.transitions = [];\n        // Used to cache lookahead during parsing, not used during construction\n        this.nextTokenWithinRule = null;\n    }\n\n    toString() {\n        return this.stateNumber;\n    }\n\n    equals(other) {\n        if (other instanceof ATNState) {\n            return this.stateNumber===other.stateNumber;\n        } else {\n            return false;\n        }\n    }\n\n    isNonGreedyExitState() {\n        return false;\n    }\n\n    addTransition(trans, index) {\n        if(index===undefined) {\n            index = -1;\n        }\n        if (this.transitions.length===0) {\n            this.epsilonOnlyTransitions = trans.isEpsilon;\n        } else if(this.epsilonOnlyTransitions !== trans.isEpsilon) {\n            this.epsilonOnlyTransitions = false;\n        }\n        if (index===-1) {\n            this.transitions.push(trans);\n        } else {\n            this.transitions.splice(index, 1, trans);\n        }\n    }\n}\n\n// constants for serialization\nATNState.INVALID_TYPE = 0;\nATNState.BASIC = 1;\nATNState.RULE_START = 2;\nATNState.BLOCK_START = 3;\nATNState.PLUS_BLOCK_START = 4;\nATNState.STAR_BLOCK_START = 5;\nATNState.TOKEN_START = 6;\nATNState.RULE_STOP = 7;\nATNState.BLOCK_END = 8;\nATNState.STAR_LOOP_BACK = 9;\nATNState.STAR_LOOP_ENTRY = 10;\nATNState.PLUS_LOOP_BACK = 11;\nATNState.LOOP_END = 12;\n\nATNState.serializationNames = [\n            \"INVALID\",\n            \"BASIC\",\n            \"RULE_START\",\n            \"BLOCK_START\",\n            \"PLUS_BLOCK_START\",\n            \"STAR_BLOCK_START\",\n            \"TOKEN_START\",\n            \"RULE_STOP\",\n            \"BLOCK_END\",\n            \"STAR_LOOP_BACK\",\n            \"STAR_LOOP_ENTRY\",\n            \"PLUS_LOOP_BACK\",\n            \"LOOP_END\" ];\n\nATNState.INVALID_STATE_NUMBER = -1;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/BasicBlockStartState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\nimport BlockStartState from \"./BlockStartState.js\";\n\nexport default class BasicBlockStartState extends BlockStartState {\n    constructor() {\n        super();\n        this.stateType = ATNState.BLOCK_START;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/BasicState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\n\nexport default class BasicState extends ATNState {\n    constructor() {\n        super();\n        this.stateType = ATNState.BASIC;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/BlockEndState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\n\n/**\n * Terminal node of a simple {@code (a|b|c)} block\n */\nexport default class BlockEndState extends ATNState {\n    constructor() {\n        super();\n        this.stateType = ATNState.BLOCK_END;\n        this.startState = null;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/BlockStartState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport DecisionState from \"./DecisionState.js\";\n\n/**\n *  The start of a regular {@code (...)} block\n */\nexport default class BlockStartState extends DecisionState {\n    constructor() {\n        super();\n        this.endState = null;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/DecisionState.d.ts",
    "content": "import {ATNState} from \"./index.js\";\n\nexport declare class DecisionState extends ATNState {\n    decision: number;\n    nonGreedy: boolean;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/DecisionState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\n\nexport default class DecisionState extends ATNState {\n    constructor() {\n        super();\n        this.decision = -1;\n        this.nonGreedy = false;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/LoopEndState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\n\n/**\n * Mark the end of a * or + loop\n */\nexport default class LoopEndState extends ATNState {\n    constructor() {\n        super();\n        this.stateType = ATNState.LOOP_END;\n        this.loopBackState = null;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/PlusBlockStartState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport BlockStartState from \"./BlockStartState.js\";\nimport ATNState from \"./ATNState.js\";\n\n/**\n * Start of {@code (A|B|...)+} loop. Technically a decision state, but\n * we don't use for code generation; somebody might need it, so I'm defining\n * it for completeness. In reality, the {@link PlusLoopbackState} node is the\n * real decision-making note for {@code A+}\n */\nexport default class PlusBlockStartState extends BlockStartState {\n    constructor() {\n        super();\n        this.stateType = ATNState.PLUS_BLOCK_START;\n        this.loopBackState = null;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/PlusLoopbackState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport DecisionState from \"./DecisionState.js\";\nimport ATNState from \"./ATNState.js\";\n\n/**\n * Decision state for {@code A+} and {@code (A|B)+}.  It has two transitions:\n * one to the loop back to start of the block and one to exit.\n */\nexport default class PlusLoopbackState extends DecisionState {\n    constructor() {\n        super();\n        this.stateType = ATNState.PLUS_LOOP_BACK;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/RuleStartState.d.ts",
    "content": "import {ATNState, RuleStopState} from \"./index.js\";\n\nexport declare class RuleStartState extends ATNState {\n    stopState: RuleStopState;\n    isLeftRecursiveRule: boolean;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/RuleStartState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\n\nexport default class RuleStartState extends ATNState {\n    constructor() {\n        super();\n        this.stateType = ATNState.RULE_START;\n        this.stopState = null;\n        this.isPrecedenceRule = false;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/RuleStopState.d.ts",
    "content": "import {ATNState} from \"./index.js\";\n\nexport declare class RuleStopState extends ATNState {\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/RuleStopState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\n\n/**\n * The last node in the ATN for a rule, unless that rule is the start symbol.\n * In that case, there is one transition to EOF. Later, we might encode\n * references to all calls to this rule to compute FOLLOW sets for\n * error handling\n */\nexport default class RuleStopState extends ATNState {\n    constructor() {\n        super();\n        this.stateType = ATNState.RULE_STOP;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/StarBlockStartState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport BlockStartState from \"./BlockStartState.js\";\nimport ATNState from \"./ATNState.js\";\n\n/**\n * The block that begins a closure loop\n */\nexport default class StarBlockStartState extends BlockStartState {\n    constructor() {\n        super();\n        this.stateType = ATNState.STAR_BLOCK_START;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/StarLoopEntryState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport DecisionState from \"./DecisionState.js\";\nimport ATNState from \"./ATNState.js\";\n\nexport default class StarLoopEntryState extends DecisionState {\n    constructor() {\n        super();\n        this.stateType = ATNState.STAR_LOOP_ENTRY;\n        this.loopBackState = null;\n        // Indicates whether this state can benefit from a precedence DFA during SLL decision making.\n        this.isPrecedenceDecision = null;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/StarLoopbackState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ATNState from \"./ATNState.js\";\n\nexport default class StarLoopbackState extends ATNState {\n    constructor() {\n        super();\n        this.stateType = ATNState.STAR_LOOP_BACK;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/TokensStartState.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport DecisionState from \"./DecisionState.js\";\nimport ATNState from \"./ATNState.js\";\n\n/**\n * The Tokens rule start state linking to each lexer rule start state\n */\nexport default class TokensStartState extends DecisionState {\n    constructor() {\n        super();\n        this.stateType = ATNState.TOKEN_START;\n        return this;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/state/index.d.ts",
    "content": "export * from \"./ATNState.js\";\nexport * from \"./DecisionState.js\";\nexport * from \"./RuleStartState.js\";\nexport * from \"./RuleStopState.js\";\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/ActionTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Transition from \"./Transition.js\";\n\nexport default class ActionTransition extends Transition {\n    constructor(target, ruleIndex, actionIndex, isCtxDependent) {\n        super(target);\n        this.serializationType = Transition.ACTION;\n        this.ruleIndex = ruleIndex;\n        this.actionIndex = actionIndex===undefined ? -1 : actionIndex;\n        this.isCtxDependent = isCtxDependent===undefined ? false : isCtxDependent; // e.g., $i ref in pred\n        this.isEpsilon = true;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return false;\n    }\n\n    toString() {\n        return \"action_\" + this.ruleIndex + \":\" + this.actionIndex;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/AtomTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport IntervalSet from \"../misc/IntervalSet.js\";\nimport Transition from \"./Transition.js\";\n\nexport default class AtomTransition extends Transition {\n    constructor(target, label) {\n        super(target);\n        // The token type or character value; or, signifies special label.\n        this.label_ = label;\n        this.label = this.makeLabel();\n        this.serializationType = Transition.ATOM;\n    }\n\n    makeLabel() {\n        const s = new IntervalSet();\n        s.addOne(this.label_);\n        return s;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return this.label_ === symbol;\n    }\n\n    toString() {\n        return this.label_;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/EpsilonTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Transition from \"./Transition.js\";\n\nexport default class EpsilonTransition extends Transition {\n    constructor(target, outermostPrecedenceReturn) {\n        super(target);\n        this.serializationType = Transition.EPSILON;\n        this.isEpsilon = true;\n        this.outermostPrecedenceReturn = outermostPrecedenceReturn;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return false;\n    }\n\n    toString() {\n        return \"epsilon\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/NotSetTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Transition from \"./Transition.js\";\nimport SetTransition from \"./SetTransition.js\";\n\nexport default class NotSetTransition extends SetTransition {\n    constructor(target, set) {\n        super(target, set);\n        this.serializationType = Transition.NOT_SET;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return symbol >= minVocabSymbol && symbol <= maxVocabSymbol &&\n            !super.matches(symbol, minVocabSymbol, maxVocabSymbol);\n    }\n\n    toString() {\n        return '~' + super.toString();\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/PrecedencePredicateTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport PrecedencePredicate from \"../atn/PrecedencePredicate.js\";\nimport Transition from \"./Transition.js\";\nimport AbstractPredicateTransition from \"../atn/AbstractPredicateTransition.js\";\n\nexport default class PrecedencePredicateTransition extends AbstractPredicateTransition {\n    constructor(target, precedence) {\n        super(target);\n        this.serializationType = Transition.PRECEDENCE;\n        this.precedence = precedence;\n        this.isEpsilon = true;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return false;\n    }\n\n    getPredicate() {\n        return new PrecedencePredicate(this.precedence);\n    }\n\n    toString() {\n        return this.precedence + \" >= _p\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/PredicateTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Predicate from \"../atn/Predicate.js\";\nimport Transition from \"./Transition.js\";\nimport AbstractPredicateTransition from \"../atn/AbstractPredicateTransition.js\";\n\nexport default class PredicateTransition extends AbstractPredicateTransition {\n    constructor(target, ruleIndex, predIndex, isCtxDependent) {\n        super(target);\n        this.serializationType = Transition.PREDICATE;\n        this.ruleIndex = ruleIndex;\n        this.predIndex = predIndex;\n        this.isCtxDependent = isCtxDependent; // e.g., $i ref in pred\n        this.isEpsilon = true;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return false;\n    }\n\n    getPredicate() {\n        return new Predicate(this.ruleIndex, this.predIndex, this.isCtxDependent);\n    }\n\n    toString() {\n        return \"pred_\" + this.ruleIndex + \":\" + this.predIndex;\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/RangeTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport IntervalSet from \"../misc/IntervalSet.js\";\nimport Transition from \"./Transition.js\";\n\nexport default class RangeTransition extends Transition {\n    constructor(target, start, stop) {\n        super(target);\n        this.serializationType = Transition.RANGE;\n        this.start = start;\n        this.stop = stop;\n        this.label = this.makeLabel();\n    }\n\n    makeLabel() {\n        const s = new IntervalSet();\n        s.addRange(this.start, this.stop);\n        return s;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return symbol >= this.start && symbol <= this.stop;\n    }\n\n    toString() {\n        return \"'\" + String.fromCharCode(this.start) + \"'..'\" + String.fromCharCode(this.stop) + \"'\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/RuleTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Transition from \"./Transition.js\";\n\nexport default class RuleTransition extends Transition {\n    constructor(ruleStart, ruleIndex, precedence, followState) {\n        super(ruleStart);\n        // ptr to the rule definition object for this rule ref\n        this.ruleIndex = ruleIndex;\n        this.precedence = precedence;\n        // what node to begin computations following ref to rule\n        this.followState = followState;\n        this.serializationType = Transition.RULE;\n        this.isEpsilon = true;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return false;\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/SetTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n// A transition containing a set of values.\nimport IntervalSet from \"../misc/IntervalSet.js\";\nimport Token from '../Token.js';\nimport Transition from \"./Transition.js\";\n\nexport default class SetTransition extends Transition {\n    constructor(target, set) {\n        super(target);\n        this.serializationType = Transition.SET;\n        if (set !==undefined && set !==null) {\n            this.label = set;\n        } else {\n            this.label = new IntervalSet();\n            this.label.addOne(Token.INVALID_TYPE);\n        }\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return this.label.contains(symbol);\n    }\n\n    toString() {\n        return this.label.toString();\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/Transition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/**\n * An ATN transition between any two ATN states.  Subclasses define\n * atom, set, epsilon, action, predicate, rule transitions.\n *\n * <p>This is a one way link.  It emanates from a state (usually via a list of\n * transitions) and has a target state.</p>\n *\n * <p>Since we never have to change the ATN transitions once we construct it,\n * we can fix these transitions as specific classes. The DFA transitions\n * on the other hand need to update the labels as it adds transitions to\n * the states. We'll use the term Edge for the DFA to distinguish them from\n * ATN transitions.</p>\n */\nexport default class Transition {\n    constructor(target) {\n        // The target of this transition.\n        if (target===undefined || target===null) {\n            throw \"target cannot be null.\";\n        }\n        this.target = target;\n        // Are we epsilon, action, sempred?\n        this.isEpsilon = false;\n        this.label = null;\n    }\n}\n\n// constants for serialization\n\nTransition.EPSILON = 1;\nTransition.RANGE = 2;\nTransition.RULE = 3;\n// e.g., {isType(input.LT(1))}?\nTransition.PREDICATE = 4;\nTransition.ATOM = 5;\nTransition.ACTION = 6;\n// ~(A|B) or ~atom, wildcard, which convert to next 2\nTransition.SET = 7;\nTransition.NOT_SET = 8;\nTransition.WILDCARD = 9;\nTransition.PRECEDENCE = 10;\n\nTransition.serializationNames = [\n            \"INVALID\",\n            \"EPSILON\",\n            \"RANGE\",\n            \"RULE\",\n            \"PREDICATE\",\n            \"ATOM\",\n            \"ACTION\",\n            \"SET\",\n            \"NOT_SET\",\n            \"WILDCARD\",\n            \"PRECEDENCE\"\n        ];\n\nTransition.serializationTypes = {\n        EpsilonTransition: Transition.EPSILON,\n        RangeTransition: Transition.RANGE,\n        RuleTransition: Transition.RULE,\n        PredicateTransition: Transition.PREDICATE,\n        AtomTransition: Transition.ATOM,\n        ActionTransition: Transition.ACTION,\n        SetTransition: Transition.SET,\n        NotSetTransition: Transition.NOT_SET,\n        WildcardTransition: Transition.WILDCARD,\n        PrecedencePredicateTransition: Transition.PRECEDENCE\n    };\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/transition/WildcardTransition.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Transition from \"./Transition.js\";\n\nexport default class WildcardTransition extends Transition {\n    constructor(target) {\n        super(target);\n        this.serializationType = Transition.WILDCARD;\n    }\n\n    matches(symbol, minVocabSymbol, maxVocabSymbol) {\n        return symbol >= minVocabSymbol && symbol <= maxVocabSymbol;\n    }\n\n    toString() {\n        return \".\";\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ErrorNode.d.ts",
    "content": "import {TerminalNode} from \"./TerminalNode.js\";\n\nexport declare class ErrorNode extends TerminalNode {\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ErrorNode.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport TerminalNode from \"./TerminalNode.js\";\n\nexport default class ErrorNode extends TerminalNode {\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ErrorNodeImpl.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n/**\n * Represents a token that was consumed during resynchronization\n * rather than during a valid match operation. For example,\n * we will create this kind of a node during single token insertion\n * and deletion as well as during \"consume until error recovery set\"\n * upon no viable alternative exceptions.\n */\nimport TerminalNodeImpl from \"./TerminalNodeImpl.js\";\n\nexport default class ErrorNodeImpl extends TerminalNodeImpl {\n    constructor(token) {\n        super(token);\n    }\n\n    isErrorNode() {\n        return true;\n    }\n\n    accept(visitor) {\n        return visitor.visitErrorNode(this);\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTree.d.ts",
    "content": "import {SyntaxTree} from \"./SyntaxTree.js\";\n\nexport declare class ParseTree extends SyntaxTree {\n    getText(): string;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTree.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport SyntaxTree from \"./SyntaxTree.js\";\n\nexport default class ParseTree extends SyntaxTree {\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTreeListener.d.ts",
    "content": "import {ParserRuleContext} from \"../context/index.js\";\nimport {ErrorNode} from \"./ErrorNode.js\";\nimport {TerminalNode} from \"./TerminalNode.js\";\n\nexport declare abstract class ParseTreeListener {\n    visitTerminal(node: TerminalNode) : void;\n    visitErrorNode(node: ErrorNode) : void;\n    enterEveryRule(ctx: ParserRuleContext) : void;\n    exitEveryRule(ctx: ParserRuleContext) : void;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTreeListener.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default class ParseTreeListener {\n    visitTerminal(node) {\n    }\n\n    visitErrorNode(node) {\n    }\n\n    enterEveryRule(node) {\n    }\n\n    exitEveryRule(node) {\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTreeVisitor.d.ts",
    "content": "import {RuleNode} from \"./RuleNode.js\";\nimport {ErrorNode} from \"./ErrorNode.js\";\nimport {TerminalNode} from \"./TerminalNode.js\";\nimport {ParseTree} from \"./ParseTree.js\";\n\nexport declare class ParseTreeVisitor<Result> {\n\n    visit(tree: ParseTree): Result;\n\n    visitChildren(node: RuleNode): Result;\n\n    visitTerminal(node: TerminalNode): Result;\n\n    visitErrorNode(node: ErrorNode): Result;\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTreeVisitor.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default class ParseTreeVisitor {\n    visit(ctx) {\n        if (Array.isArray(ctx)) {\n            return ctx.map(function(child) {\n                return child.accept(this);\n            }, this);\n        } else {\n            return ctx.accept(this);\n        }\n    }\n\n    visitChildren(ctx) {\n        if (ctx.children) {\n            return this.visit(ctx.children);\n        } else {\n            return null;\n        }\n    }\n\n    visitTerminal(node) {\n    }\n\n    visitErrorNode(node) {\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTreeWalker.d.ts",
    "content": "import {ParseTreeListener} from \"./ParseTreeListener.js\";\nimport {ParseTree} from \"./ParseTree.js\";\n\nexport declare class ParseTreeWalker {\n    static DEFAULT: ParseTreeWalker;\n\n    walk<T extends ParseTreeListener>(listener: T, t: ParseTree): void;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/ParseTreeWalker.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport TerminalNode from \"./TerminalNode.js\";\nimport ErrorNode from \"./ErrorNode.js\";\n\nexport default class ParseTreeWalker {\n\n    /**\n     * Performs a walk on the given parse tree starting at the root and going down recursively\n     * with depth-first search. On each node, {@link ParseTreeWalker//enterRule} is called before\n     * recursively walking down into child nodes, then\n     * {@link ParseTreeWalker//exitRule} is called after the recursive call to wind up.\n     * @param listener The listener used by the walker to process grammar rules\n     * @param t The parse tree to be walked on\n     */\n    walk(listener, t) {\n        const errorNode = t instanceof ErrorNode ||\n            (t.isErrorNode !== undefined && t.isErrorNode());\n        if (errorNode) {\n            listener.visitErrorNode(t);\n        } else if (t instanceof TerminalNode) {\n            listener.visitTerminal(t);\n        } else {\n            this.enterRule(listener, t);\n            for (let i = 0; i < t.getChildCount(); i++) {\n                const child = t.getChild(i);\n                this.walk(listener, child);\n            }\n            this.exitRule(listener, t);\n        }\n    }\n\n    /**\n     * Enters a grammar rule by first triggering the generic event {@link ParseTreeListener//enterEveryRule}\n     * then by triggering the event specific to the given parse tree node\n     * @param listener The listener responding to the trigger events\n     * @param r The grammar rule containing the rule context\n     */\n    enterRule(listener, r) {\n        const ctx = r.ruleContext;\n        listener.enterEveryRule(ctx);\n        ctx.enterRule(listener);\n    }\n\n    /**\n     * Exits a grammar rule by first triggering the event specific to the given parse tree node\n     * then by triggering the generic event {@link ParseTreeListener//exitEveryRule}\n     * @param listener The listener responding to the trigger events\n     * @param r The grammar rule containing the rule context\n     */\n    exitRule(listener, r) {\n        const ctx = r.ruleContext;\n        ctx.exitRule(listener);\n        listener.exitEveryRule(ctx);\n    }\n}\n\nParseTreeWalker.DEFAULT = new ParseTreeWalker();\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/RuleNode.d.ts",
    "content": "import {ParseTree} from \"./ParseTree.js\";\n\nexport declare abstract class RuleNode extends ParseTree {\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/RuleNode.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ParseTree from \"./ParseTree.js\";\n\nexport default class RuleNode extends ParseTree {\n\n    get ruleContext() {\n        throw new Error(\"missing interface implementation\")\n    }\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/SyntaxTree.d.ts",
    "content": "import {Tree} from \"./Tree.js\";\n\nexport declare class SyntaxTree extends Tree {}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/SyntaxTree.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Tree from \"./Tree.js\";\n\nexport default class SyntaxTree extends Tree {\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/TerminalNode.d.ts",
    "content": "import {ParserRuleContext} from \"../context/index.js\";\nimport {ParseTree} from \"./ParseTree.js\";\nimport {Token} from \"../Token.js\";\n\nexport declare class TerminalNode extends ParseTree {\n    symbol: Token;\n    parentCtx: ParserRuleContext;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/TerminalNode.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport ParseTree from \"./ParseTree.js\";\n\nexport default class TerminalNode extends ParseTree {\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/TerminalNodeImpl.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Interval from \"../misc/Interval.js\";\nimport Token from '../Token.js';\nimport TerminalNode from \"./TerminalNode.js\";\n\nexport default class TerminalNodeImpl extends TerminalNode {\n    constructor(symbol) {\n        super();\n        this.parentCtx = null;\n        this.symbol = symbol;\n    }\n\n    getChild(i) {\n        return null;\n    }\n\n    getSymbol() {\n        return this.symbol;\n    }\n\n    getParent() {\n        return this.parentCtx;\n    }\n\n    getPayload() {\n        return this.symbol;\n    }\n\n    getSourceInterval() {\n        if (this.symbol === null) {\n            return Interval.INVALID_INTERVAL;\n        }\n        const tokenIndex = this.symbol.tokenIndex;\n        return new Interval(tokenIndex, tokenIndex);\n    }\n\n    getChildCount() {\n        return 0;\n    }\n\n    accept(visitor) {\n        return visitor.visitTerminal(this);\n    }\n\n    getText() {\n        return this.symbol.text;\n    }\n\n    toString() {\n        if (this.symbol.type === Token.EOF) {\n            return \"<EOF>\";\n        } else {\n            return this.symbol.text;\n        }\n    }\n}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/Tree.d.ts",
    "content": "export declare class Tree {}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/Tree.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n/**\n * The basic notion of a tree has a parent, a payload, and a list of children.\n * It is the most abstract interface for all the trees used by ANTLR.\n */\nexport default class Tree {}\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/Trees.d.ts",
    "content": "import { Parser } from \"../Parser.js\";\nimport { ParseTree } from \"./ParseTree.js\";\nimport { Tree } from \"./Tree.js\";\n\nexport default Trees;\ndeclare namespace Trees {\n    function toStringTree(tree: Tree, ruleNames: string[], recog: Parser): string;\n    function getNodeText(t: Tree, ruleNames: string[], recog: Parser): string;\n    function getChildren(t: Tree): Tree[];\n    function getAncestors(t: Tree): Tree[];\n    function findAllTokenNodes(t: ParseTree, ttype: number): ParseTree[];\n    function findAllRuleNodes(t: ParseTree, ruleIndex: number): ParseTree[];\n    function findAllNodes(t: ParseTree, index: number, findTokens: boolean): ParseTree[];\n    function descendants(t: ParseTree): ParseTree[];\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/Trees.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Token from '../Token.js';\nimport ErrorNode from './ErrorNode.js';\nimport TerminalNode from './TerminalNode.js';\nimport RuleNode from './RuleNode.js';\nimport escapeWhitespace from \"../utils/escapeWhitespace.js\";\n\n/** A set of utility routines useful for all kinds of ANTLR trees. */\nconst Trees = {\n    /**\n     * Print out a whole tree in LISP form. {@link //getNodeText} is used on the\n     *  node payloads to get the text for the nodes.  Detect\n     *  parse trees and extract data appropriately.\n     */\n    toStringTree: function(tree, ruleNames, recog) {\n        ruleNames = ruleNames || null;\n        recog = recog || null;\n        if(recog!==null) {\n            ruleNames = recog.ruleNames;\n        }\n        let s = Trees.getNodeText(tree, ruleNames);\n        s = escapeWhitespace(s, false);\n        const c = tree.getChildCount();\n        if(c===0) {\n            return s;\n        }\n        let res = \"(\" + s + ' ';\n        if(c>0) {\n            s = Trees.toStringTree(tree.getChild(0), ruleNames);\n            res = res.concat(s);\n        }\n        for(let i=1;i<c;i++) {\n            s = Trees.toStringTree(tree.getChild(i), ruleNames);\n            res = res.concat(' ' + s);\n        }\n        res = res.concat(\")\");\n        return res;\n    },\n\n    getNodeText: function(t, ruleNames, recog) {\n        ruleNames = ruleNames || null;\n        recog = recog || null;\n        if(recog!==null) {\n            ruleNames = recog.ruleNames;\n        }\n        if(ruleNames!==null) {\n            if (t instanceof RuleNode) {\n                const context = t.ruleContext;\n                const altNumber = context.getAltNumber();\n                // use const value of ATN.INVALID_ALT_NUMBER to avoid circular dependency\n                if ( altNumber != 0 ) {\n                    return ruleNames[t.ruleIndex]+\":\"+altNumber;\n                }\n                return ruleNames[t.ruleIndex];\n            } else if ( t instanceof ErrorNode) {\n                return t.toString();\n            } else if(t instanceof TerminalNode) {\n                if(t.symbol!==null) {\n                    return t.symbol.text;\n                }\n            }\n        }\n        // no recog for rule names\n        const payload = t.getPayload();\n        if (payload instanceof Token ) {\n            return payload.text;\n        }\n        return t.getPayload().toString();\n    },\n\n    /**\n     * Return ordered list of all children of this node\n     */\n    getChildren: function(t) {\n        const list = [];\n        for(let i=0;i<t.getChildCount();i++) {\n            list.push(t.getChild(i));\n        }\n        return list;\n    },\n\n    /**\n     * Return a list of all ancestors of this node.  The first node of\n     * list is the root and the last is the parent of this node.\n     */\n    getAncestors: function(t) {\n        let ancestors = [];\n        t = t.getParent();\n        while(t!==null) {\n            ancestors = [t].concat(ancestors);\n            t = t.getParent();\n        }\n        return ancestors;\n    },\n\n    findAllTokenNodes: function(t, ttype) {\n        return Trees.findAllNodes(t, ttype, true);\n    },\n\n    findAllRuleNodes: function(t, ruleIndex) {\n        return Trees.findAllNodes(t, ruleIndex, false);\n    },\n\n    findAllNodes: function(t, index, findTokens) {\n        const nodes = [];\n        Trees._findAllNodes(t, index, findTokens, nodes);\n        return nodes;\n    },\n\n    _findAllNodes: function(t, index, findTokens, nodes) {\n        // check this node (the root) first\n        if(findTokens && (t instanceof TerminalNode)) {\n            if(t.symbol.type===index) {\n                nodes.push(t);\n            }\n        } else if(!findTokens && (t instanceof RuleNode)) {\n            if(t.ruleIndex===index) {\n                nodes.push(t);\n            }\n        }\n        // check children\n        for(let i=0;i<t.getChildCount();i++) {\n            Trees._findAllNodes(t.getChild(i), index, findTokens, nodes);\n        }\n    },\n\n    descendants: function(t) {\n        let nodes = [t];\n        for(let i=0;i<t.getChildCount();i++) {\n            nodes = nodes.concat(Trees.descendants(t.getChild(i)));\n        }\n        return nodes;\n    }\n}\n\nexport default Trees;\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/index.d.ts",
    "content": "export * from \"./RuleNode.js\";\nexport * from \"./ErrorNode.js\";\nexport * from \"./TerminalNode.js\";\nexport * from \"./ParseTree.js\";\nexport * from \"./ParseTreeListener.js\";\nexport * from \"./ParseTreeVisitor.js\";\nexport * from \"./ParseTreeWalker.js\";\nexport * as Trees from \"./Trees.js\";\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/tree/index.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport RuleNode from './RuleNode.js';\nimport ErrorNode from './ErrorNode.js';\nimport TerminalNode from './TerminalNode.js';\nimport ParseTreeListener from './ParseTreeListener.js';\nimport ParseTreeVisitor from './ParseTreeVisitor.js';\nimport ParseTreeWalker from './ParseTreeWalker.js';\nimport { default as Trees } from './Trees.js';\n\nexport default { Trees, RuleNode, ErrorNode, TerminalNode, ParseTreeListener, ParseTreeVisitor, ParseTreeWalker }\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/DoubleDict.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport HashMap from \"../misc/HashMap.js\";\n\nexport default class DoubleDict {\n\n    constructor(defaultMapCtor) {\n        this.defaultMapCtor = defaultMapCtor || HashMap;\n        this.cacheMap = new this.defaultMapCtor();\n    }\n\n    get(a, b) {\n        const d = this.cacheMap.get(a) || null;\n        return d === null ? null : (d.get(b) || null);\n    }\n\n    set(a, b, o) {\n        let d = this.cacheMap.get(a) || null;\n        if (d === null) {\n            d = new this.defaultMapCtor();\n            this.cacheMap.set(a, d);\n        }\n        d.set(b, o);\n    }\n\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/Printer.d.ts",
    "content": "export declare abstract class Printer {\n    print(s: string) : void;\n    println(s: string) : void;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/arrayToString.d.ts",
    "content": "export declare function arrayToString(value: any[]) : string;\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/arrayToString.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport valueToString from \"./valueToString.js\";\n\nexport default function arrayToString(a) {\n    return Array.isArray(a) ? (\"[\" + a.map(valueToString).join(\", \") + \"]\") : \"null\";\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/equalArrays.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default function equalArrays(a, b) {\n    if (!Array.isArray(a) || !Array.isArray(b))\n        return false;\n    if (a === b)\n        return true;\n    if (a.length !== b.length)\n        return false;\n    for (let i = 0; i < a.length; i++) {\n        if (a[i] === b[i])\n            continue;\n        if (!a[i].equals || !a[i].equals(b[i]))\n            return false;\n    }\n    return true;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/escapeWhitespace.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default function escapeWhitespace(s, escapeSpaces) {\n    s = s.replace(/\\t/g, \"\\\\t\")\n        .replace(/\\n/g, \"\\\\n\")\n        .replace(/\\r/g, \"\\\\r\");\n    if (escapeSpaces) {\n        s = s.replace(/ /g, \"\\u00B7\");\n    }\n    return s;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/index.d.ts",
    "content": "export * from \"./stringToCharArray.js\";\nexport * from \"./arrayToString.js\";\nexport * from \"./Printer.js\";\n\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/index.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport arrayToString from \"./arrayToString.js\";\nimport stringToCharArray from \"./stringToCharArray.js\";\n\nexport default { arrayToString, stringToCharArray };\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/standardEqualsFunction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default function standardEqualsFunction(a, b) {\n    return a && a.equals ? a.equals(b) : a===b;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/standardHashCodeFunction.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport { stringHashCode } from \"./stringHashCode.js\";\n\nexport default function standardHashCodeFunction(a) {\n    return a ? typeof a === 'string' ? stringHashCode(a) : a.hashCode() : -1;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/stringHashCode.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nexport const StringSeedHashCode = Math.round(Math.random() * Math.pow(2, 32));\n\nexport function stringHashCode (value) {\n    if (!value) {\n        return 0;\n    }\n    const type = typeof value;\n    const key = type === 'string' ? value : type === 'object' && value.toString ? value.toString() : false;\n    if (!key) {\n        return 0;\n    }\n    let h1b, k1;\n\n    const remainder = key.length & 3; // key.length % 4\n    const bytes = key.length - remainder;\n    let h1 = StringSeedHashCode;\n    const c1 = 0xcc9e2d51;\n    const c2 = 0x1b873593;\n    let i = 0;\n\n    while (i < bytes) {\n        k1 =\n            ((key.charCodeAt(i) & 0xff)) |\n            ((key.charCodeAt(++i) & 0xff) << 8) |\n            ((key.charCodeAt(++i) & 0xff) << 16) |\n            ((key.charCodeAt(++i) & 0xff) << 24);\n        ++i;\n\n        k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;\n        k1 = (k1 << 15) | (k1 >>> 17);\n        k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;\n\n        h1 ^= k1;\n        h1 = (h1 << 13) | (h1 >>> 19);\n        h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;\n        h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));\n    }\n\n    k1 = 0;\n\n    switch (remainder) {\n        case 3:\n            k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n        // no-break\n        case 2:\n            k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n        // no-break\n        case 1:\n            k1 ^= (key.charCodeAt(i) & 0xff);\n            k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;\n            k1 = (k1 << 15) | (k1 >>> 17);\n            k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;\n            h1 ^= k1;\n    }\n\n    h1 ^= key.length;\n\n    h1 ^= h1 >>> 16;\n    h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;\n    h1 ^= h1 >>> 13;\n    h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;\n    h1 ^= h1 >>> 16;\n\n    return h1 >>> 0;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/stringToCharArray.d.ts",
    "content": "export declare function stringToCharArray(str: string) : Uint16Array;\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/stringToCharArray.js",
    "content": "export default function stringToCharArray(str) {\n    let result = new Uint16Array(str.length);\n    for (let i = 0; i < str.length; i++) {\n        result[i] = str.charCodeAt(i);\n    }\n    return result;\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/titleCase.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default function titleCase(str) {\n    return str.replace(/\\w\\S*/g, function (txt) {\n        return txt.charAt(0).toUpperCase() + txt.substr(1);\n    });\n}\n"
  },
  {
    "path": "runtime/JavaScript/src/antlr4/utils/valueToString.js",
    "content": "/* Copyright (c) 2012-2022 The ANTLR Project Contributors. All rights reserved.\n * Use is of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nexport default function valueToString(v) {\n    return v === null ? \"null\" : v;\n}\n"
  },
  {
    "path": "runtime/JavaScript/test-builds.sh",
    "content": "#!/usr/bin/env bash\n\ncd spec/imports/builds/node-esm-ts\nnpm run test\ncd ../node-cjs-ts\nnpm run test"
  },
  {
    "path": "runtime/JavaScript/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES6\",\n    \"module\": \"ES2020\",\n    \"moduleResolution\": \"Node\",\n    \"sourceMap\": true,\n    \"esModuleInterop\":true,\n    \"lib\": [\n      \"ES2020\"\n    ],\n    \"noImplicitAny\": true,\n    \"strictNullChecks\": true,\n    \"preserveConstEnums\": true,\n    \"typeRoots\": [\n      \"./node_modules/@types\"\n    ],\n    \"types\": [\n      \"node\"\n    ],\n  },\n  \"include\": [\n    \"**/*.d.ts\"\n  ],\n  \"exclude\": [\n    \"node_modules\"\n  ]\n}\n"
  },
  {
    "path": "runtime/JavaScript/webpack.config.js",
    "content": "import path from 'path';\nimport ESLintPlugin from 'eslint-webpack-plugin';\nimport {fileURLToPath} from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n\nconst buildConfig = ( platform, extensions ) => ({\n    mode: \"production\",\n    entry: `./src/antlr4/index.${platform}.js`,\n    output: {\n        path: path.resolve(__dirname, 'dist'),\n        filename: `antlr4.${platform}.${extensions}`,\n        chunkFormat: extensions === \"mjs\" ? \"module\" : \"commonjs\",\n        library: {\n            type: extensions === \"mjs\" ? \"module\" : \"commonjs\"\n        }\n    },\n\n    ...(platform === 'web' && {\n        module: {\n            rules: [{\n                test: /\\.js$/,\n                exclude: [ /node_modules/, path.resolve(__dirname, \"src/FileStream.js\") ],\n                use: [ 'babel-loader' ]\n            }]\n        },\n        performance: {\n            maxAssetSize: 512000,\n            maxEntrypointSize: 512000\n        },\n        resolve: {\n            extensions: [ '.js'],\n            fallback: {\n                fs: false\n            }\n        },\n    }),\n\n    ...(platform === 'node' && {\n        module: {\n            rules: [{\n                test: /\\.js$/,\n                exclude: /node_modules/,\n                use: [ 'babel-loader' ]\n            }]\n        },\n        resolve: {\n            extensions: [ '.js'],\n        },\n    }),\n    target: platform,\n    plugins: [ new ESLintPlugin() ],\n    devtool: \"source-map\",\n    experiments: {\n        outputModule: extensions === \"mjs\"\n    },\n})\n\n\nexport default [\n    buildConfig(\"node\", \"cjs\"),\n    buildConfig(\"node\", \"mjs\"),\n    buildConfig(\"web\", \"cjs\"),\n    buildConfig(\"web\", \"mjs\"),\n];\n"
  },
  {
    "path": "runtime/Python3/MANIFEST.in",
    "content": "include *.txt\nrecursive-include test *.py *.c\n"
  },
  {
    "path": "runtime/Python3/README.txt",
    "content": "This is the Python 3.4 runtime for ANTLR.\nVisit the ANTLR web sites for more information:\nhttp://www.antlr.org\nhttps://raw.githubusercontent.com/antlr/antlr4/master/doc/python-target.md\n"
  },
  {
    "path": "runtime/Python3/RELEASE-4.5.txt",
    "content": "What's in this release?\n\n - fixed bug where non-ascii input streams would fail\n - added support for visitor pattern\n - added support for wildcards in grammar\n\n Breaking change:\n\n In version 4.4, the parser/lexer had a tokenNames member.\n This has been removed in favor of the following members:\n  - lexicalNames, containing the parsed text\n  - symbolicNames, corresponding to tokenNames\n"
  },
  {
    "path": "runtime/Python3/pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools>=61.2\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"antlr4-python3-runtime\"\nversion = \"4.13.2\"\nauthors = [{name = \"Eric Vergnaud\", email = \"eric.vergnaud@wanadoo.fr\"}, {name = \"Terence Parr\"}, {name = \"Sam Harwell\"}]\nlicense = {text = \"BSD\"}\ndescription = \"ANTLR 4.13.2 runtime for Python 3\"\nurls = {Homepage = \"http://www.antlr.org\"}\ndependencies = [\"typing ; python_version<'3.5'\"]\n\n[project.scripts]\npygrun = \"antlr4._pygrun:main\"\n\n[tool.setuptools]\npackage-dir = {\"\" = \"src\"}\ninclude-package-data = false\n\n[tool.setuptools.packages.find]\ninclude = [\"antlr4\", \"antlr4.*\"]\nwhere = [\"src\"]\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/BufferedTokenStream.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n\n# This implementation of {@link TokenStream} loads tokens from a\n# {@link TokenSource} on-demand, and places the tokens in a buffer to provide\n# access to any previous token by index.\n#\n# <p>\n# This token stream ignores the value of {@link Token#getChannel}. If your\n# parser requires the token stream filter tokens to only those on a particular\n# channel, such as {@link Token#DEFAULT_CHANNEL} or\n# {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a\n# {@link CommonTokenStream}.</p>\nfrom io import StringIO\nfrom .Token import Token\nfrom .error.Errors import IllegalStateException\n\n# need forward declaration\nLexer = None\n\n# this is just to keep meaningful parameter types to Parser\nclass TokenStream(object):\n\n    pass\n\n\nclass BufferedTokenStream(TokenStream):\n    __slots__ = ('tokenSource', 'tokens', 'index', 'fetchedEOF')\n\n    def __init__(self, tokenSource:Lexer):\n        # The {@link TokenSource} from which tokens for this stream are fetched.\n        self.tokenSource = tokenSource\n\n        # A collection of all tokens fetched from the token source. The list is\n        # considered a complete view of the input once {@link #fetchedEOF} is set\n        # to {@code true}.\n        self.tokens = []\n\n        # The index into {@link #tokens} of the current token (next token to\n        # {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be\n        # {@link #LT LT(1)}.\n        #\n        # <p>This field is set to -1 when the stream is first constructed or when\n        # {@link #setTokenSource} is called, indicating that the first token has\n        # not yet been fetched from the token source. For additional information,\n        # see the documentation of {@link IntStream} for a description of\n        # Initializing Methods.</p>\n        self.index = -1\n\n        # Indicates whether the {@link Token#EOF} token has been fetched from\n        # {@link #tokenSource} and added to {@link #tokens}. This field improves\n        # performance for the following cases:\n        #\n        # <ul>\n        # <li>{@link #consume}: The lookahead check in {@link #consume} to prevent\n        # consuming the EOF symbol is optimized by checking the values of\n        # {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li>\n        # <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into\n        # {@link #tokens} is trivial with this field.</li>\n        # <ul>\n        self.fetchedEOF = False\n\n    def mark(self):\n        return 0\n\n    def release(self, marker:int):\n        # no resources to release\n        pass\n\n    def reset(self):\n        self.seek(0)\n\n    def seek(self, index:int):\n        self.lazyInit()\n        self.index = self.adjustSeekIndex(index)\n\n    def get(self, index:int):\n        self.lazyInit()\n        return self.tokens[index]\n\n    def consume(self):\n        skipEofCheck = False\n        if self.index >= 0:\n            if self.fetchedEOF:\n                # the last token in tokens is EOF. skip check if p indexes any\n                # fetched token except the last.\n                skipEofCheck = self.index < len(self.tokens) - 1\n            else:\n               # no EOF token in tokens. skip check if p indexes a fetched token.\n                skipEofCheck = self.index < len(self.tokens)\n        else:\n            # not yet initialized\n            skipEofCheck = False\n\n        if not skipEofCheck and self.LA(1) == Token.EOF:\n            raise IllegalStateException(\"cannot consume EOF\")\n\n        if self.sync(self.index + 1):\n            self.index = self.adjustSeekIndex(self.index + 1)\n\n    # Make sure index {@code i} in tokens has a token.\n    #\n    # @return {@code true} if a token is located at index {@code i}, otherwise\n    #    {@code false}.\n    # @see #get(int i)\n    #/\n    def sync(self, i:int):\n        n = i - len(self.tokens) + 1 # how many more elements we need?\n        if n > 0 :\n            fetched = self.fetch(n)\n            return fetched >= n\n        return True\n\n    # Add {@code n} elements to buffer.\n    #\n    # @return The actual number of elements added to the buffer.\n    #/\n    def fetch(self, n:int):\n        if self.fetchedEOF:\n            return 0\n        for i in range(0, n):\n            t = self.tokenSource.nextToken()\n            t.tokenIndex = len(self.tokens)\n            self.tokens.append(t)\n            if t.type==Token.EOF:\n                self.fetchedEOF = True\n                return i + 1\n        return n\n\n\n    # Get all tokens from start..stop inclusively#/\n    def getTokens(self, start:int, stop:int, types:set=None):\n        if start<0 or stop<0:\n            return None\n        self.lazyInit()\n        subset = []\n        if stop >= len(self.tokens):\n            stop = len(self.tokens)-1\n        for i in range(start, stop):\n            t = self.tokens[i]\n            if t.type==Token.EOF:\n                break\n            if types is None or t.type in types:\n                subset.append(t)\n        return subset\n\n    def LA(self, i:int):\n        return self.LT(i).type\n\n    def LB(self, k:int):\n        if (self.index-k) < 0:\n            return None\n        return self.tokens[self.index-k]\n\n    def LT(self, k:int):\n        self.lazyInit()\n        if k==0:\n            return None\n        if k < 0:\n            return self.LB(-k)\n        i = self.index + k - 1\n        self.sync(i)\n        if i >= len(self.tokens): # return EOF token\n            # EOF must be last token\n            return self.tokens[len(self.tokens)-1]\n        return self.tokens[i]\n\n    # Allowed derived classes to modify the behavior of operations which change\n    # the current stream position by adjusting the target token index of a seek\n    # operation. The default implementation simply returns {@code i}. If an\n    # exception is thrown in this method, the current stream index should not be\n    # changed.\n    #\n    # <p>For example, {@link CommonTokenStream} overrides this method to ensure that\n    # the seek target is always an on-channel token.</p>\n    #\n    # @param i The target token index.\n    # @return The adjusted target token index.\n\n    def adjustSeekIndex(self, i:int):\n        return i\n\n    def lazyInit(self):\n        if self.index == -1:\n            self.setup()\n\n    def setup(self):\n        self.sync(0)\n        self.index = self.adjustSeekIndex(0)\n\n    # Reset this token stream by setting its token source.#/\n    def setTokenSource(self, tokenSource:Lexer):\n        self.tokenSource = tokenSource\n        self.tokens = []\n        self.index = -1\n        self.fetchedEOF = False\n\n\n    # Given a starting index, return the index of the next token on channel.\n    #  Return i if tokens[i] is on channel.  Return the index of the EOF token\n    # if there are no tokens on channel between i and EOF.\n    #/\n    def nextTokenOnChannel(self, i:int, channel:int):\n        self.sync(i)\n        if i>=len(self.tokens):\n            return len(self.tokens) - 1\n        token = self.tokens[i]\n        while token.channel!=channel:\n            if token.type==Token.EOF:\n                return i\n            i += 1\n            self.sync(i)\n            token = self.tokens[i]\n        return i\n\n    # Given a starting index, return the index of the previous token on channel.\n    #  Return i if tokens[i] is on channel. Return -1 if there are no tokens\n    #  on channel between i and 0.\n    def previousTokenOnChannel(self, i:int, channel:int):\n        while i>=0 and self.tokens[i].channel!=channel:\n            i -= 1\n        return i\n\n    # Collect all tokens on specified channel to the right of\n    #  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or\n    #  EOF. If channel is -1, find any non default channel token.\n    def getHiddenTokensToRight(self, tokenIndex:int, channel:int=-1):\n        self.lazyInit()\n        if tokenIndex<0 or tokenIndex>=len(self.tokens):\n            raise Exception(str(tokenIndex) + \" not in 0..\" + str(len(self.tokens)-1))\n        from .Lexer import Lexer\n        nextOnChannel = self.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL)\n        from_ = tokenIndex+1\n        # if none onchannel to right, nextOnChannel=-1 so set to = last token\n        to = (len(self.tokens)-1) if nextOnChannel==-1 else nextOnChannel\n        return self.filterForChannel(from_, to, channel)\n\n\n    # Collect all tokens on specified channel to the left of\n    #  the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n    #  If channel is -1, find any non default channel token.\n    def getHiddenTokensToLeft(self, tokenIndex:int, channel:int=-1):\n        self.lazyInit()\n        if tokenIndex<0 or tokenIndex>=len(self.tokens):\n            raise Exception(str(tokenIndex) + \" not in 0..\" + str(len(self.tokens)-1))\n        from .Lexer import Lexer\n        prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL)\n        if prevOnChannel == tokenIndex - 1:\n            return None\n        # if none on channel to left, prevOnChannel=-1 then from=0\n        from_ = prevOnChannel+1\n        to = tokenIndex-1\n        return self.filterForChannel(from_, to, channel)\n\n\n    def filterForChannel(self, left:int, right:int, channel:int):\n        hidden = []\n        for i in range(left, right+1):\n            t = self.tokens[i]\n            if channel==-1:\n                from .Lexer import Lexer\n                if t.channel!= Lexer.DEFAULT_TOKEN_CHANNEL:\n                    hidden.append(t)\n            elif t.channel==channel:\n                    hidden.append(t)\n        if len(hidden)==0:\n            return None\n        return hidden\n\n    def getSourceName(self):\n        return self.tokenSource.getSourceName()\n\n    # Get the text of all tokens in this buffer.#/\n    def getText(self, start:int=None, stop:int=None):\n        self.lazyInit()\n        self.fill()\n        if isinstance(start, Token):\n            start = start.tokenIndex\n        elif start is None:\n            start = 0\n        if isinstance(stop, Token):\n            stop = stop.tokenIndex\n        elif stop is None or stop >= len(self.tokens):\n            stop = len(self.tokens) - 1\n        if start < 0 or stop < 0 or stop < start:\n            return \"\"\n        with StringIO() as buf:\n            for i in range(start, stop+1):\n                t = self.tokens[i]\n                if t.type==Token.EOF:\n                    break\n                buf.write(t.text)\n            return buf.getvalue()\n\n\n    # Get all tokens from lexer until EOF#/\n    def fill(self):\n        self.lazyInit()\n        while self.fetch(1000)==1000:\n            pass\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/CommonTokenFactory.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# This default implementation of {@link TokenFactory} creates\n# {@link CommonToken} objects.\n#\nfrom .Token import CommonToken\n\nclass TokenFactory(object):\n\n    pass\n\nclass CommonTokenFactory(TokenFactory):\n    __slots__ = 'copyText'\n\n    #\n    # The default {@link CommonTokenFactory} instance.\n    #\n    # <p>\n    # This token factory does not explicitly copy token text when constructing\n    # tokens.</p>\n    #\n    DEFAULT = None\n\n    def __init__(self, copyText:bool=False):\n        # Indicates whether {@link CommonToken#setText} should be called after\n        # constructing tokens to explicitly set the text. This is useful for cases\n        # where the input stream might not be able to provide arbitrary substrings\n        # of text from the input after the lexer creates a token (e.g. the\n        # implementation of {@link CharStream#getText} in\n        # {@link UnbufferedCharStream} throws an\n        # {@link UnsupportedOperationException}). Explicitly setting the token text\n        # allows {@link Token#getText} to be called at any time regardless of the\n        # input stream implementation.\n        #\n        # <p>\n        # The default value is {@code false} to avoid the performance and memory\n        # overhead of copying text for every token unless explicitly requested.</p>\n        #\n        self.copyText = copyText\n\n    def create(self, source, type:int, text:str, channel:int, start:int, stop:int, line:int, column:int):\n        t = CommonToken(source, type, channel, start, stop)\n        t.line = line\n        t.column = column\n        if text is not None:\n            t.text = text\n        elif self.copyText and source[1] is not None:\n            t.text = source[1].getText(start,stop)\n        return t\n\n    def createThin(self, type:int, text:str):\n        t = CommonToken(type=type)\n        t.text = text\n        return t\n\nCommonTokenFactory.DEFAULT = CommonTokenFactory()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/CommonTokenStream.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n#\n# This class extends {@link BufferedTokenStream} with functionality to filter\n# token streams to tokens on a particular channel (tokens where\n# {@link Token#getChannel} returns a particular value).\n#\n# <p>\n# This token stream provides access to all tokens by index or when calling\n# methods like {@link #getText}. The channel filtering is only used for code\n# accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and\n# {@link #LB}.</p>\n#\n# <p>\n# By default, tokens are placed on the default channel\n# ({@link Token#DEFAULT_CHANNEL}), but may be reassigned by using the\n# {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to\n# call {@link Lexer#setChannel}.\n# </p>\n#\n# <p>\n# Note: lexer rules which use the {@code ->skip} lexer command or call\n# {@link Lexer#skip} do not produce tokens at all, so input text matched by\n# such a rule will not be available as part of the token stream, regardless of\n# channel.</p>\n#/\n\nfrom .BufferedTokenStream import BufferedTokenStream\nfrom .Lexer import Lexer\nfrom .Token import Token\n\n\nclass CommonTokenStream(BufferedTokenStream):\n    __slots__ = 'channel'\n\n    def __init__(self, lexer:Lexer, channel:int=Token.DEFAULT_CHANNEL):\n        super().__init__(lexer)\n        self.channel = channel\n\n    def adjustSeekIndex(self, i:int):\n        return self.nextTokenOnChannel(i, self.channel)\n\n    def LB(self, k:int):\n        if k==0 or (self.index-k)<0:\n            return None\n        i = self.index\n        n = 1\n        # find k good tokens looking backwards\n        while n <= k:\n            # skip off-channel tokens\n            i = self.previousTokenOnChannel(i - 1, self.channel)\n            n += 1\n        if i < 0:\n            return None\n        return self.tokens[i]\n\n    def LT(self, k:int):\n        self.lazyInit()\n        if k == 0:\n            return None\n        if k < 0:\n            return self.LB(-k)\n        i = self.index\n        n = 1 # we know tokens[pos] is a good one\n        # find k good tokens\n        while n < k:\n            # skip off-channel tokens, but make sure to not look past EOF\n            if self.sync(i + 1):\n                i = self.nextTokenOnChannel(i + 1, self.channel)\n            n += 1\n        return self.tokens[i]\n\n    # Count EOF just once.#/\n    def getNumberOfOnChannelTokens(self):\n        n = 0\n        self.fill()\n        for i in range(0, len(self.tokens)):\n            t = self.tokens[i]\n            if t.channel==self.channel:\n                n += 1\n            if t.type==Token.EOF:\n                break\n        return n\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/FileStream.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n#  This is an InputStream that is loaded from a file all at once\n#  when you construct the object.\n#\n\nimport codecs\nfrom .InputStream import InputStream\n\n\nclass FileStream(InputStream):\n    __slots__ = 'fileName'\n\n    def __init__(self, fileName:str, encoding:str='ascii', errors:str='strict'):\n        super().__init__(self.readDataFrom(fileName, encoding, errors))\n        self.fileName = fileName\n\n    def readDataFrom(self, fileName:str, encoding:str, errors:str='strict'):\n        # read binary to avoid line ending conversion\n        with open(fileName, 'rb') as file:\n            bytes = file.read()\n            return codecs.decode(bytes, encoding, errors)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/InputStream.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n\n#\n#  Vacuum all input from a string and then treat it like a buffer.\n#\nfrom .Token import Token\n\n\nclass InputStream (object):\n    __slots__ = ('name', 'strdata', '_index', 'data', '_size')\n\n    def __init__(self, data: str):\n        self.name = \"<empty>\"\n        self.strdata = data\n        self._loadString()\n\n    def _loadString(self):\n        self._index = 0\n        self.data = [ord(c) for c in self.strdata]\n        self._size = len(self.data)\n\n    @property\n    def index(self):\n        return self._index\n\n    @property\n    def size(self):\n        return self._size\n\n    # Reset the stream so that it's in the same state it was\n    #  when the object was created *except* the data array is not\n    #  touched.\n    #\n    def reset(self):\n        self._index = 0\n\n    def consume(self):\n        if self._index >= self._size:\n            assert self.LA(1) == Token.EOF\n            raise Exception(\"cannot consume EOF\")\n        self._index += 1\n\n    def LA(self, offset: int):\n        if offset==0:\n            return 0 # undefined\n        if offset<0:\n            offset += 1 # e.g., translate LA(-1) to use offset=0\n        pos = self._index + offset - 1\n        if pos < 0 or pos >= self._size: # invalid\n            return Token.EOF\n        return self.data[pos]\n\n    def LT(self, offset: int):\n        return self.LA(offset)\n\n    # mark/release do nothing; we have entire buffer\n    def mark(self):\n        return -1\n\n    def release(self, marker: int):\n        pass\n\n    # consume() ahead until p==_index; can't just set p=_index as we must\n    # update line and column. If we seek backwards, just set p\n    #\n    def seek(self, _index: int):\n        if _index<=self._index:\n            self._index = _index # just jump; don't update stream state (line, ...)\n            return\n        # seek forward\n        self._index = min(_index, self._size)\n\n    def getText(self, start :int, stop: int):\n        if stop >= self._size:\n            stop = self._size-1\n        if start >= self._size:\n            return \"\"\n        else:\n            return self.strdata[start:stop+1]\n\n    def __str__(self):\n        return self.strdata\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/IntervalSet.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\nfrom io import StringIO\nfrom .Token import Token\n\n# need forward declarations\nIntervalSet = None\n\nclass IntervalSet(object):\n    __slots__ = ('intervals', 'readonly')\n\n    def __init__(self):\n        self.intervals = None\n        self.readonly = False\n\n    def __iter__(self):\n        if self.intervals is not None:\n            for i in self.intervals:\n                for c in i:\n                    yield c\n\n    def __getitem__(self, item):\n        i = 0\n        for k in self:\n            if i==item:\n                return k\n            else:\n                i += 1\n        return Token.INVALID_TYPE\n\n    def addOne(self, v:int):\n        self.addRange(range(v, v+1))\n\n    def addRange(self, v:range):\n        if self.intervals is None:\n            self.intervals = list()\n            self.intervals.append(v)\n        else:\n            # find insert pos\n            k = 0\n            for i in self.intervals:\n                # distinct range -> insert\n                if v.stop<i.start:\n                    self.intervals.insert(k, v)\n                    return\n                # contiguous range -> adjust\n                elif v.stop==i.start:\n                    self.intervals[k] = range(v.start, i.stop)\n                    return\n                # overlapping range -> adjust and reduce\n                elif v.start<=i.stop:\n                    self.intervals[k] = range(min(i.start,v.start), max(i.stop,v.stop))\n                    self.reduce(k)\n                    return\n                k += 1\n            # greater than any existing\n            self.intervals.append(v)\n\n    def addSet(self, other:IntervalSet):\n        if other.intervals is not None:\n            for i in other.intervals:\n                self.addRange(i)\n        return self\n\n    def reduce(self, k:int):\n        # only need to reduce if k is not the last\n        if k<len(self.intervals)-1:\n            l = self.intervals[k]\n            r = self.intervals[k+1]\n            # if r contained in l\n            if l.stop >= r.stop:\n                self.intervals.pop(k+1)\n                self.reduce(k)\n            elif l.stop >= r.start:\n                self.intervals[k] = range(l.start, r.stop)\n                self.intervals.pop(k+1)\n\n    def complement(self, start, stop):\n        result = IntervalSet()\n        result.addRange(range(start,stop+1))\n        for i in self.intervals:\n            result.removeRange(i)\n        return result\n\n    def __contains__(self, item):\n        if self.intervals is None:\n            return False\n        else:\n            return any(item in i for i in self.intervals)\n\n    def __len__(self):\n        return sum(len(i) for i in self.intervals)\n\n    def removeRange(self, v):\n        if v.start==v.stop-1:\n            self.removeOne(v.start)\n        elif self.intervals is not None:\n            k = 0\n            for i in self.intervals:\n                # intervals are ordered\n                if v.stop<=i.start:\n                    return\n                # check for including range, split it\n                elif v.start>i.start and v.stop<i.stop:\n                    self.intervals[k] = range(i.start, v.start)\n                    x = range(v.stop, i.stop)\n                    self.intervals.insert(k, x)\n                    return\n                # check for included range, remove it\n                elif v.start<=i.start and v.stop>=i.stop:\n                    self.intervals.pop(k)\n                    k -= 1  # need another pass\n                # check for lower boundary\n                elif v.start<i.stop:\n                    self.intervals[k] = range(i.start, v.start)\n                # check for upper boundary\n                elif v.stop<i.stop:\n                    self.intervals[k] = range(v.stop, i.stop)\n                k += 1\n\n    def removeOne(self, v):\n        if self.intervals is not None:\n            k = 0\n            for i in self.intervals:\n                # intervals is ordered\n                if v<i.start:\n                    return\n                # check for single value range\n                elif v==i.start and v==i.stop-1:\n                    self.intervals.pop(k)\n                    return\n                # check for lower boundary\n                elif v==i.start:\n                    self.intervals[k] = range(i.start+1, i.stop)\n                    return\n                # check for upper boundary\n                elif v==i.stop-1:\n                    self.intervals[k] = range(i.start, i.stop-1)\n                    return\n                # split existing range\n                elif v<i.stop-1:\n                    x = range(i.start, v)\n                    self.intervals[k] = range(v + 1, i.stop)\n                    self.intervals.insert(k, x)\n                    return\n                k += 1\n\n\n    def toString(self, literalNames:list, symbolicNames:list):\n        if self.intervals is None:\n            return \"{}\"\n        with StringIO() as buf:\n            if len(self)>1:\n                buf.write(\"{\")\n            first = True\n            for i in self.intervals:\n                for j in i:\n                    if not first:\n                        buf.write(\", \")\n                    buf.write(self.elementName(literalNames, symbolicNames, j))\n                    first = False\n            if len(self)>1:\n                buf.write(\"}\")\n            return buf.getvalue()\n\n    def elementName(self, literalNames:list, symbolicNames:list, a:int):\n        if a==Token.EOF:\n            return \"<EOF>\"\n        elif a==Token.EPSILON:\n            return \"<EPSILON>\"\n        else:\n            if a<len(literalNames) and literalNames[a] != \"<INVALID>\":\n                return literalNames[a]\n            if a<len(symbolicNames):\n                return symbolicNames[a]\n            return \"<UNKNOWN>\"\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/LL1Analyzer.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\nfrom .IntervalSet import IntervalSet\nfrom .Token import Token\nfrom .PredictionContext import PredictionContext, SingletonPredictionContext, PredictionContextFromRuleContext\nfrom .RuleContext import RuleContext\nfrom .atn.ATN import ATN\nfrom .atn.ATNConfig import ATNConfig\nfrom .atn.ATNState import ATNState, RuleStopState\nfrom .atn.Transition import WildcardTransition, NotSetTransition, AbstractPredicateTransition, RuleTransition\n\n\nclass LL1Analyzer (object):\n    __slots__ = 'atn'\n\n    #* Special value added to the lookahead sets to indicate that we hit\n    #  a predicate during analysis if {@code seeThruPreds==false}.\n    #/\n    HIT_PRED = Token.INVALID_TYPE\n\n    def __init__(self, atn:ATN):\n        self.atn = atn\n\n    #*\n    # Calculates the SLL(1) expected lookahead set for each outgoing transition\n    # of an {@link ATNState}. The returned array has one element for each\n    # outgoing transition in {@code s}. If the closure from transition\n    # <em>i</em> leads to a semantic predicate before matching a symbol, the\n    # element at index <em>i</em> of the result will be {@code null}.\n    #\n    # @param s the ATN state\n    # @return the expected symbols for each outgoing transition of {@code s}.\n    #/\n    def getDecisionLookahead(self, s:ATNState):\n        if s is None:\n            return None\n\n        count = len(s.transitions)\n        look = [] * count\n        for alt in range(0, count):\n            look[alt] = set()\n            lookBusy = set()\n            seeThruPreds = False # fail to get lookahead upon pred\n            self._LOOK(s.transition(alt).target, None, PredictionContext.EMPTY,\n                  look[alt], lookBusy, set(), seeThruPreds, False)\n            # Wipe out lookahead for this alternative if we found nothing\n            # or we had a predicate when we !seeThruPreds\n            if len(look[alt])==0 or self.HIT_PRED in look[alt]:\n                look[alt] = None\n        return look\n\n    #*\n    # Compute set of tokens that can follow {@code s} in the ATN in the\n    # specified {@code ctx}.\n    #\n    # <p>If {@code ctx} is {@code null} and the end of the rule containing\n    # {@code s} is reached, {@link Token#EPSILON} is added to the result set.\n    # If {@code ctx} is not {@code null} and the end of the outermost rule is\n    # reached, {@link Token#EOF} is added to the result set.</p>\n    #\n    # @param s the ATN state\n    # @param stopState the ATN state to stop at. This can be a\n    # {@link BlockEndState} to detect epsilon paths through a closure.\n    # @param ctx the complete parser context, or {@code null} if the context\n    # should be ignored\n    #\n    # @return The set of tokens that can follow {@code s} in the ATN in the\n    # specified {@code ctx}.\n    #/\n    def LOOK(self, s:ATNState, stopState:ATNState=None, ctx:RuleContext=None):\n        r = IntervalSet()\n        seeThruPreds = True # ignore preds; get all lookahead\n        lookContext = PredictionContextFromRuleContext(s.atn, ctx) if ctx is not None else None\n        self._LOOK(s, stopState, lookContext, r, set(), set(), seeThruPreds, True)\n        return r\n\n    #*\n    # Compute set of tokens that can follow {@code s} in the ATN in the\n    # specified {@code ctx}.\n    #\n    # <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the\n    # rule containing {@code s} is reached, {@link Token#EPSILON} is added to\n    # the result set. If {@code ctx} is not {@code null} and {@code addEOF} is\n    # {@code true} and {@code stopState} or the end of the outermost rule is\n    # reached, {@link Token#EOF} is added to the result set.</p>\n    #\n    # @param s the ATN state.\n    # @param stopState the ATN state to stop at. This can be a\n    # {@link BlockEndState} to detect epsilon paths through a closure.\n    # @param ctx The outer context, or {@code null} if the outer context should\n    # not be used.\n    # @param look The result lookahead set.\n    # @param lookBusy A set used for preventing epsilon closures in the ATN\n    # from causing a stack overflow. Outside code should pass\n    # {@code new HashSet<ATNConfig>} for this argument.\n    # @param calledRuleStack A set used for preventing left recursion in the\n    # ATN from causing a stack overflow. Outside code should pass\n    # {@code new BitSet()} for this argument.\n    # @param seeThruPreds {@code true} to true semantic predicates as\n    # implicitly {@code true} and \"see through them\", otherwise {@code false}\n    # to treat semantic predicates as opaque and add {@link #HIT_PRED} to the\n    # result if one is encountered.\n    # @param addEOF Add {@link Token#EOF} to the result if the end of the\n    # outermost context is reached. This parameter has no effect if {@code ctx}\n    # is {@code null}.\n    #/\n    def _LOOK(self, s:ATNState, stopState:ATNState , ctx:PredictionContext, look:IntervalSet, lookBusy:set,\n                     calledRuleStack:set, seeThruPreds:bool, addEOF:bool):\n        c = ATNConfig(s, 0, ctx)\n\n        if c in lookBusy:\n            return\n        lookBusy.add(c)\n\n        if s == stopState:\n            if ctx is None:\n                look.addOne(Token.EPSILON)\n                return\n            elif ctx.isEmpty() and addEOF:\n                look.addOne(Token.EOF)\n                return\n\n        if isinstance(s, RuleStopState ):\n            if ctx is None:\n                look.addOne(Token.EPSILON)\n                return\n            elif ctx.isEmpty() and addEOF:\n                look.addOne(Token.EOF)\n                return\n\n            if ctx != PredictionContext.EMPTY:\n                removed = s.ruleIndex in calledRuleStack\n                try:\n                    calledRuleStack.discard(s.ruleIndex)\n                    # run thru all possible stack tops in ctx\n                    for i in range(0, len(ctx)):\n                        returnState = self.atn.states[ctx.getReturnState(i)]\n                        self._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n                finally:\n                    if removed:\n                        calledRuleStack.add(s.ruleIndex)\n                return\n\n        for t in s.transitions:\n            if type(t) == RuleTransition:\n                if t.target.ruleIndex in calledRuleStack:\n                    continue\n\n                newContext = SingletonPredictionContext.create(ctx, t.followState.stateNumber)\n\n                try:\n                    calledRuleStack.add(t.target.ruleIndex)\n                    self._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n                finally:\n                    calledRuleStack.remove(t.target.ruleIndex)\n            elif isinstance(t, AbstractPredicateTransition ):\n                if seeThruPreds:\n                    self._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n                else:\n                    look.addOne(self.HIT_PRED)\n            elif t.isEpsilon:\n                self._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)\n            elif type(t) == WildcardTransition:\n                look.addRange( range(Token.MIN_USER_TOKEN_TYPE, self.atn.maxTokenType + 1) )\n            else:\n                set_ = t.label\n                if set_ is not None:\n                    if isinstance(t, NotSetTransition):\n                        set_ = set_.complement(Token.MIN_USER_TOKEN_TYPE, self.atn.maxTokenType)\n                    look.addSet(set_)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/Lexer.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n# A lexer is recognizer that draws input symbols from a character stream.\n#  lexer grammars result in a subclass of self object. A Lexer object\n#  uses simplified match() and error recovery mechanisms in the interest\n#  of speed.\n#/\nfrom io import StringIO\n\nimport sys\nif sys.version_info >= (3, 6):\n    from typing import TextIO\nelse:\n    from typing.io import TextIO\nfrom .CommonTokenFactory import CommonTokenFactory\nfrom .atn.LexerATNSimulator import LexerATNSimulator\nfrom .InputStream import InputStream\nfrom .Recognizer import Recognizer\nfrom .Token import Token\nfrom .error.Errors import IllegalStateException, LexerNoViableAltException, RecognitionException\n\nclass TokenSource(object):\n\n    pass\n\n\nclass Lexer(Recognizer, TokenSource):\n    __slots__ = (\n        '_input', '_output', '_factory', '_tokenFactorySourcePair', '_token',\n        '_tokenStartCharIndex', '_tokenStartLine', '_tokenStartColumn',\n        '_hitEOF', '_channel', '_type', '_modeStack', '_mode', '_text'\n    )\n\n    DEFAULT_MODE = 0\n    MORE = -2\n    SKIP = -3\n\n    DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL\n    HIDDEN = Token.HIDDEN_CHANNEL\n    MIN_CHAR_VALUE = 0x0000\n    MAX_CHAR_VALUE = 0x10FFFF\n\n    def __init__(self, input:InputStream, output:TextIO = sys.stdout):\n        super().__init__()\n        self._input = input\n        self._output = output\n        self._factory = CommonTokenFactory.DEFAULT\n        self._tokenFactorySourcePair = (self, input)\n\n        self._interp = None # child classes must populate this\n\n        # The goal of all lexer rules/methods is to create a token object.\n        #  self is an instance variable as multiple rules may collaborate to\n        #  create a single token.  nextToken will return self object after\n        #  matching lexer rule(s).  If you subclass to allow multiple token\n        #  emissions, then set self to the last token to be matched or\n        #  something nonnull so that the auto token emit mechanism will not\n        #  emit another token.\n        self._token = None\n\n        # What character index in the stream did the current token start at?\n        #  Needed, for example, to get the text for current token.  Set at\n        #  the start of nextToken.\n        self._tokenStartCharIndex = -1\n\n        # The line on which the first character of the token resides#/\n        self._tokenStartLine = -1\n\n        # The character position of first character within the line#/\n        self._tokenStartColumn = -1\n\n        # Once we see EOF on char stream, next token will be EOF.\n        #  If you have DONE : EOF ; then you see DONE EOF.\n        self._hitEOF = False\n\n        # The channel number for the current token#/\n        self._channel = Token.DEFAULT_CHANNEL\n\n        # The token type for the current token#/\n        self._type = Token.INVALID_TYPE\n\n        self._modeStack = []\n        self._mode = self.DEFAULT_MODE\n\n        # You can set the text for the current token to override what is in\n        #  the input char buffer.  Use setText() or can set self instance var.\n        #/\n        self._text = None\n\n\n    def reset(self):\n        # wack Lexer state variables\n        if self._input is not None:\n            self._input.seek(0) # rewind the input\n        self._token = None\n        self._type = Token.INVALID_TYPE\n        self._channel = Token.DEFAULT_CHANNEL\n        self._tokenStartCharIndex = -1\n        self._tokenStartColumn = -1\n        self._tokenStartLine = -1\n        self._text = None\n\n        self._hitEOF = False\n        self._mode = Lexer.DEFAULT_MODE\n        self._modeStack = []\n\n        self._interp.reset()\n\n    # Return a token from self source; i.e., match a token on the char\n    #  stream.\n    def nextToken(self):\n        if self._input is None:\n            raise IllegalStateException(\"nextToken requires a non-null input stream.\")\n\n        # Mark start location in char stream so unbuffered streams are\n        # guaranteed at least have text of current token\n        tokenStartMarker = self._input.mark()\n        try:\n            while True:\n                if self._hitEOF:\n                    self.emitEOF()\n                    return self._token\n                self._token = None\n                self._channel = Token.DEFAULT_CHANNEL\n                self._tokenStartCharIndex = self._input.index\n                self._tokenStartColumn = self._interp.column\n                self._tokenStartLine = self._interp.line\n                self._text = None\n                continueOuter = False\n                while True:\n                    self._type = Token.INVALID_TYPE\n                    ttype = self.SKIP\n                    try:\n                        ttype = self._interp.match(self._input, self._mode)\n                    except LexerNoViableAltException as e:\n                        self.notifyListeners(e)\t\t# report error\n                        self.recover(e)\n                    if self._input.LA(1)==Token.EOF:\n                        self._hitEOF = True\n                    if self._type == Token.INVALID_TYPE:\n                        self._type = ttype\n                    if self._type == self.SKIP:\n                        continueOuter = True\n                        break\n                    if self._type!=self.MORE:\n                        break\n                if continueOuter:\n                    continue\n                if self._token is None:\n                    self.emit()\n                return self._token\n        finally:\n            # make sure we release marker after match or\n            # unbuffered char stream will keep buffering\n            self._input.release(tokenStartMarker)\n\n    # Instruct the lexer to skip creating a token for current lexer rule\n    #  and look for another token.  nextToken() knows to keep looking when\n    #  a lexer rule finishes with token set to SKIP_TOKEN.  Recall that\n    #  if token==null at end of any token rule, it creates one for you\n    #  and emits it.\n    #/\n    def skip(self):\n        self._type = self.SKIP\n\n    def more(self):\n        self._type = self.MORE\n\n    def mode(self, m:int):\n        self._mode = m\n\n    def pushMode(self, m:int):\n        if self._interp.debug:\n            print(\"pushMode \" + str(m), file=self._output)\n        self._modeStack.append(self._mode)\n        self.mode(m)\n\n    def popMode(self):\n        if len(self._modeStack)==0:\n            raise Exception(\"Empty Stack\")\n        if self._interp.debug:\n            print(\"popMode back to \"+ self._modeStack[:-1], file=self._output)\n        self.mode( self._modeStack.pop() )\n        return self._mode\n\n    # Set the char stream and reset the lexer#/\n    @property\n    def inputStream(self):\n        return self._input\n\n    @inputStream.setter\n    def inputStream(self, input:InputStream):\n        self._input = None\n        self._tokenFactorySourcePair = (self, self._input)\n        self.reset()\n        self._input = input\n        self._tokenFactorySourcePair = (self, self._input)\n\n    @property\n    def sourceName(self):\n        return self._input.sourceName\n\n    # By default does not support multiple emits per nextToken invocation\n    #  for efficiency reasons.  Subclass and override self method, nextToken,\n    #  and getToken (to push tokens into a list and pull from that list\n    #  rather than a single variable as self implementation does).\n    #/\n    def emitToken(self, token:Token):\n        self._token = token\n\n    # The standard method called to automatically emit a token at the\n    #  outermost lexical rule.  The token object should point into the\n    #  char buffer start..stop.  If there is a text override in 'text',\n    #  use that to set the token's text.  Override self method to emit\n    #  custom Token objects or provide a new factory.\n    #/\n    def emit(self):\n        t = self._factory.create(self._tokenFactorySourcePair, self._type, self._text, self._channel, self._tokenStartCharIndex,\n                                 self.getCharIndex()-1, self._tokenStartLine, self._tokenStartColumn)\n        self.emitToken(t)\n        return t\n\n    def emitEOF(self):\n        cpos = self.column\n        lpos = self.line\n        eof = self._factory.create(self._tokenFactorySourcePair, Token.EOF, None, Token.DEFAULT_CHANNEL, self._input.index,\n                                   self._input.index-1, lpos, cpos)\n        self.emitToken(eof)\n        return eof\n\n    @property\n    def type(self):\n        return self._type\n\n    @type.setter\n    def type(self, type:int):\n        self._type = type\n\n    @property\n    def line(self):\n        return self._interp.line\n\n    @line.setter\n    def line(self, line:int):\n        self._interp.line = line\n\n    @property\n    def column(self):\n        return self._interp.column\n\n    @column.setter\n    def column(self, column:int):\n        self._interp.column = column\n\n    # What is the index of the current character of lookahead?#/\n    def getCharIndex(self):\n        return self._input.index\n\n    # Return the text matched so far for the current token or any\n    #  text override.\n    @property\n    def text(self):\n        if self._text is not None:\n            return self._text\n        else:\n            return self._interp.getText(self._input)\n\n    # Set the complete text of self token; it wipes any previous\n    #  changes to the text.\n    @text.setter\n    def text(self, txt:str):\n        self._text = txt\n\n    # Return a list of all Token objects in input char stream.\n    #  Forces load of all tokens. Does not include EOF token.\n    #/\n    def getAllTokens(self):\n        tokens = []\n        t = self.nextToken()\n        while t.type!=Token.EOF:\n            tokens.append(t)\n            t = self.nextToken()\n        return tokens\n\n    def notifyListeners(self, e:LexerNoViableAltException):\n        start = self._tokenStartCharIndex\n        stop = self._input.index\n        text = self._input.getText(start, stop)\n        msg = \"token recognition error at: '\" + self.getErrorDisplay(text) + \"'\"\n        listener = self.getErrorListenerDispatch()\n        listener.syntaxError(self, None, self._tokenStartLine, self._tokenStartColumn, msg, e)\n\n    def getErrorDisplay(self, s:str):\n        with StringIO() as buf:\n            for c in s:\n                buf.write(self.getErrorDisplayForChar(c))\n            return buf.getvalue()\n\n    def getErrorDisplayForChar(self, c:str):\n        if ord(c[0])==Token.EOF:\n            return \"<EOF>\"\n        elif c=='\\n':\n            return \"\\\\n\"\n        elif c=='\\t':\n            return \"\\\\t\"\n        elif c=='\\r':\n            return \"\\\\r\"\n        else:\n            return c\n\n    def getCharErrorDisplay(self, c:str):\n        return \"'\" + self.getErrorDisplayForChar(c) + \"'\"\n\n    # Lexers can normally match any char in it's vocabulary after matching\n    #  a token, so do the easy thing and just kill a character and hope\n    #  it all works out.  You can instead use the rule invocation stack\n    #  to do sophisticated error recovery if you are in a fragment rule.\n    #/\n    def recover(self, re:RecognitionException):\n        if self._input.LA(1) != Token.EOF:\n            if isinstance(re, LexerNoViableAltException):\n                    # skip a char and try again\n                    self._interp.consume(self._input)\n            else:\n                # TODO: Do we lose character or line position information?\n                self._input.consume()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/ListTokenSource.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# Provides an implementation of {@link TokenSource} as a wrapper around a list\n# of {@link Token} objects.\n#\n# <p>If the final token in the list is an {@link Token#EOF} token, it will be used\n# as the EOF token for every call to {@link #nextToken} after the end of the\n# list is reached. Otherwise, an EOF token will be created.</p>\n#\nfrom .CommonTokenFactory import CommonTokenFactory\nfrom .Lexer import TokenSource\nfrom .Token import Token\n\n\nclass ListTokenSource(TokenSource):\n    __slots__ = ('tokens', 'sourceName', 'pos', 'eofToken', '_factory')\n\n    # Constructs a new {@link ListTokenSource} instance from the specified\n    # collection of {@link Token} objects and source name.\n    #\n    # @param tokens The collection of {@link Token} objects to provide as a\n    # {@link TokenSource}.\n    # @param sourceName The name of the {@link TokenSource}. If this value is\n    # {@code null}, {@link #getSourceName} will attempt to infer the name from\n    # the next {@link Token} (or the previous token if the end of the input has\n    # been reached).\n    #\n    # @exception NullPointerException if {@code tokens} is {@code null}\n    #\n    def __init__(self, tokens:list, sourceName:str=None):\n        if tokens is None:\n            raise ReferenceError(\"tokens cannot be null\")\n        self.tokens = tokens\n        self.sourceName = sourceName\n        # The index into {@link #tokens} of token to return by the next call to\n        # {@link #nextToken}. The end of the input is indicated by this value\n        # being greater than or equal to the number of items in {@link #tokens}.\n        self.pos = 0\n        # This field caches the EOF token for the token source.\n        self.eofToken = None\n        # This is the backing field for {@link #getTokenFactory} and\n        self._factory = CommonTokenFactory.DEFAULT\n\n\n    #\n    # {@inheritDoc}\n    #\n    @property\n    def column(self):\n        if self.pos < len(self.tokens):\n            return self.tokens[self.pos].column\n        elif self.eofToken is not None:\n            return self.eofToken.column\n        elif len(self.tokens) > 0:\n            # have to calculate the result from the line/column of the previous\n            # token, along with the text of the token.\n            lastToken = self.tokens[len(self.tokens) - 1]\n            tokenText = lastToken.text\n            if tokenText is not None:\n                lastNewLine = tokenText.rfind('\\n')\n                if lastNewLine >= 0:\n                    return len(tokenText) - lastNewLine - 1\n            return lastToken.column + lastToken.stop - lastToken.start + 1\n\n        # only reach this if tokens is empty, meaning EOF occurs at the first\n        # position in the input\n        return 0\n\n    #\n    # {@inheritDoc}\n    #\n    def nextToken(self):\n        if self.pos >= len(self.tokens):\n            if self.eofToken is None:\n                start = -1\n                if len(self.tokens) > 0:\n                    previousStop = self.tokens[len(self.tokens) - 1].stop\n                    if previousStop != -1:\n                        start = previousStop + 1\n                stop = max(-1, start - 1)\n                self.eofToken = self._factory.create((self, self.getInputStream()),\n                            Token.EOF, \"EOF\", Token.DEFAULT_CHANNEL, start, stop, self.line, self.column)\n            return self.eofToken\n        t = self.tokens[self.pos]\n        if self.pos == len(self.tokens) - 1 and t.type == Token.EOF:\n            self.eofToken = t\n        self.pos += 1\n        return t\n\n    #\n    # {@inheritDoc}\n    #\n    @property\n    def line(self):\n        if self.pos < len(self.tokens):\n            return self.tokens[self.pos].line\n        elif self.eofToken is not None:\n            return self.eofToken.line\n        elif len(self.tokens) > 0:\n            # have to calculate the result from the line/column of the previous\n            # token, along with the text of the token.\n            lastToken = self.tokens[len(self.tokens) - 1]\n            line = lastToken.line\n            tokenText = lastToken.text\n            if tokenText is not None:\n                line += tokenText.count('\\n')\n\n            # if no text is available, assume the token did not contain any newline characters.\n            return line\n\n        # only reach this if tokens is empty, meaning EOF occurs at the first\n        # position in the input\n        return 1\n\n    #\n    # {@inheritDoc}\n    #\n    def getInputStream(self):\n        if self.pos < len(self.tokens):\n            return self.tokens[self.pos].getInputStream()\n        elif self.eofToken is not None:\n            return self.eofToken.getInputStream()\n        elif len(self.tokens) > 0:\n            return self.tokens[len(self.tokens) - 1].getInputStream()\n        else:\n            # no input stream information is available\n            return None\n\n    #\n    # {@inheritDoc}\n    #\n    def getSourceName(self):\n        if self.sourceName is not None:\n            return self.sourceName\n        inputStream = self.getInputStream()\n        if inputStream is not None:\n            return inputStream.getSourceName()\n        else:\n            return \"List\"\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/Parser.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\nimport sys\nif sys.version_info >= (3, 6):\n    from typing import TextIO\nelse:\n    from typing.io import TextIO\nfrom .BufferedTokenStream import TokenStream\nfrom .CommonTokenFactory import TokenFactory\nfrom .error.ErrorStrategy import DefaultErrorStrategy\nfrom .InputStream import InputStream\nfrom .Recognizer import Recognizer\nfrom .RuleContext import RuleContext\nfrom .ParserRuleContext import ParserRuleContext\nfrom .Token import Token\nfrom .Lexer import Lexer\nfrom .atn.ATNDeserializer import ATNDeserializer\nfrom .atn.ATNDeserializationOptions import ATNDeserializationOptions\nfrom .error.Errors import UnsupportedOperationException, RecognitionException\nfrom .tree.ParseTreePatternMatcher import ParseTreePatternMatcher\nfrom .tree.Tree import ParseTreeListener, TerminalNode, ErrorNode\n\nclass TraceListener(ParseTreeListener):\n    __slots__ = '_parser'\n\n    def __init__(self, parser):\n        self._parser = parser\n\n    def enterEveryRule(self, ctx):\n        print(\"enter   \" + self._parser.ruleNames[ctx.getRuleIndex()] + \", LT(1)=\" + self._parser._input.LT(1).text, file=self._parser._output)\n\n    def visitTerminal(self, node):\n\n        print(\"consume \" + str(node.symbol) + \" rule \" + self._parser.ruleNames[self._parser._ctx.getRuleIndex()], file=self._parser._output)\n\n    def visitErrorNode(self, node):\n        pass\n\n\n    def exitEveryRule(self, ctx):\n        print(\"exit    \" + self._parser.ruleNames[ctx.getRuleIndex()] + \", LT(1)=\" + self._parser._input.LT(1).text, file=self._parser._output)\n\n\n# self is all the parsing support code essentially; most of it is error recovery stuff.#\nclass Parser (Recognizer):\n    __slots__ = (\n        '_input', '_output', '_errHandler', '_precedenceStack', '_ctx',\n        'buildParseTrees', '_tracer', '_parseListeners', '_syntaxErrors'\n\n    )\n    # self field maps from the serialized ATN string to the deserialized {@link ATN} with\n    # bypass alternatives.\n    #\n    # @see ATNDeserializationOptions#isGenerateRuleBypassTransitions()\n    #\n    bypassAltsAtnCache = dict()\n\n    def __init__(self, input:TokenStream, output:TextIO = sys.stdout):\n        super().__init__()\n        # The input stream.\n        self._input = None\n        self._output = output\n        # The error handling strategy for the parser. The default value is a new\n        # instance of {@link DefaultErrorStrategy}.\n        self._errHandler = DefaultErrorStrategy()\n        self._precedenceStack = list()\n        self._precedenceStack.append(0)\n        # The {@link ParserRuleContext} object for the currently executing rule.\n        # self is always non-null during the parsing process.\n        self._ctx = None\n        # Specifies whether or not the parser should construct a parse tree during\n        # the parsing process. The default value is {@code true}.\n        self.buildParseTrees = True\n        # When {@link #setTrace}{@code (true)} is called, a reference to the\n        # {@link TraceListener} is stored here so it can be easily removed in a\n        # later call to {@link #setTrace}{@code (false)}. The listener itself is\n        # implemented as a parser listener so self field is not directly used by\n        # other parser methods.\n        self._tracer = None\n        # The list of {@link ParseTreeListener} listeners registered to receive\n        # events during the parse.\n        self._parseListeners = None\n        # The number of syntax errors reported during parsing. self value is\n        # incremented each time {@link #notifyErrorListeners} is called.\n        self._syntaxErrors = 0\n        self.setInputStream(input)\n\n    # reset the parser's state#\n    def reset(self):\n        if self._input is not None:\n            self._input.seek(0)\n        self._errHandler.reset(self)\n        self._ctx = None\n        self._syntaxErrors = 0\n        self.setTrace(False)\n        self._precedenceStack = list()\n        self._precedenceStack.append(0)\n        if self._interp is not None:\n            self._interp.reset()\n\n    # Match current input symbol against {@code ttype}. If the symbol type\n    # matches, {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are\n    # called to complete the match process.\n    #\n    # <p>If the symbol type does not match,\n    # {@link ANTLRErrorStrategy#recoverInline} is called on the current error\n    # strategy to attempt recovery. If {@link #getBuildParseTree} is\n    # {@code true} and the token index of the symbol returned by\n    # {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to\n    # the parse tree by calling {@link ParserRuleContext#addErrorNode}.</p>\n    #\n    # @param ttype the token type to match\n    # @return the matched symbol\n    # @throws RecognitionException if the current input symbol did not match\n    # {@code ttype} and the error strategy could not recover from the\n    # mismatched symbol\n\n    def match(self, ttype:int):\n        t = self.getCurrentToken()\n        if t.type==ttype:\n            self._errHandler.reportMatch(self)\n            self.consume()\n        else:\n            t = self._errHandler.recoverInline(self)\n            if self.buildParseTrees and t.tokenIndex==-1:\n                # we must have conjured up a new token during single token insertion\n                # if it's not the current symbol\n                self._ctx.addErrorNode(t)\n        return t\n\n    # Match current input symbol as a wildcard. If the symbol type matches\n    # (i.e. has a value greater than 0), {@link ANTLRErrorStrategy#reportMatch}\n    # and {@link #consume} are called to complete the match process.\n    #\n    # <p>If the symbol type does not match,\n    # {@link ANTLRErrorStrategy#recoverInline} is called on the current error\n    # strategy to attempt recovery. If {@link #getBuildParseTree} is\n    # {@code true} and the token index of the symbol returned by\n    # {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to\n    # the parse tree by calling {@link ParserRuleContext#addErrorNode}.</p>\n    #\n    # @return the matched symbol\n    # @throws RecognitionException if the current input symbol did not match\n    # a wildcard and the error strategy could not recover from the mismatched\n    # symbol\n\n    def matchWildcard(self):\n        t = self.getCurrentToken()\n        if t.type > 0:\n            self._errHandler.reportMatch(self)\n            self.consume()\n        else:\n            t = self._errHandler.recoverInline(self)\n            if self.buildParseTrees and t.tokenIndex == -1:\n                # we must have conjured up a new token during single token insertion\n                # if it's not the current symbol\n                self._ctx.addErrorNode(t)\n\n        return t\n\n    def getParseListeners(self):\n        return list() if self._parseListeners is None else self._parseListeners\n\n    # Registers {@code listener} to receive events during the parsing process.\n    #\n    # <p>To support output-preserving grammar transformations (including but not\n    # limited to left-recursion removal, automated left-factoring, and\n    # optimized code generation), calls to listener methods during the parse\n    # may differ substantially from calls made by\n    # {@link ParseTreeWalker#DEFAULT} used after the parse is complete. In\n    # particular, rule entry and exit events may occur in a different order\n    # during the parse than after the parser. In addition, calls to certain\n    # rule entry methods may be omitted.</p>\n    #\n    # <p>With the following specific exceptions, calls to listener events are\n    # <em>deterministic</em>, i.e. for identical input the calls to listener\n    # methods will be the same.</p>\n    #\n    # <ul>\n    # <li>Alterations to the grammar used to generate code may change the\n    # behavior of the listener calls.</li>\n    # <li>Alterations to the command line options passed to ANTLR 4 when\n    # generating the parser may change the behavior of the listener calls.</li>\n    # <li>Changing the version of the ANTLR Tool used to generate the parser\n    # may change the behavior of the listener calls.</li>\n    # </ul>\n    #\n    # @param listener the listener to add\n    #\n    # @throws NullPointerException if {@code} listener is {@code null}\n    #\n    def addParseListener(self, listener:ParseTreeListener):\n        if listener is None:\n            raise ReferenceError(\"listener\")\n        if self._parseListeners is None:\n            self._parseListeners = []\n        self._parseListeners.append(listener)\n\n    #\n    # Remove {@code listener} from the list of parse listeners.\n    #\n    # <p>If {@code listener} is {@code null} or has not been added as a parse\n    # listener, self method does nothing.</p>\n    # @param listener the listener to remove\n    #\n    def removeParseListener(self, listener:ParseTreeListener):\n        if self._parseListeners is not None:\n            self._parseListeners.remove(listener)\n            if len(self._parseListeners)==0:\n                    self._parseListeners = None\n\n    # Remove all parse listeners.\n    def removeParseListeners(self):\n        self._parseListeners = None\n\n    # Notify any parse listeners of an enter rule event.\n    def triggerEnterRuleEvent(self):\n        if self._parseListeners is not None:\n            for listener in self._parseListeners:\n                listener.enterEveryRule(self._ctx)\n                self._ctx.enterRule(listener)\n\n    #\n    # Notify any parse listeners of an exit rule event.\n    #\n    # @see #addParseListener\n    #\n    def triggerExitRuleEvent(self):\n        if self._parseListeners is not None:\n            # reverse order walk of listeners\n            for listener in reversed(self._parseListeners):\n                self._ctx.exitRule(listener)\n                listener.exitEveryRule(self._ctx)\n\n\n    # Gets the number of syntax errors reported during parsing. This value is\n    # incremented each time {@link #notifyErrorListeners} is called.\n    #\n    # @see #notifyErrorListeners\n    #\n    def getNumberOfSyntaxErrors(self):\n        return self._syntaxErrors\n\n    def getTokenFactory(self):\n        return self._input.tokenSource._factory\n\n    # Tell our token source and error strategy about a new way to create tokens.#\n    def setTokenFactory(self, factory:TokenFactory):\n        self._input.tokenSource._factory = factory\n\n    # The ATN with bypass alternatives is expensive to create so we create it\n    # lazily.\n    #\n    # @throws UnsupportedOperationException if the current parser does not\n    # implement the {@link #getSerializedATN()} method.\n    #\n    def getATNWithBypassAlts(self):\n        serializedAtn = self.getSerializedATN()\n        if serializedAtn is None:\n            raise UnsupportedOperationException(\"The current parser does not support an ATN with bypass alternatives.\")\n        result = self.bypassAltsAtnCache.get(serializedAtn, None)\n        if result is None:\n            deserializationOptions = ATNDeserializationOptions()\n            deserializationOptions.generateRuleBypassTransitions = True\n            result = ATNDeserializer(deserializationOptions).deserialize(serializedAtn)\n            self.bypassAltsAtnCache[serializedAtn] = result\n        return result\n\n    # The preferred method of getting a tree pattern. For example, here's a\n    # sample use:\n    #\n    # <pre>\n    # ParseTree t = parser.expr();\n    # ParseTreePattern p = parser.compileParseTreePattern(\"&lt;ID&gt;+0\", MyParser.RULE_expr);\n    # ParseTreeMatch m = p.match(t);\n    # String id = m.get(\"ID\");\n    # </pre>\n    #\n    def compileParseTreePattern(self, pattern:str, patternRuleIndex:int, lexer:Lexer = None):\n        if lexer is None:\n            if self.getTokenStream() is not None:\n                tokenSource = self.getTokenStream().tokenSource\n                if isinstance( tokenSource, Lexer ):\n                    lexer = tokenSource\n        if lexer is None:\n            raise UnsupportedOperationException(\"Parser can't discover a lexer to use\")\n\n        m = ParseTreePatternMatcher(lexer, self)\n        return m.compile(pattern, patternRuleIndex)\n\n\n    def getInputStream(self):\n        return self.getTokenStream()\n\n    def setInputStream(self, input:InputStream):\n        self.setTokenStream(input)\n\n    def getTokenStream(self):\n        return self._input\n\n    # Set the token stream and reset the parser.#\n    def setTokenStream(self, input:TokenStream):\n        self._input = None\n        self.reset()\n        self._input = input\n\n    # Match needs to return the current input symbol, which gets put\n    #  into the label for the associated token ref; e.g., x=ID.\n    #\n    def getCurrentToken(self):\n        return self._input.LT(1)\n\n    def notifyErrorListeners(self, msg:str, offendingToken:Token = None, e:RecognitionException = None):\n        if offendingToken is None:\n            offendingToken = self.getCurrentToken()\n        self._syntaxErrors += 1\n        line = offendingToken.line\n        column = offendingToken.column\n        listener = self.getErrorListenerDispatch()\n        listener.syntaxError(self, offendingToken, line, column, msg, e)\n\n    #\n    # Consume and return the {@linkplain #getCurrentToken current symbol}.\n    #\n    # <p>E.g., given the following input with {@code A} being the current\n    # lookahead symbol, self function moves the cursor to {@code B} and returns\n    # {@code A}.</p>\n    #\n    # <pre>\n    #  A B\n    #  ^\n    # </pre>\n    #\n    # If the parser is not in error recovery mode, the consumed symbol is added\n    # to the parse tree using {@link ParserRuleContext#addChild(Token)}, and\n    # {@link ParseTreeListener#visitTerminal} is called on any parse listeners.\n    # If the parser <em>is</em> in error recovery mode, the consumed symbol is\n    # added to the parse tree using\n    # {@link ParserRuleContext#addErrorNode(Token)}, and\n    # {@link ParseTreeListener#visitErrorNode} is called on any parse\n    # listeners.\n    #\n    def consume(self):\n        o = self.getCurrentToken()\n        if o.type != Token.EOF:\n            self.getInputStream().consume()\n        hasListener = self._parseListeners is not None and len(self._parseListeners)>0\n        if self.buildParseTrees or hasListener:\n            if self._errHandler.inErrorRecoveryMode(self):\n                node = self._ctx.addErrorNode(o)\n            else:\n                node = self._ctx.addTokenNode(o)\n            if hasListener:\n                for listener in self._parseListeners:\n                    if isinstance(node, ErrorNode):\n                        listener.visitErrorNode(node)\n                    elif isinstance(node, TerminalNode):\n                        listener.visitTerminal(node)\n        return o\n\n    def addContextToParseTree(self):\n        # add current context to parent if we have a parent\n        if self._ctx.parentCtx is not None:\n            self._ctx.parentCtx.addChild(self._ctx)\n\n    # Always called by generated parsers upon entry to a rule. Access field\n    # {@link #_ctx} get the current context.\n    #\n    def enterRule(self, localctx:ParserRuleContext , state:int , ruleIndex:int):\n        self.state = state\n        self._ctx = localctx\n        self._ctx.start = self._input.LT(1)\n        if self.buildParseTrees:\n            self.addContextToParseTree()\n        if self._parseListeners  is not None:\n            self.triggerEnterRuleEvent()\n\n    def exitRule(self):\n        self._ctx.stop = self._input.LT(-1)\n        # trigger event on _ctx, before it reverts to parent\n        if self._parseListeners is not None:\n            self.triggerExitRuleEvent()\n        self.state = self._ctx.invokingState\n        self._ctx = self._ctx.parentCtx\n\n    def enterOuterAlt(self, localctx:ParserRuleContext, altNum:int):\n        localctx.setAltNumber(altNum)\n        # if we have new localctx, make sure we replace existing ctx\n        # that is previous child of parse tree\n        if self.buildParseTrees and self._ctx != localctx:\n            if self._ctx.parentCtx is not None:\n                self._ctx.parentCtx.removeLastChild()\n                self._ctx.parentCtx.addChild(localctx)\n        self._ctx = localctx\n\n    # Get the precedence level for the top-most precedence rule.\n    #\n    # @return The precedence level for the top-most precedence rule, or -1 if\n    # the parser context is not nested within a precedence rule.\n    #\n    def getPrecedence(self):\n        if len(self._precedenceStack)==0:\n            return -1\n        else:\n            return self._precedenceStack[-1]\n\n    def enterRecursionRule(self, localctx:ParserRuleContext, state:int, ruleIndex:int, precedence:int):\n        self.state = state\n        self._precedenceStack.append(precedence)\n        self._ctx = localctx\n        self._ctx.start = self._input.LT(1)\n        if self._parseListeners is not None:\n            self.triggerEnterRuleEvent() # simulates rule entry for left-recursive rules\n\n    #\n    # Like {@link #enterRule} but for recursive rules.\n    #\n    def pushNewRecursionContext(self, localctx:ParserRuleContext, state:int, ruleIndex:int):\n        previous = self._ctx\n        previous.parentCtx = localctx\n        previous.invokingState = state\n        previous.stop = self._input.LT(-1)\n\n        self._ctx = localctx\n        self._ctx.start = previous.start\n        if self.buildParseTrees:\n            self._ctx.addChild(previous)\n\n        if self._parseListeners is not None:\n            self.triggerEnterRuleEvent() # simulates rule entry for left-recursive rules\n\n    def unrollRecursionContexts(self, parentCtx:ParserRuleContext):\n        self._precedenceStack.pop()\n        self._ctx.stop = self._input.LT(-1)\n        retCtx = self._ctx # save current ctx (return value)\n        # unroll so _ctx is as it was before call to recursive method\n        if self._parseListeners is not None:\n            while self._ctx is not parentCtx:\n                self.triggerExitRuleEvent()\n                self._ctx = self._ctx.parentCtx\n        else:\n            self._ctx = parentCtx\n\n        # hook into tree\n        retCtx.parentCtx = parentCtx\n\n        if self.buildParseTrees and parentCtx is not None:\n            # add return ctx into invoking rule's tree\n            parentCtx.addChild(retCtx)\n\n    def getInvokingContext(self, ruleIndex:int):\n        ctx = self._ctx\n        while ctx is not None:\n            if ctx.getRuleIndex() == ruleIndex:\n                return ctx\n            ctx = ctx.parentCtx\n        return None\n\n\n    def precpred(self, localctx:RuleContext , precedence:int):\n        return precedence >= self._precedenceStack[-1]\n\n    def inContext(self, context:str):\n        # TODO: useful in parser?\n        return False\n\n    #\n    # Checks whether or not {@code symbol} can follow the current state in the\n    # ATN. The behavior of self method is equivalent to the following, but is\n    # implemented such that the complete context-sensitive follow set does not\n    # need to be explicitly constructed.\n    #\n    # <pre>\n    # return getExpectedTokens().contains(symbol);\n    # </pre>\n    #\n    # @param symbol the symbol type to check\n    # @return {@code true} if {@code symbol} can follow the current state in\n    # the ATN, otherwise {@code false}.\n    #\n    def isExpectedToken(self, symbol:int):\n        atn = self._interp.atn\n        ctx = self._ctx\n        s = atn.states[self.state]\n        following = atn.nextTokens(s)\n        if symbol in following:\n            return True\n        if not Token.EPSILON in following:\n            return False\n\n        while ctx is not None and ctx.invokingState>=0 and Token.EPSILON in following:\n            invokingState = atn.states[ctx.invokingState]\n            rt = invokingState.transitions[0]\n            following = atn.nextTokens(rt.followState)\n            if symbol in following:\n                return True\n            ctx = ctx.parentCtx\n\n        if Token.EPSILON in following and symbol == Token.EOF:\n            return True\n        else:\n            return False\n\n    # Computes the set of input symbols which could follow the current parser\n    # state and context, as given by {@link #getState} and {@link #getContext},\n    # respectively.\n    #\n    # @see ATN#getExpectedTokens(int, RuleContext)\n    #\n    def getExpectedTokens(self):\n        return self._interp.atn.getExpectedTokens(self.state, self._ctx)\n\n    def getExpectedTokensWithinCurrentRule(self):\n        atn = self._interp.atn\n        s = atn.states[self.state]\n        return atn.nextTokens(s)\n\n    # Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.#\n    def getRuleIndex(self, ruleName:str):\n        ruleIndex = self.getRuleIndexMap().get(ruleName, None)\n        if ruleIndex is not None:\n            return ruleIndex\n        else:\n            return -1\n\n    # Return List&lt;String&gt; of the rule names in your parser instance\n    #  leading up to a call to the current rule.  You could override if\n    #  you want more details such as the file/line info of where\n    #  in the ATN a rule is invoked.\n    #\n    #  this is very useful for error messages.\n    #\n    def getRuleInvocationStack(self, p:RuleContext=None):\n        if p is None:\n            p = self._ctx\n        stack = list()\n        while p is not None:\n            # compute what follows who invoked us\n            ruleIndex = p.getRuleIndex()\n            if ruleIndex<0:\n                stack.append(\"n/a\")\n            else:\n                stack.append(self.ruleNames[ruleIndex])\n            p = p.parentCtx\n        return stack\n\n    # For debugging and other purposes.#\n    def getDFAStrings(self):\n        return [ str(dfa) for dfa in self._interp.decisionToDFA]\n\n    # For debugging and other purposes.#\n    def dumpDFA(self):\n        seenOne = False\n        for i in range(0, len(self._interp.decisionToDFA)):\n            dfa = self._interp.decisionToDFA[i]\n            if len(dfa.states)>0:\n                if seenOne:\n                    print(file=self._output)\n                print(\"Decision \" + str(dfa.decision) + \":\", file=self._output)\n                print(dfa.toString(self.literalNames, self.symbolicNames), end='', file=self._output)\n                seenOne = True\n\n\n    def getSourceName(self):\n        return self._input.sourceName\n\n    # During a parse is sometimes useful to listen in on the rule entry and exit\n    #  events as well as token matches. self is for quick and dirty debugging.\n    #\n    def setTrace(self, trace:bool):\n        if not trace:\n            self.removeParseListener(self._tracer)\n            self._tracer = None\n        else:\n            if self._tracer is not None:\n                self.removeParseListener(self._tracer)\n            self._tracer = TraceListener(self)\n            self.addParseListener(self._tracer)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/ParserInterpreter.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n# A parser simulator that mimics what ANTLR's generated\n#  parser code does. A ParserATNSimulator is used to make\n#  predictions via adaptivePredict but this class moves a pointer through the\n#  ATN to simulate parsing. ParserATNSimulator just\n#  makes us efficient rather than having to backtrack, for example.\n#\n#  This properly creates parse trees even for left recursive rules.\n#\n#  We rely on the left recursive rule invocation and special predicate\n#  transitions to make left recursive rules work.\n#\n#  See TestParserInterpreter for examples.\n#\nfrom .dfa.DFA import DFA\nfrom .BufferedTokenStream import TokenStream\nfrom .Lexer import Lexer\nfrom .Parser import Parser\nfrom .ParserRuleContext import InterpreterRuleContext, ParserRuleContext\nfrom .Token import Token\nfrom .atn.ATN import ATN\nfrom .atn.ATNState import StarLoopEntryState, ATNState, LoopEndState\nfrom .atn.ParserATNSimulator import ParserATNSimulator\nfrom .PredictionContext import PredictionContextCache\nfrom .atn.Transition import Transition\nfrom .error.Errors import RecognitionException, UnsupportedOperationException, FailedPredicateException\n\n\nclass ParserInterpreter(Parser):\n    __slots__ = (\n        'grammarFileName', 'atn', 'tokenNames', 'ruleNames', 'decisionToDFA',\n        'sharedContextCache', '_parentContextStack',\n        'pushRecursionContextStates'\n    )\n\n    def __init__(self, grammarFileName:str, tokenNames:list, ruleNames:list, atn:ATN, input:TokenStream):\n        super().__init__(input)\n        self.grammarFileName = grammarFileName\n        self.atn = atn\n        self.tokenNames = tokenNames\n        self.ruleNames = ruleNames\n        self.decisionToDFA = [ DFA(state) for state in atn.decisionToState ]\n        self.sharedContextCache = PredictionContextCache()\n        self._parentContextStack = list()\n        # identify the ATN states where pushNewRecursionContext must be called\n        self.pushRecursionContextStates = set()\n        for state in atn.states:\n            if not isinstance(state, StarLoopEntryState):\n                continue\n            if state.isPrecedenceDecision:\n                self.pushRecursionContextStates.add(state.stateNumber)\n        # get atn simulator that knows how to do predictions\n        self._interp = ParserATNSimulator(self, atn, self.decisionToDFA, self.sharedContextCache)\n\n    # Begin parsing at startRuleIndex#\n    def parse(self, startRuleIndex:int):\n        startRuleStartState = self.atn.ruleToStartState[startRuleIndex]\n        rootContext = InterpreterRuleContext(None, ATNState.INVALID_STATE_NUMBER, startRuleIndex)\n        if startRuleStartState.isPrecedenceRule:\n            self.enterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0)\n        else:\n            self.enterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex)\n        while True:\n            p = self.getATNState()\n            if p.stateType==ATNState.RULE_STOP :\n                # pop; return from rule\n                if len(self._ctx)==0:\n                    if startRuleStartState.isPrecedenceRule:\n                        result = self._ctx\n                        parentContext = self._parentContextStack.pop()\n                        self.unrollRecursionContexts(parentContext.a)\n                        return result\n                    else:\n                        self.exitRule()\n                        return rootContext\n                self.visitRuleStopState(p)\n\n            else:\n                try:\n                    self.visitState(p)\n                except RecognitionException as e:\n                    self.state = self.atn.ruleToStopState[p.ruleIndex].stateNumber\n                    self._ctx.exception = e\n                    self._errHandler.reportError(self, e)\n                    self._errHandler.recover(self, e)\n\n    def enterRecursionRule(self, localctx:ParserRuleContext, state:int, ruleIndex:int, precedence:int):\n        self._parentContextStack.append((self._ctx, localctx.invokingState))\n        super().enterRecursionRule(localctx, state, ruleIndex, precedence)\n\n    def getATNState(self):\n        return self.atn.states[self.state]\n\n    def visitState(self, p:ATNState):\n        edge = 0\n        if len(p.transitions) > 1:\n            self._errHandler.sync(self)\n            edge = self._interp.adaptivePredict(self._input, p.decision, self._ctx)\n        else:\n            edge = 1\n\n        transition = p.transitions[edge - 1]\n        tt = transition.serializationType\n        if tt==Transition.EPSILON:\n\n            if self.pushRecursionContextStates[p.stateNumber] and not isinstance(transition.target, LoopEndState):\n                t = self._parentContextStack[-1]\n                ctx = InterpreterRuleContext(t[0], t[1], self._ctx.ruleIndex)\n                self.pushNewRecursionContext(ctx, self.atn.ruleToStartState[p.ruleIndex].stateNumber, self._ctx.ruleIndex)\n\n        elif tt==Transition.ATOM:\n\n            self.match(transition.label)\n\n        elif tt in [ Transition.RANGE, Transition.SET, Transition.NOT_SET]:\n\n            if not transition.matches(self._input.LA(1), Token.MIN_USER_TOKEN_TYPE, Lexer.MAX_CHAR_VALUE):\n                self._errHandler.recoverInline(self)\n            self.matchWildcard()\n\n        elif tt==Transition.WILDCARD:\n\n            self.matchWildcard()\n\n        elif tt==Transition.RULE:\n\n            ruleStartState = transition.target\n            ruleIndex = ruleStartState.ruleIndex\n            ctx = InterpreterRuleContext(self._ctx, p.stateNumber, ruleIndex)\n            if ruleStartState.isPrecedenceRule:\n                self.enterRecursionRule(ctx, ruleStartState.stateNumber, ruleIndex, transition.precedence)\n            else:\n                self.enterRule(ctx, transition.target.stateNumber, ruleIndex)\n\n        elif tt==Transition.PREDICATE:\n\n            if not self.sempred(self._ctx, transition.ruleIndex, transition.predIndex):\n                raise FailedPredicateException(self)\n\n        elif tt==Transition.ACTION:\n\n            self.action(self._ctx, transition.ruleIndex, transition.actionIndex)\n\n        elif tt==Transition.PRECEDENCE:\n\n            if not self.precpred(self._ctx, transition.precedence):\n                msg = \"precpred(_ctx, \" + str(transition.precedence) + \")\"\n                raise FailedPredicateException(self, msg)\n\n        else:\n            raise UnsupportedOperationException(\"Unrecognized ATN transition type.\")\n\n        self.state = transition.target.stateNumber\n\n    def visitRuleStopState(self, p:ATNState):\n        ruleStartState = self.atn.ruleToStartState[p.ruleIndex]\n        if ruleStartState.isPrecedenceRule:\n            parentContext = self._parentContextStack.pop()\n            self.unrollRecursionContexts(parentContext.a)\n            self.state = parentContext[1]\n        else:\n            self.exitRule()\n\n        ruleTransition = self.atn.states[self.state].transitions[0]\n        self.state = ruleTransition.followState.stateNumber\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/ParserRuleContext.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n\n#* A rule invocation record for parsing.\n#\n#  Contains all of the information about the current rule not stored in the\n#  RuleContext. It handles parse tree children list, Any ATN state\n#  tracing, and the default values available for rule indications:\n#  start, stop, rule index, current alt number, current\n#  ATN state.\n#\n#  Subclasses made for each rule and grammar track the parameters,\n#  return values, locals, and labels specific to that rule. These\n#  are the objects that are returned from rules.\n#\n#  Note text is not an actual field of a rule return value; it is computed\n#  from start and stop using the input stream's toString() method.  I\n#  could add a ctor to this so that we can pass in and store the input\n#  stream, but I'm not sure we want to do that.  It would seem to be undefined\n#  to get the .text property anyway if the rule matches tokens from multiple\n#  input streams.\n#\n#  I do not use getters for fields of objects that are used simply to\n#  group values such as this aggregate.  The getters/setters are there to\n#  satisfy the superclass interface.\n\nfrom .RuleContext import RuleContext\nfrom .Token import Token\nfrom .tree.Tree import ParseTreeListener, ParseTree, TerminalNodeImpl, ErrorNodeImpl, TerminalNode, \\\n    INVALID_INTERVAL\n\n# need forward declaration\nParserRuleContext = None\n\nclass ParserRuleContext(RuleContext):\n    __slots__ = ('children', 'start', 'stop', 'exception')\n    def __init__(self, parent:ParserRuleContext = None, invokingStateNumber:int = None ):\n        super().__init__(parent, invokingStateNumber)\n        #* If we are debugging or building a parse tree for a visitor,\n        #  we need to track all of the tokens and rule invocations associated\n        #  with this rule's context. This is empty for parsing w/o tree constr.\n        #  operation because we don't the need to track the details about\n        #  how we parse this rule.\n        #/\n        self.children = None\n        self.start = None\n        self.stop = None\n        # The exception that forced this rule to return. If the rule successfully\n        # completed, this is {@code null}.\n        self.exception = None\n\n    #* COPY a ctx (I'm deliberately not using copy constructor)#/\n    #\n    # This is used in the generated parser code to flip a generic XContext\n    # node for rule X to a YContext for alt label Y. In that sense, it is\n    # not really a generic copy function.\n    #\n    # If we do an error sync() at start of a rule, we might add error nodes\n    # to the generic XContext so this function must copy those nodes to\n    # the YContext as well else they are lost!\n    #/\n    def copyFrom(self, ctx:ParserRuleContext):\n        # from RuleContext\n        self.parentCtx = ctx.parentCtx\n        self.invokingState = ctx.invokingState\n        self.children = None\n        self.start = ctx.start\n        self.stop = ctx.stop\n\n        # copy any error nodes to alt label node\n        if ctx.children is not None:\n            self.children = []\n            # reset parent pointer for any error nodes\n            for child in ctx.children:\n                if isinstance(child, ErrorNodeImpl):\n                    self.children.append(child)\n                    child.parentCtx = self\n\n    # Double dispatch methods for listeners\n    def enterRule(self, listener:ParseTreeListener):\n        pass\n\n    def exitRule(self, listener:ParseTreeListener):\n        pass\n\n    #* Does not set parent link; other add methods do that#/\n    def addChild(self, child:ParseTree):\n        if self.children is None:\n            self.children = []\n        self.children.append(child)\n        return child\n\n    #* Used by enterOuterAlt to toss out a RuleContext previously added as\n    #  we entered a rule. If we have # label, we will need to remove\n    #  generic ruleContext object.\n    #/\n    def removeLastChild(self):\n        if self.children is not None:\n            del self.children[len(self.children)-1]\n\n    def addTokenNode(self, token:Token):\n        node = TerminalNodeImpl(token)\n        self.addChild(node)\n        node.parentCtx = self\n        return node\n\n    def addErrorNode(self, badToken:Token):\n        node = ErrorNodeImpl(badToken)\n        self.addChild(node)\n        node.parentCtx = self\n        return node\n\n    def getChild(self, i:int, ttype:type = None):\n        if ttype is None:\n            return self.children[i] if len(self.children)>i else None\n        else:\n            for child in self.getChildren():\n                if not isinstance(child, ttype):\n                    continue\n                if i==0:\n                    return child\n                i -= 1\n            return None\n\n    def getChildren(self, predicate = None):\n        if self.children is not None:\n            for child in self.children:\n                if predicate is not None and not predicate(child):\n                    continue\n                yield child\n\n    def getToken(self, ttype:int, i:int):\n        for child in self.getChildren():\n            if not isinstance(child, TerminalNode):\n                continue\n            if child.symbol.type != ttype:\n                continue\n            if i==0:\n                return child\n            i -= 1\n        return None\n\n    def getTokens(self, ttype:int ):\n        if self.getChildren() is None:\n            return []\n        tokens = []\n        for child in self.getChildren():\n            if not isinstance(child, TerminalNode):\n                continue\n            if child.symbol.type != ttype:\n                continue\n            tokens.append(child)\n        return tokens\n\n    def getTypedRuleContext(self, ctxType:type, i:int):\n        return self.getChild(i, ctxType)\n\n    def getTypedRuleContexts(self, ctxType:type):\n        children = self.getChildren()\n        if children is None:\n            return []\n        contexts = []\n        for child in children:\n            if not isinstance(child, ctxType):\n                continue\n            contexts.append(child)\n        return contexts\n\n    def getChildCount(self):\n        return len(self.children) if self.children else 0\n\n    def getSourceInterval(self):\n        if self.start is None or self.stop is None:\n            return INVALID_INTERVAL\n        else:\n            return (self.start.tokenIndex, self.stop.tokenIndex)\n\n\nRuleContext.EMPTY = ParserRuleContext()\n\nclass InterpreterRuleContext(ParserRuleContext):\n\n    def __init__(self, parent:ParserRuleContext, invokingStateNumber:int, ruleIndex:int):\n        super().__init__(parent, invokingStateNumber)\n        self.ruleIndex = ruleIndex\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/PredictionContext.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\nfrom .RuleContext import RuleContext\nfrom .atn.ATN import ATN\nfrom .error.Errors import IllegalStateException\nfrom io import StringIO\n\n# dup ParserATNSimulator class var here to avoid circular import; no idea why this can't be in PredictionContext\n_trace_atn_sim = False\n\nclass PredictionContext(object):\n\n    # Represents {@code $} in local context prediction, which means wildcard.\n    # {@code#+x =#}.\n    #/\n    EMPTY = None\n\n    # Represents {@code $} in an array in full context mode, when {@code $}\n    # doesn't mean wildcard: {@code $ + x = [$,x]}. Here,\n    # {@code $} = {@link #EMPTY_RETURN_STATE}.\n    #/\n    EMPTY_RETURN_STATE = 0x7FFFFFFF\n\n    globalNodeCount = 1\n    id = globalNodeCount\n\n    # Stores the computed hash code of this {@link PredictionContext}. The hash\n    # code is computed in parts to match the following reference algorithm.\n    #\n    # <pre>\n    #  private int referenceHashCode() {\n    #      int hash = {@link MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH});\n    #\n    #      for (int i = 0; i &lt; {@link #size()}; i++) {\n    #          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i));\n    #      }\n    #\n    #      for (int i = 0; i &lt; {@link #size()}; i++) {\n    #          hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getReturnState getReturnState}(i));\n    #      }\n    #\n    #      hash = {@link MurmurHash#finish MurmurHash.finish}(hash, 2# {@link #size()});\n    #      return hash;\n    #  }\n    # </pre>\n    #/\n\n    def __init__(self, cachedHashCode:int):\n        self.cachedHashCode = cachedHashCode\n\n    def __len__(self):\n        return 0\n\n    # This means only the {@link #EMPTY} context is in set.\n    def isEmpty(self):\n        return self is self.EMPTY\n\n    def hasEmptyPath(self):\n        return self.getReturnState(len(self) - 1) == self.EMPTY_RETURN_STATE\n\n    def getReturnState(self, index:int):\n        raise IllegalStateException(\"illegal!\")\n\n    def __hash__(self):\n        return self.cachedHashCode\n\ndef calculateHashCode(parent:PredictionContext, returnState:int):\n    return hash(\"\") if parent is None else hash((hash(parent), returnState))\n\ndef calculateListsHashCode(parents:[], returnStates:[] ):\n    h = 0\n    for parent, returnState in zip(parents, returnStates):\n        h = hash((h, calculateHashCode(parent, returnState)))\n    return h\n\n#  Used to cache {@link PredictionContext} objects. Its used for the shared\n#  context cash associated with contexts in DFA states. This cache\n#  can be used for both lexers and parsers.\n\nclass PredictionContextCache(object):\n\n    def __init__(self):\n        self.cache = dict()\n\n    #  Add a context to the cache and return it. If the context already exists,\n    #  return that one instead and do not add a new context to the cache.\n    #  Protect shared cache from unsafe thread access.\n    #\n    def add(self, ctx:PredictionContext):\n        if ctx==PredictionContext.EMPTY:\n            return PredictionContext.EMPTY\n        existing = self.cache.get(ctx, None)\n        if existing is not None:\n            return existing\n        self.cache[ctx] = ctx\n        return ctx\n\n    def get(self, ctx:PredictionContext):\n        return self.cache.get(ctx, None)\n\n    def __len__(self):\n        return len(self.cache)\n\n\nclass SingletonPredictionContext(PredictionContext):\n\n    @staticmethod\n    def create(parent:PredictionContext , returnState:int ):\n        if returnState == PredictionContext.EMPTY_RETURN_STATE and parent is None:\n            # someone can pass in the bits of an array ctx that mean $\n            return SingletonPredictionContext.EMPTY\n        else:\n            return SingletonPredictionContext(parent, returnState)\n\n    def __init__(self, parent:PredictionContext, returnState:int):\n        hashCode = calculateHashCode(parent, returnState)\n        super().__init__(hashCode)\n        self.parentCtx = parent\n        self.returnState = returnState\n\n    def __len__(self):\n        return 1\n\n    def getParent(self, index:int):\n        return self.parentCtx\n\n    def getReturnState(self, index:int):\n        return self.returnState\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif other is None:\n            return False\n        elif not isinstance(other, SingletonPredictionContext):\n            return False\n        else:\n            return self.returnState == other.returnState and self.parentCtx == other.parentCtx\n\n    def __hash__(self):\n        return self.cachedHashCode\n\n    def __str__(self):\n        up = \"\" if self.parentCtx is None else str(self.parentCtx)\n        if len(up)==0:\n            if self.returnState == self.EMPTY_RETURN_STATE:\n                return \"$\"\n            else:\n                return str(self.returnState)\n        else:\n            return str(self.returnState) + \" \" + up\n\n\nclass EmptyPredictionContext(SingletonPredictionContext):\n\n    def __init__(self):\n        super().__init__(None, PredictionContext.EMPTY_RETURN_STATE)\n\n    def isEmpty(self):\n        return True\n\n    def __eq__(self, other):\n        return self is other\n\n    def __hash__(self):\n        return self.cachedHashCode\n\n    def __str__(self):\n        return \"$\"\n\n\nPredictionContext.EMPTY = EmptyPredictionContext()\n\nclass ArrayPredictionContext(PredictionContext):\n    # Parent can be null only if full ctx mode and we make an array\n    #  from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and\n    #  returnState == {@link #EMPTY_RETURN_STATE}.\n\n    def __init__(self, parents:list, returnStates:list):\n        super().__init__(calculateListsHashCode(parents, returnStates))\n        self.parents = parents\n        self.returnStates = returnStates\n\n    def isEmpty(self):\n        # since EMPTY_RETURN_STATE can only appear in the last position, we\n        # don't need to verify that size==1\n        return self.returnStates[0]==PredictionContext.EMPTY_RETURN_STATE\n\n    def __len__(self):\n        return len(self.returnStates)\n\n    def getParent(self, index:int):\n        return self.parents[index]\n\n    def getReturnState(self, index:int):\n        return self.returnStates[index]\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, ArrayPredictionContext):\n            return False\n        elif hash(self) != hash(other):\n            return False # can't be same if hash is different\n        else:\n            return self.returnStates==other.returnStates and self.parents==other.parents\n\n    def __str__(self):\n        if self.isEmpty():\n            return \"[]\"\n        with StringIO() as buf:\n            buf.write(\"[\")\n            for i in range(0,len(self.returnStates)):\n                if i>0:\n                    buf.write(\", \")\n                if self.returnStates[i]==PredictionContext.EMPTY_RETURN_STATE:\n                    buf.write(\"$\")\n                    continue\n                buf.write(str(self.returnStates[i]))\n                if self.parents[i] is not None:\n                    buf.write(' ')\n                    buf.write(str(self.parents[i]))\n                else:\n                    buf.write(\"null\")\n            buf.write(\"]\")\n            return buf.getvalue()\n\n    def __hash__(self):\n        return self.cachedHashCode\n\n\n\n#  Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.\n#  Return {@link #EMPTY} if {@code outerContext} is empty or null.\n#/\ndef PredictionContextFromRuleContext(atn:ATN, outerContext:RuleContext=None):\n    if outerContext is None:\n        outerContext = RuleContext.EMPTY\n\n    # if we are in RuleContext of start rule, s, then PredictionContext\n    # is EMPTY. Nobody called us. (if we are empty, return empty)\n    if outerContext.parentCtx is None or outerContext is RuleContext.EMPTY:\n        return PredictionContext.EMPTY\n\n    # If we have a parent, convert it to a PredictionContext graph\n    parent = PredictionContextFromRuleContext(atn, outerContext.parentCtx)\n    state = atn.states[outerContext.invokingState]\n    transition = state.transitions[0]\n    return SingletonPredictionContext.create(parent, transition.followState.stateNumber)\n\n\ndef merge(a:PredictionContext, b:PredictionContext, rootIsWildcard:bool, mergeCache:dict):\n\n    # share same graph if both same\n    if a==b:\n        return a\n\n    if isinstance(a, SingletonPredictionContext) and isinstance(b, SingletonPredictionContext):\n        return mergeSingletons(a, b, rootIsWildcard, mergeCache)\n\n    # At least one of a or b is array\n    # If one is $ and rootIsWildcard, return $ as# wildcard\n    if rootIsWildcard:\n        if isinstance( a, EmptyPredictionContext ):\n            return a\n        if isinstance( b, EmptyPredictionContext ):\n            return b\n\n    # convert singleton so both are arrays to normalize\n    if isinstance( a, SingletonPredictionContext ):\n        a = ArrayPredictionContext([a.parentCtx], [a.returnState])\n    if isinstance( b, SingletonPredictionContext):\n        b = ArrayPredictionContext([b.parentCtx], [b.returnState])\n    return mergeArrays(a, b, rootIsWildcard, mergeCache)\n\n\n#\n# Merge two {@link SingletonPredictionContext} instances.\n#\n# <p>Stack tops equal, parents merge is same; return left graph.<br>\n# <embed src=\"images/SingletonMerge_SameRootSamePar.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Same stack top, parents differ; merge parents giving array node, then\n# remainders of those graphs. A new root node is created to point to the\n# merged parents.<br>\n# <embed src=\"images/SingletonMerge_SameRootDiffPar.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Different stack tops pointing to same parent. Make array node for the\n# root where both element in the root point to the same (original)\n# parent.<br>\n# <embed src=\"images/SingletonMerge_DiffRootSamePar.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Different stack tops pointing to different parents. Make array node for\n# the root where each element points to the corresponding original\n# parent.<br>\n# <embed src=\"images/SingletonMerge_DiffRootDiffPar.svg\" type=\"image/svg+xml\"/></p>\n#\n# @param a the first {@link SingletonPredictionContext}\n# @param b the second {@link SingletonPredictionContext}\n# @param rootIsWildcard {@code true} if this is a local-context merge,\n# otherwise false to indicate a full-context merge\n# @param mergeCache\n#/\ndef mergeSingletons(a:SingletonPredictionContext, b:SingletonPredictionContext, rootIsWildcard:bool, mergeCache:dict):\n    if mergeCache is not None:\n        previous = mergeCache.get((a,b), None)\n        if previous is not None:\n            return previous\n        previous = mergeCache.get((b,a), None)\n        if previous is not None:\n            return previous\n\n    merged = mergeRoot(a, b, rootIsWildcard)\n    if merged is not None:\n        if mergeCache is not None:\n            mergeCache[(a, b)] = merged\n        return merged\n\n    if a.returnState==b.returnState:\n        parent = merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache)\n        # if parent is same as existing a or b parent or reduced to a parent, return it\n        if parent == a.parentCtx:\n            return a # ax + bx = ax, if a=b\n        if parent == b.parentCtx:\n            return b # ax + bx = bx, if a=b\n        # else: ax + ay = a'[x,y]\n        # merge parents x and y, giving array node with x,y then remainders\n        # of those graphs.  dup a, a' points at merged array\n        # new joined parent so create new singleton pointing to it, a'\n        merged = SingletonPredictionContext.create(parent, a.returnState)\n        if mergeCache is not None:\n            mergeCache[(a, b)] = merged\n        return merged\n    else: # a != b payloads differ\n        # see if we can collapse parents due to $+x parents if local ctx\n        singleParent = None\n        if a is b or (a.parentCtx is not None and a.parentCtx==b.parentCtx): # ax + bx = [a,b]x\n            singleParent = a.parentCtx\n        if singleParent is not None:\t# parents are same\n            # sort payloads and use same parent\n            payloads = [ a.returnState, b.returnState ]\n            if a.returnState > b.returnState:\n                payloads = [ b.returnState, a.returnState ]\n            parents = [singleParent, singleParent]\n            merged = ArrayPredictionContext(parents, payloads)\n            if mergeCache is not None:\n                mergeCache[(a, b)] = merged\n            return merged\n        # parents differ and can't merge them. Just pack together\n        # into array; can't merge.\n        # ax + by = [ax,by]\n        payloads = [ a.returnState, b.returnState ]\n        parents = [ a.parentCtx, b.parentCtx ]\n        if a.returnState > b.returnState: # sort by payload\n            payloads = [ b.returnState, a.returnState ]\n            parents = [ b.parentCtx, a.parentCtx ]\n        merged = ArrayPredictionContext(parents, payloads)\n        if mergeCache is not None:\n            mergeCache[(a, b)] = merged\n        return merged\n\n\n#\n# Handle case where at least one of {@code a} or {@code b} is\n# {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used\n# to represent {@link #EMPTY}.\n#\n# <h2>Local-Context Merges</h2>\n#\n# <p>These local-context merge operations are used when {@code rootIsWildcard}\n# is true.</p>\n#\n# <p>{@link #EMPTY} is superset of any graph; return {@link #EMPTY}.<br>\n# <embed src=\"images/LocalMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>{@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is\n# {@code #EMPTY}; return left graph.<br>\n# <embed src=\"images/LocalMerge_EmptyParent.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Special case of last merge if local context.<br>\n# <embed src=\"images/LocalMerge_DiffRoots.svg\" type=\"image/svg+xml\"/></p>\n#\n# <h2>Full-Context Merges</h2>\n#\n# <p>These full-context merge operations are used when {@code rootIsWildcard}\n# is false.</p>\n#\n# <p><embed src=\"images/FullMerge_EmptyRoots.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Must keep all contexts; {@link #EMPTY} in array is a special value (and\n# null parent).<br>\n# <embed src=\"images/FullMerge_EmptyRoot.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p><embed src=\"images/FullMerge_SameRoot.svg\" type=\"image/svg+xml\"/></p>\n#\n# @param a the first {@link SingletonPredictionContext}\n# @param b the second {@link SingletonPredictionContext}\n# @param rootIsWildcard {@code true} if this is a local-context merge,\n# otherwise false to indicate a full-context merge\n#/\ndef mergeRoot(a:SingletonPredictionContext, b:SingletonPredictionContext, rootIsWildcard:bool):\n    if rootIsWildcard:\n        if a == PredictionContext.EMPTY:\n            return PredictionContext.EMPTY  ## + b =#\n        if b == PredictionContext.EMPTY:\n            return PredictionContext.EMPTY  # a +# =#\n    else:\n        if a == PredictionContext.EMPTY and b == PredictionContext.EMPTY:\n            return PredictionContext.EMPTY # $ + $ = $\n        elif a == PredictionContext.EMPTY: # $ + x = [$,x]\n            payloads = [ b.returnState, PredictionContext.EMPTY_RETURN_STATE ]\n            parents = [ b.parentCtx, None ]\n            return ArrayPredictionContext(parents, payloads)\n        elif b == PredictionContext.EMPTY: # x + $ = [$,x] ($ is always first if present)\n            payloads = [ a.returnState, PredictionContext.EMPTY_RETURN_STATE ]\n            parents = [ a.parentCtx, None ]\n            return ArrayPredictionContext(parents, payloads)\n    return None\n\n\n#\n# Merge two {@link ArrayPredictionContext} instances.\n#\n# <p>Different tops, different parents.<br>\n# <embed src=\"images/ArrayMerge_DiffTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Shared top, same parents.<br>\n# <embed src=\"images/ArrayMerge_ShareTopSamePar.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Shared top, different parents.<br>\n# <embed src=\"images/ArrayMerge_ShareTopDiffPar.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Shared top, all shared parents.<br>\n# <embed src=\"images/ArrayMerge_ShareTopSharePar.svg\" type=\"image/svg+xml\"/></p>\n#\n# <p>Equal tops, merge parents and reduce top to\n# {@link SingletonPredictionContext}.<br>\n# <embed src=\"images/ArrayMerge_EqualTop.svg\" type=\"image/svg+xml\"/></p>\n#/\ndef mergeArrays(a:ArrayPredictionContext, b:ArrayPredictionContext, rootIsWildcard:bool, mergeCache:dict):\n    if mergeCache is not None:\n        previous = mergeCache.get((a,b), None)\n        if previous is not None:\n            if _trace_atn_sim: print(\"mergeArrays a=\"+str(a)+\",b=\"+str(b)+\" -> previous\")\n            return previous\n        previous = mergeCache.get((b,a), None)\n        if previous is not None:\n            if _trace_atn_sim: print(\"mergeArrays a=\"+str(a)+\",b=\"+str(b)+\" -> previous\")\n            return previous\n\n    # merge sorted payloads a + b => M\n    i = 0 # walks a\n    j = 0 # walks b\n    k = 0 # walks target M array\n\n    mergedReturnStates = [None] * (len(a.returnStates) + len( b.returnStates))\n    mergedParents = [None] * len(mergedReturnStates)\n    # walk and merge to yield mergedParents, mergedReturnStates\n    while i<len(a.returnStates) and j<len(b.returnStates):\n        a_parent = a.parents[i]\n        b_parent = b.parents[j]\n        if a.returnStates[i]==b.returnStates[j]:\n            # same payload (stack tops are equal), must yield merged singleton\n            payload = a.returnStates[i]\n            # $+$ = $\n            bothDollars = payload == PredictionContext.EMPTY_RETURN_STATE and \\\n                            a_parent is None and b_parent is None\n            ax_ax = (a_parent is not None and b_parent is not None) and a_parent==b_parent # ax+ax -> ax\n            if bothDollars or ax_ax:\n                mergedParents[k] = a_parent # choose left\n                mergedReturnStates[k] = payload\n            else: # ax+ay -> a'[x,y]\n                mergedParent = merge(a_parent, b_parent, rootIsWildcard, mergeCache)\n                mergedParents[k] = mergedParent\n                mergedReturnStates[k] = payload\n            i += 1 # hop over left one as usual\n            j += 1 # but also skip one in right side since we merge\n        elif a.returnStates[i]<b.returnStates[j]: # copy a[i] to M\n            mergedParents[k] = a_parent\n            mergedReturnStates[k] = a.returnStates[i]\n            i += 1\n        else: # b > a, copy b[j] to M\n            mergedParents[k] = b_parent\n            mergedReturnStates[k] = b.returnStates[j]\n            j += 1\n        k += 1\n\n    # copy over any payloads remaining in either array\n    if i < len(a.returnStates):\n        for p in range(i, len(a.returnStates)):\n            mergedParents[k] = a.parents[p]\n            mergedReturnStates[k] = a.returnStates[p]\n            k += 1\n    else:\n        for p in range(j, len(b.returnStates)):\n            mergedParents[k] = b.parents[p]\n            mergedReturnStates[k] = b.returnStates[p]\n            k += 1\n\n    # trim merged if we combined a few that had same stack tops\n    if k < len(mergedParents): # write index < last position; trim\n        if k == 1: # for just one merged element, return singleton top\n            merged = SingletonPredictionContext.create(mergedParents[0], mergedReturnStates[0])\n            if mergeCache is not None:\n                mergeCache[(a,b)] = merged\n            return merged\n        mergedParents = mergedParents[0:k]\n        mergedReturnStates = mergedReturnStates[0:k]\n\n    merged = ArrayPredictionContext(mergedParents, mergedReturnStates)\n\n    # if we created same array as a or b, return that instead\n    # TODO: track whether this is possible above during merge sort for speed\n    if merged==a:\n        if mergeCache is not None:\n            mergeCache[(a,b)] = a\n        if _trace_atn_sim: print(\"mergeArrays a=\"+str(a)+\",b=\"+str(b)+\" -> a\")\n        return a\n    if merged==b:\n        if mergeCache is not None:\n            mergeCache[(a,b)] = b\n        if _trace_atn_sim: print(\"mergeArrays a=\"+str(a)+\",b=\"+str(b)+\" -> b\")\n        return b\n    combineCommonParents(mergedParents)\n\n    if mergeCache is not None:\n        mergeCache[(a,b)] = merged\n\n    if _trace_atn_sim: print(\"mergeArrays a=\"+str(a)+\",b=\"+str(b)+\" -> \"+str(M))\n\n    return merged\n\n\n#\n# Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}\n# ones.\n#/\ndef combineCommonParents(parents:list):\n    uniqueParents = dict()\n\n    for p in range(0, len(parents)):\n        parent = parents[p]\n        if uniqueParents.get(parent, None) is None:\n            uniqueParents[parent] = parent\n\n    for p in range(0, len(parents)):\n        parents[p] = uniqueParents[parents[p]]\n\ndef getCachedPredictionContext(context:PredictionContext, contextCache:PredictionContextCache, visited:dict):\n    if context.isEmpty():\n        return context\n    existing = visited.get(context)\n    if existing is not None:\n        return existing\n    existing = contextCache.get(context)\n    if existing is not None:\n        visited[context] = existing\n        return existing\n    changed = False\n    parents = [None] * len(context)\n    for i in range(0, len(parents)):\n        parent = getCachedPredictionContext(context.getParent(i), contextCache, visited)\n        if changed or parent is not context.getParent(i):\n            if not changed:\n                parents = [context.getParent(j) for j in range(len(context))]\n                changed = True\n            parents[i] = parent\n    if not changed:\n        contextCache.add(context)\n        visited[context] = context\n        return context\n\n    updated = None\n    if len(parents) == 0:\n        updated = PredictionContext.EMPTY\n    elif len(parents) == 1:\n        updated = SingletonPredictionContext.create(parents[0], context.getReturnState(0))\n    else:\n        updated = ArrayPredictionContext(parents, context.returnStates)\n\n    contextCache.add(updated)\n    visited[updated] = updated\n    visited[context] = updated\n\n    return updated\n\n\n#\t# extra structures, but cut/paste/morphed works, so leave it.\n#\t# seems to do a breadth-first walk\n#\tpublic static List<PredictionContext> getAllNodes(PredictionContext context) {\n#\t\tMap<PredictionContext, PredictionContext> visited =\n#\t\t\tnew IdentityHashMap<PredictionContext, PredictionContext>();\n#\t\tDeque<PredictionContext> workList = new ArrayDeque<PredictionContext>();\n#\t\tworkList.add(context);\n#\t\tvisited.put(context, context);\n#\t\tList<PredictionContext> nodes = new ArrayList<PredictionContext>();\n#\t\twhile (!workList.isEmpty()) {\n#\t\t\tPredictionContext current = workList.pop();\n#\t\t\tnodes.add(current);\n#\t\t\tfor (int i = 0; i < current.size(); i++) {\n#\t\t\t\tPredictionContext parent = current.getParent(i);\n#\t\t\t\tif ( parent!=null && visited.put(parent, parent) == null) {\n#\t\t\t\t\tworkList.push(parent);\n#\t\t\t\t}\n#\t\t\t}\n#\t\t}\n#\t\treturn nodes;\n#\t}\n\n# ter's recursive version of Sam's getAllNodes()\ndef getAllContextNodes(context:PredictionContext, nodes:list=None, visited:dict=None):\n    if nodes is None:\n        nodes = list()\n        return getAllContextNodes(context, nodes, visited)\n    elif visited is None:\n        visited = dict()\n        return getAllContextNodes(context, nodes, visited)\n    else:\n        if context is None or visited.get(context, None) is not None:\n            return nodes\n        visited.put(context, context)\n        nodes.add(context)\n        for i in range(0, len(context)):\n            getAllContextNodes(context.getParent(i), nodes, visited)\n        return nodes\n\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/Recognizer.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\nfrom .RuleContext import RuleContext\nfrom .Token import Token\nfrom .error.ErrorListener import ProxyErrorListener, ConsoleErrorListener\n\n# need forward delcaration\nRecognitionException = None\n\nclass Recognizer(object):\n    __slots__ = ('_listeners', '_interp', '_stateNumber')\n\n    tokenTypeMapCache = dict()\n    ruleIndexMapCache = dict()\n\n    def __init__(self):\n        self._listeners = [ ConsoleErrorListener.INSTANCE ]\n        self._interp = None\n        self._stateNumber = -1\n\n    def extractVersion(self, version):\n        pos = version.find(\".\")\n        major = version[0:pos]\n        version = version[pos+1:]\n        pos = version.find(\".\")\n        if pos==-1:\n            pos = version.find(\"-\")\n        if pos==-1:\n            pos = len(version)\n        minor = version[0:pos]\n        return major, minor\n\n    def checkVersion(self, toolVersion):\n        runtimeVersion = \"4.13.2\"\n        rvmajor, rvminor = self.extractVersion(runtimeVersion)\n        tvmajor, tvminor = self.extractVersion(toolVersion)\n        if rvmajor!=tvmajor or rvminor!=tvminor:\n            print(\"ANTLR runtime and generated code versions disagree: \"+runtimeVersion+\"!=\"+toolVersion)\n\n    def addErrorListener(self, listener):\n        self._listeners.append(listener)\n\n    def removeErrorListener(self, listener):\n        self._listeners.remove(listener)\n\n    def removeErrorListeners(self):\n        self._listeners = []\n\n    def getTokenTypeMap(self):\n        tokenNames = self.getTokenNames()\n        if tokenNames is None:\n            from .error.Errors import UnsupportedOperationException\n            raise UnsupportedOperationException(\"The current recognizer does not provide a list of token names.\")\n        result = self.tokenTypeMapCache.get(tokenNames, None)\n        if result is None:\n            result = zip( tokenNames, range(0, len(tokenNames)))\n            result[\"EOF\"] = Token.EOF\n            self.tokenTypeMapCache[tokenNames] = result\n        return result\n\n    # Get a map from rule names to rule indexes.\n    #\n    # <p>Used for XPath and tree pattern compilation.</p>\n    #\n    def getRuleIndexMap(self):\n        ruleNames = self.getRuleNames()\n        if ruleNames is None:\n            from .error.Errors import UnsupportedOperationException\n            raise UnsupportedOperationException(\"The current recognizer does not provide a list of rule names.\")\n        result = self.ruleIndexMapCache.get(ruleNames, None)\n        if result is None:\n            result = zip( ruleNames, range(0, len(ruleNames)))\n            self.ruleIndexMapCache[ruleNames] = result\n        return result\n\n    def getTokenType(self, tokenName:str):\n        ttype = self.getTokenTypeMap().get(tokenName, None)\n        if ttype is not None:\n            return ttype\n        else:\n            return Token.INVALID_TYPE\n\n\n    # What is the error header, normally line/character position information?#\n    def getErrorHeader(self, e:RecognitionException):\n        line = e.getOffendingToken().line\n        column = e.getOffendingToken().column\n        return \"line \"+line+\":\"+column\n\n\n    # How should a token be displayed in an error message? The default\n    #  is to display just the text, but during development you might\n    #  want to have a lot of information spit out.  Override in that case\n    #  to use t.toString() (which, for CommonToken, dumps everything about\n    #  the token). This is better than forcing you to override a method in\n    #  your token objects because you don't have to go modify your lexer\n    #  so that it creates a new Java type.\n    #\n    # @deprecated This method is not called by the ANTLR 4 Runtime. Specific\n    # implementations of {@link ANTLRErrorStrategy} may provide a similar\n    # feature when necessary. For example, see\n    # {@link DefaultErrorStrategy#getTokenErrorDisplay}.\n    #\n    def getTokenErrorDisplay(self, t:Token):\n        if t is None:\n            return \"<no token>\"\n        s = t.text\n        if s is None:\n            if t.type==Token.EOF:\n                s = \"<EOF>\"\n            else:\n                s = \"<\" + str(t.type) + \">\"\n        s = s.replace(\"\\n\",\"\\\\n\")\n        s = s.replace(\"\\r\",\"\\\\r\")\n        s = s.replace(\"\\t\",\"\\\\t\")\n        return \"'\" + s + \"'\"\n\n    def getErrorListenerDispatch(self):\n        return ProxyErrorListener(self._listeners)\n\n    # subclass needs to override these if there are sempreds or actions\n    # that the ATN interp needs to execute\n    def sempred(self, localctx:RuleContext, ruleIndex:int, actionIndex:int):\n        return True\n\n    def precpred(self, localctx:RuleContext , precedence:int):\n        return True\n\n    @property\n    def state(self):\n        return self._stateNumber\n\n    # Indicate that the recognizer has changed internal state that is\n    #  consistent with the ATN state passed in.  This way we always know\n    #  where we are in the ATN as the parser goes along. The rule\n    #  context objects form a stack that lets us see the stack of\n    #  invoking rules. Combine this and we have complete ATN\n    #  configuration information.\n\n    @state.setter\n    def state(self, atnState:int):\n        self._stateNumber = atnState\n\ndel RecognitionException\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/RuleContext.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n\n#  A rule context is a record of a single rule invocation. It knows\n#  which context invoked it, if any. If there is no parent context, then\n#  naturally the invoking state is not valid.  The parent link\n#  provides a chain upwards from the current rule invocation to the root\n#  of the invocation tree, forming a stack. We actually carry no\n#  information about the rule associated with this context (except\n#  when parsing). We keep only the state number of the invoking state from\n#  the ATN submachine that invoked this. Contrast this with the s\n#  pointer inside ParserRuleContext that tracks the current state\n#  being \"executed\" for the current rule.\n#\n#  The parent contexts are useful for computing lookahead sets and\n#  getting error information.\n#\n#  These objects are used during parsing and prediction.\n#  For the special case of parsers, we use the subclass\n#  ParserRuleContext.\n#\n#  @see ParserRuleContext\n#/\nfrom io import StringIO\nfrom .tree.Tree import RuleNode, INVALID_INTERVAL, ParseTreeVisitor\nfrom .tree.Trees import Trees\n\n# need forward declarations\nRuleContext = None\nParser = None\n\nclass RuleContext(RuleNode):\n    __slots__ = ('parentCtx', 'invokingState')\n    EMPTY = None\n\n    def __init__(self, parent:RuleContext=None, invokingState:int=-1):\n        super().__init__()\n        # What context invoked this rule?\n        self.parentCtx = parent\n        # What state invoked the rule associated with this context?\n        #  The \"return address\" is the followState of invokingState\n        #  If parent is null, this should be -1.\n        self.invokingState = invokingState\n\n\n    def depth(self):\n        n = 0\n        p = self\n        while p is not None:\n            p = p.parentCtx\n            n += 1\n        return n\n\n    # A context is empty if there is no invoking state; meaning nobody call\n    #  current context.\n    def isEmpty(self):\n        return self.invokingState == -1\n\n    # satisfy the ParseTree / SyntaxTree interface\n\n    def getSourceInterval(self):\n        return INVALID_INTERVAL\n\n    def getRuleContext(self):\n        return self\n\n    def getPayload(self):\n        return self\n\n   # Return the combined text of all child nodes. This method only considers\n    #  tokens which have been added to the parse tree.\n    #  <p>\n    #  Since tokens on hidden channels (e.g. whitespace or comments) are not\n    #  added to the parse trees, they will not appear in the output of this\n    #  method.\n    #/\n    def getText(self):\n        if self.getChildCount() == 0:\n            return \"\"\n        with StringIO() as builder:\n            for child in self.getChildren():\n                builder.write(child.getText())\n            return builder.getvalue()\n\n    def getRuleIndex(self):\n        return -1\n\n    # For rule associated with this parse tree internal node, return\n    # the outer alternative number used to match the input. Default\n    # implementation does not compute nor store this alt num. Create\n    # a subclass of ParserRuleContext with backing field and set\n    # option contextSuperClass.\n    # to set it.\n    def getAltNumber(self):\n        return 0 # should use ATN.INVALID_ALT_NUMBER but won't compile\n\n    # Set the outer alternative number for this context node. Default\n    # implementation does nothing to avoid backing field overhead for\n    # trees that don't need it.  Create\n    # a subclass of ParserRuleContext with backing field and set\n    # option contextSuperClass.\n    def setAltNumber(self, altNumber:int):\n        pass\n\n    def getChild(self, i:int):\n        return None\n\n    def getChildCount(self):\n        return 0\n\n    def getChildren(self):\n        for c in []:\n            yield c\n\n    def accept(self, visitor:ParseTreeVisitor):\n        return visitor.visitChildren(self)\n\n   # # Call this method to view a parse tree in a dialog box visually.#/\n   #  public Future<JDialog> inspect(@Nullable Parser parser) {\n   #      List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;\n   #      return inspect(ruleNames);\n   #  }\n   #\n   #  public Future<JDialog> inspect(@Nullable List<String> ruleNames) {\n   #      TreeViewer viewer = new TreeViewer(ruleNames, this);\n   #      return viewer.open();\n   #  }\n   #\n   # # Save this tree in a postscript file#/\n   #  public void save(@Nullable Parser parser, String fileName)\n   #      throws IOException, PrintException\n   #  {\n   #      List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;\n   #      save(ruleNames, fileName);\n   #  }\n   #\n   # # Save this tree in a postscript file using a particular font name and size#/\n   #  public void save(@Nullable Parser parser, String fileName,\n   #                   String fontName, int fontSize)\n   #      throws IOException\n   #  {\n   #      List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;\n   #      save(ruleNames, fileName, fontName, fontSize);\n   #  }\n   #\n   # # Save this tree in a postscript file#/\n   #  public void save(@Nullable List<String> ruleNames, String fileName)\n   #      throws IOException, PrintException\n   #  {\n   #      Trees.writePS(this, ruleNames, fileName);\n   #  }\n   #\n   # # Save this tree in a postscript file using a particular font name and size#/\n   #  public void save(@Nullable List<String> ruleNames, String fileName,\n   #                   String fontName, int fontSize)\n   #      throws IOException\n   #  {\n   #      Trees.writePS(this, ruleNames, fileName, fontName, fontSize);\n   #  }\n   #\n   # # Print out a whole tree, not just a node, in LISP format\n   #  #  (root child1 .. childN). Print just a node if this is a leaf.\n   #  #  We have to know the recognizer so we can get rule names.\n   #  #/\n   #  @Override\n   #  public String toStringTree(@Nullable Parser recog) {\n   #      return Trees.toStringTree(this, recog);\n   #  }\n   #\n   # Print out a whole tree, not just a node, in LISP format\n   #  (root child1 .. childN). Print just a node if this is a leaf.\n   #\n    def toStringTree(self, ruleNames:list=None, recog:Parser=None):\n        return Trees.toStringTree(self, ruleNames=ruleNames, recog=recog)\n   #  }\n   #\n   #  @Override\n   #  public String toStringTree() {\n   #      return toStringTree((List<String>)null);\n   #  }\n   #\n    def __str__(self):\n        return self.toString(None, None)\n\n   #  @Override\n   #  public String toString() {\n   #      return toString((List<String>)null, (RuleContext)null);\n   #  }\n   #\n   #  public final String toString(@Nullable Recognizer<?,?> recog) {\n   #      return toString(recog, ParserRuleContext.EMPTY);\n   #  }\n   #\n   #  public final String toString(@Nullable List<String> ruleNames) {\n   #      return toString(ruleNames, null);\n   #  }\n   #\n   #  // recog null unless ParserRuleContext, in which case we use subclass toString(...)\n   #  public String toString(@Nullable Recognizer<?,?> recog, @Nullable RuleContext stop) {\n   #      String[] ruleNames = recog != null ? recog.getRuleNames() : null;\n   #      List<String> ruleNamesList = ruleNames != null ? Arrays.asList(ruleNames) : null;\n   #      return toString(ruleNamesList, stop);\n   #  }\n\n    def toString(self, ruleNames:list, stop:RuleContext)->str:\n        with StringIO() as buf:\n            p = self\n            buf.write(\"[\")\n            while p is not None and p is not stop:\n                if ruleNames is None:\n                    if not p.isEmpty():\n                        buf.write(str(p.invokingState))\n                else:\n                    ri = p.getRuleIndex()\n                    ruleName = ruleNames[ri] if ri >= 0 and ri < len(ruleNames) else str(ri)\n                    buf.write(ruleName)\n\n                if p.parentCtx is not None and (ruleNames is not None or not p.parentCtx.isEmpty()):\n                    buf.write(\" \")\n\n                p = p.parentCtx\n\n            buf.write(\"]\")\n            return buf.getvalue()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/StdinStream.py",
    "content": "import codecs\nimport sys\n\nfrom .InputStream import InputStream\n\n\nclass StdinStream(InputStream):\n    def __init__(self, encoding:str='ascii', errors:str='strict') -> None:\n        bytes = sys.stdin.buffer.read()\n        data = codecs.decode(bytes, encoding, errors)\n        super().__init__(data)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/Token.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n# A token has properties: text, type, line, character position in the line\n# (so we can ignore tabs), token channel, index, and source from which\n# we obtained this token.\nfrom io import StringIO\n\n\nclass Token (object):\n    __slots__ = ('source', 'type', 'channel', 'start', 'stop', 'tokenIndex', 'line', 'column', '_text')\n\n    INVALID_TYPE = 0\n\n    # During lookahead operations, this \"token\" signifies we hit rule end ATN state\n    # and did not follow it despite needing to.\n    EPSILON = -2\n\n    MIN_USER_TOKEN_TYPE = 1\n\n    EOF = -1\n\n    # All tokens go to the parser (unless skip() is called in that rule)\n    # on a particular \"channel\".  The parser tunes to a particular channel\n    # so that whitespace etc... can go to the parser on a \"hidden\" channel.\n\n    DEFAULT_CHANNEL = 0\n\n    # Anything on different channel than DEFAULT_CHANNEL is not parsed\n    # by parser.\n\n    HIDDEN_CHANNEL = 1\n\n    def __init__(self):\n        self.source = None\n        self.type = None # token type of the token\n        self.channel = None # The parser ignores everything not on DEFAULT_CHANNEL\n        self.start = None # optional; return -1 if not implemented.\n        self.stop = None  # optional; return -1 if not implemented.\n        self.tokenIndex = None # from 0..n-1 of the token object in the input stream\n        self.line = None # line=1..n of the 1st character\n        self.column = None # beginning of the line at which it occurs, 0..n-1\n        self._text = None # text of the token.\n\n    @property\n    def text(self):\n        return self._text\n\n    # Explicitly set the text for this token. If {code text} is not\n    # {@code null}, then {@link #getText} will return this value rather than\n    # extracting the text from the input.\n    #\n    # @param text The explicit text of the token, or {@code null} if the text\n    # should be obtained from the input along with the start and stop indexes\n    # of the token.\n\n    @text.setter\n    def text(self, text:str):\n        self._text = text\n\n\n    def getTokenSource(self):\n        return self.source[0]\n\n    def getInputStream(self):\n        return self.source[1]\n\nclass CommonToken(Token):\n\n    # An empty {@link Pair} which is used as the default value of\n    # {@link #source} for tokens that do not have a source.\n    EMPTY_SOURCE = (None, None)\n\n    def __init__(self, source:tuple = EMPTY_SOURCE, type:int = None, channel:int=Token.DEFAULT_CHANNEL, start:int=-1, stop:int=-1):\n        super().__init__()\n        self.source = source\n        self.type = type\n        self.channel = channel\n        self.start = start\n        self.stop = stop\n        self.tokenIndex = -1\n        if source[0] is not None:\n            self.line = source[0].line\n            self.column = source[0].column\n        else:\n            self.column = -1\n\n    # Constructs a new {@link CommonToken} as a copy of another {@link Token}.\n    #\n    # <p>\n    # If {@code oldToken} is also a {@link CommonToken} instance, the newly\n    # constructed token will share a reference to the {@link #text} field and\n    # the {@link Pair} stored in {@link #source}. Otherwise, {@link #text} will\n    # be assigned the result of calling {@link #getText}, and {@link #source}\n    # will be constructed from the result of {@link Token#getTokenSource} and\n    # {@link Token#getInputStream}.</p>\n    #\n    # @param oldToken The token to copy.\n     #\n    def clone(self):\n        t = CommonToken(self.source, self.type, self.channel, self.start, self.stop)\n        t.tokenIndex = self.tokenIndex\n        t.line = self.line\n        t.column = self.column\n        t.text = self.text\n        return t\n\n    @property\n    def text(self):\n        if self._text is not None:\n            return self._text\n        input = self.getInputStream()\n        if input is None:\n            return None\n        n = input.size\n        if self.start < n and self.stop < n:\n            return input.getText(self.start, self.stop)\n        else:\n            return \"<EOF>\"\n\n    @text.setter\n    def text(self, text:str):\n        self._text = text\n\n    def __str__(self):\n        with StringIO() as buf:\n            buf.write(\"[@\")\n            buf.write(str(self.tokenIndex))\n            buf.write(\",\")\n            buf.write(str(self.start))\n            buf.write(\":\")\n            buf.write(str(self.stop))\n            buf.write(\"='\")\n            txt = self.text\n            if txt is not None:\n                txt = txt.replace(\"\\n\",\"\\\\n\")\n                txt = txt.replace(\"\\r\",\"\\\\r\")\n                txt = txt.replace(\"\\t\",\"\\\\t\")\n            else:\n                txt = \"<no text>\"\n            buf.write(txt)\n            buf.write(\"',<\")\n            buf.write(str(self.type))\n            buf.write(\">\")\n            if self.channel > 0:\n                buf.write(\",channel=\")\n                buf.write(str(self.channel))\n            buf.write(\",\")\n            buf.write(str(self.line))\n            buf.write(\":\")\n            buf.write(str(self.column))\n            buf.write(\"]\")\n            return buf.getvalue()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/TokenStreamRewriter.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\nfrom io import StringIO\nfrom .Token import Token\n\nfrom .CommonTokenStream import CommonTokenStream\n\n\nclass TokenStreamRewriter(object):\n    __slots__ = ('tokens', 'programs', 'lastRewriteTokenIndexes')\n\n    DEFAULT_PROGRAM_NAME = \"default\"\n    PROGRAM_INIT_SIZE = 100\n    MIN_TOKEN_INDEX = 0\n\n    def __init__(self, tokens):\n        \"\"\"\n        :type  tokens: antlr4.BufferedTokenStream.BufferedTokenStream\n        :param tokens:\n        :return:\n        \"\"\"\n        super(TokenStreamRewriter, self).__init__()\n        self.tokens = tokens\n        self.programs = {self.DEFAULT_PROGRAM_NAME: []}\n        self.lastRewriteTokenIndexes = {}\n\n    def getTokenStream(self):\n        return self.tokens\n\n    def rollback(self, instruction_index, program_name):\n        ins = self.programs.get(program_name, None)\n        if ins:\n            self.programs[program_name] = ins[self.MIN_TOKEN_INDEX: instruction_index]\n\n    def deleteProgram(self, program_name=DEFAULT_PROGRAM_NAME):\n        self.rollback(self.MIN_TOKEN_INDEX, program_name)\n\n    def insertAfterToken(self, token, text, program_name=DEFAULT_PROGRAM_NAME):\n        self.insertAfter(token.tokenIndex, text, program_name)\n\n    def insertAfter(self, index, text, program_name=DEFAULT_PROGRAM_NAME):\n        op = self.InsertAfterOp(self.tokens, index + 1, text)\n        rewrites = self.getProgram(program_name)\n        op.instructionIndex = len(rewrites)\n        rewrites.append(op)\n\n    def insertBeforeIndex(self, index, text):\n        self.insertBefore(self.DEFAULT_PROGRAM_NAME, index, text)\n\n    def insertBeforeToken(self, token, text, program_name=DEFAULT_PROGRAM_NAME):\n        self.insertBefore(program_name, token.tokenIndex, text)\n\n    def insertBefore(self, program_name, index, text):\n        op = self.InsertBeforeOp(self.tokens, index, text)\n        rewrites = self.getProgram(program_name)\n        op.instructionIndex = len(rewrites)\n        rewrites.append(op)\n\n    def replaceIndex(self, index, text):\n        self.replace(self.DEFAULT_PROGRAM_NAME, index, index, text)\n\n    def replaceRange(self, from_idx, to_idx, text):\n        self.replace(self.DEFAULT_PROGRAM_NAME, from_idx, to_idx, text)\n\n    def replaceSingleToken(self, token, text):\n        self.replace(self.DEFAULT_PROGRAM_NAME, token.tokenIndex, token.tokenIndex, text)\n\n    def replaceRangeTokens(self, from_token, to_token, text, program_name=DEFAULT_PROGRAM_NAME):\n        self.replace(program_name, from_token.tokenIndex, to_token.tokenIndex, text)\n\n    def replace(self, program_name, from_idx, to_idx, text):\n        if any((from_idx > to_idx, from_idx < 0, to_idx < 0, to_idx >= len(self.tokens.tokens))):\n            raise ValueError(\n                'replace: range invalid: {}..{}(size={})'.format(from_idx, to_idx, len(self.tokens.tokens)))\n        op = self.ReplaceOp(from_idx, to_idx, self.tokens, text)\n        rewrites = self.getProgram(program_name)\n        op.instructionIndex = len(rewrites)\n        rewrites.append(op)\n\n    def deleteToken(self, token):\n        self.delete(self.DEFAULT_PROGRAM_NAME, token, token)\n\n    def deleteIndex(self, index):\n        self.delete(self.DEFAULT_PROGRAM_NAME, index, index)\n\n    def delete(self, program_name, from_idx, to_idx):\n        if isinstance(from_idx, Token):\n            self.replace(program_name, from_idx.tokenIndex, to_idx.tokenIndex, \"\")\n        else:\n            self.replace(program_name, from_idx, to_idx, \"\")\n\n    def lastRewriteTokenIndex(self, program_name=DEFAULT_PROGRAM_NAME):\n        return self.lastRewriteTokenIndexes.get(program_name, -1)\n\n    def setLastRewriteTokenIndex(self, program_name, i):\n        self.lastRewriteTokenIndexes[program_name] = i\n\n    def getProgram(self, program_name):\n        return self.programs.setdefault(program_name, [])\n\n    def getDefaultText(self):\n        return self.getText(self.DEFAULT_PROGRAM_NAME, 0, len(self.tokens.tokens) - 1)\n\n    def getText(self, program_name, start:int, stop:int):\n        \"\"\"\n        :return: the text in tokens[start, stop](closed interval)\n        \"\"\"\n        rewrites = self.programs.get(program_name)\n\n        # ensure start/end are in range\n        if stop > len(self.tokens.tokens) - 1:\n            stop = len(self.tokens.tokens) - 1\n        if start < 0:\n            start = 0\n\n        # if no instructions to execute\n        if not rewrites: return self.tokens.getText(start, stop)\n        buf = StringIO()\n        indexToOp = self._reduceToSingleOperationPerIndex(rewrites)\n        i = start\n        while all((i <= stop, i < len(self.tokens.tokens))):\n            op = indexToOp.pop(i, None)\n            token = self.tokens.get(i)\n            if op is None:\n                if token.type != Token.EOF: buf.write(token.text)\n                i += 1\n            else:\n                i = op.execute(buf)\n\n        if stop == len(self.tokens.tokens)-1:\n            for op in indexToOp.values():\n                if op.index >= len(self.tokens.tokens)-1: buf.write(op.text)\n\n        return buf.getvalue()\n\n    def _reduceToSingleOperationPerIndex(self, rewrites):\n        # Walk replaces\n        for i, rop in enumerate(rewrites):\n            if any((rop is None, not isinstance(rop, TokenStreamRewriter.ReplaceOp))):\n                continue\n            # Wipe prior inserts within range\n            inserts = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.InsertBeforeOp)]\n            for iop in inserts:\n                if iop.index == rop.index:\n                    rewrites[iop.instructionIndex] = None\n                    rop.text = '{}{}'.format(iop.text, rop.text)\n                elif all((iop.index > rop.index, iop.index <= rop.last_index)):\n                    rewrites[iop.instructionIndex] = None\n\n            # Drop any prior replaces contained within\n            prevReplaces = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.ReplaceOp)]\n            for prevRop in prevReplaces:\n                if all((prevRop.index >= rop.index, prevRop.last_index <= rop.last_index)):\n                    rewrites[prevRop.instructionIndex] = None\n                    continue\n                isDisjoint = any((prevRop.last_index<rop.index, prevRop.index>rop.last_index))\n                if all((prevRop.text is None, rop.text is None, not isDisjoint)):\n                    rewrites[prevRop.instructionIndex] = None\n                    rop.index = min(prevRop.index, rop.index)\n                    rop.last_index = min(prevRop.last_index, rop.last_index)\n                    print('New rop {}'.format(rop))\n                elif (not(isDisjoint)):\n                    raise ValueError(\"replace op boundaries of {} overlap with previous {}\".format(rop, prevRop))\n\n        # Walk inserts\n        for i, iop in enumerate(rewrites):\n            if any((iop is None, not isinstance(iop, TokenStreamRewriter.InsertBeforeOp))):\n                continue\n            prevInserts = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.InsertBeforeOp)]\n            for prev_index, prevIop in enumerate(prevInserts):\n                if prevIop.index == iop.index and type(prevIop) is TokenStreamRewriter.InsertBeforeOp:\n                    iop.text += prevIop.text\n                    rewrites[prev_index] = None\n                elif prevIop.index == iop.index and type(prevIop) is TokenStreamRewriter.InsertAfterOp:\n                    iop.text = prevIop.text + iop.text\n                    rewrites[prev_index] = None\n            # look for replaces where iop.index is in range; error\n            prevReplaces = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.ReplaceOp)]\n            for rop in prevReplaces:\n                if iop.index == rop.index:\n                    rop.text = iop.text + rop.text\n                    rewrites[i] = None\n                    continue\n                if all((iop.index >= rop.index, iop.index <= rop.last_index)):\n                    raise ValueError(\"insert op {} within boundaries of previous {}\".format(iop, rop))\n\n        reduced = {}\n        for i, op in enumerate(rewrites):\n            if op is None: continue\n            if reduced.get(op.index): raise ValueError('should be only one op per index')\n            reduced[op.index] = op\n\n        return reduced\n\n    class RewriteOperation(object):\n        __slots__ = ('tokens', 'index', 'text', 'instructionIndex')\n\n        def __init__(self, tokens, index, text=\"\"):\n            \"\"\"\n            :type tokens: CommonTokenStream\n            :param tokens:\n            :param index:\n            :param text:\n            :return:\n            \"\"\"\n            self.tokens = tokens\n            self.index = index\n            self.text = text\n            self.instructionIndex = 0\n\n        def execute(self, buf):\n            \"\"\"\n            :type buf: StringIO.StringIO\n            :param buf:\n            :return:\n            \"\"\"\n            return self.index\n\n        def __str__(self):\n            return '<{}@{}:\"{}\">'.format(self.__class__.__name__, self.tokens.get(self.index), self.text)\n\n    class InsertBeforeOp(RewriteOperation):\n\n        def __init__(self, tokens, index, text=\"\"):\n            super(TokenStreamRewriter.InsertBeforeOp, self).__init__(tokens, index, text)\n\n        def execute(self, buf):\n            buf.write(self.text)\n            if self.tokens.get(self.index).type != Token.EOF:\n                buf.write(self.tokens.get(self.index).text)\n            return self.index + 1\n\n    class InsertAfterOp(InsertBeforeOp):\n        pass\n\n    class ReplaceOp(RewriteOperation):\n        __slots__ = 'last_index'\n\n        def __init__(self, from_idx, to_idx, tokens, text):\n            super(TokenStreamRewriter.ReplaceOp, self).__init__(tokens, from_idx, text)\n            self.last_index = to_idx\n\n        def execute(self, buf):\n            if self.text:\n                buf.write(self.text)\n            return self.last_index + 1\n\n        def __str__(self):\n            if self.text:\n                return '<ReplaceOp@{}..{}:\"{}\">'.format(self.tokens.get(self.index), self.tokens.get(self.last_index),\n                                                        self.text)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/Utils.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\nfrom io import StringIO\n\ndef str_list(val):\n    with StringIO() as buf:\n        buf.write('[')\n        first = True\n        for item in val:\n            if not first:\n                buf.write(', ')\n            buf.write(str(item))\n            first = False\n        buf.write(']')\n        return buf.getvalue()\n\ndef escapeWhitespace(s:str, escapeSpaces:bool):\n    with StringIO() as buf:\n        for c in s:\n            if c==' ' and escapeSpaces:\n                buf.write('\\u00B7')\n            elif c=='\\t':\n                buf.write(\"\\\\t\")\n            elif c=='\\n':\n                buf.write(\"\\\\n\")\n            elif c=='\\r':\n                buf.write(\"\\\\r\")\n            else:\n                buf.write(c)\n        return buf.getvalue()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/__init__.py",
    "content": "from .Token import Token\nfrom .InputStream import InputStream\nfrom .FileStream import FileStream\nfrom .StdinStream import StdinStream\nfrom .BufferedTokenStream import TokenStream\nfrom .CommonTokenStream import CommonTokenStream\nfrom .Lexer import Lexer\nfrom .Parser import Parser\nfrom .dfa.DFA import DFA\nfrom .atn.ATN import ATN\nfrom .atn.ATNDeserializer import ATNDeserializer\nfrom .atn.LexerATNSimulator import LexerATNSimulator\nfrom .atn.ParserATNSimulator import ParserATNSimulator\nfrom .atn.PredictionMode import PredictionMode\nfrom .PredictionContext import PredictionContextCache\nfrom .ParserRuleContext import RuleContext, ParserRuleContext\nfrom .tree.Tree import ParseTreeListener, ParseTreeVisitor, ParseTreeWalker, TerminalNode, ErrorNode, RuleNode\nfrom .error.Errors import RecognitionException, IllegalStateException, NoViableAltException\nfrom .error.ErrorStrategy import BailErrorStrategy\nfrom .error.DiagnosticErrorListener import DiagnosticErrorListener\nfrom .Utils import str_list\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/_pygrun.py",
    "content": "__author__ = 'jszheng'\nimport optparse\nimport sys\nimport os\n\nfrom . import *\n\n\n# this is a python version of TestRig\ndef beautify_lisp_string(in_string):\n    indent_size = 3\n    add_indent = ' '*indent_size\n    out_string = in_string[0]  # no indent for 1st (\n    indent = ''\n    for i in range(1, len(in_string)):\n        if in_string[i] == '(' and in_string[i+1] != ' ':\n            indent += add_indent\n            out_string += \"\\n\" + indent + '('\n        elif in_string[i] == ')':\n            out_string += ')'\n            if len(indent) > 0:\n                indent = indent.replace(add_indent, '', 1)\n        else:\n            out_string += in_string[i]\n    return out_string\n\n\ndef main():\n\n    #############################################################\n    # parse options\n    # not support -gui -encoding -ps\n    #############################################################\n    usage = \"Usage: %prog [options] Grammar_Name Start_Rule\"\n    parser = optparse.OptionParser(usage=usage)\n    # parser.add_option('-t', '--tree',\n    #                   dest=\"out_file\",\n    #                   default=\"default.out\",\n    #                   help='set output file name',\n    #                   )\n    parser.add_option('-t', '--tree',\n                      default=False,\n                      action='store_true',\n                      help='Print AST tree'\n                      )\n    parser.add_option('-k', '--tokens',\n                      dest=\"token\",\n                      default=False,\n                      action='store_true',\n                      help='Show Tokens'\n                      )\n    parser.add_option('-s', '--sll',\n                      dest=\"sll\",\n                      default=False,\n                      action='store_true',\n                      help='Show SLL'\n                      )\n    parser.add_option('-d', '--diagnostics',\n                      dest=\"diagnostics\",\n                      default=False,\n                      action='store_true',\n                      help='Enable diagnostics error listener'\n                      )\n    parser.add_option('-a', '--trace',\n                      dest=\"trace\",\n                      default=False,\n                      action='store_true',\n                      help='Enable Trace'\n                      )\n\n    options, remainder = parser.parse_args()\n    if len(remainder) < 2:\n        print('ERROR: You have to provide at least 2 arguments!')\n        parser.print_help()\n        exit(1)\n    else:\n        grammar = remainder.pop(0)\n        start_rule = remainder.pop(0)\n        file_list = remainder\n\n    #############################################################\n    # check and load antlr generated files\n    #############################################################\n    # dynamic load the module and class\n    lexerName = grammar + 'Lexer'\n    parserName = grammar + 'Parser'\n    # check if the generate file exist\n    lexer_file = lexerName + '.py'\n    parser_file = parserName + '.py'\n    if not os.path.exists(lexer_file):\n        print(\"[ERROR] Can't find lexer file {}!\".format(lexer_file))\n        print(os.path.realpath('.'))\n        exit(1)\n    if not os.path.exists(parser_file):\n        print(\"[ERROR] Can't find parser file {}!\".format(lexer_file))\n        print(os.path.realpath('.'))\n        exit(1)\n\n    # current directory is where the generated file loaded\n    # the script might be in different place.\n    sys.path.append('.')\n    # print(sys.path)\n\n    # add current directory to python global namespace in case of relative imports\n    globals().update({'__package__': os.path.basename(os.getcwd())})\n\n    # print(\"Load Lexer {}\".format(lexerName))\n    module_lexer = __import__(lexerName, globals(), locals(), lexerName)\n    class_lexer = getattr(module_lexer, lexerName)\n    # print(class_lexer)\n\n    # print(\"Load Parser {}\".format(parserName))\n    module_parser = __import__(parserName, globals(), locals(), parserName)\n    class_parser = getattr(module_parser, parserName)\n    # print(class_parser)\n\n    #############################################################\n    # main process steps.\n    #############################################################\n    def process(input_stream, class_lexer, class_parser):\n        lexer = class_lexer(input_stream)\n        token_stream = CommonTokenStream(lexer)\n        token_stream.fill()\n        if options.token:  # need to show token\n            for tok in token_stream.tokens:\n                print(tok)\n        if start_rule == 'tokens':\n            return\n\n        parser = class_parser(token_stream)\n\n        if options.diagnostics:\n            parser.addErrorListener(DiagnosticErrorListener())\n            parser._interp.predictionMode = PredictionMode.LL_EXACT_AMBIG_DETECTION\n        if options.tree:\n            parser.buildParseTrees = True\n        if options.sll:\n            parser._interp.predictionMode = PredictionMode.SLL\n        #parser.setTokenStream(token_stream)\n        parser.setTrace(options.trace)\n        if hasattr(parser, start_rule):\n            func_start_rule = getattr(parser, start_rule)\n            parser_ret = func_start_rule()\n            if options.tree:\n                lisp_tree_str = parser_ret.toStringTree(recog=parser)\n                print(beautify_lisp_string(lisp_tree_str))\n        else:\n            print(\"[ERROR] Can't find start rule '{}' in parser '{}'\".format(start_rule, parserName))\n\n    #############################################################\n    # use stdin if not provide file as input stream\n    #############################################################\n    if len(file_list) == 0:\n        input_stream = InputStream(sys.stdin.read())\n        process(input_stream, class_lexer, class_parser)\n        exit(0)\n\n    #############################################################\n    # iterate all input file\n    #############################################################\n    for file_name in file_list:\n        if os.path.exists(file_name) and os.path.isfile(file_name):\n            input_stream = FileStream(file_name)\n            process(input_stream, class_lexer, class_parser)\n        else:\n            print(\"[ERROR] file {} not exist\".format(os.path.normpath(file_name)))\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATN.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\nfrom ..IntervalSet import IntervalSet\n\nfrom ..RuleContext import RuleContext\n\nfrom ..Token import Token\nfrom ..atn.ATNType import ATNType\nfrom ..atn.ATNState import ATNState, DecisionState\n\n\nclass ATN(object):\n    __slots__ = (\n        'grammarType', 'maxTokenType', 'states', 'decisionToState',\n        'ruleToStartState', 'ruleToStopState', 'modeNameToStartState',\n        'ruleToTokenType', 'lexerActions', 'modeToStartState'\n    )\n\n    INVALID_ALT_NUMBER = 0\n\n    # Used for runtime deserialization of ATNs from strings#/\n    def __init__(self, grammarType:ATNType , maxTokenType:int ):\n        # The type of the ATN.\n        self.grammarType = grammarType\n        # The maximum value for any symbol recognized by a transition in the ATN.\n        self.maxTokenType = maxTokenType\n        self.states = []\n        # Each subrule/rule is a decision point and we must track them so we\n        #  can go back later and build DFA predictors for them.  This includes\n        #  all the rules, subrules, optional blocks, ()+, ()* etc...\n        self.decisionToState = []\n        # Maps from rule index to starting state number.\n        self.ruleToStartState = []\n        # Maps from rule index to stop state number.\n        self.ruleToStopState = None\n        self.modeNameToStartState = dict()\n        # For lexer ATNs, this maps the rule index to the resulting token type.\n        # For parser ATNs, this maps the rule index to the generated bypass token\n        # type if the\n        # {@link ATNDeserializationOptions#isGenerateRuleBypassTransitions}\n        # deserialization option was specified; otherwise, this is {@code null}.\n        self.ruleToTokenType = None\n        # For lexer ATNs, this is an array of {@link LexerAction} objects which may\n        # be referenced by action transitions in the ATN.\n        self.lexerActions = None\n        self.modeToStartState = []\n\n    # Compute the set of valid tokens that can occur starting in state {@code s}.\n    #  If {@code ctx} is null, the set of tokens will not include what can follow\n    #  the rule surrounding {@code s}. In other words, the set will be\n    #  restricted to tokens reachable staying within {@code s}'s rule.\n    def nextTokensInContext(self, s:ATNState, ctx:RuleContext):\n        from ..LL1Analyzer import LL1Analyzer\n        anal = LL1Analyzer(self)\n        return anal.LOOK(s, ctx=ctx)\n\n    # Compute the set of valid tokens that can occur starting in {@code s} and\n    # staying in same rule. {@link Token#EPSILON} is in set if we reach end of\n    # rule.\n    def nextTokensNoContext(self, s:ATNState):\n        if s.nextTokenWithinRule is not None:\n            return s.nextTokenWithinRule\n        s.nextTokenWithinRule = self.nextTokensInContext(s, None)\n        s.nextTokenWithinRule.readonly = True\n        return s.nextTokenWithinRule\n\n    def nextTokens(self, s:ATNState, ctx:RuleContext = None):\n        if ctx==None:\n            return self.nextTokensNoContext(s)\n        else:\n            return self.nextTokensInContext(s, ctx)\n\n    def addState(self, state:ATNState):\n        if state is not None:\n            state.atn = self\n            state.stateNumber = len(self.states)\n        self.states.append(state)\n\n    def removeState(self, state:ATNState):\n        self.states[state.stateNumber] = None # just free mem, don't shift states in list\n\n    def defineDecisionState(self, s:DecisionState):\n        self.decisionToState.append(s)\n        s.decision = len(self.decisionToState)-1\n        return s.decision\n\n    def getDecisionState(self, decision:int):\n        if len(self.decisionToState)==0:\n            return None\n        else:\n            return self.decisionToState[decision]\n\n    # Computes the set of input symbols which could follow ATN state number\n    # {@code stateNumber} in the specified full {@code context}. This method\n    # considers the complete parser context, but does not evaluate semantic\n    # predicates (i.e. all predicates encountered during the calculation are\n    # assumed true). If a path in the ATN exists from the starting state to the\n    # {@link RuleStopState} of the outermost context without matching any\n    # symbols, {@link Token#EOF} is added to the returned set.\n    #\n    # <p>If {@code context} is {@code null}, it is treated as\n    # {@link ParserRuleContext#EMPTY}.</p>\n    #\n    # @param stateNumber the ATN state number\n    # @param context the full parse context\n    # @return The set of potentially valid input symbols which could follow the\n    # specified state in the specified context.\n    # @throws IllegalArgumentException if the ATN does not contain a state with\n    # number {@code stateNumber}\n    #/\n    def getExpectedTokens(self, stateNumber:int, ctx:RuleContext ):\n        if stateNumber < 0 or stateNumber >= len(self.states):\n            raise Exception(\"Invalid state number.\")\n        s = self.states[stateNumber]\n        following = self.nextTokens(s)\n        if Token.EPSILON not in following:\n            return following\n        expected = IntervalSet()\n        expected.addSet(following)\n        expected.removeOne(Token.EPSILON)\n        while (ctx != None and ctx.invokingState >= 0 and Token.EPSILON in following):\n            invokingState = self.states[ctx.invokingState]\n            rt = invokingState.transitions[0]\n            following = self.nextTokens(rt.followState)\n            expected.addSet(following)\n            expected.removeOne(Token.EPSILON)\n            ctx = ctx.parentCtx\n        if Token.EPSILON in following:\n            expected.addOne(Token.EOF)\n        return expected\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATNConfig.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n# A tuple: (ATN state, predicted alt, syntactic, semantic context).\n#  The syntactic context is a graph-structured stack node whose\n#  path(s) to the root is the rule invocation(s)\n#  chain used to arrive at the state.  The semantic context is\n#  the tree of semantic predicates encountered before reaching\n#  an ATN state.\n#/\nfrom io import StringIO\nfrom ..PredictionContext import PredictionContext\nfrom ..atn.ATNState import ATNState, DecisionState\nfrom ..atn.LexerActionExecutor import LexerActionExecutor\nfrom ..atn.SemanticContext import SemanticContext\n\n# need a forward declaration\nATNConfig = None\n\nclass ATNConfig(object):\n    __slots__ = (\n        'state', 'alt', 'context', 'semanticContext', 'reachesIntoOuterContext',\n        'precedenceFilterSuppressed'\n    )\n\n    def __init__(self, state:ATNState=None, alt:int=None, context:PredictionContext=None, semantic:SemanticContext=None, config:ATNConfig=None):\n        if config is not None:\n            if state is None:\n                state = config.state\n            if alt is None:\n                alt = config.alt\n            if context is None:\n                context = config.context\n            if semantic is None:\n                semantic = config.semanticContext\n        if semantic is None:\n            semantic = SemanticContext.NONE\n        # The ATN state associated with this configuration#/\n        self.state = state\n        # What alt (or lexer rule) is predicted by this configuration#/\n        self.alt = alt\n        # The stack of invoking states leading to the rule/states associated\n        #  with this config.  We track only those contexts pushed during\n        #  execution of the ATN simulator.\n        self.context = context\n        self.semanticContext = semantic\n        # We cannot execute predicates dependent upon local context unless\n        # we know for sure we are in the correct context. Because there is\n        # no way to do this efficiently, we simply cannot evaluate\n        # dependent predicates unless we are in the rule that initially\n        # invokes the ATN simulator.\n        #\n        # closure() tracks the depth of how far we dip into the\n        # outer context: depth &gt; 0.  Note that it may not be totally\n        # accurate depth since I don't ever decrement. TODO: make it a boolean then\n        self.reachesIntoOuterContext = 0 if config is None else config.reachesIntoOuterContext\n        self.precedenceFilterSuppressed = False if config is None else config.precedenceFilterSuppressed\n\n    # An ATN configuration is equal to another if both have\n    #  the same state, they predict the same alternative, and\n    #  syntactic/semantic contexts are the same.\n    #/\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, ATNConfig):\n            return False\n        else:\n            return self.state.stateNumber==other.state.stateNumber \\\n                and self.alt==other.alt \\\n                and ((self.context is other.context) or (self.context==other.context)) \\\n                and self.semanticContext==other.semanticContext \\\n                and self.precedenceFilterSuppressed==other.precedenceFilterSuppressed\n\n    def __hash__(self):\n        return hash((self.state.stateNumber, self.alt, self.context, self.semanticContext))\n\n    def hashCodeForConfigSet(self):\n        return hash((self.state.stateNumber, self.alt, hash(self.semanticContext)))\n\n    def equalsForConfigSet(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, ATNConfig):\n            return False\n        else:\n            return self.state.stateNumber==other.state.stateNumber \\\n                and self.alt==other.alt \\\n                and self.semanticContext==other.semanticContext\n\n    def __str__(self):\n        with StringIO() as buf:\n            buf.write('(')\n            buf.write(str(self.state))\n            buf.write(\",\")\n            buf.write(str(self.alt))\n            if self.context is not None:\n                buf.write(\",[\")\n                buf.write(str(self.context))\n                buf.write(\"]\")\n            if self.semanticContext is not None and self.semanticContext is not SemanticContext.NONE:\n                buf.write(\",\")\n                buf.write(str(self.semanticContext))\n            if self.reachesIntoOuterContext>0:\n                buf.write(\",up=\")\n                buf.write(str(self.reachesIntoOuterContext))\n            buf.write(')')\n            return buf.getvalue()\n\n# need a forward declaration\nLexerATNConfig = None\n\nclass LexerATNConfig(ATNConfig):\n    __slots__ = ('lexerActionExecutor', 'passedThroughNonGreedyDecision')\n\n    def __init__(self, state:ATNState, alt:int=None, context:PredictionContext=None, semantic:SemanticContext=SemanticContext.NONE,\n                 lexerActionExecutor:LexerActionExecutor=None, config:LexerATNConfig=None):\n        super().__init__(state=state, alt=alt, context=context, semantic=semantic, config=config)\n        if config is not None:\n            if lexerActionExecutor is None:\n                lexerActionExecutor = config.lexerActionExecutor\n        # This is the backing field for {@link #getLexerActionExecutor}.\n        self.lexerActionExecutor = lexerActionExecutor\n        self.passedThroughNonGreedyDecision = False if config is None else self.checkNonGreedyDecision(config, state)\n\n    def __hash__(self):\n        return hash((self.state.stateNumber, self.alt, self.context,\n                self.semanticContext, self.passedThroughNonGreedyDecision,\n                self.lexerActionExecutor))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerATNConfig):\n            return False\n        if self.passedThroughNonGreedyDecision != other.passedThroughNonGreedyDecision:\n            return False\n        if not(self.lexerActionExecutor == other.lexerActionExecutor):\n            return False\n        return super().__eq__(other)\n\n\n\n    def hashCodeForConfigSet(self):\n        return hash(self)\n\n\n\n    def equalsForConfigSet(self, other):\n        return self==other\n\n\n\n    def checkNonGreedyDecision(self, source:LexerATNConfig, target:ATNState):\n        return source.passedThroughNonGreedyDecision \\\n            or isinstance(target, DecisionState) and target.nonGreedy\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATNConfigSet.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n\nfrom ..PredictionContext import merge\nfrom ..Utils import str_list\nfrom ..atn.ATN import ATN\nfrom ..atn.ATNConfig import ATNConfig\nfrom ..atn.SemanticContext import SemanticContext\nfrom ..error.Errors import UnsupportedOperationException, IllegalStateException\nfrom functools import reduce\n#\n# Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track\n# info about the set, with support for combining similar configurations using a\n# graph-structured stack.\n# /\nfrom io import StringIO\n\nATNSimulator = None\n\nclass ATNConfigSet(object):\n    __slots__ = (\n        'configLookup', 'fullCtx', 'readonly', 'configs', 'uniqueAlt',\n        'conflictingAlts', 'hasSemanticContext', 'dipsIntoOuterContext',\n        'cachedHashCode'\n    )\n\n    #\n    # The reason that we need this is because we don't want the hash map to use\n    # the standard hash code and equals. We need all configurations with the same\n    # {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles\n    # the number of objects associated with ATNConfigs. The other solution is to\n    # use a hash table that lets us specify the equals/hashcode operation.\n\n    def __init__(self, fullCtx:bool=True):\n        # All configs but hashed by (s, i, _, pi) not including context. Wiped out\n        # when we go readonly as this set becomes a DFA state.\n        self.configLookup = dict()\n        # Indicates that this configuration set is part of a full context\n        #  LL prediction. It will be used to determine how to merge $. With SLL\n        #  it's a wildcard whereas it is not for LL context merge.\n        self.fullCtx = fullCtx\n        # Indicates that the set of configurations is read-only. Do not\n        #  allow any code to manipulate the set; DFA states will point at\n        #  the sets and they must not change. This does not protect the other\n        #  fields; in particular, conflictingAlts is set after\n        #  we've made this readonly.\n        self.readonly = False\n        # Track the elements as they are added to the set; supports get(i)#/\n        self.configs = []\n\n        # TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation\n        # TODO: can we track conflicts as they are added to save scanning configs later?\n        self.uniqueAlt = 0\n        self.conflictingAlts = None\n\n        # Used in parser and lexer. In lexer, it indicates we hit a pred\n        # while computing a closure operation.  Don't make a DFA state from this.\n        self.hasSemanticContext = False\n        self.dipsIntoOuterContext = False\n\n        self.cachedHashCode = -1\n\n    def __iter__(self):\n        return self.configs.__iter__()\n\n    # Adding a new config means merging contexts with existing configs for\n    # {@code (s, i, pi, _)}, where {@code s} is the\n    # {@link ATNConfig#state}, {@code i} is the {@link ATNConfig#alt}, and\n    # {@code pi} is the {@link ATNConfig#semanticContext}. We use\n    # {@code (s,i,pi)} as key.\n    #\n    # <p>This method updates {@link #dipsIntoOuterContext} and\n    # {@link #hasSemanticContext} when necessary.</p>\n    #/\n    def add(self, config:ATNConfig, mergeCache=None):\n        if self.readonly:\n            raise Exception(\"This set is readonly\")\n        if config.semanticContext is not SemanticContext.NONE:\n            self.hasSemanticContext = True\n        if config.reachesIntoOuterContext > 0:\n            self.dipsIntoOuterContext = True\n        existing = self.getOrAdd(config)\n        if existing is config:\n            self.cachedHashCode = -1\n            self.configs.append(config)  # track order here\n            return True\n        # a previous (s,i,pi,_), merge with it and save result\n        rootIsWildcard = not self.fullCtx\n        merged = merge(existing.context, config.context, rootIsWildcard, mergeCache)\n        # no need to check for existing.context, config.context in cache\n        # since only way to create new graphs is \"call rule\" and here.\n        # We cache at both places.\n        existing.reachesIntoOuterContext = max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext)\n        # make sure to preserve the precedence filter suppression during the merge\n        if config.precedenceFilterSuppressed:\n            existing.precedenceFilterSuppressed = True\n        existing.context = merged # replace context; no need to alt mapping\n        return True\n\n    def getOrAdd(self, config:ATNConfig):\n        h = config.hashCodeForConfigSet()\n        l = self.configLookup.get(h, None)\n        if l is not None:\n            r = next((cfg for cfg in l if config.equalsForConfigSet(cfg)), None)\n            if r is not None:\n                return r\n        if l is None:\n            l = [config]\n            self.configLookup[h] = l\n        else:\n            l.append(config)\n        return config\n\n    def getStates(self):\n        return set(c.state for c in self.configs)\n\n    def getPredicates(self):\n        return list(cfg.semanticContext for cfg in self.configs if cfg.semanticContext!=SemanticContext.NONE)\n\n    def get(self, i:int):\n        return self.configs[i]\n\n    def optimizeConfigs(self, interpreter:ATNSimulator):\n        if self.readonly:\n            raise IllegalStateException(\"This set is readonly\")\n        if len(self.configs)==0:\n            return\n        for config in self.configs:\n            config.context = interpreter.getCachedContext(config.context)\n\n    def addAll(self, coll:list):\n        for c in coll:\n            self.add(c)\n        return False\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, ATNConfigSet):\n            return False\n\n        same = self.configs is not None and \\\n            self.configs==other.configs and \\\n            self.fullCtx == other.fullCtx and \\\n            self.uniqueAlt == other.uniqueAlt and \\\n            self.conflictingAlts == other.conflictingAlts and \\\n            self.hasSemanticContext == other.hasSemanticContext and \\\n            self.dipsIntoOuterContext == other.dipsIntoOuterContext\n\n        return same\n\n    def __hash__(self):\n        if self.readonly:\n            if self.cachedHashCode == -1:\n                self.cachedHashCode = self.hashConfigs()\n            return self.cachedHashCode\n        return self.hashConfigs()\n\n    def hashConfigs(self):\n        return reduce(lambda h, cfg: hash((h, cfg)), self.configs, 0)\n\n    def __len__(self):\n        return len(self.configs)\n\n    def isEmpty(self):\n        return len(self.configs)==0\n\n    def __contains__(self, config):\n        if self.configLookup is None:\n            raise UnsupportedOperationException(\"This method is not implemented for readonly sets.\")\n        h = config.hashCodeForConfigSet()\n        l = self.configLookup.get(h, None)\n        if l is not None:\n            for c in l:\n                if config.equalsForConfigSet(c):\n                    return True\n        return False\n\n    def clear(self):\n        if self.readonly:\n            raise IllegalStateException(\"This set is readonly\")\n        self.configs.clear()\n        self.cachedHashCode = -1\n        self.configLookup.clear()\n\n    def setReadonly(self, readonly:bool):\n        self.readonly = readonly\n        self.configLookup = None # can't mod, no need for lookup cache\n\n    def __str__(self):\n        with StringIO() as buf:\n            buf.write(str_list(self.configs))\n            if self.hasSemanticContext:\n                buf.write(\",hasSemanticContext=\")\n                buf.write(str(self.hasSemanticContext).lower()) # lower() to conform to java output\n            if self.uniqueAlt!=ATN.INVALID_ALT_NUMBER:\n                buf.write(\",uniqueAlt=\")\n                buf.write(str(self.uniqueAlt))\n            if self.conflictingAlts is not None:\n                buf.write(\",conflictingAlts=\")\n                buf.write(str(self.conflictingAlts))\n            if self.dipsIntoOuterContext:\n                buf.write(\",dipsIntoOuterContext\")\n            return buf.getvalue()\n\n\nclass OrderedATNConfigSet(ATNConfigSet):\n\n    def __init__(self):\n        super().__init__()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATNDeserializationOptions.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n\n# need a forward declaration\nATNDeserializationOptions = None\n\nclass ATNDeserializationOptions(object):\n    __slots__ = ('readonly', 'verifyATN', 'generateRuleBypassTransitions')\n\n    defaultOptions = None\n\n    def __init__(self, copyFrom:ATNDeserializationOptions = None):\n        self.readonly = False\n        self.verifyATN = True if copyFrom is None else copyFrom.verifyATN\n        self.generateRuleBypassTransitions = False if copyFrom is None else copyFrom.generateRuleBypassTransitions\n\n    def __setattr__(self, key, value):\n        if key!=\"readonly\" and self.readonly:\n            raise Exception(\"The object is read only.\")\n        super(type(self), self).__setattr__(key,value)\n\nATNDeserializationOptions.defaultOptions = ATNDeserializationOptions()\nATNDeserializationOptions.defaultOptions.readonly = True\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATNDeserializer.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\nfrom io import StringIO\nfrom typing import Callable\nfrom ..Token import Token\nfrom ..atn.ATN import ATN\nfrom ..atn.ATNType import ATNType\nfrom ..atn.ATNState import *\nfrom ..atn.Transition import *\nfrom ..atn.LexerAction import *\nfrom ..atn.ATNDeserializationOptions import ATNDeserializationOptions\n\nSERIALIZED_VERSION = 4\n\nclass ATNDeserializer (object):\n    __slots__ = ('deserializationOptions', 'data', 'pos')\n\n    def __init__(self, options : ATNDeserializationOptions = None):\n        if options is None:\n            options = ATNDeserializationOptions.defaultOptions\n        self.deserializationOptions = options\n\n    def deserialize(self, data : [int]):\n        self.data = data\n        self.pos = 0\n        self.checkVersion()\n        atn = self.readATN()\n        self.readStates(atn)\n        self.readRules(atn)\n        self.readModes(atn)\n        sets = []\n        self.readSets(atn, sets)\n        self.readEdges(atn, sets)\n        self.readDecisions(atn)\n        self.readLexerActions(atn)\n        self.markPrecedenceDecisions(atn)\n        self.verifyATN(atn)\n        if self.deserializationOptions.generateRuleBypassTransitions \\\n                and atn.grammarType == ATNType.PARSER:\n            self.generateRuleBypassTransitions(atn)\n            # re-verify after modification\n            self.verifyATN(atn)\n        return atn\n\n    def checkVersion(self):\n        version = self.readInt()\n        if version != SERIALIZED_VERSION:\n            raise Exception(\"Could not deserialize ATN with version {} (expected {}).\".format(ord(version), SERIALIZED_VERSION))\n\n    def readATN(self):\n        idx = self.readInt()\n        grammarType = ATNType.fromOrdinal(idx)\n        maxTokenType = self.readInt()\n        return ATN(grammarType, maxTokenType)\n\n    def readStates(self, atn:ATN):\n        loopBackStateNumbers = []\n        endStateNumbers = []\n        nstates = self.readInt()\n        for i in range(0, nstates):\n            stype = self.readInt()\n            # ignore bad type of states\n            if stype==ATNState.INVALID_TYPE:\n                atn.addState(None)\n                continue\n            ruleIndex = self.readInt()\n            s = self.stateFactory(stype, ruleIndex)\n            if stype == ATNState.LOOP_END: # special case\n                loopBackStateNumber = self.readInt()\n                loopBackStateNumbers.append((s, loopBackStateNumber))\n            elif isinstance(s, BlockStartState):\n                endStateNumber = self.readInt()\n                endStateNumbers.append((s, endStateNumber))\n\n            atn.addState(s)\n\n        # delay the assignment of loop back and end states until we know all the state instances have been initialized\n        for pair in loopBackStateNumbers:\n            pair[0].loopBackState = atn.states[pair[1]]\n\n        for pair in endStateNumbers:\n            pair[0].endState = atn.states[pair[1]]\n\n        numNonGreedyStates = self.readInt()\n        for i in range(0, numNonGreedyStates):\n            stateNumber = self.readInt()\n            atn.states[stateNumber].nonGreedy = True\n\n        numPrecedenceStates = self.readInt()\n        for i in range(0, numPrecedenceStates):\n            stateNumber = self.readInt()\n            atn.states[stateNumber].isPrecedenceRule = True\n\n    def readRules(self, atn:ATN):\n        nrules = self.readInt()\n        if atn.grammarType == ATNType.LEXER:\n            atn.ruleToTokenType = [0] * nrules\n\n        atn.ruleToStartState = [0] * nrules\n        for i in range(0, nrules):\n            s = self.readInt()\n            startState = atn.states[s]\n            atn.ruleToStartState[i] = startState\n            if atn.grammarType == ATNType.LEXER:\n                tokenType = self.readInt()\n                atn.ruleToTokenType[i] = tokenType\n\n        atn.ruleToStopState = [0] * nrules\n        for state in atn.states:\n            if not isinstance(state, RuleStopState):\n                continue\n            atn.ruleToStopState[state.ruleIndex] = state\n            atn.ruleToStartState[state.ruleIndex].stopState = state\n\n    def readModes(self, atn:ATN):\n        nmodes = self.readInt()\n        for i in range(0, nmodes):\n            s = self.readInt()\n            atn.modeToStartState.append(atn.states[s])\n\n    def readSets(self, atn:ATN, sets:list):\n        m = self.readInt()\n        for i in range(0, m):\n            iset = IntervalSet()\n            sets.append(iset)\n            n = self.readInt()\n            containsEof = self.readInt()\n            if containsEof!=0:\n                iset.addOne(-1)\n            for j in range(0, n):\n                i1 = self.readInt()\n                i2 = self.readInt()\n                iset.addRange(range(i1, i2 + 1)) # range upper limit is exclusive\n\n    def readEdges(self, atn:ATN, sets:list):\n        nedges = self.readInt()\n        for i in range(0, nedges):\n            src = self.readInt()\n            trg = self.readInt()\n            ttype = self.readInt()\n            arg1 = self.readInt()\n            arg2 = self.readInt()\n            arg3 = self.readInt()\n            trans = self.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets)\n            srcState = atn.states[src]\n            srcState.addTransition(trans)\n\n        # edges for rule stop states can be derived, so they aren't serialized\n        for state in atn.states:\n            for i in range(0, len(state.transitions)):\n                t = state.transitions[i]\n                if not isinstance(t, RuleTransition):\n                    continue\n                outermostPrecedenceReturn = -1\n                if atn.ruleToStartState[t.target.ruleIndex].isPrecedenceRule:\n                    if t.precedence == 0:\n                        outermostPrecedenceReturn = t.target.ruleIndex\n                trans = EpsilonTransition(t.followState, outermostPrecedenceReturn)\n                atn.ruleToStopState[t.target.ruleIndex].addTransition(trans)\n\n        for state in atn.states:\n            if isinstance(state, BlockStartState):\n                # we need to know the end state to set its start state\n                if state.endState is None:\n                    raise Exception(\"IllegalState\")\n                # block end states can only be associated to a single block start state\n                if state.endState.startState is not None:\n                    raise Exception(\"IllegalState\")\n                state.endState.startState = state\n\n            if isinstance(state, PlusLoopbackState):\n                for i in range(0, len(state.transitions)):\n                    target = state.transitions[i].target\n                    if isinstance(target, PlusBlockStartState):\n                        target.loopBackState = state\n            elif isinstance(state, StarLoopbackState):\n                for i in range(0, len(state.transitions)):\n                    target = state.transitions[i].target\n                    if isinstance(target, StarLoopEntryState):\n                        target.loopBackState = state\n\n    def readDecisions(self, atn:ATN):\n        ndecisions = self.readInt()\n        for i in range(0, ndecisions):\n            s = self.readInt()\n            decState = atn.states[s]\n            atn.decisionToState.append(decState)\n            decState.decision = i\n\n    def readLexerActions(self, atn:ATN):\n        if atn.grammarType == ATNType.LEXER:\n            count = self.readInt()\n            atn.lexerActions = [ None ] * count\n            for i in range(0, count):\n                actionType = self.readInt()\n                data1 = self.readInt()\n                data2 = self.readInt()\n                lexerAction = self.lexerActionFactory(actionType, data1, data2)\n                atn.lexerActions[i] = lexerAction\n\n    def generateRuleBypassTransitions(self, atn:ATN):\n\n        count = len(atn.ruleToStartState)\n        atn.ruleToTokenType = [ 0 ] * count\n        for i in range(0, count):\n            atn.ruleToTokenType[i] = atn.maxTokenType + i + 1\n\n        for i in range(0, count):\n            self.generateRuleBypassTransition(atn, i)\n\n    def generateRuleBypassTransition(self, atn:ATN, idx:int):\n\n        bypassStart = BasicBlockStartState()\n        bypassStart.ruleIndex = idx\n        atn.addState(bypassStart)\n\n        bypassStop = BlockEndState()\n        bypassStop.ruleIndex = idx\n        atn.addState(bypassStop)\n\n        bypassStart.endState = bypassStop\n        atn.defineDecisionState(bypassStart)\n\n        bypassStop.startState = bypassStart\n\n        excludeTransition = None\n\n        if atn.ruleToStartState[idx].isPrecedenceRule:\n            # wrap from the beginning of the rule to the StarLoopEntryState\n            endState = None\n            for state in atn.states:\n                if self.stateIsEndStateFor(state, idx):\n                    endState = state\n                    excludeTransition = state.loopBackState.transitions[0]\n                    break\n\n            if excludeTransition is None:\n                raise Exception(\"Couldn't identify final state of the precedence rule prefix section.\")\n\n        else:\n\n            endState = atn.ruleToStopState[idx]\n\n        # all non-excluded transitions that currently target end state need to target blockEnd instead\n        for state in atn.states:\n            for transition in state.transitions:\n                if transition == excludeTransition:\n                    continue\n                if transition.target == endState:\n                    transition.target = bypassStop\n\n        # all transitions leaving the rule start state need to leave blockStart instead\n        ruleToStartState = atn.ruleToStartState[idx]\n        count = len(ruleToStartState.transitions)\n        while count > 0:\n            bypassStart.addTransition(ruleToStartState.transitions[count-1])\n            del ruleToStartState.transitions[-1]\n\n        # link the new states\n        atn.ruleToStartState[idx].addTransition(EpsilonTransition(bypassStart))\n        bypassStop.addTransition(EpsilonTransition(endState))\n\n        matchState = BasicState()\n        atn.addState(matchState)\n        matchState.addTransition(AtomTransition(bypassStop, atn.ruleToTokenType[idx]))\n        bypassStart.addTransition(EpsilonTransition(matchState))\n\n\n    def stateIsEndStateFor(self, state:ATNState, idx:int):\n        if state.ruleIndex != idx:\n            return None\n        if not isinstance(state, StarLoopEntryState):\n            return None\n\n        maybeLoopEndState = state.transitions[len(state.transitions) - 1].target\n        if not isinstance(maybeLoopEndState, LoopEndState):\n            return None\n\n        if maybeLoopEndState.epsilonOnlyTransitions and \\\n                isinstance(maybeLoopEndState.transitions[0].target, RuleStopState):\n            return state\n        else:\n            return None\n\n\n    #\n    # Analyze the {@link StarLoopEntryState} states in the specified ATN to set\n    # the {@link StarLoopEntryState#isPrecedenceDecision} field to the\n    # correct value.\n    #\n    # @param atn The ATN.\n    #\n    def markPrecedenceDecisions(self, atn:ATN):\n        for state in atn.states:\n            if not isinstance(state, StarLoopEntryState):\n                continue\n\n            # We analyze the ATN to determine if this ATN decision state is the\n            # decision for the closure block that determines whether a\n            # precedence rule should continue or complete.\n            #\n            if atn.ruleToStartState[state.ruleIndex].isPrecedenceRule:\n                maybeLoopEndState = state.transitions[len(state.transitions) - 1].target\n                if isinstance(maybeLoopEndState, LoopEndState):\n                    if maybeLoopEndState.epsilonOnlyTransitions and \\\n                            isinstance(maybeLoopEndState.transitions[0].target, RuleStopState):\n                        state.isPrecedenceDecision = True\n\n    def verifyATN(self, atn:ATN):\n        if not self.deserializationOptions.verifyATN:\n            return\n        # verify assumptions\n        for state in atn.states:\n            if state is None:\n                continue\n\n            self.checkCondition(state.epsilonOnlyTransitions or len(state.transitions) <= 1)\n\n            if isinstance(state, PlusBlockStartState):\n                self.checkCondition(state.loopBackState is not None)\n\n            if isinstance(state, StarLoopEntryState):\n                self.checkCondition(state.loopBackState is not None)\n                self.checkCondition(len(state.transitions) == 2)\n\n                if isinstance(state.transitions[0].target, StarBlockStartState):\n                    self.checkCondition(isinstance(state.transitions[1].target, LoopEndState))\n                    self.checkCondition(not state.nonGreedy)\n                elif isinstance(state.transitions[0].target, LoopEndState):\n                    self.checkCondition(isinstance(state.transitions[1].target, StarBlockStartState))\n                    self.checkCondition(state.nonGreedy)\n                else:\n                    raise Exception(\"IllegalState\")\n\n            if isinstance(state, StarLoopbackState):\n                self.checkCondition(len(state.transitions) == 1)\n                self.checkCondition(isinstance(state.transitions[0].target, StarLoopEntryState))\n\n            if isinstance(state, LoopEndState):\n                self.checkCondition(state.loopBackState is not None)\n\n            if isinstance(state, RuleStartState):\n                self.checkCondition(state.stopState is not None)\n\n            if isinstance(state, BlockStartState):\n                self.checkCondition(state.endState is not None)\n\n            if isinstance(state, BlockEndState):\n                self.checkCondition(state.startState is not None)\n\n            if isinstance(state, DecisionState):\n                self.checkCondition(len(state.transitions) <= 1 or state.decision >= 0)\n            else:\n                self.checkCondition(len(state.transitions) <= 1 or isinstance(state, RuleStopState))\n\n    def checkCondition(self, condition:bool, message=None):\n        if not condition:\n            if message is None:\n                message = \"IllegalState\"\n            raise Exception(message)\n\n    def readInt(self):\n        i = self.data[self.pos]\n        self.pos += 1\n        return i\n\n    edgeFactories = [ lambda args : None,\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : EpsilonTransition(target),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        RangeTransition(target, Token.EOF, arg2) if arg3 != 0 else RangeTransition(target, arg1, arg2),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        RuleTransition(atn.states[arg1], arg2, arg3, target),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        PredicateTransition(target, arg1, arg2, arg3 != 0),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        AtomTransition(target, Token.EOF) if arg3 != 0 else AtomTransition(target, arg1),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        ActionTransition(target, arg1, arg2, arg3 != 0),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        SetTransition(target, sets[arg1]),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        NotSetTransition(target, sets[arg1]),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        WildcardTransition(target),\n                      lambda atn, src, trg, arg1, arg2, arg3, sets, target : \\\n                        PrecedencePredicateTransition(target, arg1)\n                      ]\n\n    def edgeFactory(self, atn:ATN, type:int, src:int, trg:int, arg1:int, arg2:int, arg3:int, sets:list):\n        target = atn.states[trg]\n        if type > len(self.edgeFactories) or self.edgeFactories[type] is None:\n            raise Exception(\"The specified transition type: \" + str(type) + \" is not valid.\")\n        else:\n            return self.edgeFactories[type](atn, src, trg, arg1, arg2, arg3, sets, target)\n\n    stateFactories = [  lambda : None,\n                        lambda : BasicState(),\n                        lambda : RuleStartState(),\n                        lambda : BasicBlockStartState(),\n                        lambda : PlusBlockStartState(),\n                        lambda : StarBlockStartState(),\n                        lambda : TokensStartState(),\n                        lambda : RuleStopState(),\n                        lambda : BlockEndState(),\n                        lambda : StarLoopbackState(),\n                        lambda : StarLoopEntryState(),\n                        lambda : PlusLoopbackState(),\n                        lambda : LoopEndState()\n                    ]\n\n    def stateFactory(self, type:int, ruleIndex:int):\n        if type> len(self.stateFactories) or self.stateFactories[type] is None:\n            raise Exception(\"The specified state type \" + str(type) + \" is not valid.\")\n        else:\n            s = self.stateFactories[type]()\n            if s is not None:\n                s.ruleIndex = ruleIndex\n        return s\n\n    CHANNEL = 0     #The type of a {@link LexerChannelAction} action.\n    CUSTOM = 1      #The type of a {@link LexerCustomAction} action.\n    MODE = 2        #The type of a {@link LexerModeAction} action.\n    MORE = 3        #The type of a {@link LexerMoreAction} action.\n    POP_MODE = 4    #The type of a {@link LexerPopModeAction} action.\n    PUSH_MODE = 5   #The type of a {@link LexerPushModeAction} action.\n    SKIP = 6        #The type of a {@link LexerSkipAction} action.\n    TYPE = 7        #The type of a {@link LexerTypeAction} action.\n\n    actionFactories = [ lambda data1, data2: LexerChannelAction(data1),\n                        lambda data1, data2: LexerCustomAction(data1, data2),\n                        lambda data1, data2: LexerModeAction(data1),\n                        lambda data1, data2: LexerMoreAction.INSTANCE,\n                        lambda data1, data2: LexerPopModeAction.INSTANCE,\n                        lambda data1, data2: LexerPushModeAction(data1),\n                        lambda data1, data2: LexerSkipAction.INSTANCE,\n                        lambda data1, data2: LexerTypeAction(data1)\n                      ]\n\n    def lexerActionFactory(self, type:int, data1:int, data2:int):\n\n        if type > len(self.actionFactories) or self.actionFactories[type] is None:\n            raise Exception(\"The specified lexer action type \" + str(type) + \" is not valid.\")\n        else:\n            return self.actionFactories[type](data1, data2)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATNSimulator.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\nfrom ..PredictionContext import PredictionContextCache, PredictionContext, getCachedPredictionContext\nfrom ..atn.ATN import ATN\nfrom ..atn.ATNConfigSet import ATNConfigSet\nfrom ..dfa.DFAState import DFAState\n\n\nclass ATNSimulator(object):\n    __slots__ = ('atn', 'sharedContextCache', '__dict__')\n\n    # Must distinguish between missing edge and edge we know leads nowhere#/\n    ERROR = DFAState(configs=ATNConfigSet())\n    ERROR.stateNumber = 0x7FFFFFFF\n\n    # The context cache maps all PredictionContext objects that are ==\n    #  to a single cached copy. This cache is shared across all contexts\n    #  in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet\n    #  to use only cached nodes/graphs in addDFAState(). We don't want to\n    #  fill this during closure() since there are lots of contexts that\n    #  pop up but are not used ever again. It also greatly slows down closure().\n    #\n    #  <p>This cache makes a huge difference in memory and a little bit in speed.\n    #  For the Java grammar on java.*, it dropped the memory requirements\n    #  at the end from 25M to 16M. We don't store any of the full context\n    #  graphs in the DFA because they are limited to local context only,\n    #  but apparently there's a lot of repetition there as well. We optimize\n    #  the config contexts before storing the config set in the DFA states\n    #  by literally rebuilding them with cached subgraphs only.</p>\n    #\n    #  <p>I tried a cache for use during closure operations, that was\n    #  whacked after each adaptivePredict(). It cost a little bit\n    #  more time I think and doesn't save on the overall footprint\n    #  so it's not worth the complexity.</p>\n    #/\n    def __init__(self, atn:ATN, sharedContextCache:PredictionContextCache):\n        self.atn = atn\n        self.sharedContextCache = sharedContextCache\n\n    def getCachedContext(self, context:PredictionContext):\n        if self.sharedContextCache is None:\n            return context\n        visited = dict()\n        return getCachedPredictionContext(context, self.sharedContextCache, visited)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATNState.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n# The following images show the relation of states and\n# {@link ATNState#transitions} for various grammar constructs.\n#\n# <ul>\n#\n# <li>Solid edges marked with an &#0949; indicate a required\n# {@link EpsilonTransition}.</li>\n#\n# <li>Dashed edges indicate locations where any transition derived from\n# {@link Transition} might appear.</li>\n#\n# <li>Dashed nodes are place holders for either a sequence of linked\n# {@link BasicState} states or the inclusion of a block representing a nested\n# construct in one of the forms below.</li>\n#\n# <li>Nodes showing multiple outgoing alternatives with a {@code ...} support\n# any number of alternatives (one or more). Nodes without the {@code ...} only\n# support the exact number of alternatives shown in the diagram.</li>\n#\n# </ul>\n#\n# <h2>Basic Blocks</h2>\n#\n# <h3>Rule</h3>\n#\n# <embed src=\"images/Rule.svg\" type=\"image/svg+xml\"/>\n#\n# <h3>Block of 1 or more alternatives</h3>\n#\n# <embed src=\"images/Block.svg\" type=\"image/svg+xml\"/>\n#\n# <h2>Greedy Loops</h2>\n#\n# <h3>Greedy Closure: {@code (...)*}</h3>\n#\n# <embed src=\"images/ClosureGreedy.svg\" type=\"image/svg+xml\"/>\n#\n# <h3>Greedy Positive Closure: {@code (...)+}</h3>\n#\n# <embed src=\"images/PositiveClosureGreedy.svg\" type=\"image/svg+xml\"/>\n#\n# <h3>Greedy Optional: {@code (...)?}</h3>\n#\n# <embed src=\"images/OptionalGreedy.svg\" type=\"image/svg+xml\"/>\n#\n# <h2>Non-Greedy Loops</h2>\n#\n# <h3>Non-Greedy Closure: {@code (...)*?}</h3>\n#\n# <embed src=\"images/ClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n#\n# <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>\n#\n# <embed src=\"images/PositiveClosureNonGreedy.svg\" type=\"image/svg+xml\"/>\n#\n# <h3>Non-Greedy Optional: {@code (...)??}</h3>\n#\n# <embed src=\"images/OptionalNonGreedy.svg\" type=\"image/svg+xml\"/>\n#\n\nfrom ..atn.Transition import Transition\n\nINITIAL_NUM_TRANSITIONS = 4\n\nclass ATNState(object):\n    __slots__ = (\n        'atn', 'stateNumber', 'stateType', 'ruleIndex', 'epsilonOnlyTransitions',\n        'transitions', 'nextTokenWithinRule',\n    )\n\n    # constants for serialization\n    INVALID_TYPE = 0\n    BASIC = 1\n    RULE_START = 2\n    BLOCK_START = 3\n    PLUS_BLOCK_START = 4\n    STAR_BLOCK_START = 5\n    TOKEN_START = 6\n    RULE_STOP = 7\n    BLOCK_END = 8\n    STAR_LOOP_BACK = 9\n    STAR_LOOP_ENTRY = 10\n    PLUS_LOOP_BACK = 11\n    LOOP_END = 12\n\n    serializationNames = [\n            \"INVALID\",\n            \"BASIC\",\n            \"RULE_START\",\n            \"BLOCK_START\",\n            \"PLUS_BLOCK_START\",\n            \"STAR_BLOCK_START\",\n            \"TOKEN_START\",\n            \"RULE_STOP\",\n            \"BLOCK_END\",\n            \"STAR_LOOP_BACK\",\n            \"STAR_LOOP_ENTRY\",\n            \"PLUS_LOOP_BACK\",\n            \"LOOP_END\" ]\n\n    INVALID_STATE_NUMBER = -1\n\n    def __init__(self):\n        # Which ATN are we in?\n        self.atn = None\n        self.stateNumber = ATNState.INVALID_STATE_NUMBER\n        self.stateType = None\n        self.ruleIndex = 0 # at runtime, we don't have Rule objects\n        self.epsilonOnlyTransitions = False\n        # Track the transitions emanating from this ATN state.\n        self.transitions = []\n        # Used to cache lookahead during parsing, not used during construction\n        self.nextTokenWithinRule = None\n\n    def __hash__(self):\n        return self.stateNumber\n\n    def __eq__(self, other):\n        return isinstance(other, ATNState) and self.stateNumber==other.stateNumber\n\n    def onlyHasEpsilonTransitions(self):\n        return self.epsilonOnlyTransitions\n\n    def isNonGreedyExitState(self):\n        return False\n\n    def __str__(self):\n        return str(self.stateNumber)\n\n    def addTransition(self, trans:Transition, index:int=-1):\n        if len(self.transitions)==0:\n            self.epsilonOnlyTransitions = trans.isEpsilon\n        elif self.epsilonOnlyTransitions != trans.isEpsilon:\n            self.epsilonOnlyTransitions = False\n            # TODO System.err.format(Locale.getDefault(), \"ATN state %d has both epsilon and non-epsilon transitions.\\n\", stateNumber);\n        if index==-1:\n            self.transitions.append(trans)\n        else:\n            self.transitions.insert(index, trans)\n\nclass BasicState(ATNState):\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.BASIC\n\n\nclass DecisionState(ATNState):\n    __slots__ = ('decision', 'nonGreedy')\n    def __init__(self):\n        super().__init__()\n        self.decision = -1\n        self.nonGreedy = False\n\n#  The start of a regular {@code (...)} block.\nclass BlockStartState(DecisionState):\n    __slots__ = 'endState'\n\n    def __init__(self):\n        super().__init__()\n        self.endState = None\n\nclass BasicBlockStartState(BlockStartState):\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.BLOCK_START\n\n# Terminal node of a simple {@code (a|b|c)} block.\nclass BlockEndState(ATNState):\n    __slots__ = 'startState'\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.BLOCK_END\n        self.startState = None\n\n# The last node in the ATN for a rule, unless that rule is the start symbol.\n#  In that case, there is one transition to EOF. Later, we might encode\n#  references to all calls to this rule to compute FOLLOW sets for\n#  error handling.\n#\nclass RuleStopState(ATNState):\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.RULE_STOP\n\nclass RuleStartState(ATNState):\n    __slots__ = ('stopState', 'isPrecedenceRule')\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.RULE_START\n        self.stopState = None\n        self.isPrecedenceRule = False\n\n# Decision state for {@code A+} and {@code (A|B)+}.  It has two transitions:\n#  one to the loop back to start of the block and one to exit.\n#\nclass PlusLoopbackState(DecisionState):\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.PLUS_LOOP_BACK\n\n# Start of {@code (A|B|...)+} loop. Technically a decision state, but\n#  we don't use for code generation; somebody might need it, so I'm defining\n#  it for completeness. In reality, the {@link PlusLoopbackState} node is the\n#  real decision-making note for {@code A+}.\n#\nclass PlusBlockStartState(BlockStartState):\n    __slots__ = 'loopBackState'\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.PLUS_BLOCK_START\n        self.loopBackState = None\n\n# The block that begins a closure loop.\nclass StarBlockStartState(BlockStartState):\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.STAR_BLOCK_START\n\nclass StarLoopbackState(ATNState):\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.STAR_LOOP_BACK\n\n\nclass StarLoopEntryState(DecisionState):\n    __slots__ = ('loopBackState', 'isPrecedenceDecision')\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.STAR_LOOP_ENTRY\n        self.loopBackState = None\n        # Indicates whether this state can benefit from a precedence DFA during SLL decision making.\n        self.isPrecedenceDecision = None\n\n# Mark the end of a * or + loop.\nclass LoopEndState(ATNState):\n    __slots__ = 'loopBackState'\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.LOOP_END\n        self.loopBackState = None\n\n# The Tokens rule start state linking to each lexer rule start state */\nclass TokensStartState(DecisionState):\n\n    def __init__(self):\n        super().__init__()\n        self.stateType = self.TOKEN_START\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ATNType.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\nfrom enum import IntEnum\n\n# Represents the type of recognizer an ATN applies to.\n\nclass ATNType(IntEnum):\n\n    LEXER = 0\n    PARSER = 1\n\n    @classmethod\n    def fromOrdinal(cls, i:int):\n        return cls._value2member_map_[i]\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/LexerATNSimulator.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n# When we hit an accept state in either the DFA or the ATN, we\n#  have to notify the character stream to start buffering characters\n#  via {@link IntStream#mark} and record the current state. The current sim state\n#  includes the current index into the input, the current line,\n#  and current character position in that line. Note that the Lexer is\n#  tracking the starting line and characterization of the token. These\n#  variables track the \"state\" of the simulator when it hits an accept state.\n#\n#  <p>We track these variables separately for the DFA and ATN simulation\n#  because the DFA simulation often has to fail over to the ATN\n#  simulation. If the ATN simulation fails, we need the DFA to fall\n#  back to its previously accepted state, if any. If the ATN succeeds,\n#  then the ATN does the accept and the DFA simulator that invoked it\n#  can simply return the predicted token type.</p>\n#/\n\nfrom ..PredictionContext import PredictionContextCache, SingletonPredictionContext, PredictionContext\nfrom ..InputStream import InputStream\nfrom ..Token import Token\nfrom ..atn.ATN import ATN\nfrom ..atn.ATNConfig import LexerATNConfig\nfrom ..atn.ATNSimulator import ATNSimulator\nfrom ..atn.ATNConfigSet import ATNConfigSet, OrderedATNConfigSet\nfrom ..atn.ATNState import RuleStopState, ATNState\nfrom ..atn.LexerActionExecutor import LexerActionExecutor\nfrom ..atn.Transition import Transition\nfrom ..dfa.DFAState import DFAState\nfrom ..error.Errors import LexerNoViableAltException, UnsupportedOperationException\n\nclass SimState(object):\n    __slots__ = ('index', 'line', 'column', 'dfaState')\n\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.index = -1\n        self.line = 0\n        self.column = -1\n        self.dfaState = None\n\n# need forward declaration\nLexer = None\nLexerATNSimulator = None\n\nclass LexerATNSimulator(ATNSimulator):\n    __slots__ = (\n        'decisionToDFA', 'recog', 'startIndex', 'line', 'column', 'mode',\n        'DEFAULT_MODE', 'MAX_CHAR_VALUE', 'prevAccept'\n    )\n\n    debug = False\n    dfa_debug = False\n\n    MIN_DFA_EDGE = 0\n    MAX_DFA_EDGE = 127 # forces unicode to stay in ATN\n\n    ERROR = None\n\n    def __init__(self, recog:Lexer, atn:ATN, decisionToDFA:list, sharedContextCache:PredictionContextCache):\n        super().__init__(atn, sharedContextCache)\n        self.decisionToDFA = decisionToDFA\n        self.recog = recog\n        # The current token's starting index into the character stream.\n        #  Shared across DFA to ATN simulation in case the ATN fails and the\n        #  DFA did not have a previous accept state. In this case, we use the\n        #  ATN-generated exception object.\n        self.startIndex = -1\n        # line number 1..n within the input#/\n        self.line = 1\n        # The index of the character relative to the beginning of the line 0..n-1#/\n        self.column = 0\n        from ..Lexer import Lexer\n        self.mode = Lexer.DEFAULT_MODE\n        # Cache Lexer properties to avoid further imports\n        self.DEFAULT_MODE = Lexer.DEFAULT_MODE\n        self.MAX_CHAR_VALUE = Lexer.MAX_CHAR_VALUE\n        # Used during DFA/ATN exec to record the most recent accept configuration info\n        self.prevAccept = SimState()\n\n\n    def copyState(self, simulator:LexerATNSimulator ):\n        self.column = simulator.column\n        self.line = simulator.line\n        self.mode = simulator.mode\n        self.startIndex = simulator.startIndex\n\n    def match(self, input:InputStream , mode:int):\n        self.mode = mode\n        mark = input.mark()\n        try:\n            self.startIndex = input.index\n            self.prevAccept.reset()\n            dfa = self.decisionToDFA[mode]\n            if dfa.s0 is None:\n                return self.matchATN(input)\n            else:\n                return self.execATN(input, dfa.s0)\n        finally:\n            input.release(mark)\n\n    def reset(self):\n        self.prevAccept.reset()\n        self.startIndex = -1\n        self.line = 1\n        self.column = 0\n        self.mode = self.DEFAULT_MODE\n\n    def matchATN(self, input:InputStream):\n        startState = self.atn.modeToStartState[self.mode]\n\n        if LexerATNSimulator.debug:\n            print(\"matchATN mode \" + str(self.mode) + \" start: \" + str(startState))\n\n        old_mode = self.mode\n        s0_closure = self.computeStartState(input, startState)\n        suppressEdge = s0_closure.hasSemanticContext\n        s0_closure.hasSemanticContext = False\n\n        next = self.addDFAState(s0_closure)\n        if not suppressEdge:\n            self.decisionToDFA[self.mode].s0 = next\n\n        predict = self.execATN(input, next)\n\n        if LexerATNSimulator.debug:\n            print(\"DFA after matchATN: \" + str(self.decisionToDFA[old_mode].toLexerString()))\n\n        return predict\n\n    def execATN(self, input:InputStream, ds0:DFAState):\n        if LexerATNSimulator.debug:\n            print(\"start state closure=\" + str(ds0.configs))\n\n        if ds0.isAcceptState:\n            # allow zero-length tokens\n            self.captureSimState(self.prevAccept, input, ds0)\n\n        t = input.LA(1)\n        s = ds0 # s is current/from DFA state\n\n        while True: # while more work\n            if LexerATNSimulator.debug:\n                print(\"execATN loop starting closure:\", str(s.configs))\n\n            # As we move src->trg, src->trg, we keep track of the previous trg to\n            # avoid looking up the DFA state again, which is expensive.\n            # If the previous target was already part of the DFA, we might\n            # be able to avoid doing a reach operation upon t. If s!=null,\n            # it means that semantic predicates didn't prevent us from\n            # creating a DFA state. Once we know s!=null, we check to see if\n            # the DFA state has an edge already for t. If so, we can just reuse\n            # it's configuration set; there's no point in re-computing it.\n            # This is kind of like doing DFA simulation within the ATN\n            # simulation because DFA simulation is really just a way to avoid\n            # computing reach/closure sets. Technically, once we know that\n            # we have a previously added DFA state, we could jump over to\n            # the DFA simulator. But, that would mean popping back and forth\n            # a lot and making things more complicated algorithmically.\n            # This optimization makes a lot of sense for loops within DFA.\n            # A character will take us back to an existing DFA state\n            # that already has lots of edges out of it. e.g., .* in comments.\n            # print(\"Target for:\" + str(s) + \" and:\" + str(t))\n            target = self.getExistingTargetState(s, t)\n            # print(\"Existing:\" + str(target))\n            if target is None:\n                target = self.computeTargetState(input, s, t)\n                # print(\"Computed:\" + str(target))\n\n            if target == self.ERROR:\n                break\n\n            # If this is a consumable input element, make sure to consume before\n            # capturing the accept state so the input index, line, and char\n            # position accurately reflect the state of the interpreter at the\n            # end of the token.\n            if t != Token.EOF:\n                self.consume(input)\n\n            if target.isAcceptState:\n                self.captureSimState(self.prevAccept, input, target)\n                if t == Token.EOF:\n                    break\n\n            t = input.LA(1)\n\n            s = target # flip; current DFA target becomes new src/from state\n\n        return self.failOrAccept(self.prevAccept, input, s.configs, t)\n\n    # Get an existing target state for an edge in the DFA. If the target state\n    # for the edge has not yet been computed or is otherwise not available,\n    # this method returns {@code null}.\n    #\n    # @param s The current DFA state\n    # @param t The next input symbol\n    # @return The existing target DFA state for the given input symbol\n    # {@code t}, or {@code null} if the target state for this edge is not\n    # already cached\n    def getExistingTargetState(self, s:DFAState, t:int):\n        if s.edges is None or t < self.MIN_DFA_EDGE or t > self.MAX_DFA_EDGE:\n            return None\n\n        target = s.edges[t - self.MIN_DFA_EDGE]\n        if LexerATNSimulator.debug and target is not None:\n            print(\"reuse state\", str(s.stateNumber), \"edge to\", str(target.stateNumber))\n\n        return target\n\n    # Compute a target state for an edge in the DFA, and attempt to add the\n    # computed state and corresponding edge to the DFA.\n    #\n    # @param input The input stream\n    # @param s The current DFA state\n    # @param t The next input symbol\n    #\n    # @return The computed target DFA state for the given input symbol\n    # {@code t}. If {@code t} does not lead to a valid DFA state, this method\n    # returns {@link #ERROR}.\n    def computeTargetState(self, input:InputStream, s:DFAState, t:int):\n        reach = OrderedATNConfigSet()\n\n        # if we don't find an existing DFA state\n        # Fill reach starting from closure, following t transitions\n        self.getReachableConfigSet(input, s.configs, reach, t)\n\n        if len(reach)==0: # we got nowhere on t from s\n            if not reach.hasSemanticContext:\n                # we got nowhere on t, don't throw out this knowledge; it'd\n                # cause a failover from DFA later.\n               self. addDFAEdge(s, t, self.ERROR)\n\n            # stop when we can't match any more char\n            return self.ERROR\n\n        # Add an edge from s to target DFA found/created for reach\n        return self.addDFAEdge(s, t, cfgs=reach)\n\n    def failOrAccept(self, prevAccept:SimState , input:InputStream, reach:ATNConfigSet, t:int):\n        if self.prevAccept.dfaState is not None:\n            lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor\n            self.accept(input, lexerActionExecutor, self.startIndex, prevAccept.index, prevAccept.line, prevAccept.column)\n            return prevAccept.dfaState.prediction\n        else:\n            # if no accept and EOF is first char, return EOF\n            if t==Token.EOF and input.index==self.startIndex:\n                return Token.EOF\n            raise LexerNoViableAltException(self.recog, input, self.startIndex, reach)\n\n    # Given a starting configuration set, figure out all ATN configurations\n    #  we can reach upon input {@code t}. Parameter {@code reach} is a return\n    #  parameter.\n    def getReachableConfigSet(self, input:InputStream, closure:ATNConfigSet, reach:ATNConfigSet, t:int):\n        # this is used to skip processing for configs which have a lower priority\n        # than a config that already reached an accept state for the same rule\n        skipAlt = ATN.INVALID_ALT_NUMBER\n        for cfg in closure:\n            currentAltReachedAcceptState = ( cfg.alt == skipAlt )\n            if currentAltReachedAcceptState and cfg.passedThroughNonGreedyDecision:\n                continue\n\n            if LexerATNSimulator.debug:\n                print(\"testing\", self.getTokenName(t), \"at\",  str(cfg))\n\n            for trans in cfg.state.transitions:          # for each transition\n                target = self.getReachableTarget(trans, t)\n                if target is not None:\n                    lexerActionExecutor = cfg.lexerActionExecutor\n                    if lexerActionExecutor is not None:\n                        lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - self.startIndex)\n\n                    treatEofAsEpsilon = (t == Token.EOF)\n                    config = LexerATNConfig(state=target, lexerActionExecutor=lexerActionExecutor, config=cfg)\n                    if self.closure(input, config, reach, currentAltReachedAcceptState, True, treatEofAsEpsilon):\n                        # any remaining configs for this alt have a lower priority than\n                        # the one that just reached an accept state.\n                        skipAlt = cfg.alt\n\n    def accept(self, input:InputStream, lexerActionExecutor:LexerActionExecutor, startIndex:int, index:int, line:int, charPos:int):\n        if LexerATNSimulator.debug:\n            print(\"ACTION\", lexerActionExecutor)\n\n        # seek to after last char in token\n        input.seek(index)\n        self.line = line\n        self.column = charPos\n\n        if lexerActionExecutor is not None and self.recog is not None:\n            lexerActionExecutor.execute(self.recog, input, startIndex)\n\n    def getReachableTarget(self, trans:Transition, t:int):\n        if trans.matches(t, 0, self.MAX_CHAR_VALUE):\n            return trans.target\n        else:\n            return None\n\n    def computeStartState(self, input:InputStream, p:ATNState):\n        initialContext = PredictionContext.EMPTY\n        configs = OrderedATNConfigSet()\n        for i in range(0,len(p.transitions)):\n            target = p.transitions[i].target\n            c = LexerATNConfig(state=target, alt=i+1, context=initialContext)\n            self.closure(input, c, configs, False, False, False)\n        return configs\n\n    # Since the alternatives within any lexer decision are ordered by\n    # preference, this method stops pursuing the closure as soon as an accept\n    # state is reached. After the first accept state is reached by depth-first\n    # search from {@code config}, all other (potentially reachable) states for\n    # this rule would have a lower priority.\n    #\n    # @return {@code true} if an accept state is reached, otherwise\n    # {@code false}.\n    def closure(self, input:InputStream, config:LexerATNConfig, configs:ATNConfigSet, currentAltReachedAcceptState:bool,\n                speculative:bool, treatEofAsEpsilon:bool):\n        if LexerATNSimulator.debug:\n            print(\"closure(\" + str(config) + \")\")\n\n        if isinstance( config.state, RuleStopState ):\n            if LexerATNSimulator.debug:\n                if self.recog is not None:\n                    print(\"closure at\", self.recog.symbolicNames[config.state.ruleIndex],  \"rule stop\", str(config))\n                else:\n                    print(\"closure at rule stop\", str(config))\n\n            if config.context is None or config.context.hasEmptyPath():\n                if config.context is None or config.context.isEmpty():\n                    configs.add(config)\n                    return True\n                else:\n                    configs.add(LexerATNConfig(state=config.state, config=config, context=PredictionContext.EMPTY))\n                    currentAltReachedAcceptState = True\n\n            if config.context is not None and not config.context.isEmpty():\n                for i in range(0,len(config.context)):\n                    if config.context.getReturnState(i) != PredictionContext.EMPTY_RETURN_STATE:\n                        newContext = config.context.getParent(i) # \"pop\" return state\n                        returnState = self.atn.states[config.context.getReturnState(i)]\n                        c = LexerATNConfig(state=returnState, config=config, context=newContext)\n                        currentAltReachedAcceptState = self.closure(input, c, configs,\n                                    currentAltReachedAcceptState, speculative, treatEofAsEpsilon)\n\n            return currentAltReachedAcceptState\n\n        # optimization\n        if not config.state.epsilonOnlyTransitions:\n            if not currentAltReachedAcceptState or not config.passedThroughNonGreedyDecision:\n                configs.add(config)\n\n        for t in config.state.transitions:\n            c = self.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon)\n            if c is not None:\n                currentAltReachedAcceptState = self.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon)\n\n        return currentAltReachedAcceptState\n\n    # side-effect: can alter configs.hasSemanticContext\n    def getEpsilonTarget(self, input:InputStream, config:LexerATNConfig, t:Transition, configs:ATNConfigSet,\n                                           speculative:bool, treatEofAsEpsilon:bool):\n        c = None\n        if t.serializationType==Transition.RULE:\n                newContext = SingletonPredictionContext.create(config.context, t.followState.stateNumber)\n                c = LexerATNConfig(state=t.target, config=config, context=newContext)\n\n        elif t.serializationType==Transition.PRECEDENCE:\n                raise UnsupportedOperationException(\"Precedence predicates are not supported in lexers.\")\n\n        elif t.serializationType==Transition.PREDICATE:\n                #  Track traversing semantic predicates. If we traverse,\n                # we cannot add a DFA state for this \"reach\" computation\n                # because the DFA would not test the predicate again in the\n                # future. Rather than creating collections of semantic predicates\n                # like v3 and testing them on prediction, v4 will test them on the\n                # fly all the time using the ATN not the DFA. This is slower but\n                # semantically it's not used that often. One of the key elements to\n                # this predicate mechanism is not adding DFA states that see\n                # predicates immediately afterwards in the ATN. For example,\n\n                # a : ID {p1}? | ID {p2}? ;\n\n                # should create the start state for rule 'a' (to save start state\n                # competition), but should not create target of ID state. The\n                # collection of ATN states the following ID references includes\n                # states reached by traversing predicates. Since this is when we\n                # test them, we cannot cash the DFA state target of ID.\n\n                if LexerATNSimulator.debug:\n                    print(\"EVAL rule \"+ str(t.ruleIndex) + \":\" + str(t.predIndex))\n                configs.hasSemanticContext = True\n                if self.evaluatePredicate(input, t.ruleIndex, t.predIndex, speculative):\n                    c = LexerATNConfig(state=t.target, config=config)\n\n        elif t.serializationType==Transition.ACTION:\n                if config.context is None or config.context.hasEmptyPath():\n                    # execute actions anywhere in the start rule for a token.\n                    #\n                    # TODO: if the entry rule is invoked recursively, some\n                    # actions may be executed during the recursive call. The\n                    # problem can appear when hasEmptyPath() is true but\n                    # isEmpty() is false. In this case, the config needs to be\n                    # split into two contexts - one with just the empty path\n                    # and another with everything but the empty path.\n                    # Unfortunately, the current algorithm does not allow\n                    # getEpsilonTarget to return two configurations, so\n                    # additional modifications are needed before we can support\n                    # the split operation.\n                    lexerActionExecutor = LexerActionExecutor.append(config.lexerActionExecutor,\n                                    self.atn.lexerActions[t.actionIndex])\n                    c = LexerATNConfig(state=t.target, config=config, lexerActionExecutor=lexerActionExecutor)\n\n                else:\n                    # ignore actions in referenced rules\n                    c = LexerATNConfig(state=t.target, config=config)\n\n        elif t.serializationType==Transition.EPSILON:\n            c = LexerATNConfig(state=t.target, config=config)\n\n        elif t.serializationType in [ Transition.ATOM, Transition.RANGE, Transition.SET ]:\n            if treatEofAsEpsilon:\n                if t.matches(Token.EOF, 0, self.MAX_CHAR_VALUE):\n                    c = LexerATNConfig(state=t.target, config=config)\n\n        return c\n\n    # Evaluate a predicate specified in the lexer.\n    #\n    # <p>If {@code speculative} is {@code true}, this method was called before\n    # {@link #consume} for the matched character. This method should call\n    # {@link #consume} before evaluating the predicate to ensure position\n    # sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine},\n    # and {@link Lexer#getcolumn}, properly reflect the current\n    # lexer state. This method should restore {@code input} and the simulator\n    # to the original state before returning (i.e. undo the actions made by the\n    # call to {@link #consume}.</p>\n    #\n    # @param input The input stream.\n    # @param ruleIndex The rule containing the predicate.\n    # @param predIndex The index of the predicate within the rule.\n    # @param speculative {@code true} if the current index in {@code input} is\n    # one character before the predicate's location.\n    #\n    # @return {@code true} if the specified predicate evaluates to\n    # {@code true}.\n    #/\n    def evaluatePredicate(self, input:InputStream, ruleIndex:int, predIndex:int, speculative:bool):\n        # assume true if no recognizer was provided\n        if self.recog is None:\n            return True\n\n        if not speculative:\n            return self.recog.sempred(None, ruleIndex, predIndex)\n\n        savedcolumn = self.column\n        savedLine = self.line\n        index = input.index\n        marker = input.mark()\n        try:\n            self.consume(input)\n            return self.recog.sempred(None, ruleIndex, predIndex)\n        finally:\n            self.column = savedcolumn\n            self.line = savedLine\n            input.seek(index)\n            input.release(marker)\n\n    def captureSimState(self, settings:SimState, input:InputStream, dfaState:DFAState):\n        settings.index = input.index\n        settings.line = self.line\n        settings.column = self.column\n        settings.dfaState = dfaState\n\n    def addDFAEdge(self, from_:DFAState, tk:int, to:DFAState=None, cfgs:ATNConfigSet=None) -> DFAState:\n\n        if to is None and cfgs is not None:\n            # leading to this call, ATNConfigSet.hasSemanticContext is used as a\n            # marker indicating dynamic predicate evaluation makes this edge\n            # dependent on the specific input sequence, so the static edge in the\n            # DFA should be omitted. The target DFAState is still created since\n            # execATN has the ability to resynchronize with the DFA state cache\n            # following the predicate evaluation step.\n            #\n            # TJP notes: next time through the DFA, we see a pred again and eval.\n            # If that gets us to a previously created (but dangling) DFA\n            # state, we can continue in pure DFA mode from there.\n            #/\n            suppressEdge = cfgs.hasSemanticContext\n            cfgs.hasSemanticContext = False\n\n            to = self.addDFAState(cfgs)\n\n            if suppressEdge:\n                return to\n\n        # add the edge\n        if tk < self.MIN_DFA_EDGE or tk > self.MAX_DFA_EDGE:\n            # Only track edges within the DFA bounds\n            return to\n\n        if LexerATNSimulator.debug:\n            print(\"EDGE \" + str(from_) + \" -> \" + str(to) + \" upon \"+ chr(tk))\n\n        if from_.edges is None:\n            #  make room for tokens 1..n and -1 masquerading as index 0\n            from_.edges = [ None ] * (self.MAX_DFA_EDGE - self.MIN_DFA_EDGE + 1)\n\n        from_.edges[tk - self.MIN_DFA_EDGE] = to # connect\n\n        return to\n\n\n    # Add a new DFA state if there isn't one with this set of\n    # configurations already. This method also detects the first\n    # configuration containing an ATN rule stop state. Later, when\n    # traversing the DFA, we will know which rule to accept.\n    def addDFAState(self, configs:ATNConfigSet) -> DFAState:\n\n        proposed = DFAState(configs=configs)\n        firstConfigWithRuleStopState = next((cfg for cfg in configs if isinstance(cfg.state, RuleStopState)), None)\n\n        if firstConfigWithRuleStopState is not None:\n            proposed.isAcceptState = True\n            proposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor\n            proposed.prediction = self.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex]\n\n        dfa = self.decisionToDFA[self.mode]\n        existing = dfa.states.get(proposed, None)\n        if existing is not None:\n            return existing\n\n        newState = proposed\n\n        newState.stateNumber = len(dfa.states)\n        configs.setReadonly(True)\n        newState.configs = configs\n        dfa.states[newState] = newState\n        return newState\n\n    def getDFA(self, mode:int):\n        return self.decisionToDFA[mode]\n\n    # Get the text matched so far for the current token.\n    def getText(self, input:InputStream):\n        # index is first lookahead char, don't include.\n        return input.getText(self.startIndex, input.index-1)\n\n    def consume(self, input:InputStream):\n        curChar = input.LA(1)\n        if curChar==ord('\\n'):\n            self.line += 1\n            self.column = 0\n        else:\n            self.column += 1\n        input.consume()\n\n    def getTokenName(self, t:int):\n        if t==-1:\n            return \"EOF\"\n        else:\n            return \"'\" + chr(t) + \"'\"\n\n\nLexerATNSimulator.ERROR = DFAState(0x7FFFFFFF, ATNConfigSet())\n\ndel Lexer\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/LexerAction.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n #\n\nfrom enum import IntEnum\n\n# need forward declaration\nLexer = None\n\n\nclass LexerActionType(IntEnum):\n\n    CHANNEL = 0     #The type of a {@link LexerChannelAction} action.\n    CUSTOM = 1      #The type of a {@link LexerCustomAction} action.\n    MODE = 2        #The type of a {@link LexerModeAction} action.\n    MORE = 3        #The type of a {@link LexerMoreAction} action.\n    POP_MODE = 4    #The type of a {@link LexerPopModeAction} action.\n    PUSH_MODE = 5   #The type of a {@link LexerPushModeAction} action.\n    SKIP = 6        #The type of a {@link LexerSkipAction} action.\n    TYPE = 7        #The type of a {@link LexerTypeAction} action.\n\nclass LexerAction(object):\n    __slots__ = ('actionType', 'isPositionDependent')\n\n    def __init__(self, action:LexerActionType):\n        self.actionType = action\n        self.isPositionDependent = False\n\n    def __hash__(self):\n        return hash(self.actionType)\n\n    def __eq__(self, other):\n        return self is other\n\n\n#\n# Implements the {@code skip} lexer action by calling {@link Lexer#skip}.\n#\n# <p>The {@code skip} command does not have any parameters, so this action is\n# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\nclass LexerSkipAction(LexerAction):\n\n    # Provides a singleton instance of this parameterless lexer action.\n    INSTANCE = None\n\n    def __init__(self):\n        super().__init__(LexerActionType.SKIP)\n\n    def execute(self, lexer:Lexer):\n        lexer.skip()\n\n    def __str__(self):\n        return \"skip\"\n\nLexerSkipAction.INSTANCE = LexerSkipAction()\n\n#  Implements the {@code type} lexer action by calling {@link Lexer#setType}\n# with the assigned type.\nclass LexerTypeAction(LexerAction):\n    __slots__ = 'type'\n\n    def __init__(self, type:int):\n        super().__init__(LexerActionType.TYPE)\n        self.type = type\n\n    def execute(self, lexer:Lexer):\n        lexer.type = self.type\n\n    def __hash__(self):\n        return hash((self.actionType, self.type))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerTypeAction):\n            return False\n        else:\n            return self.type == other.type\n\n    def __str__(self):\n        return \"type(\" + str(self.type) + \")\"\n\n\n# Implements the {@code pushMode} lexer action by calling\n# {@link Lexer#pushMode} with the assigned mode.\nclass LexerPushModeAction(LexerAction):\n    __slots__ = 'mode'\n\n    def __init__(self, mode:int):\n        super().__init__(LexerActionType.PUSH_MODE)\n        self.mode = mode\n\n    # <p>This action is implemented by calling {@link Lexer#pushMode} with the\n    # value provided by {@link #getMode}.</p>\n    def execute(self, lexer:Lexer):\n        lexer.pushMode(self.mode)\n\n    def __hash__(self):\n        return hash((self.actionType, self.mode))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerPushModeAction):\n            return False\n        else:\n            return self.mode == other.mode\n\n    def __str__(self):\n        return \"pushMode(\" + str(self.mode) + \")\"\n\n\n# Implements the {@code popMode} lexer action by calling {@link Lexer#popMode}.\n#\n# <p>The {@code popMode} command does not have any parameters, so this action is\n# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\nclass LexerPopModeAction(LexerAction):\n\n    INSTANCE = None\n\n    def __init__(self):\n        super().__init__(LexerActionType.POP_MODE)\n\n    # <p>This action is implemented by calling {@link Lexer#popMode}.</p>\n    def execute(self, lexer:Lexer):\n        lexer.popMode()\n\n    def __str__(self):\n        return \"popMode\"\n\nLexerPopModeAction.INSTANCE = LexerPopModeAction()\n\n# Implements the {@code more} lexer action by calling {@link Lexer#more}.\n#\n# <p>The {@code more} command does not have any parameters, so this action is\n# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>\nclass LexerMoreAction(LexerAction):\n\n    INSTANCE = None\n\n    def __init__(self):\n        super().__init__(LexerActionType.MORE)\n\n    # <p>This action is implemented by calling {@link Lexer#popMode}.</p>\n    def execute(self, lexer:Lexer):\n        lexer.more()\n\n    def __str__(self):\n        return \"more\"\n\nLexerMoreAction.INSTANCE = LexerMoreAction()\n\n# Implements the {@code mode} lexer action by calling {@link Lexer#mode} with\n# the assigned mode.\nclass LexerModeAction(LexerAction):\n    __slots__ = 'mode'\n\n    def __init__(self, mode:int):\n        super().__init__(LexerActionType.MODE)\n        self.mode = mode\n\n    # <p>This action is implemented by calling {@link Lexer#mode} with the\n    # value provided by {@link #getMode}.</p>\n    def execute(self, lexer:Lexer):\n        lexer.mode(self.mode)\n\n    def __hash__(self):\n        return hash((self.actionType, self.mode))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerModeAction):\n            return False\n        else:\n            return self.mode == other.mode\n\n    def __str__(self):\n        return \"mode(\" + str(self.mode) + \")\"\n\n# Executes a custom lexer action by calling {@link Recognizer#action} with the\n# rule and action indexes assigned to the custom action. The implementation of\n# a custom action is added to the generated code for the lexer in an override\n# of {@link Recognizer#action} when the grammar is compiled.\n#\n# <p>This class may represent embedded actions created with the <code>{...}</code>\n# syntax in ANTLR 4, as well as actions created for lexer commands where the\n# command argument could not be evaluated when the grammar was compiled.</p>\n\nclass LexerCustomAction(LexerAction):\n    __slots__ = ('ruleIndex', 'actionIndex')\n\n    # Constructs a custom lexer action with the specified rule and action\n    # indexes.\n    #\n    # @param ruleIndex The rule index to use for calls to\n    # {@link Recognizer#action}.\n    # @param actionIndex The action index to use for calls to\n    # {@link Recognizer#action}.\n    #/\n    def __init__(self, ruleIndex:int, actionIndex:int):\n        super().__init__(LexerActionType.CUSTOM)\n        self.ruleIndex = ruleIndex\n        self.actionIndex = actionIndex\n        self.isPositionDependent = True\n\n    # <p>Custom actions are implemented by calling {@link Lexer#action} with the\n    # appropriate rule and action indexes.</p>\n    def execute(self, lexer:Lexer):\n        lexer.action(None, self.ruleIndex, self.actionIndex)\n\n    def __hash__(self):\n        return hash((self.actionType, self.ruleIndex, self.actionIndex))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerCustomAction):\n            return False\n        else:\n            return self.ruleIndex == other.ruleIndex and self.actionIndex == other.actionIndex\n\n# Implements the {@code channel} lexer action by calling\n# {@link Lexer#setChannel} with the assigned channel.\nclass LexerChannelAction(LexerAction):\n    __slots__ = 'channel'\n\n    # Constructs a new {@code channel} action with the specified channel value.\n    # @param channel The channel value to pass to {@link Lexer#setChannel}.\n    def __init__(self, channel:int):\n        super().__init__(LexerActionType.CHANNEL)\n        self.channel = channel\n\n    # <p>This action is implemented by calling {@link Lexer#setChannel} with the\n    # value provided by {@link #getChannel}.</p>\n    def execute(self, lexer:Lexer):\n        lexer._channel = self.channel\n\n    def __hash__(self):\n        return hash((self.actionType, self.channel))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerChannelAction):\n            return False\n        else:\n            return self.channel == other.channel\n\n    def __str__(self):\n        return \"channel(\" + str(self.channel) + \")\"\n\n# This implementation of {@link LexerAction} is used for tracking input offsets\n# for position-dependent actions within a {@link LexerActionExecutor}.\n#\n# <p>This action is not serialized as part of the ATN, and is only required for\n# position-dependent lexer actions which appear at a location other than the\n# end of a rule. For more information about DFA optimizations employed for\n# lexer actions, see {@link LexerActionExecutor#append} and\n# {@link LexerActionExecutor#fixOffsetBeforeMatch}.</p>\nclass LexerIndexedCustomAction(LexerAction):\n    __slots__ = ('offset', 'action')\n\n    # Constructs a new indexed custom action by associating a character offset\n    # with a {@link LexerAction}.\n    #\n    # <p>Note: This class is only required for lexer actions for which\n    # {@link LexerAction#isPositionDependent} returns {@code true}.</p>\n    #\n    # @param offset The offset into the input {@link CharStream}, relative to\n    # the token start index, at which the specified lexer action should be\n    # executed.\n    # @param action The lexer action to execute at a particular offset in the\n    # input {@link CharStream}.\n    def __init__(self, offset:int, action:LexerAction):\n        super().__init__(action.actionType)\n        self.offset = offset\n        self.action = action\n        self.isPositionDependent = True\n\n    # <p>This method calls {@link #execute} on the result of {@link #getAction}\n    # using the provided {@code lexer}.</p>\n    def execute(self, lexer:Lexer):\n        # assume the input stream position was properly set by the calling code\n        self.action.execute(lexer)\n\n    def __hash__(self):\n        return hash((self.actionType, self.offset, self.action))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerIndexedCustomAction):\n            return False\n        else:\n            return self.offset == other.offset and self.action == other.action\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/LexerActionExecutor.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n# Represents an executor for a sequence of lexer actions which traversed during\n# the matching operation of a lexer rule (token).\n#\n# <p>The executor tracks position information for position-dependent lexer actions\n# efficiently, ensuring that actions appearing only at the end of the rule do\n# not cause bloating of the {@link DFA} created for the lexer.</p>\n\n\nfrom ..InputStream import InputStream\nfrom ..atn.LexerAction import LexerAction, LexerIndexedCustomAction\n\n# need a forward declaration\nLexer = None\nLexerActionExecutor = None\n\nclass LexerActionExecutor(object):\n    __slots__ = ('lexerActions', 'hashCode')\n\n    def __init__(self, lexerActions:list=list()):\n        self.lexerActions = lexerActions\n        # Caches the result of {@link #hashCode} since the hash code is an element\n        # of the performance-critical {@link LexerATNConfig#hashCode} operation.\n        self.hashCode = hash(\"\".join([str(la) for la in lexerActions]))\n\n\n    # Creates a {@link LexerActionExecutor} which executes the actions for\n    # the input {@code lexerActionExecutor} followed by a specified\n    # {@code lexerAction}.\n    #\n    # @param lexerActionExecutor The executor for actions already traversed by\n    # the lexer while matching a token within a particular\n    # {@link LexerATNConfig}. If this is {@code null}, the method behaves as\n    # though it were an empty executor.\n    # @param lexerAction The lexer action to execute after the actions\n    # specified in {@code lexerActionExecutor}.\n    #\n    # @return A {@link LexerActionExecutor} for executing the combine actions\n    # of {@code lexerActionExecutor} and {@code lexerAction}.\n    @staticmethod\n    def append(lexerActionExecutor:LexerActionExecutor , lexerAction:LexerAction ):\n        if lexerActionExecutor is None:\n            return LexerActionExecutor([ lexerAction ])\n\n        lexerActions = lexerActionExecutor.lexerActions + [ lexerAction ]\n        return LexerActionExecutor(lexerActions)\n\n    # Creates a {@link LexerActionExecutor} which encodes the current offset\n    # for position-dependent lexer actions.\n    #\n    # <p>Normally, when the executor encounters lexer actions where\n    # {@link LexerAction#isPositionDependent} returns {@code true}, it calls\n    # {@link IntStream#seek} on the input {@link CharStream} to set the input\n    # position to the <em>end</em> of the current token. This behavior provides\n    # for efficient DFA representation of lexer actions which appear at the end\n    # of a lexer rule, even when the lexer rule matches a variable number of\n    # characters.</p>\n    #\n    # <p>Prior to traversing a match transition in the ATN, the current offset\n    # from the token start index is assigned to all position-dependent lexer\n    # actions which have not already been assigned a fixed offset. By storing\n    # the offsets relative to the token start index, the DFA representation of\n    # lexer actions which appear in the middle of tokens remains efficient due\n    # to sharing among tokens of the same length, regardless of their absolute\n    # position in the input stream.</p>\n    #\n    # <p>If the current executor already has offsets assigned to all\n    # position-dependent lexer actions, the method returns {@code this}.</p>\n    #\n    # @param offset The current offset to assign to all position-dependent\n    # lexer actions which do not already have offsets assigned.\n    #\n    # @return A {@link LexerActionExecutor} which stores input stream offsets\n    # for all position-dependent lexer actions.\n    #/\n    def fixOffsetBeforeMatch(self, offset:int):\n        updatedLexerActions = None\n        for i in range(0, len(self.lexerActions)):\n            if self.lexerActions[i].isPositionDependent and not isinstance(self.lexerActions[i], LexerIndexedCustomAction):\n                if updatedLexerActions is None:\n                    updatedLexerActions = [ la for la in self.lexerActions ]\n                updatedLexerActions[i] = LexerIndexedCustomAction(offset, self.lexerActions[i])\n\n        if updatedLexerActions is None:\n            return self\n        else:\n            return LexerActionExecutor(updatedLexerActions)\n\n\n    # Execute the actions encapsulated by this executor within the context of a\n    # particular {@link Lexer}.\n    #\n    # <p>This method calls {@link IntStream#seek} to set the position of the\n    # {@code input} {@link CharStream} prior to calling\n    # {@link LexerAction#execute} on a position-dependent action. Before the\n    # method returns, the input position will be restored to the same position\n    # it was in when the method was invoked.</p>\n    #\n    # @param lexer The lexer instance.\n    # @param input The input stream which is the source for the current token.\n    # When this method is called, the current {@link IntStream#index} for\n    # {@code input} should be the start of the following token, i.e. 1\n    # character past the end of the current token.\n    # @param startIndex The token start index. This value may be passed to\n    # {@link IntStream#seek} to set the {@code input} position to the beginning\n    # of the token.\n    #/\n    def execute(self, lexer:Lexer, input:InputStream, startIndex:int):\n        requiresSeek = False\n        stopIndex = input.index\n        try:\n            for lexerAction in self.lexerActions:\n                if isinstance(lexerAction, LexerIndexedCustomAction):\n                    offset = lexerAction.offset\n                    input.seek(startIndex + offset)\n                    lexerAction = lexerAction.action\n                    requiresSeek = (startIndex + offset) != stopIndex\n                elif lexerAction.isPositionDependent:\n                    input.seek(stopIndex)\n                    requiresSeek = False\n                lexerAction.execute(lexer)\n        finally:\n            if requiresSeek:\n                input.seek(stopIndex)\n\n    def __hash__(self):\n        return self.hashCode\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, LexerActionExecutor):\n            return False\n        else:\n            return self.hashCode == other.hashCode \\\n                and self.lexerActions == other.lexerActions\n\ndel Lexer\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/ParserATNSimulator.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# The embodiment of the adaptive LL(*), ALL(*), parsing strategy.\n#\n# <p>\n# The basic complexity of the adaptive strategy makes it harder to understand.\n# We begin with ATN simulation to build paths in a DFA. Subsequent prediction\n# requests go through the DFA first. If they reach a state without an edge for\n# the current symbol, the algorithm fails over to the ATN simulation to\n# complete the DFA path for the current input (until it finds a conflict state\n# or uniquely predicting state).</p>\n#\n# <p>\n# All of that is done without using the outer context because we want to create\n# a DFA that is not dependent upon the rule invocation stack when we do a\n# prediction. One DFA works in all contexts. We avoid using context not\n# necessarily because it's slower, although it can be, but because of the DFA\n# caching problem. The closure routine only considers the rule invocation stack\n# created during prediction beginning in the decision rule. For example, if\n# prediction occurs without invoking another rule's ATN, there are no context\n# stacks in the configurations. When lack of context leads to a conflict, we\n# don't know if it's an ambiguity or a weakness in the strong LL(*) parsing\n# strategy (versus full LL(*)).</p>\n#\n# <p>\n# When SLL yields a configuration set with conflict, we rewind the input and\n# retry the ATN simulation, this time using full outer context without adding\n# to the DFA. Configuration context stacks will be the full invocation stacks\n# from the start rule. If we get a conflict using full context, then we can\n# definitively say we have a true ambiguity for that input sequence. If we\n# don't get a conflict, it implies that the decision is sensitive to the outer\n# context. (It is not context-sensitive in the sense of context-sensitive\n# grammars.)</p>\n#\n# <p>\n# The next time we reach this DFA state with an SLL conflict, through DFA\n# simulation, we will again retry the ATN simulation using full context mode.\n# This is slow because we can't save the results and have to \"interpret\" the\n# ATN each time we get that input.</p>\n#\n# <p>\n# <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>\n#\n# <p>\n# We could cache results from full context to predicted alternative easily and\n# that saves a lot of time but doesn't work in presence of predicates. The set\n# of visible predicates from the ATN start state changes depending on the\n# context, because closure can fall off the end of a rule. I tried to cache\n# tuples (stack context, semantic context, predicted alt) but it was slower\n# than interpreting and much more complicated. Also required a huge amount of\n# memory. The goal is not to create the world's fastest parser anyway. I'd like\n# to keep this algorithm simple. By launching multiple threads, we can improve\n# the speed of parsing across a large number of files.</p>\n#\n# <p>\n# There is no strict ordering between the amount of input used by SLL vs LL,\n# which makes it really hard to build a cache for full context. Let's say that\n# we have input A B C that leads to an SLL conflict with full context X. That\n# implies that using X we might only use A B but we could also use A B C D to\n# resolve conflict. Input A B C D could predict alternative 1 in one position\n# in the input and A B C E could predict alternative 2 in another position in\n# input. The conflicting SLL configurations could still be non-unique in the\n# full context prediction, which would lead us to requiring more input than the\n# original A B C.\tTo make a\tprediction cache work, we have to track\tthe exact\n# input\tused during the previous prediction. That amounts to a cache that maps\n# X to a specific DFA for that context.</p>\n#\n# <p>\n# Something should be done for left-recursive expression predictions. They are\n# likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry\n# with full LL thing Sam does.</p>\n#\n# <p>\n# <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>\n#\n# <p>\n# We avoid doing full context retry when the outer context is empty, we did not\n# dip into the outer context by falling off the end of the decision state rule,\n# or when we force SLL mode.</p>\n#\n# <p>\n# As an example of the not dip into outer context case, consider as super\n# constructor calls versus function calls. One grammar might look like\n# this:</p>\n#\n# <pre>\n# ctorBody\n#   : '{' superCall? stat* '}'\n#   ;\n# </pre>\n#\n# <p>\n# Or, you might see something like</p>\n#\n# <pre>\n# stat\n#   : superCall ';'\n#   | expression ';'\n#   | ...\n#   ;\n# </pre>\n#\n# <p>\n# In both cases I believe that no closure operations will dip into the outer\n# context. In the first case ctorBody in the worst case will stop at the '}'.\n# In the 2nd case it should stop at the ';'. Both cases should stay within the\n# entry rule and not dip into the outer context.</p>\n#\n# <p>\n# <strong>PREDICATES</strong></p>\n#\n# <p>\n# Predicates are always evaluated if present in either SLL or LL both. SLL and\n# LL simulation deals with predicates differently. SLL collects predicates as\n# it performs closure operations like ANTLR v3 did. It delays predicate\n# evaluation until it reaches and accept state. This allows us to cache the SLL\n# ATN simulation whereas, if we had evaluated predicates on-the-fly during\n# closure, the DFA state configuration sets would be different and we couldn't\n# build up a suitable DFA.</p>\n#\n# <p>\n# When building a DFA accept state during ATN simulation, we evaluate any\n# predicates and return the sole semantically valid alternative. If there is\n# more than 1 alternative, we report an ambiguity. If there are 0 alternatives,\n# we throw an exception. Alternatives without predicates act like they have\n# true predicates. The simple way to think about it is to strip away all\n# alternatives with false predicates and choose the minimum alternative that\n# remains.</p>\n#\n# <p>\n# When we start in the DFA and reach an accept state that's predicated, we test\n# those and return the minimum semantically viable alternative. If no\n# alternatives are viable, we throw an exception.</p>\n#\n# <p>\n# During full LL ATN simulation, closure always evaluates predicates and\n# on-the-fly. This is crucial to reducing the configuration set size during\n# closure. It hits a landmine when parsing with the Java grammar, for example,\n# without this on-the-fly evaluation.</p>\n#\n# <p>\n# <strong>SHARING DFA</strong></p>\n#\n# <p>\n# All instances of the same parser share the same decision DFAs through a\n# static field. Each instance gets its own ATN simulator but they share the\n# same {@link #decisionToDFA} field. They also share a\n# {@link PredictionContextCache} object that makes sure that all\n# {@link PredictionContext} objects are shared among the DFA states. This makes\n# a big size difference.</p>\n#\n# <p>\n# <strong>THREAD SAFETY</strong></p>\n#\n# <p>\n# The {@link ParserATNSimulator} locks on the {@link #decisionToDFA} field when\n# it adds a new DFA object to that array. {@link #addDFAEdge}\n# locks on the DFA for the current decision when setting the\n# {@link DFAState#edges} field. {@link #addDFAState} locks on\n# the DFA for the current decision when looking up a DFA state to see if it\n# already exists. We must make sure that all requests to add DFA states that\n# are equivalent result in the same shared DFA object. This is because lots of\n# threads will be trying to update the DFA at once. The\n# {@link #addDFAState} method also locks inside the DFA lock\n# but this time on the shared context cache when it rebuilds the\n# configurations' {@link PredictionContext} objects using cached\n# subgraphs/nodes. No other locking occurs, even during DFA simulation. This is\n# safe as long as we can guarantee that all threads referencing\n# {@code s.edge[t]} get the same physical target {@link DFAState}, or\n# {@code null}. Once into the DFA, the DFA simulation does not reference the\n# {@link DFA#states} map. It follows the {@link DFAState#edges} field to new\n# targets. The DFA simulator will either find {@link DFAState#edges} to be\n# {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or\n# {@code dfa.edges[t]} to be non-null. The\n# {@link #addDFAEdge} method could be racing to set the field\n# but in either case the DFA simulator works; if {@code null}, and requests ATN\n# simulation. It could also race trying to get {@code dfa.edges[t]}, but either\n# way it will work because it's not doing a test and set operation.</p>\n#\n# <p>\n# <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage\n# Parsing)</strong></p>\n#\n# <p>\n# Sam pointed out that if SLL does not give a syntax error, then there is no\n# point in doing full LL, which is slower. We only have to try LL if we get a\n# syntax error. For maximum speed, Sam starts the parser set to pure SLL\n# mode with the {@link BailErrorStrategy}:</p>\n#\n# <pre>\n# parser.{@link Parser#getInterpreter() getInterpreter()}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};\n# parser.{@link Parser#setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());\n# </pre>\n#\n# <p>\n# If it does not get a syntax error, then we're done. If it does get a syntax\n# error, we need to retry with the combined SLL/LL strategy.</p>\n#\n# <p>\n# The reason this works is as follows. If there are no SLL conflicts, then the\n# grammar is SLL (at least for that input set). If there is an SLL conflict,\n# the full LL analysis must yield a set of viable alternatives which is a\n# subset of the alternatives reported by SLL. If the LL set is a singleton,\n# then the grammar is LL but not SLL. If the LL set is the same size as the SLL\n# set, the decision is SLL. If the LL set has size &gt; 1, then that decision\n# is truly ambiguous on the current input. If the LL set is smaller, then the\n# SLL conflict resolution might choose an alternative that the full LL would\n# rule out as a possibility based upon better context information. If that's\n# the case, then the SLL parse will definitely get an error because the full LL\n# analysis says it's not viable. If SLL conflict resolution chooses an\n# alternative within the LL set, them both SLL and LL would choose the same\n# alternative because they both choose the minimum of multiple conflicting\n# alternatives.</p>\n#\n# <p>\n# Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and\n# a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL\n# parsing will get an error because SLL will pursue alternative 1. If\n# <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will\n# choose the same alternative because alternative one is the minimum of either\n# set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax\n# error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>\n#\n# <p>\n# Of course, if the input is invalid, then we will get an error for sure in\n# both SLL and LL parsing. Erroneous input will therefore require 2 passes over\n# the input.</p>\n#\nimport sys\nfrom ..dfa.DFA import DFA\nfrom ..BufferedTokenStream import TokenStream\nfrom ..Parser import Parser\nfrom ..ParserRuleContext import ParserRuleContext\nfrom ..PredictionContext import PredictionContextCache, PredictionContext, SingletonPredictionContext, \\\n    PredictionContextFromRuleContext\nfrom ..RuleContext import RuleContext\nfrom ..Token import Token\nfrom ..Utils import str_list\nfrom ..atn.ATN import ATN\nfrom ..atn.ATNConfig import ATNConfig\nfrom ..atn.ATNConfigSet import ATNConfigSet\nfrom ..atn.ATNSimulator import ATNSimulator\nfrom ..atn.ATNState import DecisionState, RuleStopState, ATNState\nfrom ..atn.PredictionMode import PredictionMode\nfrom ..atn.SemanticContext import SemanticContext, andContext, orContext\nfrom ..atn.Transition import Transition, RuleTransition, ActionTransition, PrecedencePredicateTransition, \\\n    PredicateTransition, AtomTransition, SetTransition, NotSetTransition\nfrom ..dfa.DFAState import DFAState, PredPrediction\nfrom ..error.Errors import NoViableAltException\n\n\nclass ParserATNSimulator(ATNSimulator):\n    __slots__ = (\n        'parser', 'decisionToDFA', 'predictionMode', '_input', '_startIndex',\n        '_outerContext', '_dfa', 'mergeCache'\n    )\n\n    debug = False\n    trace_atn_sim = False\n    dfa_debug = False\n    retry_debug = False\n\n\n    def __init__(self, parser:Parser, atn:ATN, decisionToDFA:list, sharedContextCache:PredictionContextCache):\n        super().__init__(atn, sharedContextCache)\n        self.parser = parser\n        self.decisionToDFA = decisionToDFA\n        # SLL, LL, or LL + exact ambig detection?#\n        self.predictionMode = PredictionMode.LL\n        # LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n        self._input = None\n        self._startIndex = 0\n        self._outerContext = None\n        self._dfa = None\n        # Each prediction operation uses a cache for merge of prediction contexts.\n        #  Don't keep around as it wastes huge amounts of memory. DoubleKeyMap\n        #  isn't synchronized but we're ok since two threads shouldn't reuse same\n        #  parser/atnsim object because it can only handle one input at a time.\n        #  This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid\n        #  the merge if we ever see a and b again.  Note that (b,a)&rarr;c should\n        #  also be examined during cache lookup.\n        #\n        self.mergeCache = None\n\n\n    def reset(self):\n        pass\n\n    def adaptivePredict(self, input:TokenStream, decision:int, outerContext:ParserRuleContext):\n        if ParserATNSimulator.debug or ParserATNSimulator.trace_atn_sim:\n            print(\"adaptivePredict decision \" + str(decision) +\n                                   \" exec LA(1)==\" + self.getLookaheadName(input) +\n                                   \" line \" + str(input.LT(1).line) + \":\" +\n                                   str(input.LT(1).column))\n        self._input = input\n        self._startIndex = input.index\n        self._outerContext = outerContext\n\n        dfa = self.decisionToDFA[decision]\n        self._dfa = dfa\n        m = input.mark()\n        index = input.index\n\n        # Now we are certain to have a specific decision's DFA\n        # But, do we still need an initial state?\n        try:\n            if dfa.precedenceDfa:\n                # the start state for a precedence DFA depends on the current\n                # parser precedence, and is provided by a DFA method.\n                s0 = dfa.getPrecedenceStartState(self.parser.getPrecedence())\n            else:\n                # the start state for a \"regular\" DFA is just s0\n                s0 = dfa.s0\n\n            if s0 is None:\n                if outerContext is None:\n                    outerContext = ParserRuleContext.EMPTY\n                if ParserATNSimulator.debug:\n                    print(\"predictATN decision \" + str(dfa.decision) +\n                                       \" exec LA(1)==\" + self.getLookaheadName(input) +\n                                       \", outerContext=\" + str(outerContext));#outerContext.toString(self.parser.literalNames, None))\n\n                fullCtx = False\n                s0_closure = self.computeStartState(dfa.atnStartState, ParserRuleContext.EMPTY, fullCtx)\n\n                if dfa.precedenceDfa:\n                    # If this is a precedence DFA, we use applyPrecedenceFilter\n                    # to convert the computed start state to a precedence start\n                    # state. We then use DFA.setPrecedenceStartState to set the\n                    # appropriate start state for the precedence level rather\n                    # than simply setting DFA.s0.\n                    #\n                    dfa.s0.configs = s0_closure # not used for prediction but useful to know start configs anyway\n                    s0_closure = self.applyPrecedenceFilter(s0_closure)\n                    s0 = self.addDFAState(dfa, DFAState(configs=s0_closure))\n                    dfa.setPrecedenceStartState(self.parser.getPrecedence(), s0)\n                else:\n                    s0 = self.addDFAState(dfa, DFAState(configs=s0_closure))\n                    dfa.s0 = s0\n\n            alt = self.execATN(dfa, s0, input, index, outerContext)\n            if ParserATNSimulator.debug:\n                print(\"DFA after predictATN: \" + dfa.toString(self.parser.literalNames))\n            return alt\n        finally:\n            self._dfa = None\n            self.mergeCache = None # wack cache after each prediction\n            input.seek(index)\n            input.release(m)\n\n    # Performs ATN simulation to compute a predicted alternative based\n    #  upon the remaining input, but also updates the DFA cache to avoid\n    #  having to traverse the ATN again for the same input sequence.\n\n    # There are some key conditions we're looking for after computing a new\n    # set of ATN configs (proposed DFA state):\n          # if the set is empty, there is no viable alternative for current symbol\n          # does the state uniquely predict an alternative?\n          # does the state have a conflict that would prevent us from\n          #   putting it on the work list?\n\n    # We also have some key operations to do:\n          # add an edge from previous DFA state to potentially new DFA state, D,\n          #   upon current symbol but only if adding to work list, which means in all\n          #   cases except no viable alternative (and possibly non-greedy decisions?)\n          # collecting predicates and adding semantic context to DFA accept states\n          # adding rule context to context-sensitive DFA accept states\n          # consuming an input symbol\n          # reporting a conflict\n          # reporting an ambiguity\n          # reporting a context sensitivity\n          # reporting insufficient predicates\n\n    # cover these cases:\n    #    dead end\n    #    single alt\n    #    single alt + preds\n    #    conflict\n    #    conflict + preds\n    #\n    def execATN(self, dfa:DFA, s0:DFAState, input:TokenStream, startIndex:int, outerContext:ParserRuleContext ):\n        if ParserATNSimulator.debug or ParserATNSimulator.trace_atn_sim:\n            print(\"execATN decision \" + str(dfa.decision) +\n                    \", DFA state \" + str(s0) +\n                    \", LA(1)==\" + self.getLookaheadName(input) +\n                    \" line \" + str(input.LT(1).line) + \":\" + str(input.LT(1).column))\n\n        previousD = s0\n\n        t = input.LA(1)\n\n        while True: # while more work\n            D = self.getExistingTargetState(previousD, t)\n            if D is None:\n                D = self.computeTargetState(dfa, previousD, t)\n            if D is self.ERROR:\n                # if any configs in previous dipped into outer context, that\n                # means that input up to t actually finished entry rule\n                # at least for SLL decision. Full LL doesn't dip into outer\n                # so don't need special case.\n                # We will get an error no matter what so delay until after\n                # decision; better error message. Also, no reachable target\n                # ATN states in SLL implies LL will also get nowhere.\n                # If conflict in states that dip out, choose min since we\n                # will get error no matter what.\n                e = self.noViableAlt(input, outerContext, previousD.configs, startIndex)\n                input.seek(startIndex)\n                alt = self.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext)\n                if alt!=ATN.INVALID_ALT_NUMBER:\n                    return alt\n                raise e\n\n            if D.requiresFullContext and self.predictionMode != PredictionMode.SLL:\n                # IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n                conflictingAlts = D.configs.conflictingAlts\n                if D.predicates is not None:\n                    if ParserATNSimulator.debug:\n                        print(\"DFA state has preds in DFA sim LL failover\")\n                    conflictIndex = input.index\n                    if conflictIndex != startIndex:\n                        input.seek(startIndex)\n\n                    conflictingAlts = self.evalSemanticContext(D.predicates, outerContext, True)\n                    if len(conflictingAlts)==1:\n                        if ParserATNSimulator.debug:\n                            print(\"Full LL avoided\")\n                        return min(conflictingAlts)\n\n                    if conflictIndex != startIndex:\n                        # restore the index so reporting the fallback to full\n                        # context occurs with the index at the correct spot\n                        input.seek(conflictIndex)\n\n                if ParserATNSimulator.dfa_debug:\n                    print(\"ctx sensitive state \" + str(outerContext) +\" in \" + str(D))\n                fullCtx = True\n                s0_closure = self.computeStartState(dfa.atnStartState, outerContext, fullCtx)\n                self.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index)\n                alt = self.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext)\n                return alt\n\n            if D.isAcceptState:\n                if D.predicates is None:\n                    return D.prediction\n\n                stopIndex = input.index\n                input.seek(startIndex)\n                alts = self.evalSemanticContext(D.predicates, outerContext, True)\n                if len(alts)==0:\n                    raise self.noViableAlt(input, outerContext, D.configs, startIndex)\n                elif len(alts)==1:\n                    return min(alts)\n                else:\n                    # report ambiguity after predicate evaluation to make sure the correct\n                    # set of ambig alts is reported.\n                    self.reportAmbiguity(dfa, D, startIndex, stopIndex, False, alts, D.configs)\n                    return min(alts)\n\n            previousD = D\n\n            if t != Token.EOF:\n                input.consume()\n                t = input.LA(1)\n\n    #\n    # Get an existing target state for an edge in the DFA. If the target state\n    # for the edge has not yet been computed or is otherwise not available,\n    # this method returns {@code null}.\n    #\n    # @param previousD The current DFA state\n    # @param t The next input symbol\n    # @return The existing target DFA state for the given input symbol\n    # {@code t}, or {@code null} if the target state for this edge is not\n    # already cached\n    #\n    def getExistingTargetState(self, previousD:DFAState, t:int):\n        edges = previousD.edges\n        if edges is None or t + 1 < 0 or t + 1 >= len(edges):\n            return None\n        else:\n            return edges[t + 1]\n\n    #\n    # Compute a target state for an edge in the DFA, and attempt to add the\n    # computed state and corresponding edge to the DFA.\n    #\n    # @param dfa The DFA\n    # @param previousD The current DFA state\n    # @param t The next input symbol\n    #\n    # @return The computed target DFA state for the given input symbol\n    # {@code t}. If {@code t} does not lead to a valid DFA state, this method\n    # returns {@link #ERROR}.\n    #\n    def computeTargetState(self, dfa:DFA, previousD:DFAState, t:int):\n        reach = self.computeReachSet(previousD.configs, t, False)\n        if reach is None:\n            self.addDFAEdge(dfa, previousD, t, self.ERROR)\n            return self.ERROR\n\n        # create new target state; we'll add to DFA after it's complete\n        D = DFAState(configs=reach)\n\n        predictedAlt = self.getUniqueAlt(reach)\n\n        if ParserATNSimulator.debug:\n            altSubSets = PredictionMode.getConflictingAltSubsets(reach)\n            print(\"SLL altSubSets=\" + str(altSubSets) + \", configs=\" + str(reach) +\n                        \", predict=\" + str(predictedAlt) + \", allSubsetsConflict=\" +\n                        str(PredictionMode.allSubsetsConflict(altSubSets)) + \", conflictingAlts=\" +\n                        str(self.getConflictingAlts(reach)))\n\n        if predictedAlt!=ATN.INVALID_ALT_NUMBER:\n            # NO CONFLICT, UNIQUELY PREDICTED ALT\n            D.isAcceptState = True\n            D.configs.uniqueAlt = predictedAlt\n            D.prediction = predictedAlt\n        elif PredictionMode.hasSLLConflictTerminatingPrediction(self.predictionMode, reach):\n            # MORE THAN ONE VIABLE ALTERNATIVE\n            D.configs.conflictingAlts = self.getConflictingAlts(reach)\n            D.requiresFullContext = True\n            # in SLL-only mode, we will stop at this state and return the minimum alt\n            D.isAcceptState = True\n            D.prediction = min(D.configs.conflictingAlts)\n\n        if D.isAcceptState and D.configs.hasSemanticContext:\n            self.predicateDFAState(D, self.atn.getDecisionState(dfa.decision))\n            if D.predicates is not None:\n                D.prediction = ATN.INVALID_ALT_NUMBER\n\n        # all adds to dfa are done after we've created full D state\n        D = self.addDFAEdge(dfa, previousD, t, D)\n        return D\n\n    def predicateDFAState(self, dfaState:DFAState, decisionState:DecisionState):\n        # We need to test all predicates, even in DFA states that\n        # uniquely predict alternative.\n        nalts = len(decisionState.transitions)\n        # Update DFA so reach becomes accept state with (predicate,alt)\n        # pairs if preds found for conflicting alts\n        altsToCollectPredsFrom = self.getConflictingAltsOrUniqueAlt(dfaState.configs)\n        altToPred = self.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts)\n        if altToPred is not None:\n            dfaState.predicates = self.getPredicatePredictions(altsToCollectPredsFrom, altToPred)\n            dfaState.prediction = ATN.INVALID_ALT_NUMBER # make sure we use preds\n        else:\n            # There are preds in configs but they might go away\n            # when OR'd together like {p}? || NONE == NONE. If neither\n            # alt has preds, resolve to min alt\n            dfaState.prediction = min(altsToCollectPredsFrom)\n\n    # comes back with reach.uniqueAlt set to a valid alt\n    def execATNWithFullContext(self, dfa:DFA, D:DFAState, # how far we got before failing over\n                                         s0:ATNConfigSet,\n                                         input:TokenStream,\n                                         startIndex:int,\n                                         outerContext:ParserRuleContext):\n        if ParserATNSimulator.debug or ParserATNSimulator.trace_atn_sim:\n            print(\"execATNWithFullContext\", str(s0))\n        fullCtx = True\n        foundExactAmbig = False\n        reach = None\n        previous = s0\n        input.seek(startIndex)\n        t = input.LA(1)\n        predictedAlt = -1\n        while (True): # while more work\n            reach = self.computeReachSet(previous, t, fullCtx)\n            if reach is None:\n                # if any configs in previous dipped into outer context, that\n                # means that input up to t actually finished entry rule\n                # at least for LL decision. Full LL doesn't dip into outer\n                # so don't need special case.\n                # We will get an error no matter what so delay until after\n                # decision; better error message. Also, no reachable target\n                # ATN states in SLL implies LL will also get nowhere.\n                # If conflict in states that dip out, choose min since we\n                # will get error no matter what.\n                e = self.noViableAlt(input, outerContext, previous, startIndex)\n                input.seek(startIndex)\n                alt = self.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext)\n                if alt!=ATN.INVALID_ALT_NUMBER:\n                    return alt\n                else:\n                    raise e\n\n            altSubSets = PredictionMode.getConflictingAltSubsets(reach)\n            if ParserATNSimulator.debug:\n                print(\"LL altSubSets=\" + str(altSubSets) + \", predict=\" +\n                      str(PredictionMode.getUniqueAlt(altSubSets)) + \", resolvesToJustOneViableAlt=\" +\n                      str(PredictionMode.resolvesToJustOneViableAlt(altSubSets)))\n\n            reach.uniqueAlt = self.getUniqueAlt(reach)\n            # unique prediction?\n            if reach.uniqueAlt!=ATN.INVALID_ALT_NUMBER:\n                predictedAlt = reach.uniqueAlt\n                break\n            elif self.predictionMode is not PredictionMode.LL_EXACT_AMBIG_DETECTION:\n                predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets)\n                if predictedAlt != ATN.INVALID_ALT_NUMBER:\n                    break\n            else:\n                # In exact ambiguity mode, we never try to terminate early.\n                # Just keeps scarfing until we know what the conflict is\n                if PredictionMode.allSubsetsConflict(altSubSets) and PredictionMode.allSubsetsEqual(altSubSets):\n                    foundExactAmbig = True\n                    predictedAlt = PredictionMode.getSingleViableAlt(altSubSets)\n                    break\n                # else there are multiple non-conflicting subsets or\n                # we're not sure what the ambiguity is yet.\n                # So, keep going.\n\n            previous = reach\n            if t != Token.EOF:\n                input.consume()\n                t = input.LA(1)\n\n        # If the configuration set uniquely predicts an alternative,\n        # without conflict, then we know that it's a full LL decision\n        # not SLL.\n        if reach.uniqueAlt != ATN.INVALID_ALT_NUMBER :\n            self.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index)\n            return predictedAlt\n\n        # We do not check predicates here because we have checked them\n        # on-the-fly when doing full context prediction.\n\n        #\n        # In non-exact ambiguity detection mode, we might\tactually be able to\n        # detect an exact ambiguity, but I'm not going to spend the cycles\n        # needed to check. We only emit ambiguity warnings in exact ambiguity\n        # mode.\n        #\n        # For example, we might know that we have conflicting configurations.\n        # But, that does not mean that there is no way forward without a\n        # conflict. It's possible to have nonconflicting alt subsets as in:\n\n        # altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n\n        # from\n        #\n        #    [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n        #     (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n        #\n        # In this case, (17,1,[5 $]) indicates there is some next sequence that\n        # would resolve this without conflict to alternative 1. Any other viable\n        # next sequence, however, is associated with a conflict.  We stop\n        # looking for input because no amount of further lookahead will alter\n        # the fact that we should predict alternative 1.  We just can't say for\n        # sure that there is an ambiguity without looking further.\n\n        self.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, None, reach)\n\n        return predictedAlt\n\n    def computeReachSet(self, closure:ATNConfigSet, t:int, fullCtx:bool):\n        if ParserATNSimulator.debug:\n            print(\"in computeReachSet, starting closure: \" + str(closure))\n\n        if self.mergeCache is None:\n            self.mergeCache = dict()\n\n        intermediate = ATNConfigSet(fullCtx)\n\n        # Configurations already in a rule stop state indicate reaching the end\n        # of the decision rule (local context) or end of the start rule (full\n        # context). Once reached, these configurations are never updated by a\n        # closure operation, so they are handled separately for the performance\n        # advantage of having a smaller intermediate set when calling closure.\n        #\n        # For full-context reach operations, separate handling is required to\n        # ensure that the alternative matching the longest overall sequence is\n        # chosen when multiple such configurations can match the input.\n\n        skippedStopStates = None\n\n        # First figure out where we can reach on input t\n        for c in closure:\n            if ParserATNSimulator.debug:\n                print(\"testing \" + self.getTokenName(t) + \" at \" + str(c))\n\n            if isinstance(c.state, RuleStopState):\n                if fullCtx or t == Token.EOF:\n                    if skippedStopStates is None:\n                        skippedStopStates = list()\n                    skippedStopStates.append(c)\n                continue\n\n            for trans in c.state.transitions:\n                target = self.getReachableTarget(trans, t)\n                if target is not None:\n                    intermediate.add(ATNConfig(state=target, config=c), self.mergeCache)\n\n        # Now figure out where the reach operation can take us...\n\n        reach = None\n\n        # This block optimizes the reach operation for intermediate sets which\n        # trivially indicate a termination state for the overall\n        # adaptivePredict operation.\n        #\n        # The conditions assume that intermediate\n        # contains all configurations relevant to the reach set, but this\n        # condition is not true when one or more configurations have been\n        # withheld in skippedStopStates, or when the current symbol is EOF.\n        #\n        if skippedStopStates is None and t!=Token.EOF:\n            if len(intermediate)==1:\n                # Don't pursue the closure if there is just one state.\n                # It can only have one alternative; just add to result\n                # Also don't pursue the closure if there is unique alternative\n                # among the configurations.\n                reach = intermediate\n            elif self.getUniqueAlt(intermediate)!=ATN.INVALID_ALT_NUMBER:\n                # Also don't pursue the closure if there is unique alternative\n                # among the configurations.\n                reach = intermediate\n\n        # If the reach set could not be trivially determined, perform a closure\n        # operation on the intermediate set to compute its initial value.\n        #\n        if reach is None:\n            reach = ATNConfigSet(fullCtx)\n            closureBusy = set()\n            treatEofAsEpsilon = t == Token.EOF\n            for c in intermediate:\n                self.closure(c, reach, closureBusy, False, fullCtx, treatEofAsEpsilon)\n\n        if t == Token.EOF:\n            # After consuming EOF no additional input is possible, so we are\n            # only interested in configurations which reached the end of the\n            # decision rule (local context) or end of the start rule (full\n            # context). Update reach to contain only these configurations. This\n            # handles both explicit EOF transitions in the grammar and implicit\n            # EOF transitions following the end of the decision or start rule.\n            #\n            # When reach==intermediate, no closure operation was performed. In\n            # this case, removeAllConfigsNotInRuleStopState needs to check for\n            # reachable rule stop states as well as configurations already in\n            # a rule stop state.\n            #\n            # This is handled before the configurations in skippedStopStates,\n            # because any configurations potentially added from that list are\n            # already guaranteed to meet this condition whether or not it's\n            # required.\n            #\n            reach = self.removeAllConfigsNotInRuleStopState(reach, reach is intermediate)\n\n        # If skippedStopStates is not null, then it contains at least one\n        # configuration. For full-context reach operations, these\n        # configurations reached the end of the start rule, in which case we\n        # only add them back to reach if no configuration during the current\n        # closure operation reached such a state. This ensures adaptivePredict\n        # chooses an alternative matching the longest overall sequence when\n        # multiple alternatives are viable.\n        #\n        if skippedStopStates is not None and ( (not fullCtx) or (not PredictionMode.hasConfigInRuleStopState(reach))):\n            for c in skippedStopStates:\n                reach.add(c, self.mergeCache)\n\n        if ParserATNSimulator.trace_atn_sim:\n            print(\"computeReachSet\", str(closure), \"->\", reach)\n\n        if len(reach)==0:\n            return None\n        else:\n            return reach\n\n    #\n    # Return a configuration set containing only the configurations from\n    # {@code configs} which are in a {@link RuleStopState}. If all\n    # configurations in {@code configs} are already in a rule stop state, this\n    # method simply returns {@code configs}.\n    #\n    # <p>When {@code lookToEndOfRule} is true, this method uses\n    # {@link ATN#nextTokens} for each configuration in {@code configs} which is\n    # not already in a rule stop state to see if a rule stop state is reachable\n    # from the configuration via epsilon-only transitions.</p>\n    #\n    # @param configs the configuration set to update\n    # @param lookToEndOfRule when true, this method checks for rule stop states\n    # reachable by epsilon-only transitions from each configuration in\n    # {@code configs}.\n    #\n    # @return {@code configs} if all configurations in {@code configs} are in a\n    # rule stop state, otherwise return a new configuration set containing only\n    # the configurations from {@code configs} which are in a rule stop state\n    #\n    def removeAllConfigsNotInRuleStopState(self, configs:ATNConfigSet, lookToEndOfRule:bool):\n        if PredictionMode.allConfigsInRuleStopStates(configs):\n            return configs\n        result = ATNConfigSet(configs.fullCtx)\n        for config in configs:\n            if isinstance(config.state, RuleStopState):\n                result.add(config, self.mergeCache)\n                continue\n            if lookToEndOfRule and config.state.epsilonOnlyTransitions:\n                nextTokens = self.atn.nextTokens(config.state)\n                if Token.EPSILON in nextTokens:\n                    endOfRuleState = self.atn.ruleToStopState[config.state.ruleIndex]\n                    result.add(ATNConfig(state=endOfRuleState, config=config), self.mergeCache)\n        return result\n\n    def computeStartState(self, p:ATNState, ctx:RuleContext, fullCtx:bool):\n        # always at least the implicit call to start rule\n        initialContext = PredictionContextFromRuleContext(self.atn, ctx)\n        configs = ATNConfigSet(fullCtx)\n\n        if ParserATNSimulator.trace_atn_sim:\n            print(\"computeStartState from ATN state \"+str(p)+\n                  \" initialContext=\"+str(initialContext))\n\n        for i in range(0, len(p.transitions)):\n            target = p.transitions[i].target\n            c = ATNConfig(target, i+1, initialContext)\n            closureBusy = set()\n            self.closure(c, configs, closureBusy, True, fullCtx, False)\n        return configs\n\n    #\n    # This method transforms the start state computed by\n    # {@link #computeStartState} to the special start state used by a\n    # precedence DFA for a particular precedence value. The transformation\n    # process applies the following changes to the start state's configuration\n    # set.\n    #\n    # <ol>\n    # <li>Evaluate the precedence predicates for each configuration using\n    # {@link SemanticContext#evalPrecedence}.</li>\n    # <li>Remove all configurations which predict an alternative greater than\n    # 1, for which another configuration that predicts alternative 1 is in the\n    # same ATN state with the same prediction context. This transformation is\n    # valid for the following reasons:\n    # <ul>\n    # <li>The closure block cannot contain any epsilon transitions which bypass\n    # the body of the closure, so all states reachable via alternative 1 are\n    # part of the precedence alternatives of the transformed left-recursive\n    # rule.</li>\n    # <li>The \"primary\" portion of a left recursive rule cannot contain an\n    # epsilon transition, so the only way an alternative other than 1 can exist\n    # in a state that is also reachable via alternative 1 is by nesting calls\n    # to the left-recursive rule, with the outer calls not being at the\n    # preferred precedence level.</li>\n    # </ul>\n    # </li>\n    # </ol>\n    #\n    # <p>\n    # The prediction context must be considered by this filter to address\n    # situations like the following.\n    # </p>\n    # <code>\n    # <pre>\n    # grammar TA;\n    # prog: statement* EOF;\n    # statement: letterA | statement letterA 'b' ;\n    # letterA: 'a';\n    # </pre>\n    # </code>\n    # <p>\n    # If the above grammar, the ATN state immediately before the token\n    # reference {@code 'a'} in {@code letterA} is reachable from the left edge\n    # of both the primary and closure blocks of the left-recursive rule\n    # {@code statement}. The prediction context associated with each of these\n    # configurations distinguishes between them, and prevents the alternative\n    # which stepped out to {@code prog} (and then back in to {@code statement}\n    # from being eliminated by the filter.\n    # </p>\n    #\n    # @param configs The configuration set computed by\n    # {@link #computeStartState} as the start state for the DFA.\n    # @return The transformed configuration set representing the start state\n    # for a precedence DFA at a particular precedence level (determined by\n    # calling {@link Parser#getPrecedence}).\n    #\n    def applyPrecedenceFilter(self, configs:ATNConfigSet):\n        statesFromAlt1 = dict()\n        configSet = ATNConfigSet(configs.fullCtx)\n        for config in configs:\n            # handle alt 1 first\n            if config.alt != 1:\n                continue\n            updatedContext = config.semanticContext.evalPrecedence(self.parser, self._outerContext)\n            if updatedContext is None:\n                # the configuration was eliminated\n                continue\n\n            statesFromAlt1[config.state.stateNumber] = config.context\n            if updatedContext is not config.semanticContext:\n                configSet.add(ATNConfig(config=config, semantic=updatedContext), self.mergeCache)\n            else:\n                configSet.add(config, self.mergeCache)\n\n        for config in configs:\n            if config.alt == 1:\n                # already handled\n                continue\n\n            # In the future, this elimination step could be updated to also\n            # filter the prediction context for alternatives predicting alt>1\n            # (basically a graph subtraction algorithm).\n            #\n            if not config.precedenceFilterSuppressed:\n                context = statesFromAlt1.get(config.state.stateNumber, None)\n                if context==config.context:\n                    # eliminated\n                    continue\n\n            configSet.add(config, self.mergeCache)\n\n        return configSet\n\n    def getReachableTarget(self, trans:Transition, ttype:int):\n        if trans.matches(ttype, 0, self.atn.maxTokenType):\n            return trans.target\n        else:\n            return None\n\n    def getPredsForAmbigAlts(self, ambigAlts:set, configs:ATNConfigSet, nalts:int):\n        # REACH=[1|1|[]|0:0, 1|2|[]|0:1]\n        # altToPred starts as an array of all null contexts. The entry at index i\n        # corresponds to alternative i. altToPred[i] may have one of three values:\n        #   1. null: no ATNConfig c is found such that c.alt==i\n        #   2. SemanticContext.NONE: At least one ATNConfig c exists such that\n        #      c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,\n        #      alt i has at least one unpredicated config.\n        #   3. Non-NONE Semantic Context: There exists at least one, and for all\n        #      ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.\n        #\n        # From this, it is clear that NONE||anything==NONE.\n        #\n        altToPred = [None] * (nalts + 1)\n        for c in configs:\n            if c.alt in ambigAlts:\n                altToPred[c.alt] = orContext(altToPred[c.alt], c.semanticContext)\n\n        nPredAlts = 0\n        for i in range(1, nalts+1):\n            if altToPred[i] is None:\n                altToPred[i] = SemanticContext.NONE\n            elif altToPred[i] is not SemanticContext.NONE:\n                nPredAlts += 1\n\n        # nonambig alts are null in altToPred\n        if nPredAlts==0:\n            altToPred = None\n        if ParserATNSimulator.debug:\n            print(\"getPredsForAmbigAlts result \" + str_list(altToPred))\n        return altToPred\n\n    def getPredicatePredictions(self, ambigAlts:set, altToPred:list):\n        pairs = []\n        containsPredicate = False\n        for i in range(1, len(altToPred)):\n            pred = altToPred[i]\n            # unpredicated is indicated by SemanticContext.NONE\n            if ambigAlts is not None and i in ambigAlts:\n                pairs.append(PredPrediction(pred, i))\n            if pred is not SemanticContext.NONE:\n                containsPredicate = True\n\n        if not containsPredicate:\n            return None\n\n        return pairs\n\n    #\n    # This method is used to improve the localization of error messages by\n    # choosing an alternative rather than throwing a\n    # {@link NoViableAltException} in particular prediction scenarios where the\n    # {@link #ERROR} state was reached during ATN simulation.\n    #\n    # <p>\n    # The default implementation of this method uses the following\n    # algorithm to identify an ATN configuration which successfully parsed the\n    # decision entry rule. Choosing such an alternative ensures that the\n    # {@link ParserRuleContext} returned by the calling rule will be complete\n    # and valid, and the syntax error will be reported later at a more\n    # localized location.</p>\n    #\n    # <ul>\n    # <li>If a syntactically valid path or paths reach the end of the decision rule and\n    # they are semantically valid if predicated, return the min associated alt.</li>\n    # <li>Else, if a semantically invalid but syntactically valid path exist\n    # or paths exist, return the minimum associated alt.\n    # </li>\n    # <li>Otherwise, return {@link ATN#INVALID_ALT_NUMBER}.</li>\n    # </ul>\n    #\n    # <p>\n    # In some scenarios, the algorithm described above could predict an\n    # alternative which will result in a {@link FailedPredicateException} in\n    # the parser. Specifically, this could occur if the <em>only</em> configuration\n    # capable of successfully parsing to the end of the decision rule is\n    # blocked by a semantic predicate. By choosing this alternative within\n    # {@link #adaptivePredict} instead of throwing a\n    # {@link NoViableAltException}, the resulting\n    # {@link FailedPredicateException} in the parser will identify the specific\n    # predicate which is preventing the parser from successfully parsing the\n    # decision rule, which helps developers identify and correct logic errors\n    # in semantic predicates.\n    # </p>\n    #\n    # @param configs The ATN configurations which were valid immediately before\n    # the {@link #ERROR} state was reached\n    # @param outerContext The is the \\gamma_0 initial parser context from the paper\n    # or the parser stack at the instant before prediction commences.\n    #\n    # @return The value to return from {@link #adaptivePredict}, or\n    # {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not\n    # identified and {@link #adaptivePredict} should report an error instead.\n    #\n    def getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(self, configs:ATNConfigSet, outerContext:ParserRuleContext):\n        semValidConfigs, semInvalidConfigs = self.splitAccordingToSemanticValidity(configs, outerContext)\n        alt = self.getAltThatFinishedDecisionEntryRule(semValidConfigs)\n        if alt!=ATN.INVALID_ALT_NUMBER: # semantically/syntactically viable path exists\n            return alt\n        # Is there a syntactically valid path with a failed pred?\n        if len(semInvalidConfigs)>0:\n            alt = self.getAltThatFinishedDecisionEntryRule(semInvalidConfigs)\n            if alt!=ATN.INVALID_ALT_NUMBER: # syntactically viable path exists\n                return alt\n        return ATN.INVALID_ALT_NUMBER\n\n    def getAltThatFinishedDecisionEntryRule(self, configs:ATNConfigSet):\n        alts = set()\n        for c in configs:\n            if c.reachesIntoOuterContext>0 or (isinstance(c.state, RuleStopState) and c.context.hasEmptyPath() ):\n                alts.add(c.alt)\n        if len(alts)==0:\n            return ATN.INVALID_ALT_NUMBER\n        else:\n            return min(alts)\n\n    # Walk the list of configurations and split them according to\n    #  those that have preds evaluating to true/false.  If no pred, assume\n    #  true pred and include in succeeded set.  Returns Pair of sets.\n    #\n    #  Create a new set so as not to alter the incoming parameter.\n    #\n    #  Assumption: the input stream has been restored to the starting point\n    #  prediction, which is where predicates need to evaluate.\n    #\n    def splitAccordingToSemanticValidity(self, configs:ATNConfigSet, outerContext:ParserRuleContext):\n        succeeded = ATNConfigSet(configs.fullCtx)\n        failed = ATNConfigSet(configs.fullCtx)\n        for c in configs:\n            if c.semanticContext is not SemanticContext.NONE:\n                predicateEvaluationResult = c.semanticContext.eval(self.parser, outerContext)\n                if predicateEvaluationResult:\n                    succeeded.add(c)\n                else:\n                    failed.add(c)\n            else:\n                succeeded.add(c)\n        return (succeeded,failed)\n\n    # Look through a list of predicate/alt pairs, returning alts for the\n    #  pairs that win. A {@code NONE} predicate indicates an alt containing an\n    #  unpredicated config which behaves as \"always true.\" If !complete\n    #  then we stop at the first predicate that evaluates to true. This\n    #  includes pairs with null predicates.\n    #\n    def evalSemanticContext(self, predPredictions:list, outerContext:ParserRuleContext, complete:bool):\n        predictions = set()\n        for pair in predPredictions:\n            if pair.pred is SemanticContext.NONE:\n                predictions.add(pair.alt)\n                if not complete:\n                    break\n                continue\n            predicateEvaluationResult = pair.pred.eval(self.parser, outerContext)\n            if ParserATNSimulator.debug or ParserATNSimulator.dfa_debug:\n                print(\"eval pred \" + str(pair) + \"=\" + str(predicateEvaluationResult))\n\n            if predicateEvaluationResult:\n                if ParserATNSimulator.debug or ParserATNSimulator.dfa_debug:\n                    print(\"PREDICT \" + str(pair.alt))\n                predictions.add(pair.alt)\n                if not complete:\n                    break\n        return predictions\n\n\n    # TODO: If we are doing predicates, there is no point in pursuing\n    #     closure operations if we reach a DFA state that uniquely predicts\n    #     alternative. We will not be caching that DFA state and it is a\n    #     waste to pursue the closure. Might have to advance when we do\n    #     ambig detection thought :(\n    #\n\n    def closure(self, config:ATNConfig, configs:ATNConfigSet, closureBusy:set, collectPredicates:bool, fullCtx:bool, treatEofAsEpsilon:bool):\n        initialDepth = 0\n        self.closureCheckingStopState(config, configs, closureBusy, collectPredicates,\n                                 fullCtx, initialDepth, treatEofAsEpsilon)\n\n\n    def closureCheckingStopState(self, config:ATNConfig, configs:ATNConfigSet, closureBusy:set, collectPredicates:bool, fullCtx:bool, depth:int, treatEofAsEpsilon:bool):\n        if ParserATNSimulator.trace_atn_sim:\n            print(\"closure(\" + str(config) + \")\")\n\n        if isinstance(config.state, RuleStopState):\n            # We hit rule end. If we have context info, use it\n            # run thru all possible stack tops in ctx\n            if not config.context.isEmpty():\n                for i in range(0, len(config.context)):\n                    state = config.context.getReturnState(i)\n                    if state is PredictionContext.EMPTY_RETURN_STATE:\n                        if fullCtx:\n                            configs.add(ATNConfig(state=config.state, context=PredictionContext.EMPTY, config=config), self.mergeCache)\n                            continue\n                        else:\n                            # we have no context info, just chase follow links (if greedy)\n                            if ParserATNSimulator.debug:\n                                print(\"FALLING off rule \" + self.getRuleName(config.state.ruleIndex))\n                            self.closure_(config, configs, closureBusy, collectPredicates,\n                                     fullCtx, depth, treatEofAsEpsilon)\n                        continue\n                    returnState = self.atn.states[state]\n                    newContext = config.context.getParent(i) # \"pop\" return state\n                    c = ATNConfig(state=returnState, alt=config.alt, context=newContext, semantic=config.semanticContext)\n                    # While we have context to pop back from, we may have\n                    # gotten that context AFTER having falling off a rule.\n                    # Make sure we track that we are now out of context.\n                    c.reachesIntoOuterContext = config.reachesIntoOuterContext\n                    self.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon)\n                return\n            elif fullCtx:\n                # reached end of start rule\n                configs.add(config, self.mergeCache)\n                return\n            else:\n                # else if we have no context info, just chase follow links (if greedy)\n                if ParserATNSimulator.debug:\n                    print(\"FALLING off rule \" + self.getRuleName(config.state.ruleIndex))\n\n        self.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon)\n\n    # Do the actual work of walking epsilon edges#\n    def closure_(self, config:ATNConfig, configs:ATNConfigSet, closureBusy:set, collectPredicates:bool, fullCtx:bool, depth:int, treatEofAsEpsilon:bool):\n        p = config.state\n        # optimization\n        if not p.epsilonOnlyTransitions:\n            configs.add(config, self.mergeCache)\n            # make sure to not return here, because EOF transitions can act as\n            # both epsilon transitions and non-epsilon transitions.\n\n        first = True\n        for t in p.transitions:\n            if first:\n                first = False\n                if self.canDropLoopEntryEdgeInLeftRecursiveRule(config):\n                    continue\n\n            continueCollecting = collectPredicates and not isinstance(t, ActionTransition)\n            c = self.getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEofAsEpsilon)\n            if c is not None:\n                newDepth = depth\n                if isinstance( config.state, RuleStopState):\n                    # target fell off end of rule; mark resulting c as having dipped into outer context\n                    # We can't get here if incoming config was rule stop and we had context\n                    # track how far we dip into outer context.  Might\n                    # come in handy and we avoid evaluating context dependent\n                    # preds if this is > 0.\n                    if self._dfa is not None and self._dfa.precedenceDfa:\n                        if t.outermostPrecedenceReturn == self._dfa.atnStartState.ruleIndex:\n                            c.precedenceFilterSuppressed = True\n                    c.reachesIntoOuterContext += 1\n                    if c in closureBusy:\n                        # avoid infinite recursion for right-recursive rules\n                        continue\n                    closureBusy.add(c)\n                    configs.dipsIntoOuterContext = True # TODO: can remove? only care when we add to set per middle of this method\n                    newDepth -= 1\n                    if ParserATNSimulator.debug:\n                        print(\"dips into outer ctx: \" + str(c))\n                else:\n                    if not t.isEpsilon:\n                        if c in closureBusy:\n                            # avoid infinite recursion for EOF* and EOF+\n                            continue\n                        closureBusy.add(c)\n                    if isinstance(t, RuleTransition):\n                        # latch when newDepth goes negative - once we step out of the entry context we can't return\n                        if newDepth >= 0:\n                            newDepth += 1\n\n                self.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon)\n\n\n\n    # Implements first-edge (loop entry) elimination as an optimization\n    #  during closure operations.  See antlr/antlr4#1398.\n    #\n    # The optimization is to avoid adding the loop entry config when\n    # the exit path can only lead back to the same\n    # StarLoopEntryState after popping context at the rule end state\n    # (traversing only epsilon edges, so we're still in closure, in\n    # this same rule).\n    #\n    # We need to detect any state that can reach loop entry on\n    # epsilon w/o exiting rule. We don't have to look at FOLLOW\n    # links, just ensure that all stack tops for config refer to key\n    # states in LR rule.\n    #\n    # To verify we are in the right situation we must first check\n    # closure is at a StarLoopEntryState generated during LR removal.\n    # Then we check that each stack top of context is a return state\n    # from one of these cases:\n    #\n    #   1. 'not' expr, '(' type ')' expr. The return state points at loop entry state\n    #   2. expr op expr. The return state is the block end of internal block of (...)*\n    #   3. 'between' expr 'and' expr. The return state of 2nd expr reference.\n    #      That state points at block end of internal block of (...)*.\n    #   4. expr '?' expr ':' expr. The return state points at block end,\n    #      which points at loop entry state.\n    #\n    # If any is true for each stack top, then closure does not add a\n    # config to the current config set for edge[0], the loop entry branch.\n    #\n    #  Conditions fail if any context for the current config is:\n    #\n    #   a. empty (we'd fall out of expr to do a global FOLLOW which could\n    #      even be to some weird spot in expr) or,\n    #   b. lies outside of expr or,\n    #   c. lies within expr but at a state not the BlockEndState\n    #   generated during LR removal\n    #\n    # Do we need to evaluate predicates ever in closure for this case?\n    #\n    # No. Predicates, including precedence predicates, are only\n    # evaluated when computing a DFA start state. I.e., only before\n    # the lookahead (but not parser) consumes a token.\n    #\n    # There are no epsilon edges allowed in LR rule alt blocks or in\n    # the \"primary\" part (ID here). If closure is in\n    # StarLoopEntryState any lookahead operation will have consumed a\n    # token as there are no epsilon-paths that lead to\n    # StarLoopEntryState. We do not have to evaluate predicates\n    # therefore if we are in the generated StarLoopEntryState of a LR\n    # rule. Note that when making a prediction starting at that\n    # decision point, decision d=2, compute-start-state performs\n    # closure starting at edges[0], edges[1] emanating from\n    # StarLoopEntryState. That means it is not performing closure on\n    # StarLoopEntryState during compute-start-state.\n    #\n    # How do we know this always gives same prediction answer?\n    #\n    # Without predicates, loop entry and exit paths are ambiguous\n    # upon remaining input +b (in, say, a+b). Either paths lead to\n    # valid parses. Closure can lead to consuming + immediately or by\n    # falling out of this call to expr back into expr and loop back\n    # again to StarLoopEntryState to match +b. In this special case,\n    # we choose the more efficient path, which is to take the bypass\n    # path.\n    #\n    # The lookahead language has not changed because closure chooses\n    # one path over the other. Both paths lead to consuming the same\n    # remaining input during a lookahead operation. If the next token\n    # is an operator, lookahead will enter the choice block with\n    # operators. If it is not, lookahead will exit expr. Same as if\n    # closure had chosen to enter the choice block immediately.\n    #\n    # Closure is examining one config (some loopentrystate, some alt,\n    # context) which means it is considering exactly one alt. Closure\n    # always copies the same alt to any derived configs.\n    #\n    # How do we know this optimization doesn't mess up precedence in\n    # our parse trees?\n    #\n    # Looking through expr from left edge of stat only has to confirm\n    # that an input, say, a+b+c; begins with any valid interpretation\n    # of an expression. The precedence actually doesn't matter when\n    # making a decision in stat seeing through expr. It is only when\n    # parsing rule expr that we must use the precedence to get the\n    # right interpretation and, hence, parse tree.\n    #\n    # @since 4.6\n    #\n    def canDropLoopEntryEdgeInLeftRecursiveRule(self, config):\n        # return False\n        p = config.state\n        # First check to see if we are in StarLoopEntryState generated during\n        # left-recursion elimination. For efficiency, also check if\n        # the context has an empty stack case. If so, it would mean\n        # global FOLLOW so we can't perform optimization\n        # Are we the special loop entry/exit state? or SLL wildcard\n        if p.stateType != ATNState.STAR_LOOP_ENTRY  \\\n                or not p.isPrecedenceDecision       \\\n                or config.context.isEmpty()         \\\n                or config.context.hasEmptyPath():\n            return False\n\n        # Require all return states to return back to the same rule\n        # that p is in.\n        numCtxs = len(config.context)\n        for i in range(0, numCtxs):  # for each stack context\n            returnState = self.atn.states[config.context.getReturnState(i)]\n            if returnState.ruleIndex != p.ruleIndex:\n                return False\n\n        decisionStartState = p.transitions[0].target\n        blockEndStateNum = decisionStartState.endState.stateNumber\n        blockEndState = self.atn.states[blockEndStateNum]\n\n        # Verify that the top of each stack context leads to loop entry/exit\n        # state through epsilon edges and w/o leaving rule.\n        for i in range(0, numCtxs):  # for each stack context\n            returnStateNumber = config.context.getReturnState(i)\n            returnState = self.atn.states[returnStateNumber]\n            # all states must have single outgoing epsilon edge\n            if len(returnState.transitions) != 1 or not returnState.transitions[0].isEpsilon:\n                return False\n\n            # Look for prefix op case like 'not expr', (' type ')' expr\n            returnStateTarget = returnState.transitions[0].target\n            if returnState.stateType == ATNState.BLOCK_END and returnStateTarget is p:\n                continue\n\n            # Look for 'expr op expr' or case where expr's return state is block end\n            # of (...)* internal block; the block end points to loop back\n            # which points to p but we don't need to check that\n            if returnState is blockEndState:\n                continue\n\n            # Look for ternary expr ? expr : expr. The return state points at block end,\n            # which points at loop entry state\n            if returnStateTarget is blockEndState:\n                continue\n\n            # Look for complex prefix 'between expr and expr' case where 2nd expr's\n            # return state points at block end state of (...)* internal block\n            if returnStateTarget.stateType == ATNState.BLOCK_END \\\n                and len(returnStateTarget.transitions) == 1 \\\n                and returnStateTarget.transitions[0].isEpsilon \\\n                and returnStateTarget.transitions[0].target is p:\n                    continue\n\n            # anything else ain't conforming\n            return False\n\n        return True\n\n\n    def getRuleName(self, index:int):\n        if self.parser is not None and index>=0:\n            return self.parser.ruleNames[index]\n        else:\n            return \"<rule \" + str(index) + \">\"\n\n    epsilonTargetMethods = dict()\n    epsilonTargetMethods[Transition.RULE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        sim.ruleTransition(config, t)\n    epsilonTargetMethods[Transition.PRECEDENCE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        sim.precedenceTransition(config, t, collectPredicates, inContext, fullCtx)\n    epsilonTargetMethods[Transition.PREDICATE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        sim.predTransition(config, t, collectPredicates, inContext, fullCtx)\n    epsilonTargetMethods[Transition.ACTION] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        sim.actionTransition(config, t)\n    epsilonTargetMethods[Transition.EPSILON] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        ATNConfig(state=t.target, config=config)\n    epsilonTargetMethods[Transition.ATOM] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        ATNConfig(state=t.target, config=config) if treatEofAsEpsilon and t.matches(Token.EOF, 0, 1) else None\n    epsilonTargetMethods[Transition.RANGE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        ATNConfig(state=t.target, config=config) if treatEofAsEpsilon and t.matches(Token.EOF, 0, 1) else None\n    epsilonTargetMethods[Transition.SET] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \\\n        ATNConfig(state=t.target, config=config) if treatEofAsEpsilon and t.matches(Token.EOF, 0, 1) else None\n\n    def getEpsilonTarget(self, config:ATNConfig, t:Transition, collectPredicates:bool, inContext:bool, fullCtx:bool, treatEofAsEpsilon:bool):\n        m = self.epsilonTargetMethods.get(t.serializationType, None)\n        if m is None:\n            return None\n        else:\n            return m(self, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon)\n\n    def actionTransition(self, config:ATNConfig, t:ActionTransition):\n        if ParserATNSimulator.debug:\n            print(\"ACTION edge \" + str(t.ruleIndex) + \":\" + str(t.actionIndex))\n        return ATNConfig(state=t.target, config=config)\n\n    def precedenceTransition(self, config:ATNConfig, pt:PrecedencePredicateTransition,  collectPredicates:bool, inContext:bool, fullCtx:bool):\n        if ParserATNSimulator.debug:\n            print(\"PRED (collectPredicates=\" + str(collectPredicates) + \") \" +\n                    str(pt.precedence) + \">=_p, ctx dependent=true\")\n            if self.parser is not None:\n                print(\"context surrounding pred is \" + str(self.parser.getRuleInvocationStack()))\n\n        c = None\n        if collectPredicates and inContext:\n            if fullCtx:\n                # In full context mode, we can evaluate predicates on-the-fly\n                # during closure, which dramatically reduces the size of\n                # the config sets. It also obviates the need to test predicates\n                # later during conflict resolution.\n                currentPosition = self._input.index\n                self._input.seek(self._startIndex)\n                predSucceeds = pt.getPredicate().eval(self.parser, self._outerContext)\n                self._input.seek(currentPosition)\n                if predSucceeds:\n                    c = ATNConfig(state=pt.target, config=config) # no pred context\n            else:\n                newSemCtx = andContext(config.semanticContext, pt.getPredicate())\n                c = ATNConfig(state=pt.target, semantic=newSemCtx, config=config)\n        else:\n            c = ATNConfig(state=pt.target, config=config)\n\n        if ParserATNSimulator.debug:\n            print(\"config from pred transition=\" + str(c))\n        return c\n\n    def predTransition(self, config:ATNConfig, pt:PredicateTransition, collectPredicates:bool, inContext:bool, fullCtx:bool):\n        if ParserATNSimulator.debug:\n            print(\"PRED (collectPredicates=\" + str(collectPredicates) + \") \" + str(pt.ruleIndex) +\n                    \":\" + str(pt.predIndex) + \", ctx dependent=\" + str(pt.isCtxDependent))\n            if self.parser is not None:\n                print(\"context surrounding pred is \" + str(self.parser.getRuleInvocationStack()))\n\n        c = None\n        if collectPredicates and (not pt.isCtxDependent or (pt.isCtxDependent and inContext)):\n            if fullCtx:\n                # In full context mode, we can evaluate predicates on-the-fly\n                # during closure, which dramatically reduces the size of\n                # the config sets. It also obviates the need to test predicates\n                # later during conflict resolution.\n                currentPosition = self._input.index\n                self._input.seek(self._startIndex)\n                predSucceeds = pt.getPredicate().eval(self.parser, self._outerContext)\n                self._input.seek(currentPosition)\n                if predSucceeds:\n                    c = ATNConfig(state=pt.target, config=config) # no pred context\n            else:\n                newSemCtx = andContext(config.semanticContext, pt.getPredicate())\n                c = ATNConfig(state=pt.target, semantic=newSemCtx, config=config)\n        else:\n            c = ATNConfig(state=pt.target, config=config)\n\n        if ParserATNSimulator.debug:\n            print(\"config from pred transition=\" + str(c))\n        return c\n\n    def ruleTransition(self, config:ATNConfig, t:RuleTransition):\n        if ParserATNSimulator.debug:\n            print(\"CALL rule \" + self.getRuleName(t.target.ruleIndex) + \", ctx=\" + str(config.context))\n        returnState = t.followState\n        newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber)\n        return ATNConfig(state=t.target, context=newContext, config=config )\n\n    def getConflictingAlts(self, configs:ATNConfigSet):\n        altsets = PredictionMode.getConflictingAltSubsets(configs)\n        return PredictionMode.getAlts(altsets)\n\n     # Sam pointed out a problem with the previous definition, v3, of\n     # ambiguous states. If we have another state associated with conflicting\n     # alternatives, we should keep going. For example, the following grammar\n     #\n     # s : (ID | ID ID?) ';' ;\n     #\n     # When the ATN simulation reaches the state before ';', it has a DFA\n     # state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally\n     # 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node\n     # because alternative to has another way to continue, via [6|2|[]].\n     # The key is that we have a single state that has config's only associated\n     # with a single alternative, 2, and crucially the state transitions\n     # among the configurations are all non-epsilon transitions. That means\n     # we don't consider any conflicts that include alternative 2. So, we\n     # ignore the conflict between alts 1 and 2. We ignore a set of\n     # conflicting alts when there is an intersection with an alternative\n     # associated with a single alt state in the state&rarr;config-list map.\n     #\n     # It's also the case that we might have two conflicting configurations but\n     # also a 3rd nonconflicting configuration for a different alternative:\n     # [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:\n     #\n     # a : A | A | A B ;\n     #\n     # After matching input A, we reach the stop state for rule A, state 1.\n     # State 8 is the state right before B. Clearly alternatives 1 and 2\n     # conflict and no amount of further lookahead will separate the two.\n     # However, alternative 3 will be able to continue and so we do not\n     # stop working on this state. In the previous example, we're concerned\n     # with states associated with the conflicting alternatives. Here alt\n     # 3 is not associated with the conflicting configs, but since we can continue\n     # looking for input reasonably, I don't declare the state done. We\n     # ignore a set of conflicting alts when we have an alternative\n     # that we still need to pursue.\n    #\n\n    def getConflictingAltsOrUniqueAlt(self, configs:ATNConfigSet):\n        conflictingAlts = None\n        if configs.uniqueAlt!= ATN.INVALID_ALT_NUMBER:\n            conflictingAlts = set()\n            conflictingAlts.add(configs.uniqueAlt)\n        else:\n            conflictingAlts = configs.conflictingAlts\n        return conflictingAlts\n\n    def getTokenName(self, t:int):\n        if t==Token.EOF:\n            return \"EOF\"\n        if self.parser is not None and \\\n                self.parser.literalNames is not None and \\\n                t < len(self.parser.literalNames):\n            return self.parser.literalNames[t] + \"<\" + str(t) + \">\"\n        if self.parser is not None and \\\n                self.parser.symbolicNames is not None and \\\n                t < len(self.parser.symbolicNames):\n            return self.parser.symbolicNames[t] + \"<\" + str(t) + \">\"\n        else:\n            return str(t)\n\n    def getLookaheadName(self, input:TokenStream):\n        return self.getTokenName(input.LA(1))\n\n    # Used for debugging in adaptivePredict around execATN but I cut\n    #  it out for clarity now that alg. works well. We can leave this\n    #  \"dead\" code for a bit.\n    #\n    def dumpDeadEndConfigs(self, nvae:NoViableAltException):\n        print(\"dead end configs: \")\n        for c in nvae.getDeadEndConfigs():\n            trans = \"no edges\"\n            if len(c.state.transitions)>0:\n                t = c.state.transitions[0]\n                if isinstance(t, AtomTransition):\n                    trans = \"Atom \"+ self.getTokenName(t.label)\n                elif isinstance(t, SetTransition):\n                    neg = isinstance(t, NotSetTransition)\n                    trans = (\"~\" if neg else \"\")+\"Set \"+ str(t.set)\n            print(c.toString(self.parser, True) + \":\" + trans, file=sys.stderr)\n\n    def noViableAlt(self, input:TokenStream, outerContext:ParserRuleContext, configs:ATNConfigSet, startIndex:int):\n        return NoViableAltException(self.parser, input, input.get(startIndex), input.LT(1), configs, outerContext)\n\n    def getUniqueAlt(self, configs:ATNConfigSet):\n        alt = ATN.INVALID_ALT_NUMBER\n        for c in configs:\n            if alt == ATN.INVALID_ALT_NUMBER:\n                alt = c.alt # found first alt\n            elif c.alt!=alt:\n                return ATN.INVALID_ALT_NUMBER\n        return alt\n\n    #\n    # Add an edge to the DFA, if possible. This method calls\n    # {@link #addDFAState} to ensure the {@code to} state is present in the\n    # DFA. If {@code from} is {@code null}, or if {@code t} is outside the\n    # range of edges that can be represented in the DFA tables, this method\n    # returns without adding the edge to the DFA.\n    #\n    # <p>If {@code to} is {@code null}, this method returns {@code null}.\n    # Otherwise, this method returns the {@link DFAState} returned by calling\n    # {@link #addDFAState} for the {@code to} state.</p>\n    #\n    # @param dfa The DFA\n    # @param from The source state for the edge\n    # @param t The input symbol\n    # @param to The target state for the edge\n    #\n    # @return If {@code to} is {@code null}, this method returns {@code null};\n    # otherwise this method returns the result of calling {@link #addDFAState}\n    # on {@code to}\n    #\n    def addDFAEdge(self, dfa:DFA, from_:DFAState, t:int, to:DFAState):\n        if ParserATNSimulator.debug:\n            print(\"EDGE \" + str(from_) + \" -> \" + str(to) + \" upon \" + self.getTokenName(t))\n\n        if to is None:\n            return None\n\n        to = self.addDFAState(dfa, to) # used existing if possible not incoming\n        if from_ is None or t < -1 or t > self.atn.maxTokenType:\n            return to\n\n        if from_.edges is None:\n            from_.edges = [None] * (self.atn.maxTokenType + 2)\n        from_.edges[t+1] = to # connect\n\n        if ParserATNSimulator.debug:\n            names = None if self.parser is None else self.parser.literalNames\n            print(\"DFA=\\n\" + dfa.toString(names))\n\n        return to\n\n    #\n    # Add state {@code D} to the DFA if it is not already present, and return\n    # the actual instance stored in the DFA. If a state equivalent to {@code D}\n    # is already in the DFA, the existing state is returned. Otherwise this\n    # method returns {@code D} after adding it to the DFA.\n    #\n    # <p>If {@code D} is {@link #ERROR}, this method returns {@link #ERROR} and\n    # does not change the DFA.</p>\n    #\n    # @param dfa The dfa\n    # @param D The DFA state to add\n    # @return The state stored in the DFA. This will be either the existing\n    # state if {@code D} is already in the DFA, or {@code D} itself if the\n    # state was not already present.\n    #\n    def addDFAState(self, dfa:DFA, D:DFAState):\n        if D is self.ERROR:\n            return D\n\n\n        existing = dfa.states.get(D, None)\n        if existing is not None:\n            if ParserATNSimulator.trace_atn_sim: print(\"addDFAState\", str(D), \"exists\")\n            return existing\n\n        D.stateNumber = len(dfa.states)\n        if not D.configs.readonly:\n            D.configs.optimizeConfigs(self)\n            D.configs.setReadonly(True)\n\n        if ParserATNSimulator.trace_atn_sim: print(\"addDFAState new\", str(D))\n\n        dfa.states[D] = D\n        return D\n\n    def reportAttemptingFullContext(self, dfa:DFA, conflictingAlts:set, configs:ATNConfigSet, startIndex:int, stopIndex:int):\n        if ParserATNSimulator.debug or ParserATNSimulator.retry_debug:\n            print(\"reportAttemptingFullContext decision=\" + str(dfa.decision) + \":\" + str(configs) +\n                               \", input=\" + self.parser.getTokenStream().getText(startIndex, stopIndex))\n        if self.parser is not None:\n            self.parser.getErrorListenerDispatch().reportAttemptingFullContext(self.parser, dfa, startIndex, stopIndex, conflictingAlts, configs)\n\n    def reportContextSensitivity(self, dfa:DFA, prediction:int, configs:ATNConfigSet, startIndex:int, stopIndex:int):\n        if ParserATNSimulator.debug or ParserATNSimulator.retry_debug:\n            print(\"reportContextSensitivity decision=\" + str(dfa.decision) + \":\" + str(configs) +\n                               \", input=\" + self.parser.getTokenStream().getText(startIndex, stopIndex))\n        if self.parser is not None:\n            self.parser.getErrorListenerDispatch().reportContextSensitivity(self.parser, dfa, startIndex, stopIndex, prediction, configs)\n\n    # If context sensitive parsing, we know it's ambiguity not conflict#\n    def reportAmbiguity(self, dfa:DFA, D:DFAState, startIndex:int, stopIndex:int,\n                                   exact:bool, ambigAlts:set, configs:ATNConfigSet ):\n        if ParserATNSimulator.debug or ParserATNSimulator.retry_debug:\n#\t\t\tParserATNPathFinder finder = new ParserATNPathFinder(parser, atn);\n#\t\t\tint i = 1;\n#\t\t\tfor (Transition t : dfa.atnStartState.transitions) {\n#\t\t\t\tprint(\"ALT \"+i+\"=\");\n#\t\t\t\tprint(startIndex+\"..\"+stopIndex+\", len(input)=\"+parser.getInputStream().size());\n#\t\t\t\tTraceTree path = finder.trace(t.target, parser.getContext(), (TokenStream)parser.getInputStream(),\n#\t\t\t\t\t\t\t\t\t\t\t  startIndex, stopIndex);\n#\t\t\t\tif ( path!=null ) {\n#\t\t\t\t\tprint(\"path = \"+path.toStringTree());\n#\t\t\t\t\tfor (TraceTree leaf : path.leaves) {\n#\t\t\t\t\t\tList<ATNState> states = path.getPathToNode(leaf);\n#\t\t\t\t\t\tprint(\"states=\"+states);\n#\t\t\t\t\t}\n#\t\t\t\t}\n#\t\t\t\ti++;\n#\t\t\t}\n            print(\"reportAmbiguity \" + str(ambigAlts) + \":\" + str(configs) +\n                               \", input=\" + self.parser.getTokenStream().getText(startIndex, stopIndex))\n        if self.parser is not None:\n            self.parser.getErrorListenerDispatch().reportAmbiguity(self.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/PredictionMode.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n#\n# This enumeration defines the prediction modes available in ANTLR 4 along with\n# utility methods for analyzing configuration sets for conflicts and/or\n# ambiguities.\n\n\nfrom enum import Enum\nfrom ..atn.ATN import ATN\nfrom ..atn.ATNConfig import ATNConfig\nfrom ..atn.ATNConfigSet import ATNConfigSet\nfrom ..atn.ATNState import RuleStopState\nfrom ..atn.SemanticContext import SemanticContext\n\nPredictionMode = None\n\nclass PredictionMode(Enum):\n    #\n    # The SLL(*) prediction mode. This prediction mode ignores the current\n    # parser context when making predictions. This is the fastest prediction\n    # mode, and provides correct results for many grammars. This prediction\n    # mode is more powerful than the prediction mode provided by ANTLR 3, but\n    # may result in syntax errors for grammar and input combinations which are\n    # not SLL.\n    #\n    # <p>\n    # When using this prediction mode, the parser will either return a correct\n    # parse tree (i.e. the same parse tree that would be returned with the\n    # {@link #LL} prediction mode), or it will report a syntax error. If a\n    # syntax error is encountered when using the {@link #SLL} prediction mode,\n    # it may be due to either an actual syntax error in the input or indicate\n    # that the particular combination of grammar and input requires the more\n    # powerful {@link #LL} prediction abilities to complete successfully.</p>\n    #\n    # <p>\n    # This prediction mode does not provide any guarantees for prediction\n    # behavior for syntactically-incorrect inputs.</p>\n    #\n    SLL = 0\n    #\n    # The LL(*) prediction mode. This prediction mode allows the current parser\n    # context to be used for resolving SLL conflicts that occur during\n    # prediction. This is the fastest prediction mode that guarantees correct\n    # parse results for all combinations of grammars with syntactically correct\n    # inputs.\n    #\n    # <p>\n    # When using this prediction mode, the parser will make correct decisions\n    # for all syntactically-correct grammar and input combinations. However, in\n    # cases where the grammar is truly ambiguous this prediction mode might not\n    # report a precise answer for <em>exactly which</em> alternatives are\n    # ambiguous.</p>\n    #\n    # <p>\n    # This prediction mode does not provide any guarantees for prediction\n    # behavior for syntactically-incorrect inputs.</p>\n    #\n    LL = 1\n    #\n    # The LL(*) prediction mode with exact ambiguity detection. In addition to\n    # the correctness guarantees provided by the {@link #LL} prediction mode,\n    # this prediction mode instructs the prediction algorithm to determine the\n    # complete and exact set of ambiguous alternatives for every ambiguous\n    # decision encountered while parsing.\n    #\n    # <p>\n    # This prediction mode may be used for diagnosing ambiguities during\n    # grammar development. Due to the performance overhead of calculating sets\n    # of ambiguous alternatives, this prediction mode should be avoided when\n    # the exact results are not necessary.</p>\n    #\n    # <p>\n    # This prediction mode does not provide any guarantees for prediction\n    # behavior for syntactically-incorrect inputs.</p>\n    #\n    LL_EXACT_AMBIG_DETECTION = 2\n\n\n    #\n    # Computes the SLL prediction termination condition.\n    #\n    # <p>\n    # This method computes the SLL prediction termination condition for both of\n    # the following cases.</p>\n    #\n    # <ul>\n    # <li>The usual SLL+LL fallback upon SLL conflict</li>\n    # <li>Pure SLL without LL fallback</li>\n    # </ul>\n    #\n    # <p><strong>COMBINED SLL+LL PARSING</strong></p>\n    #\n    # <p>When LL-fallback is enabled upon SLL conflict, correct predictions are\n    # ensured regardless of how the termination condition is computed by this\n    # method. Due to the substantially higher cost of LL prediction, the\n    # prediction should only fall back to LL when the additional lookahead\n    # cannot lead to a unique SLL prediction.</p>\n    #\n    # <p>Assuming combined SLL+LL parsing, an SLL configuration set with only\n    # conflicting subsets should fall back to full LL, even if the\n    # configuration sets don't resolve to the same alternative (e.g.\n    # {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting\n    # configuration, SLL could continue with the hopes that more lookahead will\n    # resolve via one of those non-conflicting configurations.</p>\n    #\n    # <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n    # stops when it sees only conflicting configuration subsets. In contrast,\n    # full LL keeps going when there is uncertainty.</p>\n    #\n    # <p><strong>HEURISTIC</strong></p>\n    #\n    # <p>As a heuristic, we stop prediction when we see any conflicting subset\n    # unless we see a state that only has one alternative associated with it.\n    # The single-alt-state thing lets prediction continue upon rules like\n    # (otherwise, it would admit defeat too soon):</p>\n    #\n    # <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>\n    #\n    # <p>When the ATN simulation reaches the state before {@code ';'}, it has a\n    # DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally\n    # {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop\n    # processing this node because alternative to has another way to continue,\n    # via {@code [6|2|[]]}.</p>\n    #\n    # <p>It also let's us continue for this rule:</p>\n    #\n    # <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>\n    #\n    # <p>After matching input A, we reach the stop state for rule A, state 1.\n    # State 8 is the state right before B. Clearly alternatives 1 and 2\n    # conflict and no amount of further lookahead will separate the two.\n    # However, alternative 3 will be able to continue and so we do not stop\n    # working on this state. In the previous example, we're concerned with\n    # states associated with the conflicting alternatives. Here alt 3 is not\n    # associated with the conflicting configs, but since we can continue\n    # looking for input reasonably, don't declare the state done.</p>\n    #\n    # <p><strong>PURE SLL PARSING</strong></p>\n    #\n    # <p>To handle pure SLL parsing, all we have to do is make sure that we\n    # combine stack contexts for configurations that differ only by semantic\n    # predicate. From there, we can do the usual SLL termination heuristic.</p>\n    #\n    # <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>\n    #\n    # <p>SLL decisions don't evaluate predicates until after they reach DFA stop\n    # states because they need to create the DFA cache that works in all\n    # semantic situations. In contrast, full LL evaluates predicates collected\n    # during start state computation so it can ignore predicates thereafter.\n    # This means that SLL termination detection can totally ignore semantic\n    # predicates.</p>\n    #\n    # <p>Implementation-wise, {@link ATNConfigSet} combines stack contexts but not\n    # semantic predicate contexts so we might see two configurations like the\n    # following.</p>\n    #\n    # <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>\n    #\n    # <p>Before testing these configurations against others, we have to merge\n    # {@code x} and {@code x'} (without modifying the existing configurations).\n    # For example, we test {@code (x+x')==x''} when looking for conflicts in\n    # the following configurations.</p>\n    #\n    # <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>\n    #\n    # <p>If the configuration set has predicates (as indicated by\n    # {@link ATNConfigSet#hasSemanticContext}), this algorithm makes a copy of\n    # the configurations to strip out all of the predicates so that a standard\n    # {@link ATNConfigSet} will merge everything ignoring predicates.</p>\n    #\n    @classmethod\n    def hasSLLConflictTerminatingPrediction(cls, mode:PredictionMode, configs:ATNConfigSet):\n        # Configs in rule stop states indicate reaching the end of the decision\n        # rule (local context) or end of start rule (full context). If all\n        # configs meet this condition, then none of the configurations is able\n        # to match additional input so we terminate prediction.\n        #\n        if cls.allConfigsInRuleStopStates(configs):\n            return True\n\n        # pure SLL mode parsing\n        if mode == PredictionMode.SLL:\n            # Don't bother with combining configs from different semantic\n            # contexts if we can fail over to full LL; costs more time\n            # since we'll often fail over anyway.\n            if configs.hasSemanticContext:\n                # dup configs, tossing out semantic predicates\n                dup = ATNConfigSet()\n                for c in configs:\n                    c = ATNConfig(config=c, semantic=SemanticContext.NONE)\n                    dup.add(c)\n                configs = dup\n            # now we have combined contexts for configs with dissimilar preds\n\n        # pure SLL or combined SLL+LL mode parsing\n        altsets = cls.getConflictingAltSubsets(configs)\n        return cls.hasConflictingAltSet(altsets) and not cls.hasStateAssociatedWithOneAlt(configs)\n\n    # Checks if any configuration in {@code configs} is in a\n    # {@link RuleStopState}. Configurations meeting this condition have reached\n    # the end of the decision rule (local context) or end of start rule (full\n    # context).\n    #\n    # @param configs the configuration set to test\n    # @return {@code true} if any configuration in {@code configs} is in a\n    # {@link RuleStopState}, otherwise {@code false}\n    @classmethod\n    def hasConfigInRuleStopState(cls, configs:ATNConfigSet):\n        return any(isinstance(cfg.state, RuleStopState) for cfg in configs)\n\n    # Checks if all configurations in {@code configs} are in a\n    # {@link RuleStopState}. Configurations meeting this condition have reached\n    # the end of the decision rule (local context) or end of start rule (full\n    # context).\n    #\n    # @param configs the configuration set to test\n    # @return {@code true} if all configurations in {@code configs} are in a\n    # {@link RuleStopState}, otherwise {@code false}\n    @classmethod\n    def allConfigsInRuleStopStates(cls, configs:ATNConfigSet):\n        return all(isinstance(cfg.state, RuleStopState) for cfg in configs)\n\n    #\n    # Full LL prediction termination.\n    #\n    # <p>Can we stop looking ahead during ATN simulation or is there some\n    # uncertainty as to which alternative we will ultimately pick, after\n    # consuming more input? Even if there are partial conflicts, we might know\n    # that everything is going to resolve to the same minimum alternative. That\n    # means we can stop since no more lookahead will change that fact. On the\n    # other hand, there might be multiple conflicts that resolve to different\n    # minimums. That means we need more look ahead to decide which of those\n    # alternatives we should predict.</p>\n    #\n    # <p>The basic idea is to split the set of configurations {@code C}, into\n    # conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with\n    # non-conflicting configurations. Two configurations conflict if they have\n    # identical {@link ATNConfig#state} and {@link ATNConfig#context} values\n    # but different {@link ATNConfig#alt} value, e.g. {@code (s, i, ctx, _)}\n    # and {@code (s, j, ctx, _)} for {@code i!=j}.</p>\n    #\n    # <p>Reduce these configuration subsets to the set of possible alternatives.\n    # You can compute the alternative subsets in one pass as follows:</p>\n    #\n    # <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in\n    # {@code C} holding {@code s} and {@code ctx} fixed.</p>\n    #\n    # <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>\n    #\n    # <pre>\n    # map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not\n    # alt and not pred\n    # </pre>\n    #\n    # <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>\n    #\n    # <p>If {@code |A_s,ctx|=1} then there is no conflict associated with\n    # {@code s} and {@code ctx}.</p>\n    #\n    # <p>Reduce the subsets to singletons by choosing a minimum of each subset. If\n    # the union of these alternative subsets is a singleton, then no amount of\n    # more lookahead will help us. We will always pick that alternative. If,\n    # however, there is more than one alternative, then we are uncertain which\n    # alternative to predict and must continue looking for resolution. We may\n    # or may not discover an ambiguity in the future, even if there are no\n    # conflicting subsets this round.</p>\n    #\n    # <p>The biggest sin is to terminate early because it means we've made a\n    # decision but were uncertain as to the eventual outcome. We haven't used\n    # enough lookahead. On the other hand, announcing a conflict too late is no\n    # big deal; you will still have the conflict. It's just inefficient. It\n    # might even look until the end of file.</p>\n    #\n    # <p>No special consideration for semantic predicates is required because\n    # predicates are evaluated on-the-fly for full LL prediction, ensuring that\n    # no configuration contains a semantic context during the termination\n    # check.</p>\n    #\n    # <p><strong>CONFLICTING CONFIGS</strong></p>\n    #\n    # <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict\n    # when {@code i!=j} but {@code x=x'}. Because we merge all\n    # {@code (s, i, _)} configurations together, that means that there are at\n    # most {@code n} configurations associated with state {@code s} for\n    # {@code n} possible alternatives in the decision. The merged stacks\n    # complicate the comparison of configuration contexts {@code x} and\n    # {@code x'}. Sam checks to see if one is a subset of the other by calling\n    # merge and checking to see if the merged result is either {@code x} or\n    # {@code x'}. If the {@code x} associated with lowest alternative {@code i}\n    # is the superset, then {@code i} is the only possible prediction since the\n    # others resolve to {@code min(i)} as well. However, if {@code x} is\n    # associated with {@code j>i} then at least one stack configuration for\n    # {@code j} is not in conflict with alternative {@code i}. The algorithm\n    # should keep going, looking for more lookahead due to the uncertainty.</p>\n    #\n    # <p>For simplicity, I'm doing a equality check between {@code x} and\n    # {@code x'} that lets the algorithm continue to consume lookahead longer\n    # than necessary. The reason I like the equality is of course the\n    # simplicity but also because that is the test you need to detect the\n    # alternatives that are actually in conflict.</p>\n    #\n    # <p><strong>CONTINUE/STOP RULE</strong></p>\n    #\n    # <p>Continue if union of resolved alternative sets from non-conflicting and\n    # conflicting alternative subsets has more than one alternative. We are\n    # uncertain about which alternative to predict.</p>\n    #\n    # <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which\n    # alternatives are still in the running for the amount of input we've\n    # consumed at this point. The conflicting sets let us to strip away\n    # configurations that won't lead to more states because we resolve\n    # conflicts to the configuration with a minimum alternate for the\n    # conflicting set.</p>\n    #\n    # <p><strong>CASES</strong></p>\n    #\n    # <ul>\n    #\n    # <li>no conflicts and more than 1 alternative in set =&gt; continue</li>\n    #\n    # <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},\n    # {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set\n    # {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n    # {@code {1,3}} =&gt; continue\n    # </li>\n    #\n    # <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n    # {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set\n    # {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =\n    # {@code {1}} =&gt; stop and predict 1</li>\n    #\n    # <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},\n    # {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U\n    # {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce\n    # ambiguity {@code {1,2}}</li>\n    #\n    # <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},\n    # {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U\n    # {@code {2}} = {@code {1,2}} =&gt; continue</li>\n    #\n    # <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},\n    # {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U\n    # {@code {3}} = {@code {1,3}} =&gt; continue</li>\n    #\n    # </ul>\n    #\n    # <p><strong>EXACT AMBIGUITY DETECTION</strong></p>\n    #\n    # <p>If all states report the same conflicting set of alternatives, then we\n    # know we have the exact ambiguity set.</p>\n    #\n    # <p><code>|A_<em>i</em>|&gt;1</code> and\n    # <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>\n    #\n    # <p>In other words, we continue examining lookahead until all {@code A_i}\n    # have more than one alternative and all {@code A_i} are the same. If\n    # {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate\n    # because the resolved set is {@code {1}}. To determine what the real\n    # ambiguity is, we have to know whether the ambiguity is between one and\n    # two or one and three so we keep going. We can only stop prediction when\n    # we need exact ambiguity detection when the sets look like\n    # {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>\n    #\n    @classmethod\n    def resolvesToJustOneViableAlt(cls, altsets:list):\n        return cls.getSingleViableAlt(altsets)\n\n    #\n    # Determines if every alternative subset in {@code altsets} contains more\n    # than one alternative.\n    #\n    # @param altsets a collection of alternative subsets\n    # @return {@code true} if every {@link BitSet} in {@code altsets} has\n    # {@link BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}\n    #\n    @classmethod\n    def allSubsetsConflict(cls, altsets:list):\n        return not cls.hasNonConflictingAltSet(altsets)\n\n    #\n    # Determines if any single alternative subset in {@code altsets} contains\n    # exactly one alternative.\n    #\n    # @param altsets a collection of alternative subsets\n    # @return {@code true} if {@code altsets} contains a {@link BitSet} with\n    # {@link BitSet#cardinality cardinality} 1, otherwise {@code false}\n    #\n    @classmethod\n    def hasNonConflictingAltSet(cls, altsets:list):\n        return any(len(alts) == 1 for alts in altsets)\n\n    #\n    # Determines if any single alternative subset in {@code altsets} contains\n    # more than one alternative.\n    #\n    # @param altsets a collection of alternative subsets\n    # @return {@code true} if {@code altsets} contains a {@link BitSet} with\n    # {@link BitSet#cardinality cardinality} &gt; 1, otherwise {@code false}\n    #\n    @classmethod\n    def hasConflictingAltSet(cls, altsets:list):\n        return any(len(alts) > 1 for alts in altsets)\n\n    #\n    # Determines if every alternative subset in {@code altsets} is equivalent.\n    #\n    # @param altsets a collection of alternative subsets\n    # @return {@code true} if every member of {@code altsets} is equal to the\n    # others, otherwise {@code false}\n    #\n    @classmethod\n    def allSubsetsEqual(cls, altsets:list):\n        if not altsets:\n            return True\n        first = next(iter(altsets))\n        return all(alts == first for alts in iter(altsets))\n\n    #\n    # Returns the unique alternative predicted by all alternative subsets in\n    # {@code altsets}. If no such alternative exists, this method returns\n    # {@link ATN#INVALID_ALT_NUMBER}.\n    #\n    # @param altsets a collection of alternative subsets\n    #\n    @classmethod\n    def getUniqueAlt(cls, altsets:list):\n        all = cls.getAlts(altsets)\n        if len(all)==1:\n            return next(iter(all))\n        return ATN.INVALID_ALT_NUMBER\n\n    # Gets the complete set of represented alternatives for a collection of\n    # alternative subsets. This method returns the union of each {@link BitSet}\n    # in {@code altsets}.\n    #\n    # @param altsets a collection of alternative subsets\n    # @return the set of represented alternatives in {@code altsets}\n    #\n    @classmethod\n    def getAlts(cls, altsets:list):\n        return set.union(*altsets)\n\n    #\n    # This function gets the conflicting alt subsets from a configuration set.\n    # For each configuration {@code c} in {@code configs}:\n    #\n    # <pre>\n    # map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not\n    # alt and not pred\n    # </pre>\n    #\n    @classmethod\n    def getConflictingAltSubsets(cls, configs:ATNConfigSet):\n        configToAlts = dict()\n        for c in configs:\n            h = hash((c.state.stateNumber, c.context))\n            alts = configToAlts.get(h, None)\n            if alts is None:\n                alts = set()\n                configToAlts[h] = alts\n            alts.add(c.alt)\n        return configToAlts.values()\n\n    #\n    # Get a map from state to alt subset from a configuration set. For each\n    # configuration {@code c} in {@code configs}:\n    #\n    # <pre>\n    # map[c.{@link ATNConfig#state state}] U= c.{@link ATNConfig#alt alt}\n    # </pre>\n    #\n    @classmethod\n    def getStateToAltMap(cls, configs:ATNConfigSet):\n        m = dict()\n        for c in configs:\n            alts = m.get(c.state, None)\n            if alts is None:\n                alts = set()\n                m[c.state] = alts\n            alts.add(c.alt)\n        return m\n\n    @classmethod\n    def hasStateAssociatedWithOneAlt(cls, configs:ATNConfigSet):\n        return any(len(alts) == 1 for alts in cls.getStateToAltMap(configs).values())\n\n    @classmethod\n    def getSingleViableAlt(cls, altsets:list):\n        viableAlts = set()\n        for alts in altsets:\n            minAlt = min(alts)\n            viableAlts.add(minAlt)\n            if len(viableAlts)>1 : # more than 1 viable alt\n                return ATN.INVALID_ALT_NUMBER\n        return min(viableAlts)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/SemanticContext.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n# A tree structure used to record the semantic context in which\n#  an ATN configuration is valid.  It's either a single predicate,\n#  a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.\n#\n#  <p>I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of\n#  {@link SemanticContext} within the scope of this outer class.</p>\n#\nfrom ..Recognizer import Recognizer\nfrom ..RuleContext import RuleContext\nfrom io import StringIO\n\n\nclass SemanticContext(object):\n    #\n    # The default {@link SemanticContext}, which is semantically equivalent to\n    # a predicate of the form {@code {true}?}.\n    #\n    NONE = None\n\n    #\n    # For context independent predicates, we evaluate them without a local\n    # context (i.e., null context). That way, we can evaluate them without\n    # having to create proper rule-specific context during prediction (as\n    # opposed to the parser, which creates them naturally). In a practical\n    # sense, this avoids a cast exception from RuleContext to myruleContext.\n    #\n    # <p>For context dependent predicates, we must pass in a local context so that\n    # references such as $arg evaluate properly as _localctx.arg. We only\n    # capture context dependent predicates in the context in which we begin\n    # prediction, so we passed in the outer context here in case of context\n    # dependent predicate evaluation.</p>\n    #\n    def eval(self, parser:Recognizer , outerContext:RuleContext ):\n        pass\n\n    #\n    # Evaluate the precedence predicates for the context and reduce the result.\n    #\n    # @param parser The parser instance.\n    # @param outerContext The current parser context object.\n    # @return The simplified semantic context after precedence predicates are\n    # evaluated, which will be one of the following values.\n    # <ul>\n    # <li>{@link #NONE}: if the predicate simplifies to {@code true} after\n    # precedence predicates are evaluated.</li>\n    # <li>{@code null}: if the predicate simplifies to {@code false} after\n    # precedence predicates are evaluated.</li>\n    # <li>{@code this}: if the semantic context is not changed as a result of\n    # precedence predicate evaluation.</li>\n    # <li>A non-{@code null} {@link SemanticContext}: the new simplified\n    # semantic context after precedence predicates are evaluated.</li>\n    # </ul>\n    #\n    def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext):\n        return self\n\n# need forward declaration\nAND = None\n\ndef andContext(a:SemanticContext, b:SemanticContext):\n    if a is None or a is SemanticContext.NONE:\n        return b\n    if b is None or b is SemanticContext.NONE:\n        return a\n    result = AND(a, b)\n    if len(result.opnds) == 1:\n        return result.opnds[0]\n    else:\n        return result\n\n# need forward declaration\nOR = None\n\ndef orContext(a:SemanticContext, b:SemanticContext):\n    if a is None:\n        return b\n    if b is None:\n        return a\n    if a is SemanticContext.NONE or b is SemanticContext.NONE:\n        return SemanticContext.NONE\n    result = OR(a, b)\n    if len(result.opnds) == 1:\n        return result.opnds[0]\n    else:\n        return result\n\ndef filterPrecedencePredicates(collection:set):\n    return [context for context in collection if isinstance(context, PrecedencePredicate)]\n\n\nclass EmptySemanticContext(SemanticContext):\n    pass\n\nclass Predicate(SemanticContext):\n    __slots__ = ('ruleIndex', 'predIndex', 'isCtxDependent')\n\n    def __init__(self, ruleIndex:int=-1, predIndex:int=-1, isCtxDependent:bool=False):\n        self.ruleIndex = ruleIndex\n        self.predIndex = predIndex\n        self.isCtxDependent = isCtxDependent # e.g., $i ref in pred\n\n    def eval(self, parser:Recognizer , outerContext:RuleContext ):\n        localctx = outerContext if self.isCtxDependent else None\n        return parser.sempred(localctx, self.ruleIndex, self.predIndex)\n\n    def __hash__(self):\n        return hash((self.ruleIndex, self.predIndex, self.isCtxDependent))\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, Predicate):\n            return False\n        return self.ruleIndex == other.ruleIndex and \\\n               self.predIndex == other.predIndex and \\\n               self.isCtxDependent == other.isCtxDependent\n\n    def __str__(self):\n        return \"{\" + str(self.ruleIndex) + \":\" + str(self.predIndex) + \"}?\"\n\n\nclass PrecedencePredicate(SemanticContext):\n\n    def __init__(self, precedence:int=0):\n        self.precedence = precedence\n\n    def eval(self, parser:Recognizer , outerContext:RuleContext ):\n        return parser.precpred(outerContext, self.precedence)\n\n    def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext):\n        if parser.precpred(outerContext, self.precedence):\n            return SemanticContext.NONE\n        else:\n            return None\n\n    def __lt__(self, other):\n        return self.precedence < other.precedence\n\n    def __hash__(self):\n        return 31\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, PrecedencePredicate):\n            return False\n        else:\n            return self.precedence == other.precedence\n\n    def __str__(self):\n        return \"{\" + str(self.precedence) + \">=prec}?\"\n\n\n# A semantic context which is true whenever none of the contained contexts\n# is false.\ndel AND\nclass AND(SemanticContext):\n    __slots__ = 'opnds'\n\n    def __init__(self, a:SemanticContext, b:SemanticContext):\n        operands = set()\n        if isinstance( a, AND ):\n            operands.update(a.opnds)\n        else:\n            operands.add(a)\n        if isinstance( b, AND ):\n            operands.update(b.opnds)\n        else:\n            operands.add(b)\n\n        precedencePredicates = filterPrecedencePredicates(operands)\n        if len(precedencePredicates)>0:\n            # interested in the transition with the lowest precedence\n            reduced = min(precedencePredicates)\n            operands.add(reduced)\n\n        self.opnds = list(operands)\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, AND):\n            return False\n        else:\n            return self.opnds == other.opnds\n\n    def __hash__(self):\n        h = 0\n        for o in self.opnds:\n            h = hash((h, o))\n        return hash((h, \"AND\"))\n\n    #\n    # {@inheritDoc}\n    #\n    # <p>\n    # The evaluation of predicates by this context is short-circuiting, but\n    # unordered.</p>\n    #\n    def eval(self, parser:Recognizer, outerContext:RuleContext):\n        return all(opnd.eval(parser, outerContext) for opnd in self.opnds)\n\n    def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext):\n        differs = False\n        operands = []\n        for context in self.opnds:\n            evaluated = context.evalPrecedence(parser, outerContext)\n            differs |= evaluated is not context\n            if evaluated is None:\n                # The AND context is false if any element is false\n                return None\n            elif evaluated is not SemanticContext.NONE:\n                # Reduce the result by skipping true elements\n                operands.append(evaluated)\n\n        if not differs:\n            return self\n\n        if len(operands)==0:\n            # all elements were true, so the AND context is true\n            return SemanticContext.NONE\n\n        result = None\n        for o in operands:\n            result = o if result is None else andContext(result, o)\n\n        return result\n\n    def __str__(self):\n        with StringIO() as buf:\n            first = True\n            for o in self.opnds:\n                if not first:\n                    buf.write(\"&&\")\n                buf.write(str(o))\n                first = False\n            return buf.getvalue()\n\n#\n# A semantic context which is true whenever at least one of the contained\n# contexts is true.\ndel OR\nclass OR (SemanticContext):\n    __slots__ = 'opnds'\n\n    def __init__(self, a:SemanticContext, b:SemanticContext):\n        operands = set()\n        if isinstance( a, OR ):\n            operands.update(a.opnds)\n        else:\n            operands.add(a)\n        if isinstance( b, OR ):\n            operands.update(b.opnds)\n        else:\n            operands.add(b)\n\n        precedencePredicates = filterPrecedencePredicates(operands)\n        if len(precedencePredicates)>0:\n            # interested in the transition with the highest precedence\n            s = sorted(precedencePredicates)\n            reduced = s[-1]\n            operands.add(reduced)\n\n        self.opnds = list(operands)\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif not isinstance(other, OR):\n            return False\n        else:\n            return self.opnds == other.opnds\n\n    def __hash__(self):\n        h = 0\n        for o in self.opnds:\n            h = hash((h, o))\n        return hash((h, \"OR\"))\n\n    # <p>\n    # The evaluation of predicates by this context is short-circuiting, but\n    # unordered.</p>\n    #\n    def eval(self, parser:Recognizer, outerContext:RuleContext):\n        return any(opnd.eval(parser, outerContext) for opnd in self.opnds)\n\n    def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext):\n        differs = False\n        operands = []\n        for context in self.opnds:\n            evaluated = context.evalPrecedence(parser, outerContext)\n            differs |= evaluated is not context\n            if evaluated is SemanticContext.NONE:\n                # The OR context is true if any element is true\n                return SemanticContext.NONE\n            elif evaluated is not None:\n                # Reduce the result by skipping false elements\n                operands.append(evaluated)\n\n        if not differs:\n            return self\n\n        if len(operands)==0:\n            # all elements were false, so the OR context is false\n            return None\n\n        result = None\n        for o in operands:\n            result = o if result is None else orContext(result, o)\n\n        return result\n\n    def __str__(self):\n        with StringIO() as buf:\n            first = True\n            for o in self.opnds:\n                if not first:\n                    buf.write(\"||\")\n                buf.write(str(o))\n                first = False\n            return buf.getvalue()\n\n\nSemanticContext.NONE = EmptySemanticContext()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/Transition.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#  An ATN transition between any two ATN states.  Subclasses define\n#  atom, set, epsilon, action, predicate, rule transitions.\n#\n#  <p>This is a one way link.  It emanates from a state (usually via a list of\n#  transitions) and has a target state.</p>\n#\n#  <p>Since we never have to change the ATN transitions once we construct it,\n#  we can fix these transitions as specific classes. The DFA transitions\n#  on the other hand need to update the labels as it adds transitions to\n#  the states. We'll use the term Edge for the DFA to distinguish them from\n#  ATN transitions.</p>\n#\nfrom ..IntervalSet import IntervalSet\nfrom ..Token import Token\n\n# need forward declarations\nfrom ..atn.SemanticContext import Predicate, PrecedencePredicate\n\nATNState = None\nRuleStartState = None\n\nclass Transition (object):\n    __slots__ = ('target','isEpsilon','label')\n\n    # constants for serialization\n    EPSILON\t\t\t= 1\n    RANGE\t\t\t= 2\n    RULE\t\t\t= 3\n    PREDICATE\t\t= 4 # e.g., {isType(input.LT(1))}?\n    ATOM\t\t\t= 5\n    ACTION\t\t\t= 6\n    SET\t\t\t\t= 7 # ~(A|B) or ~atom, wildcard, which convert to next 2\n    NOT_SET\t\t\t= 8\n    WILDCARD\t\t= 9\n    PRECEDENCE\t\t= 10\n\n    serializationNames = [\n            \"INVALID\",\n            \"EPSILON\",\n            \"RANGE\",\n            \"RULE\",\n            \"PREDICATE\",\n            \"ATOM\",\n            \"ACTION\",\n            \"SET\",\n            \"NOT_SET\",\n            \"WILDCARD\",\n            \"PRECEDENCE\"\n        ]\n\n    serializationTypes = dict()\n\n    def __init__(self, target:ATNState):\n        # The target of this transition.\n        if target is None:\n            raise Exception(\"target cannot be null.\")\n        self.target = target\n        # Are we epsilon, action, sempred?\n        self.isEpsilon = False\n        self.label = None\n\n\n# TODO: make all transitions sets? no, should remove set edges\nclass AtomTransition(Transition):\n    __slots__ = ('label_', 'serializationType')\n\n    def __init__(self, target:ATNState, label:int):\n        super().__init__(target)\n        self.label_ = label # The token type or character value; or, signifies special label.\n        self.label = self.makeLabel()\n        self.serializationType = self.ATOM\n\n    def makeLabel(self):\n        s = IntervalSet()\n        s.addOne(self.label_)\n        return s\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return self.label_ == symbol\n\n    def __str__(self):\n        return str(self.label_)\n\nclass RuleTransition(Transition):\n    __slots__ = ('ruleIndex', 'precedence', 'followState', 'serializationType')\n\n    def __init__(self, ruleStart:RuleStartState, ruleIndex:int, precedence:int, followState:ATNState):\n        super().__init__(ruleStart)\n        self.ruleIndex = ruleIndex # ptr to the rule definition object for this rule ref\n        self.precedence = precedence\n        self.followState = followState # what node to begin computations following ref to rule\n        self.serializationType = self.RULE\n        self.isEpsilon = True\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return False\n\n\nclass EpsilonTransition(Transition):\n    __slots__ = ('serializationType', 'outermostPrecedenceReturn')\n\n    def __init__(self, target, outermostPrecedenceReturn=-1):\n        super(EpsilonTransition, self).__init__(target)\n        self.serializationType = self.EPSILON\n        self.isEpsilon = True\n        self.outermostPrecedenceReturn = outermostPrecedenceReturn\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return False\n\n    def __str__(self):\n        return \"epsilon\"\n\nclass RangeTransition(Transition):\n    __slots__ = ('serializationType', 'start', 'stop')\n\n    def __init__(self, target:ATNState, start:int, stop:int):\n        super().__init__(target)\n        self.serializationType = self.RANGE\n        self.start = start\n        self.stop = stop\n        self.label = self.makeLabel()\n\n    def makeLabel(self):\n        s = IntervalSet()\n        s.addRange(range(self.start, self.stop + 1))\n        return s\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return symbol >= self.start and symbol <= self.stop\n\n    def __str__(self):\n        return \"'\" + chr(self.start) + \"'..'\" + chr(self.stop) + \"'\"\n\nclass AbstractPredicateTransition(Transition):\n\n    def __init__(self, target:ATNState):\n        super().__init__(target)\n\n\nclass PredicateTransition(AbstractPredicateTransition):\n    __slots__ = ('serializationType', 'ruleIndex', 'predIndex', 'isCtxDependent')\n\n    def __init__(self, target:ATNState, ruleIndex:int, predIndex:int, isCtxDependent:bool):\n        super().__init__(target)\n        self.serializationType = self.PREDICATE\n        self.ruleIndex = ruleIndex\n        self.predIndex = predIndex\n        self.isCtxDependent = isCtxDependent # e.g., $i ref in pred\n        self.isEpsilon = True\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return False\n\n    def getPredicate(self):\n        return Predicate(self.ruleIndex, self.predIndex, self.isCtxDependent)\n\n    def __str__(self):\n        return \"pred_\" + str(self.ruleIndex) + \":\" + str(self.predIndex)\n\nclass ActionTransition(Transition):\n    __slots__ = ('serializationType', 'ruleIndex', 'actionIndex', 'isCtxDependent')\n\n    def __init__(self, target:ATNState, ruleIndex:int, actionIndex:int=-1, isCtxDependent:bool=False):\n        super().__init__(target)\n        self.serializationType = self.ACTION\n        self.ruleIndex = ruleIndex\n        self.actionIndex = actionIndex\n        self.isCtxDependent = isCtxDependent # e.g., $i ref in pred\n        self.isEpsilon = True\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return False\n\n    def __str__(self):\n        return \"action_\"+self.ruleIndex+\":\"+self.actionIndex\n\n# A transition containing a set of values.\nclass SetTransition(Transition):\n    __slots__ = 'serializationType'\n\n    def __init__(self, target:ATNState, set:IntervalSet):\n        super().__init__(target)\n        self.serializationType = self.SET\n        if set is not None:\n            self.label = set\n        else:\n            self.label = IntervalSet()\n            self.label.addRange(range(Token.INVALID_TYPE, Token.INVALID_TYPE + 1))\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return symbol in self.label\n\n    def __str__(self):\n        return str(self.label)\n\nclass NotSetTransition(SetTransition):\n\n    def __init__(self, target:ATNState, set:IntervalSet):\n        super().__init__(target, set)\n        self.serializationType = self.NOT_SET\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return symbol >= minVocabSymbol \\\n            and symbol <= maxVocabSymbol \\\n            and not super(type(self), self).matches(symbol, minVocabSymbol, maxVocabSymbol)\n\n    def __str__(self):\n        return '~' + super(type(self), self).__str__()\n\n\nclass WildcardTransition(Transition):\n    __slots__ = 'serializationType'\n\n    def __init__(self, target:ATNState):\n        super().__init__(target)\n        self.serializationType = self.WILDCARD\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return symbol >= minVocabSymbol and symbol <= maxVocabSymbol\n\n    def __str__(self):\n        return \".\"\n\n\nclass PrecedencePredicateTransition(AbstractPredicateTransition):\n    __slots__ = ('serializationType', 'precedence')\n\n    def __init__(self, target:ATNState, precedence:int):\n        super().__init__(target)\n        self.serializationType = self.PRECEDENCE\n        self.precedence = precedence\n        self.isEpsilon = True\n\n    def matches( self, symbol:int, minVocabSymbol:int,  maxVocabSymbol:int):\n        return False\n\n\n    def getPredicate(self):\n        return PrecedencePredicate(self.precedence)\n\n    def __str__(self):\n        return self.precedence + \" >= _p\"\n\n\nTransition.serializationTypes = {\n             EpsilonTransition: Transition.EPSILON,\n             RangeTransition: Transition.RANGE,\n             RuleTransition: Transition.RULE,\n             PredicateTransition: Transition.PREDICATE,\n             AtomTransition: Transition.ATOM,\n             ActionTransition: Transition.ACTION,\n             SetTransition: Transition.SET,\n             NotSetTransition: Transition.NOT_SET,\n             WildcardTransition: Transition.WILDCARD,\n             PrecedencePredicateTransition: Transition.PRECEDENCE\n         }\n\ndel ATNState\ndel RuleStartState\n\nfrom ..atn.ATNState import *\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/atn/__init__.py",
    "content": "__author__ = 'ericvergnaud'\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/dfa/DFA.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\nfrom ..atn.ATNState import StarLoopEntryState\n\nfrom ..atn.ATNConfigSet import ATNConfigSet\nfrom ..atn.ATNState import DecisionState\nfrom ..dfa.DFAState import DFAState\nfrom ..error.Errors import IllegalStateException\n\n\nclass DFA(object):\n    __slots__ = ('atnStartState', 'decision', '_states', 's0', 'precedenceDfa')\n\n    def __init__(self, atnStartState:DecisionState, decision:int=0):\n        # From which ATN state did we create this DFA?\n        self.atnStartState = atnStartState\n        self.decision = decision\n        # A set of all DFA states. Use {@link Map} so we can get old state back\n        #  ({@link Set} only allows you to see if it's there).\n        self._states = dict()\n        self.s0 = None\n        # {@code true} if this DFA is for a precedence decision; otherwise,\n        # {@code false}. This is the backing field for {@link #isPrecedenceDfa},\n        # {@link #setPrecedenceDfa}.\n        self.precedenceDfa = False\n\n        if isinstance(atnStartState, StarLoopEntryState):\n            if atnStartState.isPrecedenceDecision:\n                self.precedenceDfa = True\n                precedenceState = DFAState(configs=ATNConfigSet())\n                precedenceState.edges = []\n                precedenceState.isAcceptState = False\n                precedenceState.requiresFullContext = False\n                self.s0 = precedenceState\n\n\n    # Get the start state for a specific precedence value.\n    #\n    # @param precedence The current precedence.\n    # @return The start state corresponding to the specified precedence, or\n    # {@code null} if no start state exists for the specified precedence.\n    #\n    # @throws IllegalStateException if this is not a precedence DFA.\n    # @see #isPrecedenceDfa()\n\n    def getPrecedenceStartState(self, precedence:int):\n        if not self.precedenceDfa:\n            raise IllegalStateException(\"Only precedence DFAs may contain a precedence start state.\")\n\n        # s0.edges is never null for a precedence DFA\n        if precedence < 0 or precedence >= len(self.s0.edges):\n            return None\n        return self.s0.edges[precedence]\n\n    # Set the start state for a specific precedence value.\n    #\n    # @param precedence The current precedence.\n    # @param startState The start state corresponding to the specified\n    # precedence.\n    #\n    # @throws IllegalStateException if this is not a precedence DFA.\n    # @see #isPrecedenceDfa()\n    #\n    def setPrecedenceStartState(self, precedence:int, startState:DFAState):\n        if not self.precedenceDfa:\n            raise IllegalStateException(\"Only precedence DFAs may contain a precedence start state.\")\n\n        if precedence < 0:\n            return\n\n        # synchronization on s0 here is ok. when the DFA is turned into a\n        # precedence DFA, s0 will be initialized once and not updated again\n        # s0.edges is never null for a precedence DFA\n        if precedence >= len(self.s0.edges):\n            ext = [None] * (precedence + 1 - len(self.s0.edges))\n            self.s0.edges.extend(ext)\n        self.s0.edges[precedence] = startState\n    #\n    # Sets whether this is a precedence DFA. If the specified value differs\n    # from the current DFA configuration, the following actions are taken;\n    # otherwise no changes are made to the current DFA.\n    #\n    # <ul>\n    # <li>The {@link #states} map is cleared</li>\n    # <li>If {@code precedenceDfa} is {@code false}, the initial state\n    # {@link #s0} is set to {@code null}; otherwise, it is initialized to a new\n    # {@link DFAState} with an empty outgoing {@link DFAState#edges} array to\n    # store the start states for individual precedence values.</li>\n    # <li>The {@link #precedenceDfa} field is updated</li>\n    # </ul>\n    #\n    # @param precedenceDfa {@code true} if this is a precedence DFA; otherwise,\n    # {@code false}\n\n    def setPrecedenceDfa(self, precedenceDfa:bool):\n        if self.precedenceDfa != precedenceDfa:\n            self._states = dict()\n            if precedenceDfa:\n                precedenceState = DFAState(configs=ATNConfigSet())\n                precedenceState.edges = []\n                precedenceState.isAcceptState = False\n                precedenceState.requiresFullContext = False\n                self.s0 = precedenceState\n            else:\n                self.s0 = None\n            self.precedenceDfa = precedenceDfa\n\n    @property\n    def states(self):\n        return self._states\n\n    # Return a list of all states in this DFA, ordered by state number.\n    def sortedStates(self):\n        return sorted(self._states.keys(), key=lambda state: state.stateNumber)\n\n    def __str__(self):\n        return self.toString(None)\n\n    def toString(self, literalNames:list=None, symbolicNames:list=None):\n        if self.s0 is None:\n            return \"\"\n        from ..dfa.DFASerializer import DFASerializer\n        serializer = DFASerializer(self,literalNames,symbolicNames)\n        return str(serializer)\n\n    def toLexerString(self):\n        if self.s0 is None:\n            return \"\"\n        from ..dfa.DFASerializer import LexerDFASerializer\n        serializer = LexerDFASerializer(self)\n        return str(serializer)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/dfa/DFASerializer.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n# A DFA walker that knows how to dump them to serialized strings.#/\nfrom io import StringIO\nfrom ..dfa.DFA import DFA\nfrom ..Utils import str_list\nfrom ..dfa.DFAState import DFAState\n\n\nclass DFASerializer(object):\n    __slots__ = ('dfa', 'literalNames', 'symbolicNames')\n\n    def __init__(self, dfa:DFA, literalNames:list=None, symbolicNames:list=None):\n        self.dfa = dfa\n        self.literalNames = literalNames\n        self.symbolicNames = symbolicNames\n\n    def __str__(self):\n        if self.dfa.s0 is None:\n            return None\n        with StringIO() as buf:\n            for s in self.dfa.sortedStates():\n                n = 0\n                if s.edges is not None:\n                    n = len(s.edges)\n                for i in range(0, n):\n                    t = s.edges[i]\n                    if t is not None and t.stateNumber != 0x7FFFFFFF:\n                        buf.write(self.getStateString(s))\n                        label = self.getEdgeLabel(i)\n                        buf.write(\"-\")\n                        buf.write(label)\n                        buf.write(\"->\")\n                        buf.write(self.getStateString(t))\n                        buf.write('\\n')\n            output = buf.getvalue()\n            if len(output)==0:\n                return None\n            else:\n                return output\n\n    def getEdgeLabel(self, i:int):\n        if i==0:\n            return \"EOF\"\n        if self.literalNames is not None and i<=len(self.literalNames):\n            return self.literalNames[i-1]\n        elif self.symbolicNames is not None and i<=len(self.symbolicNames):\n            return self.symbolicNames[i-1]\n        else:\n            return str(i-1)\n\n    def getStateString(self, s:DFAState):\n        n = s.stateNumber\n        baseStateStr = ( \":\" if s.isAcceptState else \"\") + \"s\" + str(n) + ( \"^\" if s.requiresFullContext else \"\")\n        if s.isAcceptState:\n            if s.predicates is not None:\n                return baseStateStr + \"=>\" + str_list(s.predicates)\n            else:\n                return baseStateStr + \"=>\" + str(s.prediction)\n        else:\n            return baseStateStr\n\nclass LexerDFASerializer(DFASerializer):\n\n    def __init__(self, dfa:DFA):\n        super().__init__(dfa, None)\n\n    def getEdgeLabel(self, i:int):\n        return \"'\" + chr(i) + \"'\"\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/dfa/DFAState.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n# Map a predicate to a predicted alternative.#/\nfrom io import StringIO\nfrom ..atn.ATNConfigSet import ATNConfigSet\nfrom ..atn.SemanticContext import SemanticContext\n\n\nclass PredPrediction(object):\n    __slots__ = ('alt', 'pred')\n\n    def __init__(self, pred:SemanticContext, alt:int):\n        self.alt = alt\n        self.pred = pred\n\n    def __str__(self):\n        return \"(\" + str(self.pred) + \", \" + str(self.alt) +  \")\"\n\n# A DFA state represents a set of possible ATN configurations.\n#  As Aho, Sethi, Ullman p. 117 says \"The DFA uses its state\n#  to keep track of all possible states the ATN can be in after\n#  reading each input symbol.  That is to say, after reading\n#  input a1a2..an, the DFA is in a state that represents the\n#  subset T of the states of the ATN that are reachable from the\n#  ATN's start state along some path labeled a1a2..an.\"\n#  In conventional NFA&rarr;DFA conversion, therefore, the subset T\n#  would be a bitset representing the set of states the\n#  ATN could be in.  We need to track the alt predicted by each\n#  state as well, however.  More importantly, we need to maintain\n#  a stack of states, tracking the closure operations as they\n#  jump from rule to rule, emulating rule invocations (method calls).\n#  I have to add a stack to simulate the proper lookahead sequences for\n#  the underlying LL grammar from which the ATN was derived.\n#\n#  <p>I use a set of ATNConfig objects not simple states.  An ATNConfig\n#  is both a state (ala normal conversion) and a RuleContext describing\n#  the chain of rules (if any) followed to arrive at that state.</p>\n#\n#  <p>A DFA state may have multiple references to a particular state,\n#  but with different ATN contexts (with same or different alts)\n#  meaning that state was reached via a different set of rule invocations.</p>\n#/\nclass DFAState(object):\n    __slots__ = (\n        'stateNumber', 'configs', 'edges', 'isAcceptState', 'prediction',\n        'lexerActionExecutor', 'requiresFullContext', 'predicates'\n    )\n\n    def __init__(self, stateNumber:int=-1, configs:ATNConfigSet=ATNConfigSet()):\n        self.stateNumber = stateNumber\n        self.configs = configs\n        # {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)\n        #  {@link Token#EOF} maps to {@code edges[0]}.\n        self.edges = None\n        self.isAcceptState = False\n        # if accept state, what ttype do we match or alt do we predict?\n        #  This is set to {@link ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or\n        #  {@link #requiresFullContext}.\n        self.prediction = 0\n        self.lexerActionExecutor = None\n        # Indicates that this state was created during SLL prediction that\n        # discovered a conflict between the configurations in the state. Future\n        # {@link ParserATNSimulator#execATN} invocations immediately jumped doing\n        # full context prediction if this field is true.\n        self.requiresFullContext = False\n        # During SLL parsing, this is a list of predicates associated with the\n        #  ATN configurations of the DFA state. When we have predicates,\n        #  {@link #requiresFullContext} is {@code false} since full context prediction evaluates predicates\n        #  on-the-fly. If this is not null, then {@link #prediction} is\n        #  {@link ATN#INVALID_ALT_NUMBER}.\n        #\n        #  <p>We only use these for non-{@link #requiresFullContext} but conflicting states. That\n        #  means we know from the context (it's $ or we don't dip into outer\n        #  context) that it's an ambiguity not a conflict.</p>\n        #\n        #  <p>This list is computed by {@link ParserATNSimulator#predicateDFAState}.</p>\n        self.predicates = None\n\n\n\n    # Get the set of all alts mentioned by all ATN configurations in this\n    #  DFA state.\n    def getAltSet(self):\n        if self.configs is not None:\n            return set(cfg.alt for cfg in self.configs) or None\n        return None\n\n    def __hash__(self):\n        return hash(self.configs)\n\n    # Two {@link DFAState} instances are equal if their ATN configuration sets\n    # are the same. This method is used to see if a state already exists.\n    #\n    # <p>Because the number of alternatives and number of ATN configurations are\n    # finite, there is a finite number of DFA states that can be processed.\n    # This is necessary to show that the algorithm terminates.</p>\n    #\n    # <p>Cannot test the DFA state numbers here because in\n    # {@link ParserATNSimulator#addDFAState} we need to know if any other state\n    # exists that has this exact set of ATN configurations. The\n    # {@link #stateNumber} is irrelevant.</p>\n    def __eq__(self, other):\n        # compare set of ATN configurations in this set with other\n        if self is other:\n            return True\n        elif not isinstance(other, DFAState):\n            return False\n        else:\n            return self.configs==other.configs\n\n    def __str__(self):\n        with StringIO() as buf:\n            buf.write(str(self.stateNumber))\n            buf.write(\":\")\n            buf.write(str(self.configs))\n            if self.isAcceptState:\n                buf.write(\"=>\")\n                if self.predicates is not None:\n                    buf.write(str(self.predicates))\n                else:\n                    buf.write(str(self.prediction))\n            return buf.getvalue()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/dfa/__init__.py",
    "content": "__author__ = 'ericvergnaud'\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/error/DiagnosticErrorListener.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n\n#\n# This implementation of {@link ANTLRErrorListener} can be used to identify\n# certain potential correctness and performance problems in grammars. \"Reports\"\n# are made by calling {@link Parser#notifyErrorListeners} with the appropriate\n# message.\n#\n# <ul>\n# <li><b>Ambiguities</b>: These are cases where more than one path through the\n# grammar can match the input.</li>\n# <li><b>Weak context sensitivity</b>: These are cases where full-context\n# prediction resolved an SLL conflict to a unique alternative which equaled the\n# minimum alternative of the SLL conflict.</li>\n# <li><b>Strong (forced) context sensitivity</b>: These are cases where the\n# full-context prediction resolved an SLL conflict to a unique alternative,\n# <em>and</em> the minimum alternative of the SLL conflict was found to not be\n# a truly viable alternative. Two-stage parsing cannot be used for inputs where\n# this situation occurs.</li>\n# </ul>\n\nfrom io import StringIO\nfrom ..dfa.DFA import DFA\nfrom ..Parser import Parser\nfrom ..atn.ATNConfigSet import ATNConfigSet\nfrom ..error.ErrorListener import ErrorListener\n\nclass DiagnosticErrorListener(ErrorListener):\n\n    def __init__(self, exactOnly:bool=True):\n        # whether all ambiguities or only exact ambiguities are reported.\n        self.exactOnly = exactOnly\n\n    def reportAmbiguity(self, recognizer:Parser, dfa:DFA, startIndex:int,\n                       stopIndex:int, exact:bool, ambigAlts:set, configs:ATNConfigSet):\n        if self.exactOnly and not exact:\n            return\n\n        with StringIO() as buf:\n            buf.write(\"reportAmbiguity d=\")\n            buf.write(self.getDecisionDescription(recognizer, dfa))\n            buf.write(\": ambigAlts=\")\n            buf.write(str(self.getConflictingAlts(ambigAlts, configs)))\n            buf.write(\", input='\")\n            buf.write(recognizer.getTokenStream().getText(startIndex, stopIndex))\n            buf.write(\"'\")\n            recognizer.notifyErrorListeners(buf.getvalue())\n\n\n    def reportAttemptingFullContext(self, recognizer:Parser, dfa:DFA, startIndex:int,\n                       stopIndex:int, conflictingAlts:set, configs:ATNConfigSet):\n        with StringIO() as buf:\n            buf.write(\"reportAttemptingFullContext d=\")\n            buf.write(self.getDecisionDescription(recognizer, dfa))\n            buf.write(\", input='\")\n            buf.write(recognizer.getTokenStream().getText(startIndex, stopIndex))\n            buf.write(\"'\")\n            recognizer.notifyErrorListeners(buf.getvalue())\n\n    def reportContextSensitivity(self, recognizer:Parser, dfa:DFA, startIndex:int,\n                       stopIndex:int, prediction:int, configs:ATNConfigSet):\n        with StringIO() as buf:\n            buf.write(\"reportContextSensitivity d=\")\n            buf.write(self.getDecisionDescription(recognizer, dfa))\n            buf.write(\", input='\")\n            buf.write(recognizer.getTokenStream().getText(startIndex, stopIndex))\n            buf.write(\"'\")\n            recognizer.notifyErrorListeners(buf.getvalue())\n\n    def getDecisionDescription(self, recognizer:Parser, dfa:DFA):\n        decision = dfa.decision\n        ruleIndex = dfa.atnStartState.ruleIndex\n\n        ruleNames = recognizer.ruleNames\n        if ruleIndex < 0 or ruleIndex >= len(ruleNames):\n            return str(decision)\n\n        ruleName = ruleNames[ruleIndex]\n        if ruleName is None or len(ruleName)==0:\n            return str(decision)\n\n        return str(decision) + \" (\" + ruleName + \")\"\n\n    #\n    # Computes the set of conflicting or ambiguous alternatives from a\n    # configuration set, if that information was not already provided by the\n    # parser.\n    #\n    # @param reportedAlts The set of conflicting or ambiguous alternatives, as\n    # reported by the parser.\n    # @param configs The conflicting or ambiguous configuration set.\n    # @return Returns {@code reportedAlts} if it is not {@code null}, otherwise\n    # returns the set of alternatives represented in {@code configs}.\n    #\n    def getConflictingAlts(self, reportedAlts:set, configs:ATNConfigSet):\n        if reportedAlts is not None:\n            return reportedAlts\n\n        result = set()\n        for config in configs:\n            result.add(config.alt)\n\n        return result\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/error/ErrorListener.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n\n# Provides an empty default implementation of {@link ANTLRErrorListener}. The\n# default implementation of each method does nothing, but can be overridden as\n# necessary.\n\n\nimport sys\n\nclass ErrorListener(object):\n\n    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):\n        pass\n\n    def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):\n        pass\n\n    def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):\n        pass\n\n    def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):\n        pass\n\nclass ConsoleErrorListener(ErrorListener):\n    #\n    # Provides a default instance of {@link ConsoleErrorListener}.\n    #\n    INSTANCE = None\n\n    #\n    # {@inheritDoc}\n    #\n    # <p>\n    # This implementation prints messages to {@link System#err} containing the\n    # values of {@code line}, {@code charPositionInLine}, and {@code msg} using\n    # the following format.</p>\n    #\n    # <pre>\n    # line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>\n    # </pre>\n    #\n    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):\n        print(\"line \" + str(line) + \":\" + str(column) + \" \" + msg, file=sys.stderr)\n\nConsoleErrorListener.INSTANCE = ConsoleErrorListener()\n\nclass ProxyErrorListener(ErrorListener):\n\n    def __init__(self, delegates):\n        super().__init__()\n        if delegates is None:\n            raise ReferenceError(\"delegates\")\n        self.delegates = delegates\n\n    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):\n        for delegate in self.delegates:\n            delegate.syntaxError(recognizer, offendingSymbol, line, column, msg, e)\n\n    def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):\n        for delegate in self.delegates:\n            delegate.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs)\n\n    def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):\n        for delegate in self.delegates:\n            delegate.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs)\n\n    def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):\n        for delegate in self.delegates:\n            delegate.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/error/ErrorStrategy.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\nimport sys\nfrom ..IntervalSet import IntervalSet\n\nfrom ..Token import Token\nfrom ..atn.ATNState import ATNState\nfrom ..error.Errors import RecognitionException, NoViableAltException, InputMismatchException, \\\n    FailedPredicateException, ParseCancellationException\n\n# need forward declaration\nParser = None\n\nclass ErrorStrategy(object):\n\n    def reset(self, recognizer:Parser):\n        pass\n\n    def recoverInline(self, recognizer:Parser):\n        pass\n\n    def recover(self, recognizer:Parser, e:RecognitionException):\n        pass\n\n    def sync(self, recognizer:Parser):\n        pass\n\n    def inErrorRecoveryMode(self, recognizer:Parser):\n        pass\n\n    def reportError(self, recognizer:Parser, e:RecognitionException):\n        pass\n\n\n# This is the default implementation of {@link ANTLRErrorStrategy} used for\n# error reporting and recovery in ANTLR parsers.\n#\nclass DefaultErrorStrategy(ErrorStrategy):\n\n    def __init__(self):\n        super().__init__()\n        # Indicates whether the error strategy is currently \"recovering from an\n        # error\". This is used to suppress reporting multiple error messages while\n        # attempting to recover from a detected syntax error.\n        #\n        # @see #inErrorRecoveryMode\n        #\n        self.errorRecoveryMode = False\n\n        # The index into the input stream where the last error occurred.\n        # \tThis is used to prevent infinite loops where an error is found\n        #  but no token is consumed during recovery...another error is found,\n        #  ad nauseum.  This is a failsafe mechanism to guarantee that at least\n        #  one token/tree node is consumed for two errors.\n        #\n        self.lastErrorIndex = -1\n        self.lastErrorStates = None\n        self.nextTokensContext = None\n        self.nextTokenState = 0\n\n    # <p>The default implementation simply calls {@link #endErrorCondition} to\n    # ensure that the handler is not in error recovery mode.</p>\n    def reset(self, recognizer:Parser):\n        self.endErrorCondition(recognizer)\n\n    #\n    # This method is called to enter error recovery mode when a recognition\n    # exception is reported.\n    #\n    # @param recognizer the parser instance\n    #\n    def beginErrorCondition(self, recognizer:Parser):\n        self.errorRecoveryMode = True\n\n    def inErrorRecoveryMode(self, recognizer:Parser):\n        return self.errorRecoveryMode\n\n    #\n    # This method is called to leave error recovery mode after recovering from\n    # a recognition exception.\n    #\n    # @param recognizer\n    #\n    def endErrorCondition(self, recognizer:Parser):\n        self.errorRecoveryMode = False\n        self.lastErrorStates = None\n        self.lastErrorIndex = -1\n\n    #\n    # {@inheritDoc}\n    #\n    # <p>The default implementation simply calls {@link #endErrorCondition}.</p>\n    #\n    def reportMatch(self, recognizer:Parser):\n        self.endErrorCondition(recognizer)\n\n    #\n    # {@inheritDoc}\n    #\n    # <p>The default implementation returns immediately if the handler is already\n    # in error recovery mode. Otherwise, it calls {@link #beginErrorCondition}\n    # and dispatches the reporting task based on the runtime type of {@code e}\n    # according to the following table.</p>\n    #\n    # <ul>\n    # <li>{@link NoViableAltException}: Dispatches the call to\n    # {@link #reportNoViableAlternative}</li>\n    # <li>{@link InputMismatchException}: Dispatches the call to\n    # {@link #reportInputMismatch}</li>\n    # <li>{@link FailedPredicateException}: Dispatches the call to\n    # {@link #reportFailedPredicate}</li>\n    # <li>All other types: calls {@link Parser#notifyErrorListeners} to report\n    # the exception</li>\n    # </ul>\n    #\n    def reportError(self, recognizer:Parser, e:RecognitionException):\n       # if we've already reported an error and have not matched a token\n       # yet successfully, don't report any errors.\n        if self.inErrorRecoveryMode(recognizer):\n            return # don't report spurious errors\n        self.beginErrorCondition(recognizer)\n        if isinstance( e, NoViableAltException ):\n            self.reportNoViableAlternative(recognizer, e)\n        elif isinstance( e, InputMismatchException ):\n            self.reportInputMismatch(recognizer, e)\n        elif isinstance( e, FailedPredicateException ):\n            self.reportFailedPredicate(recognizer, e)\n        else:\n            print(\"unknown recognition error type: \" + type(e).__name__)\n            recognizer.notifyErrorListeners(e.message, e.offendingToken, e)\n\n    #\n    # {@inheritDoc}\n    #\n    # <p>The default implementation resynchronizes the parser by consuming tokens\n    # until we find one in the resynchronization set--loosely the set of tokens\n    # that can follow the current rule.</p>\n    #\n    def recover(self, recognizer:Parser, e:RecognitionException):\n        if self.lastErrorIndex==recognizer.getInputStream().index \\\n            and self.lastErrorStates is not None \\\n            and recognizer.state in self.lastErrorStates:\n           # uh oh, another error at same token index and previously-visited\n           # state in ATN; must be a case where LT(1) is in the recovery\n           # token set so nothing got consumed. Consume a single token\n           # at least to prevent an infinite loop; this is a failsafe.\n            recognizer.consume()\n\n        self.lastErrorIndex = recognizer._input.index\n        if self.lastErrorStates is None:\n            self.lastErrorStates = []\n        self.lastErrorStates.append(recognizer.state)\n        followSet = self.getErrorRecoverySet(recognizer)\n        self.consumeUntil(recognizer, followSet)\n\n    # The default implementation of {@link ANTLRErrorStrategy#sync} makes sure\n    # that the current lookahead symbol is consistent with what were expecting\n    # at this point in the ATN. You can call this anytime but ANTLR only\n    # generates code to check before subrules/loops and each iteration.\n    #\n    # <p>Implements Jim Idle's magic sync mechanism in closures and optional\n    # subrules. E.g.,</p>\n    #\n    # <pre>\n    # a : sync ( stuff sync )* ;\n    # sync : {consume to what can follow sync} ;\n    # </pre>\n    #\n    # At the start of a sub rule upon error, {@link #sync} performs single\n    # token deletion, if possible. If it can't do that, it bails on the current\n    # rule and uses the default error recovery, which consumes until the\n    # resynchronization set of the current rule.\n    #\n    # <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block\n    # with an empty alternative), then the expected set includes what follows\n    # the subrule.</p>\n    #\n    # <p>During loop iteration, it consumes until it sees a token that can start a\n    # sub rule or what follows loop. Yes, that is pretty aggressive. We opt to\n    # stay in the loop as long as possible.</p>\n    #\n    # <p><strong>ORIGINS</strong></p>\n    #\n    # <p>Previous versions of ANTLR did a poor job of their recovery within loops.\n    # A single mismatch token or missing token would force the parser to bail\n    # out of the entire rules surrounding the loop. So, for rule</p>\n    #\n    # <pre>\n    # classDef : 'class' ID '{' member* '}'\n    # </pre>\n    #\n    # input with an extra token between members would force the parser to\n    # consume until it found the next class definition rather than the next\n    # member definition of the current class.\n    #\n    # <p>This functionality cost a little bit of effort because the parser has to\n    # compare token set at the start of the loop and at each iteration. If for\n    # some reason speed is suffering for you, you can turn off this\n    # functionality by simply overriding this method as a blank { }.</p>\n    #\n    def sync(self, recognizer:Parser):\n        # If already recovering, don't try to sync\n        if self.inErrorRecoveryMode(recognizer):\n            return\n\n        s = recognizer._interp.atn.states[recognizer.state]\n        la = recognizer.getTokenStream().LA(1)\n        # try cheaper subset first; might get lucky. seems to shave a wee bit off\n        nextTokens = recognizer.atn.nextTokens(s)\n        if la in nextTokens:\n            self.nextTokensContext = None\n            self.nextTokenState = ATNState.INVALID_STATE_NUMBER\n            return\n        elif Token.EPSILON in nextTokens:\n            if self.nextTokensContext is None:\n                # It's possible the next token won't match information tracked\n                # by sync is restricted for performance.\n                self.nextTokensContext = recognizer._ctx\n                self.nextTokensState = recognizer._stateNumber\n            return\n\n        if s.stateType in [ATNState.BLOCK_START, ATNState.STAR_BLOCK_START,\n                                ATNState.PLUS_BLOCK_START, ATNState.STAR_LOOP_ENTRY]:\n           # report error and recover if possible\n            if self.singleTokenDeletion(recognizer)is not None:\n                return\n            else:\n                raise InputMismatchException(recognizer)\n\n        elif s.stateType in [ATNState.PLUS_LOOP_BACK, ATNState.STAR_LOOP_BACK]:\n            self.reportUnwantedToken(recognizer)\n            expecting = recognizer.getExpectedTokens()\n            whatFollowsLoopIterationOrRule = expecting.addSet(self.getErrorRecoverySet(recognizer))\n            self.consumeUntil(recognizer, whatFollowsLoopIterationOrRule)\n\n        else:\n           # do nothing if we can't identify the exact kind of ATN state\n           pass\n\n    # This is called by {@link #reportError} when the exception is a\n    # {@link NoViableAltException}.\n    #\n    # @see #reportError\n    #\n    # @param recognizer the parser instance\n    # @param e the recognition exception\n    #\n    def reportNoViableAlternative(self, recognizer:Parser, e:NoViableAltException):\n        tokens = recognizer.getTokenStream()\n        if tokens is not None:\n            if e.startToken.type==Token.EOF:\n                input = \"<EOF>\"\n            else:\n                input = tokens.getText(e.startToken, e.offendingToken)\n        else:\n            input = \"<unknown input>\"\n        msg = \"no viable alternative at input \" + self.escapeWSAndQuote(input)\n        recognizer.notifyErrorListeners(msg, e.offendingToken, e)\n\n    #\n    # This is called by {@link #reportError} when the exception is an\n    # {@link InputMismatchException}.\n    #\n    # @see #reportError\n    #\n    # @param recognizer the parser instance\n    # @param e the recognition exception\n    #\n    def reportInputMismatch(self, recognizer:Parser, e:InputMismatchException):\n        msg = \"mismatched input \" + self.getTokenErrorDisplay(e.offendingToken) \\\n              + \" expecting \" + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames)\n        recognizer.notifyErrorListeners(msg, e.offendingToken, e)\n\n    #\n    # This is called by {@link #reportError} when the exception is a\n    # {@link FailedPredicateException}.\n    #\n    # @see #reportError\n    #\n    # @param recognizer the parser instance\n    # @param e the recognition exception\n    #\n    def reportFailedPredicate(self, recognizer, e):\n        ruleName = recognizer.ruleNames[recognizer._ctx.getRuleIndex()]\n        msg = \"rule \" + ruleName + \" \" + e.message\n        recognizer.notifyErrorListeners(msg, e.offendingToken, e)\n\n    # This method is called to report a syntax error which requires the removal\n    # of a token from the input stream. At the time this method is called, the\n    # erroneous symbol is current {@code LT(1)} symbol and has not yet been\n    # removed from the input stream. When this method returns,\n    # {@code recognizer} is in error recovery mode.\n    #\n    # <p>This method is called when {@link #singleTokenDeletion} identifies\n    # single-token deletion as a viable recovery strategy for a mismatched\n    # input error.</p>\n    #\n    # <p>The default implementation simply returns if the handler is already in\n    # error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n    # enter error recovery mode, followed by calling\n    # {@link Parser#notifyErrorListeners}.</p>\n    #\n    # @param recognizer the parser instance\n    #\n    def reportUnwantedToken(self, recognizer:Parser):\n        if self.inErrorRecoveryMode(recognizer):\n            return\n\n        self.beginErrorCondition(recognizer)\n        t = recognizer.getCurrentToken()\n        tokenName = self.getTokenErrorDisplay(t)\n        expecting = self.getExpectedTokens(recognizer)\n        msg = \"extraneous input \" + tokenName + \" expecting \" \\\n            + expecting.toString(recognizer.literalNames, recognizer.symbolicNames)\n        recognizer.notifyErrorListeners(msg, t, None)\n\n    # This method is called to report a syntax error which requires the\n    # insertion of a missing token into the input stream. At the time this\n    # method is called, the missing token has not yet been inserted. When this\n    # method returns, {@code recognizer} is in error recovery mode.\n    #\n    # <p>This method is called when {@link #singleTokenInsertion} identifies\n    # single-token insertion as a viable recovery strategy for a mismatched\n    # input error.</p>\n    #\n    # <p>The default implementation simply returns if the handler is already in\n    # error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to\n    # enter error recovery mode, followed by calling\n    # {@link Parser#notifyErrorListeners}.</p>\n    #\n    # @param recognizer the parser instance\n    #\n    def reportMissingToken(self, recognizer:Parser):\n        if self.inErrorRecoveryMode(recognizer):\n            return\n        self.beginErrorCondition(recognizer)\n        t = recognizer.getCurrentToken()\n        expecting = self.getExpectedTokens(recognizer)\n        msg = \"missing \" + expecting.toString(recognizer.literalNames, recognizer.symbolicNames) \\\n              + \" at \" + self.getTokenErrorDisplay(t)\n        recognizer.notifyErrorListeners(msg, t, None)\n\n    # <p>The default implementation attempts to recover from the mismatched input\n    # by using single token insertion and deletion as described below. If the\n    # recovery attempt fails, this method throws an\n    # {@link InputMismatchException}.</p>\n    #\n    # <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>\n    #\n    # <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the\n    # right token, however, then assume {@code LA(1)} is some extra spurious\n    # token and delete it. Then consume and return the next token (which was\n    # the {@code LA(2)} token) as the successful result of the match operation.</p>\n    #\n    # <p>This recovery strategy is implemented by {@link #singleTokenDeletion}.</p>\n    #\n    # <p><strong>MISSING TOKEN</strong> (single token insertion)</p>\n    #\n    # <p>If current token (at {@code LA(1)}) is consistent with what could come\n    # after the expected {@code LA(1)} token, then assume the token is missing\n    # and use the parser's {@link TokenFactory} to create it on the fly. The\n    # \"insertion\" is performed by returning the created token as the successful\n    # result of the match operation.</p>\n    #\n    # <p>This recovery strategy is implemented by {@link #singleTokenInsertion}.</p>\n    #\n    # <p><strong>EXAMPLE</strong></p>\n    #\n    # <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When\n    # the parser returns from the nested call to {@code expr}, it will have\n    # call chain:</p>\n    #\n    # <pre>\n    # stat &rarr; expr &rarr; atom\n    # </pre>\n    #\n    # and it will be trying to match the {@code ')'} at this point in the\n    # derivation:\n    #\n    # <pre>\n    # =&gt; ID '=' '(' INT ')' ('+' atom)* ';'\n    #                    ^\n    # </pre>\n    #\n    # The attempt to match {@code ')'} will fail when it sees {@code ';'} and\n    # call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'}\n    # is in the set of tokens that can follow the {@code ')'} token reference\n    # in rule {@code atom}. It can assume that you forgot the {@code ')'}.\n    #\n    def recoverInline(self, recognizer:Parser):\n        # SINGLE TOKEN DELETION\n        matchedSymbol = self.singleTokenDeletion(recognizer)\n        if matchedSymbol is not None:\n            # we have deleted the extra token.\n            # now, move past ttype token as if all were ok\n            recognizer.consume()\n            return matchedSymbol\n\n        # SINGLE TOKEN INSERTION\n        if self.singleTokenInsertion(recognizer):\n            return self.getMissingSymbol(recognizer)\n\n        # even that didn't work; must throw the exception\n        raise InputMismatchException(recognizer)\n\n    #\n    # This method implements the single-token insertion inline error recovery\n    # strategy. It is called by {@link #recoverInline} if the single-token\n    # deletion strategy fails to recover from the mismatched input. If this\n    # method returns {@code true}, {@code recognizer} will be in error recovery\n    # mode.\n    #\n    # <p>This method determines whether or not single-token insertion is viable by\n    # checking if the {@code LA(1)} input symbol could be successfully matched\n    # if it were instead the {@code LA(2)} symbol. If this method returns\n    # {@code true}, the caller is responsible for creating and inserting a\n    # token with the correct type to produce this behavior.</p>\n    #\n    # @param recognizer the parser instance\n    # @return {@code true} if single-token insertion is a viable recovery\n    # strategy for the current mismatched input, otherwise {@code false}\n    #\n    def singleTokenInsertion(self, recognizer:Parser):\n        currentSymbolType = recognizer.getTokenStream().LA(1)\n        # if current token is consistent with what could come after current\n        # ATN state, then we know we're missing a token; error recovery\n        # is free to conjure up and insert the missing token\n        atn = recognizer._interp.atn\n        currentState = atn.states[recognizer.state]\n        next = currentState.transitions[0].target\n        expectingAtLL2 = atn.nextTokens(next, recognizer._ctx)\n        if currentSymbolType in expectingAtLL2:\n            self.reportMissingToken(recognizer)\n            return True\n        else:\n            return False\n\n    # This method implements the single-token deletion inline error recovery\n    # strategy. It is called by {@link #recoverInline} to attempt to recover\n    # from mismatched input. If this method returns null, the parser and error\n    # handler state will not have changed. If this method returns non-null,\n    # {@code recognizer} will <em>not</em> be in error recovery mode since the\n    # returned token was a successful match.\n    #\n    # <p>If the single-token deletion is successful, this method calls\n    # {@link #reportUnwantedToken} to report the error, followed by\n    # {@link Parser#consume} to actually \"delete\" the extraneous token. Then,\n    # before returning {@link #reportMatch} is called to signal a successful\n    # match.</p>\n    #\n    # @param recognizer the parser instance\n    # @return the successfully matched {@link Token} instance if single-token\n    # deletion successfully recovers from the mismatched input, otherwise\n    # {@code null}\n    #\n    def singleTokenDeletion(self, recognizer:Parser):\n        nextTokenType = recognizer.getTokenStream().LA(2)\n        expecting = self.getExpectedTokens(recognizer)\n        if nextTokenType in expecting:\n            self.reportUnwantedToken(recognizer)\n            # print(\"recoverFromMismatchedToken deleting \" \\\n            #     + str(recognizer.getTokenStream().LT(1)) \\\n            #     + \" since \" + str(recognizer.getTokenStream().LT(2)) \\\n            #     + \" is what we want\", file=sys.stderr)\n            recognizer.consume() # simply delete extra token\n            # we want to return the token we're actually matching\n            matchedSymbol = recognizer.getCurrentToken()\n            self.reportMatch(recognizer) # we know current token is correct\n            return matchedSymbol\n        else:\n            return None\n\n    # Conjure up a missing token during error recovery.\n    #\n    #  The recognizer attempts to recover from single missing\n    #  symbols. But, actions might refer to that missing symbol.\n    #  For example, x=ID {f($x);}. The action clearly assumes\n    #  that there has been an identifier matched previously and that\n    #  $x points at that token. If that token is missing, but\n    #  the next token in the stream is what we want we assume that\n    #  this token is missing and we keep going. Because we\n    #  have to return some token to replace the missing token,\n    #  we have to conjure one up. This method gives the user control\n    #  over the tokens returned for missing tokens. Mostly,\n    #  you will want to create something special for identifier\n    #  tokens. For literals such as '{' and ',', the default\n    #  action in the parser or tree parser works. It simply creates\n    #  a CommonToken of the appropriate type. The text will be the token.\n    #  If you change what tokens must be created by the lexer,\n    #  override this method to create the appropriate tokens.\n    #\n    def getMissingSymbol(self, recognizer:Parser):\n        currentSymbol = recognizer.getCurrentToken()\n        expecting = self.getExpectedTokens(recognizer)\n        expectedTokenType = expecting[0] # get any element\n        if expectedTokenType==Token.EOF:\n            tokenText = \"<missing EOF>\"\n        else:\n            name = None\n            if expectedTokenType < len(recognizer.literalNames):\n                name = recognizer.literalNames[expectedTokenType]\n            if name is None and expectedTokenType < len(recognizer.symbolicNames):\n                name = recognizer.symbolicNames[expectedTokenType]\n            tokenText = \"<missing \" + str(name) + \">\"\n        current = currentSymbol\n        lookback = recognizer.getTokenStream().LT(-1)\n        if current.type==Token.EOF and lookback is not None:\n            current = lookback\n        return recognizer.getTokenFactory().create(current.source,\n            expectedTokenType, tokenText, Token.DEFAULT_CHANNEL,\n            -1, -1, current.line, current.column)\n\n    def getExpectedTokens(self, recognizer:Parser):\n        return recognizer.getExpectedTokens()\n\n    # How should a token be displayed in an error message? The default\n    #  is to display just the text, but during development you might\n    #  want to have a lot of information spit out.  Override in that case\n    #  to use t.toString() (which, for CommonToken, dumps everything about\n    #  the token). This is better than forcing you to override a method in\n    #  your token objects because you don't have to go modify your lexer\n    #  so that it creates a new Java type.\n    #\n    def getTokenErrorDisplay(self, t:Token):\n        if t is None:\n            return \"<no token>\"\n        s = t.text\n        if s is None:\n            if t.type==Token.EOF:\n                s = \"<EOF>\"\n            else:\n                s = \"<\" + str(t.type) + \">\"\n        return self.escapeWSAndQuote(s)\n\n    def escapeWSAndQuote(self, s:str):\n        s = s.replace(\"\\n\",\"\\\\n\")\n        s = s.replace(\"\\r\",\"\\\\r\")\n        s = s.replace(\"\\t\",\"\\\\t\")\n        return \"'\" + s + \"'\"\n\n    #  Compute the error recovery set for the current rule.  During\n    #  rule invocation, the parser pushes the set of tokens that can\n    #  follow that rule reference on the stack; this amounts to\n    #  computing FIRST of what follows the rule reference in the\n    #  enclosing rule. See LinearApproximator.FIRST().\n    #  This local follow set only includes tokens\n    #  from within the rule; i.e., the FIRST computation done by\n    #  ANTLR stops at the end of a rule.\n    #\n    #  EXAMPLE\n    #\n    #  When you find a \"no viable alt exception\", the input is not\n    #  consistent with any of the alternatives for rule r.  The best\n    #  thing to do is to consume tokens until you see something that\n    #  can legally follow a call to r#or* any rule that called r.\n    #  You don't want the exact set of viable next tokens because the\n    #  input might just be missing a token--you might consume the\n    #  rest of the input looking for one of the missing tokens.\n    #\n    #  Consider grammar:\n    #\n    #  a : '[' b ']'\n    #    | '(' b ')'\n    #    ;\n    #  b : c '^' INT ;\n    #  c : ID\n    #    | INT\n    #    ;\n    #\n    #  At each rule invocation, the set of tokens that could follow\n    #  that rule is pushed on a stack.  Here are the various\n    #  context-sensitive follow sets:\n    #\n    #  FOLLOW(b1_in_a) = FIRST(']') = ']'\n    #  FOLLOW(b2_in_a) = FIRST(')') = ')'\n    #  FOLLOW(c_in_b) = FIRST('^') = '^'\n    #\n    #  Upon erroneous input \"[]\", the call chain is\n    #\n    #  a -> b -> c\n    #\n    #  and, hence, the follow context stack is:\n    #\n    #  depth     follow set       start of rule execution\n    #    0         <EOF>                    a (from main())\n    #    1          ']'                     b\n    #    2          '^'                     c\n    #\n    #  Notice that ')' is not included, because b would have to have\n    #  been called from a different context in rule a for ')' to be\n    #  included.\n    #\n    #  For error recovery, we cannot consider FOLLOW(c)\n    #  (context-sensitive or otherwise).  We need the combined set of\n    #  all context-sensitive FOLLOW sets--the set of all tokens that\n    #  could follow any reference in the call chain.  We need to\n    #  resync to one of those tokens.  Note that FOLLOW(c)='^' and if\n    #  we resync'd to that token, we'd consume until EOF.  We need to\n    #  sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.\n    #  In this case, for input \"[]\", LA(1) is ']' and in the set, so we would\n    #  not consume anything. After printing an error, rule c would\n    #  return normally.  Rule b would not find the required '^' though.\n    #  At this point, it gets a mismatched token error and throws an\n    #  exception (since LA(1) is not in the viable following token\n    #  set).  The rule exception handler tries to recover, but finds\n    #  the same recovery set and doesn't consume anything.  Rule b\n    #  exits normally returning to rule a.  Now it finds the ']' (and\n    #  with the successful match exits errorRecovery mode).\n    #\n    #  So, you can see that the parser walks up the call chain looking\n    #  for the token that was a member of the recovery set.\n    #\n    #  Errors are not generated in errorRecovery mode.\n    #\n    #  ANTLR's error recovery mechanism is based upon original ideas:\n    #\n    #  \"Algorithms + Data Structures = Programs\" by Niklaus Wirth\n    #\n    #  and\n    #\n    #  \"A note on error recovery in recursive descent parsers\":\n    #  http:#portal.acm.org/citation.cfm?id=947902.947905\n    #\n    #  Later, Josef Grosch had some good ideas:\n    #\n    #  \"Efficient and Comfortable Error Recovery in Recursive Descent\n    #  Parsers\":\n    #  ftp:#www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip\n    #\n    #  Like Grosch I implement context-sensitive FOLLOW sets that are combined\n    #  at run-time upon error to avoid overhead during parsing.\n    #\n    def getErrorRecoverySet(self, recognizer:Parser):\n        atn = recognizer._interp.atn\n        ctx = recognizer._ctx\n        recoverSet = IntervalSet()\n        while ctx is not None and ctx.invokingState>=0:\n            # compute what follows who invoked us\n            invokingState = atn.states[ctx.invokingState]\n            rt = invokingState.transitions[0]\n            follow = atn.nextTokens(rt.followState)\n            recoverSet.addSet(follow)\n            ctx = ctx.parentCtx\n        recoverSet.removeOne(Token.EPSILON)\n        return recoverSet\n\n    # Consume tokens until one matches the given token set.#\n    def consumeUntil(self, recognizer:Parser, set_:set):\n        ttype = recognizer.getTokenStream().LA(1)\n        while ttype != Token.EOF and not ttype in set_:\n            recognizer.consume()\n            ttype = recognizer.getTokenStream().LA(1)\n\n\n#\n# This implementation of {@link ANTLRErrorStrategy} responds to syntax errors\n# by immediately canceling the parse operation with a\n# {@link ParseCancellationException}. The implementation ensures that the\n# {@link ParserRuleContext#exception} field is set for all parse tree nodes\n# that were not completed prior to encountering the error.\n#\n# <p>\n# This error strategy is useful in the following scenarios.</p>\n#\n# <ul>\n# <li><strong>Two-stage parsing:</strong> This error strategy allows the first\n# stage of two-stage parsing to immediately terminate if an error is\n# encountered, and immediately fall back to the second stage. In addition to\n# avoiding wasted work by attempting to recover from errors here, the empty\n# implementation of {@link BailErrorStrategy#sync} improves the performance of\n# the first stage.</li>\n# <li><strong>Silent validation:</strong> When syntax errors are not being\n# reported or logged, and the parse result is simply ignored if errors occur,\n# the {@link BailErrorStrategy} avoids wasting work on recovering from errors\n# when the result will be ignored either way.</li>\n# </ul>\n#\n# <p>\n# {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>\n#\n# @see Parser#setErrorHandler(ANTLRErrorStrategy)\n#\nclass BailErrorStrategy(DefaultErrorStrategy):\n    # Instead of recovering from exception {@code e}, re-throw it wrapped\n    #  in a {@link ParseCancellationException} so it is not caught by the\n    #  rule function catches.  Use {@link Exception#getCause()} to get the\n    #  original {@link RecognitionException}.\n    #\n    def recover(self, recognizer:Parser, e:RecognitionException):\n        context = recognizer._ctx\n        while context is not None:\n            context.exception = e\n            context = context.parentCtx\n        raise ParseCancellationException(e)\n\n    # Make sure we don't attempt to recover inline; if the parser\n    #  successfully recovers, it won't throw an exception.\n    #\n    def recoverInline(self, recognizer:Parser):\n        self.recover(recognizer, InputMismatchException(recognizer))\n\n    # Make sure we don't attempt to recover from problems in subrules.#\n    def sync(self, recognizer:Parser):\n        pass\n\ndel Parser"
  },
  {
    "path": "runtime/Python3/src/antlr4/error/Errors.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n# need forward declaration\nToken = None\nLexer = None\nParser = None\nTokenStream = None\nATNConfigSet = None\nParserRulecontext = None\nPredicateTransition = None\nBufferedTokenStream = None\n\nclass UnsupportedOperationException(Exception):\n\n    def __init__(self, msg:str):\n        super().__init__(msg)\n\nclass IllegalStateException(Exception):\n\n    def __init__(self, msg:str):\n        super().__init__(msg)\n\nclass CancellationException(IllegalStateException):\n\n    def __init__(self, msg:str):\n        super().__init__(msg)\n\n# The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n#  3 kinds of errors: prediction errors, failed predicate errors, and\n#  mismatched input errors. In each case, the parser knows where it is\n#  in the input, where it is in the ATN, the rule invocation stack,\n#  and what kind of problem occurred.\n\nfrom ..InputStream import InputStream\nfrom ..ParserRuleContext import ParserRuleContext\nfrom ..Recognizer import Recognizer\n\nclass RecognitionException(Exception):\n\n\n    def __init__(self, message:str=None, recognizer:Recognizer=None, input:InputStream=None, ctx:ParserRulecontext=None):\n        super().__init__(message)\n        self.message = message\n        self.recognizer = recognizer\n        self.input = input\n        self.ctx = ctx\n        # The current {@link Token} when an error occurred. Since not all streams\n        # support accessing symbols by index, we have to track the {@link Token}\n        # instance itself.\n        self.offendingToken = None\n        # Get the ATN state number the parser was in at the time the error\n        # occurred. For {@link NoViableAltException} and\n        # {@link LexerNoViableAltException} exceptions, this is the\n        # {@link DecisionState} number. For others, it is the state whose outgoing\n        # edge we couldn't match.\n        self.offendingState = -1\n        if recognizer is not None:\n            self.offendingState = recognizer.state\n\n    # <p>If the state number is not known, this method returns -1.</p>\n\n    #\n    # Gets the set of input symbols which could potentially follow the\n    # previously matched symbol at the time this exception was thrown.\n    #\n    # <p>If the set of expected tokens is not known and could not be computed,\n    # this method returns {@code null}.</p>\n    #\n    # @return The set of token types that could potentially follow the current\n    # state in the ATN, or {@code null} if the information is not available.\n    #/\n    def getExpectedTokens(self):\n        if self.recognizer is not None:\n            return self.recognizer.atn.getExpectedTokens(self.offendingState, self.ctx)\n        else:\n            return None\n\n\nclass LexerNoViableAltException(RecognitionException):\n\n    def __init__(self, lexer:Lexer, input:InputStream, startIndex:int, deadEndConfigs:ATNConfigSet):\n        super().__init__(message=None, recognizer=lexer, input=input, ctx=None)\n        self.startIndex = startIndex\n        self.deadEndConfigs = deadEndConfigs\n        self.message = \"\"\n\n    def __str__(self):\n        symbol = \"\"\n        if self.startIndex >= 0 and self.startIndex < self.input.size:\n            symbol = self.input.getText(self.startIndex, self.startIndex)\n            # TODO symbol = Utils.escapeWhitespace(symbol, false);\n        return \"LexerNoViableAltException('\" + symbol + \"')\"\n\n# Indicates that the parser could not decide which of two or more paths\n#  to take based upon the remaining input. It tracks the starting token\n#  of the offending input and also knows where the parser was\n#  in the various paths when the error. Reported by reportNoViableAlternative()\n#\nclass NoViableAltException(RecognitionException):\n\n    def __init__(self, recognizer:Parser, input:TokenStream=None, startToken:Token=None,\n                    offendingToken:Token=None, deadEndConfigs:ATNConfigSet=None, ctx:ParserRuleContext=None):\n        if ctx is None:\n            ctx = recognizer._ctx\n        if offendingToken is None:\n            offendingToken = recognizer.getCurrentToken()\n        if startToken is None:\n            startToken = recognizer.getCurrentToken()\n        if input is None:\n            input = recognizer.getInputStream()\n        super().__init__(recognizer=recognizer, input=input, ctx=ctx)\n        # Which configurations did we try at input.index() that couldn't match input.LT(1)?#\n        self.deadEndConfigs = deadEndConfigs\n        # The token object at the start index; the input stream might\n        # \tnot be buffering tokens so get a reference to it. (At the\n        #  time the error occurred, of course the stream needs to keep a\n        #  buffer all of the tokens but later we might not have access to those.)\n        self.startToken = startToken\n        self.offendingToken = offendingToken\n\n# This signifies any kind of mismatched input exceptions such as\n#  when the current input does not match the expected token.\n#\nclass InputMismatchException(RecognitionException):\n\n    def __init__(self, recognizer:Parser):\n        super().__init__(recognizer=recognizer, input=recognizer.getInputStream(), ctx=recognizer._ctx)\n        self.offendingToken = recognizer.getCurrentToken()\n\n\n# A semantic predicate failed during validation.  Validation of predicates\n#  occurs when normally parsing the alternative just like matching a token.\n#  Disambiguating predicate evaluation occurs when we test a predicate during\n#  prediction.\n\nclass FailedPredicateException(RecognitionException):\n\n    def __init__(self, recognizer:Parser, predicate:str=None, message:str=None):\n        super().__init__(message=self.formatMessage(predicate,message), recognizer=recognizer,\n                         input=recognizer.getInputStream(), ctx=recognizer._ctx)\n        s = recognizer._interp.atn.states[recognizer.state]\n        trans = s.transitions[0]\n        from ..atn.Transition import PredicateTransition\n        if isinstance(trans, PredicateTransition):\n            self.ruleIndex = trans.ruleIndex\n            self.predicateIndex = trans.predIndex\n        else:\n            self.ruleIndex = 0\n            self.predicateIndex = 0\n        self.predicate = predicate\n        self.offendingToken = recognizer.getCurrentToken()\n\n    def formatMessage(self, predicate:str, message:str):\n        if message is not None:\n            return message\n        else:\n            return \"failed predicate: {\" + predicate + \"}?\"\n\nclass ParseCancellationException(CancellationException):\n\n    pass\n\ndel Token\ndel Lexer\ndel Parser\ndel TokenStream\ndel ATNConfigSet\ndel ParserRulecontext\ndel PredicateTransition\ndel BufferedTokenStream\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/error/__init__.py",
    "content": "__author__ = 'ericvergnaud'\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/Chunk.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\nclass Chunk(object):\n    pass\n\nclass TagChunk(Chunk):\n    __slots__ = ('tag', 'label')\n\n    def __init__(self, tag:str, label:str=None):\n        self.tag = tag\n        self.label = label\n\n    def __str__(self):\n        if self.label is None:\n            return self.tag\n        else:\n            return self.label + \":\" + self.tag\n\nclass TextChunk(Chunk):\n    __slots__ = 'text'\n\n    def __init__(self, text:str):\n        self.text = text\n\n    def __str__(self):\n        return \"'\" + self.text + \"'\"\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/ParseTreeMatch.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n\n#\n# Represents the result of matching a {@link ParseTree} against a tree pattern.\n#\nfrom io import StringIO\nfrom ..tree.ParseTreePattern import ParseTreePattern\nfrom ..tree.Tree import ParseTree\n\n\nclass ParseTreeMatch(object):\n    __slots__ = ('tree', 'pattern', 'labels', 'mismatchedNode')\n    #\n    # Constructs a new instance of {@link ParseTreeMatch} from the specified\n    # parse tree and pattern.\n    #\n    # @param tree The parse tree to match against the pattern.\n    # @param pattern The parse tree pattern.\n    # @param labels A mapping from label names to collections of\n    # {@link ParseTree} objects located by the tree pattern matching process.\n    # @param mismatchedNode The first node which failed to match the tree\n    # pattern during the matching process.\n    #\n    # @exception IllegalArgumentException if {@code tree} is {@code null}\n    # @exception IllegalArgumentException if {@code pattern} is {@code null}\n    # @exception IllegalArgumentException if {@code labels} is {@code null}\n    #\n    def __init__(self, tree:ParseTree, pattern:ParseTreePattern, labels:dict, mismatchedNode:ParseTree):\n        if tree is None:\n            raise Exception(\"tree cannot be null\")\n        if pattern is None:\n            raise Exception(\"pattern cannot be null\")\n        if labels is None:\n            raise Exception(\"labels cannot be null\")\n        self.tree = tree\n        self.pattern = pattern\n        self.labels = labels\n        self.mismatchedNode = mismatchedNode\n\n    #\n    # Get the last node associated with a specific {@code label}.\n    #\n    # <p>For example, for pattern {@code <id:ID>}, {@code get(\"id\")} returns the\n    # node matched for that {@code ID}. If more than one node\n    # matched the specified label, only the last is returned. If there is\n    # no node associated with the label, this returns {@code null}.</p>\n    #\n    # <p>Pattern tags like {@code <ID>} and {@code <expr>} without labels are\n    # considered to be labeled with {@code ID} and {@code expr}, respectively.</p>\n    #\n    # @param label The label to check.\n    #\n    # @return The last {@link ParseTree} to match a tag with the specified\n    # label, or {@code null} if no parse tree matched a tag with the label.\n    #\n    def get(self, label:str):\n        parseTrees = self.labels.get(label, None)\n        if parseTrees is None or len(parseTrees)==0:\n            return None\n        else:\n            return parseTrees[len(parseTrees)-1]\n\n    #\n    # Return all nodes matching a rule or token tag with the specified label.\n    #\n    # <p>If the {@code label} is the name of a parser rule or token in the\n    # grammar, the resulting list will contain both the parse trees matching\n    # rule or tags explicitly labeled with the label and the complete set of\n    # parse trees matching the labeled and unlabeled tags in the pattern for\n    # the parser rule or token. For example, if {@code label} is {@code \"foo\"},\n    # the result will contain <em>all</em> of the following.</p>\n    #\n    # <ul>\n    # <li>Parse tree nodes matching tags of the form {@code <foo:anyRuleName>} and\n    # {@code <foo:AnyTokenName>}.</li>\n    # <li>Parse tree nodes matching tags of the form {@code <anyLabel:foo>}.</li>\n    # <li>Parse tree nodes matching tags of the form {@code <foo>}.</li>\n    # </ul>\n    #\n    # @param label The label.\n    #\n    # @return A collection of all {@link ParseTree} nodes matching tags with\n    # the specified {@code label}. If no nodes matched the label, an empty list\n    # is returned.\n    #\n    def getAll(self, label:str):\n        nodes = self.labels.get(label, None)\n        if nodes is None:\n            return list()\n        else:\n            return nodes\n\n\n    #\n    # Gets a value indicating whether the match operation succeeded.\n    #\n    # @return {@code true} if the match operation succeeded; otherwise,\n    # {@code false}.\n    #\n    def succeeded(self):\n        return self.mismatchedNode is None\n\n    #\n    # {@inheritDoc}\n    #\n    def __str__(self):\n        with StringIO() as buf:\n            buf.write(\"Match \")\n            buf.write(\"succeeded\" if self.succeeded() else \"failed\")\n            buf.write(\"; found \")\n            buf.write(str(len(self.labels)))\n            buf.write(\" labels\")\n            return buf.getvalue()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/ParseTreePattern.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# A pattern like {@code <ID> = <expr>;} converted to a {@link ParseTree} by\n# {@link ParseTreePatternMatcher#compile(String, int)}.\n#\nfrom ..tree.ParseTreePatternMatcher import ParseTreePatternMatcher\nfrom ..tree.Tree import ParseTree\nfrom ..xpath.XPathLexer import XPathLexer\n\n\nclass ParseTreePattern(object):\n    __slots__ = ('matcher', 'patternRuleIndex', 'pattern', 'patternTree')\n\n    # Construct a new instance of the {@link ParseTreePattern} class.\n    #\n    # @param matcher The {@link ParseTreePatternMatcher} which created this\n    # tree pattern.\n    # @param pattern The tree pattern in concrete syntax form.\n    # @param patternRuleIndex The parser rule which serves as the root of the\n    # tree pattern.\n    # @param patternTree The tree pattern in {@link ParseTree} form.\n    #\n    def __init__(self, matcher:ParseTreePatternMatcher, pattern:str, patternRuleIndex:int , patternTree:ParseTree):\n        self.matcher = matcher\n        self.patternRuleIndex = patternRuleIndex\n        self.pattern = pattern\n        self.patternTree = patternTree\n\n    #\n    # Match a specific parse tree against this tree pattern.\n    #\n    # @param tree The parse tree to match against this tree pattern.\n    # @return A {@link ParseTreeMatch} object describing the result of the\n    # match operation. The {@link ParseTreeMatch#succeeded()} method can be\n    # used to determine whether or not the match was successful.\n    #\n    def match(self, tree:ParseTree):\n        return self.matcher.match(tree, self)\n\n    #\n    # Determine whether or not a parse tree matches this tree pattern.\n    #\n    # @param tree The parse tree to match against this tree pattern.\n    # @return {@code true} if {@code tree} is a match for the current tree\n    # pattern; otherwise, {@code false}.\n    #\n    def matches(self, tree:ParseTree):\n        return self.matcher.match(tree, self).succeeded()\n\n    # Find all nodes using XPath and then try to match those subtrees against\n    # this tree pattern.\n    #\n    # @param tree The {@link ParseTree} to match against this pattern.\n    # @param xpath An expression matching the nodes\n    #\n    # @return A collection of {@link ParseTreeMatch} objects describing the\n    # successful matches. Unsuccessful matches are omitted from the result,\n    # regardless of the reason for the failure.\n    #\n    def findAll(self, tree:ParseTree, xpath:str):\n        subtrees = XPath.findAll(tree, xpath, self.matcher.parser)\n        matches = list()\n        for t in subtrees:\n            match = self.match(t)\n            if match.succeeded():\n                matches.append(match)\n        return matches\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/ParseTreePatternMatcher.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# A tree pattern matching mechanism for ANTLR {@link ParseTree}s.\n#\n# <p>Patterns are strings of source input text with special tags representing\n# token or rule references such as:</p>\n#\n# <p>{@code <ID> = <expr>;}</p>\n#\n# <p>Given a pattern start rule such as {@code statement}, this object constructs\n# a {@link ParseTree} with placeholders for the {@code ID} and {@code expr}\n# subtree. Then the {@link #match} routines can compare an actual\n# {@link ParseTree} from a parse with this pattern. Tag {@code <ID>} matches\n# any {@code ID} token and tag {@code <expr>} references the result of the\n# {@code expr} rule (generally an instance of {@code ExprContext}.</p>\n#\n# <p>Pattern {@code x = 0;} is a similar pattern that matches the same pattern\n# except that it requires the identifier to be {@code x} and the expression to\n# be {@code 0}.</p>\n#\n# <p>The {@link #matches} routines return {@code true} or {@code false} based\n# upon a match for the tree rooted at the parameter sent in. The\n# {@link #match} routines return a {@link ParseTreeMatch} object that\n# contains the parse tree, the parse tree pattern, and a map from tag name to\n# matched nodes (more below). A subtree that fails to match, returns with\n# {@link ParseTreeMatch#mismatchedNode} set to the first tree node that did not\n# match.</p>\n#\n# <p>For efficiency, you can compile a tree pattern in string form to a\n# {@link ParseTreePattern} object.</p>\n#\n# <p>See {@code TestParseTreeMatcher} for lots of examples.\n# {@link ParseTreePattern} has two static helper methods:\n# {@link ParseTreePattern#findAll} and {@link ParseTreePattern#match} that\n# are easy to use but not super efficient because they create new\n# {@link ParseTreePatternMatcher} objects each time and have to compile the\n# pattern in string form before using it.</p>\n#\n# <p>The lexer and parser that you pass into the {@link ParseTreePatternMatcher}\n# constructor are used to parse the pattern in string form. The lexer converts\n# the {@code <ID> = <expr>;} into a sequence of four tokens (assuming lexer\n# throws out whitespace or puts it on a hidden channel). Be aware that the\n# input stream is reset for the lexer (but not the parser; a\n# {@link ParserInterpreter} is created to parse the input.). Any user-defined\n# fields you have put into the lexer might get changed when this mechanism asks\n# it to scan the pattern string.</p>\n#\n# <p>Normally a parser does not accept token {@code <expr>} as a valid\n# {@code expr} but, from the parser passed in, we create a special version of\n# the underlying grammar representation (an {@link ATN}) that allows imaginary\n# tokens representing rules ({@code <expr>}) to match entire rules. We call\n# these <em>bypass alternatives</em>.</p>\n#\n# <p>Delimiters are {@code <} and {@code >}, with {@code \\} as the escape string\n# by default, but you can set them to whatever you want using\n# {@link #setDelimiters}. You must escape both start and stop strings\n# {@code \\<} and {@code \\>}.</p>\n#\nfrom ..CommonTokenStream import CommonTokenStream\nfrom ..InputStream import InputStream\nfrom ..ParserRuleContext import ParserRuleContext\nfrom ..Lexer import Lexer\nfrom ..ListTokenSource import ListTokenSource\nfrom ..Token import Token\nfrom ..error.ErrorStrategy import BailErrorStrategy\nfrom ..error.Errors import RecognitionException, ParseCancellationException\nfrom ..tree.Chunk import TagChunk, TextChunk\nfrom ..tree.RuleTagToken import RuleTagToken\nfrom ..tree.TokenTagToken import TokenTagToken\nfrom ..tree.Tree import ParseTree, TerminalNode, RuleNode\n\n# need forward declaration\nParser = None\nParseTreePattern = None\n\nclass CannotInvokeStartRule(Exception):\n\n    def __init__(self, e:Exception):\n        super().__init__(e)\n\nclass StartRuleDoesNotConsumeFullPattern(Exception):\n\n    pass\n\n\nclass ParseTreePatternMatcher(object):\n    __slots__ = ('lexer', 'parser', 'start', 'stop', 'escape')\n\n    # Constructs a {@link ParseTreePatternMatcher} or from a {@link Lexer} and\n    # {@link Parser} object. The lexer input stream is altered for tokenizing\n    # the tree patterns. The parser is used as a convenient mechanism to get\n    # the grammar name, plus token, rule names.\n    def __init__(self, lexer:Lexer, parser:Parser):\n        self.lexer = lexer\n        self.parser = parser\n        self.start = \"<\"\n        self.stop = \">\"\n        self.escape = \"\\\\\"  # e.g., \\< and \\> must escape BOTH!\n\n    # Set the delimiters used for marking rule and token tags within concrete\n    # syntax used by the tree pattern parser.\n    #\n    # @param start The start delimiter.\n    # @param stop The stop delimiter.\n    # @param escapeLeft The escape sequence to use for escaping a start or stop delimiter.\n    #\n    # @exception IllegalArgumentException if {@code start} is {@code null} or empty.\n    # @exception IllegalArgumentException if {@code stop} is {@code null} or empty.\n    #\n    def setDelimiters(self, start:str, stop:str, escapeLeft:str):\n        if start is None or len(start)==0:\n            raise Exception(\"start cannot be null or empty\")\n        if stop is None or len(stop)==0:\n            raise Exception(\"stop cannot be null or empty\")\n        self.start = start\n        self.stop = stop\n        self.escape = escapeLeft\n\n    # Does {@code pattern} matched as rule {@code patternRuleIndex} match {@code tree}?#\n    def matchesRuleIndex(self, tree:ParseTree, pattern:str, patternRuleIndex:int):\n        p = self.compileTreePattern(pattern, patternRuleIndex)\n        return self.matches(tree, p)\n\n    # Does {@code pattern} matched as rule patternRuleIndex match tree? Pass in a\n    #  compiled pattern instead of a string representation of a tree pattern.\n    #\n    def matchesPattern(self, tree:ParseTree, pattern:ParseTreePattern):\n        mismatchedNode = self.matchImpl(tree, pattern.patternTree, dict())\n        return mismatchedNode is None\n\n    #\n    # Compare {@code pattern} matched as rule {@code patternRuleIndex} against\n    # {@code tree} and return a {@link ParseTreeMatch} object that contains the\n    # matched elements, or the node at which the match failed.\n    #\n    def matchRuleIndex(self, tree:ParseTree, pattern:str, patternRuleIndex:int):\n        p = self.compileTreePattern(pattern, patternRuleIndex)\n        return self.matchPattern(tree, p)\n\n    #\n    # Compare {@code pattern} matched against {@code tree} and return a\n    # {@link ParseTreeMatch} object that contains the matched elements, or the\n    # node at which the match failed. Pass in a compiled pattern instead of a\n    # string representation of a tree pattern.\n    #\n    def matchPattern(self, tree:ParseTree, pattern:ParseTreePattern):\n        labels = dict()\n        mismatchedNode = self.matchImpl(tree, pattern.patternTree, labels)\n        from ..tree.ParseTreeMatch import ParseTreeMatch\n        return ParseTreeMatch(tree, pattern, labels, mismatchedNode)\n\n    #\n    # For repeated use of a tree pattern, compile it to a\n    # {@link ParseTreePattern} using this method.\n    #\n    def compileTreePattern(self, pattern:str, patternRuleIndex:int):\n        tokenList = self.tokenize(pattern)\n        tokenSrc = ListTokenSource(tokenList)\n        tokens = CommonTokenStream(tokenSrc)\n        from ..ParserInterpreter import ParserInterpreter\n        parserInterp = ParserInterpreter(self.parser.grammarFileName, self.parser.tokenNames,\n                                self.parser.ruleNames, self.parser.getATNWithBypassAlts(),tokens)\n        tree = None\n        try:\n            parserInterp.setErrorHandler(BailErrorStrategy())\n            tree = parserInterp.parse(patternRuleIndex)\n        except ParseCancellationException as e:\n            raise e.cause\n        except RecognitionException as e:\n            raise e\n        except Exception as e:\n            raise CannotInvokeStartRule(e)\n\n        # Make sure tree pattern compilation checks for a complete parse\n        if tokens.LA(1)!=Token.EOF:\n            raise StartRuleDoesNotConsumeFullPattern()\n\n        from ..tree.ParseTreePattern import ParseTreePattern\n        return ParseTreePattern(self, pattern, patternRuleIndex, tree)\n\n    #\n    # Recursively walk {@code tree} against {@code patternTree}, filling\n    # {@code match.}{@link ParseTreeMatch#labels labels}.\n    #\n    # @return the first node encountered in {@code tree} which does not match\n    # a corresponding node in {@code patternTree}, or {@code null} if the match\n    # was successful. The specific node returned depends on the matching\n    # algorithm used by the implementation, and may be overridden.\n    #\n    def matchImpl(self, tree:ParseTree, patternTree:ParseTree, labels:dict):\n        if tree is None:\n            raise Exception(\"tree cannot be null\")\n        if patternTree is None:\n            raise Exception(\"patternTree cannot be null\")\n\n        # x and <ID>, x and y, or x and x; or could be mismatched types\n        if isinstance(tree, TerminalNode) and isinstance(patternTree, TerminalNode ):\n            mismatchedNode = None\n            # both are tokens and they have same type\n            if tree.symbol.type == patternTree.symbol.type:\n                if isinstance( patternTree.symbol, TokenTagToken ): # x and <ID>\n                    tokenTagToken = patternTree.symbol\n                    # track label->list-of-nodes for both token name and label (if any)\n                    self.map(labels, tokenTagToken.tokenName, tree)\n                    if tokenTagToken.label is not None:\n                        self.map(labels, tokenTagToken.label, tree)\n                elif tree.getText()==patternTree.getText():\n                    # x and x\n                    pass\n                else:\n                    # x and y\n                    if mismatchedNode is None:\n                        mismatchedNode = tree\n            else:\n                if mismatchedNode is None:\n                    mismatchedNode = tree\n\n            return mismatchedNode\n\n        if isinstance(tree, ParserRuleContext) and isinstance(patternTree, ParserRuleContext):\n            mismatchedNode = None\n            # (expr ...) and <expr>\n            ruleTagToken = self.getRuleTagToken(patternTree)\n            if ruleTagToken is not None:\n                m = None\n                if tree.ruleContext.ruleIndex == patternTree.ruleContext.ruleIndex:\n                    # track label->list-of-nodes for both rule name and label (if any)\n                    self.map(labels, ruleTagToken.ruleName, tree)\n                    if ruleTagToken.label is not None:\n                        self.map(labels, ruleTagToken.label, tree)\n                else:\n                    if mismatchedNode is None:\n                        mismatchedNode = tree\n\n                return mismatchedNode\n\n            # (expr ...) and (expr ...)\n            if tree.getChildCount()!=patternTree.getChildCount():\n                if mismatchedNode is None:\n                    mismatchedNode = tree\n                return mismatchedNode\n\n            n = tree.getChildCount()\n            for i in range(0, n):\n                childMatch = self.matchImpl(tree.getChild(i), patternTree.getChild(i), labels)\n                if childMatch is not None:\n                    return childMatch\n\n            return mismatchedNode\n\n        # if nodes aren't both tokens or both rule nodes, can't match\n        return tree\n\n    def map(self, labels, label, tree):\n        v = labels.get(label, None)\n        if v is None:\n            v = list()\n            labels[label] = v\n        v.append(tree)\n\n    # Is {@code t} {@code (expr <expr>)} subtree?#\n    def getRuleTagToken(self, tree:ParseTree):\n        if isinstance( tree, RuleNode ):\n            if tree.getChildCount()==1 and isinstance(tree.getChild(0), TerminalNode ):\n                c = tree.getChild(0)\n                if isinstance( c.symbol, RuleTagToken ):\n                    return c.symbol\n        return None\n\n    def tokenize(self, pattern:str):\n        # split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)\n        chunks = self.split(pattern)\n\n        # create token stream from text and tags\n        tokens = list()\n        for chunk in chunks:\n            if isinstance( chunk, TagChunk ):\n                # add special rule token or conjure up new token from name\n                if chunk.tag[0].isupper():\n                    ttype = self.parser.getTokenType(chunk.tag)\n                    if ttype==Token.INVALID_TYPE:\n                        raise Exception(\"Unknown token \" + str(chunk.tag) + \" in pattern: \" + pattern)\n                    tokens.append(TokenTagToken(chunk.tag, ttype, chunk.label))\n                elif chunk.tag[0].islower():\n                    ruleIndex = self.parser.getRuleIndex(chunk.tag)\n                    if ruleIndex==-1:\n                        raise Exception(\"Unknown rule \" + str(chunk.tag) + \" in pattern: \" + pattern)\n                    ruleImaginaryTokenType = self.parser.getATNWithBypassAlts().ruleToTokenType[ruleIndex]\n                    tokens.append(RuleTagToken(chunk.tag, ruleImaginaryTokenType, chunk.label))\n                else:\n                    raise Exception(\"invalid tag: \" + str(chunk.tag) + \" in pattern: \" + pattern)\n            else:\n                self.lexer.setInputStream(InputStream(chunk.text))\n                t = self.lexer.nextToken()\n                while t.type!=Token.EOF:\n                    tokens.append(t)\n                    t = self.lexer.nextToken()\n        return tokens\n\n    # Split {@code <ID> = <e:expr> ;} into 4 chunks for tokenizing by {@link #tokenize}.#\n    def split(self, pattern:str):\n        p = 0\n        n = len(pattern)\n        chunks = list()\n        # find all start and stop indexes first, then collect\n        starts = list()\n        stops = list()\n        while p < n :\n            if p == pattern.find(self.escape + self.start, p):\n                p += len(self.escape) + len(self.start)\n            elif p == pattern.find(self.escape + self.stop, p):\n                p += len(self.escape) + len(self.stop)\n            elif p == pattern.find(self.start, p):\n                starts.append(p)\n                p += len(self.start)\n            elif p == pattern.find(self.stop, p):\n                stops.append(p)\n                p += len(self.stop)\n            else:\n                p += 1\n\n        nt = len(starts)\n\n        if nt > len(stops):\n            raise Exception(\"unterminated tag in pattern: \" + pattern)\n        if nt < len(stops):\n            raise Exception(\"missing start tag in pattern: \" + pattern)\n\n        for i in range(0, nt):\n            if starts[i] >= stops[i]:\n                raise Exception(\"tag delimiters out of order in pattern: \" + pattern)\n\n        # collect into chunks now\n        if nt==0:\n            chunks.append(TextChunk(pattern))\n\n        if nt>0 and starts[0]>0: # copy text up to first tag into chunks\n            text = pattern[0:starts[0]]\n            chunks.add(TextChunk(text))\n\n        for i in range(0, nt):\n            # copy inside of <tag>\n            tag = pattern[starts[i] + len(self.start) : stops[i]]\n            ruleOrToken = tag\n            label = None\n            colon = tag.find(':')\n            if colon >= 0:\n                label = tag[0:colon]\n                ruleOrToken = tag[colon+1 : len(tag)]\n            chunks.append(TagChunk(label, ruleOrToken))\n            if i+1 < len(starts):\n                # copy from end of <tag> to start of next\n                text = pattern[stops[i] + len(self.stop) : starts[i + 1]]\n                chunks.append(TextChunk(text))\n\n        if nt > 0 :\n            afterLastTag = stops[nt - 1] + len(self.stop)\n            if afterLastTag < n : # copy text from end of last tag to end\n                text = pattern[afterLastTag : n]\n                chunks.append(TextChunk(text))\n\n        # strip out the escape sequences from text chunks but not tags\n        for i in range(0, len(chunks)):\n            c = chunks[i]\n            if isinstance( c, TextChunk ):\n                unescaped = c.text.replace(self.escape, \"\")\n                if len(unescaped) < len(c.text):\n                    chunks[i] = TextChunk(unescaped)\n        return chunks\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/RuleTagToken.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# A {@link Token} object representing an entire subtree matched by a parser\n# rule; e.g., {@code <expr>}. These tokens are created for {@link TagChunk}\n# chunks where the tag corresponds to a parser rule.\n#\nfrom ..Token import Token\n\n\nclass RuleTagToken(Token):\n    __slots__ = ('label', 'ruleName')\n    #\n    # Constructs a new instance of {@link RuleTagToken} with the specified rule\n    # name, bypass token type, and label.\n    #\n    # @param ruleName The name of the parser rule this rule tag matches.\n    # @param bypassTokenType The bypass token type assigned to the parser rule.\n    # @param label The label associated with the rule tag, or {@code null} if\n    # the rule tag is unlabeled.\n    #\n    # @exception IllegalArgumentException if {@code ruleName} is {@code null}\n    # or empty.\n\n    def __init__(self, ruleName:str, bypassTokenType:int, label:str=None):\n        if ruleName is None or len(ruleName)==0:\n            raise Exception(\"ruleName cannot be null or empty.\")\n        self.source = None\n        self.type = bypassTokenType # token type of the token\n        self.channel = Token.DEFAULT_CHANNEL # The parser ignores everything not on DEFAULT_CHANNEL\n        self.start = -1 # optional; return -1 if not implemented.\n        self.stop = -1  # optional; return -1 if not implemented.\n        self.tokenIndex = -1 # from 0..n-1 of the token object in the input stream\n        self.line = 0 # line=1..n of the 1st character\n        self.column = -1 # beginning of the line at which it occurs, 0..n-1\n        self.label = label\n        self._text = self.getText() # text of the token.\n\n        self.ruleName = ruleName\n\n\n    def getText(self):\n        if self.label is None:\n            return \"<\" + self.ruleName + \">\"\n        else:\n            return \"<\" + self.label + \":\" + self.ruleName + \">\"\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/TokenTagToken.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# A {@link Token} object representing a token of a particular type; e.g.,\n# {@code <ID>}. These tokens are created for {@link TagChunk} chunks where the\n# tag corresponds to a lexer rule or token type.\n#\nfrom ..Token import CommonToken\n\n\nclass TokenTagToken(CommonToken):\n    __slots__ = ('tokenName', 'label')\n    # Constructs a new instance of {@link TokenTagToken} with the specified\n    # token name, type, and label.\n    #\n    # @param tokenName The token name.\n    # @param type The token type.\n    # @param label The label associated with the token tag, or {@code null} if\n    # the token tag is unlabeled.\n    #\n    def __init__(self, tokenName:str, type:int, label:str=None):\n        super().__init__(type=type)\n        self.tokenName = tokenName\n        self.label = label\n        self._text = self.getText()\n\n    #\n    # {@inheritDoc}\n    #\n    # <p>The implementation for {@link TokenTagToken} returns the token tag\n    # formatted with {@code <} and {@code >} delimiters.</p>\n    #\n    def getText(self):\n        if self.label is None:\n            return \"<\" + self.tokenName + \">\"\n        else:\n            return \"<\" + self.label + \":\" + self.tokenName + \">\"\n\n    # <p>The implementation for {@link TokenTagToken} returns a string of the form\n    # {@code tokenName:type}.</p>\n    #\n    def __str__(self):\n        return self.tokenName + \":\" + str(self.type)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/Tree.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#/\n\n\n# The basic notion of a tree has a parent, a payload, and a list of children.\n#  It is the most abstract interface for all the trees used by ANTLR.\n#/\nfrom ..Token import Token\n\nINVALID_INTERVAL = (-1, -2)\n\nclass Tree(object):\n    pass\n\nclass SyntaxTree(Tree):\n    pass\n\nclass ParseTree(SyntaxTree):\n    pass\n\nclass RuleNode(ParseTree):\n    pass\n\nclass TerminalNode(ParseTree):\n    pass\n\nclass ErrorNode(TerminalNode):\n    pass\n\nclass ParseTreeVisitor(object):\n    def visit(self, tree):\n        return tree.accept(self)\n\n    def visitChildren(self, node):\n        result = self.defaultResult()\n        n = node.getChildCount()\n        for i in range(n):\n            if not self.shouldVisitNextChild(node, result):\n                return result\n\n            c = node.getChild(i)\n            childResult = c.accept(self)\n            result = self.aggregateResult(result, childResult)\n\n        return result\n\n    def visitTerminal(self, node):\n        return self.defaultResult()\n\n    def visitErrorNode(self, node):\n        return self.defaultResult()\n\n    def defaultResult(self):\n        return None\n\n    def aggregateResult(self, aggregate, nextResult):\n        return nextResult\n\n    def shouldVisitNextChild(self, node, currentResult):\n        return True\n\nParserRuleContext = None\n\nclass ParseTreeListener(object):\n\n    def visitTerminal(self, node:TerminalNode):\n        pass\n\n    def visitErrorNode(self, node:ErrorNode):\n        pass\n\n    def enterEveryRule(self, ctx:ParserRuleContext):\n        pass\n\n    def exitEveryRule(self, ctx:ParserRuleContext):\n        pass\n\ndel ParserRuleContext\n\nclass TerminalNodeImpl(TerminalNode):\n    __slots__ = ('parentCtx', 'symbol')\n\n    def __init__(self, symbol:Token):\n        self.parentCtx = None\n        self.symbol = symbol\n    def __setattr__(self, key, value):\n        super().__setattr__(key, value)\n\n    def getChild(self, i:int):\n        return None\n\n    def getSymbol(self):\n        return self.symbol\n\n    def getParent(self):\n        return self.parentCtx\n\n    def getPayload(self):\n        return self.symbol\n\n    def getSourceInterval(self):\n        if self.symbol is None:\n            return INVALID_INTERVAL\n        tokenIndex = self.symbol.tokenIndex\n        return (tokenIndex, tokenIndex)\n\n    def getChildCount(self):\n        return 0\n\n    def accept(self, visitor:ParseTreeVisitor):\n        return visitor.visitTerminal(self)\n\n    def getText(self):\n        return self.symbol.text\n\n    def __str__(self):\n        if self.symbol.type == Token.EOF:\n            return \"<EOF>\"\n        else:\n            return self.symbol.text\n\n# Represents a token that was consumed during resynchronization\n#  rather than during a valid match operation. For example,\n#  we will create this kind of a node during single token insertion\n#  and deletion as well as during \"consume until error recovery set\"\n#  upon no viable alternative exceptions.\n\nclass ErrorNodeImpl(TerminalNodeImpl,ErrorNode):\n\n    def __init__(self, token:Token):\n        super().__init__(token)\n\n    def accept(self, visitor:ParseTreeVisitor):\n        return visitor.visitErrorNode(self)\n\n\nclass ParseTreeWalker(object):\n\n    DEFAULT = None\n\n    def walk(self, listener:ParseTreeListener, t:ParseTree):\n        \"\"\"\n\t    Performs a walk on the given parse tree starting at the root and going down recursively\n\t    with depth-first search. On each node, {@link ParseTreeWalker#enterRule} is called before\n\t    recursively walking down into child nodes, then\n\t    {@link ParseTreeWalker#exitRule} is called after the recursive call to wind up.\n\t    @param listener The listener used by the walker to process grammar rules\n\t    @param t The parse tree to be walked on\n        \"\"\"\n        if isinstance(t, ErrorNode):\n            listener.visitErrorNode(t)\n            return\n        elif isinstance(t, TerminalNode):\n            listener.visitTerminal(t)\n            return\n        self.enterRule(listener, t)\n        for child in t.getChildren():\n            self.walk(listener, child)\n        self.exitRule(listener, t)\n\n    #\n    # The discovery of a rule node, involves sending two events: the generic\n    # {@link ParseTreeListener#enterEveryRule} and a\n    # {@link RuleContext}-specific event. First we trigger the generic and then\n    # the rule specific. We to them in reverse order upon finishing the node.\n    #\n    def enterRule(self, listener:ParseTreeListener, r:RuleNode):\n        \"\"\"\n\t    Enters a grammar rule by first triggering the generic event {@link ParseTreeListener#enterEveryRule}\n\t    then by triggering the event specific to the given parse tree node\n\t    @param listener The listener responding to the trigger events\n\t    @param r The grammar rule containing the rule context\n        \"\"\"\n        ctx = r.getRuleContext()\n        listener.enterEveryRule(ctx)\n        ctx.enterRule(listener)\n\n    def exitRule(self, listener:ParseTreeListener, r:RuleNode):\n        \"\"\"\n\t    Exits a grammar rule by first triggering the event specific to the given parse tree node\n\t    then by triggering the generic event {@link ParseTreeListener#exitEveryRule}\n\t    @param listener The listener responding to the trigger events\n\t    @param r The grammar rule containing the rule context\n        \"\"\"\n        ctx = r.getRuleContext()\n        ctx.exitRule(listener)\n        listener.exitEveryRule(ctx)\n\nParseTreeWalker.DEFAULT = ParseTreeWalker()\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/Trees.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n\n# A set of utility routines useful for all kinds of ANTLR trees.#\nfrom io import StringIO\nfrom ..Token import Token\nfrom ..Utils import escapeWhitespace\nfrom ..tree.Tree import RuleNode, ErrorNode, TerminalNode, Tree, ParseTree\n\n# need forward declaration\nParser  = None\n\nclass Trees(object):\n\n     # Print out a whole tree in LISP form. {@link #getNodeText} is used on the\n    #  node payloads to get the text for the nodes.  Detect\n    #  parse trees and extract data appropriately.\n    @classmethod\n    def toStringTree(cls, t:Tree, ruleNames:list=None, recog:Parser=None):\n        if recog is not None:\n            ruleNames = recog.ruleNames\n        s = escapeWhitespace(cls.getNodeText(t, ruleNames), False)\n        if t.getChildCount()==0:\n            return s\n        with StringIO() as buf:\n            buf.write(\"(\")\n            buf.write(s)\n            buf.write(' ')\n            for i in range(0, t.getChildCount()):\n                if i > 0:\n                    buf.write(' ')\n                buf.write(cls.toStringTree(t.getChild(i), ruleNames))\n            buf.write(\")\")\n            return buf.getvalue()\n\n    @classmethod\n    def getNodeText(cls, t:Tree, ruleNames:list=None, recog:Parser=None):\n        if recog is not None:\n            ruleNames = recog.ruleNames\n        if ruleNames is not None:\n            if isinstance(t, RuleNode):\n                if t.getAltNumber()!=0: # should use ATN.INVALID_ALT_NUMBER but won't compile\n                    return ruleNames[t.getRuleIndex()]+\":\"+str(t.getAltNumber())\n                return ruleNames[t.getRuleIndex()]\n            elif isinstance( t, ErrorNode):\n                return str(t)\n            elif isinstance(t, TerminalNode):\n                if t.symbol is not None:\n                    return t.symbol.text\n        # no recog for rule names\n        payload = t.getPayload()\n        if isinstance(payload, Token ):\n            return payload.text\n        return str(t.getPayload())\n\n\n    # Return ordered list of all children of this node\n    @classmethod\n    def getChildren(cls, t:Tree):\n        return [ t.getChild(i) for i in range(0, t.getChildCount()) ]\n\n    # Return a list of all ancestors of this node.  The first node of\n    #  list is the root and the last is the parent of this node.\n    #\n    @classmethod\n    def getAncestors(cls, t:Tree):\n        ancestors = []\n        t = t.getParent()\n        while t is not None:\n            ancestors.insert(0, t) # insert at start\n            t = t.getParent()\n        return ancestors\n\n    @classmethod\n    def findAllTokenNodes(cls, t:ParseTree, ttype:int):\n        return cls.findAllNodes(t, ttype, True)\n\n    @classmethod\n    def findAllRuleNodes(cls, t:ParseTree, ruleIndex:int):\n        return cls.findAllNodes(t, ruleIndex, False)\n\n    @classmethod\n    def findAllNodes(cls, t:ParseTree, index:int, findTokens:bool):\n        nodes = []\n        cls._findAllNodes(t, index, findTokens, nodes)\n        return nodes\n\n    @classmethod\n    def _findAllNodes(cls, t:ParseTree, index:int, findTokens:bool, nodes:list):\n        from ..ParserRuleContext import ParserRuleContext\n        # check this node (the root) first\n        if findTokens and isinstance(t, TerminalNode):\n            if t.symbol.type==index:\n                nodes.append(t)\n        elif not findTokens and isinstance(t, ParserRuleContext):\n            if t.ruleIndex == index:\n                nodes.append(t)\n        # check children\n        for i in range(0, t.getChildCount()):\n            cls._findAllNodes(t.getChild(i), index, findTokens, nodes)\n\n    @classmethod\n    def descendants(cls, t:ParseTree):\n        nodes = [t]\n        for i in range(0, t.getChildCount()):\n            nodes.extend(cls.descendants(t.getChild(i)))\n        return nodes\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/tree/__init__.py",
    "content": ""
  },
  {
    "path": "runtime/Python3/src/antlr4/xpath/XPath.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\n#\n# Represent a subset of XPath XML path syntax for use in identifying nodes in\n# parse trees.\n#\n# <p>\n# Split path into words and separators {@code /} and {@code //} via ANTLR\n# itself then walk path elements from left to right. At each separator-word\n# pair, find set of nodes. Next stage uses those as work list.</p>\n#\n# <p>\n# The basic interface is\n# {@link XPath#findAll ParseTree.findAll}{@code (tree, pathString, parser)}.\n# But that is just shorthand for:</p>\n#\n# <pre>\n# {@link XPath} p = new {@link XPath#XPath XPath}(parser, pathString);\n# return p.{@link #evaluate evaluate}(tree);\n# </pre>\n#\n# <p>\n# See {@code org.antlr.v4.test.TestXPath} for descriptions. In short, this\n# allows operators:</p>\n#\n# <dl>\n# <dt>/</dt> <dd>root</dd>\n# <dt>//</dt> <dd>anywhere</dd>\n# <dt>!</dt> <dd>invert; this must appear directly after root or anywhere\n# operator</dd>\n# </dl>\n#\n# <p>\n# and path elements:</p>\n#\n# <dl>\n# <dt>ID</dt> <dd>token name</dd>\n# <dt>'string'</dt> <dd>any string literal token from the grammar</dd>\n# <dt>expr</dt> <dd>rule name</dd>\n# <dt>*</dt> <dd>wildcard matching any node</dd>\n# </dl>\n#\n# <p>\n# Whitespace is not allowed.</p>\n#\nfrom ..Lexer import Lexer\nfrom ..CommonTokenStream import CommonTokenStream\nfrom ..ParserRuleContext import ParserRuleContext\nfrom ..tree.Tree import TerminalNode\nfrom ..atn.LexerATNSimulator import LexerATNSimulator\nfrom ..PredictionContext import PredictionContextCache\nfrom ..dfa.DFA import DFA\nfrom ..InputStream import InputStream\nfrom ..Parser import Parser\nfrom ..RuleContext import RuleContext\nfrom ..Token import Token\nfrom ..atn.ATNDeserializer import ATNDeserializer\nfrom ..error.ErrorListener import ErrorListener\nfrom ..error.Errors import LexerNoViableAltException\nfrom ..tree.Tree import ParseTree\nfrom ..tree.Trees import Trees\nfrom io import StringIO\nfrom ..xpath.XPathLexer import XPathLexer\n\n\nclass XPath(object):\n\n    WILDCARD = \"*\" # word not operator/separator\n    NOT = \"!\" # word for invert operator\n\n    def __init__(self, parser:Parser, path:str):\n        self.parser = parser\n        self.path = path\n        self.elements = self.split(path)\n\n    def split(self, path:str):\n        input = InputStream(path)\n        lexer = XPathLexer(input)\n        def recover(self, e):\n            raise e\n        lexer.recover = recover\n        lexer.removeErrorListeners()\n        lexer.addErrorListener(ErrorListener()) # XPathErrorListener does no more\n        tokenStream = CommonTokenStream(lexer)\n        try:\n            tokenStream.fill()\n        except LexerNoViableAltException as e:\n            pos = lexer.column\n            msg = \"Invalid tokens or characters at index %d in path '%s'\" % (pos, path)\n            raise Exception(msg, e)\n\n        tokens = iter(tokenStream.tokens)\n        elements = list()\n        for el in tokens:\n            invert = False\n            anywhere = False\n            # Check for path separators, if none assume root\n            if el.type in [XPathLexer.ROOT, XPathLexer.ANYWHERE]:\n                anywhere = el.type == XPathLexer.ANYWHERE\n                next_el = next(tokens, None)\n                if not next_el:\n                    raise Exception('Missing element after %s' % el.getText())\n                else:\n                    el = next_el\n            # Check for bangs\n            if el.type == XPathLexer.BANG:\n                invert = True\n                next_el = next(tokens, None)\n                if not next_el:\n                    raise Exception('Missing element after %s' % el.getText())\n                else:\n                    el = next_el\n            # Add searched element\n            if el.type in [XPathLexer.TOKEN_REF, XPathLexer.RULE_REF, XPathLexer.WILDCARD, XPathLexer.STRING]:\n                element = self.getXPathElement(el, anywhere)\n                element.invert = invert\n                elements.append(element)\n            elif el.type==Token.EOF:\n                break\n            else:\n                raise Exception(\"Unknown path element %s\" % lexer.symbolicNames[el.type])\n        return elements\n\n    #\n    # Convert word like {@code#} or {@code ID} or {@code expr} to a path\n    # element. {@code anywhere} is {@code true} if {@code //} precedes the\n    # word.\n    #\n    def getXPathElement(self, wordToken:Token, anywhere:bool):\n        if wordToken.type==Token.EOF:\n            raise Exception(\"Missing path element at end of path\")\n\n        word = wordToken.text\n        if wordToken.type==XPathLexer.WILDCARD :\n            return XPathWildcardAnywhereElement() if anywhere else XPathWildcardElement()\n\n        elif wordToken.type in [XPathLexer.TOKEN_REF, XPathLexer.STRING]:\n            tsource = self.parser.getTokenStream().tokenSource\n\n            ttype = Token.INVALID_TYPE\n            if wordToken.type == XPathLexer.TOKEN_REF:\n                if word in tsource.ruleNames:\n                    ttype = tsource.ruleNames.index(word) + 1\n            else:\n                if word in tsource.literalNames:\n                    ttype = tsource.literalNames.index(word)\n\n            if ttype == Token.INVALID_TYPE:\n                raise Exception(\"%s at index %d isn't a valid token name\" % (word, wordToken.tokenIndex))\n            return XPathTokenAnywhereElement(word, ttype) if anywhere else XPathTokenElement(word, ttype)\n\n        else:\n            ruleIndex = self.parser.ruleNames.index(word) if word in self.parser.ruleNames else -1\n\n            if ruleIndex == -1:\n                raise Exception(\"%s at index %d isn't a valid rule name\" % (word, wordToken.tokenIndex))\n            return XPathRuleAnywhereElement(word, ruleIndex) if anywhere else XPathRuleElement(word, ruleIndex)\n\n\n    @staticmethod\n    def findAll(tree:ParseTree, xpath:str, parser:Parser):\n        p = XPath(parser, xpath)\n        return p.evaluate(tree)\n\n    #\n    # Return a list of all nodes starting at {@code t} as root that satisfy the\n    # path. The root {@code /} is relative to the node passed to\n    # {@link #evaluate}.\n    #\n    def evaluate(self, t:ParseTree):\n        dummyRoot = ParserRuleContext()\n        dummyRoot.children = [t] # don't set t's parent.\n\n        work = [dummyRoot]\n        for element in self.elements:\n            work_next = list()\n            for node in work:\n                if not isinstance(node, TerminalNode) and node.children:\n                    # only try to match next element if it has children\n                    # e.g., //func/*/stat might have a token node for which\n                    # we can't go looking for stat nodes.\n                    matching = element.evaluate(node)\n\n                    # See issue antlr#370 - Prevents XPath from returning the\n                    # same node multiple times\n                    matching = filter(lambda m: m not in work_next, matching)\n\n                    work_next.extend(matching)\n            work = work_next\n\n        return work\n\n\nclass XPathElement(object):\n\n    def __init__(self, nodeName:str):\n        self.nodeName = nodeName\n        self.invert = False\n\n    def __str__(self):\n        return type(self).__name__ + \"[\" + (\"!\" if self.invert else \"\") + self.nodeName + \"]\"\n\n\n\n#\n# Either {@code ID} at start of path or {@code ...//ID} in middle of path.\n#\nclass XPathRuleAnywhereElement(XPathElement):\n\n    def __init__(self, ruleName:str, ruleIndex:int):\n        super().__init__(ruleName)\n        self.ruleIndex = ruleIndex\n\n    def evaluate(self, t:ParseTree):\n        # return all ParserRuleContext descendants of t that match ruleIndex (or do not match if inverted)\n        return filter(lambda c: isinstance(c, ParserRuleContext) and (self.invert ^ (c.getRuleIndex() == self.ruleIndex)), Trees.descendants(t))\n\nclass XPathRuleElement(XPathElement):\n\n    def __init__(self, ruleName:str, ruleIndex:int):\n        super().__init__(ruleName)\n        self.ruleIndex = ruleIndex\n\n    def evaluate(self, t:ParseTree):\n        # return all ParserRuleContext children of t that match ruleIndex (or do not match if inverted)\n        return filter(lambda c: isinstance(c, ParserRuleContext) and (self.invert ^ (c.getRuleIndex() == self.ruleIndex)), Trees.getChildren(t))\n\nclass XPathTokenAnywhereElement(XPathElement):\n\n    def __init__(self, ruleName:str, tokenType:int):\n        super().__init__(ruleName)\n        self.tokenType = tokenType\n\n    def evaluate(self, t:ParseTree):\n        # return all TerminalNode descendants of t that match tokenType (or do not match if inverted)\n        return filter(lambda c: isinstance(c, TerminalNode) and (self.invert ^ (c.symbol.type == self.tokenType)), Trees.descendants(t))\n\nclass XPathTokenElement(XPathElement):\n\n    def __init__(self, ruleName:str, tokenType:int):\n        super().__init__(ruleName)\n        self.tokenType = tokenType\n\n    def evaluate(self, t:ParseTree):\n        # return all TerminalNode children of t that match tokenType (or do not match if inverted)\n        return filter(lambda c: isinstance(c, TerminalNode) and (self.invert ^ (c.symbol.type == self.tokenType)), Trees.getChildren(t))\n\n\nclass XPathWildcardAnywhereElement(XPathElement):\n\n    def __init__(self):\n        super().__init__(XPath.WILDCARD)\n\n    def evaluate(self, t:ParseTree):\n        if self.invert:\n            return list() # !* is weird but valid (empty)\n        else:\n            return Trees.descendants(t)\n\n\nclass XPathWildcardElement(XPathElement):\n\n    def __init__(self):\n        super().__init__(XPath.WILDCARD)\n\n\n    def evaluate(self, t:ParseTree):\n        if self.invert:\n            return list() # !* is weird but valid (empty)\n        else:\n            return Trees.getChildren(t)\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/xpath/XPathLexer.g4",
    "content": "lexer grammar XPathLexer;\n\ntokens { TOKEN_REF, RULE_REF }\n\nANYWHERE : '//' ;\nROOT\t : '/' ;\nWILDCARD : '*' ;\nBANG\t : '!' ;\n\nID\t\t\t:\tNameStartChar NameChar*\n\t\t\t\t{\n                char = self.text[0]\n                if char.isupper():\n                    self.type = XPathLexer.TOKEN_REF\n                else:\n                    self.type = XPathLexer.RULE_REF\n\t\t\t\t}\n\t\t\t;\n\nfragment\nNameChar    :   NameStartChar\n            |   '0'..'9'\n            |   '_'\n            |   '\\u00B7'\n            |   '\\u0300'..'\\u036F'\n            |   '\\u203F'..'\\u2040'\n            ;\n\nfragment\nNameStartChar\n            :   'A'..'Z' | 'a'..'z'\n            |   '\\u00C0'..'\\u00D6'\n            |   '\\u00D8'..'\\u00F6'\n            |   '\\u00F8'..'\\u02FF'\n            |   '\\u0370'..'\\u037D'\n            |   '\\u037F'..'\\u1FFF'\n            |   '\\u200C'..'\\u200D'\n            |   '\\u2070'..'\\u218F'\n            |   '\\u2C00'..'\\u2FEF'\n            |   '\\u3001'..'\\uD7FF'\n            |   '\\uF900'..'\\uFDCF'\n            |   '\\uFDF0'..'\\uFFFD'\n            ; // ignores | ['\\u10000-'\\uEFFFF] ;\n\nSTRING : '\\'' .*? '\\'' ;\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/xpath/XPathLexer.py",
    "content": "# Generated from XPathLexer.g4 by ANTLR 4.13.1\nfrom antlr4 import *\nfrom io import StringIO\nimport sys\nif sys.version_info[1] > 5:\n    from typing import TextIO\nelse:\n    from typing.io import TextIO\n\n\ndef serializedATN():\n    return [\n        4,0,8,50,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,\n        6,7,6,2,7,7,7,1,0,1,0,1,0,1,1,1,1,1,2,1,2,1,3,1,3,1,4,1,4,5,4,29,\n        8,4,10,4,12,4,32,9,4,1,4,1,4,1,5,1,5,3,5,38,8,5,1,6,1,6,1,7,1,7,\n        5,7,44,8,7,10,7,12,7,47,9,7,1,7,1,7,1,45,0,8,1,3,3,4,5,5,7,6,9,7,\n        11,0,13,0,15,8,1,0,2,5,0,48,57,95,95,183,183,768,879,8255,8256,13,\n        0,65,90,97,122,192,214,216,246,248,767,880,893,895,8191,8204,8205,\n        8304,8591,11264,12271,12289,55295,63744,64975,65008,65533,50,0,1,\n        1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,1,0,0,0,0,15,1,0,\n        0,0,1,17,1,0,0,0,3,20,1,0,0,0,5,22,1,0,0,0,7,24,1,0,0,0,9,26,1,0,\n        0,0,11,37,1,0,0,0,13,39,1,0,0,0,15,41,1,0,0,0,17,18,5,47,0,0,18,\n        19,5,47,0,0,19,2,1,0,0,0,20,21,5,47,0,0,21,4,1,0,0,0,22,23,5,42,\n        0,0,23,6,1,0,0,0,24,25,5,33,0,0,25,8,1,0,0,0,26,30,3,13,6,0,27,29,\n        3,11,5,0,28,27,1,0,0,0,29,32,1,0,0,0,30,28,1,0,0,0,30,31,1,0,0,0,\n        31,33,1,0,0,0,32,30,1,0,0,0,33,34,6,4,0,0,34,10,1,0,0,0,35,38,3,\n        13,6,0,36,38,7,0,0,0,37,35,1,0,0,0,37,36,1,0,0,0,38,12,1,0,0,0,39,\n        40,7,1,0,0,40,14,1,0,0,0,41,45,5,39,0,0,42,44,9,0,0,0,43,42,1,0,\n        0,0,44,47,1,0,0,0,45,46,1,0,0,0,45,43,1,0,0,0,46,48,1,0,0,0,47,45,\n        1,0,0,0,48,49,5,39,0,0,49,16,1,0,0,0,4,0,30,37,45,1,1,4,0\n    ]\n\nclass XPathLexer(Lexer):\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n    TOKEN_REF = 1\n    RULE_REF = 2\n    ANYWHERE = 3\n    ROOT = 4\n    WILDCARD = 5\n    BANG = 6\n    ID = 7\n    STRING = 8\n\n    channelNames = [ u\"DEFAULT_TOKEN_CHANNEL\", u\"HIDDEN\" ]\n\n    modeNames = [ \"DEFAULT_MODE\" ]\n\n    literalNames = [ \"<INVALID>\",\n            \"'//'\", \"'/'\", \"'*'\", \"'!'\" ]\n\n    symbolicNames = [ \"<INVALID>\",\n            \"TOKEN_REF\", \"RULE_REF\", \"ANYWHERE\", \"ROOT\", \"WILDCARD\", \"BANG\", \n            \"ID\", \"STRING\" ]\n\n    ruleNames = [ \"ANYWHERE\", \"ROOT\", \"WILDCARD\", \"BANG\", \"ID\", \"NameChar\", \n                  \"NameStartChar\", \"STRING\" ]\n\n    grammarFileName = \"XPathLexer.g4\"\n\n    def __init__(self, input=None, output:TextIO = sys.stdout):\n        super().__init__(input, output)\n        self.checkVersion(\"4.13.1\")\n        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())\n        self._actions = None\n        self._predicates = None\n\n\n    def action(self, localctx:RuleContext, ruleIndex:int, actionIndex:int):\n        if self._actions is None:\n            actions = dict()\n            actions[4] = self.ID_action \n            self._actions = actions\n        action = self._actions.get(ruleIndex, None)\n        if action is not None:\n            action(localctx, actionIndex)\n        else:\n            raise Exception(\"No registered action for:\" + str(ruleIndex))\n\n\n    def ID_action(self, localctx:RuleContext , actionIndex:int):\n        if actionIndex == 0:\n\n                            char = self.text[0]\n                            if char.isupper():\n                                self.type = XPathLexer.TOKEN_REF\n                            else:\n                                self.type = XPathLexer.RULE_REF\n            \t\t\t\t\n     \n\n\n"
  },
  {
    "path": "runtime/Python3/src/antlr4/xpath/__init__.py",
    "content": "__author__ = 'ericvergnaud'\n"
  },
  {
    "path": "runtime/Python3/tests/TestFileStream.py",
    "content": "import unittest\nfrom antlr4.FileStream import FileStream\n\n\nclass TestFileStream(unittest.TestCase):\n    def testStream(self):\n        stream = FileStream(__file__)\n        self.assertTrue(stream.size > 0)\n"
  },
  {
    "path": "runtime/Python3/tests/TestInputStream.py",
    "content": "import unittest\nfrom antlr4.Token import Token\nfrom antlr4.InputStream import InputStream\n\n\nclass TestInputStream(unittest.TestCase):\n\n    def testStream(self):\n        stream = InputStream(\"abcde\")\n        self.assertEqual(0, stream.index)\n        self.assertEqual(5, stream.size)\n        self.assertEqual(ord(\"a\"), stream.LA(1))\n        stream.consume()\n        self.assertEqual(1, stream.index)\n        stream.seek(5)\n        self.assertEqual(Token.EOF, stream.LA(1))\n        self.assertEqual(\"bcd\", stream.getText(1, 3))\n        stream.reset()\n        self.assertEqual(0, stream.index)\n"
  },
  {
    "path": "runtime/Python3/tests/TestIntervalSet.py",
    "content": "import unittest\nfrom antlr4.IntervalSet import IntervalSet\n\n\nclass TestIntervalSet(unittest.TestCase):\n    def testEmpty(self):\n        s = IntervalSet()\n        self.assertIsNone(s.intervals)\n        self.assertFalse(30 in s)\n\n    def testOne(self):\n        s = IntervalSet()\n        s.addOne(30)\n        self.assertTrue(30 in s)\n        self.assertFalse(29 in s)\n        self.assertFalse(31 in s)\n\n    def testTwo(self):\n        s = IntervalSet()\n        s.addOne(30)\n        s.addOne(40)\n        self.assertTrue(30 in s)\n        self.assertTrue(40 in s)\n        self.assertFalse(35 in s)\n\n    def testRange(self):\n        s = IntervalSet()\n        s.addRange(range(30,41))\n        self.assertTrue(30 in s)\n        self.assertTrue(40 in s)\n        self.assertTrue(35 in s)\n\n    def testDistinct1(self):\n        s = IntervalSet()\n        s.addRange(range(30,32))\n        s.addRange(range(40,42))\n        self.assertEqual(2,len(s.intervals))\n        self.assertTrue(30 in s)\n        self.assertTrue(40 in s)\n        self.assertFalse(35 in s)\n\n    def testDistinct2(self):\n        s = IntervalSet()\n        s.addRange(range(40,42))\n        s.addRange(range(30,32))\n        self.assertEqual(2,len(s.intervals))\n        self.assertTrue(30 in s)\n        self.assertTrue(40 in s)\n        self.assertFalse(35 in s)\n\n    def testContiguous1(self):\n        s = IntervalSet()\n        s.addRange(range(30,36))\n        s.addRange(range(36,41))\n        self.assertEqual(1,len(s.intervals))\n        self.assertTrue(30 in s)\n        self.assertTrue(40 in s)\n        self.assertTrue(35 in s)\n\n    def testContiguous2(self):\n        s = IntervalSet()\n        s.addRange(range(36,41))\n        s.addRange(range(30,36))\n        self.assertEqual(1,len(s.intervals))\n        self.assertTrue(30 in s)\n        self.assertTrue(40 in s)\n\n    def testOverlapping1(self):\n        s = IntervalSet()\n        s.addRange(range(30,40))\n        s.addRange(range(35,45))\n        self.assertEqual(1,len(s.intervals))\n        self.assertTrue(30 in s)\n        self.assertTrue(44 in s)\n\n    def testOverlapping2(self):\n        s = IntervalSet()\n        s.addRange(range(35,45))\n        s.addRange(range(30,40))\n        self.assertEqual(1,len(s.intervals))\n        self.assertTrue(30 in s)\n        self.assertTrue(44 in s)\n\n    def testOverlapping3(self):\n        s = IntervalSet()\n        s.addRange(range(30,32))\n        s.addRange(range(40,42))\n        s.addRange(range(50,52))\n        s.addRange(range(20,61))\n        self.assertEqual(1,len(s.intervals))\n        self.assertTrue(20 in s)\n        self.assertTrue(60 in s)\n\n    def testComplement(self):\n        s = IntervalSet()\n        s.addRange(range(10,21))\n        c = s.complement(1,100)\n        self.assertTrue(1 in c)\n        self.assertTrue(100 in c)\n        self.assertTrue(10 not in c)\n        self.assertTrue(20 not in c)\n"
  },
  {
    "path": "runtime/Python3/tests/TestRecognizer.py",
    "content": "import unittest\nfrom antlr4.Recognizer import Recognizer\n\n\nclass TestRecognizer(unittest.TestCase):\n    def testVersion(self):\n        major, minor = Recognizer().extractVersion(\"1.2\")\n        self.assertEqual(\"1\", major)\n        self.assertEqual(\"2\", minor)\n        major, minor = Recognizer().extractVersion(\"1.2.3\")\n        self.assertEqual(\"1\", major)\n        self.assertEqual(\"2\", minor)\n        major, minor = Recognizer().extractVersion(\"1.2-snapshot\")\n        self.assertEqual(\"1\", major)\n        self.assertEqual(\"2\", minor)\n"
  },
  {
    "path": "runtime/Python3/tests/TestTokenStreamRewriter.py",
    "content": "# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n\nimport unittest\n\n\nfrom mocks.TestLexer import TestLexer, TestLexer2\nfrom antlr4.TokenStreamRewriter import TokenStreamRewriter\nfrom antlr4.InputStream import InputStream\nfrom antlr4.CommonTokenStream import CommonTokenStream\n\n\nclass TestTokenStreamRewriter(unittest.TestCase):\n    def testInsertBeforeIndexZero(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n        rewriter.insertBeforeIndex(0, '0')\n\n        self.assertEqual(rewriter.getDefaultText(), '0abc')\n\n    def testInsertAfterLastIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n        rewriter.insertAfter(10, 'x')\n\n        self.assertEqual(rewriter.getDefaultText(), 'abcx')\n\n    def test2InsertBeforeAfterMiddleIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(1, 'x')\n        rewriter.insertAfter(1, 'x')\n\n        self.assertEqual(rewriter.getDefaultText(), 'axbxc')\n\n    def testReplaceIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceIndex(0, 'x')\n\n        self.assertEqual(rewriter.getDefaultText(), 'xbc')\n\n    def testReplaceLastIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceIndex(2, 'x')\n\n        self.assertEqual(rewriter.getDefaultText(), 'abx')\n\n    def testReplaceMiddleIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceIndex(1, 'x')\n\n        self.assertEqual(rewriter.getDefaultText(), 'axc')\n\n    def testToStringStartStop(self):\n        input = InputStream('x = 3 * 0;')\n        lexer = TestLexer2(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(4, 8, '0')\n\n        self.assertEqual(rewriter.getDefaultText(), 'x = 0;')\n        self.assertEqual(rewriter.getText('default', 0, 9), 'x = 0;')\n        self.assertEqual(rewriter.getText('default', 4, 8), '0')\n\n    def testToStringStartStop2(self):\n        input = InputStream('x = 3 * 0 + 2 * 0;')\n        lexer = TestLexer2(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        self.assertEqual('x = 3 * 0 + 2 * 0;', rewriter.getDefaultText())\n\n        # replace 3 * 0 with 0\n        rewriter.replaceRange(4, 8, '0')\n        self.assertEqual('x = 0 + 2 * 0;', rewriter.getDefaultText())\n        self.assertEqual('x = 0 + 2 * 0;', rewriter.getText('default', 0, 17))\n        self.assertEqual('0', rewriter.getText('default', 4, 8))\n        self.assertEqual('x = 0', rewriter.getText('default', 0, 8))\n        self.assertEqual('2 * 0', rewriter.getText('default', 12, 16))\n\n        rewriter.insertAfter(17, \"// comment\")\n        self.assertEqual('2 * 0;// comment', rewriter.getText('default', 12, 18))\n\n        self.assertEqual('x = 0', rewriter.getText('default', 0, 8))\n\n    def test2ReplaceMiddleIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceIndex(1, 'x')\n        rewriter.replaceIndex(1, 'y')\n\n        self.assertEqual('ayc', rewriter.getDefaultText())\n\n    def test2ReplaceMiddleIndex1InsertBefore(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(0, \"_\")\n        rewriter.replaceIndex(1, 'x')\n        rewriter.replaceIndex(1, 'y')\n\n        self.assertEqual('_ayc', rewriter.getDefaultText())\n\n    def test2InsertMiddleIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(1, 'x')\n        rewriter.insertBeforeIndex(1, 'y')\n\n        self.assertEqual('ayxbc', rewriter.getDefaultText())\n\n    def testReplaceThenDeleteMiddleIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(0, 2, 'x')\n        rewriter.insertBeforeIndex(1, '0')\n\n        with self.assertRaises(ValueError) as ctx:\n            rewriter.getDefaultText()\n        self.assertEqual(\n            'insert op <InsertBeforeOp@[@1,1:1=\\'b\\',<2>,1:1]:\"0\"> within boundaries of previous <ReplaceOp@[@0,0:0=\\'a\\',<1>,1:0]..[@2,2:2=\\'c\\',<3>,1:2]:\"x\">',\n            str(ctx.exception)\n        )\n\n    def testInsertThenReplaceSameIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(0, '0')\n        rewriter.replaceIndex(0, 'x')\n\n        self.assertEqual('0xbc', rewriter.getDefaultText())\n\n    def test2InsertThenReplaceIndex0(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(0, 'x')\n        rewriter.insertBeforeIndex(0, 'y')\n        rewriter.replaceIndex(0, 'z')\n\n        self.assertEqual('yxzbc', rewriter.getDefaultText())\n\n    def testReplaceThenInsertBeforeLastIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceIndex(2, 'x')\n        rewriter.insertBeforeIndex(2, 'y')\n\n        self.assertEqual('abyx', rewriter.getDefaultText())\n\n    def testReplaceThenInsertAfterLastIndex(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceIndex(2, 'x')\n        rewriter.insertAfter(2, 'y')\n\n        self.assertEqual('abxy', rewriter.getDefaultText())\n\n    def testReplaceRangeThenInsertAtLeftEdge(self):\n        input = InputStream('abcccba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(2, 4, 'x')\n        rewriter.insertBeforeIndex(2, 'y')\n\n        self.assertEqual('abyxba', rewriter.getDefaultText())\n\n    def testReplaceRangeThenInsertAtRightEdge(self):\n        input = InputStream('abcccba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(2, 4, 'x')\n        rewriter.insertBeforeIndex(4, 'y')\n\n        with self.assertRaises(ValueError) as ctx:\n            rewriter.getDefaultText()\n        msg = str(ctx.exception)\n        self.assertEqual(\n            \"insert op <InsertBeforeOp@[@4,4:4='c',<3>,1:4]:\\\"y\\\"> within boundaries of previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"x\\\">\",\n            msg\n        )\n\n    def testReplaceRangeThenInsertAfterRightEdge(self):\n        input = InputStream('abcccba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(2, 4, 'x')\n        rewriter.insertAfter(4, 'y')\n\n        self.assertEqual('abxyba', rewriter.getDefaultText())\n\n    def testReplaceAll(self):\n        input = InputStream('abcccba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(0, 6, 'x')\n\n        self.assertEqual('x', rewriter.getDefaultText())\n\n    def testReplaceSubsetThenFetch(self):\n        input = InputStream('abcccba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(2, 4, 'xyz')\n\n        self.assertEqual('abxyzba', rewriter.getDefaultText())\n\n    def testReplaceThenReplaceSuperset(self):\n        input = InputStream('abcccba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(2, 4, 'xyz')\n        rewriter.replaceRange(3, 5, 'foo')\n\n        with self.assertRaises(ValueError) as ctx:\n            rewriter.getDefaultText()\n        msg = str(ctx.exception)\n        self.assertEqual(\n            \"\"\"replace op boundaries of <ReplaceOp@[@3,3:3='c',<3>,1:3]..[@5,5:5='b',<2>,1:5]:\"foo\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\"xyz\">\"\"\",\n            msg\n        )\n\n    def testReplaceThenReplaceLowerIndexedSuperset(self):\n        input = InputStream('abcccba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(2, 4, 'xyz')\n        rewriter.replaceRange(1, 3, 'foo')\n\n        with self.assertRaises(ValueError) as ctx:\n            rewriter.getDefaultText()\n        msg = str(ctx.exception)\n        self.assertEqual(\n            \"\"\"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@3,3:3='c',<3>,1:3]:\"foo\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\"xyz\">\"\"\",\n            msg\n        )\n\n    def testReplaceSingleMiddleThenOverlappingSuperset(self):\n        input = InputStream('abcba')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceIndex(2, 'xyz')\n        rewriter.replaceRange(0, 3, 'foo')\n\n        self.assertEqual('fooa', rewriter.getDefaultText())\n\n    def testCombineInserts(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(0, 'x')\n        rewriter.insertBeforeIndex(0, 'y')\n\n        self.assertEqual('yxabc', rewriter.getDefaultText())\n\n    def testCombine3Inserts(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(1, 'x')\n        rewriter.insertBeforeIndex(0, 'y')\n        rewriter.insertBeforeIndex(1, 'z')\n\n        self.assertEqual('yazxbc', rewriter.getDefaultText())\n\n    def testCombineInsertOnLeftWithReplace(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(0, 2, 'foo')\n        rewriter.insertBeforeIndex(0, 'z')\n\n        self.assertEqual('zfoo', rewriter.getDefaultText())\n\n    def testCombineInsertOnLeftWithDelete(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.delete('default', 0, 2)\n        rewriter.insertBeforeIndex(0, 'z')\n\n        self.assertEqual('z', rewriter.getDefaultText())\n\n    def testDisjointInserts(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(1, 'x')\n        rewriter.insertBeforeIndex(2, 'y')\n        rewriter.insertBeforeIndex(0, 'z')\n\n        self.assertEqual('zaxbyc', rewriter.getDefaultText())\n\n    def testOverlappingReplace(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(1, 2, 'foo')\n        rewriter.replaceRange(0, 3, 'bar')\n\n        self.assertEqual('bar', rewriter.getDefaultText())\n\n    def testOverlappingReplace2(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(0, 3, 'bar')\n        rewriter.replaceRange(1, 2, 'foo')\n\n        with self.assertRaises(ValueError) as ctx:\n            rewriter.getDefaultText()\n\n        self.assertEqual(\n            \"\"\"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@2,2:2='c',<3>,1:2]:\"foo\"> overlap with previous <ReplaceOp@[@0,0:0='a',<1>,1:0]..[@3,3:2='<EOF>',<-1>,1:3]:\"bar\">\"\"\",\n            str(ctx.exception)\n        )\n\n    def testOverlappingReplace3(self):\n        input = InputStream('abcc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(1, 2, 'foo')\n        rewriter.replaceRange(0, 2, 'bar')\n\n        self.assertEqual('barc', rewriter.getDefaultText())\n\n    def testOverlappingReplace4(self):\n        input = InputStream('abcc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(1, 2, 'foo')\n        rewriter.replaceRange(1, 3, 'bar')\n\n        self.assertEqual('abar', rewriter.getDefaultText())\n\n    def testDropIdenticalReplace(self):\n        input = InputStream('abcc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(1, 2, 'foo')\n        rewriter.replaceRange(1, 2, 'foo')\n\n        self.assertEqual('afooc', rewriter.getDefaultText())\n\n    def testDropPrevCoveredInsert(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(1, 'foo')\n        rewriter.replaceRange(1, 2, 'foo')\n\n        self.assertEqual('afoofoo', rewriter.getDefaultText())\n\n    def testLeaveAloneDisjointInsert(self):\n        input = InputStream('abcc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(1, 'x')\n        rewriter.replaceRange(2, 3, 'foo')\n\n        self.assertEqual('axbfoo', rewriter.getDefaultText())\n\n    def testLeaveAloneDisjointInsert2(self):\n        input = InputStream('abcc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.replaceRange(2, 3, 'foo')\n        rewriter.insertBeforeIndex(1, 'x')\n\n        self.assertEqual('axbfoo', rewriter.getDefaultText())\n\n    def testInsertBeforeTokenThenDeleteThatToken(self):\n        input = InputStream('abc')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(1, 'foo')\n        rewriter.replaceRange(1, 2, 'foo')\n\n        self.assertEqual('afoofoo', rewriter.getDefaultText())\n\n    def testPreservesOrderOfContiguousInserts(self):\n        \"\"\"\n        Test for fix for: https://github.com/antlr/antlr4/issues/550\n        \"\"\"\n        input = InputStream('aa')\n        lexer = TestLexer(input)\n        stream = CommonTokenStream(lexer=lexer)\n        stream.fill()\n        rewriter = TokenStreamRewriter(tokens=stream)\n\n        rewriter.insertBeforeIndex(0, '<b>')\n        rewriter.insertAfter(0, '</b>')\n        rewriter.insertBeforeIndex(1, '<b>')\n        rewriter.insertAfter(1, '</b>')\n\n        self.assertEqual('<b>a</b><b>a</b>', rewriter.getDefaultText())\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "runtime/Python3/tests/__init__.py",
    "content": "__author__ = 'ericvergnaud'\n"
  },
  {
    "path": "runtime/Python3/tests/c.c",
    "content": "void main()\n{\n    int a=0;\n    if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        a++;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n    else if( 3 > 4){\n        ;\n    }\n}"
  },
  {
    "path": "runtime/Python3/tests/ctest.py",
    "content": "#\n# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n# Use of this file is governed by the BSD 3-clause license that\n# can be found in the LICENSE.txt file in the project root.\n#\n\nimport sys\nsys.setrecursionlimit(4000)\nimport antlr4\nfrom parser.cparser import CParser\nfrom parser.clexer import CLexer\nfrom datetime import datetime\nimport cProfile\n\nclass ErrorListener(antlr4.error.ErrorListener.ErrorListener):\n\n    def __init__(self):\n        super(ErrorListener, self).__init__()\n        self.errored_out = False\n\n    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):\n        self.errored_out = True\n\n\ndef sub():\n    # Parse the input file\n    input_stream = antlr4.FileStream(\"c.c\")\n\n    lexer = CLexer(input_stream)\n    token_stream = antlr4.CommonTokenStream(lexer)\n\n    parser = CParser(token_stream)\n\n\n    errors = ErrorListener()\n    parser.addErrorListener(errors)\n    tree = parser.compilationUnit()\n\ndef main():\n    before = datetime.now()\n    sub()\n    after = datetime.now()\n    print(str(after-before))\n    # before = after\n    # sub()\n    # after = datetime.now()\n    # print(str(after-before))\n\nif __name__ == '__main__':\n    cProfile.run(\"main()\", sort='tottime')"
  },
  {
    "path": "runtime/Python3/tests/expr/Expr.g4",
    "content": "// Taken from \"tool-testsuite/test/org/antlr/v4/test/tool/TestXPath.java\"\n// Builds ExprLexer.py and ExprParser.py\n\ngrammar Expr;\nprog:   func+ ;\nfunc:  'def' ID '(' arg (',' arg)* ')' body ;\nbody:  '{' stat+ '}' ;\narg :  ID ;\nstat:   expr ';'                 # printExpr\n    |   ID '=' expr ';'          # assign\n    |   'return' expr ';'        # ret\n    |   ';'                      # blank\n    ;\nexpr:   expr ('*'|'/') expr      # MulDiv\n    |   expr ('+'|'-') expr      # AddSub\n    |   primary                  # prim\n    ;\nprimary\n    :   INT                      # int\n    |   ID                       # id\n    |   '(' expr ')'             # parens\n\t;\nMUL :   '*' ; // assigns token name to '*' used above in grammar\nDIV :   '/' ;\nADD :   '+' ;\nSUB :   '-' ;\nRETURN : 'return' ;\nID  :   [a-zA-Z]+ ;      // match identifiers\nINT :   [0-9]+ ;         // match integers\nNEWLINE:'\\r'? '\\n' -> skip;     // return newlines to parser (is end-statement signal)\nWS  :   [ \\t]+ -> skip ; // toss out whitespace"
  },
  {
    "path": "runtime/Python3/tests/expr/ExprLexer.py",
    "content": "# Generated from Expr.g4 by ANTLR 4.13.1\nfrom antlr4 import *\nfrom io import StringIO\nimport sys\nif sys.version_info[1] > 5:\n    from typing import TextIO\nelse:\n    from typing.io import TextIO\n\n\ndef serializedATN():\n    return [\n        4,0,17,92,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,\n        6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,\n        7,13,2,14,7,14,2,15,7,15,2,16,7,16,1,0,1,0,1,0,1,0,1,1,1,1,1,2,1,\n        2,1,3,1,3,1,4,1,4,1,5,1,5,1,6,1,6,1,7,1,7,1,8,1,8,1,9,1,9,1,10,1,\n        10,1,11,1,11,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,13,4,13,70,8,13,\n        11,13,12,13,71,1,14,4,14,75,8,14,11,14,12,14,76,1,15,3,15,80,8,15,\n        1,15,1,15,1,15,1,15,1,16,4,16,87,8,16,11,16,12,16,88,1,16,1,16,0,\n        0,17,1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,\n        13,27,14,29,15,31,16,33,17,1,0,3,2,0,65,90,97,122,1,0,48,57,2,0,\n        9,9,32,32,95,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,\n        1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,1,0,0,0,0,19,\n        1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27,1,0,0,0,0,29,\n        1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,1,35,1,0,0,0,3,39,1,0,0,0,5,41,\n        1,0,0,0,7,43,1,0,0,0,9,45,1,0,0,0,11,47,1,0,0,0,13,49,1,0,0,0,15,\n        51,1,0,0,0,17,53,1,0,0,0,19,55,1,0,0,0,21,57,1,0,0,0,23,59,1,0,0,\n        0,25,61,1,0,0,0,27,69,1,0,0,0,29,74,1,0,0,0,31,79,1,0,0,0,33,86,\n        1,0,0,0,35,36,5,100,0,0,36,37,5,101,0,0,37,38,5,102,0,0,38,2,1,0,\n        0,0,39,40,5,40,0,0,40,4,1,0,0,0,41,42,5,44,0,0,42,6,1,0,0,0,43,44,\n        5,41,0,0,44,8,1,0,0,0,45,46,5,123,0,0,46,10,1,0,0,0,47,48,5,125,\n        0,0,48,12,1,0,0,0,49,50,5,59,0,0,50,14,1,0,0,0,51,52,5,61,0,0,52,\n        16,1,0,0,0,53,54,5,42,0,0,54,18,1,0,0,0,55,56,5,47,0,0,56,20,1,0,\n        0,0,57,58,5,43,0,0,58,22,1,0,0,0,59,60,5,45,0,0,60,24,1,0,0,0,61,\n        62,5,114,0,0,62,63,5,101,0,0,63,64,5,116,0,0,64,65,5,117,0,0,65,\n        66,5,114,0,0,66,67,5,110,0,0,67,26,1,0,0,0,68,70,7,0,0,0,69,68,1,\n        0,0,0,70,71,1,0,0,0,71,69,1,0,0,0,71,72,1,0,0,0,72,28,1,0,0,0,73,\n        75,7,1,0,0,74,73,1,0,0,0,75,76,1,0,0,0,76,74,1,0,0,0,76,77,1,0,0,\n        0,77,30,1,0,0,0,78,80,5,13,0,0,79,78,1,0,0,0,79,80,1,0,0,0,80,81,\n        1,0,0,0,81,82,5,10,0,0,82,83,1,0,0,0,83,84,6,15,0,0,84,32,1,0,0,\n        0,85,87,7,2,0,0,86,85,1,0,0,0,87,88,1,0,0,0,88,86,1,0,0,0,88,89,\n        1,0,0,0,89,90,1,0,0,0,90,91,6,16,0,0,91,34,1,0,0,0,5,0,71,76,79,\n        88,1,6,0,0\n    ]\n\nclass ExprLexer(Lexer):\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n    T__0 = 1\n    T__1 = 2\n    T__2 = 3\n    T__3 = 4\n    T__4 = 5\n    T__5 = 6\n    T__6 = 7\n    T__7 = 8\n    MUL = 9\n    DIV = 10\n    ADD = 11\n    SUB = 12\n    RETURN = 13\n    ID = 14\n    INT = 15\n    NEWLINE = 16\n    WS = 17\n\n    channelNames = [ u\"DEFAULT_TOKEN_CHANNEL\", u\"HIDDEN\" ]\n\n    modeNames = [ \"DEFAULT_MODE\" ]\n\n    literalNames = [ \"<INVALID>\",\n            \"'def'\", \"'('\", \"','\", \"')'\", \"'{'\", \"'}'\", \"';'\", \"'='\", \"'*'\", \n            \"'/'\", \"'+'\", \"'-'\", \"'return'\" ]\n\n    symbolicNames = [ \"<INVALID>\",\n            \"MUL\", \"DIV\", \"ADD\", \"SUB\", \"RETURN\", \"ID\", \"INT\", \"NEWLINE\", \n            \"WS\" ]\n\n    ruleNames = [ \"T__0\", \"T__1\", \"T__2\", \"T__3\", \"T__4\", \"T__5\", \"T__6\", \n                  \"T__7\", \"MUL\", \"DIV\", \"ADD\", \"SUB\", \"RETURN\", \"ID\", \"INT\", \n                  \"NEWLINE\", \"WS\" ]\n\n    grammarFileName = \"Expr.g4\"\n\n    def __init__(self, input=None, output:TextIO = sys.stdout):\n        super().__init__(input, output)\n        self.checkVersion(\"4.13.1\")\n        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())\n        self._actions = None\n        self._predicates = None\n\n\n"
  },
  {
    "path": "runtime/Python3/tests/expr/ExprParser.py",
    "content": "# Generated from Expr.g4 by ANTLR 4.13.1\n# encoding: utf-8\nfrom antlr4 import *\nfrom io import StringIO\nimport sys\nif sys.version_info[1] > 5:\n\tfrom typing import TextIO\nelse:\n\tfrom typing.io import TextIO\n\ndef serializedATN():\n    return [\n        4,1,17,81,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,\n        6,1,0,4,0,16,8,0,11,0,12,0,17,1,1,1,1,1,1,1,1,1,1,1,1,5,1,26,8,1,\n        10,1,12,1,29,9,1,1,1,1,1,1,1,1,2,1,2,4,2,36,8,2,11,2,12,2,37,1,2,\n        1,2,1,3,1,3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        3,4,57,8,4,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,5,5,68,8,5,10,5,12,\n        5,71,9,5,1,6,1,6,1,6,1,6,1,6,1,6,3,6,79,8,6,1,6,0,1,10,7,0,2,4,6,\n        8,10,12,0,2,1,0,9,10,1,0,11,12,83,0,15,1,0,0,0,2,19,1,0,0,0,4,33,\n        1,0,0,0,6,41,1,0,0,0,8,56,1,0,0,0,10,58,1,0,0,0,12,78,1,0,0,0,14,\n        16,3,2,1,0,15,14,1,0,0,0,16,17,1,0,0,0,17,15,1,0,0,0,17,18,1,0,0,\n        0,18,1,1,0,0,0,19,20,5,1,0,0,20,21,5,14,0,0,21,22,5,2,0,0,22,27,\n        3,6,3,0,23,24,5,3,0,0,24,26,3,6,3,0,25,23,1,0,0,0,26,29,1,0,0,0,\n        27,25,1,0,0,0,27,28,1,0,0,0,28,30,1,0,0,0,29,27,1,0,0,0,30,31,5,\n        4,0,0,31,32,3,4,2,0,32,3,1,0,0,0,33,35,5,5,0,0,34,36,3,8,4,0,35,\n        34,1,0,0,0,36,37,1,0,0,0,37,35,1,0,0,0,37,38,1,0,0,0,38,39,1,0,0,\n        0,39,40,5,6,0,0,40,5,1,0,0,0,41,42,5,14,0,0,42,7,1,0,0,0,43,44,3,\n        10,5,0,44,45,5,7,0,0,45,57,1,0,0,0,46,47,5,14,0,0,47,48,5,8,0,0,\n        48,49,3,10,5,0,49,50,5,7,0,0,50,57,1,0,0,0,51,52,5,13,0,0,52,53,\n        3,10,5,0,53,54,5,7,0,0,54,57,1,0,0,0,55,57,5,7,0,0,56,43,1,0,0,0,\n        56,46,1,0,0,0,56,51,1,0,0,0,56,55,1,0,0,0,57,9,1,0,0,0,58,59,6,5,\n        -1,0,59,60,3,12,6,0,60,69,1,0,0,0,61,62,10,3,0,0,62,63,7,0,0,0,63,\n        68,3,10,5,4,64,65,10,2,0,0,65,66,7,1,0,0,66,68,3,10,5,3,67,61,1,\n        0,0,0,67,64,1,0,0,0,68,71,1,0,0,0,69,67,1,0,0,0,69,70,1,0,0,0,70,\n        11,1,0,0,0,71,69,1,0,0,0,72,79,5,15,0,0,73,79,5,14,0,0,74,75,5,2,\n        0,0,75,76,3,10,5,0,76,77,5,4,0,0,77,79,1,0,0,0,78,72,1,0,0,0,78,\n        73,1,0,0,0,78,74,1,0,0,0,79,13,1,0,0,0,7,17,27,37,56,67,69,78\n    ]\n\nclass ExprParser ( Parser ):\n\n    grammarFileName = \"Expr.g4\"\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n    sharedContextCache = PredictionContextCache()\n\n    literalNames = [ \"<INVALID>\", \"'def'\", \"'('\", \"','\", \"')'\", \"'{'\", \"'}'\", \n                     \"';'\", \"'='\", \"'*'\", \"'/'\", \"'+'\", \"'-'\", \"'return'\" ]\n\n    symbolicNames = [ \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \n                      \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \n                      \"<INVALID>\", \"MUL\", \"DIV\", \"ADD\", \"SUB\", \"RETURN\", \n                      \"ID\", \"INT\", \"NEWLINE\", \"WS\" ]\n\n    RULE_prog = 0\n    RULE_func = 1\n    RULE_body = 2\n    RULE_arg = 3\n    RULE_stat = 4\n    RULE_expr = 5\n    RULE_primary = 6\n\n    ruleNames =  [ \"prog\", \"func\", \"body\", \"arg\", \"stat\", \"expr\", \"primary\" ]\n\n    EOF = Token.EOF\n    T__0=1\n    T__1=2\n    T__2=3\n    T__3=4\n    T__4=5\n    T__5=6\n    T__6=7\n    T__7=8\n    MUL=9\n    DIV=10\n    ADD=11\n    SUB=12\n    RETURN=13\n    ID=14\n    INT=15\n    NEWLINE=16\n    WS=17\n\n    def __init__(self, input:TokenStream, output:TextIO = sys.stdout):\n        super().__init__(input, output)\n        self.checkVersion(\"4.13.1\")\n        self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)\n        self._predicates = None\n\n\n\n\n    class ProgContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def func(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(ExprParser.FuncContext)\n            else:\n                return self.getTypedRuleContext(ExprParser.FuncContext,i)\n\n\n        def getRuleIndex(self):\n            return ExprParser.RULE_prog\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterProg\" ):\n                listener.enterProg(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitProg\" ):\n                listener.exitProg(self)\n\n\n\n\n    def prog(self):\n\n        localctx = ExprParser.ProgContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 0, self.RULE_prog)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 15 \n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while True:\n                self.state = 14\n                self.func()\n                self.state = 17 \n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                if not (_la==1):\n                    break\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class FuncContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def ID(self):\n            return self.getToken(ExprParser.ID, 0)\n\n        def arg(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(ExprParser.ArgContext)\n            else:\n                return self.getTypedRuleContext(ExprParser.ArgContext,i)\n\n\n        def body(self):\n            return self.getTypedRuleContext(ExprParser.BodyContext,0)\n\n\n        def getRuleIndex(self):\n            return ExprParser.RULE_func\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterFunc\" ):\n                listener.enterFunc(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitFunc\" ):\n                listener.exitFunc(self)\n\n\n\n\n    def func(self):\n\n        localctx = ExprParser.FuncContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 2, self.RULE_func)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 19\n            self.match(ExprParser.T__0)\n            self.state = 20\n            self.match(ExprParser.ID)\n            self.state = 21\n            self.match(ExprParser.T__1)\n            self.state = 22\n            self.arg()\n            self.state = 27\n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while _la==3:\n                self.state = 23\n                self.match(ExprParser.T__2)\n                self.state = 24\n                self.arg()\n                self.state = 29\n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n\n            self.state = 30\n            self.match(ExprParser.T__3)\n            self.state = 31\n            self.body()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class BodyContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def stat(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(ExprParser.StatContext)\n            else:\n                return self.getTypedRuleContext(ExprParser.StatContext,i)\n\n\n        def getRuleIndex(self):\n            return ExprParser.RULE_body\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterBody\" ):\n                listener.enterBody(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitBody\" ):\n                listener.exitBody(self)\n\n\n\n\n    def body(self):\n\n        localctx = ExprParser.BodyContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 4, self.RULE_body)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 33\n            self.match(ExprParser.T__4)\n            self.state = 35 \n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while True:\n                self.state = 34\n                self.stat()\n                self.state = 37 \n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & 57476) != 0)):\n                    break\n\n            self.state = 39\n            self.match(ExprParser.T__5)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class ArgContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def ID(self):\n            return self.getToken(ExprParser.ID, 0)\n\n        def getRuleIndex(self):\n            return ExprParser.RULE_arg\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterArg\" ):\n                listener.enterArg(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitArg\" ):\n                listener.exitArg(self)\n\n\n\n\n    def arg(self):\n\n        localctx = ExprParser.ArgContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 6, self.RULE_arg)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 41\n            self.match(ExprParser.ID)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class StatContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return ExprParser.RULE_stat\n\n     \n        def copyFrom(self, ctx:ParserRuleContext):\n            super().copyFrom(ctx)\n\n\n\n    class RetContext(StatContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def RETURN(self):\n            return self.getToken(ExprParser.RETURN, 0)\n        def expr(self):\n            return self.getTypedRuleContext(ExprParser.ExprContext,0)\n\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterRet\" ):\n                listener.enterRet(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitRet\" ):\n                listener.exitRet(self)\n\n\n    class BlankContext(StatContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterBlank\" ):\n                listener.enterBlank(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitBlank\" ):\n                listener.exitBlank(self)\n\n\n    class PrintExprContext(StatContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def expr(self):\n            return self.getTypedRuleContext(ExprParser.ExprContext,0)\n\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterPrintExpr\" ):\n                listener.enterPrintExpr(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitPrintExpr\" ):\n                listener.exitPrintExpr(self)\n\n\n    class AssignContext(StatContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def ID(self):\n            return self.getToken(ExprParser.ID, 0)\n        def expr(self):\n            return self.getTypedRuleContext(ExprParser.ExprContext,0)\n\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAssign\" ):\n                listener.enterAssign(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAssign\" ):\n                listener.exitAssign(self)\n\n\n\n    def stat(self):\n\n        localctx = ExprParser.StatContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 8, self.RULE_stat)\n        try:\n            self.state = 56\n            self._errHandler.sync(self)\n            la_ = self._interp.adaptivePredict(self._input,3,self._ctx)\n            if la_ == 1:\n                localctx = ExprParser.PrintExprContext(self, localctx)\n                self.enterOuterAlt(localctx, 1)\n                self.state = 43\n                self.expr(0)\n                self.state = 44\n                self.match(ExprParser.T__6)\n                pass\n\n            elif la_ == 2:\n                localctx = ExprParser.AssignContext(self, localctx)\n                self.enterOuterAlt(localctx, 2)\n                self.state = 46\n                self.match(ExprParser.ID)\n                self.state = 47\n                self.match(ExprParser.T__7)\n                self.state = 48\n                self.expr(0)\n                self.state = 49\n                self.match(ExprParser.T__6)\n                pass\n\n            elif la_ == 3:\n                localctx = ExprParser.RetContext(self, localctx)\n                self.enterOuterAlt(localctx, 3)\n                self.state = 51\n                self.match(ExprParser.RETURN)\n                self.state = 52\n                self.expr(0)\n                self.state = 53\n                self.match(ExprParser.T__6)\n                pass\n\n            elif la_ == 4:\n                localctx = ExprParser.BlankContext(self, localctx)\n                self.enterOuterAlt(localctx, 4)\n                self.state = 55\n                self.match(ExprParser.T__6)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class ExprContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return ExprParser.RULE_expr\n\n     \n        def copyFrom(self, ctx:ParserRuleContext):\n            super().copyFrom(ctx)\n\n\n    class PrimContext(ExprContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.ExprContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def primary(self):\n            return self.getTypedRuleContext(ExprParser.PrimaryContext,0)\n\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterPrim\" ):\n                listener.enterPrim(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitPrim\" ):\n                listener.exitPrim(self)\n\n\n    class MulDivContext(ExprContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.ExprContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def expr(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(ExprParser.ExprContext)\n            else:\n                return self.getTypedRuleContext(ExprParser.ExprContext,i)\n\n        def MUL(self):\n            return self.getToken(ExprParser.MUL, 0)\n        def DIV(self):\n            return self.getToken(ExprParser.DIV, 0)\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterMulDiv\" ):\n                listener.enterMulDiv(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitMulDiv\" ):\n                listener.exitMulDiv(self)\n\n\n    class AddSubContext(ExprContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.ExprContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def expr(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(ExprParser.ExprContext)\n            else:\n                return self.getTypedRuleContext(ExprParser.ExprContext,i)\n\n        def ADD(self):\n            return self.getToken(ExprParser.ADD, 0)\n        def SUB(self):\n            return self.getToken(ExprParser.SUB, 0)\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAddSub\" ):\n                listener.enterAddSub(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAddSub\" ):\n                listener.exitAddSub(self)\n\n\n\n    def expr(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = ExprParser.ExprContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 10\n        self.enterRecursionRule(localctx, 10, self.RULE_expr, _p)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            localctx = ExprParser.PrimContext(self, localctx)\n            self._ctx = localctx\n            _prevctx = localctx\n\n            self.state = 59\n            self.primary()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 69\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,5,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 67\n                    self._errHandler.sync(self)\n                    la_ = self._interp.adaptivePredict(self._input,4,self._ctx)\n                    if la_ == 1:\n                        localctx = ExprParser.MulDivContext(self, ExprParser.ExprContext(self, _parentctx, _parentState))\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)\n                        self.state = 61\n                        if not self.precpred(self._ctx, 3):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 3)\")\n                        self.state = 62\n                        _la = self._input.LA(1)\n                        if not(_la==9 or _la==10):\n                            self._errHandler.recoverInline(self)\n                        else:\n                            self._errHandler.reportMatch(self)\n                            self.consume()\n                        self.state = 63\n                        self.expr(4)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = ExprParser.AddSubContext(self, ExprParser.ExprContext(self, _parentctx, _parentState))\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)\n                        self.state = 64\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 65\n                        _la = self._input.LA(1)\n                        if not(_la==11 or _la==12):\n                            self._errHandler.recoverInline(self)\n                        else:\n                            self._errHandler.reportMatch(self)\n                            self.consume()\n                        self.state = 66\n                        self.expr(3)\n                        pass\n\n             \n                self.state = 71\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,5,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n\n    class PrimaryContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return ExprParser.RULE_primary\n\n     \n        def copyFrom(self, ctx:ParserRuleContext):\n            super().copyFrom(ctx)\n\n\n\n    class ParensContext(PrimaryContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.PrimaryContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def expr(self):\n            return self.getTypedRuleContext(ExprParser.ExprContext,0)\n\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterParens\" ):\n                listener.enterParens(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitParens\" ):\n                listener.exitParens(self)\n\n\n    class IdContext(PrimaryContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.PrimaryContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def ID(self):\n            return self.getToken(ExprParser.ID, 0)\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterId\" ):\n                listener.enterId(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitId\" ):\n                listener.exitId(self)\n\n\n    class IntContext(PrimaryContext):\n\n        def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.PrimaryContext\n            super().__init__(parser)\n            self.copyFrom(ctx)\n\n        def INT(self):\n            return self.getToken(ExprParser.INT, 0)\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterInt\" ):\n                listener.enterInt(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitInt\" ):\n                listener.exitInt(self)\n\n\n\n    def primary(self):\n\n        localctx = ExprParser.PrimaryContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 12, self.RULE_primary)\n        try:\n            self.state = 78\n            self._errHandler.sync(self)\n            token = self._input.LA(1)\n            if token in [15]:\n                localctx = ExprParser.IntContext(self, localctx)\n                self.enterOuterAlt(localctx, 1)\n                self.state = 72\n                self.match(ExprParser.INT)\n                pass\n            elif token in [14]:\n                localctx = ExprParser.IdContext(self, localctx)\n                self.enterOuterAlt(localctx, 2)\n                self.state = 73\n                self.match(ExprParser.ID)\n                pass\n            elif token in [2]:\n                localctx = ExprParser.ParensContext(self, localctx)\n                self.enterOuterAlt(localctx, 3)\n                self.state = 74\n                self.match(ExprParser.T__1)\n                self.state = 75\n                self.expr(0)\n                self.state = 76\n                self.match(ExprParser.T__3)\n                pass\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n\n    def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):\n        if self._predicates == None:\n            self._predicates = dict()\n        self._predicates[5] = self.expr_sempred\n        pred = self._predicates.get(ruleIndex, None)\n        if pred is None:\n            raise Exception(\"No predicate with index:\" + str(ruleIndex))\n        else:\n            return pred(localctx, predIndex)\n\n    def expr_sempred(self, localctx:ExprContext, predIndex:int):\n            if predIndex == 0:\n                return self.precpred(self._ctx, 3)\n         \n\n            if predIndex == 1:\n                return self.precpred(self._ctx, 2)\n         \n\n\n\n\n"
  },
  {
    "path": "runtime/Python3/tests/mocks/TestLexer.py",
    "content": "# Generated from /Users/lyga/Dropbox/code/python/antlr4-learn/test_grammar/T.g4 by ANTLR 4.5.3\n# encoding: utf-8\nfrom __future__ import print_function\nfrom antlr4 import *\nfrom io import StringIO\n\n\ndef serializedATN():\n    with StringIO() as buf:\n        buf.write(u\"\\3\\u0430\\ud6d1\\u8206\\uad2d\\u4417\\uaef1\\u8d80\\uaadd\\2\")\n        buf.write(u\"\\5\\17\\b\\1\\4\\2\\t\\2\\4\\3\\t\\3\\4\\4\\t\\4\\3\\2\\3\\2\\3\\3\\3\\3\\3\\4\")\n        buf.write(u\"\\3\\4\\2\\2\\5\\3\\3\\5\\4\\7\\5\\3\\2\\2\\16\\2\\3\\3\\2\\2\\2\\2\\5\\3\\2\\2\")\n        buf.write(u\"\\2\\2\\7\\3\\2\\2\\2\\3\\t\\3\\2\\2\\2\\5\\13\\3\\2\\2\\2\\7\\r\\3\\2\\2\\2\\t\")\n        buf.write(u\"\\n\\7c\\2\\2\\n\\4\\3\\2\\2\\2\\13\\f\\7d\\2\\2\\f\\6\\3\\2\\2\\2\\r\\16\\7\")\n        buf.write(u\"e\\2\\2\\16\\b\\3\\2\\2\\2\\3\\2\\2\")\n        return buf.getvalue()\n\n\nclass TestLexer(Lexer):\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [DFA(ds, i) for i, ds in enumerate(atn.decisionToState)]\n\n    A = 1\n    B = 2\n    C = 3\n\n    modeNames = [u\"DEFAULT_MODE\"]\n\n    literalNames = [u\"<INVALID>\",\n                    u\"'a'\", u\"'b'\", u\"'c'\"]\n\n    symbolicNames = [u\"<INVALID>\",\n                     u\"A\", u\"B\", u\"C\"]\n\n    ruleNames = [u\"A\", u\"B\", u\"C\"]\n\n    grammarFileName = u\"T.g4\"\n\n    def __init__(self, input=None):\n        super(TestLexer, self).__init__(input)\n        self.checkVersion(\"4.9\")\n        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())\n        self._actions = None\n        self._predicates = None\n\n\n\ndef serializedATN2():\n    with StringIO() as buf:\n        buf.write(u\"\\3\\u0430\\ud6d1\\u8206\\uad2d\\u4417\\uaef1\\u8d80\\uaadd\\2\")\n        buf.write(u\"\\t(\\b\\1\\4\\2\\t\\2\\4\\3\\t\\3\\4\\4\\t\\4\\4\\5\\t\\5\\4\\6\\t\\6\\4\\7\\t\")\n        buf.write(u\"\\7\\4\\b\\t\\b\\3\\2\\6\\2\\23\\n\\2\\r\\2\\16\\2\\24\\3\\3\\6\\3\\30\\n\\3\")\n        buf.write(u\"\\r\\3\\16\\3\\31\\3\\4\\3\\4\\3\\5\\3\\5\\3\\6\\3\\6\\3\\7\\3\\7\\3\\b\\6\\b\")\n        buf.write(u\"%\\n\\b\\r\\b\\16\\b&\\2\\2\\t\\3\\3\\5\\4\\7\\5\\t\\6\\13\\7\\r\\b\\17\\t\\3\")\n        buf.write(u\"\\2\\2*\\2\\3\\3\\2\\2\\2\\2\\5\\3\\2\\2\\2\\2\\7\\3\\2\\2\\2\\2\\t\\3\\2\\2\\2\")\n        buf.write(u\"\\2\\13\\3\\2\\2\\2\\2\\r\\3\\2\\2\\2\\2\\17\\3\\2\\2\\2\\3\\22\\3\\2\\2\\2\\5\")\n        buf.write(u\"\\27\\3\\2\\2\\2\\7\\33\\3\\2\\2\\2\\t\\35\\3\\2\\2\\2\\13\\37\\3\\2\\2\\2\\r\")\n        buf.write(u\"!\\3\\2\\2\\2\\17$\\3\\2\\2\\2\\21\\23\\4c|\\2\\22\\21\\3\\2\\2\\2\\23\\24\")\n        buf.write(u\"\\3\\2\\2\\2\\24\\22\\3\\2\\2\\2\\24\\25\\3\\2\\2\\2\\25\\4\\3\\2\\2\\2\\26\")\n        buf.write(u\"\\30\\4\\62;\\2\\27\\26\\3\\2\\2\\2\\30\\31\\3\\2\\2\\2\\31\\27\\3\\2\\2\\2\")\n        buf.write(u\"\\31\\32\\3\\2\\2\\2\\32\\6\\3\\2\\2\\2\\33\\34\\7=\\2\\2\\34\\b\\3\\2\\2\\2\")\n        buf.write(u\"\\35\\36\\7?\\2\\2\\36\\n\\3\\2\\2\\2\\37 \\7-\\2\\2 \\f\\3\\2\\2\\2!\\\"\\7\")\n        buf.write(u\",\\2\\2\\\"\\16\\3\\2\\2\\2#%\\7\\\"\\2\\2$#\\3\\2\\2\\2%&\\3\\2\\2\\2&$\\3\")\n        buf.write(u\"\\2\\2\\2&\\'\\3\\2\\2\\2\\'\\20\\3\\2\\2\\2\\6\\2\\24\\31&\\2\")\n        return buf.getvalue()\n\n\nclass TestLexer2(Lexer):\n\n    atn = ATNDeserializer().deserialize(serializedATN2())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n\n    ID = 1\n    INT = 2\n    SEMI = 3\n    ASSIGN = 4\n    PLUS = 5\n    MULT = 6\n    WS = 7\n\n    modeNames = [ u\"DEFAULT_MODE\" ]\n\n    literalNames = [ u\"<INVALID>\",\n            u\"';'\", u\"'='\", u\"'+'\", u\"'*'\" ]\n\n    symbolicNames = [ u\"<INVALID>\",\n            u\"ID\", u\"INT\", u\"SEMI\", u\"ASSIGN\", u\"PLUS\", u\"MULT\", u\"WS\" ]\n\n    ruleNames = [ u\"ID\", u\"INT\", u\"SEMI\", u\"ASSIGN\", u\"PLUS\", u\"MULT\", u\"WS\" ]\n\n    grammarFileName = u\"T2.g4\"\n\n    def __init__(self, input=None):\n        super(TestLexer2, self).__init__(input)\n        self.checkVersion(\"4.9.1\")\n        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())\n        self._actions = None\n        self._predicates = None\n"
  },
  {
    "path": "runtime/Python3/tests/mocks/__init__.py",
    "content": ""
  },
  {
    "path": "runtime/Python3/tests/parser/__init__.py",
    "content": "__author__ = 'ericvergnaud'\n"
  },
  {
    "path": "runtime/Python3/tests/parser/clexer.py",
    "content": "# Generated from C.bnf by ANTLR 4.5.1\nfrom antlr4 import *\nfrom io import StringIO\n\n\ndef serializedATN():\n    with StringIO() as buf:\n        buf.write(\"\\3\\u0430\\ud6d1\\u8206\\uad2d\\u4417\\uaef1\\u8d80\\uaadd\\2s\")\n        buf.write(\"\\u04e7\\b\\1\\4\\2\\t\\2\\4\\3\\t\\3\\4\\4\\t\\4\\4\\5\\t\\5\\4\\6\\t\\6\\4\\7\")\n        buf.write(\"\\t\\7\\4\\b\\t\\b\\4\\t\\t\\t\\4\\n\\t\\n\\4\\13\\t\\13\\4\\f\\t\\f\\4\\r\\t\\r\")\n        buf.write(\"\\4\\16\\t\\16\\4\\17\\t\\17\\4\\20\\t\\20\\4\\21\\t\\21\\4\\22\\t\\22\\4\\23\")\n        buf.write(\"\\t\\23\\4\\24\\t\\24\\4\\25\\t\\25\\4\\26\\t\\26\\4\\27\\t\\27\\4\\30\\t\\30\")\n        buf.write(\"\\4\\31\\t\\31\\4\\32\\t\\32\\4\\33\\t\\33\\4\\34\\t\\34\\4\\35\\t\\35\\4\\36\")\n        buf.write(\"\\t\\36\\4\\37\\t\\37\\4 \\t \\4!\\t!\\4\\\"\\t\\\"\\4#\\t#\\4$\\t$\\4%\\t%\")\n        buf.write(\"\\4&\\t&\\4\\'\\t\\'\\4(\\t(\\4)\\t)\\4*\\t*\\4+\\t+\\4,\\t,\\4-\\t-\\4.\")\n        buf.write(\"\\t.\\4/\\t/\\4\\60\\t\\60\\4\\61\\t\\61\\4\\62\\t\\62\\4\\63\\t\\63\\4\\64\")\n        buf.write(\"\\t\\64\\4\\65\\t\\65\\4\\66\\t\\66\\4\\67\\t\\67\\48\\t8\\49\\t9\\4:\\t:\")\n        buf.write(\"\\4;\\t;\\4<\\t<\\4=\\t=\\4>\\t>\\4?\\t?\\4@\\t@\\4A\\tA\\4B\\tB\\4C\\t\")\n        buf.write(\"C\\4D\\tD\\4E\\tE\\4F\\tF\\4G\\tG\\4H\\tH\\4I\\tI\\4J\\tJ\\4K\\tK\\4L\\t\")\n        buf.write(\"L\\4M\\tM\\4N\\tN\\4O\\tO\\4P\\tP\\4Q\\tQ\\4R\\tR\\4S\\tS\\4T\\tT\\4U\\t\")\n        buf.write(\"U\\4V\\tV\\4W\\tW\\4X\\tX\\4Y\\tY\\4Z\\tZ\\4[\\t[\\4\\\\\\t\\\\\\4]\\t]\\4\")\n        buf.write(\"^\\t^\\4_\\t_\\4`\\t`\\4a\\ta\\4b\\tb\\4c\\tc\\4d\\td\\4e\\te\\4f\\tf\\4\")\n        buf.write(\"g\\tg\\4h\\th\\4i\\ti\\4j\\tj\\4k\\tk\\4l\\tl\\4m\\tm\\4n\\tn\\4o\\to\\4\")\n        buf.write(\"p\\tp\\4q\\tq\\4r\\tr\\4s\\ts\\4t\\tt\\4u\\tu\\4v\\tv\\4w\\tw\\4x\\tx\\4\")\n        buf.write(\"y\\ty\\4z\\tz\\4{\\t{\\4|\\t|\\4}\\t}\\4~\\t~\\4\\177\\t\\177\\4\\u0080\")\n        buf.write(\"\\t\\u0080\\4\\u0081\\t\\u0081\\4\\u0082\\t\\u0082\\4\\u0083\\t\\u0083\")\n        buf.write(\"\\4\\u0084\\t\\u0084\\4\\u0085\\t\\u0085\\4\\u0086\\t\\u0086\\4\\u0087\")\n        buf.write(\"\\t\\u0087\\4\\u0088\\t\\u0088\\4\\u0089\\t\\u0089\\4\\u008a\\t\\u008a\")\n        buf.write(\"\\4\\u008b\\t\\u008b\\4\\u008c\\t\\u008c\\4\\u008d\\t\\u008d\\4\\u008e\")\n        buf.write(\"\\t\\u008e\\4\\u008f\\t\\u008f\\4\\u0090\\t\\u0090\\4\\u0091\\t\\u0091\")\n        buf.write(\"\\4\\u0092\\t\\u0092\\4\\u0093\\t\\u0093\\4\\u0094\\t\\u0094\\4\\u0095\")\n        buf.write(\"\\t\\u0095\\4\\u0096\\t\\u0096\\4\\u0097\\t\\u0097\\4\\u0098\\t\\u0098\")\n        buf.write(\"\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\")\n        buf.write(\"\\2\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\")\n        buf.write(\"\\3\\3\\3\\3\\3\\3\\3\\3\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\")\n        buf.write(\"\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\5\\3\\5\\3\\5\\3\\5\")\n        buf.write(\"\\3\\5\\3\\5\\3\\5\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\7\\3\\7\\3\")\n        buf.write(\"\\7\\3\\7\\3\\7\\3\\7\\3\\7\\3\\7\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\")\n        buf.write(\"\\3\\b\\3\\b\\3\\b\\3\\t\\3\\t\\3\\t\\3\\t\\3\\t\\3\\t\\3\\t\\3\\t\\3\\t\\3\\t\\3\")\n        buf.write(\"\\t\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\13\\3\\13\\3\")\n        buf.write(\"\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\f\\3\\f\\3\")\n        buf.write(\"\\f\\3\\f\\3\\f\\3\\f\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\")\n        buf.write(\"\\3\\r\\3\\r\\3\\r\\3\\r\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\")\n        buf.write(\"\\16\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\")\n        buf.write(\"\\3\\17\\3\\17\\3\\17\\3\\20\\3\\20\\3\\20\\3\\20\\3\\20\\3\\21\\3\\21\\3\\21\")\n        buf.write(\"\\3\\21\\3\\21\\3\\21\\3\\22\\3\\22\\3\\22\\3\\22\\3\\22\\3\\23\\3\\23\\3\\23\")\n        buf.write(\"\\3\\23\\3\\23\\3\\24\\3\\24\\3\\24\\3\\24\\3\\24\\3\\24\\3\\25\\3\\25\\3\\25\")\n        buf.write(\"\\3\\25\\3\\25\\3\\25\\3\\25\\3\\25\\3\\25\\3\\26\\3\\26\\3\\26\\3\\26\\3\\26\")\n        buf.write(\"\\3\\26\\3\\26\\3\\26\\3\\27\\3\\27\\3\\27\\3\\30\\3\\30\\3\\30\\3\\30\\3\\30\")\n        buf.write(\"\\3\\30\\3\\30\\3\\31\\3\\31\\3\\31\\3\\31\\3\\31\\3\\32\\3\\32\\3\\32\\3\\32\")\n        buf.write(\"\\3\\32\\3\\33\\3\\33\\3\\33\\3\\33\\3\\33\\3\\33\\3\\33\\3\\34\\3\\34\\3\\34\")\n        buf.write(\"\\3\\34\\3\\34\\3\\34\\3\\35\\3\\35\\3\\35\\3\\35\\3\\36\\3\\36\\3\\36\\3\\36\")\n        buf.write(\"\\3\\36\\3\\37\\3\\37\\3\\37\\3 \\3 \\3 \\3 \\3 \\3 \\3 \\3!\\3!\\3!\\3!\")\n        buf.write(\"\\3\\\"\\3\\\"\\3\\\"\\3\\\"\\3\\\"\\3#\\3#\\3#\\3#\\3#\\3#\\3#\\3#\\3#\\3$\\3$\")\n        buf.write(\"\\3$\\3$\\3$\\3$\\3$\\3$\\3$\\3%\\3%\\3%\\3%\\3%\\3%\\3%\\3&\\3&\\3&\\3\")\n        buf.write(\"&\\3&\\3&\\3\\'\\3\\'\\3\\'\\3\\'\\3\\'\\3\\'\\3\\'\\3(\\3(\\3(\\3(\\3(\\3(\")\n        buf.write(\"\\3(\\3)\\3)\\3)\\3)\\3)\\3)\\3)\\3*\\3*\\3*\\3*\\3*\\3*\\3*\\3+\\3+\\3\")\n        buf.write(\"+\\3+\\3+\\3+\\3+\\3,\\3,\\3,\\3,\\3,\\3,\\3,\\3,\\3-\\3-\\3-\\3-\\3-\\3\")\n        buf.write(\"-\\3.\\3.\\3.\\3.\\3.\\3.\\3.\\3.\\3.\\3/\\3/\\3/\\3/\\3/\\3\\60\\3\\60\")\n        buf.write(\"\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\61\\3\\61\\3\\61\\3\\61\")\n        buf.write(\"\\3\\61\\3\\61\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\")\n        buf.write(\"\\3\\63\\3\\63\\3\\63\\3\\63\\3\\63\\3\\63\\3\\63\\3\\63\\3\\63\\3\\64\\3\\64\")\n        buf.write(\"\\3\\64\\3\\64\\3\\64\\3\\64\\3\\64\\3\\64\\3\\65\\3\\65\\3\\65\\3\\65\\3\\65\")\n        buf.write(\"\\3\\65\\3\\66\\3\\66\\3\\66\\3\\66\\3\\66\\3\\66\\3\\66\\3\\66\\3\\66\\3\\67\")\n        buf.write(\"\\3\\67\\3\\67\\3\\67\\3\\67\\3\\67\\3\\67\\3\\67\\3\\67\\38\\38\\38\\38\\3\")\n        buf.write(\"8\\38\\38\\38\\38\\38\\38\\39\\39\\39\\39\\39\\39\\39\\39\\39\\39\\3:\\3\")\n        buf.write(\":\\3:\\3:\\3:\\3:\\3:\\3:\\3:\\3:\\3:\\3:\\3:\\3:\\3:\\3;\\3;\\3;\\3;\\3\")\n        buf.write(\";\\3;\\3;\\3;\\3;\\3;\\3;\\3;\\3;\\3;\\3<\\3<\\3=\\3=\\3>\\3>\\3?\\3?\\3\")\n        buf.write(\"@\\3@\\3A\\3A\\3B\\3B\\3C\\3C\\3C\\3D\\3D\\3E\\3E\\3E\\3F\\3F\\3F\\3G\\3\")\n        buf.write(\"G\\3G\\3H\\3H\\3I\\3I\\3I\\3J\\3J\\3K\\3K\\3K\\3L\\3L\\3M\\3M\\3N\\3N\\3\")\n        buf.write(\"O\\3O\\3P\\3P\\3Q\\3Q\\3Q\\3R\\3R\\3R\\3S\\3S\\3T\\3T\\3U\\3U\\3V\\3V\\3\")\n        buf.write(\"W\\3W\\3X\\3X\\3Y\\3Y\\3Z\\3Z\\3[\\3[\\3[\\3\\\\\\3\\\\\\3\\\\\\3]\\3]\\3]\\3\")\n        buf.write(\"^\\3^\\3^\\3_\\3_\\3_\\3`\\3`\\3`\\3`\\3a\\3a\\3a\\3a\\3b\\3b\\3b\\3c\\3\")\n        buf.write(\"c\\3c\\3d\\3d\\3d\\3e\\3e\\3e\\3f\\3f\\3f\\3g\\3g\\3g\\3h\\3h\\3i\\3i\\3\")\n        buf.write(\"i\\3i\\3j\\3j\\3j\\7j\\u0381\\nj\\fj\\16j\\u0384\\13j\\3k\\3k\\5k\\u0388\")\n        buf.write(\"\\nk\\3l\\3l\\3m\\3m\\3n\\3n\\3n\\3n\\3n\\3n\\3n\\3n\\3n\\3n\\5n\\u0398\")\n        buf.write(\"\\nn\\3o\\3o\\3o\\3o\\3o\\3p\\3p\\3p\\5p\\u03a2\\np\\3q\\3q\\5q\\u03a6\")\n        buf.write(\"\\nq\\3q\\3q\\5q\\u03aa\\nq\\3q\\3q\\5q\\u03ae\\nq\\5q\\u03b0\\nq\\3\")\n        buf.write(\"r\\3r\\7r\\u03b4\\nr\\fr\\16r\\u03b7\\13r\\3s\\3s\\7s\\u03bb\\ns\\f\")\n        buf.write(\"s\\16s\\u03be\\13s\\3t\\3t\\6t\\u03c2\\nt\\rt\\16t\\u03c3\\3u\\3u\\3\")\n        buf.write(\"u\\3v\\3v\\3w\\3w\\3x\\3x\\3y\\3y\\5y\\u03d1\\ny\\3y\\3y\\3y\\3y\\3y\\5\")\n        buf.write(\"y\\u03d8\\ny\\3y\\3y\\5y\\u03dc\\ny\\5y\\u03de\\ny\\3z\\3z\\3{\\3{\\3\")\n        buf.write(\"|\\3|\\3|\\3|\\5|\\u03e8\\n|\\3}\\3}\\5}\\u03ec\\n}\\3~\\3~\\5~\\u03f0\")\n        buf.write(\"\\n~\\3~\\5~\\u03f3\\n~\\3~\\3~\\3~\\5~\\u03f8\\n~\\5~\\u03fa\\n~\\3\")\n        buf.write(\"\\177\\3\\177\\3\\177\\3\\177\\5\\177\\u0400\\n\\177\\3\\177\\3\\177\\3\")\n        buf.write(\"\\177\\3\\177\\5\\177\\u0406\\n\\177\\5\\177\\u0408\\n\\177\\3\\u0080\")\n        buf.write(\"\\5\\u0080\\u040b\\n\\u0080\\3\\u0080\\3\\u0080\\3\\u0080\\3\\u0080\")\n        buf.write(\"\\3\\u0080\\5\\u0080\\u0412\\n\\u0080\\3\\u0081\\3\\u0081\\5\\u0081\")\n        buf.write(\"\\u0416\\n\\u0081\\3\\u0081\\3\\u0081\\3\\u0081\\5\\u0081\\u041b\\n\")\n        buf.write(\"\\u0081\\3\\u0081\\5\\u0081\\u041e\\n\\u0081\\3\\u0082\\3\\u0082\\3\")\n        buf.write(\"\\u0083\\6\\u0083\\u0423\\n\\u0083\\r\\u0083\\16\\u0083\\u0424\\3\")\n        buf.write(\"\\u0084\\5\\u0084\\u0428\\n\\u0084\\3\\u0084\\3\\u0084\\3\\u0084\\3\")\n        buf.write(\"\\u0084\\3\\u0084\\5\\u0084\\u042f\\n\\u0084\\3\\u0085\\3\\u0085\\5\")\n        buf.write(\"\\u0085\\u0433\\n\\u0085\\3\\u0085\\3\\u0085\\3\\u0085\\5\\u0085\\u0438\")\n        buf.write(\"\\n\\u0085\\3\\u0085\\5\\u0085\\u043b\\n\\u0085\\3\\u0086\\6\\u0086\")\n        buf.write(\"\\u043e\\n\\u0086\\r\\u0086\\16\\u0086\\u043f\\3\\u0087\\3\\u0087\")\n        buf.write(\"\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\")\n        buf.write(\"\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\")\n        buf.write(\"\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\\3\\u0088\")\n        buf.write(\"\\3\\u0088\\5\\u0088\\u045a\\n\\u0088\\3\\u0089\\6\\u0089\\u045d\\n\")\n        buf.write(\"\\u0089\\r\\u0089\\16\\u0089\\u045e\\3\\u008a\\3\\u008a\\5\\u008a\")\n        buf.write(\"\\u0463\\n\\u008a\\3\\u008b\\3\\u008b\\3\\u008b\\3\\u008b\\5\\u008b\")\n        buf.write(\"\\u0469\\n\\u008b\\3\\u008c\\3\\u008c\\3\\u008c\\3\\u008d\\3\\u008d\")\n        buf.write(\"\\3\\u008d\\3\\u008d\\3\\u008d\\3\\u008d\\3\\u008d\\3\\u008d\\3\\u008d\")\n        buf.write(\"\\3\\u008d\\3\\u008d\\5\\u008d\\u0479\\n\\u008d\\3\\u008e\\3\\u008e\")\n        buf.write(\"\\3\\u008e\\3\\u008e\\6\\u008e\\u047f\\n\\u008e\\r\\u008e\\16\\u008e\")\n        buf.write(\"\\u0480\\3\\u008f\\5\\u008f\\u0484\\n\\u008f\\3\\u008f\\3\\u008f\\5\")\n        buf.write(\"\\u008f\\u0488\\n\\u008f\\3\\u008f\\3\\u008f\\3\\u0090\\3\\u0090\\3\")\n        buf.write(\"\\u0090\\5\\u0090\\u048f\\n\\u0090\\3\\u0091\\6\\u0091\\u0492\\n\\u0091\")\n        buf.write(\"\\r\\u0091\\16\\u0091\\u0493\\3\\u0092\\3\\u0092\\5\\u0092\\u0498\")\n        buf.write(\"\\n\\u0092\\3\\u0093\\3\\u0093\\5\\u0093\\u049c\\n\\u0093\\3\\u0093\")\n        buf.write(\"\\3\\u0093\\5\\u0093\\u04a0\\n\\u0093\\3\\u0093\\3\\u0093\\7\\u0093\")\n        buf.write(\"\\u04a4\\n\\u0093\\f\\u0093\\16\\u0093\\u04a7\\13\\u0093\\3\\u0093\")\n        buf.write(\"\\3\\u0093\\3\\u0094\\3\\u0094\\5\\u0094\\u04ad\\n\\u0094\\3\\u0094\")\n        buf.write(\"\\3\\u0094\\3\\u0094\\3\\u0094\\3\\u0094\\3\\u0094\\3\\u0094\\3\\u0094\")\n        buf.write(\"\\3\\u0094\\7\\u0094\\u04b8\\n\\u0094\\f\\u0094\\16\\u0094\\u04bb\")\n        buf.write(\"\\13\\u0094\\3\\u0094\\3\\u0094\\3\\u0095\\6\\u0095\\u04c0\\n\\u0095\")\n        buf.write(\"\\r\\u0095\\16\\u0095\\u04c1\\3\\u0095\\3\\u0095\\3\\u0096\\3\\u0096\")\n        buf.write(\"\\5\\u0096\\u04c8\\n\\u0096\\3\\u0096\\5\\u0096\\u04cb\\n\\u0096\\3\")\n        buf.write(\"\\u0096\\3\\u0096\\3\\u0097\\3\\u0097\\3\\u0097\\3\\u0097\\7\\u0097\")\n        buf.write(\"\\u04d3\\n\\u0097\\f\\u0097\\16\\u0097\\u04d6\\13\\u0097\\3\\u0097\")\n        buf.write(\"\\3\\u0097\\3\\u0097\\3\\u0097\\3\\u0097\\3\\u0098\\3\\u0098\\3\\u0098\")\n        buf.write(\"\\3\\u0098\\7\\u0098\\u04e1\\n\\u0098\\f\\u0098\\16\\u0098\\u04e4\")\n        buf.write(\"\\13\\u0098\\3\\u0098\\3\\u0098\\3\\u04d4\\2\\u0099\\3\\3\\5\\4\\7\\5\")\n        buf.write(\"\\t\\6\\13\\7\\r\\b\\17\\t\\21\\n\\23\\13\\25\\f\\27\\r\\31\\16\\33\\17\\35\")\n        buf.write(\"\\20\\37\\21!\\22#\\23%\\24\\'\\25)\\26+\\27-\\30/\\31\\61\\32\\63\\33\")\n        buf.write(\"\\65\\34\\67\\359\\36;\\37= ?!A\\\"C#E$G%I&K\\'M(O)Q*S+U,W-Y.[\")\n        buf.write(\"/]\\60_\\61a\\62c\\63e\\64g\\65i\\66k\\67m8o9q:s;u<w=y>{?}@\\177\")\n        buf.write(\"A\\u0081B\\u0083C\\u0085D\\u0087E\\u0089F\\u008bG\\u008dH\\u008f\")\n        buf.write(\"I\\u0091J\\u0093K\\u0095L\\u0097M\\u0099N\\u009bO\\u009dP\\u009f\")\n        buf.write(\"Q\\u00a1R\\u00a3S\\u00a5T\\u00a7U\\u00a9V\\u00abW\\u00adX\\u00af\")\n        buf.write(\"Y\\u00b1Z\\u00b3[\\u00b5\\\\\\u00b7]\\u00b9^\\u00bb_\\u00bd`\\u00bf\")\n        buf.write(\"a\\u00c1b\\u00c3c\\u00c5d\\u00c7e\\u00c9f\\u00cbg\\u00cdh\\u00cf\")\n        buf.write(\"i\\u00d1j\\u00d3k\\u00d5\\2\\u00d7\\2\\u00d9\\2\\u00db\\2\\u00dd\")\n        buf.write(\"\\2\\u00dfl\\u00e1\\2\\u00e3\\2\\u00e5\\2\\u00e7\\2\\u00e9\\2\\u00eb\")\n        buf.write(\"\\2\\u00ed\\2\\u00ef\\2\\u00f1\\2\\u00f3\\2\\u00f5\\2\\u00f7\\2\\u00f9\")\n        buf.write(\"\\2\\u00fb\\2\\u00fd\\2\\u00ff\\2\\u0101\\2\\u0103\\2\\u0105\\2\\u0107\")\n        buf.write(\"\\2\\u0109\\2\\u010b\\2\\u010d\\2\\u010f\\2\\u0111\\2\\u0113\\2\\u0115\")\n        buf.write(\"\\2\\u0117\\2\\u0119\\2\\u011b\\2\\u011dm\\u011f\\2\\u0121\\2\\u0123\")\n        buf.write(\"\\2\\u0125n\\u0127o\\u0129p\\u012bq\\u012dr\\u012fs\\3\\2\\22\\5\")\n        buf.write(\"\\2C\\\\aac|\\3\\2\\62;\\4\\2ZZzz\\3\\2\\63;\\3\\2\\629\\5\\2\\62;CHch\")\n        buf.write(\"\\4\\2WWww\\4\\2NNnn\\4\\2--//\\6\\2HHNNhhnn\\6\\2\\f\\f\\17\\17))^\")\n        buf.write(\"^\\f\\2$$))AA^^cdhhppttvvxx\\5\\2NNWWww\\6\\2\\f\\f\\17\\17$$^^\")\n        buf.write(\"\\4\\2\\f\\f\\17\\17\\4\\2\\13\\13\\\"\\\"\\u0503\\2\\3\\3\\2\\2\\2\\2\\5\\3\\2\")\n        buf.write(\"\\2\\2\\2\\7\\3\\2\\2\\2\\2\\t\\3\\2\\2\\2\\2\\13\\3\\2\\2\\2\\2\\r\\3\\2\\2\\2\")\n        buf.write(\"\\2\\17\\3\\2\\2\\2\\2\\21\\3\\2\\2\\2\\2\\23\\3\\2\\2\\2\\2\\25\\3\\2\\2\\2\\2\")\n        buf.write(\"\\27\\3\\2\\2\\2\\2\\31\\3\\2\\2\\2\\2\\33\\3\\2\\2\\2\\2\\35\\3\\2\\2\\2\\2\\37\")\n        buf.write(\"\\3\\2\\2\\2\\2!\\3\\2\\2\\2\\2#\\3\\2\\2\\2\\2%\\3\\2\\2\\2\\2\\'\\3\\2\\2\\2\")\n        buf.write(\"\\2)\\3\\2\\2\\2\\2+\\3\\2\\2\\2\\2-\\3\\2\\2\\2\\2/\\3\\2\\2\\2\\2\\61\\3\\2\")\n        buf.write(\"\\2\\2\\2\\63\\3\\2\\2\\2\\2\\65\\3\\2\\2\\2\\2\\67\\3\\2\\2\\2\\29\\3\\2\\2\\2\")\n        buf.write(\"\\2;\\3\\2\\2\\2\\2=\\3\\2\\2\\2\\2?\\3\\2\\2\\2\\2A\\3\\2\\2\\2\\2C\\3\\2\\2\")\n        buf.write(\"\\2\\2E\\3\\2\\2\\2\\2G\\3\\2\\2\\2\\2I\\3\\2\\2\\2\\2K\\3\\2\\2\\2\\2M\\3\\2\")\n        buf.write(\"\\2\\2\\2O\\3\\2\\2\\2\\2Q\\3\\2\\2\\2\\2S\\3\\2\\2\\2\\2U\\3\\2\\2\\2\\2W\\3\")\n        buf.write(\"\\2\\2\\2\\2Y\\3\\2\\2\\2\\2[\\3\\2\\2\\2\\2]\\3\\2\\2\\2\\2_\\3\\2\\2\\2\\2a\")\n        buf.write(\"\\3\\2\\2\\2\\2c\\3\\2\\2\\2\\2e\\3\\2\\2\\2\\2g\\3\\2\\2\\2\\2i\\3\\2\\2\\2\\2\")\n        buf.write(\"k\\3\\2\\2\\2\\2m\\3\\2\\2\\2\\2o\\3\\2\\2\\2\\2q\\3\\2\\2\\2\\2s\\3\\2\\2\\2\")\n        buf.write(\"\\2u\\3\\2\\2\\2\\2w\\3\\2\\2\\2\\2y\\3\\2\\2\\2\\2{\\3\\2\\2\\2\\2}\\3\\2\\2\")\n        buf.write(\"\\2\\2\\177\\3\\2\\2\\2\\2\\u0081\\3\\2\\2\\2\\2\\u0083\\3\\2\\2\\2\\2\\u0085\")\n        buf.write(\"\\3\\2\\2\\2\\2\\u0087\\3\\2\\2\\2\\2\\u0089\\3\\2\\2\\2\\2\\u008b\\3\\2\\2\")\n        buf.write(\"\\2\\2\\u008d\\3\\2\\2\\2\\2\\u008f\\3\\2\\2\\2\\2\\u0091\\3\\2\\2\\2\\2\\u0093\")\n        buf.write(\"\\3\\2\\2\\2\\2\\u0095\\3\\2\\2\\2\\2\\u0097\\3\\2\\2\\2\\2\\u0099\\3\\2\\2\")\n        buf.write(\"\\2\\2\\u009b\\3\\2\\2\\2\\2\\u009d\\3\\2\\2\\2\\2\\u009f\\3\\2\\2\\2\\2\\u00a1\")\n        buf.write(\"\\3\\2\\2\\2\\2\\u00a3\\3\\2\\2\\2\\2\\u00a5\\3\\2\\2\\2\\2\\u00a7\\3\\2\\2\")\n        buf.write(\"\\2\\2\\u00a9\\3\\2\\2\\2\\2\\u00ab\\3\\2\\2\\2\\2\\u00ad\\3\\2\\2\\2\\2\\u00af\")\n        buf.write(\"\\3\\2\\2\\2\\2\\u00b1\\3\\2\\2\\2\\2\\u00b3\\3\\2\\2\\2\\2\\u00b5\\3\\2\\2\")\n        buf.write(\"\\2\\2\\u00b7\\3\\2\\2\\2\\2\\u00b9\\3\\2\\2\\2\\2\\u00bb\\3\\2\\2\\2\\2\\u00bd\")\n        buf.write(\"\\3\\2\\2\\2\\2\\u00bf\\3\\2\\2\\2\\2\\u00c1\\3\\2\\2\\2\\2\\u00c3\\3\\2\\2\")\n        buf.write(\"\\2\\2\\u00c5\\3\\2\\2\\2\\2\\u00c7\\3\\2\\2\\2\\2\\u00c9\\3\\2\\2\\2\\2\\u00cb\")\n        buf.write(\"\\3\\2\\2\\2\\2\\u00cd\\3\\2\\2\\2\\2\\u00cf\\3\\2\\2\\2\\2\\u00d1\\3\\2\\2\")\n        buf.write(\"\\2\\2\\u00d3\\3\\2\\2\\2\\2\\u00df\\3\\2\\2\\2\\2\\u011d\\3\\2\\2\\2\\2\\u0125\")\n        buf.write(\"\\3\\2\\2\\2\\2\\u0127\\3\\2\\2\\2\\2\\u0129\\3\\2\\2\\2\\2\\u012b\\3\\2\\2\")\n        buf.write(\"\\2\\2\\u012d\\3\\2\\2\\2\\2\\u012f\\3\\2\\2\\2\\3\\u0131\\3\\2\\2\\2\\5\\u013f\")\n        buf.write(\"\\3\\2\\2\\2\\7\\u0150\\3\\2\\2\\2\\t\\u0163\\3\\2\\2\\2\\13\\u016a\\3\\2\")\n        buf.write(\"\\2\\2\\r\\u0172\\3\\2\\2\\2\\17\\u017a\\3\\2\\2\\2\\21\\u0185\\3\\2\\2\\2\")\n        buf.write(\"\\23\\u0190\\3\\2\\2\\2\\25\\u019a\\3\\2\\2\\2\\27\\u01a5\\3\\2\\2\\2\\31\")\n        buf.write(\"\\u01ab\\3\\2\\2\\2\\33\\u01b9\\3\\2\\2\\2\\35\\u01c1\\3\\2\\2\\2\\37\\u01ce\")\n        buf.write(\"\\3\\2\\2\\2!\\u01d3\\3\\2\\2\\2#\\u01d9\\3\\2\\2\\2%\\u01de\\3\\2\\2\\2\")\n        buf.write(\"\\'\\u01e3\\3\\2\\2\\2)\\u01e9\\3\\2\\2\\2+\\u01f2\\3\\2\\2\\2-\\u01fa\")\n        buf.write(\"\\3\\2\\2\\2/\\u01fd\\3\\2\\2\\2\\61\\u0204\\3\\2\\2\\2\\63\\u0209\\3\\2\")\n        buf.write(\"\\2\\2\\65\\u020e\\3\\2\\2\\2\\67\\u0215\\3\\2\\2\\29\\u021b\\3\\2\\2\\2\")\n        buf.write(\";\\u021f\\3\\2\\2\\2=\\u0224\\3\\2\\2\\2?\\u0227\\3\\2\\2\\2A\\u022e\\3\")\n        buf.write(\"\\2\\2\\2C\\u0232\\3\\2\\2\\2E\\u0237\\3\\2\\2\\2G\\u0240\\3\\2\\2\\2I\\u0249\")\n        buf.write(\"\\3\\2\\2\\2K\\u0250\\3\\2\\2\\2M\\u0256\\3\\2\\2\\2O\\u025d\\3\\2\\2\\2\")\n        buf.write(\"Q\\u0264\\3\\2\\2\\2S\\u026b\\3\\2\\2\\2U\\u0272\\3\\2\\2\\2W\\u0279\\3\")\n        buf.write(\"\\2\\2\\2Y\\u0281\\3\\2\\2\\2[\\u0287\\3\\2\\2\\2]\\u0290\\3\\2\\2\\2_\\u0295\")\n        buf.write(\"\\3\\2\\2\\2a\\u029e\\3\\2\\2\\2c\\u02a4\\3\\2\\2\\2e\\u02ad\\3\\2\\2\\2\")\n        buf.write(\"g\\u02b6\\3\\2\\2\\2i\\u02be\\3\\2\\2\\2k\\u02c4\\3\\2\\2\\2m\\u02cd\\3\")\n        buf.write(\"\\2\\2\\2o\\u02d6\\3\\2\\2\\2q\\u02e1\\3\\2\\2\\2s\\u02eb\\3\\2\\2\\2u\\u02fa\")\n        buf.write(\"\\3\\2\\2\\2w\\u0308\\3\\2\\2\\2y\\u030a\\3\\2\\2\\2{\\u030c\\3\\2\\2\\2\")\n        buf.write(\"}\\u030e\\3\\2\\2\\2\\177\\u0310\\3\\2\\2\\2\\u0081\\u0312\\3\\2\\2\\2\")\n        buf.write(\"\\u0083\\u0314\\3\\2\\2\\2\\u0085\\u0316\\3\\2\\2\\2\\u0087\\u0319\\3\")\n        buf.write(\"\\2\\2\\2\\u0089\\u031b\\3\\2\\2\\2\\u008b\\u031e\\3\\2\\2\\2\\u008d\\u0321\")\n        buf.write(\"\\3\\2\\2\\2\\u008f\\u0324\\3\\2\\2\\2\\u0091\\u0326\\3\\2\\2\\2\\u0093\")\n        buf.write(\"\\u0329\\3\\2\\2\\2\\u0095\\u032b\\3\\2\\2\\2\\u0097\\u032e\\3\\2\\2\\2\")\n        buf.write(\"\\u0099\\u0330\\3\\2\\2\\2\\u009b\\u0332\\3\\2\\2\\2\\u009d\\u0334\\3\")\n        buf.write(\"\\2\\2\\2\\u009f\\u0336\\3\\2\\2\\2\\u00a1\\u0338\\3\\2\\2\\2\\u00a3\\u033b\")\n        buf.write(\"\\3\\2\\2\\2\\u00a5\\u033e\\3\\2\\2\\2\\u00a7\\u0340\\3\\2\\2\\2\\u00a9\")\n        buf.write(\"\\u0342\\3\\2\\2\\2\\u00ab\\u0344\\3\\2\\2\\2\\u00ad\\u0346\\3\\2\\2\\2\")\n        buf.write(\"\\u00af\\u0348\\3\\2\\2\\2\\u00b1\\u034a\\3\\2\\2\\2\\u00b3\\u034c\\3\")\n        buf.write(\"\\2\\2\\2\\u00b5\\u034e\\3\\2\\2\\2\\u00b7\\u0351\\3\\2\\2\\2\\u00b9\\u0354\")\n        buf.write(\"\\3\\2\\2\\2\\u00bb\\u0357\\3\\2\\2\\2\\u00bd\\u035a\\3\\2\\2\\2\\u00bf\")\n        buf.write(\"\\u035d\\3\\2\\2\\2\\u00c1\\u0361\\3\\2\\2\\2\\u00c3\\u0365\\3\\2\\2\\2\")\n        buf.write(\"\\u00c5\\u0368\\3\\2\\2\\2\\u00c7\\u036b\\3\\2\\2\\2\\u00c9\\u036e\\3\")\n        buf.write(\"\\2\\2\\2\\u00cb\\u0371\\3\\2\\2\\2\\u00cd\\u0374\\3\\2\\2\\2\\u00cf\\u0377\")\n        buf.write(\"\\3\\2\\2\\2\\u00d1\\u0379\\3\\2\\2\\2\\u00d3\\u037d\\3\\2\\2\\2\\u00d5\")\n        buf.write(\"\\u0387\\3\\2\\2\\2\\u00d7\\u0389\\3\\2\\2\\2\\u00d9\\u038b\\3\\2\\2\\2\")\n        buf.write(\"\\u00db\\u0397\\3\\2\\2\\2\\u00dd\\u0399\\3\\2\\2\\2\\u00df\\u03a1\\3\")\n        buf.write(\"\\2\\2\\2\\u00e1\\u03af\\3\\2\\2\\2\\u00e3\\u03b1\\3\\2\\2\\2\\u00e5\\u03b8\")\n        buf.write(\"\\3\\2\\2\\2\\u00e7\\u03bf\\3\\2\\2\\2\\u00e9\\u03c5\\3\\2\\2\\2\\u00eb\")\n        buf.write(\"\\u03c8\\3\\2\\2\\2\\u00ed\\u03ca\\3\\2\\2\\2\\u00ef\\u03cc\\3\\2\\2\\2\")\n        buf.write(\"\\u00f1\\u03dd\\3\\2\\2\\2\\u00f3\\u03df\\3\\2\\2\\2\\u00f5\\u03e1\\3\")\n        buf.write(\"\\2\\2\\2\\u00f7\\u03e7\\3\\2\\2\\2\\u00f9\\u03eb\\3\\2\\2\\2\\u00fb\\u03f9\")\n        buf.write(\"\\3\\2\\2\\2\\u00fd\\u0407\\3\\2\\2\\2\\u00ff\\u0411\\3\\2\\2\\2\\u0101\")\n        buf.write(\"\\u041d\\3\\2\\2\\2\\u0103\\u041f\\3\\2\\2\\2\\u0105\\u0422\\3\\2\\2\\2\")\n        buf.write(\"\\u0107\\u042e\\3\\2\\2\\2\\u0109\\u043a\\3\\2\\2\\2\\u010b\\u043d\\3\")\n        buf.write(\"\\2\\2\\2\\u010d\\u0441\\3\\2\\2\\2\\u010f\\u0459\\3\\2\\2\\2\\u0111\\u045c\")\n        buf.write(\"\\3\\2\\2\\2\\u0113\\u0462\\3\\2\\2\\2\\u0115\\u0468\\3\\2\\2\\2\\u0117\")\n        buf.write(\"\\u046a\\3\\2\\2\\2\\u0119\\u0478\\3\\2\\2\\2\\u011b\\u047a\\3\\2\\2\\2\")\n        buf.write(\"\\u011d\\u0483\\3\\2\\2\\2\\u011f\\u048e\\3\\2\\2\\2\\u0121\\u0491\\3\")\n        buf.write(\"\\2\\2\\2\\u0123\\u0497\\3\\2\\2\\2\\u0125\\u0499\\3\\2\\2\\2\\u0127\\u04aa\")\n        buf.write(\"\\3\\2\\2\\2\\u0129\\u04bf\\3\\2\\2\\2\\u012b\\u04ca\\3\\2\\2\\2\\u012d\")\n        buf.write(\"\\u04ce\\3\\2\\2\\2\\u012f\\u04dc\\3\\2\\2\\2\\u0131\\u0132\\7a\\2\\2\")\n        buf.write(\"\\u0132\\u0133\\7a\\2\\2\\u0133\\u0134\\7g\\2\\2\\u0134\\u0135\\7z\")\n        buf.write(\"\\2\\2\\u0135\\u0136\\7v\\2\\2\\u0136\\u0137\\7g\\2\\2\\u0137\\u0138\")\n        buf.write(\"\\7p\\2\\2\\u0138\\u0139\\7u\\2\\2\\u0139\\u013a\\7k\\2\\2\\u013a\\u013b\")\n        buf.write(\"\\7q\\2\\2\\u013b\\u013c\\7p\\2\\2\\u013c\\u013d\\7a\\2\\2\\u013d\\u013e\")\n        buf.write(\"\\7a\\2\\2\\u013e\\4\\3\\2\\2\\2\\u013f\\u0140\\7a\\2\\2\\u0140\\u0141\")\n        buf.write(\"\\7a\\2\\2\\u0141\\u0142\\7d\\2\\2\\u0142\\u0143\\7w\\2\\2\\u0143\\u0144\")\n        buf.write(\"\\7k\\2\\2\\u0144\\u0145\\7n\\2\\2\\u0145\\u0146\\7v\\2\\2\\u0146\\u0147\")\n        buf.write(\"\\7k\\2\\2\\u0147\\u0148\\7p\\2\\2\\u0148\\u0149\\7a\\2\\2\\u0149\\u014a\")\n        buf.write(\"\\7x\\2\\2\\u014a\\u014b\\7c\\2\\2\\u014b\\u014c\\7a\\2\\2\\u014c\\u014d\")\n        buf.write(\"\\7c\\2\\2\\u014d\\u014e\\7t\\2\\2\\u014e\\u014f\\7i\\2\\2\\u014f\\6\")\n        buf.write(\"\\3\\2\\2\\2\\u0150\\u0151\\7a\\2\\2\\u0151\\u0152\\7a\\2\\2\\u0152\\u0153\")\n        buf.write(\"\\7d\\2\\2\\u0153\\u0154\\7w\\2\\2\\u0154\\u0155\\7k\\2\\2\\u0155\\u0156\")\n        buf.write(\"\\7n\\2\\2\\u0156\\u0157\\7v\\2\\2\\u0157\\u0158\\7k\\2\\2\\u0158\\u0159\")\n        buf.write(\"\\7p\\2\\2\\u0159\\u015a\\7a\\2\\2\\u015a\\u015b\\7q\\2\\2\\u015b\\u015c\")\n        buf.write(\"\\7h\\2\\2\\u015c\\u015d\\7h\\2\\2\\u015d\\u015e\\7u\\2\\2\\u015e\\u015f\")\n        buf.write(\"\\7g\\2\\2\\u015f\\u0160\\7v\\2\\2\\u0160\\u0161\\7q\\2\\2\\u0161\\u0162\")\n        buf.write(\"\\7h\\2\\2\\u0162\\b\\3\\2\\2\\2\\u0163\\u0164\\7a\\2\\2\\u0164\\u0165\")\n        buf.write(\"\\7a\\2\\2\\u0165\\u0166\\7o\\2\\2\\u0166\\u0167\\7\\63\\2\\2\\u0167\")\n        buf.write(\"\\u0168\\7\\64\\2\\2\\u0168\\u0169\\7:\\2\\2\\u0169\\n\\3\\2\\2\\2\\u016a\")\n        buf.write(\"\\u016b\\7a\\2\\2\\u016b\\u016c\\7a\\2\\2\\u016c\\u016d\\7o\\2\\2\\u016d\")\n        buf.write(\"\\u016e\\7\\63\\2\\2\\u016e\\u016f\\7\\64\\2\\2\\u016f\\u0170\\7:\\2\")\n        buf.write(\"\\2\\u0170\\u0171\\7f\\2\\2\\u0171\\f\\3\\2\\2\\2\\u0172\\u0173\\7a\\2\")\n        buf.write(\"\\2\\u0173\\u0174\\7a\\2\\2\\u0174\\u0175\\7o\\2\\2\\u0175\\u0176\\7\")\n        buf.write(\"\\63\\2\\2\\u0176\\u0177\\7\\64\\2\\2\\u0177\\u0178\\7:\\2\\2\\u0178\")\n        buf.write(\"\\u0179\\7k\\2\\2\\u0179\\16\\3\\2\\2\\2\\u017a\\u017b\\7a\\2\\2\\u017b\")\n        buf.write(\"\\u017c\\7a\\2\\2\\u017c\\u017d\\7v\\2\\2\\u017d\\u017e\\7{\\2\\2\\u017e\")\n        buf.write(\"\\u017f\\7r\\2\\2\\u017f\\u0180\\7g\\2\\2\\u0180\\u0181\\7q\\2\\2\\u0181\")\n        buf.write(\"\\u0182\\7h\\2\\2\\u0182\\u0183\\7a\\2\\2\\u0183\\u0184\\7a\\2\\2\\u0184\")\n        buf.write(\"\\20\\3\\2\\2\\2\\u0185\\u0186\\7a\\2\\2\\u0186\\u0187\\7a\\2\\2\\u0187\")\n        buf.write(\"\\u0188\\7k\\2\\2\\u0188\\u0189\\7p\\2\\2\\u0189\\u018a\\7n\\2\\2\\u018a\")\n        buf.write(\"\\u018b\\7k\\2\\2\\u018b\\u018c\\7p\\2\\2\\u018c\\u018d\\7g\\2\\2\\u018d\")\n        buf.write(\"\\u018e\\7a\\2\\2\\u018e\\u018f\\7a\\2\\2\\u018f\\22\\3\\2\\2\\2\\u0190\")\n        buf.write(\"\\u0191\\7a\\2\\2\\u0191\\u0192\\7a\\2\\2\\u0192\\u0193\\7u\\2\\2\\u0193\")\n        buf.write(\"\\u0194\\7v\\2\\2\\u0194\\u0195\\7f\\2\\2\\u0195\\u0196\\7e\\2\\2\\u0196\")\n        buf.write(\"\\u0197\\7c\\2\\2\\u0197\\u0198\\7n\\2\\2\\u0198\\u0199\\7n\\2\\2\\u0199\")\n        buf.write(\"\\24\\3\\2\\2\\2\\u019a\\u019b\\7a\\2\\2\\u019b\\u019c\\7a\\2\\2\\u019c\")\n        buf.write(\"\\u019d\\7f\\2\\2\\u019d\\u019e\\7g\\2\\2\\u019e\\u019f\\7e\\2\\2\\u019f\")\n        buf.write(\"\\u01a0\\7n\\2\\2\\u01a0\\u01a1\\7u\\2\\2\\u01a1\\u01a2\\7r\\2\\2\\u01a2\")\n        buf.write(\"\\u01a3\\7g\\2\\2\\u01a3\\u01a4\\7e\\2\\2\\u01a4\\26\\3\\2\\2\\2\\u01a5\")\n        buf.write(\"\\u01a6\\7a\\2\\2\\u01a6\\u01a7\\7a\\2\\2\\u01a7\\u01a8\\7c\\2\\2\\u01a8\")\n        buf.write(\"\\u01a9\\7u\\2\\2\\u01a9\\u01aa\\7o\\2\\2\\u01aa\\30\\3\\2\\2\\2\\u01ab\")\n        buf.write(\"\\u01ac\\7a\\2\\2\\u01ac\\u01ad\\7a\\2\\2\\u01ad\\u01ae\\7c\\2\\2\\u01ae\")\n        buf.write(\"\\u01af\\7v\\2\\2\\u01af\\u01b0\\7v\\2\\2\\u01b0\\u01b1\\7t\\2\\2\\u01b1\")\n        buf.write(\"\\u01b2\\7k\\2\\2\\u01b2\\u01b3\\7d\\2\\2\\u01b3\\u01b4\\7w\\2\\2\\u01b4\")\n        buf.write(\"\\u01b5\\7v\\2\\2\\u01b5\\u01b6\\7g\\2\\2\\u01b6\\u01b7\\7a\\2\\2\\u01b7\")\n        buf.write(\"\\u01b8\\7a\\2\\2\\u01b8\\32\\3\\2\\2\\2\\u01b9\\u01ba\\7a\\2\\2\\u01ba\")\n        buf.write(\"\\u01bb\\7a\\2\\2\\u01bb\\u01bc\\7c\\2\\2\\u01bc\\u01bd\\7u\\2\\2\\u01bd\")\n        buf.write(\"\\u01be\\7o\\2\\2\\u01be\\u01bf\\7a\\2\\2\\u01bf\\u01c0\\7a\\2\\2\\u01c0\")\n        buf.write(\"\\34\\3\\2\\2\\2\\u01c1\\u01c2\\7a\\2\\2\\u01c2\\u01c3\\7a\\2\\2\\u01c3\")\n        buf.write(\"\\u01c4\\7x\\2\\2\\u01c4\\u01c5\\7q\\2\\2\\u01c5\\u01c6\\7n\\2\\2\\u01c6\")\n        buf.write(\"\\u01c7\\7c\\2\\2\\u01c7\\u01c8\\7v\\2\\2\\u01c8\\u01c9\\7k\\2\\2\\u01c9\")\n        buf.write(\"\\u01ca\\7n\\2\\2\\u01ca\\u01cb\\7g\\2\\2\\u01cb\\u01cc\\7a\\2\\2\\u01cc\")\n        buf.write(\"\\u01cd\\7a\\2\\2\\u01cd\\36\\3\\2\\2\\2\\u01ce\\u01cf\\7c\\2\\2\\u01cf\")\n        buf.write(\"\\u01d0\\7w\\2\\2\\u01d0\\u01d1\\7v\\2\\2\\u01d1\\u01d2\\7q\\2\\2\\u01d2\")\n        buf.write(\" \\3\\2\\2\\2\\u01d3\\u01d4\\7d\\2\\2\\u01d4\\u01d5\\7t\\2\\2\\u01d5\")\n        buf.write(\"\\u01d6\\7g\\2\\2\\u01d6\\u01d7\\7c\\2\\2\\u01d7\\u01d8\\7m\\2\\2\\u01d8\")\n        buf.write(\"\\\"\\3\\2\\2\\2\\u01d9\\u01da\\7e\\2\\2\\u01da\\u01db\\7c\\2\\2\\u01db\")\n        buf.write(\"\\u01dc\\7u\\2\\2\\u01dc\\u01dd\\7g\\2\\2\\u01dd$\\3\\2\\2\\2\\u01de\")\n        buf.write(\"\\u01df\\7e\\2\\2\\u01df\\u01e0\\7j\\2\\2\\u01e0\\u01e1\\7c\\2\\2\\u01e1\")\n        buf.write(\"\\u01e2\\7t\\2\\2\\u01e2&\\3\\2\\2\\2\\u01e3\\u01e4\\7e\\2\\2\\u01e4\")\n        buf.write(\"\\u01e5\\7q\\2\\2\\u01e5\\u01e6\\7p\\2\\2\\u01e6\\u01e7\\7u\\2\\2\\u01e7\")\n        buf.write(\"\\u01e8\\7v\\2\\2\\u01e8(\\3\\2\\2\\2\\u01e9\\u01ea\\7e\\2\\2\\u01ea\")\n        buf.write(\"\\u01eb\\7q\\2\\2\\u01eb\\u01ec\\7p\\2\\2\\u01ec\\u01ed\\7v\\2\\2\\u01ed\")\n        buf.write(\"\\u01ee\\7k\\2\\2\\u01ee\\u01ef\\7p\\2\\2\\u01ef\\u01f0\\7w\\2\\2\\u01f0\")\n        buf.write(\"\\u01f1\\7g\\2\\2\\u01f1*\\3\\2\\2\\2\\u01f2\\u01f3\\7f\\2\\2\\u01f3\")\n        buf.write(\"\\u01f4\\7g\\2\\2\\u01f4\\u01f5\\7h\\2\\2\\u01f5\\u01f6\\7c\\2\\2\\u01f6\")\n        buf.write(\"\\u01f7\\7w\\2\\2\\u01f7\\u01f8\\7n\\2\\2\\u01f8\\u01f9\\7v\\2\\2\\u01f9\")\n        buf.write(\",\\3\\2\\2\\2\\u01fa\\u01fb\\7f\\2\\2\\u01fb\\u01fc\\7q\\2\\2\\u01fc\")\n        buf.write(\".\\3\\2\\2\\2\\u01fd\\u01fe\\7f\\2\\2\\u01fe\\u01ff\\7q\\2\\2\\u01ff\")\n        buf.write(\"\\u0200\\7w\\2\\2\\u0200\\u0201\\7d\\2\\2\\u0201\\u0202\\7n\\2\\2\\u0202\")\n        buf.write(\"\\u0203\\7g\\2\\2\\u0203\\60\\3\\2\\2\\2\\u0204\\u0205\\7g\\2\\2\\u0205\")\n        buf.write(\"\\u0206\\7n\\2\\2\\u0206\\u0207\\7u\\2\\2\\u0207\\u0208\\7g\\2\\2\\u0208\")\n        buf.write(\"\\62\\3\\2\\2\\2\\u0209\\u020a\\7g\\2\\2\\u020a\\u020b\\7p\\2\\2\\u020b\")\n        buf.write(\"\\u020c\\7w\\2\\2\\u020c\\u020d\\7o\\2\\2\\u020d\\64\\3\\2\\2\\2\\u020e\")\n        buf.write(\"\\u020f\\7g\\2\\2\\u020f\\u0210\\7z\\2\\2\\u0210\\u0211\\7v\\2\\2\\u0211\")\n        buf.write(\"\\u0212\\7g\\2\\2\\u0212\\u0213\\7t\\2\\2\\u0213\\u0214\\7p\\2\\2\\u0214\")\n        buf.write(\"\\66\\3\\2\\2\\2\\u0215\\u0216\\7h\\2\\2\\u0216\\u0217\\7n\\2\\2\\u0217\")\n        buf.write(\"\\u0218\\7q\\2\\2\\u0218\\u0219\\7c\\2\\2\\u0219\\u021a\\7v\\2\\2\\u021a\")\n        buf.write(\"8\\3\\2\\2\\2\\u021b\\u021c\\7h\\2\\2\\u021c\\u021d\\7q\\2\\2\\u021d\")\n        buf.write(\"\\u021e\\7t\\2\\2\\u021e:\\3\\2\\2\\2\\u021f\\u0220\\7i\\2\\2\\u0220\")\n        buf.write(\"\\u0221\\7q\\2\\2\\u0221\\u0222\\7v\\2\\2\\u0222\\u0223\\7q\\2\\2\\u0223\")\n        buf.write(\"<\\3\\2\\2\\2\\u0224\\u0225\\7k\\2\\2\\u0225\\u0226\\7h\\2\\2\\u0226\")\n        buf.write(\">\\3\\2\\2\\2\\u0227\\u0228\\7k\\2\\2\\u0228\\u0229\\7p\\2\\2\\u0229\")\n        buf.write(\"\\u022a\\7n\\2\\2\\u022a\\u022b\\7k\\2\\2\\u022b\\u022c\\7p\\2\\2\\u022c\")\n        buf.write(\"\\u022d\\7g\\2\\2\\u022d@\\3\\2\\2\\2\\u022e\\u022f\\7k\\2\\2\\u022f\")\n        buf.write(\"\\u0230\\7p\\2\\2\\u0230\\u0231\\7v\\2\\2\\u0231B\\3\\2\\2\\2\\u0232\")\n        buf.write(\"\\u0233\\7n\\2\\2\\u0233\\u0234\\7q\\2\\2\\u0234\\u0235\\7p\\2\\2\\u0235\")\n        buf.write(\"\\u0236\\7i\\2\\2\\u0236D\\3\\2\\2\\2\\u0237\\u0238\\7t\\2\\2\\u0238\")\n        buf.write(\"\\u0239\\7g\\2\\2\\u0239\\u023a\\7i\\2\\2\\u023a\\u023b\\7k\\2\\2\\u023b\")\n        buf.write(\"\\u023c\\7u\\2\\2\\u023c\\u023d\\7v\\2\\2\\u023d\\u023e\\7g\\2\\2\\u023e\")\n        buf.write(\"\\u023f\\7t\\2\\2\\u023fF\\3\\2\\2\\2\\u0240\\u0241\\7t\\2\\2\\u0241\")\n        buf.write(\"\\u0242\\7g\\2\\2\\u0242\\u0243\\7u\\2\\2\\u0243\\u0244\\7v\\2\\2\\u0244\")\n        buf.write(\"\\u0245\\7t\\2\\2\\u0245\\u0246\\7k\\2\\2\\u0246\\u0247\\7e\\2\\2\\u0247\")\n        buf.write(\"\\u0248\\7v\\2\\2\\u0248H\\3\\2\\2\\2\\u0249\\u024a\\7t\\2\\2\\u024a\")\n        buf.write(\"\\u024b\\7g\\2\\2\\u024b\\u024c\\7v\\2\\2\\u024c\\u024d\\7w\\2\\2\\u024d\")\n        buf.write(\"\\u024e\\7t\\2\\2\\u024e\\u024f\\7p\\2\\2\\u024fJ\\3\\2\\2\\2\\u0250\")\n        buf.write(\"\\u0251\\7u\\2\\2\\u0251\\u0252\\7j\\2\\2\\u0252\\u0253\\7q\\2\\2\\u0253\")\n        buf.write(\"\\u0254\\7t\\2\\2\\u0254\\u0255\\7v\\2\\2\\u0255L\\3\\2\\2\\2\\u0256\")\n        buf.write(\"\\u0257\\7u\\2\\2\\u0257\\u0258\\7k\\2\\2\\u0258\\u0259\\7i\\2\\2\\u0259\")\n        buf.write(\"\\u025a\\7p\\2\\2\\u025a\\u025b\\7g\\2\\2\\u025b\\u025c\\7f\\2\\2\\u025c\")\n        buf.write(\"N\\3\\2\\2\\2\\u025d\\u025e\\7u\\2\\2\\u025e\\u025f\\7k\\2\\2\\u025f\")\n        buf.write(\"\\u0260\\7|\\2\\2\\u0260\\u0261\\7g\\2\\2\\u0261\\u0262\\7q\\2\\2\\u0262\")\n        buf.write(\"\\u0263\\7h\\2\\2\\u0263P\\3\\2\\2\\2\\u0264\\u0265\\7u\\2\\2\\u0265\")\n        buf.write(\"\\u0266\\7v\\2\\2\\u0266\\u0267\\7c\\2\\2\\u0267\\u0268\\7v\\2\\2\\u0268\")\n        buf.write(\"\\u0269\\7k\\2\\2\\u0269\\u026a\\7e\\2\\2\\u026aR\\3\\2\\2\\2\\u026b\")\n        buf.write(\"\\u026c\\7u\\2\\2\\u026c\\u026d\\7v\\2\\2\\u026d\\u026e\\7t\\2\\2\\u026e\")\n        buf.write(\"\\u026f\\7w\\2\\2\\u026f\\u0270\\7e\\2\\2\\u0270\\u0271\\7v\\2\\2\\u0271\")\n        buf.write(\"T\\3\\2\\2\\2\\u0272\\u0273\\7u\\2\\2\\u0273\\u0274\\7y\\2\\2\\u0274\")\n        buf.write(\"\\u0275\\7k\\2\\2\\u0275\\u0276\\7v\\2\\2\\u0276\\u0277\\7e\\2\\2\\u0277\")\n        buf.write(\"\\u0278\\7j\\2\\2\\u0278V\\3\\2\\2\\2\\u0279\\u027a\\7v\\2\\2\\u027a\")\n        buf.write(\"\\u027b\\7{\\2\\2\\u027b\\u027c\\7r\\2\\2\\u027c\\u027d\\7g\\2\\2\\u027d\")\n        buf.write(\"\\u027e\\7f\\2\\2\\u027e\\u027f\\7g\\2\\2\\u027f\\u0280\\7h\\2\\2\\u0280\")\n        buf.write(\"X\\3\\2\\2\\2\\u0281\\u0282\\7w\\2\\2\\u0282\\u0283\\7p\\2\\2\\u0283\")\n        buf.write(\"\\u0284\\7k\\2\\2\\u0284\\u0285\\7q\\2\\2\\u0285\\u0286\\7p\\2\\2\\u0286\")\n        buf.write(\"Z\\3\\2\\2\\2\\u0287\\u0288\\7w\\2\\2\\u0288\\u0289\\7p\\2\\2\\u0289\")\n        buf.write(\"\\u028a\\7u\\2\\2\\u028a\\u028b\\7k\\2\\2\\u028b\\u028c\\7i\\2\\2\\u028c\")\n        buf.write(\"\\u028d\\7p\\2\\2\\u028d\\u028e\\7g\\2\\2\\u028e\\u028f\\7f\\2\\2\\u028f\")\n        buf.write(\"\\\\\\3\\2\\2\\2\\u0290\\u0291\\7x\\2\\2\\u0291\\u0292\\7q\\2\\2\\u0292\")\n        buf.write(\"\\u0293\\7k\\2\\2\\u0293\\u0294\\7f\\2\\2\\u0294^\\3\\2\\2\\2\\u0295\")\n        buf.write(\"\\u0296\\7x\\2\\2\\u0296\\u0297\\7q\\2\\2\\u0297\\u0298\\7n\\2\\2\\u0298\")\n        buf.write(\"\\u0299\\7c\\2\\2\\u0299\\u029a\\7v\\2\\2\\u029a\\u029b\\7k\\2\\2\\u029b\")\n        buf.write(\"\\u029c\\7n\\2\\2\\u029c\\u029d\\7g\\2\\2\\u029d`\\3\\2\\2\\2\\u029e\")\n        buf.write(\"\\u029f\\7y\\2\\2\\u029f\\u02a0\\7j\\2\\2\\u02a0\\u02a1\\7k\\2\\2\\u02a1\")\n        buf.write(\"\\u02a2\\7n\\2\\2\\u02a2\\u02a3\\7g\\2\\2\\u02a3b\\3\\2\\2\\2\\u02a4\")\n        buf.write(\"\\u02a5\\7a\\2\\2\\u02a5\\u02a6\\7C\\2\\2\\u02a6\\u02a7\\7n\\2\\2\\u02a7\")\n        buf.write(\"\\u02a8\\7k\\2\\2\\u02a8\\u02a9\\7i\\2\\2\\u02a9\\u02aa\\7p\\2\\2\\u02aa\")\n        buf.write(\"\\u02ab\\7c\\2\\2\\u02ab\\u02ac\\7u\\2\\2\\u02acd\\3\\2\\2\\2\\u02ad\")\n        buf.write(\"\\u02ae\\7a\\2\\2\\u02ae\\u02af\\7C\\2\\2\\u02af\\u02b0\\7n\\2\\2\\u02b0\")\n        buf.write(\"\\u02b1\\7k\\2\\2\\u02b1\\u02b2\\7i\\2\\2\\u02b2\\u02b3\\7p\\2\\2\\u02b3\")\n        buf.write(\"\\u02b4\\7q\\2\\2\\u02b4\\u02b5\\7h\\2\\2\\u02b5f\\3\\2\\2\\2\\u02b6\")\n        buf.write(\"\\u02b7\\7a\\2\\2\\u02b7\\u02b8\\7C\\2\\2\\u02b8\\u02b9\\7v\\2\\2\\u02b9\")\n        buf.write(\"\\u02ba\\7q\\2\\2\\u02ba\\u02bb\\7o\\2\\2\\u02bb\\u02bc\\7k\\2\\2\\u02bc\")\n        buf.write(\"\\u02bd\\7e\\2\\2\\u02bdh\\3\\2\\2\\2\\u02be\\u02bf\\7a\\2\\2\\u02bf\")\n        buf.write(\"\\u02c0\\7D\\2\\2\\u02c0\\u02c1\\7q\\2\\2\\u02c1\\u02c2\\7q\\2\\2\\u02c2\")\n        buf.write(\"\\u02c3\\7n\\2\\2\\u02c3j\\3\\2\\2\\2\\u02c4\\u02c5\\7a\\2\\2\\u02c5\")\n        buf.write(\"\\u02c6\\7E\\2\\2\\u02c6\\u02c7\\7q\\2\\2\\u02c7\\u02c8\\7o\\2\\2\\u02c8\")\n        buf.write(\"\\u02c9\\7r\\2\\2\\u02c9\\u02ca\\7n\\2\\2\\u02ca\\u02cb\\7g\\2\\2\\u02cb\")\n        buf.write(\"\\u02cc\\7z\\2\\2\\u02ccl\\3\\2\\2\\2\\u02cd\\u02ce\\7a\\2\\2\\u02ce\")\n        buf.write(\"\\u02cf\\7I\\2\\2\\u02cf\\u02d0\\7g\\2\\2\\u02d0\\u02d1\\7p\\2\\2\\u02d1\")\n        buf.write(\"\\u02d2\\7g\\2\\2\\u02d2\\u02d3\\7t\\2\\2\\u02d3\\u02d4\\7k\\2\\2\\u02d4\")\n        buf.write(\"\\u02d5\\7e\\2\\2\\u02d5n\\3\\2\\2\\2\\u02d6\\u02d7\\7a\\2\\2\\u02d7\")\n        buf.write(\"\\u02d8\\7K\\2\\2\\u02d8\\u02d9\\7o\\2\\2\\u02d9\\u02da\\7c\\2\\2\\u02da\")\n        buf.write(\"\\u02db\\7i\\2\\2\\u02db\\u02dc\\7k\\2\\2\\u02dc\\u02dd\\7p\\2\\2\\u02dd\")\n        buf.write(\"\\u02de\\7c\\2\\2\\u02de\\u02df\\7t\\2\\2\\u02df\\u02e0\\7{\\2\\2\\u02e0\")\n        buf.write(\"p\\3\\2\\2\\2\\u02e1\\u02e2\\7a\\2\\2\\u02e2\\u02e3\\7P\\2\\2\\u02e3\")\n        buf.write(\"\\u02e4\\7q\\2\\2\\u02e4\\u02e5\\7t\\2\\2\\u02e5\\u02e6\\7g\\2\\2\\u02e6\")\n        buf.write(\"\\u02e7\\7v\\2\\2\\u02e7\\u02e8\\7w\\2\\2\\u02e8\\u02e9\\7t\\2\\2\\u02e9\")\n        buf.write(\"\\u02ea\\7p\\2\\2\\u02ear\\3\\2\\2\\2\\u02eb\\u02ec\\7a\\2\\2\\u02ec\")\n        buf.write(\"\\u02ed\\7U\\2\\2\\u02ed\\u02ee\\7v\\2\\2\\u02ee\\u02ef\\7c\\2\\2\\u02ef\")\n        buf.write(\"\\u02f0\\7v\\2\\2\\u02f0\\u02f1\\7k\\2\\2\\u02f1\\u02f2\\7e\\2\\2\\u02f2\")\n        buf.write(\"\\u02f3\\7a\\2\\2\\u02f3\\u02f4\\7c\\2\\2\\u02f4\\u02f5\\7u\\2\\2\\u02f5\")\n        buf.write(\"\\u02f6\\7u\\2\\2\\u02f6\\u02f7\\7g\\2\\2\\u02f7\\u02f8\\7t\\2\\2\\u02f8\")\n        buf.write(\"\\u02f9\\7v\\2\\2\\u02f9t\\3\\2\\2\\2\\u02fa\\u02fb\\7a\\2\\2\\u02fb\")\n        buf.write(\"\\u02fc\\7V\\2\\2\\u02fc\\u02fd\\7j\\2\\2\\u02fd\\u02fe\\7t\\2\\2\\u02fe\")\n        buf.write(\"\\u02ff\\7g\\2\\2\\u02ff\\u0300\\7c\\2\\2\\u0300\\u0301\\7f\\2\\2\\u0301\")\n        buf.write(\"\\u0302\\7a\\2\\2\\u0302\\u0303\\7n\\2\\2\\u0303\\u0304\\7q\\2\\2\\u0304\")\n        buf.write(\"\\u0305\\7e\\2\\2\\u0305\\u0306\\7c\\2\\2\\u0306\\u0307\\7n\\2\\2\\u0307\")\n        buf.write(\"v\\3\\2\\2\\2\\u0308\\u0309\\7*\\2\\2\\u0309x\\3\\2\\2\\2\\u030a\\u030b\")\n        buf.write(\"\\7+\\2\\2\\u030bz\\3\\2\\2\\2\\u030c\\u030d\\7]\\2\\2\\u030d|\\3\\2\\2\")\n        buf.write(\"\\2\\u030e\\u030f\\7_\\2\\2\\u030f~\\3\\2\\2\\2\\u0310\\u0311\\7}\\2\")\n        buf.write(\"\\2\\u0311\\u0080\\3\\2\\2\\2\\u0312\\u0313\\7\\177\\2\\2\\u0313\\u0082\")\n        buf.write(\"\\3\\2\\2\\2\\u0314\\u0315\\7>\\2\\2\\u0315\\u0084\\3\\2\\2\\2\\u0316\")\n        buf.write(\"\\u0317\\7>\\2\\2\\u0317\\u0318\\7?\\2\\2\\u0318\\u0086\\3\\2\\2\\2\\u0319\")\n        buf.write(\"\\u031a\\7@\\2\\2\\u031a\\u0088\\3\\2\\2\\2\\u031b\\u031c\\7@\\2\\2\\u031c\")\n        buf.write(\"\\u031d\\7?\\2\\2\\u031d\\u008a\\3\\2\\2\\2\\u031e\\u031f\\7>\\2\\2\\u031f\")\n        buf.write(\"\\u0320\\7>\\2\\2\\u0320\\u008c\\3\\2\\2\\2\\u0321\\u0322\\7@\\2\\2\\u0322\")\n        buf.write(\"\\u0323\\7@\\2\\2\\u0323\\u008e\\3\\2\\2\\2\\u0324\\u0325\\7-\\2\\2\\u0325\")\n        buf.write(\"\\u0090\\3\\2\\2\\2\\u0326\\u0327\\7-\\2\\2\\u0327\\u0328\\7-\\2\\2\\u0328\")\n        buf.write(\"\\u0092\\3\\2\\2\\2\\u0329\\u032a\\7/\\2\\2\\u032a\\u0094\\3\\2\\2\\2\")\n        buf.write(\"\\u032b\\u032c\\7/\\2\\2\\u032c\\u032d\\7/\\2\\2\\u032d\\u0096\\3\\2\")\n        buf.write(\"\\2\\2\\u032e\\u032f\\7,\\2\\2\\u032f\\u0098\\3\\2\\2\\2\\u0330\\u0331\")\n        buf.write(\"\\7\\61\\2\\2\\u0331\\u009a\\3\\2\\2\\2\\u0332\\u0333\\7\\'\\2\\2\\u0333\")\n        buf.write(\"\\u009c\\3\\2\\2\\2\\u0334\\u0335\\7(\\2\\2\\u0335\\u009e\\3\\2\\2\\2\")\n        buf.write(\"\\u0336\\u0337\\7~\\2\\2\\u0337\\u00a0\\3\\2\\2\\2\\u0338\\u0339\\7\")\n        buf.write(\"(\\2\\2\\u0339\\u033a\\7(\\2\\2\\u033a\\u00a2\\3\\2\\2\\2\\u033b\\u033c\")\n        buf.write(\"\\7~\\2\\2\\u033c\\u033d\\7~\\2\\2\\u033d\\u00a4\\3\\2\\2\\2\\u033e\\u033f\")\n        buf.write(\"\\7`\\2\\2\\u033f\\u00a6\\3\\2\\2\\2\\u0340\\u0341\\7#\\2\\2\\u0341\\u00a8\")\n        buf.write(\"\\3\\2\\2\\2\\u0342\\u0343\\7\\u0080\\2\\2\\u0343\\u00aa\\3\\2\\2\\2\\u0344\")\n        buf.write(\"\\u0345\\7A\\2\\2\\u0345\\u00ac\\3\\2\\2\\2\\u0346\\u0347\\7<\\2\\2\\u0347\")\n        buf.write(\"\\u00ae\\3\\2\\2\\2\\u0348\\u0349\\7=\\2\\2\\u0349\\u00b0\\3\\2\\2\\2\")\n        buf.write(\"\\u034a\\u034b\\7.\\2\\2\\u034b\\u00b2\\3\\2\\2\\2\\u034c\\u034d\\7\")\n        buf.write(\"?\\2\\2\\u034d\\u00b4\\3\\2\\2\\2\\u034e\\u034f\\7,\\2\\2\\u034f\\u0350\")\n        buf.write(\"\\7?\\2\\2\\u0350\\u00b6\\3\\2\\2\\2\\u0351\\u0352\\7\\61\\2\\2\\u0352\")\n        buf.write(\"\\u0353\\7?\\2\\2\\u0353\\u00b8\\3\\2\\2\\2\\u0354\\u0355\\7\\'\\2\\2\")\n        buf.write(\"\\u0355\\u0356\\7?\\2\\2\\u0356\\u00ba\\3\\2\\2\\2\\u0357\\u0358\\7\")\n        buf.write(\"-\\2\\2\\u0358\\u0359\\7?\\2\\2\\u0359\\u00bc\\3\\2\\2\\2\\u035a\\u035b\")\n        buf.write(\"\\7/\\2\\2\\u035b\\u035c\\7?\\2\\2\\u035c\\u00be\\3\\2\\2\\2\\u035d\\u035e\")\n        buf.write(\"\\7>\\2\\2\\u035e\\u035f\\7>\\2\\2\\u035f\\u0360\\7?\\2\\2\\u0360\\u00c0\")\n        buf.write(\"\\3\\2\\2\\2\\u0361\\u0362\\7@\\2\\2\\u0362\\u0363\\7@\\2\\2\\u0363\\u0364\")\n        buf.write(\"\\7?\\2\\2\\u0364\\u00c2\\3\\2\\2\\2\\u0365\\u0366\\7(\\2\\2\\u0366\\u0367\")\n        buf.write(\"\\7?\\2\\2\\u0367\\u00c4\\3\\2\\2\\2\\u0368\\u0369\\7`\\2\\2\\u0369\\u036a\")\n        buf.write(\"\\7?\\2\\2\\u036a\\u00c6\\3\\2\\2\\2\\u036b\\u036c\\7~\\2\\2\\u036c\\u036d\")\n        buf.write(\"\\7?\\2\\2\\u036d\\u00c8\\3\\2\\2\\2\\u036e\\u036f\\7?\\2\\2\\u036f\\u0370\")\n        buf.write(\"\\7?\\2\\2\\u0370\\u00ca\\3\\2\\2\\2\\u0371\\u0372\\7#\\2\\2\\u0372\\u0373\")\n        buf.write(\"\\7?\\2\\2\\u0373\\u00cc\\3\\2\\2\\2\\u0374\\u0375\\7/\\2\\2\\u0375\\u0376\")\n        buf.write(\"\\7@\\2\\2\\u0376\\u00ce\\3\\2\\2\\2\\u0377\\u0378\\7\\60\\2\\2\\u0378\")\n        buf.write(\"\\u00d0\\3\\2\\2\\2\\u0379\\u037a\\7\\60\\2\\2\\u037a\\u037b\\7\\60\\2\")\n        buf.write(\"\\2\\u037b\\u037c\\7\\60\\2\\2\\u037c\\u00d2\\3\\2\\2\\2\\u037d\\u0382\")\n        buf.write(\"\\5\\u00d5k\\2\\u037e\\u0381\\5\\u00d5k\\2\\u037f\\u0381\\5\\u00d9\")\n        buf.write(\"m\\2\\u0380\\u037e\\3\\2\\2\\2\\u0380\\u037f\\3\\2\\2\\2\\u0381\\u0384\")\n        buf.write(\"\\3\\2\\2\\2\\u0382\\u0380\\3\\2\\2\\2\\u0382\\u0383\\3\\2\\2\\2\\u0383\")\n        buf.write(\"\\u00d4\\3\\2\\2\\2\\u0384\\u0382\\3\\2\\2\\2\\u0385\\u0388\\5\\u00d7\")\n        buf.write(\"l\\2\\u0386\\u0388\\5\\u00dbn\\2\\u0387\\u0385\\3\\2\\2\\2\\u0387\\u0386\")\n        buf.write(\"\\3\\2\\2\\2\\u0388\\u00d6\\3\\2\\2\\2\\u0389\\u038a\\t\\2\\2\\2\\u038a\")\n        buf.write(\"\\u00d8\\3\\2\\2\\2\\u038b\\u038c\\t\\3\\2\\2\\u038c\\u00da\\3\\2\\2\\2\")\n        buf.write(\"\\u038d\\u038e\\7^\\2\\2\\u038e\\u038f\\7w\\2\\2\\u038f\\u0390\\3\\2\")\n        buf.write(\"\\2\\2\\u0390\\u0398\\5\\u00ddo\\2\\u0391\\u0392\\7^\\2\\2\\u0392\\u0393\")\n        buf.write(\"\\7W\\2\\2\\u0393\\u0394\\3\\2\\2\\2\\u0394\\u0395\\5\\u00ddo\\2\\u0395\")\n        buf.write(\"\\u0396\\5\\u00ddo\\2\\u0396\\u0398\\3\\2\\2\\2\\u0397\\u038d\\3\\2\")\n        buf.write(\"\\2\\2\\u0397\\u0391\\3\\2\\2\\2\\u0398\\u00dc\\3\\2\\2\\2\\u0399\\u039a\")\n        buf.write(\"\\5\\u00efx\\2\\u039a\\u039b\\5\\u00efx\\2\\u039b\\u039c\\5\\u00ef\")\n        buf.write(\"x\\2\\u039c\\u039d\\5\\u00efx\\2\\u039d\\u00de\\3\\2\\2\\2\\u039e\\u03a2\")\n        buf.write(\"\\5\\u00e1q\\2\\u039f\\u03a2\\5\\u00f9}\\2\\u03a0\\u03a2\\5\\u010f\")\n        buf.write(\"\\u0088\\2\\u03a1\\u039e\\3\\2\\2\\2\\u03a1\\u039f\\3\\2\\2\\2\\u03a1\")\n        buf.write(\"\\u03a0\\3\\2\\2\\2\\u03a2\\u00e0\\3\\2\\2\\2\\u03a3\\u03a5\\5\\u00e3\")\n        buf.write(\"r\\2\\u03a4\\u03a6\\5\\u00f1y\\2\\u03a5\\u03a4\\3\\2\\2\\2\\u03a5\\u03a6\")\n        buf.write(\"\\3\\2\\2\\2\\u03a6\\u03b0\\3\\2\\2\\2\\u03a7\\u03a9\\5\\u00e5s\\2\\u03a8\")\n        buf.write(\"\\u03aa\\5\\u00f1y\\2\\u03a9\\u03a8\\3\\2\\2\\2\\u03a9\\u03aa\\3\\2\")\n        buf.write(\"\\2\\2\\u03aa\\u03b0\\3\\2\\2\\2\\u03ab\\u03ad\\5\\u00e7t\\2\\u03ac\")\n        buf.write(\"\\u03ae\\5\\u00f1y\\2\\u03ad\\u03ac\\3\\2\\2\\2\\u03ad\\u03ae\\3\\2\")\n        buf.write(\"\\2\\2\\u03ae\\u03b0\\3\\2\\2\\2\\u03af\\u03a3\\3\\2\\2\\2\\u03af\\u03a7\")\n        buf.write(\"\\3\\2\\2\\2\\u03af\\u03ab\\3\\2\\2\\2\\u03b0\\u00e2\\3\\2\\2\\2\\u03b1\")\n        buf.write(\"\\u03b5\\5\\u00ebv\\2\\u03b2\\u03b4\\5\\u00d9m\\2\\u03b3\\u03b2\\3\")\n        buf.write(\"\\2\\2\\2\\u03b4\\u03b7\\3\\2\\2\\2\\u03b5\\u03b3\\3\\2\\2\\2\\u03b5\\u03b6\")\n        buf.write(\"\\3\\2\\2\\2\\u03b6\\u00e4\\3\\2\\2\\2\\u03b7\\u03b5\\3\\2\\2\\2\\u03b8\")\n        buf.write(\"\\u03bc\\7\\62\\2\\2\\u03b9\\u03bb\\5\\u00edw\\2\\u03ba\\u03b9\\3\\2\")\n        buf.write(\"\\2\\2\\u03bb\\u03be\\3\\2\\2\\2\\u03bc\\u03ba\\3\\2\\2\\2\\u03bc\\u03bd\")\n        buf.write(\"\\3\\2\\2\\2\\u03bd\\u00e6\\3\\2\\2\\2\\u03be\\u03bc\\3\\2\\2\\2\\u03bf\")\n        buf.write(\"\\u03c1\\5\\u00e9u\\2\\u03c0\\u03c2\\5\\u00efx\\2\\u03c1\\u03c0\\3\")\n        buf.write(\"\\2\\2\\2\\u03c2\\u03c3\\3\\2\\2\\2\\u03c3\\u03c1\\3\\2\\2\\2\\u03c3\\u03c4\")\n        buf.write(\"\\3\\2\\2\\2\\u03c4\\u00e8\\3\\2\\2\\2\\u03c5\\u03c6\\7\\62\\2\\2\\u03c6\")\n        buf.write(\"\\u03c7\\t\\4\\2\\2\\u03c7\\u00ea\\3\\2\\2\\2\\u03c8\\u03c9\\t\\5\\2\\2\")\n        buf.write(\"\\u03c9\\u00ec\\3\\2\\2\\2\\u03ca\\u03cb\\t\\6\\2\\2\\u03cb\\u00ee\\3\")\n        buf.write(\"\\2\\2\\2\\u03cc\\u03cd\\t\\7\\2\\2\\u03cd\\u00f0\\3\\2\\2\\2\\u03ce\\u03d0\")\n        buf.write(\"\\5\\u00f3z\\2\\u03cf\\u03d1\\5\\u00f5{\\2\\u03d0\\u03cf\\3\\2\\2\\2\")\n        buf.write(\"\\u03d0\\u03d1\\3\\2\\2\\2\\u03d1\\u03de\\3\\2\\2\\2\\u03d2\\u03d3\\5\")\n        buf.write(\"\\u00f3z\\2\\u03d3\\u03d4\\5\\u00f7|\\2\\u03d4\\u03de\\3\\2\\2\\2\\u03d5\")\n        buf.write(\"\\u03d7\\5\\u00f5{\\2\\u03d6\\u03d8\\5\\u00f3z\\2\\u03d7\\u03d6\\3\")\n        buf.write(\"\\2\\2\\2\\u03d7\\u03d8\\3\\2\\2\\2\\u03d8\\u03de\\3\\2\\2\\2\\u03d9\\u03db\")\n        buf.write(\"\\5\\u00f7|\\2\\u03da\\u03dc\\5\\u00f3z\\2\\u03db\\u03da\\3\\2\\2\\2\")\n        buf.write(\"\\u03db\\u03dc\\3\\2\\2\\2\\u03dc\\u03de\\3\\2\\2\\2\\u03dd\\u03ce\\3\")\n        buf.write(\"\\2\\2\\2\\u03dd\\u03d2\\3\\2\\2\\2\\u03dd\\u03d5\\3\\2\\2\\2\\u03dd\\u03d9\")\n        buf.write(\"\\3\\2\\2\\2\\u03de\\u00f2\\3\\2\\2\\2\\u03df\\u03e0\\t\\b\\2\\2\\u03e0\")\n        buf.write(\"\\u00f4\\3\\2\\2\\2\\u03e1\\u03e2\\t\\t\\2\\2\\u03e2\\u00f6\\3\\2\\2\\2\")\n        buf.write(\"\\u03e3\\u03e4\\7n\\2\\2\\u03e4\\u03e8\\7n\\2\\2\\u03e5\\u03e6\\7N\")\n        buf.write(\"\\2\\2\\u03e6\\u03e8\\7N\\2\\2\\u03e7\\u03e3\\3\\2\\2\\2\\u03e7\\u03e5\")\n        buf.write(\"\\3\\2\\2\\2\\u03e8\\u00f8\\3\\2\\2\\2\\u03e9\\u03ec\\5\\u00fb~\\2\\u03ea\")\n        buf.write(\"\\u03ec\\5\\u00fd\\177\\2\\u03eb\\u03e9\\3\\2\\2\\2\\u03eb\\u03ea\\3\")\n        buf.write(\"\\2\\2\\2\\u03ec\\u00fa\\3\\2\\2\\2\\u03ed\\u03ef\\5\\u00ff\\u0080\\2\")\n        buf.write(\"\\u03ee\\u03f0\\5\\u0101\\u0081\\2\\u03ef\\u03ee\\3\\2\\2\\2\\u03ef\")\n        buf.write(\"\\u03f0\\3\\2\\2\\2\\u03f0\\u03f2\\3\\2\\2\\2\\u03f1\\u03f3\\5\\u010d\")\n        buf.write(\"\\u0087\\2\\u03f2\\u03f1\\3\\2\\2\\2\\u03f2\\u03f3\\3\\2\\2\\2\\u03f3\")\n        buf.write(\"\\u03fa\\3\\2\\2\\2\\u03f4\\u03f5\\5\\u0105\\u0083\\2\\u03f5\\u03f7\")\n        buf.write(\"\\5\\u0101\\u0081\\2\\u03f6\\u03f8\\5\\u010d\\u0087\\2\\u03f7\\u03f6\")\n        buf.write(\"\\3\\2\\2\\2\\u03f7\\u03f8\\3\\2\\2\\2\\u03f8\\u03fa\\3\\2\\2\\2\\u03f9\")\n        buf.write(\"\\u03ed\\3\\2\\2\\2\\u03f9\\u03f4\\3\\2\\2\\2\\u03fa\\u00fc\\3\\2\\2\\2\")\n        buf.write(\"\\u03fb\\u03fc\\5\\u00e9u\\2\\u03fc\\u03fd\\5\\u0107\\u0084\\2\\u03fd\")\n        buf.write(\"\\u03ff\\5\\u0109\\u0085\\2\\u03fe\\u0400\\5\\u010d\\u0087\\2\\u03ff\")\n        buf.write(\"\\u03fe\\3\\2\\2\\2\\u03ff\\u0400\\3\\2\\2\\2\\u0400\\u0408\\3\\2\\2\\2\")\n        buf.write(\"\\u0401\\u0402\\5\\u00e9u\\2\\u0402\\u0403\\5\\u010b\\u0086\\2\\u0403\")\n        buf.write(\"\\u0405\\5\\u0109\\u0085\\2\\u0404\\u0406\\5\\u010d\\u0087\\2\\u0405\")\n        buf.write(\"\\u0404\\3\\2\\2\\2\\u0405\\u0406\\3\\2\\2\\2\\u0406\\u0408\\3\\2\\2\\2\")\n        buf.write(\"\\u0407\\u03fb\\3\\2\\2\\2\\u0407\\u0401\\3\\2\\2\\2\\u0408\\u00fe\\3\")\n        buf.write(\"\\2\\2\\2\\u0409\\u040b\\5\\u0105\\u0083\\2\\u040a\\u0409\\3\\2\\2\\2\")\n        buf.write(\"\\u040a\\u040b\\3\\2\\2\\2\\u040b\\u040c\\3\\2\\2\\2\\u040c\\u040d\\7\")\n        buf.write(\"\\60\\2\\2\\u040d\\u0412\\5\\u0105\\u0083\\2\\u040e\\u040f\\5\\u0105\")\n        buf.write(\"\\u0083\\2\\u040f\\u0410\\7\\60\\2\\2\\u0410\\u0412\\3\\2\\2\\2\\u0411\")\n        buf.write(\"\\u040a\\3\\2\\2\\2\\u0411\\u040e\\3\\2\\2\\2\\u0412\\u0100\\3\\2\\2\\2\")\n        buf.write(\"\\u0413\\u0415\\7g\\2\\2\\u0414\\u0416\\5\\u0103\\u0082\\2\\u0415\")\n        buf.write(\"\\u0414\\3\\2\\2\\2\\u0415\\u0416\\3\\2\\2\\2\\u0416\\u0417\\3\\2\\2\\2\")\n        buf.write(\"\\u0417\\u041e\\5\\u0105\\u0083\\2\\u0418\\u041a\\7G\\2\\2\\u0419\")\n        buf.write(\"\\u041b\\5\\u0103\\u0082\\2\\u041a\\u0419\\3\\2\\2\\2\\u041a\\u041b\")\n        buf.write(\"\\3\\2\\2\\2\\u041b\\u041c\\3\\2\\2\\2\\u041c\\u041e\\5\\u0105\\u0083\")\n        buf.write(\"\\2\\u041d\\u0413\\3\\2\\2\\2\\u041d\\u0418\\3\\2\\2\\2\\u041e\\u0102\")\n        buf.write(\"\\3\\2\\2\\2\\u041f\\u0420\\t\\n\\2\\2\\u0420\\u0104\\3\\2\\2\\2\\u0421\")\n        buf.write(\"\\u0423\\5\\u00d9m\\2\\u0422\\u0421\\3\\2\\2\\2\\u0423\\u0424\\3\\2\")\n        buf.write(\"\\2\\2\\u0424\\u0422\\3\\2\\2\\2\\u0424\\u0425\\3\\2\\2\\2\\u0425\\u0106\")\n        buf.write(\"\\3\\2\\2\\2\\u0426\\u0428\\5\\u010b\\u0086\\2\\u0427\\u0426\\3\\2\\2\")\n        buf.write(\"\\2\\u0427\\u0428\\3\\2\\2\\2\\u0428\\u0429\\3\\2\\2\\2\\u0429\\u042a\")\n        buf.write(\"\\7\\60\\2\\2\\u042a\\u042f\\5\\u010b\\u0086\\2\\u042b\\u042c\\5\\u010b\")\n        buf.write(\"\\u0086\\2\\u042c\\u042d\\7\\60\\2\\2\\u042d\\u042f\\3\\2\\2\\2\\u042e\")\n        buf.write(\"\\u0427\\3\\2\\2\\2\\u042e\\u042b\\3\\2\\2\\2\\u042f\\u0108\\3\\2\\2\\2\")\n        buf.write(\"\\u0430\\u0432\\7r\\2\\2\\u0431\\u0433\\5\\u0103\\u0082\\2\\u0432\")\n        buf.write(\"\\u0431\\3\\2\\2\\2\\u0432\\u0433\\3\\2\\2\\2\\u0433\\u0434\\3\\2\\2\\2\")\n        buf.write(\"\\u0434\\u043b\\5\\u0105\\u0083\\2\\u0435\\u0437\\7R\\2\\2\\u0436\")\n        buf.write(\"\\u0438\\5\\u0103\\u0082\\2\\u0437\\u0436\\3\\2\\2\\2\\u0437\\u0438\")\n        buf.write(\"\\3\\2\\2\\2\\u0438\\u0439\\3\\2\\2\\2\\u0439\\u043b\\5\\u0105\\u0083\")\n        buf.write(\"\\2\\u043a\\u0430\\3\\2\\2\\2\\u043a\\u0435\\3\\2\\2\\2\\u043b\\u010a\")\n        buf.write(\"\\3\\2\\2\\2\\u043c\\u043e\\5\\u00efx\\2\\u043d\\u043c\\3\\2\\2\\2\\u043e\")\n        buf.write(\"\\u043f\\3\\2\\2\\2\\u043f\\u043d\\3\\2\\2\\2\\u043f\\u0440\\3\\2\\2\\2\")\n        buf.write(\"\\u0440\\u010c\\3\\2\\2\\2\\u0441\\u0442\\t\\13\\2\\2\\u0442\\u010e\")\n        buf.write(\"\\3\\2\\2\\2\\u0443\\u0444\\7)\\2\\2\\u0444\\u0445\\5\\u0111\\u0089\")\n        buf.write(\"\\2\\u0445\\u0446\\7)\\2\\2\\u0446\\u045a\\3\\2\\2\\2\\u0447\\u0448\")\n        buf.write(\"\\7N\\2\\2\\u0448\\u0449\\7)\\2\\2\\u0449\\u044a\\3\\2\\2\\2\\u044a\\u044b\")\n        buf.write(\"\\5\\u0111\\u0089\\2\\u044b\\u044c\\7)\\2\\2\\u044c\\u045a\\3\\2\\2\")\n        buf.write(\"\\2\\u044d\\u044e\\7w\\2\\2\\u044e\\u044f\\7)\\2\\2\\u044f\\u0450\\3\")\n        buf.write(\"\\2\\2\\2\\u0450\\u0451\\5\\u0111\\u0089\\2\\u0451\\u0452\\7)\\2\\2\")\n        buf.write(\"\\u0452\\u045a\\3\\2\\2\\2\\u0453\\u0454\\7W\\2\\2\\u0454\\u0455\\7\")\n        buf.write(\")\\2\\2\\u0455\\u0456\\3\\2\\2\\2\\u0456\\u0457\\5\\u0111\\u0089\\2\")\n        buf.write(\"\\u0457\\u0458\\7)\\2\\2\\u0458\\u045a\\3\\2\\2\\2\\u0459\\u0443\\3\")\n        buf.write(\"\\2\\2\\2\\u0459\\u0447\\3\\2\\2\\2\\u0459\\u044d\\3\\2\\2\\2\\u0459\\u0453\")\n        buf.write(\"\\3\\2\\2\\2\\u045a\\u0110\\3\\2\\2\\2\\u045b\\u045d\\5\\u0113\\u008a\")\n        buf.write(\"\\2\\u045c\\u045b\\3\\2\\2\\2\\u045d\\u045e\\3\\2\\2\\2\\u045e\\u045c\")\n        buf.write(\"\\3\\2\\2\\2\\u045e\\u045f\\3\\2\\2\\2\\u045f\\u0112\\3\\2\\2\\2\\u0460\")\n        buf.write(\"\\u0463\\n\\f\\2\\2\\u0461\\u0463\\5\\u0115\\u008b\\2\\u0462\\u0460\")\n        buf.write(\"\\3\\2\\2\\2\\u0462\\u0461\\3\\2\\2\\2\\u0463\\u0114\\3\\2\\2\\2\\u0464\")\n        buf.write(\"\\u0469\\5\\u0117\\u008c\\2\\u0465\\u0469\\5\\u0119\\u008d\\2\\u0466\")\n        buf.write(\"\\u0469\\5\\u011b\\u008e\\2\\u0467\\u0469\\5\\u00dbn\\2\\u0468\\u0464\")\n        buf.write(\"\\3\\2\\2\\2\\u0468\\u0465\\3\\2\\2\\2\\u0468\\u0466\\3\\2\\2\\2\\u0468\")\n        buf.write(\"\\u0467\\3\\2\\2\\2\\u0469\\u0116\\3\\2\\2\\2\\u046a\\u046b\\7^\\2\\2\")\n        buf.write(\"\\u046b\\u046c\\t\\r\\2\\2\\u046c\\u0118\\3\\2\\2\\2\\u046d\\u046e\\7\")\n        buf.write(\"^\\2\\2\\u046e\\u0479\\5\\u00edw\\2\\u046f\\u0470\\7^\\2\\2\\u0470\")\n        buf.write(\"\\u0471\\5\\u00edw\\2\\u0471\\u0472\\5\\u00edw\\2\\u0472\\u0479\\3\")\n        buf.write(\"\\2\\2\\2\\u0473\\u0474\\7^\\2\\2\\u0474\\u0475\\5\\u00edw\\2\\u0475\")\n        buf.write(\"\\u0476\\5\\u00edw\\2\\u0476\\u0477\\5\\u00edw\\2\\u0477\\u0479\\3\")\n        buf.write(\"\\2\\2\\2\\u0478\\u046d\\3\\2\\2\\2\\u0478\\u046f\\3\\2\\2\\2\\u0478\\u0473\")\n        buf.write(\"\\3\\2\\2\\2\\u0479\\u011a\\3\\2\\2\\2\\u047a\\u047b\\7^\\2\\2\\u047b\")\n        buf.write(\"\\u047c\\7z\\2\\2\\u047c\\u047e\\3\\2\\2\\2\\u047d\\u047f\\5\\u00ef\")\n        buf.write(\"x\\2\\u047e\\u047d\\3\\2\\2\\2\\u047f\\u0480\\3\\2\\2\\2\\u0480\\u047e\")\n        buf.write(\"\\3\\2\\2\\2\\u0480\\u0481\\3\\2\\2\\2\\u0481\\u011c\\3\\2\\2\\2\\u0482\")\n        buf.write(\"\\u0484\\5\\u011f\\u0090\\2\\u0483\\u0482\\3\\2\\2\\2\\u0483\\u0484\")\n        buf.write(\"\\3\\2\\2\\2\\u0484\\u0485\\3\\2\\2\\2\\u0485\\u0487\\7$\\2\\2\\u0486\")\n        buf.write(\"\\u0488\\5\\u0121\\u0091\\2\\u0487\\u0486\\3\\2\\2\\2\\u0487\\u0488\")\n        buf.write(\"\\3\\2\\2\\2\\u0488\\u0489\\3\\2\\2\\2\\u0489\\u048a\\7$\\2\\2\\u048a\")\n        buf.write(\"\\u011e\\3\\2\\2\\2\\u048b\\u048c\\7w\\2\\2\\u048c\\u048f\\7:\\2\\2\\u048d\")\n        buf.write(\"\\u048f\\t\\16\\2\\2\\u048e\\u048b\\3\\2\\2\\2\\u048e\\u048d\\3\\2\\2\")\n        buf.write(\"\\2\\u048f\\u0120\\3\\2\\2\\2\\u0490\\u0492\\5\\u0123\\u0092\\2\\u0491\")\n        buf.write(\"\\u0490\\3\\2\\2\\2\\u0492\\u0493\\3\\2\\2\\2\\u0493\\u0491\\3\\2\\2\\2\")\n        buf.write(\"\\u0493\\u0494\\3\\2\\2\\2\\u0494\\u0122\\3\\2\\2\\2\\u0495\\u0498\\n\")\n        buf.write(\"\\17\\2\\2\\u0496\\u0498\\5\\u0115\\u008b\\2\\u0497\\u0495\\3\\2\\2\")\n        buf.write(\"\\2\\u0497\\u0496\\3\\2\\2\\2\\u0498\\u0124\\3\\2\\2\\2\\u0499\\u049b\")\n        buf.write(\"\\7%\\2\\2\\u049a\\u049c\\5\\u0129\\u0095\\2\\u049b\\u049a\\3\\2\\2\")\n        buf.write(\"\\2\\u049b\\u049c\\3\\2\\2\\2\\u049c\\u049d\\3\\2\\2\\2\\u049d\\u049f\")\n        buf.write(\"\\5\\u00e3r\\2\\u049e\\u04a0\\5\\u0129\\u0095\\2\\u049f\\u049e\\3\")\n        buf.write(\"\\2\\2\\2\\u049f\\u04a0\\3\\2\\2\\2\\u04a0\\u04a1\\3\\2\\2\\2\\u04a1\\u04a5\")\n        buf.write(\"\\5\\u011d\\u008f\\2\\u04a2\\u04a4\\n\\20\\2\\2\\u04a3\\u04a2\\3\\2\")\n        buf.write(\"\\2\\2\\u04a4\\u04a7\\3\\2\\2\\2\\u04a5\\u04a3\\3\\2\\2\\2\\u04a5\\u04a6\")\n        buf.write(\"\\3\\2\\2\\2\\u04a6\\u04a8\\3\\2\\2\\2\\u04a7\\u04a5\\3\\2\\2\\2\\u04a8\")\n        buf.write(\"\\u04a9\\b\\u0093\\2\\2\\u04a9\\u0126\\3\\2\\2\\2\\u04aa\\u04ac\\7%\")\n        buf.write(\"\\2\\2\\u04ab\\u04ad\\5\\u0129\\u0095\\2\\u04ac\\u04ab\\3\\2\\2\\2\\u04ac\")\n        buf.write(\"\\u04ad\\3\\2\\2\\2\\u04ad\\u04ae\\3\\2\\2\\2\\u04ae\\u04af\\7r\\2\\2\")\n        buf.write(\"\\u04af\\u04b0\\7t\\2\\2\\u04b0\\u04b1\\7c\\2\\2\\u04b1\\u04b2\\7i\")\n        buf.write(\"\\2\\2\\u04b2\\u04b3\\7o\\2\\2\\u04b3\\u04b4\\7c\\2\\2\\u04b4\\u04b5\")\n        buf.write(\"\\3\\2\\2\\2\\u04b5\\u04b9\\5\\u0129\\u0095\\2\\u04b6\\u04b8\\n\\20\")\n        buf.write(\"\\2\\2\\u04b7\\u04b6\\3\\2\\2\\2\\u04b8\\u04bb\\3\\2\\2\\2\\u04b9\\u04b7\")\n        buf.write(\"\\3\\2\\2\\2\\u04b9\\u04ba\\3\\2\\2\\2\\u04ba\\u04bc\\3\\2\\2\\2\\u04bb\")\n        buf.write(\"\\u04b9\\3\\2\\2\\2\\u04bc\\u04bd\\b\\u0094\\2\\2\\u04bd\\u0128\\3\\2\")\n        buf.write(\"\\2\\2\\u04be\\u04c0\\t\\21\\2\\2\\u04bf\\u04be\\3\\2\\2\\2\\u04c0\\u04c1\")\n        buf.write(\"\\3\\2\\2\\2\\u04c1\\u04bf\\3\\2\\2\\2\\u04c1\\u04c2\\3\\2\\2\\2\\u04c2\")\n        buf.write(\"\\u04c3\\3\\2\\2\\2\\u04c3\\u04c4\\b\\u0095\\2\\2\\u04c4\\u012a\\3\\2\")\n        buf.write(\"\\2\\2\\u04c5\\u04c7\\7\\17\\2\\2\\u04c6\\u04c8\\7\\f\\2\\2\\u04c7\\u04c6\")\n        buf.write(\"\\3\\2\\2\\2\\u04c7\\u04c8\\3\\2\\2\\2\\u04c8\\u04cb\\3\\2\\2\\2\\u04c9\")\n        buf.write(\"\\u04cb\\7\\f\\2\\2\\u04ca\\u04c5\\3\\2\\2\\2\\u04ca\\u04c9\\3\\2\\2\\2\")\n        buf.write(\"\\u04cb\\u04cc\\3\\2\\2\\2\\u04cc\\u04cd\\b\\u0096\\2\\2\\u04cd\\u012c\")\n        buf.write(\"\\3\\2\\2\\2\\u04ce\\u04cf\\7\\61\\2\\2\\u04cf\\u04d0\\7,\\2\\2\\u04d0\")\n        buf.write(\"\\u04d4\\3\\2\\2\\2\\u04d1\\u04d3\\13\\2\\2\\2\\u04d2\\u04d1\\3\\2\\2\")\n        buf.write(\"\\2\\u04d3\\u04d6\\3\\2\\2\\2\\u04d4\\u04d5\\3\\2\\2\\2\\u04d4\\u04d2\")\n        buf.write(\"\\3\\2\\2\\2\\u04d5\\u04d7\\3\\2\\2\\2\\u04d6\\u04d4\\3\\2\\2\\2\\u04d7\")\n        buf.write(\"\\u04d8\\7,\\2\\2\\u04d8\\u04d9\\7\\61\\2\\2\\u04d9\\u04da\\3\\2\\2\\2\")\n        buf.write(\"\\u04da\\u04db\\b\\u0097\\2\\2\\u04db\\u012e\\3\\2\\2\\2\\u04dc\\u04dd\")\n        buf.write(\"\\7\\61\\2\\2\\u04dd\\u04de\\7\\61\\2\\2\\u04de\\u04e2\\3\\2\\2\\2\\u04df\")\n        buf.write(\"\\u04e1\\n\\20\\2\\2\\u04e0\\u04df\\3\\2\\2\\2\\u04e1\\u04e4\\3\\2\\2\")\n        buf.write(\"\\2\\u04e2\\u04e0\\3\\2\\2\\2\\u04e2\\u04e3\\3\\2\\2\\2\\u04e3\\u04e5\")\n        buf.write(\"\\3\\2\\2\\2\\u04e4\\u04e2\\3\\2\\2\\2\\u04e5\\u04e6\\b\\u0098\\2\\2\\u04e6\")\n        buf.write(\"\\u0130\\3\\2\\2\\2=\\2\\u0380\\u0382\\u0387\\u0397\\u03a1\\u03a5\")\n        buf.write(\"\\u03a9\\u03ad\\u03af\\u03b5\\u03bc\\u03c3\\u03d0\\u03d7\\u03db\")\n        buf.write(\"\\u03dd\\u03e7\\u03eb\\u03ef\\u03f2\\u03f7\\u03f9\\u03ff\\u0405\")\n        buf.write(\"\\u0407\\u040a\\u0411\\u0415\\u041a\\u041d\\u0424\\u0427\\u042e\")\n        buf.write(\"\\u0432\\u0437\\u043a\\u043f\\u0459\\u045e\\u0462\\u0468\\u0478\")\n        buf.write(\"\\u0480\\u0483\\u0487\\u048e\\u0493\\u0497\\u049b\\u049f\\u04a5\")\n        buf.write(\"\\u04ac\\u04b9\\u04c1\\u04c7\\u04ca\\u04d4\\u04e2\\3\\b\\2\\2\")\n        return buf.getvalue()\n\n\nclass CLexer(Lexer):\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n\n    T__0 = 1\n    T__1 = 2\n    T__2 = 3\n    T__3 = 4\n    T__4 = 5\n    T__5 = 6\n    T__6 = 7\n    T__7 = 8\n    T__8 = 9\n    T__9 = 10\n    T__10 = 11\n    T__11 = 12\n    T__12 = 13\n    T__13 = 14\n    Auto = 15\n    Break = 16\n    Case = 17\n    Char = 18\n    Const = 19\n    Continue = 20\n    Default = 21\n    Do = 22\n    Double = 23\n    Else = 24\n    Enum = 25\n    Extern = 26\n    Float = 27\n    For = 28\n    Goto = 29\n    If = 30\n    Inline = 31\n    Int = 32\n    Long = 33\n    Register = 34\n    Restrict = 35\n    Return = 36\n    Short = 37\n    Signed = 38\n    Sizeof = 39\n    Static = 40\n    Struct = 41\n    Switch = 42\n    Typedef = 43\n    Union = 44\n    Unsigned = 45\n    Void = 46\n    Volatile = 47\n    While = 48\n    Alignas = 49\n    Alignof = 50\n    Atomic = 51\n    Bool = 52\n    Complex = 53\n    Generic = 54\n    Imaginary = 55\n    Noreturn = 56\n    StaticAssert = 57\n    ThreadLocal = 58\n    LeftParen = 59\n    RightParen = 60\n    LeftBracket = 61\n    RightBracket = 62\n    LeftBrace = 63\n    RightBrace = 64\n    Less = 65\n    LessEqual = 66\n    Greater = 67\n    GreaterEqual = 68\n    LeftShift = 69\n    RightShift = 70\n    Plus = 71\n    PlusPlus = 72\n    Minus = 73\n    MinusMinus = 74\n    Star = 75\n    Div = 76\n    Mod = 77\n    And = 78\n    Or = 79\n    AndAnd = 80\n    OrOr = 81\n    Caret = 82\n    Not = 83\n    Tilde = 84\n    Question = 85\n    Colon = 86\n    Semi = 87\n    Comma = 88\n    Assign = 89\n    StarAssign = 90\n    DivAssign = 91\n    ModAssign = 92\n    PlusAssign = 93\n    MinusAssign = 94\n    LeftShiftAssign = 95\n    RightShiftAssign = 96\n    AndAssign = 97\n    XorAssign = 98\n    OrAssign = 99\n    Equal = 100\n    NotEqual = 101\n    Arrow = 102\n    Dot = 103\n    Ellipsis = 104\n    Identifier = 105\n    Constant = 106\n    StringLiteral = 107\n    LineDirective = 108\n    PragmaDirective = 109\n    Whitespace = 110\n    Newline = 111\n    BlockComment = 112\n    LineComment = 113\n\n    modeNames = [ \"DEFAULT_MODE\" ]\n\n    literalNames = [ \"<INVALID>\",\n            \"'__extension__'\", \"'__builtin_va_arg'\", \"'__builtin_offsetof'\",\n            \"'__m128'\", \"'__m128d'\", \"'__m128i'\", \"'__typeof__'\", \"'__inline__'\",\n            \"'__stdcall'\", \"'__declspec'\", \"'__asm'\", \"'__attribute__'\",\n            \"'__asm__'\", \"'__volatile__'\", \"'auto'\", \"'break'\", \"'case'\",\n            \"'char'\", \"'const'\", \"'continue'\", \"'default'\", \"'do'\", \"'double'\",\n            \"'else'\", \"'enum'\", \"'extern'\", \"'float'\", \"'for'\", \"'goto'\",\n            \"'if'\", \"'inline'\", \"'int'\", \"'long'\", \"'register'\", \"'restrict'\",\n            \"'return'\", \"'short'\", \"'signed'\", \"'sizeof'\", \"'static'\", \"'struct'\",\n            \"'switch'\", \"'typedef'\", \"'union'\", \"'unsigned'\", \"'void'\",\n            \"'volatile'\", \"'while'\", \"'_Alignas'\", \"'_Alignof'\", \"'_Atomic'\",\n            \"'_Bool'\", \"'_Complex'\", \"'_Generic'\", \"'_Imaginary'\", \"'_Noreturn'\",\n            \"'_Static_assert'\", \"'_Thread_local'\", \"'('\", \"')'\", \"'['\",\n            \"']'\", \"'{'\", \"'}'\", \"'<'\", \"'<='\", \"'>'\", \"'>='\", \"'<<'\", \"'>>'\",\n            \"'+'\", \"'++'\", \"'-'\", \"'--'\", \"'*'\", \"'/'\", \"'%'\", \"'&'\", \"'|'\",\n            \"'&&'\", \"'||'\", \"'^'\", \"'!'\", \"'~'\", \"'?'\", \"':'\", \"';'\", \"','\",\n            \"'='\", \"'*='\", \"'/='\", \"'%='\", \"'+='\", \"'-='\", \"'<<='\", \"'>>='\",\n            \"'&='\", \"'^='\", \"'|='\", \"'=='\", \"'!='\", \"'->'\", \"'.'\", \"'...'\" ]\n\n    symbolicNames = [ \"<INVALID>\",\n            \"Auto\", \"Break\", \"Case\", \"Char\", \"Const\", \"Continue\", \"Default\",\n            \"Do\", \"Double\", \"Else\", \"Enum\", \"Extern\", \"Float\", \"For\", \"Goto\",\n            \"If\", \"Inline\", \"Int\", \"Long\", \"Register\", \"Restrict\", \"Return\",\n            \"Short\", \"Signed\", \"Sizeof\", \"Static\", \"Struct\", \"Switch\", \"Typedef\",\n            \"Union\", \"Unsigned\", \"Void\", \"Volatile\", \"While\", \"Alignas\",\n            \"Alignof\", \"Atomic\", \"Bool\", \"Complex\", \"Generic\", \"Imaginary\",\n            \"Noreturn\", \"StaticAssert\", \"ThreadLocal\", \"LeftParen\", \"RightParen\",\n            \"LeftBracket\", \"RightBracket\", \"LeftBrace\", \"RightBrace\", \"Less\",\n            \"LessEqual\", \"Greater\", \"GreaterEqual\", \"LeftShift\", \"RightShift\",\n            \"Plus\", \"PlusPlus\", \"Minus\", \"MinusMinus\", \"Star\", \"Div\", \"Mod\",\n            \"And\", \"Or\", \"AndAnd\", \"OrOr\", \"Caret\", \"Not\", \"Tilde\", \"Question\",\n            \"Colon\", \"Semi\", \"Comma\", \"Assign\", \"StarAssign\", \"DivAssign\",\n            \"ModAssign\", \"PlusAssign\", \"MinusAssign\", \"LeftShiftAssign\",\n            \"RightShiftAssign\", \"AndAssign\", \"XorAssign\", \"OrAssign\", \"Equal\",\n            \"NotEqual\", \"Arrow\", \"Dot\", \"Ellipsis\", \"Identifier\", \"Constant\",\n            \"StringLiteral\", \"LineDirective\", \"PragmaDirective\", \"Whitespace\",\n            \"Newline\", \"BlockComment\", \"LineComment\" ]\n\n    ruleNames = [ \"T__0\", \"T__1\", \"T__2\", \"T__3\", \"T__4\", \"T__5\", \"T__6\",\n                  \"T__7\", \"T__8\", \"T__9\", \"T__10\", \"T__11\", \"T__12\", \"T__13\",\n                  \"Auto\", \"Break\", \"Case\", \"Char\", \"Const\", \"Continue\",\n                  \"Default\", \"Do\", \"Double\", \"Else\", \"Enum\", \"Extern\", \"Float\",\n                  \"For\", \"Goto\", \"If\", \"Inline\", \"Int\", \"Long\", \"Register\",\n                  \"Restrict\", \"Return\", \"Short\", \"Signed\", \"Sizeof\", \"Static\",\n                  \"Struct\", \"Switch\", \"Typedef\", \"Union\", \"Unsigned\", \"Void\",\n                  \"Volatile\", \"While\", \"Alignas\", \"Alignof\", \"Atomic\", \"Bool\",\n                  \"Complex\", \"Generic\", \"Imaginary\", \"Noreturn\", \"StaticAssert\",\n                  \"ThreadLocal\", \"LeftParen\", \"RightParen\", \"LeftBracket\",\n                  \"RightBracket\", \"LeftBrace\", \"RightBrace\", \"Less\", \"LessEqual\",\n                  \"Greater\", \"GreaterEqual\", \"LeftShift\", \"RightShift\",\n                  \"Plus\", \"PlusPlus\", \"Minus\", \"MinusMinus\", \"Star\", \"Div\",\n                  \"Mod\", \"And\", \"Or\", \"AndAnd\", \"OrOr\", \"Caret\", \"Not\",\n                  \"Tilde\", \"Question\", \"Colon\", \"Semi\", \"Comma\", \"Assign\",\n                  \"StarAssign\", \"DivAssign\", \"ModAssign\", \"PlusAssign\",\n                  \"MinusAssign\", \"LeftShiftAssign\", \"RightShiftAssign\",\n                  \"AndAssign\", \"XorAssign\", \"OrAssign\", \"Equal\", \"NotEqual\",\n                  \"Arrow\", \"Dot\", \"Ellipsis\", \"Identifier\", \"IdentifierNondigit\",\n                  \"Nondigit\", \"Digit\", \"UniversalCharacterName\", \"HexQuad\",\n                  \"Constant\", \"IntegerConstant\", \"DecimalConstant\", \"OctalConstant\",\n                  \"HexadecimalConstant\", \"HexadecimalPrefix\", \"NonzeroDigit\",\n                  \"OctalDigit\", \"HexadecimalDigit\", \"IntegerSuffix\", \"UnsignedSuffix\",\n                  \"LongSuffix\", \"LongLongSuffix\", \"FloatingConstant\", \"DecimalFloatingConstant\",\n                  \"HexadecimalFloatingConstant\", \"FractionalConstant\", \"ExponentPart\",\n                  \"Sign\", \"DigitSequence\", \"HexadecimalFractionalConstant\",\n                  \"BinaryExponentPart\", \"HexadecimalDigitSequence\", \"FloatingSuffix\",\n                  \"CharacterConstant\", \"CCharSequence\", \"CChar\", \"EscapeSequence\",\n                  \"SimpleEscapeSequence\", \"OctalEscapeSequence\", \"HexadecimalEscapeSequence\",\n                  \"StringLiteral\", \"EncodingPrefix\", \"SCharSequence\", \"SChar\",\n                  \"LineDirective\", \"PragmaDirective\", \"Whitespace\", \"Newline\",\n                  \"BlockComment\", \"LineComment\" ]\n\n    grammarFileName = \"C.bnf\"\n\n    def __init__(self, input=None):\n        super().__init__(input)\n        self.checkVersion(\"4.9\")\n        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())\n        self._actions = None\n        self._predicates = None\n\n"
  },
  {
    "path": "runtime/Python3/tests/parser/cparser.py",
    "content": "# Generated from C.bnf by ANTLR 4.5.1\n# encoding: utf-8\nfrom antlr4 import *\nfrom io import StringIO\n\ndef serializedATN():\n    with StringIO() as buf:\n        buf.write(\"\\3\\u0430\\ud6d1\\u8206\\uad2d\\u4417\\uaef1\\u8d80\\uaadd\\3s\")\n        buf.write(\"\\u04e9\\4\\2\\t\\2\\4\\3\\t\\3\\4\\4\\t\\4\\4\\5\\t\\5\\4\\6\\t\\6\\4\\7\\t\\7\")\n        buf.write(\"\\4\\b\\t\\b\\4\\t\\t\\t\\4\\n\\t\\n\\4\\13\\t\\13\\4\\f\\t\\f\\4\\r\\t\\r\\4\\16\")\n        buf.write(\"\\t\\16\\4\\17\\t\\17\\4\\20\\t\\20\\4\\21\\t\\21\\4\\22\\t\\22\\4\\23\\t\\23\")\n        buf.write(\"\\4\\24\\t\\24\\4\\25\\t\\25\\4\\26\\t\\26\\4\\27\\t\\27\\4\\30\\t\\30\\4\\31\")\n        buf.write(\"\\t\\31\\4\\32\\t\\32\\4\\33\\t\\33\\4\\34\\t\\34\\4\\35\\t\\35\\4\\36\\t\\36\")\n        buf.write(\"\\4\\37\\t\\37\\4 \\t \\4!\\t!\\4\\\"\\t\\\"\\4#\\t#\\4$\\t$\\4%\\t%\\4&\\t\")\n        buf.write(\"&\\4\\'\\t\\'\\4(\\t(\\4)\\t)\\4*\\t*\\4+\\t+\\4,\\t,\\4-\\t-\\4.\\t.\\4\")\n        buf.write(\"/\\t/\\4\\60\\t\\60\\4\\61\\t\\61\\4\\62\\t\\62\\4\\63\\t\\63\\4\\64\\t\\64\")\n        buf.write(\"\\4\\65\\t\\65\\4\\66\\t\\66\\4\\67\\t\\67\\48\\t8\\49\\t9\\4:\\t:\\4;\\t\")\n        buf.write(\";\\4<\\t<\\4=\\t=\\4>\\t>\\4?\\t?\\4@\\t@\\4A\\tA\\4B\\tB\\4C\\tC\\4D\\t\")\n        buf.write(\"D\\4E\\tE\\4F\\tF\\4G\\tG\\4H\\tH\\4I\\tI\\4J\\tJ\\4K\\tK\\4L\\tL\\4M\\t\")\n        buf.write(\"M\\4N\\tN\\4O\\tO\\4P\\tP\\4Q\\tQ\\4R\\tR\\4S\\tS\\4T\\tT\\4U\\tU\\3\\2\")\n        buf.write(\"\\3\\2\\3\\2\\6\\2\\u00ae\\n\\2\\r\\2\\16\\2\\u00af\\3\\2\\3\\2\\3\\2\\3\\2\")\n        buf.write(\"\\3\\2\\3\\2\\5\\2\\u00b8\\n\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\")\n        buf.write(\"\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\3\\2\\5\\2\\u00cc\\n\\2\")\n        buf.write(\"\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\3\\4\\7\")\n        buf.write(\"\\4\\u00db\\n\\4\\f\\4\\16\\4\\u00de\\13\\4\\3\\5\\3\\5\\3\\5\\3\\5\\3\\5\\3\")\n        buf.write(\"\\5\\3\\5\\5\\5\\u00e7\\n\\5\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\")\n        buf.write(\"\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\")\n        buf.write(\"\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\5\\6\\u010b\")\n        buf.write(\"\\n\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\5\\6\\u0115\\n\\6\\3\\6\")\n        buf.write(\"\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\3\\6\\7\\6\\u0122\\n\\6\")\n        buf.write(\"\\f\\6\\16\\6\\u0125\\13\\6\\3\\7\\3\\7\\3\\7\\3\\7\\3\\7\\3\\7\\7\\7\\u012d\")\n        buf.write(\"\\n\\7\\f\\7\\16\\7\\u0130\\13\\7\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\")\n        buf.write(\"\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\\3\\b\")\n        buf.write(\"\\3\\b\\5\\b\\u0148\\n\\b\\3\\t\\3\\t\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\")\n        buf.write(\"\\3\\n\\3\\n\\3\\n\\3\\n\\3\\n\\5\\n\\u0158\\n\\n\\3\\13\\3\\13\\3\\13\\3\\13\")\n        buf.write(\"\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\3\\13\\7\\13\\u0166\\n\")\n        buf.write(\"\\13\\f\\13\\16\\13\\u0169\\13\\13\\3\\f\\3\\f\\3\\f\\3\\f\\3\\f\\3\\f\\3\\f\")\n        buf.write(\"\\3\\f\\3\\f\\7\\f\\u0174\\n\\f\\f\\f\\16\\f\\u0177\\13\\f\\3\\r\\3\\r\\3\\r\")\n        buf.write(\"\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\\3\\r\\7\\r\\u0182\\n\\r\\f\\r\\16\\r\\u0185\")\n        buf.write(\"\\13\\r\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\")\n        buf.write(\"\\3\\16\\3\\16\\3\\16\\3\\16\\3\\16\\7\\16\\u0196\\n\\16\\f\\16\\16\\16\\u0199\")\n        buf.write(\"\\13\\16\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\3\\17\\7\")\n        buf.write(\"\\17\\u01a4\\n\\17\\f\\17\\16\\17\\u01a7\\13\\17\\3\\20\\3\\20\\3\\20\\3\")\n        buf.write(\"\\20\\3\\20\\3\\20\\7\\20\\u01af\\n\\20\\f\\20\\16\\20\\u01b2\\13\\20\\3\")\n        buf.write(\"\\21\\3\\21\\3\\21\\3\\21\\3\\21\\3\\21\\7\\21\\u01ba\\n\\21\\f\\21\\16\\21\")\n        buf.write(\"\\u01bd\\13\\21\\3\\22\\3\\22\\3\\22\\3\\22\\3\\22\\3\\22\\7\\22\\u01c5\")\n        buf.write(\"\\n\\22\\f\\22\\16\\22\\u01c8\\13\\22\\3\\23\\3\\23\\3\\23\\3\\23\\3\\23\")\n        buf.write(\"\\3\\23\\7\\23\\u01d0\\n\\23\\f\\23\\16\\23\\u01d3\\13\\23\\3\\24\\3\\24\")\n        buf.write(\"\\3\\24\\3\\24\\3\\24\\3\\24\\7\\24\\u01db\\n\\24\\f\\24\\16\\24\\u01de\")\n        buf.write(\"\\13\\24\\3\\25\\3\\25\\3\\25\\3\\25\\3\\25\\3\\25\\5\\25\\u01e6\\n\\25\\3\")\n        buf.write(\"\\26\\3\\26\\3\\26\\3\\26\\3\\26\\5\\26\\u01ed\\n\\26\\3\\27\\3\\27\\3\\30\")\n        buf.write(\"\\3\\30\\3\\30\\3\\30\\3\\30\\3\\30\\7\\30\\u01f7\\n\\30\\f\\30\\16\\30\\u01fa\")\n        buf.write(\"\\13\\30\\3\\31\\3\\31\\3\\32\\3\\32\\5\\32\\u0200\\n\\32\\3\\32\\3\\32\\3\")\n        buf.write(\"\\32\\5\\32\\u0205\\n\\32\\3\\33\\6\\33\\u0208\\n\\33\\r\\33\\16\\33\\u0209\")\n        buf.write(\"\\3\\34\\6\\34\\u020d\\n\\34\\r\\34\\16\\34\\u020e\\3\\35\\3\\35\\3\\35\")\n        buf.write(\"\\3\\35\\3\\35\\5\\35\\u0216\\n\\35\\3\\36\\3\\36\\3\\36\\3\\36\\3\\36\\3\")\n        buf.write(\"\\36\\7\\36\\u021e\\n\\36\\f\\36\\16\\36\\u0221\\13\\36\\3\\37\\3\\37\\3\")\n        buf.write(\"\\37\\3\\37\\3\\37\\5\\37\\u0228\\n\\37\\3 \\3 \\3!\\3!\\3!\\3!\\3!\\3!\")\n        buf.write(\"\\3!\\3!\\3!\\3!\\3!\\3!\\3!\\3!\\5!\\u023a\\n!\\3\\\"\\3\\\"\\5\\\"\\u023e\")\n        buf.write(\"\\n\\\"\\3\\\"\\3\\\"\\3\\\"\\3\\\"\\3\\\"\\3\\\"\\3\\\"\\5\\\"\\u0247\\n\\\"\\3#\\3#\\3\")\n        buf.write(\"$\\3$\\3$\\3$\\3$\\7$\\u0250\\n$\\f$\\16$\\u0253\\13$\\3%\\3%\\5%\\u0257\")\n        buf.write(\"\\n%\\3%\\3%\\3%\\5%\\u025c\\n%\\3&\\3&\\5&\\u0260\\n&\\3&\\3&\\5&\\u0264\")\n        buf.write(\"\\n&\\5&\\u0266\\n&\\3\\'\\3\\'\\3\\'\\3\\'\\3\\'\\3\\'\\7\\'\\u026e\\n\\'\")\n        buf.write(\"\\f\\'\\16\\'\\u0271\\13\\'\\3(\\3(\\5(\\u0275\\n(\\3(\\3(\\5(\\u0279\")\n        buf.write(\"\\n(\\3)\\3)\\5)\\u027d\\n)\\3)\\3)\\3)\\3)\\3)\\3)\\5)\\u0285\\n)\\3\")\n        buf.write(\")\\3)\\3)\\3)\\3)\\3)\\3)\\5)\\u028e\\n)\\3*\\3*\\3*\\3*\\3*\\3*\\7*\\u0296\")\n        buf.write(\"\\n*\\f*\\16*\\u0299\\13*\\3+\\3+\\3+\\3+\\3+\\5+\\u02a0\\n+\\3,\\3,\")\n        buf.write(\"\\3-\\3-\\3-\\3-\\3-\\3.\\3.\\3/\\3/\\3/\\3/\\3/\\3/\\5/\\u02b1\\n/\\3\")\n        buf.write(\"\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\3\\60\\5\\60\")\n        buf.write(\"\\u02bd\\n\\60\\3\\61\\5\\61\\u02c0\\n\\61\\3\\61\\3\\61\\7\\61\\u02c4\")\n        buf.write(\"\\n\\61\\f\\61\\16\\61\\u02c7\\13\\61\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\")\n        buf.write(\"\\3\\62\\5\\62\\u02cf\\n\\62\\3\\62\\3\\62\\3\\62\\5\\62\\u02d4\\n\\62\\3\")\n        buf.write(\"\\62\\5\\62\\u02d7\\n\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\5\\62\\u02de\")\n        buf.write(\"\\n\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\")\n        buf.write(\"\\3\\62\\3\\62\\3\\62\\5\\62\\u02ed\\n\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\")\n        buf.write(\"\\62\\3\\62\\3\\62\\3\\62\\3\\62\\3\\62\\5\\62\\u02f9\\n\\62\\3\\62\\7\\62\")\n        buf.write(\"\\u02fc\\n\\62\\f\\62\\16\\62\\u02ff\\13\\62\\3\\63\\3\\63\\3\\63\\6\\63\")\n        buf.write(\"\\u0304\\n\\63\\r\\63\\16\\63\\u0305\\3\\63\\3\\63\\5\\63\\u030a\\n\\63\")\n        buf.write(\"\\3\\64\\3\\64\\3\\64\\3\\64\\3\\64\\3\\64\\3\\64\\3\\65\\3\\65\\3\\65\\7\\65\")\n        buf.write(\"\\u0316\\n\\65\\f\\65\\16\\65\\u0319\\13\\65\\3\\65\\5\\65\\u031c\\n\\65\")\n        buf.write(\"\\3\\66\\3\\66\\3\\66\\5\\66\\u0321\\n\\66\\3\\66\\5\\66\\u0324\\n\\66\\3\")\n        buf.write(\"\\66\\5\\66\\u0327\\n\\66\\3\\67\\3\\67\\3\\67\\3\\67\\3\\67\\7\\67\\u032e\")\n        buf.write(\"\\n\\67\\f\\67\\16\\67\\u0331\\13\\67\\38\\38\\58\\u0335\\n8\\38\\38\\5\")\n        buf.write(\"8\\u0339\\n8\\38\\38\\38\\58\\u033e\\n8\\38\\38\\58\\u0342\\n8\\38\\5\")\n        buf.write(\"8\\u0345\\n8\\39\\39\\39\\39\\39\\79\\u034c\\n9\\f9\\169\\u034f\\13\")\n        buf.write(\"9\\3:\\3:\\3:\\3:\\3:\\5:\\u0356\\n:\\3;\\3;\\3;\\3;\\3;\\3;\\7;\\u035e\")\n        buf.write(\"\\n;\\f;\\16;\\u0361\\13;\\3<\\3<\\3<\\3<\\3<\\5<\\u0368\\n<\\5<\\u036a\")\n        buf.write(\"\\n<\\3=\\3=\\3=\\3=\\3=\\3=\\7=\\u0372\\n=\\f=\\16=\\u0375\\13=\\3>\")\n        buf.write(\"\\3>\\5>\\u0379\\n>\\3?\\3?\\5?\\u037d\\n?\\3?\\3?\\7?\\u0381\\n?\\f\")\n        buf.write(\"?\\16?\\u0384\\13?\\5?\\u0386\\n?\\3@\\3@\\3@\\3@\\3@\\7@\\u038d\\n\")\n        buf.write(\"@\\f@\\16@\\u0390\\13@\\3@\\3@\\5@\\u0394\\n@\\3@\\5@\\u0397\\n@\\3\")\n        buf.write(\"@\\3@\\3@\\3@\\5@\\u039d\\n@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\3\")\n        buf.write(\"@\\3@\\3@\\3@\\5@\\u03ad\\n@\\3@\\3@\\7@\\u03b1\\n@\\f@\\16@\\u03b4\")\n        buf.write(\"\\13@\\5@\\u03b6\\n@\\3@\\3@\\3@\\5@\\u03bb\\n@\\3@\\5@\\u03be\\n@\\3\")\n        buf.write(\"@\\3@\\3@\\3@\\3@\\5@\\u03c5\\n@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\3\")\n        buf.write(\"@\\3@\\3@\\3@\\3@\\3@\\3@\\3@\\5@\\u03d8\\n@\\3@\\3@\\7@\\u03dc\\n@\\f\")\n        buf.write(\"@\\16@\\u03df\\13@\\7@\\u03e1\\n@\\f@\\16@\\u03e4\\13@\\3A\\3A\\3B\")\n        buf.write(\"\\3B\\3B\\3B\\3B\\3B\\3B\\3B\\3B\\3B\\5B\\u03f2\\nB\\3C\\3C\\5C\\u03f6\")\n        buf.write(\"\\nC\\3C\\3C\\3C\\3C\\3C\\5C\\u03fd\\nC\\3C\\7C\\u0400\\nC\\fC\\16C\\u0403\")\n        buf.write(\"\\13C\\3D\\3D\\3D\\3E\\3E\\3E\\3E\\3E\\7E\\u040d\\nE\\fE\\16E\\u0410\")\n        buf.write(\"\\13E\\3F\\3F\\3F\\3F\\3F\\3F\\5F\\u0418\\nF\\3G\\3G\\3G\\3G\\3G\\6G\\u041f\")\n        buf.write(\"\\nG\\rG\\16G\\u0420\\3G\\3G\\3G\\3H\\3H\\3H\\3H\\3H\\3H\\3H\\3H\\3H\\3\")\n        buf.write(\"H\\3H\\3H\\7H\\u0432\\nH\\fH\\16H\\u0435\\13H\\5H\\u0437\\nH\\3H\\3\")\n        buf.write(\"H\\3H\\3H\\7H\\u043d\\nH\\fH\\16H\\u0440\\13H\\5H\\u0442\\nH\\7H\\u0444\")\n        buf.write(\"\\nH\\fH\\16H\\u0447\\13H\\3H\\3H\\5H\\u044b\\nH\\3I\\3I\\3I\\3I\\3I\")\n        buf.write(\"\\3I\\3I\\3I\\3I\\3I\\3I\\5I\\u0458\\nI\\3J\\3J\\5J\\u045c\\nJ\\3J\\3\")\n        buf.write(\"J\\3K\\3K\\3K\\3K\\3K\\7K\\u0465\\nK\\fK\\16K\\u0468\\13K\\3L\\3L\\5\")\n        buf.write(\"L\\u046c\\nL\\3M\\5M\\u046f\\nM\\3M\\3M\\3N\\3N\\3N\\3N\\3N\\3N\\3N\\5\")\n        buf.write(\"N\\u047a\\nN\\3N\\3N\\3N\\3N\\3N\\3N\\5N\\u0482\\nN\\3O\\3O\\3O\\3O\\3\")\n        buf.write(\"O\\3O\\3O\\3O\\3O\\3O\\3O\\3O\\3O\\3O\\3O\\3O\\3O\\5O\\u0495\\nO\\3O\\3\")\n        buf.write(\"O\\5O\\u0499\\nO\\3O\\3O\\5O\\u049d\\nO\\3O\\3O\\3O\\3O\\3O\\3O\\5O\\u04a5\")\n        buf.write(\"\\nO\\3O\\3O\\5O\\u04a9\\nO\\3O\\3O\\3O\\5O\\u04ae\\nO\\3P\\3P\\3P\\3\")\n        buf.write(\"P\\3P\\3P\\3P\\3P\\3P\\5P\\u04b9\\nP\\3P\\3P\\3P\\3P\\3P\\5P\\u04c0\\n\")\n        buf.write(\"P\\3Q\\5Q\\u04c3\\nQ\\3Q\\3Q\\3R\\3R\\3R\\3R\\3R\\7R\\u04cc\\nR\\fR\\16\")\n        buf.write(\"R\\u04cf\\13R\\3S\\3S\\3S\\5S\\u04d4\\nS\\3T\\5T\\u04d7\\nT\\3T\\3T\")\n        buf.write(\"\\5T\\u04db\\nT\\3T\\3T\\3U\\3U\\3U\\3U\\3U\\7U\\u04e4\\nU\\fU\\16U\\u04e7\")\n        buf.write(\"\\13U\\3U\\2\\36\\6\\n\\f\\24\\26\\30\\32\\34\\36 \\\"$&.:FLRbptx~\\u0084\")\n        buf.write(\"\\u0088\\u0094\\u00a2\\u00a8V\\2\\4\\6\\b\\n\\f\\16\\20\\22\\24\\26\\30\")\n        buf.write(\"\\32\\34\\36 \\\"$&(*,.\\60\\62\\64\\668:<>@BDFHJLNPRTVXZ\\\\^`b\")\n        buf.write(\"dfhjlnprtvxz|~\\u0080\\u0082\\u0084\\u0086\\u0088\\u008a\\u008c\")\n        buf.write(\"\\u008e\\u0090\\u0092\\u0094\\u0096\\u0098\\u009a\\u009c\\u009e\")\n        buf.write(\"\\u00a0\\u00a2\\u00a4\\u00a6\\u00a8\\2\\16\\7\\2IIKKMMPPUV\\3\\2\")\n        buf.write(\"[e\\b\\2\\21\\21\\34\\34$$**--<<\\n\\2\\6\\b\\24\\24\\31\\31\\35\\35\\\"\")\n        buf.write(\"#\\'(/\\60\\66\\67\\3\\2\\6\\b\\4\\2++..\\6\\2\\25\\25%%\\61\\61\\65\\65\")\n        buf.write(\"\\5\\2\\n\\13!!::\\4\\2=>ZZ\\3\\2=>\\4\\2\\r\\r\\17\\17\\4\\2\\20\\20\\61\")\n        buf.write(\"\\61\\u0559\\2\\u00cb\\3\\2\\2\\2\\4\\u00cd\\3\\2\\2\\2\\6\\u00d4\\3\\2\")\n        buf.write(\"\\2\\2\\b\\u00e6\\3\\2\\2\\2\\n\\u010a\\3\\2\\2\\2\\f\\u0126\\3\\2\\2\\2\\16\")\n        buf.write(\"\\u0147\\3\\2\\2\\2\\20\\u0149\\3\\2\\2\\2\\22\\u0157\\3\\2\\2\\2\\24\\u0159\")\n        buf.write(\"\\3\\2\\2\\2\\26\\u016a\\3\\2\\2\\2\\30\\u0178\\3\\2\\2\\2\\32\\u0186\\3\")\n        buf.write(\"\\2\\2\\2\\34\\u019a\\3\\2\\2\\2\\36\\u01a8\\3\\2\\2\\2 \\u01b3\\3\\2\\2\")\n        buf.write(\"\\2\\\"\\u01be\\3\\2\\2\\2$\\u01c9\\3\\2\\2\\2&\\u01d4\\3\\2\\2\\2(\\u01df\")\n        buf.write(\"\\3\\2\\2\\2*\\u01ec\\3\\2\\2\\2,\\u01ee\\3\\2\\2\\2.\\u01f0\\3\\2\\2\\2\")\n        buf.write(\"\\60\\u01fb\\3\\2\\2\\2\\62\\u0204\\3\\2\\2\\2\\64\\u0207\\3\\2\\2\\2\\66\")\n        buf.write(\"\\u020c\\3\\2\\2\\28\\u0215\\3\\2\\2\\2:\\u0217\\3\\2\\2\\2<\\u0227\\3\")\n        buf.write(\"\\2\\2\\2>\\u0229\\3\\2\\2\\2@\\u0239\\3\\2\\2\\2B\\u0246\\3\\2\\2\\2D\\u0248\")\n        buf.write(\"\\3\\2\\2\\2F\\u024a\\3\\2\\2\\2H\\u025b\\3\\2\\2\\2J\\u0265\\3\\2\\2\\2\")\n        buf.write(\"L\\u0267\\3\\2\\2\\2N\\u0278\\3\\2\\2\\2P\\u028d\\3\\2\\2\\2R\\u028f\\3\")\n        buf.write(\"\\2\\2\\2T\\u029f\\3\\2\\2\\2V\\u02a1\\3\\2\\2\\2X\\u02a3\\3\\2\\2\\2Z\\u02a8\")\n        buf.write(\"\\3\\2\\2\\2\\\\\\u02b0\\3\\2\\2\\2^\\u02bc\\3\\2\\2\\2`\\u02bf\\3\\2\\2\\2\")\n        buf.write(\"b\\u02ce\\3\\2\\2\\2d\\u0309\\3\\2\\2\\2f\\u030b\\3\\2\\2\\2h\\u031b\\3\")\n        buf.write(\"\\2\\2\\2j\\u0326\\3\\2\\2\\2l\\u032f\\3\\2\\2\\2n\\u0344\\3\\2\\2\\2p\\u0346\")\n        buf.write(\"\\3\\2\\2\\2r\\u0355\\3\\2\\2\\2t\\u0357\\3\\2\\2\\2v\\u0369\\3\\2\\2\\2\")\n        buf.write(\"x\\u036b\\3\\2\\2\\2z\\u0376\\3\\2\\2\\2|\\u0385\\3\\2\\2\\2~\\u03b5\\3\")\n        buf.write(\"\\2\\2\\2\\u0080\\u03e5\\3\\2\\2\\2\\u0082\\u03f1\\3\\2\\2\\2\\u0084\\u03f3\")\n        buf.write(\"\\3\\2\\2\\2\\u0086\\u0404\\3\\2\\2\\2\\u0088\\u0407\\3\\2\\2\\2\\u008a\")\n        buf.write(\"\\u0417\\3\\2\\2\\2\\u008c\\u0419\\3\\2\\2\\2\\u008e\\u044a\\3\\2\\2\\2\")\n        buf.write(\"\\u0090\\u0457\\3\\2\\2\\2\\u0092\\u0459\\3\\2\\2\\2\\u0094\\u045f\\3\")\n        buf.write(\"\\2\\2\\2\\u0096\\u046b\\3\\2\\2\\2\\u0098\\u046e\\3\\2\\2\\2\\u009a\\u0481\")\n        buf.write(\"\\3\\2\\2\\2\\u009c\\u04ad\\3\\2\\2\\2\\u009e\\u04bf\\3\\2\\2\\2\\u00a0\")\n        buf.write(\"\\u04c2\\3\\2\\2\\2\\u00a2\\u04c6\\3\\2\\2\\2\\u00a4\\u04d3\\3\\2\\2\\2\")\n        buf.write(\"\\u00a6\\u04d6\\3\\2\\2\\2\\u00a8\\u04de\\3\\2\\2\\2\\u00aa\\u00cc\\7\")\n        buf.write(\"k\\2\\2\\u00ab\\u00cc\\7l\\2\\2\\u00ac\\u00ae\\7m\\2\\2\\u00ad\\u00ac\")\n        buf.write(\"\\3\\2\\2\\2\\u00ae\\u00af\\3\\2\\2\\2\\u00af\\u00ad\\3\\2\\2\\2\\u00af\")\n        buf.write(\"\\u00b0\\3\\2\\2\\2\\u00b0\\u00cc\\3\\2\\2\\2\\u00b1\\u00b2\\7=\\2\\2\")\n        buf.write(\"\\u00b2\\u00b3\\5.\\30\\2\\u00b3\\u00b4\\7>\\2\\2\\u00b4\\u00cc\\3\")\n        buf.write(\"\\2\\2\\2\\u00b5\\u00cc\\5\\4\\3\\2\\u00b6\\u00b8\\7\\3\\2\\2\\u00b7\\u00b6\")\n        buf.write(\"\\3\\2\\2\\2\\u00b7\\u00b8\\3\\2\\2\\2\\u00b8\\u00b9\\3\\2\\2\\2\\u00b9\")\n        buf.write(\"\\u00ba\\7=\\2\\2\\u00ba\\u00bb\\5\\u0092J\\2\\u00bb\\u00bc\\7>\\2\")\n        buf.write(\"\\2\\u00bc\\u00cc\\3\\2\\2\\2\\u00bd\\u00be\\7\\4\\2\\2\\u00be\\u00bf\")\n        buf.write(\"\\7=\\2\\2\\u00bf\\u00c0\\5\\16\\b\\2\\u00c0\\u00c1\\7Z\\2\\2\\u00c1\")\n        buf.write(\"\\u00c2\\5z>\\2\\u00c2\\u00c3\\7>\\2\\2\\u00c3\\u00cc\\3\\2\\2\\2\\u00c4\")\n        buf.write(\"\\u00c5\\7\\5\\2\\2\\u00c5\\u00c6\\7=\\2\\2\\u00c6\\u00c7\\5z>\\2\\u00c7\")\n        buf.write(\"\\u00c8\\7Z\\2\\2\\u00c8\\u00c9\\5\\16\\b\\2\\u00c9\\u00ca\\7>\\2\\2\")\n        buf.write(\"\\u00ca\\u00cc\\3\\2\\2\\2\\u00cb\\u00aa\\3\\2\\2\\2\\u00cb\\u00ab\\3\")\n        buf.write(\"\\2\\2\\2\\u00cb\\u00ad\\3\\2\\2\\2\\u00cb\\u00b1\\3\\2\\2\\2\\u00cb\\u00b5\")\n        buf.write(\"\\3\\2\\2\\2\\u00cb\\u00b7\\3\\2\\2\\2\\u00cb\\u00bd\\3\\2\\2\\2\\u00cb\")\n        buf.write(\"\\u00c4\\3\\2\\2\\2\\u00cc\\3\\3\\2\\2\\2\\u00cd\\u00ce\\78\\2\\2\\u00ce\")\n        buf.write(\"\\u00cf\\7=\\2\\2\\u00cf\\u00d0\\5*\\26\\2\\u00d0\\u00d1\\7Z\\2\\2\\u00d1\")\n        buf.write(\"\\u00d2\\5\\6\\4\\2\\u00d2\\u00d3\\7>\\2\\2\\u00d3\\5\\3\\2\\2\\2\\u00d4\")\n        buf.write(\"\\u00d5\\b\\4\\1\\2\\u00d5\\u00d6\\5\\b\\5\\2\\u00d6\\u00dc\\3\\2\\2\\2\")\n        buf.write(\"\\u00d7\\u00d8\\f\\3\\2\\2\\u00d8\\u00d9\\7Z\\2\\2\\u00d9\\u00db\\5\")\n        buf.write(\"\\b\\5\\2\\u00da\\u00d7\\3\\2\\2\\2\\u00db\\u00de\\3\\2\\2\\2\\u00dc\\u00da\")\n        buf.write(\"\\3\\2\\2\\2\\u00dc\\u00dd\\3\\2\\2\\2\\u00dd\\7\\3\\2\\2\\2\\u00de\\u00dc\")\n        buf.write(\"\\3\\2\\2\\2\\u00df\\u00e0\\5z>\\2\\u00e0\\u00e1\\7X\\2\\2\\u00e1\\u00e2\")\n        buf.write(\"\\5*\\26\\2\\u00e2\\u00e7\\3\\2\\2\\2\\u00e3\\u00e4\\7\\27\\2\\2\\u00e4\")\n        buf.write(\"\\u00e5\\7X\\2\\2\\u00e5\\u00e7\\5*\\26\\2\\u00e6\\u00df\\3\\2\\2\\2\")\n        buf.write(\"\\u00e6\\u00e3\\3\\2\\2\\2\\u00e7\\t\\3\\2\\2\\2\\u00e8\\u00e9\\b\\6\\1\")\n        buf.write(\"\\2\\u00e9\\u010b\\5\\2\\2\\2\\u00ea\\u00eb\\7=\\2\\2\\u00eb\\u00ec\")\n        buf.write(\"\\5z>\\2\\u00ec\\u00ed\\7>\\2\\2\\u00ed\\u00ee\\7A\\2\\2\\u00ee\\u00ef\")\n        buf.write(\"\\5\\u0084C\\2\\u00ef\\u00f0\\7B\\2\\2\\u00f0\\u010b\\3\\2\\2\\2\\u00f1\")\n        buf.write(\"\\u00f2\\7=\\2\\2\\u00f2\\u00f3\\5z>\\2\\u00f3\\u00f4\\7>\\2\\2\\u00f4\")\n        buf.write(\"\\u00f5\\7A\\2\\2\\u00f5\\u00f6\\5\\u0084C\\2\\u00f6\\u00f7\\7Z\\2\")\n        buf.write(\"\\2\\u00f7\\u00f8\\7B\\2\\2\\u00f8\\u010b\\3\\2\\2\\2\\u00f9\\u00fa\")\n        buf.write(\"\\7\\3\\2\\2\\u00fa\\u00fb\\7=\\2\\2\\u00fb\\u00fc\\5z>\\2\\u00fc\\u00fd\")\n        buf.write(\"\\7>\\2\\2\\u00fd\\u00fe\\7A\\2\\2\\u00fe\\u00ff\\5\\u0084C\\2\\u00ff\")\n        buf.write(\"\\u0100\\7B\\2\\2\\u0100\\u010b\\3\\2\\2\\2\\u0101\\u0102\\7\\3\\2\\2\")\n        buf.write(\"\\u0102\\u0103\\7=\\2\\2\\u0103\\u0104\\5z>\\2\\u0104\\u0105\\7>\\2\")\n        buf.write(\"\\2\\u0105\\u0106\\7A\\2\\2\\u0106\\u0107\\5\\u0084C\\2\\u0107\\u0108\")\n        buf.write(\"\\7Z\\2\\2\\u0108\\u0109\\7B\\2\\2\\u0109\\u010b\\3\\2\\2\\2\\u010a\\u00e8\")\n        buf.write(\"\\3\\2\\2\\2\\u010a\\u00ea\\3\\2\\2\\2\\u010a\\u00f1\\3\\2\\2\\2\\u010a\")\n        buf.write(\"\\u00f9\\3\\2\\2\\2\\u010a\\u0101\\3\\2\\2\\2\\u010b\\u0123\\3\\2\\2\\2\")\n        buf.write(\"\\u010c\\u010d\\f\\f\\2\\2\\u010d\\u010e\\7?\\2\\2\\u010e\\u010f\\5\")\n        buf.write(\".\\30\\2\\u010f\\u0110\\7@\\2\\2\\u0110\\u0122\\3\\2\\2\\2\\u0111\\u0112\")\n        buf.write(\"\\f\\13\\2\\2\\u0112\\u0114\\7=\\2\\2\\u0113\\u0115\\5\\f\\7\\2\\u0114\")\n        buf.write(\"\\u0113\\3\\2\\2\\2\\u0114\\u0115\\3\\2\\2\\2\\u0115\\u0116\\3\\2\\2\\2\")\n        buf.write(\"\\u0116\\u0122\\7>\\2\\2\\u0117\\u0118\\f\\n\\2\\2\\u0118\\u0119\\7\")\n        buf.write(\"i\\2\\2\\u0119\\u0122\\7k\\2\\2\\u011a\\u011b\\f\\t\\2\\2\\u011b\\u011c\")\n        buf.write(\"\\7h\\2\\2\\u011c\\u0122\\7k\\2\\2\\u011d\\u011e\\f\\b\\2\\2\\u011e\\u0122\")\n        buf.write(\"\\7J\\2\\2\\u011f\\u0120\\f\\7\\2\\2\\u0120\\u0122\\7L\\2\\2\\u0121\\u010c\")\n        buf.write(\"\\3\\2\\2\\2\\u0121\\u0111\\3\\2\\2\\2\\u0121\\u0117\\3\\2\\2\\2\\u0121\")\n        buf.write(\"\\u011a\\3\\2\\2\\2\\u0121\\u011d\\3\\2\\2\\2\\u0121\\u011f\\3\\2\\2\\2\")\n        buf.write(\"\\u0122\\u0125\\3\\2\\2\\2\\u0123\\u0121\\3\\2\\2\\2\\u0123\\u0124\\3\")\n        buf.write(\"\\2\\2\\2\\u0124\\13\\3\\2\\2\\2\\u0125\\u0123\\3\\2\\2\\2\\u0126\\u0127\")\n        buf.write(\"\\b\\7\\1\\2\\u0127\\u0128\\5*\\26\\2\\u0128\\u012e\\3\\2\\2\\2\\u0129\")\n        buf.write(\"\\u012a\\f\\3\\2\\2\\u012a\\u012b\\7Z\\2\\2\\u012b\\u012d\\5*\\26\\2\")\n        buf.write(\"\\u012c\\u0129\\3\\2\\2\\2\\u012d\\u0130\\3\\2\\2\\2\\u012e\\u012c\\3\")\n        buf.write(\"\\2\\2\\2\\u012e\\u012f\\3\\2\\2\\2\\u012f\\r\\3\\2\\2\\2\\u0130\\u012e\")\n        buf.write(\"\\3\\2\\2\\2\\u0131\\u0148\\5\\n\\6\\2\\u0132\\u0133\\7J\\2\\2\\u0133\")\n        buf.write(\"\\u0148\\5\\16\\b\\2\\u0134\\u0135\\7L\\2\\2\\u0135\\u0148\\5\\16\\b\")\n        buf.write(\"\\2\\u0136\\u0137\\5\\20\\t\\2\\u0137\\u0138\\5\\22\\n\\2\\u0138\\u0148\")\n        buf.write(\"\\3\\2\\2\\2\\u0139\\u013a\\7)\\2\\2\\u013a\\u0148\\5\\16\\b\\2\\u013b\")\n        buf.write(\"\\u013c\\7)\\2\\2\\u013c\\u013d\\7=\\2\\2\\u013d\\u013e\\5z>\\2\\u013e\")\n        buf.write(\"\\u013f\\7>\\2\\2\\u013f\\u0148\\3\\2\\2\\2\\u0140\\u0141\\7\\64\\2\\2\")\n        buf.write(\"\\u0141\\u0142\\7=\\2\\2\\u0142\\u0143\\5z>\\2\\u0143\\u0144\\7>\\2\")\n        buf.write(\"\\2\\u0144\\u0148\\3\\2\\2\\2\\u0145\\u0146\\7R\\2\\2\\u0146\\u0148\")\n        buf.write(\"\\7k\\2\\2\\u0147\\u0131\\3\\2\\2\\2\\u0147\\u0132\\3\\2\\2\\2\\u0147\")\n        buf.write(\"\\u0134\\3\\2\\2\\2\\u0147\\u0136\\3\\2\\2\\2\\u0147\\u0139\\3\\2\\2\\2\")\n        buf.write(\"\\u0147\\u013b\\3\\2\\2\\2\\u0147\\u0140\\3\\2\\2\\2\\u0147\\u0145\\3\")\n        buf.write(\"\\2\\2\\2\\u0148\\17\\3\\2\\2\\2\\u0149\\u014a\\t\\2\\2\\2\\u014a\\21\\3\")\n        buf.write(\"\\2\\2\\2\\u014b\\u0158\\5\\16\\b\\2\\u014c\\u014d\\7=\\2\\2\\u014d\\u014e\")\n        buf.write(\"\\5z>\\2\\u014e\\u014f\\7>\\2\\2\\u014f\\u0150\\5\\22\\n\\2\\u0150\\u0158\")\n        buf.write(\"\\3\\2\\2\\2\\u0151\\u0152\\7\\3\\2\\2\\u0152\\u0153\\7=\\2\\2\\u0153\")\n        buf.write(\"\\u0154\\5z>\\2\\u0154\\u0155\\7>\\2\\2\\u0155\\u0156\\5\\22\\n\\2\\u0156\")\n        buf.write(\"\\u0158\\3\\2\\2\\2\\u0157\\u014b\\3\\2\\2\\2\\u0157\\u014c\\3\\2\\2\\2\")\n        buf.write(\"\\u0157\\u0151\\3\\2\\2\\2\\u0158\\23\\3\\2\\2\\2\\u0159\\u015a\\b\\13\")\n        buf.write(\"\\1\\2\\u015a\\u015b\\5\\22\\n\\2\\u015b\\u0167\\3\\2\\2\\2\\u015c\\u015d\")\n        buf.write(\"\\f\\5\\2\\2\\u015d\\u015e\\7M\\2\\2\\u015e\\u0166\\5\\22\\n\\2\\u015f\")\n        buf.write(\"\\u0160\\f\\4\\2\\2\\u0160\\u0161\\7N\\2\\2\\u0161\\u0166\\5\\22\\n\\2\")\n        buf.write(\"\\u0162\\u0163\\f\\3\\2\\2\\u0163\\u0164\\7O\\2\\2\\u0164\\u0166\\5\")\n        buf.write(\"\\22\\n\\2\\u0165\\u015c\\3\\2\\2\\2\\u0165\\u015f\\3\\2\\2\\2\\u0165\")\n        buf.write(\"\\u0162\\3\\2\\2\\2\\u0166\\u0169\\3\\2\\2\\2\\u0167\\u0165\\3\\2\\2\\2\")\n        buf.write(\"\\u0167\\u0168\\3\\2\\2\\2\\u0168\\25\\3\\2\\2\\2\\u0169\\u0167\\3\\2\")\n        buf.write(\"\\2\\2\\u016a\\u016b\\b\\f\\1\\2\\u016b\\u016c\\5\\24\\13\\2\\u016c\\u0175\")\n        buf.write(\"\\3\\2\\2\\2\\u016d\\u016e\\f\\4\\2\\2\\u016e\\u016f\\7I\\2\\2\\u016f\")\n        buf.write(\"\\u0174\\5\\24\\13\\2\\u0170\\u0171\\f\\3\\2\\2\\u0171\\u0172\\7K\\2\")\n        buf.write(\"\\2\\u0172\\u0174\\5\\24\\13\\2\\u0173\\u016d\\3\\2\\2\\2\\u0173\\u0170\")\n        buf.write(\"\\3\\2\\2\\2\\u0174\\u0177\\3\\2\\2\\2\\u0175\\u0173\\3\\2\\2\\2\\u0175\")\n        buf.write(\"\\u0176\\3\\2\\2\\2\\u0176\\27\\3\\2\\2\\2\\u0177\\u0175\\3\\2\\2\\2\\u0178\")\n        buf.write(\"\\u0179\\b\\r\\1\\2\\u0179\\u017a\\5\\26\\f\\2\\u017a\\u0183\\3\\2\\2\")\n        buf.write(\"\\2\\u017b\\u017c\\f\\4\\2\\2\\u017c\\u017d\\7G\\2\\2\\u017d\\u0182\")\n        buf.write(\"\\5\\26\\f\\2\\u017e\\u017f\\f\\3\\2\\2\\u017f\\u0180\\7H\\2\\2\\u0180\")\n        buf.write(\"\\u0182\\5\\26\\f\\2\\u0181\\u017b\\3\\2\\2\\2\\u0181\\u017e\\3\\2\\2\")\n        buf.write(\"\\2\\u0182\\u0185\\3\\2\\2\\2\\u0183\\u0181\\3\\2\\2\\2\\u0183\\u0184\")\n        buf.write(\"\\3\\2\\2\\2\\u0184\\31\\3\\2\\2\\2\\u0185\\u0183\\3\\2\\2\\2\\u0186\\u0187\")\n        buf.write(\"\\b\\16\\1\\2\\u0187\\u0188\\5\\30\\r\\2\\u0188\\u0197\\3\\2\\2\\2\\u0189\")\n        buf.write(\"\\u018a\\f\\6\\2\\2\\u018a\\u018b\\7C\\2\\2\\u018b\\u0196\\5\\30\\r\\2\")\n        buf.write(\"\\u018c\\u018d\\f\\5\\2\\2\\u018d\\u018e\\7E\\2\\2\\u018e\\u0196\\5\")\n        buf.write(\"\\30\\r\\2\\u018f\\u0190\\f\\4\\2\\2\\u0190\\u0191\\7D\\2\\2\\u0191\\u0196\")\n        buf.write(\"\\5\\30\\r\\2\\u0192\\u0193\\f\\3\\2\\2\\u0193\\u0194\\7F\\2\\2\\u0194\")\n        buf.write(\"\\u0196\\5\\30\\r\\2\\u0195\\u0189\\3\\2\\2\\2\\u0195\\u018c\\3\\2\\2\")\n        buf.write(\"\\2\\u0195\\u018f\\3\\2\\2\\2\\u0195\\u0192\\3\\2\\2\\2\\u0196\\u0199\")\n        buf.write(\"\\3\\2\\2\\2\\u0197\\u0195\\3\\2\\2\\2\\u0197\\u0198\\3\\2\\2\\2\\u0198\")\n        buf.write(\"\\33\\3\\2\\2\\2\\u0199\\u0197\\3\\2\\2\\2\\u019a\\u019b\\b\\17\\1\\2\\u019b\")\n        buf.write(\"\\u019c\\5\\32\\16\\2\\u019c\\u01a5\\3\\2\\2\\2\\u019d\\u019e\\f\\4\\2\")\n        buf.write(\"\\2\\u019e\\u019f\\7f\\2\\2\\u019f\\u01a4\\5\\32\\16\\2\\u01a0\\u01a1\")\n        buf.write(\"\\f\\3\\2\\2\\u01a1\\u01a2\\7g\\2\\2\\u01a2\\u01a4\\5\\32\\16\\2\\u01a3\")\n        buf.write(\"\\u019d\\3\\2\\2\\2\\u01a3\\u01a0\\3\\2\\2\\2\\u01a4\\u01a7\\3\\2\\2\\2\")\n        buf.write(\"\\u01a5\\u01a3\\3\\2\\2\\2\\u01a5\\u01a6\\3\\2\\2\\2\\u01a6\\35\\3\\2\")\n        buf.write(\"\\2\\2\\u01a7\\u01a5\\3\\2\\2\\2\\u01a8\\u01a9\\b\\20\\1\\2\\u01a9\\u01aa\")\n        buf.write(\"\\5\\34\\17\\2\\u01aa\\u01b0\\3\\2\\2\\2\\u01ab\\u01ac\\f\\3\\2\\2\\u01ac\")\n        buf.write(\"\\u01ad\\7P\\2\\2\\u01ad\\u01af\\5\\34\\17\\2\\u01ae\\u01ab\\3\\2\\2\")\n        buf.write(\"\\2\\u01af\\u01b2\\3\\2\\2\\2\\u01b0\\u01ae\\3\\2\\2\\2\\u01b0\\u01b1\")\n        buf.write(\"\\3\\2\\2\\2\\u01b1\\37\\3\\2\\2\\2\\u01b2\\u01b0\\3\\2\\2\\2\\u01b3\\u01b4\")\n        buf.write(\"\\b\\21\\1\\2\\u01b4\\u01b5\\5\\36\\20\\2\\u01b5\\u01bb\\3\\2\\2\\2\\u01b6\")\n        buf.write(\"\\u01b7\\f\\3\\2\\2\\u01b7\\u01b8\\7T\\2\\2\\u01b8\\u01ba\\5\\36\\20\")\n        buf.write(\"\\2\\u01b9\\u01b6\\3\\2\\2\\2\\u01ba\\u01bd\\3\\2\\2\\2\\u01bb\\u01b9\")\n        buf.write(\"\\3\\2\\2\\2\\u01bb\\u01bc\\3\\2\\2\\2\\u01bc!\\3\\2\\2\\2\\u01bd\\u01bb\")\n        buf.write(\"\\3\\2\\2\\2\\u01be\\u01bf\\b\\22\\1\\2\\u01bf\\u01c0\\5 \\21\\2\\u01c0\")\n        buf.write(\"\\u01c6\\3\\2\\2\\2\\u01c1\\u01c2\\f\\3\\2\\2\\u01c2\\u01c3\\7Q\\2\\2\")\n        buf.write(\"\\u01c3\\u01c5\\5 \\21\\2\\u01c4\\u01c1\\3\\2\\2\\2\\u01c5\\u01c8\\3\")\n        buf.write(\"\\2\\2\\2\\u01c6\\u01c4\\3\\2\\2\\2\\u01c6\\u01c7\\3\\2\\2\\2\\u01c7#\")\n        buf.write(\"\\3\\2\\2\\2\\u01c8\\u01c6\\3\\2\\2\\2\\u01c9\\u01ca\\b\\23\\1\\2\\u01ca\")\n        buf.write(\"\\u01cb\\5\\\"\\22\\2\\u01cb\\u01d1\\3\\2\\2\\2\\u01cc\\u01cd\\f\\3\\2\")\n        buf.write(\"\\2\\u01cd\\u01ce\\7R\\2\\2\\u01ce\\u01d0\\5\\\"\\22\\2\\u01cf\\u01cc\")\n        buf.write(\"\\3\\2\\2\\2\\u01d0\\u01d3\\3\\2\\2\\2\\u01d1\\u01cf\\3\\2\\2\\2\\u01d1\")\n        buf.write(\"\\u01d2\\3\\2\\2\\2\\u01d2%\\3\\2\\2\\2\\u01d3\\u01d1\\3\\2\\2\\2\\u01d4\")\n        buf.write(\"\\u01d5\\b\\24\\1\\2\\u01d5\\u01d6\\5$\\23\\2\\u01d6\\u01dc\\3\\2\\2\")\n        buf.write(\"\\2\\u01d7\\u01d8\\f\\3\\2\\2\\u01d8\\u01d9\\7S\\2\\2\\u01d9\\u01db\")\n        buf.write(\"\\5$\\23\\2\\u01da\\u01d7\\3\\2\\2\\2\\u01db\\u01de\\3\\2\\2\\2\\u01dc\")\n        buf.write(\"\\u01da\\3\\2\\2\\2\\u01dc\\u01dd\\3\\2\\2\\2\\u01dd\\'\\3\\2\\2\\2\\u01de\")\n        buf.write(\"\\u01dc\\3\\2\\2\\2\\u01df\\u01e5\\5&\\24\\2\\u01e0\\u01e1\\7W\\2\\2\")\n        buf.write(\"\\u01e1\\u01e2\\5.\\30\\2\\u01e2\\u01e3\\7X\\2\\2\\u01e3\\u01e4\\5\")\n        buf.write(\"(\\25\\2\\u01e4\\u01e6\\3\\2\\2\\2\\u01e5\\u01e0\\3\\2\\2\\2\\u01e5\\u01e6\")\n        buf.write(\"\\3\\2\\2\\2\\u01e6)\\3\\2\\2\\2\\u01e7\\u01ed\\5(\\25\\2\\u01e8\\u01e9\")\n        buf.write(\"\\5\\16\\b\\2\\u01e9\\u01ea\\5,\\27\\2\\u01ea\\u01eb\\5*\\26\\2\\u01eb\")\n        buf.write(\"\\u01ed\\3\\2\\2\\2\\u01ec\\u01e7\\3\\2\\2\\2\\u01ec\\u01e8\\3\\2\\2\\2\")\n        buf.write(\"\\u01ed+\\3\\2\\2\\2\\u01ee\\u01ef\\t\\3\\2\\2\\u01ef-\\3\\2\\2\\2\\u01f0\")\n        buf.write(\"\\u01f1\\b\\30\\1\\2\\u01f1\\u01f2\\5*\\26\\2\\u01f2\\u01f8\\3\\2\\2\")\n        buf.write(\"\\2\\u01f3\\u01f4\\f\\3\\2\\2\\u01f4\\u01f5\\7Z\\2\\2\\u01f5\\u01f7\")\n        buf.write(\"\\5*\\26\\2\\u01f6\\u01f3\\3\\2\\2\\2\\u01f7\\u01fa\\3\\2\\2\\2\\u01f8\")\n        buf.write(\"\\u01f6\\3\\2\\2\\2\\u01f8\\u01f9\\3\\2\\2\\2\\u01f9/\\3\\2\\2\\2\\u01fa\")\n        buf.write(\"\\u01f8\\3\\2\\2\\2\\u01fb\\u01fc\\5(\\25\\2\\u01fc\\61\\3\\2\\2\\2\\u01fd\")\n        buf.write(\"\\u01ff\\5\\64\\33\\2\\u01fe\\u0200\\5:\\36\\2\\u01ff\\u01fe\\3\\2\\2\")\n        buf.write(\"\\2\\u01ff\\u0200\\3\\2\\2\\2\\u0200\\u0201\\3\\2\\2\\2\\u0201\\u0202\")\n        buf.write(\"\\7Y\\2\\2\\u0202\\u0205\\3\\2\\2\\2\\u0203\\u0205\\5\\u008cG\\2\\u0204\")\n        buf.write(\"\\u01fd\\3\\2\\2\\2\\u0204\\u0203\\3\\2\\2\\2\\u0205\\63\\3\\2\\2\\2\\u0206\")\n        buf.write(\"\\u0208\\58\\35\\2\\u0207\\u0206\\3\\2\\2\\2\\u0208\\u0209\\3\\2\\2\\2\")\n        buf.write(\"\\u0209\\u0207\\3\\2\\2\\2\\u0209\\u020a\\3\\2\\2\\2\\u020a\\65\\3\\2\")\n        buf.write(\"\\2\\2\\u020b\\u020d\\58\\35\\2\\u020c\\u020b\\3\\2\\2\\2\\u020d\\u020e\")\n        buf.write(\"\\3\\2\\2\\2\\u020e\\u020c\\3\\2\\2\\2\\u020e\\u020f\\3\\2\\2\\2\\u020f\")\n        buf.write(\"\\67\\3\\2\\2\\2\\u0210\\u0216\\5> \\2\\u0211\\u0216\\5@!\\2\\u0212\")\n        buf.write(\"\\u0216\\5Z.\\2\\u0213\\u0216\\5\\\\/\\2\\u0214\\u0216\\5^\\60\\2\\u0215\")\n        buf.write(\"\\u0210\\3\\2\\2\\2\\u0215\\u0211\\3\\2\\2\\2\\u0215\\u0212\\3\\2\\2\\2\")\n        buf.write(\"\\u0215\\u0213\\3\\2\\2\\2\\u0215\\u0214\\3\\2\\2\\2\\u02169\\3\\2\\2\")\n        buf.write(\"\\2\\u0217\\u0218\\b\\36\\1\\2\\u0218\\u0219\\5<\\37\\2\\u0219\\u021f\")\n        buf.write(\"\\3\\2\\2\\2\\u021a\\u021b\\f\\3\\2\\2\\u021b\\u021c\\7Z\\2\\2\\u021c\")\n        buf.write(\"\\u021e\\5<\\37\\2\\u021d\\u021a\\3\\2\\2\\2\\u021e\\u0221\\3\\2\\2\\2\")\n        buf.write(\"\\u021f\\u021d\\3\\2\\2\\2\\u021f\\u0220\\3\\2\\2\\2\\u0220;\\3\\2\\2\")\n        buf.write(\"\\2\\u0221\\u021f\\3\\2\\2\\2\\u0222\\u0228\\5`\\61\\2\\u0223\\u0224\")\n        buf.write(\"\\5`\\61\\2\\u0224\\u0225\\7[\\2\\2\\u0225\\u0226\\5\\u0082B\\2\\u0226\")\n        buf.write(\"\\u0228\\3\\2\\2\\2\\u0227\\u0222\\3\\2\\2\\2\\u0227\\u0223\\3\\2\\2\\2\")\n        buf.write(\"\\u0228=\\3\\2\\2\\2\\u0229\\u022a\\t\\4\\2\\2\\u022a?\\3\\2\\2\\2\\u022b\")\n        buf.write(\"\\u023a\\t\\5\\2\\2\\u022c\\u022d\\7\\3\\2\\2\\u022d\\u022e\\7=\\2\\2\")\n        buf.write(\"\\u022e\\u022f\\t\\6\\2\\2\\u022f\\u023a\\7>\\2\\2\\u0230\\u023a\\5\")\n        buf.write(\"X-\\2\\u0231\\u023a\\5B\\\"\\2\\u0232\\u023a\\5P)\\2\\u0233\\u023a\")\n        buf.write(\"\\5\\u0080A\\2\\u0234\\u0235\\7\\t\\2\\2\\u0235\\u0236\\7=\\2\\2\\u0236\")\n        buf.write(\"\\u0237\\5\\60\\31\\2\\u0237\\u0238\\7>\\2\\2\\u0238\\u023a\\3\\2\\2\")\n        buf.write(\"\\2\\u0239\\u022b\\3\\2\\2\\2\\u0239\\u022c\\3\\2\\2\\2\\u0239\\u0230\")\n        buf.write(\"\\3\\2\\2\\2\\u0239\\u0231\\3\\2\\2\\2\\u0239\\u0232\\3\\2\\2\\2\\u0239\")\n        buf.write(\"\\u0233\\3\\2\\2\\2\\u0239\\u0234\\3\\2\\2\\2\\u023aA\\3\\2\\2\\2\\u023b\")\n        buf.write(\"\\u023d\\5D#\\2\\u023c\\u023e\\7k\\2\\2\\u023d\\u023c\\3\\2\\2\\2\\u023d\")\n        buf.write(\"\\u023e\\3\\2\\2\\2\\u023e\\u023f\\3\\2\\2\\2\\u023f\\u0240\\7A\\2\\2\")\n        buf.write(\"\\u0240\\u0241\\5F$\\2\\u0241\\u0242\\7B\\2\\2\\u0242\\u0247\\3\\2\")\n        buf.write(\"\\2\\2\\u0243\\u0244\\5D#\\2\\u0244\\u0245\\7k\\2\\2\\u0245\\u0247\")\n        buf.write(\"\\3\\2\\2\\2\\u0246\\u023b\\3\\2\\2\\2\\u0246\\u0243\\3\\2\\2\\2\\u0247\")\n        buf.write(\"C\\3\\2\\2\\2\\u0248\\u0249\\t\\7\\2\\2\\u0249E\\3\\2\\2\\2\\u024a\\u024b\")\n        buf.write(\"\\b$\\1\\2\\u024b\\u024c\\5H%\\2\\u024c\\u0251\\3\\2\\2\\2\\u024d\\u024e\")\n        buf.write(\"\\f\\3\\2\\2\\u024e\\u0250\\5H%\\2\\u024f\\u024d\\3\\2\\2\\2\\u0250\\u0253\")\n        buf.write(\"\\3\\2\\2\\2\\u0251\\u024f\\3\\2\\2\\2\\u0251\\u0252\\3\\2\\2\\2\\u0252\")\n        buf.write(\"G\\3\\2\\2\\2\\u0253\\u0251\\3\\2\\2\\2\\u0254\\u0256\\5J&\\2\\u0255\")\n        buf.write(\"\\u0257\\5L\\'\\2\\u0256\\u0255\\3\\2\\2\\2\\u0256\\u0257\\3\\2\\2\\2\")\n        buf.write(\"\\u0257\\u0258\\3\\2\\2\\2\\u0258\\u0259\\7Y\\2\\2\\u0259\\u025c\\3\")\n        buf.write(\"\\2\\2\\2\\u025a\\u025c\\5\\u008cG\\2\\u025b\\u0254\\3\\2\\2\\2\\u025b\")\n        buf.write(\"\\u025a\\3\\2\\2\\2\\u025cI\\3\\2\\2\\2\\u025d\\u025f\\5@!\\2\\u025e\")\n        buf.write(\"\\u0260\\5J&\\2\\u025f\\u025e\\3\\2\\2\\2\\u025f\\u0260\\3\\2\\2\\2\\u0260\")\n        buf.write(\"\\u0266\\3\\2\\2\\2\\u0261\\u0263\\5Z.\\2\\u0262\\u0264\\5J&\\2\\u0263\")\n        buf.write(\"\\u0262\\3\\2\\2\\2\\u0263\\u0264\\3\\2\\2\\2\\u0264\\u0266\\3\\2\\2\\2\")\n        buf.write(\"\\u0265\\u025d\\3\\2\\2\\2\\u0265\\u0261\\3\\2\\2\\2\\u0266K\\3\\2\\2\")\n        buf.write(\"\\2\\u0267\\u0268\\b\\'\\1\\2\\u0268\\u0269\\5N(\\2\\u0269\\u026f\\3\")\n        buf.write(\"\\2\\2\\2\\u026a\\u026b\\f\\3\\2\\2\\u026b\\u026c\\7Z\\2\\2\\u026c\\u026e\")\n        buf.write(\"\\5N(\\2\\u026d\\u026a\\3\\2\\2\\2\\u026e\\u0271\\3\\2\\2\\2\\u026f\\u026d\")\n        buf.write(\"\\3\\2\\2\\2\\u026f\\u0270\\3\\2\\2\\2\\u0270M\\3\\2\\2\\2\\u0271\\u026f\")\n        buf.write(\"\\3\\2\\2\\2\\u0272\\u0279\\5`\\61\\2\\u0273\\u0275\\5`\\61\\2\\u0274\")\n        buf.write(\"\\u0273\\3\\2\\2\\2\\u0274\\u0275\\3\\2\\2\\2\\u0275\\u0276\\3\\2\\2\\2\")\n        buf.write(\"\\u0276\\u0277\\7X\\2\\2\\u0277\\u0279\\5\\60\\31\\2\\u0278\\u0272\")\n        buf.write(\"\\3\\2\\2\\2\\u0278\\u0274\\3\\2\\2\\2\\u0279O\\3\\2\\2\\2\\u027a\\u027c\")\n        buf.write(\"\\7\\33\\2\\2\\u027b\\u027d\\7k\\2\\2\\u027c\\u027b\\3\\2\\2\\2\\u027c\")\n        buf.write(\"\\u027d\\3\\2\\2\\2\\u027d\\u027e\\3\\2\\2\\2\\u027e\\u027f\\7A\\2\\2\")\n        buf.write(\"\\u027f\\u0280\\5R*\\2\\u0280\\u0281\\7B\\2\\2\\u0281\\u028e\\3\\2\")\n        buf.write(\"\\2\\2\\u0282\\u0284\\7\\33\\2\\2\\u0283\\u0285\\7k\\2\\2\\u0284\\u0283\")\n        buf.write(\"\\3\\2\\2\\2\\u0284\\u0285\\3\\2\\2\\2\\u0285\\u0286\\3\\2\\2\\2\\u0286\")\n        buf.write(\"\\u0287\\7A\\2\\2\\u0287\\u0288\\5R*\\2\\u0288\\u0289\\7Z\\2\\2\\u0289\")\n        buf.write(\"\\u028a\\7B\\2\\2\\u028a\\u028e\\3\\2\\2\\2\\u028b\\u028c\\7\\33\\2\\2\")\n        buf.write(\"\\u028c\\u028e\\7k\\2\\2\\u028d\\u027a\\3\\2\\2\\2\\u028d\\u0282\\3\")\n        buf.write(\"\\2\\2\\2\\u028d\\u028b\\3\\2\\2\\2\\u028eQ\\3\\2\\2\\2\\u028f\\u0290\")\n        buf.write(\"\\b*\\1\\2\\u0290\\u0291\\5T+\\2\\u0291\\u0297\\3\\2\\2\\2\\u0292\\u0293\")\n        buf.write(\"\\f\\3\\2\\2\\u0293\\u0294\\7Z\\2\\2\\u0294\\u0296\\5T+\\2\\u0295\\u0292\")\n        buf.write(\"\\3\\2\\2\\2\\u0296\\u0299\\3\\2\\2\\2\\u0297\\u0295\\3\\2\\2\\2\\u0297\")\n        buf.write(\"\\u0298\\3\\2\\2\\2\\u0298S\\3\\2\\2\\2\\u0299\\u0297\\3\\2\\2\\2\\u029a\")\n        buf.write(\"\\u02a0\\5V,\\2\\u029b\\u029c\\5V,\\2\\u029c\\u029d\\7[\\2\\2\\u029d\")\n        buf.write(\"\\u029e\\5\\60\\31\\2\\u029e\\u02a0\\3\\2\\2\\2\\u029f\\u029a\\3\\2\\2\")\n        buf.write(\"\\2\\u029f\\u029b\\3\\2\\2\\2\\u02a0U\\3\\2\\2\\2\\u02a1\\u02a2\\7k\\2\")\n        buf.write(\"\\2\\u02a2W\\3\\2\\2\\2\\u02a3\\u02a4\\7\\65\\2\\2\\u02a4\\u02a5\\7=\")\n        buf.write(\"\\2\\2\\u02a5\\u02a6\\5z>\\2\\u02a6\\u02a7\\7>\\2\\2\\u02a7Y\\3\\2\\2\")\n        buf.write(\"\\2\\u02a8\\u02a9\\t\\b\\2\\2\\u02a9[\\3\\2\\2\\2\\u02aa\\u02b1\\t\\t\")\n        buf.write(\"\\2\\2\\u02ab\\u02b1\\5f\\64\\2\\u02ac\\u02ad\\7\\f\\2\\2\\u02ad\\u02ae\")\n        buf.write(\"\\7=\\2\\2\\u02ae\\u02af\\7k\\2\\2\\u02af\\u02b1\\7>\\2\\2\\u02b0\\u02aa\")\n        buf.write(\"\\3\\2\\2\\2\\u02b0\\u02ab\\3\\2\\2\\2\\u02b0\\u02ac\\3\\2\\2\\2\\u02b1\")\n        buf.write(\"]\\3\\2\\2\\2\\u02b2\\u02b3\\7\\63\\2\\2\\u02b3\\u02b4\\7=\\2\\2\\u02b4\")\n        buf.write(\"\\u02b5\\5z>\\2\\u02b5\\u02b6\\7>\\2\\2\\u02b6\\u02bd\\3\\2\\2\\2\\u02b7\")\n        buf.write(\"\\u02b8\\7\\63\\2\\2\\u02b8\\u02b9\\7=\\2\\2\\u02b9\\u02ba\\5\\60\\31\")\n        buf.write(\"\\2\\u02ba\\u02bb\\7>\\2\\2\\u02bb\\u02bd\\3\\2\\2\\2\\u02bc\\u02b2\")\n        buf.write(\"\\3\\2\\2\\2\\u02bc\\u02b7\\3\\2\\2\\2\\u02bd_\\3\\2\\2\\2\\u02be\\u02c0\")\n        buf.write(\"\\5n8\\2\\u02bf\\u02be\\3\\2\\2\\2\\u02bf\\u02c0\\3\\2\\2\\2\\u02c0\\u02c1\")\n        buf.write(\"\\3\\2\\2\\2\\u02c1\\u02c5\\5b\\62\\2\\u02c2\\u02c4\\5d\\63\\2\\u02c3\")\n        buf.write(\"\\u02c2\\3\\2\\2\\2\\u02c4\\u02c7\\3\\2\\2\\2\\u02c5\\u02c3\\3\\2\\2\\2\")\n        buf.write(\"\\u02c5\\u02c6\\3\\2\\2\\2\\u02c6a\\3\\2\\2\\2\\u02c7\\u02c5\\3\\2\\2\")\n        buf.write(\"\\2\\u02c8\\u02c9\\b\\62\\1\\2\\u02c9\\u02cf\\7k\\2\\2\\u02ca\\u02cb\")\n        buf.write(\"\\7=\\2\\2\\u02cb\\u02cc\\5`\\61\\2\\u02cc\\u02cd\\7>\\2\\2\\u02cd\\u02cf\")\n        buf.write(\"\\3\\2\\2\\2\\u02ce\\u02c8\\3\\2\\2\\2\\u02ce\\u02ca\\3\\2\\2\\2\\u02cf\")\n        buf.write(\"\\u02fd\\3\\2\\2\\2\\u02d0\\u02d1\\f\\b\\2\\2\\u02d1\\u02d3\\7?\\2\\2\")\n        buf.write(\"\\u02d2\\u02d4\\5p9\\2\\u02d3\\u02d2\\3\\2\\2\\2\\u02d3\\u02d4\\3\\2\")\n        buf.write(\"\\2\\2\\u02d4\\u02d6\\3\\2\\2\\2\\u02d5\\u02d7\\5*\\26\\2\\u02d6\\u02d5\")\n        buf.write(\"\\3\\2\\2\\2\\u02d6\\u02d7\\3\\2\\2\\2\\u02d7\\u02d8\\3\\2\\2\\2\\u02d8\")\n        buf.write(\"\\u02fc\\7@\\2\\2\\u02d9\\u02da\\f\\7\\2\\2\\u02da\\u02db\\7?\\2\\2\\u02db\")\n        buf.write(\"\\u02dd\\7*\\2\\2\\u02dc\\u02de\\5p9\\2\\u02dd\\u02dc\\3\\2\\2\\2\\u02dd\")\n        buf.write(\"\\u02de\\3\\2\\2\\2\\u02de\\u02df\\3\\2\\2\\2\\u02df\\u02e0\\5*\\26\\2\")\n        buf.write(\"\\u02e0\\u02e1\\7@\\2\\2\\u02e1\\u02fc\\3\\2\\2\\2\\u02e2\\u02e3\\f\")\n        buf.write(\"\\6\\2\\2\\u02e3\\u02e4\\7?\\2\\2\\u02e4\\u02e5\\5p9\\2\\u02e5\\u02e6\")\n        buf.write(\"\\7*\\2\\2\\u02e6\\u02e7\\5*\\26\\2\\u02e7\\u02e8\\7@\\2\\2\\u02e8\\u02fc\")\n        buf.write(\"\\3\\2\\2\\2\\u02e9\\u02ea\\f\\5\\2\\2\\u02ea\\u02ec\\7?\\2\\2\\u02eb\")\n        buf.write(\"\\u02ed\\5p9\\2\\u02ec\\u02eb\\3\\2\\2\\2\\u02ec\\u02ed\\3\\2\\2\\2\\u02ed\")\n        buf.write(\"\\u02ee\\3\\2\\2\\2\\u02ee\\u02ef\\7M\\2\\2\\u02ef\\u02fc\\7@\\2\\2\\u02f0\")\n        buf.write(\"\\u02f1\\f\\4\\2\\2\\u02f1\\u02f2\\7=\\2\\2\\u02f2\\u02f3\\5r:\\2\\u02f3\")\n        buf.write(\"\\u02f4\\7>\\2\\2\\u02f4\\u02fc\\3\\2\\2\\2\\u02f5\\u02f6\\f\\3\\2\\2\")\n        buf.write(\"\\u02f6\\u02f8\\7=\\2\\2\\u02f7\\u02f9\\5x=\\2\\u02f8\\u02f7\\3\\2\")\n        buf.write(\"\\2\\2\\u02f8\\u02f9\\3\\2\\2\\2\\u02f9\\u02fa\\3\\2\\2\\2\\u02fa\\u02fc\")\n        buf.write(\"\\7>\\2\\2\\u02fb\\u02d0\\3\\2\\2\\2\\u02fb\\u02d9\\3\\2\\2\\2\\u02fb\")\n        buf.write(\"\\u02e2\\3\\2\\2\\2\\u02fb\\u02e9\\3\\2\\2\\2\\u02fb\\u02f0\\3\\2\\2\\2\")\n        buf.write(\"\\u02fb\\u02f5\\3\\2\\2\\2\\u02fc\\u02ff\\3\\2\\2\\2\\u02fd\\u02fb\\3\")\n        buf.write(\"\\2\\2\\2\\u02fd\\u02fe\\3\\2\\2\\2\\u02fec\\3\\2\\2\\2\\u02ff\\u02fd\")\n        buf.write(\"\\3\\2\\2\\2\\u0300\\u0301\\7\\r\\2\\2\\u0301\\u0303\\7=\\2\\2\\u0302\")\n        buf.write(\"\\u0304\\7m\\2\\2\\u0303\\u0302\\3\\2\\2\\2\\u0304\\u0305\\3\\2\\2\\2\")\n        buf.write(\"\\u0305\\u0303\\3\\2\\2\\2\\u0305\\u0306\\3\\2\\2\\2\\u0306\\u0307\\3\")\n        buf.write(\"\\2\\2\\2\\u0307\\u030a\\7>\\2\\2\\u0308\\u030a\\5f\\64\\2\\u0309\\u0300\")\n        buf.write(\"\\3\\2\\2\\2\\u0309\\u0308\\3\\2\\2\\2\\u030ae\\3\\2\\2\\2\\u030b\\u030c\")\n        buf.write(\"\\7\\16\\2\\2\\u030c\\u030d\\7=\\2\\2\\u030d\\u030e\\7=\\2\\2\\u030e\")\n        buf.write(\"\\u030f\\5h\\65\\2\\u030f\\u0310\\7>\\2\\2\\u0310\\u0311\\7>\\2\\2\\u0311\")\n        buf.write(\"g\\3\\2\\2\\2\\u0312\\u0317\\5j\\66\\2\\u0313\\u0314\\7Z\\2\\2\\u0314\")\n        buf.write(\"\\u0316\\5j\\66\\2\\u0315\\u0313\\3\\2\\2\\2\\u0316\\u0319\\3\\2\\2\\2\")\n        buf.write(\"\\u0317\\u0315\\3\\2\\2\\2\\u0317\\u0318\\3\\2\\2\\2\\u0318\\u031c\\3\")\n        buf.write(\"\\2\\2\\2\\u0319\\u0317\\3\\2\\2\\2\\u031a\\u031c\\3\\2\\2\\2\\u031b\\u0312\")\n        buf.write(\"\\3\\2\\2\\2\\u031b\\u031a\\3\\2\\2\\2\\u031ci\\3\\2\\2\\2\\u031d\\u0323\")\n        buf.write(\"\\n\\n\\2\\2\\u031e\\u0320\\7=\\2\\2\\u031f\\u0321\\5\\f\\7\\2\\u0320\")\n        buf.write(\"\\u031f\\3\\2\\2\\2\\u0320\\u0321\\3\\2\\2\\2\\u0321\\u0322\\3\\2\\2\\2\")\n        buf.write(\"\\u0322\\u0324\\7>\\2\\2\\u0323\\u031e\\3\\2\\2\\2\\u0323\\u0324\\3\")\n        buf.write(\"\\2\\2\\2\\u0324\\u0327\\3\\2\\2\\2\\u0325\\u0327\\3\\2\\2\\2\\u0326\\u031d\")\n        buf.write(\"\\3\\2\\2\\2\\u0326\\u0325\\3\\2\\2\\2\\u0327k\\3\\2\\2\\2\\u0328\\u032e\")\n        buf.write(\"\\n\\13\\2\\2\\u0329\\u032a\\7=\\2\\2\\u032a\\u032b\\5l\\67\\2\\u032b\")\n        buf.write(\"\\u032c\\7>\\2\\2\\u032c\\u032e\\3\\2\\2\\2\\u032d\\u0328\\3\\2\\2\\2\")\n        buf.write(\"\\u032d\\u0329\\3\\2\\2\\2\\u032e\\u0331\\3\\2\\2\\2\\u032f\\u032d\\3\")\n        buf.write(\"\\2\\2\\2\\u032f\\u0330\\3\\2\\2\\2\\u0330m\\3\\2\\2\\2\\u0331\\u032f\")\n        buf.write(\"\\3\\2\\2\\2\\u0332\\u0334\\7M\\2\\2\\u0333\\u0335\\5p9\\2\\u0334\\u0333\")\n        buf.write(\"\\3\\2\\2\\2\\u0334\\u0335\\3\\2\\2\\2\\u0335\\u0345\\3\\2\\2\\2\\u0336\")\n        buf.write(\"\\u0338\\7M\\2\\2\\u0337\\u0339\\5p9\\2\\u0338\\u0337\\3\\2\\2\\2\\u0338\")\n        buf.write(\"\\u0339\\3\\2\\2\\2\\u0339\\u033a\\3\\2\\2\\2\\u033a\\u0345\\5n8\\2\\u033b\")\n        buf.write(\"\\u033d\\7T\\2\\2\\u033c\\u033e\\5p9\\2\\u033d\\u033c\\3\\2\\2\\2\\u033d\")\n        buf.write(\"\\u033e\\3\\2\\2\\2\\u033e\\u0345\\3\\2\\2\\2\\u033f\\u0341\\7T\\2\\2\")\n        buf.write(\"\\u0340\\u0342\\5p9\\2\\u0341\\u0340\\3\\2\\2\\2\\u0341\\u0342\\3\\2\")\n        buf.write(\"\\2\\2\\u0342\\u0343\\3\\2\\2\\2\\u0343\\u0345\\5n8\\2\\u0344\\u0332\")\n        buf.write(\"\\3\\2\\2\\2\\u0344\\u0336\\3\\2\\2\\2\\u0344\\u033b\\3\\2\\2\\2\\u0344\")\n        buf.write(\"\\u033f\\3\\2\\2\\2\\u0345o\\3\\2\\2\\2\\u0346\\u0347\\b9\\1\\2\\u0347\")\n        buf.write(\"\\u0348\\5Z.\\2\\u0348\\u034d\\3\\2\\2\\2\\u0349\\u034a\\f\\3\\2\\2\\u034a\")\n        buf.write(\"\\u034c\\5Z.\\2\\u034b\\u0349\\3\\2\\2\\2\\u034c\\u034f\\3\\2\\2\\2\\u034d\")\n        buf.write(\"\\u034b\\3\\2\\2\\2\\u034d\\u034e\\3\\2\\2\\2\\u034eq\\3\\2\\2\\2\\u034f\")\n        buf.write(\"\\u034d\\3\\2\\2\\2\\u0350\\u0356\\5t;\\2\\u0351\\u0352\\5t;\\2\\u0352\")\n        buf.write(\"\\u0353\\7Z\\2\\2\\u0353\\u0354\\7j\\2\\2\\u0354\\u0356\\3\\2\\2\\2\\u0355\")\n        buf.write(\"\\u0350\\3\\2\\2\\2\\u0355\\u0351\\3\\2\\2\\2\\u0356s\\3\\2\\2\\2\\u0357\")\n        buf.write(\"\\u0358\\b;\\1\\2\\u0358\\u0359\\5v<\\2\\u0359\\u035f\\3\\2\\2\\2\\u035a\")\n        buf.write(\"\\u035b\\f\\3\\2\\2\\u035b\\u035c\\7Z\\2\\2\\u035c\\u035e\\5v<\\2\\u035d\")\n        buf.write(\"\\u035a\\3\\2\\2\\2\\u035e\\u0361\\3\\2\\2\\2\\u035f\\u035d\\3\\2\\2\\2\")\n        buf.write(\"\\u035f\\u0360\\3\\2\\2\\2\\u0360u\\3\\2\\2\\2\\u0361\\u035f\\3\\2\\2\")\n        buf.write(\"\\2\\u0362\\u0363\\5\\64\\33\\2\\u0363\\u0364\\5`\\61\\2\\u0364\\u036a\")\n        buf.write(\"\\3\\2\\2\\2\\u0365\\u0367\\5\\66\\34\\2\\u0366\\u0368\\5|?\\2\\u0367\")\n        buf.write(\"\\u0366\\3\\2\\2\\2\\u0367\\u0368\\3\\2\\2\\2\\u0368\\u036a\\3\\2\\2\\2\")\n        buf.write(\"\\u0369\\u0362\\3\\2\\2\\2\\u0369\\u0365\\3\\2\\2\\2\\u036aw\\3\\2\\2\")\n        buf.write(\"\\2\\u036b\\u036c\\b=\\1\\2\\u036c\\u036d\\7k\\2\\2\\u036d\\u0373\\3\")\n        buf.write(\"\\2\\2\\2\\u036e\\u036f\\f\\3\\2\\2\\u036f\\u0370\\7Z\\2\\2\\u0370\\u0372\")\n        buf.write(\"\\7k\\2\\2\\u0371\\u036e\\3\\2\\2\\2\\u0372\\u0375\\3\\2\\2\\2\\u0373\")\n        buf.write(\"\\u0371\\3\\2\\2\\2\\u0373\\u0374\\3\\2\\2\\2\\u0374y\\3\\2\\2\\2\\u0375\")\n        buf.write(\"\\u0373\\3\\2\\2\\2\\u0376\\u0378\\5J&\\2\\u0377\\u0379\\5|?\\2\\u0378\")\n        buf.write(\"\\u0377\\3\\2\\2\\2\\u0378\\u0379\\3\\2\\2\\2\\u0379{\\3\\2\\2\\2\\u037a\")\n        buf.write(\"\\u0386\\5n8\\2\\u037b\\u037d\\5n8\\2\\u037c\\u037b\\3\\2\\2\\2\\u037c\")\n        buf.write(\"\\u037d\\3\\2\\2\\2\\u037d\\u037e\\3\\2\\2\\2\\u037e\\u0382\\5~@\\2\\u037f\")\n        buf.write(\"\\u0381\\5d\\63\\2\\u0380\\u037f\\3\\2\\2\\2\\u0381\\u0384\\3\\2\\2\\2\")\n        buf.write(\"\\u0382\\u0380\\3\\2\\2\\2\\u0382\\u0383\\3\\2\\2\\2\\u0383\\u0386\\3\")\n        buf.write(\"\\2\\2\\2\\u0384\\u0382\\3\\2\\2\\2\\u0385\\u037a\\3\\2\\2\\2\\u0385\\u037c\")\n        buf.write(\"\\3\\2\\2\\2\\u0386}\\3\\2\\2\\2\\u0387\\u0388\\b@\\1\\2\\u0388\\u0389\")\n        buf.write(\"\\7=\\2\\2\\u0389\\u038a\\5|?\\2\\u038a\\u038e\\7>\\2\\2\\u038b\\u038d\")\n        buf.write(\"\\5d\\63\\2\\u038c\\u038b\\3\\2\\2\\2\\u038d\\u0390\\3\\2\\2\\2\\u038e\")\n        buf.write(\"\\u038c\\3\\2\\2\\2\\u038e\\u038f\\3\\2\\2\\2\\u038f\\u03b6\\3\\2\\2\\2\")\n        buf.write(\"\\u0390\\u038e\\3\\2\\2\\2\\u0391\\u0393\\7?\\2\\2\\u0392\\u0394\\5\")\n        buf.write(\"p9\\2\\u0393\\u0392\\3\\2\\2\\2\\u0393\\u0394\\3\\2\\2\\2\\u0394\\u0396\")\n        buf.write(\"\\3\\2\\2\\2\\u0395\\u0397\\5*\\26\\2\\u0396\\u0395\\3\\2\\2\\2\\u0396\")\n        buf.write(\"\\u0397\\3\\2\\2\\2\\u0397\\u0398\\3\\2\\2\\2\\u0398\\u03b6\\7@\\2\\2\")\n        buf.write(\"\\u0399\\u039a\\7?\\2\\2\\u039a\\u039c\\7*\\2\\2\\u039b\\u039d\\5p\")\n        buf.write(\"9\\2\\u039c\\u039b\\3\\2\\2\\2\\u039c\\u039d\\3\\2\\2\\2\\u039d\\u039e\")\n        buf.write(\"\\3\\2\\2\\2\\u039e\\u039f\\5*\\26\\2\\u039f\\u03a0\\7@\\2\\2\\u03a0\")\n        buf.write(\"\\u03b6\\3\\2\\2\\2\\u03a1\\u03a2\\7?\\2\\2\\u03a2\\u03a3\\5p9\\2\\u03a3\")\n        buf.write(\"\\u03a4\\7*\\2\\2\\u03a4\\u03a5\\5*\\26\\2\\u03a5\\u03a6\\7@\\2\\2\\u03a6\")\n        buf.write(\"\\u03b6\\3\\2\\2\\2\\u03a7\\u03a8\\7?\\2\\2\\u03a8\\u03a9\\7M\\2\\2\\u03a9\")\n        buf.write(\"\\u03b6\\7@\\2\\2\\u03aa\\u03ac\\7=\\2\\2\\u03ab\\u03ad\\5r:\\2\\u03ac\")\n        buf.write(\"\\u03ab\\3\\2\\2\\2\\u03ac\\u03ad\\3\\2\\2\\2\\u03ad\\u03ae\\3\\2\\2\\2\")\n        buf.write(\"\\u03ae\\u03b2\\7>\\2\\2\\u03af\\u03b1\\5d\\63\\2\\u03b0\\u03af\\3\")\n        buf.write(\"\\2\\2\\2\\u03b1\\u03b4\\3\\2\\2\\2\\u03b2\\u03b0\\3\\2\\2\\2\\u03b2\\u03b3\")\n        buf.write(\"\\3\\2\\2\\2\\u03b3\\u03b6\\3\\2\\2\\2\\u03b4\\u03b2\\3\\2\\2\\2\\u03b5\")\n        buf.write(\"\\u0387\\3\\2\\2\\2\\u03b5\\u0391\\3\\2\\2\\2\\u03b5\\u0399\\3\\2\\2\\2\")\n        buf.write(\"\\u03b5\\u03a1\\3\\2\\2\\2\\u03b5\\u03a7\\3\\2\\2\\2\\u03b5\\u03aa\\3\")\n        buf.write(\"\\2\\2\\2\\u03b6\\u03e2\\3\\2\\2\\2\\u03b7\\u03b8\\f\\7\\2\\2\\u03b8\\u03ba\")\n        buf.write(\"\\7?\\2\\2\\u03b9\\u03bb\\5p9\\2\\u03ba\\u03b9\\3\\2\\2\\2\\u03ba\\u03bb\")\n        buf.write(\"\\3\\2\\2\\2\\u03bb\\u03bd\\3\\2\\2\\2\\u03bc\\u03be\\5*\\26\\2\\u03bd\")\n        buf.write(\"\\u03bc\\3\\2\\2\\2\\u03bd\\u03be\\3\\2\\2\\2\\u03be\\u03bf\\3\\2\\2\\2\")\n        buf.write(\"\\u03bf\\u03e1\\7@\\2\\2\\u03c0\\u03c1\\f\\6\\2\\2\\u03c1\\u03c2\\7\")\n        buf.write(\"?\\2\\2\\u03c2\\u03c4\\7*\\2\\2\\u03c3\\u03c5\\5p9\\2\\u03c4\\u03c3\")\n        buf.write(\"\\3\\2\\2\\2\\u03c4\\u03c5\\3\\2\\2\\2\\u03c5\\u03c6\\3\\2\\2\\2\\u03c6\")\n        buf.write(\"\\u03c7\\5*\\26\\2\\u03c7\\u03c8\\7@\\2\\2\\u03c8\\u03e1\\3\\2\\2\\2\")\n        buf.write(\"\\u03c9\\u03ca\\f\\5\\2\\2\\u03ca\\u03cb\\7?\\2\\2\\u03cb\\u03cc\\5\")\n        buf.write(\"p9\\2\\u03cc\\u03cd\\7*\\2\\2\\u03cd\\u03ce\\5*\\26\\2\\u03ce\\u03cf\")\n        buf.write(\"\\7@\\2\\2\\u03cf\\u03e1\\3\\2\\2\\2\\u03d0\\u03d1\\f\\4\\2\\2\\u03d1\")\n        buf.write(\"\\u03d2\\7?\\2\\2\\u03d2\\u03d3\\7M\\2\\2\\u03d3\\u03e1\\7@\\2\\2\\u03d4\")\n        buf.write(\"\\u03d5\\f\\3\\2\\2\\u03d5\\u03d7\\7=\\2\\2\\u03d6\\u03d8\\5r:\\2\\u03d7\")\n        buf.write(\"\\u03d6\\3\\2\\2\\2\\u03d7\\u03d8\\3\\2\\2\\2\\u03d8\\u03d9\\3\\2\\2\\2\")\n        buf.write(\"\\u03d9\\u03dd\\7>\\2\\2\\u03da\\u03dc\\5d\\63\\2\\u03db\\u03da\\3\")\n        buf.write(\"\\2\\2\\2\\u03dc\\u03df\\3\\2\\2\\2\\u03dd\\u03db\\3\\2\\2\\2\\u03dd\\u03de\")\n        buf.write(\"\\3\\2\\2\\2\\u03de\\u03e1\\3\\2\\2\\2\\u03df\\u03dd\\3\\2\\2\\2\\u03e0\")\n        buf.write(\"\\u03b7\\3\\2\\2\\2\\u03e0\\u03c0\\3\\2\\2\\2\\u03e0\\u03c9\\3\\2\\2\\2\")\n        buf.write(\"\\u03e0\\u03d0\\3\\2\\2\\2\\u03e0\\u03d4\\3\\2\\2\\2\\u03e1\\u03e4\\3\")\n        buf.write(\"\\2\\2\\2\\u03e2\\u03e0\\3\\2\\2\\2\\u03e2\\u03e3\\3\\2\\2\\2\\u03e3\\177\")\n        buf.write(\"\\3\\2\\2\\2\\u03e4\\u03e2\\3\\2\\2\\2\\u03e5\\u03e6\\7k\\2\\2\\u03e6\")\n        buf.write(\"\\u0081\\3\\2\\2\\2\\u03e7\\u03f2\\5*\\26\\2\\u03e8\\u03e9\\7A\\2\\2\")\n        buf.write(\"\\u03e9\\u03ea\\5\\u0084C\\2\\u03ea\\u03eb\\7B\\2\\2\\u03eb\\u03f2\")\n        buf.write(\"\\3\\2\\2\\2\\u03ec\\u03ed\\7A\\2\\2\\u03ed\\u03ee\\5\\u0084C\\2\\u03ee\")\n        buf.write(\"\\u03ef\\7Z\\2\\2\\u03ef\\u03f0\\7B\\2\\2\\u03f0\\u03f2\\3\\2\\2\\2\\u03f1\")\n        buf.write(\"\\u03e7\\3\\2\\2\\2\\u03f1\\u03e8\\3\\2\\2\\2\\u03f1\\u03ec\\3\\2\\2\\2\")\n        buf.write(\"\\u03f2\\u0083\\3\\2\\2\\2\\u03f3\\u03f5\\bC\\1\\2\\u03f4\\u03f6\\5\")\n        buf.write(\"\\u0086D\\2\\u03f5\\u03f4\\3\\2\\2\\2\\u03f5\\u03f6\\3\\2\\2\\2\\u03f6\")\n        buf.write(\"\\u03f7\\3\\2\\2\\2\\u03f7\\u03f8\\5\\u0082B\\2\\u03f8\\u0401\\3\\2\")\n        buf.write(\"\\2\\2\\u03f9\\u03fa\\f\\3\\2\\2\\u03fa\\u03fc\\7Z\\2\\2\\u03fb\\u03fd\")\n        buf.write(\"\\5\\u0086D\\2\\u03fc\\u03fb\\3\\2\\2\\2\\u03fc\\u03fd\\3\\2\\2\\2\\u03fd\")\n        buf.write(\"\\u03fe\\3\\2\\2\\2\\u03fe\\u0400\\5\\u0082B\\2\\u03ff\\u03f9\\3\\2\")\n        buf.write(\"\\2\\2\\u0400\\u0403\\3\\2\\2\\2\\u0401\\u03ff\\3\\2\\2\\2\\u0401\\u0402\")\n        buf.write(\"\\3\\2\\2\\2\\u0402\\u0085\\3\\2\\2\\2\\u0403\\u0401\\3\\2\\2\\2\\u0404\")\n        buf.write(\"\\u0405\\5\\u0088E\\2\\u0405\\u0406\\7[\\2\\2\\u0406\\u0087\\3\\2\\2\")\n        buf.write(\"\\2\\u0407\\u0408\\bE\\1\\2\\u0408\\u0409\\5\\u008aF\\2\\u0409\\u040e\")\n        buf.write(\"\\3\\2\\2\\2\\u040a\\u040b\\f\\3\\2\\2\\u040b\\u040d\\5\\u008aF\\2\\u040c\")\n        buf.write(\"\\u040a\\3\\2\\2\\2\\u040d\\u0410\\3\\2\\2\\2\\u040e\\u040c\\3\\2\\2\\2\")\n        buf.write(\"\\u040e\\u040f\\3\\2\\2\\2\\u040f\\u0089\\3\\2\\2\\2\\u0410\\u040e\\3\")\n        buf.write(\"\\2\\2\\2\\u0411\\u0412\\7?\\2\\2\\u0412\\u0413\\5\\60\\31\\2\\u0413\")\n        buf.write(\"\\u0414\\7@\\2\\2\\u0414\\u0418\\3\\2\\2\\2\\u0415\\u0416\\7i\\2\\2\\u0416\")\n        buf.write(\"\\u0418\\7k\\2\\2\\u0417\\u0411\\3\\2\\2\\2\\u0417\\u0415\\3\\2\\2\\2\")\n        buf.write(\"\\u0418\\u008b\\3\\2\\2\\2\\u0419\\u041a\\7;\\2\\2\\u041a\\u041b\\7\")\n        buf.write(\"=\\2\\2\\u041b\\u041c\\5\\60\\31\\2\\u041c\\u041e\\7Z\\2\\2\\u041d\\u041f\")\n        buf.write(\"\\7m\\2\\2\\u041e\\u041d\\3\\2\\2\\2\\u041f\\u0420\\3\\2\\2\\2\\u0420\")\n        buf.write(\"\\u041e\\3\\2\\2\\2\\u0420\\u0421\\3\\2\\2\\2\\u0421\\u0422\\3\\2\\2\\2\")\n        buf.write(\"\\u0422\\u0423\\7>\\2\\2\\u0423\\u0424\\7Y\\2\\2\\u0424\\u008d\\3\\2\")\n        buf.write(\"\\2\\2\\u0425\\u044b\\5\\u0090I\\2\\u0426\\u044b\\5\\u0092J\\2\\u0427\")\n        buf.write(\"\\u044b\\5\\u0098M\\2\\u0428\\u044b\\5\\u009aN\\2\\u0429\\u044b\\5\")\n        buf.write(\"\\u009cO\\2\\u042a\\u044b\\5\\u009eP\\2\\u042b\\u042c\\t\\f\\2\\2\\u042c\")\n        buf.write(\"\\u042d\\t\\r\\2\\2\\u042d\\u0436\\7=\\2\\2\\u042e\\u0433\\5&\\24\\2\")\n        buf.write(\"\\u042f\\u0430\\7Z\\2\\2\\u0430\\u0432\\5&\\24\\2\\u0431\\u042f\\3\")\n        buf.write(\"\\2\\2\\2\\u0432\\u0435\\3\\2\\2\\2\\u0433\\u0431\\3\\2\\2\\2\\u0433\\u0434\")\n        buf.write(\"\\3\\2\\2\\2\\u0434\\u0437\\3\\2\\2\\2\\u0435\\u0433\\3\\2\\2\\2\\u0436\")\n        buf.write(\"\\u042e\\3\\2\\2\\2\\u0436\\u0437\\3\\2\\2\\2\\u0437\\u0445\\3\\2\\2\\2\")\n        buf.write(\"\\u0438\\u0441\\7X\\2\\2\\u0439\\u043e\\5&\\24\\2\\u043a\\u043b\\7\")\n        buf.write(\"Z\\2\\2\\u043b\\u043d\\5&\\24\\2\\u043c\\u043a\\3\\2\\2\\2\\u043d\\u0440\")\n        buf.write(\"\\3\\2\\2\\2\\u043e\\u043c\\3\\2\\2\\2\\u043e\\u043f\\3\\2\\2\\2\\u043f\")\n        buf.write(\"\\u0442\\3\\2\\2\\2\\u0440\\u043e\\3\\2\\2\\2\\u0441\\u0439\\3\\2\\2\\2\")\n        buf.write(\"\\u0441\\u0442\\3\\2\\2\\2\\u0442\\u0444\\3\\2\\2\\2\\u0443\\u0438\\3\")\n        buf.write(\"\\2\\2\\2\\u0444\\u0447\\3\\2\\2\\2\\u0445\\u0443\\3\\2\\2\\2\\u0445\\u0446\")\n        buf.write(\"\\3\\2\\2\\2\\u0446\\u0448\\3\\2\\2\\2\\u0447\\u0445\\3\\2\\2\\2\\u0448\")\n        buf.write(\"\\u0449\\7>\\2\\2\\u0449\\u044b\\7Y\\2\\2\\u044a\\u0425\\3\\2\\2\\2\\u044a\")\n        buf.write(\"\\u0426\\3\\2\\2\\2\\u044a\\u0427\\3\\2\\2\\2\\u044a\\u0428\\3\\2\\2\\2\")\n        buf.write(\"\\u044a\\u0429\\3\\2\\2\\2\\u044a\\u042a\\3\\2\\2\\2\\u044a\\u042b\\3\")\n        buf.write(\"\\2\\2\\2\\u044b\\u008f\\3\\2\\2\\2\\u044c\\u044d\\7k\\2\\2\\u044d\\u044e\")\n        buf.write(\"\\7X\\2\\2\\u044e\\u0458\\5\\u008eH\\2\\u044f\\u0450\\7\\23\\2\\2\\u0450\")\n        buf.write(\"\\u0451\\5\\60\\31\\2\\u0451\\u0452\\7X\\2\\2\\u0452\\u0453\\5\\u008e\")\n        buf.write(\"H\\2\\u0453\\u0458\\3\\2\\2\\2\\u0454\\u0455\\7\\27\\2\\2\\u0455\\u0456\")\n        buf.write(\"\\7X\\2\\2\\u0456\\u0458\\5\\u008eH\\2\\u0457\\u044c\\3\\2\\2\\2\\u0457\")\n        buf.write(\"\\u044f\\3\\2\\2\\2\\u0457\\u0454\\3\\2\\2\\2\\u0458\\u0091\\3\\2\\2\\2\")\n        buf.write(\"\\u0459\\u045b\\7A\\2\\2\\u045a\\u045c\\5\\u0094K\\2\\u045b\\u045a\")\n        buf.write(\"\\3\\2\\2\\2\\u045b\\u045c\\3\\2\\2\\2\\u045c\\u045d\\3\\2\\2\\2\\u045d\")\n        buf.write(\"\\u045e\\7B\\2\\2\\u045e\\u0093\\3\\2\\2\\2\\u045f\\u0460\\bK\\1\\2\\u0460\")\n        buf.write(\"\\u0461\\5\\u0096L\\2\\u0461\\u0466\\3\\2\\2\\2\\u0462\\u0463\\f\\3\")\n        buf.write(\"\\2\\2\\u0463\\u0465\\5\\u0096L\\2\\u0464\\u0462\\3\\2\\2\\2\\u0465\")\n        buf.write(\"\\u0468\\3\\2\\2\\2\\u0466\\u0464\\3\\2\\2\\2\\u0466\\u0467\\3\\2\\2\\2\")\n        buf.write(\"\\u0467\\u0095\\3\\2\\2\\2\\u0468\\u0466\\3\\2\\2\\2\\u0469\\u046c\\5\")\n        buf.write(\"\\62\\32\\2\\u046a\\u046c\\5\\u008eH\\2\\u046b\\u0469\\3\\2\\2\\2\\u046b\")\n        buf.write(\"\\u046a\\3\\2\\2\\2\\u046c\\u0097\\3\\2\\2\\2\\u046d\\u046f\\5.\\30\\2\")\n        buf.write(\"\\u046e\\u046d\\3\\2\\2\\2\\u046e\\u046f\\3\\2\\2\\2\\u046f\\u0470\\3\")\n        buf.write(\"\\2\\2\\2\\u0470\\u0471\\7Y\\2\\2\\u0471\\u0099\\3\\2\\2\\2\\u0472\\u0473\")\n        buf.write(\"\\7 \\2\\2\\u0473\\u0474\\7=\\2\\2\\u0474\\u0475\\5.\\30\\2\\u0475\\u0476\")\n        buf.write(\"\\7>\\2\\2\\u0476\\u0479\\5\\u008eH\\2\\u0477\\u0478\\7\\32\\2\\2\\u0478\")\n        buf.write(\"\\u047a\\5\\u008eH\\2\\u0479\\u0477\\3\\2\\2\\2\\u0479\\u047a\\3\\2\")\n        buf.write(\"\\2\\2\\u047a\\u0482\\3\\2\\2\\2\\u047b\\u047c\\7,\\2\\2\\u047c\\u047d\")\n        buf.write(\"\\7=\\2\\2\\u047d\\u047e\\5.\\30\\2\\u047e\\u047f\\7>\\2\\2\\u047f\\u0480\")\n        buf.write(\"\\5\\u008eH\\2\\u0480\\u0482\\3\\2\\2\\2\\u0481\\u0472\\3\\2\\2\\2\\u0481\")\n        buf.write(\"\\u047b\\3\\2\\2\\2\\u0482\\u009b\\3\\2\\2\\2\\u0483\\u0484\\7\\62\\2\")\n        buf.write(\"\\2\\u0484\\u0485\\7=\\2\\2\\u0485\\u0486\\5.\\30\\2\\u0486\\u0487\")\n        buf.write(\"\\7>\\2\\2\\u0487\\u0488\\5\\u008eH\\2\\u0488\\u04ae\\3\\2\\2\\2\\u0489\")\n        buf.write(\"\\u048a\\7\\30\\2\\2\\u048a\\u048b\\5\\u008eH\\2\\u048b\\u048c\\7\\62\")\n        buf.write(\"\\2\\2\\u048c\\u048d\\7=\\2\\2\\u048d\\u048e\\5.\\30\\2\\u048e\\u048f\")\n        buf.write(\"\\7>\\2\\2\\u048f\\u0490\\7Y\\2\\2\\u0490\\u04ae\\3\\2\\2\\2\\u0491\\u0492\")\n        buf.write(\"\\7\\36\\2\\2\\u0492\\u0494\\7=\\2\\2\\u0493\\u0495\\5.\\30\\2\\u0494\")\n        buf.write(\"\\u0493\\3\\2\\2\\2\\u0494\\u0495\\3\\2\\2\\2\\u0495\\u0496\\3\\2\\2\\2\")\n        buf.write(\"\\u0496\\u0498\\7Y\\2\\2\\u0497\\u0499\\5.\\30\\2\\u0498\\u0497\\3\")\n        buf.write(\"\\2\\2\\2\\u0498\\u0499\\3\\2\\2\\2\\u0499\\u049a\\3\\2\\2\\2\\u049a\\u049c\")\n        buf.write(\"\\7Y\\2\\2\\u049b\\u049d\\5.\\30\\2\\u049c\\u049b\\3\\2\\2\\2\\u049c\")\n        buf.write(\"\\u049d\\3\\2\\2\\2\\u049d\\u049e\\3\\2\\2\\2\\u049e\\u049f\\7>\\2\\2\")\n        buf.write(\"\\u049f\\u04ae\\5\\u008eH\\2\\u04a0\\u04a1\\7\\36\\2\\2\\u04a1\\u04a2\")\n        buf.write(\"\\7=\\2\\2\\u04a2\\u04a4\\5\\62\\32\\2\\u04a3\\u04a5\\5.\\30\\2\\u04a4\")\n        buf.write(\"\\u04a3\\3\\2\\2\\2\\u04a4\\u04a5\\3\\2\\2\\2\\u04a5\\u04a6\\3\\2\\2\\2\")\n        buf.write(\"\\u04a6\\u04a8\\7Y\\2\\2\\u04a7\\u04a9\\5.\\30\\2\\u04a8\\u04a7\\3\")\n        buf.write(\"\\2\\2\\2\\u04a8\\u04a9\\3\\2\\2\\2\\u04a9\\u04aa\\3\\2\\2\\2\\u04aa\\u04ab\")\n        buf.write(\"\\7>\\2\\2\\u04ab\\u04ac\\5\\u008eH\\2\\u04ac\\u04ae\\3\\2\\2\\2\\u04ad\")\n        buf.write(\"\\u0483\\3\\2\\2\\2\\u04ad\\u0489\\3\\2\\2\\2\\u04ad\\u0491\\3\\2\\2\\2\")\n        buf.write(\"\\u04ad\\u04a0\\3\\2\\2\\2\\u04ae\\u009d\\3\\2\\2\\2\\u04af\\u04b0\\7\")\n        buf.write(\"\\37\\2\\2\\u04b0\\u04b1\\7k\\2\\2\\u04b1\\u04c0\\7Y\\2\\2\\u04b2\\u04b3\")\n        buf.write(\"\\7\\26\\2\\2\\u04b3\\u04c0\\7Y\\2\\2\\u04b4\\u04b5\\7\\22\\2\\2\\u04b5\")\n        buf.write(\"\\u04c0\\7Y\\2\\2\\u04b6\\u04b8\\7&\\2\\2\\u04b7\\u04b9\\5.\\30\\2\\u04b8\")\n        buf.write(\"\\u04b7\\3\\2\\2\\2\\u04b8\\u04b9\\3\\2\\2\\2\\u04b9\\u04ba\\3\\2\\2\\2\")\n        buf.write(\"\\u04ba\\u04c0\\7Y\\2\\2\\u04bb\\u04bc\\7\\37\\2\\2\\u04bc\\u04bd\\5\")\n        buf.write(\"\\16\\b\\2\\u04bd\\u04be\\7Y\\2\\2\\u04be\\u04c0\\3\\2\\2\\2\\u04bf\\u04af\")\n        buf.write(\"\\3\\2\\2\\2\\u04bf\\u04b2\\3\\2\\2\\2\\u04bf\\u04b4\\3\\2\\2\\2\\u04bf\")\n        buf.write(\"\\u04b6\\3\\2\\2\\2\\u04bf\\u04bb\\3\\2\\2\\2\\u04c0\\u009f\\3\\2\\2\\2\")\n        buf.write(\"\\u04c1\\u04c3\\5\\u00a2R\\2\\u04c2\\u04c1\\3\\2\\2\\2\\u04c2\\u04c3\")\n        buf.write(\"\\3\\2\\2\\2\\u04c3\\u04c4\\3\\2\\2\\2\\u04c4\\u04c5\\7\\2\\2\\3\\u04c5\")\n        buf.write(\"\\u00a1\\3\\2\\2\\2\\u04c6\\u04c7\\bR\\1\\2\\u04c7\\u04c8\\5\\u00a4\")\n        buf.write(\"S\\2\\u04c8\\u04cd\\3\\2\\2\\2\\u04c9\\u04ca\\f\\3\\2\\2\\u04ca\\u04cc\")\n        buf.write(\"\\5\\u00a4S\\2\\u04cb\\u04c9\\3\\2\\2\\2\\u04cc\\u04cf\\3\\2\\2\\2\\u04cd\")\n        buf.write(\"\\u04cb\\3\\2\\2\\2\\u04cd\\u04ce\\3\\2\\2\\2\\u04ce\\u00a3\\3\\2\\2\\2\")\n        buf.write(\"\\u04cf\\u04cd\\3\\2\\2\\2\\u04d0\\u04d4\\5\\u00a6T\\2\\u04d1\\u04d4\")\n        buf.write(\"\\5\\62\\32\\2\\u04d2\\u04d4\\7Y\\2\\2\\u04d3\\u04d0\\3\\2\\2\\2\\u04d3\")\n        buf.write(\"\\u04d1\\3\\2\\2\\2\\u04d3\\u04d2\\3\\2\\2\\2\\u04d4\\u00a5\\3\\2\\2\\2\")\n        buf.write(\"\\u04d5\\u04d7\\5\\64\\33\\2\\u04d6\\u04d5\\3\\2\\2\\2\\u04d6\\u04d7\")\n        buf.write(\"\\3\\2\\2\\2\\u04d7\\u04d8\\3\\2\\2\\2\\u04d8\\u04da\\5`\\61\\2\\u04d9\")\n        buf.write(\"\\u04db\\5\\u00a8U\\2\\u04da\\u04d9\\3\\2\\2\\2\\u04da\\u04db\\3\\2\")\n        buf.write(\"\\2\\2\\u04db\\u04dc\\3\\2\\2\\2\\u04dc\\u04dd\\5\\u0092J\\2\\u04dd\")\n        buf.write(\"\\u00a7\\3\\2\\2\\2\\u04de\\u04df\\bU\\1\\2\\u04df\\u04e0\\5\\62\\32\")\n        buf.write(\"\\2\\u04e0\\u04e5\\3\\2\\2\\2\\u04e1\\u04e2\\f\\3\\2\\2\\u04e2\\u04e4\")\n        buf.write(\"\\5\\62\\32\\2\\u04e3\\u04e1\\3\\2\\2\\2\\u04e4\\u04e7\\3\\2\\2\\2\\u04e5\")\n        buf.write(\"\\u04e3\\3\\2\\2\\2\\u04e5\\u04e6\\3\\2\\2\\2\\u04e6\\u00a9\\3\\2\\2\\2\")\n        buf.write(\"\\u04e7\\u04e5\\3\\2\\2\\2\\u008c\\u00af\\u00b7\\u00cb\\u00dc\\u00e6\")\n        buf.write(\"\\u010a\\u0114\\u0121\\u0123\\u012e\\u0147\\u0157\\u0165\\u0167\")\n        buf.write(\"\\u0173\\u0175\\u0181\\u0183\\u0195\\u0197\\u01a3\\u01a5\\u01b0\")\n        buf.write(\"\\u01bb\\u01c6\\u01d1\\u01dc\\u01e5\\u01ec\\u01f8\\u01ff\\u0204\")\n        buf.write(\"\\u0209\\u020e\\u0215\\u021f\\u0227\\u0239\\u023d\\u0246\\u0251\")\n        buf.write(\"\\u0256\\u025b\\u025f\\u0263\\u0265\\u026f\\u0274\\u0278\\u027c\")\n        buf.write(\"\\u0284\\u028d\\u0297\\u029f\\u02b0\\u02bc\\u02bf\\u02c5\\u02ce\")\n        buf.write(\"\\u02d3\\u02d6\\u02dd\\u02ec\\u02f8\\u02fb\\u02fd\\u0305\\u0309\")\n        buf.write(\"\\u0317\\u031b\\u0320\\u0323\\u0326\\u032d\\u032f\\u0334\\u0338\")\n        buf.write(\"\\u033d\\u0341\\u0344\\u034d\\u0355\\u035f\\u0367\\u0369\\u0373\")\n        buf.write(\"\\u0378\\u037c\\u0382\\u0385\\u038e\\u0393\\u0396\\u039c\\u03ac\")\n        buf.write(\"\\u03b2\\u03b5\\u03ba\\u03bd\\u03c4\\u03d7\\u03dd\\u03e0\\u03e2\")\n        buf.write(\"\\u03f1\\u03f5\\u03fc\\u0401\\u040e\\u0417\\u0420\\u0433\\u0436\")\n        buf.write(\"\\u043e\\u0441\\u0445\\u044a\\u0457\\u045b\\u0466\\u046b\\u046e\")\n        buf.write(\"\\u0479\\u0481\\u0494\\u0498\\u049c\\u04a4\\u04a8\\u04ad\\u04b8\")\n        buf.write(\"\\u04bf\\u04c2\\u04cd\\u04d3\\u04d6\\u04da\\u04e5\")\n        return buf.getvalue()\n\n\nclass CParser ( Parser ):\n\n    grammarFileName = \"C.bnf\"\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n    sharedContextCache = PredictionContextCache()\n\n    literalNames = [ \"<INVALID>\", \"'__extension__'\", \"'__builtin_va_arg'\",\n                     \"'__builtin_offsetof'\", \"'__m128'\", \"'__m128d'\", \"'__m128i'\",\n                     \"'__typeof__'\", \"'__inline__'\", \"'__stdcall'\", \"'__declspec'\",\n                     \"'__asm'\", \"'__attribute__'\", \"'__asm__'\", \"'__volatile__'\",\n                     \"'auto'\", \"'break'\", \"'case'\", \"'char'\", \"'const'\",\n                     \"'continue'\", \"'default'\", \"'do'\", \"'double'\", \"'else'\",\n                     \"'enum'\", \"'extern'\", \"'float'\", \"'for'\", \"'goto'\",\n                     \"'if'\", \"'inline'\", \"'int'\", \"'long'\", \"'register'\",\n                     \"'restrict'\", \"'return'\", \"'short'\", \"'signed'\", \"'sizeof'\",\n                     \"'static'\", \"'struct'\", \"'switch'\", \"'typedef'\", \"'union'\",\n                     \"'unsigned'\", \"'void'\", \"'volatile'\", \"'while'\", \"'_Alignas'\",\n                     \"'_Alignof'\", \"'_Atomic'\", \"'_Bool'\", \"'_Complex'\",\n                     \"'_Generic'\", \"'_Imaginary'\", \"'_Noreturn'\", \"'_Static_assert'\",\n                     \"'_Thread_local'\", \"'('\", \"')'\", \"'['\", \"']'\", \"'{'\",\n                     \"'}'\", \"'<'\", \"'<='\", \"'>'\", \"'>='\", \"'<<'\", \"'>>'\",\n                     \"'+'\", \"'++'\", \"'-'\", \"'--'\", \"'*'\", \"'/'\", \"'%'\",\n                     \"'&'\", \"'|'\", \"'&&'\", \"'||'\", \"'^'\", \"'!'\", \"'~'\",\n                     \"'?'\", \"':'\", \"';'\", \"','\", \"'='\", \"'*='\", \"'/='\",\n                     \"'%='\", \"'+='\", \"'-='\", \"'<<='\", \"'>>='\", \"'&='\", \"'^='\",\n                     \"'|='\", \"'=='\", \"'!='\", \"'->'\", \"'.'\", \"'...'\" ]\n\n    symbolicNames = [ \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"<INVALID>\",\n                      \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"<INVALID>\",\n                      \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"<INVALID>\",\n                      \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"Auto\", \"Break\",\n                      \"Case\", \"Char\", \"Const\", \"Continue\", \"Default\", \"Do\",\n                      \"Double\", \"Else\", \"Enum\", \"Extern\", \"Float\", \"For\",\n                      \"Goto\", \"If\", \"Inline\", \"Int\", \"Long\", \"Register\",\n                      \"Restrict\", \"Return\", \"Short\", \"Signed\", \"Sizeof\",\n                      \"Static\", \"Struct\", \"Switch\", \"Typedef\", \"Union\",\n                      \"Unsigned\", \"Void\", \"Volatile\", \"While\", \"Alignas\",\n                      \"Alignof\", \"Atomic\", \"Bool\", \"Complex\", \"Generic\",\n                      \"Imaginary\", \"Noreturn\", \"StaticAssert\", \"ThreadLocal\",\n                      \"LeftParen\", \"RightParen\", \"LeftBracket\", \"RightBracket\",\n                      \"LeftBrace\", \"RightBrace\", \"Less\", \"LessEqual\", \"Greater\",\n                      \"GreaterEqual\", \"LeftShift\", \"RightShift\", \"Plus\",\n                      \"PlusPlus\", \"Minus\", \"MinusMinus\", \"Star\", \"Div\",\n                      \"Mod\", \"And\", \"Or\", \"AndAnd\", \"OrOr\", \"Caret\", \"Not\",\n                      \"Tilde\", \"Question\", \"Colon\", \"Semi\", \"Comma\", \"Assign\",\n                      \"StarAssign\", \"DivAssign\", \"ModAssign\", \"PlusAssign\",\n                      \"MinusAssign\", \"LeftShiftAssign\", \"RightShiftAssign\",\n                      \"AndAssign\", \"XorAssign\", \"OrAssign\", \"Equal\", \"NotEqual\",\n                      \"Arrow\", \"Dot\", \"Ellipsis\", \"Identifier\", \"Constant\",\n                      \"StringLiteral\", \"LineDirective\", \"PragmaDirective\",\n                      \"Whitespace\", \"Newline\", \"BlockComment\", \"LineComment\" ]\n\n    RULE_primaryExpression = 0\n    RULE_genericSelection = 1\n    RULE_genericAssocList = 2\n    RULE_genericAssociation = 3\n    RULE_postfixExpression = 4\n    RULE_argumentExpressionList = 5\n    RULE_unaryExpression = 6\n    RULE_unaryOperator = 7\n    RULE_castExpression = 8\n    RULE_multiplicativeExpression = 9\n    RULE_additiveExpression = 10\n    RULE_shiftExpression = 11\n    RULE_relationalExpression = 12\n    RULE_equalityExpression = 13\n    RULE_andExpression = 14\n    RULE_exclusiveOrExpression = 15\n    RULE_inclusiveOrExpression = 16\n    RULE_logicalAndExpression = 17\n    RULE_logicalOrExpression = 18\n    RULE_conditionalExpression = 19\n    RULE_assignmentExpression = 20\n    RULE_assignmentOperator = 21\n    RULE_expression = 22\n    RULE_constantExpression = 23\n    RULE_declaration = 24\n    RULE_declarationSpecifiers = 25\n    RULE_declarationSpecifiers2 = 26\n    RULE_declarationSpecifier = 27\n    RULE_initDeclaratorList = 28\n    RULE_initDeclarator = 29\n    RULE_storageClassSpecifier = 30\n    RULE_typeSpecifier = 31\n    RULE_structOrUnionSpecifier = 32\n    RULE_structOrUnion = 33\n    RULE_structDeclarationList = 34\n    RULE_structDeclaration = 35\n    RULE_specifierQualifierList = 36\n    RULE_structDeclaratorList = 37\n    RULE_structDeclarator = 38\n    RULE_enumSpecifier = 39\n    RULE_enumeratorList = 40\n    RULE_enumerator = 41\n    RULE_enumerationConstant = 42\n    RULE_atomicTypeSpecifier = 43\n    RULE_typeQualifier = 44\n    RULE_functionSpecifier = 45\n    RULE_alignmentSpecifier = 46\n    RULE_declarator = 47\n    RULE_directDeclarator = 48\n    RULE_gccDeclaratorExtension = 49\n    RULE_gccAttributeSpecifier = 50\n    RULE_gccAttributeList = 51\n    RULE_gccAttribute = 52\n    RULE_nestedParenthesesBlock = 53\n    RULE_pointer = 54\n    RULE_typeQualifierList = 55\n    RULE_parameterTypeList = 56\n    RULE_parameterList = 57\n    RULE_parameterDeclaration = 58\n    RULE_identifierList = 59\n    RULE_typeName = 60\n    RULE_abstractDeclarator = 61\n    RULE_directAbstractDeclarator = 62\n    RULE_typedefName = 63\n    RULE_initializer = 64\n    RULE_initializerList = 65\n    RULE_designation = 66\n    RULE_designatorList = 67\n    RULE_designator = 68\n    RULE_staticAssertDeclaration = 69\n    RULE_statement = 70\n    RULE_labeledStatement = 71\n    RULE_compoundStatement = 72\n    RULE_blockItemList = 73\n    RULE_blockItem = 74\n    RULE_expressionStatement = 75\n    RULE_selectionStatement = 76\n    RULE_iterationStatement = 77\n    RULE_jumpStatement = 78\n    RULE_compilationUnit = 79\n    RULE_translationUnit = 80\n    RULE_externalDeclaration = 81\n    RULE_functionDefinition = 82\n    RULE_declarationList = 83\n\n    ruleNames =  [ \"primaryExpression\", \"genericSelection\", \"genericAssocList\",\n                   \"genericAssociation\", \"postfixExpression\", \"argumentExpressionList\",\n                   \"unaryExpression\", \"unaryOperator\", \"castExpression\",\n                   \"multiplicativeExpression\", \"additiveExpression\", \"shiftExpression\",\n                   \"relationalExpression\", \"equalityExpression\", \"andExpression\",\n                   \"exclusiveOrExpression\", \"inclusiveOrExpression\", \"logicalAndExpression\",\n                   \"logicalOrExpression\", \"conditionalExpression\", \"assignmentExpression\",\n                   \"assignmentOperator\", \"expression\", \"constantExpression\",\n                   \"declaration\", \"declarationSpecifiers\", \"declarationSpecifiers2\",\n                   \"declarationSpecifier\", \"initDeclaratorList\", \"initDeclarator\",\n                   \"storageClassSpecifier\", \"typeSpecifier\", \"structOrUnionSpecifier\",\n                   \"structOrUnion\", \"structDeclarationList\", \"structDeclaration\",\n                   \"specifierQualifierList\", \"structDeclaratorList\", \"structDeclarator\",\n                   \"enumSpecifier\", \"enumeratorList\", \"enumerator\", \"enumerationConstant\",\n                   \"atomicTypeSpecifier\", \"typeQualifier\", \"functionSpecifier\",\n                   \"alignmentSpecifier\", \"declarator\", \"directDeclarator\",\n                   \"gccDeclaratorExtension\", \"gccAttributeSpecifier\", \"gccAttributeList\",\n                   \"gccAttribute\", \"nestedParenthesesBlock\", \"pointer\",\n                   \"typeQualifierList\", \"parameterTypeList\", \"parameterList\",\n                   \"parameterDeclaration\", \"identifierList\", \"typeName\",\n                   \"abstractDeclarator\", \"directAbstractDeclarator\", \"typedefName\",\n                   \"initializer\", \"initializerList\", \"designation\", \"designatorList\",\n                   \"designator\", \"staticAssertDeclaration\", \"statement\",\n                   \"labeledStatement\", \"compoundStatement\", \"blockItemList\",\n                   \"blockItem\", \"expressionStatement\", \"selectionStatement\",\n                   \"iterationStatement\", \"jumpStatement\", \"compilationUnit\",\n                   \"translationUnit\", \"externalDeclaration\", \"functionDefinition\",\n                   \"declarationList\" ]\n\n    EOF = Token.EOF\n    T__0=1\n    T__1=2\n    T__2=3\n    T__3=4\n    T__4=5\n    T__5=6\n    T__6=7\n    T__7=8\n    T__8=9\n    T__9=10\n    T__10=11\n    T__11=12\n    T__12=13\n    T__13=14\n    Auto=15\n    Break=16\n    Case=17\n    Char=18\n    Const=19\n    Continue=20\n    Default=21\n    Do=22\n    Double=23\n    Else=24\n    Enum=25\n    Extern=26\n    Float=27\n    For=28\n    Goto=29\n    If=30\n    Inline=31\n    Int=32\n    Long=33\n    Register=34\n    Restrict=35\n    Return=36\n    Short=37\n    Signed=38\n    Sizeof=39\n    Static=40\n    Struct=41\n    Switch=42\n    Typedef=43\n    Union=44\n    Unsigned=45\n    Void=46\n    Volatile=47\n    While=48\n    Alignas=49\n    Alignof=50\n    Atomic=51\n    Bool=52\n    Complex=53\n    Generic=54\n    Imaginary=55\n    Noreturn=56\n    StaticAssert=57\n    ThreadLocal=58\n    LeftParen=59\n    RightParen=60\n    LeftBracket=61\n    RightBracket=62\n    LeftBrace=63\n    RightBrace=64\n    Less=65\n    LessEqual=66\n    Greater=67\n    GreaterEqual=68\n    LeftShift=69\n    RightShift=70\n    Plus=71\n    PlusPlus=72\n    Minus=73\n    MinusMinus=74\n    Star=75\n    Div=76\n    Mod=77\n    And=78\n    Or=79\n    AndAnd=80\n    OrOr=81\n    Caret=82\n    Not=83\n    Tilde=84\n    Question=85\n    Colon=86\n    Semi=87\n    Comma=88\n    Assign=89\n    StarAssign=90\n    DivAssign=91\n    ModAssign=92\n    PlusAssign=93\n    MinusAssign=94\n    LeftShiftAssign=95\n    RightShiftAssign=96\n    AndAssign=97\n    XorAssign=98\n    OrAssign=99\n    Equal=100\n    NotEqual=101\n    Arrow=102\n    Dot=103\n    Ellipsis=104\n    Identifier=105\n    Constant=106\n    StringLiteral=107\n    LineDirective=108\n    PragmaDirective=109\n    Whitespace=110\n    Newline=111\n    BlockComment=112\n    LineComment=113\n\n    def __init__(self, input:TokenStream):\n        super().__init__(input)\n        self.checkVersion(\"4.9\")\n        self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)\n        self._predicates = None\n\n\n\n    class PrimaryExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def Constant(self):\n            return self.getToken(CParser.Constant, 0)\n\n        def StringLiteral(self, i:int=None):\n            if i is None:\n                return self.getTokens(CParser.StringLiteral)\n            else:\n                return self.getToken(CParser.StringLiteral, i)\n\n        def expression(self):\n            return self.getTypedRuleContext(CParser.ExpressionContext,0)\n\n\n        def genericSelection(self):\n            return self.getTypedRuleContext(CParser.GenericSelectionContext,0)\n\n\n        def compoundStatement(self):\n            return self.getTypedRuleContext(CParser.CompoundStatementContext,0)\n\n\n        def unaryExpression(self):\n            return self.getTypedRuleContext(CParser.UnaryExpressionContext,0)\n\n\n        def typeName(self):\n            return self.getTypedRuleContext(CParser.TypeNameContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_primaryExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterPrimaryExpression\" ):\n                listener.enterPrimaryExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitPrimaryExpression\" ):\n                listener.exitPrimaryExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitPrimaryExpression\" ):\n                return visitor.visitPrimaryExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def primaryExpression(self):\n\n        localctx = CParser.PrimaryExpressionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 0, self.RULE_primaryExpression)\n        self._la = 0 # Token type\n        try:\n            self.state = 201\n            la_ = self._interp.adaptivePredict(self._input,2,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 168\n                self.match(CParser.Identifier)\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 169\n                self.match(CParser.Constant)\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 171\n                self._errHandler.sync(self)\n                _alt = 1\n                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                    if _alt == 1:\n                        self.state = 170\n                        self.match(CParser.StringLiteral)\n\n                    else:\n                        raise NoViableAltException(self)\n                    self.state = 173\n                    self._errHandler.sync(self)\n                    _alt = self._interp.adaptivePredict(self._input,0,self._ctx)\n\n                pass\n\n            elif la_ == 4:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 175\n                self.match(CParser.LeftParen)\n                self.state = 176\n                self.expression(0)\n                self.state = 177\n                self.match(CParser.RightParen)\n                pass\n\n            elif la_ == 5:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 179\n                self.genericSelection()\n                pass\n\n            elif la_ == 6:\n                self.enterOuterAlt(localctx, 6)\n                self.state = 181\n                _la = self._input.LA(1)\n                if _la==CParser.T__0:\n                    self.state = 180\n                    self.match(CParser.T__0)\n\n\n                self.state = 183\n                self.match(CParser.LeftParen)\n                self.state = 184\n                self.compoundStatement()\n                self.state = 185\n                self.match(CParser.RightParen)\n                pass\n\n            elif la_ == 7:\n                self.enterOuterAlt(localctx, 7)\n                self.state = 187\n                self.match(CParser.T__1)\n                self.state = 188\n                self.match(CParser.LeftParen)\n                self.state = 189\n                self.unaryExpression()\n                self.state = 190\n                self.match(CParser.Comma)\n                self.state = 191\n                self.typeName()\n                self.state = 192\n                self.match(CParser.RightParen)\n                pass\n\n            elif la_ == 8:\n                self.enterOuterAlt(localctx, 8)\n                self.state = 194\n                self.match(CParser.T__2)\n                self.state = 195\n                self.match(CParser.LeftParen)\n                self.state = 196\n                self.typeName()\n                self.state = 197\n                self.match(CParser.Comma)\n                self.state = 198\n                self.unaryExpression()\n                self.state = 199\n                self.match(CParser.RightParen)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class GenericSelectionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def genericAssocList(self):\n            return self.getTypedRuleContext(CParser.GenericAssocListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_genericSelection\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterGenericSelection\" ):\n                listener.enterGenericSelection(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitGenericSelection\" ):\n                listener.exitGenericSelection(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGenericSelection\" ):\n                return visitor.visitGenericSelection(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def genericSelection(self):\n\n        localctx = CParser.GenericSelectionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 2, self.RULE_genericSelection)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 203\n            self.match(CParser.Generic)\n            self.state = 204\n            self.match(CParser.LeftParen)\n            self.state = 205\n            self.assignmentExpression()\n            self.state = 206\n            self.match(CParser.Comma)\n            self.state = 207\n            self.genericAssocList(0)\n            self.state = 208\n            self.match(CParser.RightParen)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class GenericAssocListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def genericAssociation(self):\n            return self.getTypedRuleContext(CParser.GenericAssociationContext,0)\n\n\n        def genericAssocList(self):\n            return self.getTypedRuleContext(CParser.GenericAssocListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_genericAssocList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterGenericAssocList\" ):\n                listener.enterGenericAssocList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitGenericAssocList\" ):\n                listener.exitGenericAssocList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGenericAssocList\" ):\n                return visitor.visitGenericAssocList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def genericAssocList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.GenericAssocListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 4\n        self.enterRecursionRule(localctx, 4, self.RULE_genericAssocList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 211\n            self.genericAssociation()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 218\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,3,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.GenericAssocListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_genericAssocList)\n                    self.state = 213\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 214\n                    self.match(CParser.Comma)\n                    self.state = 215\n                    self.genericAssociation()\n                self.state = 220\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,3,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class GenericAssociationContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def typeName(self):\n            return self.getTypedRuleContext(CParser.TypeNameContext,0)\n\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_genericAssociation\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterGenericAssociation\" ):\n                listener.enterGenericAssociation(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitGenericAssociation\" ):\n                listener.exitGenericAssociation(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGenericAssociation\" ):\n                return visitor.visitGenericAssociation(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def genericAssociation(self):\n\n        localctx = CParser.GenericAssociationContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 6, self.RULE_genericAssociation)\n        try:\n            self.state = 228\n            token = self._input.LA(1)\n            if token in [CParser.T__0, CParser.T__3, CParser.T__4, CParser.T__5, CParser.T__6, CParser.Char, CParser.Const, CParser.Double, CParser.Enum, CParser.Float, CParser.Int, CParser.Long, CParser.Restrict, CParser.Short, CParser.Signed, CParser.Struct, CParser.Union, CParser.Unsigned, CParser.Void, CParser.Volatile, CParser.Atomic, CParser.Bool, CParser.Complex, CParser.Identifier]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 221\n                self.typeName()\n                self.state = 222\n                self.match(CParser.Colon)\n                self.state = 223\n                self.assignmentExpression()\n\n            elif token in [CParser.Default]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 225\n                self.match(CParser.Default)\n                self.state = 226\n                self.match(CParser.Colon)\n                self.state = 227\n                self.assignmentExpression()\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class PostfixExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def primaryExpression(self):\n            return self.getTypedRuleContext(CParser.PrimaryExpressionContext,0)\n\n\n        def typeName(self):\n            return self.getTypedRuleContext(CParser.TypeNameContext,0)\n\n\n        def initializerList(self):\n            return self.getTypedRuleContext(CParser.InitializerListContext,0)\n\n\n        def postfixExpression(self):\n            return self.getTypedRuleContext(CParser.PostfixExpressionContext,0)\n\n\n        def expression(self):\n            return self.getTypedRuleContext(CParser.ExpressionContext,0)\n\n\n        def argumentExpressionList(self):\n            return self.getTypedRuleContext(CParser.ArgumentExpressionListContext,0)\n\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_postfixExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterPostfixExpression\" ):\n                listener.enterPostfixExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitPostfixExpression\" ):\n                listener.exitPostfixExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitPostfixExpression\" ):\n                return visitor.visitPostfixExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def postfixExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.PostfixExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 8\n        self.enterRecursionRule(localctx, 8, self.RULE_postfixExpression, _p)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 264\n            la_ = self._interp.adaptivePredict(self._input,5,self._ctx)\n            if la_ == 1:\n                self.state = 231\n                self.primaryExpression()\n                pass\n\n            elif la_ == 2:\n                self.state = 232\n                self.match(CParser.LeftParen)\n                self.state = 233\n                self.typeName()\n                self.state = 234\n                self.match(CParser.RightParen)\n                self.state = 235\n                self.match(CParser.LeftBrace)\n                self.state = 236\n                self.initializerList(0)\n                self.state = 237\n                self.match(CParser.RightBrace)\n                pass\n\n            elif la_ == 3:\n                self.state = 239\n                self.match(CParser.LeftParen)\n                self.state = 240\n                self.typeName()\n                self.state = 241\n                self.match(CParser.RightParen)\n                self.state = 242\n                self.match(CParser.LeftBrace)\n                self.state = 243\n                self.initializerList(0)\n                self.state = 244\n                self.match(CParser.Comma)\n                self.state = 245\n                self.match(CParser.RightBrace)\n                pass\n\n            elif la_ == 4:\n                self.state = 247\n                self.match(CParser.T__0)\n                self.state = 248\n                self.match(CParser.LeftParen)\n                self.state = 249\n                self.typeName()\n                self.state = 250\n                self.match(CParser.RightParen)\n                self.state = 251\n                self.match(CParser.LeftBrace)\n                self.state = 252\n                self.initializerList(0)\n                self.state = 253\n                self.match(CParser.RightBrace)\n                pass\n\n            elif la_ == 5:\n                self.state = 255\n                self.match(CParser.T__0)\n                self.state = 256\n                self.match(CParser.LeftParen)\n                self.state = 257\n                self.typeName()\n                self.state = 258\n                self.match(CParser.RightParen)\n                self.state = 259\n                self.match(CParser.LeftBrace)\n                self.state = 260\n                self.initializerList(0)\n                self.state = 261\n                self.match(CParser.Comma)\n                self.state = 262\n                self.match(CParser.RightBrace)\n                pass\n\n\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 289\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,8,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 287\n                    la_ = self._interp.adaptivePredict(self._input,7,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.PostfixExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_postfixExpression)\n                        self.state = 266\n                        if not self.precpred(self._ctx, 10):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 10)\")\n                        self.state = 267\n                        self.match(CParser.LeftBracket)\n                        self.state = 268\n                        self.expression(0)\n                        self.state = 269\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.PostfixExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_postfixExpression)\n                        self.state = 271\n                        if not self.precpred(self._ctx, 9):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 9)\")\n                        self.state = 272\n                        self.match(CParser.LeftParen)\n                        self.state = 274\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                            self.state = 273\n                            self.argumentExpressionList(0)\n\n\n                        self.state = 276\n                        self.match(CParser.RightParen)\n                        pass\n\n                    elif la_ == 3:\n                        localctx = CParser.PostfixExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_postfixExpression)\n                        self.state = 277\n                        if not self.precpred(self._ctx, 8):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 8)\")\n                        self.state = 278\n                        self.match(CParser.Dot)\n                        self.state = 279\n                        self.match(CParser.Identifier)\n                        pass\n\n                    elif la_ == 4:\n                        localctx = CParser.PostfixExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_postfixExpression)\n                        self.state = 280\n                        if not self.precpred(self._ctx, 7):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 7)\")\n                        self.state = 281\n                        self.match(CParser.Arrow)\n                        self.state = 282\n                        self.match(CParser.Identifier)\n                        pass\n\n                    elif la_ == 5:\n                        localctx = CParser.PostfixExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_postfixExpression)\n                        self.state = 283\n                        if not self.precpred(self._ctx, 6):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 6)\")\n                        self.state = 284\n                        self.match(CParser.PlusPlus)\n                        pass\n\n                    elif la_ == 6:\n                        localctx = CParser.PostfixExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_postfixExpression)\n                        self.state = 285\n                        if not self.precpred(self._ctx, 5):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 5)\")\n                        self.state = 286\n                        self.match(CParser.MinusMinus)\n                        pass\n\n\n                self.state = 291\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,8,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ArgumentExpressionListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def argumentExpressionList(self):\n            return self.getTypedRuleContext(CParser.ArgumentExpressionListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_argumentExpressionList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterArgumentExpressionList\" ):\n                listener.enterArgumentExpressionList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitArgumentExpressionList\" ):\n                listener.exitArgumentExpressionList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitArgumentExpressionList\" ):\n                return visitor.visitArgumentExpressionList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def argumentExpressionList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.ArgumentExpressionListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 10\n        self.enterRecursionRule(localctx, 10, self.RULE_argumentExpressionList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 293\n            self.assignmentExpression()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 300\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,9,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.ArgumentExpressionListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_argumentExpressionList)\n                    self.state = 295\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 296\n                    self.match(CParser.Comma)\n                    self.state = 297\n                    self.assignmentExpression()\n                self.state = 302\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,9,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class UnaryExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def postfixExpression(self):\n            return self.getTypedRuleContext(CParser.PostfixExpressionContext,0)\n\n\n        def unaryExpression(self):\n            return self.getTypedRuleContext(CParser.UnaryExpressionContext,0)\n\n\n        def unaryOperator(self):\n            return self.getTypedRuleContext(CParser.UnaryOperatorContext,0)\n\n\n        def castExpression(self):\n            return self.getTypedRuleContext(CParser.CastExpressionContext,0)\n\n\n        def typeName(self):\n            return self.getTypedRuleContext(CParser.TypeNameContext,0)\n\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_unaryExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterUnaryExpression\" ):\n                listener.enterUnaryExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitUnaryExpression\" ):\n                listener.exitUnaryExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitUnaryExpression\" ):\n                return visitor.visitUnaryExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def unaryExpression(self):\n\n        localctx = CParser.UnaryExpressionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 12, self.RULE_unaryExpression)\n        try:\n            self.state = 325\n            la_ = self._interp.adaptivePredict(self._input,10,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 303\n                self.postfixExpression(0)\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 304\n                self.match(CParser.PlusPlus)\n                self.state = 305\n                self.unaryExpression()\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 306\n                self.match(CParser.MinusMinus)\n                self.state = 307\n                self.unaryExpression()\n                pass\n\n            elif la_ == 4:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 308\n                self.unaryOperator()\n                self.state = 309\n                self.castExpression()\n                pass\n\n            elif la_ == 5:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 311\n                self.match(CParser.Sizeof)\n                self.state = 312\n                self.unaryExpression()\n                pass\n\n            elif la_ == 6:\n                self.enterOuterAlt(localctx, 6)\n                self.state = 313\n                self.match(CParser.Sizeof)\n                self.state = 314\n                self.match(CParser.LeftParen)\n                self.state = 315\n                self.typeName()\n                self.state = 316\n                self.match(CParser.RightParen)\n                pass\n\n            elif la_ == 7:\n                self.enterOuterAlt(localctx, 7)\n                self.state = 318\n                self.match(CParser.Alignof)\n                self.state = 319\n                self.match(CParser.LeftParen)\n                self.state = 320\n                self.typeName()\n                self.state = 321\n                self.match(CParser.RightParen)\n                pass\n\n            elif la_ == 8:\n                self.enterOuterAlt(localctx, 8)\n                self.state = 323\n                self.match(CParser.AndAnd)\n                self.state = 324\n                self.match(CParser.Identifier)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class UnaryOperatorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_unaryOperator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterUnaryOperator\" ):\n                listener.enterUnaryOperator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitUnaryOperator\" ):\n                listener.exitUnaryOperator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitUnaryOperator\" ):\n                return visitor.visitUnaryOperator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def unaryOperator(self):\n\n        localctx = CParser.UnaryOperatorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 14, self.RULE_unaryOperator)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 327\n            _la = self._input.LA(1)\n            if not(((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)))) != 0)):\n                self._errHandler.recoverInline(self)\n            else:\n                self.consume()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class CastExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def unaryExpression(self):\n            return self.getTypedRuleContext(CParser.UnaryExpressionContext,0)\n\n\n        def typeName(self):\n            return self.getTypedRuleContext(CParser.TypeNameContext,0)\n\n\n        def castExpression(self):\n            return self.getTypedRuleContext(CParser.CastExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_castExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterCastExpression\" ):\n                listener.enterCastExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitCastExpression\" ):\n                listener.exitCastExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitCastExpression\" ):\n                return visitor.visitCastExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def castExpression(self):\n\n        localctx = CParser.CastExpressionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 16, self.RULE_castExpression)\n        try:\n            self.state = 341\n            la_ = self._interp.adaptivePredict(self._input,11,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 329\n                self.unaryExpression()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 330\n                self.match(CParser.LeftParen)\n                self.state = 331\n                self.typeName()\n                self.state = 332\n                self.match(CParser.RightParen)\n                self.state = 333\n                self.castExpression()\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 335\n                self.match(CParser.T__0)\n                self.state = 336\n                self.match(CParser.LeftParen)\n                self.state = 337\n                self.typeName()\n                self.state = 338\n                self.match(CParser.RightParen)\n                self.state = 339\n                self.castExpression()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class MultiplicativeExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def castExpression(self):\n            return self.getTypedRuleContext(CParser.CastExpressionContext,0)\n\n\n        def multiplicativeExpression(self):\n            return self.getTypedRuleContext(CParser.MultiplicativeExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_multiplicativeExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterMultiplicativeExpression\" ):\n                listener.enterMultiplicativeExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitMultiplicativeExpression\" ):\n                listener.exitMultiplicativeExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitMultiplicativeExpression\" ):\n                return visitor.visitMultiplicativeExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def multiplicativeExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.MultiplicativeExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 18\n        self.enterRecursionRule(localctx, 18, self.RULE_multiplicativeExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 344\n            self.castExpression()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 357\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,13,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 355\n                    la_ = self._interp.adaptivePredict(self._input,12,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.MultiplicativeExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_multiplicativeExpression)\n                        self.state = 346\n                        if not self.precpred(self._ctx, 3):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 3)\")\n                        self.state = 347\n                        self.match(CParser.Star)\n                        self.state = 348\n                        self.castExpression()\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.MultiplicativeExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_multiplicativeExpression)\n                        self.state = 349\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 350\n                        self.match(CParser.Div)\n                        self.state = 351\n                        self.castExpression()\n                        pass\n\n                    elif la_ == 3:\n                        localctx = CParser.MultiplicativeExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_multiplicativeExpression)\n                        self.state = 352\n                        if not self.precpred(self._ctx, 1):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                        self.state = 353\n                        self.match(CParser.Mod)\n                        self.state = 354\n                        self.castExpression()\n                        pass\n\n\n                self.state = 359\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,13,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class AdditiveExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def multiplicativeExpression(self):\n            return self.getTypedRuleContext(CParser.MultiplicativeExpressionContext,0)\n\n\n        def additiveExpression(self):\n            return self.getTypedRuleContext(CParser.AdditiveExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_additiveExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAdditiveExpression\" ):\n                listener.enterAdditiveExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAdditiveExpression\" ):\n                listener.exitAdditiveExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAdditiveExpression\" ):\n                return visitor.visitAdditiveExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def additiveExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.AdditiveExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 20\n        self.enterRecursionRule(localctx, 20, self.RULE_additiveExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 361\n            self.multiplicativeExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 371\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,15,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 369\n                    la_ = self._interp.adaptivePredict(self._input,14,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.AdditiveExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_additiveExpression)\n                        self.state = 363\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 364\n                        self.match(CParser.Plus)\n                        self.state = 365\n                        self.multiplicativeExpression(0)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.AdditiveExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_additiveExpression)\n                        self.state = 366\n                        if not self.precpred(self._ctx, 1):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                        self.state = 367\n                        self.match(CParser.Minus)\n                        self.state = 368\n                        self.multiplicativeExpression(0)\n                        pass\n\n\n                self.state = 373\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,15,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ShiftExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def additiveExpression(self):\n            return self.getTypedRuleContext(CParser.AdditiveExpressionContext,0)\n\n\n        def shiftExpression(self):\n            return self.getTypedRuleContext(CParser.ShiftExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_shiftExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterShiftExpression\" ):\n                listener.enterShiftExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitShiftExpression\" ):\n                listener.exitShiftExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitShiftExpression\" ):\n                return visitor.visitShiftExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def shiftExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.ShiftExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 22\n        self.enterRecursionRule(localctx, 22, self.RULE_shiftExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 375\n            self.additiveExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 385\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,17,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 383\n                    la_ = self._interp.adaptivePredict(self._input,16,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.ShiftExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_shiftExpression)\n                        self.state = 377\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 378\n                        self.match(CParser.LeftShift)\n                        self.state = 379\n                        self.additiveExpression(0)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.ShiftExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_shiftExpression)\n                        self.state = 380\n                        if not self.precpred(self._ctx, 1):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                        self.state = 381\n                        self.match(CParser.RightShift)\n                        self.state = 382\n                        self.additiveExpression(0)\n                        pass\n\n\n                self.state = 387\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,17,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class RelationalExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def shiftExpression(self):\n            return self.getTypedRuleContext(CParser.ShiftExpressionContext,0)\n\n\n        def relationalExpression(self):\n            return self.getTypedRuleContext(CParser.RelationalExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_relationalExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterRelationalExpression\" ):\n                listener.enterRelationalExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitRelationalExpression\" ):\n                listener.exitRelationalExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitRelationalExpression\" ):\n                return visitor.visitRelationalExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def relationalExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.RelationalExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 24\n        self.enterRecursionRule(localctx, 24, self.RULE_relationalExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 389\n            self.shiftExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 405\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,19,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 403\n                    la_ = self._interp.adaptivePredict(self._input,18,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.RelationalExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_relationalExpression)\n                        self.state = 391\n                        if not self.precpred(self._ctx, 4):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 4)\")\n                        self.state = 392\n                        self.match(CParser.Less)\n                        self.state = 393\n                        self.shiftExpression(0)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.RelationalExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_relationalExpression)\n                        self.state = 394\n                        if not self.precpred(self._ctx, 3):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 3)\")\n                        self.state = 395\n                        self.match(CParser.Greater)\n                        self.state = 396\n                        self.shiftExpression(0)\n                        pass\n\n                    elif la_ == 3:\n                        localctx = CParser.RelationalExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_relationalExpression)\n                        self.state = 397\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 398\n                        self.match(CParser.LessEqual)\n                        self.state = 399\n                        self.shiftExpression(0)\n                        pass\n\n                    elif la_ == 4:\n                        localctx = CParser.RelationalExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_relationalExpression)\n                        self.state = 400\n                        if not self.precpred(self._ctx, 1):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                        self.state = 401\n                        self.match(CParser.GreaterEqual)\n                        self.state = 402\n                        self.shiftExpression(0)\n                        pass\n\n\n                self.state = 407\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,19,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class EqualityExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def relationalExpression(self):\n            return self.getTypedRuleContext(CParser.RelationalExpressionContext,0)\n\n\n        def equalityExpression(self):\n            return self.getTypedRuleContext(CParser.EqualityExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_equalityExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterEqualityExpression\" ):\n                listener.enterEqualityExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitEqualityExpression\" ):\n                listener.exitEqualityExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitEqualityExpression\" ):\n                return visitor.visitEqualityExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def equalityExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.EqualityExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 26\n        self.enterRecursionRule(localctx, 26, self.RULE_equalityExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 409\n            self.relationalExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 419\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,21,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 417\n                    la_ = self._interp.adaptivePredict(self._input,20,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.EqualityExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_equalityExpression)\n                        self.state = 411\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 412\n                        self.match(CParser.Equal)\n                        self.state = 413\n                        self.relationalExpression(0)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.EqualityExpressionContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_equalityExpression)\n                        self.state = 414\n                        if not self.precpred(self._ctx, 1):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                        self.state = 415\n                        self.match(CParser.NotEqual)\n                        self.state = 416\n                        self.relationalExpression(0)\n                        pass\n\n\n                self.state = 421\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,21,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class AndExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def equalityExpression(self):\n            return self.getTypedRuleContext(CParser.EqualityExpressionContext,0)\n\n\n        def andExpression(self):\n            return self.getTypedRuleContext(CParser.AndExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_andExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAndExpression\" ):\n                listener.enterAndExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAndExpression\" ):\n                listener.exitAndExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAndExpression\" ):\n                return visitor.visitAndExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def andExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.AndExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 28\n        self.enterRecursionRule(localctx, 28, self.RULE_andExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 423\n            self.equalityExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 430\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,22,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.AndExpressionContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_andExpression)\n                    self.state = 425\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 426\n                    self.match(CParser.And)\n                    self.state = 427\n                    self.equalityExpression(0)\n                self.state = 432\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,22,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ExclusiveOrExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def andExpression(self):\n            return self.getTypedRuleContext(CParser.AndExpressionContext,0)\n\n\n        def exclusiveOrExpression(self):\n            return self.getTypedRuleContext(CParser.ExclusiveOrExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_exclusiveOrExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterExclusiveOrExpression\" ):\n                listener.enterExclusiveOrExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitExclusiveOrExpression\" ):\n                listener.exitExclusiveOrExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitExclusiveOrExpression\" ):\n                return visitor.visitExclusiveOrExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def exclusiveOrExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.ExclusiveOrExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 30\n        self.enterRecursionRule(localctx, 30, self.RULE_exclusiveOrExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 434\n            self.andExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 441\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,23,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.ExclusiveOrExpressionContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_exclusiveOrExpression)\n                    self.state = 436\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 437\n                    self.match(CParser.Caret)\n                    self.state = 438\n                    self.andExpression(0)\n                self.state = 443\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,23,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class InclusiveOrExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def exclusiveOrExpression(self):\n            return self.getTypedRuleContext(CParser.ExclusiveOrExpressionContext,0)\n\n\n        def inclusiveOrExpression(self):\n            return self.getTypedRuleContext(CParser.InclusiveOrExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_inclusiveOrExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterInclusiveOrExpression\" ):\n                listener.enterInclusiveOrExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitInclusiveOrExpression\" ):\n                listener.exitInclusiveOrExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitInclusiveOrExpression\" ):\n                return visitor.visitInclusiveOrExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def inclusiveOrExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.InclusiveOrExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 32\n        self.enterRecursionRule(localctx, 32, self.RULE_inclusiveOrExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 445\n            self.exclusiveOrExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 452\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,24,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.InclusiveOrExpressionContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_inclusiveOrExpression)\n                    self.state = 447\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 448\n                    self.match(CParser.Or)\n                    self.state = 449\n                    self.exclusiveOrExpression(0)\n                self.state = 454\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,24,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class LogicalAndExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def inclusiveOrExpression(self):\n            return self.getTypedRuleContext(CParser.InclusiveOrExpressionContext,0)\n\n\n        def logicalAndExpression(self):\n            return self.getTypedRuleContext(CParser.LogicalAndExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_logicalAndExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterLogicalAndExpression\" ):\n                listener.enterLogicalAndExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitLogicalAndExpression\" ):\n                listener.exitLogicalAndExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitLogicalAndExpression\" ):\n                return visitor.visitLogicalAndExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def logicalAndExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.LogicalAndExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 34\n        self.enterRecursionRule(localctx, 34, self.RULE_logicalAndExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 456\n            self.inclusiveOrExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 463\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,25,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.LogicalAndExpressionContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_logicalAndExpression)\n                    self.state = 458\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 459\n                    self.match(CParser.AndAnd)\n                    self.state = 460\n                    self.inclusiveOrExpression(0)\n                self.state = 465\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,25,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class LogicalOrExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def logicalAndExpression(self):\n            return self.getTypedRuleContext(CParser.LogicalAndExpressionContext,0)\n\n\n        def logicalOrExpression(self):\n            return self.getTypedRuleContext(CParser.LogicalOrExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_logicalOrExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterLogicalOrExpression\" ):\n                listener.enterLogicalOrExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitLogicalOrExpression\" ):\n                listener.exitLogicalOrExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitLogicalOrExpression\" ):\n                return visitor.visitLogicalOrExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def logicalOrExpression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.LogicalOrExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 36\n        self.enterRecursionRule(localctx, 36, self.RULE_logicalOrExpression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 467\n            self.logicalAndExpression(0)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 474\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,26,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.LogicalOrExpressionContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_logicalOrExpression)\n                    self.state = 469\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 470\n                    self.match(CParser.OrOr)\n                    self.state = 471\n                    self.logicalAndExpression(0)\n                self.state = 476\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,26,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ConditionalExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def logicalOrExpression(self):\n            return self.getTypedRuleContext(CParser.LogicalOrExpressionContext,0)\n\n\n        def expression(self):\n            return self.getTypedRuleContext(CParser.ExpressionContext,0)\n\n\n        def conditionalExpression(self):\n            return self.getTypedRuleContext(CParser.ConditionalExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_conditionalExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterConditionalExpression\" ):\n                listener.enterConditionalExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitConditionalExpression\" ):\n                listener.exitConditionalExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitConditionalExpression\" ):\n                return visitor.visitConditionalExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def conditionalExpression(self):\n\n        localctx = CParser.ConditionalExpressionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 38, self.RULE_conditionalExpression)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 477\n            self.logicalOrExpression(0)\n            self.state = 483\n            la_ = self._interp.adaptivePredict(self._input,27,self._ctx)\n            if la_ == 1:\n                self.state = 478\n                self.match(CParser.Question)\n                self.state = 479\n                self.expression(0)\n                self.state = 480\n                self.match(CParser.Colon)\n                self.state = 481\n                self.conditionalExpression()\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class AssignmentExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def conditionalExpression(self):\n            return self.getTypedRuleContext(CParser.ConditionalExpressionContext,0)\n\n\n        def unaryExpression(self):\n            return self.getTypedRuleContext(CParser.UnaryExpressionContext,0)\n\n\n        def assignmentOperator(self):\n            return self.getTypedRuleContext(CParser.AssignmentOperatorContext,0)\n\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_assignmentExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAssignmentExpression\" ):\n                listener.enterAssignmentExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAssignmentExpression\" ):\n                listener.exitAssignmentExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAssignmentExpression\" ):\n                return visitor.visitAssignmentExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def assignmentExpression(self):\n\n        localctx = CParser.AssignmentExpressionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 40, self.RULE_assignmentExpression)\n        try:\n            self.state = 490\n            la_ = self._interp.adaptivePredict(self._input,28,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 485\n                self.conditionalExpression()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 486\n                self.unaryExpression()\n                self.state = 487\n                self.assignmentOperator()\n                self.state = 488\n                self.assignmentExpression()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class AssignmentOperatorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_assignmentOperator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAssignmentOperator\" ):\n                listener.enterAssignmentOperator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAssignmentOperator\" ):\n                listener.exitAssignmentOperator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAssignmentOperator\" ):\n                return visitor.visitAssignmentOperator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def assignmentOperator(self):\n\n        localctx = CParser.AssignmentOperatorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 42, self.RULE_assignmentOperator)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 492\n            _la = self._input.LA(1)\n            if not(((((_la - 89)) & ~0x3f) == 0 and ((1 << (_la - 89)) & ((1 << (CParser.Assign - 89)) | (1 << (CParser.StarAssign - 89)) | (1 << (CParser.DivAssign - 89)) | (1 << (CParser.ModAssign - 89)) | (1 << (CParser.PlusAssign - 89)) | (1 << (CParser.MinusAssign - 89)) | (1 << (CParser.LeftShiftAssign - 89)) | (1 << (CParser.RightShiftAssign - 89)) | (1 << (CParser.AndAssign - 89)) | (1 << (CParser.XorAssign - 89)) | (1 << (CParser.OrAssign - 89)))) != 0)):\n                self._errHandler.recoverInline(self)\n            else:\n                self.consume()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class ExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def expression(self):\n            return self.getTypedRuleContext(CParser.ExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_expression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterExpression\" ):\n                listener.enterExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitExpression\" ):\n                listener.exitExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitExpression\" ):\n                return visitor.visitExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def expression(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.ExpressionContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 44\n        self.enterRecursionRule(localctx, 44, self.RULE_expression, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 495\n            self.assignmentExpression()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 502\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,29,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.ExpressionContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)\n                    self.state = 497\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 498\n                    self.match(CParser.Comma)\n                    self.state = 499\n                    self.assignmentExpression()\n                self.state = 504\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,29,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ConstantExpressionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def conditionalExpression(self):\n            return self.getTypedRuleContext(CParser.ConditionalExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_constantExpression\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterConstantExpression\" ):\n                listener.enterConstantExpression(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitConstantExpression\" ):\n                listener.exitConstantExpression(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitConstantExpression\" ):\n                return visitor.visitConstantExpression(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def constantExpression(self):\n\n        localctx = CParser.ConstantExpressionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 46, self.RULE_constantExpression)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 505\n            self.conditionalExpression()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DeclarationContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declarationSpecifiers(self):\n            return self.getTypedRuleContext(CParser.DeclarationSpecifiersContext,0)\n\n\n        def initDeclaratorList(self):\n            return self.getTypedRuleContext(CParser.InitDeclaratorListContext,0)\n\n\n        def staticAssertDeclaration(self):\n            return self.getTypedRuleContext(CParser.StaticAssertDeclarationContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_declaration\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDeclaration\" ):\n                listener.enterDeclaration(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDeclaration\" ):\n                listener.exitDeclaration(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDeclaration\" ):\n                return visitor.visitDeclaration(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def declaration(self):\n\n        localctx = CParser.DeclarationContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 48, self.RULE_declaration)\n        self._la = 0 # Token type\n        try:\n            self.state = 514\n            token = self._input.LA(1)\n            if token in [CParser.T__0, CParser.T__3, CParser.T__4, CParser.T__5, CParser.T__6, CParser.T__7, CParser.T__8, CParser.T__9, CParser.T__11, CParser.Auto, CParser.Char, CParser.Const, CParser.Double, CParser.Enum, CParser.Extern, CParser.Float, CParser.Inline, CParser.Int, CParser.Long, CParser.Register, CParser.Restrict, CParser.Short, CParser.Signed, CParser.Static, CParser.Struct, CParser.Typedef, CParser.Union, CParser.Unsigned, CParser.Void, CParser.Volatile, CParser.Alignas, CParser.Atomic, CParser.Bool, CParser.Complex, CParser.Noreturn, CParser.ThreadLocal, CParser.Identifier]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 507\n                self.declarationSpecifiers()\n                self.state = 509\n                _la = self._input.LA(1)\n                if ((((_la - 59)) & ~0x3f) == 0 and ((1 << (_la - 59)) & ((1 << (CParser.LeftParen - 59)) | (1 << (CParser.Star - 59)) | (1 << (CParser.Caret - 59)) | (1 << (CParser.Identifier - 59)))) != 0):\n                    self.state = 508\n                    self.initDeclaratorList(0)\n\n\n                self.state = 511\n                self.match(CParser.Semi)\n\n            elif token in [CParser.StaticAssert]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 513\n                self.staticAssertDeclaration()\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DeclarationSpecifiersContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declarationSpecifier(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.DeclarationSpecifierContext)\n            else:\n                return self.getTypedRuleContext(CParser.DeclarationSpecifierContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_declarationSpecifiers\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDeclarationSpecifiers\" ):\n                listener.enterDeclarationSpecifiers(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDeclarationSpecifiers\" ):\n                listener.exitDeclarationSpecifiers(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDeclarationSpecifiers\" ):\n                return visitor.visitDeclarationSpecifiers(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def declarationSpecifiers(self):\n\n        localctx = CParser.DeclarationSpecifiersContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 50, self.RULE_declarationSpecifiers)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 517\n            self._errHandler.sync(self)\n            _alt = 1\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt == 1:\n                    self.state = 516\n                    self.declarationSpecifier()\n\n                else:\n                    raise NoViableAltException(self)\n                self.state = 519\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,32,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DeclarationSpecifiers2Context(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declarationSpecifier(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.DeclarationSpecifierContext)\n            else:\n                return self.getTypedRuleContext(CParser.DeclarationSpecifierContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_declarationSpecifiers2\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDeclarationSpecifiers2\" ):\n                listener.enterDeclarationSpecifiers2(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDeclarationSpecifiers2\" ):\n                listener.exitDeclarationSpecifiers2(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDeclarationSpecifiers2\" ):\n                return visitor.visitDeclarationSpecifiers2(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def declarationSpecifiers2(self):\n\n        localctx = CParser.DeclarationSpecifiers2Context(self, self._ctx, self.state)\n        self.enterRule(localctx, 52, self.RULE_declarationSpecifiers2)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 522\n            self._errHandler.sync(self)\n            _alt = 1\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt == 1:\n                    self.state = 521\n                    self.declarationSpecifier()\n\n                else:\n                    raise NoViableAltException(self)\n                self.state = 524\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,33,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DeclarationSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def storageClassSpecifier(self):\n            return self.getTypedRuleContext(CParser.StorageClassSpecifierContext,0)\n\n\n        def typeSpecifier(self):\n            return self.getTypedRuleContext(CParser.TypeSpecifierContext,0)\n\n\n        def typeQualifier(self):\n            return self.getTypedRuleContext(CParser.TypeQualifierContext,0)\n\n\n        def functionSpecifier(self):\n            return self.getTypedRuleContext(CParser.FunctionSpecifierContext,0)\n\n\n        def alignmentSpecifier(self):\n            return self.getTypedRuleContext(CParser.AlignmentSpecifierContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_declarationSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDeclarationSpecifier\" ):\n                listener.enterDeclarationSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDeclarationSpecifier\" ):\n                listener.exitDeclarationSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDeclarationSpecifier\" ):\n                return visitor.visitDeclarationSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def declarationSpecifier(self):\n\n        localctx = CParser.DeclarationSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 54, self.RULE_declarationSpecifier)\n        try:\n            self.state = 531\n            la_ = self._interp.adaptivePredict(self._input,34,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 526\n                self.storageClassSpecifier()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 527\n                self.typeSpecifier()\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 528\n                self.typeQualifier()\n                pass\n\n            elif la_ == 4:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 529\n                self.functionSpecifier()\n                pass\n\n            elif la_ == 5:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 530\n                self.alignmentSpecifier()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class InitDeclaratorListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def initDeclarator(self):\n            return self.getTypedRuleContext(CParser.InitDeclaratorContext,0)\n\n\n        def initDeclaratorList(self):\n            return self.getTypedRuleContext(CParser.InitDeclaratorListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_initDeclaratorList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterInitDeclaratorList\" ):\n                listener.enterInitDeclaratorList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitInitDeclaratorList\" ):\n                listener.exitInitDeclaratorList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitInitDeclaratorList\" ):\n                return visitor.visitInitDeclaratorList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def initDeclaratorList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.InitDeclaratorListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 56\n        self.enterRecursionRule(localctx, 56, self.RULE_initDeclaratorList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 534\n            self.initDeclarator()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 541\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,35,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.InitDeclaratorListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_initDeclaratorList)\n                    self.state = 536\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 537\n                    self.match(CParser.Comma)\n                    self.state = 538\n                    self.initDeclarator()\n                self.state = 543\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,35,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class InitDeclaratorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declarator(self):\n            return self.getTypedRuleContext(CParser.DeclaratorContext,0)\n\n\n        def initializer(self):\n            return self.getTypedRuleContext(CParser.InitializerContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_initDeclarator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterInitDeclarator\" ):\n                listener.enterInitDeclarator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitInitDeclarator\" ):\n                listener.exitInitDeclarator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitInitDeclarator\" ):\n                return visitor.visitInitDeclarator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def initDeclarator(self):\n\n        localctx = CParser.InitDeclaratorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 58, self.RULE_initDeclarator)\n        try:\n            self.state = 549\n            la_ = self._interp.adaptivePredict(self._input,36,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 544\n                self.declarator()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 545\n                self.declarator()\n                self.state = 546\n                self.match(CParser.Assign)\n                self.state = 547\n                self.initializer()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class StorageClassSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_storageClassSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStorageClassSpecifier\" ):\n                listener.enterStorageClassSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStorageClassSpecifier\" ):\n                listener.exitStorageClassSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStorageClassSpecifier\" ):\n                return visitor.visitStorageClassSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def storageClassSpecifier(self):\n\n        localctx = CParser.StorageClassSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 60, self.RULE_storageClassSpecifier)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 551\n            _la = self._input.LA(1)\n            if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Auto) | (1 << CParser.Extern) | (1 << CParser.Register) | (1 << CParser.Static) | (1 << CParser.Typedef) | (1 << CParser.ThreadLocal))) != 0)):\n                self._errHandler.recoverInline(self)\n            else:\n                self.consume()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class TypeSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def atomicTypeSpecifier(self):\n            return self.getTypedRuleContext(CParser.AtomicTypeSpecifierContext,0)\n\n\n        def structOrUnionSpecifier(self):\n            return self.getTypedRuleContext(CParser.StructOrUnionSpecifierContext,0)\n\n\n        def enumSpecifier(self):\n            return self.getTypedRuleContext(CParser.EnumSpecifierContext,0)\n\n\n        def typedefName(self):\n            return self.getTypedRuleContext(CParser.TypedefNameContext,0)\n\n\n        def constantExpression(self):\n            return self.getTypedRuleContext(CParser.ConstantExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_typeSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterTypeSpecifier\" ):\n                listener.enterTypeSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitTypeSpecifier\" ):\n                listener.exitTypeSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitTypeSpecifier\" ):\n                return visitor.visitTypeSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def typeSpecifier(self):\n\n        localctx = CParser.TypeSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 62, self.RULE_typeSpecifier)\n        self._la = 0 # Token type\n        try:\n            self.state = 567\n            token = self._input.LA(1)\n            if token in [CParser.T__3, CParser.T__4, CParser.T__5, CParser.Char, CParser.Double, CParser.Float, CParser.Int, CParser.Long, CParser.Short, CParser.Signed, CParser.Unsigned, CParser.Void, CParser.Bool, CParser.Complex]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 553\n                _la = self._input.LA(1)\n                if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5) | (1 << CParser.Char) | (1 << CParser.Double) | (1 << CParser.Float) | (1 << CParser.Int) | (1 << CParser.Long) | (1 << CParser.Short) | (1 << CParser.Signed) | (1 << CParser.Unsigned) | (1 << CParser.Void) | (1 << CParser.Bool) | (1 << CParser.Complex))) != 0)):\n                    self._errHandler.recoverInline(self)\n                else:\n                    self.consume()\n\n            elif token in [CParser.T__0]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 554\n                self.match(CParser.T__0)\n                self.state = 555\n                self.match(CParser.LeftParen)\n                self.state = 556\n                _la = self._input.LA(1)\n                if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5))) != 0)):\n                    self._errHandler.recoverInline(self)\n                else:\n                    self.consume()\n                self.state = 557\n                self.match(CParser.RightParen)\n\n            elif token in [CParser.Atomic]:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 558\n                self.atomicTypeSpecifier()\n\n            elif token in [CParser.Struct, CParser.Union]:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 559\n                self.structOrUnionSpecifier()\n\n            elif token in [CParser.Enum]:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 560\n                self.enumSpecifier()\n\n            elif token in [CParser.Identifier]:\n                self.enterOuterAlt(localctx, 6)\n                self.state = 561\n                self.typedefName()\n\n            elif token in [CParser.T__6]:\n                self.enterOuterAlt(localctx, 7)\n                self.state = 562\n                self.match(CParser.T__6)\n                self.state = 563\n                self.match(CParser.LeftParen)\n                self.state = 564\n                self.constantExpression()\n                self.state = 565\n                self.match(CParser.RightParen)\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class StructOrUnionSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def structOrUnion(self):\n            return self.getTypedRuleContext(CParser.StructOrUnionContext,0)\n\n\n        def structDeclarationList(self):\n            return self.getTypedRuleContext(CParser.StructDeclarationListContext,0)\n\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_structOrUnionSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStructOrUnionSpecifier\" ):\n                listener.enterStructOrUnionSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStructOrUnionSpecifier\" ):\n                listener.exitStructOrUnionSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStructOrUnionSpecifier\" ):\n                return visitor.visitStructOrUnionSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def structOrUnionSpecifier(self):\n\n        localctx = CParser.StructOrUnionSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 64, self.RULE_structOrUnionSpecifier)\n        self._la = 0 # Token type\n        try:\n            self.state = 580\n            la_ = self._interp.adaptivePredict(self._input,39,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 569\n                self.structOrUnion()\n                self.state = 571\n                _la = self._input.LA(1)\n                if _la==CParser.Identifier:\n                    self.state = 570\n                    self.match(CParser.Identifier)\n\n\n                self.state = 573\n                self.match(CParser.LeftBrace)\n                self.state = 574\n                self.structDeclarationList(0)\n                self.state = 575\n                self.match(CParser.RightBrace)\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 577\n                self.structOrUnion()\n                self.state = 578\n                self.match(CParser.Identifier)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class StructOrUnionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_structOrUnion\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStructOrUnion\" ):\n                listener.enterStructOrUnion(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStructOrUnion\" ):\n                listener.exitStructOrUnion(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStructOrUnion\" ):\n                return visitor.visitStructOrUnion(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def structOrUnion(self):\n\n        localctx = CParser.StructOrUnionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 66, self.RULE_structOrUnion)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 582\n            _la = self._input.LA(1)\n            if not(_la==CParser.Struct or _la==CParser.Union):\n                self._errHandler.recoverInline(self)\n            else:\n                self.consume()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class StructDeclarationListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def structDeclaration(self):\n            return self.getTypedRuleContext(CParser.StructDeclarationContext,0)\n\n\n        def structDeclarationList(self):\n            return self.getTypedRuleContext(CParser.StructDeclarationListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_structDeclarationList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStructDeclarationList\" ):\n                listener.enterStructDeclarationList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStructDeclarationList\" ):\n                listener.exitStructDeclarationList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStructDeclarationList\" ):\n                return visitor.visitStructDeclarationList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def structDeclarationList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.StructDeclarationListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 68\n        self.enterRecursionRule(localctx, 68, self.RULE_structDeclarationList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 585\n            self.structDeclaration()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 591\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,40,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.StructDeclarationListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_structDeclarationList)\n                    self.state = 587\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 588\n                    self.structDeclaration()\n                self.state = 593\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,40,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class StructDeclarationContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def specifierQualifierList(self):\n            return self.getTypedRuleContext(CParser.SpecifierQualifierListContext,0)\n\n\n        def structDeclaratorList(self):\n            return self.getTypedRuleContext(CParser.StructDeclaratorListContext,0)\n\n\n        def staticAssertDeclaration(self):\n            return self.getTypedRuleContext(CParser.StaticAssertDeclarationContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_structDeclaration\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStructDeclaration\" ):\n                listener.enterStructDeclaration(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStructDeclaration\" ):\n                listener.exitStructDeclaration(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStructDeclaration\" ):\n                return visitor.visitStructDeclaration(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def structDeclaration(self):\n\n        localctx = CParser.StructDeclarationContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 70, self.RULE_structDeclaration)\n        self._la = 0 # Token type\n        try:\n            self.state = 601\n            token = self._input.LA(1)\n            if token in [CParser.T__0, CParser.T__3, CParser.T__4, CParser.T__5, CParser.T__6, CParser.Char, CParser.Const, CParser.Double, CParser.Enum, CParser.Float, CParser.Int, CParser.Long, CParser.Restrict, CParser.Short, CParser.Signed, CParser.Struct, CParser.Union, CParser.Unsigned, CParser.Void, CParser.Volatile, CParser.Atomic, CParser.Bool, CParser.Complex, CParser.Identifier]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 594\n                self.specifierQualifierList()\n                self.state = 596\n                _la = self._input.LA(1)\n                if ((((_la - 59)) & ~0x3f) == 0 and ((1 << (_la - 59)) & ((1 << (CParser.LeftParen - 59)) | (1 << (CParser.Star - 59)) | (1 << (CParser.Caret - 59)) | (1 << (CParser.Colon - 59)) | (1 << (CParser.Identifier - 59)))) != 0):\n                    self.state = 595\n                    self.structDeclaratorList(0)\n\n\n                self.state = 598\n                self.match(CParser.Semi)\n\n            elif token in [CParser.StaticAssert]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 600\n                self.staticAssertDeclaration()\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class SpecifierQualifierListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def typeSpecifier(self):\n            return self.getTypedRuleContext(CParser.TypeSpecifierContext,0)\n\n\n        def specifierQualifierList(self):\n            return self.getTypedRuleContext(CParser.SpecifierQualifierListContext,0)\n\n\n        def typeQualifier(self):\n            return self.getTypedRuleContext(CParser.TypeQualifierContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_specifierQualifierList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterSpecifierQualifierList\" ):\n                listener.enterSpecifierQualifierList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitSpecifierQualifierList\" ):\n                listener.exitSpecifierQualifierList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitSpecifierQualifierList\" ):\n                return visitor.visitSpecifierQualifierList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def specifierQualifierList(self):\n\n        localctx = CParser.SpecifierQualifierListContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 72, self.RULE_specifierQualifierList)\n        try:\n            self.state = 611\n            la_ = self._interp.adaptivePredict(self._input,45,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 603\n                self.typeSpecifier()\n                self.state = 605\n                la_ = self._interp.adaptivePredict(self._input,43,self._ctx)\n                if la_ == 1:\n                    self.state = 604\n                    self.specifierQualifierList()\n\n\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 607\n                self.typeQualifier()\n                self.state = 609\n                la_ = self._interp.adaptivePredict(self._input,44,self._ctx)\n                if la_ == 1:\n                    self.state = 608\n                    self.specifierQualifierList()\n\n\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class StructDeclaratorListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def structDeclarator(self):\n            return self.getTypedRuleContext(CParser.StructDeclaratorContext,0)\n\n\n        def structDeclaratorList(self):\n            return self.getTypedRuleContext(CParser.StructDeclaratorListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_structDeclaratorList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStructDeclaratorList\" ):\n                listener.enterStructDeclaratorList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStructDeclaratorList\" ):\n                listener.exitStructDeclaratorList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStructDeclaratorList\" ):\n                return visitor.visitStructDeclaratorList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def structDeclaratorList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.StructDeclaratorListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 74\n        self.enterRecursionRule(localctx, 74, self.RULE_structDeclaratorList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 614\n            self.structDeclarator()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 621\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,46,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.StructDeclaratorListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_structDeclaratorList)\n                    self.state = 616\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 617\n                    self.match(CParser.Comma)\n                    self.state = 618\n                    self.structDeclarator()\n                self.state = 623\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,46,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class StructDeclaratorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declarator(self):\n            return self.getTypedRuleContext(CParser.DeclaratorContext,0)\n\n\n        def constantExpression(self):\n            return self.getTypedRuleContext(CParser.ConstantExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_structDeclarator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStructDeclarator\" ):\n                listener.enterStructDeclarator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStructDeclarator\" ):\n                listener.exitStructDeclarator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStructDeclarator\" ):\n                return visitor.visitStructDeclarator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def structDeclarator(self):\n\n        localctx = CParser.StructDeclaratorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 76, self.RULE_structDeclarator)\n        self._la = 0 # Token type\n        try:\n            self.state = 630\n            la_ = self._interp.adaptivePredict(self._input,48,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 624\n                self.declarator()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 626\n                _la = self._input.LA(1)\n                if ((((_la - 59)) & ~0x3f) == 0 and ((1 << (_la - 59)) & ((1 << (CParser.LeftParen - 59)) | (1 << (CParser.Star - 59)) | (1 << (CParser.Caret - 59)) | (1 << (CParser.Identifier - 59)))) != 0):\n                    self.state = 625\n                    self.declarator()\n\n\n                self.state = 628\n                self.match(CParser.Colon)\n                self.state = 629\n                self.constantExpression()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class EnumSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def enumeratorList(self):\n            return self.getTypedRuleContext(CParser.EnumeratorListContext,0)\n\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_enumSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterEnumSpecifier\" ):\n                listener.enterEnumSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitEnumSpecifier\" ):\n                listener.exitEnumSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitEnumSpecifier\" ):\n                return visitor.visitEnumSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def enumSpecifier(self):\n\n        localctx = CParser.EnumSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 78, self.RULE_enumSpecifier)\n        self._la = 0 # Token type\n        try:\n            self.state = 651\n            la_ = self._interp.adaptivePredict(self._input,51,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 632\n                self.match(CParser.Enum)\n                self.state = 634\n                _la = self._input.LA(1)\n                if _la==CParser.Identifier:\n                    self.state = 633\n                    self.match(CParser.Identifier)\n\n\n                self.state = 636\n                self.match(CParser.LeftBrace)\n                self.state = 637\n                self.enumeratorList(0)\n                self.state = 638\n                self.match(CParser.RightBrace)\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 640\n                self.match(CParser.Enum)\n                self.state = 642\n                _la = self._input.LA(1)\n                if _la==CParser.Identifier:\n                    self.state = 641\n                    self.match(CParser.Identifier)\n\n\n                self.state = 644\n                self.match(CParser.LeftBrace)\n                self.state = 645\n                self.enumeratorList(0)\n                self.state = 646\n                self.match(CParser.Comma)\n                self.state = 647\n                self.match(CParser.RightBrace)\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 649\n                self.match(CParser.Enum)\n                self.state = 650\n                self.match(CParser.Identifier)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class EnumeratorListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def enumerator(self):\n            return self.getTypedRuleContext(CParser.EnumeratorContext,0)\n\n\n        def enumeratorList(self):\n            return self.getTypedRuleContext(CParser.EnumeratorListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_enumeratorList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterEnumeratorList\" ):\n                listener.enterEnumeratorList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitEnumeratorList\" ):\n                listener.exitEnumeratorList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitEnumeratorList\" ):\n                return visitor.visitEnumeratorList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def enumeratorList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.EnumeratorListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 80\n        self.enterRecursionRule(localctx, 80, self.RULE_enumeratorList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 654\n            self.enumerator()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 661\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,52,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.EnumeratorListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_enumeratorList)\n                    self.state = 656\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 657\n                    self.match(CParser.Comma)\n                    self.state = 658\n                    self.enumerator()\n                self.state = 663\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,52,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class EnumeratorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def enumerationConstant(self):\n            return self.getTypedRuleContext(CParser.EnumerationConstantContext,0)\n\n\n        def constantExpression(self):\n            return self.getTypedRuleContext(CParser.ConstantExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_enumerator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterEnumerator\" ):\n                listener.enterEnumerator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitEnumerator\" ):\n                listener.exitEnumerator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitEnumerator\" ):\n                return visitor.visitEnumerator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def enumerator(self):\n\n        localctx = CParser.EnumeratorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 82, self.RULE_enumerator)\n        try:\n            self.state = 669\n            la_ = self._interp.adaptivePredict(self._input,53,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 664\n                self.enumerationConstant()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 665\n                self.enumerationConstant()\n                self.state = 666\n                self.match(CParser.Assign)\n                self.state = 667\n                self.constantExpression()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class EnumerationConstantContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_enumerationConstant\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterEnumerationConstant\" ):\n                listener.enterEnumerationConstant(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitEnumerationConstant\" ):\n                listener.exitEnumerationConstant(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitEnumerationConstant\" ):\n                return visitor.visitEnumerationConstant(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def enumerationConstant(self):\n\n        localctx = CParser.EnumerationConstantContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 84, self.RULE_enumerationConstant)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 671\n            self.match(CParser.Identifier)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class AtomicTypeSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def typeName(self):\n            return self.getTypedRuleContext(CParser.TypeNameContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_atomicTypeSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAtomicTypeSpecifier\" ):\n                listener.enterAtomicTypeSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAtomicTypeSpecifier\" ):\n                listener.exitAtomicTypeSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAtomicTypeSpecifier\" ):\n                return visitor.visitAtomicTypeSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def atomicTypeSpecifier(self):\n\n        localctx = CParser.AtomicTypeSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 86, self.RULE_atomicTypeSpecifier)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 673\n            self.match(CParser.Atomic)\n            self.state = 674\n            self.match(CParser.LeftParen)\n            self.state = 675\n            self.typeName()\n            self.state = 676\n            self.match(CParser.RightParen)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class TypeQualifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_typeQualifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterTypeQualifier\" ):\n                listener.enterTypeQualifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitTypeQualifier\" ):\n                listener.exitTypeQualifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitTypeQualifier\" ):\n                return visitor.visitTypeQualifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def typeQualifier(self):\n\n        localctx = CParser.TypeQualifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 88, self.RULE_typeQualifier)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 678\n            _la = self._input.LA(1)\n            if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0)):\n                self._errHandler.recoverInline(self)\n            else:\n                self.consume()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class FunctionSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def gccAttributeSpecifier(self):\n            return self.getTypedRuleContext(CParser.GccAttributeSpecifierContext,0)\n\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_functionSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterFunctionSpecifier\" ):\n                listener.enterFunctionSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitFunctionSpecifier\" ):\n                listener.exitFunctionSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitFunctionSpecifier\" ):\n                return visitor.visitFunctionSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def functionSpecifier(self):\n\n        localctx = CParser.FunctionSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 90, self.RULE_functionSpecifier)\n        self._la = 0 # Token type\n        try:\n            self.state = 686\n            token = self._input.LA(1)\n            if token in [CParser.T__7, CParser.T__8, CParser.Inline, CParser.Noreturn]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 680\n                _la = self._input.LA(1)\n                if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__7) | (1 << CParser.T__8) | (1 << CParser.Inline) | (1 << CParser.Noreturn))) != 0)):\n                    self._errHandler.recoverInline(self)\n                else:\n                    self.consume()\n\n            elif token in [CParser.T__11]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 681\n                self.gccAttributeSpecifier()\n\n            elif token in [CParser.T__9]:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 682\n                self.match(CParser.T__9)\n                self.state = 683\n                self.match(CParser.LeftParen)\n                self.state = 684\n                self.match(CParser.Identifier)\n                self.state = 685\n                self.match(CParser.RightParen)\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class AlignmentSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def typeName(self):\n            return self.getTypedRuleContext(CParser.TypeNameContext,0)\n\n\n        def constantExpression(self):\n            return self.getTypedRuleContext(CParser.ConstantExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_alignmentSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAlignmentSpecifier\" ):\n                listener.enterAlignmentSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAlignmentSpecifier\" ):\n                listener.exitAlignmentSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAlignmentSpecifier\" ):\n                return visitor.visitAlignmentSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def alignmentSpecifier(self):\n\n        localctx = CParser.AlignmentSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 92, self.RULE_alignmentSpecifier)\n        try:\n            self.state = 698\n            la_ = self._interp.adaptivePredict(self._input,55,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 688\n                self.match(CParser.Alignas)\n                self.state = 689\n                self.match(CParser.LeftParen)\n                self.state = 690\n                self.typeName()\n                self.state = 691\n                self.match(CParser.RightParen)\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 693\n                self.match(CParser.Alignas)\n                self.state = 694\n                self.match(CParser.LeftParen)\n                self.state = 695\n                self.constantExpression()\n                self.state = 696\n                self.match(CParser.RightParen)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DeclaratorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def directDeclarator(self):\n            return self.getTypedRuleContext(CParser.DirectDeclaratorContext,0)\n\n\n        def pointer(self):\n            return self.getTypedRuleContext(CParser.PointerContext,0)\n\n\n        def gccDeclaratorExtension(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.GccDeclaratorExtensionContext)\n            else:\n                return self.getTypedRuleContext(CParser.GccDeclaratorExtensionContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_declarator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDeclarator\" ):\n                listener.enterDeclarator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDeclarator\" ):\n                listener.exitDeclarator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDeclarator\" ):\n                return visitor.visitDeclarator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def declarator(self):\n\n        localctx = CParser.DeclaratorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 94, self.RULE_declarator)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 701\n            _la = self._input.LA(1)\n            if _la==CParser.Star or _la==CParser.Caret:\n                self.state = 700\n                self.pointer()\n\n\n            self.state = 703\n            self.directDeclarator(0)\n            self.state = 707\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,57,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    self.state = 704\n                    self.gccDeclaratorExtension()\n                self.state = 709\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,57,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DirectDeclaratorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def declarator(self):\n            return self.getTypedRuleContext(CParser.DeclaratorContext,0)\n\n\n        def directDeclarator(self):\n            return self.getTypedRuleContext(CParser.DirectDeclaratorContext,0)\n\n\n        def typeQualifierList(self):\n            return self.getTypedRuleContext(CParser.TypeQualifierListContext,0)\n\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def parameterTypeList(self):\n            return self.getTypedRuleContext(CParser.ParameterTypeListContext,0)\n\n\n        def identifierList(self):\n            return self.getTypedRuleContext(CParser.IdentifierListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_directDeclarator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDirectDeclarator\" ):\n                listener.enterDirectDeclarator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDirectDeclarator\" ):\n                listener.exitDirectDeclarator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDirectDeclarator\" ):\n                return visitor.visitDirectDeclarator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def directDeclarator(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.DirectDeclaratorContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 96\n        self.enterRecursionRule(localctx, 96, self.RULE_directDeclarator, _p)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 716\n            token = self._input.LA(1)\n            if token in [CParser.Identifier]:\n                self.state = 711\n                self.match(CParser.Identifier)\n\n            elif token in [CParser.LeftParen]:\n                self.state = 712\n                self.match(CParser.LeftParen)\n                self.state = 713\n                self.declarator()\n                self.state = 714\n                self.match(CParser.RightParen)\n\n            else:\n                raise NoViableAltException(self)\n\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 763\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,65,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 761\n                    la_ = self._interp.adaptivePredict(self._input,64,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.DirectDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directDeclarator)\n                        self.state = 718\n                        if not self.precpred(self._ctx, 6):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 6)\")\n                        self.state = 719\n                        self.match(CParser.LeftBracket)\n                        self.state = 721\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                            self.state = 720\n                            self.typeQualifierList(0)\n\n\n                        self.state = 724\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                            self.state = 723\n                            self.assignmentExpression()\n\n\n                        self.state = 726\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.DirectDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directDeclarator)\n                        self.state = 727\n                        if not self.precpred(self._ctx, 5):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 5)\")\n                        self.state = 728\n                        self.match(CParser.LeftBracket)\n                        self.state = 729\n                        self.match(CParser.Static)\n                        self.state = 731\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                            self.state = 730\n                            self.typeQualifierList(0)\n\n\n                        self.state = 733\n                        self.assignmentExpression()\n                        self.state = 734\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 3:\n                        localctx = CParser.DirectDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directDeclarator)\n                        self.state = 736\n                        if not self.precpred(self._ctx, 4):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 4)\")\n                        self.state = 737\n                        self.match(CParser.LeftBracket)\n                        self.state = 738\n                        self.typeQualifierList(0)\n                        self.state = 739\n                        self.match(CParser.Static)\n                        self.state = 740\n                        self.assignmentExpression()\n                        self.state = 741\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 4:\n                        localctx = CParser.DirectDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directDeclarator)\n                        self.state = 743\n                        if not self.precpred(self._ctx, 3):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 3)\")\n                        self.state = 744\n                        self.match(CParser.LeftBracket)\n                        self.state = 746\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                            self.state = 745\n                            self.typeQualifierList(0)\n\n\n                        self.state = 748\n                        self.match(CParser.Star)\n                        self.state = 749\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 5:\n                        localctx = CParser.DirectDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directDeclarator)\n                        self.state = 750\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 751\n                        self.match(CParser.LeftParen)\n                        self.state = 752\n                        self.parameterTypeList()\n                        self.state = 753\n                        self.match(CParser.RightParen)\n                        pass\n\n                    elif la_ == 6:\n                        localctx = CParser.DirectDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directDeclarator)\n                        self.state = 755\n                        if not self.precpred(self._ctx, 1):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                        self.state = 756\n                        self.match(CParser.LeftParen)\n                        self.state = 758\n                        _la = self._input.LA(1)\n                        if _la==CParser.Identifier:\n                            self.state = 757\n                            self.identifierList(0)\n\n\n                        self.state = 760\n                        self.match(CParser.RightParen)\n                        pass\n\n\n                self.state = 765\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,65,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class GccDeclaratorExtensionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def StringLiteral(self, i:int=None):\n            if i is None:\n                return self.getTokens(CParser.StringLiteral)\n            else:\n                return self.getToken(CParser.StringLiteral, i)\n\n        def gccAttributeSpecifier(self):\n            return self.getTypedRuleContext(CParser.GccAttributeSpecifierContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_gccDeclaratorExtension\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterGccDeclaratorExtension\" ):\n                listener.enterGccDeclaratorExtension(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitGccDeclaratorExtension\" ):\n                listener.exitGccDeclaratorExtension(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGccDeclaratorExtension\" ):\n                return visitor.visitGccDeclaratorExtension(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def gccDeclaratorExtension(self):\n\n        localctx = CParser.GccDeclaratorExtensionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 98, self.RULE_gccDeclaratorExtension)\n        self._la = 0 # Token type\n        try:\n            self.state = 775\n            token = self._input.LA(1)\n            if token in [CParser.T__10]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 766\n                self.match(CParser.T__10)\n                self.state = 767\n                self.match(CParser.LeftParen)\n                self.state = 769\n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                while True:\n                    self.state = 768\n                    self.match(CParser.StringLiteral)\n                    self.state = 771\n                    self._errHandler.sync(self)\n                    _la = self._input.LA(1)\n                    if not (_la==CParser.StringLiteral):\n                        break\n\n                self.state = 773\n                self.match(CParser.RightParen)\n\n            elif token in [CParser.T__11]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 774\n                self.gccAttributeSpecifier()\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class GccAttributeSpecifierContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def gccAttributeList(self):\n            return self.getTypedRuleContext(CParser.GccAttributeListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_gccAttributeSpecifier\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterGccAttributeSpecifier\" ):\n                listener.enterGccAttributeSpecifier(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitGccAttributeSpecifier\" ):\n                listener.exitGccAttributeSpecifier(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGccAttributeSpecifier\" ):\n                return visitor.visitGccAttributeSpecifier(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def gccAttributeSpecifier(self):\n\n        localctx = CParser.GccAttributeSpecifierContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 100, self.RULE_gccAttributeSpecifier)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 777\n            self.match(CParser.T__11)\n            self.state = 778\n            self.match(CParser.LeftParen)\n            self.state = 779\n            self.match(CParser.LeftParen)\n            self.state = 780\n            self.gccAttributeList()\n            self.state = 781\n            self.match(CParser.RightParen)\n            self.state = 782\n            self.match(CParser.RightParen)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class GccAttributeListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def gccAttribute(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.GccAttributeContext)\n            else:\n                return self.getTypedRuleContext(CParser.GccAttributeContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_gccAttributeList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterGccAttributeList\" ):\n                listener.enterGccAttributeList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitGccAttributeList\" ):\n                listener.exitGccAttributeList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGccAttributeList\" ):\n                return visitor.visitGccAttributeList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def gccAttributeList(self):\n\n        localctx = CParser.GccAttributeListContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 102, self.RULE_gccAttributeList)\n        self._la = 0 # Token type\n        try:\n            self.state = 793\n            la_ = self._interp.adaptivePredict(self._input,69,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 784\n                self.gccAttribute()\n                self.state = 789\n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                while _la==CParser.Comma:\n                    self.state = 785\n                    self.match(CParser.Comma)\n                    self.state = 786\n                    self.gccAttribute()\n                    self.state = 791\n                    self._errHandler.sync(self)\n                    _la = self._input.LA(1)\n\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class GccAttributeContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def argumentExpressionList(self):\n            return self.getTypedRuleContext(CParser.ArgumentExpressionListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_gccAttribute\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterGccAttribute\" ):\n                listener.enterGccAttribute(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitGccAttribute\" ):\n                listener.exitGccAttribute(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGccAttribute\" ):\n                return visitor.visitGccAttribute(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def gccAttribute(self):\n\n        localctx = CParser.GccAttributeContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 104, self.RULE_gccAttribute)\n        self._la = 0 # Token type\n        try:\n            self.state = 804\n            token = self._input.LA(1)\n            if token in [CParser.T__0, CParser.T__1, CParser.T__2, CParser.T__3, CParser.T__4, CParser.T__5, CParser.T__6, CParser.T__7, CParser.T__8, CParser.T__9, CParser.T__10, CParser.T__11, CParser.T__12, CParser.T__13, CParser.Auto, CParser.Break, CParser.Case, CParser.Char, CParser.Const, CParser.Continue, CParser.Default, CParser.Do, CParser.Double, CParser.Else, CParser.Enum, CParser.Extern, CParser.Float, CParser.For, CParser.Goto, CParser.If, CParser.Inline, CParser.Int, CParser.Long, CParser.Register, CParser.Restrict, CParser.Return, CParser.Short, CParser.Signed, CParser.Sizeof, CParser.Static, CParser.Struct, CParser.Switch, CParser.Typedef, CParser.Union, CParser.Unsigned, CParser.Void, CParser.Volatile, CParser.While, CParser.Alignas, CParser.Alignof, CParser.Atomic, CParser.Bool, CParser.Complex, CParser.Generic, CParser.Imaginary, CParser.Noreturn, CParser.StaticAssert, CParser.ThreadLocal, CParser.LeftBracket, CParser.RightBracket, CParser.LeftBrace, CParser.RightBrace, CParser.Less, CParser.LessEqual, CParser.Greater, CParser.GreaterEqual, CParser.LeftShift, CParser.RightShift, CParser.Plus, CParser.PlusPlus, CParser.Minus, CParser.MinusMinus, CParser.Star, CParser.Div, CParser.Mod, CParser.And, CParser.Or, CParser.AndAnd, CParser.OrOr, CParser.Caret, CParser.Not, CParser.Tilde, CParser.Question, CParser.Colon, CParser.Semi, CParser.Assign, CParser.StarAssign, CParser.DivAssign, CParser.ModAssign, CParser.PlusAssign, CParser.MinusAssign, CParser.LeftShiftAssign, CParser.RightShiftAssign, CParser.AndAssign, CParser.XorAssign, CParser.OrAssign, CParser.Equal, CParser.NotEqual, CParser.Arrow, CParser.Dot, CParser.Ellipsis, CParser.Identifier, CParser.Constant, CParser.StringLiteral, CParser.LineDirective, CParser.PragmaDirective, CParser.Whitespace, CParser.Newline, CParser.BlockComment, CParser.LineComment]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 795\n                _la = self._input.LA(1)\n                if _la <= 0 or ((((_la - 59)) & ~0x3f) == 0 and ((1 << (_la - 59)) & ((1 << (CParser.LeftParen - 59)) | (1 << (CParser.RightParen - 59)) | (1 << (CParser.Comma - 59)))) != 0):\n                    self._errHandler.recoverInline(self)\n                else:\n                    self.consume()\n                self.state = 801\n                _la = self._input.LA(1)\n                if _la==CParser.LeftParen:\n                    self.state = 796\n                    self.match(CParser.LeftParen)\n                    self.state = 798\n                    _la = self._input.LA(1)\n                    if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                        self.state = 797\n                        self.argumentExpressionList(0)\n\n\n                    self.state = 800\n                    self.match(CParser.RightParen)\n\n\n\n            elif token in [CParser.RightParen, CParser.Comma]:\n                self.enterOuterAlt(localctx, 2)\n\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class NestedParenthesesBlockContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def nestedParenthesesBlock(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.NestedParenthesesBlockContext)\n            else:\n                return self.getTypedRuleContext(CParser.NestedParenthesesBlockContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_nestedParenthesesBlock\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterNestedParenthesesBlock\" ):\n                listener.enterNestedParenthesesBlock(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitNestedParenthesesBlock\" ):\n                listener.exitNestedParenthesesBlock(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitNestedParenthesesBlock\" ):\n                return visitor.visitNestedParenthesesBlock(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def nestedParenthesesBlock(self):\n\n        localctx = CParser.NestedParenthesesBlockContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 106, self.RULE_nestedParenthesesBlock)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 813\n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5) | (1 << CParser.T__6) | (1 << CParser.T__7) | (1 << CParser.T__8) | (1 << CParser.T__9) | (1 << CParser.T__10) | (1 << CParser.T__11) | (1 << CParser.T__12) | (1 << CParser.T__13) | (1 << CParser.Auto) | (1 << CParser.Break) | (1 << CParser.Case) | (1 << CParser.Char) | (1 << CParser.Const) | (1 << CParser.Continue) | (1 << CParser.Default) | (1 << CParser.Do) | (1 << CParser.Double) | (1 << CParser.Else) | (1 << CParser.Enum) | (1 << CParser.Extern) | (1 << CParser.Float) | (1 << CParser.For) | (1 << CParser.Goto) | (1 << CParser.If) | (1 << CParser.Inline) | (1 << CParser.Int) | (1 << CParser.Long) | (1 << CParser.Register) | (1 << CParser.Restrict) | (1 << CParser.Return) | (1 << CParser.Short) | (1 << CParser.Signed) | (1 << CParser.Sizeof) | (1 << CParser.Static) | (1 << CParser.Struct) | (1 << CParser.Switch) | (1 << CParser.Typedef) | (1 << CParser.Union) | (1 << CParser.Unsigned) | (1 << CParser.Void) | (1 << CParser.Volatile) | (1 << CParser.While) | (1 << CParser.Alignas) | (1 << CParser.Alignof) | (1 << CParser.Atomic) | (1 << CParser.Bool) | (1 << CParser.Complex) | (1 << CParser.Generic) | (1 << CParser.Imaginary) | (1 << CParser.Noreturn) | (1 << CParser.StaticAssert) | (1 << CParser.ThreadLocal) | (1 << CParser.LeftParen) | (1 << CParser.LeftBracket) | (1 << CParser.RightBracket) | (1 << CParser.LeftBrace))) != 0) or ((((_la - 64)) & ~0x3f) == 0 and ((1 << (_la - 64)) & ((1 << (CParser.RightBrace - 64)) | (1 << (CParser.Less - 64)) | (1 << (CParser.LessEqual - 64)) | (1 << (CParser.Greater - 64)) | (1 << (CParser.GreaterEqual - 64)) | (1 << (CParser.LeftShift - 64)) | (1 << (CParser.RightShift - 64)) | (1 << (CParser.Plus - 64)) | (1 << (CParser.PlusPlus - 64)) | (1 << (CParser.Minus - 64)) | (1 << (CParser.MinusMinus - 64)) | (1 << (CParser.Star - 64)) | (1 << (CParser.Div - 64)) | (1 << (CParser.Mod - 64)) | (1 << (CParser.And - 64)) | (1 << (CParser.Or - 64)) | (1 << (CParser.AndAnd - 64)) | (1 << (CParser.OrOr - 64)) | (1 << (CParser.Caret - 64)) | (1 << (CParser.Not - 64)) | (1 << (CParser.Tilde - 64)) | (1 << (CParser.Question - 64)) | (1 << (CParser.Colon - 64)) | (1 << (CParser.Semi - 64)) | (1 << (CParser.Comma - 64)) | (1 << (CParser.Assign - 64)) | (1 << (CParser.StarAssign - 64)) | (1 << (CParser.DivAssign - 64)) | (1 << (CParser.ModAssign - 64)) | (1 << (CParser.PlusAssign - 64)) | (1 << (CParser.MinusAssign - 64)) | (1 << (CParser.LeftShiftAssign - 64)) | (1 << (CParser.RightShiftAssign - 64)) | (1 << (CParser.AndAssign - 64)) | (1 << (CParser.XorAssign - 64)) | (1 << (CParser.OrAssign - 64)) | (1 << (CParser.Equal - 64)) | (1 << (CParser.NotEqual - 64)) | (1 << (CParser.Arrow - 64)) | (1 << (CParser.Dot - 64)) | (1 << (CParser.Ellipsis - 64)) | (1 << (CParser.Identifier - 64)) | (1 << (CParser.Constant - 64)) | (1 << (CParser.StringLiteral - 64)) | (1 << (CParser.LineDirective - 64)) | (1 << (CParser.PragmaDirective - 64)) | (1 << (CParser.Whitespace - 64)) | (1 << (CParser.Newline - 64)) | (1 << (CParser.BlockComment - 64)) | (1 << (CParser.LineComment - 64)))) != 0):\n                self.state = 811\n                token = self._input.LA(1)\n                if token in [CParser.T__0, CParser.T__1, CParser.T__2, CParser.T__3, CParser.T__4, CParser.T__5, CParser.T__6, CParser.T__7, CParser.T__8, CParser.T__9, CParser.T__10, CParser.T__11, CParser.T__12, CParser.T__13, CParser.Auto, CParser.Break, CParser.Case, CParser.Char, CParser.Const, CParser.Continue, CParser.Default, CParser.Do, CParser.Double, CParser.Else, CParser.Enum, CParser.Extern, CParser.Float, CParser.For, CParser.Goto, CParser.If, CParser.Inline, CParser.Int, CParser.Long, CParser.Register, CParser.Restrict, CParser.Return, CParser.Short, CParser.Signed, CParser.Sizeof, CParser.Static, CParser.Struct, CParser.Switch, CParser.Typedef, CParser.Union, CParser.Unsigned, CParser.Void, CParser.Volatile, CParser.While, CParser.Alignas, CParser.Alignof, CParser.Atomic, CParser.Bool, CParser.Complex, CParser.Generic, CParser.Imaginary, CParser.Noreturn, CParser.StaticAssert, CParser.ThreadLocal, CParser.LeftBracket, CParser.RightBracket, CParser.LeftBrace, CParser.RightBrace, CParser.Less, CParser.LessEqual, CParser.Greater, CParser.GreaterEqual, CParser.LeftShift, CParser.RightShift, CParser.Plus, CParser.PlusPlus, CParser.Minus, CParser.MinusMinus, CParser.Star, CParser.Div, CParser.Mod, CParser.And, CParser.Or, CParser.AndAnd, CParser.OrOr, CParser.Caret, CParser.Not, CParser.Tilde, CParser.Question, CParser.Colon, CParser.Semi, CParser.Comma, CParser.Assign, CParser.StarAssign, CParser.DivAssign, CParser.ModAssign, CParser.PlusAssign, CParser.MinusAssign, CParser.LeftShiftAssign, CParser.RightShiftAssign, CParser.AndAssign, CParser.XorAssign, CParser.OrAssign, CParser.Equal, CParser.NotEqual, CParser.Arrow, CParser.Dot, CParser.Ellipsis, CParser.Identifier, CParser.Constant, CParser.StringLiteral, CParser.LineDirective, CParser.PragmaDirective, CParser.Whitespace, CParser.Newline, CParser.BlockComment, CParser.LineComment]:\n                    self.state = 806\n                    _la = self._input.LA(1)\n                    if _la <= 0 or _la==CParser.LeftParen or _la==CParser.RightParen:\n                        self._errHandler.recoverInline(self)\n                    else:\n                        self.consume()\n\n                elif token in [CParser.LeftParen]:\n                    self.state = 807\n                    self.match(CParser.LeftParen)\n                    self.state = 808\n                    self.nestedParenthesesBlock()\n                    self.state = 809\n                    self.match(CParser.RightParen)\n\n                else:\n                    raise NoViableAltException(self)\n\n                self.state = 815\n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class PointerContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def typeQualifierList(self):\n            return self.getTypedRuleContext(CParser.TypeQualifierListContext,0)\n\n\n        def pointer(self):\n            return self.getTypedRuleContext(CParser.PointerContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_pointer\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterPointer\" ):\n                listener.enterPointer(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitPointer\" ):\n                listener.exitPointer(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitPointer\" ):\n                return visitor.visitPointer(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def pointer(self):\n\n        localctx = CParser.PointerContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 108, self.RULE_pointer)\n        self._la = 0 # Token type\n        try:\n            self.state = 834\n            la_ = self._interp.adaptivePredict(self._input,79,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 816\n                self.match(CParser.Star)\n                self.state = 818\n                la_ = self._interp.adaptivePredict(self._input,75,self._ctx)\n                if la_ == 1:\n                    self.state = 817\n                    self.typeQualifierList(0)\n\n\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 820\n                self.match(CParser.Star)\n                self.state = 822\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                    self.state = 821\n                    self.typeQualifierList(0)\n\n\n                self.state = 824\n                self.pointer()\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 825\n                self.match(CParser.Caret)\n                self.state = 827\n                la_ = self._interp.adaptivePredict(self._input,77,self._ctx)\n                if la_ == 1:\n                    self.state = 826\n                    self.typeQualifierList(0)\n\n\n                pass\n\n            elif la_ == 4:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 829\n                self.match(CParser.Caret)\n                self.state = 831\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                    self.state = 830\n                    self.typeQualifierList(0)\n\n\n                self.state = 833\n                self.pointer()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class TypeQualifierListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def typeQualifier(self):\n            return self.getTypedRuleContext(CParser.TypeQualifierContext,0)\n\n\n        def typeQualifierList(self):\n            return self.getTypedRuleContext(CParser.TypeQualifierListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_typeQualifierList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterTypeQualifierList\" ):\n                listener.enterTypeQualifierList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitTypeQualifierList\" ):\n                listener.exitTypeQualifierList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitTypeQualifierList\" ):\n                return visitor.visitTypeQualifierList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def typeQualifierList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.TypeQualifierListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 110\n        self.enterRecursionRule(localctx, 110, self.RULE_typeQualifierList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 837\n            self.typeQualifier()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 843\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,80,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.TypeQualifierListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_typeQualifierList)\n                    self.state = 839\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 840\n                    self.typeQualifier()\n                self.state = 845\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,80,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ParameterTypeListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def parameterList(self):\n            return self.getTypedRuleContext(CParser.ParameterListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_parameterTypeList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterParameterTypeList\" ):\n                listener.enterParameterTypeList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitParameterTypeList\" ):\n                listener.exitParameterTypeList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitParameterTypeList\" ):\n                return visitor.visitParameterTypeList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def parameterTypeList(self):\n\n        localctx = CParser.ParameterTypeListContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 112, self.RULE_parameterTypeList)\n        try:\n            self.state = 851\n            la_ = self._interp.adaptivePredict(self._input,81,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 846\n                self.parameterList(0)\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 847\n                self.parameterList(0)\n                self.state = 848\n                self.match(CParser.Comma)\n                self.state = 849\n                self.match(CParser.Ellipsis)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class ParameterListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def parameterDeclaration(self):\n            return self.getTypedRuleContext(CParser.ParameterDeclarationContext,0)\n\n\n        def parameterList(self):\n            return self.getTypedRuleContext(CParser.ParameterListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_parameterList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterParameterList\" ):\n                listener.enterParameterList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitParameterList\" ):\n                listener.exitParameterList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitParameterList\" ):\n                return visitor.visitParameterList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def parameterList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.ParameterListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 114\n        self.enterRecursionRule(localctx, 114, self.RULE_parameterList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 854\n            self.parameterDeclaration()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 861\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,82,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.ParameterListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_parameterList)\n                    self.state = 856\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 857\n                    self.match(CParser.Comma)\n                    self.state = 858\n                    self.parameterDeclaration()\n                self.state = 863\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,82,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ParameterDeclarationContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declarationSpecifiers(self):\n            return self.getTypedRuleContext(CParser.DeclarationSpecifiersContext,0)\n\n\n        def declarator(self):\n            return self.getTypedRuleContext(CParser.DeclaratorContext,0)\n\n\n        def declarationSpecifiers2(self):\n            return self.getTypedRuleContext(CParser.DeclarationSpecifiers2Context,0)\n\n\n        def abstractDeclarator(self):\n            return self.getTypedRuleContext(CParser.AbstractDeclaratorContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_parameterDeclaration\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterParameterDeclaration\" ):\n                listener.enterParameterDeclaration(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitParameterDeclaration\" ):\n                listener.exitParameterDeclaration(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitParameterDeclaration\" ):\n                return visitor.visitParameterDeclaration(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def parameterDeclaration(self):\n\n        localctx = CParser.ParameterDeclarationContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 116, self.RULE_parameterDeclaration)\n        try:\n            self.state = 871\n            la_ = self._interp.adaptivePredict(self._input,84,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 864\n                self.declarationSpecifiers()\n                self.state = 865\n                self.declarator()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 867\n                self.declarationSpecifiers2()\n                self.state = 869\n                la_ = self._interp.adaptivePredict(self._input,83,self._ctx)\n                if la_ == 1:\n                    self.state = 868\n                    self.abstractDeclarator()\n\n\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class IdentifierListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def identifierList(self):\n            return self.getTypedRuleContext(CParser.IdentifierListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_identifierList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterIdentifierList\" ):\n                listener.enterIdentifierList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitIdentifierList\" ):\n                listener.exitIdentifierList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitIdentifierList\" ):\n                return visitor.visitIdentifierList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def identifierList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.IdentifierListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 118\n        self.enterRecursionRule(localctx, 118, self.RULE_identifierList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 874\n            self.match(CParser.Identifier)\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 881\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,85,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.IdentifierListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_identifierList)\n                    self.state = 876\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 877\n                    self.match(CParser.Comma)\n                    self.state = 878\n                    self.match(CParser.Identifier)\n                self.state = 883\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,85,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class TypeNameContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def specifierQualifierList(self):\n            return self.getTypedRuleContext(CParser.SpecifierQualifierListContext,0)\n\n\n        def abstractDeclarator(self):\n            return self.getTypedRuleContext(CParser.AbstractDeclaratorContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_typeName\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterTypeName\" ):\n                listener.enterTypeName(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitTypeName\" ):\n                listener.exitTypeName(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitTypeName\" ):\n                return visitor.visitTypeName(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def typeName(self):\n\n        localctx = CParser.TypeNameContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 120, self.RULE_typeName)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 884\n            self.specifierQualifierList()\n            self.state = 886\n            _la = self._input.LA(1)\n            if ((((_la - 59)) & ~0x3f) == 0 and ((1 << (_la - 59)) & ((1 << (CParser.LeftParen - 59)) | (1 << (CParser.LeftBracket - 59)) | (1 << (CParser.Star - 59)) | (1 << (CParser.Caret - 59)))) != 0):\n                self.state = 885\n                self.abstractDeclarator()\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class AbstractDeclaratorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def pointer(self):\n            return self.getTypedRuleContext(CParser.PointerContext,0)\n\n\n        def directAbstractDeclarator(self):\n            return self.getTypedRuleContext(CParser.DirectAbstractDeclaratorContext,0)\n\n\n        def gccDeclaratorExtension(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.GccDeclaratorExtensionContext)\n            else:\n                return self.getTypedRuleContext(CParser.GccDeclaratorExtensionContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_abstractDeclarator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterAbstractDeclarator\" ):\n                listener.enterAbstractDeclarator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitAbstractDeclarator\" ):\n                listener.exitAbstractDeclarator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAbstractDeclarator\" ):\n                return visitor.visitAbstractDeclarator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def abstractDeclarator(self):\n\n        localctx = CParser.AbstractDeclaratorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 122, self.RULE_abstractDeclarator)\n        self._la = 0 # Token type\n        try:\n            self.state = 899\n            la_ = self._interp.adaptivePredict(self._input,89,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 888\n                self.pointer()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 890\n                _la = self._input.LA(1)\n                if _la==CParser.Star or _la==CParser.Caret:\n                    self.state = 889\n                    self.pointer()\n\n\n                self.state = 892\n                self.directAbstractDeclarator(0)\n                self.state = 896\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,88,self._ctx)\n                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                    if _alt==1:\n                        self.state = 893\n                        self.gccDeclaratorExtension()\n                    self.state = 898\n                    self._errHandler.sync(self)\n                    _alt = self._interp.adaptivePredict(self._input,88,self._ctx)\n\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DirectAbstractDeclaratorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def abstractDeclarator(self):\n            return self.getTypedRuleContext(CParser.AbstractDeclaratorContext,0)\n\n\n        def gccDeclaratorExtension(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.GccDeclaratorExtensionContext)\n            else:\n                return self.getTypedRuleContext(CParser.GccDeclaratorExtensionContext,i)\n\n\n        def typeQualifierList(self):\n            return self.getTypedRuleContext(CParser.TypeQualifierListContext,0)\n\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def parameterTypeList(self):\n            return self.getTypedRuleContext(CParser.ParameterTypeListContext,0)\n\n\n        def directAbstractDeclarator(self):\n            return self.getTypedRuleContext(CParser.DirectAbstractDeclaratorContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_directAbstractDeclarator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDirectAbstractDeclarator\" ):\n                listener.enterDirectAbstractDeclarator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDirectAbstractDeclarator\" ):\n                listener.exitDirectAbstractDeclarator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDirectAbstractDeclarator\" ):\n                return visitor.visitDirectAbstractDeclarator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def directAbstractDeclarator(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.DirectAbstractDeclaratorContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 124\n        self.enterRecursionRule(localctx, 124, self.RULE_directAbstractDeclarator, _p)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 947\n            la_ = self._interp.adaptivePredict(self._input,96,self._ctx)\n            if la_ == 1:\n                self.state = 902\n                self.match(CParser.LeftParen)\n                self.state = 903\n                self.abstractDeclarator()\n                self.state = 904\n                self.match(CParser.RightParen)\n                self.state = 908\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,90,self._ctx)\n                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                    if _alt==1:\n                        self.state = 905\n                        self.gccDeclaratorExtension()\n                    self.state = 910\n                    self._errHandler.sync(self)\n                    _alt = self._interp.adaptivePredict(self._input,90,self._ctx)\n\n                pass\n\n            elif la_ == 2:\n                self.state = 911\n                self.match(CParser.LeftBracket)\n                self.state = 913\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                    self.state = 912\n                    self.typeQualifierList(0)\n\n\n                self.state = 916\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 915\n                    self.assignmentExpression()\n\n\n                self.state = 918\n                self.match(CParser.RightBracket)\n                pass\n\n            elif la_ == 3:\n                self.state = 919\n                self.match(CParser.LeftBracket)\n                self.state = 920\n                self.match(CParser.Static)\n                self.state = 922\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                    self.state = 921\n                    self.typeQualifierList(0)\n\n\n                self.state = 924\n                self.assignmentExpression()\n                self.state = 925\n                self.match(CParser.RightBracket)\n                pass\n\n            elif la_ == 4:\n                self.state = 927\n                self.match(CParser.LeftBracket)\n                self.state = 928\n                self.typeQualifierList(0)\n                self.state = 929\n                self.match(CParser.Static)\n                self.state = 930\n                self.assignmentExpression()\n                self.state = 931\n                self.match(CParser.RightBracket)\n                pass\n\n            elif la_ == 5:\n                self.state = 933\n                self.match(CParser.LeftBracket)\n                self.state = 934\n                self.match(CParser.Star)\n                self.state = 935\n                self.match(CParser.RightBracket)\n                pass\n\n            elif la_ == 6:\n                self.state = 936\n                self.match(CParser.LeftParen)\n                self.state = 938\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5) | (1 << CParser.T__6) | (1 << CParser.T__7) | (1 << CParser.T__8) | (1 << CParser.T__9) | (1 << CParser.T__11) | (1 << CParser.Auto) | (1 << CParser.Char) | (1 << CParser.Const) | (1 << CParser.Double) | (1 << CParser.Enum) | (1 << CParser.Extern) | (1 << CParser.Float) | (1 << CParser.Inline) | (1 << CParser.Int) | (1 << CParser.Long) | (1 << CParser.Register) | (1 << CParser.Restrict) | (1 << CParser.Short) | (1 << CParser.Signed) | (1 << CParser.Static) | (1 << CParser.Struct) | (1 << CParser.Typedef) | (1 << CParser.Union) | (1 << CParser.Unsigned) | (1 << CParser.Void) | (1 << CParser.Volatile) | (1 << CParser.Alignas) | (1 << CParser.Atomic) | (1 << CParser.Bool) | (1 << CParser.Complex) | (1 << CParser.Noreturn) | (1 << CParser.ThreadLocal))) != 0) or _la==CParser.Identifier:\n                    self.state = 937\n                    self.parameterTypeList()\n\n\n                self.state = 940\n                self.match(CParser.RightParen)\n                self.state = 944\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,95,self._ctx)\n                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                    if _alt==1:\n                        self.state = 941\n                        self.gccDeclaratorExtension()\n                    self.state = 946\n                    self._errHandler.sync(self)\n                    _alt = self._interp.adaptivePredict(self._input,95,self._ctx)\n\n                pass\n\n\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 992\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,103,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    self.state = 990\n                    la_ = self._interp.adaptivePredict(self._input,102,self._ctx)\n                    if la_ == 1:\n                        localctx = CParser.DirectAbstractDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directAbstractDeclarator)\n                        self.state = 949\n                        if not self.precpred(self._ctx, 5):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 5)\")\n                        self.state = 950\n                        self.match(CParser.LeftBracket)\n                        self.state = 952\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                            self.state = 951\n                            self.typeQualifierList(0)\n\n\n                        self.state = 955\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                            self.state = 954\n                            self.assignmentExpression()\n\n\n                        self.state = 957\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 2:\n                        localctx = CParser.DirectAbstractDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directAbstractDeclarator)\n                        self.state = 958\n                        if not self.precpred(self._ctx, 4):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 4)\")\n                        self.state = 959\n                        self.match(CParser.LeftBracket)\n                        self.state = 960\n                        self.match(CParser.Static)\n                        self.state = 962\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.Const) | (1 << CParser.Restrict) | (1 << CParser.Volatile) | (1 << CParser.Atomic))) != 0):\n                            self.state = 961\n                            self.typeQualifierList(0)\n\n\n                        self.state = 964\n                        self.assignmentExpression()\n                        self.state = 965\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 3:\n                        localctx = CParser.DirectAbstractDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directAbstractDeclarator)\n                        self.state = 967\n                        if not self.precpred(self._ctx, 3):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 3)\")\n                        self.state = 968\n                        self.match(CParser.LeftBracket)\n                        self.state = 969\n                        self.typeQualifierList(0)\n                        self.state = 970\n                        self.match(CParser.Static)\n                        self.state = 971\n                        self.assignmentExpression()\n                        self.state = 972\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 4:\n                        localctx = CParser.DirectAbstractDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directAbstractDeclarator)\n                        self.state = 974\n                        if not self.precpred(self._ctx, 2):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 2)\")\n                        self.state = 975\n                        self.match(CParser.LeftBracket)\n                        self.state = 976\n                        self.match(CParser.Star)\n                        self.state = 977\n                        self.match(CParser.RightBracket)\n                        pass\n\n                    elif la_ == 5:\n                        localctx = CParser.DirectAbstractDeclaratorContext(self, _parentctx, _parentState)\n                        self.pushNewRecursionContext(localctx, _startState, self.RULE_directAbstractDeclarator)\n                        self.state = 978\n                        if not self.precpred(self._ctx, 1):\n                            from antlr4.error.Errors import FailedPredicateException\n                            raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                        self.state = 979\n                        self.match(CParser.LeftParen)\n                        self.state = 981\n                        _la = self._input.LA(1)\n                        if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5) | (1 << CParser.T__6) | (1 << CParser.T__7) | (1 << CParser.T__8) | (1 << CParser.T__9) | (1 << CParser.T__11) | (1 << CParser.Auto) | (1 << CParser.Char) | (1 << CParser.Const) | (1 << CParser.Double) | (1 << CParser.Enum) | (1 << CParser.Extern) | (1 << CParser.Float) | (1 << CParser.Inline) | (1 << CParser.Int) | (1 << CParser.Long) | (1 << CParser.Register) | (1 << CParser.Restrict) | (1 << CParser.Short) | (1 << CParser.Signed) | (1 << CParser.Static) | (1 << CParser.Struct) | (1 << CParser.Typedef) | (1 << CParser.Union) | (1 << CParser.Unsigned) | (1 << CParser.Void) | (1 << CParser.Volatile) | (1 << CParser.Alignas) | (1 << CParser.Atomic) | (1 << CParser.Bool) | (1 << CParser.Complex) | (1 << CParser.Noreturn) | (1 << CParser.ThreadLocal))) != 0) or _la==CParser.Identifier:\n                            self.state = 980\n                            self.parameterTypeList()\n\n\n                        self.state = 983\n                        self.match(CParser.RightParen)\n                        self.state = 987\n                        self._errHandler.sync(self)\n                        _alt = self._interp.adaptivePredict(self._input,101,self._ctx)\n                        while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                            if _alt==1:\n                                self.state = 984\n                                self.gccDeclaratorExtension()\n                            self.state = 989\n                            self._errHandler.sync(self)\n                            _alt = self._interp.adaptivePredict(self._input,101,self._ctx)\n\n                        pass\n\n\n                self.state = 994\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,103,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class TypedefNameContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_typedefName\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterTypedefName\" ):\n                listener.enterTypedefName(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitTypedefName\" ):\n                listener.exitTypedefName(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitTypedefName\" ):\n                return visitor.visitTypedefName(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def typedefName(self):\n\n        localctx = CParser.TypedefNameContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 126, self.RULE_typedefName)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 995\n            self.match(CParser.Identifier)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class InitializerContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def assignmentExpression(self):\n            return self.getTypedRuleContext(CParser.AssignmentExpressionContext,0)\n\n\n        def initializerList(self):\n            return self.getTypedRuleContext(CParser.InitializerListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_initializer\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterInitializer\" ):\n                listener.enterInitializer(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitInitializer\" ):\n                listener.exitInitializer(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitInitializer\" ):\n                return visitor.visitInitializer(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def initializer(self):\n\n        localctx = CParser.InitializerContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 128, self.RULE_initializer)\n        try:\n            self.state = 1007\n            la_ = self._interp.adaptivePredict(self._input,104,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 997\n                self.assignmentExpression()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 998\n                self.match(CParser.LeftBrace)\n                self.state = 999\n                self.initializerList(0)\n                self.state = 1000\n                self.match(CParser.RightBrace)\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 1002\n                self.match(CParser.LeftBrace)\n                self.state = 1003\n                self.initializerList(0)\n                self.state = 1004\n                self.match(CParser.Comma)\n                self.state = 1005\n                self.match(CParser.RightBrace)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class InitializerListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def initializer(self):\n            return self.getTypedRuleContext(CParser.InitializerContext,0)\n\n\n        def designation(self):\n            return self.getTypedRuleContext(CParser.DesignationContext,0)\n\n\n        def initializerList(self):\n            return self.getTypedRuleContext(CParser.InitializerListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_initializerList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterInitializerList\" ):\n                listener.enterInitializerList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitInitializerList\" ):\n                listener.exitInitializerList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitInitializerList\" ):\n                return visitor.visitInitializerList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def initializerList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.InitializerListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 130\n        self.enterRecursionRule(localctx, 130, self.RULE_initializerList, _p)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1011\n            _la = self._input.LA(1)\n            if _la==CParser.LeftBracket or _la==CParser.Dot:\n                self.state = 1010\n                self.designation()\n\n\n            self.state = 1013\n            self.initializer()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 1023\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,107,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.InitializerListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_initializerList)\n                    self.state = 1015\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 1016\n                    self.match(CParser.Comma)\n                    self.state = 1018\n                    _la = self._input.LA(1)\n                    if _la==CParser.LeftBracket or _la==CParser.Dot:\n                        self.state = 1017\n                        self.designation()\n\n\n                    self.state = 1020\n                    self.initializer()\n                self.state = 1025\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,107,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class DesignationContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def designatorList(self):\n            return self.getTypedRuleContext(CParser.DesignatorListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_designation\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDesignation\" ):\n                listener.enterDesignation(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDesignation\" ):\n                listener.exitDesignation(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDesignation\" ):\n                return visitor.visitDesignation(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def designation(self):\n\n        localctx = CParser.DesignationContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 132, self.RULE_designation)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1026\n            self.designatorList(0)\n            self.state = 1027\n            self.match(CParser.Assign)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DesignatorListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def designator(self):\n            return self.getTypedRuleContext(CParser.DesignatorContext,0)\n\n\n        def designatorList(self):\n            return self.getTypedRuleContext(CParser.DesignatorListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_designatorList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDesignatorList\" ):\n                listener.enterDesignatorList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDesignatorList\" ):\n                listener.exitDesignatorList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDesignatorList\" ):\n                return visitor.visitDesignatorList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def designatorList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.DesignatorListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 134\n        self.enterRecursionRule(localctx, 134, self.RULE_designatorList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1030\n            self.designator()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 1036\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,108,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.DesignatorListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_designatorList)\n                    self.state = 1032\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 1033\n                    self.designator()\n                self.state = 1038\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,108,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class DesignatorContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def constantExpression(self):\n            return self.getTypedRuleContext(CParser.ConstantExpressionContext,0)\n\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def getRuleIndex(self):\n            return CParser.RULE_designator\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDesignator\" ):\n                listener.enterDesignator(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDesignator\" ):\n                listener.exitDesignator(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDesignator\" ):\n                return visitor.visitDesignator(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def designator(self):\n\n        localctx = CParser.DesignatorContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 136, self.RULE_designator)\n        try:\n            self.state = 1045\n            token = self._input.LA(1)\n            if token in [CParser.LeftBracket]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1039\n                self.match(CParser.LeftBracket)\n                self.state = 1040\n                self.constantExpression()\n                self.state = 1041\n                self.match(CParser.RightBracket)\n\n            elif token in [CParser.Dot]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1043\n                self.match(CParser.Dot)\n                self.state = 1044\n                self.match(CParser.Identifier)\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class StaticAssertDeclarationContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def constantExpression(self):\n            return self.getTypedRuleContext(CParser.ConstantExpressionContext,0)\n\n\n        def StringLiteral(self, i:int=None):\n            if i is None:\n                return self.getTokens(CParser.StringLiteral)\n            else:\n                return self.getToken(CParser.StringLiteral, i)\n\n        def getRuleIndex(self):\n            return CParser.RULE_staticAssertDeclaration\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStaticAssertDeclaration\" ):\n                listener.enterStaticAssertDeclaration(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStaticAssertDeclaration\" ):\n                listener.exitStaticAssertDeclaration(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStaticAssertDeclaration\" ):\n                return visitor.visitStaticAssertDeclaration(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def staticAssertDeclaration(self):\n\n        localctx = CParser.StaticAssertDeclarationContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 138, self.RULE_staticAssertDeclaration)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1047\n            self.match(CParser.StaticAssert)\n            self.state = 1048\n            self.match(CParser.LeftParen)\n            self.state = 1049\n            self.constantExpression()\n            self.state = 1050\n            self.match(CParser.Comma)\n            self.state = 1052\n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while True:\n                self.state = 1051\n                self.match(CParser.StringLiteral)\n                self.state = 1054\n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                if not (_la==CParser.StringLiteral):\n                    break\n\n            self.state = 1056\n            self.match(CParser.RightParen)\n            self.state = 1057\n            self.match(CParser.Semi)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class StatementContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def labeledStatement(self):\n            return self.getTypedRuleContext(CParser.LabeledStatementContext,0)\n\n\n        def compoundStatement(self):\n            return self.getTypedRuleContext(CParser.CompoundStatementContext,0)\n\n\n        def expressionStatement(self):\n            return self.getTypedRuleContext(CParser.ExpressionStatementContext,0)\n\n\n        def selectionStatement(self):\n            return self.getTypedRuleContext(CParser.SelectionStatementContext,0)\n\n\n        def iterationStatement(self):\n            return self.getTypedRuleContext(CParser.IterationStatementContext,0)\n\n\n        def jumpStatement(self):\n            return self.getTypedRuleContext(CParser.JumpStatementContext,0)\n\n\n        def logicalOrExpression(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.LogicalOrExpressionContext)\n            else:\n                return self.getTypedRuleContext(CParser.LogicalOrExpressionContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_statement\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterStatement\" ):\n                listener.enterStatement(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitStatement\" ):\n                listener.exitStatement(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitStatement\" ):\n                return visitor.visitStatement(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def statement(self):\n\n        localctx = CParser.StatementContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 140, self.RULE_statement)\n        self._la = 0 # Token type\n        try:\n            self.state = 1096\n            la_ = self._interp.adaptivePredict(self._input,116,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1059\n                self.labeledStatement()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1060\n                self.compoundStatement()\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 1061\n                self.expressionStatement()\n                pass\n\n            elif la_ == 4:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 1062\n                self.selectionStatement()\n                pass\n\n            elif la_ == 5:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 1063\n                self.iterationStatement()\n                pass\n\n            elif la_ == 6:\n                self.enterOuterAlt(localctx, 6)\n                self.state = 1064\n                self.jumpStatement()\n                pass\n\n            elif la_ == 7:\n                self.enterOuterAlt(localctx, 7)\n                self.state = 1065\n                _la = self._input.LA(1)\n                if not(_la==CParser.T__10 or _la==CParser.T__12):\n                    self._errHandler.recoverInline(self)\n                else:\n                    self.consume()\n                self.state = 1066\n                _la = self._input.LA(1)\n                if not(_la==CParser.T__13 or _la==CParser.Volatile):\n                    self._errHandler.recoverInline(self)\n                else:\n                    self.consume()\n                self.state = 1067\n                self.match(CParser.LeftParen)\n                self.state = 1076\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 1068\n                    self.logicalOrExpression(0)\n                    self.state = 1073\n                    self._errHandler.sync(self)\n                    _la = self._input.LA(1)\n                    while _la==CParser.Comma:\n                        self.state = 1069\n                        self.match(CParser.Comma)\n                        self.state = 1070\n                        self.logicalOrExpression(0)\n                        self.state = 1075\n                        self._errHandler.sync(self)\n                        _la = self._input.LA(1)\n\n\n\n                self.state = 1091\n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                while _la==CParser.Colon:\n                    self.state = 1078\n                    self.match(CParser.Colon)\n                    self.state = 1087\n                    _la = self._input.LA(1)\n                    if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                        self.state = 1079\n                        self.logicalOrExpression(0)\n                        self.state = 1084\n                        self._errHandler.sync(self)\n                        _la = self._input.LA(1)\n                        while _la==CParser.Comma:\n                            self.state = 1080\n                            self.match(CParser.Comma)\n                            self.state = 1081\n                            self.logicalOrExpression(0)\n                            self.state = 1086\n                            self._errHandler.sync(self)\n                            _la = self._input.LA(1)\n\n\n\n                    self.state = 1093\n                    self._errHandler.sync(self)\n                    _la = self._input.LA(1)\n\n                self.state = 1094\n                self.match(CParser.RightParen)\n                self.state = 1095\n                self.match(CParser.Semi)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class LabeledStatementContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def statement(self):\n            return self.getTypedRuleContext(CParser.StatementContext,0)\n\n\n        def constantExpression(self):\n            return self.getTypedRuleContext(CParser.ConstantExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_labeledStatement\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterLabeledStatement\" ):\n                listener.enterLabeledStatement(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitLabeledStatement\" ):\n                listener.exitLabeledStatement(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitLabeledStatement\" ):\n                return visitor.visitLabeledStatement(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def labeledStatement(self):\n\n        localctx = CParser.LabeledStatementContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 142, self.RULE_labeledStatement)\n        try:\n            self.state = 1109\n            token = self._input.LA(1)\n            if token in [CParser.Identifier]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1098\n                self.match(CParser.Identifier)\n                self.state = 1099\n                self.match(CParser.Colon)\n                self.state = 1100\n                self.statement()\n\n            elif token in [CParser.Case]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1101\n                self.match(CParser.Case)\n                self.state = 1102\n                self.constantExpression()\n                self.state = 1103\n                self.match(CParser.Colon)\n                self.state = 1104\n                self.statement()\n\n            elif token in [CParser.Default]:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 1106\n                self.match(CParser.Default)\n                self.state = 1107\n                self.match(CParser.Colon)\n                self.state = 1108\n                self.statement()\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class CompoundStatementContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def blockItemList(self):\n            return self.getTypedRuleContext(CParser.BlockItemListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_compoundStatement\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterCompoundStatement\" ):\n                listener.enterCompoundStatement(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitCompoundStatement\" ):\n                listener.exitCompoundStatement(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitCompoundStatement\" ):\n                return visitor.visitCompoundStatement(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def compoundStatement(self):\n\n        localctx = CParser.CompoundStatementContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 144, self.RULE_compoundStatement)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1111\n            self.match(CParser.LeftBrace)\n            self.state = 1113\n            _la = self._input.LA(1)\n            if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5) | (1 << CParser.T__6) | (1 << CParser.T__7) | (1 << CParser.T__8) | (1 << CParser.T__9) | (1 << CParser.T__10) | (1 << CParser.T__11) | (1 << CParser.T__12) | (1 << CParser.Auto) | (1 << CParser.Break) | (1 << CParser.Case) | (1 << CParser.Char) | (1 << CParser.Const) | (1 << CParser.Continue) | (1 << CParser.Default) | (1 << CParser.Do) | (1 << CParser.Double) | (1 << CParser.Enum) | (1 << CParser.Extern) | (1 << CParser.Float) | (1 << CParser.For) | (1 << CParser.Goto) | (1 << CParser.If) | (1 << CParser.Inline) | (1 << CParser.Int) | (1 << CParser.Long) | (1 << CParser.Register) | (1 << CParser.Restrict) | (1 << CParser.Return) | (1 << CParser.Short) | (1 << CParser.Signed) | (1 << CParser.Sizeof) | (1 << CParser.Static) | (1 << CParser.Struct) | (1 << CParser.Switch) | (1 << CParser.Typedef) | (1 << CParser.Union) | (1 << CParser.Unsigned) | (1 << CParser.Void) | (1 << CParser.Volatile) | (1 << CParser.While) | (1 << CParser.Alignas) | (1 << CParser.Alignof) | (1 << CParser.Atomic) | (1 << CParser.Bool) | (1 << CParser.Complex) | (1 << CParser.Generic) | (1 << CParser.Noreturn) | (1 << CParser.StaticAssert) | (1 << CParser.ThreadLocal) | (1 << CParser.LeftParen) | (1 << CParser.LeftBrace))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Semi - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                self.state = 1112\n                self.blockItemList(0)\n\n\n            self.state = 1115\n            self.match(CParser.RightBrace)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class BlockItemListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def blockItem(self):\n            return self.getTypedRuleContext(CParser.BlockItemContext,0)\n\n\n        def blockItemList(self):\n            return self.getTypedRuleContext(CParser.BlockItemListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_blockItemList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterBlockItemList\" ):\n                listener.enterBlockItemList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitBlockItemList\" ):\n                listener.exitBlockItemList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitBlockItemList\" ):\n                return visitor.visitBlockItemList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def blockItemList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.BlockItemListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 146\n        self.enterRecursionRule(localctx, 146, self.RULE_blockItemList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1118\n            self.blockItem()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 1124\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,119,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.BlockItemListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_blockItemList)\n                    self.state = 1120\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 1121\n                    self.blockItem()\n                self.state = 1126\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,119,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class BlockItemContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declaration(self):\n            return self.getTypedRuleContext(CParser.DeclarationContext,0)\n\n\n        def statement(self):\n            return self.getTypedRuleContext(CParser.StatementContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_blockItem\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterBlockItem\" ):\n                listener.enterBlockItem(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitBlockItem\" ):\n                listener.exitBlockItem(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitBlockItem\" ):\n                return visitor.visitBlockItem(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def blockItem(self):\n\n        localctx = CParser.BlockItemContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 148, self.RULE_blockItem)\n        try:\n            self.state = 1129\n            la_ = self._interp.adaptivePredict(self._input,120,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1127\n                self.declaration()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1128\n                self.statement()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class ExpressionStatementContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def expression(self):\n            return self.getTypedRuleContext(CParser.ExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_expressionStatement\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterExpressionStatement\" ):\n                listener.enterExpressionStatement(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitExpressionStatement\" ):\n                listener.exitExpressionStatement(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitExpressionStatement\" ):\n                return visitor.visitExpressionStatement(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def expressionStatement(self):\n\n        localctx = CParser.ExpressionStatementContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 150, self.RULE_expressionStatement)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1132\n            _la = self._input.LA(1)\n            if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                self.state = 1131\n                self.expression(0)\n\n\n            self.state = 1134\n            self.match(CParser.Semi)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class SelectionStatementContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def expression(self):\n            return self.getTypedRuleContext(CParser.ExpressionContext,0)\n\n\n        def statement(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.StatementContext)\n            else:\n                return self.getTypedRuleContext(CParser.StatementContext,i)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_selectionStatement\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterSelectionStatement\" ):\n                listener.enterSelectionStatement(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitSelectionStatement\" ):\n                listener.exitSelectionStatement(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitSelectionStatement\" ):\n                return visitor.visitSelectionStatement(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def selectionStatement(self):\n\n        localctx = CParser.SelectionStatementContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 152, self.RULE_selectionStatement)\n        try:\n            self.state = 1151\n            token = self._input.LA(1)\n            if token in [CParser.If]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1136\n                self.match(CParser.If)\n                self.state = 1137\n                self.match(CParser.LeftParen)\n                self.state = 1138\n                self.expression(0)\n                self.state = 1139\n                self.match(CParser.RightParen)\n                self.state = 1140\n                self.statement()\n                self.state = 1143\n                la_ = self._interp.adaptivePredict(self._input,122,self._ctx)\n                if la_ == 1:\n                    self.state = 1141\n                    self.match(CParser.Else)\n                    self.state = 1142\n                    self.statement()\n\n\n\n            elif token in [CParser.Switch]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1145\n                self.match(CParser.Switch)\n                self.state = 1146\n                self.match(CParser.LeftParen)\n                self.state = 1147\n                self.expression(0)\n                self.state = 1148\n                self.match(CParser.RightParen)\n                self.state = 1149\n                self.statement()\n\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class IterationStatementContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def expression(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(CParser.ExpressionContext)\n            else:\n                return self.getTypedRuleContext(CParser.ExpressionContext,i)\n\n\n        def statement(self):\n            return self.getTypedRuleContext(CParser.StatementContext,0)\n\n\n        def declaration(self):\n            return self.getTypedRuleContext(CParser.DeclarationContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_iterationStatement\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterIterationStatement\" ):\n                listener.enterIterationStatement(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitIterationStatement\" ):\n                listener.exitIterationStatement(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitIterationStatement\" ):\n                return visitor.visitIterationStatement(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def iterationStatement(self):\n\n        localctx = CParser.IterationStatementContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 154, self.RULE_iterationStatement)\n        self._la = 0 # Token type\n        try:\n            self.state = 1195\n            la_ = self._interp.adaptivePredict(self._input,129,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1153\n                self.match(CParser.While)\n                self.state = 1154\n                self.match(CParser.LeftParen)\n                self.state = 1155\n                self.expression(0)\n                self.state = 1156\n                self.match(CParser.RightParen)\n                self.state = 1157\n                self.statement()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1159\n                self.match(CParser.Do)\n                self.state = 1160\n                self.statement()\n                self.state = 1161\n                self.match(CParser.While)\n                self.state = 1162\n                self.match(CParser.LeftParen)\n                self.state = 1163\n                self.expression(0)\n                self.state = 1164\n                self.match(CParser.RightParen)\n                self.state = 1165\n                self.match(CParser.Semi)\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 1167\n                self.match(CParser.For)\n                self.state = 1168\n                self.match(CParser.LeftParen)\n                self.state = 1170\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 1169\n                    self.expression(0)\n\n\n                self.state = 1172\n                self.match(CParser.Semi)\n                self.state = 1174\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 1173\n                    self.expression(0)\n\n\n                self.state = 1176\n                self.match(CParser.Semi)\n                self.state = 1178\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 1177\n                    self.expression(0)\n\n\n                self.state = 1180\n                self.match(CParser.RightParen)\n                self.state = 1181\n                self.statement()\n                pass\n\n            elif la_ == 4:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 1182\n                self.match(CParser.For)\n                self.state = 1183\n                self.match(CParser.LeftParen)\n                self.state = 1184\n                self.declaration()\n                self.state = 1186\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 1185\n                    self.expression(0)\n\n\n                self.state = 1188\n                self.match(CParser.Semi)\n                self.state = 1190\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 1189\n                    self.expression(0)\n\n\n                self.state = 1192\n                self.match(CParser.RightParen)\n                self.state = 1193\n                self.statement()\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class JumpStatementContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def Identifier(self):\n            return self.getToken(CParser.Identifier, 0)\n\n        def expression(self):\n            return self.getTypedRuleContext(CParser.ExpressionContext,0)\n\n\n        def unaryExpression(self):\n            return self.getTypedRuleContext(CParser.UnaryExpressionContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_jumpStatement\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterJumpStatement\" ):\n                listener.enterJumpStatement(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitJumpStatement\" ):\n                listener.exitJumpStatement(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitJumpStatement\" ):\n                return visitor.visitJumpStatement(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def jumpStatement(self):\n\n        localctx = CParser.JumpStatementContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 156, self.RULE_jumpStatement)\n        self._la = 0 # Token type\n        try:\n            self.state = 1213\n            la_ = self._interp.adaptivePredict(self._input,131,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1197\n                self.match(CParser.Goto)\n                self.state = 1198\n                self.match(CParser.Identifier)\n                self.state = 1199\n                self.match(CParser.Semi)\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1200\n                self.match(CParser.Continue)\n                self.state = 1201\n                self.match(CParser.Semi)\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 1202\n                self.match(CParser.Break)\n                self.state = 1203\n                self.match(CParser.Semi)\n                pass\n\n            elif la_ == 4:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 1204\n                self.match(CParser.Return)\n                self.state = 1206\n                _la = self._input.LA(1)\n                if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__1) | (1 << CParser.T__2) | (1 << CParser.Sizeof) | (1 << CParser.Alignof) | (1 << CParser.Generic) | (1 << CParser.LeftParen))) != 0) or ((((_la - 71)) & ~0x3f) == 0 and ((1 << (_la - 71)) & ((1 << (CParser.Plus - 71)) | (1 << (CParser.PlusPlus - 71)) | (1 << (CParser.Minus - 71)) | (1 << (CParser.MinusMinus - 71)) | (1 << (CParser.Star - 71)) | (1 << (CParser.And - 71)) | (1 << (CParser.AndAnd - 71)) | (1 << (CParser.Not - 71)) | (1 << (CParser.Tilde - 71)) | (1 << (CParser.Identifier - 71)) | (1 << (CParser.Constant - 71)) | (1 << (CParser.StringLiteral - 71)))) != 0):\n                    self.state = 1205\n                    self.expression(0)\n\n\n                self.state = 1208\n                self.match(CParser.Semi)\n                pass\n\n            elif la_ == 5:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 1209\n                self.match(CParser.Goto)\n                self.state = 1210\n                self.unaryExpression()\n                self.state = 1211\n                self.match(CParser.Semi)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class CompilationUnitContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def EOF(self):\n            return self.getToken(CParser.EOF, 0)\n\n        def translationUnit(self):\n            return self.getTypedRuleContext(CParser.TranslationUnitContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_compilationUnit\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterCompilationUnit\" ):\n                listener.enterCompilationUnit(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitCompilationUnit\" ):\n                listener.exitCompilationUnit(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitCompilationUnit\" ):\n                return visitor.visitCompilationUnit(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def compilationUnit(self):\n\n        localctx = CParser.CompilationUnitContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 158, self.RULE_compilationUnit)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1216\n            _la = self._input.LA(1)\n            if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5) | (1 << CParser.T__6) | (1 << CParser.T__7) | (1 << CParser.T__8) | (1 << CParser.T__9) | (1 << CParser.T__11) | (1 << CParser.Auto) | (1 << CParser.Char) | (1 << CParser.Const) | (1 << CParser.Double) | (1 << CParser.Enum) | (1 << CParser.Extern) | (1 << CParser.Float) | (1 << CParser.Inline) | (1 << CParser.Int) | (1 << CParser.Long) | (1 << CParser.Register) | (1 << CParser.Restrict) | (1 << CParser.Short) | (1 << CParser.Signed) | (1 << CParser.Static) | (1 << CParser.Struct) | (1 << CParser.Typedef) | (1 << CParser.Union) | (1 << CParser.Unsigned) | (1 << CParser.Void) | (1 << CParser.Volatile) | (1 << CParser.Alignas) | (1 << CParser.Atomic) | (1 << CParser.Bool) | (1 << CParser.Complex) | (1 << CParser.Noreturn) | (1 << CParser.StaticAssert) | (1 << CParser.ThreadLocal) | (1 << CParser.LeftParen))) != 0) or ((((_la - 75)) & ~0x3f) == 0 and ((1 << (_la - 75)) & ((1 << (CParser.Star - 75)) | (1 << (CParser.Caret - 75)) | (1 << (CParser.Semi - 75)) | (1 << (CParser.Identifier - 75)))) != 0):\n                self.state = 1215\n                self.translationUnit(0)\n\n\n            self.state = 1218\n            self.match(CParser.EOF)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class TranslationUnitContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def externalDeclaration(self):\n            return self.getTypedRuleContext(CParser.ExternalDeclarationContext,0)\n\n\n        def translationUnit(self):\n            return self.getTypedRuleContext(CParser.TranslationUnitContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_translationUnit\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterTranslationUnit\" ):\n                listener.enterTranslationUnit(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitTranslationUnit\" ):\n                listener.exitTranslationUnit(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitTranslationUnit\" ):\n                return visitor.visitTranslationUnit(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def translationUnit(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.TranslationUnitContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 160\n        self.enterRecursionRule(localctx, 160, self.RULE_translationUnit, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1221\n            self.externalDeclaration()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 1227\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,133,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.TranslationUnitContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_translationUnit)\n                    self.state = 1223\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 1224\n                    self.externalDeclaration()\n                self.state = 1229\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,133,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n    class ExternalDeclarationContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def functionDefinition(self):\n            return self.getTypedRuleContext(CParser.FunctionDefinitionContext,0)\n\n\n        def declaration(self):\n            return self.getTypedRuleContext(CParser.DeclarationContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_externalDeclaration\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterExternalDeclaration\" ):\n                listener.enterExternalDeclaration(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitExternalDeclaration\" ):\n                listener.exitExternalDeclaration(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitExternalDeclaration\" ):\n                return visitor.visitExternalDeclaration(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def externalDeclaration(self):\n\n        localctx = CParser.ExternalDeclarationContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 162, self.RULE_externalDeclaration)\n        try:\n            self.state = 1233\n            la_ = self._interp.adaptivePredict(self._input,134,self._ctx)\n            if la_ == 1:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 1230\n                self.functionDefinition()\n                pass\n\n            elif la_ == 2:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 1231\n                self.declaration()\n                pass\n\n            elif la_ == 3:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 1232\n                self.match(CParser.Semi)\n                pass\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class FunctionDefinitionContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declarator(self):\n            return self.getTypedRuleContext(CParser.DeclaratorContext,0)\n\n\n        def compoundStatement(self):\n            return self.getTypedRuleContext(CParser.CompoundStatementContext,0)\n\n\n        def declarationSpecifiers(self):\n            return self.getTypedRuleContext(CParser.DeclarationSpecifiersContext,0)\n\n\n        def declarationList(self):\n            return self.getTypedRuleContext(CParser.DeclarationListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_functionDefinition\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterFunctionDefinition\" ):\n                listener.enterFunctionDefinition(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitFunctionDefinition\" ):\n                listener.exitFunctionDefinition(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitFunctionDefinition\" ):\n                return visitor.visitFunctionDefinition(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def functionDefinition(self):\n\n        localctx = CParser.FunctionDefinitionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 164, self.RULE_functionDefinition)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1236\n            la_ = self._interp.adaptivePredict(self._input,135,self._ctx)\n            if la_ == 1:\n                self.state = 1235\n                self.declarationSpecifiers()\n\n\n            self.state = 1238\n            self.declarator()\n            self.state = 1240\n            _la = self._input.LA(1)\n            if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << CParser.T__0) | (1 << CParser.T__3) | (1 << CParser.T__4) | (1 << CParser.T__5) | (1 << CParser.T__6) | (1 << CParser.T__7) | (1 << CParser.T__8) | (1 << CParser.T__9) | (1 << CParser.T__11) | (1 << CParser.Auto) | (1 << CParser.Char) | (1 << CParser.Const) | (1 << CParser.Double) | (1 << CParser.Enum) | (1 << CParser.Extern) | (1 << CParser.Float) | (1 << CParser.Inline) | (1 << CParser.Int) | (1 << CParser.Long) | (1 << CParser.Register) | (1 << CParser.Restrict) | (1 << CParser.Short) | (1 << CParser.Signed) | (1 << CParser.Static) | (1 << CParser.Struct) | (1 << CParser.Typedef) | (1 << CParser.Union) | (1 << CParser.Unsigned) | (1 << CParser.Void) | (1 << CParser.Volatile) | (1 << CParser.Alignas) | (1 << CParser.Atomic) | (1 << CParser.Bool) | (1 << CParser.Complex) | (1 << CParser.Noreturn) | (1 << CParser.StaticAssert) | (1 << CParser.ThreadLocal))) != 0) or _la==CParser.Identifier:\n                self.state = 1239\n                self.declarationList(0)\n\n\n            self.state = 1242\n            self.compoundStatement()\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n    class DeclarationListContext(ParserRuleContext):\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def declaration(self):\n            return self.getTypedRuleContext(CParser.DeclarationContext,0)\n\n\n        def declarationList(self):\n            return self.getTypedRuleContext(CParser.DeclarationListContext,0)\n\n\n        def getRuleIndex(self):\n            return CParser.RULE_declarationList\n\n        def enterRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"enterDeclarationList\" ):\n                listener.enterDeclarationList(self)\n\n        def exitRule(self, listener:ParseTreeListener):\n            if hasattr( listener, \"exitDeclarationList\" ):\n                listener.exitDeclarationList(self)\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDeclarationList\" ):\n                return visitor.visitDeclarationList(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n    def declarationList(self, _p:int=0):\n        _parentctx = self._ctx\n        _parentState = self.state\n        localctx = CParser.DeclarationListContext(self, self._ctx, _parentState)\n        _prevctx = localctx\n        _startState = 166\n        self.enterRecursionRule(localctx, 166, self.RULE_declarationList, _p)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 1245\n            self.declaration()\n            self._ctx.stop = self._input.LT(-1)\n            self.state = 1251\n            self._errHandler.sync(self)\n            _alt = self._interp.adaptivePredict(self._input,137,self._ctx)\n            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:\n                if _alt==1:\n                    if self._parseListeners is not None:\n                        self.triggerExitRuleEvent()\n                    _prevctx = localctx\n                    localctx = CParser.DeclarationListContext(self, _parentctx, _parentState)\n                    self.pushNewRecursionContext(localctx, _startState, self.RULE_declarationList)\n                    self.state = 1247\n                    if not self.precpred(self._ctx, 1):\n                        from antlr4.error.Errors import FailedPredicateException\n                        raise FailedPredicateException(self, \"self.precpred(self._ctx, 1)\")\n                    self.state = 1248\n                    self.declaration()\n                self.state = 1253\n                self._errHandler.sync(self)\n                _alt = self._interp.adaptivePredict(self._input,137,self._ctx)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.unrollRecursionContexts(_parentctx)\n        return localctx\n\n\n\n    def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):\n        if self._predicates == None:\n            self._predicates = dict()\n        self._predicates[2] = self.genericAssocList_sempred\n        self._predicates[4] = self.postfixExpression_sempred\n        self._predicates[5] = self.argumentExpressionList_sempred\n        self._predicates[9] = self.multiplicativeExpression_sempred\n        self._predicates[10] = self.additiveExpression_sempred\n        self._predicates[11] = self.shiftExpression_sempred\n        self._predicates[12] = self.relationalExpression_sempred\n        self._predicates[13] = self.equalityExpression_sempred\n        self._predicates[14] = self.andExpression_sempred\n        self._predicates[15] = self.exclusiveOrExpression_sempred\n        self._predicates[16] = self.inclusiveOrExpression_sempred\n        self._predicates[17] = self.logicalAndExpression_sempred\n        self._predicates[18] = self.logicalOrExpression_sempred\n        self._predicates[22] = self.expression_sempred\n        self._predicates[28] = self.initDeclaratorList_sempred\n        self._predicates[34] = self.structDeclarationList_sempred\n        self._predicates[37] = self.structDeclaratorList_sempred\n        self._predicates[40] = self.enumeratorList_sempred\n        self._predicates[48] = self.directDeclarator_sempred\n        self._predicates[55] = self.typeQualifierList_sempred\n        self._predicates[57] = self.parameterList_sempred\n        self._predicates[59] = self.identifierList_sempred\n        self._predicates[62] = self.directAbstractDeclarator_sempred\n        self._predicates[65] = self.initializerList_sempred\n        self._predicates[67] = self.designatorList_sempred\n        self._predicates[73] = self.blockItemList_sempred\n        self._predicates[80] = self.translationUnit_sempred\n        self._predicates[83] = self.declarationList_sempred\n        pred = self._predicates.get(ruleIndex, None)\n        if pred is None:\n            raise Exception(\"No predicate with index:\" + str(ruleIndex))\n        else:\n            return pred(localctx, predIndex)\n\n    def genericAssocList_sempred(self, localctx:GenericAssocListContext, predIndex:int):\n            if predIndex == 0:\n                return self.precpred(self._ctx, 1)\n\n\n    def postfixExpression_sempred(self, localctx:PostfixExpressionContext, predIndex:int):\n            if predIndex == 1:\n                return self.precpred(self._ctx, 10)\n\n\n            if predIndex == 2:\n                return self.precpred(self._ctx, 9)\n\n\n            if predIndex == 3:\n                return self.precpred(self._ctx, 8)\n\n\n            if predIndex == 4:\n                return self.precpred(self._ctx, 7)\n\n\n            if predIndex == 5:\n                return self.precpred(self._ctx, 6)\n\n\n            if predIndex == 6:\n                return self.precpred(self._ctx, 5)\n\n\n    def argumentExpressionList_sempred(self, localctx:ArgumentExpressionListContext, predIndex:int):\n            if predIndex == 7:\n                return self.precpred(self._ctx, 1)\n\n\n    def multiplicativeExpression_sempred(self, localctx:MultiplicativeExpressionContext, predIndex:int):\n            if predIndex == 8:\n                return self.precpred(self._ctx, 3)\n\n\n            if predIndex == 9:\n                return self.precpred(self._ctx, 2)\n\n\n            if predIndex == 10:\n                return self.precpred(self._ctx, 1)\n\n\n    def additiveExpression_sempred(self, localctx:AdditiveExpressionContext, predIndex:int):\n            if predIndex == 11:\n                return self.precpred(self._ctx, 2)\n\n\n            if predIndex == 12:\n                return self.precpred(self._ctx, 1)\n\n\n    def shiftExpression_sempred(self, localctx:ShiftExpressionContext, predIndex:int):\n            if predIndex == 13:\n                return self.precpred(self._ctx, 2)\n\n\n            if predIndex == 14:\n                return self.precpred(self._ctx, 1)\n\n\n    def relationalExpression_sempred(self, localctx:RelationalExpressionContext, predIndex:int):\n            if predIndex == 15:\n                return self.precpred(self._ctx, 4)\n\n\n            if predIndex == 16:\n                return self.precpred(self._ctx, 3)\n\n\n            if predIndex == 17:\n                return self.precpred(self._ctx, 2)\n\n\n            if predIndex == 18:\n                return self.precpred(self._ctx, 1)\n\n\n    def equalityExpression_sempred(self, localctx:EqualityExpressionContext, predIndex:int):\n            if predIndex == 19:\n                return self.precpred(self._ctx, 2)\n\n\n            if predIndex == 20:\n                return self.precpred(self._ctx, 1)\n\n\n    def andExpression_sempred(self, localctx:AndExpressionContext, predIndex:int):\n            if predIndex == 21:\n                return self.precpred(self._ctx, 1)\n\n\n    def exclusiveOrExpression_sempred(self, localctx:ExclusiveOrExpressionContext, predIndex:int):\n            if predIndex == 22:\n                return self.precpred(self._ctx, 1)\n\n\n    def inclusiveOrExpression_sempred(self, localctx:InclusiveOrExpressionContext, predIndex:int):\n            if predIndex == 23:\n                return self.precpred(self._ctx, 1)\n\n\n    def logicalAndExpression_sempred(self, localctx:LogicalAndExpressionContext, predIndex:int):\n            if predIndex == 24:\n                return self.precpred(self._ctx, 1)\n\n\n    def logicalOrExpression_sempred(self, localctx:LogicalOrExpressionContext, predIndex:int):\n            if predIndex == 25:\n                return self.precpred(self._ctx, 1)\n\n\n    def expression_sempred(self, localctx:ExpressionContext, predIndex:int):\n            if predIndex == 26:\n                return self.precpred(self._ctx, 1)\n\n\n    def initDeclaratorList_sempred(self, localctx:InitDeclaratorListContext, predIndex:int):\n            if predIndex == 27:\n                return self.precpred(self._ctx, 1)\n\n\n    def structDeclarationList_sempred(self, localctx:StructDeclarationListContext, predIndex:int):\n            if predIndex == 28:\n                return self.precpred(self._ctx, 1)\n\n\n    def structDeclaratorList_sempred(self, localctx:StructDeclaratorListContext, predIndex:int):\n            if predIndex == 29:\n                return self.precpred(self._ctx, 1)\n\n\n    def enumeratorList_sempred(self, localctx:EnumeratorListContext, predIndex:int):\n            if predIndex == 30:\n                return self.precpred(self._ctx, 1)\n\n\n    def directDeclarator_sempred(self, localctx:DirectDeclaratorContext, predIndex:int):\n            if predIndex == 31:\n                return self.precpred(self._ctx, 6)\n\n\n            if predIndex == 32:\n                return self.precpred(self._ctx, 5)\n\n\n            if predIndex == 33:\n                return self.precpred(self._ctx, 4)\n\n\n            if predIndex == 34:\n                return self.precpred(self._ctx, 3)\n\n\n            if predIndex == 35:\n                return self.precpred(self._ctx, 2)\n\n\n            if predIndex == 36:\n                return self.precpred(self._ctx, 1)\n\n\n    def typeQualifierList_sempred(self, localctx:TypeQualifierListContext, predIndex:int):\n            if predIndex == 37:\n                return self.precpred(self._ctx, 1)\n\n\n    def parameterList_sempred(self, localctx:ParameterListContext, predIndex:int):\n            if predIndex == 38:\n                return self.precpred(self._ctx, 1)\n\n\n    def identifierList_sempred(self, localctx:IdentifierListContext, predIndex:int):\n            if predIndex == 39:\n                return self.precpred(self._ctx, 1)\n\n\n    def directAbstractDeclarator_sempred(self, localctx:DirectAbstractDeclaratorContext, predIndex:int):\n            if predIndex == 40:\n                return self.precpred(self._ctx, 5)\n\n\n            if predIndex == 41:\n                return self.precpred(self._ctx, 4)\n\n\n            if predIndex == 42:\n                return self.precpred(self._ctx, 3)\n\n\n            if predIndex == 43:\n                return self.precpred(self._ctx, 2)\n\n\n            if predIndex == 44:\n                return self.precpred(self._ctx, 1)\n\n\n    def initializerList_sempred(self, localctx:InitializerListContext, predIndex:int):\n            if predIndex == 45:\n                return self.precpred(self._ctx, 1)\n\n\n    def designatorList_sempred(self, localctx:DesignatorListContext, predIndex:int):\n            if predIndex == 46:\n                return self.precpred(self._ctx, 1)\n\n\n    def blockItemList_sempred(self, localctx:BlockItemListContext, predIndex:int):\n            if predIndex == 47:\n                return self.precpred(self._ctx, 1)\n\n\n    def translationUnit_sempred(self, localctx:TranslationUnitContext, predIndex:int):\n            if predIndex == 48:\n                return self.precpred(self._ctx, 1)\n\n\n    def declarationList_sempred(self, localctx:DeclarationListContext, predIndex:int):\n            if predIndex == 49:\n                return self.precpred(self._ctx, 1)\n\n"
  },
  {
    "path": "runtime/Python3/tests/run.py",
    "content": "import sys\nimport os\nsrc_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'src')\nsys.path.insert(0,src_path)\nfrom xpathtest import XPathTest\n#from TestTokenStreamRewriter import TestTokenStreamRewriter\nfrom TestFileStream import TestFileStream\nfrom TestInputStream import TestInputStream\nfrom TestIntervalSet import TestIntervalSet\nfrom TestRecognizer import TestRecognizer\nimport unittest\nunittest.main()\n"
  },
  {
    "path": "runtime/Python3/tests/xpathtest.py",
    "content": "import antlr4\nfrom antlr4 import InputStream, CommonTokenStream, TerminalNode\nfrom antlr4.xpath.XPath import XPath\nimport unittest\nfrom expr.ExprParser import ExprParser\nfrom expr.ExprLexer  import ExprLexer\n\ndef tokenToString(token, ruleNames):\n    if isinstance(token, TerminalNode):\n        return str(token)\n    else:\n        return ruleNames[token.getRuleIndex()]\n\nclass XPathTest(unittest.TestCase):\n    def setUp(self):\n        self.input_stream = InputStream(\n            \"def f(x,y) { x = 3+4; y; ; }\\n\"\n            \"def g(x) { return 1+2*x; }\\n\"\n        )\n\n        # Create the Token Stream\n        self.lexer = ExprLexer(self.input_stream)\n        self.stream = CommonTokenStream(self.lexer)\n        self.stream.fill()\n\n        # Create the parser and expression parse tree\n        self.parser = ExprParser(self.stream)\n        self.tree   = self.parser.prog()\n\n    def testValidPaths(self):\n        valid_paths = [\n            \"/prog/func\",\t\t # all funcs under prog at root\n            \"/prog/*\",\t\t\t # all children of prog at root\n            \"/*/func\",\t\t\t # all func kids of any root node\n            \"prog\",\t\t\t\t # prog must be root node\n            \"/prog\",\t\t\t # prog must be root node\n            \"/*\",\t\t\t\t # any root\n            \"*\",\t\t\t\t # any root\n            \"//ID\",\t\t\t\t # any ID in tree\n            \"//expr/primary/ID\", # any ID child of a primary under any expr\n            \"//body//ID\",\t\t # any ID under a body\n            \"//'return'\",\t\t # any 'return' literal in tree, matched by literal name\n            \"//RETURN\",\t\t\t # any 'return' literal in tree, matched by symbolic name\n            \"//primary/*\",\t\t # all kids of any primary\n            \"//func/*/stat\",\t # all stat nodes grandkids of any func node\n            \"/prog/func/'def'\",\t # all def literal kids of func kid of prog\n            \"//stat/';'\",\t\t # all ';' under any stat node\n            \"//expr/primary/!ID\",# anything but ID under primary under any expr node\n            \"//expr/!primary\",\t # anything but primary under any expr node\n            \"//!*\",\t\t\t\t # nothing anywhere\n            \"/!*\",\t\t\t\t # nothing at root\n            \"//expr//ID\"\t\t # any ID under any expression (tests antlr/antlr4#370)\n        ]\n\n        expected_results = [\n            \"[func, func]\",\n            \"[func, func]\",\n            \"[func, func]\",\n            \"[prog]\",\n            \"[prog]\",\n            \"[prog]\",\n            \"[prog]\",\n            \"[f, x, y, x, y, g, x, x]\",\n            \"[y, x]\",\n            \"[x, y, x]\",\n            \"[return]\",\n            \"[return]\",\n            \"[3, 4, y, 1, 2, x]\",\n            \"[stat, stat, stat, stat]\",\n            \"[def, def]\",\n            \"[;, ;, ;, ;]\",\n            \"[3, 4, 1, 2]\",\n            \"[expr, expr, expr, expr, expr, expr]\",\n            \"[]\",\n            \"[]\",\n            \"[y, x]\",\n        ]\n\n        for path, expected in zip(valid_paths, expected_results):\n            # Build test string\n            res = XPath.findAll(self.tree, path, self.parser)\n            res_str = \", \".join([tokenToString(token, self.parser.ruleNames) for token in res])\n            res_str = \"[%s]\" % res_str\n\n            # Test against expected output\n            self.assertEqual(res_str, expected, \"Failed test %s\" % path)\n\nif __name__ == '__main__':\n    unittest.main()"
  },
  {
    "path": "runtime/Swift/.gitignore",
    "content": ".build/\nAntlr4.xcodeproj/\nTests/Antlr4Tests/gen/\nxcuserdata/\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ANTLRErrorListener.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// How to emit recognition errors.\n/// \n\npublic protocol ANTLRErrorListener: AnyObject {\n    /// \n    /// Upon syntax error, notify any interested parties. This is not how to\n    /// recover from errors or compute error messages. _org.antlr.v4.runtime.ANTLRErrorStrategy_\n    /// specifies how to recover from syntax errors and how to compute error\n    /// messages. This listener's job is simply to emit a computed message,\n    /// though it has enough information to create its own message in many cases.\n    /// \n    /// The _RecognitionException_ is non-null for all syntax errors except\n    /// when we discover mismatched token errors that we can recover from\n    /// in-line, without returning from the surrounding rule (via the single\n    /// token insertion and deletion mechanism).\n    /// \n    /// - parameter recognizer:\n    /// What parser got the error. From this\n    /// object, you can access the context as well\n    /// as the input stream.\n    /// - parameter offendingSymbol:\n    /// The offending token in the input token\n    /// stream, unless recognizer is a lexer (then it's null). If\n    /// no viable alternative error, `e` has token at which we\n    /// started production for the decision.\n    /// - parameter line:\n    /// The line number in the input where the error occurred.\n    /// - parameter charPositionInLine:\n    /// The character position within that line where the error occurred.\n    /// - parameter msg:\n    /// The message to emit.\n    /// - parameter e:\n    /// The exception generated by the parser that led to\n    /// the reporting of an error. It is null in the case where\n    /// the parser was able to recover in line without exiting the\n    /// surrounding rule.\n    /// \n    func syntaxError<T>(_ recognizer: Recognizer<T>,\n                        _ offendingSymbol: AnyObject?,\n                        _ line: Int,\n                        _ charPositionInLine: Int,\n                        _ msg: String,\n                        _ e: AnyObject?\n    )\n\n    /// \n    /// This method is called by the parser when a full-context prediction\n    /// results in an ambiguity.\n    /// \n    /// Each full-context prediction which does not result in a syntax error\n    /// will call either _#reportContextSensitivity_ or\n    /// _#reportAmbiguity_.\n    /// \n    /// When `ambigAlts` is not null, it contains the set of potentially\n    /// viable alternatives identified by the prediction algorithm. When\n    /// `ambigAlts` is null, use _org.antlr.v4.runtime.atn.ATNConfigSet#getAlts_ to obtain the\n    /// represented alternatives from the `configs` argument.\n    /// \n    /// When `exact` is `true`, __all__ of the potentially\n    /// viable alternatives are truly viable, i.e. this is reporting an exact\n    /// ambiguity. When `exact` is `false`, __at least two__ of\n    /// the potentially viable alternatives are viable for the current input, but\n    /// the prediction algorithm terminated as soon as it determined that at\n    /// least the __minimum__ potentially viable alternative is truly\n    /// viable.\n    /// \n    /// When the _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_ prediction\n    /// mode is used, the parser is required to identify exact ambiguities so\n    /// `exact` will always be `true`.\n    /// \n    /// This method is not used by lexers.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter dfa: the DFA for the current decision\n    /// - parameter startIndex: the input index where the decision started\n    /// - parameter stopIndex: the input input where the ambiguity was identified\n    /// - parameter exact: `true` if the ambiguity is exactly known, otherwise\n    /// `false`. This is always `true` when\n    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_ is used.\n    /// - parameter ambigAlts: the potentially ambiguous alternatives, or `null`\n    /// to indicate that the potentially ambiguous alternatives are the complete\n    /// set of represented alternatives in `configs`\n    /// - parameter configs: the ATN configuration set where the ambiguity was\n    /// identified\n    /// \n    func reportAmbiguity(_ recognizer: Parser,\n                         _ dfa: DFA,\n                         _ startIndex: Int,\n                         _ stopIndex: Int,\n                         _ exact: Bool,\n                         _ ambigAlts: BitSet,\n                         _ configs: ATNConfigSet)\n\n    /// \n    /// This method is called when an SLL conflict occurs and the parser is about\n    /// to use the full context information to make an LL decision.\n    /// \n    /// If one or more configurations in `configs` contains a semantic\n    /// predicate, the predicates are evaluated before this method is called. The\n    /// subset of alternatives which are still viable after predicates are\n    /// evaluated is reported in `conflictingAlts`.\n    /// \n    /// This method is not used by lexers.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter dfa: the DFA for the current decision\n    /// - parameter startIndex: the input index where the decision started\n    /// - parameter stopIndex: the input index where the SLL conflict occurred\n    /// - parameter conflictingAlts: The specific conflicting alternatives. If this is\n    /// `null`, the conflicting alternatives are all alternatives\n    /// represented in `configs`. At the moment, conflictingAlts is non-null\n    /// (for the reference implementation, but Sam's optimized version can see this\n    /// as null).\n    /// - parameter configs: the ATN configuration set where the SLL conflict was\n    /// detected\n    /// \n    func reportAttemptingFullContext(_ recognizer: Parser,\n                                     _ dfa: DFA,\n                                     _ startIndex: Int,\n                                     _ stopIndex: Int,\n                                     _ conflictingAlts: BitSet?,\n                                     _ configs: ATNConfigSet)\n\n    /// \n    /// This method is called by the parser when a full-context prediction has a\n    /// unique result.\n    /// \n    /// Each full-context prediction which does not result in a syntax error\n    /// will call either _#reportContextSensitivity_ or\n    /// _#reportAmbiguity_.\n    /// \n    /// For prediction implementations that only evaluate full-context\n    /// predictions when an SLL conflict is found (including the default\n    /// _org.antlr.v4.runtime.atn.ParserATNSimulator_ implementation), this method reports cases\n    /// where SLL conflicts were resolved to unique full-context predictions,\n    /// i.e. the decision was context-sensitive. This report does not necessarily\n    /// indicate a problem, and it may appear even in completely unambiguous\n    /// grammars.\n    /// \n    /// `configs` may have more than one represented alternative if the\n    /// full-context prediction algorithm does not evaluate predicates before\n    /// beginning the full-context prediction. In all cases, the final prediction\n    /// is passed as the `prediction` argument.\n    /// \n    /// Note that the definition of \"context sensitivity\" in this method\n    /// differs from the concept in _org.antlr.v4.runtime.atn.DecisionInfo#contextSensitivities_.\n    /// This method reports all instances where an SLL conflict occurred but LL\n    /// parsing produced a unique result, whether or not that unique result\n    /// matches the minimum alternative in the SLL conflicting set.\n    /// \n    /// This method is not used by lexers.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter dfa: the DFA for the current decision\n    /// - parameter startIndex: the input index where the decision started\n    /// - parameter stopIndex: the input index where the context sensitivity was\n    /// finally determined\n    /// - parameter prediction: the unambiguous result of the full-context prediction\n    /// - parameter configs: the ATN configuration set where the unambiguous prediction\n    /// was determined\n    /// \n    func reportContextSensitivity(_ recognizer: Parser,\n                                  _ dfa: DFA,\n                                  _ startIndex: Int,\n                                  _ stopIndex: Int,\n                                  _ prediction: Int,\n                                  _ configs: ATNConfigSet)\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ANTLRErrorStrategy.swift",
    "content": "/// \n/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n/// \n\n\n/// \n/// \n/// The interface for defining strategies to deal with syntax errors\n/// encountered during a parse by ANTLR-generated parsers. We distinguish between three\n/// different kinds of errors:\n/// \n/// * The parser could not figure out which path to take in the ATN (none of\n/// the available alternatives could possibly match)\n/// * The current input does not match what we were looking for\n/// * A predicate evaluated to false\n/// \n/// Implementations of this interface report syntax errors by calling\n/// _org.antlr.v4.runtime.Parser#notifyErrorListeners_.\n/// \n/// TODO: what to do about lexers\n/// \npublic protocol ANTLRErrorStrategy {\n    /// \n    /// Reset the error handler state for the specified `recognizer`.\n    /// - parameter recognizer: the parser instance\n    /// \n    func reset(_ recognizer: Parser)\n\n    /// \n    /// This method is called when an unexpected symbol is encountered during an\n    /// inline match operation, such as _org.antlr.v4.runtime.Parser#match_. If the error\n    /// strategy successfully recovers from the match failure, this method\n    /// returns the _org.antlr.v4.runtime.Token_ instance which should be treated as the\n    /// successful result of the match.\n    /// \n    /// This method handles the consumption of any tokens - the caller should\n    /// __not__ call _org.antlr.v4.runtime.Parser#consume_ after a successful recovery.\n    /// \n    /// Note that the calling code will not report an error if this method\n    /// returns successfully. The error strategy implementation is responsible\n    /// for calling _org.antlr.v4.runtime.Parser#notifyErrorListeners_ as appropriate.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - throws: _RecognitionException_ if the error strategy was not able to\n    /// recover from the unexpected input symbol\n    /// \n    @discardableResult\n    func recoverInline(_ recognizer: Parser) throws -> Token\n\n    /// \n    /// This method is called to recover from exception `e`. This method is\n    /// called after _#reportError_ by the default exception handler\n    /// generated for a rule method.\n    /// \n    /// - seealso: #reportError\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter e: the recognition exception to recover from\n    /// - throws: _RecognitionException_ if the error strategy could not recover from\n    /// the recognition exception\n    /// \n    func recover(_ recognizer: Parser, _ e: RecognitionException) throws\n\n    /// \n    /// This method provides the error handler with an opportunity to handle\n    /// syntactic or semantic errors in the input stream before they result in a\n    /// _org.antlr.v4.runtime.RecognitionException_.\n    /// \n    /// The generated code currently contains calls to _#sync_ after\n    /// entering the decision state of a closure block (`(...)*` or\n    /// `(...)+`).\n    /// \n    /// For an implementation based on Jim Idle's \"magic sync\" mechanism, see\n    /// _org.antlr.v4.runtime.DefaultErrorStrategy#sync_.\n    /// \n    /// - seealso: org.antlr.v4.runtime.DefaultErrorStrategy#sync\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - throws: _RecognitionException_ if an error is detected by the error\n    /// strategy but cannot be automatically recovered at the current state in\n    /// the parsing process\n    /// \n    func sync(_ recognizer: Parser) throws\n\n    /// \n    /// Tests whether or not recognizer} is in the process of recovering\n    /// from an error. In error recovery mode, _org.antlr.v4.runtime.Parser#consume_ adds\n    /// symbols to the parse tree by calling\n    /// _Parser#createErrorNode(ParserRuleContext, Token)_ then\n    /// _ParserRuleContext#addErrorNode(ErrorNode)_ instead of\n    /// _Parser#createTerminalNode(ParserRuleContext, Token)_.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - returns: `true` if the parser is currently recovering from a parse\n    /// error, otherwise `false`\n    /// \n    func inErrorRecoveryMode(_ recognizer: Parser) -> Bool\n\n    /// \n    /// This method is called by when the parser successfully matches an input\n    /// symbol.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// \n    func reportMatch(_ recognizer: Parser)\n\n    /// \n    /// Report any kind of _org.antlr.v4.runtime.RecognitionException_. This method is called by\n    /// the default exception handler generated for a rule method.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter e: the recognition exception to report\n    /// \n    func reportError(_ recognizer: Parser, _ e: RecognitionException)\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ANTLRFileStream.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// This is an _org.antlr.v4.runtime.ANTLRInputStream_ that is loaded from a file all at once\n/// when you construct the object.\n/// \n\nimport Foundation\n\npublic class ANTLRFileStream: ANTLRInputStream {\n    private let fileName: String\n\n    public init(_ fileName: String, _ encoding: String.Encoding? = nil) throws {\n        self.fileName = fileName\n        let fileContents = try String(contentsOfFile: fileName, encoding: encoding ?? .utf8)\n        let data = Array(fileContents.unicodeScalars)\n        super.init(data, data.count)\n    }\n\n    override\n    public func getSourceName() -> String {\n        return fileName\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ANTLRInputStream.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n///\n/// Vacuum all input from a _java.io.Reader_/_java.io.InputStream_ and then treat it\n/// like a `char[]` buffer. Can also pass in a _String_ or\n/// `char[]` to use.\n/// \n/// If you need encoding, pass in stream/reader with correct encoding.\n///\npublic class ANTLRInputStream: CharStream {\n    ///\n    /// The data being scanned\n    /// \n    internal let data: [UnicodeScalar]\n\n    /// \n    /// How many unicode scalars are actually in the buffer\n    /// \n    internal var n: Int\n\n    /// \n    /// 0...n-1 index into string of next char\n    /// \n    internal var p = 0\n\n    /// \n    /// What is name or source of this char stream?\n    /// \n    public var name: String?\n\n    public init() {\n        n = 0\n        data = []\n    }\n\n    /// \n    /// Copy data in string to a local char array\n    /// \n    public init(_ input: String) {\n        self.data = Array(input.unicodeScalars)\n        self.n = data.count\n    }\n\n    /// \n    /// This is the preferred constructor for strings as no data is copied\n    /// \n    public init(_ data: [UnicodeScalar], _ numberOfActualUnicodeScalarsInArray: Int) {\n        self.data = data\n        self.n = numberOfActualUnicodeScalarsInArray\n    }\n\n    ///\n    /// This is only for backward compatibility that accepts array of `Character`.\n    /// Use `init(_ data: [UnicodeScalar], _ numberOfActualUnicodeScalarsInArray: Int)` instead.\n    ///\n    public init(_ data: [Character], _ numberOfActualUnicodeScalarsInArray: Int) {\n        let string = String(data)\n        self.data = Array(string.unicodeScalars)\n        self.n = numberOfActualUnicodeScalarsInArray\n    }\n\n    public func reset() {\n        p = 0\n    }\n\n    public func consume() throws {\n        if p >= n {\n            assert(LA(1) == ANTLRInputStream.EOF, \"Expected: LA(1)==IntStream.EOF\")\n\n            throw ANTLRError.illegalState(msg: \"cannot consume EOF\")\n\n        }\n\n        // print(\"prev p=\"+p+\", c=\"+(char)data[p]);\n        if p < n {\n            p += 1\n            //print(\"p moves to \"+p+\" (c='\"+(char)data[p]+\"')\");\n        }\n    }\n\n    public func LA(_ i: Int) -> Int {\n        var i = i\n        if i == 0 {\n            return 0 // undefined\n        }\n        if i < 0 {\n            i += 1 // e.g., translate LA(-1) to use offset i=0; then data[p+0-1]\n            if (p + i - 1) < 0 {\n                return ANTLRInputStream.EOF// invalid; no char before first char\n            }\n        }\n\n        if (p + i - 1) >= n {\n            //print(\"char LA(\"+i+\")=EOF; p=\"+p);\n            return ANTLRInputStream.EOF\n        }\n        //print(\"char LA(\"+i+\")=\"+(char)data[p+i-1]+\"; p=\"+p);\n        //print(\"LA(\"+i+\"); p=\"+p+\" n=\"+n+\" data.length=\"+data.length);\n        return Int(data[p + i - 1].value)\n    }\n\n    public func LT(_ i: Int) -> Int {\n        return LA(i)\n    }\n\n    /// \n    /// Return the current input symbol index 0...n where n indicates the\n    /// last symbol has been read.  The index is the index of char to\n    /// be returned from LA(1).\n    /// \n    public func index() -> Int {\n        return p\n    }\n\n    public func size() -> Int {\n        return n\n    }\n\n    /// \n    /// mark/release do nothing; we have entire buffer\n    /// \n\n    public func mark() -> Int {\n        return -1\n    }\n\n    public func release(_ marker: Int) {\n    }\n\n    /// \n    /// consume() ahead until p==index; can't just set p=index as we must\n    /// update line and charPositionInLine. If we seek backwards, just set p\n    /// \n\n    public func seek(_ index: Int) throws {\n        var index = index\n        if index <= p {\n            p = index // just jump; don't update stream state (line, ...)\n            return\n        }\n        // seek forward, consume until p hits index or n (whichever comes first)\n        index = min(index, n)\n        while p < index {\n            try consume()\n        }\n    }\n\n    public func getText(_ interval: Interval) -> String {\n        let start = interval.a\n        if start >= n {\n            return \"\"\n        }\n        let stop = min(n, interval.b + 1)\n\n        var unicodeScalarView = String.UnicodeScalarView()\n        unicodeScalarView.append(contentsOf: data[start ..< stop])\n        return String(unicodeScalarView)\n    }\n\n    public func getSourceName() -> String {\n        return name ?? ANTLRInputStream.UNKNOWN_SOURCE_NAME\n    }\n\n    public func toString() -> String {\n        var unicodeScalarView = String.UnicodeScalarView()\n        unicodeScalarView.append(contentsOf: data)\n        return String(unicodeScalarView)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/BailErrorStrategy.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// \n/// This implementation of _org.antlr.v4.runtime.ANTLRErrorStrategy_ responds to syntax errors\n/// by immediately canceling the parse operation with a\n/// _org.antlr.v4.runtime.misc.ParseCancellationException_. The implementation ensures that the\n/// _org.antlr.v4.runtime.ParserRuleContext#exception_ field is set for all parse tree nodes\n/// that were not completed prior to encountering the error.\n/// \n/// This error strategy is useful in the following scenarios.\n/// \n/// * __Two-stage parsing:__ This error strategy allows the first\n/// stage of two-stage parsing to immediately terminate if an error is\n/// encountered, and immediately fall back to the second stage. In addition to\n/// avoiding wasted work by attempting to recover from errors here, the empty\n/// implementation of _org.antlr.v4.runtime.BailErrorStrategy#sync_ improves the performance of\n/// the first stage.\n/// \n/// * __Silent validation:__ When syntax errors are not being\n/// reported or logged, and the parse result is simply ignored if errors occur,\n/// the _org.antlr.v4.runtime.BailErrorStrategy_ avoids wasting work on recovering from errors\n/// when the result will be ignored either way.\n/// \n/// `myparser.setErrorHandler(new BailErrorStrategy());`\n/// \n/// - seealso: org.antlr.v4.runtime.Parser#setErrorHandler(org.antlr.v4.runtime.ANTLRErrorStrategy)\n/// \n/// \nopen class BailErrorStrategy: DefaultErrorStrategy {\n    public override init() {\n    }\n\n    /// \n    /// Instead of recovering from exception `e`, re-throw it wrapped\n    /// in a _org.antlr.v4.runtime.misc.ParseCancellationException_ so it is not caught by the\n    /// rule function catches.  Use _Exception#getCause()_ to get the\n    /// original _org.antlr.v4.runtime.RecognitionException_.\n    /// \n    override open func recover(_ recognizer: Parser, _ e: RecognitionException) throws {\n        var context = recognizer.getContext()\n        while let contextWrap = context {\n            contextWrap.exception = e\n            context = (contextWrap.getParent() as? ParserRuleContext)\n        }\n\n        throw ANTLRException.parseCancellation(e: e)\n    }\n\n    /// \n    /// Make sure we don't attempt to recover inline; if the parser\n    /// successfully recovers, it won't throw an exception.\n    /// \n    override\n    open func recoverInline(_ recognizer: Parser) throws -> Token {\n        let e = InputMismatchException(recognizer)\n        var context = recognizer.getContext()\n        while let contextWrap = context {\n             contextWrap.exception = e\n             context = (contextWrap.getParent() as? ParserRuleContext)\n        }\n\n        throw ANTLRException.parseCancellation(e: e)\n    }\n\n    /// \n    /// Make sure we don't attempt to recover from problems in subrules.\n    /// \n    override\n    open func sync(_ recognizer: Parser) {\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/BaseErrorListener.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// Provides an empty default implementation of _org.antlr.v4.runtime.ANTLRErrorListener_. The\n/// default implementation of each method does nothing, but can be overridden as\n/// necessary.\n/// \n/// -  Sam Harwell\n/// \n\nopen class BaseErrorListener: ANTLRErrorListener {\n    public init() {\n    }\n\n    open func syntaxError<T>(_ recognizer: Recognizer<T>,\n                             _ offendingSymbol: AnyObject?,\n                             _ line: Int,\n                             _ charPositionInLine: Int,\n                             _ msg: String,\n                             _ e: AnyObject?\n    ) {\n    }\n\n\n    open func reportAmbiguity(_ recognizer: Parser,\n                                _ dfa: DFA,\n                                _ startIndex: Int,\n                                _ stopIndex: Int,\n                                _ exact: Bool,\n                                _ ambigAlts: BitSet,\n                                _ configs: ATNConfigSet) {\n    }\n\n\n    open func reportAttemptingFullContext(_ recognizer: Parser,\n                                            _ dfa: DFA,\n                                            _ startIndex: Int,\n                                            _ stopIndex: Int,\n                                            _ conflictingAlts: BitSet?,\n                                            _ configs: ATNConfigSet) {\n    }\n\n\n    open func reportContextSensitivity(_ recognizer: Parser,\n                                         _ dfa: DFA,\n                                         _ startIndex: Int,\n                                         _ stopIndex: Int,\n                                         _ prediction: Int,\n                                         _ configs: ATNConfigSet) {\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/BufferedTokenStream.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This implementation of _org.antlr.v4.runtime.TokenStream_ loads tokens from a\n/// _org.antlr.v4.runtime.TokenSource_ on-demand, and places the tokens in a buffer to provide\n/// access to any previous token by index.\n/// \n/// \n/// This token stream ignores the value of _org.antlr.v4.runtime.Token#getChannel_. If your\n/// parser requires the token stream filter tokens to only those on a particular\n/// channel, such as _org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_ or\n/// _org.antlr.v4.runtime.Token#HIDDEN_CHANNEL_, use a filtering token stream such a\n/// _org.antlr.v4.runtime.CommonTokenStream_.\n///\n\npublic class BufferedTokenStream: TokenStream {\n    /// \n    /// The _org.antlr.v4.runtime.TokenSource_ from which tokens for this stream are fetched.\n    /// \n    internal var tokenSource: TokenSource\n\n    /// \n    /// A collection of all tokens fetched from the token source. The list is\n    /// considered a complete view of the input once _#fetchedEOF_ is set\n    /// to `true`.\n    /// \n    internal var tokens = [Token]()\n\n    /// \n    /// The index into _#tokens_ of the current token (next token to\n    /// _#consume_). _#tokens_`[`_#p_`]` should be\n    /// _#LT LT(1)_.\n    /// \n    /// This field is set to -1 when the stream is first constructed or when\n    /// _#setTokenSource_ is called, indicating that the first token has\n    /// not yet been fetched from the token source. For additional information,\n    /// see the documentation of _org.antlr.v4.runtime.IntStream_ for a description of\n    /// Initializing Methods.\n    /// \n    internal var p = -1\n\n    /// \n    /// Indicates whether the _org.antlr.v4.runtime.Token#EOF_ token has been fetched from\n    /// _#tokenSource_ and added to _#tokens_. This field improves\n    /// performance for the following cases:\n    /// \n    /// * _#consume_: The lookahead check in _#consume_ to prevent\n    /// consuming the EOF symbol is optimized by checking the values of\n    /// _#fetchedEOF_ and _#p_ instead of calling _#LA_.\n    /// \n    /// * _#fetch_: The check to prevent adding multiple EOF symbols into\n    /// _#tokens_ is trivial with this field.\n    /// \n    internal var fetchedEOF = false\n\n\n    public init(_ tokenSource: TokenSource) {\n        self.tokenSource = tokenSource\n    }\n\n\n    public func getTokenSource() -> TokenSource {\n        return tokenSource\n    }\n\n\n    public func index() -> Int {\n        return p\n    }\n\n\n    public func mark() -> Int {\n        return 0\n    }\n\n    public func release(_ marker: Int) {\n        // no resources to release\n    }\n\n    public func reset() throws {\n        try seek(0)\n    }\n\n\n    public func seek(_ index: Int) throws {\n        try lazyInit()\n        p = try adjustSeekIndex(index)\n    }\n\n\n    public func size() -> Int {\n        return tokens.count\n    }\n\n\n    public func consume() throws {\n        var skipEofCheck: Bool\n        if p >= 0 {\n            if fetchedEOF {\n                // the last token in tokens is EOF. skip check if p indexes any\n                // fetched token except the last.\n                skipEofCheck = p < tokens.count - 1\n            } else {\n                // no EOF token in tokens. skip check if p indexes a fetched token.\n                skipEofCheck = p < tokens.count\n            }\n        } else {\n            // not yet initialized\n            skipEofCheck = false\n        }\n\n        if try !skipEofCheck && LA(1) == BufferedTokenStream.EOF {\n            throw ANTLRError.illegalState(msg: \"cannot consume EOF\")\n        }\n\n        if try sync(p + 1) {\n            p = try adjustSeekIndex(p + 1)\n        }\n    }\n\n    /// \n    /// Make sure index `i` in tokens has a token.\n    /// \n    /// - returns: `true` if a token is located at index `i`, otherwise\n    /// `false`.\n    /// - seealso: #get(int i)\n    /// \n    @discardableResult\n    internal func sync(_ i: Int) throws -> Bool {\n        assert(i >= 0, \"Expected: i>=0\")\n        let n = i - tokens.count + 1 // how many more elements we need?\n        //print(\"sync(\"+i+\") needs \"+n);\n        if n > 0 {\n            let fetched = try fetch(n)\n            return fetched >= n\n        }\n\n        return true\n    }\n\n    /// \n    /// Add `n` elements to buffer.\n    /// \n    /// - returns: The actual number of elements added to the buffer.\n    /// \n    internal func fetch(_ n: Int) throws -> Int {\n        if fetchedEOF {\n            return 0\n        }\n\n        for i in 0..<n {\n            let t = try tokenSource.nextToken()\n            if let wt = t as? WritableToken {\n                wt.setTokenIndex(tokens.count)\n            }\n\n            tokens.append(t)\n            if t.getType() == BufferedTokenStream.EOF {\n                fetchedEOF = true\n                return i + 1\n            }\n        }\n\n        return n\n    }\n\n    public func get(_ i: Int) throws -> Token {\n        guard tokens.indices.contains(i) else {\n            throw ANTLRError.indexOutOfBounds(msg: \"token index \\(i) out of range 0 ..< \\(tokens.count)\")\n        }\n        return tokens[i]\n    }\n\n    /// \n    /// Get all tokens from start...stop inclusively\n    /// \n    public func get(_ start: Int,_ stop: Int) throws -> Array<Token>? {\n        var stop = stop\n        if start < 0 || stop < 0 {\n            return nil\n        }\n        try lazyInit()\n        var subset = [Token]()\n        if stop >= tokens.count {\n            stop = tokens.count - 1\n        }\n        for i in start...stop {\n            let t = tokens[i]\n            if t.getType() == BufferedTokenStream.EOF {\n                break\n            }\n            subset.append(t)\n        }\n        return subset\n    }\n\n    public func LA(_ i: Int) throws -> Int {\n        return try LT(i)!.getType()\n    }\n\n    internal func LB(_ k: Int) throws -> Token? {\n        if (p - k) < 0 {\n            return nil\n        }\n        return tokens[p - k]\n    }\n\n\n    public func LT(_ k: Int) throws -> Token? {\n        try lazyInit()\n        if k == 0 {\n            return nil\n        }\n        if k < 0 {\n            return try LB(-k)\n        }\n\n        let i = p + k - 1\n        try sync(i)\n        if i >= tokens.count {\n            // return EOF token\n            // EOF must be last token\n            return tokens.last!\n        }\n        return tokens[i]\n    }\n\n    /// \n    /// Allowed derived classes to modify the behavior of operations which change\n    /// the current stream position by adjusting the target token index of a seek\n    /// operation. The default implementation simply returns `i`. If an\n    /// exception is thrown in this method, the current stream index should not be\n    /// changed.\n    /// \n    /// For example, _org.antlr.v4.runtime.CommonTokenStream_ overrides this method to ensure that\n    /// the seek target is always an on-channel token.\n    /// \n    /// - parameter i: The target token index.\n    /// - returns: The adjusted target token index.\n    /// \n    internal func adjustSeekIndex(_ i: Int) throws -> Int {\n        return i\n    }\n\n    internal final func lazyInit() throws {\n        if p == -1 {\n            try setup()\n        }\n    }\n\n    internal func setup() throws {\n        try sync(0)\n        p = try adjustSeekIndex(0)\n    }\n\n    /// \n    /// Reset this token stream by setting its token source.\n    /// \n    public func setTokenSource(_ tokenSource: TokenSource) {\n        self.tokenSource = tokenSource\n        tokens.removeAll()\n        p = -1\n        fetchedEOF = false\n    }\n\n    public func getTokens() -> [Token] {\n        return tokens\n    }\n\n    public func getTokens(_ start: Int, _ stop: Int) throws -> [Token]? {\n        return try getTokens(start, stop, nil)\n    }\n\n    /// \n    /// Given a start and stop index, return a List of all tokens in\n    /// the token type BitSet.  Return null if no tokens were found.  This\n    /// method looks at both on and off channel tokens.\n    /// \n    public func getTokens(_ start: Int, _ stop: Int, _ types: Set<Int>?) throws -> [Token]? {\n        try lazyInit()\n        guard tokens.indices.contains(start),\n              tokens.indices.contains(stop) else {\n            throw ANTLRError.indexOutOfBounds(msg: \"start \\(start) or stop \\(stop) not in 0 ..< \\(tokens.count)\")\n\n        }\n        if start > stop {\n            return nil\n        }\n\n        var filteredTokens = [Token]()\n        for i in start...stop {\n            let t = tokens[i]\n            if types?.contains(t.getType()) ?? true {\n                filteredTokens.append(t)\n            }\n        }\n        if filteredTokens.isEmpty {\n            return nil\n        }\n        return filteredTokens\n    }\n\n    public func getTokens(_ start: Int, _ stop: Int, _ ttype: Int) throws -> [Token]? {\n        return try getTokens(start, stop, [ttype])\n    }\n\n    /// \n    /// Given a starting index, return the index of the next token on channel.\n    /// Return `i` if `tokens[i]` is on channel. Return the index of\n    /// the EOF token if there are no tokens on channel between `i` and\n    /// EOF.\n    /// \n    internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {\n        var i = i\n        try sync(i)\n        if i >= size() {\n            return size() - 1\n        }\n\n        var token = tokens[i]\n        while token.getChannel() != channel {\n            if token.getType() == BufferedTokenStream.EOF {\n                return i\n            }\n\n            i += 1\n            try sync(i)\n            token = tokens[i]\n        }\n\n        return i\n    }\n\n    /// \n    /// Given a starting index, return the index of the previous token on\n    /// channel. Return `i` if `tokens[i]` is on channel. Return -1\n    /// if there are no tokens on channel between `i` and 0.\n    /// \n    /// \n    /// If `i` specifies an index at or after the EOF token, the EOF token\n    /// index is returned. This is due to the fact that the EOF token is treated\n    /// as though it were on every channel.\n    /// \n    internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int {\n        var i = i\n        try sync(i)\n        if i >= size() {\n            // the EOF token is on every channel\n            return size() - 1\n        }\n\n        while i >= 0 {\n            let token = tokens[i]\n            if token.getType() == BufferedTokenStream.EOF || token.getChannel() == channel {\n                return i\n            }\n\n            i -= 1\n        }\n\n        return i\n    }\n\n    /// \n    /// Collect all tokens on specified channel to the right of\n    /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or\n    /// EOF. If channel is -1, find any non default channel token.\n    /// \n    public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int = -1) throws -> [Token]? {\n        try lazyInit()\n        guard tokens.indices.contains(tokenIndex) else {\n            throw ANTLRError.indexOutOfBounds(msg: \"\\(tokenIndex) not in 0 ..< \\(tokens.count)\")\n        }\n\n        let nextOnChannel = try nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL)\n        let from = tokenIndex + 1\n        let to: Int\n        // if none onchannel to right, nextOnChannel=-1 so set to = last token\n        if nextOnChannel == -1 {\n            to = size() - 1\n        }\n        else {\n            to = nextOnChannel\n        }\n\n        return filterForChannel(from, to, channel)\n    }\n\n    ///\n    /// Collect all tokens on specified channel to the left of\n    /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.\n    /// If channel is -1, find any non default channel token.\n    /// \n    public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int = -1) throws -> [Token]? {\n        try lazyInit()\n        guard tokens.indices.contains(tokenIndex) else {\n            throw ANTLRError.indexOutOfBounds(msg: \"\\(tokenIndex) not in 0 ..< \\(tokens.count)\")\n        }\n\n        if tokenIndex == 0 {\n            // obviously no tokens can appear before the first token\n            return nil\n        }\n\n        let prevOnChannel = try previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL)\n        if prevOnChannel == tokenIndex - 1 {\n            return nil\n        }\n        // if none onchannel to left, prevOnChannel=-1 then from=0\n        let from = prevOnChannel + 1\n        let to = tokenIndex - 1\n        return filterForChannel(from, to, channel)\n    }\n\n    internal func filterForChannel(_ from: Int, _ to: Int, _ channel: Int) -> [Token]? {\n        var hidden = [Token]()\n        for t in tokens[from...to] {\n            if channel == -1 {\n                if t.getChannel() != Lexer.DEFAULT_TOKEN_CHANNEL {\n                    hidden.append(t)\n                }\n            } else {\n                if t.getChannel() == channel {\n                    hidden.append(t)\n                }\n            }\n        }\n        if hidden.isEmpty {\n            return nil\n        }\n        return hidden\n    }\n\n\n    public func getSourceName() -> String {\n        return tokenSource.getSourceName()\n    }\n\n    /// \n    /// Get the text of all tokens in this buffer.\n    /// \n    public func getText() throws -> String {\n        return try getText(Interval.of(0, size() - 1))\n    }\n\n    public func getText(_ interval: Interval) throws -> String {\n        let start = interval.a\n        if start < 0 {\n            return \"\"\n        }\n        try fill()\n        let stop = min(tokens.count, interval.b + 1)\n        var buf = \"\"\n        for t in tokens[start ..< stop] {\n            if t.getType() == BufferedTokenStream.EOF {\n                break\n            }\n            buf += t.getText()!\n        }\n        return buf\n    }\n\n\n    public func getText(_ ctx: RuleContext) throws -> String {\n        return try getText(ctx.getSourceInterval())\n    }\n\n\n    public func getText(_ start: Token?, _ stop: Token?) throws -> String {\n        if let start = start, let stop = stop {\n            return try getText(Interval.of(start.getTokenIndex(), stop.getTokenIndex()))\n        }\n\n        return \"\"\n    }\n\n    /// \n    /// Get all tokens from lexer until EOF\n    /// \n    public func fill() throws {\n        try lazyInit()\n        let blockSize = 1000\n        while true {\n            let fetched = try fetch(blockSize)\n            if fetched < blockSize {\n                return\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/CharStream.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// A source of characters for an ANTLR lexer.\n/// \n\npublic protocol CharStream: IntStream {\n    /// \n    /// This method returns the text for a range of characters within this input\n    /// stream. This method is guaranteed to not throw an exception if the\n    /// specified `interval` lies entirely within a marked range. For more\n    /// information about marked ranges, see _org.antlr.v4.runtime.IntStream#mark_.\n    /// \n    /// - parameter interval: an interval within the stream\n    /// - returns: the text of the specified interval\n    /// \n    /// - throws: _ANTLRError.illegalArgument_ if `interval.a < 0`, or if\n    /// `interval.b < interval.a - 1`, or if `interval.b` lies at or\n    /// past the end of the stream\n    /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support\n    /// getting the text of the specified interval\n    /// \n    func getText(_ interval: Interval) throws -> String\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/CommonToken.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\npublic class CommonToken: WritableToken {\n    /// \n    /// This is the backing field for _#getType_ and _#setType_.\n    /// \n    internal var type: Int\n\n    /// \n    /// This is the backing field for _#getLine_ and _#setLine_.\n    /// \n    internal var line = 0\n\n    /// \n    /// This is the backing field for _#getCharPositionInLine_ and\n    /// _#setCharPositionInLine_.\n    /// \n    internal var charPositionInLine = -1\n    // set to invalid position\n\n    /// \n    /// This is the backing field for _#getChannel_ and\n    /// _#setChannel_.\n    /// \n    internal var channel = DEFAULT_CHANNEL\n\n    /// \n    /// This is the backing field for _#getTokenSource_ and\n    /// _#getInputStream_.\n    /// \n    /// \n    /// These properties share a field to reduce the memory footprint of\n    /// _org.antlr.v4.runtime.CommonToken_. Tokens created by a _org.antlr.v4.runtime.CommonTokenFactory_ from\n    /// the same source and input stream share a reference to the same\n    /// _org.antlr.v4.runtime.misc.Pair_ containing these values.\n    /// \n\n    internal let source: TokenSourceAndStream\n\n    /// \n    /// This is the backing field for _#getText_ when the token text is\n    /// explicitly set in the constructor or via _#setText_.\n    /// \n    /// - seealso: #getText()\n    /// \n    internal var text: String?\n\n    /// \n    /// This is the backing field for _#getTokenIndex_ and\n    /// _#setTokenIndex_.\n    /// \n    internal var index = -1\n\n    /// \n    /// This is the backing field for _#getStartIndex_ and\n    /// _#setStartIndex_.\n    /// \n    internal var start = 0\n\n    /// \n    /// This is the backing field for _#getStopIndex_ and\n    /// _#setStopIndex_.\n    /// \n    internal var stop = 0\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.CommonToken_ with the specified token type.\n    /// \n    /// - parameter type: The token type.\n    /// \n\n    private var _visited: Bool = false\n\n    public init(_ type: Int) {\n        self.type = type\n        self.source = TokenSourceAndStream.EMPTY\n    }\n\n    public init(_ source: TokenSourceAndStream, _ type: Int, _ channel: Int, _ start: Int, _ stop: Int) {\n        self.source = source\n        self.type = type\n        self.channel = channel\n        self.start = start\n        self.stop = stop\n        if let tsource = source.tokenSource {\n            self.line = tsource.getLine()\n            self.charPositionInLine = tsource.getCharPositionInLine()\n        }\n    }\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.CommonToken_ with the specified token type and\n    /// text.\n    /// \n    /// - parameter type: The token type.\n    /// - parameter text: The text of the token.\n    /// \n    public init(_ type: Int, _ text: String?) {\n        self.type = type\n        self.channel = CommonToken.DEFAULT_CHANNEL\n        self.text = text\n        self.source = TokenSourceAndStream.EMPTY\n    }\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.CommonToken_ as a copy of another _org.antlr.v4.runtime.Token_.\n    ///\n    /// - parameter oldToken: The token to copy.\n    /// \n    public init(_ oldToken: Token) {\n        type = oldToken.getType()\n        line = oldToken.getLine()\n        index = oldToken.getTokenIndex()\n        charPositionInLine = oldToken.getCharPositionInLine()\n        channel = oldToken.getChannel()\n        start = oldToken.getStartIndex()\n        stop = oldToken.getStopIndex()\n        text = oldToken.getText()\n        source = oldToken.getTokenSourceAndStream()\n    }\n\n\n    public func getType() -> Int {\n        return type\n    }\n\n\n    public func setLine(_ line: Int) {\n        self.line = line\n    }\n\n\n    public func getText() -> String? {\n        if let text = text {\n            return text\n        }\n\n        if let input = getInputStream() {\n            let n = input.size()\n            if start < n && stop < n {\n                do {\n                    return try input.getText(Interval.of(start, stop))\n                }\n                catch {\n                    return nil\n                }\n            } else {\n                return \"<EOF>\"\n            }\n        }\n\n        return nil\n\n    }\n\n    /// \n    /// Explicitly set the text for this token. If {code text} is not\n    /// `null`, then _#getText_ will return this value rather than\n    /// extracting the text from the input.\n    /// \n    /// - parameter text: The explicit text of the token, or `null` if the text\n    /// should be obtained from the input along with the start and stop indexes\n    /// of the token.\n    /// \n\n    public func setText(_ text: String) {\n        self.text = text\n    }\n\n    public func getLine() -> Int {\n        return line\n    }\n\n\n    public func getCharPositionInLine() -> Int {\n        return charPositionInLine\n    }\n\n\n    public func setCharPositionInLine(_ charPositionInLine: Int) {\n        self.charPositionInLine = charPositionInLine\n    }\n\n\n    public func getChannel() -> Int {\n        return channel\n    }\n\n\n    public func setChannel(_ channel: Int) {\n        self.channel = channel\n    }\n\n\n    public func setType(_ type: Int) {\n        self.type = type\n    }\n\n\n    public func getStartIndex() -> Int {\n        return start\n    }\n\n    public func setStartIndex(_ start: Int) {\n        self.start = start\n    }\n\n\n    public func getStopIndex() -> Int {\n        return stop\n    }\n\n    public func setStopIndex(_ stop: Int) {\n        self.stop = stop\n    }\n\n\n    public func getTokenIndex() -> Int {\n        return index\n    }\n\n\n    public func setTokenIndex(_ index: Int) {\n        self.index = index\n    }\n\n\n    public func getTokenSource() -> TokenSource? {\n        return source.tokenSource\n    }\n\n\n    public func getInputStream() -> CharStream? {\n        return source.stream\n    }\n\n    public func getTokenSourceAndStream() -> TokenSourceAndStream {\n        return source\n    }\n\n    public var description: String {\n        return toString(nil)\n    }\n\n    public func toString(_ r: Recognizer<ATNSimulator>?) -> String {\n        let channelStr = (channel > 0 ? \",channel=\\(channel)\" : \"\")\n\n        var txt: String\n        if let tokenText = getText() {\n            txt = tokenText.replacingOccurrences(of: \"\\n\", with: \"\\\\n\")\n            txt = txt.replacingOccurrences(of: \"\\r\", with: \"\\\\r\")\n            txt = txt.replacingOccurrences(of: \"\\t\", with: \"\\\\t\")\n        } else {\n            txt = \"<no text>\"\n        }\n        let typeString: String\n        if let r = r {\n            typeString = r.getVocabulary().getDisplayName(type)\n        }\n        else {\n            typeString = \"\\(type)\"\n        }\n       return \"[@\\(getTokenIndex()),\\(start):\\(stop)='\\(txt)',<\\(typeString)>\\(channelStr),\\(line):\\(getCharPositionInLine())]\"\n    }\n\n    public var visited: Bool {\n        get {\n            return _visited\n        }\n\n        set {\n            _visited = newValue\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/CommonTokenFactory.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This default implementation of _org.antlr.v4.runtime.TokenFactory_ creates\n/// _org.antlr.v4.runtime.CommonToken_ objects.\n/// \n\npublic class CommonTokenFactory: TokenFactory {\n    /// \n    /// The default _org.antlr.v4.runtime.CommonTokenFactory_ instance.\n    /// \n    /// \n    /// This token factory does not explicitly copy token text when constructing\n    /// tokens.\n    /// \n    public static let DEFAULT: TokenFactory = CommonTokenFactory()\n\n    /// \n    /// Indicates whether _org.antlr.v4.runtime.CommonToken#setText_ should be called after\n    /// constructing tokens to explicitly set the text. This is useful for cases\n    /// where the input stream might not be able to provide arbitrary substrings\n    /// of text from the input after the lexer creates a token (e.g. the\n    /// implementation of _org.antlr.v4.runtime.CharStream#getText_ in\n    /// _org.antlr.v4.runtime.UnbufferedCharStream_ throws an\n    /// _UnsupportedOperationException_). Explicitly setting the token text\n    /// allows _org.antlr.v4.runtime.Token#getText_ to be called at any time regardless of the\n    /// input stream implementation.\n    /// \n    /// \n    /// The default value is `false` to avoid the performance and memory\n    /// overhead of copying text for every token unless explicitly requested.\n    /// \n    internal let copyText: Bool\n\n    /// \n    /// Constructs a _org.antlr.v4.runtime.CommonTokenFactory_ with the specified value for\n    /// _#copyText_.\n    /// \n    /// \n    /// When `copyText` is `false`, the _#DEFAULT_ instance\n    /// should be used instead of constructing a new instance.\n    /// \n    /// - parameter copyText: The value for _#copyText_.\n    /// \n    public init(_ copyText: Bool) {\n        self.copyText = copyText\n    }\n\n    /// \n    /// Constructs a _org.antlr.v4.runtime.CommonTokenFactory_ with _#copyText_ set to\n    /// `false`.\n    /// \n    /// \n    /// The _#DEFAULT_ instance should be used instead of calling this\n    /// directly.\n    /// \n    public convenience init() {\n        self.init(false)\n    }\n\n\n    public func create(_ source: TokenSourceAndStream, _ type: Int, _ text: String?,\n                       _ channel: Int, _ start: Int, _ stop: Int,\n                       _ line: Int, _ charPositionInLine: Int) -> Token {\n        let t = CommonToken(source, type, channel, start, stop)\n        t.setLine(line)\n        t.setCharPositionInLine(charPositionInLine)\n        if let text = text {\n            t.setText(text)\n        }\n        else if let cStream = source.stream, copyText {\n            t.setText(try! cStream.getText(Interval.of(start, stop)))\n        }\n\n        return t\n    }\n\n\n    public func create(_ type: Int, _ text: String) -> Token {\n        return CommonToken(type, text)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/CommonTokenStream.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This class extends _org.antlr.v4.runtime.BufferedTokenStream_ with functionality to filter\n/// token streams to tokens on a particular channel (tokens where\n/// _org.antlr.v4.runtime.Token#getChannel_ returns a particular value).\n/// \n/// \n/// This token stream provides access to all tokens by index or when calling\n/// methods like _#getText_. The channel filtering is only used for code\n/// accessing tokens via the lookahead methods _#LA_, _#LT_, and\n/// _#LB_.\n/// \n/// \n/// By default, tokens are placed on the default channel\n/// (_org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_), but may be reassigned by using the\n/// `->channel(HIDDEN)` lexer command, or by using an embedded action to\n/// call _org.antlr.v4.runtime.Lexer#setChannel_.\n/// \n/// \n/// \n/// Note: lexer rules which use the `->skip` lexer command or call\n/// _org.antlr.v4.runtime.Lexer#skip_ do not produce tokens at all, so input text matched by\n/// such a rule will not be available as part of the token stream, regardless of\n/// channel.\n/// \n\npublic class CommonTokenStream: BufferedTokenStream {\n    /// \n    /// Specifies the channel to use for filtering tokens.\n    /// \n    /// \n    /// The default value is _org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_, which matches the\n    /// default channel assigned to tokens created by the lexer.\n    /// \n    internal var channel = CommonToken.DEFAULT_CHANNEL\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.CommonTokenStream_ using the specified token\n    /// source and the default token channel (_org.antlr.v4.runtime.Token#DEFAULT_CHANNEL_).\n    /// \n    /// - parameter tokenSource: The token source.\n    /// \n    public override init(_ tokenSource: TokenSource) {\n        super.init(tokenSource)\n    }\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.CommonTokenStream_ using the specified token\n    /// source and filtering tokens to the specified channel. Only tokens whose\n    /// _org.antlr.v4.runtime.Token#getChannel_ matches `channel` or have the\n    /// _org.antlr.v4.runtime.Token#getType_ equal to _org.antlr.v4.runtime.Token#EOF_ will be returned by the\n    /// token stream lookahead methods.\n    /// \n    /// - parameter tokenSource: The token source.\n    /// - parameter channel: The channel to use for filtering tokens.\n    /// \n    public convenience init(_ tokenSource: TokenSource, _ channel: Int) {\n        self.init(tokenSource)\n        self.channel = channel\n    }\n\n    override\n    internal func adjustSeekIndex(_ i: Int) throws -> Int {\n        return try nextTokenOnChannel(i, channel)\n    }\n\n    override\n    internal func LB(_ k: Int) throws -> Token? {\n        if k == 0 || (p - k) < 0 {\n            return nil\n        }\n\n        var i = p\n        var n = 1\n        // find k good tokens looking backwards\n        while n <= k {\n            // skip off-channel tokens\n            try i = previousTokenOnChannel(i - 1, channel)\n            n += 1\n        }\n        if i < 0 {\n            return nil\n        }\n        return tokens[i]\n    }\n\n    override\n    public func LT(_ k: Int) throws -> Token? {\n        //System.out.println(\"enter LT(\"+k+\")\");\n        try lazyInit()\n        if k == 0 {\n            return nil\n        }\n        if k < 0 {\n            return try LB(-k)\n        }\n        var i = p\n        var n = 1 // we know tokens[p] is a good one\n        // find k good tokens\n        while n < k {\n            // skip off-channel tokens, but make sure to not look past EOF\n            if try sync(i + 1) {\n                i = try nextTokenOnChannel(i + 1, channel)\n            }\n            n += 1\n        }\n//\t\tif ( i>range ) range = i;\n        return tokens[i]\n    }\n\n    /// \n    /// Count EOF just once.\n    /// \n    public func getNumberOfOnChannelTokens() throws -> Int {\n        var n = 0\n        try fill()\n        for t in tokens {\n            if t.getChannel() == channel {\n                n += 1\n            }\n            if t.getType() == CommonToken.EOF {\n                break\n            }\n        }\n        return n\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ConsoleErrorListener.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// \n/// -  Sam Harwell\n/// \n\npublic class ConsoleErrorListener: BaseErrorListener {\n    /// \n    /// Provides a default instance of _org.antlr.v4.runtime.ConsoleErrorListener_.\n    /// \n    public static let INSTANCE: ConsoleErrorListener = ConsoleErrorListener()\n\n    /// \n    /// \n    /// This implementation prints messages to _System#err_ containing the\n    /// values of `line`, `charPositionInLine`, and `msg` using\n    /// the following format.\n    /// \n    /// line __line__:__charPositionInLine__ __msg__\n    /// \n    /// \n    override public func syntaxError<T>(_ recognizer: Recognizer<T>,\n                                        _ offendingSymbol: AnyObject?,\n                                        _ line: Int,\n                                        _ charPositionInLine: Int,\n                                        _ msg: String,\n                                        _ e: AnyObject?\n    ) {\n        if Parser.ConsoleError {\n            errPrint(\"line \\(line):\\(charPositionInLine) \\(msg)\")\n        }\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/DefaultErrorStrategy.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n/// \n/// This is the default implementation of _org.antlr.v4.runtime.ANTLRErrorStrategy_ used for\n/// error reporting and recovery in ANTLR parsers.\n/// \n\nimport Foundation\n\nopen class DefaultErrorStrategy: ANTLRErrorStrategy {\n    /// \n    /// Indicates whether the error strategy is currently \"recovering from an\n    /// error\". This is used to suppress reporting multiple error messages while\n    /// attempting to recover from a detected syntax error.\n    /// \n    /// - seealso: #inErrorRecoveryMode\n    /// \n    open var errorRecoveryMode = false\n\n    /// \n    /// The index into the input stream where the last error occurred.\n    /// This is used to prevent infinite loops where an error is found\n    /// but no token is consumed during recovery...another error is found,\n    /// ad nauseum.  This is a failsafe mechanism to guarantee that at least\n    /// one token/tree node is consumed for two errors.\n    /// \n    open var lastErrorIndex = -1\n\n    open var lastErrorStates: IntervalSet?\n\n    /**\n     * This field is used to propagate information about the lookahead following\n     * the previous match. Since prediction prefers completing the current rule\n     * to error recovery efforts, error reporting may occur later than the\n     * original point where it was discoverable. The original context is used to\n     * compute the true expected sets as though the reporting occurred as early\n     * as possible.\n     */\n    open var nextTokensContext: ParserRuleContext?\n\n    /**\n     * @see #nextTokensContext\n     */\n    open var nextTokensState = ATNState.INVALID_STATE_NUMBER\n\n\n    public init() {\n    }\n\n    /// \n    /// The default implementation simply calls _#endErrorCondition_ to\n    /// ensure that the handler is not in error recovery mode.\n    /// \n    open func reset(_ recognizer: Parser) {\n        endErrorCondition(recognizer)\n    }\n\n    /// \n    /// This method is called to enter error recovery mode when a recognition\n    /// exception is reported.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// \n    open func beginErrorCondition(_ recognizer: Parser) {\n        errorRecoveryMode = true\n    }\n\n    open func inErrorRecoveryMode(_ recognizer: Parser) -> Bool {\n        return errorRecoveryMode\n    }\n\n    /// \n    /// This method is called to leave error recovery mode after recovering from\n    /// a recognition exception.\n    /// \n    /// - parameter recognizer:\n    /// \n    open func endErrorCondition(_ recognizer: Parser) {\n        errorRecoveryMode = false\n        lastErrorStates = nil\n        lastErrorIndex = -1\n    }\n\n    /// \n    /// The default implementation simply calls _#endErrorCondition_.\n    /// \n    open func reportMatch(_ recognizer: Parser) {\n        endErrorCondition(recognizer)\n    }\n\n    /// \n    /// \n    /// The default implementation returns immediately if the handler is already\n    /// in error recovery mode. Otherwise, it calls _#beginErrorCondition_\n    /// and dispatches the reporting task based on the runtime type of `e`\n    /// according to the following table.\n    /// \n    /// * _org.antlr.v4.runtime.NoViableAltException_: Dispatches the call to\n    /// _#reportNoViableAlternative_\n    /// * _org.antlr.v4.runtime.InputMismatchException_: Dispatches the call to\n    /// _#reportInputMismatch_\n    /// * _org.antlr.v4.runtime.FailedPredicateException_: Dispatches the call to\n    /// _#reportFailedPredicate_\n    /// * All other types: calls _org.antlr.v4.runtime.Parser#notifyErrorListeners_ to report\n    /// the exception\n    /// \n    open func reportError(_ recognizer: Parser, _ e: RecognitionException) {\n        // if we've already reported an error and have not matched a token\n        // yet successfully, don't report any errors.\n        if inErrorRecoveryMode(recognizer) {\n\n            return // don't report spurious errors\n        }\n        beginErrorCondition(recognizer)\n        if let nvae = e as? NoViableAltException {\n            reportNoViableAlternative(recognizer, nvae)\n        }\n        else if let ime = e as? InputMismatchException {\n            reportInputMismatch(recognizer, ime)\n        }\n        else if let fpe = e as? FailedPredicateException {\n            reportFailedPredicate(recognizer, fpe)\n        }\n        else {\n            errPrint(\"unknown recognition error type: \" + String(describing: type(of: e)))\n            recognizer.notifyErrorListeners(e.getOffendingToken(), e.message ?? \"\", e)\n        }\n    }\n\n    /// \n    /// The default implementation resynchronizes the parser by consuming tokens\n    /// until we find one in the resynchronization set--loosely the set of tokens\n    /// that can follow the current rule.\n    /// \n    open func recover(_ recognizer: Parser, _ e: RecognitionException) throws {\n//\t\tprint(\"recover in \"+recognizer.getRuleInvocationStack()+\n//\t\t\t\t\t\t   \" index=\"+getTokenStream(recognizer).index()+\n//\t\t\t\t\t\t   \", lastErrorIndex=\"+\n//\t\t\t\t\t\t   lastErrorIndex+\n//\t\t\t\t\t\t   \", states=\"+lastErrorStates);\n        if let lastErrorStates = lastErrorStates ,\n          lastErrorIndex == getTokenStream(recognizer).index() &&\n          lastErrorStates.contains(recognizer.getState()) {\n            // uh oh, another error at same token index and previously-visited\n            // state in ATN; must be a case where LT(1) is in the recovery\n            // token set so nothing got consumed. Consume a single token\n            // at least to prevent an infinite loop; this is a failsafe.\n//\t\t\terrPrint(\"seen error condition before index=\"+\n//\t\t\t\t\t\t\t   lastErrorIndex+\", states=\"+lastErrorStates);\n//\t\t\terrPrint(\"FAILSAFE consumes \"+recognizer.getTokenNames()[getTokenStream(recognizer).LA(1)]);\n            try recognizer.consume()\n        }\n        lastErrorIndex = getTokenStream(recognizer).index()\n        if lastErrorStates == nil {\n            lastErrorStates = IntervalSet()\n        }\n        try lastErrorStates!.add(recognizer.getState())\n        let followSet = getErrorRecoverySet(recognizer)\n        try consumeUntil(recognizer, followSet)\n    }\n\n    /// \n    /// The default implementation of _org.antlr.v4.runtime.ANTLRErrorStrategy#sync_ makes sure\n    /// that the current lookahead symbol is consistent with what were expecting\n    /// at this point in the ATN. You can call this anytime but ANTLR only\n    /// generates code to check before subrules/loops and each iteration.\n    /// \n    /// Implements Jim Idle's magic sync mechanism in closures and optional\n    /// subrules. E.g.,\n    /// \n    /// \n    /// a : sync ( stuff sync )* ;\n    /// sync : {consume to what can follow sync} ;\n    /// \n    /// \n    /// At the start of a sub rule upon error, _#sync_ performs single\n    /// token deletion, if possible. If it can't do that, it bails on the current\n    /// rule and uses the default error recovery, which consumes until the\n    /// resynchronization set of the current rule.\n    /// \n    /// If the sub rule is optional (`(...)?`, `(...)*`, or block\n    /// with an empty alternative), then the expected set includes what follows\n    /// the subrule.\n    /// \n    /// During loop iteration, it consumes until it sees a token that can start a\n    /// sub rule or what follows loop. Yes, that is pretty aggressive. We opt to\n    /// stay in the loop as long as possible.\n    /// \n    /// __ORIGINS__\n    /// \n    /// Previous versions of ANTLR did a poor job of their recovery within loops.\n    /// A single mismatch token or missing token would force the parser to bail\n    /// out of the entire rules surrounding the loop. So, for rule\n    /// \n    /// \n    /// classDef : 'class' ID '{' member* '}'\n    /// \n    /// \n    /// input with an extra token between members would force the parser to\n    /// consume until it found the next class definition rather than the next\n    /// member definition of the current class.\n    /// \n    /// This functionality cost a little bit of effort because the parser has to\n    /// compare token set at the start of the loop and at each iteration. If for\n    /// some reason speed is suffering for you, you can turn off this\n    /// functionality by simply overriding this method as a blank { }.\n    /// \n\n    open func sync(_ recognizer: Parser) throws {\n        let s = recognizer.getInterpreter().atn.states[recognizer.getState()]!\n//\t\terrPrint(\"sync @ \"+s.stateNumber+\"=\"+s.getClass().getSimpleName());\n        // If already recovering, don't try to sync\n        if inErrorRecoveryMode(recognizer) {\n            return\n        }\n\n        let tokens = getTokenStream(recognizer)\n        let la = try tokens.LA(1)\n\n        // try cheaper subset first; might get lucky. seems to shave a wee bit off\n        let nextToks = recognizer.getATN().nextTokens(s)\n        if nextToks.contains(la) {\n            // We are sure the token matches\n            nextTokensContext = nil\n            nextTokensState = ATNState.INVALID_STATE_NUMBER\n            return\n        }\n\n        if nextToks.contains(CommonToken.EPSILON) {\n            if nextTokensContext == nil {\n                    // It's possible the next token won't match; information tracked\n                    // by sync is restricted for performance.\n                    nextTokensContext = recognizer.getContext()\n                    nextTokensState = recognizer.getState()\n            }\n            return\n        }\n\n        switch s.getStateType() {\n        case ATNState.BLOCK_START: fallthrough\n        case ATNState.STAR_BLOCK_START: fallthrough\n        case ATNState.PLUS_BLOCK_START: fallthrough\n        case ATNState.STAR_LOOP_ENTRY:\n            // report error and recover if possible\n            if try singleTokenDeletion(recognizer) != nil {\n                return\n            }\n            throw ANTLRException.recognition(e: InputMismatchException(recognizer))\n\n        case ATNState.PLUS_LOOP_BACK: fallthrough\n        case ATNState.STAR_LOOP_BACK:\n//\t\t\terrPrint(\"at loop back: \"+s.getClass().getSimpleName());\n            reportUnwantedToken(recognizer)\n            let expecting = try recognizer.getExpectedTokens()\n            let whatFollowsLoopIterationOrRule = expecting.or(getErrorRecoverySet(recognizer)) as! IntervalSet\n            try consumeUntil(recognizer, whatFollowsLoopIterationOrRule)\n            break\n\n        default:\n            // do nothing if we can't identify the exact kind of ATN state\n            break\n        }\n    }\n\n    /// \n    /// This is called by _#reportError_ when the exception is a\n    /// _org.antlr.v4.runtime.NoViableAltException_.\n    /// \n    /// - seealso: #reportError\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter e: the recognition exception\n    /// \n    open func reportNoViableAlternative(_ recognizer: Parser, _ e: NoViableAltException) {\n        let tokens = getTokenStream(recognizer)\n        var input: String\n        if e.getStartToken().getType() == CommonToken.EOF {\n            input = \"<EOF>\"\n        }\n        else {\n            do {\n                input = try tokens.getText(e.getStartToken(), e.getOffendingToken())\n            }\n            catch {\n                input = \"<unknown>\"\n            }\n        }\n        let msg = \"no viable alternative at input \" + escapeWSAndQuote(input)\n        recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)\n    }\n\n    /// \n    /// This is called by _#reportError_ when the exception is an\n    /// _org.antlr.v4.runtime.InputMismatchException_.\n    /// \n    /// - seealso: #reportError\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter e: the recognition exception\n    /// \n    open func reportInputMismatch(_ recognizer: Parser, _ e: InputMismatchException) {\n        let tok = getTokenErrorDisplay(e.getOffendingToken())\n        let expected = e.getExpectedTokens()?.toString(recognizer.getVocabulary()) ?? \"<missing>\"\n        let msg = \"mismatched input \\(tok) expecting \\(expected)\"\n        recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)\n    }\n\n    /// \n    /// This is called by _#reportError_ when the exception is a\n    /// _org.antlr.v4.runtime.FailedPredicateException_.\n    /// \n    /// - seealso: #reportError\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - parameter e: the recognition exception\n    /// \n    open func reportFailedPredicate(_ recognizer: Parser, _ e: FailedPredicateException) {\n        let ruleName = recognizer.getRuleNames()[recognizer._ctx!.getRuleIndex()]\n        let msg = \"rule \\(ruleName) \\(e.message!)\"\n        recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)\n    }\n\n    /// \n    /// This method is called to report a syntax error which requires the removal\n    /// of a token from the input stream. At the time this method is called, the\n    /// erroneous symbol is current `LT(1)` symbol and has not yet been\n    /// removed from the input stream. When this method returns,\n    /// `recognizer` is in error recovery mode.\n    /// \n    /// This method is called when _#singleTokenDeletion_ identifies\n    /// single-token deletion as a viable recovery strategy for a mismatched\n    /// input error.\n    /// \n    /// The default implementation simply returns if the handler is already in\n    /// error recovery mode. Otherwise, it calls _#beginErrorCondition_ to\n    /// enter error recovery mode, followed by calling\n    /// _org.antlr.v4.runtime.Parser#notifyErrorListeners_.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// \n    open func reportUnwantedToken(_ recognizer: Parser) {\n        if inErrorRecoveryMode(recognizer) {\n            return\n        }\n\n        beginErrorCondition(recognizer)\n\n        let t = try? recognizer.getCurrentToken()\n        let tokenName = getTokenErrorDisplay(t)\n        let expecting = (try? getExpectedTokens(recognizer)) ?? IntervalSet.EMPTY_SET\n        let msg = \"extraneous input \\(tokenName) expecting \\(expecting.toString(recognizer.getVocabulary()))\"\n        recognizer.notifyErrorListeners(t, msg, nil)\n    }\n\n    /// \n    /// This method is called to report a syntax error which requires the\n    /// insertion of a missing token into the input stream. At the time this\n    /// method is called, the missing token has not yet been inserted. When this\n    /// method returns, `recognizer` is in error recovery mode.\n    /// \n    /// This method is called when _#singleTokenInsertion_ identifies\n    /// single-token insertion as a viable recovery strategy for a mismatched\n    /// input error.\n    /// \n    /// The default implementation simply returns if the handler is already in\n    /// error recovery mode. Otherwise, it calls _#beginErrorCondition_ to\n    /// enter error recovery mode, followed by calling\n    /// _org.antlr.v4.runtime.Parser#notifyErrorListeners_.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// \n    open func reportMissingToken(_ recognizer: Parser) {\n        if inErrorRecoveryMode(recognizer) {\n            return\n        }\n\n        beginErrorCondition(recognizer)\n\n        let t = try? recognizer.getCurrentToken()\n        let expecting = (try? getExpectedTokens(recognizer)) ?? IntervalSet.EMPTY_SET\n        let msg = \"missing \\(expecting.toString(recognizer.getVocabulary())) at \\(getTokenErrorDisplay(t))\"\n\n        recognizer.notifyErrorListeners(t, msg, nil)\n    }\n\n    /// \n    /// \n    /// \n    /// The default implementation attempts to recover from the mismatched input\n    /// by using single token insertion and deletion as described below. If the\n    /// recovery attempt fails, this method throws an\n    /// _org.antlr.v4.runtime.InputMismatchException_.\n    /// \n    /// __EXTRA TOKEN__ (single token deletion)\n    /// \n    /// `LA(1)` is not what we are looking for. If `LA(2)` has the\n    /// right token, however, then assume `LA(1)` is some extra spurious\n    /// token and delete it. Then consume and return the next token (which was\n    /// the `LA(2)` token) as the successful result of the match operation.\n    /// \n    /// This recovery strategy is implemented by _#singleTokenDeletion_.\n    /// \n    /// __MISSING TOKEN__ (single token insertion)\n    /// \n    /// If current token (at `LA(1)`) is consistent with what could come\n    /// after the expected `LA(1)` token, then assume the token is missing\n    /// and use the parser's _org.antlr.v4.runtime.TokenFactory_ to create it on the fly. The\n    /// \"insertion\" is performed by returning the created token as the successful\n    /// result of the match operation.\n    /// \n    /// This recovery strategy is implemented by _#singleTokenInsertion_.\n    /// \n    /// __EXAMPLE__\n    /// \n    /// For example, Input `i=(3;` is clearly missing the `')'`. When\n    /// the parser returns from the nested call to `expr`, it will have\n    /// call chain:\n    /// \n    /// \n    /// stat &rarr; expr &rarr; atom\n    /// \n    /// \n    /// and it will be trying to match the `')'` at this point in the\n    /// derivation:\n    /// \n    /// \n    /// =&gt; ID '=' '(' INT ')' ('+' atom)* ';'\n    /// ^\n    /// \n    /// \n    /// The attempt to match `')'` will fail when it sees `';'` and\n    /// call _#recoverInline_. To recover, it sees that `LA(1)==';'`\n    /// is in the set of tokens that can follow the `')'` token reference\n    /// in rule `atom`. It can assume that you forgot the `')'`.\n    /// \n\n    open func recoverInline(_ recognizer: Parser) throws -> Token {\n        // SINGLE TOKEN DELETION\n        let matchedSymbol = try singleTokenDeletion(recognizer)\n        if let matchedSymbol = matchedSymbol {\n            // we have deleted the extra token.\n            // now, move past ttype token as if all were ok\n            try recognizer.consume()\n            return matchedSymbol\n        }\n\n        // SINGLE TOKEN INSERTION\n        if try singleTokenInsertion(recognizer) {\n            return try getMissingSymbol(recognizer)\n        }\n        // even that didn't work; must throw the exception\n        let exn = InputMismatchException(recognizer, state: nextTokensState, ctx: nextTokensContext)\n        throw ANTLRException.recognition(e: exn)\n    }\n\n    /// \n    /// This method implements the single-token insertion inline error recovery\n    /// strategy. It is called by _#recoverInline_ if the single-token\n    /// deletion strategy fails to recover from the mismatched input. If this\n    /// method returns `true`, `recognizer` will be in error recovery\n    /// mode.\n    /// \n    /// This method determines whether or not single-token insertion is viable by\n    /// checking if the `LA(1)` input symbol could be successfully matched\n    /// if it were instead the `LA(2)` symbol. If this method returns\n    /// `true`, the caller is responsible for creating and inserting a\n    /// token with the correct type to produce this behavior.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - returns: `true` if single-token insertion is a viable recovery\n    /// strategy for the current mismatched input, otherwise `false`\n    /// \n    open func singleTokenInsertion(_ recognizer: Parser) throws -> Bool {\n        let currentSymbolType = try getTokenStream(recognizer).LA(1)\n        // if current token is consistent with what could come after current\n        // ATN state, then we know we're missing a token; error recovery\n        // is free to conjure up and insert the missing token\n        let currentState = recognizer.getInterpreter().atn.states[recognizer.getState()]!\n        let next = currentState.transition(0).target\n        let atn = recognizer.getInterpreter().atn\n        let expectingAtLL2 = atn.nextTokens(next, recognizer._ctx)\n//\t\tprint(\"LT(2) set=\"+expectingAtLL2.toString(recognizer.getTokenNames()));\n        if expectingAtLL2.contains(currentSymbolType) {\n            reportMissingToken(recognizer)\n            return true\n        }\n        return false\n    }\n\n    /// \n    /// This method implements the single-token deletion inline error recovery\n    /// strategy. It is called by _#recoverInline_ to attempt to recover\n    /// from mismatched input. If this method returns null, the parser and error\n    /// handler state will not have changed. If this method returns non-null,\n    /// `recognizer` will __not__ be in error recovery mode since the\n    /// returned token was a successful match.\n    /// \n    /// If the single-token deletion is successful, this method calls\n    /// _#reportUnwantedToken_ to report the error, followed by\n    /// _org.antlr.v4.runtime.Parser#consume_ to actually \"delete\" the extraneous token. Then,\n    /// before returning _#reportMatch_ is called to signal a successful\n    /// match.\n    /// \n    /// - parameter recognizer: the parser instance\n    /// - returns: the successfully matched _org.antlr.v4.runtime.Token_ instance if single-token\n    /// deletion successfully recovers from the mismatched input, otherwise\n    /// `null`\n    /// \n    open func singleTokenDeletion(_ recognizer: Parser) throws -> Token? {\n        let nextTokenType = try getTokenStream(recognizer).LA(2)\n        let expecting = try getExpectedTokens(recognizer)\n        if expecting.contains(nextTokenType) {\n            reportUnwantedToken(recognizer)\n            /// \n            /// errPrint(\"recoverFromMismatchedToken deleting \"+\n            /// ((TokenStream)getTokenStream(recognizer)).LT(1)+\n            /// \" since \"+((TokenStream)getTokenStream(recognizer)).LT(2)+\n            /// \" is what we want\");\n            /// \n            try recognizer.consume() // simply delete extra token\n            // we want to return the token we're actually matching\n            let matchedSymbol = try recognizer.getCurrentToken()\n            reportMatch(recognizer)  // we know current token is correct\n            return matchedSymbol\n        }\n        return nil\n    }\n\n    /// \n    /// Conjure up a missing token during error recovery.\n    /// \n    /// The recognizer attempts to recover from single missing\n    /// symbols. But, actions might refer to that missing symbol.\n    /// For example, x=ID {f($x);}. The action clearly assumes\n    /// that there has been an identifier matched previously and that\n    /// $x points at that token. If that token is missing, but\n    /// the next token in the stream is what we want we assume that\n    /// this token is missing and we keep going. Because we\n    /// have to return some token to replace the missing token,\n    /// we have to conjure one up. This method gives the user control\n    /// over the tokens returned for missing tokens. Mostly,\n    /// you will want to create something special for identifier\n    /// tokens. For literals such as '{' and ',', the default\n    /// action in the parser or tree parser works. It simply creates\n    /// a CommonToken of the appropriate type. The text will be the token.\n    /// If you change what tokens must be created by the lexer,\n    /// override this method to create the appropriate tokens.\n    /// \n    open func getTokenStream(_ recognizer: Parser) -> TokenStream {\n        return recognizer.getInputStream() as! TokenStream\n    }\n\n    open func getMissingSymbol(_ recognizer: Parser) throws -> Token {\n        let currentSymbol = try recognizer.getCurrentToken()\n        let expecting = try getExpectedTokens(recognizer)\n        let expectedTokenType = expecting.getMinElement() // get any element\n        var tokenText: String\n        if expectedTokenType == CommonToken.EOF {\n            tokenText = \"<missing EOF>\"\n        } else {\n            tokenText = \"<missing \" + recognizer.getVocabulary().getDisplayName(expectedTokenType) + \">\"\n        }\n        var current = currentSymbol\n        let lookback = try getTokenStream(recognizer).LT(-1)\n        if current.getType() == CommonToken.EOF && lookback != nil {\n            current = lookback!\n        }\n\n        let token = recognizer.getTokenFactory().create(\n            current.getTokenSourceAndStream(),\n            expectedTokenType, tokenText,\n            CommonToken.DEFAULT_CHANNEL,\n            -1, -1,\n            current.getLine(), current.getCharPositionInLine())\n\n        return token\n    }\n\n\n    open func getExpectedTokens(_ recognizer: Parser) throws -> IntervalSet {\n        return try recognizer.getExpectedTokens()\n    }\n\n    /// \n    /// How should a token be displayed in an error message? The default\n    /// is to display just the text, but during development you might\n    /// want to have a lot of information spit out.  Override in that case\n    /// to use t.toString() (which, for CommonToken, dumps everything about\n    /// the token). This is better than forcing you to override a method in\n    /// your token objects because you don't have to go modify your lexer\n    /// so that it creates a new Java type.\n    /// \n    open func getTokenErrorDisplay(_ t: Token?) -> String {\n        guard let t = t else {\n            return \"<no token>\"\n        }\n        var s = getSymbolText(t)\n        if s == nil {\n            if getSymbolType(t) == CommonToken.EOF {\n                s = \"<EOF>\"\n            } else {\n                s = \"<\\(getSymbolType(t))>\"\n            }\n        }\n        return escapeWSAndQuote(s!)\n    }\n\n    open func getSymbolText(_ symbol: Token) -> String? {\n        return symbol.getText()\n    }\n\n    open func getSymbolType(_ symbol: Token) -> Int {\n        return symbol.getType()\n    }\n\n\n    open func escapeWSAndQuote(_ s: String) -> String {\n        var s = s\n        s = s.replacingOccurrences(of: \"\\n\", with: \"\\\\n\")\n        s = s.replacingOccurrences(of: \"\\r\", with: \"\\\\r\")\n        s = s.replacingOccurrences(of: \"\\t\", with: \"\\\\t\")\n        return \"'\" + s + \"'\"\n    }\n\n    /// \n    /// Compute the error recovery set for the current rule.  During\n    /// rule invocation, the parser pushes the set of tokens that can\n    /// follow that rule reference on the stack; this amounts to\n    /// computing FIRST of what follows the rule reference in the\n    /// enclosing rule. See LinearApproximator.FIRST().\n    /// This local follow set only includes tokens\n    /// from within the rule; i.e., the FIRST computation done by\n    /// ANTLR stops at the end of a rule.\n    /// \n    /// EXAMPLE\n    /// \n    /// When you find a \"no viable alt exception\", the input is not\n    /// consistent with any of the alternatives for rule r.  The best\n    /// thing to do is to consume tokens until you see something that\n    /// can legally follow a call to r *or* any rule that called r.\n    /// You don't want the exact set of viable next tokens because the\n    /// input might just be missing a token--you might consume the\n    /// rest of the input looking for one of the missing tokens.\n    /// \n    /// Consider grammar:\n    /// \n    /// a : '[' b ']'\n    /// | '(' b ')'\n    /// ;\n    /// b : c '^' INT ;\n    /// c : ID\n    /// | INT\n    /// ;\n    /// \n    /// At each rule invocation, the set of tokens that could follow\n    /// that rule is pushed on a stack.  Here are the various\n    /// context-sensitive follow sets:\n    /// \n    /// FOLLOW(b1_in_a) = FIRST(']') = ']'\n    /// FOLLOW(b2_in_a) = FIRST(')') = ')'\n    /// FOLLOW(c_in_b) = FIRST('^') = '^'\n    /// \n    /// Upon erroneous input \"[]\", the call chain is\n    /// \n    /// a -> b -> c\n    /// \n    /// and, hence, the follow context stack is:\n    /// \n    /// depth     follow set       start of rule execution\n    /// 0         <EOF>                    a (from main())\n    /// 1          ']'                     b\n    /// 2          '^'                     c\n    /// \n    /// Notice that ')' is not included, because b would have to have\n    /// been called from a different context in rule a for ')' to be\n    /// included.\n    /// \n    /// For error recovery, we cannot consider FOLLOW(c)\n    /// (context-sensitive or otherwise).  We need the combined set of\n    /// all context-sensitive FOLLOW sets--the set of all tokens that\n    /// could follow any reference in the call chain.  We need to\n    /// resync to one of those tokens.  Note that FOLLOW(c)='^' and if\n    /// we resync'd to that token, we'd consume until EOF.  We need to\n    /// sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.\n    /// In this case, for input \"[]\", LA(1) is ']' and in the set, so we would\n    /// not consume anything. After printing an error, rule c would\n    /// return normally.  Rule b would not find the required '^' though.\n    /// At this point, it gets a mismatched token error and throws an\n    /// exception (since LA(1) is not in the viable following token\n    /// set).  The rule exception handler tries to recover, but finds\n    /// the same recovery set and doesn't consume anything.  Rule b\n    /// exits normally returning to rule a.  Now it finds the ']' (and\n    /// with the successful match exits errorRecovery mode).\n    /// \n    /// So, you can see that the parser walks up the call chain looking\n    /// for the token that was a member of the recovery set.\n    /// \n    /// Errors are not generated in errorRecovery mode.\n    /// \n    /// ANTLR's error recovery mechanism is based upon original ideas:\n    /// \n    /// \"Algorithms + Data Structures = Programs\" by Niklaus Wirth\n    /// \n    /// and\n    /// \n    /// \"A note on error recovery in recursive descent parsers\":\n    /// http://portal.acm.org/citation.cfm?id=947902.947905\n    /// \n    /// Later, Josef Grosch had some good ideas:\n    /// \n    /// \"Efficient and Comfortable Error Recovery in Recursive Descent\n    /// Parsers\":\n    /// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip\n    /// \n    /// Like Grosch I implement context-sensitive FOLLOW sets that are combined\n    /// at run-time upon error to avoid overhead during parsing.\n    /// \n    open func getErrorRecoverySet(_ recognizer: Parser) -> IntervalSet {\n        let atn = recognizer.getInterpreter().atn\n        var ctx: RuleContext? = recognizer._ctx\n        let recoverSet = IntervalSet()\n        while let ctxWrap = ctx, ctxWrap.invokingState >= 0 {\n            // compute what follows who invoked us\n            let invokingState = atn.states[ctxWrap.invokingState]!\n            let rt = invokingState.transition(0) as! RuleTransition\n            let follow = atn.nextTokens(rt.followState)\n            try! recoverSet.addAll(follow)\n            ctx = ctxWrap.parent\n        }\n        try! recoverSet.remove(CommonToken.EPSILON)\n//\t\tprint(\"recover set \"+recoverSet.toString(recognizer.getTokenNames()));\n        return recoverSet\n    }\n\n    /// \n    /// Consume tokens until one matches the given token set.\n    /// \n    open func consumeUntil(_ recognizer: Parser, _ set: IntervalSet) throws {\n//\t\terrPrint(\"consumeUntil(\"+set.toString(recognizer.getTokenNames())+\")\");\n        var ttype = try getTokenStream(recognizer).LA(1)\n        while ttype != CommonToken.EOF && !set.contains(ttype) {\n            //print(\"consume during recover LA(1)=\"+getTokenNames()[input.LA(1)]);\n            try recognizer.consume()\n            ttype = try getTokenStream(recognizer).LA(1)\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/DiagnosticErrorListener.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// This implementation of _org.antlr.v4.runtime.ANTLRErrorListener_ can be used to identify\n/// certain potential correctness and performance problems in grammars. \"Reports\"\n/// are made by calling _org.antlr.v4.runtime.Parser#notifyErrorListeners_ with the appropriate\n/// message.\n/// \n/// * __Ambiguities__: These are cases where more than one path through the\n/// grammar can match the input.\n/// * __Weak context sensitivity__: These are cases where full-context\n/// prediction resolved an SLL conflict to a unique alternative which equaled the\n/// minimum alternative of the SLL conflict.\n/// * __Strong (forced) context sensitivity__: These are cases where the\n/// full-context prediction resolved an SLL conflict to a unique alternative,\n/// __and__ the minimum alternative of the SLL conflict was found to not be\n/// a truly viable alternative. Two-stage parsing cannot be used for inputs where\n/// this situation occurs.\n/// \n/// -  Sam Harwell\n/// \n\nimport Foundation\n\npublic class DiagnosticErrorListener: BaseErrorListener {\n    /// \n    /// When `true`, only exactly known ambiguities are reported.\n    /// \n    internal final var exactOnly: Bool\n\n    /// \n    /// Initializes a new instance of _org.antlr.v4.runtime.DiagnosticErrorListener_ which only\n    /// reports exact ambiguities.\n    /// \n    public convenience override init() {\n        self.init(true)\n    }\n\n    /// \n    /// Initializes a new instance of _org.antlr.v4.runtime.DiagnosticErrorListener_, specifying\n    /// whether all ambiguities or only exact ambiguities are reported.\n    /// \n    /// - parameter exactOnly: `true` to report only exact ambiguities, otherwise\n    /// `false` to report all ambiguities.\n    /// \n    public init(_ exactOnly: Bool) {\n        self.exactOnly = exactOnly\n    }\n\n    override\n    public func reportAmbiguity(_ recognizer: Parser,\n        _ dfa: DFA,\n        _ startIndex: Int,\n        _ stopIndex: Int,\n        _ exact: Bool,\n        _ ambigAlts: BitSet,\n        _ configs: ATNConfigSet) {\n            if exactOnly && !exact {\n                return\n            }\n\n            let decision = getDecisionDescription(recognizer, dfa)\n            let conflictingAlts = getConflictingAlts(ambigAlts, configs)\n            let text = getTextInInterval(recognizer, startIndex, stopIndex)\n            let message = \"reportAmbiguity d=\\(decision): ambigAlts=\\(conflictingAlts), input='\\(text)'\"\n            recognizer.notifyErrorListeners(message)\n    }\n\n    override\n    public func reportAttemptingFullContext(_ recognizer: Parser,\n        _ dfa: DFA,\n        _ startIndex: Int,\n        _ stopIndex: Int,\n        _ conflictingAlts: BitSet?,\n        _ configs: ATNConfigSet) {\n            let decision = getDecisionDescription(recognizer, dfa)\n            let text = getTextInInterval(recognizer, startIndex, stopIndex)\n            let message = \"reportAttemptingFullContext d=\\(decision), input='\\(text)'\"\n            recognizer.notifyErrorListeners(message)\n    }\n\n    override\n    public func reportContextSensitivity(_ recognizer: Parser,\n        _ dfa: DFA,\n        _ startIndex: Int,\n        _ stopIndex: Int,\n        _ prediction: Int,\n        _ configs: ATNConfigSet) {\n            let decision = getDecisionDescription(recognizer, dfa)\n            let text = getTextInInterval(recognizer, startIndex, stopIndex)\n            let message = \"reportContextSensitivity d=\\(decision), input='\\(text)'\"\n            recognizer.notifyErrorListeners(message)\n    }\n\n    internal func getDecisionDescription(_ recognizer: Parser, _ dfa: DFA) -> String {\n        let decision: Int = dfa.decision\n        let ruleIndex: Int = dfa.atnStartState.ruleIndex!\n\n        let ruleNames: [String] = recognizer.getRuleNames()\n        guard ruleNames.indices.contains(ruleIndex) else {\n            return String(decision)\n        }\n\n        let ruleName: String = ruleNames[ruleIndex]\n        //if (ruleName == nil || ruleName.isEmpty()) {\n        if ruleName.isEmpty {\n            return String(decision)\n        }\n        return \"\\(decision) (\\(ruleName))\"\n    }\n\n    /// \n    /// Computes the set of conflicting or ambiguous alternatives from a\n    /// configuration set, if that information was not already provided by the\n    /// parser.\n    /// \n    /// - parameter reportedAlts: The set of conflicting or ambiguous alternatives, as\n    /// reported by the parser.\n    /// - parameter configs: The conflicting or ambiguous configuration set.\n    /// - returns: Returns `reportedAlts` if it is not `null`, otherwise\n    /// returns the set of alternatives represented in `configs`.\n    /// \n    internal func getConflictingAlts(_ reportedAlts: BitSet?, _ configs: ATNConfigSet) -> BitSet {\n        return reportedAlts ?? configs.getAltBitSet()\n    }\n}\n\n\nfileprivate func getTextInInterval(_ recognizer: Parser, _ startIndex: Int, _ stopIndex: Int) -> String {\n    do {\n        return try recognizer.getTokenStream()?.getText(Interval.of(startIndex, stopIndex)) ?? \"<unknown>\"\n    }\n    catch {\n        return \"<unknown>\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/FailedPredicateException.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// A semantic predicate failed during validation.  Validation of predicates\n/// occurs when normally parsing the alternative just like matching a token.\n/// Disambiguating predicate evaluation occurs when we test a predicate during\n/// prediction.\n/// \npublic class FailedPredicateException: RecognitionException {\n\tprivate let ruleIndex: Int\n\tprivate let predicateIndex: Int\n\tprivate let predicate: String?\n\n\tpublic init(_ recognizer: Parser, _ predicate: String? = nil, _ message: String? = nil) {\n\t\tlet s = recognizer.getInterpreter().atn.states[recognizer.getState()]!\n\n\t\tlet trans = s.transition(0) as! AbstractPredicateTransition\n\t\tif let predex = trans as? PredicateTransition {\n\t\t\tself.ruleIndex = predex.ruleIndex\n\t\t\tself.predicateIndex = predex.predIndex\n\t\t}\n\t\telse {\n\t\t\tself.ruleIndex = 0\n\t\t\tself.predicateIndex = 0\n\t\t}\n\n\t\tself.predicate = predicate\n\n        super.init(recognizer, recognizer.getInputStream()!, recognizer._ctx, FailedPredicateException.formatMessage(predicate, message))\n        if let token = try? recognizer.getCurrentToken() {\n            setOffendingToken(token)\n        }\n\t}\n\n\tpublic func getRuleIndex() -> Int {\n\t\treturn ruleIndex\n\t}\n\n\tpublic func getPredIndex() -> Int {\n\t\treturn predicateIndex\n\t}\n\n\tpublic func getPredicate() -> String? {\n\t\treturn predicate\n\t}\n\n\n\tprivate static func formatMessage(_ predicate: String?, _ message: String?) -> String {\n\t\tif let message = message {\n\t\t\treturn message\n\t\t}\n\n        let predstr = predicate ?? \"<unknown>\"\n\t\treturn \"failed predicate: {\\(predstr)}?\"\n\t}\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/InputMismatchException.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// This signifies any kind of mismatched input exceptions such as\n/// when the current input does not match the expected token.\n/// \n\npublic class InputMismatchException: RecognitionException {\n    public init(_ recognizer: Parser, state: Int = ATNState.INVALID_STATE_NUMBER, ctx: ParserRuleContext? = nil) {\n        let bestCtx = ctx ?? recognizer._ctx\n\n        super.init(recognizer, recognizer.getInputStream()!, bestCtx)\n\n        if let token = try? recognizer.getCurrentToken() {\n            setOffendingToken(token)\n        }\n        if (state != ATNState.INVALID_STATE_NUMBER) {\n            setOffendingState(state)\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/IntStream.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// A simple stream of symbols whose values are represented as integers. This\n/// interface provides __marked ranges__ with support for a minimum level\n/// of buffering necessary to implement arbitrary lookahead during prediction.\n/// For more information on marked ranges, see _#mark_.\n/// \n/// __Initializing Methods:__ Some methods in this interface have\n/// unspecified behavior if no call to an initializing method has occurred after\n/// the stream was constructed. The following is a list of initializing methods:\n/// \n/// * _#LA_\n/// * _#consume_\n/// * _#size_\n/// \npublic protocol IntStream: AnyObject {\n\n    /// \n    /// Consumes the current symbol in the stream. This method has the following\n    /// effects:\n    /// \n    /// * __Forward movement:__ The value of _#index index()_\n    /// before calling this method is less than the value of `index()`\n    /// after calling this method.\n    /// * __Ordered lookahead:__ The value of `LA(1)` before\n    /// calling this method becomes the value of `LA(-1)` after calling\n    /// this method.\n    /// \n    /// Note that calling this method does not guarantee that `index()` is\n    /// incremented by exactly 1, as that would preclude the ability to implement\n    /// filtering streams (e.g. _org.antlr.v4.runtime.CommonTokenStream_ which distinguishes\n    /// between \"on-channel\" and \"off-channel\" tokens).\n    /// \n    /// - throws: _ANTLRError.illegalState_ if an attempt is made to consume the the\n    /// end of the stream (i.e. if `LA(1)==`_#EOF EOF_ before calling\n    /// `consume`).\n    /// \n    func consume() throws\n\n    /// \n    /// Gets the value of the symbol at offset `i` from the current\n    /// position. When `i==1`, this method returns the value of the current\n    /// symbol in the stream (which is the next symbol to be consumed). When\n    /// `i==-1`, this method returns the value of the previously read\n    /// symbol in the stream. It is not valid to call this method with\n    /// `i==0`, but the specific behavior is unspecified because this\n    /// method is frequently called from performance-critical code.\n    /// \n    /// This method is guaranteed to succeed if any of the following are true:\n    /// \n    /// * `i>0`\n    /// * `i==-1` and _#index index()_ returns a value greater\n    /// than the value of `index()` after the stream was constructed\n    /// and `LA(1)` was called in that order. Specifying the current\n    /// `index()` relative to the index after the stream was created\n    /// allows for filtering implementations that do not return every symbol\n    /// from the underlying source. Specifying the call to `LA(1)`\n    /// allows for lazily initialized streams.\n    /// * `LA(i)` refers to a symbol consumed within a marked region\n    /// that has not yet been released.\n    /// \n    /// If `i` represents a position at or beyond the end of the stream,\n    /// this method returns _#EOF_.\n    /// \n    /// The return value is unspecified if `i<0` and fewer than `-i`\n    /// calls to _#consume consume()_ have occurred from the beginning of\n    /// the stream before calling this method.\n    /// \n    /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support\n    /// retrieving the value of the specified symbol\n    /// \n    func LA(_ i: Int) throws -> Int\n\n    /// \n    /// A mark provides a guarantee that _#seek seek()_ operations will be\n    /// valid over a \"marked range\" extending from the index where `mark()`\n    /// was called to the current _#index index()_. This allows the use of\n    /// streaming input sources by specifying the minimum buffering requirements\n    /// to support arbitrary lookahead during prediction.\n    /// \n    /// The returned mark is an opaque handle (type `int`) which is passed\n    /// to _#release release()_ when the guarantees provided by the marked\n    /// range are no longer necessary. When calls to\n    /// `mark()`/`release()` are nested, the marks must be released\n    /// in reverse order of which they were obtained. Since marked regions are\n    /// used during performance-critical sections of prediction, the specific\n    /// behavior of invalid usage is unspecified (i.e. a mark is not released, or\n    /// a mark is released twice, or marks are not released in reverse order from\n    /// which they were created).\n    /// \n    /// The behavior of this method is unspecified if no call to an\n    /// _org.antlr.v4.runtime.IntStream initializing method_ has occurred after this stream was\n    /// constructed.\n    /// \n    /// This method does not change the current position in the input stream.\n    /// \n    /// The following example shows the use of _#mark mark()_,\n    /// _#release release(mark)_, _#index index()_, and\n    /// _#seek seek(index)_ as part of an operation to safely work within a\n    /// marked region, then restore the stream position to its original value and\n    /// release the mark.\n    /// \n    /// IntStream stream = ...;\n    /// int index = -1;\n    /// int mark = stream.mark();\n    /// try {\n    /// index = stream.index();\n    /// // perform work here...\n    /// } finally {\n    /// if (index != -1) {\n    /// stream.seek(index);\n    /// }\n    /// stream.release(mark);\n    /// }\n    /// \n    /// \n    /// - returns: An opaque marker which should be passed to\n    /// _#release release()_ when the marked range is no longer required.\n    /// \n    func mark() -> Int\n\n    /// \n    /// This method releases a marked range created by a call to\n    /// _#mark mark()_. Calls to `release()` must appear in the\n    /// reverse order of the corresponding calls to `mark()`. If a mark is\n    /// released twice, or if marks are not released in reverse order of the\n    /// corresponding calls to `mark()`, the behavior is unspecified.\n    /// \n    /// For more information and an example, see _#mark_.\n    /// \n    /// - parameter marker: A marker returned by a call to `mark()`.\n    /// - seealso: #mark\n    /// \n    func release(_ marker: Int) throws\n\n    /// \n    /// Return the index into the stream of the input symbol referred to by\n    /// `LA(1)`.\n    /// \n    /// The behavior of this method is unspecified if no call to an\n    /// _org.antlr.v4.runtime.IntStream initializing method_ has occurred after this stream was\n    /// constructed.\n    /// \n    func index() -> Int\n\n    /// \n    /// Set the input cursor to the position indicated by `index`. If the\n    /// specified index lies past the end of the stream, the operation behaves as\n    /// though `index` was the index of the EOF symbol. After this method\n    /// returns without throwing an exception, then at least one of the following\n    /// will be true.\n    /// \n    /// * _#index index()_ will return the index of the first symbol\n    /// appearing at or after the specified `index`. Specifically,\n    /// implementations which filter their sources should automatically\n    /// adjust `index` forward the minimum amount required for the\n    /// operation to target a non-ignored symbol.\n    /// * `LA(1)` returns _#EOF_\n    /// \n    /// This operation is guaranteed to not throw an exception if `index`\n    /// lies within a marked region. For more information on marked regions, see\n    /// _#mark_. The behavior of this method is unspecified if no call to\n    /// an _org.antlr.v4.runtime.IntStream initializing method_ has occurred after this stream\n    /// was constructed.\n    /// \n    /// - parameter index: The absolute index to seek to.\n    /// \n    /// - throws: _ANTLRError.illegalArgument_ if `index` is less than 0\n    /// - throws: _ANTLRError.unsupportedOperation_ if the stream does not support\n    /// seeking to the specified index\n    /// \n    func seek(_ index: Int) throws\n\n    /// \n    /// Returns the total number of symbols in the stream, including a single EOF\n    /// symbol.\n    /// \n    /// - throws: _ANTLRError.unsupportedOperation_ if the size of the stream is\n    /// unknown.\n    /// \n    func size() -> Int\n\n    /// \n    /// Gets the name of the underlying symbol source. This method returns a\n    /// non-null, non-empty string. If such a name is not known, this method\n    /// returns _#UNKNOWN_SOURCE_NAME_.\n    /// \n    func getSourceName() -> String\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/InterpreterRuleContext.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// This class extends _org.antlr.v4.runtime.ParserRuleContext_ by allowing the value of\n/// _#getRuleIndex_ to be explicitly set for the context.\n/// \n/// \n/// _org.antlr.v4.runtime.ParserRuleContext_ does not include field storage for the rule index\n/// since the context classes created by the code generator override the\n/// _#getRuleIndex_ method to return the correct value for that context.\n/// Since the parser interpreter does not use the context classes generated for a\n/// parser, this class (with slightly more memory overhead per node) is used to\n/// provide equivalent functionality.\n/// \n\npublic class InterpreterRuleContext: ParserRuleContext {\n    /// \n    /// This is the backing field for _#getRuleIndex_.\n    /// \n    private var ruleIndex: Int = -1\n\n    public override init() {\n        super.init()\n    }\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.InterpreterRuleContext_ with the specified\n    /// parent, invoking state, and rule index.\n    /// \n    /// - parameter parent: The parent context.\n    /// - parameter invokingStateNumber: The invoking state number.\n    /// - parameter ruleIndex: The rule index for the current context.\n    /// \n    public init(_ parent: ParserRuleContext?,\n                _ invokingStateNumber: Int,\n                _ ruleIndex: Int) {\n        self.ruleIndex = ruleIndex\n        super.init(parent, invokingStateNumber)\n\n    }\n\n    override\n    public func getRuleIndex() -> Int {\n        return ruleIndex\n    }\n\n    /// \n    /// Copy a _org.antlr.v4.runtime.ParserRuleContext_ or _org.antlr.v4.runtime.InterpreterRuleContext_\n    /// stack to a _org.antlr.v4.runtime.InterpreterRuleContext_ tree.\n    /// Return _null_ if `ctx` is null.\n    /// \n    public static func fromParserRuleContext(_ ctx: ParserRuleContext?) -> InterpreterRuleContext? {\n        guard let ctx = ctx else {\n             return nil\n        }\n        let dup: InterpreterRuleContext = InterpreterRuleContext()\n        dup.copyFrom(ctx)\n        dup.ruleIndex = ctx.getRuleIndex()\n        dup.parent = fromParserRuleContext(ctx.getParent() as? ParserRuleContext)\n        return dup\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/Lexer.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// A lexer is recognizer that draws input symbols from a character stream.\n/// lexer grammars result in a subclass of this object. A Lexer object\n/// uses simplified match() and error recovery mechanisms in the interest\n/// of speed.\n/// \n\nimport Foundation\n\nopen class Lexer: Recognizer<LexerATNSimulator>, TokenSource {\n    public static let EOF = -1\n    public static let DEFAULT_MODE = 0\n    public static let MORE = -2\n    public static let SKIP = -3\n\n    public static let DEFAULT_TOKEN_CHANNEL = CommonToken.DEFAULT_CHANNEL\n    public static let HIDDEN = CommonToken.HIDDEN_CHANNEL\n    public static let MIN_CHAR_VALUE = Character.MIN_VALUE;\n    public static let MAX_CHAR_VALUE = Character.MAX_VALUE;\n\n    public var _input: CharStream?\n    internal var _tokenFactorySourcePair: TokenSourceAndStream\n\n    /// \n    /// How to create token objects\n    /// \n    internal var _factory = CommonTokenFactory.DEFAULT\n\n    /// \n    /// The goal of all lexer rules/methods is to create a token object.\n    /// This is an instance variable as multiple rules may collaborate to\n    /// create a single token.  nextToken will return this object after\n    /// matching lexer rule(s).  If you subclass to allow multiple token\n    /// emissions, then set this to the last token to be matched or\n    /// something nonnull so that the auto token emit mechanism will not\n    /// emit another token.\n    /// \n    public var _token: Token?\n\n    /// \n    /// What character index in the stream did the current token start at?\n    /// Needed, for example, to get the text for current token.  Set at\n    /// the start of nextToken.\n    /// \n    public var _tokenStartCharIndex = -1\n\n    /// \n    /// The line on which the first character of the token resides\n    /// \n    public var _tokenStartLine = 0\n\n    /// \n    /// The character position of first character within the line\n    /// \n    public var _tokenStartCharPositionInLine = 0\n\n    /// \n    /// Once we see EOF on char stream, next token will be EOF.\n    /// If you have DONE : EOF ; then you see DONE EOF.\n    /// \n    public var _hitEOF = false\n\n    /// \n    /// The channel number for the current token\n    /// \n    public var _channel = 0\n\n    /// \n    /// The token type for the current token\n    /// \n    public var _type = CommonToken.INVALID_TYPE\n\n    public final var _modeStack = Stack<Int>()\n    public var _mode = Lexer.DEFAULT_MODE\n\n    /// \n    /// You can set the text for the current token to override what is in\n    /// the input char buffer.  Use setText() or can set this instance var.\n    /// \n    public var _text: String?\n\n    public override init() {\n        self._tokenFactorySourcePair = TokenSourceAndStream()\n        super.init()\n        self._tokenFactorySourcePair.tokenSource = self\n    }\n\n    public required init(_ input: CharStream) {\n        self._input = input\n        self._tokenFactorySourcePair = TokenSourceAndStream()\n        super.init()\n        self._tokenFactorySourcePair.tokenSource = self\n        self._tokenFactorySourcePair.stream = input\n    }\n\n    open func reset() throws {\n        // wack Lexer state variables\n        if let _input = _input {\n            try  _input.seek(0) // rewind the input\n        }\n        _token = nil\n        _type = CommonToken.INVALID_TYPE\n        _channel = CommonToken.DEFAULT_CHANNEL\n        _tokenStartCharIndex = -1\n        _tokenStartCharPositionInLine = -1\n        _tokenStartLine = -1\n        _text = nil\n\n        _hitEOF = false\n        _mode = Lexer.DEFAULT_MODE\n        _modeStack.clear()\n\n        getInterpreter().reset()\n    }\n\n    /// \n    /// Return a token from this source; i.e., match a token on the char\n    /// stream.\n    /// \n\n    open func nextToken() throws -> Token {\n        guard let _input = _input else {\n            throw ANTLRError.illegalState(msg: \"nextToken requires a non-null input stream.\")\n        }\n\n        // Mark start location in char stream so unbuffered streams are\n        // guaranteed at least have text of current token\n        let tokenStartMarker = _input.mark()\n        defer {\n            // make sure we release marker after match or\n            // unbuffered char stream will keep buffering\n            try! _input.release(tokenStartMarker)\n        }\n        do {\n            outer:\n            while true {\n                if _hitEOF {\n                    emitEOF()\n                    return _token!\n                }\n\n                _token = nil\n                _channel = CommonToken.DEFAULT_CHANNEL\n                _tokenStartCharIndex = _input.index()\n                _tokenStartCharPositionInLine = getInterpreter().getCharPositionInLine()\n                _tokenStartLine = getInterpreter().getLine()\n                _text = nil\n                repeat {\n                    _type = CommonToken.INVALID_TYPE\n                    var ttype: Int\n                    do {\n                        ttype = try getInterpreter().match(_input, _mode)\n                    }\n                    catch  ANTLRException.recognition(let e) {\n                        notifyListeners(e as! LexerNoViableAltException, recognizer: self)\n                        try recover(e as! LexerNoViableAltException)\n                        ttype = Lexer.SKIP\n                    }\n                    if try _input.LA(1) == BufferedTokenStream.EOF {\n                        _hitEOF = true\n                    }\n                    if _type == CommonToken.INVALID_TYPE {\n                        _type = ttype\n                    }\n                    if _type == Lexer.SKIP {\n                        continue outer\n                    }\n                } while _type == Lexer.MORE\n\n                if _token == nil {\n                    emit()\n                }\n                return _token!\n            }\n        }\n\n    }\n\n    /// \n    /// Instruct the lexer to skip creating a token for current lexer rule\n    /// and look for another token.  nextToken() knows to keep looking when\n    /// a lexer rule finishes with token set to SKIP_TOKEN.  Recall that\n    /// if token==null at end of any token rule, it creates one for you\n    /// and emits it.\n    /// \n    open func skip() {\n        _type = Lexer.SKIP\n    }\n\n    open func more() {\n        _type = Lexer.MORE\n    }\n\n    open func mode(_ m: Int) {\n        _mode = m\n    }\n\n    open func pushMode(_ m: Int) {\n        if LexerATNSimulator.debug {\n            print(\"pushMode \\(m)\")\n        }\n        _modeStack.push(_mode)\n        mode(m)\n    }\n    @discardableResult\n    open func popMode() throws -> Int {\n        if _modeStack.isEmpty {\n            throw ANTLRError.unsupportedOperation(msg: \" EmptyStackException\")\n        }\n\n        if LexerATNSimulator.debug {\n            print(\"popMode back to \\(String(describing: _modeStack.peek()))\")\n        }\n        mode(_modeStack.pop())\n        return _mode\n    }\n\n\n    open override func setTokenFactory(_ factory: TokenFactory) {\n        self._factory = factory\n    }\n\n\n    open override func getTokenFactory() -> TokenFactory {\n        return _factory\n    }\n\n    /// \n    /// Set the char stream and reset the lexer\n    /// \n\n    open override func setInputStream(_ input: IntStream) throws {\n        self._input = nil\n        self._tokenFactorySourcePair = makeTokenSourceAndStream()\n        try reset()\n        self._input = input as? CharStream\n        self._tokenFactorySourcePair = makeTokenSourceAndStream()\n    }\n\n\n    open func getSourceName() -> String {\n        return _input!.getSourceName()\n    }\n\n\n    open func getInputStream() -> CharStream? {\n        return _input\n    }\n\n    /// \n    /// By default does not support multiple emits per nextToken invocation\n    /// for efficiency reasons.  Subclass and override this method, nextToken,\n    /// and getToken (to push tokens into a list and pull from that list\n    /// rather than a single variable as this implementation does).\n    /// \n    open func emit(_ token: Token) {\n        //System.err.println(\"emit \"+token);\n        self._token = token\n    }\n\n    /// \n    /// The standard method called to automatically emit a token at the\n    /// outermost lexical rule.  The token object should point into the\n    /// char buffer start..stop.  If there is a text override in 'text',\n    /// use that to set the token's text.  Override this method to emit\n    /// custom Token objects or provide a new factory.\n    /// \n    @discardableResult\n    open func emit() -> Token {\n        let t = _factory.create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, getCharIndex() - 1, _tokenStartLine, _tokenStartCharPositionInLine)\n        emit(t)\n        return t\n    }\n\n    @discardableResult\n    open func emitEOF() -> Token {\n        let cpos = getCharPositionInLine()\n        let line = getLine()\n        let idx = _input!.index()\n        let eof = _factory.create(\n            _tokenFactorySourcePair,\n            CommonToken.EOF,\n            nil,\n            CommonToken.DEFAULT_CHANNEL,\n            idx,\n            idx - 1,\n            line,\n            cpos)\n        emit(eof)\n        return eof\n    }\n\n\n    open func getLine() -> Int {\n        return getInterpreter().getLine()\n    }\n\n\n    open func getCharPositionInLine() -> Int {\n        return getInterpreter().getCharPositionInLine()\n    }\n\n    open func setLine(_ line: Int) {\n        getInterpreter().setLine(line)\n    }\n\n    open func setCharPositionInLine(_ charPositionInLine: Int) {\n        getInterpreter().setCharPositionInLine(charPositionInLine)\n    }\n\n    /// \n    /// What is the index of the current character of lookahead?\n    /// \n    open func getCharIndex() -> Int {\n        return _input!.index()\n    }\n\n    /// \n    /// Return the text matched so far for the current token or any\n    /// text override.\n    /// \n    open func getText() -> String {\n        if _text != nil {\n            return _text!\n        }\n        return getInterpreter().getText(_input!)\n    }\n\n    /// \n    /// Set the complete text of this token; it wipes any previous\n    /// changes to the text.\n    /// \n    open func setText(_ text: String) {\n        self._text = text\n    }\n\n    /// \n    /// Override if emitting multiple tokens.\n    /// \n    open func getToken() -> Token {\n        return _token!\n    }\n\n    open func setToken(_ _token: Token) {\n        self._token = _token\n    }\n\n    open func setType(_ ttype: Int) {\n        _type = ttype\n    }\n\n    open func getType() -> Int {\n        return _type\n    }\n\n    open func setChannel(_ channel: Int) {\n        _channel = channel\n    }\n\n    open func getChannel() -> Int {\n        return _channel\n    }\n\n    open func getChannelNames() -> [String]? {\n        return nil\n    }\n\n    open func getModeNames() -> [String]? {\n        return nil\n    }\n\n    /// \n    /// Return a list of all Token objects in input char stream.\n    /// Forces load of all tokens. Does not include EOF token.\n    /// \n    open func getAllTokens() throws -> [Token] {\n        var tokens = [Token]()\n        var t = try nextToken()\n        while t.getType() != CommonToken.EOF {\n            tokens.append(t)\n            t = try nextToken()\n        }\n        return tokens\n    }\n\n    open func recover(_ e: LexerNoViableAltException) throws {\n        if try _input!.LA(1) != BufferedTokenStream.EOF {\n            // skip a char and try again\n            try getInterpreter().consume(_input!)\n        }\n    }\n\n    open func notifyListeners<T>(_ e: LexerNoViableAltException, recognizer: Recognizer<T>) {\n\n        let text: String\n        do {\n            text = try _input!.getText(Interval.of(_tokenStartCharIndex, _input!.index()))\n        }\n        catch {\n            text = \"<unknown>\"\n        }\n        let msg = \"token recognition error at: '\\(getErrorDisplay(text))'\"\n\n        let listener = getErrorListenerDispatch()\n        listener.syntaxError(recognizer, nil, _tokenStartLine, _tokenStartCharPositionInLine, msg, e)\n    }\n\n    open func getErrorDisplay(_ s: String) -> String {\n        var buf = \"\"\n        for c in s {\n            buf += getErrorDisplay(c)\n        }\n        return buf\n    }\n\n    open func getErrorDisplay(_ c: Character) -> String {\n        if c.integerValue == CommonToken.EOF {\n            return \"<EOF>\"\n        }\n        switch c {\n        case \"\\n\":\n            return \"\\\\n\"\n        case \"\\t\":\n            return \"\\\\t\"\n        case \"\\r\":\n            return \"\\\\r\"\n        default:\n            return String(c)\n        }\n    }\n\n    open func getCharErrorDisplay(_ c: Character) -> String {\n        let s: String = getErrorDisplay(c)\n        return \"'\\(s)'\"\n    }\n\n    /// \n    /// Lexers can normally match any char in it's vocabulary after matching\n    /// a token, so do the easy thing and just kill a character and hope\n    /// it all works out.  You can instead use the rule invocation stack\n    /// to do sophisticated error recovery if you are in a fragment rule.\n    /// \n    open func recover(_ re: AnyObject) throws {\n        // TODO: Do we lose character or line position information?\n        try _input!.consume()\n    }\n\n    internal func makeTokenSourceAndStream() -> TokenSourceAndStream {\n        return TokenSourceAndStream(self, _input)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/LexerInterpreter.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic class LexerInterpreter: Lexer {\n    internal let grammarFileName: String\n    internal let atn: ATN\n\n    internal let ruleNames: [String]\n    internal let channelNames: [String]\n    internal let modeNames: [String]\n\n    private let vocabulary: Vocabulary?\n\n    internal final var _decisionToDFA: [DFA]\n    internal let _sharedContextCache = PredictionContextCache()\n\n    public init(_ grammarFileName: String, _ vocabulary: Vocabulary, _ ruleNames: Array<String>, _ channelNames: Array<String>, _ modeNames: Array<String>, _ atn: ATN, _ input: CharStream) throws {\n\n        self.grammarFileName = grammarFileName\n        self.atn = atn\n        self.ruleNames = ruleNames\n        self.channelNames = channelNames\n        self.modeNames = modeNames\n        self.vocabulary = vocabulary\n\n        self._decisionToDFA = [DFA]()\n        for i in 0 ..< atn.getNumberOfDecisions() {\n            _decisionToDFA.append(DFA(atn.getDecisionState(i)!, i))\n        }\n        super.init(input)\n        self._interp = LexerATNSimulator(self, atn, _decisionToDFA, _sharedContextCache)\n\n        if atn.grammarType != ATNType.lexer {\n            throw ANTLRError.illegalArgument(msg: \"The ATN must be a lexer ATN.\")\n\n        }\n    }\n\n    public required init(_ input: CharStream) {\n        fatalError(\"Use the other initializer\")\n    }\n\n    override\n    public func getATN() -> ATN {\n        return atn\n    }\n\n    override\n    public func getGrammarFileName() -> String {\n        return grammarFileName\n    }\n\n    override\n    public func getRuleNames() -> [String] {\n        return ruleNames\n    }\n\n    override\n    public func getChannelNames() -> [String] {\n        return channelNames\n    }\n\n    override\n    public func getModeNames() -> [String] {\n        return modeNames\n    }\n\n    override\n    public func getVocabulary() -> Vocabulary {\n        return vocabulary ?? super.getVocabulary()\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/LexerNoViableAltException.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic class LexerNoViableAltException: RecognitionException, CustomStringConvertible {\n    /// \n    /// Matching attempted at what input index?\n    /// \n    private let startIndex: Int\n\n    /// \n    /// Which configurations did we try at input.index() that couldn't match input.LA(1)?\n    /// \n    private let deadEndConfigs: ATNConfigSet\n\n    public init(_ lexer: Lexer?,\n                _ input: CharStream,\n                _ startIndex: Int,\n                _ deadEndConfigs: ATNConfigSet) {\n        let ctx: ParserRuleContext? = nil\n        self.startIndex = startIndex\n        self.deadEndConfigs = deadEndConfigs\n        super.init(lexer, input as IntStream, ctx)\n\n    }\n\n    public func getStartIndex() -> Int {\n        return startIndex\n    }\n\n    public func getDeadEndConfigs() -> ATNConfigSet {\n        return deadEndConfigs\n    }\n\n    public var description: String {\n        var symbol = \"\"\n        if let charStream = getInputStream() as? CharStream, startIndex >= 0 && startIndex < charStream.size() {\n            let interval = Interval.of(startIndex, startIndex)\n            symbol = try! charStream.getText(interval)\n            symbol = Utils.escapeWhitespace(symbol, false)\n        }\n\n        return \"\\(LexerNoViableAltException.self)('\\(symbol)')\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ListTokenSource.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n/// \n/// Provides an implementation of _org.antlr.v4.runtime.TokenSource_ as a wrapper around a list\n/// of _org.antlr.v4.runtime.Token_ objects.\n/// \n/// If the final token in the list is an _org.antlr.v4.runtime.Token#EOF_ token, it will be used\n/// as the EOF token for every call to _#nextToken_ after the end of the\n/// list is reached. Otherwise, an EOF token will be created.\n/// \n\npublic class ListTokenSource: TokenSource {\n    /// \n    /// The wrapped collection of _org.antlr.v4.runtime.Token_ objects to return.\n    /// \n    internal let tokens: [Token]\n\n    /// \n    /// The name of the input source. If this value is `null`, a call to\n    /// _#getSourceName_ should return the source name used to create the\n    /// the next token in _#tokens_ (or the previous token if the end of\n    /// the input has been reached).\n    /// \n    private let sourceName: String?\n\n    /// \n    /// The index into _#tokens_ of token to return by the next call to\n    /// _#nextToken_. The end of the input is indicated by this value\n    /// being greater than or equal to the number of items in _#tokens_.\n    /// \n    internal var i = 0\n\n    /// \n    /// This field caches the EOF token for the token source.\n    /// \n    internal var eofToken: Token?\n\n    /// \n    /// This is the backing field for _#getTokenFactory_ and\n    /// _setTokenFactory_.\n    /// \n    private var _factory = CommonTokenFactory.DEFAULT\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.ListTokenSource_ instance from the specified\n    /// collection of _org.antlr.v4.runtime.Token_ objects.\n    /// \n    /// - parameter tokens: The collection of _org.antlr.v4.runtime.Token_ objects to provide as a\n    /// _org.antlr.v4.runtime.TokenSource_.\n    /// \n    public convenience init(_ tokens: [Token]) {\n        self.init(tokens, nil)\n    }\n\n    /// \n    /// Constructs a new _org.antlr.v4.runtime.ListTokenSource_ instance from the specified\n    /// collection of _org.antlr.v4.runtime.Token_ objects and source name.\n    /// \n    /// - parameter tokens: The collection of _org.antlr.v4.runtime.Token_ objects to provide as a\n    /// _org.antlr.v4.runtime.TokenSource_.\n    /// - parameter sourceName: The name of the _org.antlr.v4.runtime.TokenSource_. If this value is\n    /// `null`, _#getSourceName_ will attempt to infer the name from\n    /// the next _org.antlr.v4.runtime.Token_ (or the previous token if the end of the input has\n    /// been reached).\n    /// \n    public init(_ tokens: [Token], _ sourceName: String?) {\n        self.tokens = tokens\n        self.sourceName = sourceName\n    }\n\n    public func getCharPositionInLine() -> Int {\n        if i < tokens.count {\n            return tokens[i].getCharPositionInLine()\n        }\n        else if let eofToken = eofToken {\n            return eofToken.getCharPositionInLine()\n        }\n        else if !tokens.isEmpty {\n            // have to calculate the result from the line/column of the previous\n            // token, along with the text of the token.\n            let lastToken = tokens.last!\n\n            if let tokenText = lastToken.getText() {\n                if let lastNewLine = tokenText.lastIndex(of: \"\\n\") {\n                    return tokenText.distance(from: lastNewLine, to: tokenText.endIndex) - 1\n                }\n            }\n            return (lastToken.getCharPositionInLine() +\n                    lastToken.getStopIndex() -\n                    lastToken.getStartIndex() + 1)\n        }\n        else {\n            // only reach this if tokens is empty, meaning EOF occurs at the first\n            // position in the input\n            return 0\n        }\n    }\n\n    public func nextToken() -> Token {\n        if i >= tokens.count {\n            if eofToken == nil {\n                var start = -1\n                if tokens.count > 0 {\n                    let previousStop = tokens[tokens.count - 1].getStopIndex()\n                    if previousStop != -1 {\n                        start = previousStop + 1\n                    }\n                }\n\n                let stop = max(-1, start - 1)\n                let source = TokenSourceAndStream(self, getInputStream())\n                eofToken = _factory.create(source, CommonToken.EOF, \"EOF\", CommonToken.DEFAULT_CHANNEL, start, stop, getLine(), getCharPositionInLine())\n            }\n\n            return eofToken!\n        }\n\n        let t = tokens[i]\n        if i == tokens.count - 1 && t.getType() == CommonToken.EOF {\n            eofToken = t\n        }\n\n        i += 1\n        return t\n    }\n\n    public func getLine() -> Int {\n        if i < tokens.count {\n            return tokens[i].getLine()\n        }\n        else if let eofToken = eofToken {\n            return eofToken.getLine()\n        }\n        else if !tokens.isEmpty {\n            // have to calculate the result from the line/column of the previous\n            // token, along with the text of the token.\n            let lastToken = tokens.last!\n            var line = lastToken.getLine()\n\n            if let tokenText = lastToken.getText() {\n                for c in tokenText {\n                    if c == \"\\n\" {\n                        line += 1\n                    }\n                }\n            }\n\n            // if no text is available, assume the token did not contain any newline characters.\n            return line\n        }\n        else {\n            // only reach this if tokens is empty, meaning EOF occurs at the first\n            // position in the input\n            return 1\n        }\n    }\n\n    public func getInputStream() -> CharStream? {\n        if i < tokens.count {\n            return tokens[i].getInputStream()\n        }\n        else if let eofToken = eofToken {\n            return eofToken.getInputStream()\n        }\n        else if !tokens.isEmpty {\n            return tokens.last!.getInputStream()\n        }\n\n        // no input stream information is available\n        return nil\n    }\n\n    public func getSourceName() -> String {\n        if let sourceName = sourceName {\n            return sourceName\n        }\n\n        if let inputStream = getInputStream() {\n            return inputStream.getSourceName()\n        }\n\n        return \"List\"\n    }\n\n    public func setTokenFactory(_ factory: TokenFactory) {\n        self._factory = factory\n    }\n\n    public func getTokenFactory() -> TokenFactory {\n        return _factory\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/NoViableAltException.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// Indicates that the parser could not decide which of two or more paths\n/// to take based upon the remaining input. It tracks the starting token\n/// of the offending input and also knows where the parser was\n/// in the various paths when the error. Reported by reportNoViableAlternative()\n/// \n\npublic class NoViableAltException: RecognitionException {\n    /// Which configurations did we try at input.index() that couldn't match input.LT(1)?\n\n    private let deadEndConfigs: ATNConfigSet?\n\n    /// The token object at the start index; the input stream might\n    /// not be buffering tokens so get a reference to it. (At the\n    /// time the error occurred, of course the stream needs to keep a\n    /// buffer all of the tokens but later we might not have access to those.)\n    /// \n    private let startToken: Token\n\n    public convenience init(_ recognizer: Parser) {\n        // LL(1) error\n        let token = try! recognizer.getCurrentToken()\n        self.init(recognizer,\n                recognizer.getInputStream()!,\n                token,\n                token,\n                nil,\n                recognizer._ctx)\n    }\n\n    public init(_ recognizer: Parser?,\n                _ input: IntStream,\n                _ startToken: Token,\n                _ offendingToken: Token?,\n                _ deadEndConfigs: ATNConfigSet?,\n                _ ctx: ParserRuleContext?) {\n\n        self.deadEndConfigs = deadEndConfigs\n        self.startToken = startToken\n\n        super.init(recognizer, input, ctx)\n        if let offendingToken = offendingToken {\n            setOffendingToken(offendingToken)\n        }\n    }\n\n\n    public func getStartToken() -> Token {\n        return startToken\n    }\n\n\n    public func getDeadEndConfigs() -> ATNConfigSet? {\n        return deadEndConfigs\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/Parser.swift",
    "content": "/// \n/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n/// \n\nimport Foundation\n\n///\n/// This field maps from the serialized ATN string to the deserialized _org.antlr.v4.runtime.atn.ATN_ with\n/// bypass alternatives.\n///\n/// - SeeAlso: `ATNDeserializationOptions.generateRuleBypassTransitions`\n///\nprivate var bypassAltsAtnCache : ATN? = nil\n\n///\n/// mutex for bypassAltsAtnCache updates\n///\nprivate let bypassAltsAtnCacheMutex = Mutex()\n\n\n///\n/// This is all the parsing support code essentially; most of it is error recovery stuff.\n/// \nopen class Parser: Recognizer<ParserATNSimulator> {\n    public static let EOF = -1\n    public static var ConsoleError = true\n\n    public class TraceListener: ParseTreeListener {\n        var host: Parser\n        init(_ host: Parser) {\n            self.host = host\n        }\n\n        public func enterEveryRule(_ ctx: ParserRuleContext) throws {\n            let ruleName = host.getRuleNames()[ctx.getRuleIndex()]\n            let lt1 = try host._input.LT(1)!.getText()!\n            print(\"enter   \\(ruleName), LT(1)=\\(lt1)\")\n        }\n\n        public func visitTerminal(_ node: TerminalNode) {\n            print(\"consume \\(String(describing: node.getSymbol())) rule \\(host.getRuleNames()[host._ctx!.getRuleIndex()])\")\n        }\n\n        public func visitErrorNode(_ node: ErrorNode) {\n        }\n\n        public func exitEveryRule(_ ctx: ParserRuleContext) throws {\n            let ruleName = host.getRuleNames()[ctx.getRuleIndex()]\n            let lt1 = try host._input.LT(1)!.getText()!\n            print(\"exit    \\(ruleName), LT(1)=\\(lt1)\")\n        }\n    }\n\n    public class TrimToSizeListener: ParseTreeListener {\n        public static let INSTANCE = TrimToSizeListener()\n\n        public func enterEveryRule(_ ctx: ParserRuleContext) {\n        }\n\n        public func visitTerminal(_ node: TerminalNode) {\n        }\n\n        public func visitErrorNode(_ node: ErrorNode) {\n        }\n\n        public func exitEveryRule(_ ctx: ParserRuleContext) {\n            // TODO: Print exit info.\n        }\n    }\n    \n    /// \n    /// The error handling strategy for the parser. The default value is a new\n    /// instance of _org.antlr.v4.runtime.DefaultErrorStrategy_.\n    /// \n    /// - SeeAlso: #getErrorHandler\n    /// - SeeAlso: #setErrorHandler\n    /// \n    public var _errHandler: ANTLRErrorStrategy = DefaultErrorStrategy()\n\n    /// \n    /// The input stream.\n    /// \n    /// - SeeAlso: #getInputStream\n    /// - SeeAlso: #setInputStream\n    /// \n    public var _input: TokenStream!\n\n    internal var _precedenceStack: Stack<Int> = {\n        var precedenceStack = Stack<Int>()\n        precedenceStack.push(0)\n        return precedenceStack\n    }()\n\n\n    /// \n    /// The _org.antlr.v4.runtime.ParserRuleContext_ object for the currently executing rule.\n    /// This is always non-null during the parsing process.\n    /// \n    public var _ctx: ParserRuleContext? = nil\n\n    /// \n    /// Specifies whether or not the parser should construct a parse tree during\n    /// the parsing process. The default value is `true`.\n    /// \n    /// - SeeAlso: #getBuildParseTree\n    /// - SeeAlso: #setBuildParseTree\n    /// \n    internal var _buildParseTrees: Bool = true\n\n    /// \n    /// When _#setTrace_`(true)` is called, a reference to the\n    /// _org.antlr.v4.runtime.Parser.TraceListener_ is stored here so it can be easily removed in a\n    /// later call to _#setTrace_`(false)`. The listener itself is\n    /// implemented as a parser listener so this field is not directly used by\n    /// other parser methods.\n    /// \n    private var _tracer: TraceListener?\n\n    /// \n    /// The list of _org.antlr.v4.runtime.tree.ParseTreeListener_ listeners registered to receive\n    /// events during the parse.\n    /// \n    /// - SeeAlso: #addParseListener\n    /// \n    public var _parseListeners: Array<ParseTreeListener>?\n\n    /// \n    /// The number of syntax errors reported during parsing. This value is\n    /// incremented each time _#notifyErrorListeners_ is called.\n    /// \n    internal var _syntaxErrors: Int = 0\n\n    public init(_ input: TokenStream) throws {\n        self._input = input\n        super.init()\n        try setInputStream(input)\n    }\n\n    /// reset the parser's state\n    public func reset() throws {\n        try getInputStream()?.seek(0)\n        _errHandler.reset(self)\n        _ctx = nil\n        _syntaxErrors = 0\n        setTrace(false)\n        _precedenceStack.clear()\n        _precedenceStack.push(0)\n\n        //  getInterpreter();\n        if let interpreter = _interp {\n            interpreter.reset()\n        }\n    }\n\n    /// \n    /// Match current input symbol against `ttype`. If the symbol type\n    /// matches, _org.antlr.v4.runtime.ANTLRErrorStrategy#reportMatch_ and _#consume_ are\n    /// called to complete the match process.\n    /// \n    /// If the symbol type does not match,\n    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is called on the current error\n    /// strategy to attempt recovery. If _#getBuildParseTree_ is\n    /// `true` and the token index of the symbol returned by\n    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is -1, the symbol is added to\n    /// the parse tree by calling _#createErrorNode(ParserRuleContext, Token)_ then\n    /// _ParserRuleContext#addErrorNode(ErrorNode)_.\n    /// \n    /// - Parameter ttype: the token type to match\n    /// - Throws: org.antlr.v4.runtime.RecognitionException if the current input symbol did not match\n    /// `ttype` and the error strategy could not recover from the\n    /// mismatched symbol\n    /// - Returns: the matched symbol\n    /// \n    @discardableResult\n    public func match(_ ttype: Int) throws -> Token {\n        var t = try getCurrentToken()\n        if t.getType() == ttype {\n            _errHandler.reportMatch(self)\n            try consume()\n        } else {\n            t = try _errHandler.recoverInline(self)\n            if _buildParseTrees && t.getTokenIndex() == -1 {\n                // we must have conjured up a new token during single token insertion\n                // if it's not the current symbol\n                _ctx!.addErrorNode(createErrorNode(parent: _ctx!, t: t))\n            }\n        }\n        return t\n    }\n\n    /// \n    /// Match current input symbol as a wildcard. If the symbol type matches\n    /// (i.e. has a value greater than 0), _org.antlr.v4.runtime.ANTLRErrorStrategy#reportMatch_\n    /// and _#consume_ are called to complete the match process.\n    /// \n    /// If the symbol type does not match,\n    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is called on the current error\n    /// strategy to attempt recovery. If _#getBuildParseTree_ is\n    /// `true` and the token index of the symbol returned by\n    /// _org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline_ is -1, the symbol is added to\n    /// the parse tree by calling _#createErrorNode(ParserRuleContext, Token)_ then\n    /// _ParserRuleContext#addErrorNode(ErrorNode)_.\n    /// \n    /// - Throws: org.antlr.v4.runtime.RecognitionException if the current input symbol did not match\n    /// a wildcard and the error strategy could not recover from the mismatched\n    /// symbol\n    /// - Returns: the matched symbol\n    /// \n    @discardableResult\n    public func matchWildcard() throws -> Token {\n        var t = try getCurrentToken()\n        if t.getType() > 0 {\n            _errHandler.reportMatch(self)\n            try consume()\n        } else {\n            t = try _errHandler.recoverInline(self)\n            if _buildParseTrees && t.getTokenIndex() == -1 {\n                // we must have conjured up a new token during single token insertion\n                // if it's not the current symbol\n                _ctx!.addErrorNode(createErrorNode(parent: _ctx!, t: t))\n            }\n        }\n\n        return t\n    }\n\n    /// \n    /// Track the _org.antlr.v4.runtime.ParserRuleContext_ objects during the parse and hook\n    /// them up using the _org.antlr.v4.runtime.ParserRuleContext#children_ list so that it\n    /// forms a parse tree. The _org.antlr.v4.runtime.ParserRuleContext_ returned from the start\n    /// rule represents the root of the parse tree.\n    /// \n    /// Note that if we are not building parse trees, rule contexts only point\n    /// upwards. When a rule exits, it returns the context but that gets garbage\n    /// collected if nobody holds a reference. It points upwards but nobody\n    /// points at it.\n    /// \n    /// When we build parse trees, we are adding all of these contexts to\n    /// _org.antlr.v4.runtime.ParserRuleContext#children_ list. Contexts are then not candidates\n    /// for garbage collection.\n    /// \n    public func setBuildParseTree(_ buildParseTrees: Bool) {\n        self._buildParseTrees = buildParseTrees\n    }\n\n    /// \n    /// Gets whether or not a complete parse tree will be constructed while\n    /// parsing. This property is `true` for a newly constructed parser.\n    /// \n    /// - Returns: `true` if a complete parse tree will be constructed while\n    /// parsing, otherwise `false`\n    /// \n    public func getBuildParseTree() -> Bool {\n        return _buildParseTrees\n    }\n\n    /// \n    /// Trim the internal lists of the parse tree during parsing to conserve memory.\n    /// This property is set to `false` by default for a newly constructed parser.\n    /// \n    /// - Parameter trimParseTrees: `true` to trim the capacity of the _org.antlr.v4.runtime.ParserRuleContext#children_\n    /// list to its size after a rule is parsed.\n    /// \n    public func setTrimParseTree(_ trimParseTrees: Bool) {\n        if trimParseTrees {\n            if getTrimParseTree() {\n                return\n            }\n            addParseListener(TrimToSizeListener.INSTANCE)\n        } else {\n            removeParseListener(TrimToSizeListener.INSTANCE)\n        }\n    }\n\n    /// \n    /// - Returns: `true` if the _org.antlr.v4.runtime.ParserRuleContext#children_ list is trimmed\n    /// using the default _org.antlr.v4.runtime.Parser.TrimToSizeListener_ during the parse process.\n    /// \n    public func getTrimParseTree() -> Bool {\n        return !getParseListeners().filter({ $0 === TrimToSizeListener.INSTANCE }).isEmpty\n    }\n\n    public func getParseListeners() -> [ParseTreeListener] {\n        return _parseListeners ?? [ParseTreeListener]()\n    }\n\n    /// \n    /// Registers `listener` to receive events during the parsing process.\n    /// \n    /// To support output-preserving grammar transformations (including but not\n    /// limited to left-recursion removal, automated left-factoring, and\n    /// optimized code generation), calls to listener methods during the parse\n    /// may differ substantially from calls made by\n    /// _org.antlr.v4.runtime.tree.ParseTreeWalker#DEFAULT_ used after the parse is complete. In\n    /// particular, rule entry and exit events may occur in a different order\n    /// during the parse than after the parser. In addition, calls to certain\n    /// rule entry methods may be omitted.\n    /// \n    /// With the following specific exceptions, calls to listener events are\n    /// __deterministic__, i.e. for identical input the calls to listener\n    /// methods will be the same.\n    /// \n    /// * Alterations to the grammar used to generate code may change the\n    /// behavior of the listener calls.\n    /// * Alterations to the command line options passed to ANTLR 4 when\n    /// generating the parser may change the behavior of the listener calls.\n    /// * Changing the version of the ANTLR Tool used to generate the parser\n    /// may change the behavior of the listener calls.\n    /// \n    /// - Parameter listener: the listener to add\n    /// \n    public func addParseListener(_ listener: ParseTreeListener) {\n        if _parseListeners == nil {\n            _parseListeners = [ParseTreeListener]()\n        }\n\n        _parseListeners!.append(listener)\n    }\n\n    /// \n    /// Remove `listener` from the list of parse listeners.\n    /// \n    /// If `listener` is `null` or has not been added as a parse\n    /// listener, this method does nothing.\n    /// \n    /// - SeeAlso: #addParseListener\n    /// \n    /// - Parameter listener: the listener to remove\n    /// \n\n    public func removeParseListener(_ listener: ParseTreeListener?) {\n        if _parseListeners != nil {\n            if !_parseListeners!.filter({ $0 === listener }).isEmpty {\n                _parseListeners = _parseListeners!.filter({\n                    $0 !== listener\n                })\n                if _parseListeners!.isEmpty {\n                    _parseListeners = nil\n                }\n            }\n        }\n    }\n\n    /// \n    /// Remove all parse listeners.\n    /// \n    /// - SeeAlso: #addParseListener\n    /// \n    public func removeParseListeners() {\n        _parseListeners = nil\n    }\n\n    /// \n    /// Notify any parse listeners of an enter rule event.\n    /// \n    /// - SeeAlso: #addParseListener\n    /// \n    public func triggerEnterRuleEvent() throws {\n        if let _parseListeners = _parseListeners, let _ctx = _ctx {\n            for listener: ParseTreeListener in _parseListeners {\n                try listener.enterEveryRule(_ctx)\n                _ctx.enterRule(listener)\n            }\n        }\n    }\n\n    /// \n    /// Notify any parse listeners of an exit rule event.\n    /// \n    /// - SeeAlso: #addParseListener\n    /// \n    public func triggerExitRuleEvent() throws {\n        // reverse order walk of listeners\n        if let _parseListeners = _parseListeners, let _ctx = _ctx {\n            for listener in _parseListeners.reversed() {\n                _ctx.exitRule(listener)\n                try listener.exitEveryRule(_ctx)\n            }\n        }\n    }\n\n    /// \n    /// Gets the number of syntax errors reported during parsing. This value is\n    /// incremented each time _#notifyErrorListeners_ is called.\n    /// \n    /// - SeeAlso: #notifyErrorListeners\n    /// \n    public func getNumberOfSyntaxErrors() -> Int {\n        return _syntaxErrors\n    }\n\n    override\n    open func getTokenFactory() -> TokenFactory {\n        return _input.getTokenSource().getTokenFactory()\n    }\n\n    /// Tell our token source and error strategy about a new way to create tokens.\n    override\n    open func setTokenFactory(_ factory: TokenFactory) {\n        _input.getTokenSource().setTokenFactory(factory)\n    }\n\n    /// \n    /// The ATN with bypass alternatives is expensive to create so we create it\n    /// lazily.\n    ///\n    public func getATNWithBypassAlts() -> ATN {\n        let serializedAtn = getSerializedATN()\n\n        return bypassAltsAtnCacheMutex.synchronized {\n            if let cachedResult = bypassAltsAtnCache {\n                return cachedResult\n            }\n\n            var opts = ATNDeserializationOptions()\n            opts.generateRuleBypassTransitions = true\n            let result = try! ATNDeserializer(opts).deserialize(serializedAtn)\n            bypassAltsAtnCache = result\n            return bypassAltsAtnCache!\n        }\n    }\n\n    /// \n    /// The preferred method of getting a tree pattern. For example, here's a\n    /// sample use:\n    /// \n    /// \n    /// ParseTree t = parser.expr();\n    /// ParseTreePattern p = parser.compileParseTreePattern(\"&lt;ID&gt;+0\", MyParser.RULE_expr);\n    /// ParseTreeMatch m = p.match(t);\n    /// String id = m.get(\"ID\");\n    /// \n    /// \n    public func compileParseTreePattern(_ pattern: String, _ patternRuleIndex: Int) throws -> ParseTreePattern {\n        if let tokenStream = getTokenStream() {\n            let tokenSource = tokenStream.getTokenSource()\n            if let lexer = tokenSource as? Lexer {\n                return try compileParseTreePattern(pattern, patternRuleIndex, lexer)\n            }\n        }\n        throw ANTLRError.unsupportedOperation(msg: \"Parser can't discover a lexer to use\")\n    }\n\n    /// \n    /// The same as _#compileParseTreePattern(String, int)_ but specify a\n    /// _org.antlr.v4.runtime.Lexer_ rather than trying to deduce it from this parser.\n    /// \n    public func compileParseTreePattern(_ pattern: String, _ patternRuleIndex: Int,\n                                        _ lexer: Lexer) throws -> ParseTreePattern {\n        let m = ParseTreePatternMatcher(lexer, self)\n        return try m.compile(pattern, patternRuleIndex)\n    }\n\n\n    public func getErrorHandler() -> ANTLRErrorStrategy {\n        return _errHandler\n    }\n\n    public func setErrorHandler(_ handler: ANTLRErrorStrategy) {\n        self._errHandler = handler\n    }\n\n    override\n    open func getInputStream() -> IntStream? {\n        return getTokenStream()\n    }\n\n    override\n    public final func setInputStream(_ input: IntStream) throws {\n        try setTokenStream(input as! TokenStream)\n    }\n\n    public func getTokenStream() -> TokenStream? {\n        return _input\n    }\n\n    /// Set the token stream and reset the parser.\n    public func setTokenStream(_ input: TokenStream) throws {\n        //TODO self._input = nil;\n        self._input = nil;\n        try reset()\n        self._input = input\n    }\n\n    /// Match needs to return the current input symbol, which gets put\n    /// into the label for the associated token ref; e.g., x=ID.\n    /// \n\n    public func getCurrentToken() throws -> Token {\n        return try _input.LT(1)!\n    }\n\n    public final func notifyErrorListeners(_ msg: String) {\n        let token = try? getCurrentToken()\n        notifyErrorListeners(token, msg, nil)\n    }\n\n    public func notifyErrorListeners(_ offendingToken: Token?, _ msg: String, _ e: AnyObject?) {\n        _syntaxErrors += 1\n        var line = -1\n        var charPositionInLine = -1\n        if let offendingToken = offendingToken {\n            line = offendingToken.getLine()\n            charPositionInLine = offendingToken.getCharPositionInLine()\n        }\n\n        let listener = getErrorListenerDispatch()\n        listener.syntaxError(self, offendingToken, line, charPositionInLine, msg, e)\n    }\n\n    /// \n    /// Consume and return the |: #getCurrentToken current symbol:|.\n    /// \n    /// E.g., given the following input with `A` being the current\n    /// lookahead symbol, this function moves the cursor to `B` and returns\n    /// `A`.\n    /// \n    /// \n    /// A B\n    /// ^\n    /// \n    /// \n    /// If the parser is not in error recovery mode, the consumed symbol is added\n    /// to the parse tree using _ParserRuleContext#addChild(TerminalNode)_, and\n    /// _org.antlr.v4.runtime.tree.ParseTreeListener#visitTerminal_ is called on any parse listeners.\n    /// If the parser __is__ in error recovery mode, the consumed symbol is\n    /// added to the parse tree using _#createErrorNode(ParserRuleContext, Token)_ then\n    /// _ParserRuleContext#addErrorNode(ErrorNode)_ and\n    /// _org.antlr.v4.runtime.tree.ParseTreeListener#visitErrorNode_ is called on any parse\n    /// listeners.\n    /// \n    @discardableResult\n    public func consume() throws -> Token {\n        let o = try getCurrentToken()\n        if o.getType() != Parser.EOF {\n            try getInputStream()!.consume()\n        }\n        guard let _ctx = _ctx else {\n            return o\n        }\n        let hasListener = _parseListeners != nil && !_parseListeners!.isEmpty\n\n        if _buildParseTrees || hasListener {\n            if _errHandler.inErrorRecoveryMode(self) {\n                let node = createErrorNode(parent: _ctx, t: o)\n                _ctx.addErrorNode(node)\n                if let _parseListeners = _parseListeners {\n                    for listener in _parseListeners {\n                        listener.visitErrorNode(node)\n                    }\n                }\n            } else {\n                let node = createTerminalNode(parent: _ctx, t: o)\n                _ctx.addChild(node)\n                if let _parseListeners = _parseListeners {\n                    for listener in _parseListeners {\n                        listener.visitTerminal(node)\n                    }\n                }\n            }\n        }\n        return o\n    }\n\n    /// How to create a token leaf node associated with a parent.\n    /// Typically, the terminal node to create is not a function of the parent.\n    /// \n    /// - Since: 4.7\n    /// \n    public func createTerminalNode(parent: ParserRuleContext, t: Token) -> TerminalNode {\n        return TerminalNodeImpl(t)\n    }\n\n    /// How to create an error node, given a token, associated with a parent.\n    /// Typically, the error node to create is not a function of the parent.\n    /// \n    /// - Since: 4.7\n    /// \n    public func createErrorNode(parent: ParserRuleContext, t: Token) -> ErrorNode {\n        return ErrorNode(t)\n    }\n\n    internal func addContextToParseTree() {\n\n        // add current context to parent if we have a parent\n        if let parent = _ctx?.parent as? ParserRuleContext {\n            parent.addChild(_ctx!)\n        }\n    }\n\n    /// \n    /// Always called by generated parsers upon entry to a rule. Access field\n    /// _#_ctx_ get the current context.\n    /// \n    public func enterRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int) throws {\n        setState(state)\n        _ctx = localctx\n        _ctx!.start = try _input.LT(1)\n        if _buildParseTrees {\n            addContextToParseTree()\n        }\n    }\n\n    public func exitRule() throws {\n        guard let ctx = _ctx else {\n            return\n        }\n        ctx.stop = try _input.LT(-1)\n        // trigger event on _ctx, before it reverts to parent\n        if _parseListeners != nil {\n            try triggerExitRuleEvent()\n        }\n        setState(ctx.invokingState)\n        _ctx = ctx.parent as? ParserRuleContext\n    }\n\n    public func enterOuterAlt(_ localctx: ParserRuleContext, _ altNum: Int) throws {\n        localctx.setAltNumber(altNum)\n        // if we have new localctx, make sure we replace existing ctx\n        // that is previous child of parse tree\n        if _buildParseTrees && _ctx! !== localctx {\n            if let parent = _ctx?.parent as? ParserRuleContext {\n                parent.removeLastChild()\n                parent.addChild(localctx)\n            }\n        }\n        _ctx = localctx\n        if _parseListeners != nil {\n            try triggerEnterRuleEvent()\n        }\n    }\n\n    /// \n    /// Get the precedence level for the top-most precedence rule.\n    /// \n    /// - Returns: The precedence level for the top-most precedence rule, or -1 if\n    /// the parser context is not nested within a precedence rule.\n    /// \n    public final func getPrecedence() -> Int {\n        if _precedenceStack.isEmpty {\n            return -1\n        }\n\n        return _precedenceStack.peek() ?? -1\n    }\n\n    /// \n    /// Use\n    /// _#enterRecursionRule(org.antlr.v4.runtime.ParserRuleContext, int, int, int)_ instead.\n    /// \n    /// \n    /// /@Deprecated\n    /// \n    public func enterRecursionRule(_ localctx: ParserRuleContext, _ ruleIndex: Int) throws {\n        try enterRecursionRule(localctx, getATN().ruleToStartState[ruleIndex].stateNumber, ruleIndex, 0)\n    }\n\n    public func enterRecursionRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int, _ precedence: Int) throws {\n        setState(state)\n        _precedenceStack.push(precedence)\n        _ctx = localctx\n        _ctx!.start = try _input.LT(1)\n        if _parseListeners != nil {\n            try triggerEnterRuleEvent() // simulates rule entry for left-recursive rules\n        }\n    }\n\n    /// Like _#enterRule_ but for recursive rules.\n    /// Make the current context the child of the incoming localctx.\n    /// \n    public func pushNewRecursionContext(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int) throws {\n        let previous = _ctx!\n        previous.parent = localctx\n        previous.invokingState = state\n        previous.stop = try _input.LT(-1)\n\n        _ctx = localctx\n        _ctx!.start = previous.start\n        if _buildParseTrees {\n            _ctx!.addChild(previous)\n        }\n\n        if _parseListeners != nil {\n            try triggerEnterRuleEvent() // simulates rule entry for left-recursive rules\n        }\n    }\n\n    public func unrollRecursionContexts(_ _parentctx: ParserRuleContext?) throws {\n        _precedenceStack.pop()\n        _ctx!.stop = try _input.LT(-1)\n        let retctx = _ctx! // save current ctx (return value)\n\n        // unroll so _ctx is as it was before call to recursive method\n        if _parseListeners != nil {\n            while let ctxWrap = _ctx, ctxWrap !== _parentctx {\n                try triggerExitRuleEvent()\n                _ctx = ctxWrap.parent as? ParserRuleContext\n            }\n        } else {\n            _ctx = _parentctx\n        }\n\n        // hook into tree\n        retctx.parent = _parentctx\n\n        if _buildParseTrees && _parentctx != nil {\n            // add return ctx into invoking rule's tree\n            _parentctx!.addChild(retctx)\n        }\n    }\n\n    public func getInvokingContext(_ ruleIndex: Int) -> ParserRuleContext? {\n        var p = _ctx\n        while let pWrap = p {\n            if pWrap.getRuleIndex() == ruleIndex {\n                return pWrap\n            }\n            p = pWrap.parent as? ParserRuleContext\n        }\n        return nil\n    }\n\n    public func getContext() -> ParserRuleContext? {\n        return _ctx\n    }\n\n    public func setContext(_ ctx: ParserRuleContext) {\n        _ctx = ctx\n    }\n\n    override\n    open func precpred(_ localctx: RuleContext?, _ precedence: Int) -> Bool {\n        return precedence >= _precedenceStack.peek()!\n    }\n\n    public func inContext(_ context: String) -> Bool {\n        // TODO: useful in parser?\n        return false\n    }\n\n    /// Given an AmbiguityInfo object that contains information about an\n    /// ambiguous decision event, return the list of ambiguous parse trees.\n    /// An ambiguity occurs when a specific token sequence can be recognized\n    /// in more than one way by the grammar. These ambiguities are detected only\n    /// at decision points.\n    /// \n    /// The list of trees includes the actual interpretation (that for\n    /// the minimum alternative number) and all ambiguous alternatives.\n    /// The actual interpretation is always first.\n    /// \n    /// This method reuses the same physical input token stream used to\n    /// detect the ambiguity by the original parser in the first place.\n    /// This method resets/seeks within but does not alter originalParser.\n    /// The input position is restored upon exit from this method.\n    /// Parsers using a _org.antlr.v4.runtime.UnbufferedTokenStream_ may not be able to\n    /// perform the necessary save index() / seek(saved_index) operation.\n    /// \n    /// The trees are rooted at the node whose start..stop token indices\n    /// include the start and stop indices of this ambiguity event. That is,\n    /// the trees returns will always include the complete ambiguous subphrase\n    /// identified by the ambiguity event.\n    /// \n    /// Be aware that this method does NOT notify error or parse listeners as\n    /// it would trigger duplicate or otherwise unwanted events.\n    /// \n    /// This uses a temporary ParserATNSimulator and a ParserInterpreter\n    /// so we don't mess up any statistics, event lists, etc...\n    /// The parse tree constructed while identifying/making ambiguityInfo is\n    /// not affected by this method as it creates a new parser interp to\n    /// get the ambiguous interpretations.\n    /// \n    /// Nodes in the returned ambig trees are independent of the original parse\n    /// tree (constructed while identifying/creating ambiguityInfo).\n    /// \n    /// - Since: 4.5.1\n    /// \n    /// - Parameter originalParser: The parser used to create ambiguityInfo; it\n    /// is not modified by this routine and can be either\n    /// a generated or interpreted parser. It's token\n    /// stream *is* reset/seek()'d.\n    /// - Parameter ambiguityInfo:  The information about an ambiguous decision event\n    /// for which you want ambiguous parse trees.\n    /// - Parameter startRuleIndex: The start rule for the entire grammar, not\n    /// the ambiguous decision. We re-parse the entire input\n    /// and so we need the original start rule.\n    /// \n    /// - Throws: org.antlr.v4.runtime.RecognitionException Throws upon syntax error while matching\n    /// ambig input.\n    /// - Returns:               The list of all possible interpretations of\n    /// the input for the decision in ambiguityInfo.\n    /// The actual interpretation chosen by the parser\n    /// is always given first because this method\n    /// retests the input in alternative order and\n    /// ANTLR always resolves ambiguities by choosing\n    /// the first alternative that matches the input.\n    /// \n    /// \n//\tpublic class func getAmbiguousParseTrees(originalParser : Parser,\n//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _ ambiguityInfo : AmbiguityInfo,\n//\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _ startRuleIndex : Int) throws -> Array<ParserRuleContext>  //; RecognitionException\n//\t{\n//\t\tvar trees : Array<ParserRuleContext> = Array<ParserRuleContext>();\n//\t\tvar saveTokenInputPosition : Int = originalParser.getTokenStream().index();\n//\t\t//try {\n//\t\t\t// Create a new parser interpreter to parse the ambiguous subphrase\n//\t\t\tvar parser : ParserInterpreter;\n//\t\t\tif ( originalParser is ParserInterpreter ) {\n//\t\t\t\tparser = ParserInterpreter( originalParser as! ParserInterpreter);\n//\t\t\t}\n//\t\t\telse {\n//\t\t\t\tvar serializedAtn : [Character] = ATNSerializer.getSerializedAsChars(originalParser.getATN());\n//\t\t\t\tvar deserialized : ATN = ATNDeserializer().deserialize(serializedAtn);\n//\t\t\t\tparser = ParserInterpreter(originalParser.getGrammarFileName(),\n//\t\t\t\t\t\t\t\t\t\t\t   originalParser.getVocabulary(),\n//\t\t\t\t\t\t\t\t\t\t\t    originalParser.getRuleNames() ,\n//\t\t\t\t\t\t\t\t\t\t\t   deserialized,\n//\t\t\t\t\t\t\t\t\t\t\t   originalParser.getTokenStream());\n//\t\t\t}\n//\n//\t\t\t// Make sure that we don't get any error messages from using this temporary parser\n//\t\t\tparser.removeErrorListeners();\n//\t\t\tparser.removeParseListeners();\n//\t\t\tparser.getInterpreter()!.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);\n//\n//\t\t\t// get ambig trees\n//\t\t\tvar alt : Int = ambiguityInfo.ambigAlts.firstSetBit();\n//\t\t\twhile  alt>=0  {\n//\t\t\t\t// re-parse entire input for all ambiguous alternatives\n//\t\t\t\t// (don't have to do first as it's been parsed, but do again for simplicity\n//\t\t\t\t//  using this temp parser.)\n//\t\t\t\tparser.reset();\n//\t\t\t\tparser.getTokenStream().seek(0); // rewind the input all the way for re-parsing\n//\t\t\t\tparser.overrideDecision = ambiguityInfo.decision;\n//\t\t\t\tparser.overrideDecisionInputIndex = ambiguityInfo.startIndex;\n//\t\t\t\tparser.overrideDecisionAlt = alt;\n//\t\t\t\tvar t : ParserRuleContext = parser.parse(startRuleIndex);\n//\t\t\t\tvar ambigSubTree : ParserRuleContext =\n//\t\t\t\t\tTrees.getRootOfSubtreeEnclosingRegion(t, ambiguityInfo.startIndex, ambiguityInfo.stopIndex)!;\n//\t\t\t\ttrees.append(ambigSubTree);\n//\t\t\t\talt = ambiguityInfo.ambigAlts.nextSetBit(alt+1);\n//\t\t\t}\n//\t\t//}\n//\t\tdefer {\n//\t\t\toriginalParser.getTokenStream().seek(saveTokenInputPosition);\n//\t\t}\n//\n//\t\treturn trees;\n//\t}\n\n    /// \n    /// Checks whether or not `symbol` can follow the current state in the\n    /// ATN. The behavior of this method is equivalent to the following, but is\n    /// implemented such that the complete context-sensitive follow set does not\n    /// need to be explicitly constructed.\n    /// \n    /// \n    /// return getExpectedTokens().contains(symbol);\n    /// \n    /// \n    /// - Parameter symbol: the symbol type to check\n    /// - Returns: `true` if `symbol` can follow the current state in\n    /// the ATN, otherwise `false`.\n    /// \n    public func isExpectedToken(_ symbol: Int) -> Bool {\n        let atn = getInterpreter().atn\n        var ctx: ParserRuleContext? = _ctx\n        let s = atn.states[getState()]!\n        var following = atn.nextTokens(s)\n        if following.contains(symbol) {\n            return true\n        }\n//        System.out.println(\"following \"+s+\"=\"+following);\n        if !following.contains(CommonToken.EPSILON) {\n            return false\n        }\n\n        while let ctxWrap = ctx, ctxWrap.invokingState >= 0 && following.contains(CommonToken.EPSILON) {\n            let invokingState = atn.states[ctxWrap.invokingState]!\n            let rt = invokingState.transition(0) as! RuleTransition\n            following = atn.nextTokens(rt.followState)\n            if following.contains(symbol) {\n                return true\n            }\n\n            ctx = ctxWrap.parent as? ParserRuleContext\n        }\n\n        if following.contains(CommonToken.EPSILON) && symbol == CommonToken.EOF {\n            return true\n        }\n\n        return false\n    }\n\n    /// \n    /// Computes the set of input symbols which could follow the current parser\n    /// state and context, as given by _#getState_ and _#getContext_,\n    /// respectively.\n    /// \n    /// - SeeAlso: org.antlr.v4.runtime.atn.ATN#getExpectedTokens(int, org.antlr.v4.runtime.RuleContext)\n    /// \n    public func getExpectedTokens() throws -> IntervalSet {\n        return try getATN().getExpectedTokens(getState(), getContext()!)\n    }\n\n\n    public func getExpectedTokensWithinCurrentRule() -> IntervalSet {\n        let atn = getInterpreter().atn\n        let s = atn.states[getState()]!\n        return atn.nextTokens(s)\n    }\n\n    /// Get a rule's index (i.e., `RULE_ruleName` field) or -1 if not found.\n    public func getRuleIndex(_ ruleName: String) -> Int {\n        return getRuleIndexMap()[ruleName] ?? -1\n    }\n\n    public func getRuleContext() -> ParserRuleContext? {\n        return _ctx\n    }\n\n    /// Return List&lt;String&gt; of the rule names in your parser instance\n    /// leading up to a call to the current rule.  You could override if\n    /// you want more details such as the file/line info of where\n    /// in the ATN a rule is invoked.\n    /// \n    /// This is very useful for error messages.\n    /// \n    public func getRuleInvocationStack() -> [String] {\n        return getRuleInvocationStack(_ctx)\n    }\n\n    public func getRuleInvocationStack(_ p: RuleContext?) -> [String] {\n        var p = p\n        let ruleNames = getRuleNames()\n        var stack = [String]()\n        while let pWrap = p {\n            // compute what follows who invoked us\n            let ruleIndex = pWrap.getRuleIndex()\n            if ruleIndex < 0 {\n                stack.append(\"n/a\")\n            } else {\n                stack.append(ruleNames[ruleIndex])\n            }\n            p = pWrap.parent\n        }\n        return stack\n    }\n\n    /// For debugging and other purposes.\n    public func getDFAStrings() -> [String] {\n        guard let _interp = _interp else {\n            return []\n        }\n        let vocab = getVocabulary()\n        return _interp.decisionToDFA.map {\n            $0.toString(vocab)\n        }\n    }\n\n    /// For debugging and other purposes.\n    public func dumpDFA() {\n        guard let _interp = _interp else {\n            return\n        }\n        var seenOne = false\n        let vocab = getVocabulary()\n        for dfa in _interp.decisionToDFA {\n            if !dfa.states.isEmpty {\n                if seenOne {\n                    print(\"\")\n                }\n                print(\"Decision \\(dfa.decision):\")\n                print(dfa.toString(vocab), terminator: \"\")\n                seenOne = true\n            }\n        }\n    }\n\n    public func getSourceName() -> String {\n        return _input.getSourceName()\n    }\n\n    override\n    open func getParseInfo() -> ParseInfo? {\n        let interp = getInterpreter()\n        if let interp = interp as? ProfilingATNSimulator {\n            return ParseInfo(interp)\n        }\n        return nil\n    }\n\n    /// \n    /// - Since: 4.3\n    /// \n    public func setProfile(_ profile: Bool) {\n        let interp = getInterpreter()\n        let saveMode = interp.getPredictionMode()\n        if profile {\n            if !(interp is ProfilingATNSimulator) {\n                setInterpreter(ProfilingATNSimulator(self))\n            }\n        }\n        else if interp is ProfilingATNSimulator {\n            let sim = ParserATNSimulator(self, getATN(), interp.decisionToDFA, interp.getSharedContextCache())\n            setInterpreter(sim)\n        }\n        getInterpreter().setPredictionMode(saveMode)\n    }\n\n    /// During a parse is sometimes useful to listen in on the rule entry and exit\n    /// events as well as token matches. This is for quick and dirty debugging.\n    /// \n    public func setTrace(_ trace: Bool) {\n        if !trace {\n            removeParseListener(_tracer)\n            _tracer = nil\n        } else {\n            if let _tracer = _tracer {\n                removeParseListener(_tracer)\n            } else {\n                _tracer = TraceListener(self)\n            }\n            addParseListener(_tracer!)\n        }\n    }\n\n    /// \n    /// Gets whether a _org.antlr.v4.runtime.Parser.TraceListener_ is registered as a parse listener\n    /// for the parser.\n    /// \n    /// - SeeAlso: #setTrace(boolean)\n    /// \n    public func isTrace() -> Bool {\n        return _tracer != nil\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ParserInterpreter.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// A parser simulator that mimics what ANTLR's generated\n/// parser code does. A ParserATNSimulator is used to make\n/// predictions via adaptivePredict but this class moves a pointer through the\n/// ATN to simulate parsing. ParserATNSimulator just\n/// makes us efficient rather than having to backtrack, for example.\n/// \n/// This properly creates parse trees even for left recursive rules.\n/// \n/// We rely on the left recursive rule invocation and special predicate\n/// transitions to make left recursive rules work.\n/// \n/// See TestParserInterpreter for examples.\n/// \n\npublic class ParserInterpreter: Parser {\n    internal let grammarFileName: String\n    internal let atn: ATN\n    /// This identifies StarLoopEntryState's that begin the (...)*\n    /// precedence loops of left recursive rules.\n    /// \n    internal let statesNeedingLeftRecursionContext: BitSet\n\n    internal final var decisionToDFA: [DFA]\n    // not shared like it is for generated parsers\n    internal let sharedContextCache = PredictionContextCache()\n\n    internal let ruleNames: [String]\n\n    private let vocabulary: Vocabulary\n\n    /// Tracks LR rules for adjusting the contexts\n    internal final var _parentContextStack: Array<(ParserRuleContext?, Int)> =\n    Array<(ParserRuleContext?, Int)>()\n\n    /// We need a map from (decision,inputIndex)->forced alt for computing ambiguous\n    /// parse trees. For now, we allow exactly one override.\n    /// \n    internal var overrideDecision: Int = -1\n    internal var overrideDecisionInputIndex: Int = -1\n    internal var overrideDecisionAlt: Int = -1\n\n    /// A copy constructor that creates a new parser interpreter by reusing\n    /// the fields of a previous interpreter.\n    /// \n    /// - Since: 4.5.1\n    /// \n    /// - Parameter old: The interpreter to copy\n    /// \n    public init(_ old: ParserInterpreter) throws {\n\n        self.atn = old.atn\n        self.grammarFileName = old.grammarFileName\n        self.statesNeedingLeftRecursionContext = old.statesNeedingLeftRecursionContext\n        self.decisionToDFA = old.decisionToDFA\n        self.ruleNames = old.ruleNames\n        self.vocabulary = old.vocabulary\n        try  super.init(old.getTokenStream()!)\n        setInterpreter(ParserATNSimulator(self, atn,\n                decisionToDFA,\n                sharedContextCache))\n    }\n\n    public init(_ grammarFileName: String, _ vocabulary: Vocabulary,\n                _ ruleNames: Array<String>, _ atn: ATN, _ input: TokenStream) throws {\n\n        self.grammarFileName = grammarFileName\n        self.atn = atn\n        self.ruleNames = ruleNames\n        self.vocabulary = vocabulary\n        self.decisionToDFA = [DFA]()\n        for i in 0 ..< atn.getNumberOfDecisions() {\n            decisionToDFA.append(DFA(atn.getDecisionState(i)!, i))\n        }\n\n        // identify the ATN states where pushNewRecursionContext() must be called\n        self.statesNeedingLeftRecursionContext = try! BitSet(atn.states.count)\n        for  state in atn.states {\n            if let state = state as? StarLoopEntryState {\n                if state.precedenceRuleDecision {\n                    try! self.statesNeedingLeftRecursionContext.set(state.stateNumber)\n                }\n            }\n\n        }\n        try super.init(input)\n        // get atn simulator that knows how to do predictions\n        setInterpreter(ParserATNSimulator(self, atn,\n                decisionToDFA,\n                sharedContextCache))\n    }\n\n    override\n    public func getATN() -> ATN {\n        return atn\n    }\n\n    override\n    public func getVocabulary() -> Vocabulary {\n        return vocabulary\n    }\n\n    override\n    public func getRuleNames() -> [String] {\n        return ruleNames\n    }\n\n    override\n    public func getGrammarFileName() -> String {\n        return grammarFileName\n    }\n\n    /// Begin parsing at startRuleIndex\n    public func parse(_ startRuleIndex: Int) throws -> ParserRuleContext {\n        let startRuleStartState = atn.ruleToStartState[startRuleIndex]\n\n        let rootContext = InterpreterRuleContext(nil, ATNState.INVALID_STATE_NUMBER, startRuleIndex)\n        if startRuleStartState.isPrecedenceRule {\n            try enterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0)\n        } else {\n            try enterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex)\n        }\n\n        while true {\n            let p = getATNState()!\n            switch p.getStateType() {\n            case ATNState.RULE_STOP:\n                // pop; return from rule\n                if _ctx!.isEmpty() {\n                    if startRuleStartState.isPrecedenceRule {\n                        let result: ParserRuleContext = _ctx!\n                        let parentContext: (ParserRuleContext?, Int) = _parentContextStack.pop()\n                        try unrollRecursionContexts(parentContext.0!)\n                        return result\n                    } else {\n                        try exitRule()\n                        return rootContext\n                    }\n                }\n\n                try visitRuleStopState(p)\n                break\n\n            default:\n                do {\n                    try self.visitState(p)\n                }\n                 catch ANTLRException.recognition(let e) {\n                    setState(self.atn.ruleToStopState[p.ruleIndex!].stateNumber)\n                    getContext()!.exception = e\n                    getErrorHandler().reportError(self, e)\n                    try getErrorHandler().recover(self, e)\n                }\n\n                break\n            }\n        }\n    }\n\n    override\n    public func enterRecursionRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int, _ precedence: Int) throws {\n        let pair: (ParserRuleContext?, Int) = (_ctx, localctx.invokingState)\n        _parentContextStack.push(pair)\n        try super.enterRecursionRule(localctx, state, ruleIndex, precedence)\n    }\n\n    internal func getATNState() -> ATNState? {\n        return atn.states[getState()]\n    }\n\n    internal func visitState(_ p: ATNState) throws {\n        var altNum: Int\n        if p.getNumberOfTransitions() > 1 {\n            try getErrorHandler().sync(self)\n            let decision = (p as! DecisionState).decision\n            if decision == overrideDecision && _input.index() == overrideDecisionInputIndex {\n                altNum = overrideDecisionAlt\n            } else {\n                altNum = try getInterpreter().adaptivePredict(_input, decision, _ctx)\n            }\n        } else {\n            altNum = 1\n        }\n\n        let transition = p.transition(altNum - 1)\n        switch transition.getSerializationType() {\n        case Transition.EPSILON:\n            if try statesNeedingLeftRecursionContext.get(p.stateNumber) &&\n                    !(transition.target is LoopEndState) {\n                // We are at the start of a left recursive rule's (...)* loop\n                // but it's not the exit branch of loop.\n                let ctx: InterpreterRuleContext = InterpreterRuleContext(\n                _parentContextStack.last!.0, //peek()\n                        _parentContextStack.last!.1, //peek()\n\n                        _ctx!.getRuleIndex())\n                try    pushNewRecursionContext(ctx, atn.ruleToStartState[p.ruleIndex!].stateNumber, _ctx!.getRuleIndex())\n            }\n            break\n\n        case Transition.ATOM:\n            try match((transition as! AtomTransition).label)\n            break\n\n        case Transition.RANGE: fallthrough\n        case Transition.SET: fallthrough\n        case Transition.NOT_SET:\n            if !transition.matches(try _input.LA(1), CommonToken.MIN_USER_TOKEN_TYPE, 65535) {\n                try _errHandler.recoverInline(self)\n            }\n            try matchWildcard()\n            break\n\n        case Transition.WILDCARD:\n            try matchWildcard()\n            break\n\n        case Transition.RULE:\n            let ruleStartState = transition.target as! RuleStartState\n            let ruleIndex = ruleStartState.ruleIndex!\n            let ctx = InterpreterRuleContext(_ctx, p.stateNumber, ruleIndex)\n            if ruleStartState.isPrecedenceRule {\n                try enterRecursionRule(ctx, ruleStartState.stateNumber, ruleIndex, (transition as! RuleTransition).precedence)\n            } else {\n                try enterRule(ctx, transition.target.stateNumber, ruleIndex)\n            }\n            break\n\n        case Transition.PREDICATE:\n            let predicateTransition = transition as! PredicateTransition\n            if try !sempred(_ctx!, predicateTransition.ruleIndex, predicateTransition.predIndex) {\n                throw ANTLRException.recognition(e: FailedPredicateException(self))\n            }\n            break\n\n        case Transition.ACTION:\n            let actionTransition = transition as! ActionTransition\n            try action(_ctx, actionTransition.ruleIndex, actionTransition.actionIndex)\n            break\n\n        case Transition.PRECEDENCE:\n            if !precpred(_ctx!, (transition as! PrecedencePredicateTransition).precedence) {\n                throw ANTLRException.recognition(e: FailedPredicateException(self, \"precpred(_ctx,\\((transition as! PrecedencePredicateTransition).precedence))\"))\n            }\n            break\n\n        default:\n            throw ANTLRError.unsupportedOperation(msg: \"Unrecognized ATN transition type.\")\n\n        }\n\n        setState(transition.target.stateNumber)\n    }\n\n    internal func visitRuleStopState(_ p: ATNState) throws {\n        let ruleStartState = atn.ruleToStartState[p.ruleIndex!]\n        if ruleStartState.isPrecedenceRule {\n            let (parentContext, parentState) = _parentContextStack.pop()\n            try unrollRecursionContexts(parentContext!)\n            setState(parentState)\n        } else {\n            try exitRule()\n        }\n\n        let ruleTransition = atn.states[getState()]!.transition(0) as! RuleTransition\n        setState(ruleTransition.followState.stateNumber)\n    }\n\n    /// Override this parser interpreters normal decision-making process\n    /// at a particular decision and input token index. Instead of\n    /// allowing the adaptive prediction mechanism to choose the\n    /// first alternative within a block that leads to a successful parse,\n    /// force it to take the alternative, 1..n for n alternatives.\n    /// \n    /// As an implementation limitation right now, you can only specify one\n    /// override. This is sufficient to allow construction of different\n    /// parse trees for ambiguous input. It means re-parsing the entire input\n    /// in general because you're never sure where an ambiguous sequence would\n    /// live in the various parse trees. For example, in one interpretation,\n    /// an ambiguous input sequence would be matched completely in expression\n    /// but in another it could match all the way back to the root.\n    /// \n    /// s : e '!'? ;\n    /// e : ID\n    /// | ID '!'\n    /// ;\n    /// \n    /// Here, x! can be matched as (s (e ID) !) or (s (e ID !)). In the first\n    /// case, the ambiguous sequence is fully contained only by the root.\n    /// In the second case, the ambiguous sequences fully contained within just\n    /// e, as in: (e ID !).\n    /// \n    /// Rather than trying to optimize this and make\n    /// some intelligent decisions for optimization purposes, I settled on\n    /// just re-parsing the whole input and then using\n    /// {link Trees#getRootOfSubtreeEnclosingRegion} to find the minimal\n    /// subtree that contains the ambiguous sequence. I originally tried to\n    /// record the call stack at the point the parser detected and ambiguity but\n    /// left recursive rules create a parse tree stack that does not reflect\n    /// the actual call stack. That impedance mismatch was enough to make\n    /// it it challenging to restart the parser at a deeply nested rule\n    /// invocation.\n    /// \n    /// Only parser interpreters can override decisions so as to avoid inserting\n    /// override checking code in the critical ALL(*) prediction execution path.\n    /// \n    /// - Since: 4.5.1\n    /// \n    public func addDecisionOverride(_ decision: Int, _ tokenIndex: Int, _ forcedAlt: Int) {\n        overrideDecision = decision\n        overrideDecisionInputIndex = tokenIndex\n        overrideDecisionAlt = forcedAlt\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ParserRuleContext.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// A rule invocation record for parsing.\n///\n/// Contains all of the information about the current rule not stored in the\n/// RuleContext. It handles parse tree children list, Any ATN state\n/// tracing, and the default values available for rule invocations:\n/// start, stop, rule index, current alt number.\n///\n/// Subclasses made for each rule and grammar track the parameters,\n/// return values, locals, and labels specific to that rule. These\n/// are the objects that are returned from rules.\n///\n/// Note text is not an actual field of a rule return value; it is computed\n/// from start and stop using the input stream's toString() method.  I\n/// could add a ctor to this so that we can pass in and store the input\n/// stream, but I'm not sure we want to do that.  It would seem to be undefined\n/// to get the .text property anyway if the rule matches tokens from multiple\n/// input streams.\n///\n/// I do not use getters for fields of objects that are used simply to\n/// group values such as this aggregate.  The getters/setters are there to\n/// satisfy the superclass interface.\n///\nopen class ParserRuleContext: RuleContext {\n    public static let EMPTY = ParserRuleContext()\n\n    public var visited = false\n\n    /// If we are debugging or building a parse tree for a visitor,\n    /// we need to track all of the tokens and rule invocations associated\n    /// with this rule's context. This is empty for parsing w/o tree constr.\n    /// operation because we don't the need to track the details about\n    /// how we parse this rule.\n    ///\n    public var children: [ParseTree]?\n\n    /// For debugging/tracing purposes, we want to track all of the nodes in\n    /// the ATN traversed by the parser for a particular rule.\n    /// This list indicates the sequence of ATN nodes used to match\n    /// the elements of the children list. This list does not include\n    /// ATN nodes and other rules used to match rule invocations. It\n    /// traces the rule invocation node itself but nothing inside that\n    /// other rule's ATN submachine.\n    ///\n    /// There is NOT a one-to-one correspondence between the children and\n    /// states list. There are typically many nodes in the ATN traversed\n    /// for each element in the children list. For example, for a rule\n    /// invocation there is the invoking state and the following state.\n    ///\n    /// The parser setState() method updates field s and adds it to this list\n    /// if we are debugging/tracing.\n    ///\n    /// This does not trace states visited during prediction.\n    ///\n    public var start: Token?, stop: Token?\n\n    ///\n    /// The exception that forced this rule to return. If the rule successfully\n    /// completed, this is `null`.\n    ///\n    public var exception: RecognitionException?\n\n    public override init() {\n        super.init()\n    }\n\n    public init(_ parent: ParserRuleContext?, _ invokingStateNumber: Int) {\n        super.init(parent, invokingStateNumber)\n    }\n\n    /// COPY a ctx (I'm deliberately not using copy constructor) to avoid\n    /// confusion with creating node with parent. Does not copy children.\n    ///\n    /// This is used in the generated parser code to flip a generic XContext\n    /// node for rule X to a YContext for alt label Y. In that sense, it is\n    /// not really a generic copy function.\n    ///\n    /// If we do an error sync() at start of a rule, we might add error nodes\n    /// to the generic XContext so this function must copy those nodes to\n    /// the YContext as well else they are lost!\n    ///\n    open func copyFrom(_ ctx: ParserRuleContext) {\n        self.parent = ctx.parent\n        self.invokingState = ctx.invokingState\n        self.start = ctx.start\n        self.stop = ctx.stop\n\n        // copy any error nodes to alt label node\n        if let ctxChildren = ctx.children {\n            self.children = [ParseTree]()\n            // reset parent pointer for any error nodes\n            for child in ctxChildren {\n                if let errNode = child as? ErrorNode {\n                    addChild(errNode)\n                }\n            }\n        }\n    }\n\n    // Double dispatch methods for listeners\n\n    open func enterRule(_ listener: ParseTreeListener) {\n    }\n\n    open func exitRule(_ listener: ParseTreeListener) {\n    }\n\n    /// Add a parse tree node to this as a child.  Works for\n    /// internal and leaf nodes. Does not set parent link;\n    /// other add methods must do that. Other addChild methods\n    /// call this.\n    ///\n    /// We cannot set the parent pointer of the incoming node\n    /// because the existing interfaces do not have a setParent()\n    /// method and I don't want to break backward compatibility for this.\n    ///\n    /// - Since: 4.7\n    ///\n    open func addAnyChild(_ t: ParseTree) {\n        if children == nil {\n            children = [ParseTree]()\n        }\n        children!.append(t)\n    }\n\n    open func addChild(_ ruleInvocation: RuleContext) {\n        addAnyChild(ruleInvocation)\n    }\n\n    /// Add a token leaf node child and force its parent to be this node.\n    open func addChild(_ t: TerminalNode) {\n        t.setParent(self)\n        addAnyChild(t)\n    }\n\n    /// Add an error node child and force its parent to be this node.\n    open func addErrorNode(_ errorNode: ErrorNode) {\n        errorNode.setParent(self)\n        addAnyChild(errorNode)\n    }\n\n\n    /// Used by enterOuterAlt to toss out a RuleContext previously added as\n    /// we entered a rule. If we have # label, we will need to remove\n    /// generic ruleContext object.\n    ///\n    open func removeLastChild() {\n        children?.removeLast()\n    }\n\n\n    override\n    open func getChild(_ i: Int) -> Tree? {\n        guard let children = children, i >= 0 && i < children.count else {\n            return nil\n        }\n        return children[i]\n    }\n\n    open func getChild<T: ParseTree>(_ ctxType: T.Type, i: Int) -> T? {\n        guard let children = children, i >= 0 && i < children.count else {\n            return nil\n        }\n        var j = -1 // what element have we found with ctxType?\n        for o in children {\n            if let o = o as? T {\n                j += 1\n                if j == i {\n                    return o\n                }\n            }\n        }\n\n        return nil\n    }\n\n    open func getToken(_ ttype: Int, _ i: Int) -> TerminalNode? {\n        guard let children = children, i >= 0 && i < children.count else {\n            return nil\n        }\n        var j = -1 // what token with ttype have we found?\n        for o in children {\n            if let tnode = o as? TerminalNode {\n                let symbol = tnode.getSymbol()!\n                if symbol.getType() == ttype {\n                    j += 1\n                    if j == i {\n                        return tnode\n                    }\n                }\n            }\n        }\n\n        return nil\n    }\n\n    open func getTokens(_ ttype: Int) -> [TerminalNode] {\n        guard let children = children else {\n            return [TerminalNode]()\n        }\n\n        return children.compactMap {\n            if let tnode = $0 as? TerminalNode, let symbol = tnode.getSymbol(), symbol.getType() == ttype {\n                return tnode\n            }\n            else {\n                return nil\n            }\n        }\n    }\n\n    open func getRuleContext<T: ParserRuleContext>(_ ctxType: T.Type, _ i: Int) -> T? {\n        return getChild(ctxType, i: i)\n    }\n\n    open func getRuleContexts<T: ParserRuleContext>(_ ctxType: T.Type) -> [T] {\n        guard let children = children else {\n            return [T]()\n        }\n        return children.compactMap { $0 as? T }\n    }\n\n    override\n    open func getChildCount() -> Int {\n        return children?.count ?? 0\n    }\n\n    override\n    open subscript(index: Int) -> ParseTree {\n        return children![index]\n    }\n\n    override\n    open func getSourceInterval() -> Interval {\n        guard let start = start, let stop = stop else {\n             return Interval.INVALID\n        }\n        return Interval.of(start.getTokenIndex(), stop.getTokenIndex())\n    }\n\n    ///\n    /// Get the initial token in this context.\n    /// Note that the range from start to stop is inclusive, so for rules that do not consume anything\n    /// (for example, zero length or error productions) this token may exceed stop.\n    ///\n    open func getStart() -> Token? {\n        return start\n    }\n    ///\n    /// Get the final token in this context.\n    /// Note that the range from start to stop is inclusive, so for rules that do not consume anything\n    /// (for example, zero length or error productions) this token may precede start.\n    ///\n    open func getStop() -> Token? {\n        return stop\n    }\n\n    /// Used for rule context info debugging during parse-time, not so much for ATN debugging\n    open func toInfoString(_ recognizer: Parser) -> String {\n        let rules = Array(recognizer.getRuleInvocationStack(self).reversed())\n        let startStr = start?.description ?? \"<unknown>\"\n        let stopStr = stop?.description ?? \"<unknown>\"\n        return \"ParserRuleContext\\(rules){start=\\(startStr)), stop=\\(stopStr)}\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/ProxyErrorListener.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// This implementation of _org.antlr.v4.runtime.ANTLRErrorListener_ dispatches all calls to a\n/// collection of delegate listeners. This reduces the effort required to support multiple\n/// listeners.\n/// \n/// - Author: Sam Harwell\n/// \n\npublic class ProxyErrorListener: ANTLRErrorListener {\n    private final var delegates: [ANTLRErrorListener]\n\n    public init(_ delegates: [ANTLRErrorListener]) {\n        self.delegates = delegates\n    }\n\n    public func syntaxError<T>(_ recognizer: Recognizer<T>,\n                               _ offendingSymbol: AnyObject?,\n                               _ line: Int,\n                               _ charPositionInLine: Int,\n                               _ msg: String,\n                               _ e: AnyObject?)\n    {\n        for listener in delegates {\n            listener.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e)\n        }\n    }\n\n\n    public func reportAmbiguity(_ recognizer: Parser,\n                                _ dfa: DFA,\n                                _ startIndex: Int,\n                                _ stopIndex: Int,\n                                _ exact: Bool,\n                                _ ambigAlts: BitSet,\n                                _ configs: ATNConfigSet) {\n        for listener in delegates {\n            listener.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs)\n        }\n    }\n\n\n    public func reportAttemptingFullContext(_ recognizer: Parser,\n                                            _ dfa: DFA,\n                                            _ startIndex: Int,\n                                            _ stopIndex: Int,\n                                            _ conflictingAlts: BitSet?,\n                                            _ configs: ATNConfigSet) {\n        for listener in delegates {\n            listener.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs)\n        }\n    }\n\n\n    public func reportContextSensitivity(_ recognizer: Parser,\n                                         _ dfa: DFA,\n                                         _ startIndex: Int,\n                                         _ stopIndex: Int,\n                                         _ prediction: Int,\n                                         _ configs: ATNConfigSet) {\n        for listener in delegates {\n            listener.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs)\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/RecognitionException.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just\n/// 3 kinds of errors: prediction errors, failed predicate errors, and\n/// mismatched input errors. In each case, the parser knows where it is\n/// in the input, where it is in the ATN, the rule invocation stack,\n/// and what kind of problem occurred.\n/// \n\npublic class RecognitionException {\n    /// \n    /// The _org.antlr.v4.runtime.Recognizer_ where this exception originated.\n    /// \n    private final var recognizer: RecognizerProtocol?\n\n    private final weak var ctx: RuleContext?\n\n    private final var input: IntStream?\n\n    /// \n    /// The current _org.antlr.v4.runtime.Token_ when an error occurred. Since not all streams\n    /// support accessing symbols by index, we have to track the _org.antlr.v4.runtime.Token_\n    /// instance itself.\n    /// \n    private var offendingToken: Token!\n\n    private var offendingState = ATNState.INVALID_STATE_NUMBER\n\n    public var message: String?\n\n    public init(_ recognizer: RecognizerProtocol?,\n                _ input: IntStream,\n                _ ctx: ParserRuleContext? = nil,\n                _ message: String? = nil) {\n        self.recognizer = recognizer\n        self.input = input\n        self.ctx = ctx\n        self.message = message\n        if let recognizer = recognizer {\n            self.offendingState = recognizer.getState()\n        }\n    }\n\n    /// \n    /// Get the ATN state number the parser was in at the time the error\n    /// occurred. For _org.antlr.v4.runtime.NoViableAltException_ and\n    /// _org.antlr.v4.runtime.LexerNoViableAltException_ exceptions, this is the\n    /// _org.antlr.v4.runtime.atn.DecisionState_ number. For others, it is the state whose outgoing\n    /// edge we couldn't match.\n    /// \n    /// If the state number is not known, this method returns -1.\n    /// \n    public func getOffendingState() -> Int {\n        return offendingState\n    }\n\n    internal final func setOffendingState(_ offendingState: Int) {\n        self.offendingState = offendingState\n    }\n\n    /// \n    /// Gets the set of input symbols which could potentially follow the\n    /// previously matched symbol at the time this exception was thrown.\n    /// \n    /// If the set of expected tokens is not known and could not be computed,\n    /// this method returns `null`.\n    /// \n    /// - Returns: The set of token types that could potentially follow the current\n    /// state in the ATN, or `null` if the information is not available.\n    /// \n    public func getExpectedTokens() -> IntervalSet? {\n        if let recognizer = recognizer {\n            return try? recognizer.getATN().getExpectedTokens(offendingState, ctx!)\n        }\n        return nil\n    }\n\n    /// \n    /// Gets the _org.antlr.v4.runtime.RuleContext_ at the time this exception was thrown.\n    /// \n    /// If the context is not available, this method returns `null`.\n    /// \n    /// - Returns: The _org.antlr.v4.runtime.RuleContext_ at the time this exception was thrown.\n    /// If the context is not available, this method returns `null`.\n    /// \n    public func getCtx() -> RuleContext? {\n        return ctx\n    }\n\n    /// \n    /// Gets the input stream which is the symbol source for the recognizer where\n    /// this exception was thrown.\n    /// \n    /// If the input stream is not available, this method returns `null`.\n    /// \n    /// - Returns: The input stream which is the symbol source for the recognizer\n    /// where this exception was thrown, or `null` if the stream is not\n    /// available.\n    /// \n    public func getInputStream() -> IntStream? {\n        return input\n    }\n\n    public func clearInputStream() {\n        input = nil\n    }\n\n    public func getOffendingToken() -> Token {\n        return offendingToken\n    }\n\n    internal final func setOffendingToken(_ offendingToken: Token) {\n        self.offendingToken = offendingToken\n    }\n\n    /// \n    /// Gets the _org.antlr.v4.runtime.Recognizer_ where this exception occurred.\n    /// \n    /// If the recognizer is not available, this method returns `null`.\n    /// \n    /// - Returns: The recognizer where this exception occurred, or `null` if\n    /// the recognizer is not available.\n    /// \n    public func getRecognizer() -> RecognizerProtocol? {\n        return recognizer\n    }\n\n    public func clearRecognizer() {\n        self.recognizer = nil\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/Recognizer.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Foundation\n\n\npublic protocol RecognizerProtocol {\n    func getATN() -> ATN\n    func getGrammarFileName() -> String\n    func getParseInfo() -> ParseInfo?\n    func getRuleNames() -> [String]\n    func getSerializedATN() -> [Int]\n    func getState() -> Int\n    func getTokenType(_ tokenName: String) -> Int\n    func getVocabulary() -> Vocabulary\n}\n\n\nopen class Recognizer<ATNInterpreter: ATNSimulator>: RecognizerProtocol {\n    private var _listeners: [ANTLRErrorListener] = [ConsoleErrorListener.INSTANCE]\n\n    public var _interp: ATNInterpreter!\n\n    private var _stateNumber = ATNState.INVALID_STATE_NUMBER\n\n    open func getRuleNames() -> [String] {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    ///\n    /// Get the vocabulary used by the recognizer.\n    /// \n    /// - Returns: A _org.antlr.v4.runtime.Vocabulary_ instance providing information about the\n    /// vocabulary used by the grammar.\n    /// \n    open func getVocabulary() -> Vocabulary {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Get a map from token names to token types.\n    /// \n    /// Used for XPath and tree pattern compilation.\n    /// \n    public func getTokenTypeMap() -> [String: Int] {\n        return tokenTypeMap\n    }\n\n    public lazy var tokenTypeMap: [String: Int] = {\n        let vocabulary = getVocabulary()\n\n        var result = [String: Int]()\n        let length = getATN().maxTokenType\n        for i in 0...length {\n            if let literalName = vocabulary.getLiteralName(i) {\n                result[literalName] = i\n            }\n\n            if let symbolicName = vocabulary.getSymbolicName(i) {\n                result[symbolicName] = i\n            }\n        }\n\n        result[\"EOF\"] = CommonToken.EOF\n\n        return result\n    }()\n\n\n    /// \n    /// Get a map from rule names to rule indexes.\n    /// \n    /// Used for XPath and tree pattern compilation.\n    /// \n    public func getRuleIndexMap() -> [String : Int] {\n        return ruleIndexMap\n    }\n\n    public lazy var ruleIndexMap: [String: Int] = {\n        let ruleNames = getRuleNames()\n        return Utils.toMap(ruleNames)\n    }()\n\n\n    public func getTokenType(_ tokenName: String) -> Int {\n        return getTokenTypeMap()[tokenName] ?? CommonToken.INVALID_TYPE\n    }\n\n    /// \n    /// If this recognizer was generated, it will have a serialized ATN\n    /// representation of the grammar.\n    /// \n    /// For interpreters, we don't know their serialized ATN despite having\n    /// created the interpreter from it.\n    /// \n    open func getSerializedATN() -> [Int] {\n        fatalError(\"there is no serialized ATN\")\n    }\n\n    /// For debugging and other purposes, might want the grammar name.\n    /// Have ANTLR generate an implementation for this method.\n    /// \n    open func getGrammarFileName() -> String {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Get the _org.antlr.v4.runtime.atn.ATN_ used by the recognizer for prediction.\n    /// \n    /// - Returns: The _org.antlr.v4.runtime.atn.ATN_ used by the recognizer for prediction.\n    /// \n    open func getATN() -> ATN {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Get the ATN interpreter used by the recognizer for prediction.\n    /// \n    /// - Returns: The ATN interpreter used by the recognizer for prediction.\n    /// \n    open func getInterpreter() -> ATNInterpreter {\n        return _interp\n    }\n\n    /// If profiling during the parse/lex, this will return DecisionInfo records\n    /// for each decision in recognizer in a ParseInfo object.\n    /// \n    /// - Since: 4.3\n    /// \n    open func getParseInfo() -> ParseInfo? {\n        return nil\n    }\n\n    /// \n    /// Set the ATN interpreter used by the recognizer for prediction.\n    /// \n    /// - Parameter interpreter: The ATN interpreter used by the recognizer for\n    /// prediction.\n    /// \n    open func setInterpreter(_ interpreter: ATNInterpreter) {\n        _interp = interpreter\n    }\n\n    /// \n    /// What is the error header, normally line/character position information?\n    /// \n    open func getErrorHeader(_ e: RecognitionException) -> String {\n        let offending = e.getOffendingToken()\n        let line = offending.getLine()\n        let charPositionInLine = offending.getCharPositionInLine()\n        return \"line \\(line):\\(charPositionInLine)\"\n    }\n\n    open func addErrorListener(_ listener: ANTLRErrorListener) {\n        _listeners.append(listener)\n    }\n\n    open func removeErrorListener(_ listener: ANTLRErrorListener) {\n        _listeners = _listeners.filter() {\n            $0 !== listener\n        }\n    }\n\n    open func removeErrorListeners() {\n        _listeners.removeAll()\n    }\n\n    open func getErrorListeners() -> [ANTLRErrorListener] {\n        return _listeners\n    }\n\n    open func getErrorListenerDispatch() -> ANTLRErrorListener {\n        return ProxyErrorListener(getErrorListeners())\n    }\n\n    // subclass needs to override these if there are sempreds or actions\n    // that the ATN interp needs to execute\n    open func sempred(_ _localctx: RuleContext?, _ ruleIndex: Int, _ actionIndex: Int) throws -> Bool {\n        return true\n    }\n\n    open func precpred(_ localctx: RuleContext?, _ precedence: Int) -> Bool {\n        return true\n    }\n\n    open func action(_ _localctx: RuleContext?, _ ruleIndex: Int, _ actionIndex: Int) throws {\n    }\n\n    public final func getState() -> Int {\n        return _stateNumber\n    }\n\n    /// Indicate that the recognizer has changed internal state that is\n    /// consistent with the ATN state passed in.  This way we always know\n    /// where we are in the ATN as the parser goes along. The rule\n    /// context objects form a stack that lets us see the stack of\n    /// invoking rules. Combine this and we have complete ATN\n    /// configuration information.\n    /// \n    public final func setState(_ atnState: Int) {\n//\t\tSystem.err.println(\"setState \"+atnState);\n        _stateNumber = atnState\n//\t\tif ( traceATNStates ) _ctx.trace(atnState);\n    }\n\n    open func getInputStream() -> IntStream? {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    open func setInputStream(_ input: IntStream) throws {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    open func getTokenFactory() -> TokenFactory {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    open func setTokenFactory(_ input: TokenFactory) {\n        fatalError(#function + \" must be overridden\")\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/RuleContext.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// A rule context is a record of a single rule invocation.\n///\n/// We form a stack of these context objects using the parent\n/// pointer. A parent pointer of null indicates that the current\n/// context is the bottom of the stack. The ParserRuleContext subclass\n/// as a children list so that we can turn this data structure into a\n/// tree.\n///\n/// The root node always has a null pointer and invokingState of ATNState.INVALID_STATE_NUMBER.\n///\n/// Upon entry to parsing, the first invoked rule function creates a\n/// context object (asubclass specialized for that rule such as\n/// SContext) and makes it the root of a parse tree, recorded by field\n/// Parser._ctx.\n///\n/// public final SContext s() throws RecognitionException {\n/// SContext _localctx = new SContext(_ctx, getState()); <-- create new node\n/// enterRule(_localctx, 0, RULE_s);                     <-- push it\n/// ...\n/// exitRule();                                          <-- pop back to _localctx\n/// return _localctx;\n/// }\n///\n/// A subsequent rule invocation of r from the start rule s pushes a\n/// new context object for r whose parent points at s and use invoking\n/// state is the state with r emanating as edge label.\n///\n/// The invokingState fields from a context object to the root\n/// together form a stack of rule indication states where the root\n/// (bottom of the stack) has a -1 sentinel value. If we invoke start\n/// symbol s then call r1, which calls r2, the  would look like\n/// this:\n///\n/// SContext[-1]   <- root node (bottom of the stack)\n/// R1Context[p]   <- p in rule s called r1\n/// R2Context[q]   <- q in rule r1 called r2\n///\n/// So the top of the stack, _ctx, represents a call to the current\n/// rule and it holds the return address from another rule that invoke\n/// to this rule. To invoke a rule, we must always have a current context.\n///\n/// The parent contexts are useful for computing lookahead sets and\n/// getting error information.\n///\n/// These objects are used during parsing and prediction.\n/// For the special case of parsers, we use the subclass\n/// ParserRuleContext.\n///\n/// - SeeAlso: org.antlr.v4.runtime.ParserRuleContext\n///\n\nopen class RuleContext: RuleNode {\n    /// What context invoked this rule?\n    public weak var parent: RuleContext?\n\n    /// What state invoked the rule associated with this context?\n    /// The \"return address\" is the followState of invokingState\n    /// If parent is null, this should be ATNState.INVALID_STATE_NUMBER\n    /// this context object represents the start rule.\n    ///\n    public var invokingState = ATNState.INVALID_STATE_NUMBER\n\n    public init() {\n    }\n\n    public init(_ parent: RuleContext?, _ invokingState: Int) {\n        self.parent = parent\n        //if ( parent!=null ) { print(\"invoke \"+stateNumber+\" from \"+parent)}\n        self.invokingState = invokingState\n    }\n\n    open func depth() -> Int {\n        var n = 0\n        var p: RuleContext? = self\n        while let pWrap = p {\n            p = pWrap.parent\n            n += 1\n        }\n        return n\n    }\n\n    /// A context is empty if there is no invoking state; meaning nobody called\n    /// current context.\n    ///\n    open func isEmpty() -> Bool {\n        return invokingState == ATNState.INVALID_STATE_NUMBER\n    }\n\n    // satisfy the ParseTree / SyntaxTree interface\n\n    open func getSourceInterval() -> Interval {\n        return Interval.INVALID\n    }\n\n    open func getRuleContext() -> RuleContext {\n        return self\n    }\n\n    open func getParent() -> Tree? {\n        return parent\n    }\n\n    open func setParent(_ parent: RuleContext) {\n        self.parent = parent\n    }\n\n    open func getPayload() -> AnyObject {\n        return self\n    }\n\n    /// Return the combined text of all child nodes. This method only considers\n    /// tokens which have been added to the parse tree.\n    ///\n    /// Since tokens on hidden channels (e.g. whitespace or comments) are not\n    /// added to the parse trees, they will not appear in the output of this\n    /// method.\n    ///\n\n    open func getText() -> String {\n        let length = getChildCount()\n        if length == 0 {\n            return \"\"\n        }\n\n        var builder = \"\"\n        for i in 0..<length {\n            builder += self[i].getText()\n        }\n\n        return builder\n    }\n\n    open func getRuleIndex() -> Int {\n        return -1\n    }\n\n    open func getAltNumber() -> Int { return ATN.INVALID_ALT_NUMBER }\n    open func setAltNumber(_ altNumber: Int) { }\n\n    open func getChild(_ i: Int) -> Tree? {\n        return nil\n    }\n\n\n    open func getChildCount() -> Int {\n        return 0\n    }\n\n\n    open subscript(index: Int) -> ParseTree {\n        preconditionFailure(\"Index out of range (RuleContext never has children, though its subclasses may).\")\n    }\n\n\n    open func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? {\n        return visitor.visitChildren(self)\n    }\n\n    /// Print out a whole tree, not just a node, in LISP format\n    /// (root child1 .. childN). Print just a node if this is a leaf.\n    /// We have to know the recognizer so we can get rule names.\n    ///\n    open func toStringTree(_ recog: Parser) -> String {\n        return Trees.toStringTree(self, recog)\n    }\n\n    /// Print out a whole tree, not just a node, in LISP format\n    /// (root child1 .. childN). Print just a node if this is a leaf.\n    ///\n    public func toStringTree(_ ruleNames: [String]?) -> String {\n        return Trees.toStringTree(self, ruleNames)\n    }\n\n    open func toStringTree() -> String {\n        return toStringTree(nil)\n    }\n\n    open var description: String {\n        return toString(nil, nil)\n    }\n\n     open var debugDescription: String {\n         return description\n    }\n\n    public final func toString<T>(_ recog: Recognizer<T>) -> String {\n        return toString(recog, ParserRuleContext.EMPTY)\n    }\n\n    public final func toString(_ ruleNames: [String]) -> String {\n        return toString(ruleNames, nil)\n    }\n\n    // recog null unless ParserRuleContext, in which case we use subclass toString(...)\n    open func toString<T>(_ recog: Recognizer<T>?, _ stop: RuleContext) -> String {\n        let ruleNames = recog?.getRuleNames()\n        return toString(ruleNames, stop)\n    }\n\n    open func toString(_ ruleNames: [String]?, _ stop: RuleContext?) -> String {\n        var buf = \"\"\n        var p: RuleContext? = self\n        buf += \"[\"\n        while let pWrap = p, pWrap !== stop {\n            if let ruleNames = ruleNames {\n                let ruleIndex = pWrap.getRuleIndex()\n                let ruleIndexInRange = (ruleIndex >= 0 && ruleIndex < ruleNames.count)\n                let ruleName = (ruleIndexInRange ? ruleNames[ruleIndex] : String(ruleIndex))\n                buf += ruleName\n            }\n            else {\n                if !pWrap.isEmpty() {\n                    buf += String(pWrap.invokingState)\n                }\n            }\n\n            if let pWp = pWrap.parent, (ruleNames != nil || !pWp.isEmpty()) {\n                buf += \" \"\n            }\n\n            p = pWrap.parent\n        }\n\n        buf += \"]\"\n        return buf\n    }\n\n    open func castdown<T>(_ subType: T.Type) -> T {\n        return self as! T\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/RuntimeMetaData.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// This class provides access to the current version of the ANTLR 4 runtime\n/// library as compile-time and runtime constants, along with methods for\n/// checking for matching version numbers and notifying listeners in the case\n/// where a version mismatch is detected.\n/// \n/// \n/// The runtime version information is provided by _#VERSION_ and\n/// _#getRuntimeVersion()_. Detailed information about these values is\n/// provided in the documentation for each member.\n/// \n/// \n/// The runtime version check is implemented by _#checkVersion_. Detailed\n/// information about incorporating this call into user code, as well as its use\n/// in generated code, is provided in the documentation for the method.\n/// \n/// \n/// Version strings x.y and x.y.z are considered \"compatible\" and no error\n/// would be generated. Likewise, version strings x.y-SNAPSHOT and x.y.z are\n/// considered \"compatible\" because the major and minor components x.y\n/// are the same in each.\n/// \n/// \n/// To trap any error messages issued by this code, use System.setErr()\n/// in your main() startup code.\n/// \n/// \n/// - Since: 4.3\n/// \n\npublic class RuntimeMetaData {\n    /// \n    /// A compile-time constant containing the current version of the ANTLR 4\n    /// runtime library.\n    /// \n    /// This compile-time constant value allows generated parsers and other\n    /// libraries to include a literal reference to the version of the ANTLR 4\n    /// runtime library the code was compiled against. At each release, we\n    /// change this value.\n    /// \n    /// Version numbers are assumed to have the form\n    /// \n    /// __major\u0013__.__minor__.__patch__.__revision__-__suffix__,\n    /// \n    /// with the individual components defined as follows.\n    /// \n    /// * __major__ is a required non-negative integer, and is equal to\n    /// `4` for ANTLR 4.\n    /// * __minor__ is a required non-negative integer.\n    /// * __patch__ is an optional non-negative integer. When\n    /// patch is omitted, the `.` (dot) appearing before it is\n    /// also omitted.\n    /// * __revision__ is an optional non-negative integer, and may only\n    /// be included when __patch__ is also included. When __revision__\n    /// is omitted, the `.` (dot) appearing before it is also omitted.\n    /// * __suffix__ is an optional string. When __suffix__ is\n    /// omitted, the `-` (hyphen-minus) appearing before it is also\n    /// omitted.\n    /// \n    public static let VERSION: String = \"4.13.2\"\n\n    /// \n    /// Gets the currently executing version of the ANTLR 4 runtime library.\n    /// \n    /// \n    /// This method provides runtime access to the _#VERSION_ field, as\n    /// opposed to directly referencing the field as a compile-time constant.\n    /// \n    /// - Returns: The currently executing version of the ANTLR 4 library\n    /// \n\n    public static func getRuntimeVersion() -> String {\n        return RuntimeMetaData.VERSION\n    }\n\n    /// \n    /// This method provides the ability to detect mismatches between the version\n    /// of ANTLR 4 used to generate a parser, the version of the ANTLR runtime a\n    /// parser was compiled against, and the version of the ANTLR runtime which\n    /// is currently executing.\n    /// \n    /// The version check is designed to detect the following two specific\n    /// scenarios.\n    /// \n    /// * The ANTLR Tool version used for code generation does not match the\n    /// currently executing runtime version.\n    /// * The ANTLR Runtime version referenced at the time a parser was\n    /// compiled does not match the currently executing runtime version.\n    /// \n    /// Starting with ANTLR 4.3, the code generator emits a call to this method\n    /// using two constants in each generated lexer and parser: a hard-coded\n    /// constant indicating the version of the tool used to generate the parser\n    /// and a reference to the compile-time constant _#VERSION_. At\n    /// runtime, this method is called during the initialization of the generated\n    /// parser to detect mismatched versions, and notify the registered listeners\n    /// prior to creating instances of the parser.\n    /// \n    /// This method does not perform any detection or filtering of semantic\n    /// changes between tool and runtime versions. It simply checks for a\n    /// version match and emits an error to stderr if a difference\n    /// is detected.\n    /// \n    /// Note that some breaking changes between releases could result in other\n    /// types of runtime exceptions, such as a _LinkageError_, prior to\n    /// calling this method. In these cases, the underlying version mismatch will\n    /// not be reported here. This method is primarily intended to\n    /// notify users of potential semantic changes between releases that do not\n    /// result in binary compatibility problems which would be detected by the\n    /// class loader. As with semantic changes, changes that break binary\n    /// compatibility between releases are mentioned in the release notes\n    /// accompanying the affected release.\n    /// \n    /// __ Additional note for target developers:__ The version check\n    /// implemented by this class is designed to address specific compatibility\n    /// concerns that may arise during the execution of Java applications. Other\n    /// targets should consider the implementation of this method in the context\n    /// of that target's known execution environment, which may or may not\n    /// resemble the design provided for the Java target.\n    /// \n    /// - Parameter generatingToolVersion: The version of the tool used to generate a parser.\n    /// This value may be null when called from user code that was not generated\n    /// by, and does not reference, the ANTLR 4 Tool itself.\n    /// - Parameter compileTimeVersion: The version of the runtime the parser was\n    /// compiled against. This should always be passed using a direct reference\n    /// to _#VERSION_.\n    /// \n    public static func checkVersion(_ generatingToolVersion: String, _ compileTimeVersion: String) {\n        let runtimeVersion: String = RuntimeMetaData.VERSION\n        var runtimeConflictsWithGeneratingTool: Bool = false\n        var runtimeConflictsWithCompileTimeTool: Bool = false\n\n        //if ( generatingToolVersion != nil ) {\n        runtimeConflictsWithGeneratingTool =\n                !(runtimeVersion == (generatingToolVersion)) &&\n                !(getMajorMinorVersion(runtimeVersion) == (getMajorMinorVersion(generatingToolVersion)))\n        //}\n\n        runtimeConflictsWithCompileTimeTool =\n                !(runtimeVersion == (compileTimeVersion)) &&\n                !(getMajorMinorVersion(runtimeVersion) == (getMajorMinorVersion(compileTimeVersion)))\n\n        if runtimeConflictsWithGeneratingTool {\n            print(\"ANTLR Tool version \\(generatingToolVersion) used for code generation does not match the current runtime version \\(runtimeVersion)\")\n        }\n        if runtimeConflictsWithCompileTimeTool {\n            print(\"ANTLR Runtime version \\(compileTimeVersion)used for parser compilation does not match the current runtime version \\(runtimeVersion)\")\n        }\n    }\n\n    /// \n    /// Gets the major and minor version numbers from a version string. For\n    /// details about the syntax of the input `version`.\n    /// E.g., from x.y.z return x.y.\n    /// \n    /// - Parameter version: The complete version string.\n    /// - Returns: A string of the form __major__.__minor__ containing\n    /// only the major and minor components of the version string.\n    /// \n    public static func getMajorMinorVersion(_ version: String) -> String {\n        var result = version\n\n        let dotBits = version.split(separator: \".\", maxSplits: 2, omittingEmptySubsequences: false)\n        if dotBits.count >= 2 {\n            result = dotBits[0..<2].joined(separator: \".\")\n        }\n\n        let dashBits = result.split(separator: \"-\", maxSplits: 1, omittingEmptySubsequences: false)\n        return String(dashBits[0])\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/Token.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// A token has properties: text, type, line, character position in the line\n/// (so we can ignore tabs), token channel, index, and source from which\n/// we obtained this token.\n/// \n\npublic protocol Token: AnyObject, CustomStringConvertible {\n    //let INVALID_TYPE : Int = 0;\n\n    /// During lookahead operations, this \"token\" signifies we hit rule end ATN state\n    /// and did not follow it despite needing to.\n    /// \n    //let EPSILON : Int = -2;\n\n    //let MIN_USER_TOKEN_TYPE : Int = 1;\n\n    //let EOF : Int = IntStream.EOF;\n\n    /// All tokens go to the parser (unless skip() is called in that rule)\n    /// on a particular \"channel\".  The parser tunes to a particular channel\n    /// so that whitespace etc... can go to the parser on a \"hidden\" channel.\n    /// \n    //let DEFAULT_CHANNEL : Int = 0;\n\n    /// Anything on different channel than DEFAULT_CHANNEL is not parsed\n    /// by parser.\n    /// \n    //let HIDDEN_CHANNEL : Int = 1;\n\n    /// \n    /// This is the minimum constant value which can be assigned to a\n    /// user-defined token channel.\n    /// \n    /// \n    /// The non-negative numbers less than _#MIN_USER_CHANNEL_VALUE_ are\n    /// assigned to the predefined channels _#DEFAULT_CHANNEL_ and\n    /// _#HIDDEN_CHANNEL_.\n    /// \n    /// - SeeAlso: org.antlr.v4.runtime.Token#getChannel()\n    /// \n    //let MIN_USER_CHANNEL_VALUE : Int = 2;\n\n    /// \n    /// Get the text of the token.\n    /// \n    func getText() -> String?\n\n    /// Get the token type of the token\n    func getType() -> Int\n\n    /// The line number on which the 1st character of this token was matched,\n    /// line=1..n\n    /// \n    func getLine() -> Int\n\n    /// The index of the first character of this token relative to the\n    /// beginning of the line at which it occurs, 0..n-1\n    /// \n    func getCharPositionInLine() -> Int\n\n    /// Return the channel this token. Each token can arrive at the parser\n    /// on a different channel, but the parser only \"tunes\" to a single channel.\n    /// The parser ignores everything not on DEFAULT_CHANNEL.\n    /// \n    func getChannel() -> Int\n\n    /// An index from 0..n-1 of the token object in the input stream.\n    /// This must be valid in order to print token streams and\n    /// use TokenRewriteStream.\n    /// \n    /// Return -1 to indicate that this token was conjured up since\n    /// it doesn't have a valid index.\n    /// \n    func getTokenIndex() -> Int\n\n    /// The starting character index of the token\n    /// This method is optional; return -1 if not implemented.\n    /// \n    func getStartIndex() -> Int\n\n    /// The last character index of the token.\n    /// This method is optional; return -1 if not implemented.\n    /// \n    func getStopIndex() -> Int\n\n    /// Gets the _org.antlr.v4.runtime.TokenSource_ which created this token.\n    /// \n    func getTokenSource() -> TokenSource?\n\n    /// \n    /// Gets the _org.antlr.v4.runtime.CharStream_ from which this token was derived.\n    /// \n    func getInputStream() -> CharStream?\n\n    func getTokenSourceAndStream() -> TokenSourceAndStream\n\n    var visited: Bool { get set }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/TokenFactory.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// The default mechanism for creating tokens. It's used by default in Lexer and\n/// the error handling strategy (to create missing tokens).  Notifying the parser\n/// of a new factory means that it notifies it's token source and error strategy.\n/// \npublic protocol TokenFactory {\n\n    //typealias Symbol\n    /// This is the method used to create tokens in the lexer and in the\n    /// error handling strategy. If text!=null, than the start and stop positions\n    /// are wiped to -1 in the text override is set in the CommonToken.\n    /// \n    func create(_ source: TokenSourceAndStream, _ type: Int, _ text: String?,\n                _ channel: Int, _ start: Int, _ stop: Int,\n                _ line: Int, _ charPositionInLine: Int) -> Token\n    /// Generically useful\n    func create(_ type: Int, _ text: String) -> Token\n\n}\n\n\n/**\n Holds the references to the TokenSource and CharStream used to create a Token.\n These are together to reduce memory footprint by having one instance of\n TokenSourceAndStream shared across many tokens.  The references here are weak\n to avoid retain cycles.\n */\npublic class TokenSourceAndStream {\n    ///\n    /// An empty TokenSourceAndStream which is used as the default value of\n    /// _#source_ for tokens that do not have a source.\n    ///\n    public static let EMPTY = TokenSourceAndStream()\n\n    public weak var tokenSource: TokenSource?\n    public weak var stream: CharStream?\n\n    public init(_ tokenSource: TokenSource? = nil, _ stream: CharStream? = nil) {\n        self.tokenSource = tokenSource\n        self.stream = stream\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/TokenSource.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// A source of tokens must provide a sequence of tokens via _#nextToken()_\n/// and also must reveal it's source of characters; _org.antlr.v4.runtime.CommonToken_'s text is\n/// computed from a _org.antlr.v4.runtime.CharStream_; it only store indices into the char\n/// stream.\n/// \n/// Errors from the lexer are never passed to the parser. Either you want to keep\n/// going or you do not upon token recognition error. If you do not want to\n/// continue lexing then you do not want to continue parsing. Just throw an\n/// exception not under _org.antlr.v4.runtime.RecognitionException_ and Java will naturally toss\n/// you all the way out of the recognizers. If you want to continue lexing then\n/// you should not throw an exception to the parser--it has already requested a\n/// token. Keep lexing until you get a valid one. Just report errors and keep\n/// going, looking for a valid token.\n/// \n\npublic protocol TokenSource: AnyObject {\n    /// \n    /// Return a _org.antlr.v4.runtime.Token_ object from your input stream (usually a\n    /// _org.antlr.v4.runtime.CharStream_). Do not fail/return upon lexing error; keep chewing\n    /// on the characters until you get a good one; errors are not passed through\n    /// to the parser.\n    /// \n    func nextToken() throws -> Token\n\n    /// \n    /// Get the line number for the current position in the input stream. The\n    /// first line in the input is line 1.\n    /// \n    /// - Returns: The line number for the current position in the input stream, or\n    /// 0 if the current token source does not track line numbers.\n    /// \n    func getLine() -> Int\n\n    /// \n    /// Get the index into the current line for the current position in the input\n    /// stream. The first character on a line has position 0.\n    /// \n    /// - Returns: The line number for the current position in the input stream, or\n    /// -1 if the current token source does not track character positions.\n    /// \n    func getCharPositionInLine() -> Int\n\n    /// \n    /// Get the _org.antlr.v4.runtime.CharStream_ from which this token source is currently\n    /// providing tokens.\n    /// \n    /// - Returns: The _org.antlr.v4.runtime.CharStream_ associated with the current position in\n    /// the input, or `null` if no input stream is available for the token\n    /// source.\n    /// \n    func getInputStream() -> CharStream?\n\n    /// \n    /// Gets the name of the underlying input source. This method returns a\n    /// non-null, non-empty string. If such a name is not known, this method\n    /// returns _org.antlr.v4.runtime.IntStream#UNKNOWN_SOURCE_NAME_.\n    /// \n    func getSourceName() -> String\n\n    /// \n    /// Set the _org.antlr.v4.runtime.TokenFactory_ this token source should use for creating\n    /// _org.antlr.v4.runtime.Token_ objects from the input.\n    /// \n    /// - Parameter factory: The _org.antlr.v4.runtime.TokenFactory_ to use for creating tokens.\n    /// \n    func setTokenFactory(_ factory: TokenFactory)\n\n    /// \n    /// Gets the _org.antlr.v4.runtime.TokenFactory_ this token source is currently using for\n    /// creating _org.antlr.v4.runtime.Token_ objects from the input.\n    /// \n    /// - Returns: The _org.antlr.v4.runtime.TokenFactory_ currently used by this token source.\n    /// \n    func getTokenFactory() -> TokenFactory\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/TokenStream.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// \n/// An _org.antlr.v4.runtime.IntStream_ whose symbols are _org.antlr.v4.runtime.Token_ instances.\n/// \n\npublic protocol TokenStream: IntStream {\n    /// \n    /// Get the _org.antlr.v4.runtime.Token_ instance associated with the value returned by\n    /// _#LA LA(k)_. This method has the same pre- and post-conditions as\n    /// _org.antlr.v4.runtime.IntStream#LA_. In addition, when the preconditions of this method\n    /// are met, the return value is non-null and the value of\n    /// `LT(k).getType()==LA(k)`.\n    /// \n    /// - SeeAlso: org.antlr.v4.runtime.IntStream#LA\n    /// \n    func LT(_ k: Int) throws -> Token?\n\n    /// \n    /// Gets the _org.antlr.v4.runtime.Token_ at the specified `index` in the stream. When\n    /// the preconditions of this method are met, the return value is non-null.\n    /// \n    /// The preconditions for this method are the same as the preconditions of\n    /// _org.antlr.v4.runtime.IntStream#seek_. If the behavior of `seek(index)` is\n    /// unspecified for the current state and given `index`, then the\n    /// behavior of this method is also unspecified.\n    /// \n    /// The symbol referred to by `index` differs from `seek()` only\n    /// in the case of filtering streams where `index` lies before the end\n    /// of the stream. Unlike `seek()`, this method does not adjust\n    /// `index` to point to a non-ignored symbol.\n    /// \n    /// - Throws: ANTLRError.illegalArgument if {code index} is less than 0\n    /// - Throws: ANTLRError.unsupportedOperation if the stream does not support\n    /// retrieving the token at the specified index\n    /// \n    func get(_ index: Int) throws -> Token\n\n    /// \n    /// Gets the underlying _org.antlr.v4.runtime.TokenSource_ which provides tokens for this\n    /// stream.\n    /// \n    func getTokenSource() -> TokenSource\n\n    /// \n    /// Return the text of all tokens within the specified `interval`. This\n    /// method behaves like the following code (including potential exceptions\n    /// for violating preconditions of _#get_, but may be optimized by the\n    /// specific implementation.\n    /// \n    /// \n    /// TokenStream stream = ...;\n    /// String text = \"\";\n    /// for (int i = interval.a; i &lt;= interval.b; i++) {\n    /// text += stream.get(i).getText();\n    /// }\n    /// \n    /// \n    /// - Parameter interval: The interval of tokens within this stream to get text\n    /// for.\n    /// - Returns: The text of all tokens within the specified interval in this\n    /// stream.\n    /// \n    /// \n    func getText(_ interval: Interval) throws -> String\n\n    /// \n    /// Return the text of all tokens in the stream. This method behaves like the\n    /// following code, including potential exceptions from the calls to\n    /// _org.antlr.v4.runtime.IntStream#size_ and _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be\n    /// optimized by the specific implementation.\n    /// \n    /// \n    /// TokenStream stream = ...;\n    /// String text = stream.getText(new Interval(0, stream.size()));\n    /// \n    /// \n    /// - Returns: The text of all tokens in the stream.\n    /// \n    func getText() throws -> String\n\n    /// \n    /// Return the text of all tokens in the source interval of the specified\n    /// context. This method behaves like the following code, including potential\n    /// exceptions from the call to _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be\n    /// optimized by the specific implementation.\n    /// \n    /// If `ctx.getSourceInterval()` does not return a valid interval of\n    /// tokens provided by this stream, the behavior is unspecified.\n    /// \n    /// \n    /// TokenStream stream = ...;\n    /// String text = stream.getText(ctx.getSourceInterval());\n    /// \n    /// \n    /// - Parameter ctx: The context providing the source interval of tokens to get\n    /// text for.\n    /// - Returns: The text of all tokens within the source interval of `ctx`.\n    /// \n    func getText(_ ctx: RuleContext) throws -> String\n\n    /// \n    /// Return the text of all tokens in this stream between `start` and\n    /// `stop` (inclusive).\n    /// \n    /// If the specified `start` or `stop` token was not provided by\n    /// this stream, or if the `stop` occurred before the `start`\n    /// token, the behavior is unspecified.\n    /// \n    /// For streams which ensure that the _org.antlr.v4.runtime.Token#getTokenIndex_ method is\n    /// accurate for all of its provided tokens, this method behaves like the\n    /// following code. Other streams may implement this method in other ways\n    /// provided the behavior is consistent with this at a high level.\n    /// \n    /// \n    /// TokenStream stream = ...;\n    /// String text = \"\";\n    /// for (int i = start.getTokenIndex(); i &lt;= stop.getTokenIndex(); i++) {\n    /// text += stream.get(i).getText();\n    /// }\n    /// \n    /// \n    /// - Parameter start: The first token in the interval to get text for.\n    /// - Parameter stop: The last token in the interval to get text for (inclusive).\n    /// - Throws: ANTLRError.unsupportedOperation if this stream does not support\n    /// this method for the specified tokens\n    /// - Returns: The text of all tokens lying between the specified `start`\n    /// and `stop` tokens.\n    /// \n    /// \n    func getText(_ start: Token?, _ stop: Token?) throws -> String\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/TokenStreamRewriter.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// Useful for rewriting out a buffered input token stream after doing some\n/// augmentation or other manipulations on it.\n/// \n/// \n/// You can insert stuff, replace, and delete chunks. Note that the operations\n/// are done lazily--only if you convert the buffer to a _String_ with\n/// _org.antlr.v4.runtime.TokenStream#getText()_. This is very efficient because you are not\n/// moving data around all the time. As the buffer of tokens is converted to\n/// strings, the _#getText()_ method(s) scan the input token stream and\n/// check to see if there is an operation at the current index. If so, the\n/// operation is done and then normal _String_ rendering continues on the\n/// buffer. This is like having multiple Turing machine instruction streams\n/// (programs) operating on a single input tape. :)\n/// \n/// \n/// This rewriter makes no modifications to the token stream. It does not ask the\n/// stream to fill itself up nor does it advance the input cursor. The token\n/// stream _org.antlr.v4.runtime.TokenStream#index()_ will return the same value before and\n/// after any _#getText()_ call.\n/// \n/// \n/// The rewriter only works on tokens that you have in the buffer and ignores the\n/// current input cursor. If you are buffering tokens on-demand, calling\n/// _#getText()_ halfway through the input will only do rewrites for those\n/// tokens in the first half of the file.\n/// \n/// \n/// Since the operations are done lazily at _#getText_-time, operations do\n/// not screw up the token index values. That is, an insert operation at token\n/// index `i` does not change the index values for tokens\n/// `i`+1..n-1.\n/// \n/// \n/// Because operations never actually alter the buffer, you may always get the\n/// original token stream back without undoing anything. Since the instructions\n/// are queued up, you can easily simulate transactions and roll back any changes\n/// if there is an error just by removing instructions. For example,\n/// \n/// \n/// CharStream input = new ANTLRFileStream(\"input\");\n/// TLexer lex = new TLexer(input);\n/// CommonTokenStream tokens = new CommonTokenStream(lex);\n/// T parser = new T(tokens);\n/// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);\n/// parser.startRule();\n/// \n/// \n/// \n/// Then in the rules, you can execute (assuming rewriter is visible):\n/// \n/// \n/// Token t,u;\n/// ...\n/// rewriter.insertAfter(t, \"text to put after t\");}\n/// rewriter.insertAfter(u, \"text after u\");}\n/// System.out.println(rewriter.getText());\n/// \n/// \n/// \n/// You can also have multiple \"instruction streams\" and get multiple rewrites\n/// from a single pass over the input. Just name the instruction streams and use\n/// that name again when printing the buffer. This could be useful for generating\n/// a C file and also its header file--all from the same buffer:\n/// \n/// \n/// rewriter.insertAfter(\"pass1\", t, \"text to put after t\");}\n/// rewriter.insertAfter(\"pass2\", u, \"text after u\");}\n/// System.out.println(rewriter.getText(\"pass1\"));\n/// System.out.println(rewriter.getText(\"pass2\"));\n/// \n/// \n/// \n/// If you don't use named rewrite streams, a \"default\" stream is used as the\n/// first example shows.\n/// \n\nimport Foundation\n\npublic class TokenStreamRewriter {\n    public let DEFAULT_PROGRAM_NAME = \"default\"\n    public static let PROGRAM_INIT_SIZE = 100\n    public static let MIN_TOKEN_INDEX = 0\n\n    // Define the rewrite operation hierarchy\n    public class RewriteOperation: CustomStringConvertible {\n        /// What index into rewrites List are we?\n        internal var instructionIndex = 0\n        /// Token buffer index.\n        internal var index: Int\n        internal var text: String?\n        internal var lastIndex = 0\n        internal weak var tokens: TokenStream!\n\n        init(_ index: Int, _ tokens: TokenStream) {\n            self.index = index\n            self.tokens = tokens\n        }\n\n        init(_ index: Int, _ text: String?, _ tokens: TokenStream) {\n            self.index = index\n            self.text = text\n            self.tokens = tokens\n        }\n\n        /// Execute the rewrite operation by possibly adding to the buffer.\n        /// Return the index of the next token to operate on.\n        /// \n        public func execute(_ buf: inout String) throws -> Int {\n            return index\n        }\n\n        public var description: String {\n            let opName = String(describing: type(of: self))\n            return \"<\\(opName)@\\(try! tokens.get(index)):\\\"\\(text!)\\\">\"\n        }\n    }\n\n    public class InsertBeforeOp: RewriteOperation {\n        override public func execute(_ buf: inout String) throws -> Int {\n            if let text = text {\n                buf.append(text)\n            }\n            let token = try tokens.get(index)\n            if token.getType() != CommonToken.EOF {\n                buf.append(token.getText()!)\n            }\n            return index + 1\n        }\n    }\n\n    public class InsertAfterOp: InsertBeforeOp {\n        public override init(_ index: Int, _ text: String?, _ tokens: TokenStream) {\n            super.init(index + 1, text, tokens)\n        }\n    }\n\n    /// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp\n    /// instructions.\n    ///\n\n    public class ReplaceOp: RewriteOperation {\n\n        public init(_ from: Int, _ to: Int, _ text: String?, _ tokens: TokenStream) {\n            super.init(from, text, tokens)\n            lastIndex = to\n        }\n\n        override\n        public func execute(_ buf: inout String) -> Int {\n            if let text = text {\n                buf += text\n            }\n            return lastIndex + 1\n        }\n\n        override\n        public var description: String {\n            let token = try! tokens.get(index)\n            let lastToken = try! tokens.get(lastIndex)\n            if let text = text {\n                return \"<ReplaceOp@\\(token)..\\(lastToken):\\\"\\(text)\\\">\"\n            }\n            return \"<DeleteOp@\\(token)..\\(lastToken)>\"\n        }\n    }\n\n    public class RewriteOperationArray{\n        private final var rewrites = [RewriteOperation?]()\n\n        public init() {\n            rewrites.reserveCapacity(TokenStreamRewriter.PROGRAM_INIT_SIZE)\n        }\n\n        final func append(_ op: RewriteOperation) {\n            op.instructionIndex = rewrites.count\n            rewrites.append(op)\n        }\n\n        final func rollback(_ instructionIndex: Int) {\n            rewrites = Array(rewrites[TokenStreamRewriter.MIN_TOKEN_INDEX ..< instructionIndex])\n        }\n\n        final var count: Int {\n            return rewrites.count\n        }\n\n        final var isEmpty: Bool {\n            return rewrites.isEmpty\n        }\n\n        /// We need to combine operations and report invalid operations (like\n        /// overlapping replaces that are not completed nested). Inserts to\n        /// same index need to be combined etc...  Here are the cases:\n        /// \n        /// I.i.u I.j.v                             leave alone, nonoverlapping\n        /// I.i.u I.i.v                             combine: Iivu\n        /// \n        /// R.i-j.u R.x-y.v | i-j in x-y            delete first R\n        /// R.i-j.u R.i-j.v                         delete first R\n        /// R.i-j.u R.x-y.v | x-y in i-j            ERROR\n        /// R.i-j.u R.x-y.v | boundaries overlap    ERROR\n        /// \n        /// Delete special case of replace (text==null):\n        /// D.i-j.u D.x-y.v | boundaries overlap    combine to max(min)..max(right)\n        /// \n        /// I.i.u R.x-y.v | i in (x+1)-y            delete I (since insert before\n        /// we're not deleting i)\n        /// I.i.u R.x-y.v | i not in (x+1)-y        leave alone, nonoverlapping\n        /// R.x-y.v I.i.u | i in x-y                ERROR\n        /// R.x-y.v I.x.u                           R.x-y.uv (combine, delete I)\n        /// R.x-y.v I.i.u | i not in x-y            leave alone, nonoverlapping\n        /// \n        /// I.i.u = insert u before op @ index i\n        /// R.x-y.u = replace x-y indexed tokens with u\n        /// \n        /// First we need to examine replaces. For any replace op:\n        /// \n        /// 1. wipe out any insertions before op within that range.\n        /// 2. Drop any replace op before that is contained completely within\n        /// that range.\n        /// 3. Throw exception upon boundary overlap with any previous replace.\n        /// \n        /// Then we can deal with inserts:\n        /// \n        /// 1. for any inserts to same index, combine even if not adjacent.\n        /// 2. for any prior replace with same left boundary, combine this\n        /// insert with replace and delete this replace.\n        /// 3. throw exception if index in same range as previous replace\n        /// \n        /// Don't actually delete; make op null in list. Easier to walk list.\n        /// Later we can throw as we add to index &rarr; op map.\n        /// \n        /// Note that I.2 R.2-2 will wipe out I.2 even though, technically, the\n        /// inserted stuff would be before the replace range. But, if you\n        /// add tokens in front of a method body '{' and then delete the method\n        /// body, I think the stuff before the '{' you added should disappear too.\n        /// \n        /// Return a map from token index to operation.\n        /// \n        final func reduceToSingleOperationPerIndex() throws -> [Int: RewriteOperation] {\n\n            let rewritesCount = rewrites.count\n            // WALK REPLACES\n            for i in 0..<rewritesCount {\n                guard let rop = rewrites[i] as? ReplaceOp else {\n                    continue\n                }\n\n                // Wipe prior inserts within range\n                let inserts = getKindOfOps(&rewrites, InsertBeforeOp.self, i)\n                for j in inserts {\n                    if let iop = rewrites[j] {\n                        if iop.index == rop.index {\n                            // E.g., insert before 2, delete 2..2; update replace\n                            // text to include insert before, kill insert\n                            rewrites[iop.instructionIndex] = nil\n                            rop.text = catOpText(iop.text, rop.text)\n                        }\n                        else if iop.index > rop.index && iop.index <= rop.lastIndex {\n                            // delete insert as it's a no-op.\n                            rewrites[iop.instructionIndex] = nil\n                        }\n                    }\n                }\n                // Drop any prior replaces contained within\n                let prevRopIndexList = getKindOfOps(&rewrites, ReplaceOp.self, i)\n                for j in prevRopIndexList {\n                    if let prevRop = rewrites[j] {\n                        if prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex {\n                            // delete replace as it's a no-op.\n                            rewrites[prevRop.instructionIndex] = nil\n                            continue\n                        }\n                        // throw exception unless disjoint or identical\n                        let disjoint: Bool =\n                            prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex\n                        // Delete special case of replace (text==null):\n                        // D.i-j.u D.x-y.v  | boundaries overlap    combine to max(min)..max(right)\n                        if prevRop.text == nil && rop.text == nil && !disjoint {\n                            rewrites[prevRop.instructionIndex] = nil // kill first delete\n                            rop.index = min(prevRop.index, rop.index)\n                            rop.lastIndex = max(prevRop.lastIndex, rop.lastIndex)\n                        } else if !disjoint {\n                            throw ANTLRError.illegalArgument(msg: \"replace op boundaries of \\(rop.description) \" +\n                                \"overlap with previous \\(prevRop.description)\")\n                        }\n                    }\n                }\n            }\n\n            // WALK INSERTS\n            for i in 0..<rewritesCount {\n                guard let iop = rewrites[i] else {\n                    continue\n                }\n                if !(iop is InsertBeforeOp) {\n                    continue\n                }\n\n                // combine current insert with prior if any at same index\n                let prevIopIndexList = getKindOfOps(&rewrites, InsertBeforeOp.self, i)\n                for j in prevIopIndexList {\n                    if let prevIop = rewrites[j] {\n                        if prevIop.index == iop.index {\n                            if prevIop is InsertAfterOp {\n                                iop.text = catOpText(prevIop.text, iop.text)\n                                rewrites[prevIop.instructionIndex] = nil\n                            }\n                            else if prevIop is InsertBeforeOp {\n                                // convert to strings...we're in process of toString'ing\n                                // whole token buffer so no lazy eval issue with any templates\n                                iop.text = catOpText(iop.text, prevIop.text)\n                                // delete redundant prior insert\n                                rewrites[prevIop.instructionIndex] = nil\n                            }\n                        }\n                    }\n                }\n\n                // look for replaces where iop.index is in range; error\n                let ropIndexList = getKindOfOps(&rewrites, ReplaceOp.self, i)\n                for j in ropIndexList  {\n                    if let rop = rewrites[j] {\n                        if iop.index == rop.index {\n                            rop.text = catOpText(iop.text, rop.text)\n                            rewrites[i] = nil    // delete current insert\n                            continue\n                        }\n                        if iop.index >= rop.index && iop.index <= rop.lastIndex {\n                            throw ANTLRError.illegalArgument(msg: \"insert op \\(iop.description) within\" +\n                                \" boundaries of previous \\(rop.description)\")\n\n                        }\n                    }\n                }\n            }\n\n            var m = [Int: RewriteOperation]()\n            for i in 0..<rewritesCount {\n                if let op = rewrites[i] {\n                    if m[op.index] != nil {\n                        throw ANTLRError.illegalArgument(msg: \"should only be one op per index\")\n                    }\n                    m[op.index] = op\n                }\n            }\n\n            return m\n        }\n\n        final func catOpText(_ a: String?, _ b: String?) -> String {\n            let x = a ?? \"\"\n            let y = b ?? \"\"\n            return x + y\n        }\n\n        /// Get all operations before an index of a particular kind\n\n        final func getKindOfOps<T: RewriteOperation>(_ rewrites: inout [RewriteOperation?], _ kind: T.Type, _ before: Int ) -> [Int] {\n\n            let length = min(before, rewrites.count)\n            var op = [Int]()\n            op.reserveCapacity(length)\n            for i in 0..<length {\n                if rewrites[i] is T {\n                    op.append(i)\n                }\n            }\n            return op\n        }\n    }\n\n    /// Our source stream\n    internal var tokens: TokenStream\n\n    /// You may have multiple, named streams of rewrite operations.\n    /// I'm calling these things \"programs.\"\n    /// Maps String (name) &rarr; rewrite (List)\n    /// \n    internal var programs = [String: RewriteOperationArray]()\n\n    /// Map String (program name) &rarr; Integer index\n    internal final var lastRewriteTokenIndexes: [String: Int]\n\n    public init(_ tokens: TokenStream) {\n        self.tokens = tokens\n        programs[DEFAULT_PROGRAM_NAME] = RewriteOperationArray()\n        lastRewriteTokenIndexes = Dictionary<String, Int>()\n    }\n\n    public final func getTokenStream() -> TokenStream {\n        return tokens\n    }\n\n    public func rollback(_ instructionIndex: Int) {\n        rollback(DEFAULT_PROGRAM_NAME, instructionIndex)\n    }\n\n    /// Rollback the instruction stream for a program so that\n    /// the indicated instruction (via instructionIndex) is no\n    /// longer in the stream. UNTESTED!\n    /// \n    public func rollback(_ programName: String, _ instructionIndex: Int) {\n        if let program = programs[programName] {\n            program.rollback(instructionIndex)\n        }\n    }\n\n    public func deleteProgram() {\n        deleteProgram(DEFAULT_PROGRAM_NAME)\n    }\n\n    /// Reset the program so that no instructions exist\n    public func deleteProgram(_ programName: String) {\n        rollback(programName, TokenStreamRewriter.MIN_TOKEN_INDEX)\n    }\n\n    public func insertAfter(_ t: Token, _ text: String) {\n        insertAfter(DEFAULT_PROGRAM_NAME, t, text)\n    }\n\n    public func insertAfter(_ index: Int, _ text: String) {\n        insertAfter(DEFAULT_PROGRAM_NAME, index, text)\n    }\n\n    public func insertAfter(_ programName: String, _ t: Token, _ text: String) {\n        insertAfter(programName, t.getTokenIndex(), text)\n    }\n\n    public func insertAfter(_ programName: String, _ index: Int, _ text: String) {\n        // to insert after, just insert before next index (even if past end)\n        let op = InsertAfterOp(index, text, tokens)\n        let rewrites = getProgram(programName)\n        rewrites.append(op)\n    }\n\n    public func insertBefore(_ t: Token, _ text: String) {\n        insertBefore(DEFAULT_PROGRAM_NAME, t, text)\n    }\n\n    public func insertBefore(_ index: Int, _ text: String) {\n        insertBefore(DEFAULT_PROGRAM_NAME, index, text)\n    }\n\n    public func insertBefore(_ programName: String, _ t: Token, _ text: String) {\n        insertBefore(programName, t.getTokenIndex(), text)\n    }\n\n    public func insertBefore(_ programName: String, _ index: Int, _ text: String) {\n        let op = InsertBeforeOp(index, text, tokens)\n        let rewrites = getProgram(programName)\n        rewrites.append(op)\n    }\n\n    public func replace(_ index: Int, _ text: String) throws {\n        try replace(DEFAULT_PROGRAM_NAME, index, index, text)\n    }\n\n    public func replace(_ from: Int, _ to: Int, _ text: String) throws {\n        try replace(DEFAULT_PROGRAM_NAME, from, to, text)\n    }\n\n    public func replace(_ indexT: Token, _ text: String) throws {\n        try replace(DEFAULT_PROGRAM_NAME, indexT, indexT, text)\n    }\n\n    public func replace(_ from: Token, _ to: Token, _ text: String) throws {\n        try  replace(DEFAULT_PROGRAM_NAME, from, to, text)\n    }\n\n    public func replace(_ programName: String, _ from: Int, _ to: Int, _ text: String?) throws {\n        if from > to || from < 0 || to < 0 || to >= tokens.size() {\n            throw ANTLRError.illegalArgument(msg: \"replace: range invalid: \\(from)..\\(to)(size=\\(tokens.size()))\")\n        }\n        let op = ReplaceOp(from, to, text, tokens)\n        let rewritesArray = getProgram(programName)\n        rewritesArray.append(op)\n    }\n\n    public func replace(_ programName: String, _ from: Token, _ to: Token, _ text: String?) throws {\n        try replace(programName,\n            from.getTokenIndex(),\n            to.getTokenIndex(),\n            text)\n    }\n\n    public func delete(_ index: Int) throws {\n        try delete(DEFAULT_PROGRAM_NAME, index, index)\n    }\n\n    public func delete(_ from: Int, _ to: Int) throws {\n        try delete(DEFAULT_PROGRAM_NAME, from, to)\n    }\n\n    public func delete(_ indexT: Token) throws {\n        try delete(DEFAULT_PROGRAM_NAME, indexT, indexT)\n    }\n\n    public func delete(_ from: Token, _ to: Token) throws {\n        try delete(DEFAULT_PROGRAM_NAME, from, to)\n    }\n\n    public func delete(_ programName: String, _ from: Int, _ to: Int) throws {\n        try replace(programName, from, to, nil)\n    }\n\n    public func delete(_ programName: String, _ from: Token, _ to: Token) throws {\n        try replace(programName, from, to, nil)\n    }\n\n    public func getLastRewriteTokenIndex() -> Int {\n        return getLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME)\n    }\n\n    internal func getLastRewriteTokenIndex(_ programName: String) -> Int {\n        return lastRewriteTokenIndexes[programName] ?? -1\n    }\n\n    internal func setLastRewriteTokenIndex(_ programName: String, _ i: Int) {\n        lastRewriteTokenIndexes[programName] = i\n    }\n\n    internal func getProgram(_ name: String) -> RewriteOperationArray {\n        if let program = programs[name] {\n            return program\n        }\n        else {\n            return initializeProgram(name)\n        }\n    }\n\n    private func initializeProgram(_ name: String) -> RewriteOperationArray {\n        let program = RewriteOperationArray()\n        programs[name] = program\n        return program\n    }\n\n    /// Return the text from the original tokens altered per the\n    /// instructions given to this rewriter.\n    /// \n    public func getText() throws -> String {\n        return try getText(DEFAULT_PROGRAM_NAME, Interval.of(0, tokens.size() - 1))\n    }\n\n    /// Return the text from the original tokens altered per the\n    /// instructions given to this rewriter in programName.\n    /// \n    public func getText(_ programName: String) throws -> String {\n        return try getText(programName, Interval.of(0, tokens.size() - 1))\n    }\n\n    /// Return the text associated with the tokens in the interval from the\n    /// original token stream but with the alterations given to this rewriter.\n    /// The interval refers to the indexes in the original token stream.\n    /// We do not alter the token stream in any way, so the indexes\n    /// and intervals are still consistent. Includes any operations done\n    /// to the first and last token in the interval. So, if you did an\n    /// insertBefore on the first token, you would get that insertion.\n    /// The same is true if you do an insertAfter the stop token.\n    /// \n    public func getText(_ interval: Interval) throws -> String {\n        return try getText(DEFAULT_PROGRAM_NAME, interval)\n    }\n\n    public func getText(_ programName: String, _ interval: Interval) throws -> String {\n        var start = interval.a\n        var stop = interval.b\n\n        // ensure start/end are in range\n        if stop > tokens.size() - 1 {\n            stop = tokens.size() - 1\n        }\n        if start < 0 {\n            start = 0\n        }\n        guard let rewrites = programs[programName], !rewrites.isEmpty else {\n             return try tokens.getText(interval) // no instructions to execute\n        }\n\n        var buf = \"\"\n\n        // First, optimize instruction stream\n        var indexToOp = try rewrites.reduceToSingleOperationPerIndex()\n\n        // Walk buffer, executing instructions and emitting tokens\n        var i = start\n        while i <= stop && i < tokens.size() {\n            let op = indexToOp[i]\n            indexToOp.removeValue(forKey: i)  // remove so any left have index size-1\n            let t = try tokens.get(i)\n            if let op = op {\n                i = try op.execute(&buf) // execute operation and skip\n            }\n            else {\n                // no operation at that index, just dump token\n                if t.getType() != CommonToken.EOF {\n                    buf.append(t.getText()!)\n                }\n                i += 1 // move to next token\n            }\n        }\n\n        // include stuff after end if it's last index in buffer\n        // So, if they did an insertAfter(lastValidIndex, \"foo\"), include\n        // foo if end==lastValidIndex.\n        if stop == tokens.size() - 1 {\n            // Scan any remaining operations after last token\n            // should be included (they will be inserts).\n            for op in indexToOp.values {\n                if op.index >= tokens.size() - 1 {\n                    buf += op.text!\n                }\n            }\n        }\n\n        return buf\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/UnbufferedCharStream.swift",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\nimport Foundation\n\n\n/** Do not buffer up the entire char stream. It does keep a small buffer\n *  for efficiency and also buffers while a mark exists (set by the\n *  lookahead prediction in parser). \"Unbuffered\" here refers to fact\n *  that it doesn't buffer all data, not that's it's on demand loading of char.\n *\n *  Before 4.7, this class used the default environment encoding to convert\n *  bytes to UTF-16, and held the UTF-16 bytes in the buffer as chars.\n *\n *  As of 4.7, the class uses UTF-8 by default, and the buffer holds Unicode\n *  code points in the buffer as ints.\n */\nopen class UnbufferedCharStream: CharStream {\n    private let bufferSize: Int\n\n    /**\n     * A moving window buffer of the data being scanned. While there's a marker,\n     * we keep adding to buffer. Otherwise, {@link #consume consume()} resets so\n     * we start filling at index 0 again.\n     */\n    internal var data: [Int]\n\n    /**\n     * The number of characters currently in {@link #data data}.\n     *\n     * <p>This is not the buffer capacity, that's {@code data.length}.</p>\n     */\n    internal var n = 0\n\n    /**\n     * 0..n-1 index into {@link #data data} of next character.\n     *\n     * <p>The {@code LA(1)} character is {@code data[p]}. If {@code p == n}, we are\n     * out of buffered characters.</p>\n     */\n    internal var p = 0\n\n    /**\n     * Count up with {@link #mark mark()} and down with\n     * {@link #release release()}. When we {@code release()} the last mark,\n     * {@code numMarkers} reaches 0 and we reset the buffer. Copy\n     * {@code data[p]..data[n-1]} to {@code data[0]..data[(n-1)-p]}.\n     */\n    internal var numMarkers = 0\n\n    /**\n     * This is the {@code LA(-1)} character for the current position.\n     */\n    internal var lastChar = -1\n\n    /**\n     * When {@code numMarkers > 0}, this is the {@code LA(-1)} character for the\n     * first character in {@link #data data}. Otherwise, this is unspecified.\n     */\n    internal var lastCharBufferStart = 0\n\n    /**\n     * Absolute character index. It's the index of the character about to be\n     * read via {@code LA(1)}. Goes from 0 to the number of characters in the\n     * entire stream, although the stream size is unknown before the end is\n     * reached.\n     */\n    internal var currentCharIndex = 0\n\n    internal let input: InputStream\n    private var unicodeIterator: UnicodeScalarStreamIterator\n\n\n    /** The name or source of this char stream. */\n    public var name: String = \"\"\n\n    public init(_ input: InputStream, _ bufferSize: Int = 256) {\n        self.input = input\n        self.bufferSize = bufferSize\n        self.data = [Int](repeating: 0, count: bufferSize)\n        let si = UInt8StreamIterator(input)\n        self.unicodeIterator = UnicodeScalarStreamIterator(si)\n    }\n\n    public func consume() throws {\n        if try LA(1) == CommonToken.EOF {\n            throw ANTLRError.illegalState(msg: \"cannot consume EOF\")\n        }\n\n        // buf always has at least data[p==0] in this method due to ctor\n        lastChar = data[p]   // track last char for LA(-1)\n\n        if p == n - 1 && numMarkers == 0 {\n            n = 0\n            p = -1 // p++ will leave this at 0\n            lastCharBufferStart = lastChar\n        }\n\n        p += 1\n        currentCharIndex += 1\n        sync(1)\n    }\n\n    /**\n     * Make sure we have 'need' elements from current position {@link #p p}.\n     * Last valid {@code p} index is {@code data.length-1}. {@code p+need-1} is\n     * the char index 'need' elements ahead. If we need 1 element,\n     * {@code (p+1-1)==p} must be less than {@code data.length}.\n     */\n    internal func sync(_ want: Int) {\n        let need = (p + want - 1) - n + 1 // how many more elements we need?\n        if need > 0 {\n            fill(need)\n        }\n    }\n\n    /**\n     * Add {@code n} characters to the buffer. Returns the number of characters\n     * actually added to the buffer. If the return value is less than {@code n},\n     * then EOF was reached before {@code n} characters could be added.\n     */\n    @discardableResult internal func fill(_ toAdd: Int) -> Int {\n        for i in 0 ..< toAdd {\n            if n > 0 && data[n - 1] == CommonToken.EOF {\n                return i\n            }\n\n            guard let c = nextChar() else {\n                return i\n            }\n            add(c)\n        }\n\n        return n\n    }\n\n    /**\n     * Override to provide different source of characters than\n     * {@link #input input}.\n     */\n    internal func nextChar() -> Int? {\n        if let next = unicodeIterator.next() {\n            return Int(next.value)\n        }\n        else if unicodeIterator.hasErrorOccurred {\n            return nil\n        }\n        else {\n            return nil\n        }\n    }\n\n    internal func add(_ c: Int) {\n        if n >= data.count {\n            data += [Int](repeating: 0, count: data.count)\n        }\n        data[n] = c\n        n += 1\n    }\n\n    public func LA(_ i: Int) throws -> Int {\n        if i == -1 {\n            return lastChar // special case\n        }\n        sync(i)\n        let index = p + i - 1\n        if index < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"\")\n        }\n        if index >= n {\n            return CommonToken.EOF\n        }\n        return data[index]\n    }\n\n    /**\n     * Return a marker that we can release later.\n     *\n     * <p>The specific marker value used for this class allows for some level of\n     * protection against misuse where {@code seek()} is called on a mark or\n     * {@code release()} is called in the wrong order.</p>\n     */\n    public func mark() -> Int {\n        if numMarkers == 0 {\n            lastCharBufferStart = lastChar\n        }\n\n        let mark = -numMarkers - 1\n        numMarkers += 1\n        return mark\n    }\n\n    /** Decrement number of markers, resetting buffer if we hit 0.\n     * @param marker\n     */\n    public func release(_ marker: Int) throws {\n        let expectedMark = -numMarkers\n        if marker != expectedMark {\n            preconditionFailure(\"release() called with an invalid marker.\")\n        }\n\n        numMarkers -= 1\n        if numMarkers == 0 && p > 0 {\n            // release buffer when we can, but don't do unnecessary work\n\n            // Copy data[p]..data[n-1] to data[0]..data[(n-1)-p], reset ptrs\n            // p is last valid char; move nothing if p==n as we have no valid char\n            if p == n {\n                if data.count != bufferSize {\n                    data = [Int](repeating: 0, count: bufferSize)\n                }\n                n = 0\n            }\n            else {\n                data = Array(data[p ..< n])\n                n -= p\n            }\n            p = 0\n            lastCharBufferStart = lastChar\n        }\n    }\n\n    public func index() -> Int {\n        return currentCharIndex\n    }\n\n    /** Seek to absolute character index, which might not be in the current\n     *  sliding window.  Move {@code p} to {@code index-bufferStartIndex}.\n     */\n    public func seek(_ index_: Int) throws {\n        var index = index_\n\n        if index == currentCharIndex {\n            return\n        }\n\n        if index > currentCharIndex {\n            sync(index - currentCharIndex)\n            index = min(index, getBufferStartIndex() + n - 1)\n        }\n\n        // index == to bufferStartIndex should set p to 0\n        let i = index - getBufferStartIndex()\n        if i < 0 {\n            throw ANTLRError.illegalArgument(msg: \"cannot seek to negative index \\(index)\")\n        }\n        else if i >= n {\n            let si = getBufferStartIndex()\n            let ei = si + n\n            let msg = \"seek to index outside buffer: \\(index) not in \\(si)..\\(ei)\"\n            throw ANTLRError.unsupportedOperation(msg: msg)\n        }\n\n        p = i\n        currentCharIndex = index\n        if p == 0 {\n            lastChar = lastCharBufferStart\n        }\n        else {\n            lastChar = data[p - 1]\n        }\n    }\n\n    public func size() -> Int {\n        preconditionFailure(\"Unbuffered stream cannot know its size\")\n    }\n\n    public func getSourceName() -> String {\n        return name\n    }\n\n    public func getText(_ interval: Interval) throws -> String {\n        if interval.a < 0 || interval.b < interval.a - 1 {\n            throw ANTLRError.illegalArgument(msg: \"invalid interval\")\n        }\n\n        let bufferStartIndex = getBufferStartIndex()\n        if n > 0 &&\n            data[n - 1] == CommonToken.EOF &&\n            interval.a + interval.length() > bufferStartIndex + n {\n            throw ANTLRError.illegalArgument(msg: \"the interval extends past the end of the stream\")\n        }\n\n        if interval.a < bufferStartIndex || interval.b >= bufferStartIndex + n {\n            let msg = \"interval \\(interval) outside buffer: \\(bufferStartIndex)...\\(bufferStartIndex + n - 1)\"\n            throw ANTLRError.unsupportedOperation(msg: msg)\n        }\n\n        if interval.b < interval.a {\n            // The EOF token.\n            return \"\"\n        }\n\n        // convert from absolute to local index\n        let i = interval.a - bufferStartIndex\n        let j = interval.b - bufferStartIndex\n\n        // Convert from Int codepoints to a String.\n        let codepoints = data[i ... j].map { Character(Unicode.Scalar($0)!) }\n        return String(codepoints)\n    }\n\n    internal func getBufferStartIndex() -> Int {\n        return currentCharIndex - p\n    }\n}\n\n\nfileprivate struct UInt8StreamIterator: IteratorProtocol {\n    private static let bufferSize = 1024\n\n    private let stream: InputStream\n    private var buffer = [UInt8](repeating: 0, count: UInt8StreamIterator.bufferSize)\n    private var buffGen: IndexingIterator<ArraySlice<UInt8>>\n\n    var hasErrorOccurred = false\n\n\n    init(_ stream: InputStream) {\n        self.stream = stream\n        self.buffGen = buffer[0..<0].makeIterator()\n    }\n\n    mutating func next() -> UInt8? {\n        if let result = buffGen.next() {\n            return result\n        }\n\n        if hasErrorOccurred {\n            return nil\n        }\n\n        switch stream.streamStatus {\n            case .notOpen, .writing, .closed:\n                preconditionFailure()\n            case .atEnd:\n                return nil\n            case .error:\n                hasErrorOccurred = true\n                return nil\n            case .opening, .open, .reading:\n                break\n        }\n\n        let count = stream.read(&buffer, maxLength: buffer.count)\n        if count < 0 {\n            hasErrorOccurred = true\n            return nil\n        }\n        else if count == 0 {\n            return nil\n        }\n\n        buffGen = buffer.prefix(count).makeIterator()\n        return buffGen.next()\n    }\n}\n\n\nfileprivate struct UnicodeScalarStreamIterator: IteratorProtocol {\n    private var streamIterator: UInt8StreamIterator\n    private var codec = Unicode.UTF8()\n\n    var hasErrorOccurred = false\n\n    init(_ streamIterator: UInt8StreamIterator) {\n        self.streamIterator = streamIterator\n    }\n\n    mutating func next() -> Unicode.Scalar? {\n        if streamIterator.hasErrorOccurred {\n            hasErrorOccurred = true\n            return nil\n        }\n\n        switch codec.decode(&streamIterator) {\n        case .scalarValue(let scalar):\n            return scalar\n        case .emptyInput:\n            return nil\n        case .error:\n            hasErrorOccurred = true\n            return nil\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/UnbufferedTokenStream.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\npublic class UnbufferedTokenStream: TokenStream {\n    internal var tokenSource: TokenSource\n\n    /// \n    /// A moving window buffer of the data being scanned. While there's a marker,\n    /// we keep adding to buffer. Otherwise, _#consume consume()_ resets so\n    /// we start filling at index 0 again.\n    /// \n    internal var tokens = [Token]()\n\n    /// \n    /// The number of tokens currently in `self.tokens`.\n    /// \n    /// This is not the buffer capacity, that's `self.tokens.count`.\n    /// \n    internal var n = 0\n\n    /// \n    /// `0...n-1` index into `self.tokens` of next token.\n    /// \n    /// The `LT(1)` token is `tokens[p]`. If `p == n`, we are\n    /// out of buffered tokens.\n    /// \n    internal var p = 0\n\n    /// \n    /// Count up with _#mark mark()_ and down with\n    /// _#release release()_. When we `release()` the last mark,\n    /// `numMarkers` reaches 0 and we reset the buffer. Copy\n    /// `tokens[p]..tokens[n-1]` to `tokens[0]..tokens[(n-1)-p]`.\n    /// \n    internal var numMarkers = 0\n\n    /// \n    /// This is the `LT(-1)` token for the current position.\n    /// \n    internal var lastToken: Token!\n\n    /// \n    /// When `numMarkers > 0`, this is the `LT(-1)` token for the\n    /// first token in _#tokens_. Otherwise, this is `null`.\n    /// \n    internal var lastTokenBufferStart: Token!\n\n    /// \n    /// Absolute token index. It's the index of the token about to be read via\n    /// `LT(1)`. Goes from 0 to the number of tokens in the entire stream,\n    /// although the stream size is unknown before the end is reached.\n    /// \n    /// This value is used to set the token indexes if the stream provides tokens\n    /// that implement _org.antlr.v4.runtime.WritableToken_.\n    /// \n    internal var currentTokenIndex = 0\n\n\n    public init(_ tokenSource: TokenSource) throws {\n        self.tokenSource = tokenSource\n        try fill(1) // prime the pump\n    }\n\n\n    public func get(_ i: Int) throws -> Token {\n        // get absolute index\n        let bufferStartIndex = getBufferStartIndex()\n        if i < bufferStartIndex || i >= bufferStartIndex + n {\n            throw ANTLRError.indexOutOfBounds(msg: \"get(\\(i)) outside buffer: \\(bufferStartIndex)..\\(bufferStartIndex + n)\")\n        }\n        return tokens[i - bufferStartIndex]\n    }\n\n\n    public func LT(_ i: Int) throws -> Token? {\n        if i == -1 {\n            return lastToken\n        }\n\n        try sync(i)\n        let index: Int = p + i - 1\n        if index < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"LT(\\(i) gives negative index\")\n        }\n\n        if index >= n {\n            //Token.EOF\n            assert(n > 0 && tokens[n - 1].getType() == CommonToken.EOF, \"Expected: n>0&&tokens[n-1].getType()==Token.EOF\")\n            return tokens[n - 1]\n        }\n\n        return tokens[index]\n    }\n\n\n    public func LA(_ i: Int) throws -> Int {\n        return try LT(i)!.getType()\n    }\n\n\n    public func getTokenSource() -> TokenSource {\n        return tokenSource\n    }\n\n\n    public func getText() -> String {\n        return \"\"\n    }\n\n\n    public func getText(_ ctx: RuleContext) throws -> String {\n        return try getText(ctx.getSourceInterval())\n    }\n\n\n    public func getText(_ start: Token?, _ stop: Token?) throws -> String {\n        return try getText(Interval.of(start!.getTokenIndex(), stop!.getTokenIndex()))\n    }\n\n\n    public func consume() throws {\n        //Token.EOF\n        if try  LA(1) == CommonToken.EOF {\n            throw ANTLRError.illegalState(msg: \"cannot consume EOF\")\n        }\n\n        // buf always has at least tokens[p==0] in this method due to ctor\n        lastToken = tokens[p]   // track last token for LT(-1)\n\n        // if we're at last token and no markers, opportunity to flush buffer\n        if p == n - 1 && numMarkers == 0 {\n            n = 0\n            p = -1 // p++ will leave this at 0\n            lastTokenBufferStart = lastToken\n        }\n\n        p += 1\n        currentTokenIndex += 1\n        try sync(1)\n    }\n\n    /// Make sure we have 'need' elements from current position _#p p_. Last valid\n    /// `p` index is `tokens.length-1`.  `p+need-1` is the tokens index 'need' elements\n    /// ahead.  If we need 1 element, `(p+1-1)==p` must be less than `tokens.length`.\n    /// \n    internal func sync(_ want: Int) throws {\n        let need: Int = (p + want - 1) - n + 1 // how many more elements we need?\n        if need > 0 {\n            try fill(need)\n        }\n    }\n\n    /// \n    /// Add `n` elements to the buffer. Returns the number of tokens\n    /// actually added to the buffer. If the return value is less than `n`,\n    /// then EOF was reached before `n` tokens could be added.\n    /// \n    @discardableResult\n    internal func fill(_ n: Int) throws -> Int {\n        for i in 0..<n {\n            if self.n > 0 && tokens[self.n - 1].getType() == CommonToken.EOF {\n                return i\n            }\n\n            let t: Token = try tokenSource.nextToken()\n            add(t)\n        }\n\n        return n\n    }\n\n    internal func add(_ t: Token) {\n        if n >= tokens.count {\n            //TODO: array count buffer size\n            //tokens = Arrays.copyOf(tokens, tokens.length * 2);\n        }\n\n        if let wt = t as? WritableToken {\n            wt.setTokenIndex(getBufferStartIndex() + n)\n        }\n\n        tokens[n] = t\n        n += 1\n    }\n\n    /// \n    /// Return a marker that we can release later.\n    /// \n    /// The specific marker value used for this class allows for some level of\n    /// protection against misuse where `seek()` is called on a mark or\n    /// `release()` is called in the wrong order.\n    /// \n\n    public func mark() -> Int {\n        if numMarkers == 0 {\n            lastTokenBufferStart = lastToken\n        }\n\n        let mark = -numMarkers - 1\n        numMarkers += 1\n        return mark\n    }\n\n\n    public func release(_ marker: Int) throws {\n        let expectedMark = -numMarkers\n        if marker != expectedMark {\n            throw ANTLRError.illegalState(msg: \"release() called with an invalid marker.\")\n        }\n\n        numMarkers -= 1\n        if numMarkers == 0 {\n            // can we release buffer?\n            if p > 0 {\n                // Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs\n                // p is last valid token; move nothing if p==n as we have no valid char\n                tokens = Array(tokens[p ... n - 1])\n                n = n - p\n                p = 0\n            }\n\n            lastTokenBufferStart = lastToken\n        }\n    }\n\n\n    public func index() -> Int {\n        return currentTokenIndex\n    }\n\n\n    public func seek(_ index: Int) throws {\n        var index = index\n        // seek to absolute index\n        if index == currentTokenIndex {\n            return\n        }\n\n        if index > currentTokenIndex {\n            try sync(index - currentTokenIndex)\n            index = min(index, getBufferStartIndex() + n - 1)\n        }\n\n        let bufferStartIndex = getBufferStartIndex()\n        let i = index - bufferStartIndex\n        if i < 0 {\n            throw ANTLRError.illegalState(msg: \"cannot seek to negative index \\(index)\")\n\n        }\n        else if i >= n {\n            throw ANTLRError.unsupportedOperation(msg: \"seek to index outside buffer: \\(index) not in \\(bufferStartIndex)..<\\(bufferStartIndex + n)\")\n        }\n\n        p = i\n        currentTokenIndex = index\n        if p == 0 {\n            lastToken = lastTokenBufferStart\n        } else {\n            lastToken = tokens[p - 1]\n        }\n    }\n\n\n    public func size() -> Int {\n        fatalError(\"Unbuffered stream cannot know its size\")\n    }\n\n\n    public func getSourceName() -> String {\n        return tokenSource.getSourceName()\n    }\n\n\n    public func getText(_ interval: Interval) throws -> String {\n        let bufferStartIndex = getBufferStartIndex()\n        let bufferStopIndex = bufferStartIndex + tokens.count - 1\n\n        let start = interval.a\n        let stop = interval.b\n        if start < bufferStartIndex || stop > bufferStopIndex {\n            throw ANTLRError.unsupportedOperation(msg: \"interval \\(interval) not in token buffer window: \\(bufferStartIndex)...\\(bufferStopIndex)\")\n        }\n\n        let a = start - bufferStartIndex\n        let b = stop - bufferStartIndex\n\n        var buf = \"\"\n        for t in tokens[a...b] {\n            buf += t.getText()!\n        }\n        return buf\n    }\n\n    internal final func getBufferStartIndex() -> Int {\n        return currentTokenIndex - p\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/VocabularySingle.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// This class provides a default implementation of the _org.antlr.v4.runtime.Vocabulary_\n/// interface.\n/// \n/// - Author: Sam Harwell\n/// \n\npublic class Vocabulary: Hashable {\n    private static let EMPTY_NAMES: [String?] = [String?](repeating: \"\", count: 1)\n\n    /// \n    /// Gets an empty _org.antlr.v4.runtime.Vocabulary_ instance.\n    /// \n    /// \n    /// No literal or symbol names are assigned to token types, so\n    /// _#getDisplayName(int)_ returns the numeric value for all tokens\n    /// except _org.antlr.v4.runtime.Token#EOF_.\n    /// \n    public static let EMPTY_VOCABULARY: Vocabulary = Vocabulary(EMPTY_NAMES, EMPTY_NAMES, EMPTY_NAMES)\n\n\n    private let literalNames: [String?]\n\n    private let symbolicNames: [String?]\n\n    private let displayNames: [String?]\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.Vocabulary_ from the specified\n    /// literal and symbolic token names.\n    /// \n    /// - SeeAlso: #getLiteralName(int)\n    /// - SeeAlso: #getSymbolicName(int)\n    /// - Parameter literalNames: The literal names assigned to tokens, or `null`\n    /// if no literal names are assigned.\n    /// - Parameter symbolicNames: The symbolic names assigned to tokens, or\n    /// `null` if no symbolic names are assigned.\n    /// \n    /// \n    public convenience init(_ literalNames: [String?], _ symbolicNames: [String?]) {\n        self.init(literalNames, symbolicNames, nil)\n    }\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.Vocabulary_ from the specified\n    /// literal, symbolic, and display token names.\n    /// \n    /// - SeeAlso: #getLiteralName(int)\n    /// - SeeAlso: #getSymbolicName(int)\n    /// - SeeAlso: #getDisplayName(int)\n    /// - Parameter literalNames: The literal names assigned to tokens, or `null`\n    /// if no literal names are assigned.\n    /// - Parameter symbolicNames: The symbolic names assigned to tokens, or\n    /// `null` if no symbolic names are assigned.\n    /// - Parameter displayNames: The display names assigned to tokens, or `null`\n    /// to use the values in `literalNames` and `symbolicNames` as\n    /// the source of display names, as described in\n    /// _#getDisplayName(int)_.\n    /// \n    /// \n    public init(_ literalNames: [String?]?, _ symbolicNames: [String?]?, _ displayNames: [String?]?) {\n        self.literalNames = literalNames ?? Vocabulary.EMPTY_NAMES\n        self.symbolicNames = symbolicNames ?? Vocabulary.EMPTY_NAMES\n        self.displayNames = displayNames ?? Vocabulary.EMPTY_NAMES\n    }\n\n    /// \n    /// Returns a _org.antlr.v4.runtime.Vocabulary_ instance from the specified set of token\n    /// names. This method acts as a compatibility layer for the single\n    /// `tokenNames` array generated by previous releases of ANTLR.\n    /// \n    /// The resulting vocabulary instance returns `null` for\n    /// _#getLiteralName(int)_ and _#getSymbolicName(int)_, and the\n    /// value from `tokenNames` for the display names.\n    /// \n    /// - Parameter tokenNames: The token names, or `null` if no token names are\n    /// available.\n    /// - Returns: A _org.antlr.v4.runtime.Vocabulary_ instance which uses `tokenNames` for\n    /// the display names of tokens.\n    /// \n    public static func fromTokenNames(_ tokenNames: [String?]?) -> Vocabulary {\n        guard let tokenNames = tokenNames, tokenNames.count > 0 else {\n            return EMPTY_VOCABULARY\n        }\n\n        var literalNames = tokenNames\n        var symbolicNames = tokenNames\n        let length = tokenNames.count\n        for i in 0..<length {\n            guard let tokenName = tokenNames[i] else {\n                continue\n            }\n            if let firstChar = tokenName.first {\n                if firstChar == \"\\'\" {\n                    symbolicNames[i] = nil\n                    continue\n                }\n                else if String(firstChar).uppercased() != String(firstChar) {\n                    literalNames[i] = nil\n                    continue\n                }\n            }\n\n            // wasn't a literal or symbolic name\n            literalNames[i] = nil\n            symbolicNames[i] = nil\n        }\n\n        return Vocabulary(literalNames, symbolicNames, tokenNames)\n    }\n\n\n    public func getLiteralName(_ tokenType: Int) -> String? {\n        if tokenType >= 0 && tokenType < literalNames.count {\n            return literalNames[tokenType]\n        }\n\n        return nil\n    }\n\n\n    public func getSymbolicName(_ tokenType: Int) -> String? {\n        if tokenType >= 0 && tokenType < symbolicNames.count {\n            return symbolicNames[tokenType]\n        }\n        if tokenType == CommonToken.EOF {\n            return \"EOF\"\n        }\n\n        return nil\n    }\n\n\n    public func getDisplayName(_ tokenType: Int) -> String {\n        if tokenType >= 0 && tokenType < displayNames.count {\n            if let displayName = displayNames[tokenType] {\n                return displayName\n            }\n        }\n\n        if let literalName = getLiteralName(tokenType) {\n            return literalName\n        }\n\n        if let symbolicName = getSymbolicName(tokenType) {\n            return symbolicName\n        }\n\n        return String(tokenType)\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n}\n\npublic func ==(lhs: Vocabulary, rhs: Vocabulary) -> Bool {\n    return lhs === rhs\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/WritableToken.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\npublic protocol WritableToken: Token {\n    func setText(_ text: String)\n\n    func setType(_ ttype: Int)\n\n    func setLine(_ line: Int)\n\n    func setCharPositionInLine(_ pos: Int)\n\n    func setChannel(_ channel: Int)\n\n    func setTokenIndex(_ index: Int)\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATN.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic class ATN {\n    public static let INVALID_ALT_NUMBER = 0\n\n    public private(set) final var states = [ATNState?]()\n\n    /// \n    /// Each subrule/rule is a decision point and we must track them so we\n    /// can go back later and build DFA predictors for them.  This includes\n    /// all the rules, subrules, optional blocks, ()+, ()* etc...\n    /// \n    public private(set) final var decisionToState = [DecisionState]()\n\n    /// \n    /// Maps from rule index to starting state number.\n    /// \n    public internal(set) final var ruleToStartState: [RuleStartState]!\n\n    /// \n    /// Maps from rule index to stop state number.\n    /// \n    public internal(set) final var ruleToStopState: [RuleStopState]!\n\n    /// \n    /// The type of the ATN.\n    /// \n    public let grammarType: ATNType\n\n    /// \n    /// The maximum value for any symbol recognized by a transition in the ATN.\n    /// \n    public let maxTokenType: Int\n\n    /// \n    /// For lexer ATNs, this maps the rule index to the resulting token type.\n    /// For parser ATNs, this maps the rule index to the generated bypass token\n    /// type if the `ATNDeserializationOptions.generateRuleBypassTransitions`\n    /// deserialization option was specified; otherwise, this is `null`.\n    /// \n    public internal(set) final var ruleToTokenType: [Int]!\n\n    /// \n    /// For lexer ATNs, this is an array of _org.antlr.v4.runtime.atn.LexerAction_ objects which may\n    /// be referenced by action transitions in the ATN.\n    /// \n    public internal(set) final var lexerActions: [LexerAction]!\n\n    public internal(set) final var modeToStartState = [TokensStartState]()\n\n    /// \n    /// Used for runtime deserialization of ATNs from strings\n    /// \n    public init(_ grammarType: ATNType, _ maxTokenType: Int) {\n        self.grammarType = grammarType\n        self.maxTokenType = maxTokenType\n    }\n\n    /// \n    /// Compute the set of valid tokens that can occur starting in state `s`.\n    /// If `ctx` is null, the set of tokens will not include what can follow\n    /// the rule surrounding `s`. In other words, the set will be\n    /// restricted to tokens reachable staying within `s`'s rule.\n    /// \n    public func nextTokens(_ s: ATNState, _ ctx: RuleContext?) -> IntervalSet {\n        let anal = LL1Analyzer(self)\n        let next = anal.LOOK(s, ctx)\n        return next\n    }\n\n    /// \n    /// Compute the set of valid tokens that can occur starting in `s` and\n    /// staying in same rule. _org.antlr.v4.runtime.Token#EPSILON_ is in set if we reach end of\n    /// rule.\n    /// \n    public func nextTokens(_ s: ATNState) -> IntervalSet {\n        if let nextTokenWithinRule = s.nextTokenWithinRule {\n            return nextTokenWithinRule\n        }\n        let intervalSet = nextTokens(s, nil)\n        s.nextTokenWithinRule = intervalSet\n        intervalSet.makeReadonly()\n        return intervalSet\n    }\n\n    public func addState(_ state: ATNState?) {\n        if let state = state {\n            state.atn = self\n            state.stateNumber = states.count\n        }\n\n        states.append(state)\n    }\n\n    public func removeState(_ state: ATNState) {\n        states[state.stateNumber] = nil\n        //states.set(state.stateNumber, nil); // just free mem, don't shift states in list\n    }\n    @discardableResult\n    public func defineDecisionState(_ s: DecisionState) -> Int {\n        decisionToState.append(s)\n        s.decision = decisionToState.count-1\n        return s.decision\n    }\n\n    public func getDecisionState(_ decision: Int) -> DecisionState? {\n        if  !decisionToState.isEmpty  {\n            return decisionToState[decision]\n        }\n        return nil\n    }\n\n    public func getNumberOfDecisions() -> Int {\n        return decisionToState.count\n    }\n\n    /// \n    /// Computes the set of input symbols which could follow ATN state number\n    /// `stateNumber` in the specified full `context`. This method\n    /// considers the complete parser context, but does not evaluate semantic\n    /// predicates (i.e. all predicates encountered during the calculation are\n    /// assumed true). If a path in the ATN exists from the starting state to the\n    /// _org.antlr.v4.runtime.atn.RuleStopState_ of the outermost context without matching any\n    /// symbols, _org.antlr.v4.runtime.Token#EOF_ is added to the returned set.\n    /// \n    /// If `context` is `null`, it is treated as\n    /// _org.antlr.v4.runtime.ParserRuleContext#EMPTY_.\n    /// \n    /// - parameter stateNumber: the ATN state number\n    /// - parameter context: the full parse context\n    /// - returns: The set of potentially valid input symbols which could follow the\n    /// specified state in the specified context.\n    /// - throws: _ANTLRError.illegalArgument_ if the ATN does not contain a state with\n    /// number `stateNumber`\n    /// \n    public func getExpectedTokens(_ stateNumber: Int, _ context: RuleContext) throws -> IntervalSet {\n        guard states.indices.contains(stateNumber) else {\n            throw ANTLRError.illegalArgument(msg: \"Invalid state number.\")\n        }\n\n        var ctx: RuleContext? = context\n        let s = states[stateNumber]!\n        var following = nextTokens(s)\n        if !following.contains(CommonToken.EPSILON) {\n            return following\n        }\n\n        let expected = IntervalSet()\n        try! expected.addAll(following)\n        try! expected.remove(CommonToken.EPSILON)\n\n        while let ctxWrap = ctx, ctxWrap.invokingState >= 0 && following.contains(CommonToken.EPSILON) {\n            let invokingState = states[ctxWrap.invokingState]!\n            let rt = invokingState.transition(0) as! RuleTransition\n            following = nextTokens(rt.followState)\n            try! expected.addAll(following)\n            try! expected.remove(CommonToken.EPSILON)\n            ctx = ctxWrap.parent\n        }\n\n        if following.contains(CommonToken.EPSILON) {\n            try! expected.add(CommonToken.EOF)\n        }\n\n        return expected\n    }\n\n    public final func appendDecisionToState(_ state: DecisionState) {\n        decisionToState.append(state)\n    }\n    public final func appendModeToStartState(_ state: TokensStartState) {\n        modeToStartState.append(state)\n    }\n\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATNConfig.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n///\n/// A tuple: (ATN state, predicted alt, syntactic, semantic context).\n/// The syntactic context is a graph-structured stack node whose\n/// path(s) to the root is the rule invocation(s)\n/// chain used to arrive at the state.  The semantic context is\n/// the tree of semantic predicates encountered before reaching\n/// an ATN state.\n///\n\n\npublic class ATNConfig: Hashable, CustomStringConvertible {\n    ///\n    /// This field stores the bit mask for implementing the\n    /// _#isPrecedenceFilterSuppressed_ property as a bit within the\n    /// existing _#reachesIntoOuterContext_ field.\n    ///\n    private static let SUPPRESS_PRECEDENCE_FILTER: Int = 0x40000000\n\n    ///\n    /// The ATN state associated with this configuration\n    ///\n    public final let state: ATNState\n\n    ///\n    /// What alt (or lexer rule) is predicted by this configuration\n    ///\n    public final let alt: Int\n\n    ///\n    /// The stack of invoking states leading to the rule/states associated\n    /// with this config.  We track only those contexts pushed during\n    /// execution of the ATN simulator.\n    ///\n    public internal(set) final var context: PredictionContext?\n\n    ///\n    /// We cannot execute predicates dependent upon local context unless\n    /// we know for sure we are in the correct context. Because there is\n    /// no way to do this efficiently, we simply cannot evaluate\n    /// dependent predicates unless we are in the rule that initially\n    /// invokes the ATN simulator.\n    ///\n    ///\n    /// closure() tracks the depth of how far we dip into the outer context:\n    /// depth &gt; 0.  Note that it may not be totally accurate depth since I\n    /// don't ever decrement. TODO: make it a boolean then\n    ///\n    ///\n    /// For memory efficiency, the _#isPrecedenceFilterSuppressed_ method\n    /// is also backed by this field. Since the field is publicly accessible, the\n    /// highest bit which would not cause the value to become negative is used to\n    /// store this field. This choice minimizes the risk that code which only\n    /// compares this value to 0 would be affected by the new purpose of the\n    /// flag. It also ensures the performance of the existing _org.antlr.v4.runtime.atn.ATNConfig_\n    /// constructors as well as certain operations like\n    /// _org.antlr.v4.runtime.atn.ATNConfigSet#add(org.antlr.v4.runtime.atn.ATNConfig, DoubleKeyMap)_ method are\n    /// __completely__ unaffected by the change.\n    ///\n    public internal(set) final var reachesIntoOuterContext: Int = 0\n\n    public final let semanticContext: SemanticContext\n\n    public init(_ state: ATNState,\n                _ alt: Int,\n                _ context: PredictionContext?,\n                _ semanticContext: SemanticContext = SemanticContext.Empty.Instance) {\n        self.state = state\n        self.alt = alt\n        self.context = context\n        self.semanticContext = semanticContext\n    }\n\n    public convenience init(_ c: ATNConfig, _ state: ATNState) {\n        self.init(c, state, c.context, c.semanticContext)\n    }\n\n    public convenience init(_ c: ATNConfig, _ state: ATNState,\n                            _ semanticContext: SemanticContext) {\n        self.init(c, state, c.context, semanticContext)\n    }\n\n    public convenience init(_ c: ATNConfig,\n                            _ semanticContext: SemanticContext) {\n        self.init(c, c.state, c.context, semanticContext)\n    }\n\n    public convenience init(_ c: ATNConfig, _ state: ATNState,\n                            _ context: PredictionContext?) {\n        self.init(c, state, context, c.semanticContext)\n    }\n\n    public init(_ c: ATNConfig, _ state: ATNState,\n                _ context: PredictionContext?,\n                _ semanticContext: SemanticContext) {\n        self.state = state\n        self.alt = c.alt\n        self.context = context\n        self.semanticContext = semanticContext\n        self.reachesIntoOuterContext = c.reachesIntoOuterContext\n    }\n\n    ///\n    /// This method gets the value of the _#reachesIntoOuterContext_ field\n    /// as it existed prior to the introduction of the\n    /// _#isPrecedenceFilterSuppressed_ method.\n    ///\n    public final func getOuterContextDepth() -> Int {\n        return reachesIntoOuterContext & ~Self.SUPPRESS_PRECEDENCE_FILTER\n    }\n\n    public final func isPrecedenceFilterSuppressed() -> Bool {\n        return (reachesIntoOuterContext & Self.SUPPRESS_PRECEDENCE_FILTER) != 0\n    }\n\n    public final func setPrecedenceFilterSuppressed(_ value: Bool) {\n        if value {\n            self.reachesIntoOuterContext |= Self.SUPPRESS_PRECEDENCE_FILTER\n        } else {\n            self.reachesIntoOuterContext &= ~Self.SUPPRESS_PRECEDENCE_FILTER\n        }\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(state.stateNumber)\n        hasher.combine(alt)\n        hasher.combine(context)\n        hasher.combine(semanticContext)\n    }\n\n    public var description: String {\n        //return \"MyClass \\(string)\"\n        return toString(nil, true)\n    }\n    public func toString<T>(_ recog: Recognizer<T>?, _ showAlt: Bool) -> String {\n        var buf = \"(\\(state)\"\n        if showAlt {\n            buf += \",\\(alt)\"\n        }\n        if let context = context {\n            buf += \",[\\(context)]\"\n        }\n        if semanticContext != SemanticContext.Empty.Instance {\n            buf += \",\\(semanticContext)\"\n        }\n        let outerDepth = getOuterContextDepth()\n        if outerDepth > 0 {\n            buf += \",up=\\(outerDepth)\"\n        }\n        buf += \")\"\n        return buf\n    }\n}\n\n///\n/// An ATN configuration is equal to another if both have\n/// the same state, they predict the same alternative, and\n/// syntactic/semantic contexts are the same.\n///\npublic func ==(lhs: ATNConfig, rhs: ATNConfig) -> Bool {\n\n    if lhs === rhs {\n        return true\n    }\n\n    if let l = lhs as? LexerATNConfig, let r = rhs as? LexerATNConfig {\n        return l == r\n\n\n    }\n\n    if lhs.state.stateNumber != rhs.state.stateNumber {\n        return false\n    }\n    if lhs.alt != rhs.alt {\n        return false\n    }\n\n    if lhs.isPrecedenceFilterSuppressed() != rhs.isPrecedenceFilterSuppressed() {\n        return false\n    }\n\n    if lhs.context != rhs.context {\n        return false\n    }\n\n    return  lhs.semanticContext == rhs.semanticContext\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATNConfigSet.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\n///\n/// Specialized _java.util.Set_`<`_org.antlr.v4.runtime.atn.ATNConfig_`>` that can track\n/// info about the set, with support for combining similar configurations using a\n/// graph-structured stack.\n///\npublic final class ATNConfigSet: Hashable, CustomStringConvertible {\n    ///\n    /// The reason that we need this is because we don't want the hash map to use\n    /// the standard hash code and equals. We need all configurations with the same\n    /// `(s,i,_,semctx)` to be equal. Unfortunately, this key effectively doubles\n    /// the number of objects associated with ATNConfigs. The other solution is to\n    /// use a hash table that lets us specify the equals/hashcode operation.\n    ///\n\n\n    ///\n    /// Indicates that the set of configurations is read-only. Do not\n    /// allow any code to manipulate the set; DFA states will point at\n    /// the sets and they must not change. This does not protect the other\n    /// fields; in particular, conflictingAlts is set after\n    /// we've made this readonly.\n    ///\n    private var readonly = false\n\n    ///\n    /// All configs but hashed by (s, i, _, pi) not including context. Wiped out\n    /// when we go readonly as this set becomes a DFA state.\n    ///\n    private var configLookup: LookupDictionary\n\n    ///\n    /// Track the elements as they are added to the set; supports get(i)\n    ///\n    public private(set) var configs = [ATNConfig]()\n\n    // TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation\n    // TODO: can we track conflicts as they are added to save scanning configs later?\n    public internal(set) var uniqueAlt = ATN.INVALID_ALT_NUMBER\n    //TODO no default\n    ///\n    /// Currently this is only used when we detect SLL conflict; this does\n    /// not necessarily represent the ambiguous alternatives. In fact,\n    /// I should also point out that this seems to include predicated alternatives\n    /// that have predicates that evaluate to false. Computed in computeTargetState().\n    ///\n    internal var conflictingAlts: BitSet?\n\n    // Used in parser and lexer. In lexer, it indicates we hit a pred\n    // while computing a closure operation.  Don't make a DFA state from this.\n    public internal(set) var hasSemanticContext = false\n    //TODO no default\n    public internal(set) var dipsIntoOuterContext = false\n    //TODO no default\n\n    ///\n    /// Indicates that this configuration set is part of a full context\n    /// LL prediction. It will be used to determine how to merge $. With SLL\n    /// it's a wildcard whereas it is not for LL context merge.\n    ///\n    public let fullCtx: Bool\n\n    private var cachedHashCode = -1\n\n    public init(_ fullCtx: Bool = true, isOrdered: Bool = false) {\n        configLookup = isOrdered ? LookupDictionary(type: LookupDictionaryType.ordered) : LookupDictionary()\n        self.fullCtx = fullCtx\n    }\n\n    //override\n    @discardableResult\n    public func add(_ config: ATNConfig) throws -> Bool {\n        var mergeCache : DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>? = nil\n        return try add(config, &mergeCache)\n    }\n\n    ///\n    /// Adding a new config means merging contexts with existing configs for\n    /// `(s, i, pi, _)`, where `s` is the\n    /// _org.antlr.v4.runtime.atn.ATNConfig#state_, `i` is the _org.antlr.v4.runtime.atn.ATNConfig#alt_, and\n    /// `pi` is the _org.antlr.v4.runtime.atn.ATNConfig#semanticContext_. We use\n    /// `(s,i,pi)` as key.\n    ///\n    /// This method updates _#dipsIntoOuterContext_ and\n    /// _#hasSemanticContext_ when necessary.\n    ///\n    @discardableResult\n    public func add(\n        _ config: ATNConfig,\n        _ mergeCache: inout DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>?) throws -> Bool {\n            if readonly {\n                throw ANTLRError.illegalState(msg: \"This set is readonly\")\n            }\n\n            if config.semanticContext != SemanticContext.Empty.Instance {\n                hasSemanticContext = true\n            }\n            if config.getOuterContextDepth() > 0 {\n                dipsIntoOuterContext = true\n            }\n            let existing: ATNConfig = getOrAdd(config)\n            if existing === config {\n                // we added this new one\n                cachedHashCode = -1\n                configs.append(config)  // track order here\n                return true\n            }\n            // a previous (s,i,pi,_), merge with it and save result\n            let rootIsWildcard = !fullCtx\n\n            let merged = PredictionContext.merge(existing.context!, config.context!, rootIsWildcard, &mergeCache)\n\n            // no need to check for existing.context, config.context in cache\n            // since only way to create new graphs is \"call rule\" and here. We\n            // cache at both places.\n            existing.reachesIntoOuterContext =\n                max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext)\n\n            // make sure to preserve the precedence filter suppression during the merge\n            if config.isPrecedenceFilterSuppressed() {\n                existing.setPrecedenceFilterSuppressed(true)\n            }\n\n            existing.context = merged // replace context; no need to alt mapping\n            return true\n    }\n\n    public func getOrAdd(_ config: ATNConfig) -> ATNConfig {\n\n        return configLookup.getOrAdd(config)\n    }\n\n\n    ///\n    /// Return a List holding list of configs\n    ///\n    public func elements() -> [ATNConfig] {\n        return configs\n    }\n\n    public func getStates() -> Set<ATNState> {\n        var states = Set<ATNState>(minimumCapacity: configs.count)\n        for config in configs {\n            states.insert(config.state)\n        }\n        return states\n    }\n\n    ///\n    /// Gets the complete set of represented alternatives for the configuration\n    /// set.\n    ///\n    /// - returns: the set of represented alternatives in this configuration set\n    ///\n    /// - since: 4.3\n    ///\n    public func getAlts() -> BitSet {\n        let alts = BitSet()\n        for config in configs {\n            try! alts.set(config.alt)\n        }\n        return alts\n    }\n\n    public func getPredicates() -> [SemanticContext] {\n        var preds = [SemanticContext]()\n        for config in configs {\n            if config.semanticContext != SemanticContext.Empty.Instance {\n                preds.append(config.semanticContext)\n            }\n        }\n        return preds\n    }\n\n    public func get(_ i: Int) -> ATNConfig {\n        return configs[i]\n    }\n\n    public func optimizeConfigs(_ interpreter: ATNSimulator) throws {\n        if readonly {\n            throw ANTLRError.illegalState(msg: \"This set is readonly\")\n        }\n        if configLookup.isEmpty {\n            return\n        }\n        for config in configs {\n            config.context = interpreter.getCachedContext(config.context!)\n\n        }\n    }\n\n    @discardableResult\n    public func addAll(_ coll: ATNConfigSet) throws -> Bool {\n        for c in coll.configs {\n            try add(c)\n        }\n        return false\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        if isReadonly() {\n            if cachedHashCode == -1 {\n                cachedHashCode = configsHashValue\n            }\n            hasher.combine(cachedHashCode)\n        }\n        else {\n            hasher.combine(configsHashValue)\n        }\n    }\n\n    private var configsHashValue: Int {\n        var hashCode = 1\n        for item in configs {\n            hashCode = hashCode &* 3 &+ item.hashValue\n        }\n        return hashCode\n    }\n\n    public var count: Int {\n        return configs.count\n    }\n\n    public func size() -> Int {\n        return configs.count\n    }\n\n\n    public func isEmpty() -> Bool {\n        return configs.isEmpty\n    }\n\n\n    public func contains(_ o: ATNConfig) -> Bool {\n        return configLookup.contains(o)\n    }\n\n\n    public func clear() throws {\n        if readonly {\n            throw ANTLRError.illegalState(msg: \"This set is readonly\")\n        }\n        configs.removeAll()\n        cachedHashCode = -1\n        configLookup.removeAll()\n    }\n\n    public func isReadonly() -> Bool {\n        return readonly\n    }\n\n    public func setReadonly(_ readonly: Bool) {\n        self.readonly = readonly\n        configLookup.removeAll()\n\n    }\n\n    public var description: String {\n        var buf = \"\"\n        buf += String(describing: elements())\n        if hasSemanticContext {\n            buf += \",hasSemanticContext=true\"\n        }\n        if uniqueAlt != ATN.INVALID_ALT_NUMBER {\n            buf += \",uniqueAlt=\\(uniqueAlt)\"\n        }\n        if let conflictingAlts = conflictingAlts {\n            buf += \",conflictingAlts=\\(conflictingAlts)\"\n        }\n        if dipsIntoOuterContext {\n            buf += \",dipsIntoOuterContext\"\n        }\n        return buf\n    }\n\n    ///\n    /// override\n    /// public <T> func toArray(a : [T]) -> [T] {\n    /// return configLookup.toArray(a);\n    ///\n    private func configHash(_ stateNumber: Int,_ context: PredictionContext?) -> Int{\n        var hashCode = MurmurHash.initialize(7)\n        hashCode = MurmurHash.update(hashCode, stateNumber)\n        hashCode = MurmurHash.update(hashCode, context)\n        return MurmurHash.finish(hashCode, 2)\n    }\n\n    public func getConflictingAltSubsets() -> [BitSet] {\n        var configToAlts = [Int: BitSet]()\n\n        for cfg in configs {\n            let hash = configHash(cfg.state.stateNumber, cfg.context)\n            var alts: BitSet\n            if let configToAlt = configToAlts[hash] {\n                alts = configToAlt\n            } else {\n                alts = BitSet()\n                configToAlts[hash] = alts\n            }\n\n            try! alts.set(cfg.alt)\n        }\n\n        return Array(configToAlts.values)\n    }\n\n    public func getStateToAltMap() -> [Int: BitSet] {\n        var m = [Int: BitSet]()\n\n        for cfg in configs {\n            var alts: BitSet\n            if let mAlts =  m[cfg.state.stateNumber] {\n                alts = mAlts\n            } else {\n                alts = BitSet()\n                m[cfg.state.stateNumber] = alts\n            }\n\n            try! alts.set(cfg.alt)\n        }\n        return m\n    }\n\n    //for DFAState\n    public func getAltSet() -> Set<Int>?  {\n        if configs.isEmpty {\n            return nil\n        }\n        var alts = Set<Int>()\n        for config in configs {\n            alts.insert(config.alt)\n        }\n        return alts\n    }\n\n    //for DiagnosticErrorListener\n    public func getAltBitSet() -> BitSet  {\n        let result = BitSet()\n        for config in configs {\n            try! result.set(config.alt)\n        }\n        return result\n    }\n\n    //LexerATNSimulator\n    public var firstConfigWithRuleStopState: ATNConfig? {\n        for config in configs {\n            if config.state is RuleStopState {\n                return config\n            }\n        }\n\n        return nil\n    }\n\n    //ParserATNSimulator\n\n    public func getUniqueAlt() -> Int {\n        var alt = ATN.INVALID_ALT_NUMBER\n        for config in configs {\n            if alt == ATN.INVALID_ALT_NUMBER {\n                alt = config.alt // found first alt\n            } else if config.alt != alt {\n                return ATN.INVALID_ALT_NUMBER\n            }\n        }\n        return alt\n    }\n\n    public func removeAllConfigsNotInRuleStopState(_ mergeCache: inout DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>?,_ lookToEndOfRule: Bool,_ atn: ATN) -> ATNConfigSet {\n        if PredictionMode.allConfigsInRuleStopStates(self) {\n            return self\n        }\n\n        let result = ATNConfigSet(fullCtx)\n        for config in configs {\n            if config.state is RuleStopState {\n                try! result.add(config, &mergeCache)\n                continue\n            }\n\n            if lookToEndOfRule && config.state.onlyHasEpsilonTransitions() {\n                let nextTokens = atn.nextTokens(config.state)\n                if nextTokens.contains(CommonToken.EPSILON) {\n                    let endOfRuleState = atn.ruleToStopState[config.state.ruleIndex!]\n                    try! result.add(ATNConfig(config, endOfRuleState), &mergeCache)\n                }\n            }\n        }\n\n        return result\n    }\n\n    public func applyPrecedenceFilter(_ mergeCache: inout DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>?,_ parser: Parser,_ _outerContext: ParserRuleContext!) throws -> ATNConfigSet {\n\n        let configSet = ATNConfigSet(fullCtx)\n        var statesFromAlt1 = [Int: PredictionContext]()\n        for config in configs {\n            // handle alt 1 first\n            if config.alt != 1 {\n                continue\n            }\n\n            let updatedContext = try config.semanticContext.evalPrecedence(parser, _outerContext)\n            if updatedContext == nil {\n                // the configuration was eliminated\n                continue\n            }\n\n            statesFromAlt1[config.state.stateNumber] = config.context\n            if updatedContext != config.semanticContext {\n                try! configSet.add(ATNConfig(config, updatedContext!), &mergeCache)\n            } else {\n                try! configSet.add(config, &mergeCache)\n            }\n        }\n\n        for config in configs {\n            if config.alt == 1 {\n                // already handled\n                continue\n            }\n\n            if !config.isPrecedenceFilterSuppressed() {\n                ///\n                /// In the future, this elimination step could be updated to also\n                /// filter the prediction context for alternatives predicting alt>1\n                /// (basically a graph subtraction algorithm).\n                ///\n                let context = statesFromAlt1[config.state.stateNumber]\n                if context != nil && context == config.context {\n                    // eliminated\n                    continue\n                }\n            }\n\n            try! configSet.add(config, &mergeCache)\n        }\n\n        return configSet\n    }\n\n    internal func getPredsForAmbigAlts(_ ambigAlts: BitSet, _ nalts: Int) -> [SemanticContext?]? {\n        var altToPred = [SemanticContext?](repeating: nil, count: nalts + 1)\n        for config in configs {\n            if try! ambigAlts.get(config.alt) {\n                altToPred[config.alt] = SemanticContext.or(altToPred[config.alt], config.semanticContext)\n            }\n        }\n        var nPredAlts = 0\n        for i in 1...nalts {\n            if altToPred[i] == nil {\n                altToPred[i] = SemanticContext.Empty.Instance\n            }\n            else if altToPred[i] != SemanticContext.Empty.Instance {\n                nPredAlts += 1\n            }\n        }\n\n        //\t\t// Optimize away p||p and p&&p TODO: optimize() was a no-op\n        //\t\tfor (int i = 0; i < altToPred.length; i++) {\n        //\t\t\taltToPred[i] = altToPred[i].optimize();\n        //\t\t}\n\n        // nonambig alts are null in altToPred\n        return (nPredAlts == 0 ? nil : altToPred)\n    }\n\n    public func getAltThatFinishedDecisionEntryRule() -> Int {\n        let alts = IntervalSet()\n        for config in configs {\n            if config.getOuterContextDepth() > 0 ||\n                (config.state is RuleStopState &&\n                    config.context!.hasEmptyPath()) {\n                try! alts.add(config.alt)\n            }\n        }\n        if alts.size() == 0 {\n            return ATN.INVALID_ALT_NUMBER\n        }\n        return alts.getMinElement()\n    }\n\n    ///\n    /// Walk the list of configurations and split them according to\n    /// those that have preds evaluating to true/false.  If no pred, assume\n    /// true pred and include in succeeded set.  Returns Pair of sets.\n    ///\n    /// Create a new set so as not to alter the incoming parameter.\n    ///\n    /// Assumption: the input stream has been restored to the starting point\n    /// prediction, which is where predicates need to evaluate.\n    ///\n    public func splitAccordingToSemanticValidity(\n        _ outerContext: ParserRuleContext,\n        _ evalSemanticContext: (SemanticContext, ParserRuleContext, Int, Bool) throws -> Bool) rethrows -> (ATNConfigSet, ATNConfigSet) {\n        let succeeded = ATNConfigSet(fullCtx)\n        let failed = ATNConfigSet(fullCtx)\n        for config in configs {\n            if config.semanticContext != SemanticContext.Empty.Instance {\n                let predicateEvaluationResult = try evalSemanticContext(config.semanticContext, outerContext, config.alt,fullCtx)\n                if predicateEvaluationResult {\n                    try! succeeded.add(config)\n                } else {\n                    try! failed.add(config)\n                }\n            } else {\n                try! succeeded.add(config)\n            }\n        }\n        return (succeeded, failed)\n    }\n\n    public func dupConfigsWithoutSemanticPredicates() -> ATNConfigSet {\n        let dup = ATNConfigSet()\n        for config in configs {\n            let c = ATNConfig(config, SemanticContext.Empty.Instance)\n            try! dup.add(c)\n        }\n        return dup\n    }\n\n    public var hasConfigInRuleStopState: Bool {\n        return configs.contains(where: { $0.state is RuleStopState })\n    }\n\n    public var allConfigsInRuleStopStates: Bool {\n        return !configs.contains(where: { !($0.state is RuleStopState) })\n    }\n}\n\n\npublic func ==(lhs: ATNConfigSet, rhs: ATNConfigSet) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n\n    return\n        lhs.configs == rhs.configs && // includes stack context\n        lhs.fullCtx == rhs.fullCtx &&\n        lhs.uniqueAlt == rhs.uniqueAlt &&\n        lhs.conflictingAlts == rhs.conflictingAlts &&\n        lhs.hasSemanticContext == rhs.hasSemanticContext &&\n        lhs.dipsIntoOuterContext == rhs.dipsIntoOuterContext\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATNDeserializationOptions.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\npublic struct ATNDeserializationOptions {\n    public var verifyATN = true\n    public var generateRuleBypassTransitions = false\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATNDeserializer.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\nimport Foundation\n\npublic class ATNDeserializer {\n    public static let SERIALIZED_VERSION = 4\n\n    private let deserializationOptions: ATNDeserializationOptions\n\n    public init(_ deserializationOptions: ATNDeserializationOptions? = nil) {\n        self.deserializationOptions = deserializationOptions ?? ATNDeserializationOptions()\n    }\n\n    public func deserialize(_ data: [Int]) throws -> ATN {\n        var p = 0\n\n        let version = data[p]\n        p += 1\n        if version != ATNDeserializer.SERIALIZED_VERSION {\n            let reason = \"Could not deserialize ATN with version \\(version) (expected \\(ATNDeserializer.SERIALIZED_VERSION)).\"\n            throw ANTLRError.unsupportedOperation(msg: reason)\n        }\n\n        let grammarType = ATNType(rawValue: data[p])!\n        p += 1\n        let maxTokenType = data[p]\n        p += 1\n        let atn = ATN(grammarType, maxTokenType)\n\n        //\n        // STATES\n        //\n        var loopBackStateNumbers = [(LoopEndState, Int)]()\n        var endStateNumbers = [(BlockStartState, Int)]()\n        let nstates = data[p]\n        p += 1\n        for _ in 0..<nstates {\n            let stype = data[p]\n            p += 1\n            // ignore bad type of states\n            if stype == ATNState.INVALID_TYPE {\n                atn.addState(nil)\n                continue\n            }\n\n            let ruleIndex = data[p]\n            p += 1\n            let s = try stateFactory(stype, ruleIndex)!\n            if stype == ATNState.LOOP_END {\n                // special case\n                let loopBackStateNumber = data[p]\n                p += 1\n                loopBackStateNumbers.append((s as! LoopEndState, loopBackStateNumber))\n            } else if let s = s as? BlockStartState {\n                let endStateNumber = data[p]\n                p += 1\n                endStateNumbers.append((s, endStateNumber))\n            }\n            atn.addState(s)\n        }\n\n        // delay the assignment of loop back and end states until we know all the state instances have been initialized\n        for pair in loopBackStateNumbers {\n            pair.0.loopBackState = atn.states[pair.1]\n        }\n\n        for pair in endStateNumbers {\n            pair.0.endState = atn.states[pair.1] as? BlockEndState\n        }\n\n        let numNonGreedyStates = data[p]\n        p += 1\n        for _ in 0..<numNonGreedyStates {\n            let stateNumber = data[p]\n            p += 1\n            (atn.states[stateNumber] as! DecisionState).nonGreedy = true\n        }\n\n        let numPrecedenceStates = data[p]\n        p += 1\n        for _ in 0..<numPrecedenceStates {\n            let stateNumber = data[p]\n            p += 1\n            (atn.states[stateNumber] as! RuleStartState).isPrecedenceRule = true\n        }\n\n        //\n        // RULES\n        //\n        let nrules = data[p]\n        p += 1\n        var ruleToTokenType = [Int]()\n        var ruleToStartState = [RuleStartState]()\n        for _ in 0..<nrules {\n            let s = data[p]\n            p += 1\n            let startState = atn.states[s] as! RuleStartState\n            ruleToStartState.append(startState)\n\n            if atn.grammarType == ATNType.lexer {\n                let tokenType = data[p]\n                p += 1\n                ruleToTokenType.append(tokenType)\n            }\n        }\n        atn.ruleToStartState = ruleToStartState\n        if atn.grammarType == ATNType.lexer {\n            atn.ruleToTokenType = ruleToTokenType\n        }\n\n        fillRuleToStopState(atn)\n\n        //\n        // MODES\n        //\n        let nmodes = data[p]\n        p += 1\n        for _ in 0..<nmodes {\n            let s = data[p]\n            p += 1\n            atn.appendModeToStartState(atn.states[s] as! TokensStartState)\n        }\n\n        //\n        // SETS\n        //\n        var sets = [IntervalSet]()\n\n        readSets(data, &p, &sets, readInt)\n\n        //\n        // EDGES\n        //\n        let nedges = data[p]\n        p += 1\n        for _ in 0..<nedges {\n            let src = data[p]\n            let trg = data[p + 1]\n            let ttype = data[p + 2]\n            let arg1 = data[p + 3]\n            let arg2 = data[p + 4]\n            let arg3 = data[p + 5]\n            let trans = try edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets)\n\n            let srcState = atn.states[src]!\n            srcState.addTransition(trans)\n            p += 6\n        }\n\n        deriveEdgesForRuleStopStates(atn)\n        try validateStates(atn)\n\n        //\n        // DECISIONS\n        //\n        let ndecisions = data[p]\n        p += 1\n        if (ndecisions >= 1) {\n            for i in 1...ndecisions {\n                let s = data[p]\n                p += 1\n                let decState = atn.states[s] as! DecisionState\n                atn.appendDecisionToState(decState)\n                decState.decision = i - 1\n            }\n        }\n\n        //\n        // LEXER ACTIONS\n        //\n        if atn.grammarType == ATNType.lexer {\n            let length = data[p]\n            p += 1\n            var lexerActions = [LexerAction]()\n            for _ in 0..<length {\n                let actionType = LexerActionType(rawValue: data[p])!\n                p += 1\n                let data1 = data[p]\n                p += 1\n                let data2 = data[p]\n                p += 1\n                let lexerAction = lexerActionFactory(actionType, data1, data2)\n                lexerActions.append(lexerAction)\n            }\n            atn.lexerActions = lexerActions\n        }\n\n        try finalizeATN(atn)\n        return atn\n    }\n\n    private func readInt(_ data: [Int], _ p: inout Int) -> Int {\n        let result = data[p]\n        p += 1\n        return result\n    }\n\n    private func readSets(_ data: [Int], _ p: inout Int, _ sets: inout [IntervalSet], _ readUnicode: ([Int], inout Int) -> Int) {\n        let nsets = data[p]\n        p += 1\n        for _ in 0..<nsets {\n            let nintervals = data[p]\n            p += 1\n            let set = IntervalSet()\n            sets.append(set)\n\n            let containsEof = (data[p] != 0)\n            p += 1\n            if containsEof {\n                try! set.add(-1)\n            }\n\n            for _ in 0..<nintervals {\n                try! set.add(readUnicode(data, &p), readUnicode(data, &p))\n            }\n        }\n    }\n\n    private func fillRuleToStopState(_ atn: ATN) {\n        let nrules = atn.ruleToStartState.count\n        atn.ruleToStopState = [RuleStopState](repeating: RuleStopState(), count: nrules)\n\n        for state in atn.states {\n            if let stopState = state as? RuleStopState, let index = stopState.ruleIndex {\n                atn.ruleToStopState[index] = stopState\n                atn.ruleToStartState[index].stopState = stopState\n            }\n        }\n    }\n\n    /// edges for rule stop states can be derived, so they aren't serialized\n    private func deriveEdgesForRuleStopStates(_ atn: ATN) {\n        for state in atn.states {\n            guard let state = state else {\n                continue\n            }\n            let length = state.getNumberOfTransitions()\n            for i in 0..<length {\n                let t = state.transition(i)\n                guard let ruleTransition = t as? RuleTransition else {\n                    continue\n                }\n                var outermostPrecedenceReturn = -1\n                if let targetRuleIndex = ruleTransition.target.ruleIndex {\n                    if atn.ruleToStartState[targetRuleIndex].isPrecedenceRule {\n                        if ruleTransition.precedence == 0 {\n                            outermostPrecedenceReturn = targetRuleIndex\n                        }\n                    }\n\n                    let returnTransition = EpsilonTransition(ruleTransition.followState, outermostPrecedenceReturn)\n                    atn.ruleToStopState[targetRuleIndex].addTransition(returnTransition)\n                }\n            }\n        }\n    }\n\n    private func validateStates(_ atn: ATN) throws {\n        for state in atn.states {\n            if let state = state as? BlockStartState {\n                // we need to know the end state to set its start state\n                if let stateEndState = state.endState {\n                    // block end states can only be associated to a single block start state\n                    if stateEndState.startState != nil {\n                        throw ANTLRError.illegalState(msg: \"state.endState.startState != nil\")\n                    }\n                    stateEndState.startState = state\n                }\n                else {\n                    throw ANTLRError.illegalState(msg: \"state.endState == nil\")\n                }\n            }\n            else if let loopbackState = state as? PlusLoopbackState {\n                let length = loopbackState.getNumberOfTransitions()\n                for i in 0..<length {\n                    let target = loopbackState.transition(i).target\n                    if let startState = target as? PlusBlockStartState {\n                        startState.loopBackState = loopbackState\n                    }\n                }\n            }\n            else if let loopbackState = state as? StarLoopbackState {\n                let length = loopbackState.getNumberOfTransitions()\n                for i in 0..<length {\n                    let target = loopbackState.transition(i).target\n                    if let entryState = target as? StarLoopEntryState {\n                        entryState.loopBackState = loopbackState\n                    }\n                }\n            }\n        }\n    }\n\n\n    private func finalizeATN(_ atn: ATN) throws {\n        markPrecedenceDecisions(atn)\n        if deserializationOptions.verifyATN {\n            try verifyATN(atn)\n        }\n        if deserializationOptions.generateRuleBypassTransitions && atn.grammarType == ATNType.parser {\n            try generateRuleBypassTransitions(atn)\n\n            if deserializationOptions.verifyATN {\n                // reverify after modification\n                try verifyATN(atn)\n            }\n        }\n    }\n\n\n    ///\n    /// Analyze the _org.antlr.v4.runtime.atn.StarLoopEntryState_ states in the specified ATN to set\n    /// the _org.antlr.v4.runtime.atn.StarLoopEntryState#precedenceRuleDecision_ field to the\n    /// correct value.\n    ///\n    /// - parameter atn: The ATN.\n    ///\n    internal func markPrecedenceDecisions(_ atn: ATN) {\n        for state in atn.states {\n            ///\n            /// We analyze the ATN to determine if this ATN decision state is the\n            /// decision for the closure block that determines whether a\n            /// precedence rule should continue or complete.\n            ///\n            guard let state = state as? StarLoopEntryState, let stateRuleIndex = state.ruleIndex, atn.ruleToStartState[stateRuleIndex].isPrecedenceRule else {\n                continue\n            }\n            let maybeLoopEndState = state.transition(state.getNumberOfTransitions() - 1).target\n            if maybeLoopEndState is LoopEndState && maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transition(0).target is RuleStopState {\n                state.precedenceRuleDecision = true\n            }\n        }\n    }\n\n\n    private func generateRuleBypassTransitions(_ atn: ATN) throws {\n        let length = atn.ruleToStartState.count\n        atn.ruleToTokenType = (0..<length).map { atn.maxTokenType + $0 + 1 }\n\n        for i in 0..<length {\n            let bypassStart = BasicBlockStartState()\n            bypassStart.ruleIndex = i\n            atn.addState(bypassStart)\n\n            let bypassStop = BlockEndState()\n            bypassStop.ruleIndex = i\n            atn.addState(bypassStop)\n\n            bypassStart.endState = bypassStop\n            atn.defineDecisionState(bypassStart)\n\n            bypassStop.startState = bypassStart\n\n            var endState: ATNState?\n            var excludeTransition: Transition? = nil\n            if atn.ruleToStartState[i].isPrecedenceRule {\n                // wrap from the beginning of the rule to the StarLoopEntryState\n                endState = nil\n                for state in atn.states {\n                    guard let state = state, state.ruleIndex == i, state is StarLoopEntryState else {\n                        continue\n                    }\n\n                    let maybeLoopEndState = state.transition(state.getNumberOfTransitions() - 1).target\n                    if !(maybeLoopEndState is LoopEndState) {\n                        continue\n                    }\n\n                    if maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transition(0).target is RuleStopState {\n                        endState = state\n                        break\n                    }\n                }\n\n                if endState == nil {\n                    throw ANTLRError.unsupportedOperation(msg: \"Couldn't identify final state of the precedence rule prefix section.\")\n                }\n\n                excludeTransition = (endState as? StarLoopEntryState)?.loopBackState?.transition(0)\n            }\n            else {\n                endState = atn.ruleToStopState[i]\n            }\n\n            // all non-excluded transitions that currently target end state need to target blockEnd instead\n            for state in atn.states {\n                guard let state = state else {\n                    continue\n                }\n                for transition in state.transitions {\n                    if transition === excludeTransition! {\n                        continue\n                    }\n\n                    if transition.target == endState {\n                        transition.target = bypassStop\n                    }\n                }\n            }\n\n            // all transitions leaving the rule start state need to leave blockStart instead\n            while atn.ruleToStartState[i].getNumberOfTransitions() > 0 {\n                let transition = atn.ruleToStartState[i].removeTransition(atn.ruleToStartState[i].getNumberOfTransitions() - 1)\n                bypassStart.addTransition(transition)\n            }\n\n            // link the new states\n            atn.ruleToStartState[i].addTransition(EpsilonTransition(bypassStart))\n            bypassStop.addTransition(EpsilonTransition(endState!))\n\n            let matchState = BasicState()\n            atn.addState(matchState)\n            matchState.addTransition(AtomTransition(bypassStop, atn.ruleToTokenType[i]))\n            bypassStart.addTransition(EpsilonTransition(matchState))\n        }\n    }\n\n\n    internal func verifyATN(_ atn: ATN) throws {\n        // verify assumptions\n        for state in atn.states {\n            guard let state = state else {\n                continue\n            }\n\n            try checkCondition(state.onlyHasEpsilonTransitions() || state.getNumberOfTransitions() <= 1)\n\n            if let state = state as? PlusBlockStartState {\n                try checkCondition(state.loopBackState != nil)\n            }\n\n            if let starLoopEntryState = state as? StarLoopEntryState {\n                try checkCondition(starLoopEntryState.loopBackState != nil)\n                try checkCondition(starLoopEntryState.getNumberOfTransitions() == 2)\n\n                if starLoopEntryState.transition(0).target is StarBlockStartState {\n                    try checkCondition(starLoopEntryState.transition(1).target is LoopEndState)\n                    try checkCondition(!starLoopEntryState.nonGreedy)\n                } else {\n                    if starLoopEntryState.transition(0).target is LoopEndState {\n                        try checkCondition(starLoopEntryState.transition(1).target is StarBlockStartState)\n                        try checkCondition(starLoopEntryState.nonGreedy)\n                    } else {\n                        throw ANTLRError.illegalState(msg: \"IllegalStateException\")\n                    }\n                }\n            }\n\n            if let state = state as? StarLoopbackState {\n                try checkCondition(state.getNumberOfTransitions() == 1)\n                try checkCondition(state.transition(0).target is StarLoopEntryState)\n            }\n\n            if state is LoopEndState {\n                try checkCondition((state as! LoopEndState).loopBackState != nil)\n            }\n\n            if state is RuleStartState {\n                try checkCondition((state as! RuleStartState).stopState != nil)\n            }\n\n            if state is BlockStartState {\n                try checkCondition((state as! BlockStartState).endState != nil)\n            }\n\n            if state is BlockEndState {\n                try checkCondition((state as! BlockEndState).startState != nil)\n            }\n\n            if let decisionState = state as? DecisionState {\n                try checkCondition(decisionState.getNumberOfTransitions() <= 1 || decisionState.decision >= 0)\n            } else {\n                try checkCondition(state.getNumberOfTransitions() <= 1 || state is RuleStopState)\n            }\n        }\n    }\n\n    internal func checkCondition(_ condition: Bool) throws {\n        try checkCondition(condition, nil)\n    }\n\n    internal func checkCondition(_ condition: Bool, _ message: String?) throws {\n        if !condition {\n            throw ANTLRError.illegalState(msg: message ?? \"\")\n\n        }\n    }\n\n\n    internal func edgeFactory(_ atn: ATN,\n                              _ type: Int, _ src: Int, _ trg: Int,\n                              _ arg1: Int, _ arg2: Int, _ arg3: Int,\n                              _ sets: [IntervalSet]) throws -> Transition {\n        let target = atn.states[trg]!\n        switch type {\n        case Transition.EPSILON: return EpsilonTransition(target)\n        case Transition.RANGE:\n            if arg3 != 0 {\n                return RangeTransition(target, CommonToken.EOF, arg2)\n            } else {\n                return RangeTransition(target, arg1, arg2)\n            }\n        case Transition.RULE:\n            let rt = RuleTransition(atn.states[arg1] as! RuleStartState, arg2, arg3, target)\n            return rt\n        case Transition.PREDICATE:\n            let pt = PredicateTransition(target, arg1, arg2, arg3 != 0)\n            return pt\n        case Transition.PRECEDENCE:\n            return PrecedencePredicateTransition(target, arg1)\n        case Transition.ATOM:\n            if arg3 != 0 {\n                return AtomTransition(target, CommonToken.EOF)\n            } else {\n                return AtomTransition(target, arg1)\n            }\n        case Transition.ACTION:\n            return ActionTransition(target, arg1, arg2, arg3 != 0)\n\n        case Transition.SET: return SetTransition(target, sets[arg1])\n        case Transition.NOT_SET: return NotSetTransition(target, sets[arg1])\n        case Transition.WILDCARD: return WildcardTransition(target)\n        default:\n            throw ANTLRError.illegalState(msg: \"The specified transition type is not valid.\")\n        }\n    }\n\n    internal func stateFactory(_ type: Int, _ ruleIndex: Int) throws -> ATNState? {\n        var s: ATNState\n        switch type {\n        case ATNState.INVALID_TYPE: return nil\n        case ATNState.BASIC: s = BasicState()\n        case ATNState.RULE_START: s = RuleStartState()\n        case ATNState.BLOCK_START: s = BasicBlockStartState()\n        case ATNState.PLUS_BLOCK_START: s = PlusBlockStartState()\n        case ATNState.STAR_BLOCK_START: s = StarBlockStartState()\n        case ATNState.TOKEN_START: s = TokensStartState()\n        case ATNState.RULE_STOP: s = RuleStopState()\n        case ATNState.BLOCK_END: s = BlockEndState()\n        case ATNState.STAR_LOOP_BACK: s = StarLoopbackState()\n        case ATNState.STAR_LOOP_ENTRY: s = StarLoopEntryState()\n        case ATNState.PLUS_LOOP_BACK: s = PlusLoopbackState()\n        case ATNState.LOOP_END: s = LoopEndState()\n        default:\n            let message: String = \"The specified state type \\(type) is not valid.\"\n\n            throw ANTLRError.illegalArgument(msg: message)\n        }\n\n        s.ruleIndex = ruleIndex\n        return s\n    }\n\n    internal func lexerActionFactory(_ type: LexerActionType, _ data1: Int, _ data2: Int) -> LexerAction {\n        switch type {\n        case .channel:\n            return LexerChannelAction(data1)\n\n        case .custom:\n            return LexerCustomAction(data1, data2)\n\n        case .mode:\n            return LexerModeAction(data1)\n\n        case .more:\n            return LexerMoreAction.INSTANCE\n\n        case .popMode:\n            return LexerPopModeAction.INSTANCE\n\n        case .pushMode:\n            return LexerPushModeAction(data1)\n\n        case .skip:\n            return LexerSkipAction.INSTANCE\n\n        case .type:\n            return LexerTypeAction(data1)\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATNSimulator.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\nimport Foundation\n\nopen class ATNSimulator {\n    ///\n    /// Must distinguish between missing edge and edge we know leads nowhere\n    /// \n    public static let ERROR: DFAState = {\n        let error = DFAState(ATNConfigSet())\n        error.stateNumber = Int.max\n        return error\n    }()\n\n    public let atn: ATN\n\n    /// \n    /// The context cache maps all PredictionContext objects that are equals()\n    /// to a single cached copy. This cache is shared across all contexts\n    /// in all ATNConfigs in all DFA states.  We rebuild each ATNConfigSet\n    /// to use only cached nodes/graphs in addDFAState(). We don't want to\n    /// fill this during closure() since there are lots of contexts that\n    /// pop up but are not used ever again. It also greatly slows down closure().\n    /// \n    /// This cache makes a huge difference in memory and a little bit in speed.\n    /// For the Java grammar on java.*, it dropped the memory requirements\n    /// at the end from 25M to 16M. We don't store any of the full context\n    /// graphs in the DFA because they are limited to local context only,\n    /// but apparently there's a lot of repetition there as well. We optimize\n    /// the config contexts before storing the config set in the DFA states\n    /// by literally rebuilding them with cached subgraphs only.\n    /// \n    /// I tried a cache for use during closure operations, that was\n    /// whacked after each adaptivePredict(). It cost a little bit\n    /// more time I think and doesn't save on the overall footprint\n    /// so it's not worth the complexity.\n    /// \n    internal let sharedContextCache: PredictionContextCache\n\n    public init(_ atn: ATN,\n                _ sharedContextCache: PredictionContextCache) {\n\n        self.atn = atn\n        self.sharedContextCache = sharedContextCache\n    }\n\n    open func reset() {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Clear the DFA cache used by the current instance. Since the DFA cache may\n    /// be shared by multiple ATN simulators, this method may affect the\n    /// performance (but not accuracy) of other parsers which are being used\n    /// concurrently.\n    /// \n    /// - throws: ANTLRError.unsupportedOperation if the current instance does not\n    /// support clearing the DFA.\n    /// \n    /// - since: 4.3\n    /// \n    open func clearDFA() throws {\n        throw ANTLRError.unsupportedOperation(msg: \"This ATN simulator does not support clearing the DFA. \")\n    }\n\n    open func getSharedContextCache() -> PredictionContextCache {\n        return sharedContextCache\n    }\n\n    open func getCachedContext(_ context: PredictionContext) -> PredictionContext {\n        //TODO: synced (sharedContextCache!)\n        //synced (sharedContextCache!) {\n        var visited = [PredictionContext: PredictionContext]()\n        return PredictionContext.getCachedContext(context,\n                sharedContextCache,\n                &visited)\n    }\n\n    public static func edgeFactory(_ atn: ATN,\n                                  _ type: Int, _ src: Int, _ trg: Int,\n                                  _ arg1: Int, _ arg2: Int, _ arg3: Int,\n                                  _ sets: Array<IntervalSet>) throws -> Transition {\n        return try ATNDeserializer().edgeFactory(atn, type, src, trg, arg1, arg2, arg3, sets)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATNState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// \n/// The following images show the relation of states and\n/// _org.antlr.v4.runtime.atn.ATNState#transitions_ for various grammar constructs.\n/// \n/// \n/// * Solid edges marked with an &#0949; indicate a required\n/// _org.antlr.v4.runtime.atn.EpsilonTransition_.\n/// \n/// * Dashed edges indicate locations where any transition derived from\n/// _org.antlr.v4.runtime.atn.Transition_ might appear.\n/// \n/// * Dashed nodes are place holders for either a sequence of linked\n/// _org.antlr.v4.runtime.atn.BasicState_ states or the inclusion of a block representing a nested\n/// construct in one of the forms below.\n/// \n/// * Nodes showing multiple outgoing alternatives with a `...` support\n/// any number of alternatives (one or more). Nodes without the `...` only\n/// support the exact number of alternatives shown in the diagram.\n/// \n/// \n/// ## Basic Blocks\n/// \n/// ### Rule\n/// \n/// \n/// \n/// ## Block of 1 or more alternatives\n/// \n/// \n/// \n/// ## Greedy Loops\n/// \n/// ### Greedy Closure: `(...)*`\n/// \n/// \n/// \n/// ### Greedy Positive Closure: `(...)+`\n/// \n/// \n/// \n/// ### Greedy Optional: `(...)?`\n/// \n/// \n/// \n/// ## Non-Greedy Loops\n/// \n/// ### Non-Greedy Closure: `(...)*?`\n/// \n/// \n/// \n/// ### Non-Greedy Positive Closure: `(...)+?`\n/// \n/// \n/// \n/// ### Non-Greedy Optional: `(...)??`\n/// \n/// \n/// \n/// \npublic class ATNState: Hashable, CustomStringConvertible {\n    // constants for serialization\n    public static let INVALID_TYPE: Int = 0\n    public static let BASIC: Int = 1\n    public static let RULE_START: Int = 2\n    public static let BLOCK_START: Int = 3\n    public static let PLUS_BLOCK_START: Int = 4\n    public static let STAR_BLOCK_START: Int = 5\n    public static let TOKEN_START: Int = 6\n    public static let RULE_STOP: Int = 7\n    public static let BLOCK_END: Int = 8\n    public static let STAR_LOOP_BACK: Int = 9\n    public static let STAR_LOOP_ENTRY: Int = 10\n    public static let PLUS_LOOP_BACK: Int = 11\n    public static let LOOP_END: Int = 12\n\n    public static let serializationNames: Array<String> =\n\n    [\"INVALID\",\n        \"BASIC\",\n        \"RULE_START\",\n        \"BLOCK_START\",\n        \"PLUS_BLOCK_START\",\n        \"STAR_BLOCK_START\",\n        \"TOKEN_START\",\n        \"RULE_STOP\",\n        \"BLOCK_END\",\n        \"STAR_LOOP_BACK\",\n        \"STAR_LOOP_ENTRY\",\n        \"PLUS_LOOP_BACK\",\n        \"LOOP_END\"]\n\n\n    public static let INVALID_STATE_NUMBER: Int = -1\n\n    /// \n    /// Which ATN are we in?\n    /// \n    public final var atn: ATN? = nil\n\n    public internal(set) final var stateNumber: Int = INVALID_STATE_NUMBER\n\n    public internal(set) final var ruleIndex: Int?\n    // at runtime, we don't have Rule objects\n\n    public private(set) final var epsilonOnlyTransitions: Bool = false\n\n    /// \n    /// Track the transitions emanating from this ATN state.\n    /// \n    internal private(set) final var transitions = [Transition]()\n\n    /// \n    /// Used to cache lookahead during parsing, not used during construction\n    /// \n    public internal(set) final var nextTokenWithinRule: IntervalSet?\n\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(stateNumber)\n    }\n\n    public func isNonGreedyExitState() -> Bool {\n        return false\n    }\n\n\n    public var description: String {\n        //return \"MyClass \\(string)\"\n        return String(stateNumber)\n    }\n    public final func getTransitions() -> [Transition] {\n        return transitions\n    }\n\n    public final func getNumberOfTransitions() -> Int {\n        return transitions.count\n    }\n\n    public final func addTransition(_ e: Transition) {\n        if transitions.isEmpty {\n            epsilonOnlyTransitions = e.isEpsilon()\n        }\n        else if epsilonOnlyTransitions != e.isEpsilon() {\n            print(\"ATN state %d has both epsilon and non-epsilon transitions.\\n\", String(stateNumber))\n            epsilonOnlyTransitions = false\n        }\n\n        var alreadyPresent = false\n        for t in transitions {\n            if t.target.stateNumber == e.target.stateNumber {\n                if let tLabel = t.labelIntervalSet(), let eLabel = e.labelIntervalSet(), tLabel == eLabel {\n//                    print(\"Repeated transition upon \\(eLabel) from \\(stateNumber)->\\(t.target.stateNumber)\")\n                    alreadyPresent = true\n                    break\n                }\n                else if t.isEpsilon() && e.isEpsilon() {\n//                    print(\"Repeated epsilon transition from \\(stateNumber)->\\(t.target.stateNumber)\")\n                    alreadyPresent = true\n                    break\n                }\n            }\n        }\n\n        if !alreadyPresent {\n            transitions.append(e)\n        }\n    }\n\n    public final func transition(_ i: Int) -> Transition {\n        return transitions[i]\n    }\n\n    public final func setTransition(_ i: Int, _ e: Transition) {\n        transitions[i] = e\n    }\n\n    public final func removeTransition(_ index: Int) -> Transition {\n\n        return transitions.remove(at: index)\n    }\n\n    public func getStateType() -> Int {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    public final func onlyHasEpsilonTransitions() -> Bool {\n        return epsilonOnlyTransitions\n    }\n\n    public final func setRuleIndex(_ ruleIndex: Int) {\n        self.ruleIndex = ruleIndex\n    }\n}\n\npublic func ==(lhs: ATNState, rhs: ATNState) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    // are these states same object?\n    return lhs.stateNumber == rhs.stateNumber\n\n}\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ATNType.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Represents the type of recognizer an ATN applies to.\n/// \n/// -  Sam Harwell\n/// \n\npublic enum ATNType: Int {\n\n    /// \n    /// A lexer grammar.\n    /// \n    case lexer = 0\n\n    /// \n    /// A parser grammar.\n    /// \n    case parser\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/AbstractPredicateTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// \n/// -  Sam Harwell\n/// \n\npublic class AbstractPredicateTransition: Transition {\n\n    /*public  override init(_ target : ATNState) {\n        super.init(target);\n    }*/\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ActionTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic final class ActionTransition: Transition, CustomStringConvertible {\n    public let ruleIndex: Int\n    public let actionIndex: Int\n    public let isCtxDependent: Bool\n    // e.g., $i ref in action\n\n\n    public convenience init(_ target: ATNState, _ ruleIndex: Int) {\n        self.init(target, ruleIndex, -1, false)\n    }\n\n    public init(_ target: ATNState, _ ruleIndex: Int, _ actionIndex: Int, _ isCtxDependent: Bool) {\n\n        self.ruleIndex = ruleIndex\n        self.actionIndex = actionIndex\n        self.isCtxDependent = isCtxDependent\n        super.init(target)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.ACTION\n    }\n\n    override\n    public func isEpsilon() -> Bool {\n        return true // we are to be ignored by analysis 'cept for predicates\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return false\n    }\n\n    public var description: String {\n        return \"action_\\(ruleIndex):\\(actionIndex)\"\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/AmbiguityInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This class represents profiling event information for an ambiguity.\n/// Ambiguities are decisions where a particular input resulted in an SLL\n/// conflict, followed by LL prediction also reaching a conflict state\n/// (indicating a true ambiguity in the grammar).\n/// \n/// \n/// This event may be reported during SLL prediction in cases where the\n/// conflicting SLL configuration set provides sufficient information to\n/// determine that the SLL conflict is truly an ambiguity. For example, if none\n/// of the ATN configurations in the conflicting SLL configuration set have\n/// traversed a global follow transition (i.e.\n/// _org.antlr.v4.runtime.atn.ATNConfig#reachesIntoOuterContext_ is 0 for all configurations), then\n/// the result of SLL prediction for that input is known to be equivalent to the\n/// result of LL prediction for that input.\n/// \n/// \n/// In some cases, the minimum represented alternative in the conflicting LL\n/// configuration set is not equal to the minimum represented alternative in the\n/// conflicting SLL configuration set. Grammars and inputs which result in this\n/// scenario are unable to use _org.antlr.v4.runtime.atn.PredictionMode#SLL_, which in turn means\n/// they cannot use the two-stage parsing strategy to improve parsing performance\n/// for that input.\n/// \n/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#reportAmbiguity\n/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#reportAmbiguity\n/// \n/// -  4.3\n/// \n\npublic class AmbiguityInfo: DecisionEventInfo {\n    /// \n    /// The set of alternative numbers for this decision event that lead to a valid parse.\n    /// \n    public var ambigAlts: BitSet\n\n    /// \n    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.AmbiguityInfo_ class with the\n    /// specified detailed ambiguity information.\n    /// \n    /// - parameter decision: The decision number\n    /// - parameter configs: The final configuration set identifying the ambiguous\n    /// alternatives for the current input\n    /// - parameter ambigAlts: The set of alternatives in the decision that lead to a valid parse.\n    /// - parameter input: The input token stream\n    /// - parameter startIndex: The start index for the current prediction\n    /// - parameter stopIndex: The index at which the ambiguity was identified during\n    /// prediction\n    /// - parameter fullCtx: `true` if the ambiguity was identified during LL\n    /// prediction; otherwise, `false` if the ambiguity was identified\n    /// during SLL prediction\n    /// \n    public init(_ decision: Int,\n                _ configs: ATNConfigSet,\n                _ ambigAlts: BitSet,\n                _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int,\n                _ fullCtx: Bool) {\n        self.ambigAlts = ambigAlts\n        super.init(decision, configs, input, startIndex, stopIndex, fullCtx)\n\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ArrayPredictionContext.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic class ArrayPredictionContext: PredictionContext {\n    /// \n    /// Parent can be null only if full ctx mode and we make an array\n    /// from _#EMPTY_ and non-empty. We merge _#EMPTY_ by using null parent and\n    /// returnState == _#EMPTY_RETURN_STATE_.\n    /// \n    public private(set) final var parents: [PredictionContext?]\n\n    /// \n    /// Sorted for merge, no duplicates; if present,\n    /// _#EMPTY_RETURN_STATE_ is always last.\n    /// \n    public final let returnStates: [Int]\n\n    public convenience init(_ a: SingletonPredictionContext) {\n        let parents = [a.parent]\n        self.init(parents, [a.returnState])\n    }\n\n    public init(_ parents: [PredictionContext?], _ returnStates: [Int]) {\n\n        self.parents = parents\n        self.returnStates = returnStates\n        super.init(PredictionContext.calculateHashCode(parents, returnStates))\n    }\n\n    override\n    final public func isEmpty() -> Bool {\n        // since EMPTY_RETURN_STATE can only appear in the last position, we\n        // don't need to verify that size==1\n        return returnStates[0] == PredictionContext.EMPTY_RETURN_STATE\n    }\n\n    override\n    final public func size() -> Int {\n        return returnStates.count\n    }\n\n    override\n    final public func getParent(_ index: Int) -> PredictionContext? {\n        return parents[index]\n    }\n\n    override\n    final public func getReturnState(_ index: Int) -> Int {\n        return returnStates[index]\n    }\n\n    override\n    public var description: String {\n        if isEmpty() {\n            return \"[]\"\n        }\n        var buf = \"[\"\n        for (i, returnState) in returnStates.enumerated() {\n            if i > 0 {\n                buf += \", \"\n            }\n            if returnState == PredictionContext.EMPTY_RETURN_STATE {\n                buf += \"$\"\n                continue\n            }\n            buf += \"\\(returnState)\"\n            if let parent = parents[i] {\n                buf += \" \\(parent)\"\n            }\n            else {\n                buf += \"null\"\n            }\n        }\n        buf += \"]\"\n        return buf\n    }\n\n    internal final func combineCommonParents() {\n\n        let length = parents.count\n        var uniqueParents: Dictionary<PredictionContext, PredictionContext> =\n        Dictionary<PredictionContext, PredictionContext>()\n        for p in parents {\n            if let parent: PredictionContext = p {\n                // if !uniqueParents.keys.contains(parent) {\n                if uniqueParents[parent] == nil {\n                    uniqueParents[parent] = parent  // don't replace\n                }\n            }\n        }\n\n        for p in 0..<length {\n            if let parent: PredictionContext = parents[p] {\n                parents[p] = uniqueParents[parent]\n            }\n        }\n\n    }\n}\n\n\npublic func ==(lhs: ArrayPredictionContext, rhs: ArrayPredictionContext) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    if lhs.hashValue != rhs.hashValue {\n        return false\n    }\n\n    return lhs.returnStates == rhs.returnStates && lhs.parents == rhs.parents\n}\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/AtomTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// TODO: make all transitions sets? no, should remove set edges\n/// \n\npublic final class AtomTransition: Transition, CustomStringConvertible {\n    /// \n    /// The token type or character value; or, signifies special label.\n    /// \n    public let label: Int\n\n    public init(_ target: ATNState, _ label: Int) {\n\n        self.label = label\n        super.init(target)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.ATOM\n    }\n\n    override\n    public func labelIntervalSet() -> IntervalSet? {\n        return IntervalSet(label)\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return label == symbol\n    }\n\n\n    public var description: String {\n        return String(label)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/BasicBlockStartState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// \n/// -  Sam Harwell\n/// \n\npublic final class BasicBlockStartState: BlockStartState {\n    override\n    public func getStateType() -> Int {\n        return BlockStartState.BLOCK_START\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/BasicState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// \n/// -  Sam Harwell\n/// \n\npublic final class BasicState: ATNState {\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.BASIC\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/BlockEndState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Terminal node of a simple `(a|b|c)` block.\n/// \n\npublic final class BlockEndState: ATNState {\n    public var startState: BlockStartState?\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.BLOCK_END\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/BlockStartState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// The start of a regular `(...)` block.\n/// \n\npublic class BlockStartState: DecisionState {\n    public var endState: BlockEndState?\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ContextSensitivityInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// This class represents profiling event information for a context sensitivity.\n/// Context sensitivities are decisions where a particular input resulted in an\n/// SLL conflict, but LL prediction produced a single unique alternative.\n/// \n/// \n/// In some cases, the unique alternative identified by LL prediction is not\n/// equal to the minimum represented alternative in the conflicting SLL\n/// configuration set. Grammars and inputs which result in this scenario are\n/// unable to use _org.antlr.v4.runtime.atn.PredictionMode#SLL_, which in turn means they cannot use\n/// the two-stage parsing strategy to improve parsing performance for that\n/// input.\n/// \n/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#reportContextSensitivity\n/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#reportContextSensitivity\n/// \n/// -  4.3\n/// \n\npublic class ContextSensitivityInfo: DecisionEventInfo {\n    /// \n    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.ContextSensitivityInfo_ class\n    /// with the specified detailed context sensitivity information.\n    /// \n    /// - parameter decision: The decision number\n    /// - parameter configs: The final configuration set containing the unique\n    /// alternative identified by full-context prediction\n    /// - parameter input: The input token stream\n    /// - parameter startIndex: The start index for the current prediction\n    /// - parameter stopIndex: The index at which the context sensitivity was\n    /// identified during full-context prediction\n    /// \n    public init(_ decision: Int,\n                _ configs: ATNConfigSet,\n                _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int) {\n        super.init(decision, configs, input, startIndex, stopIndex, true)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/DecisionEventInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This is the base class for gathering detailed information about prediction\n/// events which occur during parsing.\n/// \n/// Note that we could record the parser call stack at the time this event\n/// occurred but in the presence of left recursive rules, the stack is kind of\n/// meaningless. It's better to look at the individual configurations for their\n/// individual stacks. Of course that is a _org.antlr.v4.runtime.atn.PredictionContext_ object\n/// not a parse tree node and so it does not have information about the extent\n/// (start...stop) of the various subtrees. Examining the stack tops of all\n/// configurations provide the return states for the rule invocations.\n/// From there you can get the enclosing rule.\n/// \n/// -  4.3\n/// \n\npublic class DecisionEventInfo {\n    /// \n    /// The invoked decision number which this event is related to.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.ATN#decisionToState\n    /// \n    public let decision: Int\n\n    /// \n    /// The configuration set containing additional information relevant to the\n    /// prediction state when the current event occurred, or `null` if no\n    /// additional information is relevant or available.\n    /// \n    public let configs: ATNConfigSet?\n\n    /// \n    /// The input token stream which is being parsed.\n    /// \n    public let input: TokenStream\n\n    /// \n    /// The token index in the input stream at which the current prediction was\n    /// originally invoked.\n    /// \n    public let startIndex: Int\n\n    /// \n    /// The token index in the input stream at which the current event occurred.\n    /// \n    public let stopIndex: Int\n\n    /// \n    /// `true` if the current event occurred during LL prediction;\n    /// otherwise, `false` if the input occurred during SLL prediction.\n    /// \n    public let fullCtx: Bool\n\n    public init(_ decision: Int,\n                _ configs: ATNConfigSet?,\n                _ input: TokenStream,\n                _ startIndex: Int,\n                _ stopIndex: Int,\n                _ fullCtx: Bool) {\n        self.decision = decision\n        self.fullCtx = fullCtx\n        self.stopIndex = stopIndex\n        self.input = input\n        self.startIndex = startIndex\n        self.configs = configs\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/DecisionInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// This class contains profiling gathered for a particular decision.\n/// \n/// \n/// Parsing performance in ANTLR 4 is heavily influenced by both static factors\n/// (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the\n/// choice of input and the state of the DFA cache at the time profiling\n/// operations are started). For best results, gather and use aggregate\n/// statistics from a large sample of inputs representing the inputs expected in\n/// production before using the results to make changes in the grammar.\n/// \n/// -  4.3\n/// \n\npublic class DecisionInfo: CustomStringConvertible {\n    /// \n    /// The decision number, which is an index into _org.antlr.v4.runtime.atn.ATN#decisionToState_.\n    /// \n    public private(set) final var decision: Int\n\n    /// \n    /// The total number of times _org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict_ was\n    /// invoked for this decision.\n    /// \n    public var invocations: Int64 = 0\n\n    /// \n    /// The total time spent in _org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict_ for\n    /// this decision, in nanoseconds.\n    /// \n    /// \n    /// The value of this field contains the sum of differential results obtained\n    /// by _System#nanoTime()_, and is not adjusted to compensate for JIT\n    /// and/or garbage collection overhead. For best accuracy, use a modern JVM\n    /// implementation that provides precise results from\n    /// _System#nanoTime()_, and perform profiling in a separate process\n    /// which is warmed up by parsing the input prior to profiling. If desired,\n    /// call _org.antlr.v4.runtime.atn.ATNSimulator#clearDFA_ to reset the DFA cache to its initial\n    /// state before starting the profiling measurement pass.\n    /// \n    public var timeInPrediction: Int64 = 0\n\n    /// \n    /// The sum of the lookahead required for SLL prediction for this decision.\n    /// Note that SLL prediction is used before LL prediction for performance\n    /// reasons even when _org.antlr.v4.runtime.atn.PredictionMode#LL_ or\n    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_ is used.\n    /// \n    public var SLL_TotalLook: Int64 = 0\n\n    /// \n    /// Gets the minimum lookahead required for any single SLL prediction to\n    /// complete for this decision, by reaching a unique prediction, reaching an\n    /// SLL conflict state, or encountering a syntax error.\n    /// \n    public var SLL_MinLook: Int64 = 0\n\n    /// \n    /// Gets the maximum lookahead required for any single SLL prediction to\n    /// complete for this decision, by reaching a unique prediction, reaching an\n    /// SLL conflict state, or encountering a syntax error.\n    /// \n    public var SLL_MaxLook: Int64 = 0\n\n    /// \n    /// Gets the _org.antlr.v4.runtime.atn.LookaheadEventInfo_ associated with the event where the\n    /// _#SLL_MaxLook_ value was set.\n    /// \n    public var SLL_MaxLookEvent: LookaheadEventInfo!\n\n    /// \n    /// The sum of the lookahead required for LL prediction for this decision.\n    /// Note that LL prediction is only used when SLL prediction reaches a\n    /// conflict state.\n    /// \n    public var LL_TotalLook: Int64 = 0\n\n    /// \n    /// Gets the minimum lookahead required for any single LL prediction to\n    /// complete for this decision. An LL prediction completes when the algorithm\n    /// reaches a unique prediction, a conflict state (for\n    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_, an ambiguity state (for\n    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_, or a syntax error.\n    /// \n    public var LL_MinLook: Int64 = 0\n\n    /// \n    /// Gets the maximum lookahead required for any single LL prediction to\n    /// complete for this decision. An LL prediction completes when the algorithm\n    /// reaches a unique prediction, a conflict state (for\n    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_, an ambiguity state (for\n    /// _org.antlr.v4.runtime.atn.PredictionMode#LL_EXACT_AMBIG_DETECTION_, or a syntax error.\n    /// \n    public var LL_MaxLook: Int64 = 0\n\n    /// \n    /// Gets the _org.antlr.v4.runtime.atn.LookaheadEventInfo_ associated with the event where the\n    /// _#LL_MaxLook_ value was set.\n    /// \n    public var LL_MaxLookEvent: LookaheadEventInfo!\n\n    /// \n    /// A collection of _org.antlr.v4.runtime.atn.ContextSensitivityInfo_ instances describing the\n    /// context sensitivities encountered during LL prediction for this decision.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.ContextSensitivityInfo\n    /// \n    public final var contextSensitivities: Array<ContextSensitivityInfo> = Array<ContextSensitivityInfo>()\n\n    /// \n    /// A collection of _org.antlr.v4.runtime.atn.ErrorInfo_ instances describing the parse errors\n    /// identified during calls to _org.antlr.v4.runtime.atn.ParserATNSimulator#adaptivePredict_ for\n    /// this decision.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.ErrorInfo\n    /// \n    public final var errors: Array<ErrorInfo> = Array<ErrorInfo>()\n\n    /// \n    /// A collection of _org.antlr.v4.runtime.atn.AmbiguityInfo_ instances describing the\n    /// ambiguities encountered during LL prediction for this decision.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.AmbiguityInfo\n    /// \n    public final var ambiguities: Array<AmbiguityInfo> = Array<AmbiguityInfo>()\n\n    /// \n    /// A collection of _org.antlr.v4.runtime.atn.PredicateEvalInfo_ instances describing the\n    /// results of evaluating individual predicates during prediction for this\n    /// decision.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.PredicateEvalInfo\n    /// \n    public final var predicateEvals: Array<PredicateEvalInfo> = Array<PredicateEvalInfo>()\n\n    /// \n    /// The total number of ATN transitions required during SLL prediction for\n    /// this decision. An ATN transition is determined by the number of times the\n    /// DFA does not contain an edge that is required for prediction, resulting\n    /// in on-the-fly computation of that edge.\n    /// \n    /// \n    /// If DFA caching of SLL transitions is employed by the implementation, ATN\n    /// computation may cache the computed edge for efficient lookup during\n    /// future parsing of this decision. Otherwise, the SLL parsing algorithm\n    /// will use ATN transitions exclusively.\n    /// \n    /// - seealso: #SLL_ATNTransitions\n    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState\n    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState\n    /// \n    public var SLL_ATNTransitions: Int64 = 0\n\n    /// \n    /// The total number of DFA transitions required during SLL prediction for\n    /// this decision.\n    /// \n    /// If the ATN simulator implementation does not use DFA caching for SLL\n    /// transitions, this value will be 0.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState\n    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState\n    /// \n    public var SLL_DFATransitions: Int64 = 0\n\n    /// \n    /// Gets the total number of times SLL prediction completed in a conflict\n    /// state, resulting in fallback to LL prediction.\n    /// \n    /// Note that this value is not related to whether or not\n    /// _org.antlr.v4.runtime.atn.PredictionMode#SLL_ may be used successfully with a particular\n    /// grammar. If the ambiguity resolution algorithm applied to the SLL\n    /// conflicts for this decision produce the same result as LL prediction for\n    /// this decision, _org.antlr.v4.runtime.atn.PredictionMode#SLL_ would produce the same overall\n    /// parsing result as _org.antlr.v4.runtime.atn.PredictionMode#LL_.\n    /// \n    public var LL_Fallback: Int64 = 0\n\n    /// \n    /// The total number of ATN transitions required during LL prediction for\n    /// this decision. An ATN transition is determined by the number of times the\n    /// DFA does not contain an edge that is required for prediction, resulting\n    /// in on-the-fly computation of that edge.\n    /// \n    /// \n    /// If DFA caching of LL transitions is employed by the implementation, ATN\n    /// computation may cache the computed edge for efficient lookup during\n    /// future parsing of this decision. Otherwise, the LL parsing algorithm will\n    /// use ATN transitions exclusively.\n    /// \n    /// - seealso: #LL_DFATransitions\n    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#computeTargetState\n    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#computeTargetState\n    /// \n    public var LL_ATNTransitions: Int64 = 0\n\n    /// \n    /// The total number of DFA transitions required during LL prediction for\n    /// this decision.\n    /// \n    /// If the ATN simulator implementation does not use DFA caching for LL\n    /// transitions, this value will be 0.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getExistingTargetState\n    /// - seealso: org.antlr.v4.runtime.atn.LexerATNSimulator#getExistingTargetState\n    /// \n    public var LL_DFATransitions: Int64 = 0\n\n    /// \n    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.DecisionInfo_ class to contain\n    /// statistics for a particular decision.\n    /// \n    /// - parameter decision: The decision number\n    /// \n    public init(_ decision: Int) {\n        self.decision = decision\n    }\n\n\n    public var description: String {\n        var desc = \"\"\n\n        desc += \"{\"\n        desc += \"decision=\\(decision)\"\n        desc += \", contextSensitivities=\\(contextSensitivities.count)\"\n        desc += \", errors=\\(errors.count)\"\n        desc += \", ambiguities=\\(ambiguities.count)\"\n        desc += \", SLL_lookahead=\\(SLL_TotalLook)\"\n        desc += \", SLL_ATNTransitions=\\(SLL_ATNTransitions)\"\n        desc += \", SLL_DFATransitions=\\(SLL_DFATransitions)\"\n        desc += \", LL_Fallback=\\(LL_Fallback)\"\n        desc += \", LL_lookahead=\\(LL_TotalLook)\"\n        desc += \", LL_ATNTransitions=\\(LL_ATNTransitions)\"\n        desc += \"}\"\n\n        return desc\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/DecisionState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic class DecisionState: ATNState {\n    public var decision: Int = -1\n    public var nonGreedy: Bool = false\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/DefaultATNConfig.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  DefaultATNConfig.swift\n//  antlr.swift\n//\n//  Created by janyou on 15/9/14.\n//\n\nimport Foundation\n//public struct DefaultATNConfig: ATNConfig {\n//    public var state: ATNState\n//    public var alt: Int\n//    public var context: PredictionContext?\n//    public var semanticContext: SemanticContext\n//    public var hashValue: Int {\n//\n//        var hashCode: Int = 7\n//        hashCode = 31 * hashCode + state.stateNumber\n//        hashCode = 31 * hashCode + alt\n//        hashCode = 31 * hashCode + semanticContext.hashValue\n//        return hashCode\n//\n//    }\n//\n//\n//}\n//\n//public func ==(lhs: DefaultATNConfig, rhs: DefaultATNConfig) -> Bool {\n//\n//    if lhs === rhs {\n//        return true\n//    }\n//\n//    let same: Bool =\n//    lhs.state.stateNumber == rhs.state.stateNumber &&\n//            lhs.alt == rhs.alt &&\n//            lhs.semanticContext == rhs.semanticContext\n//\n//    return same\n//\n//}\n//public class DefaultATNConfig: ATNConfig {\n//\n//    override\n//    public var hashValue: Int {\n//\n//        var hashCode: Int = 7\n//        hashCode = 31 * hashCode + state.stateNumber\n//        hashCode = 31 * hashCode + alt\n//        hashCode = 31 * hashCode + semanticContext.hashValue\n//        return hashCode\n//\n//    }\n//\n//\n//}\n//\n//public func ==(lhs: DefaultATNConfig, rhs: DefaultATNConfig) -> Bool {\n//\n//    if lhs === rhs {\n//        return true\n//    }\n//\n//    let same: Bool =\n//    lhs.state.stateNumber == rhs.state.stateNumber &&\n//            lhs.alt == rhs.alt &&\n//            lhs.semanticContext == rhs.semanticContext\n//\n//    return same\n//\n//}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/EmptyPredictionContext.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\npublic class EmptyPredictionContext: SingletonPredictionContext {\n    ///\n    /// Represents `$` in local context prediction, which means wildcard.\n    /// `+x = *`.\n    ///\n    public static let Instance = EmptyPredictionContext()\n\n    public init() {\n        super.init(nil, PredictionContext.EMPTY_RETURN_STATE)\n    }\n\n    override\n    public func isEmpty() -> Bool {\n        return true\n    }\n\n    override\n    public func size() -> Int {\n        return 1\n    }\n\n    override\n    public func getParent(_ index: Int) -> PredictionContext? {\n        return nil\n    }\n\n    override\n    public func getReturnState(_ index: Int) -> Int {\n        return returnState\n    }\n\n\n    override\n    public var description: String {\n        return \"$\"\n    }\n}\n\n\npublic func ==(lhs: EmptyPredictionContext, rhs: EmptyPredictionContext) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n\n    return false\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/EpsilonTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic final class EpsilonTransition: Transition, CustomStringConvertible {\n\n    private let outermostPrecedenceReturnInside: Int\n\n    public convenience override init(_ target: ATNState) {\n        self.init(target, -1)\n    }\n\n    public init(_ target: ATNState, _ outermostPrecedenceReturn: Int) {\n\n        self.outermostPrecedenceReturnInside = outermostPrecedenceReturn\n        super.init(target)\n    }\n\n    /// \n    /// - returns: the rule index of a precedence rule for which this transition is\n    /// returning from, where the precedence value is 0; otherwise, -1.\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed()\n    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#applyPrecedenceFilter(org.antlr.v4.runtime.atn.ATNConfigSet)\n    /// -  4.4.1\n    /// \n    public func outermostPrecedenceReturn() -> Int {\n        return outermostPrecedenceReturnInside\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.EPSILON\n    }\n\n    override\n    public func isEpsilon() -> Bool {\n        return true\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return false\n    }\n\n\n    public var description: String {\n        return \"epsilon\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ErrorInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This class represents profiling event information for a syntax error\n/// identified during prediction. Syntax errors occur when the prediction\n/// algorithm is unable to identify an alternative which would lead to a\n/// successful parse.\n/// \n/// - seealso: org.antlr.v4.runtime.Parser#notifyErrorListeners(org.antlr.v4.runtime.Token, String, org.antlr.v4.runtime.RecognitionException)\n/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#syntaxError\n/// \n/// -  4.3\n/// \n\npublic class ErrorInfo: DecisionEventInfo {\n    /// \n    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.ErrorInfo_ class with the\n    /// specified detailed syntax error information.\n    /// \n    /// - parameter decision: The decision number\n    /// - parameter configs: The final configuration set reached during prediction\n    /// prior to reaching the _org.antlr.v4.runtime.atn.ATNSimulator#ERROR_ state\n    /// - parameter input: The input token stream\n    /// - parameter startIndex: The start index for the current prediction\n    /// - parameter stopIndex: The index at which the syntax error was identified\n    /// - parameter fullCtx: `true` if the syntax error was identified during LL\n    /// prediction; otherwise, `false` if the syntax error was identified\n    /// during SLL prediction\n    /// \n    public init(_ decision: Int,\n                _ configs: ATNConfigSet,\n                _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int,\n                _ fullCtx: Bool) {\n        super.init(decision, configs, input, startIndex, stopIndex, fullCtx)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LL1Analyzer.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\npublic class LL1Analyzer {\n    ///\n    /// Special value added to the lookahead sets to indicate that we hit\n    /// a predicate during analysis if `seeThruPreds==false`.\n    ///\n    public let HIT_PRED: Int = CommonToken.INVALID_TYPE\n\n    public let atn: ATN\n\n    public init(_ atn: ATN) {\n        self.atn = atn\n    }\n\n    ///\n    /// Calculates the SLL(1) expected lookahead set for each outgoing transition\n    /// of an _org.antlr.v4.runtime.atn.ATNState_. The returned array has one element for each\n    /// outgoing transition in `s`. If the closure from transition\n    /// __i__ leads to a semantic predicate before matching a symbol, the\n    /// element at index __i__ of the result will be `null`.\n    ///\n    /// - parameter s: the ATN state\n    /// - returns: the expected symbols for each outgoing transition of `s`.\n    ///\n    public func getDecisionLookahead(_ s: ATNState?) -> [IntervalSet?]? {\n\n        guard let s = s else {\n             return nil\n        }\n        let length = s.getNumberOfTransitions()\n        var look = [IntervalSet?](repeating: nil, count: length)\n        for alt in 0..<length {\n            look[alt] = IntervalSet()\n            var lookBusy = Set<ATNConfig>()\n            let seeThruPreds = false // fail to get lookahead upon pred\n            _LOOK(s.transition(alt).target, nil, EmptyPredictionContext.Instance,\n                    look[alt]!, &lookBusy, BitSet(), seeThruPreds, false)\n            // Wipe out lookahead for this alternative if we found nothing\n            // or we had a predicate when we !seeThruPreds\n            if look[alt]!.size() == 0 || look[alt]!.contains(HIT_PRED) {\n                look[alt] = nil\n            }\n        }\n        return look\n    }\n\n    ///\n    /// Compute set of tokens that can follow `s` in the ATN in the\n    /// specified `ctx`.\n    ///\n    /// If `ctx` is `null` and the end of the rule containing\n    /// `s` is reached, _org.antlr.v4.runtime.Token#EPSILON_ is added to the result set.\n    /// If `ctx` is not `null` and the end of the outermost rule is\n    /// reached, _org.antlr.v4.runtime.Token#EOF_ is added to the result set.\n    ///\n    /// - parameter s: the ATN state\n    /// - parameter ctx: the complete parser context, or `null` if the context\n    /// should be ignored\n    ///\n    /// - returns: The set of tokens that can follow `s` in the ATN in the\n    /// specified `ctx`.\n    ///\n    public func LOOK(_ s: ATNState, _ ctx: RuleContext?) -> IntervalSet {\n        return LOOK(s, nil, ctx)\n    }\n\n    ///\n    /// Compute set of tokens that can follow `s` in the ATN in the\n    /// specified `ctx`.\n    ///\n    /// If `ctx` is `null` and the end of the rule containing\n    /// `s` is reached, _org.antlr.v4.runtime.Token#EPSILON_ is added to the result set.\n    /// If `ctx` is not `null` and the end of the outermost rule is\n    /// reached, _org.antlr.v4.runtime.Token#EOF_ is added to the result set.\n    ///\n    /// - parameter s: the ATN state\n    /// - parameter stopState: the ATN state to stop at. This can be a\n    /// _org.antlr.v4.runtime.atn.BlockEndState_ to detect epsilon paths through a closure.\n    /// - parameter ctx: the complete parser context, or `null` if the context\n    /// should be ignored\n    ///\n    /// - returns: The set of tokens that can follow `s` in the ATN in the\n    /// specified `ctx`.\n    ///\n\n    public func LOOK(_ s: ATNState, _ stopState: ATNState?, _ ctx: RuleContext?) -> IntervalSet {\n        let r = IntervalSet()\n        let seeThruPreds = true // ignore preds; get all lookahead\n        let lookContext = ctx != nil ? PredictionContext.fromRuleContext(s.atn!, ctx) : nil\n        var config = Set<ATNConfig>()\n        _LOOK(s, stopState, lookContext, r, &config, BitSet(), seeThruPreds, true)\n        return r\n    }\n\n    ///\n    /// Compute set of tokens that can follow `s` in the ATN in the\n    /// specified `ctx`.\n    ///\n    /// If `ctx` is `null` and `stopState` or the end of the\n    /// rule containing `s` is reached, _org.antlr.v4.runtime.Token#EPSILON_ is added to\n    /// the result set. If `ctx` is not `null` and `addEOF` is\n    /// `true` and `stopState` or the end of the outermost rule is\n    /// reached, _org.antlr.v4.runtime.Token#EOF_ is added to the result set.\n    ///\n    /// - parameter s: the ATN state.\n    /// - parameter stopState: the ATN state to stop at. This can be a\n    /// _org.antlr.v4.runtime.atn.BlockEndState_ to detect epsilon paths through a closure.\n    /// - parameter ctx: The outer context, or `null` if the outer context should\n    /// not be used.\n    /// - parameter look: The result lookahead set.\n    /// - parameter lookBusy: A set used for preventing epsilon closures in the ATN\n    /// from causing a stack overflow. Outside code should pass\n    /// `new HashSet<ATNConfig>` for this argument.\n    /// - parameter calledRuleStack: A set used for preventing left recursion in the\n    /// ATN from causing a stack overflow. Outside code should pass\n    /// `new BitSet()` for this argument.\n    /// - parameter seeThruPreds: `true` to true semantic predicates as\n    /// implicitly `true` and \"see through them\", otherwise `false`\n    /// to treat semantic predicates as opaque and add _#HIT_PRED_ to the\n    /// result if one is encountered.\n    /// - parameter addEOF: Add _org.antlr.v4.runtime.Token#EOF_ to the result if the end of the\n    /// outermost context is reached. This parameter has no effect if `ctx`\n    /// is `null`.\n    ///\n    internal func _LOOK(_ s: ATNState,\n                        _ stopState: ATNState?,\n                        _ ctx: PredictionContext?,\n                        _ look: IntervalSet,\n                        _ lookBusy: inout Set<ATNConfig>,\n                        _ calledRuleStack: BitSet,\n                        _ seeThruPreds: Bool,\n                        _ addEOF: Bool) {\n        // print (\"_LOOK(\\(s.stateNumber), ctx=\\(ctx)\");\n        let c = ATNConfig(s, ATN.INVALID_ALT_NUMBER, ctx)\n        if lookBusy.contains(c) {\n            return\n        } else {\n            lookBusy.insert(c)\n        }\n\n        if s == stopState {\n            guard let ctx = ctx else {\n                try! look.add(CommonToken.EPSILON)\n                return\n            }\n\n            if ctx.isEmpty() && addEOF {\n                try! look.add(CommonToken.EOF)\n                return\n            }\n\n        }\n\n        if s is RuleStopState {\n            guard let ctx = ctx else {\n                try! look.add(CommonToken.EPSILON)\n                return\n            }\n\n            if ctx.isEmpty() && addEOF {\n                try! look.add(CommonToken.EOF)\n                return\n            }\n\n            if ctx != EmptyPredictionContext.Instance {\n                let removed = try! calledRuleStack.get(s.ruleIndex!)\n                try! calledRuleStack.clear(s.ruleIndex!)\n                defer {\n                    if removed {\n                         try! calledRuleStack.set(s.ruleIndex!)\n                     }\n                }\n                // run thru all possible stack tops in ctx\n                let length = ctx.size()\n                for i in 0..<length {\n                    let returnState = atn.states[(ctx.getReturnState(i))]!\n                    _LOOK(returnState, stopState, ctx.getParent(i), look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)\n                }\n                return\n            }\n        }\n\n        let n = s.getNumberOfTransitions()\n        for i in 0..<n {\n            let t = s.transition(i)\n            if let rt = t as? RuleTransition {\n                if try! calledRuleStack.get(rt.target.ruleIndex!) {\n                    continue\n                }\n\n                let newContext = SingletonPredictionContext.create(ctx, rt.followState.stateNumber)\n                try! calledRuleStack.set(rt.target.ruleIndex!)\n                _LOOK(t.target, stopState, newContext, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)\n                try! calledRuleStack.clear(rt.target.ruleIndex!)\n            }\n            else if t is AbstractPredicateTransition {\n                if seeThruPreds {\n                    _LOOK(t.target, stopState, ctx, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)\n                } else {\n                    try! look.add(HIT_PRED)\n                }\n            }\n            else if t.isEpsilon() {\n                _LOOK(t.target, stopState, ctx, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)\n            }\n            else if t is WildcardTransition {\n                try! look.addAll(IntervalSet.of(CommonToken.MIN_USER_TOKEN_TYPE, atn.maxTokenType))\n            }\n            else {\n                var set = t.labelIntervalSet()\n                if set != nil {\n                    if t is NotSetTransition {\n                        set = set!.complement(IntervalSet.of(CommonToken.MIN_USER_TOKEN_TYPE, atn.maxTokenType)) as? IntervalSet\n                    }\n                    try! look.addAll(set)\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerATNConfig.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\npublic class LexerATNConfig: ATNConfig {\n    ///\n    /// This is the backing field for _#getLexerActionExecutor_.\n    ///\n    private let lexerActionExecutor: LexerActionExecutor?\n\n    fileprivate let passedThroughNonGreedyDecision: Bool\n\n    public init(_ state: ATNState,\n                _ alt: Int,\n                _ context: PredictionContext) {\n\n        self.passedThroughNonGreedyDecision = false\n        self.lexerActionExecutor = nil\n        super.init(state, alt, context, SemanticContext.Empty.Instance)\n    }\n\n    public init(_ state: ATNState,\n                _ alt: Int,\n                _ context: PredictionContext,\n                _ lexerActionExecutor: LexerActionExecutor?) {\n\n        self.lexerActionExecutor = lexerActionExecutor\n        self.passedThroughNonGreedyDecision = false\n        super.init(state, alt, context, SemanticContext.Empty.Instance)\n    }\n\n    public init(_ c: LexerATNConfig, _ state: ATNState) {\n        self.lexerActionExecutor = c.lexerActionExecutor\n        self.passedThroughNonGreedyDecision = LexerATNConfig.checkNonGreedyDecision(c, state)\n        super.init(c, state, c.context, c.semanticContext)\n\n    }\n\n    public init(_ c: LexerATNConfig, _ state: ATNState,\n                _ lexerActionExecutor: LexerActionExecutor?) {\n\n        self.lexerActionExecutor = lexerActionExecutor\n        self.passedThroughNonGreedyDecision = LexerATNConfig.checkNonGreedyDecision(c, state)\n        super.init(c, state, c.context, c.semanticContext)\n    }\n\n    public init(_ c: LexerATNConfig, _ state: ATNState,\n                _ context: PredictionContext) {\n\n        self.lexerActionExecutor = c.lexerActionExecutor\n        self.passedThroughNonGreedyDecision = LexerATNConfig.checkNonGreedyDecision(c, state)\n\n        super.init(c, state, context, c.semanticContext)\n    }\n\n    private static func checkNonGreedyDecision(_ source: LexerATNConfig, _ target: ATNState) -> Bool {\n        return source.passedThroughNonGreedyDecision\n                || target is DecisionState && (target as! DecisionState).nonGreedy\n    }\n    ///\n    /// Gets the _org.antlr.v4.runtime.atn.LexerActionExecutor_ capable of executing the embedded\n    /// action(s) for the current configuration.\n    ///\n    public final func getLexerActionExecutor() -> LexerActionExecutor? {\n        return lexerActionExecutor\n    }\n\n    public final func hasPassedThroughNonGreedyDecision() -> Bool {\n        return passedThroughNonGreedyDecision\n    }\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(state.stateNumber)\n        hasher.combine(alt)\n        hasher.combine(context)\n        hasher.combine(semanticContext)\n        hasher.combine(passedThroughNonGreedyDecision)\n        hasher.combine(lexerActionExecutor)\n    }\n}\n\n//useless\npublic func ==(lhs: LexerATNConfig, rhs: LexerATNConfig) -> Bool {\n\n    if lhs === rhs {\n        return true\n    }\n\n\n    //let lexerOther : LexerATNConfig = rhs  // as! LexerATNConfig;\n    if lhs.passedThroughNonGreedyDecision != rhs.passedThroughNonGreedyDecision {\n        return false\n    }\n\n\n\n    if lhs.state.stateNumber != rhs.state.stateNumber {\n        return false\n    }\n    if lhs.alt != rhs.alt {\n        return false\n    }\n\n    if lhs.isPrecedenceFilterSuppressed() != rhs.isPrecedenceFilterSuppressed() {\n        return false\n    }\n\n    if lhs.getLexerActionExecutor() != rhs.getLexerActionExecutor() {\n        return false\n    }\n\n    if lhs.context != rhs.context {\n        return false\n    }\n\n    return  lhs.semanticContext == rhs.semanticContext\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerATNSimulator.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\n\n///\n/// \"dup\" of ParserInterpreter\n///\n\nopen class LexerATNSimulator: ATNSimulator {\n    public static let debug = false\n    public let dfa_debug = false\n\n    public static let MIN_DFA_EDGE = 0\n    public static let MAX_DFA_EDGE = 127  // forces unicode to stay in ATN\n\n    ///\n    /// When we hit an accept state in either the DFA or the ATN, we\n    /// have to notify the character stream to start buffering characters\n    /// via _org.antlr.v4.runtime.IntStream#mark_ and record the current state. The current sim state\n    /// includes the current index into the input, the current line,\n    /// and current character position in that line. Note that the Lexer is\n    /// tracking the starting line and characterization of the token. These\n    /// variables track the \"state\" of the simulator when it hits an accept state.\n    ///\n    /// We track these variables separately for the DFA and ATN simulation\n    /// because the DFA simulation often has to fail over to the ATN\n    /// simulation. If the ATN simulation fails, we need the DFA to fall\n    /// back to its previously accepted state, if any. If the ATN succeeds,\n    /// then the ATN does the accept and the DFA simulator that invoked it\n    /// can simply return the predicted token type.\n    ///\n\n    internal class SimState {\n        internal var index: Int = -1\n        internal var line: Int = 0\n        internal var charPos: Int = -1\n        internal var dfaState: DFAState?\n\n        internal func reset() {\n            index = -1\n            line = 0\n            charPos = -1\n            dfaState = nil\n        }\n    }\n\n\n    internal weak var recog: Lexer?\n\n    ///\n    /// The current token's starting index into the character stream.\n    /// Shared across DFA to ATN simulation in case the ATN fails and the\n    /// DFA did not have a previous accept state. In this case, we use the\n    /// ATN-generated exception object.\n    ///\n    internal var startIndex = -1\n\n    ///\n    /// line number 1..n within the input\n    ///\n    public var line = 1\n\n    ///\n    /// The index of the character relative to the beginning of the line 0..n-1\n    ///\n    public var charPositionInLine = 0\n\n    public private(set) final var decisionToDFA: [DFA]\n\n    internal var mode = Lexer.DEFAULT_MODE\n\n    ///\n    /// Used during DFA/ATN exec to record the most recent accept configuration info\n    ///\n\n    internal final var prevAccept = SimState()\n\n    public convenience init(_ atn: ATN, _ decisionToDFA: [DFA],\n        _ sharedContextCache: PredictionContextCache) {\n            self.init(nil, atn, decisionToDFA, sharedContextCache)\n    }\n\n    public init(_ recog: Lexer?, _ atn: ATN,\n        _ decisionToDFA: [DFA],\n        _ sharedContextCache: PredictionContextCache) {\n\n            self.decisionToDFA = decisionToDFA\n            self.recog = recog\n            super.init(atn, sharedContextCache)\n    }\n\n    open func copyState(_ simulator: LexerATNSimulator) {\n        self.charPositionInLine = simulator.charPositionInLine\n        self.line = simulator.line\n        self.mode = simulator.mode\n        self.startIndex = simulator.startIndex\n    }\n\n    open func match(_ input: CharStream, _ mode: Int) throws -> Int {\n        self.mode = mode\n        let mark = input.mark()\n        defer {\n            try! input.release(mark)\n        }\n\n        self.startIndex = input.index()\n        self.prevAccept.reset()\n        let dfa = decisionToDFA[mode]\n\n        if let s0 = dfa.s0 {\n            return try execATN(input, s0)\n        }\n        else {\n            return try matchATN(input)\n        }\n    }\n\n    override\n    open func reset() {\n        prevAccept.reset()\n        startIndex = -1\n        line = 1\n        charPositionInLine = 0\n        mode = Lexer.DEFAULT_MODE\n    }\n\n    override\n    open func clearDFA() {\n        for d in 0..<decisionToDFA.count {\n            decisionToDFA[d] = DFA(atn.getDecisionState(d)!, d)\n        }\n    }\n\n    internal func matchATN(_ input: CharStream) throws -> Int {\n        let startState = atn.modeToStartState[mode]\n\n        if LexerATNSimulator.debug {\n            print(\"matchATN mode \\(mode) start: \\(startState)\\n\")\n        }\n\n        let old_mode = mode\n\n        let s0_closure = try computeStartState(input, startState)\n        let suppressEdge = s0_closure.hasSemanticContext\n        s0_closure.hasSemanticContext = false\n\n        let next = addDFAState(s0_closure)\n        if !suppressEdge {\n            decisionToDFA[mode].s0 = next\n        }\n\n        let predict = try execATN(input, next)\n\n        if LexerATNSimulator.debug {\n            print(\"DFA after matchATN: \\(decisionToDFA[old_mode].toLexerString())\")\n        }\n\n        return predict\n    }\n\n    internal func execATN(_ input: CharStream, _ ds0: DFAState) throws -> Int {\n        //print(\"enter exec index \"+input.index()+\" from \"+ds0.configs);\n        if LexerATNSimulator.debug {\n            print(\"start state closure=\\(ds0.configs)\\n\")\n        }\n\n        if ds0.isAcceptState {\n            // allow zero-length tokens\n            captureSimState(prevAccept, input, ds0)\n        }\n\n        var t = try input.LA(1)\n\n        var s = ds0 // s is current/from DFA state\n\n        while true {\n            // while more work\n            if LexerATNSimulator.debug {\n                print(\"execATN loop starting closure: \\(s.configs)\\n\")\n            }\n\n            // As we move src->trg, src->trg, we keep track of the previous trg to\n            // avoid looking up the DFA state again, which is expensive.\n            // If the previous target was already part of the DFA, we might\n            // be able to avoid doing a reach operation upon t. If s!=null,\n            // it means that semantic predicates didn't prevent us from\n            // creating a DFA state. Once we know s!=null, we check to see if\n            // the DFA state has an edge already for t. If so, we can just reuse\n            // it's configuration set; there's no point in re-computing it.\n            // This is kind of like doing DFA simulation within the ATN\n            // simulation because DFA simulation is really just a way to avoid\n            // computing reach/closure sets. Technically, once we know that\n            // we have a previously added DFA state, we could jump over to\n            // the DFA simulator. But, that would mean popping back and forth\n            // a lot and making things more complicated algorithmically.\n            // This optimization makes a lot of sense for loops within DFA.\n            // A character will take us back to an existing DFA state\n            // that already has lots of edges out of it. e.g., .* in comments.\n            var target: DFAState\n            if let existingTarget = getExistingTargetState(s, t) {\n                target = existingTarget\n            } else {\n                target = try computeTargetState(input, s, t)\n            }\n\n            if target == ATNSimulator.ERROR {\n                break\n            }\n\n            // If this is a consumable input element, make sure to consume before\n            // capturing the accept state so the input index, line, and char\n            // position accurately reflect the state of the interpreter at the\n            // end of the token.\n            if t != BufferedTokenStream.EOF {\n                try consume(input)\n            }\n\n            if target.isAcceptState {\n                captureSimState(prevAccept, input, target)\n                if t == BufferedTokenStream.EOF {\n                    break\n                }\n            }\n\n            t = try input.LA(1)\n            s = target // flip; current DFA target becomes new src/from state\n        }\n\n        return try failOrAccept(prevAccept, input, s.configs, t)\n    }\n\n    ///\n    /// Get an existing target state for an edge in the DFA. If the target state\n    /// for the edge has not yet been computed or is otherwise not available,\n    /// this method returns `null`.\n    ///\n    /// - parameter s: The current DFA state\n    /// - parameter t: The next input symbol\n    /// - returns: The existing target DFA state for the given input symbol\n    /// `t`, or `null` if the target state for this edge is not\n    /// already cached\n    ///\n\n    internal func getExistingTargetState(_ s: DFAState, _ t: Int) -> DFAState? {\n        if s.edges == nil || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE {\n            return nil\n        }\n\n        let target = s.edges[t - LexerATNSimulator.MIN_DFA_EDGE]\n        if LexerATNSimulator.debug && target != nil {\n            print(\"reuse state \\(s.stateNumber) edge to \\(target!.stateNumber)\")\n        }\n\n        return target\n    }\n\n    ///\n    /// Compute a target state for an edge in the DFA, and attempt to add the\n    /// computed state and corresponding edge to the DFA.\n    ///\n    /// - parameter input: The input stream\n    /// - parameter s: The current DFA state\n    /// - parameter t: The next input symbol\n    ///\n    /// - returns: The computed target DFA state for the given input symbol\n    /// `t`. If `t` does not lead to a valid DFA state, this method\n    /// returns _#ERROR_.\n    ///\n\n    internal func computeTargetState(_ input: CharStream, _ s: DFAState, _ t: Int) throws -> DFAState {\n        let reach = ATNConfigSet(true, isOrdered: true)\n\n        // if we don't find an existing DFA state\n        // Fill reach starting from closure, following t transitions\n\n        try getReachableConfigSet(input, s.configs, reach, t)\n\n        if reach.isEmpty() {\n            // we got nowhere on t from s\n            if !reach.hasSemanticContext {\n                // we got nowhere on t, don't throw out this knowledge; it'd\n                // cause a failover from DFA later.\n                addDFAEdge(s, t, ATNSimulator.ERROR)\n            }\n\n            // stop when we can't match any more char\n            return ATNSimulator.ERROR\n        }\n\n        // Add an edge from s to target DFA found/created for reach\n        return addDFAEdge(s, t, reach)\n    }\n\n    internal func failOrAccept(_ prevAccept: SimState, _ input: CharStream,\n        _ reach: ATNConfigSet, _ t: Int) throws -> Int {\n            if let dfaState = prevAccept.dfaState {\n                let lexerActionExecutor = dfaState.lexerActionExecutor\n                try accept(input, lexerActionExecutor, startIndex,\n                    prevAccept.index, prevAccept.line, prevAccept.charPos)\n                return dfaState.prediction\n            } else {\n                // if no accept and EOF is first char, return EOF\n                if t == BufferedTokenStream.EOF && input.index() == startIndex {\n                    return CommonToken.EOF\n                }\n                throw ANTLRException.recognition(e: LexerNoViableAltException(recog, input, startIndex, reach))\n            }\n    }\n\n    ///\n    /// Given a starting configuration set, figure out all ATN configurations\n    /// we can reach upon input `t`. Parameter `reach` is a return\n    /// parameter.\n    ///\n    internal func getReachableConfigSet(_ input: CharStream, _ closureConfig: ATNConfigSet, _ reach: ATNConfigSet, _ t: Int) throws {\n        // this is used to skip processing for configs which have a lower priority\n        // than a config that already reached an accept state for the same rule\n        var skipAlt = ATN.INVALID_ALT_NUMBER\n        for c in closureConfig.configs {\n            guard let c = c as? LexerATNConfig else {\n                continue\n            }\n            let currentAltReachedAcceptState = (c.alt == skipAlt)\n            if currentAltReachedAcceptState && c.hasPassedThroughNonGreedyDecision() {\n                continue\n            }\n\n            if LexerATNSimulator.debug {\n                print(\"testing \\(getTokenName(t)) at \\(c.toString(recog, true))\\n\")\n\n            }\n\n            let n = c.state.getNumberOfTransitions()\n            for ti in 0..<n {\n                // for each transition\n                let trans = c.state.transition(ti)\n                if let target = getReachableTarget(trans, t) {\n                    var lexerActionExecutor = c.getLexerActionExecutor()\n                    if let lex = lexerActionExecutor {\n                        lexerActionExecutor = lex.fixOffsetBeforeMatch(input.index() - startIndex)\n                    }\n\n                    let treatEofAsEpsilon = (t == BufferedTokenStream.EOF)\n                    if try closure(input,\n                        LexerATNConfig(c, target, lexerActionExecutor),\n                        reach,\n                        currentAltReachedAcceptState,\n                        true,\n                        treatEofAsEpsilon) {\n                            // any remaining configs for this alt have a lower priority than\n                            // the one that just reached an accept state.\n                            skipAlt = c.alt\n                            break\n                    }\n                }\n            }\n        }\n    }\n\n    internal func accept(_ input: CharStream, _ lexerActionExecutor: LexerActionExecutor?,\n        _ startIndex: Int, _ index: Int, _ line: Int, _ charPos: Int) throws {\n            if LexerATNSimulator.debug {\n                print(\"ACTION \\(String(describing: lexerActionExecutor))\\n\")\n            }\n\n            // seek to after last char in token\n            try input.seek(index)\n            self.line = line\n            self.charPositionInLine = charPos\n            //TODO: CHECK\n            if let lexerActionExecutor = lexerActionExecutor, let recog = recog {\n                try lexerActionExecutor.execute(recog, input, startIndex)\n            }\n    }\n\n\n    internal func getReachableTarget(_ trans: Transition, _ t: Int) -> ATNState? {\n        if trans.matches(t, Character.MIN_VALUE, Character.MAX_VALUE) {\n            return trans.target\n        }\n\n        return nil\n    }\n\n\n    final func computeStartState(_ input: CharStream,\n        _ p: ATNState) throws -> ATNConfigSet {\n            let initialContext = EmptyPredictionContext.Instance\n            let configs = ATNConfigSet(true, isOrdered: true)\n            let length = p.getNumberOfTransitions()\n            for i in 0..<length {\n                let target = p.transition(i).target\n                let c = LexerATNConfig(target, i + 1, initialContext)\n                try closure(input, c, configs, false, false, false)\n            }\n            return configs\n    }\n\n    ///\n    /// Since the alternatives within any lexer decision are ordered by\n    /// preference, this method stops pursuing the closure as soon as an accept\n    /// state is reached. After the first accept state is reached by depth-first\n    /// search from `config`, all other (potentially reachable) states for\n    /// this rule would have a lower priority.\n    ///\n    /// - returns: `true` if an accept state is reached, otherwise\n    /// `false`.\n    ///\n    @discardableResult\n    final func closure(_ input: CharStream, _ config: LexerATNConfig, _ configs: ATNConfigSet, _ currentAltReachedAcceptState: Bool, _ speculative: Bool, _ treatEofAsEpsilon: Bool) throws -> Bool {\n        var currentAltReachedAcceptState = currentAltReachedAcceptState\n        if LexerATNSimulator.debug {\n            print(\"closure(\" + config.toString(recog, true) + \")\")\n        }\n\n        if config.state is RuleStopState {\n            if LexerATNSimulator.debug {\n                if let recog = recog {\n                    print(\"closure at \\(recog.getRuleNames()[config.state.ruleIndex!]) rule stop \\(config)\\n\")\n                } else {\n                    print(\"closure at rule stop \\(config)\\n\")\n                }\n            }\n\n            if config.context?.hasEmptyPath() ?? true {\n                if config.context?.isEmpty() ?? true {\n                    try configs.add(config)\n                    return true\n                } else {\n                    try configs.add(LexerATNConfig(config, config.state, EmptyPredictionContext.Instance))\n                    currentAltReachedAcceptState = true\n                }\n            }\n\n            if let configContext = config.context , !configContext.isEmpty() {\n                let length = configContext.size()\n                for i in 0..<length {\n                    if configContext.getReturnState(i) != PredictionContext.EMPTY_RETURN_STATE {\n                        let newContext = configContext.getParent(i)! // \"pop\" return state\n                        let returnState = atn.states[configContext.getReturnState(i)]\n                        let c = LexerATNConfig(config, returnState!, newContext)\n                        currentAltReachedAcceptState = try closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon)\n                    }\n                }\n            }\n\n            return currentAltReachedAcceptState\n        }\n\n        // optimization\n        if !config.state.onlyHasEpsilonTransitions() {\n            if !currentAltReachedAcceptState || !config.hasPassedThroughNonGreedyDecision() {\n                try configs.add(config)\n            }\n        }\n\n        let p = config.state\n        let length = p.getNumberOfTransitions()\n        for i in 0..<length {\n            let t = p.transition(i)\n            if let c = try getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon) {\n                currentAltReachedAcceptState = try closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon)\n            }\n        }\n\n        return currentAltReachedAcceptState\n    }\n\n    // side-effect: can alter configs.hasSemanticContext\n\n    final func getEpsilonTarget(_ input: CharStream,\n        _ config: LexerATNConfig,\n        _ t: Transition,\n        _ configs: ATNConfigSet,\n        _ speculative: Bool,\n        _ treatEofAsEpsilon: Bool) throws -> LexerATNConfig? {\n            var c: LexerATNConfig? = nil\n            switch t.getSerializationType() {\n            case Transition.RULE:\n                let ruleTransition = t as! RuleTransition\n                let newContext = SingletonPredictionContext.create(config.context, ruleTransition.followState.stateNumber)\n                c = LexerATNConfig(config, t.target, newContext)\n                break\n\n            case Transition.PRECEDENCE:\n                throw ANTLRError.unsupportedOperation(msg: \"Precedence predicates are not supported in lexers.\")\n\n\n            case Transition.PREDICATE:\n                ///\n                /// Track traversing semantic predicates. If we traverse,\n                /// we cannot add a DFA state for this \"reach\" computation\n                /// because the DFA would not test the predicate again in the\n                /// future. Rather than creating collections of semantic predicates\n                /// like v3 and testing them on prediction, v4 will test them on the\n                /// fly all the time using the ATN not the DFA. This is slower but\n                /// semantically it's not used that often. One of the key elements to\n                /// this predicate mechanism is not adding DFA states that see\n                /// predicates immediately afterwards in the ATN. For example,\n                ///\n                /// a : ID {p1}? | ID {p2}? ;\n                ///\n                /// should create the start state for rule 'a' (to save start state\n                /// competition), but should not create target of ID state. The\n                /// collection of ATN states the following ID references includes\n                /// states reached by traversing predicates. Since this is when we\n                /// test them, we cannot cash the DFA state target of ID.\n                ///\n                let pt = t as! PredicateTransition\n                if LexerATNSimulator.debug {\n                    print(\"EVAL rule \\(pt.ruleIndex):\\(pt.predIndex)\")\n                }\n                configs.hasSemanticContext = true\n                if try evaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative) {\n                    c = LexerATNConfig(config, t.target)\n                }\n                break\n\n            case Transition.ACTION:\n                if config.context == nil || config.context!.hasEmptyPath() {\n                    // execute actions anywhere in the start rule for a token.\n                    //\n                    // TODO: if the entry rule is invoked recursively, some\n                    // actions may be executed during the recursive call. The\n                    // problem can appear when hasEmptyPath() is true but\n                    // isEmpty() is false. In this case, the config needs to be\n                    // split into two contexts - one with just the empty path\n                    // and another with everything but the empty path.\n                    // Unfortunately, the current algorithm does not allow\n                    // getEpsilonTarget to return two configurations, so\n                    // additional modifications are needed before we can support\n                    // the split operation.\n                    let lexerActionExecutor = LexerActionExecutor.append(config.getLexerActionExecutor(), atn.lexerActions[(t as! ActionTransition).actionIndex])\n                    c = LexerATNConfig(config, t.target, lexerActionExecutor)\n                    break\n                } else {\n                    // ignore actions in referenced rules\n                    c = LexerATNConfig(config, t.target)\n                    break\n                }\n\n            case Transition.EPSILON:\n                c = LexerATNConfig(config, t.target)\n                break\n\n            case Transition.ATOM: fallthrough\n            case Transition.RANGE: fallthrough\n            case Transition.SET:\n                if treatEofAsEpsilon {\n                    if t.matches(BufferedTokenStream.EOF, Character.MIN_VALUE, Character.MAX_VALUE) {\n                        c = LexerATNConfig(config, t.target)\n                        break\n                    }\n                }\n\n                break\n            default:\n                return c\n            }\n\n            return c\n    }\n\n    ///\n    /// Evaluate a predicate specified in the lexer.\n    ///\n    /// If `speculative` is `true`, this method was called before\n    /// _#consume_ for the matched character. This method should call\n    /// _#consume_ before evaluating the predicate to ensure position\n    /// sensitive values, including _org.antlr.v4.runtime.Lexer#getText_, _org.antlr.v4.runtime.Lexer#getLine_,\n    /// and _org.antlr.v4.runtime.Lexer#getCharPositionInLine_, properly reflect the current\n    /// lexer state. This method should restore `input` and the simulator\n    /// to the original state before returning (i.e. undo the actions made by the\n    /// call to _#consume_.\n    ///\n    /// - parameter input: The input stream.\n    /// - parameter ruleIndex: The rule containing the predicate.\n    /// - parameter predIndex: The index of the predicate within the rule.\n    /// - parameter speculative: `true` if the current index in `input` is\n    /// one character before the predicate's location.\n    ///\n    /// - returns: `true` if the specified predicate evaluates to\n    /// `true`.\n    ///\n    final func evaluatePredicate(_ input: CharStream, _ ruleIndex: Int, _ predIndex: Int, _ speculative: Bool) throws -> Bool {\n        // assume true if no recognizer was provided\n        guard let recog = recog else {\n            return true\n        }\n        if !speculative {\n            return try recog.sempred(nil, ruleIndex, predIndex)\n        }\n\n        let savedCharPositionInLine = charPositionInLine\n        let savedLine = line\n        let index = input.index()\n        let marker = input.mark()\n        do {\n            try consume(input)\n            defer\n            {\n                charPositionInLine = savedCharPositionInLine\n                line = savedLine\n                try! input.seek(index)\n                try! input.release(marker)\n            }\n\n            return try recog.sempred(nil, ruleIndex, predIndex)\n        }\n\n    }\n\n    final func captureSimState(_ settings: SimState,\n        _ input: CharStream,\n        _ dfaState: DFAState) {\n            settings.index = input.index()\n            settings.line = line\n            settings.charPos = charPositionInLine\n            settings.dfaState = dfaState\n    }\n\n\n    private final func addDFAEdge(_ from: DFAState,\n        _ t: Int,\n        _ q: ATNConfigSet) -> DFAState {\n            ///\n            /// leading to this call, ATNConfigSet.hasSemanticContext is used as a\n            /// marker indicating dynamic predicate evaluation makes this edge\n            /// dependent on the specific input sequence, so the static edge in the\n            /// DFA should be omitted. The target DFAState is still created since\n            /// execATN has the ability to resynchronize with the DFA state cache\n            /// following the predicate evaluation step.\n            ///\n            /// TJP notes: next time through the DFA, we see a pred again and eval.\n            /// If that gets us to a previously created (but dangling) DFA\n            /// state, we can continue in pure DFA mode from there.\n            ///\n            let suppressEdge = q.hasSemanticContext\n            q.hasSemanticContext = false\n            let to = addDFAState(q)\n\n            if suppressEdge {\n                return to\n            }\n\n            addDFAEdge(from, t, to)\n            return to\n    }\n\n    private final func addDFAEdge(_ p: DFAState, _ t: Int, _ q: DFAState) {\n        if t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE {\n            // Only track edges within the DFA bounds\n            return\n        }\n\n        if LexerATNSimulator.debug {\n            print(\"EDGE \\(p) -> \\(q) upon \\(t)\")\n        }\n\n        p.mutex.synchronized {\n            if p.edges == nil {\n                //  make room for tokens 1..n and -1 masquerading as index 0\n                p.edges = [DFAState?](repeating: nil, count: LexerATNSimulator.MAX_DFA_EDGE - LexerATNSimulator.MIN_DFA_EDGE + 1)\n            }\n            p.edges[t - LexerATNSimulator.MIN_DFA_EDGE] = q // connect\n        }\n    }\n\n    ///\n    /// Add a new DFA state if there isn't one with this set of\n    /// configurations already. This method also detects the first\n    /// configuration containing an ATN rule stop state. Later, when\n    /// traversing the DFA, we will know which rule to accept.\n    ///\n\n    final func addDFAState(_ configs: ATNConfigSet) -> DFAState {\n        ///\n        /// the lexer evaluates predicates on-the-fly; by this point configs\n        /// should not contain any configurations with unevaluated predicates.\n        ///\n        assert(!configs.hasSemanticContext, \"Expected: !configs.hasSemanticContext\")\n\n        let proposed = DFAState(configs)\n\n        if let rss = configs.firstConfigWithRuleStopState {\n            proposed.isAcceptState = true\n            proposed.lexerActionExecutor = (rss as! LexerATNConfig).getLexerActionExecutor()\n            proposed.prediction = atn.ruleToTokenType[rss.state.ruleIndex!]\n        }\n\n        let dfa = decisionToDFA[mode]\n\n        return dfa.statesMutex.synchronized {\n            if let existing = dfa.states[proposed] {\n                return existing\n            }\n\n            let newState = proposed\n            newState.stateNumber = dfa.states.count\n            configs.setReadonly(true)\n            newState.configs = configs\n            dfa.states[newState] = newState\n            return newState\n        }\n    }\n\n\n    public final func getDFA(_ mode: Int) -> DFA {\n        return decisionToDFA[mode]\n    }\n\n    ///\n    /// Get the text matched so far for the current token.\n    ///\n\n    public func getText(_ input: CharStream) -> String {\n        // index is first lookahead char, don't include.\n        return try! input.getText(Interval.of(startIndex, input.index() - 1))\n    }\n\n    public func getLine() -> Int {\n        return line\n    }\n\n    public func setLine(_ line: Int) {\n        self.line = line\n    }\n\n    public func getCharPositionInLine() -> Int {\n        return charPositionInLine\n    }\n\n    public func setCharPositionInLine(_ charPositionInLine: Int) {\n        self.charPositionInLine = charPositionInLine\n    }\n\n    public func consume(_ input: CharStream) throws {\n        let curChar = try input.LA(1)\n        if String(Character(integerLiteral: curChar)) == \"\\n\" {\n            line += 1\n            charPositionInLine = 0\n        } else {\n            charPositionInLine += 1\n        }\n        try  input.consume()\n    }\n\n\n    public func getTokenName(_ t: Int) -> String {\n        if t == -1 {\n            return \"EOF\"\n        }\n        //if ( atn.g!=null ) return atn.g.getTokenDisplayName(t);\n        return \"'\" + String(Character(integerLiteral: t)) + \"'\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Represents a single action which can be executed following the successful\n/// match of a lexer rule. Lexer actions are used for both embedded action syntax\n/// and ANTLR 4's new lexer command syntax.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic class LexerAction: Hashable {\n    /// \n    /// Gets the serialization type of the lexer action.\n    /// \n    /// - returns: The serialization type of the lexer action.\n    /// \n    public func getActionType() -> LexerActionType {\n        fatalError(#function + \" must be overridden\")\n    }\n\n\n    /// \n    /// Gets whether the lexer action is position-dependent. Position-dependent\n    /// actions may have different semantics depending on the _org.antlr.v4.runtime.CharStream_\n    /// index at the time the action is executed.\n    /// \n    /// Many lexer commands, including `type`, `skip`, and\n    /// `more`, do not check the input index during their execution.\n    /// Actions like this are position-independent, and may be stored more\n    /// efficiently as part of the _org.antlr.v4.runtime.atn.LexerATNConfig#lexerActionExecutor_.\n    /// \n    /// - returns: `true` if the lexer action semantics can be affected by the\n    /// position of the input _org.antlr.v4.runtime.CharStream_ at the time it is executed;\n    /// otherwise, `false`.\n    /// \n    public func isPositionDependent() -> Bool {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Execute the lexer action in the context of the specified _org.antlr.v4.runtime.Lexer_.\n    /// \n    /// For position-dependent actions, the input stream must already be\n    /// positioned correctly prior to calling this method.\n    /// \n    /// - parameter lexer: The lexer instance.\n    /// \n    public func execute(_ lexer: Lexer) throws {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        fatalError(#function + \" must be overridden\")\n    }\n\n}\n\npublic func ==(lhs: LexerAction, rhs: LexerAction) -> Bool {\n\n    if lhs === rhs {\n        return true\n    }\n\n    if (lhs is LexerChannelAction) && (rhs is LexerChannelAction) {\n        return (lhs as! LexerChannelAction) == (rhs as! LexerChannelAction)\n    } else if (lhs is LexerCustomAction) && (rhs is LexerCustomAction) {\n        return (lhs as! LexerCustomAction) == (rhs as! LexerCustomAction)\n    } else if (lhs is LexerIndexedCustomAction) && (rhs is LexerIndexedCustomAction) {\n        return (lhs as! LexerIndexedCustomAction) == (rhs as! LexerIndexedCustomAction)\n    } else if (lhs is LexerModeAction) && (rhs is LexerModeAction) {\n        return (lhs as! LexerModeAction) == (rhs as! LexerModeAction)\n    } else if (lhs is LexerMoreAction) && (rhs is LexerMoreAction) {\n        return (lhs as! LexerMoreAction) == (rhs as! LexerMoreAction)\n    } else if (lhs is LexerPopModeAction) && (rhs is LexerPopModeAction) {\n        return (lhs as! LexerPopModeAction) == (rhs as! LexerPopModeAction)\n    } else if (lhs is LexerPushModeAction) && (rhs is LexerPushModeAction) {\n        return (lhs as! LexerPushModeAction) == (rhs as! LexerPushModeAction)\n    } else if (lhs is LexerSkipAction) && (rhs is LexerSkipAction) {\n        return (lhs as! LexerSkipAction) == (rhs as! LexerSkipAction)\n    } else if (lhs is LexerTypeAction) && (rhs is LexerTypeAction) {\n        return (lhs as! LexerTypeAction) == (rhs as! LexerTypeAction)\n    }\n\n\n    return false\n\n}\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerActionExecutor.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n\n\n/// \n/// Represents an executor for a sequence of lexer actions which traversed during\n/// the matching operation of a lexer rule (token).\n/// \n/// The executor tracks position information for position-dependent lexer actions\n/// efficiently, ensuring that actions appearing only at the end of the rule do\n/// not cause bloating of the _org.antlr.v4.runtime.dfa.DFA_ created for the lexer.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic class LexerActionExecutor: Hashable {\n\n    fileprivate final var lexerActions: [LexerAction]\n    /// \n    /// Caches the result of _#hashCode_ since the hash code is an element\n    /// of the performance-critical _org.antlr.v4.runtime.atn.LexerATNConfig#hashCode_ operation.\n    /// \n    fileprivate final var hashCode: Int\n\n    /// \n    /// Constructs an executor for a sequence of _org.antlr.v4.runtime.atn.LexerAction_ actions.\n    /// - parameter lexerActions: The lexer actions to execute.\n    /// \n    public init(_ lexerActions: [LexerAction]) {\n        self.lexerActions = lexerActions\n\n        var hash = MurmurHash.initialize()\n        for lexerAction: LexerAction in lexerActions {\n            hash = MurmurHash.update(hash, lexerAction)\n        }\n\n        self.hashCode = MurmurHash.finish(hash, lexerActions.count)\n    }\n\n    /// \n    /// Creates a _org.antlr.v4.runtime.atn.LexerActionExecutor_ which executes the actions for\n    /// the input `lexerActionExecutor` followed by a specified\n    /// `lexerAction`.\n    /// \n    /// - parameter lexerActionExecutor: The executor for actions already traversed by\n    /// the lexer while matching a token within a particular\n    /// _org.antlr.v4.runtime.atn.LexerATNConfig_. If this is `null`, the method behaves as\n    /// though it were an empty executor.\n    /// - parameter lexerAction: The lexer action to execute after the actions\n    /// specified in `lexerActionExecutor`.\n    /// \n    /// - returns: A _org.antlr.v4.runtime.atn.LexerActionExecutor_ for executing the combine actions\n    /// of `lexerActionExecutor` and `lexerAction`.\n    /// \n    public static func append(_ lexerActionExecutor: LexerActionExecutor?, _ lexerAction: LexerAction) -> LexerActionExecutor {\n        guard let lexerActionExecutor = lexerActionExecutor else {\n            return LexerActionExecutor([lexerAction])\n        }\n\n        //var lexerActions : [LexerAction] = lexerActionExecutor.lexerActions, //lexerActionExecutor.lexerActions.length + 1);\n        var lexerActions: [LexerAction] = lexerActionExecutor.lexerActions\n        lexerActions.append(lexerAction)\n        //lexerActions[lexerActions.length - 1] = lexerAction;\n        return LexerActionExecutor(lexerActions)\n    }\n\n    /// \n    /// Creates a _org.antlr.v4.runtime.atn.LexerActionExecutor_ which encodes the current offset\n    /// for position-dependent lexer actions.\n    /// \n    /// Normally, when the executor encounters lexer actions where\n    /// _org.antlr.v4.runtime.atn.LexerAction#isPositionDependent_ returns `true`, it calls\n    /// _org.antlr.v4.runtime.IntStream#seek_ on the input _org.antlr.v4.runtime.CharStream_ to set the input\n    /// position to the __end__ of the current token. This behavior provides\n    /// for efficient DFA representation of lexer actions which appear at the end\n    /// of a lexer rule, even when the lexer rule matches a variable number of\n    /// characters.\n    /// \n    /// Prior to traversing a match transition in the ATN, the current offset\n    /// from the token start index is assigned to all position-dependent lexer\n    /// actions which have not already been assigned a fixed offset. By storing\n    /// the offsets relative to the token start index, the DFA representation of\n    /// lexer actions which appear in the middle of tokens remains efficient due\n    /// to sharing among tokens of the same length, regardless of their absolute\n    /// position in the input stream.\n    /// \n    /// If the current executor already has offsets assigned to all\n    /// position-dependent lexer actions, the method returns `this`.\n    /// \n    /// - parameter offset: The current offset to assign to all position-dependent\n    /// lexer actions which do not already have offsets assigned.\n    /// \n    /// - returns: A _org.antlr.v4.runtime.atn.LexerActionExecutor_ which stores input stream offsets\n    /// for all position-dependent lexer actions.\n    /// \n    public func fixOffsetBeforeMatch(_ offset: Int) -> LexerActionExecutor {\n        var updatedLexerActions: [LexerAction]? = nil\n        let length = lexerActions.count\n        for i in 0..<length {\n            if lexerActions[i].isPositionDependent() && !(lexerActions[i] is LexerIndexedCustomAction) {\n                if updatedLexerActions == nil {\n                    updatedLexerActions = lexerActions   //lexerActions.clone();\n                }\n\n                updatedLexerActions![i] = LexerIndexedCustomAction(offset, lexerActions[i])\n            }\n        }\n\n        if updatedLexerActions == nil {\n            return self\n        }\n\n        return LexerActionExecutor(updatedLexerActions!)\n    }\n\n    /// \n    /// Gets the lexer actions to be executed by this executor.\n    /// - returns: The lexer actions to be executed by this executor.\n    /// \n    public func getLexerActions() -> [LexerAction] {\n        return lexerActions\n    }\n\n    /// \n    /// Execute the actions encapsulated by this executor within the context of a\n    /// particular _org.antlr.v4.runtime.Lexer_.\n    /// \n    /// This method calls _org.antlr.v4.runtime.IntStream#seek_ to set the position of the\n    /// `input` _org.antlr.v4.runtime.CharStream_ prior to calling\n    /// _org.antlr.v4.runtime.atn.LexerAction#execute_ on a position-dependent action. Before the\n    /// method returns, the input position will be restored to the same position\n    /// it was in when the method was invoked.\n    /// \n    /// - parameter lexer: The lexer instance.\n    /// - parameter input: The input stream which is the source for the current token.\n    /// When this method is called, the current _org.antlr.v4.runtime.IntStream#index_ for\n    /// `input` should be the start of the following token, i.e. 1\n    /// character past the end of the current token.\n    /// - parameter startIndex: The token start index. This value may be passed to\n    /// _org.antlr.v4.runtime.IntStream#seek_ to set the `input` position to the beginning\n    /// of the token.\n    /// \n    public func execute(_ lexer: Lexer, _ input: CharStream, _ startIndex: Int) throws {\n        var requiresSeek: Bool = false\n        let stopIndex: Int = input.index()\n        defer {\n            if requiresSeek {\n                try! input.seek(stopIndex)\n            }\n        }\n        //try {\n        for var lexerAction: LexerAction in self.lexerActions {\n            if let runLexerAction = lexerAction as? LexerIndexedCustomAction {\n                let offset: Int = runLexerAction.getOffset()\n                try input.seek(startIndex + offset)\n                lexerAction = runLexerAction.getAction()\n                requiresSeek = (startIndex + offset) != stopIndex\n            } else {\n                if lexerAction.isPositionDependent() {\n                    try input.seek(stopIndex)\n                    requiresSeek = false\n                }\n            }\n\n            try lexerAction.execute(lexer)\n        }\n        //}\n\n    }\n\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(hashCode)\n    }\n}\n\npublic func ==(lhs: LexerActionExecutor, rhs: LexerActionExecutor) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    if lhs.lexerActions.count != rhs.lexerActions.count {\n        return false\n    }\n    let length = lhs.lexerActions.count\n    for i in 0..<length {\n        if !(lhs.lexerActions[i] == rhs.lexerActions[i]) {\n            return false\n        }\n    }\n\n\n    return lhs.hashCode == rhs.hashCode\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerActionType.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Represents the serialization type of a _org.antlr.v4.runtime.atn.LexerAction_.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic enum LexerActionType: Int {\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerChannelAction_ action.\n    /// \n    case channel = 0\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerCustomAction_ action.\n    /// \n    case custom\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerModeAction_ action.\n    /// \n    case mode\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerMoreAction_ action.\n    /// \n    case more\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerPopModeAction_ action.\n    /// \n    case popMode\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerPushModeAction_ action.\n    /// \n    case pushMode\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerSkipAction_ action.\n    /// \n    case skip\n    /// \n    /// The type of a _org.antlr.v4.runtime.atn.LexerTypeAction_ action.\n    /// \n    case type\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerChannelAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// Implements the `channel` lexer action by calling\n/// _org.antlr.v4.runtime.Lexer#setChannel_ with the assigned channel.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerChannelAction: LexerAction, CustomStringConvertible {\n    fileprivate let channel: Int\n\n    /// \n    /// Constructs a new `channel` action with the specified channel value.\n    /// - parameter channel: The channel value to pass to _org.antlr.v4.runtime.Lexer#setChannel_.\n    /// \n    public init(_ channel: Int) {\n        self.channel = channel\n    }\n\n    /// \n    /// Gets the channel to use for the _org.antlr.v4.runtime.Token_ created by the lexer.\n    /// \n    /// - returns: The channel to use for the _org.antlr.v4.runtime.Token_ created by the lexer.\n    /// \n    public func getChannel() -> Int {\n        return channel\n    }\n\n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#CHANNEL_.\n    /// \n\n    public override func getActionType() -> LexerActionType {\n        return LexerActionType.channel\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `false`.\n    /// \n\n    public override func isPositionDependent() -> Bool {\n        return false\n    }\n\n    /// \n    /// \n    /// \n    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#setChannel_ with the\n    /// value provided by _#getChannel_.\n    /// \n\n    public override func execute(_ lexer: Lexer) {\n        lexer.setChannel(channel)\n    }\n\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(getActionType())\n        hasher.combine(channel)\n    }\n\n    public var description: String {\n        return \"channel\\(channel)\"\n    }\n\n}\n\n\npublic func ==(lhs: LexerChannelAction, rhs: LexerChannelAction) -> Bool {\n\n    if lhs === rhs {\n        return true\n    }\n\n\n    return lhs.channel == rhs.channel\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerCustomAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// Executes a custom lexer action by calling _org.antlr.v4.runtime.Recognizer#action_ with the\n/// rule and action indexes assigned to the custom action. The implementation of\n/// a custom action is added to the generated code for the lexer in an override\n/// of _org.antlr.v4.runtime.Recognizer#action_ when the grammar is compiled.\n/// \n/// This class may represent embedded actions created with the {...}\n/// syntax in ANTLR 4, as well as actions created for lexer commands where the\n/// command argument could not be evaluated when the grammar was compiled.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerCustomAction: LexerAction {\n    fileprivate let ruleIndex: Int\n    fileprivate let actionIndex: Int\n\n    /// \n    /// Constructs a custom lexer action with the specified rule and action\n    /// indexes.\n    /// \n    /// - parameter ruleIndex: The rule index to use for calls to\n    /// _org.antlr.v4.runtime.Recognizer#action_.\n    /// - parameter actionIndex: The action index to use for calls to\n    /// _org.antlr.v4.runtime.Recognizer#action_.\n    /// \n    public init(_ ruleIndex: Int, _ actionIndex: Int) {\n        self.ruleIndex = ruleIndex\n        self.actionIndex = actionIndex\n    }\n\n    /// \n    /// Gets the rule index to use for calls to _org.antlr.v4.runtime.Recognizer#action_.\n    /// \n    /// - returns: The rule index for the custom action.\n    /// \n    public func getRuleIndex() -> Int {\n        return ruleIndex\n    }\n\n    /// \n    /// Gets the action index to use for calls to _org.antlr.v4.runtime.Recognizer#action_.\n    /// \n    /// - returns: The action index for the custom action.\n    /// \n    public func getActionIndex() -> Int {\n        return actionIndex\n    }\n\n    /// \n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#CUSTOM_.\n    /// \n\n    public override func getActionType() -> LexerActionType {\n        return LexerActionType.custom\n    }\n\n    /// \n    /// Gets whether the lexer action is position-dependent. Position-dependent\n    /// actions may have different semantics depending on the _org.antlr.v4.runtime.CharStream_\n    /// index at the time the action is executed.\n    /// \n    /// Custom actions are position-dependent since they may represent a\n    /// user-defined embedded action which makes calls to methods like\n    /// _org.antlr.v4.runtime.Lexer#getText_.\n    /// \n    /// - returns: This method returns `true`.\n    /// \n    override\n    public func isPositionDependent() -> Bool {\n        return true\n    }\n\n    /// \n    /// \n    /// \n    /// Custom actions are implemented by calling _org.antlr.v4.runtime.Lexer#action_ with the\n    /// appropriate rule and action indexes.\n    /// \n    override\n    public func execute(_ lexer: Lexer) throws {\n        try lexer.action(nil, ruleIndex, actionIndex)\n    }\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(ruleIndex)\n        hasher.combine(actionIndex)\n    }\n}\n\npublic func ==(lhs: LexerCustomAction, rhs: LexerCustomAction) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n\n    return lhs.ruleIndex == rhs.ruleIndex\n            && lhs.actionIndex == rhs.actionIndex\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerIndexedCustomAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This implementation of _org.antlr.v4.runtime.atn.LexerAction_ is used for tracking input offsets\n/// for position-dependent actions within a _org.antlr.v4.runtime.atn.LexerActionExecutor_.\n/// \n/// This action is not serialized as part of the ATN, and is only required for\n/// position-dependent lexer actions which appear at a location other than the\n/// end of a rule. For more information about DFA optimizations employed for\n/// lexer actions, see _org.antlr.v4.runtime.atn.LexerActionExecutor#append_ and\n/// _org.antlr.v4.runtime.atn.LexerActionExecutor#fixOffsetBeforeMatch_.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerIndexedCustomAction: LexerAction {\n    fileprivate let offset: Int\n    fileprivate let action: LexerAction\n\n    /// \n    /// Constructs a new indexed custom action by associating a character offset\n    /// with a _org.antlr.v4.runtime.atn.LexerAction_.\n    /// \n    /// Note: This class is only required for lexer actions for which\n    /// _org.antlr.v4.runtime.atn.LexerAction#isPositionDependent_ returns `true`.\n    /// \n    /// - parameter offset: The offset into the input _org.antlr.v4.runtime.CharStream_, relative to\n    /// the token start index, at which the specified lexer action should be\n    /// executed.\n    /// - parameter action: The lexer action to execute at a particular offset in the\n    /// input _org.antlr.v4.runtime.CharStream_.\n    /// \n    public init(_ offset: Int, _ action: LexerAction) {\n        self.offset = offset\n        self.action = action\n    }\n\n    /// \n    /// Gets the location in the input _org.antlr.v4.runtime.CharStream_ at which the lexer\n    /// action should be executed. The value is interpreted as an offset relative\n    /// to the token start index.\n    /// \n    /// - returns: The location in the input _org.antlr.v4.runtime.CharStream_ at which the lexer\n    /// action should be executed.\n    /// \n    public func getOffset() -> Int {\n        return offset\n    }\n\n    /// \n    /// Gets the lexer action to execute.\n    /// \n    /// - returns: A _org.antlr.v4.runtime.atn.LexerAction_ object which executes the lexer action.\n    /// \n    public func getAction() -> LexerAction {\n        return action\n    }\n\n    /// \n    /// \n    /// \n    /// - returns: This method returns the result of calling _#getActionType_\n    /// on the _org.antlr.v4.runtime.atn.LexerAction_ returned by _#getAction_.\n    /// \n\n    public override func getActionType() -> LexerActionType {\n        return action.getActionType()\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `true`.\n    /// \n\n    public override func isPositionDependent() -> Bool {\n        return true\n    }\n\n    /// \n    /// \n    /// \n    /// This method calls _#execute_ on the result of _#getAction_\n    /// using the provided `lexer`.\n    /// \n\n    public override func execute(_ lexer: Lexer) throws {\n        // assume the input stream position was properly set by the calling code\n        try action.execute(lexer)\n    }\n\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(offset)\n        hasher.combine(action)\n    }\n}\n\npublic func ==(lhs: LexerIndexedCustomAction, rhs: LexerIndexedCustomAction) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n\n    return lhs.offset == rhs.offset\n            && lhs.action == rhs.action\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerModeAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Implements the `mode` lexer action by calling _org.antlr.v4.runtime.Lexer#mode_ with\n/// the assigned mode.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerModeAction: LexerAction, CustomStringConvertible {\n    fileprivate let mode: Int\n\n    /// \n    /// Constructs a new `mode` action with the specified mode value.\n    /// - parameter mode: The mode value to pass to _org.antlr.v4.runtime.Lexer#mode_.\n    /// \n    public init(_ mode: Int) {\n        self.mode = mode\n    }\n\n    /// \n    /// Get the lexer mode this action should transition the lexer to.\n    /// \n    /// - returns: The lexer mode for this `mode` command.\n    /// \n    public func getMode() -> Int {\n        return mode\n    }\n\n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#MODE_.\n    /// \n\n    public override func getActionType() -> LexerActionType {\n        return LexerActionType.mode\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `false`.\n    /// \n\n    public override func isPositionDependent() -> Bool {\n        return false\n    }\n\n    /// \n    /// \n    /// \n    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#mode_ with the\n    /// value provided by _#getMode_.\n    /// \n    override\n    public func execute(_ lexer: Lexer) {\n        lexer.mode(mode)\n    }\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(mode)\n    }\n\n    public var description: String {\n        return \"mode(\\(mode))\"\n    }\n}\n\npublic func ==(lhs: LexerModeAction, rhs: LexerModeAction) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n\n    return lhs.mode == rhs.mode\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerMoreAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// Implements the `more` lexer action by calling _org.antlr.v4.runtime.Lexer#more_.\n/// \n/// The `more` command does not have any parameters, so this action is\n/// implemented as a singleton instance exposed by _#INSTANCE_.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerMoreAction: LexerAction, CustomStringConvertible {\n    /// \n    /// Provides a singleton instance of this parameterless lexer action.\n    /// \n    public static let INSTANCE: LexerMoreAction = LexerMoreAction()\n\n    /// \n    /// Constructs the singleton instance of the lexer `more` command.\n    /// \n    private override init() {\n    }\n\n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#MORE_.\n    /// \n    override\n    public func getActionType() -> LexerActionType {\n        return LexerActionType.more\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `false`.\n    /// \n    override\n    public func isPositionDependent() -> Bool {\n        return false\n    }\n\n    /// \n    /// \n    /// \n    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#more_.\n    /// \n    override\n    public func execute(_ lexer: Lexer) {\n        lexer.more()\n    }\n\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    public var description: String {\n        return \"more\"\n    }\n}\n\npublic func ==(lhs: LexerMoreAction, rhs: LexerMoreAction) -> Bool {\n    return lhs === rhs\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerPopModeAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Implements the `popMode` lexer action by calling _org.antlr.v4.runtime.Lexer#popMode_.\n/// \n/// The `popMode` command does not have any parameters, so this action is\n/// implemented as a singleton instance exposed by _#INSTANCE_.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerPopModeAction: LexerAction, CustomStringConvertible {\n    /// \n    /// Provides a singleton instance of this parameterless lexer action.\n    /// \n    public static let INSTANCE: LexerPopModeAction = LexerPopModeAction()\n\n    /// \n    /// Constructs the singleton instance of the lexer `popMode` command.\n    /// \n    private override init() {\n    }\n\n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#popMode_.\n    /// \n    override\n    public func getActionType() -> LexerActionType {\n        return LexerActionType.popMode\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `false`.\n    /// \n\n    public override func isPositionDependent() -> Bool {\n        return false\n    }\n\n    /// \n    /// \n    /// \n    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#popMode_.\n    /// \n\n    public override func execute(_ lexer: Lexer) throws {\n        try lexer.popMode()\n    }\n\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    public var description: String {\n        return \"popMode\"\n    }\n}\n\npublic func ==(lhs: LexerPopModeAction, rhs: LexerPopModeAction) -> Bool {\n    return lhs === rhs\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerPushModeAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Implements the `pushMode` lexer action by calling\n/// _org.antlr.v4.runtime.Lexer#pushMode_ with the assigned mode.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerPushModeAction: LexerAction, CustomStringConvertible {\n    fileprivate let mode: Int\n\n    /// \n    /// Constructs a new `pushMode` action with the specified mode value.\n    /// - parameter mode: The mode value to pass to _org.antlr.v4.runtime.Lexer#pushMode_.\n    /// \n    public init(_ mode: Int) {\n        self.mode = mode\n    }\n\n    /// \n    /// Get the lexer mode this action should transition the lexer to.\n    /// \n    /// - returns: The lexer mode for this `pushMode` command.\n    /// \n    public func getMode() -> Int {\n        return mode\n    }\n\n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#pushMode_.\n    /// \n\n    public override func getActionType() -> LexerActionType {\n        return LexerActionType.pushMode\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `false`.\n    /// \n\n    public override func isPositionDependent() -> Bool {\n        return false\n    }\n\n    /// \n    /// \n    /// \n    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#pushMode_ with the\n    /// value provided by _#getMode_.\n    /// \n    override\n    public func execute(_ lexer: Lexer) {\n        lexer.pushMode(mode)\n    }\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(mode)\n    }\n\n    public var description: String {\n        return \"pushMode(\\(mode))\"\n    }\n}\n\n\npublic func ==(lhs: LexerPushModeAction, rhs: LexerPushModeAction) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    return lhs.mode == rhs.mode\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerSkipAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// Implements the `skip` lexer action by calling _org.antlr.v4.runtime.Lexer#skip_.\n/// \n/// The `skip` command does not have any parameters, so this action is\n/// implemented as a singleton instance exposed by _#INSTANCE_.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic final class LexerSkipAction: LexerAction, CustomStringConvertible {\n    /// \n    /// Provides a singleton instance of this parameterless lexer action.\n    /// \n    public static let INSTANCE: LexerSkipAction = LexerSkipAction()\n\n    /// \n    /// Constructs the singleton instance of the lexer `skip` command.\n    /// \n    private override init() {\n    }\n\n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#SKIP_.\n    /// \n    override\n    public func getActionType() -> LexerActionType {\n        return LexerActionType.skip\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `false`.\n    /// \n    override\n    public func isPositionDependent() -> Bool {\n        return false\n    }\n\n    /// \n    /// \n    /// \n    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#skip_.\n    /// \n    override\n    public func execute(_ lexer: Lexer) {\n        lexer.skip()\n    }\n\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    public var description: String {\n        return \"skip\"\n    }\n}\n\npublic func ==(lhs: LexerSkipAction, rhs: LexerSkipAction) -> Bool {\n    return lhs === rhs\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LexerTypeAction.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// Implements the `type` lexer action by calling _org.antlr.v4.runtime.Lexer#setType_\n/// with the assigned type.\n/// \n/// -  Sam Harwell\n/// -  4.2\n/// \n\npublic class LexerTypeAction: LexerAction, CustomStringConvertible {\n    fileprivate let type: Int\n\n    /// \n    /// Constructs a new `type` action with the specified token type value.\n    /// - parameter type: The type to assign to the token using _org.antlr.v4.runtime.Lexer#setType_.\n    /// \n    public init(_ type: Int) {\n        self.type = type\n    }\n\n    /// \n    /// Gets the type to assign to a token created by the lexer.\n    /// - returns: The type to assign to a token created by the lexer.\n    /// \n    public func getType() -> Int {\n        return type\n    }\n\n    /// \n    /// \n    /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#TYPE_.\n    /// \n\n    public override func getActionType() -> LexerActionType {\n        return LexerActionType.type\n    }\n\n    /// \n    /// \n    /// - returns: This method returns `false`.\n    /// \n    override\n    public func isPositionDependent() -> Bool {\n        return false\n    }\n\n    /// \n    /// \n    /// \n    /// This action is implemented by calling _org.antlr.v4.runtime.Lexer#setType_ with the\n    /// value provided by _#getType_.\n    /// \n\n    public override func execute(_ lexer: Lexer) {\n        lexer.setType(type)\n    }\n\n\n    public override func hash(into hasher: inout Hasher) {\n        hasher.combine(type)\n    }\n\n    public var description: String {\n        return \"type(\\(type))\"\n    }\n}\n\npublic func ==(lhs: LexerTypeAction, rhs: LexerTypeAction) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    return lhs.type == rhs.type\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LookaheadEventInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// This class represents profiling event information for tracking the lookahead\n/// depth required in order to make a prediction.\n/// \n/// -  4.3\n/// \n\npublic class LookaheadEventInfo: DecisionEventInfo {\n    /// \n    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.LookaheadEventInfo_ class with\n    /// the specified detailed lookahead information.\n    /// \n    /// - parameter decision: The decision number\n    /// - parameter configs: The final configuration set containing the necessary\n    /// information to determine the result of a prediction, or `null` if\n    /// the final configuration set is not available\n    /// - parameter input: The input token stream\n    /// - parameter startIndex: The start index for the current prediction\n    /// - parameter stopIndex: The index at which the prediction was finally made\n    /// - parameter fullCtx: `true` if the current lookahead is part of an LL\n    /// prediction; otherwise, `false` if the current lookahead is part of\n    /// an SLL prediction\n    /// \n    public override init(_ decision: Int,\n                         _ configs: ATNConfigSet?,\n                         _ input: TokenStream, _ startIndex: Int, _ stopIndex: Int,\n                         _ fullCtx: Bool) {\n        super.init(decision, configs, input, startIndex, stopIndex, fullCtx)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LookupATNConfig.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  LookupATNConfig.swift\n//  objc2swiftwithswith\n//\n//  Created by janyou on 15/9/22.\n//\n\nimport Foundation\n\npublic class LookupATNConfig: Hashable {\n\n    public let config: ATNConfig\n    public init(_ old: ATNConfig) {\n        // dup\n        config = old\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(config.state.stateNumber)\n        hasher.combine(config.alt)\n        hasher.combine(config.semanticContext)\n    }\n}\n\npublic func ==(lhs: LookupATNConfig, rhs: LookupATNConfig) -> Bool {\n    if lhs.config === rhs.config {\n        return true\n    }\n\n    return lhs.config.state.stateNumber == rhs.config.state.stateNumber &&\n            lhs.config.alt == rhs.config.alt &&\n            lhs.config.semanticContext == rhs.config.semanticContext\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LookupDictionary.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  LookupDictionary.swift\n//   antlr.swift\n//\n//  Created by janyou on 15/9/23.\n//\n\nimport Foundation\n\npublic enum LookupDictionaryType: Int {\n    case lookup = 0\n    case ordered\n}\n\npublic struct LookupDictionary {\n    private let type: LookupDictionaryType\n    private var cache = [Int: ATNConfig]()\n\n    public init(type: LookupDictionaryType = LookupDictionaryType.lookup) {\n        self.type = type\n    }\n\n    private func hash(_ config: ATNConfig) -> Int {\n        if type == LookupDictionaryType.lookup {\n            /* migrating to XCode 12.3/Swift 5.3 introduced a very weird bug\n             where reading hashValue from a SemanticContext.AND instance woul:\n                call the AND empty constructor\n                NOT call AND.hash(into)\n             Could it be a Swift compiler bug ?\n             All tests pass when using Hasher.combine()\n             Keeping the old code for reference:\n             \n                var hashCode: Int = 7\n                hashCode = 31 * hashCode + config.state.stateNumber\n                hashCode = 31 * hashCode + config.alt\n                hashCode = 31 * hashCode + config.semanticContext.hashValue // <- the crash would occur here\n                return hashCode\n             \n            */\n            var hasher = Hasher()\n            hasher.combine(7)\n            hasher.combine(config.state.stateNumber)\n            hasher.combine(config.alt)\n            hasher.combine(config.semanticContext)\n            return hasher.finalize()\n        } else {\n            //Ordered\n            return config.hashValue\n        }\n    }\n\n    private func equal(_ lhs: ATNConfig, _ rhs: ATNConfig) -> Bool {\n        if type == LookupDictionaryType.lookup {\n            if lhs === rhs {\n                return true\n            }\n\n            return\n                lhs.state.stateNumber == rhs.state.stateNumber &&\n                    lhs.alt == rhs.alt &&\n                    lhs.semanticContext == rhs.semanticContext\n        }\n        else {\n            //Ordered\n            return lhs == rhs\n        }\n    }\n\n    public mutating func getOrAdd(_ config: ATNConfig) -> ATNConfig {\n        let h = hash(config)\n\n        if let configList = cache[h] {\n            return configList\n        }\n        else {\n            cache[h] = config\n        }\n\n        return config\n    }\n\n    public var isEmpty: Bool {\n        return cache.isEmpty\n    }\n\n    public func contains(_ config: ATNConfig) -> Bool {\n        let h = hash(config)\n        return cache[h] != nil\n    }\n\n    public mutating func removeAll() {\n        cache.removeAll()\n    }\n\n}\n\n\n\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/LoopEndState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Mark the end of a * or + loop.\n/// \n\npublic final class LoopEndState: ATNState {\n    public var loopBackState: ATNState?\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.LOOP_END\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/NotSetTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic final class NotSetTransition: SetTransition {\n//\tpublic override init(_ target : ATNState, inout _ set : IntervalSet?) {\n//\t\tsuper.init(target, &set);\n//\t}\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.NOT_SET\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return symbol >= minVocabSymbol\n                && symbol <= maxVocabSymbol\n                && !super.matches(symbol, minVocabSymbol, maxVocabSymbol)\n    }\n\n    override\n    public var description: String {\n        return \"~\" + super.description\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ParseInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This class provides access to specific and aggregate statistics gathered\n/// during profiling of a parser.\n/// \n/// -  4.3\n/// \n\npublic class ParseInfo {\n    internal let atnSimulator: ProfilingATNSimulator\n\n    public init(_ atnSimulator: ProfilingATNSimulator) {\n        self.atnSimulator = atnSimulator\n    }\n\n    /// \n    /// Gets an array of _org.antlr.v4.runtime.atn.DecisionInfo_ instances containing the profiling\n    /// information gathered for each decision in the ATN.\n    /// \n    /// - returns: An array of _org.antlr.v4.runtime.atn.DecisionInfo_ instances, indexed by decision\n    /// number.\n    /// \n    public func getDecisionInfo() -> [DecisionInfo] {\n        return atnSimulator.getDecisionInfo()\n    }\n\n    /// \n    /// Gets the decision numbers for decisions that required one or more\n    /// full-context predictions during parsing. These are decisions for which\n    /// _org.antlr.v4.runtime.atn.DecisionInfo#LL_Fallback_ is non-zero.\n    /// \n    /// - returns: A list of decision numbers which required one or more\n    /// full-context predictions during parsing.\n    /// \n    public func getLLDecisions() -> Array<Int> {\n        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()\n        var LL: Array<Int> = Array<Int>()\n        let length = decisions.count\n        for i in 0..<length {\n            let fallBack: Int64 = decisions[i].LL_Fallback\n            if fallBack > 0 {\n                LL.append(i)\n                // LL.add(i);\n            }\n        }\n        return LL\n    }\n\n    /// \n    /// Gets the total time spent during prediction across all decisions made\n    /// during parsing. This value is the sum of\n    /// _org.antlr.v4.runtime.atn.DecisionInfo#timeInPrediction_ for all decisions.\n    /// \n    public func getTotalTimeInPrediction() -> Int64 {\n        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()\n        var t: Int64 = 0\n        for d in decisions {\n            t += d.timeInPrediction\n        }\n        return t\n    }\n\n    /// \n    /// Gets the total number of SLL lookahead operations across all decisions\n    /// made during parsing. This value is the sum of\n    /// _org.antlr.v4.runtime.atn.DecisionInfo#SLL_TotalLook_ for all decisions.\n    /// \n    public func getTotalSLLLookaheadOps() -> Int64 {\n        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()\n        var k: Int64 = 0\n        for d in decisions {\n            k += d.SLL_TotalLook\n        }\n        return k\n    }\n\n    /// \n    /// Gets the total number of LL lookahead operations across all decisions\n    /// made during parsing. This value is the sum of\n    /// _org.antlr.v4.runtime.atn.DecisionInfo#LL_TotalLook_ for all decisions.\n    /// \n    public func getTotalLLLookaheadOps() -> Int64 {\n        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()\n        var k: Int64 = 0\n        for d in decisions {\n            k += d.LL_TotalLook\n        }\n        return k\n    }\n\n    /// \n    /// Gets the total number of ATN lookahead operations for SLL prediction\n    /// across all decisions made during parsing.\n    /// \n    public func getTotalSLLATNLookaheadOps() -> Int64 {\n        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()\n        var k: Int64 = 0\n        for d in decisions {\n            k += d.SLL_ATNTransitions\n        }\n        return k\n    }\n\n    /// \n    /// Gets the total number of ATN lookahead operations for LL prediction\n    /// across all decisions made during parsing.\n    /// \n    public func getTotalLLATNLookaheadOps() -> Int64 {\n        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()\n        var k: Int64 = 0\n        for d in decisions {\n            k += d.LL_ATNTransitions\n        }\n        return k\n    }\n\n    /// \n    /// Gets the total number of ATN lookahead operations for SLL and LL\n    /// prediction across all decisions made during parsing.\n    /// \n    /// \n    /// This value is the sum of _#getTotalSLLATNLookaheadOps_ and\n    /// _#getTotalLLATNLookaheadOps_.\n    /// \n    public func getTotalATNLookaheadOps() -> Int64 {\n        let decisions: [DecisionInfo] = atnSimulator.getDecisionInfo()\n        var k: Int64 = 0\n        for d in decisions {\n            k += d.SLL_ATNTransitions\n            k += d.LL_ATNTransitions\n        }\n        return k\n    }\n\n    /// \n    /// Gets the total number of DFA states stored in the DFA cache for all\n    /// decisions in the ATN.\n    /// \n    public func getDFASize() -> Int {\n        var n: Int = 0\n        let decisionToDFA: [DFA] = atnSimulator.decisionToDFA\n        let length = decisionToDFA.count\n        for i in 0..<length {\n            n += getDFASize(i)\n        }\n        return n\n    }\n\n    /// \n    /// Gets the total number of DFA states stored in the DFA cache for a\n    /// particular decision.\n    /// \n    public func getDFASize(_ decision: Int) -> Int {\n        let decisionToDFA: DFA = atnSimulator.decisionToDFA[decision]\n        return decisionToDFA.states.count\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ParserATNSimulator.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\n\n///\n/// The embodiment of the adaptive LL(*), ALL(*), parsing strategy.\n///\n///\n/// The basic complexity of the adaptive strategy makes it harder to understand.\n/// We begin with ATN simulation to build paths in a DFA. Subsequent prediction\n/// requests go through the DFA first. If they reach a state without an edge for\n/// the current symbol, the algorithm fails over to the ATN simulation to\n/// complete the DFA path for the current input (until it finds a conflict state\n/// or uniquely predicting state).\n///\n///\n/// All of that is done without using the outer context because we want to create\n/// a DFA that is not dependent upon the rule invocation stack when we do a\n/// prediction. One DFA works in all contexts. We avoid using context not\n/// necessarily because it's slower, although it can be, but because of the DFA\n/// caching problem. The closure routine only considers the rule invocation stack\n/// created during prediction beginning in the decision rule. For example, if\n/// prediction occurs without invoking another rule's ATN, there are no context\n/// stacks in the configurations. When lack of context leads to a conflict, we\n/// don't know if it's an ambiguity or a weakness in the strong LL(*) parsing\n/// strategy (versus full LL(*)).\n///\n///\n/// When SLL yields a configuration set with conflict, we rewind the input and\n/// retry the ATN simulation, this time using full outer context without adding\n/// to the DFA. Configuration context stacks will be the full invocation stacks\n/// from the start rule. If we get a conflict using full context, then we can\n/// definitively say we have a true ambiguity for that input sequence. If we\n/// don't get a conflict, it implies that the decision is sensitive to the outer\n/// context. (It is not context-sensitive in the sense of context-sensitive\n/// grammars.)\n///\n///\n/// The next time we reach this DFA state with an SLL conflict, through DFA\n/// simulation, we will again retry the ATN simulation using full context mode.\n/// This is slow because we can't save the results and have to \"interpret\" the\n/// ATN each time we get that input.\n///\n///\n/// __CACHING FULL CONTEXT PREDICTIONS__\n///\n///\n/// We could cache results from full context to predicted alternative easily and\n/// that saves a lot of time but doesn't work in presence of predicates. The set\n/// of visible predicates from the ATN start state changes depending on the\n/// context, because closure can fall off the end of a rule. I tried to cache\n/// tuples (stack context, semantic context, predicted alt) but it was slower\n/// than interpreting and much more complicated. Also required a huge amount of\n/// memory. The goal is not to create the world's fastest parser anyway. I'd like\n/// to keep this algorithm simple. By launching multiple threads, we can improve\n/// the speed of parsing across a large number of files.\n///\n///\n/// There is no strict ordering between the amount of input used by SLL vs LL,\n/// which makes it really hard to build a cache for full context. Let's say that\n/// we have input A B C that leads to an SLL conflict with full context X. That\n/// implies that using X we might only use A B but we could also use A B C D to\n/// resolve conflict. Input A B C D could predict alternative 1 in one position\n/// in the input and A B C E could predict alternative 2 in another position in\n/// input. The conflicting SLL configurations could still be non-unique in the\n/// full context prediction, which would lead us to requiring more input than the\n/// original A B C.\tTo make a\tprediction cache work, we have to track\tthe exact\n/// input\tused during the previous prediction. That amounts to a cache that maps\n/// X to a specific DFA for that context.\n///\n///\n/// Something should be done for left-recursive expression predictions. They are\n/// likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry\n/// with full LL thing Sam does.\n///\n///\n/// __AVOIDING FULL CONTEXT PREDICTION__\n///\n///\n/// We avoid doing full context retry when the outer context is empty, we did not\n/// dip into the outer context by falling off the end of the decision state rule,\n/// or when we force SLL mode.\n///\n///\n/// As an example of the not dip into outer context case, consider as super\n/// constructor calls versus function calls. One grammar might look like\n/// this:\n///\n///\n/// ctorBody\n/// : '{' superCall? stat* '}'\n/// ;\n///\n///\n///\n/// Or, you might see something like\n///\n///\n/// stat\n/// : superCall ';'\n/// | expression ';'\n/// | ...\n/// ;\n///\n///\n///\n/// In both cases I believe that no closure operations will dip into the outer\n/// context. In the first case ctorBody in the worst case will stop at the '}'.\n/// In the 2nd case it should stop at the ';'. Both cases should stay within the\n/// entry rule and not dip into the outer context.\n///\n///\n/// __PREDICATES__\n///\n///\n/// Predicates are always evaluated if present in either SLL or LL both. SLL and\n/// LL simulation deals with predicates differently. SLL collects predicates as\n/// it performs closure operations like ANTLR v3 did. It delays predicate\n/// evaluation until it reaches and accept state. This allows us to cache the SLL\n/// ATN simulation whereas, if we had evaluated predicates on-the-fly during\n/// closure, the DFA state configuration sets would be different and we couldn't\n/// build up a suitable DFA.\n///\n///\n/// When building a DFA accept state during ATN simulation, we evaluate any\n/// predicates and return the sole semantically valid alternative. If there is\n/// more than 1 alternative, we report an ambiguity. If there are 0 alternatives,\n/// we throw an exception. Alternatives without predicates act like they have\n/// true predicates. The simple way to think about it is to strip away all\n/// alternatives with false predicates and choose the minimum alternative that\n/// remains.\n///\n///\n/// When we start in the DFA and reach an accept state that's predicated, we test\n/// those and return the minimum semantically viable alternative. If no\n/// alternatives are viable, we throw an exception.\n///\n///\n/// During full LL ATN simulation, closure always evaluates predicates and\n/// on-the-fly. This is crucial to reducing the configuration set size during\n/// closure. It hits a landmine when parsing with the Java grammar, for example,\n/// without this on-the-fly evaluation.\n///\n///\n/// __SHARING DFA__\n///\n///\n/// All instances of the same parser share the same decision DFAs through a\n/// static field. Each instance gets its own ATN simulator but they share the\n/// same _#decisionToDFA_ field. They also share a\n/// _org.antlr.v4.runtime.atn.PredictionContextCache_ object that makes sure that all\n/// _org.antlr.v4.runtime.atn.PredictionContext_ objects are shared among the DFA states. This makes\n/// a big size difference.\n///\n///\n/// __THREAD SAFETY__\n///\n///\n/// The _org.antlr.v4.runtime.atn.ParserATNSimulator_ locks on the _#decisionToDFA_ field when\n/// it adds a new DFA object to that array. _#addDFAEdge_\n/// locks on the DFA for the current decision when setting the\n/// _org.antlr.v4.runtime.dfa.DFAState#edges_ field. _#addDFAState_ locks on\n/// the DFA for the current decision when looking up a DFA state to see if it\n/// already exists. We must make sure that all requests to add DFA states that\n/// are equivalent result in the same shared DFA object. This is because lots of\n/// threads will be trying to update the DFA at once. The\n/// _#addDFAState_ method also locks inside the DFA lock\n/// but this time on the shared context cache when it rebuilds the\n/// configurations' _org.antlr.v4.runtime.atn.PredictionContext_ objects using cached\n/// subgraphs/nodes. No other locking occurs, even during DFA simulation. This is\n/// safe as long as we can guarantee that all threads referencing\n/// `s.edge[t]` get the same physical target _org.antlr.v4.runtime.dfa.DFAState_, or\n/// `null`. Once into the DFA, the DFA simulation does not reference the\n/// _org.antlr.v4.runtime.dfa.DFA#states_ map. It follows the _org.antlr.v4.runtime.dfa.DFAState#edges_ field to new\n/// targets. The DFA simulator will either find _org.antlr.v4.runtime.dfa.DFAState#edges_ to be\n/// `null`, to be non-`null` and `dfa.edges[t]` null, or\n/// `dfa.edges[t]` to be non-null. The\n/// _#addDFAEdge_ method could be racing to set the field\n/// but in either case the DFA simulator works; if `null`, and requests ATN\n/// simulation. It could also race trying to get `dfa.edges[t]`, but either\n/// way it will work because it's not doing a test and set operation.\n///\n///\n/// __Starting with SLL then failing to combined SLL/LL (Two-Stage\n/// Parsing)__\n///\n///\n/// Sam pointed out that if SLL does not give a syntax error, then there is no\n/// point in doing full LL, which is slower. We only have to try LL if we get a\n/// syntax error. For maximum speed, Sam starts the parser set to pure SLL\n/// mode with the _org.antlr.v4.runtime.BailErrorStrategy_:\n///\n///\n/// parser._org.antlr.v4.runtime.Parser#getInterpreter() getInterpreter()_._#setPredictionMode setPredictionMode_`(`_PredictionMode#SLL_`)`;\n/// parser._org.antlr.v4.runtime.Parser#setErrorHandler setErrorHandler_(new _org.antlr.v4.runtime.BailErrorStrategy_());\n///\n///\n///\n/// If it does not get a syntax error, then we're done. If it does get a syntax\n/// error, we need to retry with the combined SLL/LL strategy.\n///\n///\n/// The reason this works is as follows. If there are no SLL conflicts, then the\n/// grammar is SLL (at least for that input set). If there is an SLL conflict,\n/// the full LL analysis must yield a set of viable alternatives which is a\n/// subset of the alternatives reported by SLL. If the LL set is a singleton,\n/// then the grammar is LL but not SLL. If the LL set is the same size as the SLL\n/// set, the decision is SLL. If the LL set has size &gt; 1, then that decision\n/// is truly ambiguous on the current input. If the LL set is smaller, then the\n/// SLL conflict resolution might choose an alternative that the full LL would\n/// rule out as a possibility based upon better context information. If that's\n/// the case, then the SLL parse will definitely get an error because the full LL\n/// analysis says it's not viable. If SLL conflict resolution chooses an\n/// alternative within the LL set, them both SLL and LL would choose the same\n/// alternative because they both choose the minimum of multiple conflicting\n/// alternatives.\n///\n///\n/// Let's say we have a set of SLL conflicting alternatives `{1, 2, 3`} and\n/// a smaller LL set called __s__. If __s__ is `{2, 3`}, then SLL\n/// parsing will get an error because SLL will pursue alternative 1. If\n/// __s__ is `{1, 2`} or `{1, 3`} then both SLL and LL will\n/// choose the same alternative because alternative one is the minimum of either\n/// set. If __s__ is `{2`} or `{3`} then SLL will get a syntax\n/// error. If __s__ is `{1`} then SLL will succeed.\n///\n///\n/// Of course, if the input is invalid, then we will get an error for sure in\n/// both SLL and LL parsing. Erroneous input will therefore require 2 passes over\n/// the input.\n///\nimport Foundation\n\nopen class ParserATNSimulator: ATNSimulator {\n    public let debug = false\n    public let trace_atn_sim = false\n    public let dfa_debug = false\n    public let retry_debug = false\n\n    ///\n    /// Just in case this optimization is bad, add an ENV variable to turn it off\n    ///\n    public static let TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT: Bool = {\n        if let value = ProcessInfo.processInfo.environment[\"TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT\"] {\n            return NSString(string: value).boolValue\n        }\n        return false\n    }()\n\n    internal final unowned let parser: Parser\n\n    public private(set) final var decisionToDFA: [DFA]\n\n    ///\n    /// SLL, LL, or LL + exact ambig detection?\n    ///\n\n    private var mode = PredictionMode.LL\n\n    ///\n    /// Each prediction operation uses a cache for merge of prediction contexts.\n    /// Don't keep around as it wastes huge amounts of memory. DoubleKeyMap\n    /// isn't synchronized but we're ok since two threads shouldn't reuse same\n    /// parser/atnsim object because it can only handle one input at a time.\n    /// This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid\n    /// the merge if we ever see a and b again.  Note that (b,a)&rarr;c should\n    /// also be examined during cache lookup.\n    ///\n    internal final var mergeCache: DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>?\n\n    // LAME globals to avoid parameters!!!!! I need these down deep in predTransition\n    internal var _input: TokenStream!\n    internal var _startIndex = 0\n    internal var _outerContext: ParserRuleContext!\n    internal var _dfa: DFA?\n\n//    /// Testing only!\n//    public convenience init(_ atn : ATN, _ decisionToDFA : [DFA],\n//                              _ sharedContextCache : PredictionContextCache) {\n//        self.init(nil, atn, decisionToDFA, sharedContextCache);\n//    }\n\n    public init(_ parser: Parser, _ atn: ATN,\n        _ decisionToDFA: [DFA],\n        _ sharedContextCache: PredictionContextCache) {\n\n            self.parser = parser\n            self.decisionToDFA = decisionToDFA\n            super.init(atn, sharedContextCache)\n            //\t\tDOTGenerator dot = new DOTGenerator(null);\n            //\t\tprint(dot.getDOT(atn.rules.get(0), parser.getRuleNames()));\n            //\t\tprint(dot.getDOT(atn.rules.get(1), parser.getRuleNames()));\n    }\n\n    override\n    open func reset() {\n    }\n\n    override\n    open func clearDFA() {\n        for d in 0..<decisionToDFA.count {\n            decisionToDFA[d] = DFA(atn.getDecisionState(d)!, d)\n        }\n    }\n\n    open func adaptivePredict(_ input: TokenStream, _ decision: Int,\n        _ outerContext: ParserRuleContext?) throws -> Int {\n        var outerContext = outerContext\n        if debug || trace_atn_sim {\n            var debugInfo = \"adaptivePredict decision \\(decision) \"\n            debugInfo += \"exec LA(1)==\\(try getLookaheadName(input)) \"\n            debugInfo += \"line \\(try input.LT(1)!.getLine()):\"\n            debugInfo += \"\\(try input.LT(1)!.getCharPositionInLine())\"\n            print(debugInfo)\n        }\n\n\n        _input = input\n        _startIndex = input.index()\n        _outerContext = outerContext\n        let dfa = decisionToDFA[decision]\n        _dfa = dfa\n\n        let m = input.mark()\n        let index = _startIndex\n\n        // Now we are certain to have a specific decision's DFA\n        // But, do we still need an initial state?\n        //TODO: exception handler\n        do {\n            var s0: DFAState?\n            if dfa.isPrecedenceDfa() {\n                // the start state for a precedence DFA depends on the current\n                // parser precedence, and is provided by a DFA method.\n                s0 = try dfa.getPrecedenceStartState(parser.getPrecedence())\n            } else {\n                // the start state for a \"regular\" DFA is just s0\n                s0 = dfa.s0\n            }\n\n            if s0 == nil {\n                //BIG BUG\n                if outerContext == nil {\n                    outerContext = ParserRuleContext.EMPTY\n                }\n                if debug || trace_atn_sim {\n                    var debugInfo = \"predictATN decision \\(dfa.decision) \"\n                    debugInfo += \"exec LA(1)==\\(try getLookaheadName(input)), \"\n                    debugInfo += \"outerContext=\\(outerContext!.toString(parser))\"\n                    print(debugInfo)\n                }\n\n                let fullCtx = false\n                var s0_closure = try computeStartState(dfa.atnStartState, ParserRuleContext.EMPTY, fullCtx)\n\n                if dfa.isPrecedenceDfa() {\n                    ///\n                    /// If this is a precedence DFA, we use applyPrecedenceFilter\n                    /// to convert the computed start state to a precedence start\n                    /// state. We then use DFA.setPrecedenceStartState to set the\n                    /// appropriate start state for the precedence level rather\n                    /// than simply setting DFA.s0.\n                    ///\n                    //added by janyou 20160224\n                    // dfa.s0!.configs = s0_closure // not used for prediction but useful to know start configs anyway\n                    s0_closure = try applyPrecedenceFilter(s0_closure)\n                    s0 = addDFAState(dfa, DFAState(s0_closure))\n                    try dfa.setPrecedenceStartState(parser.getPrecedence(), s0!)\n                } else {\n                    s0 = addDFAState(dfa, DFAState(s0_closure))\n                    dfa.s0 = s0\n                }\n            }\n\n            let alt = try execATN(dfa, s0!, input, index, outerContext!)\n            if debug {\n                print(\"DFA after predictATN: \\(dfa.toString(parser.getVocabulary()))\")\n            }\n            mergeCache = nil // wack cache after each prediction\n            _dfa = nil\n            try! input.seek(index)\n            try! input.release(m)\n            return alt\n        }\n\n    }\n\n    ///\n    /// Performs ATN simulation to compute a predicted alternative based\n    /// upon the remaining input, but also updates the DFA cache to avoid\n    /// having to traverse the ATN again for the same input sequence.\n    ///\n    /// There are some key conditions we're looking for after computing a new\n    /// set of ATN configs (proposed DFA state):\n    /// if the set is empty, there is no viable alternative for current symbol\n    /// does the state uniquely predict an alternative?\n    /// does the state have a conflict that would prevent us from\n    /// putting it on the work list?\n    ///\n    /// We also have some key operations to do:\n    /// add an edge from previous DFA state to potentially new DFA state, D,\n    /// upon current symbol but only if adding to work list, which means in all\n    /// cases except no viable alternative (and possibly non-greedy decisions?)\n    /// collecting predicates and adding semantic context to DFA accept states\n    /// adding rule context to context-sensitive DFA accept states\n    /// consuming an input symbol\n    /// reporting a conflict\n    /// reporting an ambiguity\n    /// reporting a context sensitivity\n    /// reporting insufficient predicates\n    ///\n    /// cover these cases:\n    /// dead end\n    /// single alt\n    /// single alt + preds\n    /// conflict\n    /// conflict + preds\n    ///\n    final func execATN(_ dfa: DFA, _ s0: DFAState,\n        _ input: TokenStream, _ startIndex: Int,\n        _ outerContext: ParserRuleContext) throws -> Int {\n            if debug || trace_atn_sim {\n                try print(\"execATN decision \\(dfa.decision) exec LA(1)==\\(getLookaheadName(input)) line \\(input.LT(1)!.getLine()):\\(input.LT(1)!.getCharPositionInLine())\")\n            }\n\n            var previousD = s0\n\n            if debug {\n                print(\"s0 = \\(s0)\")\n            }\n\n            var t = try input.LA(1)\n\n            while true {\n                // while more work\n                var D: DFAState\n                if let dState = getExistingTargetState(previousD, t) {\n                    D = dState\n                } else {\n                    D = try computeTargetState(dfa, previousD, t)\n                }\n\n                if D == ATNSimulator.ERROR {\n                    // if any configs in previous dipped into outer context, that\n                    // means that input up to t actually finished entry rule\n                    // at least for SLL decision. Full LL doesn't dip into outer\n                    // so don't need special case.\n                    // We will get an error no matter what so delay until after\n                    // decision; better error message. Also, no reachable target\n                    // ATN states in SLL implies LL will also get nowhere.\n                    // If conflict in states that dip out, choose min since we\n                    // will get error no matter what.\n                    let e = noViableAlt(input, outerContext, previousD.configs, startIndex)\n                    try input.seek(startIndex)\n                    let alt = try getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext)\n                    if alt != ATN.INVALID_ALT_NUMBER {\n                        return alt\n                    }\n\n                    throw ANTLRException.recognition(e: e)\n\n                }\n\n                if D.requiresFullContext && (mode != PredictionMode.SLL) {\n                    // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)\n                    var conflictingAlts = D.configs.conflictingAlts!\n                    if let preds = D.predicates {\n                        if debug {\n                            print(\"DFA state has preds in DFA sim LL failover\")\n                        }\n                        let conflictIndex = input.index()\n                        if conflictIndex != startIndex {\n                            try input.seek(startIndex)\n                        }\n\n                        conflictingAlts = try evalSemanticContext(preds, outerContext, true)\n                        if conflictingAlts.cardinality() == 1 {\n                            if debug {\n                                print(\"Full LL avoided\")\n                            }\n                            return conflictingAlts.firstSetBit()\n                        }\n\n                        if conflictIndex != startIndex {\n                            // restore the index so reporting the fallback to full\n                            // context occurs with the index at the correct spot\n                            try input.seek(conflictIndex)\n                        }\n                    }\n\n                    if dfa_debug {\n                        print(\"ctx sensitive state \\(outerContext) in \\(D)\")\n                    }\n                    let fullCtx = true\n                    let s0_closure = try computeStartState(dfa.atnStartState, outerContext, fullCtx)\n                    reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index())\n                    let alt = try execATNWithFullContext(dfa, D, s0_closure,\n                        input, startIndex,\n                        outerContext)\n                    return alt\n                }\n\n                if D.isAcceptState {\n                    guard let preds = D.predicates else {\n                        return D.prediction\n                    }\n\n                    let stopIndex = input.index()\n                    try input.seek(startIndex)\n                    let alts = try evalSemanticContext(preds, outerContext, true)\n                    switch alts.cardinality() {\n                    case 0:\n                        throw ANTLRException.recognition(e: noViableAlt(input, outerContext, D.configs, startIndex))\n\n\n                    case 1:\n                        return alts.firstSetBit()\n\n                    default:\n                        // report ambiguity after predicate evaluation to make sure the correct\n                        // set of ambig alts is reported.\n                        reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs)\n                        return alts.firstSetBit()\n                    }\n                }\n\n                previousD = D\n\n                if t != BufferedTokenStream.EOF {\n                    try input.consume()\n                    t = try input.LA(1)\n                }\n            }\n    }\n\n    ///\n    /// Get an existing target state for an edge in the DFA. If the target state\n    /// for the edge has not yet been computed or is otherwise not available,\n    /// this method returns `null`.\n    ///\n    /// - parameter previousD: The current DFA state\n    /// - parameter t: The next input symbol\n    /// - returns: The existing target DFA state for the given input symbol\n    /// `t`, or `null` if the target state for this edge is not\n    /// already cached\n    ///\n   func getExistingTargetState(_ previousD: DFAState, _ t: Int) -> DFAState? {\n        let edges = previousD.edges\n        if edges == nil || (t + 1) < 0 || (t + 1) >= (edges!.count) {\n            return nil\n        }\n\n        return edges![t + 1]\n    }\n\n    ///\n    /// Compute a target state for an edge in the DFA, and attempt to add the\n    /// computed state and corresponding edge to the DFA.\n    ///\n    /// - parameter dfa: The DFA\n    /// - parameter previousD: The current DFA state\n    /// - parameter t: The next input symbol\n    ///\n    /// - returns: The computed target DFA state for the given input symbol\n    /// `t`. If `t` does not lead to a valid DFA state, this method\n    /// returns _#ERROR_.\n    ///\n   func computeTargetState(_ dfa: DFA, _ previousD: DFAState, _ t: Int) throws -> DFAState {\n\n        guard let reach = try computeReachSet(previousD.configs, t, false) else {\n            addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR)\n            return ATNSimulator.ERROR\n        }\n\n        // create new target state; we'll add to DFA after it's complete\n        let D = DFAState(reach)\n\n        let predictedAlt = ParserATNSimulator.getUniqueAlt(reach)\n\n        if debug {\n            let altSubSets = PredictionMode.getConflictingAltSubsets(reach)\n            print(\"SLL altSubSets=\\(altSubSets), configs=\\(reach), predict=\\(predictedAlt), allSubsetsConflict=\\(PredictionMode.allSubsetsConflict(altSubSets)), conflictingAlts=\\(getConflictingAlts(reach))\")\n        }\n\n        if predictedAlt != ATN.INVALID_ALT_NUMBER {\n            // NO CONFLICT, UNIQUELY PREDICTED ALT\n            D.isAcceptState = true\n            D.configs.uniqueAlt = predictedAlt\n            D.prediction = predictedAlt\n        } else {\n            if PredictionMode.hasSLLConflictTerminatingPrediction(mode, reach) {\n                // MORE THAN ONE VIABLE ALTERNATIVE\n                D.configs.conflictingAlts = getConflictingAlts(reach)\n                D.requiresFullContext = true\n                // in SLL-only mode, we will stop at this state and return the minimum alt\n                D.isAcceptState = true\n                D.prediction = D.configs.conflictingAlts!.firstSetBit()\n            }\n        }\n\n        if D.isAcceptState && D.configs.hasSemanticContext {\n            predicateDFAState(D, atn.getDecisionState(dfa.decision)!)\n            if D.predicates != nil {\n                D.prediction = ATN.INVALID_ALT_NUMBER\n            }\n        }\n\n        // all adds to dfa are done after we've created full D state\n        return addDFAEdge(dfa, previousD, t, D)\n    }\n\n    final func predicateDFAState(_ dfaState: DFAState, _ decisionState: DecisionState) {\n        // We need to test all predicates, even in DFA states that\n        // uniquely predict alternative.\n        let nalts = decisionState.getNumberOfTransitions()\n        // Update DFA so reach becomes accept state with (predicate,alt)\n        // pairs if preds found for conflicting alts\n        let altsToCollectPredsFrom = getConflictingAltsOrUniqueAlt(dfaState.configs)\n        if let altToPred = getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts) {\n            dfaState.predicates = getPredicatePredictions(altsToCollectPredsFrom, altToPred)\n            dfaState.prediction = ATN.INVALID_ALT_NUMBER // make sure we use preds\n        } else {\n            // There are preds in configs but they might go away\n            // when OR'd together like {p}? || NONE == NONE. If neither\n            // alt has preds, resolve to min alt\n            dfaState.prediction = altsToCollectPredsFrom.firstSetBit()\n        }\n    }\n\n    // comes back with reach.uniqueAlt set to a valid alt\n    final func execATNWithFullContext(_ dfa: DFA,\n                                      _ D: DFAState, // how far we got in SLL DFA before failing over\n        _ s0: ATNConfigSet,\n        _ input: TokenStream, _ startIndex: Int,\n        _ outerContext: ParserRuleContext) throws -> Int {\n        if debug || trace_atn_sim {\n            print(\"execATNWithFullContext \\(s0)\")\n        }\n        let fullCtx = true\n        var foundExactAmbig = false\n        var reach: ATNConfigSet? = nil\n        var previous = s0\n        try input.seek(startIndex)\n        var t = try input.LA(1)\n        var predictedAlt = ATN.INVALID_ALT_NUMBER\n        while true {\n            // while more work\n            if let computeReach = try computeReachSet(previous, t, fullCtx) {\n                reach = computeReach\n            } else {\n                // if any configs in previous dipped into outer context, that\n                // means that input up to t actually finished entry rule\n                // at least for LL decision. Full LL doesn't dip into outer\n                // so don't need special case.\n                // We will get an error no matter what so delay until after\n                // decision; better error message. Also, no reachable target\n                // ATN states in SLL implies LL will also get nowhere.\n                // If conflict in states that dip out, choose min since we\n                // will get error no matter what.\n                let e = noViableAlt(input, outerContext, previous, startIndex)\n                try input.seek(startIndex)\n                let alt = try getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext)\n                if alt != ATN.INVALID_ALT_NUMBER {\n                    return alt\n                }\n                throw ANTLRException.recognition(e: e)\n\n            }\n            if let reach = reach {\n                let altSubSets = PredictionMode.getConflictingAltSubsets(reach)\n                if debug {\n                    print(\"LL altSubSets=\\(altSubSets), predict=\\(PredictionMode.getUniqueAlt(altSubSets)), resolvesToJustOneViableAlt=\\(PredictionMode.resolvesToJustOneViableAlt(altSubSets))\")\n                }\n\n\n                reach.uniqueAlt = ParserATNSimulator.getUniqueAlt(reach)\n                // unique prediction?\n                if reach.uniqueAlt != ATN.INVALID_ALT_NUMBER {\n                    predictedAlt = reach.uniqueAlt\n                    break\n                }\n                if mode != PredictionMode.LL_EXACT_AMBIG_DETECTION {\n                    predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets)\n                    if predictedAlt != ATN.INVALID_ALT_NUMBER {\n                        break\n                    }\n                } else {\n                    // In exact ambiguity mode, we never try to terminate early.\n                    // Just keeps scarfing until we know what the conflict is\n                    if PredictionMode.allSubsetsConflict(altSubSets) &&\n                        PredictionMode.allSubsetsEqual(altSubSets) {\n                        foundExactAmbig = true\n                        predictedAlt = PredictionMode.getSingleViableAlt(altSubSets)\n                        break\n                    }\n                    // else there are multiple non-conflicting subsets or\n                    // we're not sure what the ambiguity is yet.\n                    // So, keep going.\n                }\n\n                previous = reach\n                if t != BufferedTokenStream.EOF {\n                    try input.consume()\n                    t = try input.LA(1)\n                }\n            }\n        }\n        if let reach = reach {\n            // If the configuration set uniquely predicts an alternative,\n            // without conflict, then we know that it's a full LL decision\n            // not SLL.\n            if reach.uniqueAlt != ATN.INVALID_ALT_NUMBER {\n                reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index())\n                return predictedAlt\n            }\n\n            // We do not check predicates here because we have checked them\n            // on-the-fly when doing full context prediction.\n\n            ///\n            /// In non-exact ambiguity detection mode, we might\tactually be able to\n            /// detect an exact ambiguity, but I'm not going to spend the cycles\n            /// needed to check. We only emit ambiguity warnings in exact ambiguity\n            /// mode.\n            ///\n            /// For example, we might know that we have conflicting configurations.\n            /// But, that does not mean that there is no way forward without a\n            /// conflict. It's possible to have nonconflicting alt subsets as in:\n            ///\n            /// LL altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]\n            ///\n            /// from\n            ///\n            /// [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),\n            /// (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]\n            ///\n            /// In this case, (17,1,[5 $]) indicates there is some next sequence that\n            /// would resolve this without conflict to alternative 1. Any other viable\n            /// next sequence, however, is associated with a conflict.  We stop\n            /// looking for input because no amount of further lookahead will alter\n            /// the fact that we should predict alternative 1.  We just can't say for\n            /// sure that there is an ambiguity without looking further.\n            ///\n            reportAmbiguity(dfa, D, startIndex, input.index(), foundExactAmbig,\n                            reach.getAlts(), reach)\n        }\n        return predictedAlt\n    }\n\n    func computeReachSet(_ closureConfigSet: ATNConfigSet, _ t: Int,\n                         _ fullCtx: Bool) throws -> ATNConfigSet? {\n\n        if debug {\n            print(\"in computeReachSet, starting closure: \\(closureConfigSet)\")\n        }\n\n        if mergeCache == nil {\n            mergeCache = DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>()\n        }\n\n        let intermediate = ATNConfigSet(fullCtx)\n\n        ///\n        /// Configurations already in a rule stop state indicate reaching the end\n        /// of the decision rule (local context) or end of the start rule (full\n        /// context). Once reached, these configurations are never updated by a\n        /// closure operation, so they are handled separately for the performance\n        /// advantage of having a smaller intermediate set when calling closure.\n        ///\n        /// For full-context reach operations, separate handling is required to\n        /// ensure that the alternative matching the longest overall sequence is\n        /// chosen when multiple such configurations can match the input.\n        ///\n        var skippedStopStates: [ATNConfig]? = nil\n\n        // First figure out where we can reach on input t\n        let configs = closureConfigSet.configs\n        for config in configs {\n            if debug {\n                print(\"testing \\(getTokenName(t)) at \\(config.description)\")\n            }\n\n            if config.state is RuleStopState {\n                assert(config.context!.isEmpty(), \"Expected: c.context.isEmpty()\")\n                if fullCtx || t == BufferedTokenStream.EOF {\n                    if skippedStopStates == nil {\n                        skippedStopStates = [ATNConfig]()\n                    }\n                    skippedStopStates!.append(config)\n                }\n\n                continue\n            }\n\n            let n = config.state.getNumberOfTransitions()\n            for ti in 0..<n {\n                // for each transition\n                let trans = config.state.transition(ti)\n                if let target = getReachableTarget(trans, t) {\n                    try! intermediate.add(ATNConfig(config, target), &mergeCache)\n                }\n            }\n        }\n\n        // Now figure out where the reach operation can take us...\n\n        var reach: ATNConfigSet? = nil\n\n        ///\n        /// This block optimizes the reach operation for intermediate sets which\n        /// trivially indicate a termination state for the overall\n        /// adaptivePredict operation.\n        ///\n        /// The conditions assume that intermediate\n        /// contains all configurations relevant to the reach set, but this\n        /// condition is not true when one or more configurations have been\n        /// withheld in skippedStopStates, or when the current symbol is EOF.\n        ///\n        if skippedStopStates == nil && t != CommonToken.EOF {\n            if intermediate.size() == 1 {\n                // Don't pursue the closure if there is just one state.\n                // It can only have one alternative; just add to result\n                // Also don't pursue the closure if there is unique alternative\n                // among the configurations.\n                reach = intermediate\n            } else {\n                if ParserATNSimulator.getUniqueAlt(intermediate) != ATN.INVALID_ALT_NUMBER {\n                    // Also don't pursue the closure if there is unique alternative\n                    // among the configurations.\n                    reach = intermediate\n                }\n            }\n        }\n\n        ///\n        /// If the reach set could not be trivially determined, perform a closure\n        /// operation on the intermediate set to compute its initial value.\n        ///\n        if reach == nil {\n            reach = ATNConfigSet(fullCtx)\n            var closureBusy = Set<ATNConfig>()\n            let treatEofAsEpsilon = (t == CommonToken.EOF)\n            for config in intermediate.configs {\n                try closure(config, reach!, &closureBusy, false, fullCtx, treatEofAsEpsilon)\n            }\n        }\n\n        if t == BufferedTokenStream.EOF {\n            ///\n            /// After consuming EOF no additional input is possible, so we are\n            /// only interested in configurations which reached the end of the\n            /// decision rule (local context) or end of the start rule (full\n            /// context). Update reach to contain only these configurations. This\n            /// handles both explicit EOF transitions in the grammar and implicit\n            /// EOF transitions following the end of the decision or start rule.\n            ///\n            /// When reach==intermediate, no closure operation was performed. In\n            /// this case, removeAllConfigsNotInRuleStopState needs to check for\n            /// reachable rule stop states as well as configurations already in\n            /// a rule stop state.\n            ///\n            /// This is handled before the configurations in skippedStopStates,\n            /// because any configurations potentially added from that list are\n            /// already guaranteed to meet this condition whether or not it's\n            /// required.\n            ///\n            reach = removeAllConfigsNotInRuleStopState(reach!, reach! === intermediate)\n        }\n\n        ///\n        /// If skippedStopStates is not null, then it contains at least one\n        /// configuration. For full-context reach operations, these\n        /// configurations reached the end of the start rule, in which case we\n        /// only add them back to reach if no configuration during the current\n        /// closure operation reached such a state. This ensures adaptivePredict\n        /// chooses an alternative matching the longest overall sequence when\n        /// multiple alternatives are viable.\n        ///\n        if let reach = reach {\n            if let skippedStopStates = skippedStopStates, (!fullCtx || !PredictionMode.hasConfigInRuleStopState(reach)) {\n                assert(!skippedStopStates.isEmpty, \"Expected: !skippedStopStates.isEmpty()\")\n                for c in skippedStopStates {\n                    try! reach.add(c, &mergeCache)\n                }\n            }\n\n            if reach.isEmpty() {\n                return nil\n            }\n        }\n        return reach\n    }\n\n    ///\n    /// Return a configuration set containing only the configurations from\n    /// `configs` which are in a _org.antlr.v4.runtime.atn.RuleStopState_. If all\n    /// configurations in `configs` are already in a rule stop state, this\n    /// method simply returns `configs`.\n    ///\n    /// When `lookToEndOfRule` is true, this method uses\n    /// _org.antlr.v4.runtime.atn.ATN#nextTokens_ for each configuration in `configs` which is\n    /// not already in a rule stop state to see if a rule stop state is reachable\n    /// from the configuration via epsilon-only transitions.\n    ///\n    /// - parameter configs: the configuration set to update\n    /// - parameter lookToEndOfRule: when true, this method checks for rule stop states\n    /// reachable by epsilon-only transitions from each configuration in\n    /// `configs`.\n    ///\n    /// - returns: `configs` if all configurations in `configs` are in a\n    /// rule stop state, otherwise return a new configuration set containing only\n    /// the configurations from `configs` which are in a rule stop state\n    ///\n    final func removeAllConfigsNotInRuleStopState(_ configs: ATNConfigSet, _ lookToEndOfRule: Bool) -> ATNConfigSet {\n        return configs.removeAllConfigsNotInRuleStopState(&mergeCache,lookToEndOfRule,atn)\n    }\n\n\n    final func computeStartState(_ p: ATNState, _ ctx: RuleContext, _ fullCtx: Bool) throws -> ATNConfigSet {\n            let initialContext = PredictionContext.fromRuleContext(atn, ctx)\n            let configs = ATNConfigSet(fullCtx)\n            let length = p.getNumberOfTransitions()\n            for i in 0..<length {\n                let target = p.transition(i).target\n                let c = ATNConfig(target, i + 1, initialContext)\n                var closureBusy = Set<ATNConfig>()\n                try closure(c, configs, &closureBusy, true, fullCtx, false)\n            }\n\n            return configs\n    }\n\n    ///\n    /// parrt internal source braindump that doesn't mess up\n    /// external API spec.\n    ///\n    /// applyPrecedenceFilter is an optimization to avoid highly\n    /// nonlinear prediction of expressions and other left recursive\n    /// rules. The precedence predicates such as {3>=prec}? Are highly\n    /// context-sensitive in that they can only be properly evaluated\n    /// in the context of the proper prec argument. Without pruning,\n    /// these predicates are normal predicates evaluated when we reach\n    /// conflict state (or unique prediction). As we cannot evaluate\n    /// these predicates out of context, the resulting conflict leads\n    /// to full LL evaluation and nonlinear prediction which shows up\n    /// very clearly with fairly large expressions.\n    ///\n    /// Example grammar:\n    ///\n    /// e : e '*' e\n    /// | e '+' e\n    /// | INT\n    /// ;\n    ///\n    /// We convert that to the following:\n    ///\n    /// e[int prec]\n    /// :   INT\n    /// ( {3>=prec}? '*' e[4]\n    /// | {2>=prec}? '+' e[3]\n    /// )*\n    /// ;\n    ///\n    /// The (..)* loop has a decision for the inner block as well as\n    /// an enter or exit decision, which is what concerns us here. At\n    /// the 1st + of input 1+2+3, the loop entry sees both predicates\n    /// and the loop exit also sees both predicates by falling off the\n    /// edge of e.  This is because we have no stack information with\n    /// SLL and find the follow of e, which will hit the return states\n    /// inside the loop after e[4] and e[3], which brings it back to\n    /// the enter or exit decision. In this case, we know that we\n    /// cannot evaluate those predicates because we have fallen off\n    /// the edge of the stack and will in general not know which prec\n    /// parameter is the right one to use in the predicate.\n    ///\n    /// Because we have special information, that these are precedence\n    /// predicates, we can resolve them without failing over to full\n    /// LL despite their context sensitive nature. We make an\n    /// assumption that prec[-1] <= prec[0], meaning that the current\n    /// precedence level is greater than or equal to the precedence\n    /// level of recursive invocations above us in the stack. For\n    /// example, if predicate {3>=prec}? is true of the current prec,\n    /// then one option is to enter the loop to match it now. The\n    /// other option is to exit the loop and the left recursive rule\n    /// to match the current operator in rule invocation further up\n    /// the stack. But, we know that all of those prec are lower or\n    /// the same value and so we can decide to enter the loop instead\n    /// of matching it later. That means we can strip out the other\n    /// configuration for the exit branch.\n    ///\n    /// So imagine we have (14,1,$,{2>=prec}?) and then\n    /// (14,2,$-dipsIntoOuterContext,{2>=prec}?). The optimization\n    /// allows us to collapse these two configurations. We know that\n    /// if {2>=prec}? is true for the current prec parameter, it will\n    /// also be true for any prec from an invoking e call, indicated\n    /// by dipsIntoOuterContext. As the predicates are both true, we\n    /// have the option to evaluate them early in the decision start\n    /// state. We do this by stripping both predicates and choosing to\n    /// enter the loop as it is consistent with the notion of operator\n    /// precedence. It's also how the full LL conflict resolution\n    /// would work.\n    ///\n    /// The solution requires a different DFA start state for each\n    /// precedence level.\n    ///\n    /// The basic filter mechanism is to remove configurations of the\n    /// form (p, 2, pi) if (p, 1, pi) exists for the same p and pi. In\n    /// other words, for the same ATN state and predicate context,\n    /// remove any configuration associated with an exit branch if\n    /// there is a configuration associated with the enter branch.\n    ///\n    /// It's also the case that the filter evaluates precedence\n    /// predicates and resolves conflicts according to precedence\n    /// levels. For example, for input 1+2+3 at the first +, we see\n    /// prediction filtering\n    ///\n    /// [(11,1,[$],{3>=prec}?), (14,1,[$],{2>=prec}?), (5,2,[$],up=1),\n    /// (11,2,[$],up=1), (14,2,[$],up=1)],hasSemanticContext=true,dipsIntoOuterContext\n    ///\n    /// to\n    ///\n    /// [(11,1,[$]), (14,1,[$]), (5,2,[$],up=1)],dipsIntoOuterContext\n    ///\n    /// This filters because {3>=prec}? evals to true and collapses\n    /// (11,1,[$],{3>=prec}?) and (11,2,[$],up=1) since early conflict\n    /// resolution based upon rules of operator precedence fits with\n    /// our usual match first alt upon conflict.\n    ///\n    /// We noticed a problem where a recursive call resets precedence\n    /// to 0. Sam's fix: each config has flag indicating if it has\n    /// returned from an expr[0] call. then just don't filter any\n    /// config with that flag set. flag is carried along in\n    /// closure(). so to avoid adding field, set bit just under sign\n    /// bit of dipsIntoOuterContext (SUPPRESS_PRECEDENCE_FILTER).\n    /// With the change you filter \"unless (p, 2, pi) was reached\n    /// after leaving the rule stop state of the LR rule containing\n    /// state p, corresponding to a rule invocation with precedence\n    /// level 0\"\n    ///\n\n    ///\n    /// This method transforms the start state computed by\n    /// _#computeStartState_ to the special start state used by a\n    /// precedence DFA for a particular precedence value. The transformation\n    /// process applies the following changes to the start state's configuration\n    /// set.\n    ///\n    /// * Evaluate the precedence predicates for each configuration using\n    /// _org.antlr.v4.runtime.atn.SemanticContext#evalPrecedence_.\n    /// * When _org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed_ is `false`,\n    /// remove all configurations which predict an alternative greater than 1,\n    /// for which another configuration that predicts alternative 1 is in the\n    /// same ATN state with the same prediction context. This transformation is\n    /// valid for the following reasons:\n    ///\n    /// * The closure block cannot contain any epsilon transitions which bypass\n    /// the body of the closure, so all states reachable via alternative 1 are\n    /// part of the precedence alternatives of the transformed left-recursive\n    /// rule.\n    /// * The \"primary\" portion of a left recursive rule cannot contain an\n    /// epsilon transition, so the only way an alternative other than 1 can exist\n    /// in a state that is also reachable via alternative 1 is by nesting calls\n    /// to the left-recursive rule, with the outer calls not being at the\n    /// preferred precedence level. The\n    /// _org.antlr.v4.runtime.atn.ATNConfig#isPrecedenceFilterSuppressed_ property marks ATN\n    /// configurations which do not meet this condition, and therefore are not\n    /// eligible for elimination during the filtering process.\n    ///\n    /// The prediction context must be considered by this filter to address\n    /// situations like the following.\n    /// ```\n    /// grammar TA;\n    /// prog: statement* EOF;\n    /// statement: letterA | statement letterA 'b' ;\n    /// letterA: 'a';\n    /// ```\n    /// If the above grammar, the ATN state immediately before the token\n    /// reference `'a'` in `letterA` is reachable from the left edge\n    /// of both the primary and closure blocks of the left-recursive rule\n    /// `statement`. The prediction context associated with each of these\n    /// configurations distinguishes between them, and prevents the alternative\n    /// which stepped out to `prog` (and then back in to `statement`\n    /// from being eliminated by the filter.\n    ///\n    /// - parameter configs: The configuration set computed by\n    /// _#computeStartState_ as the start state for the DFA.\n    /// - returns: The transformed configuration set representing the start state\n    /// for a precedence DFA at a particular precedence level (determined by\n    /// calling _org.antlr.v4.runtime.Parser#getPrecedence_).\n    ///\n    final internal func applyPrecedenceFilter(_ configs: ATNConfigSet) throws -> ATNConfigSet {\n        return try configs.applyPrecedenceFilter(&mergeCache,parser,_outerContext)\n    }\n\n    final internal func getReachableTarget(_ trans: Transition, _ ttype: Int) -> ATNState? {\n\n        if trans.matches(ttype, 0, atn.maxTokenType) {\n            return trans.target\n        }\n\n        return nil\n    }\n\n    final internal func getPredsForAmbigAlts(_ ambigAlts: BitSet,\n        _ configs: ATNConfigSet,\n        _ nalts: Int) -> [SemanticContext?]? {\n            // REACH=[1|1|[]|0:0, 1|2|[]|0:1]\n            ///\n            /// altToPred starts as an array of all null contexts. The entry at index i\n            /// corresponds to alternative i. altToPred[i] may have one of three values:\n            /// 1. null: no ATNConfig c is found such that c.alt==i\n            /// 2. SemanticContext.Empty.Instance: At least one ATNConfig c exists such that\n            /// c.alt==i and c.semanticContext==SemanticContext.Empty.Instance. In other words,\n            /// alt i has at least one unpredicated config.\n            /// 3. Non-NONE Semantic Context: There exists at least one, and for all\n            /// ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.Empty.Instance.\n            ///\n            /// From this, it is clear that NONE||anything==NONE.\n            ///\n            let altToPred = configs.getPredsForAmbigAlts(ambigAlts,nalts)\n            if debug {\n                print(\"getPredsForAmbigAlts result \\(String(describing: altToPred))\")\n            }\n            return altToPred\n    }\n\n    final internal func getPredicatePredictions(_ ambigAlts: BitSet?,\n        _ altToPred: [SemanticContext?]) -> [DFAState.PredPrediction]? {\n            var pairs = [DFAState.PredPrediction]()\n            var containsPredicate = false\n            for (i, pred) in altToPred.enumerated().dropFirst() {\n\n                // unpredicated is indicated by SemanticContext.Empty.Instance\n                assert(pred != nil, \"Expected: pred!=null\")\n\n                if let ambigAlts = ambigAlts, try! ambigAlts.get(i) {\n                    pairs.append(DFAState.PredPrediction(pred!, i))\n                }\n                if pred != SemanticContext.Empty.Instance {\n                    containsPredicate = true\n                }\n            }\n\n            if !containsPredicate {\n                return nil\n            }\n\n            return pairs    ///pairs.toArray(new, DFAState.PredPrediction[pairs.size()]);\n    }\n\n    ///\n    /// This method is used to improve the localization of error messages by\n    /// choosing an alternative rather than throwing a\n    /// _org.antlr.v4.runtime.NoViableAltException_ in particular prediction scenarios where the\n    /// _#ERROR_ state was reached during ATN simulation.\n    ///\n    /// The default implementation of this method uses the following\n    /// algorithm to identify an ATN configuration which successfully parsed the\n    /// decision entry rule. Choosing such an alternative ensures that the\n    /// _org.antlr.v4.runtime.ParserRuleContext_ returned by the calling rule will be complete\n    /// and valid, and the syntax error will be reported later at a more\n    /// localized location.\n    ///\n    /// * If a syntactically valid path or paths reach the end of the decision rule and\n    /// they are semantically valid if predicated, return the min associated alt.\n    /// * Else, if a semantically invalid but syntactically valid path exist\n    /// or paths exist, return the minimum associated alt.\n    /// * Otherwise, return _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_.\n    ///\n    /// In some scenarios, the algorithm described above could predict an\n    /// alternative which will result in a _org.antlr.v4.runtime.FailedPredicateException_ in\n    /// the parser. Specifically, this could occur if the __only__ configuration\n    /// capable of successfully parsing to the end of the decision rule is\n    /// blocked by a semantic predicate. By choosing this alternative within\n    /// _#adaptivePredict_ instead of throwing a\n    /// _org.antlr.v4.runtime.NoViableAltException_, the resulting\n    /// _org.antlr.v4.runtime.FailedPredicateException_ in the parser will identify the specific\n    /// predicate which is preventing the parser from successfully parsing the\n    /// decision rule, which helps developers identify and correct logic errors\n    /// in semantic predicates.\n    ///\n    /// - parameter configs: The ATN configurations which were valid immediately before\n    /// the _#ERROR_ state was reached\n    /// - parameter outerContext: The is the \\gamma_0 initial parser context from the paper\n    /// or the parser stack at the instant before prediction commences.\n    ///\n    /// - returns: The value to return from _#adaptivePredict_, or\n    /// _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_ if a suitable alternative was not\n    /// identified and _#adaptivePredict_ should report an error instead.\n    ///\n    final internal func getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(_ configs: ATNConfigSet,\n        _ outerContext: ParserRuleContext) throws -> Int {\n            let (semValidConfigs, semInvalidConfigs) = try splitAccordingToSemanticValidity(configs, outerContext)\n            var alt = getAltThatFinishedDecisionEntryRule(semValidConfigs)\n            if alt != ATN.INVALID_ALT_NUMBER {\n                // semantically/syntactically viable path exists\n                return alt\n            }\n            // Is there a syntactically valid path with a failed pred?\n            if semInvalidConfigs.size() > 0 {\n                alt = getAltThatFinishedDecisionEntryRule(semInvalidConfigs)\n                if alt != ATN.INVALID_ALT_NUMBER {\n                    // syntactically viable path exists\n                    return alt\n                }\n            }\n            return ATN.INVALID_ALT_NUMBER\n    }\n\n    final internal func getAltThatFinishedDecisionEntryRule(_ configs: ATNConfigSet) -> Int {\n\n        return configs.getAltThatFinishedDecisionEntryRule()\n    }\n\n    ///\n    /// Walk the list of configurations and split them according to\n    /// those that have preds evaluating to true/false.  If no pred, assume\n    /// true pred and include in succeeded set.  Returns Pair of sets.\n    ///\n    /// Create a new set so as not to alter the incoming parameter.\n    ///\n    /// Assumption: the input stream has been restored to the starting point\n    /// prediction, which is where predicates need to evaluate.\n    ///\n    final internal func splitAccordingToSemanticValidity(\n        _ configs: ATNConfigSet,\n        _ outerContext: ParserRuleContext) throws -> (ATNConfigSet, ATNConfigSet) {\n\n            return try configs.splitAccordingToSemanticValidity(outerContext, evalSemanticContext)\n    }\n\n    ///\n    /// Look through a list of predicate/alt pairs, returning alts for the\n    /// pairs that win. A `NONE` predicate indicates an alt containing an\n    /// unpredicated config which behaves as \"always true.\" If !complete\n    /// then we stop at the first predicate that evaluates to true. This\n    /// includes pairs with null predicates.\n    ///\n   final internal func evalSemanticContext(_ predPredictions: [DFAState.PredPrediction],\n        _ outerContext: ParserRuleContext,\n        _ complete: Bool) throws -> BitSet {\n            let predictions = BitSet()\n            for pair in predPredictions {\n                if pair.pred == SemanticContext.Empty.Instance {\n                    try! predictions.set(pair.alt)\n                    if !complete {\n                        break\n                    }\n                    continue\n                }\n\n                let fullCtx = false // in dfa\n                let predicateEvaluationResult = try evalSemanticContext(pair.pred, outerContext, pair.alt, fullCtx)\n                if debug || dfa_debug {\n                    print(\"eval pred \\(pair)= \\(predicateEvaluationResult)\")\n                }\n\n                if predicateEvaluationResult {\n                    if debug || dfa_debug {\n                        print(\"PREDICT \\(pair.alt)\")\n                    }\n                    try! predictions.set(pair.alt)\n                    if !complete {\n                        break\n                    }\n                }\n            }\n\n            return predictions\n    }\n\n    ///\n    /// Evaluate a semantic context within a specific parser context.\n    ///\n    /// This method might not be called for every semantic context evaluated\n    /// during the prediction process. In particular, we currently do not\n    /// evaluate the following but it may change in the future:\n    ///\n    /// * Precedence predicates (represented by\n    /// _org.antlr.v4.runtime.atn.SemanticContext.PrecedencePredicate_) are not currently evaluated\n    /// through this method.\n    /// * Operator predicates (represented by _org.antlr.v4.runtime.atn.SemanticContext.AND_ and\n    /// _org.antlr.v4.runtime.atn.SemanticContext.OR_) are evaluated as a single semantic\n    /// context, rather than evaluating the operands individually.\n    /// Implementations which require evaluation results from individual\n    /// predicates should override this method to explicitly handle evaluation of\n    /// the operands within operator predicates.\n    ///\n    /// - parameter pred: The semantic context to evaluate\n    /// - parameter parserCallStack: The parser context in which to evaluate the\n    /// semantic context\n    /// - parameter alt: The alternative which is guarded by `pred`\n    /// - parameter fullCtx: `true` if the evaluation is occurring during LL\n    /// prediction; otherwise, `false` if the evaluation is occurring\n    /// during SLL prediction\n    ///\n    /// - since: 4.3\n    ///\n    internal func evalSemanticContext(_ pred: SemanticContext, _ parserCallStack: ParserRuleContext, _ alt: Int, _ fullCtx: Bool) throws -> Bool {\n        return try pred.eval(parser, parserCallStack)\n    }\n\n    ///\n    /// TODO: If we are doing predicates, there is no point in pursuing\n    /// closure operations if we reach a DFA state that uniquely predicts\n    /// alternative. We will not be caching that DFA state and it is a\n    /// waste to pursue the closure. Might have to advance when we do\n    /// ambig detection thought :(\n    ///\n    final internal func closure(_ config: ATNConfig,\n        _ configs: ATNConfigSet,\n        _ closureBusy: inout Set<ATNConfig>,\n        _ collectPredicates: Bool,\n        _ fullCtx: Bool,\n        _ treatEofAsEpsilon: Bool) throws {\n            let initialDepth = 0\n            try closureCheckingStopState(config, configs, &closureBusy, collectPredicates, fullCtx, initialDepth, treatEofAsEpsilon)\n            assert(!fullCtx || !configs.dipsIntoOuterContext, \"Expected: !fullCtx||!configs.dipsIntoOuterContext\")\n    }\n\n\n    final internal func closureCheckingStopState(_ config: ATNConfig,\n        _ configs: ATNConfigSet,\n        _ closureBusy: inout Set<ATNConfig>,\n        _ collectPredicates: Bool,\n        _ fullCtx: Bool,\n        _ depth: Int,\n        _ treatEofAsEpsilon: Bool) throws {\n\n            if debug {\n                print(\"closure(\" + config.toString(parser, true) + \")\")\n            }\n\n            if config.state is RuleStopState {\n                let configContext = config.context!\n                // We hit rule end. If we have context info, use it\n                // run thru all possible stack tops in ctx\n                if !configContext.isEmpty() {\n                    let length = configContext.size()\n                    for i in 0..<length {\n                        if configContext.getReturnState(i) == PredictionContext.EMPTY_RETURN_STATE {\n                            if fullCtx {\n                                try! configs.add(ATNConfig(config, config.state, EmptyPredictionContext.Instance), &mergeCache)\n                                continue\n                            } else {\n                                // we have no context info, just chase follow links (if greedy)\n                                if debug {\n                                    print(\"FALLING off rule\\(getRuleName(config.state.ruleIndex!))\")\n                                }\n                                try closure_(config, configs, &closureBusy, collectPredicates,\n                                    fullCtx, depth, treatEofAsEpsilon)\n                            }\n                            continue\n                        }\n                        let returnState: ATNState = atn.states[configContext.getReturnState(i)]!\n                        let newContext: PredictionContext? = configContext.getParent(i) // \"pop\" return state\n                        let c: ATNConfig = ATNConfig(returnState, config.alt, newContext,\n                            config.semanticContext)\n                        // While we have context to pop back from, we may have\n                        // gotten that context AFTER having falling off a rule.\n                        // Make sure we track that we are now out of context.\n                        //\n                        // This assignment also propagates the\n                        // isPrecedenceFilterSuppressed() value to the new\n                        // configuration.\n                        c.reachesIntoOuterContext = config.reachesIntoOuterContext\n                        assert(depth > Int.min, \"Expected: depth>Integer.MIN_VALUE\")\n                        try closureCheckingStopState(c, configs, &closureBusy, collectPredicates,\n                            fullCtx, depth - 1, treatEofAsEpsilon)\n                    }\n                    return\n                } else if fullCtx {\n                    // reached end of start rule\n                    try! configs.add(config, &mergeCache)\n                    return\n                } else {\n                    // else if we have no context info, just chase follow links (if greedy)\n                    if debug {\n                        print(\"FALLING off rule \\(getRuleName(config.state.ruleIndex!))\")\n                    }\n\n                }\n            }\n            try closure_(config, configs, &closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon)\n    }\n\n    ///\n    /// Do the actual work of walking epsilon edges\n    ///\n    final internal func closure_(_ config: ATNConfig,\n        _ configs: ATNConfigSet,\n        _ closureBusy: inout Set<ATNConfig>,\n        _ collectPredicates: Bool,\n        _ fullCtx: Bool,\n        _ depth: Int,\n        _ treatEofAsEpsilon: Bool) throws {\n            // print(__FUNCTION__)\n            //long startTime = System.currentTimeMillis();\n            let p = config.state\n            // optimization\n            if !p.onlyHasEpsilonTransitions() {\n                try! configs.add(config, &mergeCache)\n                // make sure to not return here, because EOF transitions can act as\n                // both epsilon transitions and non-epsilon transitions.\n                //            if ( debug ) print(\"added config \"+configs);\n            }\n            let length = p.getNumberOfTransitions()\n            for i in 0..<length {\n                if i == 0 &&\n                    canDropLoopEntryEdgeInLeftRecursiveRule(config) {\n                    continue\n                }\n                let t = p.transition(i)\n                let continueCollecting = !(t is ActionTransition) && collectPredicates\n                let c = try getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEofAsEpsilon)\n                if let c = c {\n                    var newDepth = depth\n                    if config.state is RuleStopState {\n                        assert(!fullCtx, \"Expected: !fullCtx\")\n                        // target fell off end of rule; mark resulting c as having dipped into outer context\n                        // We can't get here if incoming config was rule stop and we had context\n                        // track how far we dip into outer context.  Might\n                        // come in handy and we avoid evaluating context dependent\n                        // preds if this is > 0.\n                        if let _dfa = _dfa , _dfa.isPrecedenceDfa() {\n                            let outermostPrecedenceReturn: Int = (t as! EpsilonTransition).outermostPrecedenceReturn()\n                            if outermostPrecedenceReturn == _dfa.atnStartState.ruleIndex {\n                                c.setPrecedenceFilterSuppressed(true)\n                            }\n                        }\n\n                        c.reachesIntoOuterContext += 1\n                        if closureBusy.contains(c) {\n                            // avoid infinite recursion for right-recursive rules\n                            continue\n                        } else {\n                            closureBusy.insert(c)\n                        }\n\n                        configs.dipsIntoOuterContext = true // TODO: can remove? only care when we add to set per middle of this method\n                        //print(\"newDepth=>\\(newDepth)\")\n                        assert(newDepth > Int.min, \"Expected: newDepth>Integer.MIN_VALUE\")\n                        newDepth -= 1\n\n                        if debug {\n                            print(\"dips into outer ctx: \\(c)\")\n                        }\n                    }\n                    else {\n                        if !t.isEpsilon() {\n                            if closureBusy.contains(c) {\n                                // avoid infinite recursion for EOF* and EOF+\n                                continue\n                            }\n                            else {\n                                closureBusy.insert(c)\n                            }\n                        }\n\n                        if t is RuleTransition {\n                            // latch when newDepth goes negative - once we step out of the entry context we can't return\n                            if newDepth >= 0 {\n                                newDepth += 1\n                            }\n                        }\n                    }\n\n                    try closureCheckingStopState(c, configs, &closureBusy, continueCollecting,\n                        fullCtx, newDepth, treatEofAsEpsilon)\n                }\n            }\n            //long finishTime = System.currentTimeMillis();\n            //  if ((finishTime-startTime)>1)\n            //print(\"That took: \"+(finishTime-startTime)+ \" ms\");\n    }\n\n    ///\n    /// Implements first-edge (loop entry) elimination as an optimization\n    /// during closure operations.  See antlr/antlr4#1398.\n    ///\n    /// The optimization is to avoid adding the loop entry config when\n    /// the exit path can only lead back to the same\n    /// StarLoopEntryState after popping context at the rule end state\n    /// (traversing only epsilon edges, so we're still in closure, in\n    /// this same rule).\n    ///\n    /// We need to detect any state that can reach loop entry on\n    /// epsilon w/o exiting rule. We don't have to look at FOLLOW\n    /// links, just ensure that all stack tops for config refer to key\n    /// states in LR rule.\n    ///\n    /// To verify we are in the right situation we must first check\n    /// closure is at a StarLoopEntryState generated during LR removal.\n    /// Then we check that each stack top of context is a return state\n    /// from one of these cases:\n    ///\n    /// 1. 'not' expr, '(' type ')' expr. The return state points at loop entry state\n    /// 2. expr op expr. The return state is the block end of internal block of (...)*\n    /// 3. 'between' expr 'and' expr. The return state of 2nd expr reference.\n    /// That state points at block end of internal block of (...)*.\n    /// 4. expr '?' expr ':' expr. The return state points at block end,\n    /// which points at loop entry state.\n    ///\n    /// If any is true for each stack top, then closure does not add a\n    /// config to the current config set for edge[0], the loop entry branch.\n    ///\n    /// Conditions fail if any context for the current config is:\n    ///\n    /// a. empty (we'd fall out of expr to do a global FOLLOW which could\n    /// even be to some weird spot in expr) or,\n    /// b. lies outside of expr or,\n    /// c. lies within expr but at a state not the BlockEndState\n    /// generated during LR removal\n    ///\n    /// Do we need to evaluate predicates ever in closure for this case?\n    ///\n    /// No. Predicates, including precedence predicates, are only\n    /// evaluated when computing a DFA start state. I.e., only before\n    /// the lookahead (but not parser) consumes a token.\n    ///\n    /// There are no epsilon edges allowed in LR rule alt blocks or in\n    /// the \"primary\" part (ID here). If closure is in\n    /// StarLoopEntryState any lookahead operation will have consumed a\n    /// token as there are no epsilon-paths that lead to\n    /// StarLoopEntryState. We do not have to evaluate predicates\n    /// therefore if we are in the generated StarLoopEntryState of a LR\n    /// rule. Note that when making a prediction starting at that\n    /// decision point, decision d=2, compute-start-state performs\n    /// closure starting at edges[0], edges[1] emanating from\n    /// StarLoopEntryState. That means it is not performing closure on\n    /// StarLoopEntryState during compute-start-state.\n    ///\n    /// How do we know this always gives same prediction answer?\n    ///\n    /// Without predicates, loop entry and exit paths are ambiguous\n    /// upon remaining input +b (in, say, a+b). Either paths lead to\n    /// valid parses. Closure can lead to consuming + immediately or by\n    /// falling out of this call to expr back into expr and loop back\n    /// again to StarLoopEntryState to match +b. In this special case,\n    /// we choose the more efficient path, which is to take the bypass\n    /// path.\n    ///\n    /// The lookahead language has not changed because closure chooses\n    /// one path over the other. Both paths lead to consuming the same\n    /// remaining input during a lookahead operation. If the next token\n    /// is an operator, lookahead will enter the choice block with\n    /// operators. If it is not, lookahead will exit expr. Same as if\n    /// closure had chosen to enter the choice block immediately.\n    ///\n    /// Closure is examining one config (some loopentrystate, some alt,\n    /// context) which means it is considering exactly one alt. Closure\n    /// always copies the same alt to any derived configs.\n    ///\n    /// How do we know this optimization doesn't mess up precedence in\n    /// our parse trees?\n    ///\n    /// Looking through expr from left edge of stat only has to confirm\n    /// that an input, say, a+b+c; begins with any valid interpretation\n    /// of an expression. The precedence actually doesn't matter when\n    /// making a decision in stat seeing through expr. It is only when\n    /// parsing rule expr that we must use the precedence to get the\n    /// right interpretation and, hence, parse tree.\n    ///\n    /// -  4.6\n    ///\n    internal func canDropLoopEntryEdgeInLeftRecursiveRule(_ config: ATNConfig) -> Bool {\n        if ParserATNSimulator.TURN_OFF_LR_LOOP_ENTRY_BRANCH_OPT {\n            return false\n        }\n        let p = config.state\n        guard let configContext = config.context else {\n            return false\n        }\n        // First check to see if we are in StarLoopEntryState generated during\n        // left-recursion elimination. For efficiency, also check if\n        // the context has an empty stack case. If so, it would mean\n        // global FOLLOW so we can't perform optimization\n        if p.getStateType() != ATNState.STAR_LOOP_ENTRY ||\n            !( (p as! StarLoopEntryState)).precedenceRuleDecision || // Are we the special loop entry/exit state?\n            configContext.isEmpty() || // If SLL wildcard\n            configContext.hasEmptyPath(){\n            return false\n        }\n\n        // Require all return states to return back to the same rule\n        // that p is in.\n        let numCtxs = configContext.size()\n        for  i in 0 ..< numCtxs { // for each stack context\n            let returnState = atn.states[configContext.getReturnState(i)]!\n            if  returnState.ruleIndex != p.ruleIndex\n            {return false}\n        }\n\n        let decisionStartState = (p.transition(0).target as! BlockStartState)\n        let blockEndStateNum = decisionStartState.endState!.stateNumber\n        let blockEndState = (atn.states[blockEndStateNum] as! BlockEndState)\n\n        // Verify that the top of each stack context leads to loop entry/exit\n        // state through epsilon edges and w/o leaving rule.\n        for  i in 0 ..< numCtxs { // for each stack context\n            let returnStateNumber = configContext.getReturnState(i)\n            let returnState = atn.states[returnStateNumber]!\n            // all states must have single outgoing epsilon edge\n            if  returnState.getNumberOfTransitions() != 1 || !returnState.transition(0).isEpsilon(){\n                return false\n            }\n            // Look for prefix op case like 'not expr', (' type ')' expr\n            let returnStateTarget = returnState.transition(0).target\n            if returnState.getStateType() == ATNState.BLOCK_END &&\n                returnStateTarget == p {\n                continue\n            }\n            // Look for 'expr op expr' or case where expr's return state is block end\n            // of (...)* internal block; the block end points to loop back\n            // which points to p but we don't need to check that\n            if returnState == blockEndState {\n                continue\n            }\n            // Look for ternary expr ? expr : expr. The return state points at block end,\n            // which points at loop entry state\n            if returnStateTarget == blockEndState {\n                continue\n            }\n            // Look for complex prefix 'between expr and expr' case where 2nd expr's\n            // return state points at block end state of (...)* internal block\n            if  returnStateTarget.getStateType() == ATNState.BLOCK_END &&\n                returnStateTarget.getNumberOfTransitions() == 1 &&\n                returnStateTarget.transition(0).isEpsilon() &&\n                returnStateTarget.transition(0).target == p{\n                continue\n            }\n\n            // anything else ain't conforming\n            return false\n        }\n\n        return true\n    }\n\n    open func getRuleName(_ index: Int) -> String {\n        if index >= 0  {\n            return parser.getRuleNames()[index]\n        }\n        return \"<rule \\(index)>\"\n    }\n\n\n    final func getEpsilonTarget(_ config: ATNConfig,\n        _ t: Transition,\n        _ collectPredicates: Bool,\n        _ inContext: Bool,\n        _ fullCtx: Bool,\n        _ treatEofAsEpsilon: Bool) throws -> ATNConfig? {\n            switch t.getSerializationType() {\n            case Transition.RULE:\n                return ruleTransition(config, t as! RuleTransition)\n\n            case Transition.PRECEDENCE:\n                return try precedenceTransition(config, t as! PrecedencePredicateTransition, collectPredicates, inContext, fullCtx)\n\n            case Transition.PREDICATE:\n                return try predTransition(config, t as! PredicateTransition,\n                    collectPredicates,\n                    inContext,\n                    fullCtx)\n\n            case Transition.ACTION:\n                return actionTransition(config, t as! ActionTransition)\n\n            case Transition.EPSILON:\n                return ATNConfig(config, t.target)\n\n            case Transition.ATOM: fallthrough\n            case Transition.RANGE: fallthrough\n            case Transition.SET:\n                // EOF transitions act like epsilon transitions after the first EOF\n                // transition is traversed\n                if treatEofAsEpsilon {\n                    if t.matches(CommonToken.EOF, 0, 1) {\n                        return ATNConfig(config, t.target)\n                    }\n                }\n\n                return nil\n\n            default:\n                return nil\n            }\n\n            //return nil;\n\n    }\n\n\n    final func actionTransition(_ config: ATNConfig, _ t: ActionTransition) -> ATNConfig {\n        if debug {\n            print(\"ACTION edge \\(t.ruleIndex):\\(t.actionIndex)\")\n        }\n        return ATNConfig(config, t.target)\n    }\n\n\n    final func precedenceTransition(_ config: ATNConfig,\n                                    _ pt: PrecedencePredicateTransition,\n                                    _ collectPredicates: Bool,\n                                    _ inContext: Bool,\n                                    _ fullCtx: Bool) throws -> ATNConfig? {\n        if debug {\n            print(\"PRED (collectPredicates=\\(collectPredicates)) \\(pt.precedence)>=_p, ctx dependent=true\")\n            //if ( parser != nil ) {\n            print(\"context surrounding pred is \\(parser.getRuleInvocationStack())\")\n            // }\n        }\n\n        var c: ATNConfig? = nil\n        if collectPredicates && inContext {\n            if fullCtx {\n                // In full context mode, we can evaluate predicates on-the-fly\n                // during closure, which dramatically reduces the size of\n                // the config sets. It also obviates the need to test predicates\n                // later during conflict resolution.\n                let currentPosition = _input.index()\n                try _input.seek(_startIndex)\n                let predSucceeds = try evalSemanticContext(pt.getPredicate(), _outerContext, config.alt, fullCtx)\n                try _input.seek(currentPosition)\n                if predSucceeds {\n                    c = ATNConfig(config, pt.target) // no pred context\n                }\n            }\n            else {\n                let newSemCtx = SemanticContext.and(config.semanticContext, pt.getPredicate())\n                c = ATNConfig(config, pt.target, newSemCtx)\n            }\n        }\n        else {\n            c = ATNConfig(config, pt.target)\n        }\n\n        if debug {\n            print(\"config from pred transition=\\(c?.description ?? \"nil\")\")\n        }\n        return c\n    }\n\n\n    final func predTransition(_ config: ATNConfig,\n                              _ pt: PredicateTransition,\n                              _ collectPredicates: Bool,\n                              _ inContext: Bool,\n                              _ fullCtx: Bool) throws -> ATNConfig? {\n        if debug {\n            print(\"PRED (collectPredicates=\\(collectPredicates)) \\(pt.ruleIndex):\\(pt.predIndex), ctx dependent=\\(pt.isCtxDependent)\")\n            //if ( parser != nil ) {\n            print(\"context surrounding pred is \\(parser.getRuleInvocationStack())\")\n            //}\n        }\n\n        var c: ATNConfig? = nil\n        if collectPredicates &&\n            (!pt.isCtxDependent || (pt.isCtxDependent && inContext)) {\n            if fullCtx {\n                // In full context mode, we can evaluate predicates on-the-fly\n                // during closure, which dramatically reduces the size of\n                // the config sets. It also obviates the need to test predicates\n                // later during conflict resolution.\n                let currentPosition = _input.index()\n                try _input.seek(_startIndex)\n                let predSucceeds = try evalSemanticContext(pt.getPredicate(), _outerContext, config.alt, fullCtx)\n                try _input.seek(currentPosition)\n                if predSucceeds {\n                    c = ATNConfig(config, pt.target) // no pred context\n                }\n            } else {\n                let newSemCtx = SemanticContext.and(config.semanticContext, pt.getPredicate())\n                c = ATNConfig(config, pt.target, newSemCtx)\n            }\n        } else {\n            c = ATNConfig(config, pt.target)\n        }\n\n        if debug {\n            print(\"config from pred transition=\\(c?.description ?? \"nil\")\")\n        }\n        return c\n    }\n\n\n    final func ruleTransition(_ config: ATNConfig, _ t: RuleTransition) -> ATNConfig {\n        if debug {\n            print(\"CALL rule \\(getRuleName(t.target.ruleIndex!)), ctx=\\(config.context?.description ?? \"nil\")\")\n        }\n\n        let returnState = t.followState\n        let newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber)\n        return ATNConfig(config, t.target, newContext)\n    }\n\n    ///\n    /// Gets a _java.util.BitSet_ containing the alternatives in `configs`\n    /// which are part of one or more conflicting alternative subsets.\n    ///\n    /// - parameter configs: The _org.antlr.v4.runtime.atn.ATNConfigSet_ to analyze.\n    /// - returns: The alternatives in `configs` which are part of one or more\n    /// conflicting alternative subsets. If `configs` does not contain any\n    /// conflicting subsets, this method returns an empty _java.util.BitSet_.\n    ///\n    final func getConflictingAlts(_ configs: ATNConfigSet) -> BitSet {\n        let altsets = PredictionMode.getConflictingAltSubsets(configs)\n        return PredictionMode.getAlts(altsets)\n    }\n\n    ///\n    /// Sam pointed out a problem with the previous definition, v3, of\n    /// ambiguous states. If we have another state associated with conflicting\n    /// alternatives, we should keep going. For example, the following grammar\n    ///\n    /// s : (ID | ID ID?) ';' ;\n    ///\n    /// When the ATN simulation reaches the state before ';', it has a DFA\n    /// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally\n    /// 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node\n    /// because alternative to has another way to continue, via [6|2|[]].\n    /// The key is that we have a single state that has config's only associated\n    /// with a single alternative, 2, and crucially the state transitions\n    /// among the configurations are all non-epsilon transitions. That means\n    /// we don't consider any conflicts that include alternative 2. So, we\n    /// ignore the conflict between alts 1 and 2. We ignore a set of\n    /// conflicting alts when there is an intersection with an alternative\n    /// associated with a single alt state in the state&rarr;config-list map.\n    ///\n    /// It's also the case that we might have two conflicting configurations but\n    /// also a 3rd nonconflicting configuration for a different alternative:\n    /// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:\n    ///\n    /// a : A | A | A B ;\n    ///\n    /// After matching input A, we reach the stop state for rule A, state 1.\n    /// State 8 is the state right before B. Clearly alternatives 1 and 2\n    /// conflict and no amount of further lookahead will separate the two.\n    /// However, alternative 3 will be able to continue and so we do not\n    /// stop working on this state. In the previous example, we're concerned\n    /// with states associated with the conflicting alternatives. Here alt\n    /// 3 is not associated with the conflicting configs, but since we can continue\n    /// looking for input reasonably, I don't declare the state done. We\n    /// ignore a set of conflicting alts when we have an alternative\n    /// that we still need to pursue.\n    ///\n    final func getConflictingAltsOrUniqueAlt(_ configs: ATNConfigSet) -> BitSet {\n        var conflictingAlts: BitSet\n        if configs.uniqueAlt != ATN.INVALID_ALT_NUMBER {\n            conflictingAlts = BitSet()\n            try! conflictingAlts.set(configs.uniqueAlt)\n        } else {\n            conflictingAlts = configs.conflictingAlts!\n        }\n        return conflictingAlts\n    }\n\n\n    public final func getTokenName(_ t: Int) -> String {\n        if t == CommonToken.EOF {\n            return \"EOF\"\n        }\n        let vocabulary = parser.getVocabulary()\n        let displayName = vocabulary.getDisplayName(t)\n        if displayName == String(t) {\n            return displayName\n        }\n\n        return \"\\(displayName) <\\(t)>\"\n    }\n\n    public final func getLookaheadName(_ input: TokenStream) throws -> String {\n        return try getTokenName(input.LA(1))\n    }\n\n    ///\n    /// Used for debugging in adaptivePredict around execATN but I cut\n    /// it out for clarity now that alg. works well. We can leave this\n    /// \"dead\" code for a bit.\n    ///\n    public final func dumpDeadEndConfigs(_ nvae: NoViableAltException) {\n        errPrint(\"dead end configs: \")\n        for c in nvae.getDeadEndConfigs()!.configs {\n            var trans = \"no edges\"\n            if c.state.getNumberOfTransitions() > 0 {\n                let t = c.state.transition(0)\n                if let at = t as? AtomTransition {\n                    trans = \"Atom \" + getTokenName(at.label)\n                }\n                else if let st = t as? SetTransition {\n                    let not = st is NotSetTransition\n                    trans = (not ? \"~\" : \"\") + \"Set \" + st.set.description\n                }\n            }\n            errPrint(\"\\(c.toString(parser, true)):\\(trans)\")\n        }\n    }\n\n\n    final func noViableAlt(_ input: TokenStream,\n                           _ outerContext: ParserRuleContext,\n                           _ configs: ATNConfigSet,\n                           _ startIndex: Int) -> NoViableAltException {\n        let startToken = try! input.get(startIndex)\n        var offendingToken: Token? = nil\n        do {\n            offendingToken = try input.LT(1)\n        }\n        catch {\n        }\n        return NoViableAltException(parser, input, startToken, offendingToken, configs, outerContext)\n    }\n\n    internal static func getUniqueAlt(_ configs: ATNConfigSet) -> Int {\n        let alt = configs.getUniqueAlt()\n        return alt\n    }\n\n    ///\n    /// Add an edge to the DFA, if possible. This method calls\n    /// _#addDFAState_ to ensure the `to` state is present in the\n    /// DFA. If `from` is `null`, or if `t` is outside the\n    /// range of edges that can be represented in the DFA tables, this method\n    /// returns without adding the edge to the DFA.\n    ///\n    /// If `to` is `null`, this method returns `null`.\n    /// Otherwise, this method returns the _org.antlr.v4.runtime.dfa.DFAState_ returned by calling\n    /// _#addDFAState_ for the `to` state.\n    ///\n    /// - parameter dfa: The DFA\n    /// - parameter from: The source state for the edge\n    /// - parameter t: The input symbol\n    /// - parameter to: The target state for the edge\n    ///\n    /// - returns: the result of calling _#addDFAState_ on `to`\n    ///\n    @discardableResult\n    private final func addDFAEdge(_ dfa: DFA,\n                          _ from: DFAState,\n                          _ t: Int,\n                          _ to: DFAState) -> DFAState {\n        var to = to\n        if debug {\n            print(\"EDGE \\(from) -> \\(to) upon \\(getTokenName(t))\")\n        }\n\n        to = addDFAState(dfa, to) // used existing if possible not incoming\n        if t < -1 || t > atn.maxTokenType {\n            return to\n        }\n        from.mutex.synchronized {\n            [unowned self] in\n            if from.edges == nil {\n                from.edges = [DFAState?](repeating: nil, count: self.atn.maxTokenType + 1 + 1)       //new DFAState[atn.maxTokenType+1+1];\n            }\n\n            from.edges[t + 1] = to // connect\n        }\n\n        if debug {\n            print(\"DFA=\\n\" + dfa.toString(parser.getVocabulary()))\n        }\n\n        return to\n    }\n\n    ///\n    /// Add state `D` to the DFA if it is not already present, and return\n    /// the actual instance stored in the DFA. If a state equivalent to `D`\n    /// is already in the DFA, the existing state is returned. Otherwise this\n    /// method returns `D` after adding it to the DFA.\n    ///\n    /// If `D` is _#ERROR_, this method returns _#ERROR_ and\n    /// does not change the DFA.\n    ///\n    /// - parameter dfa: The dfa\n    /// - parameter D: The DFA state to add\n    /// - returns: The state stored in the DFA. This will be either the existing\n    /// state if `D` is already in the DFA, or `D` itself if the\n    /// state was not already present.\n    ///\n    private final func addDFAState(_ dfa: DFA, _ D: DFAState) -> DFAState {\n        if D == ATNSimulator.ERROR {\n            return D\n        }\n\n        return dfa.statesMutex.synchronized {\n            if let existing = dfa.states[D] {\n                return existing\n            }\n\n            D.stateNumber = dfa.states.count\n\n            if !D.configs.isReadonly() {\n                try! D.configs.optimizeConfigs(self)\n                D.configs.setReadonly(true)\n            }\n\n            dfa.states[D] = D\n            if debug {\n                print(\"adding new DFA state: \\(D)\")\n            }\n\n            return D\n        }\n    }\n\n    func reportAttemptingFullContext(_ dfa: DFA, _ conflictingAlts: BitSet?, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) {\n        if debug || retry_debug {\n            let input = getTextInInterval(startIndex, stopIndex)\n            print(\"reportAttemptingFullContext decision=\\(dfa.decision):\\(configs), input=\\(input)\")\n        }\n        parser.getErrorListenerDispatch().reportAttemptingFullContext(parser, dfa, startIndex, stopIndex, conflictingAlts, configs)\n    }\n\n    func reportContextSensitivity(_ dfa: DFA, _ prediction: Int, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) {\n        if debug || retry_debug {\n            let input = getTextInInterval(startIndex, stopIndex)\n            print(\"reportContextSensitivity decision=\\(dfa.decision):\\(configs), input=\\(input)\")\n        }\n        parser.getErrorListenerDispatch().reportContextSensitivity(parser, dfa, startIndex, stopIndex, prediction, configs)\n    }\n\n    ///\n    /// If context sensitive parsing, we know it's ambiguity not conflict\n    ///\n     // configs that LL not SLL considered conflictin\n    internal func reportAmbiguity(_ dfa: DFA,\n        _ D: DFAState, // the DFA state from execATN() that had SLL conflicts\n        _ startIndex: Int, _ stopIndex: Int,\n        _ exact: Bool,\n        _ ambigAlts: BitSet,\n        _ configs: ATNConfigSet)\n    {\n        if debug || retry_debug {\n            let input = getTextInInterval(startIndex, stopIndex)\n            print(\"reportAmbiguity \\(ambigAlts):\\(configs), input=\\(input)\")\n        }\n        parser.getErrorListenerDispatch().reportAmbiguity(parser, dfa, startIndex, stopIndex,\n            exact, ambigAlts, configs)\n    }\n\n    private func getTextInInterval(_ startIndex: Int, _ stopIndex: Int) -> String {\n        let interval = Interval.of(startIndex, stopIndex)\n        do {\n            return try parser.getTokenStream()?.getText(interval) ?? \"<unknown>\"\n        }\n        catch {\n            return \"<unknown>\"\n        }\n    }\n\n    public final func setPredictionMode(_ mode: PredictionMode) {\n        self.mode = mode\n    }\n\n\n    public final func getPredictionMode() -> PredictionMode {\n        return mode\n    }\n\n    public final func getParser() -> Parser {\n        return parser\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PlusBlockStartState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Start of `(A|B|...)+` loop. Technically a decision state, but\n/// we don't use for code generation; somebody might need it, so I'm defining\n/// it for completeness. In reality, the _org.antlr.v4.runtime.atn.PlusLoopbackState_ node is the\n/// real decision-making note for `A+`.\n/// \n\npublic final class PlusBlockStartState: BlockStartState {\n    public var loopBackState: PlusLoopbackState?\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.PLUS_BLOCK_START\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PlusLoopbackState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Decision state for `A+` and `(A|B)+`.  It has two transitions:\n/// one to the loop back to start of the block and one to exit.\n/// \n\npublic final class PlusLoopbackState: DecisionState {\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.PLUS_LOOP_BACK\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PrecedencePredicateTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// \n/// -  Sam Harwell\n/// \n\npublic final class PrecedencePredicateTransition: AbstractPredicateTransition, CustomStringConvertible {\n    public let precedence: Int\n\n    public init(_ target: ATNState, _ precedence: Int) {\n\n        self.precedence = precedence\n        super.init(target)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.PRECEDENCE\n    }\n\n    override\n    public func isEpsilon() -> Bool {\n        return true\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return false\n    }\n\n    public func getPredicate() -> SemanticContext.PrecedencePredicate {\n        return SemanticContext.PrecedencePredicate(precedence)\n    }\n\n    public var description: String {\n        return \"\\(precedence)  >= _p\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PredicateEvalInfo.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This class represents profiling event information for semantic predicate\n/// evaluations which occur during prediction.\n/// \n/// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext\n/// \n/// -  4.3\n/// \n\npublic class PredicateEvalInfo: DecisionEventInfo {\n    /// \n    /// The semantic context which was evaluated.\n    /// \n    public private(set) var semctx: SemanticContext\n    /// \n    /// The alternative number for the decision which is guarded by the semantic\n    /// context _#semctx_. Note that other ATN\n    /// configurations may predict the same alternative which are guarded by\n    /// other semantic contexts and/or _org.antlr.v4.runtime.atn.SemanticContext#NONE_.\n    /// \n    public private(set) var predictedAlt: Int\n    /// \n    /// The result of evaluating the semantic context _#semctx_.\n    /// \n    public private(set) var evalResult: Bool\n\n    /// \n    /// Constructs a new instance of the _org.antlr.v4.runtime.atn.PredicateEvalInfo_ class with the\n    /// specified detailed predicate evaluation information.\n    /// \n    /// - parameter decision: The decision number\n    /// - parameter input: The input token stream\n    /// - parameter startIndex: The start index for the current prediction\n    /// - parameter stopIndex: The index at which the predicate evaluation was\n    /// triggered. Note that the input stream may be reset to other positions for\n    /// the actual evaluation of individual predicates.\n    /// - parameter semctx: The semantic context which was evaluated\n    /// - parameter evalResult: The results of evaluating the semantic context\n    /// - parameter predictedAlt: The alternative number for the decision which is\n    /// guarded by the semantic context `semctx`. See _#predictedAlt_\n    /// for more information.\n    /// - parameter fullCtx: `true` if the semantic context was\n    /// evaluated during LL prediction; otherwise, `false` if the semantic\n    /// context was evaluated during SLL prediction\n    /// \n    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#evalSemanticContext(org.antlr.v4.runtime.atn.SemanticContext, org.antlr.v4.runtime.ParserRuleContext, int, boolean)\n    /// - seealso: org.antlr.v4.runtime.atn.SemanticContext#eval(org.antlr.v4.runtime.Recognizer, org.antlr.v4.runtime.RuleContext)\n    /// \n    public init(_ decision: Int,\n                _ input: TokenStream,\n                _ startIndex: Int,\n                _ stopIndex: Int,\n                _ semctx: SemanticContext,\n                _ evalResult: Bool,\n                _ predictedAlt: Int,\n                _ fullCtx: Bool) {\n\n        self.semctx = semctx\n        self.evalResult = evalResult\n        self.predictedAlt = predictedAlt\n        super.init(decision, ATNConfigSet(), input, startIndex, stopIndex, fullCtx)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PredicateTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// TODO: this is old comment:\n/// A tree of semantic predicates from the grammar AST if label==SEMPRED.\n/// In the ATN, labels will always be exactly one predicate, but the DFA\n/// may have to combine a bunch of them as it collects predicates from\n/// multiple ATN configurations into a single DFA state.\n/// \n\npublic final class PredicateTransition: AbstractPredicateTransition, CustomStringConvertible {\n    public let ruleIndex: Int\n    public let predIndex: Int\n    public let isCtxDependent: Bool\n    // e.g., $i ref in pred\n\n    public init(_ target: ATNState, _ ruleIndex: Int, _ predIndex: Int, _ isCtxDependent: Bool) {\n\n        self.ruleIndex = ruleIndex\n        self.predIndex = predIndex\n        self.isCtxDependent = isCtxDependent\n        super.init(target)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return PredicateTransition.PREDICATE\n    }\n\n    override\n    public func isEpsilon() -> Bool {\n        return true\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return false\n    }\n\n    public func getPredicate() -> SemanticContext.Predicate {\n        return SemanticContext.Predicate(ruleIndex, predIndex, isCtxDependent)\n    }\n\n    public var description: String {\n        return \"pred_\\(ruleIndex):\\(predIndex)\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PredictionContext.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\nimport Foundation\n\npublic class PredictionContext: Hashable, CustomStringConvertible {\n    ///\n    /// Represents `$` in an array in full context mode, when `$`\n    /// doesn't mean wildcard: `$ + x = [$,x]`. Here,\n    /// `$` = _#EMPTY_RETURN_STATE_.\n    ///\n    public static let EMPTY_RETURN_STATE = Int(Int32.max)\n\n    private static let INITIAL_HASH = UInt32(1)\n\n    public static var globalNodeCount = 0\n\n    public final let id: Int = {\n        let oldGlobalNodeCount = globalNodeCount\n        globalNodeCount += 1\n        return oldGlobalNodeCount\n    }()\n\n    ///\n    /// Stores the computed hash code of this _org.antlr.v4.runtime.atn.PredictionContext_. The hash\n    /// code is computed in parts to match the following reference algorithm.\n    ///\n    ///\n    /// private int referenceHashCode() {\n    /// int hash = _org.antlr.v4.runtime.misc.MurmurHash#initialize MurmurHash.initialize_(_#INITIAL_HASH_);\n    ///\n    /// for (int i = 0; i &lt; _#size()_; i++) {\n    /// hash = _org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update_(hash, _#getParent getParent_(i));\n    /// }\n    ///\n    /// for (int i = 0; i &lt; _#size()_; i++) {\n    /// hash = _org.antlr.v4.runtime.misc.MurmurHash#update MurmurHash.update_(hash, _#getReturnState getReturnState_(i));\n    /// }\n    ///\n    /// hash = _org.antlr.v4.runtime.misc.MurmurHash#finish MurmurHash.finish_(hash, 2 * _#size()_);\n    /// return hash;\n    /// }\n    ///\n    ///\n    public let cachedHashCode: Int\n\n    init(_ cachedHashCode: Int) {\n        self.cachedHashCode = cachedHashCode\n    }\n\n    ///\n    /// Convert a _org.antlr.v4.runtime.RuleContext_ tree to a _org.antlr.v4.runtime.atn.PredictionContext_ graph.\n    /// Return _#EMPTY_ if `outerContext` is empty or null.\n    ///\n    public static func fromRuleContext(_ atn: ATN, _ outerContext: RuleContext?) -> PredictionContext {\n        let _outerContext = outerContext ?? ParserRuleContext.EMPTY\n\n        // if we are in RuleContext of start rule, s, then PredictionContext\n        // is EMPTY. Nobody called us. (if we are empty, return empty)\n        if (_outerContext.parent == nil || _outerContext === ParserRuleContext.EMPTY) {\n            return EmptyPredictionContext.Instance\n        }\n\n        // If we have a parent, convert it to a PredictionContext graph\n        let parent = PredictionContext.fromRuleContext(atn, _outerContext.parent)\n\n        let state = atn.states[_outerContext.invokingState]!\n        let transition = state.transition(0) as! RuleTransition\n        return SingletonPredictionContext.create(parent, transition.followState.stateNumber)\n    }\n\n    public func size() -> Int {\n        fatalError(#function + \" must be overridden\")\n    }\n\n\n    public func getParent(_ index: Int) -> PredictionContext? {\n        fatalError(#function + \" must be overridden\")\n    }\n\n\n    public func getReturnState(_ index: Int) -> Int {\n        fatalError(#function + \" must be overridden\")\n    }\n\n\n    ///\n    /// This means only the _#EMPTY_ context is in set.\n    ///\n    public func isEmpty() -> Bool {\n        return self === EmptyPredictionContext.Instance\n    }\n\n    public func hasEmptyPath() -> Bool {\n        return getReturnState(size() - 1) == PredictionContext.EMPTY_RETURN_STATE\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(cachedHashCode)\n    }\n\n    static func calculateEmptyHashCode() -> Int {\n        let hash = MurmurHash.initialize(INITIAL_HASH)\n        return MurmurHash.finish(hash, 0)\n    }\n\n    static func calculateHashCode(_ parent: PredictionContext?, _ returnState: Int) -> Int {\n        var hash = MurmurHash.initialize(INITIAL_HASH)\n        hash = MurmurHash.update(hash, parent)\n        hash = MurmurHash.update(hash, returnState)\n        return MurmurHash.finish(hash, 2)\n    }\n\n    static func calculateHashCode(_ parents: [PredictionContext?], _ returnStates: [Int]) -> Int {\n        var hash = MurmurHash.initialize(INITIAL_HASH)\n        for parent in parents {\n            hash = MurmurHash.update(hash, parent)\n        }\n        for state in returnStates {\n            hash = MurmurHash.update(hash, state)\n        }\n\n        return  MurmurHash.finish(hash, 2 * parents.count)\n    }\n\n    // dispatch\n    public static func merge(\n        _ a: PredictionContext,\n        _ b: PredictionContext,\n        _ rootIsWildcard: Bool,\n        _ mergeCache: inout DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>?) -> PredictionContext {\n        var a = a\n        var b = b\n            // assert ( a != nil && b != nil,\"Expected: a!=null&&b!=null\");\n            //assert ( a!=nil && b!=nil,\"Expected: a!=null&&b!=null\"); // must be empty context, never null\n            // share same graph if both same\n\n\n            if a == b {\n                return a\n            }\n\n            if let spc_a = a as? SingletonPredictionContext, let spc_b = b as? SingletonPredictionContext {\n                return mergeSingletons(spc_a, spc_b, rootIsWildcard, &mergeCache)\n            }\n\n            // At least one of a or b is array\n            // If one is $ and rootIsWildcard, return $ as * wildcard\n            if rootIsWildcard {\n                if a is EmptyPredictionContext {\n                    return a\n                }\n                if b is EmptyPredictionContext {\n                    return b\n                }\n            }\n\n            // convert singleton so both are arrays to normalize\n            if let spc_a = a as? SingletonPredictionContext {\n                a = ArrayPredictionContext(spc_a)\n            }\n            if let spc_b = b as? SingletonPredictionContext {\n                b = ArrayPredictionContext(spc_b)\n            }\n            return mergeArrays(a as! ArrayPredictionContext, b as! ArrayPredictionContext,\n                rootIsWildcard, &mergeCache)\n    }\n\n    ///\n    /// Merge two _org.antlr.v4.runtime.atn.SingletonPredictionContext_ instances.\n    ///\n    /// Stack tops equal, parents merge is same; return left graph.\n    ///\n    ///\n    /// Same stack top, parents differ; merge parents giving array node, then\n    /// remainders of those graphs. A new root node is created to point to the\n    /// merged parents.\n    ///\n    ///\n    /// Different stack tops pointing to same parent. Make array node for the\n    /// root where both element in the root point to the same (original)\n    /// parent.\n    ///\n    ///\n    /// Different stack tops pointing to different parents. Make array node for\n    /// the root where each element points to the corresponding original\n    /// parent.\n    ///\n    ///\n    /// - parameter a: the first _org.antlr.v4.runtime.atn.SingletonPredictionContext_\n    /// - parameter b: the second _org.antlr.v4.runtime.atn.SingletonPredictionContext_\n    /// - parameter rootIsWildcard: `true` if this is a local-context merge,\n    /// otherwise false to indicate a full-context merge\n    /// - parameter mergeCache:\n    ///\n    public static func mergeSingletons(\n        _ a: SingletonPredictionContext,\n        _ b: SingletonPredictionContext,\n        _ rootIsWildcard: Bool,\n        _ mergeCache: inout DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>?) -> PredictionContext {\n\n            if let mergeCache = mergeCache {\n                var previous = mergeCache.get(a, b)\n                if let previous = previous {\n                    return previous\n                }\n                previous = mergeCache.get(b, a)\n                if let previous = previous {\n                    return previous\n                }\n            }\n\n\n            if let rootMerge = mergeRoot(a, b, rootIsWildcard) {\n                mergeCache?.put(a, b, rootMerge)\n                return rootMerge\n            }\n\n            if a.returnState == b.returnState {\n                // a == b\n                let parent = merge(a.parent!, b.parent!, rootIsWildcard, &mergeCache)\n                // if parent is same as existing a or b parent or reduced to a parent, return it\n                if parent === a.parent! {\n                    return a\n                } // ax + bx = ax, if a=b\n                if parent === b.parent! {\n                    return b\n                } // ax + bx = bx, if a=b\n                // else: ax + ay = a'[x,y]\n                // merge parents x and y, giving array node with x,y then remainders\n                // of those graphs.  dup a, a' points at merged array\n                // new joined parent so create new singleton pointing to it, a'\n                let a_ = SingletonPredictionContext.create(parent, a.returnState);\n                mergeCache?.put(a, b, a_)\n                return a_\n            } else {\n                // a != b payloads differ\n                // see if we can collapse parents due to $+x parents if local ctx\n                var singleParent: PredictionContext? = nil\n                //added by janyou\n                if a === b || (a.parent != nil && a.parent! == b.parent) {\n                    // ax + bx = [a,b]x\n                    singleParent = a.parent\n                }\n                if let singleParent = singleParent {\n                    // parents are same\n                    // sort payloads and use same parent\n                    var payloads = [a.returnState, b.returnState]\n                    if a.returnState > b.returnState {\n                        payloads[0] = b.returnState\n                        payloads[1] = a.returnState\n                    }\n                    let parents = [singleParent, singleParent]\n                    let a_ = ArrayPredictionContext(parents, payloads)\n                    mergeCache?.put(a, b, a_)\n                    return a_\n                }\n                // parents differ and can't merge them. Just pack together\n                // into array; can't merge.\n                // ax + by = [ax,by]\n                var payloads = [a.returnState, b.returnState]\n                var parents = [a.parent, b.parent]\n                if a.returnState > b.returnState {\n                    // sort by payload\n                    payloads[0] = b.returnState\n                    payloads[1] = a.returnState\n                    parents = [b.parent, a.parent]\n                }\n                if a is EmptyPredictionContext {\n                    // print(\"parent is null\")\n                }\n                let a_ = ArrayPredictionContext(parents, payloads)\n                mergeCache?.put(a, b, a_)\n                return a_\n            }\n    }\n\n    ///\n    /// Handle case where at least one of `a` or `b` is\n    /// _#EMPTY_. In the following diagrams, the symbol `$` is used\n    /// to represent _#EMPTY_.\n    ///\n    /// Local-Context Merges\n    ///\n    /// These local-context merge operations are used when `rootIsWildcard`\n    /// is true.\n    ///\n    /// _#EMPTY_ is superset of any graph; return _#EMPTY_.\n    ///\n    ///\n    /// _#EMPTY_ and anything is `#EMPTY`, so merged parent is\n    /// `#EMPTY`; return left graph.\n    ///\n    ///\n    /// Special case of last merge if local context.\n    ///\n    ///\n    /// Full-Context Merges\n    ///\n    /// These full-context merge operations are used when `rootIsWildcard`\n    /// is false.\n    ///\n    ///\n    ///\n    /// Must keep all contexts; _#EMPTY_ in array is a special value (and\n    /// null parent).\n    ///\n    ///\n    ///\n    ///\n    /// - parameter a: the first _org.antlr.v4.runtime.atn.SingletonPredictionContext_\n    /// - parameter b: the second _org.antlr.v4.runtime.atn.SingletonPredictionContext_\n    /// - parameter rootIsWildcard: `true` if this is a local-context merge,\n    /// otherwise false to indicate a full-context merge\n    ///\n    public static func mergeRoot(_ a: SingletonPredictionContext,\n        _ b: SingletonPredictionContext,\n        _ rootIsWildcard: Bool) -> PredictionContext? {\n            if rootIsWildcard {\n                if a === EmptyPredictionContext.Instance {\n                    return EmptyPredictionContext.Instance\n                }  // * + b = *\n                if b === EmptyPredictionContext.Instance {\n                    return EmptyPredictionContext.Instance\n                }  // a + * = *\n            } else {\n                if a === EmptyPredictionContext.Instance && b === EmptyPredictionContext.Instance {\n                    return EmptyPredictionContext.Instance\n                } // $ + $ = $\n                if a === EmptyPredictionContext.Instance {\n                    // $ + x = [$,x]\n                    let payloads = [b.returnState, EMPTY_RETURN_STATE]\n                    let parents = [b.parent, nil]\n                    let joined = ArrayPredictionContext(parents, payloads)\n                    return joined\n                }\n                if b === EmptyPredictionContext.Instance {\n                    // x + $ = [$,x] ($ is always first if present)\n                    let payloads = [a.returnState, EMPTY_RETURN_STATE]\n                    let parents = [a.parent, nil]\n                    let joined = ArrayPredictionContext(parents, payloads)\n                    return joined\n                }\n            }\n            return nil\n    }\n\n    ///\n    /// Merge two _org.antlr.v4.runtime.atn.ArrayPredictionContext_ instances.\n    ///\n    /// Different tops, different parents.\n    ///\n    ///\n    /// Shared top, same parents.\n    ///\n    ///\n    /// Shared top, different parents.\n    ///\n    ///\n    /// Shared top, all shared parents.\n    ///\n    ///\n    /// Equal tops, merge parents and reduce top to\n    /// _org.antlr.v4.runtime.atn.SingletonPredictionContext_.\n    ///\n    ///\n    public static func mergeArrays(\n        _ a: ArrayPredictionContext,\n        _ b: ArrayPredictionContext,\n        _ rootIsWildcard: Bool,\n        _ mergeCache: inout DoubleKeyMap<PredictionContext, PredictionContext, PredictionContext>?) -> PredictionContext {\n\n            if let previous = mergeCache?.get(a, b) ?? mergeCache?.get(b, a) {\n                return previous\n            }\n\n            // merge sorted payloads a + b => M\n            var i = 0 // walks a\n            var j = 0 // walks b\n            var k = 0 // walks target M array\n\n            let aReturnStatesLength = a.returnStates.count\n            let bReturnStatesLength = b.returnStates.count\n\n            let mergedReturnStatesLength = aReturnStatesLength + bReturnStatesLength\n            var mergedReturnStates = [Int](repeating: 0, count: mergedReturnStatesLength)\n\n            var mergedParents = [PredictionContext?](repeating: nil, count: mergedReturnStatesLength)\n            // walk and merge to yield mergedParents, mergedReturnStates\n            let aReturnStates = a.returnStates\n            let bReturnStates = b.returnStates\n            let aParents = a.parents\n            let bParents = b.parents\n\n            while i < aReturnStatesLength && j < bReturnStatesLength {\n                let a_parent = aParents[i]\n                let b_parent = bParents[j]\n                if aReturnStates[i] == bReturnStates[j] {\n                    // same payload (stack tops are equal), must yield merged singleton\n                    let payload = aReturnStates[i]\n                    // $+$ = $\n                    let both$ = ((payload == EMPTY_RETURN_STATE) && a_parent == nil && b_parent == nil)\n                    let ax_ax = (a_parent != nil && b_parent != nil && a_parent == b_parent)\n\n                    if both$ || ax_ax {\n                        mergedParents[k] = a_parent // choose left\n                        mergedReturnStates[k] = payload\n                    } else {\n                        // ax+ay -> a'[x,y]\n                        let mergedParent = merge(a_parent!, b_parent!, rootIsWildcard, &mergeCache)\n                        mergedParents[k] = mergedParent\n                        mergedReturnStates[k] = payload\n                    }\n                    i += 1 // hop over left one as usual\n                    j += 1 // but also skip one in right side since we merge\n                } else if aReturnStates[i] < bReturnStates[j] {\n                    // copy a[i] to M\n                    mergedParents[k] = a_parent\n                    mergedReturnStates[k] = aReturnStates[i]\n                    i += 1\n                } else {\n                    // b > a, copy b[j] to M\n                    mergedParents[k] = b_parent\n                    mergedReturnStates[k] = bReturnStates[j]\n                    j += 1\n                }\n                k += 1\n            }\n\n            // copy over any payloads remaining in either array\n            if i < aReturnStatesLength {\n\n                for p in i..<aReturnStatesLength {\n                    mergedParents[k] = aParents[p]\n                    mergedReturnStates[k] = aReturnStates[p]\n                    k += 1\n                }\n            } else {\n                for p in j..<bReturnStatesLength {\n                    mergedParents[k] = bParents[p]\n                    mergedReturnStates[k] = bReturnStates[p]\n                    k += 1\n                }\n            }\n\n            // trim merged if we combined a few that had same stack tops\n            if k < mergedParents.count {\n                // write index < last position; trim\n                if k == 1 {\n                    // for just one merged element, return singleton top\n                    let a_ = SingletonPredictionContext.create(mergedParents[0], mergedReturnStates[0])\n                    mergeCache?.put(a, b, a_)\n                    //print(\"merge array 1 \\(a_)\")\n                    return a_\n                }\n                mergedParents = Array(mergedParents[0 ..< k])\n                mergedReturnStates = Array(mergedReturnStates[0 ..< k])\n            }\n\n            let M = ArrayPredictionContext(mergedParents, mergedReturnStates)\n\n            // if we created same array as a or b, return that instead\n            // TODO: track whether this is possible above during merge sort for speed\n            if M == a {\n                mergeCache?.put(a, b, a)\n                return a\n            }\n            if M == b {\n                mergeCache?.put(a, b, b)\n                return b\n            }\n\n            //modify by janyou\n            //combineCommonParents(&mergedParents)\n            M.combineCommonParents()\n\n            mergeCache?.put(a, b, M)\n            // print(\"merge array 4 \\(M)\")\n            return M\n    }\n\n    public static func toDOTString(_ context: PredictionContext?) -> String {\n        if context == nil {\n            return \"\"\n        }\n        var buf = \"\"\n        buf += \"digraph G {\\n\"\n        buf += \"rankdir=LR;\\n\"\n\n        var nodes = getAllContextNodes(context!)\n\n        nodes.sort { $0.id > $1.id }\n\n        for current in nodes {\n            if current is SingletonPredictionContext {\n                buf += \"  s\\(current.id)\"\n                var returnState = String(current.getReturnState(0))\n                if current is EmptyPredictionContext {\n                    returnState = \"$\"\n                }\n                buf += \" [label=\\\"\\(returnState)\\\"];\\n\"\n                continue\n            }\n            let arr = current as! ArrayPredictionContext\n            buf += \"  s\\(arr.id) [shape=box, label=\\\"[\"\n            var first = true\n            let returnStates = arr.returnStates\n            for inv in returnStates {\n                if !first {\n                    buf += \", \"\n                }\n                if inv == EMPTY_RETURN_STATE {\n                    buf += \"$\"\n                } else {\n                    buf += String(inv)\n                }\n                first = false\n            }\n            buf += \"]\\\"];\\n\"\n        }\n\n        for current in nodes {\n            if current === EmptyPredictionContext.Instance {\n                continue\n            }\n            let length = current.size()\n            for i in 0..<length {\n                guard let currentParent = current.getParent(i) else {\n                    continue\n                }\n                buf += \"  s\\(current.id) -> s\\(currentParent.id)\"\n                if current.size() > 1 {\n                    buf += \" [label=\\\"parent[\\(i)]\\\"];\\n\"\n                } else {\n                    buf += \";\\n\"\n                }\n            }\n        }\n\n        buf.append(\"}\\n\")\n        return buf\n    }\n\n    // From Sam\n    public static func getCachedContext(\n        _ context: PredictionContext,\n        _ contextCache: PredictionContextCache,\n        _ visited: inout [PredictionContext: PredictionContext]) -> PredictionContext {\n        if context.isEmpty() {\n            return context\n        }\n\n        if let visitedContext = visited[context] {\n            return visitedContext\n        }\n\n        if let cachedContext = contextCache.get(context) {\n            visited[context] = cachedContext\n            return cachedContext\n        }\n\n        var changed = false\n        var parents = [PredictionContext?](repeating: nil, count: context.size())\n        let length = parents.count\n        for i in 0..<length {\n            guard let p = context.getParent(i) else {\n                return context\n            }\n\n            let parent = getCachedContext(p, contextCache, &visited)\n            if changed || parent !== p {\n                if !changed {\n                    parents = [PredictionContext?](repeating: nil, count: context.size())\n\n                    for j in 0..<context.size() {\n                        parents[j] = context.getParent(j)\n                    }\n\n                    changed = true\n                }\n\n                parents[i] = parent\n            }\n        }\n\n        if !changed {\n            contextCache.add(context)\n            visited[context] = context\n            return context\n        }\n\n        let updated: PredictionContext\n        if parents.isEmpty {\n            updated = EmptyPredictionContext.Instance\n        }\n        else if parents.count == 1 {\n            updated = SingletonPredictionContext.create(parents[0], context.getReturnState(0))\n        }\n        else {\n            let arrayPredictionContext = context as! ArrayPredictionContext\n            updated = ArrayPredictionContext(parents, arrayPredictionContext.returnStates)\n        }\n\n        contextCache.add(updated)\n        visited[updated] = updated\n        visited[context] = updated\n\n        return updated\n    }\n\n\n\n    // ter's recursive version of Sam's getAllNodes()\n    public static func getAllContextNodes(_ context: PredictionContext) -> [PredictionContext] {\n        var nodes = [PredictionContext]()\n        var visited = [PredictionContext: PredictionContext]()\n        getAllContextNodes_(context, &nodes, &visited)\n        return nodes\n    }\n\n    private static func getAllContextNodes_(_ context: PredictionContext?,\n                                            _ nodes: inout [PredictionContext],\n                                            _ visited: inout [PredictionContext: PredictionContext]) {\n        guard let context = context, visited[context] == nil else {\n            return\n        }\n        visited[context] = context\n        nodes.append(context)\n        let length = context.size()\n        for i in 0..<length {\n            getAllContextNodes_(context.getParent(i), &nodes, &visited)\n        }\n    }\n\n    public func toString<T>(_ recog: Recognizer<T>) -> String {\n        return String(describing: PredictionContext.self)\n        //\t\treturn toString(recog, ParserRuleContext.EMPTY);\n    }\n\n    public func toStrings<T>(_ recognizer: Recognizer<T>, _ currentState: Int) -> [String] {\n        return toStrings(recognizer, EmptyPredictionContext.Instance, currentState)\n    }\n\n    // FROM SAM\n    public func toStrings<T>(_ recognizer: Recognizer<T>?, _ stop: PredictionContext, _ currentState: Int) -> [String] {\n        var result = [String]()\n        var perm = 0\n        outer: while true {\n                var offset = 0\n                var last = true\n                var p = self\n                var stateNumber = currentState\n                var localBuffer = \"[\"\n                while !p.isEmpty() && p !== stop {\n                    var index = 0\n                    if p.size() > 0 {\n                        var bits = 1\n                        while (1 << bits) < p.size() {\n                            bits += 1\n                        }\n\n                        let mask = (1 << bits) - 1\n                        index = (perm >> offset) & mask\n\n                        //last &= index >= p.size() - 1;\n                        //last = Bool(Int(last) & (index >= p.size() - 1));\n                        last = last && (index >= p.size() - 1)\n\n                        if index >= p.size() {\n                            continue outer\n                        }\n                        offset += bits\n                    }\n\n                    if let recognizer = recognizer {\n                        if localBuffer.count > 1 {\n                            // first char is '[', if more than that this isn't the first rule\n                            localBuffer += \" \"\n                        }\n\n                        let atn = recognizer.getATN()\n                        let s = atn.states[stateNumber]!\n                        let ruleName = recognizer.getRuleNames()[s.ruleIndex!]\n                        localBuffer.append(ruleName)\n                    }\n                    else if p.getReturnState(index) != PredictionContext.EMPTY_RETURN_STATE {\n                        if !p.isEmpty() {\n                            if localBuffer.count > 1 {\n                                // first char is '[', if more than that this isn't the first rule\n                                localBuffer += \" \"\n                            }\n\n                            localBuffer += String(p.getReturnState(index))\n                        }\n                    }\n                    stateNumber = p.getReturnState(index)\n                    p = p.getParent(index)!\n                }\n                localBuffer += \"]\"\n                result.append(localBuffer)\n\n                if last {\n                    break\n                }\n\n                perm += 1\n        }\n\n        return result\n    }\n\n    public var description: String {\n        return String(describing: PredictionContext.self) + \"@\" + String(Unmanaged.passUnretained(self).toOpaque().hashValue)\n    }\n}\n\n\npublic func ==(lhs: RuleContext, rhs: ParserRuleContext) -> Bool {\n    if let lhs = lhs as? ParserRuleContext {\n        return lhs === rhs\n    }\n    else {\n        return false\n    }\n}\n\npublic func ==(lhs: PredictionContext, rhs: PredictionContext) -> Bool {\n\n    if lhs === rhs {\n        return true\n    }\n    if lhs is EmptyPredictionContext {\n        return lhs === rhs\n    }\n\n    if let lhs = lhs as? SingletonPredictionContext, let rhs = rhs as? SingletonPredictionContext {\n        return lhs == rhs\n    }\n\n    if let lhs = lhs as? ArrayPredictionContext, let rhs = rhs as? ArrayPredictionContext {\n        return lhs == rhs\n    }\n\n    return false\n}\n\npublic func ==(lhs: ArrayPredictionContext, rhs: SingletonPredictionContext) -> Bool {\n    return false\n}\n\npublic func ==(lhs: SingletonPredictionContext, rhs: ArrayPredictionContext) -> Bool {\n    return false\n}\n\npublic func ==(lhs: SingletonPredictionContext, rhs: EmptyPredictionContext) -> Bool {\n    return false\n}\n\npublic func ==(lhs: EmptyPredictionContext, rhs: ArrayPredictionContext) -> Bool {\n    return lhs === rhs\n}\n\npublic func ==(lhs: EmptyPredictionContext, rhs: SingletonPredictionContext) -> Bool {\n    return lhs === rhs\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PredictionContextCache.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\n///\n/// Used to cache _org.antlr.v4.runtime.atn.PredictionContext_ objects. Its used for the shared\n/// context cash associated with contexts in DFA states. This cache\n/// can be used for both lexers and parsers.\n///\n\npublic final class PredictionContextCache {\n    private var cache = [PredictionContext: PredictionContext]()\n\n    public init() {\n    }\n\n    ///\n    /// Add a context to the cache and return it. If the context already exists,\n    /// return that one instead and do not add a new context to the cache.\n    /// Protect shared cache from unsafe thread access.\n    ///\n    @discardableResult\n    public func add(_ ctx: PredictionContext) -> PredictionContext {\n        if ctx === EmptyPredictionContext.Instance {\n            return EmptyPredictionContext.Instance\n        }\n        if let existing = cache[ctx] {\n//\t\t\tprint(name+\" reuses \"+existing);\n            return existing\n        }\n        cache[ctx] = ctx\n        return ctx\n    }\n\n    public func get(_ ctx: PredictionContext) -> PredictionContext? {\n        return cache[ctx]\n    }\n\n    public func size() -> Int {\n        return cache.count\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/PredictionMode.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// This enumeration defines the prediction modes available in ANTLR 4 along with\n/// utility methods for analyzing configuration sets for conflicts and/or\n/// ambiguities.\n/// \n\npublic enum PredictionMode {\n    /// \n    /// The SLL(*) prediction mode. This prediction mode ignores the current\n    /// parser context when making predictions. This is the fastest prediction\n    /// mode, and provides correct results for many grammars. This prediction\n    /// mode is more powerful than the prediction mode provided by ANTLR 3, but\n    /// may result in syntax errors for grammar and input combinations which are\n    /// not SLL.\n    /// \n    /// \n    /// When using this prediction mode, the parser will either return a correct\n    /// parse tree (i.e. the same parse tree that would be returned with the\n    /// _#LL_ prediction mode), or it will report a syntax error. If a\n    /// syntax error is encountered when using the _#SLL_ prediction mode,\n    /// it may be due to either an actual syntax error in the input or indicate\n    /// that the particular combination of grammar and input requires the more\n    /// powerful _#LL_ prediction abilities to complete successfully.\n    /// \n    /// \n    /// This prediction mode does not provide any guarantees for prediction\n    /// behavior for syntactically-incorrect inputs.\n    /// \n    case SLL\n    /// \n    /// The LL(*) prediction mode. This prediction mode allows the current parser\n    /// context to be used for resolving SLL conflicts that occur during\n    /// prediction. This is the fastest prediction mode that guarantees correct\n    /// parse results for all combinations of grammars with syntactically correct\n    /// inputs.\n    /// \n    /// \n    /// When using this prediction mode, the parser will make correct decisions\n    /// for all syntactically-correct grammar and input combinations. However, in\n    /// cases where the grammar is truly ambiguous this prediction mode might not\n    /// report a precise answer for __exactly which__ alternatives are\n    /// ambiguous.\n    /// \n    /// \n    /// This prediction mode does not provide any guarantees for prediction\n    /// behavior for syntactically-incorrect inputs.\n    /// \n    case LL\n    /// \n    /// The LL(*) prediction mode with exact ambiguity detection. In addition to\n    /// the correctness guarantees provided by the _#LL_ prediction mode,\n    /// this prediction mode instructs the prediction algorithm to determine the\n    /// complete and exact set of ambiguous alternatives for every ambiguous\n    /// decision encountered while parsing.\n    /// \n    /// \n    /// This prediction mode may be used for diagnosing ambiguities during\n    /// grammar development. Due to the performance overhead of calculating sets\n    /// of ambiguous alternatives, this prediction mode should be avoided when\n    /// the exact results are not necessary.\n    /// \n    /// \n    /// This prediction mode does not provide any guarantees for prediction\n    /// behavior for syntactically-incorrect inputs.\n    /// \n    case LL_EXACT_AMBIG_DETECTION\n\n\n    /// \n    /// Computes the SLL prediction termination condition.\n    /// \n    /// \n    /// This method computes the SLL prediction termination condition for both of\n    /// the following cases.\n    /// \n    /// * The usual SLL+LL fallback upon SLL conflict\n    /// * Pure SLL without LL fallback\n    /// \n    /// __COMBINED SLL+LL PARSING__\n    /// \n    /// When LL-fallback is enabled upon SLL conflict, correct predictions are\n    /// ensured regardless of how the termination condition is computed by this\n    /// method. Due to the substantially higher cost of LL prediction, the\n    /// prediction should only fall back to LL when the additional lookahead\n    /// cannot lead to a unique SLL prediction.\n    /// \n    /// Assuming combined SLL+LL parsing, an SLL configuration set with only\n    /// conflicting subsets should fall back to full LL, even if the\n    /// configuration sets don't resolve to the same alternative (e.g.\n    /// `{1,2`} and `{3,4`}. If there is at least one non-conflicting\n    /// configuration, SLL could continue with the hopes that more lookahead will\n    /// resolve via one of those non-conflicting configurations.\n    /// \n    /// Here's the prediction termination rule them: SLL (for SLL+LL parsing)\n    /// stops when it sees only conflicting configuration subsets. In contrast,\n    /// full LL keeps going when there is uncertainty.\n    /// \n    /// __HEURISTIC__\n    /// \n    /// As a heuristic, we stop prediction when we see any conflicting subset\n    /// unless we see a state that only has one alternative associated with it.\n    /// The single-alt-state thing lets prediction continue upon rules like\n    /// (otherwise, it would admit defeat too soon):\n    /// \n    /// `[12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;`\n    /// \n    /// When the ATN simulation reaches the state before `';'`, it has a\n    /// DFA state that looks like: `[12|1|[], 6|2|[], 12|2|[]]`. Naturally\n    /// `12|1|[]` and `12|2|[]` conflict, but we cannot stop\n    /// processing this node because alternative to has another way to continue,\n    /// via `[6|2|[]]`.\n    /// \n    /// It also let's us continue for this rule:\n    /// \n    /// `[1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;`\n    /// \n    /// After matching input A, we reach the stop state for rule A, state 1.\n    /// State 8 is the state right before B. Clearly alternatives 1 and 2\n    /// conflict and no amount of further lookahead will separate the two.\n    /// However, alternative 3 will be able to continue and so we do not stop\n    /// working on this state. In the previous example, we're concerned with\n    /// states associated with the conflicting alternatives. Here alt 3 is not\n    /// associated with the conflicting configs, but since we can continue\n    /// looking for input reasonably, don't declare the state done.\n    /// \n    /// __PURE SLL PARSING__\n    /// \n    /// To handle pure SLL parsing, all we have to do is make sure that we\n    /// combine stack contexts for configurations that differ only by semantic\n    /// predicate. From there, we can do the usual SLL termination heuristic.\n    /// \n    /// __PREDICATES IN SLL+LL PARSING__\n    /// \n    /// SLL decisions don't evaluate predicates until after they reach DFA stop\n    /// states because they need to create the DFA cache that works in all\n    /// semantic situations. In contrast, full LL evaluates predicates collected\n    /// during start state computation so it can ignore predicates thereafter.\n    /// This means that SLL termination detection can totally ignore semantic\n    /// predicates.\n    /// \n    /// Implementation-wise, _org.antlr.v4.runtime.atn.ATNConfigSet_ combines stack contexts but not\n    /// semantic predicate contexts so we might see two configurations like the\n    /// following.\n    /// \n    /// `(s, 1, x, {`), (s, 1, x', {p})}\n    /// \n    /// Before testing these configurations against others, we have to merge\n    /// `x` and `x'` (without modifying the existing configurations).\n    /// For example, we test `(x+x')==x''` when looking for conflicts in\n    /// the following configurations.\n    /// \n    /// `(s, 1, x, {`), (s, 1, x', {p}), (s, 2, x'', {})}\n    /// \n    /// If the configuration set has predicates (as indicated by\n    /// _org.antlr.v4.runtime.atn.ATNConfigSet#hasSemanticContext_), this algorithm makes a copy of\n    /// the configurations to strip out all of the predicates so that a standard\n    /// _org.antlr.v4.runtime.atn.ATNConfigSet_ will merge everything ignoring predicates.\n    /// \n    public static func hasSLLConflictTerminatingPrediction(_ mode: PredictionMode,_ configs: ATNConfigSet) -> Bool {\n        var configs = configs\n        /// \n        /// Configs in rule stop states indicate reaching the end of the decision\n        /// rule (local context) or end of start rule (full context). If all\n        /// configs meet this condition, then none of the configurations is able\n        /// to match additional input so we terminate prediction.\n        /// \n        if allConfigsInRuleStopStates(configs) {\n            return true\n        }\n\n        // pure SLL mode parsing\n        if mode == PredictionMode.SLL {\n            // Don't bother with combining configs from different semantic\n            // contexts if we can fail over to full LL; costs more time\n            // since we'll often fail over anyway.\n            if configs.hasSemanticContext {\n                // dup configs, tossing out semantic predicates\n                configs = configs.dupConfigsWithoutSemanticPredicates()\n            }\n            // now we have combined contexts for configs with dissimilar preds\n        }\n\n        // pure SLL or combined SLL+LL mode parsing\n\n        let altsets = getConflictingAltSubsets(configs)\n\n        let heuristic = hasConflictingAltSet(altsets) && !hasStateAssociatedWithOneAlt(configs)\n        return heuristic\n    }\n\n    /// \n    /// Checks if any configuration in `configs` is in a\n    /// _org.antlr.v4.runtime.atn.RuleStopState_. Configurations meeting this condition have reached\n    /// the end of the decision rule (local context) or end of start rule (full\n    /// context).\n    /// \n    /// - parameter configs: the configuration set to test\n    /// - returns: `true` if any configuration in `configs` is in a\n    /// _org.antlr.v4.runtime.atn.RuleStopState_, otherwise `false`\n    /// \n    public static func hasConfigInRuleStopState(_ configs: ATNConfigSet) -> Bool {\n\n        return  configs.hasConfigInRuleStopState\n    }\n\n    /// \n    /// Checks if all configurations in `configs` are in a\n    /// _org.antlr.v4.runtime.atn.RuleStopState_. Configurations meeting this condition have reached\n    /// the end of the decision rule (local context) or end of start rule (full\n    /// context).\n    /// \n    /// - parameter configs: the configuration set to test\n    /// - returns: `true` if all configurations in `configs` are in a\n    /// _org.antlr.v4.runtime.atn.RuleStopState_, otherwise `false`\n    /// \n    public static func allConfigsInRuleStopStates(_ configs: ATNConfigSet) -> Bool {\n\n        return configs.allConfigsInRuleStopStates\n    }\n\n    /// \n    /// Full LL prediction termination.\n    /// \n    /// Can we stop looking ahead during ATN simulation or is there some\n    /// uncertainty as to which alternative we will ultimately pick, after\n    /// consuming more input? Even if there are partial conflicts, we might know\n    /// that everything is going to resolve to the same minimum alternative. That\n    /// means we can stop since no more lookahead will change that fact. On the\n    /// other hand, there might be multiple conflicts that resolve to different\n    /// minimums. That means we need more look ahead to decide which of those\n    /// alternatives we should predict.\n    /// \n    /// The basic idea is to split the set of configurations `C`, into\n    /// conflicting subsets `(s, _, ctx, _)` and singleton subsets with\n    /// non-conflicting configurations. Two configurations conflict if they have\n    /// identical _org.antlr.v4.runtime.atn.ATNConfig#state_ and _org.antlr.v4.runtime.atn.ATNConfig#context_ values\n    /// but different _org.antlr.v4.runtime.atn.ATNConfig#alt_ value, e.g. `(s, i, ctx, _)`\n    /// and `(s, j, ctx, _)` for `i!=j`.\n    /// \n    /// Reduce these configuration subsets to the set of possible alternatives.\n    /// You can compute the alternative subsets in one pass as follows:\n    /// \n    /// `A_s,ctx = {i | (s, i, ctx, _)`} for each configuration in\n    /// `C` holding `s` and `ctx` fixed.\n    /// \n    /// Or in pseudo-code, for each configuration `c` in `C`:\n    /// \n    /// \n    /// map[c] U= c._org.antlr.v4.runtime.atn.ATNConfig#alt alt_ # map hash/equals uses s and x, not\n    /// alt and not pred\n    /// \n    /// \n    /// The values in `map` are the set of `A_s,ctx` sets.\n    /// \n    /// If `|A_s,ctx|=1` then there is no conflict associated with\n    /// `s` and `ctx`.\n    /// \n    /// Reduce the subsets to singletons by choosing a minimum of each subset. If\n    /// the union of these alternative subsets is a singleton, then no amount of\n    /// more lookahead will help us. We will always pick that alternative. If,\n    /// however, there is more than one alternative, then we are uncertain which\n    /// alternative to predict and must continue looking for resolution. We may\n    /// or may not discover an ambiguity in the future, even if there are no\n    /// conflicting subsets this round.\n    /// \n    /// The biggest sin is to terminate early because it means we've made a\n    /// decision but were uncertain as to the eventual outcome. We haven't used\n    /// enough lookahead. On the other hand, announcing a conflict too late is no\n    /// big deal; you will still have the conflict. It's just inefficient. It\n    /// might even look until the end of file.\n    /// \n    /// No special consideration for semantic predicates is required because\n    /// predicates are evaluated on-the-fly for full LL prediction, ensuring that\n    /// no configuration contains a semantic context during the termination\n    /// check.\n    /// \n    /// __CONFLICTING CONFIGS__\n    /// \n    /// Two configurations `(s, i, x)` and `(s, j, x')`, conflict\n    /// when `i!=j` but `x=x'`. Because we merge all\n    /// `(s, i, _)` configurations together, that means that there are at\n    /// most `n` configurations associated with state `s` for\n    /// `n` possible alternatives in the decision. The merged stacks\n    /// complicate the comparison of configuration contexts `x` and\n    /// `x'`. Sam checks to see if one is a subset of the other by calling\n    /// merge and checking to see if the merged result is either `x` or\n    /// `x'`. If the `x` associated with lowest alternative `i`\n    /// is the superset, then `i` is the only possible prediction since the\n    /// others resolve to `min(i)` as well. However, if `x` is\n    /// associated with `j>i` then at least one stack configuration for\n    /// `j` is not in conflict with alternative `i`. The algorithm\n    /// should keep going, looking for more lookahead due to the uncertainty.\n    /// \n    /// For simplicity, I'm doing a equality check between `x` and\n    /// `x'` that lets the algorithm continue to consume lookahead longer\n    /// than necessary. The reason I like the equality is of course the\n    /// simplicity but also because that is the test you need to detect the\n    /// alternatives that are actually in conflict.\n    /// \n    /// __CONTINUE/STOP RULE__\n    /// \n    /// Continue if union of resolved alternative sets from non-conflicting and\n    /// conflicting alternative subsets has more than one alternative. We are\n    /// uncertain about which alternative to predict.\n    /// \n    /// The complete set of alternatives, `[i for (_,i,_)]`, tells us which\n    /// alternatives are still in the running for the amount of input we've\n    /// consumed at this point. The conflicting sets let us to strip away\n    /// configurations that won't lead to more states because we resolve\n    /// conflicts to the configuration with a minimum alternate for the\n    /// conflicting set.\n    /// \n    /// __CASES__\n    /// \n    /// * no conflicts and more than 1 alternative in set =&gt; continue\n    /// \n    /// * `(s, 1, x)`, `(s, 2, x)`, `(s, 3, z)`,\n    /// `(s', 1, y)`, `(s', 2, y)` yields non-conflicting set\n    /// `{3`} U conflicting sets `min({1,2`)} U `min({1,2`)} =\n    /// `{1,3`} =&gt; continue\n    /// \n    /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 1, y)`,\n    /// `(s', 2, y)`, `(s'', 1, z)` yields non-conflicting set\n    /// `{1`} U conflicting sets `min({1,2`)} U `min({1,2`)} =\n    /// `{1`} =&gt; stop and predict 1\n    /// \n    /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 1, y)`,\n    /// `(s', 2, y)` yields conflicting, reduced sets `{1`} U\n    /// `{1`} = `{1`} =&gt; stop and predict 1, can announce\n    /// ambiguity `{1,2`}\n    /// \n    /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 2, y)`,\n    /// `(s', 3, y)` yields conflicting, reduced sets `{1`} U\n    /// `{2`} = `{1,2`} =&gt; continue\n    /// \n    /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 3, y)`,\n    /// `(s', 4, y)` yields conflicting, reduced sets `{1`} U\n    /// `{3`} = `{1,3`} =&gt; continue\n    /// \n    /// \n    /// __EXACT AMBIGUITY DETECTION__\n    /// \n    /// If all states report the same conflicting set of alternatives, then we\n    /// know we have the exact ambiguity set.\n    /// \n    /// `|A_i__|&gt;1` and\n    /// `A_i = A_j` for all i, j.\n    /// \n    /// In other words, we continue examining lookahead until all `A_i`\n    /// have more than one alternative and all `A_i` are the same. If\n    /// `A={{1,2`, {1,3}}}, then regular LL prediction would terminate\n    /// because the resolved set is `{1`}. To determine what the real\n    /// ambiguity is, we have to know whether the ambiguity is between one and\n    /// two or one and three so we keep going. We can only stop prediction when\n    /// we need exact ambiguity detection when the sets look like\n    /// `A={{1,2`}} or `{{1,2`,{1,2}}}, etc...\n    /// \n    public static func resolvesToJustOneViableAlt(_ altsets: [BitSet]) -> Int {\n        return getSingleViableAlt(altsets)\n    }\n\n    /// \n    /// Determines if every alternative subset in `altsets` contains more\n    /// than one alternative.\n    /// \n    /// - parameter altsets: a collection of alternative subsets\n    /// - returns: `true` if every _java.util.BitSet_ in `altsets` has\n    /// _java.util.BitSet#cardinality cardinality_ &gt; 1, otherwise `false`\n    /// \n    public static func allSubsetsConflict(_ altsets: [BitSet]) -> Bool {\n        return !hasNonConflictingAltSet(altsets)\n    }\n\n    /// \n    /// Determines if any single alternative subset in `altsets` contains\n    /// exactly one alternative.\n    /// \n    /// - parameter altsets: a collection of alternative subsets\n    /// - returns: `true` if `altsets` contains a _java.util.BitSet_ with\n    /// _java.util.BitSet#cardinality cardinality_ 1, otherwise `false`\n    /// \n    public static func hasNonConflictingAltSet(_ altsets: [BitSet]) -> Bool {\n        for alts: BitSet in altsets {\n            if alts.cardinality() == 1 {\n                return true\n            }\n        }\n        return false\n    }\n\n    /// \n    /// Determines if any single alternative subset in `altsets` contains\n    /// more than one alternative.\n    /// \n    /// - parameter altsets: a collection of alternative subsets\n    /// - returns: `true` if `altsets` contains a _java.util.BitSet_ with\n    /// _java.util.BitSet#cardinality cardinality_ &gt; 1, otherwise `false`\n    /// \n    public static func hasConflictingAltSet(_ altsets: [BitSet]) -> Bool {\n        for alts: BitSet in altsets {\n            if alts.cardinality() > 1 {\n                return true\n            }\n        }\n        return false\n    }\n\n    /// \n    /// Determines if every alternative subset in `altsets` is equivalent.\n    /// \n    /// - parameter altsets: a collection of alternative subsets\n    /// - returns: `true` if every member of `altsets` is equal to the\n    /// others, otherwise `false`\n    /// \n    public static func allSubsetsEqual(_ altsets: [BitSet]) -> Bool {\n\n        let first: BitSet = altsets[0]\n        for it in altsets {\n            if it != first {\n                return false\n            }\n\n        }\n        return true\n    }\n\n    /// \n    /// Returns the unique alternative predicted by all alternative subsets in\n    /// `altsets`. If no such alternative exists, this method returns\n    /// _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_.\n    /// \n    /// - parameter altsets: a collection of alternative subsets\n    /// \n    public static func getUniqueAlt(_ altsets: [BitSet]) -> Int {\n        let all: BitSet = getAlts(altsets)\n        if all.cardinality() == 1 {\n            return all.firstSetBit()\n        }\n        return ATN.INVALID_ALT_NUMBER\n    }\n\n    /// \n    /// Gets the complete set of represented alternatives for a collection of\n    /// alternative subsets. This method returns the union of each _java.util.BitSet_\n    /// in `altsets`.\n    /// \n    /// - parameter altsets: a collection of alternative subsets\n    /// - returns: the set of represented alternatives in `altsets`\n    /// \n    public static func getAlts(_ altsets: Array<BitSet>) -> BitSet {\n        let all: BitSet = BitSet()\n        for alts: BitSet in altsets {\n            all.or(alts)\n        }\n        return all\n    }\n\n    /// \n    /// Get union of all alts from configs. - Since: 4.5.1\n    /// \n    public static func getAlts(_ configs: ATNConfigSet) -> BitSet {\n        return configs.getAltBitSet()\n\n    }\n\n    /// \n    /// This function gets the conflicting alt subsets from a configuration set.\n    /// For each configuration `c` in `configs`:\n    /// \n    /// \n    /// map[c] U= c._org.antlr.v4.runtime.atn.ATNConfig#alt alt_ # map hash/equals uses s and x, not\n    /// alt and not pred\n    /// \n    /// \n\n    public static func getConflictingAltSubsets(_ configs: ATNConfigSet) -> [BitSet] {\n        return configs.getConflictingAltSubsets()\n    }\n\n    public static func hasStateAssociatedWithOneAlt(_ configs: ATNConfigSet) -> Bool {\n        let x = configs.getStateToAltMap()\n        for alts in x.values {\n            if alts.cardinality() == 1 {\n                return true\n            }\n        }\n        return false\n    }\n\n    public static func getSingleViableAlt(_ altsets: [BitSet]) -> Int {\n        let viableAlts = BitSet()\n        for alts in altsets {\n            let minAlt = alts.firstSetBit()\n            try! viableAlts.set(minAlt)\n            if viableAlts.cardinality() > 1 {\n                // more than 1 viable alt\n                return ATN.INVALID_ALT_NUMBER\n            }\n        }\n        return viableAlts.firstSetBit()\n    }\n\n}\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/ProfilingATNSimulator.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// -  4.3\n/// \n\nimport Foundation\n\npublic class ProfilingATNSimulator: ParserATNSimulator {\n    private(set) var decisions: [DecisionInfo]\n    internal var numDecisions: Int = 0\n\n    internal var _sllStopIndex: Int = 0\n    internal var _llStopIndex: Int = 0\n\n    internal var currentDecision: Int = 0\n    internal var currentState: DFAState?\n\n    /// \n    /// At the point of LL failover, we record how SLL would resolve the conflict so that\n    /// we can determine whether or not a decision / input pair is context-sensitive.\n    /// If LL gives a different result than SLL's predicted alternative, we have a\n    /// context sensitivity for sure. The converse is not necessarily true, however.\n    /// It's possible that after conflict resolution chooses minimum alternatives,\n    /// SLL could get the same answer as LL. Regardless of whether or not the result indicates\n    /// an ambiguity, it is not treated as a context sensitivity because LL prediction\n    /// was not required in order to produce a correct prediction for this decision and input sequence.\n    /// It may in fact still be a context sensitivity but we don't know by looking at the\n    /// minimum alternatives for the current input.\n    /// \n    internal var conflictingAltResolvedBySLL: Int = 0\n\n    public init(_ parser: Parser) {\n        decisions = [DecisionInfo]()\n\n        super.init(parser,\n                parser.getInterpreter().atn,\n                parser.getInterpreter().decisionToDFA,\n                parser.getInterpreter().sharedContextCache)\n\n        numDecisions = atn.decisionToState.count\n        for i in 0..<numDecisions {\n            decisions.append(DecisionInfo(i))\n        }\n\n\n    }\n\n    override\n    public func adaptivePredict(_ input: TokenStream, _ decision: Int,_ outerContext: ParserRuleContext?) throws -> Int {\n        let outerContext = outerContext\n        self._sllStopIndex = -1\n        self._llStopIndex = -1\n        self.currentDecision = decision\n        let start = ProcessInfo.processInfo.systemUptime //System.nanoTime(); // expensive but useful info\n        let alt: Int = try  super.adaptivePredict(input, decision, outerContext)\n        let stop = ProcessInfo.processInfo.systemUptime  //System.nanoTime();\n        decisions[decision].timeInPrediction += Int64((stop - start) * TimeInterval(1_000_000_000)) // Nanoseconds per 1 Second\n        decisions[decision].invocations += 1\n\n        let SLL_k: Int64 = Int64(_sllStopIndex - _startIndex + 1)\n        decisions[decision].SLL_TotalLook += SLL_k\n        decisions[decision].SLL_MinLook = decisions[decision].SLL_MinLook == 0 ? SLL_k : min(decisions[decision].SLL_MinLook, SLL_k)\n        if SLL_k > decisions[decision].SLL_MaxLook {\n            decisions[decision].SLL_MaxLook = SLL_k\n            decisions[decision].SLL_MaxLookEvent =\n                    LookaheadEventInfo(decision, nil, input, _startIndex, _sllStopIndex, false)\n        }\n\n        if _llStopIndex >= 0 {\n            let LL_k: Int64 = Int64(_llStopIndex - _startIndex + 1)\n            decisions[decision].LL_TotalLook += LL_k\n            decisions[decision].LL_MinLook = decisions[decision].LL_MinLook == 0 ? LL_k : min(decisions[decision].LL_MinLook, LL_k)\n            if LL_k > decisions[decision].LL_MaxLook {\n                decisions[decision].LL_MaxLook = LL_k\n                decisions[decision].LL_MaxLookEvent =\n                        LookaheadEventInfo(decision, nil, input, _startIndex, _llStopIndex, true)\n            }\n        }\n\n        defer {\n            self.currentDecision = -1\n        }\n        return alt\n\n\n    }\n\n    override\n    internal func getExistingTargetState(_ previousD: DFAState, _ t: Int) -> DFAState? {\n        // this method is called after each time the input position advances\n        // during SLL prediction\n        _sllStopIndex = _input.index()\n\n        let existingTargetState: DFAState? = super.getExistingTargetState(previousD, t)\n        if existingTargetState != nil {\n            decisions[currentDecision].SLL_DFATransitions += 1 // count only if we transition over a DFA state\n            if existingTargetState == ATNSimulator.ERROR {\n                decisions[currentDecision].errors.append(\n                ErrorInfo(currentDecision, previousD.configs, _input, _startIndex, _sllStopIndex, false)\n                )\n            }\n        }\n\n        currentState = existingTargetState\n        return existingTargetState\n    }\n\n    override\n    internal func computeTargetState(_ dfa: DFA, _ previousD: DFAState, _ t: Int) throws -> DFAState {\n        let state = try super.computeTargetState(dfa, previousD, t)\n        currentState = state\n        return state\n    }\n\n    override\n    internal func computeReachSet(_ closure: ATNConfigSet, _ t: Int, _ fullCtx: Bool) throws -> ATNConfigSet? {\n        if fullCtx {\n            // this method is called after each time the input position advances\n            // during full context prediction\n            _llStopIndex = _input.index()\n        }\n\n        let reachConfigs = try super.computeReachSet(closure, t, fullCtx)\n        if fullCtx {\n            decisions[currentDecision].LL_ATNTransitions += 1 // count computation even if error\n            if reachConfigs != nil {\n            } else {\n                // no reach on current lookahead symbol. ERROR.\n                // TODO: does not handle delayed errors per getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule()\n                decisions[currentDecision].errors.append(\n                ErrorInfo(currentDecision, closure, _input, _startIndex, _llStopIndex, true)\n                )\n            }\n        } else {\n            decisions[currentDecision].SLL_ATNTransitions += 1\n            if reachConfigs != nil {\n            } else {\n                // no reach on current lookahead symbol. ERROR.\n                decisions[currentDecision].errors.append(\n                ErrorInfo(currentDecision, closure, _input, _startIndex, _sllStopIndex, false)\n                )\n            }\n        }\n        return reachConfigs\n    }\n\n    override\n    internal func evalSemanticContext(_ pred: SemanticContext, _ parserCallStack: ParserRuleContext, _ alt: Int, _ fullCtx: Bool) throws -> Bool {\n        let result = try super.evalSemanticContext(pred, parserCallStack, alt, fullCtx)\n        if !(pred is SemanticContext.PrecedencePredicate) {\n            let fullContext = _llStopIndex >= 0\n            let stopIndex = fullContext ? _llStopIndex : _sllStopIndex\n            decisions[currentDecision].predicateEvals.append(\n                PredicateEvalInfo(currentDecision, _input, _startIndex, stopIndex, pred, result, alt, fullCtx)\n            )\n        }\n\n        return result\n    }\n\n    override\n    internal func reportAttemptingFullContext(_ dfa: DFA, _ conflictingAlts: BitSet?, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) {\n        if let conflictingAlts = conflictingAlts {\n            conflictingAltResolvedBySLL = conflictingAlts.firstSetBit()\n        } else {\n            let configAlts = configs.getAlts()\n            conflictingAltResolvedBySLL = configAlts.firstSetBit()\n        }\n        decisions[currentDecision].LL_Fallback += 1\n        super.reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex)\n    }\n\n    override\n    internal func reportContextSensitivity(_ dfa: DFA, _ prediction: Int, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) {\n        if prediction != conflictingAltResolvedBySLL {\n            decisions[currentDecision].contextSensitivities.append(\n            ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex)\n            )\n        }\n        super.reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex)\n    }\n\n    override\n    internal func reportAmbiguity(_ dfa: DFA, _ D: DFAState, _ startIndex: Int, _ stopIndex: Int, _ exact: Bool,\n                                  _ ambigAlts: BitSet?, _ configs: ATNConfigSet) {\n        var prediction: Int\n        if let ambigAlts = ambigAlts {\n            prediction = ambigAlts.firstSetBit()\n        } else {\n            let configAlts = configs.getAlts()\n            prediction = configAlts.firstSetBit()\n        }\n        if configs.fullCtx && prediction != conflictingAltResolvedBySLL {\n            // Even though this is an ambiguity we are reporting, we can\n            // still detect some context sensitivities.  Both SLL and LL\n            // are showing a conflict, hence an ambiguity, but if they resolve\n            // to different minimum alternatives we have also identified a\n            // context sensitivity.\n            decisions[currentDecision].contextSensitivities.append(\n            ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex)\n            )\n        }\n        decisions[currentDecision].ambiguities.append(\n        AmbiguityInfo(currentDecision, configs, ambigAlts!,\n                _input, startIndex, stopIndex, configs.fullCtx)\n        )\n        super.reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts!, configs)\n    }\n\n\n    public func getDecisionInfo() -> [DecisionInfo] {\n        return decisions\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/RangeTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic final class RangeTransition: Transition, CustomStringConvertible {\n    public let from: Int\n    public let to: Int\n\n    public init(_ target: ATNState, _ from: Int, _ to: Int) {\n\n        self.from = from\n        self.to = to\n        super.init(target)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.RANGE\n    }\n\n    override\n    public func labelIntervalSet() -> IntervalSet? {\n        return IntervalSet.of(from, to)\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return symbol >= from && symbol <= to\n    }\n\n    public var description: String {\n        return \"'\" + String(from) + \"'..'\" + String(to) + \"'\"\n\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/RuleStartState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic final class RuleStartState: ATNState {\n    public var stopState: RuleStopState?\n    public var isPrecedenceRule: Bool = false\n    //Synonymous with rule being left recursive; consider renaming.\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.RULE_START\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/RuleStopState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// The last node in the ATN for a rule, unless that rule is the start symbol.\n/// In that case, there is one transition to EOF. Later, we might encode\n/// references to all calls to this rule to compute FOLLOW sets for\n/// error handling.\n/// \n\npublic final class RuleStopState: ATNState {\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.RULE_STOP\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/RuleTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n\n\npublic final class RuleTransition: Transition {\n    /// \n    /// Ptr to the rule definition object for this rule ref\n    /// \n    public let ruleIndex: Int\n    // no Rule object at runtime\n\n    public let precedence: Int\n\n    /// \n    /// What node to begin computations following ref to rule\n    /// \n    public let followState: ATNState\n\n    public init(_ ruleStart: RuleStartState,\n                _ ruleIndex: Int,\n                _ precedence: Int,\n                _ followState: ATNState) {\n\n        self.ruleIndex = ruleIndex\n        self.precedence = precedence\n        self.followState = followState\n\n        super.init(ruleStart)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.RULE\n    }\n\n    override\n    public func isEpsilon() -> Bool {\n        return true\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return false\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/SemanticContext.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\n\n///\n/// A tree structure used to record the semantic context in which\n/// an ATN configuration is valid.  It's either a single predicate,\n/// a conjunction `p1&&p2`, or a sum of products `p1||p2`.\n///\n/// I have scoped the _org.antlr.v4.runtime.atn.SemanticContext.AND_, _org.antlr.v4.runtime.atn.SemanticContext.OR_, and _org.antlr.v4.runtime.atn.SemanticContext.Predicate_ subclasses of\n/// _org.antlr.v4.runtime.atn.SemanticContext_ within the scope of this outer class.\n///\n\nimport Foundation\n\npublic class SemanticContext: Hashable, CustomStringConvertible {\n    ///\n    /// For context independent predicates, we evaluate them without a local\n    /// context (i.e., null context). That way, we can evaluate them without\n    /// having to create proper rule-specific context during prediction (as\n    /// opposed to the parser, which creates them naturally). In a practical\n    /// sense, this avoids a cast exception from RuleContext to myruleContext.\n    ///\n    /// For context dependent predicates, we must pass in a local context so that\n    /// references such as $arg evaluate properly as _localctx.arg. We only\n    /// capture context dependent predicates in the context in which we begin\n    /// prediction, so we passed in the outer context here in case of context\n    /// dependent predicate evaluation.\n    ///\n    public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    ///\n    /// Evaluate the precedence predicates for the context and reduce the result.\n    ///\n    /// - parameter parser: The parser instance.\n    /// - parameter parserCallStack:\n    /// - returns: The simplified semantic context after precedence predicates are\n    /// evaluated, which will be one of the following values.\n    /// * _#NONE_: if the predicate simplifies to `true` after\n    /// precedence predicates are evaluated.\n    /// * `null`: if the predicate simplifies to `false` after\n    /// precedence predicates are evaluated.\n    /// * `this`: if the semantic context is not changed as a result of\n    /// precedence predicate evaluation.\n    /// * A non-`null` _org.antlr.v4.runtime.atn.SemanticContext_: the new simplified\n    /// semantic context after precedence predicates are evaluated.\n    ///\n    public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {\n        return self\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    public var description: String {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    public class Empty: SemanticContext {\n        //\n        /// The default _org.antlr.v4.runtime.atn.SemanticContext_, which is semantically equivalent to\n        /// a predicate of the form `{true?}.\n        ///\n        public static let Instance: Empty = Empty()\n\n        public override func hash(into hasher: inout Hasher) {\n        }\n\n        override\n        public var description: String {\n            return \"{true}?\"\n        }\n    }\n\n    public class Predicate: SemanticContext {\n        public let ruleIndex: Int\n        public let predIndex: Int\n        public let isCtxDependent: Bool\n        // e.g., $i ref in pred\n\n        override\n        public init() {\n            self.ruleIndex = -1\n            self.predIndex = -1\n            self.isCtxDependent = false\n        }\n\n        public init(_ ruleIndex: Int, _ predIndex: Int, _ isCtxDependent: Bool) {\n            self.ruleIndex = ruleIndex\n            self.predIndex = predIndex\n            self.isCtxDependent = isCtxDependent\n        }\n\n        override\n        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {\n            let localctx = isCtxDependent ? parserCallStack : nil\n            return try parser.sempred(localctx, ruleIndex, predIndex)\n        }\n\n        public override func hash(into hasher: inout Hasher) {\n            hasher.combine(ruleIndex)\n            hasher.combine(predIndex)\n            hasher.combine(isCtxDependent)\n        }\n\n        override\n        public var description: String {\n            return \"{\\(ruleIndex):\\(predIndex)}?\"\n        }\n\n    }\n\n\n    public class PrecedencePredicate: SemanticContext {\n        public let precedence: Int\n        override\n        init() {\n            self.precedence = 0\n        }\n\n        public init(_ precedence: Int) {\n            self.precedence = precedence\n        }\n\n        override\n        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {\n            return parser.precpred(parserCallStack, precedence)\n        }\n\n        override\n        public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {\n            if parser.precpred(parserCallStack, precedence) {\n                return SemanticContext.Empty.Instance\n            } else {\n                return nil\n            }\n        }\n\n\n        public override func hash(into hasher: inout Hasher) {\n            hasher.combine(precedence)\n        }\n\n        override\n        public var description: String {\n            return \"{\" + String(precedence) + \">=prec}?\"\n\n        }\n    }\n\n    ///\n    /// This is the base class for semantic context \"operators\", which operate on\n    /// a collection of semantic context \"operands\".\n    ///\n    /// -  4.3\n    ///\n\n    public class Operator: SemanticContext {\n        ///\n        /// Gets the operands for the semantic context operator.\n        ///\n        /// - returns: a collection of _org.antlr.v4.runtime.atn.SemanticContext_ operands for the\n        /// operator.\n        ///\n        /// -  4.3\n        ///\n\n        public func getOperands() -> Array<SemanticContext> {\n            fatalError(#function + \" must be overridden\")\n        }\n    }\n\n    ///\n    /// A semantic context which is true whenever none of the contained contexts\n    /// is false.\n    ///\n\n    public class AND: Operator {\n        public let opnds: [SemanticContext]\n\n        public init(_ a: SemanticContext, _ b: SemanticContext) {\n            var operands = Set<SemanticContext>()\n            if let aAnd = a as? AND {\n                operands.formUnion(aAnd.opnds)\n            } else {\n                operands.insert(a)\n            }\n            if let bAnd = b as? AND {\n                operands.formUnion(bAnd.opnds)\n            } else {\n                operands.insert(b)\n            }\n\n            let precedencePredicates = SemanticContext.filterPrecedencePredicates(&operands)\n            if !precedencePredicates.isEmpty {\n                // interested in the transition with the lowest precedence\n\n                let reduced = precedencePredicates.sorted {\n                    $0.precedence < $1.precedence\n                }\n                operands.insert(reduced[0])\n            }\n\n            opnds = Array(operands)\n        }\n\n        override\n        public func getOperands() -> [SemanticContext] {\n            return opnds\n        }\n\n\n        public override func hash(into hasher: inout Hasher) {\n            hasher.combine(opnds)\n        }\n\n        ///\n        ///\n        ///\n        ///\n        /// The evaluation of predicates by this context is short-circuiting, but\n        /// unordered.\n        ///\n        override\n        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {\n            for opnd in opnds {\n                if try !opnd.eval(parser, parserCallStack) {\n                    return false\n                }\n            }\n            return true\n        }\n\n        override\n        public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {\n            var differs = false\n            var operands = [SemanticContext]()\n            for context in opnds {\n                let evaluated = try context.evalPrecedence(parser, parserCallStack)\n                //TODO differs |= (evaluated != context)\n                //differs |= (evaluated != context);\n                differs = differs || (evaluated != context)\n\n                if evaluated == nil {\n                    // The AND context is false if any element is false\n                    return nil\n                }\n                else if evaluated != SemanticContext.Empty.Instance {\n                    // Reduce the result by skipping true elements\n                    operands.append(evaluated!)\n                }\n            }\n\n            if !differs {\n                return self\n            }\n\n            return operands.reduce(SemanticContext.Empty.Instance, SemanticContext.and)\n        }\n\n        override\n        public var description: String {\n            return opnds.map({ $0.description }).joined(separator: \"&&\")\n\n        }\n    }\n\n    ///\n    /// A semantic context which is true whenever at least one of the contained\n    /// contexts is true.\n    ///\n\n    public class OR: Operator {\n        public final var opnds: [SemanticContext]\n\n        public init(_ a: SemanticContext, _ b: SemanticContext) {\n            var operands: Set<SemanticContext> = Set<SemanticContext>()\n            if let aOr = a as? OR {\n                operands.formUnion(aOr.opnds)\n            } else {\n                operands.insert(a)\n            }\n            if let bOr = b as? OR {\n                operands.formUnion(bOr.opnds)\n            } else {\n                operands.insert(b)\n            }\n\n            let precedencePredicates = SemanticContext.filterPrecedencePredicates(&operands)\n            if !precedencePredicates.isEmpty {\n                // interested in the transition with the highest precedence\n\n                let reduced = precedencePredicates.sorted {\n                    $0.precedence > $1.precedence\n                }\n                operands.insert(reduced[0])\n            }\n\n            self.opnds = Array(operands)\n        }\n\n        override\n        public func getOperands() -> [SemanticContext] {\n            return opnds\n        }\n\n        public override func hash(into hasher: inout Hasher) {\n            hasher.combine(opnds)\n        }\n\n        ///\n        ///\n        ///\n        ///\n        /// The evaluation of predicates by this context is short-circuiting, but\n        /// unordered.\n        ///\n        override\n        public func eval<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> Bool {\n            for opnd in opnds {\n                if try opnd.eval(parser, parserCallStack) {\n                    return true\n                }\n            }\n            return false\n        }\n\n        override\n        public func evalPrecedence<T>(_ parser: Recognizer<T>, _ parserCallStack: RuleContext) throws -> SemanticContext? {\n            var differs = false\n            var operands = [SemanticContext]()\n            for context in opnds {\n                let evaluated = try context.evalPrecedence(parser, parserCallStack)\n                differs = differs || (evaluated != context)\n                if evaluated == SemanticContext.Empty.Instance {\n                    // The OR context is true if any element is true\n                    return SemanticContext.Empty.Instance\n                }\n                else if let evaluated = evaluated {\n                    // Reduce the result by skipping false elements\n                    operands.append(evaluated)\n                }\n            }\n\n            if !differs {\n                return self\n            }\n\n            return operands.reduce(nil, SemanticContext.or)\n        }\n\n        override\n        public var description: String {\n            return opnds.map({ $0.description }).joined(separator: \"||\")\n\n        }\n    }\n\n    public static func and(_ a: SemanticContext?, _ b: SemanticContext?) -> SemanticContext {\n        if a == nil || a == SemanticContext.Empty.Instance {\n            return b!\n        }\n        if b == nil || b == SemanticContext.Empty.Instance {\n            return a!\n        }\n        let result: AND = AND(a!, b!)\n        if result.opnds.count == 1 {\n            return result.opnds[0]\n        }\n\n        return result\n    }\n\n    ///\n    ///\n    /// - seealso: org.antlr.v4.runtime.atn.ParserATNSimulator#getPredsForAmbigAlts\n    ///\n    public static func or(_ a: SemanticContext?, _ b: SemanticContext?) -> SemanticContext {\n        if a == nil {\n            return b!\n        }\n        if b == nil {\n            return a!\n        }\n        if a == SemanticContext.Empty.Instance || b == SemanticContext.Empty.Instance {\n            return SemanticContext.Empty.Instance\n        }\n        let result: OR = OR(a!, b!)\n        if result.opnds.count == 1 {\n            return result.opnds[0]\n        }\n\n        return result\n    }\n\n    private static func filterPrecedencePredicates(_ collection: inout Set<SemanticContext>) -> [PrecedencePredicate] {\n        let result = collection.compactMap {\n            $0 as? PrecedencePredicate\n        }\n        collection = Set<SemanticContext>(collection.filter {\n            !($0 is PrecedencePredicate)\n        })\n        return result\n    }\n}\n\npublic func ==(lhs: SemanticContext, rhs: SemanticContext) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n\n    if (lhs is SemanticContext.Predicate) && (rhs is SemanticContext.Predicate) {\n        return (lhs as! SemanticContext.Predicate) == (rhs as! SemanticContext.Predicate)\n    }\n\n    if (lhs is SemanticContext.PrecedencePredicate) && (rhs is SemanticContext.PrecedencePredicate) {\n        return (lhs as! SemanticContext.PrecedencePredicate) == (rhs as! SemanticContext.PrecedencePredicate)\n    }\n\n    if (lhs is SemanticContext.AND) && (rhs is SemanticContext.AND) {\n        return (lhs as! SemanticContext.AND) == (rhs as! SemanticContext.AND)\n    }\n\n    if (lhs is SemanticContext.OR) && (rhs is SemanticContext.OR) {\n        return (lhs as! SemanticContext.OR) == (rhs as! SemanticContext.OR)\n    }\n\n\n    return false\n}\n\npublic func ==(lhs: SemanticContext.Predicate, rhs: SemanticContext.Predicate) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    return lhs.ruleIndex == rhs.ruleIndex &&\n            lhs.predIndex == rhs.predIndex &&\n            lhs.isCtxDependent == rhs.isCtxDependent\n}\n\npublic func ==(lhs: SemanticContext.PrecedencePredicate, rhs: SemanticContext.PrecedencePredicate) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    return lhs.precedence == rhs.precedence\n}\n\n\npublic func ==(lhs: SemanticContext.AND, rhs: SemanticContext.AND) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    return lhs.opnds == rhs.opnds\n}\n\npublic func ==(lhs: SemanticContext.OR, rhs: SemanticContext.OR) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    return lhs.opnds == rhs.opnds\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/SetTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// A transition containing a set of values.\n/// \n\npublic class SetTransition: Transition, CustomStringConvertible {\n    public let set: IntervalSet\n\n    // TODO (sam): should we really allow null here?\n    public init(_ target: ATNState, _ set: IntervalSet) {\n\n        self.set = set\n        super.init(target)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.SET\n    }\n\n    override\n    public func labelIntervalSet() -> IntervalSet? {\n        return set\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return set.contains(symbol)\n    }\n\n    public var description: String {\n        return set.description\n    }\n\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/SingletonPredictionContext.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\n\npublic class SingletonPredictionContext: PredictionContext {\n    public final let parent: PredictionContext?\n    public final let returnState: Int\n\n    init(_ parent: PredictionContext?, _ returnState: Int) {\n\n        //TODO assert\n        //assert ( returnState=ATNState.INVALID_STATE_NUMBER,\"Expected: returnState!/=ATNState.INVALID_STATE_NUMBER\");\n        self.parent = parent\n        self.returnState = returnState\n\n\n        super.init(parent.map { PredictionContext.calculateHashCode($0, returnState) } ?? PredictionContext.calculateEmptyHashCode())\n    }\n\n    public static func create(_ parent: PredictionContext?, _ returnState: Int) -> SingletonPredictionContext {\n        if returnState == PredictionContext.EMPTY_RETURN_STATE && parent == nil {\n            // someone can pass in the bits of an array ctx that mean $\n            return EmptyPredictionContext.Instance\n        }\n        return SingletonPredictionContext(parent, returnState)\n    }\n\n    override\n    public func size() -> Int {\n        return 1\n    }\n\n    override\n    public func getParent(_ index: Int) -> PredictionContext? {\n        assert(index == 0, \"Expected: index==0\")\n        return parent\n    }\n\n    override\n    public func getReturnState(_ index: Int) -> Int {\n        assert(index == 0, \"Expected: index==0\")\n        return returnState\n    }\n\n\n    override\n    public var description: String {\n        let up = parent?.description ?? \"\"\n        if up.isEmpty {\n            if returnState == PredictionContext.EMPTY_RETURN_STATE {\n                return \"$\"\n            }\n            return String(returnState)\n        }\n        return String(returnState) + \" \" + up\n    }\n}\n\n\npublic func ==(lhs: SingletonPredictionContext, rhs: SingletonPredictionContext) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    if lhs.hashValue != rhs.hashValue {\n        return false\n    }\n    if lhs.returnState != rhs.returnState {\n        return false\n    }\n\n    return lhs.parent == rhs.parent\n}\n\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/StarBlockStartState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// The block that begins a closure loop.\n/// \n\npublic final class StarBlockStartState: BlockStartState {\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.STAR_BLOCK_START\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/StarLoopEntryState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic final class StarLoopEntryState: DecisionState {\n    public var loopBackState: StarLoopbackState?\n\n    /// \n    /// Indicates whether this state can benefit from a precedence DFA during SLL\n    /// decision making.\n    /// \n    /// This is a computed property that is calculated during ATN deserialization\n    /// and stored for use in _org.antlr.v4.runtime.atn.ParserATNSimulator_ and\n    /// _org.antlr.v4.runtime.ParserInterpreter_.\n    /// \n    /// - seealso: org.antlr.v4.runtime.dfa.DFA#isPrecedenceDfa()\n    /// \n    public var precedenceRuleDecision: Bool = false\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.STAR_LOOP_ENTRY\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/StarLoopbackState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic final class StarLoopbackState: ATNState {\n    public func getLoopEntryState() -> StarLoopEntryState {\n        return transition(0).target as! StarLoopEntryState\n    }\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.STAR_LOOP_BACK\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/TokensStartState.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// The Tokens rule start state linking to each lexer rule start state\n/// \n\npublic final class TokensStartState: DecisionState {\n\n    override\n    public func getStateType() -> Int {\n        return ATNState.TOKEN_START\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/Transition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// An ATN transition between any two ATN states.  Subclasses define\n/// atom, set, epsilon, action, predicate, rule transitions.\n/// \n/// This is a one way link.  It emanates from a state (usually via a list of\n/// transitions) and has a target state.\n/// \n/// Since we never have to change the ATN transitions once we construct it,\n/// we can fix these transitions as specific classes. The DFA transitions\n/// on the other hand need to update the labels as it adds transitions to\n/// the states. We'll use the term Edge for the DFA to distinguish them from\n/// ATN transitions.\n/// \n\nimport Foundation\n\npublic class Transition {\n    // constants for serialization\n    public static let EPSILON: Int = 1\n    public static let RANGE: Int = 2\n    public static let RULE: Int = 3\n    public static let PREDICATE: Int = 4\n    // e.g., {isType(input.LT(1))}?\n    public static let ATOM: Int = 5\n    public static let ACTION: Int = 6\n    public static let SET: Int = 7\n    // ~(A|B) or ~atom, wildcard, which convert to next 2\n    public static let NOT_SET: Int = 8\n    public static let WILDCARD: Int = 9\n    public static let PRECEDENCE: Int = 10\n\n\n    public let serializationNames: Array<String> =\n\n    [\"INVALID\",\n     \"EPSILON\",\n     \"RANGE\",\n     \"RULE\",\n     \"PREDICATE\",\n     \"ATOM\",\n     \"ACTION\",\n     \"SET\",\n     \"NOT_SET\",\n     \"WILDCARD\",\n     \"PRECEDENCE\"]\n\n\n    public static let serializationTypes: Dictionary<String, Int> = [\n\n            String(describing: EpsilonTransition.self): EPSILON,\n            String(describing: RangeTransition.self): RANGE,\n            String(describing: RuleTransition.self): RULE,\n            String(describing: PredicateTransition.self): PREDICATE,\n            String(describing: AtomTransition.self): ATOM,\n            String(describing: ActionTransition.self): ACTION,\n            String(describing: SetTransition.self): SET,\n            String(describing: NotSetTransition.self): NOT_SET,\n            String(describing: WildcardTransition.self): WILDCARD,\n            String(describing: PrecedencePredicateTransition.self): PRECEDENCE,\n\n\n    ]\n\n\n    /// \n    /// The target of this transition.\n    /// \n\n    public internal(set) final var target: ATNState\n\n    init(_ target: ATNState) {\n\n\n        self.target = target\n    }\n\n    public func getSerializationType() -> Int {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Determines if the transition is an \"epsilon\" transition.\n    /// \n    /// The default implementation returns `false`.\n    /// \n    /// - returns: `true` if traversing this transition in the ATN does not\n    /// consume an input symbol; otherwise, `false` if traversing this\n    /// transition consumes (matches) an input symbol.\n    /// \n    public func isEpsilon() -> Bool {\n        return false\n    }\n\n\n    public func labelIntervalSet() -> IntervalSet? {\n        return nil\n    }\n\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        fatalError(#function + \" must be overridden\")\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/atn/WildcardTransition.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\nfinal public class WildcardTransition: Transition, CustomStringConvertible {\n    public override init(_ target: ATNState) {\n        super.init(target)\n    }\n\n    override\n    public func getSerializationType() -> Int {\n        return Transition.WILDCARD\n    }\n\n    override\n    public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {\n        return symbol >= minVocabSymbol && symbol <= maxVocabSymbol\n    }\n\n    public var description: String {\n\n        return \".\"\n    }\n\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/dfa/DFA.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic class DFA: CustomStringConvertible {\n    /// \n    /// A set of all DFA states.\n    /// \n    public var states = [DFAState: DFAState]()\n\n    public var s0: DFAState?\n\n    public let decision: Int\n\n    /// \n    /// From which ATN state did we create this DFA?\n    ///\n    public let atnStartState: DecisionState\n\n    /// \n    /// `true` if this DFA is for a precedence decision; otherwise,\n    /// `false`. This is the backing field for _#isPrecedenceDfa_.\n    /// \n    private let precedenceDfa: Bool\n    \n    ///\n    /// mutex for states changes.\n    ///\n    internal private(set) var statesMutex = Mutex()\n\n    public convenience init(_ atnStartState: DecisionState) {\n        self.init(atnStartState, 0)\n    }\n\n    public init(_ atnStartState: DecisionState, _ decision: Int) {\n        self.atnStartState = atnStartState\n        self.decision = decision\n\n        if let starLoopState = atnStartState as? StarLoopEntryState, starLoopState.precedenceRuleDecision {\n            let precedenceState = DFAState(ATNConfigSet())\n            precedenceState.edges = [DFAState]()\n            precedenceState.isAcceptState = false\n            precedenceState.requiresFullContext = false\n\n            precedenceDfa = true\n            s0 = precedenceState\n        }\n        else {\n            precedenceDfa = false\n            s0 = nil\n        }\n    }\n\n    /// \n    /// Gets whether this DFA is a precedence DFA. Precedence DFAs use a special\n    /// start state _#s0_ which is not stored in _#states_. The\n    /// _org.antlr.v4.runtime.dfa.DFAState#edges_ array for this start state contains outgoing edges\n    /// supplying individual start states corresponding to specific precedence\n    /// values.\n    /// \n    /// - returns: `true` if this is a precedence DFA; otherwise,\n    /// `false`.\n    /// - seealso: org.antlr.v4.runtime.Parser#getPrecedence()\n    /// \n    public final func isPrecedenceDfa() -> Bool {\n        return precedenceDfa\n    }\n\n    /// \n    /// Get the start state for a specific precedence value.\n    /// \n    /// - parameter precedence: The current precedence.\n    /// - returns: The start state corresponding to the specified precedence, or\n    /// `null` if no start state exists for the specified precedence.\n    /// \n    /// - throws: _ANTLRError.illegalState_ if this is not a precedence DFA.\n    /// - seealso: #isPrecedenceDfa()\n    /// \n    public final func getPrecedenceStartState(_ precedence: Int) throws -> DFAState? {\n        if !isPrecedenceDfa() {\n            throw ANTLRError.illegalState(msg: \"Only precedence DFAs may contain a precedence start state.\")\n\n        }\n\n        guard let s0 = s0, let edges = s0.edges, precedence >= 0, precedence < edges.count else {\n            return nil\n        }\n\n        return edges[precedence]\n    }\n\n    /// \n    /// Set the start state for a specific precedence value.\n    /// \n    /// - parameter precedence: The current precedence.\n    /// - parameter startState: The start state corresponding to the specified\n    /// precedence.\n    /// \n    /// - throws: _ANTLRError.illegalState_ if this is not a precedence DFA.\n    /// - seealso: #isPrecedenceDfa()\n    /// \n    public final func setPrecedenceStartState(_ precedence: Int, _ startState: DFAState) throws {\n        if !isPrecedenceDfa() {\n            throw ANTLRError.illegalState(msg: \"Only precedence DFAs may contain a precedence start state.\")\n        }\n\n        guard let s0 = s0, let edges = s0.edges, precedence >= 0 else {\n            return\n        }\n\n        // synchronization on s0 here is ok. when the DFA is turned into a\n        // precedence DFA, s0 will be initialized once and not updated again\n        s0.mutex.synchronized {\n            // s0.edges is never null for a precedence DFA\n            if precedence >= edges.count {\n                let increase = [DFAState?](repeating: nil, count: (precedence + 1 - edges.count))\n                s0.edges = edges + increase\n            }\n\n            s0.edges[precedence] = startState\n        }\n    }\n\n    ///\n    /// Return a list of all states in this DFA, ordered by state number.\n    /// \n    public func getStates() -> [DFAState] {\n        var result = [DFAState](states.keys)\n\n        result = result.sorted {\n            $0.stateNumber < $1.stateNumber\n        }\n\n        return result\n    }\n\n    public var description: String {\n        return toString(Vocabulary.EMPTY_VOCABULARY)\n    }\n\n    public func toString(_ vocabulary: Vocabulary) -> String {\n        if s0 == nil {\n            return \"\"\n        }\n\n        let serializer = DFASerializer(self, vocabulary)\n        return serializer.description\n    }\n\n    public func toLexerString() -> String {\n        if s0 == nil {\n            return \"\"\n        }\n        let serializer = LexerDFASerializer(self)\n        return serializer.description\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/dfa/DFASerializer.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// A DFA walker that knows how to dump them to serialized strings.\n/// \n\npublic class DFASerializer: CustomStringConvertible {\n    private let dfa: DFA\n    private let vocabulary: Vocabulary\n\n    public init(_ dfa: DFA, _ vocabulary: Vocabulary) {\n        self.dfa = dfa\n        self.vocabulary = vocabulary\n    }\n\n    public var description: String {\n        if dfa.s0 == nil {\n            return \"\"\n        }\n        var buf = \"\"\n        let states = dfa.getStates()\n        for s in states {\n            guard let edges = s.edges else {\n                continue\n            }\n            for (i, t) in edges.enumerated() {\n                guard let t = t, t.stateNumber != Int.max else {\n                    continue\n                }\n                let edgeLabel = getEdgeLabel(i)\n                buf += getStateString(s)\n                buf += \"-\\(edgeLabel)->\"\n                buf += getStateString(t)\n                buf += \"\\n\"\n            }\n        }\n\n        return buf\n    }\n\n    internal func getEdgeLabel(_ i: Int) -> String {\n        return vocabulary.getDisplayName(i - 1)\n    }\n\n\n    internal func getStateString(_ s: DFAState) -> String {\n        let n = s.stateNumber\n\n        let s1 = s.isAcceptState ? \":\" : \"\"\n        let s2 = s.requiresFullContext ? \"^\" : \"\"\n        let baseStateStr = s1 + \"s\" + String(n) + s2\n        if s.isAcceptState {\n            if let predicates = s.predicates {\n                return baseStateStr + \"=>\\(predicates)\"\n            } else {\n                return baseStateStr + \"=>\\(s.prediction)\"\n            }\n        } else {\n            return baseStateStr\n        }\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/dfa/DFAState.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\n///\n/// A DFA state represents a set of possible ATN configurations.\n/// As Aho, Sethi, Ullman p. 117 says \"The DFA uses its state\n/// to keep track of all possible states the ATN can be in after\n/// reading each input symbol.  That is to say, after reading\n/// input a1a2..an, the DFA is in a state that represents the\n/// subset T of the states of the ATN that are reachable from the\n/// ATN's start state along some path labeled a1a2..an.\"\n/// In conventional NFA&rarr;DFA conversion, therefore, the subset T\n/// would be a bitset representing the set of states the\n/// ATN could be in.  We need to track the alt predicted by each\n/// state as well, however.  More importantly, we need to maintain\n/// a stack of states, tracking the closure operations as they\n/// jump from rule to rule, emulating rule invocations (method calls).\n/// I have to add a stack to simulate the proper lookahead sequences for\n/// the underlying LL grammar from which the ATN was derived.\n///\n/// I use a set of ATNConfig objects not simple states.  An ATNConfig\n/// is both a state (ala normal conversion) and a RuleContext describing\n/// the chain of rules (if any) followed to arrive at that state.\n///\n/// A DFA state may have multiple references to a particular state,\n/// but with different ATN contexts (with same or different alts)\n/// meaning that state was reached via a different set of rule invocations.\n///\n\npublic final class DFAState: Hashable, CustomStringConvertible {\n    public internal(set) var stateNumber = ATNState.INVALID_STATE_NUMBER\n\n    public internal(set) var configs: ATNConfigSet\n\n    ///\n    /// `edges[symbol]` points to target of symbol. Shift up by 1 so (-1)\n    /// _org.antlr.v4.runtime.Token#EOF_ maps to `edges[0]`.\n    ///\n    public internal(set) var edges: [DFAState?]!\n\n    public internal(set) var isAcceptState = false\n\n    ///\n    /// if accept state, what ttype do we match or alt do we predict?\n    /// This is set to _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_ when _#predicates_`!=null` or\n    /// _#requiresFullContext_.\n    ///\n    public internal(set) var prediction = ATN.INVALID_ALT_NUMBER\n\n    public internal(set) var lexerActionExecutor: LexerActionExecutor?\n\n    ///\n    /// Indicates that this state was created during SLL prediction that\n    /// discovered a conflict between the configurations in the state. Future\n    /// _org.antlr.v4.runtime.atn.ParserATNSimulator#execATN_ invocations immediately jumped doing\n    /// full context prediction if this field is true.\n    ///\n    public internal(set) var requiresFullContext = false\n\n    ///\n    /// During SLL parsing, this is a list of predicates associated with the\n    /// ATN configurations of the DFA state. When we have predicates,\n    /// _#requiresFullContext_ is `false` since full context prediction evaluates predicates\n    /// on-the-fly. If this is not null, then _#prediction_ is\n    /// _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_.\n    ///\n    /// We only use these for non-_#requiresFullContext_ but conflicting states. That\n    /// means we know from the context (it's $ or we don't dip into outer\n    /// context) that it's an ambiguity not a conflict.\n    ///\n    /// This list is computed by _org.antlr.v4.runtime.atn.ParserATNSimulator#predicateDFAState_.\n    ///\n\n    public internal(set) var predicates: [PredPrediction]?\n\n    ///\n    /// mutex for states changes.\n    ///\n    internal private(set) var mutex = Mutex()\n\n    ///\n    /// Map a predicate to a predicted alternative.\n    ///\n\n    public final class PredPrediction: CustomStringConvertible {\n        public let pred: SemanticContext\n        // never null; at least SemanticContext.Empty.Instance\n        public let alt: Int\n\n        public init(_ pred: SemanticContext, _ alt: Int) {\n            self.alt = alt\n            self.pred = pred\n        }\n\n        public var description: String {\n            return \"(\\(pred),\\(alt))\"\n        }\n    }\n\n    public init(_ configs: ATNConfigSet) {\n        self.configs = configs\n    }\n\n    ///\n    /// Get the set of all alts mentioned by all ATN configurations in this\n    /// DFA state.\n    ///\n    public func getAltSet() -> Set<Int>? {\n        return configs.getAltSet()\n    }\n\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(configs)\n    }\n\n    public var description: String {\n        var buf = \"\\(stateNumber):\\(configs)\"\n        if isAcceptState {\n            buf += \"=>\"\n            if let predicates = predicates {\n                buf += String(describing: predicates)\n            }\n            else {\n                buf += String(prediction)\n            }\n        }\n        return buf\n    }\n}\n\n///\n/// Two _org.antlr.v4.runtime.dfa.DFAState_ instances are equal if their ATN configuration sets\n/// are the same. This method is used to see if a state already exists.\n///\n/// Because the number of alternatives and number of ATN configurations are\n/// finite, there is a finite number of DFA states that can be processed.\n/// This is necessary to show that the algorithm terminates.\n///\n/// Cannot test the DFA state numbers here because in\n/// _org.antlr.v4.runtime.atn.ParserATNSimulator#addDFAState_ we need to know if any other state\n/// exists that has this exact set of ATN configurations. The\n/// _#stateNumber_ is irrelevant.\n///\npublic func ==(lhs: DFAState, rhs: DFAState) -> Bool {\n    if lhs === rhs {\n        return true\n    }\n    return (lhs.configs == rhs.configs)\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/dfa/LexerDFASerializer.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\npublic class LexerDFASerializer: DFASerializer {\n    public init(_ dfa: DFA) {\n        super.init(dfa, Vocabulary.EMPTY_VOCABULARY)\n    }\n\n    override\n\n    internal func getEdgeLabel(_ i: Int) -> String {\n        return \"'\\(Character(integerLiteral: i))'\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/BitSet.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  BitSet.swift\n//  Antlr.swift\n//\n//  Created by janyou on 15/9/8.\n//\n\nimport Foundation\n\n\n/// \n/// This class implements a vector of bits that grows as needed. Each\n/// component of the bit set has a `boolean` value. The\n/// bits of a `BitSet` are indexed by nonnegative integers.\n/// Individual indexed bits can be examined, set, or cleared. One\n/// `BitSet` may be used to modify the contents of another\n/// `BitSet` through logical AND, logical inclusive OR, and\n/// logical exclusive OR operations.\n/// \n/// By default, all bits in the set initially have the value\n/// `false`.\n/// \n/// Every bit set has a current size, which is the number of bits\n/// of space currently in use by the bit set. Note that the size is\n/// related to the implementation of a bit set, so it may change with\n/// implementation. The length of a bit set relates to logical length\n/// of a bit set and is defined independently of implementation.\n/// \n/// A `BitSet` is not safe for multithreaded use without\n/// external synchronization.\n/// \n/// - note: Arthur van Hoff\n/// - note: Michael McCloskey\n/// - note: Martin Buchholz\n/// - note: JDK1.0\n/// \n\npublic class BitSet: Hashable, CustomStringConvertible {\n    /// \n    /// BitSets are packed into arrays of \"words.\"  Currently a word is\n    /// a long, which consists of 64 bits, requiring 6 address bits.\n    /// The choice of word size is determined purely by performance concerns.\n    /// \n    private static let ADDRESS_BITS_PER_WORD: Int = 6\n    private static let BITS_PER_WORD: Int = 1 << ADDRESS_BITS_PER_WORD\n    private static let BIT_INDEX_MASK: Int = BITS_PER_WORD - 1\n\n    /// \n    /// Used to shift left or right for a partial word mask\n    /// \n    private static let WORD_MASK: Int64 = Int64.max\n    //0xfffffffffffffff//-1\n    // 0xffffffffffffffffL;\n\n    /// \n    /// -  bits long[]\n    /// \n    /// The bits in this BitSet.  The ith bit is stored in bits[i/64] at\n    /// bit position i % 64 (where bit position 0 refers to the least\n    /// significant bit and 63 refers to the most significant bit).\n    /// \n\n\n    /// \n    /// The internal field corresponding to the serialField \"bits\".\n    /// \n    fileprivate var words: [Int64]\n\n    /// \n    /// The number of words in the logical size of this BitSet.\n    /// \n    fileprivate var wordsInUse: Int = 0\n    //transient\n\n    /// \n    /// Whether the size of \"words\" is user-specified.  If so, we assume\n    /// the user knows what he's doing and try harder to preserve it.\n    /// \n    private var sizeIsSticky: Bool = false\n    //transient\n\n    /// \n    /// use serialVersionUID from JDK 1.0.2 for interoperability\n    /// \n    private let serialVersionUID: Int64 = 7997698588986878753\n    //L;\n\n    /// \n    /// Given a bit index, return word index containing it.\n    /// \n    private static func wordIndex(_ bitIndex: Int) -> Int {\n        return bitIndex >> ADDRESS_BITS_PER_WORD\n    }\n\n    /// \n    /// Every public method must preserve these invariants.\n    /// \n    fileprivate func checkInvariants() {\n        assert((wordsInUse == 0 || words[wordsInUse - 1] != 0), \"Expected: (wordsInUse==0||words[wordsInUse-1]!=0)\")\n        assert((wordsInUse >= 0 && wordsInUse <= words.count), \"Expected: (wordsInUse>=0&&wordsInUse<=words.length)\")\n        // print(\"\\(wordsInUse),\\(words.count),\\(words[wordsInUse])\")\n        assert((wordsInUse == words.count || words[wordsInUse] == 0), \"Expected: (wordsInUse==words.count||words[wordsInUse]==0)\")\n    }\n\n    /// \n    /// Sets the field wordsInUse to the logical size in words of the bit set.\n    /// WARNING:This method assumes that the number of words actually in use is\n    /// less than or equal to the current value of wordsInUse!\n    /// \n    private func recalculateWordsInUse() {\n        // Traverse the bitset until a used word is found\n        var i: Int = wordsInUse - 1\n        while i >= 0 {\n            if words[i] != 0 {\n                break\n            }\n            i -= 1\n        }\n\n        wordsInUse = i + 1 // The new logical size\n    }\n\n    /// \n    /// Creates a new bit set. All bits are initially `false`.\n    /// \n    public init() {\n        sizeIsSticky = false\n        words = [Int64](repeating: Int64(0), count: BitSet.wordIndex(BitSet.BITS_PER_WORD - 1) + 1)\n        //initWords(BitSet.BITS_PER_WORD);\n\n    }\n\n    /// \n    /// Creates a bit set whose initial size is large enough to explicitly\n    /// represent bits with indices in the range `0` through\n    /// `nbits-1`. All bits are initially `false`.\n    /// \n    /// - parameter  nbits: the initial size of the bit set\n    /// - throws: _ANTLRError.negativeArraySize_ if the specified initial size\n    /// is negative\n    /// \n    public init(_ nbits: Int) throws {\n        // nbits can't be negative; size 0 is OK\n\n        // words = [BitSet.wordIndex(nbits-1) + 1];\n        words = [Int64](repeating: Int64(0), count: BitSet.wordIndex(BitSet.BITS_PER_WORD - 1) + 1)\n        sizeIsSticky = true\n        if nbits < 0 {\n            throw ANTLRError.negativeArraySize(msg: \"nbits < 0:\\(nbits) \")\n\n        }\n        // initWords(nbits);\n    }\n\n    private func initWords(_ nbits: Int) {\n        // words =  [Int64](count: BitSet.wordIndex(BitSet.BITS_PER_WORD-1) + 1, repeatedValue: Int64(0));\n        //  words = [BitSet.wordIndex(nbits-1) + 1];\n    }\n\n    /// \n    /// Creates a bit set using words as the internal representation.\n    /// The last word (if there is one) must be non-zero.\n    /// \n    private init(_ words: [Int64]) {\n        self.words = words\n        self.wordsInUse = words.count\n        checkInvariants()\n    }\n\n\n    /// \n    /// Returns a new long array containing all the bits in this bit set.\n    /// \n    /// More precisely, if\n    /// `long[] longs = s.toLongArray();`\n    /// then `longs.length == (s.length()+63)/64` and\n    /// `s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)`\n    /// for all `n < 64 * longs.length`.\n    /// \n    /// - returns: a long array containing a little-endian representation\n    /// of all the bits in this bit set\n    /// \n    public func toLongArray() -> [Int64] {\n        return copyOf(words, wordsInUse)\n    }\n\n    private func copyOf(_ words: [Int64], _ newLength: Int) -> [Int64] {\n        var newWords = [Int64](repeating: Int64(0), count: newLength)\n        let length = min(words.count, newLength)\n        newWords[0 ..< length] = words[0 ..< length]\n        return newWords\n    }\n    /// \n    /// Ensures that the BitSet can hold enough words.\n    /// - parameter wordsRequired: the minimum acceptable number of words.\n    /// \n    private func ensureCapacity(_ wordsRequired: Int) {\n        if words.count < wordsRequired {\n            // Allocate larger of doubled size or required size\n            let request: Int = max(2 * words.count, wordsRequired)\n            words = copyOf(words, request)\n            sizeIsSticky = false\n        }\n    }\n\n    /// \n    /// Ensures that the BitSet can accommodate a given wordIndex,\n    /// temporarily violating the invariants.  The caller must\n    /// restore the invariants before returning to the user,\n    /// possibly using recalculateWordsInUse().\n    /// - parameter wordIndex: the index to be accommodated.\n    /// \n    private func expandTo(_ wordIndex: Int) {\n        let wordsRequired: Int = wordIndex + 1\n        if wordsInUse < wordsRequired {\n            ensureCapacity(wordsRequired)\n            wordsInUse = wordsRequired\n        }\n    }\n\n    /// \n    /// Checks that fromIndex ... toIndex is a valid range of bit indices.\n    /// \n    private static func checkRange(_ fromIndex: Int, _ toIndex: Int) throws {\n        if fromIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"fromIndex < 0: \\(fromIndex)\")\n\n        }\n\n        if toIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"toIndex < 0: \\(toIndex)\")\n\n        }\n        if fromIndex > toIndex {\n            throw ANTLRError.indexOutOfBounds(msg: \"fromInde: \\(fromIndex) > toIndex: \\(toIndex)\")\n\n        }\n    }\n\n    /// \n    /// Sets the bit at the specified index to the complement of its\n    /// current value.\n    /// \n    /// - parameter  bitIndex: the index of the bit to flip\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative\n    /// \n    public func flip(_ bitIndex: Int) throws {\n        if bitIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"bitIndex < 0: \\(bitIndex)\")\n\n\n        }\n        let index: Int = BitSet.wordIndex(bitIndex)\n        expandTo(index)\n\n        words[index] ^= (Int64(1) << Int64(bitIndex % 64))\n\n        recalculateWordsInUse()\n        checkInvariants()\n    }\n\n    /// \n    /// Sets each bit from the specified `fromIndex` (inclusive) to the\n    /// specified `toIndex` (exclusive) to the complement of its current\n    /// value.\n    /// \n    /// - parameter  fromIndex: index of the first bit to flip\n    /// - parameter  toIndex: index after the last bit to flip\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative,\n    /// or `toIndex` is negative, or `fromIndex` is\n    /// larger than `toIndex`\n    /// \n    public func flip(_ fromIndex: Int, _ toIndex: Int) throws {\n        try BitSet.checkRange(fromIndex, toIndex)\n\n        if fromIndex == toIndex {\n            return\n        }\n\n        let startWordIndex: Int = BitSet.wordIndex(fromIndex)\n        let endWordIndex: Int = BitSet.wordIndex(toIndex - 1)\n        expandTo(endWordIndex)\n\n        let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64)\n        let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)\n        //var lastWordMask : Int64  = WORD_MASK >>> Int64(-toIndex);\n        if startWordIndex == endWordIndex {\n            // Case 1: One word\n            words[startWordIndex] ^= (firstWordMask & lastWordMask)\n        } else {\n            // Case 2: Multiple words\n            // Handle first word\n            words[startWordIndex] ^= firstWordMask\n\n            // Handle intermediate words, if any\n            let start = startWordIndex + 1\n            for i in start..<endWordIndex {\n                words[i] ^= BitSet.WORD_MASK\n            }\n\n            // Handle last word\n            words[endWordIndex] ^= lastWordMask\n        }\n\n        recalculateWordsInUse()\n        checkInvariants()\n    }\n\n    /// \n    /// Sets the bit at the specified index to `true`.\n    /// \n    /// - parameter  bitIndex: a bit index\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative\n    /// \n    public func set(_ bitIndex: Int) throws {\n        if bitIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"bitIndex < 0: \\(bitIndex)\")\n\n        }\n        let index: Int = BitSet.wordIndex(bitIndex)\n        expandTo(index)\n\n        // print(words.count)\n        words[index] |= (Int64(1) << Int64(bitIndex % 64))  // Restores invariants\n\n        checkInvariants()\n    }\n\n    /// \n    /// Sets the bit at the specified index to the specified value.\n    /// \n    /// - parameter  bitIndex: a bit index\n    /// - parameter  value: a boolean value to set\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative\n    /// \n    public func set(_ bitIndex: Int, _ value: Bool) throws {\n        if value {\n            try set(bitIndex)\n        } else {\n            try clear(bitIndex)\n        }\n    }\n\n    /// \n    /// Sets the bits from the specified `fromIndex` (inclusive) to the\n    /// specified `toIndex` (exclusive) to `true`.\n    /// \n    /// - parameter  fromIndex: index of the first bit to be set\n    /// - parameter  toIndex: index after the last bit to be set\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative,\n    /// or `toIndex` is negative, or `fromIndex` is\n    /// larger than `toIndex`\n    /// \n    public func set(_ fromIndex: Int, _ toIndex: Int) throws {\n        try BitSet.checkRange(fromIndex, toIndex)\n\n        if fromIndex == toIndex {\n            return\n        }\n\n        // Increase capacity if necessary\n        let startWordIndex: Int = BitSet.wordIndex(fromIndex)\n        let endWordIndex: Int = BitSet.wordIndex(toIndex - 1)\n        expandTo(endWordIndex)\n\n        let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64)\n        let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)\n        //var lastWordMask : Int64  = WORD_MASK >>>Int64( -toIndex);\n        if startWordIndex == endWordIndex {\n            // Case 1: One word\n            words[startWordIndex] |= (firstWordMask & lastWordMask)\n        } else {\n            // Case 2: Multiple words\n            // Handle first word\n            words[startWordIndex] |= firstWordMask\n\n            // Handle intermediate words, if any\n            let start = startWordIndex + 1\n            for i in start..<endWordIndex {\n                words[i] = BitSet.WORD_MASK\n            }\n\n            // Handle last word (restores invariants)\n            words[endWordIndex] |= lastWordMask\n        }\n\n        checkInvariants()\n    }\n\n    /// \n    /// Sets the bits from the specified `fromIndex` (inclusive) to the\n    /// specified `toIndex` (exclusive) to the specified value.\n    /// \n    /// - parameter  fromIndex: index of the first bit to be set\n    /// - parameter  toIndex: index after the last bit to be set\n    /// - parameter  value: value to set the selected bits to\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative,\n    /// or `toIndex` is negative, or `fromIndex` is\n    /// larger than `toIndex`\n    /// \n    public func set(_ fromIndex: Int, _ toIndex: Int, _ value: Bool) throws {\n        if value {\n            try set(fromIndex, toIndex)\n        } else {\n            try clear(fromIndex, toIndex)\n        }\n    }\n\n    /// \n    /// Sets the bit specified by the index to `false`.\n    /// \n    /// - parameter  bitIndex: the index of the bit to be cleared\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative\n    /// -   JDK1.0\n    /// \n    public func clear(_ bitIndex: Int) throws {\n        if bitIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"bitIndex < 0: \\(bitIndex)\")\n        }\n        let index: Int = BitSet.wordIndex(bitIndex)\n        if index >= wordsInUse {\n            return\n        }\n        let option = Int64(1) << Int64(bitIndex % 64)\n        words[index] &= ~option\n\n        recalculateWordsInUse()\n        checkInvariants()\n    }\n\n    /// \n    /// Sets the bits from the specified `fromIndex` (inclusive) to the\n    /// specified `toIndex` (exclusive) to `false`.\n    /// \n    /// - parameter  fromIndex: index of the first bit to be cleared\n    /// - parameter  toIndex: index after the last bit to be cleared\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative,\n    /// or `toIndex` is negative, or `fromIndex` is\n    /// larger than `toIndex`\n    /// \n    public func clear(_ fromIndex: Int,  _ toIndex: Int) throws {\n        var toIndex = toIndex\n        try BitSet.checkRange(fromIndex, toIndex)\n\n        if fromIndex == toIndex {\n            return\n        }\n\n        let startWordIndex: Int = BitSet.wordIndex(fromIndex)\n        if startWordIndex >= wordsInUse {\n            return\n        }\n\n        var endWordIndex: Int = BitSet.wordIndex(toIndex - 1)\n        if endWordIndex >= wordsInUse {\n            toIndex = length()\n            endWordIndex = wordsInUse - 1\n        }\n\n        let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64)\n        // ar lastWordMask : Int64  = WORD_MASK >>> Int64((-toIndex);\n        let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)\n        if startWordIndex == endWordIndex {\n            // Case 1: One word\n            words[startWordIndex] &= ~(firstWordMask & lastWordMask)\n        } else {\n            // Case 2: Multiple words\n            // Handle first word\n            words[startWordIndex] &= ~firstWordMask\n\n            // Handle intermediate words, if any\n            let start = startWordIndex + 1\n            for i in start..<endWordIndex {\n                words[i] = 0\n            }\n\n            // Handle last word\n            words[endWordIndex] &= ~lastWordMask\n        }\n\n        recalculateWordsInUse()\n        checkInvariants()\n    }\n\n    /// \n    /// Sets all of the bits in this BitSet to `false`.\n    /// \n    public func clear() {\n        while wordsInUse > 0 {\n            wordsInUse -= 1\n            words[wordsInUse] = 0\n        }\n    }\n\n    /// \n    /// Returns the value of the bit with the specified index. The value\n    /// is `true` if the bit with the index `bitIndex`\n    /// is currently set in this `BitSet`; otherwise, the result\n    /// is `false`.\n    /// \n    /// - parameter  bitIndex:   the bit index\n    /// - returns: the value of the bit with the specified index\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative\n    /// \n    public func get(_ bitIndex: Int) throws -> Bool {\n        if bitIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"bitIndex < 0: \\(bitIndex)\")\n\n        }\n        checkInvariants()\n\n        let index: Int = BitSet.wordIndex(bitIndex)\n\n        return (index < wordsInUse)\n                && ((words[index] & ((Int64(1) << Int64(bitIndex % 64)))) != 0)\n    }\n\n    /// \n    /// Returns a new `BitSet` composed of bits from this `BitSet`\n    /// from `fromIndex` (inclusive) to `toIndex` (exclusive).\n    /// \n    /// - parameter  fromIndex: index of the first bit to include\n    /// - parameter  toIndex: index after the last bit to include\n    /// - returns: a new `BitSet` from a range of this `BitSet`\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if `fromIndex` is negative,\n    /// or `toIndex` is negative, or `fromIndex` is\n    /// larger than `toIndex`\n    /// \n    public func get(_ fromIndex: Int, _ toIndex: Int) throws -> BitSet {\n        var toIndex = toIndex\n        try  BitSet.checkRange(fromIndex, toIndex)\n\n        checkInvariants()\n\n        let len: Int = length()\n\n        // If no set bits in range return empty bitset\n        if len <= fromIndex || fromIndex == toIndex {\n            return try  BitSet(0)\n        }\n\n        // An optimization\n        if toIndex > len {\n            toIndex = len\n        }\n\n        let result: BitSet = try BitSet(toIndex - fromIndex)\n        let targetWords: Int = BitSet.wordIndex(toIndex - fromIndex - 1) + 1\n        var sourceIndex: Int = BitSet.wordIndex(fromIndex)\n        let wordAligned: Bool = (fromIndex & BitSet.BIT_INDEX_MASK) == 0\n\n        // Process all words but the last word\n        var i: Int = 0;\n        while i < targetWords - 1 {\n            let wordOption1: Int64 = (words[sourceIndex] >>> Int64(fromIndex))\n            let wordOption2: Int64 = (words[sourceIndex + 1] << Int64(-fromIndex % 64))\n            let wordOption = wordOption1 | wordOption2\n            result.words[i] = wordAligned ? words[sourceIndex] : wordOption\n\n            i += 1\n            sourceIndex += 1\n        }\n        // Process the last word\n        // var lastWordMask : Int64 = WORD_MASK >>> Int64(-toIndex);\n        let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)\n        let toIndexTest = ((toIndex - 1) & BitSet.BIT_INDEX_MASK)\n        let fromIndexTest = (fromIndex & BitSet.BIT_INDEX_MASK)\n\n        let wordOption1: Int64 = (words[sourceIndex] >>> Int64(fromIndex))\n        let wordOption2: Int64 = (words[sourceIndex + 1] & lastWordMask)\n        let wordOption3: Int64 = (64 + Int64(-fromIndex % 64))\n        let wordOption = wordOption1 | wordOption2 << wordOption3\n\n        let wordOption4 = (words[sourceIndex] & lastWordMask)\n        let wordOption5 = wordOption4 >>> Int64(fromIndex)\n        result.words[targetWords - 1] =\n                toIndexTest < fromIndexTest\n                ? wordOption : wordOption5\n\n        // Set wordsInUse correctly\n        result.wordsInUse = targetWords\n\n        result.recalculateWordsInUse()\n        result.checkInvariants()\n\n        return result\n    }\n\n    ///\n    /// Equivalent to nextSetBit(0), but guaranteed not to throw an exception.\n    ///\n    public func firstSetBit() -> Int {\n        return try! nextSetBit(0)\n    }\n\n    ///\n    /// Returns the index of the first bit that is set to `true`\n    /// that occurs on or after the specified starting index. If no such\n    /// bit exists then `-1` is returned.\n    /// \n    /// To iterate over the `true` bits in a `BitSet`,\n    /// use the following loop:\n    /// \n    /// `\n    /// for (int i = bs.firstSetBit(); i >= 0; i = bs.nextSetBit(i+1)) {\n    /// // operate on index i here\n    /// `}\n    /// \n    /// - parameter  fromIndex: the index to start checking from (inclusive)\n    /// - returns: the index of the next set bit, or `-1` if there\n    /// is no such bit\n    /// - throws: _ANTLRError.IndexOutOfBounds_ if the specified index is negative\n    /// \n    public func nextSetBit(_ fromIndex: Int) throws -> Int {\n        if fromIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"fromIndex < 0: \\(fromIndex)\")\n\n        }\n        checkInvariants()\n\n        var u: Int = BitSet.wordIndex(fromIndex)\n        if u >= wordsInUse {\n            return -1\n        }\n\n        var word: Int64 = words[u] & (BitSet.WORD_MASK << Int64(fromIndex % 64))\n\n        while true {\n            if word != 0 {\n                let bit = (u * BitSet.BITS_PER_WORD) + word.trailingZeroBitCount\n                return bit\n            }\n            u += 1\n            if u == wordsInUse {\n                return -1\n            }\n            word = words[u]\n        }\n    }\n\n    /// \n    /// Returns the index of the first bit that is set to `false`\n    /// that occurs on or after the specified starting index.\n    /// \n    /// - parameter  fromIndex: the index to start checking from (inclusive)\n    /// - returns: the index of the next clear bit\n    /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is negative\n    /// \n    public func nextClearBit(_ fromIndex: Int) throws -> Int {\n        // Neither spec nor implementation handle bitsets of maximal length.\n        // See 4816253.\n        if fromIndex < 0 {\n            throw ANTLRError.indexOutOfBounds(msg: \"fromIndex < 0: \\(fromIndex)\")\n\n        }\n        checkInvariants()\n\n        var u: Int = BitSet.wordIndex(fromIndex)\n        if u >= wordsInUse {\n            return fromIndex\n        }\n\n        var word: Int64 = ~words[u] & (BitSet.WORD_MASK << Int64(fromIndex % 64))\n\n        while true {\n            if word != 0 {\n                return (u * BitSet.BITS_PER_WORD) + word.trailingZeroBitCount\n            }\n            u += 1\n            if u == wordsInUse {\n                return wordsInUse * BitSet.BITS_PER_WORD\n            }\n\n            word = ~words[u]\n        }\n    }\n\n    /// \n    /// Returns the index of the nearest bit that is set to `true`\n    /// that occurs on or before the specified starting index.\n    /// If no such bit exists, or if `-1` is given as the\n    /// starting index, then `-1` is returned.\n    /// \n    /// To iterate over the `true` bits in a `BitSet`,\n    /// use the following loop:\n    /// \n    /// `\n    /// for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {\n    /// // operate on index i here\n    /// `}\n    /// \n    /// - parameter  fromIndex: the index to start checking from (inclusive)\n    /// - returns: the index of the previous set bit, or `-1` if there\n    /// is no such bit\n    /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is less\n    /// than `-1`\n    /// - note: 1.7\n    /// \n    public func previousSetBit(_ fromIndex: Int) throws -> Int {\n        if fromIndex < 0 {\n            if fromIndex == -1 {\n                return -1\n            }\n            throw ANTLRError.indexOutOfBounds(msg: \"fromIndex < -1: \\(fromIndex)\")\n\n        }\n\n        checkInvariants()\n\n        var u: Int = BitSet.wordIndex(fromIndex)\n        if u >= wordsInUse {\n            return length() - 1\n        }\n\n        var word: Int64 = words[u] & (BitSet.WORD_MASK >>> Int64(-(fromIndex + 1)))\n        while true {\n            if word != 0 {\n                return (u + 1) * BitSet.BITS_PER_WORD - 1 - word.leadingZeroBitCount\n            }\n            if u == 0 {\n                return -1\n            }\n            u -= 1\n            word = words[u]\n        }\n    }\n\n    /// \n    /// Returns the index of the nearest bit that is set to `false`\n    /// that occurs on or before the specified starting index.\n    /// If no such bit exists, or if `-1` is given as the\n    /// starting index, then `-1` is returned.\n    /// \n    /// - parameter  fromIndex: the index to start checking from (inclusive)\n    /// - returns: the index of the previous clear bit, or `-1` if there\n    /// is no such bit\n    /// - throws: _ANTLRError.IndexOutOfBounds if the specified index is less\n    /// than `-1`\n    /// - note: 1.7\n    /// \n    public func previousClearBit(_ fromIndex: Int) throws -> Int {\n        if fromIndex < 0 {\n            if fromIndex == -1 {\n                return -1\n            }\n            throw ANTLRError.indexOutOfBounds(msg: \"fromIndex < -1: \\(fromIndex)\")\n\n        }\n\n        checkInvariants()\n\n        var u: Int = BitSet.wordIndex(fromIndex)\n        if u >= wordsInUse {\n            return fromIndex\n        }\n\n        var word: Int64 = ~words[u] & (BitSet.WORD_MASK >>> Int64(-(fromIndex + 1)))\n        // var word : Int64 = ~words[u] & (WORD_MASK >>> -(fromIndex+1));\n\n        while true {\n            if word != 0 {\n                return (u + 1) * BitSet.BITS_PER_WORD - 1 - word.leadingZeroBitCount\n            }\n            if u == 0 {\n                return -1\n            }\n            u -= 1\n            word = ~words[u]\n        }\n    }\n    /// \n    /// Returns the \"logical size\" of this `BitSet`: the index of\n    /// the highest set bit in the `BitSet` plus one. Returns zero\n    /// if the `BitSet` contains no set bits.\n    /// \n    /// - returns: the logical size of this `BitSet`\n    /// \n    public func length() -> Int {\n        if wordsInUse == 0 {\n            return 0\n        }\n\n        return BitSet.BITS_PER_WORD * (wordsInUse - 1) +\n                (BitSet.BITS_PER_WORD - words[wordsInUse - 1].leadingZeroBitCount)\n    }\n\n    /// \n    /// Returns true if this `BitSet` contains no bits that are set\n    /// to `true`.\n    /// \n    /// - returns: boolean indicating whether this `BitSet` is empty\n    /// \n    public func isEmpty() -> Bool {\n        return wordsInUse == 0\n    }\n\n    /// \n    /// Returns true if the specified `BitSet` has any bits set to\n    /// `true` that are also set to `true` in this `BitSet`.\n    /// \n    /// - parameter  set: `BitSet` to intersect with\n    /// - returns: boolean indicating whether this `BitSet` intersects\n    /// the specified `BitSet`\n    /// \n    public func intersects(_ set: BitSet) -> Bool {\n        var i: Int = min(wordsInUse, set.wordsInUse) - 1\n        while i >= 0 {\n            if (words[i] & set.words[i]) != 0 {\n                return true\n            }\n            i -= 1\n        }\n        return false\n    }\n\n    /// \n    /// Returns the number of bits set to `true` in this `BitSet`.\n    /// \n    /// - returns: the number of bits set to `true` in this `BitSet`\n    /// \n    public func cardinality() -> Int {\n        var sum: Int = 0\n        for i in 0..<wordsInUse {\n            sum += words[i].nonzeroBitCount\n        }\n        return sum\n    }\n\n    /// \n    /// Performs a logical __AND__ of this target bit set with the\n    /// argument bit set. This bit set is modified so that each bit in it\n    /// has the value `true` if and only if it both initially\n    /// had the value `true` and the corresponding bit in the\n    /// bit set argument also had the value `true`.\n    /// \n    /// - parameter set: a bit set\n    /// \n    public func and(_ set: BitSet) {\n        if self == set {\n            return\n        }\n\n        while wordsInUse > set.wordsInUse {\n            wordsInUse -= 1\n            words[wordsInUse] = 0\n        }\n\n        // Perform logical AND on words in common\n        for i in 0..<wordsInUse {\n            words[i] &= set.words[i]\n        }\n\n        recalculateWordsInUse()\n        checkInvariants()\n    }\n\n    /// \n    /// Performs a logical __OR__ of this bit set with the bit set\n    /// argument. This bit set is modified so that a bit in it has the\n    /// value `true` if and only if it either already had the\n    /// value `true` or the corresponding bit in the bit set\n    /// argument has the value `true`.\n    /// \n    /// - parameter set: a bit set\n    /// \n    public func or(_ set: BitSet) {\n        if self == set {\n            return\n        }\n\n        let wordsInCommon: Int = min(wordsInUse, set.wordsInUse)\n\n        if wordsInUse < set.wordsInUse {\n            ensureCapacity(set.wordsInUse)\n            wordsInUse = set.wordsInUse\n        }\n\n        // Perform logical OR on words in common\n        for i in 0..<wordsInCommon {\n            words[i] |= set.words[i]\n        }\n\n        // Copy any remaining words\n        if wordsInCommon < set.wordsInUse {\n            words[wordsInCommon ..< wordsInUse] = set.words[wordsInCommon ..< wordsInUse]\n\n        }\n\n        // recalculateWordsInUse() is unnecessary\n        checkInvariants()\n    }\n\n    /// \n    /// Performs a logical __XOR__ of this bit set with the bit set\n    /// argument. This bit set is modified so that a bit in it has the\n    /// value `true` if and only if one of the following\n    /// statements holds:\n    /// \n    /// * The bit initially has the value `true`, and the\n    /// corresponding bit in the argument has the value `false`.\n    /// * The bit initially has the value `false`, and the\n    /// corresponding bit in the argument has the value `true`.\n    /// \n    /// - parameter  set: a bit set\n    /// \n    public func xor(_ set: BitSet) {\n        let wordsInCommon: Int = min(wordsInUse, set.wordsInUse)\n\n        if wordsInUse < set.wordsInUse {\n            ensureCapacity(set.wordsInUse)\n            wordsInUse = set.wordsInUse\n        }\n\n        // Perform logical XOR on words in common\n        for i in 0..<wordsInCommon {\n            words[i] ^= set.words[i]\n        }\n\n        // Copy any remaining words\n        if wordsInCommon < set.wordsInUse {\n            words[wordsInCommon ..< wordsInUse] = set.words[wordsInCommon ..< wordsInUse]\n\n\n        }\n\n        recalculateWordsInUse()\n        checkInvariants()\n    }\n\n    /// \n    /// Clears all of the bits in this `BitSet` whose corresponding\n    /// bit is set in the specified `BitSet`.\n    /// \n    /// - parameter  set: the `BitSet` with which to mask this\n    /// `BitSet`\n    /// \n    public func andNot(_ set: BitSet) {\n        // Perform logical (a & !b) on words in common\n        var i: Int = min(wordsInUse, set.wordsInUse) - 1\n        while i >= 0 {\n            words[i] &= ~set.words[i]\n            i -= 1\n        }\n\n        recalculateWordsInUse()\n        checkInvariants()\n    }\n\n    /// \n    /// Returns the hash code value for this bit set. The hash code depends\n    /// only on which bits are set within this `BitSet`.\n    /// \n    /// The hash code is defined to be the result of the following\n    /// calculation:\n    /// `\n    /// public int hashCode() {\n    /// long h = 1234;\n    /// long[] words = toLongArray();\n    /// for (int i = words.length; --i >= 0; )\n    /// h ^= words[i] * (i + 1);\n    /// return (int)((h >> 32) ^ h);\n    /// `}\n    /// Note that the hash code changes if the set of bits is altered.\n    /// \n    /// - returns: the hash code value for this bit set\n    /// \n    private var hashCode: Int {\n        var h: Int64 = 1234\n        var i: Int = wordsInUse\n        i -= 1\n        while i >= 0 {\n             h ^= words[i] * Int64(i + 1)\n             i -= 1\n        }\n\n        return Int(Int32((h >> 32) ^ h))\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(hashCode)\n    }\n\n    /// \n    /// Returns the number of bits of space actually in use by this\n    /// `BitSet` to represent bit values.\n    /// The maximum element in the set is the size - 1st element.\n    /// \n    /// - returns: the number of bits currently in this bit set\n    /// \n    public func size() -> Int {\n        return words.count * BitSet.BITS_PER_WORD\n    }\n\n\n\n\n\n    /// \n    /// Attempts to reduce internal storage used for the bits in this bit set.\n    /// Calling this method may, but is not required to, affect the value\n    /// returned by a subsequent call to the _#size()_ method.\n    /// \n    private func trimToSize() {\n        if wordsInUse != words.count {\n            words = copyOf(words, wordsInUse)\n            checkInvariants()\n        }\n    }\n\n\n    /// \n    /// Returns a string representation of this bit set. For every index\n    /// for which this `BitSet` contains a bit in the set\n    /// state, the decimal representation of that index is included in\n    /// the result. Such indices are listed in order from lowest to\n    /// highest, separated by \",&nbsp;\" (a comma and a space) and\n    /// surrounded by braces, resulting in the usual mathematical\n    /// notation for a set of integers.\n    /// \n    /// Example:\n    /// \n    /// `BitSet drPepper = new BitSet();`\n    /// Now `drPepper.description` returns `\"{}\"`.\n    /// \n    /// `drPepper.set(2);`\n    /// Now `drPepper.description` returns `\"{2}\"`.\n    /// \n    /// `drPepper.set(4);`\n    /// `drPepper.set(10);`\n    /// Now `drPepper.description` returns `\"{2, 4, 10}\"`.\n    /// \n    /// - returns: a string representation of this bit set\n    /// \n    public var description: String {\n        checkInvariants()\n\n        //let numBits: Int = (wordsInUse > 128) ?\n        // cardinality() : wordsInUse * BitSet.BITS_PER_WORD\n        var b = \"{\"\n        var i = firstSetBit()\n        if i != -1 {\n            b += String(i)\n            i = try! nextSetBit(i + 1)\n            while i >= 0 {\n                let endOfRun = try! nextClearBit(i)\n                repeat {\n                    b += \", \\(i)\"\n                    i += 1\n                } while i < endOfRun\n                i = try! nextSetBit(i + 1)\n            }\n        }\n        b += \"}\"\n        return b\n\n    }\n}\n\npublic func ==(lhs: BitSet, rhs: BitSet) -> Bool {\n\n    if lhs === rhs {\n        return true\n    }\n\n\n    lhs.checkInvariants()\n    rhs.checkInvariants()\n\n    if lhs.wordsInUse != rhs.wordsInUse {\n        return false\n    }\n\n    // Check words in use by both BitSets\n    let length = lhs.wordsInUse\n    for i in 0..<length {\n        if lhs.words[i] != rhs.words[i] {\n            return false\n        }\n    }\n\n    return true\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/DoubleKeyMap.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n\n/// \n/// Sometimes we need to map a key to a value but key is two pieces of data.\n/// This nested hash table saves creating a single key each time we access\n/// map; avoids mem creation.\n///\npublic struct DoubleKeyMap<Key1: Hashable, Key2: Hashable, Value> {\n    private var data = [Key1: [Key2: Value]]()\n\n    @discardableResult\n    public mutating func put(_ k1: Key1, _ k2: Key2, _ v: Value) -> Value? {\n\n        let prev: Value?\n        if var data2 = data[k1] {\n            prev = data2[k2]\n            data2[k2] = v\n            data[k1] = data2\n        }\n        else {\n            prev = nil\n            let data2 = [\n                k2: v\n            ]\n            data[k1] = data2\n        }\n        return prev\n    }\n\n    public func get(_ k1: Key1, _ k2: Key2) -> Value? {\n        return data[k1]?[k2]\n    }\n\n    public func get(_ k1: Key1) -> [Key2: Value]? {\n        return data[k1]\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/IntSet.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// A generic set of integers.\n/// \n/// - seealso: org.antlr.v4.runtime.misc.IntervalSet\n/// \n\npublic protocol IntSet {\n    /// \n    /// Adds the specified value to the current set.\n    /// \n    /// - parameter el: the value to add\n    /// \n    /// - throws: _ANTLRError.illegalState_ if the current set is read-only\n    /// \n    func add(_ el: Int) throws\n\n    /// \n    /// Modify the current _org.antlr.v4.runtime.misc.IntSet_ object to contain all elements that are\n    /// present in itself, the specified `set`, or both.\n    /// \n    /// - parameter set: The set to add to the current set. A `null` argument is\n    /// treated as though it were an empty set.\n    /// - returns: `this` (to support chained calls)\n    /// \n    /// - throws: _ANTLRError.illegalState_ if the current set is read-only\n    /// \n    func addAll(_ set: IntSet?) throws -> IntSet\n\n    /// \n    /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are\n    /// present in both the current set and the specified set `a`.\n    /// \n    /// - parameter a: The set to intersect with the current set. A `null`\n    /// argument is treated as though it were an empty set.\n    /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the intersection of the\n    /// current set and `a`. The value `null` may be returned in\n    /// place of an empty result set.\n    /// \n    func and(_ a: IntSet?) -> IntSet?\n\n    /// \n    /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are\n    /// present in `elements` but not present in the current set. The\n    /// following expressions are equivalent for input non-null _org.antlr.v4.runtime.misc.IntSet_\n    /// instances `x` and `y`.\n    /// \n    /// * `x.complement(y)`\n    /// *`y.subtract(x)`\n    /// \n    /// - parameter elements: The set to compare with the current set. A `null`\n    /// argument is treated as though it were an empty set.\n    /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the elements present in\n    /// `elements` but not present in the current set. The value\n    /// `null` may be returned in place of an empty result set.\n    /// \n    func complement(_ elements: IntSet?) -> IntSet?\n\n    /// \n    /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are\n    /// present in the current set, the specified set `a`, or both.\n    /// \n    /// \n    /// This method is similar to _#addAll(org.antlr.v4.runtime.misc.IntSet)_, but returns a new\n    /// _org.antlr.v4.runtime.misc.IntSet_ instance instead of modifying the current set.\n    /// \n    /// - parameter a: The set to union with the current set. A `null` argument\n    /// is treated as though it were an empty set.\n    /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the union of the current\n    /// set and `a`. The value `null` may be returned in place of an\n    /// empty result set.\n    /// \n    func or(_ a: IntSet) -> IntSet\n\n    /// \n    /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are\n    /// present in the current set but not present in the input set `a`.\n    /// The following expressions are equivalent for input non-null\n    /// _org.antlr.v4.runtime.misc.IntSet_ instances `x` and `y`.\n    /// \n    /// * `y.subtract(x)`\n    /// * `x.complement(y)`\n    /// \n    /// - parameter a: The set to compare with the current set. A `null`\n    /// argument is treated as though it were an empty set.\n    /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the elements present in\n    /// `elements` but not present in the current set. The value\n    /// `null` may be returned in place of an empty result set.\n    /// \n    func subtract(_ a: IntSet?) -> IntSet\n\n    /// \n    /// Return the total number of elements represented by the current set.\n    /// \n    /// - returns: the total number of elements represented by the current set,\n    /// regardless of the manner in which the elements are stored.\n    /// \n    func size() -> Int\n\n    /// \n    /// Returns `true` if this set contains no elements.\n    /// \n    /// - returns: `true` if the current set contains no elements; otherwise,\n    /// `false`.\n    /// \n    func isNil() -> Bool\n\n    /// \n    /// Returns the single value contained in the set, if _#size_ is 1;\n    /// otherwise, returns _org.antlr.v4.runtime.Token#INVALID_TYPE_.\n    /// \n    /// - returns: the single value contained in the set, if _#size_ is 1;\n    /// otherwise, returns _org.antlr.v4.runtime.Token#INVALID_TYPE_.\n    /// \n    func getSingleElement() -> Int\n\n    /// \n    /// Returns `true` if the set contains the specified element.\n    /// \n    /// - parameter el: The element to check for.\n    /// - returns: `true` if the set contains `el`; otherwise `false`.\n    /// \n    func contains(_ el: Int) -> Bool\n\n    /// \n    /// Removes the specified value from the current set. If the current set does\n    /// not contain the element, no changes are made.\n    /// \n    /// - parameter el: the value to remove\n    /// \n    /// - throws: _ANTLRError.illegalState_ if the current set is read-only\n    /// \n    func remove(_ el: Int) throws\n\n    /// \n    /// Return a list containing the elements represented by the current set. The\n    /// list is returned in ascending numerical order.\n    /// \n    /// - returns: A list containing all element present in the current set, sorted\n    /// in ascending numerical order.\n    /// \n    func toList() -> [Int]\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/InterpreterDataReader.swift",
    "content": "/// Copyright (c) 2021 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\n// A class to read plain text interpreter data produced by ANTLR.\npublic class InterpreterDataReader {\n    \n    let filePath:String,\n        atn:ATN,\n        vocabulary:Vocabulary,\n        ruleNames:[String],\n        channelNames:[String], // Only valid for lexer grammars.\n        modeNames:[String] // ditto\n    \n    /**\n     * The structure of the data file is line based with empty lines\n     * separating the different parts. For lexers the layout is:\n     * token literal names:\n     * ...\n     *\n     * token symbolic names:\n     * ...\n     *\n     * rule names:\n     * ...\n     *\n     * channel names:\n     * ...\n     *\n     * mode names:\n     * ...\n     *\n     * atn:\n     * <a single line with comma separated int values> enclosed in a pair of squared brackets.\n     *\n     * Data for a parser does not contain channel and mode names.\n     */\n    enum Part {\n        case partName\n        case tokenLiteralNames\n        case tokenSymbolicNames\n        case ruleNames\n        case channelNames\n        case modeNames\n        case atn\n    }\n\n    enum Error: Swift.Error {\n        case dataError(String)\n    }\n    \n    public init(_ filePath:String) throws {\n        self.filePath = filePath\n        let contents = try String(contentsOfFile: filePath, encoding: String.Encoding.utf8)\n        var part = Part.partName,\n            literalNames = [String](),\n            symbolicNames = [String](),\n            ruleNames = [String](),\n            channelNames = [String](),\n            modeNames = [String](),\n            atnText = [Substring](),\n            fail:Error?\n        contents.enumerateLines { (line,stop) in\n            // throws have to be moved outside the enumerateLines block\n            if line == \"\" {\n                part = .partName\n            }\n            switch part {\n            case .partName:\n                switch line {\n                case \"token literal names:\":\n                    part = .tokenLiteralNames\n                case \"token symbolic names:\":\n                    part = .tokenSymbolicNames\n                case \"rule names:\":\n                    part = .ruleNames\n                case \"channel names:\":\n                    part = .channelNames\n                case \"mode names:\":\n                    part = .modeNames\n                case \"atn:\":\n                    part = .atn\n                case \"\":\n                    break\n                default:\n                    fail = Error.dataError(\"Unrecognized interpreter data part at \"+line)\n                }\n            case .tokenLiteralNames:\n                literalNames.append((line == \"null\") ? \"\" : line)\n            case .tokenSymbolicNames:\n                symbolicNames.append((line == \"null\") ? \"\" : line)\n            case .ruleNames:\n                ruleNames.append(line)\n            case .channelNames:\n                channelNames.append(line)\n            case .modeNames:\n                modeNames.append(line)\n            case .atn:\n                if line.prefix(1) == \"[\" && line.suffix(1) == \"]\" {\n                    atnText = line.dropFirst().dropLast().split(separator:\",\")\n                } else {\n                    fail = Error.dataError(\"Missing bracket(s) at \"+line)\n                }\n                part = .partName\n            }\n        }\n        if let fail = fail { throw fail }\n        vocabulary = Vocabulary(literalNames, symbolicNames)\n        self.ruleNames = ruleNames\n        self.channelNames = channelNames\n        self.modeNames = modeNames\n        let atnSerialized = atnText.map{Int($0.trimmingCharacters(in:.whitespaces))!}\n        atn = try ATNDeserializer().deserialize(atnSerialized)\n    }\n        \n    public func createLexer(input: CharStream)throws->LexerInterpreter {\n        return try LexerInterpreter(filePath,\n                                    vocabulary,\n                                    ruleNames,\n                                    channelNames,\n                                    modeNames,\n                                    atn,\n                                    input)\n    }\n    \n    public func createParser(input: TokenStream)throws->ParserInterpreter {\n        return try ParserInterpreter(filePath,\n                                    vocabulary,\n                                    ruleNames,\n                                    atn,\n                                    input)\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/Interval.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// An immutable inclusive interval a..b\n/// \n\npublic struct Interval: Hashable {\n   public static let INVALID: Interval = Interval(-1, -2)\n\n    public var a: Int\n    public var b: Int\n\n    public init(_ a: Int, _ b: Int) {\n        self.a = a\n        self.b = b\n    }\n\n    /// \n    /// Interval objects are used readonly so share all with the\n    /// same single value a==b up to some max size.  Use an array as a perfect hash.\n    /// Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new\n    /// Interval object with a..a in it.  On Java.g4, 218623 IntervalSets\n    /// have a..a (set with 1 element).\n    /// \n    public static func of(_ a: Int, _ b: Int) -> Interval {\n        return Interval(a, b)\n    }\n\n    /// \n    /// return number of elements between a and b inclusively. x..x is length 1.\n    /// if b &lt; a, then length is 0.  9..10 has length 2.\n    /// \n    public func length() -> Int {\n        if b < a {\n            return 0\n        }\n        return b - a + 1\n    }\n\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(a)\n        hasher.combine(b)\n    }\n\n    ///\n    /// Does this start completely before other? Disjoint\n    /// \n    public func startsBeforeDisjoint(_ other: Interval) -> Bool {\n        return self.a < other.a && self.b < other.a\n    }\n\n    /// \n    /// Does this start at or before other? Nondisjoint\n    /// \n    public func startsBeforeNonDisjoint(_ other: Interval) -> Bool {\n        return self.a <= other.a && self.b >= other.a\n    }\n\n    /// \n    /// Does this.a start after other.b? May or may not be disjoint\n    /// \n    public func startsAfter(_ other: Interval) -> Bool {\n        return self.a > other.a\n    }\n\n    /// \n    /// Does this start completely after other? Disjoint\n    /// \n    public func startsAfterDisjoint(_ other: Interval) -> Bool {\n        return self.a > other.b\n    }\n\n    /// \n    /// Does this start after other? NonDisjoint\n    /// \n    public func startsAfterNonDisjoint(_ other: Interval) -> Bool {\n        return self.a > other.a && self.a <= other.b // this.b>=other.b implied\n    }\n\n    /// \n    /// Are both ranges disjoint? I.e., no overlap?\n    /// \n    public func disjoint(_ other: Interval) -> Bool {\n        return startsBeforeDisjoint(other) || startsAfterDisjoint(other)\n    }\n\n    /// \n    /// Are two intervals adjacent such as 0..41 and 42..42?\n    /// \n    public func adjacent(_ other: Interval) -> Bool {\n        return self.a == other.b + 1 || self.b == other.a - 1\n    }\n\n    public func properlyContains(_ other: Interval) -> Bool {\n        return other.a >= self.a && other.b <= self.b\n    }\n\n    /// \n    /// Return the interval computed from combining this and other\n    /// \n    public func union(_ other: Interval) -> Interval {\n        return Interval.of(min(a, other.a), max(b, other.b))\n    }\n\n    /// \n    /// Return the interval in common between this and o\n    /// \n    public func intersection(_ other: Interval) -> Interval {\n        return Interval.of(max(a, other.a), min(b, other.b))\n    }\n\n    /// \n    /// Return the interval with elements from this not in other;\n    /// other must not be totally enclosed (properly contained)\n    /// within this, which would result in two disjoint intervals\n    /// instead of the single one returned by this method.\n    /// \n    public func differenceNotProperlyContained(_ other: Interval) -> Interval? {\n        var diff: Interval? = nil\n        // other.a to left of this.a (or same)\n        if other.startsBeforeNonDisjoint(self) {\n            diff = Interval.of(max(self.a, other.b + 1),\n                    self.b)\n        }\n\n                // other.a to right of this.a\n        else {\n            if other.startsAfterNonDisjoint(self) {\n                diff = Interval.of(self.a, other.a - 1)\n            }\n        }\n        return diff\n    }\n\n\n   public var description: String {\n        return \"\\(a)..\\(b)\"\n    }\n}\n\npublic func ==(lhs: Interval, rhs: Interval) -> Bool {\n    return lhs.a == rhs.a && lhs.b == rhs.b\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/IntervalSet.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n\n/// \n/// This class implements the _org.antlr.v4.runtime.misc.IntSet_ backed by a sorted array of\n/// non-overlapping intervals. It is particularly efficient for representing\n/// large collections of numbers, where the majority of elements appear as part\n/// of a sequential range of numbers that are all part of the set. For example,\n/// the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }.\n/// \n/// \n/// This class is able to represent sets containing any combination of values in\n/// the range _Integer#MIN_VALUE_ to _Integer#MAX_VALUE_\n/// (inclusive).\n/// \n\npublic class IntervalSet: IntSet, Hashable, CustomStringConvertible {\n    public static let COMPLETE_CHAR_SET: IntervalSet =\n    {\n        let set = IntervalSet.of(Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE)\n        set.makeReadonly()\n        return set\n    }()\n\n    public static let EMPTY_SET: IntervalSet = {\n        let set = IntervalSet()\n        set.makeReadonly()\n        return set\n    }()\n\n\n    /// \n    /// The list of sorted, disjoint intervals.\n    /// \n    internal var intervals: [Interval]\n\n    internal var readonly = false\n\n    public init(_ intervals: [Interval]) {\n        self.intervals = intervals\n    }\n\n    public convenience init(_ set: IntervalSet) {\n        self.init()\n        try! addAll(set)\n    }\n\n    public init(_ els: Int...) {\n        if els.isEmpty {\n            intervals = [Interval]() // most sets are 1 or 2 elements\n        } else {\n            intervals = [Interval]()\n            for e in els {\n                try! add(e)\n            }\n        }\n    }\n\n    ///\n    /// Create a set with all ints within range [a..b] (inclusive)\n    /// \n    public static func of(_ a: Int, _ b: Int) -> IntervalSet {\n        let s = IntervalSet()\n        try! s.add(a, b)\n        return s\n    }\n\n    public func clear() throws {\n        if readonly {\n            throw ANTLRError.illegalState(msg: \"can't alter readonly IntervalSet\")\n        }\n        intervals.removeAll()\n    }\n\n    /// \n    /// Add a single element to the set.  An isolated element is stored\n    /// as a range el..el.\n    /// \n\n    public func add(_ el: Int) throws {\n        if readonly {\n            throw ANTLRError.illegalState(msg: \"can't alter readonly IntervalSet\")\n        }\n        try! add(el, el)\n    }\n\n    /// \n    /// Add interval; i.e., add all integers from a to b to set.\n    /// If b&lt;a, do nothing.\n    /// Keep list in sorted order (by left range value).\n    /// If overlap, combine ranges.  For example,\n    /// If this is {1..5, 10..20}, adding 6..7 yields\n    /// {1..5, 6..7, 10..20}.  Adding 4..8 yields {1..8, 10..20}.\n    /// \n    public func add(_ a: Int, _ b: Int) throws {\n        try add(Interval.of(a, b))\n    }\n\n    // copy on write so we can cache a..a intervals and sets of that\n    internal func add(_ addition: Interval) throws {\n        if readonly {\n            throw ANTLRError.illegalState(msg: \"can't alter readonly IntervalSet\")\n        }\n        if addition.b < addition.a {\n            return\n        }\n        // find position in list\n        // Use iterators as we modify list in place\n        var i = 0\n\n        while i < intervals.count {\n\n            let r = intervals[i]\n            if addition == r {\n                return\n            }\n            if addition.adjacent(r) || !addition.disjoint(r) {\n                // next to each other, make a single larger interval\n                let bigger = addition.union(r)\n                //iter.set(bigger);\n                intervals[i] = bigger\n                // make sure we didn't just create an interval that\n                // should be merged with next interval in list\n                while i < intervals.count - 1 {\n                    i += 1\n                    let next = intervals[i]\n                    if !bigger.adjacent(next) && bigger.disjoint(next) {\n                        break\n                    }\n\n                    // if we bump up against or overlap next, merge\n                    /// \n                    /// iter.remove();   // remove this one\n                    /// iter.previous(); // move backwards to what we just set\n                    /// iter.set(bigger.union(next)); // set to 3 merged ones\n                    /// iter.next(); // first call to next after previous duplicates the resul\n                    /// \n                    intervals.remove(at: i)\n                    i -= 1\n                    intervals[i] = bigger.union(next)\n                }\n                return\n            }\n            if addition.startsBeforeDisjoint(r) {\n                // insert before r\n                intervals.insert(addition, at: i)\n                return\n            }\n            // if disjoint and after r, a future iteration will handle it\n\n            i += 1\n        }\n        // ok, must be after last interval (and disjoint from last interval)\n        // just add it\n        intervals.append(addition)\n    }\n\n    /// \n    /// combine all sets in the array returned the or'd value\n    /// \n    public func or(_ sets: [IntervalSet]) -> IntSet {\n        let r = IntervalSet()\n        for s in sets {\n            try! r.addAll(s)\n        }\n        return r\n    }\n\n    @discardableResult\n    public func addAll(_ set: IntSet?) throws -> IntSet {\n\n        guard let set = set else {\n             return self\n        }\n        if let other = set as? IntervalSet {\n            // walk set and add each interval\n            for interval in other.intervals {\n                try add(interval)\n            }\n        } else {\n            let setList = set.toList()\n            for value in setList {\n                try add(value)\n            }\n        }\n\n        return self\n    }\n\n    public func complement(_ minElement: Int, _ maxElement: Int) -> IntSet? {\n        return complement(IntervalSet.of(minElement, maxElement))\n    }\n\n    ///\n    /// \n    /// \n\n    public func complement(_ vocabulary: IntSet?) -> IntSet? {\n        guard let vocabulary = vocabulary, !vocabulary.isNil() else {\n            return nil  // nothing in common with null set\n        }\n        var vocabularyIS: IntervalSet\n        if let vocabulary = vocabulary as? IntervalSet {\n            vocabularyIS = vocabulary\n        } else {\n            vocabularyIS = IntervalSet()\n            try! vocabularyIS.addAll(vocabulary)\n        }\n\n        return vocabularyIS.subtract(self)\n    }\n\n\n    public func subtract(_ a: IntSet?) -> IntSet {\n        guard let a = a, !a.isNil() else {\n            return IntervalSet(self)\n        }\n        if let a = a as? IntervalSet {\n            return subtract(self, a)\n        }\n\n        let other = IntervalSet()\n        try! other.addAll(a)\n        return subtract(self, other)\n    }\n\n    /// \n    /// Compute the set difference between two interval sets. The specific\n    /// operation is `left - right`. If either of the input sets is\n    /// `null`, it is treated as though it was an empty set.\n    /// \n\n    public func subtract(_ left: IntervalSet?, _ right: IntervalSet?) -> IntervalSet {\n\n        guard let left = left, !left.isNil() else {\n            return IntervalSet()\n        }\n\n        let result = IntervalSet(left)\n\n        guard let right = right, !right.isNil() else {\n            // right set has no elements; just return the copy of the current set\n            return result\n        }\n        var resultI = 0\n        var rightI = 0\n        while resultI < result.intervals.count && rightI < right.intervals.count {\n            let resultInterval = result.intervals[resultI]\n            let rightInterval = right.intervals[rightI]\n\n            // operation: (resultInterval - rightInterval) and update indexes\n\n            if rightInterval.b < resultInterval.a {\n                rightI += 1\n                continue\n            }\n\n            if rightInterval.a > resultInterval.b {\n                resultI += 1\n                continue\n            }\n\n            var beforeCurrent: Interval? = nil\n            var afterCurrent: Interval? = nil\n            if rightInterval.a > resultInterval.a {\n                beforeCurrent = Interval(resultInterval.a, rightInterval.a - 1)\n            }\n\n            if rightInterval.b < resultInterval.b {\n                afterCurrent = Interval(rightInterval.b + 1, resultInterval.b)\n            }\n\n            if let beforeCurrent = beforeCurrent {\n                if let afterCurrent = afterCurrent {\n                    // split the current interval into two\n                    result.intervals[resultI] = beforeCurrent\n                    result.intervals.insert(afterCurrent, at: resultI + 1)\n                    resultI += 1\n                    rightI += 1\n                    continue\n                } else {\n                    // replace the current interval\n                    result.intervals[resultI] = beforeCurrent\n                    resultI += 1\n                    continue\n                }\n            } else {\n                if let afterCurrent = afterCurrent {\n                    // replace the current interval\n                    result.intervals[resultI] = afterCurrent\n                    rightI += 1\n                    continue\n                } else {\n                    // remove the current interval (thus no need to increment resultI)\n                    result.intervals.remove(at: resultI)\n                    //result.intervals.remove(resultI);\n                    continue\n                }\n            }\n        }\n\n        // If rightI reached right.intervals.size(), no more intervals to subtract from result.\n        // If resultI reached result.intervals.size(), we would be subtracting from an empty set.\n        // Either way, we are done.\n        return result\n    }\n\n\n    public func or(_ a: IntSet) -> IntSet {\n        let o = IntervalSet()\n        try! o.addAll(self)\n        try! o.addAll(a)\n        return o\n    }\n\n    /// \n    /// \n    /// \n\n    public func and(_ other: IntSet?) -> IntSet? {\n        if other == nil {\n            return nil // nothing in common with null set\n        }\n\n        let myIntervals = self.intervals\n        let theirIntervals = (other as! IntervalSet).intervals\n        var intersection: IntervalSet? = nil\n        let mySize = myIntervals.count\n        let theirSize = theirIntervals.count\n        var i = 0\n        var j = 0\n        // iterate down both interval lists looking for nondisjoint intervals\n        while i < mySize && j < theirSize {\n            let mine = myIntervals[i]\n            let theirs = theirIntervals[j]\n\n            if mine.startsBeforeDisjoint(theirs) {\n                // move this iterator looking for interval that might overlap\n                i += 1\n            } else {\n                if theirs.startsBeforeDisjoint(mine) {\n                    // move other iterator looking for interval that might overlap\n                    j += 1\n                } else {\n                    if mine.properlyContains(theirs) {\n                        // overlap, add intersection, get next theirs\n                        if intersection == nil {\n                            intersection = IntervalSet()\n                        }\n\n                        try! intersection!.add(mine.intersection(theirs))\n                        j += 1\n                    } else {\n                        if theirs.properlyContains(mine) {\n                            // overlap, add intersection, get next mine\n                            if intersection == nil {\n                                intersection = IntervalSet()\n                            }\n                            try! intersection!.add(mine.intersection(theirs))\n                            i += 1\n                        } else {\n                            if !mine.disjoint(theirs) {\n                                // overlap, add intersection\n                                if intersection == nil {\n                                    intersection = IntervalSet()\n                                }\n                                try! intersection!.add(mine.intersection(theirs))\n                                // Move the iterator of lower range [a..b], but not\n                                // the upper range as it may contain elements that will collide\n                                // with the next iterator. So, if mine=[0..115] and\n                                // theirs=[115..200], then intersection is 115 and move mine\n                                // but not theirs as theirs may collide with the next range\n                                // in thisIter.\n                                // move both iterators to next ranges\n                                if mine.startsAfterNonDisjoint(theirs) {\n                                    j += 1\n                                } else {\n                                    if theirs.startsAfterNonDisjoint(mine) {\n                                        i += 1\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        if intersection == nil {\n            return IntervalSet()\n        }\n        return intersection\n    }\n\n    /// \n    /// \n    /// \n\n    public func contains(_ el: Int) -> Bool {\n        for interval in intervals {\n            let a = interval.a\n            let b = interval.b\n            if el < a {\n                break // list is sorted and el is before this interval; not here\n            }\n            if el >= a && el <= b {\n                return true // found in this interval\n            }\n        }\n        return false\n    }\n\n    /// \n    /// \n    /// \n\n    public func isNil() -> Bool {\n        return intervals.isEmpty\n    }\n\n    /// \n    /// \n    /// \n\n    public func getSingleElement() -> Int {\n        if intervals.count == 1 {\n            let interval = intervals[0]\n            if interval.a == interval.b {\n                return interval.a\n            }\n        }\n        return CommonToken.INVALID_TYPE\n    }\n\n    /// \n    /// Returns the maximum value contained in the set.\n    /// \n    /// - returns: the maximum value contained in the set. If the set is empty, this\n    /// method returns _org.antlr.v4.runtime.Token#INVALID_TYPE_.\n    /// \n    public func getMaxElement() -> Int {\n        if isNil() {\n            return CommonToken.INVALID_TYPE\n        }\n        let last = intervals[intervals.count - 1]\n        return last.b\n    }\n\n    /// \n    /// Returns the minimum value contained in the set.\n    /// \n    /// - returns: the minimum value contained in the set. If the set is empty, this\n    /// method returns _org.antlr.v4.runtime.Token#INVALID_TYPE_.\n    /// \n    public func getMinElement() -> Int {\n        if isNil() {\n            return CommonToken.INVALID_TYPE\n        }\n\n        return intervals[0].a\n    }\n\n    /// \n    /// Return a list of Interval objects.\n    /// \n    public func getIntervals() -> [Interval] {\n        return intervals\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        for interval in intervals {\n            hasher.combine(interval.a)\n            hasher.combine(interval.b)\n        }\n    }\n\n    /// \n    /// Are two IntervalSets equal?  Because all intervals are sorted\n    /// and disjoint, equals is a simple linear walk over both lists\n    /// to make sure they are the same.  Interval.equals() is used\n    /// by the List.equals() method to check the ranges.\n    /// \n\n    /// \n    /// public func equals(obj : AnyObject) -> Bool {\n    /// if ( obj==nil || !(obj is IntervalSet) ) {\n    /// return false;\n    /// }\n    /// var other : IntervalSet = obj as! IntervalSet;\n    /// return self.intervals.equals(other.intervals);\n    /// \n\n    public var description: String {\n        return toString(false)\n    }\n\n    public func toString(_ elemAreChar: Bool) -> String {\n        if intervals.isEmpty {\n            return \"{}\"\n        }\n\n        let selfSize = size()\n\n        var buf = \"\"\n\n        if selfSize > 1 {\n            buf += \"{\"\n        }\n        var first = true\n        for interval in intervals {\n            if !first {\n                buf += \", \"\n            }\n            first = false\n\n            let a = interval.a\n            let b = interval.b\n            if a == b {\n                if a == CommonToken.EOF {\n                    buf += \"<EOF>\"\n                }\n                else if elemAreChar {\n                    buf += \"'\\(a)'\"\n                }\n                else {\n                    buf += \"\\(a)\"\n                }\n            }\n            else if elemAreChar {\n                buf += \"'\\(a)'..'\\(b)'\"\n            }\n            else {\n                buf += \"\\(a)..\\(b)\"\n            }\n        }\n\n        if selfSize > 1 {\n            buf += \"}\"\n        }\n\n        return buf\n    }\n\n    public func toString(_ vocabulary: Vocabulary) -> String {\n        if intervals.isEmpty {\n            return \"{}\"\n        }\n\n        let selfSize = size()\n\n        var buf = \"\"\n\n        if selfSize > 1 {\n            buf += \"{\"\n        }\n\n        var first = true\n        for interval in intervals {\n            if !first {\n                buf += \", \"\n            }\n            first = false\n\n            let a = interval.a\n            let b = interval.b\n            if a == b {\n                buf += elementName(vocabulary, a)\n            }\n            else {\n                for i in a...b {\n                    if i > a {\n                        buf += \", \"\n                    }\n                    buf += elementName(vocabulary, i)\n                }\n            }\n        }\n\n        if selfSize > 1 {\n            buf += \"}\"\n        }\n\n        return buf\n    }\n\n    internal func elementName(_ vocabulary: Vocabulary, _ a: Int) -> String {\n        if a == CommonToken.EOF {\n            return \"<EOF>\"\n        }\n        else if a == CommonToken.EPSILON {\n            return \"<EPSILON>\"\n        }\n        else {\n            return vocabulary.getDisplayName(a)\n        }\n    }\n\n\n    public func size() -> Int {\n        var n = 0\n        for interval in intervals {\n            n += (interval.b - interval.a + 1)\n        }\n        return n\n    }\n\n\n    public func toList() -> [Int] {\n        var values = [Int]()\n        for interval in intervals {\n            let a = interval.a\n            let b = interval.b\n            values.append(contentsOf: a...b)\n        }\n        return values\n    }\n\n    public func toSet() -> Set<Int> {\n        var s = Set<Int>()\n        for interval in intervals {\n            let a = interval.a\n            let b = interval.b\n            for v in a...b  {\n                s.insert(v)\n            }\n        }\n        return s\n    }\n\n    /// \n    /// Get the ith element of ordered set.  Used only by RandomPhrase so\n    /// don't bother to implement if you're not doing that for a new\n    /// ANTLR code gen target.\n    /// \n    public func get(_ i: Int) -> Int {\n        var index = 0\n        for interval in intervals {\n            let a = interval.a\n            let b = interval.b\n            for v in a...b  {\n                if index == i {\n                    return v\n                }\n                index += 1\n            }\n        }\n        return -1\n    }\n\n    public func remove(_ el: Int) throws {\n        if readonly {\n            throw ANTLRError.illegalState(msg: \"can't alter readonly IntervalSet\")\n        }\n        var idx = intervals.startIndex\n        while idx < intervals.endIndex {\n            defer { intervals.formIndex(after: &idx) }\n            var interval: Interval {\n                get {\n                    return intervals[idx]\n                }\n                set {\n                    intervals[idx] = newValue\n                }\n            } \n            let a = interval.a\n            let b = interval.b\n            if el < a {\n                break // list is sorted and el is before this interval; not here\n            }\n            // if whole interval x..x, rm\n            if el == a && el == b {\n                intervals.remove(at: idx)\n                break\n            }\n            // if on left edge x..b, adjust left\n            if el == a {\n                interval.a += 1\n                break\n            }\n            // if on right edge a..x, adjust right\n            if el == b {\n                interval.b -= 1\n                break\n            }\n            // if in middle a..x..b, split interval\n            if el > a && el < b {\n                // found in this interval\n                let oldb = interval.b\n                interval.b = el - 1      // [a..x-1]\n                try add(el + 1, oldb) // add [x+1..b]\n            }\n        }\n    }\n\n    public func isReadonly() -> Bool {\n        return readonly\n    }\n\n    public func makeReadonly() {\n        readonly = true\n    }\n}\n\npublic func ==(lhs: IntervalSet, rhs: IntervalSet) -> Bool {\n    return lhs.intervals == rhs.intervals\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/MultiMap.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\npublic class MultiMap<K:Hashable, V> {\n    private var mapping = [K: Array<V>]()\n    public func map(_ key: K, _ value: V) {\n        mapping[key, default: Array()].append(value)\n    }\n\n    public func getPairs() -> Array<(K, V)> {\n        var pairs: Array<(K, V)> = Array<(K, V)>()\n        for key: K in mapping.keys {\n            for value: V in mapping[key]! {\n                pairs.append((key, value))\n            }\n        }\n        return pairs\n    }\n\n    public func get(_ key: K) -> Array<(V)>? {\n        return mapping[key]\n    }\n\n    public func size() -> Int {\n        return mapping.count\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/MurmurHash.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// \n/// https://en.wikipedia.org/wiki/MurmurHash\n/// \n/// - Author: Sam Harwell\n/// \n\npublic final class MurmurHash {\n\n    private static let DEFAULT_SEED: UInt32 = 0\n\n    private static let c1 = UInt32(0xCC9E2D51)\n    private static let c2 = UInt32(0x1B873593)\n    private static let r1 = UInt32(15)\n    private static let r2 = UInt32(13)\n    private static let m = UInt32(5)\n    private static let n = UInt32(0xE6546B64)\n\n    /// \n    /// Initialize the hash using the default seed value.\n    /// \n    /// - Returns: the intermediate hash value\n    /// \n    public static func initialize() -> UInt32 {\n        return initialize(DEFAULT_SEED)\n    }\n\n    /// \n    /// Initialize the hash using the specified `seed`.\n    /// \n    /// - Parameter seed: the seed\n    /// - Returns: the intermediate hash value\n    /// \n    public static func initialize(_ seed: UInt32) -> UInt32 {\n        return seed\n    }\n\n    private static func calcK(_ value: UInt32) -> UInt32 {\n        var k = value\n        k = k &* c1\n        k = (k << r1) | (k >> (32 - r1))\n        k = k &* c2\n        return k\n     }\n\n    /// \n    /// Update the intermediate hash value for the next input `value`.\n    /// \n    /// - Parameter hash: the intermediate hash value\n    /// - Parameter value: the value to add to the current hash\n    /// - Returns: the updated intermediate hash value\n    /// \n    public static func update2(_ hashIn: UInt32, _ value: Int) -> UInt32 {\n        return updateInternal(hashIn, UInt32(truncatingIfNeeded: value))\n    }\n\n\n    private static func updateInternal(_ hashIn: UInt32, _ value: UInt32) -> UInt32 {\n        let k = calcK(value)\n        var hash = hashIn\n        hash = hash ^ k\n        hash = (hash << r2) | (hash >> (32 - r2))\n        hash = hash &* m &+ n\n        // print(\"murmur update2 : \\(hash)\")\n        return hash\n    }\n\n    /// \n    /// Update the intermediate hash value for the next input `value`.\n    /// \n    /// - Parameter hash: the intermediate hash value\n    /// - Parameter value: the value to add to the current hash\n    /// - Returns: the updated intermediate hash value\n    /// \n    public static func update<T:Hashable>(_ hash: UInt32, _ value: T?) -> UInt32 {\n        return update2(hash, value?.hashValue ?? 0)\n    }\n\n    /// \n    /// Apply the final computation steps to the intermediate value `hash`\n    /// to form the final result of the MurmurHash 3 hash function.\n    /// \n    /// - Parameter hash: the intermediate hash value\n    /// - Parameter numberOfWords: the number of UInt32 values added to the hash\n    /// - Returns: the final hash result\n    /// \n    public static func finish(_ hashin: UInt32, _ numberOfWords: Int) -> Int {\n        return Int(finish(hashin, byteCount: (numberOfWords &* 4)))\n    }\n\n    private static func finish(_ hashin: UInt32, byteCount byteCountInt: Int) -> UInt32 {\n        let byteCount = UInt32(truncatingIfNeeded: byteCountInt)\n        var hash = hashin\n        hash ^= byteCount\n        hash ^= (hash >> 16)\n        hash = hash &* 0x85EBCA6B\n        hash ^= (hash >> 13)\n        hash = hash &* 0xC2B2AE35\n        hash ^= (hash >> 16)\n        //print(\"murmur finish : \\(hash)\")\n        return hash\n    }\n\n    /// \n    /// Utility function to compute the hash code of an array using the\n    /// MurmurHash algorithm.\n    /// \n    /// - Parameter <T>: the array element type\n    /// - Parameter data: the array data\n    /// - Parameter seed: the seed for the MurmurHash algorithm\n    /// - Returns: the hash code of the data\n    /// \n    public static func hashCode<T:Hashable>(_ data: [T], _ seed: Int) -> Int {\n        var hash = initialize(UInt32(truncatingIfNeeded: seed))\n        for value in data {\n            hash = update(hash, value)\n        }\n\n        return finish(hash, data.count)\n    }\n\n    ///\n    /// Compute a hash for the given String and seed.  The String is encoded\n    /// using UTF-8, then the bytes are interpreted as unsigned 32-bit\n    /// little-endian values, giving UInt32 values for the update call.\n    ///\n    /// If the bytes do not evenly divide by 4, the final bytes are treated\n    /// slightly differently (not doing the final rotate / multiply / add).\n    ///\n    /// This matches the treatment of byte sequences in publicly available\n    /// test patterns (see MurmurHashTests.swift) and the example code on\n    /// Wikipedia.\n    ///\n    public static func hashString(_ s: String, _ seed: UInt32) -> UInt32 {\n        let bytes = Array(s.utf8)\n        return hashBytesLittleEndian(bytes, seed)\n    }\n\n    private static func hashBytesLittleEndian(_ bytes: [UInt8], _ seed: UInt32) -> UInt32 {\n        let byteCount = bytes.count\n\n        var hash = seed\n        for i in stride(from: 0, to: byteCount - 3, by: 4) {\n            var word = UInt32(bytes[i])\n            word |= UInt32(bytes[i + 1]) << 8\n            word |= UInt32(bytes[i + 2]) << 16\n            word |= UInt32(bytes[i + 3]) << 24\n\n            hash = updateInternal(hash, word)\n        }\n        let remaining = byteCount & 3\n        if remaining != 0 {\n            var lastWord = UInt32(0)\n            for r in 0 ..< remaining {\n                lastWord |= UInt32(bytes[byteCount - 1 - r]) << (8 * (remaining - 1 - r))\n            }\n\n            let k = calcK(lastWord)\n            hash ^= k\n        }\n\n        return finish(hash, byteCount: byteCount)\n    }\n\n    private init() {\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/Utils.swift",
    "content": "///\n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n///\n\n\nimport Foundation\n\npublic class Utils {\n\n    public static func escapeWhitespace(_ s: String, _ escapeSpaces: Bool) -> String {\n        var buf = \"\"\n        for c in s {\n            if c == \" \" && escapeSpaces {\n                buf += \"\\u{00B7}\"\n            }\n            else if c == \"\\t\" {\n                    buf += \"\\\\t\"\n            }\n            else if c == \"\\n\" {\n                buf += \"\\\\n\"\n            }\n            else if c == \"\\r\" {\n                buf += \"\\\\r\"\n            }\n            else {\n                buf.append(c)\n            }\n        }\n        return buf\n    }\n\n\n    public static func toMap(_ keys: [String]) -> [String: Int] {\n        var m = [String: Int]()\n        for (index, v) in keys.enumerated() {\n            m[v] = index\n        }\n        return m\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/exception/ANTLRError.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  ANTLRError.swift\n//  antlr.swift\n//\n//  Created by janyou on 15/9/4.\n//\n\nimport Foundation\n\npublic enum ANTLRError: Error {\n    case unsupportedOperation(msg:String)\n    case indexOutOfBounds(msg:String)\n    case illegalState(msg:String)\n    case illegalArgument(msg:String)\n    case negativeArraySize(msg:String)\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/exception/ANTLRException.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  ANTLRException.swift\n//  antlr.swift\n//\n//  Created by janyou on 15/9/8.\n//\n\n\nimport Foundation\n\npublic enum ANTLRException: Error {\n    case parseCancellation(e: RecognitionException)\n    case recognition(e: RecognitionException)\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/extension/ArrayExtension.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\nimport Foundation\n\n//https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift\nextension Array {\n   @discardableResult\n    mutating func concat(_ addArray: [Element]) -> [Element] {\n        return self + addArray\n    }\n\n    mutating func removeObject<T:Equatable>(_ object: T) {\n        var index: Int?\n        for (idx, objectToCompare) in self.enumerated() {\n\n            if let to = objectToCompare as? T {\n                if object == to {\n                    index = idx\n                }\n            }\n        }\n\n        if index != nil {\n\n            self.remove(at: index!)\n        }\n\n    }\n\n    /// \n    /// Removes the last element from self and returns it.\n    /// \n    /// :returns: The removed element\n    /// \n    mutating func pop() -> Element {\n        return removeLast()\n    }\n    /// \n    /// Same as append.\n    /// \n    /// :param: newElement Element to append\n    /// \n    mutating func push(_ newElement: Element) {\n        return append(newElement)\n    }\n\n    func all(_ test: (Element) -> Bool) -> Bool {\n        for item in self {\n            if !test(item) {\n                return false\n            }\n        }\n\n        return true\n    }\n\n\n    /// \n    /// Checks if test returns true for all the elements in self\n    /// \n    /// :param: test Function to call for each element\n    /// :returns: True if test returns true for all the elements in self\n    /// \n    func every(_ test: (Element) -> Bool) -> Bool {\n        for item in self {\n            if !test(item) {\n                return false\n            }\n        }\n\n        return true\n    }\n\n    /// \n    /// Checks if test returns true for any element of self.\n    /// \n    /// :param: test Function to call for each element\n    /// :returns: true if test returns true for any element of self\n    /// \n    func any(_ test: (Element) -> Bool) -> Bool {\n        for item in self {\n            if test(item) {\n                return true\n            }\n        }\n\n        return false\n    }\n\n\n\n    /// \n    /// slice array\n    /// :param: index slice index\n    /// :param: isClose is close array\n    /// :param: first First array\n    /// :param: second Second array\n    /// \n    //func slice(startIndex startIndex:Int, endIndex:Int) -> Slice<Element> {\n    func slice(startIndex: Int, endIndex: Int) -> ArraySlice<Element> {\n\n\n        return self[startIndex ... endIndex]\n\n    }\n    // func slice(index:Int,isClose:Bool = false) ->(first:Slice<Element> ,second:Slice<Element>){\n    func slice(_ index: Int, isClose: Bool = false) -> (first:ArraySlice<Element>, second:ArraySlice<Element>) {\n        var first = self[0 ... index]\n        var second = self[index ..< count]\n\n        if isClose {\n            first = second + first\n            second = []\n        }\n\n        return (first, second)\n\n    }\n\n\n}\n\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/extension/CharacterExtension.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  CharacterEextension.swift\n//  Antlr.swift\n//\n//  Created by janyou on 15/9/4.\n//\n\nimport Foundation\n\nextension Character {\n\n    //\"1\" -> 1 \"2\"  -> 2\n    var integerValue: Int {\n        return Int(String(self)) ?? 0\n    }\n    public init(integerLiteral value: IntegerLiteralType) {\n        self = Character(UnicodeScalar(value)!)\n    }\n    var utf8Value: UInt8 {\n        for s in String(self).utf8 {\n            return s\n        }\n        return 0\n    }\n\n    var utf16Value: UInt16 {\n        for s in String(self).utf16 {\n            return s\n        }\n        return 0\n    }\n\n    //char ->  int\n    var unicodeValue: Int {\n        return Int(String(self).unicodeScalars.first?.value ?? 0)\n    }\n\n    public static var MAX_VALUE: Int {\n        let c: Character = \"\\u{10FFFF}\"\n        return c.unicodeValue\n    }\n    public static var MIN_VALUE: Int {\n        let c: Character = \"\\u{0000}\"\n        return c.unicodeValue\n    }\n\n    public static func isJavaIdentifierStart(_ char: Int) -> Bool {\n        let ch = Character(integerLiteral: char)\n        return ch == \"_\" || ch == \"$\" || (\"a\" <= ch && ch <= \"z\")\n                || (\"A\" <= ch && ch <= \"Z\")\n\n    }\n\n    public static func isJavaIdentifierPart(_ char: Int) -> Bool {\n        let ch = Character(integerLiteral: char)\n        return isJavaIdentifierStart(char) || (\"0\" <= ch && ch <= \"9\")\n    }\n\n    public static func toCodePoint(_ high: Int, _ low: Int) -> Int {\n        let MIN_SUPPLEMENTARY_CODE_POINT = 65536 // 0x010000\n        let MIN_HIGH_SURROGATE = 0xd800 //\"\\u{dbff}\"  //\"\\u{DBFF}\"  //\"\\u{DBFF}\"\n        let MIN_LOW_SURROGATE = 0xdc00 //\"\\u{dc00}\" //\"\\u{DC00}\"\n        return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT\n                - (MIN_HIGH_SURROGATE << 10)\n                - MIN_LOW_SURROGATE)\n    }\n\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/extension/IntStreamExtension.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  IntStreamExtension.swift\n//  Antlr.swift\n//\n//  Created by janyou on 15/9/3.\n//\n\nimport Foundation\n\nextension IntStream {\n\n    /// \n    /// The value returned by _#LA LA()_ when the end of the stream is\n    /// reached.\n    /// \n    public static var EOF: Int {\n        return -1\n    }\n\n    /// \n    /// The value returned by _#getSourceName_ when the actual name of the\n    /// underlying source is not known.\n    /// \n    public static var UNKNOWN_SOURCE_NAME: String {\n        return \"<unknown>\"\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/extension/StringExtension.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\nimport Foundation\n\nextension String {\n    func lastIndex(of target: String) -> String.Index? {\n        if target.isEmpty {\n            return nil\n        }\n        var result: String.Index? = nil\n        var substring = self[...]\n        while true {\n            guard let targetRange = substring.range(of: target) else {\n                return result\n            }\n            result = targetRange.lowerBound\n            let nextChar = substring.index(after: targetRange.lowerBound)\n            substring = self[nextChar...]\n        }\n    }\n\n    subscript(integerRange: Range<Int>) -> String {\n        let start = index(startIndex, offsetBy: integerRange.lowerBound)\n        let end = index(startIndex, offsetBy: integerRange.upperBound)\n        let range = start ..< end\n        return String(self[range])\n    }\n}\n\n\n// Implement Substring.hasPrefix, which is not currently in the Linux stdlib.\n// https://bugs.swift.org/browse/SR-5627\n#if os(Linux)\nextension Substring {\n    func hasPrefix(_ prefix: String) -> Bool {\n        return String(self).hasPrefix(prefix)\n    }\n}\n#endif\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/extension/TokenExtension.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\n//\n//  TokenExtension.swift\n//  Antlr.swift\n//\n//  Created by janyou on 15/9/4.\n//\n\nimport Foundation\n\nextension Token {\n\n    static public var INVALID_TYPE: Int {\n        return 0\n    }\n\n    /// \n    /// During lookahead operations, this \"token\" signifies we hit rule end ATN state\n    /// and did not follow it despite needing to.\n    /// \n    static public var EPSILON: Int {\n        return -2\n    }\n\n\n    static public var MIN_USER_TOKEN_TYPE: Int {\n        return 1\n    }\n\n    static public var EOF: Int {\n        return -1\n    }\n    \n    ///\n    /// All tokens go to the parser (unless skip() is called in that rule)\n    /// on a particular \"channel\".  The parser tunes to a particular channel\n    /// so that whitespace etc... can go to the parser on a \"hidden\" channel.\n    ///\n    static public var DEFAULT_CHANNEL: Int {\n        return 0\n    }\n    \n    /// \n    /// Anything on different channel than DEFAULT_CHANNEL is not parsed\n    /// by parser.\n    ///\n    static public var HIDDEN_CHANNEL: Int {\n        return 1\n    }\n    \n    /// \n    /// This is the minimum constant value which can be assigned to a\n    /// user-defined token channel.\n    /// \n    /// \n    /// The non-negative numbers less than _#MIN_USER_CHANNEL_VALUE_ are\n    /// assigned to the predefined channels _#DEFAULT_CHANNEL_ and\n    /// _#HIDDEN_CHANNEL_.\n    /// \n    /// - seealso: org.antlr.v4.runtime.Token#getChannel()\n    /// \n    static public var MIN_USER_CHANNEL_VALUE: Int {\n        return 2\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/extension/UUIDExtension.swift",
    "content": "/// \n/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n/// \n\nimport Foundation\n\n\nextension UUID {\n    public init(mostSigBits: Int64, leastSigBits: Int64) {\n        let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)\n        defer {\n            bytes.deallocate()\n        }\n        bytes.withMemoryRebound(to: Int64.self, capacity: 2) {\n            $0.pointee = leastSigBits\n            $0.advanced(by: 1).pointee = mostSigBits\n        }\n        let u = NSUUID(uuidBytes: bytes)\n        self.init(uuidString: u.uuidString)!\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/utils/CommonUtil.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n//\n//  CommonUtil.swift\n//   antlr.swift\n//\n//  Created by janyou on 15/9/4.\n//\n\nimport Foundation\n\nfunc errPrint(_ msg: String) {\n    fputs(msg + \"\\n\", stderr)\n}\n\npublic func +(lhs: String, rhs: Int) -> String {\n    return lhs + String(rhs)\n}\n\npublic func +(lhs: Int, rhs: String) -> String {\n    return String(lhs) + rhs\n}\n\npublic func +(lhs: String, rhs: Token) -> String {\n    return lhs + rhs.description\n}\n\npublic func +(lhs: Token, rhs: String) -> String {\n    return lhs.description + rhs\n}\n\ninfix operator >>> : BitwiseShiftPrecedence\n\nfunc >>>(lhs: Int32, rhs: Int32) -> Int32 {\n    return lhs &>> rhs\n}\n\nfunc >>>(lhs: Int64, rhs: Int64) -> Int64 {\n    return lhs &>> rhs\n}\n\nfunc >>>(lhs: Int, rhs: Int) -> Int {\n    return lhs &>> rhs\n}\n\nfunc intChar2String(_ i: Int) -> String {\n    return String(Character(integerLiteral: i))\n}\n\nfunc log(_ message: String = \"\", file: String = #file, function: String = #function, lineNum: Int = #line) {\n\n    // #if DEBUG\n    print(\"FILE: \\(URL(fileURLWithPath: file).pathComponents.last!),FUNC: \\(function), LINE: \\(lineNum) MESSAGE: \\(message)\")\n    //   #else\n    // do nothing\n    //   #endif\n}\n\nfunc toInt(_ c: Character) -> Int {\n    return c.unicodeValue\n}\n\nfunc toInt32(_ data: [Character], _ offset: Int) -> Int {\n    return data[offset].unicodeValue | (data[offset + 1].unicodeValue << 16)\n}\n\nfunc toLong(_ data: [Character], _ offset: Int) -> Int64 {\n    let mask: Int64 = 0x00000000FFFFFFFF\n    let lowOrder: Int64 = Int64(toInt32(data, offset)) & mask\n    return lowOrder | Int64(toInt32(data, offset + 2) << 32)\n}\n\nfunc toUUID(_ data: [Character], _ offset: Int) -> UUID {\n    let leastSigBits: Int64 = toLong(data, offset)\n    let mostSigBits: Int64 = toLong(data, offset + 4)\n    return UUID(mostSigBits: mostSigBits, leastSigBits: leastSigBits)\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/utils/Mutex.swift",
    "content": "import Foundation\n\n\n///\n/// Using class so it can be shared even if\n/// it appears to be a field in a class.\n///\nclass Mutex {\n    ///\n    /// The mutex instance.\n    ///\n    private let semaphore = DispatchSemaphore(value: 1)\n\n    ///\n    /// Running the supplied closure synchronously.\n    ///\n    /// - Parameter closure: the closure to run\n    /// - Returns: the value returned by the closure\n    /// - Throws: the exception populated by the closure run\n    ///\n    @discardableResult\n    func synchronized<R>(closure: () throws -> R) rethrows -> R {\n        semaphore.wait()\n        defer {\n            semaphore.signal()\n        }\n        return try closure()\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/misc/utils/Stack.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n//\n//  Stack.swift\n//  antlr.swift\n//\n//  Created by janyou on 15/9/8.\n//\n\nimport Foundation\n\npublic struct Stack<T> {\n    var items = [T]()\n    public mutating func push(_ item: T) {\n        items.append(item)\n    }\n    @discardableResult\n    public mutating func pop() -> T {\n        return items.removeLast()\n    }\n\n    public mutating func clear() {\n        return items.removeAll()\n    }\n\n    public func peek() -> T? {\n        return items.last\n    }\n    public var isEmpty: Bool {\n        return items.isEmpty\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/AbstractParseTreeVisitor.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\nopen class AbstractParseTreeVisitor<T>: ParseTreeVisitor<T> {\n    public override init() {\n        super.init()\n    }\n\n    /// \n    /// The default implementation calls _org.antlr.v4.runtime.tree.ParseTree#accept_ on the\n    /// specified tree.\n    /// \n    open override func visit(_ tree: ParseTree) -> T? {\n        return tree.accept(self)\n    }\n\n    ///\n    /// The default implementation initializes the aggregate result to\n    /// _#defaultResult defaultResult()_. Before visiting each child, it\n    /// calls _#shouldVisitNextChild shouldVisitNextChild_; if the result\n    /// is `false` no more children are visited and the current aggregate\n    /// result is returned. After visiting a child, the aggregate result is\n    /// updated by calling _#aggregateResult aggregateResult_ with the\n    /// previous aggregate result and the result of visiting the child.\n    /// \n    /// The default implementation is not safe for use in visitors that modify\n    /// the tree structure. Visitors that modify the tree should override this\n    /// method to behave properly in respect to the specific algorithm in use.\n    /// \n    open override func visitChildren(_ node: RuleNode) -> T? {\n        var result: T? = defaultResult()\n        let n = node.getChildCount()\n\n        for i in 0..<n {\n            if !shouldVisitNextChild(node, result) {\n                break\n            }\n\n            let c = node[i]\n            let childResult = c.accept(self)\n            result = aggregateResult(result, childResult)\n        }\n\n        return result\n    }\n\n    ///\n    /// The default implementation returns the result of\n    /// _#defaultResult defaultResult_.\n    /// \n    open override func visitTerminal(_ node: TerminalNode) -> T? {\n        return defaultResult()\n    }\n\n    ///\n    /// The default implementation returns the result of\n    /// _#defaultResult defaultResult_.\n    /// \n    override\n    open func visitErrorNode(_ node: ErrorNode) -> T? {\n        return defaultResult()\n    }\n\n    /// \n    /// Gets the default value returned by visitor methods. This value is\n    /// returned by the default implementations of\n    /// _#visitTerminal visitTerminal_, _#visitErrorNode visitErrorNode_.\n    /// The default implementation of _#visitChildren visitChildren_\n    /// initializes its aggregate result to this value.\n    /// \n    /// The base implementation returns `null`.\n    /// \n    /// - Returns: The default value returned by visitor methods.\n    /// \n    open func defaultResult() -> T? {\n        return nil\n    }\n\n    /// \n    /// Aggregates the results of visiting multiple children of a node. After\n    /// either all children are visited or _#shouldVisitNextChild_ returns\n    /// `false`, the aggregate value is returned as the result of\n    /// _#visitChildren_.\n    /// \n    /// The default implementation returns `nextResult`, meaning\n    /// _#visitChildren_ will return the result of the last child visited\n    /// (or return the initial value if the node has no children).\n    /// \n    /// - Parameter aggregate: The previous aggregate value. In the default\n    /// implementation, the aggregate value is initialized to\n    /// _#defaultResult_, which is passed as the `aggregate` argument\n    /// to this method after the first child node is visited.\n    /// - Parameter nextResult: The result of the immediately preceeding call to visit\n    /// a child node.\n    /// \n    /// - Returns: The updated aggregate result.\n    /// \n    open func aggregateResult(_ aggregate: T?, _ nextResult: T?) -> T? {\n        return nextResult\n    }\n\n    /// \n    /// This method is called after visiting each child in\n    /// _#visitChildren_. This method is first called before the first\n    /// child is visited; at that point `currentResult` will be the initial\n    /// value (in the default implementation, the initial value is returned by a\n    /// call to _#defaultResult_. This method is not called after the last\n    /// child is visited.\n    /// \n    /// The default implementation always returns `true`, indicating that\n    /// `visitChildren` should only return after all children are visited.\n    /// One reason to override this method is to provide a \"short circuit\"\n    /// evaluation option for situations where the result of visiting a single\n    /// child has the potential to determine the result of the visit operation as\n    /// a whole.\n    /// \n    /// - Parameter node: The _org.antlr.v4.runtime.tree.RuleNode_ whose children are currently being\n    /// visited.\n    /// - Parameter currentResult: The current aggregate result of the children visited\n    /// to the current point.\n    /// \n    /// - Returns: `true` to continue visiting children. Otherwise return\n    /// `false` to stop visiting children and immediately return the\n    /// current aggregate result from _#visitChildren_.\n    /// \n    open func shouldVisitNextChild(_ node: RuleNode, _ currentResult: T?) -> Bool {\n        return true\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/ErrorNode.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// Represents a token that was consumed during resynchronization\n/// rather than during a valid match operation. For example,\n/// we will create this kind of a node during single token insertion\n/// and deletion as well as during \"consume until error recovery set\"\n/// upon no viable alternative exceptions.\n/// \npublic class ErrorNode: TerminalNodeImpl {\n    public override init(_ token: Token) {\n        super.init(token)\n    }\n\n\n    override\n    public func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? {\n        return visitor.visitErrorNode(self)\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/ParseTree.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// An interface to access the tree of _org.antlr.v4.runtime.RuleContext_ objects created\n/// during a parse that makes the data structure look like a simple parse tree.\n/// This node represents both internal nodes, rule invocations,\n/// and leaf nodes, token matches.\n/// \n/// The payload is either a _org.antlr.v4.runtime.Token_ or a _org.antlr.v4.runtime.RuleContext_ object.\n///\npublic protocol ParseTree: SyntaxTree, CustomStringConvertible, CustomDebugStringConvertible {\n    /// Set the parent for this leaf node.\n    func setParent(_ parent: RuleContext)\n\n    /// The _org.antlr.v4.runtime.tree.ParseTreeVisitor_ needs a double dispatch method.\n    func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T?\n\n    /// Return the combined text of all leaf nodes. Does not get any\n    /// off-channel tokens (if any) so won't return whitespace and\n    /// comments if they are sent to parser on hidden channel.\n    func getText() -> String\n\n    /// Specialize toStringTree so that it can print out more information\n    /// based upon the parser.\n    func toStringTree(_ parser: Parser) -> String\n\n    /// Equivalent to `getChild(index)! as! ParseTree`\n    subscript(index: Int) -> ParseTree { get }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/ParseTreeListener.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// This interface describes the minimal core of methods triggered\n/// by _org.antlr.v4.runtime.tree.ParseTreeWalker_. E.g.,\n/// \n/// ParseTreeWalker walker = new ParseTreeWalker();\n/// walker.walk(myParseTreeListener, myParseTree); <-- triggers events in your listener\n/// \n/// If you want to trigger events in multiple listeners during a single\n/// tree walk, you can use the ParseTreeDispatcher object available at\n/// \n/// https://github.com/antlr/antlr4/issues/841\n/// \n\npublic protocol ParseTreeListener: AnyObject {\n    func visitTerminal(_ node: TerminalNode)\n\n    func visitErrorNode(_ node: ErrorNode)\n\n    func enterEveryRule(_ ctx: ParserRuleContext) throws\n\n    func exitEveryRule(_ ctx: ParserRuleContext) throws\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/ParseTreeProperty.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\nimport Foundation\n\npublic class ParseTreeProperty<V> {\n  var annotations = Dictionary<ObjectIdentifier, V>()\n  \n  public init() {}\n  \n  open func get(_ node: ParseTree) -> V? { return annotations[ObjectIdentifier(node)] }\n  open func put(_ node: ParseTree, _ value: V) { annotations[ObjectIdentifier(node)] = value }\n  open func removeFrom(_ node: ParseTree) { annotations.removeValue(forKey: ObjectIdentifier(node)) }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/ParseTreeVisitor.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// \n/// This interface defines the basic notion of a parse tree visitor. Generated\n/// visitors implement this interface and the `XVisitor` interface for\n/// grammar `X`.\n/// \n/// - Parameter <T>: The return type of the visit operation. Use _Void_ for\n/// operations with no return type.\n/// \n\n\nopen class ParseTreeVisitor<T> {\n    public init() {\n\n    }\n    // typealias T\n    /// \n    /// Visit a parse tree, and return a user-defined result of the operation.\n    /// \n    /// - Parameter tree: The _org.antlr.v4.runtime.tree.ParseTree_ to visit.\n    /// - Returns: The result of visiting the parse tree.\n    /// \n    open func visit(_ tree: ParseTree) -> T? {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Visit the children of a node, and return a user-defined result of the\n    /// operation.\n    /// \n    /// - Parameter node: The _org.antlr.v4.runtime.tree.RuleNode_ whose children should be visited.\n    /// - Returns: The result of visiting the children of the node.\n    /// \n    open func visitChildren(_ node: RuleNode) -> T? {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Visit a terminal node, and return a user-defined result of the operation.\n    /// \n    /// - Parameter node: The _org.antlr.v4.runtime.tree.TerminalNode_ to visit.\n    /// - Returns: The result of visiting the node.\n    /// \n    open func visitTerminal(_ node: TerminalNode) -> T? {\n        fatalError(#function + \" must be overridden\")\n    }\n\n    /// \n    /// Visit an error node, and return a user-defined result of the operation.\n    /// \n    /// - Parameter node: The _org.antlr.v4.runtime.tree.ErrorNode_ to visit.\n    /// - Returns: The result of visiting the node.\n    /// \n    open func visitErrorNode(_ node: ErrorNode) -> T? {\n        fatalError(#function + \" must be overridden\")\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/ParseTreeWalker.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\npublic class ParseTreeWalker {\n    public static let DEFAULT = ParseTreeWalker()\n\n    public init() {\n    }\n\n    /**\n\t * Performs a walk on the given parse tree starting at the root and going down recursively\n\t * with depth-first search. On each node, ParseTreeWalker.enterRule is called before\n\t * recursively walking down into child nodes, then\n\t * ParseTreeWalker.exitRule is called after the recursive call to wind up.\n\t * - Parameter listener: The listener used by the walker to process grammar rules\n\t * - Parameter t: The parse tree to be walked on\n\t */\n    public func walk(_ listener: ParseTreeListener, _ t: ParseTree) throws {\n        if let errNode = t as? ErrorNode {\n            listener.visitErrorNode(errNode)\n        }\n        else if let termNode = t as? TerminalNode {\n            listener.visitTerminal(termNode)\n        }\n        else if let r = t as? RuleNode {\n            try enterRule(listener, r)\n            let n = r.getChildCount()\n            for i in 0..<n {\n                try walk(listener, r[i])\n            }\n            try exitRule(listener, r)\n        }\n        else {\n            preconditionFailure()\n        }\n    }\n\n    /**\n\t * Enters a grammar rule by first triggering the generic event ParseTreeListener.enterEveryRule\n\t * then by triggering the event specific to the given parse tree node\n\t * - Parameter listener: The listener responding to the trigger events\n\t * - Parameter r: The grammar rule containing the rule context\n\t */\n    internal func enterRule(_ listener: ParseTreeListener, _ r: RuleNode) throws {\n        let ctx = r.getRuleContext() as! ParserRuleContext\n        try listener.enterEveryRule(ctx)\n        ctx.enterRule(listener)\n    }\n\n    /**\n\t * Exits a grammar rule by first triggering the event specific to the given parse tree node\n\t * then by triggering the generic event ParseTreeListener.exitEveryRule\n\t * - Parameter listener: The listener responding to the trigger events\n\t * - Parameter r: The grammar rule containing the rule context\n\t */\n    internal func exitRule(_ listener: ParseTreeListener, _ r: RuleNode) throws {\n        let ctx = r.getRuleContext() as! ParserRuleContext\n        ctx.exitRule(listener)\n        try listener.exitEveryRule(ctx)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/RuleNode.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\npublic protocol RuleNode: ParseTree {\n    func getRuleContext() -> RuleContext\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/SyntaxTree.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// A tree that knows about an interval in a token stream\n/// is some kind of syntax tree. Subinterfaces distinguish\n/// between parse trees and other kinds of syntax trees we might want to create.\n/// \n\npublic protocol SyntaxTree: Tree {\n    /// \n    /// Return an _org.antlr.v4.runtime.misc.Interval_ indicating the index in the\n    /// _org.antlr.v4.runtime.TokenStream_ of the first and last token associated with this\n    /// subtree. If this node is a leaf, then the interval represents a single\n    /// token.\n    /// \n    /// If source interval is unknown, this returns _org.antlr.v4.runtime.misc.Interval#INVALID_.\n    /// \n\n    func getSourceInterval() -> Interval\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/TerminalNode.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\npublic protocol TerminalNode: ParseTree {\n    func getSymbol() -> Token?\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/TerminalNodeImpl.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\npublic class TerminalNodeImpl: TerminalNode {\n    public var symbol: Token\n    public weak var parent: ParseTree?\n\n    public init(_ symbol: Token) {\n        self.symbol = symbol\n    }\n\n\n    public func getChild(_ i: Int) -> Tree? {\n        return nil\n    }\n\n    open subscript(index: Int) -> ParseTree {\n        preconditionFailure(\"Index out of range (TerminalNode never has children)\")\n    }\n\n    public func getSymbol() -> Token? {\n        return symbol\n    }\n\n    public func getParent() -> Tree? {\n        return parent\n    }\n\n    public func setParent(_ parent: RuleContext) {\n        self.parent = parent\n    }\n\n    public func getPayload() -> AnyObject {\n        return symbol\n    }\n\n    public func getSourceInterval() -> Interval {\n        //if   symbol == nil   { return Interval.INVALID; }\n\n        let tokenIndex: Int = symbol.getTokenIndex()\n        return Interval(tokenIndex, tokenIndex)\n    }\n\n    public func getChildCount() -> Int {\n        return 0\n    }\n\n\n    public func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? {\n        return visitor.visitTerminal(self)\n    }\n\n    public func getText() -> String {\n        return (symbol.getText())!\n    }\n\n    public func toStringTree(_ parser: Parser) -> String {\n        return description\n    }\n\n    public var description: String {\n        //TODO: symbol == nil?\n        //if    symbol == nil   {return \"<nil>\"; }\n        if symbol.getType() == CommonToken.EOF {\n            return \"<EOF>\"\n        }\n        return symbol.getText()!\n    }\n\n    public var debugDescription: String {\n        return description\n    }\n\n    public func toStringTree() -> String {\n        return description\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/Tree.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// The basic notion of a tree has a parent, a payload, and a list of children.\n/// It is the most abstract interface for all the trees used by ANTLR.\n/// \n\npublic protocol Tree: AnyObject {\n    /// The parent of this node. If the return value is null, then this\n    /// node is the root of the tree.\n    /// \n    func getParent() -> Tree?\n\n    /// \n    /// This method returns whatever object represents the data at this note. For\n    /// example, for parse trees, the payload can be a _org.antlr.v4.runtime.Token_ representing\n    /// a leaf node or a _org.antlr.v4.runtime.RuleContext_ object representing a rule\n    /// invocation. For abstract syntax trees (ASTs), this is a _org.antlr.v4.runtime.Token_\n    /// object.\n    /// \n    func getPayload() -> AnyObject\n\n    /// If there are children, get the `i`th value indexed from 0.\n    func getChild(_ i: Int) -> Tree?\n\n    /// How many children are there? If there is none, then this\n    /// node represents a leaf node.\n    /// \n    func getChildCount() -> Int\n\n    /// Print out a whole tree, not just a node, in LISP format\n    /// `(root child1 .. childN)`. Print just a node if this is a leaf.\n    /// \n    func toStringTree() -> String\n\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/Trees.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// A set of utility routines useful for all kinds of ANTLR trees.\n\npublic class Trees {\n    /*\n    public class func getPS(t: Tree, _ ruleNames: Array<String>,\n    _ fontName: String, _ fontSize: Int) -> String {\n    let psgen: TreePostScriptGenerator =\n    TreePostScriptGenerator(ruleNames, t, fontName, fontSize)\n    return psgen.getPS()\n    }\n\n    public class func getPS(t: Tree, _ ruleNames: Array<String>) -> String {\n    return getPS(t, ruleNames, \"Helvetica\", 11)\n    }\n    //TODO: write to file\n\n    public class func writePS(t: Tree, _ ruleNames: Array<String>,\n    _ fileName: String,\n    _ fontName: String, _ fontSize: Int)\n    throws {\n    var ps: String = getPS(t, ruleNames, fontName, fontSize)\n    var f: FileWriter = FileWriter(fileName)\n    var bw: BufferedWriter = BufferedWriter(f)\n    try {\n    bw.write(ps)\n    }\n    defer {\n    bw.close()\n    }\n    }\n\n    public class func writePS(t: Tree, _ ruleNames: Array<String>, _ fileName: String)\n    throws {\n    writePS(t, ruleNames, fileName, \"Helvetica\", 11)\n    }\n    */\n    /// Print out a whole tree in LISP form. _#getNodeText_ is used on the\n    /// node payloads to get the text for the nodes.  Detect\n    /// parse trees and extract data appropriately.\n    /// \n    public static func toStringTree(_ t: Tree) -> String {\n        let rulsName: Array<String>? = nil\n        return toStringTree(t, rulsName)\n    }\n\n    /// Print out a whole tree in LISP form. _#getNodeText_ is used on the\n    /// node payloads to get the text for the nodes.  Detect\n    /// parse trees and extract data appropriately.\n    /// \n    public static func toStringTree(_ t: Tree, _ recog: Parser?) -> String {\n        let ruleNamesList: [String]? = recog?.getRuleNames()\n        return toStringTree(t, ruleNamesList)\n    }\n\n    /// Print out a whole tree in LISP form. _#getNodeText_ is used on the\n    /// node payloads to get the text for the nodes.  Detect\n    /// parse trees and extract data appropriately.\n    /// \n    public static func toStringTree(_ t: Tree, _ ruleNames: Array<String>?) -> String {\n        let s = Utils.escapeWhitespace(getNodeText(t, ruleNames), false)\n        if t.getChildCount() == 0 {\n            return s\n        }\n        var buf = \"(\\(s) \"\n        let length = t.getChildCount()\n        for i in 0..<length {\n            if i > 0 {\n                buf += \" \"\n            }\n            buf += toStringTree(t.getChild(i)!, ruleNames)\n        }\n        buf += \")\"\n        return buf\n    }\n\n    public static func getNodeText(_ t: Tree, _ recog: Parser?) -> String {\n        return getNodeText(t, recog?.getRuleNames())\n    }\n\n    public static func getNodeText(_ t: Tree, _ ruleNames: Array<String>?) -> String {\n        if let ruleNames = ruleNames {\n            if let ruleNode = t as? RuleNode {\n                let ruleIndex: Int = ruleNode.getRuleContext().getRuleIndex()\n                let ruleName: String = ruleNames[ruleIndex]\n                let altNumber = (t as! RuleContext).getAltNumber()\n                if altNumber != ATN.INVALID_ALT_NUMBER  {\n                    return \"\\(ruleName):\\(altNumber)\"\n                }\n                return ruleName\n            } else {\n                if let errorNode = t as? ErrorNode {\n                    return errorNode.description\n                } else if let terminalNode = t as? TerminalNode {\n                    if let symbol = terminalNode.getSymbol() {\n                        let s: String = symbol.getText()!\n                        return s\n                    }\n                }\n            }\n        }\n        // no recog for rule names\n        let payload: AnyObject = t.getPayload()\n        if let token = payload as? Token {\n            return token.getText()!\n        }\n        return \"\\(t.getPayload())\"\n\n    }\n\n    /// Return ordered list of all children of this node\n    public static func getChildren(_ t: Tree) -> Array<Tree> {\n        var kids: Array<Tree> = Array<Tree>()\n        let length = t.getChildCount()\n        for i in 0..<length {\n            kids.append(t.getChild(i)!)\n        }\n        return kids\n    }\n\n    /// Return a list of all ancestors of this node.  The first node of\n    /// list is the root and the last is the parent of this node.\n    /// \n\n    public static func getAncestors(_ t: Tree) -> Array<Tree> {\n        var ancestors: Array<Tree> = Array<Tree>()\n        if t.getParent() == nil {\n\n            return ancestors\n            //return Collections.emptyList();\n        }\n\n        var tp = t.getParent()\n        while let tpWrap = tp {\n            ancestors.insert(t, at: 0)\n            //ancestors.add(0, t); // insert at start\n            tp = tpWrap.getParent()\n        }\n        return ancestors\n    }\n\n    public static func findAllTokenNodes(_ t: ParseTree, _ ttype: Int) -> Array<ParseTree> {\n        return findAllNodes(t, ttype, true)\n    }\n\n    public static func findAllRuleNodes(_ t: ParseTree, _ ruleIndex: Int) -> Array<ParseTree> {\n        return findAllNodes(t, ruleIndex, false)\n    }\n\n    public static func findAllNodes(_ t: ParseTree, _ index: Int, _ findTokens: Bool) -> Array<ParseTree> {\n        var nodes: Array<ParseTree> = Array<ParseTree>()\n        _findAllNodes(t, index, findTokens, &nodes)\n        return nodes\n    }\n\n    public static func _findAllNodes(_ t: ParseTree,\n                                    _ index: Int, _ findTokens: Bool, _ nodes: inout Array<ParseTree>) {\n        // check this node (the root) first\n        if let tnode = t as? TerminalNode , findTokens {\n            if tnode.getSymbol()!.getType() == index {\n                nodes.append(t)\n            }\n        } else {\n            if let ctx = t as? ParserRuleContext , !findTokens {\n                if ctx.getRuleIndex() == index {\n                    nodes.append(t)\n                }\n            }\n        }\n        // check children\n        let length = t.getChildCount()\n        for i in 0..<length {\n            _findAllNodes(t.getChild(i) as! ParseTree, index, findTokens, &nodes)\n        }\n    }\n\n    public static func descendants(_ t: ParseTree) -> Array<ParseTree> {\n        var nodes: Array<ParseTree> = [t]\n\n        let n: Int = t.getChildCount()\n        for i in 0..<n {\n\n            //nodes.addAll(descendants(t.getChild(i)));\n            if let child = t.getChild(i) {\n                nodes.concat(descendants(child as! ParseTree))\n            }\n\n        }\n        return nodes\n    }\n\n    /// Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex\n    /// inclusively using postorder traversal.  Recursive depth-first-search.\n    /// \n    /// - Since: 4.5.1\n    /// \n    public static func getRootOfSubtreeEnclosingRegion(_ t: ParseTree,\n                                                      _ startTokenIndex: Int,\n                                                      _ stopTokenIndex: Int) -> ParserRuleContext? {\n        let n: Int = t.getChildCount()\n\n        for i in 0..<n {\n            //TODO t.getChild(i) nil\n            //Added by janyou\n            guard let child = t.getChild(i) as? ParseTree else {\n                return nil\n            }\n            if let r = getRootOfSubtreeEnclosingRegion(child, startTokenIndex, stopTokenIndex) {\n                return r\n            }\n        }\n        if let r = t as? ParserRuleContext {\n            if startTokenIndex >= r.getStart()!.getTokenIndex() && // is range fully contained in t?\n                    stopTokenIndex <= r.getStop()!.getTokenIndex() {\n                return r\n            }\n        }\n        return nil\n    }\n\n    private init() {\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/Chunk.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// \n/// A chunk is either a token tag, a rule tag, or a span of literal text within a\n/// tree pattern.\n/// \n/// The method _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#split(String)_ returns a list of\n/// chunks in preparation for creating a token stream by\n/// _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#tokenize(String)_. From there, we get a parse\n/// tree from with _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#compile(String, int)_. These\n/// chunks are converted to _org.antlr.v4.runtime.tree.pattern.RuleTagToken_, _org.antlr.v4.runtime.tree.pattern.TokenTagToken_, or the\n/// regular tokens of the text surrounding the tags.\n/// \n\npublic class Chunk: Equatable {\n    public static func ==(lhs: Chunk, rhs: Chunk) -> Bool {\n        return lhs.isEqual(rhs)\n    }\n\n    public func isEqual(_ other: Chunk) -> Bool {\n        return self === other\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/ParseTreeMatch.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// Represents the result of matching a _org.antlr.v4.runtime.tree.ParseTree_ against a tree pattern.\n/// \n\npublic class ParseTreeMatch: CustomStringConvertible {\n    /// \n    /// This is the backing field for _#getTree()_.\n    /// \n    private let tree: ParseTree\n\n    /// \n    /// This is the backing field for _#getPattern()_.\n    /// \n    private let pattern: ParseTreePattern\n\n    /// \n    /// This is the backing field for _#getLabels()_.\n    /// \n    private let labels: MultiMap<String, ParseTree>\n\n    /// \n    /// This is the backing field for _#getMismatchedNode()_.\n    /// \n    private let mismatchedNode: ParseTree?\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ from the specified\n    /// parse tree and pattern.\n    /// \n    /// - Parameter tree: The parse tree to match against the pattern.\n    /// - Parameter pattern: The parse tree pattern.\n    /// - Parameter labels: A mapping from label names to collections of\n    /// _org.antlr.v4.runtime.tree.ParseTree_ objects located by the tree pattern matching process.\n    /// - Parameter mismatchedNode: The first node which failed to match the tree\n    /// pattern during the matching process.\n    /// \n    /// - Throws: ANTLRError.ilegalArgument if `tree` is `null`\n    /// - Throws: ANTLRError.ilegalArgument if `pattern` is `null`\n    /// - Throws: ANTLRError.ilegalArgument if `labels` is `null`\n    /// \n    public init(_ tree: ParseTree, _ pattern: ParseTreePattern, _ labels: MultiMap<String, ParseTree>, _ mismatchedNode: ParseTree?) {\n\n        self.tree = tree\n        self.pattern = pattern\n        self.labels = labels\n        self.mismatchedNode = mismatchedNode\n    }\n\n    /// \n    /// Get the last node associated with a specific `label`.\n    /// \n    /// For example, for pattern `<id:ID>`, `get(\"id\")` returns the\n    /// node matched for that `ID`. If more than one node\n    /// matched the specified label, only the last is returned. If there is\n    /// no node associated with the label, this returns `null`.\n    /// \n    /// Pattern tags like `<ID>` and `<expr>` without labels are\n    /// considered to be labeled with `ID` and `expr`, respectively.\n    /// \n    /// - Parameter label: The label to check.\n    /// \n    /// - Returns: The last _org.antlr.v4.runtime.tree.ParseTree_ to match a tag with the specified\n    /// label, or `null` if no parse tree matched a tag with the label.\n    /// \n\n    public func get(_ label: String) -> ParseTree? {\n        if let parseTrees = labels.get(label) , parseTrees.count > 0 {\n            return parseTrees[parseTrees.count - 1]   // return last if multiple\n        } else {\n            return nil\n        }\n\n    }\n\n    /// \n    /// Return all nodes matching a rule or token tag with the specified label.\n    /// \n    /// If the `label` is the name of a parser rule or token in the\n    /// grammar, the resulting list will contain both the parse trees matching\n    /// rule or tags explicitly labeled with the label and the complete set of\n    /// parse trees matching the labeled and unlabeled tags in the pattern for\n    /// the parser rule or token. For example, if `label` is `\"foo\"`,\n    /// the result will contain __all__ of the following.\n    /// \n    /// * Parse tree nodes matching tags of the form `<foo:anyRuleName>` and\n    /// `<foo:AnyTokenName>`.\n    /// * Parse tree nodes matching tags of the form `<anyLabel:foo>`.\n    /// * Parse tree nodes matching tags of the form `<foo>`.\n    /// \n    /// - Parameter label: The label.\n    /// \n    /// - Returns: A collection of all _org.antlr.v4.runtime.tree.ParseTree_ nodes matching tags with\n    /// the specified `label`. If no nodes matched the label, an empty list\n    /// is returned.\n    /// \n    public func getAll(_ label: String) -> Array<ParseTree> {\n        return labels.get(label) ?? []\n    }\n\n    /// \n    /// Return a mapping from label &rarr; [list of nodes].\n    /// \n    /// The map includes special entries corresponding to the names of rules and\n    /// tokens referenced in tags in the original pattern. For additional\n    /// information, see the description of _#getAll(String)_.\n    /// \n    /// - Returns: A mapping from labels to parse tree nodes. If the parse tree\n    /// pattern did not contain any rule or token tags, this map will be empty.\n    /// \n    public func getLabels() -> MultiMap<String, ParseTree> {\n        return labels\n    }\n\n    /// \n    /// Get the node at which we first detected a mismatch.\n    /// \n    /// - Returns: the node at which we first detected a mismatch, or `null`\n    /// if the match was successful.\n    /// \n    public func getMismatchedNode() -> ParseTree? {\n        return mismatchedNode\n    }\n\n    /// \n    /// Gets a value indicating whether the match operation succeeded.\n    /// \n    /// - Returns: `true` if the match operation succeeded; otherwise,\n    /// `false`.\n    /// \n    public func succeeded() -> Bool {\n        return mismatchedNode == nil\n    }\n\n    /// \n    /// Get the tree pattern we are matching against.\n    /// \n    /// - Returns: The tree pattern we are matching against.\n    /// \n    public func getPattern() -> ParseTreePattern {\n        return pattern\n    }\n\n    /// \n    /// Get the parse tree we are trying to match to a pattern.\n    /// \n    /// - Returns: The _org.antlr.v4.runtime.tree.ParseTree_ we are trying to match to a pattern.\n    /// \n    public func getTree() -> ParseTree {\n        return tree\n    }\n\n    public var description: String {\n        let info = succeeded() ? \"succeeded\" : \"failed\"\n        return \"Match \\(info); found \\(getLabels().size()) labels\"\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/ParseTreePattern.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// A pattern like `<ID> = <expr>;` converted to a _org.antlr.v4.runtime.tree.ParseTree_ by\n/// _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#compile(String, int)_.\n/// \n\npublic class ParseTreePattern {\n    /// \n    /// This is the backing field for _#getPatternRuleIndex()_.\n    /// \n    private let patternRuleIndex: Int\n\n    /// \n    /// This is the backing field for _#getPattern()_.\n    /// \n\n    private let pattern: String\n\n    /// \n    /// This is the backing field for _#getPatternTree()_.\n    /// \n\n    private let patternTree: ParseTree\n\n    /// \n    /// This is the backing field for _#getMatcher()_.\n    /// \n\n    private let matcher: ParseTreePatternMatcher\n\n    /// \n    /// Construct a new instance of the _org.antlr.v4.runtime.tree.pattern.ParseTreePattern_ class.\n    /// \n    /// - Parameter matcher: The _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ which created this\n    /// tree pattern.\n    /// - Parameter pattern: The tree pattern in concrete syntax form.\n    /// - Parameter patternRuleIndex: The parser rule which serves as the root of the\n    /// tree pattern.\n    /// - Parameter patternTree: The tree pattern in _org.antlr.v4.runtime.tree.ParseTree_ form.\n    /// \n    public init(_ matcher: ParseTreePatternMatcher,\n                _ pattern: String, _ patternRuleIndex: Int, _ patternTree: ParseTree) {\n        self.matcher = matcher\n        self.patternRuleIndex = patternRuleIndex\n        self.pattern = pattern\n        self.patternTree = patternTree\n    }\n\n    /// \n    /// Match a specific parse tree against this tree pattern.\n    /// \n    /// - Parameter tree: The parse tree to match against this tree pattern.\n    /// - Returns: A _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ object describing the result of the\n    /// match operation. The _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch#succeeded()_ method can be\n    /// used to determine whether or not the match was successful.\n    /// \n\n    public func match(_ tree: ParseTree) throws -> ParseTreeMatch {\n        return try matcher.match(tree, self)\n    }\n\n    /// \n    /// Determine whether or not a parse tree matches this tree pattern.\n    /// \n    /// - Parameter tree: The parse tree to match against this tree pattern.\n    /// - Returns: `true` if `tree` is a match for the current tree\n    /// pattern; otherwise, `false`.\n    /// \n    public func matches(_ tree: ParseTree) throws -> Bool {\n        return try matcher.match(tree, self).succeeded()\n    }\n\n    /// \n    /// Find all nodes using XPath and then try to match those subtrees against\n    /// this tree pattern.\n    /// \n    /// - Parameter tree: The _org.antlr.v4.runtime.tree.ParseTree_ to match against this pattern.\n    /// - Parameter xpath: An expression matching the nodes\n    /// \n    /// - Returns: A collection of _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ objects describing the\n    /// successful matches. Unsuccessful matches are omitted from the result,\n    /// regardless of the reason for the failure.\n    /// \n\n    /*public func findAll(tree : ParseTree, _ xpath : String) -> Array<ParseTreeMatch> {\n        var subtrees : Array<ParseTree> = XPath.findAll(tree, xpath, matcher.getParser());\n        var matches : Array<ParseTreeMatch> = Array<ParseTreeMatch>();\n        for t : ParseTree in subtrees {\n            var match : ParseTreeMatch = match(t);\n            if ( match.succeeded() ) {\n                matches.add(match);\n            }\n        }\n        return matches;\n    }*/\n\n    /// \n    /// Get the _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ which created this tree pattern.\n    /// \n    /// - Returns: The _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ which created this tree\n    /// pattern.\n    /// \n\n    public func getMatcher() -> ParseTreePatternMatcher {\n        return matcher\n    }\n\n    /// \n    /// Get the tree pattern in concrete syntax form.\n    /// \n    /// - Returns: The tree pattern in concrete syntax form.\n    /// \n\n    public func getPattern() -> String {\n        return pattern\n    }\n\n    /// \n    /// Get the parser rule which serves as the outermost rule for the tree\n    /// pattern.\n    /// \n    /// - Returns: The parser rule which serves as the outermost rule for the tree\n    /// pattern.\n    /// \n    public func getPatternRuleIndex() -> Int {\n        return patternRuleIndex\n    }\n\n    /// \n    /// Get the tree pattern as a _org.antlr.v4.runtime.tree.ParseTree_. The rule and token tags from\n    /// the pattern are present in the parse tree as terminal nodes with a symbol\n    /// of type _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ or _org.antlr.v4.runtime.tree.pattern.TokenTagToken_.\n    /// \n    /// - Returns: The tree pattern as a _org.antlr.v4.runtime.tree.ParseTree_.\n    /// \n\n    public func getPatternTree() -> ParseTree {\n        return patternTree\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/ParseTreePatternMatcher.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// \n/// A tree pattern matching mechanism for ANTLR _org.antlr.v4.runtime.tree.ParseTree_s.\n/// \n/// Patterns are strings of source input text with special tags representing\n/// token or rule references such as:\n/// \n/// `<ID> = <expr>;`\n/// \n/// Given a pattern start rule such as `statement`, this object constructs\n/// a _org.antlr.v4.runtime.tree.ParseTree_ with placeholders for the `ID` and `expr`\n/// subtree. Then the _#match_ routines can compare an actual\n/// _org.antlr.v4.runtime.tree.ParseTree_ from a parse with this pattern. Tag `<ID>` matches\n/// any `ID` token and tag `<expr>` references the result of the\n/// `expr` rule (generally an instance of `ExprContext`.\n/// \n/// Pattern `x = 0;` is a similar pattern that matches the same pattern\n/// except that it requires the identifier to be `x` and the expression to\n/// be `0`.\n/// \n/// The _#matches_ routines return `true` or `false` based\n/// upon a match for the tree rooted at the parameter sent in. The\n/// _#match_ routines return a _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ object that\n/// contains the parse tree, the parse tree pattern, and a map from tag name to\n/// matched nodes (more below). A subtree that fails to match, returns with\n/// _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch#mismatchedNode_ set to the first tree node that did not\n/// match.\n/// \n/// For efficiency, you can compile a tree pattern in string form to a\n/// _org.antlr.v4.runtime.tree.pattern.ParseTreePattern_ object.\n/// \n/// See `TestParseTreeMatcher` for lots of examples.\n/// _org.antlr.v4.runtime.tree.pattern.ParseTreePattern_ has two static helper methods:\n/// _org.antlr.v4.runtime.tree.pattern.ParseTreePattern#findAll_ and _org.antlr.v4.runtime.tree.pattern.ParseTreePattern#match_ that\n/// are easy to use but not super efficient because they create new\n/// _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ objects each time and have to compile the\n/// pattern in string form before using it.\n/// \n/// The lexer and parser that you pass into the _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_\n/// constructor are used to parse the pattern in string form. The lexer converts\n/// the `<ID> = <expr>;` into a sequence of four tokens (assuming lexer\n/// throws out whitespace or puts it on a hidden channel). Be aware that the\n/// input stream is reset for the lexer (but not the parser; a\n/// _org.antlr.v4.runtime.ParserInterpreter_ is created to parse the input.). Any user-defined\n/// fields you have put into the lexer might get changed when this mechanism asks\n/// it to scan the pattern string.\n/// \n/// Normally a parser does not accept token `<expr>` as a valid\n/// `expr` but, from the parser passed in, we create a special version of\n/// the underlying grammar representation (an _org.antlr.v4.runtime.atn.ATN_) that allows imaginary\n/// tokens representing rules (`<expr>`) to match entire rules. We call\n/// these __bypass alternatives__.\n/// \n/// Delimiters are `<` and `>`, with `\\` as the escape string\n/// by default, but you can set them to whatever you want using\n/// _#setDelimiters_. You must escape both start and stop strings\n/// `\\<` and `\\>`.\n/// \n\npublic class ParseTreePatternMatcher {\n\n    /// \n    /// This is the backing field for _#getLexer()_.\n    /// \n    private final let lexer: Lexer\n\n    /// \n    /// This is the backing field for _#getParser()_.\n    /// \n    private final let parser: Parser\n\n    internal var start: String = \"<\"\n    internal var stop: String = \">\"\n    internal var escape: String = \"\\\\\"\n\n    /// \n    /// Constructs a _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ or from a _org.antlr.v4.runtime.Lexer_ and\n    /// _org.antlr.v4.runtime.Parser_ object. The lexer input stream is altered for tokenizing\n    /// the tree patterns. The parser is used as a convenient mechanism to get\n    /// the grammar name, plus token, rule names.\n    /// \n    public init(_ lexer: Lexer, _ parser: Parser) {\n        self.lexer = lexer\n        self.parser = parser\n    }\n\n    /// \n    /// Set the delimiters used for marking rule and token tags within concrete\n    /// syntax used by the tree pattern parser.\n    /// \n    /// - Parameter start: The start delimiter.\n    /// - Parameter stop: The stop delimiter.\n    /// - Parameter escapeLeft: The escape sequence to use for escaping a start or stop delimiter.\n    /// \n    /// - Throws: ANTLRError.ilegalArgument if `start` is `null` or empty.\n    /// - Throws: ANTLRError.ilegalArgument if `stop` is `null` or empty.\n    /// \n    public func setDelimiters(_ start: String, _ stop: String, _ escapeLeft: String) throws {\n        if start.isEmpty {\n            throw ANTLRError.illegalArgument(msg: \"start cannot be null or empty\")\n        }\n        if stop.isEmpty {\n            throw ANTLRError.illegalArgument(msg: \"stop cannot be null or empty\")\n        }\n\n        self.start = start\n        self.stop = stop\n        self.escape = escapeLeft\n    }\n\n    /// \n    /// Does `pattern` matched as rule `patternRuleIndex` match `tree`?\n    /// \n    public func matches(_ tree: ParseTree, _ pattern: String, _ patternRuleIndex: Int) throws -> Bool {\n        let p: ParseTreePattern = try compile(pattern, patternRuleIndex)\n        return try matches(tree, p)\n    }\n\n    /// \n    /// Does `pattern` matched as rule patternRuleIndex match tree? Pass in a\n    /// compiled pattern instead of a string representation of a tree pattern.\n    /// \n    public func matches(_ tree: ParseTree, _ pattern: ParseTreePattern) throws -> Bool {\n        let labels: MultiMap<String, ParseTree> = MultiMap<String, ParseTree>()\n        let mismatchedNode: ParseTree? = try matchImpl(tree, pattern.getPatternTree(), labels)\n        return mismatchedNode == nil\n    }\n\n    /// \n    /// Compare `pattern` matched as rule `patternRuleIndex` against\n    /// `tree` and return a _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ object that contains the\n    /// matched elements, or the node at which the match failed.\n    /// \n    public func match(_ tree: ParseTree, _ pattern: String, _ patternRuleIndex: Int) throws -> ParseTreeMatch {\n        let p: ParseTreePattern = try compile(pattern, patternRuleIndex)\n        return try match(tree, p)\n    }\n\n    /// \n    /// Compare `pattern` matched against `tree` and return a\n    /// _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ object that contains the matched elements, or the\n    /// node at which the match failed. Pass in a compiled pattern instead of a\n    /// string representation of a tree pattern.\n    /// \n    public func match(_ tree: ParseTree, _ pattern: ParseTreePattern) throws -> ParseTreeMatch {\n        let labels: MultiMap<String, ParseTree> = MultiMap<String, ParseTree>()\n        let mismatchedNode: ParseTree? = try matchImpl(tree, pattern.getPatternTree(), labels)\n        return ParseTreeMatch(tree, pattern, labels, mismatchedNode)\n    }\n\n    /// \n    /// For repeated use of a tree pattern, compile it to a\n    /// _org.antlr.v4.runtime.tree.pattern.ParseTreePattern_ using this method.\n    /// \n    public func compile(_ pattern: String, _ patternRuleIndex: Int) throws -> ParseTreePattern {\n        let tokenList = try tokenize(pattern)\n        let tokenSrc = ListTokenSource(tokenList)\n        let tokens = CommonTokenStream(tokenSrc)\n\n        let parserInterp = try ParserInterpreter(parser.getGrammarFileName(),\n                parser.getVocabulary(),\n                parser.getRuleNames(),\n                parser.getATNWithBypassAlts(),\n                tokens)\n\n        parserInterp.setErrorHandler(BailErrorStrategy())\n        let tree = try parserInterp.parse(patternRuleIndex)\n\n        // Make sure tree pattern compilation checks for a complete parse\n        if try tokens.LA(1) != CommonToken.EOF {\n            throw ANTLRError.illegalState(msg: \"Tree pattern compilation doesn't check for a complete parse\")\n        }\n\n        return ParseTreePattern(self, pattern, patternRuleIndex, tree)\n    }\n\n    /// \n    /// Used to convert the tree pattern string into a series of tokens. The\n    /// input stream is reset.\n    /// \n    public func getLexer() -> Lexer {\n        return lexer\n    }\n\n    /// \n    /// Used to collect to the grammar file name, token names, rule names for\n    /// used to parse the pattern into a parse tree.\n    /// \n    public func getParser() -> Parser {\n        return parser\n    }\n\n    // ---- SUPPORT CODE ----\n\n    /// \n    /// Recursively walk `tree` against `patternTree`, filling\n    /// `match.`_org.antlr.v4.runtime.tree.pattern.ParseTreeMatch#labels labels_.\n    /// \n    /// - Returns: the first node encountered in `tree` which does not match\n    /// a corresponding node in `patternTree`, or `null` if the match\n    /// was successful. The specific node returned depends on the matching\n    /// algorithm used by the implementation, and may be overridden.\n    /// \n    internal func matchImpl(_ tree: ParseTree,\n                            _ patternTree: ParseTree,\n                            _ labels: MultiMap<String, ParseTree>) throws -> ParseTree? {\n\n        // x and <ID>, x and y, or x and x; or could be mismatched types\n        if tree is TerminalNode && patternTree is TerminalNode {\n            let t1 = tree as! TerminalNode\n            let t2 = patternTree as! TerminalNode\n            var mismatchedNode: ParseTree? = nil\n            // both are tokens and they have same type\n            if t1.getSymbol()!.getType() == t2.getSymbol()!.getType() {\n                if t2.getSymbol() is TokenTagToken {\n                    // x and <ID>\n                    let tokenTagToken: TokenTagToken = t2.getSymbol() as! TokenTagToken\n                    // track label->list-of-nodes for both token name and label (if any)\n                    labels.map(tokenTagToken.getTokenName(), tree)\n                    if let label = tokenTagToken.getLabel() {\n                        labels.map(label, tree)\n                    }\n                } else {\n                    if t1.getText() == t2.getText() {\n                        // x and x\n                    } else {\n                        // x and y\n                        if mismatchedNode == nil {\n                            mismatchedNode = t1\n                        }\n                    }\n                }\n            } else {\n                if mismatchedNode == nil {\n                    mismatchedNode = t1\n                }\n            }\n\n            return mismatchedNode\n        }\n\n        if tree is ParserRuleContext && patternTree is ParserRuleContext {\n            let r1: ParserRuleContext = tree as! ParserRuleContext\n            let r2: ParserRuleContext = patternTree as! ParserRuleContext\n            var mismatchedNode: ParseTree? = nil\n            // (expr ...) and <expr>\n            if let ruleTagToken = getRuleTagToken(r2) {\n                if r1.getRuleContext().getRuleIndex() == r2.getRuleContext().getRuleIndex() {\n                    // track label->list-of-nodes for both rule name and label (if any)\n                    labels.map(ruleTagToken.getRuleName(), tree)\n                    if let label = ruleTagToken.getLabel() {\n                        labels.map(label, tree)\n                    }\n                } else {\n                    if mismatchedNode == nil {\n                        mismatchedNode = r1\n                    }\n                }\n\n                return mismatchedNode\n            }\n\n            // (expr ...) and (expr ...)\n            if r1.getChildCount() != r2.getChildCount() {\n                if mismatchedNode == nil {\n                    mismatchedNode = r1\n                }\n\n                return mismatchedNode\n            }\n\n            for i in 0 ..< r1.getChildCount() {\n                if let childMatch = try matchImpl(r1[i], patternTree[i], labels) {\n                    return childMatch\n                }\n            }\n\n            return mismatchedNode\n        }\n\n        // if nodes aren't both tokens or both rule nodes, can't match\n        return tree\n    }\n\n    /// Is `t` `(expr <expr>)` subtree?\n    internal func getRuleTagToken(_ t: ParseTree) -> RuleTagToken? {\n        if let ruleNode = t as? RuleNode,\n            ruleNode.getChildCount() == 1,\n            let terminalNode = ruleNode[0] as? TerminalNode,\n            let ruleTag = terminalNode.getSymbol() as? RuleTagToken {\n//            print(\"rule tag subtree \"+t.toStringTree(parser));\n            return ruleTag\n        }\n        return nil\n    }\n\n    public func tokenize(_ pattern: String) throws -> Array<Token> {\n        // split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)\n        let chunks = try split(pattern)\n\n        // create token stream from text and tags\n        var tokens = [Token]()\n        for chunk in chunks {\n            if let tagChunk = chunk as? TagChunk {\n                // add special rule token or conjure up new token from name\n                let firstStr = String(tagChunk.getTag().first!)\n                if firstStr.lowercased() != firstStr {\n                    let ttype = parser.getTokenType(tagChunk.getTag())\n                    if ttype == CommonToken.INVALID_TYPE {\n                        throw ANTLRError.illegalArgument(msg: \"Unknown token \" + tagChunk.getTag() + \" in pattern: \" + pattern)\n                    }\n                    let t = TokenTagToken(tagChunk.getTag(), ttype, tagChunk.getLabel())\n                    tokens.append(t)\n                } else {\n                    if firstStr.uppercased() != firstStr {\n                        let ruleIndex: Int = parser.getRuleIndex(tagChunk.getTag())\n                        if ruleIndex == -1 {\n                            throw ANTLRError.illegalArgument(msg: \"Unknown rule \" + tagChunk.getTag() + \" in pattern: \" + pattern)\n                        }\n                        let ruleImaginaryTokenType: Int = parser.getATNWithBypassAlts().ruleToTokenType[ruleIndex]\n                        tokens.append(RuleTagToken(tagChunk.getTag(), ruleImaginaryTokenType, tagChunk.getLabel()))\n                    } else {\n                        throw ANTLRError.illegalArgument(msg: \"invalid tag: \" + tagChunk.getTag() + \" in pattern: \" + pattern)\n                    }\n                }\n            } else {\n                let textChunk = chunk as! TextChunk\n                let inputStream = ANTLRInputStream(textChunk.getText())\n                try lexer.setInputStream(inputStream)\n                var t = try lexer.nextToken()\n                while t.getType() != CommonToken.EOF {\n                    tokens.append(t)\n                    t = try lexer.nextToken()\n                }\n            }\n        }\n\n//\t\tprint(\"tokens=\"+tokens);\n        return tokens\n    }\n\n    /// \n    /// Split `<ID> = <e:expr> ;` into 4 chunks for tokenizing by _#tokenize_.\n    /// \n    public func split(_ pattern: String) throws -> [Chunk] {\n        var p = pattern.startIndex\n        let n = pattern.endIndex\n        var chunks = [Chunk]()\n        // find all start and stop indexes first, then collect\n        var starts = [Range<String.Index>]()\n        var stops = [Range<String.Index>]()\n        let escapedStart = escape + start\n        let escapedStop = escape + stop\n        while p < n {\n            let slice = pattern[p...]\n            if slice.hasPrefix(escapedStart) {\n                p = pattern.index(p, offsetBy: escapedStart.count)\n            }\n            else if slice.hasPrefix(escapedStop) {\n                p = pattern.index(p, offsetBy: escapedStop.count)\n            }\n            else if slice.hasPrefix(start) {\n                let upperBound = pattern.index(p, offsetBy: start.count)\n                starts.append(p ..< upperBound)\n                p = upperBound\n            }\n            else if slice.hasPrefix(stop) {\n                let upperBound = pattern.index(p, offsetBy: stop.count)\n                stops.append(p ..< upperBound)\n                p = upperBound\n            }\n            else {\n                p = pattern.index(after: p)\n            }\n        }\n\n        if starts.count > stops.count {\n            throw ANTLRError.illegalArgument(msg: \"unterminated tag in pattern: \" + pattern)\n        }\n\n        if starts.count < stops.count {\n            throw ANTLRError.illegalArgument(msg: \"missing start tag in pattern: \" + pattern)\n        }\n\n        let ntags = starts.count\n        for i in 0..<ntags {\n            if starts[i].lowerBound >= stops[i].lowerBound {\n                throw ANTLRError.illegalArgument(msg: \"tag delimiters out of order in pattern: \" + pattern)\n            }\n        }\n\n        // collect into chunks now\n        if ntags == 0 {\n            let text = String(pattern[..<n])\n            chunks.append(TextChunk(text))\n        }\n\n        if ntags > 0 && starts[0].lowerBound > pattern.startIndex {\n            // copy text up to first tag into chunks\n            let text = pattern[pattern.startIndex ..< starts[0].lowerBound]\n            chunks.append(TextChunk(String(text)))\n        }\n\n        for i in 0 ..< ntags {\n            // copy inside of <tag>\n            let tag = pattern[starts[i].upperBound ..< stops[i].lowerBound]\n            let ruleOrToken: String\n            let label: String?\n            let bits = tag.split(separator: \":\", maxSplits: 1)\n            if bits.count == 2 {\n                label = String(bits[0])\n                ruleOrToken = String(bits[1])\n            }\n            else {\n                label = nil\n                ruleOrToken = String(tag)\n            }\n            chunks.append(try TagChunk(label, ruleOrToken))\n            if i + 1 < ntags {\n                // copy from end of <tag> to start of next\n                let text = pattern[stops[i].upperBound ..< starts[i + 1].lowerBound]\n                chunks.append(TextChunk(String(text)))\n            }\n        }\n        if ntags > 0 {\n            let afterLastTag = stops[ntags - 1].upperBound\n            if afterLastTag < n {\n                // copy text from end of last tag to end\n                let text = pattern[afterLastTag ..< n]\n                chunks.append(TextChunk(String(text)))\n            }\n        }\n\n        // strip out the escape sequences from text chunks but not tags\n        for i in 0 ..< chunks.count {\n            let c = chunks[i]\n            if let tc = c as? TextChunk {\n                let unescaped = tc.getText().replacingOccurrences(of: escape, with: \"\")\n                if unescaped.count < tc.getText().count {\n                    chunks[i] = TextChunk(unescaped)\n                }\n            }\n        }\n\n        return chunks\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/RuleTagToken.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// \n/// A _org.antlr.v4.runtime.Token_ object representing an entire subtree matched by a parser\n/// rule; e.g., `<expr>`. These tokens are created for _org.antlr.v4.runtime.tree.pattern.TagChunk_\n/// chunks where the tag corresponds to a parser rule.\n/// \n\npublic class RuleTagToken: Token, CustomStringConvertible {\n    /// \n    /// This is the backing field for _#getRuleName_.\n    /// \n    private let ruleName: String\n    /// \n    /// The token type for the current token. This is the token type assigned to\n    /// the bypass alternative for the rule during ATN deserialization.\n    /// \n    private let bypassTokenType: Int\n    /// \n    /// This is the backing field for _#getLabel_.\n    /// \n    private let label: String?\n\n    public var visited = false\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ with the specified rule\n    /// name and bypass token type and no label.\n    /// \n    /// - Parameter ruleName: The name of the parser rule this rule tag matches.\n    /// - Parameter bypassTokenType: The bypass token type assigned to the parser rule.\n    /// \n    /// - Throws: ANTLRError.illegalArgument if `ruleName` is `null`\n    /// or empty.\n    /// \n    public convenience init(_ ruleName: String, _ bypassTokenType: Int) {\n        self.init(ruleName, bypassTokenType, nil)\n    }\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ with the specified rule\n    /// name, bypass token type, and label.\n    /// \n    /// - Parameter ruleName: The name of the parser rule this rule tag matches.\n    /// - Parameter bypassTokenType: The bypass token type assigned to the parser rule.\n    /// - Parameter label: The label associated with the rule tag, or `null` if\n    /// the rule tag is unlabeled.\n    /// \n    /// - Throws: ANTLRError.illegalArgument if `ruleName` is `null`\n    /// or empty.\n    /// \n    public init(_ ruleName: String, _ bypassTokenType: Int, _ label: String?) {\n        self.ruleName = ruleName\n        self.bypassTokenType = bypassTokenType\n        self.label = label\n    }\n\n    /// \n    /// Gets the name of the rule associated with this rule tag.\n    /// \n    /// - Returns: The name of the parser rule associated with this rule tag.\n    /// \n    public final func getRuleName() -> String {\n        return ruleName\n    }\n\n    /// \n    /// Gets the label associated with the rule tag.\n    /// \n    /// - Returns: The name of the label associated with the rule tag, or\n    /// `null` if this is an unlabeled rule tag.\n    /// \n    public final func getLabel() -> String? {\n        return label\n    }\n\n    /// \n    /// Rule tag tokens are always placed on the _#DEFAULT_CHANNEL_.\n    /// \n    public func getChannel() -> Int {\n        return RuleTagToken.DEFAULT_CHANNEL\n    }\n\n    /// \n    /// This method returns the rule tag formatted with `<` and `>`\n    /// delimiters.\n    /// \n    public func getText() -> String? {\n        if let label = label {\n            return \"<\\(label):\\(ruleName)>\"\n        }\n        return \"<\\(ruleName)>\"\n    }\n\n    /// \n    /// Rule tag tokens have types assigned according to the rule bypass\n    /// transitions created during ATN deserialization.\n    /// \n    public func getType() -> Int {\n        return bypassTokenType\n    }\n\n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns 0.\n    /// \n    public func getLine() -> Int {\n        return 0\n    }\n\n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1.\n    /// \n    public func getCharPositionInLine() -> Int {\n        return -1\n    }\n\n    /// \n    /// \n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1.\n    /// \n    public func getTokenIndex() -> Int {\n        return -1\n    }\n\n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1.\n    /// \n    public func getStartIndex() -> Int {\n        return -1\n    }\n\n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1.\n    /// \n    public func getStopIndex() -> Int {\n        return -1\n    }\n\n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns `null`.\n    /// \n    public func getTokenSource() -> TokenSource? {\n        return nil\n    }\n\n    ///\n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns `null`.\n    /// \n    public func getInputStream() -> CharStream? {\n        return nil\n    }\n\n    public func getTokenSourceAndStream() -> TokenSourceAndStream {\n        return TokenSourceAndStream.EMPTY\n    }\n\n    ///\n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ returns a string of the form\n    /// `ruleName:bypassTokenType`.\n    /// \n    public var description: String {\n        return ruleName + \":\" + String(bypassTokenType)\n    }\n\n\n}\n\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/TagChunk.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// Represents a placeholder tag in a tree pattern. A tag can have any of the\n/// following forms.\n/// \n/// * `expr`: An unlabeled placeholder for a parser rule `expr`.\n/// * `ID`: An unlabeled placeholder for a token of type `ID`.\n/// * `e:expr`: A labeled placeholder for a parser rule `expr`.\n/// * `id:ID`: A labeled placeholder for a token of type `ID`.\n/// \n/// This class does not perform any validation on the tag or label names aside\n/// from ensuring that the tag is a non-null, non-empty string.\n/// \npublic class TagChunk: Chunk, CustomStringConvertible {\n    /// \n    /// This is the backing field for _#getTag_.\n    /// \n    private let tag: String\n    /// \n    /// This is the backing field for _#getLabel_.\n    /// \n    private let label: String?\n\n    /// \n    /// Construct a new instance of _org.antlr.v4.runtime.tree.pattern.TagChunk_ using the specified tag and\n    /// no label.\n    /// \n    /// - Parameter tag: The tag, which should be the name of a parser rule or token\n    /// type.\n    /// \n    /// - Throws: ANTLRError.illegalArgument if `tag` is `null` or\n    /// empty.\n    /// \n    public convenience init(_ tag: String) throws {\n        try self.init(nil, tag)\n    }\n\n    /// \n    /// Construct a new instance of _org.antlr.v4.runtime.tree.pattern.TagChunk_ using the specified label\n    /// and tag.\n    /// \n    /// - Parameter label: The label for the tag. If this is `null`, the\n    /// _org.antlr.v4.runtime.tree.pattern.TagChunk_ represents an unlabeled tag.\n    /// - Parameter tag: The tag, which should be the name of a parser rule or token\n    /// type.\n    /// \n    /// - Throws: ANTLRError.illegalArgument if `tag` is `null` or\n    /// empty.\n    /// \n    public init(_ label: String?, _ tag: String) throws {\n\n        self.label = label\n        self.tag = tag\n        super.init()\n        if tag.isEmpty {\n            throw ANTLRError.illegalArgument(msg: \"tag cannot be null or empty\")\n        }\n    }\n\n    /// \n    /// Get the tag for this chunk.\n    /// \n    /// - Returns: The tag for the chunk.\n    /// \n    public final func getTag() -> String {\n        return tag\n    }\n\n    /// \n    /// Get the label, if any, assigned to this chunk.\n    /// \n    /// - Returns: The label assigned to this chunk, or `null` if no label is\n    /// assigned to the chunk.\n    /// \n    public final func getLabel() -> String? {\n        return label\n    }\n\n    /// \n    /// This method returns a text representation of the tag chunk. Labeled tags\n    /// are returned in the form `label:tag`, and unlabeled tags are\n    /// returned as just the tag name.\n    /// \n    public var description: String {\n        if let label = label {\n            return \"\\(label):\\(tag)\"\n        }\n        else {\n            return tag\n        }\n    }\n\n\n    override public func isEqual(_ other: Chunk) -> Bool {\n        guard let other = other as? TagChunk else {\n            return false\n        }\n        return tag == other.tag && label == other.label\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/TextChunk.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n/// \n/// Represents a span of raw text (concrete syntax) between tags in a tree\n/// pattern string.\n/// \n\npublic class TextChunk: Chunk, CustomStringConvertible {\n    /// \n    /// This is the backing field for _#getText_.\n    /// \n\n    private let text: String\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.TextChunk_ with the specified text.\n    /// \n    /// - Parameter text: The text of this chunk.\n    /// - Throws: ANTLRError.illegalArgument if `text` is `null`.\n    /// \n    public init(_ text: String) {\n        self.text = text\n    }\n\n    /// \n    /// Gets the raw text of this chunk.\n    /// \n    /// - Returns: The text of the chunk.\n    /// \n\n    public final func getText() -> String {\n        return text\n    }\n\n    ///\n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.TextChunk_ returns the result of\n    /// _#getText()_ in single quotes.\n    ///\n    public var description: String {\n        return \"'\\(text)'\"\n    }\n\n\n    override public func isEqual(_ other: Chunk) -> Bool {\n        guard let other = other as? TextChunk else {\n            return false\n        }\n        return text == other.text\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Antlr4/tree/pattern/TokenTagToken.swift",
    "content": "/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\n\n\n/// \n/// A _org.antlr.v4.runtime.Token_ object representing a token of a particular type; e.g.,\n/// `<ID>`. These tokens are created for _org.antlr.v4.runtime.tree.pattern.TagChunk_ chunks where the\n/// tag corresponds to a lexer rule or token type.\n/// \n\npublic class TokenTagToken: CommonToken {\n    /// \n    /// This is the backing field for _#getTokenName_.\n    /// \n\n    private let tokenName: String\n    /// \n    /// This is the backing field for _#getLabel_.\n    /// \n\n    private let label: String?\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ for an unlabeled tag\n    /// with the specified token name and type.\n    /// \n    /// - Parameter tokenName: The token name.\n    /// - Parameter type: The token type.\n    /// \n    public convenience init(_ tokenName: String, _ type: Int) {\n        self.init(tokenName, type, nil)\n    }\n\n    /// \n    /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ with the specified\n    /// token name, type, and label.\n    /// \n    /// - Parameter tokenName: The token name.\n    /// - Parameter type: The token type.\n    /// - Parameter label: The label associated with the token tag, or `null` if\n    /// the token tag is unlabeled.\n    /// \n    public init(_ tokenName: String, _ type: Int, _ label: String?) {\n\n        self.tokenName = tokenName\n        self.label = label\n        super.init(type)\n    }\n\n    /// \n    /// Gets the token name.\n    /// - Returns: The token name.\n    /// \n\n    public final func getTokenName() -> String {\n        return tokenName\n    }\n\n    /// \n    /// Gets the label associated with the rule tag.\n    /// \n    /// - Returns: The name of the label associated with the rule tag, or\n    /// `null` if this is an unlabeled rule tag.\n    /// \n\n    public final func getLabel() -> String? {\n        return label\n    }\n\n    /// \n    /// \n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ returns the token tag\n    /// formatted with `<` and `>` delimiters.\n    /// \n    override\n    public func getText() -> String {\n        if let label = label {\n            return \"<\" + label + \":\" + tokenName + \">\"\n        }\n\n        return \"<\" + tokenName + \">\"\n    }\n\n    /// \n    /// \n    /// \n    /// The implementation for _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ returns a string of the form\n    /// `tokenName:type`.\n    /// \n\n    override\n    public var description: String {\n        return tokenName + \":\" + String(type)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Sources/Info-IOS.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>FMWK</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>NSPrincipalClass</key>\n\t<string></string>\n</dict>\n</plist>\n"
  },
  {
    "path": "runtime/Swift/Sources/Info-OSX.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>FMWK</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>NSPrincipalClass</key>\n\t<string></string>\n</dict>\n</plist>\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/ANTLRInputStreamTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport Foundation\n\nimport XCTest\nimport Antlr4\n\nclass ANTLRInputStreamTests: XCTestCase {\n    func testASCIICharactersString() {\n        let inputStream = ANTLRInputStream(\"Cat\")\n        XCTAssertEqual(inputStream.LA(1), 0x0043)\n        XCTAssertEqual(inputStream.LA(2), 0x0061)\n        XCTAssertEqual(inputStream.LA(3), 0x0074)\n    }\n\n    func testBasicMultilingualPlaneCharactersString() {\n        // Three Japanese hiragana characters.\n        let inputStream = ANTLRInputStream(\"\\u{3053}\\u{306D}\\u{3053}\")\n        XCTAssertEqual(inputStream.LA(1), 0x3053)\n        XCTAssertEqual(inputStream.LA(2), 0x306D)\n        XCTAssertEqual(inputStream.LA(3), 0x3053)\n    }\n\n    func testSupplementaryMultilingualPlaneCharactersString() {\n        // Three \"Cat\", \"Cat Face\", and \"Grinning Cat with Smiling Eyes\" emojis\n        let inputStream = ANTLRInputStream(\"\\u{1F408}\\u{1F431}\\u{1F638}\")\n        XCTAssertEqual(inputStream.LA(1), 0x1F408)\n        XCTAssertEqual(inputStream.LA(2), 0x1F431)\n        XCTAssertEqual(inputStream.LA(3), 0x1F638)\n    }\n\n    func testGraphemeCharactersString() {\n        // One \"Family (Man, Woman, Girl, Boy)\" emoji\n        let inputStream = ANTLRInputStream(\"\\u{1F468}\\u{200D}\\u{1F469}\\u{200D}\\u{1F467}\\u{200D}\\u{1F466}\")\n        XCTAssertEqual(inputStream.LA(1), 0x1F468)\n        XCTAssertEqual(inputStream.LA(2), 0x200D)\n        XCTAssertEqual(inputStream.LA(3), 0x1F469)\n        XCTAssertEqual(inputStream.LA(4), 0x200D)\n        XCTAssertEqual(inputStream.LA(5), 0x1F467)\n        XCTAssertEqual(inputStream.LA(6), 0x200D)\n        XCTAssertEqual(inputStream.LA(7), 0x1F466)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/InterpreterDataTests.swift",
    "content": "/// Copyright (c) 2021 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport XCTest\nimport Antlr4\n\nclass InterpreterDataTests: XCTestCase {\n\n    // https://stackoverflow.com/a/57713176\n    let sourceDir = URL(fileURLWithPath:#file).deletingLastPathComponent()\n\n    func testLexerA() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let interpPath = sourceDir.appendingPathComponent(\"gen/LexerA.interp\").path\n        let data = try InterpreterDataReader(interpPath)\n        let lexer = try data.createLexer(input:input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let result = try stream.getText()\n        let expecting = \"abc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testLexerB() throws {\n        let input = ANTLRInputStream(\"x = 3 * 0 + 2 * 0;\")\n        let interpPath = sourceDir.appendingPathComponent(\"gen/LexerB.interp\").path\n        let data = try InterpreterDataReader(interpPath)\n        let lexer = try data.createLexer(input:input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let result = try stream.getText()\n        let expecting = \"x = 3 * 0 + 2 * 0;\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testCalculator() throws {\n        let input = \"2 + 8 / 2\"\n        let lexerInterpPath = sourceDir.appendingPathComponent(\"gen/VisitorCalcLexer.interp\").path\n        let lexerInterpData = try InterpreterDataReader(lexerInterpPath)\n        let lexer = try lexerInterpData.createLexer(input:ANTLRInputStream(input))\n        let parserInterpPath = sourceDir.appendingPathComponent(\"gen/VisitorCalc.interp\").path\n        let parserInterpData = try InterpreterDataReader(parserInterpPath)\n        let parser = try parserInterpData.createParser(input:CommonTokenStream(lexer))\n\n        let context = try parser.parse(parser.getRuleIndex(\"s\"))\n        XCTAssertEqual(\"(s (expr (expr 2) + (expr (expr 8) / (expr 2))) <EOF>)\", context.toStringTree(parser))\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/LexerA.g4",
    "content": "lexer grammar LexerA;\nA : 'a';\nB : 'b';\nC : 'c';\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/LexerB.g4",
    "content": "lexer grammar LexerB;\nID : 'a'..'z'+;\nINT : '0'..'9'+;\nSEMI : ';';\nMUL : '*';\nPLUS : '+';\nASSIGN : '=';\nWS : ' '+;\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/MurmurHashTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\n/// The test patterns below are by Ian Boyd and have been released into the\n/// public domain.\n/// https://stackoverflow.com/questions/14747343/murmurhash3-test-vectors\n\nimport XCTest\nimport Antlr4\n\nclass MurmurHashTests: XCTestCase {\n\n    func testMurmurHash() {\n        doMurmurHashTest(\"\", 0, 0) //empty string with zero seed should give zero\n        doMurmurHashTest(\"\", 1, 0x514E28B7)\n        doMurmurHashTest(\"\", 0xffffffff, 0x81F16F39) //make sure seed value is handled unsigned\n        doMurmurHashTest(\"\\0\\0\\0\\0\", 0, 0x2362F9DE) //make sure we handle embedded nulls\n\n        doMurmurHashTest(\"aaaa\", 0x9747b28c, 0x5A97808A) //one full chunk\n        doMurmurHashTest(\"aaa\", 0x9747b28c, 0x283E0130) //three characters\n        doMurmurHashTest(\"aa\", 0x9747b28c, 0x5D211726) //two characters\n        doMurmurHashTest(\"a\", 0x9747b28c, 0x7FA09EA6) //one character\n\n        //Endian order within the chunks\n        doMurmurHashTest(\"abcd\", 0x9747b28c, 0xF0478627) //one full chunk\n        doMurmurHashTest(\"abc\", 0x9747b28c, 0xC84A62DD)\n        doMurmurHashTest(\"ab\", 0x9747b28c, 0x74875592)\n        doMurmurHashTest(\"a\", 0x9747b28c, 0x7FA09EA6)\n\n        doMurmurHashTest(\"Hello, world!\", 0x9747b28c, 0x24884CBA)\n\n        //Make sure you handle UTF-8 high characters. A bcrypt implementation messed this up\n        doMurmurHashTest(\"ππππππππ\", 0x9747b28c, 0xD58063C1) //U+03C0: Greek Small Letter Pi\n\n        //String of 256 characters.\n        doMurmurHashTest(String(repeating: \"a\", count: 256), 0x9747b28c, 0x37405BDC)\n\n        doMurmurHashTest(\"abc\", 0, 0xB3DD93FA)\n        doMurmurHashTest(\"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\", 0, 0xEE925B90)\n        doMurmurHashTest(\"The quick brown fox jumps over the lazy dog\", 0x9747b28c, 0x2FA826CD)\n    }\n}\n\nprivate func doMurmurHashTest(_ input: String, _ seed: UInt32, _ expected: UInt32) {\n    XCTAssertEqual(MurmurHash.hashString(input, seed), expected)\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/ParseTreePatternMatcherTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport Foundation\nimport XCTest\nimport Antlr4\n\nclass ParseTreePatternMatcherTests: XCTestCase {\n\n    func testSplit() throws {\n        try doSplitTest(\"\", [TextChunk(\"\")])\n        try doSplitTest(\"Foo\", [TextChunk(\"Foo\")])\n        try doSplitTest(\"<ID> = <e:expr> ;\",\n                        [TagChunk(\"ID\"), TextChunk(\" = \"), TagChunk(\"e\", \"expr\"), TextChunk(\" ;\")])\n        try doSplitTest(\"\\\\<ID\\\\> = <e:expr> ;\",\n                        [TextChunk(\"<ID> = \"), TagChunk(\"e\", \"expr\"), TextChunk(\" ;\")])\n    }\n}\n\nprivate func doSplitTest(_ input: String, _ expected: [Chunk]) throws {\n    let matcher = try makeMatcher()\n    XCTAssertEqual(try matcher.split(input), expected)\n}\n\nprivate func makeMatcher() throws -> ParseTreePatternMatcher {\n    // The lexer and parser here aren't actually used.  They're just here\n    // so that ParseTreePatternMatcher can be constructed, but in this file\n    // we're currently only testing methods that don't depend on them.\n    let lexer = Lexer()\n    let ts = BufferedTokenStream(lexer)\n    let parser = try Parser(ts)\n    return ParseTreePatternMatcher(lexer, parser)\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/RuntimeMetaDataTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport Foundation\nimport XCTest\nimport Antlr4\n\nclass RuntimeMetaDataTests: XCTestCase {\n\n    func testGetMajorMinorVersion() {\n        doGetMajorMinorVersionTest(\"\", \"\")\n        doGetMajorMinorVersionTest(\"4\", \"4\")\n        doGetMajorMinorVersionTest(\"4.\", \"4.\")\n        doGetMajorMinorVersionTest(\"4.7\", \"4.7\")\n        doGetMajorMinorVersionTest(\"4.7.1\", \"4.7\")\n        doGetMajorMinorVersionTest(\"4.7.2\", \"4.7\")\n        doGetMajorMinorVersionTest(\"4.8\", \"4.8\")\n        doGetMajorMinorVersionTest(\"4.9\", \"4.9\")\n        doGetMajorMinorVersionTest(\"4.9.1\", \"4.9\")\n        doGetMajorMinorVersionTest(\"4.9.2\", \"4.9\")\n        doGetMajorMinorVersionTest(\"4.9.3\", \"4.9\")\n        doGetMajorMinorVersionTest(\"4-SNAPSHOT\", \"4\")\n        doGetMajorMinorVersionTest(\"4.-SNAPSHOT\", \"4.\")\n        doGetMajorMinorVersionTest(\"4.7-SNAPSHOT\", \"4.7\")\n        doGetMajorMinorVersionTest(\"4.7.1-SNAPSHOT\", \"4.7\")\n        doGetMajorMinorVersionTest(\"4.7.2-SNAPSHOT\", \"4.7\")\n        doGetMajorMinorVersionTest(\"4.9.1-SNAPSHOT\", \"4.9\")\n        doGetMajorMinorVersionTest(\"4.9.2-SNAPSHOT\", \"4.9\")\n        doGetMajorMinorVersionTest(\"4.9.3-SNAPSHOT\", \"4.9\")\n        doGetMajorMinorVersionTest(\"4.10-SNAPSHOT\", \"4.10\")\n        doGetMajorMinorVersionTest(\"4.10.1\", \"4.10\")\n        doGetMajorMinorVersionTest(\"4.11.0\", \"4.11\")\n        doGetMajorMinorVersionTest(\"4.11.1\", \"4.11\")\n        doGetMajorMinorVersionTest(\"4.11.0-SNAPSHOT\", \"4.11\")\n        doGetMajorMinorVersionTest(\"4.11.1-SNAPSHOT\", \"4.11\")\n        doGetMajorMinorVersionTest(\"4.12.0-SNAPSHOT\", \"4.12\")\n        doGetMajorMinorVersionTest(\"4.12.0\", \"4.12\")\n        doGetMajorMinorVersionTest(\"4.13.0-SNAPSHOT\", \"4.13\")\n        doGetMajorMinorVersionTest(\"4.13.0\", \"4.13\")\n        doGetMajorMinorVersionTest(\"4.13.1\", \"4.13\")\n    }\n}\n\nprivate func doGetMajorMinorVersionTest(_ input: String, _ expected: String) {\n    XCTAssertEqual(RuntimeMetaData.getMajorMinorVersion(input), expected)\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/StringExtensionTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport Foundation\nimport XCTest\n@testable import Antlr4\n\nclass StringExtensionTests: XCTestCase {\n\n    func testLastIndex() {\n        doLastIndexTest(\"\", \"\", nil)\n        doLastIndexTest(\"a\", \"\", nil)\n        doLastIndexTest(\"a\", \"a\", 0)\n        doLastIndexTest(\"aba\", \"a\", 2)\n        doLastIndexTest(\"aba\", \"b\", 1)\n        doLastIndexTest(\"abc\", \"d\", nil)\n    }\n\n}\n\nprivate func doLastIndexTest(_ str: String, _ target: String, _ expectedOffset: Int?) {\n    let expectedIdx: String.Index?\n    if let expectedOffset = expectedOffset {\n        expectedIdx = str.index(str.startIndex, offsetBy: expectedOffset)\n    }\n    else {\n        expectedIdx = nil\n    }\n    XCTAssertEqual(str.lastIndex(of: target), expectedIdx)\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/Threading.g4",
    "content": "grammar Threading;\n\ns\n    :   expr EOF\n    ;\n\nexpr\n    :   INT                     # number\n    |   expr (MUL | DIV) expr   # multiply\n    |   expr (ADD | SUB) expr   # add\n    ;\n\nINT : [0-9]+;\nMUL : '*';\nDIV : '/';\nADD : '+';\nSUB : '-';\nWS : [ \\t]+ -> channel(HIDDEN);\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/ThreadingTests.swift",
    "content": "/// Copyright (c) 2012-2021 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport XCTest\nimport Antlr4\n\nclass ThreadingTests: XCTestCase {\n    static let allTests = [\n        (\"testParallelExecution\", testParallelExecution),\n    ]\n\n    ///\n    /// This test verifies parallel execution of the parser\n    ///\n    func testParallelExecution() throws {\n        let input = [\n            \"2 * 8 - 4\",\n            \"2 + 8 / 4\",\n            \"2 - 8 - 4\",\n            \"2 * 8 * 4\",\n            \"2 / 8 / 4\",\n            \"2 + 8 + 4\",\n            \"890\",\n        ]\n        let exp = expectation(description: \"Waiting on async-task\")\n        exp.expectedFulfillmentCount = 100\n        for i in 1...100 {\n            DispatchQueue.global().async {\n                let lexer = ThreadingLexer(ANTLRInputStream(input[i % 7]))\n                let tokenStream = CommonTokenStream(lexer)\n                let parser = try? ThreadingParser(tokenStream)\n\n                let _ = try? parser?.s()\n\n                exp.fulfill()\n            }\n        }\n\n        waitForExpectations(timeout: 30.0) { (_) in\n            print(\"Completed\")\n        }\n    }\n}"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/TokenStreamRewriterTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport XCTest\nimport Antlr4\n\nclass TokenStreamRewriterTests: XCTestCase {\n    \n    static let allTests = [\n        (\"testPreservesOrderOfContiguousInserts\", testPreservesOrderOfContiguousInserts),\n        (\"testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder2\", testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder2),\n        (\"testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder\", testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder),\n        (\"testInsertBeforeTokenThenDeleteThatToken\", testInsertBeforeTokenThenDeleteThatToken),\n        (\"testLeaveAloneDisjointInsert2\", testLeaveAloneDisjointInsert2),\n        (\"testLeaveAloneDisjointInsert\", testLeaveAloneDisjointInsert),\n        (\"testDropPrevCoveredInsert\", testDropPrevCoveredInsert),\n        (\"testDropIdenticalReplace\", testDropIdenticalReplace),\n        (\"testOverlappingReplace4\", testOverlappingReplace4),\n        (\"testOverlappingReplace3\", testOverlappingReplace3),\n        (\"testOverlappingReplace2\", testOverlappingReplace2),\n        (\"testOverlappingReplace\", testOverlappingReplace),\n        (\"testDisjointInserts\", testDisjointInserts),\n        (\"testCombineInsertOnLeftWithDelete\", testCombineInsertOnLeftWithDelete),\n        (\"testCombineInsertOnLeftWithReplace\", testCombineInsertOnLeftWithReplace),\n        (\"testCombine3Inserts\", testCombine3Inserts),\n        (\"testCombineInserts\", testCombineInserts),\n        (\"testReplaceSingleMiddleThenOverlappingSuperset\", testReplaceSingleMiddleThenOverlappingSuperset),\n        (\"testReplaceThenReplaceLowerIndexedSuperset\", testReplaceThenReplaceLowerIndexedSuperset),\n        (\"testReplaceThenReplaceSuperset\", testReplaceThenReplaceSuperset),\n        (\"testReplaceSubsetThenFetch\", testReplaceSubsetThenFetch),\n        (\"testReplaceAll\", testReplaceAll),\n        (\"testReplaceRangeThenInsertAfterRightEdge\", testReplaceRangeThenInsertAfterRightEdge),\n        (\"testReplaceRangeThenInsertAtRightEdge\", testReplaceRangeThenInsertAtRightEdge),\n        (\"testReplaceThenInsertAtLeftEdge\", testReplaceThenInsertAtLeftEdge),\n        (\"testReplaceThenInsertAfterLastIndex\", testReplaceThenInsertAfterLastIndex),\n        (\"testInsertThenReplaceLastIndex\", testInsertThenReplaceLastIndex),\n        (\"testReplaceThenInsertBeforeLastIndex\", testReplaceThenInsertBeforeLastIndex),\n        (\"test2InsertThenReplaceIndex0\", test2InsertThenReplaceIndex0),\n        (\"test2InsertMiddleIndex\", test2InsertMiddleIndex),\n        (\"testInsertThenReplaceSameIndex\", testInsertThenReplaceSameIndex),\n        (\"testInsertInPriorReplace\", testInsertInPriorReplace),\n        (\"testReplaceThenDeleteMiddleIndex\", testReplaceThenDeleteMiddleIndex),\n        (\"test2ReplaceMiddleIndex1InsertBefore\", test2ReplaceMiddleIndex1InsertBefore),\n        (\"test2ReplaceMiddleIndex\", test2ReplaceMiddleIndex),\n        (\"testToStringStartStop2\", testToStringStartStop2),\n        (\"testToStringStartStop\", testToStringStartStop),\n        (\"testReplaceMiddleIndex\", testReplaceMiddleIndex),\n        (\"testReplaceLastIndex\", testReplaceLastIndex),\n        (\"testReplaceIndex0\", testReplaceIndex0),\n        (\"test2InsertBeforeAfterMiddleIndex\", test2InsertBeforeAfterMiddleIndex),\n        (\"testInsertAfterLastIndex\", testInsertAfterLastIndex),\n        (\"testInsertBeforeIndex0\", testInsertBeforeIndex0)\n    ]\n    \n    func testInsertBeforeIndex0() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"0\")\n        let result = try tokens.getText()\n        let expecting = \"0abc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testInsertAfterLastIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertAfter(2, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"abcx\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func test2InsertBeforeAfterMiddleIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(1, \"x\")\n        tokens.insertAfter(1, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"axbxc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceIndex0() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(0, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"xbc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceLastIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"abx\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceMiddleIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(1, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"axc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testToStringStartStop() throws {\n        // Tokens: 0123456789\n        // Input:  x = 3 * 0\n        let input = ANTLRInputStream(\"x = 3 * 0;\")\n        let lexer = LexerB(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n\n        // replace 3 * 0 with 0\n        try tokens.replace(4, 8, \"0\")\n        try stream.fill()\n\n        var result = try tokens.getTokenStream().getText()\n        var expecting = \"x = 3 * 0;\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText()\n        expecting = \"x = 0;\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText(Interval.of(0, 9))\n        expecting = \"x = 0;\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText(Interval.of(4, 8))\n        expecting = \"0\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testToStringStartStop2() throws {\n        // Tokens: 012345678901234567\n        // Input:  x = 3 * 0 + 2 * 0;\n        let input = ANTLRInputStream(\"x = 3 * 0 + 2 * 0;\")\n        let lexer = LexerB(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n\n        var result = try tokens.getTokenStream().getText()\n        var expecting = \"x = 3 * 0 + 2 * 0;\"\n        XCTAssertEqual(expecting, result)\n\n        // replace 3 * 0 with 0\n        try tokens.replace(4, 8, \"0\")\n        try stream.fill()\n\n        result = try tokens.getText()\n        expecting = \"x = 0 + 2 * 0;\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText(Interval.of(0, 17))\n        expecting = \"x = 0 + 2 * 0;\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText(Interval.of(4, 8))\n        expecting = \"0\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText(Interval.of(0, 8))\n        expecting = \"x = 0\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText(Interval.of(12, 16))\n        expecting = \"2 * 0\"\n        XCTAssertEqual(expecting, result)\n\n        tokens.insertAfter(17, \"// comment\")\n        result = try tokens.getText(Interval.of(12, 18))\n        expecting = \"2 * 0;// comment\"\n        XCTAssertEqual(expecting, result)\n\n        result = try tokens.getText(Interval.of(0, 8))\n        try stream.fill()\n        // try again after insert at end\n        expecting = \"x = 0\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func test2ReplaceMiddleIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(1, \"x\")\n        try tokens.replace(1, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"ayc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func test2ReplaceMiddleIndex1InsertBefore() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"_\")\n        try tokens.replace(1, \"x\")\n        try tokens.replace(1, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"_ayc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceThenDeleteMiddleIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(1, \"x\")\n        try tokens.delete(1)\n        let result = try tokens.getText()\n        let expecting = \"ac\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testInsertInPriorReplace() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(0, 2, \"x\")\n        tokens.insertBefore(1, \"0\")\n\n        do {\n            _ = try tokens.getText()\n            XCTFail(\"Expected exception not thrown.\")\n        } catch ANTLRError.illegalArgument(let msg) {\n            let expecting = \"insert op <InsertBeforeOp@[@1,1:1='b',<2>,1:1]:\\\"0\\\"> within boundaries of previous <ReplaceOp@[@0,0:0='a',<1>,1:0]..[@2,2:2='c',<3>,1:2]:\\\"x\\\">\"\n\n            XCTAssertEqual(expecting, msg)\n        }\n    }\n\n    func testInsertThenReplaceSameIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"0\")\n        try tokens.replace(0, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"0xbc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func test2InsertMiddleIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(1, \"x\")\n        tokens.insertBefore(1, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"ayxbc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func test2InsertThenReplaceIndex0() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"x\")\n        tokens.insertBefore(0, \"y\")\n        try tokens.replace(0, \"z\")\n        let result = try tokens.getText()\n        let expecting = \"yxzbc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceThenInsertBeforeLastIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, \"x\")\n        tokens.insertBefore(2, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"abyx\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testInsertThenReplaceLastIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(2, \"y\")\n        try tokens.replace(2, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"abyx\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceThenInsertAfterLastIndex() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, \"x\")\n        tokens.insertAfter(2, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"abxy\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceThenInsertAtLeftEdge() throws {\n        let input = ANTLRInputStream(\"abcccba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 4, \"x\")\n        tokens.insertBefore(2, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"abyxba\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceRangeThenInsertAtRightEdge() throws {\n        let input = ANTLRInputStream(\"abcccba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 4, \"x\")\n        tokens.insertBefore(4, \"y\")\n\n        do {\n            _ = try tokens.getText()\n            XCTFail(\"Expected exception not thrown.\")\n        } catch ANTLRError.illegalArgument(let msg) {\n            let expecting = \"insert op <InsertBeforeOp@[@4,4:4='c',<3>,1:4]:\\\"y\\\"> within boundaries of previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"x\\\">\"\n\n            XCTAssertEqual(expecting, msg)\n        }\n    }\n\n    func testReplaceRangeThenInsertAfterRightEdge() throws {\n        let input = ANTLRInputStream(\"abcccba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 4, \"x\")\n        tokens.insertAfter(4, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"abxyba\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceAll() throws {\n        let input = ANTLRInputStream(\"abcccba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(0, 6, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"x\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceSubsetThenFetch() throws {\n        let input = ANTLRInputStream(\"abcccba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 4, \"xyz\")\n        let result = try tokens.getText(Interval.of(0, 6))\n        let expecting = \"abxyzba\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testReplaceThenReplaceSuperset() throws {\n        let input = ANTLRInputStream(\"abcccba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 4, \"xyz\")\n        try tokens.replace(3, 5, \"foo\")\n\n        do {\n            _ = try tokens.getText()\n            XCTFail(\"Expected exception not thrown.\")\n        } catch ANTLRError.illegalArgument(let msg) {\n            let expecting = \"replace op boundaries of <ReplaceOp@[@3,3:3='c',<3>,1:3]..[@5,5:5='b',<2>,1:5]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"xyz\\\">\"\n            XCTAssertEqual(expecting, msg)\n        }\n    }\n\n    func testReplaceThenReplaceLowerIndexedSuperset() throws {\n        let input = ANTLRInputStream(\"abcccba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 4, \"xyz\")\n        try tokens.replace(1, 3, \"foo\")\n\n        do {\n            _ = try tokens.getText()\n            XCTFail(\"Expected exception not thrown.\")\n        } catch ANTLRError.illegalArgument(let msg) {\n            let expecting = \"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@3,3:3='c',<3>,1:3]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"xyz\\\">\"\n            XCTAssertEqual(expecting, msg)\n        }\n    }\n\n    func testReplaceSingleMiddleThenOverlappingSuperset() throws {\n        let input = ANTLRInputStream(\"abcba\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 2, \"xyz\")\n        try tokens.replace(0, 3, \"foo\")\n        let result = try tokens.getText()\n        let expecting = \"fooa\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testCombineInserts() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"x\")\n        tokens.insertBefore(0, \"y\")\n        let result = try tokens.getText()\n        let expecting = \"yxabc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testCombine3Inserts() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(1, \"x\")\n        tokens.insertBefore(0, \"y\")\n        tokens.insertBefore(1, \"z\")\n        let result = try tokens.getText()\n        let expecting = \"yazxbc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testCombineInsertOnLeftWithReplace() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        // combine with left edge of rewrite\n        try tokens.replace(0, 2, \"foo\")\n        tokens.insertBefore(0, \"z\")\n        try stream.fill()\n        let result = try tokens.getText()\n        let expecting = \"zfoo\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testCombineInsertOnLeftWithDelete() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        // combine with left edge of rewrite\n        try tokens.delete(0, 2)\n        tokens.insertBefore(0, \"z\")\n        try stream.fill()\n        let result = try tokens.getText()\n        let expecting = \"z\"\n        // make sure combo is not znull\n        try stream.fill()\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testDisjointInserts() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(1, \"x\")\n        tokens.insertBefore(2, \"y\")\n        tokens.insertBefore(0, \"z\")\n        try stream.fill()\n        let result = try tokens.getText()\n        let expecting = \"zaxbyc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testOverlappingReplace() throws {\n        let input = ANTLRInputStream(\"abcc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(1, 2, \"foo\")\n        try tokens.replace(0, 3, \"bar\")\n        try stream.fill()\n        // wipes prior nested replace\n        let result = try tokens.getText()\n        let expecting = \"bar\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testOverlappingReplace2() throws {\n        let input = ANTLRInputStream(\"abcc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(0, 3, \"bar\")\n        try tokens.replace(1, 2, \"foo\")\n        try stream.fill()\n        // cannot split earlier replace\n\n        do {\n            _ = try tokens.getText()\n            XCTFail(\"Expected exception not thrown.\")\n        } catch ANTLRError.illegalArgument(let msg) {\n            let expecting = \"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@2,2:2='c',<3>,1:2]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@0,0:0='a',<1>,1:0]..[@3,3:3='c',<3>,1:3]:\\\"bar\\\">\"\n            XCTAssertEqual(expecting, msg)\n        }\n    }\n\n    func testOverlappingReplace3() throws {\n        let input = ANTLRInputStream(\"abcc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(1, 2, \"foo\")\n        try tokens.replace(0, 2, \"bar\")\n        try stream.fill()\n        // wipes prior nested replace\n        let result = try tokens.getText()\n        let expecting = \"barc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testOverlappingReplace4() throws {\n        let input = ANTLRInputStream(\"abcc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(1, 2, \"foo\")\n        try tokens.replace(1, 3, \"bar\")\n        try stream.fill()\n        // wipes prior nested replace\n        let result = try tokens.getText()\n        let expecting = \"abar\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testDropIdenticalReplace() throws {\n        let input = ANTLRInputStream(\"abcc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(1, 2, \"foo\")\n        try tokens.replace(1, 2, \"foo\")\n        try stream.fill()\n        // drop previous, identical\n        let result = try tokens.getText()\n        let expecting = \"afooc\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testDropPrevCoveredInsert() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(1, \"foo\")\n        try tokens.replace(1, 2, \"foo\")\n        try stream.fill()\n        // kill prev insert\n        let result = try tokens.getText()\n        let expecting = \"afoofoo\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testLeaveAloneDisjointInsert() throws {\n        let input = ANTLRInputStream(\"abcc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(1, \"x\")\n        try tokens.replace(2, 3, \"foo\")\n        let result = try tokens.getText()\n        let expecting = \"axbfoo\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testLeaveAloneDisjointInsert2() throws {\n        let input = ANTLRInputStream(\"abcc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        try tokens.replace(2, 3, \"foo\")\n        tokens.insertBefore(1, \"x\")\n        let result = try tokens.getText()\n        let expecting = \"axbfoo\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testInsertBeforeTokenThenDeleteThatToken() throws {\n        let input = ANTLRInputStream(\"abc\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(2, \"y\")\n        try tokens.delete(2)\n        let result = try tokens.getText()\n        let expecting = \"aby\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder() throws {\n        let input = ANTLRInputStream(\"aa\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"<b>\")\n        tokens.insertAfter(0, \"</b>\")\n        tokens.insertBefore(1, \"<b>\")\n        tokens.insertAfter(1, \"</b>\")\n        let result = try tokens.getText()\n        let expecting = \"<b>a</b><b>a</b>\" // fails with <b>a<b></b>a</b>\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder2() throws {\n        let input = ANTLRInputStream(\"aa\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"<p>\")\n        tokens.insertBefore(0, \"<b>\")\n        tokens.insertAfter(0, \"</p>\")\n        tokens.insertAfter(0, \"</b>\")\n        tokens.insertBefore(1, \"<b>\")\n        tokens.insertAfter(1, \"</b>\")\n        let result = try tokens.getText()\n        let expecting = \"<b><p>a</p></b><b>a</b>\"\n        XCTAssertEqual(expecting, result)\n    }\n\n    func testPreservesOrderOfContiguousInserts() throws {\n        let input = ANTLRInputStream(\"ab\")\n        let lexer = LexerA(input)\n        let stream = CommonTokenStream(lexer)\n        try stream.fill()\n        let tokens = TokenStreamRewriter(stream)\n        tokens.insertBefore(0, \"<p>\")\n        tokens.insertBefore(0, \"<b>\")\n        tokens.insertBefore(0, \"<div>\")\n        tokens.insertAfter(0, \"</p>\")\n        tokens.insertAfter(0, \"</b>\")\n        tokens.insertAfter(0, \"</div>\")\n        tokens.insertBefore(1, \"!\")\n        let result = try tokens.getText()\n        let expecting = \"<div><b><p>a</p></b></div>!b\"\n        XCTAssertEqual(expecting, result)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/TokenStreamTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport XCTest\nimport Antlr4\n\nclass TokenStreamTests: XCTestCase {\n    \n    static let allTests = [\n        (\"testBufferedTokenStreamClearFetchEOFWithNewSource\", testBufferedTokenStreamClearFetchEOFWithNewSource)\n    ]\n\n    /// Test fetchEOF reset after setTokenSource\n    func testBufferedTokenStreamClearFetchEOFWithNewSource() throws {\n        let inputStream1 = ANTLRInputStream(\"A\")\n        let tokenStream = CommonTokenStream(VisitorBasicLexer(inputStream1))\n\n        try tokenStream.fill();\n        XCTAssertEqual(2, tokenStream.size())\n        XCTAssertEqual(VisitorBasicLexer.A, try tokenStream.get(0).getType())\n        XCTAssertEqual(Lexer.EOF, try tokenStream.get(1).getType())\n\n        let inputStream2 = ANTLRInputStream(\"AA\");\n        tokenStream.setTokenSource(VisitorBasicLexer(inputStream2));\n        try tokenStream.fill();\n        XCTAssertEqual(3, tokenStream.size())\n        XCTAssertEqual(VisitorBasicLexer.A, try tokenStream.get(0).getType())\n        XCTAssertEqual(VisitorBasicLexer.A, try tokenStream.get(1).getType())\n        XCTAssertEqual(Lexer.EOF, try tokenStream.get(2).getType())\n    }\n\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/VisitorBasic.g4",
    "content": "grammar VisitorBasic;\n\ns\n    :   'A' EOF\n    ;\n\nA\n    :   'A'\n    ;\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/VisitorCalc.g4",
    "content": "grammar VisitorCalc;\n\ns\n    :   expr EOF\n    ;\n\nexpr\n    :   INT                     # number\n    |   expr (MUL | DIV) expr   # multiply\n    |   expr (ADD | SUB) expr   # add\n    ;\n\nINT : [0-9]+;\nMUL : '*';\nDIV : '/';\nADD : '+';\nSUB : '-';\nWS : [ \\t]+ -> channel(HIDDEN);\n"
  },
  {
    "path": "runtime/Swift/Tests/Antlr4Tests/VisitorTests.swift",
    "content": "/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n/// Use of this file is governed by the BSD 3-clause license that\n/// can be found in the LICENSE.txt file in the project root.\n\nimport XCTest\nimport Antlr4\n\nclass VisitorTests: XCTestCase {\n    static let allTests = [\n        (\"testCalculatorVisitor\", testCalculatorVisitor),\n        (\"testShouldNotVisitTerminal\", testShouldNotVisitTerminal),\n        (\"testShouldNotVisitEOF\", testShouldNotVisitEOF),\n        (\"testVisitErrorNode\", testVisitErrorNode),\n        (\"testVisitTerminalNode\", testVisitTerminalNode)\n    ]\n    \n    ///\n    /// This test verifies the basic behavior of visitors, with an emphasis on\n    /// {@link AbstractParseTreeVisitor#visitTerminal}.\n    ///\n    func testVisitTerminalNode() throws {\n        let lexer = VisitorBasicLexer(ANTLRInputStream(\"A\"))\n        let parser = try VisitorBasicParser(CommonTokenStream(lexer))\n\n        let context = try parser.s()\n        XCTAssertEqual(\"(s A <EOF>)\", context.toStringTree(parser))\n\n        class Visitor: VisitorBasicBaseVisitor<String> {\n            override func visitTerminal(_ node: TerminalNode) -> String? {\n                return \"\\(node.getSymbol()!)\\n\"\n            }\n\n            override func defaultResult() -> String? {\n                return \"\"\n            }\n\n            override func aggregateResult(_ aggregate: String?, _ nextResult: String?) -> String? {\n                return aggregate! + nextResult!\n            }\n        }\n\n        let visitor = Visitor()\n        let result = visitor.visit(context)\n        let expected =\n        \"[@0,0:0='A',<1>,1:0]\\n\" +\n        \"[@1,1:0='<EOF>',<-1>,1:1]\\n\"\n        XCTAssertEqual(expected, result)\n    }\n\n    ///\n    /// This test verifies the basic behavior of visitors, with an emphasis on\n    /// {@link AbstractParseTreeVisitor#visitErrorNode}.\n    ///\n    func testVisitErrorNode() throws {\n        let lexer = VisitorBasicLexer(ANTLRInputStream(\"\"))\n        let parser = try VisitorBasicParser(CommonTokenStream(lexer))\n\n        class ErrorListener: BaseErrorListener {\n            override init() {\n                super.init()\n            }\n\n            var errors = [String]()\n\n            override func syntaxError<T>(_ recognizer: Recognizer<T>,\n                                         _ offendingSymbol: AnyObject?,\n                                         _ line: Int, _ charPositionInLine: Int,\n                                         _ msg: String, _ e: AnyObject?) {\n                errors.append(\"line \\(line):\\(charPositionInLine) \\(msg)\")\n            }\n        }\n\n        parser.removeErrorListeners()\n        let errorListener = ErrorListener()\n        parser.addErrorListener(errorListener)\n\n        let context = try parser.s()\n        let errors = errorListener.errors\n        XCTAssertEqual(\"(s <missing 'A'> <EOF>)\", context.toStringTree(parser))\n        XCTAssertEqual(1, errors.count)\n        XCTAssertEqual(\"line 1:0 missing 'A' at '<EOF>'\", errors[0])\n\n        class Visitor: VisitorBasicBaseVisitor<String> {\n            override func visitErrorNode(_ node: ErrorNode) -> String? {\n                return \"Error encountered: \\(node.getSymbol()!)\"\n            }\n\n            override func defaultResult() -> String? {\n                return \"\"\n            }\n\n            override func aggregateResult(_ aggregate: String?, _ nextResult: String?) -> String? {\n                return aggregate! + nextResult!\n            }\n        }\n\n        let visitor = Visitor()\n        let result = visitor.visit(context)\n        let expected = \"Error encountered: [@-1,-1:-1='<missing 'A'>',<1>,1:0]\"\n        XCTAssertEqual(expected, result)\n    }\n\n    ///\n    /// This test verifies that {@link AbstractParseTreeVisitor#visitChildren} does not call\n    /// {@link ParseTreeVisitor#visit} after {@link AbstractParseTreeVisitor#shouldVisitNextChild} returns\n    /// {@code false}.\n    ///\n    func testShouldNotVisitEOF() throws {\n        let input = \"A\"\n        let lexer = VisitorBasicLexer(ANTLRInputStream(input))\n        let parser = try VisitorBasicParser(CommonTokenStream(lexer))\n\n        let context = try parser.s()\n        XCTAssertEqual(\"(s A <EOF>)\", context.toStringTree(parser))\n\n        class Visitor: VisitorBasicBaseVisitor<String> {\n            override func visitTerminal(_ node: TerminalNode) -> String? {\n                return \"\\(node.getSymbol()!)\\n\"\n            }\n\n            override func shouldVisitNextChild(_ node: RuleNode, _ currentResult: String?) -> Bool {\n                return currentResult == nil || currentResult!.isEmpty\n            }\n        }\n\n        let visitor = Visitor()\n        let result = visitor.visit(context)\n        let expected = \"[@0,0:0='A',<1>,1:0]\\n\"\n        XCTAssertEqual(expected, result)\n    }\n\n    ///\n    /// This test verifies that {@link AbstractParseTreeVisitor#shouldVisitNextChild} is called before visiting the first\n    /// child. It also verifies that {@link AbstractParseTreeVisitor#defaultResult} provides the default return value for\n    /// visiting a tree.\n    ///\n    func testShouldNotVisitTerminal() throws {\n        let input = \"A\"\n        let lexer = VisitorBasicLexer(ANTLRInputStream(input))\n        let parser = try VisitorBasicParser(CommonTokenStream(lexer))\n\n        let context = try parser.s()\n        XCTAssertEqual(\"(s A <EOF>)\", context.toStringTree(parser))\n\n        class Visitor: VisitorBasicBaseVisitor<String> {\n            override func visitTerminal(_ node: TerminalNode) -> String? {\n                XCTFail()\n                return nil\n            }\n\n            override func defaultResult() -> String? {\n                return \"default result\"\n            }\n\n            override func shouldVisitNextChild(_ node: RuleNode, _ currentResult: String?) -> Bool {\n                return false\n            }\n        }\n\n        let visitor = Visitor()\n        let result = visitor.visit(context)\n        let expected = \"default result\"\n        XCTAssertEqual(expected, result)\n    }\n\n    ///\n    /// This test verifies that the visitor correctly dispatches calls for labeled outer alternatives.\n    ///\n    func testCalculatorVisitor() throws {\n        let input = \"2 + 8 / 2\"\n        let lexer = VisitorCalcLexer(ANTLRInputStream(input))\n        let parser = try VisitorCalcParser(CommonTokenStream(lexer))\n\n        let context = try parser.s()\n        XCTAssertEqual(\"(s (expr (expr 2) + (expr (expr 8) / (expr 2))) <EOF>)\", context.toStringTree(parser))\n\n        class Visitor: VisitorCalcBaseVisitor<Int> {\n            override func visitS(_ ctx: VisitorCalcParser.SContext) -> Int? {\n                return visit(ctx.expr()!)\n            }\n\n            override func visitNumber(_ ctx: VisitorCalcParser.NumberContext) -> Int? {\n                return Int((ctx.INT()?.getText())!)\n            }\n\n            override func visitMultiply(_ ctx: VisitorCalcParser.MultiplyContext) -> Int? {\n                let left = visit(ctx.expr(0)!)!\n                let right = visit(ctx.expr(1)!)!\n                if ctx.MUL() != nil {\n                    return left * right\n                }\n                else {\n                    return left / right\n                }\n            }\n\n            override func visitAdd(_ ctx: VisitorCalcParser.AddContext) -> Int? {\n                let left = visit(ctx.expr(0)!)!\n                let right = visit(ctx.expr(1)!)!\n                if ctx.ADD() != nil {\n                    return left + right\n                }\n                else {\n                    return left - right\n                }\n            }\n        }\n\n        let visitor = Visitor()\n        let result = visitor.visit(context)\n        let expected = 6\n        XCTAssertEqual(expected, result!)\n    }\n}\n"
  },
  {
    "path": "runtime/Swift/Tests/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>BNDL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>1</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "runtime/Swift/Tests/LinuxMain.swift",
    "content": "#if os(Linux)\n\nimport XCTest\n@testable import Antlr4Tests\n\nXCTMain([\n    // Antlr4Tests\n    testCase(TokenStreamTests.allTests),\n    testCase(TokenStreamRewriterTests.allTests),\n    testCase(VisitorTests.allTests)\n])\n\n#endif\n"
  },
  {
    "path": "runtime/Swift/boot.py",
    "content": "#! /usr/bin/python\n\n\"\"\"\nFind all .g4 files and generate parsers in the same directory.\nthe antlr used should be the one located at user's mvn directory\nthe filename is antlr4-ANTLR_VERSION-SNAPSHOT.jar. You can get it\nby running: \"mvn install\"\n\nNOTE: In case of customized location of .m2 folder, you can change the\nUSER_M2 constant below.\n\nthe java version is used according to environment variable $JAVA_HOME.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport glob\nimport shutil\nimport argparse\nimport fnmatch\nimport os.path\nimport subprocess\nimport sys\nimport time\nfrom subprocess import check_call\n\n\n# ANTLR Version, here we only care about major version.\nMAJOR_VERSION = \"4\"\n\n# Note: User defines their own M2_HOME should change this variable.\nUSER_M2 = os.path.expanduser(\"~\") + \"/.m2\"\nTMP_FOLDER = \"/tmp/\"\n\n# The directory contains this script.\nDIR = os.path.dirname(os.path.realpath(__file__))\n\n# The following two are using glob syntax.\nANTLR4_FOLDER = USER_M2 + \"/repository/org/antlr/antlr4/*-SNAPSHOT\"\nANTLR4 = ANTLR4_FOLDER + \"/antlr4-*-SNAPSHOT-complete.jar\"\n\n# Colors\nRED = \"\\033[91;1m\"\nGREEN = \"\\033[32;1m\"\nYELLOW = \"\\033[93;1m\"\nCYAN = \"\\033[36;1m\"\nGREY = \"\\033[38;2;127;127;127m\"\nRESET = \"\\033[0m\"\n\n\ndef find_a4_jar():\n    \"\"\"\n    Finds the antlr4 jar.\n    \"\"\"\n    matches = glob.glob(ANTLR4)\n    if len(matches) == 0:\n        return None\n    sorted(matches, reverse=True)\n    return matches[0]\n\n\ndef find_g4():\n    \"\"\"\n    Find all g4 files and return a list of them.\n    The recursive search starts from the directory containing\n    this python file.\n    \"\"\"\n    file_path = os.path.realpath(__file__)\n    parent_folder = file_path[0:file_path.rindex(\"/\") + 1]\n    res = []\n    for cur, _, filenames in os.walk(parent_folder):\n        cur_files = fnmatch.filter(filenames, \"*.g4\")\n        res += [cur + \"/\" + cur_file for cur_file in cur_files]\n    return res\n\n\ndef gen_parser(grammar, a4):\n    \"\"\"\n    Generate parser for the input g4 file.\n    :param grammar: grammar file\n    :param a4: antlr4 runtime\n    :return: None\n    \"\"\"\n    grammar_folder = grammar[0:grammar.rindex(\"/\") + 1]\n    java_home = os.environ[\"JAVA_HOME\"]\n    java = java_home + \"/bin/java\"\n    if not os.path.exists(java):\n        antlr_complains(\"Cannot find java. Check your JAVA_HOME setting.\")\n        return\n\n    check_call([java, \"-jar\", a4,\n               \"-Dlanguage=Swift\", grammar, \"-visitor\",\n               \"-o\", grammar_folder + \"/gen\"])\n\n\ndef swift_test():\n    \"\"\"\n    Run unit tests.\n    \"\"\"\n    generate_parser()\n    check_call([\"cd\",\"./../..\"])\n    check_call([\"swift\", \"test\"])\n\n\ndef get_argument_parser():\n    \"\"\"\n    Initialize argument parser.\n    :return: the argument parser\n    \"\"\"\n    p = argparse.ArgumentParser(description=\"Helper script for ANTLR4 Swift target. \"\n                                            \"<DEVELOPER> flag means the command is mostly used by a developer. \"\n                                            \"<USER> flag means the command should be used by user. \")\n    p.add_argument(\"--gen-spm-module\",\n                   action=\"store_true\",\n                   help=\"<USER> Generates a Swift Package Manager flavored module. \"\n                        \"Use this command if you want to include ANTLR4 as SPM dependency.\", )\n    p.add_argument(\"--gen-xcodeproj\",\n                   action=\"store_true\",\n                   help=\"<DEVELOPER, USER> Generates an Xcode project for ANTLR4 Swift runtime. \"\n                        \"This directive will generate all the required parsers for the project. \"\n                        \"Feel free to re-run whenever you updated the test grammar files.\")\n    p.add_argument(\"--test\",\n                   action=\"store_true\",\n                   help=\"<DEVELOPER> Run unit tests.\")\n    return p\n\n\ndef generate_spm_module(in_folder=TMP_FOLDER):\n    \"\"\"\n    Generate spm module in the specified folder, default\n    to the system's tmp folder.\n\n    After generation, user can simply use the prompt SPM\n    code to include the ANTLR4 Swift runtime package.\n    :param in_folder: the folder where we generate the SPM module.\n    :return: None\n    \"\"\"\n\n    tmp_antlr_folder = in_folder + \"Antlr4-tmp-\" + str(int(time.time()))\n    os.mkdir(tmp_antlr_folder)\n\n    # Copy folders and SPM manifest file.\n    dirs_to_copy = [\"Sources\", \"Tests\"]\n    for dir_to_copy in dirs_to_copy:\n        shutil.copytree(DIR + \"/\" + dir_to_copy, tmp_antlr_folder + \"/\" + dir_to_copy)\n\n    shutil.copy(\"Package.swift\", tmp_antlr_folder)\n\n    os.chdir(tmp_antlr_folder)\n    check_call([\"git\", \"init\"])\n    check_call([\"git\", \"add\", \"*\"])\n    check_call([\"git\", \"commit\", \"-m\", \"Initial commit.\"])\n    check_call([\"git\", \"tag\", \"{}.0.0\".format(MAJOR_VERSION)])\n\n    antlr_says(\"Created local repository.\")\n    antlr_says(\"(swift-tools-version:3.0) \" \n               \"Put .Package(url: \\\"{}\\\", majorVersion: {}) in Package.swift.\".format(os.getcwd(), MAJOR_VERSION))\n    antlr_says(\"(swift-tools-wersion:4.0) \"\n               \"Put .package(url: \\\"{}\\\", from: \\\"{}.0.0\\\") in Package.swift \"\n               \"and add \\\"Antlr4\\\" to target dependencies. \".format(os.getcwd(), MAJOR_VERSION))\n\n\ndef generate_xcodeproj():\n    \"\"\"\n    Generates the ANTLR4 Swift runtime Xcode project.\n\n    This method will also generate parsers required by\n    the runtime tests.\n    :return:\n    \"\"\"\n    generate_parser()\n    check_call([\"swift\", \"package\", \"generate-xcodeproj\"])\n\n\ndef generate_parser():\n    antlr = find_a4_jar()\n    if antlr is None:\n        antlr_complains(\"Run \\\"mvn install\\\" in antlr4 project root first or check mvn settings\")\n        exit()\n\n    _ = [gen_parser(f, antlr) for f in find_g4()]\n\n\ndef antlr_says(msg):\n    print(GREEN + \"[ANTLR] \" + msg + RESET)\n\n\ndef antlr_complains(msg):\n    print(RED + \"[ANTLR] \" + msg + RESET)\n\n\nif __name__ == \"__main__\":\n    parser = get_argument_parser()\n    args = parser.parse_args()\n    try:\n        if args.gen_spm_module:\n            generate_spm_module()\n        elif args.gen_xcodeproj:\n            generate_xcodeproj()\n        elif args.test:\n            swift_test()\n        else:\n            parser.print_help()\n    except subprocess.CalledProcessError as err:\n        print(\"Error: command '%s' exited with status %d\" %\n              (' '.join(err.cmd), err.returncode), file=sys.stderr)\n        sys.exit(err.returncode)\n    except (IOError, OSError) as err:\n        print(err, file=sys.stderr)\n        sys.exit(1)\n"
  },
  {
    "path": "runtime-testsuite/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<groupId>org.antlr</groupId>\n\t\t<artifactId>antlr4-master</artifactId>\n\t\t<version>4.13.3-SNAPSHOT</version>\n\t</parent>\n\t<artifactId>antlr4-runtime-testsuite</artifactId>\n\t<name>ANTLR 4 Runtime Tests (4th generation)</name>\n\t<description>A collection of tests for ANTLR 4 Runtime libraries.</description>\n\n\t<prerequisites>\n\t\t<maven>3.8</maven>\n\t</prerequisites>\n\n\t<inceptionYear>2009</inceptionYear>\n\n\t<properties>\n\t\t<jUnitVersion>5.9.0</jUnitVersion>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.antlr</groupId>\n\t\t\t<artifactId>ST4</artifactId>\n\t\t\t<version>4.3.4</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.antlr</groupId>\n\t\t\t<artifactId>antlr4</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.antlr</groupId>\n\t\t\t<artifactId>antlr4-runtime</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.junit.jupiter</groupId>\n\t\t\t<artifactId>junit-jupiter-api</artifactId>\n\t\t\t<version>${jUnitVersion}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.junit.jupiter</groupId>\n\t\t\t<artifactId>junit-jupiter-engine</artifactId>\n\t\t\t<version>${jUnitVersion}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.glassfish</groupId>\n\t\t\t<artifactId>javax.json</artifactId>\n\t\t\t<version>1.1.4</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t    <groupId>org.openjdk.jol</groupId>\n\t\t    <artifactId>jol-core</artifactId>\n\t\t    <version>0.16</version>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<testSourceDirectory>test</testSourceDirectory>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t\t<version>2.22.0</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<!-- SUREFIRE-951: file.encoding cannot be set via systemPropertyVariables -->\n\t\t\t\t\t<argLine>-Dfile.encoding=UTF-8</argLine>\n                </configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>3.2.0</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.antlr</groupId>\n\t\t\t\t<artifactId>antlr4-maven-plugin</artifactId>\n\t\t\t\t<version>${project.version}</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>antlr4</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<sourceDirectory>${basedir}/test</sourceDirectory>\n\t\t\t\t\t\t\t<outputDirectory>${project.build.directory}/generated-test-sources/antlr4</outputDirectory>\n\t\t\t\t\t\t\t<visitor>true</visitor>\n\t\t\t\t\t\t\t<generateTestSources>true</generateTestSources>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n            <plugin>\n                <groupId>org.apache.maven.plugins</groupId>\n                <artifactId>maven-compiler-plugin</artifactId>\n                <configuration>\n                    <release>8</release>\n                    <source>9</source>\n                    <target>9</target>\n                </configuration>\n            </plugin>\n        </plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "runtime-testsuite/resources/junit-platform.properties",
    "content": "junit.jupiter.execution.parallel.enabled = true\njunit.jupiter.execution.parallel.mode.default = concurrent\njunit.jupiter.execution.parallel.mode.classes.default = concurrent"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeLexers/LexerDelegatorInvokesDelegateRule.txt",
    "content": "[type]\nCompositeLexer\n\n[grammar]\nlexer grammar M;\nimport S;\nB : 'b';\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nlexer grammar S;\nA : 'a' {<writeln(\"\\\"S.A\\\"\")>};\nC : 'c' ;\n\n[input]\nabc\n\n[output]\nS.A\n[@0,0:0='a',<3>,1:0]\n[@1,1:1='b',<1>,1:1]\n[@2,2:2='c',<4>,1:2]\n[@3,3:2='<EOF>',<-1>,1:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeLexers/LexerDelegatorRuleOverridesDelegate.txt",
    "content": "[type]\nCompositeLexer\n\n[grammar]\nlexer grammar M;\nimport S;\nA : 'a' B {<writeln(\"\\\"M.A\\\"\")>} ;\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nlexer grammar S;\nA : 'a' {<writeln(\"\\\"S.A\\\"\")>} ;\nB : 'b' {<writeln(\"\\\"S.B\\\"\")>} ;\n\n[input]\nab\n\n[output]\nM.A\n[@0,0:1='ab',<1>,1:0]\n[@1,2:1='<EOF>',<-1>,1:2]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/BringInLiteralsFromDelegate.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\ns : a ;\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\na : '=' 'a' {<write(\"\\\"S.a\\\"\")>};\n\n[start]\ns\n\n[input]\n=a\n\n[output]\n\"\"\"S.a\"\"\""
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/CombinedImportsCombined.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\ns : x INT;\n\n[slaveGrammar]\nparser grammar S;\ntokens { A, B, C }\nx : 'x' INT {<writeln(\"\\\"S.x\\\"\")>};\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx 34 9\n\n[output]\n\"\"\"S.x\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatesSeeSameTokenType.txt",
    "content": "[notes]\nThe lexer will create rules to match letters a, b, c.\nThe associated token types A, B, C must have the same value\nand all import'd parsers.  Since ANTLR regenerates all imports\nfor use with the delegator M, it can generate the same token type\nmapping in each parser:\npublic static final int C=6;\npublic static final int EOF=-1;\npublic static final int B=5;\npublic static final int WS=7;\npublic static final int A=4;\n\n[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S,T;\ns : x y ; // matches AA, which should be 'aa'\nB : 'b' ; // another order: B, A, C\nA : 'a' ;\nC : 'c' ;\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar T;\ntokens { C, B, A } // reverse order\ny : A {<writeln(\"\\\"T.y\\\"\")>};\n\n[slaveGrammar]\nparser grammar S;\ntokens { A, B, C }\nx : A {<writeln(\"\\\"S.x\\\"\")>};\n\n[start]\ns\n\n[input]\naa\n\n[output]\nS.x\nT.y\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorAccessesDelegateMembers.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M; // uses no rules from the import\nimport S;\ns : 'b' {<Invoke_foo()>} ; // gS is import pointer\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\n@parser::members {\n<Declare_foo()>\n}\na : B;\n\n[start]\ns\n\n[input]\nb\n\n[output]\n\"\"\"foo\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorInvokesDelegateRule.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\ns : a ;\nB : 'b' ; // defines B from inherited token space\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\na : B {<writeln(\"\\\"S.a\\\"\")>};\n\n[start]\ns\n\n[input]\nb\n\n[output]\n\"\"\"S.a\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorInvokesDelegateRuleWithArgs.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\ns : label=a[3] {<writeln(\"$label.y\")>} ;\nB : 'b' ; // defines B from inherited token space\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\na[int x] returns [int y] : B {<write(\"\\\"S.a\\\"\")>} {$y=1000;} ;\n\n[start]\ns\n\n[input]\nb\n\n[output]\n\"\"\"S.a1000\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorInvokesDelegateRuleWithReturnStruct.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\ns : a {<write(\"$a.text\")>} ;\nB : 'b' ; // defines B from inherited token space\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\na : B {<write(\"\\\"S.a\\\"\")>} ;\n\n[start]\ns\n\n[input]\nb\n\n[output]\n\"\"\"S.ab\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorInvokesFirstVersionOfDelegateRule.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S,T;\ns : a ;\nB : 'b' ; // defines B from inherited token space\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar T;\na : B {<writeln(\"\\\"T.a\\\"\")>};<! hidden by S.a !>\n\n[slaveGrammar]\nparser grammar S;\na : b {<writeln(\"\\\"S.a\\\"\")>};\nb : B;\n\n[start]\ns\n\n[input]\nb\n\n[output]\n\"\"\"S.a\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorRuleOverridesDelegate.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\nb : 'b'|'c';\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\na : b {<write(\"\\\"S.a\\\"\")>};\nb : B ;\n\n[start]\na\n\n[input]\nc\n\n[output]\n\"\"\"S.a\"\"\""
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorRuleOverridesDelegates.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S, T;\nb : 'b'|'c' {<writeln(\"\\\"M.b\\\"\")>}|B|A;\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar T;\ntokens { A }\nb : 'b' {<writeln(\"\\\"T.b\\\"\")>};\n\n[slaveGrammar]\nparser grammar S;\na : b {<writeln(\"\\\"S.a\\\"\")>};\nb : 'b' ;\n\n[start]\na\n\n[input]\nc\n\n[output]\nM.b\nS.a\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorRuleOverridesLookaheadInDelegate.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\nprog : decl ;\ntype_ : 'int' | 'float' ;\nID  : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip;\n\n[slaveGrammar]\nparser grammar S;\ntype_ : 'int' ;\ndecl : type_ ID ';'\n    | type_ ID init_ ';' {<AppendStr(\"\\\"JavaDecl: \\\"\",\"$text\"):writeln()>};\ninit_ : '=' INT;\n\n[start]\nprog\n\n[input]\nfloat x = 3;\n\n[output]\n\"\"\"JavaDecl: floatx=3;\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/ImportLexerWithOnlyFragmentRules.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#248 \"Including grammar with only\nfragments breaks generated lexer\".  https://github.com/antlr/antlr4/issues/248\n\n[type]\nCompositeParser\n\n[grammar]\ngrammar Test;\nimport Unicode;\n\nprogram : 'test' 'test';\n\nWS : (UNICODE_CLASS_Zs)+ -> skip;\n\n[slaveGrammar]\n\"\"\"lexer grammar Unicode;\n\nfragment\nUNICODE_CLASS_Zs    : ' ' | ' ' | ' ' | '᠎'\n    | ' '..' '\n    | ' ' | ' ' | '　'\n    ;\n\n\"\"\"\n\n[start]\nprogram\n\n[input]\ntest test\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/ImportedGrammarWithEmptyOptions.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\ns : a ;\nB : 'b' ;\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\noptions {}\na : B ;\n\n[start]\ns\n\n[input]\nb\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/ImportedRuleWithAction.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\ns : a;\nB : 'b';\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nparser grammar S;\na @after {<InitIntVar(\"x\",\"0\")>} : B;\n\n[start]\ns\n\n[input]\nb\n\n[skip]\nGo\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/KeywordVSIDOrder.txt",
    "content": "[type]\nCompositeParser\n\n[grammar]\ngrammar M;\nimport S;\na : A {<Append(\"\\\"M.a: \\\"\",\"$A\"):writeln()>};\nA : 'abc' {<writeln(\"\\\"M.A\\\"\")>};\nWS : (' '|'\\n') -> skip ;\n\n[slaveGrammar]\nlexer grammar S;\nID : 'a'..'z'+;\n\n[start]\na\n\n[input]\nabc\n\n[output]\nM.A\nM.a: [@0,0:2='abc',<1>,1:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/AmbigYieldsCtxSensitiveDFA.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<DumpDFA()>}\n   : ID | ID {} ;\nID : 'a'..'z'+;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\nabc\n\n[output]\nDecision 0:\ns0-ID->:s1^=>1\n\n[errors]\n\"\"\"line 1:0 reportAttemptingFullContext d=0 (s), input='abc'\n\"\"\"\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/AmbiguityNoLoop.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nprog\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n   : expr expr {<writeln(\"\\\"alt 1\\\"\")>}\n   | expr\n   ;\nexpr: '@'\n   | ID '@'\n   | ID\n   ;\nID  : [a-z]+ ;\nWS  : [ \\r\\n\\t]+ -> skip ;\n\n[start]\nprog\n\n[input]\na@\n\n[output]\n\"\"\"alt 1\n\"\"\"\n\n[errors]\nline 1:2 reportAttemptingFullContext d=0 (prog), input='a@'\nline 1:2 reportAmbiguity d=0 (prog): ambigAlts={1, 2}, input='a@'\nline 1:2 reportAttemptingFullContext d=1 (expr), input='a@'\nline 1:2 reportContextSensitivity d=1 (expr), input='a@'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/CtxSensitiveDFATwoDiffInput.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<DumpDFA()>}\n  : ('$' a | '@' b)+ ;\na : e ID ;\nb : e INT ID ;\ne : INT | ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n$ 34 abc @ 34 abc\n\n[output]\nDecision 2:\ns0-INT->s1\ns1-ID->:s2^=>1\n\n[errors]\nline 1:5 reportAttemptingFullContext d=2 (e), input='34abc'\nline 1:2 reportContextSensitivity d=2 (e), input='34'\nline 1:14 reportAttemptingFullContext d=2 (e), input='34abc'\nline 1:14 reportContextSensitivity d=2 (e), input='34abc'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/CtxSensitiveDFA_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<DumpDFA()>}\n  : '$' a | '@' b ;\na : e ID ;\nb : e INT ID ;\ne : INT | ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n$ 34 abc\n\n[output]\nDecision 1:\ns0-INT->s1\ns1-ID->:s2^=>1\n\n[errors]\nline 1:5 reportAttemptingFullContext d=1 (e), input='34abc'\nline 1:2 reportContextSensitivity d=1 (e), input='34'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/CtxSensitiveDFA_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<DumpDFA()>}\n  : '$' a | '@' b ;\na : e ID ;\nb : e INT ID ;\ne : INT | ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n@ 34 abc\n\n[output]\nDecision 1:\ns0-INT->s1\ns1-ID->:s2^=>1\n\n[errors]\nline 1:5 reportAttemptingFullContext d=1 (e), input='34abc'\nline 1:5 reportContextSensitivity d=1 (e), input='34abc'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/ExprAmbiguity_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n:   expr[0] {<ToStringTree(\"$expr.ctx\"):writeln()>};\n   expr[int _p]\n       : ID\n       (\n  {5 >= $_p}? '*' expr[6]\n  | {4 >= $_p}? '+' expr[5]\n       )*\n       ;\nID  : [a-zA-Z]+ ;\nWS  : [ \\r\\n\\t]+ -> skip ;\n\n[start]\ns\n\n[input]\na+b\n\n[output]\n\"\"\"(expr a + (expr b))\n\"\"\"\n\n[errors]\nline 1:1 reportAttemptingFullContext d=1 (expr), input='+'\nline 1:2 reportContextSensitivity d=1 (expr), input='+b'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/ExprAmbiguity_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n:   expr[0] {<ToStringTree(\"$expr.ctx\"):writeln()>};\n   expr[int _p]\n       : ID\n       (\n  {5 >= $_p}? '*' expr[6]\n  | {4 >= $_p}? '+' expr[5]\n       )*\n       ;\nID  : [a-zA-Z]+ ;\nWS  : [ \\r\\n\\t]+ -> skip ;\n\n[start]\ns\n\n[input]\na+b*c\n\n[output]\n\"\"\"(expr a + (expr b * (expr c)))\n\"\"\"\n\n[errors]\nline 1:1 reportAttemptingFullContext d=1 (expr), input='+'\nline 1:2 reportContextSensitivity d=1 (expr), input='+b'\nline 1:3 reportAttemptingFullContext d=1 (expr), input='*'\nline 1:5 reportAmbiguity d=1 (expr): ambigAlts={1, 2}, input='*c'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/FullContextIF_THEN_ELSEParse_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n@after {<DumpDFA()>}\n   : '{' stat* '}' ;\nstat: 'if' ID 'then' stat ('else' ID)?\n       | 'return'\n       ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n{ if x then return }\n\n[output]\nDecision 1:\ns0-'}'->:s1=>2\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/FullContextIF_THEN_ELSEParse_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n@after {<DumpDFA()>}\n   : '{' stat* '}' ;\nstat: 'if' ID 'then' stat ('else' ID)?\n       | 'return'\n       ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n{ if x then return else foo }\n\n[output]\nDecision 1:\ns0-'else'->:s1^=>1\n\n[errors]\nline 1:19 reportAttemptingFullContext d=1 (stat), input='else'\nline 1:19 reportContextSensitivity d=1 (stat), input='else'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/FullContextIF_THEN_ELSEParse_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n@after {<DumpDFA()>}\n   : '{' stat* '}' ;\nstat: 'if' ID 'then' stat ('else' ID)?\n       | 'return'\n       ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n{ if x then if y then return else foo }\n\n[output]\nDecision 1:\ns0-'}'->:s2=>2\ns0-'else'->:s1^=>1\n\n[errors]\nline 1:29 reportAttemptingFullContext d=1 (stat), input='else'\nline 1:38 reportAmbiguity d=1 (stat): ambigAlts={1, 2}, input='elsefoo}'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/FullContextIF_THEN_ELSEParse_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n@after {<DumpDFA()>}\n   : '{' stat* '}' ;\nstat: 'if' ID 'then' stat ('else' ID)?\n       | 'return'\n       ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n{ if x then if y then return else foo else bar }\n\n[output]\nDecision 1:\ns0-'else'->:s1^=>1\n\n[errors]\nline 1:29 reportAttemptingFullContext d=1 (stat), input='else'\nline 1:38 reportContextSensitivity d=1 (stat), input='elsefooelse'\nline 1:38 reportAttemptingFullContext d=1 (stat), input='else'\nline 1:38 reportContextSensitivity d=1 (stat), input='else'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/FullContextIF_THEN_ELSEParse_5.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n@after {<DumpDFA()>}\n   : '{' stat* '}' ;\nstat: 'if' ID 'then' stat ('else' ID)?\n       | 'return'\n       ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n{ if x then return else foo\nif x then if y then return else foo }\n\n[output]\nDecision 1:\ns0-'}'->:s2=>2\ns0-'else'->:s1^=>1\n\n[errors]\nline 1:19 reportAttemptingFullContext d=1 (stat), input='else'\nline 1:19 reportContextSensitivity d=1 (stat), input='else'\nline 2:27 reportAttemptingFullContext d=1 (stat), input='else'\nline 2:36 reportAmbiguity d=1 (stat): ambigAlts={1, 2}, input='elsefoo}'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/FullContextIF_THEN_ELSEParse_6.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n@after {<DumpDFA()>}\n   : '{' stat* '}' ;\nstat: 'if' ID 'then' stat ('else' ID)?\n       | 'return'\n       ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n{ if x then return else foo\nif x then if y then return else foo }\n\n[output]\nDecision 1:\ns0-'}'->:s2=>2\ns0-'else'->:s1^=>1\n\n[errors]\nline 1:19 reportAttemptingFullContext d=1 (stat), input='else'\nline 1:19 reportContextSensitivity d=1 (stat), input='else'\nline 2:27 reportAttemptingFullContext d=1 (stat), input='else'\nline 2:36 reportAmbiguity d=1 (stat): ambigAlts={1, 2}, input='elsefoo}'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/LoopsSimulateTailRecursion.txt",
    "content": "[notes]\nTests predictions for the following case involving closures.\nhttp://www.antlr.org/wiki/display/~admin/2011/12/29/Flaw+in+ANTLR+v3+LL(*)+analysis+algorithm\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nprog\n@init {<LL_EXACT_AMBIG_DETECTION()>}\n   : expr_or_assign*;\nexpr_or_assign\n   : expr '++' {<writeln(\"\\\"fail.\\\"\")>}\n   |  expr {<AppendStr(\"\\\"pass: \\\"\",\"$expr.text\"):writeln()>}\n   ;\nexpr: expr_primary ('\\<-' ID)?;\nexpr_primary\n   : '(' ID ')'\n   | ID '(' ID ')'\n   | ID\n   ;\nID  : [a-z]+ ;\n\n[start]\nprog\n\n[input]\na(i)<-x\n\n[output]\n\"\"\"pass: a(i)<-x\n\"\"\"\n\n[errors]\nline 1:3 reportAttemptingFullContext d=3 (expr_primary), input='a(i)'\nline 1:7 reportAmbiguity d=3 (expr_primary): ambigAlts={2, 3}, input='a(i)<-x'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/FullContextParsing/SLLSeesEOFInLLGrammar.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<DumpDFA()>}\n  : a;\na : e ID ;\nb : e INT ID ;\ne : INT | ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\t'|'\\n')+ -> skip ;\n\n[start]\ns\n\n[input]\n34 abc\n\n[output]\nDecision 0:\ns0-INT->s1\ns1-ID->:s2^=>1\n\n[errors]\nline 1:3 reportAttemptingFullContext d=0 (e), input='34abc'\nline 1:0 reportContextSensitivity d=0 (e), input='34'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/AmbigLR_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar Expr;\nprog:   stat ;\nstat:   expr NEWLINE       # printExpr\n    |   ID '=' expr NEWLINE# assign\n    |   NEWLINE   # blank\n    ;\nexpr:   expr ('*'|'/') expr      # MulDiv\n    |   expr ('+'|'-') expr      # AddSub\n    |   INT    # int\n    |   ID     # id\n    |   '(' expr ')'    # parens\n    ;\n\nMUL :   '*' ; // assigns token name to '*' used above in grammar\nDIV :   '/' ;\nADD :   '+' ;\nSUB :   '-' ;\nID  :   [a-zA-Z]+ ;      // match identifiers\nINT :   [0-9]+ ;// match integers\nNEWLINE:'\\r'? '\\n' ;     // return newlines to parser (is end-statement signal)\nWS  :   [ \\t]+ -> skip ; // toss out whitespace\n\n[start]\nprog\n\n[input]\n\"\"\"1\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/AmbigLR_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar Expr;\nprog:   stat ;\nstat:   expr NEWLINE       # printExpr\n    |   ID '=' expr NEWLINE# assign\n    |   NEWLINE   # blank\n    ;\nexpr:   expr ('*'|'/') expr      # MulDiv\n    |   expr ('+'|'-') expr      # AddSub\n    |   INT    # int\n    |   ID     # id\n    |   '(' expr ')'    # parens\n    ;\n\nMUL :   '*' ; // assigns token name to '*' used above in grammar\nDIV :   '/' ;\nADD :   '+' ;\nSUB :   '-' ;\nID  :   [a-zA-Z]+ ;      // match identifiers\nINT :   [0-9]+ ;// match integers\nNEWLINE:'\\r'? '\\n' ;     // return newlines to parser (is end-statement signal)\nWS  :   [ \\t]+ -> skip ; // toss out whitespace\n\n[start]\nprog\n\n[input]\n\"\"\"a = 5\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/AmbigLR_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar Expr;\nprog:   stat ;\nstat:   expr NEWLINE       # printExpr\n    |   ID '=' expr NEWLINE# assign\n    |   NEWLINE   # blank\n    ;\nexpr:   expr ('*'|'/') expr      # MulDiv\n    |   expr ('+'|'-') expr      # AddSub\n    |   INT    # int\n    |   ID     # id\n    |   '(' expr ')'    # parens\n    ;\n\nMUL :   '*' ; // assigns token name to '*' used above in grammar\nDIV :   '/' ;\nADD :   '+' ;\nSUB :   '-' ;\nID  :   [a-zA-Z]+ ;      // match identifiers\nINT :   [0-9]+ ;// match integers\nNEWLINE:'\\r'? '\\n' ;     // return newlines to parser (is end-statement signal)\nWS  :   [ \\t]+ -> skip ; // toss out whitespace\n\n[start]\nprog\n\n[input]\n\"\"\"b = 6\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/AmbigLR_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar Expr;\nprog:   stat ;\nstat:   expr NEWLINE       # printExpr\n    |   ID '=' expr NEWLINE# assign\n    |   NEWLINE   # blank\n    ;\nexpr:   expr ('*'|'/') expr      # MulDiv\n    |   expr ('+'|'-') expr      # AddSub\n    |   INT    # int\n    |   ID     # id\n    |   '(' expr ')'    # parens\n    ;\n\nMUL :   '*' ; // assigns token name to '*' used above in grammar\nDIV :   '/' ;\nADD :   '+' ;\nSUB :   '-' ;\nID  :   [a-zA-Z]+ ;      // match identifiers\nINT :   [0-9]+ ;// match integers\nNEWLINE:'\\r'? '\\n' ;     // return newlines to parser (is end-statement signal)\nWS  :   [ \\t]+ -> skip ; // toss out whitespace\n\n[start]\nprog\n\n[input]\n\"\"\"a+b*2\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/AmbigLR_5.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar Expr;\nprog:   stat ;\nstat:   expr NEWLINE       # printExpr\n    |   ID '=' expr NEWLINE# assign\n    |   NEWLINE   # blank\n    ;\nexpr:   expr ('*'|'/') expr      # MulDiv\n    |   expr ('+'|'-') expr      # AddSub\n    |   INT    # int\n    |   ID     # id\n    |   '(' expr ')'    # parens\n    ;\n\nMUL :   '*' ; // assigns token name to '*' used above in grammar\nDIV :   '/' ;\nADD :   '+' ;\nSUB :   '-' ;\nID  :   [a-zA-Z]+ ;      // match identifiers\nINT :   [0-9]+ ;// match integers\nNEWLINE:'\\r'? '\\n' ;     // return newlines to parser (is end-statement signal)\nWS  :   [ \\t]+ -> skip ; // toss out whitespace\n\n[start]\nprog\n\n[input]\n\"\"\"(1+2)*3\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na\n\n[output]\n\"\"\"(s (declarator a) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_10.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(*a)[]\n\n[output]\n\"\"\"(s (declarator (declarator ( (declarator * (declarator a)) )) [ ]) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n*a\n\n[output]\n\"\"\"(s (declarator * (declarator a)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n**a\n\n[output]\n\"\"\"(s (declarator * (declarator * (declarator a))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na[3]\n\n[output]\n\"\"\"(s (declarator (declarator a) [ (e 3) ]) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_5.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nb[]\n\n[output]\n\"\"\"(s (declarator (declarator b) [ ]) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_6.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(a)\n\n[output]\n\"\"\"(s (declarator ( (declarator a) )) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_7.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na[]()\n\n[output]\n\"\"\"(s (declarator (declarator (declarator a) [ ]) ( )) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_8.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na[][]\n\n[output]\n\"\"\"(s (declarator (declarator (declarator a) [ ]) [ ]) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_9.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : declarator EOF ; // must indicate EOF can follow\ndeclarator\n        : declarator '[' e ']'\n        | declarator '[' ']'\n        | declarator '(' ')'\n        | '*' declarator // binds less tight than suffixes\n        | '(' declarator ')'\n        | ID\n        ;\ne : INT ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n*a[]\n\n[output]\n\"\"\"(s (declarator * (declarator (declarator a) [ ])) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/DirectCallToLeftRecursiveRule_1.txt",
    "content": "[notes]\nThis is a regression test for \"Support direct calls to left-recursive\nrules\".  https://github.com/antlr/antlr4/issues/161\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na @after {<ToStringTree(\"$ctx\"):writeln()>} : a ID\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\nx\n\n[output]\n\"\"\"(a x)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/DirectCallToLeftRecursiveRule_2.txt",
    "content": "[notes]\nThis is a regression test for \"Support direct calls to left-recursive\nrules\".  https://github.com/antlr/antlr4/issues/161\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na @after {<ToStringTree(\"$ctx\"):writeln()>} : a ID\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\nx y\n\n[output]\n\"\"\"(a (a x) y)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/DirectCallToLeftRecursiveRule_3.txt",
    "content": "[notes]\nThis is a regression test for \"Support direct calls to left-recursive\nrules\".  https://github.com/antlr/antlr4/issues/161\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na @after {<ToStringTree(\"$ctx\"):writeln()>} : a ID\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\nx y z\n\n[output]\n\"\"\"(a (a (a x) y) z)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Expressions_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\ne : e '.' ID\n  | e '.' 'this'\n  | '-' e\n  | e '*' e\n  | e ('+'|'-') e\n  | INT\n  | ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na\n\n[output]\n\"\"\"(s (e a) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Expressions_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\ne : e '.' ID\n  | e '.' 'this'\n  | '-' e\n  | e '*' e\n  | e ('+'|'-') e\n  | INT\n  | ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n1\n\n[output]\n\"\"\"(s (e 1) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Expressions_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\ne : e '.' ID\n  | e '.' 'this'\n  | '-' e\n  | e '*' e\n  | e ('+'|'-') e\n  | INT\n  | ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na-1\n\n[output]\n\"\"\"(s (e (e a) - (e 1)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Expressions_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\ne : e '.' ID\n  | e '.' 'this'\n  | '-' e\n  | e '*' e\n  | e ('+'|'-') e\n  | INT\n  | ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na.b\n\n[output]\n\"\"\"(s (e (e a) . b) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Expressions_5.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\ne : e '.' ID\n  | e '.' 'this'\n  | '-' e\n  | e '*' e\n  | e ('+'|'-') e\n  | INT\n  | ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na.this\n\n[output]\n\"\"\"(s (e (e a) . this) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Expressions_6.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\ne : e '.' ID\n  | e '.' 'this'\n  | '-' e\n  | e '*' e\n  | e ('+'|'-') e\n  | INT\n  | ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n-a\n\n[output]\n\"\"\"(s (e - (e a)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Expressions_7.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\ne : e '.' ID\n  | e '.' 'this'\n  | '-' e\n  | e '*' e\n  | e ('+'|'-') e\n  | INT\n  | ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n-a+b\n\n[output]\n\"\"\"(s (e (e - (e a)) + (e b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na|b&c\n\n[output]\n\"\"\"(s (e (e a) | (e (e b) & (e c))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_10.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na.f(x)==T.c\n\n[output]\n\"\"\"(s (e (e (e (e a) . f) ( (expressionList (e x)) )) == (e (e T) . c)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_11.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na.f().g(x,1)\n\n[output]\n\"\"\"(s (e (e (e (e (e a) . f) ( )) . g) ( (expressionList (e x) , (e 1)) )) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_12.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nnew T[((n-1) * x) + 1]\n\n[output]\n\"\"\"(s (e new (typespec T) [ (e (e ( (e (e ( (e (e n) - (e 1)) )) * (e x)) )) + (e 1)) ]) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(a|b)&c\n\n[output]\n\"\"\"(s (e (e ( (e (e a) | (e b)) )) & (e c)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na > b\n\n[output]\n\"\"\"(s (e (e a) > (e b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na >> b\n\n[output]\n\"\"\"(s (e (e a) >> (e b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_5.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na=b=c\n\n[output]\n\"\"\"(s (e (e a) = (e (e b) = (e c))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_6.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na^b^c\n\n[output]\n\"\"\"(s (e (e a) ^ (e (e b) ^ (e c))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_7.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(T)x\n\n[output]\n\"\"\"(s (e ( (typespec T) ) (e x)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_8.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nnew A().b\n\n[output]\n\"\"\"(s (e (e new (typespec A) ( )) . b) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_9.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow\nexpressionList\n    :   e (',' e)*\n    ;\ne   :   '(' e ')'\n    |   'this'\n    |   'super'\n    |   INT\n    |   ID\n    |   typespec '.' 'class'\n    |   e '.' ID\n    |   e '.' 'this'\n    |   e '.' 'super' '(' expressionList? ')'\n    |   e '.' 'new' ID '(' expressionList? ')'\n    |   'new' typespec ( '(' expressionList? ')' | ('[' e ']')+)\n    |   e '[' e ']'\n    |   '(' typespec ')' e\n    |   e ('++' | '--')\n    |   e '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') e\n    |   ('~'|'!') e\n    |   e ('*'|'/'|'%') e\n    |   e ('+'|'-') e\n    |   e ('\\<\\<' | '>>>' | '>>') e\n    |   e ('\\<=' | '>=' | '>' | '\\<') e\n    |   e 'instanceof' e\n    |   e ('==' | '!=') e\n    |   e '&' e\n    |\\<assoc=right> e '^' e\n    |   e '|' e\n    |   e '&&' e\n    |   e '||' e\n    |   e '?' e ':' e\n    |\\<assoc=right>\n        e ('='\n |'+='\n |'-='\n |'*='\n |'/='\n |'&='\n |'|='\n |'^='\n |'>>='\n |'>>>='\n |'\\<\\<='\n |'%=') e\n    ;\ntypespec\n    : ID\n    | ID '[' ']'\n    | 'int'\n    | 'int' '[' ']'\n    ;\nID  : ('a'..'z'|'A'..'Z'|'_'|'$')+;\nINT : '0'..'9'+ ;\nWS  : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(T)t.f()\n\n[output]\n\"\"\"(s (e (e ( (typespec T) ) (e (e t) . f)) ( )) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/LabelsOnOpSubrule_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e;\ne : a=e op=('*'|'/') b=e  {}\n  | INT {}\n  | '(' x=e ')' {}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n4\n\n[output]\n\"\"\"(s (e 4))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/LabelsOnOpSubrule_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e;\ne : a=e op=('*'|'/') b=e  {}\n  | INT {}\n  | '(' x=e ')' {}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n1*2/3\n\n[output]\n\"\"\"(s (e (e (e 1) * (e 2)) / (e 3)))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/LabelsOnOpSubrule_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e;\ne : a=e op=('*'|'/') b=e  {}\n  | INT {}\n  | '(' x=e ')' {}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(1/2)*3\n\n[output]\n\"\"\"(s (e (e ( (e (e 1) / (e 2)) )) * (e 3)))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleActionsPredicatesOptions_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#625 \"Duplicate action breaks\noperator precedence\" https://github.com/antlr/antlr4/issues/625\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e ;\ne : a=e op=('*'|'/') b=e  {}{<True()>}?\n  | a=e op=('+'|'-') b=e  {}\\<p=3>{<True()>}?\\<fail='Message'>\n  | INT {}{}\n  | '(' x=e ')' {}{}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\n4\n\n[output]\n\"\"\"(s (e 4))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleActionsPredicatesOptions_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#625 \"Duplicate action breaks\noperator precedence\" https://github.com/antlr/antlr4/issues/625\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e ;\ne : a=e op=('*'|'/') b=e  {}{<True()>}?\n  | a=e op=('+'|'-') b=e  {}\\<p=3>{<True()>}?\\<fail='Message'>\n  | INT {}{}\n  | '(' x=e ')' {}{}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\n1*2/3\n\n[output]\n\"\"\"(s (e (e (e 1) * (e 2)) / (e 3)))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleActionsPredicatesOptions_3.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#625 \"Duplicate action breaks\noperator precedence\" https://github.com/antlr/antlr4/issues/625\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e ;\ne : a=e op=('*'|'/') b=e  {}{<True()>}?\n  | a=e op=('+'|'-') b=e  {}\\<p=3>{<True()>}?\\<fail='Message'>\n  | INT {}{}\n  | '(' x=e ')' {}{}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\n(1/2)*3\n\n[output]\n\"\"\"(s (e (e ( (e (e 1) / (e 2)) )) * (e 3)))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleActions_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#625 \"Duplicate action breaks\noperator precedence\" https://github.com/antlr/antlr4/issues/625\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e ;\ne : a=e op=('*'|'/') b=e  {}{}\n  | INT {}{}\n  | '(' x=e ')' {}{}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n4\n\n[output]\n\"\"\"(s (e 4))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleActions_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#625 \"Duplicate action breaks\noperator precedence\" https://github.com/antlr/antlr4/issues/625\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e ;\ne : a=e op=('*'|'/') b=e  {}{}\n  | INT {}{}\n  | '(' x=e ')' {}{}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n1*2/3\n\n[output]\n\"\"\"(s (e (e (e 1) * (e 2)) / (e 3)))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleActions_3.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#625 \"Duplicate action breaks\noperator precedence\" https://github.com/antlr/antlr4/issues/625\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e ;\ne : a=e op=('*'|'/') b=e  {}{}\n  | INT {}{}\n  | '(' x=e ')' {}{}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(1/2)*3\n\n[output]\n\"\"\"(s (e (e ( (e (e 1) / (e 2)) )) * (e 3)))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleAlternativesWithCommonLabel_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#433 \"Not all context accessor\nmethods are generated when an alternative rule label is used for multiple\nalternatives\".  https://github.com/antlr/antlr4/issues/433\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : e '*' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> * <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | e '+' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> + <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | INT{$v = $INT.int;} # anInt\n  | '(' e ')'   {$v = $e.v;}     # parens\n  | left=e INC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"INC()\"):Concat(\" != null\"):Assert()>$v = $left.v + 1;}      # unary\n  | left=e DEC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"DEC()\"):Concat(\" != null\"):Assert()>$v = $left.v - 1;}      # unary\n  | ID {<AssignLocal(\"$v\",\"3\")>}        # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nINC : '++' ;\nDEC : '--' ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\n4\n\n[output]\n\"\"\"4\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleAlternativesWithCommonLabel_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#433 \"Not all context accessor\nmethods are generated when an alternative rule label is used for multiple\nalternatives\".  https://github.com/antlr/antlr4/issues/433\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : e '*' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> * <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | e '+' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> + <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | INT{$v = $INT.int;} # anInt\n  | '(' e ')'   {$v = $e.v;}     # parens\n  | left=e INC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"INC()\"):Concat(\" != null\"):Assert()>$v = $left.v + 1;}      # unary\n  | left=e DEC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"DEC()\"):Concat(\" != null\"):Assert()>$v = $left.v - 1;}      # unary\n  | ID {<AssignLocal(\"$v\",\"3\")>}        # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nINC : '++' ;\nDEC : '--' ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\n1+2\n\n[output]\n\"\"\"3\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleAlternativesWithCommonLabel_3.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#433 \"Not all context accessor\nmethods are generated when an alternative rule label is used for multiple\nalternatives\".  https://github.com/antlr/antlr4/issues/433\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : e '*' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> * <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | e '+' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> + <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | INT{$v = $INT.int;} # anInt\n  | '(' e ')'   {$v = $e.v;}     # parens\n  | left=e INC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"INC()\"):Concat(\" != null\"):Assert()>$v = $left.v + 1;}      # unary\n  | left=e DEC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"DEC()\"):Concat(\" != null\"):Assert()>$v = $left.v - 1;}      # unary\n  | ID {<AssignLocal(\"$v\",\"3\")>}        # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nINC : '++' ;\nDEC : '--' ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\n1+2*3\n\n[output]\n\"\"\"7\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleAlternativesWithCommonLabel_4.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#433 \"Not all context accessor\nmethods are generated when an alternative rule label is used for multiple\nalternatives\".  https://github.com/antlr/antlr4/issues/433\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : e '*' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> * <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | e '+' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> + <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | INT{$v = $INT.int;} # anInt\n  | '(' e ')'   {$v = $e.v;}     # parens\n  | left=e INC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"INC()\"):Concat(\" != null\"):Assert()>$v = $left.v + 1;}      # unary\n  | left=e DEC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"DEC()\"):Concat(\" != null\"):Assert()>$v = $left.v - 1;}      # unary\n  | ID {<AssignLocal(\"$v\",\"3\")>}        # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nINC : '++' ;\nDEC : '--' ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\ni++*3\n\n[output]\n\"\"\"12\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/MultipleAlternativesWithCommonLabel_5.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#433 \"Not all context accessor\nmethods are generated when an alternative rule label is used for multiple\nalternatives\".  https://github.com/antlr/antlr4/issues/433\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : e '*' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> * <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | e '+' e     {$v = <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(0)}, {<Result(\"v\")>})> + <Cast(\"BinaryContext\",\"$ctx\"):SubContextLocal({<Production(\"e\")>(1)}, {<Result(\"v\")>})>;}  # binary\n  | INT{$v = $INT.int;} # anInt\n  | '(' e ')'   {$v = $e.v;}     # parens\n  | left=e INC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"INC()\"):Concat(\" != null\"):Assert()>$v = $left.v + 1;}      # unary\n  | left=e DEC  {<ContextRuleFunction(Cast(\"UnaryContext\",\"$ctx\"), \"DEC()\"):Concat(\" != null\"):Assert()>$v = $left.v - 1;}      # unary\n  | ID {<AssignLocal(\"$v\",\"3\")>}        # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nINC : '++' ;\nDEC : '--' ;\nWS : (' '|'\\n') -> skip;\n\n[start]\ns\n\n[input]\n(99)+3\n\n[output]\n\"\"\"102\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/PrecedenceFilterConsidersContext.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#509 \"Incorrect rule chosen in\nunambiguous grammar\".  https://github.com/antlr/antlr4/issues/509\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nprog\n@after {<ToStringTree(\"$ctx\"):writeln()>}\n: statement* EOF {};\nstatement: letterA | statement letterA 'b' ;\nletterA: 'a';\n\n[start]\nprog\n\n[input]\naa\n\n[output]\n\"\"\"(prog (statement (letterA a)) (statement (letterA a)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/PrefixAndOtherAlt_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF ;\nexpr : literal\n     | op expr\n     | expr op expr\n     ;\nliteral : '-'? Integer ;\nop : '+' | '-' ;\nInteger : [0-9]+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n-1\n\n[output]\n\"\"\"(s (expr (literal - 1)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/PrefixAndOtherAlt_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF ;\nexpr : literal\n     | op expr\n     | expr op expr\n     ;\nliteral : '-'? Integer ;\nop : '+' | '-' ;\nInteger : [0-9]+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n-1 + -1\n\n[output]\n\"\"\"(s (expr (expr (literal - 1)) (op +) (expr (literal - 1))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/PrefixOpWithActionAndLabel_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.result\")>} ;\ne returns [<StringType()> result]\n    :   ID '=' e1=e    {$result = <AppendStr(\"\\\"(\\\"\", AppendStr(\"$ID.text\", AppendStr(\"\\\"=\\\"\", AppendStr(\"$e1.result\", \"\\\")\\\"\"))))>;}\n    |   ID    {$result = $ID.text;}\n    |   e1=e '+' e2=e  {$result = <AppendStr(\"\\\"(\\\"\", AppendStr(\"$e1.result\", AppendStr(\"\\\"+\\\"\", AppendStr(\"$e2.result\", \"\\\")\\\"\"))))>;}\n    ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na\n\n[output]\n\"\"\"a\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/PrefixOpWithActionAndLabel_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.result\")>} ;\ne returns [<StringType()> result]\n    :   ID '=' e1=e    {$result = <AppendStr(\"\\\"(\\\"\", AppendStr(\"$ID.text\", AppendStr(\"\\\"=\\\"\", AppendStr(\"$e1.result\", \"\\\")\\\"\"))))>;}\n    |   ID    {$result = $ID.text;}\n    |   e1=e '+' e2=e  {$result = <AppendStr(\"\\\"(\\\"\", AppendStr(\"$e1.result\", AppendStr(\"\\\"+\\\"\", AppendStr(\"$e2.result\", \"\\\")\\\"\"))))>;}\n    ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na+b\n\n[output]\n\"\"\"(a+b)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/PrefixOpWithActionAndLabel_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.result\")>} ;\ne returns [<StringType()> result]\n    :   ID '=' e1=e    {$result = <AppendStr(\"\\\"(\\\"\", AppendStr(\"$ID.text\", AppendStr(\"\\\"=\\\"\", AppendStr(\"$e1.result\", \"\\\")\\\"\"))))>;}\n    |   ID    {$result = $ID.text;}\n    |   e1=e '+' e2=e  {$result = <AppendStr(\"\\\"(\\\"\", AppendStr(\"$e1.result\", AppendStr(\"\\\"+\\\"\", AppendStr(\"$e2.result\", \"\\\")\\\"\"))))>;}\n    ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na=b+c\n\n[output]\n\"\"\"((a=b)+c)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsAndLabels_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : q=e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : a=e op='*' b=e {$v = $a.v * $b.v;}  # mult\n  | a=e '+' b=e {$v = $a.v + $b.v;}     # add\n  | INT{$v = $INT.int;}        # anInt\n  | '(' x=e ')' {$v = $x.v;}   # parens\n  | x=e '++'    {$v = $x.v+1;} # inc\n  | e '--'   # dec\n  | ID {$v = 3;}      # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n4\n\n[output]\n\"\"\"4\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsAndLabels_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : q=e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : a=e op='*' b=e {$v = $a.v * $b.v;}  # mult\n  | a=e '+' b=e {$v = $a.v + $b.v;}     # add\n  | INT{$v = $INT.int;}        # anInt\n  | '(' x=e ')' {$v = $x.v;}   # parens\n  | x=e '++'    {$v = $x.v+1;} # inc\n  | e '--'   # dec\n  | ID {$v = 3;}      # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n1+2\n\n[output]\n\"\"\"3\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsAndLabels_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : q=e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : a=e op='*' b=e {$v = $a.v * $b.v;}  # mult\n  | a=e '+' b=e {$v = $a.v + $b.v;}     # add\n  | INT{$v = $INT.int;}        # anInt\n  | '(' x=e ')' {$v = $x.v;}   # parens\n  | x=e '++'    {$v = $x.v+1;} # inc\n  | e '--'   # dec\n  | ID {$v = 3;}      # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n1+2*3\n\n[output]\n\"\"\"7\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsAndLabels_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : q=e {<writeln(\"$e.v\")>};\ne returns [int v]\n  : a=e op='*' b=e {$v = $a.v * $b.v;}  # mult\n  | a=e '+' b=e {$v = $a.v + $b.v;}     # add\n  | INT{$v = $INT.int;}        # anInt\n  | '(' x=e ')' {$v = $x.v;}   # parens\n  | x=e '++'    {$v = $x.v+1;} # inc\n  | e '--'   # dec\n  | ID {$v = 3;}      # anID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\ni++*3\n\n[output]\n\"\"\"12\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList1_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr (',' b+=expr)* '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n;\n\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\n\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\na*b\n\n[output]\n\"\"\"(s (expr (expr a) * (expr b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList1_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr (',' b+=expr)* '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n;\n\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\n\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\na,c>>x\n\n[output]\n\"\"\"(s (expr (expr a) , (expr c) >> (expr x)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList1_3.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr (',' b+=expr)* '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n;\n\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\n\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\nx\n\n[output]\n\"\"\"(s (expr x) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList1_4.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr (',' b+=expr)* '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n;\n\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\n\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\na*b,c,x*y>>r\n\n[output]\n\"\"\"(s (expr (expr (expr a) * (expr b)) , (expr c) , (expr (expr x) * (expr y)) >> (expr r)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList2_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr ',' b+=expr #Comma\n    | b+=expr '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n   ;\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\na*b\n\n[output]\n\"\"\"(s (expr (expr a) * (expr b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList2_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr ',' b+=expr #Comma\n    | b+=expr '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n   ;\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\na,c>>x\n\n[output]\n\"\"\"(s (expr (expr (expr a) , (expr c)) >> (expr x)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList2_3.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr ',' b+=expr #Comma\n    | b+=expr '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n   ;\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\nx\n\n[output]\n\"\"\"(s (expr x) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActionsList2_4.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#677 \"labels not working in grammar\nfile\".  https://github.com/antlr/antlr4/issues/677\nThis test treats `,` and `>>` as part of a single compound operator (similar\nto a ternary operator).\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : expr EOF;\nexpr:\n    a=expr '*' a=expr #Factor\n    | b+=expr ',' b+=expr #Comma\n    | b+=expr '>>' c=expr #Send\n    | ID #JustId //semantic check on modifiers\n   ;\nID  : ('a'..'z'|'A'..'Z'|'_')\n      ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\na*b,c,x*y>>r\n\n[output]\n\"\"\"(s (expr (expr (expr (expr (expr a) * (expr b)) , (expr c)) , (expr (expr x) * (expr y))) >> (expr r)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActions_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v, <StringList()> ignored]\n  : a=e '*' b=e {$v = $a.v * $b.v;}\n  | a=e '+' b=e {$v = $a.v + $b.v;}\n  | INT {$v = $INT.int;}\n  | '(' x=e ')' {$v = $x.v;}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n4\n\n[output]\n\"\"\"4\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActions_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v, <StringList()> ignored]\n  : a=e '*' b=e {$v = $a.v * $b.v;}\n  | a=e '+' b=e {$v = $a.v + $b.v;}\n  | INT {$v = $INT.int;}\n  | '(' x=e ')' {$v = $x.v;}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n1+2\n\n[output]\n\"\"\"3\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActions_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v, <StringList()> ignored]\n  : a=e '*' b=e {$v = $a.v * $b.v;}\n  | a=e '+' b=e {$v = $a.v + $b.v;}\n  | INT {$v = $INT.int;}\n  | '(' x=e ')' {$v = $x.v;}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n1+2*3\n\n[output]\n\"\"\"7\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/ReturnValueAndActions_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e {<writeln(\"$e.v\")>};\ne returns [int v, <StringList()> ignored]\n  : a=e '*' b=e {$v = $a.v * $b.v;}\n  | a=e '+' b=e {$v = $a.v + $b.v;}\n  | INT {$v = $INT.int;}\n  | '(' x=e ')' {$v = $x.v;}\n  ;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n(1+2)*3\n\n[output]\n\"\"\"9\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/SemPred.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : a ;\na : a {<True()>}? ID\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx y z\n\n[output]\n\"\"\"(s (a (a (a x) y) z))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/SemPredFailOption.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : a ;\na : a ID {<False()>}?\\<fail='custom message'>\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx y z\n\n[output]\n\"\"\"(s (a (a x) y z))\n\"\"\"\n\n[errors]\n\"\"\"line 1:4 rule a custom message\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Simple_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : a ;\na : a ID\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx\n\n[output]\n\"\"\"(s (a x))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Simple_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : a ;\na : a ID\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx y\n\n[output]\n\"\"\"(s (a (a x) y))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Simple_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : a ;\na : a ID\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx y z\n\n[output]\n\"\"\"(s (a (a (a x) y) z))\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na\n\n[output]\n\"\"\"(s (e a) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na+b\n\n[output]\n\"\"\"(s (e (e a) + (e b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_3.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na*b\n\n[output]\n\"\"\"(s (e (e a) * (e b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_4.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b:c\n\n[output]\n\"\"\"(s (e (e a) ? (e b) : (e c)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_5.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na=b=c\n\n[output]\n\"\"\"(s (e (e a) = (e (e b) = (e c))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_6.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b+c:d\n\n[output]\n\"\"\"(s (e (e a) ? (e (e b) + (e c)) : (e d)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_7.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b=c:d\n\n[output]\n\"\"\"(s (e (e a) ? (e (e b) = (e c)) : (e d)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_8.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na? b?c:d : e\n\n[output]\n\"\"\"(s (e (e a) ? (e (e b) ? (e c) : (e d)) : (e e)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExprExplicitAssociativity_9.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#542 \"First alternative cannot\nbe right-associative\".  https://github.com/antlr/antlr4/issues/542\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne :\\<assoc=right> e '*' e\n  |\\<assoc=right> e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b: c?d:e\n\n[output]\n\"\"\"(s (e (e a) ? (e b) : (e (e c) ? (e d) : (e e))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na\n\n[output]\n\"\"\"(s (e a) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na+b\n\n[output]\n\"\"\"(s (e (e a) + (e b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na*b\n\n[output]\n\"\"\"(s (e (e a) * (e b)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b:c\n\n[output]\n\"\"\"(s (e (e a) ? (e b) : (e c)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_5.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na=b=c\n\n[output]\n\"\"\"(s (e (e a) = (e (e b) = (e c))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_6.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b+c:d\n\n[output]\n\"\"\"(s (e (e a) ? (e (e b) + (e c)) : (e d)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_7.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b=c:d\n\n[output]\n\"\"\"(s (e (e a) ? (e (e b) = (e c)) : (e d)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_8.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na? b?c:d : e\n\n[output]\n\"\"\"(s (e (e a) ? (e (e b) ? (e c) : (e d)) : (e e)) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/TernaryExpr_9.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns @after {<ToStringTree(\"$ctx\"):writeln()>} : e EOF ; // must indicate EOF can follow or 'a\\<EOF>' won't match\ne : e '*' e\n  | e '+' e\n  |\\<assoc=right> e '?' e ':' e\n  |\\<assoc=right> e '=' e\n  | ID\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na?b: c?d:e\n\n[output]\n\"\"\"(s (e (e a) ? (e b) : (e (e c) ? (e d) : (e e))) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/WhitespaceInfluence_1.txt",
    "content": "[notes]\nThis is a regression test for #239 \"recoursive parser using implicit tokens\nignore white space lexer rule\".  https://github.com/antlr/antlr4/issues/239\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\nprog : expression EOF;\nexpression\n    : ID '(' expression (',' expression)* ')'      # doFunction\n    | '(' expression ')'# doParenthesis\n    | '!' expression    # doNot\n    | '-' expression    # doNegate\n    | '+' expression    # doPositiv\n    | expression '^' expression  # doPower\n    | expression '*' expression  # doMultipy\n    | expression '/' expression  # doDivide\n    | expression '%' expression  # doModulo\n    | expression '-' expression  # doMinus\n    | expression '+' expression  # doPlus\n    | expression '=' expression  # doEqual\n    | expression '!=' expression # doNotEqual\n    | expression '>' expression  # doGreather\n    | expression '>=' expression # doGreatherEqual\n    | expression '\\<' expression  # doLesser\n    | expression '\\<=' expression # doLesserEqual\n    | expression K_IN '(' expression (',' expression)* ')'  # doIn\n    | expression ( '&' | K_AND) expression# doAnd\n    | expression ( '|' | K_OR) expression # doOr\n    | '[' expression (',' expression)* ']'# newArray\n    | K_TRUE   # newTrueBoolean\n    | K_FALSE  # newFalseBoolean\n    | NUMBER   # newNumber\n    | DATE     # newDateTime\n    | ID       # newIdentifier\n    | SQ_STRING# newString\n    | K_NULL   # newNull\n    ;\n\n// Fragments\nfragment DIGIT    : '0' .. '9';\nfragment UPPER    : 'A' .. 'Z';\nfragment LOWER    : 'a' .. 'z';\nfragment LETTER   : LOWER | UPPER;\nfragment WORD     : LETTER | '_' | '$' | '#' | '.';\nfragment ALPHANUM : WORD | DIGIT;\n\n// Tokens\nID     : LETTER ALPHANUM*;\nNUMBER : DIGIT+ ('.' DIGIT+)? (('e'|'E')('+'|'-')? DIGIT+)?;\nDATE   : '\\'' DIGIT DIGIT DIGIT DIGIT '-' DIGIT DIGIT '-' DIGIT DIGIT (' ' DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT ('.' DIGIT+)?)? '\\'';\nSQ_STRING       : '\\'' ('\\'\\'' | ~'\\'')* '\\'';\nDQ_STRING       : '\"' ('\\\\\\\\\"' | ~'\"')* '\"';\nWS     : [ \\t\\n\\r]+ -> skip ;\nCOMMENTS        : ('/*' .*? '*' '/' | '//' ~'\\n'* '\\n' ) -> skip;\n\n[start]\nprog\n\n[input]\nTest(1,3)\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/WhitespaceInfluence_2.txt",
    "content": "[notes]\nThis is a regression test for #239 \"recoursive parser using implicit tokens\nignore white space lexer rule\".  https://github.com/antlr/antlr4/issues/239\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\nprog : expression EOF;\nexpression\n    : ID '(' expression (',' expression)* ')'      # doFunction\n    | '(' expression ')'# doParenthesis\n    | '!' expression    # doNot\n    | '-' expression    # doNegate\n    | '+' expression    # doPositiv\n    | expression '^' expression  # doPower\n    | expression '*' expression  # doMultipy\n    | expression '/' expression  # doDivide\n    | expression '%' expression  # doModulo\n    | expression '-' expression  # doMinus\n    | expression '+' expression  # doPlus\n    | expression '=' expression  # doEqual\n    | expression '!=' expression # doNotEqual\n    | expression '>' expression  # doGreather\n    | expression '>=' expression # doGreatherEqual\n    | expression '\\<' expression  # doLesser\n    | expression '\\<=' expression # doLesserEqual\n    | expression K_IN '(' expression (',' expression)* ')'  # doIn\n    | expression ( '&' | K_AND) expression# doAnd\n    | expression ( '|' | K_OR) expression # doOr\n    | '[' expression (',' expression)* ']'# newArray\n    | K_TRUE   # newTrueBoolean\n    | K_FALSE  # newFalseBoolean\n    | NUMBER   # newNumber\n    | DATE     # newDateTime\n    | ID       # newIdentifier\n    | SQ_STRING# newString\n    | K_NULL   # newNull\n    ;\n\n// Fragments\nfragment DIGIT    : '0' .. '9';\nfragment UPPER    : 'A' .. 'Z';\nfragment LOWER    : 'a' .. 'z';\nfragment LETTER   : LOWER | UPPER;\nfragment WORD     : LETTER | '_' | '$' | '#' | '.';\nfragment ALPHANUM : WORD | DIGIT;\n\n// Tokens\nID     : LETTER ALPHANUM*;\nNUMBER : DIGIT+ ('.' DIGIT+)? (('e'|'E')('+'|'-')? DIGIT+)?;\nDATE   : '\\'' DIGIT DIGIT DIGIT DIGIT '-' DIGIT DIGIT '-' DIGIT DIGIT (' ' DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT ('.' DIGIT+)?)? '\\'';\nSQ_STRING       : '\\'' ('\\'\\'' | ~'\\'')* '\\'';\nDQ_STRING       : '\"' ('\\\\\\\\\"' | ~'\"')* '\"';\nWS     : [ \\t\\n\\r]+ -> skip ;\nCOMMENTS        : ('/*' .*? '*' '/' | '//' ~'\\n'* '\\n' ) -> skip;\n\n[start]\nprog\n\n[input]\nTest(1, 3)\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/DFAToATNThatFailsBackToDFA.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'ab' ;\nB : 'abc' ;\n\n[input]\nababx\n\n[output]\n[@0,0:1='ab',<1>,1:0]\n[@1,2:3='ab',<1>,1:2]\n[@2,5:4='<EOF>',<-1>,1:5]\n\n[errors]\n\"\"\"line 1:4 token recognition error at: 'x'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/DFAToATNThatMatchesThenFailsInATN.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'ab' ;\nB : 'abc' ;\nC : 'abcd' ;\n\n[input]\nababcx\n\n[output]\n[@0,0:1='ab',<1>,1:0]\n[@1,2:4='abc',<2>,1:2]\n[@2,6:5='<EOF>',<-1>,1:6]\n\n[errors]\n\"\"\"line 1:5 token recognition error at: 'x'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/EnforcedGreedyNestedBraces_1.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nACTION : '{' (ACTION | ~[{}])* '}';\nWS : [ \\r\\n\\t]+ -> skip;\n\n[input]\n{ { } }\n\n[output]\n[@0,0:6='{ { } }',<1>,1:0]\n[@1,7:6='<EOF>',<-1>,1:7]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/EnforcedGreedyNestedBraces_2.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nACTION : '{' (ACTION | ~[{}])* '}';\nWS : [ \\r\\n\\t]+ -> skip;\n\n[input]\n{ { }\n\n[output]\n\"\"\"[@0,5:4='<EOF>',<-1>,1:5]\n\"\"\"\n\n[errors]\n\"\"\"line 1:0 token recognition error at: '{ { }'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/ErrorInMiddle.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'abc' ;\n\n[input]\nabx\n\n[output]\n\"\"\"[@0,3:2='<EOF>',<-1>,1:3]\n\"\"\"\n\n[errors]\n\"\"\"line 1:0 token recognition error at: 'abx'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/InvalidCharAtStart.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'a' 'b' ;\n\n[input]\nx\n\n[output]\n\"\"\"[@0,1:0='<EOF>',<-1>,1:1]\n\"\"\"\n\n[errors]\n\"\"\"line 1:0 token recognition error at: 'x'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/InvalidCharAtStartAfterDFACache.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'a' 'b' ;\n\n[input]\nabx\n\n[output]\n[@0,0:1='ab',<1>,1:0]\n[@1,3:2='<EOF>',<-1>,1:3]\n\n[errors]\n\"\"\"line 1:2 token recognition error at: 'x'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/InvalidCharInToken.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'a' 'b' ;\n\n[input]\nax\n\n[output]\n\"\"\"[@0,2:1='<EOF>',<-1>,1:2]\n\"\"\"\n\n[errors]\n\"\"\"line 1:0 token recognition error at: 'ax'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/InvalidCharInTokenAfterDFACache.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'a' 'b' ;\n\n[input]\nabax\n\n[output]\n[@0,0:1='ab',<1>,1:0]\n[@1,4:3='<EOF>',<-1>,1:4]\n\n[errors]\n\"\"\"line 1:2 token recognition error at: 'ax'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/LexerExecDFA.txt",
    "content": "[notes]\nThis is a regression test for #45 \"NullPointerException in LexerATNSimulator.execDFA\".  https://github.com/antlr/antlr4/issues/46\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCOLON : ':' ;\nPTR : '->' ;\nID : [a-z]+;\n\n[input]\nx : x\n\n[output]\n[@0,0:0='x',<3>,1:0]\n[@1,2:2=':',<1>,1:2]\n[@2,4:4='x',<3>,1:4]\n[@3,5:4='<EOF>',<-1>,1:5]\n\n[errors]\nline 1:1 token recognition error at: ' '\nline 1:3 token recognition error at: ' '\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/StringsEmbeddedInActions_1.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nACTION2 : '[' (STRING | ~'\"')*? ']';\nSTRING : '\"' ('\\\\\\\\' '\"' | .)*? '\"';\nWS : [ \\t\\r\\n]+ -> skip;\n\n[input]\n[\"foo\"]\n\n[output]\n[@0,0:6='[\"foo\"]',<1>,1:0]\n[@1,7:6='<EOF>',<-1>,1:7]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/StringsEmbeddedInActions_2.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nACTION2 : '[' (STRING | ~'\"')*? ']';\nSTRING : '\"' ('\\\\\\\\' '\"' | .)*? '\"';\nWS : [ \\t\\r\\n]+ -> skip;\n\n[input]\n[\"foo]\n\n[output]\n\"\"\"[@0,6:5='<EOF>',<-1>,1:6]\n\"\"\"\n\n[errors]\n\"\"\"line 1:0 token recognition error at: '[\"foo]'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/ActionPlacement.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : ({<PlusText(\"stuff fail: \"):writeln()>} 'a'\n| {<PlusText(\"stuff0:\"):writeln()>}\n       'a' {<PlusText(\"stuff1: \"):writeln()>}\n       'b' {<PlusText(\"stuff2: \"):writeln()>})\n       {<Text():writeln()>} ;\nWS : (' '|'\\n') -> skip ;\nJ : .;\n\n[input]\nab\n\n[output]\nstuff0:\nstuff1: a\nstuff2: ab\nab\n[@0,0:1='ab',<1>,1:0]\n[@1,2:1='<EOF>',<-1>,1:2]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSet.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : '0'..'9'+ {<writeln(\"\\\"I\\\"\")>} ;\nWS : [ \\n\\\\u000D] -> skip ;\n\n[input]\n\"\"\"34\n 34\"\"\"\n\n[output]\nI\nI\n[@0,0:1='34',<1>,1:0]\n[@1,4:5='34',<1>,2:1]\n[@2,6:5='<EOF>',<-1>,2:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetInSet.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : (~[ab \\\\n]|'a')  {<writeln(\"\\\"I\\\"\")>} ;\nWS : [ \\n\\\\u000D]+ -> skip ;\n\n[input]\na x\n\n[output]\nI\nI\n[@0,0:0='a',<1>,1:0]\n[@1,2:2='x',<1>,1:2]\n[@2,3:2='<EOF>',<-1>,1:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetNot.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : ~[ab \\n] ~[ \\ncd]* {<writeln(\"\\\"I\\\"\")>} ;\nWS : [ \\n\\\\u000D]+ -> skip ;\n\n[input]\nxaf\n\n[output]\nI\n[@0,0:2='xaf',<1>,1:0]\n[@1,3:2='<EOF>',<-1>,1:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetPlus.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : '0'..'9'+ {<writeln(\"\\\"I\\\"\")>} ;\nWS : [ \\n\\\\u000D]+ -> skip ;\n\n[input]\n\"\"\"34\n 34\"\"\"\n\n[output]\nI\nI\n[@0,0:1='34',<1>,1:0]\n[@1,4:5='34',<1>,2:1]\n[@2,6:5='<EOF>',<-1>,2:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetRange.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : [0-9]+ {<writeln(\"\\\"I\\\"\")>} ;\nID : [a-zA-Z] [a-zA-Z0-9]* {<writeln(\"\\\"ID\\\"\")>} ;\nWS : [ \\n\\\\u0009\\r]+ -> skip ;\n\n[input]\n\"\"\"34\n 34 a2 abc \n   \"\"\"\n\n[output]\nI\nI\nID\nID\n[@0,0:1='34',<1>,1:0]\n[@1,4:5='34',<1>,2:1]\n[@2,7:8='a2',<2>,2:4]\n[@3,10:12='abc',<2>,2:7]\n[@4,18:17='<EOF>',<-1>,3:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetWithEscapedChar.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nDASHBRACK : [\\\\-\\]]+ {<writeln(\"\\\"DASHBRACK\\\"\")>} ;\nWS : [ \\n]+ -> skip ;\n\n[input]\n\"\"\"- ] \"\"\"\n\n[output]\nDASHBRACK\nDASHBRACK\n[@0,0:0='-',<1>,1:0]\n[@1,2:2=']',<1>,1:2]\n[@2,4:3='<EOF>',<-1>,1:4]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetWithMissingEscapeChar.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : [0-9]+ {<writeln(\"\\\"I\\\"\")>} ;\nWS : [ \\n]+ -> skip ;\n\n[input]\n\"\"\"34 \"\"\"\n\n[output]\nI\n[@0,0:1='34',<1>,1:0]\n[@1,3:2='<EOF>',<-1>,1:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetWithQuote1.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : [\"a-z]+ {<writeln(\"\\\"A\\\"\")>} ;\nWS : [ \\n\\t]+ -> skip ;\n\n[input]\nb\"a\n\n[output]\nA\n[@0,0:2='b\"a',<1>,1:0]\n[@1,3:2='<EOF>',<-1>,1:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetWithQuote2.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : [\"\\\\\\\\ab]+ {<writeln(\"\\\"A\\\"\")>} ;\nWS : [ \\n\\t]+ -> skip ;\n\n[input]\nb\"\\a\n\n[output]\nA\n[@0,0:3='b\"\\a',<1>,1:0]\n[@1,4:3='<EOF>',<-1>,1:4]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/EOFByItself.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nDONE : EOF ;\nA : 'a';\n\n[input]\n\n\n[output]\n[@0,0:-1='<EOF>',<1>,1:0]\n[@1,0:-1='<EOF>',<-1>,1:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/EOFSuffixInFirstRule_1.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'a' EOF ;\nB : 'a';\nC : 'c';\n\n[input]\n\n\n[output]\n\"\"\"[@0,0:-1='<EOF>',<-1>,1:0]\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/EOFSuffixInFirstRule_2.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : 'a' EOF ;\nB : 'a';\nC : 'c';\n\n[input]\na\n\n[output]\n[@0,0:0='a',<1>,1:0]\n[@1,1:0='<EOF>',<-1>,1:1]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/EscapeTargetStringLiteral.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#2709 \"PHP target generates\ninvalid output when $ is used as part of the literal in lexer rule\"\nhttps://github.com/antlr/antlr4/issues/2709\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\nACTION_WITH_DOLLAR: '$ACTION';\n\n[output]\n\"\"\"[@0,0:-1='<EOF>',<-1>,1:0]\n\"\"\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/EscapedCharacters.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nLF : '\\\\u000A';\nX  : 'x';\n\n[input]\n\"\"\"x\n\"\"\"\n\n[output]\n[@0,0:0='x',<2>,1:0]\n[@1,1:1='\\n',<1>,1:1]\n[@2,2:1='<EOF>',<-1>,2:0]\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/GreedyClosure.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '//' .*? '\\n' CMT*;\nWS : (' '|'\\t')+;\n\n[input]\n//blah\n//blah\n\n[output]\n[@0,0:13='//blah\\n//blah\\n',<1>,1:0]\n[@1,14:13='<EOF>',<-1>,3:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/GreedyConfigs.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : ('a' | 'ab') {<Text():writeln()>} ;\nWS : (' '|'\\n') -> skip ;\nJ : .;\n\n[input]\nab\n\n[output]\nab\n[@0,0:1='ab',<1>,1:0]\n[@1,2:1='<EOF>',<-1>,1:2]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/GreedyOptional.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '//' .*? '\\n' CMT?;\nWS : (' '|'\\t')+;\n\n[input]\n//blah\n//blah\n\n[output]\n[@0,0:13='//blah\\n//blah\\n',<1>,1:0]\n[@1,14:13='<EOF>',<-1>,3:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/GreedyPositiveClosure.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : ('//' .*? '\\n')+;\nWS : (' '|'\\t')+;\n\n[input]\n//blah\n//blah\n\n[output]\n[@0,0:13='//blah\\n//blah\\n',<1>,1:0]\n[@1,14:13='<EOF>',<-1>,3:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/HexVsID.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nHexLiteral : '0' ('x'|'X') HexDigit+ ;\nDecimalLiteral : ('0' | '1'..'9' '0'..'9'*) ;\nFloatingPointLiteral : ('0x' | '0X') HexDigit* ('.' HexDigit*)? ;\nDOT : '.' ;\nID : 'a'..'z'+ ;\nfragment HexDigit : ('0'..'9'|'a'..'f'|'A'..'F') ;\nWS : (' '|'\\n')+;\n\n[input]\nx 0 1 a.b a.l\n\n[output]\n[@0,0:0='x',<5>,1:0]\n[@1,1:1=' ',<6>,1:1]\n[@2,2:2='0',<2>,1:2]\n[@3,3:3=' ',<6>,1:3]\n[@4,4:4='1',<2>,1:4]\n[@5,5:5=' ',<6>,1:5]\n[@6,6:6='a',<5>,1:6]\n[@7,7:7='.',<4>,1:7]\n[@8,8:8='b',<5>,1:8]\n[@9,9:9=' ',<6>,1:9]\n[@10,10:10='a',<5>,1:10]\n[@11,11:11='.',<4>,1:11]\n[@12,12:12='l',<5>,1:12]\n[@13,13:12='<EOF>',<-1>,1:13]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/KeywordID.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nKEND : 'end' ; // has priority\nID : 'a'..'z'+ ;\nWS : (' '|'\\n')+;\n\n[input]\nend eend ending a\n\n[output]\n[@0,0:2='end',<1>,1:0]\n[@1,3:3=' ',<3>,1:3]\n[@2,4:7='eend',<2>,1:4]\n[@3,8:8=' ',<3>,1:8]\n[@4,9:14='ending',<2>,1:9]\n[@5,15:15=' ',<3>,1:15]\n[@6,16:16='a',<2>,1:16]\n[@7,17:16='<EOF>',<-1>,1:17]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/NonGreedyClosure.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '//' .*? '\\n' CMT*?;\nWS : (' '|'\\t')+;\n\n[input]\n//blah\n//blah\n\n[output]\n[@0,0:6='//blah\\n',<1>,1:0]\n[@1,7:13='//blah\\n',<1>,2:0]\n[@2,14:13='<EOF>',<-1>,3:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/NonGreedyConfigs.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nI : .*? ('a' | 'ab') {<Text():writeln()>} ;\nWS : (' '|'\\n') -> skip ;\nJ : . {<Text():writeln()>};\n\n[input]\nab\n\n[output]\na\nb\n[@0,0:0='a',<1>,1:0]\n[@1,1:1='b',<3>,1:1]\n[@2,2:1='<EOF>',<-1>,1:2]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/NonGreedyOptional.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '//' .*? '\\n' CMT??;\nWS : (' '|'\\t')+;\n\n[input]\n//blah\n//blah\n\n[output]\n[@0,0:6='//blah\\n',<1>,1:0]\n[@1,7:13='//blah\\n',<1>,2:0]\n[@2,14:13='<EOF>',<-1>,3:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/NonGreedyPositiveClosure.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : ('//' .*? '\\n')+?;\nWS : (' '|'\\t')+;\n\n[input]\n//blah\n//blah\n\n[output]\n[@0,0:6='//blah\\n',<1>,1:0]\n[@1,7:13='//blah\\n',<1>,2:0]\n[@2,14:13='<EOF>',<-1>,3:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/NonGreedyTermination1.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nSTRING : '!' ('!!' | .)*? '!';\n\n[input]\n!hi!!mom!\n\n[output]\n[@0,0:3='!hi!',<1>,1:0]\n[@1,4:8='!mom!',<1>,1:4]\n[@2,9:8='<EOF>',<-1>,1:9]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/NonGreedyTermination2.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nSTRING : '!' ('!!' | .)+? '!';\n\n[input]\n!!!mom!\n\n[output]\n[@0,0:6='!!!mom!',<1>,1:0]\n[@1,7:6='<EOF>',<-1>,1:7]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/Parentheses.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#224: \"Parentheses without\nquantifier in lexer rules have unclear effect\".\nhttps://github.com/antlr/antlr4/issues/224\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\nSTART_BLOCK: '-.-.-';\nID : (LETTER SEPARATOR) (LETTER SEPARATOR)+;\nfragment LETTER: L_A|L_K;\nfragment L_A: '.-';\nfragment L_K: '-.-';\nSEPARATOR: '!';\n\n[input]\n-.-.-!\n\n[output]\n[@0,0:4='-.-.-',<1>,1:0]\n[@1,5:5='!',<3>,1:5]\n[@2,6:5='<EOF>',<-1>,1:6]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/PositionAdjustingLexer.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar PositionAdjustingLexer;\n\n@definitions {\n<PositionAdjustingLexerDef()>\n}\n\n@members {\n<PositionAdjustingLexer()>\n}\n\nASSIGN : '=' ;\nPLUS_ASSIGN : '+=' ;\nLCURLY:    '{';\n\n// 'tokens' followed by '{'\nTOKENS : 'tokens' IGNORED '{';\n\n// IDENTIFIER followed by '+=' or '='\nLABEL\n   :   IDENTIFIER IGNORED '+'? '='\n   ;\n\nIDENTIFIER\n   :   [a-zA-Z_] [a-zA-Z0-9_]*\n   ;\n\nfragment\nIGNORED\n   :   [ \\t\\r\\n]*\n   ;\n\nNEWLINE\n   :   [\\r\\n]+ -> skip\n   ;\n\nWS\n   :   [ \\t]+ -> skip\n   ;\n\n[input]\ntokens\ntokens {\nnotLabel\nlabel1 =\nlabel2 +=\nnotLabel\n\n[output]\n[@0,0:5='tokens',<6>,1:0]\n[@1,7:12='tokens',<4>,2:0]\n[@2,14:14='{',<3>,2:7]\n[@3,16:23='notLabel',<6>,3:0]\n[@4,25:30='label1',<5>,4:0]\n[@5,32:32='=',<1>,4:7]\n[@6,34:39='label2',<5>,5:0]\n[@7,41:42='+=',<2>,5:7]\n[@8,44:51='notLabel',<6>,6:0]\n[@9,53:52='<EOF>',<-1>,7:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/QuoteTranslation.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nQUOTE : '\"' ; // make sure this compiles\n\n[input]\n\"\n\n[output]\n[@0,0:0='\"',<1>,1:0]\n[@1,1:0='<EOF>',<-1>,1:1]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/RecursiveLexerRuleRefWithWildcardPlus_1.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '/*' (CMT | .)+? '*' '/' ;\nWS : (' '|'\\n')+;\n\n[input]\n/* ick */\n/* /* */\n/* /*nested*/ */\n\n[output]\n[@0,0:8='/* ick */',<1>,1:0]\n[@1,9:9='\\n',<2>,1:9]\n[@2,10:34='/* /* */\\n/* /*nested*/ */',<1>,2:0]\n[@3,35:35='\\n',<2>,3:16]\n[@4,36:35='<EOF>',<-1>,4:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/RecursiveLexerRuleRefWithWildcardPlus_2.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '/*' (CMT | .)+? '*' '/' ;\nWS : (' '|'\\n')+;\n\n[input]\n/* ick */x\n/* /* */x\n/* /*nested*/ */x\n\n[output]\n[@0,0:8='/* ick */',<1>,1:0]\n[@1,10:10='\\n',<2>,1:10]\n[@2,11:36='/* /* */x\\n/* /*nested*/ */',<1>,2:0]\n[@3,38:38='\\n',<2>,3:17]\n[@4,39:38='<EOF>',<-1>,4:0]\n\n[errors]\nline 1:9 token recognition error at: 'x'\nline 3:16 token recognition error at: 'x'\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/RecursiveLexerRuleRefWithWildcardStar_1.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '/*' (CMT | .)*? '*' '/' ;\nWS : (' '|'\\n')+;\n\n[input]\n/* ick */\n/* /* */\n/* /*nested*/ */\n\n[output]\n[@0,0:8='/* ick */',<1>,1:0]\n[@1,9:9='\\n',<2>,1:9]\n[@2,10:34='/* /* */\\n/* /*nested*/ */',<1>,2:0]\n[@3,35:35='\\n',<2>,3:16]\n[@4,36:35='<EOF>',<-1>,4:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/RecursiveLexerRuleRefWithWildcardStar_2.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nCMT : '/*' (CMT | .)*? '*' '/' ;\nWS : (' '|'\\n')+;\n\n[input]\n/* ick */x\n/* /* */x\n/* /*nested*/ */x\n\n[output]\n[@0,0:8='/* ick */',<1>,1:0]\n[@1,10:10='\\n',<2>,1:10]\n[@2,11:36='/* /* */x\\n/* /*nested*/ */',<1>,2:0]\n[@3,38:38='\\n',<2>,3:17]\n[@4,39:38='<EOF>',<-1>,4:0]\n\n[errors]\nline 1:9 token recognition error at: 'x'\nline 3:16 token recognition error at: 'x'\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/RefToRuleDoesNotSetTokenNorEmitAnother.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nA : '-' I ;\nI : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[input]\n34 -21 3\n\n[output]\n[@0,0:1='34',<2>,1:0]\n[@1,3:5='-21',<1>,1:3]\n[@2,7:7='3',<2>,1:7]\n[@3,8:7='<EOF>',<-1>,1:8]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/ReservedWordsEscaping.txt",
    "content": "[notes]\nhttps://github.com/antlr/antlr4/issues/1070\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\n\nchannels { break }\n\nA: 'a' -> mode(for);\n\nmode for;\nB: 'b' -> channel(break);\n\n[input]\nab\n\n[output]\n[@0,0:0='a',<1>,1:0]\n[@1,1:1='b',<2>,channel=2,1:1]\n[@2,2:1='<EOF>',<-1>,1:2]\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/ReservedWordsEscaping_NULL.txt",
    "content": "[notes]\nhttps://github.com/antlr/antlr4/pull/3889\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\n\nNULL : ('N' | 'n')('U' | 'u')('L' | 'l')('L' | 'l') ;\n\n[input]\nNULL\n\n[output]\n[@0,0:3='NULL',<1>,1:0]\n[@1,4:3='<EOF>',<-1>,1:4]\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/Slashes.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nBackslash : '\\\\\\\\';\nSlash : '/';\nVee : '\\\\\\\\/';\nWedge : '/\\\\\\\\';\nWS : [ \\t] -> skip;\n\n[input]\n\\ / \\/ /\\\n\n[output]\n[@0,0:0='\\',<1>,1:0]\n[@1,2:2='/',<2>,1:2]\n[@2,4:5='\\/',<3>,1:4]\n[@3,7:8='/\\',<4>,1:7]\n[@4,9:8='<EOF>',<-1>,1:9]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/StackoverflowDueToNotEscapedHyphen.txt",
    "content": "[notes]\nhttps://github.com/antlr/antlr4/issues/1943\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\nWORD   : [a-z-+]+;\n\n[input]\nword\n\n[output]\n[@0,0:3='word',<1>,1:0]\n[@1,4:3='<EOF>',<-1>,1:4]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/TokenType0xFFFF.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nT_FFFF: 'FFFF' -> type(65535);\n\n[input]\nFFFF\n\n[output]\n[@0,0:3='FFFF',<65535>,1:0]\n[@1,4:3='<EOF>',<-1>,1:4]\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/UnicodeCharSet.txt",
    "content": "[notes]\nregression test for antlr/antlr4#1925\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\nID : ([A-Z_]|'Ā'..'\\uFFFC') ([A-Z_0-9]|'Ā'..'\\uFFFC')*; // FFFD+ are not valid char\n\n[input]\n均\n\n[output]\n[@0,0:0='均',<1>,1:0]\n[@1,1:0='<EOF>',<-1>,1:1]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/ZeroLengthToken.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#687 \"Empty zero-length tokens\ncannot have lexer commands\" and antlr/antlr4#688 \"Lexer cannot match\nzero-length tokens\"\nhttps://github.com/antlr/antlr4/issues/687\nhttps://github.com/antlr/antlr4/issues/688\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\nBeginString\n   :   '\\'' -> more, pushMode(StringMode)\n   ;\nmode StringMode;\n   StringMode_X : 'x' -> more;\n   StringMode_Done : -> more, mode(EndStringMode);\nmode EndStringMode;\n   EndString : '\\'' -> popMode;\n\n[input]\n'xxx'\n\n[output]\n[@0,0:4=''xxx'',<1>,1:0]\n[@1,5:4='<EOF>',<-1>,1:5]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/Basic.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\n<ImportListener(\"T\")>\n<BasicListener(\"T\")>\n\ns\n@after {\n<ContextMember(\"$ctx\", \"r\"):ToStringTree():writeln()>\n<ContextMember(\"$ctx\", \"r\"):WalkListener()>\n}\n  : r=a ;\na : INT INT\n  | ID\n  ;\nMULT: '*' ;\nADD : '+' ;\nINT : [0-9]+ ;\nID  : [a-z]+ ;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\n1 2\n\n[output]\n(a 1 2)\n1\n2\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/LR.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\n<ImportListener(\"T\")>\n<LRListener(\"T\")>\n\ns\n@after {\n<ContextMember(\"$ctx\", \"r\"):ToStringTree():writeln()>\n<ContextMember(\"$ctx\", \"r\"):WalkListener()>\n}\n   : r=e ;\ne : e op='*' e\n   | e op='+' e\n   | INT\n   ;\nMULT: '*' ;\nADD : '+' ;\nINT : [0-9]+ ;\nID  : [a-z]+ ;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\n1+2*3\n\n[output]\n(e (e 1) + (e (e 2) * (e 3)))\n1\n2\n3\n2 3 2\n1 2 1\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/LRWithLabels.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\n<ImportListener(\"T\")>\n<LRWithLabelsListener(\"T\")>\n\ns\n@after {\n<ContextMember(\"$ctx\", \"r\"):ToStringTree():writeln()>\n<ContextMember(\"$ctx\", \"r\"):WalkListener()>\n}\n  : r=e ;\ne : e '(' eList ')' # Call\n  | INT    # Int\n  ;\neList : e (',' e)* ;\nMULT: '*' ;\nADD : '+' ;\nINT : [0-9]+ ;\nID  : [a-z]+ ;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\n1(2,3)\n\n[output]\n(e (e 1) ( (eList (e 2) , (e 3)) ))\n1\n2\n3\n1 [13 6]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/RuleGetters_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\n<ImportListener(\"T\")>\n<RuleGetterListener(\"T\")>\n\ns\n@after {\n<ContextMember(\"$ctx\", \"r\"):ToStringTree():writeln()>\n<ContextMember(\"$ctx\", \"r\"):WalkListener()>\n}\n  : r=a ;\na : b b        // forces list\n  | b      // a list still\n  ;\nb : ID | INT;\nMULT: '*' ;\nADD : '+' ;\nINT : [0-9]+ ;\nID  : [a-z]+ ;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\n1 2\n\n[output]\n(a (b 1) (b 2))\n1 2 1\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/RuleGetters_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\n<ImportListener(\"T\")>\n<RuleGetterListener(\"T\")>\n\ns\n@after {\n<ContextMember(\"$ctx\", \"r\"):ToStringTree():writeln()>\n<ContextMember(\"$ctx\", \"r\"):WalkListener()>\n}\n  : r=a ;\na : b b        // forces list\n  | b      // a list still\n  ;\nb : ID | INT;\nMULT: '*' ;\nADD : '+' ;\nINT : [0-9]+ ;\nID  : [a-z]+ ;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\nabc\n\n[output]\n(a (b abc))\nabc\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/TokenGetters_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\n<ImportListener(\"T\")>\n<TokenGetterListener(\"T\")>\n\ns\n@after {\n<ContextMember(\"$ctx\", \"r\"):ToStringTree():writeln()>\n<ContextMember(\"$ctx\", \"r\"):WalkListener()>\n}\n  : r=a ;\na : INT INT\n  | ID\n  ;\nMULT: '*' ;\nADD : '+' ;\nINT : [0-9]+ ;\nID  : [a-z]+ ;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\n1 2\n\n[output]\n(a 1 2)\n1 2 [1, 2]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/TokenGetters_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\n<ImportListener(\"T\")>\n<TokenGetterListener(\"T\")>\n\ns\n@after {\n<ContextMember(\"$ctx\", \"r\"):ToStringTree():writeln()>\n<ContextMember(\"$ctx\", \"r\"):WalkListener()>\n}\n  : r=a ;\na : INT INT\n  | ID\n  ;\nMULT: '*' ;\nADD : '+' ;\nINT : [0-9]+ ;\nID  : [a-z]+ ;\nWS : [ \\t\\n]+ -> skip ;\n\n[start]\ns\n\n[input]\nabc\n\n[output]\n(a abc)\n[@0,0:2='abc',<4>,1:0]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/AltNum.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\noptions { contextSuperClass=MyRuleNode; }\n\n<TreeNodeWithAltNumField(X=\"T\")>\n\n\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\n\na : 'f'\n  | 'g'\n  | 'x' b 'z'\n  ;\nb : 'e' {} | 'y'\n  ;\n\n[start]\ns\n\n[input]\nxyz\n\n[output]\n\"\"\"(a:3 x (b:2 y) z)\n\"\"\"\n\n[skip]\nGo\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/ExtraToken.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : 'x' 'y'\n  ;\nZ : 'z'\n  ;\n\n[start]\ns\n\n[input]\nxzy\n\n[output]\n\"\"\"(a x z y)\n\"\"\"\n\n[errors]\n\"\"\"line 1:1 extraneous input 'z' expecting 'y'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/ExtraTokensAndAltLabels.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$ctx\"):writeln()>\n}\n  : '${' v '}'\n  ;\n\nv : A #altA\n  | B #altB\n  ;\n\nA : 'a' ;\nB : 'b' ;\n\nWHITESPACE : [ \\n\\t\\r]+ -> channel(HIDDEN) ;\n\nERROR : . ;\n\n[start]\ns\n\n[input]\n${ ? a ?}\n\n[output]\n\"\"\"(s ${ (v ? a) ? })\n\"\"\"\n\n[errors]\nline 1:3 extraneous input '?' expecting {'a', 'b'}\nline 1:7 extraneous input '?' expecting '}'\n\n[skip]\nCpp\nGo\nPHP\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/NoViableAlt.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : 'x' | 'y'\n  ;\nZ : 'z'\n  ;\n\n[start]\ns\n\n[input]\nz\n\n[output]\n\"\"\"(a z)\n\"\"\"\n\n[errors]\n\"\"\"line 1:0 mismatched input 'z' expecting {'x', 'y'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/RuleRef.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : b 'x'\n  ;\nb : 'y'\n  ;\n\n[start]\ns\n\n[input]\nyx\n\n[output]\n\"\"\"(a (b y) x)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/Sync.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : 'x' 'y'* '!'\n  ;\nZ : 'z'\n  ;\n\n[start]\ns\n\n[input]\nxzyy!\n\n[output]\n\"\"\"(a x z y y !)\n\"\"\"\n\n[errors]\n\"\"\"line 1:1 extraneous input 'z' expecting {'y', '!'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/Token2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : 'x' 'y'\n  ;\n\n[start]\ns\n\n[input]\nxy\n\n[output]\n\"\"\"(a x y)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/TokenAndRuleContextString.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n<ImportRuleInvocationStack()>\n\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : 'x' {\n<RuleInvocationStack():writeln()>\n} ;\n\n[start]\ns\n\n[input]\nx\n\n[output]\n[a, s]\n(a x)\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/TwoAltLoop.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : ('x' | 'y')* 'z'\n  ;\n\n[start]\ns\n\n[input]\nxyyxyxz\n\n[output]\n\"\"\"(a x y y x y x z)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParseTrees/TwoAlts.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns\n@init {\n<BuildParseTrees()>\n}\n@after {\n<ToStringTree(\"$r.ctx\"):writeln()>\n}\n  : r=a ;\na : 'x' | 'y'\n  ;\n\n[start]\ns\n\n[input]\ny\n\n[output]\n\"\"\"(a y)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/ConjuringUpToken.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' x='b' {<Append(\"\\\"conjured=\\\"\",\"$x\"):writeln()>} 'c' ;\n\n[start]\na\n\n[input]\nac\n\n[output]\n\"\"\"conjured=[@-1,-1:-1='<missing 'b'>',<2>,1:1]\n\"\"\"\n\n[errors]\n\"\"\"line 1:1 missing 'b' at 'c'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/ConjuringUpTokenFromSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' x=('b'|'c') {<Append(\"\\\"conjured=\\\"\",\"$x\"):writeln()>} 'd' ;\n\n[start]\na\n\n[input]\nad\n\n[output]\n\"\"\"conjured=[@-1,-1:-1='<missing 'b'>',<2>,1:1]\n\"\"\"\n\n[errors]\n\"\"\"line 1:1 missing {'b', 'c'} at 'd'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/ContextListGetters.txt",
    "content": "[notes]\nRegression test for \"Getter for context is not a list when it should be\".\nhttps://github.com/antlr/antlr4/issues/19\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members{\n<DeclareContextListGettersFunction()>\n}\ns : (a | b)+;\na : 'a' {<write(\"\\\"a\\\"\")>};\nb : 'b' {<write(\"\\\"b\\\"\")>};\n\n[start]\ns\n\n[input]\nabab\n\n[output]\n\"\"\"abab\"\"\""
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/DuplicatedLeftRecursiveCall_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : expr EOF;\nexpr : 'x'\n     | expr expr\n     ;\n\n[start]\nstart\n\n[input]\nx\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/DuplicatedLeftRecursiveCall_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : expr EOF;\nexpr : 'x'\n     | expr expr\n     ;\n\n[start]\nstart\n\n[input]\nxx\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/DuplicatedLeftRecursiveCall_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : expr EOF;\nexpr : 'x'\n     | expr expr\n     ;\n\n[start]\nstart\n\n[input]\nxxx\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/DuplicatedLeftRecursiveCall_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : expr EOF;\nexpr : 'x'\n     | expr expr\n     ;\n\n[start]\nstart\n\n[input]\nxxxx\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/ExtraneousInput.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nmember : 'a';\nbody : member*;\nfile : body EOF;\nB : 'b';\n\n[start]\nfile\n\n[input]\nbaa\n\n[output]\n\n[errors]\n\"\"\"line 1:0 mismatched input 'b' expecting {<EOF>, 'a'}\n\"\"\"\n\n[skip]\nCpp\nCSharp\nGo\nJavaScript\nTypeScript\nPHP\nPython3\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/InvalidATNStateRemoval.txt",
    "content": "[notes]\nThis is a regression test for #45 \"NullPointerException in ATNConfig.hashCode\".\nhttps://github.com/antlr/antlr4/issues/45\nThe original cause of this issue was an error in the tool's ATN state optimization,\nwhich is now detected early in {@link ATNSerializer} by ensuring that all\nserialized transitions point to states which were not removed.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstart : ID ':' expr;\nexpr : primary expr? {<Pass()>} | expr '->' ID;\nprimary : ID;\nID : [a-z]+;\n\n[start]\nstart\n\n[input]\nx:x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/InvalidEmptyInput.txt",
    "content": "[notes]\nThis is a regression test for #6 \"NullPointerException in getMissingSymbol\".\nhttps://github.com/antlr/antlr4/issues/6\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstart : ID+;\nID : [a-z]+;\n\n[start]\nstart\n\n[input]\n\n\n[errors]\n\"\"\"line 1:0 mismatched input '<EOF>' expecting ID\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/LL1ErrorInfo.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : animal (AND acClass)? service EOF;\nanimal : (DOG | CAT );\nservice : (HARDWARE | SOFTWARE) ;\nAND : 'and';\nDOG : 'dog';\nCAT : 'cat';\nHARDWARE: 'hardware';\nSOFTWARE: 'software';\nWS : ' ' -> skip ;\nacClass\n@init\n{<GetExpectedTokenNames():writeln()>}\n  : ;\n\n[start]\nstart\n\n[input]\ndog and software\n\n[output]\n\"\"\"{'hardware', 'software'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/LL2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b'\n  | 'a' 'c'\n;\nq : 'e' ;\n\n[start]\na\n\n[input]\nae\n\n[errors]\n\"\"\"line 1:1 no viable alternative at input 'ae'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/LL3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b'* 'c'\n  | 'a' 'b' 'd'\n;\nq : 'e' ;\n\n[start]\na\n\n[input]\nabe\n\n[errors]\n\"\"\"line 1:2 no viable alternative at input 'abe'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/LLStar.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a'+ 'b'\n  | 'a'+ 'c'\n;\nq : 'e' ;\n\n[start]\na\n\n[input]\naaae\n\n[errors]\n\"\"\"line 1:3 no viable alternative at input 'aaae'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/MultiTokenDeletionBeforeLoop.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b'* 'c';\n\n[start]\na\n\n[input]\naacabc\n\n[errors]\n\"\"\"line 1:1 extraneous input 'a' expecting {'b', 'c'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/MultiTokenDeletionBeforeLoop2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' ('b'|'z'{<Pass()>})* 'c';\n\n[start]\na\n\n[input]\naacabc\n\n[errors]\n\"\"\"line 1:1 extraneous input 'a' expecting {'b', 'z', 'c'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/MultiTokenDeletionDuringLoop.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b'* 'c' ;\n\n[start]\na\n\n[input]\nabaaababc\n\n[errors]\nline 1:2 extraneous input 'a' expecting {'b', 'c'}\nline 1:6 extraneous input 'a' expecting {'b', 'c'}\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/MultiTokenDeletionDuringLoop2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' ('b'|'z'{<Pass()>})* 'c' ;\n\n[start]\na\n\n[input]\nabaaababc\n\n[errors]\nline 1:2 extraneous input 'a' expecting {'b', 'z', 'c'}\nline 1:6 extraneous input 'a' expecting {'b', 'z', 'c'}\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/NoViableAltAvoidance.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : e '!' ;\ne : 'a' 'b'\n  | 'a'\n  ;\nDOT : '.' ;\nWS : [ \\t\\r\\n]+ -> skip;\n\n[start]\ns\n\n[input]\na.\n\n[errors]\n\"\"\"line 1:1 mismatched input '.' expecting '!'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleSetInsertion.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' ('b'|'c') 'd' ;\n\n[start]\na\n\n[input]\nad\n\n[errors]\n\"\"\"line 1:1 missing {'b', 'c'} at 'd'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleSetInsertionConsumption.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nmyset: ('b'|'c') ;\na: 'a' myset 'd' {<writeln(Append(\"\\\"\\\"\",\"$myset.stop\"))>} ; <! bit complicated because of the JavaScript target !>\n\n[start]\na\n\n[input]\nad\n\n[output]\n\"\"\"[@0,0:0='a',<3>,1:0]\n\"\"\"\n\n[errors]\n\"\"\"line 1:1 missing {'b', 'c'} at 'd'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletion.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b' ;\n\n[start]\na\n\n[input]\naab\n\n[errors]\n\"\"\"line 1:1 extraneous input 'a' expecting 'b'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionBeforeAlt.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ('b' | 'c')\n;\nq : 'a'\n;\n\n[start]\na\n\n[input]\nac\n\n[errors]\n\"\"\"line 1:0 extraneous input 'a' expecting {'b', 'c'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionBeforeLoop.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b'* EOF ;\n\n[start]\na\n\n[input]\naabc\n\n[errors]\nline 1:1 extraneous input 'a' expecting {<EOF>, 'b'}\nline 1:3 token recognition error at: 'c'\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionBeforeLoop2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' ('b'|'z'{<Pass()>})* EOF ;\n\n[start]\na\n\n[input]\naabc\n\n[errors]\nline 1:1 extraneous input 'a' expecting {<EOF>, 'b', 'z'}\nline 1:3 token recognition error at: 'c'\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionBeforePredict.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a'+ 'b'\n  | 'a'+ 'c'\n;\nq : 'e' ;\n\n[start]\na\n\n[input]\ncaaab\n\n[errors]\n\"\"\"line 1:0 extraneous input 'c' expecting 'a'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionConsumption.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nmyset: ('b'|'c') ;\na: 'a' myset 'd' {<writeln(Append(\"\\\"\\\"\",\"$myset.stop\"))>} ; <! bit complicated because of the JavaScript target !>\n\n[start]\na\n\n[input]\naabd\n\n[output]\n\"\"\"[@2,2:2='b',<1>,1:2]\n\"\"\"\n\n[errors]\n\"\"\"line 1:1 extraneous input 'a' expecting {'b', 'c'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionDuringLoop.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b'* 'c' ;\n\n[start]\na\n\n[input]\nababbc\n\n[errors]\n\"\"\"line 1:2 extraneous input 'a' expecting {'b', 'c'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionDuringLoop2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' ('b'|'z'{<Pass()>})* 'c' ;\n\n[start]\na\n\n[input]\nababbc\n\n[errors]\n\"\"\"line 1:2 extraneous input 'a' expecting {'b', 'z', 'c'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenDeletionExpectingSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' ('b'|'c') ;\n\n[start]\na\n\n[input]\naab\n\n[errors]\n\"\"\"line 1:1 extraneous input 'a' expecting {'b', 'c'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/SingleTokenInsertion.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b' 'c' ;\n\n[start]\na\n\n[input]\nac\n\n[errors]\n\"\"\"line 1:1 missing 'b' at 'c'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/TokenMismatch.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : 'a' 'b' ;\n\n[start]\na\n\n[input]\naa\n\n[errors]\n\"\"\"line 1:1 mismatched input 'a' expecting 'b'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/TokenMismatch2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nstat:   ( '(' expr? ')' )? EOF ;\nexpr:   ID '=' STR ;\n\nERR :   '~FORCE_ERROR~' ;\nID  :   [a-zA-Z]+ ;\nSTR :   '\"' ~[\"]* '\"' ;\nWS  :   [ \\t\\r\\n]+ -> skip ;\n\n[start]\nstat\n\n[input]\n\"\"\"( ~FORCE_ERROR~ \"\"\"\n\n[errors]\n\"\"\"line 1:2 mismatched input '~FORCE_ERROR~' expecting {')', ID}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/TokenMismatch3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nexpression\n:   value\n|   expression op=AND expression\n|   expression op=OR expression\n;\nvalue\n:   BOOLEAN_LITERAL\n|   ID\n|   ID1\n|   '(' expression ')'\n;\n\nAND : '&&';\nOR  : '||';\n\nBOOLEAN_LITERAL : 'true' | 'false';\n\nID  : [a-z]+;\nID1 : '$';\n\nWS  : [ \\t\\r\\n]+ -> skip ;\n\n[start]\nexpression\n\n[input]\n\n\n[errors]\n\"\"\"line 1:0 mismatched input '<EOF>' expecting {'(', BOOLEAN_LITERAL, ID, '$'}\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/APlus.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ID+ {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\na b c\n\n[output]\n\"\"\"abc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AStar_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ID* {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\n\n\n[output]\n\"\"\"\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AStar_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ID* {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\na b c\n\n[output]\n\"\"\"abc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AorAPlus.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|ID)+ {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\na b c\n\n[output]\n\"\"\"abc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AorAStar_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|ID)* {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\n\n\n[output]\n\"\"\"\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AorAStar_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|ID)* {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\na b c\n\n[output]\n\"\"\"abc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AorB.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ID {\n<writeln(\"\\\"alt 1\\\"\")>\n} | INT {\n<writeln(\"\\\"alt 2\\\"\")>\n};\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\\\n') -> skip ;\n\n[start]\na\n\n[input]\n34\n\n[output]\n\"\"\"alt 2\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AorBPlus.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|INT{\n})+ {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\\\n') -> skip ;\n\n[start]\na\n\n[input]\na 34 c\n\n[output]\n\"\"\"a34c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AorBStar_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|INT{\n})* {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\\\n') -> skip ;\n\n[start]\na\n\n[input]\n\n\n[output]\n\"\"\"\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/AorBStar_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|INT{\n})* {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\\\n') -> skip ;\n\n[start]\na\n\n[input]\na 34 c\n\n[output]\n\"\"\"a34c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Basic.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ID INT {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\nabc 34\n\n[output]\n\"\"\"abc34\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/BuildParseTree_FALSE.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nr\n   : a b {<ToStringTree(\"$ctx\"):writeln()>}\n   ;\na\n   : A\n   ;\nb\n   : B\n   ;\nA  : 'A';\nB  : 'B';\nWS  : [ \\r\\n\\t]+ -> skip ;\n\n[start]\nr\n\n[input]\nA B\n\n[output]\n\"\"\"r\n\"\"\"\n\n[flags]\nnotBuildParseTree\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/BuildParseTree_TRUE.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nr\n   : a b {<ToStringTree(\"$ctx\"):writeln()>}\n   ;\na\n   : A\n   ;\nb\n   : B\n   ;\nA  : 'A';\nB  : 'B';\nWS  : [ \\r\\n\\t]+ -> skip ;\n\n[start]\nr\n\n[input]\nA B\n\n[output]\n\"\"\"(r (a A) (b B))\n\"\"\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/IfIfElseGreedyBinding1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : statement+ ;\nstatement : 'x' | ifStatement;\nifStatement : 'if' 'y' statement ('else' statement)? {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> channel(HIDDEN);\n\n[start]\nstart\n\n[input]\nif y if y x else x\n\n[output]\nif y x else x\nif y if y x else x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/IfIfElseGreedyBinding2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : statement+ ;\nstatement : 'x' | ifStatement;\nifStatement : 'if' 'y' statement ('else' statement|) {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> channel(HIDDEN);\n\n[start]\nstart\n\n[input]\nif y if y x else x\n\n[output]\nif y x else x\nif y if y x else x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/IfIfElseNonGreedyBinding1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : statement+ ;\nstatement : 'x' | ifStatement;\nifStatement : 'if' 'y' statement ('else' statement)?? {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> channel(HIDDEN);\n\n[start]\nstart\n\n[input]\nif y if y x else x\n\n[output]\nif y x\nif y if y x else x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/IfIfElseNonGreedyBinding2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nstart : statement+ ;\nstatement : 'x' | ifStatement;\nifStatement : 'if' 'y' statement (|'else' statement) {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> channel(HIDDEN);\n\n[start]\nstart\n\n[input]\nif y if y x else x\n\n[output]\nif y x\nif y if y x else x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Keyword_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nprogram : state*{<writeln(\"$text\")>} EOF ;\nstate: 'break;' | 'continue;' | 'return;' ;\n\n[start]\nprogram\n\n[input]\nbreak;continue;return;\n\n[output]\n\"\"\"break;continue;return;\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Keyword_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nprogram : sempred*{<writeln(\"$text\")>} EOF ;\nsempred: 'break;' | 'continue;' | 'return;' ;\n\n[start]\nprogram\n\n[input]\nbreak;continue;return;\n\n[output]\n\"\"\"break;continue;return;\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Keyword_3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nprogram : action*{<writeln(\"$text\")>} EOF ;\naction: 'break;' | 'continue;' | 'return;' ;\n\n[start]\nprogram\n\n[input]\nbreak;continue;return;\n\n[output]\n\"\"\"break;continue;return;\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Keyword_4.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nprogram : ruleIndexMap*{<writeln(\"$text\")>} EOF ;\nruleIndexMap: 'break;' | 'continue;' | 'return;' ;\n\n[start]\nprogram\n\n[input]\nbreak;continue;return;\n\n[output]\n\"\"\"break;continue;return;\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Keyword_5.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nprogram : addErrorListener*{<writeln(\"$text\")>} EOF ;\naddErrorListener: 'break;' | 'continue;' | 'return;' ;\n\n[start]\nprogram\n\n[input]\nbreak;continue;return;\n\n[output]\n\"\"\"break;continue;return;\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Keyword_6.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nprogram : reset*{<writeln(\"$text\")>} EOF ;\nreset: 'break;' | 'continue;' | 'return;' ;\n\n[start]\nprogram\n\n[input]\nbreak;continue;return;\n\n[output]\n\"\"\"break;continue;return;\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/LL1OptionalBlock_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|{}INT)? {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\n\n\n[output]\n\"\"\"\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/LL1OptionalBlock_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|{}INT)? {\n<writeln(\"$text\")>\n};\nID : 'a'..'z'+;\nINT : '0'..'9'+ ;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\na\n\n[output]\n\"\"\"a\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/LabelAliasingAcrossLabeledAlternatives.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#195 \"label 'label' type\nmismatch with previous definition: TOKEN_LABEL!=RULE_LABEL\"\nhttps://github.com/antlr/antlr4/issues/195\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstart : a* EOF;\na\n  : label=subrule {<writeln(\"$label.text\")>} #One\n  | label='y' {<writeln(\"$label.text\")>} #Two\n  ;\nsubrule : 'x';\nWS : (' '|'\\n') -> skip ;\n\n[start]\nstart\n\n[input]\nxy\n\n[output]\nx\ny\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Labels.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : b1=b b2+=b* b3+=';' ;\nb : id_=ID val+=INT*;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\nabc 34;\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/ListLabelForClosureContext.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#299 \"Repeating subtree not\naccessible in visitor\".  https://github.com/antlr/antlr4/issues/299\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nifStatement\n@after {\n<AssertIsList({<ContextListFunction(\"$ctx\",\"elseIfStatement\")>})>\n}\n    : 'if' expression\n      ( ( 'then'\n executableStatement*\n elseIfStatement*  // \\<--- problem is here; should yield a list not node\n elseStatement?\n 'end' 'if'\n        ) | executableStatement )\n    ;\n\nelseIfStatement\n    : 'else' 'if' expression 'then' executableStatement*\n    ;\nexpression : 'a' ;\nexecutableStatement : 'a' ;\nelseStatement : 'a' ;\n\n[start]\nexpression\n\n[input]\na\n\n[skip]\nGo"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/ListLabelsOnRuleRefStartOfAlt.txt",
    "content": "[notes]\nChecks that this compiles; see https://github.com/antlr/antlr4/issues/2016\n\n[type]\nParser\n\n[grammar]\ngrammar Test;\n\nexpression\n@after {\n<AssertIsList(\"$args\")>\n}\n    : op=NOT args+=expression\n    | args+=expression (op=AND args+=expression)+\n    | args+=expression (op=OR args+=expression)+\n    | IDENTIFIER\n    ;\n\nAND : 'and' ;\nOR : 'or' ;\nNOT : 'not' ;\nIDENTIFIER : [a-zA-Z_][a-zA-Z0-9_]* ;\nWS : [ \\t\\r\\n]+ -> skip ;\n\n[start]\nexpression\n\n[input]\na and b\n\n[skip]\nPHP"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/ListLabelsOnSet.txt",
    "content": "[notes]\nThis is a regression test for #270 \"Fix operator += applied to a set of\ntokens\".  https://github.com/antlr/antlr4/issues/270\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na : b b* ';' ;\nb : ID val+=(INT | FLOAT)*;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nFLOAT : [0-9]+ '.' [0-9]+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\nabc 34;\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/MultipleEOFHandling.txt",
    "content": "[notes]\nThis test ensures that {@link ParserATNSimulator} produces a correct\nresult when the grammar contains multiple explicit references to\n{@code EOF} inside of parser rules.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nprog : ('x' | 'x' 'y') EOF EOF;\n\n[start]\nprog\n\n[input]\nx\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/OpenDeviceStatement_Case1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#1545, case 1.\n\n[type]\nParser\n\n[grammar]\ngrammar OpenDeviceStatement;\nprogram : statement+ '.' ;\n\nstatement : 'OPEN' ( 'DEVICE' (  OPT1  |  OPT2  |  OPT3  )? )+ {<writeln(\"$text\")>} ;\n\nOPT1 : 'OPT-1';\nOPT2 : 'OPT-2';\nOPT3 : 'OPT-3';\n\nWS : (' '|'\\n')+ -> channel(HIDDEN);\n\n[start]\nstatement\n\n[input]\nOPEN DEVICE DEVICE\n\n[output]\n\"\"\"OPEN DEVICE DEVICE\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/OpenDeviceStatement_Case2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#1545, case 2.\n\n[type]\nParser\n\n[grammar]\ngrammar OpenDeviceStatement;\nprogram : statement+ '.' ;\n\nstatement : 'OPEN' ( 'DEVICE' (  (OPT1)  |  OPT2  |  OPT3  )? )+ {<writeln(\"$text\")>} ;\n\nOPT1 : 'OPT-1';\nOPT2 : 'OPT-2';\nOPT3 : 'OPT-3';\n\nWS : (' '|'\\n')+ -> channel(HIDDEN);\n\n[start]\nstatement\n\n[input]\nOPEN DEVICE DEVICE\n\n[output]\n\"\"\"OPEN DEVICE DEVICE\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/OpenDeviceStatement_Case3.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#1545, case 3.\n\n[type]\nParser\n\n[grammar]\ngrammar OpenDeviceStatement;\nprogram : statement+ '.' ;\n\nstatement : 'OPEN' ( 'DEVICE' (  (OPT1)  |  OPT2  |  OPT3  )? )+ {<writeln(\"$text\")>} ;\n\nOPT1 : 'OPT-1';\nOPT2 : 'OPT-2';\nOPT3 : 'OPT-3';\n\nWS : (' '|'\\n')+ -> channel(HIDDEN);\n\n[start]\nstatement\n\n[input]\nOPEN DEVICE DEVICE.\n\n[output]\n\"\"\"OPEN DEVICE DEVICE\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Optional_1.txt",
    "content": "[notes]\nThis test is meant to detect regressions of bug antlr/antlr4#41.\nhttps://github.com/antlr/antlr4/issues/41\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstat : ifstat | 'x';\nifstat : 'if' stat ('else' stat)?;\nWS : [ \\n\\t]+ -> skip ;\n\n[start]\nstat\n\n[input]\nx\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Optional_2.txt",
    "content": "[notes]\nThis test is meant to detect regressions of bug antlr/antlr4#41.\nhttps://github.com/antlr/antlr4/issues/41\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstat : ifstat | 'x';\nifstat : 'if' stat ('else' stat)?;\nWS : [ \\n\\t]+ -> skip ;\n\n[start]\nstat\n\n[input]\nif x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Optional_3.txt",
    "content": "[notes]\nThis test is meant to detect regressions of bug antlr/antlr4#41.\nhttps://github.com/antlr/antlr4/issues/41\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstat : ifstat | 'x';\nifstat : 'if' stat ('else' stat)?;\nWS : [ \\n\\t]+ -> skip ;\n\n[start]\nstat\n\n[input]\nif x else x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Optional_4.txt",
    "content": "[notes]\nThis test is meant to detect regressions of bug antlr/antlr4#41.\nhttps://github.com/antlr/antlr4/issues/41\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstat : ifstat | 'x';\nifstat : 'if' stat ('else' stat)?;\nWS : [ \\n\\t]+ -> skip ;\n\n[start]\nstat\n\n[input]\nif if x else x\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/OrderingPredicates.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#2301.\n\n[type]\nParser\n\n[grammar]\ngrammar Issue2301;\n\nSPACES: [ \\t\\r\\n]+ -> skip;\n\nAT: 'AT';\nX : 'X';\nY : 'Y';\n\nID: [A-Z]+;\n\nconstant\n: 'DUMMY'\n;\n\nexpr\n: ID constant?\n| expr AT X\n| expr AT Y\n;\n\n[start]\nexpr\n\n[input]\nPOINT AT X\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/ParserProperty.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#561 \"Issue with parser\ngeneration in 4.2.2\" https://github.com/antlr/antlr4/issues/561\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n<ParserPropertyMember()>\na : {<ParserPropertyCall({$parser}, \"Property()\")>}? ID {<writeln(\"\\\"valid\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\nabc\n\n[output]\n\"\"\"valid\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/PredicatedIfIfElse.txt",
    "content": "[notes]\nThis test is meant to test the expected solution to antlr/antlr4#42.\nhttps://github.com/antlr/antlr4/issues/42\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ns : stmt EOF ;\nstmt : ifStmt | ID;\nifStmt : 'if' ID stmt ('else' stmt | { <LANotEquals(\"1\", {T<ParserToken(\"Parser\", \"ELSE\")>})> }?);\nELSE : 'else';\nID : [a-zA-Z]+;\nWS : [ \\\\n\\\\t]+ -> skip;\n\n[start]\ns\n\n[input]\nif x if x a else b\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/PredictionIssue334.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#334 \"BailErrorStrategy: bails\non proper input\".  https://github.com/antlr/antlr4/issues/334\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nfile_ @init{\n<BailErrorStrategy()>\n}\n@after {\n<ToStringTree(\"$ctx\"):writeln()>\n}\n  :   item (SEMICOLON item)* SEMICOLON? EOF ;\nitem : A B?;\nSEMICOLON: ';';\nA : 'a'|'A';\nB : 'b'|'B';\nWS      : [ \\r\\t\\n]+ -> skip;\n\n[start]\nfile_\n\n[input]\na\n\n[output]\n\"\"\"(file_ (item a) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/PredictionMode_LL.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nr\n   : (a b | a) EOF {<ToStringTree(\"$ctx\"):writeln()>}\n   ;\na\n   : X Y?\n   ;\nb\n   : Y\n   ;\nX: 'X';\nY: 'Y';\nWS  : [ \\r\\n\\t]+ -> skip ;\n\n[start]\nr\n\n[input]\nX Y\n\n[output]\n\"\"\"(r (a X) (b Y) <EOF>)\n\"\"\"\n\n[flags]\npredictionMode=LL\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/PredictionMode_SLL.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n\nr\n   : (a b | a) EOF {<writeln(\"$text\")>}\n   ;\na\n   : X Y?\n   ;\nb\n   : Y\n   ;\nX: 'X';\nY: 'Y';\nWS  : [ \\r\\n\\t]+ -> skip ;\n\n[start]\nr\n\n[input]\nX Y\n\n[output]\n\"\"\"XY\n\"\"\"\n\n[errors]\n\"\"\"line 1:3 missing 'Y' at '<EOF>'\n\"\"\"\n\n[flags]\npredictionMode=SLL\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/ReferenceToATN_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#561 \"Issue with parser\ngeneration in 4.2.2\" https://github.com/antlr/antlr4/issues/561\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|ATN)* ATN? {<writeln(\"$text\")>} ;\nID : 'a'..'z'+ ;\nATN : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\n\n\n[output]\n\"\"\"\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/ReferenceToATN_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#561 \"Issue with parser\ngeneration in 4.2.2\" https://github.com/antlr/antlr4/issues/561\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na : (ID|ATN)* ATN? {<writeln(\"$text\")>} ;\nID : 'a'..'z'+ ;\nATN : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\na\n\n[input]\na 34 c\n\n[output]\n\"\"\"a34c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/ReservedWordsEscaping.txt",
    "content": "[notes]\nhttps://github.com/antlr/antlr4/issues/1070\n\n[type]\nParser\n\n[grammar]\ngrammar G;\n\nroot\n    : {0==0}? continue+ {<write(\"$text\")>}\n    ;\n\ncontinue returns [<IntArg(\"return\")>]\n    : for for? {1==1}?              #else\n    | break=BREAK BREAK+ (for | IF) #else\n    | if+=IF  if+=IF*               #int\n    | continue CONTINUE_ {<AssignLocal(\"$return\",\"0\")>}   #class\n    ;\n\nargs[int else] locals [<IntArg(\"return\")>]\n    : for\n    ;\n\nfor: FOR;\nFOR: 'for ';\nBREAK: 'break ';\nIF: 'if ';\nCONTINUE_: 'continue';\n\n[start]\nroot\n\n[input]\nfor for break break for if if for continue\n\n[output]\n\"\"\"for for break break for if if for continue\"\"\""
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/TokenOffset.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#2728\nIt should generate correct code for grammars with more than 65 tokens.\nhttps://github.com/antlr/antlr4/pull/2728#issuecomment-622940562\n\n[type]\nParser\n\n[grammar]\ngrammar L;\na : ('1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'|'10'|'11'|'12'|'13'|'14'|'15'|'16'\n|'17'|'18'|'19'|'20'|'21'|'22'|'23'|'24'|'25'|'26'|'27'|'28'|'29'|'30'|'31'|'32'\n|'33'|'34'|'35'|'36'|'37'|'38'|'39'|'40'|'41'|'42'|'43'|'44'|'45'|'46'|'47'|'48'\n|'49'|'50'|'51'|'52'|'53'|'54'|'55'|'56'|'57'|'58'|'59'|'60'|'61'|'62'|'63'|'64'\n|'65'|'66')+ {\n<writeln(\"$text\")>\n};\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\n12 34 56 66\n\n[output]\n\"\"\"12345666\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Wildcard.txt",
    "content": "[notes]\nMatch assignments, ignore other tokens with wildcard.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\na : (assign|.)+ EOF ;\nassign : ID '=' INT ';' {\n<writeln(\"$text\")>\n} ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip;\n\n[start]\na\n\n[input]\nx=10; abc;;;; y=99;\n\n[output]\nx=10;\ny=99;\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/uStartingCharDoesNotCauseIllegalUnicodeEscape.txt",
    "content": "[notes]\nTest for https://github.com/antlr/antlr4/issues/4128\n\n[type]\nParser\n\n[grammar]\ngrammar u;\nu : 'u' {<writeln(\"$text\")>};\n\n[start]\nu\n\n[input]\nu\n\n[output]\n\"\"\"u\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Performance/DropLoopEntryBranchInLRRule_1.txt",
    "content": "[notes]\nfor https://github.com/antlr/antlr4/issues/1398.\nSeeing through a large expression takes 5 _minutes_ on\nmy fast box to complete.  After fix, it's instantaneous.\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\n\nstat : expr ';'\n     | expr '.'\n     ;\n\nexpr\n   : ID\n   | 'not' expr\n   | expr 'and' expr\n   | expr 'or' expr\n   | '(' ID ')' expr\n   | expr '?' expr ':' expr\n   | 'between' expr 'and' expr\n   ;\n\nID: [a-zA-Z_][a-zA-Z_0-9]*;\nWS: [ \\t\\n\\r\\f]+ -> skip;\n\n[start]\nstat\n\n[input]\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7\n;\n\n[skip]\nPHP\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Performance/DropLoopEntryBranchInLRRule_2.txt",
    "content": "[notes]\nfor https://github.com/antlr/antlr4/issues/1398.\nSeeing through a large expression takes 5 _minutes_ on\nmy fast box to complete.  After fix, it's instantaneous.\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\n\nstat : expr ';'\n     | expr '.'\n     ;\n\nexpr\n   : ID\n   | 'not' expr\n   | expr 'and' expr\n   | expr 'or' expr\n   | '(' ID ')' expr\n   | expr '?' expr ':' expr\n   | 'between' expr 'and' expr\n   ;\n\nID: [a-zA-Z_][a-zA-Z_0-9]*;\nWS: [ \\t\\n\\r\\f]+ -> skip;\n\n[start]\nstat\n\n[input]\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7 or\nX1 and X2 and X3 and X4 and X5 and X6 and X7\n.\n\n[skip]\nPHP\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Performance/DropLoopEntryBranchInLRRule_3.txt",
    "content": "[notes]\nfor https://github.com/antlr/antlr4/issues/1398.\nSeeing through a large expression takes 5 _minutes_ on\nmy fast box to complete.  After fix, it's instantaneous.\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\n\nstat : expr ';'\n     | expr '.'\n     ;\n\nexpr\n   : ID\n   | 'not' expr\n   | expr 'and' expr\n   | expr 'or' expr\n   | '(' ID ')' expr\n   | expr '?' expr ':' expr\n   | 'between' expr 'and' expr\n   ;\n\nID: [a-zA-Z_][a-zA-Z_0-9]*;\nWS: [ \\t\\n\\r\\f]+ -> skip;\n\n[start]\nstat\n\n[input]\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7\n;\n\n[skip]\nPHP\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Performance/DropLoopEntryBranchInLRRule_4.txt",
    "content": "[notes]\nfor https://github.com/antlr/antlr4/issues/1398.\nSeeing through a large expression takes 5 _minutes_ on\nmy fast box to complete.  After fix, it's instantaneous.\nWas working for C++ but I think it was not parsing correctly (Nov 2022)\nSo I'll make it skip for now and will add bug. I believe it is not\nmerging arrays properly.\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\n\nstat : expr ';'\n     | expr '.'\n     ;\n\nexpr\n   : ID\n   | 'not' expr\n   | expr 'and' expr\n   | expr 'or' expr\n   | '(' ID ')' expr\n   | expr '?' expr ':' expr\n   | 'between' expr 'and' expr\n   ;\n\nID: [a-zA-Z_][a-zA-Z_0-9]*;\nWS: [ \\t\\n\\r\\f]+ -> skip;\n\n[start]\nstat\n\n[input]\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4 and\nbetween X1 and X2 or between X3 and X4\n;\n\n[skip]\nPython3\nJavaScript\nTypeScript\nPHP\nGo\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Performance/DropLoopEntryBranchInLRRule_5.txt",
    "content": "[notes]\nfor https://github.com/antlr/antlr4/issues/1398.\nSeeing through a large expression takes 5 _minutes_ on\nmy fast box to complete.  After fix, it's instantaneous.\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\n\nstat : expr ';'\n     | expr '.'\n     ;\n\nexpr\n   : ID\n   | 'not' expr\n   | expr 'and' expr\n   | expr 'or' expr\n   | '(' ID ')' expr\n   | expr '?' expr ':' expr\n   | 'between' expr 'and' expr\n   ;\n\nID: [a-zA-Z_][a-zA-Z_0-9]*;\nWS: [ \\t\\n\\r\\f]+ -> skip;\n\n[start]\nstat\n\n[input]\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z or\nX ? Y : Z\n;\n\n[skip]\nPHP\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Performance/ExpressionGrammar_1.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#192 \"Poor performance of\nexpression parsing\".  https://github.com/antlr/antlr4/issues/192\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\n\nprogram: expr EOF;\n\nexpr\n   : ID\n   | 'not' expr\n   | expr 'and' expr\n   | expr 'or' expr\n   ;\n\nID: [a-zA-Z_][a-zA-Z_0-9]*;\nWS: [ \\t\\n\\r\\f]+ -> skip;\nERROR: .;\n\n[start]\nprogram\n\n[input]\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\n    X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Performance/ExpressionGrammar_2.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#192 \"Poor performance of\nexpression parsing\".  https://github.com/antlr/antlr4/issues/192\n\n[type]\nParser\n\n[grammar]\ngrammar Expr;\n\nprogram: expr EOF;\n\nexpr\n   : ID\n   | 'not' expr\n   | expr 'and' expr\n   | expr 'or' expr\n   ;\n\nID: [a-zA-Z_][a-zA-Z_0-9]*;\nWS: [ \\t\\n\\r\\f]+ -> skip;\nERROR: .;\n\n[start]\nprogram\n\n[input]\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12  or\nnot X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or     X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and     X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and     X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and     X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and     X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and     X6 and not X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and     X7 and not X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and     X8 and not X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and     X9 and not X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and     X10 and not X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and     X11 and not X12 or not X1 and not X2 and not X3 and not X4 and not X5 and not X6 and not X7 and not X8 and not X9 and not X10 and not X11 and     X12\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/DisableRule.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nE1 : 'enum' { <False()> }? ;\nE2 : 'enum' { <True()> }? ;  // winner not E1 or ID\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip;\n\n[input]\nenum abc\n\n[output]\n[@0,0:3='enum',<2>,1:0]\n[@1,5:7='abc',<3>,1:5]\n[@2,8:7='<EOF>',<-1>,1:8]\ns0-' '->:s5=>4\ns0-'a'->:s6=>3\ns0-'e'->:s1=>3\n:s1=>3-'n'->:s2=>3\n:s2=>3-'u'->:s3=>3\n:s6=>3-'b'->:s6=>3\n:s6=>3-'c'->:s6=>3\n\n[flags]\nshowDFA\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/EnumNotID.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nENUM : [a-z]+  { <TextEquals(\"enum\")> }? ;\nID : [a-z]+  ;\nWS : (' '|'\\n') -> skip;\n\n[input]\nenum abc enum\n\n[output]\n[@0,0:3='enum',<1>,1:0]\n[@1,5:7='abc',<2>,1:5]\n[@2,9:12='enum',<1>,1:9]\n[@3,13:12='<EOF>',<-1>,1:13]\ns0-' '->:s3=>3\n\n[flags]\nshowDFA\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/IDnotEnum.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nENUM : [a-z]+  { <False()> }? ;\nID : [a-z]+  ;\nWS : (' '|'\\n') -> skip;\n\n[input]\nenum abc enum\n\n[output]\n[@0,0:3='enum',<2>,1:0]\n[@1,5:7='abc',<2>,1:5]\n[@2,9:12='enum',<2>,1:9]\n[@3,13:12='<EOF>',<-1>,1:13]\ns0-' '->:s2=>3\n\n[flags]\nshowDFA\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/IDvsEnum.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nENUM : 'enum' { <False()> }? ;\nID : 'a'..'z'+ ;\nWS : (' '|'\\n') -> skip;\n\n[input]\nenum abc enum\n\n[output]\n[@0,0:3='enum',<2>,1:0]\n[@1,5:7='abc',<2>,1:5]\n[@2,9:12='enum',<2>,1:9]\n[@3,13:12='<EOF>',<-1>,1:13]\ns0-' '->:s5=>3\ns0-'a'->:s4=>2\ns0-'e'->:s1=>2\n:s1=>2-'n'->:s2=>2\n:s2=>2-'u'->:s3=>2\n:s4=>2-'b'->:s4=>2\n:s4=>2-'c'->:s4=>2\n\n[flags]\nshowDFA\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/Indent.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nID : [a-z]+  ;\nINDENT : [ \\t]+ { <TokenStartColumnEquals(\"0\")> }?\n{ <writeln(\"\\\"INDENT\\\"\")> }  ;\nNL : '\\n';\nWS : [ \\t]+ ;\n\n[input]\n\"\"\"abc\n  def  \n\"\"\"\n\n[output]\nINDENT\n[@0,0:2='abc',<1>,1:0]\n[@1,3:3='\\n',<3>,1:3]\n[@2,4:5='  ',<2>,2:0]\n[@3,6:8='def',<1>,2:2]\n[@4,9:10='  ',<4>,2:5]\n[@5,11:11='\\n',<3>,2:7]\n[@6,12:11='<EOF>',<-1>,3:0]\ns0-'\n'->:s2=>3\ns0-'a'->:s1=>1\ns0-'d'->:s1=>1\n:s1=>1-'b'->:s1=>1\n:s1=>1-'c'->:s1=>1\n:s1=>1-'e'->:s1=>1\n:s1=>1-'f'->:s1=>1\n\n[flags]\nshowDFA\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/LexerInputPositionSensitivePredicates.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nWORD1 : ID1+ { <Text():writeln()> } ;\nWORD2 : ID2+ { <Text():writeln()> } ;\nfragment ID1 : { <Column()> \\< 2 }? [a-zA-Z];\nfragment ID2 : { <Column()> >= 2 }? [a-zA-Z];\nWS : (' '|'\\n') -> skip;\n\n[input]\na cde\nabcde\n\n[output]\na\ncde\nab\ncde\n[@0,0:0='a',<1>,1:0]\n[@1,2:4='cde',<2>,1:2]\n[@2,6:7='ab',<1>,2:0]\n[@3,8:10='cde',<2>,2:2]\n[@4,12:11='<EOF>',<-1>,3:0]\n\n[flags]\nshowDFA\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/PredicatedKeywords.txt",
    "content": "[type]\nLexer\n\n[grammar]\nlexer grammar L;\nENUM : [a-z]+ { <TextEquals(\"enum\")> }? { <writeln(\"\\\"enum!\\\"\")> } ;\nID   : [a-z]+ { <PlusText(\"ID \"):writeln()> } ;\nWS   : [ \\n] -> skip ;\n\n[input]\nenum enu a\n\n[output]\nenum!\nID enu\nID a\n[@0,0:3='enum',<1>,1:0]\n[@1,5:7='enu',<2>,1:5]\n[@2,9:9='a',<2>,1:9]\n[@3,10:9='<EOF>',<-1>,1:10]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/RuleSempredFunction.txt",
    "content": "[notes]\nTest for https://github.com/antlr/antlr4/issues/958\n\n[type]\nLexer\n\n[grammar]\nlexer grammar L;\nT : 'a' {<True()>}? ;\n\n[input]\naaa\n\n[output]\n[@0,0:0='a',<1>,1:0]\n[@1,1:1='a',<1>,1:1]\n[@2,2:2='a',<1>,1:2]\n[@3,3:2='<EOF>',<-1>,1:3]\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/ActionHidesPreds.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {<InitIntMember(\"i\",\"0\")>}\ns : a+ ;\na : {<SetMember(\"i\",\"1\")>} ID {<MemberEquals(\"i\",\"1\")>}? {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<SetMember(\"i\",\"2\")>} ID {<MemberEquals(\"i\",\"2\")>}? {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx x y\n\n[output]\nalt 1\nalt 1\nalt 1\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/ActionsHidePredsInGlobalFOLLOW.txt",
    "content": "[notes]\nRegular non-forced actions can create side effects used by semantic\npredicates and so we cannot evaluate any semantic predicate\nencountered after having seen a regular action. This includes\nduring global follow operations.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {\n<Declare_pred()>\n}\ns : e {} {<True():Invoke_pred()>}? {<writeln(\"\\\"parse\\\"\")>} '!' ;\nt : e {} {<False():Invoke_pred()>}? ID ;\ne : ID | ; // non-LL(1) so we use ATN\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na!\n\n[output]\neval=true\nparse\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/AtomWithClosureInTranslatedLRRule.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#196\n\"element+ in expression grammar doesn't parse properly\"\nhttps://github.com/antlr/antlr4/issues/196\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nstart : e[0] EOF;\ne[int _p]\n    :   ( 'a' | 'b'+ ) ( {3 >= $_p}? '+' e[4] )*\n    ;\n\n[start]\nstart\n\n[input]\na+b+a\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/DepedentPredsInGlobalFOLLOW.txt",
    "content": "[notes]\nWe cannot collect predicates that are dependent on local context if\nwe are doing a global follow. They appear as if they were not there at all.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {\n<Declare_pred()>\n}\ns : a[99] ;\na[int i] : e {<ValEquals(\"$i\",\"99\"):Invoke_pred()>}? {<writeln(\"\\\"parse\\\"\")>} '!' ;\nb[int i] : e {<ValEquals(\"$i\",\"99\"):Invoke_pred()>}? ID ;\ne : ID | ; // non-LL(1) so we use ATN\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na!\n\n[output]\neval=true\nparse\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/DependentPredNotInOuterCtxShouldBeIgnored.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : b[2] ';' |  b[2] '.' ; // decision in s drills down to ctx-dependent pred in a;\nb[<IntArg(\"i\")>] : a[<VarRef(\"i\")>] ;\na[<IntArg(\"i\")>]\n  : {<ValEquals(\"$i\",\"1\")>}? ID {<writeln(\"\\\"alt 1\\\"\")>}\n    | {<ValEquals(\"$i\",\"2\")>}? ID {<writeln(\"\\\"alt 2\\\"\")>}\n    ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na;\n\n[output]\n\"\"\"alt 2\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/DisabledAlternative.txt",
    "content": "[notes]\nThis is a regression test for antlr/antlr4#218 \"ANTLR4 EOF Related Bug\".\nhttps://github.com/antlr/antlr4/issues/218\n\n[type]\nParser\n\n[grammar]\ngrammar T;\ncppCompilationUnit : content+ EOF;\ncontent: anything | {<False()>}? .;\nanything: ANY_CHAR;\nANY_CHAR: [_a-zA-Z0-9];\n\n[start]\ncppCompilationUnit\n\n[input]\nhello\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/IndependentPredNotPassedOuterCtxToAvoidCastException.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : b ';' |  b '.' ;\nb : a ;\na\n  : {<False()>}? ID {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<True()>}? ID {<writeln(\"\\\"alt 2\\\"\")>}\n ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na;\n\n[output]\n\"\"\"alt 2\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/NoTruePredsThrowsNoViableAlt.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a a;\na : {<False()>}? ID INT {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<False()>}? ID INT {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\ny 3 x 4\n\n[errors]\n\"\"\"line 1:0 no viable alternative at input 'y'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/Order.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a {} a; // do 2x: once in ATN, next in DFA;\n// action blocks lookahead from falling off of 'a'\n// and looking into 2nd 'a' ref. !ctx dependent pred\na : ID {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<True()>}?  ID {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx y\n\n[output]\nalt 1\nalt 1\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/PredFromAltTestedInLoopBack_1.txt",
    "content": "[notes]\nLoopback doesn't eval predicate at start of alt\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nfile_\n@after {<ToStringTree(\"$ctx\"):writeln()>}\n  : para para EOF ;\npara: paraContent NL NL ;\nparaContent : ('s'|'x'|{<LANotEquals(\"2\",{T<ParserToken(\"Parser\", \"NL\")>})>}? NL)+ ;\nNL : '\\n' ;\ns : 's' ;\nX : 'x' ;\n\n[start]\nfile_\n\n[input]\n\"\"\"s\n\n\nx\n\"\"\"\n\n[output]\n\"\"\"(file_ (para (paraContent s) \\n \\n) (para (paraContent \\n x \\n)) <EOF>)\n\"\"\"\n\n[errors]\n\"\"\"line 5:0 mismatched input '<EOF>' expecting {'s', '\\n', 'x'}\n\"\"\"\n\n[skip]\nCpp\nCSharp\nDart\nGo\nJavaScript\nTypeScript\nPHP\nPython3\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/PredFromAltTestedInLoopBack_2.txt",
    "content": "[notes]\nLoopback doesn't eval predicate at start of alt\n\n[type]\nParser\n\n[grammar]\ngrammar T;\nfile_\n@after {<ToStringTree(\"$ctx\"):writeln()>}\n  : para para EOF ;\npara: paraContent NL NL ;\nparaContent : ('s'|'x'|{<LANotEquals(\"2\",{T<ParserToken(\"Parser\", \"NL\")>})>}? NL)+ ;\nNL : '\\n' ;\ns : 's' ;\nX : 'x' ;\n\n[start]\nfile_\n\n[input]\n\"\"\"s\n\n\nx\n\n\"\"\"\n\n[output]\n\"\"\"(file_ (para (paraContent s) \\n \\n) (para (paraContent \\n x) \\n \\n) <EOF>)\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/PredTestedEvenWhenUnAmbig_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {<InitBooleanMember(\"enumKeyword\",True())>}\nprimary\n    :   ID {<AppendStr(\"\\\"ID \\\"\", \"$ID.text\"):writeln()>}\n    |   {<GetMember(\"enumKeyword\"):Not()>}? 'enum' {<writeln(\"\\\"enum\\\"\")>}\n    ;\nID : [a-z]+ ;\nWS : [ \\t\\n\\r]+ -> skip ;\n\n[start]\nprimary\n\n[input]\nabc\n\n[output]\n\"\"\"ID abc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/PredTestedEvenWhenUnAmbig_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {<InitBooleanMember(\"enumKeyword\",True())>}\nprimary\n    :   ID {<AppendStr(\"\\\"ID \\\"\", \"$ID.text\"):writeln()>}\n    |   {<GetMember(\"enumKeyword\"):Not()>}? 'enum' {<writeln(\"\\\"enum\\\"\")>}\n    ;\nID : [a-z]+ ;\nWS : [ \\t\\n\\r]+ -> skip ;\n\n[start]\nprimary\n\n[input]\nenum\n\n[errors]\n\"\"\"line 1:0 no viable alternative at input 'enum'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/PredicateDependentOnArg.txt",
    "content": "[notes]\nIn this case, we're passing a parameter into a rule that uses that\ninformation to predict the alternatives. This is the special case\nwhere we know exactly which context we are in. The context stack\nis empty and we have not dipped into the outer context to make a decision.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {<InitIntMember(\"i\",\"0\")>}\ns : a[2] a[1];\na[int i]\n  : {<ValEquals(\"$i\",\"1\")>}? ID {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<ValEquals(\"$i\",\"2\")>}? ID {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na b\n\n[output]\nalt 2\nalt 1\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/PredicateDependentOnArg2.txt",
    "content": "[notes]\nIn this case, we have to ensure that the predicates are not tested\nduring the closure after recognizing the 1st ID. The closure will\nfall off the end of 'a' 1st time and reach into the a[1] rule\ninvocation. It should not execute predicates because it does not know\nwhat the parameter is. The context stack will not be empty and so\nthey should be ignored. It will not affect recognition, however. We\nare really making sure the ATN simulation doesn't crash with context\nobject issues when it encounters preds during FOLLOW.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {<InitIntMember(\"i\",\"0\")>}\ns : a[2] a[1];\na[int i]\n  : {<ValEquals(\"$i\",\"1\")>}? ID\n  | {<ValEquals(\"$i\",\"2\")>}? ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na b\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/PredsInGlobalFOLLOW.txt",
    "content": "[notes]\nDuring a global follow operation, we still collect semantic\npredicates as long as they are not dependent on local context\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {\n<Declare_pred()>\n}\ns : e {<True():Invoke_pred()>}? {<writeln(\"\\\"parse\\\"\")>} '!' ;\nt : e {<False():Invoke_pred()>}? ID ;\ne : ID | ; // non-LL(1) so we use ATN\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\na!\n\n[output]\neval=true\nparse\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/RewindBeforePredEval.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a a;\na : {<LTEquals(\"1\", \"\\\"x\\\"\")>}? ID INT {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<LTEquals(\"1\", \"\\\"y\\\"\")>}? ID INT {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\ny 3 x 4\n\n[output]\nalt 2\nalt 1\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/Simple.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a a a; // do 3x: once in ATN, next in DFA then INT in ATN\na : {<False()>}? ID {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<True()>}?  ID {<writeln(\"\\\"alt 2\\\"\")>}\n  | INT{<writeln(\"\\\"alt 3\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx y 3\n\n[output]\nalt 2\nalt 2\nalt 3\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/SimpleValidate.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a ;\na : {<False()>}? ID  {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<True()>}?  INT {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx\n\n[errors]\n\"\"\"line 1:0 no viable alternative at input 'x'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/SimpleValidate2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a a a;\na : {<False()>}? ID  {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<True()>}?  INT {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n3 4 x\n\n[output]\nalt 2\nalt 2\n\n[errors]\n\"\"\"line 1:4 no viable alternative at input 'x'\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/ToLeft.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\n   s : a+ ;\na : {<False()>}? ID {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<True()>}?  ID {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx x y\n\n[output]\nalt 2\nalt 2\nalt 2\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/ToLeftWithVaryingPredicate.txt",
    "content": "[notes]\nIn this case, we use predicates that depend on global information\nlike we would do for a symbol table. We simply execute\nthe predicates assuming that all necessary information is available.\nThe i++ action is done outside of the prediction and so it is executed.\n\n[type]\nParser\n\n[grammar]\ngrammar T;\n@parser::members {<InitIntMember(\"i\",\"0\")>}\ns : ({<AddMember(\"i\",\"1\")>\n<write(\"\\\"i=\\\"\")>\n<writeln(GetMember(\"i\"))>} a)+ ;\na : {<ModMemberEquals(\"i\",\"2\",\"0\")>}? ID {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<ModMemberNotEquals(\"i\",\"2\",\"0\")>}? ID {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx x y\n\n[output]\ni=1\nalt 2\ni=2\nalt 1\ni=3\nalt 2\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/TwoUnpredicatedAlts.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : {<LL_EXACT_AMBIG_DETECTION()>} a ';' a; // do 2x: once in ATN, next in DFA\na : ID {<writeln(\"\\\"alt 1\\\"\")>}\n  | ID {<writeln(\"\\\"alt 2\\\"\")>}\n  | {<False()>}? ID {<writeln(\"\\\"alt 3\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx; y\n\n[output]\nalt 1\nalt 1\n\n[errors]\nline 1:0 reportAttemptingFullContext d=0 (a), input='x'\nline 1:0 reportAmbiguity d=0 (a): ambigAlts={1, 2}, input='x'\nline 1:3 reportAttemptingFullContext d=0 (a), input='y'\nline 1:3 reportAmbiguity d=0 (a): ambigAlts={1, 2}, input='y'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/TwoUnpredicatedAltsAndOneOrthogonalAlt.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : {<LL_EXACT_AMBIG_DETECTION()>} a ';' a ';' a;\na : INT {<writeln(\"\\\"alt 1\\\"\")>}\n  | ID {<writeln(\"\\\"alt 2\\\"\")>} // must pick this one for ID since pred is false\n  | ID {<writeln(\"\\\"alt 3\\\"\")>}\n  | {<False()>}? ID {<writeln(\"\\\"alt 4\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\n34; x; y\n\n[output]\nalt 1\nalt 2\nalt 2\n\n[errors]\nline 1:4 reportAttemptingFullContext d=0 (a), input='x'\nline 1:4 reportAmbiguity d=0 (a): ambigAlts={2, 3}, input='x'\nline 1:7 reportAttemptingFullContext d=0 (a), input='y'\nline 1:7 reportAmbiguity d=0 (a): ambigAlts={2, 3}, input='y'\n\n[flags]\nshowDiagnosticErrors\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/UnpredicatedPathsInAlt.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a {<writeln(\"\\\"alt 1\\\"\")>}\n  | b {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\na : {<False()>}? ID INT\n  | ID INT\n  ;\nb : ID ID\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx 4\n\n[output]\n\"\"\"alt 1\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/ValidateInDFA.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\ns : a ';' a;\n// ';' helps us to resynchronize without consuming\n// 2nd 'a' reference. We our testing that the DFA also\n// throws an exception if the validating predicate fails\na : {<False()>}? ID  {<writeln(\"\\\"alt 1\\\"\")>}\n  | {<True()>}?  INT {<writeln(\"\\\"alt 2\\\"\")>}\n  ;\nID : 'a'..'z'+ ;\nINT : '0'..'9'+;\nWS : (' '|'\\n') -> skip ;\n\n[start]\ns\n\n[input]\nx ; y\n\n[errors]\nline 1:0 no viable alternative at input 'x'\nline 1:4 no viable alternative at input 'y'\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/CharSetLiteral.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : (A {<writeln(\"$A.text\")>})+ ;\nA : [AaBb] ;\nWS : (' '|'\\n')+ -> skip ;\n\n[start]\na\n\n[input]\nA a B b\n\n[output]\nA\na\nB\nb\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/ComplementSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\nparse : ~NEW_LINE;\nNEW_LINE: '\\\\r'? '\\\\n';\n\n[start]\nparse\n\n[input]\na\n\n[errors]\nline 1:0 token recognition error at: 'a'\nline 1:1 missing {} at '<EOF>'\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/LexerOptionalSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<InputText():writeln()>} ;\nA : ('a'|'b')? 'c' ;\n\n[start]\na\n\n[input]\nac\n\n[output]\n\"\"\"ac\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/LexerPlusSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<InputText():writeln()>} ;\nA : ('a'|'b')+ 'c' ;\n\n[start]\na\n\n[input]\nabaac\n\n[output]\n\"\"\"abaac\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/LexerStarSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<InputText():writeln()>} ;\nA : ('a'|'b')* 'c' ;\n\n[start]\na\n\n[input]\nabaac\n\n[output]\n\"\"\"abaac\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/NotChar.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<writeln(\"$A.text\")>} ;\nA : ~'b' ;\n\n[start]\na\n\n[input]\nx\n\n[output]\n\"\"\"x\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/NotCharSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<writeln(\"$A.text\")>} ;\nA : ~('b'|'c') ;\n\n[start]\na\n\n[input]\nx\n\n[output]\n\"\"\"x\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/NotCharSetWithRuleRef3.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<writeln(\"$A.text\")>} ;\nA : ('a'|B) ;  // this doesn't collapse to set but works\nfragment\nB : ~('a'|'c') ;\n\n[start]\na\n\n[input]\nx\n\n[output]\n\"\"\"x\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/OptionalLexerSingleElement.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<InputText():writeln()>} ;\nA : 'b'? 'c' ;\n\n[start]\na\n\n[input]\nbc\n\n[output]\n\"\"\"bc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/OptionalSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ('a'|'b')? 'c' {<InputText():writeln()>} ;\n\n[start]\na\n\n[input]\nac\n\n[output]\n\"\"\"ac\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/OptionalSingleElement.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A? 'c' {<InputText():writeln()>} ;\nA : 'b' ;\n\n[start]\na\n\n[input]\nbc\n\n[output]\n\"\"\"bc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/ParserNotSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : t=~('x'|'y') 'z' {<writeln(\"$t.text\")>} ;\n\n[start]\na\n\n[input]\nzz\n\n[output]\n\"\"\"z\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/ParserNotToken.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ~'x' 'z' {<InputText():writeln()>} ;\n\n[start]\na\n\n[input]\nzz\n\n[output]\n\"\"\"zz\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/ParserNotTokenWithLabel.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : t=~'x' 'z' {<writeln(\"$t.text\")>} ;\n\n[start]\na\n\n[input]\nzz\n\n[output]\n\"\"\"z\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/ParserSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : t=('x'|'y') {<writeln(\"$t.text\")>} ;\n\n[start]\na\n\n[input]\nx\n\n[output]\n\"\"\"x\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/PlusLexerSingleElement.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<InputText():writeln()>} ;\nA : 'b'+ 'c' ;\n\n[start]\na\n\n[input]\nbbbbc\n\n[output]\n\"\"\"bbbbc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/PlusSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ('a'|'b')+ 'c' {<InputText():writeln()>} ;\n\n[start]\na\n\n[input]\nabaac\n\n[output]\n\"\"\"abaac\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/RuleAsSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na @after {<InputText():writeln()>} : 'a' | 'b' |'c' ;\n\n[start]\na\n\n[input]\nb\n\n[output]\n\"\"\"b\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/SeqDoesNotBecomeSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : C {<InputText():writeln()>} ;\nfragment A : '1' | '2';\nfragment B : '3' '4';\nC : A | B;\n\n[start]\na\n\n[input]\n34\n\n[output]\n\"\"\"34\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/StarLexerSingleElement_1.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<InputText():writeln()>} ;\nA : 'b'* 'c' ;\n\n[start]\na\n\n[input]\nbbbbc\n\n[output]\n\"\"\"bbbbc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/StarLexerSingleElement_2.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : A {<InputText():writeln()>} ;\nA : 'b'* 'c' ;\n\n[start]\na\n\n[input]\nc\n\n[output]\n\"\"\"c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/StarSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : ('a'|'b')* 'c' {<InputText():writeln()>} ;\n\n[start]\na\n\n[input]\nabaac\n\n[output]\n\"\"\"abaac\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeEscapedBMPRangeSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS* 'd' {<InputText():writeln()>} ;\n// Note the double-backslash to avoid Java passing\n// unescaped values as part of the grammar.\nLETTERS : ('a'|'\\\\u00E0'..'\\\\u00E5');\n\n[start]\na\n\n[input]\naáäáâåd\n\n[output]\n\"\"\"aáäáâåd\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeEscapedBMPSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS {<InputText():writeln()>} ;\n// Note the double-backslash to avoid Java passing\n// unescaped values as part of the grammar.\nLETTERS : ('a'|'\\\\u00E4'|'\\\\u4E9C'|'\\\\u3042')* 'c';\n\n[start]\na\n\n[input]\naäあ亜c\n\n[output]\n\"\"\"aäあ亜c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeEscapedSMPRangeSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS* 'd' {<InputText():writeln()>} ;\n// Note the double-backslash to avoid Java passing\n// unescaped values as part of the grammar.\nLETTERS : ('a'|'\\\\u{1F600}'..'\\\\u{1F943}');\n\n[start]\na\n\n[input]\na😉🥂🜀d\n\n[output]\n\"\"\"a😉🥂🜀d\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeEscapedSMPRangeSetMismatch.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS* 'd' {<InputText():writeln()>} ;\n// Note the double-backslash to avoid Java passing\n// unescaped values as part of the grammar.\nLETTERS : ('a'|'\\\\u{1F600}'..'\\\\u{1F943}');\n\n[start]\na\n\n[input]\na🗿🥄d\n\n[output]\n\"\"\"ad\n\"\"\"\n\n[errors]\nline 1:1 token recognition error at: '🗿'\nline 1:2 token recognition error at: '🥄'\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeEscapedSMPSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS  {<InputText():writeln()>} ;\n// Note the double-backslash to avoid Java passing\n// unescaped values as part of the grammar.\nLETTERS : ('a'|'\\\\u{1D5BA}'|'\\\\u{1D5BE}'|'\\\\u{1D5C2}'|'\\\\u{1D5C8}'|'\\\\u{1D5CE}')* 'c';\n\n[start]\na\n\n[input]\na𝗂𝗎𝖺c\n\n[output]\n\"\"\"a𝗂𝗎𝖺c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeNegatedBMPSetIncludesSMPCodePoints.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS {<InputText():writeln()>} ;\nLETTERS : 'a' ~('b')+ 'c';\n\n[start]\na\n\n[input]\na😳😡😝🤓c\n\n[output]\n\"\"\"a😳😡😝🤓c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeNegatedSMPSetIncludesBMPCodePoints.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS {<InputText():writeln()>} ;\nLETTERS : 'a' ~('\\\\u{1F600}'..'\\\\u{1F943}')+ 'c';\n\n[start]\na\n\n[input]\nabc\n\n[output]\n\"\"\"abc\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeUnescapedBMPRangeSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS* 'd' {<InputText():writeln()>} ;\n// These are actually not escaped -- Java passes the\n// raw unescaped Unicode values to the grammar compiler.\nLETTERS : ('a'|'à'..'å');\n\n[start]\na\n\n[input]\naáäáâåd\n\n[output]\n\"\"\"aáäáâåd\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeUnescapedBMPSet.txt",
    "content": "[type]\nParser\n\n[grammar]\ngrammar T;\na : LETTERS {<InputText():writeln()>} ;\n// These are actually not escaped -- Java passes the\n// raw unescaped Unicode values to the grammar compiler.\nLETTERS : ('a'|'ä'|'亜'|'あ')* 'c';\n\n[start]\na\n\n[input]\naäあ亜c\n\n[output]\n\"\"\"aäあ亜c\n\"\"\"\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Antlr4.Test.csproj.stg",
    "content": "﻿\\<Project Sdk=\"Microsoft.NET.Sdk\">\n\n  \\<PropertyGroup>\n    \\<TargetFramework>net7.0\\</TargetFramework>\n    \\<NoWarn>$(NoWarn);CS3021\\</NoWarn>\n    \\<AssemblyName>Test\\</AssemblyName>\n    \\<OutputType>Exe\\</OutputType>\n    \\<OutDir>.\\</OutDir>\n    \\<PackageId>Antlr4.Test\\</PackageId>\n    \\<GenerateAssemblyTitleAttribute>false\\</GenerateAssemblyTitleAttribute>\n    \\<GenerateAssemblyDescriptionAttribute>false\\</GenerateAssemblyDescriptionAttribute>\n    \\<GenerateAssemblyConfigurationAttribute>false\\</GenerateAssemblyConfigurationAttribute>\n    \\<GenerateAssemblyCompanyAttribute>false\\</GenerateAssemblyCompanyAttribute>\n    \\<GenerateAssemblyProductAttribute>false\\</GenerateAssemblyProductAttribute>\n    \\<GenerateAssemblyCopyrightAttribute>false\\</GenerateAssemblyCopyrightAttribute>\n    \\<GenerateAssemblyVersionAttribute>false\\</GenerateAssemblyVersionAttribute>\n  \\</PropertyGroup>\n\n  \\<ItemGroup>\n    \\<Reference Include=\"Antlr4.Runtime\">\n      \\<HintPath><runtimeLibraryPath>\\</HintPath>\n    \\</Reference>\n  \\</ItemGroup>\n\n\\</Project>\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Package.swift.stg",
    "content": "// swift-tools-version: 5.6\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Test\",\n    targets: [\n        .executableTarget(name: \"Test\", path: \".\",\n             exclude:[ <excludedFiles: {f | \"<f>\"}; separator = \", \", wrap> ]),\n    ]\n)\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.cpp.stg",
    "content": "#include \\<iostream>\n\n#include \"antlr4-runtime.h\"\n#include \"<lexerName>.h\"\n<if(parserName)>\n#include \"<parserName>.h\"\n<endif>\n\nusing namespace antlr4;\n\n<if(parserName)>\nclass TreeShapeListener : public tree::ParseTreeListener {\npublic:\n  void visitTerminal(tree::TerminalNode *) override {}\n  void visitErrorNode(tree::ErrorNode *) override {}\n  void exitEveryRule(ParserRuleContext *) override {}\n  void enterEveryRule(ParserRuleContext *ctx) override {\n    for (auto child : ctx->children) {\n      tree::ParseTree *parent = child->parent;\n      ParserRuleContext *rule = dynamic_cast\\<ParserRuleContext *>(parent);\n      if (rule != ctx) {\n        throw \"Invalid parse tree shape detected.\";\n      }\n    }\n  }\n};\n<endif>\n\nint main(int argc, const char* argv[]) {\n  ANTLRFileStream input;\n  input.loadFromFile(argv[1]);\n  <lexerName> lexer(&input);\n  CommonTokenStream tokens(&lexer);\n<if(parserName)>\n  <parserName> parser(&tokens);\n  parser.getInterpreter\\<atn::ParserATNSimulator>()->setPredictionMode(antlr4::atn::PredictionMode::<predictionMode>);\n<if(!buildParseTree)>\n  parser.setBuildParseTree(false);\n<endif>\n<if(showDiagnosticErrors)>\n  DiagnosticErrorListener errorListener;\n  parser.addErrorListener(&errorListener);\n<endif>\n  tree::ParseTree *tree = parser.<parserStartRuleName>();\n  TreeShapeListener listener;\n  tree::ParseTreeWalker::DEFAULT.walk(&listener, tree);\n<else>\n  tokens.fill();\n  for (auto token : tokens.getTokens())\n    std::cout \\<\\< token->toString() \\<\\< std::endl;\n<if(showDFA)>\n  std::cout \\<\\< lexer.getInterpreter\\<atn::LexerATNSimulator>()->getDFA(Lexer::DEFAULT_MODE).toLexerString();\n<endif>\n<endif>\n  return 0;\n}\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.cs.stg",
    "content": "using System;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Tree;\nusing System.Text;\n\npublic class Test {\n\tpublic static void Main(string[] args) {\n\t\tConsole.OutputEncoding = Encoding.UTF8;\n\t\tConsole.InputEncoding = Encoding.UTF8;\n\t\tvar input = CharStreams.fromPath(args[0]);\n\t\tvar lex = new <lexerName>(input);\n\t\tvar tokens = new CommonTokenStream(lex);\n<if(parserName)>\n\t\tvar parser = new <parserName>(tokens);\n\t\tparser.Interpreter.PredictionMode = PredictionMode.<predictionMode>;\n<if(!buildParseTree)>\n\t\tparser.BuildParseTree = false;\n<endif>\n<if(showDiagnosticErrors)>\n\t\tparser.AddErrorListener(new DiagnosticErrorListener());\n<endif>\n<if(traceATN)>\n\t\tParserATNSimulator.trace_atn_sim = true;\n<endif>\n\t\tvar tree = parser.<parserStartRuleName>();\n\t\tParseTreeWalker.Default.Walk(new TreeShapeListener(), tree);\n<else>\n\t\ttokens.Fill();\n\t\tforeach (object t in tokens.GetTokens())\n\t\t\tConsole.Out.WriteLine(t);\n<if(showDFA)>\n\t\tConsole.Out.Write(lex.Interpreter.GetDFA(Lexer.DEFAULT_MODE).ToLexerString());\n<endif>\n<endif>\n\t}\n}\n\n<if(parserName)>\nclass TreeShapeListener : IParseTreeListener {\n\tpublic void VisitTerminal(ITerminalNode node) { }\n\tpublic void VisitErrorNode(IErrorNode node) { }\n\tpublic void ExitEveryRule(ParserRuleContext ctx) { }\n\n\tpublic void EnterEveryRule(ParserRuleContext ctx) {\n\t\tfor (int i = 0; i \\< ctx.ChildCount; i++) {\n\t\t\tIParseTree parent = ctx.GetChild(i).Parent;\n\t\t\tif (!(parent is IRuleNode) || ((IRuleNode)parent).RuleContext != ctx) {\n\t\t\t\tthrow new Exception(\"Invalid parse tree shape detected.\");\n\t\t\t}\n\t\t}\n\t}\n}\n<endif>\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.dart.stg",
    "content": "import 'dart:io';\nimport 'package:antlr4/antlr4.dart';\n\nimport '<lexerName>.dart';\n<if(parserName)>\nimport '<parserName>.dart';\n<endif>\n\nvoid main(List\\<String> args) async {\n  CharStream input = await InputStream.fromPath(args[0]);\n  final lex = <lexerName>(input);\n  final tokens = CommonTokenStream(lex);\n<if(parserName)>\n  final parser = <parserName>(tokens);\n<if(showDiagnosticErrors)>\n  parser.addErrorListener(new DiagnosticErrorListener());\n<endif>\n<if(profile)>\n  ProfilingATNSimulator profiler = ProfilingATNSimulator(parser);\n  parser.setInterpreter(profiler);\n<endif>\n  parser.interpreter!.predictionMode = PredictionMode.<predictionMode>;\n<if(!buildParseTree)>\n  parser.buildParseTree = false;\n<endif>\n  ParserRuleContext tree = parser.<parserStartRuleName>();\n<if(profile)>\n  print('[${profiler.getDecisionInfo().join(', ')}]');\n<endif>\n  ParseTreeWalker.DEFAULT.walk(TreeShapeListener(), tree);\n<else>\n  tokens.fill();\n  for (Object t in tokens.getTokens()!)\n    print(t);\n<if(showDFA)>\n  stdout.write(lex.interpreter!.getDFA(Lexer.DEFAULT_MODE).toLexerString());\n<endif>\n<endif>\n}\n\n<if(parserName)>\nclass TreeShapeListener implements ParseTreeListener {\n  @override void visitTerminal(TerminalNode node) {}\n\n  @override void visitErrorNode(ErrorNode node) {}\n\n  @override void exitEveryRule(ParserRuleContext ctx) {}\n\n  @override\n  void enterEveryRule(ParserRuleContext ctx) {\n    for (var i = 0; i \\< ctx.childCount; i++) {\n      final parent = ctx.getChild(i)?.parent;\n      if (!(parent is RuleNode) || (parent as RuleNode).ruleContext != ctx) {\n        throw StateError('Invalid parse tree shape detected.');\n      }\n    }\n  }\n}\n<endif>\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.go.stg",
    "content": "package main\nimport (\n\t\"fmt\"\n    \"github.com/antlr4-go/antlr/v4\"\n    \"os\"\n    \"test/parser\"\n)\n\n<if(parserName)>\n\nimport \"reflect\"\n\ntype TreeShapeListener struct {\n\t*parser.Base<grammarName>Listener\n}\n\nfunc NewTreeShapeListener() *TreeShapeListener {\n\treturn new(TreeShapeListener)\n}\n\nfunc (this *TreeShapeListener) EnterEveryRule(ctx antlr.ParserRuleContext) {\n\tfor i := 0; i\\<ctx.GetChildCount(); i++ {\n\t\tchild := ctx.GetChild(i)\n\t\tparentR, ok := child.GetParent().(antlr.ParserRuleContext)\n\n\t\t// Have to use reflect here - we need to compare the underlying pointers, but we\n\t\t// do not know the types of the underlying structs, just that they will be the same\n\t\t// type.\n\t\tparPointer := reflect.ValueOf(parentR).Elem().Addr().Pointer()\n\t\tctxPointer := reflect.ValueOf(ctx).Elem().Addr().Pointer()\n\t\tif !ok || parPointer != ctxPointer {\n\t\t\tpanic(\"Invalid parse tree shape detected.\")\n\t\t}\n\t}\n}\n<endif>\n\nfunc main() {\n<if(traceATN)>\n    antlr.ParserATNSimulatorTraceATNSim = true\n<endif>\n\tinput, err := antlr.NewFileStream(os.Args[1])\n\t\tif err != nil {\n\t\tfmt.Printf(\"Failed to find file: %v\", err)\n\t\treturn\n\t}\n\tlexer := parser.New<lexerName>(input)\n\tstream := antlr.NewCommonTokenStream(lexer,0)\n<if(parserName)>\n\tp := parser.New<parserName>(stream)\n\tp.Interpreter.SetPredictionMode(antlr.PredictionMode<predictionMode>)\n<if(!buildParseTree)>\n\tp.BuildParseTrees = false\n<endif>\n<if(showDiagnosticErrors)>\n\tp.AddErrorListener(antlr.NewDiagnosticErrorListener(true))\n<endif>\n\ttree := p.<parserStartRuleName>()\n\tantlr.ParseTreeWalkerDefault.Walk(NewTreeShapeListener(), tree)\n<else>\n\tstream.Fill()\n\tfor _, t := range stream.GetAllTokens() {\n\t\tfmt.Println(t)\n\t}\n<if(showDFA)>\n\tfmt.Print(lexer.GetInterpreter().DecisionToDFA()[antlr.LexerDefaultMode].ToLexerString())\n<endif>\n<endif>\n}\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.js.stg",
    "content": "import antlr4 from 'file://<runtimePath>/src/antlr4/index.node.js'\nimport <lexerName> from './<lexerName>.js';\n<if(parserName)>\nimport <parserName> from './<parserName>.js';\n<if(useListener)>\nimport <grammarName>Listener from './<grammarName>Listener.js';\n<endif>\n<if(useVisitor)>\nimport <grammarName>Visitor from './<grammarName>Visitor.js';\n<endif>\n\nclass TreeShapeListener extends antlr4.tree.ParseTreeListener {\n    enterEveryRule(ctx) {\n        for (let i = 0; i \\< ctx.getChildCount; i++) {\n            const child = ctx.getChild(i)\n            const parent = child.parentCtx\n            if (parent.getRuleContext() !== ctx || !(parent instanceof antlr4.tree.RuleNode)) {\n                throw `Invalid parse tree shape detected.`\n            }\n        }\n    }\n}\n<endif>\n\nfunction main(argv) {\n    var input = new antlr4.FileStream(argv[2], \"utf-8\", true);\n    var lexer = new <lexerName>(input);\n    var stream = new antlr4.CommonTokenStream(lexer);\n<if(parserName)>\n    var parser = new <parserName>(stream);\n<if(showDiagnosticErrors)>\n    parser.addErrorListener(new antlr4.error.DiagnosticErrorListener());\n<endif>\n    const printer = function() {\n        this.println = function(s) { console.log(s); }\n        this.print = function(s) { process.stdout.write(s); }\n        return this;\n    };\n    parser.printer = new printer();\n    parser._interp.predictionMode = antlr4.atn.PredictionMode.<predictionMode>;\n<if(!buildParseTree)>\n    parser.buildParseTrees = false;\n<endif>\n<if(traceATN)>\n    parser._interp.trace_atn_sim = true;\n    antlr4.context.PredictionContext.trace_atn_sim = true;\n<endif>\n    var tree = parser.<parserStartRuleName>();\n    antlr4.tree.ParseTreeWalker.DEFAULT.walk(new TreeShapeListener(), tree);\n<else>\n    stream.fill();\n    for(var i=0; i\\<stream.tokens.length; i++) {\n        console.log(stream.tokens[i].toString());\n    }\n<if(showDFA)>\n    process.stdout.write(lexer._interp.decisionToDFA[antlr4.Lexer.DEFAULT_MODE].toLexerString());\n<endif>\n<endif>\n}\n\nmain(process.argv);\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.php.stg",
    "content": "\\<?php\n\ndeclare(strict_types=1);\n\nuse Antlr\\Antlr4\\Runtime\\Atn\\ParserATNSimulator;\nuse Antlr\\Antlr4\\Runtime\\CommonTokenStream;\nuse Antlr\\Antlr4\\Runtime\\Error\\Listeners\\ConsoleErrorListener;\nuse Antlr\\Antlr4\\Runtime\\Error\\Listeners\\DiagnosticErrorListener;\nuse Antlr\\Antlr4\\Runtime\\InputStream;\nuse Antlr\\Antlr4\\Runtime\\Lexer;\nuse Antlr\\Antlr4\\Runtime\\ParserRuleContext;\nuse Antlr\\Antlr4\\Runtime\\Tree\\ErrorNode;\nuse Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeListener;\nuse Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeWalker;\nuse Antlr\\Antlr4\\Runtime\\Tree\\RuleNode;\nuse Antlr\\Antlr4\\Runtime\\Tree\\TerminalNode;\nuse Antlr\\Antlr4\\Runtime\\Atn\\PredictionMode;\n\n$runtime = \\getenv('RUNTIME');\n\nrequire_once $runtime . '/vendor/autoload.php';\n\n\\spl_autoload_register(function (string $class) use ($runtime) : void {\n    $file = \\str_replace('\\\\\\', \\DIRECTORY_SEPARATOR, $class) . '.php';\n\n    if (\\file_exists($file)) {\n        require_once $file;\n    }\n});\n\n<if(parserName)>\nfinal class TreeShapeListener implements ParseTreeListener {\n    public function visitTerminal(TerminalNode $node) : void {}\n    public function visitErrorNode(ErrorNode $node) : void {}\n    public function exitEveryRule(ParserRuleContext $ctx) : void {}\n\n    public function enterEveryRule(ParserRuleContext $ctx) : void {\n        for ($i = 0, $count = $ctx->getChildCount(); $i \\< $count; $i++) {\n            $parent = $ctx->getChild($i)->getParent();\n\n            if (!($parent instanceof RuleNode) || $parent->getRuleContext() !== $ctx) {\n                throw new RuntimeException('Invalid parse tree shape detected.');\n            }\n        }\n    }\n}\n<endif>\n\n$input = InputStream::fromPath($argv[1]);\n$lexer = new <lexerName>($input);\n$lexer->addErrorListener(new ConsoleErrorListener());\n$tokens = new CommonTokenStream($lexer);\n<if(parserName)>\n$parser = new <parserName>($tokens);\n$parser->getInterpreter()->setPredictionMode(PredictionMode::<predictionMode>);\n<if(!buildParseTree)>\n$parser->setBuildParseTree(false);\n<endif>\n<if(showDiagnosticErrors)>\n$parser->addErrorListener(new DiagnosticErrorListener());\n<endif>\n$parser->addErrorListener(new ConsoleErrorListener());\n<if(traceATN)>\nParserATNSimulator::$traceAtnSimulation = true;\n<endif>\n$tree = $parser-><parserStartRuleName>();\n\nParseTreeWalker::default()->walk(new TreeShapeListener(), $tree);\n<else>\n$tokens->fill();\n\nforeach ($tokens->getAllTokens() as $token) {\n    echo $token . \\PHP_EOL;\n}\n<if(showDFA)>\necho $lexer->getInterpreter()->getDFA(Lexer::DEFAULT_MODE)->toLexerString();\n<endif>\n<endif>\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.py.stg",
    "content": "<if(!python3)>from __future__ import print_function<endif>\nimport sys\nimport codecs\nfrom antlr4 import *\nfrom <lexerName> import <lexerName>\n<if(parserName)>\nfrom <parserName> import <parserName>\nfrom <grammarName>Listener import <grammarName>Listener\nfrom <grammarName>Visitor import <grammarName>Visitor\n\nclass TreeShapeListener(ParseTreeListener):\n\n    def visitTerminal(self, node<if(python3)>:TerminalNode<endif>):\n        pass\n\n    def visitErrorNode(self, node<if(python3)>:ErrorNode<endif>):\n        pass\n\n    def exitEveryRule(self, ctx<if(python3)>:ParserRuleContext<endif>):\n        pass\n\n    def enterEveryRule(self, ctx<if(python3)>:ParserRuleContext<endif>):\n        for child in ctx.getChildren():\n            parent = child.parentCtx\n            if not isinstance(parent, RuleNode) or parent.getRuleContext() != ctx:\n                raise IllegalStateException(\"Invalid parse tree shape detected.\")\n<endif>\n\ndef main(argv):\n<if(traceATN)>\n    ParserATNSimulator.trace_atn_sim = True\n    PredictionContext._trace_atn_sim = True\n<endif>\n    input = FileStream(argv[1], encoding='utf-8', errors='replace')\n    lexer = <lexerName>(input)\n    stream = CommonTokenStream(lexer)\n<if(parserName)>\n    parser = <parserName>(stream)\n    parser._interp.predictionMode = PredictionMode.<predictionMode>\n<if(!buildParseTree)>\n    parser.buildParseTrees = False\n<endif>\n<if(showDiagnosticErrors)>\n    parser.addErrorListener(DiagnosticErrorListener())\n<endif>\n    tree = parser.<parserStartRuleName>()\n    ParseTreeWalker.DEFAULT.walk(TreeShapeListener(), tree)\n<else>\n    stream.fill()\n    [ print(<if(python3)>t<else>unicode(t)<endif>) for t in stream.tokens ]\n<if(showDFA)>\n    print(lexer._interp.decisionToDFA[Lexer.DEFAULT_MODE].toLexerString(), end='')\n<endif>\n<endif>\n\nif __name__ == '__main__':\n    main(sys.argv)\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.ts.stg",
    "content": "import {\n\tFileStream,\n\tCommonTokenStream,\n\tDiagnosticErrorListener,\n\tLexer,\n\tParseTreeListener,\n\tParseTreeWalker,\n\tRuleContext,\n\tParserRuleContext,\n\tRuleNode,\n\tPredictionMode\n} from 'antlr4';\nimport <lexerName> from './<lexerName>.js';\n<if(parserName)>\nimport <parserName> from './<parserName>.js';\n<if(useListener)>\nimport <grammarName>Listener from './<grammarName>Listener.js';\n<endif>\n<if(useVisitor)>\nimport <grammarName>Visitor from './<grammarName>Visitor.js';\n<endif>\n\nclass TreeShapeListener extends ParseTreeListener {\n    enterEveryRule(ctx: ParserRuleContext) {\n        for (let i = 0; i \\< ctx.getChildCount(); i++) {\n            const child = ctx.getChild(i) as RuleContext;\n            const parent = child.parentCtx;\n            if (parent!.ruleContext !== ctx || !(parent instanceof RuleNode)) {\n                throw `Invalid parse tree shape detected.`;\n            }\n        }\n    }\n}\n<endif>\n\nfunction main(argv: string[]): void {\n    const input = new FileStream(argv[2], \"utf-8\", true);\n    const lexer = new <lexerName>(input);\n    const stream = new CommonTokenStream(lexer);\n<if(parserName)>\n    const parser = new <parserName>(stream);\n<if(showDiagnosticErrors)>\n    parser.addErrorListener(new DiagnosticErrorListener());\n<endif>\n    parser.printer = {\n        println : function(s: string) { console.log(s); },\n        print : function(s: string) { process.stdout.write(s); }\n    };\n    parser._interp.predictionMode = PredictionMode.<predictionMode>;\n<if(!buildParseTree)>\n    parser.buildParseTrees = false;\n<endif>\n    const tree = parser.<parserStartRuleName>();\n    ParseTreeWalker.DEFAULT.walk(new TreeShapeListener(), tree);\n<else>\n    stream.fill();\n    for(let i=0; i\\<stream.tokens.length; i++) {\n        console.log(stream.tokens[i].toString());\n    }\n<if(showDFA)>\n    process.stdout.write(lexer._interp.decisionToDFA[Lexer.DEFAULT_MODE].toLexerString());\n<endif>\n<endif>\n}\n\nmain(process.argv);\n\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/Test.vcxproj.stg",
    "content": "\\<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\\<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  \\<ItemGroup Label=\"ProjectConfigurations\">\n    \\<ProjectConfiguration Include=\"Release|x64\">\n      \\<Configuration>Release\\</Configuration>\n      \\<Platform>x64\\</Platform>\n    \\</ProjectConfiguration>\n  \\</ItemGroup>\n  \\<PropertyGroup Label=\"Globals\">\n    \\<VCProjectVersion>16.0\\</VCProjectVersion>\n    \\<Keyword>Win32Proj\\</Keyword>\n    \\<ProjectGuid>{f3708606-c8fb-45ca-ae36-b729f91e972b}\\</ProjectGuid>\n    \\<RootNamespace>Test\\</RootNamespace>\n    \\<WindowsTargetPlatformVersion>10.0\\</WindowsTargetPlatformVersion>\n  \\</PropertyGroup>\n  \\<Import Project=\"$(VCTargetsPath)\\\\Microsoft.Cpp.Default.props\" />\n\n  \\<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\n    \\<ConfigurationType>Application\\</ConfigurationType>\n    \\<UseDebugLibraries>false\\</UseDebugLibraries>\n    \\<PlatformToolset>v143\\</PlatformToolset>\n    \\<WholeProgramOptimization>false\\</WholeProgramOptimization> \\<!-- compile time is more important than run time for tests -->\n    \\<CharacterSet>Unicode\\</CharacterSet>\n  \\</PropertyGroup>\n\n  \\<Import Project=\"$(VCTargetsPath)\\\\Microsoft.Cpp.props\" />\n  \\<ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    \\<Import Project=\"$(UserRootDir)\\\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  \\</ImportGroup>\n\n  \\<PropertyGroup>\n    \\<LinkIncremental>false\\</LinkIncremental>\n    \\<IncludePath><runtimeSourcePath>;$(IncludePath)\\</IncludePath>\n    \\<ReferencePath>$(VC_ReferencesPath_x64);<runtimeBinaryPath>\\</ReferencePath>\n    \\<OutDir>$(SolutionDir)\\</OutDir>\n  \\</PropertyGroup>\n\n  \\<ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    \\<ClCompile>\n      \\<WarningLevel>TurnOffAllWarnings\\</WarningLevel>\n      \\<FunctionLevelLinking>false\\</FunctionLevelLinking>\n      \\<IntrinsicFunctions>false\\</IntrinsicFunctions>\n      \\<SDLCheck>false\\</SDLCheck>\n      \\<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)\\</PreprocessorDefinitions>\n      \\<ConformanceMode>true\\</ConformanceMode>\n      \\<LanguageStandard>stdcpp17\\</LanguageStandard>\n      \\<DebugInformationFormat>None\\</DebugInformationFormat>\n    \\</ClCompile>\n    \\<Link>\n      \\<SubSystem>Console\\</SubSystem>\n      \\<EnableCOMDATFolding>true\\</EnableCOMDATFolding>\n      \\<OptimizeReferences>false\\</OptimizeReferences>\n      \\<GenerateDebugInformation>false\\</GenerateDebugInformation>\n      \\<AdditionalDependencies>\"<runtimeBinaryPath>\\\\antlr4-runtime.lib\";%(AdditionalDependencies)\\</AdditionalDependencies>\n    \\</Link>\n  \\</ItemDefinitionGroup>\n\n  \\<ItemGroup>\n    \\<ClInclude Include=\"<lexerName>.h\" />\n    \\<ClCompile Include=\"<lexerName>.cpp\" />\n\n<if(parserName)>\n    \\<ClInclude Include=\"<parserName>.h\" />\n    \\<ClCompile Include=\"<parserName>.cpp\" />\n<endif>\n\n<if(useListener)>\n    \\<ClInclude Include=\"<grammarName>BaseListener.h\" />\n    \\<ClCompile Include=\"<grammarName>BaseListener.cpp\" />\n    \\<ClInclude Include=\"<grammarName>Listener.h\" />\n    \\<ClCompile Include=\"<grammarName>Listener.cpp\" />\n<endif>\n\n<if(useVisitor)>\n    \\<ClInclude Include=\"<grammarName>BaseVisitor.h\" />\n    \\<ClCompile Include=\"<grammarName>BaseVisitor.cpp\" />\n    \\<ClInclude Include=\"<grammarName>Visitor.h\" />\n    \\<ClCompile Include=\"<grammarName>Visitor.cpp\" />\n<endif>\n\n    \\<ClCompile Include=\"Test.cpp\" />\n  \\</ItemGroup>\n\n  \\<Import Project=\"$(VCTargetsPath)\\\\Microsoft.Cpp.targets\" />\n\\</Project>\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/main.swift.stg",
    "content": "import Antlr4\nimport Foundation\n\n<if(parserName)>\nclass TreeShapeListener: ParseTreeListener{\n    func visitTerminal(_ node: TerminalNode){ }\n    func visitErrorNode(_ node: ErrorNode){ }\n    func enterEveryRule(_ ctx: ParserRuleContext) throws { }\n    func exitEveryRule(_ ctx: ParserRuleContext) throws {\n        for i in 0..\\<ctx.getChildCount() {\n            let parent = ctx.getChild(i)?.getParent()\n            if (!(parent is RuleNode) || (parent as! RuleNode ).getRuleContext() !== ctx) {\n                throw ANTLRError.illegalState(msg: \"Invalid parse tree shape detected.\")\n            }\n        }\n    }\n}\n<endif>\n\nlet args = CommandLine.arguments\nlet input = try ANTLRFileStream(args[1])\nlet lex = <lexerName>(input)\nlet tokens = CommonTokenStream(lex)\n<if(parserName)>\nlet parser = try <parserName>(tokens)\n<if(showDiagnosticErrors)>\nparser.addErrorListener(DiagnosticErrorListener())\n<endif>\n<if(profile)>\nlet profiler = ProfilingATNSimulator(parser)\nparser.setInterpreter(profiler)\n<endif>\nparser.getInterpreter().setPredictionMode(PredictionMode.<predictionMode>)\n<if(!buildParseTree)>\nparser.setBuildParseTree(false)\n<endif>\nlet tree = try parser.<parserStartRuleName>()\n<if(profile)>\nprint(profiler.getDecisionInfo().description)\n<endif>\ntry ParseTreeWalker.DEFAULT.walk(TreeShapeListener(), tree)\n<else>\ntry tokens.fill()\nfor t in tokens.getTokens() {\n    print(t)\n}\n<if(showDFA)>\nprint(lex.getInterpreter().getDFA(Lexer.DEFAULT_MODE).toLexerString(), terminator: \"\")\n<endif>\n<endif>\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/package_js.json",
    "content": "{\"type\": \"module\"}"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/package_ts.json",
    "content": "{\n  \"type\": \"module\",\n   \"devDependencies\": {\n    \"@types/node\": \"^18.0.5\"\n   },\n  \"dependencies\": {\n    \"antlr4\": \"^4.13.2\"\n  }\n}\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/pubspec.yaml.stg",
    "content": "name: \"test\"\ndependencies:\n  antlr4:\n    path: <runtimePath>\nenvironment:\n  sdk: \">=2.12.0 \\<3.0.0\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/helpers/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"ES2020\",\n    \"moduleResolution\": \"node\",\n    \"target\": \"ES6\",\n    \"noImplicitAny\": true,\n  },\n  \"ts-node\": {\n    \"esm\": true\n  }\n}\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/CSharp.test.stg",
    "content": "writeln(s) ::= <<Output.WriteLine(<s>);>>\nwrite(s) ::= <<Output.Write(<s>);>>\nwriteList(s) ::= <<Output.WriteLine(<s; separator=\"+\">);>>\n\nFalse() ::= \"false\"\n\nTrue() ::= \"true\"\n\nNot(v) ::= \"!<v>\"\n\nAssert(s) ::= <<Debug.Assert(<s>);>>\n\nCast(t,v) ::= \"((<t>)<v>)\"\n\nAppend(a,b) ::= \"<a> + <b>\"\n\nAppendStr(a,b) ::= <%<Append(a,b)>%>\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= \"System.Collections.IList __ttt__ = (System.Collections.IList)<v>;\" // just use static type system\n\nAssignLocal(s,v) ::= \"<s> = <v>;\"\n\nInitIntMember(n,v) ::= <%int <n> = <v>;%>\n\nInitBooleanMember(n,v) ::= <%bool <n> = <v>;%>\n\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\n\nIntArg(n) ::= \"int <n>\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%this.<n>%>\n\nSetMember(n,v) ::= <%this.<n> = <v>;%>\n\nAddMember(n,v) ::= <%this.<n> += <v>;%>\n\nMemberEquals(n,v) ::= <%this.<n> == <v>%>\n\nModMemberEquals(n,m,v) ::= <%this.<n> % <m> == <v>%>\n\nModMemberNotEquals(n,m,v) ::= <%this.<n> % <m> != <v>%>\n\nDumpDFA() ::= \"this.DumpDFA();\"\n\nPass() ::= \"\"\n\nStringList() ::= \"List\\<String>\"\n\nBuildParseTrees() ::= \"this.BuildParseTree = true;\"\n\nBailErrorStrategy() ::= <%ErrorHandler = new BailErrorStrategy();%>\n\nToStringTree(s) ::= <%<s>.ToStringTree(this)%>\n\nColumn() ::= \"this.Column\"\n\nText() ::= \"this.Text\"\n\nValEquals(a,b) ::= <%<a>==<b>%>\n\nTextEquals(a) ::= <%this.Text.Equals(\"<a>\")%>\n\nPlusText(a) ::= <%\"<a>\" + this.Text%>\n\nInputText() ::= \"this.TokenStream.GetText()\"\n\nLTEquals(i, v) ::= <%this.TokenStream.LT(<i>).Text.Equals(<v>)%>\n\nLANotEquals(i, v) ::= <%this.InputStream.LA(<i>)!=<v>%>\n\nTokenStartColumnEquals(i) ::= <%this.TokenStartColumn==<i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"this.GetExpectedTokens().ToString(this.Vocabulary)\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"GetRuleInvocationStackAsString()\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<Interpreter.PredictionMode = PredictionMode.LL_EXACT_AMBIG_DETECTION;>>\n\nParserToken(parser, token) ::= <%<parser>.<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\nbool Property() {\n\treturn true;\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>.<call>\"\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\n\npublic override IToken NextToken() {\n\tif (!(Interpreter is PositionAdjustingLexerATNSimulator)) {\n\t\tInterpreter = new PositionAdjustingLexerATNSimulator(this, _ATN, decisionToDFA, sharedContextCache);\n\t}\n\n\treturn base.NextToken();\n}\n\npublic override IToken Emit() {\n\tswitch (Type) {\n\tcase TOKENS:\n\t\tHandleAcceptPositionForKeyword(\"tokens\");\n\t\tbreak;\n\n\tcase LABEL:\n\t\tHandleAcceptPositionForIdentifier();\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn base.Emit();\n}\n\nprivate bool HandleAcceptPositionForIdentifier() {\n\tstring tokenText = this.Text;\n\tint identifierLength = 0;\n\twhile (identifierLength \\< tokenText.Length && IsIdentifierChar(tokenText[identifierLength])) {\n\t\tidentifierLength++;\n\t}\n\n\tif (InputStream.Index > TokenStartCharIndex + identifierLength) {\n\t\tint offset = identifierLength - 1;\n\t\tgetInterpreter().ResetAcceptPosition((ICharStream)InputStream, TokenStartCharIndex + offset, TokenStartLine, TokenStartColumn + offset);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nprivate bool HandleAcceptPositionForKeyword(string keyword) {\n\tif (InputStream.Index > TokenStartCharIndex + keyword.Length) {\n\t\tint offset = keyword.Length - 1;\n\t\tgetInterpreter().ResetAcceptPosition((ICharStream)InputStream, TokenStartCharIndex + offset, TokenStartLine, TokenStartColumn + offset);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\npublic PositionAdjustingLexerATNSimulator getInterpreter() {\n\treturn (PositionAdjustingLexerATNSimulator)base.Interpreter;\n}\n\nprivate static bool IsIdentifierChar(char c) {\n\treturn Char.IsLetterOrDigit(c) || c == '_';\n}\n\npublic class PositionAdjustingLexerATNSimulator : LexerATNSimulator {\n\n\tpublic PositionAdjustingLexerATNSimulator(Lexer recog, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache)\n\t: base(recog, atn, decisionToDFA, sharedContextCache)\n\t{\n\t}\n\n\tpublic void ResetAcceptPosition(ICharStream input, int index, int line, int column) {\n\t\tinput.Seek(index);\n\t\tthis.Line = line;\n\t\tthis.Column = column;\n\t\tConsume(input);\n\t}\n\n}\n\n>>\n\nBasicListener(X) ::= <<\n@parser::members {\npublic class LeafListener : TBaseListener {\n\tprivate readonly TextWriter Output;\n\n\tpublic LeafListener(TextWriter output) {\n\t\tOutput = output;\n\t}\n\n\tpublic override void VisitTerminal(ITerminalNode node) {\n\t\tOutput.WriteLine(node.Symbol.Text);\n\t}\n}\n}\n>>\n\nWalkListener(s) ::= <<\nParseTreeWalker walker = new ParseTreeWalker();\nwalker.Walk(new LeafListener(Output), <s>);\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::members {\npublic class MyRuleNode : ParserRuleContext {\n\tpublic int altNum;\n\tpublic MyRuleNode(ParserRuleContext parent, int invokingStateNumber): base(parent, invokingStateNumber)\n\t{\n\t}\n\tpublic override int getAltNumber() { return altNum; }\n\tpublic override void setAltNumber(int altNum) { this.altNum = altNum; }\n}\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::members {\npublic class LeafListener : TBaseListener {\n\tprivate readonly TextWriter Output;\n\n\tpublic LeafListener(TextWriter output) {\n\t\tOutput = output;\n\t}\n\n\tpublic override void ExitA(TParser.AContext ctx) {\n\t\tif (ctx.ChildCount==2)\n\t\t{\n\t\t\tStringBuilder sb = new StringBuilder (\"[\");\n\t\t\tforeach (ITerminalNode node in ctx.INT ()) {\n\t\t\t\tsb.Append (node.ToString ());\n\t\t\t\tsb.Append (\", \");\n\t\t\t}\n\t\t\tsb.Length = sb.Length - 2;\n\t\t\tsb.Append (\"]\");\n\t\t\tOutput.Write (\"{0} {1} {2}\\n\", ctx.INT (0).Symbol.Text,\n\t\t\t\tctx.INT (1).Symbol.Text, sb.ToString());\n\t\t}\n\t\telse\n\t\t\tOutput.WriteLine(ctx.ID().Symbol);\n\t}\n}\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::members {\npublic class LeafListener : TBaseListener {\n\tprivate readonly TextWriter Output;\n\n\tpublic LeafListener(TextWriter output) {\n\t\tOutput = output;\n\t}\n\n\tpublic override void ExitA(TParser.AContext ctx) {\n\t\tif (ctx.ChildCount==2) {\n\t\t\tOutput.Write(\"{0} {1} {2}\\n\",ctx.b(0).Start.Text,\n\t\t\t\tctx.b(1).Start.Text,ctx.b()[0].Start.Text);\n\t\t} else\n\t\t\tOutput.WriteLine(ctx.b(0).Start.Text);\n\t}\n}\n}\n>>\n\n\nLRListener(X) ::= <<\n@parser::members {\npublic class LeafListener : TBaseListener {\n\tprivate readonly TextWriter Output;\n\n\tpublic LeafListener(TextWriter output) {\n\t\tOutput = output;\n\t}\n\n\tpublic override void ExitE(TParser.EContext ctx) {\n\t\tif (ctx.ChildCount==3) {\n\t\t\tOutput.Write(\"{0} {1} {2}\\n\",ctx.e(0).Start.Text,\n\t\t\t\tctx.e(1).Start.Text, ctx.e()[0].Start.Text);\n\t\t} else\n\t\t\tOutput.WriteLine(ctx.INT().Symbol.Text);\n\t}\n}\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::members {\npublic class LeafListener : TBaseListener {\n\tprivate readonly TextWriter Output;\n\n\tpublic LeafListener(TextWriter output) {\n\t\tOutput = output;\n\t}\n\n\tpublic override void ExitCall(TParser.CallContext ctx) {\n\t\tOutput.Write(\"{0} {1}\\n\",ctx.e().Start.Text,ctx.eList());\n\t}\n\tpublic override void ExitInt(TParser.IntContext ctx) {\n\t\tOutput.WriteLine(ctx.INT().Symbol.Text);\n\t}\n}\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\nvoid foo() {\n\tSContext s = null;\n\tAContext[] a = s.a();\n\tBContext[] b = s.b();\n}\n>>\n\nDeclare_foo() ::= <<public void foo() {Output.WriteLine(\"foo\");}>>\n\nInvoke_foo() ::= \"this.foo();\"\n\nDeclare_pred() ::= <<bool pred(bool v) {\n\tOutput.WriteLine(\"eval=\"+v.ToString().ToLower());\n\treturn v;\n}\n>>\n\nInvoke_pred(v) ::= <<this.pred(<v>)>>\nParserTokenType(t) ::= \"Parser.<t>\"\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>()\"\nStringType() ::= \"String\"\nContextMember(ctx, member) ::= \"<ctx>.<member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>.<local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>.<member>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Cpp.test.stg",
    "content": "writeln(s) ::= \"std::cout \\<\\< <s> \\<\\< std::endl;\"\nwrite(s) ::= \"std::cout \\<\\< <s>;\"\nwriteList(s) ::= << std::cout \\<\\< <s; separator=\" \\<\\< \"> \\<\\< std::endl;>>\n\nFalse() ::= \"false\"\nTrue() ::= \"true\"\nNot(v) ::= \"!<v>\"\nAssert(s) ::= \"\"\nCast(t,v) ::= \"dynamic_cast\\<<t> *>(<v>)\" // Should actually use a more specific name. We may have to use other casts as well.\nAppend(a,b) ::= \"<a> + <b>->toString()\"\nConcat(a,b) ::= \"<a><b>\"\nAppendStr(a,b) ::= \"<a> + <b>\"\n\nAssertIsList(v) ::= \"assert(<v>.size() >= 0);\" // Use a method that exists only on a list (vector actually).\nAssignLocal(s,v) ::= \"<s> = <v>;\"\n\nInitIntMember(n,v) ::= \"int <n> = <v>;\"\nInitBooleanMember(n,v) ::= \"bool <n> = <v>;\"\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\nIntArg(n) ::= \"int <n>\"\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= \"<n>\"\nSetMember(n,v) ::= \"<n> = <v>;\"\nAddMember(n,v) ::= \"<n> += <v>;\"\nMemberEquals(n,v) ::= \"<n> == <v>\"\nModMemberEquals(n,m,v) ::= \"<n> % <m> == <v>\"\nModMemberNotEquals(n,m,v) ::= \"<n> % <m> != <v>\"\n\nDumpDFA() ::= \"dumpDFA();\"\nPass() ::= \"/* do nothing */\"\n\nStringList() ::= \"std::vector\\<std::string>\"\nBuildParseTrees() ::= \"setBuildParseTree(true);\"\nBailErrorStrategy() ::= \"_errHandler = std::make_shared\\<BailErrorStrategy>();\"\n\nToStringTree(s) ::= \"<s>->toStringTree(this)\"\nColumn() ::= \"getCharPositionInLine()\"\nText() ::= \"getText()\"\nValEquals(a,b) ::= \"<a> == <b>\"\nTextEquals(a) ::= \"getText() == \\\"<a>\\\"\"\nPlusText(a) ::=\"\\\"<a>\\\" + getText()\"\nInputText() ::= \"_input->getText()\"\nLTEquals(i, v) ::= \"_input->LT(<i>)->getText() == <v>\"\nLANotEquals(i, v) ::= \"_input->LA(<i>) != <v>\"\nTokenStartColumnEquals(i) ::= \"tokenStartCharPositionInLine == <i>\"\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"getExpectedTokens().toString(getVocabulary())\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"Arrays::listToString(getRuleInvocationStack(), \\\", \\\")\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<getInterpreter\\<atn::ParserATNSimulator>()->setPredictionMode(atn::PredictionMode::LL_EXACT_AMBIG_DETECTION);>>\n\nParserToken(parser, token) ::= <%<parser>::<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\nbool Property() {\n\treturn true;\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<call>\"\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\nprotected:\n  class PositionAdjustingLexerATNSimulator : public antlr4::atn::LexerATNSimulator {\n  public:\n    PositionAdjustingLexerATNSimulator(antlr4::Lexer *recog, const antlr4::atn::ATN &atn, std::vector\\<antlr4::dfa::DFA> &decisionToDFA,\n                                       antlr4::atn::PredictionContextCache &sharedContextCache)\n      : antlr4::atn::LexerATNSimulator(recog, atn, decisionToDFA, sharedContextCache) {\n    }\n\n    void resetAcceptPosition(antlr4::CharStream *input, int index, int line, int charPositionInLine) {\n      input->seek(index);\n      _line = line;\n      _charPositionInLine = charPositionInLine;\n      consume(input);\n    }\n\n  };\n\npublic:\n  virtual std::unique_ptr\\<antlr4::Token> nextToken() override {\n    if (dynamic_cast\\<PositionAdjustingLexerATNSimulator *>(_interpreter) == nullptr) {\n      const auto &atn = _interpreter->atn;\n      auto &decisionToDFA = dynamic_cast\\<antlr4::atn::LexerATNSimulator*>(_interpreter)->_decisionToDFA;\n      auto &sharedContextCache = dynamic_cast\\<antlr4::atn::LexerATNSimulator*>(_interpreter)->getSharedContextCache();\n      delete _interpreter;\n      _interpreter = new PositionAdjustingLexerATNSimulator(this, atn, decisionToDFA, sharedContextCache);\n    }\n\n    return antlr4::Lexer::nextToken();\n  }\n\n  virtual antlr4::Token* emit() override {\n    switch (type) {\n      case TOKENS:\n        handleAcceptPositionForKeyword(\"tokens\");\n        break;\n\n      case LABEL:\n        handleAcceptPositionForIdentifier();\n        break;\n\n      default:\n        break;\n    }\n    return antlr4::Lexer::emit();\n  }\n\nprivate:\n  bool handleAcceptPositionForIdentifier() {\n    std::string tokenText = getText();\n    int identifierLength = 0;\n    while (identifierLength \\< tokenText.length() && isIdentifierChar(tokenText[identifierLength])) {\n      identifierLength++;\n    }\n\n    if (getInputStream()->index() > tokenStartCharIndex + identifierLength) {\n      int offset = identifierLength - 1;\n      getInterpreter\\<PositionAdjustingLexerATNSimulator>()->resetAcceptPosition(getInputStream(),\n        tokenStartCharIndex + offset, tokenStartLine, tokenStartCharPositionInLine + offset);\n      return true;\n    }\n\n    return false;\n  }\n\n  bool handleAcceptPositionForKeyword(const std::string &keyword) {\n    if (getInputStream()->index() > tokenStartCharIndex + keyword.length()) {\n      long offset = keyword.size() - 1;\n      getInterpreter\\<PositionAdjustingLexerATNSimulator>()->resetAcceptPosition(getInputStream(),\n        tokenStartCharIndex + offset, tokenStartLine, tokenStartCharPositionInLine + offset);\n      return true;\n    }\n\n    return false;\n  }\n\n  static bool isIdentifierChar(char c) {\n    return std::isalnum(c) || c == '_';\n  }\n\npublic:\n>>\n\nBasicListener(X) ::= <<\n@parser::definitions {\n#include \"TBaseListener.h\"\nclass LeafListener : public TBaseListener {\npublic:\n  virtual void visitTerminal(tree::TerminalNode *node) override {\n  std::cout \\<\\< node->getSymbol()->getText() \\<\\< std::endl;\n  }\n};\n}\n>>\n\nWalkListener(s) ::= <<\nLeafListener listener;\ntree::ParseTreeWalker::DEFAULT.walk(&listener, <s>);\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::members {\nclass MyRuleNode : public antlr4::ParserRuleContext {\npublic:\n  size_t altNum;\n\tMyRuleNode(antlr4::ParserRuleContext *parent, int invokingStateNumber)\n\t\t: antlr4::ParserRuleContext(parent, invokingStateNumber) {\n\t}\n\tvirtual size_t getAltNumber() const override { return altNum; }\n\tvirtual void setAltNumber(size_t altNum) override { this->altNum = altNum; }\n};\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::definitions {\n#include \"TBaseListener.h\"\nclass LeafListener : public TBaseListener {\npublic:\n  virtual void exitA(TParser::AContext *ctx) override {\n\t\tif (ctx->children.size() == 2)\n\t\t\tstd::cout \\<\\< ctx->INT(0)->getSymbol()->getText() \\<\\< \" \" \\<\\< ctx->INT(1)->getSymbol()->getText()\n        \\<\\< \" \" \\<\\< Arrays::toString(ctx->INT()) \\<\\< std::endl;\n\t\telse\n\t\t\tstd::cout \\<\\< ctx->ID()->getSymbol()->toString() \\<\\< std::endl;\n\t}\n};\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::definitions {\n#include \"TBaseListener.h\"\nclass LeafListener : public TBaseListener {\npublic:\n  virtual void exitA(TParser::AContext *ctx) override {\n    if (ctx->children.size() == 2) {\n      std::cout \\<\\< ctx->b(0)->start->getText() \\<\\< \" \" \\<\\< ctx->b(1)->start->getText() \\<\\< \" \" \\<\\< ctx->b()[0]->start->getText() \\<\\< std::endl;\n    } else {\n      std::cout \\<\\< ctx->b(0)->start->getText() \\<\\< std::endl;\n    }\n  }\n};\n}\n>>\n\n\nLRListener(X) ::= <<\n@parser::definitions {\n#include \"TBaseListener.h\"\nclass LeafListener : public TBaseListener {\npublic:\n  virtual void exitE(TParser::EContext *ctx) override {\n    if (ctx->children.size() == 3) {\n      std::cout \\<\\< ctx->e(0)->start->getText() \\<\\< \" \" \\<\\< ctx->e(1)->start->getText() \\<\\< \" \" \\<\\< ctx->e()[0]->start->getText() \\<\\< std::endl;\n    } else {\n      std::cout \\<\\< ctx->INT()->getSymbol()->getText() \\<\\< std::endl;\n    }\n  }\n};\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::definitions {\n#include \"TBaseListener.h\"\nclass LeafListener : public TBaseListener {\npublic:\n  virtual void exitCall(TParser::CallContext *ctx) override {\n    std::cout \\<\\< ctx->e()->start->getText() \\<\\< \" \" \\<\\< ctx->eList()->toString() \\<\\< std::endl;\n\t}\n\tvirtual void exitInt(TParser::IntContext *ctx) override {\n\t\tstd::cout \\<\\<  ctx->INT()->getSymbol()->getText() \\<\\< std::endl;\n\t}\n};\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\nvoid foo() {\n  SContext *s;\n  std::vector\\<AContext *> a = s->a();\n  std::vector\\<BContext *> b = s->b();\n}\n>>\n\nDeclare_foo() ::= <<void foo() {\n\tstd::cout \\<\\< \"foo\" \\<\\< std::endl;\n}\n>>\n\nInvoke_foo() ::= \"foo();\"\n\nDeclare_pred() ::= <<\nbool pred(bool v) {\n\tstd::cout \\<\\< \"eval=\" \\<\\< std::boolalpha \\<\\< v \\<\\< std::endl;\n\treturn v;\n}\n>>\n\nInvoke_pred(v) ::= <<pred(<v>)>>\n\nContextRuleFunction(ctx, rule) ::= \"<ctx>-><rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>-><rule>()\"\nStringType() ::= \"std::string\"\nContextMember(ctx, member) ::= \"<ctx>-><member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>-><subctx>-><local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>-><subctx>-><member>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Dart.test.stg",
    "content": "writeln(s) ::= <<print(<s>);>>\nwrite(s) ::= <<TEST_platformStdoutWrite(<s>);>>\nwriteList(s) ::= <<print(<s; separator=\"+\">);>>\n\nFalse() ::= \"false\"\n\nTrue() ::= \"true\"\n\nNot(v) ::= \"!<v>\"\n\nAssert(s) ::= <<assert(<s>);>>\n\nCast(t,v) ::= \"(<v> as <t>)\"\n\nAppend(a,b) ::= \"<a>.toString() + <b>.toString()\"\n\nAppendStr(a,b) ::= <%<Append(a,b)>%>\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= \"assert (<v> is List);\" // just use static type system\n\nAssignLocal(s,v) ::= \"<s> = <v>;\"\n\nInitIntMember(n,v) ::= <%int <n> = <v>;%>\n\nInitBooleanMember(n,v) ::= <%bool <n> = <v>;%>\n\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\n\nIntArg(n) ::= \"int <n>\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%this.<n>%>\n\nSetMember(n,v) ::= <%this.<n> = <v>;%>\n\nAddMember(n,v) ::= <%this.<n> += <v>;%>\n\nMemberEquals(n,v) ::= <%this.<n> == <v>%>\n\nModMemberEquals(n,m,v) ::= <%this.<n> % <m> == <v>%>\n\nModMemberNotEquals(n,m,v) ::= <%this.<n> % <m> != <v>%>\n\nDumpDFA() ::= \"this.dumpDFA();\"\n\nPass() ::= \"\"\n\nStringList() ::= \"List\\<String>\"\n\nBuildParseTrees() ::= \"buildParseTree = true;\"\n\nBailErrorStrategy() ::= <%errorHandler = new BailErrorStrategy();%>\n\nToStringTree(s) ::= <%<s>.toStringTree(parser: this)%>\n\nColumn() ::= \"this.charPositionInLine\"\n\nText() ::= \"this.text\"\n\nValEquals(a,b) ::= <%<a>==<b>%>\n\nTextEquals(a) ::= <%this.text == \"<a>\"%>\n\nPlusText(a) ::= <%\"<a>\" + this.text%>\n\nInputText() ::= \"tokenStream.text\"\n\nLTEquals(i, v) ::= <%tokenStream.LT(<i>)!.text == <v>%>\n\nLANotEquals(i, v) ::= <%tokenStream.LA(<i>)!=<v>%>\n\nTokenStartColumnEquals(i) ::= <%this.tokenStartCharPositionInLine==<i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"this.expectedTokens.toString(vocabulary: this.vocabulary)\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"ruleInvocationStack\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<interpreter!.predictionMode = PredictionMode.LL_EXACT_AMBIG_DETECTION;>>\n\nParserToken(parser, token) ::= <%<parser>.TOKEN_<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\nbool Property() {\n  return true;\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>.<call>\"\n\nPositionAdjustingLexerDef() ::= <<\nclass PositionAdjustingLexerATNSimulator extends LexerATNSimulator {\n  PositionAdjustingLexerATNSimulator(Lexer recog, ATN atn,\n      List\\<DFA> decisionToDFA, PredictionContextCache sharedContextCache)\n      : super(atn, decisionToDFA, sharedContextCache, recog: recog);\n\n  void resetAcceptPosition(CharStream input, int index, int line,\n      int charPositionInLine) {\n    input.seek(index);\n    this.line = line;\n    this.charPositionInLine = charPositionInLine;\n    consume(input);\n  }\n}\n>>\n\nPositionAdjustingLexer() ::= <<\n@override\nToken nextToken() {\n  if (!(super.interpreter is PositionAdjustingLexerATNSimulator)) {\n    interpreter = new PositionAdjustingLexerATNSimulator(\n        this, _ATN, _decisionToDFA, _sharedContextCache);\n  }\n\n  return super.nextToken();\n}\n\n@override\nToken emit() {\n  switch (type) {\n    case TOKEN_TOKENS:\n      handleAcceptPositionForKeyword(\"tokens\");\n      break;\n\n    case TOKEN_LABEL:\n      handleAcceptPositionForIdentifier();\n      break;\n\n    default:\n      break;\n  }\n\n  return super.emit();\n}\n\nbool handleAcceptPositionForIdentifier() {\n  String tokenText = text;\n  int identifierLength = 0;\n  while (identifierLength \\< tokenText.length &&\n    isIdentifierChar(tokenText[identifierLength])) {\n    identifierLength++;\n  }\n\n  if (inputStream.index > tokenStartCharIndex + identifierLength) {\n    int offset = identifierLength - 1;\n    interpreter.resetAcceptPosition(inputStream, tokenStartCharIndex + offset,\n        tokenStartLine, tokenStartCharPositionInLine + offset);\n    return true;\n  }\n\n  return false;\n}\n\nbool handleAcceptPositionForKeyword(String keyword) {\n  if (inputStream.index > tokenStartCharIndex + keyword.length) {\n    int offset = keyword.length - 1;\n    interpreter.resetAcceptPosition(inputStream, tokenStartCharIndex + offset,\n        tokenStartLine, tokenStartCharPositionInLine + offset);\n    return true;\n  }\n\n  return false;\n}\n\n@override\nPositionAdjustingLexerATNSimulator get interpreter {\n  return super.interpreter as PositionAdjustingLexerATNSimulator;\n}\n\nstatic bool isIdentifierChar(String c) {\n  return isLetterOrDigit(c) || c == '_';\n}\n\nstatic const ZERO = 48;\nstatic const LOWER_A = 97;\nstatic const LOWER_Z = 122;\nstatic const UPPER_A = 65;\nstatic const UPPER_Z = 90;\n\nstatic bool isLetterOrDigit(String char) => isLetter(char) || isDigit(char);\n\n// Note: this is intentially ASCII only\nstatic bool isLetter(String char) {\n  if (char == null) return false;\n  var cc = char.codeUnitAt(0);\n  return cc >= LOWER_A && cc \\<= LOWER_Z || cc >= UPPER_A && cc \\<= UPPER_Z;\n}\n\nstatic bool isDigit(String char) {\n  if (char == null) return false;\n  var cc = char.codeUnitAt(0);\n  return cc >= ZERO && cc \\< ZERO + 10;\n}\n>>\n\nBasicListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n  void visitTerminal(TerminalNode node) {\n    print(node.symbol.text);\n  }\n}\n}\n>>\n\nWalkListener(s) ::= <<\nParseTreeWalker walker = new ParseTreeWalker();\nwalker.walk(new LeafListener(), <s>);\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::definitions {\nclass MyRuleNode extends ParserRuleContext {\n  late int altNum;\n\n  MyRuleNode(ParserRuleContext? parent, int? invokingStateNumber)\n      : super(parent, invokingStateNumber);\n\n  @override int get altNumber {\n    return altNum;\n  }\n\n  @override void set altNumber(int altNum) {\n    this.altNum = altNum;\n  }\n}\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n  void exitA(AContext ctx) {\n    if (ctx.childCount==2)\n      TEST_platformStdoutWrite(\"${ctx.INT(0)?.symbol.text} ${ctx.INT(1)?.symbol.text} ${ctx.INTs()}\\n\");\n    else\n      print(ctx.ID()?.symbol);\n  }\n}\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n  void exitA(AContext ctx) {\n    if (ctx.childCount==2) {\n      TEST_platformStdoutWrite(\"${ctx.b(0)?.start?.text} ${ctx.b(1)?.start?.text} ${ctx.bs()[0].start?.text}\\n\");\n    } else\n      print(ctx.b(0)?.start?.text);\n  }\n}\n}\n>>\n\n\nLRListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n  void exitE(EContext ctx) {\n    if (ctx.childCount==3) {\n      print(\"${ctx.e(0)?.start?.text} ${ctx.e(1)?.start?.text} ${ctx.es()[0].start?.text}\");\n    } else\n      print(ctx.INT()?.symbol.text);\n  }\n}\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n  void exitCall(CallContext ctx) {\n    TEST_platformStdoutWrite(\"${ctx.e()?.start?.text} ${ctx.eList()}\\n\");\n  }\n  void exitInt(IntContext ctx) {\n    print(ctx.INT()?.symbol.text);\n  }\n}\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\nvoid foo() {\n  SContext? s = null;\n  List\\<AContext>? a = s?.as();\n  List\\<BContext>? b = s?.bs();\n}\n>>\n\nDeclare_foo() ::= <<\n  void foo() {print(\"foo\");}\n>>\n\nInvoke_foo() ::= \"foo();\"\n\nDeclare_pred() ::= <<bool pred(bool v) {\n  print(\"eval=\\$v\");\n  return v;\n}\n>>\n\nInvoke_pred(v) ::= <<this.pred(<v>)>>\n\nParserTokenType(t) ::= \"Parser.<t>\"\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>()\"\nStringType() ::= \"String\"\nContextMember(ctx, member) ::= \"<ctx>.<member>!\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>!.<local>!\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>!.<member>!\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Go.test.stg",
    "content": "writeln(s) ::= <<fmt.Println(<s>)>>\nwrite(s) ::= <<fmt.Print(<s>)>>\nwriteList(s) ::= <<fmt.Print(<s; separator=\"+\">);>>\n\nFalse() ::= \"false\"\n\nTrue() ::= \"true\"\n\nNot(v) ::= \"!<v>\"\n\nAssert(s) ::= \"\"\n\nCast(t,v) ::= \"(<v>)\"\n\nAppend(a,b) ::= \"<a> + fmt.Sprint(<b>)\"\n\nAppendStr(a,b) ::= \"<a> + <b>\"\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= <<\n// Go will not compile this generated code if the slice vs single value is wrong.\nfor i := range localctx.(*ExpressionContext).GetArgs() {\n    _ = localctx.(*ExpressionContext).GetArgs()[i]\n}\n>>\n\nAssignLocal(s, v) ::= \"<s> = <v>;\"\n\nInitIntMember(n, v) ::= <%var <n> int = <v>; var _ int = <n>; %>\n\nInitBooleanMember(n, v) ::= <%var <n> bool = <v>; var _ bool = <n>; %>\n\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\n\nIntArg(n) ::= \"int <n>\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%<n>%>\n\nSetMember(n, v) ::= <%<n> = <v>;%>\n\nAddMember(n, v) ::= <%<n> += <v>;%>\n\nMemberEquals(n, v) ::= <%<n> == <v>%>\n\nModMemberEquals(n, m, v) ::= <%<n> % <m> == <v>%>\n\nModMemberNotEquals(n, m, v) ::= <%<n> % <m> != <v>%>\n\nDumpDFA() ::= \"p.DumpDFA()\"\n\nPass() ::= \"\"\n\nStringList() ::= \"[]string\"\n\nBuildParseTrees() ::= \"p.BuildParseTrees = true\"\n\nBailErrorStrategy() ::= <%p.SetErrorHandler(antlr.NewBailErrorStrategy())%>\n\nToStringTree(s) ::= <%<s>.ToStringTree(nil, p)%>\n\nColumn() ::= \"p.GetCharPositionInLine()\"\n\nText() ::= \"l.GetText()\"\n\nValEquals(a, b) ::= <%<a> == <b>%>\n\nTextEquals(a) ::= <%p.GetText() == \"<a>\"%>\n\nPlusText(a) ::= <%\"<a>\" + l.GetText()%>\n\nInputText() ::= \"p.GetTokenStream().GetAllText()\"\n\nLTEquals(i, v) ::= <%p.GetTokenStream().LT(<i>).GetText() == <v>%>\n\nLANotEquals(i, v) ::= <%p.GetTokenStream().LA(<i>) != <v>%>\n\nTokenStartColumnEquals(i) ::= <%p.TokenStartColumn == <i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"p.GetExpectedTokens().StringVerbose(p.GetTokenNames(), nil, false)\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"antlr.PrintArrayJavaStyle(p.GetRuleInvocationStack(nil))\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<p.Interpreter.SetPredictionMode(antlr.PredictionModeLLExactAmbigDetection);>>\n\nParserToken(parser, token) ::= <%<parser><token>%>\n\nProduction(p) ::= <%<p; format=\"cap\">%>\n\nResult(r) ::= <%Get<r; format=\"cap\">()%>\n\nParserPropertyMember() ::= <<\n@parser::members {\nfunc (p *TParser) Property() bool {\n\treturn true\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>.<call>\"\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\nfunc (p *PositionAdjustingLexer) NextToken() antlr.Token {\n\tif _, ok := p.Interpreter.(*PositionAdjustingLexerATNSimulator); !ok {\n\t\tp.Interpreter = NewPositionAdjustingLexerATNSimulator(p, p.Interpreter.ATN(), p.Interpreter.DecisionToDFA(), p.Interpreter.SharedContextCache())\n\t\tp.Virt = p\n\t}\n\n\treturn p.BaseLexer.NextToken()\n}\n\nfunc (p *PositionAdjustingLexer) Emit() antlr.Token {\n\tswitch p.GetType() {\n\tcase PositionAdjustingLexerTOKENS:\n\t\tp.HandleAcceptPositionForKeyword(\"tokens\")\n\n\tcase PositionAdjustingLexerLABEL:\n\t\tp.HandleAcceptPositionForIdentifier()\n\t}\n\n\treturn p.BaseLexer.Emit()\n}\n\nfunc isIdentifierChar(c rune) bool {\n\treturn unicode.IsLetter(c) || unicode.IsDigit(c) || c == '_'\n}\n\nfunc (p *PositionAdjustingLexer) HandleAcceptPositionForIdentifier() bool {\n\tvar tokenText = p.GetText()\n\tvar identifierLength int\n\n\tfor identifierLength \\< len(tokenText) && isIdentifierChar([]rune(tokenText)[identifierLength]) {\n\t\tidentifierLength++\n\t}\n\n\tif p.GetInputStream().Index() \\<= p.TokenStartCharIndex + identifierLength {\n\t\treturn false\n\t}\n\n\tvar offset = identifierLength - 1\n\n\tp.GetInterpreter().(*PositionAdjustingLexerATNSimulator).ResetAcceptPosition(p.GetInputStream(), p.TokenStartCharIndex + offset, p.TokenStartLine, p.TokenStartColumn + offset)\n\n\treturn true\n}\n\nfunc (p *PositionAdjustingLexer) HandleAcceptPositionForKeyword(keyword string) bool {\n\tif p.GetInputStream().Index() \\<= p.TokenStartCharIndex + len(keyword) {\n\t\treturn false\n\t}\n\n\tvar offset = len(keyword) - 1\n\n\tp.GetInterpreter().(*PositionAdjustingLexerATNSimulator).ResetAcceptPosition(p.GetInputStream(), p.TokenStartCharIndex + offset, p.TokenStartLine, p.TokenStartColumn + offset)\n\n\treturn true\n}\n\ntype PositionAdjustingLexerATNSimulator struct {\n\t*antlr.LexerATNSimulator\n}\n\nfunc NewPositionAdjustingLexerATNSimulator(recog antlr.Lexer, atn *antlr.ATN, decisionToDFA []*antlr.DFA, sharedContextCache *antlr.PredictionContextCache) *PositionAdjustingLexerATNSimulator {\n\treturn &PositionAdjustingLexerATNSimulator{\n\t\tLexerATNSimulator: antlr.NewLexerATNSimulator(recog, atn, decisionToDFA, sharedContextCache),\n\t}\n}\n\nfunc (p *PositionAdjustingLexerATNSimulator) ResetAcceptPosition(input antlr.CharStream, index, line, charPositionInLine int) {\n\tinput.Seek(index)\n\tp.Line = line\n\tp.CharPositionInLine = charPositionInLine\n\tp.Consume(input)\n}\n\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::members {\n\ntype MyRuleNode struct {\n\t*antlr.BaseParserRuleContext\n\n\taltNum int\n}\n\nfunc NewMyRuleNode(parent antlr.ParserRuleContext, invokingStateNumber int) *MyRuleNode {\n\treturn &MyRuleNode{\n\t\tBaseParserRuleContext : antlr.NewBaseParserRuleContext(parent, invokingStateNumber),\n\t}\n}\n\nfunc (m *MyRuleNode) GetAltNumber() int {\n\treturn m.altNum\n}\n\nfunc (m *MyRuleNode) SetAltNumber(altNum int) {\n\tm.altNum = altNum\n}\n\n}\n>>\n\nBasicListener(notused) ::= <<\n@parser::members {\ntype LeafListener struct {\n\t*BaseTListener\n}\n\nfunc NewLeafListener() *LeafListener {\n\treturn &LeafListener{BaseTListener: &BaseTListener{}}\n}\n\nfunc (*LeafListener) VisitTerminal(node antlr.TerminalNode) {\n\tfmt.Println(node.GetSymbol().GetText())\n}\n}\n>>\n\nWalkListener(s) ::= <<\nvar walker = antlr.NewParseTreeWalker()\n\nwalker.Walk(NewLeafListener(), <s>)\n>>\n\nTokenGetterListener(notused) ::= <<\n@parser::members {\ntype LeafListener struct {\n\t*BaseTListener\n}\n\nfunc NewLeafListener() *LeafListener {\n\treturn &LeafListener{BaseTListener: &BaseTListener{}}\n}\n\nfunc (*LeafListener) ExitA(ctx *AContext) {\n\tif ctx.GetChildCount() == 2 {\n\t\tfmt.Printf(\"%s %s %s\\n\", ctx.INT(0).GetSymbol().GetText(), ctx.INT(1).GetSymbol().GetText(), antlr.PrintArrayJavaStyle(antlr.TerminalNodeToStringArray(ctx.AllINT())))\n\t} else {\n\t\tfmt.Println(ctx.ID().GetSymbol())\n\t}\n}\n}\n>>\n\nRuleGetterListener(notused) ::= <<\n@parser::members {\ntype LeafListener struct {\n\t*BaseTListener\n}\n\nfunc NewLeafListener() *LeafListener {\n\treturn &LeafListener{BaseTListener: &BaseTListener{}}\n}\n\nfunc (*LeafListener) ExitA(ctx *AContext) {\n\tif ctx.GetChildCount() == 2 {\n\t\tfmt.Printf(\"%s %s %s\\n\", ctx.B(0).GetStart().GetText(), ctx.B(1).GetStart().GetText(), ctx.AllB()[0].GetStart().GetText())\n\t} else {\n\t\tfmt.Println(ctx.B(0).GetStart().GetText())\n\t}\n}\n}\n>>\n\nLRListener(notused) ::= <<\n@parser::members {\ntype LeafListener struct {\n\t*BaseTListener\n}\n\nfunc NewLeafListener() *LeafListener {\n\treturn &LeafListener{BaseTListener: &BaseTListener{}}\n}\n\nfunc (*LeafListener) ExitE(ctx *EContext) {\n\tif ctx.GetChildCount() == 3 {\n\t\tfmt.Printf(\"%s %s %s\\n\", ctx.E(0).GetStart().GetText(), ctx.E(1).GetStart().GetText(), ctx.AllE()[0].GetStart().GetText())\n\t} else {\n\t\tfmt.Println(ctx.INT().GetSymbol().GetText())\n\t}\n}\n}\n>>\n\nLRWithLabelsListener(notused) ::= <<\n@parser::members {\ntype LeafListener struct {\n\t*BaseTListener\n}\n\nfunc NewLeafListener() *LeafListener {\n\treturn &LeafListener{BaseTListener: &BaseTListener{}}\n}\n\nfunc (*LeafListener) ExitCall(ctx *CallContext) {\n\tfmt.Printf(\"%s %s\\n\", ctx.E().GetStart().GetText(), ctx.EList().String(nil, nil))\n}\n\nfunc (*LeafListener) ExitInt(ctx *IntContext) {\n\tfmt.Println(ctx.INT().GetSymbol().GetText())\n}\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\nfunc foo() {\n\t// TODO\n\t// var s SContext\n\t// var a = s.A()\n\t// var b = s.B()\n}\n>>\n\nDeclare_foo() ::= <<\nfunc foo() {\n\tfmt.Println(\"foo\")\n}\n>>\n\nInvoke_foo() ::= \"foo()\"\n\nDeclare_pred() ::= <<\nfunc pred(v bool) bool {\n\tfmt.Println(\"eval=\" + fmt.Sprint(v))\n\n\treturn v\n}\n>>\n\nInvoke_pred(v) ::= <<pred(<v>)>>\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>()\"\nStringType() ::= \"string\"\nContextMember(ctx, member) ::= \"<ctx>.<member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>.<local; format={cap}>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>.<member; format={cap}>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Java.test.stg",
    "content": "writeln(s) ::= <<outStream.println(<s>);>>\nwrite(s) ::= <<outStream.print(<s>);>>\nwriteList(s) ::= <<outStream.println(<s; separator=\"+\">);>>\n\nFalse() ::= \"false\"\n\nTrue() ::= \"true\"\n\nNot(v) ::= \"!<v>\"\n\nAssert(s) ::= <<assert(<s>);>>\n\nCast(t,v) ::= \"((<t>)<v>)\"\n\nAppend(a,b) ::= \"<a> + <b>\"\n\nAppendStr(a,b) ::= <%<Append(a,b)>%>\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= \"List\\<?> __ttt__ = <v>;\" // just use static type system\n\nAssignLocal(s,v) ::= \"<s> = <v>;\"\n\nInitIntMember(n,v) ::= <%int <n> = <v>;%>\n\nInitBooleanMember(n,v) ::= <%boolean <n> = <v>;%>\n\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\n\nIntArg(n) ::= \"int <n>\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%this.<n>%>\n\nSetMember(n,v) ::= <%this.<n> = <v>;%>\n\nAddMember(n,v) ::= <%this.<n> += <v>;%>\n\nMemberEquals(n,v) ::= <%this.<n> == <v>%>\n\nModMemberEquals(n,m,v) ::= <%this.<n> % <m> == <v>%>\n\nModMemberNotEquals(n,m,v) ::= <%this.<n> % <m> != <v>%>\n\nDumpDFA() ::= \"this.dumpDFA(outStream);\"\n\nPass() ::= \"\"\n\nStringList() ::= \"List\\<String>\"\n\nBuildParseTrees() ::= \"setBuildParseTree(true);\"\n\nBailErrorStrategy() ::= <%setErrorHandler(new BailErrorStrategy());%>\n\nToStringTree(s) ::= <%<s>.toStringTree(this)%>\n\nColumn() ::= \"this.getCharPositionInLine()\"\n\nText() ::= \"this.getText()\"\n\nValEquals(a,b) ::= <%<a>==<b>%>\n\nTextEquals(a) ::= <%this.getText().equals(\"<a>\")%>\n\nPlusText(a) ::= <%\"<a>\" + this.getText()%>\n\nInputText() ::= \"this._input.getText()\"\n\nLTEquals(i, v) ::= <%this._input.LT(<i>).getText().equals(<v>)%>\n\nLANotEquals(i, v) ::= <%this._input.LA(<i>)!=<v>%>\n\nTokenStartColumnEquals(i) ::= <%this._tokenStartCharPositionInLine==<i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"this.getExpectedTokens().toString(this.tokenNames)\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"getRuleInvocationStack()\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<_interp.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);>>\n\nParserToken(parser, token) ::= <%<parser>.<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\nboolean Property() {\n  return true;\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>.<call>\"\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\n\n@Override\npublic Token nextToken() {\n\tif (!(_interp instanceof PositionAdjustingLexerATNSimulator)) {\n\t\t_interp = new PositionAdjustingLexerATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache);\n\t}\n\n\treturn super.nextToken();\n}\n\n@Override\npublic Token emit() {\n\tswitch (_type) {\n\tcase TOKENS:\n\t\thandleAcceptPositionForKeyword(\"tokens\");\n\t\tbreak;\n\n\tcase LABEL:\n\t\thandleAcceptPositionForIdentifier();\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn super.emit();\n}\n\nprivate boolean handleAcceptPositionForIdentifier() {\n\tString tokenText = getText();\n\tint identifierLength = 0;\n\twhile (identifierLength \\< tokenText.length() && isIdentifierChar(tokenText.charAt(identifierLength))) {\n\t\tidentifierLength++;\n\t}\n\n\tif (getInputStream().index() > _tokenStartCharIndex + identifierLength) {\n\t\tint offset = identifierLength - 1;\n\t\tgetInterpreter().resetAcceptPosition(getInputStream(), _tokenStartCharIndex + offset, _tokenStartLine, _tokenStartCharPositionInLine + offset);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nprivate boolean handleAcceptPositionForKeyword(String keyword) {\n\tif (getInputStream().index() > _tokenStartCharIndex + keyword.length()) {\n\t\tint offset = keyword.length() - 1;\n\t\tgetInterpreter().resetAcceptPosition(getInputStream(), _tokenStartCharIndex + offset, _tokenStartLine, _tokenStartCharPositionInLine + offset);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n@Override\npublic PositionAdjustingLexerATNSimulator getInterpreter() {\n\treturn (PositionAdjustingLexerATNSimulator)super.getInterpreter();\n}\n\nprivate static boolean isIdentifierChar(char c) {\n\treturn Character.isLetterOrDigit(c) || c == '_';\n}\n\nprotected static class PositionAdjustingLexerATNSimulator extends LexerATNSimulator {\n\n\tpublic PositionAdjustingLexerATNSimulator(Lexer recog, ATN atn,\n\t\t\t\t\t\t\t\t\t\t\t  DFA[] decisionToDFA,\n\t\t\t\t\t\t\t\t\t\t\t  PredictionContextCache sharedContextCache)\n\t{\n\t\tsuper(recog, atn, decisionToDFA, sharedContextCache);\n\t}\n\n\tprotected void resetAcceptPosition(CharStream input, int index, int line, int charPositionInLine) {\n\t\tinput.seek(index);\n\t\tthis.line = line;\n\t\tthis.charPositionInLine = charPositionInLine;\n\t\tconsume(input);\n\t}\n\n}\n\n>>\n\nBasicListener(X) ::= <<\n@parser::members {\npublic class LeafListener extends TBaseListener {\n\tpublic void visitTerminal(TerminalNode node) {\n\t\toutStream.println(node.getSymbol().getText());\n\t}\n}\n}\n>>\n\nWalkListener(s) ::= <<\nParseTreeWalker walker = new ParseTreeWalker();\nwalker.walk(new LeafListener(), <s>);\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::members {\npublic static class MyRuleNode extends ParserRuleContext {\n\tpublic int altNum;\n\tpublic MyRuleNode(ParserRuleContext parent, int invokingStateNumber) {\n\t\tsuper(parent, invokingStateNumber);\n\t}\n\t@Override public int getAltNumber() { return altNum; }\n\t@Override public void setAltNumber(int altNum) { this.altNum = altNum; }\n}\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::members {\npublic class LeafListener extends TBaseListener {\n\tpublic void exitA(TParser.AContext ctx) {\n\t\tif (ctx.getChildCount()==2)\n\t\t\toutStream.printf(\"%s %s %s\\n\",ctx.INT(0).getSymbol().getText(),\n\t\t\t\tctx.INT(1).getSymbol().getText(),ctx.INT());\n\t\telse\n\t\t\toutStream.println(ctx.ID().getSymbol());\n\t}\n}\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::members {\npublic class LeafListener extends TBaseListener {\n\tpublic void exitA(TParser.AContext ctx) {\n\t\tif (ctx.getChildCount()==2) {\n\t\t\toutStream.printf(\"%s %s %s\\n\",ctx.b(0).start.getText(),\n\t\t\t\tctx.b(1).start.getText(),ctx.b().get(0).start.getText());\n\t\t} else\n\t\t\toutStream.println(ctx.b(0).start.getText());\n\t}\n}\n}\n>>\n\n\nLRListener(X) ::= <<\n@parser::members {\npublic class LeafListener extends TBaseListener {\n\tpublic void exitE(TParser.EContext ctx) {\n\t\tif (ctx.getChildCount()==3) {\n\t\t\toutStream.printf(\"%s %s %s\\n\",ctx.e(0).start.getText(),\n\t\t\t\tctx.e(1).start.getText(), ctx.e().get(0).start.getText());\n\t\t} else\n\t\t\toutStream.println(ctx.INT().getSymbol().getText());\n\t}\n}\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::members {\npublic class LeafListener extends TBaseListener {\n\tpublic void exitCall(TParser.CallContext ctx) {\n\t\toutStream.printf(\"%s %s\\n\",ctx.e().start.getText(),ctx.eList());\n\t}\n\tpublic void exitInt(TParser.IntContext ctx) {\n\t\toutStream.println(ctx.INT().getSymbol().getText());\n\t}\n}\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\nvoid foo() {\n\tSContext s = null;\n\tList\\<? extends AContext> a = s.a();\n\tList\\<? extends BContext> b = s.b();\n}\n>>\n\nDeclare_foo() ::= <<\n\tpublic void foo() {outStream.println(\"foo\");}\n>>\n\nInvoke_foo() ::= \"foo();\"\n\nDeclare_pred() ::= <<boolean pred(boolean v) {\n\toutStream.println(\"eval=\"+v);\n\treturn v;\n}\n>>\n\nInvoke_pred(v) ::= <<this.pred(<v>)>>\n\nParserTokenType(t) ::= \"Parser.<t>\"\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>()\"\nStringType() ::= \"String\"\nContextMember(ctx, member) ::= \"<ctx>.<member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>.<local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>.<member>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/JavaScript.test.stg",
    "content": "writeln(s) ::= <<console.log(<s> || '');>>\nwrite(s) ::= <<process.stdout.write(<s> || '');>>\nwriteList(s) ::= <<console.log(<s; separator=\"+\">);>>\n\nFalse() ::= \"false\"\n\nTrue() ::= \"true\"\n\nNot(v) ::= \"!<v>\"\n\nAssert(s) ::= <<console.assert(<s>);>>\n\nCast(t,v) ::= \"<v>\"\n\nAppend(a,b) ::= \"<a> + <b>\"\n\nAppendStr(a,b) ::= <%<Append(a,b)>%>\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= <<if ( !(<v> instanceof Array) ) {throw \"value is not an array\";}>>\n\nAssignLocal(s,v) ::= \"<s> = <v>;\"\n\nInitIntMember(n,v) ::= <%this.<n> = <v>;%>\n\nInitBooleanMember(n,v) ::= <%this.<n> = <v>;%>\n\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\n\nIntArg(n) ::= \"<n>\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%this.<n>%>\n\nSetMember(n,v) ::= <%this.<n> = <v>;%>\n\nAddMember(n,v) ::= <%this.<n> += <v>;%>\n\nMemberEquals(n,v) ::= <%this.<n> === <v>%>\n\nModMemberEquals(n,m,v) ::= <%this.<n> % <m> === <v>%>\n\nModMemberNotEquals(n,m,v) ::= <%this.<n> % <m> != <v>%>\n\nDumpDFA() ::= \"this.dumpDFA();\"\n\nPass() ::= \"\"\n\nStringList() ::= \"list\"\n\nBuildParseTrees() ::= \"this.buildParseTrees = true;\"\n\nBailErrorStrategy() ::= <%this._errHandler = new antlr4.error.BailErrorStrategy();%>\n\nToStringTree(s) ::= <%<s>.toStringTree(null, this)%>\n\nColumn() ::= \"this.column\"\n\nText() ::= \"this.text\"\n\nValEquals(a,b) ::= <%<a>===<b>%>\n\nTextEquals(a) ::= <%this.text===\"<a>\"%>\n\nPlusText(a) ::= <%\"<a>\" + this.text%>\n\nInputText() ::= \"this._input.getText()\"\n\nLTEquals(i, v) ::= <%this._input.LT(<i>).text===<v>%>\n\nLANotEquals(i, v) ::= <%this._input.LA(<i>)!=<v>%>\n\nTokenStartColumnEquals(i) ::= <%this._tokenStartColumn===<i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"this.getExpectedTokens().toString(this.literalNames)\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"antlr4.Utils.arrayToString(this.getRuleInvocationStack())\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<this._interp.predictionMode = antlr4.atn.PredictionMode.LL_EXACT_AMBIG_DETECTION;>>\n\nParserToken(parser, token) ::= <%<parser>.<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\nthis.Property = function() {\n    return true;\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>.<call>\"\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\n\nPositionAdjustingLexer.prototype.resetAcceptPosition = function(index, line, column) {\n\tthis._input.seek(index);\n\tthis.line = line;\n\tthis.column = column;\n\tthis._interp.consume(this._input);\n};\n\nPositionAdjustingLexer.prototype.nextToken = function() {\n\tif (!(\"resetAcceptPosition\" in this._interp)) {\n\t\tvar lexer = this;\n\t\tthis._interp.resetAcceptPosition = function(index, line, column) { lexer.resetAcceptPosition(index, line, column); };\n\t}\n\treturn antlr4.Lexer.prototype.nextToken.call(this);\n};\n\nPositionAdjustingLexer.prototype.emit = function() {\n\tswitch(this._type) {\n\tcase PositionAdjustingLexer.TOKENS:\n\t\tthis.handleAcceptPositionForKeyword(\"tokens\");\n\t\tbreak;\n\tcase PositionAdjustingLexer.LABEL:\n\t\tthis.handleAcceptPositionForIdentifier();\n\t\tbreak;\n\t}\n\treturn antlr4.Lexer.prototype.emit.call(this);\n};\n\nPositionAdjustingLexer.prototype.handleAcceptPositionForIdentifier = function() {\n\tvar tokenText = this.text;\n\tvar identifierLength = 0;\n\twhile (identifierLength \\< tokenText.length &&\n\t\tPositionAdjustingLexer.isIdentifierChar(tokenText[identifierLength])\n\t) {\n\t\tidentifierLength += 1;\n\t}\n\tif (this._input.index > this._tokenStartCharIndex + identifierLength) {\n\t\tvar offset = identifierLength - 1;\n\t\tthis._interp.resetAcceptPosition(this._tokenStartCharIndex + offset,\n\t\t\t\tthis._tokenStartLine, this._tokenStartColumn + offset);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n};\n\nPositionAdjustingLexer.prototype.handleAcceptPositionForKeyword = function(keyword) {\n\tif (this._input.index > this._tokenStartCharIndex + keyword.length) {\n\t\tvar offset = keyword.length - 1;\n\t\tthis._interp.resetAcceptPosition(this._tokenStartCharIndex + offset,\n\t\t\tthis._tokenStartLine, this._tokenStartColumn + offset);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n};\n\nPositionAdjustingLexer.isIdentifierChar = function(c) {\n\treturn c.match(/^[0-9a-zA-Z_]+$/);\n}\n\n>>\n\nBasicListener(X) ::= <<\n@parser::members {\nthis.LeafListener = function() {\n    this.visitTerminal = function(node) {\n    \tconsole.log(node.symbol.text);\n    };\n    return this;\n};\nthis.LeafListener.prototype = Object.create(<X>Listener.prototype);\nthis.LeafListener.prototype.constructor = this.LeafListener;\n}\n>>\n\nWalkListener(s) ::= <<\nvar walker = new antlr4.tree.ParseTreeWalker();\nwalker.walk(new this.LeafListener(), <s>);\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::header {\nclass MyRuleNode extends antlr4.ParserRuleContext {\n    constructor(parent, invokingState) {\n        super(parent, invokingState);\n        this.altNum = 0;\n    }\n\n    getAltNumber() {\n        return this.altNum;\n    }\n\n    setAltNumber(altNumber){\n        this.altNum = altNumber;\n    }\n};\n\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::members {\nthis.LeafListener = function() {\n    this.exitA = function(ctx) {\n    \tvar str;\n        if(ctx.getChildCount()===2) {\n            str = ctx.INT(0).symbol.text + ' ' + ctx.INT(1).symbol.text + ' ' + antlr4.Utils.arrayToString(ctx.INT());\n        } else {\n            str = ctx.ID().symbol.toString();\n        }\n    \tconsole.log(str);\n    };\n    return this;\n};\nthis.LeafListener.prototype = Object.create(<X>Listener.prototype);\nthis.LeafListener.prototype.constructor = this.LeafListener;\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::members {\nthis.LeafListener = function() {\n    this.exitA = function(ctx) {\n    \tvar str;\n        if(ctx.getChildCount()===2) {\n            str = ctx.b(0).start.text + ' ' + ctx.b(1).start.text + ' ' + ctx.b()[0].start.text;\n        } else {\n            str = ctx.b(0).start.text;\n        }\n    \tconsole.log(str);\n    };\n    return this;\n};\nthis.LeafListener.prototype = Object.create(<X>Listener.prototype);\nthis.LeafListener.prototype.constructor = this.LeafListener;\n}\n>>\n\nLRListener(X) ::= <<\n@parser::members {\nthis.LeafListener = function() {\n    this.exitE = function(ctx) {\n    \tvar str;\n        if(ctx.getChildCount()===3) {\n            str = ctx.e(0).start.text + ' ' + ctx.e(1).start.text + ' ' + ctx.e()[0].start.text;\n        } else {\n            str = ctx.INT().symbol.text;\n        }\n    \tconsole.log(str);\n    };\n    return this;\n};\nthis.LeafListener.prototype = Object.create(<X>Listener.prototype);\nthis.LeafListener.prototype.constructor = this.LeafListener;\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::members {\nthis.LeafListener = function() {\n    this.exitCall = function(ctx) {\n    \tvar str = ctx.e().start.text + ' ' + ctx.eList();\n    \tconsole.log(str);\n    };\n    this.exitInt = function(ctx) {\n        var str = ctx.INT().symbol.text;\n        console.log(str);\n    };\n    return this;\n};\nthis.LeafListener.prototype = Object.create(<X>Listener.prototype);\nthis.LeafListener.prototype.constructor = this.LeafListener;\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\n\tfunction foo() {\n\t\tvar s = new SContext();\n\t    var a = s.a();\n\t    var b = s.b();\n    };\n>>\n\nDeclare_foo() ::= \"this.foo = function() {console.log('foo');};\"\n\nInvoke_foo() ::= \"this.foo();\"\n\nDeclare_pred() ::= <<this.pred = function(v) {\n\tconsole.log(\"eval=\" + v.toString());\n\treturn v;\n};\n>>\n\nInvoke_pred(v) ::= <<this.pred(<v>)>>\nParserTokenType(t) ::= \"Parser.<t>\"\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>_list()\"\nStringType() ::= \"String\"\nContextMember(ctx, member) ::= \"<ctx>.<member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>.<local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>.<member>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/PHP.test.stg",
    "content": "writeln(s) ::= <<echo <s> . \\PHP_EOL;>>\nwrite(s) ::= <<echo <s>;>>\nwriteList(s) ::= <<echo <s; separator=\".\">;>>\n\nFalse() ::= \"false\"\nTrue() ::= \"true\"\nNot(v) ::= \"!<v>\"\nAssert(s) ::= <<assert(<s>);>>\nCast(t,v) ::= \"<v>\"\nAppend(a,b) ::= \"<a> . <b>\"\nAppendStr(a,b) ::= <%<Append(a,b)>%>\nConcat(a,b) ::= \"<a><b>\"\n\nDeclareLocal(s,v) ::= \"<s> = <v>;\"\n\nAssertIsList(v) ::= \"assert(\\is_array(<v>));\" // just use static type system\nAssignLocal(s,v) ::= \"<s> = <v>;\"\n\nInitIntMember(n,v) ::= <%public \\$<n> = <v>;%>\nInitBooleanMember(n,v) ::= <%public \\$<n> = <v>;%>\nInitIntVar(n,v) ::= <%\\$<n> = <v>;%>\nIntArg(n) ::= \"int <n>\"\nVarRef(n) ::= \"$<n>\"\n\nGetMember(n) ::= <%\\$this-><n>%>\nSetMember(n,v) ::= <%\\$this-><n> = <v>;%>\nAddMember(n,v) ::= <%\\$this-><n> += <v>;%>\nPlusMember(v,n) ::= <%<v> + \\$this-><n>%>\nMemberEquals(n,v) ::= <%\\$this-><n> == <v>%>\nModMemberEquals(n,m,v) ::= <%\\$this-><n> % <m> == <v>%>\nModMemberNotEquals(n,m,v) ::= <%\\$this-><n> % <m> !== <v>%>\n\nDumpDFA() ::= \"\\$this->dumpDFA();\"\nPass() ::= \"\"\n\nStringList() ::= \"\"\nBuildParseTrees() ::= \"\\$this->setBuildParseTree(true);\"\nBailErrorStrategy() ::= <%\\$this->setErrorHandler(new Antlr\\\\Antlr4\\\\Runtime\\\\Error\\\\BailErrorStrategy());%>\n\nToStringTree(s) ::= <%<s>->toStringTree(\\$this->getRuleNames())%>\nColumn() ::= \"\\$this->getCharPositionInLine()\"\nText() ::= \"\\$this->getText()\"\nValEquals(a,b) ::= <%<a>===<b>%>\nTextEquals(a) ::= <%\\$this->getText() === \"<a>\"%>\nPlusText(a) ::= <%\"<a>\" . \\$this->getText()%>\nInputText() ::= \"\\$this->input->getText()\"\nLTEquals(i, v) ::= <%\\$this->input->LT(<i>)->getText() === <v>%>\nLANotEquals(i, v) ::= <%\\$this->input->LA(<i>) !== <v>%>\nTokenStartColumnEquals(i) ::= <%\\$this->tokenStartCharPositionInLine === <i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"\\$this->getExpectedTokens()->toStringVocabulary(\\$this->getVocabulary())\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"'[' . \\implode(', ', \\$this->getRuleInvocationStack()) . ']'\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<\\$this->interp->setPredictionMode(Antlr\\\\Antlr4\\\\Runtime\\\\Atn\\\\PredictionMode::LL_EXACT_AMBIG_DETECTION);>>\n\n\nParserToken(parser, token) ::= <%<parser>::<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\npublic function Property() : bool\n{\n\treturn true;\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>-><call>\"\n\nPositionAdjustingLexerDef() ::= <<\nclass PositionAdjustingLexerATNSimulator extends LexerATNSimulator {\n\tpublic function resetAcceptPosition(CharStream \\$input, int \\$index, int \\$line, int \\$charPositionInLine) : void {\n\t\t\\$input->seek(\\$index);\n\t\t\\$this->line = \\$line;\n\t\t\\$this->charPositionInLine = \\$charPositionInLine;\n\t\t\\$this->consume(\\$input);\n\t}\n}\n>>\n\nPositionAdjustingLexer() ::= <<\npublic function nextToken() : Antlr\\\\Antlr4\\\\Runtime\\\\Token\n{\n\tif (!\\$this->interp instanceof PositionAdjustingLexerATNSimulator) {\n\t\t\\$this->interp = new PositionAdjustingLexerATNSimulator(\\$this, self::\\$atn, self::\\$decisionToDFA, self::\\$sharedContextCache);\n\t}\n\n\treturn parent::nextToken();\n}\n\npublic function emit() : Antlr\\\\Antlr4\\\\Runtime\\\\Token\n{\n\tswitch (\\$this->type) {\n\tcase self::TOKENS:\n\t\t\\$this->handleAcceptPositionForKeyword('tokens');\n\t\tbreak;\n\n\tcase self::LABEL:\n\t\t\\$this->handleAcceptPositionForIdentifier();\n\t\tbreak;\n\t}\n\n\treturn parent::emit();\n}\n\nprivate function handleAcceptPositionForIdentifier() : bool\n{\n\t\\$tokenText = \\$this->getText();\n\t\\$identifierLength = 0;\n\twhile (\\$identifierLength \\< \\strlen(\\$tokenText) && self::isIdentifierChar(\\$tokenText[\\$identifierLength])) {\n\t\t\\$identifierLength++;\n\t}\n\n\tif (\\$this->getInputStream()->getIndex() > \\$this->tokenStartCharIndex + \\$identifierLength) {\n\t\t\\$offset = \\$identifierLength - 1;\n\t\t\\$this->getInterpreter()->resetAcceptPosition(\\$this->getInputStream(), \\$this->tokenStartCharIndex + \\$offset, \\$this->tokenStartLine, \\$this->tokenStartCharPositionInLine + \\$offset);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nprivate function handleAcceptPositionForKeyword(string \\$keyword) : bool\n{\n\tif (\\$this->getInputStream()->getIndex() > \\$this->tokenStartCharIndex + \\strlen(\\$keyword)) {\n\t\t\\$offset = \\strlen(\\$keyword) - 1;\n\t\t\\$this->getInterpreter()->resetAcceptPosition(\\$this->getInputStream(), \\$this->tokenStartCharIndex + \\$offset, \\$this->tokenStartLine, \\$this->tokenStartCharPositionInLine + \\$offset);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nprivate static function isIdentifierChar(string \\$c) : bool\n{\n\treturn \\ctype_alnum(\\$c) || \\$c === '_';\n}\n>>\n\nBasicListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener\n{\n\tpublic function visitTerminal(Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\TerminalNode \\$node) : void\n\t{\n\t\techo \\$node->getSymbol()->getText() . \\PHP_EOL;\n\t}\n}\n}\n>>\n\nWalkListener(s) ::= <<\n\\$walker = new Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\ParseTreeWalker();\n\\$walker->walk(new LeafListener(), <s>);\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::contexts {\nclass MyRuleNode extends ParserRuleContext\n{\n\tpublic \\$altNum;\n\n\tpublic function getAltNumber() : int\n\t{\n\t\treturn \\$this->altNum;\n\t}\n\n\tpublic function setAltNumber(int \\$altNum) : void\n\t{\n\t\t\\$this->altNum = \\$altNum;\n\t}\n}\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n\tpublic function exitA(Context\\\\AContext \\$ctx) : void {\n\t\tif (\\$ctx->getChildCount() === 2) {\n\t\t\techo \\sprintf('%s %s [%s]',\\$ctx->INT(0)->getSymbol()->getText(), \\$ctx->INT(1)->getSymbol()->getText(), \\implode(', ', \\$ctx->INT())) . \\PHP_EOL;\n\t\t} else {\n\t\t\techo \\$ctx->ID()->getSymbol() . \\PHP_EOL;\n\t\t}\n\t}\n}\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n\tpublic function exitA(Context\\\\AContext \\$ctx) : void\n\t{\n\t\tif (\\$ctx->getChildCount() === 2) {\n\t\t\techo \\sprintf('%s %s %s', \\$ctx->b(0)->start->getText(), \\$ctx->b(1)->start->getText(),\\$ctx->b()[0]->start->getText()) . \\PHP_EOL;\n\t\t} else {\n\t\t\techo \\$ctx->b(0)->start->getText() . \\PHP_EOL;\n\t\t}\n\t}\n}\n}\n>>\n\n\nLRListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener {\n\tpublic function exitE(Context\\\\EContext \\$ctx) : void\n\t{\n\t\tif (\\$ctx->getChildCount() === 3) {\n\t\t\techo \\sprintf('%s %s %s', \\$ctx->e(0)->start->getText(), \\$ctx->e(1)->start->getText(), \\$ctx->e()[0]->start->getText()) . \\PHP_EOL;\n\t\t} else {\n\t\t\techo \\$ctx->INT()->getSymbol()->getText() . \\PHP_EOL;\n\t\t}\n\t}\n}\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::definitions {\nclass LeafListener extends TBaseListener\n{\n\tpublic function exitCall(Context\\\\CallContext \\$ctx) : void {\n\t\techo \\sprintf('%s %s',\\$ctx->e()->start->getText(),\\$ctx->eList()) . \\PHP_EOL;\n\t}\n\n\tpublic function exitInt(Context\\\\IntContext \\$ctx) : void {\n\t\techo \\$ctx->INT()->getSymbol()->getText() . \\PHP_EOL;\n\t}\n}\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\npublic function foo() : void {\n\t\\$s = null;\n\t\\$a = \\$s->a();\n\t\\$b = \\$s->b();\n}\n>>\n\nDeclare_foo() ::= <<\npublic function foo() : void {\n\techo 'foo' . \\PHP_EOL;\n}\n>>\n\nInvoke_foo() ::= \"\\$this->foo();\"\n\nDeclare_pred() ::= <<public function pred(bool \\$v) : bool {\n\techo \"eval=\".(\\$v ? 'true' : 'false') . \\PHP_EOL;\n\treturn \\$v;\n}\n>>\n\nInvoke_pred(v) ::= \"\\$this->pred(<v>)\"\n\nParserTokenType(t) ::= \"Parser::<t>\"\nContextRuleFunction(ctx, rule) ::= \"<ctx>-><rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>-><rule>()\"\nStringType() ::= \"\"\nContextMember(ctx, member) ::= \"<ctx>-><member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>-><subctx>-><local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>-><subctx>-><member>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python3.test.stg",
    "content": "writeln(s) ::= <<print(<s>, file=self._output)>>\nwrite(s) ::= <<print(<s>,end='',file=self._output)>>\nwriteList(s) ::= <<print(<s: {v | str(<v>)}; separator=\"+\">, file=self._output)>>\n\nFalse() ::= \"False\"\n\nTrue() ::= \"True\"\n\nNot(v) ::= \"not <v>\"\n\nAssert(s) ::= \"\"\n\nCast(t,v) ::= \"<v>\"\n\nAppend(a,b) ::= \"<a> + str(<b>)\"\n\nAppendStr(a,b) ::= \"<a> + <b>\"\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= \"assert isinstance(<v>, (list, tuple))\"\n\nAssignLocal(s,v) ::= \"<s> = <v>\"\n\nInitIntMember(n,v) ::= <%<n> = <v>%>\n\nInitBooleanMember(n,v) ::= <%<n> = <v>%>\n\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\n\nIntArg(n) ::= \"<n>\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%self.<n>%>\n\nSetMember(n,v) ::= <%self.<n> = <v>%>\n\nAddMember(n,v) ::= <%self.<n> += <v>%>\n\nMemberEquals(n,v) ::= <%self.<n> == <v>%>\n\nModMemberEquals(n,m,v) ::= <%self.<n> % <m> == <v>%>\n\nModMemberNotEquals(n,m,v) ::= <%self.<n> % <m> != <v>%>\n\nDumpDFA() ::= \"self.dumpDFA()\"\n\nPass() ::= \"pass\"\n\nStringList() ::= \"\"\n\nBuildParseTrees() ::= \"self._buildParseTrees = True\"\n\nBailErrorStrategy() ::= <%self._errHandler = BailErrorStrategy()%>\n\nToStringTree(s) ::= <%<s>.toStringTree(recog=self)%>\n\nColumn() ::= \"self.column\"\n\nText() ::= \"self.text\"\n\nValEquals(a,b) ::= <%<a>==<b>%>\n\nTextEquals(a) ::= <%self.text==\"<a>\"%>\n\nPlusText(a) ::= <%\"<a>\" + self.text%>\n\nInputText() ::= \"self._input.getText()\"\n\nLTEquals(i, v) ::= <%self._input.LT(<i>).text==<v>%>\n\nLANotEquals(i, v) ::= <%self._input.LA(<i>)!=<v>%>\n\nTokenStartColumnEquals(i) ::= <%self._tokenStartColumn==<i>%>\n\nImportListener(X) ::= <<\n@parser::header {\nclass MockListener:\n    pass\n}\n>>\n\nGetExpectedTokenNames() ::= \"self.getExpectedTokens().toString(self.literalNames, self.symbolicNames)\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"str_list(self.getRuleInvocationStack())\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<self._interp.predictionMode =  PredictionMode.LL_EXACT_AMBIG_DETECTION>>\n\nParserToken(parser, token) ::= <%<parser>.<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\ndef Property(self):\n    return True\n\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>.<call>\"\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\n\ndef resetAcceptPosition(self, index, line, column):\n\tself._input.seek(index)\n\tself.line = line\n\tself.column = column\n\tself._interp.consume(self._input)\n\ndef nextToken(self):\n\tif self._interp.__dict__.get(\"resetAcceptPosition\", None) is None:\n\t\tself._interp.__dict__[\"resetAcceptPosition\"] = self.resetAcceptPosition\n\treturn super(type(self),self).nextToken()\n\ndef emit(self):\n\tif self._type==PositionAdjustingLexer.TOKENS:\n\t\tself.handleAcceptPositionForKeyword(\"tokens\")\n\telif self._type==PositionAdjustingLexer.LABEL:\n\t\tself.handleAcceptPositionForIdentifier()\n\treturn super(type(self),self).emit()\n\ndef handleAcceptPositionForIdentifier(self):\n\ttokenText = self.text\n\tidentifierLength = 0\n\twhile identifierLength \\< len(tokenText) and self.isIdentifierChar(tokenText[identifierLength]):\n\t\tidentifierLength += 1\n\n\tif self._input.index > self._tokenStartCharIndex + identifierLength:\n\t\toffset = identifierLength - 1\n\t\tself._interp.resetAcceptPosition(self._tokenStartCharIndex + offset,\n\t\t\t\tself._tokenStartLine, self._tokenStartColumn + offset)\n\t\treturn True\n\telse:\n\t\treturn False\n\n\ndef handleAcceptPositionForKeyword(self, keyword):\n\tif self._input.index > self._tokenStartCharIndex + len(keyword):\n\t\toffset = len(keyword) - 1\n\t\tself._interp.resetAcceptPosition(self._tokenStartCharIndex + offset,\n\t\t\tself._tokenStartLine, self._tokenStartColumn + offset)\n\t\treturn True\n\telse:\n\t\treturn False\n\n@staticmethod\ndef isIdentifierChar(c):\n\treturn c.isalnum() or c == '_'\n\n>>\n\nBasicListener(X) ::= <<\n@parser::members {\nclass LeafListener(MockListener):\n    def __init__(self, output):\n        self._output = output\n    def visitTerminal(self, node):\n        print(node.symbol.text, file=self._output)\n}\n>>\n\nWalkListener(s) ::= <<\nif \".\" in __name__:\n    from .TListener import TListener\nelse:\n    from TListener import TListener\nTParser.LeafListener.__bases__ = (TListener,)\nwalker = ParseTreeWalker()\nwalker.walk(TParser.LeafListener(self._output), <s>)\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::members {\nclass MyRuleNode(ParserRuleContext):\n    def __init__(self, parent:ParserRuleContext = None, invokingStateNumber:int = None ):\n        super(<X>Parser.MyRuleNode, self).__init__(parent, invokingStateNumber)\n        self.altNum = 0;\n    def getAltNumber(self):\n        return self.altNum\n    def setAltNumber(self, altNum):\n        self.altNum = altNum\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::members {\nclass LeafListener(MockListener):\n    def __init__(self, output):\n        self._output = output\n    def exitA(self, ctx):\n        if ctx.getChildCount()==2:\n            print(ctx.INT(0).symbol.text + ' ' + ctx.INT(1).symbol.text + ' ' + str_list(ctx.INT()), file=self._output)\n        else:\n            print(str(ctx.ID().symbol), file=self._output)\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::members {\nclass LeafListener(MockListener):\n    def __init__(self, output):\n        self._output = output\n    def exitA(self, ctx):\n        if ctx.getChildCount()==2:\n            print(ctx.b(0).start.text + ' ' + ctx.b(1).start.text + ' ' + ctx.b()[0].start.text, file=self._output)\n        else:\n            print(ctx.b(0).start.text, file=self._output)\n}\n>>\n\n\nLRListener(X) ::= <<\n@parser::members {\nclass LeafListener(MockListener):\n    def __init__(self, output):\n        self._output = output\n    def exitE(self, ctx):\n        if ctx.getChildCount()==3:\n            print(ctx.e(0).start.text + ' ' + ctx.e(1).start.text + ' ' + ctx.e()[0].start.text, file=self._output)\n        else:\n            print(ctx.INT().symbol.text, file=self._output)\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::members {\nclass LeafListener(MockListener):\n    def __init__(self, output):\n        self._output = output\n    def exitCall(self, ctx):\n        print(ctx.e().start.text + ' ' + str(ctx.eList()), file=self._output)\n    def exitInt(self, ctx):\n        print(ctx.INT().symbol.text, file=self._output)\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\ndef foo():\n    s = SContext()\n    a = s.a()\n    b = s.b()\n>>\n\nDeclare_foo() ::= <<def foo(self):\n\tprint('foo', file=self._output)\n>>\n\nInvoke_foo() ::= \"self.foo()\"\n\nDeclare_pred() ::= <<def pred(self, v):\n\tprint('eval=' + str(v).lower(), file=self._output)\n\treturn v\n\n>>\n\nInvoke_pred(v) ::= <<self.pred(<v>)>>\nParserTokenType(t) ::= \"Parser.<t>\"\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>_list()\"\nStringType() ::= \"String\"\nContextMember(ctx, member) ::= \"<ctx>.<member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>.<local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>.<member>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Swift.test.stg",
    "content": "writeln(s) ::= <<print((<s>) ?? \"nil\")>>\n\nwrite(s) ::= <<print((<s>) ?? \"nil\", terminator: \"\")>>\n\nFalse() ::= \"false\"\n\nTrue() ::= \"true\"\n\nNot(v) ::= \"!<v>\"\n\nAssert(s) ::= \"\"\n\nCast(t,v) ::= \"((<v> as! <t>))\"\n\nAppend(a,b) ::= \"<a> + <b>\"\n\nAppendStr(a,b) ::= <%<Append(a,b)>%>\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= \"var __ttt__ = <v>;\" // just use static type system\n\nAssignLocal(s,v) ::= \"<s> = <v>\"\n\nInitIntMember(n,v) ::= <%var <n> = <v>%>\n\nInitBooleanMember(n,v) ::= <%var <n> = <v>%>\n\nInitIntVar(n,v) ::= <%<InitIntMember(n,v)>%>\n\nIntArg(n) ::= \"int <n>\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%self.<n>%>\n\nSetMember(n,v) ::= <%self.<n> = <v>%>\n\nAddMember(n,v) ::= <%self.<n> += <v>%>\n\nMemberEquals(n,v) ::= <%self.<n> == <v>%>\n\nModMemberEquals(n,m,v) ::= <%self.<n> % <m> == <v>%>\n\nModMemberNotEquals(n,m,v) ::= <%self.<n> % <m> != <v>%>\n\nDumpDFA() ::= \"self.dumpDFA()\"\n\nPass() ::= \"\"\n\nStringList() ::= \"Array\\<String>\"\n\nBuildParseTrees() ::= \"setBuildParseTree(true)\"\n\nBailErrorStrategy() ::= <%setErrorHandler(BailErrorStrategy())%>\n\nToStringTree(s) ::= <%<s>.toStringTree(self)%>\n\nColumn() ::= \"self.getCharPositionInLine()\"\n\nText() ::= \"self.getText()\"\n\nValEquals(a,b) ::= <%<a>==<b>%>\n\nTextEquals(a) ::= <%self.getText() == \"<a>\"%>\n\nPlusText(a) ::= <%\"<a>\" + self.getText()%>\n\nInputText() ::= \"try self._input.getText()\"\n\nLTEquals(i, v) ::= <%try self._input.LT(<i>)?.getText() == <v>%>\n\nLANotEquals(i, v) ::= <%try self._input.LA(<i>) != <v>%>\n\nTokenStartColumnEquals(i) ::= <%self._tokenStartCharPositionInLine == <i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"try self.getExpectedTokens().toString(self.getVocabulary())\"\n\nImportRuleInvocationStack() ::= \"\"\n\nRuleInvocationStack() ::= \"getRuleInvocationStack().description.replacingOccurrences(of: \\\"\\\\\\\"\\\", with: \\\"\\\")\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<_interp.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);>>\n\nParserToken(parser, token) ::= <%<parser>.Tokens.<token>.rawValue%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\nfunc Property() -> Bool {\n  return true\n}\n}\n>>\n\nParserPropertyCall(parser, property) ::= <<\n<parser>.<property>\n>>\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\n\noverride\nopen func nextToken() throws -> Token {\n\tif (!(_interp is PositionAdjustingLexerATNSimulator)) {\n\t\t_interp = PositionAdjustingLexerATNSimulator(self, PositionAdjustingLexer._ATN, PositionAdjustingLexer._decisionToDFA, PositionAdjustingLexer._sharedContextCache)\n\t}\n\n\treturn try super.nextToken()\n}\n\noverride\nopen func emit() -> Token  {\n\tswitch (_type) {\n\tcase PositionAdjustingLexer.TOKENS:\n\t\thandleAcceptPositionForKeyword(\"tokens\")\n\tcase PositionAdjustingLexer.LABEL:\n\t\thandleAcceptPositionForIdentifier()\n\tdefault:\n\t\tbreak\n\t}\n\treturn super.emit()\n}\n\nprivate func handleAcceptPositionForIdentifier() -> Bool {\n\tlet tokenText = getText()\n\tvar identifierLength = 0\n\twhile ((identifierLength \\< tokenText.count)  &&  isIdentifierChar(tokenText[tokenText.index(tokenText.startIndex, offsetBy: identifierLength)])) {\n\t\tidentifierLength += 1\n\t}\n\n\tif (getInputStream()!.index() > _tokenStartCharIndex + identifierLength) {\n\t\tlet offset = identifierLength - 1\n\t\t(getInterpreter() as! PositionAdjustingLexerATNSimulator).resetAcceptPosition(getInputStream()!, _tokenStartCharIndex + offset, _tokenStartLine, _tokenStartCharPositionInLine + offset)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nprivate func handleAcceptPositionForKeyword(_ keyword:String) -> Bool  {\n\tif getInputStream()!.index() > _tokenStartCharIndex + keyword.count {\n\t\tlet offset = keyword.count - 1\n\t\t(getInterpreter() as! PositionAdjustingLexerATNSimulator).resetAcceptPosition(getInputStream()!, _tokenStartCharIndex + offset, _tokenStartLine, _tokenStartCharPositionInLine + offset)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\n//public func getInterpreter() -> PositionAdjustingLexerATNSimulator {\n//\treturn super.getInterpreter() as! PositionAdjustingLexerATNSimulator\n//}\n\nprivate  func isIdentifierChar(_ c: Character) -> Bool  {\n\treturn (c >= \"0\" && c \\<= \"9\") || (c >= \"a\" && c \\<= \"z\") || c >= \"A\" && c \\<= \"Z\" || c == \"_\"\n}\n\nclass PositionAdjustingLexerATNSimulator: LexerATNSimulator {\n\n\t  init(_ recog: Lexer,_ atn: ATN,\n\t\t\t\t _ decisionToDFA: [DFA],\n\t\t\t\t _ sharedContextCache:PredictionContextCache)\n\t{\n\t\tsuper.init(recog, atn, decisionToDFA, sharedContextCache)\n\t}\n\n   func resetAcceptPosition(_ input: CharStream,_ index: Int,_ line: Int,_ charPositionInLine: Int) {\n\t\ttry! input.seek(index)\n\t\tself.line = line\n\t\tself.charPositionInLine = charPositionInLine\n\t\ttry! consume(input)\n\t}\n\n}\n\n>>\n\nBasicListener(X) ::= <<\n@parser::members {\nopen class LeafListener: TBaseListener {\n    override\n\topen func visitTerminal(_ node: TerminalNode) {\n\t\tprint(node.getSymbol()?.getText() ?? \"\")\n\t}\n}\n}\n>>\n\nWalkListener(s) ::= <<\nlet walker =  ParseTreeWalker()\ntry! walker.walk(LeafListener(), <s>)\n>>\n\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::members {\nopen class MyRuleNode: ParserRuleContext {\n\tpublic var altNum: Int = 0\n    override\n\tpublic init(_ parent: ParserRuleContext?, _ invokingStateNumber: Int) {\n        super.init(parent, invokingStateNumber)\n    }\n    override\n\topen func getAltNumber() -> Int { return altNum }\n\n\toverride\n\topen func setAltNumber(_ altNum: Int) { self.altNum = altNum }\n}\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::members {\nopen class LeafListener: TBaseListener {\n    override\n\topen func exitA(_ ctx: TParser.AContext) {\n\t\tif (ctx.getChildCount() == 2) {\n\t\t\tprint(\"\\(ctx.INT(0)?.getSymbol()?.getText() ?? \"\") \\(ctx.INT(1)?.getSymbol()?.getText() ?? \"\") \\(ctx.INT())\")\n\t\t}\n\t\telse {\n\t\t\tprint(ctx.ID()?.getSymbol() ?? \"\")\n\t\t}\n\t}\n}\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::members {\nopen class LeafListener: TBaseListener {\n    override\n\topen func exitA(_ ctx: TParser.AContext) {\n\t\tif (ctx.getChildCount() == 2) {\n\t\t\tprint(\"\\(ctx.b(0)?.start?.getText() ?? \"\") \\(ctx.b(1)?.start?.getText() ?? \"\") \\(ctx.b()[0].start?.getText() ?? \"\")\")\n\t\t} else {\n\t\t\tprint(ctx.b(0)?.start?.getText() ?? \"\")\n\t\t}\n\t}\n}\n}\n>>\n\n\nLRListener(X) ::= <<\n@parser::members {\nopen class LeafListener: TBaseListener {\n    override\n\topen func exitE(_ ctx: TParser.EContext) {\n\t\tif (ctx.getChildCount() == 3) {\n\t\t    print(\"\\(ctx.e(0)?.start?.getText() ?? \"\") \\(ctx.e(1)?.start?.getText() ?? \"\") \\(ctx.e()[0].start?.getText() ?? \"\")\")\n\t\t} else {\n\t\t\tprint(ctx.INT()?.getSymbol()?.getText() ?? \"\")\n\t   }\n\t}\n}\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::members {\nopen class LeafListener: TBaseListener {\n    override\n\topen func exitCall(_ ctx: TParser.CallContext) {\n\t\tprint(\"\\(ctx.e()?.start?.getText() ?? \"\") \\(ctx.eList()!)\")\n\t}\n\toverride\n\topen func exitInt(_ ctx: TParser.IntContext) {\n\t\tprint(ctx.INT()?.getSymbol()?.getText() ?? \"\")\n\t}\n}\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\nfunc foo() {\n\t//let s: SContext? = nil\n\t//let a: [AContext]? = s?.a()\n\t//let b: [BContext]? = s?.b()\n}\n>>\n\nDeclare_foo() ::= <<\n\tpublic func foo() {print(\"foo\")}\n>>\n\nInvoke_foo() ::= \"foo()\"\n\nDeclare_pred() ::= <<\nfunc pred(_ v: Bool) -> Bool {\n\tprint(\"eval=\\(v)\")\n\treturn v\n}\n>>\n\nStringType() ::= \"String\"\nInvoke_pred(v) ::= <<self.pred(<v>)>>\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>()\"\nContextMember(ctx, member) ::= \"<ctx>!.<member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>!.<local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>!.<member>\"\n"
  },
  {
    "path": "runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/TypeScript.test.stg",
    "content": "writeln(s) ::= <<console.log(<s>);>>\nwrite(s) ::= <<process.stdout.write(<s>);>>\nwriteList(s) ::= <<console.log(<s; separator=\"+\">);>>\n\nFalse() ::= \"false\"\n\nTrue() ::= \"true\"\n\nNot(v) ::= \"!<v>\"\n\nAssert(s) ::= <<console.assert(<s>);>>\n\nCast(t,v) ::= \"(<v> as <t>)\"\n\nAppend(a,b) ::= \"<a> + <b>\"\n\nAppendStr(a,b) ::= <%<Append(a,b)>%>\n\nConcat(a,b) ::= \"<a><b>\"\n\nAssertIsList(v) ::= <%if ( !(<v> instanceof Array) ) {throw \"value is not an array\";}%>\n\nAssignLocal(s,v) ::= \"<s> = <v>;\"\n\nInitIntMember(n,v) ::= <%<n> : number = <v>;%>\n\nInitBooleanMember(n,v) ::= <%<n> : boolean = <v>;%>\n\nInitIntVar(n,v) ::= <%let <n> : number = <v>;%>\n\nIntArg(n) ::= \"<n>: number\"\n\nVarRef(n) ::= \"<n>\"\n\nGetMember(n) ::= <%this.<n>%>\n\nSetMember(n,v) ::= <%this.<n> = <v>;%>\n\nAddMember(n,v) ::= <%this.<n> += <v>;%>\n\nMemberEquals(n,v) ::= <%this.<n> === <v>%>\n\nModMemberEquals(n,m,v) ::= <%this.<n> % <m> === <v>%>\n\nModMemberNotEquals(n,m,v) ::= <%this.<n> % <m> != <v>%>\n\nDumpDFA() ::= \"this.dumpDFA();\"\n\nPass() ::= \"\"\n\nStringList() ::= \"string[]\"\n\nBuildParseTrees() ::= \"this.buildParseTrees = true;\"\n\nBailErrorStrategy() ::= <%this._errHandler = new BailErrorStrategy();%>\n\nToStringTree(s) ::= <%<s>.toStringTree(null, this)%>\n\nColumn() ::= \"this.column\"\n\nText() ::= \"this.text\"\n\nValEquals(a,b) ::= <%<a>===<b>%>\n\nTextEquals(a) ::= <%this.text===\"<a>\"%>\n\nPlusText(a) ::= <%\"<a>\" + this.text%>\n\nInputText() ::= \"this._input.getText()\"\n\nLTEquals(i, v) ::= <%this._input.LT(<i>).text===<v>%>\n\nLANotEquals(i, v) ::= <%this._input.LA(<i>)!=<v>%>\n\nTokenStartColumnEquals(i) ::= <%this._tokenStartColumn===<i>%>\n\nImportListener(X) ::= \"\"\n\nGetExpectedTokenNames() ::= \"this.getExpectedTokens().toString(this.literalNames)\"\n\nImportRuleInvocationStack() ::= <<\n@parser::header {\n\timport { arrayToString } from 'antlr4';\n}>>\n\nRuleInvocationStack() ::= \"arrayToString(this.getRuleInvocationStack())\"\n\nLL_EXACT_AMBIG_DETECTION() ::= <<this._interp.predictionMode = PredictionMode.LL_EXACT_AMBIG_DETECTION;>>\n\nParserToken(parser, token) ::= <%<parser>.<token>%>\n\nProduction(p) ::= <%<p>%>\n\nResult(r) ::= <%<r>%>\n\nParserPropertyMember() ::= <<\n@members {\npublic Property() {\n    return true;\n}\n}\n>>\n\nParserPropertyCall(p, call) ::= \"<p>.<call>\"\n\nPositionAdjustingLexerDef() ::= \"\"\n\nPositionAdjustingLexer() ::= <<\n\nresetAcceptPosition (index: number, line: number, column: number) : void {\n\tthis._input.seek(index);\n\tthis.line = line;\n\tthis.column = column;\n\tthis._interp.consume(this._input);\n}\n\nemit () : any /* should be Token */ {\n\tswitch(this._type) {\n\tcase PositionAdjustingLexer.TOKENS:\n\t\tthis.handleAcceptPositionForKeyword(\"tokens\");\n\t\tbreak;\n\tcase PositionAdjustingLexer.LABEL:\n\t\tthis.handleAcceptPositionForIdentifier();\n\t\tbreak;\n\t}\n\treturn super.emit();\n}\n\nhandleAcceptPositionForIdentifier () : boolean {\n\tvar tokenText = this.text;\n\tvar identifierLength = 0;\n\twhile (identifierLength \\< tokenText.length && PositionAdjustingLexer.isIdentifierChar(tokenText[identifierLength])\n\t) {\n\t\tidentifierLength += 1;\n\t}\n\tif (this._input.index > this._tokenStartCharIndex + identifierLength) {\n\t\tvar offset = identifierLength - 1;\n\t\tthis.resetAcceptPosition(this._tokenStartCharIndex + offset,\n\t\t\t\tthis._tokenStartLine, this._tokenStartColumn + offset);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\nhandleAcceptPositionForKeyword (keyword: string) : boolean {\n\tif (this._input.index > this._tokenStartCharIndex + keyword.length) {\n\t\tvar offset = keyword.length - 1;\n\t\tthis.resetAcceptPosition(this._tokenStartCharIndex + offset,\n\t\t\tthis._tokenStartLine, this._tokenStartColumn + offset);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\nstatic isIdentifierChar (c: string) {\n\treturn c.match(/^[0-9a-zA-Z_]+$/);\n}\n\n>>\n\nBasicListener(X) ::= <<\n@parser::header {\nimport { ParseTreeWalker } from 'antlr4';\n\nclass LeafListener extends <X>Listener {\n\tvisitTerminal(node: TerminalNode) {\n\t\tconsole.log(node.symbol.text);\n\t}\n}\n\n}\n>>\n\nWalkListener(s) ::= <<\nvar walker = new ParseTreeWalker();\nwalker.walk(new LeafListener(), <s>);\n>>\n\nTreeNodeWithAltNumField(X) ::= <<\n@parser::header {\nclass MyRuleNode extends ParserRuleContext {\n\n    altNum: number;\n\n    constructor(parent?: ParserRuleContext, invokingState?: number) {\n        super(parent, invokingState);\n        this.altNum = 0;\n    }\n\n    getAltNumber(): number {\n        return this.altNum;\n    }\n\n    setAltNumber(altNumber: number){\n        this.altNum = altNumber;\n    }\n};\n\n}\n>>\n\nTokenGetterListener(X) ::= <<\n@parser::header {\nimport { arrayToString, ParseTreeWalker } from 'antlr4';\n\nclass LeafListener extends <X>Listener {\n\n\texitA? = (ctx: AContext) => {\n    \tvar str;\n        if(ctx.getChildCount()===2) {\n            str = ctx.INT(0).symbol.text + ' ' + ctx.INT(1).symbol.text + ' ' + arrayToString(ctx.INT_list());\n        } else {\n            str = ctx.ID()!.symbol.toString();\n        }\n    \tconsole.log(str);\n    };\n\n}\n\n}\n>>\n\nRuleGetterListener(X) ::= <<\n@parser::header {\nimport { ParseTreeWalker } from 'antlr4';\n\nclass LeafListener extends <X>Listener {\n\texitA? = (ctx: AContext) => {\n    \tvar str;\n        if(ctx.getChildCount()===2) {\n            str = ctx.b(0).start.text + ' ' + ctx.b(1).start.text + ' ' + ctx.b_list()[0].start.text;\n        } else {\n            str = ctx.b(0).start.text;\n        }\n    \tconsole.log(str);\n    };\n}\n\n}\n>>\n\nLRListener(X) ::= <<\n@parser::header {\nimport { ParseTreeWalker } from 'antlr4';\n\nclass LeafListener extends <X>Listener {\n\n\texitE? = (ctx: EContext) => {\n    \tvar str;\n        if(ctx.getChildCount()===3) {\n            str = ctx.e(0).start.text + ' ' + ctx.e(1).start.text + ' ' + ctx.e_list()[0].start.text;\n        } else {\n            str = ctx.INT()!.symbol.text;\n        }\n    \tconsole.log(str);\n    };\n}\n\n}\n>>\n\nLRWithLabelsListener(X) ::= <<\n@parser::header {\nimport { ParseTreeWalker } from 'antlr4';\n\nclass LeafListener extends <X>Listener {\n\n    exitCall? = (ctx: CallContext) => {\n    \tvar str = ctx.e().start.text + ' ' + ctx.eList();\n    \tconsole.log(str);\n    };\n\n    exitInt? = (ctx: IntContext) => {\n        var str = ctx.INT().symbol.text;\n        console.log(str);\n    }\n\n}\n\n}\n>>\n\nDeclareContextListGettersFunction() ::= <<\n\tfoo() {\n\t\tvar s = new SContext();\n\t    var a = s.a_list();\n\t    var b = s.b_list();\n    };\n>>\n\nDeclare_foo() ::= \"foo() {console.log('foo');}\"\n\nInvoke_foo() ::= \"this.foo();\"\n\nDeclare_pred() ::= <<\n\n\tpred(v: any) {\n\t\tconsole.log(\"eval=\" + v.toString());\n\t\treturn v;\n\t}\n>>\n\nInvoke_pred(v) ::= <<this.pred(<v>)>>\nParserTokenType(t) ::= \"Parser.<t>\"\nContextRuleFunction(ctx, rule) ::= \"<ctx>.<rule>\"\nContextListFunction(ctx, rule) ::= \"<ctx>.<rule>_list()\"\nStringType() ::= \"string | undefined\"\nContextMember(ctx, member) ::= \"<ctx>._<member>\"\nSubContextLocal(ctx, subctx, local) ::= \"<ctx>.<subctx>.<local>\"\nSubContextMember(ctx, subctx, member) ::= \"<ctx>.<subctx>._<member>\"\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/runtime/TestCodePointCharStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.runtime;\n\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class TestCodePointCharStream {\n\t@Test\n\tpublic void emptyBytesHasSize0() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\");\n\t\tassertEquals(0, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"\", s.toString());\n\t}\n\n\t@Test\n\tpublic void emptyBytesLookAheadReturnsEOF() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\");\n\t\tassertEquals(IntStream.EOF, s.LA(1));\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void consumingEmptyStreamShouldThrow() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\");\n\t\tIllegalStateException illegalStateException = assertThrows(\n\t\t\t\tIllegalStateException.class,\n\t\t\t\ts::consume\n\t\t);\n\t\tassertEquals(\"cannot consume EOF\", illegalStateException.getMessage());\n\t}\n\n\t@Test\n\tpublic void singleLatinCodePointHasSize1() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"X\");\n\t\tassertEquals(1, s.size());\n\t}\n\n\t@Test\n\tpublic void consumingSingleLatinCodePointShouldMoveIndex() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"X\");\n\t\tassertEquals(0, s.index());\n\t\ts.consume();\n\t\tassertEquals(1, s.index());\n\t}\n\n\t@Test\n\tpublic void consumingPastSingleLatinCodePointShouldThrow() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"X\");\n\t\ts.consume();\n\t\tIllegalStateException illegalStateException = assertThrows(IllegalStateException.class, s::consume);\n\t\tassertEquals(\"cannot consume EOF\", illegalStateException.getMessage());\n\t}\n\n\t@Test\n\tpublic void singleLatinCodePointLookAheadShouldReturnCodePoint() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"X\");\n\t\tassertEquals('X', s.LA(1));\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void multipleLatinCodePointsLookAheadShouldReturnCodePoints() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"XYZ\");\n\t\tassertEquals('X', s.LA(1));\n\t\tassertEquals(0, s.index());\n\t\tassertEquals('Y', s.LA(2));\n\t\tassertEquals(0, s.index());\n\t\tassertEquals('Z', s.LA(3));\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void singleLatinCodePointLookAheadPastEndShouldReturnEOF() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"X\");\n\t\tassertEquals(IntStream.EOF, s.LA(2));\n\t}\n\n\t@Test\n\tpublic void singleCJKCodePointHasSize1() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\\u611B\");\n\t\tassertEquals(1, s.size());\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void consumingSingleCJKCodePointShouldMoveIndex() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\\u611B\");\n\t\tassertEquals(0, s.index());\n\t\ts.consume();\n\t\tassertEquals(1, s.index());\n\t}\n\n\t@Test\n\tpublic void consumingPastSingleCJKCodePointShouldThrow() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\\u611B\");\n\t\ts.consume();\n\t\tIllegalStateException illegalStateException = assertThrows(IllegalStateException.class, s::consume);\n\t\tassertEquals(\"cannot consume EOF\", illegalStateException.getMessage());\n\t}\n\n\t@Test\n\tpublic void singleCJKCodePointLookAheadShouldReturnCodePoint() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\\u611B\");\n\t\tassertEquals(0x611B, s.LA(1));\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void singleCJKCodePointLookAheadPastEndShouldReturnEOF() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"\\u611B\");\n\t\tassertEquals(IntStream.EOF, s.LA(2));\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void singleEmojiCodePointHasSize1() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder().appendCodePoint(0x1F4A9).toString());\n\t\tassertEquals(1, s.size());\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void consumingSingleEmojiCodePointShouldMoveIndex() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder().appendCodePoint(0x1F4A9).toString());\n\t\tassertEquals(0, s.index());\n\t\ts.consume();\n\t\tassertEquals(1, s.index());\n\t}\n\n\t@Test\n\tpublic void consumingPastEndOfEmojiCodePointWithShouldThrow() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder().appendCodePoint(0x1F4A9).toString());\n\t\tassertEquals(0, s.index());\n\t\ts.consume();\n\t\tassertEquals(1, s.index());\n\t\tIllegalStateException illegalStateException = assertThrows(IllegalStateException.class, s::consume);\n\t\tassertEquals(\"cannot consume EOF\", illegalStateException.getMessage());\n\t}\n\n\t@Test\n\tpublic void singleEmojiCodePointLookAheadShouldReturnCodePoint() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder().appendCodePoint(0x1F4A9).toString());\n\t\tassertEquals(0x1F4A9, s.LA(1));\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void singleEmojiCodePointLookAheadPastEndShouldReturnEOF() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder().appendCodePoint(0x1F4A9).toString());\n\t\tassertEquals(IntStream.EOF, s.LA(2));\n\t\tassertEquals(0, s.index());\n\t}\n\n\t@Test\n\tpublic void getTextWithLatin() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"0123456789\");\n\t\tassertEquals(\"34567\", s.getText(Interval.of(3, 7)));\n\t}\n\n\t@Test\n\tpublic void getTextWithCJK() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"01234\\u40946789\");\n\t\tassertEquals(\"34\\u409467\", s.getText(Interval.of(3, 7)));\n\t}\n\n\t@Test\n\tpublic void getTextWithEmoji() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder(\"01234\")\n\t\t\t\t\t.appendCodePoint(0x1F522)\n\t\t\t\t\t.append(\"6789\")\n\t\t\t\t\t.toString());\n\t\tassertEquals(\"34\\uD83D\\uDD2267\", s.getText(Interval.of(3, 7)));\n\t}\n\n\t@Test\n\tpublic void toStringWithLatin() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"0123456789\");\n\t\tassertEquals(\"0123456789\", s.toString());\n\t}\n\n\t@Test\n\tpublic void toStringWithCJK() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"01234\\u40946789\");\n\t\tassertEquals(\"01234\\u40946789\", s.toString());\n\t}\n\n\t@Test\n\tpublic void toStringWithEmoji() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder(\"01234\")\n\t\t\t\t\t.appendCodePoint(0x1F522)\n\t\t\t\t\t.append(\"6789\")\n\t\t\t\t\t.toString());\n\t\tassertEquals(\"01234\\uD83D\\uDD226789\", s.toString());\n\t}\n\n\t@Test\n\tpublic void lookAheadWithLatin() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"0123456789\");\n\t\tassertEquals('5', s.LA(6));\n\t}\n\n\t@Test\n\tpublic void lookAheadWithCJK() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"01234\\u40946789\");\n\t\tassertEquals(0x4094, s.LA(6));\n\t}\n\n\t@Test\n\tpublic void lookAheadWithEmoji() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder(\"01234\")\n\t\t\t\t\t.appendCodePoint(0x1F522)\n\t\t\t\t\t.append(\"6789\")\n\t\t\t\t\t.toString());\n\t\tassertEquals(0x1F522, s.LA(6));\n\t}\n\n\t@Test\n\tpublic void seekWithLatin() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"0123456789\");\n\t\ts.seek(5);\n\t\tassertEquals('5', s.LA(1));\n\t}\n\n\t@Test\n\tpublic void seekWithCJK() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"01234\\u40946789\");\n\t\ts.seek(5);\n\t\tassertEquals(0x4094, s.LA(1));\n\t}\n\n\t@Test\n\tpublic void seekWithEmoji() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder(\"01234\")\n\t\t\t\t\t.appendCodePoint(0x1F522)\n\t\t\t\t\t.append(\"6789\")\n\t\t\t\t\t.toString());\n\t\ts.seek(5);\n\t\tassertEquals(0x1F522, s.LA(1));\n\t}\n\n\t@Test\n\tpublic void lookBehindWithLatin() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"0123456789\");\n\t\ts.seek(6);\n\t\tassertEquals('5', s.LA(-1));\n\t}\n\n\t@Test\n\tpublic void lookBehindWithCJK() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"01234\\u40946789\");\n\t\ts.seek(6);\n\t\tassertEquals(0x4094, s.LA(-1));\n\t}\n\n\t@Test\n\tpublic void lookBehindWithEmoji() {\n\t\tCodePointCharStream s = CharStreams.fromString(\n\t\t\t\tnew StringBuilder(\"01234\")\n\t\t\t\t\t.appendCodePoint(0x1F522)\n\t\t\t\t\t.append(\"6789\")\n\t\t\t\t\t.toString());\n\t\ts.seek(6);\n\t\tassertEquals(0x1F522, s.LA(-1));\n\t}\n\n\t@Test\n\tpublic void asciiContentsShouldUse8BitBuffer() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"hello\");\n\t\tassertTrue(s.getInternalStorage() instanceof byte[]);\n\t\tassertEquals(5, s.size());\n\t}\n\n\t@Test\n\tpublic void bmpContentsShouldUse16BitBuffer() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"hello \\u4E16\\u754C\");\n\t\tassertTrue(s.getInternalStorage() instanceof char[]);\n\t\tassertEquals(8, s.size());\n\t}\n\n\t@Test\n\tpublic void smpContentsShouldUse32BitBuffer() {\n\t\tCodePointCharStream s = CharStreams.fromString(\"hello \\uD83C\\uDF0D\");\n\t\tassertTrue(s.getInternalStorage() instanceof int[]);\n\t\tassertEquals(7, s.size());\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/CustomDescriptors.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.runtime.atn.PredictionMode;\n\nimport java.net.URI;\nimport java.nio.file.Paths;\nimport java.util.*;\n\npublic class CustomDescriptors {\n\tpublic final static HashMap<String, RuntimeTestDescriptor[]> descriptors;\n\tprivate final static URI uri;\n\n\tstatic {\n\t\turi = Paths.get(RuntimeTestUtils.runtimeTestsuitePath.toString(),\n\t\t\t\t\t\t\"test\", \"org\", \"antlr\", \"v4\", \"test\", \"runtime\", \"CustomDescriptors.java\").toUri();\n\n\t\tdescriptors = new HashMap<>();\n\t\tdescriptors.put(\"LexerExec\",\n\t\t\t\tnew RuntimeTestDescriptor[]{\n\t\t\t\t\t\tgetLineSeparatorLfDescriptor(),\n\t\t\t\t\t\tgetLineSeparatorCrLfDescriptor(),\n\t\t\t\t\t\tgetLargeLexerDescriptor(),\n\t\t\t\t\t\tgetAtnStatesSizeMoreThan65535Descriptor()\n\t\t\t\t});\n\t\tdescriptors.put(\"ParserExec\",\n\t\t\t\tnew RuntimeTestDescriptor[] {\n\t\t\t\t\t\tgetMultiTokenAlternativeDescriptor()\n\t\t\t\t});\n\t}\n\n\tprivate static RuntimeTestDescriptor getLineSeparatorLfDescriptor() {\n\t\treturn new RuntimeTestDescriptor(\n\t\t\t\tGrammarType.Lexer,\n\t\t\t\t\"LineSeparatorLf\",\n\t\t\t\t\"\",\n\t\t\t\t\"1\\n2\\n3\",\n\t\t\t\t\"[@0,0:0='1',<1>,1:0]\\n\" +\n\t\t\t\t\t\t\"[@1,1:1='\\\\n',<2>,1:1]\\n\" +\n\t\t\t\t\t\t\"[@2,2:2='2',<1>,2:0]\\n\" +\n\t\t\t\t\t\t\"[@3,3:3='\\\\n',<2>,2:1]\\n\" +\n\t\t\t\t\t\t\"[@4,4:4='3',<1>,3:0]\\n\" +\n\t\t\t\t\t\t\"[@5,5:4='<EOF>',<-1>,3:1]\\n\",\n\t\t\t\t\"\",\n\t\t\t\tnull,\n\t\t\t\t\"L\",\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\t\t\"T: ~'\\\\n'+;\\n\" +\n\t\t\t\t\t\t\"SEPARATOR: '\\\\n';\",\n\t\t\t\tnull, false, false, false,  PredictionMode.LL, true, null, uri);\n\t}\n\n\tprivate static RuntimeTestDescriptor getLineSeparatorCrLfDescriptor() {\n\t\treturn new RuntimeTestDescriptor(\n\t\t\t\tGrammarType.Lexer,\n\t\t\t\t\"LineSeparatorCrLf\",\n\t\t\t\t\"\",\n\t\t\t\t\"1\\r\\n2\\r\\n3\",\n\t\t\t\t\"[@0,0:0='1',<1>,1:0]\\n\" +\n\t\t\t\t\t\t\"[@1,1:2='\\\\r\\\\n',<2>,1:1]\\n\" +\n\t\t\t\t\t\t\"[@2,3:3='2',<1>,2:0]\\n\" +\n\t\t\t\t\t\t\"[@3,4:5='\\\\r\\\\n',<2>,2:1]\\n\" +\n\t\t\t\t\t\t\"[@4,6:6='3',<1>,3:0]\\n\" +\n\t\t\t\t\t\t\"[@5,7:6='<EOF>',<-1>,3:1]\\n\",\n\t\t\t\t\"\",\n\t\t\t\t\"\",\n\t\t\t\t\"L\",\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\t\t\"T: ~'\\\\r'+;\\n\" +\n\t\t\t\t\t\t\"SEPARATOR: '\\\\r\\\\n';\",\n\t\t\t\tnull, false, false, false, PredictionMode.LL, true, null, uri);\n\t}\n\n\tprivate static RuntimeTestDescriptor getLargeLexerDescriptor() {\n\t\tfinal int tokensCount = 4000;\n\t\tfinal String grammarName = \"L\";\n\n\t\tStringBuilder grammar = new StringBuilder();\n\t\tgrammar.append(\"lexer grammar \").append(grammarName).append(\";\\n\");\n\t\tgrammar.append(\"WS: [ \\\\t\\\\r\\\\n]+ -> skip;\\n\");\n\t\tfor (int i = 0; i < tokensCount; i++) {\n\t\t\tgrammar.append(\"KW\").append(i).append(\" : 'KW' '\").append(i).append(\"';\\n\");\n\t\t}\n\n\t\treturn new RuntimeTestDescriptor(\n\t\t\t\tGrammarType.Lexer,\n\t\t\t\t\"LargeLexer\",\n\t\t\t\t\"This is a regression test for antlr/antlr4#76 \\\"Serialized ATN strings\\n\" +\n\t\t\t\t\t\t\"should be split when longer than 2^16 bytes (class file limitation)\\\"\\n\" +\n\t\t\t\t\t\t\"https://github.com/antlr/antlr4/issues/76\",\n\t\t\t\t\"KW400\",\n\t\t\t\t\"[@0,0:4='KW400',<402>,1:0]\\n\" +\n\t\t\t\t\t\t\"[@1,5:4='<EOF>',<-1>,1:5]\\n\",\n\t\t\t\t\"\",\n\t\t\t\t\"\",\n\t\t\t\tgrammarName,\n\t\t\t\tgrammar.toString(),\n\t\t\t\tnull, false, false, false, PredictionMode.LL, true, null, uri);\n\t}\n\n\tprivate static RuntimeTestDescriptor getAtnStatesSizeMoreThan65535Descriptor() {\n\t\t// I tried playing around with different sizes, and I think 1002 works for Go but 1003 does not;\n\t\t// the executing lexer gets a token syntax error for T208 or something like that\n\t\tfinal int tokensCount = 1024;\n\t\tfinal String suffix = String.join(\"\", Collections.nCopies(70, \"_\"));\n\n\t\tfinal String grammarName = \"L\";\n\t\tStringBuilder grammar = new StringBuilder();\n\t\tgrammar.append(\"lexer grammar \").append(grammarName).append(\";\\n\");\n\t\tgrammar.append('\\n');\n\t\tStringBuilder input = new StringBuilder();\n\t\tStringBuilder output = new StringBuilder();\n\t\tint startOffset;\n\t\tint stopOffset = -2;\n\t\tfor (int i = 0; i < tokensCount; i++) {\n\t\t\tString ruleName = String.format(\"T_%06d\", i);\n\t\t\tString value = ruleName+suffix;\n\t\t\tgrammar.append(ruleName).append(\": '\").append(value).append(\"';\\n\");\n\t\t\tinput.append(value).append('\\n');\n\n\t\t\tstartOffset = stopOffset + 2;\n\t\t\tstopOffset += value.length() + 1;\n\n\t\t\toutput.append(\"[@\").append(i).append(',').append(startOffset).append(':').append(stopOffset)\n\t\t\t\t\t.append(\"='\").append(value).append(\"',<\").append(i + 1).append(\">,\").append(i + 1)\n\t\t\t\t\t.append(\":0]\\n\");\n\t\t}\n\n\t\tgrammar.append(\"\\n\");\n\t\tgrammar.append(\"WS: [ \\\\t\\\\r\\\\n]+ -> skip;\\n\");\n\n\t\tstartOffset = stopOffset + 2;\n\t\tstopOffset = startOffset - 1;\n\t\toutput.append(\"[@\").append(tokensCount).append(',').append(startOffset).append(':').append(stopOffset)\n\t\t\t\t.append(\"='<EOF>',<-1>,\").append(tokensCount + 1).append(\":0]\\n\");\n\n\t\treturn new RuntimeTestDescriptor(\n\t\t\t\tGrammarType.Lexer,\n\t\t\t\t\"AtnStatesSizeMoreThan65535\",\n\t\t\t\t\"Regression for https://github.com/antlr/antlr4/issues/1863\",\n\t\t\t\tinput.toString(),\n\t\t\t\toutput.toString(),\n\t\t\t\t\"\",\n\t\t\t\t\"\",\n\t\t\t\tgrammarName,\n\t\t\t\tgrammar.toString(),\n\t\t\t\tnull, false, false, false, PredictionMode.LL, true,\n\t\t\t\tnew String[] {\"CSharp\", \"Python3\", \"Go\", \"PHP\", \"Swift\", \"JavaScript\", \"TypeScript\", \"Dart\"},\n\t\t\t\turi);\n\t}\n\n\tprivate static RuntimeTestDescriptor getMultiTokenAlternativeDescriptor() {\n\t\tfinal int tokensCount = 64;\n\n\t\tStringBuilder rule = new StringBuilder(\"r1: \");\n\t\tStringBuilder tokens = new StringBuilder();\n\t\tStringBuilder input = new StringBuilder();\n\t\tStringBuilder output = new StringBuilder();\n\n\t\tfor (int i = 0; i < tokensCount; i++) {\n\t\t\tString currentToken = \"T\" + i;\n\t\t\trule.append(currentToken);\n\t\t\tif (i < tokensCount - 1) {\n\t\t\t\trule.append(\" | \");\n\t\t\t} else {\n\t\t\t\trule.append(\";\");\n\t\t\t}\n\t\t\ttokens.append(currentToken).append(\": '\").append(currentToken).append(\"';\\n\");\n\t\t\tinput.append(currentToken).append(\" \");\n\t\t\toutput.append(currentToken);\n\t\t}\n\t\tString currentToken = \"T\" + tokensCount;\n\t\ttokens.append(currentToken).append(\": '\").append(currentToken).append(\"';\\n\");\n\t\tinput.append(currentToken).append(\" \");\n\t\toutput.append(currentToken);\n\n\t\tString grammar = \"grammar P;\\n\" +\n\t\t\t\t\"r: (r1 | T\" + tokensCount + \")+ EOF {<writeln(\\\"$text\\\")>};\\n\" +\n\t\t\t\trule + \"\\n\" +\n\t\t\t\ttokens + \"\\n\" +\n\t\t\t\t\"WS: [ ]+ -> skip;\";\n\n\t\treturn new RuntimeTestDescriptor(\n\t\t\t\tGrammarType.Parser,\n\t\t\t\t\"MultiTokenAlternative\",\n\t\t\t\t\"https://github.com/antlr/antlr4/issues/3698, https://github.com/antlr/antlr4/issues/3703\",\n\t\t\t\tinput.toString(),\n\t\t\t\toutput + \"\\n\",\n\t\t\t\t\"\",\n\t\t\t\t\"r\",\n\t\t\t\t\"P\",\n\t\t\t\tgrammar,\n\t\t\t\tnull, false, false, false, PredictionMode.LL, true, null, uri);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/ErrorQueue.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.runtime.misc.Utils;\nimport org.antlr.v4.tool.ANTLRMessage;\nimport org.antlr.v4.tool.ANTLRToolListener;\nimport org.antlr.v4.tool.ToolMessage;\nimport org.stringtemplate.v4.ST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ErrorQueue implements ANTLRToolListener {\n\tpublic final Tool tool;\n\tpublic final List<String> infos = new ArrayList<String>();\n\tpublic final List<ANTLRMessage> errors = new ArrayList<ANTLRMessage>();\n\tpublic final List<ANTLRMessage> warnings = new ArrayList<ANTLRMessage>();\n\tpublic final List<ANTLRMessage> all = new ArrayList<ANTLRMessage>();\n\n\tpublic ErrorQueue() {\n\t\tthis(null);\n\t}\n\n\tpublic ErrorQueue(Tool tool) {\n\t\tthis.tool = tool;\n\t}\n\n\t@Override\n\tpublic void info(String msg) {\n\t\tinfos.add(msg);\n\t}\n\n\t@Override\n\tpublic void error(ANTLRMessage msg) {\n\t\terrors.add(msg);\n        all.add(msg);\n\t}\n\n\t@Override\n\tpublic void warning(ANTLRMessage msg) {\n\t\twarnings.add(msg);\n        all.add(msg);\n\t}\n\n\tpublic void error(ToolMessage msg) {\n\t\terrors.add(msg);\n\t\tall.add(msg);\n\t}\n\n\tpublic int size() {\n\t\treturn all.size() + infos.size();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn toString(false);\n\t}\n\n\tpublic String toString(boolean rendered) {\n\t\tif (!rendered) {\n\t\t\treturn Utils.join(all.iterator(), \"\\n\");\n\t\t}\n\n\t\tif (tool == null) {\n\t\t\tthrow new IllegalStateException(String.format(\"No %s instance is available.\", Tool.class.getName()));\n\t\t}\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (ANTLRMessage m : all) {\n\t\t\tST st = tool.errMgr.getMessageTemplate(m);\n\t\t\tbuf.append(st.render());\n\t\t\tbuf.append(\"\\n\");\n\t\t}\n\n\t\treturn buf.toString();\n\t}\n\n}\n\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/FileUtils.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.runtime.misc.Utils;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.LinkOption;\nimport java.nio.file.Path;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.nio.file.attribute.DosFileAttributes;\n\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.FileSeparator;\n\npublic class FileUtils {\n\tpublic static void writeFile(String dir, String fileName, String content) {\n\t\ttry {\n\t\t\tUtils.writeFile(dir + FileSeparator + fileName, content, \"UTF-8\");\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tSystem.err.println(\"can't write file\");\n\t\t\tioe.printStackTrace(System.err);\n\t\t}\n\t}\n\n\tpublic static String readFile(String dir, String fileName) {\n\t\ttry {\n\t\t\treturn String.copyValueOf(Utils.readFile(dir+\"/\"+fileName, \"UTF-8\"));\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tSystem.err.println(\"can't read file\");\n\t\t\tioe.printStackTrace(System.err);\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static void replaceInFile(Path sourcePath, String target, String replacement) throws IOException {\n\t\treplaceInFile(sourcePath, sourcePath, target, replacement);\n\t}\n\n\tpublic static void replaceInFile(Path sourcePath, Path destPath, String target, String replacement) throws IOException {\n\t\tString content = new String(Files.readAllBytes(sourcePath), StandardCharsets.UTF_8);\n\t\tString newContent = content.replace(target, replacement);\n\t\ttry (PrintWriter out = new PrintWriter(destPath.toString())) {\n\t\t\tout.println(newContent);\n\t\t}\n\t}\n\n\tpublic static void mkdir(String dir) {\n\t\tFile f = new File(dir);\n\t\t//noinspection ResultOfMethodCallIgnored\n\t\tf.mkdirs();\n\t}\n\n\tpublic static void deleteDirectory(File f) throws IOException {\n\t\tif (f.isDirectory() && !isLink(f.toPath())) {\n\t\t\tFile[] files = f.listFiles();\n\t\t\tif (files != null) {\n\t\t\t\tfor (File c : files)\n\t\t\t\t\tdeleteDirectory(c);\n\t\t\t}\n\t\t}\n\t\tif (!f.delete())\n\t\t\tthrow new IOException(\"Failed to delete file: \" + f);\n\t}\n\n\tpublic static boolean isLink(Path path) throws IOException {\n\t\ttry {\n\t\t\tBasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);\n\t\t\treturn attrs.isSymbolicLink() || (attrs instanceof DosFileAttributes && attrs.isOther());\n\t\t} catch (IOException ignored) {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/GeneratedFile.java",
    "content": "package org.antlr.v4.test.runtime;\n\npublic class GeneratedFile {\n\tpublic final String name;\n\tpublic final boolean isParser;\n\n\tpublic GeneratedFile(String name, boolean isParser) {\n\t\tthis.name = name;\n\t\tthis.isParser = isParser;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name + \"; isParser:\" + isParser;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/Generator.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.tool.ANTLRMessage;\nimport org.antlr.v4.tool.DefaultToolListener;\nimport org.stringtemplate.v4.ST;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\n\npublic class Generator {\n\t/** Write a grammar to tmpdir and run antlr */\n\tpublic static ErrorQueue antlrOnString(String workdir,\n\t\t\t\t\t\t\t\t\t\t   String targetName,\n\t\t\t\t\t\t\t\t\t\t   String grammarFileName,\n\t\t\t\t\t\t\t\t\t\t   String grammarStr,\n\t\t\t\t\t\t\t\t\t\t   boolean defaultListener,\n\t\t\t\t\t\t\t\t\t\t   String... extraOptions)\n\t{\n\t\tFileUtils.mkdir(workdir);\n\t\twriteFile(workdir, grammarFileName, grammarStr);\n\t\treturn antlrOnString(workdir, targetName, grammarFileName, defaultListener, extraOptions);\n\t}\n\n\t/** Run ANTLR on stuff in workdir and error queue back */\n\tpublic static ErrorQueue antlrOnString(String workdir,\n\t\t\t\t\t\t\t\t\t\t   String targetName,\n\t\t\t\t\t\t\t\t\t\t   String grammarFileName,\n\t\t\t\t\t\t\t\t\t\t   boolean defaultListener,\n\t\t\t\t\t\t\t\t\t\t   String... extraOptions)\n\t{\n\t\tfinal List<String> options = new ArrayList<>();\n\t\tCollections.addAll(options, extraOptions);\n\t\tif ( targetName!=null ) {\n\t\t\toptions.add(\"-Dlanguage=\"+targetName);\n\t\t}\n\t\tif ( !options.contains(\"-o\") ) {\n\t\t\toptions.add(\"-o\");\n\t\t\toptions.add(workdir);\n\t\t}\n\t\tif ( !options.contains(\"-lib\") ) {\n\t\t\toptions.add(\"-lib\");\n\t\t\toptions.add(workdir);\n\t\t}\n\t\tif ( !options.contains(\"-encoding\") ) {\n\t\t\toptions.add(\"-encoding\");\n\t\t\toptions.add(\"UTF-8\");\n\t\t}\n\t\toptions.add(new File(workdir,grammarFileName).toString());\n\n\t\tfinal String[] optionsA = new String[options.size()];\n\t\toptions.toArray(optionsA);\n\t\tTool antlr = new Tool(optionsA);\n\t\tErrorQueue equeue = new ErrorQueue(antlr);\n\t\tantlr.addListener(equeue);\n\t\tif (defaultListener) {\n\t\t\tantlr.addListener(new DefaultToolListener(antlr));\n\t\t}\n\t\tantlr.processGrammarsOnCommandLine();\n\n\t\tList<String> errors = new ArrayList<>();\n\n\t\tif ( !defaultListener && !equeue.errors.isEmpty() ) {\n\t\t\tfor (int i = 0; i < equeue.errors.size(); i++) {\n\t\t\t\tANTLRMessage msg = equeue.errors.get(i);\n\t\t\t\tST msgST = antlr.errMgr.getMessageTemplate(msg);\n\t\t\t\terrors.add(msgST.render());\n\t\t\t}\n\t\t}\n\t\tif ( !defaultListener && !equeue.warnings.isEmpty() ) {\n\t\t\tfor (int i = 0; i < equeue.warnings.size(); i++) {\n\t\t\t\tANTLRMessage msg = equeue.warnings.get(i);\n\t\t\t\t// antlrToolErrors.append(msg); warnings are hushed\n\t\t\t}\n\t\t}\n\n\t\treturn equeue;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/GrammarType.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\npublic enum GrammarType {\n\tLexer,\n\tParser,\n\tCompositeLexer,\n\tCompositeParser\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/OSType.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\npublic enum OSType {\n\tWindows,\n\tLinux,\n\tMac,\n\tUnknown\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/Processor.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.joinLines;\n\npublic class Processor {\n\t/** Turn this on to see output like:\n\t *  RUNNING cmake . -DCMAKE_BUILD_TYPE=Release in /Users/parrt/antlr/code/antlr4/runtime/Cpp\n\t *  RUNNING make -j 20 in /Users/parrt/antlr/code/antlr4/runtime/Cpp\n\t *  RUNNING ln -s /Users/parrt/antlr/code/antlr4/runtime/Cpp/dist/libantlr4-runtime.dylib in /var/folders/w1/_nr4stn13lq0rvjdkwh7q8cc0000gn/T/CppRunner-ForkJoinPool-1-worker-23-1668284191961\n\t *  RUNNING clang++ -std=c++17 -I /Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/src -L. -lantlr4-runtime -pthread -o Test.out Test.cpp TLexer.cpp TParser.cpp TListener.cpp TBaseListener.cpp TVisitor.cpp TBaseVisitor.cpp in /var/folders/w1/_nr4stn13lq0rvjdkwh7q8cc0000gn/T/CppRunner-ForkJoinPool-1-worker-23-1668284191961\n\t */\n\tpublic static final boolean WATCH_COMMANDS_EXEC = false;\n\tpublic final String[] arguments;\n\tpublic final String workingDirectory;\n\tpublic final Map<String, String> environmentVariables;\n\tpublic final boolean throwOnNonZeroErrorCode;\n\n\tpublic static ProcessorResult run(String[] arguments, String workingDirectory, Map<String, String> environmentVariables)\n\t\t\tthrows InterruptedException, IOException\n\t{\n\t\treturn new Processor(arguments, workingDirectory, environmentVariables, true).start();\n\t}\n\n\tpublic static ProcessorResult run(String[] arguments, String workingDirectory) throws InterruptedException, IOException {\n\t\treturn new Processor(arguments, workingDirectory, new HashMap<>(), true).start();\n\t}\n\n\tpublic Processor(String[] arguments, String workingDirectory, Map<String, String> environmentVariables,\n\t\t\t\t\t boolean throwOnNonZeroErrorCode) {\n\t\tthis.arguments = arguments;\n\t\tthis.workingDirectory = workingDirectory;\n\t\tthis.environmentVariables = environmentVariables;\n\t\tthis.throwOnNonZeroErrorCode = throwOnNonZeroErrorCode;\n\t}\n\n\tpublic ProcessorResult start() throws InterruptedException, IOException {\n\t\tif ( WATCH_COMMANDS_EXEC ) {\n\t\t\tSystem.out.println(\"RUNNING \"+ String.join(\" \", arguments)+\" in \"+workingDirectory);\n\t\t}\n\t\tProcessBuilder builder = new ProcessBuilder(arguments);\n\t\tif (workingDirectory != null) {\n\t\t\tbuilder.directory(new File(workingDirectory));\n\t\t}\n\t\tif (environmentVariables != null && environmentVariables.size() > 0) {\n\t\t\tMap<String, String> environment = builder.environment();\n\t\t\tfor (String key : environmentVariables.keySet()) {\n\t\t\t\tenvironment.put(key, environmentVariables.get(key));\n\t\t\t}\n\t\t}\n\n\t\tProcess process = builder.start();\n\t\tStreamReader stdoutReader = new StreamReader(process.getInputStream());\n\t\tStreamReader stderrReader = new StreamReader(process.getErrorStream());\n\t\tstdoutReader.start();\n\t\tstderrReader.start();\n\t\tprocess.waitFor();\n\t\tstdoutReader.join();\n\t\tstderrReader.join();\n\n\t\tString output = stdoutReader.toString();\n\t\tString errors = stderrReader.toString();\n\t\tif (throwOnNonZeroErrorCode && process.exitValue() != 0) {\n\t\t\tthrow new InterruptedException(\"Exit code \"+process.exitValue()+\" with output:\\n\"+joinLines(output, errors));\n\t\t}\n\t\treturn new ProcessorResult(process.exitValue(), output, errors);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/ProcessorResult.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\npublic class ProcessorResult {\n\tpublic final int exitCode;\n\tpublic final String output;\n\tpublic final String errors;\n\n\tpublic ProcessorResult(int exitCode, String output, String errors) {\n\t\tthis.exitCode = exitCode;\n\t\tthis.output = output;\n\t\tthis.errors = errors;\n\t}\n\n\tpublic boolean isSuccess() {\n\t\treturn exitCode == 0;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/README.md",
    "content": "# Runtime test mechanism\n\nThe files in the various target subdirectories were automatically generated\nand exist as a convenience so that we can test individual targets and also\ngroups of tests using the development environments like Intellij."
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/RunOptions.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.runtime.atn.PredictionMode;\n\npublic class RunOptions {\n\tpublic final String grammarFileName;\n\tpublic final String grammarStr;\n\tpublic final String parserName;\n\tpublic final String lexerName;\n\tpublic final String grammarName;\n\tpublic final boolean useListener;\n\tpublic final boolean useVisitor;\n\tpublic final String startRuleName;\n\tpublic final String input;\n\tpublic final boolean profile;\n\tpublic final boolean showDiagnosticErrors;\n\tpublic final boolean traceATN;\n\tpublic final boolean showDFA;\n\tpublic final Stage endStage;\n\tpublic final String superClass;\n\tpublic final PredictionMode predictionMode;\n\tpublic final boolean buildParseTree;\n\n\tpublic RunOptions(String grammarFileName, String grammarStr, String parserName, String lexerName,\n\t\t\t\t\t  boolean useListener, boolean useVisitor, String startRuleName,\n\t\t\t\t\t  String input, boolean profile, boolean showDiagnosticErrors,\n\t\t\t\t\t  boolean traceATN, boolean showDFA, Stage endStage,\n\t\t\t\t\t  String language, String superClass, PredictionMode predictionMode, boolean buildParseTree) {\n\t\tthis.grammarFileName = grammarFileName;\n\t\tthis.grammarStr = grammarStr;\n\t\tthis.parserName = parserName;\n\t\tthis.lexerName = lexerName;\n\t\tString grammarName = null;\n\t\tboolean isCombinedGrammar = lexerName != null && parserName != null || language.equals(\"Go\");\n\t\tif (isCombinedGrammar) {\n\t\t\tif (parserName != null) {\n\t\t\t\tgrammarName = parserName.endsWith(\"Parser\")\n\t\t\t\t\t? parserName.substring(0, parserName.length() - \"Parser\".length())\n\t\t\t\t\t: parserName;\n\t\t\t}\n\t\t\telse if (lexerName != null) {\n\t\t\t\tgrammarName = lexerName.endsWith(\"Lexer\")\n\t\t\t\t\t? lexerName.substring(0, lexerName.length() - \"Lexer\".length())\n\t\t\t\t\t: lexerName;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (parserName != null) {\n\t\t\t\tgrammarName = parserName;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tgrammarName = lexerName;\n\t\t\t}\n\t\t}\n\t\tthis.grammarName = grammarName;\n\t\tthis.useListener = useListener;\n\t\tthis.useVisitor = useVisitor;\n\t\tthis.startRuleName = startRuleName;\n\t\tthis.input = input;\n\t\tthis.profile = profile;\n\t\tthis.showDiagnosticErrors = showDiagnosticErrors;\n\t\tthis.traceATN = traceATN;\n\t\tthis.showDFA = showDFA;\n\t\tthis.endStage = endStage;\n\t\tthis.superClass = superClass;\n\t\tthis.predictionMode = predictionMode;\n\t\tthis.buildParseTree = buildParseTree;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/RuntimeRunner.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\nimport org.antlr.v4.test.runtime.states.State;\nimport org.stringtemplate.v4.ST;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.*;\n\nimport static org.antlr.v4.test.runtime.FileUtils.deleteDirectory;\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.*;\n\npublic abstract class RuntimeRunner implements AutoCloseable {\n\n\tpublic abstract String getLanguage();\n\n\tprotected String getExtension() { return getLanguage().toLowerCase(); }\n\n\tprotected String getTitleName() { return getLanguage(); }\n\n\tprotected String getTestFileName() { return \"Test\"; }\n\n\tprotected String getLexerSuffix() { return \"Lexer\"; }\n\n\tprotected String getParserSuffix() { return \"Parser\"; }\n\n\tprotected String getBaseListenerSuffix() { return \"BaseListener\"; }\n\n\tprotected String getListenerSuffix() { return \"Listener\"; }\n\n\tprotected String getBaseVisitorSuffix() { return \"BaseVisitor\"; }\n\n\tprotected String getVisitorSuffix() { return \"Visitor\"; }\n\n\tprotected String grammarNameToFileName(String grammarName) { return grammarName; }\n\n\tprivate static String runtimeToolPath;\n\tprivate static String compilerPath;\n\n\tpublic final static String InputFileName = \"input\";\n\n\tprotected final String getCompilerPath() {\n\t\tif (compilerPath == null) {\n\t\t\tcompilerPath = getCompilerName();\n\t\t\tif (compilerPath != null) {\n\t\t\t\tString compilerPathFromProperty = System.getProperty(getPropertyPrefix() + \"-compiler\");\n\t\t\t\tif (compilerPathFromProperty != null && compilerPathFromProperty.length() > 0) {\n\t\t\t\t\tcompilerPath = compilerPathFromProperty;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn compilerPath;\n\t}\n\n\tprotected final String getRuntimeToolPath() {\n\t\tif (runtimeToolPath == null) {\n\t\t\truntimeToolPath = getRuntimeToolName();\n\t\t\tif (runtimeToolPath != null) {\n\t\t\t\tString runtimeToolPathFromProperty = System.getProperty(getPropertyPrefix() + \"-exec\");\n\t\t\t\tif (runtimeToolPathFromProperty != null && runtimeToolPathFromProperty.length() > 0) {\n\t\t\t\t\truntimeToolPath = runtimeToolPathFromProperty;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn runtimeToolPath;\n\t}\n\n\tprotected String getCompilerName() { return null; }\n\n\tprotected String getRuntimeToolName() { return getLanguage().toLowerCase(); }\n\n\tprotected String getTestFileWithExt() { return getTestFileName() + \".\" + getExtension(); }\n\n\tprotected String getExecFileName() { return getTestFileWithExt(); }\n\n\tprotected String[] getExtraRunArgs() { return null; }\n\n\tprotected Map<String, String> getExecEnvironment() { return null; }\n\n\tprotected String getPropertyPrefix() {\n\t\treturn \"antlr-\" + getLanguage().toLowerCase();\n\t}\n\n\tpublic final String getTempDirPath() {\n\t\treturn tempTestDir.toString();\n\t}\n\n\tprivate boolean saveTestDir;\n\n\tprotected final Path tempTestDir;\n\n\tprotected RuntimeRunner() {\n\t\tthis(null, false);\n\t}\n\n\tprotected RuntimeRunner(Path tempDir, boolean saveTestDir) {\n\t\tif (tempDir == null) {\n\t\t\tString dirName = getClass().getSimpleName() + \"-\" + Thread.currentThread().getName() + \"-\" + System.currentTimeMillis();\n\t\t\ttempTestDir = Paths.get(TempDirectory, dirName);\n\t\t}\n\t\telse {\n\t\t\ttempTestDir = tempDir;\n\t\t}\n\t\tthis.saveTestDir = saveTestDir;\n\t}\n\n\tpublic void setSaveTestDir(boolean saveTestDir) {\n\t\tthis.saveTestDir = saveTestDir;\n\t}\n\n\tpublic void close() {\n\t\tremoveTempTestDirIfRequired();\n\t}\n\n\tpublic final static String cacheDirectory;\n\n\tprivate static class InitializationStatus {\n\t\tpublic final Object lockObject = new Object();\n\t\tpublic volatile Boolean isInitialized;\n\t\tpublic Exception exception;\n\t}\n\n\tprivate final static HashMap<String, InitializationStatus> runtimeInitializationStatuses = new HashMap<>();\n\n\tstatic {\n\t\tcacheDirectory = new File(System.getProperty(\"java.io.tmpdir\"), \"ANTLR-runtime-testsuite-cache\").getAbsolutePath();\n\t}\n\n\tprotected final String getCachePath() {\n\t\treturn getCachePath(getLanguage());\n\t}\n\n\tpublic static String getCachePath(String language) {\n\t\treturn cacheDirectory + FileSeparator + language;\n\t}\n\n\tprotected final String getRuntimePath() {\n\t\treturn getRuntimePath(getLanguage());\n\t}\n\n\tpublic static String getRuntimePath(String language) {\n\t\treturn runtimePath.toString() + FileSeparator + language;\n\t}\n\n\t// Allows any target to add additional options for the antlr tool such as the location of the output files\n\t// which is useful for the Go target for instance to avoid having to move them before running the test\n\t//\n\tprotected List<String> getTargetToolOptions(RunOptions ro) {\n\t\treturn null;\n\t}\n\n\tpublic State run(RunOptions runOptions) {\n\t\tList<String> options = new ArrayList<>();\n\t\tif (runOptions.useVisitor) {\n\t\t\toptions.add(\"-visitor\");\n\t\t}\n\t\tif (runOptions.superClass != null && runOptions.superClass.length() > 0) {\n\t\t\toptions.add(\"-DsuperClass=\" + runOptions.superClass);\n\t\t}\n\n\t\t// See if the target wants to add tool options.\n\t\t//\n\t\tList<String> targetOpts = getTargetToolOptions(runOptions);\n\t\tif (targetOpts != null) {\n\t\t\toptions.addAll(targetOpts);\n\t\t}\n\n\t\tErrorQueue errorQueue = Generator.antlrOnString(getTempDirPath(), getLanguage(),\n\t\t\t\trunOptions.grammarFileName, runOptions.grammarStr, false, options.toArray(new String[0]));\n\n\t\tList<GeneratedFile> generatedFiles = getGeneratedFiles(runOptions);\n\t\tGeneratedState generatedState = new GeneratedState(errorQueue, generatedFiles, null);\n\n\t\tif (generatedState.containsErrors() || runOptions.endStage == Stage.Generate) {\n\t\t\treturn generatedState;\n\t\t}\n\n\t\tif (!initAntlrRuntimeIfRequired(runOptions)) {\n\t\t\t// Do not repeat ANTLR runtime initialization error\n\t\t\treturn new CompiledState(generatedState, new Exception(getTitleName() + \" ANTLR runtime is not initialized\"));\n\t\t}\n\n\t\twriteRecognizerFile(runOptions);\n\n\t\tCompiledState compiledState = compile(runOptions, generatedState);\n\n\t\tif (compiledState.containsErrors() || runOptions.endStage == Stage.Compile) {\n\t\t\treturn compiledState;\n\t\t}\n\n\t\twriteInputFile(runOptions);\n\n\t\treturn execute(runOptions, compiledState);\n\t}\n\n\tprotected List<GeneratedFile> getGeneratedFiles(RunOptions runOptions) {\n\t\tList<GeneratedFile> files = new ArrayList<>();\n\t\tString extensionWithDot = \".\" + getExtension();\n\t\tString fileGrammarName = grammarNameToFileName(runOptions.grammarName);\n\t\tboolean isCombinedGrammarOrGo = runOptions.lexerName != null && runOptions.parserName != null || getLanguage().equals(\"Go\");\n\t\tif (runOptions.lexerName != null) {\n\t\t\tfiles.add(new GeneratedFile(fileGrammarName + (isCombinedGrammarOrGo ? getLexerSuffix() : \"\") + extensionWithDot, false));\n\t\t}\n\t\tif (runOptions.parserName != null) {\n\t\t\tfiles.add(new GeneratedFile(fileGrammarName + (isCombinedGrammarOrGo ? getParserSuffix() : \"\") + extensionWithDot, true));\n\t\t\tif (runOptions.useListener) {\n\t\t\t\tfiles.add(new GeneratedFile(fileGrammarName + getListenerSuffix() + extensionWithDot, true));\n\t\t\t\tString baseListenerSuffix = getBaseListenerSuffix();\n\t\t\t\tif (baseListenerSuffix != null) {\n\t\t\t\t\tfiles.add(new GeneratedFile(fileGrammarName + baseListenerSuffix + extensionWithDot, true));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (runOptions.useVisitor) {\n\t\t\t\tfiles.add(new GeneratedFile(fileGrammarName + getVisitorSuffix() + extensionWithDot, true));\n\t\t\t\tString baseVisitorSuffix = getBaseVisitorSuffix();\n\t\t\t\tif (baseVisitorSuffix != null) {\n\t\t\t\t\tfiles.add(new GeneratedFile(fileGrammarName + baseVisitorSuffix + extensionWithDot, true));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t}\n\n\tprotected void writeRecognizerFile(RunOptions runOptions) {\n\t\tString text = RuntimeTestUtils.getTextFromResource(\"org/antlr/v4/test/runtime/helpers/\" + getTestFileWithExt() + \".stg\");\n\t\tST outputFileST = new ST(text);\n\t\toutputFileST.add(\"grammarName\", runOptions.grammarName);\n\t\toutputFileST.add(\"lexerName\", runOptions.lexerName);\n\t\toutputFileST.add(\"parserName\", runOptions.parserName);\n\t\toutputFileST.add(\"parserStartRuleName\", grammarParseRuleToRecognizerName(runOptions.startRuleName));\n\t\toutputFileST.add(\"showDiagnosticErrors\", runOptions.showDiagnosticErrors);\n\t\toutputFileST.add(\"traceATN\", runOptions.traceATN);\n\t\toutputFileST.add(\"profile\", runOptions.profile);\n\t\toutputFileST.add(\"showDFA\", runOptions.showDFA);\n\t\toutputFileST.add(\"useListener\", runOptions.useListener);\n\t\toutputFileST.add(\"useVisitor\", runOptions.useVisitor);\n\t\toutputFileST.add(\"predictionMode\", runOptions.predictionMode);\n\t\toutputFileST.add(\"buildParseTree\", runOptions.buildParseTree);\n\t\taddExtraRecognizerParameters(outputFileST);\n\t\twriteFile(getTempDirPath(), getTestFileWithExt(), outputFileST.render());\n\t}\n\n\tprotected String grammarParseRuleToRecognizerName(String startRuleName) {\n\t\treturn startRuleName;\n\t}\n\n\tprotected void addExtraRecognizerParameters(ST template) {\n\t}\n\n\tprivate boolean initAntlrRuntimeIfRequired(RunOptions runOptions) {\n\t\tString language = getLanguage();\n\t\tInitializationStatus status;\n\n\t\t// Create initialization status for every runtime with lock object\n\t\tsynchronized (runtimeInitializationStatuses) {\n\t\t\tstatus = runtimeInitializationStatuses.get(language);\n\t\t\tif (status == null) {\n\t\t\t\tstatus = new InitializationStatus();\n\t\t\t\truntimeInitializationStatuses.put(language, status);\n\t\t\t}\n\t\t}\n\n\t\tif (status.isInitialized != null) {\n\t\t\treturn status.isInitialized;\n\t\t}\n\n\t\t// Locking per runtime, several runtimes can be being initialized simultaneously\n\t\tsynchronized (status.lockObject) {\n\t\t\tif (status.isInitialized == null) {\n\t\t\t\tException exception = null;\n\t\t\t\ttry {\n\t\t\t\t\tinitRuntime(runOptions);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\texception = e;\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tstatus.isInitialized = exception == null;\n\t\t\t\tstatus.exception = exception;\n\t\t\t}\n\t\t}\n\t\treturn status.isInitialized;\n\t}\n\n\tprotected void initRuntime(RunOptions runOptions) throws Exception {\n\t}\n\n\tprotected CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\treturn new CompiledState(generatedState, null);\n\t}\n\n\tprotected void writeInputFile(RunOptions runOptions) {\n\t\twriteFile(getTempDirPath(), InputFileName, runOptions.input);\n\t}\n\n\tprotected ExecutedState execute(RunOptions runOptions, CompiledState compiledState) {\n\t\tString output = null;\n\t\tString errors = null;\n\t\tException exception = null;\n\t\ttry {\n\t\t\tList<String> args = new ArrayList<>();\n\t\t\tString runtimeToolPath = getRuntimeToolPath();\n\t\t\tif (runtimeToolPath != null) {\n\t\t\t\targs.add(runtimeToolPath);\n\t\t\t}\n\t\t\tString[] extraRunArgs = getExtraRunArgs();\n\t\t\tif (extraRunArgs != null) {\n\t\t\t\targs.addAll(Arrays.asList(extraRunArgs));\n\t\t\t}\n\t\t\targs.add(getExecFileName());\n\t\t\targs.add(InputFileName);\n\t\t\tProcessorResult result = Processor.run(args.toArray(new String[0]), getTempDirPath(), getExecEnvironment());\n\t\t\toutput = result.output;\n\t\t\terrors = result.errors;\n\t\t} catch (InterruptedException | IOException e) {\n\t\t\texception = e;\n\t\t}\n\t\treturn new ExecutedState(compiledState, output, errors, exception);\n\t}\n\n\tprotected ProcessorResult runCommand(String[] command, String workPath) throws Exception {\n\t\treturn runCommand(command, workPath, null);\n\t}\n\n\tprotected ProcessorResult runCommand(String[] command, String workPath, String description) throws Exception {\n\t\tString cmd = String.join(\" \", command);\n\t\ttry {\n\t\t\treturn Processor.run(command, workPath);\n\t\t} catch (InterruptedException | IOException e) {\n\t\t\tString msg = \"command \\\"\" + cmd + \"\\\"\\n  in \" + workPath + \" failed\";\n\t\t\tif (description != null) {\n\t\t\t\tmsg += \":\\n  can't \" + description;\n\t\t\t}\n\t\t\tthrow new Exception(msg, e);\n\t\t}\n\t}\n\n\tprivate void removeTempTestDirIfRequired() {\n\t\tif (!saveTestDir) {\n\t\t\tFile dirFile = tempTestDir.toFile();\n\t\t\tif (dirFile.exists()) {\n\t\t\t\ttry {\n\t\t\t\t\tdeleteDirectory(dirFile);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/RuntimeTestDescriptor.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.List;\n\n/** This object represents all the information we need about a single test and is the\n * in-memory representation of a descriptor file\n */\npublic class RuntimeTestDescriptor {\n\t/** A type in {\"Lexer\", \"Parser\", \"CompositeLexer\", \"CompositeParser\"} */\n\tpublic final GrammarType testType;\n\n\t/** Return a string representing the name of the target currently testing\n\t *  this descriptor.\n\t *  Multiple instances of the same descriptor class\n\t *  can be created to test different targets.\n\t */\n\tpublic final String name;\n\n\tpublic final String notes;\n\n\t/** Parser input. Return \"\" if not input should be provided to the parser or lexer. */\n\tpublic final String input;\n\n\t/** Output from executing the parser. Return null if no output is expected. */\n\tpublic final String output;\n\n\t/** Parse errors Return null if no errors are expected. */\n\tpublic final String errors;\n\n\t/** The rule at which parsing should start */\n\tpublic final String startRule;\n\tpublic final String grammarName;\n\n\tpublic final String grammar;\n\t/** List of grammars imported into the grammar */\n\tpublic final List<Pair<String, String>> slaveGrammars;\n\n\t/** For lexical tests, dump the DFA of the default lexer mode to stdout */\n\tpublic final boolean showDFA;\n\n\t/** For parsing, engage the DiagnosticErrorListener, dumping results to stderr */\n\tpublic final boolean showDiagnosticErrors;\n\n\tpublic final boolean traceATN;\n\n\tpublic final PredictionMode predictionMode;\n\n\tpublic final boolean buildParseTree;\n\n\tpublic final String[] skipTargets;\n\n\tpublic final URI uri;\n\n\tpublic RuntimeTestDescriptor(GrammarType testType, String name, String notes,\n\t\t\t\t\t\t\t\t String input, String output, String errors,\n\t\t\t\t\t\t\t\t String startRule,\n\t\t\t\t\t\t\t\t String grammarName, String grammar, List<Pair<String, String>> slaveGrammars,\n\t\t\t\t\t\t\t\t boolean showDiagnosticErrors, boolean traceATN, boolean showDFA, PredictionMode predictionMode,\n\t\t\t\t\t\t\t\t boolean buildParseTree, String[] skipTargets, URI uri) {\n\t\tthis.testType = testType;\n\t\tthis.name = name;\n\t\tthis.notes = notes;\n\t\tthis.input = input;\n\t\tthis.output = output;\n\t\tthis.errors = errors;\n\t\tthis.startRule = startRule;\n\t\tthis.grammarName = grammarName;\n\t\tthis.grammar = grammar;\n\t\tthis.slaveGrammars = slaveGrammars;\n\t\tthis.showDFA = showDFA;\n\t\tthis.showDiagnosticErrors = showDiagnosticErrors;\n\t\tthis.traceATN = traceATN;\n\t\tthis.predictionMode = predictionMode;\n\t\tthis.buildParseTree = buildParseTree;\n\t\tthis.skipTargets = skipTargets != null ? skipTargets : new String[0];\n\t\tthis.uri = uri;\n\t}\n\n\t/** Return true if this test should be ignored for the indicated target */\n\tpublic boolean ignore(String targetName) {\n\t\treturn Arrays.asList(skipTargets).contains(targetName);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/RuntimeTestDescriptorParser.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.misc.Pair;\n\nimport java.net.URI;\nimport java.util.*;\n\npublic class RuntimeTestDescriptorParser {\n\tprivate final static Set<String> sections = new HashSet<>(Arrays.asList(\n\t\t\t\"notes\", \"type\", \"grammar\", \"slaveGrammar\", \"start\", \"input\", \"output\", \"errors\", \"flags\", \"skip\"\n\t));\n\n\t/**  Read stuff like:\n\t [grammar]\n\t grammar T;\n\t s @after {<DumpDFA()>}\n\t : ID | ID {} ;\n\t ID : 'a'..'z'+;\n\t WS : (' '|'\\t'|'\\n')+ -> skip ;\n\n\t [grammarName]\n\t T\n\n\t [start]\n\t s\n\n\t [input]\n\t abc\n\n\t [output]\n\t Decision 0:\n\t s0-ID->:s1^=>1\n\n\t [errors]\n\t \"\"\"line 1:0 reportAttemptingFullContext d=0 (s), input='abc'\n\t \"\"\"\n\n\t Some can be missing like [errors].\n\n\t Get gr names automatically \"lexer grammar Unicode;\" \"grammar T;\" \"parser grammar S;\"\n\n\t Also handle slave grammars:\n\n\t [grammar]\n\t grammar M;\n\t import S,T;\n\t s : a ;\n\t B : 'b' ; // defines B from inherited token space\n\t WS : (' '|'\\n') -> skip ;\n\n\t [slaveGrammar]\n\t parser grammar T;\n\t a : B {<writeln(\"\\\"T.a\\\"\")>};<! hidden by S.a !>\n\n\t [slaveGrammar]\n\t parser grammar S;\n\t a : b {<writeln(\"\\\"S.a\\\"\")>};\n\t b : B;\n\t */\n\tpublic static RuntimeTestDescriptor parse(String name, String text, URI uri) throws RuntimeException {\n\t\tString currentField = null;\n\t\tStringBuilder currentValue = new StringBuilder();\n\n\t\tList<Pair<String, String>> pairs = new ArrayList<>();\n\t\tString[] lines = text.split(\"\\r?\\n\");\n\n\t\tfor (String line : lines) {\n\t\t\tboolean newSection = false;\n\t\t\tString sectionName = null;\n\t\t\tif (line.startsWith(\"[\") && line.length() > 2) {\n\t\t\t\tsectionName = line.substring(1, line.length() - 1);\n\t\t\t\tnewSection = sections.contains(sectionName);\n\t\t\t}\n\n\t\t\tif (newSection) {\n\t\t\t\tif (currentField != null) {\n\t\t\t\t\tpairs.add(new Pair<>(currentField, currentValue.toString()));\n\t\t\t\t}\n\t\t\t\tcurrentField = sectionName;\n\t\t\t\tcurrentValue.setLength(0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcurrentValue.append(line);\n\t\t\t\tcurrentValue.append(\"\\n\");\n\t\t\t}\n\t\t}\n\t\tpairs.add(new Pair<>(currentField, currentValue.toString()));\n\n\t\tString notes = \"\";\n\t\tGrammarType testType = GrammarType.Lexer;\n\t\tString grammar = \"\";\n\t\tString grammarName = \"\";\n\t\tList<Pair<String, String>> slaveGrammars = new ArrayList<>();\n\t\tString startRule = \"\";\n\t\tString input = \"\";\n\t\tString output = \"\";\n\t\tString errors = \"\";\n\t\tboolean showDFA = false;\n\t\tboolean showDiagnosticErrors = false;\n\t\tboolean traceATN = false;\n\t\tPredictionMode predictionMode = PredictionMode.LL;\n\t\tboolean buildParseTree = true;\n\t\tString[] skipTargets = new String[0];\n\t\tfor (Pair<String,String> p : pairs) {\n\t\t\tString section = p.a;\n\t\t\tString value = \"\";\n\t\t\tif ( p.b!=null ) {\n\t\t\t\tvalue = p.b.trim();\n\t\t\t}\n\t\t\tif ( value.startsWith(\"\\\"\\\"\\\"\") ) {\n\t\t\t\tvalue = value.replace(\"\\\"\\\"\\\"\", \"\");\n\t\t\t}\n\t\t\telse if ( value.indexOf('\\n')>=0 ) {\n\t\t\t\tvalue = value + \"\\n\"; // if multi line and not quoted, leave \\n on end.\n\t\t\t}\n\t\t\tswitch (section) {\n\t\t\t\tcase \"notes\":\n\t\t\t\t\tnotes = value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"type\":\n\t\t\t\t\ttestType = Enum.valueOf(GrammarType.class, value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"grammar\":\n\t\t\t\t\tgrammarName = getGrammarName(value.split(\"\\n\")[0]);\n\t\t\t\t\tgrammar = value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"slaveGrammar\":\n\t\t\t\t\tString gname = getGrammarName(value.split(\"\\n\")[0]);\n\t\t\t\t\tslaveGrammars.add(new Pair<>(gname, value));\n\t\t\t\tcase \"start\":\n\t\t\t\t\tstartRule = value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"input\":\n\t\t\t\t\tinput = value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"output\":\n\t\t\t\t\toutput = value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"errors\":\n\t\t\t\t\terrors = value;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"flags\":\n\t\t\t\t\tString[] flags = value.split(\"\\n\");\n\t\t\t\t\tfor (String f : flags) {\n\t\t\t\t\t\tString[] parts = f.split(\"=\", 2);\n\t\t\t\t\t\tswitch (parts[0]) {\n\t\t\t\t\t\t\tcase \"showDFA\":\n\t\t\t\t\t\t\t\tshowDFA = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"showDiagnosticErrors\":\n\t\t\t\t\t\t\t\tshowDiagnosticErrors = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"traceATN\":\n\t\t\t\t\t\t\t\ttraceATN = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"predictionMode\":\n\t\t\t\t\t\t\t\tpredictionMode = PredictionMode.valueOf(parts[1]);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"notBuildParseTree\":\n\t\t\t\t\t\t\t\tbuildParseTree = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"skip\":\n\t\t\t\t\tskipTargets = value.split(\"\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new RuntimeException(\"Unknown descriptor section ignored: \"+section);\n\t\t\t}\n\t\t}\n\t\treturn new RuntimeTestDescriptor(testType, name, notes, input, output, errors, startRule, grammarName, grammar,\n\t\t\t\tslaveGrammars, showDiagnosticErrors, traceATN, showDFA, predictionMode, buildParseTree, skipTargets, uri);\n\t}\n\n\t/** Get A, B, or C from:\n\t * \"lexer grammar A;\" \"grammar B;\" \"parser grammar C;\"\n\t */\n\tprivate static String getGrammarName(String grammarDeclLine) {\n\t\tint gi = grammarDeclLine.indexOf(\"grammar \");\n\t\tif ( gi<0 ) {\n\t\t\treturn \"<unknown grammar name>\";\n\t\t}\n\t\tgi += \"grammar \".length();\n\t\tint gsemi = grammarDeclLine.indexOf(';');\n\t\treturn grammarDeclLine.substring(gi, gsemi);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/RuntimeTestUtils.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.automata.ATNPrinter;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\n\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic abstract class RuntimeTestUtils {\n\tpublic static final String NewLine = System.getProperty(\"line.separator\");\n\tpublic static final String PathSeparator = System.getProperty(\"path.separator\");\n\tpublic static final String FileSeparator = System.getProperty(\"file.separator\");\n\tpublic static final String TempDirectory = System.getProperty(\"java.io.tmpdir\");\n\n\tpublic final static Path runtimePath;\n\tpublic final static Path runtimeTestsuitePath;\n\tpublic final static Path resourcePath;\n\n\tprivate final static Map<String, String> resourceCache = new HashMap<>();\n\tprivate static OSType detectedOS;\n\tprivate static Boolean isWindows;\n\n\tstatic {\n\t\tString locationPath = RuntimeTestUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();\n\t\tif (isWindows()) {\n\t\t\tlocationPath = locationPath.replaceFirst(\"/\", \"\");\n\t\t}\n\t\tPath potentialRuntimeTestsuitePath = Paths.get(locationPath, \"..\", \"..\").normalize().toAbsolutePath();\n\t\tPath potentialResourcePath = Paths.get(potentialRuntimeTestsuitePath.toString(), \"resources\");\n\n\t\tif (Files.exists(potentialResourcePath)) {\n\t\t\truntimeTestsuitePath = potentialRuntimeTestsuitePath;\n\t\t}\n\t\telse {\n\t\t\truntimeTestsuitePath = Paths.get(\"..\", \"runtime-testsuite\").normalize().toAbsolutePath();\n\t\t}\n\n\t\truntimePath = Paths.get(runtimeTestsuitePath.toString(), \"..\", \"runtime\").normalize().toAbsolutePath();\n\t\tresourcePath = Paths.get(runtimeTestsuitePath.toString(), \"resources\");\n\t}\n\n\tpublic static boolean isWindows() {\n\t\tif (isWindows == null) {\n\t\t\tisWindows = getOS() == OSType.Windows;\n\t\t}\n\n\t\treturn isWindows;\n\t}\n\n\tpublic static OSType getOS() {\n\t\tif (detectedOS == null) {\n\t\t\tString os = System.getProperty(\"os.name\", \"generic\").toLowerCase(Locale.ENGLISH);\n\t\t\tif (os.contains(\"mac\") || os.contains(\"darwin\")) {\n\t\t\t\tdetectedOS = OSType.Mac;\n\t\t\t}\n\t\t\telse if (os.contains(\"win\")) {\n\t\t\t\tdetectedOS = OSType.Windows;\n\t\t\t}\n\t\t\telse if (os.contains(\"nux\")) {\n\t\t\t\tdetectedOS = OSType.Linux;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdetectedOS = OSType.Unknown;\n\t\t\t}\n\t\t}\n\t\treturn detectedOS;\n\t}\n\n\tpublic static synchronized String getTextFromResource(String name) {\n\t\ttry {\n\t\t\tString text = resourceCache.get(name);\n\t\t\tif (text == null) {\n\t\t\t\tPath path = Paths.get(resourcePath.toString(), name);\n\t\t\t\ttext = new String(Files.readAllBytes(path));\n\t\t\t\tresourceCache.put(name, text);\n\t\t\t}\n\t\t\treturn text;\n\t\t}\n\t\tcatch (Exception ex) {\n\t\t\tthrow new RuntimeException(ex);\n\t\t}\n\t}\n\n\tpublic static void checkRuleATN(Grammar g, String ruleName, String expecting) {\n\t\tRule r = g.getRule(ruleName);\n\t\tATNState startState = g.getATN().ruleToStartState[r.index];\n\t\tATNPrinter serializer = new ATNPrinter(g, startState);\n\t\tString result = serializer.asString();\n\n\t\tassertEquals(expecting, result);\n\t}\n\n\tpublic static String joinLines(Object... args) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tfor (Object arg : args) {\n\t\t\tString str = arg.toString();\n\t\t\tresult.append(str);\n\t\t\tif (!str.endsWith(\"\\n\"))\n\t\t\t\tresult.append(\"\\n\");\n\t\t}\n\t\treturn result.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/RuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.java.JavaRuntimeTests;\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.antlr.v4.test.runtime.states.State;\nimport org.junit.jupiter.api.DynamicNode;\nimport org.junit.jupiter.api.TestFactory;\nimport org.junit.jupiter.api.parallel.Execution;\nimport org.junit.jupiter.api.parallel.ExecutionMode;\nimport org.stringtemplate.v4.*;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.*;\nimport java.util.stream.Stream;\n\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.joinLines;\nimport static org.junit.jupiter.api.Assertions.fail;\nimport static org.junit.jupiter.api.DynamicContainer.dynamicContainer;\nimport static org.junit.jupiter.api.DynamicTest.dynamicTest;\n\n/** This class represents runtime tests for specified runtime.\n *  It pulls data from {@link RuntimeTestDescriptor} and uses junit to trigger tests.\n *  The only functionality needed to execute a test is defined in {@link RuntimeRunner}.\n *  All the various test rig classes derived from this one.\n *  E.g., see {@link JavaRuntimeTests}.\n */\npublic abstract class RuntimeTests {\n\tprotected abstract RuntimeRunner createRuntimeRunner();\n\n\tprivate final static HashMap<String, RuntimeTestDescriptor[]> testDescriptors = new HashMap<>();\n\tprivate final static Map<String, STGroup> cachedTargetTemplates = new HashMap<>();\n\tprivate final static StringRenderer rendered = new StringRenderer();\n\n\tstatic {\n\t\tFile descriptorsDir = new File(Paths.get(RuntimeTestUtils.resourcePath.toString(), \"org/antlr/v4/test/runtime/descriptors\").toString());\n\t\tFile[] directoryListing = descriptorsDir.listFiles();\n\t\tassert directoryListing != null;\n\t\tfor (File directory : directoryListing) {\n\t\t\tString groupName = directory.getName();\n\t\t\tif (groupName.startsWith(\".\")) {\n\t\t\t\tcontinue; // Ignore service directories (like .DS_Store in Mac)\n\t\t\t}\n\n\t\t\tList<RuntimeTestDescriptor> descriptors = new ArrayList<>();\n\n\t\t\tFile[] descriptorFiles = directory.listFiles();\n\t\t\tassert descriptorFiles != null;\n\t\t\tfor (File descriptorFile : descriptorFiles) {\n\t\t\t\tString name = descriptorFile.getName().replace(\".txt\", \"\");\n\t\t\t\tif (name.startsWith(\".\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString text;\n\t\t\t\ttry {\n\t\t\t\t\ttext = new String(Files.readAllBytes(descriptorFile.toPath()));\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t\tdescriptors.add(RuntimeTestDescriptorParser.parse(name, text, descriptorFile.toURI()));\n\t\t\t}\n\n\t\t\ttestDescriptors.put(groupName, descriptors.toArray(new RuntimeTestDescriptor[0]));\n\t\t}\n\n\t\tfor (String key : CustomDescriptors.descriptors.keySet()) {\n\t\t\tRuntimeTestDescriptor[] descriptors = CustomDescriptors.descriptors.get(key);\n\t\t\tRuntimeTestDescriptor[] existedDescriptors = testDescriptors.putIfAbsent(key, descriptors);\n\t\t\tif (existedDescriptors != null) {\n\t\t\t\ttestDescriptors.put(key, Stream.concat(Arrays.stream(existedDescriptors), Arrays.stream(descriptors))\n\t\t\t\t\t\t.toArray(RuntimeTestDescriptor[]::new));\n\t\t\t}\n\t\t}\n\t}\n\n\t@TestFactory\n\t@Execution(ExecutionMode.CONCURRENT)\n\tpublic List<DynamicNode> runtimeTests() {\n\t\tList<DynamicNode> result = new ArrayList<>();\n\n\t\tfor (String group : testDescriptors.keySet()) {\n\t\t\tArrayList<DynamicNode> descriptorTests = new ArrayList<>();\n\t\t\tRuntimeTestDescriptor[] descriptors = testDescriptors.get(group);\n\t\t\tfor (RuntimeTestDescriptor descriptor : descriptors) {\n\t\t\t\tdescriptorTests.add(dynamicTest(descriptor.name, descriptor.uri, () -> {\n\t\t\t\t\ttry (RuntimeRunner runner = createRuntimeRunner()) {\n\t\t\t\t\t\tString errorMessage = test(descriptor, runner);\n\t\t\t\t\t\tif (errorMessage != null) {\n\t\t\t\t\t\t\trunner.setSaveTestDir(true);\n\t\t\t\t\t\t\tfail(joinLines(\"Test: \" + descriptor.name + \"; \" + errorMessage, \"Test directory: \" + runner.getTempDirPath()));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t}\n\n\t\t\tPath descriptorGroupPath = Paths.get(RuntimeTestUtils.resourcePath.toString(), \"descriptors\", group);\n\t\t\tresult.add(dynamicContainer(group, descriptorGroupPath.toUri(), Arrays.stream(descriptorTests.toArray(new DynamicNode[0]))));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate static String test(RuntimeTestDescriptor descriptor, RuntimeRunner runner) {\n\t\tString targetName = runner.getLanguage();\n\t\tif (descriptor.ignore(targetName)) {\n\t\t\tSystem.out.println(\"Ignore \" + descriptor);\n\t\t\treturn null;\n\t\t}\n\n\t\tFileUtils.mkdir(runner.getTempDirPath());\n\n\t\tString grammarName = descriptor.grammarName;\n\t\tString grammar = prepareGrammars(descriptor, runner);\n\n\t\tString lexerName, parserName;\n\t\tboolean useListenerOrVisitor;\n\t\tString superClass;\n\t\tif (descriptor.testType == GrammarType.Parser || descriptor.testType == GrammarType.CompositeParser) {\n\t\t\tlexerName = grammarName + \"Lexer\";\n\t\t\tparserName = grammarName + \"Parser\";\n\t\t\tuseListenerOrVisitor = true;\n\t\t\tif (targetName.equals(\"Java\")) {\n\t\t\t\tsuperClass = JavaRunner.runtimeTestParserName;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsuperClass = null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tlexerName = grammarName;\n\t\t\tparserName = null;\n\t\t\tuseListenerOrVisitor = false;\n\t\t\tif (targetName.equals(\"Java\")) {\n\t\t\t\tsuperClass = JavaRunner.runtimeTestLexerName;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsuperClass = null;\n\t\t\t}\n\t\t}\n\n\t\tRunOptions runOptions = new RunOptions(grammarName + \".g4\",\n\t\t\t\tgrammar,\n\t\t\t\tparserName,\n\t\t\t\tlexerName,\n\t\t\t\tuseListenerOrVisitor,\n\t\t\t\tuseListenerOrVisitor,\n\t\t\t\tdescriptor.startRule,\n\t\t\t\tdescriptor.input,\n\t\t\t\tfalse,\n\t\t\t\tdescriptor.showDiagnosticErrors,\n\t\t\t\tdescriptor.traceATN,\n\t\t\t\tdescriptor.showDFA,\n\t\t\t\tStage.Execute,\n\t\t\t\ttargetName,\n\t\t\t\tsuperClass,\n\t\t\t\tdescriptor.predictionMode,\n\t\t\t\tdescriptor.buildParseTree\n\t\t);\n\n\t\tState result = runner.run(runOptions);\n\n\t\treturn assertCorrectOutput(descriptor, targetName, result);\n\t}\n\n\tprivate static String prepareGrammars(RuntimeTestDescriptor descriptor, RuntimeRunner runner) {\n\t\tString targetName = runner.getLanguage();\n\n\t\tSTGroup targetTemplates;\n\t\tsynchronized (cachedTargetTemplates) {\n\t\t\ttargetTemplates = cachedTargetTemplates.get(targetName);\n\t\t\tif (targetTemplates == null) {\n\t\t\t\tClassLoader classLoader = RuntimeTests.class.getClassLoader();\n\t\t\t\tURL templates = classLoader.getResource(\"org/antlr/v4/test/runtime/templates/\" + targetName + \".test.stg\");\n\t\t\t\tassert templates != null;\n\t\t\t\ttargetTemplates = new STGroupFile(templates, \"UTF-8\", '<', '>');\n\t\t\t\ttargetTemplates.registerRenderer(String.class, rendered);\n\t\t\t\tcachedTargetTemplates.put(targetName, targetTemplates);\n\t\t\t}\n\t\t}\n\n\t\t// write out any slave grammars\n\t\tList<Pair<String, String>> slaveGrammars = descriptor.slaveGrammars;\n\t\tif (slaveGrammars != null) {\n\t\t\tfor (Pair<String, String> spair : slaveGrammars) {\n\t\t\t\tSTGroup g = new STGroup('<', '>');\n\t\t\t\tg.registerRenderer(String.class, rendered);\n\t\t\t\tg.importTemplates(targetTemplates);\n\t\t\t\tST grammarST = new ST(g, spair.b);\n\t\t\t\twriteFile(runner.getTempDirPath(), spair.a + \".g4\", grammarST.render());\n\t\t\t}\n\t\t}\n\n\t\tSTGroup g = new STGroup('<', '>');\n\t\tg.importTemplates(targetTemplates);\n\t\tg.registerRenderer(String.class, rendered);\n\t\tST grammarST = new ST(g, descriptor.grammar);\n\t\treturn grammarST.render();\n\t}\n\n\tpublic static String assertCorrectOutput(RuntimeTestDescriptor descriptor, String targetName, State state) {\n\t\tExecutedState executedState;\n\t\tif (state instanceof ExecutedState) {\n\t\t\texecutedState = (ExecutedState)state;\n\t\t\tif (executedState.exception != null) {\n\t\t\t\treturn state.getErrorMessage();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn state.getErrorMessage();\n\t\t}\n\n\t\tString expectedOutput = descriptor.output;\n\t\tString expectedParseErrors = descriptor.errors;\n\n\t\tboolean doesOutputEqualToExpected = executedState.output.equals(expectedOutput);\n\t\tif (!doesOutputEqualToExpected || !executedState.errors.equals(expectedParseErrors)) {\n\t\t\tString message;\n\t\t\tif (doesOutputEqualToExpected) {\n\t\t\t\tmessage = \"Parse output is as expected, but errors are not: \";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmessage = \"Parse output is incorrect: \" +\n\t\t\t\t\t\t\"expectedOutput:<\" + expectedOutput + \">; actualOutput:<\" + executedState.output + \">; \";\n\t\t\t}\n\n\t\t\treturn \"[\" + targetName + \":\" + descriptor.name + \"] \" +\n\t\t\t\t\tmessage +\n\t\t\t\t\t\"expectedParseErrors:<\" + expectedParseErrors + \">;\" +\n\t\t\t\t\t\"actualParseErrors:<\" + executedState.errors + \">.\";\n\t\t}\n\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/Stage.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\npublic enum Stage {\n\tGenerate,\n\tCompile,\n\tExecute\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/StreamReader.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\n\npublic final class StreamReader implements Runnable {\n\tprivate final StringBuilder buffer = new StringBuilder();\n\tprivate final BufferedReader in;\n\tprivate final Thread worker;\n\n\tpublic StreamReader(InputStream in) {\n\t\tthis.in = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8) );\n\t\tworker = new Thread(this);\n\t}\n\n\tpublic void start() {\n\t\tworker.start();\n\t}\n\n\t@Override\n\tpublic void run() {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tint c = in.read();\n\t\t\t\tif (c == -1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (c == '\\r') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbuffer.append((char) c);\n\t\t\t}\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tSystem.err.println(\"can't read output from process\");\n\t\t}\n\t}\n\n\t/** wait for the thread to finish */\n\tpublic void join() throws InterruptedException {\n\t\tworker.join();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn buffer.toString();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/TraceATN.java",
    "content": "package org.antlr.v4.test.runtime;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.antlr.v4.test.runtime.states.State;\nimport org.antlr.v4.test.runtime.swift.SwiftRunner;\nimport org.antlr.v4.tool.*;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\n\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.joinLines;\nimport static org.junit.jupiter.api.Assertions.fail;\n\n/** Run a lexer/parser and dump ATN debug/trace information\n *\n *  java org.antlr.v4.test.runtime.TraceATN [X.g4|XParser.g4 XLexer.g4] startRuleName -target [Java|Cpp|...] inputFileName\n *\n *\n * In preparation, run this so we get right jars before trying this script:\n *\n * cd ANTLR-ROOT-DIR\n * mvn install -DskipTests=true\n * cd runtime-tests\n * mvn install jar:test-jar -DskipTests=true\n *\n * Run shell script with\n *\n * scripts/traceatn.sh /tmp/JSON.g4 json /tmp/foo.json\n *\n * Here is scripts/traceatn.sh:\n *\n * export ANTLRJAR=/Users/parrt/.m2/repository/org/antlr/antlr4/4.11.2-SNAPSHOT/antlr4-4.11.2-SNAPSHOT-complete.jar\n * export TESTJAR=/Users/parrt/.m2/repository/org/antlr/antlr4-runtime-testsuite/4.11.2-SNAPSHOT/antlr4-runtime-testsuite-4.11.2-SNAPSHOT-tests.jar\n * java -classpath $ANTLRJAR:$TESTJAR org.antlr.v4.test.runtime.TraceATN $@\n */\npublic class TraceATN {\n\tprotected static class IgnoreTokenVocabGrammar extends Grammar {\n\t\tpublic IgnoreTokenVocabGrammar(String fileName,\n\t\t\t\t\t\t\t\t\t   String grammarText,\n\t\t\t\t\t\t\t\t\t   Grammar tokenVocabSource,\n\t\t\t\t\t\t\t\t\t   ANTLRToolListener listener)\n\t\t\t\tthrows RecognitionException\n\t\t{\n\t\t\tsuper(fileName, grammarText, tokenVocabSource, listener);\n\t\t}\n\n\t\t@Override\n\t\tpublic void importTokensFromTokensFile() {\n\t\t\t// don't try to import tokens files; must give me both grammars if split\n\t\t}\n\t}\n\n\tprotected String grammarFileName;\n\tprotected String parserGrammarFileName;\n\tprotected String lexerGrammarFileName;\n\tprotected String startRuleName;\n\tprotected String inputFileName;\n\tprotected String targetName = \"Java\";\n\tprotected String encoding;\n\n\tpublic TraceATN(String[] args) {\n\t\tif ( args.length < 2 ) {\n\t\t\tSystem.err.println(\"java org.antlr.v4.test.runtime.TraceATN [X.g4|XParser.g4 XLexer.g4] startRuleName\\n\" +\n\t\t\t\t\t\"    [-encoding encodingname] -target (Java|Cpp|...) input-filename\");\n\t\t\tSystem.err.println(\"Omitting input-filename makes program read from stdin.\");\n\t\t\treturn;\n\t\t}\n\t\tint i=0;\n\t\tgrammarFileName = args[i];\n\t\ti++;\n\t\tif ( args[i].endsWith(\".g4\") ) {\n\t\t\tparserGrammarFileName = grammarFileName;\n\t\t\tlexerGrammarFileName = args[i];\n\t\t\ti++;\n\t\t\tgrammarFileName = null;\n\n\t\t\tif ( parserGrammarFileName.toLowerCase().endsWith(\"lexer.g4\") ) { // swap\n\t\t\t\tString save = parserGrammarFileName;\n\t\t\t\tparserGrammarFileName = lexerGrammarFileName;\n\t\t\t\tlexerGrammarFileName = save;\n\t\t\t}\n\t\t}\n\t\tstartRuleName = args[i];\n\t\ti++;\n\t\twhile ( i<args.length ) {\n\t\t\tString arg = args[i];\n\t\t\ti++;\n\t\t\tif ( arg.charAt(0)!='-' ) { // input file name\n\t\t\t\tinputFileName = arg;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-encoding\") ) {\n\t\t\t\tif ( i>=args.length ) {\n\t\t\t\t\tSystem.err.println(\"missing encoding on -encoding\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tencoding = args[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-target\") ) {\n\t\t\t\tif ( i>=args.length ) {\n\t\t\t\t\tSystem.err.println(\"missing name on -target\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttargetName = args[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String test(RuntimeTestDescriptor descriptor, RuntimeRunner runner, String targetName) {\n\t\tFileUtils.mkdir(runner.getTempDirPath());\n\n\t\tString grammarName = descriptor.grammarName;\n\t\tString grammar = descriptor.grammar;\n\n\t\tString lexerName, parserName;\n\t\tboolean useListenerOrVisitor;\n\t\tString superClass;\n\t\tif (descriptor.testType == GrammarType.Parser || descriptor.testType == GrammarType.CompositeParser) {\n\t\t\tlexerName = grammarName + \"Lexer\";\n\t\t\tparserName = grammarName + \"Parser\";\n\t\t\tuseListenerOrVisitor = true;\n\t\t\tif ( targetName!=null && targetName.equals(\"Java\") ) {\n\t\t\t\tsuperClass = JavaRunner.runtimeTestParserName;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsuperClass = null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tlexerName = grammarName;\n\t\t\tparserName = null;\n\t\t\tuseListenerOrVisitor = false;\n\t\t\tif (targetName.equals(\"Java\")) {\n\t\t\t\tsuperClass = JavaRunner.runtimeTestLexerName;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsuperClass = null;\n\t\t\t}\n\t\t}\n\n\t\tRunOptions runOptions = new RunOptions(grammarName + \".g4\",\n\t\t\t\tgrammar,\n\t\t\t\tparserName,\n\t\t\t\tlexerName,\n\t\t\t\tuseListenerOrVisitor,\n\t\t\t\tuseListenerOrVisitor,\n\t\t\t\tdescriptor.startRule,\n\t\t\t\tdescriptor.input,\n\t\t\t\tfalse,\n\t\t\t\tdescriptor.showDiagnosticErrors,\n\t\t\t\tdescriptor.traceATN,\n\t\t\t\tdescriptor.showDFA,\n\t\t\t\tStage.Execute,\n\t\t\t\ttargetName,\n\t\t\t\tsuperClass,\n\t\t\t\tPredictionMode.LL,\n\t\t\t\ttrue\n\t\t);\n\n\t\tState result = runner.run(runOptions);\n\n\t\tExecutedState executedState;\n\t\tif (result instanceof ExecutedState) {\n\t\t\texecutedState = (ExecutedState)result;\n\t\t\tif (executedState.exception != null) {\n\t\t\t\treturn result.getErrorMessage();\n\t\t\t}\n\t\t\treturn executedState.output;\n\t\t}\n\t\telse {\n\t\t\treturn result.getErrorMessage();\n\t\t}\n\t}\n\n\tvoid execParse() throws Exception {\n\t\tif ( grammarFileName==null && (parserGrammarFileName==null && lexerGrammarFileName==null) ) {\n\t\t\tSystem.err.println(\"No grammar specified\");\n\t\t\treturn;\n\t\t}\n\n\t\tif ( inputFileName==null ) {\n\t\t\tSystem.err.println(\"No input file specified\");\n\t\t\treturn;\n\t\t}\n\n\t\tString grammarName =\n\t\t\t\tgrammarFileName.substring(grammarFileName.lastIndexOf('/')+1, grammarFileName.length());\n\t\tgrammarName = grammarName.substring(0, grammarName.indexOf(\".g4\"));\n\t\tif ( grammarFileName!=null ) {\n\t\t\tString grammar = new String(Files.readAllBytes(Paths.get(grammarFileName)));\n\n\t\t\tString input = new String(Files.readAllBytes(Paths.get(inputFileName)));\n\n\t\t\tRuntimeTestDescriptor descriptor = new RuntimeTestDescriptor(\n\t\t\t\t\tGrammarType.CompositeParser,\n\t\t\t\t\t\"TraceATN-\" + grammarFileName,\n\t\t\t\t\t\"\",\n\t\t\t\t\tinput,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"\",\n\t\t\t\t\tstartRuleName,\n\t\t\t\t\tgrammarName,\n\t\t\t\t\tgrammar,\n\t\t\t\t\tnull,\n\t\t\t\t\tfalse,\n\t\t\t\t\ttrue,\n\t\t\t\t\tfalse,\n\t\t\t\t\tPredictionMode.LL,\n\t\t\t\t\ttrue,\n\t\t\t\t\tnull,\n\t\t\t\t\tnull);\n\n\t\t\tRuntimeRunner runner = getRunner(targetName);\n\n\t\t\tString result = test(descriptor, runner, targetName);\n\t\t\tSystem.out.println(result);\n\t\t}\n\t}\n\n\tpublic static RuntimeRunner getRunner(String targetName) throws Exception {\n\t\tClass<?> cl = Class.forName(\"org.antlr.v4.test.runtime.\"+\n\t\t\t\ttargetName.toLowerCase() + \".\" + targetName + \"Runner\");\n\t\treturn (RuntimeRunner)cl.newInstance();\n\t}\n\n\tpublic static void main(String[] args) throws Exception {\n\t\tTraceATN I = new TraceATN(args);\n\t\tI.execParse();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/cpp/CppRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.cpp;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\nimport org.stringtemplate.v4.ST;\n\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.getOS;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.isWindows;\n\n/**\n * For my own information on I'm recording what I needed to do to get a unit test to compile and run in C++ on the Mac.\n * I got a segmentation violation and couldn't figure out how to get information about it, so I turned on debugging\n * and then figured out lldb enough to create this issue: https://github.com/antlr/antlr4/issues/3845 on a bug.\n *\n * cd ~/antlr/code/antlr4/runtime/Cpp\n * cmake . -D CMAKE_OSX_ARCHITECTURES=\"arm64; x86_64\" -DCMAKE_BUILD_TYPE=Debug\n * make -j 8\n *\n * In test dir with generated test code:\n *\n * clang++ -g -std=c++17 -I /Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/src -L. -lantlr4-runtime *.cpp\n * ./a.out input\n *\n * $ lldb ./a.out input\n * (lldb) run\n * ... crash ...\n * (lldb) thread backtrace\n */\npublic class CppRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"Cpp\";\n\t}\n\n\t@Override\n\tpublic String getTitleName() { return \"C++\"; }\n\n\tprivate static final String runtimeSourcePath;\n\tprivate static final String runtimeBinaryPath;\n\tprivate static final String runtimeLibraryFileName;\n\tprivate static String compilerName;\n\tprivate static final String visualStudioProjectContent;\n\tprivate static final Map<String, String> environment;\n\n\tstatic {\n\t\tString runtimePath = getRuntimePath(\"Cpp\");\n\t\truntimeSourcePath = Paths.get(runtimePath, \"runtime\", \"src\").toString();\n\n\t\tenvironment = new HashMap<>();\n\t\tif (isWindows()) {\n\t\t\truntimeBinaryPath = Paths.get(runtimePath, \"runtime\", \"bin\", \"vs-2022\", \"x64\", \"Release DLL\").toString();\n\t\t\truntimeLibraryFileName = Paths.get(runtimeBinaryPath, \"antlr4-runtime.dll\").toString();\n\t\t\tString path = System.getenv(\"PATH\");\n\t\t\tenvironment.put(\"PATH\", path == null ? runtimeBinaryPath : path + \";\" + runtimeBinaryPath);\n\t\t}\n\t\telse {\n\t\t\truntimeBinaryPath = Paths.get(runtimePath, \"dist\").toString();\n\t\t\truntimeLibraryFileName = Paths.get(runtimeBinaryPath,\n\t\t\t\t\t\"libantlr4-runtime.\" + (getOS() == OSType.Mac ? \"dylib\" : \"so\")).toString();\n\t\t\tenvironment.put(\"LD_PRELOAD\", runtimeLibraryFileName);\n\t\t}\n\n\t\tif (isWindows()) {\n\t\t\tvisualStudioProjectContent = RuntimeTestUtils.getTextFromResource(\"org/antlr/v4/test/runtime/helpers/Test.vcxproj.stg\");\n\t\t} else {\n\t\t\tvisualStudioProjectContent = null;\n\t\t}\n\t}\n\n\t@Override\n\tprotected String getCompilerName() {\n\t\tif (compilerName == null) {\n\t\t\tif (isWindows()) {\n\t\t\t\tcompilerName = \"MSBuild\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcompilerName = \"clang++\";\n\t\t\t}\n\t\t}\n\n\t\treturn compilerName;\n\t}\n\n\t@Override\n\tprotected void initRuntime(RunOptions runOptions) throws Exception {\n\t\tString runtimePath = getRuntimePath();\n\n\t\tif (isWindows()) {\n\t\t\tString[] command = {\n\t\t\t\tgetCompilerPath(), \"antlr4cpp-vs2022.vcxproj\", \"/p:configuration=Release DLL\", \"/p:platform=x64\"\n\t\t\t};\n\n\t\t\trunCommand(command, runtimePath + \"\\\\runtime\",\"build c++ ANTLR runtime using MSBuild\");\n\t\t}\n\t\telse {\n\t\t\t// cmake ignores default of OFF and must explicitly say yes or no on tracing arg. grrr...\n\t\t\tString trace = \"-DTRACE_ATN=\"+(runOptions.traceATN?\"ON\":\"OFF\");\n\t\t\tString[] command = {\"cmake\", \".\", trace, \"-DCMAKE_BUILD_TYPE=Release\"};\n\t\t\trunCommand(command, runtimePath, \"run cmake on antlr c++ runtime\");\n\n\t\t\tcommand = new String[] {\"make\", \"-j\", Integer.toString(Runtime.getRuntime().availableProcessors())};\n\t\t\trunCommand(command, runtimePath, \"run make on antlr c++ runtime\");\n\t\t}\n\t}\n\n\t@Override\n\tprotected CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\tif (isWindows()) {\n\t\t\twriteVisualStudioProjectFile(runOptions.grammarName, runOptions.lexerName, runOptions.parserName,\n\t\t\t\t\trunOptions.useListener, runOptions.useVisitor);\n\t\t}\n\n\t\tException exception = null;\n\t\ttry {\n\t\t\tif (!isWindows()) {\n\t\t\t\tString[] linkCommand = new String[]{\"ln\", \"-s\", runtimeLibraryFileName};\n\t\t\t\trunCommand(linkCommand, getTempDirPath(), \"sym link C++ runtime\");\n\t\t\t}\n\n\t\t\tList<String> buildCommand = new ArrayList<>();\n\t\t\tbuildCommand.add(getCompilerPath());\n\t\t\tif (isWindows()) {\n\t\t\t\tbuildCommand.add(getTestFileName() + \".vcxproj\");\n\t\t\t\tbuildCommand.add(\"/p:configuration=Release\");\n\t\t\t\tbuildCommand.add(\"/p:platform=x64\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbuildCommand.add(\"-std=c++17\");\n\t\t\t\tbuildCommand.add(\"-I\");\n\t\t\t\tbuildCommand.add(runtimeSourcePath);\n\t\t\t\tbuildCommand.add(\"-L.\");\n\t\t\t\tbuildCommand.add(\"-lantlr4-runtime\");\n\t\t\t\tbuildCommand.add(\"-pthread\");\n\t\t\t\tbuildCommand.add(\"-o\");\n\t\t\t\tbuildCommand.add(getTestFileName() + \".out\");\n\t\t\t\tbuildCommand.add(getTestFileWithExt());\n\t\t\t\tbuildCommand.addAll(generatedState.generatedFiles.stream().map(file -> file.name).collect(Collectors.toList()));\n\t\t\t}\n\n\t\t\trunCommand(buildCommand.toArray(new String[0]), getTempDirPath(), \"build test c++ binary\");\n\t\t}\n\t\tcatch (Exception ex) {\n\t\t\texception = ex;\n\t\t}\n\t\treturn new CompiledState(generatedState, exception);\n\t}\n\n\tprivate void writeVisualStudioProjectFile(String grammarName, String lexerName, String parserName,\n\t\t\t\t\t\t\t\t\t\t\t  boolean useListener, boolean useVisitor) {\n\t\tST projectFileST = new ST(visualStudioProjectContent);\n\t\tprojectFileST.add(\"runtimeSourcePath\", runtimeSourcePath);\n\t\tprojectFileST.add(\"runtimeBinaryPath\", runtimeBinaryPath);\n\t\tprojectFileST.add(\"grammarName\", grammarName);\n\t\tprojectFileST.add(\"lexerName\", lexerName);\n\t\tprojectFileST.add(\"parserName\", parserName);\n\t\tprojectFileST.add(\"useListener\", useListener);\n\t\tprojectFileST.add(\"useVisitor\", useVisitor);\n\t\twriteFile(getTempDirPath(), \"Test.vcxproj\", projectFileST.render());\n\t}\n\n\t@Override\n\tpublic String getRuntimeToolName() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getExecFileName() {\n\t\treturn Paths.get(getTempDirPath(), getTestFileName() + \".\" + (isWindows() ? \"exe\" : \"out\")).toString();\n\t}\n\n\t@Override\n\tpublic Map<String, String> getExecEnvironment() {\n\t\treturn environment;\n\t}\n}\n\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/cpp/CppRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.cpp;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class CppRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new CppRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/csharp/CSharpRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.csharp;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\nimport org.stringtemplate.v4.ST;\n\nimport java.nio.file.Paths;\n\nimport static org.antlr.v4.test.runtime.FileUtils.mkdir;\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\n\npublic class CSharpRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getLanguage() { return \"CSharp\"; }\n\n\t@Override\n\tpublic String getTitleName() { return \"C#\"; }\n\n\t@Override\n\tpublic String getExtension() { return \"cs\"; }\n\n\t@Override\n\tpublic String getRuntimeToolName() { return \"dotnet\"; }\n\n\t@Override\n\tpublic String getExecFileName() { return getTestFileName() + \".dll\"; }\n\n\tprivate final static String testProjectFileName = \"Antlr4.Test.csproj\";\n\tprivate final static String cSharpAntlrRuntimeDllName =\n\t\t\tPaths.get(getCachePath(\"CSharp\"), \"Antlr4.Runtime.Standard.dll\").toString();\n\n\tprivate final static String cSharpTestProjectContent;\n\n\tstatic {\n\t\tST projectTemplate = new ST(RuntimeTestUtils.getTextFromResource(\"org/antlr/v4/test/runtime/helpers/Antlr4.Test.csproj.stg\"));\n\t\tprojectTemplate.add(\"runtimeLibraryPath\", cSharpAntlrRuntimeDllName);\n\t\tcSharpTestProjectContent = projectTemplate.render();\n\t}\n\n\t@Override\n\tprotected void initRuntime(RunOptions runOptions) throws Exception {\n\t\tString cachePath = getCachePath();\n\t\tmkdir(cachePath);\n\t\tString projectPath = Paths.get(getRuntimePath(), \"src\", \"Antlr4.csproj\").toString();\n\t\tString[] args = new String[]{getRuntimeToolPath(), \"build\", projectPath, \"-c\", \"Release\", \"-o\", cachePath};\n\t\trunCommand(args, cachePath, \"build \" + getTitleName() + \" ANTLR runtime\");\n\t}\n\n\t@Override\n\tpublic CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\tException exception = null;\n\t\ttry {\n\t\t\twriteFile(getTempDirPath(), testProjectFileName, cSharpTestProjectContent);\n\t\t\trunCommand(new String[]{getRuntimeToolPath(), \"build\", testProjectFileName, \"-c\", \"Release\"}, getTempDirPath(),\n\t\t\t\t\t\"build C# test binary\");\n\t\t} catch (Exception e) {\n\t\t\texception = e;\n\t\t}\n\t\treturn new CompiledState(generatedState, exception);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/csharp/CSharpRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.csharp;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class CSharpRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new CSharpRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/dart/DartRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.dart;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\nimport org.stringtemplate.v4.ST;\n\nimport java.io.*;\n\nimport static org.antlr.v4.test.runtime.FileUtils.*;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.FileSeparator;\n\npublic class DartRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"Dart\";\n\t}\n\n\tprivate static String cacheDartPackageConfig;\n\n\t@Override\n\tprotected void initRuntime(RunOptions runOptions) throws Exception {\n\t\tString cachePath = getCachePath();\n\t\tmkdir(cachePath);\n\n\t\tST projectTemplate = new ST(RuntimeTestUtils.getTextFromResource(\"org/antlr/v4/test/runtime/helpers/pubspec.yaml.stg\"));\n\t\tprojectTemplate.add(\"runtimePath\", getRuntimePath());\n\n\t\twriteFile(cachePath, \"pubspec.yaml\", projectTemplate.render());\n\n\t\trunCommand(new String[]{getRuntimeToolPath(), \"pub\", \"get\"}, cachePath);\n\n\t\tcacheDartPackageConfig = readFile(cachePath + FileSeparator + \".dart_tool\", \"package_config.json\");\n\t}\n\n\t@Override\n\tprotected CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\tString dartToolDirPath = new File(getTempDirPath(), \".dart_tool\").getAbsolutePath();\n\t\tmkdir(dartToolDirPath);\n\t\twriteFile(dartToolDirPath, \"package_config.json\", cacheDartPackageConfig);\n\n\t\treturn new CompiledState(generatedState, null);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/dart/DartRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.dart;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class DartRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new DartRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/go/GoRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.go;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\n\nimport java.io.*;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.*;\n\nimport static org.antlr.v4.test.runtime.FileUtils.*;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.FileSeparator;\n\npublic class GoRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"Go\";\n\t}\n\n\t@Override\n\tpublic String getLexerSuffix() {\n\t\treturn \"_lexer\";\n\t}\n\n\t@Override\n\tpublic String getParserSuffix() {\n\t\treturn \"_parser\";\n\t}\n\n\t@Override\n\tpublic String getBaseListenerSuffix() {\n\t\treturn \"_base_listener\";\n\t}\n\n\t@Override\n\tpublic String getListenerSuffix() {\n\t\treturn \"_listener\";\n\t}\n\n\t@Override\n\tpublic String getBaseVisitorSuffix() {\n\t\treturn \"_base_visitor\";\n\t}\n\n\t@Override\n\tpublic String getVisitorSuffix() {\n\t\treturn \"_visitor\";\n\t}\n\n\t@Override\n\tprotected String grammarNameToFileName(String grammarName) {\n\t\treturn grammarName.toLowerCase();\n\t}\n\n\t@Override\n\tpublic String[] getExtraRunArgs() {\n\t\treturn new String[]{\"run\"};\n\t}\n\n\tprivate static final String GoRuntimeImportPath = \"github.com/antlr4-go/antlr/v4\";\n\n\tprivate final static Map<String, String> environment;\n\n\tprivate static String cachedGoMod;\n\tprivate static String cachedGoSum;\n\tprivate static ArrayList<String> options = new ArrayList<>();\n\n\tstatic {\n\t\tenvironment = new HashMap<>();\n\t\tenvironment.put(\"GOWORK\", \"off\");\n\t}\n\n\t@Override\n\tprotected void initRuntime(RunOptions runOptions) throws Exception {\n\t\tString cachePath = getCachePath();\n\t\tmkdir(cachePath);\n\t\tPath runtimeFilesPath = Paths.get(getRuntimePath(\"Go\"), \"antlr\", \"v4\");\n\t\tString runtimeToolPath = getRuntimeToolPath();\n\t\tFile goModFile = new File(cachePath, \"go.mod\");\n\t\tif (goModFile.exists())\n\t\t\tif (!goModFile.delete())\n\t\t\t\tthrow new IOException(\"Can't delete \" + goModFile);\n\t\tProcessor.run(new String[]{runtimeToolPath, \"mod\", \"init\", \"test\"}, cachePath, environment);\n\t\tProcessor.run(new String[]{runtimeToolPath, \"mod\", \"edit\",\n\t\t\t\t\"-replace=\" + GoRuntimeImportPath + \"=\" + runtimeFilesPath}, cachePath, environment);\n\t\tProcessor.run(new String[]{runtimeToolPath, \"mod\", \"edit\",\n\t\t\t\t\"-require=\" + GoRuntimeImportPath + \"@v4.0.0\"}, cachePath, environment);\n\t\tcachedGoMod = readFile(cachePath + FileSeparator, \"go.mod\");\n\t}\n\n\t@Override\n\tprotected String grammarParseRuleToRecognizerName(String startRuleName) {\n\t\tif (startRuleName == null || startRuleName.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// The rule name start is now translated to Start_ at runtime to avoid clashes with labels.\n\t\t// Some tests use start as the first rule name, and we must cater for that\n\t\t//\n\t\tString rn = startRuleName.substring(0, 1).toUpperCase() + startRuleName.substring(1);\n\t\tswitch (rn) {\n\t\t\tcase \"Start\":\n\t\t\tcase \"End\":\n\t\t\tcase \"Exception\":\n\t\t\t\trn += \"_\";\n\t\t\tdefault:\n\t\t}\n\t\treturn rn;\n\t}\n\n\t@Override\n\tprotected List<String> getTargetToolOptions(RunOptions ro) {\n\t\t// Unfortunately this cannot be cached because all the synchronization is out of whack, and\n\t\t// we end up return the options before they are populated. I prefer to make this small change\n\t\t// at the expense of an object rather than try to change teh synchronized initialization, which is\n\t\t// very fragile.\n\t\t// Also, the options may need to change in the future according to the test options. This is safe\n\t\tArrayList<String> options = new ArrayList<>();\n\t\toptions.add(\"-o\");\n\t\toptions.add(tempTestDir.resolve(\"parser\").toString());\n\t\treturn options;\n\t}\n\n\t@Override\n\tprotected CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\t// We have already created a suitable go.mod file, though it may need to have go mod tidy run on it one time\n\t\t//\n\t\twriteFile(getTempDirPath(), \"go.mod\", cachedGoMod);\n\n\t\t// We need to run a go mod tidy once, now that we have source code. This will generate a valid go.sum file and\n\t\t// recognize the indirect requirements in the go.mod file. Then we re-cache the go.mod and cache\n\t\t// the go.sum and therefore save sparking a new process for all the remaining go tests. This is probably\n\t\t// a race condition as these tests are run in parallel, but it does not matter as they are all going to\n\t\t// generate the same go.mod and go.sum file anyway.\n\t\t//\n\t\tException ex = null;\n\t\tif (cachedGoSum == null) {\n\t\t\ttry {\n\t\t\t\tProcessor.run(new String[]{getRuntimeToolPath(), \"mod\", \"tidy\"}, getTempDirPath(), environment);\n\t\t\t} catch (InterruptedException | IOException e) {\n\t\t\t\tex = e;\n\t\t\t}\n\t\t\tcachedGoMod = readFile(getTempDirPath() + FileSeparator, \"go.mod\");\n\t\t\tcachedGoSum = readFile(getTempDirPath() + FileSeparator, \"go.sum\");\n\t\t}\n\n\t\t// We can now write the go.sum file, which will allow the go compiler to build the module\n\t\t//\n\t\twriteFile(getTempDirPath(), \"go.sum\", cachedGoSum);\n\n\t\treturn new CompiledState(generatedState, ex);\n\t}\n\n\t@Override\n\tpublic Map<String, String> getExecEnvironment() {\n\t\treturn environment;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/go/GoRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.go;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class GoRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new GoRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/JavaRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.java;\n\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.atn.ParserATNSimulator;\nimport org.antlr.v4.runtime.atn.ProfilingATNSimulator;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.ParseTreeWalker;\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.java.helpers.CustomStreamErrorListener;\nimport org.antlr.v4.test.runtime.java.helpers.RuntimeTestLexer;\nimport org.antlr.v4.test.runtime.java.helpers.RuntimeTestParser;\nimport org.antlr.v4.test.runtime.java.helpers.TreeShapeListener;\nimport org.antlr.v4.test.runtime.states.*;\n\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.ToolProvider;\nimport java.io.*;\nimport java.lang.reflect.Method;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport static org.antlr.v4.test.runtime.FileUtils.replaceInFile;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.PathSeparator;\n\npublic class JavaRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"Java\";\n\t}\n\n\tpublic static final String classPath = System.getProperty(\"java.class.path\");\n\n\tpublic static final String runtimeTestLexerName = \"org.antlr.v4.test.runtime.java.helpers.RuntimeTestLexer\";\n\tpublic static final String runtimeTestParserName = \"org.antlr.v4.test.runtime.java.helpers.RuntimeTestParser\";\n\n\tpublic static final String runtimeHelpersPath = Paths.get(RuntimeTestUtils.runtimeTestsuitePath.toString(),\n\t\t\"test\", \"org\", \"antlr\", \"v4\", \"test\", \"runtime\", \"java\", \"helpers\").toString();\n\n\tprivate static JavaCompiler compiler;\n\n\tprivate final static DiagnosticErrorListener DiagnosticErrorListenerInstance = new DiagnosticErrorListener();\n\n\tpublic JavaRunner(Path tempDir, boolean saveTestDir) {\n\t\tsuper(tempDir, saveTestDir);\n\t}\n\n\tpublic JavaRunner() {\n\t\tsuper();\n\t}\n\n\t@Override\n\tprotected void initRuntime(RunOptions runOptions) {\n\t\tcompiler = ToolProvider.getSystemJavaCompiler();\n\t}\n\n\t@Override\n\tprotected String getCompilerName() {\n\t\treturn \"javac\";\n\t}\n\n\t@Override\n\tprotected void writeInputFile(RunOptions runOptions) {}\n\n\t@Override\n\tprotected void writeRecognizerFile(RunOptions runOptions) {}\n\n\t@Override\n\tprotected JavaCompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\tString tempTestDir = getTempDirPath();\n\n\t\tList<GeneratedFile> generatedFiles = generatedState.generatedFiles;\n\t\tGeneratedFile firstFile = generatedFiles.get(0);\n\n\t\tif (!firstFile.isParser) {\n\t\t\ttry {\n\t\t\t\t// superClass for combined grammar generates the same extends base class for Lexer and Parser\n\t\t\t\t// So, for lexer it should be replaced on correct base lexer class\n\t\t\t\treplaceInFile(Paths.get(getTempDirPath(), firstFile.name),\n\t\t\t\t\t\t\"extends \" + runtimeTestParserName + \" {\",\n\t\t\t\t\t\t\"extends \" + runtimeTestLexerName + \" {\");\n\t\t\t} catch (IOException e) {\n\t\t\t\treturn new JavaCompiledState(generatedState, null, null, null, e);\n\t\t\t}\n\t\t}\n\n\t\tClassLoader loader = null;\n\t\tClass<? extends Lexer> lexer = null;\n\t\tClass<? extends Parser> parser = null;\n\t\tException exception = null;\n\n\t\ttry {\n\t\t\tStandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);\n\n\t\t\tClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();\n\n\t\t\tList<File> files = new ArrayList<>();\n\t\t\tif (runOptions.lexerName != null) {\n\t\t\t\tfiles.add(new File(tempTestDir, runOptions.lexerName + \".java\"));\n\t\t\t}\n\t\t\tif (runOptions.parserName != null) {\n\t\t\t\tfiles.add(new File(tempTestDir, runOptions.parserName + \".java\"));\n\t\t\t}\n\n\t\t\tIterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);\n\n\t\t\tIterable<String> compileOptions =\n\t\t\t\t\tArrays.asList(\"-g\", \"-source\", \"1.8\", \"-target\", \"1.8\", \"-implicit:class\", \"-Xlint:-options\", \"-d\",\n\t\t\t\t\t\t\ttempTestDir, \"-cp\", tempTestDir + PathSeparator + runtimeHelpersPath + PathSeparator + classPath);\n\n\t\t\tJavaCompiler.CompilationTask task =\n\t\t\t\t\tcompiler.getTask(null, fileManager, null, compileOptions, null,\n\t\t\t\t\t\t\tcompilationUnits);\n\t\t\ttask.call();\n\n\t\t\tloader = new URLClassLoader(new URL[]{new File(tempTestDir).toURI().toURL()}, systemClassLoader);\n\t\t\tif (runOptions.lexerName != null) {\n\t\t\t\tlexer = loader.loadClass(runOptions.lexerName).asSubclass(Lexer.class);\n\t\t\t}\n\t\t\tif (runOptions.parserName != null) {\n\t\t\t\tparser = loader.loadClass(runOptions.parserName).asSubclass(Parser.class);\n\t\t\t}\n\t\t} catch (Exception ex) {\n\t\t\texception = ex;\n\t\t}\n\n\t\treturn new JavaCompiledState(generatedState, loader, lexer, parser, exception);\n\t}\n\n\t@Override\n\tprotected ExecutedState execute(RunOptions runOptions, CompiledState compiledState) {\n\t\tJavaCompiledState javaCompiledState = (JavaCompiledState) compiledState;\n\t\tString output = null;\n\t\tString errors = null;\n\t\tParseTree parseTree = null;\n\t\tException exception = null;\n\n\t\ttry {\n\t\t\tInMemoryStreamHelper outputStreamHelper = InMemoryStreamHelper.initialize();\n\t\t\tInMemoryStreamHelper errorsStreamHelper = InMemoryStreamHelper.initialize();\n\n\t\t\tPrintStream outStream = new PrintStream(outputStreamHelper.pipedOutputStream);\n\t\t\tCustomStreamErrorListener errorListener = new CustomStreamErrorListener(new PrintStream(errorsStreamHelper.pipedOutputStream));\n\n\t\t\tCommonTokenStream tokenStream;\n\t\t\tRuntimeTestLexer lexer;\n\t\t\tif (runOptions.lexerName != null) {\n\t\t\t\tlexer = (RuntimeTestLexer) javaCompiledState.initializeLexer(runOptions.input);\n\t\t\t\tlexer.setOutStream(outStream);\n\t\t\t\tlexer.removeErrorListeners();\n\t\t\t\tlexer.addErrorListener(errorListener);\n\t\t\t\ttokenStream = new CommonTokenStream(lexer);\n\t\t\t} else {\n\t\t\t\tlexer = null;\n\t\t\t\ttokenStream = null;\n\t\t\t}\n\n\t\t\tif (runOptions.parserName != null) {\n\t\t\t\tRuntimeTestParser parser = (RuntimeTestParser) javaCompiledState.initializeParser(tokenStream);\n\t\t\t\tparser.setOutStream(outStream);\n\t\t\t\tparser.removeErrorListeners();\n\t\t\t\tparser.addErrorListener(errorListener);\n\n\t\t\t\tif (runOptions.showDiagnosticErrors) {\n\t\t\t\t\tparser.addErrorListener(DiagnosticErrorListenerInstance);\n\t\t\t\t}\n\n\t\t\t\tif (runOptions.traceATN) {\n\t\t\t\t\t// Setting trace_atn_sim isn't thread-safe,\n\t\t\t\t\t// But it's used only in helper TraceATN that is not integrated into tests infrastructure\n\t\t\t\t\tParserATNSimulator.trace_atn_sim = true;\n\t\t\t\t}\n\n\t\t\t\tProfilingATNSimulator profiler = null;\n\t\t\t\tif (runOptions.profile) {\n\t\t\t\t\tprofiler = new ProfilingATNSimulator(parser);\n\t\t\t\t\tparser.setInterpreter(profiler);\n\t\t\t\t}\n\t\t\t\tparser.getInterpreter().setPredictionMode(runOptions.predictionMode);\n\t\t\t\tparser.setBuildParseTree(runOptions.buildParseTree);\n\n\t\t\t\tMethod startRule;\n\t\t\t\tObject[] args = null;\n\t\t\t\ttry {\n\t\t\t\t\tstartRule = javaCompiledState.parser.getMethod(runOptions.startRuleName);\n\t\t\t\t} catch (NoSuchMethodException noSuchMethodException) {\n\t\t\t\t\t// try with int _p arg for recursive func\n\t\t\t\t\tstartRule = javaCompiledState.parser.getMethod(runOptions.startRuleName, int.class);\n\t\t\t\t\targs = new Integer[]{0};\n\t\t\t\t}\n\n\t\t\t\tparseTree = (ParserRuleContext) startRule.invoke(parser, args);\n\n\t\t\t\tif (runOptions.profile) {\n\t\t\t\t\toutStream.println(Arrays.toString(profiler.getDecisionInfo()));\n\t\t\t\t}\n\n\t\t\t\tParseTreeWalker.DEFAULT.walk(TreeShapeListener.INSTANCE, parseTree);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tassert tokenStream != null;\n\t\t\t\ttokenStream.fill();\n\t\t\t\tfor (Object t : tokenStream.getTokens()) {\n\t\t\t\t\toutStream.println(t);\n\t\t\t\t}\n\t\t\t\tif (runOptions.showDFA) {\n\t\t\t\t\toutStream.print(lexer.getInterpreter().getDFA(Lexer.DEFAULT_MODE).toLexerString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput = outputStreamHelper.close();\n\t\t\terrors = errorsStreamHelper.close();\n\t\t} catch (Exception ex) {\n\t\t\texception = ex;\n\t\t}\n\t\treturn new JavaExecutedState(javaCompiledState, output, errors, parseTree, exception);\n\t}\n\n\tstatic class InMemoryStreamHelper {\n\t\tprivate final PipedOutputStream pipedOutputStream;\n\t\tprivate final StreamReader streamReader;\n\n\t\tprivate InMemoryStreamHelper(PipedOutputStream pipedOutputStream, StreamReader streamReader) {\n\t\t\tthis.pipedOutputStream = pipedOutputStream;\n\t\t\tthis.streamReader = streamReader;\n\t\t}\n\n\t\tpublic static InMemoryStreamHelper initialize() throws IOException {\n\t\t\tPipedInputStream pipedInputStream = new PipedInputStream();\n\t\t\tPipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream);\n\t\t\tStreamReader stdoutReader = new StreamReader(pipedInputStream);\n\t\t\tstdoutReader.start();\n\t\t\treturn new InMemoryStreamHelper(pipedOutputStream, stdoutReader);\n\t\t}\n\n\t\tpublic String close() throws InterruptedException, IOException {\n\t\t\tpipedOutputStream.close();\n\t\t\tstreamReader.join();\n\t\t\treturn streamReader.toString();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/JavaRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.java;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class JavaRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new JavaRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/TestCharStreams.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.java;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CharStreams;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.io.TempDir;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.io.Reader;\nimport java.nio.channels.SeekableByteChannel;\nimport java.nio.charset.CharacterCodingException;\nimport java.nio.charset.Charset;\nimport java.nio.charset.CodingErrorAction;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\n\npublic class TestCharStreams {\n\t@Test\n\tpublic void fromBMPStringHasExpectedSize() {\n\t\tCharStream s = CharStreams.fromString(\"hello\");\n\t\tassertEquals(5, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello\", s.toString());\n\t}\n\n\t@Test\n\tpublic void fromSMPStringHasExpectedSize() {\n\t\tCharStream s = CharStreams.fromString(\n\t\t\t\t\"hello \\uD83C\\uDF0E\");\n\t\tassertEquals(7, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t}\n\n\t@Test\n\tpublic void fromBMPUTF8PathHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath test = new File(tempDir.toString(), \"test\").toPath();\n\t\tFiles.write(test, \"hello\".getBytes(StandardCharsets.UTF_8));\n\t\tCharStream s = CharStreams.fromPath(test);\n\t\tassertEquals(5, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello\", s.toString());\n\t\tassertEquals(test.toString(), s.getSourceName());\n\t}\n\n\t@Test\n\tpublic void fromSMPUTF8PathHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(StandardCharsets.UTF_8));\n\t\tCharStream s = CharStreams.fromPath(p);\n\t\tassertEquals(7, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\tassertEquals(p.toString(), s.getSourceName());\n\t}\n\n\t@Test\n\tpublic void fromBMPUTF8InputStreamHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello\".getBytes(StandardCharsets.UTF_8));\n\t\ttry (InputStream is = Files.newInputStream(p)) {\n\t\t\tCharStream s = CharStreams.fromStream(is);\n\t\t\tassertEquals(5, s.size());\n\t\t\tassertEquals(0, s.index());\n\t\t\tassertEquals(\"hello\", s.toString());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromSMPUTF8InputStreamHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(StandardCharsets.UTF_8));\n\t\ttry (InputStream is = Files.newInputStream(p)) {\n\t\t\tCharStream s = CharStreams.fromStream(is);\n\t\t\tassertEquals(7, s.size());\n\t\t\tassertEquals(0, s.index());\n\t\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromBMPUTF8ChannelHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello\".getBytes(StandardCharsets.UTF_8));\n\t\ttry (SeekableByteChannel c = Files.newByteChannel(p)) {\n\t\t\tCharStream s = CharStreams.fromChannel(\n\t\t\t\t\tc, 4096, CodingErrorAction.REPLACE, \"foo\");\n\t\t\tassertEquals(5, s.size());\n\t\t\tassertEquals(0, s.index());\n\t\t\tassertEquals(\"hello\", s.toString());\n\t\t\tassertEquals(\"foo\", s.getSourceName());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromSMPUTF8ChannelHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(StandardCharsets.UTF_8));\n\t\ttry (SeekableByteChannel c = Files.newByteChannel(p)) {\n\t\t\tCharStream s = CharStreams.fromChannel(\n\t\t\t\t\tc, 4096, CodingErrorAction.REPLACE, \"foo\");\n\t\t\tassertEquals(7, s.size());\n\t\t\tassertEquals(0, s.index());\n\t\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\t\tassertEquals(\"foo\", s.getSourceName());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromInvalidUTF8BytesChannelReplacesWithSubstCharInReplaceMode(@TempDir Path tempDir)\n\t\tthrows Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tbyte[] toWrite = new byte[] { (byte)0xCA, (byte)0xFE, (byte)0xFE, (byte)0xED };\n\t\tFiles.write(p, toWrite);\n\t\ttry (SeekableByteChannel c = Files.newByteChannel(p)) {\n\t\t\tCharStream s = CharStreams.fromChannel(\n\t\t\t\t\tc, 4096, CodingErrorAction.REPLACE, \"foo\");\n\t\t\tassertEquals(4, s.size());\n\t\t\tassertEquals(0, s.index());\n\t\t\tassertEquals(\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\", s.toString());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromInvalidUTF8BytesThrowsInReportMode(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tbyte[] toWrite = new byte[] { (byte)0xCA, (byte)0xFE };\n\t\tFiles.write(p, toWrite);\n\t\ttry (SeekableByteChannel c = Files.newByteChannel(p)) {\n\t\t\tassertThrows(\n\t\t\t\t\tCharacterCodingException.class,\n\t\t\t\t\t() -> CharStreams.fromChannel(c, 4096, CodingErrorAction.REPORT, \"foo\")\n\t\t\t);\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromSMPUTF8SequenceStraddlingBufferBoundary(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(StandardCharsets.UTF_8));\n\t\ttry (SeekableByteChannel c = Files.newByteChannel(p)) {\n\t\t\tCharStream s = CharStreams.fromChannel(\n\t\t\t\t\tc,\n\t\t\t\t\t// Note this buffer size ensures the SMP code point\n\t\t\t\t\t// straddles the boundary of two buffers\n\t\t\t\t\t8,\n\t\t\t\t\tCodingErrorAction.REPLACE,\n\t\t\t\t\t\"foo\");\n\t\t\tassertEquals(7, s.size());\n\t\t\tassertEquals(0, s.index());\n\t\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromFileName(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(StandardCharsets.UTF_8));\n\t\tCharStream s = CharStreams.fromFileName(p.toString());\n\t\tassertEquals(7, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\tassertEquals(p.toString(), s.getSourceName());\n\n\t}\n\n\t@Test\n\tpublic void fromFileNameWithLatin1(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\u00CA\\u00FE\".getBytes(StandardCharsets.ISO_8859_1));\n\t\tCharStream s = CharStreams.fromFileName(p.toString(), StandardCharsets.ISO_8859_1);\n\t\tassertEquals(8, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello \\u00CA\\u00FE\", s.toString());\n\t\tassertEquals(p.toString(), s.getSourceName());\n\t}\n\n\t@Test\n\tpublic void fromReader(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(StandardCharsets.UTF_8));\n\t\ttry (Reader r = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {\n\t\t\tCharStream s = CharStreams.fromReader(r);\n\t\t\tassertEquals(7, s.size());\n\t\t\tassertEquals(0, s.index());\n\t\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void fromSMPUTF16LEPathSMPHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(StandardCharsets.UTF_16LE));\n\t\tCharStream s = CharStreams.fromPath(p, StandardCharsets.UTF_16LE);\n\t\tassertEquals(7, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\tassertEquals(p.toString(), s.getSourceName());\n\t}\n\n\t@Test\n\tpublic void fromSMPUTF32LEPathSMPHasExpectedSize(@TempDir Path tempDir) throws Exception {\n\t\tPath p = getTestFile(tempDir);\n\t\t// UTF-32 isn't popular enough to have an entry in StandardCharsets.\n\t\tCharset c = Charset.forName(\"UTF-32LE\");\n\t\tFiles.write(p, \"hello \\uD83C\\uDF0E\".getBytes(c));\n\t\tCharStream s = CharStreams.fromPath(p, c);\n\t\tassertEquals(7, s.size());\n\t\tassertEquals(0, s.index());\n\t\tassertEquals(\"hello \\uD83C\\uDF0E\", s.toString());\n\t\tassertEquals(p.toString(), s.getSourceName());\n\t}\n\n\tprivate Path getTestFile(Path dir) {\n\t\treturn new File(dir.toString(), \"test\").toPath();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/TestIntegerList.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.java;\n\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertArrayEquals;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\n\npublic class TestIntegerList {\n\t@Test\n\tpublic void emptyListToEmptyCharArray() {\n\t\tIntegerList l = new IntegerList();\n\t\tassertArrayEquals(new char[0], l.toCharArray());\n\t}\n\n\t@Test\n\tpublic void negativeIntegerToCharArrayThrows() {\n\t\tIntegerList l = new IntegerList();\n\t\tl.add(-42);\n\t\tassertThrows(\n\t\t\t\tIllegalArgumentException.class,\n\t\t\t\tl::toCharArray\n\t\t);\n\t}\n\n\t@Test\n\tpublic void surrogateRangeIntegerToCharArray() {\n\t\tIntegerList l = new IntegerList();\n\t\t// Java allows dangling surrogates, so (currently) we do\n\t\t// as well. We could change this if desired.\n\t\tl.add(0xDC00);\n\t\tchar[] expected = new char[] { 0xDC00 };\n\t\tassertArrayEquals(expected, l.toCharArray());\n\t}\n\n\t@Test\n\tpublic void tooLargeIntegerToCharArrayThrows() {\n\t\tIntegerList l = new IntegerList();\n\t\tl.add(0x110000);\n\t\tassertThrows(\n\t\t\t\tIllegalArgumentException.class,\n\t\t\t\tl::toCharArray\n\t\t);\n\t}\n\n\t@Test\n\tpublic void unicodeBMPIntegerListToCharArray() {\n\t\tIntegerList l = new IntegerList();\n\t\tl.add(0x35);\n\t\tl.add(0x4E94);\n\t\tl.add(0xFF15);\n\t\tchar[] expected = new char[] { 0x35, 0x4E94, 0xFF15 };\n\t\tassertArrayEquals(expected, l.toCharArray());\n\t}\n\n\t@Test\n\tpublic void unicodeSMPIntegerListToCharArray() {\n\t\tIntegerList l = new IntegerList();\n\t\tl.add(0x104A5);\n\t\tl.add(0x116C5);\n\t\tl.add(0x1D7FB);\n\t\tchar[] expected = new char[] { 0xD801, 0xDCA5, 0xD805, 0xDEC5, 0xD835, 0xDFFB };\n\t\tassertArrayEquals(expected, l.toCharArray());\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/TestInterpreterDataReader.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.java;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.misc.InterpreterDataReader;\nimport org.antlr.v4.tool.Grammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\n/** This file represents a simple sanity checks on the parsing of the .interp file\n *  available to the Java runtime for interpreting rather than compiling and executing parsers.\n */\npublic class TestInterpreterDataReader {\n    @Test\n    public void testParseFile() throws IOException, NoSuchFieldException, IllegalAccessException, org.antlr.runtime.RecognitionException {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar Calc;\\n\" +\n\t\t\t\t\"s :  expr EOF\\n\" +\n\t\t\t\t\"  ;\\n\" +\n\t\t\t\t\"expr\\n\" +\n\t\t\t\t\"  :  INT            # number\\n\" +\n\t\t\t\t\"  |  expr (MUL | DIV) expr  # multiply\\n\" +\n\t\t\t\t\"  |  expr (ADD | SUB) expr  # add\\n\" +\n\t\t\t\t\"  ;\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"INT : [0-9]+;\\n\" +\n\t\t\t\t\"MUL : '*';\\n\" +\n\t\t\t\t\"DIV : '/';\\n\" +\n\t\t\t\t\"ADD : '+';\\n\" +\n\t\t\t\t\"SUB : '-';\\n\" +\n\t\t\t\t\"WS : [ \\\\t]+ -> channel(HIDDEN);\");\n\t\tString interpString = Tool.generateInterpreterData(g);\n\t\tPath interpFile = Files.createTempFile(null, null);\n\t\tFiles.write(interpFile, interpString.getBytes(StandardCharsets.UTF_8));\n\n        InterpreterDataReader.InterpreterData interpreterData = InterpreterDataReader.parseFile(interpFile.toString());\n        Field atnField = interpreterData.getClass().getDeclaredField(\"atn\");\n        Field vocabularyField = interpreterData.getClass().getDeclaredField(\"vocabulary\");\n        Field ruleNamesField = interpreterData.getClass().getDeclaredField(\"ruleNames\");\n        Field channelsField = interpreterData.getClass().getDeclaredField(\"channels\");\n        Field modesField = interpreterData.getClass().getDeclaredField(\"modes\");\n\n        atnField.setAccessible(true);\n        vocabularyField.setAccessible(true);\n        ruleNamesField.setAccessible(true);\n        channelsField.setAccessible(true);\n        modesField.setAccessible(true);\n\n        ATN atn = (ATN) atnField.get(interpreterData);\n        Vocabulary vocabulary = (Vocabulary) vocabularyField.get(interpreterData);\n\t\tString[] literalNames = ((VocabularyImpl) vocabulary).getLiteralNames();\n\t\tString[] symbolicNames = ((VocabularyImpl) vocabulary).getSymbolicNames();\n\t\tList<String> ruleNames = castList(ruleNamesField.get(interpreterData), String.class);\n        List<String> channels = castList(channelsField.get(interpreterData), String.class);\n        List<String> modes = castList(modesField.get(interpreterData), String.class);\n\n\t\tassertEquals(6, vocabulary.getMaxTokenType());\n\t\tassertArrayEquals(new String[]{\"s\",\"expr\"}, ruleNames.toArray());\n\t\tassertArrayEquals(new String[]{\"\", \"\", \"'*'\", \"'/'\", \"'+'\", \"'-'\", \"\"}, literalNames);\n\t\tassertArrayEquals(new String[]{\"\", \"INT\", \"MUL\", \"DIV\", \"ADD\", \"SUB\", \"WS\"}, symbolicNames);\n\t\tassertNull(channels);\n\t\tassertNull(modes);\n\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tassertEquals(ATNDeserializer.SERIALIZED_VERSION, serialized.get(0));\n    }\n\n    private <T> List<T> castList(Object obj, Class<T> clazz) {\n        List<T> result = new ArrayList<T>();\n        if (obj instanceof List<?>) {\n            for (Object o : (List<?>) obj) {\n                result.add(clazz.cast(o));\n            }\n            return result;\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/Java.g4",
    "content": "/*\n [The \"BSD licence\"]\n Copyright (c) 2013 Terence Parr, Sam Harwell\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/** A Java 1.7 grammar for ANTLR v4 derived from ANTLR v3 Java grammar.\n *  Uses ANTLR v4's left-recursive expression notation.\n *  It parses ECJ, Netbeans, JDK etc...\n *\n *  Sam Harwell cleaned this up significantly and updated to 1.7!\n *\n *  You can test with\n *\n *  $ antlr4 Java.g4\n *  $ javac *.java\n *  $ grun Java compilationUnit *.java\n */\ngrammar Java;\n\n// starting point for parsing a java file\ncompilationUnit\n    :   packageDeclaration? importDeclaration* typeDeclaration* EOF\n    ;\n\npackageDeclaration\n    :   annotation* 'package' qualifiedName ';'\n    ;\n\nimportDeclaration\n    :   'import' 'static'? qualifiedName ('.' '*')? ';'\n    ;\n\ntypeDeclaration\n    :   classOrInterfaceModifier* classDeclaration\n    |   classOrInterfaceModifier* enumDeclaration\n    |   classOrInterfaceModifier* interfaceDeclaration\n    |   classOrInterfaceModifier* annotationTypeDeclaration\n    |   ';'\n    ;\n\nmodifier\n    :   classOrInterfaceModifier\n    |   (   'native'\n        |   'synchronized'\n        |   'transient'\n        |   'volatile'\n        )\n    ;\n\nclassOrInterfaceModifier\n    :   annotation       // class or interface\n    |   (   'public'     // class or interface\n        |   'protected'  // class or interface\n        |   'private'    // class or interface\n        |   'static'     // class or interface\n        |   'abstract'   // class or interface\n        |   'final'      // class only -- does not apply to interfaces\n        |   'strictfp'   // class or interface\n        )\n    ;\n\nvariableModifier\n    :   'final'\n    |   annotation\n    ;\n\nclassDeclaration\n    :   'class' Identifier typeParameters?\n        ('extends' type)?\n        ('implements' typeList)?\n        classBody\n    ;\n\ntypeParameters\n    :   '<' typeParameter (',' typeParameter)* '>'\n    ;\n\ntypeParameter\n    :   Identifier ('extends' typeBound)?\n    ;\n\ntypeBound\n    :   type ('&' type)*\n    ;\n\nenumDeclaration\n    :   ENUM Identifier ('implements' typeList)?\n        '{' enumConstants? ','? enumBodyDeclarations? '}'\n    ;\n\nenumConstants\n    :   enumConstant (',' enumConstant)*\n    ;\n\nenumConstant\n    :   annotation* Identifier arguments? classBody?\n    ;\n\nenumBodyDeclarations\n    :   ';' classBodyDeclaration*\n    ;\n\ninterfaceDeclaration\n    :   'interface' Identifier typeParameters? ('extends' typeList)? interfaceBody\n    ;\n\ntypeList\n    :   type (',' type)*\n    ;\n\nclassBody\n    :   '{' classBodyDeclaration* '}'\n    ;\n\ninterfaceBody\n    :   '{' interfaceBodyDeclaration* '}'\n    ;\n\nclassBodyDeclaration\n    :   ';'\n    |   'static'? block\n    |   modifier* memberDeclaration\n    ;\n\nmemberDeclaration\n    :   methodDeclaration\n    |   genericMethodDeclaration\n    |   fieldDeclaration\n    |   constructorDeclaration\n    |   genericConstructorDeclaration\n    |   interfaceDeclaration\n    |   annotationTypeDeclaration\n    |   classDeclaration\n    |   enumDeclaration\n    ;\n\n/* We use rule this even for void methods which cannot have [] after parameters.\n   This simplifies grammar and we can consider void to be a type, which\n   renders the [] matching as a context-sensitive issue or a semantic check\n   for invalid return type after parsing.\n */\nmethodDeclaration\n    :   (type|'void') Identifier formalParameters ('[' ']')*\n        ('throws' qualifiedNameList)?\n        (   methodBody\n        |   ';'\n        )\n    ;\n\ngenericMethodDeclaration\n    :   typeParameters methodDeclaration\n    ;\n\nconstructorDeclaration\n    :   Identifier formalParameters ('throws' qualifiedNameList)?\n        constructorBody\n    ;\n\ngenericConstructorDeclaration\n    :   typeParameters constructorDeclaration\n    ;\n\nfieldDeclaration\n    :   type variableDeclarators ';'\n    ;\n\ninterfaceBodyDeclaration\n    :   modifier* interfaceMemberDeclaration\n    |   ';'\n    ;\n\ninterfaceMemberDeclaration\n    :   constDeclaration\n    |   interfaceMethodDeclaration\n    |   genericInterfaceMethodDeclaration\n    |   interfaceDeclaration\n    |   annotationTypeDeclaration\n    |   classDeclaration\n    |   enumDeclaration\n    ;\n\nconstDeclaration\n    :   type constantDeclarator (',' constantDeclarator)* ';'\n    ;\n\nconstantDeclarator\n    :   Identifier ('[' ']')* '=' variableInitializer\n    ;\n\n// see matching of [] comment in methodDeclaratorRest\ninterfaceMethodDeclaration\n    :   (type|'void') Identifier formalParameters ('[' ']')*\n        ('throws' qualifiedNameList)?\n        ';'\n    ;\n\ngenericInterfaceMethodDeclaration\n    :   typeParameters interfaceMethodDeclaration\n    ;\n\nvariableDeclarators\n    :   variableDeclarator (',' variableDeclarator)*\n    ;\n\nvariableDeclarator\n    :   variableDeclaratorId ('=' variableInitializer)?\n    ;\n\nvariableDeclaratorId\n    :   Identifier ('[' ']')*\n    ;\n\nvariableInitializer\n    :   arrayInitializer\n    |   expression\n    ;\n\narrayInitializer\n    :   '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'\n    ;\n\nenumConstantName\n    :   Identifier\n    ;\n\ntype\n    :   classOrInterfaceType ('[' ']')*\n    |   primitiveType ('[' ']')*\n    ;\n\nclassOrInterfaceType\n    :   Identifier typeArguments? ('.' Identifier typeArguments? )*\n    ;\n\nprimitiveType\n    :   'boolean'\n    |   'char'\n    |   'byte'\n    |   'short'\n    |   'int'\n    |   'long'\n    |   'float'\n    |   'double'\n    ;\n\ntypeArguments\n    :   '<' typeArgument (',' typeArgument)* '>'\n    ;\n\ntypeArgument\n    :   type\n    |   '?' (('extends' | 'super') type)?\n    ;\n\nqualifiedNameList\n    :   qualifiedName (',' qualifiedName)*\n    ;\n\nformalParameters\n    :   '(' formalParameterList? ')'\n    ;\n\nformalParameterList\n    :   formalParameter (',' formalParameter)* (',' lastFormalParameter)?\n    |   lastFormalParameter\n    ;\n\nformalParameter\n    :   variableModifier* type variableDeclaratorId\n    ;\n\nlastFormalParameter\n    :   variableModifier* type '...' variableDeclaratorId\n    ;\n\nmethodBody\n    :   block\n    ;\n\nconstructorBody\n    :   block\n    ;\n\nqualifiedName\n    :   Identifier ('.' Identifier)*\n    ;\n\nliteral\n    :   IntegerLiteral\n    |   FloatingPointLiteral\n    |   CharacterLiteral\n    |   StringLiteral\n    |   BooleanLiteral\n    |   'null'\n    ;\n\n// ANNOTATIONS\n\nannotation\n    :   '@' annotationName ( '(' ( elementValuePairs | elementValue )? ')' )?\n    ;\n\nannotationName : qualifiedName ;\n\nelementValuePairs\n    :   elementValuePair (',' elementValuePair)*\n    ;\n\nelementValuePair\n    :   Identifier '=' elementValue\n    ;\n\nelementValue\n    :   expression\n    |   annotation\n    |   elementValueArrayInitializer\n    ;\n\nelementValueArrayInitializer\n    :   '{' (elementValue (',' elementValue)*)? (',')? '}'\n    ;\n\nannotationTypeDeclaration\n    :   '@' 'interface' Identifier annotationTypeBody\n    ;\n\nannotationTypeBody\n    :   '{' (annotationTypeElementDeclaration)* '}'\n    ;\n\nannotationTypeElementDeclaration\n    :   modifier* annotationTypeElementRest\n    |   ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler\n    ;\n\nannotationTypeElementRest\n    :   type annotationMethodOrConstantRest ';'\n    |   classDeclaration ';'?\n    |   interfaceDeclaration ';'?\n    |   enumDeclaration ';'?\n    |   annotationTypeDeclaration ';'?\n    ;\n\nannotationMethodOrConstantRest\n    :   annotationMethodRest\n    |   annotationConstantRest\n    ;\n\nannotationMethodRest\n    :   Identifier '(' ')' defaultValue?\n    ;\n\nannotationConstantRest\n    :   variableDeclarators\n    ;\n\ndefaultValue\n    :   'default' elementValue\n    ;\n\n// STATEMENTS / BLOCKS\n\nblock\n    :   '{' blockStatement* '}'\n    ;\n\nblockStatement\n    :   localVariableDeclarationStatement\n    |   statement\n    |   typeDeclaration\n    ;\n\nlocalVariableDeclarationStatement\n    :    localVariableDeclaration ';'\n    ;\n\nlocalVariableDeclaration\n    :   variableModifier* type variableDeclarators\n    ;\n\nstatement\n    :   block\n    |   ASSERT expression (':' expression)? ';'\n    |   'if' parExpression statement ('else' statement)?\n    |   'for' '(' forControl ')' statement\n    |   'while' parExpression statement\n    |   'do' statement 'while' parExpression ';'\n    |   'try' block (catchClause+ finallyBlock? | finallyBlock)\n    |   'try' resourceSpecification block catchClause* finallyBlock?\n    |   'switch' parExpression '{' switchBlockStatementGroup* switchLabel* '}'\n    |   'synchronized' parExpression block\n    |   'return' expression? ';'\n    |   'throw' expression ';'\n    |   'break' Identifier? ';'\n    |   'continue' Identifier? ';'\n    |   ';'\n    |   statementExpression ';'\n    |   Identifier ':' statement\n    ;\n\ncatchClause\n    :   'catch' '(' variableModifier* catchType Identifier ')' block\n    ;\n\ncatchType\n    :   qualifiedName ('|' qualifiedName)*\n    ;\n\nfinallyBlock\n    :   'finally' block\n    ;\n\nresourceSpecification\n    :   '(' resources ';'? ')'\n    ;\n\nresources\n    :   resource (';' resource)*\n    ;\n\nresource\n    :   variableModifier* classOrInterfaceType variableDeclaratorId '=' expression\n    ;\n\n/** Matches cases then statements, both of which are mandatory.\n *  To handle empty cases at the end, we add switchLabel* to statement.\n */\nswitchBlockStatementGroup\n    :   switchLabel+ blockStatement+\n    ;\n\nswitchLabel\n    :   'case' constantExpression ':'\n    |   'case' enumConstantName ':'\n    |   'default' ':'\n    ;\n\nforControl\n    :   enhancedForControl\n    |   forInit? ';' expression? ';' forUpdate?\n    ;\n\nforInit\n    :   localVariableDeclaration\n    |   expressionList\n    ;\n\nenhancedForControl\n    :   variableModifier* type variableDeclaratorId ':' expression\n    ;\n\nforUpdate\n    :   expressionList\n    ;\n\n// EXPRESSIONS\n\nparExpression\n    :   '(' expression ')'\n    ;\n\nexpressionList\n    :   expression (',' expression)*\n    ;\n\nstatementExpression\n    :   expression\n    ;\n\nconstantExpression\n    :   expression\n    ;\n\nexpression\n    :   primary\n    |   expression '.' Identifier\n    |   expression '.' 'this'\n    |   expression '.' 'new' nonWildcardTypeArguments? innerCreator\n    |   expression '.' 'super' superSuffix\n    |   expression '.' explicitGenericInvocation\n    |   expression '[' expression ']'\n    |   expression '(' expressionList? ')'\n    |   'new' creator\n    |   '(' type ')' expression\n    |   expression ('++' | '--')\n    |   ('+'|'-'|'++'|'--') expression\n    |   ('~'|'!') expression\n    |   expression ('*'|'/'|'%') expression\n    |   expression ('+'|'-') expression\n    |   expression ('<' '<' | '>' '>' '>' | '>' '>') expression\n    |   expression ('<=' | '>=' | '>' | '<') expression\n    |   expression 'instanceof' type\n    |   expression ('==' | '!=') expression\n    |   expression '&' expression\n    |   expression '^' expression\n    |   expression '|' expression\n    |   expression '&&' expression\n    |   expression '||' expression\n    |   expression '?' expression ':' expression\n    |   <assoc=right> expression\n        (   '='\n        |   '+='\n        |   '-='\n        |   '*='\n        |   '/='\n        |   '&='\n        |   '|='\n        |   '^='\n        |   '>>='\n        |   '>>>='\n        |   '<<='\n        |   '%='\n        )\n        expression\n    ;\n\nprimary\n    :   '(' expression ')'\n    |   'this'\n    |   'super'\n    |   literal\n    |   Identifier\n    |   type '.' 'class'\n    |   'void' '.' 'class'\n    |   nonWildcardTypeArguments (explicitGenericInvocationSuffix | 'this' arguments)\n    ;\n\ncreator\n    :   nonWildcardTypeArguments createdName classCreatorRest\n    |   createdName (arrayCreatorRest | classCreatorRest)\n    ;\n\ncreatedName\n    :   Identifier typeArgumentsOrDiamond? ('.' Identifier typeArgumentsOrDiamond?)*\n    |   primitiveType\n    ;\n\ninnerCreator\n    :   Identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest\n    ;\n\narrayCreatorRest\n    :   '['\n        (   ']' ('[' ']')* arrayInitializer\n        |   expression ']' ('[' expression ']')* ('[' ']')*\n        )\n    ;\n\nclassCreatorRest\n    :   arguments classBody?\n    ;\n\nexplicitGenericInvocation\n    :   nonWildcardTypeArguments explicitGenericInvocationSuffix\n    ;\n\nnonWildcardTypeArguments\n    :   '<' typeList '>'\n    ;\n\ntypeArgumentsOrDiamond\n    :   '<' '>'\n    |   typeArguments\n    ;\n\nnonWildcardTypeArgumentsOrDiamond\n    :   '<' '>'\n    |   nonWildcardTypeArguments\n    ;\n\nsuperSuffix\n    :   arguments\n    |   '.' Identifier arguments?\n    ;\n\nexplicitGenericInvocationSuffix\n    :   'super' superSuffix\n    |   Identifier arguments\n    ;\n\narguments\n    :   '(' expressionList? ')'\n    ;\n\n// LEXER\n\n// §3.9 Keywords\n\nABSTRACT      : 'abstract';\nASSERT        : 'assert';\nBOOLEAN       : 'boolean';\nBREAK         : 'break';\nBYTE          : 'byte';\nCASE          : 'case';\nCATCH         : 'catch';\nCHAR          : 'char';\nCLASS         : 'class';\nCONST         : 'const';\nCONTINUE      : 'continue';\nDEFAULT       : 'default';\nDO            : 'do';\nDOUBLE        : 'double';\nELSE          : 'else';\nENUM          : 'enum';\nEXTENDS       : 'extends';\nFINAL         : 'final';\nFINALLY       : 'finally';\nFLOAT         : 'float';\nFOR           : 'for';\nIF            : 'if';\nGOTO          : 'goto';\nIMPLEMENTS    : 'implements';\nIMPORT        : 'import';\nINSTANCEOF    : 'instanceof';\nINT           : 'int';\nINTERFACE     : 'interface';\nLONG          : 'long';\nNATIVE        : 'native';\nNEW           : 'new';\nPACKAGE       : 'package';\nPRIVATE       : 'private';\nPROTECTED     : 'protected';\nPUBLIC        : 'public';\nRETURN        : 'return';\nSHORT         : 'short';\nSTATIC        : 'static';\nSTRICTFP      : 'strictfp';\nSUPER         : 'super';\nSWITCH        : 'switch';\nSYNCHRONIZED  : 'synchronized';\nTHIS          : 'this';\nTHROW         : 'throw';\nTHROWS        : 'throws';\nTRANSIENT     : 'transient';\nTRY           : 'try';\nVOID          : 'void';\nVOLATILE      : 'volatile';\nWHILE         : 'while';\n\n// §3.10.1 Integer Literals\n\nIntegerLiteral\n    :   DecimalIntegerLiteral\n    |   HexIntegerLiteral\n    |   OctalIntegerLiteral\n    |   BinaryIntegerLiteral\n    ;\n\nfragment\nDecimalIntegerLiteral\n    :   DecimalNumeral IntegerTypeSuffix?\n    ;\n\nfragment\nHexIntegerLiteral\n    :   HexNumeral IntegerTypeSuffix?\n    ;\n\nfragment\nOctalIntegerLiteral\n    :   OctalNumeral IntegerTypeSuffix?\n    ;\n\nfragment\nBinaryIntegerLiteral\n    :   BinaryNumeral IntegerTypeSuffix?\n    ;\n\nfragment\nIntegerTypeSuffix\n    :   [lL]\n    ;\n\nfragment\nDecimalNumeral\n    :   '0'\n    |   NonZeroDigit (Digits? | Underscores Digits)\n    ;\n\nfragment\nDigits\n    :   Digit (DigitOrUnderscore* Digit)?\n    ;\n\nfragment\nDigit\n    :   '0'\n    |   NonZeroDigit\n    ;\n\nfragment\nNonZeroDigit\n    :   [1-9]\n    ;\n\nfragment\nDigitOrUnderscore\n    :   Digit\n    |   '_'\n    ;\n\nfragment\nUnderscores\n    :   '_'+\n    ;\n\nfragment\nHexNumeral\n    :   '0' [xX] HexDigits\n    ;\n\nfragment\nHexDigits\n    :   HexDigit (HexDigitOrUnderscore* HexDigit)?\n    ;\n\nfragment\nHexDigit\n    :   [0-9a-fA-F]\n    ;\n\nfragment\nHexDigitOrUnderscore\n    :   HexDigit\n    |   '_'\n    ;\n\nfragment\nOctalNumeral\n    :   '0' Underscores? OctalDigits\n    ;\n\nfragment\nOctalDigits\n    :   OctalDigit (OctalDigitOrUnderscore* OctalDigit)?\n    ;\n\nfragment\nOctalDigit\n    :   [0-7]\n    ;\n\nfragment\nOctalDigitOrUnderscore\n    :   OctalDigit\n    |   '_'\n    ;\n\nfragment\nBinaryNumeral\n    :   '0' [bB] BinaryDigits\n    ;\n\nfragment\nBinaryDigits\n    :   BinaryDigit (BinaryDigitOrUnderscore* BinaryDigit)?\n    ;\n\nfragment\nBinaryDigit\n    :   [01]\n    ;\n\nfragment\nBinaryDigitOrUnderscore\n    :   BinaryDigit\n    |   '_'\n    ;\n\n// §3.10.2 Floating-Point Literals\n\nFloatingPointLiteral\n    :   DecimalFloatingPointLiteral\n    |   HexadecimalFloatingPointLiteral\n    ;\n\nfragment\nDecimalFloatingPointLiteral\n    :   Digits '.' Digits? ExponentPart? FloatTypeSuffix?\n    |   '.' Digits ExponentPart? FloatTypeSuffix?\n    |   Digits ExponentPart FloatTypeSuffix?\n    |   Digits FloatTypeSuffix\n    ;\n\nfragment\nExponentPart\n    :   ExponentIndicator SignedInteger\n    ;\n\nfragment\nExponentIndicator\n    :   [eE]\n    ;\n\nfragment\nSignedInteger\n    :   Sign? Digits\n    ;\n\nfragment\nSign\n    :   [+-]\n    ;\n\nfragment\nFloatTypeSuffix\n    :   [fFdD]\n    ;\n\nfragment\nHexadecimalFloatingPointLiteral\n    :   HexSignificand BinaryExponent FloatTypeSuffix?\n    ;\n\nfragment\nHexSignificand\n    :   HexNumeral '.'?\n    |   '0' [xX] HexDigits? '.' HexDigits\n    ;\n\nfragment\nBinaryExponent\n    :   BinaryExponentIndicator SignedInteger\n    ;\n\nfragment\nBinaryExponentIndicator\n    :   [pP]\n    ;\n\n// §3.10.3 Boolean Literals\n\nBooleanLiteral\n    :   'true'\n    |   'false'\n    ;\n\n// §3.10.4 Character Literals\n\nCharacterLiteral\n    :   '\\'' SingleCharacter '\\''\n    |   '\\'' EscapeSequence '\\''\n    ;\n\nfragment\nSingleCharacter\n    :   ~['\\\\]\n    ;\n\n// §3.10.5 String Literals\n\nStringLiteral\n    :   '\"' StringCharacters? '\"'\n    ;\n\nfragment\nStringCharacters\n    :   StringCharacter+\n    ;\n\nfragment\nStringCharacter\n    :   ~[\"\\\\]\n    |   EscapeSequence\n    ;\n\n// §3.10.6 Escape Sequences for Character and String Literals\n\nfragment\nEscapeSequence\n    :   '\\\\' [btnfr\"'\\\\]\n    |   OctalEscape\n    |   UnicodeEscape\n    ;\n\nfragment\nOctalEscape\n    :   '\\\\' OctalDigit\n    |   '\\\\' OctalDigit OctalDigit\n    |   '\\\\' ZeroToThree OctalDigit OctalDigit\n    ;\n\nfragment\nUnicodeEscape\n    :   '\\\\' 'u' HexDigit HexDigit HexDigit HexDigit\n    ;\n\nfragment\nZeroToThree\n    :   [0-3]\n    ;\n\n// §3.10.7 The Null Literal\n\nNullLiteral\n    :   'null'\n    ;\n\n// §3.11 Separators\n\nLPAREN          : '(';\nRPAREN          : ')';\nLBRACE          : '{';\nRBRACE          : '}';\nLBRACK          : '[';\nRBRACK          : ']';\nSEMI            : ';';\nCOMMA           : ',';\nDOT             : '.';\n\n// §3.12 Operators\n\nASSIGN          : '=';\nGT              : '>';\nLT              : '<';\nBANG            : '!';\nTILDE           : '~';\nQUESTION        : '?';\nCOLON           : ':';\nEQUAL           : '==';\nLE              : '<=';\nGE              : '>=';\nNOTEQUAL        : '!=';\nAND             : '&&';\nOR              : '||';\nINC             : '++';\nDEC             : '--';\nADD             : '+';\nSUB             : '-';\nMUL             : '*';\nDIV             : '/';\nBITAND          : '&';\nBITOR           : '|';\nCARET           : '^';\nMOD             : '%';\n\nADD_ASSIGN      : '+=';\nSUB_ASSIGN      : '-=';\nMUL_ASSIGN      : '*=';\nDIV_ASSIGN      : '/=';\nAND_ASSIGN      : '&=';\nOR_ASSIGN       : '|=';\nXOR_ASSIGN      : '^=';\nMOD_ASSIGN      : '%=';\nLSHIFT_ASSIGN   : '<<=';\nRSHIFT_ASSIGN   : '>>=';\nURSHIFT_ASSIGN  : '>>>=';\n\n// §3.8 Identifiers (must appear after all keywords in the grammar)\n\nIdentifier\n    :   JavaLetter JavaLetterOrDigit*\n    ;\n\nfragment\nJavaLetter\n    :   [a-zA-Z$_] // these are the \"java letters\" below 0x7F\n    |   // covers all characters above 0x7F which are not a surrogate\n        ~[\\u0000-\\u007F\\uD800-\\uDBFF]\n        {Character.isJavaIdentifierStart(_input.LA(-1))}?\n    |   // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF\n        [\\uD800-\\uDBFF] [\\uDC00-\\uDFFF]\n        {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?\n    ;\n\nfragment\nJavaLetterOrDigit\n    :   [a-zA-Z0-9$_] // these are the \"java letters or digits\" below 0x7F\n    |   // covers all characters above 0x7F which are not a surrogate\n        ~[\\u0000-\\u007F\\uD800-\\uDBFF]\n        {Character.isJavaIdentifierPart(_input.LA(-1))}?\n    |   // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF\n        [\\uD800-\\uDBFF] [\\uDC00-\\uDFFF]\n        {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?\n    ;\n\n//\n// Additional symbols not defined in the lexical specification\n//\n\nAT : '@';\nELLIPSIS : '...';\n\n//\n// Whitespace and comments\n//\n\nWS  :  [ \\t\\r\\n\\u000C]+ -> skip\n    ;\n\nCOMMENT\n    :   '/*' .*? '*/' -> skip\n    ;\n\nLINE_COMMENT\n    :   '//' ~[\\r\\n]* -> skip\n    ;\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/TestExpectedTokens.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.java.api;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.test.runtime.RuntimeTestUtils;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.tool.Grammar;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestExpectedTokens extends JavaRunner {\n\t@Test\n\tpublic void testEpsilonAltSubrule() throws Exception {\n\t\tString gtext =\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"a : A (B | ) C ;\\n\";\n\t\tGrammar g = new Grammar(gtext);\n\t\tString atnText =\n\t\t\t\"RuleStart_a_0->s2\\n\"+\n\t\t\t\"s2-A->BlockStart_5\\n\"+\n\t\t\t\"BlockStart_5->s3\\n\"+\n\t\t\t\"BlockStart_5->s4\\n\"+\n\t\t\t\"s3-B->BlockEnd_6\\n\"+\n\t\t\t\"s4->BlockEnd_6\\n\"+\n\t\t\t\"BlockEnd_6->s7\\n\"+\n\t\t\t\"s7-C->s8\\n\"+\n\t\t\t\"s8->RuleStop_a_1\\n\"+\n\t\t\t\"RuleStop_a_1-EOF->s9\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", atnText);\n\n\t\tATN atn = g.getATN();\n\t\tint blkStartStateNumber = 5;\n\t\tIntervalSet tokens = atn.getExpectedTokens(blkStartStateNumber, null);\n\t\tassertEquals(\"{B, C}\", tokens.toString(g.getTokenNames()));\n\t}\n\n\t@Test public void testOptionalSubrule() throws Exception {\n\t\tString gtext =\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"a : A B? C ;\\n\";\n\t\tGrammar g = new Grammar(gtext);\n\t\tString atnText =\n\t\t\t\"RuleStart_a_0->s2\\n\"+\n\t\t\t\"s2-A->BlockStart_4\\n\"+\n\t\t\t\"BlockStart_4->s3\\n\"+\n\t\t\t\"BlockStart_4->BlockEnd_5\\n\"+\n\t\t\t\"s3-B->BlockEnd_5\\n\"+\n\t\t\t\"BlockEnd_5->s6\\n\"+\n\t\t\t\"s6-C->s7\\n\"+\n\t\t\t\"s7->RuleStop_a_1\\n\"+\n\t\t\t\"RuleStop_a_1-EOF->s8\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", atnText);\n\n\t\tATN atn = g.getATN();\n\t\tint blkStartStateNumber = 4;\n\t\tIntervalSet tokens = atn.getExpectedTokens(blkStartStateNumber, null);\n\t\tassertEquals(\"{B, C}\", tokens.toString(g.getTokenNames()));\n\t}\n\n\t@Test public void testFollowIncluded() throws Exception {\n\t\tString gtext =\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"a : b A ;\\n\" +\n\t\t\t\t\"b : B | ;\";\n\t\tGrammar g = new Grammar(gtext);\n\t\tString atnText =\n\t\t\t\"RuleStart_a_0->s4\\n\"+\n\t\t\t\"s4-b->RuleStart_b_2\\n\"+\n\t\t\t\"s5-A->s6\\n\"+\n\t\t\t\"s6->RuleStop_a_1\\n\"+\n\t\t\t\"RuleStop_a_1-EOF->s11\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", atnText);\n\t\tatnText =\n\t\t\t\"RuleStart_b_2->BlockStart_9\\n\"+\n\t\t\t\"BlockStart_9->s7\\n\"+\n\t\t\t\"BlockStart_9->s8\\n\"+\n\t\t\t\"s7-B->BlockEnd_10\\n\"+\n\t\t\t\"s8->BlockEnd_10\\n\"+\n\t\t\t\"BlockEnd_10->RuleStop_b_3\\n\"+\n\t\t\t\"RuleStop_b_3->s5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"b\", atnText);\n\n\t\tATN atn = g.getATN();\n\n\t\t// From the start of 'b' with empty stack, can only see B and EOF\n\t\tint blkStartStateNumber = 9;\n\t\tIntervalSet tokens = atn.getExpectedTokens(blkStartStateNumber, ParserRuleContext.EMPTY);\n\t\tassertEquals(\"{<EOF>, B}\", tokens.toString(g.getTokenNames()));\n\n\t\t// Now call from 'a'\n\t\ttokens = atn.getExpectedTokens(blkStartStateNumber, new ParserRuleContext(ParserRuleContext.EMPTY, 4));\n\t\tassertEquals(\"{A, B}\", tokens.toString(g.getTokenNames()));\n\t}\n\n\t// Test for https://github.com/antlr/antlr4/issues/1480\n\t// can't reproduce\n\t@Test public void testFollowIncludedInLeftRecursiveRule() throws Exception {\n\t\tString gtext =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"s : expr EOF ;\\n\" +\n\t\t\t\"expr : L expr R\\n\"+\n\t\t\t\"     | expr PLUS expr\\n\"+\n\t\t\t\"     | ID\\n\"+\n\t\t\t\"     ;\\n\";\n\t\tGrammar g = new Grammar(gtext);\n\t\tString atnText =\n\t\t\t\"RuleStart_expr_2->BlockStart_13\\n\"+\n\t\t\t\"BlockStart_13->s7\\n\"+\n\t\t\t\"BlockStart_13->s12\\n\"+\n\t\t\t\"s7-action_1:-1->s8\\n\"+\n\t\t\t\"s12-ID->BlockEnd_14\\n\"+\n\t\t\t\"s8-L->s9\\n\"+\n\t\t\t\"BlockEnd_14->StarLoopEntry_20\\n\"+\n\t\t\t\"s9-expr->RuleStart_expr_2\\n\"+\n\t\t\t\"StarLoopEntry_20->StarBlockStart_18\\n\"+\n\t\t\t\"StarLoopEntry_20->s21\\n\"+\n\t\t\t\"s10-R->s11\\n\"+\n\t\t\t\"StarBlockStart_18->s15\\n\"+\n\t\t\t\"s21->RuleStop_expr_3\\n\"+\n\t\t\t\"s11->BlockEnd_14\\n\"+\n\t\t\t\"s15-2 >= _p->s16\\n\"+\n\t\t\t\"RuleStop_expr_3->s5\\n\"+\n\t\t\t\"RuleStop_expr_3->s10\\n\"+\n\t\t\t\"RuleStop_expr_3->BlockEnd_19\\n\"+\n\t\t\t\"s16-PLUS->s17\\n\"+\n\t\t\t\"s17-expr->RuleStart_expr_2\\n\"+\n\t\t\t\"BlockEnd_19->StarLoopBack_22\\n\"+\n\t\t\t\"StarLoopBack_22->StarLoopEntry_20\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"expr\", atnText);\n\n\t\tATN atn = g.getATN();\n\n//\t\tDOTGenerator gen = new DOTGenerator(g);\n//\t\tString dot = gen.getDOT(atn.states.get(2), g.getRuleNames(), false);\n//\t\tSystem.out.println(dot);\n\n\t\t// Simulate call stack after input '(x' from rule s\n\t\tParserRuleContext callStackFrom_s = new ParserRuleContext(null, 4);\n\t\tParserRuleContext callStackFrom_expr = new ParserRuleContext(callStackFrom_s, 9);\n\t\tint afterID = 14;\n\t\tIntervalSet tokens = atn.getExpectedTokens(afterID, callStackFrom_expr);\n\t\tassertEquals(\"{R, PLUS}\", tokens.toString(g.getTokenNames()));\n\n\t\t// Simulate call stack after input '(x' from within rule expr\n\t\tcallStackFrom_expr = new ParserRuleContext(null, 9);\n\t\ttokens = atn.getExpectedTokens(afterID, callStackFrom_expr);\n\t\tassertEquals(\"{R, PLUS}\", tokens.toString(g.getTokenNames()));\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/TestTokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.java.api;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.BufferedTokenStream;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/**\n * This class contains tests for specific API functionality in {@link TokenStream} and derived types.\n */\npublic class TestTokenStream {\n\n\t/**\n\t * This is a targeted regression test for antlr/antlr4#1584 ({@link BufferedTokenStream} cannot be reused after EOF).\n\t */\n\t@Test\n\tpublic void testBufferedTokenStreamReuseAfterFill() {\n\t\tCharStream firstInput = new ANTLRInputStream(\"A\");\n\t\tBufferedTokenStream tokenStream = new BufferedTokenStream(new VisitorBasicLexer(firstInput));\n\t\ttokenStream.fill();\n\t\tassertEquals(2, tokenStream.size());\n\t\tassertEquals(VisitorBasicLexer.A, tokenStream.get(0).getType());\n\t\tassertEquals(Token.EOF, tokenStream.get(1).getType());\n\n\t\tCharStream secondInput = new ANTLRInputStream(\"AA\");\n\t\ttokenStream.setTokenSource(new VisitorBasicLexer(secondInput));\n\t\ttokenStream.fill();\n\t\tassertEquals(3, tokenStream.size());\n\t\tassertEquals(VisitorBasicLexer.A, tokenStream.get(0).getType());\n\t\tassertEquals(VisitorBasicLexer.A, tokenStream.get(1).getType());\n\t\tassertEquals(Token.EOF, tokenStream.get(2).getType());\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/TestTokenStreamRewriter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.java.api;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.TokenStreamRewriter;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\n\npublic class TestTokenStreamRewriter {\n\n\t/** Public default constructor used by TestRig */\n\tpublic TestTokenStreamRewriter() {\n\t}\n\n\t@Test\n\tpublic void testInsertBeforeIndex0() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(\"abc\"));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"0\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"0abc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testInsertAfterLastIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertAfter(2, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abcx\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void test2InsertBeforeAfterMiddleIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(1, \"x\");\n\t\ttokens.insertAfter(1, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"axbxc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceIndex0() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(0, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"xbc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceLastIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abx\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceMiddleIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(1, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"axc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testToStringStartStop() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"ID : 'a'..'z'+;\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"INT : '0'..'9'+;\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"SEMI : ';';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"MUL : '*';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"ASSIGN : '=';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"WS : ' '+;\\n\");\n\t\t// Tokens: 0123456789\n\t\t// Input:  x = 3 * 0;\n\t\tString input = \"x = 3 * 0;\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(4, 8, \"0\");\n\t\tstream.fill();\n// replace 3 * 0 with 0\n\n\t\tString result = tokens.getTokenStream().getText();\n\t\tString expecting = \"x = 3 * 0;\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText();\n\t\texpecting = \"x = 0;\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText(Interval.of(0, 9));\n\t\texpecting = \"x = 0;\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText(Interval.of(4, 8));\n\t\texpecting = \"0\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testToStringStartStop2() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"ID : 'a'..'z'+;\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"INT : '0'..'9'+;\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"SEMI : ';';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"ASSIGN : '=';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"PLUS : '+';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"MULT : '*';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"WS : ' '+;\\n\");\n\t\t// Tokens: 012345678901234567\n\t\t// Input:  x = 3 * 0 + 2 * 0;\n\t\tString input = \"x = 3 * 0 + 2 * 0;\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\n\t\tString result = tokens.getTokenStream().getText();\n\t\tString expecting = \"x = 3 * 0 + 2 * 0;\";\n\t\tassertEquals(expecting, result);\n\n\t\ttokens.replace(4, 8, \"0\");\n\t\tstream.fill();\n// replace 3 * 0 with 0\n\t\tresult = tokens.getText();\n\t\texpecting = \"x = 0 + 2 * 0;\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText(Interval.of(0, 17));\n\t\texpecting = \"x = 0 + 2 * 0;\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText(Interval.of(4, 8));\n\t\texpecting = \"0\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText(Interval.of(0, 8));\n\t\texpecting = \"x = 0\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText(Interval.of(12, 16));\n\t\texpecting = \"2 * 0\";\n\t\tassertEquals(expecting, result);\n\n\t\ttokens.insertAfter(17, \"// comment\");\n\t\tresult = tokens.getText(Interval.of(12, 18));\n\t\texpecting = \"2 * 0;// comment\";\n\t\tassertEquals(expecting, result);\n\n\t\tresult = tokens.getText(Interval.of(0, 8));\n\t\tstream.fill();\n// try again after insert at end\n\t\texpecting = \"x = 0\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\n\t@Test public void test2ReplaceMiddleIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(1, \"x\");\n\t\ttokens.replace(1, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"ayc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void test2ReplaceMiddleIndex1InsertBefore() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"_\");\n\t\ttokens.replace(1, \"x\");\n\t\ttokens.replace(1, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"_ayc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceThenDeleteMiddleIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(1, \"x\");\n\t\ttokens.delete(1);\n\t\tString result = tokens.getText();\n\t\tString expecting = \"ac\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testInsertInPriorReplace() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(0, 2, \"x\");\n\t\ttokens.insertBefore(1, \"0\");\n\t\tException exc = null;\n\t\ttry {\n\t\t\ttokens.getText();\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\texc = iae;\n\t\t}\n\t\tString expecting = \"insert op <InsertBeforeOp@[@1,1:1='b',<2>,1:1]:\\\"0\\\"> within boundaries of previous <ReplaceOp@[@0,0:0='a',<1>,1:0]..[@2,2:2='c',<3>,1:2]:\\\"x\\\">\";\n\t\tassertNotNull(exc);\n\t\tassertEquals(expecting, exc.getMessage());\n\t}\n\n\t@Test public void testInsertThenReplaceSameIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"0\");\n\t\ttokens.replace(0, \"x\");\n\t\tstream.fill();\n// supercedes insert at 0\n\t\tString result = tokens.getText();\n\t\tString expecting = \"0xbc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void test2InsertMiddleIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(1, \"x\");\n\t\ttokens.insertBefore(1, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"ayxbc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void test2InsertThenReplaceIndex0() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"x\");\n\t\ttokens.insertBefore(0, \"y\");\n\t\ttokens.replace(0, \"z\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"yxzbc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceThenInsertBeforeLastIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, \"x\");\n\t\ttokens.insertBefore(2, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abyx\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testInsertThenReplaceLastIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(2, \"y\");\n\t\ttokens.replace(2, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abyx\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceThenInsertAfterLastIndex() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, \"x\");\n\t\ttokens.insertAfter(2, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abxy\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceRangeThenInsertAtLeftEdge() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcccba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 4, \"x\");\n\t\ttokens.insertBefore(2, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abyxba\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceRangeThenInsertAtRightEdge() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcccba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 4, \"x\");\n\t\ttokens.insertBefore(4, \"y\");\n\t\tstream.fill(); // no effect; within range of a replace\n\t\tException exc = null;\n\t\ttry {\n\t\t\ttokens.getText();\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\texc = iae;\n\t\t}\n\t\tString expecting = \"insert op <InsertBeforeOp@[@4,4:4='c',<3>,1:4]:\\\"y\\\"> within boundaries of previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"x\\\">\";\n\t\tassertNotNull(exc);\n\t\tassertEquals(expecting, exc.getMessage());\n\t}\n\n\t@Test public void testReplaceRangeThenInsertAfterRightEdge() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcccba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 4, \"x\");\n\t\ttokens.insertAfter(4, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abxyba\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceAll() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcccba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(0, 6, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"x\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceSubsetThenFetch() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcccba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 4, \"xyz\");\n\t\tString result = tokens.getText(Interval.of(0, 6));\n\t\tString expecting = \"abxyzba\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testReplaceThenReplaceSuperset() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcccba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 4, \"xyz\");\n\t\ttokens.replace(3, 5, \"foo\");\n\t\tstream.fill();\n// overlaps, error\n\t\tException exc = null;\n\t\ttry {\n\t\t\ttokens.getText();\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\texc = iae;\n\t\t}\n\t\tString expecting = \"replace op boundaries of <ReplaceOp@[@3,3:3='c',<3>,1:3]..[@5,5:5='b',<2>,1:5]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"xyz\\\">\";\n\t\tassertNotNull(exc);\n\t\tassertEquals(expecting, exc.getMessage());\n\t}\n\n\t@Test public void testReplaceThenReplaceLowerIndexedSuperset() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcccba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 4, \"xyz\");\n\t\ttokens.replace(1, 3, \"foo\");\n\t\tstream.fill();\n// overlap, error\n\t\tException exc = null;\n\t\ttry {\n\t\t\ttokens.getText();\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\texc = iae;\n\t\t}\n\t\tString expecting = \"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@3,3:3='c',<3>,1:3]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@2,2:2='c',<3>,1:2]..[@4,4:4='c',<3>,1:4]:\\\"xyz\\\">\";\n\t\tassertNotNull(exc);\n\t\tassertEquals(expecting, exc.getMessage());\n\t}\n\n\t@Test public void testReplaceSingleMiddleThenOverlappingSuperset() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcba\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 2, \"xyz\");\n\t\ttokens.replace(0, 3, \"foo\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"fooa\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testCombineInserts() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"x\");\n\t\ttokens.insertBefore(0, \"y\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"yxabc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testCombine3Inserts() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(1, \"x\");\n\t\ttokens.insertBefore(0, \"y\");\n\t\ttokens.insertBefore(1, \"z\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"yazxbc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testCombineInsertOnLeftWithReplace() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(0, 2, \"foo\");\n\t\ttokens.insertBefore(0, \"z\");\n\t\tstream.fill();\n// combine with left edge of rewrite\n\t\tString result = tokens.getText();\n\t\tString expecting = \"zfoo\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testCombineInsertOnLeftWithDelete() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.delete(0, 2);\n\t\ttokens.insertBefore(0, \"z\");\n\t\tstream.fill();\n// combine with left edge of rewrite\n\t\tString result = tokens.getText();\n\t\tString expecting = \"z\";\n\t\tstream.fill();\n// make sure combo is not znull\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testDisjointInserts() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(1, \"x\");\n\t\ttokens.insertBefore(2, \"y\");\n\t\ttokens.insertBefore(0, \"z\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"zaxbyc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testOverlappingReplace() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(1, 2, \"foo\");\n\t\ttokens.replace(0, 3, \"bar\");\n\t\tstream.fill();\n// wipes prior nested replace\n\t\tString result = tokens.getText();\n\t\tString expecting = \"bar\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testOverlappingReplace2() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(0, 3, \"bar\");\n\t\ttokens.replace(1, 2, \"foo\");\n\t\tstream.fill();\n// cannot split earlier replace\n\t\tException exc = null;\n\t\ttry {\n\t\t\ttokens.getText();\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\texc = iae;\n\t\t}\n\t\tString expecting = \"replace op boundaries of <ReplaceOp@[@1,1:1='b',<2>,1:1]..[@2,2:2='c',<3>,1:2]:\\\"foo\\\"> overlap with previous <ReplaceOp@[@0,0:0='a',<1>,1:0]..[@3,3:3='c',<3>,1:3]:\\\"bar\\\">\";\n\t\tassertNotNull(exc);\n\t\tassertEquals(expecting, exc.getMessage());\n\t}\n\n\t@Test public void testOverlappingReplace3() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(1, 2, \"foo\");\n\t\ttokens.replace(0, 2, \"bar\");\n\t\tstream.fill();\n// wipes prior nested replace\n\t\tString result = tokens.getText();\n\t\tString expecting = \"barc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testOverlappingReplace4() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(1, 2, \"foo\");\n\t\ttokens.replace(1, 3, \"bar\");\n\t\tstream.fill();\n// wipes prior nested replace\n\t\tString result = tokens.getText();\n\t\tString expecting = \"abar\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testDropIdenticalReplace() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(1, 2, \"foo\");\n\t\ttokens.replace(1, 2, \"foo\");\n\t\tstream.fill();\n// drop previous, identical\n\t\tString result = tokens.getText();\n\t\tString expecting = \"afooc\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testDropPrevCoveredInsert() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(1, \"foo\");\n\t\ttokens.replace(1, 2, \"foo\");\n\t\tstream.fill();\n// kill prev insert\n\t\tString result = tokens.getText();\n\t\tString expecting = \"afoofoo\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLeaveAloneDisjointInsert() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(1, \"x\");\n\t\ttokens.replace(2, 3, \"foo\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"axbfoo\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLeaveAloneDisjointInsert2() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abcc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.replace(2, 3, \"foo\");\n\t\ttokens.insertBefore(1, \"x\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"axbfoo\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testInsertBeforeTokenThenDeleteThatToken() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"abc\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(2, \"y\");\n\t\ttokens.delete(2);\n\t\tString result = tokens.getText();\n\t\tString expecting = \"aby\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t// Test Fix for https://github.com/antlr/antlr4/issues/550\n\t@Test\n\tpublic void testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"aa\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"<b>\");\n\t\ttokens.insertAfter(0, \"</b>\");\n\t\ttokens.insertBefore(1, \"<b>\");\n\t\ttokens.insertAfter(1, \"</b>\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"<b>a</b><b>a</b>\"; // fails with <b>a<b></b>a</b>\"\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test\n\tpublic void testDistinguishBetweenInsertAfterAndInsertBeforeToPreserverOrder2() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"aa\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"<p>\");\n\t\ttokens.insertBefore(0, \"<b>\");\n\t\ttokens.insertAfter(0, \"</p>\");\n\t\ttokens.insertAfter(0, \"</b>\");\n\t\ttokens.insertBefore(1, \"<b>\");\n\t\ttokens.insertAfter(1, \"</b>\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"<b><p>a</p></b><b>a</b>\";\n\t\tassertEquals(expecting, result);\n\t}\n\n\t// Test Fix for https://github.com/antlr/antlr4/issues/550\n\t@Test\n\tpublic void testPreservesOrderOfContiguousInserts() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\t\t\t\t\t\t\t \"lexer grammar T;\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t \"A : 'a';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"B : 'b';\\n\" +\n\t\t\t\t\t\t\t\t\t\t\t \"C : 'c';\\n\");\n\t\tString input = \"ab\";\n\t\tLexerInterpreter lexEngine = g.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream stream = new CommonTokenStream(lexEngine);\n\t\tstream.fill();\n\t\tTokenStreamRewriter tokens = new TokenStreamRewriter(stream);\n\t\ttokens.insertBefore(0, \"<p>\");\n\t\ttokens.insertBefore(0, \"<b>\");\n\t\ttokens.insertBefore(0, \"<div>\");\n\t\ttokens.insertAfter(0, \"</p>\");\n\t\ttokens.insertAfter(0, \"</b>\");\n\t\ttokens.insertAfter(0, \"</div>\");\n\t\ttokens.insertBefore(1, \"!\");\n\t\tString result = tokens.getText();\n\t\tString expecting = \"<div><b><p>a</p></b></div>!b\";\n\t\tassertEquals(expecting, result);\n\t}\n\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/TestVisitors.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.java.api;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.BaseErrorListener;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.RecognitionException;\nimport org.antlr.v4.runtime.Recognizer;\nimport org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.RuleNode;\nimport org.antlr.v4.runtime.tree.TerminalNode;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestVisitors {\n\n\t/**\n\t * This test verifies the basic behavior of visitors, with an emphasis on\n\t * {@link AbstractParseTreeVisitor#visitTerminal}.\n\t */\n\t@Test\n\tpublic void testVisitTerminalNode() {\n\t\tString input = \"A\";\n\t\tVisitorBasicLexer lexer = new VisitorBasicLexer(new ANTLRInputStream(input));\n\t\tVisitorBasicParser parser = new VisitorBasicParser(new CommonTokenStream(lexer));\n\n\t\tVisitorBasicParser.SContext context = parser.s();\n\t\tassertEquals(\"(s A <EOF>)\", context.toStringTree(parser));\n\n\t\tVisitorBasicVisitor<String> listener = new VisitorBasicBaseVisitor<String>() {\n\t\t\t@Override\n\t\t\tpublic String visitTerminal(TerminalNode node) {\n\t\t\t\treturn node.getSymbol().toString() + \"\\n\";\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String defaultResult() {\n\t\t\t\treturn \"\";\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String aggregateResult(String aggregate, String nextResult) {\n\t\t\t\treturn aggregate + nextResult;\n\t\t\t}\n\t\t};\n\n\t\tString result = listener.visit(context);\n\t\tString expected =\n\t\t\t\"[@0,0:0='A',<1>,1:0]\\n\" +\n\t\t\t\"[@1,1:0='<EOF>',<-1>,1:1]\\n\";\n\t\tassertEquals(expected, result);\n\t}\n\n\t/**\n\t * This test verifies the basic behavior of visitors, with an emphasis on\n\t * {@link AbstractParseTreeVisitor#visitErrorNode}.\n\t */\n\t@Test\n\tpublic void testVisitErrorNode() {\n\t\tString input = \"\";\n\t\tVisitorBasicLexer lexer = new VisitorBasicLexer(new ANTLRInputStream(input));\n\t\tVisitorBasicParser parser = new VisitorBasicParser(new CommonTokenStream(lexer));\n\n\t\tfinal List<String> errors = new ArrayList<>();\n\t\tparser.removeErrorListeners();\n\t\tparser.addErrorListener(new BaseErrorListener() {\n\t\t\t@Override\n\t\t\tpublic void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {\n\t\t\t\terrors.add(\"line \" + line + \":\" + charPositionInLine + \" \" + msg);\n\t\t\t}\n\t\t});\n\n\t\tVisitorBasicParser.SContext context = parser.s();\n\t\tassertEquals(\"(s <missing 'A'> <EOF>)\", context.toStringTree(parser));\n\t\tassertEquals(1, errors.size());\n\t\tassertEquals(\"line 1:0 missing 'A' at '<EOF>'\", errors.get(0));\n\n\t\tVisitorBasicVisitor<String> listener = new VisitorBasicBaseVisitor<String>() {\n\t\t\t@Override\n\t\t\tpublic String visitErrorNode(ErrorNode node) {\n\t\t\t\treturn \"Error encountered: \" + node.getSymbol();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String defaultResult() {\n\t\t\t\treturn \"\";\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String aggregateResult(String aggregate, String nextResult) {\n\t\t\t\treturn aggregate + nextResult;\n\t\t\t}\n\t\t};\n\n\t\tString result = listener.visit(context);\n\t\tString expected = \"Error encountered: [@-1,-1:-1='<missing 'A'>',<1>,1:0]\";\n\t\tassertEquals(expected, result);\n\t}\n\n\t/**\n\t * This test verifies that {@link AbstractParseTreeVisitor#visitChildren} does not call\n\t * {@link org.antlr.v4.runtime.tree.ParseTreeVisitor#visit} after\n\t * {@link org.antlr.v4.runtime.tree.AbstractParseTreeVisitor#shouldVisitNextChild} returns\n\t * {@code false}.\n\t */\n\t@Test\n\tpublic void testShouldNotVisitEOF() {\n\t\tString input = \"A\";\n\t\tVisitorBasicLexer lexer = new VisitorBasicLexer(new ANTLRInputStream(input));\n\t\tVisitorBasicParser parser = new VisitorBasicParser(new CommonTokenStream(lexer));\n\n\t\tVisitorBasicParser.SContext context = parser.s();\n\t\tassertEquals(\"(s A <EOF>)\", context.toStringTree(parser));\n\n\t\tVisitorBasicVisitor<String> listener = new VisitorBasicBaseVisitor<String>() {\n\t\t\t@Override\n\t\t\tpublic String visitTerminal(TerminalNode node) {\n\t\t\t\treturn node.getSymbol().toString() + \"\\n\";\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected boolean shouldVisitNextChild(RuleNode node, String currentResult) {\n\t\t\t\treturn currentResult == null || currentResult.isEmpty();\n\t\t\t}\n\t\t};\n\n\t\tString result = listener.visit(context);\n\t\tString expected = \"[@0,0:0='A',<1>,1:0]\\n\";\n\t\tassertEquals(expected, result);\n\t}\n\n\t/**\n\t * This test verifies that {@link AbstractParseTreeVisitor#shouldVisitNextChild} is called before visiting the first\n\t * child. It also verifies that {@link AbstractParseTreeVisitor#defaultResult} provides the default return value for\n\t * visiting a tree.\n\t */\n\t@Test\n\tpublic void testShouldNotVisitTerminal() {\n\t\tString input = \"A\";\n\t\tVisitorBasicLexer lexer = new VisitorBasicLexer(new ANTLRInputStream(input));\n\t\tVisitorBasicParser parser = new VisitorBasicParser(new CommonTokenStream(lexer));\n\n\t\tVisitorBasicParser.SContext context = parser.s();\n\t\tassertEquals(\"(s A <EOF>)\", context.toStringTree(parser));\n\n\t\tVisitorBasicVisitor<String> listener = new VisitorBasicBaseVisitor<String>() {\n\t\t\t@Override\n\t\t\tpublic String visitTerminal(TerminalNode node) {\n\t\t\t\tthrow new RuntimeException(\"Should not be reachable\");\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String defaultResult() {\n\t\t\t\treturn \"default result\";\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected boolean shouldVisitNextChild(RuleNode node, String currentResult) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t};\n\n\t\tString result = listener.visit(context);\n\t\tString expected = \"default result\";\n\t\tassertEquals(expected, result);\n\t}\n\n\t/**\n\t * This test verifies that the visitor correctly dispatches calls for labeled outer alternatives.\n\t */\n\t@Test\n\tpublic void testCalculatorVisitor() {\n\t\tString input = \"2 + 8 / 2\";\n\t\tVisitorCalcLexer lexer = new VisitorCalcLexer(new ANTLRInputStream(input));\n\t\tVisitorCalcParser parser = new VisitorCalcParser(new CommonTokenStream(lexer));\n\n\t\tVisitorCalcParser.SContext context = parser.s();\n\t\tassertEquals(\"(s (expr (expr 2) + (expr (expr 8) / (expr 2))) <EOF>)\", context.toStringTree(parser));\n\n\t\tVisitorCalcVisitor<Integer> listener = new VisitorCalcBaseVisitor<Integer>() {\n\t\t\t@Override\n\t\t\tpublic Integer visitS(VisitorCalcParser.SContext ctx) {\n\t\t\t\treturn visit(ctx.expr());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Integer visitNumber(VisitorCalcParser.NumberContext ctx) {\n\t\t\t\treturn Integer.valueOf(ctx.INT().getText());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Integer visitMultiply(VisitorCalcParser.MultiplyContext ctx) {\n\t\t\t\tInteger left = visit(ctx.expr(0));\n\t\t\t\tInteger right = visit(ctx.expr(1));\n\t\t\t\tif (ctx.MUL() != null) {\n\t\t\t\t\treturn left * right;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn left / right;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Integer visitAdd(VisitorCalcParser.AddContext ctx) {\n\t\t\t\tInteger left = visit(ctx.expr(0));\n\t\t\t\tInteger right = visit(ctx.expr(1));\n\t\t\t\tif (ctx.ADD() != null) {\n\t\t\t\t\treturn left + right;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn left - right;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected Integer defaultResult() {\n\t\t\t\tthrow new RuntimeException(\"Should not be reachable\");\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected Integer aggregateResult(Integer aggregate, Integer nextResult) {\n\t\t\t\tthrow new RuntimeException(\"Should not be reachable\");\n\t\t\t}\n\t\t};\n\n\t\tint result = listener.visit(context);\n\t\tint expected = 6;\n\t\tassertEquals(expected, result);\n\t}\n\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/VisitorBasic.g4",
    "content": "grammar VisitorBasic;\n\ns\n\t:\t'A' EOF\n\t;\n\nA : 'A';\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/VisitorCalc.g4",
    "content": "grammar VisitorCalc;\n\ns\n\t:\texpr EOF\n\t;\n\nexpr\n\t:\tINT\t\t\t\t\t\t# number\n\t|\texpr (MUL | DIV) expr\t# multiply\n\t|\texpr (ADD | SUB) expr\t# add\n\t;\n\nINT : [0-9]+;\nMUL : '*';\nDIV : '/';\nADD : '+';\nSUB : '-';\nWS : [ \\t]+ -> channel(HIDDEN);\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/Instrumentor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.java.api.perf;\n\nimport java.lang.instrument.Instrumentation;\n\n/** Just a hook so we can call {@link java.lang.instrument.Instrumentation}\n *  methods like sizeof().  Start the Java VM with -javaagent instrumentor.jar\n *  if instrumentor.jar is where you put the .class file for this code.\n *  MANIFEST.MF for that jar must have \"Premain-Class:Instrumentor\".\n *\n *  I'm not using at moment but I'm adding in case.\n */\npublic class Instrumentor {\n\tpublic static Instrumentation instrumentation;\n\n\tpublic static void premain(String args, Instrumentation I) {\n\t\tinstrumentation = I;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/TimeLexerSpeed.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.java.api.perf;\n\nimport org.antlr.v4.runtime.ANTLRFileStream;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CharStreams;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.test.runtime.java.api.JavaLexer;\nimport org.openjdk.jol.info.GraphLayout;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.lang.management.ManagementFactory;\nimport java.lang.management.RuntimeMXBean;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/** Test how fast we can lex Java and some unicode graphemes using old and\n *  new unicode stream mechanism. It also tests load time for unicode code points beyond 0xFFFF.\n *\n *  Sample output on Linux with Intel Xeon E5-2600 @ 2.20 GHz (us == microseconds, 1/1000 of a millisecond):\n *\nJava VM args:\nWarming up Java compiler....\n    load_legacy_java_utf8 average time   273us size 132266b over 3500 loads of 29038 symbols from Parser.java\n    load_legacy_java_utf8 average time   299us size 128386b over 3500 loads of 13379 symbols from udhr_hin.txt\n            load_new_utf8 average time   535us size 284788b over 3500 loads of 29038 symbols from Parser.java\n            load_new_utf8 average time   439us size 153150b over 3500 loads of 13379 symbols from udhr_hin.txt\n\n     lex_legacy_java_utf8 average time   624us over 2000 runs of 29038 symbols\n     lex_legacy_java_utf8 average time  1530us over 2000 runs of 29038 symbols DFA cleared\n        lex_new_java_utf8 average time   672us over 2000 runs of 29038 symbols\n        lex_new_java_utf8 average time  1671us over 2000 runs of 29038 symbols DFA cleared\n\n lex_legacy_grapheme_utf8 average time 11942us over  400 runs of  6614 symbols from udhr_kor.txt\n lex_legacy_grapheme_utf8 average time 12075us over  400 runs of  6614 symbols from udhr_kor.txt DFA cleared\n lex_legacy_grapheme_utf8 average time 10040us over  400 runs of 13379 symbols from udhr_hin.txt\n lex_legacy_grapheme_utf8 average time 10221us over  400 runs of 13379 symbols from udhr_hin.txt DFA cleared\n *\n *  Sample output on OS X with 4 GHz Intel Core i7 (us == microseconds, 1/1000 of a millisecond):\n *\n Java VM args: -Xms2G -Xmx8g\n Warming up Java compiler....\n load_legacy_java_ascii_file average time    53us size  58384b over 3500 loads of 29038 symbols from Parser.java\n load_legacy_java_ascii_file average time    27us size  15568b over 3500 loads of  7625 symbols from RuleContext.java\n      load_legacy_java_ascii average time    53us size  65584b over 3500 loads of 29038 symbols from Parser.java\n      load_legacy_java_ascii average time    13us size  32816b over 3500 loads of  7625 symbols from RuleContext.java\n       load_legacy_java_utf8 average time    54us size  65584b over 3500 loads of 29038 symbols from Parser.java\n       load_legacy_java_utf8 average time   118us size  32816b over 3500 loads of 13379 symbols from udhr_hin.txt\n               load_new_utf8 average time   232us size 131232b over 3500 loads of 29038 symbols from Parser.java\n               load_new_utf8 average time    69us size  32928b over 3500 loads of  7625 symbols from RuleContext.java\n               load_new_utf8 average time   210us size  65696b over 3500 loads of 13379 symbols from udhr_hin.txt\n\n        lex_legacy_java_utf8 average time   342us over 2000 runs of 29038 symbols\n        lex_legacy_java_utf8 average time   890us over 2000 runs of 29038 symbols DFA cleared\n           lex_new_java_utf8 average time   439us over 2000 runs of 29038 symbols\n           lex_new_java_utf8 average time   969us over 2000 runs of 29038 symbols DFA cleared\n\n    lex_legacy_grapheme_utf8 average time  3971us over  400 runs of  6614 symbols from udhr_kor.txt\n    lex_legacy_grapheme_utf8 average time  4084us over  400 runs of  6614 symbols from udhr_kor.txt DFA cleared\n    lex_legacy_grapheme_utf8 average time  7542us over  400 runs of 13379 symbols from udhr_hin.txt\n    lex_legacy_grapheme_utf8 average time  7666us over  400 runs of 13379 symbols from udhr_hin.txt DFA cleared\n       lex_new_grapheme_utf8 average time  4034us over  400 runs of  6614 symbols from udhr_kor.txt\n       lex_new_grapheme_utf8 average time  4173us over  400 runs of  6614 symbols from udhr_kor.txt DFA cleared\n       lex_new_grapheme_utf8 average time  7680us over  400 runs of 13379 symbols from udhr_hin.txt\n       lex_new_grapheme_utf8 average time  7946us over  400 runs of 13379 symbols from udhr_hin.txt DFA cleared\n       lex_new_grapheme_utf8 average time    70us over  400 runs of    85 symbols from emoji.txt\n       lex_new_grapheme_utf8 average time    82us over  400 runs of    85 symbols from emoji.txt DFA cleared\n *\n *  I dump footprint now too (this is 64-bit HotSpot VM):\n *\n Parser.java (29038 char): org.antlr.v4.runtime.ANTLRFileStream@6b8e0782d footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          2     29164     58328   [C\n          1        24        24   java.lang.String\n          1        32        32   org.antlr.v4.runtime.ANTLRFileStream\n          4               58384   (total)\n\n RuleContext.java (7625 char): org.antlr.v4.runtime.ANTLRFileStream@76fb7505d footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          2      7756     15512   [C\n          1        24        24   java.lang.String\n          1        32        32   org.antlr.v4.runtime.ANTLRFileStream\n          4               15568   (total)\n\n Parser.java (29038 char): org.antlr.v4.runtime.ANTLRInputStream@1fc1cb1d footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          1     65552     65552   [C\n          1        32        32   org.antlr.v4.runtime.ANTLRInputStream\n          2               65584   (total)\n\n RuleContext.java (7625 char): org.antlr.v4.runtime.ANTLRInputStream@2c6aa25dd footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          1     32784     32784   [C\n          1        32        32   org.antlr.v4.runtime.ANTLRInputStream\n          2               32816   (total)\n\n Parser.java (29038 char): org.antlr.v4.runtime.ANTLRInputStream@3d08db0bd footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          1     65552     65552   [C\n          1        32        32   org.antlr.v4.runtime.ANTLRInputStream\n          2               65584   (total)\n\n udhr_hin.txt (13379 char): org.antlr.v4.runtime.ANTLRInputStream@486dc6f3d footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          1     32784     32784   [C\n          1        32        32   org.antlr.v4.runtime.ANTLRInputStream\n          2               32816   (total)\n\n Parser.java (29038 char): org.antlr.v4.runtime.CodePointCharStream@798fe5a1d footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          1        40        40   [C\n          1    131088    131088   [I\n          1        24        24   java.lang.String\n          1        48        48   java.nio.HeapIntBuffer\n          1        32        32   org.antlr.v4.runtime.CodePointCharStream\n          5              131232   (total)\n\n RuleContext.java (7625 char): org.antlr.v4.runtime.CodePointCharStream@29cf5a20d footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          1        40        40   [C\n          1     32784     32784   [I\n          1        24        24   java.lang.String\n          1        48        48   java.nio.HeapIntBuffer\n          1        32        32   org.antlr.v4.runtime.CodePointCharStream\n          5               32928   (total)\n\n udhr_hin.txt (13379 char): org.antlr.v4.runtime.CodePointCharStream@1adb8a22d footprint:\n      COUNT       AVG       SUM   DESCRIPTION\n          1        40        40   [C\n          1     65552     65552   [I\n          1        24        24   java.lang.String\n          1        48        48   java.nio.HeapIntBuffer\n          1        32        32   org.antlr.v4.runtime.CodePointCharStream\n          5               65696   (total)\n *\n *  The \"DFA cleared\" indicates that the lexer was returned to initial conditions\n *  before the tokenizing of each file.\t As the ALL(*) lexer encounters new input,\n *  it records how it tokenized the chars. The next time it sees that input,\n *  it will more quickly recognize the token.\n *\n *  Lexing times have the top 20% stripped off before doing the average\n *  to account for issues with the garbage collection and compilation pauses;\n *  other OS tasks could also pop in randomly.\n *\n *  Load times are too fast to measure with a microsecond clock using an SSD\n *  so the average load time is computed as the overall time to load\n *  n times divided by n (rather then summing up the individual times).\n *\n *  @since 4.7\n */\npublic class TimeLexerSpeed { // don't call it Test else it'll run during \"mvn test\"\n\tpublic static final String Parser_java_file = \"Java/src/org/antlr/v4/runtime/Parser.java\";\n\tpublic static final String RuleContext_java_file = \"Java/src/org/antlr/v4/runtime/RuleContext.java\";\n\tpublic static final String PerfDir = \"org/antlr/v4/test/runtime/java/api/perf\";\n\n\tpublic boolean output = true;\n\n\tpublic List<String> streamFootprints = new ArrayList<>();\n\n\tpublic static void main(String[] args) throws Exception {\n\t\tRuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();\n\t\tList<String> vmArgs = runtimeMxBean.getInputArguments();\n\t\tSystem.out.print(\"Java VM args: \");\n\t\tfor (String vmArg : vmArgs) {\n\t\t\tif ( !vmArg.startsWith(\"-D\") ) {\n\t\t\t\tSystem.out.print(vmArg+\" \");\n\t\t\t}\n\t\t}\n\t\tSystem.out.println();\n//\t\tSystem.out.println(VM.current().details());\n\n\t\tTimeLexerSpeed tests = new TimeLexerSpeed();\n\n\t\ttests.compilerWarmUp(100);\n\n\t\tint n = 3500;\n\t\ttests.load_legacy_java_ascii_file(Parser_java_file, n);\n\t\ttests.load_legacy_java_ascii_file(RuleContext_java_file, n);\n\t\ttests.load_legacy_java_ascii(Parser_java_file, n);\n\t\ttests.load_legacy_java_ascii(RuleContext_java_file, n);\n\t\ttests.load_legacy_java_utf8(Parser_java_file, n);\n\t\ttests.load_legacy_java_utf8(PerfDir+\"/udhr_hin.txt\", n);\n\t\ttests.load_new_utf8(Parser_java_file, n);\n\t\ttests.load_new_utf8(RuleContext_java_file, n);\n\t\ttests.load_new_utf8(PerfDir+\"/udhr_hin.txt\", n);\n\t\tSystem.out.println();\n\n\t\tn = 2000;\n\t\ttests.lex_legacy_java_utf8(n, false);\n\t\ttests.lex_legacy_java_utf8(n, true);\n\t\ttests.lex_new_java_utf8(n, false);\n\t\ttests.lex_new_java_utf8(n, true);\n\t\tSystem.out.println();\n\n\t\tn = 400;\n\t\ttests.lex_legacy_grapheme_utf8(\"udhr_kor.txt\", n, false);\n\t\ttests.lex_legacy_grapheme_utf8(\"udhr_kor.txt\", n, true);\n\t\ttests.lex_legacy_grapheme_utf8(\"udhr_hin.txt\", n, false);\n\t\ttests.lex_legacy_grapheme_utf8(\"udhr_hin.txt\", n, true);\n\t\t// legacy can't handle the emoji (32 bit stuff)\n\n\t\ttests.lex_new_grapheme_utf8(\"udhr_kor.txt\", n, false);\n\t\ttests.lex_new_grapheme_utf8(\"udhr_kor.txt\", n, true);\n\t\ttests.lex_new_grapheme_utf8(\"udhr_hin.txt\", n, false);\n\t\ttests.lex_new_grapheme_utf8(\"udhr_hin.txt\", n, true);\n\t\ttests.lex_new_grapheme_utf8(\"emoji.txt\", n, false);\n\t\ttests.lex_new_grapheme_utf8(\"emoji.txt\", n, true);\n\n\t\tfor (String streamFootprint : tests.streamFootprints) {\n\t\t\tSystem.out.print(streamFootprint);\n\t\t}\n\t}\n\n\tpublic void compilerWarmUp(int n) throws Exception {\n\t\tSystem.out.print(\"Warming up Java compiler\");\n\t\toutput = false;\n\t\tlex_new_java_utf8(n, false);\n\t\tSystem.out.print('.');\n\t\tlex_legacy_java_utf8(n, false);\n\t\tSystem.out.print('.');\n\t\tSystem.out.print('.');\n\t\tlex_legacy_grapheme_utf8(\"udhr_hin.txt\", n, false);\n\t\tSystem.out.print('.');\n\t\tlex_new_grapheme_utf8(\"udhr_hin.txt\", n, false);\n\t\tSystem.out.println();\n\t\toutput = true;\n\t}\n\n\tpublic void load_legacy_java_ascii_file(String resourceName, int n) throws Exception {\n\t\tURL sampleJavaFile = TimeLexerSpeed.class.getClassLoader().getResource(resourceName);\n\t\tif ( sampleJavaFile==null ) {\n\t\t\tSystem.err.println(\"Can't run load_legacy_java_ascii_file from jar (or can't find \"+resourceName+\")\");\n\t\t\treturn; // cannot find resource\n\t\t}\n\t\tif ( !new File(sampleJavaFile.getFile()).exists() ) {\n\t\t\tSystem.err.println(\"Can't run load_legacy_java_ascii_file from jar (or can't find \"+resourceName+\")\");\n\t\t\treturn;\n\t\t}\n\t\tlong start = System.nanoTime();\n\t\tCharStream[] input = new CharStream[n]; // keep refs around so we can average memory\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\tinput[i] = new ANTLRFileStream(sampleJavaFile.getFile());\n\t\t}\n\t\tlong stop = System.nanoTime();\n\t\tlong tus = (stop-start)/1000;\n\t\tint size = input[0].size();\n\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\tGraphLayout olayout = GraphLayout.parseInstance((Object) input[0]);\n\t\tlong streamSize = olayout.totalSize();\n\t\tstreamFootprints.add(basename(resourceName)+\" (\"+size+\" char): \"+olayout.toFootprint());\n\t\tif ( output ) System.out.printf(\"%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\\n\",\n\t\t                                currentMethodName,\n\t\t                                tus/n,\n\t\t                                streamSize,\n\t\t                                n,\n\t\t                                size,\n\t\t                                basename(resourceName));\n\t}\n\n\tpublic void load_legacy_java_ascii(String resourceName, int n) throws Exception {\n\t\tCharStream[] input = new CharStream[n]; // keep refs around so we can average memory\n\t\tClassLoader loader = TimeLexerSpeed.class.getClassLoader();\n\t\tInputStream[] streams = new InputStream[n];\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\tstreams[i] = loader.getResourceAsStream(resourceName);\n\t\t}\n\t\tlong start = System.nanoTime(); // track only time to suck data out of stream\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\ttry (InputStream is = streams[i]) {\n\t\t\t\tinput[i] = new ANTLRInputStream(is);\n\t\t\t}\n\t\t}\n\t\tlong stop = System.nanoTime();\n\t\tlong tus = (stop-start)/1000;\n\t\tint size = input[0].size();\n\t\tlong streamSize = GraphLayout.parseInstance((Object)input[0]).totalSize();\n\t\tstreamFootprints.add(basename(resourceName)+\" (\"+size+\" char): \"+GraphLayout.parseInstance((Object)input[0]).toFootprint());\n\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\tif ( output ) System.out.printf(\"%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\\n\",\n\t\t                                currentMethodName,\n\t\t                                tus/n,\n\t\t                                streamSize,\n\t\t                                n,\n\t\t                                size,\n\t\t                                basename(resourceName));\n\t}\n\n\tpublic void load_legacy_java_utf8(String resourceName, int n) throws Exception {\n\t\tCharStream[] input = new CharStream[n]; // keep refs around so we can average memory\n\t\tClassLoader loader = TimeLexerSpeed.class.getClassLoader();\n\t\tInputStream[] streams = new InputStream[n];\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\tstreams[i] = loader.getResourceAsStream(resourceName);\n\t\t}\n\t\tlong start = System.nanoTime(); // track only time to suck data out of stream\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\ttry (InputStream is = streams[i];\n\t\t\t     InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);\n\t\t\t     BufferedReader br = new BufferedReader(isr)) {\n\t\t\t\tinput[i] = new ANTLRInputStream(br);\n\t\t\t}\n\t\t}\n\t\tlong stop = System.nanoTime();\n\t\tlong tus = (stop-start)/1000;\n\t\tint size = input[0].size();\n\t\tlong streamSize = GraphLayout.parseInstance((Object)input[0]).totalSize();\n\t\tstreamFootprints.add(basename(resourceName)+\" (\"+size+\" char): \"+GraphLayout.parseInstance((Object)input[0]).toFootprint());\n\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\tif ( output ) System.out.printf(\"%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\\n\",\n\t\t                                currentMethodName,\n\t\t                                tus/n,\n\t\t                                streamSize,\n\t\t                                n,\n\t\t                                size,\n\t\t                                basename(resourceName));\n\t}\n\n\tpublic void load_new_utf8(String resourceName, int n) throws Exception {\n\t\tCharStream[] input = new CharStream[n]; // keep refs around so we can average memory\n\t\tClassLoader loader = TimeLexerSpeed.class.getClassLoader();\n\t\tInputStream[] streams = new InputStream[n];\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\tstreams[i] = loader.getResourceAsStream(resourceName);\n\t\t}\n\t\tURLConnection uc = null;\n\t\tlong streamLength = getResourceSize(loader, resourceName);\n\t\tlong start = System.nanoTime(); // track only time to suck data out of stream\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\ttry (InputStream is = streams[i]) {\n\t\t\t\tinput[i] = CharStreams.fromStream(is, StandardCharsets.UTF_8, streamLength);\n\t\t\t}\n\t\t}\n\t\tlong stop = System.nanoTime();\n\t\tlong tus = (stop-start)/1000;\n\t\tint size = input[0].size();\n\t\tlong streamSize = GraphLayout.parseInstance((Object)input[0]).totalSize();\n\t\tstreamFootprints.add(basename(resourceName)+\" (\"+size+\" char): \"+GraphLayout.parseInstance((Object)input[0]).toFootprint());\n\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\tif ( output ) System.out.printf(\"%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\\n\",\n\t\t\t\t\t\tcurrentMethodName,\n\t\t\t\t\t\ttus/n,\n\t\t\t\t\t\tstreamSize,\n\t\t\t\t\t\tn,\n\t\t\t\t\t\tsize,\n\t\t\t\t\t\tbasename(resourceName));\n\t}\n\n\tpublic void lex_legacy_java_utf8(int n, boolean clearLexerDFACache) throws Exception {\n\t\ttry (InputStream is = TimeLexerSpeed.class.getClassLoader().getResourceAsStream(Parser_java_file);\n\t\t     InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);\n\t\t     BufferedReader br = new BufferedReader(isr)) {\n\t\t\tCharStream input = new ANTLRInputStream(br);\n\t\t\tJavaLexer lexer = new JavaLexer(input);\n\t\t\tdouble avg = tokenize(lexer, n, clearLexerDFACache);\n\t\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\t\tif ( output ) System.out.printf(\"%27s average time %5dus over %4d runs of %5d symbols%s\\n\",\n\t\t\t\t\t\t\tcurrentMethodName,\n\t\t\t\t\t\t\t(int)avg,\n\t\t\t\t\t\t\tn,\n\t\t\t\t\t\t\tinput.size(),\n\t\t\t\t\t\t\tclearLexerDFACache ? \" DFA cleared\" : \"\");\n\t\t}\n\t}\n\n\tpublic void lex_new_java_utf8(int n, boolean clearLexerDFACache) throws Exception {\n\t\tClassLoader loader = TimeLexerSpeed.class.getClassLoader();\n\t\ttry (InputStream is = loader.getResourceAsStream(Parser_java_file)) {\n\t\t\tlong size = getResourceSize(loader, Parser_java_file);\n\t\t\tCharStream input = CharStreams.fromStream(is, StandardCharsets.UTF_8, size);\n\t\t\tJavaLexer lexer = new JavaLexer(input);\n\t\t\tdouble avg = tokenize(lexer, n, clearLexerDFACache);\n\t\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\t\tif ( output ) System.out.printf(\"%27s average time %5dus over %4d runs of %5d symbols%s\\n\",\n\t\t\t\t\t\t\tcurrentMethodName,\n\t\t\t\t\t\t\t(int)avg,\n\t\t\t\t\t\t\tn,\n\t\t\t\t\t\t\tinput.size(),\n\t\t\t\t\t\t\tclearLexerDFACache ? \" DFA cleared\" : \"\");\n\t\t}\n\t}\n\n\tpublic void lex_legacy_grapheme_utf8(String fileName, int n, boolean clearLexerDFACache) throws Exception {\n\t\ttry (InputStream is = TimeLexerSpeed.class.getClassLoader().getResourceAsStream(PerfDir+\"/\"+fileName);\n\t\t     InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);\n\t\t     BufferedReader br = new BufferedReader(isr)) {\n\t\t\tCharStream input = new ANTLRInputStream(br);\n\t\t\tgraphemesLexer lexer = new graphemesLexer(input);\n\t\t\tdouble avg = tokenize(lexer, n, clearLexerDFACache);\n\t\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\t\tif ( output ) System.out.printf(\"%27s average time %5dus over %4d runs of %5d symbols from %s%s\\n\",\n\t\t\t\t\t\t\tcurrentMethodName,\n\t\t\t\t\t\t\t(int)avg,\n\t\t\t\t\t\t\tn,\n\t\t\t\t\t\t\tinput.size(),\n\t\t\t\t\t\t\tfileName,\n\t\t\t\t\t\t\tclearLexerDFACache ? \" DFA cleared\" : \"\");\n\t\t}\n\t}\n\n\tpublic void lex_new_grapheme_utf8(String fileName, int n, boolean clearLexerDFACache) throws Exception {\n\t\tString resourceName = PerfDir+\"/\"+fileName;\n\t\tClassLoader loader = TimeLexerSpeed.class.getClassLoader();\n\t\ttry (InputStream is = loader.getResourceAsStream(resourceName)) {\n\t\t\tlong size = getResourceSize(loader, resourceName);\n\t\t\tCharStream input = CharStreams.fromStream(is, StandardCharsets.UTF_8, size);\n\t\t\tgraphemesLexer lexer = new graphemesLexer(input);\n\t\t\tdouble avg = tokenize(lexer, n, clearLexerDFACache);\n\t\t\tString currentMethodName = new Exception().getStackTrace()[0].getMethodName();\n\t\t\tif ( output ) System.out.printf(\"%27s average time %5dus over %4d runs of %5d symbols from %s%s\\n\",\n\t\t\t\t\t\t\tcurrentMethodName,\n\t\t\t\t\t\t\t(int)avg,\n\t\t\t\t\t\t\tn,\n\t\t\t\t\t\t\tinput.size(),\n\t\t\t\t\t\t\tfileName,\n\t\t\t\t\t\t\tclearLexerDFACache ? \" DFA cleared\" : \"\");\n\t\t}\n\t}\n\n\tpublic double tokenize(Lexer lexer, int n, boolean clearLexerDFACache) {\n\t\t// always wipe the DFA before we begin tests so previous tests\n\t\t// don't affect this run!\n\t\tlexer.getInterpreter().clearDFA();\n\t\tlong[] times = new long[n];\n\t\tfor (int i = 0; i<n; i++) {\n\t\t\tlexer.reset();\n\t\t\tif ( clearLexerDFACache ) {\n\t\t\t\tlexer.getInterpreter().clearDFA();\n\t\t\t}\n\t\t\tlong start = System.nanoTime();\n\t\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\t\t\ttokens.fill(); // lex whole file.\n//\t\t\tint size = lexer.getInputStream().size();\n\t\t\tlong stop = System.nanoTime();\n\t\t\ttimes[i] = (stop-start)/1000;\n//\t\t\tif ( output ) System.out.printf(\"Tokenized %d char in %dus\\n\", size, times[i]);\n\t\t}\n\t\tArrays.sort(times);\n\t\ttimes = Arrays.copyOfRange(times, 0, times.length-(int)(n*.2)); // drop highest 20% of times\n\t\treturn avg(times);\n\t}\n\n\tpublic double avg(long[] values) {\n\t\tdouble sum = 0.0;\n\t\tfor (Long v : values) {\n\t\t\tsum += v;\n\t\t}\n\t\treturn sum / values.length;\n\t}\n\n\tpublic double std(double mean, List<Long> values) { // unbiased std dev\n\t\tdouble sum = 0.0;\n\t\tfor (Long v : values) {\n\t\t\tsum += (v-mean)*(v-mean);\n\t\t}\n\t\treturn Math.sqrt(sum / (values.size() - 1));\n\t}\n\n\tpublic static String basename(String fullyQualifiedFileName) {\n\t\tPath path = Paths.get(fullyQualifiedFileName);\n\t\treturn basename(path);\n\t}\n\n\tpublic static String dirname(String fullyQualifiedFileName) {\n\t\tPath path = Paths.get(fullyQualifiedFileName);\n\t\treturn dirname(path);\n\t}\n\n\tpublic static String basename(Path path) {\n\t\treturn path.getName(path.getNameCount()-1).toString();\n\t}\n\n\tpublic static String dirname(Path path) {\n\t\treturn path.getName(0).toString();\n\t}\n\n\tpublic static long getResourceSize(ClassLoader loader, String resourceName) throws IOException {\n\t\tURLConnection uc = null;\n\t\ttry {\n\t\t\t// Sadly, URLConnection is not AutoCloseable, but it leaks resources if\n\t\t\t// we don't close its stream.\n\t\t\tuc = loader.getResource(resourceName).openConnection();\n\t\t\treturn uc.getContentLengthLong();\n\t\t} finally {\n\t\t\tif (uc != null) {\n\t\t\t\tuc.getInputStream().close();\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/emoji.txt",
    "content": "😀🖖💩\n👴🏽🖖🏿👦🏼\n👮‍♀️👷‍♀️👯‍♂️\n🙇🏻‍♀️👼🏽🎅🏿\n01234\n0️⃣1️⃣2️⃣3️⃣4️⃣\n™©®\n™️©️®️\n🇨🇨🇧🇬🇯🇲\n🏳️‍🌈\n🏴‍☠️\n\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/graphemes.g4",
    "content": "grammar graphemes;\n\nExtend: [\\p{Grapheme_Cluster_Break=Extend}];\nZWJ: '\\u200D';\nSpacingMark: [\\p{Grapheme_Cluster_Break=SpacingMark}];\nfragment VS15: '\\uFE0E';\nfragment VS16: '\\uFE0F';\nfragment NonspacingMark: [\\p{Nonspacing_Mark}];\nfragment TextPresentationCharacter: [\\p{EmojiPresentation=TextDefault}];\nfragment EmojiPresentationCharacter: [\\p{EmojiPresentation=EmojiDefault}];\nfragment TextPresentationSequence: EmojiPresentationCharacter VS15;\nfragment EmojiPresentationSequence: TextPresentationCharacter VS16;\n\n/* No Longer supported; see https://github.com/antlr/antlr4/pull/3261\nfragment EmojiModifierSequence:\n    [\\p{Grapheme_Cluster_Break=E_Base}\\p{Grapheme_Cluster_Break=E_Base_GAZ}] [\\p{Grapheme_Cluster_Break=E_Modifier}];\n*/\n\nfragment EmojiFlagSequence:\n    [\\p{Grapheme_Cluster_Break=Regional_Indicator}] [\\p{Grapheme_Cluster_Break=Regional_Indicator}];\nfragment ExtendedPictographic: [\\p{Extended_Pictographic}];\nfragment EmojiNRK: [\\p{EmojiNRK}];\nfragment EmojiCombiningSequence:\n  (   EmojiPresentationSequence\n    | TextPresentationSequence\n    | EmojiPresentationCharacter )\n  NonspacingMark*;\nEmojiCoreSequence:\n    EmojiCombiningSequence\n  | EmojiFlagSequence;\nfragment EmojiZWJElement:\n    EmojiPresentationSequence\n  | EmojiPresentationCharacter\n  | ExtendedPictographic\n  | EmojiNRK;\nEmojiZWJSequence:\n    EmojiZWJElement (ZWJ EmojiZWJElement)+;\nemoji_sequence:\n  (   EmojiZWJSequence\n    | EmojiCoreSequence )\n  ( Extend | ZWJ | SpacingMark )*;\n\nPrepend: [\\p{Grapheme_Cluster_Break=Prepend}];\nNonControl: [\\P{Grapheme_Cluster_Break=Control}];\nCRLF: [\\p{Grapheme_Cluster_Break=CR}][\\p{Grapheme_Cluster_Break=LF}];\nHangulSyllable:\n    [\\p{Grapheme_Cluster_Break=L}]* [\\p{Grapheme_Cluster_Break=V}]+ [\\p{Grapheme_Cluster_Break=T}]*\n  | [\\p{Grapheme_Cluster_Break=L}]* [\\p{Grapheme_Cluster_Break=LV}] [\\p{Grapheme_Cluster_Break=V}]* [\\p{Grapheme_Cluster_Break=T}]*\n  | [\\p{Grapheme_Cluster_Break=L}]* [\\p{Grapheme_Cluster_Break=LVT}] [\\p{Grapheme_Cluster_Break=T}]*\n  | [\\p{Grapheme_Cluster_Break=L}]+\n  | [\\p{Grapheme_Cluster_Break=T}]+;\n\ngrapheme_cluster:\n    CRLF\n  | Prepend* ( emoji_sequence | HangulSyllable | NonControl ) ( Extend | ZWJ | SpacingMark )*;\n\ngraphemes: grapheme_cluster* EOF;\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/udhr_hin.txt",
    "content": "Universal Declaration of Human Rights - Hindi\n© 1996 – 2009 The Office of the High Commissioner for Human Rights\nThis plain text version prepared by the “UDHR in Unicode”\nproject, http://www.unicode.org/udhr.\n---\n\nमानव अधिकारों की सार्वभौम घोषणा\n      १० दिसम्बर १९४८ को यूनाइटेड नेशन्स की जनरल असेम्बली ने मानव अधिकारों की सार्वभौम घोषणा को स्वीकृत और घोषित किया । इसका पूर्ण पाठ आगे के पृष्ठों में दिया गया है । इस ऐतिहासिक कार्य के बाद ही असेम्बली ने सभी सदस्य देशों से अपील की कि वे इस घोषणा का प्रचार करें और देशों अथवा प्रदेशों की राजनैतिक स्थिति पर आधारित भेदभाव का विचार किए बिना, विशेषतः स्कूलों और अन्य शिक्षा संस्थाओं में इसके प्रचार, प्रदर्शन, पठन और व्याख्या का प्रबन्ध करें ।\n      इसी घोषणा का सरकारी पाठ संयुक्त राष्ट्रों की इन पांच भाषाओं में प्राप्य हैः—अंग्रेजी, चीनी, फ्रांसीसी, रूसी और स्पेनिश । अनुवाद का जो पाठ यहां दिया गया है, वह भारत सरकार द्वारा स्वीकृत है ।\n   \n      प्रस्तावना\n      चूंकि मानव परिवार के सभी सदस्यों के जन्मजात गौरव और समान तथा अविच्छिन्न अधिकार की स्वीकृति ही विश्व-शान्ति, न्याय और स्वतन्त्रता की बुनियाद है,\n      चूंकि मानव अधिकारों के प्रति उपेक्षा और घृणा के फलस्वरूप ही ऐसे बर्बर कार्य हुए जिनसे मनुष्य की आत्मा पर अत्याचार किया गया, चूंकि एक ऐसी विश्व-व्यवस्था की उस स्थापना को ( जिसमें लोगों को भाषण और धर्म की आज़ादी तथा भय और अभाव से मुक्ति मिलेगी ) सर्वसाधारण के लिए सर्वोच्च आकांक्षा घोषित किया गया है,\n      चूंकि अगर अन्याययुक्त शासन और जुल्म के विरुद्घ लोगों को विद्रोह करने के लिए—उसे ही अन्तिम उपाय समझ कर—मजबूर नहीं हो जाना है, तो कानून द्वारा नियम बनाकर मानव अधिकारों की रक्षा करना अनिवार्य है,\n      चूंकि राष्ट्रों के बीच मैत्रीपूर्ण सम्बन्धों को बढ़ाना ज़रूरी है,\n      चूंकि संयुक्त राष्ट्रों के सदस्य देशों की जनताओं ने बुनियादी मानव अधिकारों में, मानव व्यक्तित्व के गौरव और योग्यता में और नरनारियों के समान अधिकारों में अपने विश्वास को अधिकार-पत्र में दुहराया है और यह निश्चय किया है कि अधिक व्यापक स्वतन्त्रता के अन्तर्गत सामाजिक प्रगति एवं जीवन के बेहतर स्तर को ऊंचा किया जाया,\n      चूंकि सदस्य देशों ने यह प्रतिज्ञा को है कि वे संयुक्त राष्ट्रों के सहयोग से मानव अधिकारों और बुनियादी आज़ादियों के प्रति सार्वभौम सम्मान की वृद्घि करेंगे,\n      चूंकि इस प्रतिज्ञा को पूरी तरह से निभाने के लिए इन अधिकारों और आज़ादियों का स्वरूप ठीक-ठीक समझना सबसे अधिक ज़रूरी है । इसलिए, अब,\n      सामान्य सभा\n      घोषित करती है कि\n      मानव अधिकारों की यह सार्वभौम घोषणा सभी देशों और सभी लोगों की समान सफलता है । इसका उद्देश्य यह है कि प्रत्येक व्यक्ति और समाज का प्रत्येक भाग इस घोषणा को लगातार दृष्टि में रखते हुए अध्यापन और शिक्षा के द्वारा यह प्रयत्न करेगा कि इन अधिकारों और आज़ादियों के प्रति सम्मान की भावना जाग्रत हो, और उत्तरोत्तर ऐसे राष्ट्रीय तथा अन्तर्राष्ट्रीय उपाय किये जाएं जिनसे सदस्य देशों की जनता तथा उनके द्वारा अधिकृत प्रदेशों की जनता इन अधिकारों की सार्वभौम और प्रभावोत्पादक स्वीकृति दे और उनका पालन करावे ।\n   \n      अनुच्छेद १.\n      सभी मनुष्यों को गौरव और अधिकारों के मामले में जन्मजात स्वतन्त्रता और समानता प्राप्त है । उन्हें बुद्धि और अन्तरात्मा की देन प्राप्त है और परस्पर उन्हें भाईचारे के भाव से बर्ताव करना चाहिए ।\n   \n      अनुच्छेद २.\n      सभी को इस घोषणा में सन्निहित सभी अधिकारों और आज़ादियों को प्राप्त करने का हक़ है और इस मामले में जाति, वर्ण, लिंग, भाषा, धर्म, राजनीति या अन्य विचार-प्रणाली, किसी देश या समाज विशेष में जन्म, सम्पत्ति या किसी प्रकार की अन्य मर्यादा आदि के कारण भेदभाव का विचार न किया जाएगा ।\n      इसके अतिरिक्त, चाहे कोई देश या प्रदेश स्वतन्त्र हो, संरक्षित हो, या स्त्रशासन रहित हो या परिमित प्रभुसत्ता वाला हो, उस देश या प्रदेश की राजनैतिक, क्षेत्रीय या अन्तर्राष्ट्रीय स्थिति के आधार पर वहां के निवासियों के प्रति कोई फ़रक़ न रखा जाएगा ।\n   \n      अनुच्छेद ३.\n      प्रत्येक व्यक्ति को जीवन, स्वाधीनता और वैयक्तिक सुरक्षा का अधिकार है ।\n   \n      अनुच्छेद ४.\n      कोई भी ग़ुलामी या दासता की हालत में न रखा जाएगा, ग़ुलामी-प्रथा और ग़ुलामों का व्यापार अपने सभी रूपों में निषिद्ध होगा ।\n   \n      अनुच्छेद ५.\n      किसी को भी शारीरिक यातना न दी जाएगी और न किसी के भी प्रति निर्दय, अमानुषिक या अपमानजनक व्यवहार होगा ।\n   \n      अनुच्छेद ६.\n      हर किसी को हर जगह क़ानून की निग़ाह में व्यक्ति के रूप में स्वीकृति-प्राप्ति का अधिकार है ।\n   \n      अनुच्छेद ७.\n      क़ानून की निग़ाह में सभी समान हैं और सभी बिना भेदभाव के समान क़ानूनी सुरक्षा के अधिकारी हैं । यदि इस घोषणा का अतिक्रमण करके कोई भी भेद-भाव किया जाया उस प्रकार के भेद-भाव को किसी प्रकार से उकसाया जाया, तो उसके विरुद्ध समान संरक्षण का अधिकार सभी को प्राप्त है ।\n   \n      अनुच्छेद ८.\n      सभी को संविधान या क़ानून द्वारा प्राप्त बुनियादी अधिकारों का अतिक्रमण करने वाले कार्यों के विरुद्ध समुचित राष्ट्रीय अदालतों की कारगर सहायता पाने का हक़ है ।\n   \n      अनुच्छेद ९.\n      किसी को भी मनमाने ढंग से गिरफ़्तार, नज़रबन्द या देश-निष्कासित न किया जाएगा ।\n   \n      अनुच्छेद १०.\n      सभी को पूर्णत: समान रूप से हक़ है कि उनके अधिकारों और कर्तव्यों के निश्चय करने के मामले में और उन पर आरोपित फौज़दारी के किसी मामले में उनकी सुनवाई न्यायोचित और सार्वजनिक रूप से निरपेक्ष एवं निष्पक्ष अदालत द्वारा हो ।\n   \n      अनुच्छेद ११.\n      \n         \n            प्रत्येक व्यक्ति, जिस पर दण्डनीय अपराध का आरोप किया गया हो, तब तक निरपराध माना जाएगा, जब तक उसे ऐसी खुली अदालत में, जहां उसे अपनी सफ़ाई की सभी आवश्यक सुविधाएं प्राप्त हों, कानून के अनुसार अपराधी न सिद्ध कर दिया जाया ।\n         \n         \n            कोई भी व्यक्ति किसी भी ऐसे कृत या अकृत (अपराध) के कारण उस दण्डनीय अपराध का अपराधी न माना जाएगा, जिसे तत्कालीन प्रचलित राष्ट्रीय या अन्तर्राष्ट्रीय क़ानून के अनुसार दण्डनीय अपराध न माना जाए और न उससे अधिक भारी दण्ड दिया जा सकेगा, जो उस समय दिया जाता जिस समय वह दण्डनीय अपराध किया गया था ।\n         \n      \n   \n      अनुच्छेद १२.\n      किसी व्यक्ति की एकान्तता, परिवार, घर या पत्रव्यवहार के प्रति कोई मनमाना हस्तक्षेप न किया जाएगा, न किसी के सम्मान और ख्याति पर कोई आक्षेप हो सकेगा । ऐसे हस्तक्षेप या आधेपों के विरुद्ध प्रत्येक को क़ानूनी रक्षा का अधिकार प्राप्त है ।\n   \n      अनुच्छेद १३.\n      \n         \n            प्रत्येक व्यक्ति को प्रत्येक देश की सीपाओं के अन्दर स्वतन्त्रतापूर्वक आने, जाने और बसने का अधिकार है ।\n         \n         \n            प्रत्येक व्यक्ति को अपने या पराये किसी भी देश को छोड़नो और अपने देश को वापस आनो का अधिकार है ।\n         \n      \n   \n      अनुच्छेद १४.\n      \n         \n            प्रत्येक व्यक्ति को सताये जाने पर दूसरे देशों में शरण लेने और रहने का अधिकार है ।\n         \n         \n            इस अधिकार का लाभ ऐसे मामलों में नहीं मिलेगा जो वास्तव में गैर-राजनीतिक अपराधों से सम्बन्धित हैं, या जो संयुक्त राष्ट्रों के उद्देश्यों और सिद्धान्तों के विरुद्ध कार्य हैं ।\n         \n      \n   \n      अनुच्छेद १५.\n      \n         \n            प्रत्येक व्यक्ति को किसी भी राष्ट्र-विशेष को नागरिकता का अधिकार है ।\n         \n         \n            किसी को भी मनमाने ढंग से अपने राष्ट्र की नागरिकता से वंचित न किया जाएगा या नागरिकता का यरिवर्तन करने से मना न किया जाएगा ।\n         \n      \n   \n      अनुच्छेद १६.\n      \n         \n            बालिग़ स्त्री-पुरुषों को बिना किसी जाति, राष्ट्रीयता या धर्म की रुकावटों के आपस में विवाह करने और परिवार को स्थापन करने का अधिकार है । उन्हें विवाह के विषय में वैवाहिक जीवन में, तथा विवाह विच्छेड के बारे में समान अधिकार है ।\n         \n         \n             विवाह का इरादा रखने वाले स्त्री-पुरुषों की पूर्ण और स्वतन्त्र सहमित पर ही विवाह हो सकेगा ।\n         \n         \n            परिवार समाज की स्वाभाविक और बुनियादी सामूहिक इकाई है और उसे समाज तथा राज्य द्वारा संरक्षण पाने का अधिकार है ।\n         \n      \n   \n      अनुच्छेद १७.\n      \n         \n            प्रत्येक व्यक्ति को अकेले और दूसरों के साथ मिलकर सम्मति रखने का अधिकार है ।\n         \n         \n            किसी को भी मनमाने ढंग से अपनी सम्मति से वंचित न किया जाएगा ।\n         \n      \n   \n      अनुच्छेद १८.\n      प्रत्येक व्यक्ति को विचार, अन्तरात्मा और धर्म की आज़ादी का अधिकार है । इस अधिकार के अन्तर्गत अपना धर्म या विश्वास बदलने और अकेले या दूसरों के साथ मिलकर तथा सार्वजनिक रूप में अथवा निजी तोर पर अपने धर्म या विश्वास को शिक्षा, क्रिया, उपासना, तथा व्यवहार के द्वारा प्रकट करने की स्वतन्त्रता है ।\n   \n      अनुच्छेद १९.\n      प्रत्येक व्यक्ति को विचार और उसकी अभिव्यक्ति की स्वतन्त्रता का अधिकार है । इसके अन्तर्गत बिना हस्तक्षेप के कोई राय रखना और किसी भी माध्यम के ज़रिए से तथा सीमाओं की परवाह न कर के किसी की मूचना और धारणा का अन्वेषण, प्रहण तथा प्रदान सम्मिलित है ।\n   \n      अनुच्छेद २०.\n      \n         \n            प्रत्येक व्यक्ति को शान्ति पूर्ण सभा करने या समिति बनाने की स्वतन्त्रता का अधिकार है ।\n         \n         \n            किसी को भी किसी संस्था का सदस्य बनने के लिए मजबूर नहीं किया जा सकता ।\n         \n      \n   \n      अनुच्छेद २१.\n      \n         \n            प्रत्येक व्यक्ति को अपने देश के शासन में प्रत्यक्ष रूप से या स्वतन्त्र रूप से चुने गए प्रतिनिधियों के ज़रिए हिस्सा लेने का अधिकार है ।\n         \n         \n            प्रत्येक व्यक्ति को अपने देश की सरकारी नौकरियों को प्राप्त करने का समान अधिकार है ।\n         \n         \n            सरकार की सत्ता का आधार जनता की दच्छा होगी । इस इच्छा का प्रकटन समय-समय पर और असली चुनावों द्वारा होगा । ये चुनाव सार्वभौम और समान मताधिकार द्वारा होंगे और गुप्त मतदान द्वारा या किमी अन्य समान स्वतन्त्र मतदान पद्धति से कराये जाएंगे ।\n         \n      \n   \n      अनुच्छेद २२.\n      समाज के एक सदस्य के रूप में प्रत्येक व्यक्ति को सामाजिक सुरक्षा का अधिकार है और प्रत्येक व्यक्ति को अपने व्यक्तित्व के उस स्वतन्त्र विकास तथा गोरव के लिए—जो राष्ट्रीय प्रयत्न या अन्तर्राष्ट्रीय सहयोग तथा प्रत्येक राज्य के संगठन एवं साधनों के अनुकूल हो—अनिकार्यतः आवश्यक आर्थिक, सामाजिक, और सांस्कृतिक अधिकारों की प्राप्ति का हक़ है ।\n   \n      अनुच्छेद २३.\n      \n         \n            प्रत्येक व्यक्ति को काम करने, इच्छानुमार रोज़गार के चुनाव, काम की उचित और सुविधाजनक परिस्थितियों को प्राप्त करने और बेकारी से संरक्षण पाने का हक़ है ।\n         \n         \n            प्रत्येक व्यक्ति को समान कार्य के लिए बिना किसी भेदभाव के समान मज़दूरी पाने का अधिकार है ।\n         \n         \n            प्रत्येक व्यक्ति को जो काम करता है, अधिकार है कि वह इतनी उचित और अनुकूल मज़दूरी पाए, जिससे वह अपने लिए और अपने परिवार के लिए ऐसी आजीविका का प्रबन्ध कर मके, जो मानवीय गौरव के योग्य हो तथा आवश्यकता होने पर उसकी पूर्ति अन्य प्रकार के सामाजिक संरक्षणों द्वारा हो सके ।\n         \n         \n            प्रत्येक व्यक्ति को अपने हितों की रक्षा के लिए श्रमजीवी संघ बनाने और उनमें भाग लेने का अधिकार है ।\n         \n      \n   \n      अनुच्छेद २४.\n      प्रत्येक व्यक्ति को विश्राम और अवकाश का अधिकार है । इसके अन्तर्गत काम के घंटों की उचित हदबन्दी और समय-समय पर मज़दूरी सहित छुट्टियां सम्मिलित है ।\n   \n      अनुच्छेद २५.\n      \n         \n            प्रत्येक व्यक्ति को ऐसे जीवनस्तर को प्राप्त करने का अधिकार है जो उसे और उसके परिवार के स्वास्थ्य एवं कल्याण के लिए पर्याप्त हो । इसके अन्तर्गत खाना, कपड़ा, मकान, चिकित्सा-सम्बन्धी सुविधाएं और आवश्यक सामाजिक सेवाएं सम्मिलित है । सभी को बेकारी, बीमारी, असमर्थता, वैधव्य, बुढापे या अन्य किसी ऐसी परिस्थिति में आजीविका का साधन न होने पर जो उसके क़ाबू के बाहर हो, सुरक्षा का अधिकार प्राप्त है ।\n         \n         \n            जच्चा और बच्चा को खास सहायता और सुविधा का हक़ है । प्रत्येक बच्चे को चाहे वह विवाहिता माता से जन्मा हो या अविवाहिता से, समान सासाजिक संरक्षण प्राप्त होगा ।\n         \n      \n   \n      अनुच्छेद २६.\n      \n         \n            प्रत्येक व्यक्ति को शिक्षा का अधिकार है । शिक्षा कम से कम प्रारम्भिक और बुनियादी अवस्थाओं में निःशुल्क होगी । प्रारम्भिक शिक्षा अनिवार्य होगी । टेक्निकल, यांत्रिक और पेशों-सम्बन्धी शिक्षा साधारण रूप से प्राप्त होगी और उच्चतर शिक्षा सभी को योग्यता के आधार पर समान रूप से उपलब्ध होगी ।\n         \n         \n            शिक्षा का उद्देश्य होगा मानव व्यक्तित्व का पूर्ण विकास और मानाव अधिकारों तथा बुनियादी स्वतन्त्रताओं के प्रति सम्मान को पुष्टि । शिक्षा द्वारा राष्ट्रों, जातियों अथवा घार्मिक समूहों के बीच आपसी सद्भावना, सहिष्णुता और मंत्री का विकास होगा और शांति बनाए रखने के लिए संयुक्त राष्ट्रों के प्रयत्नों के आगे बढ़ाया जाएगा ।\n         \n         \n            माता-पिता को सबसे पहले इस बात का अक्षिकार है कि वे चुनाव कर सकें कि किस क़िस्म की शिक्षा उनके बच्चों को दी जाएगी ।\n         \n      \n   \n      अनुच्छेद २७.\n      \n         \n             प्रत्येक व्यक्ति को स्वतन्त्रतापूर्वक समाज के सांस्कृतिक जीवन में हिस्सा लेने, कलाओं का आनन्द लेने, तथा वैज्ञानिक उन्नति और उसकी सुविधाओं में भाग लेने का हक़ है ।\n         \n         \n            प्रत्येक व्यक्ति को किसी भी ऐसी वैज्ञानिक, साहित्यिक या कलास्मक कृति मे उत्पन्न नैतिक और आर्थिक हितों की रक्षा का अधिकार है जिसका रचयिता वह स्वयं हो ।\n         \n      \n   \n      अनुच्छेद २८.\n      प्रत्येक व्यक्ति को ऐसी सामाजिक और अन्तर्राष्ट्रीय व्यवस्था की प्राप्ति का अधिकार है जिसमें इस घोषणा में उल्लिखित अधिकारों और स्वतन्त्रताओं को पूर्णतः प्राप्त किया जा सके ।\n   \n      अनुच्छेद २९.\n      \n         \n            प्रत्येक व्यक्ति का उसी समाज के प्रति कर्तव्य है जिसमें रहकर उसके व्यक्तित्व का स्वतन्त्र और पूर्ण विकास संभव हो ।\n         \n         \n            अपने अधिकारों और स्वतन्त्रताओं का उपयोग करते हुए प्रत्येक व्यक्ति केवल ऐसी ही सीमाओं द्वारा बद्ध होगा, जो कानून द्वारा निश्चित की जाएंगी और जिनका एकमात्र उद्देश्य दूसरों के अधिकारों और स्वतन्त्रताओं के लिये आदर और समुचित स्वीकृति की प्राप्ति होगा तथा जिनकी आवश्यकता एक प्रजातन्त्रात्मक समाज में नैतिकता, सार्वजनिक व्यवस्था और सामान्य कल्याण की उचित आवश्यकताओं को पूरा करना होगा ।\n         \n         \n            इन अधिकारों और स्वतन्त्रताओं का उपयोग किसी प्रकार से भी संयुक्त राष्ट्रों के सिद्धान्तों और उद्देश्यों के विरुद्ध नहीं किया जायगा ।\n         \n      \n   \n      अनुच्छेद ३०.\n      इस घोषणा में उल्लिखित किसी भी बात का यह अर्थ नहीं लगाना चाहिए जिससे यह प्रतीत हो कि किसी भी राज्य, समूह, या व्यक्ति की किसी ऐसे प्रयत्न में संलग्न होने या ऐसा कार्य करने का अधिकार है, जिसका उद्देश्य यहां बताये गए अधिकारों और स्वतन्त्रताओं में मे किसी का भी विनाश करना हो ।\n   "
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/perf/udhr_kor.txt",
    "content": "Universal Declaration of Human Rights - Korean\n© 1996 – 2009 The Office of the High Commissioner for Human Rights\nThis plain text version prepared by the “UDHR in Unicode”\nproject, http://www.unicode.org/udhr.\n---\n\n세 계 인 권 선 언\n      전 문\n      모든 인류 구성원의 천부의 존엄성과 동등하고 양도할 수 없는 권리를 인정하는 것이 세계의 자유, 정의 및 평화의 기초이며,\n      인권에 대한 무시와 경멸이 인류의 양심을 격분시키는 만행을 초래하였으며, 인간이 언론과 신앙의 자유, 그리고 공포와 결핍으로부터의 자유를 누릴 수 있는 세계의 도래가 모든 사람들의 지고한 열망으로서 천명되어 왔으며,\n      인간이 폭정과 억압에 대항하는 마지막 수단으로서 반란을 일으키도록 강요받지 않으려면, 법에 의한 통치에 의하여 인권이 보호되어야 하는 것이 필수적이며,\n      국가간에 우호관계의 발전을 증진하는 것이 필수적이며,\n      국제연합의 모든 사람들은 그 헌장에서 기본적 인권, 인간의 존엄과 가치, 그리고 남녀의 동등한 권리에 대한 신념을 재확인하였으며, 보다 폭넓은 자유속에서 사회적 진보와 보다 나은 생활수준을 증진하기로 다짐하였고,\n      회원국들은 국제연합과 협력하여 인권과 기본적 자유의 보편적 존중과 준수를 증진할 것을 스스로 서약하였으며,\n      이러한 권리와 자유에 대한 공통의 이해가 이 서약의 완전한 이행을 위하여 가장 중요하므로,\n      이에,\n      국제연합총회는,\n      모든 개인과 사회 각 기관이 이 선언을 항상 유념하면서 학습 및 교육을 통하여 이러한 권리와 자유에 대한 존중을 증진하기 위하여 노력하며, 국내적 그리고 국제적인 점진적 조치를 통하여 회원국 국민들 자신과 그 관할 영토의 국민들 사이에서 이러한 권리와 자유가 보편적이고 효과적으로 인식되고 준수되도록 노력하도록 하기 위하여, 모든 사람과 국가가 성취하여야 할 공통의 기준으로서 이 세계인권선언을 선포한다.\n   \n      제 1 조\n      모든 인간은 태어날 때부터 자유로우며 그 존엄과 권리에 있어 동등하다. 인간은 천부적으로 이성과 양심을 부여받았으며 서로 형제애의 정신으로 행동하여야 한다.\n   \n      제 2 조\n      모든 사람은 인종, 피부색, 성, 언어, 종교, 정치적 또는 기타의 견해, 민족적 또는 사회적 출신, 재산, 출생 또는 기타의 신분과 같은 어떠한 종류의 차별이 없이, 이 선언에 규정된 모든 권리와 자유를 향유할 자격이 있다.\n      더 나아가 개인이 속한 국가 또는 영토가 독립국, 신탁통치지역, 비자치지역이거나 또는 주권에 대한 여타의 제약을 받느냐에 관계없이, 그 국가 또는 영토의 정치적, 법적 또는 국제적 지위에 근거하여 차별이 있어서는 아니된다.\n   \n      제 3 조\n      모든 사람은 생명과 신체의 자유와 안전에 대한 권리를 가진다.\n   \n      제 4 조\n      어느 누구도 노예상태 또는 예속상태에 놓여지지 아니한다. 모든 형태의 노예제도와 노예매매는 금지된다.\n   \n      제 5 조\n      어느 누구도 고문, 또는 잔혹하거나 비인도적이거나 굴욕적인 처우 또는 형벌을 받지 아니한다.\n   \n      제 6 조\n      모든 사람은 어디에서나 법 앞에 인간으로서 인정받을 권리를 가진다.\n   \n      제 7 조\n      모든 사람은 법 앞에 평등하며 어떠한 차별도 없이 법의 동등한 보호를 받을 권리를 가진다. 모든 사람은 이 선언에 위반되는 어떠한 차별과 그러한 차별의 선동으로부터 동등한 보호를 받을 권리를 가진다.\n   \n      제 8 조\n      모든 사람은 헌법 또는 법률이 부여한 기본적 권리를 침해하는 행위에 대하여 권한있는 국내법정에서 실효성 있는 구제를 받을 권리를 가진다.\n   \n      제 9 조\n      어느 누구도 자의적으로 체포, 구금 또는 추방되지 아니한다.\n   \n      제 10 조\n      모든 사람은 자신의 권리, 의무 그리고 자신에 대한 형사상 혐의에 대한 결정에 있어 독립적이며 공평한 법정에서 완전히 평등하게 공정하고 공개된 재판을 받을 권리를 가진다.\n   \n      제 11 조\n      \n         \n            모든 형사피의자는 자신의 변호에 필요한 모든 것이 보장된 공개 재판에서 법률에 따라 유죄로 입증될 때까지 무죄로 추정받을 권리를 가진다.\n         \n         \n            어느 누구도 행위시에 국내법 또는 국제법에 의하여 범죄를 구성하지 아니하는 작위 또는 부작위를 이유로 유죄로 되지 아니한다. 또한 범죄 행위시에 적용될 수 있었던 형벌보다 무거운 형벌이 부과되지 아니한다.\n         \n      \n   \n      제 12 조\n      어느 누구도 그의 사생활, 가정, 주거 또는 통신에 대하여 자의적인 간섭을 받거나 또는 그의 명예와 명성에 대한 비난을 받지 아니한다. 모든 사람은 이러한 간섭이나 비난에 대하여 법의 보호를 받을 권리를 가진다.\n   \n      제 13 조\n      \n         \n            모든 사람은 자국내에서 이동 및 거주의 자유에 대한 권리를 가진다.\n         \n         \n            모든 사람은 자국을 포함하여 어떠한 나라를 떠날 권리와 또한 자국으로 돌아올 권리를 가진다.\n         \n      \n   \n      제 14 조\n      \n         \n            모든 사람은 박해를 피하여 다른 나라에서 비호를 구하거나 비호를 받을 권리를 가진다.\n         \n         \n            이러한 권리는 진실로 비정치적 범죄 또는 국제연합의 목적과 원칙에 위배되는 행위로 인하여 기소된 경우에는 주장될 수 없다.\n         \n      \n   \n      제 15 조\n      \n         \n            모든 사람은 국적을 가질 권리를 가진다.\n         \n         \n            어느 누구도 자의적으로 자신의 국적을 박탈당하지 아니하며 자신의 국적을 변경할 권리가 부인되지 아니한다.\n         \n      \n   \n      제 16 조\n      \n         \n            성인 남녀는 인종, 국적 또는 종교에 따른 어떠한 제한도 없이 혼인하고 가정을 이룰 권리를 가진다. 그들은 혼인에 대하여, 혼인기간중 그리고 혼인해소시에 동등한 권리를 향유할 자격이 있다.\n         \n         \n            혼인은 장래 배우자들의 자유롭고 완전한 동의하에서만 성립된다.\n         \n         \n            가정은 사회의 자연적이고 기초적인 단위이며, 사회와 국가의 보호를 받을 권리가 있다.\n         \n      \n   \n      제 17 조\n      \n         \n            모든 사람은 단독으로 뿐만 아니라 다른 사람과 공동으로 재산을 소유할 권리를 가진다.\n         \n         \n            어느 누구도 자의적으로 자신의 재산을 박탈당하지 아니한다.\n         \n      \n   \n      제 18 조\n      모든 사람은 사상, 양심 및 종교의 자유에 대한 권리를 가진다. 이러한 권리는 종교 또는 신념을 변경할 자유와, 단독으로 또는 다른 사람과 공동으로 그리고 공적으로 또는 사적으로 선교, 행사, 예배 및 의식에 의하여 자신의 종교나 신념을 표명하는 자유를 포함한다.\n   \n      제 19 조\n      모든 사람은 의견의 자유와 표현의 자유에 대한 권리를 가진다. 이러한 권리는 간섭없이 의견을 가질 자유와 국경에 관계없이 어떠한 매체를 통해서도 정보와 사상을 추구하고, 얻으며, 전달하는 자유를 포함한다.\n   \n      제 20 조\n      \n         \n            모든 사람은 평화적인 집회 및 결사의 자유에 대한 권리를 가진다.\n         \n         \n            어느 누구도 어떤 결사에 참여하도록 강요받지 아니한다.\n         \n      \n   \n      제 21 조\n      \n         \n            모든 사람은 직접 또는 자유로이 선출된 대표를 통하여 자국의 정부에 참여할 권리를 가진다.\n         \n         \n            모든 사람은 자국에서 동등한 공무담임권을 가진다.\n         \n         \n            국민의 의사가 정부 권능의 기반이다. 이러한 의사는 보통·평등 선거권에 따라 비밀 또는 그에 상당한 자유 투표절차에 의한 정기적이고 진정한 선거에 의하여 표현된다.\n         \n      \n   \n      제 22 조\n      모든 사람은 사회의 일원으로서 사회보장을 받을 권리를 가지며, 국가적 노력과 국제적 협력을 통하여, 그리고 각 국가의 조직과 자원에 따라서 자신의 존엄과 인격의 자유로운 발전에 불가결한 경제적, 사회적 및 문화적 권리들을 실현할 권리를 가진다.\n   \n      제 23 조\n      \n         \n            모든 사람은 일, 직업의 자유로운 선택, 정당하고 유리한 노동 조건, 그리고 실업에 대한 보호의 권리를 가진다.\n         \n         \n            모든 사람은 아무런 차별없이 동일한 노동에 대하여 동등한 보수를 받을 권리를 가진다.\n         \n         \n            노동을 하는 모든 사람은 자신과 가족에게 인간의 존엄에 부합하는 생존을 보장하며, 필요한 경우에 다른 사회보장방법으로 보충되는 정당하고 유리한 보수에 대한 권리를 가진다.\n         \n         \n            모든 사람은 자신의 이익을 보호하기 위하여 노동조합을 결성하고, 가입할 권리를 가진다.\n         \n      \n   \n      제 24 조\n      모든 사람은 노동시간의 합리적 제한과 정기적인 유급휴가를 포함하여 휴식과 여가의 권리를 가진다.\n   \n      제 25 조\n      \n         \n            모든 사람은 의식주, 의료 및 필요한 사회복지를 포함하여 자신과 가족의 건강과 안녕에 적합한 생활수준을 누릴 권리와, 실업, 질병, 장애, 배우자 사망, 노령 또는 기타 불가항력의 상황으로 인한 생계 결핍의 경우에 보장을 받을 권리를 가진다.\n         \n         \n            어머니와 아동은 특별한 보호와 지원을 받을 권리를 가진다. 모든 아동은 적서에 관계없이 동일한 사회적 보호를 누린다.\n         \n      \n   \n      제 26 조\n      \n         \n            모든 사람은 교육을 받을 권리를 가진다. 교육은 최소한 초등 및 기초단계에서는 무상이어야 한다. 초등교육은 의무적이어야 한다. 기술 및 직업교육은 일반적으로 접근이 가능하여야 하며, 고등교육은 모든 사람에게 실력에 근거하여 동등하게 접근 가능하여야 한다.\n         \n         \n            교육은 인격의 완전한 발전과 인권과 기본적 자유에 대한 존중의 강화를 목표로 한다. 교육은 모든 국가, 인종 또는 종교 집단간에 이해, 관용 및 우의를 증진하며, 평화의 유지를 위한 국제연합의 활동을 촉진하여야 한다.\n         \n         \n            부모는 자녀에게 제공되는 교육의 종류를 선택할 우선권을 가진다.\n         \n      \n   \n      제 27 조\n      \n         \n            모든 사람은 공동체의 문화생활에 자유롭게 참여하며 예술을 향유하고 과학의 발전과 그 혜택을 공유할 권리를 가진다.\n         \n         \n            모든 사람은 자신이 창작한 과학적, 문학적 또는 예술적 산물로부터 발생하는 정신적, 물질적 이익을 보호받을 권리를 가진다.\n         \n      \n   \n      제 28 조\n      모든 사람은 이 선언에 규정된 권리와 자유가 완전히 실현될 수 있도록 사회적, 국제적 질서에 대한 권리를 가진다.\n   \n      제 29 조\n      \n         \n            모든 사람은 그 안에서만 자신의 인격이 자유롭고 완전하게 발전할 수 있는 공동체에 대하여 의무를 가진다.\n         \n         \n            모든 사람은 자신의 권리와 자유를 행사함에 있어, 다른 사람의 권리와 자유를 당연히 인정하고 존중하도록 하기 위한 목적과, 민주사회의 도덕, 공공질서 및 일반적 복리에 대한 정당한 필요에 부응하기 위한 목적을 위해서만 법에 따라 정하여진 제한을 받는다.\n         \n         \n            이러한 권리와 자유는 어떠한 경우에도 국제연합의 목적과 원칙에 위배되어 행사되어서는 아니된다.\n         \n      \n   \n      제 30 조\n      이 선언의 어떠한 규정도 어떤 국가, 집단 또는 개인에게 이 선언에 규정된 어떠한 권리와 자유를 파괴하기 위한 활동에 가담하거나 또는 행위를 할 수 있는 권리가 있는 것으로 해석되어서는 아니된다.\n   "
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/helpers/CustomStreamErrorListener.java",
    "content": "package org.antlr.v4.test.runtime.java.helpers;\n\nimport org.antlr.v4.runtime.BaseErrorListener;\nimport org.antlr.v4.runtime.RecognitionException;\nimport org.antlr.v4.runtime.Recognizer;\n\nimport java.io.PrintStream;\n\npublic class CustomStreamErrorListener extends BaseErrorListener {\n\tprivate final PrintStream printStream;\n\n\tpublic CustomStreamErrorListener(PrintStream printStream){\n\t\tthis.printStream = printStream;\n\t}\n\n\t@Override\n\tpublic void syntaxError(Recognizer<?, ?> recognizer,\n\t\t\t\t\t\t\tObject offendingSymbol,\n\t\t\t\t\t\t\tint line,\n\t\t\t\t\t\t\tint charPositionInLine,\n\t\t\t\t\t\t\tString msg,\n\t\t\t\t\t\t\tRecognitionException e) {\n\t\tprintStream.println(\"line \" + line + \":\" + charPositionInLine + \" \" + msg);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/helpers/RuntimeTestLexer.java",
    "content": "package org.antlr.v4.test.runtime.java.helpers;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Lexer;\n\npublic abstract class RuntimeTestLexer extends Lexer {\n\tprotected java.io.PrintStream outStream = System.out;\n\n\tpublic RuntimeTestLexer(CharStream input) { super(input); }\n\n\tpublic void setOutStream(java.io.PrintStream outStream) { this.outStream = outStream; }\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/helpers/RuntimeTestParser.java",
    "content": "package org.antlr.v4.test.runtime.java.helpers;\n\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.TokenStream;\n\npublic abstract class RuntimeTestParser extends Parser {\n\tprotected java.io.PrintStream outStream = System.out;\n\n\tpublic RuntimeTestParser(TokenStream input) {\n\t\tsuper(input);\n\t}\n\n\tpublic void setOutStream(java.io.PrintStream outStream) {\n\t\tthis.outStream = outStream;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/java/helpers/TreeShapeListener.java",
    "content": "package org.antlr.v4.test.runtime.java.helpers;\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.tree.*;\n\npublic class TreeShapeListener implements ParseTreeListener {\n\tpublic static final TreeShapeListener INSTANCE = new TreeShapeListener();\n\n\t@Override public void visitTerminal(TerminalNode node) { }\n\t@Override public void visitErrorNode(ErrorNode node) { }\n\t@Override public void exitEveryRule(ParserRuleContext ctx) { }\n\n\t@Override\n\tpublic void enterEveryRule(ParserRuleContext ctx) {\n\t\tfor (int i = 0; i < ctx.getChildCount(); i++) {\n\t\t\tParseTree parent = ctx.getChild(i).getParent();\n\t\t\tif (!(parent instanceof RuleNode) || ((RuleNode)parent).getRuleContext() != ctx) {\n\t\t\t\tthrow new IllegalStateException(\"Invalid parse tree shape detected.\");\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/javascript/JavaScriptRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.javascript;\n\nimport org.antlr.v4.test.runtime.RuntimeRunner;\nimport org.antlr.v4.test.runtime.RuntimeTests;\n\npublic class JavaScriptRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new NodeRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/javascript/NodeRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.javascript;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\nimport org.stringtemplate.v4.ST;\n\nimport java.io.IOException;\nimport java.nio.file.Paths;\nimport java.util.List;\n\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\n\npublic class NodeRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"JavaScript\";\n\t}\n\n\t@Override\n\tpublic String getExtension() { return \"js\"; }\n\n\t@Override\n\tpublic String getBaseListenerSuffix() { return null; }\n\n\t@Override\n\tpublic String getBaseVisitorSuffix() { return null; }\n\n\t@Override\n\tpublic String getRuntimeToolName() { return \"node\"; }\n\n\tprivate final static String normalizedRuntimePath = getRuntimePath(\"JavaScript\").replace('\\\\', '/');\n\tprivate final static String newImportAntlrString =\n\t\t\t\"import antlr4 from 'file://\" + normalizedRuntimePath + \"/src/antlr4/index.node.js'\";\n\n\t@Override\n\tprotected CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\tList<GeneratedFile> generatedFiles = generatedState.generatedFiles;\n\t\tfor (GeneratedFile generatedFile : generatedFiles) {\n\t\t\ttry {\n\t\t\t\tFileUtils.replaceInFile(Paths.get(getTempDirPath(), generatedFile.name),\n\t\t\t\t\t\t\"import antlr4 from 'antlr4';\",\n\t\t\t\t\t\tnewImportAntlrString);\n\t\t\t} catch (IOException e) {\n\t\t\t\treturn new CompiledState(generatedState, e);\n\t\t\t}\n\t\t}\n\n\t\twriteFile(getTempDirPath(), \"package.json\",\n\t\t\t\tRuntimeTestUtils.getTextFromResource(\"org/antlr/v4/test/runtime/helpers/package_js.json\"));\n\t\treturn new CompiledState(generatedState, null);\n\t}\n\n\t@Override\n\tprotected void addExtraRecognizerParameters(ST template) {\n\t\ttemplate.add(\"runtimePath\", normalizedRuntimePath);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/php/PHPRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.php;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.antlr.v4.test.runtime.*;\n\npublic class PHPRunner extends RuntimeRunner {\n\tprivate static final Map<String, String> environment;\n\n\tstatic {\n\t\tenvironment = new HashMap<>();\n\t\tenvironment.put(\"RUNTIME\", getRuntimePath(\"PHP\"));\n\t}\n\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"PHP\";\n\t}\n\n\t@Override\n\tpublic Map<String, String> getExecEnvironment() {\n\t\treturn environment;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/php/PhpRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.php;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class PhpRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new PHPRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/python/PythonRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.python;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.stringtemplate.v4.ST;\n\npublic abstract class PythonRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getExtension() { return \"py\"; }\n\n\t@Override\n\tprotected void addExtraRecognizerParameters(ST template) {\n\t\ttemplate.add(\"python3\", getLanguage().equals(\"Python3\"));\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/python3/Python3Runner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.python3;\n\nimport org.antlr.v4.test.runtime.python.PythonRunner;\n\nimport java.nio.file.Paths;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Python3Runner extends PythonRunner {\n\tpublic final static Map<String, String> environment;\n\n\tstatic {\n\t\tenvironment = new HashMap<>();\n\t\tenvironment.put(\"PYTHONPATH\", Paths.get(getRuntimePath(\"Python3\"), \"src\").toString());\n\t\tenvironment.put(\"PYTHONIOENCODING\", \"utf-8\");\n\t}\n\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"Python3\";\n\t}\n\n\t@Override\n\tpublic Map<String, String> getExecEnvironment() {\n\t\treturn environment;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/python3/Python3RuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.python3;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class Python3RuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new Python3Runner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/states/CompiledState.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.states;\n\nimport org.antlr.v4.test.runtime.Stage;\n\npublic class CompiledState extends State {\n\t@Override\n\tpublic Stage getStage() {\n\t\treturn Stage.Compile;\n\t}\n\n\tpublic CompiledState(GeneratedState previousState, Exception exception) {\n\t\tsuper(previousState, exception);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/states/ExecutedState.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.states;\n\nimport org.antlr.v4.test.runtime.Stage;\n\npublic class ExecutedState extends State {\n\t@Override\n\tpublic Stage getStage() {\n\t\treturn Stage.Execute;\n\t}\n\n\tpublic final String output;\n\n\tpublic final String errors;\n\n\tpublic ExecutedState(CompiledState previousState, String output, String errors, Exception exception) {\n\t\tsuper(previousState, exception);\n\t\tthis.output = output != null ? output : \"\";\n\t\tthis.errors = errors != null ? errors : \"\";\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/states/GeneratedState.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.states;\n\nimport org.antlr.v4.test.runtime.ErrorQueue;\nimport org.antlr.v4.test.runtime.GeneratedFile;\nimport org.antlr.v4.test.runtime.Stage;\n\nimport java.util.List;\n\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.joinLines;\n\npublic class GeneratedState extends State {\n\t@Override\n\tpublic Stage getStage() {\n\t\treturn Stage.Generate;\n\t}\n\n\tpublic final ErrorQueue errorQueue;\n\tpublic final List<GeneratedFile> generatedFiles;\n\n\t@Override\n\tpublic boolean containsErrors() {\n\t\treturn errorQueue.errors.size() > 0 || super.containsErrors();\n\t}\n\n\tpublic String getErrorMessage() {\n\t\tString result = super.getErrorMessage();\n\n\t\tif (errorQueue.errors.size() > 0) {\n\t\t\tresult = joinLines(result, errorQueue.toString(true));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic GeneratedState(ErrorQueue errorQueue, List<GeneratedFile>  generatedFiles, Exception exception) {\n\t\tsuper(null, exception);\n\t\tthis.errorQueue = errorQueue;\n\t\tthis.generatedFiles = generatedFiles;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/states/JavaCompiledState.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.states;\n\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\nimport java.lang.reflect.InvocationTargetException;\n\npublic class JavaCompiledState extends CompiledState {\n\tpublic final ClassLoader loader;\n\tpublic final Class<? extends Lexer> lexer;\n\tpublic final Class<? extends Parser> parser;\n\n\tpublic JavaCompiledState(GeneratedState previousState,\n\t\t\t\t\t\t\t ClassLoader loader,\n\t\t\t\t\t\t\t Class<? extends Lexer> lexer,\n\t\t\t\t\t\t\t Class<? extends Parser> parser,\n\t\t\t\t\t\t\t Exception exception\n\t) {\n\t\tsuper(previousState, exception);\n\t\tthis.loader = loader;\n\t\tthis.lexer = lexer;\n\t\tthis.parser = parser;\n\t}\n\n\tpublic Pair<Lexer, Parser> initializeDummyLexerAndParser()\n\t\t\tthrows InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {\n\t\treturn initializeLexerAndParser(\"\");\n\t}\n\n\tpublic Pair<Lexer, Parser> initializeLexerAndParser(String input)\n\t\t\tthrows NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {\n\t\tLexer lexer = initializeLexer(input);\n\t\tParser parser = initializeParser(new CommonTokenStream(lexer));\n\t\treturn new Pair<>(lexer, parser);\n\t}\n\n\tpublic Lexer initializeLexer(String input)\n\t\tthrows NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {\n\t\tCharStream inputString = CharStreams.fromString(input, RuntimeRunner.InputFileName);\n\t\treturn lexer.getConstructor(CharStream.class).newInstance(inputString);\n\t}\n\n\tpublic Parser initializeParser(CommonTokenStream tokenStream)\n\t\t\tthrows NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {\n\t\treturn parser.getConstructor(TokenStream.class).newInstance(tokenStream);\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/states/JavaExecutedState.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.states;\n\nimport org.antlr.v4.runtime.tree.ParseTree;\n\npublic class JavaExecutedState extends ExecutedState {\n\tpublic final ParseTree parseTree;\n\n\tpublic JavaExecutedState(JavaCompiledState previousState, String output, String errors, ParseTree parseTree,\n\t\t\t\t\t\t\t Exception exception) {\n\t\tsuper(previousState, output, errors, exception);\n\t\tthis.parseTree = parseTree;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/states/State.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.states;\n\nimport org.antlr.v4.test.runtime.Stage;\n\npublic abstract class State {\n\tpublic final State previousState;\n\n\tpublic final Exception exception;\n\n\tpublic abstract Stage getStage();\n\n\tpublic boolean containsErrors() {\n\t\treturn exception != null;\n\t}\n\n\tpublic String getErrorMessage() {\n\t\tString result = \"State: \" + getStage() + \"; \";\n\t\tif (exception != null) {\n\t\t\tresult += exception.toString();\n\t\t\tif ( exception.getCause()!=null ) {\n\t\t\t\tresult += \"\\nCause:\\n\";\n\t\t\t\tresult += exception.getCause().toString();\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic State(State previousState, Exception exception) {\n\t\tthis.previousState = previousState;\n\t\tthis.exception = exception;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/swift/SwiftRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.swift;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\nimport org.stringtemplate.v4.ST;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.nio.file.Paths;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\nimport static org.antlr.v4.test.runtime.FileUtils.*;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.getTextFromResource;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.isWindows;\n\npublic class SwiftRunner extends RuntimeRunner {\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"Swift\";\n\t}\n\n\t@Override\n\tpublic String getTestFileName() {\n\t\treturn \"main\";\n\t}\n\n\tprivate static final String swiftRuntimePath;\n\tprivate static final String buildSuffix;\n\tprivate static final Map<String, String> environment;\n\n\tprivate static final String includePath;\n\tprivate static final String libraryPath;\n\n\tstatic {\n\t\tswiftRuntimePath = getRuntimePath(\"Swift\");\n\t\tbuildSuffix = isWindows() ? \"x86_64-unknown-windows-msvc\" : \"\";\n\t\tincludePath = Paths.get(swiftRuntimePath, \".build\", buildSuffix, \"release\").toString();\n\t\tenvironment = new HashMap<>();\n\t\tif (isWindows()) {\n\t\t\tlibraryPath = Paths.get(includePath, \"Antlr4.lib\").toString();\n\t\t\tString path = System.getenv(\"PATH\");\n\t\t\tenvironment.put(\"PATH\", path == null ? includePath : path + \";\" + includePath);\n\t\t}\n\t\telse {\n\t\t\tlibraryPath = includePath;\n\t\t}\n\t}\n\n\t@Override\n\tprotected String getCompilerName() {\n\t\treturn \"swift\";\n\t}\n\n\t@Override\n\tprotected void initRuntime(RunOptions runOptions) throws Exception {\n\t\trunCommand(new String[] {getCompilerPath(), \"build\", \"-c\", \"release\"}, swiftRuntimePath, \"build Swift runtime\");\n\t}\n\n\t@Override\n\tprotected CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\t\tException exception = null;\n\t\ttry {\n\t\t\tString tempDirPath = getTempDirPath();\n\t\t\tFile tempDirFile = new File(tempDirPath);\n\n\t\t\tFile[] ignoredFiles = tempDirFile.listFiles(NoSwiftFileFilter.Instance);\n\t\t\tassert ignoredFiles != null;\n\t\t\tList<String> excludedFiles = Arrays.stream(ignoredFiles).map(File::getName).collect(Collectors.toList());\n\n\t\t\tString text = getTextFromResource(\"org/antlr/v4/test/runtime/helpers/Package.swift.stg\");\n\t\t\tST outputFileST = new ST(text);\n\t\t\toutputFileST.add(\"excludedFiles\", excludedFiles);\n\t\t\twriteFile(tempDirPath, \"Package.swift\", outputFileST.render());\n\n\t\t\tString[] buildProjectArgs = new String[]{\n\t\t\t\t\tgetCompilerPath(),\n\t\t\t\t\t\"build\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"release\",\n\t\t\t\t\t\"-Xswiftc\",\n\t\t\t\t\t\"-I\" + includePath,\n\t\t\t\t\t\"-Xlinker\",\n\t\t\t\t\t\"-L\" + includePath,\n\t\t\t\t\t\"-Xlinker\",\n\t\t\t\t\t\"-lAntlr4\",\n\t\t\t\t\t\"-Xlinker\",\n\t\t\t\t\t\"-rpath\",\n\t\t\t\t\t\"-Xlinker\",\n\t\t\t\t\tlibraryPath\n\t\t\t};\n\t\t\trunCommand(buildProjectArgs, tempDirPath);\n\t\t} catch (Exception e) {\n\t\t\texception = e;\n\t\t}\n\n\t\treturn new CompiledState(generatedState, exception);\n\t}\n\n\tstatic class NoSwiftFileFilter implements FilenameFilter {\n\t\tpublic final static NoSwiftFileFilter Instance = new NoSwiftFileFilter();\n\n\t\tpublic boolean accept(File dir, String name) {\n\t\t\treturn !name.endsWith(\".swift\");\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getRuntimeToolName() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getExecFileName() {\n\t\treturn Paths.get(getTempDirPath(),\n\t\t\t\t\".build\",\n\t\t\t\tbuildSuffix,\n\t\t\t\t\"release\",\n\t\t\t\t\"Test\" + (isWindows() ? \".exe\" : \"\")).toString();\n\t}\n\n\t@Override\n\tpublic Map<String, String> getExecEnvironment() {\n\t\treturn environment;\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/swift/SwiftRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.swift;\n\nimport org.antlr.v4.test.runtime.RuntimeTests;\nimport org.antlr.v4.test.runtime.RuntimeRunner;\n\npublic class SwiftRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new SwiftRunner();\n\t}\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/typescript/TsNodeRunner.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.runtime.typescript;\n\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.states.CompiledState;\nimport org.antlr.v4.test.runtime.states.GeneratedState;\n\nimport java.io.File;\nimport java.nio.file.Files;\n\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.isWindows;\n\npublic class TsNodeRunner extends RuntimeRunner {\n\n\t/* TypeScript runtime is the same as JavaScript runtime */\n\tprivate final static String NORMALIZED_JAVASCRIPT_RUNTIME_PATH = getRuntimePath(\"JavaScript\").replace('\\\\', '/');\n\tprivate final static String NPM_EXEC = \"npm\" + (isWindows() ? \".cmd\" : \"\");\n\tprivate final static String WEBPACK_EXEC = \"webpack\" + (isWindows() ? \".cmd\" : \"\");\n\n\t@Override\n\tpublic String getLanguage() {\n\t\treturn \"TypeScript\";\n\t}\n\n\n\t@Override\n\tprotected void initRuntime(RunOptions runOptions) throws Exception {\n\t\tnpmInstallTsNodeAndWebpack();\n\t\tnpmLinkRuntime();\n\t}\n\n\tprivate void npmInstallTsNodeAndWebpack() throws Exception {\n\t\tProcessor.run(new String[] {NPM_EXEC, \"--silent\", \"install\", \"-g\", \"typescript\", \"ts-node\", \"webpack\", \"webpack-cli\"}, null);\n\t}\n\n\tprivate void npmLinkRuntime() throws Exception {\n\t\tProcessor.run(new String[] {NPM_EXEC, \"--silent\", \"install\"}, NORMALIZED_JAVASCRIPT_RUNTIME_PATH);\n\t\tProcessor.run(new String[] {WEBPACK_EXEC, \"--no-stats\"}, NORMALIZED_JAVASCRIPT_RUNTIME_PATH);\n\t\tProcessor.run(new String[] {NPM_EXEC, \"--silent\", \"link\"}, NORMALIZED_JAVASCRIPT_RUNTIME_PATH);\n\t}\n\n\t@Override\n\tpublic String getExtension() { return \"ts\"; }\n\n\t@Override\n\tprotected String getExecFileName() { return getTestFileName() + \".ts\"; }\n\n\t@Override\n\tpublic String getBaseListenerSuffix() { return null; }\n\n\t@Override\n\tpublic String getBaseVisitorSuffix() { return null; }\n\n\t@Override\n\tpublic String getRuntimeToolName() { return \"ts-node\"  + (isWindows() ? \".cmd\" : \"\"); }\n\n\t@Override\n\tprotected CompiledState compile(RunOptions runOptions, GeneratedState generatedState) {\n\n\t\ttry {\n\t\t\twriteFile(getTempDirPath(), \"package.json\",\n\t\t\t\t\tRuntimeTestUtils.getTextFromResource(\"org/antlr/v4/test/runtime/helpers/package_ts.json\"));\n\n\t\t\twriteFile(getTempDirPath(), \"tsconfig.json\",\n\t\t\t\t\tRuntimeTestUtils.getTextFromResource(\"org/antlr/v4/test/runtime/helpers/tsconfig.json\"));\n\n\t\t\tnpmInstall();\n\n\t\t\tnpmLinkAntlr4();\n\n\t\t\treturn new CompiledState(generatedState, null);\n\n\t\t} catch (Exception e) {\n\t\t\treturn new CompiledState(generatedState, e);\n\t\t}\n\n\t}\n\n\tprivate void npmInstall() throws Exception {\n\t\tProcessor.run(new String[] {NPM_EXEC, \"--silent\", \"install\"}, getTempDirPath());\n\t}\n\n\n\tprivate void npmLinkAntlr4() throws Exception {\n\t\tProcessor.run(new String[] {NPM_EXEC, \"--silent\", \"link\", \"antlr4\"}, getTempDirPath());\n\t}\n\n\n}\n"
  },
  {
    "path": "runtime-testsuite/test/org/antlr/v4/test/runtime/typescript/TypeScriptRuntimeTests.java",
    "content": "/*\n * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.runtime.typescript;\n\nimport org.antlr.v4.test.runtime.RuntimeRunner;\nimport org.antlr.v4.test.runtime.RuntimeTests;\n\npublic class TypeScriptRuntimeTests extends RuntimeTests {\n\t@Override\n\tprotected RuntimeRunner createRuntimeRunner() {\n\t\treturn new TsNodeRunner();\n\t}\n}\n"
  },
  {
    "path": "scripts/deploy_to_website.py",
    "content": "# Deploy targets, update version number at website, update Javadoc\n\nimport sys\nimport os\nimport subprocess\n\n\nWEBSITE_ROOT  = '/Users/parrt/antlr/sites/website-antlr4'\nANTLR_M2_ROOT = '/Users/parrt/.m2/repository/org/antlr'\n\nwebsite_files_to_update = ['download.html',\n                           'index.html',\n                           'api/index.html',\n                           'scripts/topnav.js']\n\n\ndef runme(cmd):\n    return subprocess.check_output(cmd.split(' '))\n\n\ndef update_file(qfname, multi, before, after):\n    with open(qfname, \"r\", encoding=\"UTF-8\") as f:\n        text = f.read()\n\n    if before not in text:\n        print(f\"{before} not in {qfname}\")\n        return\n\n    # Don't update if on > 1 line; too complex for tool\n    lines = text.split('\\n')\n    count = sum(before in line for line in lines)\n    if count>1 and not multi:\n        print(f\"{before} appears on {count} lines so _not_ updating {qfname}\")\n\n    # print(f\"{before} => {after} in {qfname}\")\n    text = text.replace(before, after)\n    with open(qfname, \"w\", encoding=\"UTF-8\") as f:\n        f.write(text)\n\n\ndef copy_javadoc(release_version):\n    # release_version = release_version+\"-SNAPSHOT\" # testing\n    os.chdir(WEBSITE_ROOT+\"/api/Java\")\n    print(\"Javadoc copied:\")\n    runme(f\"jar xf {ANTLR_M2_ROOT}/antlr4-runtime/{release_version}/antlr4-runtime-{release_version}-javadoc.jar\")\n    print(f\"\\tapi/Java updated from antlr4-runtime-{release_version}-javadoc.jar\")\n    os.chdir(WEBSITE_ROOT+\"/api/JavaTool\")\n    runme(f\"jar xf {ANTLR_M2_ROOT}/antlr4/{release_version}/antlr4-{release_version}-javadoc.jar\")\n    print(f\"\\tapi/JavaTool updated from antlr4-{release_version}-javadoc.jar\")\n    os.chdir(WEBSITE_ROOT+\"/api/maven-plugin/latest\")\n    runme(f\"jar xf {ANTLR_M2_ROOT}/antlr4-maven-plugin/{release_version}/antlr4-maven-plugin-{release_version}-javadoc.jar\")\n    print(f\"\\tapi/JavaTool updated from antlr4-maven-plugin-{release_version}-javadoc.jar\")\n\n\ndef copy_jars(release_version):\n    # release_version = release_version+\"-SNAPSHOT\" # testing\n    print(\"Jars copied:\")\n    runme(f\"cp {ANTLR_M2_ROOT}/antlr4-runtime/{release_version}/antlr4-runtime-{release_version}.jar {WEBSITE_ROOT}/download/antlr-runtime-{release_version}.jar\")\n    runme(f\"cp {ANTLR_M2_ROOT}/antlr4/{release_version}/antlr4-{release_version}-complete.jar {WEBSITE_ROOT}/download/antlr-{release_version}-complete.jar\")\n    os.chdir(WEBSITE_ROOT+\"/download\")\n    runme(f\"git add antlr-{release_version}-complete.jar\")\n    runme(f\"git add antlr-runtime-{release_version}.jar\")\n    print(f\"\\tantlr-{release_version}-complete.jar\")\n    print(f\"\\tantlr-runtime-{release_version}.jar\")\n\n\ndef update_version():\n    for fname in website_files_to_update:\n        qfname = WEBSITE_ROOT + \"/\" + fname\n        update_file(qfname, True, before, after)\n    print(\"Version string updated. Please commit/push:\")\n\n\nif __name__ == '__main__':\n    before = sys.argv[1]\n    after = sys.argv[2]\n    print(f\"Updating ANTLR version from {before} to {after}\")\n\n    root = input(f\"Set ANTLR website root (default {WEBSITE_ROOT}): \")\n    if len(root.strip())>0:\n        WEBSITE_ROOT = root\n\n    update_version()\n    os.chdir(WEBSITE_ROOT)\n\n    copy_javadoc(release_version=after)\n    copy_jars(release_version=after)\n\n    print()\n    print(\"Please look for and add new api files!!\")\n    print(\"Then MANUALLY commit/push:\")\n    print()\n    print(f\"cd {WEBSITE_ROOT}\")\n    print(f\"git commit -a -m 'Update website, javadoc, jars to {after}'\")\n    print(\"git push origin gh-pages\")\n"
  },
  {
    "path": "scripts/files-to-update.txt",
    "content": "# The list of files with an antlr version number to update\n# generated initially from:\n# $ mvn clean\n# $ find tool runtime -type f -exec grep -l '4\\.9' {} \\; | grep -v -E '\\.o|\\.a|\\.jar|\\.dylib|node_modules/|\\.class|tests/|CHANGELOG|\\.zip|\\.gz|.iml|.svg'\n#\n# Lines starting with '*' allow multiple changes in single file\n\ndocker/Dockerfile\nruntime/Go/antlr/v4/recognizer.go\nruntime/Go/antlr/v4/antlrdoc.go\nruntime/Python3/pyproject.toml\nruntime/Python3/src/antlr4/Recognizer.py\nruntime/Dart/pubspec.yaml\nruntime/Dart/lib/src/runtime_meta_data.dart\nruntime/Java/src/org/antlr/v4/runtime/RuntimeMetaData.java\nruntime/Cpp/CPackConfig.cmake\nruntime/Cpp/demo/generate.cmd\nruntime/Cpp/cmake/Antlr4Package.md\nruntime/Cpp/cmake/README.md\nruntime/Cpp/cmake/ExternalAntlr4Cpp.cmake\nruntime/Cpp/cmake/FindANTLR.cmake\nruntime/Cpp/runtime/src/Version.h\nruntime/Cpp/runtime/cmake_install.cmake\nruntime/Cpp/VERSION\nruntime/Swift/Sources/Antlr4/RuntimeMetaData.swift\nruntime/CSharp/src/README.md\nruntime/CSharp/src/Properties/AssemblyInfo.cs\nruntime/CSharp/src/Antlr4.csproj\nruntime/JavaScript/package-lock.json\nruntime/JavaScript/package.json\nruntime/JavaScript/src/antlr4/Recognizer.js\nruntime/JavaScript/spec/rewriter/Makefile\nruntime-testsuite/resources/org/antlr/v4/test/runtime/helpers/package_ts.json\n\n# Allow doc files to have multiple values updated\n* doc/swift-target.md\n# doc/releasing-antlr.md\n* doc/getting-started.md\n* doc/swift-target.md\n* doc/getting-started.md\n* doc/go-target.md \n\n# runtime/Swift/Tests/Antlr4Tests/RuntimeMetaDataTests.swift  This is special so must manually edit\n\n# Just documenting that these are generated...\n\n# runtime/Python3/src/antlr4/xpath/XPathLexer.py\n# runtime/Cpp/runtime/src/tree/xpath/XPathLexer.cpp\n# runtime/Cpp/runtime/src/tree/xpath/XPathLexer.h\n# runtime/CSharp/src/Tree/Xpath/XPathLexer.cs\n"
  },
  {
    "path": "scripts/github_release_notes.py",
    "content": "# Get github issues / PR for a release\n# Exec with \"python github_release_notes.py YOUR_GITHUB_API_ACCESS_TOKEN 4.7.1\"\n\nfrom github import Github\nfrom collections import Counter\nimport sys\n\nTARGETS = ['csharp', 'cpp', 'go', 'java', 'javascript', 'python3', 'swift', 'php', 'dart']\n\nTOKEN=sys.argv[1]\nMILESTONE=sys.argv[2]\ng = Github(login_or_token=TOKEN)\n\n# Then play with your Github objects:\norg = g.get_organization(\"antlr\")\nrepo = org.get_repo(\"antlr4\")\nmilestone = [x for x in repo.get_milestones() if x.title==MILESTONE]\nmilestone = milestone[0]\n\nissues = repo.get_issues(state=\"closed\", milestone=milestone, sort=\"created\", direction=\"desc\")\n\n# dump bugs fixed\nprint()\nprint(\"## Issues fixed\")\nfor x in issues:\n    labels = [l.name for l in x.labels]\n    if x.pull_request is None and not (\"type:improvement\" in labels or \"type:feature\" in labels):\n        print(\"* [%s](%s) (%s)\" % (x.title, x.html_url, \", \".join([l.name for l in x.labels])))\n\n# dump improvements closed for this release (issues or pulls)\nprint()\nprint(\"## Improvements, features\")\nfor x in issues:\n    labels = [l.name for l in x.labels]\n    if (\"type:improvement\" in labels or \"type:feature\" in labels):\n        print(\"* [%s](%s) (%s)\" % (x.title, x.html_url, \", \".join(labels)))\n\n# dump PRs closed for this release by target\nprint()\nprint(\"## Pull requests grouped by target\")\nfor target in TARGETS:\n    print()\n    print(f\"### {target} target\")\n    for x in issues:\n        labels = [l.name for l in x.labels]\n        if x.pull_request is not None and f\"target:{target}\" in labels:\n            print(\"* [%s](%s) (%s)\" % (x.title, x.html_url, \", \".join(labels)))\n\n# dump contributors\nprint()\nprint(\"## Contributors\")\nuser_counts = Counter([x.user.login for x in issues])\nusers = {x.user.login:x.user for x in issues}\nfor login,count in user_counts.most_common(10000):\n    name = users[login].name\n    logins = f\" ({users[login].login})\"\n    if name is None:\n        name = users[login].login\n        logins = \"\"\n    print(f\"* {count:3d} items: [{name}]({users[login].html_url}){logins}\")\n"
  },
  {
    "path": "scripts/parse-extended-pictographic/ExtendedPictographic-Parsed.txt",
    "content": "set.add(0x1F774, 0x1F77F);\nset.add(0x2700, 0x2701);\nset.add(0x2703, 0x2704);\nset.add(0x270E);\nset.add(0x2710, 0x2711);\nset.add(0x2765, 0x2767);\nset.add(0x1F030, 0x1F093);\nset.add(0x1F094, 0x1F09F);\nset.add(0x1F10D, 0x1F10F);\nset.add(0x1F12F);\nset.add(0x1F16C, 0x1F16F);\nset.add(0x1F1AD, 0x1F1E5);\nset.add(0x1F260, 0x1F265);\nset.add(0x1F203, 0x1F20F);\nset.add(0x1F23C, 0x1F23F);\nset.add(0x1F249, 0x1F24F);\nset.add(0x1F252, 0x1F25F);\nset.add(0x1F266, 0x1F2FF);\nset.add(0x1F7D5, 0x1F7FF);\nset.add(0x1F000, 0x1F003);\nset.add(0x1F005, 0x1F02B);\nset.add(0x1F02C, 0x1F02F);\nset.add(0x1F322, 0x1F323);\nset.add(0x1F394, 0x1F395);\nset.add(0x1F398);\nset.add(0x1F39C, 0x1F39D);\nset.add(0x1F3F1, 0x1F3F2);\nset.add(0x1F3F6);\nset.add(0x1F4FE);\nset.add(0x1F53E, 0x1F548);\nset.add(0x1F54F);\nset.add(0x1F568, 0x1F56E);\nset.add(0x1F571, 0x1F572);\nset.add(0x1F57B, 0x1F586);\nset.add(0x1F588, 0x1F589);\nset.add(0x1F58E, 0x1F58F);\nset.add(0x1F591, 0x1F594);\nset.add(0x1F597, 0x1F5A3);\nset.add(0x1F5A6, 0x1F5A7);\nset.add(0x1F5A9, 0x1F5B0);\nset.add(0x1F5B3, 0x1F5BB);\nset.add(0x1F5BD, 0x1F5C1);\nset.add(0x1F5C5, 0x1F5D0);\nset.add(0x1F5D4, 0x1F5DB);\nset.add(0x1F5DF, 0x1F5E0);\nset.add(0x1F5E2);\nset.add(0x1F5E4, 0x1F5E7);\nset.add(0x1F5E9, 0x1F5EE);\nset.add(0x1F5F0, 0x1F5F2);\nset.add(0x1F5F4, 0x1F5F9);\nset.add(0x2605);\nset.add(0x2607, 0x260D);\nset.add(0x260F, 0x2610);\nset.add(0x2612);\nset.add(0x2616, 0x2617);\nset.add(0x2619, 0x261C);\nset.add(0x261E, 0x261F);\nset.add(0x2621);\nset.add(0x2624, 0x2625);\nset.add(0x2627, 0x2629);\nset.add(0x262B, 0x262D);\nset.add(0x2630, 0x2637);\nset.add(0x263B, 0x2647);\nset.add(0x2654, 0x265F);\nset.add(0x2661, 0x2662);\nset.add(0x2664);\nset.add(0x2667);\nset.add(0x2669, 0x267A);\nset.add(0x267C, 0x267E);\nset.add(0x2680, 0x2691);\nset.add(0x2695);\nset.add(0x2698);\nset.add(0x269A);\nset.add(0x269D, 0x269F);\nset.add(0x26A2, 0x26A9);\nset.add(0x26AC, 0x26AF);\nset.add(0x26B2, 0x26BC);\nset.add(0x26BF, 0x26C3);\nset.add(0x26C6, 0x26C7);\nset.add(0x26C9, 0x26CD);\nset.add(0x26D0);\nset.add(0x26D2);\nset.add(0x26D5, 0x26E8);\nset.add(0x26EB, 0x26EF);\nset.add(0x26F6);\nset.add(0x26FB, 0x26FC);\nset.add(0x26FE, 0x26FF);\nset.add(0x2388);\nset.add(0x1FA00, 0x1FFFD);\nset.add(0x1F0A0, 0x1F0AE);\nset.add(0x1F0B1, 0x1F0BF);\nset.add(0x1F0C1, 0x1F0CF);\nset.add(0x1F0D1, 0x1F0F5);\nset.add(0x1F0AF, 0x1F0B0);\nset.add(0x1F0C0);\nset.add(0x1F0D0);\nset.add(0x1F0F6, 0x1F0FF);\nset.add(0x1F80C, 0x1F80F);\nset.add(0x1F848, 0x1F84F);\nset.add(0x1F85A, 0x1F85F);\nset.add(0x1F888, 0x1F88F);\nset.add(0x1F8AE, 0x1F8FF);\nset.add(0x1F900, 0x1F90B);\nset.add(0x1F91F);\nset.add(0x1F928, 0x1F92F);\nset.add(0x1F931, 0x1F932);\nset.add(0x1F94C);\nset.add(0x1F95F, 0x1F96B);\nset.add(0x1F992, 0x1F997);\nset.add(0x1F9D0, 0x1F9E6);\nset.add(0x1F90C, 0x1F90F);\nset.add(0x1F93F);\nset.add(0x1F94D, 0x1F94F);\nset.add(0x1F96C, 0x1F97F);\nset.add(0x1F998, 0x1F9BF);\nset.add(0x1F9C1, 0x1F9CF);\nset.add(0x1F9E7, 0x1F9FF);\nset.add(0x1F6C6, 0x1F6CA);\nset.add(0x1F6D3, 0x1F6D4);\nset.add(0x1F6E6, 0x1F6E8);\nset.add(0x1F6EA);\nset.add(0x1F6F1, 0x1F6F2);\nset.add(0x1F6F7, 0x1F6F8);\nset.add(0x1F6D5, 0x1F6DF);\nset.add(0x1F6ED, 0x1F6EF);\nset.add(0x1F6F9, 0x1F6FF);\n"
  },
  {
    "path": "scripts/parse-extended-pictographic/ExtendedPictographic.txt",
    "content": "# ExtendedPictographic.txt\n# Date: 2016-10-12\n# © 2016 Unicode®, Inc.\n# For terms of use, see http://www.unicode.org/terms_of_use.html\n#\n# Extended_Pictographic (EP) is a binary code point property for characters that are pictographic \n# (or otherwise similar in kind to characters with the Emoji property)\n# and used to customize segmentation (UAX #29 and UAX #14) so that possible future emoji zwj sequences\n# will not break grapheme clusters, words, or lines. It also includes unassigned codepoints that\n# are in blocks intended for use for emoji characters, added to the Unicode 9.0 Linebreak property.\n#\n# For usage information, see http://unicode.org/reports/tr35/#Property_Data\n# \n# Format\n#\n# This file follows the format used for UCD files. \n# Field 1 indicates that the character(s) listed in Field 0 have the value ExtendedPictographic=Yes\n# All other characters have the value ExtendedPictographic=No\n#\n# The files contain additional comments to aid in understanding the context of the property values.\n#\n# 1. Blocks are included if they contain any emoji characters, even if there are no EP characters.\n#\n# 2. EP code points may include unassigned values. Those are based on the Line_Break assignments that\n#    were added in Unicode 9.0 to future-proof ZWJ linebreak behavior. \n#\n# 3. Comment lines are included to describe the content of the blocks for comparison. For example:\n#    emoji=33\t: [✂✅✈-✍✏✒✔✖✝✡✨✳✴❄❇❌❎❓-❕❗❣❤➕-➗➡➰➿]\n#    EP=10\t: [✀✁✃✄✎✐✑❥-❧]\n#    other=149\t: [✆✇✓✕✗-✜✞-✠✢-✧✩-✲✵-❃❅❆❈-❋❍❏-❒❖❘-❢❨-➔➘-➠➢-➯➱-➾]\n#    otherCn=2\n#\n#    Meaning\n#    • emoji:   the number of Emoji=Yes characters in that block,\n#    • EP:     the number of ExtendedPictographic in the block (with details below), and\n#    • other:   the number of other characters in the block (non-Emoji, non-EP),\n#    • otherCn: the number of other code points in the block (non-Emoji, non-EP, not characters).\n#\n#    The characters can be listed out in detail by using any implementation that supports UnicodeSet,\n#    such as ​http://unicode.org/cldr/utility/list-unicodeset.jsp.\n#    The lines are omitted if empty: for example, Transport_And_Map_Symbols have no \"other\" characters.\n#    \n# =====\n\n# Alchemical_Symbols\n# EP=12\t: [🝴-🝿]\n# other=116\t: [🜀-🝳]\n\nU+1F774..U+1F77F\t; ExtendedPictographic #\tGC=Cn\n# count=12\n\n# Arrows\n# emoji=8\t: [↔-↙↩↪]\n# other=104\t: [←-↓↚-↨↫-⇿]\n\n# CJK_Symbols_And_Punctuation\n# emoji=2\t: [〰〽]\n# other=62\t: [　-〯〱-〼〾〿]\n\n# Dingbats\n# emoji=33\t: [✂✅✈-✍✏✒✔✖✝✡✨✳✴❄❇❌❎❓-❕❗❣❤➕-➗➡➰➿]\n# EP=10\t: [✀✁✃✄✎✐✑❥-❧]\n# other=149\t: [✆✇✓✕✗-✜✞-✠✢-✧✩-✲✵-❃❅❆❈-❋❍❏-❒❖❘-❢❨-➔➘-➠➢-➯➱-➾]\n\nU+2700..U+2701\t; ExtendedPictographic #\t[✀✁]\tBLACK SAFETY SCISSORS .. UPPER BLADE SCISSORS\nU+2703..U+2704\t; ExtendedPictographic #\t[✃✄]\tLOWER BLADE SCISSORS .. WHITE SCISSORS\nU+270E\t; ExtendedPictographic #\t[✎]\tLOWER RIGHT PENCIL\nU+2710..U+2711\t; ExtendedPictographic #\t[✐✑]\tUPPER RIGHT PENCIL .. WHITE NIB\nU+2765..U+2767\t; ExtendedPictographic #\t[❥-❧]\tROTATED HEAVY BLACK HEART BULLET .. ROTATED FLORAL HEART BULLET\n# count=10\n\n# Domino_Tiles\n# EP=112\t: [🀰-🂟]\n\nU+1F030..U+1F093\t; ExtendedPictographic #\t[🀰-🂓]\tDOMINO TILE HORIZONTAL BACK .. DOMINO TILE VERTICAL-06-06\nU+1F094..U+1F09F\t; ExtendedPictographic #\tGC=Cn\n# count=112\n\n# Emoticons\n# emoji=80\t: [😀-🙏]\n\n# Enclosed_Alphanumerics\n# emoji=1\t: [Ⓜ]\n# other=159\t: [①-ⓁⓃ-⓿]\n\n# Enclosed_Alphanumeric_Supplement\n# emoji=15\t: [🅰🅱🅾🅿🆎🆑-🆚]\n# EP=65\t: [🄍-🄏🄯🅬-🅯🆭-🇥]\n# other=176\t: [🄀-🄌🄐-🄮🄰-🅫🅲-🅽🆀-🆍🆏🆐🆛-🆬🇦-🇿]\n\nU+1F10D..U+1F10F\t; ExtendedPictographic #\tGC=Cn\nU+1F12F\t; ExtendedPictographic #\tGC=Cn\nU+1F16C..U+1F16F\t; ExtendedPictographic #\tGC=Cn\nU+1F1AD..U+1F1E5\t; ExtendedPictographic #\tGC=Cn\n# count=65\n\n# Enclosed_CJK_Letters_And_Months\n# emoji=2\t: [㊗㊙]\n# other=252\t: [㈀-㈞㈠-㊖㊘㊚-㋾]\n\n# Enclosed_Ideographic_Supplement\n# emoji=15\t: [🈁🈂🈚🈯🈲-🈺🉐🉑]\n# EP=198\t: [🈃-🈏🈼-🈿🉉-🉏🉒-🋿]\n# other=43\t: [🈀🈐-🈙🈛-🈮🈰🈱🈻🉀-🉈]\n\nU+1F260..U+1F265\t; ExtendedPictographic #\t[🉠-🉥]\tROUNDED SYMBOL FOR FU .. ROUNDED SYMBOL FOR CAI\nU+1F203..U+1F20F\t; ExtendedPictographic #\tGC=Cn\nU+1F23C..U+1F23F\t; ExtendedPictographic #\tGC=Cn\nU+1F249..U+1F24F\t; ExtendedPictographic #\tGC=Cn\nU+1F252..U+1F25F\t; ExtendedPictographic #\tGC=Cn\nU+1F266..U+1F2FF\t; ExtendedPictographic #\tGC=Cn\n# count=198\n\n# Geometric_Shapes\n# emoji=8\t: [▪▫▶◀◻-◾]\n# other=88\t: [■-▩▬-▵▷-▿◁-◺◿]\n\n# Geometric_Shapes_Extended\n# EP=43\t: [🟕-🟿]\n# other=85\t: [🞀-🟔]\n\nU+1F7D5..U+1F7FF\t; ExtendedPictographic #\tGC=Cn\n# count=43\n\n# Latin_1_Supplement\n# emoji=2\t: [©®]\n# other=126\t: [-¨ª-­¯-ÿ]\n\n# Letterlike_Symbols\n# emoji=2\t: [™ℹ]\n# other=78\t: [℀-℡℣-ℸ℺-⅏]\n\n# Mahjong_Tiles\n# emoji=1\t: [🀄]\n# EP=47\t: [🀀-🀃🀅-🀯]\n\nU+1F000..U+1F003\t; ExtendedPictographic #\t[🀀-🀃]\tMAHJONG TILE EAST WIND .. MAHJONG TILE NORTH WIND\nU+1F005..U+1F02B\t; ExtendedPictographic #\t[🀅-🀫]\tMAHJONG TILE GREEN DRAGON .. MAHJONG TILE BACK\nU+1F02C..U+1F02F\t; ExtendedPictographic #\tGC=Cn\n# count=47\n\n# Miscellaneous_Symbols_And_Arrows\n# emoji=7\t: [⬅-⬇⬛⬜⭐⭕]\n# other=200\t: [⬀-⬄⬈-⬚⬝-⭏⭑-⭔⭖-⭳⭶-⮕⮘-⮹⮽-⯈⯊-⯒⯬-⯯]\n\n# Miscellaneous_Symbols_And_Pictographs\n# emoji=637\t: [🌀-🌡🌤-🎓🎖🎗🎙-🎛🎞-🏰🏳-🏵🏷-📽📿-🔽🕉-🕎🕐-🕧🕯🕰🕳-🕺🖇🖊-🖍🖐🖕🖖🖤🖥🖨🖱🖲🖼🗂-🗄🗑-🗓🗜-🗞🗡🗣🗨🗯🗳🗺-🗿]\n# EP=131\t: [🌢🌣🎔🎕🎘🎜🎝🏱🏲🏶📾🔾-🕈🕏🕨-🕮🕱🕲🕻-🖆🖈🖉🖎🖏🖑-🖔🖗-🖣🖦🖧🖩-🖰🖳-🖻🖽-🗁🗅-🗐🗔-🗛🗟🗠🗢🗤-🗧🗩-🗮🗰-🗲🗴-🗹]\n\nU+1F322..U+1F323\t; ExtendedPictographic #\t[🌢🌣]\tBLACK DROPLET .. WHITE SUN\nU+1F394..U+1F395\t; ExtendedPictographic #\t[🎔🎕]\tHEART WITH TIP ON THE LEFT .. BOUQUET OF FLOWERS\nU+1F398\t; ExtendedPictographic #\t[🎘]\tMUSICAL KEYBOARD WITH JACKS\nU+1F39C..U+1F39D\t; ExtendedPictographic #\t[🎜🎝]\tBEAMED ASCENDING MUSICAL NOTES .. BEAMED DESCENDING MUSICAL NOTES\nU+1F3F1..U+1F3F2\t; ExtendedPictographic #\t[🏱🏲]\tWHITE PENNANT .. BLACK PENNANT\nU+1F3F6\t; ExtendedPictographic #\t[🏶]\tBLACK ROSETTE\nU+1F4FE\t; ExtendedPictographic #\t[📾]\tPORTABLE STEREO\nU+1F53E..U+1F548\t; ExtendedPictographic #\t[🔾-🕈]\tLOWER RIGHT SHADOWED WHITE CIRCLE .. CELTIC CROSS\nU+1F54F\t; ExtendedPictographic #\t[🕏]\tBOWL OF HYGIEIA\nU+1F568..U+1F56E\t; ExtendedPictographic #\t[🕨-🕮]\tRIGHT SPEAKER .. BOOK\nU+1F571..U+1F572\t; ExtendedPictographic #\t[🕱🕲]\tBLACK SKULL AND CROSSBONES .. NO PIRACY\nU+1F57B..U+1F586\t; ExtendedPictographic #\t[🕻-🖆]\tLEFT HAND TELEPHONE RECEIVER .. PEN OVER STAMPED ENVELOPE\nU+1F588..U+1F589\t; ExtendedPictographic #\t[🖈🖉]\tBLACK PUSHPIN .. LOWER LEFT PENCIL\nU+1F58E..U+1F58F\t; ExtendedPictographic #\t[🖎🖏]\tLEFT WRITING HAND .. TURNED OK HAND SIGN\nU+1F591..U+1F594\t; ExtendedPictographic #\t[🖑-🖔]\tREVERSED RAISED HAND WITH FINGERS SPLAYED .. REVERSED VICTORY HAND\nU+1F597..U+1F5A3\t; ExtendedPictographic #\t[🖗-🖣]\tWHITE DOWN POINTING LEFT HAND INDEX .. BLACK DOWN POINTING BACKHAND INDEX\nU+1F5A6..U+1F5A7\t; ExtendedPictographic #\t[🖦🖧]\tKEYBOARD AND MOUSE .. THREE NETWORKED COMPUTERS\nU+1F5A9..U+1F5B0\t; ExtendedPictographic #\t[🖩-🖰]\tPOCKET CALCULATOR .. TWO BUTTON MOUSE\nU+1F5B3..U+1F5BB\t; ExtendedPictographic #\t[🖳-🖻]\tOLD PERSONAL COMPUTER .. DOCUMENT WITH PICTURE\nU+1F5BD..U+1F5C1\t; ExtendedPictographic #\t[🖽-🗁]\tFRAME WITH TILES .. OPEN FOLDER\nU+1F5C5..U+1F5D0\t; ExtendedPictographic #\t[🗅-🗐]\tEMPTY NOTE .. PAGES\nU+1F5D4..U+1F5DB\t; ExtendedPictographic #\t[🗔-🗛]\tDESKTOP WINDOW .. DECREASE FONT SIZE SYMBOL\nU+1F5DF..U+1F5E0\t; ExtendedPictographic #\t[🗟🗠]\tPAGE WITH CIRCLED TEXT .. STOCK CHART\nU+1F5E2\t; ExtendedPictographic #\t[🗢]\tLIPS\nU+1F5E4..U+1F5E7\t; ExtendedPictographic #\t[🗤-🗧]\tTHREE RAYS ABOVE .. THREE RAYS RIGHT\nU+1F5E9..U+1F5EE\t; ExtendedPictographic #\t[🗩-🗮]\tRIGHT SPEECH BUBBLE .. LEFT ANGER BUBBLE\nU+1F5F0..U+1F5F2\t; ExtendedPictographic #\t[🗰-🗲]\tMOOD BUBBLE .. LIGHTNING MOOD\nU+1F5F4..U+1F5F9\t; ExtendedPictographic #\t[🗴-🗹]\tBALLOT SCRIPT X .. BALLOT BOX WITH BOLD CHECK\n# count=131\n\n# Miscellaneous_Symbols\n# emoji=80\t: [☀-☄☎☑☔☕☘☝☠☢☣☦☪☮☯☸-☺♀♂♈-♓♠♣♥♦♨♻♿⚒-⚗⚙⚛⚜⚠⚡⚪⚫⚰⚱⚽⚾⛄⛅⛈⛎⛏⛑⛓⛔⛩⛪⛰-⛵⛷-⛺⛽]\n# EP=177\t: [★☇-☍☏☐☒☖☗☙-☜☞☟☡☤☥☧-☩☫-☭☰-☷☻-♇♔-♟♡♢♤♧♩-♺♼-♾⚀-⚑⚕⚘⚚⚝-⚟⚢-⚩⚬-⚯⚲-⚼⚿-⛃⛆⛇⛉-⛍⛐⛒⛕-⛨⛫-⛯⛶⛻⛼⛾⛿]\n# other=2\t: [☆☓]\n\nU+2605\t; ExtendedPictographic #\t[★]\tBLACK STAR\nU+2607..U+260D\t; ExtendedPictographic #\t[☇-☍]\tLIGHTNING .. OPPOSITION\nU+260F..U+2610\t; ExtendedPictographic #\t[☏☐]\tWHITE TELEPHONE .. BALLOT BOX\nU+2612\t; ExtendedPictographic #\t[☒]\tBALLOT BOX WITH X\nU+2616..U+2617\t; ExtendedPictographic #\t[☖☗]\tWHITE SHOGI PIECE .. BLACK SHOGI PIECE\nU+2619..U+261C\t; ExtendedPictographic #\t[☙-☜]\tREVERSED ROTATED FLORAL HEART BULLET .. WHITE LEFT POINTING INDEX\nU+261E..U+261F\t; ExtendedPictographic #\t[☞☟]\tWHITE RIGHT POINTING INDEX .. WHITE DOWN POINTING INDEX\nU+2621\t; ExtendedPictographic #\t[☡]\tCAUTION SIGN\nU+2624..U+2625\t; ExtendedPictographic #\t[☤☥]\tCADUCEUS .. ANKH\nU+2627..U+2629\t; ExtendedPictographic #\t[☧-☩]\tCHI RHO .. CROSS OF JERUSALEM\nU+262B..U+262D\t; ExtendedPictographic #\t[☫-☭]\tFARSI SYMBOL .. HAMMER AND SICKLE\nU+2630..U+2637\t; ExtendedPictographic #\t[☰-☷]\tTRIGRAM FOR HEAVEN .. TRIGRAM FOR EARTH\nU+263B..U+2647\t; ExtendedPictographic #\t[☻-♇]\tBLACK SMILING FACE .. PLUTO\nU+2654..U+265F\t; ExtendedPictographic #\t[♔-♟]\tWHITE CHESS KING .. BLACK CHESS PAWN\nU+2661..U+2662\t; ExtendedPictographic #\t[♡♢]\tWHITE HEART SUIT .. WHITE DIAMOND SUIT\nU+2664\t; ExtendedPictographic #\t[♤]\tWHITE SPADE SUIT\nU+2667\t; ExtendedPictographic #\t[♧]\tWHITE CLUB SUIT\nU+2669..U+267A\t; ExtendedPictographic #\t[♩-♺]\tQUARTER NOTE .. RECYCLING SYMBOL FOR GENERIC MATERIALS\nU+267C..U+267E\t; ExtendedPictographic #\t[♼-♾]\tRECYCLED PAPER SYMBOL .. PERMANENT PAPER SIGN\nU+2680..U+2691\t; ExtendedPictographic #\t[⚀-⚑]\tDIE FACE-1 .. BLACK FLAG\nU+2695\t; ExtendedPictographic #\t[⚕]\tSTAFF OF AESCULAPIUS\nU+2698\t; ExtendedPictographic #\t[⚘]\tFLOWER\nU+269A\t; ExtendedPictographic #\t[⚚]\tSTAFF OF HERMES\nU+269D..U+269F\t; ExtendedPictographic #\t[⚝-⚟]\tOUTLINED WHITE STAR .. THREE LINES CONVERGING LEFT\nU+26A2..U+26A9\t; ExtendedPictographic #\t[⚢-⚩]\tDOUBLED FEMALE SIGN .. HORIZONTAL MALE WITH STROKE SIGN\nU+26AC..U+26AF\t; ExtendedPictographic #\t[⚬-⚯]\tMEDIUM SMALL WHITE CIRCLE .. UNMARRIED PARTNERSHIP SYMBOL\nU+26B2..U+26BC\t; ExtendedPictographic #\t[⚲-⚼]\tNEUTER .. SESQUIQUADRATE\nU+26BF..U+26C3\t; ExtendedPictographic #\t[⚿-⛃]\tSQUARED KEY .. BLACK DRAUGHTS KING\nU+26C6..U+26C7\t; ExtendedPictographic #\t[⛆⛇]\tRAIN .. BLACK SNOWMAN\nU+26C9..U+26CD\t; ExtendedPictographic #\t[⛉-⛍]\tTURNED WHITE SHOGI PIECE .. DISABLED CAR\nU+26D0\t; ExtendedPictographic #\t[⛐]\tCAR SLIDING\nU+26D2\t; ExtendedPictographic #\t[⛒]\tCIRCLED CROSSING LANES\nU+26D5..U+26E8\t; ExtendedPictographic #\t[⛕-⛨]\tALTERNATE ONE-WAY LEFT WAY TRAFFIC .. BLACK CROSS ON SHIELD\nU+26EB..U+26EF\t; ExtendedPictographic #\t[⛫-⛯]\tCASTLE .. MAP SYMBOL FOR LIGHTHOUSE\nU+26F6\t; ExtendedPictographic #\t[⛶]\tSQUARE FOUR CORNERS\nU+26FB..U+26FC\t; ExtendedPictographic #\t[⛻⛼]\tJAPANESE BANK SYMBOL .. HEADSTONE GRAVEYARD SYMBOL\nU+26FE..U+26FF\t; ExtendedPictographic #\t[⛾⛿]\tCUP ON BLACK SQUARE .. WHITE FLAG WITH HORIZONTAL MIDDLE BLACK STRIPE\n# count=177\n\n# Miscellaneous_Technical\n# emoji=18\t: [⌚⌛⌨⏏⏩-⏳⏸-⏺]\n# EP=1\t: [⎈]\n# other=237\t: [⌀-⌙⌜-⌧〈-⎇⎉-⏎⏐-⏨⏴-⏷⏻-⏿]\n\nU+2388\t; ExtendedPictographic #\t[⎈]\tHELM SYMBOL\n# count=1\n\n# No_Block\n# EP=1534\t: [🨀-🿽]\n\nU+1FA00..U+1FFFD\t; ExtendedPictographic #\tGC=Cn\n# count=1534\n\n# Playing_Cards\n# emoji=1\t: [🃏]\n# EP=96\t: [🂠-🃿]\n\nU+1F0A0..U+1F0AE\t; ExtendedPictographic #\t[🂠-🂮]\tPLAYING CARD BACK .. PLAYING CARD KING OF SPADES\nU+1F0B1..U+1F0BF\t; ExtendedPictographic #\t[🂱-🂿]\tPLAYING CARD ACE OF HEARTS .. PLAYING CARD RED JOKER\nU+1F0C1..U+1F0CF\t; ExtendedPictographic #\t[🃁-🃏]\tPLAYING CARD ACE OF DIAMONDS .. PLAYING CARD BLACK JOKER\nU+1F0D1..U+1F0F5\t; ExtendedPictographic #\t[🃑-🃵]\tPLAYING CARD ACE OF CLUBS .. PLAYING CARD TRUMP-21\nU+1F0AF..U+1F0B0\t; ExtendedPictographic #\tGC=Cn\nU+1F0C0\t; ExtendedPictographic #\tGC=Cn\nU+1F0D0\t; ExtendedPictographic #\tGC=Cn\nU+1F0F6..U+1F0FF\t; ExtendedPictographic #\tGC=Cn\n# count=96\n\n# General_Punctuation\n# emoji=2\t: [‼⁉]\n# other=109\t: [ -※‽-⁈⁊-⁤⁦-⁯]\n\n# Supplemental_Arrows_B\n# emoji=2\t: [⤴⤵]\n# other=126\t: [⤀-⤳⤶-⥿]\n\n# Supplemental_Arrows_C\n# EP=108\t: [🠌-🠏🡈-🡏🡚-🡟🢈-🢏🢮-🣿]\n# other=148\t: [🠀-🠋🠐-🡇🡐-🡙🡠-🢇🢐-🢭]\n\nU+1F80C..U+1F80F\t; ExtendedPictographic #\tGC=Cn\nU+1F848..U+1F84F\t; ExtendedPictographic #\tGC=Cn\nU+1F85A..U+1F85F\t; ExtendedPictographic #\tGC=Cn\nU+1F888..U+1F88F\t; ExtendedPictographic #\tGC=Cn\nU+1F8AE..U+1F8FF\t; ExtendedPictographic #\tGC=Cn\n# count=108\n\n# Supplemental_Symbols_And_Pictographs\n# emoji=134\t: [🤐-🤺🤼-🤾🥀-🥅🥇-🥌🥐-🥫🦀-🦗🧀🧐-🧦]\n# EP=174\t: [🤀-🤏🤟🤨-🤯🤱🤲🤿🥌-🥏🥟-🥿🦒-🦿🧁-🧿]\n# other=2\t: [🤻🥆]\n\nU+1F900..U+1F90B\t; ExtendedPictographic #\t[🤀-🤋]\tCIRCLED CROSS FORMEE WITH FOUR DOTS .. DOWNWARD FACING NOTCHED HOOK WITH DOT\nU+1F91F\t; ExtendedPictographic #\t[🤟]\tI LOVE YOU HAND SIGN\nU+1F928..U+1F92F\t; ExtendedPictographic #\t[🤨-🤯]\tFACE WITH ONE EYEBROW RAISED .. SHOCKED FACE WITH EXPLODING HEAD\nU+1F931..U+1F932\t; ExtendedPictographic #\t[🤱🤲]\tBREAST-FEEDING .. PALMS UP TOGETHER\nU+1F94C\t; ExtendedPictographic #\t[🥌]\tCURLING STONE\nU+1F95F..U+1F96B\t; ExtendedPictographic #\t[🥟-🥫]\tDUMPLING .. CANNED FOOD\nU+1F992..U+1F997\t; ExtendedPictographic #\t[🦒-🦗]\tGIRAFFE FACE .. CRICKET\nU+1F9D0..U+1F9E6\t; ExtendedPictographic #\t[🧐-🧦]\tFACE WITH MONOCLE .. SOCKS\nU+1F90C..U+1F90F\t; ExtendedPictographic #\tGC=Cn\nU+1F93F\t; ExtendedPictographic #\tGC=Cn\nU+1F94D..U+1F94F\t; ExtendedPictographic #\tGC=Cn\nU+1F96C..U+1F97F\t; ExtendedPictographic #\tGC=Cn\nU+1F998..U+1F9BF\t; ExtendedPictographic #\tGC=Cn\nU+1F9C1..U+1F9CF\t; ExtendedPictographic #\tGC=Cn\nU+1F9E7..U+1F9FF\t; ExtendedPictographic #\tGC=Cn\n# count=174\n\n# Transport_And_Map_Symbols\n# emoji=94\t: [🚀-🛅🛋-🛒🛠-🛥🛩🛫🛬🛰🛳-🛸]\n# EP=36\t: [🛆-🛊🛓-🛟🛦-🛨🛪🛭-🛯🛱🛲🛷-🛿]\n\nU+1F6C6..U+1F6CA\t; ExtendedPictographic #\t[🛆-🛊]\tTRIANGLE WITH ROUNDED CORNERS .. GIRLS SYMBOL\nU+1F6D3..U+1F6D4\t; ExtendedPictographic #\t[🛓🛔]\tSTUPA .. PAGODA\nU+1F6E6..U+1F6E8\t; ExtendedPictographic #\t[🛦-🛨]\tUP-POINTING MILITARY AIRPLANE .. UP-POINTING SMALL AIRPLANE\nU+1F6EA\t; ExtendedPictographic #\t[🛪]\tNORTHEAST-POINTING AIRPLANE\nU+1F6F1..U+1F6F2\t; ExtendedPictographic #\t[🛱🛲]\tONCOMING FIRE ENGINE .. DIESEL LOCOMOTIVE\nU+1F6F7..U+1F6F8\t; ExtendedPictographic #\t[🛷🛸]\tSLED .. FLYING SAUCER\nU+1F6D5..U+1F6DF\t; ExtendedPictographic #\tGC=Cn\nU+1F6ED..U+1F6EF\t; ExtendedPictographic #\tGC=Cn\nU+1F6F9..U+1F6FF\t; ExtendedPictographic #\tGC=Cn\n# count=36\n\n# total_count=2744\n# EOF\n"
  },
  {
    "path": "scripts/parse-extended-pictographic/README.md",
    "content": "README for scripts/extended-pictographic\n===========\n\nThis directory contains the Unicode UTS #35 `ExtendedPictographic.txt` data file,\nintended to be parsed by the script `parse.py` to produce `ExtendedPictographic-Parsed.txt`.\n\nThis produces a series of `IntervalSet` entries to be consumed by\n`UnicodeDataTemplateController`.\n"
  },
  {
    "path": "scripts/parse-extended-pictographic/parse.py",
    "content": "from __future__ import print_function\nimport codecs\nimport re\nimport sys\n\ndef main(input, output):\n    code_point_re = re.compile(r'^U\\+([0-9a-fA-F]+)\\s*;\\s*ExtendedPictographic.*$')\n    code_point_range_re = re.compile(r'^U\\+([0-9a-fA-F]+)\\.\\.U\\+([0-9a-fA-F]+)\\s*;\\s*ExtendedPictographic.*$')\n\n    for line in input:\n        m = code_point_re.match(line)\n        if m:\n            print('set.add(0x' + m.group(1) + ');', file=output)\n        else:\n            m = code_point_range_re.match(line)\n            if m:\n                print('set.add(0x' + m.group(1) + ', 0x' + m.group(2) + ');', file=output)\n\nif __name__ == '__main__':\n    with codecs.open(sys.argv[1], 'r', 'utf-8') as f:\n        main(f, sys.stdout)\n"
  },
  {
    "path": "scripts/traceatn.sh",
    "content": "#! /bin/sh\n\n# Run this so we get right jars before trying this script:\n#  cd ANTLR-ROOT-DIR\n#  mvn install -DskipTests=true\n#  cd runtime-testsuite\n#  mvn install jar:test-jar -DskipTests=true \n#\n# Run script with \n#\n#  traceatn.sh /tmp/JSON.g4 json /tmp/foo.json\n\nexport ANTLRJAR=~/.m2/repository/org/antlr/antlr4/4.13.0-SNAPSHOT/antlr4-4.13.0-SNAPSHOT-complete.jar\nexport TESTJAR=~/.m2/repository/org/antlr/antlr4-runtime-testsuite/4.13.0-SNAPSHOT/antlr4-runtime-testsuite-4.13.0-SNAPSHOT-tests.jar\nexport JUPITER=~/.m2/repository/org/junit/jupiter/junit-jupiter-api/5.9.0/junit-jupiter-api-5.9.0.jar\nexport OPENTEST=~/.m2/repository/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar\njava -classpath $ANTLRJAR:$TESTJAR:$JUPITER:$OPENTEST org.antlr.v4.test.runtime.TraceATN $@\n"
  },
  {
    "path": "scripts/update_antlr_version.py",
    "content": "\"\"\"\n$ python update_antlr_version.py 4.9.3 4.10\n\nRead file\n\"\"\"\nimport sys\nimport os\nimport subprocess\n\n\ndef runme(cmd):\n    return subprocess.check_output(cmd.split(' '))\n\n\ndef freshen(ROOT):\n    ok = input(\"Perform antlr4 `mvn clean` and wipe build dirs Y/N? (default no): \")\n    ok = ok.lower()\n    if ok.lower() != 'y' and ok !='yes':\n        print(\"Ok, not cleaning antlr4 dir\")\n        return\n    # runme(\"mvn clean\")\n    runme(f\"rm -rf {ROOT}/runtime/CSharp/src/bin\")\n    runme(f\"rm -rf {ROOT}/runtime/CSharp/src/obj\")\n    runme(f\"rm -rf {ROOT}/runtime/Cpp/runtime/build\")\n    runme(f\"rm -rf {ROOT}/runtime/gen\")\n    runme(f\"rm -rf {ROOT}/runtime/JavaScript/dist\")\n\n\ndef get_change_list(fname):\n    files = {}\n    with open(fname, \"r\") as f:\n        for line in f.readlines():\n            line = line.strip()\n            if len(line)>0 and not line.startswith(\"#\"):\n                if line.startswith('*'): # '*' implies change multiple lines\n                    files[line[1:].strip()] = True\n                else:\n                    files[line] = False\n\n    return files\n\n\ndef update_file(qfname, multi, before, after):\n    with open(qfname, \"r\", encoding=\"UTF-8\") as f:\n        text = f.read()\n\n    if before not in text:\n        print(f\"{before} not in {qfname}\")\n        return\n\n    # Don't update if on > 1 line; too complex for tool\n    lines = text.split('\\n')\n    count = sum(before in line for line in lines)\n    if count>1 and not multi:\n        print(f\"{before} appears on {count} lines so _not_ updating {qfname}\")\n    else:\n        # print(f\"{before} => {after} in {qfname}\")\n        text = text.replace(before, after)\n        with open(qfname, \"w\", encoding=\"UTF-8\") as f:\n            f.write(text)\n\n\ndef update_files(ROOT, before, after):\n    files = get_change_list(f\"{ROOT}/scripts/files-to-update.txt\")\n    for fname,multi in files.items():\n        update_file(f\"{ROOT}/{fname}\", multi, before, after)\n\n\ndef find_remaining(ROOT, before):\n    return\n\n\nif __name__ == '__main__':\n    # This is where parrt puts antlr\n    ROOT = f\"{os.path.expanduser('~')}/antlr/code/antlr4\"\n    # ROOT = f\"/tmp/antlr4\" # for testing, it's nice to have diff target\n\n    before = sys.argv[1]\n    after = sys.argv[2]\n    print(f\"Updating ANTLR version from {before} to {after}\")\n\n    root = input(f\"Set ANTLR repo root (default {ROOT}): \")\n    if len(root.strip())>0:\n        ROOT = root\n\n    freshen(ROOT)\n\n    update_files(ROOT, before, after)\n\n    find_remaining(ROOT, before)\n\n    print(\"Warning: manually update runtime/Cpp/runtime/src/Version.h has non-standard version mechanism\")\n    print(\"Warning: some targets can't handle 4.x; must be 4.x.0:\")\n    print(\"\\truntime/Dart/pubspec.yaml\")\n    print(\"\\truntime/JavaScript/package.json\")\n"
  },
  {
    "path": "tool/nb-configuration.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project-shared-configuration>\n    <!--\nThis file contains additional configuration written by modules in the NetBeans IDE.\nThe configuration is intended to be shared among all the users of project and\ntherefore it is assumed to be part of version control checkout.\nWithout this configuration present, some functionality in the IDE may be limited or fail altogether.\n-->\n    <properties xmlns=\"http://www.netbeans.org/ns/maven-properties-data/1\">\n        <!--\nProperties that influence various parts of the IDE, especially code formatting and the like.\nYou can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.\nThat way multiple projects can share the same settings (useful for formatting rules for example).\nAny value defined here will override the pom.xml file value but is only applicable to the current project.\n-->\n        <org-netbeans-modules-editor-indent.CodeStyle.usedProfile>project</org-netbeans-modules-editor-indent.CodeStyle.usedProfile>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs>true</org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.text-line-wrap>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.continuationIndentSize>4</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.continuationIndentSize>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStarImport>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStarImport>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStaticStarImport>false</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.allowConvertToStaticStarImport>\n        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>*;java</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>\n        <netbeans.compile.on.save>test</netbeans.compile.on.save>\n        <org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.expand-tabs>false</org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.text.x-stringtemplate4.CodeStyle.project.text-line-wrap>\n        <org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.spaces-per-tab>4</org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.spaces-per-tab>\n        <org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.tab-size>\n        <org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.indent-shift-width>4</org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.indent-shift-width>\n        <org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.expand-tabs>false</org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.expand-tabs>\n        <org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.text-limit-width>\n        <org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.text-line-wrap>none</org-netbeans-modules-editor-indent.text.x-antlr3.CodeStyle.project.text-line-wrap>\n    </properties>\n</project-shared-configuration>\n"
  },
  {
    "path": "tool/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<groupId>org.antlr</groupId>\n\t\t<artifactId>antlr4-master</artifactId>\n\t\t<version>4.13.3-SNAPSHOT</version>\n\t</parent>\n\t<artifactId>antlr4</artifactId>\n\t<name>ANTLR 4 Tool</name>\n\t<url>http://www.antlr.org</url>\n\t<description>The ANTLR 4 grammar compiler.</description>\n\n    <prerequisites>\n        <maven>3.8</maven>\n    </prerequisites>\n\n    <dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.antlr</groupId>\n\t\t\t<artifactId>antlr4-runtime</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.antlr</groupId>\n\t\t\t<artifactId>antlr-runtime</artifactId>\n\t\t\t<version>3.5.3</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.antlr</groupId>\n\t\t\t<artifactId>ST4</artifactId>\n\t\t\t<version>4.3.4</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.abego.treelayout</groupId>\n\t\t\t<artifactId>org.abego.treelayout.core</artifactId>\n\t\t\t<version>1.0.3</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.ibm.icu</groupId>\n\t\t\t<artifactId>icu4j</artifactId>\n\t\t\t<version>72.1</version>\n\t\t</dependency>\n\t</dependencies>\n\t<build>\n\t\t<sourceDirectory>src</sourceDirectory>\n\t\t<testResources>\n\t\t\t<testResource>\n\t\t\t\t<directory>test</directory>\n\t\t\t</testResource>\n\t\t</testResources>\n\t\t<plugins>\n\t\t\t<plugin> <!-- create src jar -->\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-source-plugin</artifactId>\n\t\t\t\t<version>3.2.1</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin> <!-- create javadoc jar -->\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t<version>3.3.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<javadocVersion>11</javadocVersion>\n\t\t\t\t\t<failOnError>false</failOnError>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<phase>deploy</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>javadoc</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin> <!-- include code-generated sources -->\n\t\t\t\t<groupId>org.codehaus.mojo</groupId>\n\t\t\t\t<artifactId>build-helper-maven-plugin</artifactId>\n\t\t\t\t<version>3.2.0</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<phase>generate-sources</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>add-source</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<sources>\n\t\t\t\t\t\t\t\t<source>${project.build.directory}/generated-sources/antlr4-tool-codegen</source>\n\t\t\t\t\t\t\t</sources>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin> <!-- this makes a fat jar with all dependencies -->\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-shade-plugin</artifactId>\n\t\t\t\t<version>3.2.4</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<phase>package</phase>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<minimizeJar>false</minimizeJar>\n\t\t\t\t\t\t\t<createDependencyReducedPom>false</createDependencyReducedPom>\n\t\t\t\t\t\t\t<shadedArtifactAttached>true</shadedArtifactAttached>\n\t\t\t\t\t\t\t<shadedClassifierName>complete</shadedClassifierName>\n\t\t\t\t\t\t\t<artifactSet>\n\t\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t\t<exclude>com.ibm.icu:*</exclude>\n\t\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t</artifactSet>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>shade</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<!-- can't get this to add bundle items <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.5.4</version> <executions> <execution> <id>bundle-manifest</id> <phase>process-classes</phase> <configuration> <instructions> <Bundle-SymbolicName>org.antlr.antlr4-tool</Bundle-SymbolicName> </instructions> </configuration> <goals> <goal>manifest</goal> </goals> </execution> </executions> </plugin> -->\n\t\t\t<plugin> <!-- this just jars up tool stuff and sets main class -->\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>3.2.0</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<archive>\n\t\t\t\t\t\t<manifest>\n\t\t\t\t\t\t\t<addDefaultImplementationEntries>true</addDefaultImplementationEntries>\n\t\t\t\t\t\t\t<mainClass>org.antlr.v4.Tool</mainClass>\n\t\t\t\t\t\t</manifest>\n\t\t\t\t\t</archive>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.antlr</groupId>\n\t\t\t\t<artifactId>antlr3-maven-plugin</artifactId>\n\t\t\t\t<version>3.5.3</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<sourceDirectory>src</sourceDirectory>\n\t\t\t\t\t<verbose>true</verbose>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>antlr</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n            <plugin><!-- workaround for https://github.com/antlr/antlr3/pull/209 -->\n              <groupId>com.google.code.maven-replacer-plugin</groupId>\n                <artifactId>replacer</artifactId>\n                <version>1.5.3</version>\n                <executions>\n                    <execution>\n                        <id>fix-antlr3-RB</id>\n                        <phase>process-sources</phase>\n                        <goals>\n                            <goal>replace</goal>\n                        </goals>\n                    </execution>\n                </executions>\n                <configuration>\n                    <basedir>${project.build.directory}/generated-sources/antlr3/org/antlr/v4</basedir>\n                    <includes>\n                        <include>parse/*.java</include>\n                        <include>codegen/*.java</include>\n                    </includes>\n                    <replacements>\n                        <replacement>\n                            <token>(// .ANTLR .+) ....-..-.. ..:..:..</token>\n                            <value>$1</value>\n                        </replacement>\n                        <replacement>\n                            <token>(// elements: ).*</token>\n                            <value>$1</value>\n                        </replacement>\n                    </replacements>\n                    <regex>true</regex>\n                </configuration>\n            </plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>com.webguys</groupId>\n\t\t\t\t<artifactId>string-template-maven-plugin</artifactId>\n\t\t\t\t<version>1.1</version>\n\t\t\t\t<!-- this nonsense is for some reason needed to make this plugin work with maven 3 -->\n\t\t\t\t<dependencies>\n\t\t\t\t\t<dependency>\n\t\t\t\t\t\t<groupId>org.twdata.maven</groupId>\n\t\t\t\t\t\t<artifactId>mojo-executor</artifactId>\n\t\t\t\t\t\t<version>2.1.0</version>\n\t\t\t\t\t</dependency>\n\t\t\t\t</dependencies>\n\t\t\t\t<configuration>\n\t\t\t\t\t<templates>\n\t\t\t\t\t\t<template>\n\t\t\t\t\t\t\t<directory>${basedir}/resources/org/antlr/v4/tool/templates</directory>\n\t\t\t\t\t\t\t<name>unicodedata</name>\n\t\t\t\t\t\t\t<target>${basedir}/target/generated-sources/tool/src/org/antlr/v4/unicode/UnicodeData.java</target>\n\t\t\t\t\t\t\t<controller>\n\t\t\t\t\t\t\t\t<className>org.antlr.v4.unicode.UnicodeDataTemplateController</className>\n\t\t\t\t\t\t\t\t<sourceVersion>11</sourceVersion>\n\t\t\t\t\t\t\t\t<targetVersion>11</targetVersion>\n\t\t\t\t\t\t\t\t<method>getProperties</method>\n\t\t\t\t\t\t\t</controller>\n\t\t\t\t\t\t</template>\n\t\t\t\t\t</templates>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<phase>generate-sources</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>render</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/LeftRecursiveRules.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** How to generate rules derived from left-recursive rules.\n *  These rely on recRuleAltPredicate(),\n *  recRuleArg(), recRuleSetResultAction(), recRuleSetReturnAction()\n *  templates in main language.stg\n */\ngroup LeftRecursiveRules;\n\nrecRule(ruleName, argName, primaryAlts, opAlts, setResultAction,\n        userRetvals, leftRecursiveRuleRefLabels) ::=\n<<\n<ruleName><if(userRetvals)> returns [<userRetvals>]<endif>\n    :   ( {} <primaryAlts:{alt | <alt.altText> }; separator=\"\\n        | \">\n        )\n        (\n          <opAlts; separator=\"\\n        | \">\n        )*\n    ;\n>>\n\nrecRuleAlt(alt, precOption, opPrec, pred) ::= <<\n{<pred>}?\\<<precOption>=<opPrec>\\> <alt.altText>\n>>\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/CSharp/CSharp.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2013 Terence Parr\n *  Copyright (c) 2013 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n<namedActions.header>\nusing System;\nusing System.IO;\nusing System.Text;\nusing System.Diagnostics;\nusing System.Collections.Generic;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Tree;\nusing DFA = Antlr4.Runtime.Dfa.DFA;\n\n<parser>\n<if(file.genPackage)>\n} // namespace <file.genPackage>\n<endif>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n<header>\nusing Antlr4.Runtime.Misc;\nusing IParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener;\nusing IToken = Antlr4.Runtime.IToken;\n\n/// \\<summary>\n/// This interface defines a complete listener for a parse tree produced by\n/// \\<see cref=\"<file.parserName>\"/>.\n/// \\</summary>\n[System.CodeDom.Compiler.GeneratedCode(\"ANTLR\", \"<file.ANTLRVersion>\")]\n[System.CLSCompliant(false)]\npublic interface I<file.grammarName>Listener : IParseTreeListener {\n\t<file.listenerNames:{lname |\n/// \\<summary>\n<if(file.listenerLabelRuleNames.(lname))>\n/// Enter a parse tree produced by the \\<c><lname>\\</c>\n/// labeled alternative in \\<see cref=\"<file.parserName>.<file.listenerLabelRuleNames.(lname)>\"/>.\n<else>\n/// Enter a parse tree produced by \\<see cref=\"<file.parserName>.<lname>\"/>.\n<endif>\n/// \\</summary>\n/// \\<param name=\"context\">The parse tree.\\</param>\nvoid Enter<lname; format=\"cap\">([NotNull] <file.parserName>.<lname; format=\"cap\">Context context);\n/// \\<summary>\n<if(file.listenerLabelRuleNames.(lname))>\n/// Exit a parse tree produced by the \\<c><lname>\\</c>\n/// labeled alternative in \\<see cref=\"<file.parserName>.<file.listenerLabelRuleNames.(lname)>\"/>.\n<else>\n/// Exit a parse tree produced by \\<see cref=\"<file.parserName>.<lname>\"/>.\n<endif>\n/// \\</summary>\n/// \\<param name=\"context\">The parse tree.\\</param>\nvoid Exit<lname; format=\"cap\">([NotNull] <file.parserName>.<lname; format=\"cap\">Context context);}; separator=\"\\n\">\n}\n<if(file.genPackage)>\n} // namespace <file.genPackage>\n<endif>\n>>\n\nBaseListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n<header>\n\nusing Antlr4.Runtime.Misc;\nusing IErrorNode = Antlr4.Runtime.Tree.IErrorNode;\nusing ITerminalNode = Antlr4.Runtime.Tree.ITerminalNode;\nusing IToken = Antlr4.Runtime.IToken;\nusing ParserRuleContext = Antlr4.Runtime.ParserRuleContext;\n\n/// \\<summary>\n/// This class provides an empty implementation of \\<see cref=\"I<file.grammarName>Listener\"/>,\n/// which can be extended to create a listener which only needs to handle a subset\n/// of the available methods.\n/// \\</summary>\n[System.CodeDom.Compiler.GeneratedCode(\"ANTLR\", \"<file.ANTLRVersion>\")]\n[System.Diagnostics.DebuggerNonUserCode]\n[System.CLSCompliant(false)]\npublic partial class <file.grammarName>BaseListener : I<file.grammarName>Listener {\n\t<file.listenerNames:{lname |\n/// \\<summary>\n<if(file.listenerLabelRuleNames.(lname))>\n/// Enter a parse tree produced by the \\<c><lname>\\</c>\n/// labeled alternative in \\<see cref=\"<file.parserName>.<file.listenerLabelRuleNames.(lname)>\"/>.\n<else>\n/// Enter a parse tree produced by \\<see cref=\"<file.parserName>.<lname>\"/>.\n<endif>\n/// \\<para>The default implementation does nothing.\\</para>\n/// \\</summary>\n/// \\<param name=\"context\">The parse tree.\\</param>\npublic virtual void Enter<lname; format=\"cap\">([NotNull] <file.parserName>.<lname; format=\"cap\">Context context) { \\}\n/// \\<summary>\n<if(file.listenerLabelRuleNames.(lname))>\n/// Exit a parse tree produced by the \\<c><lname>\\</c>\n/// labeled alternative in \\<see cref=\"<file.parserName>.<file.listenerLabelRuleNames.(lname)>\"/>.\n<else>\n/// Exit a parse tree produced by \\<see cref=\"<file.parserName>.<lname>\"/>.\n<endif>\n/// \\<para>The default implementation does nothing.\\</para>\n/// \\</summary>\n/// \\<param name=\"context\">The parse tree.\\</param>\npublic virtual void Exit<lname; format=\"cap\">([NotNull] <file.parserName>.<lname; format=\"cap\">Context context) { \\}}; separator=\"\\n\">\n\n\t/// \\<inheritdoc/>\n\t/// \\<remarks>The default implementation does nothing.\\</remarks>\n\tpublic virtual void EnterEveryRule([NotNull] ParserRuleContext context) { }\n\t/// \\<inheritdoc/>\n\t/// \\<remarks>The default implementation does nothing.\\</remarks>\n\tpublic virtual void ExitEveryRule([NotNull] ParserRuleContext context) { }\n\t/// \\<inheritdoc/>\n\t/// \\<remarks>The default implementation does nothing.\\</remarks>\n\tpublic virtual void VisitTerminal([NotNull] ITerminalNode node) { }\n\t/// \\<inheritdoc/>\n\t/// \\<remarks>The default implementation does nothing.\\</remarks>\n\tpublic virtual void VisitErrorNode([NotNull] IErrorNode node) { }\n}\n<if(file.genPackage)>\n} // namespace <file.genPackage>\n<endif>\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n<header>\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Tree;\nusing IToken = Antlr4.Runtime.IToken;\n\n/// \\<summary>\n/// This interface defines a complete generic visitor for a parse tree produced\n/// by \\<see cref=\"<file.parserName>\"/>.\n/// \\</summary>\n/// \\<typeparam name=\"Result\">The return type of the visit operation.\\</typeparam>\n[System.CodeDom.Compiler.GeneratedCode(\"ANTLR\", \"<file.ANTLRVersion>\")]\n[System.CLSCompliant(false)]\npublic interface I<file.grammarName>Visitor\\<Result> : IParseTreeVisitor\\<Result> {\n\t<file.visitorNames:{lname |\n/// \\<summary>\n<if(file.visitorLabelRuleNames.(lname))>\n/// Visit a parse tree produced by the \\<c><lname>\\</c>\n/// labeled alternative in \\<see cref=\"<file.parserName>.<file.visitorLabelRuleNames.(lname)>\"/>.\n<else>\n/// Visit a parse tree produced by \\<see cref=\"<file.parserName>.<lname>\"/>.\n<endif>\n/// \\</summary>\n/// \\<param name=\"context\">The parse tree.\\</param>\n/// \\<return>The visitor result.\\</return>\nResult Visit<lname; format=\"cap\">([NotNull] <file.parserName>.<lname; format=\"cap\">Context context);}; separator=\"\\n\">\n}\n<if(file.genPackage)>\n} // namespace <file.genPackage>\n<endif>\n>>\n\nBaseVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n<header>\nusing Antlr4.Runtime.Misc;\nusing Antlr4.Runtime.Tree;\nusing IToken = Antlr4.Runtime.IToken;\nusing ParserRuleContext = Antlr4.Runtime.ParserRuleContext;\n\n/// \\<summary>\n/// This class provides an empty implementation of \\<see cref=\"I<file.grammarName>Visitor{Result}\"/>,\n/// which can be extended to create a visitor which only needs to handle a subset\n/// of the available methods.\n/// \\</summary>\n/// \\<typeparam name=\"Result\">The return type of the visit operation.\\</typeparam>\n[System.CodeDom.Compiler.GeneratedCode(\"ANTLR\", \"<file.ANTLRVersion>\")]\n[System.Diagnostics.DebuggerNonUserCode]\n[System.CLSCompliant(false)]\npublic partial class <file.grammarName>BaseVisitor\\<Result> : AbstractParseTreeVisitor\\<Result>, I<file.grammarName>Visitor\\<Result> {\n\t<file.visitorNames:{lname |\n/// \\<summary>\n<if(file.visitorLabelRuleNames.(lname))>\n/// Visit a parse tree produced by the \\<c><lname>\\</c>\n/// labeled alternative in \\<see cref=\"<file.parserName>.<file.visitorLabelRuleNames.(lname)>\"/>.\n<else>\n/// Visit a parse tree produced by \\<see cref=\"<file.parserName>.<lname>\"/>.\n<endif>\n/// \\<para>\n/// The default implementation returns the result of calling \\<see cref=\"AbstractParseTreeVisitor{Result\\}.VisitChildren(IRuleNode)\"/>\n/// on \\<paramref name=\"context\"/>.\n/// \\</para>\n/// \\</summary>\n/// \\<param name=\"context\">The parse tree.\\</param>\n/// \\<return>The visitor result.\\</return>\npublic virtual Result Visit<lname; format=\"cap\">([NotNull] <file.parserName>.<lname; format=\"cap\">Context context) { return VisitChildren(context); \\}}; separator=\"\\n\">\n}\n<if(file.genPackage)>\n} // namespace <file.genPackage>\n<endif>\n>>\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n//------------------------------------------------------------------------------\n// \\<auto-generated>\n//     This code was generated by a tool.\n//     ANTLR Version: <ANTLRVersion>\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// \\</auto-generated>\n//------------------------------------------------------------------------------\n\n// Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n\n// Unreachable code detected\n#pragma warning disable 0162\n// The variable '...' is assigned but its value is never used\n#pragma warning disable 0219\n// Missing XML comment for publicly visible type or member '...'\n#pragma warning disable 1591\n// Ambiguous reference in cref attribute\n#pragma warning disable 419\n\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\n<Parser_(ctor=\"parser_ctor\", ...)>\n>>\n\nParser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<\n[System.CodeDom.Compiler.GeneratedCode(\"ANTLR\", \"<file.ANTLRVersion>\")]\n[System.CLSCompliant(false)]\npublic partial class <parser.name> : <superClass; null=\"Parser\"> {\n\tprotected static DFA[] decisionToDFA;\n\tprotected static PredictionContextCache sharedContextCache = new PredictionContextCache();\n\t<if(parser.tokens)>\n\tpublic const int\n\t\t<parser.tokens:{k | <k>=<parser.tokens.(k)>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\t<if(parser.rules)>\n\tpublic const int\n\t\t<parser.rules:{r | RULE_<r.name> = <r.index>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\tpublic static readonly string[] ruleNames = {\n\t\t<parser.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor>\n\t};\n\n\t<vocabulary(parser.literalNames, parser.symbolicNames)>\n\n\tpublic override string GrammarFileName { get { return \"<parser.grammarFileName>\"; } }\n\n\tpublic override string[] RuleNames { get { return ruleNames; } }\n\n\tpublic override int[] SerializedAtn { get { return _serializedATN; } }\n\n\tstatic <parser.name>() {\n\t\tdecisionToDFA = new DFA[_ATN.NumberOfDecisions];\n\t\tfor (int i = 0; i \\< _ATN.NumberOfDecisions; i++) {\n\t\t\tdecisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i);\n\t\t}\n\t}\n\n\t<namedActions.members>\n\t<parser:(ctor)()>\n\t<funcs; separator=\"\\n\">\n\n<if(sempredFuncs)>\n\tpublic override bool Sempred(RuleContext _localctx, int ruleIndex, int predIndex) {\n\t\tswitch (ruleIndex) {\n\t\t<parser.sempredFuncs.values:{f|\ncase <f.ruleIndex>: return <f.name>_sempred((<f.ctxType>)_localctx, predIndex);}; separator=\"\\n\">\n\t\t}\n\t\treturn true;\n\t}\n\t<sempredFuncs.values; separator=\"\\n\">\n<endif>\n\n\t<atn>\n}\n>>\n\nvocabulary(literalNames, symbolicNames) ::= <<\nprivate static readonly string[] _LiteralNames = {\n\t<literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n};\nprivate static readonly string[] _SymbolicNames = {\n\t<symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n};\npublic static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames);\n\n[NotNull]\npublic override IVocabulary Vocabulary\n{\n\tget\n\t{\n\t\treturn DefaultVocabulary;\n\t}\n}\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\npublic override void Action(RuleContext _localctx, int ruleIndex, int actionIndex) {\n\tswitch (ruleIndex) {\n\t<recog.actionFuncs.values:{f|\ncase <f.ruleIndex> : <f.name>_action(<if(!recog.modes)>(<f.ctxType>)<endif>_localctx, actionIndex); break;}; separator=\"\\n\">\n\t}\n}\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<if(sempredFuncs)>\npublic override bool Sempred(RuleContext _localctx, int ruleIndex, int predIndex) {\n\tswitch (ruleIndex) {\n\t<recog.sempredFuncs.values:{f|\ncase <f.ruleIndex> : return <f.name>_sempred(<if(!recog.modes)>(<f.ctxType>)<endif>_localctx, predIndex);}; separator=\"\\n\">\n\t}\n\treturn true;\n}\n<sempredFuncs.values; separator=\"\\n\">\n<endif>\n>>\n\nparser_ctor(parser) ::= <<\n\tpublic <parser.name>(ITokenStream input) : this(input, Console.Out, Console.Error) { }\n\n\tpublic <parser.name>(ITokenStream input, TextWriter output, TextWriter errorOutput)\n\t: base(input, output, errorOutput)\n{\n\tInterpreter = new ParserATNSimulator(this, _ATN, decisionToDFA, sharedContextCache);\n}\n>>\n\n/* This generates a private method since the actionIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\nprivate void <r.name>_action(<r.ctxType> _localctx, int actionIndex) {\n\tswitch (actionIndex) {\n\t<actions:{index|\ncase <index>: <actions.(index)> break;}; separator=\"\\n\">\n\t}\n}\n>>\n\n/* This generates a private method since the predIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\nprivate bool <r.name>_sempred(<r.ctxType> _localctx, int predIndex) {\n\tswitch (predIndex) {\n\t<actions:{index|\ncase <index>: return <actions.(index)>;}; separator=\"\\n\">\n\t}\n\treturn true;\n}\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<\n\n<if(ruleCtx)>\n<ruleCtx>\n<endif>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n\n[RuleVersion(<namedActions.version; null=\"0\">)]\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public <endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\", \">) {\n\t<currentRule.ctxType> _localctx = new <currentRule.ctxType>(Context, State<currentRule.args:{a | , <a.escapedName>}>);\n\tEnterRule(_localctx, <currentRule.startState>, RULE_<currentRule.name>);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tint _alt;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\t<if(exceptions)>\n\t<exceptions; separator=\"\\n\">\n\t<else>\n\tcatch (RecognitionException re) {\n\t\t_localctx.exception = re;\n\t\tErrorHandler.ReportError(this, re);\n\t\tErrorHandler.Recover(this, re);\n\t}\n\t<endif>\n\tfinally {\n\t\t<finallyAction>\n\t\tExitRule();\n\t}\n\treturn _localctx;\n}\n>>\n\nLeftFactoredRuleFunction(currentRule,args,code,locals,namedActions,finallyAction,postamble) ::=\n<<\n\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>private <endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\", \">) {\n\t<currentRule.ctxType> _localctx = new <currentRule.ctxType>(Context, State<currentRule.args:{a | , <a.escapedName>}>);\n\tEnterLeftFactoredRule(_localctx, <currentRule.startState>, RULE_<currentRule.variantOf>);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tint _alt;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\tcatch (RecognitionException re) {\n\t\t_localctx.exception = re;\n\t\tErrorHandler.ReportError(this, re);\n\t\tErrorHandler.Recover(this, re);\n\t}\n\tfinally {\n\t\t<finallyAction>\n\t\tExitRule();\n\t}\n\treturn _localctx;\n}\n>>\n\n// This behaves similar to RuleFunction (enterRule is called, and no adjustments\n// are made to the parse tree), but since it's still a variant no context class\n// needs to be generated.\nLeftUnfactoredRuleFunction(currentRule,args,code,locals,namedActions,finallyAction,postamble) ::=\n<<\n\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>private <endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\", \">) {\n\t<currentRule.ctxType> _localctx = new <currentRule.ctxType>(Context, State<currentRule.args:{a | , <a.escapedName>}>);\n\tEnterRule(_localctx, <currentRule.startState>, RULE_<currentRule.variantOf>);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tint _alt;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\tcatch (RecognitionException re) {\n\t\t_localctx.exception = re;\n\t\tErrorHandler.ReportError(this, re);\n\t\tErrorHandler.Recover(this, re);\n\t}\n\tfinally {\n\t\t<finallyAction>\n\t\tExitRule();\n\t}\n\treturn _localctx;\n}\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,\n\tnamedActions,finallyAction,postamble) ::=\n<<\n\n<ruleCtx>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n\n[RuleVersion(<namedActions.version; null=\"0\">)]\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public <endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\", \">) {\n\treturn <currentRule.escapedName>(0<currentRule.args:{a | , <a.escapedName>}>);\n}\n\nprivate <currentRule.ctxType> <currentRule.escapedName>(int _p<args:{a | , <a>}>) {\n\tParserRuleContext _parentctx = Context;\n\tint _parentState = State;\n\t<currentRule.ctxType> _localctx = new <currentRule.ctxType>(Context, _parentState<currentRule.args:{a | , <a.escapedName>}>);\n\t<currentRule.ctxType> _prevctx = _localctx;\n\tint _startState = <currentRule.startState>;\n\tEnterRecursionRule(_localctx, <currentRule.startState>, RULE_<currentRule.name>, _p);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tint _alt;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\tcatch (RecognitionException re) {\n\t\t_localctx.exception = re;\n\t\tErrorHandler.ReportError(this, re);\n\t\tErrorHandler.Recover(this, re);\n\t}\n\tfinally {\n\t\t<finallyAction>\n\t\tUnrollRecursionContexts(_parentctx);\n\t}\n\treturn _localctx;\n}\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>_localctx = new <currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(_localctx);<endif>\nEnterOuterAlt(_localctx, <currentOuterMostAltCodeBlock.alt.altNum>);\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n{\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n}\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nState = <choice.stateNumber>;\nErrorHandler.Sync(this);\n<if(choice.label)><labelref(choice.label)> = TokenStream.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch (TokenStream.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\">\ndefault:\n\t<error>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\nState = <choice.stateNumber>;\nErrorHandler.Sync(this);\nswitch (TokenStream.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\">\ndefault:\n\tbreak;\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nState = <choice.stateNumber>;\nErrorHandler.Sync(this);\n<preamble; separator=\"\\n\">\nif (<expr>) {\n\t<alts; separator=\"\\n\">\n}\n<!else if ( !(<followExpr>) ) <error>!>\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nState = <choice.stateNumber>;\nErrorHandler.Sync(this);\n<preamble; separator=\"\\n\">\nwhile (<loopExpr>) {\n\t<alts; separator=\"\\n\">\n\tState = <choice.loopBackStateNumber>;\n\tErrorHandler.Sync(this);\n\t<iteration>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nState = <choice.blockStartStateNumber>;<! alt block decision !>\nErrorHandler.Sync(this);\n<preamble; separator=\"\\n\">\ndo {\n\t<alts; separator=\"\\n\">\n\tState = <choice.stateNumber>;<! loopback/exit decision !>\n\tErrorHandler.Sync(this);\n\t<iteration>\n} while ( <loopExpr> );\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\nState = <choice.stateNumber>;\nErrorHandler.Sync(this);\n<if(choice.label)><labelref(choice.label)> = TokenStream.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch ( Interpreter.AdaptivePredict(TokenStream,<choice.decision>,Context) ) {\n<alts:{alt |\ncase <i>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\nState = <choice.stateNumber>;\nErrorHandler.Sync(this);\nswitch ( Interpreter.AdaptivePredict(TokenStream,<choice.decision>,Context) ) {\n<alts:{alt |\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n}\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\nState = <choice.stateNumber>;\nErrorHandler.Sync(this);\n_alt = Interpreter.AdaptivePredict(TokenStream,<choice.decision>,Context);\nwhile ( _alt!=<choice.exitAlt> && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ) {\n\tif ( _alt==1<if(!choice.ast.greedy)>+1<endif> ) {\n\t\t<iteration>\n\t\t<alts> <! should only be one !>\n\t}\n\tState = <choice.loopBackStateNumber>;\n\tErrorHandler.Sync(this);\n\t_alt = Interpreter.AdaptivePredict(TokenStream,<choice.decision>,Context);\n}\n>>\n\nPlusBlock(choice, alts, error) ::= <<\nState = <choice.blockStartStateNumber>;<! alt block decision !>\nErrorHandler.Sync(this);\n_alt = 1<if(!choice.ast.greedy)>+1<endif>;\ndo {\n\tswitch (_alt) {\n\t<alts:{alt|\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n\tdefault:\n\t\t<error>\n\t}\n\tState = <choice.loopBackStateNumber>;<! loopback/exit decision !>\n\tErrorHandler.Sync(this);\n\t_alt = Interpreter.AdaptivePredict(TokenStream,<choice.decision>,Context);\n} while ( _alt!=<choice.exitAlt> && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER );\n>>\n\nSync(s) ::= \"Sync(<s.expecting.name>);\"\n\nThrowNoViableAlt(t) ::= \"throw new NoViableAltException(this);\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount>) & ~0x3f) == 0\n>>\n\n// produces smaller bytecode only when bits.tokens contains more than two items\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShift(s.varName, bits.shift)>})> && ((1L \\<\\< <offsetShift(s.varName, bits.shift)>) & <bits.calculated>L) != 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShift(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName>==<tokenType.(t.name)>}; separator=\" || \">\n%>\n\ncases(tokens) ::= <<\n<tokens:{t | case <tokenType.(t.name)>:}; separator=\"\\n\">\n>>\n\nInvokeRule(r, argExprsChunks) ::= <<\nState = <r.stateNumber>;\n<if(r.labels)><r.labels:{l | <labelref(l)> = }><endif><r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>);\n>>\n\nMatchToken(m) ::= <<\nState = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>Match(<tokenType.(m.name)>);\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nState = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>TokenStream.LT(1);<endif>\n<capture>\nif ( <if(invert)><m.varName> \\<= 0 || <else>!<endif>(<expr>) ) {\n\t<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>ErrorHandler.RecoverInline(this);\n}\nelse {\n\tErrorHandler.ReportMatch(this);\n    Consume();\n}\n>>\n\nWildcard(w) ::= <<\nState = <w.stateNumber>;\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>MatchWildcard();\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\nState = <p.stateNumber>;\nif (!(<chunks>)) throw new FailedPredicateException(this, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>);\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n\t<catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"Skip();\"\nLexerMoreCommand()  ::= \"More();\"\nLexerPopModeCommand() ::= \"PopMode();\"\n\nLexerTypeCommand(arg, grammar)      ::= \"_type = <tokenType.(arg)>;\"\nLexerChannelCommand(arg, grammar)   ::= \"_channel = <channelName.(arg)>;\"\nLexerModeCommand(arg, grammar)      ::= \"_mode = <modeName.(arg)>;\"\nLexerPushModeCommand(arg, grammar)  ::= \"PushMode(<modeName.(arg)>);\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"_localctx.<a.escapedName>\"\nLocalRef(a) ::= \"_localctx.<a.escapedName>\"\nRetValueRef(a) ::= \"_localctx.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>.<a.dict>.<a.escapedName>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>.<tokenType.(t.escapedName)>\"\nLabelRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nListLabelRef(t) ::= \"<ctx(t)>.<ListLabelName(t.escapedName)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>.<s.escapedName> = <rhsChunks>;\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={IToken}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={IToken}>\"\n\nTokenPropertyRef_text(t) ::= \"(<ctx(t)>.<tokenType.(t.label)>!=null?<ctx(t)>.<tokenType.(t.label)>.Text:null)\"\nTokenPropertyRef_type(t) ::= \"(<ctx(t)>.<tokenType.(t.label)>!=null?<ctx(t)>.<tokenType.(t.label)>.Type:0)\"\nTokenPropertyRef_line(t) ::= \"(<ctx(t)>.<tokenType.(t.label)>!=null?<ctx(t)>.<tokenType.(t.label)>.Line:0)\"\nTokenPropertyRef_pos(t) ::= \"(<ctx(t)>.<tokenType.(t.label)>!=null?<ctx(t)>.<tokenType.(t.label)>.CharPositionInLine:0)\"\nTokenPropertyRef_channel(t) ::= \"(<ctx(t)>.<tokenType.(t.label)>!=null?<ctx(t)>.<tokenType.(t.label)>.Channel:0)\"\nTokenPropertyRef_index(t) ::= \"(<ctx(t)>.<tokenType.(t.label)>!=null?<ctx(t)>.<tokenType.(t.label)>.TokenIndex:0)\"\nTokenPropertyRef_int(t) ::= \"(<ctx(t)>.<tokenType.(t.label)>!=null?int.Parse(<ctx(t)>.<tokenType.(t.label)>.Text):0)\"\n\nRulePropertyRef_start(r) ::= \"(<ctx(r)>.<r.label>!=null?(<ctx(r)>.<r.label>.Start):null)\"\nRulePropertyRef_stop(r)\t ::= \"(<ctx(r)>.<r.label>!=null?(<ctx(r)>.<r.label>.Stop):null)\"\nRulePropertyRef_text(r)\t ::= \"(<ctx(r)>.<r.label>!=null?TokenStream.GetText(<ctx(r)>.<r.label>.Start,<ctx(r)>.<r.label>.Stop):null)\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>.<r.label>\"\nRulePropertyRef_parser(r)\t ::= \"this\"\n\nThisRulePropertyRef_start(r) ::= \"_localctx.Start\"\nThisRulePropertyRef_stop(r)\t ::= \"_localctx.Stop\"\nThisRulePropertyRef_text(r)\t ::= \"TokenStream.GetText(_localctx.Start, TokenStream.LT(-1))\"\nThisRulePropertyRef_ctx(r)\t ::= \"_localctx\"\nThisRulePropertyRef_parser(r)\t ::= \"this\"\n\nNonLocalAttrRef(s)\t\t ::= <%((<s.ruleName; format=\"cap\">Context)GetInvokingContext(<s.ruleIndex>)).<s.escapedName>%>\nSetNonLocalAttr(s, rhsChunks)\t  ::=\n\t<%((<s.ruleName; format=\"cap\">Context)GetInvokingContext(<s.ruleIndex>)).<s.escapedName> = <rhsChunks>;%>\n\nAddToLabelList(a) ::= \"<ctx(a.label)>.<a.listName>.Add(<labelref(a.label)>);\"\n\nTokenDecl(t) ::= \"<TokenLabelType()> <tokenType.(t.escapedName)>\"\nTokenTypeDecl(t) ::= \"int <tokenType.(t.escapedName)>;\"\nTokenListDecl(t) ::= \"IList\\<IToken> <tokenType.(t.escapedName)> = new List\\<IToken>()\"\nRuleContextDecl(r) ::= \"<r.ctxName> <r.escapedName>\"\nRuleContextListDecl(rdecl) ::= \"IList\\<<rdecl.ctxName>> <rdecl.escapedName> = new List\\<<rdecl.ctxName>>()\"\n\ncontextGetterCollection(elementType) ::= <%\n<elementType>[]\n%>\n\nContextTokenGetterDecl(t)      ::=\n    \"[System.Diagnostics.DebuggerNonUserCode] public ITerminalNode <tokenType.(t.name)>() { return GetToken(<parser.name>.<tokenType.(t.name)>, 0); }\"\nContextTokenListGetterDecl(t)  ::= <<\n[System.Diagnostics.DebuggerNonUserCode] public <contextGetterCollection(\"ITerminalNode\")> <tokenType.(t.name)>() { return GetTokens(<parser.name>.<tokenType.(t.name)>); }\n>>\nContextTokenListIndexedGetterDecl(t)  ::= <<\n[System.Diagnostics.DebuggerNonUserCode] public ITerminalNode <tokenType.(t.name)>(int i) {\n\treturn GetToken(<parser.name>.<tokenType.(t.name)>, i);\n}\n>>\nContextRuleGetterDecl(r)       ::= <<\n[System.Diagnostics.DebuggerNonUserCode] public <r.ctxName> <r.escapedName>() {\n\treturn GetRuleContext\\<<r.ctxName>\\>(0);\n}\n>>\nContextRuleListGetterDecl(r)   ::= <<\n[System.Diagnostics.DebuggerNonUserCode] public <contextGetterCollection({<r.ctxName>})> <r.escapedName>() {\n\treturn GetRuleContexts\\<<r.ctxName>\\>();\n}\n>>\nContextRuleListIndexedGetterDecl(r)   ::= <<\n[System.Diagnostics.DebuggerNonUserCode] public <r.ctxName> <r.escapedName>(int i) {\n\treturn GetRuleContext\\<<r.ctxName>\\>(i);\n}\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/** The rule context name is the rule followed by a suffix; e.g.,\n *\tr becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"_<tokenType.(tokenName)>\"\nImplicitRuleLabel(ruleName)\t  ::= \"_<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"_<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = TokenStream.LT(1);\"\nCaptureNextTokenType(d) ::= \"<d.varName> = TokenStream.LA(1);\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures,\n           superClass={ParserRuleContext}) ::= <<\npublic partial class <struct.escapedName> : <if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif><if(interfaces)>, <interfaces; separator=\", \"><endif> {\n\t<attrs:{a | public <a>;}; separator=\"\\n\">\n\t<getters:{g | <g>}; separator=\"\\n\">\n\t<if(ctorAttrs)>public <struct.escapedName>(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { }<endif>\n\tpublic <struct.escapedName>(ParserRuleContext parent, int invokingState<ctorAttrs:{a | , <a>}>)\n\t\t: base(parent, invokingState)\n\t{\n\t\t<struct.ctorAttrs:{a | this.<a.escapedName> = <a.escapedName>;}; separator=\"\\n\">\n\t}\n\tpublic override int RuleIndex { get { return RULE_<struct.derivedFromName>; } }\n<if(struct.provideCopyFrom)> <! don't need copy unless we have subclasses !>\n\tpublic <struct.escapedName>() { }\n\tpublic virtual void CopyFrom(<struct.escapedName> context) {\n\t\tbase.CopyFrom(context);\n\t\t<struct.attrs:{a | this.<a.escapedName> = context.<a.escapedName>;}; separator=\"\\n\">\n\t}\n<endif>\n\t<dispatchMethods; separator=\"\\n\">\n\t<extensionMembers; separator=\"\\n\">\n}\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\npublic partial class <struct.escapedName> : <currentRule.name; format=\"cap\">Context {\n\t<attrs:{a | public <a>;}; separator=\"\\n\">\n\t<getters:{g | <g>}; separator=\"\\n\">\n\tpublic <struct.escapedName>(<currentRule.name; format=\"cap\">Context context) { CopyFrom(context); }\n\t<dispatchMethods; separator=\"\\n\">\n}\n>>\n\nListenerDispatchMethod(method) ::= <<\n[System.Diagnostics.DebuggerNonUserCode]\npublic override void <if(method.isEnter)>Enter<else>Exit<endif>Rule(IParseTreeListener listener) {\n\tI<parser.grammarName>Listener typedListener = listener as I<parser.grammarName>Listener;\n\tif (typedListener != null) typedListener.<if(method.isEnter)>Enter<else>Exit<endif><struct.derivedFromName; format=\"cap\">(this);\n}\n>>\n\nVisitorDispatchMethod(method) ::= <<\n[System.Diagnostics.DebuggerNonUserCode]\npublic override TResult Accept\\<TResult>(IParseTreeVisitor\\<TResult> visitor) {\n\tI<parser.grammarName>Visitor\\<TResult> typedVisitor = visitor as I<parser.grammarName>Visitor\\<TResult>;\n\tif (typedVisitor != null) return typedVisitor.Visit<struct.derivedFromName; format=\"cap\">(this);\n\telse return visitor.VisitChildren(this);\n}\n>>\n\nAttributeDecl(d) ::= \"<d.type> <d.escapedName><if(d.initValue)> = <d.initValue><endif>\"\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if(!x.isLocal)><typedContext(x.ctx)>.<endif><x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"<typedContext(actionChunk.ctx)>\"\n\n// only casts _localctx to the type when the cast isn't redundant (i.e. to a sub-context for a labeled alt)\ntypedContext(ctx) ::= \"<if(ctx.provideCopyFrom)>((<ctx.name>)_localctx)<else>_localctx<endif>\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"Precpred(Context, <opPrec>)\"\nrecRuleSetReturnAction(src,name)\t  ::= \"$<name>=$<src>.<name>;\"\nrecRuleSetStopToken()                 ::= \"Context.Stop = TokenStream.LT(-1);\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\n_localctx = new <ctxName>Context(_parentctx, _parentState);\n<if(label)>\n<if(isListLabel)>\n_localctx.<label>.Add(_prevctx);\n<else>\n_localctx.<label> = _prevctx;\n<endif>\n<endif>\nPushNewRecursionContext(_localctx, _startState, RULE_<ruleName>);\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\n_localctx = new <currentAltLabel; format=\"cap\">Context(new <ruleName; format=\"cap\">Context(_parentctx, _parentState));\n<if(label)>\n<if(isListLabel)>\n((<currentAltLabel; format=\"cap\">Context)_localctx).<label>.Add(_prevctx);\n<else>\n((<currentAltLabel; format=\"cap\">Context)_localctx).<label> = _prevctx;\n<endif>\n<endif>\nPushNewRecursionContext(_localctx, _startState, RULE_<ruleName>);\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\n_localctx = new <ctxName>Context(_localctx);\nContext = _localctx;\n_prevctx = _localctx;\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif ( ParseListeners!=null )\n\tTriggerExitRuleEvent();\n_prevctx = _localctx;\n>>\n\n\nLexerFile(file, lexer, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n<namedActions.header>\nusing System;\nusing System.IO;\nusing System.Text;\nusing Antlr4.Runtime;\nusing Antlr4.Runtime.Atn;\nusing Antlr4.Runtime.Misc;\nusing DFA = Antlr4.Runtime.Dfa.DFA;\n\n<lexer>\n<if(file.genPackage)>\n} // namespace <file.genPackage>\n<endif>\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\n[System.CodeDom.Compiler.GeneratedCode(\"ANTLR\", \"<file.ANTLRVersion>\")]\n[System.CLSCompliant(false)]\npublic partial class <lexer.name> : <superClass; null=\"Lexer\"> {\n\tprotected static DFA[] decisionToDFA;\n\tprotected static PredictionContextCache sharedContextCache = new PredictionContextCache();\n\t<if(lexer.tokens)>\n\tpublic const int\n\t\t<lexer.tokens:{k | <tokenType.(k)>=<lexer.tokens.(k)>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\t<if(lexer.escapedChannels)>\n\tpublic const int\n\t\t<lexer.escapedChannels:{k | <k>=<lexer.escapedChannels.(k)>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\t<if(rest(lexer.escapedModeNames))>\n\tpublic const int\n\t\t<rest(lexer.escapedModeNames):{m | <m>=<i>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\tpublic static string[] channelNames = {\n\t\t\"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"<if (lexer.channelNames)>, <lexer.channelNames:{c| \"<c>\"}; separator=\", \", wrap, anchor><endif>\n\t};\n\n\tpublic static string[] modeNames = {\n\t\t<lexer.modes:{m| \"<m>\"}; separator=\", \", wrap, anchor>\n\t};\n\n\tpublic static readonly string[] ruleNames = {\n\t\t<lexer.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor>\n\t};\n\n\t<namedActions.members>\n\n\tpublic <lexer.name>(ICharStream input)\n\t: this(input, Console.Out, Console.Error) { }\n\n\tpublic <lexer.name>(ICharStream input, TextWriter output, TextWriter errorOutput)\n\t: base(input, output, errorOutput)\n\t{\n\t\tInterpreter = new LexerATNSimulator(this, _ATN, decisionToDFA, sharedContextCache);\n\t}\n\n\t<vocabulary(lexer.literalNames, lexer.symbolicNames)>\n\n\tpublic override string GrammarFileName { get { return \"<lexer.grammarFileName>\"; } }\n\n\tpublic override string[] RuleNames { get { return ruleNames; } }\n\n\tpublic override string[] ChannelNames { get { return channelNames; } }\n\n\tpublic override string[] ModeNames { get { return modeNames; } }\n\n\tpublic override int[] SerializedAtn { get { return _serializedATN; } }\n\n\tstatic <lexer.name>() {\n\t\tdecisionToDFA = new DFA[_ATN.NumberOfDecisions];\n\t\tfor (int i = 0; i \\< _ATN.NumberOfDecisions; i++) {\n\t\t\tdecisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i);\n\t\t}\n\t}\n\t<dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n\t<atn>\n}\n>>\n\nSerializedATN(model) ::= <<\nprivate static int[] _serializedATN = {\n\t<model.serialized: {s | <s>}; separator=\",\", wrap>\n};\n\npublic static readonly ATN _ATN =\n\tnew ATNDeserializer().Deserialize(_serializedATN);\n\n\n>>\n\ninitValue(typeName) ::= <<\ndefault(<typeName>)\n>>\n\ncodeFileExtension() ::= \".cs\"\n\nmodeName ::= [\n\t\"DEFAULT_MODE\" : \"DefaultMode\",\n\tdefault : key\n]\n\nchannelName ::= [\n\t\"HIDDEN\" : \"Hidden\",\n\t\"DEFAULT_TOKEN_CHANNEL\" : \"DefaultTokenChannel\",\n\tdefault : key\n]\n\ntokenType ::= [\n\t\"EOF\" : \"Eof\",\n\tdefault : key\n]\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/Cpp/Cpp.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2015 Dan McLaughlin, Mike Lischke\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport \"Files.stg\" // All file specific stuff.\n\ncppTypeInitMap ::= [\n    \"int\":\"0\",\n    \"long\":\"0\",\n    \"float\":\"0.0f\",\n    \"double\":\"0.0\",\n    \"bool\":\"false\",\n    \"short\":\"0\",\n    \"char\":\"0\",\n    default: \"nullptr\" // anything other than a primitive type is an object\n]\n\nLexerHeader(lexer, atn, actionFuncs, sempredFuncs, superClass = {antlr4::Lexer}) ::= <<\n<namedActions.context>\n\nclass <file.exportMacro> <lexer.name> : public <superClass> {\npublic:\n<if (lexer.tokens)>\n  enum {\n    <lexer.tokens: {k | <k> = <lexer.tokens.(k)>}; separator=\", \", wrap, anchor>\n  };\n<endif>\n\n<if (lexer.escapedChannels)>\n  enum {\n    <lexer.escapedChannels: {k | <k> = <lexer.escapedChannels.(k)>}; separator=\", \", wrap, anchor>\n  };\n<endif>\n\n<if (rest(lexer.escapedModeNames))>\n  enum {\n    <rest(lexer.escapedModeNames): {m | <m> = <i>}; separator=\", \", wrap, anchor>\n  };\n<endif>\n\n  explicit <lexer.name>(antlr4::CharStream *input);\n\n  ~<lexer.name>() override;\n\n  <namedActions.members>\n\n  std::string getGrammarFileName() const override;\n\n  const std::vector\\<std::string>& getRuleNames() const override;\n\n  const std::vector\\<std::string>& getChannelNames() const override;\n\n  const std::vector\\<std::string>& getModeNames() const override;\n\n  const antlr4::dfa::Vocabulary& getVocabulary() const override;\n\n  antlr4::atn::SerializedATNView getSerializedATN() const override;\n\n  const antlr4::atn::ATN& getATN() const override;\n\n  <if (actionFuncs)>\n  void action(antlr4::RuleContext *context, size_t ruleIndex, size_t actionIndex) override;\n  <endif>\n\n  <if (sempredFuncs)>\n  bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex, size_t predicateIndex) override;\n  <endif>\n\n  // By default the static state used to implement the lexer is lazily initialized during the first\n  // call to the constructor. You can call this function if you wish to initialize the static state\n  // ahead of time.\n  static void initialize();\n\nprivate:\n  <namedActions.declarations>\n\n  // Individual action functions triggered by action() above.\n  <actionFuncs.values; separator=\"\\n\">\n\n  // Individual semantic predicate functions triggered by sempred() above.\n  <sempredFuncs.values; separator=\"\\n\">\n\n  <atn>\n};\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass = {Lexer}) ::= <<\n\nusing namespace antlr4;\n\nnamespace {\n\nstruct <lexer.name; format = \"cap\">StaticData final {\n  <lexer.name; format = \"cap\">StaticData(std::vector\\<std::string> ruleNames,\n                          std::vector\\<std::string> channelNames,\n                          std::vector\\<std::string> modeNames,\n                          std::vector\\<std::string> literalNames,\n                          std::vector\\<std::string> symbolicNames)\n      : ruleNames(std::move(ruleNames)), channelNames(std::move(channelNames)),\n        modeNames(std::move(modeNames)), literalNames(std::move(literalNames)),\n        symbolicNames(std::move(symbolicNames)),\n        vocabulary(this->literalNames, this->symbolicNames) {}\n\n  <lexer.name; format = \"cap\">StaticData(const <lexer.name; format = \"cap\">StaticData&) = delete;\n  <lexer.name; format = \"cap\">StaticData(<lexer.name; format = \"cap\">StaticData&&) = delete;\n  <lexer.name; format = \"cap\">StaticData& operator=(const <lexer.name; format = \"cap\">StaticData&) = delete;\n  <lexer.name; format = \"cap\">StaticData& operator=(<lexer.name; format = \"cap\">StaticData&&) = delete;\n\n  std::vector\\<antlr4::dfa::DFA> decisionToDFA;\n  antlr4::atn::PredictionContextCache sharedContextCache;\n  const std::vector\\<std::string> ruleNames;\n  const std::vector\\<std::string> channelNames;\n  const std::vector\\<std::string> modeNames;\n  const std::vector\\<std::string> literalNames;\n  const std::vector\\<std::string> symbolicNames;\n  const antlr4::dfa::Vocabulary vocabulary;\n  antlr4::atn::SerializedATNView serializedATN;\n  std::unique_ptr\\<antlr4::atn::ATN> atn;\n};\n\n::antlr4::internal::OnceFlag <lexer.grammarName; format = \"lower\">LexerOnceFlag;\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\nstatic thread_local\n#endif\nstd::unique_ptr\\<<lexer.name; format = \"cap\">StaticData> <lexer.grammarName; format = \"lower\">LexerStaticData = nullptr;\n\nvoid <lexer.grammarName; format = \"lower\">LexerInitialize() {\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\n  if (<lexer.grammarName; format = \"lower\">LexerStaticData != nullptr) {\n    return;\n  }\n#else\n  assert(<lexer.grammarName; format = \"lower\">LexerStaticData == nullptr);\n#endif\n  auto staticData = std::make_unique\\<<lexer.name; format = \"cap\">StaticData>(\n    std::vector\\<std::string>{\n      <lexer.ruleNames: {r | \"<r>\"}; separator = \", \", wrap, anchor>\n    },\n    std::vector\\<std::string>{\n      \"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"<if (lexer.channels)>, <lexer.channels: {c | \"<c>\"}; separator = \", \", wrap, anchor><endif>\n    },\n    std::vector\\<std::string>{\n      <lexer.modes: {m | \"<m>\"}; separator = \", \", wrap, anchor>\n    },\n    std::vector\\<std::string>{\n      <lexer.literalNames: {t | <t>}; null = \"\\\"\\\"\", separator = \", \", wrap, anchor>\n    },\n    std::vector\\<std::string>{\n      <lexer.symbolicNames: {t | <t>}; null = \"\\\"\\\"\", separator = \", \", wrap, anchor>\n    }\n  );\n  <atn>\n  <lexer.grammarName; format = \"lower\">LexerStaticData = std::move(staticData);\n}\n\n}\n\n<lexer.name>::<lexer.name>(CharStream *input) : <superClass>(input) {\n  <lexer.name>::initialize();\n  _interpreter = new atn::LexerATNSimulator(this, *<lexer.grammarName; format = \"lower\">LexerStaticData->atn, <lexer.grammarName; format = \"lower\">LexerStaticData->decisionToDFA, <lexer.grammarName; format = \"lower\">LexerStaticData->sharedContextCache);\n}\n\n<lexer.name>::~<lexer.name>() {\n  delete _interpreter;\n}\n\nstd::string <lexer.name>::getGrammarFileName() const {\n  return \"<lexer.grammarFileName>\";\n}\n\nconst std::vector\\<std::string>& <lexer.name>::getRuleNames() const {\n  return <lexer.grammarName; format = \"lower\">LexerStaticData->ruleNames;\n}\n\nconst std::vector\\<std::string>& <lexer.name>::getChannelNames() const {\n  return <lexer.grammarName; format = \"lower\">LexerStaticData->channelNames;\n}\n\nconst std::vector\\<std::string>& <lexer.name>::getModeNames() const {\n  return <lexer.grammarName; format = \"lower\">LexerStaticData->modeNames;\n}\n\nconst dfa::Vocabulary& <lexer.name>::getVocabulary() const {\n  return <lexer.grammarName; format = \"lower\">LexerStaticData->vocabulary;\n}\n\nantlr4::atn::SerializedATNView <lexer.name>::getSerializedATN() const {\n  return <lexer.grammarName; format = \"lower\">LexerStaticData->serializedATN;\n}\n\nconst atn::ATN& <lexer.name>::getATN() const {\n  return *<lexer.grammarName; format = \"lower\">LexerStaticData->atn;\n}\n\n<namedActions.definitions>\n\n<if (actionFuncs)>\nvoid <lexer.name>::action(RuleContext *context, size_t ruleIndex, size_t actionIndex) {\n  switch (ruleIndex) {\n    <lexer.actionFuncs.values: {f | case <f.ruleIndex>: <f.name>Action(antlrcpp::downCast\\<<f.ctxType> *>(context), actionIndex); break;}; separator=\"\\n\">\n\n  default:\n    break;\n  }\n}\n<endif>\n\n<if (sempredFuncs)>\nbool <lexer.name>::sempred(RuleContext *context, size_t ruleIndex, size_t predicateIndex) {\n  switch (ruleIndex) {\n    <lexer.sempredFuncs.values: {f | case <f.ruleIndex>: return <f.name>Sempred(antlrcpp::downCast\\<<f.ctxType> *>(context), predicateIndex);}; separator=\"\\n\">\n\n  default:\n    break;\n  }\n  return true;\n}\n<endif>\n\n<actionFuncs.values; separator=\"\\n\">\n\n<sempredFuncs.values; separator=\"\\n\">\n\nvoid <lexer.name>::initialize() {\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\n  <lexer.grammarName; format = \"lower\">LexerInitialize();\n#else\n  ::antlr4::internal::call_once(<lexer.grammarName; format = \"lower\">LexerOnceFlag, <lexer.grammarName; format = \"lower\">LexerInitialize);\n#endif\n}\n>>\n\nRuleActionFunctionHeader(r, actions) ::= <<\nvoid <r.name>Action(<r.ctxType> *context, size_t actionIndex);\n>>\n\nRuleActionFunction(r, actions) ::= <<\nvoid <r.factory.grammar.name>::<r.name>Action(<r.ctxType> *context, size_t actionIndex) {\n  switch (actionIndex) {\n    <actions: {index | case <index>: <actions.(index)> break;}; separator=\"\\n\">\n\n  default:\n    break;\n  }\n}\n\n>>\n\nRuleSempredFunctionHeader(r, actions) ::= <<\nbool <r.name>Sempred(<r.ctxType> *_localctx, size_t predicateIndex);\n>>\n\nRuleSempredFunction(r, actions) ::= <<\n<! Called for both lexer and parser. But only one of them is actually available. Testing for the parser directly\n   generates a warning, however. So do the check via the factory instead. !>\nbool <if (r.factory.g.lexer)><lexer.name><else><parser.name><endif>::<r.name>Sempred(<r.ctxType> *_localctx, size_t predicateIndex) {\n  switch (predicateIndex) {\n    <actions: {index | case <index>: return <actions.(index)>}; separator=\";\\n\">;\n\n  default:\n    break;\n  }\n  return true;\n}\n\n>>\n\n//--------------------------------------------------------------------------------------------------\n\nParserHeader(parser, funcs, atn, sempredFuncs, superClass = {antlr4::Parser}) ::= <<\n<namedActions.context>\n\nclass <file.exportMacro> <parser.name> : public <superClass> {\npublic:\n<if (parser.tokens)>\n  enum {\n    <parser.tokens: {k | <k> = <parser.tokens.(k)>}; separator=\", \", wrap, anchor>\n  };\n<endif>\n\n<if (parser.rules)>\n  enum {\n    <parser.rules: {r | Rule<r.name; format=\"cap\"> = <r.index>}; separator=\", \", wrap, anchor>\n  };\n<endif>\n\n  explicit <parser.name>(antlr4::TokenStream *input);\n\n  <parser.name>(antlr4::TokenStream *input, const antlr4::atn::ParserATNSimulatorOptions &options);\n\n  ~<parser.name>() override;\n\n  std::string getGrammarFileName() const override;\n\n  const antlr4::atn::ATN& getATN() const override;\n\n  const std::vector\\<std::string>& getRuleNames() const override;\n\n  const antlr4::dfa::Vocabulary& getVocabulary() const override;\n\n  antlr4::atn::SerializedATNView getSerializedATN() const override;\n\n  <namedActions.members>\n\n  <parser.funcs: {f | class <f.name; format = \"cap\">Context;};  separator = \"\\n\"> <! Forward declare context classes. !>\n\n  <funcs; separator = \"\\n\">\n\n  <if (sempredFuncs)>\n  bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex, size_t predicateIndex) override;\n\n  <sempredFuncs.values; separator = \"\\n\">\n  <endif>\n\n  // By default the static state used to implement the parser is lazily initialized during the first\n  // call to the constructor. You can call this function if you wish to initialize the static state\n  // ahead of time.\n  static void initialize();\n\nprivate:\n  <namedActions.declarations>\n};\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass = {Parser}) ::= <<\n\nusing namespace antlr4;\n\nnamespace {\n\nstruct <parser.name; format = \"cap\">StaticData final {\n  <parser.name; format = \"cap\">StaticData(std::vector\\<std::string> ruleNames,\n                        std::vector\\<std::string> literalNames,\n                        std::vector\\<std::string> symbolicNames)\n      : ruleNames(std::move(ruleNames)), literalNames(std::move(literalNames)),\n        symbolicNames(std::move(symbolicNames)),\n        vocabulary(this->literalNames, this->symbolicNames) {}\n\n  <parser.name; format = \"cap\">StaticData(const <parser.name; format = \"cap\">StaticData&) = delete;\n  <parser.name; format = \"cap\">StaticData(<parser.name; format = \"cap\">StaticData&&) = delete;\n  <parser.name; format = \"cap\">StaticData& operator=(const <parser.name; format = \"cap\">StaticData&) = delete;\n  <parser.name; format = \"cap\">StaticData& operator=(<parser.name; format = \"cap\">StaticData&&) = delete;\n\n  std::vector\\<antlr4::dfa::DFA> decisionToDFA;\n  antlr4::atn::PredictionContextCache sharedContextCache;\n  const std::vector\\<std::string> ruleNames;\n  const std::vector\\<std::string> literalNames;\n  const std::vector\\<std::string> symbolicNames;\n  const antlr4::dfa::Vocabulary vocabulary;\n  antlr4::atn::SerializedATNView serializedATN;\n  std::unique_ptr\\<antlr4::atn::ATN> atn;\n};\n\n::antlr4::internal::OnceFlag <parser.grammarName; format = \"lower\">ParserOnceFlag;\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\nstatic thread_local\n#endif\nstd::unique_ptr\\<<parser.name; format = \"cap\">StaticData> <parser.grammarName; format = \"lower\">ParserStaticData = nullptr;\n\nvoid <parser.grammarName; format = \"lower\">ParserInitialize() {\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\n  if (<parser.grammarName; format = \"lower\">ParserStaticData != nullptr) {\n    return;\n  }\n#else\n  assert(<parser.grammarName; format = \"lower\">ParserStaticData == nullptr);\n#endif\n  auto staticData = std::make_unique\\<<parser.name; format = \"cap\">StaticData>(\n    std::vector\\<std::string>{\n      <parser.ruleNames: {r | \"<r>\"}; separator = \", \", wrap, anchor>\n    },\n    std::vector\\<std::string>{\n      <parser.literalNames: {t | <t>}; null = \"\\\"\\\"\", separator = \", \", wrap, anchor>\n    },\n    std::vector\\<std::string>{\n      <parser.symbolicNames: {t | <t>}; null = \"\\\"\\\"\", separator = \", \", wrap, anchor>\n    }\n  );\n  <atn>\n  <parser.grammarName; format = \"lower\">ParserStaticData = std::move(staticData);\n}\n\n}\n\n<parser.name>::<parser.name>(TokenStream *input) : <parser.name>(input, antlr4::atn::ParserATNSimulatorOptions()) {}\n\n<parser.name>::<parser.name>(TokenStream *input, const antlr4::atn::ParserATNSimulatorOptions &options) : <superClass>(input) {\n  <parser.name>::initialize();\n  _interpreter = new atn::ParserATNSimulator(this, *<parser.grammarName; format = \"lower\">ParserStaticData->atn, <parser.grammarName; format = \"lower\">ParserStaticData->decisionToDFA, <parser.grammarName; format = \"lower\">ParserStaticData->sharedContextCache, options);\n}\n\n<parser.name>::~<parser.name>() {\n  delete _interpreter;\n}\n\nconst atn::ATN& <parser.name>::getATN() const {\n  return *<parser.grammarName; format = \"lower\">ParserStaticData->atn;\n}\n\nstd::string <parser.name>::getGrammarFileName() const {\n  return \"<parser.grammarFileName>\";\n}\n\nconst std::vector\\<std::string>& <parser.name>::getRuleNames() const {\n  return <parser.grammarName; format = \"lower\">ParserStaticData->ruleNames;\n}\n\nconst dfa::Vocabulary& <parser.name>::getVocabulary() const {\n  return <parser.grammarName; format = \"lower\">ParserStaticData->vocabulary;\n}\n\nantlr4::atn::SerializedATNView <parser.name>::getSerializedATN() const {\n  return <parser.grammarName; format = \"lower\">ParserStaticData->serializedATN;\n}\n\n<namedActions.definitions>\n\n<funcs; separator = \"\\n\\n\">\n\n<if (sempredFuncs)>\nbool <parser.name>::sempred(RuleContext *context, size_t ruleIndex, size_t predicateIndex) {\n  switch (ruleIndex) {\n  <parser.sempredFuncs.values: {f |\n  case <f.ruleIndex>: return <f.name>Sempred(antlrcpp::downCast\\<<f.ctxType> *>(context), predicateIndex);}; separator=\"\\n\">\n\n  default:\n    break;\n  }\n  return true;\n}\n\n<sempredFuncs.values; separator=\"\\n\"><endif>\n\nvoid <parser.name>::initialize() {\n#if ANTLR4_USE_THREAD_LOCAL_CACHE\n  <parser.grammarName; format = \"lower\">ParserInitialize();\n#else\n  ::antlr4::internal::call_once(<parser.grammarName; format = \"lower\">ParserOnceFlag, <parser.grammarName; format = \"lower\">ParserInitialize);\n#endif\n}\n>>\n\nSerializedATNHeader(model) ::= <<\n>>\n\nSerializedATN(model) ::= <<\nstatic const int32_t serializedATNSegment[] = {\n\t<model.serialized: {s | <s>}; separator=\",\", wrap>\n};\nstaticData->serializedATN = antlr4::atn::SerializedATNView(serializedATNSegment, sizeof(serializedATNSegment) / sizeof(serializedATNSegment[0]));\n\nantlr4::atn::ATNDeserializer deserializer;\nstaticData->atn = deserializer.deserialize(staticData->serializedATN);\n\nconst size_t count = staticData->atn->getNumberOfDecisions();\nstaticData->decisionToDFA.reserve(count);\nfor (size_t i = 0; i \\< count; i++) { <! Rework class ATN to allow standard iterations. !>\n  staticData->decisionToDFA.emplace_back(staticData->atn->getDecisionState(i), i);\n}\n>>\n\nRuleFunctionHeader(currentRule, args, code, locals, ruleCtx, altLabelCtxs, namedActions, finallyAction, postamble, exceptions) ::= <<\n<ruleCtx>\n<! TODO: untested !><if (altLabelCtxs)><altLabelCtxs: {l | <altLabelCtxs.(l)>}; separator=\"\\n\"><endif>\n<currentRule.ctxType>* <currentRule.escapedName>(<args; separator=\",\">);\n\n>>\n\nRuleFunction(currentRule, args, code, locals, ruleCtx, altLabelCtxs, namedActions, finallyAction, postamble, exceptions) ::= <<\n<ruleCtx>\n<! TODO: untested !><altLabelCtxs: {l | <altLabelCtxs.(l)>}; separator = \"\\n\">\n<parser.name>::<currentRule.ctxType>* <parser.name>::<currentRule.escapedName>(<args; separator=\",\">) {\n  <currentRule.ctxType> *_localctx = _tracker.createInstance\\<<currentRule.ctxType>\\>(_ctx, getState()<currentRule.args:{a | , <a.escapedName>}>);\n  enterRule(_localctx, <currentRule.startState>, <parser.name>::Rule<currentRule.name; format = \"cap\">);\n  <namedActions.init>\n  <locals; separator = \"\\n\">\n\n#if __cplusplus > 201703L\n  auto onExit = finally([=, this] {\n#else\n  auto onExit = finally([=] {\n#endif\n  <finallyAction>\n    exitRule();\n  });\n  try {\n<! TODO: untested !><if (currentRule.hasLookaheadBlock)>\n    size_t alt;\n    <endif>\n    <code>\n<! TODO: untested !>   <postamble; separator = \"\\n\">\n    <namedActions.after>\n  }\n  <if (exceptions)>\n  <exceptions; separator=\"\\n\">\n  <else>\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n  <endif>\n\n  return _localctx;\n}\n>>\n\nLeftRecursiveRuleFunctionHeader(currentRule, args, code, locals, ruleCtx, altLabelCtxs, namedActions, finallyAction, postamble) ::= <<\n<ruleCtx>\n<! TODO: untested !><altLabelCtxs: {l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n<currentRule.ctxType>* <currentRule.escapedName>(<currentRule.args; separator = \", \">);\n<currentRule.ctxType>* <currentRule.escapedName>(int precedence<currentRule.args: {a | , <a>}>);\n>>\n\nLeftRecursiveRuleFunction(currentRule, args, code, locals, ruleCtx, altLabelCtxs, namedActions, finallyAction, postamble) ::= <<\n<ruleCtx>\n<altLabelCtxs: {l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n\n<parser.name>::<currentRule.ctxType>* <parser.name>::<currentRule.escapedName>(<currentRule.args; separator=\", \">) {\n<! TODO: currentRule.args untested !>   return <currentRule.escapedName>(0<currentRule.args: {a | , <a.escapedName>}>);\n}\n\n<parser.name>::<currentRule.ctxType>* <parser.name>::<currentRule.escapedName>(int precedence<currentRule.args:{a | , <a>}>) {\n  ParserRuleContext *parentContext = _ctx;\n  size_t parentState = getState();\n  <parser.name>::<currentRule.ctxType> *_localctx = _tracker.createInstance\\<<currentRule.ctxType>\\>(_ctx, parentState<currentRule.args: {a | , <a.escapedName>}>);\n  <parser.name>::<currentRule.ctxType> *previousContext = _localctx;\n  (void)previousContext; // Silence compiler, in case the context is not used by generated code.\n  size_t startState = <currentRule.startState>;\n  enterRecursionRule(_localctx, <currentRule.startState>, <parser.name>::Rule<currentRule.name; format = \"cap\">, precedence);\n\n    <namedActions.init>\n<! TODO: untested !>    <locals; separator = \"\\n\">\n\n#if __cplusplus > 201703L\n  auto onExit = finally([=, this] {\n#else\n  auto onExit = finally([=] {\n#endif\n  <if (finallyAction)><finallyAction><endif>\n    unrollRecursionContexts(parentContext);\n  });\n  try {\n    <if (currentRule.hasLookaheadBlock)>size_t alt;<endif>\n    <code>\n<! TODO: untested !><postamble; separator = \"\\n\">\n    <namedActions.after>\n  }\n  catch (RecognitionException &e) {\n    _errHandler->reportError(this, e);\n    _localctx->exception = std::current_exception();\n    _errHandler->recover(this, _localctx->exception);\n  }\n  return _localctx;\n}\n>>\n\nStructDeclHeader(struct, ctorAttrs, attrs, getters, dispatchMethods, interfaces, extensionMembers) ::= <<\nclass <file.exportMacro> <struct.escapedName> : public <if (contextSuperClass)><contextSuperClass><else>antlr4::ParserRuleContext<endif><if(interfaces)>, <interfaces; separator=\", \"><endif> {\npublic:\n  <attrs: {a | <a>;}; separator = \"\\n\">\n  <if (ctorAttrs)><struct.escapedName>(antlr4::ParserRuleContext *parent, size_t invokingState);<endif>\n  <struct.escapedName>(antlr4::ParserRuleContext *parent, size_t invokingState<ctorAttrs: {a | , <a>}>);\n<if (struct.provideCopyFrom)> <! don't need copy unless we have subclasses !>\n  <struct.escapedName>() = default;\n  void copyFrom(<struct.escapedName> *context);\n  using antlr4::ParserRuleContext::copyFrom;\n<endif>\n\n  virtual size_t getRuleIndex() const override;\n  <getters: {g | <g>}; separator = \"\\n\">\n\n  <dispatchMethods; separator = \"\\n\">\n<! TODO: untested !> <extensionMembers; separator = \"\\n\">\n};\n\n>>\n\nStructDecl(struct, ctorAttrs, attrs, getters, dispatchMethods, interfaces, extensionMembers, signatures) ::= <<\n//----------------- <struct.escapedName> ------------------------------------------------------------------\n\n<if (ctorAttrs)>\n<parser.name>::<struct.escapedName>::<struct.escapedName>(ParserRuleContext *parent, size_t invokingState)\n  : <if (contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif>(parent, invokingState) {\n}\n<endif>\n\n<parser.name>::<struct.escapedName>::<struct.escapedName>(ParserRuleContext *parent, size_t invokingState<ctorAttrs: {a | , <a>}>)\n  : <if (contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif>(parent, invokingState) {\n  <struct.ctorAttrs: {a | this-><a.escapedName> = <a.escapedName>;}; separator=\"\\n\">\n}\n\n<getters: {g | <g>}; separator = \"\\n\">\n\nsize_t <parser.name>::<struct.escapedName>::getRuleIndex() const {\n  return <parser.name>::Rule<struct.derivedFromName; format = \"cap\">;\n}\n\n<if (struct.provideCopyFrom)>\nvoid <parser.name>::<struct.escapedName>::copyFrom(<struct.escapedName> *ctx) {\n  <if (contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif>::copyFrom(ctx);\n  <struct.attrs: {a | this-><a.escapedName> = ctx-><a.escapedName>;}; separator = \"\\n\">\n}\n<endif>\n<dispatchMethods; separator = \"\\n\\n\">\n<! TODO: untested !><extensionMembers; separator = \"\\n\\n\">\n\n>>\n\nAltLabelStructDeclHeader(struct, attrs, getters, dispatchMethods) ::= <<\nclass <file.exportMacro> <struct.escapedName> : public <currentRule.name; format = \"cap\">Context {\npublic:\n  <struct.escapedName>(<currentRule.name; format = \"cap\">Context *ctx);\n\n  <if (attrs)><attrs: {a | <a>;}; separator = \"\\n\"><endif>\n  <getters: {g | <g>}; separator = \"\\n\">\n  <dispatchMethods; separator = \"\\n\">\n};\n\n>>\n\nAltLabelStructDecl(struct, attrs, getters, dispatchMethods) ::= <<\n//----------------- <struct.escapedName> ------------------------------------------------------------------\n\n<! TODO: untested !><if (attrs)><attrs: {a | <a>}; separator = \"\\n\"><endif>\n<getters: {g | <g>}; separator = \"\\n\">\n<parser.name>::<struct.escapedName>::<struct.escapedName>(<currentRule.name; format = \"cap\">Context *ctx) { copyFrom(ctx); }\n\n<dispatchMethods; separator=\"\\n\">\n>>\n\n\nCodeBlockForOuterMostAltHeader(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= \"<! Required to exist, but unused. !>\"\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if (currentOuterMostAltCodeBlock.altLabel)>\n_localctx = _tracker.createInstance\\<<parser.name>::<currentOuterMostAltCodeBlock.altLabel; format = \"cap\">Context>(_localctx);\n<endif>\nenterOuterAlt(_localctx, <currentOuterMostAltCodeBlock.alt.altNum>);\n<CodeBlockForAlt(currentAltCodeBlock = currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAltHeader(currentAltCodeBlock, locals, preamble, ops) ::= \"<! Required to exist, but unused. !>\"\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<! TODO: untested !><locals; separator = \"\\n\">\n<! TODO: untested !><preamble; separator = \"\\n\">\n<ops; separator = \"\\n\">\n>>\n\nLL1AltBlockHeader(choice, preamble, alts, error) ::= \"<! Required to exist, but unused. !>\"\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler->sync(this);\n<! TODO: untested !><if (choice.label)>LL1AltBlock(choice, preamble, alts, error) <labelref(choice.label)> = _input->LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch (_input->LA(1)) {\n  <choice.altLook, alts: {look, alt | <cases(tokens = look)> {\n  <alt>\n  break;\n\\}\n}; separator = \"\\n\">\ndefault:\n  <error>\n}\n>>\n\nLL1OptionalBlockHeader(choice, alts, error) ::= \"<! Required but unused. !>\"\nLL1OptionalBlock(choice, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler->sync(this);\nswitch (_input->LA(1)) {\n  <choice.altLook, alts: {look, alt | <cases(tokens = look)> {\n  <alt>\n  break;\n\\}\n}; separator=\"\\n\">\ndefault:\n  break;\n}\n>>\n\nLL1OptionalBlockSingleAltHeader(choice, expr, alts, preamble, error, followExpr) ::= \"<! Required but unused. !>\"\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler->sync(this);\n\n<preamble; separator = \"\\n\">\nif (<expr>) {\n  <alts; separator = \"\\n\">\n}\n>>\n\nLL1StarBlockSingleAltHeader(choice, loopExpr, alts, preamble, iteration) ::= \"<! Required but unused. !>\"\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler->sync(this);\n<preamble; separator=\"\\n\">\nwhile (<loopExpr>) {\n  <alts; separator=\"\\n\">\n  setState(<choice.loopBackStateNumber>);\n  _errHandler->sync(this);\n  <iteration>\n}\n>>\n\nLL1PlusBlockSingleAltHeader(choice, loopExpr, alts, preamble, iteration) ::= \"<! Required but unused. !>\"\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nsetState(<choice.blockStartStateNumber>); <! alt block decision !>\n_errHandler->sync(this);\n<preamble; separator=\"\\n\">\ndo {\n  <alts; separator=\"\\n\">\n  setState(<choice.stateNumber>); <! loopback/exit decision !>\n  _errHandler->sync(this);\n  <iteration>\n} while (<loopExpr>);\n>>\n\n// LL(*) stuff\n\nAltBlockHeader(choice, preamble, alts, error) ::= \"<! Unused but must be present. !>\"\nAltBlock(choice, preamble, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler->sync(this);\n<! TODO: untested !><if (choice.label)><labelref(choice.label)> = _input->LT(1);<endif>\n<! TODO: untested !><preamble; separator = \"\\n\">\nswitch (getInterpreter\\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, _ctx)) {\n<alts: {alt | case <i>: {\n  <alt>\n  break;\n\\}\n}; separator=\"\\n\">\ndefault:\n  break;\n}\n>>\n\nOptionalBlockHeader(choice, alts, error) ::= \"<! Unused but must be present. !>\"\nOptionalBlock(choice, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler->sync(this);\n\nswitch (getInterpreter\\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, _ctx)) {\n<alts: {alt | case <i><if (!choice.ast.greedy)> + 1<endif>: {\n  <alt>\n  break;\n\\}\n}; separator = \"\\n\">\ndefault:\n  break;\n}\n>>\n\nStarBlockHeader(choice, alts, sync, iteration) ::= \"<! Unused but must be present. !>\"\nStarBlock(choice, alts, sync, iteration) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler->sync(this);\nalt = getInterpreter\\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, _ctx);\nwhile (alt != <choice.exitAlt> && alt != atn::ATN::INVALID_ALT_NUMBER) {\n  if (alt == 1<if(!choice.ast.greedy)> + 1<endif>) {\n    <iteration>\n    <alts> <! should only be one !>\n  }\n  setState(<choice.loopBackStateNumber>);\n  _errHandler->sync(this);\n  alt = getInterpreter\\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, _ctx);\n}\n>>\n\nPlusBlockHeader(choice, alts, error) ::= \"<! Required to exist, but unused. !>\"\nPlusBlock(choice, alts, error) ::= <<\nsetState(<choice.blockStartStateNumber>); <! alt block decision !>\n_errHandler->sync(this);\nalt = 1<if(!choice.ast.greedy)> + 1<endif>;\ndo {\n  switch (alt) {\n    <alts: {alt | case <i><if (!choice.ast.greedy)> + 1<endif>: {\n      <alt>\n      break;\n    \\}\n}; separator=\"\\n\">\n  default:\n    <error>\n  }\n  setState(<choice.loopBackStateNumber>); <! loopback/exit decision !>\n  _errHandler->sync(this);\n  alt = getInterpreter\\<atn::ParserATNSimulator>()->adaptivePredict(_input, <choice.decision>, _ctx);\n} while (alt != <choice.exitAlt> && alt != atn::ATN::INVALID_ALT_NUMBER);\n>>\n\nSync(s) ::= \"Sync(s) sync(<s.expecting.name>);\"\n\nThrowNoViableAltHeader(t) ::= \"<! Unused but must be present. !>\"\nThrowNoViableAlt(t) ::= \"throw NoViableAltException(this);\"\n\nTestSetInlineHeader(s) ::= \"<! Required but unused. !>\"\nTestSetInline(s) ::= <<\n<s.bitsets: {bits | <if (rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount> & ~ 0x3fULL) == 0)\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <<\n(<testShiftInRange({<offsetShift(s.varName, bits.shift)>})> &&\n  ((1ULL \\<\\< <offsetShift(s.varName, bits.shift)>) & <bits.calculated>) != 0)\n>>\n\nisZero ::= [\n  \"0\": true,\n  default: false\n]\n\noffsetShift(shiftAmount, offset, prefix = false) ::= <%\n<if (!isZero.(offset))>(<if (prefix)><parser.name>::<endif><shiftAmount> - <offset>)<else><if (prefix)><parser.name>::<endif><shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens: {t | <s.varName> == <parser.name>::<t.name>}; separator = \"\\n\\n|| \">\n%>\n\ncases(tokens) ::= <<\n<tokens: {t | case <parser.name>::<t.name>:}; separator=\"\\n\">\n>>\n\nInvokeRuleHeader(r, argExprsChunks) ::= \"InvokeRuleHeader\"\nInvokeRule(r, argExprsChunks) ::= <<\nsetState(<r.stateNumber>);\n<if(r.labels)><r.labels: {l | <labelref(l)> = }><endif><r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>);\n>>\n\nMatchTokenHeader(m) ::= \"<! Required but unused. !>\"\nMatchToken(m) ::= <<\nsetState(<m.stateNumber>);\n<if (m.labels)><m.labels: {l | <labelref(l)> = }><endif>match(<parser.name>::<m.escapedName>);\n>>\n\nMatchSetHeader(m, expr, capture) ::= \"<! Required but unused. !>\"\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSetHeader(m, expr, capture) ::= \"<! Required but unused. !>\"\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nsetState(<m.stateNumber>);\n<if (m.labels)><m.labels: {l | <labelref(l)> = }>_input->LT(1);<endif>\n<capture>\nif (<if (invert)><m.varName> == 0 || <m.varName> == Token::EOF || <else>!<endif>(<expr>)) {\n  <if (m.labels)><m.labels: {l | <labelref(l)> = }><endif>_errHandler->recoverInline(this);\n}\nelse {\n  _errHandler->reportMatch(this);\n  consume();\n}\n>>\n\nWildcardHeader(w) ::= \"<! Required but unused. !>\"\nWildcard(w) ::= <<\nsetState(<w.stateNumber>);\n<if (w.labels)><w.labels: {l | <labelref(l)> = }><endif>matchWildcard();\n>>\n\n// ACTION STUFF\n\nActionHeader(a, foo, chunks) ::= \"<chunks>\"\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"ArgAction(a, chunks) <chunks>\"\n\nSemPredHeader(p, chunks, failChunks) ::= \"<! Required but unused. !>\"\nSemPred(p, chunks, failChunks) ::= <<\nsetState(<p.stateNumber>);\n\nif (!(<chunks>)) throw FailedPredicateException(this, <p.predicate><if (failChunks)>, <failChunks><elseif (p.msg)>, <p.msg><endif>);\n>>\n\nExceptionClauseHeader(e, catchArg, catchAction) ::= \"<! Required but unused. !>\"\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n  <catchAction>\n}\n>>\n\n// Lexer actions are not associated with model objects.\n\nLexerSkipCommand()  ::= \"skip();\"\nLexerMoreCommand()  ::= \"more();\"\nLexerPopModeCommand() ::= \"popMode();\"\n\nLexerTypeCommand(arg, grammar)      ::= \"type = <grammar.name>::<arg>;\"\nLexerChannelCommand(arg, grammar)   ::= \"channel = <arg>;\"\nLexerModeCommand(arg, grammar)      ::= \"mode = <grammar.name>Mode::<arg>;\"\nLexerPushModeCommand(arg, grammar)  ::= \"pushMode(<grammar.name>Mode::<arg>);\"\n\nActionTextHeader(t) ::= \"<t.text>\"\nActionText(t) ::= \"<t.text>\"\n\nActionTemplateHeader(t) ::= \"<! Required but unused. !>\"\nActionTemplate(t) ::= \"<t.st>\"\n\nArgRefHeader(t) ::= \"<! Required but unused. !>\"\nArgRef(a) ::= \"_localctx-><a.escapedName>\"\n\nLocalRefHeader(t) ::= \"<! Required but unused. !>\"\nLocalRef(a) ::= \"_localctx-><a.escapedName>\"\n\nRetValueRefHeader(t) ::= \"<! Required but unused. !>\"\nRetValueRef(a) ::= \"_localctx-><a.escapedName>\"\n\nQRetValueRefHeader(t) ::= \"<! Required but unused. !>\"\nQRetValueRef(a) ::= \"<ctx(a)>-><a.dict>-><a.escapedName>\"\n/** How to translate $tokenLabel */\n\nTokenRefHeader(t) ::= \"<! Required but unused. !>\"\nTokenRef(t) ::= \"<ctx(t)>-><t.escapedName>\"\n\nLabelRefHeader(t) ::= \"<! Required but unused. !>\"\nLabelRef(t) ::= \"<ctx(t)>-><t.escapedName>\"\n\nListLabelRefHeader(t) ::= \"<! Required but unused. !>\"\nListLabelRef(t) ::= \"<ctx(t)>-><ListLabelName(t.escapedName)>\"\n\nSetAttrHeader(t) ::= \"<! Required but unused. !>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>-><s.escapedName> = <rhsChunks>;\"\n\nInputSymbolType() ::= \"<file.InputSymbolType; null = {Token}> *\"\n\nTokenPropertyRef_textHeader(t) ::= \"<! Required but unused. !>\"\nTokenPropertyRef_text(t) ::= <<(<ctx(t)>-><t.label> != nullptr ? <ctx(t)>-><t.label>->getText() : \"\")>>\n\nTokenPropertyRef_typeHeader(t) ::= \"<! Required but unused. !>\"\nTokenPropertyRef_type(t) ::= \"(<ctx(t)>-><t.label> != nullptr ? <ctx(t)>-><t.label>->getType() : 0)\"\n\nTokenPropertyRef_lineHeader(t) ::= \"<! Required but unused. !>\"\nTokenPropertyRef_line(t) ::= \"(<ctx(t)>-><t.label> != nullptr ? <ctx(t)>-><t.label>->getLine() : 0)\"\n\nTokenPropertyRef_posHeader(t) ::= \"<! Required but unused. !>\"\nTokenPropertyRef_pos(t) ::= \"(<ctx(t)>-><t.label> != nullptr ? <ctx(t)>-><t.label>->getCharPositionInLine() : 0)\"\n\nTokenPropertyRef_channelHeader(t) ::= \"<! Required but unused. !>\"\nTokenPropertyRef_channel(t) ::= \"(<ctx(t)>-><t.label> != nullptr ? <ctx(t)>-><t.label>->getChannel() : 0)\"\n\nTokenPropertyRef_indexHeader(t) ::= \"<! Required but unused. !>\"\nTokenPropertyRef_index(t) ::= \"(<ctx(t)>-><t.label> != nullptr ? <ctx(t)>-><t.label>->getTokenIndex() : 0)\"\n\nTokenPropertyRef_intHeader(t) ::= \"<! Required but unused. !>\"\nTokenPropertyRef_int(t) ::= \"(<ctx(t)>-><t.label> != nullptr ? std::stoi(<ctx(t)>-><t.label>->getText()) : 0)\"\n\nRulePropertyRef_startHeader(r)  ::= \"<! Required but unused. !>\"\nRulePropertyRef_start(r) ::= \"(<ctx(r)>-><r.label> != nullptr ? (<ctx(r)>-><r.label>->start) : nullptr)\"\n\nRulePropertyRef_stopHeader(r)  ::= \"<! Required but unused. !>\"\nRulePropertyRef_stop(r)  ::= \"(<ctx(r)>-><r.label> != nullptr ? (<ctx(r)>-><r.label>->stop) : nullptr)\"\n\nRulePropertyRef_textHeader(r)  ::= \"<! Required but unused. !>\"\nRulePropertyRef_text(r)  ::= \"(<ctx(r)>-><r.label> != nullptr ? _input->getText(<ctx(r)>-><r.label>->start, <ctx(r)>-><r.label>->stop) : nullptr)\"\n\nRulePropertyRef_ctxHeader(r)   ::= \"<! Required but unused. !>\"\nRulePropertyRef_ctx(r)   ::= \"<ctx(r)>-><r.label>\"\n\nThisRulePropertyRef_start(r) ::= \"ThisRulePropertyRef_start(r) _localctx->start\"\nThisRulePropertyRef_stop(r)  ::= \"ThisRulePropertyRef_stop(r) _localctx->stop\"\n\nThisRulePropertyRef_textHeader(r)  ::= \"<! Required but unused. !>\"\nThisRulePropertyRef_text(r)  ::= \"_input->getText(_localctx->start, _input->LT(-1))\"\n\nThisRulePropertyRef_ctxHeader(r)   ::= \"<! Required but unused. !>\"\nThisRulePropertyRef_ctx(r)   ::= \"_localctx\"\n\nThisRulePropertyRef_parserHeader(r)\t ::= \"<! Required but unused. !>\"\nThisRulePropertyRef_parser(r)\t ::= \"this\"\n\nNonLocalAttrRef(s) ::= \"NonLocalAttrRef(s) ((<s.ruleName; format=\\\"cap\\\">Context)getInvokingContext(<s.ruleIndex>)).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks) ::=\n  \"SetNonLocalAttr(s, rhsChunks) ((<s.ruleName; format=\\\"cap\\\">Context)getInvokingContext(<s.ruleIndex>)).<s.escapedName> = <rhsChunks>;\"\n\nAddToLabelListHeader(a) ::= \"<! Required but unused. !>\"\nAddToLabelList(a) ::= <<\n<ctx(a.label)>-><a.listName>.push_back(<labelref(a.label)>);\n>>\n\nTokenLabelType() ::= \"<file.TokenLabelType; null = {Token}> *\"\n\nTokenDeclHeader(t) ::= \"antlr4::<TokenLabelType()><t.escapedName> = nullptr\"\nTokenDecl(t) ::= \"<! Variable Declaration !>\"\n\nTokenTypeDeclHeader(t) ::= \"<! Local Variable !>\"\nTokenTypeDecl(t) ::= \"size_t <t.escapedName> = 0;\"\n\nTokenListDeclHeader(t) ::= \"std::vector\\<antlr4::Token *> <t.escapedName>\"\nTokenListDecl(t) ::= \"<! Variable Declaration !>\"\n\nRuleContextDeclHeader(r) ::= \"<parser.name>::<r.ctxName> *<r.escapedName> = nullptr\"\nRuleContextDecl(r) ::= \"<! Variable Declaration !>\"\n\nRuleContextListDeclHeader(rdecl) ::= \"std::vector\\<<rdecl.ctxName> *> <rdecl.escapedName>\"\nRuleContextListDecl(rdecl) ::= \"<! Variable Declaration !>\"\n\nContextTokenGetterDeclHeader(t) ::= \"antlr4::tree::TerminalNode *<t.escapedName>();\"\nContextTokenGetterDecl(t) ::= <<\ntree::TerminalNode* <parser.name>::<t.ctx.name>::<t.escapedName>() {\n  return getToken(<parser.name>::<t.escapedName>, 0);\n}\n\n>>\n\nContextTokenListGetterDeclHeader(t) ::= \"std::vector\\<antlr4::tree::TerminalNode *> <t.escapedName>();\"\nContextTokenListGetterDecl(t) ::= <<\nstd::vector\\<tree::TerminalNode *> <parser.name>::<t.ctx.name>::<t.escapedName>() {\n  return getTokens(<parser.name>::<t.escapedName>);\n}\n\n>>\n\nContextTokenListIndexedGetterDeclHeader(t) ::= \"antlr4::tree::TerminalNode* <t.escapedName>(size_t i);\"\nContextTokenListIndexedGetterDecl(t)  ::= <<\ntree::TerminalNode* <parser.name>::<t.ctx.name>::<t.escapedName>(size_t i) {\n  return getToken(<parser.name>::<t.escapedName>, i);\n}\n\n>>\n\nContextRuleGetterDeclHeader(r) ::= \"<r.ctxName> *<r.escapedName>();\"\nContextRuleGetterDecl(r) ::= <<\n<! Note: ctxName is the name of the context to return, while ctx is the owning context. !>\n<parser.name>::<r.ctxName>* <parser.name>::<r.ctx.name>::<r.escapedName>() {\n  return getRuleContext\\<<parser.name>::<r.ctxName>\\>(0);\n}\n\n>>\n\nContextRuleListGetterDeclHeader(r) ::= \"std::vector\\<<r.ctxName> *> <r.escapedName>();\"\nContextRuleListGetterDecl(r) ::= <<\nstd::vector\\<<parser.name>::<r.ctxName> *> <parser.name>::<r.ctx.name>::<r.escapedName>() {\n  return getRuleContexts\\<<parser.name>::<r.ctxName>\\>();\n}\n\n>>\n\nContextRuleListIndexedGetterDeclHeader(r) ::= \"<r.ctxName>* <r.escapedName>(size_t i);\"\nContextRuleListIndexedGetterDecl(r) ::= <<\n<parser.name>::<r.ctxName>* <parser.name>::<r.ctx.name>::<r.escapedName>(size_t i) {\n  return getRuleContext\\<<parser.name>::<r.ctxName>\\>(i);\n}\n\n>>\n\nLexerRuleContext() ::= \"antlr4::RuleContext\"\n\n// The rule context name is the rule followed by a suffix; e.g. r becomes rContext.\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= <<\n<tokenName; format = \"lower\">Token\n>>\n\nImplicitRuleLabel(ruleName) ::= \"<ruleName>Context\"\nImplicitSetLabel(id) ::= \"_tset<id>\"\nListLabelName(label) ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"CaptureNextToken(d) <d.varName> = _input->LT(1);\"\n\nCaptureNextTokenTypeHeader(d) ::= \"<! Required but unused. !>\"\nCaptureNextTokenType(d) ::= \"<d.varName> = _input->LA(1);\"\n\nListenerDispatchMethodHeader(method) ::= <<\nvirtual void <if (method.isEnter)>enter<else>exit<endif>Rule(antlr4::tree::ParseTreeListener *listener) override;\n>>\nListenerDispatchMethod(method) ::= <<\nvoid <parser.name>::<struct.escapedName>::<if (method.isEnter)>enter<else>exit<endif>Rule(tree::ParseTreeListener *listener) {\n  auto parserListener = dynamic_cast\\<<parser.grammarName>Listener *>(listener);\n  if (parserListener != nullptr)\n    parserListener-><if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">(this);\n}\n>>\n\nVisitorDispatchMethodHeader(method) ::= <<\n\nvirtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override;\n>>\nVisitorDispatchMethod(method) ::=  <<\n\nstd::any <parser.name>::<struct.escapedName>::accept(tree::ParseTreeVisitor *visitor) {\n  if (auto parserVisitor = dynamic_cast\\<<parser.grammarName>Visitor*>(visitor))\n    return parserVisitor->visit<struct.derivedFromName; format=\"cap\">(this);\n  else\n    return visitor->visitChildren(this);\n}\n>>\n\nAttributeDeclHeader(d) ::= \"<d.type> <d.escapedName><if(d.initValue)> = <d.initValue><endif>\"\nAttributeDecl(d) ::= \"<d.type> <d.escapedName>\"\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if (!x.isLocal)>antlrcpp::downCast\\<<x.ctx.name> *>(_localctx)-><endif><x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"antlrcpp::downCast\\<<actionChunk.ctx.name> *>(_localctx)\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec) ::= \"precpred(_ctx, <opPrec>)\"\nrecRuleSetReturnAction(src,name) ::= \"recRuleSetReturnAction(src,name) $<name>=$<src>.<name>;\"\nrecRuleSetStopToken() ::= \"_ctx->stop = _input->LT(-1);\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\n_localctx = _tracker.createInstance\\<<ctxName>Context>(parentContext, parentState);\n<if(label)>\n<if(isListLabel)>\n_localctx-><label>.push_back(previousContext);\n<else>\n_localctx-><label> = previousContext;\n<endif>\n<endif>\npushNewRecursionContext(_localctx, startState, Rule<ruleName; format = \"cap\">);\n>>\n\n// Separate context variable to avoid frequent pointer type casts.\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\nauto newContext = _tracker.createInstance\\<<currentAltLabel; format = \"cap\">Context>(_tracker.createInstance\\<<ruleName; format=\"cap\">Context>(parentContext, parentState));\n_localctx = newContext;\n<if(label)>\n<if(isListLabel)>\nnewContext-><label>.push_back(previousContext);\n<else>\nnewContext-><label> = previousContext;\n<endif>\n<endif>\npushNewRecursionContext(newContext, startState, Rule<ruleName; format = \"cap\">);\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\n_localctx = _tracker.createInstance\\<<ctxName>Context>(_localctx);\n_ctx = _localctx;\npreviousContext = _localctx;\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif (!_parseListeners.empty())\n  triggerExitRuleEvent();\npreviousContext = _localctx;\n>>\n\n/** Using a type to init value map, try to init a type; if not in table\n *  must be an object, default value is \"null\".\n */\ninitValue(typeName) ::= <<\n<cppTypeInitMap.(typeName)>\n>>\n\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/Cpp/Files.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2016, Mike Lischke\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\ncodeFileExtension() ::= \".cpp\"\nheaderFileExtension() ::= \".h\"\n\nfileHeader(grammarFileName, ANTLRVersion, header) ::= <<\n<header>\n\n// Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n>>\n\nLexerFileHeader(file, lexer, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, namedActions.header)>\n\n#pragma once\n\n<namedActions.preinclude>\n\n#include \"antlr4-runtime.h\"\n\n<namedActions.postinclude>\n\n<if(file.genPackage)>namespace <file.genPackage> {<endif>\n\n<lexer>\n\n<if (file.genPackage)>\n}  // namespace <file.genPackage>\n<endif>\n>>\n\nLexerFile(file, lexer, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, namedActions.header)>\n\n<namedActions.preinclude>\n\n#include \"<file.lexer.name>.h\"\n\n<namedActions.postinclude>\n\nusing namespace antlr4;\n\n<if (file.genPackage)>using namespace <file.genPackage>;<endif>\n\n<lexer>\n\n>>\n\nParserFileHeader(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, namedActions.header)>\n\n#pragma once\n\n<namedActions.preinclude>\n\n#include \"antlr4-runtime.h\"\n\n<namedActions.postinclude>\n\n<if (file.genPackage)>namespace <file.genPackage> {<endif>\n\n<parser>\n\n<if (file.genPackage)>\n}  // namespace <file.genPackage>\n<endif>\n>>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, namedActions.header)>\n\n<namedActions.preinclude>\n\n<if (file.genListener)>#include \"<file.grammarName>Listener.h\"<endif>\n<if (file.genVisitor)>#include \"<file.grammarName>Visitor.h\"<endif>\n\n#include \"<file.parser.name>.h\"\n\n<namedActions.postinclude>\n\nusing namespace antlrcpp;\n<if (file.genPackage)>using namespace <file.genPackage>;<endif>\n<parser>\n\n>>\n\nBaseListenerFileHeader(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n#pragma once\n\n<namedActions.baselistenerpreinclude>\n\n#include \"antlr4-runtime.h\"\n#include \"<file.grammarName>Listener.h\"\n\n<namedActions.baselistenerpostinclude>\n\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n\n/**\n * This class provides an empty implementation of <file.grammarName>Listener,\n * which can be extended to create a listener which only needs to handle a subset\n * of the available methods.\n */\nclass <file.exportMacro> <file.grammarName>BaseListener : public <file.grammarName>Listener {\npublic:\n<namedActions.baselistenerdeclarations>\n\n<file.listenerNames: {lname |\n  virtual void enter<lname; format=\"cap\">(<file.parserName>::<lname; format = \"cap\">Context * /*ctx*/) override { \\}\n  virtual void exit<lname; format=\"cap\">(<file.parserName>::<lname; format = \"cap\">Context * /*ctx*/) override { \\}\n}; separator=\"\\n\">\n\n  virtual void enterEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }\n  virtual void exitEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }\n  virtual void visitTerminal(antlr4::tree::TerminalNode * /*node*/) override { }\n  virtual void visitErrorNode(antlr4::tree::ErrorNode * /*node*/) override { }\n\n<if (namedActions.baselistenermembers)>\nprivate:\n<namedActions.baselistenermembers>\n<endif>\n};\n\n<if (file.genPackage)>\n}  // namespace <file.genPackage>\n<endif>\n>>\n\nBaseListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n<namedActions.baselistenerpreinclude>\n\n#include \"<file.grammarName>BaseListener.h\"\n\n<namedActions.baselistenerpostinclude>\n\n<if(file.genPackage)>\nusing namespace <file.genPackage>;\n<endif>\n\n<namedActions.baselistenerdefinitions>\n>>\n\nListenerFileHeader(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n#pragma once\n\n<namedActions.listenerpreinclude>\n\n#include \"antlr4-runtime.h\"\n#include \"<file.parserName>.h\"\n\n<namedActions.listenerpostinclude>\n\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n\n/**\n * This interface defines an abstract listener for a parse tree produced by <file.parserName>.\n */\nclass <file.exportMacro> <file.grammarName>Listener : public antlr4::tree::ParseTreeListener {\npublic:\n<namedActions.listenerdeclarations>\n\n<file.listenerNames: {lname |\n  virtual void enter<lname; format = \"cap\">(<file.parserName>::<lname; format =\"cap\">Context *ctx) = 0;\n  virtual void exit<lname; format = \"cap\">(<file.parserName>::<lname; format=\"cap\">Context *ctx) = 0;\n}; separator = \"\\n\">\n\n<if (namedActions.listenermembers)>\nprivate:\n<namedActions.listenermembers>\n<endif>\n};\n\n<if(file.genPackage)>\n}  // namespace <file.genPackage>\n<endif>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n<namedActions.listenerpreinclude>\n\n#include \"<file.grammarName>Listener.h\"\n\n<namedActions.listenerpostinclude>\n\n<if(file.genPackage)>\nusing namespace <file.genPackage>;\n<endif>\n\n<namedActions.listenerdefinitions>\n>>\n\nBaseVisitorFileHeader(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n#pragma once\n\n<namedActions.basevisitorpreinclude>\n\n#include \"antlr4-runtime.h\"\n#include \"<file.grammarName>Visitor.h\"\n\n<namedActions.basevisitorpostinclude>\n\n<if(file.genPackage)>\nnamespace <file.genPackage> {\n<endif>\n\n/**\n * This class provides an empty implementation of <file.grammarName>Visitor, which can be\n * extended to create a visitor which only needs to handle a subset of the available methods.\n */\nclass <file.exportMacro> <file.grammarName>BaseVisitor : public <file.grammarName>Visitor {\npublic:\n<namedActions.basevisitordeclarations>\n\n<file.visitorNames: { lname |\n  virtual std::any visit<lname; format = \"cap\">(<file.parserName>::<lname; format = \"cap\">Context *ctx) override {\n    return visitChildren(ctx);\n  \\}\n}; separator=\"\\n\">\n\n<if (namedActions.basevisitormembers)>\nprivate:\n<namedActions.basevisitormembers>\n<endif>\n};\n\n<if(file.genPackage)>\n}  // namespace <file.genPackage>\n<endif>\n>>\n\nBaseVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n<namedActions.basevisitorpreinclude>\n\n#include \"<file.grammarName>BaseVisitor.h\"\n\n<namedActions.basevisitorpostinclude>\n\n<if(file.genPackage)>\nusing namespace <file.genPackage>;\n<endif>\n\n<namedActions.basevisitordefinitions>\n\n>>\n\nVisitorFileHeader(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n#pragma once\n\n<namedActions.visitorpreinclude>\n\n#include \"antlr4-runtime.h\"\n#include \"<file.parserName>.h\"\n\n<namedActions.visitorpostinclude>\n\n<if(file.genPackage)>namespace <file.genPackage> {<endif>\n\n/**\n * This class defines an abstract visitor for a parse tree\n * produced by <file.parserName>.\n */\nclass <file.exportMacro> <file.grammarName>Visitor : public antlr4::tree::AbstractParseTreeVisitor {\npublic:\n  <namedActions.visitordeclarations>\n\n  /**\n   * Visit parse trees produced by <file.parserName>.\n   */\n  <file.visitorNames: {lname |\n  virtual std::any visit<lname; format = \"cap\">(<file.parserName>::<lname; format = \"cap\">Context *context) = 0;\n  }; separator=\"\\n\">\n\n<if (namedActions.visitormembers)>\nprivate:\n<namedActions.visitormembers>\n<endif>\n};\n\n<if(file.genPackage)>\n}  // namespace <file.genPackage>\n<endif>\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion, header)>\n\n<namedActions.visitorpreinclude>\n\n#include \"<file.grammarName>Visitor.h\"\n\n<namedActions.visitorpostinclude>\n\n<if(file.genPackage)>\nusing namespace <file.genPackage>;\n<endif>\n\n<namedActions.visitordefinitions>\n\n>>\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/Dart/Dart.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012 Terence Parr\n *  Copyright (c) 2012 Sam Harwell\n *  Copyright (c) 2014 Tiago Mazzutti\n *  Copyright (c) 2017 Tobe Osakwe\n *  Copyright (c) 2020 Larry Li\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\ndartTypeInitMap ::= [\n  \"int\":\"0\",\n  \"double\":\"0.0\",\n  \"bool\":\"false\",\n  default:\"null\" // anything other than a primitive type is an object\n]\n\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport 'package:antlr4/antlr4.dart';\n\n<if(file.genListener)>\nimport '<file.grammarName>Listener.dart';\nimport '<file.grammarName>BaseListener.dart';\n<endif>\n<if(file.genVisitor)>\nimport '<file.grammarName>Visitor.dart';\nimport '<file.grammarName>BaseVisitor.dart';\n<endif>\n<if(parser.superClass)>\nimport '<parser.superClass>.dart';\n<endif>\n\n<namedActions.header>\n<parser>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport 'package:antlr4/antlr4.dart';\n\nimport '<file.parserName>.dart';\n<header>\n\n/// This abstract class defines a complete listener for a parse tree produced by\n/// [<file.parserName>].\nabstract class <file.grammarName>Listener extends ParseTreeListener {\n<file.listenerNames:{lname |\n<if(file.listenerLabelRuleNames.(lname))>\n  /// Enter a parse tree produced by the [<lname>]\n  /// labeled alternative in [file.parserName>.<file.listenerLabelRuleNames.(lname)>].\n<else>\n  /// Enter a parse tree produced by [<file.parserName>.<lname>].\n<endif>\n  /// [ctx] the parse tree\n  void enter<lname; format=\"cap\">(<lname; format=\"cap\">Context ctx);\n<if(file.listenerLabelRuleNames.(lname))>\n  /// Exit a parse tree produced by the [<lname>]\n  /// labeled alternative in [<file.parserName>.<file.listenerLabelRuleNames.(lname)>].\n<else>\n  /// Exit a parse tree produced by [<file.parserName>.<lname>].\n<endif>\n  /// [ctx] the parse tree\n  void exit<lname; format=\"cap\">(<lname; format=\"cap\">Context ctx);}; separator=\"\\n\">\n}\n>>\n\nBaseListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport 'package:antlr4/antlr4.dart';\n\nimport '<file.parserName>.dart';\nimport '<file.grammarName>Listener.dart';\n\n<header>\n\n/// This class provides an empty implementation of [<file.grammarName>Listener],\n/// which can be extended to create a listener which only needs to handle\n/// a subset of the available methods.\nclass <file.grammarName>BaseListener implements <file.grammarName>Listener {\n<file.listenerNames:{lname |\n\n  /// The default implementation does nothing.\n  @override\n  void enter<lname; format=\"cap\">(<lname; format=\"cap\">Context ctx) {\\}\n\n  /// The default implementation does nothing.\n  @override\n  void exit<lname; format=\"cap\">(<lname; format=\"cap\">Context ctx) {\\}}; separator=\"\\n\">\n\n  /// The default implementation does nothing.\n  @override\n  void enterEveryRule(ParserRuleContext ctx) {}\n\n  /// The default implementation does nothing.\n  @override\n  void exitEveryRule(ParserRuleContext ctx) {}\n\n  /// The default implementation does nothing.\n  @override\n  void visitTerminal(TerminalNode node) {}\n\n  /// The default implementation does nothing.\n  @override\n  void visitErrorNode(ErrorNode node) {}\n}\n\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport 'package:antlr4/antlr4.dart';\n\nimport '<file.parserName>.dart';\n<header>\n\n/// This abstract class defines a complete generic visitor for a parse tree\n/// produced by [<file.parserName>].\n///\n/// [T] is the eturn type of the visit operation. Use `void` for\n/// operations with no return type.\nabstract class <file.grammarName>Visitor\\<T> extends ParseTreeVisitor\\<T> {\n  <file.visitorNames:{lname |\n<if(file.visitorLabelRuleNames.(lname))>\n/// Visit a parse tree produced by the {@code <lname>\\}\n/// labeled alternative in {@link <file.parserName>#<file.visitorLabelRuleNames.(lname)>\\}.\n<else>\n/// Visit a parse tree produced by [<file.parserName>.<lname>].\n<endif>\n/// [ctx] the parse tree.\n/// Return the visitor result.\nT? visit<lname; format=\"cap\">(<lname; format=\"cap\">Context ctx);}; separator=\"\\n\">\n}\n>>\n\nBaseVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport 'package:antlr4/antlr4.dart';\n\nimport '<file.parserName>.dart';\nimport '<file.grammarName>Visitor.dart';\n<header>\n\n/// This class provides an empty implementation of [<file.grammarName>Visitor],\n/// which can be extended to create a visitor which only needs to handle\n/// a subset of the available methods.\n///\n/// [T] is the return type of the visit operation. Use `void` for\n/// operations with no return type.\nclass <file.grammarName>BaseVisitor\\<T> extends ParseTreeVisitor\\<T> implements <file.grammarName>Visitor\\<T> {\n  <file.visitorNames:{lname |\n/// The default implementation returns the result of calling\n/// [visitChildren] on [ctx].\n@override\nT? visit<lname; format=\"cap\">(<lname; format=\"cap\">Context ctx) => visitChildren(ctx);}; separator=\"\\n\">\n}\n>>\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n// Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n// ignore_for_file: unused_import, unused_local_variable, prefer_single_quotes\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\n<Parser_(ctor=\"parser_ctor\", ...)>\n>>\n\nParser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<\n<if(namedActions.definitions)><namedActions.definitions><endif>\n<if(parser.rules)>\nconst int <parser.rules:{r | RULE_<r.name> = <r.index>}; separator=\", \", wrap, anchor>;\n<endif>\nclass <parser.name> extends <superClass; null=\"Parser\"> {\n  static final checkVersion = () => RuntimeMetaData.checkVersion('<file.ANTLRVersion>', RuntimeMetaData.VERSION);\n  static const int TOKEN_EOF = IntStream.EOF;\n\n  static final List\\<DFA> _decisionToDFA = List.generate(\n      _ATN.numberOfDecisions, (i) => DFA(_ATN.getDecisionState(i), i));\n  static final PredictionContextCache _sharedContextCache = PredictionContextCache();\n  <if(parser.tokens)>\n  static const int <parser.tokens:{k | TOKEN_<k> = <parser.tokens.(k)>}; separator=\", \", wrap, anchor>;\n  <endif>\n\n  @override\n  final List\\<String> ruleNames = [\n    <parser.ruleNames:{r | '<r>'}; separator=\", \", wrap, anchor>\n  ];\n\n  <vocabulary(parser.literalNames, parser.symbolicNames)>\n\n  @override\n  String get grammarFileName => '<parser.grammarFileName>';\n\n  @override\n  List\\<int> get serializedATN => _serializedATN;\n\n  @override\n  ATN getATN() {\n   return _ATN;\n  }\n\n  <namedActions.members>\n  <parser:(ctor)()>\n  <funcs; separator=\"\\n\">\n\n<if(sempredFuncs)>\n  @override\n  bool sempred(RuleContext? _localctx, int ruleIndex, int predIndex) {\n    switch (ruleIndex) {\n    <parser.sempredFuncs.values:{f|\ncase <f.ruleIndex>:\n  return _<f.name>_sempred(_localctx as <f.ctxType>?, predIndex);}; separator=\"\\n\">\n    }\n    return true;\n  }\n  <sempredFuncs.values; separator=\"\\n\">\n<endif>\n\n  <atn>\n}\n<funcs:{func | <if(func.ruleCtx)><func.ruleCtx><endif>}; separator=\"\\n\\n\">\n\n<funcs:{func | <if(func.altLabelCtxs)><func.altLabelCtxs:{l | <func.altLabelCtxs.(l)>}; separator=\"\\n\\n\"><endif>}>\n>>\n\nvocabulary(literalNames, symbolicNames) ::= <<\nstatic final List\\<String?> _LITERAL_NAMES = [\n    <literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n];\nstatic final List\\<String?> _SYMBOLIC_NAMES = [\n    <symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n];\nstatic final Vocabulary VOCABULARY = VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);\n\n@override\nVocabulary get vocabulary {\n  return VOCABULARY;\n}\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\nvoid action(RuleContext? _localctx, int ruleIndex, int actionIndex) {\n  switch (ruleIndex) {\n  <recog.actionFuncs.values:{f|\ncase <f.ruleIndex>:\n  _<f.name>_action(_localctx, actionIndex);\n  break;}; separator=\"\\n\">\n  }\n}\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<if(sempredFuncs)>\nbool sempred(RuleContext? _localctx, int ruleIndex, int predIndex) {\n  switch (ruleIndex) {\n  <recog.sempredFuncs.values:{f|\ncase <f.ruleIndex>:\n  return _<f.name>_sempred(_localctx, predIndex);}; separator=\"\\n\">\n  }\n  return true;\n}\n<sempredFuncs.values; separator=\"\\n\">\n<endif>\n>>\n\nparser_ctor(p) ::= <<\n<p.name>(TokenStream input) : super(input) {\n  interpreter = ParserATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache);\n}\n>>\n\n/// This generates a private method since the actionIndex is generated, making an\n/// overriding implementation impossible to maintain.\nRuleActionFunction(r, actions) ::= <<\nvoid _<r.name>_action(<r.ctxType>? _localctx, int actionIndex) {\n  switch (actionIndex) {\n    <actions:{index|case <index>: <actions.(index)> break;}; separator=\"\\n\">\n  }\n}\n>>\n\n/// This generates a private method since the predIndex is generated, making an\n/// overriding implementation impossible to maintain.\nRuleSempredFunction(r, actions) ::= <<\nbool _<r.name>_sempred(dynamic _localctx, int predIndex) {\n  switch (predIndex) {\n    <actions:{index|case <index>: return <actions.(index)>;}; separator=\"\\n\">\n  }\n  return true;\n}\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<\n\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else><endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\", \">) {\n  dynamic _localctx = <currentRule.ctxType>(context, state<currentRule.args:{a | , <a.escapedName>}>);\n  enterRule(_localctx, <currentRule.startState>, RULE_<currentRule.name>);\n  <namedActions.init>\n  <locals; separator=\"\\n\">\n  try {\n<if(currentRule.hasLookaheadBlock)>\n    int _alt;\n<endif>\n    <code>\n    <postamble; separator=\"\\n\">\n    <namedActions.after>\n  } <if(exceptions)> <exceptions; separator=\"\\n\"><else>on RecognitionException catch (re) {\n    _localctx.exception = re;\n    errorHandler.reportError(this, re);\n    errorHandler.recover(this, re);\n  }<endif> finally {\n    <finallyAction>\n    exitRule();\n  }\n  return _localctx;\n}\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,\n  namedActions,finallyAction,postamble) ::=\n<<\n\n<currentRule.ctxType> <currentRule.escapedName>([int _p = 0]<args:{a | , <a>}>) {\n  final _parentctx = context;\n  final _parentState = state;\n  dynamic _localctx = <currentRule.ctxType>(context, _parentState<currentRule.args:{a | , <a.escapedName>}>);\n  var _prevctx = _localctx;\n  var _startState = <currentRule.startState>;\n  enterRecursionRule(_localctx, <currentRule.startState>, RULE_<currentRule.name>, _p);\n  <namedActions.init>\n  <locals; separator=\"\\n\">\n  try {\n<if(currentRule.hasLookaheadBlock)>\n    int _alt;\n<endif>\n    <code>\n    <postamble; separator=\"\\n\">\n    <namedActions.after>\n  } on RecognitionException catch (re) {\n    _localctx.exception = re;\n    errorHandler.reportError(this, re);\n    errorHandler.recover(this, re);\n  } finally {\n    <finallyAction>\n    unrollRecursionContexts(_parentctx);\n  }\n  return _localctx;\n}\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>_localctx = <currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(_localctx);<endif>\nenterOuterAlt(_localctx, <currentOuterMostAltCodeBlock.alt.altNum>);\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nstate = <choice.stateNumber>;\nerrorHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = tokenStream.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch (tokenStream.LA(1)!) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n  <alt>\n  break;}; separator=\"\\n\">\ndefault:\n  <error>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\nstate = <choice.stateNumber>;\nerrorHandler.sync(this);\nswitch (tokenStream.LA(1)!) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n  <alt>\n  break;}; separator=\"\\n\">\ndefault:\n  break;\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nstate = <choice.stateNumber>;\nerrorHandler.sync(this);\n<preamble; separator=\"\\n\">\nif (<expr>) {\n  <alts; separator=\"\\n\">\n}\n<!else if ( !(<followExpr>) ) <error>!>\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nstate = <choice.stateNumber>;\nerrorHandler.sync(this);\n<preamble; separator=\"\\n\">\nwhile (<loopExpr>) {\n  <alts; separator=\"\\n\">\n  state = <choice.loopBackStateNumber>;\n  errorHandler.sync(this);\n  <iteration>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nstate = <choice.blockStartStateNumber>; <! alt block decision !>\nerrorHandler.sync(this);\n<preamble; separator=\"\\n\">\ndo {\n  <alts; separator=\"\\n\">\n  state = <choice.stateNumber>; <! loopback/exit decision !>\n  errorHandler.sync(this);\n  <iteration>\n} while (<loopExpr>);\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\nstate = <choice.stateNumber>;\nerrorHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = tokenStream.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch (interpreter!.adaptivePredict(tokenStream, <choice.decision>, context)) {\n<alts:{alt |\ncase <i>:\n  <alt>\n  break;}; separator=\"\\n\">\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\nstate = <choice.stateNumber>;\nerrorHandler.sync(this);\nswitch (interpreter!.adaptivePredict(tokenStream, <choice.decision>, context)) {\n<alts:{alt |\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n  <alt>\n  break;}; separator=\"\\n\">\n}\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\nstate = <choice.stateNumber>;\nerrorHandler.sync(this);\n_alt = interpreter!.adaptivePredict(tokenStream, <choice.decision>, context);\nwhile (_alt != <choice.exitAlt> && _alt != ATN.INVALID_ALT_NUMBER) {\n  if (_alt == 1<if(!choice.ast.greedy)> + 1<endif>) {\n    <iteration>\n    <alts> <! should only be one !>\n  }\n  state = <choice.loopBackStateNumber>;\n  errorHandler.sync(this);\n  _alt = interpreter!.adaptivePredict(tokenStream, <choice.decision>, context);\n}\n>>\n\nPlusBlock(choice, alts, error) ::= <<\nstate = <choice.blockStartStateNumber>; <! alt block decision !>\nerrorHandler.sync(this);\n_alt = 1<if(!choice.ast.greedy)>+1<endif>;\ndo {\n  switch (_alt) {\n  <alts:{alt|\ncase <i><if(!choice.ast.greedy)> + 1<endif>:\n  <alt>\n  break;}; separator=\"\\n\">\n  default:\n    <error>\n  }\n  state = <choice.loopBackStateNumber>; <! loopback/exit decision !>\n  errorHandler.sync(this);\n  _alt = interpreter!.adaptivePredict(tokenStream, <choice.decision>, context);\n} while (_alt != <choice.exitAlt> && _alt != ATN.INVALID_ALT_NUMBER);\n>>\n\nSync(s) ::= \"sync(<s.expecting.name>);\"\n\nThrowNoViableAlt(t) ::= \"throw NoViableAltException(this);\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount>) & ~0x3f) == 0\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShift(s.varName, bits.shift)>})> && ((1 \\<\\< <offsetShift(s.varName, bits.shift)>) & <bits.calculated>) != 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShift(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName> == TOKEN_<t.name>}; separator=\" || \">\n%>\n\ncases(tokens) ::= <<\n<tokens:{t | case TOKEN_<t.name>:}; separator=\"\\n\">\n>>\n\nInvokeRule(r, argExprsChunks) ::=<<\nstate = <r.stateNumber>;\n<if(r.labels)><r.labels:{l | <labelref(l)> = }><endif><r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>);\n>>\n\nMatchToken(m) ::= <<\nstate = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>match(TOKEN_<m.name>);\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nstate = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>tokenStream.LT(1);<endif>\n<capture>\nif (<if(invert)><m.varName> \\<= 0 || <else>!<endif>(<expr>)) {\n  <if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>errorHandler.recoverInline(this);\n} else {\n  if ( tokenStream.LA(1)! == IntStream.EOF ) matchedEOF = true;\n  errorHandler.reportMatch(this);\n  consume();\n}\n>>\n\nWildcard(w) ::= <<\nstate = <w.stateNumber>;\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>matchWildcard();\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\nstate = <p.stateNumber>;\nif (!(<chunks>)) {\n  throw FailedPredicateException(this, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>);\n}\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n  <catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"skip();\"\nLexerMoreCommand()  ::= \"more();\"\nLexerPopModeCommand() ::= \"popMode();\"\n\nLexerTypeCommand(arg, grammar)      ::= \"type = <arg>;\"\nLexerChannelCommand(arg, grammar)   ::= \"channel = <arg>;\"\nLexerModeCommand(arg, grammar)      ::= \"mode_ = <arg>;\"\nLexerPushModeCommand(arg, grammar)  ::= \"pushMode(<arg>);\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"_localctx.<a.escapedName>\"\nLocalRef(a) ::= \"_localctx.<a.escapedName>\"\nRetValueRef(a) ::= \"_localctx.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>.<a.dict>.<a.escapedName>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nLabelRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nListLabelRef(t) ::= \"<ctx(t)>.<ListLabelName(t.escapedName)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>.<s.escapedName> = <rhsChunks>;\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={Token}>\"\n\nTokenPropertyRef_text(t) ::= \"<ctx(t)>.<t.label>.text\"\nTokenPropertyRef_type(t) ::= \"<ctx(t)>.<t.label> != null ? <ctx(t)>.<t.label>.type : 0\"\nTokenPropertyRef_line(t) ::= \"<ctx(t)>.<t.label> != null ? <ctx(t)>.<t.label>.line : 0\"\nTokenPropertyRef_pos(t) ::= \"<ctx(t)>.<t.label> != null ? <ctx(t)>.<t.label>.charPositionInLine : 0\"\nTokenPropertyRef_channel(t) ::= \"<ctx(t)>.<t.label> != null ? <ctx(t)>.<t.label>.channel : 0\"\nTokenPropertyRef_index(t) ::= \"<ctx(t)>.<t.label> != null ? <ctx(t)>.<t.label>.tokenIndex : 0\"\nTokenPropertyRef_int(t) ::= \"<ctx(t)>.<t.label> != null ? int.parse(<ctx(t)>.<t.label>.text) : 0\"\n\nRulePropertyRef_start(r) ::= \"<ctx(r)>.<r.label>.start\"\nRulePropertyRef_stop(r)\t ::= \"<ctx(r)>.<r.label>.stop\"\nRulePropertyRef_text(r)\t ::= \"(<ctx(r)>.<r.label> != null ? tokenStream.getTextRange(<ctx(r)>.<r.label>.start, <ctx(r)>.<r.label>.stop) : null)\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>.<r.label>\"\nRulePropertyRef_parser(r)\t ::= \"this\"\n\nThisRulePropertyRef_start(r) ::= \"_localctx.start\"\nThisRulePropertyRef_stop(r)\t ::= \"_localctx.stop\"\nThisRulePropertyRef_text(r)\t ::= \"tokenStream.getTextRange(_localctx.start, tokenStream.LT(-1))\"\nThisRulePropertyRef_ctx(r)\t ::= \"_localctx\"\nThisRulePropertyRef_parser(r)\t ::= \"this\"\n\nNonLocalAttrRef(s)\t\t ::= \"(getInvokingContext(<s.ruleIndex>) as <s.ruleName; format=\\\"cap\\\">Context).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks)\t  ::=\n\t\"(getInvokingContext(<s.ruleIndex>) as <s.ruleName; format=\\\"cap\\\">Context).<s.escapedName> = <rhsChunks>;\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>.<a.listName>.add(<labelref(a.label)>);\"\n\nTokenDecl(t) ::= \"<TokenLabelType()>? <t.escapedName>\"\nTokenTypeDecl(t) ::= \"int <t.escapedName>;\"\nTokenListDecl(t) ::= \"var <t.escapedName> = \\<Token>[]\"\nRuleContextDecl(r) ::= \"<r.ctxName>? <r.escapedName>\"\nRuleContextListDecl(rdecl) ::= \"var <rdecl.escapedName> = \\<<rdecl.ctxName>>[]\"\n\nContextTokenGetterDecl(t) ::= <<\nTerminalNode? <t.escapedName>() => getToken(<parser.name>.TOKEN_<t.name>, 0);\n>>\nContextTokenListGetterDecl(t)  ::= <<\nList\\<TerminalNode> <t.name>s() => getTokens(<parser.name>.TOKEN_<t.name>);\n>>\nContextTokenListIndexedGetterDecl(t)  ::= <<\nTerminalNode? <t.escapedName>(int i) => getToken(<parser.name>.TOKEN_<t.name>, i);\n>>\nContextRuleGetterDecl(r) ::= <<\n<r.ctxName>? <r.escapedName>() => getRuleContext\\<<r.ctxName>\\>(0);\n>>\nContextRuleListGetterDecl(r) ::= <<\nList\\<<r.ctxName>\\> <r.name>s() => getRuleContexts\\<<r.ctxName>\\>();\n>>\nContextRuleListIndexedGetterDecl(r) ::= <<\n<r.ctxName>? <r.escapedName>(int i) => getRuleContext\\<<r.ctxName>\\>(i);\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/// The rule context name is the rule followed by a suffix; e.g.,\n/// r becomes rContext.\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"_<tokenName>\"\nImplicitRuleLabel(ruleName)\t  ::= \"_<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = tokenStream.LT(1);\"\nCaptureNextTokenType(d) ::= \"<d.varName> = tokenStream.LA(1)!;\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures)\n  ::= <<\nclass <struct.escapedName> extends <if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif><if(interfaces)> implements <interfaces; separator=\", \"><endif> {\n  <attrs:{a | <a>;}; separator=\"\\n\">\n  <getters:{g | <g>}; separator=\"\\n\">\n  <struct.escapedName>([ParserRuleContext? parent, int? invokingState<ctorAttrs:{a | , <a>}>]) : super(parent, invokingState)<if(struct.ctorAttrs)> {\n    <struct.ctorAttrs:{a | this.<a.escapedName> = <a.escapedName>;}; separator=\"\\n\">\n  }<else>;<endif>\n\n  @override\n  int get ruleIndex => RULE_<struct.derivedFromName>;\n<if(struct.provideCopyFrom)> <! don't need copy unless we have subclasses !>\n  @override\n  void copyFrom(<if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif> ctx) {\n    super.copyFrom(ctx);\n    <struct.attrs:{a | if((ctx as <struct.escapedName>).<a.escapedName> != null) this.<a.escapedName> = (ctx as <struct.escapedName>).<a.escapedName>;}; separator=\"\\n\">\n  }\n<endif>\n  <dispatchMethods; separator=\"\\n\">\n  <extensionMembers; separator=\"\\n\">\n}\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\nclass <struct.escapedName> extends <struct.parentRule; format=\"cap\">Context {\n  <attrs:{a | <a>;}; separator=\"\\n\">\n  <getters:{g | <g>}; separator=\"\\n\">\n  <struct.escapedName>(<struct.parentRule; format=\"cap\">Context ctx) { copyFrom(ctx); }\n  <dispatchMethods; separator=\"\\n\">\n}\n>>\n\nListenerDispatchMethod(method) ::= <<\n@override\nvoid <if(method.isEnter)>enter<else>exit<endif>Rule(ParseTreeListener listener) {\n  if (listener is <parser.grammarName>Listener) listener.<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">(this);\n}\n>>\n\nVisitorDispatchMethod(method) ::= <<\n@override\nT? accept\\<T>(ParseTreeVisitor\\<T> visitor) {\n  if (visitor is <parser.grammarName>Visitor\\<T>) {\n   return visitor.visit<struct.derivedFromName; format=\"cap\">(this);\n  } else {\n  \treturn visitor.visitChildren(this);\n  }\n}\n>>\n\nAttributeDecl(d) ::= \"<d.type><if(d.initValue)><else>?<endif> <d.escapedName><if(d.initValue)> = <d.initValue><endif>\"\n\n// If we don't know location of label def x, use this template\nlabelref(x) ::= \"<if(!x.isLocal)>_localctx.<endif><x.escapedName>\"\n\n// For any action chunk, what is correctly-typed context struct ptr?\nctx(actionChunk) ::= \"_localctx\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"precpred(context, <opPrec>)\"\nrecRuleSetReturnAction(src,name)\t  ::= \"$<name> = $<src>.<name>;\"\nrecRuleSetStopToken()                 ::= \"context!.stop = tokenStream.LT(-1);\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\n_localctx = <ctxName>Context(_parentctx, _parentState);\n<if(label)>\n<if(isListLabel)>\n_localctx.<label>.add(_prevctx);\n<else>\n_localctx.<label> = _prevctx;\n<endif>\n<endif>\npushNewRecursionContext(_localctx, _startState, RULE_<ruleName>);\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\n_localctx = <currentAltLabel; format=\"cap\">Context(new <ruleName; format=\"cap\">Context(_parentctx, _parentState));\n<if(label)>\n<if(isListLabel)>\n_localctx.<label>.add(_prevctx);\n<else>\n_localctx.<label> = _prevctx;\n<endif>\n<endif>\npushNewRecursionContext(_localctx, _startState, RULE_<ruleName>);\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\n_localctx = <ctxName>Context(_localctx);\ncontext = _localctx;\n_prevctx = _localctx;\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif (parseListeners != null) triggerExitRuleEvent();\n_prevctx = _localctx;\n>>\n\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\nimport 'package:antlr4/antlr4.dart';\n<if(lexer.superClass)>\nimport '<lexer.superClass>.dart';\n<endif>\n<namedActions.header>\n\n<lexer>\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\n<if(namedActions.definitions)><namedActions.definitions><endif>\n\nclass <lexer.name> extends <superClass; null=\"Lexer\"> {\n  static final checkVersion = () => RuntimeMetaData.checkVersion('<lexerFile.ANTLRVersion>', RuntimeMetaData.VERSION);\n\n  static final List\\<DFA> _decisionToDFA = List.generate(\n        _ATN.numberOfDecisions, (i) => DFA(_ATN.getDecisionState(i), i));\n  static final PredictionContextCache _sharedContextCache = PredictionContextCache();\n  <if(lexer.tokens)>\n  static const int\n    <lexer.tokens:{k | TOKEN_<k> = <lexer.tokens.(k)>}; separator=\", \", wrap, anchor>;\n  <endif>\n  <if(lexer.escapedChannels)>\n  static const int\n    <lexer.escapedChannels:{c | <c> = <lexer.escapedChannels.(c)>}; separator=\", \", wrap, anchor>;\n  <endif>\n  <if(rest(lexer.escapedModeNames))>\n  static const int\n    <rest(lexer.escapedModeNames):{m | <m> = <i>}; separator=\", \", wrap, anchor>;\n  <endif>\n\n  @override\n  final List\\<String> channelNames = [\n    'DEFAULT_TOKEN_CHANNEL', 'HIDDEN'<if (lexer.channelNames)>, <lexer.channelNames:{c| '<c>'}; separator=\", \", wrap, anchor><endif>\n  ];\n\n  @override\n  final List\\<String> modeNames = [\n    <lexer.modes:{m| '<m>'}; separator=\", \", wrap, anchor>\n  ];\n\n  @override\n  final List\\<String> ruleNames = [\n    <lexer.ruleNames:{r | '<r>'}; separator=\", \", wrap, anchor>\n  ];\n\n  <vocabulary(lexer.literalNames, lexer.symbolicNames)>\n\n  <namedActions.members>\n\n  <lexer.name>(CharStream input) : super(input) {\n    interpreter = LexerATNSimulator(_ATN, _decisionToDFA, _sharedContextCache, recog: this);\n  }\n\n  @override\n  List\\<int> get serializedATN => _serializedATN;\n\n  @override\n  String get grammarFileName => '<lexer.grammarFileName>';\n\n  @override\n  ATN getATN() { return _ATN; }\n\n  <dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n  <atn>\n}\n>>\n\nSerializedATN(model) ::= <<\nstatic const List\\<int> _serializedATN = [\n    <model.serialized: {s | <s>}; separator=\",\", wrap>\n];\n\nstatic final ATN _ATN =\n    ATNDeserializer().deserialize(_serializedATN);\n>>\n\n/// Using a type to init value map, try to init a type; if not in table\n/// must be an object, default value is \"null\".\ninitValue(typeName) ::= <<\n<dartTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".dart\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/Go/Go.stg",
    "content": "GoTypeMap ::= [\n\t\"boolean\":\"bool\",\n\tdefault : key\n]\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n// Code generated from <grammarFileName> by ANTLR <ANTLRVersion>. DO NOT EDIT.\n>>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n\n<if(file.genPackage)>\npackage <file.genPackage> // <file.grammarName>\n<else>\npackage parser // <file.grammarName>\n<endif>\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n  \t\"sync\"\n\n\t<if(namedActions.includes)>\n\t// Grammar author supplied additional includes\n\t<namedActions.includes>\n\t<endif>\n\t\"github.com/antlr4-go/antlr/v4\"\n)\n\n<if(namedActions.header)>\n\n<namedActions.header>\n<endif>\n\n// Suppress unused import errors\nvar _ = fmt.Printf\nvar _ = strconv.Itoa\nvar _ = sync.Once{}\n\n<if(parser)>\n\n<parser>\n<endif>\n\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n\n<if(file.genPackage)>\npackage <file.genPackage> // <file.grammarName>\n<else>\npackage parser // <file.grammarName>\n<endif>\n\nimport \"github.com/antlr4-go/antlr/v4\"\n\n\n// <file.grammarName>Listener is a complete listener for a parse tree produced by <file.parserName>.\ntype <file.grammarName>Listener interface {\n\tantlr.ParseTreeListener\n\n\t<file.listenerNames:{lname | // Enter<lname; format=\"cap\"> is called when entering the <lname> production.\nEnter<lname; format=\"cap\">(c *<lname; format=\"cap\">Context)}; separator=\"\\n\\n\">\n\n\t<file.listenerNames:{lname | // Exit<lname; format=\"cap\"> is called when exiting the <lname> production.\nExit<lname; format=\"cap\">(c *<lname; format=\"cap\">Context)}; separator=\"\\n\\n\">\n}\n\n>>\n\nBaseListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n\n<if(file.genPackage)>\npackage <file.genPackage> // <file.grammarName>\n<else>\npackage parser // <file.grammarName>\n<endif>\n\nimport \"github.com/antlr4-go/antlr/v4\"\n\n// Base<file.grammarName>Listener is a complete listener for a parse tree produced by <file.parserName>.\ntype Base<file.grammarName>Listener struct{}\n\nvar _ <file.grammarName>Listener = &Base<file.grammarName>Listener{}\n\n// VisitTerminal is called when a terminal node is visited.\nfunc (s *Base<file.grammarName>Listener) VisitTerminal(node antlr.TerminalNode) {}\n\n// VisitErrorNode is called when an error node is visited.\nfunc (s *Base<file.grammarName>Listener) VisitErrorNode(node antlr.ErrorNode) {}\n\n// EnterEveryRule is called when any rule is entered.\nfunc (s *Base<file.grammarName>Listener) EnterEveryRule(ctx antlr.ParserRuleContext) {}\n\n// ExitEveryRule is called when any rule is exited.\nfunc (s *Base<file.grammarName>Listener) ExitEveryRule(ctx antlr.ParserRuleContext) {}\n\n<file.listenerNames:{lname | // Enter<lname; format=\"cap\"> is called when production <lname> is entered.\nfunc (s *Base<file.grammarName>Listener) Enter<lname; format=\"cap\">(ctx *<lname; format=\"cap\">Context) {\\}\n\n// Exit<lname; format=\"cap\"> is called when production <lname> is exited.\nfunc (s *Base<file.grammarName>Listener) Exit<lname; format=\"cap\">(ctx *<lname; format=\"cap\">Context) {\\}}; separator=\"\\n\\n\">\n\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n\n<if(file.genPackage)>\npackage <file.genPackage> // <file.grammarName>\n<else>\npackage parser // <file.grammarName>\n<endif>\n\nimport \"github.com/antlr4-go/antlr/v4\"\n\n\n<if(header)>\n\n<header>\n<endif>\n\n// A complete Visitor for a parse tree produced by <file.parserName>.\ntype <file.grammarName>Visitor interface {\n\tantlr.ParseTreeVisitor\n\n<file.visitorNames:{lname |\n\t// Visit a parse tree produced by <file.parserName>#<lname>.\n\tVisit<lname; format=\"cap\">(ctx *<lname; format=\"cap\">Context) interface{\\}\n}; separator=\"\\n\">\n}\n>>\n\nBaseVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n\n<if(file.genPackage)>\npackage <file.genPackage> // <file.grammarName>\n<else>\npackage parser // <file.grammarName>\n<endif>\n\nimport \"github.com/antlr4-go/antlr/v4\"\n\n\ntype Base<file.grammarName>Visitor struct {\n\t*antlr.BaseParseTreeVisitor\n}\n\n<file.visitorNames:{lname |\nfunc (v *Base<file.grammarName>Visitor) Visit<lname; format=\"cap\">(ctx *<lname; format=\"cap\">Context) interface{\\} {\n\treturn v.VisitChildren(ctx)\n\\}}; separator=\"\\n\\n\">\n\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\ntype <parser.name> struct {\n\t<superClass; null=\"*antlr.BaseParser\">\n\t<if(namedActions.structmembers)>\n\t// Grammar author supplied members of the instance struct\n\t<namedActions.structmembers>\n\t<endif>\n}\n\nvar <parser.grammarName; format=\"cap\">ParserStaticData struct {\n  once                   sync.Once\n  serializedATN          []int32\n  LiteralNames           []string\n  SymbolicNames          []string\n  RuleNames              []string\n  PredictionContextCache *antlr.PredictionContextCache\n  atn                    *antlr.ATN\n  decisionToDFA          []*antlr.DFA\n}\n\nfunc <parser.grammarName; format=\"lower\">ParserInit() {\n  staticData := &<parser.grammarName; format=\"cap\">ParserStaticData\n<if(parser.literalNames)>\n  staticData.LiteralNames = []string{\n    <parser.literalNames; null=\"\\\"\\\"\", separator=\", \", wrap>,\n  }\n<endif>\n<if(parser.symbolicNames)>\n  staticData.SymbolicNames = []string{\n    <parser.symbolicNames; null=\"\\\"\\\"\", separator=\", \", wrap>,\n  }\n<endif>\n<if(parser.ruleNames)>\n  staticData.RuleNames = []string{\n    <parser.ruleNames:{r | \"<r>\"}; separator=\", \", wrap>,\n  }\n<endif>\n  staticData.PredictionContextCache = antlr.NewPredictionContextCache()\n  staticData.serializedATN = <atn>\n  deserializer := antlr.NewATNDeserializer(nil)\n  staticData.atn = deserializer.Deserialize(staticData.serializedATN)\n  atn := staticData.atn\n  staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState))\n  decisionToDFA := staticData.decisionToDFA\n  for index, state := range atn.DecisionToState {\n    decisionToDFA[index] = antlr.NewDFA(state, index)\n  }\n}\n\n// <parser.name>Init initializes any static state used to implement <parser.name>. By default the\n// static state used to implement the parser is lazily initialized during the first call to\n// New<parser.name>(). You can call this function if you wish to initialize the static state ahead\n// of time.\nfunc <parser.name; format=\"cap\">Init() {\n  staticData := &<parser.grammarName; format=\"cap\">ParserStaticData\n  staticData.once.Do(<parser.grammarName; format=\"lower\">ParserInit)\n}\n\n// New<parser.name> produces a new parser instance for the optional input antlr.TokenStream.\nfunc New<parser.name>(input antlr.TokenStream) *<parser.name> {\n\t<parser.name; format=\"cap\">Init()\n\tthis := new(<parser.name>)\n\tthis.BaseParser = antlr.NewBaseParser(input)\n  staticData := &<parser.grammarName; format=\"cap\">ParserStaticData\n\tthis.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache)\n\tthis.RuleNames = staticData.RuleNames\n\tthis.LiteralNames = staticData.LiteralNames\n\tthis.SymbolicNames = staticData.SymbolicNames\n\tthis.GrammarFileName = \"<parser.grammarFileName>\"\n\n\treturn this\n}\n\n<if(namedActions.members)>\n// Note that '@members' cannot be changed now, but this should have been 'globals'\n// If you are looking to have variables for each instance, use '@structmembers'\n<namedActions.members>\n<endif>\n\n<if(parser.tokens)>\n\n// <parser.name> tokens.\nconst (\n\t<parser.name>EOF = antlr.TokenEOF\n\t<parser.tokens:{k | <parser.name><k> = <parser.tokens.(k)>}; separator=\"\\n\">\n)\n<else>\n\n// <parser.name>EOF is the <parser.name> token.\nconst <parser.name>EOF = antlr.TokenEOF\n<endif>\n\n<if(rest(parser.rules))>\n\n// <parser.name> rules.\nconst (\n\t<parser.rules:{r | <parser.name>RULE_<r.name> = <r.index>}; separator=\"\\n\">\n)\n<elseif(parser.rules)>\n\n// <parser.name>RULE_<first(parser.rules).name> is the <parser.name> rule.\nconst <parser.name>RULE_<first(parser.rules).name> = <first(parser.rules).index>\n<endif>\n\n<if(funcs)>\n\n<funcs; separator=\"\\n\\n\">\n<endif>\n\n<if(sempredFuncs)>\n\nfunc (p *<parser.name>) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex int) bool {\n\tswitch ruleIndex {\n\t<if(parser.sempredFuncs.values)>\n\t<parser.sempredFuncs.values:{f | case <f.ruleIndex>:\n\t\tvar t *<f.name; format=\"cap\">Context = nil\n\t\tif localctx != nil { t = localctx.(*<f.name; format=\"cap\">Context) \\}\n\t\treturn p.<f.escapedName; format=\"cap\">_Sempred(t, predIndex)}; separator=\"\\n\\n\">\n\n\n\t<endif>\n\tdefault:\n\t\tpanic(\"No predicate with index: \" + fmt.Sprint(ruleIndex))\n\t}\n}\n<if(sempredFuncs.values)>\n\n<sempredFuncs.values; separator=\"\\n\\n\">\n<endif>\n<endif>\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\n\nfunc (l *<lexer.name>) Action(localctx antlr.RuleContext, ruleIndex, actionIndex int) {\n\tswitch ruleIndex {\n\t<if(recog.actionFuncs.values)>\n\t<recog.actionFuncs.values:{f | case <f.ruleIndex>:\n\t\t<if(f.factory.grammar.lexer)>\n\t\tl.<f.name>_Action(localctx, actionIndex)\n\t\t<else>\n\t\tvar t *<f.name; format=\"cap\">Context = nil\n\t\tif localctx != nil { t = localctx.(*<f.ctxType>) \\}\n\t\tl.<f.name>_Action(t, actionIndex)\n\t\t<endif>\n\t}; separator=\"\\n\\n\">\n\n\t<endif>\n\tdefault:\n\t\tpanic(\"No registered action for: \" + fmt.Sprint(ruleIndex))\n\t}\n}\n<if(actionFuncs.values)>\n\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<endif>\n<if(actionFuncs && sempredFuncs)>\n\n\n<endif>\n<if(sempredFuncs)>\nfunc (l *<lexer.name>) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex int) bool {\n\tswitch ruleIndex {\n\t<if(recog.sempredFuncs.values)>\n\t<recog.sempredFuncs.values:{f | case <f.ruleIndex>:\n\t\t<if(f.factory.grammar.lexer)>\n\t\treturn l.<f.name>_Sempred(localctx, predIndex)\n\t\t<else>\n\t\tvar t *<f.name; format=\"cap\">Context = nil\n\t\tif localctx != nil { t = localctx.(*<f.ctxType>) \\}\n\t\treturn l.<f.name>_Sempred(t, predIndex)\n\t\t<endif>\n\t}; separator=\"\\n\\n\">\n\n\n\t<endif>\n\tdefault:\n\t\tpanic(\"No registered predicate for: \" + fmt.Sprint(ruleIndex))\n\t}\n}\n<if(sempredFuncs.values)>\n\n<sempredFuncs.values; separator=\"\\n\\n\">\n<endif>\n<endif>\n>>\n\n/* This generates a private method since the actionIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\nfunc (l *<lexer.name>) <r.escapedName; format=\"cap\">_Action(localctx <if(r.factory.grammar.lexer)>antlr.RuleContext<else>*<r.ctxType><endif>, actionIndex int) {\n\tswitch actionIndex {\n\t<if(actions)>\n\t<actions:{index | case <index>:\n\t\t<actions.(index)>}; separator=\"\\n\\n\">\n\n\t<endif>\n\tdefault:\n\t\tpanic(\"No registered action for: \" + fmt.Sprint(actionIndex))\n\t}\n}\n>>\n\n/* This generates a private method since the predIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\nfunc (p *<r.factory.grammar.recognizerName>) <r.escapedName; format=\"cap\">_Sempred(localctx antlr.RuleContext, predIndex int) bool {\n\tswitch predIndex {\n\t<if(actions)>\n\t<actions:{index | case <index>:\n\t\treturn <actions.(index)>}; separator=\"\\n\\n\">\n\n\t<endif>\n\tdefault:<! TODO: Should this return true like C#/Java? !>\n\t\tpanic(\"No predicate with index: \" + fmt.Sprint(predIndex))\n\t}\n}\n>>\n\nRuleFunction(currentRule, args, code, locals, ruleCtx, altLabelCtxs, namedActions, finallyAction, postamble, exceptions) ::= <<\n<if(ruleCtx)>\n<ruleCtx>\n\n\n<endif>\n<if(altLabelCtxs)>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\\n\">\n\n\n<endif>\nfunc (p *<parser.name>) <currentRule.escapedName; format=\"cap\">(<currentRule.args:{a | <a.escapedName> <a.type>}; separator=\", \">) (localctx I<currentRule.ctxType>) {\n\tlocalctx = New<currentRule.ctxType>(p, p.GetParserRuleContext(), p.GetState()<currentRule.args:{a | , <a.escapedName>}>)\n\tp.EnterRule(localctx, <currentRule.startState>, <parser.name>RULE_<currentRule.name>)\n\t<if(namedActions.init)>\n\t<namedActions.init>\n\t<endif>\n\t<if(locals)>\n\t<locals:{l | var <l>}; separator=\"\\n\">\n\t<endif>\n\n\t<if(currentRule.hasLookaheadBlock)>\n\tvar _alt int\n\t<endif>\n\n\t<if(code)>\n\t<code>\n\n\n\t<endif>\n\t<if(postamble)>\n\t<postamble; separator=\"\\n\">\n\n\n\t<endif>\n\t<if(namedActions.after)>\n\t<namedActions.after>\n\n\n\t<endif>\nerrorExit:\n\tif p.HasError() {\n\t\tv := p.GetError()\n\t\tlocalctx.SetException(v)\n\t\tp.GetErrorHandler().ReportError(p, v)\n\t\tp.GetErrorHandler().Recover(p, v)\n\t\tp.SetError(nil)\n\t}\n\t<if(finallyAction)>\n\t<finallyAction>\n\t<endif>\n\tp.ExitRule()\n\treturn localctx\n\tgoto errorExit // Trick to prevent compiler error if the label is not used\n}\n>>\n\nLeftRecursiveRuleFunction(currentRule, args, code, locals, ruleCtx, altLabelCtxs, namedActions, finallyAction, postamble) ::= <<\n<if(ruleCtx)>\n<ruleCtx>\n\n\n\n<endif>\n<if(altLabelCtxs)>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\\n\">\n\n\n<endif>\nfunc (p *<parser.name>) <currentRule.escapedName; format=\"cap\">(<args:{a | <a.escapedName> <a.type>}; separator=\", \">) (localctx I<currentRule.ctxType>) {\n\treturn p.<currentRule.escapedName>(0<args:{a | , <a.escapedName>}>)\n}\n\nfunc (p *<parser.name>) <currentRule.escapedName>(_p int<args:{a | , <a.escapedName> <a.type>}>) (localctx I<currentRule.ctxType>) {\n\tvar _parentctx antlr.ParserRuleContext = p.GetParserRuleContext()\n\n\t_parentState := p.GetState()\n\tlocalctx = New<currentRule.ctxType>(p, p.GetParserRuleContext(), _parentState<args:{a | , <a.escapedName>}>)\n\tvar _prevctx I<currentRule.ctxType> = localctx\n\tvar _ antlr.ParserRuleContext = _prevctx // TODO: To prevent unused variable warning.\n\t_startState := <currentRule.startState>\n\tp.EnterRecursionRule(localctx, <currentRule.startState>, <parser.name>RULE_<currentRule.name>, _p)\n\t<if(namedActions.init)>\n\t<namedActions.init>\n\t<endif>\n\t<if(locals)>\n\t<locals:{l | var <l>}; separator=\"\\n\">\n\t<endif>\n\n\t<if(currentRule.hasLookaheadBlock)>\n\tvar _alt int\n\t<endif>\n\n\t<if(code)>\n\t<code>\n\n\n\t<endif>\n\t<if(postamble)>\n\t<postamble; separator=\"\\n\">\n\n\n\t<endif>\n\t<if(namedActions.after)>\n\t<namedActions.after>\n\n\n\t<endif>\n\terrorExit:\n\tif p.HasError() {\n\t\tv := p.GetError()\n\t\tlocalctx.SetException(v)\n\t\tp.GetErrorHandler().ReportError(p, v)\n\t\tp.GetErrorHandler().Recover(p, v)\n\t\tp.SetError(nil)\n\t}\n\t<if(finallyAction)>\n\t<finallyAction>\n\t<endif>\n\tp.UnrollRecursionContexts(_parentctx)\n\treturn localctx\n\tgoto errorExit // Trick to prevent compiler error if the label is not used\n}\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>localctx = New<currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(p, localctx)<endif>\np.EnterOuterAlt(localctx, <currentOuterMostAltCodeBlock.alt.altNum>)\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<if(locals)>\n<locals:{l | var <l>}; separator=\"\\n\">\n\n\n<endif>\n<if(preamble)>\n<preamble; separator=\"\\n\">\n\n\n<endif>\n<if(ops)>\n<ops; separator=\"\\n\">\n<endif>\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\np.SetState(<choice.stateNumber>)\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\n<if(choice.label)>\n<labelref(choice.label)> = p.GetTokenStream().LT(1)\n<endif>\n<if(preamble)>\n\n<preamble; separator=\"\\n\">\n<endif>\n\n\nswitch p.GetTokenStream().LA(1) {\n<if(choice.altLook && alts)>\n<choice.altLook, alts:{look, alt | case <look:{l | <parser.name><l.name>}; separator=\", \">:\n\t<alt>}; separator=\"\\n\\n\">\n\n\n<endif>\ndefault:\n\t<if(error)>\n\t<error>\n\t<endif>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\np.SetState(<choice.stateNumber>)\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\nswitch p.GetTokenStream().LA(1) {\n<if(choice.altLook && alts)>\n<choice.altLook, alts:{look, alt | case <look:{l | <parser.name><l.name>}; separator=\", \">:\n\t<alt>}; separator=\"\\n\\n\">\n\n\n<endif>\ndefault:\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\np.SetState(<choice.stateNumber>)\n<! TODO: this should not consume anything but does I think;\n See TokenMismatch2 test, which fails w/o this sync.\n But, see TestLeftRecursion.testJavaExpressions_10, 11 which fails with sync()\n !>\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\n<if(preamble)>\n<preamble; separator=\"\\n\">\n\n\n<endif>\nif <expr> {\n\t<if(alts)>\n\t<alts; separator=\"\\n\">\n\t<endif>\n}<! else if !(<followExpr>) {\n\t<error>\n}!>\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\np.SetState(<choice.stateNumber>)\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\n<if(preamble)>\n<preamble; separator=\"\\n\">\n\n\n<endif>\nfor <loopExpr> {\n\t<if(alts)>\n\t<alts; separator=\"\\n\">\n\t<endif>\n\tp.SetState(<choice.loopBackStateNumber>)\n\tp.GetErrorHandler().Sync(p)\n\tif p.HasError() {\n    \tgoto errorExit\n    }\n\t<if(iteration)>\n\t<iteration>\n\t<endif>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\np.SetState(<choice.blockStartStateNumber>)<! alt block decision !>\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\n<if(preamble)>\n<preamble; separator=\"\\n\">\n\n\n<endif>\nfor ok := true; ok; ok = <loopExpr> {\n\t<if(alts)>\n\t<alts; separator=\"\\n\">\n\t<endif>\n\tp.SetState(<choice.stateNumber>)<! loopback/exit decision !>\n\tp.GetErrorHandler().Sync(p)\n\tif p.HasError() {\n    \tgoto errorExit\n    }\n\t<if(iteration)>\n\t<iteration>\n\t<endif>\n}\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\np.SetState(<choice.stateNumber>)\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\n\n<if(choice.label)>\n<labelref(choice.label)> = _input.LT(1)\n\n<endif>\n<if(preamble)>\n<preamble; separator=\"\\n\">\n\n<endif>\n\nswitch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), <choice.decision>, p.GetParserRuleContext()) {\n<if(alts)>\n<alts:{alt | case <i>:\n\t<alt>}; separator=\"\\n\\n\">\n<endif>\ncase antlr.ATNInvalidAltNumber:\n\tgoto errorExit\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\np.SetState(<choice.stateNumber>)\np.GetErrorHandler().Sync(p)\n\n<if(alts)>\n\n<alts:{alt | if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), <choice.decision>, p.GetParserRuleContext()) == <i><if(!choice.ast.greedy)>+1<endif> {\n\t<alt>\n\t\\} else if p.HasError() { // JIM\n\t\tgoto errorExit}; separator=\"} else \">\n<endif>\n}\n>>\n\nStarBlock(choice, alts, Sync, iteration) ::= <<\np.SetState(<choice.stateNumber>)\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\n_alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), <choice.decision>, p.GetParserRuleContext())\nif p.HasError() {\n\tgoto errorExit\n}\nfor _alt != <choice.exitAlt> && _alt != antlr.ATNInvalidAltNumber {\n\tif _alt == 1<if(!choice.ast.greedy)>+1<endif> {\n\t\t<if(iteration)>\n\t\t<iteration>\n\t\t<endif>\n\t\t<if(alts)>\n\t\t<alts><! should only be one !>\n\t\t<endif>\n\t}\n\tp.SetState(<choice.loopBackStateNumber>)\n\tp.GetErrorHandler().Sync(p)\n\tif p.HasError() {\n    \tgoto errorExit\n    }\n\t_alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), <choice.decision>, p.GetParserRuleContext())\n\tif p.HasError() {\n\t\tgoto errorExit\n\t}\n}\n>>\n\nPlusBlock(choice, alts, error) ::= <<\np.SetState(<choice.blockStartStateNumber>)<! alt block decision !>\np.GetErrorHandler().Sync(p)\nif p.HasError() {\n\tgoto errorExit\n}\n_alt = 1<if(!choice.ast.greedy)>+1<endif>\nfor ok := true; ok; ok = _alt != <choice.exitAlt> && _alt != antlr.ATNInvalidAltNumber {\n\tswitch _alt {\n\t<if(alts)>\n\t<alts:{alt | case <i><if(!choice.ast.greedy)>+1<endif>:\n\t\t<alt>}; separator=\"\\n\\n\">\n\n\n\t<endif>\n\tdefault:\n\t\t<if(error)>\n\t\t<error>\n\t\t<endif>\n\t}\n\n\tp.SetState(<choice.loopBackStateNumber>)<! loopback/exit decision !>\n\tp.GetErrorHandler().Sync(p)\n\t_alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), <choice.decision>, p.GetParserRuleContext())\n\tif p.HasError() {\n\t\tgoto errorExit\n\t}\n}\n>>\n\nSync(s) ::= \"Sync(<s.expecting.name>)\"\n\nThrowNoViableAlt(t) ::= <<\np.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))\ngoto errorExit\n>>\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Javascript language spec - shift operators are 32 bits long max\ntestShiftInRange(shiftAmount) ::= <<\n(int64(<shiftAmount>) & ^0x3f) == 0\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShiftVar(s.varName, bits.shift)>})> && ((int64(1) \\<\\< <offsetShiftVar(s.varName, bits.shift)>) & <bits.calculated>) != 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShiftVar(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\noffsetShiftType(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<parser.name><shiftAmount> - <offset>)<else><parser.name><shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName> == <parser.name><t.name>}; separator=\" || \">\n%>\n\nInvokeRule(r, argExprsChunks) ::= <<\n{\n\tp.SetState(<r.stateNumber>)\n\t<if(r.labels)>\n\n\t<if(r.ast.options.p)>\n\tvar _x = p.<r.escapedName>(<r.ast.options.p><if(argExprsChunks)>, <endif><argExprsChunks>)\n\t<else>\n\tvar _x = p.<r.escapedName; format=\"cap\">(<argExprsChunks>)\n\t<endif>\n\n\n\t<r.labels:{l | <labelref(l)> = _x}; separator=\"\\n\">\n\t<else>\n\t<if(r.ast.options.p)>\n\tp.<r.escapedName>(<r.ast.options.p><if(argExprsChunks)>, <endif><argExprsChunks>)\n\t<else>\n\tp.<r.escapedName; format=\"cap\">(<argExprsChunks>)\n\t<endif>\n\t<endif>\n}\n>>\n\nMatchToken(m) ::= <<\n{\n\tp.SetState(<m.stateNumber>)\n\t<if(m.labels)>\n\n\tvar _m = p.Match(<parser.name><m.escapedName>)\n\n\t<m.labels:{l | <labelref(l)> = _m}; separator=\"\\n\">\n\t<else>\n\tp.Match(<parser.name><m.escapedName>)\n\t<endif>\n\tif p.HasError() {\n\t\t\t// Recognition error - abort rule\n\t\t\tgoto errorExit\n\t}\n}\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\n{\n\tp.SetState(<m.stateNumber>)\n\t<if(m.labels)>\n\n\tvar _lt = p.GetTokenStream().LT(1)<! TODO: Should LT be called always like InvokeRule and MatchToken? !>\n\n\t<m.labels:{l | <labelref(l)> = _lt}; separator=\"\\n\">\n\n\t<endif>\n\t<if(capture)>\n\t<capture>\n\n\t<endif>\n\t<if(invert)>if <m.varName> \\<= 0 || <expr> <else>if !(<expr>)<endif> {\n\t\t<if(m.labels)>\n\t\tvar _ri = p.GetErrorHandler().RecoverInline(p)\n\n\t\t<m.labels:{l | <labelref(l)> = _ri}; separator=\"\\n\">\n\t\t<else>\n\t\tp.GetErrorHandler().RecoverInline(p)\n\t\t<endif>\n\t} else {\n\t\tp.GetErrorHandler().ReportMatch(p)\n\t\tp.Consume()\n\t}\n}\n>>\n\nWildcard(w) ::= <<\np.SetState(<w.stateNumber>)\n<if(w.labels)>\n\nvar _mwc = p.MatchWildcard()\n\n<w.labels:{l | <labelref(l)> = _mwc}; separator=\"\\n\">\n<else>\np.MatchWildcard()\n<endif>\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\np.SetState(<p.stateNumber>)\n\nif !(<chunks>) {\n\tp.SetError(antlr.NewFailedPredicateException(p, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><else>, \"\"<endif>))\n\tgoto errorExit\n}\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n\t<catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand() ::= \"p.Skip()\"\nLexerMoreCommand() ::= \"p.More()\"\nLexerPopModeCommand() ::= \"p.PopMode()\"\nLexerTypeCommand(arg, grammar)     ::= \"p.SetType(<arg>)\"\nLexerChannelCommand(arg, grammar)  ::= \"p.SetChannel(<arg>)\"\nLexerModeCommand(arg, grammar)     ::= \"p.SetMode(<arg>)\"\nLexerPushModeCommand(arg, grammar) ::= \"p.PushMode(<arg>)\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\n\nArgRef(a) ::= \"<ctx(a)>.<a.escapedName>\"\nLocalRef(a) ::= \"<ctx(a)>.<a.escapedName>\"\nRetValueRef(a) ::= \"<ctx(a)>.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>.Get<a.dict;format={cap}>().Get<a.escapedName;format={cap}>()\"\n\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>.Get<t.escapedName;format={cap}>()\"\nLabelRef(t) ::= \"<ctx(t)>.Get<t.escapedName;format={cap}>()\"\nListLabelRef(t) ::= \"<ctx(t)>.Get<t.escapedName;format={cap}>()\"\n\nSetAttr(s, rhsChunks) ::= \"<ctx(s)>.Set<s.escapedName; format={cap}>(<rhsChunks>)\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={antlr.Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={antlr.Token}>\"\n\nTokenPropertyRef_text(t) ::= \"(func() string { if <ctx(t)>.Get<t.label; format={cap}>() == nil { return \\\"\\\" } else { return <ctx(t)>.Get<t.label; format={cap}>().GetText() }}())\"\nTokenPropertyRef_type(t) ::= \"(func() int { if <ctx(t)>.Get<t.label; format={cap}>() == nil { return 0 } else { return <ctx(t)>.Get<t.label; format={cap}>().GetTokenType() }}())\"\nTokenPropertyRef_line(t) ::= \"(func() int { if <ctx(t)>.Get<t.label; format={cap}>() == nil { return 0 } else { return <ctx(t)>.Get<t.label; format={cap}>().GetLine() }}())\"\nTokenPropertyRef_pos(t) ::= \"(func() int { if <ctx(t)>.Get<t.label; format={cap}>() == nil { return 0 } else { return <ctx(t)>.Get<t.label; format={cap}>().GetColumn() }}())\"\nTokenPropertyRef_channel(t) ::= \"(func() int { if <ctx(t)>.Get<t.label; format={cap}>() == nil { return 0 } else { return <ctx(t)>.Get<t.label; format={cap}>().GetChannel() }}())\"\nTokenPropertyRef_index(t) ::= \"(func() int { if <ctx(t)>.Get<t.label; format={cap}>() == nil { return 0 } else { return <ctx(t)>.Get<t.label; format={cap}>().GetTokenIndex() }}())\"\nTokenPropertyRef_int(t) ::= \"(func() int { if <ctx(t)>.Get<t.label; format={cap}>() == nil { return 0 } else { i, _ := strconv.Atoi(<ctx(t)>.Get<t.label; format={cap}>().GetText()); return i }}())\"\n\nRulePropertyRef_start(r) ::= \"(func() antlr.Token { if <ctx(r)>.Get<r.label;format={cap}>() == nil { return nil } else { return <ctx(r)>.Get<r.label;format={cap}>().GetStart() }}())\"\nRulePropertyRef_stop(r) ::= \"(func() antlr.Token { if <ctx(r)>.Get<r.label;format={cap}>() == nil { return nil } else { return <ctx(r)>.Get<r.label;format={cap}>().GetStop() }}())\"\nRulePropertyRef_text(r) ::= \"(func() string { if <ctx(r)>.Get<r.label;format={cap}>() == nil { return \\\"\\\" } else { return p.GetTokenStream().GetTextFromTokens(<ctx(r)>.Get<r.label;format={cap}>().GetStart(), <ctx(r)>.<r.label>.GetStop()) }}())\"\nRulePropertyRef_ctx(r) ::= \"<ctx(r)>.Get<r.label;format={cap}>()\"\nRulePropertyRef_parser(r) ::= \"p\"\n\nThisRulePropertyRef_start(r) ::= \"localctx.GetStart()\"\nThisRulePropertyRef_stop(r) ::= \"localctx.GetStop()\"\nThisRulePropertyRef_text(r) ::= \"p.GetTokenStream().GetTextFromTokens(localctx.GetStart(), p.GetTokenStream().LT(-1))\"\nThisRulePropertyRef_ctx(r) ::= \"<ctx(r)>\"\nThisRulePropertyRef_parser(r) ::= \"p\"\n\nNonLocalAttrRef(s) ::= \"p.GetInvokingContext(<s.ruleIndex>).(*<s.ruleName; format={cap}>Context).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks) ::= \"p.GetInvokingContext(<s.ruleIndex>).(*<s.ruleName; format={cap}>Context).<s.escapedName> = <rhsChunks>\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>.<a.listName> = append(<ctx(a.label)>.<a.listName>, <labelref(a.label)>)\"\n\nTokenDecl(t) ::= \"<t.escapedName> <GoTypeMap.(TokenLabelType())>\"\nTokenTypeDecl(t) ::= \"<t.escapedName> int\"\nTokenListDecl(t) ::= \"<t.escapedName> []antlr.Token\"\n\nRuleContextDecl(r) ::= \"<r.escapedName> I<r.ctxName> \"\nRuleContextListDecl(rdecl) ::= \"<rdecl.escapedName> []I<rdecl.ctxName>\"\n\nAttributeDecl(d) ::= \"<d.escapedName> <GoTypeMap.(d.type)><if(d.initValue)>// TODO = <d.initValue><endif>\"\n\nContextTokenGetterDecl(t) ::= <<\n<t.escapedName; format=\"cap\">() antlr.TerminalNode<if(!t.signature)> {\n\treturn s.GetToken(<parser.name><t.escapedName>, 0)\n}<endif>\n>>\n\nContextTokenListGetterDecl(t) ::= <<\nAll<t.escapedName; format=\"cap\">() []antlr.TerminalNode<if(!t.signature)> {\n\treturn s.GetTokens(<parser.name><t.escapedName>)\n}<endif>\n>>\n\nContextTokenListIndexedGetterDecl(t) ::= <<\n<t.escapedName; format=\"cap\">(i int) antlr.TerminalNode<if(!t.signature)> {\n\treturn s.GetToken(<parser.name><t.escapedName>, i)\n}<endif>\n>>\n\nContextRuleGetterDecl(r) ::= <<\n<r.escapedName; format=\"cap\">() I<r.ctxName><if(!r.signature)> {\n\tvar t antlr.RuleContext;\n\tfor _, ctx := range s.GetChildren() {\n\t\tif _, ok := ctx.(I<r.ctxName>); ok {\n\t\t\tt = ctx.(antlr.RuleContext);\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif t == nil {\n\t\treturn nil\n\t}\n\n\treturn t.(I<r.ctxName>)\n}<endif>\n>>\n\nContextRuleListGetterDecl(r) ::= <<\nAll<r.escapedName; format=\"cap\">() []I<r.ctxName><if(!r.signature)> {\n\tchildren := s.GetChildren()\n\tlen := 0\n\tfor _, ctx := range children {\n\t\tif _, ok := ctx.(I<r.ctxName>); ok {\n\t\t\tlen++\n\t\t}\n\t}\n\n\ttst := make([]I<r.ctxName>, len)\n\ti := 0\n\tfor _, ctx := range children {\n\t\tif t, ok := ctx.(I<r.ctxName>); ok {\n\t\t\ttst[i] = t.(I<r.ctxName>)\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn tst\n}<endif>\n>>\n\nContextRuleListIndexedGetterDecl(r) ::= <<\n<r.escapedName; format=\"cap\">(i int) I<r.ctxName><if(!r.signature)> {\n\tvar t antlr.RuleContext;\n\tj := 0\n\tfor _, ctx := range s.GetChildren() {\n\t\tif _, ok := ctx.(I<r.ctxName>); ok {\n\t\t\tif j == i {\n\t\t\t\tt = ctx.(antlr.RuleContext);\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tj++\n\t\t}\n\t}\n\n\tif t == nil {\n\t\treturn nil\n\t}\n\n\treturn t.(I<r.ctxName>)\n}<endif>\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/** The rule context name is the rule followed by a suffix; e.g.,\n *\tr becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"_<tokenName>\"\nImplicitRuleLabel(ruleName) ::= \"_<ruleName>\"\nImplicitSetLabel(id) ::= \"_tset<id>\"\nListLabelName(label) ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = p.GetTokenStream().LT(1)\"\nCaptureNextTokenType(d) ::= \"<d.varName> = p.GetTokenStream().LA(1)\"\n\nStructDecl(struct, ctorAttrs, attrs, getters, dispatchMethods, interfaces, extensionMembers, signatures) ::= <<\n// I<struct.escapedName> is an interface to support dynamic dispatch.\ntype I<struct.escapedName> interface {\n\tantlr.ParserRuleContext\n\n\t// GetParser returns the parser.\n\tGetParser() antlr.Parser\n\t<if(struct.tokenDecls)>\n\n\t<struct.tokenDecls:{a | // Get<a.escapedName; format=\"cap\"> returns the <a.escapedName> token.\nGet<a.escapedName; format=\"cap\">() <TokenLabelType()> }; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.tokenDecls)>\n\n\t<struct.tokenDecls:{a | // Set<a.escapedName; format=\"cap\"> sets the <a.escapedName> token.\nSet<a.escapedName; format=\"cap\">(<TokenLabelType()>) }; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.tokenTypeDecls)>\n\n\t<struct.tokenTypeDecls:{a | // Get<a.escapedName; format=\"cap\"> returns the <a.escapedName> token type.\nGet<a.escapedName; format=\"cap\">() int }; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.tokenTypeDecls)>\n\n\t<struct.tokenTypeDecls:{a | // Set<a.escapedName; format=\"cap\"> sets the <a.escapedName> token type.\nSet<a.escapedName; format=\"cap\">(int) }; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.tokenListDecls)>\n\n\t<struct.tokenListDecls:{a | // Get<a.escapedName; format=\"cap\"> returns the <a.escapedName> token list.\nGet<a.escapedName; format=\"cap\">() []<TokenLabelType()>}; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.tokenListDecls)>\n\n\t<struct.tokenListDecls:{a | // Set<a.escapedName; format=\"cap\"> sets the <a.escapedName> token list.\nSet<a.escapedName; format=\"cap\">([]<TokenLabelType()>)}; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.ruleContextDecls)>\n\n\t<struct.ruleContextDecls:{a | // Get<a.escapedName; format=\"cap\"> returns the <a.escapedName> rule contexts.\nGet<a.escapedName; format=\"cap\">() I<a.ctxName>}; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.ruleContextDecls)>\n\n\t<struct.ruleContextDecls:{a | // Set<a.escapedName; format=\"cap\"> sets the <a.escapedName> rule contexts.\nSet<a.escapedName; format=\"cap\">(I<a.ctxName>)}; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.ruleContextListDecls)>\n\n\t<struct.ruleContextListDecls:{a | // Get<a.escapedName; format=\"cap\"> returns the <a.escapedName> rule context list.\nGet<a.escapedName; format=\"cap\">() []I<a.ctxName>}; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.ruleContextListDecls)>\n\n\t<struct.ruleContextListDecls:{a | // Set<a.escapedName; format=\"cap\"> sets the <a.escapedName> rule context list.\nSet<a.escapedName; format=\"cap\">([]I<a.ctxName>) }; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.attributeDecls)>\n\n\t<struct.attributeDecls:{a | // Get<a.escapedName; format=\"cap\"> returns the <a.escapedName> attribute.\nGet<a.escapedName; format=\"cap\">() <a.type>}; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(struct.attributeDecls)>\n\n\t<struct.attributeDecls:{a | // Set<a.escapedName; format=\"cap\"> sets the <a.escapedName> attribute.\nSet<a.escapedName; format=\"cap\">(<a.type>)}; separator=\"\\n\\n\">\n\t<endif>\n\n\t<if(signatures)>\n\n\t// Getter signatures\n\t<signatures:{s | <s>}; separator=\"\\n\">\n\t<endif>\n\n\t// Is<struct.escapedName> differentiates from other interfaces.\n\tIs<struct.escapedName>()\n}\n\ntype <struct.escapedName> struct {\n\t<if(contextSuperClass)>*<contextSuperClass><else>antlr.BaseParserRuleContext<endif>\n\tparser antlr.Parser\n\t<if(attrs)>\n\t<attrs; separator=\"\\n\">\n\t<endif>\n}\n\nfunc NewEmpty<struct.escapedName>() *<struct.escapedName> {\n\tvar p = new(<struct.escapedName>)\n\t<if(contextSuperClass)>\n\tp.<contextSuperClass> = New<contextSuperClass>(nil, -1) // Jim super\n\t<else>\n\tantlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1)\n\t<endif>\n\tp.RuleIndex = <parser.name>RULE_<struct.derivedFromName>\n\treturn p\n}\n\nfunc InitEmpty<struct.escapedName>(p *<struct.escapedName>)  {\n\t<if(contextSuperClass)>\n\tp.<contextSuperClass> = New<contextSuperClass>(nil, -1) // Jim super\n\t<else>\n\tantlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1)\n\t<endif>\n\tp.RuleIndex = <parser.name>RULE_<struct.derivedFromName>\n}\n\nfunc (*<struct.escapedName>) Is<struct.escapedName>() {}\n\nfunc New<struct.escapedName>(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int<struct.ctorAttrs:{a | , <a.escapedName> <a.type>}>) *<struct.escapedName> {\n\tvar p = new(<struct.escapedName>)\n\n\t<if(contextSuperClass)>\n\tp.<contextSuperClass> = New<contextSuperClass>(parent, invokingState)\n\t<else>\n\tantlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState)\n\t<endif>\n\n\tp.parser = parser\n\tp.RuleIndex = <parser.name>RULE_<struct.derivedFromName>\n\n\t<if(struct.ctorAttrs)>\n\t<struct.ctorAttrs:{a | p.<a.escapedName> = <a.escapedName>}; separator=\"\\n\">\n\n\t<endif>\n\treturn p\n}\n\nfunc (s *<struct.escapedName>) GetParser() antlr.Parser { return s.parser }\n<if(struct.tokenDecls)>\n\n<struct.tokenDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() <TokenLabelType()> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenDecls)>\n\n<struct.tokenDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v <TokenLabelType()>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenTypeDecls)>\n\n<struct.tokenTypeDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() int { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenTypeDecls)>\n\n<struct.tokenTypeDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v int) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenListDecls)>\n\n<struct.tokenListDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() []<TokenLabelType()> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenListDecls)>\n\n<struct.tokenListDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v []<TokenLabelType()>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextDecls)>\n\n<struct.ruleContextDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() I<a.ctxName> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextDecls)>\n\n<struct.ruleContextDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v I<a.ctxName>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextListDecls)>\n\n<struct.ruleContextListDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() []I<a.ctxName> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextListDecls)>\n\n<struct.ruleContextListDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v []I<a.ctxName>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.attributeDecls)>\n\n<struct.attributeDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() <a.type> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.attributeDecls)>\n\n<struct.attributeDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v <a.type>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(getters)>\n\n<getters:{g | func (s *<struct.escapedName>) <g>}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.provideCopyFrom)>\n\nfunc (s *<struct.escapedName>) CopyAll(ctx *<struct.escapedName>) {\n\ts.CopyFrom(&ctx.BaseParserRuleContext)\n\t<struct.attrs:{a | s.<a.escapedName> = ctx.<a.escapedName>}; separator=\"\\n\">\n}\n<endif>\n\nfunc (s *<struct.escapedName>) GetRuleContext() antlr.RuleContext {\n\treturn s\n}\n\nfunc (s *<struct.escapedName>) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {\n\treturn antlr.TreesStringTree(s, ruleNames, recog)\n}\n\n<if(dispatchMethods)>\n\n<dispatchMethods; separator=\"\\n\\n\">\n<endif>\n\n<if(extensionMembers)>\n\n<extensionMembers; separator=\"\\n\\n\">\n<endif>\n>>\n\nAltLabelStructDecl(struct, attrs, getters, dispatchMethods, tokenDecls, tokenTypeDecls, tokenListDecls, ruleContextDecls, ruleContextListDecls, attributeDecls) ::= <<\ntype <struct.escapedName> struct {\n\t<currentRule.name; format=\"cap\">Context\n\t<if(attrs)>\n\t<attrs; separator=\"\\n\">\n\t<endif>\n}\n\nfunc New<struct.escapedName>(parser antlr.Parser, ctx antlr.ParserRuleContext) *<struct.escapedName> {\n\tvar p = new(<struct.escapedName>)\n\n\tInitEmpty<currentRule.name; format=\"cap\">Context(&p.<currentRule.name; format=\"cap\">Context)\n\tp.parser = parser\n\tp.CopyAll(ctx.(*<currentRule.name; format=\"cap\">Context))\n\n\treturn p\n}\n\n<if(struct.tokenDecls)>\n\n<struct.tokenDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() <TokenLabelType()> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenDecls)>\n\n<struct.tokenDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v <TokenLabelType()>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenTypeDecls)>\n\n<struct.tokenTypeDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() int { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenTypeDecls)>\n\n<struct.tokenTypeDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v int) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenListDecls)>\n\n<struct.tokenListDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() []<TokenLabelType()> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.tokenListDecls)>\n\n<struct.tokenListDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v []<TokenLabelType()>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextDecls)>\n\n<struct.ruleContextDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() I<a.ctxName> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextDecls)>\n\n<struct.ruleContextDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v I<a.ctxName>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextListDecls)>\n\n<struct.ruleContextListDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() []I<a.ctxName> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.ruleContextListDecls)>\n\n<struct.ruleContextListDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v []I<a.ctxName>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.attributeDecls)>\n\n<struct.attributeDecls:{a | func (s *<struct.escapedName>) Get<a.escapedName; format=\"cap\">() <a.type> { return s.<a.escapedName> \\}}; separator=\"\\n\\n\">\n<endif>\n\n<if(struct.attributeDecls)>\n\n<struct.attributeDecls:{a | func (s *<struct.escapedName>) Set<a.escapedName; format=\"cap\">(v <a.type>) { s.<a.escapedName> = v \\}}; separator=\"\\n\\n\">\n<endif>\n\nfunc (s *<struct.escapedName>) GetRuleContext() antlr.RuleContext {\n\treturn s\n}\n<if(getters)>\n\n<getters:{g | func (s *<struct.escapedName>) <g>}; separator=\"\\n\\n\">\n<endif>\n\n<if(dispatchMethods)>\n\n<dispatchMethods; separator=\"\\n\\n\">\n<endif>\n>>\n\nListenerDispatchMethod(method) ::= <<\nfunc (s *<struct.escapedName>) <if(method.isEnter)>Enter<else>Exit<endif>Rule(listener antlr.ParseTreeListener) {\n\tif listenerT, ok := listener.(<parser.grammarName>Listener); ok {\n\t\tlistenerT.<if(method.isEnter)>Enter<else>Exit<endif><struct.derivedFromName; format=\"cap\">(s)\n\t}\n}\n>>\n\nVisitorDispatchMethod(method) ::= <<\nfunc (s *<struct.escapedName>) Accept(visitor antlr.ParseTreeVisitor) interface{} {\n\tswitch t := visitor.(type) {\n\tcase <parser.grammarName>Visitor:\n\t\treturn t.Visit<struct.derivedFromName; format=\"cap\">(s)\n\n\tdefault:\n\t\treturn t.VisitChildren(s)\n\t}\n}\n>>\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if(!x.isLocal)>localctx.(*<x.ctx.escapedName>).<endif><x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"localctx.(*<actionChunk.ctx.escapedName>)\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName, opPrec) ::= \"p.Precpred(p.GetParserRuleContext(), <opPrec>)\"\nrecRuleSetReturnAction(src, name) ::= \"$<name> = $<src>.<name>\" // TODO: Is this valid Go syntax?\nrecRuleSetStopToken() ::= \"p.GetParserRuleContext().SetStop(p.GetTokenStream().LT(-1))\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\nlocalctx = New<ctxName>Context(p, _parentctx, _parentState)\n<if(label)>\n<if(isListLabel)>\nlocalctx.(*<ctxName>Context).<label> = append(localctx.(*<ctxName>Context).<label>, _prevctx);\n<else>\nlocalctx.(*<ctxName>Context).<label> = _prevctx\n<endif>\n<endif>\np.PushNewRecursionContext(localctx, _startState, <parser.name>RULE_<ruleName>)\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\nlocalctx = New<currentAltLabel; format=\"cap\">Context(p, New<ruleName; format=\"cap\">Context(p, _parentctx, _parentState))\n<if(label)>\n<if(isListLabel)>\nlocalctx.(*<currentAltLabel; format=\"cap\">Context).<label> = append(localctx.(*<currentAltLabel; format=\"cap\">Context).<label>, _prevctx)\n<else>\nlocalctx.(*<currentAltLabel; format=\"cap\">Context).<label> = _prevctx\n<endif>\n\n<endif>\n\np.PushNewRecursionContext(localctx, _startState, <parser.name>RULE_<ruleName>)\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\nlocalctx = New<ctxName>Context(p, localctx)\np.SetParserRuleContext(localctx)\n_prevctx = localctx\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif p.GetParseListeners() != nil {\n\tp.TriggerExitRuleEvent()\n}\n_prevctx = localctx\n>>\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\n\n<if(lexerFile.genPackage)>\npackage <lexerFile.genPackage>\n<else>\npackage parser\n<endif>\n\nimport (\n\t\"fmt\"\n  \t\"sync\"\n\t\"unicode\"\n\t<if(namedActions.includes)>\n\t// Grammar author supplied additional includes\n\t<namedActions.includes>\n\t<endif>\n\t\"github.com/antlr4-go/antlr/v4\"\n)\n<if(namedActions.header)>\n<namedActions.header>\n<endif>\n\n// Suppress unused import error\nvar _ = fmt.Printf\nvar _ = sync.Once{}\nvar _ = unicode.IsLetter\n\n<if(lexer)>\n\n<lexer>\n<endif>\n\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\ntype <lexer.name> struct {\n\t<if(superClass)><superClass><else>*antlr.BaseLexer<endif>\n\tchannelNames []string\n\tmodeNames []string\n\t<if(namedActions.structmembers)>\n    // Grammar author supplied members of the instance struct\n    <namedActions.structmembers>\n    <endif>\n\t// TODO: EOF string\n}\n\nvar <lexer.grammarName; format=\"cap\">LexerStaticData struct {\n  once                   sync.Once\n  serializedATN          []int32\n  ChannelNames           []string\n  ModeNames              []string\n  LiteralNames           []string\n  SymbolicNames          []string\n  RuleNames              []string\n  PredictionContextCache *antlr.PredictionContextCache\n  atn                    *antlr.ATN\n  decisionToDFA          []*antlr.DFA\n}\n\nfunc <lexer.grammarName; format=\"lower\">LexerInit() {\n  staticData := &<lexer.grammarName; format=\"cap\">LexerStaticData\n  staticData.ChannelNames = []string{\n    \"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"<if (lexer.channelNames)>, <lexer.channelNames:{c | \"<c>\"}; separator=\", \", wrap><endif>,\n  }\n  staticData.ModeNames = []string{\n    <lexer.escapedModeNames:{m | \"<m>\"}; separator=\", \", wrap>,\n  }\n<if(lexer.literalNames)>\n  staticData.LiteralNames = []string{\n    <lexer.literalNames; null=\"\\\"\\\"\", separator=\", \", wrap>,\n  }\n<endif>\n<if(lexer.symbolicNames)>\n  staticData.SymbolicNames = []string{\n    <lexer.symbolicNames; null=\"\\\"\\\"\", separator=\", \", wrap>,\n  }\n<endif>\n<if(lexer.ruleNames)>\n  staticData.RuleNames = []string{\n    <lexer.ruleNames:{r | \"<r>\"}; separator=\", \", wrap>,\n  }\n<endif>\n  staticData.PredictionContextCache = antlr.NewPredictionContextCache()\n  staticData.serializedATN = <atn>\n  deserializer := antlr.NewATNDeserializer(nil)\n  staticData.atn = deserializer.Deserialize(staticData.serializedATN)\n  atn := staticData.atn\n  staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState))\n  decisionToDFA := staticData.decisionToDFA\n  for index, state := range atn.DecisionToState {\n    decisionToDFA[index] = antlr.NewDFA(state, index)\n  }\n}\n\n// <lexer.name>Init initializes any static state used to implement <lexer.name>. By default the\n// static state used to implement the lexer is lazily initialized during the first call to\n// New<lexer.name>(). You can call this function if you wish to initialize the static state ahead\n// of time.\nfunc <lexer.name; format=\"cap\">Init() {\n  staticData := &<lexer.grammarName; format=\"cap\">LexerStaticData\n  staticData.once.Do(<lexer.grammarName; format=\"lower\">LexerInit)\n}\n\n// New<lexer.name> produces a new lexer instance for the optional input antlr.CharStream.\nfunc New<lexer.name>(input antlr.CharStream) *<lexer.name> {\n  <lexer.name; format=\"cap\">Init()\n\tl := new(<lexer.name>)\n\tl.BaseLexer = antlr.NewBaseLexer(input)\n  staticData := &<lexer.grammarName; format=\"cap\">LexerStaticData\n\tl.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache)\n\tl.channelNames = staticData.ChannelNames\n\tl.modeNames = staticData.ModeNames\n\tl.RuleNames = staticData.RuleNames\n\tl.LiteralNames = staticData.LiteralNames\n\tl.SymbolicNames = staticData.SymbolicNames\n\tl.GrammarFileName = \"<lexer.grammarFileName>\"\n\t// TODO: l.EOF = antlr.TokenEOF\n\n\treturn l\n}\n<if(rest(lexer.tokens))>\n\n// <lexer.name> tokens.\nconst (\n\t<lexer.tokens:{k | <lexer.name><k> = <lexer.tokens.(k)>}; separator=\"\\n\">\n)\n<elseif(lexer.tokens)>\n\n// <lexer.name><first(lexer.tokens)> is the <lexer.name> token.\nconst <lexer.name><first(lexer.tokens)> = <lexer.tokens.(first(lexer.tokens))>\n<endif>\n\n<if(rest(lexer.escapedChannels))>\n\n// <lexer.name> escapedChannels.\nconst (\n\t<lexer.escapedChannels:{c | <lexer.name><c> = <lexer.escapedChannels.(c)>}; separator=\"\\n\">\n)\n<elseif(lexer.escapedChannels)>\n\n// <lexer.name><first(lexer.escapedChannels)> is the <lexer.name> channel.\nconst <lexer.name><first(lexer.escapedChannels)> = <lexer.escapedChannels.(first(lexer.escapedChannels))>\n<endif>\n\n<if(rest(rest(lexer.escapedModeNames)))>\n\n// <lexer.name> modes.\nconst (\n\t<first(rest(lexer.escapedModeNames)):{m | <lexer.name><m> = iota + 1}>\n\t<rest(rest(lexer.escapedModeNames)):{m | <lexer.name><m>}; separator=\"\\n\">\n)\n<elseif(rest(lexer.escapedModeNames))>\n\n// <lexer.name><first(rest(lexer.escapedModeNames))> is the <lexer.name> mode.\nconst <lexer.name><first(rest(lexer.escapedModeNames))> = 1\n<endif>\n<if(namedActions.members)>\n\n<namedActions.members>\n<endif>\n\n<dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n>>\n\nSerializedATN(model) ::= <<\n<if(model.serialized)>[]int32{\n\t<model.serialized; separator=\", \", wrap>,\n}<endif>\n>>\n\n/**\n * Using a type to init value map, try to init a type; if not in table\n *\tmust be an object, default value is \"nil\".\n */\ninitValue(typeName) ::= <<\n<javaTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".go\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\njavaTypeInitMap ::= [\n\t\"int\":\"0\",\n\t\"long\":\"0\",\n\t\"float\":\"0.0f\",\n\t\"double\":\"0.0\",\n\t\"boolean\":\"false\",\n\t\"byte\":\"0\",\n\t\"short\":\"0\",\n\t\"char\":\"0\",\n\tdefault:\"null\" // anything other than a primitive type is an object\n]\n\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\npackage <file.genPackage>;\n<endif>\n<namedActions.header>\n<if(file.genLean)>\nimport org.antlr.v4.runtime.atn.*;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.*;\n<elseif(file.genContexts)>\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.tree.*;\nimport java.util.List;\nimport java.util.ArrayList;\n<elseif(file.genDFA)>\nimport org.antlr.v4.runtime.atn.*;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.Utils;\n<else>\nimport org.antlr.v4.runtime.atn.*;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.misc.*;\nimport org.antlr.v4.runtime.tree.*;\nimport java.util.List;\nimport java.util.Iterator;\nimport java.util.ArrayList;\n<endif>\n\n<parser>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\npackage <file.genPackage>;\n<endif>\n<header>\nimport org.antlr.v4.runtime.tree.ParseTreeListener;\n\n/**\n * This interface defines a complete listener for a parse tree produced by\n * {@link <file.parserName>}.\n */\npublic interface <file.grammarName>Listener extends ParseTreeListener {\n\t<file.listenerNames:{lname |\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Enter a parse tree produced by the {@code <lname>\\}\n * labeled alternative in {@link <file.parserName><if(file.genLean)>Contexts<endif>#<file.listenerLabelRuleNames.(lname)>\\}.\n<else>\n * Enter a parse tree produced by {@link <file.parserName>#<lname>\\}.\n<endif>\n * @param ctx the parse tree\n */\n\nvoid enter<lname; format=\"cap\">(<file.parserName><if(file.genLean)>Contexts<endif>.<lname; format=\"cap\">Context ctx);\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Exit a parse tree produced by the {@code <lname>\\}\n * labeled alternative in {@link <file.parserName>#<file.listenerLabelRuleNames.(lname)>\\}.\n<else>\n * Exit a parse tree produced by {@link <file.parserName>#<lname>\\}.\n<endif>\n * @param ctx the parse tree\n */\nvoid exit<lname; format=\"cap\">(<file.parserName><if(file.genLean)>Contexts<endif>.<lname; format=\"cap\">Context ctx);}; separator=\"\\n\">\n}\n>>\n\nBaseListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\npackage <file.genPackage>;\n<endif>\n<header>\n\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.TerminalNode;\n\n/**\n * This class provides an empty implementation of {@link <file.grammarName>Listener},\n * which can be extended to create a listener which only needs to handle a subset\n * of the available methods.\n */\n@SuppressWarnings(\"CheckReturnValue\")\npublic class <file.grammarName>BaseListener implements <file.grammarName>Listener {\n\t<file.listenerNames:{lname |\n/**\n * {@inheritDoc\\}\n *\n * \\<p>The default implementation does nothing.\\</p>\n */\n@Override public void enter<lname; format=\"cap\">(<file.parserName><if(file.genLean)>Contexts<endif>.<lname; format=\"cap\">Context ctx) { \\}\n/**\n * {@inheritDoc\\}\n *\n * \\<p>The default implementation does nothing.\\</p>\n */\n@Override public void exit<lname; format=\"cap\">(<file.parserName><if(file.genLean)>Contexts<endif>.<lname; format=\"cap\">Context ctx) { \\}}; separator=\"\\n\">\n\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t@Override public void enterEveryRule(ParserRuleContext ctx) { }\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t@Override public void exitEveryRule(ParserRuleContext ctx) { }\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t@Override public void visitTerminal(TerminalNode node) { }\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t@Override public void visitErrorNode(ErrorNode node) { }\n}\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\npackage <file.genPackage>;\n<endif>\n<header>\nimport org.antlr.v4.runtime.tree.ParseTreeVisitor;\n\n/**\n * This interface defines a complete generic visitor for a parse tree produced\n * by {@link <file.parserName>}.\n *\n * @param \\<T> The return type of the visit operation. Use {@link Void} for\n * operations with no return type.\n */\npublic interface <file.grammarName>Visitor\\<T> extends ParseTreeVisitor\\<T> {\n\t<file.visitorNames:{lname |\n/**\n<if(file.visitorLabelRuleNames.(lname))>\n * Visit a parse tree produced by the {@code <lname>\\}\n * labeled alternative in {@link <file.parserName>#<file.visitorLabelRuleNames.(lname)>\\}.\n<else>\n * Visit a parse tree produced by {@link <file.parserName>#<lname>\\}.\n<endif>\n * @param ctx the parse tree\n * @return the visitor result\n */\nT visit<lname; format=\"cap\">(<file.parserName><if(file.genLean)>Contexts<endif>.<lname; format=\"cap\">Context ctx);}; separator=\"\\n\">\n}\n>>\n\nBaseVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\npackage <file.genPackage>;\n<endif>\n<header>\nimport org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;\n\n/**\n * This class provides an empty implementation of {@link <file.grammarName>Visitor},\n * which can be extended to create a visitor which only needs to handle a subset\n * of the available methods.\n *\n * @param \\<T> The return type of the visit operation. Use {@link Void} for\n * operations with no return type.\n */\n@SuppressWarnings(\"CheckReturnValue\")\npublic class <file.grammarName>BaseVisitor\\<T> extends AbstractParseTreeVisitor\\<T> implements <file.grammarName>Visitor\\<T> {\n\t<file.visitorNames:{lname |\n/**\n * {@inheritDoc\\}\n *\n * \\<p>The default implementation returns the result of calling\n * {@link #visitChildren\\} on {@code ctx\\}.\\</p>\n */\n@Override public T visit<lname; format=\"cap\">(<file.parserName><if(file.genLean)>Contexts<endif>.<lname; format=\"cap\">Context ctx) { return visitChildren(ctx); \\}}; separator=\"\\n\">\n}\n>>\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n// Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\n<if(parser.file.genContexts)>\n<Parser_Contexts(...)>\n<elseif(parser.file.genDFA)>\n<Parser_DFA(...)>\n<else>\n<Parser_(ctor=\"parser_ctor\", ...)>\n<endif>\n>>\n\nParser_Contexts(parser, funcs) ::= <<\npublic abstract class <parser.name>Contexts {\n\t<funcs; separator=\"\\n\">\n}\n>>\n\nParser_DFA(parser, atn) ::= <<\n@SuppressWarnings({\"UnnecessaryUnicodeEscape\", \"UnnecessaryStringEscape\"})\nabstract class <parser.name>DFA {\n\tstatic final DFA[] _decisionToDFA;\n\t<atn>\n}\n>>\n\nParser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<\n@SuppressWarnings({\"all\", \"warnings\", \"unchecked\", \"unused\", \"cast\", \"CheckReturnValue\", \"this-escape\"})\npublic class <parser.name> extends <superClass; null=\"Parser\"> {\n\tstatic { RuntimeMetaData.checkVersion(\"<file.ANTLRVersion>\", RuntimeMetaData.VERSION); }\n\n<if(parser.file.genLean)>\n\tprotected static final DFA[] _decisionToDFA = <parser.name>DFA._decisionToDFA;\n<else>\n\tprotected static final DFA[] _decisionToDFA;\n<endif>\n\tprotected static final PredictionContextCache _sharedContextCache =\n\t\tnew PredictionContextCache();\n\t<if(parser.tokens)>\n\tpublic static final int\n\t\t<parser.tokens:{k | <k>=<parser.tokens.(k)>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\t<if(parser.rules)>\n\tpublic static final int\n\t\t<parser.rules:{r | RULE_<r.name> = <r.index>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\tprivate static String[] makeRuleNames() {\n\t\treturn new String[] {\n\t\t\t<parser.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor>\n\t\t};\n\t}\n\tpublic static final String[] ruleNames = makeRuleNames();\n\n\t<vocabulary(parser.literalNames, parser.symbolicNames)>\n\n\t@Override\n\tpublic String getGrammarFileName() { return \"<parser.grammarFileName>\"; }\n\n\t@Override\n\tpublic String[] getRuleNames() { return ruleNames; }\n\n\t@Override\n\tpublic String getSerializedATN() { return _serializedATN; }\n\n\t@Override\n\tpublic ATN getATN() { return _ATN; }\n\n\t<namedActions.members>\n\t<parser:(ctor)()>\n\t<funcs; separator=\"\\n\">\n\n<if(sempredFuncs)>\n\tpublic boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) {\n\t\tswitch (ruleIndex) {\n\t\t<parser.sempredFuncs.values:{f|\ncase <f.ruleIndex>:\n\treturn <f.name>_sempred((<if(parser.file.genLean)><parser.name>Contexts.<endif><f.ctxType>)_localctx, predIndex);}; separator=\"\\n\">\n\t\t}\n\t\treturn true;\n\t}\n\t<sempredFuncs.values; separator=\"\\n\">\n<endif>\n<if(parser.file.genLean)>\n\tpublic static final String _serializedATN = <parser.name>DFA._serializedATN;\n\tpublic static final ATN _ATN = <parser.name>DFA._ATN;\n<else>\n\t<atn>\n<endif>\n}\n>>\n\nvocabulary(literalNames, symbolicNames) ::= <<\nprivate static String[] makeLiteralNames() {\n\treturn new String[] {\n\t\t<literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n\t};\n}\nprivate static final String[] _LITERAL_NAMES = makeLiteralNames();\nprivate static String[] makeSymbolicNames() {\n\treturn new String[] {\n\t\t<symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n\t};\n}\nprivate static final String[] _SYMBOLIC_NAMES = makeSymbolicNames();\npublic static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);\n\n/**\n * @deprecated Use {@link #VOCABULARY} instead.\n */\n@Deprecated\npublic static final String[] tokenNames;\nstatic {\n\ttokenNames = new String[_SYMBOLIC_NAMES.length];\n\tfor (int i = 0; i \\< tokenNames.length; i++) {\n\t\ttokenNames[i] = VOCABULARY.getLiteralName(i);\n\t\tif (tokenNames[i] == null) {\n\t\t\ttokenNames[i] = VOCABULARY.getSymbolicName(i);\n\t\t}\n\t\tif (tokenNames[i] == null) {\n\t\t\ttokenNames[i] = \"\\<INVALID>\";\n\t\t}\n\t}\n}\n\n@Override\n@Deprecated\npublic String[] getTokenNames() { return tokenNames; }\n\n@Override\npublic Vocabulary getVocabulary() { return VOCABULARY; }\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\n@Override\npublic void action(RuleContext _localctx, int ruleIndex, int actionIndex) {\n\tswitch (ruleIndex) {\n\t<recog.actionFuncs.values:{f|\ncase <f.ruleIndex>:\n\t<f.name>_action((<f.ctxType>)_localctx, actionIndex);\n\tbreak;}; separator=\"\\n\">\n\t}\n}\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<if(sempredFuncs)>\n@Override\npublic boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) {\n\tswitch (ruleIndex) {\n\t<recog.sempredFuncs.values:{f|\ncase <f.ruleIndex>:\n\treturn <f.name>_sempred((<f.ctxType>)_localctx, predIndex);}; separator=\"\\n\">\n\t}\n\treturn true;\n}\n<sempredFuncs.values; separator=\"\\n\">\n<endif>\n>>\n\nparser_ctor(p) ::= <<\npublic <p.name>(TokenStream input) {\n\tsuper(input);\n\t_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);\n}\n>>\n\n/* This generates a private method since the actionIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\nprivate void <r.name>_action(<r.ctxType> _localctx, int actionIndex) {\n\tswitch (actionIndex) {\n\t<actions:{index|\ncase <index>:\n\t<actions.(index)>\n\tbreak;}; separator=\"\\n\">\n\t}\n}\n>>\n\n/* This generates a private method since the predIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\nprivate boolean <r.name>_sempred(<if(parser.file.genLean)><parser.name>Contexts.<endif><r.ctxType> _localctx, int predIndex) {\n\tswitch (predIndex) {\n\t<actions:{index|\ncase <index>:\n\treturn <actions.(index)>;}; separator=\"\\n\">\n\t}\n\treturn true;\n}\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<\n<if(!parser.file.genLean)>\n<ruleCtx>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n<endif>\n\n<if(!parser.file.genContexts)>\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public final <endif><if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\",\">) throws RecognitionException {\n\t<if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType> _localctx = new <if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType>(_ctx, getState()<currentRule.args:{a | , <a.escapedName>}>);\n\tenterRule(_localctx, <currentRule.startState>, RULE_<currentRule.name>);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tint _alt;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t<if(exceptions)>\n\t} <exceptions; separator=\"\\n\"> finally {\n\t<else>\n\t} catch (RecognitionException re) {\n\t\t_localctx.exception = re;\n\t\t_errHandler.reportError(this, re);\n\t\t_errHandler.recover(this, re);\n\t} finally {\n\t<endif>\n\t\t<finallyAction>\n\t\texitRule();\n\t}\n\treturn _localctx;\n}\n<endif>\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,\n\tnamedActions,finallyAction,postamble) ::=\n<<\n\n<if(!parser.file.genLean)>\n<ruleCtx>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n<endif>\n\n<if(!parser.file.genContexts)>\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public final <endif><if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\", \">) throws RecognitionException {\n\treturn <currentRule.escapedName>(0<currentRule.args:{a | , <a.escapedName>}>);\n}\n\nprivate <if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType> <currentRule.escapedName>(int _p<args:{a | , <a>}>) throws RecognitionException {\n\tParserRuleContext _parentctx = _ctx;\n\tint _parentState = getState();\n\t<if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType> _localctx = new <if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType>(_ctx, _parentState<currentRule.args:{a | , <a.escapedName>}>);\n\t<if(parser.file.genLean)><parser.name>Contexts.<endif><currentRule.ctxType> _prevctx = _localctx;\n\tint _startState = <currentRule.startState>;\n\tenterRecursionRule(_localctx, <currentRule.startState>, RULE_<currentRule.name>, _p);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tint _alt;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\tcatch (RecognitionException re) {\n\t\t_localctx.exception = re;\n\t\t_errHandler.reportError(this, re);\n\t\t_errHandler.recover(this, re);\n\t}\n\tfinally {\n\t\t<finallyAction>\n\t\tunrollRecursionContexts(_parentctx);\n\t}\n\treturn _localctx;\n}\n<endif>\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>_localctx = new <if(parser.file.genLean)><parser.name>Contexts.<endif><currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(_localctx);<endif>\nenterOuterAlt(_localctx, <currentOuterMostAltCodeBlock.alt.altNum>);\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n{\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n}\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = _input.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch (_input.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\">\ndefault:\n\t<error>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler.sync(this);\nswitch (_input.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\">\ndefault:\n\tbreak;\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler.sync(this);\n<preamble; separator=\"\\n\">\nif (<expr>) {\n\t<alts; separator=\"\\n\">\n}\n<!else if ( !(<followExpr>) ) <error>!>\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler.sync(this);\n<preamble; separator=\"\\n\">\nwhile (<loopExpr>) {\n\t<alts; separator=\"\\n\">\n\tsetState(<choice.loopBackStateNumber>);\n\t_errHandler.sync(this);\n\t<iteration>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nsetState(<choice.blockStartStateNumber>); <! alt block decision !>\n_errHandler.sync(this);\n<preamble; separator=\"\\n\">\ndo {\n\t<alts; separator=\"\\n\">\n\tsetState(<choice.stateNumber>); <! loopback/exit decision !>\n\t_errHandler.sync(this);\n\t<iteration>\n} while ( <loopExpr> );\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = _input.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch ( getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx) ) {\n<alts:{alt |\ncase <i>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler.sync(this);\nswitch ( getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx) ) {\n<alts:{alt |\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n}\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\nsetState(<choice.stateNumber>);\n_errHandler.sync(this);\n_alt = getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx);\nwhile ( _alt!=<choice.exitAlt> && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) {\n\tif ( _alt==1<if(!choice.ast.greedy)>+1<endif> ) {\n\t\t<iteration>\n\t\t<alts> <! should only be one !>\n\t}\n\tsetState(<choice.loopBackStateNumber>);\n\t_errHandler.sync(this);\n\t_alt = getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx);\n}\n>>\n\nPlusBlock(choice, alts, error) ::= <<\nsetState(<choice.blockStartStateNumber>); <! alt block decision !>\n_errHandler.sync(this);\n_alt = 1<if(!choice.ast.greedy)>+1<endif>;\ndo {\n\tswitch (_alt) {\n\t<alts:{alt|\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n\tdefault:\n\t\t<error>\n\t}\n\tsetState(<choice.loopBackStateNumber>); <! loopback/exit decision !>\n\t_errHandler.sync(this);\n\t_alt = getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx);\n} while ( _alt!=<choice.exitAlt> && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER );\n>>\n\nSync(s) ::= \"sync(<s.expecting.name>);\"\n\nThrowNoViableAlt(t) ::= \"throw new NoViableAltException(this);\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount>) & ~0x3f) == 0\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShift(s.varName, bits.shift)>})> && ((1L \\<\\< <offsetShift(s.varName, bits.shift)>) & <bits.calculated>L) != 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShift(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName>==<t.name>}; separator=\" || \">\n%>\n\ncases(tokens) ::= <<\n<tokens:{t | case <t.name>:}; separator=\"\\n\">\n>>\n\nInvokeRule(r, argExprsChunks) ::= <<\nsetState(<r.stateNumber>);\n<if(r.labels)><r.labels:{l | <labelref(l)> = }><endif><r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>);\n>>\n\nMatchToken(m) ::= <<\nsetState(<m.stateNumber>);\n<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>match(<m.escapedName>);\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nsetState(<m.stateNumber>);\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>_input.LT(1);<endif>\n<capture>\nif ( <if(invert)><m.varName> \\<= 0 || <else>!<endif>(<expr>) ) {\n\t<if(m.labels)><m.labels:{l | <labelref(l)> = (Token)}><endif>_errHandler.recoverInline(this);\n}\nelse {\n\tif ( _input.LA(1)==Token.EOF ) matchedEOF = true;\n\t_errHandler.reportMatch(this);\n\tconsume();\n}\n>>\n\nWildcard(w) ::= <<\nsetState(<w.stateNumber>);\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>matchWildcard();\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\nsetState(<p.stateNumber>);\nif (!(<chunks>)) throw new FailedPredicateException(this, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>);\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n\t<catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"skip();\"\nLexerMoreCommand()  ::= \"more();\"\nLexerPopModeCommand() ::= \"popMode();\"\n\nLexerTypeCommand(arg, grammar)      ::= \"_type = <arg>;\"\nLexerChannelCommand(arg, grammar)   ::= \"_channel = <arg>;\"\nLexerModeCommand(arg, grammar)      ::= \"_mode = <arg>;\"\nLexerPushModeCommand(arg, grammar)  ::= \"pushMode(<arg>);\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"_localctx.<a.escapedName>\"\nLocalRef(a) ::= \"_localctx.<a.escapedName>\"\nRetValueRef(a) ::= \"_localctx.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>.<a.dict>.<a.escapedName>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nLabelRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nListLabelRef(t) ::= \"<ctx(t)>.<ListLabelName(t.escapedName)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>.<s.escapedName> = <rhsChunks>;\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={Token}>\"\n\nTokenPropertyRef_text(t) ::= \"(<ctx(t)>.<t.label>!=null?<ctx(t)>.<t.label>.getText():null)\"\nTokenPropertyRef_type(t) ::= \"(<ctx(t)>.<t.label>!=null?<ctx(t)>.<t.label>.getType():0)\"\nTokenPropertyRef_line(t) ::= \"(<ctx(t)>.<t.label>!=null?<ctx(t)>.<t.label>.getLine():0)\"\nTokenPropertyRef_pos(t) ::= \"(<ctx(t)>.<t.label>!=null?<ctx(t)>.<t.label>.getCharPositionInLine():0)\"\nTokenPropertyRef_channel(t) ::= \"(<ctx(t)>.<t.label>!=null?<ctx(t)>.<t.label>.getChannel():0)\"\nTokenPropertyRef_index(t) ::= \"(<ctx(t)>.<t.label>!=null?<ctx(t)>.<t.label>.getTokenIndex():0)\"\nTokenPropertyRef_int(t) ::= \"(<ctx(t)>.<t.label>!=null?Integer.valueOf(<ctx(t)>.<t.label>.getText()):0)\"\n\nRulePropertyRef_start(r) ::= \"(<ctx(r)>.<r.label>!=null?(<ctx(r)>.<r.label>.start):null)\"\nRulePropertyRef_stop(r)\t ::= \"(<ctx(r)>.<r.label>!=null?(<ctx(r)>.<r.label>.stop):null)\"\nRulePropertyRef_text(r)\t ::= \"(<ctx(r)>.<r.label>!=null?_input.getText(<ctx(r)>.<r.label>.start,<ctx(r)>.<r.label>.stop):null)\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>.<r.label>\"\nRulePropertyRef_parser(r)\t ::= \"this\"\n\nThisRulePropertyRef_start(r) ::= \"_localctx.start\"\nThisRulePropertyRef_stop(r)\t ::= \"_localctx.stop\"\nThisRulePropertyRef_text(r)\t ::= \"_input.getText(_localctx.start, _input.LT(-1))\"\nThisRulePropertyRef_ctx(r)\t ::= \"_localctx\"\nThisRulePropertyRef_parser(r)\t ::= \"this\"\n\nNonLocalAttrRef(s)\t\t ::= \"((<s.ruleName; format=\\\"cap\\\">Context)getInvokingContext(<s.ruleIndex>)).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks)\t  ::=\n\t\"((<s.ruleName; format=\\\"cap\\\">Context)getInvokingContext(<s.ruleIndex>)).<s.escapedName> = <rhsChunks>;\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>.<a.listName>.add(<labelref(a.label)>);\"\n\nTokenDecl(t) ::= \"<TokenLabelType()> <t.escapedName>\"\nTokenTypeDecl(t) ::= \"int <t.escapedName>;\"\nTokenListDecl(t) ::= \"List\\<Token> <t.escapedName> = new ArrayList\\<Token>()\"\nRuleContextDecl(r) ::= \"<r.ctxName> <r.escapedName>\"\nRuleContextListDecl(rdecl) ::= \"List\\<<rdecl.ctxName>> <rdecl.escapedName> = new ArrayList\\<<rdecl.ctxName>>()\"\n\nContextTokenGetterDecl(t)      ::=\n    \"public TerminalNode <t.name>() { return getToken(<parser.name>.<t.name>, 0); }\"\nContextTokenListGetterDecl(t)  ::=\n    \"public List\\<TerminalNode> <t.name>() { return getTokens(<parser.name>.<t.name>); }\"\nContextTokenListIndexedGetterDecl(t)  ::= <<\npublic TerminalNode <t.name>(int i) {\n\treturn getToken(<parser.name>.<t.name>, i);\n}\n>>\nContextRuleGetterDecl(r)       ::= <<\npublic <r.ctxName> <r.escapedName>() {\n\treturn getRuleContext(<r.ctxName>.class,0);\n}\n>>\nContextRuleListGetterDecl(r)   ::= <<\npublic List\\<<r.ctxName>\\> <r.escapedName>() {\n\treturn getRuleContexts(<r.ctxName>.class);\n}\n>>\nContextRuleListIndexedGetterDecl(r)   ::= <<\npublic <r.ctxName> <r.escapedName>(int i) {\n\treturn getRuleContext(<r.ctxName>.class,i);\n}\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/** The rule context name is the rule followed by a suffix; e.g.,\n *\tr becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"<tokenName>\"\nImplicitRuleLabel(ruleName)\t  ::= \"<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = _input.LT(1);\"\nCaptureNextTokenType(d) ::= \"<d.varName> = _input.LA(1);\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures)\n\t::= <<\n@SuppressWarnings(\"CheckReturnValue\")\npublic static class <struct.escapedName> extends <if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif><if(interfaces)> implements <interfaces; separator=\", \"><endif> {\n\t<attrs:{a | public <a>;}; separator=\"\\n\">\n\t<getters:{g | <g>}; separator=\"\\n\">\n\t<if(ctorAttrs)>public <struct.escapedName>(ParserRuleContext parent, int invokingState) { super(parent, invokingState); }<endif>\n\tpublic <struct.escapedName>(ParserRuleContext parent, int invokingState<ctorAttrs:{a | , <a>}>) {\n\t\tsuper(parent, invokingState);\n\t\t<struct.ctorAttrs:{a | this.<a.escapedName> = <a.escapedName>;}; separator=\"\\n\">\n\t}\n\t@Override public int getRuleIndex() { return <if(parser.file.genContexts)><parser.name>.<endif>RULE_<struct.derivedFromName>; }\n<if(struct.provideCopyFrom)> <! don't need copy unless we have subclasses !>\n\tpublic <struct.escapedName>() { }\n\tpublic void copyFrom(<struct.escapedName> ctx) {\n\t\tsuper.copyFrom(ctx);\n\t\t<struct.attrs:{a | this.<a.escapedName> = ctx.<a.escapedName>;}; separator=\"\\n\">\n\t}\n<endif>\n\t<dispatchMethods; separator=\"\\n\">\n\t<extensionMembers; separator=\"\\n\">\n}\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\n@SuppressWarnings(\"CheckReturnValue\")\npublic static class <struct.escapedName> extends <currentRule.name; format=\"cap\">Context {\n\t<attrs:{a | public <a>;}; separator=\"\\n\">\n\t<getters:{g | <g>}; separator=\"\\n\">\n\tpublic <struct.escapedName>(<currentRule.name; format=\"cap\">Context ctx) { copyFrom(ctx); }\n\t<dispatchMethods; separator=\"\\n\">\n}\n>>\n\nListenerDispatchMethod(method) ::= <<\n@Override\npublic void <if(method.isEnter)>enter<else>exit<endif>Rule(ParseTreeListener listener) {\n\tif ( listener instanceof <parser.grammarName>Listener ) ((<parser.grammarName>Listener)listener).<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">(this);\n}\n>>\n\nVisitorDispatchMethod(method) ::= <<\n@Override\npublic \\<T> T accept(ParseTreeVisitor\\<? extends T> visitor) {\n\tif ( visitor instanceof <parser.grammarName>Visitor ) return ((<parser.grammarName>Visitor\\<? extends T>)visitor).visit<struct.derivedFromName; format=\"cap\">(this);\n\telse return visitor.visitChildren(this);\n}\n>>\n\nAttributeDecl(d) ::= \"<d.type> <d.escapedName><if(d.initValue)> = <d.initValue><endif>\"\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if(!x.isLocal)>((<if(parser.file.genLean)><parser.name>Contexts.<endif><x.ctx.name>)_localctx).<endif><x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"((<if(parser.file.genLean)><parser.name>Contexts.<endif><actionChunk.ctx.name>)_localctx)\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"precpred(_ctx, <opPrec>)\"\nrecRuleSetReturnAction(src,name)\t  ::= \"$<name>=$<src>.<name>;\"\nrecRuleSetStopToken()                 ::= \"_ctx.stop = _input.LT(-1);\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\n_localctx = new <if(parser.file.genLean)><parser.name>Contexts.<endif><ctxName>Context(_parentctx, _parentState);\n<if(label)>\n<if(isListLabel)>\n_localctx.<label>.add(_prevctx);\n<else>\n_localctx.<label> = _prevctx;\n<endif>\n<endif>\npushNewRecursionContext(_localctx, _startState, RULE_<ruleName>);\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\n_localctx = new <if(parser.file.genLean)><parser.name>Contexts.<endif><currentAltLabel; format=\"cap\">Context(new <if(parser.file.genLean)><parser.name>Contexts.<endif><ruleName; format=\"cap\">Context(_parentctx, _parentState));\n<if(label)>\n<if(isListLabel)>\n((<currentAltLabel; format=\"cap\">Context)_localctx).<label>.add(_prevctx);\n<else>\n((<currentAltLabel; format=\"cap\">Context)_localctx).<label> = _prevctx;\n<endif>\n<endif>\npushNewRecursionContext(_localctx, _startState, RULE_<ruleName>);\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\n_localctx = new <if(parser.file.genLean)><parser.name>Contexts.<endif><ctxName>Context(_localctx);\n_ctx = _localctx;\n_prevctx = _localctx;\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif ( _parseListeners!=null ) triggerExitRuleEvent();\n_prevctx = _localctx;\n>>\n\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\n<if(lexerFile.genPackage)>\npackage <lexerFile.genPackage>;\n<endif>\n<namedActions.header>\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.atn.*;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.*;\n\n<lexer>\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\n@SuppressWarnings({\"all\", \"warnings\", \"unchecked\", \"unused\", \"cast\", \"CheckReturnValue\", \"this-escape\"})\npublic class <lexer.name> extends <superClass; null=\"Lexer\"> {\n\tstatic { RuntimeMetaData.checkVersion(\"<lexerFile.ANTLRVersion>\", RuntimeMetaData.VERSION); }\n\n\tprotected static final DFA[] _decisionToDFA;\n\tprotected static final PredictionContextCache _sharedContextCache =\n\t\tnew PredictionContextCache();\n\t<if(lexer.tokens)>\n\tpublic static final int\n\t\t<lexer.tokens:{k | <k>=<lexer.tokens.(k)>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\t<if(lexer.escapedChannels)>\n\tpublic static final int\n\t\t<lexer.escapedChannels:{c | <c>=<lexer.escapedChannels.(c)>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\t<if(rest(lexer.escapedModeNames))>\n\tpublic static final int\n\t\t<rest(lexer.escapedModeNames):{m | <m>=<i>}; separator=\", \", wrap, anchor>;\n\t<endif>\n\tpublic static String[] channelNames = {\n\t\t\"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"<if (lexer.channelNames)>, <lexer.channelNames:{c| \"<c>\"}; separator=\", \", wrap, anchor><endif>\n\t};\n\n\tpublic static String[] modeNames = {\n\t\t<lexer.modes:{m| \"<m>\"}; separator=\", \", wrap, anchor>\n\t};\n\n\tprivate static String[] makeRuleNames() {\n\t\treturn new String[] {\n\t\t\t<lexer.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor>\n\t\t};\n\t}\n\tpublic static final String[] ruleNames = makeRuleNames();\n\n\t<vocabulary(lexer.literalNames, lexer.symbolicNames)>\n\n\t<namedActions.members>\n\n\tpublic <lexer.name>(CharStream input) {\n\t\tsuper(input);\n\t\t_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);\n\t}\n\n\t@Override\n\tpublic String getGrammarFileName() { return \"<lexer.grammarFileName>\"; }\n\n\t@Override\n\tpublic String[] getRuleNames() { return ruleNames; }\n\n\t@Override\n\tpublic String getSerializedATN() { return _serializedATN; }\n\n\t@Override\n\tpublic String[] getChannelNames() { return channelNames; }\n\n\t@Override\n\tpublic String[] getModeNames() { return modeNames; }\n\n\t@Override\n\tpublic ATN getATN() { return _ATN; }\n\n\t<dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n\t<atn>\n}\n>>\n\nSerializedJavaATN(model) ::= <<\n<if(rest(model.segments))>\n<! requires segmented representation !>\n<model.segments:{segment|private static final String _serializedATNSegment<i0> =\n\t\"<segment; wrap={\"+<\\n><\\t>\"}>\";}; separator=\"\\n\">\npublic static final String _serializedATN = Utils.join(\n\tnew String[] {\n\t\t<model.segments:{segment | _serializedATNSegment<i0>}; separator=\",\\n\">\n\t},\n\t\"\"\n);\n<else>\n<! only one segment, can be inlined !>\npublic static final String _serializedATN =\n\t\"<model.serialized; wrap={\"+<\\n><\\t>\"}>\";\n<endif>\npublic static final ATN _ATN =\n\tnew ATNDeserializer().deserialize(_serializedATN.toCharArray());\nstatic {\n\t_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];\n\tfor (int i = 0; i \\< _ATN.getNumberOfDecisions(); i++) {\n\t\t_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);\n\t}\n<!\torg.antlr.v4.tool.DOTGenerator dot = new org.antlr.v4.tool.DOTGenerator(null);!>\n<!\tSystem.out.println(dot.getDOT(_ATN.decisionToState.get(0), ruleNames, false));!>\n<!\tSystem.out.println(dot.getDOT(_ATN.ruleToStartState[2], ruleNames, false));!>\n}\n>>\n\n/** Using a type to init value map, try to init a type; if not in table\n *\tmust be an object, default value is \"null\".\n */\ninitValue(typeName) ::= <<\n<javaTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".java\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/JavaScript/JavaScript.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  Copyright (c) 2014 Eric Vergnaud\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** ANTLR tool checks output templates are compatible with tool code generation.\n *  For now, a simple string match used on x.y of x.y.z scheme.\n *  Must match Tool.VERSION during load to templates.\n *\n *  REQUIRED.\n */\n\njavascriptTypeInitMap ::= [\n\t\"bool\":\"false\",\n\t\"int\":\"0\",\n\t\"float\":\"0.0\",\n\t\"str\":\"\",\n\tdefault:\"{}\" // anything other than a primitive type is an object\n]\n\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport antlr4 from 'antlr4';\n<if(file.genListener)>\nimport <file.grammarName>Listener from './<file.grammarName>Listener.js';\n<endif>\n<if(file.genVisitor)>\nimport <file.grammarName>Visitor from './<file.grammarName>Visitor.js';\n<endif>\n\n<namedActions.header>\n<parser>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport antlr4 from 'antlr4';\n\n// This class defines a complete listener for a parse tree produced by <file.parserName>.\nexport default class <file.grammarName>Listener extends antlr4.tree.ParseTreeListener {\n\n<file.listenerNames:{lname |\n\t// Enter a parse tree produced by <file.parserName>#<lname>.\n\tenter<lname; format=\"cap\">(ctx) {\n\t\\}\n\n\t// Exit a parse tree produced by <file.parserName>#<lname>.\n\texit<lname; format=\"cap\">(ctx) {\n\t\\}\n\n}; separator=\"\\n\">\n\n}\n>>\n\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nimport antlr4 from 'antlr4';\n\n// This class defines a complete generic visitor for a parse tree produced by <file.parserName>.\n\nexport default class <file.grammarName>Visitor extends antlr4.tree.ParseTreeVisitor {\n\n<file.visitorNames:{lname |\n\t// Visit a parse tree produced by <file.parserName>#<lname>.\n\tvisit<lname; format=\"cap\">(ctx) {\n\t  return this.visitChildren(ctx);\n\t\\}\n\n}; separator=\"\\n\">\n\n}\n>>\n\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n// Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n// jshint ignore: start\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\n<if(superClass)>\nimport <superClass> from './<superClass>.js';\n<endif>\n\n<atn>\n\nconst atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);\n\nconst decisionsToDFA = atn.decisionToState.map( (ds, index) => new antlr4.dfa.DFA(ds, index) );\n\nconst sharedContextCache = new antlr4.atn.PredictionContextCache();\n\nexport default class <parser.name> extends <superClass; null=\"antlr4.Parser\"> {\n\n    static grammarFileName = \"<parser.grammarFileName>\";\n    static literalNames = [ <parser.literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n    static symbolicNames = [ <parser.symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n    static ruleNames = [ <parser.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor> ];\n\n    constructor(input) {\n        super(input);\n        this._interp = new antlr4.atn.ParserATNSimulator(this, atn, decisionsToDFA, sharedContextCache);\n        this.ruleNames = <parser.name>.ruleNames;\n        this.literalNames = <parser.name>.literalNames;\n        this.symbolicNames = <parser.name>.symbolicNames;\n        <namedActions.members>\n    }\n\n    <if(sempredFuncs)>\n    sempred(localctx, ruleIndex, predIndex) {\n    \tswitch(ruleIndex) {\n    \t<parser.sempredFuncs.values:{f | case <f.ruleIndex>:\n    \t\treturn this.<f.name>_sempred(localctx, predIndex);}; separator=\"\\n\">\n        default:\n            throw \"No predicate with index:\" + ruleIndex;\n       }\n    }\n\n    <sempredFuncs.values; separator=\"\\n\">\n    <endif>\n\n\t<funcs; separator=\"\\n\">\n\n}\n\n<parser.name>.EOF = antlr4.Token.EOF;\n<if(parser.tokens)>\n<parser.tokens:{k | <parser.name>.<k> = <parser.tokens.(k)>;}; separator=\"\\n\", wrap, anchor>\n<endif>\n\n<if(parser.rules)>\n<parser.rules:{r | <parser.name>.RULE_<r.name> = <r.index>;}; separator=\"\\n\", wrap, anchor>\n<endif>\n\n<funcs:{f | <ruleContexts(f)>}; separator=\"\\n\">\n\n<! Define fields of this parser to export the context classes !>\n<parser.funcs:{f | <parser.name>.<f.ctxType> = <f.ctxType>; }; separator=\"\\n\">\n\n>>\n\nruleContexts(currentRule) ::= <<\n<currentRule.ruleCtx>\n\n<currentRule.altLabelCtxs:{l | <currentRule.altLabelCtxs.(l)>}; separator=\"\\n\">\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\n<lexer.name>.prototype.action = function(localctx, ruleIndex, actionIndex) {\n\tswitch (ruleIndex) {\n\t<recog.actionFuncs.values:{f|\ncase <f.ruleIndex>:\n\tthis.<f.name>_action(localctx, actionIndex);\n\tbreak;}; separator=\"\\n\">\n\tdefault:\n\t\tthrow \"No registered action for:\" + ruleIndex;\n\t}\n};\n\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<if(sempredFuncs)>\n<lexer.name>.prototype.sempred = function(localctx, ruleIndex, predIndex) {\n\tswitch (ruleIndex) {\n\t\t<recog.sempredFuncs.values:{f| case <f.ruleIndex>:\n\treturn this.<f.name>_sempred(localctx, predIndex);}; separator=\"\\n\">\n    \tdefault:\n    \t\tthrow \"No registered predicate for:\" + ruleIndex;\n    }\n};\n\n<sempredFuncs.values; separator=\"\\n\">\n<endif>\n>>\n\n\n/* This generates a private method since the actionIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\n\n<lexer.name>.prototype.<r.name>_action = function(localctx , actionIndex) {\n\tswitch (actionIndex) {\n\t<actions:{index|\ncase <index>:\n\t<actions.(index)>\n\tbreak;}; separator=\"\\n\">\n\tdefault:\n\t\tthrow \"No registered action for:\" + actionIndex;\n\t}\n};\n>>\n\n/* This generates a private method since the predIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\n<if (r.factory.g.lexer)><lexer.name>.prototype.<r.name>_sempred = function<else><r.name>_sempred<endif>(localctx, predIndex) {\n\tswitch(predIndex) {\n\t\t<actions:{index| case <index>:\n\treturn <actions.(index)>;}; separator=\"\\n\">\n\t\tdefault:\n\t\t\tthrow \"No predicate with index:\" + predIndex;\n\t}\n};\n\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<\n\n\n<currentRule.escapedName>(<currentRule.args:{a | <a.escapedName>}; separator=\", \">) {\n    let localctx = new <currentRule.ctxType>(this, this._ctx, this.state<currentRule.args:{a | , <a.escapedName>}>);\n    this.enterRule(localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.name>);\n    <namedActions.init>\n    <locals; separator=\"\\n\">\n    try {\n        <code>\n        <postamble; separator=\"\\n\">\n        <namedActions.after>\n    }<if(exceptions)>\n    <exceptions; separator=\"\\n\">\n    <else> catch (re) {\n    \tif(re instanceof antlr4.error.RecognitionException) {\n\t        localctx.exception = re;\n\t        this._errHandler.reportError(this, re);\n\t        this._errHandler.recover(this, re);\n\t    } else {\n\t    \tthrow re;\n\t    }\n    }<endif> finally {\n        <finallyAction>\n        this.exitRule();\n    }\n    return localctx;\n}\n\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,\n\tnamedActions,finallyAction,postamble) ::=\n<<\n\n<currentRule.escapedName>(_p<if(currentRule.args)>, <args:{a | , <a>}><endif>) {\n\tif(_p===undefined) {\n\t    _p = 0;\n\t}\n    const _parentctx = this._ctx;\n    const _parentState = this.state;\n    let localctx = new <currentRule.ctxType>(this, this._ctx, _parentState<args:{a | , <a.escapedName>}>);\n    let _prevctx = localctx;\n    const _startState = <currentRule.startState>;\n    this.enterRecursionRule(localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.name>, _p);\n    <namedActions.init>\n    <locals; separator=\"\\n\">\n    try {\n        <code>\n        <postamble; separator=\"\\n\">\n        <namedActions.after>\n    } catch( error) {\n        if(error instanceof antlr4.error.RecognitionException) {\n\t        localctx.exception = error;\n\t        this._errHandler.reportError(this, error);\n\t        this._errHandler.recover(this, error);\n\t    } else {\n\t    \tthrow error;\n\t    }\n    } finally {\n        <finallyAction>\n        this.unrollRecursionContexts(_parentctx)\n    }\n    return localctx;\n}\n\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>localctx = new <currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(this, localctx);<endif>\nthis.enterOuterAlt(localctx, <currentOuterMostAltCodeBlock.alt.altNum>);\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = this._input.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch(this._input.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n    <alt>\n    break;}; separator=\"\\n\">\ndefault:\n    <error>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\nswitch (this._input.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\">\ndefault:\n\tbreak;\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<preamble; separator=\"\\n\">\nif(<expr>) {\n    <alts; separator=\"\\n\">\n}\n<!else if ( !(<followExpr>) ) <error>!>\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<preamble; separator=\"\\n\">\nwhile(<loopExpr>) {\n    <alts; separator=\"\\n\">\n    this.state = <choice.loopBackStateNumber>;\n    this._errHandler.sync(this);\n    <iteration>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nthis.state = <choice.blockStartStateNumber>; <! alt block decision !>\nthis._errHandler.sync(this);\n<preamble; separator=\"\\n\">\ndo {\n    <alts; separator=\"\\n\">\n    this.state = <choice.stateNumber>; <! loopback/exit decision !>\n    this._errHandler.sync(this);\n    <iteration>\n} while(<loopExpr>);\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = _input.LT(1)<endif>\n<preamble; separator=\"\\n\">\nvar la_ = this._interp.adaptivePredict(this._input,<choice.decision>,this._ctx);\nswitch(la_) {\n<alts:{alt |\ncase <i>:\n    <alt>\n    break;\n}; separator=\"\\n\">\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\nvar la_ = this._interp.adaptivePredict(this._input,<choice.decision>,this._ctx);\n<alts:{alt |\nif(la_===<i><if(!choice.ast.greedy)>+1<endif>) {\n    <alt>\n}; separator=\"\\n} else \">\n}\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\nvar _alt = this._interp.adaptivePredict(this._input,<choice.decision>,this._ctx)\nwhile(_alt!=<choice.exitAlt> && _alt!=antlr4.atn.ATN.INVALID_ALT_NUMBER) {\n    if(_alt===1<if(!choice.ast.greedy)>+1<endif>) {\n        <iteration>\n        <alts> <! should only be one !>\n    }\n    this.state = <choice.loopBackStateNumber>;\n    this._errHandler.sync(this);\n    _alt = this._interp.adaptivePredict(this._input,<choice.decision>,this._ctx);\n}\n\n>>\n\nPlusBlock(choice, alts, error) ::= <<\nthis.state = <choice.blockStartStateNumber>; <! alt block decision !>\nthis._errHandler.sync(this);\nvar _alt = 1<if(!choice.ast.greedy)>+1<endif>;\ndo {\n\tswitch (_alt) {\n\t<alts:{alt|\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n\tdefault:\n\t\t<error>\n\t}\n\tthis.state = <choice.loopBackStateNumber>; <! loopback/exit decision !>\n\tthis._errHandler.sync(this);\n\t_alt = this._interp.adaptivePredict(this._input,<choice.decision>, this._ctx);\n} while ( _alt!=<choice.exitAlt> && _alt!=antlr4.atn.ATN.INVALID_ALT_NUMBER );\n>>\n\nSync(s) ::= \"sync(<s.expecting.name>)\"\n\nThrowNoViableAlt(t) ::= \"throw new antlr4.error.NoViableAltException(this);\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Javascript language spec - shift operators are 32 bits long max\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount>) & ~0x1f) === 0\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShiftVar(s.varName, bits.shift)>})> && ((1 \\<\\< <offsetShiftVar(s.varName, bits.shift)>) & <bits.calculated>) !== 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShiftVar(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\noffsetShiftType(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<parser.name>.<shiftAmount> - <offset>)<else><parser.name>.<shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName>===<t.type>}; separator=\" || \">\n%>\n\ncases(tokens) ::= <<\n<tokens:{t | case <t.type>:}; separator=\"\\n\">\n>>\n\nInvokeRule(r, argExprsChunks) ::= <<\nthis.state = <r.stateNumber>;\n<if(r.labels)><r.labels:{l | <labelref(l)> = }><endif>this.<r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>);\n>>\n\nMatchToken(m) ::= <<\nthis.state = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>this.match(<parser.name>.<m.name>);\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nthis.state = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>this._input.LT(1);<endif>\n<capture>\n<if(invert)>if(<m.varName>\\<=0 || <expr>)<else>if(!(<expr>))<endif> {\n    <if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>this._errHandler.recoverInline(this);\n}\nelse {\n\tthis._errHandler.reportMatch(this);\n    this.consume();\n}\n>>\n\nWildcard(w) ::= <<\nthis.state = <w.stateNumber>;\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>this.matchWildcard();\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\nthis.state = <p.stateNumber>;\nif (!( <chunks>)) {\n    throw new antlr4.error.FailedPredicateException(this, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>);\n}\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n\t<catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"this.skip();\"\nLexerMoreCommand()  ::= \"this.more();\"\nLexerPopModeCommand() ::= \"this.popMode();\"\nLexerTypeCommand(arg, grammar)      ::= \"this._type = <arg>;\"\nLexerChannelCommand(arg, grammar)   ::= \"this._channel = <arg>;\"\nLexerModeCommand(arg, grammar)      ::= \"this._mode = <arg>;\"\nLexerPushModeCommand(arg, grammar)  ::= \"this.pushMode(<arg>);\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"localctx.<a.escapedName>\"\nLocalRef(a) ::= \"localctx.<a.escapedName>\"\nRetValueRef(a) ::= \"localctx.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>.<a.dict>.<a.escapedName>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nLabelRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nListLabelRef(t) ::= \"<ctx(t)>.<ListLabelName(t.escapedName)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>.<s.escapedName> = <rhsChunks>\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={Token}>\"\n\nTokenPropertyRef_text(t) ::= \"(<ctx(t)>.<t.label> == null ? null : <ctx(t)>.<t.label>.text)\"\nTokenPropertyRef_type(t) ::= \"(<ctx(t)>.<t.label> == null ? 0 : <ctx(t)>.<t.label>.type)\"\nTokenPropertyRef_line(t) ::= \"(<ctx(t)>.<t.label> == null ? 0 : <ctx(t)>.<t.label>.line)\"\nTokenPropertyRef_pos(t) ::= \"(<ctx(t)>.<t.label> == null ? 0 : <ctx(t)>.<t.label>.column)\"\nTokenPropertyRef_channel(t) ::= \"(<ctx(t)>.<t.label> == null ? 0 : <ctx(t)>.<t.label>.channel)\"\nTokenPropertyRef_index(t) ::= \"(<ctx(t)>.<t.label> == null ? 0 : <ctx(t)>.<t.label>.tokenIndex)\"\nTokenPropertyRef_int(t) ::= \"(<ctx(t)>.<t.label> == null ? 0 : parseInt(<ctx(t)>.<t.label>.text))\"\n\nRulePropertyRef_start(r) ::= \"(<ctx(r)>.<r.label> == null ? null : <ctx(r)>.<r.label>.start)\"\nRulePropertyRef_stop(r)\t ::= \"(<ctx(r)>.<r.label> == null ? null : <ctx(r)>.<r.label>.stop)\"\nRulePropertyRef_text(r)\t ::= \"(<ctx(r)>.<r.label> == null ? null : this._input.getText(new antlr4.Interval(<ctx(r)>.<r.label>.start,<ctx(r)>.<r.label>.stop)))\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>.<r.label>\"\nRulePropertyRef_parser(r)\t ::= \"this\"\n\nThisRulePropertyRef_start(r) ::= \"localctx.start\"\nThisRulePropertyRef_stop(r)\t ::= \"localctx.stop\"\nThisRulePropertyRef_text(r)\t ::= \"this._input.getText(new antlr4.Interval(localctx.start, this._input.LT(-1)))\"\nThisRulePropertyRef_ctx(r)\t ::= \"localctx\"\nThisRulePropertyRef_parser(r)\t ::= \"this\"\n\nNonLocalAttrRef(s)\t\t \t ::= \"this.getInvokingContext(<s.ruleIndex>).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks)  ::= \"this.getInvokingContext(<s.ruleIndex>).<s.escapedName> = <rhsChunks>\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>.<a.listName>.push(<labelref(a.label)>);\"\n\nTokenDecl(t) ::= \"this.<t.escapedName> = null;\"\nTokenTypeDecl(t) ::= \"var <t.escapedName> = 0;\"\nTokenListDecl(t) ::= \"this.<t.escapedName> = [];\"\nRuleContextDecl(r) ::= \"this.<r.escapedName> = null;\"\nRuleContextListDecl(rdecl) ::= \"this.<rdecl.escapedName> = [];\"\n\nContextTokenGetterDecl(t)      ::= <<\n<t.escapedName>() {\n    return this.getToken(<parser.name>.<t.name>, 0);\n};\n>>\n\n// should never be called\nContextTokenListGetterDecl(t)  ::= <<\n<t.escapedName>_list() {\n    return this.getTokens(<parser.name>.<t.name>);\n}\n>>\n\nContextTokenListIndexedGetterDecl(t)  ::= <<\n<t.escapedName> = function(i) {\n\tif(i===undefined) {\n\t\ti = null;\n\t}\n    if(i===null) {\n        return this.getTokens(<parser.name>.<t.name>);\n    } else {\n        return this.getToken(<parser.name>.<t.name>, i);\n    }\n};\n\n>>\n\nContextRuleGetterDecl(r)       ::= <<\n<r.escapedName>() {\n    return this.getTypedRuleContext(<r.ctxName>,0);\n};\n>>\n\n// should never be called\nContextRuleListGetterDecl(r)   ::= <<\n<r.escapedName>_list() {\n    return this.getTypedRuleContexts(<parser.name>.<r.ctxName>);\n}\n>>\n\nContextRuleListIndexedGetterDecl(r)   ::= <<\n<r.escapedName> = function(i) {\n    if(i===undefined) {\n        i = null;\n    }\n    if(i===null) {\n        return this.getTypedRuleContexts(<r.ctxName>);\n    } else {\n        return this.getTypedRuleContext(<r.ctxName>,i);\n    }\n};\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/** The rule context name is the rule followed by a suffix; e.g.,\n *\tr becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"_<tokenName>\"\nImplicitRuleLabel(ruleName)\t  ::= \"_<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = self._input.LT(1)\"\nCaptureNextTokenType(d) ::= \"<d.varName> = this._input.LA(1);\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures) ::= <<\nclass <struct.escapedName> extends <if(contextSuperClass)><contextSuperClass><else>antlr4.ParserRuleContext<endif> {\n\n    constructor(parser, parent, invokingState<struct.ctorAttrs:{a | , <a.escapedName>}>) {\n        if(parent===undefined) {\n            parent = null;\n        }\n        if(invokingState===undefined || invokingState===null) {\n            invokingState = -1;\n        }\n        super(parent, invokingState);\n        this.parser = parser;\n        this.ruleIndex = <parser.name>.RULE_<struct.derivedFromName>;\n        <attrs:{a | <a>}; separator=\"\\n\">\n        <struct.ctorAttrs:{a | this.<a.escapedName> = <a.escapedName> || null;}; separator=\"\\n\">\n    }\n\n\t<getters:{g | <g>}; separator=\"\\n\\n\">\n\n\t<if(struct.provideCopyFrom)> <! don't need copy unless we have subclasses !>\n\tcopyFrom(ctx) {\n\t\tsuper.copyFrom(ctx);\n\t\t<struct.attrs:{a | this.<a.escapedName> = ctx.<a.escapedName>;}; separator=\"\\n\">\n\t}\n\t<endif>\n\t<dispatchMethods; separator=\"\\n\">\n\t<extensionMembers; separator=\"\\n\">\n\n}\n\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\nclass <struct.escapedName> extends <struct.parentRule; format=\"cap\">Context {\n\n    constructor(parser, ctx) {\n        super(parser);\n        <attrs:{a | <a>;}; separator=\"\\n\">\n        super.copyFrom(ctx);\n    }\n\n\t<getters:{g | <g>}; separator=\"\\n\\n\">\n\n\t<dispatchMethods; separator=\"\\n\">\n\n}\n\n<! Define fields of this parser to export this struct/context class !>\n<parser.name>.<struct.name> = <struct.escapedName>;\n\n>>\n\nListenerDispatchMethod(method) ::= <<\n<if(method.isEnter)>enter<else>exit<endif>Rule(listener) {\n    if(listener instanceof <parser.grammarName>Listener ) {\n        listener.<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">(this);\n\t}\n}\n\n>>\n\nVisitorDispatchMethod(method) ::= <<\naccept(visitor) {\n    if ( visitor instanceof <parser.grammarName>Visitor ) {\n        return visitor.visit<struct.derivedFromName; format=\"cap\">(this);\n    } else {\n        return visitor.visitChildren(this);\n    }\n}\n\n>>\n\nAttributeDecl(d) ::= \"this.<d.escapedName> = <if(d.initValue)><d.initValue><else>null<endif>\"\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if(!x.isLocal)>localctx.<endif><x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"localctx\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"this.precpred(this._ctx, <opPrec>)\"\nrecRuleSetReturnAction(src,name)\t  ::= \"$<name>=$<src>.<name>\"\nrecRuleSetStopToken()                 ::= \"this._ctx.stop = this._input.LT(-1);\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\nlocalctx = new <ctxName>Context(this, _parentctx, _parentState);\n<if(label)>\n<if(isListLabel)>\nlocalctx.<label>.push(_prevctx);\n<else>\nlocalctx.<label> = _prevctx;\n<endif>\n<endif>\nthis.pushNewRecursionContext(localctx, _startState, <parser.name>.RULE_<ruleName>);\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\nlocalctx = new <currentAltLabel; format=\"cap\">Context(this, new <ruleName; format=\"cap\">Context(this, _parentctx, _parentState));\n<if(label)>\n<if(isListLabel)>\nlocalctx.<label>.push(_prevctx);\n<else>\nlocalctx.<label> = _prevctx;\n<endif>\n<endif>\nthis.pushNewRecursionContext(localctx, _startState, <parser.name>.RULE_<ruleName>);\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\nlocalctx = new <ctxName>Context(this, localctx);\nthis._ctx = localctx;\n_prevctx = localctx;\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif(this._parseListeners!==null) {\n    this.triggerExitRuleEvent();\n}\n_prevctx = localctx;\n>>\n\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\nimport antlr4 from 'antlr4';\n\n<namedActions.header>\n\n<lexer>\n\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\n<if(superClass)>\nimport <superClass> from './<superClass>.js';\n\n<endif>\n<atn>\n\nconst atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);\n\nconst decisionsToDFA = atn.decisionToState.map( (ds, index) => new antlr4.dfa.DFA(ds, index) );\n\nexport default class <lexer.name> extends <if(superClass)><superClass><else>antlr4.Lexer<endif> {\n\n    static grammarFileName = \"<lexer.grammarFileName>\";\n    static channelNames = [ \"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"<if (lexer.channelNames)>, <lexer.channelNames:{c| \"<c>\"}; separator=\", \", wrap, anchor><endif> ];\n\tstatic modeNames = [ <lexer.modes:{m| \"<m>\"}; separator=\", \", wrap, anchor> ];\n\tstatic literalNames = [ <lexer.literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n\tstatic symbolicNames = [ <lexer.symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n\tstatic ruleNames = [ <lexer.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor> ];\n\n    constructor(input) {\n        super(input)\n        this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.atn.PredictionContextCache());\n        <namedActions.members>\n    }\n}\n\n<lexer.name>.EOF = antlr4.Token.EOF;\n<if(lexer.tokens)>\n<lexer.tokens:{k | <lexer.name>.<k> = <lexer.tokens.(k)>;}; separator=\"\\n\", wrap, anchor>\n<endif>\n\n<if(lexer.escapedChannels)>\n<lexer.escapedChannels:{c| <lexer.name>.<c> = <lexer.escapedChannels.(c)>;}; separator=\"\\n\">\n\n<endif>\n<if(rest(lexer.escapedModeNames))>\n<rest(lexer.escapedModeNames):{m| <lexer.name>.<m> = <i>;}; separator=\"\\n\">\n\n<endif>\n\n<dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n\n\n>>\n\nSerializedATN(model) ::= <<\nconst serializedATN = [<model.serialized: {s | <s>}; separator=\",\", wrap>];\n\n>>\n\n/** Using a type to init value map, try to init a type; if not in table\n *\tmust be an object, default value is \"null\".\n */\ninitValue(typeName) ::= <<\n<javacriptTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".js\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/PHP/PHP.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nphpTypeInitMap ::= [\n\t\"int\":\"0\",\n\t\"long\":\"0\",\n\t\"float\":\"0.0\",\n\t\"double\":\"0.0\",\n\t\"boolean\":\"false\",\n\tdefault:\"null\"\n]\n\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<parser>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage>;\n<endif>\n<header>\nuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\ParseTreeListener;\n\n/**\n * This interface defines a complete listener for a parse tree produced by\n * {@see <file.parserName>}.\n */\ninterface <file.grammarName>Listener extends ParseTreeListener {\n\t<file.listenerNames:{lname |\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Enter a parse tree produced by the `<lname>`\n * labeled alternative in {@see <file.parserName>::<file.listenerLabelRuleNames.(lname)>()\\}.\n<else>\n * Enter a parse tree produced by {@see <file.parserName>::<lname>()\\}.\n<endif>\n * @param $context The parse tree.\n */\npublic function enter<lname; format=\"cap\">(Context\\\\<lname; format=\"cap\">Context $context): void;\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Exit a parse tree produced by the `<lname>` labeled alternative\n * in {@see <file.parserName>::<file.listenerLabelRuleNames.(lname)>()\\}.\n<else>\n * Exit a parse tree produced by {@see <file.parserName>::<lname>()\\}.\n<endif>\n * @param $context The parse tree.\n */\npublic function exit<lname; format=\"cap\">(Context\\\\<lname; format=\"cap\">Context $context): void;}; separator=\"\\n\">\n}\n>>\n\nBaseListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage>;\n<endif>\n<header>\n\nuse Antlr\\\\Antlr4\\\\Runtime\\\\ParserRuleContext;\nuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\ErrorNode;\nuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\TerminalNode;\n\n/**\n * This class provides an empty implementation of {@see <file.grammarName>Listener},\n * which can be extended to create a listener which only needs to handle a subset\n * of the available methods.\n */\nclass <file.grammarName>BaseListener implements <file.grammarName>Listener\n{\n\t<file.listenerNames:{lname |\n/**\n * {@inheritdoc\\}\n *\n * The default implementation does nothing.\n */\npublic function enter<lname; format=\"cap\">(Context\\\\<lname; format=\"cap\">Context $context): void {\\}\n\n/**\n * {@inheritdoc\\}\n *\n * The default implementation does nothing.\n */\npublic function exit<lname; format=\"cap\">(Context\\\\<lname; format=\"cap\">Context $context): void {\\}}; separator=\"\\n\">\n\n\t/**\n\t * {@inheritdoc\\}\n\t *\n\t * The default implementation does nothing.\n\t */\n\tpublic function enterEveryRule(ParserRuleContext $context): void {}\n\n\t/**\n\t * {@inheritdoc\\}\n\t *\n\t * The default implementation does nothing.\n\t */\n\tpublic function exitEveryRule(ParserRuleContext $context): void {}\n\n\t/**\n\t * {@inheritdoc\\}\n\t *\n\t * The default implementation does nothing.\n\t */\n\tpublic function visitTerminal(TerminalNode $node): void {}\n\n\t/**\n\t * {@inheritdoc\\}\n\t *\n\t * The default implementation does nothing.\n\t */\n\tpublic function visitErrorNode(ErrorNode $node): void {}\n}\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage>;\n<endif>\n\n<header>\nuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\ParseTreeVisitor;\n\n/**\n * This interface defines a complete generic visitor for a parse tree produced by {@see <file.parserName>}.\n */\ninterface <file.grammarName>Visitor extends ParseTreeVisitor\n{\n\t<file.visitorNames:{lname |\n/**\n<if(file.visitorLabelRuleNames.(lname))>\n * Visit a parse tree produced by the `<lname>` labeled alternative\n * in {@see <file.parserName>::<file.visitorLabelRuleNames.(lname)>()\\}.\n<else>\n * Visit a parse tree produced by {@see <file.parserName>::<lname>()\\}.\n<endif>\n *\n * @param Context\\\\<lname; format=\"cap\">Context $context The parse tree.\n *\n * @return mixed The visitor result.\n */\npublic function visit<lname; format=\"cap\">(Context\\\\<lname; format=\"cap\">Context $context);}; separator=\"\\n\\n\">\n}\n>>\n\nBaseVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\nnamespace <file.genPackage>;\n<endif>\n<header>\nuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\AbstractParseTreeVisitor;\n\n/**\n * This class provides an empty implementation of {@see <file.grammarName>Visitor},\n * which can be extended to create a visitor which only needs to handle a subset\n * of the available methods.\n */\nclass <file.grammarName>BaseVisitor extends AbstractParseTreeVisitor implements <file.grammarName>Visitor\n{\n\t<file.visitorNames:{lname |\n/**\n * {@inheritdoc\\}\n *\n * The default implementation returns the result of calling\n * {@see self::visitChildren()\\} on `context`.\n */\npublic function visit<lname; format=\"cap\">(Context\\\\<lname; format=\"cap\">Context $context)\n{\n    return $this->visitChildren($context);\n\\}}; separator=\"\\n\\n\">\n}\n>>\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n\\<?php\n\n/*\n * Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n */\n\n>>\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\n<Parser_(ctor=\"parser_ctor\", ...)>\n>>\n\nParser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<\nnamespace<if(file.genPackage)> <file.genPackage><endif> {\n<if(namedActions.header)><namedActions.header><endif>\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Atn\\\\ATN;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Atn\\\\ATNDeserializer;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Atn\\\\ParserATNSimulator;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Dfa\\\\DFA;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Error\\\\Exceptions\\\\FailedPredicateException;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Error\\\\Exceptions\\\\NoViableAltException;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\PredictionContexts\\\\PredictionContextCache;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Error\\\\Exceptions\\\\RecognitionException;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\RuleContext;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Token;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\TokenStream;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Vocabulary;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\VocabularyImpl;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\RuntimeMetaData;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Parser;\n<if(namedActions.definitions)><namedActions.definitions><endif>\n\n\tfinal class <parser.name> extends <superClass; null=\"Parser\">\n\t{\n\t\t<if(parser.tokens)>\n\t\tpublic const <parser.tokens:{k | <k> = <parser.tokens.(k)>}; separator=\", \", wrap, anchor>;\n\t\t<endif>\n\n\t\t<if(parser.rules)>\n\t\tpublic const <parser.rules:{r | RULE_<r.name> = <r.index>}; separator=\", \", wrap, anchor>;\n\t\t<endif>\n\n\t\t/**\n\t\t * @var array\\<string>\n\t\t */\n\t\tpublic const RULE_NAMES = [\n\t\t\t<parser.ruleNames:{r | '<r>'}; separator=\", \", wrap, anchor>\n\t\t];\n\n\t\t<vocabulary(parser.literalNames, parser.symbolicNames)>\n\n\t\t<atn>\n\t\tprotected static $atn;\n\t\tprotected static $decisionToDFA;\n\t\tprotected static $sharedContextCache;\n\t\t<if(namedActions.members)>\n\n\t\t<namedActions.members>\n\t\t<endif>\n\n\n\t\t<parser:(ctor)()>\n\n\t\tprivate static function initialize(): void\n\t\t{\n\t\t\tif (self::$atn !== null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tRuntimeMetaData::checkVersion('<file.ANTLRVersion>', RuntimeMetaData::VERSION);\n\n\t\t\t$atn = (new ATNDeserializer())->deserialize(self::SERIALIZED_ATN);\n\n\t\t\t$decisionToDFA = [];\n\t\t\tfor ($i = 0, $count = $atn->getNumberOfDecisions(); $i \\< $count; $i++) {\n\t\t\t\t$decisionToDFA[] = new DFA($atn->getDecisionState($i), $i);\n\t\t\t}\n\n\t\t\tself::$atn = $atn;\n\t\t\tself::$decisionToDFA = $decisionToDFA;\n\t\t\tself::$sharedContextCache = new PredictionContextCache();\n\t\t}\n\n\t\tpublic function getGrammarFileName(): string\n\t\t{\n\t\t\treturn \"<parser.grammarFileName>\";\n\t\t}\n\n\t\tpublic function getRuleNames(): array\n\t\t{\n\t\t\treturn self::RULE_NAMES;\n\t\t}\n\n\t\tpublic function getSerializedATN(): array\n\t\t{\n\t\t\treturn self::SERIALIZED_ATN;\n\t\t}\n\n\t\tpublic function getATN(): ATN\n\t\t{\n\t\t\treturn self::$atn;\n\t\t}\n\n\t\tpublic function getVocabulary(): Vocabulary\n        {\n            static $vocabulary;\n\n\t\t\treturn $vocabulary = $vocabulary ?? new VocabularyImpl(self::LITERAL_NAMES, self::SYMBOLIC_NAMES);\n        }\n<if(funcs)>\n\n\t\t<funcs; separator=\"\\n\\n\">\n<endif>\n<if(sempredFuncs)>\n\n\t\tpublic function sempred(?RuleContext $localContext, int $ruleIndex, int $predicateIndex): bool\n\t\t{\n\t\t\tswitch ($ruleIndex) {\n\t\t\t<parser.sempredFuncs.values:{f|\n\t\tcase <f.ruleIndex>:\n\t\t\treturn $this->sempred<f.name; format=\"cap\">($localContext, $predicateIndex);}; separator=\"\\n\\n\">\n\n\t\t\t\tdefault:\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t}\n\n\t\t<sempredFuncs.values; separator=\"\\n\\n\">\n<endif>\n\t}\n}\n\nnamespace <if(file.genPackage)><file.genPackage>\\\\<endif>Context {\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\ParserRuleContext;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Token;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\ParseTreeVisitor;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\TerminalNode;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Tree\\\\ParseTreeListener;\n\tuse <if(file.genPackage)><file.genPackage>\\\\<endif><parser.name>;\n\t<if (file.genVisitor)>use <if(file.genPackage)><file.genPackage>\\\\<endif><file.grammarName>Visitor;<endif>\n\t<if (file.genListener)>use <if(file.genPackage)><file.genPackage>\\\\<endif><file.grammarName>Listener;<endif>\n\t<namedActions.contexts>\n\n\t<funcs :{ func | <func.ruleCtx><if(func.altLabelCtxs)>\n\n<func.altLabelCtxs:{l | <func.altLabelCtxs.(l)>}; separator=\"\\n\\n\"><endif> }; separator=\"\\n\\n\">\n}\n>>\n\nvocabulary(literalNames, symbolicNames) ::= <<\n/**\n * @var array\\<string|null>\n */\nprivate const LITERAL_NAMES = [\n    <literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n];\n\n/**\n * @var array\\<string>\n */\nprivate const SYMBOLIC_NAMES = [\n    <symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor>\n];\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\n\npublic function action(?RuleContext $localContext, int $ruleIndex, int $actionIndex): void\n{\n\tswitch ($ruleIndex) {\n\t<recog.actionFuncs.values:{f|\n\tcase <f.ruleIndex>:\n\t\t$this->action<f.name; format=\"cap\">($localContext, $actionIndex);\n\t\tbreak;}; separator=\"\\n\\n\">\n\t}\n}\n\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<if(sempredFuncs)>\n\npublic function sempred(?RuleContext $localContext, int $ruleIndex, int $predicateIndex): bool\n{\n\tswitch ($ruleIndex) {\n\t<recog.sempredFuncs.values:{f|\n    case <f.ruleIndex>:\n        return $this->sempred<f.name; format=\"cap\">($localContext, $predicateIndex);}; separator=\"\\n\\n\">\n\t}\n\n\treturn true;\n}\n<sempredFuncs.values; separator=\"\\n\\n\">\n<endif>\n>>\n\nparser_ctor(p) ::= <<\npublic function __construct(TokenStream $input)\n{\n\tparent::__construct($input);\n\n\tself::initialize();\n\n\t$this->interp = new ParserATNSimulator($this, self::$atn, self::$decisionToDFA, self::$sharedContextCache);\n}\n>>\n\n/**\n * This generates a private method since the actionIndex is generated, making\n * an overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\nprivate function action<r.name; format=\"cap\">(?<r.ctxType> $localContext, int $actionIndex): void\n{\n\tswitch ($actionIndex) {\n\t<actions:{index|\n\tcase <index>:\n\t<actions.(index)>\n\n\tbreak;}; separator=\"\\n\\n\">\n\t}\n}\n>>\n\n/**\n * This generates a private method since the predicateIndex is generated, making\n * an overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\nprivate function sempred<r.name; format=\"cap\">(?Context\\\\<r.ctxType> $localContext, int $predicateIndex): bool\n{\n\tswitch ($predicateIndex) {\n\t<actions:{index|\n    case <index>:\n        return <actions.(index)>;}; separator=\"\\n\\n\">\n\t}\n\n\treturn true;\n}\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,exceptions,postamble) ::= <<\n/**\n * @throws RecognitionException\n */\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><endif>public function <currentRule.escapedName>(<args; separator=\",\">): Context\\\\<currentRule.ctxType>\n{\n    $localContext = new Context\\\\<currentRule.ctxType>($this->ctx, $this->getState()<currentRule.args:{a | , $<a.name>}>);\n\n    $this->enterRule($localContext, <currentRule.startState>, self::RULE_<currentRule.name>);\n    <namedActions.init>\n    <locals; separator=\"\\n\">\n\n    try {\n        <code>\n        <postamble; separator=\"\\n\">\n        <namedActions.after>\n    }<if(exceptions)><exceptions; separator=\"\\n\"><else> catch (RecognitionException $exception) {\n        $localContext->exception = $exception;\n        $this->errorHandler->reportError($this, $exception);\n        $this->errorHandler->recover($this, $exception);\n    }<endif> finally {\n        <finallyAction>\n        $this->exitRule();\n    }\n\n    return $localContext;\n}\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble) ::= <<\n/**\n * @throws RecognitionException\n */\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><endif>public function <currentRule.name>(<args; separator=\", \">): Context\\\\<currentRule.ctxType>\n{\n\treturn $this->recursive<currentRule.name; format=\"cap\">(0<currentRule.args:{a | , <a.name>}>);\n}\n\n/**\n * @throws RecognitionException\n */\nprivate function recursive<currentRule.name; format=\"cap\">(int $precedence<args:{a | , <a>}>): Context\\\\<currentRule.ctxType>\n{\n\t$parentContext = $this->ctx;\n\t$parentState = $this->getState();\n\t$localContext = new Context\\\\<currentRule.ctxType>($this->ctx, $parentState<currentRule.args:{a | , <a.name>}>);\n\t$previousContext = $localContext;\n\t$startState = <currentRule.startState>;\n\t$this->enterRecursionRule($localContext, <currentRule.startState>, self::RULE_<currentRule.name>, $precedence);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\n\ttry {\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t} catch (RecognitionException $exception) {\n\t\t$localContext->exception = $exception;\n\t\t$this->errorHandler->reportError($this, $exception);\n\t\t$this->errorHandler->recover($this, $exception);\n\t} finally {\n\t\t<finallyAction>\n\t\t$this->unrollRecursionContexts($parentContext);\n\t}\n\n\treturn $localContext;\n}\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>$localContext = new Context\\\\<currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context($localContext);<endif>\n$this->enterOuterAlt($localContext, <currentOuterMostAltCodeBlock.alt.altNum>);\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\n$this->setState(<choice.stateNumber>);\n$this->errorHandler->sync($this);\n<if(choice.label)><labelref(choice.label)> = $this->input->LT(1);<endif>\n<preamble; separator=\"\\n\">\n\nswitch ($this->input->LA(1)) {\n    <choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\\n\">\n\ndefault:\n\t<error>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\n$this->setState(<choice.stateNumber>);\n$this->errorHandler->sync($this);\n\nswitch ($this->input->LA(1)) {\n    <choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\\n\">\n\ndefault:\n\tbreak;\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\n$this->setState(<choice.stateNumber>);\n$this->errorHandler->sync($this);\n<preamble; separator=\"\\n\">\n\nif (<expr>) {\n\t<alts; separator=\"\\n\">\n}\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\n$this->setState(<choice.stateNumber>);\n$this->errorHandler->sync($this);\n\n<preamble; separator=\"\\n\">\nwhile (<loopExpr>) {\n\t<alts; separator=\"\\n\">\n\t$this->setState(<choice.loopBackStateNumber>);\n\t$this->errorHandler->sync($this);\n\t<iteration>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\n$this->setState(<choice.blockStartStateNumber>); <! alt block decision !>\n$this->errorHandler->sync($this);\n\n<preamble; separator=\"\\n\">\ndo {\n\t<alts; separator=\"\\n\">\n\t$this->setState(<choice.stateNumber>); <! loopback/exit decision !>\n\t$this->errorHandler->sync($this);\n\t<iteration>\n} while (<loopExpr>);\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\n$this->setState(<choice.stateNumber>);\n$this->errorHandler->sync($this);\n<if(choice.label)><labelref(choice.label)> = $this->input->LT(1);<endif>\n<preamble; separator=\"\\n\">\n\nswitch ($this->getInterpreter()->adaptivePredict($this->input, <choice.decision>, $this->ctx)) {\n\t<alts:{alt |\ncase <i>:\n    <alt>\nbreak;}; separator=\"\\n\\n\">\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\n$this->setState(<choice.stateNumber>);\n$this->errorHandler->sync($this);\n\nswitch ($this->getInterpreter()->adaptivePredict($this->input, <choice.decision>, $this->ctx)) {\n<alts:{alt |\n    case <i><if(!choice.ast.greedy)>+1<endif>:\n\t    <alt>\n\tbreak;}; separator=\"\\n\\n\">\n}\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\n$this->setState(<choice.stateNumber>);\n$this->errorHandler->sync($this);\n\n$alt = $this->getInterpreter()->adaptivePredict($this->input, <choice.decision>, $this->ctx);\n\nwhile ($alt !== <choice.exitAlt> && $alt !== ATN::INVALID_ALT_NUMBER) {\n\tif ($alt === 1<if(!choice.ast.greedy)>+1<endif>) {\n\t\t<iteration>\n\t\t<alts> <! should only be one !>\n\t}\n\n\t$this->setState(<choice.loopBackStateNumber>);\n\t$this->errorHandler->sync($this);\n\n\t$alt = $this->getInterpreter()->adaptivePredict($this->input, <choice.decision>, $this->ctx);\n}\n>>\n\nPlusBlock(choice, alts, error) ::= <<\n$this->setState(<choice.blockStartStateNumber>); <! alt block decision !>\n$this->errorHandler->sync($this);\n\n$alt = 1<if(!choice.ast.greedy)>+1<endif>;\n\ndo {\n\tswitch ($alt) {\n\t<alts:{alt|\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\\n\">\n\tdefault:\n\t\t<error>\n\t}\n\n\t$this->setState(<choice.loopBackStateNumber>); <! loopback/exit decision !>\n\t$this->errorHandler->sync($this);\n\n\t$alt = $this->getInterpreter()->adaptivePredict($this->input, <choice.decision>, $this->ctx);\n} while ($alt !== <choice.exitAlt> && $alt !== ATN::INVALID_ALT_NUMBER);\n>>\n\nSync(s) ::= \"sync(<s.expecting.name>);\"\n\nThrowNoViableAlt(t) ::= \"throw new NoViableAltException($this);\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount>) & ~0x3f) === 0\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShiftVar(s.varName, bits.shift)>})> && ((1 \\<\\< <offsetShiftVar(s.varName, bits.shift)>) & <bits.calculated>) !== 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShiftVar(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>($<shiftAmount> - <offset>)<else>$<shiftAmount><endif>\n%>\noffsetShiftConst(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(self::<shiftAmount> - <offset>)<else>self::<shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | $<s.varName> === self::<t.name>}; separator=\" || \">\n%>\n\ncases(tokens) ::= <<\n<tokens:{t | case self::<t.name>:}; separator=\"\\n\">\n>>\n\nInvokeRule(r, argExprsChunks) ::= <<\n$this->setState(<r.stateNumber>);\n<if(r.labels)><r.labels:{l | <labelref(l)> = }><endif>$this-><if(r.ast.options.p)>recursive<r.name; format=\"cap\"><else><r.escapedName><endif>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>);\n>>\n\nMatchToken(m) ::= <<\n$this->setState(<m.stateNumber>);\n<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>$this->match(self::<m.name>);\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\n$this->setState(<m.stateNumber>);\n\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>$this->input->LT(1);<endif>\n<capture>\n\nif (<if(invert)>$<m.varName> \\<= 0 || <else>!<endif>(<expr>)) {\n\t    <if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>$this->errorHandler->recoverInline($this);\n} else {\n\tif ($this->input->LA(1) === Token::EOF) {\n\t    $this->matchedEOF = true;\n    }\n\n\t$this->errorHandler->reportMatch($this);\n\t$this->consume();\n}\n>>\n\nWildcard(w) ::= <<\n$this->setState(<w.stateNumber>);\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>$this->matchWildcard();\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\n$this->setState(<p.stateNumber>);\n\nif (!(<chunks>)) {\n    throw new FailedPredicateException($this, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>);\n}\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n\t<catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"$this->skip();\"\nLexerMoreCommand()  ::= \"$this->more();\"\nLexerPopModeCommand() ::= \"$this->popMode();\"\n\nLexerTypeCommand(arg, grammar)      ::= \"$this->type = <arg>;\"\nLexerChannelCommand(arg, grammar)   ::= \"$this->channel = <arg>;\"\nLexerModeCommand(arg, grammar)      ::= \"$this->mode = <arg>;\"\nLexerPushModeCommand(arg, grammar)  ::= \"$this->pushMode(<arg>);\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"$localContext-><a.name>\"\nLocalRef(a) ::= \"$localContext-><a.name>\"\nRetValueRef(a) ::= \"$localContext-><a.name>\"\nQRetValueRef(a) ::= \"<ctx(a)>-><a.dict>-><a.name>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>-><t.name>\"\nLabelRef(t) ::= \"<ctx(t)>-><t.name>\"\nListLabelRef(t) ::= \"<ctx(t)>-><ListLabelName(t.name)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>-><s.name> = <rhsChunks>;\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={Token}>\"\n\nTokenPropertyRef_text(t) ::= \"(<ctx(t)>-><t.label> !== null ? <ctx(t)>-><t.label>->getText() : null)\"\nTokenPropertyRef_type(t) ::= \"(<ctx(t)>-><t.label> !== null ? <ctx(t)>-><t.label>->getType() : 0)\"\nTokenPropertyRef_line(t) ::= \"(<ctx(t)>-><t.label> !== null ? <ctx(t)>-><t.label>->getLine() : 0)\"\nTokenPropertyRef_pos(t) ::= \"(<ctx(t)>-><t.label> !== null ? <ctx(t)>-><t.label>->getCharPositionInLine() : 0)\"\nTokenPropertyRef_channel(t) ::= \"(<ctx(t)>-><t.label> !== null ? <ctx(t)>-><t.label>->getChannel() : 0)\"\nTokenPropertyRef_index(t) ::= \"(<ctx(t)>-><t.label> !== null ? <ctx(t)>-><t.label>->getTokenIndex() : 0)\"\nTokenPropertyRef_int(t) ::= \"(<ctx(t)>-><t.label> !== null ? (int) <ctx(t)>-><t.label>->getText() : 0)\"\n\nRulePropertyRef_start(r) ::= \"(<ctx(r)>-><r.label> !== null ? (<ctx(r)>-><r.label>->start) : null)\"\nRulePropertyRef_stop(r)\t ::= \"(<ctx(r)>-><r.label> !== null ? (<ctx(r)>-><r.label>->stop) : null)\"\nRulePropertyRef_text(r)\t ::= \"(<ctx(r)>-><r.label> !== null ? $this->input->getTextByTokens(<ctx(r)>-><r.label>->start, <ctx(r)>-><r.label>->stop) : null)\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>-><r.label>\"\nRulePropertyRef_parser(r)::= \"\\$this\"\n\nThisRulePropertyRef_start(r) ::= \"$localContext->start\"\nThisRulePropertyRef_stop(r)\t ::= \"$localContext->stop\"\nThisRulePropertyRef_text(r)\t ::= \"$this->input->getTextByTokens($localContext->start, $this->input->LT(-1))\"\nThisRulePropertyRef_ctx(r)\t ::= \"$localContext\"\nThisRulePropertyRef_parser(r)::= \"$this\"\n\nNonLocalAttrRef(s)\t\t      ::= \"\\$this->getInvokingContext(<s.ruleIndex>)-><s.name>\"\nSetNonLocalAttr(s, rhsChunks) ::= \"\\$this->getInvokingContext(<s.ruleIndex>)-><s.name> = <rhsChunks>;\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>-><a.listName>[] = <labelref(a.label)>;\"\n\nTokenDecl(t) ::= \"<TokenLabelType()> $<t.name>\"\nTokenTypeDecl(t) ::= \"\"\nTokenListDecl(t) ::= \"array $<t.name> = []\"\nRuleContextDecl(r) ::= \"<r.ctxName> $<r.name>\"\nRuleContextListDecl(rdecl) ::= \"array $<rdecl.name> = []\"\nAttributeDecl(d) ::= \"<d.type> $<d.name><if(d.initValue)> = <d.initValue><endif>\"\n\nPropertiesDecl(struct) ::= <<\n<if(struct.tokenListDecls)>\n\t<struct.tokenListDecls : {d | /**\n * @var array\\<Token>|null $<d.name>\n */\npublic $<d.name>;}; separator=\"\\n\\n\">\n<endif>\n<if(struct.tokenDecls)>\n<if(struct.tokenListDecls)>\n\n<endif>\n\t<struct.tokenDecls : {d | /**\n * @var <TokenLabelType()>|null $<d.name>\n */\npublic $<d.name>;}; separator=\"\\n\\n\">\n<endif>\n<if(struct.ruleContextDecls)>\n<if(struct.tokenListDecls || struct.tokenDecls)>\n\n<endif>\n\t<struct.ruleContextDecls : {d | /**\n * @var <d.ctxName>|null $<d.name>\n */\npublic $<d.name>;}; separator=\"\\n\\n\">\n<endif>\n<if(struct.ruleContextListDecls)>\n<if(struct.tokenListDecls || struct.tokenDecls || struct.ruleContextDecls)>\n\n<endif>\n\t<struct.ruleContextListDecls : {d | /**\n * @var array\\<<d.ctxName>\\>|null $<d.name>\n */\npublic $<d.name>;}; separator=\"\\n\\n\">\n<endif>\n<if(struct.attributeDecls)>\n<if(struct.tokenListDecls || struct.tokenDecls || struct.ruleContextDecls || struct.ruleContextListDecls)>\n\n<endif>\n\t<struct.attributeDecls : {d | /**\n * @var <d.type><if(!d.initValue)>|null<endif> $<d.name>\n */\npublic $<d.name><if(d.initValue)> = <d.initValue><endif>;}; separator=\"\\n\\n\">\n<endif>\n\n>>\n\nContextTokenGetterDecl(t) ::= <<\npublic function <t.name>(): ?TerminalNode\n{\n    return $this->getToken(<parser.name>::<t.name>, 0);\n}\n>>\n\nContextTokenListGetterDecl(t)  ::= <<\n>>\n\nContextTokenListIndexedGetterDecl(t)  ::= <<\n/**\n * @return array\\<TerminalNode>|TerminalNode|null\n */\npublic function <t.name>(?int $index = null)\n{\n\tif ($index === null) {\n\t\treturn $this->getTokens(<parser.name>::<t.name>);\n\t}\n\n    return $this->getToken(<parser.name>::<t.name>, $index);\n}\n>>\n\nContextRuleGetterDecl(r)       ::= <<\npublic function <r.name>(): ?<r.ctxName>\n{\n\treturn $this->getTypedRuleContext(<r.ctxName>::class, 0);\n}\n>>\n\nContextRuleListGetterDecl(r)   ::= <<\n>>\n\nContextRuleListIndexedGetterDecl(r)   ::= <<\n/**\n * @return array\\<<r.ctxName>\\>|<r.ctxName>|null\n */\npublic function <r.name>(?int $index = null)\n{\n\tif ($index === null) {\n\t\treturn $this->getTypedRuleContexts(<r.ctxName>::class);\n\t}\n\n    return $this->getTypedRuleContext(<r.ctxName>::class, $index);\n}\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/**\n * The rule context name is the rule followed by a suffix; e.g., r becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"<tokenName>\"\nImplicitRuleLabel(ruleName)\t  ::= \"<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"$<d.varName> = \\$this->input->LT(1);\"\nCaptureNextTokenType(d) ::= \"$<d.varName> = $this->input->LA(1);\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures) ::= <<\nclass <struct.name> extends <if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif><if(interfaces)> implements <interfaces; separator=\", \"><endif>\n{\n<PropertiesDecl(struct)>\n\tpublic function __construct(?ParserRuleContext $parent, ?int $invokingState = null<ctorAttrs:{a | , ?<a> = null}>)\n\t{\n\t\tparent::__construct($parent, $invokingState);\n<if(struct.ctorAttrs)>\n\n\t\t<struct.ctorAttrs:{a | $this-><a.name> = $<a.name> ?? $this-><a.name>;}; separator=\"\\n\">\n<endif>\n\t}\n\n\tpublic function getRuleIndex(): int\n\t{\n\t    return <parser.name>::RULE_<struct.derivedFromName>;\n    }\n<if(getters)>\n\n    <getters:{g | <g>}; separator=\"\\n\\n\">\n<endif>\n<if(struct.provideCopyFrom)> <! don't need copy unless we have subclasses !>\n\tpublic function copyFrom(ParserRuleContext $context): void\n\t{\n\t\tparent::copyFrom($context);\n\n\t\t<struct.attrs:{a | $this-><a.name> = $context-><a.name>;}; separator=\"\\n\">\n\t}\n<endif>\n<if(dispatchMethods)>\n\n\t<dispatchMethods; separator=\"\\n\\n\">\n<endif>\n<if(extensionMembers)>\n\n\t<extensionMembers; separator=\"\\n\\n\">\n<endif>\n}\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\nclass <struct.name> extends <struct.parentRule; format=\"cap\">Context\n{\n<PropertiesDecl(struct)>\n\tpublic function __construct(<struct.parentRule; format=\"cap\">Context $context)\n\t{\n\t    parent::__construct($context);\n\n\t    $this->copyFrom($context);\n    }\n<if(getters)>\n\n    <getters:{g | <g>}; separator=\"\\n\\n\">\n<endif>\n<if(dispatchMethods)>\n\n\t<dispatchMethods; separator=\"\\n\\n\">\n<endif>\n}\n>>\n\nListenerDispatchMethod(method) ::= <<\npublic function <if(method.isEnter)>enter<else>exit<endif>Rule(ParseTreeListener $listener): void\n{\n\tif ($listener instanceof <parser.grammarName>Listener) {\n\t    $listener-><if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">($this);\n    }\n}\n>>\n\nVisitorDispatchMethod(method) ::= <<\npublic function accept(ParseTreeVisitor $visitor): mixed\n{\n\tif ($visitor instanceof <parser.grammarName>Visitor) {\n\t    return $visitor->visit<struct.derivedFromName; format=\"cap\">($this);\n    }\n\n\treturn $visitor->visitChildren($this);\n}\n>>\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if(!x.isLocal)>$localContext-><endif><x.name>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"$localContext\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"\\$this->precpred(\\$this->ctx, <opPrec>)\"\n\nrecRuleSetReturnAction(src,name)\t  ::= \"\\$<name> = \\$<src>-><name>;\"\n\nrecRuleSetStopToken()                 ::= \"$this->ctx->stop = $this->input->LT(-1);\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\n$localContext = new Context\\\\<ctxName>Context($parentContext, $parentState);\n<if(label)>\n<if(isListLabel)>\n$localContext-><label>[] = $previousContext;\n<else>\n$localContext-><label> = $previousContext;\n<endif>\n<endif>\n\n$this->pushNewRecursionContext($localContext, $startState, self::RULE_<ruleName>);\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\n$localContext = new Context\\\\<currentAltLabel; format=\"cap\">Context(new Context\\\\<ruleName; format=\"cap\">Context($parentContext, $parentState));\n<if(label)>\n<if(isListLabel)>\n$localContext-><label>[] = $previousContext;\n<else>\n$localContext-><label> = $previousContext;\n<endif>\n<endif>\n\n$this->pushNewRecursionContext($localContext, $startState, self::RULE_<ruleName>);\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\n$localContext = new Context\\\\<ctxName>Context($localContext);\n$this->ctx = $localContext;\n$previousContext = $localContext;\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif ($this->getParseListeners() !== null) {\n    $this->triggerExitRuleEvent();\n}\n\n$previousContext = $localContext;\n>>\n\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\n<lexer>\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\nnamespace<if(lexerFile.genPackage)> <lexerFile.genPackage><endif> {\n<if(namedActions.header)><namedActions.header><endif>\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Atn\\\\ATNDeserializer;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Atn\\\\LexerATNSimulator;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Lexer;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\CharStream;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\PredictionContexts\\\\PredictionContextCache;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\RuleContext;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Atn\\\\ATN;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Dfa\\\\DFA;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\Vocabulary;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\RuntimeMetaData;\n\tuse Antlr\\\\Antlr4\\\\Runtime\\\\VocabularyImpl;\n<if(namedActions.definitions)><namedActions.definitions><endif>\n\n\tfinal class <lexer.name> extends <superClass; null=\"Lexer\">\n\t{\n\t\t<if(lexer.tokens)>\n\t\tpublic const <lexer.tokens:{k | <k> = <lexer.tokens.(k)>}; separator=\", \", wrap, anchor>;\n\t\t<endif>\n\n\t\t<if(lexer.escapedChannels)>\n\t\tpublic const <lexer.escapedChannels:{c | <c> = <lexer.escapedChannels.(c)>}; separator=\", \", wrap, anchor>;\n\t\t<endif>\n\n\t\t<if(rest(lexer.escapedModeNames))>\n\t\tpublic const <rest(lexer.escapedModeNames):{m | <m>=<i>}; separator=\", \", wrap, anchor>;\n\t\t<endif>\n\n\t\t/**\n\t\t * @var array\\<string>\n\t\t */\n\t\tpublic const CHANNEL_NAMES = [\n\t\t\t'DEFAULT_TOKEN_CHANNEL', 'HIDDEN'<if (lexer.channelNames)>, <lexer.channelNames:{c| '<c>'}; separator=\", \", wrap, anchor><endif>\n\t\t];\n\n\t\t/**\n\t\t * @var array\\<string>\n\t\t */\n\t\tpublic const MODE_NAMES = [\n\t\t\t<lexer.modes:{m| '<m>'}; separator=\", \", wrap, anchor>\n\t\t];\n\n\t\t/**\n\t\t * @var array\\<string>\n\t\t */\n\t\tpublic const RULE_NAMES = [\n\t\t\t<lexer.ruleNames:{r | '<r>'}; separator=\", \", wrap, anchor>\n\t\t];\n\n\t\t<vocabulary(lexer.literalNames, lexer.symbolicNames)>\n\n\t\t<atn>\n\t\tprotected static $atn;\n\t\tprotected static $decisionToDFA;\n\t\tprotected static $sharedContextCache;\n<if(namedActions.members)>\n\n\t\t<namedActions.members>\n<endif>\n\n\t\tpublic function __construct(CharStream $input)\n\t\t{\n\t\t\tparent::__construct($input);\n\n\t\t\tself::initialize();\n\n\t\t\t$this->interp = new LexerATNSimulator($this, self::$atn, self::$decisionToDFA, self::$sharedContextCache);\n\t\t}\n\n\t\tprivate static function initialize(): void\n\t\t{\n\t\t\tif (self::$atn !== null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tRuntimeMetaData::checkVersion('<lexerFile.ANTLRVersion>', RuntimeMetaData::VERSION);\n\n\t\t\t$atn = (new ATNDeserializer())->deserialize(self::SERIALIZED_ATN);\n\n\t\t\t$decisionToDFA = [];\n\t\t\tfor ($i = 0, $count = $atn->getNumberOfDecisions(); $i \\< $count; $i++) {\n\t\t\t\t$decisionToDFA[] = new DFA($atn->getDecisionState($i), $i);\n\t\t\t}\n\n\t\t\tself::$atn = $atn;\n\t\t\tself::$decisionToDFA = $decisionToDFA;\n\t\t\tself::$sharedContextCache = new PredictionContextCache();\n\t\t}\n\n\t\tpublic static function vocabulary(): Vocabulary\n\t\t{\n\t\t\tstatic $vocabulary;\n\n\t\t\treturn $vocabulary = $vocabulary ?? new VocabularyImpl(self::LITERAL_NAMES, self::SYMBOLIC_NAMES);\n\t\t}\n\n\t\tpublic function getGrammarFileName(): string\n\t\t{\n\t\t\treturn '<lexer.grammarFileName>';\n\t\t}\n\n\t\tpublic function getRuleNames(): array\n\t\t{\n\t\t\treturn self::RULE_NAMES;\n\t\t}\n\n\t\tpublic function getSerializedATN(): array\n\t\t{\n\t\t\treturn self::SERIALIZED_ATN;\n\t\t}\n\n\t\t/**\n\t\t * @return array\\<string>\n\t\t */\n\t\tpublic function getChannelNames(): array\n\t\t{\n\t\t\treturn self::CHANNEL_NAMES;\n\t\t}\n\n\t\t/**\n\t\t * @return array\\<string>\n\t\t */\n\t\tpublic function getModeNames(): array\n\t\t{\n\t\t\treturn self::MODE_NAMES;\n\t\t}\n\n\t\tpublic function getATN(): ATN\n\t\t{\n\t\t\treturn self::$atn;\n\t\t}\n\n\t\tpublic function getVocabulary(): Vocabulary\n\t\t{\n\t\t\treturn self::vocabulary();\n\t\t}\n\t\t<dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n\t}\n}\n>>\n\nSerializedATN(model) ::= <<\nprivate const SERIALIZED_ATN =\n\t[<model.serialized: {s | <s>}; separator=\", \", wrap={<\\n>    }>];\n>>\n\n/**\n * Using a type to init value map, try to init a type; if not in table\n * must be an object, default value is `null`.\n */\ninitValue(typeName) ::= <<\n<phpTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".php\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/Python3/Python3.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  Copyright (c) 2014 Eric Vergnaud\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** ANTLR tool checks output templates are compatible with tool code generation.\n *  For now, a simple string match used on x.y of x.y.z scheme.\n *  Must match Tool.VERSION during load to templates.\n *\n *  REQUIRED.\n */\n\npythonTypeInitMap ::= [\n\t\"bool\":\"False\",\n\t\"int\":\"0\",\n\t\"float\":\"0.0\",\n\t\"str\":\"\",\n\tdefault:\"None\" // anything other than a primitive type is an object\n]\n\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n# encoding: utf-8\nfrom antlr4 import *\nfrom io import StringIO\nimport sys\nif sys.version_info >= (3, 6):\n\tfrom typing import TextIO\nelse:\n\tfrom typing.io import TextIO\n\n<namedActions.header>\n<parser>\n\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nfrom antlr4 import *\nif \".\" in __name__:\n    from .<file.parserName> import <file.parserName>\nelse:\n    from <file.parserName> import <file.parserName>\n<header>\n\n# This class defines a complete listener for a parse tree produced by <file.parserName>.\nclass <file.grammarName>Listener(ParseTreeListener):\n\n    <file.listenerNames:{lname |\n# Enter a parse tree produced by <file.parserName>#<lname>.\ndef enter<lname; format=\"cap\">(self, ctx:<file.parserName>.<lname; format=\"cap\">Context):\n    pass\n\n# Exit a parse tree produced by <file.parserName>#<lname>.\ndef exit<lname; format=\"cap\">(self, ctx:<file.parserName>.<lname; format=\"cap\">Context):\n    pass\n\n}; separator=\"\\n\">\n\ndel <file.parserName>\n>>\n\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\nfrom antlr4 import *\nif \".\" in __name__:\n    from .<file.parserName> import <file.parserName>\nelse:\n    from <file.parserName> import <file.parserName>\n<header>\n\n# This class defines a complete generic visitor for a parse tree produced by <file.parserName>.\n\nclass <file.grammarName>Visitor(ParseTreeVisitor):\n\n    <file.visitorNames:{lname |\n# Visit a parse tree produced by <file.parserName>#<lname>.\ndef visit<lname; format=\"cap\">(self, ctx:<file.parserName>.<lname; format=\"cap\">Context):\n    return self.visitChildren(ctx)\n\n}; separator=\"\\n\">\n\ndel <file.parserName>\n>>\n\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n# Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\n<Parser_(ctor=\"parser_ctor\", ...)>\n>>\n\nParser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<\n<if(superClass)>\nif \".\" in __name__:\n    from .<superClass> import <superClass>\nelse:\n    from <superClass> import <superClass>\n\n<endif>\n<atn>\n\nclass <parser.name> ( <if(superClass)><superClass><else>Parser<endif> ):\n\n    grammarFileName = \"<parser.grammarFileName>\"\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n    sharedContextCache = PredictionContextCache()\n\n    literalNames = [ <parser.literalNames:{t | <t>}; null=\"\\\"\\<INVALID>\\\"\", separator=\", \", wrap, anchor> ]\n\n    symbolicNames = [ <parser.symbolicNames:{t | <t>}; null=\"\\\"\\<INVALID>\\\"\", separator=\", \", wrap, anchor> ]\n\n    <if(parser.rules)>\n    <parser.rules:{r | RULE_<r.name> = <r.index>}; separator=\"\\n\", wrap, anchor>\n    <endif>\n\n    ruleNames =  [ <parser.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor> ]\n\n    EOF = <TokenLabelType()>.EOF\n    <if(parser.tokens)>\n    <parser.tokens:{k | <k>=<parser.tokens.(k)>}; separator=\"\\n\", wrap, anchor>\n    <endif>\n\n    <parser:(ctor)()>\n\n    <namedActions.members>\n\n    <funcs; separator=\"\\n\">\n\n\n<if(sempredFuncs)>\n    def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):\n        if self._predicates == None:\n            self._predicates = dict()\n<parser.sempredFuncs.values:{f |\n        self._predicates[<f.ruleIndex>] = self.<f.name>_sempred}; separator=\"\\n        \">\n        pred = self._predicates.get(ruleIndex, None)\n        if pred is None:\n            raise Exception(\"No predicate with index:\" + str(ruleIndex))\n        else:\n            return pred(localctx, predIndex)\n\n    <sempredFuncs.values; separator=\"\\n\">\n<endif>\n\n\n\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\ndef action(self, localctx:RuleContext, ruleIndex:int, actionIndex:int):\n    if self._actions is None:\n        actions = dict()\n<recog.actionFuncs.values:{f|\n        actions[<f.ruleIndex>] = self.<f.name>_action }; separator=\"\\n\">\n        self._actions = actions\n    action = self._actions.get(ruleIndex, None)\n    if action is not None:\n        action(localctx, actionIndex)\n    else:\n        raise Exception(\"No registered action for:\" + str(ruleIndex))\n\n<actionFuncs.values; separator=\"\\n\">\n\n<endif>\n<if(sempredFuncs)>\ndef sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):\n    if self._predicates is None:\n        preds = dict()\n<recog.sempredFuncs.values:{f|\n        preds[<f.ruleIndex>] = self.<f.name>_sempred}; separator=\"\\n\">\n        self._predicates = preds\n    pred = self._predicates.get(ruleIndex, None)\n    if pred is not None:\n        return pred(localctx, predIndex)\n    else:\n        raise Exception(\"No registered predicate for:\" + str(ruleIndex))\n\n<sempredFuncs.values; separator=\"\\n\">\n<endif>\n>>\n\nparser_ctor(p) ::= <<\ndef __init__(self, input:TokenStream, output:TextIO = sys.stdout):\n    super().__init__(input, output)\n    self.checkVersion(\"<file.ANTLRVersion>\")\n    self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)\n    self._predicates = None\n\n>>\n\n/* This generates a private method since the actionIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\n\ndef <r.name>_action(self, localctx:<r.ctxType> , actionIndex:int):\n<actions:{index|\n<if(first(actions))>\n    if actionIndex == <index>:\n        <actions.(index)>\n<elseif(rest(actions))>\n    elif actionIndex == <index>:\n        <actions.(index)>\n<endif> }; separator=\"\\n\">\n>>\n\n/* This generates a private method since the predIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\ndef <r.name>_sempred(self, localctx:<r.ctxType>, predIndex:int):\n    <actions:{index|\n<if(first(actions))>\n    if predIndex == <index>:\n        return <actions.(index)>\n<elseif(rest(actions))>\n    elif predIndex == <index>:\n        return <actions.(index)>\n<endif> }; separator=\"\\n\">\n\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<\n\n<ruleCtx>\n\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n\ndef <currentRule.escapedName>(self<currentRule.args:{a | , <a.escapedName><if(a.type)>:<a.type><endif>}>):\n\n    localctx = <parser.name>.<currentRule.ctxType>(self, self._ctx, self.state<currentRule.args:{a | , <a.escapedName>}>)\n    self.enterRule(localctx, <currentRule.startState>, self.RULE_<currentRule.name>)\n    <namedActions.init>\n    <locals; separator=\"\\n\">\n    try:\n        <code>\n        <postamble; separator=\"\\n\">\n        <namedActions.after>\n    <if(exceptions)>\n    <exceptions; separator=\"\\n\">\n    <else>\n    except RecognitionException as re:\n        localctx.exception = re\n        self._errHandler.reportError(self, re)\n        self._errHandler.recover(self, re)\n    <endif>\n    finally:\n        <finallyAction>\n        self.exitRule()\n    return localctx\n\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,\n\tnamedActions,finallyAction,postamble) ::=\n<<\n\n<ruleCtx>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n\ndef <currentRule.escapedName>(self, _p:int=0<if(currentRule.args)>, <args:{a | , <a>}><endif>):\n    _parentctx = self._ctx\n    _parentState = self.state\n    localctx = <parser.name>.<currentRule.ctxType>(self, self._ctx, _parentState<args:{a | , <a.escapedName>}>)\n    _prevctx = localctx\n    _startState = <currentRule.startState>\n    self.enterRecursionRule(localctx, <currentRule.startState>, self.RULE_<currentRule.name>, _p)\n    <namedActions.init>\n    <locals; separator=\"\\n\">\n    try:\n        <code>\n        <postamble; separator=\"\\n\">\n        <namedActions.after>\n    except RecognitionException as re:\n        localctx.exception = re\n        self._errHandler.reportError(self, re)\n        self._errHandler.recover(self, re)\n    finally:\n        <finallyAction>\n        self.unrollRecursionContexts(_parentctx)\n    return localctx\n\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>localctx = <parser.name>.<currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(self, localctx)<endif>\nself.enterOuterAlt(localctx, <currentOuterMostAltCodeBlock.alt.altNum>)\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nself.state = <choice.stateNumber>\nself._errHandler.sync(self)\n<if(choice.label)><labelref(choice.label)> = _input.LT(1)<endif>\n<preamble; separator=\"\\n\">\ntoken = self._input.LA(1)\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n    <alt>\n    pass}; separator=\"\\nel\">\nelse:\n    <error>\n\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\nself.state = <choice.stateNumber>\nself._errHandler.sync(self)\ntoken = self._input.LA(1)\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n    <alt>\n    pass}; separator=\"\\nel\">\nelse:\n    pass\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nself.state = <choice.stateNumber>\nself._errHandler.sync(self)\n<preamble; separator=\"\\n\">\nif <expr>:\n    <alts; separator=\"\\n\">\n\n<!else if ( !(<followExpr>) ) <error>!>\n>>\n\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nself.state = <choice.stateNumber>\nself._errHandler.sync(self)\n<preamble; separator=\"\\n\">\nwhile <loopExpr>:\n    <alts; separator=\"\\n\">\n    self.state = <choice.loopBackStateNumber>\n    self._errHandler.sync(self)\n    <iteration>\n\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nself.state = <choice.blockStartStateNumber> <! alt block decision !>\nself._errHandler.sync(self)\n<preamble; separator=\"\\n\">\nwhile True:\n    <alts; separator=\"\\n\">\n    self.state = <choice.stateNumber> <! loopback/exit decision !>\n    self._errHandler.sync(self)\n    <iteration>\n    if not (<loopExpr>):\n        break\n\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\nself.state = <choice.stateNumber>\nself._errHandler.sync(self)\n<if(choice.label)><labelref(choice.label)> = _input.LT(1)<endif>\n<preamble; separator=\"\\n\">\nla_ = self._interp.adaptivePredict(self._input,<choice.decision>,self._ctx)\n<alts:{alt |\nif la_ == <i>:\n    <alt>\n    pass\n}; separator=\"\\nel\">\n\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\nself.state = <choice.stateNumber>\nself._errHandler.sync(self)\nla_ = self._interp.adaptivePredict(self._input,<choice.decision>,self._ctx)\n<alts:{alt |\nif la_ == <i><if(!choice.ast.greedy)>+1<endif>:\n    <alt>\n}; separator=\"\\nel\">\n\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\nself.state = <choice.stateNumber>\nself._errHandler.sync(self)\n_alt = self._interp.adaptivePredict(self._input,<choice.decision>,self._ctx)\nwhile _alt!=<choice.exitAlt> and _alt!=ATN.INVALID_ALT_NUMBER:\n    if _alt==1<if(!choice.ast.greedy)>+1<endif>:\n        <iteration>\n        <alts> <! should only be one !>\n    self.state = <choice.loopBackStateNumber>\n    self._errHandler.sync(self)\n    _alt = self._interp.adaptivePredict(self._input,<choice.decision>,self._ctx)\n\n>>\n\nPlusBlock(choice, alts, error) ::= <<\nself.state = <choice.blockStartStateNumber> <! alt block decision !>\nself._errHandler.sync(self)\n_alt = 1<if(!choice.ast.greedy)>+1<endif>\nwhile _alt!=<choice.exitAlt> and _alt!=ATN.INVALID_ALT_NUMBER:\n    <alts:{alt|\nif _alt == <i><if(!choice.ast.greedy)>+1<endif>:\n    <alt>\n}; separator=\"\\nel\">\n    else:\n        <error>\n    self.state = <choice.loopBackStateNumber> <! loopback/exit decision !>\n    self._errHandler.sync(self)\n    _alt = self._interp.adaptivePredict(self._input,<choice.decision>,self._ctx)\n\n>>\n\nSync(s) ::= \"sync(<s.expecting.name>)\"\n\nThrowNoViableAlt(t) ::= \"raise NoViableAltException(self)\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" or \">\n>>\n\n// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount>) & ~0x3f) == 0\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShiftVar(s.varName, bits.shift)>})> and ((1 \\<\\< <offsetShiftVar(s.varName, bits.shift)>) & <bits.calculated>) != 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShiftVar(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\noffsetShiftType(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<parser.name>.<shiftAmount> - <offset>)<else><parser.name>.<shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName>==<t.type>}; separator=\" or \">\n%>\n\ncases(tokens) ::= <<\nif token in [<tokens:{t | <t.type>}; separator=\", \">]:\n>>\n\nInvokeRule(r, argExprsChunks) ::= <<\nself.state = <r.stateNumber>\n<if(r.labels)><r.labels:{l | <labelref(l)> = }><endif>self.<r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>)\n>>\n\nMatchToken(m) ::= <<\nself.state = <m.stateNumber>\n<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>self.match(<parser.name>.<m.name>)\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nself.state = <m.stateNumber>\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>self._input.LT(1)<endif>\n<capture>\n<if(invert)>if <m.varName> \\<= 0 or <expr><else>if not(<expr>)<endif>:\n<if(m.labels)><m.labels:{l |     <labelref(l)> = }><else>    <endif>self._errHandler.recoverInline(self)\nelse:\n    self._errHandler.reportMatch(self)\n    self.consume()\n>>\n\nWildcard(w) ::= <<\nself.state = <w.stateNumber>\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>self.matchWildcard()\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\nself.state = <p.stateNumber>\nif not <chunks>:\n    from antlr4.error.Errors import FailedPredicateException\n    raise FailedPredicateException(self, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>)\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\nexcept <catchArg>:\n    <catchAction>\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"skip()\"\nLexerMoreCommand()  ::= \"more()\"\nLexerPopModeCommand() ::= \"popMode()\"\n\nLexerTypeCommand(arg, grammar)      ::= \"_type = <arg>\"\nLexerChannelCommand(arg, grammar)   ::= \"_channel = <arg>\"\nLexerModeCommand(arg, grammar)      ::= \"_mode = <arg>\"\nLexerPushModeCommand(arg, grammar)  ::= \"pushMode(<arg>)\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"localctx.<a.escapedName>\"\nLocalRef(a) ::= \"localctx.<a.escapedName>\"\nRetValueRef(a) ::= \"localctx.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>.<a.dict>.<a.escapedName>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nLabelRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nListLabelRef(t) ::= \"<ctx(t)>.<ListLabelName(t.escapedName)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>.<s.escapedName> = <rhsChunks>\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={Token}>\"\n\nTokenPropertyRef_text(t) ::= \"(None if <ctx(t)>.<t.label> is None else <ctx(t)>.<t.label>.text)\"\nTokenPropertyRef_type(t) ::= \"(0 if <ctx(t)>.<t.label> is None else <ctx(t)>.<t.label>.type)\"\nTokenPropertyRef_line(t) ::= \"(0 if <ctx(t)>.<t.label> is None else <ctx(t)>.<t.label>.line)\"\nTokenPropertyRef_pos(t) ::= \"(0 if <ctx(t)>.<t.label> is None else <ctx(t)>.<t.label>.column)\"\nTokenPropertyRef_channel(t) ::= \"(0 if <ctx(t)>.<t.label> is None else <ctx(t)>.<t.label>.channel)\"\nTokenPropertyRef_index(t) ::= \"(0 if <ctx(t)>.<t.label> is None else <ctx(t)>.<t.label>.tokenIndex)\"\nTokenPropertyRef_int(t) ::= \"(0 if <ctx(t)>.<t.label> is None else int(<ctx(t)>.<t.label>.text))\"\n\nRulePropertyRef_start(r) ::= \"(None if <ctx(r)>.<r.label> is None else <ctx(r)>.<r.label>.start)\"\nRulePropertyRef_stop(r)\t ::= \"(None if <ctx(r)>.<r.label> is None else <ctx(r)>.<r.label>.stop)\"\nRulePropertyRef_text(r)\t ::= \"(None if <ctx(r)>.<r.label> is None else self._input.getText(<ctx(r)>.<r.label>.start,<ctx(r)>.<r.label>.stop))\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>.<r.label>\"\nRulePropertyRef_parser(r)\t ::= \"self\"\n\nThisRulePropertyRef_start(r) ::= \"localctx.start\"\nThisRulePropertyRef_stop(r)\t ::= \"localctx.stop\"\nThisRulePropertyRef_text(r)\t ::= \"self._input.getText(localctx.start, self._input.LT(-1))\"\nThisRulePropertyRef_ctx(r)\t ::= \"localctx\"\nThisRulePropertyRef_parser(r)\t ::= \"self\"\n\nNonLocalAttrRef(s)\t\t \t ::= \"self.getInvokingContext(<s.ruleIndex>).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks)  ::= \"self.getInvokingContext(<s.ruleIndex>).<s.escapedName> = <rhsChunks>\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>.<a.listName>.append(<labelref(a.label)>)\"\n\nTokenDecl(t) ::= \"self.<t.escapedName> = None # <TokenLabelType()>\"\nTokenTypeDecl(t) ::= \"self.<t.escapedName> = 0 # <TokenLabelType()> type\"\nTokenListDecl(t) ::= \"self.<t.escapedName> = list() # of <TokenLabelType()>s\"\nRuleContextDecl(r) ::= \"self.<r.escapedName> = None # <r.ctxName>\"\nRuleContextListDecl(rdecl) ::= \"self.<rdecl.escapedName> = list() # of <rdecl.ctxName>s\"\n\nContextTokenGetterDecl(t)      ::= <<\ndef <t.escapedName>(self):\n    return self.getToken(<parser.name>.<t.name>, 0)\n>>\n\n// should never be called\nContextTokenListGetterDecl(t)  ::= <<\ndef <t.name>_list(self):\n    return self.getTokens(<parser.name>.<t.name>)\n>>\n\nContextTokenListIndexedGetterDecl(t)  ::= <<\ndef <t.escapedName>(self, i:int=None):\n    if i is None:\n        return self.getTokens(<parser.name>.<t.name>)\n    else:\n        return self.getToken(<parser.name>.<t.name>, i)\n>>\n\nContextRuleGetterDecl(r)       ::= <<\ndef <r.escapedName>(self):\n    return self.getTypedRuleContext(<parser.name>.<r.ctxName>,0)\n\n>>\n\n// should never be called\nContextRuleListGetterDecl(r)   ::= <<\ndef <r.name>_list(self):\n    return self.getTypedRuleContexts(<parser.name>.<r.ctxName>)\n\n>>\n\nContextRuleListIndexedGetterDecl(r)   ::= <<\ndef <r.escapedName>(self, i:int=None):\n    if i is None:\n        return self.getTypedRuleContexts(<parser.name>.<r.ctxName>)\n    else:\n        return self.getTypedRuleContext(<parser.name>.<r.ctxName>,i)\n\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/** The rule context name is the rule followed by a suffix; e.g.,\n *  r becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"_<tokenName>\"\nImplicitRuleLabel(ruleName)\t  ::= \"_<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = self._input.LT(1)\"\nCaptureNextTokenType(d) ::= \"<d.varName> = self._input.LA(1)\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures) ::= <<\nclass <struct.escapedName>(<if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif>):\n    __slots__ = 'parser'\n\n    def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1<struct.ctorAttrs:{a | , <a.escapedName><if(a.type)>:<a.type><endif>=None}>):\n        super().__init__(parent, invokingState)\n        self.parser = parser\n        <attrs:{a | <a>}; separator=\"\\n\">\n        <struct.ctorAttrs:{a | self.<a.escapedName> = <a.escapedName>}; separator=\"\\n\">\n\n    <getters:{g | <g>}; separator=\"\\n\\n\">\n\n    def getRuleIndex(self):\n        return <parser.name>.RULE_<struct.derivedFromName>\n\n<if(struct.provideCopyFrom)> <! don't need copy unless we have subclasses !>\n    def copyFrom(self, ctx:ParserRuleContext):\n        super().copyFrom(ctx)\n        <struct.attrs:{a | self.<a.escapedName> = ctx.<a.escapedName>}; separator=\"\\n\">\n\n<endif>\n    <dispatchMethods; separator=\"\\n\">\n    <extensionMembers; separator=\"\\n\">\n\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\nclass <struct.escapedName>(<currentRule.name; format=\"cap\">Context):\n\n    def __init__(self, parser, ctx:ParserRuleContext): # actually a <parser.name>.<currentRule.name; format=\"cap\">Context\n        super().__init__(parser)\n        <attrs:{a | <a>}; separator=\"\\n\">\n        self.copyFrom(ctx)\n\n    <getters:{g | <g>}; separator=\"\\n\">\n\n    <dispatchMethods; separator=\"\\n\">\n\n>>\n\nListenerDispatchMethod(method) ::= <<\ndef <if(method.isEnter)>enter<else>exit<endif>Rule(self, listener:ParseTreeListener):\n    if hasattr( listener, \"<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">\" ):\n        listener.<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">(self)\n\n>>\n\nVisitorDispatchMethod(method) ::= <<\ndef accept(self, visitor:ParseTreeVisitor):\n    if hasattr( visitor, \"visit<struct.derivedFromName; format=\"cap\">\" ):\n        return visitor.visit<struct.derivedFromName; format=\"cap\">(self)\n    else:\n        return visitor.visitChildren(self)\n\n>>\n\nAttributeDecl(d) ::= \"self.<d.escapedName> = <if(d.initValue)><d.initValue><else>None<endif>\"\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if(!x.isLocal)>localctx.<endif><x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"localctx\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"self.precpred(self._ctx, <opPrec>)\"\nrecRuleSetReturnAction(src,name)\t  ::= \"$<name>=$<src>.<name>\"\nrecRuleSetStopToken()                 ::= \"self._ctx.stop = self._input.LT(-1)\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\nlocalctx = <parser.name>.<ctxName>Context(self, _parentctx, _parentState)\n<if(label)>\n<if(isListLabel)>\nlocalctx.<label>.append(_prevctx)\n<else>\nlocalctx.<label> = _prevctx\n<endif>\n<endif>\nself.pushNewRecursionContext(localctx, _startState, self.RULE_<ruleName>)\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\nlocalctx = <parser.name>.<currentAltLabel; format=\"cap\">Context(self, <parser.name>.<ruleName; format=\"cap\">Context(self, _parentctx, _parentState))\n<if(label)>\n<if(isListLabel)>\nlocalctx.<label>.append(_prevctx)\n<else>\nlocalctx.<label> = _prevctx\n<endif>\n<endif>\nself.pushNewRecursionContext(localctx, _startState, self.RULE_<ruleName>)\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\nlocalctx = <parser.name>.<ctxName>Context(self, localctx)\nself._ctx = localctx\n_prevctx = localctx\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif self._parseListeners is not None:\n    self.triggerExitRuleEvent()\n_prevctx = localctx\n>>\n\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\nfrom antlr4 import *\nfrom io import StringIO\nimport sys\nif sys.version_info >= (3, 6):\n    from typing import TextIO\nelse:\n    from typing.io import TextIO\n\n<namedActions.header>\n\n<lexer>\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\n<if(superClass)>\nif \".\" in __name__:\n    from .<superClass> import <superClass>\nelse:\n    from <superClass> import <superClass>\n\n<endif>\n<atn>\n\nclass <lexer.name>(<if(superClass)><superClass><else>Lexer<endif>):\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n<if(lexer.escapedChannels)>\n    <lexer.escapedChannels:{c| <c> = <lexer.escapedChannels.(c)>}; separator=\"\\n\">\n\n<endif>\n<if(rest(lexer.escapedModeNames))>\n    <rest(lexer.escapedModeNames):{m| <m> = <i>}; separator=\"\\n\">\n\n<endif>\n    <if(lexer.tokens)>\n    <lexer.tokens:{k | <k> = <lexer.tokens.(k)>}; separator=\"\\n\", wrap, anchor>\n    <endif>\n\n    channelNames = [ u\"DEFAULT_TOKEN_CHANNEL\", u\"HIDDEN\"<if (lexer.channelNames)>, <lexer.channelNames:{c| u\"<c>\"}; separator=\", \", wrap, anchor><endif> ]\n\n    modeNames = [ <lexer.modes:{m| \"<m>\"}; separator=\", \", wrap, anchor> ]\n\n    literalNames = [ \"\\<INVALID>\",\n            <lexer.literalNames:{t | <t>}; separator=\", \", wrap, anchor> ]\n\n    symbolicNames = [ \"\\<INVALID>\",\n            <lexer.symbolicNames:{t | <t>}; separator=\", \", wrap, anchor> ]\n\n    ruleNames = [ <lexer.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor> ]\n\n    grammarFileName = \"<lexer.grammarFileName>\"\n\n    def __init__(self, input=None, output:TextIO = sys.stdout):\n        super().__init__(input, output)\n        self.checkVersion(\"<lexerFile.ANTLRVersion>\")\n        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())\n        self._actions = None\n        self._predicates = None\n\n    <namedActions.members>\n\n    <dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n\n>>\n\nSerializedATN(model) ::= <<\ndef serializedATN():\n    return [\n        <model.serialized: {s | <s>}; separator=\",\", wrap>\n    ]\n>>\n\n/** Using a type to init value map, try to init a type; if not in table\n *  must be an object, default value is \"null\".\n */\ninitValue(typeName) ::= <<\n<pythonTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".py\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/Swift/Swift.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  Copyright (c) 2015 Janyou\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nSwiftTypeInitMap ::= [\n\t\"Int\":\"0\",\n\t\"Int64\":\"0\",\n\t\"Float\":\"0.0\",\n\t\"Double\":\"0.0\",\n\t\"Bool\":\"false\",\n\tdefault:\"nil\" // anything other than a primitive type is an object\n]\nSwiftTypeMap ::= [\n\t\"int\":\"Int\",\n\t\"float\":\"Float\",\n\t\"long\":\"Int64\",\n\t\"double\":\"Double\",\n\t\"bool\":\"Bool\",\n\t\"boolean\":\"Bool\",\n\tdefault : key\n]\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\naccessLevelOpenOK(obj) ::= \"<obj.accessLevel; null=\\\"open\\\">\"\naccessLevelNotOpen(obj) ::= \"<obj.accessLevel; null=\\\"public\\\">\"\n\nParserFile(file, parser, namedActions,contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\n<!package <file.genPackage>;!>\n<endif>\n<namedActions.header>\nimport Antlr4\n\n<parser>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\n<!package <file.genPackage>;!>\n<endif>\n<header>\nimport Antlr4\n\n/**\n * This interface defines a complete listener for a parse tree produced by\n * {@link <file.parserName>}.\n */\n<accessLevelNotOpen(file)> protocol <file.grammarName>Listener: ParseTreeListener {\n\t<file.listenerNames:{lname |\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Enter a parse tree produced by the {@code <lname>\\}\n * labeled alternative in {@link <file.parserName>#<file.listenerLabelRuleNames.(lname)>\\}.\n<else>\n * Enter a parse tree produced by {@link <file.parserName>#<lname>\\}.\n<endif>\n - Parameters:\n   - ctx: the parse tree\n */\nfunc enter<lname; format=\"cap\">(_ ctx: <file.parserName>.<lname; format=\"cap\">Context)\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Exit a parse tree produced by the {@code <lname>\\}\n * labeled alternative in {@link <file.parserName>#<file.listenerLabelRuleNames.(lname)>\\}.\n<else>\n * Exit a parse tree produced by {@link <file.parserName>#<lname>\\}.\n<endif>\n - Parameters:\n   - ctx: the parse tree\n */\nfunc exit<lname; format=\"cap\">(_ ctx: <file.parserName>.<lname; format=\"cap\">Context)}; separator=\"\\n\">\n}\n>>\n\nBaseListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\n<!package <file.genPackage>;!>\n<endif>\n<header>\n\nimport Antlr4\n\n\n/**\n * This class provides an empty implementation of {@link <file.grammarName>Listener},\n * which can be extended to create a listener which only needs to handle a subset\n * of the available methods.\n */\n<accessLevelOpenOK(file)> class <file.grammarName>BaseListener: <file.grammarName>Listener {\n     <accessLevelNotOpen(file)> init() { \\}\n\t<file.listenerNames:{lname |\n\n/**\n * {@inheritDoc\\}\n *\n * \\<p>The default implementation does nothing.\\</p>\n */\n<accessLevelOpenOK(file)> func enter<lname; format=\"cap\">(_ ctx: <file.parserName>.<lname; format=\"cap\">Context) { \\}\n/**\n * {@inheritDoc\\}\n *\n * \\<p>The default implementation does nothing.\\</p>\n */\n<accessLevelOpenOK(file)> func exit<lname; format=\"cap\">(_ ctx: <file.parserName>.<lname; format=\"cap\">Context) { \\}}; separator=\"\\n\">\n\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t<accessLevelOpenOK(file)> func enterEveryRule(_ ctx: ParserRuleContext) throws { }\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t<accessLevelOpenOK(file)> func exitEveryRule(_ ctx: ParserRuleContext) throws { }\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t<accessLevelOpenOK(file)> func visitTerminal(_ node: TerminalNode) { }\n\t/**\n\t * {@inheritDoc\\}\n\t *\n\t * \\<p>The default implementation does nothing.\\</p>\n\t */\n\t<accessLevelOpenOK(file)> func visitErrorNode(_ node: ErrorNode) { }\n}\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\n<!package <file.genPackage>;!>\n<endif>\n<header>\nimport Antlr4\n\n/**\n * This interface defines a complete generic visitor for a parse tree produced\n * by {@link <file.parserName>}.\n *\n * @param \\<T> The return type of the visit operation. Use {@link Void} for\n * operations with no return type.\n */\n<accessLevelOpenOK(file)> class <file.grammarName>Visitor\\<T>: ParseTreeVisitor\\<T> {\n\t<file.visitorNames:{lname |\n/**\n<if(file.visitorLabelRuleNames.(lname))>\n * Visit a parse tree produced by the {@code <lname>\\}\n * labeled alternative in {@link <file.parserName>#<file.visitorLabelRuleNames.(lname)>\\}.\n<else>\n * Visit a parse tree produced by {@link <file.parserName>#<lname>\\}.\n<endif>\n- Parameters:\n  - ctx: the parse tree\n- returns: the visitor result\n */\n<accessLevelOpenOK(file)> func visit<lname; format=\"cap\">(_ ctx: <file.parserName>.<lname; format=\"cap\">Context) -> T {\n \tfatalError(#function + \" must be overridden\")\n\\}\n}; separator=\"\\n\">\n}\n>>\n\nBaseVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n<if(file.genPackage)>\n<!package <file.genPackage>;!>\n<endif>\n<header>\nimport Antlr4\n\n/**\n * This class provides an empty implementation of {@link <file.grammarName>Visitor},\n * which can be extended to create a visitor which only needs to handle a subset\n * of the available methods.\n *\n * @param \\<T> The return type of the visit operation. Use {@link Void} for\n * operations with no return type.\n */\n<accessLevelOpenOK(file)> class <file.grammarName>BaseVisitor\\<T>: AbstractParseTreeVisitor\\<T> {\n\t<file.visitorNames:{lname |\n/**\n * {@inheritDoc\\}\n *\n * \\<p>The default implementation returns the result of calling\n * {@link #visitChildren\\} on {@code ctx\\}.\\</p>\n */\n<accessLevelOpenOK(file)> func visit<lname; format=\"cap\">(_ ctx: <file.parserName>.<lname; format=\"cap\">Context) -> T? { return visitChildren(ctx) \\}}; separator=\"\\n\">\n}\n>>\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n// Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass) ::= <<\n<Parser_(ctor=\"parser_ctor\", ...)>\n>>\n\nParser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<\n<!//@SuppressWarnings({\"all\", \"warnings\", \"unchecked\", \"unused\", \"cast\"})!>\n<accessLevelOpenOK(parser)> class <parser.name>: <superClass; null=\"Parser\"> {\n\n\tinternal static var _decisionToDFA: [DFA] = {\n          var decisionToDFA = [DFA]()\n          let length = <parser.name>._ATN.getNumberOfDecisions()\n          for i in 0..\\<length {\n           <!// decisionToDFA[i] = DFA(<parser.name>._ATN.getDecisionState(i)!, i);!>\n            decisionToDFA.append(DFA(<parser.name>._ATN.getDecisionState(i)!, i))\n           }\n           return decisionToDFA\n     }()\n\n\tinternal static let _sharedContextCache = PredictionContextCache()\n\n\t<if(parser.tokens)>\n\t<accessLevelNotOpen(parser)>\n\tenum Tokens: Int {\n\t\tcase EOF = -1, <parser.tokens:{k | <k> = <parser.tokens.(k)>}; separator=\", \", wrap, anchor>\n\t}\n\t<endif>\n\n\t<accessLevelNotOpen(parser)>\n\t<if(parser.rules)>\n\tstatic let <parser.rules:{r | RULE_<r.name> = <r.index>}; separator=\", \", wrap, anchor>\n\t<endif>\n\n\t<accessLevelNotOpen(parser)>\n\tstatic let ruleNames: [String] = [\n\t\t<parser.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor>\n\t]\n\n\t<vocabulary(parser.literalNames, parser.symbolicNames,\n                    accessLevelNotOpen(parser))>\n\n\toverride <accessLevelOpenOK(parser)>\n\tfunc getGrammarFileName() -> String { return \"<parser.grammarFileName>\" }\n\n\toverride <accessLevelOpenOK(parser)>\n\tfunc getRuleNames() -> [String] { return <parser.name>.ruleNames }\n\n\toverride <accessLevelOpenOK(parser)>\n\tfunc getSerializedATN() -> [Int] { return <parser.name>._serializedATN }\n\n\toverride <accessLevelOpenOK(parser)>\n\tfunc getATN() -> ATN { return <parser.name>._ATN }\n\n\t<namedActions.members>\n\t<parser:(ctor)()>\n\t<funcs; separator=\"\\n\">\n\n<if(sempredFuncs)>\n\toverride <accessLevelOpenOK(parser)>\n\tfunc sempred(_ _localctx: RuleContext?, _ ruleIndex: Int,  _ predIndex: Int)throws -> Bool {\n\t\tswitch (ruleIndex) {\n\t\t<parser.sempredFuncs.values:{f|\ncase  <f.ruleIndex>:\n\treturn try <f.name>_sempred(_localctx?.castdown(<f.ctxType>.self), predIndex)}; separator=\"\\n\">\n\t    default: return true\n\t\t}\n\t\t<!return true;!>\n\t}\n\t<sempredFuncs.values; separator=\"\\n\">\n<endif>\n\n\t<atn>\n\n\t<accessLevelNotOpen(parser)>\n\tstatic let _ATN = try! ATNDeserializer().deserialize(_serializedATN)\n}\n>>\n\nvocabulary(literalNames, symbolicNames, accessLevel) ::= <<\nprivate static let _LITERAL_NAMES: [String?] = [\n\t<literalNames:{t | <t>}; null=\"nil\", separator=\", \", wrap, anchor>\n]\nprivate static let _SYMBOLIC_NAMES: [String?] = [\n\t<symbolicNames:{t | <t>}; null=\"nil\", separator=\", \", wrap, anchor>\n]\n<accessLevel>\nstatic let VOCABULARY = Vocabulary(_LITERAL_NAMES, _SYMBOLIC_NAMES)\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\noverride <accessLevelOpenOK(parser)>\nfunc action(_ _localctx: RuleContext?,  _ ruleIndex: Int, _ actionIndex: Int) throws {\n\tswitch (ruleIndex) {\n\t<recog.actionFuncs.values:{f|\ncase <f.ruleIndex>:\n\ttry <f.name>_action((_localctx as <f.ctxType>?), actionIndex)\n\t }; separator=\"\\n\">\n\tdefault: break\n\t}\n}\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<if(sempredFuncs)>\noverride <accessLevelOpenOK(parser)>\nfunc sempred(_ _localctx: RuleContext?, _  ruleIndex: Int,_   predIndex: Int) throws -> Bool {\n\tswitch (ruleIndex) {\n\t<recog.sempredFuncs.values:{f|\ncase <f.ruleIndex>:\n\treturn try <f.name>_sempred(_localctx?.castdown(<f.ctxType>.self), predIndex)}; separator=\"\\n\">\n\tdefault: return true\n\t}\n\t<!return true;!>\n}\n<sempredFuncs.values; separator=\"\\n\">\n<endif>\n>>\n\nparser_ctor(p) ::= <<\n\noverride <accessLevelOpenOK(parser)>\nfunc getVocabulary() -> Vocabulary {\n    return <p.name>.VOCABULARY\n}\n\noverride <accessLevelNotOpen(parser)>\ninit(_ input:TokenStream) throws {\n    RuntimeMetaData.checkVersion(\"<file.ANTLRVersion>\", RuntimeMetaData.VERSION)\n\ttry super.init(input)\n\t_interp = ParserATNSimulator(self,<p.name>._ATN,<p.name>._decisionToDFA, <parser.name>._sharedContextCache)\n}\n\n>>\n\n/* This generates a private method since the actionIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\nprivate func <r.name>_action(_ _localctx: <r.ctxType>?,  _ actionIndex: Int) throws {\n\tswitch (actionIndex) {\n\t<actions:{index|\ncase <index>:\n\t<actions.(index)>\n\t }; separator=\"\\n\">\n\t default: break\n\t}\n}\n>>\n\n/* This generates a private method since the predIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\nprivate func <r.name>_sempred(_ _localctx: <r.ctxType>!,  _ predIndex: Int) throws -> Bool {\n\tswitch (predIndex) {\n\t<actions:{index|\n    case <index>:return <actions.(index)>}; separator=\"\\n\">\n\t    default: return true\n\t}\n\t<!return true;!>\n}\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<\n<ruleCtx>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n@discardableResult\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else> <accessLevelOpenOK(parser)> func <endif><currentRule.escapedName>(<if(first(args))>_ <endif><args; separator=\", _\">) throws -> <currentRule.ctxType> {\n\tvar _localctx: <currentRule.ctxType>\n\t_localctx = <currentRule.ctxType>(_ctx, getState()<currentRule.args:{a | , <a.escapedName>}>)\n\ttry enterRule(_localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.name>)\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\tdefer {\n    \t\t<finallyAction>\n    \t\ttry! exitRule()\n    }\n\tdo {\n<if(currentRule.hasLookaheadBlock)>\n\t\tvar _alt:Int\n<endif>\n\t \t<code>\n\t\t<postamble; separator=\"\\n\">\n\t \t<namedActions.after>\n\t}\n\t<if(exceptions)>\n\t<exceptions; separator=\"\\n\">\n\t<else>\n\tcatch ANTLRException.recognition(let re) {\n\t\t_localctx.exception = re\n\t\t_errHandler.reportError(self, re)\n\t\ttry _errHandler.recover(self, re)\n\t}\n\t<endif>\n\n\treturn _localctx\n}\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,\n\tnamedActions,finallyAction,postamble) ::=\n<<\n\n<ruleCtx>\n<altLabelCtxs:{l | <altLabelCtxs.(l)>}; separator=\"\\n\">\n\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else> <accessLevelNotOpen(parser)> final <endif> func <currentRule.escapedName>( <if(first(args))>_ <endif><args; separator=\", _\">) throws -> <currentRule.ctxType>   {\n\treturn try <currentRule.escapedName>(0<currentRule.args:{a | , <a.escapedName>}>)\n}\n@discardableResult\nprivate func <currentRule.escapedName>(_ _p<args:{a | , <a>}>: Int) throws -> <currentRule.ctxType>   {\n\tlet _parentctx: ParserRuleContext? = _ctx\n\tlet _parentState: Int = getState()\n\tvar _localctx: <currentRule.ctxType>\n\t_localctx = <currentRule.ctxType>(_ctx, _parentState<currentRule.args:{a | , <a.escapedName>}>)\n\tvar _prevctx: <currentRule.ctxType> = _localctx\n\tlet _startState: Int = <currentRule.startState>\n\ttry enterRecursionRule(_localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.name>, _p)\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\tdefer {\n    \t\t<finallyAction>\n    \t\ttry! unrollRecursionContexts(_parentctx)\n    }\n\tdo {\n<if(currentRule.hasLookaheadBlock)>\n\t\tvar _alt: Int\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\tcatch ANTLRException.recognition(let re) {\n\t\t_localctx.exception = re\n\t\t_errHandler.reportError(self, re)\n\t\ttry _errHandler.recover(self, re)\n\t}\n\n\treturn _localctx;\n}\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>_localctx =  <currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(_localctx);<endif>\ntry enterOuterAlt(_localctx, <currentOuterMostAltCodeBlock.alt.altNum>)\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<!//{!>\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n<!//}!>\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nsetState(<choice.stateNumber>)\ntry _errHandler.sync(self)\n<if(choice.label)><labelref(choice.label)> = try _input.LT(1)<endif>\n<preamble; separator=\"\\n\">\nswitch (<parser.name>.Tokens(rawValue: try _input.LA(1))!) {\n<choice.altLook,alts:{look,alt | <cases(tokens=look)>\n\t<alt>\n\tbreak}; separator=\"\\n\">\ndefault:\n\t<error>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\nsetState(<choice.stateNumber>)\ntry _errHandler.sync(self)\nswitch (<parser.name>.Tokens(rawValue: try _input.LA(1))!) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n \t<alt>\n\tbreak}; separator=\"\\n\">\ndefault:\n\tbreak\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nsetState(<choice.stateNumber>)\ntry _errHandler.sync(self)\n<preamble; separator=\"\\n\">\nif (<expr>) {\n\t<alts; separator=\"\\n\">\n}\n<!else if ( !(<followExpr>) ) <error>!>\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nsetState(<choice.stateNumber>)\ntry _errHandler.sync(self)\n<preamble; separator=\"\\n\">\nwhile (<loopExpr>) {\n\t<alts; separator=\"\\n\">\n\tsetState(<choice.loopBackStateNumber>)\n\ttry _errHandler.sync(self)\n\t<iteration>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nsetState(<choice.blockStartStateNumber>) <! alt block decision !>\ntry _errHandler.sync(self)\n<preamble; separator=\"\\n\">\nrepeat {\n\t<alts; separator=\"\\n\">\n\tsetState(<choice.stateNumber>); <! loopback/exit decision !>\n\ttry _errHandler.sync(self)\n\t<iteration>\n} while (<loopExpr>)\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\nsetState(<choice.stateNumber>)\ntry _errHandler.sync(self)\n<if(choice.label)><labelref(choice.label)> = try _input.LT(1)<endif>\n<preamble; separator=\"\\n\">\nswitch(try getInterpreter().adaptivePredict(_input,<choice.decision>, _ctx)) {\n<alts:{alt |\ncase <i>:\n\t<alt>\n\tbreak}; separator=\"\\n\">\ndefault: break\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\nsetState(<choice.stateNumber>)\ntry _errHandler.sync(self)\nswitch (try getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx)) {\n<alts:{alt |\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak}; separator=\"\\n\">\ndefault: break\n}\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\nsetState(<choice.stateNumber>)\ntry _errHandler.sync(self)\n_alt = try getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx)\nwhile (_alt != <choice.exitAlt> && _alt != ATN.INVALID_ALT_NUMBER) {\n\tif ( _alt==1<if(!choice.ast.greedy)>+1<endif> ) {\n\t\t<iteration>\n\t\t<alts> <! should only be one !>\n\t}\n\tsetState(<choice.loopBackStateNumber>)\n\ttry _errHandler.sync(self)\n\t_alt = try getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx)\n}\n>>\n\nPlusBlock(choice, alts, error) ::= <<\nsetState(<choice.blockStartStateNumber>); <! alt block decision !>\ntry _errHandler.sync(self)\n_alt = 1<if(!choice.ast.greedy)>+1<endif>;\nrepeat {\n\tswitch (_alt) {\n\t<alts:{alt|\ncase <i><if(!choice.ast.greedy)>+1<endif>:\n\t<alt>\n\tbreak}; separator=\"\\n\">\n\tdefault:\n\t\t<error>\n\t}\n\tsetState(<choice.loopBackStateNumber>); <! loopback/exit decision !>\n\ttry _errHandler.sync(self)\n\t_alt = try getInterpreter().adaptivePredict(_input,<choice.decision>,_ctx)\n} while (_alt != <choice.exitAlt> && _alt !=  ATN.INVALID_ALT_NUMBER)\n>>\n\nSync(s) ::= \"sync(<s.expecting.name>);\"\n\nThrowNoViableAlt(t) ::= \"throw ANTLRException.recognition(e: NoViableAltException(self))\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test\ntestShiftInRange(shiftAmount) ::= <<\n(Int64(<shiftAmount>) & ~0x3f) == 0\n>>\n\nbitsetBitfieldComparison(s, bits) ::= <<\n(<testShiftInRange({<offsetShift(s.varName, bits.shift)>})> && ((Int64(1) \\<\\< <offsetShift(s.varName, bits.shift)>) & <bits.calculated>) != 0)\n>>\n\nisZero ::= [\n\"0\": true,\ndefault: false\n]\nparserName(t) ::= <%\n <parser.name>.Tokens.<t.name>.rawValue\n%>\noffsetShift(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName> == <parser.name>.Tokens.<t.name>.rawValue}; separator=\" || \">\n%>\n\ncases(tokens) ::= <<\n<trunc(tokens): {t | case .<t.name>:fallthrough}  ; separator=\"\\n\">\n<last(tokens): {t | case .<t.name>:}  ; separator=\"\\n\">\n>>\n\nInvokeRule(r, argExprsChunks) ::= <<\nsetState(<r.stateNumber>)\n<if(r.labels)>\ntry {\n\t\tlet assignmentValue = try <r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>)\n\t\t<r.labels:{l | <labelref(l)> = assignmentValue} ; separator=\"\\n\">\n     }()\n<else>try <r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>)<endif>\n>>\n\nMatchToken(m) ::= <<\nsetState(<m.stateNumber>)\n<if(m.labels)>\ntry {\n\t\tlet assignmentValue = try match(<parser.name>.Tokens.<m.escapedName>.rawValue)\n\t\t<m.labels:{l | <labelref(l)> = assignmentValue}  ; separator=\"\\n\">\n     }()\n<else>try match(<parser.name>.Tokens.<m.escapedName>.rawValue)<endif>\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nsetState(<m.stateNumber>)\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>try _input.LT(1)<endif>\n<capture>\nif (<if(invert)><m.varName> \\<= 0 || <else>!<endif>(<expr>)) {\n\t<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>try _errHandler.recoverInline(self)<if(m.labels)> as Token<endif>\n}\nelse {\n\t_errHandler.reportMatch(self)\n\ttry consume()\n}\n>>\n\nWildcard(w) ::= <<\nsetState(<w.stateNumber>)\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>try matchWildcard();\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\nsetState(<p.stateNumber>)\nif (!(<chunks>)) {\n    throw ANTLRException.recognition(e:FailedPredicateException(self, <p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>))\n}\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n\t<catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"skip()\"\nLexerMoreCommand()  ::= \"more()\"\nLexerPopModeCommand() ::= \"popMode()\"\n\nLexerTypeCommand(arg)      ::= \"_type = <arg>\"\nLexerChannelCommand(arg)   ::= \"_channel = <arg>\"\nLexerModeCommand(arg)      ::= \"_mode = <arg>\"\nLexerPushModeCommand(arg)  ::= \"pushMode(<arg>)\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"_localctx.<a.escapedName>\"\nLocalRef(a) ::= \"_localctx.<a.escapedName>\"\nRetValueRef(a) ::= \"_localctx.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>.<a.dict>.<a.escapedName>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nLabelRef(t) ::= \"<ctx(t)>.<t.escapedName>\"\nListLabelRef(t) ::= \"<ctx(t)>.<ListLabelName(t.escapedName)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>.<s.escapedName> = <rhsChunks>\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={Token}>\"\n\nTokenPropertyRef_text(t) ::= \"(<ctx(t)>.<t.label> != nil ? <ctx(t)>.<t.label>!.getText()! : \\\"\\\")\"\nTokenPropertyRef_type(t) ::= \"(<ctx(t)>.<t.label> != nil ? <ctx(t)>.<t.label>!.getType() : 0)\"\nTokenPropertyRef_line(t) ::= \"(<ctx(t)>.<t.label> != nil ? <ctx(t)>.<t.label>!.getLine() : 0)\"\nTokenPropertyRef_pos(t) ::= \"(<ctx(t)>.<t.label> != nil ? <ctx(t)>.<t.label>!.getCharPositionInLine() : 0)\"\nTokenPropertyRef_channel(t) ::= \"(<ctx(t)>.<t.label> != nil ? <ctx(t)>.<t.label>!.getChannel() : 0)\"\nTokenPropertyRef_index(t) ::= \"(<ctx(t)>.<t.label> != nil ? <ctx(t)>.<t.label>!.getTokenIndex() : 0)\"\nTokenPropertyRef_int(t) ::= \"(<ctx(t)>.<t.label> != nil ? Int(<ctx(t)>.<t.label>!.getText()!) : 0)\"\n\nRulePropertyRef_start(r) ::= \"(<ctx(r)>.<r.label> != nil ? (<ctx(r)>.<r.label>!.start?.description ?? \\\"\\\") : \\\"\\\")\"\nRulePropertyRef_stop(r)\t ::= \"(<ctx(r)>.<r.label> != nil ? (<ctx(r)>.<r.label>!.stop?.description ?? \\\"\\\") : \\\"\\\")\"\nRulePropertyRef_text(r)\t ::= \"(<ctx(r)>.<r.label> != nil ? try _input.getText(<ctx(r)>.<r.label>!.start,<ctx(r)>.<r.label>!.stop) : \\\"\\\")\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>.<r.label>\"\nRulePropertyRef_parser(r)\t ::= \"self\"\n\nThisRulePropertyRef_start(r) ::= \"_localctx.start\"\nThisRulePropertyRef_stop(r)\t ::= \"_localctx.stop\"\nThisRulePropertyRef_text(r)\t ::= \"(try _input.getText(_localctx.start, try _input.LT(-1)))\"\nThisRulePropertyRef_ctx(r)\t ::= \"_localctx\"\nThisRulePropertyRef_parser(r)\t ::= \"self\"\n\nNonLocalAttrRef(s)\t\t ::= \"((<s.ruleName; format=\\\"cap\\\">Context)getInvokingContext(<s.ruleIndex>)).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks)\t  ::=\n\t\"((<s.ruleName; format=\\\"cap\\\">Context)getInvokingContext(<s.ruleIndex>)).<s.escapedName> = <rhsChunks>\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>.<a.listName>.append(<labelref(a.label)>)\"\n\nTokenDecl(t) ::= \"<t.escapedName>: <SwiftTypeMap.(TokenLabelType())>!\"\nTokenTypeDecl(t) ::= \"var <t.escapedName>: Int = 0\"\nTokenListDecl(t) ::= \"<t.escapedName>: [Token] = [Token]()\"\nRuleContextDecl(r) ::= \"<r.escapedName>: <r.ctxName>!\"\nRuleContextListDecl(rdecl) ::= \"<rdecl.escapedName>: [<rdecl.ctxName>] = [<rdecl.ctxName>]()\"\n\nContextTokenGetterDecl(t) ::= <<\n\t<accessLevelOpenOK(parser)>\n\tfunc <t.escapedName>() -> TerminalNode? {\n\t\treturn getToken(<parser.name>.Tokens.<t.escapedName>.rawValue, 0)\n\t}\n>>\nContextTokenListGetterDecl(t) ::= <<\n\t<accessLevelOpenOK(parser)>\n\tfunc <t.escapedName>() -> [TerminalNode] {\n\t\treturn getTokens(<parser.name>.Tokens.<t.escapedName>.rawValue)\n\t}\n>>\nContextTokenListIndexedGetterDecl(t) ::= <<\n\t<accessLevelOpenOK(parser)>\n\tfunc <t.escapedName>(_ i:Int) -> TerminalNode? {\n\t\treturn getToken(<parser.name>.Tokens.<t.escapedName>.rawValue, i)\n\t}\n>>\nContextRuleGetterDecl(r) ::= <<\n\t<accessLevelOpenOK(parser)>\n\tfunc <r.escapedName>() -> <r.ctxName>? {\n\t\treturn getRuleContext(<r.ctxName>.self, 0)\n\t}\n>>\nContextRuleListGetterDecl(r) ::= <<\n\t<accessLevelOpenOK(parser)>\n\tfunc <r.escapedName>() -> [<r.ctxName>] {\n\t\treturn getRuleContexts(<r.ctxName>.self)\n\t}\n>>\nContextRuleListIndexedGetterDecl(r)   ::= <<\n\t<accessLevelOpenOK(parser)>\n\tfunc <r.escapedName>(_ i: Int) -> <r.ctxName>? {\n\t\treturn getRuleContext(<r.ctxName>.self, i)\n\t}\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/** The rule context name is the rule followed by a suffix; e.g.,\n *\tr becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"_<tokenName>\"\nImplicitRuleLabel(ruleName)\t  ::= \"_<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = try _input.LT(1)\"\nCaptureNextTokenType(d) ::= \"<d.varName> = try _input.LA(1)\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures,\n           superClass={ParserRuleContext}) ::= <<\n\n<accessLevelNotOpen(parser)> class <struct.escapedName>: <if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif><if(interfaces)>, <interfaces; separator=\", \"><endif> {\n\t<attrs:{a | <accessLevelOpenOK(parser)> var <a>}; separator=\"\\n\">\n\t<getters:{g | <g>}; separator=\"\\n\">\n\t<! <if(ctorAttrs)> <accessLevelNotOpen(parser)> init(_ parent: ParserRuleContext,_ invokingState: Int) { super.init(parent, invokingState)  }<endif> !>\n\t<if(ctorAttrs)>\n\t<accessLevelNotOpen(parser)> convenience init(_ parent: ParserRuleContext?, _ invokingState: Int<ctorAttrs:{a | , _ <a>}>) {\n\t\tself.init(parent, invokingState)\n\t\t<struct.ctorAttrs:{a | self.<a.escapedName> = <a.escapedName>;}; separator=\"\\n\">\n\t}\n\t<endif>\n\n\toverride <accessLevelOpenOK(parser)>\n\tfunc getRuleIndex() -> Int {\n\t\treturn <parser.name>.RULE_<struct.derivedFromName>\n\t}\n<if(struct.provideCopyFrom && struct.attrs)> <! don't need copy unless we have subclasses !>\n\t<accessLevelOpenOK(parser)>\n\toverride func copyFrom(_ ctx_: ParserRuleContext) {\n\t\tsuper.copyFrom(ctx_)\n\t\tlet ctx = ctx_ as! <struct.escapedName>\n\t\t<struct.attrs:{a | self.<a.escapedName> = ctx.<a.escapedName>;}; separator=\"\\n\">\n\t}\n<endif>\n\t<dispatchMethods; separator=\"\\n\">\n\t<extensionMembers; separator=\"\\n\">\n}\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\n<accessLevelNotOpen(parser)> class <struct.escapedName>: <currentRule.name; format=\"cap\">Context {\n\t<attrs:{a | <accessLevelNotOpen(parser)> var <a>}; separator=\"\\n\">\n\t<getters:{g | <g>}; separator=\"\\n\">\n\n\t<accessLevelNotOpen(parser)>\n\tinit(_ ctx: <currentRule.name; format=\"cap\">Context) {\n\t\tsuper.init()\n\t\tcopyFrom(ctx)\n\t}\n\t<dispatchMethods; separator=\"\\n\">\n}\n>>\n\nListenerDispatchMethod(method) ::= <<\noverride <accessLevelOpenOK(parser)>\nfunc <if(method.isEnter)>enter<else>exit<endif>Rule(_ listener: ParseTreeListener) {\n\tif let listener = listener as? <parser.grammarName>Listener {\n\t\tlistener.<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">(self)\n\t}\n}\n>>\n\nVisitorDispatchMethod(method) ::= <<\noverride <accessLevelOpenOK(parser)>\nfunc accept\\<T>(_ visitor: ParseTreeVisitor\\<T>) -> T? {\n\tif let visitor = visitor as? <parser.grammarName>Visitor {\n\t    return visitor.visit<struct.derivedFromName; format=\"cap\">(self)\n\t}\n\telse if let visitor = visitor as? <parser.grammarName>BaseVisitor {\n\t    return visitor.visit<struct.derivedFromName; format=\"cap\">(self)\n\t}\n\telse {\n\t     return visitor.visitChildren(self)\n\t}\n}\n>>\n\nAttributeDecl(d) ::= \"<d.escapedName>: <SwiftTypeMap.(d.type)><if(d.initValue)> = <d.initValue><else>!<endif>\"\n\n/** If we don't know location of label def x, use this template (_localctx as! <x.ctx.name> */\nlabelref(x) ::= \"<if(!x.isLocal)>_localctx.castdown(<x.ctx.name>.self).<endif><x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr?    */\nctx(actionChunk) ::= \"_localctx.castdown(<actionChunk.ctx.name>.self)\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"precpred(_ctx, <opPrec>)\"\nrecRuleSetReturnAction(src,name)\t  ::= \"$<name>=$<src>.<name>\"\nrecRuleSetStopToken()                 ::= \"_ctx!.stop = try _input.LT(-1)\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\n_localctx = <ctxName>Context(_parentctx, _parentState);\n<if(label)>\n<if(isListLabel)>\n_localctx.<label>.append(_prevctx)\n<else>\n_localctx.<label> = _prevctx\n<endif>\n<endif>\ntry pushNewRecursionContext(_localctx, _startState, <parser.name>.RULE_<ruleName>)\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\n_localctx = <currentAltLabel; format=\"cap\">Context(  <ruleName; format=\"cap\">Context(_parentctx, _parentState))\n<if(label)>\n<if(isListLabel)>\n(_localctx as! <currentAltLabel; format=\"cap\">Context).<label>.append(_prevctx)\n<else>\n(_localctx as! <currentAltLabel; format=\"cap\">Context).<label> = _prevctx\n<endif>\n<endif>\ntry pushNewRecursionContext(_localctx, _startState, <parser.name>.RULE_<ruleName>)\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\n_localctx = <ctxName>Context(_localctx)\n_ctx = _localctx\n_prevctx = _localctx\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif _parseListeners != nil {\n   try triggerExitRuleEvent()\n}\n_prevctx = _localctx\n>>\n\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\n<if(lexerFile.genPackage)>\n<!package <lexerFile.genPackage>;!>\n<endif>\n<namedActions.header>\nimport Antlr4\n\n<lexer>\n>>\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass) ::= <<\n<accessLevelOpenOK(lexer)> class <lexer.name>: <superClass; null=\"Lexer\"> {\n\n\tinternal static var _decisionToDFA: [DFA] = {\n          var decisionToDFA = [DFA]()\n          let length = <lexer.name>._ATN.getNumberOfDecisions()\n          for i in 0..\\<length {\n            <! decisionToDFA[i] = DFA(<lexer.name>._ATN.getDecisionState(i)!, i);!>\n          \t    decisionToDFA.append(DFA(<lexer.name>._ATN.getDecisionState(i)!, i))\n          }\n           return decisionToDFA\n     }()\n\n\tinternal static let _sharedContextCache = PredictionContextCache()\n\n\t<accessLevelNotOpen(lexer)>\n\t<if(lexer.tokens)>\n\tstatic let <lexer.tokens:{k | <k>=<lexer.tokens.(k)>}; separator=\", \", wrap, anchor>\n\t<endif>\n\n\t<if(lexer.escapedChannels)>\n\t<accessLevelNotOpen(lexer)>\n\tstatic let <lexer.escapedChannels:{k | <k>=<lexer.escapedChannels.(k)>}; separator=\", \", wrap, anchor>\n\t<endif>\n\t<if(rest(lexer.escapedModeNames))>\n\t<accessLevelNotOpen(lexer)>\n\tstatic let <rest(lexer.escapedModeNames):{m| <m>=<i>}; separator=\", \", wrap, anchor>\n\t<endif>\n\t<accessLevelNotOpen(lexer)>\n\tstatic let channelNames: [String] = [\n\t\t\"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"<if (lexer.channelNames)>, <lexer.channelNames:{c| \"<c>\"}; separator=\", \", wrap, anchor><endif>\n\t]\n\n\t<accessLevelNotOpen(lexer)>\n\tstatic let modeNames: [String] = [\n\t\t<lexer.modes:{m| \"<m>\"}; separator=\", \", wrap, anchor>\n\t]\n\n\t<accessLevelNotOpen(lexer)>\n\tstatic let ruleNames: [String] = [\n\t\t<lexer.ruleNames:{r | \"<r>\"}; separator=\", \", wrap, anchor>\n\t]\n\n\t<vocabulary(lexer.literalNames, lexer.symbolicNames,\n                    accessLevelNotOpen(lexer))>\n\n\t<namedActions.members>\n\n\toverride <accessLevelOpenOK(lexer)>\n\tfunc getVocabulary() -> Vocabulary {\n\t\treturn <lexer.name>.VOCABULARY\n\t}\n\n\t<accessLevelNotOpen(lexer)>\n\trequired init(_ input: CharStream) {\n\t    RuntimeMetaData.checkVersion(\"<lexerFile.ANTLRVersion>\", RuntimeMetaData.VERSION)\n\t\tsuper.init(input)\n\t\t_interp = LexerATNSimulator(self, <lexer.name>._ATN, <lexer.name>._decisionToDFA, <lexer.name>._sharedContextCache)\n\t}\n\n\toverride <accessLevelOpenOK(lexer)>\n\tfunc getGrammarFileName() -> String { return \"<lexer.grammarFileName>\" }\n\n\toverride <accessLevelOpenOK(lexer)>\n\tfunc getRuleNames() -> [String] { return <lexer.name>.ruleNames }\n\n\toverride <accessLevelOpenOK(lexer)>\n\tfunc getSerializedATN() -> [Int] { return <lexer.name>._serializedATN }\n\n\toverride <accessLevelOpenOK(lexer)>\n\tfunc getChannelNames() -> [String] { return <lexer.name>.channelNames }\n\n\toverride <accessLevelOpenOK(lexer)>\n\tfunc getModeNames() -> [String] { return <lexer.name>.modeNames }\n\n\toverride <accessLevelOpenOK(lexer)>\n\tfunc getATN() -> ATN { return <lexer.name>._ATN }\n\n\t<dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n\t<atn>\n\n\t<accessLevelNotOpen(lexer)>\n\tstatic let _ATN: ATN = try! ATNDeserializer().deserialize(_serializedATN)\n}\n>>\n\nSerializedATN(model) ::= <<\nstatic let _serializedATN:[Int] = [\n\t<model.serialized: {s | <s>}; separator=\",\", wrap>\n]\n>>\n\n/** Using a type to init value map, try to init a type; if not in table\n *\tmust be an object, default value is \"null\".\n */\ninitValue(typeName) ::= <<\n <SwiftTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".swift\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/codegen/TypeScript/TypeScript.stg",
    "content": "// Copyright 2016-2022 The ANTLR Project. All rights reserved.\n// Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.\n\ntypescriptTypeInitMap ::= [\n\t\"bool\":\"false\",\n\t\"int\":\"0\",\n\t\"float\":\"0.0\",\n\t\"str\":\"\",\n\tdefault:\"{}\" // anything other than a primitive type is an object\n]\n\n// args must be <object-model-object>, <fields-resulting-in-STs>\n\nParserFile(file, parser, namedActions, contextSuperClass) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n// noinspection ES6UnusedImports,JSUnusedGlobalSymbols,JSUnusedLocalSymbols\n\nimport {\n\tATN,\n\tATNDeserializer, DecisionState, DFA, FailedPredicateException,\n\tRecognitionException, NoViableAltException, BailErrorStrategy,\n\tParser, ParserATNSimulator,\n\tRuleContext, ParserRuleContext, PredictionMode, PredictionContextCache,\n\tTerminalNode, RuleNode,\n\tToken, TokenStream,\n\tInterval, IntervalSet\n} from 'antlr4';\n<if(file.genListener)>\nimport <file.grammarName>Listener from \"./<file.grammarName>Listener.js\";\n<endif>\n<if(file.genVisitor)>\nimport <file.grammarName>Visitor from \"./<file.grammarName>Visitor.js\";\n<endif>\n\n// for running tests with parameters, TODO: discuss strategy for typed parameters in CI\n// @ts-ignore\n// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars\ntype int = number;\n\n<namedActions.header>\n<parser>\n>>\n\nListenerFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n\nimport {ParseTreeListener} from \"antlr4\";\n\n<header>\n\n<file.listenerNames:{lname | import { <lname; format=\"cap\">Context \\} from \"./<file.parserName>.js\";}; separator=\"\\n\">\n\n<namedActions.beforeListener>\n\n/**\n * This interface defines a complete listener for a parse tree produced by\n * `<file.parserName>`.\n */\nexport default class <file.grammarName>Listener extends ParseTreeListener {\n\t<file.listenerNames:{lname |\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Enter a parse tree produced by the `<lname>`\n * labeled alternative in `<file.parserName>.<file.listenerLabelRuleNames.(lname)>`.\n<else>\n * Enter a parse tree produced by `<file.parserName>.<lname>`.\n<endif>\n * @param ctx the parse tree\n */\nenter<lname; format=\"cap\">?: (ctx: <lname; format=\"cap\">Context) => void;\n/**\n<if(file.listenerLabelRuleNames.(lname))>\n * Exit a parse tree produced by the `<lname>`\n * labeled alternative in `<file.parserName>.<file.listenerLabelRuleNames.(lname)>`.\n<else>\n * Exit a parse tree produced by `<file.parserName>.<lname>`.\n<endif>\n * @param ctx the parse tree\n */\nexit<lname; format=\"cap\">?: (ctx: <lname; format=\"cap\">Context) => void;}; separator=\"\\n\">\n}\n\n<namedActions.afterListener>\n>>\n\nVisitorFile(file, header, namedActions) ::= <<\n<fileHeader(file.grammarFileName, file.ANTLRVersion)>\n\nimport {ParseTreeVisitor} from 'antlr4';\n\n<header>\n\n<file.visitorNames:{lname | import { <lname; format=\"cap\">Context \\} from \"./<file.parserName>.js\";}; separator=\"\\n\">\n\n<namedActions.beforeVisitor>\n\n/**\n * This interface defines a complete generic visitor for a parse tree produced\n * by `<file.parserName>`.\n *\n * @param \\<Result> The return type of the visit operation. Use `void` for\n * operations with no return type.\n */\nexport default class <file.grammarName>Visitor\\<Result> extends ParseTreeVisitor\\<Result> {\n\t<file.visitorNames:{lname |\n/**\n<if(file.visitorLabelRuleNames.(lname))>\n * Visit a parse tree produced by the `<lname>`\n * labeled alternative in `<file.parserName>.<file.visitorLabelRuleNames.(lname)>`.\n<else>\n * Visit a parse tree produced by `<file.parserName>.<lname>`.\n<endif>\n * @param ctx the parse tree\n * @return the visitor result\n */\nvisit<lname; format=\"cap\">?: (ctx: <lname; format=\"cap\">Context) => Result;}; separator=\"\\n\">\n}\n\n<namedActions.afterVisitor>\n>>\n\nfileHeader(grammarFileName, ANTLRVersion) ::= <<\n// Generated from <grammarFileName> by ANTLR <ANTLRVersion>\n>>\n\nParser(parser, funcs, atn, sempredFuncs, superClass, isLexer=false) ::= <<\n<Parser_(ctor=\"parser_ctor\", ...)>\n>>\n\nParser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<\n<if(superClass)>\nimport <superClass> from './<superClass>.js';\n<endif>\n\nexport default class <parser.name> extends <superClass; null=\"Parser\"> {\n\t<if(parser.tokens)>\n\t<parser.tokens:{k | public static readonly <k> = <parser.tokens.(k)>;}; separator=\"\\n\", wrap, anchor>\n\t<endif>\n\tpublic static override readonly EOF = Token.EOF;\n\t<parser.rules:{r | public static readonly RULE_<r.name> = <r.index>;}; separator=\"\\n\", wrap, anchor>\n\tpublic static readonly literalNames: (string | null)[] = [ <parser.literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n\tpublic static readonly symbolicNames: (string | null)[] = [ <parser.symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n\t// tslint:disable:no-trailing-whitespace\n\tpublic static readonly ruleNames: string[] = [\n\t\t<parser.ruleNames:{r | \"<r>\",}; separator=\" \", wrap, anchor>\n\t];\n\tpublic get grammarFileName(): string { return \"<parser.grammarFileName>\"; }\n\tpublic get literalNames(): (string | null)[] { return <parser.name>.literalNames; }\n\tpublic get symbolicNames(): (string | null)[] { return <parser.name>.symbolicNames; }\n\tpublic get ruleNames(): string[] { return <parser.name>.ruleNames; }\n\tpublic get serializedATN(): number[] { return <parser.name>._serializedATN; }\n\n\tprotected createFailedPredicateException(predicate?: string, message?: string): FailedPredicateException {\n\t\treturn new FailedPredicateException(this, predicate, message);\n\t}\n\n\t<namedActions.members>\n\t<parser:(ctor)()>\n\t<funcs; separator=\"\\n\">\n\n<if(sempredFuncs)>\n\tpublic sempred(localctx: RuleContext, ruleIndex: number, predIndex: number): boolean {\n\t\tswitch (ruleIndex) {\n\t\t<parser.sempredFuncs.values:{f|\ncase <f.ruleIndex>:\n\treturn this.<f.name>_sempred(localctx as <f.ctxType>, predIndex);}; separator=\"\\n\">\n\t\t}\n\t\treturn true;\n\t}\n\t<sempredFuncs.values; separator=\"\\n\">\n<endif>\n\n\t<atn>\n\n\tstatic DecisionsToDFA = <parser.name>._ATN.decisionToState.map( (ds: DecisionState, index: number) => new DFA(ds, index) );\n\n}\n\n<! The argument must be called currentRule because AltLabelStructDecl looks it up by name. !>\n<funcs:{currentRule |\n<if(currentRule.ruleCtx)>\n<currentRule.ruleCtx>\n<endif>\n<if(currentRule.altLabelCtxs)>\n<currentRule.altLabelCtxs:{l | <currentRule.altLabelCtxs.(l)>}; separator=\"\\n\">\n<endif>\n}; separator=\"\\n\\n\">\n>>\n\ndumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<\n<if(actionFuncs)>\n// @Override\npublic action(localctx: RuleContext, ruleIndex: number, actionIndex: number): void {\n\tswitch (ruleIndex) {\n\t<recog.actionFuncs.values:{f|\ncase <f.ruleIndex>:\n\tthis.<f.name>_action(<if(!recog.modes)>(<f.ctxType>)<endif>localctx, actionIndex);\n\tbreak;}; separator=\"\\n\">\n\t}\n}\n<actionFuncs.values; separator=\"\\n\">\n<endif>\n<if(sempredFuncs)>\n// @Override\npublic sempred(localctx: RuleContext, ruleIndex: number, predIndex: number): boolean {\n\tswitch (ruleIndex) {\n\t<recog.sempredFuncs.values:{f|\ncase <f.ruleIndex>:\n\treturn this.<f.name>_sempred(localctx<if(!recog.modes)> as <f.ctxType><endif>, predIndex);}; separator=\"\\n\">\n\t}\n\treturn true;\n}\n<sempredFuncs.values; separator=\"\\n\">\n<endif>\n>>\n\nparser_ctor(p) ::= <<\nconstructor(input: TokenStream) {\n\tsuper(input);\n\tthis._interp = new ParserATNSimulator(this, <p.name>._ATN, <p.name>.DecisionsToDFA, new PredictionContextCache());\n}\n>>\n\n/* This generates a private method since the actionIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleActionFunction(r, actions) ::= <<\nprivate <r.name>_action(localctx: <r.ctxType>, actionIndex: number): void {\n\tswitch (actionIndex) {\n\t<actions:{index|\ncase <index>:\n\t<actions.(index)>\n\tbreak;}; separator=\"\\n\">\n\t}\n}\n>>\n\n/* This generates a private method since the predIndex is generated, making an\n * overriding implementation impossible to maintain.\n */\nRuleSempredFunction(r, actions) ::= <<\nprivate <r.name>_sempred(localctx: <r.ctxType>, predIndex: number): boolean {\n\tswitch (predIndex) {\n\t<actions:{index|\ncase <index>:\n\treturn <actions.(index)>;}; separator=\"\\n\">\n\t}\n\treturn true;\n}\n>>\n\nRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<\n// @RuleVersion(<namedActions.version; null=\"0\">)\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public <endif><currentRule.escapedName>(<currentRule.args:{a | <a.escapedName>: <a.type>}; separator=\", \">): <currentRule.ctxType> {\n\tlet localctx: <currentRule.ctxType> = new <currentRule.ctxType>(this, this._ctx, this.state<currentRule.args:{a | , <a.escapedName>}>);\n\tthis.enterRule(localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.name>);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tlet _alt: number;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\t<if(exceptions)>\n\t<exceptions; separator=\"\\n\">\n\t<else>\n\tcatch (re) {\n\t\tif (re instanceof RecognitionException) {\n\t\t\tlocalctx.exception = re;\n\t\t\tthis._errHandler.reportError(this, re);\n\t\t\tthis._errHandler.recover(this, re);\n\t\t} else {\n\t\t\tthrow re;\n\t\t}\n\t}\n\t<endif>\n\tfinally {\n\t\t<finallyAction>\n\t\tthis.exitRule();\n\t}\n\treturn localctx;\n}\n>>\n\nLeftFactoredRuleFunction(currentRule,args,code,locals,namedActions,finallyAction,postamble) ::=\n<<\n\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>private <endif><currentRule.ctxType> <currentRule.escapedName>(<args; separator=\",\">) {\n\tlet localctx: <currentRule.ctxType> = new <currentRule.ctxType>(this, this._ctx, this.state<currentRule.args:{a | , <a.escapedName>}>);\n\tthis.enterLeftFactoredRule(localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.variantOf>);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tlet _alt: number;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t} catch (re) {\n\t\tif (re instanceof RecognitionException) {\n\t\t\tlocalctx.exception = re;\n\t\t\tthis._errHandler.reportError(this, re);\n\t\t\tthis._errHandler.recover(this, re);\n\t\t} else {\n\t\t\tthrow re;\n\t\t}\n\t}\n\tfinally {\n\t\t<finallyAction>\n\t\tthis.exitRule();\n\t}\n\treturn localctx;\n}\n>>\n\n// This behaves similar to RuleFunction (enterRule is called, and no adjustments\n// are made to the parse tree), but since it's still a variant no context class\n// needs to be generated.\nLeftUnfactoredRuleFunction(currentRule,args,code,locals,namedActions,finallyAction,postamble) ::=\n<<\n\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>private <endif><currentRule.ctxType> <currentRule.name>(<args; separator=\",\">) {\n\tlet localctx: <currentRule.ctxType> = new <currentRule.ctxType>(this, this._ctx, this.state<currentRule.args:{a | , <a.name>}>);\n\tthis.enterRule(localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.variantOf>);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tlet _alt: number;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\tcatch (re) {\n\t\tif (re instanceof RecognitionException) {\n\t\t\tlocalctx.exception = re;\n\t\t\tthis._errHandler.reportError(this, re);\n\t\t\tthis._errHandler.recover(this, re);\n\t\t} else {\n\t\t\tthrow re;\n\t\t}\n\t}\n\tfinally {\n\t\t<finallyAction>\n\t\tthis.exitRule();\n\t}\n\treturn localctx;\n}\n>>\n\nLeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,\n\tnamedActions,finallyAction,postamble) ::=\n<<\n\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public <endif><currentRule.escapedName>(<args; separator=\", \">): <currentRule.ctxType>;\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public <endif><currentRule.escapedName>(<args; separator=\", \"><if(args)>, <endif>_p: number): <currentRule.ctxType>;\n// @RuleVersion(<namedActions.version; null=\"0\">)\n<if(currentRule.modifiers)><currentRule.modifiers:{f | <f> }><else>public <endif><currentRule.escapedName>(<args; separator=\", \"><if(args)>, <endif>_p?: number): <currentRule.ctxType> {\n\tif (_p === undefined) {\n\t\t_p = 0;\n\t}\n\n\tlet _parentctx: ParserRuleContext = this._ctx;\n\tlet _parentState: number = this.state;\n\tlet localctx: <currentRule.ctxType> = new <currentRule.ctxType>(this, this._ctx, _parentState<currentRule.args:{a | , <a.escapedName>}>);\n\tlet _prevctx: <currentRule.ctxType> = localctx;\n\tlet _startState: number = <currentRule.startState>;\n\tthis.enterRecursionRule(localctx, <currentRule.startState>, <parser.name>.RULE_<currentRule.name>, _p);\n\t<namedActions.init>\n\t<locals; separator=\"\\n\">\n\ttry {\n<if(currentRule.hasLookaheadBlock)>\n\t\tlet _alt: number;\n<endif>\n\t\t<code>\n\t\t<postamble; separator=\"\\n\">\n\t\t<namedActions.after>\n\t}\n\tcatch (re) {\n\t\tif (re instanceof RecognitionException) {\n\t\t\tlocalctx.exception = re;\n\t\t\tthis._errHandler.reportError(this, re);\n\t\t\tthis._errHandler.recover(this, re);\n\t\t} else {\n\t\t\tthrow re;\n\t\t}\n\t}\n\tfinally {\n\t\t<finallyAction>\n\t\tthis.unrollRecursionContexts(_parentctx);\n\t}\n\treturn localctx;\n}\n>>\n\nCodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<\n<if(currentOuterMostAltCodeBlock.altLabel)>localctx = new <currentOuterMostAltCodeBlock.altLabel; format=\"cap\">Context(this, localctx);<endif>\nthis.enterOuterAlt(localctx, <currentOuterMostAltCodeBlock.alt.altNum>);\n<CodeBlockForAlt(currentAltCodeBlock=currentOuterMostAltCodeBlock, ...)>\n>>\n\nCodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<\n<if(!(locals || preamble || ops))>\n// tslint:disable-next-line:no-empty\n<endif>\n{\n<locals; separator=\"\\n\">\n<preamble; separator=\"\\n\">\n<ops; separator=\"\\n\">\n}\n>>\n\nLL1AltBlock(choice, preamble, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = this._input.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch (this._input.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\">\ndefault:\n\t<error>\n}\n>>\n\nLL1OptionalBlock(choice, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\nswitch (this._input.LA(1)) {\n<choice.altLook,alts:{look,alt| <cases(tokens=look)>\n\t<alt>\n\tbreak;}; separator=\"\\n\">\ndefault:\n\tbreak;\n}\n>>\n\nLL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<preamble; separator=\"\\n\">\nif (<expr>) {\n\t<alts; separator=\"\\n\">\n}\n<!else if (!(<followExpr>)) <error>!>\n>>\n\nLL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<preamble; separator=\"\\n\">\nwhile (<loopExpr>) {\n\t<alts; separator=\"\\n\">\n\tthis.state = <choice.loopBackStateNumber>;\n\tthis._errHandler.sync(this);\n\t<iteration>\n}\n>>\n\nLL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<\nthis.state = <choice.blockStartStateNumber>;<! alt block decision !>\nthis._errHandler.sync(this);\n<preamble; separator=\"\\n\">\ndo {\n\t<alts; separator=\"\\n\">\n\tthis.state = <choice.stateNumber>;<! loopback/exit decision !>\n\tthis._errHandler.sync(this);\n\t<iteration>\n} while (<loopExpr>);\n>>\n\n// LL(*) stuff\n\nAltBlock(choice, preamble, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n<if(choice.label)><labelref(choice.label)> = this._input.LT(1);<endif>\n<preamble; separator=\"\\n\">\nswitch ( this._interp.adaptivePredict(this._input, <choice.decision>, this._ctx) ) {\n<alts:{alt |\ncase <i>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n}\n>>\n\nOptionalBlock(choice, alts, error) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\nswitch ( this._interp.adaptivePredict(this._input, <choice.decision>, this._ctx) ) {\n<alts:{alt |\ncase <i><if(!choice.ast.greedy)> + 1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n}\n>>\n\nStarBlock(choice, alts, sync, iteration) ::= <<\nthis.state = <choice.stateNumber>;\nthis._errHandler.sync(this);\n_alt = this._interp.adaptivePredict(this._input, <choice.decision>, this._ctx);\nwhile (_alt !== <choice.exitAlt> && _alt !== ATN.INVALID_ALT_NUMBER) {\n\tif (_alt === 1<if(!choice.ast.greedy)> + 1<endif>) {\n\t\t<iteration>\n\t\t<alts><! should only be one !>\n\t}\n\tthis.state = <choice.loopBackStateNumber>;\n\tthis._errHandler.sync(this);\n\t_alt = this._interp.adaptivePredict(this._input, <choice.decision>, this._ctx);\n}\n>>\n\nPlusBlock(choice, alts, error) ::= <<\nthis.state = <choice.blockStartStateNumber>;<! alt block decision !>\nthis._errHandler.sync(this);\n_alt = 1<if(!choice.ast.greedy)> + 1<endif>;\ndo {\n\tswitch (_alt) {\n\t<alts:{alt|\ncase <i><if(!choice.ast.greedy)> + 1<endif>:\n\t<alt>\n\tbreak;}; separator=\"\\n\">\n\tdefault:\n\t\t<error>\n\t}\n\tthis.state = <choice.loopBackStateNumber>;<! loopback/exit decision !>\n\tthis._errHandler.sync(this);\n\t_alt = this._interp.adaptivePredict(this._input, <choice.decision>, this._ctx);\n} while (_alt !== <choice.exitAlt> && _alt !== ATN.INVALID_ALT_NUMBER);\n>>\n\nSync(s) ::= \"this.sync(<s.expecting.name>);\"\n\nThrowNoViableAlt(t) ::= \"throw new NoViableAltException(this);\"\n\nTestSetInline(s) ::= <<\n<s.bitsets:{bits | <if(rest(rest(bits.tokens)))><bitsetBitfieldComparison(s, bits)><else><bitsetInlineComparison(s, bits)><endif>}; separator=\" || \">\n>>\n\n// Javascript language spec - shift operators are 32 bits long max\ntestShiftInRange(shiftAmount) ::= <<\n((<shiftAmount>) & ~0x1F) === 0\n>>\n\n// produces smaller bytecode only when bits.ttypes contains more than two items\nbitsetBitfieldComparison(s, bits) ::= <%\n(<testShiftInRange({<offsetShiftVar(s.varName, bits.shift)>})> && ((1 \\<\\< <offsetShiftVar(s.varName, bits.shift)>) & <bits.calculated>) !== 0)\n%>\n\nisZero ::= [\n\"0\":true,\ndefault:false\n]\n\noffsetShiftVar(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<shiftAmount> - <offset>)<else><shiftAmount><endif>\n%>\n\noffsetShiftType(shiftAmount, offset) ::= <%\n<if(!isZero.(offset))>(<parser.name>.<shiftAmount> - <offset>)<else><parser.name>.<shiftAmount><endif>\n%>\n\n\nbitsetInlineComparison(s, bits) ::= <%\n<bits.tokens:{t | <s.varName>===<t.type>}; separator=\" || \">\n%>\n\ncases(tokens) ::= <<\n<tokens:{t | case <t.type>:}; separator=\"\\n\">\n>>\n\nInvokeRule(r, argExprsChunks) ::= <<\nthis.state = <r.stateNumber>;\n<if(r.labels)><r.labels:{l | <labelref(l)> = }><endif>this.<r.escapedName>(<if(r.ast.options.p)><r.ast.options.p><if(argExprsChunks)>,<endif><endif><argExprsChunks>);\n>>\n\nMatchToken(m) ::= <<\nthis.state = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>this.match(<parser.name>.<m.name>);\n>>\n\nMatchSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, false)>\"\n\nMatchNotSet(m, expr, capture) ::= \"<CommonSetStuff(m, expr, capture, true)>\"\n\nCommonSetStuff(m, expr, capture, invert) ::= <<\nthis.state = <m.stateNumber>;\n<if(m.labels)><m.labels:{l | <labelref(l)> = }>this._input.LT(1);<endif>\n<capture>\n<if(invert)>if(<m.varName>\\<=0 || <expr>)<else>if(!(<expr>))<endif> {\n    <if(m.labels)><m.labels:{l | <labelref(l)> = }><endif>this._errHandler.recoverInline(this);\n}\nelse {\n\tthis._errHandler.reportMatch(this);\n    this.consume();\n}\n>>\n\nWildcard(w) ::= <<\nthis.state = <w.stateNumber>;\n<if(w.labels)><w.labels:{l | <labelref(l)> = }><endif>this.matchWildcard();\n>>\n\n// ACTION STUFF\n\nAction(a, foo, chunks) ::= \"<chunks>\"\n\nArgAction(a, chunks) ::= \"<chunks>\"\n\nSemPred(p, chunks, failChunks) ::= <<\nthis.state = <p.stateNumber>;\nif (!(<chunks>)) {\n\tthrow this.createFailedPredicateException(<p.predicate><if(failChunks)>, <failChunks><elseif(p.msg)>, <p.msg><endif>);\n}\n>>\n\nExceptionClause(e, catchArg, catchAction) ::= <<\ncatch (<catchArg>) {\n\t<catchAction>\n}\n>>\n\n// lexer actions are not associated with model objects\n\nLexerSkipCommand()  ::= \"this.skip();\"\nLexerMoreCommand()  ::= \"this.more();\"\nLexerPopModeCommand() ::= \"this.popMode();\"\nLexerTypeCommand(arg, grammar)      ::= \"this._type = <arg>;\"\nLexerChannelCommand(arg, grammar)   ::= \"this._channel = <arg>;\"\nLexerModeCommand(arg, grammar)      ::= \"this._mode = <arg>;\"\nLexerPushModeCommand(arg, grammar)  ::= \"this.pushMode(<arg>);\"\n\nActionText(t) ::= \"<t.text>\"\nActionTemplate(t) ::= \"<t.st>\"\nArgRef(a) ::= \"localctx.<a.escapedName>\"\nLocalRef(a) ::= \"localctx.<a.escapedName>\"\nRetValueRef(a) ::= \"localctx.<a.escapedName>\"\nQRetValueRef(a) ::= \"<ctx(a)>._<a.dict>.<a.escapedName>\"\n/** How to translate $tokenLabel */\nTokenRef(t) ::= \"<ctx(t)>._<t.escapedName>\"\nLabelRef(t) ::= \"<ctx(t)>._<t.escapedName>\"\nListLabelRef(t) ::= \"<ctx(t)>._<ListLabelName(t.escapedName)>\"\nSetAttr(s,rhsChunks) ::= \"<ctx(s)>.<s.escapedName> = <rhsChunks>;\"\n\nTokenLabelType() ::= \"<file.TokenLabelType; null={Token}>\"\nInputSymbolType() ::= \"<file.InputSymbolType; null={Token}>\"\n\nTokenPropertyRef_text(t) ::= \"(<ctx(t)>._<t.label> != null ? <ctx(t)>._<t.label>.text : undefined)\"\nTokenPropertyRef_type(t) ::= \"(<ctx(t)>._<t.label> != null ? <ctx(t)>._<t.label>.type : 0)\"\nTokenPropertyRef_line(t) ::= \"(<ctx(t)>._<t.label> != null ? <ctx(t)>._<t.label>.line : 0)\"\nTokenPropertyRef_pos(t) ::= \"(<ctx(t)>._<t.label> != null ? <ctx(t)>._<t.label>.charPositionInLine : 0)\"\nTokenPropertyRef_channel(t) ::= \"(<ctx(t)>._<t.label> != null ? <ctx(t)>._<t.label>.channel : 0)\"\nTokenPropertyRef_index(t) ::= \"(<ctx(t)>._<t.label> != null ? <ctx(t)>._<t.label>.tokenIndex : 0)\"\nTokenPropertyRef_int(t) ::= \"(<ctx(t)>._<t.label> != null ? Number(<ctx(t)>._<t.label>.text) : 0)\"\n\nRulePropertyRef_start(r) ::= \"(<ctx(r)>._<r.label> != null ? (<ctx(r)>._<r.label>.start) : undefined)\"\nRulePropertyRef_stop(r)\t ::= \"(<ctx(r)>._<r.label> != null ? (<ctx(r)>._<r.label>.stop) : undefined)\"\nRulePropertyRef_text(r)\t ::= \"(<ctx(r)>._<r.label> != null ? this._input.getText(new Interval(<ctx(r)>._<r.label>.start, <ctx(r)>._<r.label>.stop)) : undefined)\"\nRulePropertyRef_ctx(r)\t ::= \"<ctx(r)>._<r.label>\"\nRulePropertyRef_parser(r)\t ::= \"this\"\n\nThisRulePropertyRef_start(r) ::= \"localctx.start\"\nThisRulePropertyRef_stop(r)\t ::= \"localctx.stop\"\nThisRulePropertyRef_text(r)\t ::= \"this._input.getText(new Interval(localctx.start, this._input.LT(-1)))\"\nThisRulePropertyRef_ctx(r)\t ::= \"localctx\"\nThisRulePropertyRef_parser(r)\t ::= \"this\"\n\nNonLocalAttrRef(s)\t\t ::= \"(this.getInvokingContext(<s.ruleIndex>) as <s.ruleName; format=\\\"cap\\\">Context).<s.escapedName>\"\nSetNonLocalAttr(s, rhsChunks)\t  ::=\n\t\"(this.getInvokingContext(<s.ruleIndex>) as <s.escapedName>Context).<s.escapedName> = <rhsChunks>;\"\n\nAddToLabelList(a) ::= \"<ctx(a.label)>._<a.listName>.push(<labelref(a.label)>);\"\n\nTokenDecl(t) ::= \"_<t.escapedName>!: <TokenLabelType()>\"\nTokenTypeDecl(t) ::= \"let <t.escapedName>: number;\"\nTokenListDecl(t) ::= \"_<t.escapedName>: Token[] = []\"\nRuleContextDecl(r) ::= \"_<r.escapedName>!: <r.ctxName>\"\nRuleContextListDecl(rdecl) ::= \"_<rdecl.escapedName>: <rdecl.ctxName>[] = []\"\n\nContextTokenGetterDecl(t)      ::= <<\npublic <t.escapedName>(): TerminalNode {\n\treturn this.getToken(<parser.name>.<t.name>, 0);\n}\n>>\nContextTokenListGetterDecl(t)  ::= <<\npublic <t.escapedName>_list(): TerminalNode[] {\n    \treturn this.getTokens(<parser.name>.<t.name>);\n}\n>>\nContextTokenListIndexedGetterDecl(t)  ::= <<\npublic <t.escapedName>(i: number): TerminalNode {\n\treturn this.getToken(<parser.name>.<t.name>, i);\n}\n>>\nContextRuleGetterDecl(r)       ::= <<\npublic <r.escapedName>(): <r.ctxName> {\n\treturn this.getTypedRuleContext(<r.ctxName>, 0) as <r.ctxName>;\n}\n>>\nContextRuleListGetterDecl(r)   ::= <<\npublic <r.escapedName>_list(): <r.ctxName>[] {\n\treturn this.getTypedRuleContexts(<r.ctxName>) as <r.ctxName>[];\n}\n>>\nContextRuleListIndexedGetterDecl(r)   ::= <<\npublic <r.escapedName>(i: number): <r.ctxName> {\n\treturn this.getTypedRuleContext(<r.ctxName>, i) as <r.ctxName>;\n}\n>>\n\nLexerRuleContext() ::= \"RuleContext\"\n\n/** The rule context name is the rule followed by a suffix; e.g.,\n *\tr becomes rContext.\n */\nRuleContextNameSuffix() ::= \"Context\"\n\nImplicitTokenLabel(tokenName) ::= \"<tokenName>\"\nImplicitRuleLabel(ruleName)\t  ::= \"<ruleName>\"\nImplicitSetLabel(id)\t\t  ::= \"_tset<id>\"\nListLabelName(label)\t\t  ::= \"<label>\"\n\nCaptureNextToken(d) ::= \"<d.varName> = this._input.LT(1);\"\nCaptureNextTokenType(d) ::= \"<d.varName> = this._input.LA(1);\"\n\nStructDecl(struct,ctorAttrs,attrs,getters,dispatchMethods,interfaces,extensionMembers,signatures)\n\t::= <<\nexport class <struct.escapedName> extends <if(contextSuperClass)><contextSuperClass><else>ParserRuleContext<endif><if(interfaces)> implements <interfaces; separator=\", \"><endif> {\n\t<attrs:{a | public <a>;}; separator=\"\\n\">\n\t<if(struct.ctorAttrs)>\n\tconstructor(parser: <parser.name>, parent: ParserRuleContext, invokingState: number<struct.ctorAttrs:{a |, <a.escapedName>: <a.type>}>) {\n\t\tsuper(parent, invokingState);\n    \tthis.parser = parser;\n        <struct.ctorAttrs:{a | this.<a.escapedName> = <a.escapedName>;}; separator=\"\\n\">\n\t}\n\t<else>\n\tconstructor(parser?: <parser.name>, parent?: ParserRuleContext, invokingState?: number) {\n\t\tsuper(parent, invokingState);\n    \tthis.parser = parser;\n\t}\n\t<endif>\n\t<getters:{g | <g>}; separator=\"\\n\">\n    public get ruleIndex(): number {\n    \treturn <parser.name>.RULE_<struct.derivedFromName>;\n\t}\n<if(struct.provideCopyFrom)><! don't need copy unless we have subclasses !>\n\tpublic override copyFrom(ctx: <struct.name>): void {\n\t\tsuper.copyFrom(ctx);\n\t\t<struct.attrs:{a | this.<a.escapedName> = ctx.<a.escapedName>;}; separator=\"\\n\">\n\t}\n<endif>\n\t<dispatchMethods; separator=\"\\n\">\n\t<extensionMembers; separator=\"\\n\">\n}\n>>\n\nAltLabelStructDecl(struct,attrs,getters,dispatchMethods) ::= <<\nexport class <struct.escapedName> extends <struct.parentRule; format=\"cap\">Context {\n\t<attrs:{a | public <a>;}; separator=\"\\n\">\n\tconstructor(parser: <parser.name>, ctx: <currentRule.currentRule.name; format=\"cap\">Context) {\n\t\tsuper(parser, ctx.parentCtx, ctx.invokingState<currentRule.ruleCtx.ctorAttrs:{a | , ctx.<a.d.name>}>);\n\t\tsuper.copyFrom(ctx);\n\t}\n\t<getters:{g | <g>}; separator=\"\\n\">\n\t<dispatchMethods; separator=\"\\n\">\n}\n>>\n\nListenerDispatchMethod(method) ::= <<\npublic <if(method.isEnter)>enter<else>exit<endif>Rule(listener: <parser.grammarName>Listener): void {\n    if(listener.<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">) {\n \t\tlistener.<if(method.isEnter)>enter<else>exit<endif><struct.derivedFromName; format=\"cap\">(this);\n\t}\n}\n>>\n\nVisitorDispatchMethod(method) ::= <<\n// @Override\npublic accept\\<Result>(visitor: <parser.grammarName>Visitor\\<Result>): Result {\n\tif (visitor.visit<struct.derivedFromName; format=\"cap\">) {\n\t\treturn visitor.visit<struct.derivedFromName; format=\"cap\">(this);\n\t} else {\n\t\treturn visitor.visitChildren(this);\n\t}\n}\n>>\n\nAttributeDecl(d) ::= \"<d.escapedName>: <d.type><if(d.initValue)> = <d.initValue><endif>\"\n\n/** If we don't know location of label def x, use this template */\nlabelref(x) ::= \"<if(!x.isLocal)><typedContext(x.ctx)>.<endif>_<x.escapedName>\"\n\n/** For any action chunk, what is correctly-typed context struct ptr? */\nctx(actionChunk) ::= \"<typedContext(actionChunk.ctx)>\"\n\n// only casts localctx to the type when the cast isn't redundant (i.e. to a sub-context for a labeled alt)\ntypedContext(ctx) ::= \"<if(ctx.provideCopyFrom)>(localctx as <ctx.name>)<else>localctx<endif>\"\n\n// used for left-recursive rules\nrecRuleAltPredicate(ruleName,opPrec)  ::= \"this.precpred(this._ctx, <opPrec>)\"\nrecRuleSetReturnAction(src,name)\t  ::= \"$<name>=$<src>.<name>;\"\nrecRuleSetStopToken()                 ::= \"this._ctx.stop = this._input.LT(-1);\"\n\nrecRuleAltStartAction(ruleName, ctxName, label, isListLabel) ::= <<\nlocalctx = new <ctxName>Context(this, _parentctx, _parentState);\n<if(label)>\n<if(isListLabel)>\nlocalctx._<label>.push(_prevctx);\n<else>\nlocalctx._<label> = _prevctx;\n<endif>\n<endif>\nthis.pushNewRecursionContext(localctx, _startState, <parser.name>.RULE_<ruleName>);\n>>\n\nrecRuleLabeledAltStartAction(ruleName, currentAltLabel, label, isListLabel) ::= <<\nlocalctx = new <currentAltLabel; format=\"cap\">Context(this, new <ruleName; format=\"cap\">Context(this, _parentctx, _parentState));\n<if(label)>\n<if(isListLabel)>\n(localctx as <currentAltLabel; format=\"cap\">Context)._<label>.push(_prevctx);\n<else>\n(localctx as <currentAltLabel; format=\"cap\">Context)._<label> = _prevctx;\n<endif>\n<endif>\nthis.pushNewRecursionContext(localctx, _startState, <parser.name>.RULE_<ruleName>);\n>>\n\nrecRuleReplaceContext(ctxName) ::= <<\nlocalctx = new <ctxName>Context(this, localctx);\nthis._ctx = localctx;\n_prevctx = localctx;\n>>\n\nrecRuleSetPrevCtx() ::= <<\nif (this._parseListeners != null) {\n\tthis.triggerExitRuleEvent();\n}\n_prevctx = localctx;\n>>\n\n\nLexerFile(lexerFile, lexer, namedActions) ::= <<\n<fileHeader(lexerFile.grammarFileName, lexerFile.ANTLRVersion)>\n// noinspection ES6UnusedImports,JSUnusedGlobalSymbols,JSUnusedLocalSymbols\nimport {\n\tATN,\n\tATNDeserializer,\n\tCharStream,\n\tDecisionState, DFA,\n\tLexer,\n\tLexerATNSimulator,\n\tRuleContext,\n\tPredictionContextCache,\n\tToken\n} from \"antlr4\";\n<namedActions.header>\n<lexer>\n>>\n\nLexer(lexer, atn, actionFuncs, sempredFuncs, superClass, isLexer=true) ::= <<\n<if(superClass)>\nimport <superClass> from './<superClass>.js';\n\n<endif>\nexport default class <lexer.name> extends <superClass; null=\"Lexer\"> {\n\t<lexer.tokens:{k | public static readonly <k> = <lexer.tokens.(k)>;}; separator=\"\\n\">\n\tpublic static readonly EOF = Token.EOF;\n\t<if(lexer.escapedChannels)>\n\t<lexer.escapedChannels:{c| public static readonly <c> = <lexer.escapedChannels.(c)>;}; separator=\"\\n\">\n\t<endif>\n\t<rest(lexer.modes):{m | public static readonly <m> = <i>;}; separator=\"\\n\">\n\n\tpublic static readonly channelNames: string[] = [ \"DEFAULT_TOKEN_CHANNEL\", \"HIDDEN\"<if (lexer.channelNames)>, <lexer.channelNames:{c| \"<c>\"}; separator=\", \", wrap, anchor><endif> ];\n\tpublic static readonly literalNames: (string | null)[] = [ <lexer.literalNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n\tpublic static readonly symbolicNames: (string | null)[] = [ <lexer.symbolicNames:{t | <t>}; null=\"null\", separator=\", \", wrap, anchor> ];\n\tpublic static readonly modeNames: string[] = [ <lexer.modes:{m| \"<m>\",}; separator=\" \", wrap, anchor> ];\n\n\tpublic static readonly ruleNames: string[] = [\n\t\t<lexer.ruleNames:{r | \"<r>\",}; separator=\" \", wrap, anchor>\n\t];\n\n\t<namedActions.members>\n\n\tconstructor(input: CharStream) {\n\t\tsuper(input);\n\t\tthis._interp = new LexerATNSimulator(this, <lexer.name>._ATN, <lexer.name>.DecisionsToDFA, new PredictionContextCache());\n\t}\n\n\tpublic get grammarFileName(): string { return \"<lexer.grammarFileName>\"; }\n\n\tpublic get literalNames(): (string | null)[] { return <lexer.name>.literalNames; }\n\tpublic get symbolicNames(): (string | null)[] { return <lexer.name>.symbolicNames; }\n\tpublic get ruleNames(): string[] { return <lexer.name>.ruleNames; }\n\n\tpublic get serializedATN(): number[] { return <lexer.name>._serializedATN; }\n\n\tpublic get channelNames(): string[] { return <lexer.name>.channelNames; }\n\n\tpublic get modeNames(): string[] { return <lexer.name>.modeNames; }\n\n\t<dumpActions(lexer, \"\", actionFuncs, sempredFuncs)>\n\t<atn>\n\n\tstatic DecisionsToDFA = <lexer.name>._ATN.decisionToState.map( (ds: DecisionState, index: number) => new DFA(ds, index) );\n}\n>>\n\nSerializedATN(model, className={<if(isLexer)><lexer.name><else><parser.name><endif>}) ::= <<\npublic static readonly _serializedATN: number[] = [<model.serialized: {s | <s>}; separator=\",\", wrap>];\n\nprivate static __ATN: ATN;\npublic static get _ATN(): ATN {\n\tif (!<className>.__ATN) {\n\t\t<className>.__ATN = new ATNDeserializer().deserialize(<className>._serializedATN);\n\t}\n\n\treturn <className>.__ATN;\n}\n\n>>\n\n/** Using a type to init value map, try to init a type; if not in table\n *\tmust be an object, default value is \"null\".\n */\ninitValue(typeName) ::= <<\n<typescriptTypeInitMap.(typeName)>\n>>\n\ncodeFileExtension() ::= \".ts\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/depend.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** templates used to generate make-compatible dependencies */\n\n/** Generate \"f : x, y, z\" dependencies for input\n *  dependencies and generated files. in and out\n *  are File objects.  For example, you can say\n *  <f.canonicalPath>\n */\ndependencies(grammarFileName,in,out) ::= <<\n<if(in)><grammarFileName>: <in; separator=\", \"><endif>\n<out:{f | <f> : <grammarFileName>}; separator=\"\\n\">\n>>\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/dot/graphs.stg",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\natn(startState, states, edges, rankdir, decisionRanks, useBox) ::= <<\ndigraph ATN {\nrankdir=LR;\n<decisionRanks; separator=\"\\n\">\n<states; separator=\"\\n\">\n<edges; separator=\"\\n\">\n}\n>>\n\ndfa(name, startState, states, edges, rankdir, decisionRanks, useBox) ::= <<\ndigraph <name>  {\n<if(rankdir)>rankdir=<rankdir>;<endif>\n<decisionRanks; separator=\"\\n\">\n<states; separator=\"\\n\">\n<edges; separator=\"\\n\">\n}\n>>\n\ndecision-rank(states) ::= <<\n{rank=same; rankdir=TB; <states:{s | s<s>}; separator=\"; \">}\n>>\n\nedge(src,target,label,arrowhead,transitionIndex) ::= <<\n<src><if(transitionIndex)>:p<transitionIndex><endif> -> <target> [fontsize=11, fontname=\"Courier\", arrowsize=.7, label = \"<label>\"<if(arrowhead)>, arrowhead = <arrowhead><endif>];\n>>\n\naction-edge(src,target,label,arrowhead,transitionIndex) ::= <<\n<src><if(transitionIndex)>:p<transitionIndex><endif> -> <target> [fontsize=11, fontname=\"Courier\", arrowsize=.7, label = \"<label>\"<if(arrowhead)>, arrowhead = <arrowhead><endif>];\n>>\n\nepsilon-edge(src,label,target,arrowhead,transitionIndex,loopback=false) ::= <<\n<src><if(transitionIndex)>:p<transitionIndex><endif> -> <target> [fontname=\"Times-Italic\", label=\"&epsilon;\"<if(loopback)>, style=\"dashed\"<endif>];\n>>\n\nstate(state, label, name, transitions) ::= <%\n<name>[fontsize=11,\n    label=\"\n        <! rest(transition) tests for decision states: these nodes have a non-empty set of transitions after the first one. !>\n        <if(rest(transitions))>\n            {\n            <! Label on the left side of the record node. !>\n            <label>\n            |\n            <! Named ports in order on right side of record node, no display text. !>\n            {<transitions:{t|\\<p<i0>>}; separator=\"|\">}}\n        <else>\n            <label>\n        <endif>\n        \"\n    <if(rest(transitions))>\n        , shape=record, fixedsize=false\n    <else>\n        , shape=circle, fixedsize=true, width=.55\n    <endif>\n    , peripheries=1];\n%>\n\nstopstate(name,label,actionIndex,useBox) ::= <<\n<name>[fontsize=11, label=\"<label><if(actionIndex)>,\\naction:<actionIndex><endif>\", <if(useBox)>shape=polygon,sides=4,peripheries=2,fixedsize=false<else>shape=doublecircle, fixedsize=true, width=.6<endif>];\n>>\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/messages/formats/antlr.stg",
    "content": "/*\n [The \"BSD licence\"]\n Copyright (c) 2006 Kay Roepke\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\n This file contains the actual layout of the messages emitted by ANTLR.\n This file contains the default format ANTLR uses.\n*/\n\nlocation(file, line, column) ::= \"<file>:<line>:<column>:\"\n\nmessage(id, text) ::= \"(<id>) <text>\"\n\nreport(location, message, type) ::= \"<type>(<message.id>): <location> <message.text>\"\n\nwantsSingleLineMessage() ::= \"false\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/messages/formats/gnu.stg",
    "content": "/*\n [The \"BSD licence\"]\n Copyright (c) 2006 Kay Roepke\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\nThis file contains the actual layout of the messages emitted by ANTLR.\n The text itself is coming out of the languages/*stg files, according to the chosen locale.\n This file contains the format that mimicks GCC output.\n*/\n\nlocation(file, line, column) ::= \"<file>:<line>:<column>:\"\n\nmessage(id, text) ::= \"<text> [error <id>]\"\n\nreport(location, message, type) ::= \"<location> <type>: <message>\"\n\nwantsSingleLineMessage() ::= \"true\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/messages/formats/vs2005.stg",
    "content": "/*\n [The \"BSD licence\"]\n Copyright (c) 2006 Kay Roepke\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\n This file contains the actual layout of the messages emitted by ANTLR.\n The text itself is coming out of the languages/*stg files, according to the chosen locale.\n This file contains the default format ANTLR uses.\n*/\n\nlocation(file, line, column) ::= \"<file>(<line>,<column>)\"\n\nmessage(id, text) ::= \"error <id> : <text>\"\n\nreport(location, message, type) ::= \"<location> : <type> <message.id> : <message.text>\"\n\nwantsSingleLineMessage() ::= \"true\"\n"
  },
  {
    "path": "tool/resources/org/antlr/v4/tool/templates/unicodedata.st",
    "content": "unicodedata(rawPropertyCodePointRanges, rawPropertyAliases) ::= <<\npackage org.antlr.v4.unicode;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.ArrayList;\n\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.misc.Interval;\n\n/**\n * Code-generated utility class mapping Unicode properties to Unicode code point ranges.\n */\npublic abstract class UnicodeData {\n\tprivate static final Map\\<String, IntervalSet\\> propertyCodePointRanges = new HashMap\\<\\>(<length(rawPropertyCodePointRanges)>);\n\tprivate static final Map\\<String, String\\> propertyAliases = new HashMap\\<\\>(<length(rawPropertyAliases)> / 2);\n\n\tprivate static void addProperty(String propertyName, int[] rawIntervals) {\n\t\tList\\<Interval> intervals = new ArrayList\\<>(rawIntervals.length / 2);\n\t\tfor (int i = 0; i \\< rawIntervals.length; i += 2) {\n\t\t\tintervals.add(new Interval(rawIntervals[i], rawIntervals[i + 1]));\n\t\t}\n\t\tIntervalSet result = new IntervalSet(intervals);\n\t\tresult.setReadonly(true);\n\t\tpropertyCodePointRanges.put(propertyName, result);\n\t}\n\n\t<rawPropertyCodePointRanges.keys:{ k |\nstatic private void addProperty<i>() { addProperty(\"<k>\", new int[] { <rawPropertyCodePointRanges.(k):{j | <j>}; separator=\",\", wrap> \\}); \\}}; separator=\"\\n\">\n\n\tstatic private void addPropertyAliases() {\n\t\tString[] rawAliases = new String[] { <rawPropertyAliases:{k | \"<k>\"}; separator=\",\", wrap> };\n\t\tfor (int i = 0; i \\< rawAliases.length; i += 2) {\n\t\t\tpropertyAliases.put(rawAliases[i], rawAliases[i + 1]);\n\t\t}\n\t}\n\n\tstatic {\n\t\t<rawPropertyCodePointRanges.keys:{ k | addProperty<i>();}; separator=\"\\n\">\n\t\taddPropertyAliases();\n\t}\n\n\tprivate static String normalize(String propertyCodeOrAlias) {\n\t\treturn propertyCodeOrAlias.toLowerCase(Locale.US).replace('-', '_');\n\t}\n\n\t/**\n\t * Given a Unicode property (general category code, binary property name, or script name),\n\t * returns the {@link IntervalSet} of Unicode code point ranges which have that property.\n\t */\n\tpublic static IntervalSet getPropertyCodePoints(String propertyCodeOrAlias) {\n\t\tString normalizedPropertyCodeOrAlias = normalize(propertyCodeOrAlias);\n\t\tIntervalSet result = propertyCodePointRanges.get(normalizedPropertyCodeOrAlias);\n\t\tif (result == null) {\n\t\t\tString propertyCode = propertyAliases.get(normalizedPropertyCodeOrAlias);\n\t\t\tresult = propertyCodePointRanges.get(propertyCode);\n\t\t}\n\t\treturn result;\n\t}\n}\n>>\n"
  },
  {
    "path": "tool/src/org/antlr/v4/Tool.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4;\n\nimport org.antlr.runtime.ANTLRFileStream;\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.CharStream;\nimport org.antlr.runtime.CommonTokenStream;\nimport org.antlr.runtime.ParserRuleReturnScope;\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.analysis.AnalysisPipeline;\nimport org.antlr.v4.automata.ATNFactory;\nimport org.antlr.v4.automata.LexerATNFactory;\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.codegen.CodeGenPipeline;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.misc.Graph;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.parse.GrammarTreeVisitor;\nimport org.antlr.v4.parse.ToolANTLRLexer;\nimport org.antlr.v4.parse.ToolANTLRParser;\nimport org.antlr.v4.runtime.RuntimeMetaData;\nimport org.antlr.v4.runtime.misc.LogManager;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.semantics.SemanticPipeline;\nimport org.antlr.v4.tool.ANTLRMessage;\nimport org.antlr.v4.tool.ANTLRToolListener;\nimport org.antlr.v4.tool.BuildDependencyGenerator;\nimport org.antlr.v4.tool.DOTGenerator;\nimport org.antlr.v4.tool.DefaultToolListener;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.GrammarTransformPipeline;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTErrorNode;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\nimport org.stringtemplate.v4.STGroup;\n\nimport java.io.BufferedWriter;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStreamWriter;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.lang.reflect.Field;\nimport java.util.*;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\npublic class Tool {\n\tpublic static final String VERSION;\n\tstatic {\n\t\t// Assigned in a static{} block to prevent the field from becoming a\n\t\t// compile-time constant\n\t\tVERSION = RuntimeMetaData.VERSION;\n\t}\n\n\tpublic static final String GRAMMAR_EXTENSION = \".g4\";\n\tpublic static final String LEGACY_GRAMMAR_EXTENSION = \".g\";\n\n\tpublic static final List<String> ALL_GRAMMAR_EXTENSIONS =\n\t\tCollections.unmodifiableList(Arrays.asList(GRAMMAR_EXTENSION, LEGACY_GRAMMAR_EXTENSION));\n\n\tpublic static enum OptionArgType { NONE, STRING } // NONE implies boolean\n\tpublic static class Option {\n\t\tString fieldName;\n\t\tString name;\n\t\tOptionArgType argType;\n\t\tString description;\n\n\t\tpublic Option(String fieldName, String name, String description) {\n\t\t\tthis(fieldName, name, OptionArgType.NONE, description);\n\t\t}\n\n\t\tpublic Option(String fieldName, String name, OptionArgType argType, String description) {\n\t\t\tthis.fieldName = fieldName;\n\t\t\tthis.name = name;\n\t\t\tthis.argType = argType;\n\t\t\tthis.description = description;\n\t\t}\n\t}\n\n\t// fields set by option manager\n\n\tpublic File inputDirectory; // used by mvn plugin but not set by tool itself.\n\tpublic String outputDirectory;\n\tpublic String libDirectory;\n\tpublic boolean generate_ATN_dot = false;\n\tpublic String grammarEncoding = null; // use default locale's encoding\n\tpublic String msgFormat = \"antlr\";\n\tpublic boolean launch_ST_inspector = false;\n\tpublic boolean ST_inspector_wait_for_close = false;\n    public boolean force_atn = false;\n    public boolean log = false;\n\tpublic boolean gen_listener = true;\n\tpublic boolean gen_visitor = false;\n\tpublic boolean gen_split_parser = false;\n\tpublic boolean gen_dependencies = false;\n\tpublic String genPackage = null;\n\tpublic Map<String, String> grammarOptions = null;\n\tpublic boolean warnings_are_errors = false;\n\tpublic boolean longMessages = false;\n\tpublic boolean exact_output_dir = false;\n\n    public final static Option[] optionDefs = {\n\t\tnew Option(\"outputDirectory\",             \"-o\", OptionArgType.STRING, \"specify output directory where all output is generated\"),\n\t\tnew Option(\"libDirectory\",                \"-lib\", OptionArgType.STRING, \"specify location of grammars, tokens files\"),\n\t\tnew Option(\"generate_ATN_dot\",            \"-atn\", \"generate rule augmented transition network diagrams\"),\n\t\tnew Option(\"grammarEncoding\",             \"-encoding\", OptionArgType.STRING, \"specify grammar file encoding; e.g., euc-jp\"),\n\t\tnew Option(\"msgFormat\",                   \"-message-format\", OptionArgType.STRING, \"specify output style for messages in antlr, gnu, vs2005\"),\n\t\tnew Option(\"longMessages\",                \"-long-messages\", \"show exception details when available for errors and warnings\"),\n\t\tnew Option(\"gen_listener\",                \"-listener\", \"generate parse tree listener (default)\"),\n\t\tnew Option(\"gen_listener\",                \"-no-listener\", \"don't generate parse tree listener\"),\n\t\tnew Option(\"gen_visitor\",                 \"-visitor\", \"generate parse tree visitor\"),\n\t\tnew Option(\"gen_visitor\",                 \"-no-visitor\", \"don't generate parse tree visitor (default)\"),\n\t\tnew Option(\"genPackage\",                  \"-package\", OptionArgType.STRING, \"specify a package/namespace for the generated code\"),\n\t\tnew Option(\"gen_dependencies\",            \"-depend\", \"generate file dependencies\"),\n\t\tnew Option(\"gen_split_parser\",           \"-split-parser\", \"generate separate files for parser serialized DFA and context classes\"),\n\t\tnew Option(\"gen_split_parser\",           \"-no-split-parser\", \"generate parser serialized DFA and context classes locally (default)\"),\n\t\tnew Option(\"\",                            \"-D<option>=value\", \"set/override a grammar-level option\"),\n\t\tnew Option(\"warnings_are_errors\",         \"-Werror\", \"treat warnings as errors\"),\n\t\tnew Option(\"launch_ST_inspector\",         \"-XdbgST\", \"launch StringTemplate visualizer on generated code\"),\n\t\tnew Option(\"ST_inspector_wait_for_close\", \"-XdbgSTWait\", \"wait for STViz to close before continuing\"),\n\t\tnew Option(\"force_atn\",                   \"-Xforce-atn\", \"use the ATN simulator for all predictions\"),\n\t\tnew Option(\"log\",                         \"-Xlog\", \"dump lots of logging info to antlr-timestamp.log\"),\n\t    new Option(\"exact_output_dir\",            \"-Xexact-output-dir\", \"all output goes into -o dir regardless of paths/package\"),\n\t};\n\n\t// helper vars for option management\n\tprotected boolean haveOutputDir = false;\n\tprotected boolean return_dont_exit = false;\n\n\n\tpublic final String[] args;\n\n\tprotected List<String> grammarFiles = new ArrayList<String>();\n\n\tpublic ErrorManager errMgr;\n    public LogManager logMgr = new LogManager();\n\n\tList<ANTLRToolListener> listeners = new CopyOnWriteArrayList<ANTLRToolListener>();\n\n\t/** Track separately so if someone adds a listener, it's the only one\n\t *  instead of it and the default stderr listener.\n\t */\n\tDefaultToolListener defaultListener = new DefaultToolListener(this);\n\n\tpublic static void main(String[] args) {\n        Tool antlr = new Tool(args);\n        if ( args.length == 0 ) { antlr.help(); antlr.exit(0); }\n\n        try {\n            antlr.processGrammarsOnCommandLine();\n        }\n        finally {\n            if ( antlr.log ) {\n                try {\n                    String logname = antlr.logMgr.save();\n                    System.out.println(\"wrote \"+logname);\n                }\n                catch (IOException ioe) {\n                    antlr.errMgr.toolError(ErrorType.INTERNAL_ERROR, ioe);\n                }\n            }\n        }\n\t\tif ( antlr.return_dont_exit ) return;\n\n\t\tif (antlr.errMgr.getNumErrors() > 0) {\n\t\t\tantlr.exit(1);\n\t\t}\n\t\tantlr.exit(0);\n\t}\n\n\tpublic Tool() { this(null); }\n\n\tpublic Tool(String[] args) {\n\t\tthis.args = args;\n\t\terrMgr = new ErrorManager(this);\n\t\t// We have to use the default message format until we have\n\t\t// parsed the -message-format command line option.\n\t\terrMgr.setFormat(\"antlr\");\n\t\thandleArgs();\n\t\terrMgr.setFormat(msgFormat);\n\t}\n\n\tprotected void handleArgs() {\n\t\tint i=0;\n\t\twhile ( args!=null && i<args.length ) {\n\t\t\tString arg = args[i];\n\t\t\ti++;\n\t\t\tif ( arg.startsWith(\"-D\") ) { // -Dlanguage=Java syntax\n\t\t\t\thandleOptionSetArg(arg);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( arg.charAt(0)!='-' ) { // file name\n\t\t\t\tif ( !grammarFiles.contains(arg) ) grammarFiles.add(arg);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tboolean found = false;\n\t\t\tfor (Option o : optionDefs) {\n\t\t\t\tif ( arg.equals(o.name) ) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tString argValue = null;\n\t\t\t\t\tif ( o.argType==OptionArgType.STRING ) {\n\t\t\t\t\t\targValue = args[i];\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\t// use reflection to set field\n\t\t\t\t\tClass<? extends Tool> c = this.getClass();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tField f = c.getField(o.fieldName);\n\t\t\t\t\t\tif ( argValue==null ) {\n\t\t\t\t\t\t\tif ( arg.startsWith(\"-no-\") ) f.setBoolean(this, false);\n\t\t\t\t\t\t\telse f.setBoolean(this, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse f.set(this, argValue);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\terrMgr.toolError(ErrorType.INTERNAL_ERROR, \"can't access field \"+o.fieldName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( !found ) {\n\t\t\t\terrMgr.toolError(ErrorType.INVALID_CMDLINE_ARG, arg);\n\t\t\t}\n\t\t}\n\t\tif ( outputDirectory!=null ) {\n\t\t\tif (outputDirectory.endsWith(\"/\") ||\n\t\t\t\toutputDirectory.endsWith(\"\\\\\")) {\n\t\t\t\toutputDirectory =\n\t\t\t\t\toutputDirectory.substring(0, outputDirectory.length() - 1);\n\t\t\t}\n\t\t\tFile outDir = new File(outputDirectory);\n\t\t\thaveOutputDir = true;\n\t\t\tif (outDir.exists() && !outDir.isDirectory()) {\n\t\t\t\terrMgr.toolError(ErrorType.OUTPUT_DIR_IS_FILE, outputDirectory);\n\t\t\t\toutputDirectory = \".\";\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\toutputDirectory = \".\";\n\t\t}\n\t\tif ( libDirectory!=null ) {\n\t\t\tif (libDirectory.endsWith(\"/\") ||\n\t\t\t\tlibDirectory.endsWith(\"\\\\\")) {\n\t\t\t\tlibDirectory = libDirectory.substring(0, libDirectory.length() - 1);\n\t\t\t}\n\t\t\tFile outDir = new File(libDirectory);\n\t\t\tif (!outDir.exists()) {\n\t\t\t\terrMgr.toolError(ErrorType.DIR_NOT_FOUND, libDirectory);\n\t\t\t\tlibDirectory = \".\";\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tlibDirectory = \".\";\n\t\t}\n\t\tif ( launch_ST_inspector ) {\n\t\t\tSTGroup.trackCreationEvents = true;\n\t\t\treturn_dont_exit = true;\n\t\t}\n\t}\n\n\tprotected void handleOptionSetArg(String arg) {\n\t\tint eq = arg.indexOf('=');\n\t\tif ( eq>0 && arg.length()>3 ) {\n\t\t\tString option = arg.substring(\"-D\".length(), eq);\n\t\t\tString value = arg.substring(eq+1);\n\t\t\tif ( value.length()==0 ) {\n\t\t\t\terrMgr.toolError(ErrorType.BAD_OPTION_SET_SYNTAX, arg);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ( Grammar.parserOptions.contains(option) ||\n\t\t\t\t Grammar.lexerOptions.contains(option) )\n\t\t\t{\n\t\t\t\tif ( grammarOptions==null ) grammarOptions = new HashMap<String, String>();\n\t\t\t\tgrammarOptions.put(option, value);\n\t\t\t}\n\t\t\telse {\n\t\t\t\terrMgr.grammarError(ErrorType.ILLEGAL_OPTION,\n\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t\toption);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\terrMgr.toolError(ErrorType.BAD_OPTION_SET_SYNTAX, arg);\n\t\t}\n\t}\n\n\tpublic void processGrammarsOnCommandLine() {\n\t\tList<GrammarRootAST> sortedGrammars = sortGrammarByTokenVocab(grammarFiles);\n\n\t\tfor (GrammarRootAST t : sortedGrammars) {\n\t\t\tfinal Grammar g = createGrammar(t);\n\t\t\tg.fileName = t.fileName;\n\t\t\tif ( gen_dependencies ) {\n\t\t\t\tBuildDependencyGenerator dep =\n\t\t\t\t\tnew BuildDependencyGenerator(this, g);\n\t\t\t\t/*\n\t\t\t\t\tList outputFiles = dep.getGeneratedFileList();\n\t\t\t\t\tList dependents = dep.getDependenciesFileList();\n\t\t\t\t\tSystem.out.println(\"output: \"+outputFiles);\n\t\t\t\t\tSystem.out.println(\"dependents: \"+dependents);\n\t\t\t\t\t */\n\t\t\t\tSystem.out.println(dep.getDependencies().render());\n\n\t\t\t}\n\t\t\telse if (errMgr.getNumErrors() == 0) {\n\t\t\t\tprocess(g, true);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** To process a grammar, we load all of its imported grammars into\n\t\tsubordinate grammar objects. Then we merge the imported rules\n\t\tinto the root grammar. If a root grammar is a combined grammar,\n\t\twe have to extract the implicit lexer. Once all this is done, we\n\t\tprocess the lexer first, if present, and then the parser grammar\n\t */\n\tpublic void process(Grammar g, boolean gencode) {\n\t\tg.loadImportedGrammars();\n\n\t\tGrammarTransformPipeline transform = new GrammarTransformPipeline(g, this);\n\t\ttransform.process();\n\n\t\tLexerGrammar lexerg;\n\t\tGrammarRootAST lexerAST;\n\t\tif ( g.ast!=null && g.ast.grammarType== ANTLRParser.COMBINED &&\n\t\t\t !g.ast.hasErrors )\n\t\t{\n\t\t\tlexerAST = transform.extractImplicitLexer(g); // alters g.ast\n\t\t\tif ( lexerAST!=null ) {\n\t\t\t\tif (grammarOptions != null) {\n\t\t\t\t\tlexerAST.cmdLineOptions = grammarOptions;\n\t\t\t\t}\n\n\t\t\t\tlexerg = new LexerGrammar(this, lexerAST);\n\t\t\t\tlexerg.fileName = g.fileName;\n\t\t\t\tlexerg.originalGrammar = g;\n\t\t\t\tg.implicitLexer = lexerg;\n\t\t\t\tlexerg.implicitLexerOwner = g;\n\t\t\t\tprocessNonCombinedGrammar(lexerg, gencode);\n//\t\t\t\tSystem.out.println(\"lexer tokens=\"+lexerg.tokenNameToTypeMap);\n//\t\t\t\tSystem.out.println(\"lexer strings=\"+lexerg.stringLiteralToTypeMap);\n\t\t\t}\n\t\t}\n\t\tif ( g.implicitLexer!=null ) g.importVocab(g.implicitLexer);\n//\t\tSystem.out.println(\"tokens=\"+g.tokenNameToTypeMap);\n//\t\tSystem.out.println(\"strings=\"+g.stringLiteralToTypeMap);\n\t\tprocessNonCombinedGrammar(g, gencode);\n\t}\n\n\tpublic void processNonCombinedGrammar(Grammar g, boolean gencode) {\n\t\tif ( g.ast==null || g.ast.hasErrors ) return;\n\n\t\tboolean ruleFail = checkForRuleIssues(g);\n\t\tif ( ruleFail ) return;\n\n\t\tint prevErrors = errMgr.getNumErrors();\n\t\t// MAKE SURE GRAMMAR IS SEMANTICALLY CORRECT (FILL IN GRAMMAR OBJECT)\n\t\tSemanticPipeline sem = new SemanticPipeline(g);\n\t\tsem.process();\n\n\t\tif ( errMgr.getNumErrors()>prevErrors ) return;\n\n\t\tCodeGenerator codeGenerator = CodeGenerator.create(g);\n\t\tif (codeGenerator == null) {\n\t\t\treturn;\n\t\t}\n\n\t\t// BUILD ATN FROM AST\n\t\tATNFactory factory;\n\t\tif ( g.isLexer() ) factory = new LexerATNFactory((LexerGrammar)g, codeGenerator);\n\t\telse factory = new ParserATNFactory(g);\n\t\tg.atn = factory.createATN();\n\n\t\tif ( generate_ATN_dot ) generateATNs(g);\n\n\t\tif (gencode && g.tool.getNumErrors()==0 ) {\n\t\t\tString interpFile = generateInterpreterData(g);\n\t\t\ttry (Writer fw = getOutputFileWriter(g, g.name + \".interp\")) {\n\t\t\t\tfw.write(interpFile);\n\t\t\t}\n\t\t\tcatch (IOException ioe) {\n\t\t\t\terrMgr.toolError(ErrorType.CANNOT_WRITE_FILE, ioe);\n\t\t\t}\n\t\t}\n\n\t\t// PERFORM GRAMMAR ANALYSIS ON ATN: BUILD DECISION DFAs\n\t\tAnalysisPipeline anal = new AnalysisPipeline(g);\n\t\tanal.process();\n\n\t\t//if ( generate_DFA_dot ) generateDFAs(g);\n\n\t\tif ( g.tool.getNumErrors()>prevErrors ) return;\n\n\t\t// GENERATE CODE\n\t\tif ( gencode ) {\n\t\t\tCodeGenPipeline gen = new CodeGenPipeline(g, codeGenerator);\n\t\t\tgen.process();\n\t\t}\n\t}\n\n\t/**\n\t * Important enough to avoid multiple definitions that we do very early,\n\t * right after AST construction. Also check for undefined rules in\n\t * parser/lexer to avoid exceptions later. Return true if we find multiple\n\t * definitions of the same rule or a reference to an undefined rule or\n\t * parser rule ref in lexer rule.\n\t */\n\tpublic boolean checkForRuleIssues(final Grammar g) {\n\t\t// check for redefined rules\n\t\tGrammarAST RULES = (GrammarAST)g.ast.getFirstChildWithType(ANTLRParser.RULES);\n\t\tList<GrammarAST> rules = new ArrayList<GrammarAST>(RULES.getAllChildrenWithType(ANTLRParser.RULE));\n\t\tfor (GrammarAST mode : g.ast.getAllChildrenWithType(ANTLRParser.MODE)) {\n\t\t\trules.addAll(mode.getAllChildrenWithType(ANTLRParser.RULE));\n\t\t}\n\n\t\tboolean redefinition = false;\n\t\tfinal Map<String, RuleAST> ruleToAST = new HashMap<String, RuleAST>();\n\t\tfor (GrammarAST r : rules) {\n\t\t\tRuleAST ruleAST = (RuleAST)r;\n\t\t\tGrammarAST ID = (GrammarAST)ruleAST.getChild(0);\n\t\t\tString ruleName = ID.getText();\n\t\t\tRuleAST prev = ruleToAST.get(ruleName);\n\t\t\tif ( prev !=null ) {\n\t\t\t\tGrammarAST prevChild = (GrammarAST)prev.getChild(0);\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.RULE_REDEFINITION,\n\t\t\t\t\t\t\t\t\t\t   g.fileName,\n\t\t\t\t\t\t\t\t\t\t   ID.getToken(),\n\t\t\t\t\t\t\t\t\t\t   ruleName,\n\t\t\t\t\t\t\t\t\t\t   prevChild.getToken().getLine());\n\t\t\t\tredefinition = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\truleToAST.put(ruleName, ruleAST);\n\t\t}\n\n\t\t// check for undefined rules\n\t\tclass UndefChecker extends GrammarTreeVisitor {\n\t\t\tpublic boolean badref = false;\n\t\t\t@Override\n\t\t\tpublic void tokenRef(TerminalAST ref) {\n\t\t\t\tif (\"EOF\".equals(ref.getText())) {\n\t\t\t\t\t// this is a special predefined reference\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif ( g.isLexer() ) ruleRef(ref, null);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void ruleRef(GrammarAST ref, ActionAST arg) {\n\t\t\t\tRuleAST ruleAST = ruleToAST.get(ref.getText());\n\t\t\t\tString fileName = ref.getToken().getInputStream().getSourceName();\n\t\t\t\tif (Character.isUpperCase(currentRuleName.charAt(0)) &&\n\t\t\t\t\tCharacter.isLowerCase(ref.getText().charAt(0)))\n\t\t\t\t{\n\t\t\t\t\tbadref = true;\n\t\t\t\t\terrMgr.grammarError(ErrorType.PARSER_RULE_REF_IN_LEXER_RULE,\n\t\t\t\t\t\t\t\t\t\tfileName, ref.getToken(), ref.getText(), currentRuleName);\n\t\t\t\t}\n\t\t\t\telse if ( ruleAST==null ) {\n\t\t\t\t\tbadref = true;\n\t\t\t\t\terrMgr.grammarError(ErrorType.UNDEFINED_RULE_REF,\n\t\t\t\t\t\t\t\t\t\tfileName, ref.token, ref.getText());\n\t\t\t\t}\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic ErrorManager getErrorManager() { return errMgr; }\n\t\t}\n\n\t\tUndefChecker chk = new UndefChecker();\n\t\tchk.visitGrammar(g.ast);\n\n\t\treturn redefinition || chk.badref;\n\t}\n\n\tpublic List<GrammarRootAST> sortGrammarByTokenVocab(List<String> fileNames) {\n//\t\tSystem.out.println(fileNames);\n\t\tGraph<String> g = new Graph<String>();\n\t\tList<GrammarRootAST> roots = new ArrayList<GrammarRootAST>();\n\t\tfor (String fileName : fileNames) {\n\t\t\tGrammarAST t = parseGrammar(fileName);\n\t\t\tif ( t==null || t instanceof GrammarASTErrorNode) continue; // came back as error node\n\t\t\tif ( ((GrammarRootAST)t).hasErrors ) continue;\n\t\t\tGrammarRootAST root = (GrammarRootAST)t;\n\t\t\troots.add(root);\n\t\t\troot.fileName = fileName;\n\t\t\tString grammarName = root.getChild(0).getText();\n\n\t\t\tGrammarAST tokenVocabNode = findOptionValueAST(root, \"tokenVocab\");\n\t\t\t// Make grammars depend on any tokenVocab options\n\t\t\tif ( tokenVocabNode!=null ) {\n\t\t\t\tString vocabName = tokenVocabNode.getText();\n\t\t\t\t// Strip quote characters if any\n\t\t\t\tint len = vocabName.length();\n\t\t\t\tint firstChar = vocabName.charAt(0);\n\t\t\t\tint lastChar = vocabName.charAt(len - 1);\n\t\t\t\tif (len >= 2 && firstChar == '\\'' && lastChar == '\\'') {\n\t\t\t\t\tvocabName = vocabName.substring(1, len-1);\n\t\t\t\t}\n\t\t\t\t// If the name contains a path delimited by forward slashes,\n\t\t\t\t// use only the part after the last slash as the name\n\t\t\t\tint lastSlash = vocabName.lastIndexOf('/');\n\t\t\t\tif (lastSlash >= 0) {\n\t\t\t\t\tvocabName = vocabName.substring(lastSlash + 1);\n\t\t\t\t}\n\t\t\t\tg.addEdge(grammarName, vocabName);\n\t\t\t}\n\t\t\t// add cycle to graph so we always process a grammar if no error\n\t\t\t// even if no dependency\n\t\t\tg.addEdge(grammarName, grammarName);\n\t\t}\n\n\t\tList<String> sortedGrammarNames = g.sort();\n//\t\tSystem.out.println(\"sortedGrammarNames=\"+sortedGrammarNames);\n\n\t\tList<GrammarRootAST> sortedRoots = new ArrayList<GrammarRootAST>();\n\t\tfor (String grammarName : sortedGrammarNames) {\n\t\t\tfor (GrammarRootAST root : roots) {\n\t\t\t\tif ( root.getGrammarName().equals(grammarName) ) {\n\t\t\t\t\tsortedRoots.add(root);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sortedRoots;\n\t}\n\n\t/** Manually get option node from tree; return null if no defined. */\n\tpublic static GrammarAST findOptionValueAST(GrammarRootAST root, String option) {\n\t\tGrammarAST options = (GrammarAST)root.getFirstChildWithType(ANTLRParser.OPTIONS);\n\t\tif ( options!=null && options.getChildCount() > 0 ) {\n\t\t\tfor (Object o : options.getChildren()) {\n\t\t\t\tGrammarAST c = (GrammarAST)o;\n\t\t\t\tif ( c.getType() == ANTLRParser.ASSIGN &&\n\t\t\t\t\t c.getChild(0).getText().equals(option) )\n\t\t\t\t{\n\t\t\t\t\treturn (GrammarAST)c.getChild(1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\n\t/** Given the raw AST of a grammar, create a grammar object\n\t\tassociated with the AST. Once we have the grammar object, ensure\n\t\tthat all nodes in tree referred to this grammar. Later, we will\n\t\tuse it for error handling and generally knowing from where a rule\n\t\tcomes from.\n\t */\n\tpublic Grammar createGrammar(GrammarRootAST ast) {\n\t\tfinal Grammar g;\n\t\tif ( ast.grammarType==ANTLRParser.LEXER ) g = new LexerGrammar(this, ast);\n\t\telse g = new Grammar(this, ast);\n\n\t\t// ensure each node has pointer to surrounding grammar\n\t\tGrammarTransformPipeline.setGrammarPtr(g, ast);\n\t\treturn g;\n\t}\n\n\tpublic GrammarRootAST parseGrammar(String fileName) {\n\t\ttry {\n\t\t\tFile file = new File(fileName);\n\t\t\tif (!file.isAbsolute()) {\n\t\t\t\tfile = new File(inputDirectory, fileName);\n\t\t\t}\n\n\t\t\tANTLRFileStream in = new ANTLRFileStream(file.getAbsolutePath(), grammarEncoding);\n\t\t\tGrammarRootAST t = parse(fileName, in);\n\t\t\treturn t;\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\terrMgr.toolError(ErrorType.CANNOT_OPEN_FILE, ioe, fileName);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Convenience method to load and process an ANTLR grammar. Useful\n\t *  when creating interpreters.  If you need to access to the lexer\n\t *  grammar created while processing a combined grammar, use\n\t *  getImplicitLexer() on returned grammar.\n\t */\n\tpublic Grammar loadGrammar(String fileName) {\n\t\tGrammarRootAST grammarRootAST = parseGrammar(fileName);\n\t\tfinal Grammar g = createGrammar(grammarRootAST);\n\t\tg.fileName = fileName;\n\t\tprocess(g, false);\n\t\treturn g;\n\t}\n\n\tprivate final Map<String, Grammar> importedGrammars = new HashMap<String, Grammar>();\n\n\t/**\n\t * Try current dir then dir of g then lib dir\n\t * @param g\n\t * @param nameNode The node associated with the imported grammar name.\n\t */\n\tpublic Grammar loadImportedGrammar(Grammar g, GrammarAST nameNode) throws IOException {\n\t\tString name = nameNode.getText();\n\t\tGrammar imported = importedGrammars.get(name);\n\t\tif (imported == null) {\n\t\t\tg.tool.log(\"grammar\", \"load \" + name + \" from \" + g.fileName);\n\t\t\tFile importedFile = null;\n\t\t\tfor (String extension : ALL_GRAMMAR_EXTENSIONS) {\n\t\t\t\timportedFile = getImportedGrammarFile(g, name + extension);\n\t\t\t\tif (importedFile != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( importedFile==null ) {\n\t\t\t\terrMgr.grammarError(ErrorType.CANNOT_FIND_IMPORTED_GRAMMAR, g.fileName, nameNode.getToken(), name);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tString absolutePath = importedFile.getAbsolutePath();\n\t\t\tANTLRFileStream in = new ANTLRFileStream(absolutePath, grammarEncoding);\n\t\t\tGrammarRootAST root = parse(g.fileName, in);\n\t\t\tif (root == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\timported = createGrammar(root);\n\t\t\timported.fileName = absolutePath;\n\t\t\timportedGrammars.put(root.getGrammarName(), imported);\n\t\t}\n\n\t\treturn imported;\n\t}\n\n\tpublic GrammarRootAST parseGrammarFromString(String grammar) {\n\t\treturn parse(\"<string>\", new ANTLRStringStream(grammar));\n\t}\n\n\tpublic GrammarRootAST parse(String fileName, CharStream in) {\n\t\ttry {\n\t\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(in);\n\t\t\tToolANTLRLexer lexer = new ToolANTLRLexer(in, this);\n\t\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\t\t\tlexer.tokens = tokens;\n\t\t\tToolANTLRParser p = new ToolANTLRParser(tokens, this);\n\t\t\tp.setTreeAdaptor(adaptor);\n\t\t\tParserRuleReturnScope r = p.grammarSpec();\n\t\t\tGrammarAST root = (GrammarAST) r.getTree();\n\t\t\tif (root instanceof GrammarRootAST) {\n\t\t\t\t((GrammarRootAST) root).hasErrors = lexer.getNumberOfSyntaxErrors() > 0 || p.getNumberOfSyntaxErrors() > 0;\n\t\t\t\tassert ((GrammarRootAST) root).tokenStream == tokens;\n\t\t\t\tif (grammarOptions != null) {\n\t\t\t\t\t((GrammarRootAST) root).cmdLineOptions = grammarOptions;\n\t\t\t\t}\n\t\t\t\treturn ((GrammarRootAST) root);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\tcatch (RecognitionException re) {\n\t\t\t// TODO: do we gen errors now?\n\t\t\tErrorManager.internalError(\"can't generate this message at moment; antlr recovers\");\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void generateATNs(Grammar g) {\n\t\tDOTGenerator dotGenerator = new DOTGenerator(g);\n\t\tList<Grammar> grammars = new ArrayList<Grammar>();\n\t\tgrammars.add(g);\n\t\tList<Grammar> imported = g.getAllImportedGrammars();\n\t\tif ( imported!=null ) grammars.addAll(imported);\n\t\tfor (Grammar ig : grammars) {\n\t\t\tfor (Rule r : ig.rules.values()) {\n\t\t\t\ttry {\n\t\t\t\t\tString dot = dotGenerator.getDOT(g.atn.ruleToStartState[r.index], g.isLexer());\n\t\t\t\t\tif (dot != null) {\n\t\t\t\t\t\twriteDOTFile(g, r, dot);\n\t\t\t\t\t}\n\t\t\t\t}\n                catch (IOException ioe) {\n\t\t\t\t\terrMgr.toolError(ErrorType.CANNOT_WRITE_FILE, ioe);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static String generateInterpreterData(Grammar g) {\n\t\tStringBuilder content = new StringBuilder();\n\n\t\tcontent.append(\"token literal names:\\n\");\n\t\tString[] names = g.getTokenLiteralNames();\n\t\tfor (String name : names) {\n\t\t\tcontent.append(name + \"\\n\");\n\t\t}\n\t\tcontent.append(\"\\n\");\n\n\t\tcontent.append(\"token symbolic names:\\n\");\n\t\tnames = g.getTokenSymbolicNames();\n\t\tfor (String name : names) {\n\t\t\tcontent.append(name + \"\\n\");\n\t\t}\n\t\tcontent.append(\"\\n\");\n\n\t\tcontent.append(\"rule names:\\n\");\n\t\tnames = g.getRuleNames();\n\t\tfor (String name : names) {\n\t\t\tcontent.append(name + \"\\n\");\n\t\t}\n\t\tcontent.append(\"\\n\");\n\n\t\tif ( g.isLexer() ) {\n\t\t\tcontent.append(\"channel names:\\n\");\n\t\t\tcontent.append(\"DEFAULT_TOKEN_CHANNEL\\n\");\n\t\t\tcontent.append(\"HIDDEN\\n\");\n\t\t\tfor (String channel : g.channelValueToNameList) {\n\t\t\t\tcontent.append(channel + \"\\n\");\n\t\t\t}\n\t\t\tcontent.append(\"\\n\");\n\n\t\t\tcontent.append(\"mode names:\\n\");\n\t\t\tfor (String mode : ((LexerGrammar)g).modes.keySet()) {\n\t\t\t\tcontent.append(mode + \"\\n\");\n\t\t\t}\n\t\t}\n\t\tcontent.append(\"\\n\");\n\n\t\tIntegerList serializedATN = ATNSerializer.getSerialized(g.atn);\n\t\t// Uncomment if you'd like to write out histogram info on the numbers of\n\t\t// each integer value:\n\t\t//Utils.writeSerializedATNIntegerHistogram(g.name+\"-histo.csv\", serializedATN);\n\n\t\tcontent.append(\"atn:\\n\");\n\t\tcontent.append(serializedATN.toString());\n\n\t\treturn content.toString();\n\t}\n\n\t/** This method is used by all code generators to create new output\n\t *  files. If the outputDir set by -o is not present it will be created.\n\t *  The final filename is sensitive to the output directory and\n\t *  the directory where the grammar file was found.  If -o is /tmp\n\t *  and the original grammar file was foo/t.g4 then output files\n\t *  go in /tmp/foo.\n\t *\n\t *  The output dir -o spec takes precedence if it's absolute.\n\t *  E.g., if the grammar file dir is absolute the output dir is given\n\t *  precedence. \"-o /tmp /usr/lib/t.g4\" results in \"/tmp/T.java\" as\n\t *  output (assuming t.g4 holds T.java).\n\t *\n\t *  If no -o is specified, then just write to the directory where the\n\t *  grammar file was found.\n\t *\n\t *  If outputDirectory==null then write a String.\n\t */\n\tpublic Writer getOutputFileWriter(Grammar g, String fileName) throws IOException {\n\t\tif (outputDirectory == null) {\n\t\t\treturn new StringWriter();\n\t\t}\n\t\t// output directory is a function of where the grammar file lives\n\t\t// for subdir/T.g4, you get subdir here.  Well, depends on -o etc...\n\t\tFile outputDir = getOutputDirectory(g.fileName);\n\t\tFile outputFile = new File(outputDir, fileName);\n\n\t\tif (!outputDir.exists()) {\n\t\t\toutputDir.mkdirs();\n\t\t}\n\t\tFileOutputStream fos = new FileOutputStream(outputFile);\n\t\tOutputStreamWriter osw;\n\t\tif ( grammarEncoding!=null ) {\n\t\t\tosw = new OutputStreamWriter(fos, grammarEncoding);\n\t\t}\n\t\telse {\n\t\t\tosw = new OutputStreamWriter(fos);\n\t\t}\n\t\treturn new BufferedWriter(osw);\n\t}\n\n\tpublic File getImportedGrammarFile(Grammar g, String fileName) {\n\t\tFile importedFile = new File(inputDirectory, fileName);\n\t\tif ( !importedFile.exists() ) {\n\t\t\tFile gfile = new File(g.fileName);\n\t\t\tString parentDir = gfile.getParent();\n\t\t\timportedFile = new File(parentDir, fileName);\n\t\t\tif ( !importedFile.exists() ) { // try in lib dir\n\t\t\t\timportedFile = new File(libDirectory, fileName);\n\t\t\t\tif ( !importedFile.exists() ) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn importedFile;\n\t}\n\n\t/**\n\t * Return the location where ANTLR will generate output files for a given\n\t * file. This is a base directory and output files will be relative to\n\t * here in some cases such as when -o option is used and input files are\n\t * given relative to the input directory.\n\t *\n\t * @param fileNameWithPath path to input source\n\t */\n\tpublic File getOutputDirectory(String fileNameWithPath) {\n\t\tif ( exact_output_dir ) {\n\t\t\treturn new_getOutputDirectory(fileNameWithPath);\n\t\t}\n\n\t\tFile outputDir;\n\t\tString fileDirectory;\n\n\t\t// Some files are given to us without a PATH but should should\n\t\t// still be written to the output directory in the relative path of\n\t\t// the output directory. The file directory is either the set of sub directories\n\t\t// or just or the relative path recorded for the parent grammar. This means\n\t\t// that when we write the tokens files, or the .java files for imported grammars\n\t\t// taht we will write them in the correct place.\n\t\tif ((fileNameWithPath == null) || (fileNameWithPath.lastIndexOf(File.separatorChar) == -1)) {\n\t\t\t// No path is included in the file name, so make the file\n\t\t\t// directory the same as the parent grammar (which might sitll be just \"\"\n\t\t\t// but when it is not, we will write the file in the correct place.\n\t\t\tfileDirectory = \".\";\n\n\t\t}\n\t\telse {\n\t\t\tfileDirectory = fileNameWithPath.substring(0, fileNameWithPath.lastIndexOf(File.separatorChar));\n\t\t}\n\t\tif ( haveOutputDir ) {\n\t\t\t// -o /tmp /var/lib/t.g4 => /tmp/T.java\n\t\t\t// -o subdir/output /usr/lib/t.g4 => subdir/output/T.java\n\t\t\t// -o . /usr/lib/t.g4 => ./T.java\n\t\t\tif (fileDirectory != null &&\n\t\t\t\t(new File(fileDirectory).isAbsolute() ||\n\t\t\t\t\tfileDirectory.startsWith(\"~\"))) { // isAbsolute doesn't count this :(\n\t\t\t\t// somebody set the dir, it takes precendence; write new file there\n\t\t\t\toutputDir = new File(outputDirectory);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// -o /tmp subdir/t.g4 => /tmp/subdir/T.java\n\t\t\t\tif (fileDirectory != null) {\n\t\t\t\t\toutputDir = new File(outputDirectory, fileDirectory);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\toutputDir = new File(outputDirectory);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// they didn't specify a -o dir so just write to location\n\t\t\t// where grammar is, absolute or relative, this will only happen\n\t\t\t// with command line invocation as build tools will always\n\t\t\t// supply an output directory.\n\t\t\toutputDir = new File(fileDirectory);\n\t\t}\n\t\treturn outputDir;\n\t}\n\n\t/** @since 4.7.1 in response to -Xexact-output-dir */\n\tpublic File new_getOutputDirectory(String fileNameWithPath) {\n\t\tFile outputDir;\n\t\tString fileDirectory;\n\n\t\tif (fileNameWithPath.lastIndexOf(File.separatorChar) == -1) {\n\t\t\t// No path is included in the file name, so make the file\n\t\t\t// directory the same as the parent grammar (which might still be just \"\"\n\t\t\t// but when it is not, we will write the file in the correct place.\n\t\t\tfileDirectory = \".\";\n\t\t}\n\t\telse {\n\t\t\tfileDirectory = fileNameWithPath.substring(0, fileNameWithPath.lastIndexOf(File.separatorChar));\n\t\t}\n\t\tif ( haveOutputDir ) {\n\t\t\t// -o /tmp /var/lib/t.g4 => /tmp/T.java\n\t\t\t// -o subdir/output /usr/lib/t.g4 => subdir/output/T.java\n\t\t\t// -o . /usr/lib/t.g4 => ./T.java\n\t\t\t// -o /tmp subdir/t.g4 => /tmp/T.java\n\t\t\toutputDir = new File(outputDirectory);\n\t\t}\n\t\telse {\n\t\t\t// they didn't specify a -o dir so just write to location\n\t\t\t// where grammar is, absolute or relative, this will only happen\n\t\t\t// with command line invocation as build tools will always\n\t\t\t// supply an output directory.\n\t\t\toutputDir = new File(fileDirectory);\n\t\t}\n\t\treturn outputDir;\n\t}\n\n\tprotected void writeDOTFile(Grammar g, Rule r, String dot) throws IOException {\n\t\twriteDOTFile(g, r.g.name + \".\" + r.name, dot);\n\t}\n\n\tprotected void writeDOTFile(Grammar g, String name, String dot) throws IOException {\n\t\tWriter fw = getOutputFileWriter(g, name + \".dot\");\n\t\ttry {\n\t\t\tfw.write(dot);\n\t\t}\n\t\tfinally {\n\t\t\tfw.close();\n\t\t}\n\t}\n\n\tpublic void help() {\n\t\tinfo(\"ANTLR Parser Generator  Version \" + Tool.VERSION);\n\t\tfor (Option o : optionDefs) {\n\t\t\tString name = o.name + (o.argType!=OptionArgType.NONE? \" ___\" : \"\");\n\t\t\tString s = String.format(\" %-19s %s\", name, o.description);\n\t\t\tinfo(s);\n\t\t}\n\t}\n\n    public void log(String component, String msg) { logMgr.log(component, msg); }\n    public void log(String msg) { log(null, msg); }\n\n\tpublic int getNumErrors() { return errMgr.getNumErrors(); }\n\n\tpublic void addListener(ANTLRToolListener tl) {\n\t\tif ( tl!=null ) listeners.add(tl);\n\t}\n\tpublic void removeListener(ANTLRToolListener tl) { listeners.remove(tl); }\n\tpublic void removeListeners() { listeners.clear(); }\n\tpublic List<ANTLRToolListener> getListeners() { return listeners; }\n\n\tpublic void info(String msg) {\n\t\tif ( listeners.isEmpty() ) {\n\t\t\tdefaultListener.info(msg);\n\t\t\treturn;\n\t\t}\n\t\tfor (ANTLRToolListener l : listeners) l.info(msg);\n\t}\n\tpublic void error(ANTLRMessage msg) {\n\t\tif ( listeners.isEmpty() ) {\n\t\t\tdefaultListener.error(msg);\n\t\t\treturn;\n\t\t}\n\t\tfor (ANTLRToolListener l : listeners) l.error(msg);\n\t}\n\tpublic void warning(ANTLRMessage msg) {\n\t\tif ( listeners.isEmpty() ) {\n\t\t\tdefaultListener.warning(msg);\n\t\t}\n\t\telse {\n\t\t\tfor (ANTLRToolListener l : listeners) l.warning(msg);\n\t\t}\n\n\t\tif (warnings_are_errors) {\n\t\t\terrMgr.emit(ErrorType.WARNING_TREATED_AS_ERROR, new ANTLRMessage(ErrorType.WARNING_TREATED_AS_ERROR));\n\t\t}\n\t}\n\n\tpublic void version() {\n\t\tinfo(\"ANTLR Parser Generator  Version \" + VERSION);\n\t}\n\n\tpublic void exit(int e) { System.exit(e); }\n\n\tpublic void panic() { throw new Error(\"ANTLR panic\"); }\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/analysis/AnalysisPipeline.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.analysis;\n\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.LL1Analyzer;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\npublic class AnalysisPipeline {\n\tpublic Grammar g;\n\n\tpublic AnalysisPipeline(Grammar g) {\n\t\tthis.g = g;\n\t}\n\n\tpublic void process() {\n\t\t// LEFT-RECURSION CHECK\n\t\tLeftRecursionDetector lr = new LeftRecursionDetector(g, g.atn);\n\t\tlr.check();\n\t\tif ( !lr.listOfRecursiveCycles.isEmpty() ) return; // bail out\n\n\t\tif (g.isLexer()) {\n\t\t\tprocessLexer();\n\t\t}\n\t\telse {\n\t\t\t// BUILD DFA FOR EACH DECISION\n\t\t\tprocessParser();\n\t\t}\n\t}\n\n\tprotected void processLexer() {\n\t\t// make sure all non-fragment lexer rules must match at least one symbol\n\t\tfor (Rule rule : g.rules.values()) {\n\t\t\tif (rule.isFragment()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tLL1Analyzer analyzer = new LL1Analyzer(g.atn);\n\t\t\tIntervalSet look = analyzer.LOOK(g.atn.ruleToStartState[rule.index], null);\n\t\t\tif (look.contains(Token.EPSILON)) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.EPSILON_TOKEN, g.fileName, ((GrammarAST)rule.ast.getChild(0)).getToken(), rule.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void processParser() {\n\t\tg.decisionLOOK = new ArrayList<IntervalSet[]>(g.atn.getNumberOfDecisions()+1);\n\t\tfor (DecisionState s : g.atn.decisionToState) {\n            g.tool.log(\"LL1\", \"\\nDECISION \"+s.decision+\" in rule \"+g.getRule(s.ruleIndex).name);\n\t\t\tIntervalSet[] look;\n\t\t\tif ( s.nonGreedy ) { // nongreedy decisions can't be LL(1)\n\t\t\t\tlook = new IntervalSet[s.getNumberOfTransitions()+1];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLL1Analyzer anal = new LL1Analyzer(g.atn);\n\t\t\t\tlook = anal.getDecisionLookahead(s);\n\t\t\t\tg.tool.log(\"LL1\", \"look=\" + Arrays.toString(look));\n\t\t\t}\n\n\t\t\tassert s.decision + 1 >= g.decisionLOOK.size();\n\t\t\tUtils.setSize(g.decisionLOOK, s.decision+1);\n\t\t\tg.decisionLOOK.set(s.decision, look);\n\t\t\tg.tool.log(\"LL1\", \"LL(1)? \" + disjoint(look));\n\t\t}\n\t}\n\n\t/** Return whether lookahead sets are disjoint; no lookahead ⇒ not disjoint */\n\tpublic static boolean disjoint(IntervalSet[] altLook) {\n\t\tboolean collision = false;\n\t\tIntervalSet combined = new IntervalSet();\n\t\tif ( altLook==null ) return false;\n\t\tfor (IntervalSet look : altLook) {\n\t\t\tif ( look==null ) return false; // lookahead must've computation failed\n\t\t\tif ( !look.and(combined).isNil() ) {\n\t\t\t\tcollision = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcombined.addAll(look);\n\t\t}\n\t\treturn !collision;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/analysis/LeftRecursionDetector.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.analysis;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.RuleStartState;\nimport org.antlr.v4.runtime.atn.RuleStopState;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.misc.OrderedHashSet;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class LeftRecursionDetector {\n\tGrammar g;\n\tpublic ATN atn;\n\n\t/** Holds a list of cycles (sets of rule names). */\n\tpublic List<Set<Rule>> listOfRecursiveCycles = new ArrayList<Set<Rule>>();\n\n\t/** Which rule start states have we visited while looking for a single\n\t * \tleft-recursion check?\n\t */\n\tSet<RuleStartState> rulesVisitedPerRuleCheck = new HashSet<RuleStartState>();\n\n\tpublic LeftRecursionDetector(Grammar g, ATN atn) {\n\t\tthis.g = g;\n\t\tthis.atn = atn;\n\t}\n\n\tpublic void check() {\n\t\tfor (RuleStartState start : atn.ruleToStartState) {\n\t\t\t//System.out.print(\"check \"+start.rule.name);\n\t\t\trulesVisitedPerRuleCheck.clear();\n\t\t\trulesVisitedPerRuleCheck.add(start);\n\t\t\t//FASerializer ser = new FASerializer(atn.g, start);\n\t\t\t//System.out.print(\":\\n\"+ser+\"\\n\");\n\n\t\t\tcheck(g.getRule(start.ruleIndex), start, new HashSet<ATNState>());\n\t\t}\n\t\t//System.out.println(\"cycles=\"+listOfRecursiveCycles);\n\t\tif ( !listOfRecursiveCycles.isEmpty() ) {\n\t\t\tg.tool.errMgr.leftRecursionCycles(g.fileName, listOfRecursiveCycles);\n\t\t}\n\t}\n\n\t/** From state s, look for any transition to a rule that is currently\n\t *  being traced.  When tracing r, visitedPerRuleCheck has r\n\t *  initially.  If you reach a rule stop state, return but notify the\n\t *  invoking rule that the called rule is nullable. This implies that\n\t *  invoking rule must look at follow transition for that invoking state.\n\t *\n\t *  The visitedStates tracks visited states within a single rule so\n\t *  we can avoid epsilon-loop-induced infinite recursion here.  Keep\n\t *  filling the cycles in listOfRecursiveCycles and also, as a\n\t *  side-effect, set leftRecursiveRules.\n\t */\n\tpublic boolean check(Rule enclosingRule, ATNState s, Set<ATNState> visitedStates) {\n\t\tif ( s instanceof RuleStopState) return true;\n\t\tif ( visitedStates.contains(s) ) return false;\n\t\tvisitedStates.add(s);\n\n\t\t//System.out.println(\"visit \"+s);\n\t\tint n = s.getNumberOfTransitions();\n\t\tboolean stateReachesStopState = false;\n\t\tfor (int i=0; i<n; i++) {\n\t\t\tTransition t = s.transition(i);\n\t\t\tif ( t instanceof RuleTransition ) {\n\t\t\t\tRuleTransition rt = (RuleTransition) t;\n\t\t\t\tRule r = g.getRule(rt.ruleIndex);\n\t\t\t\tif ( rulesVisitedPerRuleCheck.contains((RuleStartState)t.target) ) {\n\t\t\t\t\taddRulesToCycle(enclosingRule, r);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// must visit if not already visited; mark target, pop when done\n\t\t\t\t\trulesVisitedPerRuleCheck.add((RuleStartState)t.target);\n\t\t\t\t\t// send new visitedStates set per rule invocation\n\t\t\t\t\tboolean nullable = check(r, t.target, new HashSet<ATNState>());\n\t\t\t\t\t// we're back from visiting that rule\n\t\t\t\t\trulesVisitedPerRuleCheck.remove((RuleStartState)t.target);\n\t\t\t\t\tif ( nullable ) {\n\t\t\t\t\t\tstateReachesStopState |= check(enclosingRule, rt.followState, visitedStates);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( t.isEpsilon() ) {\n\t\t\t\tstateReachesStopState |= check(enclosingRule, t.target, visitedStates);\n\t\t\t}\n\t\t\t// else ignore non-epsilon transitions\n\t\t}\n\t\treturn stateReachesStopState;\n\t}\n\n\t/** enclosingRule calls targetRule. Find the cycle containing\n\t *  the target and add the caller.  Find the cycle containing the caller\n\t *  and add the target.  If no cycles contain either, then create a new\n\t *  cycle.\n\t */\n\tprotected void addRulesToCycle(Rule enclosingRule, Rule targetRule) {\n\t\t//System.err.println(\"left-recursion to \"+targetRule.name+\" from \"+enclosingRule.name);\n\t\tboolean foundCycle = false;\n\t\tfor (Set<Rule> rulesInCycle : listOfRecursiveCycles) {\n\t\t\t// ensure both rules are in same cycle\n\t\t\tif (rulesInCycle.contains(targetRule)) {\n\t\t\t\trulesInCycle.add(enclosingRule);\n\t\t\t\tfoundCycle = true;\n\t\t\t}\n\t\t\tif (rulesInCycle.contains(enclosingRule)) {\n\t\t\t\trulesInCycle.add(targetRule);\n\t\t\t\tfoundCycle = true;\n\t\t\t}\n\t\t}\n\t\tif ( !foundCycle ) {\n\t\t\tSet<Rule> cycle = new OrderedHashSet<Rule>();\n\t\t\tcycle.add(targetRule);\n\t\t\tcycle.add(enclosingRule);\n\t\t\tlistOfRecursiveCycles.add(cycle);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/analysis/LeftRecursiveRuleAltInfo.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.analysis;\n\nimport org.antlr.v4.tool.ast.AltAST;\n\npublic class LeftRecursiveRuleAltInfo {\n\tpublic int altNum; // original alt index (from 1)\n\tpublic String leftRecursiveRuleRefLabel;\n\tpublic String altLabel;\n\tpublic final boolean isListLabel;\n\tpublic String altText;\n\tpublic AltAST altAST; // transformed ALT\n\tpublic AltAST originalAltAST;\n\tpublic int nextPrec;\n\n\tpublic LeftRecursiveRuleAltInfo(int altNum, String altText) {\n\t\tthis(altNum, altText, null, null, false, null);\n\t}\n\n\tpublic LeftRecursiveRuleAltInfo(int altNum, String altText,\n\t\t\t\t\t\t\t\t\tString leftRecursiveRuleRefLabel,\n\t\t\t\t\t\t\t\t\tString altLabel,\n\t\t\t\t\t\t\t\t\tboolean isListLabel,\n\t\t\t\t\t\t\t\t\tAltAST originalAltAST)\n\t{\n\t\tthis.altNum = altNum;\n\t\tthis.altText = altText;\n\t\tthis.leftRecursiveRuleRefLabel = leftRecursiveRuleRefLabel;\n\t\tthis.altLabel = altLabel;\n\t\tthis.isListLabel = isListLabel;\n\t\tthis.originalAltAST = originalAltAST;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/analysis/LeftRecursiveRuleAnalyzer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.analysis;\n\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.TokenStream;\nimport org.antlr.runtime.tree.CommonTreeNodeStream;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.parse.LeftRecursiveRuleWalker;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTWithOptions;\nimport org.antlr.v4.tool.ast.RuleRefAST;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STGroupFile;\n\nimport java.io.FileNotFoundException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** Using a tree walker on the rules, determine if a rule is directly left-recursive and if it follows\n *  our pattern.\n */\npublic class LeftRecursiveRuleAnalyzer extends LeftRecursiveRuleWalker {\n\tpublic static enum ASSOC { left, right }\n\n\tpublic Tool tool;\n\tpublic String ruleName;\n\tpublic LinkedHashMap<Integer, LeftRecursiveRuleAltInfo> binaryAlts = new LinkedHashMap<Integer, LeftRecursiveRuleAltInfo>();\n\tpublic LinkedHashMap<Integer, LeftRecursiveRuleAltInfo> ternaryAlts = new LinkedHashMap<Integer, LeftRecursiveRuleAltInfo>();\n\tpublic LinkedHashMap<Integer, LeftRecursiveRuleAltInfo> suffixAlts = new LinkedHashMap<Integer, LeftRecursiveRuleAltInfo>();\n\tpublic List<LeftRecursiveRuleAltInfo> prefixAndOtherAlts = new ArrayList<LeftRecursiveRuleAltInfo>();\n\n\t/** Pointer to ID node of ^(= ID element) */\n\tpublic List<Pair<GrammarAST,String>> leftRecursiveRuleRefLabels =\n\t\tnew ArrayList<Pair<GrammarAST,String>>();\n\n\t/** Tokens from which rule AST comes from */\n\tpublic final TokenStream tokenStream;\n\n\tpublic GrammarAST retvals;\n\n\tpublic final static STGroup recRuleTemplates;\n\tpublic final STGroup codegenTemplates;\n\tpublic final String language;\n\n\tpublic Map<Integer, ASSOC> altAssociativity = new HashMap<Integer, ASSOC>();\n\n\tstatic {\n\t\tString templateGroupFile = \"org/antlr/v4/tool/templates/LeftRecursiveRules.stg\";\n\t\trecRuleTemplates = new STGroupFile(templateGroupFile);\n\t\tif (!recRuleTemplates.isDefined(\"recRule\")) {\n\t\t\ttry {\n\t\t\t\tthrow new FileNotFoundException(\"can't find code generation templates: LeftRecursiveRules\");\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic LeftRecursiveRuleAnalyzer(GrammarAST ruleAST,\n\t\t\t\t\t\t\t\t\t Tool tool, String ruleName, String language)\n\t{\n\t\tsuper(new CommonTreeNodeStream(new GrammarASTAdaptor(ruleAST.token.getInputStream()), ruleAST));\n\t\tthis.tool = tool;\n\t\tthis.ruleName = ruleName;\n\t\tthis.language = language;\n\t\tthis.tokenStream = ruleAST.g.tokenStream;\n\t\tif (this.tokenStream == null) {\n\t\t\tthrow new NullPointerException(\"grammar must have a token stream\");\n\t\t}\n\n\t\t// use codegen to get correct language templates; that's it though\n\t\tcodegenTemplates = CodeGenerator.create(tool, null, language).getTemplates();\n\t}\n\n\t@Override\n\tpublic void setReturnValues(GrammarAST t) {\n\t\tretvals = t;\n\t}\n\n\t@Override\n\tpublic void setAltAssoc(AltAST t, int alt) {\n\t\tASSOC assoc = ASSOC.left;\n\t\tif ( t.getOptions()!=null ) {\n\t\t\tString a = t.getOptionString(\"assoc\");\n\t\t\tif ( a!=null ) {\n\t\t\t\tif ( a.equals(ASSOC.right.toString()) ) {\n\t\t\t\t\tassoc = ASSOC.right;\n\t\t\t\t}\n\t\t\t\telse if ( a.equals(ASSOC.left.toString()) ) {\n\t\t\t\t\tassoc = ASSOC.left;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION_VALUE, t.g.fileName, t.getOptionAST(\"assoc\").getToken(), \"assoc\", assoc);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ( altAssociativity.get(alt)!=null && altAssociativity.get(alt)!=assoc ) {\n\t\t\ttool.errMgr.toolError(ErrorType.INTERNAL_ERROR, \"all operators of alt \" + alt + \" of left-recursive rule must have same associativity\");\n\t\t}\n\t\taltAssociativity.put(alt, assoc);\n\n//\t\tSystem.out.println(\"setAltAssoc: op \" + alt + \": \" + t.getText()+\", assoc=\"+assoc);\n\t}\n\n\t@Override\n\tpublic void binaryAlt(AltAST originalAltTree, int alt) {\n\t\tAltAST altTree = (AltAST)originalAltTree.dupTree();\n\t\tString altLabel = altTree.altLabel!=null ? altTree.altLabel.getText() : null;\n\n\t\tString label = null;\n\t\tboolean isListLabel = false;\n\t\tGrammarAST lrlabel = stripLeftRecursion(altTree);\n\t\tif ( lrlabel!=null ) {\n\t\t\tlabel = lrlabel.getText();\n\t\t\tisListLabel = lrlabel.getParent().getType() == PLUS_ASSIGN;\n\t\t\tleftRecursiveRuleRefLabels.add(new Pair<GrammarAST,String>(lrlabel,altLabel));\n\t\t}\n\n\t\tstripAltLabel(altTree);\n\n\t\t// rewrite e to be e_[rec_arg]\n\t\tint nextPrec = nextPrecedence(alt);\n\t\taltTree = addPrecedenceArgToRules(altTree, nextPrec);\n\n\t\tstripAltLabel(altTree);\n\t\tString altText = text(altTree);\n\t\taltText = altText.trim();\n\t\tLeftRecursiveRuleAltInfo a =\n\t\t\tnew LeftRecursiveRuleAltInfo(alt, altText, label, altLabel, isListLabel, originalAltTree);\n\t\ta.nextPrec = nextPrec;\n\t\tbinaryAlts.put(alt, a);\n\t\t//System.out.println(\"binaryAlt \" + alt + \": \" + altText + \", rewrite=\" + rewriteText);\n\t}\n\n\t@Override\n\tpublic void prefixAlt(AltAST originalAltTree, int alt) {\n\t\tAltAST altTree = (AltAST)originalAltTree.dupTree();\n\t\tstripAltLabel(altTree);\n\n\t\tint nextPrec = precedence(alt);\n\t\t// rewrite e to be e_[prec]\n\t\taltTree = addPrecedenceArgToRules(altTree, nextPrec);\n\t\tString altText = text(altTree);\n\t\taltText = altText.trim();\n\t\tString altLabel = altTree.altLabel!=null ? altTree.altLabel.getText() : null;\n\t\tLeftRecursiveRuleAltInfo a =\n\t\t\tnew LeftRecursiveRuleAltInfo(alt, altText, null, altLabel, false, originalAltTree);\n\t\ta.nextPrec = nextPrec;\n\t\tprefixAndOtherAlts.add(a);\n\t\t//System.out.println(\"prefixAlt \" + alt + \": \" + altText + \", rewrite=\" + rewriteText);\n\t}\n\n\t@Override\n\tpublic void suffixAlt(AltAST originalAltTree, int alt) {\n\t\tAltAST altTree = (AltAST)originalAltTree.dupTree();\n\t\tString altLabel = altTree.altLabel!=null ? altTree.altLabel.getText() : null;\n\n\t\tString label = null;\n\t\tboolean isListLabel = false;\n\t\tGrammarAST lrlabel = stripLeftRecursion(altTree);\n\t\tif ( lrlabel!=null ) {\n\t\t\tlabel = lrlabel.getText();\n\t\t\tisListLabel = lrlabel.getParent().getType() == PLUS_ASSIGN;\n\t\t\tleftRecursiveRuleRefLabels.add(new Pair<GrammarAST,String>(lrlabel,altLabel));\n\t\t}\n\t\tstripAltLabel(altTree);\n\t\tString altText = text(altTree);\n\t\taltText = altText.trim();\n\t\tLeftRecursiveRuleAltInfo a =\n\t\t\tnew LeftRecursiveRuleAltInfo(alt, altText, label, altLabel, isListLabel, originalAltTree);\n\t\tsuffixAlts.put(alt, a);\n//\t\tSystem.out.println(\"suffixAlt \" + alt + \": \" + altText + \", rewrite=\" + rewriteText);\n\t}\n\n\t@Override\n\tpublic void otherAlt(AltAST originalAltTree, int alt) {\n\t\tAltAST altTree = (AltAST)originalAltTree.dupTree();\n\t\tstripAltLabel(altTree);\n\t\tString altText = text(altTree);\n\t\tString altLabel = altTree.altLabel!=null ? altTree.altLabel.getText() : null;\n\t\tLeftRecursiveRuleAltInfo a =\n\t\t\tnew LeftRecursiveRuleAltInfo(alt, altText, null, altLabel, false, originalAltTree);\n\t\t// We keep other alts with prefix alts since they are all added to the start of the generated rule, and\n\t\t// we want to retain any prior ordering between them\n\t\tprefixAndOtherAlts.add(a);\n//\t\tSystem.out.println(\"otherAlt \" + alt + \": \" + altText);\n\t}\n\n\t// --------- get transformed rules ----------------\n\n\tpublic String getArtificialOpPrecRule() {\n\t\tST ruleST = recRuleTemplates.getInstanceOf(\"recRule\");\n\t\truleST.add(\"ruleName\", ruleName);\n\t\tST ruleArgST = codegenTemplates.getInstanceOf(\"recRuleArg\");\n\t\truleST.add(\"argName\", ruleArgST);\n\t\tST setResultST = codegenTemplates.getInstanceOf(\"recRuleSetResultAction\");\n\t\truleST.add(\"setResultAction\", setResultST);\n\t\truleST.add(\"userRetvals\", retvals);\n\n\t\tLinkedHashMap<Integer, LeftRecursiveRuleAltInfo> opPrecRuleAlts = new LinkedHashMap<Integer, LeftRecursiveRuleAltInfo>();\n\t\topPrecRuleAlts.putAll(binaryAlts);\n\t\topPrecRuleAlts.putAll(ternaryAlts);\n\t\topPrecRuleAlts.putAll(suffixAlts);\n\t\tfor (int alt : opPrecRuleAlts.keySet()) {\n\t\t\tLeftRecursiveRuleAltInfo altInfo = opPrecRuleAlts.get(alt);\n\t\t\tST altST = recRuleTemplates.getInstanceOf(\"recRuleAlt\");\n\t\t\tST predST = codegenTemplates.getInstanceOf(\"recRuleAltPredicate\");\n\t\t\tpredST.add(\"opPrec\", precedence(alt));\n\t\t\tpredST.add(\"ruleName\", ruleName);\n\t\t\taltST.add(\"pred\", predST);\n\t\t\taltST.add(\"alt\", altInfo);\n\t\t\taltST.add(\"precOption\", LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME);\n\t\t\taltST.add(\"opPrec\", precedence(alt));\n\t\t\truleST.add(\"opAlts\", altST);\n\t\t}\n\n\t\truleST.add(\"primaryAlts\", prefixAndOtherAlts);\n\n\t\ttool.log(\"left-recursion\", ruleST.render());\n\n\t\treturn ruleST.render();\n\t}\n\n\tpublic AltAST addPrecedenceArgToRules(AltAST t, int prec) {\n\t\tif ( t==null ) return null;\n\t\t// get all top-level rule refs from ALT\n\t\tList<GrammarAST> outerAltRuleRefs = t.getNodesWithTypePreorderDFS(IntervalSet.of(RULE_REF));\n\t\tfor (GrammarAST x : outerAltRuleRefs) {\n\t\t\tRuleRefAST rref = (RuleRefAST)x;\n\t\t\tboolean recursive = rref.getText().equals(ruleName);\n\t\t\tboolean rightmost = rref == outerAltRuleRefs.get(outerAltRuleRefs.size()-1);\n\t\t\tif ( recursive && rightmost ) {\n\t\t\t\tGrammarAST dummyValueNode = new GrammarAST(new CommonToken(ANTLRParser.INT, \"\"+prec));\n\t\t\t\trref.setOption(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME, dummyValueNode);\n\t\t\t}\n\t\t}\n\t\treturn t;\n\t}\n\n\t/**\n\t * Match (RULE RULE_REF (BLOCK (ALT .*) (ALT RULE_REF[self] .*) (ALT .*)))\n\t * Match (RULE RULE_REF (BLOCK (ALT .*) (ALT (ASSIGN ID RULE_REF[self]) .*) (ALT .*)))\n\t */\n\tpublic static boolean hasImmediateRecursiveRuleRefs(GrammarAST t, String ruleName) {\n\t\tif ( t==null ) return false;\n\t\tGrammarAST blk = (GrammarAST)t.getFirstChildWithType(BLOCK);\n\t\tif ( blk==null ) return false;\n\t\tint n = blk.getChildren().size();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tGrammarAST alt = (GrammarAST)blk.getChildren().get(i);\n\t\t\tTree first = alt.getChild(0);\n\t\t\tif ( first==null ) continue;\n\t\t\tif (first.getType() == ELEMENT_OPTIONS) {\n\t\t\t\tfirst = alt.getChild(1);\n\t\t\t\tif (first == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( first.getType()==RULE_REF && first.getText().equals(ruleName) ) return true;\n\t\t\tTree rref = first.getChild(1);\n\t\t\tif ( rref!=null && rref.getType()==RULE_REF && rref.getText().equals(ruleName) ) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t// TODO: this strips the tree properly, but since text()\n\t// uses the start of stop token index and gets text from that\n\t// ineffectively ignores this routine.\n\tpublic GrammarAST stripLeftRecursion(GrammarAST altAST) {\n\t\tGrammarAST lrlabel=null;\n\t\tGrammarAST first = (GrammarAST)altAST.getChild(0);\n\t\tint leftRecurRuleIndex = 0;\n\t\tif ( first.getType() == ELEMENT_OPTIONS ) {\n\t\t\tfirst = (GrammarAST)altAST.getChild(1);\n\t\t\tleftRecurRuleIndex = 1;\n\t\t}\n\t\tTree rref = first.getChild(1); // if label=rule\n\t\tif ( (first.getType()==RULE_REF && first.getText().equals(ruleName)) ||\n\t\t\t (rref!=null && rref.getType()==RULE_REF && rref.getText().equals(ruleName)) )\n\t\t{\n\t\t\tif ( first.getType()==ASSIGN || first.getType()==PLUS_ASSIGN ) lrlabel = (GrammarAST)first.getChild(0);\n\t\t\t// remove rule ref (first child unless options present)\n\t\t\taltAST.deleteChild(leftRecurRuleIndex);\n\t\t\t// reset index so it prints properly (sets token range of\n\t\t\t// ALT to start to right of left recur rule we deleted)\n\t\t\tGrammarAST newFirstChild = (GrammarAST)altAST.getChild(leftRecurRuleIndex);\n\t\t\taltAST.setTokenStartIndex(newFirstChild.getTokenStartIndex());\n\t\t}\n\t\treturn lrlabel;\n\t}\n\n\t/** Strip last 2 tokens if → label; alter indexes in altAST */\n\tpublic void stripAltLabel(GrammarAST altAST) {\n\t\tint start = altAST.getTokenStartIndex();\n\t\tint stop = altAST.getTokenStopIndex();\n\t\t// find =>\n\t\tfor (int i=stop; i>=start; i--) {\n\t\t\tif ( tokenStream.get(i).getType()==POUND ) {\n\t\t\t\taltAST.setTokenStopIndex(i-1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic String text(GrammarAST t) {\n\t\tif ( t==null ) return \"\";\n\n\t\tint tokenStartIndex = t.getTokenStartIndex();\n\t\tint tokenStopIndex = t.getTokenStopIndex();\n\n\t\t// ignore tokens from existing option subtrees like:\n\t\t//    (ELEMENT_OPTIONS (= assoc right))\n\t\t//\n\t\t// element options are added back according to the values in the map\n\t\t// returned by getOptions().\n\t\tIntervalSet ignore = new IntervalSet();\n\t\tList<GrammarAST> optionsSubTrees = t.getNodesWithType(ELEMENT_OPTIONS);\n\t\tfor (GrammarAST sub : optionsSubTrees) {\n\t\t\tignore.add(sub.getTokenStartIndex(), sub.getTokenStopIndex());\n\t\t}\n\n\t\t// Individual labels appear as RULE_REF or TOKEN_REF tokens in the tree,\n\t\t// but do not support the ELEMENT_OPTIONS syntax. Make sure to not try\n\t\t// and add the tokenIndex option when writing these tokens.\n\t\tIntervalSet noOptions = new IntervalSet();\n\t\tList<GrammarAST> labeledSubTrees = t.getNodesWithType(new IntervalSet(ASSIGN,PLUS_ASSIGN));\n\t\tfor (GrammarAST sub : labeledSubTrees) {\n\t\t\tnoOptions.add(sub.getChild(0).getTokenStartIndex());\n\t\t}\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tint i=tokenStartIndex;\n\t\twhile ( i<=tokenStopIndex ) {\n\t\t\tif ( ignore.contains(i) ) {\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tToken tok = tokenStream.get(i);\n\n\t\t\t// Compute/hold any element options\n\t\t\tStringBuilder elementOptions = new StringBuilder();\n\t\t\tif (!noOptions.contains(i)) {\n\t\t\t\tGrammarAST node = t.getNodeWithTokenIndex(tok.getTokenIndex());\n\t\t\t\tif ( node!=null &&\n\t\t\t\t\t (tok.getType()==TOKEN_REF ||\n\t\t\t\t\t  tok.getType()==STRING_LITERAL ||\n\t\t\t\t\t  tok.getType()==RULE_REF) )\n\t\t\t\t{\n\t\t\t\t\telementOptions.append(\"tokenIndex=\").append(tok.getTokenIndex());\n\t\t\t\t}\n\n\t\t\t\tif ( node instanceof GrammarASTWithOptions ) {\n\t\t\t\t\tGrammarASTWithOptions o = (GrammarASTWithOptions)node;\n\t\t\t\t\tfor (Map.Entry<String, GrammarAST> entry : o.getOptions().entrySet()) {\n\t\t\t\t\t\tif (elementOptions.length() > 0) {\n\t\t\t\t\t\t\telementOptions.append(',');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\telementOptions.append(entry.getKey());\n\t\t\t\t\t\telementOptions.append('=');\n\t\t\t\t\t\telementOptions.append(entry.getValue().getText());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuf.append(tok.getText()); // add actual text of the current token to the rewritten alternative\n\t\t\ti++;                       // move to the next token\n\n\t\t\t// Are there args on a rule?\n\t\t\tif ( tok.getType()==RULE_REF && i<=tokenStopIndex && tokenStream.get(i).getType()==ARG_ACTION ) {\n\t\t\t\tbuf.append('['+tokenStream.get(i).getText()+']');\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\t// now that we have the actual element, we can add the options.\n\t\t\tif (elementOptions.length() > 0) {\n\t\t\t\tbuf.append('<').append(elementOptions).append('>');\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic int precedence(int alt) {\n\t\treturn numAlts-alt+1;\n\t}\n\n\t// Assumes left assoc\n\tpublic int nextPrecedence(int alt) {\n\t\tint p = precedence(alt);\n\t\tif ( altAssociativity.get(alt)==ASSOC.right ) return p;\n\t\treturn p+1;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"PrecRuleOperatorCollector{\" +\n\t\t\t   \"binaryAlts=\" + binaryAlts +\n\t\t\t   \", ternaryAlts=\" + ternaryAlts +\n\t\t\t   \", suffixAlts=\" + suffixAlts +\n\t\t\t   \", prefixAndOtherAlts=\" +prefixAndOtherAlts+\n\t\t\t   '}';\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/analysis/LeftRecursiveRuleTransformer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.analysis;\n\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.CommonTokenStream;\nimport org.antlr.runtime.ParserRuleReturnScope;\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.misc.OrderedHashMap;\nimport org.antlr.v4.parse.ANTLRLexer;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.parse.ScopeParser;\nimport org.antlr.v4.parse.ToolANTLRParser;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.semantics.BasicSemanticChecks;\nimport org.antlr.v4.semantics.RuleCollector;\nimport org.antlr.v4.tool.AttributeDict;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.GrammarTransformPipeline;\nimport org.antlr.v4.tool.LabelElementPair;\nimport org.antlr.v4.tool.LeftRecursiveRule;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTWithOptions;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\nimport org.antlr.v4.tool.ast.RuleAST;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\n/** Remove left-recursive rule refs, add precedence args to recursive rule refs.\n *  Rewrite rule so we can create ATN.\n *\n *  MODIFIES grammar AST in place.\n */\npublic class LeftRecursiveRuleTransformer {\n\tpublic static final String PRECEDENCE_OPTION_NAME = \"p\";\n\tpublic static final String TOKENINDEX_OPTION_NAME = \"tokenIndex\";\n\n\tpublic GrammarRootAST ast;\n\tpublic Collection<Rule> rules;\n\tpublic Grammar g;\n\tpublic Tool tool;\n\n\tpublic LeftRecursiveRuleTransformer(GrammarRootAST ast, Collection<Rule> rules, Grammar g) {\n\t\tthis.ast = ast;\n\t\tthis.rules = rules;\n\t\tthis.g = g;\n\t\tthis.tool = g.tool;\n\t}\n\n\tpublic void translateLeftRecursiveRules() {\n\t\tString language = g.getLanguage();\n\t\t// translate all recursive rules\n\t\tList<String> leftRecursiveRuleNames = new ArrayList<String>();\n\t\tfor (Rule r : rules) {\n\t\t\tif ( !Grammar.isTokenName(r.name) ) {\n\t\t\t\tif ( LeftRecursiveRuleAnalyzer.hasImmediateRecursiveRuleRefs(r.ast, r.name) ) {\n\t\t\t\t\tboolean fitsPattern = translateLeftRecursiveRule(ast, (LeftRecursiveRule)r, language);\n\t\t\t\t\tif ( fitsPattern ) {\n\t\t\t\t\t\tleftRecursiveRuleNames.add(r.name);\n\t\t\t\t\t}\n\t\t\t\t\telse { // better given an error that non-conforming left-recursion exists\n\t\t\t\t\t\ttool.errMgr.grammarError(ErrorType.NONCONFORMING_LR_RULE, g.fileName, ((GrammarAST)r.ast.getChild(0)).token, r.name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// update all refs to recursive rules to have [0] argument\n\t\tfor (GrammarAST r : ast.getNodesWithType(ANTLRParser.RULE_REF)) {\n\t\t\tif ( r.getParent().getType()==ANTLRParser.RULE ) continue; // must be rule def\n\t\t\tif ( ((GrammarASTWithOptions)r).getOptionString(PRECEDENCE_OPTION_NAME) != null ) continue; // already has arg; must be in rewritten rule\n\t\t\tif ( leftRecursiveRuleNames.contains(r.getText()) ) {\n\t\t\t\t// found ref to recursive rule not already rewritten with arg\n\t\t\t\t((GrammarASTWithOptions)r).setOption(PRECEDENCE_OPTION_NAME, (GrammarAST)new GrammarASTAdaptor().create(ANTLRParser.INT, \"0\"));\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Return true if successful */\n\tpublic boolean translateLeftRecursiveRule(GrammarRootAST ast,\n\t\t\t\t\t\t\t\t\t\t\t  LeftRecursiveRule r,\n\t\t\t\t\t\t\t\t\t\t\t  String language)\n\t{\n\t\t//tool.log(\"grammar\", ruleAST.toStringTree());\n\t\tGrammarAST prevRuleAST = r.ast;\n\t\tString ruleName = prevRuleAST.getChild(0).getText();\n\t\tLeftRecursiveRuleAnalyzer leftRecursiveRuleWalker =\n\t\t\tnew LeftRecursiveRuleAnalyzer(prevRuleAST, tool, ruleName, language);\n\t\tboolean isLeftRec;\n\t\ttry {\n//\t\t\tSystem.out.println(\"TESTING ---------------\\n\"+\n//\t\t\t\t\t\t\t   leftRecursiveRuleWalker.text(ruleAST));\n\t\t\tisLeftRec = leftRecursiveRuleWalker.rec_rule();\n\t\t}\n\t\tcatch (RecognitionException re) {\n\t\t\tisLeftRec = false; // didn't match; oh well\n\t\t}\n\t\tif ( !isLeftRec ) return false;\n\n\t\t// replace old rule's AST; first create text of altered rule\n\t\tGrammarAST RULES = (GrammarAST)ast.getFirstChildWithType(ANTLRParser.RULES);\n\t\tString newRuleText = leftRecursiveRuleWalker.getArtificialOpPrecRule();\n//\t\tSystem.out.println(\"created: \"+newRuleText);\n\t\t// now parse within the context of the grammar that originally created\n\t\t// the AST we are transforming. This could be an imported grammar so\n\t\t// we cannot just reference this.g because the role might come from\n\t\t// the imported grammar and not the root grammar (this.g)\n\t\tRuleAST t = parseArtificialRule(prevRuleAST.g, newRuleText);\n\n\t\t// reuse the name token from the original AST since it refers to the proper source location in the original grammar\n\t\t((GrammarAST)t.getChild(0)).token = ((GrammarAST)prevRuleAST.getChild(0)).getToken();\n\n\t\t// update grammar AST and set rule's AST.\n\t\tRULES.setChild(prevRuleAST.getChildIndex(), t);\n\t\tr.ast = t;\n\n\t\t// Reduce sets in newly created rule tree\n\t\tGrammarTransformPipeline transform = new GrammarTransformPipeline(g, g.tool);\n\t\ttransform.reduceBlocksToSets(r.ast);\n\t\ttransform.expandParameterizedLoops(r.ast);\n\n\t\t// Rerun semantic checks on the new rule\n\t\tRuleCollector ruleCollector = new RuleCollector(g);\n\t\truleCollector.visit(t, \"rule\");\n\t\tBasicSemanticChecks basics = new BasicSemanticChecks(g, ruleCollector);\n\t\t// disable the assoc element option checks because they are already\n\t\t// handled for the pre-transformed rule.\n\t\tbasics.checkAssocElementOption = false;\n\t\tbasics.visit(t, \"rule\");\n\n\t\t// track recursive alt info for codegen\n\t\tr.recPrimaryAlts = new ArrayList<LeftRecursiveRuleAltInfo>();\n\t\tr.recPrimaryAlts.addAll(leftRecursiveRuleWalker.prefixAndOtherAlts);\n\t\tif (r.recPrimaryAlts.isEmpty()) {\n\t\t\ttool.errMgr.grammarError(ErrorType.NO_NON_LR_ALTS, g.fileName, ((GrammarAST)r.ast.getChild(0)).getToken(), r.name);\n\t\t}\n\n\t\tr.recOpAlts = new OrderedHashMap<Integer, LeftRecursiveRuleAltInfo>();\n\t\tr.recOpAlts.putAll(leftRecursiveRuleWalker.binaryAlts);\n\t\tr.recOpAlts.putAll(leftRecursiveRuleWalker.ternaryAlts);\n\t\tr.recOpAlts.putAll(leftRecursiveRuleWalker.suffixAlts);\n\n\t\t// walk alt info records and set their altAST to point to appropriate ALT subtree\n\t\t// from freshly created AST\n\t\tsetAltASTPointers(r, t);\n\n\t\t// update Rule to just one alt and add prec alt\n\t\tActionAST arg = (ActionAST)r.ast.getFirstChildWithType(ANTLRParser.ARG_ACTION);\n\t\tif ( arg!=null ) {\n\t\t\tr.args = ScopeParser.parseTypedArgList(arg, arg.getText(), g);\n\t\t\tr.args.type = AttributeDict.DictType.ARG;\n\t\t\tr.args.ast = arg;\n\t\t\targ.resolver = r.alt[1]; // todo: isn't this Rule or something?\n\t\t}\n\n\t\t// define labels on recursive rule refs we delete; they don't point to nodes of course\n\t\t// these are so $label in action translation works\n\t\tfor (Pair<GrammarAST,String> pair : leftRecursiveRuleWalker.leftRecursiveRuleRefLabels) {\n\t\t\tGrammarAST labelNode = pair.a;\n\t\t\tGrammarAST labelOpNode = (GrammarAST)labelNode.getParent();\n\t\t\tGrammarAST elementNode = (GrammarAST)labelOpNode.getChild(1);\n\t\t\tLabelElementPair lp = new LabelElementPair(g, labelNode, elementNode, labelOpNode.getType());\n\t\t\tr.alt[1].labelDefs.map(labelNode.getText(), lp);\n\t\t}\n\t\t// copy to rule from walker\n\t\tr.leftRecursiveRuleRefLabels = leftRecursiveRuleWalker.leftRecursiveRuleRefLabels;\n\n\t\ttool.log(\"grammar\", \"added: \"+t.toStringTree());\n\t\treturn true;\n\t}\n\n\tpublic RuleAST parseArtificialRule(final Grammar g, String ruleText) {\n\t\tANTLRLexer lexer = new ANTLRLexer(new ANTLRStringStream(ruleText));\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(lexer.getCharStream());\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\t\tlexer.tokens = tokens;\n\t\tToolANTLRParser p = new ToolANTLRParser(tokens, tool);\n\t\tp.setTreeAdaptor(adaptor);\n\t\tToken ruleStart = null;\n\t\ttry {\n\t\t\tParserRuleReturnScope r = p.rule();\n\t\t\tRuleAST tree = (RuleAST)r.getTree();\n\t\t\truleStart = (Token)r.getStart();\n\t\t\tGrammarTransformPipeline.setGrammarPtr(g, tree);\n\t\t\tGrammarTransformPipeline.augmentTokensWithOriginalPosition(g, tree);\n\t\t\treturn tree;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\ttool.errMgr.toolError(ErrorType.INTERNAL_ERROR,\n\t\t\t\t\t\t\t\t  e,\n\t\t\t\t\t\t\t\t  ruleStart,\n\t\t\t\t\t\t\t\t  \"error parsing rule created during left-recursion detection: \"+ruleText);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * <pre>\n\t * (RULE e int _p (returns int v)\n\t * \t(BLOCK\n\t * \t  (ALT\n\t * \t\t(BLOCK\n\t * \t\t\t(ALT INT {$v = $INT.int;})\n\t * \t\t\t(ALT '(' (= x e) ')' {$v = $x.v;})\n\t * \t\t\t(ALT ID))\n\t * \t\t(* (BLOCK\n\t *\t\t\t(OPTIONS ...)\n\t * \t\t\t(ALT {7 &gt;= $_p}? '*' (= b e) {$v = $a.v * $b.v;})\n\t * \t\t\t(ALT {6 &gt;= $_p}? '+' (= b e) {$v = $a.v + $b.v;})\n\t * \t\t\t(ALT {3 &gt;= $_p}? '++') (ALT {2 &gt;= $_p}? '--'))))))\n\t * </pre>\n\t */\n\tpublic void setAltASTPointers(LeftRecursiveRule r, RuleAST t) {\n//\t\tSystem.out.println(\"RULE: \"+t.toStringTree());\n\t\tBlockAST ruleBlk = (BlockAST)t.getFirstChildWithType(ANTLRParser.BLOCK);\n\t\tAltAST mainAlt = (AltAST)ruleBlk.getChild(0);\n\t\tBlockAST primaryBlk = (BlockAST)mainAlt.getChild(0);\n\t\tBlockAST opsBlk = (BlockAST)mainAlt.getChild(1).getChild(0); // (* BLOCK ...)\n\t\tfor (int i = 0; i < r.recPrimaryAlts.size(); i++) {\n\t\t\tLeftRecursiveRuleAltInfo altInfo = r.recPrimaryAlts.get(i);\n\t\t\taltInfo.altAST = (AltAST)primaryBlk.getChild(i);\n\t\t\taltInfo.altAST.leftRecursiveAltInfo = altInfo;\n\t\t\taltInfo.originalAltAST.leftRecursiveAltInfo = altInfo;\n//\t\t\taltInfo.originalAltAST.parent = altInfo.altAST.parent;\n//\t\t\tSystem.out.println(altInfo.altAST.toStringTree());\n\t\t}\n\t\tfor (int i = 0; i < r.recOpAlts.size(); i++) {\n\t\t\tLeftRecursiveRuleAltInfo altInfo = r.recOpAlts.getElement(i);\n\t\t\taltInfo.altAST = (AltAST)opsBlk.getChild(i);\n\t\t\taltInfo.altAST.leftRecursiveAltInfo = altInfo;\n\t\t\taltInfo.originalAltAST.leftRecursiveAltInfo = altInfo;\n//\t\t\taltInfo.originalAltAST.parent = altInfo.altAST.parent;\n//\t\t\tSystem.out.println(altInfo.altAST.toStringTree());\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/ATNFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.automata;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.PredAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.List;\n\npublic interface ATNFactory {\n\t/** A pair of states pointing to the left/right (start and end) states of a\n\t *  state submachine.  Used to build ATNs.\n\t */\n\tpublic static class Handle {\n\t\tpublic ATNState left;\n\t\tpublic ATNState right;\n\n\t\tpublic Handle(ATNState left, ATNState right) {\n\t\t\tthis.left = left;\n\t\t\tthis.right = right;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"(\"+left+\",\"+right+\")\";\n\t\t}\n\t}\n\n\n\tATN createATN();\n\n\tvoid setCurrentRuleName(String name);\n\n\tvoid setCurrentOuterAlt(int alt);\n\n\n\tHandle rule(GrammarAST ruleAST, String name, Handle blk);\n\n\n\tATNState newState();\n\n\n\tHandle label(Handle t);\n\n\n\tHandle listLabel(Handle t);\n\n\n\tHandle tokenRef(TerminalAST node);\n\n\n\tHandle set(GrammarAST associatedAST, List<GrammarAST> alts, boolean invert);\n\n\n\tHandle charSetLiteral(GrammarAST charSetAST);\n\n\n\tHandle range(GrammarAST a, GrammarAST b);\n\n\t/** For a non-lexer, just build a simple token reference atom.\n\t *  For a lexer, a string is a sequence of char to match.  That is,\n\t *  \"fog\" is treated as 'f' 'o' 'g' not as a single transition in\n\t *  the DFA.  Machine== o-'f'-&gt;o-'o'-&gt;o-'g'-&gt;o and has n+1 states\n\t *  for n characters.\n\t */\n\n\tHandle stringLiteral(TerminalAST stringLiteralAST);\n\n\t/** For reference to rule r, build\n\t *\n\t *  o-e-&gt;(r)  o\n\t *\n\t *  where (r) is the start of rule r and the trailing o is not linked\n\t *  to from rule ref state directly (it's done thru the transition(0)\n\t *  RuleClosureTransition.\n\t *\n\t *  If the rule r is just a list of tokens, it's block will be just\n\t *  a set on an edge o-&gt;o-&gt;o-set-&gt;o-&gt;o-&gt;o, could inline it rather than doing\n\t *  the rule reference, but i'm not doing this yet as I'm not sure\n\t *  it would help much in the ATN-&gt;DFA construction.\n\t *\n\t *  TODO add to codegen: collapse alt blks that are sets into single matchSet\n\t * @param node\n\t */\n\n\tHandle ruleRef(GrammarAST node);\n\n\t/** From an empty alternative build Grip o-e-&gt;o */\n\n\tHandle epsilon(GrammarAST node);\n\n\t/** Build what amounts to an epsilon transition with a semantic\n\t *  predicate action.  The pred is a pointer into the AST of\n\t *  the SEMPRED token.\n\t */\n\n\tHandle sempred(PredAST pred);\n\n\t/** Build what amounts to an epsilon transition with an action.\n\t *  The action goes into ATN though it is ignored during analysis.\n\t */\n\n\tHandle action(ActionAST action);\n\n\n\tHandle action(String action);\n\n\n\tHandle alt(List<Handle> els);\n\n\t/** From A|B|..|Z alternative block build\n     *\n     *  o-&gt;o-A-&gt;o-&gt;o (last ATNState is blockEndATNState pointed to by all alts)\n     *  |          ^\n     *  o-&gt;o-B-&gt;o--|\n     *  |          |\n     *  ...        |\n     *  |          |\n     *  o-&gt;o-Z-&gt;o--|\n     *\n     *  So every alternative gets begin ATNState connected by epsilon\n     *  and every alt right side points at a block end ATNState.  There is a\n     *  new ATNState in the ATNState in the Grip for each alt plus one for the\n     *  end ATNState.\n     *\n     *  Special case: only one alternative: don't make a block with alt\n     *  begin/end.\n     *\n     *  Special case: if just a list of tokens/chars/sets, then collapse\n     *  to a single edge'd o-set-&gt;o graph.\n     *\n     *  Set alt number (1..n) in the left-Transition ATNState.\n     */\n\n\tHandle block(BlockAST blockAST, GrammarAST ebnfRoot, List<Handle> alternativeGrips);\n\n//\tHandle notBlock(GrammarAST blockAST, Handle set);\n\n\t/** From (A)? build either:\n\t *\n\t *  o--A-&gt;o\n\t *  |     ^\n\t *  o----&gt;|\n\t *\n\t *  or, if A is a block, just add an empty alt to the end of the block\n\t */\n\n\tHandle optional(GrammarAST optAST, Handle blk);\n\n\t/** From (A)+ build\n\t *\n\t *     |---|    (Transition 2 from A.right points at alt 1)\n\t *     v   |    (follow of loop is Transition 1)\n\t *  o-&gt;o-A-o-&gt;o\n\t *\n\t *  Meaning that the last ATNState in A points back to A's left Transition ATNState\n\t *  and we add a new begin/end ATNState.  A can be single alternative or\n\t *  multiple.\n\t *\n\t *  During analysis we'll call the follow link (transition 1) alt n+1 for\n\t *  an n-alt A block.\n\t */\n\n\tHandle plus(GrammarAST plusAST, Handle blk);\n\n\t/** From (A)* build\n\t *\n\t *     |---|\n\t *     v   |\n\t *  o-&gt;o-A-o--o (Transition 2 from block end points at alt 1; follow is Transition 1)\n\t *  |         ^\n\t *  o---------| (optional branch is 2nd alt of optional block containing A+)\n\t *\n\t *  Meaning that the last (end) ATNState in A points back to A's\n\t *  left side ATNState and we add 3 new ATNStates (the\n\t *  optional branch is built just like an optional subrule).\n\t *  See the Aplus() method for more on the loop back Transition.\n\t *  The new node on right edge is set to RIGHT_EDGE_OF_CLOSURE so we\n\t *  can detect nested (A*)* loops and insert an extra node.  Previously,\n\t *  two blocks shared same EOB node.\n\t *\n\t *  There are 2 or 3 decision points in a A*.  If A is not a block (i.e.,\n\t *  it only has one alt), then there are two decisions: the optional bypass\n\t *  and then loopback.  If A is a block of alts, then there are three\n\t *  decisions: bypass, loopback, and A's decision point.\n\t *\n\t *  Note that the optional bypass must be outside the loop as (A|B)* is\n\t *  not the same thing as (A|B|)+.\n\t *\n\t *  This is an accurate ATN representation of the meaning of (A)*, but\n\t *  for generating code, I don't need a DFA for the optional branch by\n\t *  virtue of how I generate code.  The exit-loopback-branch decision\n\t *  is sufficient to let me make an appropriate enter, exit, loop\n\t *  determination.  See codegen.g\n\t */\n\n\tHandle star(GrammarAST starAST, Handle blk);\n\n\t/** Build an atom with all possible values in its label */\n\n\tHandle wildcard(GrammarAST associatedAST);\n\n\n\tHandle lexerAltCommands(Handle alt, Handle cmds);\n\n\n\tHandle lexerCallCommand(GrammarAST ID, GrammarAST arg);\n\n\n\tHandle lexerCommand(GrammarAST ID);\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/ATNOptimizer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.automata;\n\nimport org.antlr.v4.misc.CharSupport;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.AtomTransition;\nimport org.antlr.v4.runtime.atn.BlockEndState;\nimport org.antlr.v4.runtime.atn.CodePointTransitions;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.EpsilonTransition;\nimport org.antlr.v4.runtime.atn.NotSetTransition;\nimport org.antlr.v4.runtime.atn.RangeTransition;\nimport org.antlr.v4.runtime.atn.SetTransition;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class ATNOptimizer {\n\n\tpublic static void optimize(Grammar g, ATN atn) {\n\t\toptimizeSets(g, atn);\n\t\toptimizeStates(atn);\n\t}\n\n\tprivate static void optimizeSets(Grammar g, ATN atn) {\n\t\tif (g.isParser()) {\n\t\t\t// parser codegen doesn't currently support SetTransition\n\t\t\treturn;\n\t\t}\n\n\t\tint removedStates = 0;\n\t\tList<DecisionState> decisions = atn.decisionToState;\n\t\tfor (DecisionState decision : decisions) {\n\t\t\tif (decision.ruleIndex >= 0) {\n\t\t\t\tRule rule = g.getRule(decision.ruleIndex);\n\t\t\t\tif (Character.isLowerCase(rule.name.charAt(0))) {\n\t\t\t\t\t// parser codegen doesn't currently support SetTransition\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tIntervalSet setTransitions = new IntervalSet();\n\t\t\tfor (int i = 0; i < decision.getNumberOfTransitions(); i++) {\n\t\t\t\tTransition epsTransition = decision.transition(i);\n\t\t\t\tif (!(epsTransition instanceof EpsilonTransition)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (epsTransition.target.getNumberOfTransitions() != 1) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tTransition transition = epsTransition.target.transition(0);\n\t\t\t\tif (!(transition.target instanceof BlockEndState)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (transition instanceof NotSetTransition) {\n\t\t\t\t\t// TODO: not yet implemented\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (transition instanceof AtomTransition\n\t\t\t\t\t|| transition instanceof RangeTransition\n\t\t\t\t\t|| transition instanceof SetTransition)\n\t\t\t\t{\n\t\t\t\t\tsetTransitions.add(i);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// due to min alt resolution policies, can only collapse sequential alts\n\t\t\tfor (int i = setTransitions.getIntervals().size() - 1; i >= 0; i--) {\n\t\t\t\tInterval interval = setTransitions.getIntervals().get(i);\n\t\t\t\tif (interval.length() <= 1) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tATNState blockEndState = decision.transition(interval.a).target.transition(0).target;\n\t\t\t\tIntervalSet matchSet = new IntervalSet();\n\t\t\t\tfor (int j = interval.a; j <= interval.b; j++) {\n\t\t\t\t\tTransition matchTransition = decision.transition(j).target.transition(0);\n\t\t\t\t\tif (matchTransition instanceof NotSetTransition) {\n\t\t\t\t\t\tthrow new UnsupportedOperationException(\"Not yet implemented.\");\n\t\t\t\t\t}\n\t\t\t\t\tIntervalSet set =  matchTransition.label();\n\t\t\t\t\tList<Interval> intervals = set.getIntervals();\n\t\t\t\t\tint n = intervals.size();\n\t\t\t\t\tfor (int k = 0; k < n; k++) {\n\t\t\t\t\t\tInterval setInterval = intervals.get(k);\n\t\t\t\t\t\tint a = setInterval.a;\n\t\t\t\t\t\tint b = setInterval.b;\n\t\t\t\t\t\tif (a != -1 && b != -1) {\n\t\t\t\t\t\t\tfor (int v = a; v <= b; v++) {\n\t\t\t\t\t\t\t\tif (matchSet.contains(v)) {\n\t\t\t\t\t\t\t\t\t// TODO: Token is missing (i.e. position in source is not displayed).\n\t\t\t\t\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.CHARACTERS_COLLISION_IN_SET, g.fileName,\n\t\t\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t\t\t\tCharSupport.getANTLRCharLiteralForChar(v),\n\t\t\t\t\t\t\t\t\t\t\tCharSupport.getIntervalSetEscapedString(matchSet));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tmatchSet.addAll(set);\n\t\t\t\t}\n\n\t\t\t\tTransition newTransition;\n\t\t\t\tif (matchSet.getIntervals().size() == 1) {\n\t\t\t\t\tif (matchSet.size() == 1) {\n\t\t\t\t\t\tnewTransition = CodePointTransitions.createWithCodePoint(blockEndState, matchSet.getMinElement());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tInterval matchInterval = matchSet.getIntervals().get(0);\n\t\t\t\t\t\tnewTransition = CodePointTransitions.createWithCodePointRange(blockEndState, matchInterval.a, matchInterval.b);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnewTransition = new SetTransition(blockEndState, matchSet);\n\t\t\t\t}\n\n\t\t\t\tdecision.transition(interval.a).target.setTransition(0, newTransition);\n\t\t\t\tfor (int j = interval.a + 1; j <= interval.b; j++) {\n\t\t\t\t\tTransition removed = decision.removeTransition(interval.a + 1);\n\t\t\t\t\tatn.removeState(removed.target);\n\t\t\t\t\tremovedStates++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n//\t\tSystem.out.println(\"ATN optimizer removed \" + removedStates + \" states by collapsing sets.\");\n\t}\n\n\tprivate static void optimizeStates(ATN atn) {\n//\t\tSystem.out.println(atn.states);\n\t\tList<ATNState> compressed = new ArrayList<ATNState>();\n\t\tint i = 0; // new state number\n\t\tfor (ATNState s : atn.states) {\n\t\t\tif ( s!=null ) {\n\t\t\t\tcompressed.add(s);\n\t\t\t\ts.stateNumber = i; // reset state number as we shift to new position\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n//\t\tSystem.out.println(compressed);\n//\t\tSystem.out.println(\"ATN optimizer removed \" + (atn.states.size() - compressed.size()) + \" null states.\");\n\t\tatn.states.clear();\n\t\tatn.states.addAll(compressed);\n\t}\n\n\tprivate ATNOptimizer() {\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/ATNPrinter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.automata;\n\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.ActionTransition;\nimport org.antlr.v4.runtime.atn.AtomTransition;\nimport org.antlr.v4.runtime.atn.BlockEndState;\nimport org.antlr.v4.runtime.atn.BlockStartState;\nimport org.antlr.v4.runtime.atn.EpsilonTransition;\nimport org.antlr.v4.runtime.atn.NotSetTransition;\nimport org.antlr.v4.runtime.atn.PlusBlockStartState;\nimport org.antlr.v4.runtime.atn.PlusLoopbackState;\nimport org.antlr.v4.runtime.atn.RuleStartState;\nimport org.antlr.v4.runtime.atn.RuleStopState;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.SetTransition;\nimport org.antlr.v4.runtime.atn.StarBlockStartState;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.runtime.atn.StarLoopbackState;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.tool.Grammar;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n/** An ATN walker that knows how to dump them to serialized strings. */\npublic class ATNPrinter {\n\tList<ATNState> work;\n\tSet<ATNState> marked;\n\tGrammar g;\n\tATNState start;\n\n\tpublic ATNPrinter(Grammar g, ATNState start) {\n\t\tthis.g = g;\n\t\tthis.start = start;\n\t}\n\n\tpublic String asString() {\n\t\tif ( start==null ) return null;\n\t\tmarked = new HashSet<ATNState>();\n\n\t\twork = new ArrayList<ATNState>();\n\t\twork.add(start);\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tATNState s;\n\n\t\twhile ( !work.isEmpty() ) {\n\t\t\ts = work.remove(0);\n\t\t\tif ( marked.contains(s) ) continue;\n\t\t\tint n = s.getNumberOfTransitions();\n//\t\t\tSystem.out.println(\"visit \"+s+\"; edges=\"+n);\n\t\t\tmarked.add(s);\n\t\t\tfor (int i=0; i<n; i++) {\n\t\t\t\tTransition t = s.transition(i);\n\t\t\t\tif ( !(s instanceof RuleStopState) ) { // don't add follow states to work\n\t\t\t\t\tif ( t instanceof RuleTransition ) work.add(((RuleTransition)t).followState);\n\t\t\t\t\telse work.add( t.target );\n\t\t\t\t}\n\t\t\t\tbuf.append(getStateString(s));\n\t\t\t\tif ( t instanceof EpsilonTransition ) {\n\t\t\t\t\tbuf.append(\"->\").append(getStateString(t.target)).append('\\n');\n\t\t\t\t}\n\t\t\t\telse if ( t instanceof RuleTransition ) {\n\t\t\t\t\tbuf.append(\"-\").append(g.getRule(((RuleTransition)t).ruleIndex).name).append(\"->\").append(getStateString(t.target)).append('\\n');\n\t\t\t\t}\n\t\t\t\telse if ( t instanceof ActionTransition ) {\n\t\t\t\t\tActionTransition a = (ActionTransition)t;\n\t\t\t\t\tbuf.append(\"-\").append(a.toString()).append(\"->\").append(getStateString(t.target)).append('\\n');\n\t\t\t\t}\n\t\t\t\telse if ( t instanceof SetTransition ) {\n\t\t\t\t\tSetTransition st = (SetTransition)t;\n\t\t\t\t\tboolean not = st instanceof NotSetTransition;\n\t\t\t\t\tif ( g.isLexer() ) {\n\t\t\t\t\t\tbuf.append(\"-\").append(not?\"~\":\"\").append(st.toString()).append(\"->\").append(getStateString(t.target)).append('\\n');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tbuf.append(\"-\").append(not?\"~\":\"\").append(st.label().toString(g.getVocabulary())).append(\"->\").append(getStateString(t.target)).append('\\n');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( t instanceof AtomTransition ) {\n\t\t\t\t\tAtomTransition a = (AtomTransition)t;\n\t\t\t\t\tString label = g.getTokenDisplayName(a.label);\n\t\t\t\t\tbuf.append(\"-\").append(label).append(\"->\").append(getStateString(t.target)).append('\\n');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbuf.append(\"-\").append(t.toString()).append(\"->\").append(getStateString(t.target)).append('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tString getStateString(ATNState s) {\n\t\tint n = s.stateNumber;\n\t\tString stateStr = \"s\"+n;\n\t\tif ( s instanceof StarBlockStartState ) stateStr = \"StarBlockStart_\"+n;\n\t\telse if ( s instanceof PlusBlockStartState ) stateStr = \"PlusBlockStart_\"+n;\n\t\telse if ( s instanceof BlockStartState) stateStr = \"BlockStart_\"+n;\n\t\telse if ( s instanceof BlockEndState ) stateStr = \"BlockEnd_\"+n;\n\t\telse if ( s instanceof RuleStartState) stateStr = \"RuleStart_\"+g.getRule(s.ruleIndex).name+\"_\"+n;\n\t\telse if ( s instanceof RuleStopState ) stateStr = \"RuleStop_\"+g.getRule(s.ruleIndex).name+\"_\"+n;\n\t\telse if ( s instanceof PlusLoopbackState) stateStr = \"PlusLoopBack_\"+n;\n\t\telse if ( s instanceof StarLoopbackState) stateStr = \"StarLoopBack_\"+n;\n\t\telse if ( s instanceof StarLoopEntryState) stateStr = \"StarLoopEntry_\"+n;\n\t\treturn stateStr;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/ATNVisitor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.automata;\n\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.Transition;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\n/** A simple visitor that walks everywhere it can go starting from s,\n *  without going into an infinite cycle. Override and implement\n *  visitState() to provide functionality.\n */\npublic class ATNVisitor {\n\tpublic void visit(ATNState s) {\n\t\tvisit_(s, new HashSet<Integer>());\n\t}\n\n\tpublic void visit_(ATNState s, Set<Integer> visited) {\n\t\tif ( !visited.add(s.stateNumber) ) return;\n\t\tvisited.add(s.stateNumber);\n\n\t\tvisitState(s);\n\t\tint n = s.getNumberOfTransitions();\n\t\tfor (int i=0; i<n; i++) {\n\t\t\tTransition t = s.transition(i);\n\t\t\tvisit_(t.target, visited);\n\t\t}\n\t}\n\n\tpublic void visitState(ATNState s) { }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/CharactersDataCheckStatus.java",
    "content": "package org.antlr.v4.automata;\n\npublic class CharactersDataCheckStatus {\n\tpublic final boolean collision;\n\tpublic final boolean notImpliedCharacters;\n\n\tpublic CharactersDataCheckStatus(boolean collision, boolean notImpliedCharacters) {\n\t\tthis.collision = collision;\n\t\tthis.notImpliedCharacters = notImpliedCharacters;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/LexerATNFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.automata;\n\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.tree.CommonTree;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.misc.CharSupport;\nimport org.antlr.v4.misc.EscapeSequenceParsing;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.IntStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.atn.*;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.RangeAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Set;\n\npublic class LexerATNFactory extends ParserATNFactory {\n\tpublic STGroup codegenTemplates;\n\n\t/**\n\t * Provides a map of names of predefined constants which are likely to\n\t * appear as the argument for lexer commands. These names would be resolved\n\t * by the Java compiler for lexer commands that are translated to embedded\n\t * actions, but are required during code generation for creating\n\t * {@link LexerAction} instances that are usable by a lexer interpreter.\n\t */\n\tpublic static final Map<String, Integer> COMMON_CONSTANTS = new HashMap<String, Integer>();\n\tstatic {\n\t\tCOMMON_CONSTANTS.put(\"HIDDEN\", Lexer.HIDDEN);\n\t\tCOMMON_CONSTANTS.put(\"DEFAULT_TOKEN_CHANNEL\", Lexer.DEFAULT_TOKEN_CHANNEL);\n\t\tCOMMON_CONSTANTS.put(\"DEFAULT_MODE\", Lexer.DEFAULT_MODE);\n\t\tCOMMON_CONSTANTS.put(\"SKIP\", Lexer.SKIP);\n\t\tCOMMON_CONSTANTS.put(\"MORE\", Lexer.MORE);\n\t\tCOMMON_CONSTANTS.put(\"EOF\", Lexer.EOF);\n\t\tCOMMON_CONSTANTS.put(\"MAX_CHAR_VALUE\", Lexer.MAX_CHAR_VALUE);\n\t\tCOMMON_CONSTANTS.put(\"MIN_CHAR_VALUE\", Lexer.MIN_CHAR_VALUE);\n\t}\n\n\tprivate final List<String> ruleCommands = new ArrayList<String>();\n\n\t/**\n\t * Maps from an action index to a {@link LexerAction} object.\n\t */\n\tprotected Map<Integer, LexerAction> indexToActionMap = new HashMap<Integer, LexerAction>();\n\t/**\n\t * Maps from a {@link LexerAction} object to the action index.\n\t */\n\tprotected Map<LexerAction, Integer> actionToIndexMap = new HashMap<LexerAction, Integer>();\n\n\tpublic LexerATNFactory(LexerGrammar g) {\n\t\tthis(g, null);\n\t}\n\n\tpublic LexerATNFactory(LexerGrammar g, CodeGenerator codeGenerator) {\n\t\tsuper(g);\n\t\t// use codegen to get correct language templates for lexer commands\n\t\tcodegenTemplates = (codeGenerator == null ? CodeGenerator.create(g) : codeGenerator).getTemplates();\n\t}\n\n\tpublic static Set<String> getCommonConstants() {\n\t\treturn COMMON_CONSTANTS.keySet();\n\t}\n\n\t@Override\n\tpublic ATN createATN() {\n\t\t// BUILD ALL START STATES (ONE PER MODE)\n\t\tSet<String> modes = ((LexerGrammar) g).modes.keySet();\n\t\tfor (String modeName : modes) {\n\t\t\t// create s0, start state; implied Tokens rule node\n\t\t\tTokensStartState startState =\n\t\t\t\tnewState(TokensStartState.class, null);\n\t\t\tatn.modeNameToStartState.put(modeName, startState);\n\t\t\tatn.modeToStartState.add(startState);\n\t\t\tatn.defineDecisionState(startState);\n\t\t}\n\n\t\t// INIT ACTION, RULE->TOKEN_TYPE MAP\n\t\tatn.ruleToTokenType = new int[g.rules.size()];\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tatn.ruleToTokenType[r.index] = g.getTokenType(r.name);\n\t\t}\n\n\t\t// CREATE ATN FOR EACH RULE\n\t\t_createATN(g.rules.values());\n\n\t\tatn.lexerActions = new LexerAction[indexToActionMap.size()];\n\t\tfor (Map.Entry<Integer, LexerAction> entry : indexToActionMap.entrySet()) {\n\t\t\tatn.lexerActions[entry.getKey()] = entry.getValue();\n\t\t}\n\n\t\t// LINK MODE START STATE TO EACH TOKEN RULE\n\t\tfor (String modeName : modes) {\n\t\t\tList<Rule> rules = ((LexerGrammar)g).modes.get(modeName);\n\t\t\tTokensStartState startState = atn.modeNameToStartState.get(modeName);\n\t\t\tfor (Rule r : rules) {\n\t\t\t\tif ( !r.isFragment() ) {\n\t\t\t\t\tRuleStartState s = atn.ruleToStartState[r.index];\n\t\t\t\t\tepsilon(startState, s);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tATNOptimizer.optimize(g, atn);\n\t\tcheckEpsilonClosure();\n\t\treturn atn;\n\t}\n\n\t@Override\n\tpublic Handle rule(GrammarAST ruleAST, String name, Handle blk) {\n\t\truleCommands.clear();\n\t\treturn super.rule(ruleAST, name, blk);\n\t}\n\n\t@Override\n\tpublic Handle action(ActionAST action) {\n\t\tint ruleIndex = currentRule.index;\n\t\tint actionIndex = g.lexerActions.get(action);\n\t\tLexerCustomAction lexerAction = new LexerCustomAction(ruleIndex, actionIndex);\n\t\treturn action(action, lexerAction);\n\t}\n\n\tprotected int getLexerActionIndex(LexerAction lexerAction) {\n\t\tInteger lexerActionIndex = actionToIndexMap.get(lexerAction);\n\t\tif (lexerActionIndex == null) {\n\t\t\tlexerActionIndex = actionToIndexMap.size();\n\t\t\tactionToIndexMap.put(lexerAction, lexerActionIndex);\n\t\t\tindexToActionMap.put(lexerActionIndex, lexerAction);\n\t\t}\n\n\t\treturn lexerActionIndex;\n\t}\n\n\t@Override\n\tpublic Handle action(String action) {\n\t\tif (action.trim().isEmpty()) {\n\t\t\tATNState left = newState(null);\n\t\t\tATNState right = newState(null);\n\t\t\tepsilon(left, right);\n\t\t\treturn new Handle(left, right);\n\t\t}\n\n\t\t// define action AST for this rule as if we had found in grammar\n        ActionAST ast =\tnew ActionAST(new CommonToken(ANTLRParser.ACTION, action));\n\t\tcurrentRule.defineActionInAlt(currentOuterAlt, ast);\n\t\treturn action(ast);\n\t}\n\n\tprotected Handle action(GrammarAST node, LexerAction lexerAction) {\n\t\tATNState left = newState(node);\n\t\tATNState right = newState(node);\n\t\tboolean isCtxDependent = false;\n\t\tint lexerActionIndex = getLexerActionIndex(lexerAction);\n\t\tActionTransition a =\n\t\t\tnew ActionTransition(right, currentRule.index, lexerActionIndex, isCtxDependent);\n\t\tleft.addTransition(a);\n\t\tnode.atnState = left;\n\t\tHandle h = new Handle(left, right);\n\t\treturn h;\n\t}\n\n\t@Override\n\tpublic Handle lexerAltCommands(Handle alt, Handle cmds) {\n\t\tHandle h = new Handle(alt.left, cmds.right);\n\t\tepsilon(alt.right, cmds.left);\n\t\treturn h;\n\t}\n\n\t@Override\n\tpublic Handle lexerCallCommand(GrammarAST ID, GrammarAST arg) {\n\t\treturn lexerCallCommandOrCommand(ID, arg);\n\t}\n\n\t@Override\n\tpublic Handle lexerCommand(GrammarAST ID) {\n\t\treturn lexerCallCommandOrCommand(ID, null);\n\t}\n\n\tprivate Handle lexerCallCommandOrCommand(GrammarAST ID, GrammarAST arg) {\n\t\tLexerAction lexerAction = createLexerAction(ID, arg);\n\t\tif (lexerAction != null) {\n\t\t\treturn action(ID, lexerAction);\n\t\t}\n\n\t\t// fall back to standard action generation for the command\n\t\tST cmdST = codegenTemplates.getInstanceOf(\"Lexer\" +\n\t\t\t\tCharSupport.capitalize(ID.getText())+\n\t\t\t\t\"Command\");\n\t\tif (cmdST == null) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_LEXER_COMMAND, g.fileName, ID.token, ID.getText());\n\t\t\treturn epsilon(ID);\n\t\t}\n\n\t\tboolean callCommand = arg != null;\n\t\tboolean containsArg = cmdST.impl.formalArguments != null && cmdST.impl.formalArguments.containsKey(\"arg\");\n\t\tif (callCommand != containsArg) {\n\t\t\tErrorType errorType = callCommand ? ErrorType.UNWANTED_LEXER_COMMAND_ARGUMENT : ErrorType.MISSING_LEXER_COMMAND_ARGUMENT;\n\t\t\tg.tool.errMgr.grammarError(errorType, g.fileName, ID.token, ID.getText());\n\t\t\treturn epsilon(ID);\n\t\t}\n\n\t\tif (callCommand) {\n\t\t\tcmdST.add(\"arg\", arg.getText());\n\t\t\tcmdST.add(\"grammar\", arg.g);\n\t\t}\n\n\t\treturn action(cmdST.render());\n\t}\n\n\t@Override\n\tpublic Handle range(GrammarAST a, GrammarAST b) {\n\t\tATNState left = newState(a);\n\t\tATNState right = newState(b);\n\t\tint t1 = CharSupport.getCharValueFromGrammarCharLiteral(a.getText());\n\t\tint t2 = CharSupport.getCharValueFromGrammarCharLiteral(b.getText());\n\t\tif (checkRange(a, b, t1, t2)) {\n\t\t\tleft.addTransition(createTransition(right, t1, t2, a));\n\t\t}\n\t\ta.atnState = left;\n\t\tb.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\t@Override\n\tpublic Handle set(GrammarAST associatedAST, List<GrammarAST> alts, boolean invert) {\n\t\tATNState left = newState(associatedAST);\n\t\tATNState right = newState(associatedAST);\n\t\tIntervalSet set = new IntervalSet();\n\t\tfor (GrammarAST t : alts) {\n\t\t\tif ( t.getType()==ANTLRParser.RANGE ) {\n\t\t\t\tint a = CharSupport.getCharValueFromGrammarCharLiteral(t.getChild(0).getText());\n\t\t\t\tint b = CharSupport.getCharValueFromGrammarCharLiteral(t.getChild(1).getText());\n\t\t\t\tif (checkRange((GrammarAST)t.getChild(0), (GrammarAST)t.getChild(1), a, b)) {\n\t\t\t\t\tcheckRangeAndAddToSet(associatedAST, t, set, a, b, currentRule.caseInsensitive, null);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( t.getType()==ANTLRParser.LEXER_CHAR_SET ) {\n\t\t\t\tset.addAll(getSetFromCharSetLiteral(t));\n\t\t\t}\n\t\t\telse if ( t.getType()==ANTLRParser.STRING_LITERAL ) {\n\t\t\t\tint c = CharSupport.getCharValueFromGrammarCharLiteral(t.getText());\n\t\t\t\tif ( c != -1 ) {\n\t\t\t\t\tcheckCharAndAddToSet(associatedAST, set, c);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_LITERAL_IN_LEXER_SET,\n\t\t\t\t\t\t\t\t\t\t\t   g.fileName, t.getToken(), t.getText());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( t.getType()==ANTLRParser.TOKEN_REF ) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.UNSUPPORTED_REFERENCE_IN_LEXER_SET,\n\t\t\t\t\t\t\t\t\t\t   g.fileName, t.getToken(), t.getText());\n\t\t\t}\n\t\t}\n\t\tif ( invert ) {\n\t\t\tleft.addTransition(new NotSetTransition(right, set));\n\t\t}\n\t\telse {\n\t\t\tTransition transition;\n\t\t\tif (set.getIntervals().size() == 1) {\n\t\t\t\tInterval interval = set.getIntervals().get(0);\n\t\t\t\ttransition = CodePointTransitions.createWithCodePointRange(right, interval.a, interval.b);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttransition = new SetTransition(right, set);\n\t\t\t}\n\n\t\t\tleft.addTransition(transition);\n\t\t}\n\t\tassociatedAST.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\tprotected boolean checkRange(GrammarAST leftNode, GrammarAST rightNode, int leftValue, int rightValue) {\n\t\tboolean result = true;\n\t\tif (leftValue == -1) {\n\t\t\tresult = false;\n\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_LITERAL_IN_LEXER_SET,\n\t\t\t\t\tg.fileName, leftNode.getToken(), leftNode.getText());\n\t\t}\n\t\tif (rightValue == -1) {\n\t\t\tresult = false;\n\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_LITERAL_IN_LEXER_SET,\n\t\t\t\t\tg.fileName, rightNode.getToken(), rightNode.getText());\n\t\t}\n\t\tif (!result) return false;\n\n\t\tif (rightValue < leftValue) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED,\n\t\t\t\t\tg.fileName, leftNode.parent.getToken(), leftNode.getText() + \"..\" + rightNode.getText());\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** For a lexer, a string is a sequence of char to match.  That is,\n\t *  \"fog\" is treated as 'f' 'o' 'g' not as a single transition in\n\t *  the DFA.  Machine== o-'f'-&gt;o-'o'-&gt;o-'g'-&gt;o and has n+1 states\n\t *  for n characters.\n\t *  if \"caseInsensitive\" option is enabled, \"fog\" will be treated as\n\t *  o-('f'|'F') -> o-('o'|'O') -> o-('g'|'G')\n\t */\n\t@Override\n\tpublic Handle stringLiteral(TerminalAST stringLiteralAST) {\n\t\tString chars = stringLiteralAST.getText();\n\t\tATNState left = newState(stringLiteralAST);\n\t\tATNState right;\n\t\tString s = CharSupport.getStringFromGrammarStringLiteral(chars);\n\t\tif (s == null) {\n\t\t\t// the lexer will already have given an error\n\t\t\treturn new Handle(left, left);\n\t\t}\n\n\t\tint n = s.length();\n\t\tATNState prev = left;\n\t\tright = null;\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tright = newState(stringLiteralAST);\n\t\t\tint codePoint = s.codePointAt(i);\n\t\t\tprev.addTransition(createTransition(right, codePoint, codePoint, stringLiteralAST));\n\t\t\tprev = right;\n\t\t\ti += Character.charCount(codePoint);\n\t\t}\n\t\tstringLiteralAST.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\t/** [Aa\\t \\u1234a-z\\]\\p{Letter}\\-] char sets */\n\t@Override\n\tpublic Handle charSetLiteral(GrammarAST charSetAST) {\n\t\tATNState left = newState(charSetAST);\n\t\tATNState right = newState(charSetAST);\n\t\tIntervalSet set = getSetFromCharSetLiteral(charSetAST);\n\n\t\tleft.addTransition(new SetTransition(right, set));\n\t\tcharSetAST.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\tprivate static class CharSetParseState {\n\t\tenum Mode {\n\t\t\tNONE,\n\t\t\tERROR,\n\t\t\tPREV_CODE_POINT,\n\t\t\tPREV_PROPERTY\n\t\t}\n\n\t\tpublic static final CharSetParseState NONE = new CharSetParseState(Mode.NONE, false, -1, IntervalSet.EMPTY_SET);\n\t\tpublic static final CharSetParseState ERROR = new CharSetParseState(Mode.ERROR, false, -1, IntervalSet.EMPTY_SET);\n\n\t\tpublic final Mode mode;\n\t\tpublic final boolean inRange;\n\t\tpublic final int prevCodePoint;\n\t\tpublic final IntervalSet prevProperty;\n\n\t\tpublic CharSetParseState(\n\t\t\t\tMode mode,\n\t\t\t\tboolean inRange,\n\t\t\t\tint prevCodePoint,\n\t\t\t\tIntervalSet prevProperty) {\n\t\t\tthis.mode = mode;\n\t\t\tthis.inRange = inRange;\n\t\t\tthis.prevCodePoint = prevCodePoint;\n\t\t\tthis.prevProperty = prevProperty;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn String.format(\n\t\t\t\t\t\"%s mode=%s inRange=%s prevCodePoint=%d prevProperty=%s\",\n\t\t\t\t\tsuper.toString(),\n\t\t\t\t\tmode,\n\t\t\t\t\tinRange,\n\t\t\t\t\tprevCodePoint,\n\t\t\t\t\tprevProperty);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object other) {\n\t\t\tif (!(other instanceof CharSetParseState)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tCharSetParseState that = (CharSetParseState) other;\n\t\t\tif (this == that) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn Objects.equals(this.mode, that.mode) &&\n\t\t\t\tObjects.equals(this.inRange, that.inRange) &&\n\t\t\t\tObjects.equals(this.prevCodePoint, that.prevCodePoint) &&\n\t\t\t\tObjects.equals(this.prevProperty, that.prevProperty);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn Objects.hash(mode, inRange, prevCodePoint, prevProperty);\n\t\t}\n\t}\n\n\tpublic IntervalSet getSetFromCharSetLiteral(GrammarAST charSetAST) {\n\t\tString chars = charSetAST.getText();\n\t\tchars = chars.substring(1, chars.length() - 1);\n\t\tIntervalSet set = new IntervalSet();\n\t\tCharSetParseState state = CharSetParseState.NONE;\n\n\t\tint n = chars.length();\n\t\tfor (int i = 0; i < n; ) {\n\t\t\tif (state.mode == CharSetParseState.Mode.ERROR) {\n\t\t\t\treturn new IntervalSet();\n\t\t\t}\n\t\t\tint c = chars.codePointAt(i);\n\t\t\tint offset = Character.charCount(c);\n\t\t\tif (c == '\\\\') {\n\t\t\t\tEscapeSequenceParsing.Result escapeParseResult =\n\t\t\t\t\tEscapeSequenceParsing.parseEscape(chars, i);\n\t\t\t\tswitch (escapeParseResult.type) {\n\t\t\t\t\tcase INVALID:\n\t\t\t\t\t\tString invalid = chars.substring(escapeParseResult.startOffset,\n\t\t\t\t\t\t                                 escapeParseResult.startOffset+escapeParseResult.parseLength);\n\t\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_ESCAPE_SEQUENCE,\n\t\t\t\t\t\t                           g.fileName, charSetAST.getToken(), invalid);\n\t\t\t\t\t\tstate = CharSetParseState.ERROR;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase CODE_POINT:\n\t\t\t\t\t\tstate = applyPrevStateAndMoveToCodePoint(charSetAST, set, state, escapeParseResult.codePoint);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PROPERTY:\n\t\t\t\t\t\tstate = applyPrevStateAndMoveToProperty(charSetAST, set, state, escapeParseResult.propertyIntervalSet);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toffset = escapeParseResult.parseLength;\n\t\t\t}\n\t\t\telse if (c == '-' && !state.inRange && i != 0 && i != n - 1 && state.mode != CharSetParseState.Mode.NONE) {\n\t\t\t\tif (state.mode == CharSetParseState.Mode.PREV_PROPERTY) {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE,\n\t\t\t\t\t\t\tg.fileName, charSetAST.getToken(), charSetAST.getText());\n\t\t\t\t\tstate = CharSetParseState.ERROR;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstate = new CharSetParseState(state.mode, true, state.prevCodePoint, state.prevProperty);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstate = applyPrevStateAndMoveToCodePoint(charSetAST, set, state, c);\n\t\t\t}\n\t\t\ti += offset;\n\t\t}\n\t\tif (state.mode == CharSetParseState.Mode.ERROR) {\n\t\t\treturn new IntervalSet();\n\t\t}\n\t\t// Whether or not we were in a range, we'll add the last code point found to the set.\n\t\tapplyPrevState(charSetAST, set, state);\n\n\t\tif (set.isNil()) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED, g.fileName, charSetAST.getToken(), \"[]\");\n\t\t}\n\n\t\treturn set;\n\t}\n\n\tprivate CharSetParseState applyPrevStateAndMoveToCodePoint(\n\t\t\tGrammarAST charSetAST,\n\t\t\tIntervalSet set,\n\t\t\tCharSetParseState state,\n\t\t\tint codePoint) {\n\t\tif (state.inRange) {\n\t\t\tif (state.prevCodePoint > codePoint) {\n\t\t\t\tg.tool.errMgr.grammarError(\n\t\t\t\t\t\tErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED,\n\t\t\t\t\t\tg.fileName,\n\t\t\t\t\t\tcharSetAST.getToken(),\n\t\t\t\t\t\tCharSupport.getRangeEscapedString(state.prevCodePoint, codePoint));\n\t\t\t}\n\t\t\tcheckRangeAndAddToSet(charSetAST, set, state.prevCodePoint, codePoint);\n\t\t\tstate = CharSetParseState.NONE;\n\t\t}\n\t\telse {\n\t\t\tapplyPrevState(charSetAST, set, state);\n\t\t\tstate = new CharSetParseState(\n\t\t\t\t\tCharSetParseState.Mode.PREV_CODE_POINT,\n\t\t\t\t\tfalse,\n\t\t\t\t\tcodePoint,\n\t\t\t\t\tIntervalSet.EMPTY_SET);\n\t\t}\n\t\treturn state;\n\t}\n\n\tprivate CharSetParseState applyPrevStateAndMoveToProperty(\n\t\t\tGrammarAST charSetAST,\n\t\t\tIntervalSet set,\n\t\t\tCharSetParseState state,\n\t\t\tIntervalSet property) {\n\t\tif (state.inRange) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE,\n\t\t\t\t\t\t   g.fileName, charSetAST.getToken(), charSetAST.getText());\n\t\t\treturn CharSetParseState.ERROR;\n\t\t}\n\t\telse {\n\t\t\tapplyPrevState(charSetAST, set, state);\n\t\t\tstate = new CharSetParseState(\n\t\t\t\t\tCharSetParseState.Mode.PREV_PROPERTY,\n\t\t\t\t\tfalse,\n\t\t\t\t\t-1,\n\t\t\t\t\tproperty);\n\t\t}\n\t\treturn state;\n\t}\n\n\tprivate void applyPrevState(GrammarAST charSetAST, IntervalSet set, CharSetParseState state) {\n\t\tswitch (state.mode) {\n\t\t\tcase NONE:\n\t\t\tcase ERROR:\n\t\t\t\tbreak;\n\t\t\tcase PREV_CODE_POINT:\n\t\t\t\tcheckCharAndAddToSet(charSetAST, set, state.prevCodePoint);\n\t\t\t\tbreak;\n\t\t\tcase PREV_PROPERTY:\n\t\t\t\tset.addAll(state.prevProperty);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate void checkCharAndAddToSet(GrammarAST ast, IntervalSet set, int c) {\n\t\tcheckRangeAndAddToSet(ast, ast, set, c, c, currentRule.caseInsensitive, null);\n\t}\n\n\tprivate void checkRangeAndAddToSet(GrammarAST mainAst, IntervalSet set, int a, int b) {\n\t\tcheckRangeAndAddToSet(mainAst, mainAst, set, a, b, currentRule.caseInsensitive, null);\n\t}\n\n\tprivate CharactersDataCheckStatus checkRangeAndAddToSet(GrammarAST rootAst, GrammarAST ast, IntervalSet set, int a, int b, boolean caseInsensitive, CharactersDataCheckStatus previousStatus) {\n\t\tCharactersDataCheckStatus status;\n\t\tRangeBorderCharactersData charactersData = RangeBorderCharactersData.getAndCheckCharactersData(a, b, g, ast,\n\t\t\t\tpreviousStatus == null || !previousStatus.notImpliedCharacters);\n\t\tif (caseInsensitive) {\n\t\t\tstatus = new CharactersDataCheckStatus(false, charactersData.mixOfLowerAndUpperCharCase);\n\t\t\tif (charactersData.isSingleRange()) {\n\t\t\t\tstatus = checkRangeAndAddToSet(rootAst, ast, set, a, b, false, status);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstatus = checkRangeAndAddToSet(rootAst, ast, set, charactersData.lowerFrom, charactersData.lowerTo, false, status);\n\t\t\t\t// Don't report similar warning twice\n\t\t\t\tstatus = checkRangeAndAddToSet(rootAst, ast, set, charactersData.upperFrom, charactersData.upperTo, false, status);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tboolean charactersCollision = previousStatus != null && previousStatus.collision;\n\t\t\tif (!charactersCollision) {\n\t\t\t\tfor (int i = a; i <= b; i++) {\n\t\t\t\t\tif (set.contains(i)) {\n\t\t\t\t\t\tString setText;\n\t\t\t\t\t\tif (rootAst.getChildren() == null) {\n\t\t\t\t\t\t\tsetText = rootAst.getText();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tStringBuilder sb = new StringBuilder();\n\t\t\t\t\t\t\tfor (Object child : rootAst.getChildren()) {\n\t\t\t\t\t\t\t\tif (child instanceof RangeAST) {\n\t\t\t\t\t\t\t\t\tsb.append(((RangeAST) child).getChild(0).getText());\n\t\t\t\t\t\t\t\t\tsb.append(\"..\");\n\t\t\t\t\t\t\t\t\tsb.append(((RangeAST) child).getChild(1).getText());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tsb.append(((GrammarAST) child).getText());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsb.append(\" | \");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsb.replace(sb.length() - 3, sb.length(), \"\");\n\t\t\t\t\t\t\tsetText = sb.toString();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tString charsString = a == b ? String.valueOf((char)a) : (char) a + \"-\" + (char) b;\n\t\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.CHARACTERS_COLLISION_IN_SET, g.fileName, ast.getToken(),\n\t\t\t\t\t\t\t\tcharsString, setText);\n\t\t\t\t\t\tcharactersCollision = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstatus = new CharactersDataCheckStatus(charactersCollision, charactersData.mixOfLowerAndUpperCharCase);\n\t\t\tset.add(a, b);\n\t\t}\n\t\treturn status;\n\t}\n\n\tprivate Transition createTransition(ATNState target, int from, int to, CommonTree tree) {\n\t\tRangeBorderCharactersData charactersData = RangeBorderCharactersData.getAndCheckCharactersData(from, to, g, tree, true);\n\t\tif (currentRule.caseInsensitive) {\n\t\t\tif (charactersData.isSingleRange()) {\n\t\t\t\treturn CodePointTransitions.createWithCodePointRange(target, from, to);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tIntervalSet intervalSet = new IntervalSet();\n\t\t\t\tintervalSet.add(charactersData.lowerFrom, charactersData.lowerTo);\n\t\t\t\tintervalSet.add(charactersData.upperFrom, charactersData.upperTo);\n\t\t\t\treturn new SetTransition(target, intervalSet);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn CodePointTransitions.createWithCodePointRange(target, from, to);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Handle tokenRef(TerminalAST node) {\n\t\t// Ref to EOF in lexer yields char transition on -1\n\t\tif (node.getText().equals(\"EOF\") ) {\n\t\t\tATNState left = newState(node);\n\t\t\tATNState right = newState(node);\n\t\t\tleft.addTransition(new AtomTransition(right, IntStream.EOF));\n\t\t\treturn new Handle(left, right);\n\t\t}\n\t\treturn _ruleRef(node);\n\t}\n\n\tprivate LexerAction createLexerAction(GrammarAST ID, GrammarAST arg) {\n\t\tString command = ID.getText();\n\t\tcheckCommands(command, ID.getToken());\n\n\t\tif (\"skip\".equals(command) && arg == null) {\n\t\t\treturn LexerSkipAction.INSTANCE;\n\t\t}\n\t\telse if (\"more\".equals(command) && arg == null) {\n\t\t\treturn LexerMoreAction.INSTANCE;\n\t\t}\n\t\telse if (\"popMode\".equals(command) && arg == null) {\n\t\t\treturn LexerPopModeAction.INSTANCE;\n\t\t}\n\t\telse if (\"mode\".equals(command) && arg != null) {\n\t\t\tString modeName = arg.getText();\n\t\t\tInteger mode = getModeConstantValue(modeName, arg.getToken());\n\t\t\tif (mode == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn new LexerModeAction(mode);\n\t\t}\n\t\telse if (\"pushMode\".equals(command) && arg != null) {\n\t\t\tString modeName = arg.getText();\n\t\t\tInteger mode = getModeConstantValue(modeName, arg.getToken());\n\t\t\tif (mode == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn new LexerPushModeAction(mode);\n\t\t}\n\t\telse if (\"type\".equals(command) && arg != null) {\n\t\t\tString typeName = arg.getText();\n\t\t\tInteger type = getTokenConstantValue(typeName, arg.getToken());\n\t\t\tif (type == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn new LexerTypeAction(type);\n\t\t}\n\t\telse if (\"channel\".equals(command) && arg != null) {\n\t\t\tString channelName = arg.getText();\n\t\t\tInteger channel = getChannelConstantValue(channelName, arg.getToken());\n\t\t\tif (channel == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn new LexerChannelAction(channel);\n\t\t}\n\t\telse {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate void checkCommands(String command, Token commandToken) {\n\t\t// Command combinations list: https://github.com/antlr/antlr4/issues/1388#issuecomment-263344701\n\t\tif (!command.equals(\"pushMode\") && !command.equals(\"popMode\")) {\n\t\t\tif (ruleCommands.contains(command)) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.DUPLICATED_COMMAND, g.fileName, commandToken, command);\n\t\t\t}\n\n\t\t\tString firstCommand = null;\n\n\t\t\tif (command.equals(\"skip\")) {\n\t\t\t\tif (ruleCommands.contains(\"more\")) {\n\t\t\t\t\tfirstCommand = \"more\";\n\t\t\t\t}\n\t\t\t\telse if (ruleCommands.contains(\"type\")) {\n\t\t\t\t\tfirstCommand = \"type\";\n\t\t\t\t}\n\t\t\t\telse if (ruleCommands.contains(\"channel\")) {\n\t\t\t\t\tfirstCommand = \"channel\";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (command.equals(\"more\")) {\n\t\t\t\tif (ruleCommands.contains(\"skip\")) {\n\t\t\t\t\tfirstCommand = \"skip\";\n\t\t\t\t}\n\t\t\t\telse if (ruleCommands.contains(\"type\")) {\n\t\t\t\t\tfirstCommand = \"type\";\n\t\t\t\t}\n\t\t\t\telse if (ruleCommands.contains(\"channel\")) {\n\t\t\t\t\tfirstCommand = \"channel\";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (command.equals(\"type\") || command.equals(\"channel\")) {\n\t\t\t\tif (ruleCommands.contains(\"more\")) {\n\t\t\t\t\tfirstCommand = \"more\";\n\t\t\t\t}\n\t\t\t\telse if (ruleCommands.contains(\"skip\")) {\n\t\t\t\t\tfirstCommand = \"skip\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (firstCommand != null) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.INCOMPATIBLE_COMMANDS, g.fileName, commandToken, firstCommand, command);\n\t\t\t}\n\t\t}\n\n\t\truleCommands.add(command);\n\t}\n\n\tprivate Integer getModeConstantValue(String modeName, Token token) {\n\t\tif (modeName == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (modeName.equals(\"DEFAULT_MODE\")) {\n\t\t\treturn Lexer.DEFAULT_MODE;\n\t\t}\n\t\tif (COMMON_CONSTANTS.containsKey(modeName)) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.MODE_CONFLICTS_WITH_COMMON_CONSTANTS, g.fileName, token, token.getText());\n\t\t\treturn null;\n\t\t}\n\n\t\tList<String> modeNames = new ArrayList<String>(((LexerGrammar)g).modes.keySet());\n\t\tint mode = modeNames.indexOf(modeName);\n\t\tif (mode >= 0) {\n\t\t\treturn mode;\n\t\t}\n\n\t\ttry {\n\t\t\treturn Integer.parseInt(modeName);\n\t\t} catch (NumberFormatException ex) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_MODE_NAME, g.fileName, token, token.getText());\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate Integer getTokenConstantValue(String tokenName, Token token) {\n\t\tif (tokenName == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (tokenName.equals(\"EOF\")) {\n\t\t\treturn Lexer.EOF;\n\t\t}\n\t\tif (COMMON_CONSTANTS.containsKey(tokenName)) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.TOKEN_CONFLICTS_WITH_COMMON_CONSTANTS, g.fileName, token, token.getText());\n\t\t\treturn null;\n\t\t}\n\n\t\tint tokenType = g.getTokenType(tokenName);\n\t\tif (tokenType != org.antlr.v4.runtime.Token.INVALID_TYPE) {\n\t\t\treturn tokenType;\n\t\t}\n\n\t\ttry {\n\t\t\treturn Integer.parseInt(tokenName);\n\t\t} catch (NumberFormatException ex) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_TOKEN_NAME, g.fileName, token, token.getText());\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate Integer getChannelConstantValue(String channelName, Token token) {\n\t\tif (channelName == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (channelName.equals(\"HIDDEN\")) {\n\t\t\treturn Lexer.HIDDEN;\n\t\t}\n\t\tif (channelName.equals(\"DEFAULT_TOKEN_CHANNEL\")) {\n\t\t\treturn Lexer.DEFAULT_TOKEN_CHANNEL;\n\t\t}\n\t\tif (COMMON_CONSTANTS.containsKey(channelName)) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.CHANNEL_CONFLICTS_WITH_COMMON_CONSTANTS, g.fileName, token, token.getText());\n\t\t\treturn null;\n\t\t}\n\n\t\tint channelValue = g.getChannelValue(channelName);\n\t\tif (channelValue >= org.antlr.v4.runtime.Token.MIN_USER_CHANNEL_VALUE) {\n\t\t\treturn channelValue;\n\t\t}\n\n\t\ttry {\n\t\t\treturn Integer.parseInt(channelName);\n\t\t} catch (NumberFormatException ex) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_CHANNEL_NAME, g.fileName, token, token.getText());\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/ParserATNFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.automata;\n\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.tree.CommonTreeNodeStream;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.v4.analysis.LeftRecursiveRuleTransformer;\nimport org.antlr.v4.misc.CharSupport;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.ATNBuilder;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.ATNType;\nimport org.antlr.v4.runtime.atn.AbstractPredicateTransition;\nimport org.antlr.v4.runtime.atn.ActionTransition;\nimport org.antlr.v4.runtime.atn.AtomTransition;\nimport org.antlr.v4.runtime.atn.BasicBlockStartState;\nimport org.antlr.v4.runtime.atn.BasicState;\nimport org.antlr.v4.runtime.atn.BlockEndState;\nimport org.antlr.v4.runtime.atn.BlockStartState;\nimport org.antlr.v4.runtime.atn.EpsilonTransition;\nimport org.antlr.v4.runtime.atn.LL1Analyzer;\nimport org.antlr.v4.runtime.atn.LoopEndState;\nimport org.antlr.v4.runtime.atn.NotSetTransition;\nimport org.antlr.v4.runtime.atn.PlusBlockStartState;\nimport org.antlr.v4.runtime.atn.PlusLoopbackState;\nimport org.antlr.v4.runtime.atn.PrecedencePredicateTransition;\nimport org.antlr.v4.runtime.atn.PredicateTransition;\nimport org.antlr.v4.runtime.atn.RuleStartState;\nimport org.antlr.v4.runtime.atn.RuleStopState;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.SetTransition;\nimport org.antlr.v4.runtime.atn.StarBlockStartState;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.runtime.atn.StarLoopbackState;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.atn.WildcardTransition;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.misc.Triple;\nimport org.antlr.v4.semantics.UseDefAnalyzer;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LeftRecursiveRule;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTWithOptions;\nimport org.antlr.v4.tool.ast.PredAST;\nimport org.antlr.v4.tool.ast.QuantifierAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\n/** ATN construction routines triggered by ATNBuilder.g.\n *\n *  No side-effects. It builds an {@link ATN} object and returns it.\n */\npublic class ParserATNFactory implements ATNFactory {\n\n\tpublic final Grammar g;\n\n\n\tpublic final ATN atn;\n\n\tpublic Rule currentRule;\n\n\tpublic int currentOuterAlt;\n\n\n\tprotected final List<Triple<Rule, ATNState, ATNState>> preventEpsilonClosureBlocks =\n\t\tnew ArrayList<Triple<Rule, ATNState, ATNState>>();\n\n\n\tprotected final List<Triple<Rule, ATNState, ATNState>> preventEpsilonOptionalBlocks =\n\t\tnew ArrayList<Triple<Rule, ATNState, ATNState>>();\n\n\tpublic ParserATNFactory(Grammar g) {\n\t\tif (g == null) {\n\t\t\tthrow new NullPointerException(\"g\");\n\t\t}\n\n\t\tthis.g = g;\n\n\t\tATNType atnType = g instanceof LexerGrammar ? ATNType.LEXER : ATNType.PARSER;\n\t\tint maxTokenType = g.getMaxTokenType();\n\t\tthis.atn = new ATN(atnType, maxTokenType);\n\t}\n\n\n\t@Override\n\tpublic ATN createATN() {\n\t\t_createATN(g.rules.values());\n\t\tassert atn.maxTokenType == g.getMaxTokenType();\n        addRuleFollowLinks();\n\t\taddEOFTransitionToStartRules();\n\t\tATNOptimizer.optimize(g, atn);\n\t\tcheckEpsilonClosure();\n\n\t\toptionalCheck:\n\t\tfor (Triple<Rule, ATNState, ATNState> pair : preventEpsilonOptionalBlocks) {\n\t\t\tint bypassCount = 0;\n\t\t\tfor (int i = 0; i < pair.b.getNumberOfTransitions(); i++) {\n\t\t\t\tATNState startState = pair.b.transition(i).target;\n\t\t\t\tif (startState == pair.c) {\n\t\t\t\t\tbypassCount++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tLL1Analyzer analyzer = new LL1Analyzer(atn);\n\t\t\t\tif (analyzer.LOOK(startState, pair.c, null).contains(org.antlr.v4.runtime.Token.EPSILON)) {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.EPSILON_OPTIONAL, g.fileName, ((GrammarAST)pair.a.ast.getChild(0)).getToken(), pair.a.name);\n\t\t\t\t\tcontinue optionalCheck;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (bypassCount != 1) {\n\t\t\t\tthrow new UnsupportedOperationException(\"Expected optional block with exactly 1 bypass alternative.\");\n\t\t\t}\n\t\t}\n\n\t\treturn atn;\n\t}\n\n\tprotected void checkEpsilonClosure() {\n\t\tfor (Triple<Rule, ATNState, ATNState> pair : preventEpsilonClosureBlocks) {\n\t\t\tLL1Analyzer analyzer = new LL1Analyzer(atn);\n\t\t\tATNState blkStart = pair.b;\n\t\t\tATNState blkStop = pair.c;\n\t\t\tIntervalSet lookahead = analyzer.LOOK(blkStart, blkStop, null);\n\t\t\tif ( lookahead.contains(org.antlr.v4.runtime.Token.EPSILON)) {\n\t\t\t\tErrorType errorType = pair.a instanceof LeftRecursiveRule ? ErrorType.EPSILON_LR_FOLLOW : ErrorType.EPSILON_CLOSURE;\n\t\t\t\tg.tool.errMgr.grammarError(errorType, g.fileName, ((GrammarAST)pair.a.ast.getChild(0)).getToken(), pair.a.name);\n\t\t\t}\n\t\t\tif ( lookahead.contains(org.antlr.v4.runtime.Token.EOF)) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.EOF_CLOSURE, g.fileName, ((GrammarAST)pair.a.ast.getChild(0)).getToken(), pair.a.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void _createATN(Collection<Rule> rules) {\n\t\tcreateRuleStartAndStopATNStates();\n\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor();\n\t\tfor (Rule r : rules) {\n\t\t\t// find rule's block\n\t\t\tGrammarAST blk = (GrammarAST)r.ast.getFirstChildWithType(ANTLRParser.BLOCK);\n\t\t\tCommonTreeNodeStream nodes = new CommonTreeNodeStream(adaptor,blk);\n\t\t\tATNBuilder b = new ATNBuilder(nodes,this);\n\t\t\ttry {\n\t\t\t\tsetCurrentRuleName(r.name);\n\t\t\t\tHandle h = b.ruleBlock(null);\n\t\t\t\trule(r.ast, r.name, h);\n\t\t\t}\n\t\t\tcatch (RecognitionException re) {\n\t\t\t\tErrorManager.fatalInternalError(\"bad grammar AST structure\", re);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setCurrentRuleName(String name) {\n\t\tthis.currentRule = g.getRule(name);\n\t}\n\n\t@Override\n\tpublic void setCurrentOuterAlt(int alt) {\n\t\tcurrentOuterAlt = alt;\n\t}\n\n\t/* start->ruleblock->end */\n\n\t@Override\n\tpublic Handle rule(GrammarAST ruleAST, String name, Handle blk) {\n\t\tRule r = g.getRule(name);\n\t\tRuleStartState start = atn.ruleToStartState[r.index];\n\t\tepsilon(start, blk.left);\n\t\tRuleStopState stop = atn.ruleToStopState[r.index];\n\t\tepsilon(blk.right, stop);\n\t\tHandle h = new Handle(start, stop);\n//\t\tATNPrinter ser = new ATNPrinter(g, h.left);\n//\t\tSystem.out.println(ruleAST.toStringTree()+\":\\n\"+ser.asString());\n\t\truleAST.atnState = start;\n\t\treturn h;\n\t}\n\n\t/** From label {@code A} build graph {@code o-A->o}. */\n\n\t@Override\n\tpublic Handle tokenRef(TerminalAST node) {\n\t\tATNState left = newState(node);\n\t\tATNState right = newState(node);\n\t\tint ttype = g.getTokenType(node.getText());\n\t\tleft.addTransition(new AtomTransition(right, ttype));\n\t\tnode.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\t/** From set build single edge graph {@code o->o-set->o}.  To conform to\n     *  what an alt block looks like, must have extra state on left.\n\t *  This also handles {@code ~A}, converted to {@code ~{A}} set.\n     */\n\n\t@Override\n\tpublic Handle set(GrammarAST associatedAST, List<GrammarAST> terminals, boolean invert) {\n\t\tATNState left = newState(associatedAST);\n\t\tATNState right = newState(associatedAST);\n\t\tIntervalSet set = new IntervalSet();\n\t\tfor (GrammarAST t : terminals) {\n\t\t\tint ttype = g.getTokenType(t.getText());\n\t\t\tset.add(ttype);\n\t\t}\n\t\tif ( invert ) {\n\t\t\tleft.addTransition(new NotSetTransition(right, set));\n\t\t}\n\t\telse {\n\t\t\tleft.addTransition(new SetTransition(right, set));\n\t\t}\n\t\tassociatedAST.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\t/** Not valid for non-lexers. */\n\n\t@Override\n\tpublic Handle range(GrammarAST a, GrammarAST b) {\n\t\tg.tool.errMgr.grammarError(ErrorType.TOKEN_RANGE_IN_PARSER, g.fileName,\n\t\t                           a.getToken(),\n\t\t                           a.getToken().getText(),\n\t\t                           b.getToken().getText());\n\t\t// From a..b, yield ATN for just a.\n\t\treturn tokenRef((TerminalAST)a);\n\t}\n\n\tprotected int getTokenType(GrammarAST atom) {\n\t\tint ttype;\n\t\tif ( g.isLexer() ) {\n\t\t\tttype = CharSupport.getCharValueFromGrammarCharLiteral(atom.getText());\n\t\t}\n\t\telse {\n\t\t\tttype = g.getTokenType(atom.getText());\n\t\t}\n\t\treturn ttype;\n\t}\n\n\t/** For a non-lexer, just build a simple token reference atom. */\n\n\t@Override\n\tpublic Handle stringLiteral(TerminalAST stringLiteralAST) {\n\t\treturn tokenRef(stringLiteralAST);\n\t}\n\n\t/** {@code [Aa]} char sets not allowed in parser */\n\n\t@Override\n\tpublic Handle charSetLiteral(GrammarAST charSetAST) {\n\t\treturn null;\n\t}\n\n\t/**\n\t * For reference to rule {@code r}, build\n\t *\n\t * <pre>\n\t *  o-&gt;(r)  o\n\t * </pre>\n\t *\n\t * where {@code (r)} is the start of rule {@code r} and the trailing\n\t * {@code o} is not linked to from rule ref state directly (uses\n\t * {@link RuleTransition#followState}).\n\t */\n\n\t@Override\n\tpublic Handle ruleRef(GrammarAST node) {\n\t\tHandle h = _ruleRef(node);\n\t\treturn h;\n\t}\n\n\n\tpublic Handle _ruleRef(GrammarAST node) {\n\t\tRule r = g.getRule(node.getText());\n\t\tif ( r==null ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.INTERNAL_ERROR, g.fileName, node.getToken(), \"Rule \"+node.getText()+\" undefined\");\n\t\t\treturn null;\n\t\t}\n\t\tRuleStartState start = atn.ruleToStartState[r.index];\n\t\tATNState left = newState(node);\n\t\tATNState right = newState(node);\n\t\tint precedence = 0;\n\t\tif (((GrammarASTWithOptions)node).getOptionString(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME) != null) {\n\t\t\tprecedence = Integer.parseInt(((GrammarASTWithOptions)node).getOptionString(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME));\n\t\t}\n\t\tRuleTransition call = new RuleTransition(start, r.index, precedence, right);\n\t\tleft.addTransition(call);\n\n\t\tnode.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\tpublic void addFollowLink(int ruleIndex, ATNState right) {\n\t\t// add follow edge from end of invoked rule\n\t\tRuleStopState stop = atn.ruleToStopState[ruleIndex];\n//        System.out.println(\"add follow link from \"+ruleIndex+\" to \"+right);\n\t\tepsilon(stop, right);\n\t}\n\n\t/** From an empty alternative build {@code o-e->o}. */\n\n\t@Override\n\tpublic Handle epsilon(GrammarAST node) {\n\t\tATNState left = newState(node);\n\t\tATNState right = newState(node);\n\t\tepsilon(left, right);\n\t\tnode.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\t/** Build what amounts to an epsilon transition with a semantic\n\t *  predicate action.  The {@code pred} is a pointer into the AST of\n\t *  the {@link ANTLRParser#SEMPRED} token.\n\t */\n\n\t@Override\n\tpublic Handle sempred(PredAST pred) {\n\t\t//System.out.println(\"sempred: \"+ pred);\n\t\tATNState left = newState(pred);\n\t\tATNState right = newState(pred);\n\n\t\tAbstractPredicateTransition p;\n\t\tif (pred.getOptionString(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME) != null) {\n\t\t\tint precedence = Integer.parseInt(pred.getOptionString(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME));\n\t\t\tp = new PrecedencePredicateTransition(right, precedence);\n\t\t}\n\t\telse {\n\t\t\tboolean isCtxDependent = UseDefAnalyzer.actionIsContextDependent(pred);\n\t\t\tp = new PredicateTransition(right, currentRule.index, g.sempreds.get(pred), isCtxDependent);\n\t\t}\n\n\t\tleft.addTransition(p);\n\t\tpred.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\t/** Build what amounts to an epsilon transition with an action.\n\t *  The action goes into ATN though it is ignored during prediction\n\t *  if {@link ActionTransition#actionIndex actionIndex}{@code <0}.\n\t */\n\n\t@Override\n\tpublic Handle action(ActionAST action) {\n\t\t//System.out.println(\"action: \"+action);\n\t\tATNState left = newState(action);\n\t\tATNState right = newState(action);\n\t\tActionTransition a = new ActionTransition(right, currentRule.index);\n\t\tleft.addTransition(a);\n\t\taction.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\n\t@Override\n\tpublic Handle action(String action) {\n\t\tthrow new UnsupportedOperationException(\"This element is not valid in parsers.\");\n\t}\n\n\t/**\n\t * From {@code A|B|..|Z} alternative block build\n\t *\n\t * <pre>\n\t *  o-&gt;o-A-&gt;o-&gt;o (last ATNState is BlockEndState pointed to by all alts)\n\t *  |          ^\n\t *  |-&gt;o-B-&gt;o--|\n\t *  |          |\n\t *  ...        |\n\t *  |          |\n\t *  |-&gt;o-Z-&gt;o--|\n\t * </pre>\n\t *\n\t * So start node points at every alternative with epsilon transition and\n\t * every alt right side points at a block end ATNState.\n\t * <p>\n\t * Special case: only one alternative: don't make a block with alt\n\t * begin/end.\n\t * <p>\n\t * Special case: if just a list of tokens/chars/sets, then collapse to a\n\t * single edged o-set-&gt;o graph.\n\t * <p>\n\t * TODO: Set alt number (1..n) in the states?\n\t */\n\n\t@Override\n\tpublic Handle block(BlockAST blkAST, GrammarAST ebnfRoot, List<Handle> alts) {\n\t\tif ( ebnfRoot==null ) {\n\t\t\tif ( alts.size()==1 ) {\n\t\t\t\tHandle h = alts.get(0);\n\t\t\t\tblkAST.atnState = h.left;\n\t\t\t\treturn h;\n\t\t\t}\n\t\t\tBlockStartState start = newState(BasicBlockStartState.class, blkAST);\n\t\t\tif ( alts.size()>1 ) atn.defineDecisionState(start);\n\t\t\treturn makeBlock(start, blkAST, alts);\n\t\t}\n\t\tswitch ( ebnfRoot.getType() ) {\n\t\t\tcase ANTLRParser.OPTIONAL :\n\t\t\t\tBlockStartState start = newState(BasicBlockStartState.class, blkAST);\n\t\t\t\tatn.defineDecisionState(start);\n\t\t\t\tHandle h = makeBlock(start, blkAST, alts);\n\t\t\t\treturn optional(ebnfRoot, h);\n\t\t\tcase ANTLRParser.CLOSURE :\n\t\t\t\tBlockStartState star = newState(StarBlockStartState.class, ebnfRoot);\n\t\t\t\tif ( alts.size()>1 ) atn.defineDecisionState(star);\n\t\t\t\th = makeBlock(star, blkAST, alts);\n\t\t\t\treturn star(ebnfRoot, h);\n\t\t\tcase ANTLRParser.POSITIVE_CLOSURE :\n\t\t\t\tPlusBlockStartState plus = newState(PlusBlockStartState.class, ebnfRoot);\n\t\t\t\tif ( alts.size()>1 ) atn.defineDecisionState(plus);\n\t\t\t\th = makeBlock(plus, blkAST, alts);\n\t\t\t\treturn plus(ebnfRoot, h);\n\t\t}\n\t\treturn null;\n\t}\n\n\n\tprotected Handle makeBlock(BlockStartState start, BlockAST blkAST, List<Handle> alts) {\n\t\tBlockEndState end = newState(BlockEndState.class, blkAST);\n\t\tstart.endState = end;\n\t\tfor (Handle alt : alts) {\n\t\t\t// hook alts up to decision block\n\t\t\tepsilon(start, alt.left);\n\t\t\tepsilon(alt.right, end);\n\t\t\t// no back link in ATN so must walk entire alt to see if we can\n\t\t\t// strip out the epsilon to 'end' state\n\t\t\tTailEpsilonRemover opt = new TailEpsilonRemover(atn);\n\t\t\topt.visit(alt.left);\n\t\t}\n\t\tHandle h = new Handle(start, end);\n//\t\tFASerializer ser = new FASerializer(g, h.left);\n//\t\tSystem.out.println(blkAST.toStringTree()+\":\\n\"+ser);\n\t\tblkAST.atnState = start;\n\n\t\treturn h;\n\t}\n\n\n\t@Override\n\tpublic Handle alt(List<Handle> els) {\n\t\treturn elemList(els);\n\t}\n\n\n\tpublic Handle elemList(List<Handle> els) {\n\t\tint n = els.size();\n\t\tfor (int i = 0; i < n - 1; i++) {\t// hook up elements (visit all but last)\n\t\t\tHandle el = els.get(i);\n\t\t\t// if el is of form o-x->o for x in {rule, action, pred, token, ...}\n\t\t\t// and not last in alt\n            Transition tr = null;\n            if ( el.left.getNumberOfTransitions()==1 ) tr = el.left.transition(0);\n            boolean isRuleTrans = tr instanceof RuleTransition;\n            if ( el.left.getStateType() == ATNState.BASIC &&\n\t\t\t\tel.right != null &&\n\t\t\t\tel.right.getStateType()== ATNState.BASIC &&\n\t\t\t\ttr!=null && (isRuleTrans && ((RuleTransition)tr).followState == el.right || tr.target == el.right) ) {\n\t\t\t\t// we can avoid epsilon edge to next el\n\t\t\t\tHandle handle = null;\n\t\t\t\tif (i + 1 < els.size()) {\n\t\t\t\t\thandle = els.get(i + 1);\n\t\t\t\t}\n\t\t\t\tif (handle != null) {\n\t\t\t\t\tif (isRuleTrans) {\n\t\t\t\t\t\t((RuleTransition) tr).followState = handle.left;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttr.target = handle.left;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tatn.removeState(el.right); // we skipped over this state\n\t\t\t}\n\t\t\telse { // need epsilon if previous block's right end node is complicated\n\t\t\t\tepsilon(el.right, els.get(i+1).left);\n\t\t\t}\n\t\t}\n\t\tHandle first = els.get(0);\n\t\tHandle last = els.get(n - 1);\n\t\tATNState left = null;\n\t\tif (first != null) {\n\t\t\tleft = first.left;\n\t\t}\n\t\tATNState right = null;\n\t\tif (last != null) {\n\t\t\tright = last.right;\n\t\t}\n\t\treturn new Handle(left, right);\n\t}\n\n\t/**\n\t * From {@code (A)?} build either:\n\t *\n\t * <pre>\n\t *  o--A-&gt;o\n\t *  |     ^\n\t *  o----&gt;|\n\t * </pre>\n\t *\n\t * or, if {@code A} is a block, just add an empty alt to the end of the\n\t * block\n\t */\n\n\t@Override\n\tpublic Handle optional(GrammarAST optAST, Handle blk) {\n\t\tBlockStartState blkStart = (BlockStartState)blk.left;\n\t\tATNState blkEnd = blk.right;\n\t\tpreventEpsilonOptionalBlocks.add(new Triple<Rule, ATNState, ATNState>(currentRule, blkStart, blkEnd));\n\n\t\tboolean greedy = ((QuantifierAST)optAST).isGreedy();\n\t\tblkStart.nonGreedy = !greedy;\n\t\tepsilon(blkStart, blk.right, !greedy);\n\n\t\toptAST.atnState = blk.left;\n\t\treturn blk;\n\t}\n\n\t/**\n\t * From {@code (blk)+} build\n\t *\n\t * <pre>\n\t *   |---------|\n\t *   v         |\n\t *  [o-blk-o]-&gt;o-&gt;o\n\t * </pre>\n\t *\n\t * We add a decision for loop back node to the existing one at {@code blk}\n\t * start.\n\t */\n\n\t@Override\n\tpublic Handle plus(GrammarAST plusAST, Handle blk) {\n\t\tPlusBlockStartState blkStart = (PlusBlockStartState)blk.left;\n\t\tBlockEndState blkEnd = (BlockEndState)blk.right;\n\t\tpreventEpsilonClosureBlocks.add(new Triple<Rule, ATNState, ATNState>(currentRule, blkStart, blkEnd));\n\n\t\tPlusLoopbackState loop = newState(PlusLoopbackState.class, plusAST);\n\t\tloop.nonGreedy = !((QuantifierAST)plusAST).isGreedy();\n\t\tatn.defineDecisionState(loop);\n\t\tLoopEndState end = newState(LoopEndState.class, plusAST);\n\t\tblkStart.loopBackState = loop;\n\t\tend.loopBackState = loop;\n\n\t\tplusAST.atnState = loop;\n\t\tepsilon(blkEnd, loop);\t\t// blk can see loop back\n\n\t\tBlockAST blkAST = (BlockAST)plusAST.getChild(0);\n\t\tif ( ((QuantifierAST)plusAST).isGreedy() ) {\n\t\t\tif (expectNonGreedy(blkAST)) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.EXPECTED_NON_GREEDY_WILDCARD_BLOCK, g.fileName, plusAST.getToken(), plusAST.getToken().getText());\n\t\t\t}\n\n\t\t\tepsilon(loop, blkStart);\t// loop back to start\n\t\t\tepsilon(loop, end);\t\t\t// or exit\n\t\t}\n\t\telse {\n\t\t\t// if not greedy, priority to exit branch; make it first\n\t\t\tepsilon(loop, end);\t\t\t// exit\n\t\t\tepsilon(loop, blkStart);\t// loop back to start\n\t\t}\n\n\t\treturn new Handle(blkStart, end);\n\t}\n\n\t/**\n\t * From {@code (blk)*} build {@code ( blk+ )?} with *two* decisions, one for\n\t * entry and one for choosing alts of {@code blk}.\n\t *\n\t * <pre>\n\t *   |-------------|\n\t *   v             |\n\t *   o--[o-blk-o]-&gt;o  o\n\t *   |                ^\n\t *   -----------------|\n\t * </pre>\n\t *\n\t * Note that the optional bypass must jump outside the loop as\n\t * {@code (A|B)*} is not the same thing as {@code (A|B|)+}.\n\t */\n\n\t@Override\n\tpublic Handle star(GrammarAST starAST, Handle elem) {\n\t\tStarBlockStartState blkStart = (StarBlockStartState)elem.left;\n\t\tBlockEndState blkEnd = (BlockEndState)elem.right;\n\t\tpreventEpsilonClosureBlocks.add(new Triple<Rule, ATNState, ATNState>(currentRule, blkStart, blkEnd));\n\n\t\tStarLoopEntryState entry = newState(StarLoopEntryState.class, starAST);\n\t\tentry.nonGreedy = !((QuantifierAST)starAST).isGreedy();\n\t\tatn.defineDecisionState(entry);\n\t\tLoopEndState end = newState(LoopEndState.class, starAST);\n\t\tStarLoopbackState loop = newState(StarLoopbackState.class, starAST);\n\t\tentry.loopBackState = loop;\n\t\tend.loopBackState = loop;\n\n\t\tBlockAST blkAST = (BlockAST)starAST.getChild(0);\n\t\tif ( ((QuantifierAST)starAST).isGreedy() ) {\n\t\t\tif (expectNonGreedy(blkAST)) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.EXPECTED_NON_GREEDY_WILDCARD_BLOCK, g.fileName, starAST.getToken(), starAST.getToken().getText());\n\t\t\t}\n\n\t\t\tepsilon(entry, blkStart);\t// loop enter edge (alt 1)\n\t\t\tepsilon(entry, end);\t\t// bypass loop edge (alt 2)\n\t\t}\n\t\telse {\n\t\t\t// if not greedy, priority to exit branch; make it first\n\t\t\tepsilon(entry, end);\t\t// bypass loop edge (alt 1)\n\t\t\tepsilon(entry, blkStart);\t// loop enter edge (alt 2)\n\t\t}\n\t\tepsilon(blkEnd, loop);\t\t// block end hits loop back\n\t\tepsilon(loop, entry);\t\t// loop back to entry/exit decision\n\n\t\tstarAST.atnState = entry;\t// decision is to enter/exit; blk is its own decision\n\t\treturn new Handle(entry, end);\n\t}\n\n\t/** Build an atom with all possible values in its label. */\n\n\t@Override\n\tpublic Handle wildcard(GrammarAST node) {\n\t\tATNState left = newState(node);\n\t\tATNState right = newState(node);\n\t\tleft.addTransition(new WildcardTransition(right));\n\t\tnode.atnState = left;\n\t\treturn new Handle(left, right);\n\t}\n\n\tprotected void epsilon(ATNState a, ATNState b) {\n\t\tepsilon(a, b, false);\n\t}\n\n\tprotected void epsilon(ATNState a, ATNState b, boolean prepend) {\n\t\tif ( a!=null ) {\n\t\t\tint index = prepend ? 0 : a.getNumberOfTransitions();\n\t\t\ta.addTransition(index, new EpsilonTransition(b));\n\t\t}\n\t}\n\n\t/** Define all the rule begin/end ATNStates to solve forward reference\n\t *  issues.\n\t */\n\tvoid createRuleStartAndStopATNStates() {\n\t\tatn.ruleToStartState = new RuleStartState[g.rules.size()];\n\t\tatn.ruleToStopState = new RuleStopState[g.rules.size()];\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tRuleStartState start = newState(RuleStartState.class, r.ast);\n\t\t\tRuleStopState stop = newState(RuleStopState.class, r.ast);\n\t\t\tstart.stopState = stop;\n\t\t\tstart.isLeftRecursiveRule = r instanceof LeftRecursiveRule;\n\t\t\tstart.setRuleIndex(r.index);\n\t\t\tstop.setRuleIndex(r.index);\n\t\t\tatn.ruleToStartState[r.index] = start;\n\t\t\tatn.ruleToStopState[r.index] = stop;\n\t\t}\n\t}\n\n    public void addRuleFollowLinks() {\n        for (ATNState p : atn.states) {\n            if ( p!=null &&\n                 p.getStateType() == ATNState.BASIC && p.getNumberOfTransitions()==1 &&\n                 p.transition(0) instanceof RuleTransition )\n            {\n                RuleTransition rt = (RuleTransition) p.transition(0);\n                addFollowLink(rt.ruleIndex, rt.followState);\n            }\n        }\n    }\n\n\t/** Add an EOF transition to any rule end ATNState that points to nothing\n     *  (i.e., for all those rules not invoked by another rule).  These\n     *  are start symbols then.\n\t *\n\t *  Return the number of grammar entry points; i.e., how many rules are\n\t *  not invoked by another rule (they can only be invoked from outside).\n\t *  These are the start rules.\n     */\n\tpublic int addEOFTransitionToStartRules() {\n\t\tint n = 0;\n\t\tATNState eofTarget = newState(null); // one unique EOF target for all rules\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tATNState stop = atn.ruleToStopState[r.index];\n\t\t\tif ( stop.getNumberOfTransitions()>0 ) continue;\n\t\t\tn++;\n\t\t\tTransition t = new AtomTransition(eofTarget, Token.EOF);\n\t\t\tstop.addTransition(t);\n\t\t}\n\t\treturn n;\n\t}\n\n\n\t@Override\n\tpublic Handle label(Handle t) {\n\t\treturn t;\n\t}\n\n\n\t@Override\n\tpublic Handle listLabel(Handle t) {\n\t\treturn t;\n\t}\n\n\n\tpublic <T extends ATNState> T newState(Class<T> nodeType, GrammarAST node) {\n\t\tException cause;\n\t\ttry {\n\t\t\tConstructor<T> ctor = nodeType.getConstructor();\n\t\t\tT s = ctor.newInstance();\n\t\t\tif ( currentRule==null ) s.setRuleIndex(-1);\n\t\t\telse s.setRuleIndex(currentRule.index);\n\t\t\tatn.addState(s);\n\t\t\treturn s;\n\t\t} catch (InstantiationException ex) {\n\t\t\tcause = ex;\n\t\t} catch (IllegalAccessException ex) {\n\t\t\tcause = ex;\n\t\t} catch (IllegalArgumentException ex) {\n\t\t\tcause = ex;\n\t\t} catch (InvocationTargetException ex) {\n\t\t\tcause = ex;\n\t\t} catch (NoSuchMethodException ex) {\n\t\t\tcause = ex;\n\t\t} catch (SecurityException ex) {\n\t\t\tcause = ex;\n\t\t}\n\n\t\tString message = String.format(\"Could not create %s of type %s.\", ATNState.class.getName(), nodeType.getName());\n\t\tthrow new UnsupportedOperationException(message, cause);\n\t}\n\n\n\tpublic ATNState newState(GrammarAST node) {\n\t\tATNState n = new BasicState();\n\t\tn.setRuleIndex(currentRule.index);\n\t\tatn.addState(n);\n\t\treturn n;\n\t}\n\n\n\t@Override\n\tpublic ATNState newState() { return newState(null); }\n\n\tpublic boolean expectNonGreedy(BlockAST blkAST) {\n\t\tif ( blockHasWildcardAlt(blkAST) ) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * {@code (BLOCK (ALT .))} or {@code (BLOCK (ALT 'a') (ALT .))}.\n\t */\n\tpublic static boolean blockHasWildcardAlt(GrammarAST block) {\n\t\tfor (Object alt : block.getChildren()) {\n\t\t\tif ( !(alt instanceof AltAST) ) continue;\n\t\t\tAltAST altAST = (AltAST)alt;\n\t\t\tif ( altAST.getChildCount()==1 || (altAST.getChildCount() == 2 && altAST.getChild(0).getType() == ANTLRParser.ELEMENT_OPTIONS) ) {\n\t\t\t\tTree e = altAST.getChild(altAST.getChildCount() - 1);\n\t\t\t\tif ( e.getType()==ANTLRParser.WILDCARD ) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\n\t@Override\n\tpublic Handle lexerAltCommands(Handle alt, Handle cmds) {\n\t\tthrow new UnsupportedOperationException(\"This element is not allowed in parsers.\");\n\t}\n\n\n\t@Override\n\tpublic Handle lexerCallCommand(GrammarAST ID, GrammarAST arg) {\n\t\tthrow new UnsupportedOperationException(\"This element is not allowed in parsers.\");\n\t}\n\n\n\t@Override\n\tpublic Handle lexerCommand(GrammarAST ID) {\n\t\tthrow new UnsupportedOperationException(\"This element is not allowed in parsers.\");\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/RangeBorderCharactersData.java",
    "content": "package org.antlr.v4.automata;\n\nimport org.antlr.runtime.tree.CommonTree;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\n\npublic class RangeBorderCharactersData {\n\tpublic final int lowerFrom;\n\tpublic final int upperFrom;\n\tpublic final int lowerTo;\n\tpublic final int upperTo;\n\tpublic final boolean mixOfLowerAndUpperCharCase;\n\n\tpublic RangeBorderCharactersData(int lowerFrom, int upperFrom, int lowerTo, int upperTo, boolean mixOfLowerAndUpperCharCase) {\n\t\tthis.lowerFrom = lowerFrom;\n\t\tthis.upperFrom = upperFrom;\n\t\tthis.lowerTo = lowerTo;\n\t\tthis.upperTo = upperTo;\n\t\tthis.mixOfLowerAndUpperCharCase = mixOfLowerAndUpperCharCase;\n\t}\n\n\tpublic static RangeBorderCharactersData getAndCheckCharactersData(int from, int to, Grammar grammar, CommonTree tree,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  boolean reportRangeContainsNotImpliedCharacters\n\t) {\n\t\tint lowerFrom = Character.toLowerCase(from);\n\t\tint upperFrom = Character.toUpperCase(from);\n\t\tint lowerTo = Character.toLowerCase(to);\n\t\tint upperTo = Character.toUpperCase(to);\n\n\t\tboolean isLowerFrom = lowerFrom == from;\n\t\tboolean isLowerTo = lowerTo == to;\n\t\tboolean mixOfLowerAndUpperCharCase = isLowerFrom && !isLowerTo || !isLowerFrom && isLowerTo;\n\t\tif (reportRangeContainsNotImpliedCharacters && mixOfLowerAndUpperCharCase && from <= 0x7F && to <= 0x7F) {\n\t\t\tStringBuilder notImpliedCharacters = new StringBuilder();\n\t\t\tfor (int i = from; i < to; i++) {\n\t\t\t\tif (!Character.isAlphabetic(i)) {\n\t\t\t\t\tnotImpliedCharacters.append((char)i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (notImpliedCharacters.length() > 0) {\n\t\t\t\tgrammar.tool.errMgr.grammarError(ErrorType.RANGE_PROBABLY_CONTAINS_NOT_IMPLIED_CHARACTERS, grammar.fileName, tree.getToken(),\n\t\t\t\t\t\t(char) from, (char) to, notImpliedCharacters.toString());\n\t\t\t}\n\t\t}\n\t\treturn new RangeBorderCharactersData(lowerFrom, upperFrom, lowerTo, upperTo, mixOfLowerAndUpperCharCase);\n\t}\n\n\tpublic boolean isSingleRange() {\n\t\treturn lowerFrom == upperFrom && lowerTo == upperTo ||\n\t\t\t\tmixOfLowerAndUpperCharCase ||\n\t\t\t\tlowerTo - lowerFrom != upperTo - upperFrom;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/automata/TailEpsilonRemover.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.automata;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.BlockEndState;\nimport org.antlr.v4.runtime.atn.EpsilonTransition;\nimport org.antlr.v4.runtime.atn.PlusLoopbackState;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.StarLoopbackState;\nimport org.antlr.v4.runtime.atn.Transition;\n\n/**\n *\n * @author Terence Parr\n */\npublic class TailEpsilonRemover extends ATNVisitor {\n\n\tprivate final ATN _atn;\n\n\tpublic TailEpsilonRemover(ATN atn) {\n\t\tthis._atn = atn;\n\t}\n\n\t@Override\n\tpublic void visitState(ATNState p) {\n\t\tif (p.getStateType() == ATNState.BASIC && p.getNumberOfTransitions() == 1) {\n\t\t\tATNState q = p.transition(0).target;\n\t\t\tif (p.transition(0) instanceof RuleTransition) {\n\t\t\t\tq = ((RuleTransition) p.transition(0)).followState;\n\t\t\t}\n\t\t\tif (q.getStateType() == ATNState.BASIC) {\n\t\t\t\t// we have p-x->q for x in {rule, action, pred, token, ...}\n\t\t\t\t// if edge out of q is single epsilon to block end\n\t\t\t\t// we can strip epsilon p-x->q-eps->r\n\t\t\t\tTransition trans = q.transition(0);\n\t\t\t\tif (q.getNumberOfTransitions() == 1 && trans instanceof EpsilonTransition) {\n\t\t\t\t\tATNState r = trans.target;\n\t\t\t\t\tif (r instanceof BlockEndState || r instanceof PlusLoopbackState || r instanceof StarLoopbackState) {\n\t\t\t\t\t\t// skip over q\n\t\t\t\t\t\tif (p.transition(0) instanceof RuleTransition) {\n\t\t\t\t\t\t\t((RuleTransition) p.transition(0)).followState = r;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tp.transition(0).target = r;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_atn.removeState(q);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/ActionTranslator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.chunk.ActionChunk;\nimport org.antlr.v4.codegen.model.chunk.ActionText;\nimport org.antlr.v4.codegen.model.chunk.ArgRef;\nimport org.antlr.v4.codegen.model.chunk.LabelRef;\nimport org.antlr.v4.codegen.model.chunk.ListLabelRef;\nimport org.antlr.v4.codegen.model.chunk.LocalRef;\nimport org.antlr.v4.codegen.model.chunk.NonLocalAttrRef;\nimport org.antlr.v4.codegen.model.chunk.QRetValueRef;\nimport org.antlr.v4.codegen.model.chunk.RetValueRef;\nimport org.antlr.v4.codegen.model.chunk.RulePropertyRef;\nimport org.antlr.v4.codegen.model.chunk.RulePropertyRef_ctx;\nimport org.antlr.v4.codegen.model.chunk.RulePropertyRef_parser;\nimport org.antlr.v4.codegen.model.chunk.RulePropertyRef_start;\nimport org.antlr.v4.codegen.model.chunk.RulePropertyRef_stop;\nimport org.antlr.v4.codegen.model.chunk.RulePropertyRef_text;\nimport org.antlr.v4.codegen.model.chunk.SetAttr;\nimport org.antlr.v4.codegen.model.chunk.SetNonLocalAttr;\nimport org.antlr.v4.codegen.model.chunk.ThisRulePropertyRef_ctx;\nimport org.antlr.v4.codegen.model.chunk.ThisRulePropertyRef_parser;\nimport org.antlr.v4.codegen.model.chunk.ThisRulePropertyRef_start;\nimport org.antlr.v4.codegen.model.chunk.ThisRulePropertyRef_stop;\nimport org.antlr.v4.codegen.model.chunk.ThisRulePropertyRef_text;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef_channel;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef_index;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef_int;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef_line;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef_pos;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef_text;\nimport org.antlr.v4.codegen.model.chunk.TokenPropertyRef_type;\nimport org.antlr.v4.codegen.model.chunk.TokenRef;\nimport org.antlr.v4.codegen.model.decl.StructDecl;\nimport org.antlr.v4.parse.ActionSplitter;\nimport org.antlr.v4.parse.ActionSplitterListener;\nimport org.antlr.v4.tool.Attribute;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\n\nimport java.lang.reflect.Constructor;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** */\npublic class ActionTranslator implements ActionSplitterListener {\n\tpublic static final Map<String, Class<? extends RulePropertyRef>> thisRulePropToModelMap =\n\t\tnew HashMap<String, Class<? extends RulePropertyRef>>();\n\tstatic {\n\t\tthisRulePropToModelMap.put(\"start\", ThisRulePropertyRef_start.class);\n\t\tthisRulePropToModelMap.put(\"stop\",  ThisRulePropertyRef_stop.class);\n\t\tthisRulePropToModelMap.put(\"text\",  ThisRulePropertyRef_text.class);\n\t\tthisRulePropToModelMap.put(\"ctx\",   ThisRulePropertyRef_ctx.class);\n\t\tthisRulePropToModelMap.put(\"parser\",  ThisRulePropertyRef_parser.class);\n\t}\n\n\tpublic static final Map<String, Class<? extends RulePropertyRef>> rulePropToModelMap =\n\t\tnew HashMap<String, Class<? extends RulePropertyRef>>();\n\tstatic {\n\t\trulePropToModelMap.put(\"start\", RulePropertyRef_start.class);\n\t\trulePropToModelMap.put(\"stop\",  RulePropertyRef_stop.class);\n\t\trulePropToModelMap.put(\"text\",  RulePropertyRef_text.class);\n\t\trulePropToModelMap.put(\"ctx\",   RulePropertyRef_ctx.class);\n\t\trulePropToModelMap.put(\"parser\",  RulePropertyRef_parser.class);\n\t}\n\n\tpublic static final Map<String, Class<? extends TokenPropertyRef>> tokenPropToModelMap =\n\t\tnew HashMap<String, Class<? extends TokenPropertyRef>>();\n\tstatic {\n\t\ttokenPropToModelMap.put(\"text\",  TokenPropertyRef_text.class);\n\t\ttokenPropToModelMap.put(\"type\",  TokenPropertyRef_type.class);\n\t\ttokenPropToModelMap.put(\"line\",  TokenPropertyRef_line.class);\n\t\ttokenPropToModelMap.put(\"index\", TokenPropertyRef_index.class);\n\t\ttokenPropToModelMap.put(\"pos\",   TokenPropertyRef_pos.class);\n\t\ttokenPropToModelMap.put(\"channel\", TokenPropertyRef_channel.class);\n\t\ttokenPropToModelMap.put(\"int\",   TokenPropertyRef_int.class);\n\t}\n\n\tfinal CodeGenerator gen;\n\tfinal Target target;\n\tfinal ActionAST node;\n\tRuleFunction rf;\n\tfinal List<ActionChunk> chunks = new ArrayList<ActionChunk>();\n\tfinal OutputModelFactory factory;\n\tStructDecl nodeContext;\n\n\tpublic ActionTranslator(OutputModelFactory factory, ActionAST node) {\n\t\tthis.factory = factory;\n\t\tthis.node = node;\n\t\tthis.gen = factory.getGenerator();\n\t\tthis.target = gen.getTarget();\n\t}\n\n\tpublic static String toString(List<ActionChunk> chunks) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (ActionChunk c : chunks) buf.append(c.toString());\n\t\treturn buf.toString();\n\t}\n\n\tpublic static List<ActionChunk> translateAction(OutputModelFactory factory,\n\t\t\t\t\t\t\t\t\t\t\t\t\tRuleFunction rf,\n\t\t\t\t\t\t\t\t\t\t\t\t\tToken tokenWithinAction,\n\t\t\t\t\t\t\t\t\t\t\t\t\tActionAST node)\n\t{\n\t\tString action = tokenWithinAction.getText();\n\t\tif ( action!=null && action.length()>0 && action.charAt(0)=='{' ) {\n\t\t\tint firstCurly = action.indexOf('{');\n\t\t\tint lastCurly = action.lastIndexOf('}');\n\t\t\tif ( firstCurly>=0 && lastCurly>=0 ) {\n\t\t\t\taction = action.substring(firstCurly+1, lastCurly); // trim {...}\n\t\t\t}\n\t\t}\n\t\treturn translateActionChunk(factory, rf, action, node);\n\t}\n\n\tpublic static List<ActionChunk> translateActionChunk(OutputModelFactory factory,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t RuleFunction rf,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t String action,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ActionAST node)\n\t{\n\t\tToken tokenWithinAction = node.token;\n\t\tActionTranslator translator = new ActionTranslator(factory, node);\n\t\ttranslator.rf = rf;\n        factory.getGrammar().tool.log(\"action-translator\", \"translate \" + action);\n\t\tString altLabel = node.getAltLabel();\n\t\tif ( rf!=null ) {\n\t\t    translator.nodeContext = rf.ruleCtx;\n\t        if ( altLabel!=null ) translator.nodeContext = rf.altLabelCtxs.get(altLabel);\n\t\t}\n\t\tANTLRStringStream in = new ANTLRStringStream(action);\n\t\tin.setLine(tokenWithinAction.getLine());\n\t\tin.setCharPositionInLine(tokenWithinAction.getCharPositionInLine());\n\t\tActionSplitter trigger = new ActionSplitter(in, translator);\n\t\t// forces eval, triggers listener methods\n\t\ttrigger.getActionTokens();\n\t\treturn translator.chunks;\n\t}\n\n\t@Override\n\tpublic void attr(String expr, Token x) {\n\t\tgen.g.tool.log(\"action-translator\", \"attr \"+x);\n\t\tAttribute a = node.resolver.resolveToAttribute(x.getText(), node);\n\t\tString name = x.getText();\n\t\tString escapedName = target.escapeIfNeeded(name);\n\t\tif ( a!=null ) {\n\t\t\tswitch ( a.dict.type ) {\n\t\t\t\tcase ARG:\n\t\t\t\t\tchunks.add(new ArgRef(nodeContext, name, escapedName));\n\t\t\t\t\tbreak;\n\t\t\t\tcase RET:\n\t\t\t\t\tchunks.add(new RetValueRef(rf.ruleCtx, name, escapedName));\n\t\t\t\t\tbreak;\n\t\t\t\tcase LOCAL:\n\t\t\t\t\tchunks.add(new LocalRef(nodeContext, name, escapedName));\n\t\t\t\t\tbreak;\n\t\t\t\tcase PREDEFINED_RULE:\n\t\t\t\t\tchunks.add(getRulePropertyRef(null, x));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif ( node.resolver.resolvesToToken(name, node) ) {\n\t\t\tString tokenLabel = getTokenLabel(name);\n\t\t\tchunks.add(new TokenRef(nodeContext, tokenLabel, target.escapeIfNeeded(tokenLabel))); // $label\n\t\t\treturn;\n\t\t}\n\t\tif ( node.resolver.resolvesToLabel(name, node) ) {\n\t\t\tString tokenLabel = getTokenLabel(name);\n\t\t\tchunks.add(new LabelRef(nodeContext, tokenLabel, target.escapeIfNeeded(tokenLabel))); // $x for x=ID etc...\n\t\t\treturn;\n\t\t}\n\t\tif ( node.resolver.resolvesToListLabel(name, node) ) {\n\t\t\tchunks.add(new ListLabelRef(nodeContext, name, escapedName)); // $ids for ids+=ID etc...\n\t\t\treturn;\n\t\t}\n\t\tRule r = factory.getGrammar().getRule(name);\n\t\tif ( r!=null ) {\n\t\t\tString ruleLabel = getRuleLabel(name);\n\t\t\tchunks.add(new LabelRef(nodeContext, ruleLabel, target.escapeIfNeeded(ruleLabel))); // $r for r rule ref\n\t\t}\n\t}\n\n\t@Override\n\tpublic void qualifiedAttr(String expr, Token x, Token y) {\n\t\tgen.g.tool.log(\"action-translator\", \"qattr \"+x+\".\"+y);\n\t\tif ( node.resolver.resolveToAttribute(x.getText(), node)!=null ) {\n\t\t\t// must be a member access to a predefined attribute like $ctx.foo\n\t\t\tattr(expr, x);\n\t\t\tchunks.add(new ActionText(nodeContext, \".\"+y.getText()));\n\t\t\treturn;\n\t\t}\n\t\tAttribute a = node.resolver.resolveToAttribute(x.getText(), y.getText(), node);\n\t\tif ( a==null ) {\n\t\t\t// Added in response to https://github.com/antlr/antlr4/issues/1211\n\t\t\tgen.g.tool.errMgr.grammarError(ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE,\n\t\t\t                               gen.g.fileName, x,\n\t\t\t                               x.getText(),\n\t\t\t                               \"rule\");\n\t\t\treturn;\n\t\t}\n\t\tswitch ( a.dict.type ) {\n\t\t\tcase ARG: chunks.add(new ArgRef(nodeContext, y.getText(), target.escapeIfNeeded(y.getText()))); break; // has to be current rule\n\t\t\tcase RET:\n\t\t\t\tchunks.add(new QRetValueRef(nodeContext, getRuleLabel(x.getText()), y.getText(), target.escapeIfNeeded(y.getText())));\n\t\t\t\tbreak;\n\t\t\tcase PREDEFINED_RULE:\n\t\t\t\tchunks.add(getRulePropertyRef(x, y));\n\t\t\t\tbreak;\n\t\t\tcase TOKEN:\n\t\t\t\tchunks.add(getTokenPropertyRef(x, y));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setAttr(String expr, Token x, Token rhs) {\n\t\tgen.g.tool.log(\"action-translator\", \"setAttr \"+x+\" \"+rhs);\n\t\tList<ActionChunk> rhsChunks = translateActionChunk(factory,rf,rhs.getText(),node);\n\t\tString name = x.getText();\n\t\tSetAttr s = new SetAttr(nodeContext, name, target.escapeIfNeeded(name), rhsChunks);\n\t\tchunks.add(s);\n\t}\n\n\t@Override\n\tpublic void nonLocalAttr(String expr, Token x, Token y) {\n\t\tgen.g.tool.log(\"action-translator\", \"nonLocalAttr \"+x+\"::\"+y);\n\t\tRule r = factory.getGrammar().getRule(x.getText());\n\t\tString name = y.getText();\n\t\tchunks.add(new NonLocalAttrRef(nodeContext, x.getText(), name, target.escapeIfNeeded(name), r.index));\n\t}\n\n\t@Override\n\tpublic void setNonLocalAttr(String expr, Token x, Token y, Token rhs) {\n\t\tgen.g.tool.log(\"action-translator\", \"setNonLocalAttr \"+x+\"::\"+y+\"=\"+rhs);\n\t\tRule r = factory.getGrammar().getRule(x.getText());\n\t\tList<ActionChunk> rhsChunks = translateActionChunk(factory,rf,rhs.getText(),node);\n\t\tString name = y.getText();\n\t\tSetNonLocalAttr s = new SetNonLocalAttr(nodeContext, x.getText(), name, target.escapeIfNeeded(name), r.index, rhsChunks);\n\t\tchunks.add(s);\n\t}\n\n\t@Override\n\tpublic void text(String text) {\n\t\tchunks.add(new ActionText(nodeContext,text));\n\t}\n\n\tTokenPropertyRef getTokenPropertyRef(Token x, Token y) {\n\t\ttry {\n\t\t\tClass<? extends TokenPropertyRef> c = tokenPropToModelMap.get(y.getText());\n\t\t\tConstructor<? extends TokenPropertyRef> ctor = c.getConstructor(StructDecl.class, String.class);\n\t\t\treturn ctor.newInstance(nodeContext, getTokenLabel(x.getText()));\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tfactory.getGrammar().tool.errMgr.toolError(ErrorType.INTERNAL_ERROR, e);\n\t\t}\n\t\treturn null;\n\t}\n\n\tRulePropertyRef getRulePropertyRef(Token x, Token prop) {\n\t\ttry {\n\t\t\tClass<? extends RulePropertyRef> c = (x != null ? rulePropToModelMap : thisRulePropToModelMap).get(prop.getText());\n\t\t\tConstructor<? extends RulePropertyRef> ctor = c.getConstructor(StructDecl.class, String.class);\n\t\t\treturn ctor.newInstance(nodeContext, getRuleLabel((x != null ? x : prop).getText()));\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tfactory.getGrammar().tool.errMgr.toolError(ErrorType.INTERNAL_ERROR, e, prop.getText());\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic String getTokenLabel(String x) {\n\t\tif ( node.resolver.resolvesToLabel(x, node) ) return x;\n\t\treturn target.getImplicitTokenLabel(x);\n\t}\n\n\tpublic String getRuleLabel(String x) {\n\t\tif ( node.resolver.resolvesToLabel(x, node) ) return x;\n\t\treturn target.getImplicitRuleLabel(x);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/BlankOutputModelFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.codegen.model.Choice;\nimport org.antlr.v4.codegen.model.CodeBlockForAlt;\nimport org.antlr.v4.codegen.model.LabeledOp;\nimport org.antlr.v4.codegen.model.Lexer;\nimport org.antlr.v4.codegen.model.LexerFile;\nimport org.antlr.v4.codegen.model.Parser;\nimport org.antlr.v4.codegen.model.ParserFile;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.SrcOp;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\npublic abstract class BlankOutputModelFactory implements OutputModelFactory {\n\t@Override\n\tpublic ParserFile parserFile(String fileName) { return null; }\n\n\t@Override\n\tpublic Parser parser(ParserFile file) { return null; }\n\n\t@Override\n\tpublic RuleFunction rule(Rule r) { return null; }\n\n\t@Override\n\tpublic List<SrcOp> rulePostamble(RuleFunction function, Rule r) { return null; }\n\n\t@Override\n\tpublic LexerFile lexerFile(String fileName) { return null; }\n\n\t@Override\n\tpublic Lexer lexer(LexerFile file) { return null; }\n\n\t// ALTERNATIVES / ELEMENTS\n\n\t@Override\n\tpublic CodeBlockForAlt alternative(Alternative alt, boolean outerMost) { return null; }\n\n\t@Override\n\tpublic CodeBlockForAlt finishAlternative(CodeBlockForAlt blk, List<SrcOp> ops) { return blk; }\n\n\t@Override\n\tpublic CodeBlockForAlt epsilon(Alternative alt, boolean outerMost) { return null; }\n\n\t@Override\n\tpublic List<SrcOp> ruleRef(GrammarAST ID, GrammarAST label, GrammarAST args) { return null; }\n\n\t@Override\n\tpublic List<SrcOp> tokenRef(GrammarAST ID, GrammarAST label, GrammarAST args) { return null; }\n\n\t@Override\n\tpublic List<SrcOp> stringRef(GrammarAST ID, GrammarAST label) { return tokenRef(ID, label, null); }\n\n\t@Override\n\tpublic List<SrcOp> set(GrammarAST setAST, GrammarAST label, boolean invert) {\treturn null; }\n\n\t@Override\n\tpublic List<SrcOp> wildcard(GrammarAST ast, GrammarAST labelAST) { return null; }\n\n\t// ACTIONS\n\n\t@Override\n\tpublic List<SrcOp> action(ActionAST ast) { return null; }\n\n\t@Override\n\tpublic List<SrcOp> sempred(ActionAST ast) { return null; }\n\n\t// BLOCKS\n\n\t@Override\n\tpublic Choice getChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts, GrammarAST label) { return null; }\n\n\t@Override\n\tpublic Choice getEBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) { return null; }\n\n\t@Override\n\tpublic Choice getLL1ChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts) { return null; }\n\n\t@Override\n\tpublic Choice getComplexChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts) { return null; }\n\n\t@Override\n\tpublic Choice getLL1EBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) { return null; }\n\n\t@Override\n\tpublic Choice getComplexEBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) { return null; }\n\n\t@Override\n\tpublic List<SrcOp> getLL1Test(IntervalSet look, GrammarAST blkAST) { return null; }\n\n\t@Override\n\tpublic boolean needsImplicitLabel(GrammarAST ID, LabeledOp op) { return false; }\n}\n\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/CodeGenPipeline.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.gui.STViz;\n\npublic class CodeGenPipeline {\n\tfinal Grammar g;\n\tfinal CodeGenerator gen;\n\n\tpublic CodeGenPipeline(Grammar g, CodeGenerator gen) {\n\t\tthis.g = g;\n\t\tthis.gen = gen;\n\t}\n\n\tpublic void process() {\n\t\t// all templates are generated in memory to report the most complete\n\t\t// error information possible, but actually writing output files stops\n\t\t// after the first error is reported\n\t\tint errorCount = g.tool.errMgr.getNumErrors();\n\n\t\tif ( g.isLexer() ) {\n\t\t\tif (gen.getTarget().needsHeader()) {\n\t\t\t\tST lexer = gen.generateLexer(SourceType.HEADER); // Header file if needed.\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\twriteRecognizer(lexer, gen, SourceType.HEADER);\n\t\t\t\t}\n\t\t\t}\n\t\t\tST lexer = gen.generateLexer(SourceType.SOURCE);\n\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\twriteRecognizer(lexer, gen, SourceType.SOURCE);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (gen.getTarget().needsHeader()) {\n\t\t\t\tST parser = gen.generateParser(SourceType.HEADER);\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\twriteRecognizer(parser, gen, SourceType.HEADER);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( gen.getTarget().supportsSplitParser() && g.tool.gen_split_parser) {\n\t\t\t\tST parser = gen.generateParser(SourceType.SOURCE_LEAN);\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\twriteRecognizer(parser, gen, SourceType.SOURCE_LEAN);\n\t\t\t\t}\n\t\t\t\tparser = gen.generateParser(SourceType.SOURCE_CONTEXTS);\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\twriteRecognizer(parser, gen, SourceType.SOURCE_CONTEXTS);\n\t\t\t\t}\n\t\t\t\tparser = gen.generateParser(SourceType.SOURCE_DFA);\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\twriteRecognizer(parser, gen, SourceType.SOURCE_DFA);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tST parser = gen.generateParser(SourceType.SOURCE);\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\twriteRecognizer(parser, gen, SourceType.SOURCE);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tSourceType sourceType = gen.getTarget().supportsSplitParser() && g.tool.gen_split_parser ? SourceType.SOURCE_LEAN : SourceType.SOURCE;\n\n\t\t\tif ( g.tool.gen_listener ) {\n\t\t\t\tif (gen.getTarget().needsHeader()) {\n\t\t\t\t\tST listener = gen.generateListener(SourceType.HEADER);\n\t\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\t\tgen.writeListener(listener, SourceType.HEADER);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tST listener = gen.generateListener(sourceType);\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\tgen.writeListener(listener, sourceType);\n\t\t\t\t}\n\n\t\t\t\tif (gen.getTarget().needsHeader()) {\n\t\t\t\t\tST baseListener = gen.generateBaseListener(SourceType.HEADER);\n\t\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\t\tgen.writeBaseListener(baseListener, SourceType.HEADER);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (gen.getTarget().wantsBaseListener()) {\n\t\t\t\t\tST baseListener = gen.generateBaseListener(sourceType);\n\t\t\t\t\tif ( g.tool.errMgr.getNumErrors()==errorCount ) {\n\t\t\t\t\t\tgen.writeBaseListener(baseListener, sourceType);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( g.tool.gen_visitor ) {\n\t\t\t\tif (gen.getTarget().needsHeader()) {\n\t\t\t\t\tST visitor = gen.generateVisitor(SourceType.HEADER);\n\t\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\t\tgen.writeVisitor(visitor, SourceType.HEADER);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tST visitor = gen.generateVisitor(sourceType);\n\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\tgen.writeVisitor(visitor, sourceType);\n\t\t\t\t}\n\n\t\t\t\tif (gen.getTarget().needsHeader()) {\n\t\t\t\t\tST baseVisitor = gen.generateBaseVisitor(SourceType.HEADER);\n\t\t\t\t\tif (g.tool.errMgr.getNumErrors() == errorCount) {\n\t\t\t\t\t\tgen.writeBaseVisitor(baseVisitor, SourceType.HEADER);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (gen.getTarget().wantsBaseVisitor()) {\n\t\t\t\t\tST baseVisitor = gen.generateBaseVisitor(sourceType);\n\t\t\t\t\tif ( g.tool.errMgr.getNumErrors()==errorCount ) {\n\t\t\t\t\t\tgen.writeBaseVisitor(baseVisitor, sourceType);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgen.writeVocabFile();\n\t}\n\n\tprotected void writeRecognizer(ST template, CodeGenerator gen, SourceType sourceType) {\n\t\tif ( g.tool.launch_ST_inspector ) {\n\t\t\tSTViz viz = template.inspect();\n\t\t\tif (g.tool.ST_inspector_wait_for_close) {\n\t\t\t\ttry {\n\t\t\t\t\tviz.waitForClose();\n\t\t\t\t}\n\t\t\t\tcatch (InterruptedException ex) {\n\t\t\t\t\tg.tool.errMgr.toolError(ErrorType.INTERNAL_ERROR, ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tgen.writeRecognizer(template, sourceType);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/CodeGenerator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.model.OutputModelObject;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.stringtemplate.v4.AutoIndentWriter;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STWriter;\n\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.lang.reflect.Constructor;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\n/** General controller for code gen.  Can instantiate sub generator(s).\n */\npublic class CodeGenerator {\n\tpublic static final String TEMPLATE_ROOT = \"org/antlr/v4/tool/templates/codegen\";\n\tpublic static final String VOCAB_FILE_EXTENSION = \".tokens\";\n\tpublic static final String vocabFilePattern =\n\t\t\"<tokens.keys:{t | <t>=<tokens.(t)>\\n}>\" +\n\t\t\"<literals.keys:{t | <t>=<literals.(t)>\\n}>\";\n\n\tpublic final Grammar g;\n\n\tpublic final Tool tool;\n\n\tpublic final String language;\n\n\tprivate Target target;\n\n\tpublic int lineWidth = 72;\n\n\tpublic static CodeGenerator create(Grammar g) {\n\t\treturn create(g.tool, g, g.getLanguage());\n\t}\n\n\tpublic static CodeGenerator create(Tool tool, Grammar g, String language) {\n\t\tString targetName = \"org.antlr.v4.codegen.target.\"+language+\"Target\";\n\t\ttry {\n\t\t\tClass<? extends Target> c = Class.forName(targetName).asSubclass(Target.class);\n\t\t\tConstructor<? extends Target> ctor = c.getConstructor(CodeGenerator.class);\n\t\t\tCodeGenerator codeGenerator = new CodeGenerator(tool, g, language);\n\t\t\tcodeGenerator.target = ctor.newInstance(codeGenerator);\n\t\t\treturn codeGenerator;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tg.tool.errMgr.toolError(ErrorType.CANNOT_CREATE_TARGET_GENERATOR, e, language);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate CodeGenerator(Tool tool, Grammar g, String language) {\n\t\tthis.g = g;\n\t\tthis.tool = tool;\n\t\tthis.language = language;\n\t}\n\n\tpublic Target getTarget() {\n\t\treturn target;\n\t}\n\n\tpublic STGroup getTemplates() {\n\t\treturn target.getTemplates();\n\t}\n\n\t// CREATE TEMPLATES BY WALKING MODEL\n\n\tprivate OutputModelController createController() {\n\t\tOutputModelFactory factory = new ParserFactory(this);\n\t\tOutputModelController controller = new OutputModelController(factory);\n\t\tfactory.setController(controller);\n\t\treturn controller;\n\t}\n\n\tprivate ST walk(OutputModelObject outputModel, SourceType sourceType) {\n\t\tOutputModelWalker walker = new OutputModelWalker(tool, getTemplates());\n\t\treturn walker.walk(outputModel, sourceType);\n\t}\n\n\tpublic ST generateLexer() { return generateLexer(SourceType.SOURCE); }\n\tpublic ST generateLexer(SourceType sourceType) { return walk(createController().buildLexerOutputModel(sourceType), sourceType); }\n\n\tpublic ST generateParser() { return generateParser(SourceType.SOURCE); }\n\tpublic ST generateParser(SourceType sourceType) { return walk(createController().buildParserOutputModel(sourceType), sourceType); }\n\n\tpublic ST generateListener() { return generateListener(SourceType.SOURCE); }\n\tpublic ST generateListener(SourceType sourceType) { return walk(createController().buildListenerOutputModel(sourceType), sourceType); }\n\n\tpublic ST generateBaseListener() { return generateBaseListener(SourceType.SOURCE); }\n\tpublic ST generateBaseListener(SourceType sourceType) { return walk(createController().buildBaseListenerOutputModel(sourceType), sourceType); }\n\n\tpublic ST generateVisitor() { return generateVisitor(SourceType.SOURCE); }\n\tpublic ST generateVisitor(SourceType sourceType) { return walk(createController().buildVisitorOutputModel(sourceType), sourceType); }\n\n\tpublic ST generateBaseVisitor() { return generateBaseVisitor(SourceType.SOURCE); }\n\tpublic ST generateBaseVisitor(SourceType sourceType) { return walk(createController().buildBaseVisitorOutputModel(sourceType), sourceType); }\n\n\t/** Generate a token vocab file with all the token names/types.  For example:\n\t *  ID=7\n\t *  FOR=8\n\t *  'for'=8\n\t *\n\t *  This is independent of the target language; used by antlr internally\n\t */\n\tST getTokenVocabOutput() {\n\t\tST vocabFileST = new ST(vocabFilePattern);\n\t\tMap<String,Integer> tokens = new LinkedHashMap<String,Integer>();\n\t\t// make constants for the token names\n\t\tfor (String t : g.tokenNameToTypeMap.keySet()) {\n\t\t\tint tokenType = g.tokenNameToTypeMap.get(t);\n\t\t\tif ( tokenType>=Token.MIN_USER_TOKEN_TYPE) {\n\t\t\t\ttokens.put(t, tokenType);\n\t\t\t}\n\t\t}\n\t\tvocabFileST.add(\"tokens\", tokens);\n\n\t\t// now dump the strings\n\t\tMap<String,Integer> literals = new LinkedHashMap<String,Integer>();\n\t\tfor (String literal : g.stringLiteralToTypeMap.keySet()) {\n\t\t\tint tokenType = g.stringLiteralToTypeMap.get(literal);\n\t\t\tif ( tokenType>=Token.MIN_USER_TOKEN_TYPE) {\n\t\t\t\tliterals.put(literal, tokenType);\n\t\t\t}\n\t\t}\n\t\tvocabFileST.add(\"literals\", literals);\n\n\t\treturn vocabFileST;\n\t}\n\n\tpublic void writeRecognizer(ST outputFileST, SourceType sourceType) {\n\t\ttarget.genFile(g, outputFileST, getRecognizerFileName(sourceType));\n\t}\n\n\tpublic void writeListener(ST outputFileST, SourceType sourceType) {\n\t\ttarget.genFile(g, outputFileST, getListenerFileName(sourceType));\n\t}\n\n\tpublic void writeBaseListener(ST outputFileST, SourceType sourceType) {\n\t\ttarget.genFile(g, outputFileST, getBaseListenerFileName(sourceType));\n\t}\n\n\tpublic void writeVisitor(ST outputFileST, SourceType sourceType) {\n\t\ttarget.genFile(g, outputFileST, getVisitorFileName(sourceType));\n\t}\n\n\tpublic void writeBaseVisitor(ST outputFileST, SourceType sourceType) {\n\t\ttarget.genFile(g, outputFileST, getBaseVisitorFileName(sourceType));\n\t}\n\n\tpublic void writeVocabFile() {\n\t\t// write out the vocab interchange file; used by antlr,\n\t\t// does not change per target\n\t\tST tokenVocabSerialization = getTokenVocabOutput();\n\t\tString fileName = getVocabFileName();\n\t\tif ( fileName!=null ) {\n\t\t\ttarget.genFile(g, tokenVocabSerialization, fileName);\n\t\t}\n\t}\n\n\tpublic void write(ST code, String fileName) {\n\t\ttry {\n//\t\t\tlong start = System.currentTimeMillis();\n\t\t\tWriter w = tool.getOutputFileWriter(g, fileName);\n\t\t\tSTWriter wr = new AutoIndentWriter(w);\n\t\t\twr.setLineWidth(lineWidth);\n\t\t\tcode.write(wr);\n\t\t\tw.close();\n//\t\t\tlong stop = System.currentTimeMillis();\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\ttool.errMgr.toolError(ErrorType.CANNOT_WRITE_FILE,\n\t\t\t\t\t\t\t\t  ioe,\n\t\t\t\t\t\t\t\t  fileName);\n\t\t}\n\t}\n\n\tpublic String getRecognizerFileName() { return getRecognizerFileName(SourceType.SOURCE); }\n\tpublic String getListenerFileName() { return getListenerFileName(SourceType.SOURCE); }\n\tpublic String getVisitorFileName() { return getVisitorFileName(SourceType.SOURCE); }\n\tpublic String getBaseListenerFileName() { return getBaseListenerFileName(SourceType.SOURCE); }\n\tpublic String getBaseVisitorFileName() { return getBaseVisitorFileName(SourceType.SOURCE); }\n\n\tpublic String getRecognizerFileName(SourceType sourceType) { return target.getRecognizerFileName(sourceType); }\n\tpublic String getListenerFileName(SourceType sourceType) { return target.getListenerFileName(sourceType); }\n\tpublic String getVisitorFileName(SourceType sourceType) { return target.getVisitorFileName(sourceType); }\n\tpublic String getBaseListenerFileName(SourceType sourceType) { return target.getBaseListenerFileName(sourceType); }\n\tpublic String getBaseVisitorFileName(SourceType sourceType) { return target.getBaseVisitorFileName(sourceType); }\n\n\t/** What is the name of the vocab file generated for this grammar?\n\t *  Returns null if no .tokens file should be generated.\n\t */\n\tpublic String getVocabFileName() {\n\t\treturn g.name+VOCAB_FILE_EXTENSION;\n\t}\n\n\tpublic String getHeaderFileName() {\n\t\tST extST = getTemplates().getInstanceOf(\"headerFileExtension\");\n\t\tif ( extST==null ) return null;\n\t\tString recognizerName = g.getRecognizerName();\n\t\treturn recognizerName+extST.render();\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/CodeGeneratorExtension.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\n\nimport org.antlr.v4.codegen.model.Choice;\nimport org.antlr.v4.codegen.model.CodeBlockForAlt;\nimport org.antlr.v4.codegen.model.LabeledOp;\nimport org.antlr.v4.codegen.model.Lexer;\nimport org.antlr.v4.codegen.model.LexerFile;\nimport org.antlr.v4.codegen.model.Parser;\nimport org.antlr.v4.codegen.model.ParserFile;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.SrcOp;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** Filter list of SrcOps and return; default is pass-through filter */\npublic class CodeGeneratorExtension {\n\tpublic OutputModelFactory factory;\n\n\tpublic CodeGeneratorExtension(OutputModelFactory factory) {\n\t\tthis.factory = factory;\n\t}\n\n\tpublic ParserFile parserFile(ParserFile f) { return f; }\n\n\tpublic Parser parser(Parser p) { return p; }\n\n\tpublic LexerFile lexerFile(LexerFile f) { return f; }\n\n\tpublic Lexer lexer(Lexer l) { return l; }\n\n\tpublic RuleFunction rule(RuleFunction rf) { return rf; }\n\n\tpublic List<SrcOp> rulePostamble(List<SrcOp> ops) { return ops; }\n\n\tpublic CodeBlockForAlt alternative(CodeBlockForAlt blk, boolean outerMost) { return blk; }\n\n\tpublic CodeBlockForAlt finishAlternative(CodeBlockForAlt blk, boolean outerMost) { return blk; }\n\n\tpublic CodeBlockForAlt epsilon(CodeBlockForAlt blk) { return blk; }\n\n\tpublic List<SrcOp> ruleRef(List<SrcOp> ops) { return ops; }\n\n\tpublic List<SrcOp> tokenRef(List<SrcOp> ops) { return ops; }\n\n\tpublic List<SrcOp> set(List<SrcOp> ops) { return ops; }\n\n\tpublic List<SrcOp> stringRef(List<SrcOp> ops) { return ops; }\n\n\tpublic List<SrcOp> wildcard(List<SrcOp> ops) { return ops; }\n\n\t// ACTIONS\n\n\tpublic List<SrcOp> action(List<SrcOp> ops) { return ops; }\n\n\tpublic List<SrcOp> sempred(List<SrcOp> ops) { return ops; }\n\n\t// BLOCKS\n\n\tpublic Choice getChoiceBlock(Choice c) { return c; }\n\n\tpublic Choice getEBNFBlock(Choice c) { return c; }\n\n\tpublic boolean needsImplicitLabel(GrammarAST ID, LabeledOp op) { return false; }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/DefaultOutputModelFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.codegen.model.Action;\nimport org.antlr.v4.codegen.model.CodeBlockForOuterMostAlt;\nimport org.antlr.v4.codegen.model.OutputModelObject;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.SrcOp;\nimport org.antlr.v4.codegen.model.decl.CodeBlock;\nimport org.antlr.v4.codegen.model.decl.Decl;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\n\n/** Create output objects for elements *within* rule functions except\n *  buildOutputModel() which builds outer/root model object and any\n *  objects such as RuleFunction that surround elements in rule\n *  functions.\n */\npublic abstract class DefaultOutputModelFactory extends BlankOutputModelFactory {\n\t// Interface to outside world\n\n\tpublic final Grammar g;\n\n\tpublic final CodeGenerator gen;\n\n\tpublic OutputModelController controller;\n\n\tprotected DefaultOutputModelFactory(CodeGenerator gen) {\n\t\tthis.gen = gen;\n\t\tthis.g = gen.g;\n\t}\n\n\t@Override\n\tpublic void setController(OutputModelController controller) {\n\t\tthis.controller = controller;\n\t}\n\n\t@Override\n\tpublic OutputModelController getController() {\n\t\treturn controller;\n\t}\n\n\t@Override\n\tpublic List<SrcOp> rulePostamble(RuleFunction function, Rule r) {\n\t\tif ( r.namedActions.containsKey(\"after\") || r.namedActions.containsKey(\"finally\") ) {\n\t\t\t// See OutputModelController.buildLeftRecursiveRuleFunction\n\t\t\t// and Parser.exitRule for other places which set stop.\n\t\t\tCodeGenerator gen = getGenerator();\n\t\t\tSTGroup codegenTemplates = gen.getTemplates();\n\t\t\tST setStopTokenAST = codegenTemplates.getInstanceOf(\"recRuleSetStopToken\");\n\t\t\tAction setStopTokenAction = new Action(this, function.ruleCtx, setStopTokenAST);\n\t\t\tList<SrcOp> ops = new ArrayList<SrcOp>(1);\n\t\t\tops.add(setStopTokenAction);\n\t\t\treturn ops;\n\t\t}\n\t\treturn super.rulePostamble(function, r);\n\t}\n\n\t// Convenience methods\n\n\n\t@Override\n\tpublic Grammar getGrammar() { return g; }\n\n\t@Override\n\tpublic CodeGenerator getGenerator() { return gen; }\n\n\t@Override\n\tpublic OutputModelObject getRoot() { return controller.getRoot(); }\n\n\t@Override\n\tpublic RuleFunction getCurrentRuleFunction() { return controller.getCurrentRuleFunction(); }\n\n\t@Override\n\tpublic Alternative getCurrentOuterMostAlt() { return controller.getCurrentOuterMostAlt(); }\n\n\t@Override\n\tpublic CodeBlock getCurrentBlock() { return controller.getCurrentBlock(); }\n\n\t@Override\n\tpublic CodeBlockForOuterMostAlt getCurrentOuterMostAlternativeBlock() { return controller.getCurrentOuterMostAlternativeBlock(); }\n\n\t@Override\n\tpublic int getCodeBlockLevel() { return controller.codeBlockLevel; }\n\n\t@Override\n\tpublic int getTreeLevel() { return controller.treeLevel; }\n\n\t// MISC\n\n\n\tpublic static List<SrcOp> list(SrcOp... values) {\n\t\treturn new ArrayList<SrcOp>(Arrays.asList(values));\n\t}\n\n\n\tpublic static List<SrcOp> list(Collection<? extends SrcOp> values) {\n\t\treturn new ArrayList<SrcOp>(values);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/LexerFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\n/** */\npublic class LexerFactory extends DefaultOutputModelFactory {\n\tpublic LexerFactory(CodeGenerator gen) { super(gen); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/OutputModelController.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.runtime.tree.CommonTreeNodeStream;\nimport org.antlr.v4.analysis.LeftRecursiveRuleAltInfo;\nimport org.antlr.v4.codegen.model.Action;\nimport org.antlr.v4.codegen.model.AltBlock;\nimport org.antlr.v4.codegen.model.BaseListenerFile;\nimport org.antlr.v4.codegen.model.BaseVisitorFile;\nimport org.antlr.v4.codegen.model.Choice;\nimport org.antlr.v4.codegen.model.CodeBlockForAlt;\nimport org.antlr.v4.codegen.model.CodeBlockForOuterMostAlt;\nimport org.antlr.v4.codegen.model.LabeledOp;\nimport org.antlr.v4.codegen.model.LeftRecursiveRuleFunction;\nimport org.antlr.v4.codegen.model.Lexer;\nimport org.antlr.v4.codegen.model.LexerFile;\nimport org.antlr.v4.codegen.model.ListenerFile;\nimport org.antlr.v4.codegen.model.OutputModelObject;\nimport org.antlr.v4.codegen.model.Parser;\nimport org.antlr.v4.codegen.model.ParserFile;\nimport org.antlr.v4.codegen.model.RuleActionFunction;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.RuleSempredFunction;\nimport org.antlr.v4.codegen.model.SrcOp;\nimport org.antlr.v4.codegen.model.StarBlock;\nimport org.antlr.v4.codegen.model.VisitorFile;\nimport org.antlr.v4.codegen.model.decl.CodeBlock;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LeftRecursiveRule;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.PredAST;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Stack;\n\n/** This receives events from SourceGenTriggers.g and asks factory to do work.\n *  Then runs extensions in order on resulting SrcOps to get final list.\n **/\npublic class OutputModelController {\n\t/** Who does the work? Doesn't have to be CoreOutputModelFactory. */\n\tpublic OutputModelFactory delegate;\n\n\t/** Post-processing CodeGeneratorExtension objects; done in order given. */\n\tpublic List<CodeGeneratorExtension> extensions = new ArrayList<CodeGeneratorExtension>();\n\n\t/** While walking code in rules, this is set to the tree walker that\n\t *  triggers actions.\n\t */\n\tpublic SourceGenTriggers walker;\n\n\t/** Context set by the SourceGenTriggers.g */\n\tpublic int codeBlockLevel = -1;\n\tpublic int treeLevel = -1;\n\tpublic OutputModelObject root; // normally ParserFile, LexerFile, ...\n\tpublic Stack<RuleFunction> currentRule = new Stack<RuleFunction>();\n\tpublic Alternative currentOuterMostAlt;\n\tpublic CodeBlock currentBlock;\n\tpublic CodeBlockForOuterMostAlt currentOuterMostAlternativeBlock;\n\n\tpublic OutputModelController(OutputModelFactory factory) {\n\t\tthis.delegate = factory;\n\t}\n\n\tpublic void addExtension(CodeGeneratorExtension ext) { extensions.add(ext); }\n\n\t/** Build a file with a parser containing rule functions. Use the\n\t *  controller as factory in SourceGenTriggers so it triggers codegen\n\t *  extensions too, not just the factory functions in this factory.\n\t */\n\tpublic OutputModelObject buildParserOutputModel(SourceType sourceType) {\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\tParserFile file = parserFile(gen.getRecognizerFileName(sourceType));\n\t\tsetRoot(file);\n\t\tfile.parser = parser(file);\n\t\t// ST can't compare strings so need booleans\n\t\tfile.genLean = sourceType == SourceType.SOURCE_LEAN;\n\t\tfile.genContexts = sourceType == SourceType.SOURCE_CONTEXTS;\n\t\tfile.genDFA = sourceType == SourceType.SOURCE_DFA;\n\n\t\tGrammar g = delegate.getGrammar();\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tbuildRuleFunction(file.parser, r);\n\t\t}\n\n\t\treturn file;\n\t}\n\n\tpublic OutputModelObject buildLexerOutputModel(SourceType sourceType) {\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\tLexerFile file = lexerFile(gen.getRecognizerFileName(sourceType));\n\t\tsetRoot(file);\n\t\tfile.lexer = lexer(file);\n\n\t\tGrammar g = delegate.getGrammar();\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tbuildLexerRuleActions(file.lexer, r);\n\t\t}\n\n\t\treturn file;\n\t}\n\n\tpublic OutputModelObject buildListenerOutputModel(SourceType sourceType) {\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\treturn new ListenerFile(delegate, gen.getListenerFileName(sourceType));\n\t}\n\n\tpublic OutputModelObject buildBaseListenerOutputModel(SourceType sourceType) {\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\treturn new BaseListenerFile(delegate, gen.getBaseListenerFileName(sourceType));\n\t}\n\n\tpublic OutputModelObject buildVisitorOutputModel(SourceType sourceType) {\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\treturn new VisitorFile(delegate, gen.getVisitorFileName(sourceType));\n\t}\n\n\tpublic OutputModelObject buildBaseVisitorOutputModel(SourceType sourceType) {\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\treturn new BaseVisitorFile(delegate, gen.getBaseVisitorFileName(sourceType));\n\t}\n\n\tpublic ParserFile parserFile(String fileName) {\n\t\tParserFile f = delegate.parserFile(fileName);\n\t\tfor (CodeGeneratorExtension ext : extensions) f = ext.parserFile(f);\n\t\treturn f;\n\t}\n\n\tpublic Parser parser(ParserFile file) {\n\t\tParser p = delegate.parser(file);\n\t\tfor (CodeGeneratorExtension ext : extensions) p = ext.parser(p);\n\t\treturn p;\n\t}\n\n\tpublic LexerFile lexerFile(String fileName) {\n\t\treturn new LexerFile(delegate, fileName);\n\t}\n\n\tpublic Lexer lexer(LexerFile file) {\n\t\treturn new Lexer(delegate, file);\n\t}\n\n\t/** Create RuleFunction per rule and update sempreds,actions of parser\n\t *  output object with stuff found in r.\n\t */\n\tpublic void buildRuleFunction(Parser parser, Rule r) {\n\t\tRuleFunction function = rule(r);\n\t\tparser.funcs.add(function);\n\t\tpushCurrentRule(function);\n\t\tfunction.fillNamedActions(delegate, r);\n\n\t\tif ( r instanceof LeftRecursiveRule ) {\n\t\t\tbuildLeftRecursiveRuleFunction((LeftRecursiveRule)r,\n\t\t\t\t\t\t\t\t\t\t   (LeftRecursiveRuleFunction)function);\n\t\t}\n\t\telse {\n\t\t\tbuildNormalRuleFunction(r, function);\n\t\t}\n\n\t\tGrammar g = getGrammar();\n\t\tfor (ActionAST a : r.actions) {\n\t\t\tif ( a instanceof PredAST ) {\n\t\t\t\tPredAST p = (PredAST)a;\n\t\t\t\tRuleSempredFunction rsf = parser.sempredFuncs.get(r);\n\t\t\t\tif ( rsf==null ) {\n\t\t\t\t\trsf = new RuleSempredFunction(delegate, r, function.ctxType);\n\t\t\t\t\tparser.sempredFuncs.put(r, rsf);\n\t\t\t\t}\n\t\t\t\trsf.actions.put(g.sempreds.get(p), new Action(delegate, p));\n\t\t\t}\n\t\t}\n\n\t\tpopCurrentRule();\n\t}\n\n\tpublic void buildLeftRecursiveRuleFunction(LeftRecursiveRule r, LeftRecursiveRuleFunction function) {\n\t\tbuildNormalRuleFunction(r, function);\n\n\t\t// now inject code to start alts\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\tSTGroup codegenTemplates = gen.getTemplates();\n\n\t\t// pick out alt(s) for primaries\n\t\tCodeBlockForOuterMostAlt outerAlt = (CodeBlockForOuterMostAlt)function.code.get(0);\n\t\tList<CodeBlockForAlt> primaryAltsCode = new ArrayList<CodeBlockForAlt>();\n\t\tSrcOp primaryStuff = outerAlt.ops.get(0);\n\t\tif ( primaryStuff instanceof Choice ) {\n\t\t\tChoice primaryAltBlock = (Choice) primaryStuff;\n\t\t\tprimaryAltsCode.addAll(primaryAltBlock.alts);\n\t\t}\n\t\telse { // just a single alt I guess; no block\n\t\t\tprimaryAltsCode.add((CodeBlockForAlt)primaryStuff);\n\t\t}\n\n\t\t// pick out alt(s) for op alts\n\t\tStarBlock opAltStarBlock = (StarBlock)outerAlt.ops.get(1);\n\t\tCodeBlockForAlt altForOpAltBlock = opAltStarBlock.alts.get(0);\n\t\tList<CodeBlockForAlt> opAltsCode = new ArrayList<CodeBlockForAlt>();\n\t\tSrcOp opStuff = altForOpAltBlock.ops.get(0);\n\t\tif ( opStuff instanceof AltBlock ) {\n\t\t\tAltBlock opAltBlock = (AltBlock)opStuff;\n\t\t\topAltsCode.addAll(opAltBlock.alts);\n\t\t}\n\t\telse { // just a single alt I guess; no block\n\t\t\topAltsCode.add((CodeBlockForAlt)opStuff);\n\t\t}\n\n\t\t// Insert code in front of each primary alt to create specialized ctx if there was a label\n\t\tfor (int i = 0; i < primaryAltsCode.size(); i++) {\n\t\t\tLeftRecursiveRuleAltInfo altInfo = r.recPrimaryAlts.get(i);\n\t\t\tif ( altInfo.altLabel==null ) continue;\n\t\t\tST altActionST = codegenTemplates.getInstanceOf(\"recRuleReplaceContext\");\n\t\t\taltActionST.add(\"ctxName\", Utils.capitalize(altInfo.altLabel));\n\t\t\tAction altAction =\n\t\t\t\tnew Action(delegate, function.altLabelCtxs.get(altInfo.altLabel), altActionST);\n\t\t\tCodeBlockForAlt alt = primaryAltsCode.get(i);\n\t\t\talt.insertOp(0, altAction);\n\t\t}\n\n\t\t// Insert code to set ctx.stop after primary block and before op * loop\n\t\tST setStopTokenAST = codegenTemplates.getInstanceOf(\"recRuleSetStopToken\");\n\t\tAction setStopTokenAction = new Action(delegate, function.ruleCtx, setStopTokenAST);\n\t\touterAlt.insertOp(1, setStopTokenAction);\n\n\t\t// Insert code to set _prevctx at start of * loop\n\t\tST setPrevCtx = codegenTemplates.getInstanceOf(\"recRuleSetPrevCtx\");\n\t\tAction setPrevCtxAction = new Action(delegate, function.ruleCtx, setPrevCtx);\n\t\topAltStarBlock.addIterationOp(setPrevCtxAction);\n\n\t\t// Insert code in front of each op alt to create specialized ctx if there was an alt label\n\t\tfor (int i = 0; i < opAltsCode.size(); i++) {\n\t\t\tST altActionST;\n\t\t\tLeftRecursiveRuleAltInfo altInfo = r.recOpAlts.getElement(i);\n\t\t\tString templateName;\n\t\t\tif ( altInfo.altLabel!=null ) {\n\t\t\t\ttemplateName = \"recRuleLabeledAltStartAction\";\n\t\t\t\taltActionST = codegenTemplates.getInstanceOf(templateName);\n\t\t\t\taltActionST.add(\"currentAltLabel\", altInfo.altLabel);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttemplateName = \"recRuleAltStartAction\";\n\t\t\t\taltActionST = codegenTemplates.getInstanceOf(templateName);\n\t\t\t\taltActionST.add(\"ctxName\", Utils.capitalize(r.name));\n\t\t\t}\n\t\t\taltActionST.add(\"ruleName\", r.name);\n\t\t\t// add label of any lr ref we deleted\n\t\t\taltActionST.add(\"label\", altInfo.leftRecursiveRuleRefLabel);\n\t\t\tif (altActionST.impl.formalArguments.containsKey(\"isListLabel\")) {\n\t\t\t\taltActionST.add(\"isListLabel\", altInfo.isListLabel);\n\t\t\t}\n\t\t\telse if (altInfo.isListLabel) {\n\t\t\t\tdelegate.getGenerator().tool.errMgr.toolError(ErrorType.CODE_TEMPLATE_ARG_ISSUE, templateName, \"isListLabel\");\n\t\t\t}\n\t\t\tAction altAction =\n\t\t\t\tnew Action(delegate, function.altLabelCtxs.get(altInfo.altLabel), altActionST);\n\t\t\tCodeBlockForAlt alt = opAltsCode.get(i);\n\t\t\talt.insertOp(0, altAction);\n\t\t}\n\t}\n\n\tpublic void buildNormalRuleFunction(Rule r, RuleFunction function) {\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\t// TRIGGER factory functions for rule alts, elements\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(r.ast.token.getInputStream());\n\t\tGrammarAST blk = (GrammarAST)r.ast.getFirstChildWithType(ANTLRParser.BLOCK);\n\t\tCommonTreeNodeStream nodes = new CommonTreeNodeStream(adaptor,blk);\n\t\twalker = new SourceGenTriggers(nodes, this);\n\t\ttry {\n\t\t\t// walk AST of rule alts/elements\n\t\t\tfunction.code = DefaultOutputModelFactory.list(walker.block(null, null));\n\t\t\tfunction.hasLookaheadBlock = walker.hasLookaheadBlock;\n\t\t}\n\t\tcatch (org.antlr.runtime.RecognitionException e){\n\t\t\te.printStackTrace(System.err);\n\t\t}\n\n\t\tfunction.ctxType = gen.getTarget().getRuleFunctionContextStructName(function);\n\n\t\tfunction.postamble = rulePostamble(function, r);\n\t}\n\n\tpublic void buildLexerRuleActions(Lexer lexer, final Rule r) {\n\t\tif (r.actions.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\n\t\tCodeGenerator gen = delegate.getGenerator();\n\t\tGrammar g = delegate.getGrammar();\n\t\tString ctxType = gen.getTarget().getRuleFunctionContextStructName(r);\n\t\tRuleActionFunction raf = lexer.actionFuncs.get(r);\n\t\tif ( raf==null ) {\n\t\t\traf = new RuleActionFunction(delegate, r, ctxType);\n\t\t}\n\n\t\tfor (ActionAST a : r.actions) {\n\t\t\tif ( a instanceof PredAST ) {\n\t\t\t\tPredAST p = (PredAST)a;\n\t\t\t\tRuleSempredFunction rsf = lexer.sempredFuncs.get(r);\n\t\t\t\tif ( rsf==null ) {\n\t\t\t\t\trsf = new RuleSempredFunction(delegate, r, ctxType);\n\t\t\t\t\tlexer.sempredFuncs.put(r, rsf);\n\t\t\t\t}\n\t\t\t\trsf.actions.put(g.sempreds.get(p), new Action(delegate, p));\n\t\t\t}\n\t\t\telse if ( a.getType()== ANTLRParser.ACTION ) {\n\t\t\t\traf.actions.put(g.lexerActions.get(a), new Action(delegate, a));\n\t\t\t}\n\t\t}\n\n\t\tif (!raf.actions.isEmpty() && !lexer.actionFuncs.containsKey(r)) {\n\t\t\t// only add to lexer if the function actually contains actions\n\t\t\tlexer.actionFuncs.put(r, raf);\n\t\t}\n\t}\n\n\tpublic RuleFunction rule(Rule r) {\n\t\tRuleFunction rf = delegate.rule(r);\n\t\tfor (CodeGeneratorExtension ext : extensions) rf = ext.rule(rf);\n\t\treturn rf;\n\t}\n\n\tpublic List<SrcOp> rulePostamble(RuleFunction function, Rule r) {\n\t\tList<SrcOp> ops = delegate.rulePostamble(function, r);\n\t\tfor (CodeGeneratorExtension ext : extensions) ops = ext.rulePostamble(ops);\n\t\treturn ops;\n\t}\n\n\tpublic Grammar getGrammar() { return delegate.getGrammar(); }\n\n\tpublic CodeGenerator getGenerator() { return delegate.getGenerator(); }\n\n\tpublic CodeBlockForAlt alternative(Alternative alt, boolean outerMost) {\n\t\tCodeBlockForAlt blk = delegate.alternative(alt, outerMost);\n\t\tif ( outerMost ) {\n\t\t\tcurrentOuterMostAlternativeBlock = (CodeBlockForOuterMostAlt)blk;\n\t\t}\n\t\tfor (CodeGeneratorExtension ext : extensions) blk = ext.alternative(blk, outerMost);\n\t\treturn blk;\n\t}\n\n\tpublic CodeBlockForAlt finishAlternative(CodeBlockForAlt blk, List<SrcOp> ops,\n\t\t\t\t\t\t\t\t\t\t\t boolean outerMost)\n\t{\n\t\tblk = delegate.finishAlternative(blk, ops);\n\t\tfor (CodeGeneratorExtension ext : extensions) blk = ext.finishAlternative(blk, outerMost);\n\t\treturn blk;\n\t}\n\n\tpublic List<SrcOp> ruleRef(GrammarAST ID, GrammarAST label, GrammarAST args) {\n\t\tList<SrcOp> ops = delegate.ruleRef(ID, label, args);\n\t\tfor (CodeGeneratorExtension ext : extensions) {\n\t\t\tops = ext.ruleRef(ops);\n\t\t}\n\t\treturn ops;\n\t}\n\n\tpublic List<SrcOp> tokenRef(GrammarAST ID, GrammarAST label, GrammarAST args)\n\t{\n\t\tList<SrcOp> ops = delegate.tokenRef(ID, label, args);\n\t\tfor (CodeGeneratorExtension ext : extensions) {\n\t\t\tops = ext.tokenRef(ops);\n\t\t}\n\t\treturn ops;\n\t}\n\n\tpublic List<SrcOp> stringRef(GrammarAST ID, GrammarAST label) {\n\t\tList<SrcOp> ops = delegate.stringRef(ID, label);\n\t\tfor (CodeGeneratorExtension ext : extensions) {\n\t\t\tops = ext.stringRef(ops);\n\t\t}\n\t\treturn ops;\n\t}\n\n\t/** (A|B|C) possibly with ebnfRoot and label */\n\tpublic List<SrcOp> set(GrammarAST setAST, GrammarAST labelAST, boolean invert) {\n\t\tList<SrcOp> ops = delegate.set(setAST, labelAST, invert);\n\t\tfor (CodeGeneratorExtension ext : extensions) {\n\t\t\tops = ext.set(ops);\n\t\t}\n\t\treturn ops;\n\t}\n\n\tpublic CodeBlockForAlt epsilon(Alternative alt, boolean outerMost) {\n\t\tCodeBlockForAlt blk = delegate.epsilon(alt, outerMost);\n\t\tfor (CodeGeneratorExtension ext : extensions) blk = ext.epsilon(blk);\n\t\treturn blk;\n\t}\n\n\tpublic List<SrcOp> wildcard(GrammarAST ast, GrammarAST labelAST) {\n\t\tList<SrcOp> ops = delegate.wildcard(ast, labelAST);\n\t\tfor (CodeGeneratorExtension ext : extensions) {\n\t\t\tops = ext.wildcard(ops);\n\t\t}\n\t\treturn ops;\n\t}\n\n\tpublic List<SrcOp> action(ActionAST ast) {\n\t\tList<SrcOp> ops = delegate.action(ast);\n\t\tfor (CodeGeneratorExtension ext : extensions) ops = ext.action(ops);\n\t\treturn ops;\n\t}\n\n\tpublic List<SrcOp> sempred(ActionAST ast) {\n\t\tList<SrcOp> ops = delegate.sempred(ast);\n\t\tfor (CodeGeneratorExtension ext : extensions) ops = ext.sempred(ops);\n\t\treturn ops;\n\t}\n\n\tpublic Choice getChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts, GrammarAST label) {\n\t\tChoice c = delegate.getChoiceBlock(blkAST, alts, label);\n\t\tfor (CodeGeneratorExtension ext : extensions) c = ext.getChoiceBlock(c);\n\t\treturn c;\n\t}\n\n\tpublic Choice getEBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) {\n\t\tChoice c = delegate.getEBNFBlock(ebnfRoot, alts);\n\t\tfor (CodeGeneratorExtension ext : extensions) c = ext.getEBNFBlock(c);\n\t\treturn c;\n\t}\n\n\tpublic boolean needsImplicitLabel(GrammarAST ID, LabeledOp op) {\n\t\tboolean needs = delegate.needsImplicitLabel(ID, op);\n\t\tfor (CodeGeneratorExtension ext : extensions) needs |= ext.needsImplicitLabel(ID, op);\n\t\treturn needs;\n\t}\n\n\tpublic OutputModelObject getRoot() { return root; }\n\n\tpublic void setRoot(OutputModelObject root) { this.root = root; }\n\n\tpublic RuleFunction getCurrentRuleFunction() {\n\t\tif ( !currentRule.isEmpty() )\treturn currentRule.peek();\n\t\treturn null;\n\t}\n\n\tpublic void pushCurrentRule(RuleFunction r) { currentRule.push(r); }\n\n\tpublic RuleFunction popCurrentRule() {\n\t\tif ( !currentRule.isEmpty() ) return currentRule.pop();\n\t\treturn null;\n\t}\n\n\tpublic Alternative getCurrentOuterMostAlt() { return currentOuterMostAlt; }\n\n\tpublic void setCurrentOuterMostAlt(Alternative currentOuterMostAlt) { this.currentOuterMostAlt = currentOuterMostAlt; }\n\n\tpublic void setCurrentBlock(CodeBlock blk) {\n\t\tcurrentBlock = blk;\n\t}\n\n\tpublic CodeBlock getCurrentBlock() {\n\t\treturn currentBlock;\n\t}\n\n\tpublic void setCurrentOuterMostAlternativeBlock(CodeBlockForOuterMostAlt currentOuterMostAlternativeBlock) {\n\t\tthis.currentOuterMostAlternativeBlock = currentOuterMostAlternativeBlock;\n\t}\n\n\tpublic CodeBlockForOuterMostAlt getCurrentOuterMostAlternativeBlock() {\n\t\treturn currentOuterMostAlternativeBlock;\n\t}\n\n\tpublic int getCodeBlockLevel() { return codeBlockLevel; }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/OutputModelFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.codegen.model.Choice;\nimport org.antlr.v4.codegen.model.CodeBlockForAlt;\nimport org.antlr.v4.codegen.model.CodeBlockForOuterMostAlt;\nimport org.antlr.v4.codegen.model.LabeledOp;\nimport org.antlr.v4.codegen.model.Lexer;\nimport org.antlr.v4.codegen.model.LexerFile;\nimport org.antlr.v4.codegen.model.OutputModelObject;\nimport org.antlr.v4.codegen.model.Parser;\nimport org.antlr.v4.codegen.model.ParserFile;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.SrcOp;\nimport org.antlr.v4.codegen.model.decl.CodeBlock;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\npublic interface OutputModelFactory {\n\tGrammar getGrammar();\n\n\tCodeGenerator getGenerator();\n\n\tvoid setController(OutputModelController controller);\n\n\tOutputModelController getController();\n\n\tParserFile parserFile(String fileName);\n\n\tParser parser(ParserFile file);\n\n\tLexerFile lexerFile(String fileName);\n\n\tLexer lexer(LexerFile file);\n\n\tRuleFunction rule(Rule r);\n\n\tList<SrcOp> rulePostamble(RuleFunction function, Rule r);\n\n\t// ELEMENT TRIGGERS\n\n\tCodeBlockForAlt alternative(Alternative alt, boolean outerMost);\n\n\tCodeBlockForAlt finishAlternative(CodeBlockForAlt blk, List<SrcOp> ops);\n\n\tCodeBlockForAlt epsilon(Alternative alt, boolean outerMost);\n\n\tList<SrcOp> ruleRef(GrammarAST ID, GrammarAST label, GrammarAST args);\n\n\tList<SrcOp> tokenRef(GrammarAST ID, GrammarAST label, GrammarAST args);\n\n\tList<SrcOp> stringRef(GrammarAST ID, GrammarAST label);\n\n\tList<SrcOp> set(GrammarAST setAST, GrammarAST label, boolean invert);\n\n\tList<SrcOp> wildcard(GrammarAST ast, GrammarAST labelAST);\n\n\tList<SrcOp> action(ActionAST ast);\n\n\tList<SrcOp> sempred(ActionAST ast);\n\n\tChoice getChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts, GrammarAST label);\n\n\tChoice getEBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts);\n\n\tChoice getLL1ChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts);\n\n\tChoice getComplexChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts);\n\n\tChoice getLL1EBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts);\n\n\tChoice getComplexEBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts);\n\n\tList<SrcOp> getLL1Test(IntervalSet look, GrammarAST blkAST);\n\n\tboolean needsImplicitLabel(GrammarAST ID, LabeledOp op);\n\n\t// CONTEXT INFO\n\n\tOutputModelObject getRoot();\n\n\tRuleFunction getCurrentRuleFunction();\n\n\tAlternative getCurrentOuterMostAlt();\n\n\tCodeBlock getCurrentBlock();\n\n\tCodeBlockForOuterMostAlt getCurrentOuterMostAlternativeBlock();\n\n\tint getCodeBlockLevel();\n\n\tint getTreeLevel();\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/OutputModelWalker.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.model.ModelElement;\nimport org.antlr.v4.codegen.model.OutputModelObject;\nimport org.antlr.v4.tool.ErrorType;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.compiler.FormalArgument;\n\nimport java.lang.reflect.Field;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.Set;\n\n/** Convert an output model tree to template hierarchy by walking\n *  the output model. Each output model object has a corresponding template\n *  of the same name.  An output model object can have nested objects.\n *  We identify those nested objects by the list of arguments in the template\n *  definition. For example, here is the definition of the parser template:\n *\n *  Parser(parser, scopes, funcs) ::= &lt;&lt;...&gt;&gt;\n *\n *  The first template argument is always the output model object from which\n *  this walker will create the template. Any other arguments identify\n *  the field names within the output model object of nested model objects.\n *  So, in this case, template Parser is saying that output model object\n *  Parser has two fields the walker should chase called a scopes and funcs.\n *\n *  This simple mechanism means we don't have to include code in every\n *  output model object that says how to create the corresponding template.\n */\npublic class OutputModelWalker {\n\tTool tool;\n\tSTGroup templates;\n\n\tpublic OutputModelWalker(Tool tool,\n\t\t\t\t\t\t\t STGroup templates)\n\t{\n\t\tthis.tool = tool;\n\t\tthis.templates = templates;\n\t}\n\n\tpublic ST walk(OutputModelObject omo, SourceType sourceType) {\n\t\t// CREATE TEMPLATE FOR THIS OUTPUT OBJECT\n\t\tClass<? extends OutputModelObject> cl = omo.getClass();\n\t\tString templateName = cl.getSimpleName();\n\t\tif ( templateName == null ) {\n\t\t\ttool.errMgr.toolError(ErrorType.NO_MODEL_TO_TEMPLATE_MAPPING, cl.getSimpleName());\n\t\t\treturn new ST(\"[\"+templateName+\" invalid]\");\n\t\t}\n\n\t\tif (sourceType == SourceType.HEADER) templateName += \"Header\";\n\n\t\tST st = templates.getInstanceOf(templateName);\n\t\tif ( st == null ) {\n\t\t\ttool.errMgr.toolError(ErrorType.CODE_GEN_TEMPLATES_INCOMPLETE, templateName);\n\t\t\treturn new ST(\"[\"+templateName+\" invalid]\");\n\t\t}\n\t\tif ( st.impl.formalArguments == null ) {\n\t\t\ttool.errMgr.toolError(ErrorType.CODE_TEMPLATE_ARG_ISSUE, templateName, \"<none>\");\n\t\t\treturn st;\n\t\t}\n\n\t\tMap<String,FormalArgument> formalArgs = st.impl.formalArguments;\n\n\t\t// PASS IN OUTPUT MODEL OBJECT TO TEMPLATE AS FIRST ARG\n\t\tSet<String> argNames = formalArgs.keySet();\n\t\tIterator<String> arg_it = argNames.iterator();\n\t\tString modelArgName = arg_it.next(); // ordered so this is first arg\n\t\tst.add(modelArgName, omo);\n\n\t\t// COMPUTE STs FOR EACH NESTED MODEL OBJECT MARKED WITH @ModelElement AND MAKE ST ATTRIBUTE\n\t\tSet<String> usedFieldNames = new HashSet<String>();\n\t\tField fields[] = cl.getFields();\n\t\tfor (Field fi : fields) {\n\t\t\tModelElement annotation = fi.getAnnotation(ModelElement.class);\n\t\t\tif (annotation == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tString fieldName = fi.getName();\n\n\t\t\tif (!usedFieldNames.add(fieldName)) {\n\t\t\t\ttool.errMgr.toolError(ErrorType.INTERNAL_ERROR, \"Model object \" + omo.getClass().getSimpleName() + \" has multiple fields named '\" + fieldName + \"'\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Just don't set @ModelElement fields w/o formal arg in target ST\n\t\t\tif ( formalArgs.get(fieldName)==null ) continue;\n\n\t\t\ttry {\n\t\t\t\tObject o = fi.get(omo);\n\t\t\t\tif ( o instanceof OutputModelObject ) {  // SINGLE MODEL OBJECT?\n\t\t\t\t\tOutputModelObject nestedOmo = (OutputModelObject)o;\n\t\t\t\t\tST nestedST = walk(nestedOmo, sourceType);\n//\t\t\t\t\tSystem.out.println(\"set ModelElement \"+fieldName+\"=\"+nestedST+\" in \"+templateName);\n\t\t\t\t\tst.add(fieldName, nestedST);\n\t\t\t\t}\n\t\t\t\telse if ( o instanceof Collection || o instanceof OutputModelObject[] ) {\n\t\t\t\t\t// LIST OF MODEL OBJECTS?\n\t\t\t\t\tif ( o instanceof OutputModelObject[] ) {\n\t\t\t\t\t\to = Arrays.asList((OutputModelObject[])o);\n\t\t\t\t\t}\n\t\t\t\t\tCollection<?> nestedOmos = (Collection<?>)o;\n\t\t\t\t\tfor (Object nestedOmo : nestedOmos) {\n\t\t\t\t\t\tif ( nestedOmo==null ) continue;\n\t\t\t\t\t\tST nestedST = walk((OutputModelObject)nestedOmo, sourceType);\n//\t\t\t\t\t\tSystem.out.println(\"set ModelElement \"+fieldName+\"=\"+nestedST+\" in \"+templateName);\n\t\t\t\t\t\tst.add(fieldName, nestedST);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( o instanceof Map ) {\n\t\t\t\t\tMap<?, ?> nestedOmoMap = (Map<?, ?>)o;\n\t\t\t\t\tMap<Object, ST> m = new LinkedHashMap<Object, ST>();\n\t\t\t\t\tfor (Map.Entry<?, ?> entry : nestedOmoMap.entrySet()) {\n\t\t\t\t\t\tST nestedST = walk((OutputModelObject)entry.getValue(), sourceType);\n//\t\t\t\t\t\tSystem.out.println(\"set ModelElement \"+fieldName+\"=\"+nestedST+\" in \"+templateName);\n\t\t\t\t\t\tm.put(entry.getKey(), nestedST);\n\t\t\t\t\t}\n\t\t\t\t\tst.add(fieldName, m);\n\t\t\t\t}\n\t\t\t\telse if ( o!=null ) {\n\t\t\t\t\ttool.errMgr.toolError(ErrorType.INTERNAL_ERROR, \"not recognized nested model element: \"+fieldName);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (IllegalAccessException iae) {\n\t\t\t\ttool.errMgr.toolError(ErrorType.CODE_TEMPLATE_ARG_ISSUE, templateName, fieldName);\n\t\t\t}\n\t\t}\n\t\t//st.impl.dump();\n\t\treturn st;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/ParserFactory.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.analysis.AnalysisPipeline;\nimport org.antlr.v4.codegen.model.Action;\nimport org.antlr.v4.codegen.model.AddToLabelList;\nimport org.antlr.v4.codegen.model.AltBlock;\nimport org.antlr.v4.codegen.model.Choice;\nimport org.antlr.v4.codegen.model.CodeBlockForAlt;\nimport org.antlr.v4.codegen.model.CodeBlockForOuterMostAlt;\nimport org.antlr.v4.codegen.model.InvokeRule;\nimport org.antlr.v4.codegen.model.LL1AltBlock;\nimport org.antlr.v4.codegen.model.LL1OptionalBlock;\nimport org.antlr.v4.codegen.model.LL1OptionalBlockSingleAlt;\nimport org.antlr.v4.codegen.model.LL1PlusBlockSingleAlt;\nimport org.antlr.v4.codegen.model.LL1StarBlockSingleAlt;\nimport org.antlr.v4.codegen.model.LabeledOp;\nimport org.antlr.v4.codegen.model.LeftRecursiveRuleFunction;\nimport org.antlr.v4.codegen.model.MatchNotSet;\nimport org.antlr.v4.codegen.model.MatchSet;\nimport org.antlr.v4.codegen.model.MatchToken;\nimport org.antlr.v4.codegen.model.OptionalBlock;\nimport org.antlr.v4.codegen.model.Parser;\nimport org.antlr.v4.codegen.model.ParserFile;\nimport org.antlr.v4.codegen.model.PlusBlock;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.SemPred;\nimport org.antlr.v4.codegen.model.SrcOp;\nimport org.antlr.v4.codegen.model.StarBlock;\nimport org.antlr.v4.codegen.model.TestSetInline;\nimport org.antlr.v4.codegen.model.Wildcard;\nimport org.antlr.v4.codegen.model.decl.Decl;\nimport org.antlr.v4.codegen.model.decl.RuleContextDecl;\nimport org.antlr.v4.codegen.model.decl.TokenDecl;\nimport org.antlr.v4.codegen.model.decl.TokenListDecl;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.PlusLoopbackState;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.LeftRecursiveRule;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.List;\n\n/** */\npublic class ParserFactory extends DefaultOutputModelFactory {\n\tpublic ParserFactory(CodeGenerator gen) { super(gen); }\n\n\t@Override\n\tpublic ParserFile parserFile(String fileName) {\n\t\treturn new ParserFile(this, fileName);\n\t}\n\n\t@Override\n\tpublic Parser parser(ParserFile file) {\n\t\treturn new Parser(this, file);\n\t}\n\n\t@Override\n\tpublic RuleFunction rule(Rule r) {\n\t\tif ( r instanceof LeftRecursiveRule ) {\n\t\t\treturn new LeftRecursiveRuleFunction(this, (LeftRecursiveRule)r);\n\t\t}\n\t\telse {\n\t\t\tRuleFunction rf = new RuleFunction(this, r);\n\t\t\treturn rf;\n\t\t}\n\t}\n\n\t@Override\n\tpublic CodeBlockForAlt epsilon(Alternative alt, boolean outerMost) {\n\t\treturn alternative(alt, outerMost);\n\t}\n\n\t@Override\n\tpublic CodeBlockForAlt alternative(Alternative alt, boolean outerMost) {\n\t\tif ( outerMost ) return new CodeBlockForOuterMostAlt(this, alt);\n\t\treturn new CodeBlockForAlt(this);\n\t}\n\n\t@Override\n\tpublic CodeBlockForAlt finishAlternative(CodeBlockForAlt blk, List<SrcOp> ops) {\n\t\tblk.ops = ops;\n\t\treturn blk;\n\t}\n\n\t@Override\n\tpublic List<SrcOp> action(ActionAST ast) { return list(new Action(this, ast)); }\n\n\t@Override\n\tpublic List<SrcOp> sempred(ActionAST ast) { return list(new SemPred(this, ast)); }\n\n\t@Override\n\tpublic List<SrcOp> ruleRef(GrammarAST ID, GrammarAST label, GrammarAST args) {\n\t\tInvokeRule invokeOp = new InvokeRule(this, ID, label);\n\t\t// If no manual label and action refs as token/rule not label, we need to define implicit label\n\t\tif ( controller.needsImplicitLabel(ID, invokeOp) ) defineImplicitLabel(ID, invokeOp);\n\t\tAddToLabelList listLabelOp = getAddToListOpIfListLabelPresent(invokeOp, label);\n\t\treturn list(invokeOp, listLabelOp);\n\t}\n\n\t@Override\n\tpublic List<SrcOp> tokenRef(GrammarAST ID, GrammarAST labelAST, GrammarAST args) {\n\t\tMatchToken matchOp = new MatchToken(this, (TerminalAST) ID);\n\t\tif ( labelAST!=null ) {\n\t\t\tString label = labelAST.getText();\n\t\t\tRuleFunction rf = getCurrentRuleFunction();\n\t\t\tif ( labelAST.parent.getType() == ANTLRParser.PLUS_ASSIGN ) {\n\t\t\t\t// add Token _X and List<Token> X decls\n\t\t\t\tdefineImplicitLabel(ID, matchOp); // adds _X\n\t\t\t\tTokenListDecl l = getTokenListLabelDecl(label);\n\t\t\t\trf.addContextDecl(ID.getAltLabel(), l);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tDecl d = getTokenLabelDecl(label);\n\t\t\t\tmatchOp.labels.add(d);\n\t\t\t\trf.addContextDecl(ID.getAltLabel(), d);\n\t\t\t}\n\n//\t\t\tDecl d = getTokenLabelDecl(label);\n//\t\t\t((MatchToken)matchOp).labels.add(d);\n//\t\t\tgetCurrentRuleFunction().addContextDecl(ID.getAltLabel(), d);\n//\t\t\tif ( labelAST.parent.getType() == ANTLRParser.PLUS_ASSIGN ) {\n//\t\t\t\tTokenListDecl l = getTokenListLabelDecl(label);\n//\t\t\t\tgetCurrentRuleFunction().addContextDecl(ID.getAltLabel(), l);\n//\t\t\t}\n\t\t}\n\t\tif ( controller.needsImplicitLabel(ID, matchOp) ) defineImplicitLabel(ID, matchOp);\n\t\tAddToLabelList listLabelOp = getAddToListOpIfListLabelPresent(matchOp, labelAST);\n\t\treturn list(matchOp, listLabelOp);\n\t}\n\n\tpublic Decl getTokenLabelDecl(String label) {\n\t\treturn new TokenDecl(this, label);\n\t}\n\n\tpublic TokenListDecl getTokenListLabelDecl(String label) {\n\t\treturn new TokenListDecl(this, gen.getTarget().getListLabel(label));\n\t}\n\n\t@Override\n\tpublic List<SrcOp> set(GrammarAST setAST, GrammarAST labelAST, boolean invert) {\n\t\tMatchSet matchOp;\n\t\tif ( invert ) matchOp = new MatchNotSet(this, setAST);\n\t\telse matchOp = new MatchSet(this, setAST);\n\t\tif ( labelAST!=null ) {\n\t\t\tString label = labelAST.getText();\n\t\t\tRuleFunction rf = getCurrentRuleFunction();\n\t\t\tif ( labelAST.parent.getType() == ANTLRParser.PLUS_ASSIGN ) {\n\t\t\t\tdefineImplicitLabel(setAST, matchOp);\n\t\t\t\tTokenListDecl l = getTokenListLabelDecl(label);\n\t\t\t\trf.addContextDecl(setAST.getAltLabel(), l);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tDecl d = getTokenLabelDecl(label);\n\t\t\t\tmatchOp.labels.add(d);\n\t\t\t\trf.addContextDecl(setAST.getAltLabel(), d);\n\t\t\t}\n\t\t}\n\t\tif ( controller.needsImplicitLabel(setAST, matchOp) ) defineImplicitLabel(setAST, matchOp);\n\t\tAddToLabelList listLabelOp = getAddToListOpIfListLabelPresent(matchOp, labelAST);\n\t\treturn list(matchOp, listLabelOp);\n\t}\n\n\t@Override\n\tpublic List<SrcOp> wildcard(GrammarAST ast, GrammarAST labelAST) {\n\t\tWildcard wild = new Wildcard(this, ast);\n\t\t// TODO: dup with tokenRef\n\t\tif ( labelAST!=null ) {\n\t\t\tString label = labelAST.getText();\n\t\t\tDecl d = getTokenLabelDecl(label);\n\t\t\twild.labels.add(d);\n\t\t\tgetCurrentRuleFunction().addContextDecl(ast.getAltLabel(), d);\n\t\t\tif ( labelAST.parent.getType() == ANTLRParser.PLUS_ASSIGN ) {\n\t\t\t\tTokenListDecl l = getTokenListLabelDecl(label);\n\t\t\t\tgetCurrentRuleFunction().addContextDecl(ast.getAltLabel(), l);\n\t\t\t}\n\t\t}\n\t\tif ( controller.needsImplicitLabel(ast, wild) ) defineImplicitLabel(ast, wild);\n\t\tAddToLabelList listLabelOp = getAddToListOpIfListLabelPresent(wild, labelAST);\n\t\treturn list(wild, listLabelOp);\n\t}\n\n\t@Override\n\tpublic Choice getChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts, GrammarAST labelAST) {\n\t\tint decision = ((DecisionState)blkAST.atnState).decision;\n\t\tChoice c;\n\t\tif ( !g.tool.force_atn && AnalysisPipeline.disjoint(g.decisionLOOK.get(decision)) ) {\n\t\t\tc = getLL1ChoiceBlock(blkAST, alts);\n\t\t}\n\t\telse {\n\t\t\tc = getComplexChoiceBlock(blkAST, alts);\n\t\t}\n\n\t\tif ( labelAST!=null ) { // for x=(...), define x or x_list\n\t\t\tString label = labelAST.getText();\n\t\t\tDecl d = getTokenLabelDecl(label);\n\t\t\tc.label = d;\n\t\t\tgetCurrentRuleFunction().addContextDecl(labelAST.getAltLabel(), d);\n\t\t\tif ( labelAST.parent.getType() == ANTLRParser.PLUS_ASSIGN  ) {\n\t\t\t\tString listLabel = gen.getTarget().getListLabel(label);\n\t\t\t\tTokenListDecl l = new TokenListDecl(this, listLabel);\n\t\t\t\tgetCurrentRuleFunction().addContextDecl(labelAST.getAltLabel(), l);\n\t\t\t}\n\t\t}\n\n\t\treturn c;\n\t}\n\n\t@Override\n\tpublic Choice getEBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) {\n\t\tif (!g.tool.force_atn) {\n\t\t\tint decision;\n\t\t\tif ( ebnfRoot.getType()==ANTLRParser.POSITIVE_CLOSURE ) {\n\t\t\t\tdecision = ((PlusLoopbackState)ebnfRoot.atnState).decision;\n\t\t\t}\n\t\t\telse if ( ebnfRoot.getType()==ANTLRParser.CLOSURE ) {\n\t\t\t\tdecision = ((StarLoopEntryState)ebnfRoot.atnState).decision;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdecision = ((DecisionState)ebnfRoot.atnState).decision;\n\t\t\t}\n\n\t\t\tif ( AnalysisPipeline.disjoint(g.decisionLOOK.get(decision)) ) {\n\t\t\t\treturn getLL1EBNFBlock(ebnfRoot, alts);\n\t\t\t}\n\t\t}\n\n\t\treturn getComplexEBNFBlock(ebnfRoot, alts);\n\t}\n\n\t@Override\n\tpublic Choice getLL1ChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts) {\n\t\treturn new LL1AltBlock(this, blkAST, alts);\n\t}\n\n\t@Override\n\tpublic Choice getComplexChoiceBlock(BlockAST blkAST, List<CodeBlockForAlt> alts) {\n\t\treturn new AltBlock(this, blkAST, alts);\n\t}\n\n\t@Override\n\tpublic Choice getLL1EBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) {\n\t\tint ebnf = 0;\n\t\tif ( ebnfRoot!=null ) ebnf = ebnfRoot.getType();\n\t\tChoice c = null;\n\t\tswitch ( ebnf ) {\n\t\t\tcase ANTLRParser.OPTIONAL :\n\t\t\t\tif ( alts.size()==1 ) c = new LL1OptionalBlockSingleAlt(this, ebnfRoot, alts);\n\t\t\t\telse c = new LL1OptionalBlock(this, ebnfRoot, alts);\n\t\t\t\tbreak;\n\t\t\tcase ANTLRParser.CLOSURE :\n\t\t\t\tif ( alts.size()==1 ) c = new LL1StarBlockSingleAlt(this, ebnfRoot, alts);\n\t\t\t\telse c = getComplexEBNFBlock(ebnfRoot, alts);\n\t\t\t\tbreak;\n\t\t\tcase ANTLRParser.POSITIVE_CLOSURE :\n\t\t\t\tif ( alts.size()==1 ) c = new LL1PlusBlockSingleAlt(this, ebnfRoot, alts);\n\t\t\t\telse c = getComplexEBNFBlock(ebnfRoot, alts);\n\t\t\t\tbreak;\n\t\t}\n\t\treturn c;\n\t}\n\n\t@Override\n\tpublic Choice getComplexEBNFBlock(GrammarAST ebnfRoot, List<CodeBlockForAlt> alts) {\n\t\tint ebnf = 0;\n\t\tif ( ebnfRoot!=null ) ebnf = ebnfRoot.getType();\n\t\tChoice c = null;\n\t\tswitch ( ebnf ) {\n\t\t\tcase ANTLRParser.OPTIONAL :\n\t\t\t\tc = new OptionalBlock(this, ebnfRoot, alts);\n\t\t\t\tbreak;\n\t\t\tcase ANTLRParser.CLOSURE :\n\t\t\t\tc = new StarBlock(this, ebnfRoot, alts);\n\t\t\t\tbreak;\n\t\t\tcase ANTLRParser.POSITIVE_CLOSURE :\n\t\t\t\tc = new PlusBlock(this, ebnfRoot, alts);\n\t\t\t\tbreak;\n\t\t}\n\t\treturn c;\n\t}\n\n\t@Override\n\tpublic List<SrcOp> getLL1Test(IntervalSet look, GrammarAST blkAST) {\n\t\treturn list(new TestSetInline(this, blkAST, look, gen.getTarget().getInlineTestSetWordSize()));\n\t}\n\n\t@Override\n\tpublic boolean needsImplicitLabel(GrammarAST ID, LabeledOp op) {\n\t\tAlternative currentOuterMostAlt = getCurrentOuterMostAlt();\n\t\tboolean actionRefsAsToken = currentOuterMostAlt.tokenRefsInActions.containsKey(ID.getText());\n\t\tboolean actionRefsAsRule = currentOuterMostAlt.ruleRefsInActions.containsKey(ID.getText());\n\t\treturn\top.getLabels().isEmpty() &&\t(actionRefsAsToken || actionRefsAsRule);\n\t}\n\n\t// support\n\n\tpublic void defineImplicitLabel(GrammarAST ast, LabeledOp op) {\n\t\tDecl d;\n\t\tif ( ast.getType()==ANTLRParser.SET || ast.getType()==ANTLRParser.WILDCARD ) {\n\t\t\tString implLabel =\n\t\t\t\tgen.getTarget().getImplicitSetLabel(String.valueOf(ast.token.getTokenIndex()));\n\t\t\td = getTokenLabelDecl(implLabel);\n\t\t\t((TokenDecl)d).isImplicit = true;\n\t\t}\n\t\telse if ( ast.getType()==ANTLRParser.RULE_REF ) { // a rule reference?\n\t\t\tRule r = g.getRule(ast.getText());\n\t\t\tString implLabel = gen.getTarget().getImplicitRuleLabel(ast.getText());\n\t\t\tString ctxName =\n\t\t\t\tgen.getTarget().getRuleFunctionContextStructName(r);\n\t\t\td = new RuleContextDecl(this, implLabel, ctxName);\n\t\t\t((RuleContextDecl)d).isImplicit = true;\n\t\t}\n\t\telse {\n\t\t\tString implLabel = gen.getTarget().getImplicitTokenLabel(ast.getText());\n\t\t\td = getTokenLabelDecl(implLabel);\n\t\t\t((TokenDecl)d).isImplicit = true;\n\t\t}\n\t\top.getLabels().add(d);\n\t\t// all labels must be in scope struct in case we exec action out of context\n\t\tgetCurrentRuleFunction().addContextDecl(ast.getAltLabel(), d);\n\t}\n\n\tpublic AddToLabelList getAddToListOpIfListLabelPresent(LabeledOp op, GrammarAST label) {\n\t\tAddToLabelList labelOp = null;\n\t\tif ( label!=null && label.parent.getType()==ANTLRParser.PLUS_ASSIGN ) {\n\t\t\tTarget target = gen.getTarget();\n\t\t\tString listLabel = target.getListLabel(label.getText());\n\t\t\tString listRuntimeName = target.escapeIfNeeded(listLabel);\n\t\t\tlabelOp = new AddToLabelList(this, listRuntimeName, op.getLabels().get(0));\n\t\t}\n\t\treturn labelOp;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/SourceGenTriggers.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\ntree grammar SourceGenTriggers;\noptions {\n\tlanguage     = Java;\n\ttokenVocab   = ANTLRParser;\n\tASTLabelType = GrammarAST;\n}\n\n@header {\npackage org.antlr.v4.codegen;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.codegen.model.*;\nimport org.antlr.v4.codegen.model.decl.*;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.*;\nimport java.util.Collections;\nimport java.util.Map;\nimport java.util.HashMap;\n}\n\n@members {\n\tpublic OutputModelController controller;\n    public boolean hasLookaheadBlock;\n    public SourceGenTriggers(TreeNodeStream input, OutputModelController controller) {\n    \tthis(input);\n    \tthis.controller = controller;\n    }\n}\n\ndummy : block[null, null] ;\n\nblock[GrammarAST label, GrammarAST ebnfRoot] returns [List<? extends SrcOp> omos]\n    :\t^(\tblk=BLOCK (^(OPTIONS .+))?\n\t\t\t{List<CodeBlockForAlt> alts = new ArrayList<CodeBlockForAlt>();}\n    \t\t( alternative {alts.add($alternative.altCodeBlock);} )+\n    \t)\n    \t{\n    \tif ( alts.size()==1 && ebnfRoot==null) return alts;\n    \tif ( ebnfRoot==null ) {\n    \t    $omos = DefaultOutputModelFactory.list(controller.getChoiceBlock((BlockAST)$blk, alts, $label));\n    \t}\n    \telse {\n            Choice choice = controller.getEBNFBlock($ebnfRoot, alts);\n            hasLookaheadBlock |= choice instanceof PlusBlock || choice instanceof StarBlock;\n    \t    $omos = DefaultOutputModelFactory.list(choice);\n    \t}\n    \t}\n    ;\n\nalternative returns [CodeBlockForAlt altCodeBlock, List<SrcOp> ops]\n@init {\n   \tboolean outerMost = inContext(\"RULE BLOCK\");\n}\n@after {\n   \tcontroller.finishAlternative($altCodeBlock, $ops, outerMost);\n}\n    :\ta=alt[outerMost] {$altCodeBlock=$a.altCodeBlock; $ops=$a.ops;}\n\t;\n\nalt[boolean outerMost] returns [CodeBlockForAlt altCodeBlock, List<SrcOp> ops]\n@init {\n\t// set alt if outer ALT only (the only ones with alt field set to Alternative object)\n\tAltAST altAST = (AltAST)retval.start;\n\tif ( outerMost ) controller.setCurrentOuterMostAlt(altAST.alt);\n}\n\t:\t{\n\t\tList<SrcOp> elems = new ArrayList<SrcOp>();\n\t\t// TODO: shouldn't we pass $start to controller.alternative()?\n\t\t$altCodeBlock = controller.alternative(controller.getCurrentOuterMostAlt(), outerMost);\n\t\t$altCodeBlock.ops = $ops = elems;\n\t\tcontroller.setCurrentBlock($altCodeBlock);\n\t\t}\n\t\t^( ALT elementOptions? ( element {if ($element.omos!=null) elems.addAll($element.omos);} )+ )\n\n\t|\t^(ALT elementOptions? EPSILON)\n        {$altCodeBlock = controller.epsilon(controller.getCurrentOuterMostAlt(), outerMost);}\n    ;\n\nelement returns [List<? extends SrcOp> omos]\n\t:\tlabeledElement\t\t\t\t\t{$omos = $labeledElement.omos;}\n\t|\tatom[null,false]\t\t\t{$omos = $atom.omos;}\n\t|\tsubrule\t\t\t\t\t\t\t{$omos = $subrule.omos;}\n\t|   ACTION\t\t\t\t\t\t\t{$omos = controller.action((ActionAST)$ACTION);}\n\t|   SEMPRED\t\t\t\t\t\t\t{$omos = controller.sempred((ActionAST)$SEMPRED);}\n\t|\t^(ACTION elementOptions)\t\t{$omos = controller.action((ActionAST)$ACTION);}\n\t|   ^(SEMPRED elementOptions)\t\t{$omos = controller.sempred((ActionAST)$SEMPRED);}\n\t;\n\nlabeledElement returns [List<? extends SrcOp> omos]\n\t:\t^(ASSIGN ID atom[$ID,false] )\t\t\t{$omos = $atom.omos;}\n\t|\t^(PLUS_ASSIGN ID atom[$ID,false])\t\t{$omos = $atom.omos;}\n\t|\t^(ASSIGN ID block[$ID,null] )\t\t\t{$omos = $block.omos;}\n\t|\t^(PLUS_ASSIGN ID block[$ID,null])\t\t{$omos = $block.omos;}\n\t;\n\nsubrule returns [List<? extends SrcOp> omos]\n\t:\t^(OPTIONAL b=block[null,$OPTIONAL])\n\t\t{\n\t\t$omos = $block.omos;\n\t\t}\n\t|\t(\t^(op=CLOSURE b=block[null,null])\n\t\t|\t^(op=POSITIVE_CLOSURE b=block[null,null])\n\t\t)\n\t\t{\n\t\tList<CodeBlockForAlt> alts = new ArrayList<CodeBlockForAlt>();\n\t\tSrcOp blk = $b.omos.get(0);\n\t\tCodeBlockForAlt alt = new CodeBlockForAlt(controller.delegate);\n\t\talt.addOp(blk);\n\t\talts.add(alt);\n\t\tSrcOp loop = controller.getEBNFBlock($op, alts); // \"star it\"\n        hasLookaheadBlock |= loop instanceof PlusBlock || loop instanceof StarBlock;\n   \t    $omos = DefaultOutputModelFactory.list(loop);\n\t\t}\n\t| \tblock[null, null]\t\t\t\t\t{$omos = $block.omos;}\n    ;\n\nblockSet[GrammarAST label, boolean invert] returns [List<SrcOp> omos]\n    :\t^(SET atom[label,invert]+) {$omos = controller.set($SET, $label, invert);}\n    ;\n\n/*\nsetElement\n\t:\tSTRING_LITERAL\n\t|\tTOKEN_REF\n\t|\t^(RANGE STRING_LITERAL STRING_LITERAL)\n\t;\n*/\n\n// TODO: combine ROOT/BANG into one then just make new op ref'ing return value of atom/terminal...\n// TODO: same for NOT\natom[GrammarAST label, boolean invert] returns [List<SrcOp> omos]\n\t:\t^(NOT a=atom[$label, true])\t\t{$omos = $a.omos;}\n\t|\trange[label]\t\t\t\t\t\t\t{$omos = $range.omos;}\n\t|\t^(DOT ID terminal[$label])\n\t|\t^(DOT ID ruleref[$label])\n    |\t^(WILDCARD .)\t\t\t\t\t\t\t{$omos = controller.wildcard($WILDCARD, $label);}\n    |\tWILDCARD\t\t\t\t\t\t\t\t{$omos = controller.wildcard($WILDCARD, $label);}\n    |   terminal[label]\t\t\t\t\t{$omos = $terminal.omos;}\n    |   ruleref[label]\t\t\t\t\t{$omos = $ruleref.omos;}\n\t|\tblockSet[$label, invert]\t\t{$omos = $blockSet.omos;}\n\t;\n\nruleref[GrammarAST label] returns [List<SrcOp> omos]\n    :\t^(RULE_REF ARG_ACTION? elementOptions?)\t\t{$omos = controller.ruleRef($RULE_REF, $label, $ARG_ACTION);}\n    ;\n\nrange[GrammarAST label] returns [List<SrcOp> omos]\n    :\t^(RANGE a=STRING_LITERAL b=STRING_LITERAL)\n    ;\n\nterminal[GrammarAST label] returns [List<SrcOp> omos]\n    :  ^(STRING_LITERAL .)\t\t\t{$omos = controller.stringRef($STRING_LITERAL, $label);}\n    |\tSTRING_LITERAL\t\t\t\t{$omos = controller.stringRef($STRING_LITERAL, $label);}\n    |\t^(TOKEN_REF ARG_ACTION .)\t{$omos = controller.tokenRef($TOKEN_REF, $label, $ARG_ACTION);}\n    |\t^(TOKEN_REF .)\t\t\t\t{$omos = controller.tokenRef($TOKEN_REF, $label, null);}\n    |\tTOKEN_REF\t\t\t\t\t{$omos = controller.tokenRef($TOKEN_REF, $label, null);}\n    ;\n\nelementOptions\n    :\t^(ELEMENT_OPTIONS elementOption+)\n    ;\n\nelementOption\n    :\tID\n    |   ^(ASSIGN ID ID)\n    |   ^(ASSIGN ID STRING_LITERAL)\n    |   ^(ASSIGN ID ACTION)\n    |   ^(ASSIGN ID INT)\n    ;\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/SourceType.java",
    "content": "package org.antlr.v4.codegen;\n\npublic enum SourceType {\n\tHEADER,\n\tSOURCE,\n\tSOURCE_LEAN,\n\tSOURCE_DFA,\n\tSOURCE_CONTEXTS\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/Target.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.model.RuleFunction;\nimport org.antlr.v4.codegen.model.SerializedATN;\nimport org.antlr.v4.misc.CharSupport;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.RuntimeMetaData;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.stringtemplate.v4.*;\nimport org.stringtemplate.v4.misc.STMessage;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\n\n/** */\npublic abstract class Target {\n\tprivate final static Map<String, STGroup> languageTemplates = new HashMap<>();\n\n\tprotected final CodeGenerator gen;\n\n\tprotected static final Map<Character, String> defaultCharValueEscape;\n\tstatic {\n\t\t// https://docs.oracle.com/javase/tutorial/java/data/characters.html\n\t\tHashMap<Character, String> map = new HashMap<>();\n\t\taddEscapedChar(map, '\\t', 't');\n\t\taddEscapedChar(map, '\\b', 'b');\n\t\taddEscapedChar(map, '\\n', 'n');\n\t\taddEscapedChar(map, '\\r', 'r');\n\t\taddEscapedChar(map, '\\f', 'f');\n\t\taddEscapedChar(map, '\\'');\n\t\taddEscapedChar(map, '\\\"');\n\t\taddEscapedChar(map, '\\\\');\n\t\tdefaultCharValueEscape = map;\n\t}\n\n\tprotected Target(CodeGenerator gen) {\n\t\tthis.gen = gen;\n\t}\n\n\t/** For pure strings of Unicode char, how can we display\n\t *  it in the target language as a literal. Useful for dumping\n\t *  predicates and such that may refer to chars that need to be escaped\n\t *  when represented as strings.  Also, templates need to be escaped so\n\t *  that the target language can hold them as a string.\n\t *  Each target can have a different set in memory at same time.\n\t */\n\tpublic Map<Character, String> getTargetCharValueEscape() {\n\t\treturn defaultCharValueEscape;\n\t}\n\n\tprotected static void addEscapedChar(HashMap<Character, String> map, char key) {\n\t\taddEscapedChar(map, key, key);\n\t}\n\n\tprotected static void addEscapedChar(HashMap<Character, String> map, char key, char representation) {\n\t\tmap.put(key, \"\\\\\" + representation);\n\t}\n\n\tpublic String getLanguage() { return gen.language; }\n\n\tpublic CodeGenerator getCodeGenerator() {\n\t\treturn gen;\n\t}\n\n\t/** ANTLR tool should check output templates / target are compatible with tool code generation.\n\t *  For now, a simple string match used on x.y of x.y.z scheme. We use a method to avoid mismatches\n\t *  between a template called VERSION. This value is checked against Tool.VERSION during load of templates.\n\t *\n\t *  This additional method forces all targets 4.3 and beyond to add this method.\n\t *\n\t * @since 4.3\n\t */\n\tpublic String getVersion() {\n\t\treturn Tool.VERSION;\n\t}\n\n\tpublic synchronized STGroup getTemplates() {\n\t\tString language = getLanguage();\n\t\tSTGroup templates = languageTemplates.get(language);\n\n\t\tif (templates == null) {\n\t\t\tString version = getVersion();\n\t\t\tif (version == null ||\n\t\t\t\t\t!RuntimeMetaData.getMajorMinorVersion(version).equals(RuntimeMetaData.getMajorMinorVersion(Tool.VERSION))) {\n\t\t\t\tgen.tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language);\n\t\t\t}\n\t\t\ttemplates = loadTemplates();\n\t\t\tlanguageTemplates.put(language, templates);\n\t\t}\n\n\t\treturn templates;\n\t}\n\n\tprotected abstract Set<String> getReservedWords();\n\n\tpublic String escapeIfNeeded(String identifier) {\n\t\treturn getReservedWords().contains(identifier) ? escapeWord(identifier) : identifier;\n\t}\n\n\tprotected String escapeWord(String word) {\n\t\treturn word + \"_\";\n\t}\n\n\tprotected void genFile(Grammar g, ST outputFileST, String fileName)\n\t{\n\t\tgetCodeGenerator().write(outputFileST, fileName);\n\t}\n\n\t/** Get a meaningful name for a token type useful during code generation.\n\t *  Literals without associated names are converted to the string equivalent\n\t *  of their integer values. Used to generate x==ID and x==34 type comparisons\n\t *  etc...  Essentially we are looking for the most obvious way to refer\n\t *  to a token type in the generated code.\n\t */\n\tpublic String getTokenTypeAsTargetLabel(Grammar g, int ttype) {\n\t    String name = this.escapeIfNeeded(g.getTokenName(ttype));\n\t\t// If name is not valid, return the token type instead\n\t\tif ( Grammar.INVALID_TOKEN_NAME.equals(name) ) {\n\t\t\treturn String.valueOf(ttype);\n\t\t}\n\n\t\treturn name;\n\t}\n\n\tpublic String[] getTokenTypesAsTargetLabels(Grammar g, int[] ttypes) {\n\t\tString[] labels = new String[ttypes.length];\n\t\tfor (int i=0; i<ttypes.length; i++) {\n\t\t\tlabels[i] = getTokenTypeAsTargetLabel(g, ttypes[i]);\n\t\t}\n\t\treturn labels;\n\t}\n\n\t/** Given a random string of Java unicode chars, return a new string with\n\t *  optionally appropriate quote characters for target language and possibly\n\t *  with some escaped characters.  For example, if the incoming string has\n\t *  actual newline characters, the output of this method would convert them\n\t *  to the two char sequence \\n for Java, C, C++, ...  The new string has\n\t *  double-quotes around it as well.  Example String in memory:\n\t *\n\t *     a\"[newlinechar]b'c[carriagereturnchar]d[tab]e\\f\n\t *\n\t *  would be converted to the valid Java s:\n\t *\n\t *     \"a\\\"\\nb'c\\rd\\te\\\\f\"\n\t *\n\t *  or\n\t *\n\t *     a\\\"\\nb'c\\rd\\te\\\\f\n\t *\n\t *  depending on the quoted arg.\n\t */\n\tpublic String getTargetStringLiteralFromString(String s, boolean quoted) {\n\t\tif ( s==null ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tif ( quoted ) {\n\t\t\tbuf.append('\"');\n\t\t}\n\t\tfor (int i=0; i < s.length(); ) {\n\t\t\tint c = s.codePointAt(i);\n\t\t\tString escaped = c <= Character.MAX_VALUE ? getTargetCharValueEscape().get((char)c) : null;\n\t\t\tif (c != '\\'' && escaped != null) { // don't escape single quotes in strings for java\n\t\t\t\tbuf.append(escaped);\n\t\t\t}\n\t\t\telse if (shouldUseUnicodeEscapeForCodePointInDoubleQuotedString(c)) {\n\t\t\t\tappendUnicodeEscapedCodePoint(i, buf);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbuf.appendCodePoint(c);\n\t\t\t}\n\t\t\ti += Character.charCount(c);\n\t\t}\n\t\tif ( quoted ) {\n\t\t\tbuf.append('\"');\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tprivate void appendUnicodeEscapedCodePoint(int codePoint, StringBuilder sb, boolean escape) {\n\t\tif (escape) {\n\t\t\tsb.append(\"\\\\\");\n\t\t}\n\t\tappendUnicodeEscapedCodePoint(codePoint, sb);\n\t}\n\n\t/**\n\t * Escape the Unicode code point appropriately for this language\n\t * and append the escaped value to {@code sb}.\n\t * It exists for flexibility and backward compatibility with external targets\n\t * The static method {@link UnicodeEscapes#appendEscapedCodePoint(StringBuilder, int, String)} can be used as well\n\t * if default escaping method (Java) is used or language is officially supported\n\t */\n\tprotected void appendUnicodeEscapedCodePoint(int codePoint, StringBuilder sb) {\n\t\tUnicodeEscapes.appendEscapedCodePoint(sb, codePoint, getLanguage());\n\t}\n\n\tpublic String getTargetStringLiteralFromString(String s) {\n\t\treturn getTargetStringLiteralFromString(s, true);\n\t}\n\n\tpublic String getTargetStringLiteralFromANTLRStringLiteral(CodeGenerator generator, String literal, boolean addQuotes) {\n\t\treturn getTargetStringLiteralFromANTLRStringLiteral(generator, literal, addQuotes, false);\n\t}\n\n\t/**\n\t * <p>Convert from an ANTLR string literal found in a grammar file to an\n\t * equivalent string literal in the target language.\n\t *</p>\n\t * <p>\n\t * For Java, this is the translation {@code 'a\\n\"'} &rarr; {@code \"a\\n\\\"\"}.\n\t * Expect single quotes around the incoming literal. Just flip the quotes\n\t * and replace double quotes with {@code \\\"}.\n\t * </p>\n\t * <p>\n\t * Note that we have decided to allow people to use '\\\"' without penalty, so\n\t * we must build the target string in a loop as {@link String#replace}\n\t * cannot handle both {@code \\\"} and {@code \"} without a lot of messing\n\t * around.\n\t * </p>\n\t */\n\tpublic String getTargetStringLiteralFromANTLRStringLiteral(\n\t\tCodeGenerator generator,\n\t\tString literal,\n\t\tboolean addQuotes,\n\t\tboolean escapeSpecial)\n\t{\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tif ( addQuotes ) sb.append('\"');\n\n\t\tfor (int i = 1; i < literal.length() -1; ) {\n\t\t\tint codePoint = literal.codePointAt(i);\n\t\t\tint toAdvance = Character.charCount(codePoint);\n\t\t\tif  (codePoint == '\\\\') {\n\t\t\t\t// Anything escaped is what it is! We assume that\n\t\t\t\t// people know how to escape characters correctly. However\n\t\t\t\t// we catch anything that does not need an escape in Java (which\n\t\t\t\t// is what the default implementation is dealing with and remove\n\t\t\t\t// the escape. The C target does this for instance.\n\t\t\t\t//\n\t\t\t\tint escapedCodePoint = literal.codePointAt(i+toAdvance);\n\t\t\t\ttoAdvance++;\n\t\t\t\tswitch (escapedCodePoint) {\n\t\t\t\t\t// Pass through any escapes that Java also needs\n\t\t\t\t\t//\n\t\t\t\t\tcase    'n':\n\t\t\t\t\tcase    'r':\n\t\t\t\t\tcase    't':\n\t\t\t\t\tcase    'b':\n\t\t\t\t\tcase    'f':\n\t\t\t\t\tcase    '\\\\':\n\t\t\t\t\t\t// Pass the escape through\n\t\t\t\t\t\tif (escapeSpecial && escapedCodePoint != '\\\\') {\n\t\t\t\t\t\t\tsb.append('\\\\');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsb.append('\\\\');\n\t\t\t\t\t\tsb.appendCodePoint(escapedCodePoint);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase    'u':    // Either unnnn or u{nnnnnn}\n\t\t\t\t\t\tif (literal.charAt(i+toAdvance) == '{') {\n\t\t\t\t\t\t\twhile (literal.charAt(i+toAdvance) != '}') {\n\t\t\t\t\t\t\t\ttoAdvance++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttoAdvance++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\ttoAdvance += 4;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ( i+toAdvance <= literal.length() ) { // we might have an invalid \\\\uAB or something\n\t\t\t\t\t\t\tString fullEscape = literal.substring(i, i+toAdvance);\n\t\t\t\t\t\t\tappendUnicodeEscapedCodePoint(\n\t\t\t\t\t\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(fullEscape),\n\t\t\t\t\t\t\t\tsb,\n\t\t\t\t\t\t\t\tescapeSpecial);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif (shouldUseUnicodeEscapeForCodePointInDoubleQuotedString(escapedCodePoint)) {\n\t\t\t\t\t\t\tappendUnicodeEscapedCodePoint(escapedCodePoint, sb, escapeSpecial);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsb.appendCodePoint(escapedCodePoint);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (codePoint == 0x22) {\n\t\t\t\t\t// ANTLR doesn't escape \" in literal strings,\n\t\t\t\t\t// but every other language needs to do so.\n\t\t\t\t\tsb.append(\"\\\\\\\"\");\n\t\t\t\t}\n\t\t\t\telse if (shouldUseUnicodeEscapeForCodePointInDoubleQuotedString(codePoint)) {\n\t\t\t\t\tappendUnicodeEscapedCodePoint(codePoint, sb, escapeSpecial);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsb.appendCodePoint(codePoint);\n\t\t\t\t}\n\t\t\t}\n\t\t\ti += toAdvance;\n\t\t}\n\n\t\tif ( addQuotes ) sb.append('\"');\n\n\t\treturn sb.toString();\n\t}\n\n\tprotected boolean shouldUseUnicodeEscapeForCodePointInDoubleQuotedString(int codePoint) {\n\t\t// We don't want anyone passing 0x0A (newline) or 0x22\n\t\t// (double-quote) here because Java treats \\\\u000A as\n\t\t// a literal newline and \\\\u0022 as a literal\n\t\t// double-quote, so Unicode escaping doesn't help.\n\t\tassert codePoint != 0x0A && codePoint != 0x22;\n\n\t\treturn\n\t\t\tcodePoint < 0x20  || // control characters up to but not including space\n\t\t\tcodePoint == 0x5C || // backslash\n\t\t\tcodePoint >= 0x7F;   // DEL and beyond (keeps source code 7-bit US-ASCII)\n\t}\n\n\t/** Assume 16-bit char */\n\tpublic String encodeInt16AsCharEscape(int v) {\n\t\tif (v < Character.MIN_VALUE || v > Character.MAX_VALUE) {\n\t\t\tthrow new IllegalArgumentException(String.format(\"Cannot encode the specified value: %d\", v));\n\t\t}\n\n\t\tif ( isATNSerializedAsInts() ) {\n\t\t\treturn Integer.toString(v);\n\t\t}\n\n\t\tchar c = (char)v;\n\t\tString escaped = getTargetCharValueEscape().get(c);\n\t\tif (escaped != null) {\n\t\t\treturn escaped;\n\t\t}\n\n\t\tswitch (Character.getType(c)) {\n\t\t\tcase Character.CONTROL:\n\t\t\tcase Character.LINE_SEPARATOR:\n\t\t\tcase Character.PARAGRAPH_SEPARATOR:\n\t\t\t\treturn escapeChar(v);\n\t\t\tdefault:\n\t\t\t\tif ( v<=127 ) {\n\t\t\t\t\treturn String.valueOf(c);  // ascii chars can be as-is, no encoding\n\t\t\t\t}\n\t\t\t\t// else we use hex encoding to ensure pure ascii chars generated\n\t\t\t\treturn escapeChar(v);\n\t\t}\n\t}\n\n\tprotected String escapeChar(int v) {\n\t\treturn String.format(\"\\\\u%04x\", v);\n\t}\n\n\tpublic String getLoopLabel(GrammarAST ast) {\n\t\treturn \"loop\"+ ast.token.getTokenIndex();\n\t}\n\n\tpublic String getLoopCounter(GrammarAST ast) {\n\t\treturn \"cnt\"+ ast.token.getTokenIndex();\n\t}\n\n\tpublic String getListLabel(String label) {\n\t\tST st = getTemplates().getInstanceOf(\"ListLabelName\");\n\t\tst.add(\"label\", label);\n\t\treturn st.render();\n\t}\n\n\tpublic String getRuleFunctionContextStructName(Rule r) {\n\t\tif ( r.g.isLexer() ) {\n\t\t\treturn getTemplates().getInstanceOf(\"LexerRuleContext\").render();\n\t\t}\n\t\treturn Utils.capitalize(r.name)+getTemplates().getInstanceOf(\"RuleContextNameSuffix\").render();\n\t}\n\n\tpublic String getAltLabelContextStructName(String label) {\n\t\treturn Utils.capitalize(label)+getTemplates().getInstanceOf(\"RuleContextNameSuffix\").render();\n\t}\n\n\t/** If we know which actual function, we can provide the actual ctx type.\n\t *  This will contain implicit labels etc...  From outside, though, we\n\t *  see only ParserRuleContext unless there are externally visible stuff\n\t *  like args, locals, explicit labels, etc...\n\t */\n\tpublic String getRuleFunctionContextStructName(RuleFunction function) {\n\t\tRule r = function.rule;\n\t\tif ( r.g.isLexer() ) {\n\t\t\treturn getTemplates().getInstanceOf(\"LexerRuleContext\").render();\n\t\t}\n\t\treturn Utils.capitalize(r.name)+getTemplates().getInstanceOf(\"RuleContextNameSuffix\").render();\n\t}\n\n\t// should be same for all refs to same token like ctx.ID within single rule function\n\t// for literals like 'while', we gen _s<ttype>\n\tpublic String getImplicitTokenLabel(String tokenName) {\n\t\tST st = getTemplates().getInstanceOf(\"ImplicitTokenLabel\");\n\t\tint ttype = getCodeGenerator().g.getTokenType(tokenName);\n\t\tif ( tokenName.startsWith(\"'\") ) {\n\t\t\treturn \"s\"+ttype;\n\t\t}\n\t\tString text = getTokenTypeAsTargetLabel(getCodeGenerator().g, ttype);\n\t\tst.add(\"tokenName\", text);\n\t\treturn st.render();\n\t}\n\n\t// x=(A|B)\n\tpublic String getImplicitSetLabel(String id) {\n\t\tST st = getTemplates().getInstanceOf(\"ImplicitSetLabel\");\n\t\tst.add(\"id\", id);\n\t\treturn st.render();\n\t}\n\n\tpublic String getImplicitRuleLabel(String ruleName) {\n\t\tST st = getTemplates().getInstanceOf(\"ImplicitRuleLabel\");\n\t\tst.add(\"ruleName\", ruleName);\n\t\treturn st.render();\n\t}\n\n\tpublic String getElementListName(String name) {\n\t\tST st = getTemplates().getInstanceOf(\"ElementListName\");\n\t\tst.add(\"elemName\", getElementName(name));\n\t\treturn st.render();\n\t}\n\n\tpublic String getElementName(String name) {\n\t\tif (\".\".equals(name)) {\n\t\t\treturn \"_wild\";\n\t\t}\n\n\t\tif ( getCodeGenerator().g.getRule(name)!=null ) return name;\n\t\tint ttype = getCodeGenerator().g.getTokenType(name);\n\t\tif ( ttype==Token.INVALID_TYPE ) return name;\n\t\treturn getTokenTypeAsTargetLabel(getCodeGenerator().g, ttype);\n\t}\n\n\t/** Generate TParser.java and TLexer.java from T.g4 if combined, else\n\t *  just use T.java as output regardless of type.\n\t */\n\tpublic String getRecognizerFileName(SourceType sourceType) {\n\t\tST extST = getTemplates().getInstanceOf(\"codeFileExtension\");\n\t\tString recognizerName = gen.g.getRecognizerName();\n\t\treturn recognizerName+extST.render();\n\t}\n\n\t/** A given grammar T, return the listener name such as\n\t *  TListener.java, if we're using the Java target.\n \t */\n\tpublic String getListenerFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(\"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"Listener\";\n\t\treturn listenerName+extST.render();\n\t}\n\n\t/** A given grammar T, return the visitor name such as\n\t *  TVisitor.java, if we're using the Java target.\n \t */\n\tpublic String getVisitorFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(\"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"Visitor\";\n\t\treturn listenerName+extST.render();\n\t}\n\n\t/** A given grammar T, return a blank listener implementation\n\t *  such as TBaseListener.java, if we're using the Java target.\n \t */\n\tpublic String getBaseListenerFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(\"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"BaseListener\";\n\t\treturn listenerName+extST.render();\n\t}\n\n\t/** A given grammar T, return a blank listener implementation\n\t *  such as TBaseListener.java, if we're using the Java target.\n \t */\n\tpublic String getBaseVisitorFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(\"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"BaseVisitor\";\n\t\treturn listenerName+extST.render();\n\t}\n\n\t/**\n\t * Gets the maximum number of 16-bit unsigned integers that can be encoded\n\t * in a single segment (a declaration in target language) of the serialized ATN.\n\t * E.g., in C++, a small segment length results in multiple decls like:\n\t *\n\t *   static const int32_t serializedATNSegment1[] = {\n\t *     0x7, 0x12, 0x2, 0x13, 0x7, 0x13, 0x2, 0x14, 0x7, 0x14, 0x2, 0x15, 0x7,\n\t *        0x15, 0x2, 0x16, 0x7, 0x16, 0x2, 0x17, 0x7, 0x17, 0x2, 0x18, 0x7,\n\t *        0x18, 0x2, 0x19, 0x7, 0x19, 0x2, 0x1a, 0x7, 0x1a, 0x2, 0x1b, 0x7,\n\t *        0x1b, 0x2, 0x1c, 0x7, 0x1c, 0x2, 0x1d, 0x7, 0x1d, 0x2, 0x1e, 0x7,\n\t *        0x1e, 0x2, 0x1f, 0x7, 0x1f, 0x2, 0x20, 0x7, 0x20, 0x2, 0x21, 0x7,\n\t *        0x21, 0x2, 0x22, 0x7, 0x22, 0x2, 0x23, 0x7, 0x23, 0x2, 0x24, 0x7,\n\t *        0x24, 0x2, 0x25, 0x7, 0x25, 0x2, 0x26,\n\t *   };\n\t *\n\t * instead of one big one.  Targets are free to ignore this like JavaScript does.\n\t *\n\t * This is primarily needed by Java target to limit size of any single ATN string\n\t * to 65k length.\n\t *\n\t * @see SerializedATN#getSegments\n\t *\n\t * @return the serialized ATN segment limit\n\t */\n\tpublic int getSerializedATNSegmentLimit() {\n\t\treturn Integer.MAX_VALUE;\n\t}\n\n\t/** How many bits should be used to do inline token type tests? Java assumes\n\t *  a 64-bit word for bitsets.  Must be a valid wordsize for your target like\n\t *  8, 16, 32, 64, etc...\n\t *\n\t *  @since 4.5\n\t */\n\tpublic int getInlineTestSetWordSize() { return 64; }\n\n\tpublic boolean grammarSymbolCausesIssueInGeneratedCode(GrammarAST idNode) {\n\t\tswitch (idNode.getParent().getType()) {\n\t\t\tcase ANTLRParser.ASSIGN:\n\t\t\t\tswitch (idNode.getParent().getParent().getType()) {\n\t\t\t\t\tcase ANTLRParser.ELEMENT_OPTIONS:\n\t\t\t\t\tcase ANTLRParser.OPTIONS:\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase ANTLRParser.AT:\n\t\t\tcase ANTLRParser.ELEMENT_OPTIONS:\n\t\t\t\treturn false;\n\n\t\t\tcase ANTLRParser.LEXER_ACTION_CALL:\n\t\t\t\tif (idNode.getChildIndex() == 0) {\n\t\t\t\t\t// first child is the command name which is part of the ANTLR language\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\t// arguments to the command should be checked\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn getReservedWords().contains(idNode.getText());\n\t}\n\n\t@Deprecated\n\tprotected boolean visibleGrammarSymbolCausesIssueInGeneratedCode(GrammarAST idNode) {\n\t\treturn getReservedWords().contains(idNode.getText());\n\t}\n\n\tpublic boolean templatesExist() {\n\t\treturn loadTemplatesHelper(false) != null;\n\t}\n\n\tprotected STGroup loadTemplates() {\n\t\tSTGroup result = loadTemplatesHelper(true);\n\t\tif (result == null) {\n\t\t\treturn null;\n\t\t}\n\t\tresult.registerRenderer(Integer.class, new NumberRenderer());\n\t\tresult.registerRenderer(String.class, new StringRenderer());\n\t\tresult.setListener(new STErrorListener() {\n\t\t\t@Override\n\t\t\tpublic void compileTimeError(STMessage msg) {\n\t\t\t\treportError(msg);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void runTimeError(STMessage msg) {\n\t\t\t\treportError(msg);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void IOError(STMessage msg) {\n\t\t\t\treportError(msg);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void internalError(STMessage msg) {\n\t\t\t\treportError(msg);\n\t\t\t}\n\n\t\t\tprivate void reportError(STMessage msg) {\n\t\t\t\t// TODO check how to avoid this with Ter\n\t\t\t\tif(\"/RuleSempredFunction()\".equals(String.valueOf(msg.self)) && \"Java\".equals(String.valueOf(msg.self.groupThatCreatedThisInstance))) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tgetCodeGenerator().tool.errMgr.toolError(ErrorType.STRING_TEMPLATE_WARNING, msg.cause, msg.toString());\n\t\t\t}\n\t\t});\n\n\t\treturn result;\n\t}\n\n\tprivate STGroup loadTemplatesHelper(boolean reportErrorIfFail) {\n\t\tString language = getLanguage();\n\t\tString groupFileName = CodeGenerator.TEMPLATE_ROOT + \"/\" + language + \"/\" + language + STGroup.GROUP_FILE_EXTENSION;\n\t\ttry {\n\t\t\treturn new STGroupFile(groupFileName);\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\tif (reportErrorIfFail) {\n\t\t\t\tgen.tool.errMgr.toolError(ErrorType.MISSING_CODE_GEN_TEMPLATES, iae, getLanguage());\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * @since 4.3\n\t */\n\tpublic boolean wantsBaseListener() {\n\t\treturn true;\n\t}\n\n\t/** @since 4.3 */\n\tpublic boolean wantsBaseVisitor() {\n\t\treturn true;\n\t}\n\n\t/** @since 4.3 */\n\tpublic boolean supportsOverloadedMethods() {\n\t\treturn true;\n\t}\n\n\tpublic boolean isATNSerializedAsInts() {\n\t\treturn true;\n\t}\n\n\t/** @since 4.6 */\n\tpublic boolean needsHeader() { return false; } // Override in targets that need header files.\n\n\t/** @since 4.14 */\n    public boolean supportsSplitParser() { return false; }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/UnicodeEscapes.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen;\n\n/**\n * Utility class to escape Unicode code points using various\n * languages' syntax.\n */\npublic class UnicodeEscapes {\n\tpublic static String escapeCodePoint(int codePoint, String language) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tappendEscapedCodePoint(result, codePoint, language);\n\t\treturn result.toString();\n\t}\n\n\tpublic static void appendEscapedCodePoint(StringBuilder sb, int codePoint, String language) {\n\t\tswitch (language) {\n\t\t\tcase \"CSharp\":\n\t\t\tcase \"Python3\":\n\t\t\tcase \"Cpp\":\n\t\t\tcase \"Go\":\n\t\t\tcase \"PHP\":\n\t\t\t\tString format = Character.isSupplementaryCodePoint(codePoint) ? \"\\\\U%08X\" : \"\\\\u%04X\";\n\t\t\t\tsb.append(String.format(format, codePoint));\n\t\t\t\tbreak;\n\t\t\tcase \"Swift\":\n\t\t\t\tsb.append(String.format(\"\\\\u{%04X}\", codePoint));\n\t\t\t\tbreak;\n\t\t\tcase \"Java\":\n\t\t\tcase \"JavaScript\":\n\t\t\tcase \"TypeScript\":\n\t\t\tcase \"Dart\":\n\t\t\tdefault:\n\t\t\t\tif (Character.isSupplementaryCodePoint(codePoint)) {\n\t\t\t\t\t// char is not an 'integral' type, so we have to explicitly convert\n\t\t\t\t\t// to int before passing to the %X formatter or else it throws.\n\t\t\t\t\tsb.append(String.format(\"\\\\u%04X\", (int)Character.highSurrogate(codePoint)));\n\t\t\t\t\tsb.append(String.format(\"\\\\u%04X\", (int)Character.lowSurrogate(codePoint)));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsb.append(String.format(\"\\\\u%04X\", codePoint));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Action.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.v4.codegen.ActionTranslator;\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.chunk.ActionChunk;\nimport org.antlr.v4.codegen.model.chunk.ActionTemplate;\nimport org.antlr.v4.codegen.model.chunk.ActionText;\nimport org.antlr.v4.codegen.model.decl.StructDecl;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.stringtemplate.v4.ST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** */\npublic class Action extends RuleElement {\n\t@ModelElement public List<ActionChunk> chunks;\n\n\tpublic Action(OutputModelFactory factory, ActionAST ast) {\n\t\tsuper(factory,ast);\n\t\tRuleFunction rf = factory.getCurrentRuleFunction();\n\t\tif (ast != null) {\n\t\t\tchunks = ActionTranslator.translateAction(factory, rf, ast.token, ast);\n\t\t}\n\t\telse {\n\t\t\tchunks = new ArrayList<ActionChunk>();\n\t\t}\n\t\t//System.out.println(\"actions=\"+chunks);\n\t}\n\n\tpublic Action(OutputModelFactory factory, StructDecl ctx, String action) {\n\t\tsuper(factory,null);\n\t\tActionAST ast = new ActionAST(new CommonToken(ANTLRParser.ACTION, action));\n\t\tRuleFunction rf = factory.getCurrentRuleFunction();\n\t\tif ( rf!=null ) { // we can translate\n\t\t\tast.resolver = rf.rule;\n\t\t\tchunks = ActionTranslator.translateActionChunk(factory, rf, action, ast);\n\t\t}\n\t\telse {\n\t\t\tchunks = new ArrayList<ActionChunk>();\n\t\t\tchunks.add(new ActionText(ctx, action));\n\t\t}\n\t}\n\n\tpublic Action(OutputModelFactory factory, StructDecl ctx, ST actionST) {\n\t\tsuper(factory, null);\n\t\tchunks = new ArrayList<ActionChunk>();\n\t\tchunks.add(new ActionTemplate(ctx, actionST));\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/AddToLabelList.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.decl.Decl;\n\n/** */\npublic class AddToLabelList extends SrcOp {\n\tpublic final Decl label;\n\tpublic final String listName;\n\n\tpublic AddToLabelList(OutputModelFactory factory, String listName, Decl label) {\n\t\tsuper(factory);\n\t\tthis.label = label;\n\t\tthis.listName = listName;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/AltBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.atn.BlockStartState;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\npublic class AltBlock extends Choice {\n//\t@ModelElement public ThrowNoViableAlt error;\n\n\tpublic AltBlock(OutputModelFactory factory,\n\t\t\t\t\tGrammarAST blkOrEbnfRootAST,\n\t\t\t\t\tList<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, blkOrEbnfRootAST, alts);\n\t\tdecision = ((BlockStartState)blkOrEbnfRootAST.atnState).decision;\n\t\t// interp.predict() throws exception\n//\t\tthis.error = new ThrowNoViableAlt(factory, blkOrEbnfRootAST, null);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ArgAction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.ActionAST;\n\npublic class ArgAction extends Action {\n\t/** Context type of invoked rule */\n\tpublic String ctxType;\n\tpublic ArgAction(OutputModelFactory factory, ActionAST ast, String ctxType) {\n\t\tsuper(factory, ast);\n\t\tthis.ctxType = ctxType;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/BaseListenerFile.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class BaseListenerFile extends ListenerFile {\n\tpublic BaseListenerFile(OutputModelFactory factory, String fileName) {\n\t\tsuper(factory, fileName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/BaseVisitorFile.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class BaseVisitorFile extends VisitorFile {\n\tpublic BaseVisitorFile(OutputModelFactory factory, String fileName) {\n\t\tsuper(factory, fileName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/CaptureNextToken.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class CaptureNextToken extends SrcOp {\n\tpublic String varName;\n\tpublic CaptureNextToken(OutputModelFactory factory, String varName) {\n\t\tsuper(factory);\n\t\tthis.varName = varName;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/CaptureNextTokenType.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** */\npublic class CaptureNextTokenType extends SrcOp {\n\tpublic String varName;\n\tpublic CaptureNextTokenType(OutputModelFactory factory, String varName) {\n\t\tsuper(factory);\n\t\tthis.varName = varName;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Choice.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.codegen.model.decl.Decl;\nimport org.antlr.v4.codegen.model.decl.TokenTypeDecl;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** The class hierarchy underneath SrcOp is pretty deep but makes sense that,\n *  for example LL1StarBlock is a kind of LL1Loop which is a kind of Choice.\n *  The problem is it's impossible to figure\n *  out how to construct one of these deeply nested objects because of the\n *  long super constructor call chain. Instead, I decided to in-line all of\n *  this and then look for opportunities to re-factor code into functions.\n *  It makes sense to use a class hierarchy to share data fields, but I don't\n *  think it makes sense to factor code using super constructors because\n *  it has too much work to do.\n */\npublic abstract class Choice extends RuleElement {\n\tpublic int decision = -1;\n\tpublic Decl label;\n\n\t@ModelElement public List<CodeBlockForAlt> alts;\n\t@ModelElement public List<SrcOp> preamble = new ArrayList<SrcOp>();\n\n\tpublic Choice(OutputModelFactory factory,\n\t\t\t\t  GrammarAST blkOrEbnfRootAST,\n\t\t\t\t  List<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, blkOrEbnfRootAST);\n\t\tthis.alts = alts;\n\t}\n\n\tpublic void addPreambleOp(SrcOp op) {\n\t\tpreamble.add(op);\n\t}\n\n\tpublic List<TokenInfo[]> getAltLookaheadAsStringLists(IntervalSet[] altLookSets) {\n\t\tList<TokenInfo[]> altLook = new ArrayList<>();\n\t\tTarget target = factory.getGenerator().getTarget();\n\t\tGrammar grammar = factory.getGrammar();\n\t\tfor (IntervalSet s : altLookSets) {\n\t\t\tIntegerList list = s.toIntegerList();\n\t\t\tTokenInfo[] info = new TokenInfo[list.size()];\n\t\t\tfor (int i = 0; i < info.length; i++) {\n\t\t\t\tinfo[i] = new TokenInfo(list.get(i), target.getTokenTypeAsTargetLabel(grammar, list.get(i)));\n\t\t\t}\n\t\t\taltLook.add(info);\n\t\t}\n\t\treturn altLook;\n\t}\n\n\tpublic TestSetInline addCodeForLookaheadTempVar(IntervalSet look) {\n\t\tList<SrcOp> testOps = factory.getLL1Test(look, ast);\n\t\tTestSetInline expr = Utils.find(testOps, TestSetInline.class);\n\t\tif (expr != null) {\n\t\t\tDecl d = new TokenTypeDecl(factory, expr.varName);\n\t\t\tfactory.getCurrentRuleFunction().addLocalDecl(d);\n\t\t\tCaptureNextTokenType nextType = new CaptureNextTokenType(factory,expr.varName);\n\t\t\taddPreambleOp(nextType);\n\t\t}\n\t\treturn expr;\n\t}\n\n\tpublic ThrowNoViableAlt getThrowNoViableAlt(OutputModelFactory factory,\n\t\t\t\t\t\t\t\t\t\t\t\tGrammarAST blkAST,\n\t\t\t\t\t\t\t\t\t\t\t\tIntervalSet expecting) {\n\t\treturn new ThrowNoViableAlt(factory, blkAST, expecting);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/CodeBlockForAlt.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.decl.CodeBlock;\n\n/** Contains Rewrite block (usually as last op) */\npublic class CodeBlockForAlt extends CodeBlock {\n\n\tpublic CodeBlockForAlt(OutputModelFactory factory) {\n\t\tsuper(factory);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/CodeBlockForOuterMostAlt.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.Alternative;\n\n/** The code associated with the outermost alternative of a rule.\n *  Sometimes we might want to treat them differently in the\n *  code generation.\n */\npublic class CodeBlockForOuterMostAlt extends CodeBlockForAlt {\n\t/**\n\t * The label for the alternative; or null if the alternative is not labeled.\n\t */\n\tpublic String altLabel;\n\t/**\n\t * The alternative.\n\t */\n\tpublic Alternative alt;\n\n\tpublic CodeBlockForOuterMostAlt(OutputModelFactory factory, Alternative alt) {\n\t\tsuper(factory);\n\t\tthis.alt = alt;\n\t\taltLabel = alt.ast.altLabel!=null ? alt.ast.altLabel.getText() : null;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/DispatchMethod.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class DispatchMethod extends OutputModelObject {\n\tpublic DispatchMethod(OutputModelFactory factory) {\n\t\tsuper(factory);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ElementFrequenciesVisitor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.runtime.tree.TreeNodeStream;\nimport org.antlr.v4.misc.FrequencySet;\nimport org.antlr.v4.misc.MutableInt;\nimport org.antlr.v4.parse.GrammarTreeVisitor;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.ArrayDeque;\nimport java.util.Deque;\nimport java.util.Map;\n\npublic class ElementFrequenciesVisitor extends GrammarTreeVisitor {\n\t/**\n\t * This special value means \"no set\", and is used by {@link #minFrequencies}\n\t * to ensure that {@link #combineMin} doesn't merge an empty set (all zeros)\n\t * with the results of the first alternative.\n\t */\n\tprivate static final FrequencySet<String> SENTINEL = new FrequencySet<String>();\n\n\tfinal Deque<FrequencySet<String>> frequencies;\n\tprivate final Deque<FrequencySet<String>> minFrequencies;\n\n\tpublic ElementFrequenciesVisitor(TreeNodeStream input) {\n\t\tsuper(input);\n\t\tfrequencies = new ArrayDeque<FrequencySet<String>>();\n\t\tfrequencies.push(new FrequencySet<String>());\n\t\tminFrequencies = new ArrayDeque<FrequencySet<String>>();\n\t\tminFrequencies.push(SENTINEL);\n\t}\n\n\tFrequencySet<String> getMinFrequencies() {\n\t\tassert minFrequencies.size() == 1;\n\t\tassert minFrequencies.peek() != SENTINEL;\n\t\tassert SENTINEL.isEmpty();\n\n\t\treturn minFrequencies.peek();\n\t}\n\n\t/** During code gen, we can assume tree is in good shape */\n\t@Override\n\tpublic ErrorManager getErrorManager() { return super.getErrorManager(); }\n\n\t/*\n\t * Common\n\t */\n\n\t/**\n\t * Generate a frequency set as the union of two input sets. If an\n\t * element is contained in both sets, the value for the output will be\n\t * the maximum of the two input values.\n\t *\n\t * @param a The first set.\n\t * @param b The second set.\n\t * @return The union of the two sets, with the maximum value chosen\n\t * whenever both sets contain the same key.\n\t */\n\tprotected static FrequencySet<String> combineMax(FrequencySet<String> a, FrequencySet<String> b) {\n\t\tFrequencySet<String> result = combineAndClip(a, b, 1);\n\t\tfor (Map.Entry<String, MutableInt> entry : a.entrySet()) {\n\t\t\tresult.get(entry.getKey()).v = entry.getValue().v;\n\t\t}\n\n\t\tfor (Map.Entry<String, MutableInt> entry : b.entrySet()) {\n\t\t\tMutableInt slot = result.get(entry.getKey());\n\t\t\tslot.v = Math.max(slot.v, entry.getValue().v);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Generate a frequency set as the union of two input sets. If an\n\t * element is contained in both sets, the value for the output will be\n\t * the minimum of the two input values.\n\t *\n\t * @param a The first set.\n\t * @param b The second set. If this set is {@link #SENTINEL}, it is treated\n\t * as though no second set were provided.\n\t * @return The union of the two sets, with the minimum value chosen\n\t * whenever both sets contain the same key.\n\t */\n\tprotected static FrequencySet<String> combineMin(FrequencySet<String> a, FrequencySet<String> b) {\n\t\tif (b == SENTINEL) {\n\t\t\treturn a;\n\t\t}\n\n\t\tassert a != SENTINEL;\n\t\tFrequencySet<String> result = combineAndClip(a, b, Integer.MAX_VALUE);\n\t\tfor (Map.Entry<String, MutableInt> entry : result.entrySet()) {\n\t\t\tentry.getValue().v = Math.min(a.count(entry.getKey()), b.count(entry.getKey()));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Generate a frequency set as the union of two input sets, with the\n\t * values clipped to a specified maximum value. If an element is\n\t * contained in both sets, the value for the output, prior to clipping,\n\t * will be the sum of the two input values.\n\t *\n\t * @param a The first set.\n\t * @param b The second set.\n\t * @param clip The maximum value to allow for any output.\n\t * @return The sum of the two sets, with the individual elements clipped\n\t * to the maximum value given by {@code clip}.\n\t */\n\tprotected static FrequencySet<String> combineAndClip(FrequencySet<String> a, FrequencySet<String> b, int clip) {\n\t\tFrequencySet<String> result = new FrequencySet<String>();\n\t\tfor (Map.Entry<String, MutableInt> entry : a.entrySet()) {\n\t\t\tfor (int i = 0; i < entry.getValue().v; i++) {\n\t\t\t\tresult.add(entry.getKey());\n\t\t\t}\n\t\t}\n\n\t\tfor (Map.Entry<String, MutableInt> entry : b.entrySet()) {\n\t\t\tfor (int i = 0; i < entry.getValue().v; i++) {\n\t\t\t\tresult.add(entry.getKey());\n\t\t\t}\n\t\t}\n\n\t\tfor (Map.Entry<String, MutableInt> entry : result.entrySet()) {\n\t\t\tentry.getValue().v = Math.min(entry.getValue().v, clip);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic void tokenRef(TerminalAST ref) {\n\t\tfrequencies.peek().add(ref.getText());\n\t\tminFrequencies.peek().add(ref.getText());\n\t}\n\n\t@Override\n\tpublic void ruleRef(GrammarAST ref, ActionAST arg) {\n\t\tfrequencies.peek().add(ref.getText());\n\t\tminFrequencies.peek().add(ref.getText());\n\t}\n\n\t@Override\n\tpublic void stringRef(TerminalAST ref) {\n\t\tString tokenName = ref.g.getTokenName(ref.getText());\n\n\t\tif (tokenName != null && !tokenName.startsWith(\"T__\")) {\n\t\t\tfrequencies.peek().add(tokenName);\n\t\t\tminFrequencies.peek().add(tokenName);\n\t\t}\n\t}\n\n\t/*\n\t * Parser rules\n\t */\n\n\t@Override\n\tprotected void enterAlternative(AltAST tree) {\n\t\tfrequencies.push(new FrequencySet<String>());\n\t\tminFrequencies.push(new FrequencySet<String>());\n\t}\n\n\t@Override\n\tprotected void exitAlternative(AltAST tree) {\n\t\tfrequencies.push(combineMax(frequencies.pop(), frequencies.pop()));\n\t\tminFrequencies.push(combineMin(minFrequencies.pop(), minFrequencies.pop()));\n\t}\n\n\t@Override\n\tprotected void enterElement(GrammarAST tree) {\n\t\tfrequencies.push(new FrequencySet<String>());\n\t\tminFrequencies.push(new FrequencySet<String>());\n\t}\n\n\t@Override\n\tprotected void exitElement(GrammarAST tree) {\n\t\tfrequencies.push(combineAndClip(frequencies.pop(), frequencies.pop(), 2));\n\t\tminFrequencies.push(combineAndClip(minFrequencies.pop(), minFrequencies.pop(), 2));\n\t}\n\n\t@Override\n\tprotected void enterBlockSet(GrammarAST tree) {\n\t\tfrequencies.push(new FrequencySet<String>());\n\t\tminFrequencies.push(new FrequencySet<String>());\n\t}\n\n\t@Override\n\tprotected void exitBlockSet(GrammarAST tree) {\n\t\tfor (Map.Entry<String, MutableInt> entry : frequencies.peek().entrySet()) {\n\t\t\t// This visitor counts a block set as a sequence of elements, not a\n\t\t\t// sequence of alternatives of elements. Reset the count back to 1\n\t\t\t// for all items when leaving the set to ensure duplicate entries in\n\t\t\t// the set are treated as a maximum of one item.\n\t\t\tentry.getValue().v = 1;\n\t\t}\n\n\t\tif (minFrequencies.peek().size() > 1) {\n\t\t\t// Everything is optional\n\t\t\tminFrequencies.peek().clear();\n\t\t}\n\n\t\tfrequencies.push(combineAndClip(frequencies.pop(), frequencies.pop(), 2));\n\t\tminFrequencies.push(combineAndClip(minFrequencies.pop(), minFrequencies.pop(), 2));\n\t}\n\n\t@Override\n\tprotected void exitSubrule(GrammarAST tree) {\n\t\tif (tree.getType() == CLOSURE || tree.getType() == POSITIVE_CLOSURE) {\n\t\t\tfor (Map.Entry<String, MutableInt> entry : frequencies.peek().entrySet()) {\n\t\t\t\tentry.getValue().v = 2;\n\t\t\t}\n\t\t}\n\n\t\tif (tree.getType() == CLOSURE || tree.getType() == OPTIONAL) {\n\t\t\t// Everything inside a closure is optional, so the minimum\n\t\t\t// number of occurrences for all elements is 0.\n\t\t\tminFrequencies.peek().clear();\n\t\t}\n\t}\n\n\t/*\n\t * Lexer rules\n\t */\n\n\t@Override\n\tprotected void enterLexerAlternative(GrammarAST tree) {\n\t\tfrequencies.push(new FrequencySet<String>());\n\t\tminFrequencies.push(new FrequencySet<String>());\n\t}\n\n\t@Override\n\tprotected void exitLexerAlternative(GrammarAST tree) {\n\t\tfrequencies.push(combineMax(frequencies.pop(), frequencies.pop()));\n\t\tminFrequencies.push(combineMin(minFrequencies.pop(), minFrequencies.pop()));\n\t}\n\n\t@Override\n\tprotected void enterLexerElement(GrammarAST tree) {\n\t\tfrequencies.push(new FrequencySet<String>());\n\t\tminFrequencies.push(new FrequencySet<String>());\n\t}\n\n\t@Override\n\tprotected void exitLexerElement(GrammarAST tree) {\n\t\tfrequencies.push(combineAndClip(frequencies.pop(), frequencies.pop(), 2));\n\t\tminFrequencies.push(combineAndClip(minFrequencies.pop(), minFrequencies.pop(), 2));\n\t}\n\n\t@Override\n\tprotected void exitLexerSubrule(GrammarAST tree) {\n\t\tif (tree.getType() == CLOSURE || tree.getType() == POSITIVE_CLOSURE) {\n\t\t\tfor (Map.Entry<String, MutableInt> entry : frequencies.peek().entrySet()) {\n\t\t\t\tentry.getValue().v = 2;\n\t\t\t}\n\t\t}\n\n\t\tif (tree.getType() == CLOSURE) {\n\t\t\t// Everything inside a closure is optional, so the minimum\n\t\t\t// number of occurrences for all elements is 0.\n\t\t\tminFrequencies.peek().clear();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ExceptionClause.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.ActionAST;\n\npublic class ExceptionClause extends SrcOp {\n\t@ModelElement public Action catchArg;\n\t@ModelElement public Action catchAction;\n\n\tpublic ExceptionClause(OutputModelFactory factory,\n\t\t\t\t\t\t   ActionAST catchArg,\n\t\t\t\t\t\t   ActionAST catchAction)\n\t{\n\t\tsuper(factory, catchArg);\n\t\tthis.catchArg = new Action(factory, catchArg);\n\t\tthis.catchAction = new Action(factory, catchAction);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/InvokeRule.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.ActionTranslator;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.ParserFactory;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.codegen.model.chunk.ActionChunk;\nimport org.antlr.v4.codegen.model.decl.Decl;\nimport org.antlr.v4.codegen.model.decl.RuleContextDecl;\nimport org.antlr.v4.codegen.model.decl.RuleContextListDecl;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.misc.OrderedHashSet;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** */\npublic class InvokeRule extends RuleElement implements LabeledOp {\n\tpublic final String name;\n\tpublic final String escapedName;\n\tpublic final OrderedHashSet<Decl> labels = new OrderedHashSet<Decl>(); // TODO: should need just 1\n\tpublic final String ctxName;\n\n\t@ModelElement public List<ActionChunk> argExprsChunks;\n\n\tpublic InvokeRule(ParserFactory factory, GrammarAST ast, GrammarAST labelAST) {\n\t\tsuper(factory, ast);\n\t\tif ( ast.atnState!=null ) {\n\t\t\tstateNumber = ast.atnState.stateNumber;\n\t\t}\n\n\t\tCodeGenerator gen = factory.getGenerator();\n\t\tTarget target = gen.getTarget();\n\t\tString identifier = ast.getText();\n\t\tRule r = factory.getGrammar().getRule(identifier);\n\t\tthis.name = r.name;\n\t\tthis.escapedName = gen.getTarget().escapeIfNeeded(name);\n\t\tctxName = target.getRuleFunctionContextStructName(r);\n\n\t\t// TODO: move to factory\n\t\tRuleFunction rf = factory.getCurrentRuleFunction();\n\t\tif ( labelAST!=null ) {\n\t\t\tRuleContextDecl decl;\n\t\t\t// for x=r, define <rule-context-type> x and list_x\n\t\t\tString label = labelAST.getText();\n\t\t\tif ( labelAST.parent.getType() == ANTLRParser.PLUS_ASSIGN  ) {\n\t\t\t\tfactory.defineImplicitLabel(ast, this);\n\t\t\t\tString listLabel = gen.getTarget().getListLabel(label);\n\t\t\t\tdecl = new RuleContextListDecl(factory, listLabel, ctxName);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdecl = new RuleContextDecl(factory,label,ctxName);\n\t\t\t\tlabels.add(decl);\n\t\t\t}\n\t\t\trf.addContextDecl(ast.getAltLabel(), decl);\n\t\t}\n\n\t\tActionAST arg = (ActionAST)ast.getFirstChildWithType(ANTLRParser.ARG_ACTION);\n\t\tif ( arg != null ) {\n\t\t\targExprsChunks = ActionTranslator.translateAction(factory, rf, arg.token, arg);\n\t\t}\n\n\t\t// If action refs rule as rulename not label, we need to define implicit label\n\t\tif ( factory.getCurrentOuterMostAlt().ruleRefsInActions.containsKey(identifier) ) {\n\t\t\tString label = gen.getTarget().getImplicitRuleLabel(identifier);\n\t\t\tRuleContextDecl d = new RuleContextDecl(factory,label,ctxName);\n\t\t\tlabels.add(d);\n\t\t\trf.addContextDecl(ast.getAltLabel(), d);\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<Decl> getLabels() {\n\t\treturn labels.elements();\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LL1AltBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** (A | B | C) */\npublic class LL1AltBlock extends LL1Choice {\n\tpublic LL1AltBlock(OutputModelFactory factory, GrammarAST blkAST, List<CodeBlockForAlt> alts) {\n\t\tsuper(factory, blkAST, alts);\n\t\tthis.decision = ((DecisionState)blkAST.atnState).decision;\n\n\t\t/** Lookahead for each alt 1..n */\n\t\tIntervalSet[] altLookSets = factory.getGrammar().decisionLOOK.get(decision);\n\t\taltLook = getAltLookaheadAsStringLists(altLookSets);\n\n\t\tIntervalSet expecting = IntervalSet.or(altLookSets); // combine alt sets\n\t\tthis.error = getThrowNoViableAlt(factory, blkAST, expecting);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LL1Choice.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\npublic abstract class LL1Choice extends Choice {\n\t/** Token names for each alt 0..n-1 */\n\tpublic List<TokenInfo[]> altLook;\n\t@ModelElement public ThrowNoViableAlt error;\n\n\tpublic LL1Choice(OutputModelFactory factory, GrammarAST blkAST,\n\t\t\t\t\t List<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, blkAST, alts);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LL1Loop.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** */\npublic abstract class LL1Loop extends Choice {\n\t/** The state associated wih the (A|B|...) block not loopback, which\n\t *  is super.stateNumber\n\t */\n\tpublic int blockStartStateNumber;\n\tpublic int loopBackStateNumber;\n\n\t@ModelElement public OutputModelObject loopExpr;\n\t@ModelElement public List<SrcOp> iteration;\n\n\tpublic LL1Loop(OutputModelFactory factory,\n\t\t\t\t   GrammarAST blkAST,\n\t\t\t\t   List<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, blkAST, alts);\n\t}\n\n\tpublic void addIterationOp(SrcOp op) {\n\t\tif ( iteration==null ) iteration = new ArrayList<SrcOp>();\n\t\titeration.add(op);\n\t}\n\n\tpublic SrcOp addCodeForLoopLookaheadTempVar(IntervalSet look) {\n\t\tTestSetInline expr = addCodeForLookaheadTempVar(look);\n\t\tif (expr != null) {\n\t\t\tCaptureNextTokenType nextType = new CaptureNextTokenType(factory, expr.varName);\n\t\t\taddIterationOp(nextType);\n\t\t}\n\t\treturn expr;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LL1OptionalBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** An optional block is just an alternative block where the last alternative\n *  is epsilon. The analysis takes care of adding to the empty alternative.\n *\n *  (A | B | C)?\n */\npublic class LL1OptionalBlock extends LL1AltBlock {\n\tpublic LL1OptionalBlock(OutputModelFactory factory, GrammarAST blkAST, List<CodeBlockForAlt> alts) {\n\t\tsuper(factory, blkAST, alts);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LL1OptionalBlockSingleAlt.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** (A B C)? */\npublic class LL1OptionalBlockSingleAlt extends LL1Choice {\n\t@ModelElement public SrcOp expr;\n\t@ModelElement public List<SrcOp> followExpr; // might not work in template if size>1\n\n\tpublic LL1OptionalBlockSingleAlt(OutputModelFactory factory,\n\t\t\t\t\t\t\t\t\t GrammarAST blkAST,\n\t\t\t\t\t\t\t\t\t List<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, blkAST, alts);\n\t\tthis.decision = ((DecisionState)blkAST.atnState).decision;\n\n\t\t/** Lookahead for each alt 1..n */\n//\t\tIntervalSet[] altLookSets = LinearApproximator.getLL1LookaheadSets(dfa);\n\t\tIntervalSet[] altLookSets = factory.getGrammar().decisionLOOK.get(decision);\n\t\taltLook = getAltLookaheadAsStringLists(altLookSets);\n\t\tIntervalSet look = altLookSets[0];\n\t\tIntervalSet followLook = altLookSets[1];\n\n\t\tIntervalSet expecting = look.or(followLook);\n\t\tthis.error = getThrowNoViableAlt(factory, blkAST, expecting);\n\n\t\texpr = addCodeForLookaheadTempVar(look);\n\t\tfollowExpr = factory.getLL1Test(followLook, blkAST);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LL1PlusBlockSingleAlt.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.atn.PlusBlockStartState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** */\npublic class LL1PlusBlockSingleAlt extends LL1Loop {\n\tpublic LL1PlusBlockSingleAlt(OutputModelFactory factory, GrammarAST plusRoot, List<CodeBlockForAlt> alts) {\n\t\tsuper(factory, plusRoot, alts);\n\n\t\tBlockAST blkAST = (BlockAST)plusRoot.getChild(0);\n\t\tPlusBlockStartState blkStart = (PlusBlockStartState)blkAST.atnState;\n\n\t\tstateNumber = blkStart.loopBackState.stateNumber;\n\t\tblockStartStateNumber = blkStart.stateNumber;\n\t\tPlusBlockStartState plus = (PlusBlockStartState)blkAST.atnState;\n\t\tthis.decision = plus.loopBackState.decision;\n\t\tIntervalSet[] altLookSets = factory.getGrammar().decisionLOOK.get(decision);\n\n\t\tIntervalSet loopBackLook = altLookSets[0];\n\t\tloopExpr = addCodeForLoopLookaheadTempVar(loopBackLook);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LL1StarBlockSingleAlt.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** */\npublic class LL1StarBlockSingleAlt extends LL1Loop {\n\tpublic LL1StarBlockSingleAlt(OutputModelFactory factory, GrammarAST starRoot, List<CodeBlockForAlt> alts) {\n\t\tsuper(factory, starRoot, alts);\n\n\t\tStarLoopEntryState star = (StarLoopEntryState)starRoot.atnState;\n\t\tloopBackStateNumber = star.loopBackState.stateNumber;\n\t\tthis.decision = star.decision;\n\t\tIntervalSet[] altLookSets = factory.getGrammar().decisionLOOK.get(decision);\n\t\tassert altLookSets.length == 2;\n\t\tIntervalSet enterLook = altLookSets[0];\n\t\tIntervalSet exitLook = altLookSets[1];\n\t\tloopExpr = addCodeForLoopLookaheadTempVar(enterLook);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LabeledOp.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.model.decl.Decl;\n\nimport java.util.List;\n\n/** All the rule elements we can label like tokens, rules, sets, wildcard. */\npublic interface LabeledOp {\n\tpublic List<Decl> getLabels();\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LeftRecursiveRuleFunction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.decl.RuleContextDecl;\nimport org.antlr.v4.codegen.model.decl.RuleContextListDecl;\nimport org.antlr.v4.codegen.model.decl.StructDecl;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.LeftRecursiveRule;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\npublic class LeftRecursiveRuleFunction extends RuleFunction {\n\tpublic LeftRecursiveRuleFunction(OutputModelFactory factory, LeftRecursiveRule r) {\n\t\tsuper(factory, r);\n\n\t\tCodeGenerator gen = factory.getGenerator();\n\t\t// Since we delete x=lr, we have to manually add decls for all labels\n\t\t// on left-recur refs to proper structs\n\t\tfor (Pair<GrammarAST,String> pair : r.leftRecursiveRuleRefLabels) {\n\t\t\tGrammarAST idAST = pair.a;\n\t\t\tString altLabel = pair.b;\n\t\t\tString label = idAST.getText();\n\t\t\tGrammarAST rrefAST = (GrammarAST)idAST.getParent().getChild(1);\n\t\t\tif ( rrefAST.getType() == ANTLRParser.RULE_REF ) {\n\t\t\t\tRule targetRule = factory.getGrammar().getRule(rrefAST.getText());\n\t\t\t\tString ctxName = gen.getTarget().getRuleFunctionContextStructName(targetRule);\n\t\t\t\tRuleContextDecl d;\n\t\t\t\tif (idAST.getParent().getType() == ANTLRParser.ASSIGN) {\n\t\t\t\t\td = new RuleContextDecl(factory, label, ctxName);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\td = new RuleContextListDecl(factory, label, ctxName);\n\t\t\t\t}\n\n\t\t\t\tStructDecl struct = ruleCtx;\n\t\t\t\tif ( altLabelCtxs!=null ) {\n\t\t\t\t\tStructDecl s = altLabelCtxs.get(altLabel);\n\t\t\t\t\tif ( s!=null ) struct = s; // if alt label, use subctx\n\t\t\t\t}\n\t\t\t\tstruct.addDecl(d); // stick in overall rule's ctx\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Lexer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\n\nimport java.util.*;\n\npublic class Lexer extends Recognizer {\n\tpublic final Collection<String> channelNames;\n\tpublic final Map<String, Integer> escapedChannels;\n\tpublic final LexerFile file;\n\tpublic final Collection<String> modes;\n\tpublic final Collection<String> escapedModeNames;\n\n\t@ModelElement public LinkedHashMap<Rule, RuleActionFunction> actionFuncs =\n\t\tnew LinkedHashMap<Rule, RuleActionFunction>();\n\n\tpublic Lexer(OutputModelFactory factory, LexerFile file) {\n\t\tsuper(factory);\n\t\tthis.file = file; // who contains us?\n\n\t\tGrammar g = factory.getGrammar();\n\t\tTarget target = factory.getGenerator().getTarget();\n\n\t\tescapedChannels = new LinkedHashMap<>();\n\t\tchannelNames = new ArrayList<>();\n\t\tfor (String key : g.channelNameToValueMap.keySet()) {\n\t\t\tInteger value = g.channelNameToValueMap.get(key);\n\t\t\tescapedChannels.put(target.escapeIfNeeded(key), value);\n\t\t\tchannelNames.add(key);\n\t\t}\n\n\t\tmodes = ((LexerGrammar)g).modes.keySet();\n\t\tescapedModeNames = new ArrayList<>(modes.size());\n\t\tfor (String mode : modes) {\n\t\t\tescapedModeNames.add(target.escapeIfNeeded(mode));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/LexerFile.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\nimport java.util.Map;\n\npublic class LexerFile extends OutputFile {\n\tpublic String genPackage; // from -package cmd-line\n\tpublic String exportMacro; // from -DexportMacro cmd-line\n\tpublic boolean genListener; // from -listener cmd-line\n\tpublic boolean genVisitor; // from -visitor cmd-line\n\t@ModelElement public Lexer lexer;\n\t@ModelElement public Map<String, Action> namedActions;\n\n\tpublic LexerFile(OutputModelFactory factory, String fileName) {\n\t\tsuper(factory, fileName);\n\t\tnamedActions = buildNamedActions(factory.getGrammar());\n\t\tgenPackage = factory.getGrammar().tool.genPackage;\n\t\texportMacro = factory.getGrammar().getOptionString(\"exportMacro\");\n\t\tgenListener = factory.getGrammar().tool.gen_listener;\n\t\tgenVisitor = factory.getGrammar().tool.gen_visitor;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ListenerDispatchMethod.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class ListenerDispatchMethod extends DispatchMethod {\n\tpublic boolean isEnter;\n\n\tpublic ListenerDispatchMethod(OutputModelFactory factory, boolean isEnter) {\n\t\tsuper(factory);\n\t\tthis.isEnter = isEnter;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ListenerFile.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\n\nimport java.util.*;\n\n/** A model object representing a parse tree listener file.\n *  These are the rules specific events triggered by a parse tree visitor.\n */\npublic class ListenerFile extends OutputFile {\n\tpublic String genPackage; // from -package cmd-line\n\tpublic boolean genLean; // from -split-parser cmd-line\n\tpublic String accessLevel; // from -DaccessLevel cmd-line\n\tpublic String exportMacro; // from -DexportMacro cmd-line\n\tpublic String grammarName;\n\tpublic String parserName;\n\t/**\n\t * The names of all listener contexts.\n\t */\n\tpublic Set<String> listenerNames = new LinkedHashSet<String>();\n\t/**\n\t * For listener contexts created for a labeled outer alternative, maps from\n\t * a listener context name to the name of the rule which defines the\n\t * context.\n\t */\n\tpublic Map<String, String> listenerLabelRuleNames = new LinkedHashMap<String, String>();\n\n\t@ModelElement public Action header;\n\t@ModelElement public Map<String, Action> namedActions;\n\n\tpublic ListenerFile(OutputModelFactory factory, String fileName) {\n\t\tsuper(factory, fileName);\n\t\tGrammar g = factory.getGrammar();\n\t\tparserName = g.getRecognizerName();\n\t\tgrammarName = g.name;\n\t\tnamedActions = buildNamedActions(factory.getGrammar(), ast -> ast.getScope() == null);\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tMap<String, List<Pair<Integer,AltAST>>> labels = r.getAltLabels();\n\t\t\tif ( labels!=null ) {\n\t\t\t\tfor (Map.Entry<String, List<Pair<Integer, AltAST>>> pair : labels.entrySet()) {\n\t\t\t\t\tlistenerNames.add(pair.getKey());\n\t\t\t\t\tlistenerLabelRuleNames.put(pair.getKey(), r.name);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// only add rule context if no labels\n\t\t\t\tlistenerNames.add(r.name);\n\t\t\t}\n\t\t}\n\t\tActionAST ast = g.namedActions.get(\"header\");\n\t\tif ( ast!=null && ast.getScope()==null ) {\n\t\t\theader = new Action(factory, ast);\n\t\t}\n\t\tgenPackage = g.tool.genPackage;\n\t\tgenLean = g.tool.gen_split_parser;\n\t\taccessLevel = g.getOptionString(\"accessLevel\");\n\t\texportMacro = g.getOptionString(\"exportMacro\");\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Loop.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.QuantifierAST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Loop extends Choice {\n\tpublic int blockStartStateNumber;\n\tpublic int loopBackStateNumber;\n\tpublic final int exitAlt;\n\n\t@ModelElement public List<SrcOp> iteration;\n\n\tpublic Loop(OutputModelFactory factory,\n\t\t\t\tGrammarAST blkOrEbnfRootAST,\n\t\t\t\tList<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, blkOrEbnfRootAST, alts);\n\t\tboolean nongreedy = (blkOrEbnfRootAST instanceof QuantifierAST) && !((QuantifierAST)blkOrEbnfRootAST).isGreedy();\n\t\texitAlt = nongreedy ? 1 : alts.size() + 1;\n\t}\n\n\tpublic void addIterationOp(SrcOp op) {\n\t\tif ( iteration==null ) iteration = new ArrayList<SrcOp>();\n\t\titeration.add(op);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/MatchNotSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\npublic class MatchNotSet extends MatchSet {\n\tpublic String varName = \"_la\";\n\tpublic MatchNotSet(OutputModelFactory factory, GrammarAST ast) {\n\t\tsuper(factory, ast);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/MatchSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.decl.Decl;\nimport org.antlr.v4.codegen.model.decl.TokenTypeDecl;\nimport org.antlr.v4.runtime.atn.SetTransition;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\npublic class MatchSet extends MatchToken {\n\t@ModelElement public TestSetInline expr;\n\t@ModelElement public CaptureNextTokenType capture;\n\n\tpublic MatchSet(OutputModelFactory factory, GrammarAST ast) {\n\t\tsuper(factory, ast);\n\t\tSetTransition st = (SetTransition)ast.atnState.transition(0);\n\t\tint wordSize = factory.getGenerator().getTarget().getInlineTestSetWordSize();\n\t\texpr = new TestSetInline(factory, null, st.set, wordSize);\n\t\tDecl d = new TokenTypeDecl(factory, expr.varName);\n\t\tfactory.getCurrentRuleFunction().addLocalDecl(d);\n\t\tcapture = new CaptureNextTokenType(factory,expr.varName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/MatchToken.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.codegen.model.decl.Decl;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** */\npublic class MatchToken extends RuleElement implements LabeledOp {\n\tpublic final String name;\n\tpublic final String escapedName;\n\tpublic final int ttype;\n\tpublic final List<Decl> labels = new ArrayList<Decl>();\n\n\tpublic MatchToken(OutputModelFactory factory, TerminalAST ast) {\n\t\tsuper(factory, ast);\n\t\tGrammar g = factory.getGrammar();\n\t\tCodeGenerator gen = factory.getGenerator();\n\t\tttype = g.getTokenType(ast.getText());\n\t\tTarget target = gen.getTarget();\n\t\tname = target.getTokenTypeAsTargetLabel(g, ttype);\n\t\tescapedName = target.escapeIfNeeded(name);\n\t}\n\n\tpublic MatchToken(OutputModelFactory factory, GrammarAST ast) {\n\t\tsuper(factory, ast);\n\t\tttype = 0;\n\t\tname = null;\n\t\tescapedName = null;\n\t}\n\n\t@Override\n\tpublic List<Decl> getLabels() { return labels; }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ModelElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n/** Indicate field of OutputModelObject is an element to be walked by\n *  OutputModelWalker.\n */\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface ModelElement {\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/OptionalBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** */\npublic class OptionalBlock extends AltBlock {\n\tpublic OptionalBlock(OutputModelFactory factory,\n\t\t\t\t\t\t GrammarAST questionAST,\n\t\t\t\t\t\t List<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, questionAST, alts);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/OutputFile.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.ast.ActionAST;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.function.Predicate;\n\npublic abstract class OutputFile extends OutputModelObject {\n\tpublic final String fileName;\n\tpublic final String grammarFileName;\n\tpublic final String ANTLRVersion;\n    public final String TokenLabelType;\n    public final String InputSymbolType;\n\n    public OutputFile(OutputModelFactory factory, String fileName) {\n        super(factory);\n        this.fileName = fileName;\n        Grammar g = factory.getGrammar();\n\t\tgrammarFileName = g.fileName.replace(\"\\\\\", \"/\"); // Prevent a path with windows delim and u breaking Java pre-parser on comments\n\t\tANTLRVersion = Tool.VERSION;\n        TokenLabelType = g.getOptionString(\"TokenLabelType\");\n        InputSymbolType = TokenLabelType;\n    }\n\n\tpublic Map<String, Action> buildNamedActions(Grammar g) {\n\t\treturn buildNamedActions(g, null);\n\t}\n\n\tpublic Map<String, Action> buildNamedActions(Grammar g, Predicate<ActionAST> filter) {\n\t\tMap<String, Action> namedActions = new HashMap<String, Action>();\n\t\tfor (String name : g.namedActions.keySet()) {\n\t\t\tActionAST ast = g.namedActions.get(name);\n\t\t\tif(filter==null || filter.test(ast))\n\t\t\t\tnamedActions.put(name, new Action(factory, ast));\n\t\t}\n\t\treturn namedActions;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/OutputModelObject.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\n/** */\npublic abstract class OutputModelObject {\n\tpublic OutputModelFactory factory;\n\tpublic GrammarAST ast;\n\n\tpublic OutputModelObject() {}\n\n\tpublic OutputModelObject(OutputModelFactory factory) { this(factory, null); }\n\n\tpublic OutputModelObject(OutputModelFactory factory, GrammarAST ast) {\n\t\tthis.factory = factory;\n\t\tthis.ast = ast;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Parser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Parser extends Recognizer {\n\tpublic ParserFile file;\n\n\t@ModelElement public List<RuleFunction> funcs = new ArrayList<RuleFunction>();\n\n\tpublic Parser(OutputModelFactory factory, ParserFile file) {\n\t\tsuper(factory);\n\t\tthis.file = file; // who contains us?\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ParserFile.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.chunk.ActionChunk;\nimport org.antlr.v4.codegen.model.chunk.ActionText;\nimport org.antlr.v4.tool.Grammar;\n\nimport java.util.Map;\n\n/** */\npublic class ParserFile extends OutputFile {\n\tpublic String genPackage; // from -package cmd-line\n\tpublic String exportMacro; // from -DexportMacro cmd-line\n\tpublic boolean genListener; // from -listener cmd-line\n\tpublic boolean genVisitor; // from -visitor cmd-line\n\tpublic boolean genLean; // from -split-parser cmd-line\n\tpublic boolean genContexts; // from -split-parser cmd-line\n\tpublic boolean genDFA; // from -split-parser cmd-line\n\t@ModelElement public Parser parser;\n\t@ModelElement public Map<String, Action> namedActions;\n\t@ModelElement public ActionChunk contextSuperClass;\n\tpublic String grammarName;\n\n\tpublic ParserFile(OutputModelFactory factory, String fileName) {\n\t\tsuper(factory, fileName);\n\t\tGrammar g = factory.getGrammar();\n\t\tnamedActions = buildNamedActions(factory.getGrammar());\n\t\tgenPackage = g.tool.genPackage;\n\t\texportMacro = factory.getGrammar().getOptionString(\"exportMacro\");\n\t\t// need the below members in the ST for Python, C++\n\t\tgenListener = g.tool.gen_listener;\n\t\tgenVisitor = g.tool.gen_visitor;\n\t\tgrammarName = g.name;\n\n\t\tif (g.getOptionString(\"contextSuperClass\") != null) {\n\t\t\tcontextSuperClass = new ActionText(null, g.getOptionString(\"contextSuperClass\"));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/PlusBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.atn.PlusBlockStartState;\nimport org.antlr.v4.runtime.atn.PlusLoopbackState;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\npublic class PlusBlock extends Loop {\n\t@ModelElement public ThrowNoViableAlt error;\n\n\tpublic PlusBlock(OutputModelFactory factory,\n\t\t\t\t\t GrammarAST plusRoot,\n\t\t\t\t\t List<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, plusRoot, alts);\n\t\tBlockAST blkAST = (BlockAST)plusRoot.getChild(0);\n\t\tPlusBlockStartState blkStart = (PlusBlockStartState)blkAST.atnState;\n\t\tPlusLoopbackState loop = blkStart.loopBackState;\n\t\tstateNumber = blkStart.loopBackState.stateNumber;\n\t\tblockStartStateNumber = blkStart.stateNumber;\n\t\tloopBackStateNumber = loop.stateNumber;\n\t\tthis.error = getThrowNoViableAlt(factory, plusRoot, null);\n\t\tdecision = loop.decision;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Recognizer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.chunk.ActionChunk;\nimport org.antlr.v4.codegen.model.chunk.ActionText;\nimport org.antlr.v4.codegen.target.JavaTarget;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\n\nimport java.io.File;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic abstract class Recognizer extends OutputModelObject {\n\tpublic String name;\n\tpublic String grammarName;\n\tpublic String grammarFileName;\n\tpublic String accessLevel;\n\tpublic Map<String,Integer> tokens;\n\n\t/**\n\t * @deprecated This field is provided only for compatibility with code\n\t * generation targets which have not yet been updated to use\n\t * {@link #literalNames} and {@link #symbolicNames}.\n\t */\n\t@Deprecated\n\tpublic List<String> tokenNames;\n\n\tpublic List<String> literalNames;\n\tpublic List<String> symbolicNames;\n\tpublic Set<String> ruleNames;\n\tpublic Collection<Rule> rules;\n\t@ModelElement public ActionChunk superClass;\n\n\t@ModelElement public SerializedATN atn;\n\t@ModelElement public LinkedHashMap<Rule, RuleSempredFunction> sempredFuncs =\n\t\tnew LinkedHashMap<Rule, RuleSempredFunction>();\n\n\tpublic Recognizer(OutputModelFactory factory) {\n\t\tsuper(factory);\n\n\t\tGrammar g = factory.getGrammar();\n\t\tCodeGenerator gen = factory.getGenerator();\n\t\tgrammarFileName = new File(g.fileName).getName();\n\t\tgrammarName = g.name;\n\t\tname = g.getRecognizerName();\n\t\taccessLevel = g.getOptionString(\"accessLevel\");\n\t\ttokens = new LinkedHashMap<String,Integer>();\n\t\tfor (Map.Entry<String, Integer> entry : g.tokenNameToTypeMap.entrySet()) {\n\t\t\tInteger ttype = entry.getValue();\n\t\t\tif ( ttype>0 ) {\n\t\t\t    tokens.put(gen.getTarget().escapeIfNeeded(entry.getKey()), ttype);\n\t\t\t}\n\t\t}\n\n\t\truleNames = g.rules.keySet();\n\t\trules = g.rules.values();\n\t\tif ( gen.getTarget() instanceof JavaTarget ) {\n\t\t\tatn = new SerializedJavaATN(factory, g.atn);\n\t\t}\n\t\telse {\n\t\t\tatn = new SerializedATN(factory, g.atn);\n\t\t}\n\t\tif (g.getOptionString(\"superClass\") != null) {\n\t\t\tsuperClass = new ActionText(null, g.getOptionString(\"superClass\"));\n\t\t}\n\t\telse {\n\t\t\tsuperClass = null;\n\t\t}\n\n\t\ttokenNames = translateTokenStringsToTarget(g.getTokenDisplayNames(), gen);\n\t\tliteralNames = translateTokenStringsToTarget(g.getTokenLiteralNames(), gen);\n\t\tsymbolicNames = translateTokenStringsToTarget(g.getTokenSymbolicNames(), gen);\n\t}\n\n\tprotected static List<String> translateTokenStringsToTarget(String[] tokenStrings, CodeGenerator gen) {\n\t\tString[] result = tokenStrings.clone();\n\t\tfor (int i = 0; i < tokenStrings.length; i++) {\n\t\t\tresult[i] = translateTokenStringToTarget(tokenStrings[i], gen);\n\t\t}\n\n\t\tint lastTrueEntry = result.length - 1;\n\t\twhile (lastTrueEntry >= 0 && result[lastTrueEntry] == null) {\n\t\t\tlastTrueEntry --;\n\t\t}\n\n\t\tif (lastTrueEntry < result.length - 1) {\n\t\t\tresult = Arrays.copyOf(result, lastTrueEntry + 1);\n\t\t}\n\n\t\treturn Arrays.asList(result);\n\t}\n\n\tprotected static String translateTokenStringToTarget(String tokenName, CodeGenerator gen) {\n\t\tif (tokenName == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (tokenName.charAt(0) == '\\'') {\n\t\t\tString targetString =\n\t\t\t\tgen.getTarget().getTargetStringLiteralFromANTLRStringLiteral(gen, tokenName, false, true);\n\t\t\treturn \"\\\"'\" + targetString + \"'\\\"\";\n\t\t}\n\t\telse {\n\t\t\treturn gen.getTarget().getTargetStringLiteralFromString(tokenName, true);\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/RuleActionFunction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.Rule;\n\nimport java.util.LinkedHashMap;\n\npublic class RuleActionFunction extends OutputModelObject {\n\tpublic final String name;\n\tpublic final String escapedName;\n\tpublic final String ctxType;\n\tpublic final int ruleIndex;\n\n\t/** Map actionIndex to Action */\n\t@ModelElement public LinkedHashMap<Integer, Action> actions =\n\t\tnew LinkedHashMap<Integer, Action>();\n\n\tpublic RuleActionFunction(OutputModelFactory factory, Rule r, String ctxType) {\n\t\tsuper(factory);\n\t\tname = r.name;\n\t\tescapedName = factory.getGenerator().getTarget().escapeIfNeeded(name);\n\t\truleIndex = r.index;\n\t\tthis.ctxType = ctxType;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/RuleElement.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\npublic class RuleElement extends SrcOp {\n\t/** Associated ATN state for this rule elements (action, token, ruleref, ...) */\n\tpublic int stateNumber;\n\n\tpublic RuleElement(OutputModelFactory factory, GrammarAST ast) {\n\t\tsuper(factory, ast);\n\t\tif ( ast != null && ast.atnState!=null ) stateNumber = ast.atnState.stateNumber;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/RuleFunction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.runtime.tree.CommonTree;\nimport org.antlr.runtime.tree.CommonTreeNodeStream;\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.decl.AltLabelStructDecl;\nimport org.antlr.v4.codegen.model.decl.AttributeDecl;\nimport org.antlr.v4.codegen.model.decl.ContextRuleGetterDecl;\nimport org.antlr.v4.codegen.model.decl.ContextRuleListGetterDecl;\nimport org.antlr.v4.codegen.model.decl.ContextRuleListIndexedGetterDecl;\nimport org.antlr.v4.codegen.model.decl.ContextTokenGetterDecl;\nimport org.antlr.v4.codegen.model.decl.ContextTokenListGetterDecl;\nimport org.antlr.v4.codegen.model.decl.ContextTokenListIndexedGetterDecl;\nimport org.antlr.v4.codegen.model.decl.Decl;\nimport org.antlr.v4.codegen.model.decl.StructDecl;\nimport org.antlr.v4.misc.FrequencySet;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.runtime.misc.OrderedHashSet;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.Attribute;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.PredAST;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport static org.antlr.v4.parse.ANTLRParser.RULE_REF;\nimport static org.antlr.v4.parse.ANTLRParser.STRING_LITERAL;\nimport static org.antlr.v4.parse.ANTLRParser.TOKEN_REF;\n\n/** */\npublic class RuleFunction extends OutputModelObject {\n\tpublic final String name;\n\tpublic final String escapedName;\n\tpublic final List<String> modifiers;\n\tpublic String ctxType;\n\tpublic final Collection<String> ruleLabels;\n\tpublic final Collection<String> tokenLabels;\n\tpublic final ATNState startState;\n\tpublic final int index;\n\tpublic final Rule rule;\n\tpublic final AltLabelStructDecl[] altToContext;\n\tpublic boolean hasLookaheadBlock;\n\n\t@ModelElement public List<SrcOp> code;\n\t@ModelElement public OrderedHashSet<Decl> locals; // TODO: move into ctx?\n\t@ModelElement public Collection<AttributeDecl> args = null;\n\t@ModelElement public StructDecl ruleCtx;\n\t@ModelElement public Map<String,AltLabelStructDecl> altLabelCtxs;\n\t@ModelElement public Map<String,Action> namedActions;\n\t@ModelElement public Action finallyAction;\n\t@ModelElement public List<ExceptionClause> exceptions;\n\t@ModelElement public List<SrcOp> postamble;\n\n\tpublic RuleFunction(OutputModelFactory factory, Rule r) {\n\t\tsuper(factory);\n\t\tthis.name = r.name;\n\t\tthis.escapedName = factory.getGenerator().getTarget().escapeIfNeeded(r.name);\n\t\tthis.rule = r;\n\t\tmodifiers = Utils.nodesToStrings(r.modifiers);\n\n\t\tindex = r.index;\n\n\t\truleCtx = new StructDecl(factory, r);\n\t\taltToContext = new AltLabelStructDecl[r.getOriginalNumberOfAlts()+1];\n\t\taddContextGetters(factory, r);\n\n\t\tif ( r.args!=null ) {\n\t\t\tCollection<Attribute> decls = r.args.attributes.values();\n\t\t\tif ( decls.size()>0 ) {\n\t\t\t\targs = new ArrayList<AttributeDecl>();\n\t\t\t\truleCtx.addDecls(decls);\n\t\t\t\tfor (Attribute a : decls) {\n\t\t\t\t\targs.add(new AttributeDecl(factory, a));\n\t\t\t\t}\n\t\t\t\truleCtx.ctorAttrs = args;\n\t\t\t}\n\t\t}\n\t\tif ( r.retvals!=null ) {\n\t\t\truleCtx.addDecls(r.retvals.attributes.values());\n\t\t}\n\t\tif ( r.locals!=null ) {\n\t\t\truleCtx.addDecls(r.locals.attributes.values());\n\t\t}\n\n\t\truleLabels = r.getElementLabelNames();\n\t\ttokenLabels = r.getTokenRefs();\n\t\tif ( r.exceptions!=null ) {\n\t\t\texceptions = new ArrayList<ExceptionClause>();\n\t\t\tfor (GrammarAST e : r.exceptions) {\n\t\t\t\tActionAST catchArg = (ActionAST)e.getChild(0);\n\t\t\t\tActionAST catchAction = (ActionAST)e.getChild(1);\n\t\t\t\texceptions.add(new ExceptionClause(factory, catchArg, catchAction));\n\t\t\t}\n\t\t}\n\n\t\tstartState = factory.getGrammar().atn.ruleToStartState[r.index];\n\t}\n\n\tpublic void addContextGetters(OutputModelFactory factory, Rule r) {\n\t\t// Add ctx labels for elements in alts with no -> label\n\t\tList<AltAST> altsNoLabels = r.getUnlabeledAltASTs();\n\t\tif ( altsNoLabels!=null ) {\n\t\t\tSet<Decl> decls = getDeclsForAllElements(altsNoLabels);\n\t\t\t// we know to put in rule ctx, so do it directly\n\t\t\tfor (Decl d : decls) ruleCtx.addDecl(d);\n\t\t}\n\n\t\t// make structs for -> labeled alts, define ctx labels for elements\n\t\taltLabelCtxs = new HashMap<String,AltLabelStructDecl>();\n\t\tMap<String, List<Pair<Integer, AltAST>>> labels = r.getAltLabels();\n\t\tif ( labels!=null ) {\n\t\t\tfor (Map.Entry<String, List<Pair<Integer, AltAST>>> entry : labels.entrySet()) {\n\t\t\t\tString label = entry.getKey();\n\t\t\t\tList<AltAST> alts = new ArrayList<AltAST>();\n\t\t\t\tfor (Pair<Integer, AltAST> pair : entry.getValue()) {\n\t\t\t\t\talts.add(pair.b);\n\t\t\t\t}\n\n\t\t\t\tSet<Decl> decls = getDeclsForAllElements(alts);\n\t\t\t\tfor (Pair<Integer, AltAST> pair : entry.getValue()) {\n\t\t\t\t\tInteger altNum = pair.a;\n\t\t\t\t\taltToContext[altNum] = new AltLabelStructDecl(factory, r, altNum, label);\n\t\t\t\t\tif (!altLabelCtxs.containsKey(label)) {\n\t\t\t\t\t\taltLabelCtxs.put(label, altToContext[altNum]);\n\t\t\t\t\t}\n\n\t\t\t\t\t// we know which ctx to put in, so do it directly\n\t\t\t\t\tfor (Decl d : decls) {\n\t\t\t\t\t\taltToContext[altNum].addDecl(d);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void fillNamedActions(OutputModelFactory factory, Rule r) {\n\t\tif ( r.finallyAction!=null ) {\n\t\t\tfinallyAction = new Action(factory, r.finallyAction);\n\t\t}\n\n\t\tnamedActions = new HashMap<String, Action>();\n\t\tfor (String name : r.namedActions.keySet()) {\n\t\t\tActionAST ast = r.namedActions.get(name);\n\t\t\tnamedActions.put(name, new Action(factory, ast));\n\t\t}\n\t}\n\n\t/** for all alts, find which ref X or r needs List\n\t   Must see across alts. If any alt needs X or r as list, then\n\t   define as list.\n\t */\n\tpublic Set<Decl> getDeclsForAllElements(List<AltAST> altASTs) {\n\t\tSet<String> needsList = new HashSet<String>();\n\t\tSet<String> nonOptional = new HashSet<String>();\n\t\tList<GrammarAST> allRefs = new ArrayList<GrammarAST>();\n\t\tboolean firstAlt = true;\n\t\tIntervalSet reftypes = new IntervalSet(RULE_REF, TOKEN_REF, STRING_LITERAL);\n\t\tfor (AltAST ast : altASTs) {\n\t\t\tList<GrammarAST> refs = getRuleTokens(ast.getNodesWithType(reftypes));\n\t\t\tallRefs.addAll(refs);\n\t\t\tPair<FrequencySet<String>, FrequencySet<String>> minAndAltFreq = getElementFrequenciesForAlt(ast);\n\t\t\tFrequencySet<String> minFreq = minAndAltFreq.a;\n\t\t\tFrequencySet<String> altFreq = minAndAltFreq.b;\n\t\t\tfor (GrammarAST t : refs) {\n\t\t\t\tString refLabelName = getName(t);\n\n\t\t\t\tif (refLabelName != null) {\n\t\t\t\t\tif (altFreq.count(refLabelName) > 1) {\n\t\t\t\t\t\tneedsList.add(refLabelName);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (firstAlt && minFreq.count(refLabelName) != 0) {\n\t\t\t\t\t\tnonOptional.add(refLabelName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (String ref : nonOptional.toArray(new String[0])) {\n\t\t\t\tif (minFreq.count(ref) == 0) {\n\t\t\t\t\tnonOptional.remove(ref);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfirstAlt = false;\n\t\t}\n\t\tSet<Decl> decls = new LinkedHashSet<Decl>();\n\t\tfor (GrammarAST t : allRefs) {\n\t\t\tString refLabelName = getName(t);\n\n\t\t\tif (refLabelName == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tList<Decl> d = getDeclForAltElement(t,\n\t\t\t\t\t\t\t\t\t\t\t\trefLabelName,\n\t\t\t\t\t\t\t\t\t\t\t\tneedsList.contains(refLabelName),\n\t\t\t\t\t\t\t\t\t\t\t\t!nonOptional.contains(refLabelName));\n\t\t\tdecls.addAll(d);\n\t\t}\n\t\treturn decls;\n\t}\n\n\tprivate List<GrammarAST> getRuleTokens(List<GrammarAST> refs) {\n\t\tList<GrammarAST> result = new ArrayList<>(refs.size());\n\t\tfor (GrammarAST ref : refs) {\n\t\t\tCommonTree r = ref;\n\n\t\t\tboolean ignore = false;\n\t\t\twhile (r != null) {\n\t\t\t\t// Ignore string literals in predicates\n\t\t\t\tif (r instanceof PredAST) {\n\t\t\t\t\tignore = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tr = r.parent;\n\t\t\t}\n\n\t\t\tif (!ignore) {\n\t\t\t\tresult.add(ref);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate String getName(GrammarAST token) {\n\t\tString tokenText = token.getText();\n\t\tString tokenName = token.getType() != STRING_LITERAL ? tokenText : token.g.getTokenName(tokenText);\n\t\treturn tokenName == null || tokenName.startsWith(\"T__\") ? null : tokenName; // Do not include tokens with auto generated names\n\t}\n\n\t/** Given list of X and r refs in alt, compute how many of each there are */\n\tprotected Pair<FrequencySet<String>, FrequencySet<String>> getElementFrequenciesForAlt(AltAST ast) {\n\t\ttry {\n\t\t\tElementFrequenciesVisitor visitor = new ElementFrequenciesVisitor(new CommonTreeNodeStream(new GrammarASTAdaptor(), ast));\n\t\t\tvisitor.outerAlternative();\n\t\t\tif (visitor.frequencies.size() != 1) {\n\t\t\t\tfactory.getGrammar().tool.errMgr.toolError(ErrorType.INTERNAL_ERROR);\n\t\t\t\treturn new Pair<>(new FrequencySet<String>(), new FrequencySet<String>());\n\t\t\t}\n\n\t\t\treturn new Pair<>(visitor.getMinFrequencies(), visitor.frequencies.peek());\n\t\t}\n\t\tcatch (RecognitionException ex) {\n\t\t\tfactory.getGrammar().tool.errMgr.toolError(ErrorType.INTERNAL_ERROR, ex);\n\t\t\treturn new Pair<>(new FrequencySet<String>(), new FrequencySet<String>());\n\t\t}\n\t}\n\n\tpublic List<Decl> getDeclForAltElement(GrammarAST t, String refLabelName, boolean needList, boolean optional) {\n\t\tList<Decl> decls = new ArrayList<Decl>();\n\t\tif ( t.getType()==RULE_REF ) {\n\t\t\tRule rref = factory.getGrammar().getRule(t.getText());\n\t\t\tString ctxName = factory.getGenerator().getTarget()\n\t\t\t\t\t\t\t .getRuleFunctionContextStructName(rref);\n\t\t\tif ( needList) {\n\t\t\t\tif(factory.getGenerator().getTarget().supportsOverloadedMethods())\n\t\t\t\t\tdecls.add( new ContextRuleListGetterDecl(factory, refLabelName, ctxName) );\n\t\t\t\tdecls.add( new ContextRuleListIndexedGetterDecl(factory, refLabelName, ctxName) );\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdecls.add( new ContextRuleGetterDecl(factory, refLabelName, ctxName, optional) );\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif ( needList ) {\n\t\t\t\tif(factory.getGenerator().getTarget().supportsOverloadedMethods())\n\t\t\t\t\tdecls.add( new ContextTokenListGetterDecl(factory, refLabelName) );\n\t\t\t\tdecls.add( new ContextTokenListIndexedGetterDecl(factory, refLabelName) );\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdecls.add( new ContextTokenGetterDecl(factory, refLabelName, optional) );\n\t\t\t}\n\t\t}\n\t\treturn decls;\n\t}\n\n\t/** Add local var decl */\n\tpublic void addLocalDecl(Decl d) {\n\t\tif ( locals ==null ) locals = new OrderedHashSet<Decl>();\n\t\tlocals.add(d);\n\t\td.isLocal = true;\n\t}\n\n\t/** Add decl to struct ctx for rule or alt if labeled */\n\tpublic void addContextDecl(String altLabel, Decl d) {\n\t\tCodeBlockForOuterMostAlt alt = d.getOuterMostAltCodeBlock();\n\t\t// if we found code blk and might be alt label, try to add to that label ctx\n\t\tif ( alt!=null && altLabelCtxs!=null ) {\n//\t\t\tSystem.out.println(d.name+\" lives in alt \"+alt.alt.altNum);\n\t\t\tAltLabelStructDecl altCtx = altLabelCtxs.get(altLabel);\n\t\t\tif ( altCtx!=null ) { // we have an alt ctx\n//\t\t\t\tSystem.out.println(\"ctx is \"+ altCtx.name);\n\t\t\t\taltCtx.addDecl(d);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\truleCtx.addDecl(d); // stick in overall rule's ctx\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/RuleSempredFunction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.Rule;\n\npublic class RuleSempredFunction extends RuleActionFunction {\n\tpublic RuleSempredFunction(OutputModelFactory factory, Rule r, String ctxType) {\n\t\tsuper(factory, r, ctxType);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/SemPred.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.ActionTranslator;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.chunk.ActionChunk;\nimport org.antlr.v4.runtime.atn.AbstractPredicateTransition;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** */\npublic class SemPred extends Action {\n\t/**\n\t * The user-specified terminal option {@code fail}, if it was used and the\n\t * value is a string literal. For example:\n\t *\n\t * <p>\n\t * {@code {pred}?<fail='message'>}</p>\n\t */\n\tpublic String msg;\n\t/**\n\t * The predicate string with <code>{</code> and <code>}?</code> stripped from the ends.\n\t */\n\tpublic String predicate;\n\n\t/**\n\t * The translated chunks of the user-specified terminal option {@code fail},\n\t * if it was used and the value is an action. For example:\n\t *\n\t * <p>\n\t * {@code {pred}?<fail={\"Java literal\"}>}</p>\n\t */\n\t@ModelElement public List<ActionChunk> failChunks;\n\n\tpublic SemPred(OutputModelFactory factory, ActionAST ast) {\n\t\tsuper(factory,ast);\n\n\t\tassert ast.atnState != null\n\t\t\t&& ast.atnState.getNumberOfTransitions() == 1\n\t\t\t&& ast.atnState.transition(0) instanceof AbstractPredicateTransition;\n\n\t\tGrammarAST failNode = ast.getOptionAST(\"fail\");\n\t\tCodeGenerator gen = factory.getGenerator();\n\t\tpredicate = ast.getText();\n\t\tif (predicate.startsWith(\"{\") && predicate.endsWith(\"}?\")) {\n\t\t\tpredicate = predicate.substring(1, predicate.length() - 2);\n\t\t}\n\t\tpredicate = gen.getTarget().getTargetStringLiteralFromString(predicate);\n\n\t\tif ( failNode==null ) return;\n\n\t\tif ( failNode instanceof ActionAST ) {\n\t\t\tActionAST failActionNode = (ActionAST)failNode;\n\t\t\tRuleFunction rf = factory.getCurrentRuleFunction();\n\t\t\tfailChunks = ActionTranslator.translateAction(factory, rf,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  failActionNode.token,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  failActionNode);\n\t\t}\n\t\telse {\n\t\t\tmsg = gen.getTarget().getTargetStringLiteralFromANTLRStringLiteral(gen,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  failNode.getText(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  true);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/SerializedATN.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.runtime.misc.IntegerList;\n\n/** Represents a serialized ATN that is just a list of signed integers; works for all targets\n *  except for java, which requires a 16-bit char encoding. See {@link SerializedJavaATN}.\n */\npublic class SerializedATN extends OutputModelObject {\n\tpublic int[] serialized;\n\n\tpublic SerializedATN(OutputModelFactory factory) {\n\t\tsuper(factory);\n\t}\n\n\tpublic SerializedATN(OutputModelFactory factory, ATN atn) {\n\t\tsuper(factory);\n\t\tIntegerList data = ATNSerializer.getSerialized(atn);\n\t\tserialized = data.toArray();\n\t}\n\n\tpublic Object getSerialized() { return serialized; }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/SerializedJavaATN.java",
    "content": "package org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.runtime.misc.IntegerList;\n\n/** A serialized ATN for the java target, which requires we use strings and 16-bit unicode values */\npublic class SerializedJavaATN extends SerializedATN {\n\tprivate final String[] serializedAsString;\n\tprivate final String[][] segments;\n\n\tpublic SerializedJavaATN(OutputModelFactory factory, ATN atn) {\n\t\tsuper(factory);\n\t\tIntegerList data = ATNSerializer.getSerialized(atn);\n\t\tdata = ATNDeserializer.encodeIntsWith16BitWords(data);\n\n\t\tint size = data.size();\n\t\tTarget target = factory.getGenerator().getTarget();\n\t\tint segmentLimit = target.getSerializedATNSegmentLimit();\n\t\tsegments = new String[(int)(((long)size + segmentLimit - 1) / segmentLimit)][];\n\t\tint segmentIndex = 0;\n\n\t\tfor (int i = 0; i < size; i += segmentLimit) {\n\t\t\tint segmentSize = Math.min(i + segmentLimit, size) - i;\n\t\t\tString[] segment = new String[segmentSize];\n\t\t\tsegments[segmentIndex++] = segment;\n\t\t\tfor (int j = 0; j < segmentSize; j++) {\n\t\t\t\tsegment[j] = target.encodeInt16AsCharEscape(data.get(i + j));\n\t\t\t}\n\t\t}\n\n\t\tserializedAsString = segments[0]; // serializedAsString is valid if only one segment\n\t}\n\n\tpublic Object getSerialized() { return serializedAsString; }\n\tpublic String[][] getSegments() { return segments; }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/SrcOp.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.decl.CodeBlock;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\n/** */\npublic abstract class SrcOp extends OutputModelObject {\n\t/** Used to create unique var names etc... */\n\tpublic int uniqueID; // TODO: do we need?\n\n\t/** All operations know in which block they live:\n\t *\n\t *  \tCodeBlock, CodeBlockForAlt\n\t *\n\t *  Templates might need to know block nesting level or find\n\t *  a specific declaration, etc...\n\t */\n\tpublic CodeBlock enclosingBlock;\n\n\tpublic RuleFunction enclosingRuleRunction;\n\n\tpublic SrcOp(OutputModelFactory factory) { this(factory,null); }\n\tpublic SrcOp(OutputModelFactory factory, GrammarAST ast) {\n\t\tsuper(factory,ast);\n\t\tif ( ast!=null ) uniqueID = ast.token.getTokenIndex();\n\t\tenclosingBlock = factory.getCurrentBlock();\n\t\tenclosingRuleRunction = factory.getCurrentRuleFunction();\n\t}\n\n\t/** Walk upwards in model tree, looking for outer alt's code block */\n\tpublic CodeBlockForOuterMostAlt getOuterMostAltCodeBlock() {\n\t\tif ( this instanceof CodeBlockForOuterMostAlt ) {\n\t\t\treturn (CodeBlockForOuterMostAlt)this;\n\t\t}\n\t\tCodeBlock p = enclosingBlock;\n\t\twhile ( p!=null ) {\n\t\t\tif ( p instanceof CodeBlockForOuterMostAlt ) {\n\t\t\t\treturn (CodeBlockForOuterMostAlt)p;\n\t\t\t}\n\t\t\tp = p.enclosingBlock;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Return label alt or return name of rule */\n\tpublic String getContextName() {\n\t\tCodeBlockForOuterMostAlt alt = getOuterMostAltCodeBlock();\n\t\tif ( alt!=null && alt.altLabel!=null ) return alt.altLabel;\n\t\treturn enclosingRuleRunction.name;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/StarBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\npublic class StarBlock extends Loop {\n\tpublic String loopLabel;\n\n\tpublic StarBlock(OutputModelFactory factory,\n\t\t\t\t\t GrammarAST blkOrEbnfRootAST,\n\t\t\t\t\t List<CodeBlockForAlt> alts)\n\t{\n\t\tsuper(factory, blkOrEbnfRootAST, alts);\n\t\tloopLabel = factory.getGenerator().getTarget().getLoopLabel(blkOrEbnfRootAST);\n\t\tStarLoopEntryState star = (StarLoopEntryState)blkOrEbnfRootAST.atnState;\n\t\tloopBackStateNumber = star.loopBackState.stateNumber;\n\t\tdecision = star.decision;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Sync.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\n/** */\npublic class Sync extends SrcOp {\n\tpublic int decision;\n//\tpublic BitSetDecl expecting;\n\tpublic Sync(OutputModelFactory factory,\n\t\t\t\tGrammarAST blkOrEbnfRootAST,\n\t\t\t\tIntervalSet expecting,\n\t\t\t\tint decision,\n\t\t\t\tString position)\n\t{\n\t\tsuper(factory, blkOrEbnfRootAST);\n\t\tthis.decision = decision;\n//\t\tthis.expecting = factory.createExpectingBitSet(ast, decision, expecting, position);\n//\t\tfactory.defineBitSet(this.expecting);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/TestSetInline.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** */\npublic class TestSetInline extends SrcOp {\n\tpublic final int bitsetWordSize;\n\tpublic final String varName;\n\tpublic final Bitset[] bitsets;\n\n\tpublic TestSetInline(OutputModelFactory factory, GrammarAST ast, IntervalSet set, int wordSize) {\n\t\tsuper(factory, ast);\n\t\tbitsetWordSize = wordSize;\n\t\tBitset[] withZeroOffset = createBitsets(factory, set, wordSize, true);\n\t\tBitset[] withoutZeroOffset = createBitsets(factory, set, wordSize, false);\n\t\tthis.bitsets = withZeroOffset.length <= withoutZeroOffset.length ? withZeroOffset : withoutZeroOffset;\n\t\tthis.varName = \"_la\";\n\t}\n\n\tprivate static Bitset[] createBitsets(OutputModelFactory factory,\n\t\t\t\t\t\t\t\t\t\t  IntervalSet set,\n\t\t\t\t\t\t\t\t\t\t  int wordSize,\n\t\t\t\t\t\t\t\t\t\t  boolean useZeroOffset) {\n\t\tList<Bitset> bitsetList = new ArrayList<>();\n\t\tTarget target = factory.getGenerator().getTarget();\n\t\tBitset current = null;\n\t\tfor (int ttype : set.toArray()) {\n\t\t\tif (current == null || ttype > (current.shift + wordSize-1)) {\n\t\t\t\tint shift;\n\t\t\t\tif (useZeroOffset && ttype >= 0 && ttype < wordSize-1) {\n\t\t\t\t\tshift = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tshift = ttype;\n\t\t\t\t}\n\t\t\t\tcurrent = new Bitset(shift);\n\t\t\t\tbitsetList.add(current);\n\t\t\t}\n\n\t\t\tcurrent.addToken(ttype, target.getTokenTypeAsTargetLabel(factory.getGrammar(), ttype));\n\t\t}\n\n\t\treturn bitsetList.toArray(new Bitset[0]);\n\t}\n\n\tpublic static final class Bitset {\n\t\tpublic final int shift;\n\t\tprivate final List<TokenInfo> tokens = new ArrayList<>();\n\t\tprivate long calculated;\n\n\t\tpublic Bitset(int shift) {\n\t\t\tthis.shift = shift;\n\t\t}\n\n\t\tpublic void addToken(int type, String name) {\n\t\t\ttokens.add(new TokenInfo(type, name));\n\t\t\tcalculated |= 1L << (type - shift);\n\t\t}\n\n\t\tpublic List<TokenInfo> getTokens() {\n\t\t\treturn tokens;\n\t\t}\n\n\t\tpublic long getCalculated() {\n\t\t\treturn calculated;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ThrowEarlyExitException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\n/** */\npublic class ThrowEarlyExitException extends ThrowRecognitionException {\n\tpublic ThrowEarlyExitException(OutputModelFactory factory, GrammarAST ast, IntervalSet expecting) {\n\t\tsuper(factory, ast, expecting);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ThrowNoViableAlt.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\n/** */\npublic class ThrowNoViableAlt extends ThrowRecognitionException {\n\tpublic ThrowNoViableAlt(OutputModelFactory factory, GrammarAST blkOrEbnfRootAST,\n\t\t\t\t\t\t\tIntervalSet expecting)\n\t{\n\t\tsuper(factory, blkOrEbnfRootAST, expecting);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/ThrowRecognitionException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\n/** */\npublic class ThrowRecognitionException extends SrcOp {\n\tpublic int decision;\n\tpublic String grammarFile;\n\tpublic int grammarLine;\n\tpublic int grammarCharPosInLine;\n\n\tpublic ThrowRecognitionException(OutputModelFactory factory, GrammarAST ast, IntervalSet expecting) {\n\t\tsuper(factory, ast);\n\t\t//this.decision = ((BlockStartState)ast.ATNState).decision;\n\t\tgrammarLine = ast.getLine();\n\t\tgrammarLine = ast.getCharPositionInLine();\n\t\tgrammarFile = factory.getGrammar().fileName;\n\t\t//this.expecting = factory.createExpectingBitSet(ast, decision, expecting, \"error\");\n//\t\tfactory.defineBitSet(this.expecting);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/TokenInfo.java",
    "content": "package org.antlr.v4.codegen.model;\n\npublic class TokenInfo {\n\tpublic final int type;\n\tpublic final String name;\n\n\tpublic TokenInfo(int type, String name) {\n\t\tthis.type = type;\n\t\tthis.name = name;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"TokenInfo{\" +\n\t\t\t\t\"type=\" + type +\n\t\t\t\t\", name='\" + name + '\\'' +\n\t\t\t\t'}';\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/VisitorDispatchMethod.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class VisitorDispatchMethod extends DispatchMethod {\n\tpublic VisitorDispatchMethod(OutputModelFactory factory) {\n\t\tsuper(factory);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/VisitorFile.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\n\nimport java.util.*;\n\npublic class VisitorFile extends OutputFile {\n\tpublic String genPackage; // from -package cmd-line\n\tpublic boolean genLean; // from -split-parser cmd-line\n\tpublic String accessLevel; // from -DaccessLevel cmd-line\n\tpublic String exportMacro; // from -DexportMacro cmd-line\n\tpublic String grammarName;\n\tpublic String parserName;\n\t/**\n\t * The names of all rule contexts which may need to be visited.\n\t */\n\tpublic Set<String> visitorNames = new LinkedHashSet<String>();\n\t/**\n\t * For rule contexts created for a labeled outer alternative, maps from\n\t * a listener context name to the name of the rule which defines the\n\t * context.\n\t */\n\tpublic Map<String, String> visitorLabelRuleNames = new LinkedHashMap<String, String>();\n\n\t@ModelElement public Action header;\n\t@ModelElement public Map<String, Action> namedActions;\n\n\tpublic VisitorFile(OutputModelFactory factory, String fileName) {\n\t\tsuper(factory, fileName);\n\t\tGrammar g = factory.getGrammar();\n\t\tnamedActions = buildNamedActions(g, ast -> ast.getScope()==null);\n\t\tparserName = g.getRecognizerName();\n\t\tgrammarName = g.name;\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tMap<String, List<Pair<Integer, AltAST>>> labels = r.getAltLabels();\n\t\t\tif ( labels!=null ) {\n\t\t\t\tfor (Map.Entry<String, List<Pair<Integer, AltAST>>> pair : labels.entrySet()) {\n\t\t\t\t\tvisitorNames.add(pair.getKey());\n\t\t\t\t\tvisitorLabelRuleNames.put(pair.getKey(), r.name);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// if labels, must label all. no need for generic rule visitor then\n\t\t\t\tvisitorNames.add(r.name);\n\t\t\t}\n\t\t}\n\t\tActionAST ast = g.namedActions.get(\"header\");\n\t\tif ( ast!=null && ast.getScope()==null)\n\t\t\theader = new Action(factory, ast);\n\t\tgenPackage = g.tool.genPackage;\n\t\tgenLean = g.tool.gen_split_parser;\n\t\taccessLevel = g.getOptionString(\"accessLevel\");\n\t\texportMacro = g.getOptionString(\"exportMacro\");\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/Wildcard.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\npublic class Wildcard extends MatchToken {\n\tpublic Wildcard(OutputModelFactory factory, GrammarAST ast) {\n\t\tsuper(factory, ast);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ActionChunk.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.OutputModelObject;\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class ActionChunk extends OutputModelObject {\n\t/** Where is the ctx that defines attrs,labels etc... for this action? */\n\tpublic StructDecl ctx;\n\n\tpublic ActionChunk(StructDecl ctx) {\n\t\tthis.ctx = ctx;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ActionTemplate.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\nimport org.stringtemplate.v4.ST;\n\npublic class ActionTemplate extends ActionChunk {\n\tpublic ST st;\n\n\tpublic ActionTemplate(StructDecl ctx, ST st) {\n\t\tsuper(ctx);\n\t\tthis.st = st;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ActionText.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class ActionText extends ActionChunk {\n\tpublic String text;\n\n\tpublic ActionText(StructDecl ctx, String text) {\n\t\tsuper(ctx);\n\t\tthis.text = text;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ArgRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class ArgRef extends LocalRef {\n\tpublic ArgRef(StructDecl ctx, String name, String escapedName) {\n\t\tsuper(ctx, name, escapedName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/LabelRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\npublic class LabelRef extends SymbolRefChunk {\n\tpublic LabelRef(StructDecl ctx, String name, String escapedName) {\n\t\tsuper(ctx, name, escapedName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ListLabelRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\npublic class ListLabelRef extends LabelRef {\n\tpublic ListLabelRef(StructDecl ctx, String name, String escapedName) { super(ctx, name, escapedName); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/LocalRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\npublic class LocalRef extends SymbolRefChunk {\n\tpublic LocalRef(StructDecl ctx, String name, String escapedName) {\n\t\tsuper(ctx, name, escapedName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/NonLocalAttrRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\npublic class NonLocalAttrRef extends SymbolRefChunk {\n\tpublic String ruleName;\n\tpublic int ruleIndex;\n\n\tpublic NonLocalAttrRef(StructDecl ctx, String ruleName, String name, String escapedName, int ruleIndex) {\n\t\tsuper(ctx, name, escapedName);\n\t\tthis.ruleName = ruleName;\n\t\tthis.ruleIndex = ruleIndex;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/QRetValueRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class QRetValueRef extends RetValueRef {\n\tpublic final String dict;\n\n\tpublic QRetValueRef(StructDecl ctx, String dict, String name, String escapedName) {\n\t\tsuper(ctx, name, escapedName);\n\t\tthis.dict = dict;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/RetValueRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class RetValueRef extends SymbolRefChunk {\n\tpublic RetValueRef(StructDecl ctx, String name, String escapedName) {\n\t\tsuper(ctx, name, escapedName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/RulePropertyRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class RulePropertyRef extends ActionChunk {\n\tpublic String label;\n\n\tpublic RulePropertyRef(StructDecl ctx, String label) {\n\t\tsuper(ctx);\n\t\tthis.label = label;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/RulePropertyRef_ctx.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\npublic class RulePropertyRef_ctx extends RulePropertyRef {\n    public RulePropertyRef_ctx(StructDecl ctx, String label) {\n        super(ctx, label);\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/RulePropertyRef_parser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class RulePropertyRef_parser extends RulePropertyRef {\n\tpublic RulePropertyRef_parser(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/RulePropertyRef_start.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class RulePropertyRef_start extends RulePropertyRef {\n\tpublic RulePropertyRef_start(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/RulePropertyRef_stop.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class RulePropertyRef_stop extends RulePropertyRef {\n\tpublic RulePropertyRef_stop(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/RulePropertyRef_text.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class RulePropertyRef_text extends RulePropertyRef {\n\tpublic RulePropertyRef_text(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/SetAttr.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.ModelElement;\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\nimport java.util.List;\n\n/** */\npublic class SetAttr extends SymbolRefChunk {\n\t@ModelElement public List<ActionChunk> rhsChunks;\n\n\tpublic SetAttr(StructDecl ctx, String name, String escapedName, List<ActionChunk> rhsChunks) {\n\t\tsuper(ctx, name, escapedName);\n\t\tthis.rhsChunks = rhsChunks;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/SetNonLocalAttr.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\nimport java.util.List;\n\npublic class SetNonLocalAttr extends SetAttr {\n\tpublic String ruleName;\n\tpublic int ruleIndex;\n\n\tpublic SetNonLocalAttr(StructDecl ctx,\n\t\t\t\t\t\t   String ruleName, String name, String escapedName, int ruleIndex,\n\t\t\t\t\t\t   List<ActionChunk> rhsChunks)\n\t{\n\t\tsuper(ctx, name, escapedName, rhsChunks);\n\t\tthis.ruleName = ruleName;\n\t\tthis.ruleIndex = ruleIndex;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/SymbolRefChunk.java",
    "content": "package org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\npublic abstract class SymbolRefChunk extends ActionChunk {\n\tpublic final String name;\n\tpublic final String escapedName;\n\n\tpublic SymbolRefChunk(StructDecl ctx, String name, String escapedName) {\n\t\tsuper(ctx);\n\t\tthis.name = name;\n\t\tthis.escapedName = escapedName;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ThisRulePropertyRef_ctx.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\npublic class ThisRulePropertyRef_ctx extends RulePropertyRef {\n    public ThisRulePropertyRef_ctx(StructDecl ctx, String label) {\n        super(ctx, label);\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ThisRulePropertyRef_parser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class ThisRulePropertyRef_parser extends RulePropertyRef {\n\tpublic ThisRulePropertyRef_parser(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ThisRulePropertyRef_start.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class ThisRulePropertyRef_start extends RulePropertyRef {\n\tpublic ThisRulePropertyRef_start(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ThisRulePropertyRef_stop.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class ThisRulePropertyRef_stop extends RulePropertyRef {\n\tpublic ThisRulePropertyRef_stop(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/ThisRulePropertyRef_text.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class ThisRulePropertyRef_text extends RulePropertyRef {\n\tpublic ThisRulePropertyRef_text(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef extends ActionChunk {\n\tpublic String label;\n\n\tpublic TokenPropertyRef(StructDecl ctx, String label) {\n\t\tsuper(ctx);\n\t\tthis.label = label;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef_channel.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef_channel extends TokenPropertyRef {\n\tpublic TokenPropertyRef_channel(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef_index.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef_index extends TokenPropertyRef {\n\tpublic TokenPropertyRef_index(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef_int.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef_int extends TokenPropertyRef {\n\tpublic TokenPropertyRef_int(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef_line.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef_line extends TokenPropertyRef {\n\tpublic TokenPropertyRef_line(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef_pos.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef_pos extends TokenPropertyRef {\n\tpublic TokenPropertyRef_pos(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef_text.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef_text extends TokenPropertyRef {\n\tpublic TokenPropertyRef_text(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenPropertyRef_type.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenPropertyRef_type extends TokenPropertyRef {\n\tpublic TokenPropertyRef_type(StructDecl ctx, String label) {\n\t\tsuper(ctx, label);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/chunk/TokenRef.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.chunk;\n\nimport org.antlr.v4.codegen.model.decl.StructDecl;\n\n/** */\npublic class TokenRef extends SymbolRefChunk {\n\tpublic TokenRef(StructDecl ctx, String name, String escapedName) {\n\t\tsuper(ctx, name, escapedName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/dbg.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model;\n\n/** */\npublic class dbg extends OutputModelObject {\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/AltLabelStructDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.DispatchMethod;\nimport org.antlr.v4.codegen.model.ListenerDispatchMethod;\nimport org.antlr.v4.codegen.model.VisitorDispatchMethod;\nimport org.antlr.v4.tool.Rule;\n\nimport java.util.ArrayList;\n\n/** A StructDecl to handle a -&gt; label on alt */\npublic class AltLabelStructDecl extends StructDecl {\n\tpublic int altNum;\n\tpublic String parentRule;\n\tpublic AltLabelStructDecl(OutputModelFactory factory, Rule r,\n\t\t\t\t\t\t\t  int altNum, String label)\n\t{\n\t\t// override name set in super to the label ctx\n\t\tsuper(factory, r, factory.getGenerator().getTarget().getAltLabelContextStructName(label));\n\t\tthis.altNum = altNum;\n\t\tthis.parentRule = r.name;\n\t\tderivedFromName = label;\n\t}\n\n\t@Override\n\tpublic void addDispatchMethods(Rule r) {\n\t\tdispatchMethods = new ArrayList<DispatchMethod>();\n\t\tif ( factory.getGrammar().tool.gen_listener ) {\n\t\t\tdispatchMethods.add(new ListenerDispatchMethod(factory, true));\n\t\t\tdispatchMethods.add(new ListenerDispatchMethod(factory, false));\n\t\t}\n\t\tif ( factory.getGrammar().tool.gen_visitor ) {\n\t\t\tdispatchMethods.add(new VisitorDispatchMethod(factory));\n\t\t}\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn name.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif ( obj == this ) return true;\n\t\tif (!(obj instanceof AltLabelStructDecl)) return false;\n\n\t\treturn name.equals(((AltLabelStructDecl)obj).name);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/AttributeDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.tool.Attribute;\n\n/** */\npublic class AttributeDecl extends Decl {\n\tpublic String type;\n\tpublic String initValue;\n\tpublic AttributeDecl(OutputModelFactory factory, Attribute a) {\n\t\tsuper(factory, a.name, a.decl);\n\t\tthis.type = a.type;\n\t\tthis.initValue = a.initValue;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/CodeBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.ModelElement;\nimport org.antlr.v4.codegen.model.SrcOp;\nimport org.antlr.v4.runtime.misc.OrderedHashSet;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class CodeBlock extends SrcOp {\n\tpublic int codeBlockLevel;\n\tpublic int treeLevel;\n\n\t@ModelElement public OrderedHashSet<Decl> locals;\n\t@ModelElement public List<SrcOp> preamble;\n\t@ModelElement public List<SrcOp> ops;\n\n\tpublic CodeBlock(OutputModelFactory factory) {\n\t\tsuper(factory);\n\t}\n\n\tpublic CodeBlock(OutputModelFactory factory, int treeLevel, int codeBlockLevel) {\n\t\tsuper(factory);\n\t\tthis.treeLevel = treeLevel;\n\t\tthis.codeBlockLevel = codeBlockLevel;\n\t}\n\n\t/** Add local var decl */\n\tpublic void addLocalDecl(Decl d) {\n\t\tif ( locals==null ) locals = new OrderedHashSet<Decl>();\n\t\tlocals.add(d);\n\t\td.isLocal = true;\n\t}\n\n\tpublic void addPreambleOp(SrcOp op) {\n\t\tif ( preamble==null ) preamble = new ArrayList<SrcOp>();\n\t\tpreamble.add(op);\n\t}\n\n\tpublic void addOp(SrcOp op) {\n\t\tif ( ops==null ) ops = new ArrayList<SrcOp>();\n\t\tops.add(op);\n\t}\n\n\tpublic void insertOp(int i, SrcOp op) {\n\t\tif ( ops==null ) ops = new ArrayList<SrcOp>();\n\t\tops.add(i, op);\n\t}\n\n\tpublic void addOps(List<SrcOp> ops) {\n\t\tif ( this.ops==null ) this.ops = new ArrayList<SrcOp>();\n\t\tthis.ops.addAll(ops);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ContextGetterDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.runtime.misc.MurmurHash;\n\npublic abstract class ContextGetterDecl extends Decl {\n\tpublic ContextGetterDecl(OutputModelFactory factory, String name) {\n\t\tthis(factory, name, false);\n\t}\n\n\tpublic ContextGetterDecl(OutputModelFactory factory, String name, boolean signature) {\n\t\tsuper(factory, name);\n\t\tthis.signature = signature;\n\t}\n\n\t/** Not used for output; just used to distinguish between decl types\n\t *  to avoid dups.\n\t */\n\tpublic String getArgType() { return \"\"; }; // assume no args\n\n\tpublic final boolean signature;\n\tabstract ContextGetterDecl getSignatureDecl();\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint hash = MurmurHash.initialize();\n\t\thash = MurmurHash.update(hash, name);\n\t\thash = MurmurHash.update(hash, getArgType());\n\t\thash = MurmurHash.finish(hash, 2);\n\t\treturn hash;\n\t}\n\n\t/** Make sure that a getter does not equal a label. X() and X are ok.\n\t *  OTOH, treat X() with two diff return values as the same.  Treat\n\t *  two X() with diff args as different.\n\t */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif ( this==obj ) return true;\n\t\t// A() and label A are different\n\t\tif ( !(obj instanceof ContextGetterDecl) ) return false;\n\t\treturn name.equals(((Decl) obj).name) &&\n\t\t\t\tgetArgType().equals(((ContextGetterDecl) obj).getArgType());\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ContextRuleGetterDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** {@code public XContext X() { }} */\npublic class ContextRuleGetterDecl extends ContextGetterDecl {\n\tpublic String ctxName;\n\tpublic boolean optional;\n\n\tpublic ContextRuleGetterDecl(OutputModelFactory factory, String name, String ctxName, boolean optional) {\n\t\tthis(factory, name, ctxName, optional, false);\n\t}\n\n\tpublic ContextRuleGetterDecl(OutputModelFactory factory, String name, String ctxName, boolean optional, boolean signature) {\n\t\tsuper(factory, name, signature);\n\t\tthis.ctxName = ctxName;\n\t\tthis.optional = optional;\n\t}\n\n\t@Override\n\tpublic ContextGetterDecl getSignatureDecl() {\n\t\treturn new ContextRuleGetterDecl(factory, name, ctxName, optional, true);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ContextRuleListGetterDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** {@code public List<XContext> X() { }\n *  public XContext X(int i) { }}\n */\npublic class ContextRuleListGetterDecl extends ContextGetterDecl {\n\tpublic String ctxName;\n\tpublic ContextRuleListGetterDecl(OutputModelFactory factory, String name, String ctxName) {\n\t\tthis(factory, name, ctxName, false);\n\t}\n\n\tpublic ContextRuleListGetterDecl(OutputModelFactory factory, String name, String ctxName, boolean signature) {\n\t\tsuper(factory, name, signature);\n\t\tthis.ctxName = ctxName;\n\t}\n\n\t@Override\n\tpublic ContextGetterDecl getSignatureDecl() {\n\t\treturn new ContextRuleListGetterDecl(factory, name, ctxName, true);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ContextRuleListIndexedGetterDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class ContextRuleListIndexedGetterDecl extends ContextRuleListGetterDecl {\n\tpublic ContextRuleListIndexedGetterDecl(OutputModelFactory factory, String name, String ctxName) {\n\t\tthis(factory, name, ctxName, false);\n\t}\n\n\tpublic ContextRuleListIndexedGetterDecl(OutputModelFactory factory, String name, String ctxName, boolean signature) {\n\t\tsuper(factory, name, ctxName, signature);\n\t}\n\n\t@Override\n\tpublic String getArgType() {\n\t\treturn \"int\";\n\t}\n\n\t@Override\n\tpublic ContextGetterDecl getSignatureDecl() {\n\t\treturn new ContextRuleListIndexedGetterDecl(factory, name, ctxName, true);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ContextTokenGetterDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** {@code public Token X() { }} */\npublic class ContextTokenGetterDecl extends ContextGetterDecl {\n\tpublic boolean optional;\n\n\tpublic ContextTokenGetterDecl(OutputModelFactory factory, String name, boolean optional) {\n\t\tthis(factory, name, optional, false);\n\t}\n\n\tpublic ContextTokenGetterDecl(OutputModelFactory factory, String name, boolean optional, boolean signature) {\n\t\tsuper(factory, name, signature);\n\t\tthis.optional = optional;\n\t}\n\n\t@Override\n\tpublic ContextGetterDecl getSignatureDecl() {\n\t\treturn new ContextTokenGetterDecl(factory, name, optional, true);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ContextTokenListGetterDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** {@code public List<Token> X() { }\n *  public Token X(int i) { }}\n */\npublic class ContextTokenListGetterDecl extends ContextGetterDecl {\n\tpublic ContextTokenListGetterDecl(OutputModelFactory factory, String name) {\n\t\tthis(factory, name, false);\n\t}\n\n\tpublic ContextTokenListGetterDecl(OutputModelFactory factory, String name, boolean signature) {\n\t\tsuper(factory, name, signature);\n\t}\n\n\t@Override\n\tpublic ContextGetterDecl getSignatureDecl() {\n\t\treturn new ContextTokenListGetterDecl(factory, name, true);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ContextTokenListIndexedGetterDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class ContextTokenListIndexedGetterDecl extends ContextTokenListGetterDecl {\n\tpublic ContextTokenListIndexedGetterDecl(OutputModelFactory factory, String name) {\n\t\tthis(factory, name, false);\n\t}\n\n\tpublic ContextTokenListIndexedGetterDecl(OutputModelFactory factory, String name, boolean signature) {\n\t\tsuper(factory, name, signature);\n\t}\n\n\t@Override\n\tpublic String getArgType() {\n\t\treturn \"int\";\n\t}\n\n\t@Override\n\tpublic ContextGetterDecl getSignatureDecl() {\n\t\treturn new ContextTokenListIndexedGetterDecl(factory, name, true);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/Decl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.SrcOp;\n\n/** */\npublic class Decl extends SrcOp {\n\tpublic final String name;\n\tpublic final String escapedName;\n\tpublic final String decl; \t// whole thing if copied from action\n\tpublic boolean isLocal; // if local var (not in RuleContext struct)\n\tpublic StructDecl ctx;  // which context contains us? set by addDecl\n\n\tpublic Decl(OutputModelFactory factory, String name) {\n\t\tthis(factory, name, null);\n\t}\n\n\tpublic Decl(OutputModelFactory factory, String name, String decl) {\n\t\tsuper(factory);\n\t\tthis.name = name;\n\t\tthis.escapedName = factory.getGenerator().getTarget().escapeIfNeeded(name);\n\t\tthis.decl = decl;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn name.hashCode();\n\t}\n\n\t/** If same name, can't redefine, unless it's a getter */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif ( this==obj ) return true;\n\t\tif ( !(obj instanceof Decl) ) return false;\n\t\t// A() and label A are different\n\t\tif ( obj instanceof ContextGetterDecl ) return false;\n\t\treturn name.equals(((Decl) obj).name);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/ElementListDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class ElementListDecl extends Decl {\n\tpublic ElementListDecl(OutputModelFactory factory, String name) {\n\t\tsuper(factory, name);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/RuleContextDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** */\npublic class RuleContextDecl extends Decl {\n\tpublic String ctxName;\n\tpublic boolean isImplicit;\n\n\tpublic RuleContextDecl(OutputModelFactory factory, String name, String ctxName) {\n\t\tsuper(factory, name);\n\t\tthis.ctxName = ctxName;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/RuleContextListDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\npublic class RuleContextListDecl extends RuleContextDecl {\n\tpublic RuleContextListDecl(OutputModelFactory factory, String name, String ctxName) {\n\t\tsuper(factory, name, ctxName);\n\t\tisImplicit = false;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/StructDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\nimport org.antlr.v4.codegen.model.DispatchMethod;\nimport org.antlr.v4.codegen.model.ListenerDispatchMethod;\nimport org.antlr.v4.codegen.model.ModelElement;\nimport org.antlr.v4.codegen.model.OutputModelObject;\nimport org.antlr.v4.codegen.model.VisitorDispatchMethod;\nimport org.antlr.v4.runtime.misc.OrderedHashSet;\nimport org.antlr.v4.tool.Attribute;\nimport org.antlr.v4.tool.Rule;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\n/** This object models the structure holding all of the parameters,\n *  return values, local variables, and labels associated with a rule.\n */\npublic class StructDecl extends Decl {\n\tpublic String derivedFromName; // rule name or label name\n\tpublic boolean provideCopyFrom;\n\t@ModelElement public OrderedHashSet<Decl> attrs = new OrderedHashSet<Decl>();\n\t@ModelElement public OrderedHashSet<Decl> getters = new OrderedHashSet<Decl>();\n\t@ModelElement public Collection<AttributeDecl> ctorAttrs;\n\t@ModelElement public List<? super DispatchMethod> dispatchMethods;\n\t@ModelElement public List<OutputModelObject> interfaces;\n\t@ModelElement public List<OutputModelObject> extensionMembers;\n\t// Used to generate method signatures in Go target interfaces\n\t@ModelElement public OrderedHashSet<Decl> signatures = new OrderedHashSet<Decl>();\n\n\t// Track these separately; Go target needs to generate getters/setters\n\t// Do not make them templates; we only need the Decl object not the ST\n\t// built from it. Avoids adding args to StructDecl template\n\tpublic OrderedHashSet<Decl> tokenDecls = new OrderedHashSet<Decl>();\n\tpublic OrderedHashSet<Decl> tokenTypeDecls = new OrderedHashSet<Decl>();\n\tpublic OrderedHashSet<Decl> tokenListDecls = new OrderedHashSet<Decl>();\n\tpublic OrderedHashSet<Decl> ruleContextDecls = new OrderedHashSet<Decl>();\n\tpublic OrderedHashSet<Decl> ruleContextListDecls = new OrderedHashSet<Decl>();\n\tpublic OrderedHashSet<Decl> attributeDecls = new OrderedHashSet<Decl>();\n\n\tpublic StructDecl(OutputModelFactory factory, Rule r) {\n\t\tthis(factory, r, null);\n\t}\n\n\tprotected StructDecl(OutputModelFactory factory, Rule r, String name) {\n\t\tsuper(factory, name == null ? factory.getGenerator().getTarget().getRuleFunctionContextStructName(r) : name);\n\t\taddDispatchMethods(r);\n\t\tderivedFromName = r.name;\n\t\tprovideCopyFrom = r.hasAltSpecificContexts();\n\t}\n\n\tpublic void addDispatchMethods(Rule r) {\n\t\tdispatchMethods = new ArrayList<DispatchMethod>();\n\t\tif ( !r.hasAltSpecificContexts() ) {\n\t\t\t// no enter/exit for this ruleContext if rule has labels\n\t\t\tif ( factory.getGrammar().tool.gen_listener ) {\n\t\t\t\tdispatchMethods.add(new ListenerDispatchMethod(factory, true));\n\t\t\t\tdispatchMethods.add(new ListenerDispatchMethod(factory, false));\n\t\t\t}\n\t\t\tif ( factory.getGrammar().tool.gen_visitor ) {\n\t\t\t\tdispatchMethods.add(new VisitorDispatchMethod(factory));\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void addDecl(Decl d) {\n\t\td.ctx = this;\n\n\t\tif ( d instanceof ContextGetterDecl ) {\n\t\t\tgetters.add(d);\n\t\t\tsignatures.add(((ContextGetterDecl) d).getSignatureDecl());\n\t\t} else {\n\t\t\tattrs.add(d);\n\t\t}\n\t\t// add to specific \"lists\"\n\t\tif ( d instanceof TokenTypeDecl ) {\n\t\t\ttokenTypeDecls.add(d);\n\t\t}\n\t\telse if ( d instanceof TokenListDecl ) {\n\t\t\ttokenListDecls.add(d);\n\t\t}\n\t\telse if ( d instanceof TokenDecl ) {\n\t\t\ttokenDecls.add(d);\n\t\t}\n\t\telse if ( d instanceof RuleContextListDecl ) {\n\t\t\truleContextListDecls.add(d);\n\t\t}\n\t\telse if ( d instanceof RuleContextDecl ) {\n\t\t\truleContextDecls.add(d);\n\t\t}\n\t\telse if ( d instanceof AttributeDecl ) {\n\t\t\tattributeDecls.add(d);\n\t\t}\n\t}\n\n\tpublic void addDecl(Attribute a) {\n\t\taddDecl(new AttributeDecl(factory, a));\n\t}\n\n\tpublic void addDecls(Collection<Attribute> attrList) {\n\t\tfor (Attribute a : attrList) addDecl(a);\n\t}\n\n\tpublic void implementInterface(OutputModelObject value) {\n\t\tif (interfaces == null) {\n\t\t\tinterfaces = new ArrayList<OutputModelObject>();\n\t\t}\n\n\t\tinterfaces.add(value);\n\t}\n\n\tpublic void addExtensionMember(OutputModelObject member) {\n\t\tif (extensionMembers == null) {\n\t\t\textensionMembers = new ArrayList<OutputModelObject>();\n\t\t}\n\n\t\textensionMembers.add(member);\n\t}\n\n\tpublic boolean isEmpty() { return attrs.isEmpty(); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/TokenDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** x=ID or implicit _tID label */\npublic class TokenDecl extends Decl {\n\tpublic boolean isImplicit;\n\n\tpublic TokenDecl(OutputModelFactory factory, String varName) {\n\t\tsuper(factory, varName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/TokenListDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** */\npublic class TokenListDecl extends TokenDecl {\n\tpublic TokenListDecl(OutputModelFactory factory, String varName) {\n\t\tsuper(factory, varName);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/model/decl/TokenTypeDecl.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.model.decl;\n\nimport org.antlr.v4.codegen.OutputModelFactory;\n\n/** */\npublic class TokenTypeDecl extends Decl {\n\tpublic TokenTypeDecl(OutputModelFactory factory, String name) {\n\t\tsuper(factory, name);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/CSharpTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.tool.ErrorType;\nimport org.stringtemplate.v4.NumberRenderer;\nimport org.stringtemplate.v4.STErrorListener;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STGroupFile;\nimport org.stringtemplate.v4.StringRenderer;\nimport org.stringtemplate.v4.misc.STMessage;\n\nimport java.util.*;\n\npublic class CSharpTarget extends Target {\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\"abstract\",\n\t\t\"as\",\n\t\t\"base\",\n\t\t\"bool\",\n\t\t\"break\",\n\t\t\"byte\",\n\t\t\"case\",\n\t\t\"catch\",\n\t\t\"char\",\n\t\t\"checked\",\n\t\t\"class\",\n\t\t\"const\",\n\t\t\"continue\",\n\t\t\"decimal\",\n\t\t\"default\",\n\t\t\"delegate\",\n\t\t\"do\",\n\t\t\"double\",\n\t\t\"else\",\n\t\t\"enum\",\n\t\t\"event\",\n\t\t\"explicit\",\n\t\t\"extern\",\n\t\t\"false\",\n\t\t\"finally\",\n\t\t\"fixed\",\n\t\t\"float\",\n\t\t\"for\",\n\t\t\"foreach\",\n\t\t\"goto\",\n\t\t\"if\",\n\t\t\"implicit\",\n\t\t\"in\",\n\t\t\"int\",\n\t\t\"interface\",\n\t\t\"internal\",\n\t\t\"is\",\n\t\t\"lock\",\n\t\t\"long\",\n\t\t\"namespace\",\n\t\t\"new\",\n\t\t\"null\",\n\t\t\"object\",\n\t\t\"operator\",\n\t\t\"out\",\n\t\t\"override\",\n\t\t\"params\",\n\t\t\"private\",\n\t\t\"protected\",\n\t\t\"public\",\n\t\t\"readonly\",\n\t\t\"ref\",\n\t\t\"return\",\n\t\t\"sbyte\",\n\t\t\"sealed\",\n\t\t\"short\",\n\t\t\"sizeof\",\n\t\t\"stackalloc\",\n\t\t\"static\",\n\t\t\"string\",\n\t\t\"struct\",\n\t\t\"switch\",\n\t\t\"this\",\n\t\t\"throw\",\n\t\t\"true\",\n\t\t\"try\",\n\t\t\"typeof\",\n\t\t\"uint\",\n\t\t\"ulong\",\n\t\t\"unchecked\",\n\t\t\"unsafe\",\n\t\t\"ushort\",\n\t\t\"using\",\n\t\t\"virtual\",\n\t\t\"values\",\n\t\t\"void\",\n\t\t\"volatile\",\n\t\t\"while\"\n\t));\n\n\tprotected static final Map<Character, String> targetCharValueEscape;\n\tstatic {\n\t\t// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-escape-sequences\n\t\tHashMap<Character, String> map = new HashMap<>();\n\t\taddEscapedChar(map, '\\'');\n\t\taddEscapedChar(map, '\\\"');\n\t\taddEscapedChar(map, '\\\\');\n\t\taddEscapedChar(map, '\\0', '0');\n\t\taddEscapedChar(map, (char)0x0007, 'a');\n\t\taddEscapedChar(map, (char)0x0008, 'b');\n\t\taddEscapedChar(map, '\\f', 'f');\n\t\taddEscapedChar(map, '\\n', 'n');\n\t\taddEscapedChar(map, '\\r', 'r');\n\t\taddEscapedChar(map, '\\t', 't');\n\t\taddEscapedChar(map, (char)0x000B, 'v');\n\t\ttargetCharValueEscape = map;\n\t}\n\n\tpublic CSharpTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tpublic Map<Character, String> getTargetCharValueEscape() {\n\t\treturn targetCharValueEscape;\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tprotected String escapeWord(String word) {\n\t\treturn \"@\" + word;\n\t}\n\n\t@Override\n\tpublic boolean isATNSerializedAsInts() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected String escapeChar(int v) {\n\t\treturn String.format(\"\\\\x%X\", v);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/CppTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.SourceType;\nimport org.antlr.v4.codegen.Target;\nimport org.stringtemplate.v4.ST;\nimport java.util.*;\n\npublic class CppTarget extends Target {\n\tprotected static final Map<Character, String> targetCharValueEscape;\n\tstatic {\n\t\t// https://stackoverflow.com/a/10220539/1046374\n\t\tHashMap<Character, String> map = new HashMap<>();\n\t\taddEscapedChar(map, (char)0x0007, 'a');\n\t\taddEscapedChar(map, (char)0x0008, 'b');\n\t\taddEscapedChar(map, '\\t', 't');\n\t\taddEscapedChar(map, '\\n', 'n');\n\t\taddEscapedChar(map, (char)0x000B, 'v');\n\t\taddEscapedChar(map, '\\f', 'f');\n\t\taddEscapedChar(map, '\\r', 'r');\n\t\taddEscapedChar(map, (char)0x001B, 'e');\n\t\taddEscapedChar(map, '\\\"');\n\t\taddEscapedChar(map, '\\'');\n\t\taddEscapedChar(map, '?');\n\t\taddEscapedChar(map, '\\\\');\n\t\ttargetCharValueEscape = map;\n\t}\n\n\tprotected static final HashSet<String> reservedWords =  new HashSet<>(Arrays.asList(\n\t\t\"alignas\", \"alignof\", \"and\", \"and_eq\", \"asm\", \"auto\", \"bitand\",\n\t\t\"bitor\", \"bool\", \"break\", \"case\", \"catch\", \"char\", \"char16_t\",\n\t\t\"char32_t\", \"class\", \"compl\", \"concept\", \"const\", \"constexpr\",\n\t\t\"const_cast\", \"continue\", \"decltype\", \"default\", \"delete\", \"do\",\n\t\t\"double\", \"dynamic_cast\", \"else\", \"enum\", \"explicit\", \"export\",\n\t\t\"extern\", \"false\", \"float\", \"for\", \"friend\", \"goto\", \"if\",\n\t\t\"inline\", \"int\", \"long\", \"mutable\", \"namespace\", \"new\",\n\t\t\"noexcept\", \"not\", \"not_eq\", \"nullptr\", \"NULL\", \"operator\", \"or\",\n\t\t\"or_eq\", \"private\", \"protected\", \"public\", \"register\",\n\t\t\"reinterpret_cast\", \"requires\", \"return\", \"short\", \"signed\",\n\t\t\"sizeof\", \"static\", \"static_assert\", \"static_cast\", \"struct\",\n\t\t\"switch\", \"template\", \"this\", \"thread_local\", \"throw\", \"true\",\n\t\t\"try\", \"typedef\", \"typeid\", \"typename\", \"union\", \"unsigned\",\n\t\t\"using\", \"virtual\", \"void\", \"volatile\", \"wchar_t\", \"while\",\n\t\t\"xor\", \"xor_eq\",\n\n\t\t\"rule\", \"parserRule\", \"reset\"\n\t));\n\n\tpublic CppTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tpublic Map<Character, String> getTargetCharValueEscape() {\n\t\treturn targetCharValueEscape;\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\tpublic boolean needsHeader() { return true; }\n\n    @Override\n\tprotected boolean shouldUseUnicodeEscapeForCodePointInDoubleQuotedString(int codePoint) {\n\t\tif (codePoint == '?') {\n\t\t\t// in addition to the default escaped code points, also escape ? to prevent trigraphs\n\t\t\t// ideally, we would escape ? with \\?, but escaping as unicode \\u003F works as well\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn super.shouldUseUnicodeEscapeForCodePointInDoubleQuotedString(codePoint);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getRecognizerFileName(SourceType sourceType) {\n\t\tST extST = getTemplates().getInstanceOf(sourceType== SourceType.HEADER ? \"headerFileExtension\" : \"codeFileExtension\");\n\t\tString recognizerName = gen.g.getRecognizerName();\n\t\treturn recognizerName+extST.render();\n\t}\n\n\t@Override\n\tpublic String getListenerFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(sourceType== SourceType.HEADER ? \"headerFileExtension\" : \"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"Listener\";\n\t\treturn listenerName+extST.render();\n\t}\n\n\t@Override\n\tpublic String getVisitorFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(sourceType== SourceType.HEADER ? \"headerFileExtension\" : \"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"Visitor\";\n\t\treturn listenerName+extST.render();\n\t}\n\n\t@Override\n\tpublic String getBaseListenerFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(sourceType== SourceType.HEADER ? \"headerFileExtension\" : \"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"BaseListener\";\n\t\treturn listenerName+extST.render();\n\t}\n\n\t@Override\n\tpublic String getBaseVisitorFileName(SourceType sourceType) {\n\t\tassert gen.g.name != null;\n\t\tST extST = getTemplates().getInstanceOf(sourceType== SourceType.HEADER ? \"headerFileExtension\" : \"codeFileExtension\");\n\t\tString listenerName = gen.g.name + \"BaseVisitor\";\n\t\treturn listenerName+extST.render();\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/DartTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.Target;\n\nimport java.util.*;\n\npublic class DartTarget extends Target {\n\tprotected static final Map<Character, String> targetCharValueEscape;\n\tstatic {\n\t\tHashMap<Character, String> map = new HashMap<>(defaultCharValueEscape);\n\t\taddEscapedChar(map, '$');\n\t\ttargetCharValueEscape = map;\n\t}\n\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\"abstract\", \"dynamic\", \"implements\", \"show\",\n\t\t\"as\", \"else\", \"import\", \"static\",\n\t\t\"assert\", \"enum\", \"in\", \"super\",\n\t\t\"async\", \"export\", \"interface\", \"switch\",\n\t\t\"await\", \"extends\", \"is\", \"sync\",\n\t\t\"break\", \"external\", \"library\", \"this\",\n\t\t\"case\", \"factory\", \"mixin\", \"throw\",\n\t\t\"catch\", \"false\", \"new\", \"true\",\n\t\t\"class\", \"final\", \"null\", \"try\",\n\t\t\"const\", \"finally\", \"on\", \"typedef\",\n\t\t\"continue\", \"for\", \"operator\", \"var\",\n\t\t\"covariant\", \"Function\", \"part\", \"void\",\n\t\t\"default\", \"get\", \"rethrow\", \"while\",\n\t\t\"deferred\", \"hide\", \"return\", \"with\",\n\t\t\"do\", \"if\", \"set\", \"yield\",\n\n\t\t\"rule\", \"parserRule\",\n\t\t\"interpreter\", \"state\", \"ruleNames\", \"vocabulary\", \"ruleIndexMap\", \"getTokenType\", \"grammarFileName\", \"getATN\",\n\t\t\"parseInfo\", \"getErrorHeader\", \"addErrorListener\", \"removeErrorListener\",  \"removeErrorListeners\",\"errorListeners\",\n\t\t\"errorListenerDispatch\", \"sempred\", \"precpred\", \"action\", \"inputStream\", \"tokenFactory\",\n\n\t\t\"errorHandler\", \"context\", \"buildParseTree\", \"matchedEOF\", \"reset\", \"match\", \"matchWildcard\", \"trimParseTree\",\n\t\t\"addParseListener\", \"removeParseListener\", \"removeParseListeners\", \"triggerEnterRuleEvent\", \"triggerExitRuleEvent\",\n\t\t\"numberOfSyntaxErrors\", \"currentToken\", \"notifyErrorListeners\", \"consume\", \"createTerminalNode\", \"createErrorNode\",\n\t\t\"addContextToParseTree\", \"enterRule\", \"exitRule\", \"enterOuterAlt\", \"precedence\", \"enterRecursionRule\"\n\t));\n\n\tpublic DartTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tpublic Map<Character, String> getTargetCharValueEscape() {\n\t\treturn targetCharValueEscape;\n\t}\n\n\t@Override\n\tpublic String getTargetStringLiteralFromANTLRStringLiteral(CodeGenerator generator, String literal, boolean addQuotes,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   boolean escapeSpecial) {\n\t\treturn super.getTargetStringLiteralFromANTLRStringLiteral(generator, literal, addQuotes, escapeSpecial).replace(\"$\", \"\\\\$\");\n\t}\n\n\tpublic Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tpublic boolean isATNSerializedAsInts() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected String escapeChar(int v) {\n\t\treturn String.format(\"\\\\u{%X}\", v);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/GoTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.SourceType;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.tool.Grammar;\nimport org.stringtemplate.v4.ST;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class GoTarget extends Target {\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t// keywords\n\t\t\"break\", \"default\", \"func\", \"interface\", \"select\",\n\t\t\"case\", \"defer\", \"go\", \"map\", \"struct\",\n\t\t\"chan\", \"else\", \"goto\", \"package\", \"switch\",\n\t\t\"const\", \"fallthrough\", \"if\", \"range\", \"type\",\n\t\t\"continue\", \"for\", \"import\", \"return\", \"var\",\n\n\t\t// predeclared identifiers https://golang.org/ref/spec#Predeclared_identifiers\n\t\t\"bool\", \"byte\", \"complex64\", \"complex128\", \"error\", \"float32\", \"float64\",\n\t\t\"int\", \"int8\", \"int16\", \"int32\", \"int64\", \"rune\", \"string\",\n\t\t\"uint\", \"uint8\", \"uint16\", \"uint32\", \"uint64\", \"uintptr\",\n\t\t\"true\", \"false\", \"iota\", \"nil\",\n\t\t\"append\", \"cap\", \"close\", \"complex\", \"copy\", \"delete\", \"imag\", \"len\",\n\t\t\"make\", \"new\", \"panic\", \"print\", \"println\", \"real\", \"recover\",\n\t\t\"string\",\n\n\t\t// interface definition of RuleContext from runtime/Go/antlr/rule_context.go\n\t\t\"Accept\", \"GetAltNumber\", \"GetBaseRuleContext\", \"GetChild\", \"GetChildCount\",\n\t\t\"GetChildren\", \"GetInvokingState\", \"GetParent\", \"GetPayload\", \"GetRuleContext\",\n\t\t\"GetRuleIndex\", \"GetSourceInterval\", \"GetText\", \"IsEmpty\", \"SetAltNumber\",\n\t\t\"SetInvokingState\", \"SetParent\", \"String\",\n\n\t\t// misc\n\t\t\"rule\", \"parserRule\", \"action\",\n\n\t\t// the use of start or stop abd others as a label name will cause the generation of a GetStart() or GetStop() method, which\n\t\t// then clashes with the GetStart() or GetStop() method that is generated by the code gen for the rule. So, we need to\n\t\t// convert it. This is not ideal as it will still probably confuse authors of parse listeners etc. but the code will\n\t\t// compile. This is a proof of Hyrum's law.\n\t\t\"start\", \"stop\", \"exception\",\n\t\t\"sempred\", \"precpred\", \"addErrorListener\"\n\t));\n\n\tprivate static final boolean DO_GOFMT = !Boolean.parseBoolean(System.getenv(\"ANTLR_GO_DISABLE_GOFMT\"))\n\t\t\t&& !Boolean.parseBoolean(System.getProperty(\"antlr.go.disable-gofmt\"));\n\n\tpublic GoTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tprotected void genFile(Grammar g, ST outputFileST, String fileName) {\n\t\tsuper.genFile(g, outputFileST, fileName);\n\t\tif (DO_GOFMT && !fileName.startsWith(\".\") /* criterion taken from gofmt */ && fileName.endsWith(\".go\")) {\n\t\t\tgofmt(new File(getCodeGenerator().tool.getOutputDirectory(g.fileName), fileName));\n\t\t}\n\t}\n\n\tprivate void gofmt(File fileName) {\n\t\t// Optimistically run gofmt. If this fails, it doesn't matter at this point. Wait for termination though,\n\t\t// because \"gofmt -w\" uses ioutil.WriteFile internally, which means it literally writes in-place with O_TRUNC.\n\t\t// That could result in a race. (Why oh why doesn't it do tmpfile + rename?)\n\t\ttry {\n\t\t\t// TODO: need something like: String goExecutable = locateGo();\n\t\t\tProcessBuilder gofmtBuilder = new ProcessBuilder(\"gofmt\", \"-w\", \"-s\", fileName.getPath());\n\t\t\tgofmtBuilder.redirectErrorStream(true);\n\t\t\tProcess gofmt = gofmtBuilder.start();\n\t\t\tInputStream stdout = gofmt.getInputStream();\n\t\t\t// TODO(wjkohnen): simplify to `while (stdout.Read() > 1) {}`\n\t\t\tbyte[] buf = new byte[1 << 10];\n\t\t\tfor (int l = 0; l > -1; l = stdout.read(buf)) {\n\t\t\t\t// There should not be any output that exceeds the implicit output buffer. In normal ops there should be\n\t\t\t\t// zero output. In case there is output, blocking and therefore killing the process is acceptable. This\n\t\t\t\t// drains the buffer anyway to play it safe.\n\n\t\t\t\t// dirty debug (change -w above to -d):\n\t\t\t\t// System.err.write(buf, 0, l);\n\t\t\t}\n\t\t\tgofmt.waitFor();\n\t\t} catch (IOException e) {\n\t\t\t// Probably gofmt not in $PATH, in any case ignore.\n\t\t} catch (InterruptedException forward) {\n\t\t\tThread.currentThread().interrupt();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getRecognizerFileName(SourceType sourceType) {\n\t\tCodeGenerator gen = getCodeGenerator();\n\t\tGrammar g = gen.g;\n\t\tassert g!=null;\n\t\tString name;\n\t\tswitch ( g.getType()) {\n\t\t\tcase ANTLRParser.PARSER:\n\t\t\t\tname = g.name.endsWith(\"Parser\") ? g.name.substring(0, g.name.length()-6) : g.name;\n\t\t\t\treturn name.toLowerCase()+\"_parser.go\";\n\t\t\tcase ANTLRParser.LEXER:\n\t\t\t\tname = g.name.endsWith(\"Lexer\") ? g.name.substring(0, g.name.length()-5) : g.name; // trim off \"lexer\"\n\t\t\t\treturn name.toLowerCase()+\"_lexer.go\";\n\t\t\tcase ANTLRParser.COMBINED:\n\t\t\t\treturn g.name.toLowerCase()+\"_parser.go\";\n\t\t\tdefault :\n\t\t\t\treturn \"INVALID_FILE_NAME\";\n\t\t}\n\t}\n\n\t/** A given grammar T, return the listener name such as\n\t *  TListener.java, if we're using the Java target.\n \t */\n\t@Override\n\tpublic String getListenerFileName(SourceType sourceType) {\n\t\tCodeGenerator gen = getCodeGenerator();\n\t\tGrammar g = gen.g;\n\t\tassert g.name != null;\n\t\treturn g.name.toLowerCase()+\"_listener.go\";\n\t}\n\n\t/** A given grammar T, return the visitor name such as\n\t *  TVisitor.java, if we're using the Java target.\n \t */\n\t@Override\n\tpublic String getVisitorFileName(SourceType sourceType) {\n\t\tCodeGenerator gen = getCodeGenerator();\n\t\tGrammar g = gen.g;\n\t\tassert g.name != null;\n\t\treturn g.name.toLowerCase()+\"_visitor.go\";\n\t}\n\n\t/** A given grammar T, return a blank listener implementation\n\t *  such as TBaseListener.java, if we're using the Java target.\n \t */\n\t@Override\n\tpublic String getBaseListenerFileName(SourceType sourceType) {\n\t\tCodeGenerator gen = getCodeGenerator();\n\t\tGrammar g = gen.g;\n\t\tassert g.name != null;\n\t\treturn g.name.toLowerCase()+\"_base_listener.go\";\n\t}\n\n\t/** A given grammar T, return a blank listener implementation\n\t *  such as TBaseListener.java, if we're using the Java target.\n \t */\n\t@Override\n\tpublic String getBaseVisitorFileName(SourceType sourceType) {\n\t\tCodeGenerator gen = getCodeGenerator();\n\t\tGrammar g = gen.g;\n\t\tassert g.name != null;\n\t\treturn g.name.toLowerCase()+\"_base_visitor.go\";\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/JavaScriptTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.Target;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class JavaScriptTarget extends Target {\n\t/** Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar */\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\"break\", \"case\", \"class\", \"catch\", \"const\", \"continue\", \"debugger\",\n\t\t\"default\", \"delete\", \"do\", \"else\", \"export\", \"extends\", \"finally\", \"for\",\n\t\t\"function\", \"if\", \"import\", \"in\", \"instanceof\", \"let\", \"new\", \"return\",\n\t\t\"super\", \"switch\", \"this\", \"throw\", \"try\", \"typeof\", \"var\", \"void\",\n\t\t\"while\", \"with\", \"yield\",\n\n\t\t//future reserved\n\t\t\"enum\", \"await\", \"implements\", \"package\", \"protected\", \"static\",\n\t\t\"interface\", \"private\", \"public\",\n\n\t\t//future reserved in older standards\n\t\t\"abstract\", \"boolean\", \"byte\", \"char\", \"double\", \"final\", \"float\",\n\t\t\"goto\", \"int\", \"long\", \"native\", \"short\", \"synchronized\", \"transient\",\n\t\t\"volatile\",\n\n\t\t//literals\n\t\t\"null\", \"true\", \"false\",\n\n\t\t// misc\n\t\t\"rule\", \"parserRule\",\n\t\t\"state\", \"reset\"\n\t));\n\n\tpublic JavaScriptTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tpublic int getInlineTestSetWordSize() {\n\t\treturn 32;\n\t}\n\n\t@Override\n\tpublic boolean wantsBaseListener() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean wantsBaseVisitor() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean supportsOverloadedMethods() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isATNSerializedAsInts() {\n\t\treturn true;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/JavaTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.SourceType;\nimport org.antlr.v4.codegen.Target;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class JavaTarget extends Target {\n\t/**\n\t * The Java target can cache the code generation templates.\n\t */\n\tprivate static final ThreadLocal<STGroup> targetTemplates = new ThreadLocal<STGroup>();\n\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\"abstract\", \"assert\", \"boolean\", \"break\", \"byte\", \"case\", \"catch\",\n\t\t\"char\", \"class\", \"const\", \"continue\", \"default\", \"do\", \"double\", \"else\",\n\t\t\"enum\", \"extends\", \"false\", \"final\", \"finally\", \"float\", \"for\", \"goto\",\n\t\t\"if\", \"implements\", \"import\", \"instanceof\", \"int\", \"interface\",\n\t\t\"long\", \"native\", \"new\", \"null\", \"package\", \"private\", \"protected\",\n\t\t\"public\", \"return\", \"short\", \"static\", \"strictfp\", \"super\", \"switch\",\n\t\t\"synchronized\", \"this\", \"throw\", \"throws\", \"transient\", \"true\", \"try\",\n\t\t\"void\", \"volatile\", \"while\",\n\n\t\t// misc\n\t\t\"rule\", \"parserRule\", \"reset\"\n\t));\n\n\tpublic JavaTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n    public Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tpublic int getSerializedATNSegmentLimit() {\n\t\t// 65535 is the class file format byte limit for a UTF-8 encoded string literal\n\t\t// 3 is the maximum number of bytes it takes to encode a value in the range 0-0xFFFF\n\t\treturn 65535 / 3;\n\t}\n\n\t@Override\n\tpublic boolean isATNSerializedAsInts() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean supportsSplitParser() { return true; }\n\n\t@Override\n\tpublic String getRecognizerFileName(SourceType sourceType) {\n\t\tST extST = getTemplates().getInstanceOf(\"codeFileExtension\");\n\t\tString recognizerName = gen.g.getRecognizerName();\n\t\tif (sourceType == SourceType.SOURCE_CONTEXTS)\n\t\t\trecognizerName += \"Contexts\";\n\t\telse if (sourceType == SourceType.SOURCE_DFA)\n\t\t\trecognizerName += \"DFA\";\n\t\treturn recognizerName + extST.render();\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/PHPTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.Target;\n\nimport java.util.*;\n\npublic class PHPTarget extends Target {\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\"abstract\", \"and\", \"array\", \"as\",\n\t\t\"break\",\n\t\t\"callable\", \"case\", \"catch\", \"class\", \"clone\", \"const\", \"continue\",\n\t\t\"declare\", \"default\", \"die\", \"do\",\n\t\t\"echo\", \"else\", \"elseif\", \"empty\", \"enddeclare\", \"endfor\", \"endforeach\",\n\t\t\"endif\", \"endswitch\", \"endwhile\", \"eval\", \"exit\", \"extends\",\n\t\t\"final\", \"finally\", \"for\", \"foreach\", \"function\",\n\t\t\"global\", \"goto\",\n\t\t\"if\", \"implements\", \"include\", \"include_once\", \"instanceof\", \"insteadof\", \"interface\", \"isset\",\n\t\t\"list\",\n\t\t\"namespace\", \"new\",\n\t\t\"or\",\n\t\t\"print\", \"private\", \"protected\", \"public\",\n\t\t\"require\", \"require_once\", \"return\",\n\t\t\"static\", \"switch\",\n\t\t\"throw\", \"trait\", \"try\",\n\t\t\"unset\", \"use\",\n\t\t\"var\",\n\t\t\"while\",\n\t\t\"xor\",\n\t\t\"yield\",\n\t\t\"__halt_compiler\", \"__CLASS__\", \"__DIR__\", \"__FILE__\", \"__FUNCTION__\",\n\t\t\"__LINE__\", \"__METHOD__\", \"__NAMESPACE__\", \"__TRAIT__\",\n\n\t\t// misc\n\t\t\"rule\", \"parserRule\",\n\t\t\"state\", \"reset\", \"action\", \"sempred\", \"addErrorListener\"\n\t));\n\n\tprotected static final Map<Character, String> targetCharValueEscape;\n\tstatic {\n\t\t// https://www.php.net/manual/en/language.types.string.php\n\t\tHashMap<Character, String> map = new HashMap<>();\n\t\taddEscapedChar(map, '\\n', 'n');\n\t\taddEscapedChar(map, '\\r', 'r');\n\t\taddEscapedChar(map, '\\t', 't');\n\t\taddEscapedChar(map, (char)0x000B, 'v');\n\t\taddEscapedChar(map, (char)0x001B, 'e');\n\t\taddEscapedChar(map, '\\f', 'f');\n\t\taddEscapedChar(map, '\\\\');\n\t\taddEscapedChar(map, '$');\n\t\taddEscapedChar(map, '\\\"');\n\t\ttargetCharValueEscape = map;\n\t}\n\n\tpublic PHPTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tpublic Map<Character, String> getTargetCharValueEscape() {\n\t\treturn targetCharValueEscape;\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tpublic boolean supportsOverloadedMethods() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String getTargetStringLiteralFromANTLRStringLiteral(CodeGenerator generator, String literal, boolean addQuotes,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   boolean escapeSpecial) {\n\t\tString targetStringLiteral = super.getTargetStringLiteralFromANTLRStringLiteral(generator, literal, addQuotes, escapeSpecial);\n\t\ttargetStringLiteral = targetStringLiteral.replace(\"$\", \"\\\\$\");\n\t\treturn targetStringLiteral;\n\t}\n\n\t@Override\n\tpublic boolean isATNSerializedAsInts() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected String escapeChar(int v) {\n\t\treturn String.format(\"\\\\u{%X}\", v);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/Python3Target.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.Target;\n\nimport java.util.*;\n\npublic class Python3Target extends Target {\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\"abs\", \"all\", \"and\", \"any\", \"apply\", \"as\", \"assert\",\n\t\t\"bin\", \"bool\", \"break\", \"buffer\", \"bytearray\",\n\t\t\"callable\", \"chr\", \"class\", \"classmethod\", \"coerce\", \"compile\", \"complex\", \"continue\",\n\t\t\"def\", \"del\", \"delattr\", \"dict\", \"dir\", \"divmod\",\n\t\t\"elif\", \"else\", \"enumerate\", \"eval\", \"execfile\", \"except\",\n\t\t\"file\", \"filter\", \"finally\", \"float\", \"for\", \"format\", \"from\", \"frozenset\",\n\t\t\"getattr\", \"global\", \"globals\",\n\t\t\"hasattr\", \"hash\", \"help\", \"hex\",\n\t\t\"id\", \"if\", \"import\", \"in\", \"input\", \"int\", \"intern\", \"is\", \"isinstance\", \"issubclass\", \"iter\",\n\t\t\"lambda\", \"len\", \"list\", \"locals\",\n\t\t\"map\", \"max\", \"min\", \"memoryview\",\n\t\t\"next\", \"nonlocal\", \"not\",\n\t\t\"object\", \"oct\", \"open\", \"or\", \"ord\",\n\t\t\"pass\", \"pow\", \"print\", \"property\",\n\t\t\"raise\", \"range\", \"raw_input\", \"reduce\", \"reload\", \"repr\", \"return\", \"reversed\", \"round\",\n\t\t\"set\", \"setattr\", \"slice\", \"sorted\", \"staticmethod\", \"str\", \"sum\", \"super\",\n\t\t\"try\", \"tuple\", \"type\",\n\t\t\"unichr\", \"unicode\",\n\t\t\"vars\",\n\t\t\"with\", \"while\",\n\t\t\"yield\",\n\t\t\"zip\",\n\t\t\"__import__\",\n\t\t\"True\", \"False\", \"None\",\n\n\t\t// misc\n\t\t\"rule\", \"parserRule\",\n\t\t\"state\", \"reset\"\n\t));\n\n\tprotected static final Map<Character, String> targetCharValueEscape;\n\tstatic {\n\t\t// https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals\n\t\tHashMap<Character, String> map = new HashMap<>();\n\t\taddEscapedChar(map, '\\\\');\n\t\taddEscapedChar(map, '\\'');\n\t\taddEscapedChar(map, '\\\"');\n\t\taddEscapedChar(map, (char)0x0007, 'a');\n\t\taddEscapedChar(map, (char)0x0008, 'b');\n\t\taddEscapedChar(map, '\\f', 'f');\n\t\taddEscapedChar(map, '\\n', 'n');\n\t\taddEscapedChar(map, '\\r', 'r');\n\t\taddEscapedChar(map, '\\t', 't');\n\t\taddEscapedChar(map, (char)0x000B, 'v');\n\t\ttargetCharValueEscape = map;\n\t}\n\n\tpublic Python3Target(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tpublic Map<Character, String> getTargetCharValueEscape() {\n\t\treturn targetCharValueEscape;\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tpublic boolean wantsBaseListener() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean wantsBaseVisitor() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean supportsOverloadedMethods() {\n\t\treturn false;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/SwiftTarget.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.Target;\nimport org.antlr.v4.tool.Grammar;\nimport org.stringtemplate.v4.ST;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class SwiftTarget extends Target {\n\tprotected static final Map<Character, String> targetCharValueEscape;\n\n\tstatic {\n\t\t// https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html\n\t\tHashMap<Character, String> map = new HashMap<>();\n\t\taddEscapedChar(map, '\\0', '0');\n\t\taddEscapedChar(map, '\\\\');\n\t\taddEscapedChar(map, '\\t', 't');\n\t\taddEscapedChar(map, '\\n', 'n');\n\t\taddEscapedChar(map, '\\r', 'r');\n\t\taddEscapedChar(map, '\\\"');\n\t\taddEscapedChar(map, '\\'');\n\t\ttargetCharValueEscape = map;\n\t}\n\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\"associatedtype\", \"class\", \"deinit\", \"enum\", \"extension\", \"func\", \"import\", \"init\", \"inout\", \"internal\",\n\t\t\"let\", \"operator\", \"private\", \"protocol\", \"public\", \"static\", \"struct\", \"subscript\", \"typealias\", \"var\",\n\t\t\"break\", \"case\", \"continue\", \"default\", \"defer\", \"do\", \"else\", \"fallthrough\", \"for\", \"guard\", \"if\",\n\t\t\"in\", \"repeat\", \"return\", \"switch\", \"where\", \"while\",\n\t\t\"as\", \"catch\", \"dynamicType\", \"false\", \"is\", \"nil\", \"rethrows\", \"super\", \"self\", \"Self\", \"throw\", \"throws\",\n\t\t\"true\", \"try\", \"__COLUMN__\", \"__FILE__\", \"__FUNCTION__\", \"__LINE__\", \"#column\", \"#file\", \"#function\", \"#line\", \"_\", \"#available\", \"#else\", \"#elseif\", \"#endif\", \"#if\", \"#selector\",\n\t\t\"associativity\", \"convenience\", \"dynamic\", \"didSet\", \"final\", \"get\", \"infix\", \"indirect\", \"lazy\",\n\t\t\"left\", \"mutating\", \"none\", \"nonmutating\", \"optional\", \"override\", \"postfix\", \"precedence\",\n\t\t\"prefix\", \"Protocol\", \"required\", \"right\", \"set\", \"Type\", \"unowned\", \"weak\", \"willSet\",\n\n\t\t\"rule\", \"parserRule\"\n\t));\n\n\tpublic SwiftTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tpublic Map<Character, String> getTargetCharValueEscape() {\n\t\treturn targetCharValueEscape;\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tprotected String escapeWord(String word) {\n\t\treturn \"`\" + word + \"`\";\n\t}\n\n\t@Override\n\tprotected String escapeChar(int v) {\n\t\treturn String.format(\"\\\\u{%X}\", v);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/codegen/target/TypeScriptTarget.java",
    "content": "/*\n * Copyright 20162022 The ANTLR Project. All rights reserved.\n * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.\n */\npackage org.antlr.v4.codegen.target;\n\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.Target;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class TypeScriptTarget extends Target {\n\n\t/* source: https://github.com/microsoft/TypeScript/blob/fad889283e710ee947e8412e173d2c050107a3c1/src/compiler/scanner.ts */\n\tprotected static final HashSet<String> reservedWords = new HashSet<>(Arrays.asList(\n\t\t\t\"any\",\n\t\t\t\"as\",\n\t\t\t\"boolean\",\n\t\t\t\"break\",\n\t\t\t\"case\",\n\t\t\t\"catch\",\n\t\t\t\"class\",\n\t\t\t\"continue\",\n\t\t\t\"const\",\n\t\t\t\"constructor\",\n\t\t\t\"debugger\",\n\t\t\t\"declare\",\n\t\t\t\"default\",\n\t\t\t\"delete\",\n\t\t\t\"do\",\n\t\t\t\"else\",\n\t\t\t\"enum\",\n\t\t\t\"export\",\n\t\t\t\"extends\",\n\t\t\t\"false\",\n\t\t\t\"finally\",\n\t\t\t\"for\",\n\t\t\t\"from\",\n\t\t\t\"function\",\n\t\t\t\"get\",\n\t\t\t\"if\",\n\t\t\t\"implements\",\n\t\t\t\"import\",\n\t\t\t\"in\",\n\t\t\t\"instanceof\",\n\t\t\t\"interface\",\n\t\t\t\"let\",\n\t\t\t\"module\",\n\t\t\t\"new\",\n\t\t\t\"null\",\n\t\t\t\"number\",\n\t\t\t\"package\",\n\t\t\t\"private\",\n\t\t\t\"protected\",\n\t\t\t\"public\",\n\t\t\t\"require\",\n\t\t\t\"return\",\n\t\t\t\"set\",\n\t\t\t\"static\",\n\t\t\t\"string\",\n\t\t\t\"super\",\n\t\t\t\"switch\",\n\t\t\t\"symbol\",\n\t\t\t\"this\",\n\t\t\t\"throw\",\n\t\t\t\"true\",\n\t\t\t\"try\",\n\t\t\t\"type\",\n\t\t\t\"typeof\",\n\t\t\t\"var\",\n\t\t\t\"void\",\n\t\t\t\"while\",\n\t\t\t\"with\",\n\t\t\t\"yield\",\n\t\t\t\"of\",\n\t\t    \"state\", \"reset\"\n\t));\n\n\tpublic TypeScriptTarget(CodeGenerator gen) {\n\t\tsuper(gen);\n\t}\n\n\t@Override\n\tprotected Set<String> getReservedWords() {\n\t\treturn reservedWords;\n\t}\n\n\t@Override\n\tpublic int getInlineTestSetWordSize() {\n\t\treturn 32;\n\t}\n\n\t@Override\n\tpublic boolean wantsBaseListener() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean wantsBaseVisitor() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean supportsOverloadedMethods() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isATNSerializedAsInts() {\n\t\treturn true;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/BasicFontMetrics.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\n/** Font metrics.  The only way to generate accurate images\n *  in any format that contain text is to know the font metrics.\n *  Specifically, we need to know the width of every character and the\n *  maximum height (since we want all characters to fit within same line height).\n *  I used ttf2tfm to dump the font metrics from Mac TrueType fonts and\n *  then converted that to a Java class for use in a PostScript generator\n *  for trees. Commands:\n *\n * <pre>\n *\t $ ttf2tfm /Library/Fonts/Arial\\ Black.ttf &gt; metrics\n * </pre>\n *\n * \tThen run metrics into python code after stripping header/footer:\n *\n * <pre>\n *\t #\n *\t # Process lines from ttf2tfm that look like this:\n *\t # Glyph  Code   Glyph Name                Width  llx    lly      urx    ury\n *\t # ------------------------------------------------------------------------\n *\t #     3  00020  space                       333  0,     0 --     0,     0\n *\t #\n *\t lines = open(\"metrics\").read().split('\\n')\n *\t print \"public class FontName {\"\n *\t print \"    {\"\n *\t maxh = 0;\n *\t for line in lines[4:]: # skip header 0..3\n *\t\t\t all = line.split(' ')\n *\t\t\t words = [x for x in all if len(x)&gt;0]\n *\t\t\t ascii = int(words[1], 16)\n *\t\t\t height = int(words[8])\n *\t\t\t if height&gt;maxh: maxh = height\n *\t\t\t if ascii&gt;=128: break\n *\t\t\t print \"        widths[%d] = %s; // %s\" % (ascii, words[3], words[2])\n *\n *\t print \"        maxCharHeight = \"+str(maxh)+\";\"\n *\t print \"    }\"\n *\t print \"}\"\n * </pre>\n *\n *\tUnits are 1000th of an 'em'.\n */\npublic abstract class BasicFontMetrics {\n\tpublic static final int MAX_CHAR = '\\u00FF';\n\tprotected int maxCharHeight;\n\tprotected int[] widths = new int[MAX_CHAR+1];\n\n\tpublic double getWidth(String s, int fontSize) {\n\t\tdouble w = 0;\n\t\tfor (char c : s.toCharArray()) {\n\t\t\tw += getWidth(c, fontSize);\n\t\t}\n\t\treturn w;\n\t}\n\n\tpublic double getWidth(char c, int fontSize) {\n\t\tif ( c > MAX_CHAR || widths[c]==0 ) return widths['m']/1000.0; // return width('m')\n\t\treturn widths[c]/1000.0 * fontSize;\n\t}\n\n\tpublic double getLineHeight(int fontSize) {\n\t\treturn maxCharHeight / 1000.0 * fontSize;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/GraphicsSupport.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport javax.imageio.ImageIO;\nimport javax.print.DocFlavor;\nimport javax.print.DocPrintJob;\nimport javax.print.PrintException;\nimport javax.print.PrintService;\nimport javax.print.SimpleDoc;\nimport javax.print.StreamPrintServiceFactory;\nimport javax.print.attribute.HashPrintRequestAttributeSet;\nimport javax.print.attribute.PrintRequestAttributeSet;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;\nimport java.awt.print.PageFormat;\nimport java.awt.print.Printable;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class GraphicsSupport {\n\t/**\n\t [The \"BSD license\"]\n\t Copyright (c) 2011 Cay Horstmann\n\t All rights reserved.\n\n\t Redistribution and use in source and binary forms, with or without\n\t modification, are permitted provided that the following conditions\n\t are met:\n\n\t 1. Redistributions of source code must retain the above copyright\n\t notice, this list of conditions and the following disclaimer.\n\t 2. Redistributions in binary form must reproduce the above copyright\n\t notice, this list of conditions and the following disclaimer in the\n\t documentation and/or other materials provided with the distribution.\n\t 3. The name of the author may not be used to endorse or promote products\n\t derived from this software without specific prior written permission.\n\n\t THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n\t IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\t OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n\t IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n\t INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n\t NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n\t THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\tpublic static void saveImage(final JComponent comp, String fileName)\n\t\tthrows IOException, PrintException\n\t{\n\t\tif ( fileName.endsWith(\".ps\") || fileName.endsWith(\".eps\") ) {\n\t\t\tDocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;\n\t\t\tString mimeType = \"application/postscript\";\n\t\t\tStreamPrintServiceFactory[] factories =\n\t\t\t\tStreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, mimeType);\n\t\t\tSystem.out.println(Arrays.toString(factories));\n\t\t\tif (factories.length > 0) {\n\t\t\t\tFileOutputStream out = new FileOutputStream(fileName);\n\t\t\t\tPrintService service = factories[0].getPrintService(out);\n\t\t\t\tSimpleDoc doc = new SimpleDoc(new Printable() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic int print(Graphics g, PageFormat pf, int page) {\n\t\t\t\t\t\tif (page >= 1) return Printable.NO_SUCH_PAGE;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tGraphics2D g2 = (Graphics2D) g;\n\t\t\t\t\t\t\tg2.translate((pf.getWidth() - pf.getImageableWidth()) / 2,\n\t\t\t\t\t\t\t\t\t\t (pf.getHeight() - pf.getImageableHeight()) / 2);\n\t\t\t\t\t\t\tif ( comp.getWidth() > pf.getImageableWidth() ||\n\t\t\t\t\t\t\t\t comp.getHeight() > pf.getImageableHeight() )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdouble sf1 = pf.getImageableWidth() / (comp.getWidth() + 1);\n\t\t\t\t\t\t\t\tdouble sf2 = pf.getImageableHeight() / (comp.getHeight() + 1);\n\t\t\t\t\t\t\t\tdouble s = Math.min(sf1, sf2);\n\t\t\t\t\t\t\t\tg2.scale(s, s);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcomp.paint(g);\n\t\t\t\t\t\t\treturn Printable.PAGE_EXISTS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}, flavor, null);\n\t\t\t\tDocPrintJob job = service.createPrintJob();\n\t\t\t\tPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();\n\t\t\t\tjob.print(doc, attributes);\n\t\t\t\tout.close();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// parrt: works with [image/jpeg, image/png, image/x-png, image/vnd.wap.wbmp, image/bmp, image/gif]\n\t\t\tRectangle rect = comp.getBounds();\n\t\t\tBufferedImage image = new BufferedImage(rect.width, rect.height,\n\t\t\t\t\t\t\t\t\t\t\t\t\tBufferedImage.TYPE_INT_RGB);\n\t\t\tGraphics2D g = (Graphics2D) image.getGraphics();\n\t\t\tg.setColor(Color.WHITE);\n\t\t\tg.fill(rect);\n//\t\t\tg.setColor(Color.BLACK);\n\t\t\tcomp.paint(g);\n\t\t\tString extension = fileName.substring(fileName.lastIndexOf('.') + 1);\n\t\t\tboolean result = ImageIO.write(image, extension, new File(fileName));\n\t\t\tif ( !result ) {\n\t\t\t\tSystem.err.println(\"Now imager for \" + extension);\n\t\t\t}\n\t\t\tg.dispose();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/Interpreter.java",
    "content": "package org.antlr.v4.gui;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.atn.DecisionInfo;\nimport org.antlr.v4.runtime.atn.ParseInfo;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.tool.*;\n\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.NoSuchFileException;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\n/** Interpret a lexer/parser, optionally printing tree string and dumping profile info\n *\n *  $ java org.antlr.v4.gui.Interpreter [X.g4|XParser.g4 XLexer.g4] startRuleName inputFileName\n *        [-tree]\n *        [-gui]\n *        [-trace]\n *        [-encoding encoding]\n *        [-tokens]\n *        [-profile filename.csv]\n */\npublic class Interpreter {\n\tpublic static final String[] profilerColumnNames = {\n\t\t\t\"Rule\",\"Invocations\", \"Time (ms)\", \"Total k\", \"Max k\", \"Ambiguities\", \"DFA cache miss\"\n\t};\n\n\tprotected static class IgnoreTokenVocabGrammar extends Grammar {\n\t\tpublic IgnoreTokenVocabGrammar(String fileName,\n\t\t\t\t\t\t\t\t\t   String grammarText,\n\t\t\t\t\t\t\t\t\t   Grammar tokenVocabSource,\n\t\t\t\t\t\t\t\t\t   ANTLRToolListener listener)\n\t\t\t\tthrows RecognitionException\n\t\t{\n\t\t\tsuper(fileName, grammarText, tokenVocabSource, listener);\n\t\t}\n\n\t\t@Override\n\t\tpublic void importTokensFromTokensFile() {\n\t\t\t// don't try to import tokens files; must give me both grammars if split\n\t\t}\n\t}\n\n\tprotected String grammarFileName;\n\tprotected String parserGrammarFileName;\n\tprotected String lexerGrammarFileName;\n\tprotected String startRuleName;\n\tprotected boolean printTree = false;\n\tprotected boolean gui = false;\n\tprotected boolean trace = false;\n\tprotected String encoding = null;\n\tprotected boolean showTokens = false;\n\tprotected String profileFileName = null;\n\tprotected String inputFileName;\n\n\tpublic Interpreter(String[] args) throws Exception {\n\t\tif ( args.length < 2 ) {\n\t\t\tSystem.err.println(\"java org.antlr.v4.gui.Intrepreter [X.g4|XParser.g4 XLexer.g4] startRuleName\\n\" +\n\t\t\t\t\t\"  [-tokens] [-tree] [-gui] [-encoding encodingname]\\n\" +\n\t\t\t\t\t\"  [-trace] [-profile filename.csv] [input-filename(s)]\");\n\t\t\tSystem.err.println(\"Omitting input-filename makes rig read from stdin.\");\n\t\t\treturn;\n\t\t}\n\t\tint i=0;\n\t\tgrammarFileName = args[i];\n\t\ti++;\n\t\tif ( args[i].endsWith(\".g4\") ) {\n\t\t\tparserGrammarFileName = grammarFileName;\n\t\t\tlexerGrammarFileName = args[i];\n\t\t\ti++;\n\t\t\tgrammarFileName = null;\n\n\t\t\tif ( parserGrammarFileName.toLowerCase().endsWith(\"lexer.g4\") ) { // swap\n\t\t\t\tString save = parserGrammarFileName;\n\t\t\t\tparserGrammarFileName = lexerGrammarFileName;\n\t\t\t\tlexerGrammarFileName = save;\n\t\t\t}\n\t\t}\n\t\tstartRuleName = args[i];\n\t\ti++;\n\t\twhile ( i<args.length ) {\n\t\t\tString arg = args[i];\n\t\t\ti++;\n\t\t\tif ( arg.charAt(0)!='-' ) { // input file name\n\t\t\t\tinputFileName = arg;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-tree\") ) {\n\t\t\t\tprintTree = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-gui\") ) {\n\t\t\t\tgui = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-tokens\") ) {\n\t\t\t\tshowTokens = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-trace\") ) {\n\t\t\t\ttrace = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-profile\") ) {\n\t\t\t\tif ( i>=args.length ) {\n\t\t\t\t\tSystem.err.println(\"missing CSV filename on -profile (ignoring -profile)\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif ( args[i].startsWith(\"-\") ) { // filename can't start with '-' since likely an arg\n\t\t\t\t\tSystem.err.println(\"missing CSV filename on -profile (ignoring -profile)\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tprofileFileName = args[i];\n\t\t\t\tif ( !profileFileName.endsWith(\".csv\") ) {\n\t\t\t\t\tSystem.err.println(\"warning: missing '.csv' suffix on -profile filename: \"+profileFileName);\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-encoding\") ) {\n\t\t\t\tif ( i>=args.length ) {\n\t\t\t\t\tSystem.err.println(\"missing encoding on -encoding\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tencoding = args[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected ParseInfo interp() throws RecognitionException, IOException {\n\t\tif ( grammarFileName==null && (parserGrammarFileName==null && lexerGrammarFileName==null) ) {\n\t\t\treturn null;\n\t\t}\n\t\tGrammar g;\n\t\tLexerGrammar lg = null;\n\t\tDefaultToolListener listener = new DefaultToolListener(new Tool());\n\t\tif (grammarFileName != null) {\n\t\t\tString grammarContent = Files.readString(Path.of(grammarFileName));\n\t\t\tg = new IgnoreTokenVocabGrammar(grammarFileName, grammarContent, null, listener);\n\t\t}\n\t\telse {\n\t\t\tString lexerGrammarContent = Files.readString(Path.of(lexerGrammarFileName));\n\t\t\tlg = new LexerGrammar(lexerGrammarContent, listener);\n\t\t\tString parserGrammarContent = Files.readString(Path.of(parserGrammarFileName));\n\t\t\tg = new IgnoreTokenVocabGrammar(parserGrammarFileName, parserGrammarContent, lg, listener);\n\t\t}\n\n\t\tCharset charset = ( encoding == null ? Charset.defaultCharset () : Charset.forName(encoding) );\n\t\tCharStream charStream = null;\n\t\tif ( inputFileName==null ) {\n\t\t\tcharStream = CharStreams.fromStream(System.in, charset);\n\t\t}\n\t\telse {\n\t\t\ttry {\n\t\t\t\tcharStream = CharStreams.fromPath(Paths.get(inputFileName), charset);\n\t\t\t}\n\t\t\tcatch (NoSuchFileException nsfe) {\n\t\t\t\tSystem.err.println(\"Can't find input file \"+inputFileName);\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t}\n\n\t\tLexerInterpreter lexEngine = (lg!=null) ?\n\t\t\t\tlg.createLexerInterpreter(charStream) :\n\t\t\t\tg.createLexerInterpreter(charStream);\n\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\n\t\ttokens.fill();\n\n\t\tif ( showTokens ) {\n\t\t\tfor (Token tok : tokens.getTokens()) {\n\t\t\t\tif ( tok instanceof CommonToken ) {\n\t\t\t\t\tSystem.out.println(((CommonToken)tok).toString(lexEngine));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.println(tok.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tGrammarParserInterpreter parser = g.createGrammarParserInterpreter(tokens);\n\t\tif ( profileFileName!=null ) {\n\t\t\tparser.setProfile(true);\n\t\t}\n\t\tparser.setTrace(trace);\n\n\t\tRule r = g.rules.get(startRuleName);\n\t\tif (r == null) {\n\t\t\tSystem.err.println(\"No such start rule: \"+startRuleName);\n\t\t\treturn null;\n\t\t}\n\t\tParseTree t = parser.parse(r.index);\n\t\tParseInfo parseInfo = parser.getParseInfo();\n\n\t\tif ( printTree ) {\n\t\t\tSystem.out.println(t.toStringTree(parser));\n\t\t}\n\t\tif ( gui ) {\n\t\t\tTrees.inspect(t, parser);\n\t\t}\n\t\tif ( profileFileName!=null ) {\n\t\t\tdumpProfilerCSV(parser, parseInfo);\n\t\t}\n\n\t\treturn parseInfo;\n\t}\n\n\tprivate void dumpProfilerCSV(GrammarParserInterpreter parser, ParseInfo parseInfo) {\n\t\tString[] ruleNamesByDecision = new String[parser.getATN().decisionToState.size()];\n\t\tfor(int i = 0; i < ruleNamesByDecision .length; i++) {\n\t\t\truleNamesByDecision [i] = parser.getRuleNames()[parser.getATN().getDecisionState(i).ruleIndex];\n\t\t}\n\n\t\tDecisionInfo[] decisionInfo = parseInfo.getDecisionInfo();\n\t\tString[][] table = new String[decisionInfo.length][profilerColumnNames.length];\n\n\t\tfor (int decision = 0; decision < decisionInfo.length; decision++) {\n\t\t\tfor (int col = 0; col < profilerColumnNames.length; col++) {\n\t\t\t\tObject colVal = getValue(decisionInfo[decision], ruleNamesByDecision, decision, col);\n\t\t\t\ttable[decision][col] = colVal.toString();\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tFileWriter fileWriter = new FileWriter(profileFileName);\n\t\t\tPrintWriter pw = new PrintWriter(fileWriter);\n\n\t\t\tfor (int i = 0; i < profilerColumnNames.length; i++) {\n\t\t\t\tif (i > 0) pw.print(\",\");\n\t\t\t\tpw.print(profilerColumnNames[i]);\n\t\t\t}\n\t\t\tpw.println();\n\t\t\tfor (String[] row : table) {\n\t\t\t\tfor (int i = 0; i < profilerColumnNames.length; i++) {\n\t\t\t\t\tif (i > 0) pw.print(\",\");\n\t\t\t\t\tpw.print(row[i]);\n\t\t\t\t}\n\t\t\t\tpw.println();\n\t\t\t}\n\t\t\tpw.close();\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tSystem.err.println(\"Error writing profile info to \"+profileFileName+\": \"+ioe.getMessage());\n\t\t}\n\t}\n\n\tpublic static Object getValue(DecisionInfo decisionInfo,\n\t\t\t\t\t\t\t\t  String[] ruleNamesByDecision,\n\t\t\t\t\t\t\t\t  int decision,\n\t\t\t\t\t\t\t\t  int col)\n\t{\n\t\tswitch (col) { // laborious but more efficient than reflection\n\t\t\tcase 0:\n\t\t\t\treturn  String.format(\"%s:%d\",ruleNamesByDecision[decision],decision);\n\t\t\tcase 1:\n\t\t\t\treturn decisionInfo.invocations;\n\t\t\tcase 2:\n\t\t\t\treturn decisionInfo.timeInPrediction/(1000.0 * 1000.0);\n\t\t\tcase 3:\n\t\t\t\treturn decisionInfo.LL_TotalLook+decisionInfo.SLL_TotalLook;\n\t\t\tcase 4:\n\t\t\t\treturn Math.max(decisionInfo.LL_MaxLook, decisionInfo.SLL_MaxLook);\n\t\t\tcase 5:\n\t\t\t\treturn decisionInfo.ambiguities.size();\n\t\t\tcase 6:\n\t\t\t\treturn decisionInfo.SLL_ATNTransitions+\n\t\t\t\t\t\tdecisionInfo.LL_ATNTransitions;\n\t\t}\n\t\treturn \"n/a\";\n\t}\n\n\tpublic static void main(String[] args) throws Exception {\n\t\tInterpreter I = new Interpreter(args);\n\t\tI.interp();\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/JFileChooserConfirmOverwrite.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.gui;\n\nimport javax.swing.*;\nimport java.io.File;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class JFileChooserConfirmOverwrite extends JFileChooser {\n\n\tpublic JFileChooserConfirmOverwrite() {\n\t\tsetMultiSelectionEnabled(false);\n\t}\n\n\t@Override\n\tpublic void approveSelection() {\n\t\tFile selectedFile = getSelectedFile();\n\n\t\tif (selectedFile.exists()) {\n\t\t\tint answer = JOptionPane.showConfirmDialog(this,\n\t\t\t\t\t\t\t\t\t\t\t\t\t   \"Overwrite existing file?\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t   \"Overwrite?\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t   JOptionPane.YES_NO_OPTION);\n\t\t\tif (answer != JOptionPane.YES_OPTION) {\n\t\t\t\t// do not call super.approveSelection\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tsuper.approveSelection();\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/PostScriptDocument.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport java.awt.*;\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\n\npublic class PostScriptDocument {\n\tpublic static final String DEFAULT_FONT = \"CourierNew\";\n\n\tpublic static final Map<String, String> POSTSCRIPT_FONT_NAMES;\n\tstatic {\n\t\tPOSTSCRIPT_FONT_NAMES = new HashMap<String, String>();\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SANS_SERIF + \".plain\", \"ArialMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SANS_SERIF + \".bold\", \"Arial-BoldMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SANS_SERIF + \".italic\", \"Arial-ItalicMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SANS_SERIF + \".bolditalic\", \"Arial-BoldItalicMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SERIF + \".plain\", \"TimesNewRomanPSMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SERIF + \".bold\", \"TimesNewRomanPS-BoldMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SERIF + \".italic\", \"TimesNewRomanPS-ItalicMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.SERIF + \".bolditalic\", \"TimesNewRomanPS-BoldItalicMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.MONOSPACED + \".plain\", \"CourierNewPSMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.MONOSPACED + \".bold\", \"CourierNewPS-BoldMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.MONOSPACED + \".italic\", \"CourierNewPS-ItalicMT\");\n\t\tPOSTSCRIPT_FONT_NAMES.put(Font.MONOSPACED + \".bolditalic\", \"CourierNewPS-BoldItalicMT\");\n\t}\n\n\tprotected int boundingBoxWidth;\n\tprotected int boundingBoxHeight;\n\n\tprotected SystemFontMetrics fontMetrics;\n\tprotected String fontName;\n\tprotected int fontSize = 12;\n\tprotected double lineWidth = 0.3;\n\tprotected String boundingBox;\n\n\tprotected StringBuilder ps = new StringBuilder();\n\tprotected boolean closed = false;\n\n\tpublic PostScriptDocument() {\n\t\tthis(DEFAULT_FONT, 12);\n\t}\n\n\tpublic PostScriptDocument(String fontName, int fontSize) {\n\t\theader();\n\t\tsetFont(fontName, fontSize);\n\t}\n\n\tpublic String getPS() {\n\t\tclose();\n\t\treturn header()+ps.toString();\n\t}\n\n\tpublic void boundingBox(int w, int h) {\n\t\tboundingBoxWidth = w;\n\t\tboundingBoxHeight = h;\n\t\tboundingBox = String.format(Locale.US, \"%%%%BoundingBox: %d %d %d %d\\n\", 0,0,\n\t\t\t\t\t\t\t\t\tboundingBoxWidth,boundingBoxHeight);\n\t}\n\n\tpublic void close() {\n\t\tif ( closed ) return;\n//\t\tps.append(\"showpage\\n\");\n\t\tps.append(\"%%Trailer\\n\");\n\t\tclosed = true;\n\t}\n\n\t/** Compute the header separately because we need to wait for the bounding box */\n\tprotected StringBuilder header() {\n\t\tStringBuilder b = new StringBuilder();\n\t\tb.append(\"%!PS-Adobe-3.0 EPSF-3.0\\n\");\n\t\tb.append(boundingBox).append(\"\\n\");\n\t\tb.append(\"0.3 setlinewidth\\n\");\n\t\tb.append(\"%% x y w h highlight\\n\" +\n\t\t\t\t \"/highlight {\\n\" +\n\t\t\t\t \"        4 dict begin\\n\" +\n\t\t\t\t \"        /h exch def\\n\" +\n\t\t\t\t \"        /w exch def\\n\" +\n\t\t\t\t \"        /y exch def\\n\" +\n\t\t\t\t \"        /x exch def\\n\" +\n\t\t\t\t \"        gsave\\n\" +\n\t\t\t\t \"        newpath\\n\" +\n\t\t\t\t \"        x y moveto\\n\" +\n\t\t\t\t \"        0 h rlineto     % up to left corner\\n\" +\n\t\t\t\t \"        w 0 rlineto     % to upper right corner\\n\" +\n\t\t\t\t \"        0 h neg rlineto % to lower right corner\\n\" +\n\t\t\t\t \"        w neg 0 rlineto % back home to lower left corner\\n\" +\n\t\t\t\t \"        closepath\\n\" +\n\t\t\t\t \"        .95 .83 .82 setrgbcolor\\n\" +\n\t\t\t\t \"        fill\\n\" +\n\t\t\t\t \"        grestore\\n\" +\n\t\t\t\t \"        end\\n\" +\n\t\t\t\t \"} def\\n\");\n\n\t\treturn b;\n\t}\n\n\tpublic void setFont(String fontName, int fontSize) {\n\t\tthis.fontMetrics = new SystemFontMetrics(fontName);\n\t\tthis.fontName = fontMetrics.getFont().getPSName();\n\t\tthis.fontSize = fontSize;\n\n\t\tString psname = POSTSCRIPT_FONT_NAMES.get(this.fontName);\n\t\tif (psname == null) {\n\t\t\tpsname = this.fontName;\n\t\t}\n\n\t\tps.append(String.format(Locale.US, \"/%s findfont %d scalefont setfont\\n\", psname, fontSize));\n\t}\n\n\tpublic void lineWidth(double w) {\n\t\tlineWidth = w;\n\t\tps.append(w).append(\" setlinewidth\\n\");\n\t}\n\n\tpublic void move(double x, double y) {\n\t\tps.append(String.format(Locale.US, \"%1.3f %1.3f moveto\\n\", x, y));\n\t}\n\n\tpublic void lineto(double x, double y) {\n\t\tps.append(String.format(Locale.US, \"%1.3f %1.3f lineto\\n\", x, y));\n\t}\n\n\tpublic void line(double x1, double y1, double x2, double y2) {\n\t\tmove(x1, y1);\n\t\tlineto(x2, y2);\n\t}\n\n\tpublic void rect(double x, double y, double width, double height) {\n\t\tline(x, y, x, y + height);\n\t\tline(x, y + height, x + width, y + height);\n\t\tline(x + width, y + height, x + width, y);\n\t\tline(x + width, y, x, y);\n\t}\n\n\t/** Make red box */\n\tpublic void highlight(double x, double y, double width, double height) {\n\t\tps.append(String.format(Locale.US, \"%1.3f %1.3f %1.3f %1.3f highlight\\n\", x, y, width, height));\n\t}\n\n\tpublic void stroke() {\n\t\tps.append(\"stroke\\n\");\n\t}\n\n//\tpublic void rarrow(double x, double y) {\n//\t\tps.append(String.format(Locale.US, \"%1.3f %1.3f rarrow\\n\", x,y));\n//\t}\n//\n//\tpublic void darrow(double x, double y) {\n//\t\tps.append(String.format(Locale.US, \"%1.3f %1.3f darrow\\n\", x,y));\n//\t}\n\n\tpublic void text(String s, double x, double y) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\t// escape \\, (, ): \\\\,  \\(,  \\)\n\t\tfor (char c : s.toCharArray()) {\n\t\t\tswitch ( c ) {\n\t\t\t\tcase '\\\\' :\n\t\t\t\tcase '(' :\n\t\t\t\tcase ')' :\n\t\t\t\t\tbuf.append('\\\\');\n\t\t\t\t\tbuf.append(c);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault :\n\t\t\t\t\tbuf.append(c);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\ts = buf.toString();\n\t\tmove(x,y);\n\t\tps.append(String.format(Locale.US, \"(%s) show\\n\", s));\n\t\tstroke();\n\t}\n\n\t// courier new: wid/hei 7.611979\t10.0625\n\t/** All chars are 600 thousands of an 'em' wide if courier */\n\tpublic double getWidth(char c) { return fontMetrics.getWidth(c, fontSize); }\n\tpublic double getWidth(String s) { return fontMetrics.getWidth(s, fontSize); }\n\tpublic double getLineHeight() { return fontMetrics.getLineHeight(fontSize); }\n\n\tpublic int getFontSize() { return fontSize; }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/SystemFontMetrics.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport java.awt.*;\nimport java.awt.font.FontRenderContext;\nimport java.awt.font.TextLayout;\nimport java.awt.image.BufferedImage;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class SystemFontMetrics extends BasicFontMetrics {\n\tprotected final Font font;\n\n\tpublic SystemFontMetrics(String fontName) {\n\t\tBufferedImage img = new BufferedImage(40, 40, BufferedImage.TYPE_4BYTE_ABGR);\n\t\tGraphics2D graphics = GraphicsEnvironment.getLocalGraphicsEnvironment().createGraphics(img);\n\t\tFontRenderContext fontRenderContext = graphics.getFontRenderContext();\n\t\tthis.font = new Font(fontName, Font.PLAIN, 1000);\n\t\tdouble maxHeight = 0;\n\t\tfor (int i = 0; i < 255; i++) {\n\t\t\tTextLayout layout = new TextLayout(Character.toString((char)i), font, fontRenderContext);\n\t\t\tmaxHeight = Math.max(maxHeight, layout.getBounds().getHeight());\n\t\t\tsuper.widths[i] = (int)layout.getAdvance();\n\t\t}\n\n\t\tsuper.maxCharHeight = (int)Math.round(maxHeight);\n\t}\n\n\tpublic Font getFont() {\n\t\treturn font;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/TestRig.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CharStreams;\nimport org.antlr.v4.runtime.CommonToken;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.DiagnosticErrorListener;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.atn.PredictionMode;\n\nimport javax.print.PrintException;\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.nio.charset.Charset;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** Run a lexer/parser combo, optionally printing tree string or generating\n *  postscript file. Optionally taking input file.\n *\n *  $ java org.antlr.v4.runtime.misc.TestRig GrammarName startRuleName\n *        [-tree]\n *        [-tokens] [-gui] [-ps file.ps]\n *        [-trace]\n *        [-diagnostics]\n *        [-SLL]\n *        [input-filename(s)]\n */\npublic class TestRig {\n\tpublic static final String LEXER_START_RULE_NAME = \"tokens\";\n\n\tprotected String grammarName;\n\tprotected String startRuleName;\n\tprotected final List<String> inputFiles = new ArrayList<String>();\n\tprotected boolean printTree = false;\n\tprotected boolean gui = false;\n\tprotected String psFile = null;\n\tprotected boolean showTokens = false;\n\tprotected boolean trace = false;\n\tprotected boolean diagnostics = false;\n\tprotected String encoding = null;\n\tprotected boolean SLL = false;\n\n\tpublic TestRig(String[] args) throws Exception {\n\t\tif ( args.length < 2 ) {\n\t\t\tSystem.err.println(\"java org.antlr.v4.gui.TestRig GrammarName startRuleName\\n\" +\n\t\t\t\t\t\t\t   \"  [-tokens] [-tree] [-gui] [-ps file.ps] [-encoding encodingname]\\n\" +\n\t\t\t\t\t\t\t   \"  [-trace] [-diagnostics] [-SLL]\\n\"+\n\t\t\t\t\t\t\t   \"  [input-filename(s)]\");\n\t\t\tSystem.err.println(\"Use startRuleName='tokens' if GrammarName is a lexer grammar.\");\n\t\t\tSystem.err.println(\"Omitting input-filename makes rig read from stdin.\");\n\t\t\treturn;\n\t\t}\n\t\tint i=0;\n\t\tgrammarName = args[i];\n\t\ti++;\n\t\tstartRuleName = args[i];\n\t\ti++;\n\t\twhile ( i<args.length ) {\n\t\t\tString arg = args[i];\n\t\t\ti++;\n\t\t\tif ( arg.charAt(0)!='-' ) { // input file name\n\t\t\t\tinputFiles.add(arg);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( arg.equals(\"-tree\") ) {\n\t\t\t\tprintTree = true;\n\t\t\t}\n\t\t\tif ( arg.equals(\"-gui\") ) {\n\t\t\t\tgui = true;\n\t\t\t}\n\t\t\tif ( arg.equals(\"-tokens\") ) {\n\t\t\t\tshowTokens = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-trace\") ) {\n\t\t\t\ttrace = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-SLL\") ) {\n\t\t\t\tSLL = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-diagnostics\") ) {\n\t\t\t\tdiagnostics = true;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-encoding\") ) {\n\t\t\t\tif ( i>=args.length ) {\n\t\t\t\t\tSystem.err.println(\"missing encoding on -encoding\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tencoding = args[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse if ( arg.equals(\"-ps\") ) {\n\t\t\t\tif ( i>=args.length ) {\n\t\t\t\t\tSystem.err.println(\"missing filename on -ps\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpsFile = args[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) throws Exception {\n\t\tTestRig testRig = new TestRig(args);\n \t\tif(args.length >= 2) {\n\t\t\ttestRig.process();\n\t\t}\n\t}\n\n\tpublic void process() throws Exception {\n//\t\tSystem.out.println(\"exec \"+grammarName+\".\"+startRuleName);\n\t\tString lexerName = grammarName+\"Lexer\";\n\t\tClassLoader cl = Thread.currentThread().getContextClassLoader();\n\t\tClass<? extends Lexer> lexerClass = null;\n\t\ttry {\n\t\t\tlexerClass = cl.loadClass(lexerName).asSubclass(Lexer.class);\n\t\t}\n\t\tcatch (java.lang.ClassNotFoundException cnfe) {\n\t\t\t// might be pure lexer grammar; no Lexer suffix then\n\t\t\tlexerName = grammarName;\n\t\t\ttry {\n\t\t\t\tlexerClass = cl.loadClass(lexerName).asSubclass(Lexer.class);\n\t\t\t}\n\t\t\tcatch (ClassNotFoundException cnfe2) {\n\t\t\t\tSystem.err.println(\"Can't load \"+lexerName+\" as lexer or parser\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tConstructor<? extends Lexer> lexerCtor = lexerClass.getConstructor(CharStream.class);\n\t\tLexer lexer = lexerCtor.newInstance((CharStream)null);\n\n\t\tClass<? extends Parser> parserClass = null;\n\t\tParser parser = null;\n\t\tif ( !startRuleName.equals(LEXER_START_RULE_NAME) ) {\n\t\t\tString parserName = grammarName+\"Parser\";\n\t\t\tparserClass = cl.loadClass(parserName).asSubclass(Parser.class);\n\t\t\tConstructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class);\n\t\t\tparser = parserCtor.newInstance((TokenStream)null);\n\t\t}\n\n\t\tCharset charset = ( encoding == null ? Charset.defaultCharset () : Charset.forName(encoding) );\n\t\tif ( inputFiles.size()==0 ) {\n\t\t\tCharStream charStream = CharStreams.fromStream(System.in, charset);\n\t\t\tprocess(lexer, parserClass, parser, charStream);\n\t\t\treturn;\n\t\t}\n\t\tfor (String inputFile : inputFiles) {\n\t                CharStream charStream = CharStreams.fromPath(Paths.get(inputFile), charset);\n\t\t\tif ( inputFiles.size()>1 ) {\n\t\t\t\tSystem.err.println(inputFile);\n\t\t\t}\n\t\t\tprocess(lexer, parserClass, parser, charStream);\n\t\t}\n\t}\n\n\tprotected void process(Lexer lexer, Class<? extends Parser> parserClass, Parser parser, CharStream input) throws IOException, IllegalAccessException, InvocationTargetException, PrintException {\n\t\t\tlexer.setInputStream(input);\n\t\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\n\t\t\ttokens.fill();\n\n\t\t\tif ( showTokens ) {\n\t\t\t\tfor (Token tok : tokens.getTokens()) {\n\t\t\t\t\tif ( tok instanceof CommonToken ) {\n\t\t\t\t\t\tSystem.out.println(((CommonToken)tok).toString(lexer));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.println(tok.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( startRuleName.equals(LEXER_START_RULE_NAME) ) return;\n\n\t\t\tif ( diagnostics ) {\n\t\t\t\tparser.addErrorListener(new DiagnosticErrorListener());\n\t\t\t\tparser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);\n\t\t\t}\n\n\t\t\tif ( printTree || gui || psFile!=null ) {\n\t\t\t\tparser.setBuildParseTree(true);\n\t\t\t}\n\n\t\t\tif ( SLL ) { // overrides diagnostics\n\t\t\t\tparser.getInterpreter().setPredictionMode(PredictionMode.SLL);\n\t\t\t}\n\n\t\t\tparser.setTokenStream(tokens);\n\t\t\tparser.setTrace(trace);\n\n\t\t\ttry {\n\t\t\t\tMethod startRule = parserClass.getMethod(startRuleName);\n\t\t\t\tParserRuleContext tree = (ParserRuleContext)startRule.invoke(parser, (Object[])null);\n\n\t\t\t\tif ( printTree ) {\n\t\t\t\t\tSystem.out.println(tree.toStringTree(parser));\n\t\t\t\t}\n\t\t\t\tif ( gui ) {\n\t\t\t\t\tTrees.inspect(tree, parser);\n\t\t\t\t}\n\t\t\t\tif ( psFile!=null ) {\n\t\t\t\t\tTrees.save(tree, parser, psFile); // Generate postscript\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (NoSuchMethodException nsme) {\n\t\t\t\tSystem.err.println(\"No method for rule \"+startRuleName+\" or it has arguments\");\n\t\t\t}\n\t\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/TreeLayoutAdaptor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport org.abego.treelayout.TreeForTreeLayout;\nimport org.antlr.v4.runtime.tree.Tree;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n/** Adaptor ANTLR trees to {@link TreeForTreeLayout}. */\npublic class TreeLayoutAdaptor implements TreeForTreeLayout<Tree> {\n\tprivate static class AntlrTreeChildrenIterable implements Iterable<Tree> {\n\t\tprivate final Tree tree;\n\n\t\tpublic AntlrTreeChildrenIterable(Tree tree) {\n\t\t\tthis.tree = tree;\n\t\t}\n\n\t\t@Override\n\t\tpublic Iterator<Tree> iterator() {\n\t\t\treturn new Iterator<Tree>() {\n\t\t\t\tprivate int i = 0;\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn tree.getChildCount() > i;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Tree next() {\n\t\t\t\t\tif (!hasNext())\n\t\t\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\t\t\treturn tree.getChild(i++);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void remove() {\n\t\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate static class AntlrTreeChildrenReverseIterable implements\n\t\tIterable<Tree>\n\t{\n\t\tprivate final Tree tree;\n\n\t\tpublic AntlrTreeChildrenReverseIterable(Tree tree) {\n\t\t\tthis.tree = tree;\n\t\t}\n\n\t\t@Override\n\t\tpublic Iterator<Tree> iterator() {\n\t\t\treturn new Iterator<Tree>() {\n\t\t\t\tprivate int i = tree.getChildCount();\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\treturn i > 0;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Tree next() {\n\t\t\t\t\tif (!hasNext())\n\t\t\t\t\t\tthrow new NoSuchElementException();\n\n\t\t\t\t\treturn tree.getChild(--i);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void remove() {\n\t\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate Tree root;\n\n\tpublic TreeLayoutAdaptor(Tree root) {\n\t\tthis.root = root;\n\t}\n\n\t@Override\n\tpublic boolean isLeaf(Tree node) {\n\t\treturn node.getChildCount() == 0;\n\t}\n\n\t@Override\n\tpublic boolean isChildOfParent(Tree node, Tree parentNode) {\n\t\treturn node.getParent() == parentNode;\n\t}\n\n\t@Override\n\tpublic Tree getRoot() {\n\t\treturn root;\n\t}\n\n\t@Override\n\tpublic Tree getLastChild(Tree parentNode) {\n\t\treturn parentNode.getChild(parentNode.getChildCount() - 1);\n\t}\n\n\t@Override\n\tpublic Tree getFirstChild(Tree parentNode) {\n\t\treturn parentNode.getChild(0);\n\t}\n\n\t@Override\n\tpublic Iterable<Tree> getChildrenReverse(Tree node) {\n\t\treturn new AntlrTreeChildrenReverseIterable(node);\n\t}\n\n\t@Override\n\tpublic Iterable<Tree> getChildren(Tree node) {\n\t\treturn new AntlrTreeChildrenIterable(node);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/TreePostScriptGenerator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport org.abego.treelayout.Configuration;\nimport org.abego.treelayout.NodeExtentProvider;\nimport org.abego.treelayout.TreeForTreeLayout;\nimport org.abego.treelayout.TreeLayout;\nimport org.abego.treelayout.util.DefaultConfiguration;\nimport org.antlr.v4.runtime.misc.Utils;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.Tree;\n\nimport java.awt.*;\nimport java.awt.geom.Rectangle2D;\nimport java.util.List;\n\npublic class TreePostScriptGenerator {\n\tpublic class VariableExtentProvide implements NodeExtentProvider<Tree> {\n\t\t@Override\n\t\tpublic double getWidth(Tree tree) {\n\t\t\tString s = getText(tree);\n\t\t\treturn doc.getWidth(s) + nodeWidthPadding*2;\n\t\t}\n\n\t\t@Override\n\t\tpublic double getHeight(Tree tree) {\n\t\t\tString s = getText(tree);\n\t\t\tdouble h =\n\t\t\t\tdoc.getLineHeight() + nodeHeightPaddingAbove + nodeHeightPaddingBelow;\n\t\t\tString[] lines = s.split(\"\\n\");\n\t\t\treturn h * lines.length;\n\t\t}\n\t}\n\n\tprotected double gapBetweenLevels = 17;\n\tprotected double gapBetweenNodes = 7;\n\tprotected int nodeWidthPadding = 1;  // added to left/right\n\tprotected int nodeHeightPaddingAbove = 0;\n\tprotected int nodeHeightPaddingBelow = 5;\n\n\tprotected Tree root;\n\tprotected TreeTextProvider treeTextProvider;\n\tprotected TreeLayout<Tree> treeLayout;\n\n\tprotected PostScriptDocument doc;\n\n\tpublic TreePostScriptGenerator(List<String> ruleNames, Tree root) {\n\t\tthis(ruleNames, root, PostScriptDocument.DEFAULT_FONT, 11);\n\t}\n\n\tpublic TreePostScriptGenerator(List<String> ruleNames, Tree root,\n\t\t\t\t\t\t\t\t   String fontName, int fontSize)\n\t{\n\t\tthis.root = root;\n\t\tsetTreeTextProvider(new TreeViewer.DefaultTreeTextProvider(ruleNames));\n\t\tdoc = new PostScriptDocument(fontName, fontSize);\n\t\tboolean compareNodeIdentities = true;\n\t\tthis.treeLayout =\n\t\t\tnew TreeLayout<Tree>(getTreeLayoutAdaptor(root),\n\t\t\t\t\t\t\t\t new VariableExtentProvide(),\n\t\t\t\t\t\t\t\t new DefaultConfiguration<Tree>(gapBetweenLevels,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgapBetweenNodes,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tConfiguration.Location.Bottom),\n                                 compareNodeIdentities);\n\t}\n\n\t/** Get an adaptor for root that indicates how to walk ANTLR trees.\n\t *  Override to change the adapter from the default of {@link TreeLayoutAdaptor}  */\n\tpublic TreeForTreeLayout<Tree> getTreeLayoutAdaptor(Tree root) {\n\t\treturn new TreeLayoutAdaptor(root);\n\t}\n\n\tpublic String getPS() {\n\t\t// generate the edges and boxes (with text)\n\t\tgenerateEdges(getTree().getRoot());\n\t\tfor (Tree node : treeLayout.getNodeBounds().keySet()) {\n\t\t\tgenerateNode(node);\n\t\t}\n\n\t\tDimension size = treeLayout.getBounds().getBounds().getSize();\n\t\tdoc.boundingBox(size.width, size.height);\n\t\tdoc.close();\n\t\treturn doc.getPS();\n\t}\n\n\tprotected void generateEdges(Tree parent) {\n\t\tif (!getTree().isLeaf(parent)) {\n\t\t\tRectangle2D.Double parentBounds = getBoundsOfNode(parent);\n//\t\t\tSystem.out.println(\"%% parent(\"+getText(parent)+\")=\"+parentBounds);\n\t\t\tdouble x1 = parentBounds.getCenterX();\n\t\t\tdouble y1 = parentBounds.y;\n\t\t\tfor (Tree child : getChildren(parent)) {\n\t\t\t\tRectangle2D.Double childBounds = getBoundsOfNode(child);\n//\t\t\t\tSystem.out.println(\"%% child(\"+getText(child)+\")=\"+childBounds);\n\t\t\t\tdouble x2 = childBounds.getCenterX();\n\t\t\t\tdouble y2 = childBounds.getMaxY();\n\t\t\t\tdoc.line(x1, y1, x2, y2);\n\t\t\t\tgenerateEdges(child);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void generateNode(Tree t) {\n\t\t// draw the text on top of the box (possibly multiple lines)\n\t\tString[] lines = getText(t).split(\"\\n\");\n\t\tRectangle2D.Double box = getBoundsOfNode(t);\n\t\t// for debugging, turn this on to see boundingbox of nodes\n\t\t//doc.rect(box.x, box.y, box.width, box.height);\n\t\t// make error nodes from parse tree red by default\n\t\tif ( t instanceof ErrorNode ) {\n\t\t\tdoc.highlight(box.x, box.y, box.width, box.height);\n\t\t}\n\t\tdouble x = box.x+nodeWidthPadding;\n\t\tdouble y = box.y+nodeHeightPaddingBelow;\n\t\tfor (int i = 0; i < lines.length; i++) {\n\t\t\tdoc.text(lines[i], x, y);\n\t\t\ty += doc.getLineHeight();\n\t\t}\n\t}\n\n\tprotected TreeForTreeLayout<Tree> getTree() {\n\t\treturn treeLayout.getTree();\n\t}\n\n\tprotected Iterable<Tree> getChildren(Tree parent) {\n\t\treturn getTree().getChildren(parent);\n\t}\n\n\tprotected Rectangle2D.Double getBoundsOfNode(Tree node) {\n\t\treturn treeLayout.getNodeBounds().get(node);\n\t}\n\n\tprotected String getText(Tree tree) {\n\t\tString s = treeTextProvider.getText(tree);\n\t\ts = Utils.escapeWhitespace(s, false);\n\t\treturn s;\n\t}\n\n\tpublic TreeTextProvider getTreeTextProvider() {\n\t\treturn treeTextProvider;\n\t}\n\n\tpublic void setTreeTextProvider(TreeTextProvider treeTextProvider) {\n\t\tthis.treeTextProvider = treeTextProvider;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/TreeTextProvider.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport org.antlr.v4.runtime.tree.Tree;\n\npublic interface TreeTextProvider {\n\tString getText(Tree node);\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/TreeViewer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport org.abego.treelayout.NodeExtentProvider;\nimport org.abego.treelayout.TreeForTreeLayout;\nimport org.abego.treelayout.TreeLayout;\nimport org.abego.treelayout.util.DefaultConfiguration;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.misc.Utils;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.Tree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport javax.imageio.ImageIO;\nimport javax.print.PrintException;\nimport javax.swing.*;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\nimport javax.swing.event.TreeSelectionEvent;\nimport javax.swing.event.TreeSelectionListener;\nimport javax.swing.filechooser.FileFilter;\nimport javax.swing.tree.DefaultMutableTreeNode;\nimport javax.swing.tree.TreePath;\nimport javax.swing.tree.TreeSelectionModel;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.event.WindowListener;\nimport java.awt.geom.CubicCurve2D;\nimport java.awt.geom.Rectangle2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.FileWriter;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.prefs.Preferences;\n\npublic class TreeViewer extends JComponent {\n\tpublic static final Color LIGHT_RED = new Color(244, 213, 211);\n\n\tpublic static class DefaultTreeTextProvider implements TreeTextProvider {\n\t\tprivate final List<String> ruleNames;\n\n\t\tpublic DefaultTreeTextProvider(List<String> ruleNames) {\n\t\t\tthis.ruleNames = ruleNames;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getText(Tree node) {\n\t\t\treturn String.valueOf(Trees.getNodeText(node, ruleNames));\n\t\t}\n\t}\n\n\tpublic static class VariableExtentProvide implements NodeExtentProvider<Tree> {\n\t\tTreeViewer viewer;\n\t\tpublic VariableExtentProvide(TreeViewer viewer) {\n\t\t\tthis.viewer = viewer;\n\t\t}\n\t\t@Override\n\t\tpublic double getWidth(Tree tree) {\n\t\t\tFontMetrics fontMetrics = viewer.getFontMetrics(viewer.font);\n\t\t\tString s = viewer.getText(tree);\n\t\t\tint w = fontMetrics.stringWidth(s) + viewer.nodeWidthPadding*2;\n\t\t\treturn w;\n\t\t}\n\n\t\t@Override\n\t\tpublic double getHeight(Tree tree) {\n\t\t\tFontMetrics fontMetrics = viewer.getFontMetrics(viewer.font);\n\t\t\tint h = fontMetrics.getHeight() + viewer.nodeHeightPadding*2;\n\t\t\tString s = viewer.getText(tree);\n\t\t\tString[] lines = s.split(\"\\n\");\n\t\t\treturn h * lines.length;\n\t\t}\n\t}\n\n\tprotected TreeTextProvider treeTextProvider;\n\tprotected TreeLayout<Tree> treeLayout;\n\tprotected java.util.List<Tree> highlightedNodes;\n\n\tprotected String fontName = \"Helvetica\"; //Font.SANS_SERIF;\n\tprotected int fontStyle = Font.PLAIN;\n\tprotected int fontSize = 11;\n\tprotected Font font = new Font(fontName, fontStyle, fontSize);\n\n\tprotected double gapBetweenLevels = 17;\n\tprotected double gapBetweenNodes = 7;\n\tprotected int nodeWidthPadding = 2;  // added to left/right\n\tprotected int nodeHeightPadding = 0; // added above/below\n\tprotected int arcSize = 0;           // make an arc in node outline?\n\n\tprotected double scale = 1.0;\n\n\tprotected Color boxColor = null;     // set to a color to make it draw background\n\n\tprotected Color highlightedBoxColor = Color.lightGray;\n\tprotected Color borderColor = null;\n\tprotected Color textColor = Color.black;\n\n\tpublic TreeViewer(List<String> ruleNames, Tree tree) {\n\t\tsetRuleNames(ruleNames);\n\t\tif ( tree!=null ) {\n\t\t\tsetTree(tree);\n\t\t}\n\t\tsetFont(font);\n\t}\n\n\tprivate void updatePreferredSize() {\n\t\tsetPreferredSize(getScaledTreeSize());\n\t\tinvalidate();\n\t\tif (getParent() != null) {\n\t\t\tgetParent().validate();\n\t\t}\n\t\trepaint();\n\t}\n\n\t// ---------------- PAINT -----------------------------------------------\n\n\tprivate boolean useCurvedEdges = false;\n\n\tpublic boolean getUseCurvedEdges() {\n\t\treturn useCurvedEdges;\n\t}\n\n\tpublic void setUseCurvedEdges(boolean useCurvedEdges) {\n\t\tthis.useCurvedEdges = useCurvedEdges;\n\t}\n\n\tprotected void paintEdges(Graphics g, Tree parent) {\n\t\tif (!getTree().isLeaf(parent)) {\n            BasicStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND,\n                    BasicStroke.JOIN_ROUND);\n            ((Graphics2D)g).setStroke(stroke);\n\n\t\t\tRectangle2D.Double parentBounds = getBoundsOfNode(parent);\n\t\t\tdouble x1 = parentBounds.getCenterX();\n\t\t\tdouble y1 = parentBounds.getMaxY();\n\t\t\tfor (Tree child : getTree().getChildren(parent)) {\n\t\t\t\tRectangle2D.Double childBounds = getBoundsOfNode(child);\n\t\t\t\tdouble x2 = childBounds.getCenterX();\n\t\t\t\tdouble y2 = childBounds.getMinY();\n\t\t\t\tif (getUseCurvedEdges()) {\n\t\t\t\t\tCubicCurve2D c = new CubicCurve2D.Double();\n\t\t\t\t\tdouble ctrlx1 = x1;\n\t\t\t\t\tdouble ctrly1 = (y1+y2)/2;\n\t\t\t\t\tdouble ctrlx2 = x2;\n\t\t\t\t\tdouble ctrly2 = y1;\n\t\t\t\t\tc.setCurve(x1, y1, ctrlx1, ctrly1, ctrlx2, ctrly2, x2, y2);\n\t\t\t\t\t((Graphics2D) g).draw(c);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tg.drawLine((int) x1, (int) y1,\n\t\t\t\t\t\t\t   (int) x2, (int) y2);\n\t\t\t\t}\n\t\t\t\tpaintEdges(g, child);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void paintBox(Graphics g, Tree tree) {\n\t\tRectangle2D.Double box = getBoundsOfNode(tree);\n\t\t// draw the box in the background\n\t\tboolean ruleFailedAndMatchedNothing = false;\n\t\tif ( tree instanceof ParserRuleContext ) {\n\t\t\tParserRuleContext ctx = (ParserRuleContext) tree;\n\t\t\truleFailedAndMatchedNothing = ctx.exception != null &&\n\t\t\t\t\t\t\t\t\t\t  ctx.stop != null && ctx.stop.getTokenIndex() < ctx.start.getTokenIndex();\n\t\t}\n\t\tif ( isHighlighted(tree) || boxColor!=null ||\n\t\t\t tree instanceof ErrorNode ||\n\t\t\t ruleFailedAndMatchedNothing)\n\t\t{\n\t\t\tif ( isHighlighted(tree) ) g.setColor(highlightedBoxColor);\n\t\t\telse if ( tree instanceof ErrorNode || ruleFailedAndMatchedNothing ) g.setColor(LIGHT_RED);\n\t\t\telse g.setColor(boxColor);\n\t\t\tg.fillRoundRect((int) box.x, (int) box.y, (int) box.width - 1,\n\t\t\t\t\t\t\t(int) box.height - 1, arcSize, arcSize);\n\t\t}\n\t\tif ( borderColor!=null ) {\n            g.setColor(borderColor);\n            g.drawRoundRect((int) box.x, (int) box.y, (int) box.width - 1,\n                    (int) box.height - 1, arcSize, arcSize);\n        }\n\n\t\t// draw the text on top of the box (possibly multiple lines)\n\t\tg.setColor(textColor);\n\t\tString s = getText(tree);\n\t\tString[] lines = s.split(\"\\n\");\n\t\tFontMetrics m = getFontMetrics(font);\n\t\tint x = (int) box.x + arcSize / 2 + nodeWidthPadding;\n\t\tint y = (int) box.y + m.getAscent() + m.getLeading() + 1 + nodeHeightPadding;\n\t\tfor (int i = 0; i < lines.length; i++) {\n\t\t\ttext(g, lines[i], x, y);\n\t\t\ty += m.getHeight();\n\t\t}\n\t}\n\n\tpublic void text(Graphics g, String s, int x, int y) {\n//\t\tSystem.out.println(\"drawing '\"+s+\"' @ \"+x+\",\"+y);\n\t\ts = Utils.escapeWhitespace(s, true);\n\t\tg.drawString(s, x, y);\n\t}\n\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tsuper.paint(g);\n\n\t\tif ( treeLayout==null ) {\n\t\t\treturn;\n\t\t}\n\n\t\tGraphics2D g2 = (Graphics2D)g;\n\t\t// anti-alias the lines\n\t\tg2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n      \t\t\t\t\t\tRenderingHints.VALUE_ANTIALIAS_ON);\n\n\t\t// Anti-alias the text\n\t\tg2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n                         \tRenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n\n//\t\tAffineTransform at = g2.getTransform();\n//        g2.scale(\n//            (double) this.getWidth() / 400,\n//            (double) this.getHeight() / 400);\n//\n//\t\tg2.setTransform(at);\n\n\t\tpaintEdges(g, getTree().getRoot());\n\n\t\t// paint the boxes\n\t\tfor (Tree Tree : treeLayout.getNodeBounds().keySet()) {\n\t\t\tpaintBox(g, Tree);\n\t\t}\n\t}\n\n\tprotected void generateEdges(Writer writer, Tree parent) throws IOException {\n\t\tif (!getTree().isLeaf(parent)) {\n\t\t\tRectangle2D.Double b1 = getBoundsOfNode(parent);\n\t\t\tdouble x1 = b1.getCenterX();\n\t\t\tdouble y1 = b1.getCenterY();\n\n\t\t\tfor (Tree child : getTree().getChildren(parent)) {\n\t\t\t\tRectangle2D.Double childBounds = getBoundsOfNode(child);\n\t\t\t\tdouble x2 = childBounds.getCenterX();\n\t\t\t\tdouble y2 = childBounds.getMinY();\n\t\t\t\twriter.write(line(\"\"+x1, \"\"+y1, \"\"+x2, \"\"+y2,\n\t\t\t\t\t\"stroke:black; stroke-width:1px;\"));\n\t\t\t\tgenerateEdges(writer, child);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void generateBox(Writer writer, Tree parent) throws IOException {\n\n\t\t// draw the box in the background\n\t\tRectangle2D.Double box = getBoundsOfNode(parent);\n\t\twriter.write(rect(\"\"+box.x, \"\"+box.y, \"\"+box.width, \"\"+box.height,\n\t\t\t\"fill:orange; stroke:rgb(0,0,0);\", \"rx=\\\"1\\\"\"));\n\n\t\t// draw the text on top of the box (possibly multiple lines)\n\t\tString line = getText(parent).replace(\"<\",\"&lt;\").replace(\">\",\"&gt;\");\n\t\tint fontSize = 10;\n\t\tint x = (int) box.x + 2;\n\t\tint y = (int) box.y + fontSize - 1;\n\t\tString style = String.format(\"font-family:sans-serif;font-size:%dpx;\",\n\t\t\tfontSize);\n\t\twriter.write(text(\"\"+x, \"\"+y, style, line));\n\t}\n\n\tprivate static String line(String x1, String y1, String x2, String y2,\n\t\tString style) {\n\t\treturn String\n\t\t\t.format(\"<line x1=\\\"%s\\\" y1=\\\"%s\\\" x2=\\\"%s\\\" y2=\\\"%s\\\" style=\\\"%s\\\" />\\n\",\n\t\t\t\tx1, y1, x2, y2, style);\n\t}\n\n\tprivate static String rect(String x, String y, String width, String height,\n\t\tString style, String extraAttributes) {\n\t\treturn String\n\t\t\t.format(\"<rect x=\\\"%s\\\" y=\\\"%s\\\" width=\\\"%s\\\" height=\\\"%s\\\" style=\\\"%s\\\" %s/>\\n\",\n\t\t\t\tx, y, width, height, style, extraAttributes);\n\t}\n\n\tprivate static String text(String x, String y, String style, String text) {\n\t\treturn String.format(\n\t\t\t\"<text x=\\\"%s\\\" y=\\\"%s\\\" style=\\\"%s\\\">\\n%s\\n</text>\\n\", x, y,\n\t\t\tstyle, text);\n\t}\n\n\tprivate void paintSVG(Writer writer) throws IOException {\n\n\t\tgenerateEdges(writer, getTree().getRoot());\n\n\t\tfor (Tree tree : treeLayout.getNodeBounds().keySet()) {\n\t\t\tgenerateBox(writer, tree);\n\t\t}\n\t}\n\n\t@Override\n\tprotected Graphics getComponentGraphics(Graphics g) {\n\t\tGraphics2D g2d=(Graphics2D)g;\n\t\tg2d.scale(scale, scale);\n\t\treturn super.getComponentGraphics(g2d);\n\t}\n\n\t// ----------------------------------------------------------------------\n\n\n    private static final String DIALOG_WIDTH_PREFS_KEY          = \"dialog_width\";\n    private static final String DIALOG_HEIGHT_PREFS_KEY         = \"dialog_height\";\n    private static final String DIALOG_X_PREFS_KEY              = \"dialog_x\";\n    private static final String DIALOG_Y_PREFS_KEY              = \"dialog_y\";\n    private static final String DIALOG_DIVIDER_LOC_PREFS_KEY    = \"dialog_divider_location\";\n    private static final String DIALOG_VIEWER_SCALE_PREFS_KEY   = \"dialog_viewer_scale\";\n\n\tprotected static JFrame showInDialog(final TreeViewer viewer) {\n\t\tfinal JFrame dialog = new JFrame();\n\t\tdialog.setTitle(\"Parse Tree Inspector\");\n\n        final Preferences prefs = Preferences.userNodeForPackage(TreeViewer.class);\n\n\t\t// Make new content panes\n\t\tfinal Container mainPane = new JPanel(new BorderLayout(5,5));\n\t\tfinal Container contentPane = new JPanel(new BorderLayout(0,0));\n\t\tcontentPane.setBackground(Color.white);\n\n\t\t// Wrap viewer in scroll pane\n\t\tJScrollPane scrollPane = new JScrollPane(viewer);\n\t\t// Make the scrollpane (containing the viewer) the center component\n\t\tcontentPane.add(scrollPane, BorderLayout.CENTER);\n\n\t\tJPanel wrapper = new JPanel(new FlowLayout());\n\n\t\t// Add button to bottom\n\t\tJPanel bottomPanel = new JPanel(new BorderLayout(0,0));\n\t\tcontentPane.add(bottomPanel, BorderLayout.SOUTH);\n\n\t\tJButton ok = new JButton(\"OK\");\n\t\tok.addActionListener(\n\t\t\tnew ActionListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void actionPerformed(ActionEvent e) {\n                    dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t\twrapper.add(ok);\n\n\t\t// Add an export-to-png button right of the \"OK\" button\n\t\tJButton png = new JButton(\"Export as PNG\");\n\t\tpng.addActionListener(\n\t\t\tnew ActionListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\tgeneratePNGFile(viewer, dialog);\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t\twrapper.add(png);\n\n\t\t// Add an export-to-png button right of the \"OK\" button\n\t\tJButton svg = new JButton(\"Export as SVG\");\n\t\tsvg.addActionListener(\n\t\t\tnew ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tgenerateSVGFile(viewer, dialog);\n\t\t\t}\n\t\t}\n\t\t);\n\t\twrapper.add(svg);\n\n\t\tbottomPanel.add(wrapper, BorderLayout.SOUTH);\n\n\t\t// Add scale slider\n        double lastKnownViewerScale = prefs.getDouble(DIALOG_VIEWER_SCALE_PREFS_KEY, viewer.getScale());\n        viewer.setScale(lastKnownViewerScale);\n\n\t\tint sliderValue = (int) ((lastKnownViewerScale - 1.0) * 1000);\n\t\tfinal JSlider scaleSlider = new JSlider(JSlider.HORIZONTAL, -999, 1000, sliderValue);\n\n\t\tscaleSlider.addChangeListener(\n\t\t\tnew ChangeListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void stateChanged(ChangeEvent e) {\n\t\t\t\t\tint v = scaleSlider.getValue();\n\t\t\t\t\tviewer.setScale(v / 1000.0 + 1.0);\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t\tbottomPanel.add(scaleSlider, BorderLayout.CENTER);\n\n\t\t// Add a JTree representing the parser tree of the input.\n\t\tJPanel treePanel = new JPanel(new BorderLayout(5, 5));\n\n\t\t// An \"empty\" icon that will be used for the JTree's nodes.\n\t\tIcon empty = new EmptyIcon();\n\n\t\tUIManager.put(\"Tree.closedIcon\", empty);\n\t\tUIManager.put(\"Tree.openIcon\", empty);\n\t\tUIManager.put(\"Tree.leafIcon\", empty);\n\n\t\tTree parseTreeRoot = viewer.getTree().getRoot();\n\t\tTreeNodeWrapper nodeRoot = new TreeNodeWrapper(parseTreeRoot, viewer);\n\t\tfillTree(nodeRoot, parseTreeRoot, viewer);\n\t\tfinal JTree tree = new JTree(nodeRoot);\n\t\ttree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);\n\n\t\ttree.addTreeSelectionListener(new TreeSelectionListener() {\n\t\t\t@Override\n\t\t\tpublic void valueChanged(TreeSelectionEvent e) {\n\n\t\t\t\tJTree selectedTree = (JTree) e.getSource();\n\t\t\t\tTreePath path = selectedTree.getSelectionPath();\n\t\t\t\tif (path!=null) {\n\t\t\t\t\tTreeNodeWrapper treeNode = (TreeNodeWrapper) path.getLastPathComponent();\n\n\t\t\t\t\t// Set the clicked AST.\n\t\t\t\t\tviewer.setTree((Tree) treeNode.getUserObject());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\ttreePanel.add(new JScrollPane(tree));\n\n\t\t// Create the pane for both the JTree and the AST\n\t\tfinal JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,\n\t\t\t\ttreePanel, contentPane);\n\n\t\tmainPane.add(splitPane, BorderLayout.CENTER);\n\n\t\tdialog.setContentPane(mainPane);\n\n\t\t// make viz\n        WindowListener exitListener = new WindowAdapter() {\n\t        @Override\n            public void windowClosing(WindowEvent e) {\n                prefs.putInt(DIALOG_WIDTH_PREFS_KEY, (int) dialog.getSize().getWidth());\n                prefs.putInt(DIALOG_HEIGHT_PREFS_KEY, (int) dialog.getSize().getHeight());\n                prefs.putDouble(DIALOG_X_PREFS_KEY, dialog.getLocationOnScreen().getX());\n                prefs.putDouble(DIALOG_Y_PREFS_KEY, dialog.getLocationOnScreen().getY());\n                prefs.putInt(DIALOG_DIVIDER_LOC_PREFS_KEY, splitPane.getDividerLocation());\n                prefs.putDouble(DIALOG_VIEWER_SCALE_PREFS_KEY, viewer.getScale());\n\n                dialog.setVisible(false);\n                dialog.dispose();\n            }\n        };\n        dialog.addWindowListener(exitListener);\n\t\tdialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\n\n        int width = prefs.getInt(DIALOG_WIDTH_PREFS_KEY, 600);\n        int height = prefs.getInt(DIALOG_HEIGHT_PREFS_KEY, 500);\n\t\tdialog.setPreferredSize(new Dimension(width, height));\n\t\tdialog.pack();\n\n\t\t// After pack(): set the divider at 1/3 (200/600) of the frame.\n        int dividerLocation = prefs.getInt(DIALOG_DIVIDER_LOC_PREFS_KEY, 200);\n\t\tsplitPane.setDividerLocation(dividerLocation);\n\n        if (prefs.getDouble(DIALOG_X_PREFS_KEY, -1) != -1) {\n            dialog.setLocation(\n                    (int)prefs.getDouble(DIALOG_X_PREFS_KEY, 100),\n                    (int)prefs.getDouble(DIALOG_Y_PREFS_KEY, 100)\n            );\n        }\n        else {\n            dialog.setLocationRelativeTo(null);\n        }\n\n\t\tdialog.setVisible(true);\n\t\treturn dialog;\n\t}\n\n\tprivate static void generatePNGFile(TreeViewer viewer, JFrame dialog) {\n\t\tBufferedImage bi = new BufferedImage(viewer.getSize().width,\n\t\t\t\t\t\t\t\t\t\t\t viewer.getSize().height,\n\t\t\t\t\t\t\t\t\t\t\t BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics g = bi.createGraphics();\n\t\tviewer.paint(g);\n\t\tg.dispose();\n\n\t\ttry {\n\t\t\tJFileChooser fileChooser = getFileChooser(\".png\", \"PNG files\");\n\n\t\t\tint returnValue = fileChooser.showSaveDialog(dialog);\n\t\t\tif (returnValue == JFileChooser.APPROVE_OPTION) {\n\t\t\t\tFile pngFile = fileChooser.getSelectedFile();\n\t\t\t\tImageIO.write(bi, \"png\", pngFile);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Try to open the parent folder using the OS' native file manager.\n\t\t\t\t\tDesktop.getDesktop().open(pngFile.getParentFile());\n\t\t\t\t}\n\t\t\t\tcatch (Exception ex) {\n\t\t\t\t\t// We could not launch the file manager: just show a popup that we\n\t\t\t\t\t// succeeded in saving the PNG file.\n\t\t\t\t\tJOptionPane.showMessageDialog(dialog, \"Saved PNG to: \" +\n\t\t\t\t\t\t\t\t\t\t\t\t  pngFile.getAbsolutePath());\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (Exception ex) {\n\t\t\tJOptionPane.showMessageDialog(dialog,\n\t\t\t\t\t\t\t\t\t\t  \"Could not export to PNG: \" + ex.getMessage(),\n\t\t\t\t\t\t\t\t\t\t  \"Error\",\n\t\t\t\t\t\t\t\t\t\t  JOptionPane.ERROR_MESSAGE);\n\t\t\tex.printStackTrace();\n\t\t}\n\t}\n\n\tprivate static JFileChooser getFileChooser(final String fileEnding,\n\t\t\t\t\t\t\t\t\t\t\t\tfinal String description) {\n\t\tFile suggestedFile = generateNonExistingFile(fileEnding);\n\t\tJFileChooser fileChooser = new JFileChooserConfirmOverwrite();\n\t\tfileChooser.setCurrentDirectory(suggestedFile.getParentFile());\n\t\tfileChooser.setSelectedFile(suggestedFile);\n\t\tFileFilter filter = new FileFilter() {\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File pathname) {\n\t\t\t\tif (pathname.isFile()) {\n\t\t\t\t\treturn pathname.getName().toLowerCase().endsWith(fileEnding);\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String getDescription() {\n\t\t\t\treturn description+\" (*\"+fileEnding+\")\";\n\t\t\t}\n\t\t};\n\t\tfileChooser.addChoosableFileFilter(filter);\n\t\tfileChooser.setFileFilter(filter);\n\t\treturn fileChooser;\n\t}\n\n\tprivate static void generateSVGFile(TreeViewer viewer, JFrame dialog) {\n\n\t\ttry {\n\t\t\tJFileChooser fileChooser = getFileChooser(\".svg\", \"SVG files\");\n\n\t\t\tint returnValue = fileChooser.showSaveDialog(dialog);\n\t\t\tif (returnValue == JFileChooser.APPROVE_OPTION) {\n\t\t\t\tFile svgFile = fileChooser.getSelectedFile();\n\t\t\t\t// save the new svg file here!\n\t\t\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(svgFile));\n\t\t\t\t// HACK: multiplying with 1.1 should be replaced wit an accurate number\n\t\t\t\twriter.write(\"<svg width=\\\"\" + viewer.getSize().getWidth() * 1.1 + \"\\\" height=\\\"\" + viewer.getSize().getHeight() * 1.1 + \"\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\">\");\n\t\t\t\tviewer.paintSVG(writer);\n\t\t\t\twriter.write(\"</svg>\");\n\t\t\t\twriter.flush();\n\t\t\t\twriter.close();\n\t\t\t\ttry {\n\t\t\t\t\t// Try to open the parent folder using the OS' native file manager.\n\t\t\t\t\tDesktop.getDesktop().open(svgFile.getParentFile());\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t// We could not launch the file manager: just show a popup that we\n\t\t\t\t\t// succeeded in saving the PNG file.\n\t\t\t\t\tJOptionPane.showMessageDialog(dialog, \"Saved SVG to: \"\n\t\t\t\t\t\t+ svgFile.getAbsolutePath());\n\t\t\t\t\tex.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception ex) {\n\t\t\tJOptionPane.showMessageDialog(dialog,\n\t\t\t\t\"Could not export to SVG: \" + ex.getMessage(),\n\t\t\t\t\"Error\",\n\t\t\t\tJOptionPane.ERROR_MESSAGE);\n\t\t\tex.printStackTrace();\n\t\t}\n\t}\n\n\tprivate static File generateNonExistingFile(String extension) {\n\n\t\tfinal String parent = \".\";\n\t\tfinal String name = \"antlr4_parse_tree\";\n\n\t\tFile file = new File(parent, name + extension);\n\n\t\tint counter = 1;\n\n\t\t// Keep looping until we create a File that does not yet exist.\n\t\twhile (file.exists()) {\n\t\t\tfile = new File(parent, name + \"_\" + counter + extension);\n\t\t\tcounter++;\n\t\t}\n\n\t\treturn file;\n\t}\n\n\tprivate static void fillTree(TreeNodeWrapper node, Tree tree, TreeViewer viewer) {\n\n\t\tif (tree == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (int i = 0; i < tree.getChildCount(); i++) {\n\n\t\t\tTree childTree = tree.getChild(i);\n\t\t\tTreeNodeWrapper childNode = new TreeNodeWrapper(childTree, viewer);\n\n\t\t\tnode.add(childNode);\n\n\t\t\tfillTree(childNode, childTree, viewer);\n\t\t}\n\t}\n\n\tprivate Dimension getScaledTreeSize() {\n\t\tDimension scaledTreeSize =\n\t\t\ttreeLayout.getBounds().getBounds().getSize();\n\t\tscaledTreeSize = new Dimension((int)(scaledTreeSize.width*scale),\n\t\t\t\t\t\t\t\t\t   (int)(scaledTreeSize.height*scale));\n\t\treturn scaledTreeSize;\n\t}\n\n\n\tpublic Future<JFrame> open() {\n\t\tfinal TreeViewer viewer = this;\n\t\tviewer.setScale(1.5);\n\t\tCallable<JFrame> callable = new Callable<JFrame>() {\n\t\t\tJFrame result;\n\n\t\t\t@Override\n\t\t\tpublic JFrame call() throws Exception {\n\t\t\t\tSwingUtilities.invokeAndWait(new Runnable() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tresult = showInDialog(viewer);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\treturn result;\n\t\t\t}\n\t\t};\n\n\t\tExecutorService executor = Executors.newSingleThreadExecutor();\n\n\t\ttry {\n\t\t\treturn executor.submit(callable);\n\t\t}\n\t\tfinally {\n\t\t\texecutor.shutdown();\n\t\t}\n\t}\n\n\tpublic void save(String fileName) throws IOException, PrintException {\n\t\tJFrame dialog = new JFrame();\n\t\tContainer contentPane = dialog.getContentPane();\n\t\t((JComponent) contentPane).setBorder(BorderFactory.createEmptyBorder(\n\t\t\t\t10, 10, 10, 10));\n\t\tcontentPane.add(this);\n\t\tcontentPane.setBackground(Color.white);\n\t\tdialog.pack();\n\t\tdialog.setLocationRelativeTo(null);\n\t\tdialog.dispose();\n\t\tGraphicsSupport.saveImage(this, fileName);\n\t}\n\n\t// ---------------------------------------------------\n\n\tprotected Rectangle2D.Double getBoundsOfNode(Tree node) {\n\t\treturn treeLayout.getNodeBounds().get(node);\n\t}\n\n\tprotected String getText(Tree tree) {\n\t\tString s = treeTextProvider.getText(tree);\n\t\ts = Utils.escapeWhitespace(s, true);\n\t\treturn s;\n\t}\n\n\tpublic TreeTextProvider getTreeTextProvider() {\n\t\treturn treeTextProvider;\n\t}\n\n\tpublic void setTreeTextProvider(TreeTextProvider treeTextProvider) {\n\t\tthis.treeTextProvider = treeTextProvider;\n\t}\n\n\tpublic void setFontSize(int sz) {\n\t\tfontSize = sz;\n\t\tfont = new Font(fontName, fontStyle, fontSize);\n\t}\n\n\tpublic void setFontName(String name) {\n\t\tfontName = name;\n\t\tfont = new Font(fontName, fontStyle, fontSize);\n\t}\n\n\t/** Slow for big lists of highlighted nodes */\n\tpublic void addHighlightedNodes(Collection<Tree> nodes) {\n\t\thighlightedNodes = new ArrayList<Tree>();\n\t\thighlightedNodes.addAll(nodes);\n\t}\n\n\tpublic void removeHighlightedNodes(Collection<Tree> nodes) {\n\t\tif ( highlightedNodes!=null ) {\n\t\t\t// only remove exact objects defined by ==, not equals()\n\t\t\tfor (Tree t : nodes) {\n\t\t\t\tint i = getHighlightedNodeIndex(t);\n\t\t\t\tif ( i>=0 ) highlightedNodes.remove(i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected boolean isHighlighted(Tree node) {\n\t\treturn getHighlightedNodeIndex(node) >= 0;\n\t}\n\n\tprotected int getHighlightedNodeIndex(Tree node) {\n\t\tif ( highlightedNodes==null ) return -1;\n\t\tfor (int i = 0; i < highlightedNodes.size(); i++) {\n\t\t\tTree t = highlightedNodes.get(i);\n\t\t\tif ( t == node ) return i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t@Override\n\tpublic Font getFont() {\n\t\treturn font;\n\t}\n\n\t@Override\n\tpublic void setFont(Font font) {\n\t\tthis.font = font;\n\t}\n\n\tpublic int getArcSize() {\n\t\treturn arcSize;\n\t}\n\n\tpublic void setArcSize(int arcSize) {\n\t\tthis.arcSize = arcSize;\n\t}\n\n\tpublic Color getBoxColor() {\n\t\treturn boxColor;\n\t}\n\n\tpublic void setBoxColor(Color boxColor) {\n\t\tthis.boxColor = boxColor;\n\t}\n\n\tpublic Color getHighlightedBoxColor() {\n\t\treturn highlightedBoxColor;\n\t}\n\n\tpublic void setHighlightedBoxColor(Color highlightedBoxColor) {\n\t\tthis.highlightedBoxColor = highlightedBoxColor;\n\t}\n\n\tpublic Color getBorderColor() {\n\t\treturn borderColor;\n\t}\n\n\tpublic void setBorderColor(Color borderColor) {\n\t\tthis.borderColor = borderColor;\n\t}\n\n\tpublic Color getTextColor() {\n\t\treturn textColor;\n\t}\n\n\tpublic void setTextColor(Color textColor) {\n\t\tthis.textColor = textColor;\n\t}\n\n\tprotected TreeForTreeLayout<Tree> getTree() {\n\t\treturn treeLayout.getTree();\n\t}\n\n\tpublic void setTree(Tree root) {\n\t\tif ( root!=null ) {\n\t\t\tboolean useIdentity = true; // compare node identity\n\t\t\tthis.treeLayout =\n\t\t\t\tnew TreeLayout<Tree>(getTreeLayoutAdaptor(root),\n\t\t\t\t\t\t\t\t\t new TreeViewer.VariableExtentProvide(this),\n\t\t\t\t\t\t\t\t\t new DefaultConfiguration<Tree>(gapBetweenLevels,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgapBetweenNodes),\n\t\t\t\t\t\t\t\t\t useIdentity);\n\t\t\t// Let the UI display this new AST.\n\t\t\tupdatePreferredSize();\n\t\t}\n\t\telse {\n\t\t\tthis.treeLayout = null;\n\t\t\trepaint();\n\t\t}\n\t}\n\n\t/** Get an adaptor for root that indicates how to walk ANTLR trees.\n\t *  Override to change the adapter from the default of {@link TreeLayoutAdaptor}  */\n\tpublic TreeForTreeLayout<Tree> getTreeLayoutAdaptor(Tree root) {\n\t\treturn new TreeLayoutAdaptor(root);\n\t}\n\n\tpublic double getScale() {\n\t\treturn scale;\n\t}\n\n\tpublic void setScale(double scale) {\n\t\tif(scale <= 0) {\n\t\t\tscale = 1;\n\t\t}\n\t\tthis.scale = scale;\n\t\tupdatePreferredSize();\n\t}\n\n\tpublic void setRuleNames(List<String> ruleNames) {\n\t\tsetTreeTextProvider(new DefaultTreeTextProvider(ruleNames));\n\t}\n\n\tprivate static class TreeNodeWrapper extends DefaultMutableTreeNode {\n\n\t\tfinal TreeViewer viewer;\n\n\t\tTreeNodeWrapper(Tree tree, TreeViewer viewer) {\n\t\t\tsuper(tree);\n\t\t\tthis.viewer = viewer;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn viewer.getText((Tree) this.getUserObject());\n\t\t}\n\t}\n\n\tprivate static class EmptyIcon implements Icon {\n\n\t\t@Override\n\t\tpublic int getIconWidth() {\n\t\t\treturn 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getIconHeight() {\n\t\t\treturn 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic void paintIcon(Component c, Graphics g, int x, int y) {\n\t\t\t/* Do nothing. */\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/gui/Trees.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.gui;\n\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.misc.Utils;\nimport org.antlr.v4.runtime.tree.Tree;\n\nimport javax.print.PrintException;\nimport javax.swing.*;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.Future;\n\npublic class Trees {\n\t/** Call this method to view a parse tree in a dialog box visually. */\n\tpublic static Future<JFrame> inspect(Tree t, List<String> ruleNames) {\n\t\tTreeViewer viewer = new TreeViewer(ruleNames, t);\n\t\treturn viewer.open();\n\t}\n\n\t/** Call this method to view a parse tree in a dialog box visually. */\n\tpublic static Future<JFrame> inspect(Tree t, Parser parser) {\n\t\tList<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;\n\t\treturn inspect(t, ruleNames);\n\t}\n\n\t/** Save this tree in a postscript file */\n\tpublic static void save(Tree t, Parser parser, String fileName)\n\t\tthrows IOException, PrintException\n\t{\n\t\tList<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;\n\t\tsave(t, ruleNames, fileName);\n\t}\n\n\t/** Save this tree in a postscript file using a particular font name and size */\n\tpublic static void save(Tree t, Parser parser, String fileName,\n\t\t\t\t\t String fontName, int fontSize)\n\t\tthrows IOException\n\t{\n\t\tList<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null;\n\t\tsave(t, ruleNames, fileName, fontName, fontSize);\n\t}\n\n\t/** Save this tree in a postscript file */\n\tpublic static void save(Tree t, List<String> ruleNames, String fileName)\n\t\tthrows IOException, PrintException\n\t{\n\t\twritePS(t, ruleNames, fileName);\n\t}\n\n\t/** Save this tree in a postscript file using a particular font name and size */\n\tpublic static void save(Tree t,\n\t                        List<String> ruleNames, String fileName,\n\t                        String fontName, int fontSize)\n\tthrows IOException\n\t{\n\t\twritePS(t, ruleNames, fileName, fontName, fontSize);\n\t}\n\n\tpublic static String getPS(Tree t, List<String> ruleNames,\n\t\t\t\t\t\t\t   String fontName, int fontSize)\n\t{\n\t\tTreePostScriptGenerator psgen =\n\t\t\tnew TreePostScriptGenerator(ruleNames, t, fontName, fontSize);\n\t\treturn psgen.getPS();\n\t}\n\n\tpublic static String getPS(Tree t, List<String> ruleNames) {\n\t\treturn getPS(t, ruleNames, \"Helvetica\", 11);\n\t}\n\n\tpublic static void writePS(Tree t, List<String> ruleNames,\n\t\t\t\t\t\t\t   String fileName,\n\t\t\t\t\t\t\t   String fontName, int fontSize)\n\t\tthrows IOException\n\t{\n\t\tString ps = getPS(t, ruleNames, fontName, fontSize);\n\t\tFileWriter f = new FileWriter(fileName);\n\t\tBufferedWriter bw = new BufferedWriter(f);\n\t\ttry {\n\t\t\tbw.write(ps);\n\t\t}\n\t\tfinally {\n\t\t\tbw.close();\n\t\t}\n\t}\n\n\tpublic static void writePS(Tree t, List<String> ruleNames, String fileName)\n\t\tthrows IOException\n\t{\n\t\twritePS(t, ruleNames, fileName, \"Helvetica\", 11);\n\t}\n\n\t/** Print out a whole tree in LISP form. Arg nodeTextProvider is used on the\n\t *  node payloads to get the text for the nodes.\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic static String toStringTree(Tree t, TreeTextProvider nodeTextProvider) {\n\t\tif ( t==null ) return \"null\";\n\t\tString s = Utils.escapeWhitespace(nodeTextProvider.getText(t), false);\n\t\tif ( t.getChildCount()==0 ) return s;\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append(\"(\");\n\t\ts = Utils.escapeWhitespace(nodeTextProvider.getText(t), false);\n\t\tbuf.append(s);\n\t\tbuf.append(' ');\n\t\tfor (int i = 0; i<t.getChildCount(); i++) {\n\t\t\tif ( i>0 ) buf.append(' ');\n\t\t\tbuf.append(toStringTree(t.getChild(i), nodeTextProvider));\n\t\t}\n\t\tbuf.append(\")\");\n\t\treturn buf.toString();\n\t}\n\n\tprivate Trees() {\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/misc/CharSupport.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.misc;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.Iterator;\n\n/** */\npublic class CharSupport {\n\t/** When converting ANTLR char and string literals, here is the\n\t *  value set of escape chars.\n\t */\n\tpublic final static int[] ANTLRLiteralEscapedCharValue = new int[255];\n\n\t/** Given a char, we need to be able to show as an ANTLR literal.\n\t */\n\tpublic final static String[] ANTLRLiteralCharValueEscape = new String[255];\n\n\tstatic {\n\t\tANTLRLiteralEscapedCharValue['n'] = '\\n';\n\t\tANTLRLiteralEscapedCharValue['r'] = '\\r';\n\t\tANTLRLiteralEscapedCharValue['t'] = '\\t';\n\t\tANTLRLiteralEscapedCharValue['b'] = '\\b';\n\t\tANTLRLiteralEscapedCharValue['f'] = '\\f';\n\t\tANTLRLiteralEscapedCharValue['\\\\'] = '\\\\';\n\t\tANTLRLiteralCharValueEscape['\\n'] = \"\\\\n\";\n\t\tANTLRLiteralCharValueEscape['\\r'] = \"\\\\r\";\n\t\tANTLRLiteralCharValueEscape['\\t'] = \"\\\\t\";\n\t\tANTLRLiteralCharValueEscape['\\b'] = \"\\\\b\";\n\t\tANTLRLiteralCharValueEscape['\\f'] = \"\\\\f\";\n\t\tANTLRLiteralCharValueEscape['\\\\'] = \"\\\\\\\\\";\n\t}\n\n\t/** Return a string representing the escaped char for code c.  E.g., If c\n\t *  has value 0x100, you will get \"\\\\u0100\".  ASCII gets the usual\n\t *  char (non-hex) representation.  Non-ASCII characters are spit out\n\t *  as \\\\uXXXX or \\\\u{XXXXXX} escapes.\n\t */\n\tpublic static String getANTLRCharLiteralForChar(int c) {\n\t\tString result;\n\t\tif ( c < Lexer.MIN_CHAR_VALUE ) {\n\t\t\tresult = \"<INVALID>\";\n\t\t}\n\t\telse {\n\t\t\tString charValueEscape = c < ANTLRLiteralCharValueEscape.length ? ANTLRLiteralCharValueEscape[c] : null;\n\t\t\tif (charValueEscape != null) {\n\t\t\t\tresult = charValueEscape;\n\t\t\t}\n\t\t\telse if (Character.UnicodeBlock.of((char) c) == Character.UnicodeBlock.BASIC_LATIN &&\n\t\t\t\t\t!Character.isISOControl((char) c)) {\n\t\t\t\tif (c == '\\\\') {\n\t\t\t\t\tresult = \"\\\\\\\\\";\n\t\t\t\t}\n\t\t\t\telse if (c == '\\'') {\n\t\t\t\t\tresult = \"\\\\'\";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tresult = Character.toString((char) c);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (c <= 0xFFFF) {\n\t\t\t\tresult = String.format(\"\\\\u%04X\", c);\n\t\t\t} else {\n\t\t\t\tresult = String.format(\"\\\\u{%06X}\", c);\n\t\t\t}\n\t\t}\n\t\treturn '\\'' + result + '\\'';\n\t}\n\n\t/** Given a literal like (the 3 char sequence with single quotes) 'a',\n\t *  return the int value of 'a'. Convert escape sequences here also.\n\t *  Return -1 if not single char.\n\t */\n\tpublic static int getCharValueFromGrammarCharLiteral(String literal) {\n\t\tif ( literal==null || literal.length()<3 ) return -1;\n\t\treturn getCharValueFromCharInGrammarLiteral(literal.substring(1,literal.length()-1));\n\t}\n\n\tpublic static String getStringFromGrammarStringLiteral(String literal) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tint i = 1; // skip first quote\n\t\tint n = literal.length()-1; // skip last quote\n\t\twhile ( i < n ) { // scan all but last quote\n\t\t\tint end = i+1;\n\t\t\tif ( literal.charAt(i) == '\\\\' ) {\n\t\t\t\tend = i+2;\n\t\t\t\tif ( i+1 < n && literal.charAt(i+1) == 'u' ) {\n\t\t\t\t\tif ( i+2 < n && literal.charAt(i+2) == '{' ) { // extended escape sequence\n\t\t\t\t\t\tend = i + 3;\n\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\tif ( end + 1 > n ) return null; // invalid escape sequence.\n\t\t\t\t\t\t\tchar charAt = literal.charAt(end++);\n\t\t\t\t\t\t\tif (charAt == '}') {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!Character.isDigit(charAt) && !(charAt >= 'a' && charAt <= 'f') && !(charAt >= 'A' && charAt <= 'F')) {\n\t\t\t\t\t\t\t\treturn null; // invalid escape sequence.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (end = i + 2; end < i + 6; end++) {\n\t\t\t\t\t\t\tif ( end>n ) return null; // invalid escape sequence.\n\t\t\t\t\t\t\tchar charAt = literal.charAt(end);\n\t\t\t\t\t\t\tif (!Character.isDigit(charAt) && !(charAt >= 'a' && charAt <= 'f') && !(charAt >= 'A' && charAt <= 'F')) {\n\t\t\t\t\t\t\t\treturn null; // invalid escape sequence.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( end>n ) return null; // invalid escape sequence.\n\t\t\tString esc = literal.substring(i, end);\n\t\t\tint c = getCharValueFromCharInGrammarLiteral(esc);\n\t\t\tif ( c==-1 ) {\n\t\t\t\treturn null; // invalid escape sequence.\n\t\t\t}\n\t\t\telse buf.appendCodePoint(c);\n\t\t\ti = end;\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\t/** Given char x or \\\\t or \\\\u1234 return the char value;\n\t *  Unnecessary escapes like '\\{' yield -1.\n\t */\n\tpublic static int getCharValueFromCharInGrammarLiteral(String cstr) {\n\t\tswitch ( cstr.length() ) {\n\t\t\tcase 1:\n\t\t\t\t// 'x'\n\t\t\t\treturn cstr.charAt(0); // no escape char\n\t\t\tcase 2:\n\t\t\t\tif ( cstr.charAt(0)!='\\\\' ) return -1;\n\t\t\t\t// '\\x'  (antlr lexer will catch invalid char)\n\t\t\t\tchar escChar = cstr.charAt(1);\n\t\t\t\tif (escChar == '\\'') return escChar; // escape quote only in string literals.\n\t\t\t\tint charVal = ANTLRLiteralEscapedCharValue[escChar];\n\t\t\t\tif (charVal == 0) return -1;\n\t\t\t\treturn charVal;\n\t\t\tcase 6:\n\t\t\t\t// '\\\\u1234' or '\\\\u{12}'\n\t\t\t\tif ( !cstr.startsWith(\"\\\\u\") ) return -1;\n\t\t\t\tint startOff;\n\t\t\t\tint endOff;\n\t\t\t\tif ( cstr.charAt(2) == '{' ) {\n\t\t\t\t\tstartOff = 3;\n\t\t\t\t\tendOff = cstr.indexOf('}');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstartOff = 2;\n\t\t\t\t\tendOff = cstr.length();\n\t\t\t\t}\n\t\t\t\treturn parseHexValue(cstr, startOff, endOff);\n\t\t\tdefault:\n\t\t\t\tif ( cstr.startsWith(\"\\\\u{\") ) {\n\t\t\t\t\treturn parseHexValue(cstr, 3, cstr.indexOf('}'));\n\t\t\t\t}\n\t\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic static int parseHexValue(String cstr, int startOff, int endOff) {\n\t\tif (startOff < 0 || endOff < 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tString unicodeChars = cstr.substring(startOff, endOff);\n\t\tint result = -1;\n\t\ttry {\n\t\t\tresult = Integer.parseInt(unicodeChars, 16);\n\t\t}\n\t\tcatch (NumberFormatException e) {\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static String capitalize(String s) {\n\t\treturn Character.toUpperCase(s.charAt(0)) + s.substring(1);\n\t}\n\n\tpublic static String getIntervalSetEscapedString(IntervalSet intervalSet) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tIterator<Interval> iter = intervalSet.getIntervals().iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tInterval interval = iter.next();\n\t\t\tbuf.append(getRangeEscapedString(interval.a, interval.b));\n\t\t\tif (iter.hasNext()) {\n\t\t\t\tbuf.append(\" | \");\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic static String getRangeEscapedString(int codePointStart, int codePointEnd) {\n\t\treturn codePointStart != codePointEnd\n\t\t\t\t? getANTLRCharLiteralForChar(codePointStart) + \"..\" + getANTLRCharLiteralForChar(codePointEnd)\n\t\t\t\t: getANTLRCharLiteralForChar(codePointStart);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/misc/EscapeSequenceParsing.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.misc;\n\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.unicode.UnicodeData;\n\nimport java.util.Objects;\n\n/**\n * Utility class to parse escapes like:\n *   \\\\n\n *   \\\\uABCD\n *   \\\\u{10ABCD}\n *   \\\\p{Foo}\n *   \\\\P{Bar}\n *   \\\\p{Baz=Blech}\n *   \\\\P{Baz=Blech}\n */\npublic abstract class EscapeSequenceParsing {\n\tpublic static class Result {\n\t\tpublic enum Type {\n\t\t\tINVALID,\n\t\t\tCODE_POINT,\n\t\t\tPROPERTY\n\t\t};\n\n\t\tpublic final Type type;\n\t\tpublic final int codePoint;\n\t\tpublic final IntervalSet propertyIntervalSet;\n\t\tpublic final int startOffset;\n\t\tpublic final int parseLength;\n\n\t\tpublic Result(Type type, int codePoint, IntervalSet propertyIntervalSet, int startOffset, int parseLength) {\n\t\t\tthis.type = type;\n\t\t\tthis.codePoint = codePoint;\n\t\t\tthis.propertyIntervalSet = propertyIntervalSet;\n\t\t\tthis.startOffset = startOffset;\n\t\t\tthis.parseLength = parseLength;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn String.format(\n\t\t\t\t\t\"%s type=%s codePoint=%d propertyIntervalSet=%s parseLength=%d\",\n\t\t\t\t\tsuper.toString(),\n\t\t\t\t\ttype,\n\t\t\t\t\tcodePoint,\n\t\t\t\t\tpropertyIntervalSet,\n\t\t\t\t\tparseLength);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object other) {\n\t\t\tif (!(other instanceof Result)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tResult that = (Result) other;\n\t\t\tif (this == that) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn Objects.equals(this.type, that.type) &&\n\t\t\t\tObjects.equals(this.codePoint, that.codePoint) &&\n\t\t\t\tObjects.equals(this.propertyIntervalSet, that.propertyIntervalSet) &&\n\t\t\t\tObjects.equals(this.parseLength, that.parseLength);\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn Objects.hash(type, codePoint, propertyIntervalSet, parseLength);\n\t\t}\n\t}\n\n\t/**\n\t * Parses a single escape sequence starting at {@code startOff}.\n\t *\n\t * Returns a type of INVALID if no valid escape sequence was found, a Result otherwise.\n\t */\n\tpublic static Result parseEscape(String s, int startOff) {\n\t\tint offset = startOff;\n\t\tif (offset + 2 > s.length() || s.codePointAt(offset) != '\\\\') {\n\t\t\treturn invalid(startOff, s.length()-1);\n\t\t}\n\t\t// Move past backslash\n\t\toffset++;\n\t\tint escaped = s.codePointAt(offset);\n\t\t// Move past escaped code point\n\t\toffset += Character.charCount(escaped);\n\t\tif (escaped == 'u') {\n\t\t\t// \\\\u{1} is the shortest we support\n\t\t\tif (offset + 3 > s.length()) {\n\t\t\t\treturn invalid(startOff, s.length()-1);\n\t\t\t}\n\t\t\tint hexStartOffset;\n\t\t\tint hexEndOffset; // appears to be exclusive\n\t\t\tif (s.codePointAt(offset) == '{') {\n\t\t\t\thexStartOffset = offset + 1;\n\t\t\t\thexEndOffset = s.indexOf('}', hexStartOffset);\n\t\t\t\tif (hexEndOffset == -1) {\n\t\t\t\t\treturn invalid(startOff, s.length()-1);\n\t\t\t\t}\n\t\t\t\toffset = hexEndOffset + 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (offset + 4 > s.length()) {\n\t\t\t\t\treturn invalid(startOff, s.length()-1);\n\t\t\t\t}\n\t\t\t\thexStartOffset = offset;\n\t\t\t\thexEndOffset = offset + 4;\n\t\t\t\toffset = hexEndOffset;\n\t\t\t}\n\t\t\tint codePointValue = CharSupport.parseHexValue(s, hexStartOffset, hexEndOffset);\n\t\t\tif (codePointValue == -1 || codePointValue > Character.MAX_CODE_POINT) {\n\t\t\t\treturn invalid(startOff, startOff+6-1);\n\t\t\t}\n\t\t\treturn new Result(\n\t\t\t\tResult.Type.CODE_POINT,\n\t\t\t\tcodePointValue,\n\t\t\t\tIntervalSet.EMPTY_SET,\n\t\t\t\tstartOff,\n\t\t\t\toffset - startOff);\n\t\t}\n\t\telse if (escaped == 'p' || escaped == 'P') {\n\t\t\t// \\p{L} is the shortest we support\n\t\t\tif (offset + 3 > s.length()) {\n\t\t\t\treturn invalid(startOff, s.length()-1);\n\t\t\t}\n\t\t\tif (s.codePointAt(offset) != '{') {\n\t\t\t\treturn invalid(startOff, offset);\n\t\t\t}\n\t\t\tint openBraceOffset = offset;\n\t\t\tint closeBraceOffset = s.indexOf('}', openBraceOffset);\n\t\t\tif (closeBraceOffset == -1) {\n\t\t\t\treturn invalid(startOff, s.length()-1);\n\t\t\t}\n\t\t\tString propertyName = s.substring(openBraceOffset + 1, closeBraceOffset);\n\t\t\tIntervalSet propertyIntervalSet = UnicodeData.getPropertyCodePoints(propertyName);\n\t\t\tif (propertyIntervalSet == null || propertyIntervalSet.isNil()) {\n\t\t\t\treturn invalid(startOff, closeBraceOffset);\n\t\t\t}\n\t\t\toffset = closeBraceOffset + 1;\n\t\t\tif (escaped == 'P') {\n\t\t\t\tpropertyIntervalSet = propertyIntervalSet.complement(IntervalSet.COMPLETE_CHAR_SET);\n\t\t\t}\n\t\t\treturn new Result(\n\t\t\t\tResult.Type.PROPERTY,\n\t\t\t\t-1,\n\t\t\t\tpropertyIntervalSet,\n\t\t\t\tstartOff,\n\t\t\t\toffset - startOff);\n\t\t}\n\t\telse if (escaped < CharSupport.ANTLRLiteralEscapedCharValue.length) {\n\t\t\tint codePoint = CharSupport.ANTLRLiteralEscapedCharValue[escaped];\n\t\t\tif (codePoint == 0) {\n\t\t\t\tif (escaped != ']' && escaped != '-') { // escape ']' and '-' only in char sets.\n\t\t\t\t\treturn invalid(startOff, startOff+1);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcodePoint = escaped;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Result(\n\t\t\t\tResult.Type.CODE_POINT,\n\t\t\t\tcodePoint,\n\t\t\t\tIntervalSet.EMPTY_SET,\n\t\t\t\tstartOff,\n\t\t\t\toffset - startOff);\n\t\t}\n\t\telse {\n\t\t\treturn invalid(startOff,s.length()-1);\n\t\t}\n\t}\n\n\tprivate static Result invalid(int start, int stop) { // start..stop is inclusive\n\t\treturn new Result(\n\t\t\tResult.Type.INVALID,\n\t\t\t0,\n\t\t\tIntervalSet.EMPTY_SET,\n\t\t\tstart,\n\t\t\tstop - start + 1);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/misc/FrequencySet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.misc;\n\nimport java.util.HashMap;\n\n/** Count how many of each key we have; not thread safe */\npublic class FrequencySet<T> extends HashMap<T, MutableInt> {\n\tpublic int count(T key) {\n\t\tMutableInt value = get(key);\n\t\tif (value == null) return 0;\n\t\treturn value.v;\n\t}\n\tpublic void add(T key) {\n\t\tMutableInt value = get(key);\n\t\tif (value == null) {\n\t\t\tvalue = new MutableInt(1);\n\t\t\tput(key, value);\n\t\t}\n\t\telse {\n\t\t\tvalue.v++;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/misc/Graph.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.misc;\n\nimport org.antlr.v4.runtime.misc.OrderedHashSet;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n/** A generic graph with edges; Each node as a single Object payload.\n *  This is only used to topologically sort a list of file dependencies\n *  at the moment.\n */\npublic class Graph<T> {\n\n\tpublic static class Node<T> {\n\t\tpublic T payload;\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tpublic List<Node<T>> edges = Collections.EMPTY_LIST; // points at which nodes?\n\n\t\tpublic Node(T payload) { this.payload = payload; }\n\n\t\tpublic void addEdge(Node<T> n) {\n\t\t\tif ( edges==Collections.EMPTY_LIST ) edges = new ArrayList<Node<T>>();\n\t\t\tif ( !edges.contains(n) ) edges.add(n);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() { return payload.toString(); }\n\t}\n\n\t/** Map from node payload to node containing it */\n\tprotected Map<T,Node<T>> nodes = new LinkedHashMap<T,Node<T>>();\n\n\tpublic void addEdge(T a, T b) {\n\t\t//System.out.println(\"add edge \"+a+\" to \"+b);\n\t\tNode<T> a_node = getNode(a);\n\t\tNode<T> b_node = getNode(b);\n\t\ta_node.addEdge(b_node);\n\t}\n\n\tpublic Node<T> getNode(T a) {\n\t\tNode<T> existing = nodes.get(a);\n\t\tif ( existing!=null ) return existing;\n\t\tNode<T> n = new Node<T>(a);\n\t\tnodes.put(a, n);\n\t\treturn n;\n\t}\n\n\t/** DFS-based topological sort.  A valid sort is the reverse of\n\t *  the post-order DFA traversal.  Amazingly simple but true.\n\t *  For sorting, I'm not following convention here since ANTLR\n\t *  needs the opposite.  Here's what I assume for sorting:\n\t *\n\t *    If there exists an edge u -&gt; v then u depends on v and v\n\t *    must happen before u.\n\t *\n\t *  So if this gives nonreversed postorder traversal, I get the order\n\t *  I want.\n\t */\n\tpublic List<T> sort() {\n\t\tSet<Node<T>> visited = new OrderedHashSet<Node<T>>();\n\t\tArrayList<T> sorted = new ArrayList<T>();\n\t\twhile ( visited.size() < nodes.size() ) {\n\t\t\t// pick any unvisited node, n\n\t\t\tNode<T> n = null;\n\t\t\tfor (Node<T> tNode : nodes.values()) {\n\t\t\t\tn = tNode;\n\t\t\t\tif ( !visited.contains(n) ) break;\n\t\t\t}\n\t\t\tif (n!=null) { // if at least one unvisited\n\t\t\t\tDFS(n, visited, sorted);\n\t\t\t}\n\t\t}\n\t\treturn sorted;\n\t}\n\n\tpublic void DFS(Node<T> n, Set<Node<T>> visited, ArrayList<T> sorted) {\n\t\tif ( visited.contains(n) ) return;\n\t\tvisited.add(n);\n\t\tif ( n.edges!=null ) {\n\t\t\tfor (Node<T> target : n.edges) {\n\t\t\t\tDFS(target, visited, sorted);\n\t\t\t}\n\t\t}\n\t\tsorted.add(n.payload);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/misc/MutableInt.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.misc;\n\npublic class MutableInt extends Number implements Comparable<MutableInt> {\n\tpublic int v;\n\n\tpublic MutableInt(int v) { this.v = v; }\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif ( o instanceof Number ) return v == ((Number)o).intValue();\n\t\treturn false;\n\t}\n\n\t@Override public int hashCode() { return v; }\n\n\t@Override public int compareTo(MutableInt o) { return v-o.intValue(); }\n\t@Override public int intValue() { return v; }\n\t@Override public long longValue() { return v; }\n\t@Override public float floatValue() { return v; }\n\t@Override public double doubleValue() { return v; }\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.valueOf(v);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/misc/OrderedHashMap.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.misc;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** I need the get-element-i functionality so I'm subclassing\n *  LinkedHashMap.\n */\npublic class OrderedHashMap<K,V> extends LinkedHashMap<K,V> {\n\t/** Track the elements as they are added to the set */\n\tprotected List<K> elements = new ArrayList<K>();\n\n\tpublic K getKey(int i) { return elements.get(i); }\n\n\tpublic V getElement(int i) { return get(elements.get(i)); }\n\n\t@Override\n\tpublic V put(K key, V value) {\n\t\telements.add(key);\n\t\treturn super.put(key, value);\n\t}\n\n\t@Override\n\tpublic void putAll(Map<? extends K, ? extends V> m) {\n\t\tfor (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {\n\t\t\tput(entry.getKey(), entry.getValue());\n\t\t}\n\t}\n\n\t@Override\n\tpublic V remove(Object key) {\n\t\telements.remove(key);\n\t\treturn super.remove(key);\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\telements.clear();\n\t\tsuper.clear();\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/misc/Utils.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.misc;\n\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.*;\n\n/** */\npublic class Utils {\n\tpublic static final int INTEGER_POOL_MAX_VALUE = 1000;\n\n\tpublic interface Filter<T> {\n\t\tboolean select(T t);\n\t}\n\n\tpublic interface Func0<TResult> {\n\t\tTResult exec();\n\t}\n\n\tpublic interface Func1<T1, TResult> {\n\t\tTResult exec(T1 arg1);\n\t}\n\n    public static String stripFileExtension(String name) {\n        if ( name==null ) return null;\n        int lastDot = name.lastIndexOf('.');\n        if ( lastDot<0 ) return name;\n        return name.substring(0, lastDot);\n    }\n\n\tpublic static String join(Object[] a, String separator) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (int i=0; i<a.length; i++) {\n\t\t\tObject o = a[i];\n\t\t\tbuf.append(o.toString());\n\t\t\tif ( (i+1)<a.length ) {\n\t\t\t\tbuf.append(separator);\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic static String sortLinesInString(String s) {\n\t\tString lines[] = s.split(\"\\n\");\n\t\tArrays.sort(lines);\n\t\tList<String> linesL = Arrays.asList(lines);\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (String l : linesL) {\n\t\t\tbuf.append(l);\n\t\t\tbuf.append('\\n');\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic static <T extends GrammarAST> List<String> nodesToStrings(List<T> nodes) {\n\t\tif ( nodes == null ) return null;\n\t\tList<String> a = new ArrayList<String>();\n\t\tfor (T t : nodes) a.add(t.getText());\n\t\treturn a;\n\t}\n\n//\tpublic static <T> List<T> list(T... values) {\n//\t\tList<T> x = new ArrayList<T>(values.length);\n//\t\tfor (T v : values) {\n//\t\t\tif ( v!=null ) x.add(v);\n//\t\t}\n//\t\treturn x;\n//\t}\n\n\tpublic static void writeSerializedATNIntegerHistogram(String filename, IntegerList serializedATN) {\n\t\tHashMap<Integer, Integer> histo = new HashMap<>();\n\t\tfor (int i : serializedATN.toArray()) {\n\t\t\tif ( histo.containsKey(i) ) {\n\t\t\t\thisto.put(i, histo.get(i) + 1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\thisto.put(i, 1);\n\t\t\t}\n\t\t}\n\t\tTreeMap<Integer,Integer> sorted = new TreeMap<>(histo);\n\n\t\tString output = \"\";\n\t\toutput += \"value,count\\n\";\n\t\tfor (int key : sorted.keySet()) {\n\t\t\toutput += key+\",\"+sorted.get(key)+\"\\n\";\n\t\t}\n\t\ttry {\n\t\t\tFiles.write(Paths.get(filename), output.getBytes(StandardCharsets.UTF_8));\n\t\t}\n\t\tcatch (IOException ioe) {\n\t\t\tSystem.err.println(ioe);\n\t\t}\n\t}\n\n\tpublic static String capitalize(String s) {\n\t\treturn Character.toUpperCase(s.charAt(0)) + s.substring(1);\n\t}\n\n\tpublic static String decapitalize(String s) {\n\t\treturn Character.toLowerCase(s.charAt(0)) + s.substring(1);\n\t}\n\n\t/** apply methodName to list and return list of results. method has\n\t *  no args.  This pulls data out of a list essentially.\n\t */\n\tpublic static <From,To> List<To> select(List<From> list, Func1<From, To> selector) {\n\t\tif ( list==null ) return null;\n\t\tList<To> b = new ArrayList<To>();\n\t\tfor (From f : list) {\n\t\t\tb.add(selector.exec(f));\n\t\t}\n\t\treturn b;\n\t}\n\n\t/** Find exact object type or subclass of cl in list */\n\tpublic static <T> T find(List<?> ops, Class<T> cl) {\n\t\tfor (Object o : ops) {\n\t\t\tif ( cl.isInstance(o) ) return cl.cast(o);\n//\t\t\tif ( o.getClass() == cl ) return o;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static <T> int indexOf(List<? extends T> elems, Filter<T> filter) {\n\t\tfor (int i=0; i<elems.size(); i++) {\n\t\t\tif ( filter.select(elems.get(i)) ) return i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic static <T> int lastIndexOf(List<? extends T> elems, Filter<T> filter) {\n\t\tfor (int i=elems.size()-1; i>=0; i--) {\n\t\t\tif ( filter.select(elems.get(i)) ) return i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic static void setSize(List<?> list, int size) {\n\t\tif (size < list.size()) {\n\t\t\tlist.subList(size, list.size()).clear();\n\t\t}\n\t\telse {\n\t\t\twhile (size > list.size()) {\n\t\t\t\tlist.add(null);\n\t\t\t}\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ANTLRLexer.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// File      : A3Lexer.g\n// Author    : Jim Idle (jimi@temporal-wave.com)\n// Copyright : Free BSD - See @header clause below\n// Version   : First implemented as part of ANTLR 3.2 this is the self\n//             hosting ANTLR 3 Lexer.\n//\n// Description\n// -----------\n// This is the definitive lexer grammar for parsing ANTLR V3.x.x grammars. All other\n// grammars are derived from this grammar via source code control integration (perforce)\n// or by the gdiff tool.\n//\n// This grammar and its associated grammars A3Parser.g and A3Walker.g exhibit the following\n// traits, which are recommended for all production quality grammars:\n//\n// 1) They are separate grammars, not composite grammars;\n// 2) They implement all supporting methods in a superclass (at least this is recommended\n//    for language targets that support inheritance;\n// 3) All errors are pushed as far down the parsing chain as possible, which means\n//    that the lexer tries to defer error reporting to the parser, and the parser\n//    tries to defer error reporting to a semantic phase consisting of a single\n//    walk of the AST. The reason for this is that the error messages produced\n//    from later phases of the parse will generally have better context and so\n//    be more useful to the end user. Consider the message: \"Syntax error at 'options'\"\n//    vs: \"You cannot specify two options{} sections in a single grammar file\".\n// 4) The lexer is 'programmed' to catch common mistakes such as unterminated literals\n//    and report them specifically and not just issue confusing lexer mismatch errors.\n//\n\n/** Read in an ANTLR grammar and build an AST.  Try not to do\n *  any actions, just build the tree.\n *\n *  The phases are:\n *\n *\t\tA3Lexer.g (this file)\n *              A3Parser.g\n *              A3Verify.g (derived from A3Walker.g)\n *\t\tassign.types.g\n *\t\tdefine.g\n *\t\tbuildnfa.g\n *\t\tantlr.print.g (optional)\n *\t\tcodegen.g\n *\n *  Terence Parr\n *  University of San Francisco\n *  2005\n *  Jim Idle (this v3 grammar)\n *  Temporal Wave LLC\n *  2009\n */\nlexer grammar ANTLRLexer;\n\n// ==============================================================================\n// Note that while this grammar does not care about order of constructs\n// that don't really matter, such as options before @header etc, it must first\n// be parsed by the original v2 parser, before it replaces it. That parser does\n// care about order of structures. Hence we are constrained by the v2 parser\n// for at least the first bootstrap release that causes this parser to replace\n// the v2 version.\n// ==============================================================================\n\n// -------\n// Options\n//\n// V3 option directives to tell the tool what we are asking of it for this\n// grammar.\n//\noptions {\n\n\t// Target language is Java, which is the default but being specific\n\t// here as this grammar is also meant as a good example grammar for\n\t// for users.\n\t//\n\tlanguage      = Java;\n\n\t// The super class that this lexer should expect to inherit from, and\n\t// which contains any and all support routines for the lexer. This is\n\t// commented out in this baseline (definitive or normative grammar)\n\t// - see the ANTLR tool implementation for hints on how to use the super\n\t//   class\n\t//\n\t//superclass    = AbstractA3Lexer;\n}\n\ntokens { SEMPRED; TOKEN_REF; RULE_REF; LEXER_CHAR_SET; ARG_ACTION; }\n\n// Include the copyright in this source and also the generated source\n//\n@lexer::header {\n/*\n [The \"BSD licence\"]\n Copyright (c) 2005-2009 Terence Parr\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\npackage org.antlr.v4.parse;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.runtime.misc.Interval;\n}\n\n\n@members {\n\tpublic static final int COMMENTS_CHANNEL = 2;\n\n    public CommonTokenStream tokens; // track stream we push to; need for context info\n    public boolean isLexerRule = false;\n\n\tpublic void grammarError(ErrorType etype, org.antlr.runtime.Token token, Object... args) { }\n\n\t/** scan backwards from current point in this.tokens list\n\t *  looking for the start of the rule or subrule.\n\t *  Return token or null if for some reason we can't find the start.\n\t */\n\tpublic Token getRuleOrSubruleStartToken() {\n\t\tif (tokens == null) return null;\n\t\tint i = tokens.index();\n\t\tint n = tokens.size();\n\t\tif (i >= n) i = n - 1; // seems index == n as we lex\n\t\tboolean withinOptionsBlock = false;\n\t\twhile (i >= 0 && i < n) {\n\t\t\tint ttype = tokens.get(i).getType();\n\t\t\tif (withinOptionsBlock) {\n\t\t\t\t// Ignore rule options content\n\t\t\t\tif (ttype == OPTIONS) {\n\t\t\t\t\twithinOptionsBlock = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (ttype == RBRACE) {\n\t\t\t\t\twithinOptionsBlock = true;\n\t\t\t\t}\n\t\t\t\telse if (ttype == LPAREN || ttype == TOKEN_REF || ttype == RULE_REF) {\n\t\t\t\t\treturn tokens.get(i);\n\t\t\t\t}\n\t\t\t}\n\t\t\ti--;\n\t\t}\n\t\treturn null;\n\t}\n}\n\n// --------\n// Comments\n//\n// ANTLR comments can be multi or single line and we don't care\n// which particularly. However we also accept Javadoc style comments\n// of the form: /** ... */ and we do take care to distinguish those\n// from ordinary multi-line comments\n// Note how we guide the lexical PATH because we want to issue a descriptive\n// error message in case of a standalone '/' character, which makes no\n// sense in ANTLR source code. We alo trap unterminated multi-line comments\n//\nfragment DOC_COMMENT : ;\nCOMMENT\n@init {\n\n\t// Record the start line and offsets as if we need to report an\n\t// unterminated comment, then we want to show the start of the comment\n\t// we think is broken, not the end, where people will have to try and work\n\t// it out themselves.\n\t//\n\tint startLine = $line;\n\tint offset    = getCharPositionInLine();\n}\n    : // Eat the first character only, then see if we have a comment\n      // or something silly.\n      //\n      '/'  // Comment introducer\n\n      (\n          // Single line comment, possibly with embedded src/line directives\n          // in a similar style to the C pre-processor, allowing generated\n          // code to refer the programmer back to the original source code\n          // in case of error.\n          //\n          '/'\n            (\n                (' $ANTLR')=> ' $ANTLR' SRC\n              | ~NLCHARS*\n            )\n\n         | // Multi-line comment, which may be a documentation comment\n           // if it starts /** (note that we protect against accidentally\n           // recognizing a comment /**/ as a documentation comment\n           //\n           '*' (\n           \t\t\t  { input.LA(2) != '/'}?=> '*' { $type = DOC_COMMENT; }\n           \t\t\t| { true }?=>  // Required to cover all alts with predicates\n           \t   )\n\n               // Should we support embedded multiline comments here?\n               //\n               (\n                   // Pick out end of multiline comment and exit the loop\n                   // if we find it.\n                   //\n               \t   {    !(input.LA(1) == '*' && input.LA(2) == '/') }?\n\n              \t      // Anything else other than the non-greedy match of\n              \t      // the comment close sequence\n              \t      //\n              \t      .\n               )*\n            (\n                 // Look for the comment terminator, but if it is accidentally\n                 // unterminated, then we will hit EOF, which will trigger the\n                 // epsilon alt and hence we can issue an error message relative\n                 // to the start of the unterminated multi-line comment\n                 //\n                 '*/'\n\n               | // Unterminated comment!\n                 //\n                 {\n                   // ErrorManager.msg(Msg.UNTERMINATED_DOC_COMMENT, startLine, offset, $pos, startLine, offset, $pos, (Object)null);\n                 }\n             )\n\n         | // There was nothing that made sense following the opening '/' and so\n           // we issue an error regarding the malformed comment\n           //\n           {\n           \t // TODO: Insert error message relative to comment start\n             //\n           }\n       )\n       {\n         // We do not wish to pass the comments in to the parser. If you are\n         // writing a formatter then you will want to preserve the comments off\n         // channel, but could just skip and save token space if not.\n         //\n         $channel=COMMENTS_CHANNEL;\n       }\n    ;\n\nARG_OR_CHARSET\noptions {k=1;}\n    :   {isLexerRule}?=> LEXER_CHAR_SET {$type=LEXER_CHAR_SET;}\n    |   {!isLexerRule}?=> ARG_ACTION\n        {\n        $type=ARG_ACTION;\n        // Set the token text to our gathered string minus outer [ ]\n        String t = $text;\n        t = t.substring(1,t.length()-1);\n        setText(t);\n        }\n    ;\n\nfragment\nLEXER_CHAR_SET\n\t:\t'['\n\t\t(\t'\\\\' ~('\\r'|'\\n')\n\t\t|\t~('\\r'|'\\n'|'\\\\'|']')\n\t\t)*\n\t\t']'\n\t;\n\n// --------------\n// Argument specs\n//\n// Certain argument lists, such as those specifying call parameters\n// to a rule invocation, or input parameters to a rule specification\n// are contained within square brackets. In the lexer we consume them\n// all at once and sort them out later in the grammar analysis.\n//\nfragment\nARG_ACTION\n\t: '['\n         (\n             ARG_ACTION\n\n           | ('\"')=>ACTION_STRING_LITERAL\n\n           | ('\\'')=>ACTION_CHAR_LITERAL\n\n           | ~('['|']')\n\t     )*\n\n       ']'\n\t;\n\n// -------\n// Actions\n//\n// Other than making sure to distinguish between { and } embedded\n// within what we have assumed to be literals in the action code, the\n// job of the lexer is merely to gather the code within the action\n// (delimited by {}) and pass it to the parser as a single token.\n// We know that this token will be asked for its text somewhere\n// in the upcoming parse, so setting the text here to exclude\n// the delimiting {} is no additional overhead.\n//\nACTION\n\t:\tNESTED_ACTION (\t'?' {$type = SEMPRED;} )?\n\t;\n\n// ----------------\n// Action structure\n//\n// Many language targets use {} as block delimiters and so we\n// must recursively match {} delimited blocks to balance the\n// braces. Additionally, we must make some assumptions about\n// literal string representation in the target language. We assume\n// that they are delimited by ' or \" and so consume these\n// in their own alts so as not to inadvertently match {}.\n// This rule calls itself on matching a {\n//\nfragment\nNESTED_ACTION\n@init {\n\n\t// Record the start line and offsets as if we need to report an\n\t// unterminated block, then we want to show the start of the comment\n\t// we think is broken, not the end, where people will have to try and work\n\t// it out themselves.\n\t//\n\tint startLine = getLine();\n\tint offset    = getCharPositionInLine();\n}\n\n    : // Action and other blocks start with opening {\n      //\n\t  '{'\n      (\n\t    // And now we can match one of a number of embedded\n\t    // elements within the action until we find a\n\t    // } that balances the opening {. If we do not find\n\t    // the balanced } then we will hit EOF and can issue\n\t    // an error message about the brace that we believe to\n\t    // be mismatched. This won't be foolproof but we will\n\t    // be able to at least report an error against the\n\t    // opening brace that we feel is in error and this will\n\t    // guide the user to the correction as best we can.\n\t    //\n\n\n          // An embedded {} block\n\t      //\n\t      NESTED_ACTION\n\n        | // What appears to be a literal\n          //\n          ACTION_CHAR_LITERAL\n\n        | // We have assumed that the target language has C/Java\n          // type comments.\n          //\n          COMMENT\n\n        | // What appears to be a literal\n          //\n          ACTION_STRING_LITERAL\n\n\t    | // What appears to be an escape sequence\n\t      //\n\t      ACTION_ESC\n\n\t    | // Some other single character that is not\n\t      // handled above\n\t      //\n\t      ~('\\\\'|'\"'|'\\''|'/'|'{'|'}')\n\n      )*\n\n\t(\n\t    // Correctly balanced closing brace\n\t    //\n\t    '}'\n\n\t  | // Looks like have an imbalanced {} block, report\n\t    // with respect to the opening brace.\n\t    //\n\t    {\n\t        // TODO: Report imbalanced {}\n\t        System.out.println(\"Block starting  at line \" + startLine + \" offset \" + (offset+1) + \" contains imbalanced {} or is missing a }\");\n\t    }\n\t)\n   ;\n\n\n// Keywords\n// --------\n// Keywords may not be used as labels for rules or in any other context\n// where they would be ambiguous with the keyword vs some other identifier\n// OPTIONS, TOKENS, and CHANNELS must also consume the opening brace that captures\n// their option block, as this is the easiest way to parse it separate\n// to an ACTION block, despite it using the same {} delimiters.\n//\nOPTIONS      : 'options'  WSNLCHARS* '{'  ;\nTOKENS_SPEC  : 'tokens'   WSNLCHARS* '{'  ;\nCHANNELS     : 'channels' WSNLCHARS* '{'  ;\n\nIMPORT       : 'import'               ;\nFRAGMENT     : 'fragment'             ;\nLEXER        : 'lexer'                ;\nPARSER       : 'parser'               ;\nGRAMMAR      : 'grammar'              ;\nRETURNS      : 'returns'              ;\nLOCALS       : 'locals'               ;\nTHROWS       : 'throws'               ;\nCATCH        : 'catch'                ;\nFINALLY      : 'finally'              ;\nMODE         : 'mode'                 ;\n\n// -----------\n// Punctuation\n//\n// Character sequences used as separators, delimiters, operators, etc\n//\nCOLON        : ':'\n               {\n               // scan backwards, looking for a RULE_REF or TOKEN_REF.\n               // which would indicate the start of a rule definition.\n               // If we see a LPAREN, then it's the start of the subrule.\n               // this.tokens is the token string we are pushing into, so\n               // just loop backwards looking for a rule definition. Then\n               // we set isLexerRule.\n               Token t = getRuleOrSubruleStartToken();\n               if ( t!=null ) {\n                    if ( t.getType()==RULE_REF ) isLexerRule = false;\n                    else if ( t.getType()==TOKEN_REF ) isLexerRule = true;\n                    // else must be subrule; don't alter context\n               }\n               }\n             ;\nCOLONCOLON   : '::'                   ;\nCOMMA        : ','                    ;\nSEMI         : ';'                    ;\nLPAREN       : '('                    ;\nRPAREN       : ')'                    ;\nRARROW       : '->'                   ;\nLT           : '<'                    ;\nGT           : '>'                    ;\nASSIGN       : '='                    ;\nQUESTION     : '?'                    ;\nSTAR         : '*'                    ;\nPLUS         : '+'                    ;\nPLUS_ASSIGN  : '+='                   ;\nOR           : '|'                    ;\nDOLLAR       : '$'                    ;\nDOT\t\t     : '.'                    ; // can be WILDCARD or DOT in qid or imported rule ref\nRANGE        : '..'                   ;\nAT           : '@'                    ;\nPOUND        : '#'                    ;\nNOT          : '~'                    ;\nRBRACE       : '}'                    ;\n\n/** Allow unicode rule/token names */\nID\t\t\t:\ta=NameStartChar NameChar*\n\t\t\t\t{\n\t\t\t\tif ( Grammar.isTokenName($a.text) ) $type = TOKEN_REF;\n\t\t\t\telse $type = RULE_REF;\n\t\t\t\t}\n\t\t\t;\n\nfragment\nNameChar    :   NameStartChar\n            |   '0'..'9'\n            |   '_'\n            |   '\\u00B7'\n            |   '\\u0300'..'\\u036F'\n            |   '\\u203F'..'\\u2040'\n            ;\n\nfragment\nNameStartChar\n            :   'A'..'Z' | 'a'..'z'\n            |   '\\u00C0'..'\\u00D6'\n            |   '\\u00D8'..'\\u00F6'\n            |   '\\u00F8'..'\\u02FF'\n            |   '\\u0370'..'\\u037D'\n            |   '\\u037F'..'\\u1FFF'\n            |   '\\u200C'..'\\u200D'\n            |   '\\u2070'..'\\u218F'\n            |   '\\u2C00'..'\\u2FEF'\n            |   '\\u3001'..'\\uD7FF'\n            |   '\\uF900'..'\\uFDCF'\n            |   '\\uFDF0'..'\\uFEFE'\n            |   '\\uFF00'..'\\uFFFD'\n            ; // ignores | ['\\u10000-'\\uEFFFF] ;\n\n// ----------------------------\n// Literals embedded in actions\n//\n// Note that we have made the assumption that the language used within\n// actions uses the fairly standard \" and ' delimiters for literals and\n// that within these literals, characters are escaped using the \\ character.\n// There are some languages which do not conform to this in all cases, such\n// as by using /string/ and so on. We will have to deal with such cases if\n// if they come up in targets.\n//\n\n// Within actions, or other structures that are not part of the ANTLR\n// syntax, we may encounter literal characters. Within these, we do\n// not want to inadvertently match things like '}' and so we eat them\n// specifically. While this rule is called CHAR it allows for the fact that\n// some languages may use/allow ' as the string delimiter.\n//\nfragment\nACTION_CHAR_LITERAL\n\t:\t'\\'' (('\\\\')=>ACTION_ESC | ~'\\'' )* '\\''\n\t;\n\n// Within actions, or other structures that are not part of the ANTLR\n// syntax, we may encounter literal strings. Within these, we do\n// not want to inadvertently match things like '}' and so we eat them\n// specifically.\n//\nfragment\nACTION_STRING_LITERAL\n\t:\t'\"' (('\\\\')=>ACTION_ESC | ~'\"')* '\"'\n\t;\n\n// Within literal strings and characters that are not part of the ANTLR\n// syntax, we must allow for escaped character sequences so that we do not\n// inadvertently recognize the end of a string or character when the terminating\n// delimiter has been escaped.\n//\nfragment\nACTION_ESC\n\t: '\\\\' .\n\t;\n\n// -------\n// Integer\n//\n// Obviously (I hope) match an arbitrary long sequence of digits.\n//\nINT : ('0'..'9')+\n    ;\n\n// -----------\n// Source spec\n//\n// A fragment rule for picking up information about an originating\n// file from which the grammar we are parsing has been generated. This allows\n// ANTLR to report errors against the originating file and not the generated\n// file.\n//\nfragment\nSRC : 'src' WSCHARS+ file=ACTION_STRING_LITERAL WSCHARS+ line=INT\n      {\n         // TODO: Add target specific code to change the source file name and current line number\n         //\n      }\n    ;\n\n// --------------\n// Literal string\n//\n// ANTLR makes no distinction between a single character literal and a\n// multi-character string. All literals are single quote delimited and\n// may contain unicode escape sequences of the form \\uxxxx or \\u{xxxxxx},\n// where x is a valid hexadecimal number.\nSTRING_LITERAL\n    :  '\\'' ( ( ESC_SEQ | ~('\\\\'|'\\''|'\\r'|'\\n') ) )*\n       (    '\\''\n       |    // Unterminated string literal\n            {\n            Token t = new CommonToken(input, state.type, state.channel, state.tokenStartCharIndex, getCharIndex()-1);\n            t.setLine(state.tokenStartLine);\n            t.setText(state.text);\n            t.setCharPositionInLine(state.tokenStartCharPositionInLine);\n            grammarError(ErrorType.UNTERMINATED_STRING_LITERAL, t);\n            }\n       )\n    ;\n\n// A valid hex digit specification\n//\nfragment\nHEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;\n\n// Any kind of escaped character that we can embed within ANTLR\n// literal strings.\n//\nfragment\nESC_SEQ\n    : '\\\\'\n        (\n              // The standard escaped character set such as tab, newline, etc...\n    \t\t  'b'|'t'|'n'|'f'|'r'|'\\''|'\\\\'\n\n    \t    | // A Java style Unicode escape sequence\n    \t      UNICODE_ESC\n\n            | // A Swift/Hack style Unicode escape sequence\n              UNICODE_EXTENDED_ESC\n\n    \t    | // An illegal escape sequence\n    \t      ~('b'|'t'|'n'|'f'|'r'|'\\''|'\\\\'|'u') // \\x for any invalid x (make sure to match char here)\n    \t      {\n                Token t = new CommonToken(input, state.type, state.channel, getCharIndex()-2, getCharIndex()-1);\n                t.setText(t.getText());\n                t.setLine(input.getLine());\n                t.setCharPositionInLine(input.getCharPositionInLine()-2);\n                grammarError(ErrorType.INVALID_ESCAPE_SEQUENCE, t, input.substring(getCharIndex()-2,getCharIndex()-1));\n    \t      }\n        )\n    ;\n\nfragment\nUNICODE_ESC\n@init {\n\n\t// Flag to tell us whether we have a valid number of\n\t// hex digits in the escape sequence\n\t//\n\tint\thCount = 0;\n}\n    :   'u' // Leadin for unicode escape sequence\n\n        // We now require 4 hex digits. Note though\n        // that we accept any number of characters\n        // and issue an error if we do not get 4. We cannot\n        // use an infinite count such as + because this\n        // might consume too many, so we lay out the lexical\n        // options and issue an error at the invalid paths.\n        //\n    \t(\n    \t   (\n    \t      HEX_DIGIT  { hCount++; }\n    \t        (\n    \t             HEX_DIGIT  { hCount++; }\n    \t\t         (\n    \t\t              HEX_DIGIT  { hCount++; }\n    \t\t              (\n    \t\t                  // Four valid hex digits, we are good\n    \t\t                  //\n    \t\t                  HEX_DIGIT { hCount++; }\n\n    \t\t                | // Three valid digits\n    \t\t              )\n\n    \t\t            | // Two valid digits\n    \t\t          )\n\n    \t\t        | // One valid digit\n    \t\t    )\n            )\n          | // No valid hex digits at all\n    \t)\n\n    \t// Now check the digit count and issue an error if we need to\n    \t//\n    \t{\n    \t\tif (hCount < 4) {\n\t\t\t\tInterval badRange = Interval.of(getCharIndex()-2-hCount, getCharIndex());\n\t\t\t\tString lastChar = input.substring(badRange.b, badRange.b);\n\t\t\t\tif ( lastChar.codePointAt(0)=='\\'' ) {\n\t\t\t\t\tbadRange = Interval.of(badRange.a, badRange.b-1);\n\t\t\t\t}\n\t\t\t\tString bad = input.substring(badRange.a, badRange.b);\n\t\t\t\tToken t = new CommonToken(input, state.type, state.channel, badRange.a, badRange.b);\n\t\t\t\tt.setLine(input.getLine());\n\t\t\t\tt.setCharPositionInLine(input.getCharPositionInLine()-hCount-2);\n\t\t\t\tgrammarError(ErrorType.INVALID_ESCAPE_SEQUENCE, t, bad);\n    \t\t}\n    \t}\n    ;\n\nfragment\nUNICODE_EXTENDED_ESC\n    :   'u{' // Leadin for unicode extended escape sequence\n\n        HEX_DIGIT+ // One or more hexadecimal digits\n\n        '}' // Leadout for unicode extended escape sequence\n\n        // Now check the digit count and issue an error if we need to\n        {\n            int numDigits = getCharIndex()-state.tokenStartCharIndex-6;\n            if (numDigits > 6) {\n                Token t = new CommonToken(input, state.type, state.channel, state.tokenStartCharIndex, getCharIndex()-1);\n                t.setText(t.getText());\n                t.setLine(input.getLine());\n                t.setCharPositionInLine(input.getCharPositionInLine()-numDigits);\n                grammarError(ErrorType.INVALID_ESCAPE_SEQUENCE, t, input.substring(state.tokenStartCharIndex,getCharIndex()-1));\n\t\t\t}\n        }\n    ;\n\n// ----------\n// Whitespace\n//\n// Characters and character constructs that are of no import\n// to the parser and are used to make the grammar easier to read\n// for humans.\n//\nWS\n    : (\n    \t  ' '\n        | '\\t'\n        | '\\r'\n        | '\\n'\n        | '\\f'\n      )+\n      {$channel=HIDDEN;}\n    ;\n\n// A fragment rule for use in recognizing end of line in\n// rules like COMMENT.\n//\nfragment\nNLCHARS\n    : '\\n' | '\\r'\n    ;\n\n// A fragment rule for recognizing traditional whitespace\n// characters within lexer rules.\n//\nfragment\nWSCHARS\n    : ' ' | '\\t' | '\\f'\n    ;\n\n// A fragment rule for recognizing both traditional whitespace and\n// end of line markers, when we don't care to distinguish but don't\n// want any action code going on.\n//\nfragment\nWSNLCHARS\n    : ' ' | '\\t' | '\\f' | '\\n' | '\\r'\n    ;\n\n// This rule allows ANTLR 4 to parse grammars using the UTF-8 encoding with a\n// byte order mark. Since this Unicode character doesn't appear as a token\n// anywhere else in the grammar, we can simply skip all instances of it without\n// problem. This rule will not break usage of \\uFEFF inside a LEXER_CHAR_SET or\n// STRING_LITERAL.\nUnicodeBOM\n    :   '\\uFEFF' {skip();}\n    ;\n\n// -----------------\n// Illegal Character\n//\n// This is an illegal character trap which is always the last rule in the\n// lexer specification. It matches a single character of any value and being\n// the last rule in the file will match when no other rule knows what to do\n// about the character. It is reported as an error but is not passed on to the\n// parser. This means that the parser to deal with the grammar file anyway\n// but we will not try to analyse or code generate from a file with lexical\n// errors.\n//\nERRCHAR\n    : .\n      {\n         Token t = new CommonToken(input, state.type, state.channel, state.tokenStartCharIndex, getCharIndex()-1);\n         t.setLine(state.tokenStartLine);\n         t.setText(state.text);\n         t.setCharPositionInLine(state.tokenStartCharPositionInLine);\n         String msg = getTokenErrorDisplay(t) + \" came as a complete surprise to me\";\n         grammarError(ErrorType.SYNTAX_ERROR, t, msg);\n         state.syntaxErrors++;\n         skip();\n      }\n    ;\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ANTLRParser.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** The definitive ANTLR v3 grammar to parse ANTLR v4 grammars.\n *  The grammar builds ASTs that are sniffed by subsequent stages.\n */\nparser grammar ANTLRParser;\n\noptions {\n\t// Target language is Java, which is the default but being specific\n\t// here as this grammar is also meant as a good example grammar for\n\t// for users.\n\tlanguage      = Java;\n\n\t// The output of this grammar is going to be an AST upon which\n\t// we run a semantic checking phase, then the rest of the analysis\n\t// including final code generation.\n\toutput        = AST;\n\n\t// The vocabulary (tokens and their int token types) we are using\n\t// for the parser. This is generated by the lexer. The vocab will be extended\n\t// to include the imaginary tokens below.\n\ttokenVocab    = ANTLRLexer;\n\n\tASTLabelType  = GrammarAST;\n}\n\n// Imaginary Tokens\n//\n// Imaginary tokens do not exist as far as the lexer is concerned, and it cannot\n// generate them. However we sometimes need additional 'tokens' to use as root\n// nodes for the AST we are generating. The tokens section is where we\n// specify any such tokens\ntokens {\n    RULE;\n    RULES;\n    RULEMODIFIERS;\n    BLOCK;\n    OPTIONAL;\n    CLOSURE;\n    POSITIVE_CLOSURE;\n    RANGE;\n    SET;\n    EPSILON;\n    ALT;\n    ID;\n    COMBINED;\n    WILDCARD;\n    ELEMENT_OPTIONS;      // TOKEN<options>\n\n    // lexer action stuff\n    LEXER_ALT_ACTION;\n    LEXER_ACTION_CALL; // ID(foo)\n}\n\n// Include the copyright in this source and also the generated source\n//\n@header {\n/*\n [The \"BSD licence\"]\n Copyright (c) 2005-20012 Terence Parr\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\npackage org.antlr.v4.parse;\n\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.*;\n\nimport java.util.ArrayDeque;\nimport java.util.Deque;\n}\n\n@members {\nDeque<String> paraphrases = new ArrayDeque<String>();\npublic void grammarError(ErrorType etype, org.antlr.runtime.Token token, Object... args) { }\n}\n\n// The main entry point for parsing a V3 grammar from top to toe. This is\n// the method call from whence to obtain the AST for the parse.\n//\ngrammarSpec\n@after {\nGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.OPTIONS);\nif ( options!=null ) {\n\tGrammar.setNodeOptions($tree, options);\n}\n}\n    : // First we should see the type and name of the grammar file that\n      // we are about to parse.\n      //\n      grammarType id SEMI\n\n      // There now follows zero or more declaration sections that should\n      // be given to us before the rules are declared\n      //\n// A number of things can be declared/stated before the grammar rules\n// 'proper' are parsed. These include grammar imports (delegate), grammar\n// options, imaginary token declarations, global scope declarations,\n// and actions such as @header. In this rule we allow any number of\n// these constructs in any order so that the grammar author is not\n// constrained by some arbitrary order of declarations that nobody\n// can remember. In the next phase of the parse, we verify that these\n// constructs are valid, not repeated and so on.\n      sync ( prequelConstruct sync )*\n\n\t  // We should now see at least one ANTLR EBNF style rule\n\t  // declaration. If the rules are missing we will let the\n\t  // semantic verification phase tell the user about it.\n\t  //\n\t  rules\n\n\t  modeSpec*\n\n      // And we force ANTLR to process everything it finds in the input\n      // stream by specifying hte need to match End Of File before the\n      // parse is complete.\n      //\n      EOF\n\n      // Having parsed everything in the file and accumulated the relevant\n      // subtrees, we can now rewrite everything into the main AST form\n      // that our tree walkers are expecting.\n      //\n\n      -> ^(grammarType       // The grammar type is our root AST node\n             id              // We need to identify the grammar of course\n             prequelConstruct* // The set of declarations we accumulated\n             rules           // And of course, we need the set of rules we discovered\n             modeSpec*\n         )\n\t;\n\ngrammarType\n@after {\n\tif ( $t!=null ) ((GrammarRootAST)$tree).grammarType = $t.type;\n\telse ((GrammarRootAST)$tree).grammarType=COMBINED;\n}\n    :\t(\tt=LEXER g=GRAMMAR  -> GRAMMAR<GrammarRootAST>[$g, \"LEXER_GRAMMAR\", getTokenStream()]\n\t\t| // A standalone parser specification\n\t\t  \tt=PARSER g=GRAMMAR -> GRAMMAR<GrammarRootAST>[$g, \"PARSER_GRAMMAR\", getTokenStream()]\n\n\t\t// A combined lexer and parser specification\n\t\t| \tg=GRAMMAR          -> GRAMMAR<GrammarRootAST>[$g, \"COMBINED_GRAMMAR\", getTokenStream()]\n\t\t)\n    ;\n\n// This is the list of all constructs that can be declared before\n// the set of rules that compose the grammar, and is invoked 0..n\n// times by the grammarPrequel rule.\nprequelConstruct\n\t: // A list of options that affect analysis and/or code generation\n\t  optionsSpec\n\n    | // A list of grammars to which this grammar will delegate certain\n      // parts of the parsing sequence - a set of imported grammars\n      delegateGrammars\n\n    | // The declaration of any token types we need that are not already\n      // specified by a preceding grammar, such as when a parser declares\n      // imaginary tokens with which to construct the AST, or a rewriting\n      // tree parser adds further imaginary tokens to ones defined in a prior\n      // {tree} parser.\n      tokensSpec\n\n\t| // A list of custom channels used by the grammar\n\t  channelsSpec\n\n    | // A declaration of language target implemented constructs. All such\n      // action sections start with '@' and are given to the language target's\n      // StringTemplate group. For instance @parser::header and @lexer::header\n      // are gathered here.\n      action\n    ;\n\n// A list of options that affect analysis and/or code generation\noptionsSpec\n\t:\tOPTIONS (option SEMI)* RBRACE -> ^(OPTIONS[$OPTIONS, \"OPTIONS\"] option*)\n    ;\n\noption\n    :   id ASSIGN^ optionValue\n    ;\n\n// ------------\n// Option Value\n//\n// The actual value of an option - Doh!\n//\noptionValue\n    : // If the option value is a single word that conforms to the\n      // lexical rules of token or rule names, then the user may skip quotes\n      // and so on. Many option values meet this description\n      qid\n    | STRING_LITERAL\n\t| ACTION<ActionAST>\n    | INT\n    ;\n\n// A list of grammars to which this grammar will delegate certain\n// parts of the parsing sequence - a set of imported grammars\ndelegateGrammars\n\t: IMPORT delegateGrammar (COMMA delegateGrammar)* SEMI -> ^(IMPORT delegateGrammar+)\n\t;\n\n// A possibly named grammar file that should be imported to this grammar\n// and delegated to for the rules it specifies\ndelegateGrammar\n    :   id ASSIGN^ id\n    |   id\n    ;\n\ntokensSpec\n\t: TOKENS_SPEC id (COMMA id)* RBRACE -> ^(TOKENS_SPEC id+)\n    | TOKENS_SPEC RBRACE ->\n\t;\n\nchannelsSpec\n\t:\tCHANNELS^ id (COMMA! id)* RBRACE!\n\t;\n\n// A declaration of a language target specific section,\n// such as @header, @includes and so on. We do not verify these\n// sections, they are just passed on to the language target.\n/** Match stuff like @parser::members {int i;} */\naction\n\t:\tAT (actionScopeName COLONCOLON)? id ACTION -> ^(AT actionScopeName? id ACTION<ActionAST>)\n\t;\n\n/** Sometimes the scope names will collide with keywords; allow them as\n *  ids for action scopes.\n */\nactionScopeName\n\t:\tid\n\t|\tLEXER\t-> ID[$LEXER]\n    |   PARSER\t-> ID[$PARSER]\n\t;\n\nmodeSpec\n    :\tMODE id SEMI sync (lexerRule sync)*  -> ^(MODE id lexerRule*)\n    ;\n\nrules\n    :\tsync (rule sync)*\n      // Rewrite with an enclosing node as this is good for counting\n      // the number of rules and an easy marker for the walker to detect\n      // that there are no rules.\n      ->^(RULES rule*)\n    ;\n\nsync\n@init {\n\tBitSet followSet = computeErrorRecoverySet();\n\tif ( input.LA(1)!=Token.EOF && !followSet.member(input.LA(1)) ) {\n\t\treportError(new NoViableAltException(\"\",0,0,input));\n       \tbeginResync();\n       \tconsumeUntil(input, followSet);\n       \tendResync();\n\t}\n}\t:\n\t;\n\nrule:\tparserRule\n\t|\tlexerRule\n\t;\n\n// The specification of an EBNF rule in ANTLR style, with all the\n// rule level parameters, declarations, actions, rewrite specs and so\n// on.\n//\n// Note that here we allow any number of rule declaration sections (such\n// as scope, returns, etc) in any order and we let the upcoming semantic\n// verification of the AST determine if things are repeated or if a\n// particular functional element is not valid in the context of the\n// grammar type, such as using returns in lexer rules and so on.\nparserRule\n@init { paraphrases.push(\"matching a rule\"); }\n@after {\n\tparaphrases.pop();\n\tGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.OPTIONS);\n\tif ( options!=null ) {\n\t\tGrammar.setNodeOptions($tree, options);\n\t}\n}\n    : // Start with the rule name. Here we do not distinguish between\n\t  // parser or lexer rules, the semantic verification phase will\n\t  // reject any rules that make no sense, such as lexer rules in\n\t  // a pure parser or tree parser.\n\t  RULE_REF\n\n\t  // Immediately following the rulename, there may be a specification\n\t  // of input parameters for the rule. We do not do anything with the\n\t  // parameters here except gather them for future phases such as\n\t  // semantic verification, type assignment etc. We require that\n\t  // the input parameters are the next syntactically significant element\n\t  // following the rule id.\n\t  ARG_ACTION?\n\n\t  ruleReturns?\n\n\t  throwsSpec?\n\n\t  localsSpec?\n\n\t  // Now, before the rule specification itself, which is introduced\n\t  // with a COLON, we may have zero or more configuration sections.\n\t  // As usual we just accept anything that is syntactically valid for\n\t  // one form of the rule or another and let the semantic verification\n\t  // phase throw out anything that is invalid.\n// At the rule level, a programmer may specify a number of sections, such\n// as scope declarations, rule return elements, @ sections (which may be\n// language target specific) and so on. We allow any number of these in any\n// order here and as usual rely on the semantic verification phase to reject\n// anything invalid using its additional context information. Here we are\n// context free and just accept anything that is a syntactically correct\n// construct.\n//\n      rulePrequels\n\n      COLON\n\n      // The rule is, at the top level, just a list of alts, with\n      // finer grained structure defined within the alts.\n      ruleBlock\n\n      SEMI\n\n      exceptionGroup\n\n      -> ^( RULE<RuleAST> RULE_REF ARG_ACTION<ActionAST>?\n      \t\truleReturns? throwsSpec? localsSpec? rulePrequels? ruleBlock exceptionGroup*\n      \t  )\n    ;\n\n// Many language targets support exceptions and the rule will\n// generally be able to throw the language target equivalent\n// of a recognition exception. The grammar programmer can\n// specify a list of exceptions to catch or a generic catch all\n// and the target language code generation template is\n// responsible for generating code that makes sense.\nexceptionGroup\n    : exceptionHandler* finallyClause?\n    ;\n\n// Specifies a handler for a particular type of exception\n// thrown by a rule\nexceptionHandler\n\t: CATCH ARG_ACTION ACTION -> ^(CATCH ARG_ACTION<ActionAST> ACTION<ActionAST>)\n\t;\n\nfinallyClause\n\t: FINALLY ACTION -> ^(FINALLY ACTION<ActionAST>)\n\t;\n\nrulePrequels\n@init { paraphrases.push(\"matching rule preamble\"); }\n@after { paraphrases.pop(); }\n\t:\tsync (rulePrequel sync)* -> rulePrequel*\n\t;\n\n// An individual rule level configuration as referenced by the ruleActions\n// rule above.\n//\nrulePrequel\n    : optionsSpec\n    | ruleAction\n    ;\n\n// A rule can return elements that it constructs as it executes.\n// The return values are specified in a 'returns' prequel element,\n// which contains COMMA separated declarations, where the declaration\n// is target language specific. Here we see the returns declaration\n// as a single lexical action element, to be processed later.\n//\nruleReturns\n\t: RETURNS^ ARG_ACTION<ActionAST>\n\t;\n\n// --------------\n// Exception spec\n//\n// Some target languages, such as Java and C# support exceptions\n// and they are specified as a prequel element for each rule that\n// wishes to throw its own exception type. Note that the name of the\n// exception is just a single word, so the header section of the grammar\n// must specify the correct import statements (or language equivalent).\n// Target languages that do not support exceptions just safely ignore\n// them.\n//\nthrowsSpec\n    : THROWS qid (COMMA qid)* -> ^(THROWS qid+)\n    ;\n\n// locals [Cat x, float g]\nlocalsSpec : LOCALS^ ARG_ACTION<ActionAST> ;\n\n// @ Sections are generally target language specific things\n// such as local variable declarations, code to run before the\n// rule starts and so on. Fir instance most targets support the\n// @init {} section where declarations and code can be placed\n// to run before the rule is entered. The C target also has\n// an @declarations {} section, where local variables are declared\n// in order that the generated code is C89 compliant.\n//\n/** Match stuff like @init {int i;} */\nruleAction\n\t:\tAT id ACTION -> ^(AT id ACTION<ActionAST>)\n\t;\n\n// A set of alts, rewritten as a BLOCK for generic processing\n// in tree walkers. Used by the rule 'rule' so that the list of\n// alts for a rule appears as a BLOCK containing the alts and\n// can be processed by the generic BLOCK rule. Note that we\n// use a separate rule so that the BLOCK node has start and stop\n// boundaries set correctly by rule post processing of rewrites.\nruleBlock\n@init {Token colon = input.LT(-1);}\n    :\truleAltList -> ^(BLOCK<BlockAST>[colon,\"BLOCK\"] ruleAltList)\n    ;\n    catch [ResyncToEndOfRuleBlock e] {\n    \t// just resyncing; ignore error\n\t\tretval.tree = (GrammarAST)adaptor.errorNode(input, retval.start, input.LT(-1), null);\n    }\n\nruleAltList\n\t:\tlabeledAlt (OR labeledAlt)* -> labeledAlt+\n\t;\n\nlabeledAlt\n\t:\talternative\n\t\t(\tPOUND! id! {((AltAST)$alternative.tree).altLabel=$id.tree;}\n\t\t)?\n\t;\n\nlexerRule\n@init { paraphrases.push(\"matching a lexer rule\"); }\n@after {\n\tparaphrases.pop();\n}\n    : FRAGMENT?\n\t  TOKEN_REF\n\n\t  optionsSpec?\n\n\t  COLON lexerRuleBlock SEMI\n      -> ^( RULE<RuleAST> TOKEN_REF\n      \t\t^(RULEMODIFIERS FRAGMENT)? optionsSpec? lexerRuleBlock\n      \t  )\n\t;\n\nlexerRuleBlock\n@init {Token colon = input.LT(-1);}\n    :\tlexerAltList -> ^(BLOCK<BlockAST>[colon,\"BLOCK\"] lexerAltList)\n    ;\n    catch [ResyncToEndOfRuleBlock e] {\n    \t// just resyncing; ignore error\n\t\tretval.tree = (GrammarAST)adaptor.errorNode(input, retval.start, input.LT(-1), null);\n    }\n\nlexerAltList\n\t:\tlexerAlt (OR lexerAlt)* -> lexerAlt+\n\t;\n\nlexerAlt\n\t:\tlexerElements\n\t\t(\tlexerCommands\t-> ^(LEXER_ALT_ACTION<AltAST> lexerElements lexerCommands)\n\t\t|\t\t\t\t\t-> lexerElements\n\t\t)\n\t;\n\nlexerElements\n    :\tlexerElement+\t-> ^(ALT<AltAST> lexerElement+)\n\t|\t\t\t\t\t-> ^(ALT<AltAST> EPSILON) // empty alt\n    ;\n\nlexerElement\n@init {\n\tparaphrases.push(\"looking for lexer rule element\");\n\tint m = input.mark();\n}\n@after { paraphrases.pop(); }\n\t:\tlexerAtom\n\t\t(\tebnfSuffix\t-> ^( ebnfSuffix ^(BLOCK<BlockAST>[$lexerAtom.start,\"BLOCK\"] ^(ALT<AltAST> lexerAtom) ) )\n\t\t|\t\t\t\t-> lexerAtom\n\t\t)\n\t|\tlexerBlock\n\t\t(\tebnfSuffix\t-> ^(ebnfSuffix lexerBlock)\n\t\t|\t\t\t\t-> lexerBlock\n\t\t)\n\t|\tactionElement // actions only allowed at end of outer alt actually,\n\t\t\t\t\t  // but preds can be anywhere\n\t;\n    catch [RecognitionException re] {\n    \tretval.tree = (GrammarAST)adaptor.errorNode(input, retval.start, input.LT(-1), re);\n    \tint ttype = input.get(input.range()).getType(); // seems to be next token\n\t    // look for anything that really belongs at the start of the rule minus the initial ID\n    \tif ( ttype==COLON || ttype==RETURNS || ttype==CATCH || ttype==FINALLY || ttype==AT || ttype==EOF ) {\n\t\t\tRecognitionException missingSemi =\n\t\t\t\tnew v4ParserException(\"unterminated rule (missing ';') detected at '\"+\n\t\t\t\t\t\t\t\t\t  input.LT(1).getText()+\" \"+input.LT(2).getText()+\"'\", input);\n\t\t\treportError(missingSemi);\n\t\t\tif ( ttype==EOF ) {\n\t\t\t\tinput.seek(input.index()+1);\n\t\t\t}\n\t\t\telse if ( ttype==CATCH || ttype==FINALLY ) {\n\t\t\t\tinput.seek(input.range()); // ignore what's before rule trailer stuff\n\t\t\t}\n\t\t\telse if ( ttype==RETURNS || ttype==AT ) { // scan back looking for ID of rule header\n\t\t\t\tint p = input.index();\n\t\t\t\tToken t = input.get(p);\n\t\t\t\twhile ( t.getType()!=RULE_REF && t.getType()!=TOKEN_REF ) {\n\t\t\t\t\tp--;\n\t\t\t\t\tt = input.get(p);\n\t\t\t\t}\n\t\t\t\tinput.seek(p);\n\t\t\t}\n\t\t\tthrow new ResyncToEndOfRuleBlock(); // make sure it goes back to rule block level to recover\n\t\t}\n        reportError(re);\n        recover(input,re);\n\t}\n\nlexerBlock\n@after {\nGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.OPTIONS);\nif ( options!=null ) {\n\tGrammar.setNodeOptions($tree, options);\n}\n}\n \t:\tLPAREN\n        ( optionsSpec COLON )?\n        lexerAltList\n        RPAREN\n      -> ^(BLOCK<BlockAST>[$LPAREN,\"BLOCK\"] optionsSpec? lexerAltList )\n    ;\n\n// channel=HIDDEN, skip, more, mode(INSIDE), push(INSIDE), pop\nlexerCommands\n\t:\tRARROW lexerCommand (COMMA lexerCommand)* -> lexerCommand+\n\t;\n\nlexerCommand\n\t:\tlexerCommandName LPAREN lexerCommandExpr RPAREN -> ^(LEXER_ACTION_CALL lexerCommandName lexerCommandExpr)\n\t|\tlexerCommandName\n\t;\n\nlexerCommandExpr\n\t:\tid\n\t|\tINT\n\t;\n\nlexerCommandName\n        :       id\n        |       MODE    ->ID[$MODE]\n        ;\n\naltList\n    :\talternative (OR alternative)* -> alternative+\n    ;\n\n// An individual alt with an optional alt option like <assoc=right>\nalternative\n@init { paraphrases.push(\"matching alternative\"); }\n@after {\n    paraphrases.pop();\n    Grammar.setNodeOptions($tree, $o.tree);\n}\n\t:\to=elementOptions?\n\t\t(\te+=element+                     -> ^(ALT<AltAST> elementOptions? $e+)\n\t\t|                                   -> ^(ALT<AltAST> elementOptions? EPSILON) // empty alt\n\t\t)\n\t;\n\nelement\n@init {\n\tparaphrases.push(\"looking for rule element\");\n\tint m = input.mark();\n}\n@after { paraphrases.pop(); }\n\t:\tlabeledElement\n\t\t(\tebnfSuffix\t-> ^( ebnfSuffix ^(BLOCK<BlockAST>[$labeledElement.start,\"BLOCK\"] ^(ALT<AltAST> labeledElement ) ))\n\t\t|\t\t\t\t-> labeledElement\n\t\t)\n\t|\tatom\n\t\t(\tebnfSuffix\t-> ^( ebnfSuffix ^(BLOCK<BlockAST>[$atom.start,\"BLOCK\"] ^(ALT<AltAST> atom) ) )\n\t\t|\t\t\t\t-> atom\n\t\t)\n\t|\tebnf\n\t|\tactionElement\n\t;\n    catch [RecognitionException re] {\n    \tretval.tree = (GrammarAST)adaptor.errorNode(input, retval.start, input.LT(-1), re);\n    \tint ttype = input.get(input.range()).getType();\n\t    // look for anything that really belongs at the start of the rule minus the initial ID\n    \tif ( ttype==COLON || ttype==RETURNS || ttype==CATCH || ttype==FINALLY || ttype==AT ) {\n\t\t\tRecognitionException missingSemi =\n\t\t\t\tnew v4ParserException(\"unterminated rule (missing ';') detected at '\"+\n\t\t\t\t\t\t\t\t\t  input.LT(1).getText()+\" \"+input.LT(2).getText()+\"'\", input);\n\t\t\treportError(missingSemi);\n\t\t\tif ( ttype==CATCH || ttype==FINALLY ) {\n\t\t\t\tinput.seek(input.range()); // ignore what's before rule trailer stuff\n\t\t\t}\n\t\t\tif ( ttype==RETURNS || ttype==AT ) { // scan back looking for ID of rule header\n\t\t\t\tint p = input.index();\n\t\t\t\tToken t = input.get(p);\n\t\t\t\twhile ( t.getType()!=RULE_REF && t.getType()!=TOKEN_REF ) {\n\t\t\t\t\tp--;\n\t\t\t\t\tt = input.get(p);\n\t\t\t\t}\n\t\t\t\tinput.seek(p);\n\t\t\t}\n\t\t\tthrow new ResyncToEndOfRuleBlock(); // make sure it goes back to rule block level to recover\n\t\t}\n        reportError(re);\n        recover(input,re);\n\t}\n\nactionElement\n@after {\n\tGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.ELEMENT_OPTIONS);\n\tif ( options!=null ) {\n\t\tGrammar.setNodeOptions($tree, options);\n\t}\n}\n\t:\tACTION<ActionAST>\n\t|   ACTION elementOptions\t-> ^(ACTION<ActionAST> elementOptions)\n\t|   SEMPRED<PredAST>\n\t|   SEMPRED elementOptions\t-> ^(SEMPRED<PredAST> elementOptions)\n\t;\n\nlabeledElement\n\t:\tid (ass=ASSIGN|ass=PLUS_ASSIGN)\n\t\t(\tatom\t\t\t\t\t\t-> ^($ass id atom)\n\t\t|\tblock\t\t\t\t\t\t-> ^($ass id block)\n\t\t)\n\t;\n\n// A block of grammar structure optionally followed by standard EBNF\n// notation, or ANTLR specific notation. I.E. ? + ^ and so on\nebnf\n    : block\n      // And now we see if we have any of the optional suffixs and rewrite\n      // the AST for this rule accordingly\n      (\tblockSuffix\t-> ^(blockSuffix block)\n      |\t\t\t\t-> block\n      )\n    ;\n\n// The standard EBNF suffixes with additional components that make\n// sense only to ANTLR, in the context of a grammar block.\nblockSuffix\n    : ebnfSuffix // Standard EBNF\n    ;\n\nebnfSuffix\n\t:\tQUESTION nongreedy=QUESTION?\t-> OPTIONAL<OptionalBlockAST>[$start, $nongreedy]\n  \t|\tSTAR nongreedy=QUESTION?\t\t-> CLOSURE<StarBlockAST>[$start, $nongreedy]\n   \t|\tPLUS nongreedy=QUESTION?\t\t-> POSITIVE_CLOSURE<PlusBlockAST>[$start, $nongreedy]\n\t;\n\nlexerAtom\n\t:\trange\n\t|\tterminal\n    |   RULE_REF<RuleRefAST>\n    |\tnotSet\n    |\twildcard\n    |\tLEXER_CHAR_SET\n\t;\n\natom\n\t:\t// Qualified reference delegate.rule. This must be\n\t    // lexically contiguous (no spaces either side of the DOT)\n\t    // otherwise it is two references with a wildcard in between\n\t    // and not a qualified reference.\n\t    /*\n\t    {\n\t    \tinput.LT(1).getCharPositionInLine()+input.LT(1).getText().length()==\n\t        input.LT(2).getCharPositionInLine() &&\n\t        input.LT(2).getCharPositionInLine()+1==input.LT(3).getCharPositionInLine()\n\t    }?\n\t    id DOT ruleref -> ^(DOT id ruleref)\n\n    |\n    \t*/\n        range  // Range x..y - only valid in lexers\n\t|\tterminal\n    |   ruleref\n    |\tnotSet\n    |\twildcard\n    ;\n    catch [RecognitionException re] { throw re; } // pass upwards to element\n\nwildcard\n@after {\n\tGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.ELEMENT_OPTIONS);\n\tif ( options!=null ) {\n\t\tGrammar.setNodeOptions($tree, options);\n\t}\n}\n\t:\t// Wildcard '.' means any character in a lexer, any\n\t\t// token in parser and any node or subtree in a tree parser\n\t\t// Because the terminal rule is allowed to be the node\n\t\t// specification for the start of a tree rule, we must\n\t\t// later check that wildcard was not used for that.\n\t    DOT elementOptions?\n\t    -> ^(WILDCARD<TerminalAST>[$DOT] elementOptions?)\n\t;\n\n// --------------------\n// Inverted element set\n//\n// A set of characters (in a lexer) or terminal tokens, if a parser,\n// that are then used to create the inverse set of them.\nnotSet\n    : NOT setElement\t-> ^(NOT<NotAST>[$NOT] ^(SET<SetAST>[$setElement.start,\"SET\"] setElement))\n    | NOT blockSet\t\t-> ^(NOT<NotAST>[$NOT] blockSet)\n    ;\n\nblockSet\n@init {\n\tToken t;\n\tboolean ebnf = false;\n}\n    :\tLPAREN setElement (OR setElement)* RPAREN\n\t\t-> ^(SET<SetAST>[$LPAREN,\"SET\"] setElement+ )\n    ;\n\nsetElement\n\t:\tTOKEN_REF<TerminalAST>^ elementOptions?\n\t|\tSTRING_LITERAL<TerminalAST>^ elementOptions?\n\t|\trange\n    |   LEXER_CHAR_SET\n\t;\n\n// -------------\n// Grammar Block\n//\n// Anywhere where an element is valid, the grammar may start a new block\n// of alts by surrounding that block with ( ). A new block may also have a set\n// of options, which apply only to that block.\n//\nblock\n@after {\nGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.OPTIONS);\nif ( options!=null ) {\n\tGrammar.setNodeOptions($tree, options);\n}\n}\n \t:\tLPAREN\n        ( optionsSpec? ra+=ruleAction* COLON )?\n        altList\n\t\tRPAREN\n      -> ^(BLOCK<BlockAST>[$LPAREN,\"BLOCK\"] optionsSpec? $ra* altList )\n    ;\n\n// ----------------\n// Parser rule ref\n//\n// Reference to a parser rule with optional arguments and optional\n// directive to become the root node or ignore the tree produced\n//\nruleref\n@after {\nGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.ELEMENT_OPTIONS);\nif ( options!=null ) {\n\tGrammar.setNodeOptions($tree, options);\n}\n}\n    :\tRULE_REF ARG_ACTION? elementOptions? -> ^(RULE_REF<RuleRefAST> ARG_ACTION<ActionAST>? elementOptions?)\n    ;\n    catch [RecognitionException re] { throw re; } // pass upwards to element\n\n// ---------------\n// Character Range\n//\n// Specifies a range of characters. Valid for lexer rules only, but\n// we do not check that here, the tree walkers shoudl do that.\n// Note also that the parser also allows through more than just\n// character literals so that we can produce a much nicer semantic\n// error about any abuse of the .. operator.\n//\nrange\n    : STRING_LITERAL<TerminalAST> RANGE<RangeAST>^ STRING_LITERAL<TerminalAST>\n    ;\n\nterminal\n@after {\nGrammarAST options = (GrammarAST)$tree.getFirstChildWithType(ANTLRParser.ELEMENT_OPTIONS);\nif ( options!=null ) {\n\tGrammar.setNodeOptions($tree, options);\n}\n}\n\t:   TOKEN_REF elementOptions?\t\t-> ^(TOKEN_REF<TerminalAST> elementOptions?)\n\t|   STRING_LITERAL elementOptions?\t-> ^(STRING_LITERAL<TerminalAST> elementOptions?)\n\t;\n\n// Terminals may be adorned with certain options when\n// reference in the grammar: TOK<,,,>\nelementOptions\n    :   LT (elementOption (COMMA elementOption)*)? GT\n            -> ^(ELEMENT_OPTIONS[$LT,\"ELEMENT_OPTIONS\"] elementOption*)\n    ;\n\n// When used with elements we can specify what the tree node type can\n// be and also assign settings of various options  (which we do not check here)\nelementOption\n    : // This format indicates the default element option\n      qid\n    | id ASSIGN^ optionValue\n    ;\n\n// The name of the grammar, and indeed some other grammar elements may\n// come through to the parser looking like a rule reference or a token\n// reference, hence this rule is used to pick up whichever it is and rewrite\n// it as a generic ID token.\nid\n@init { paraphrases.push(\"looking for an identifier\"); }\n@after { paraphrases.pop(); }\n    : RULE_REF  ->ID[$RULE_REF]\n    | TOKEN_REF ->ID[$TOKEN_REF]\n    ;\n\nqid\n@init { paraphrases.push(\"looking for a qualified identifier\"); }\n@after { paraphrases.pop(); }\n\t:\tid (DOT id)* -> ID[$qid.start, $text]\n\t;\n\nalternativeEntry : alternative EOF ; // allow gunit to call alternative and see EOF afterwards\nelementEntry : element EOF ;\nruleEntry : rule EOF ;\nblockEntry : block EOF ;\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ATNBuilder.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\ntree grammar ATNBuilder;\noptions {\n\tlanguage     = Java;\n\ttokenVocab   = ANTLRParser;\n\tASTLabelType = GrammarAST;\n//\tfilter \t     = true;\n}\n\n// Include the copyright in this source and also the generated source\n@header {\n/*\n [The \"BSD license\"]\n Copyright (c) 2010 Terence Parr\n All rights reserved.\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\npackage org.antlr.v4.parse;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.*;\nimport org.antlr.v4.automata.ATNFactory;\n}\n\n@members {\n    ATNFactory factory;\n    public ATNBuilder(TreeNodeStream input, ATNFactory factory) {\n    \tthis(input);\n    \tthis.factory = factory;\n    }\n}\n\ndummy : block[null] ; // avoid error about no start rule\n\nruleBlock[GrammarAST ebnfRoot] returns [ATNFactory.Handle p]\n@init {\n    List<ATNFactory.Handle> alts = new ArrayList<ATNFactory.Handle>();\n    int alt = 1;\n    factory.setCurrentOuterAlt(alt);\n}\n    :\t^(BLOCK\n            (^(OPTIONS .*))?\n            (   a=alternative\n                {alts.add($a.p); factory.setCurrentOuterAlt(++alt);}\n            )+\n        )\n    \t{$p = factory.block((BlockAST)$BLOCK, ebnfRoot, alts);}\n    ;\n\nblock[GrammarAST ebnfRoot] returns [ATNFactory.Handle p]\n@init {List<ATNFactory.Handle> alts = new ArrayList<ATNFactory.Handle>();}\n    :\t^(BLOCK (^(OPTIONS .*))? (a=alternative {alts.add($a.p);})+)\n    \t{$p = factory.block((BlockAST)$BLOCK, ebnfRoot, alts);}\n    ;\n\nalternative returns [ATNFactory.Handle p]\n@init {List<ATNFactory.Handle> els = new ArrayList<ATNFactory.Handle>();}\n    :\t^(LEXER_ALT_ACTION a=alternative lexerCommands)\n        {$p = factory.lexerAltCommands($a.p,$lexerCommands.p);}\n    |\t^(ALT elementOptions? EPSILON)\t\t\t\t\t\t\t{$p = factory.epsilon($EPSILON);}\n    |   ^(ALT elementOptions? (e=element {els.add($e.p);})+)\t{$p = factory.alt(els);}\n    ;\n\nlexerCommands returns [ATNFactory.Handle p]\n@init {List<ATNFactory.Handle> cmds = new ArrayList<ATNFactory.Handle>();}\n    :   (c=lexerCommand {if ($c.cmd != null) cmds.add($c.cmd);})+\n        {\n        $p = factory.alt(cmds);\n        }\n    ;\n\nlexerCommand returns [ATNFactory.Handle cmd]\n\t:\t^(LEXER_ACTION_CALL ID lexerCommandExpr)\n        {$cmd = factory.lexerCallCommand($ID, $lexerCommandExpr.start);}\n\t|\tID\n        {$cmd = factory.lexerCommand($ID);}\n\t;\n\nlexerCommandExpr\n\t:\tID\n\t|\tINT\n\t;\n\nelement returns [ATNFactory.Handle p]\n\t:\tlabeledElement\t\t\t\t{$p = $labeledElement.p;}\n\t|\tatom\t\t\t\t\t\t{$p = $atom.p;}\n\t|\tsubrule\t\t\t\t\t\t{$p = $subrule.p;}\n\t|   ACTION\t\t\t\t\t\t{$p = factory.action((ActionAST)$ACTION);}\n\t|   SEMPRED\t\t\t\t\t\t{$p = factory.sempred((PredAST)$SEMPRED);}\n\t|   ^(ACTION .)\t\t\t\t\t{$p = factory.action((ActionAST)$ACTION);}\n\t|   ^(SEMPRED .)\t\t\t\t{$p = factory.sempred((PredAST)$SEMPRED);}\n    |\t^(NOT b=blockSet[true])\t\t{$p = $b.p;}\n    |\tLEXER_CHAR_SET\t\t\t\t{$p = factory.charSetLiteral($start);}\n\t;\n\nastOperand returns [ATNFactory.Handle p]\n\t:\tatom\t\t\t\t\t\t{$p = $atom.p;}\n\t|\t^(NOT blockSet[true])\t\t{$p = $blockSet.p;}\n\t;\n\nlabeledElement returns [ATNFactory.Handle p]\n\t:\t^(ASSIGN ID element)\t    {$p = factory.label($element.p);}\n\t|\t^(PLUS_ASSIGN ID element)   {$p = factory.listLabel($element.p);}\n\t;\n\nsubrule returns [ATNFactory.Handle p]\n\t:\t^(OPTIONAL block[$start])\t\t\t{$p = $block.p;}\n\t|\t^(CLOSURE block[$start])\t\t\t{$p = $block.p;}\n\t|\t^(POSITIVE_CLOSURE block[$start])\t{$p = $block.p;}\n\t| \tblock[null] \t\t\t\t\t\t{$p = $block.p;}\n    ;\n\nblockSet[boolean invert] returns [ATNFactory.Handle p]\n@init {List<GrammarAST> alts = new ArrayList<GrammarAST>();}\n\t:\t^(SET (setElement {alts.add($setElement.start);})+) {$p = factory.set($start, alts, $invert);}\n\t;\n\n/** Don't combine with atom otherwise it will build spurious ATN nodes */\nsetElement\n\t:\t^(STRING_LITERAL .)\n\t|\t^(TOKEN_REF .)\n\t|\tSTRING_LITERAL\n\t|\tTOKEN_REF\n\t|\t^(RANGE a=STRING_LITERAL b=STRING_LITERAL)\n    |   LEXER_CHAR_SET\n\t;\n\natom returns [ATNFactory.Handle p]\n\t:\trange\t\t\t\t\t{$p = $range.p;}\n\t|\t^(DOT ID terminal)\t\t{$p = $terminal.p;}\n\t|\t^(DOT ID ruleref)\t\t{$p = $ruleref.p;}\n    |\t^(WILDCARD .)\t\t\t{$p = factory.wildcard($start);}\n    |\tWILDCARD\t\t\t\t{$p = factory.wildcard($start);}\n    |\tblockSet[false]\t\t\t{$p = $blockSet.p;}\n    |   terminal\t\t\t\t{$p = $terminal.p;}\n    |   ruleref\t\t\t\t\t{$p = $ruleref.p;}\n    ;\n\nruleref returns [ATNFactory.Handle p]\n    :\t^(RULE_REF ARG_ACTION? ^(ELEMENT_OPTIONS .*))\t\t{$p = factory.ruleRef($RULE_REF);}\n    |\t^(RULE_REF ARG_ACTION?)\t\t\t\t\t\t\t\t{$p = factory.ruleRef($RULE_REF);}\n    |\tRULE_REF\t\t\t\t\t\t\t\t\t\t\t{$p = factory.ruleRef($RULE_REF);}\n    ;\n\nrange returns [ATNFactory.Handle p]\n    : ^(RANGE a=STRING_LITERAL b=STRING_LITERAL) {$p = factory.range($a,$b);}\n    ;\n\nterminal returns [ATNFactory.Handle p]\n    :  ^(STRING_LITERAL .)\t\t\t{$p = factory.stringLiteral((TerminalAST)$start);}\n    |\tSTRING_LITERAL\t\t\t\t{$p = factory.stringLiteral((TerminalAST)$start);}\n    |\t^(TOKEN_REF ARG_ACTION .)\t{$p = factory.tokenRef((TerminalAST)$start);}\n    |\t^(TOKEN_REF .)\t\t\t\t{$p = factory.tokenRef((TerminalAST)$start);}\n    |\tTOKEN_REF\t\t\t\t\t{$p = factory.tokenRef((TerminalAST)$start);}\n    ;\n\nelementOptions\n\t:\t^(ELEMENT_OPTIONS elementOption*)\n\t;\n\nelementOption\n\t:\tID\n\t|\t^(ASSIGN ID ID)\n\t|\t^(ASSIGN ID STRING_LITERAL)\n\t|\t^(ASSIGN ID ACTION)\n\t|\t^(ASSIGN ID INT)\n\t;\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ActionSplitter.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nlexer grammar ActionSplitter;\n\noptions { filter=true; }\n\n@header {\npackage org.antlr.v4.parse;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.*;\n}\n\n@members {\nActionSplitterListener delegate;\n\npublic ActionSplitter(CharStream input, ActionSplitterListener delegate) {\n    this(input, new RecognizerSharedState());\n    this.delegate = delegate;\n}\n\n/** force filtering (and return tokens). triggers all above actions. */\npublic List<Token> getActionTokens() {\n    List<Token> chunks = new ArrayList<Token>();\n    Token t = nextToken();\n    while ( t.getType()!=Token.EOF ) {\n        chunks.add(t);\n        t = nextToken();\n    }\n    return chunks;\n}\n\nprivate boolean isIDStartChar(int c) {\n\treturn c == '_' || Character.isLetter(c);\n}\n}\n\n// ignore comments right away\n\nCOMMENT\n    :   '/*' ( options {greedy=false;} : . )* '*/' {delegate.text($text);}\n    ;\n\nLINE_COMMENT\n    : '//' ~('\\n'|'\\r')* '\\r'? '\\n' {delegate.text($text);}\n    ;\n\nSET_NONLOCAL_ATTR\n\t:\t'$' x=ID '::' y=ID WS? '=' expr=ATTR_VALUE_EXPR ';'\n\t\t{\n\t\tdelegate.setNonLocalAttr($text, $x, $y, $expr);\n\t\t}\n\t;\n\nNONLOCAL_ATTR\n\t:\t'$' x=ID '::' y=ID {delegate.nonLocalAttr($text, $x, $y);}\n\t;\n\nQUALIFIED_ATTR\n\t:\t'$' x=ID '.' y=ID {input.LA(1)!='('}? {delegate.qualifiedAttr($text, $x, $y);}\n\t;\n\nSET_ATTR\n\t:\t'$' x=ID WS? '=' expr=ATTR_VALUE_EXPR ';'\n\t\t{\n\t\tdelegate.setAttr($text, $x, $expr);\n\t\t}\n\t;\n\nATTR\n\t:\t'$' x=ID {delegate.attr($text, $x);}\n\t;\n\n// Anything else is just random text\nTEXT\n@init {StringBuilder buf = new StringBuilder();}\n@after {delegate.text(buf.toString());}\n\t:\t(\tc=~('\\\\'| '$') {buf.append((char)$c);}\n\t\t|\t'\\\\$' {buf.append('$');}\n\t\t|\t'\\\\' c=~('$') {buf.append('\\\\').append((char)$c);}\n\t\t|\t{!isIDStartChar(input.LA(2))}? => '$' {buf.append('$');}\n\t\t)+\n\t;\n\nfragment\nID  :\t('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*\n    ;\n\n/** Don't allow an = as first char to prevent $x == 3; kind of stuff. */\nfragment\nATTR_VALUE_EXPR\n\t:\t~'=' (~';')*\n\t;\n\nfragment\nWS\t:\t(' '|'\\t'|'\\n'|'\\r')+\n\t;\n\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ActionSplitterListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.Token;\n\n/** */\npublic interface ActionSplitterListener {\n    void qualifiedAttr(String expr, Token x, Token y);\n\tvoid setAttr(String expr, Token x, Token rhs);\n\tvoid attr(String expr, Token x);\n\n\tvoid setNonLocalAttr(String expr, Token x, Token y, Token rhs);\n\tvoid nonLocalAttr(String expr, Token x, Token y);\n\n    void text(String text);\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/BlockSetTransformer.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\ntree grammar BlockSetTransformer;\noptions {\n\tlanguage     = Java;\n\ttokenVocab   = ANTLRParser;\n\tASTLabelType = GrammarAST;\n\toutput\t\t = AST;\n\tfilter\t\t = true;\n}\n\n@header {\npackage org.antlr.v4.parse;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.misc.*;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.*;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.HashSet;\nimport java.util.ArrayList;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n}\n\n@members {\npublic String currentRuleName;\npublic GrammarAST currentAlt;\npublic Grammar g;\npublic BlockSetTransformer(TreeNodeStream input, Grammar g) {\n    this(input, new RecognizerSharedState());\n    this.g = g;\n}\n}\n\ntopdown\n    :\t^(RULE (id=TOKEN_REF|id=RULE_REF) {currentRuleName=$id.text;} .+)\n    |\tsetAlt\n    |\tebnfBlockSet\n    |\tblockSet\n\t;\n\nsetAlt\n\t:\t{inContext(\"RULE BLOCK\")}?\n\t\tALT {currentAlt = $start;}\n\t;\n\n// (BLOCK (ALT (+ (BLOCK (ALT INT) (ALT ID)))))\nebnfBlockSet\n@after {\n\tGrammarTransformPipeline.setGrammarPtr(g, $tree);\n}\n\t:\t^(ebnfSuffix blockSet) -> ^(ebnfSuffix ^(BLOCK<BlockAST> ^(ALT<AltAST> blockSet)))\n\t;\n\nebnfSuffix\n@after {$tree = (GrammarAST)adaptor.dupNode($start);}\n\t:\tOPTIONAL\n  \t|\tCLOSURE\n   \t|\tPOSITIVE_CLOSURE\n\t;\n\nblockSet\n@init {\nboolean inLexer = Grammar.isTokenName(currentRuleName);\n}\n@after {\n\tGrammarTransformPipeline.setGrammarPtr(g, $tree);\n}\n\t:\t{inContext(\"RULE\")}? // top-level: rule block and > 1 alt\n\t\t^(BLOCK ^(alt=ALT elementOptions? {((AltAST)$alt).altLabel==null}? setElement[inLexer]) ( ^(ALT elementOptions? setElement[inLexer]) )+)\n\t\t-> ^(BLOCK<BlockAST>[$BLOCK.token] ^(ALT<AltAST>[$BLOCK.token,\"ALT\"] ^(SET[$BLOCK.token, \"SET\"] setElement+)))\n\t|\t{!inContext(\"RULE\")}? // if not rule block and > 1 alt\n\t\t^(BLOCK ^(ALT elementOptions? setElement[inLexer]) ( ^(ALT elementOptions? setElement[inLexer]) )+)\n\t\t-> ^(SET[$BLOCK.token, \"SET\"] setElement+)\n\t;\n\nsetElement[boolean inLexer]\n@after {\n\tGrammarTransformPipeline.setGrammarPtr(g, $tree);\n}\n\t:\t(\t^(a=STRING_LITERAL elementOptions) {!inLexer || CharSupport.getCharValueFromGrammarCharLiteral($a.getText())!=-1}?\n\t\t|\t  a=STRING_LITERAL {!inLexer || CharSupport.getCharValueFromGrammarCharLiteral($a.getText())!=-1}?\n\t\t|\t{!inLexer}?=> ^(TOKEN_REF elementOptions)\n\t\t|\t{!inLexer}?=>   TOKEN_REF\n\t\t|\t{inLexer}?=>  ^(RANGE a=STRING_LITERAL b=STRING_LITERAL)\n\t\t\t{CharSupport.getCharValueFromGrammarCharLiteral($a.getText())!=-1 &&\n\t\t\t CharSupport.getCharValueFromGrammarCharLiteral($b.getText())!=-1}?\n\t\t)\n\t;\n\nelementOptions\n\t:\t^(ELEMENT_OPTIONS elementOption*)\n\t;\n\nelementOption\n\t:\tID\n\t|\t^(ASSIGN id=ID v=ID)\n\t|\t^(ASSIGN ID v=STRING_LITERAL)\n\t|\t^(ASSIGN ID v=ACTION)\n\t|\t^(ASSIGN ID v=INT)\n\t;\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/GrammarASTAdaptor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.tree.CommonTreeAdaptor;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTErrorNode;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\npublic class GrammarASTAdaptor extends CommonTreeAdaptor {\n    org.antlr.runtime.CharStream input; // where we can find chars ref'd by tokens in tree\n    public GrammarASTAdaptor() { }\n    public GrammarASTAdaptor(org.antlr.runtime.CharStream input) { this.input = input; }\n\n    @Override\n    public Object create(Token token) {\n        return new GrammarAST(token);\n    }\n\n    @Override\n    /** Make sure even imaginary nodes know the input stream */\n    public Object create(int tokenType, String text) {\n\t\tGrammarAST t;\n\t\tif ( tokenType==ANTLRParser.RULE ) {\n\t\t\t// needed by TreeWizard to make RULE tree\n        \tt = new RuleAST(new CommonToken(tokenType, text));\n\t\t}\n\t\telse if ( tokenType==ANTLRParser.STRING_LITERAL ) {\n\t\t\t// implicit lexer construction done with wizard; needs this node type\n\t\t\t// whereas grammar ANTLRParser.g can use token option to spec node type\n\t\t\tt = new TerminalAST(new CommonToken(tokenType, text));\n\t\t}\n\t\telse {\n\t\t\tt = (GrammarAST)super.create(tokenType, text);\n\t\t}\n        t.token.setInputStream(input);\n        return t;\n    }\n\n    @Override\n    public Object dupNode(Object t) {\n        if ( t==null ) return null;\n        return ((GrammarAST)t).dupNode(); //create(((GrammarAST)t).token);\n    }\n\n    @Override\n    public Object errorNode(org.antlr.runtime.TokenStream input, org.antlr.runtime.Token start, org.antlr.runtime.Token stop,\n                            org.antlr.runtime.RecognitionException e)\n    {\n        return new GrammarASTErrorNode(input, start, stop, e);\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/GrammarToken.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.tool.Grammar;\n\n/** A CommonToken that can also track it's original location,\n *  derived from options on the element ref like BEGIN&lt;line=34,...&gt;.\n */\npublic class GrammarToken extends CommonToken {\n\tpublic Grammar g;\n\tpublic int originalTokenIndex = -1;\n\n\tpublic GrammarToken(Grammar g, Token oldToken) {\n\t\tsuper(oldToken);\n\t\tthis.g = g;\n\t}\n\n\t@Override\n\tpublic int getCharPositionInLine() {\n\t\tif ( originalTokenIndex>=0 ) return g.originalTokenStream.get(originalTokenIndex).getCharPositionInLine();\n\t\treturn super.getCharPositionInLine();\n\t}\n\n\t@Override\n\tpublic int getLine() {\n\t\tif ( originalTokenIndex>=0 ) return g.originalTokenStream.get(originalTokenIndex).getLine();\n\t\treturn super.getLine();\n\t}\n\n\t@Override\n\tpublic int getTokenIndex() {\n\t\treturn originalTokenIndex;\n\t}\n\n\t@Override\n\tpublic int getStartIndex() {\n\t\tif ( originalTokenIndex>=0 ) {\n\t\t\treturn ((CommonToken)g.originalTokenStream.get(originalTokenIndex)).getStartIndex();\n\t\t}\n\t\treturn super.getStartIndex();\n\t}\n\n\t@Override\n\tpublic int getStopIndex() {\n\t\tint n = super.getStopIndex() - super.getStartIndex() + 1;\n\t\treturn getStartIndex() + n - 1;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString channelStr = \"\";\n\t\tif ( channel>0 ) {\n\t\t\tchannelStr=\",channel=\"+channel;\n\t\t}\n\t\tString txt = getText();\n\t\tif ( txt!=null ) {\n\t\t\ttxt = txt.replaceAll(\"\\n\",\"\\\\\\\\n\");\n\t\t\ttxt = txt.replaceAll(\"\\r\",\"\\\\\\\\r\");\n\t\t\ttxt = txt.replaceAll(\"\\t\",\"\\\\\\\\t\");\n\t\t}\n\t\telse {\n\t\t\ttxt = \"<no text>\";\n\t\t}\n\t\treturn \"[@\"+getTokenIndex()+\",\"+getStartIndex()+\":\"+getStopIndex()+\n\t\t\t   \"='\"+txt+\"',<\"+getType()+\">\"+channelStr+\",\"+getLine()+\":\"+getCharPositionInLine()+\"]\";\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/GrammarTreeVisitor.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** The definitive ANTLR v3 tree grammar to walk/visit ANTLR v4 grammars.\n *  Parses trees created by ANTLRParser.g.\n *\n *  Rather than have multiple tree grammars, one for each visit, I'm\n *  creating this generic visitor that knows about context. All of the\n *  boilerplate pattern recognition is done here. Then, subclasses can\n *  override the methods they care about. This prevents a lot of the same\n *  context tracking stuff like \"set current alternative for current\n *  rule node\" that is repeated in lots of tree filters.\n */\ntree grammar GrammarTreeVisitor;\noptions {\n\tlanguage      = Java;\n\ttokenVocab    = ANTLRParser;\n\tASTLabelType  = GrammarAST;\n}\n\n// Include the copyright in this source and also the generated source\n@header {\n/*\n [The \"BSD license\"]\n Copyright (c) 2011 Terence Parr\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage org.antlr.v4.parse;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.*;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n}\n\n@members {\npublic String grammarName;\npublic GrammarAST currentRuleAST;\npublic String currentModeName = LexerGrammar.DEFAULT_MODE_NAME;\npublic String currentRuleName;\npublic GrammarAST currentOuterAltRoot;\npublic int currentOuterAltNumber = 1; // 1..n\npublic int rewriteEBNFLevel = 0;\n\npublic GrammarTreeVisitor() { this(null); }\n\n// Should be abstract but can't make gen'd parser abstract;\n// subclasses should implement else everything goes to stderr!\npublic ErrorManager getErrorManager() { return null; }\n\npublic void visitGrammar(GrammarAST t) { visit(t, \"grammarSpec\"); }\npublic void visit(GrammarAST t, String ruleName) {\n\tCommonTreeNodeStream nodes = new CommonTreeNodeStream(new GrammarASTAdaptor(), t);\n\tsetTreeNodeStream(nodes);\n\ttry {\n\t\tMethod m = getClass().getMethod(ruleName);\n\t\tm.invoke(this);\n\t}\n\tcatch (Throwable e) {\n\t\tErrorManager errMgr = getErrorManager();\n\t\tif ( e instanceof InvocationTargetException ) {\n\t\t\te = e.getCause();\n\t\t}\n\t\t//e.printStackTrace(System.err);\n\t\tif ( errMgr==null ) {\n\t\t\tSystem.err.println(\"can't find rule \"+ruleName+\n\t\t\t\t\t\t\t   \" or tree structure error: \"+t.toStringTree()\n\t\t\t\t\t\t\t   );\n\t\t\te.printStackTrace(System.err);\n\t\t}\n\t\telse errMgr.toolError(ErrorType.INTERNAL_ERROR, e);\n\t}\n}\n\npublic void discoverGrammar(GrammarRootAST root, GrammarAST ID) { }\npublic void finishPrequels(GrammarAST firstPrequel) { }\npublic void finishGrammar(GrammarRootAST root, GrammarAST ID) { }\n\npublic void grammarOption(GrammarAST ID, GrammarAST valueAST) { }\npublic void ruleOption(GrammarAST ID, GrammarAST valueAST) { }\npublic void blockOption(GrammarAST ID, GrammarAST valueAST) { }\npublic void defineToken(GrammarAST ID) { }\npublic void defineChannel(GrammarAST ID) { }\npublic void globalNamedAction(GrammarAST scope, GrammarAST ID, ActionAST action) { }\npublic void importGrammar(GrammarAST label, GrammarAST ID) { }\n\npublic void modeDef(GrammarAST m, GrammarAST ID) { }\n\npublic void discoverRules(GrammarAST rules) { }\npublic void finishRules(GrammarAST rule) { }\npublic void discoverRule(RuleAST rule, GrammarAST ID, List<GrammarAST> modifiers,\n\t\t\t\t\t\t ActionAST arg, ActionAST returns, GrammarAST thrws,\n\t\t\t\t\t\t GrammarAST options, ActionAST locals,\n\t\t\t\t\t\t List<GrammarAST> actions,\n\t\t\t\t\t\t GrammarAST block) { }\npublic void finishRule(RuleAST rule, GrammarAST ID, GrammarAST block) { }\npublic void discoverLexerRule(RuleAST rule, GrammarAST ID, List<GrammarAST> modifiers, GrammarAST options,\n                              GrammarAST block) { }\npublic void finishLexerRule(RuleAST rule, GrammarAST ID, GrammarAST block) { }\npublic void ruleCatch(GrammarAST arg, ActionAST action) { }\npublic void finallyAction(ActionAST action) { }\npublic void discoverOuterAlt(AltAST alt) { }\npublic void finishOuterAlt(AltAST alt) { }\npublic void discoverAlt(AltAST alt) { }\npublic void finishAlt(AltAST alt) { }\n\npublic void ruleRef(GrammarAST ref, ActionAST arg) { }\npublic void tokenRef(TerminalAST ref) { }\npublic void elementOption(GrammarASTWithOptions t, GrammarAST ID, GrammarAST valueAST) { }\npublic void stringRef(TerminalAST ref) { }\npublic void wildcardRef(GrammarAST ref) { }\npublic void actionInAlt(ActionAST action) { }\npublic void sempredInAlt(PredAST pred) { }\npublic void label(GrammarAST op, GrammarAST ID, GrammarAST element) { }\npublic void lexerCallCommand(int outerAltNumber, GrammarAST ID, GrammarAST arg) { }\npublic void lexerCommand(int outerAltNumber, GrammarAST ID) { }\n\nprotected void enterGrammarSpec(GrammarAST tree) { }\nprotected void exitGrammarSpec(GrammarAST tree) { }\n\nprotected void enterPrequelConstructs(GrammarAST tree) { }\nprotected void exitPrequelConstructs(GrammarAST tree) { }\n\nprotected void enterPrequelConstruct(GrammarAST tree) { }\nprotected void exitPrequelConstruct(GrammarAST tree) { }\n\nprotected void enterOptionsSpec(GrammarAST tree) { }\nprotected void exitOptionsSpec(GrammarAST tree) { }\n\nprotected void enterOption(GrammarAST tree) { }\nprotected void exitOption(GrammarAST tree) { }\n\nprotected void enterOptionValue(GrammarAST tree) { }\nprotected void exitOptionValue(GrammarAST tree) { }\n\nprotected void enterDelegateGrammars(GrammarAST tree) { }\nprotected void exitDelegateGrammars(GrammarAST tree) { }\n\nprotected void enterDelegateGrammar(GrammarAST tree) { }\nprotected void exitDelegateGrammar(GrammarAST tree) { }\n\nprotected void enterTokensSpec(GrammarAST tree) { }\nprotected void exitTokensSpec(GrammarAST tree) { }\n\nprotected void enterTokenSpec(GrammarAST tree) { }\nprotected void exitTokenSpec(GrammarAST tree) { }\n\nprotected void enterChannelsSpec(GrammarAST tree) { }\nprotected void exitChannelsSpec(GrammarAST tree) { }\n\nprotected void enterChannelSpec(GrammarAST tree) { }\nprotected void exitChannelSpec(GrammarAST tree) { }\n\nprotected void enterAction(GrammarAST tree) { }\nprotected void exitAction(GrammarAST tree) { }\n\nprotected void enterRules(GrammarAST tree) { }\nprotected void exitRules(GrammarAST tree) { }\n\nprotected void enterMode(GrammarAST tree) { }\nprotected void exitMode(GrammarAST tree) { }\n\nprotected void enterLexerRule(GrammarAST tree) { }\nprotected void exitLexerRule(GrammarAST tree) { }\n\nprotected void enterRule(GrammarAST tree) { }\nprotected void exitRule(GrammarAST tree) { }\n\nprotected void enterExceptionGroup(GrammarAST tree) { }\nprotected void exitExceptionGroup(GrammarAST tree) { }\n\nprotected void enterExceptionHandler(GrammarAST tree) { }\nprotected void exitExceptionHandler(GrammarAST tree) { }\n\nprotected void enterFinallyClause(GrammarAST tree) { }\nprotected void exitFinallyClause(GrammarAST tree) { }\n\nprotected void enterLocals(GrammarAST tree) { }\nprotected void exitLocals(GrammarAST tree) { }\n\nprotected void enterRuleReturns(GrammarAST tree) { }\nprotected void exitRuleReturns(GrammarAST tree) { }\n\nprotected void enterThrowsSpec(GrammarAST tree) { }\nprotected void exitThrowsSpec(GrammarAST tree) { }\n\nprotected void enterRuleAction(GrammarAST tree) { }\nprotected void exitRuleAction(GrammarAST tree) { }\n\nprotected void enterRuleModifier(GrammarAST tree) { }\nprotected void exitRuleModifier(GrammarAST tree) { }\n\nprotected void enterLexerRuleBlock(GrammarAST tree) { }\nprotected void exitLexerRuleBlock(GrammarAST tree) { }\n\nprotected void enterRuleBlock(GrammarAST tree) { }\nprotected void exitRuleBlock(GrammarAST tree) { }\n\nprotected void enterLexerOuterAlternative(AltAST tree) { }\nprotected void exitLexerOuterAlternative(AltAST tree) { }\n\nprotected void enterOuterAlternative(AltAST tree) { }\nprotected void exitOuterAlternative(AltAST tree) { }\n\nprotected void enterLexerAlternative(GrammarAST tree) { }\nprotected void exitLexerAlternative(GrammarAST tree) { }\n\nprotected void enterLexerElements(GrammarAST tree) { }\nprotected void exitLexerElements(GrammarAST tree) { }\n\nprotected void enterLexerElement(GrammarAST tree) { }\nprotected void exitLexerElement(GrammarAST tree) { }\n\nprotected void enterLexerBlock(GrammarAST tree) { }\nprotected void exitLexerBlock(GrammarAST tree) { }\n\nprotected void enterLexerAtom(GrammarAST tree) { }\nprotected void exitLexerAtom(GrammarAST tree) { }\n\nprotected void enterActionElement(GrammarAST tree) { }\nprotected void exitActionElement(GrammarAST tree) { }\n\nprotected void enterAlternative(AltAST tree) { }\nprotected void exitAlternative(AltAST tree) { }\n\nprotected void enterLexerCommand(GrammarAST tree) { }\nprotected void exitLexerCommand(GrammarAST tree) { }\n\nprotected void enterLexerCommandExpr(GrammarAST tree) { }\nprotected void exitLexerCommandExpr(GrammarAST tree) { }\n\nprotected void enterElement(GrammarAST tree) { }\nprotected void exitElement(GrammarAST tree) { }\n\nprotected void enterAstOperand(GrammarAST tree) { }\nprotected void exitAstOperand(GrammarAST tree) { }\n\nprotected void enterLabeledElement(GrammarAST tree) { }\nprotected void exitLabeledElement(GrammarAST tree) { }\n\nprotected void enterSubrule(GrammarAST tree) { }\nprotected void exitSubrule(GrammarAST tree) { }\n\nprotected void enterLexerSubrule(GrammarAST tree) { }\nprotected void exitLexerSubrule(GrammarAST tree) { }\n\nprotected void enterBlockSuffix(GrammarAST tree) { }\nprotected void exitBlockSuffix(GrammarAST tree) { }\n\nprotected void enterEbnfSuffix(GrammarAST tree) { }\nprotected void exitEbnfSuffix(GrammarAST tree) { }\n\nprotected void enterAtom(GrammarAST tree) { }\nprotected void exitAtom(GrammarAST tree) { }\n\nprotected void enterBlockSet(GrammarAST tree) { }\nprotected void exitBlockSet(GrammarAST tree) { }\n\nprotected void enterSetElement(GrammarAST tree) { }\nprotected void exitSetElement(GrammarAST tree) { }\n\nprotected void enterBlock(GrammarAST tree) { }\nprotected void exitBlock(GrammarAST tree) { }\n\nprotected void enterRuleref(GrammarAST tree) { }\nprotected void exitRuleref(GrammarAST tree) { }\n\nprotected void enterRange(GrammarAST tree) { }\nprotected void exitRange(GrammarAST tree) { }\n\nprotected void enterTerminal(GrammarAST tree) { }\nprotected void exitTerminal(GrammarAST tree) { }\n\nprotected void enterElementOptions(GrammarAST tree) { }\nprotected void exitElementOptions(GrammarAST tree) { }\n\nprotected void enterElementOption(GrammarAST tree) { }\nprotected void exitElementOption(GrammarAST tree) { }\n\n\t@Override\n\tpublic void traceIn(String ruleName, int ruleIndex)  {\n\t\tSystem.err.println(\"enter \"+ruleName+\": \"+input.LT(1));\n\t}\n\n\t@Override\n\tpublic void traceOut(String ruleName, int ruleIndex)  {\n\t\tSystem.err.println(\"exit \"+ruleName+\": \"+input.LT(1));\n\t}\n}\n\ngrammarSpec\n@init {\n\tenterGrammarSpec($start);\n}\n@after {\n\texitGrammarSpec($start);\n}\n    :   ^(\tGRAMMAR ID {grammarName=$ID.text;}\n    \t\t{discoverGrammar((GrammarRootAST)$GRAMMAR, $ID);}\n \t\t   \tprequelConstructs\n    \t\t{finishPrequels($prequelConstructs.firstOne);}\n \t\t   \trules mode*\n    \t\t{finishGrammar((GrammarRootAST)$GRAMMAR, $ID);}\n \t\t )\n\t;\n\nprequelConstructs returns [GrammarAST firstOne=null]\n@init {\n\tenterPrequelConstructs($start);\n}\n@after {\n\texitPrequelConstructs($start);\n}\n\t:\t{$firstOne=$start;} prequelConstruct+\n\t|\n\t;\n\nprequelConstruct\n@init {\n\tenterPrequelConstructs($start);\n}\n@after {\n\texitPrequelConstructs($start);\n}\n\t:   optionsSpec\n    |   delegateGrammars\n    |   tokensSpec\n    |   channelsSpec\n    |   action\n    ;\n\noptionsSpec\n@init {\n\tenterOptionsSpec($start);\n}\n@after {\n\texitOptionsSpec($start);\n}\n\t:\t^(OPTIONS option*)\n    ;\n\noption\n@init {\n\tenterOption($start);\n\tboolean rule = inContext(\"RULE ...\");\n\tboolean block = inContext(\"BLOCK ...\");\n}\n@after {\n\texitOption($start);\n}\n    :   ^(a=ASSIGN ID v=optionValue)\n    \t{\n    \tif ( block ) blockOption($ID, $v.start); // most specific first\n    \telse if ( rule ) ruleOption($ID, $v.start);\n    \telse grammarOption($ID, $v.start);\n    \t}\n    ;\n\noptionValue returns [String v]\n@init {\n\tenterOptionValue($start);\n\t$v = $start.token.getText();\n}\n@after {\n\texitOptionValue($start);\n}\n    :   ID\n    |   STRING_LITERAL\n    |   INT\n    ;\n\ndelegateGrammars\n@init {\n\tenterDelegateGrammars($start);\n}\n@after {\n\texitDelegateGrammars($start);\n}\n\t:   ^(IMPORT delegateGrammar+)\n\t;\n\ndelegateGrammar\n@init {\n\tenterDelegateGrammar($start);\n}\n@after {\n\texitDelegateGrammar($start);\n}\n    :   ^(ASSIGN label=ID id=ID)\t{importGrammar($label, $id);}\n    |   id=ID\t\t\t\t\t\t{importGrammar(null, $id);}\n    ;\n\ntokensSpec\n@init {\n\tenterTokensSpec($start);\n}\n@after {\n\texitTokensSpec($start);\n}\n\t:   ^(TOKENS_SPEC tokenSpec+)\n\t;\n\ntokenSpec\n@init {\n\tenterTokenSpec($start);\n}\n@after {\n\texitTokenSpec($start);\n}\n\t:\tID\t\t\t\t\t{defineToken($ID);}\n\t;\n\nchannelsSpec\n@init {\n\tenterChannelsSpec($start);\n}\n@after {\n\texitChannelsSpec($start);\n}\n\t:   ^(CHANNELS channelSpec+)\n\t;\n\nchannelSpec\n@init {\n\tenterChannelSpec($start);\n}\n@after {\n\texitChannelSpec($start);\n}\n\t:\tID\t\t\t\t\t{defineChannel($ID);}\n\t;\n\naction\n@init {\n\tenterAction($start);\n}\n@after {\n\texitAction($start);\n}\n\t:\t^(AT sc=ID? name=ID ACTION) {globalNamedAction($sc, $name, (ActionAST)$ACTION);}\n\t;\n\nrules\n@init {\n\tenterRules($start);\n}\n@after {\n\texitRules($start);\n}\n    : ^(RULES {discoverRules($RULES);} (rule|lexerRule)* {finishRules($RULES);})\n    ;\n\nmode\n@init {\n\tenterMode($start);\n}\n@after {\n\texitMode($start);\n}\n\t:\t^( MODE ID {currentModeName=$ID.text; modeDef($MODE, $ID);} lexerRule* )\n\t;\n\nlexerRule\n@init {\n\tenterLexerRule($start);\n\tList<GrammarAST> mods = new ArrayList<GrammarAST>();\n\tcurrentOuterAltNumber=0;\n}\n@after {\n\texitLexerRule($start);\n}\n\t:\t^(\tRULE TOKEN_REF\n\t\t\t{currentRuleName=$TOKEN_REF.text; currentRuleAST=$RULE;}\n\t\t\t(^(RULEMODIFIERS m=FRAGMENT {mods.add($m);}))?\n\t\t\topts=optionsSpec*\n      \t\t{discoverLexerRule((RuleAST)$RULE, $TOKEN_REF, mods, $opts.start, (GrammarAST)input.LT(1));}\n      \t\tlexerRuleBlock\n      \t\t{\n      \t\tfinishLexerRule((RuleAST)$RULE, $TOKEN_REF, $lexerRuleBlock.start);\n      \t\tcurrentRuleName=null; currentRuleAST=null;\n      \t\t}\n      \t )\n\t;\n\nrule\n@init {\n\tenterRule($start);\n\tList<GrammarAST> mods = new ArrayList<GrammarAST>();\n\tList<GrammarAST> actions = new ArrayList<GrammarAST>(); // track roots\n\tcurrentOuterAltNumber=0;\n}\n@after {\n\texitRule($start);\n}\n\t:   ^(\tRULE RULE_REF {currentRuleName=$RULE_REF.text; currentRuleAST=$RULE;}\n\t\t\t(^(RULEMODIFIERS (m=ruleModifier{mods.add($m.start);})+))?\n\t\t\tARG_ACTION?\n      \t\tret=ruleReturns?\n      \t\tthr=throwsSpec?\n      \t\tloc=locals?\n      \t\t(\topts=optionsSpec\n\t\t    |   a=ruleAction {actions.add($a.start);}\n\t\t    )*\n      \t\t{discoverRule((RuleAST)$RULE, $RULE_REF, mods, (ActionAST)$ARG_ACTION,\n      \t\t\t\t\t  $ret.start!=null?(ActionAST)$ret.start.getChild(0):null,\n      \t\t\t\t\t  $thr.start, $opts.start,\n      \t\t\t\t\t  $loc.start!=null?(ActionAST)$loc.start.getChild(0):null,\n      \t\t\t\t\t  actions, (GrammarAST)input.LT(1));}\n      \t\truleBlock exceptionGroup\n      \t\t{finishRule((RuleAST)$RULE, $RULE_REF, $ruleBlock.start); currentRuleName=null; currentRuleAST=null;}\n      \t )\n    ;\n\nexceptionGroup\n@init {\n\tenterExceptionGroup($start);\n}\n@after {\n\texitExceptionGroup($start);\n}\n    :\texceptionHandler* finallyClause?\n    ;\n\nexceptionHandler\n@init {\n\tenterExceptionHandler($start);\n}\n@after {\n\texitExceptionHandler($start);\n}\n\t: ^(CATCH ARG_ACTION ACTION)\t{ruleCatch($ARG_ACTION, (ActionAST)$ACTION);}\n\t;\n\nfinallyClause\n@init {\n\tenterFinallyClause($start);\n}\n@after {\n\texitFinallyClause($start);\n}\n\t: ^(FINALLY ACTION)\t\t\t\t{finallyAction((ActionAST)$ACTION);}\n\t;\n\nlocals\n@init {\n\tenterLocals($start);\n}\n@after {\n\texitLocals($start);\n}\n\t:\t^(LOCALS ARG_ACTION)\n\t;\n\nruleReturns\n@init {\n\tenterRuleReturns($start);\n}\n@after {\n\texitRuleReturns($start);\n}\n\t: ^(RETURNS ARG_ACTION)\n\t;\n\nthrowsSpec\n@init {\n\tenterThrowsSpec($start);\n}\n@after {\n\texitThrowsSpec($start);\n}\n    : ^(THROWS ID+)\n    ;\n\nruleAction\n@init {\n\tenterRuleAction($start);\n}\n@after {\n\texitRuleAction($start);\n}\n\t:\t^(AT ID ACTION)\n\t;\n\nruleModifier\n@init {\n\tenterRuleModifier($start);\n}\n@after {\n\texitRuleModifier($start);\n}\n    : PUBLIC\n    | PRIVATE\n    | PROTECTED\n    | FRAGMENT\n    ;\n\nlexerRuleBlock\n@init {\n\tenterLexerRuleBlock($start);\n}\n@after {\n\texitLexerRuleBlock($start);\n}\n    :\t^(\tBLOCK\n    \t\t(\t{\n    \t\t\tcurrentOuterAltRoot = (GrammarAST)input.LT(1);\n\t\t\t\tcurrentOuterAltNumber++;\n\t\t\t\t}\n    \t\t\tlexerOuterAlternative\n    \t\t)+\n    \t)\n    ;\n\nruleBlock\n@init {\n\tenterRuleBlock($start);\n}\n@after {\n\texitRuleBlock($start);\n}\n    :\t^(\tBLOCK\n    \t\t(\t{\n    \t\t\tcurrentOuterAltRoot = (GrammarAST)input.LT(1);\n\t\t\t\tcurrentOuterAltNumber++;\n\t\t\t\t}\n    \t\t\touterAlternative\n    \t\t)+\n    \t)\n    ;\n\nlexerOuterAlternative\n@init {\n\tenterLexerOuterAlternative((AltAST)$start);\n\tdiscoverOuterAlt((AltAST)$start);\n}\n@after {\n\tfinishOuterAlt((AltAST)$start);\n\texitLexerOuterAlternative((AltAST)$start);\n}\n\t:\tlexerAlternative\n\t;\n\n\nouterAlternative\n@init {\n\tenterOuterAlternative((AltAST)$start);\n\tdiscoverOuterAlt((AltAST)$start);\n}\n@after {\n\tfinishOuterAlt((AltAST)$start);\n\texitOuterAlternative((AltAST)$start);\n}\n\t:\talternative\n\t;\n\nlexerAlternative\n@init {\n\tenterLexerAlternative($start);\n}\n@after {\n\texitLexerAlternative($start);\n}\n\t:\t^(LEXER_ALT_ACTION lexerElements lexerCommand+)\n    |   lexerElements\n    ;\n\nlexerElements\n@init {\n\tenterLexerElements($start);\n}\n@after {\n\texitLexerElements($start);\n}\n    :\t^(ALT lexerElement+)\n    ;\n\nlexerElement\n@init {\n\tenterLexerElement($start);\n}\n@after {\n\texitLexerElement($start);\n}\n\t:\tlexerAtom\n\t|\tlexerSubrule\n\t|   ACTION\t\t\t\t\t\t{actionInAlt((ActionAST)$ACTION);}\n\t|   SEMPRED\t\t\t\t\t\t{sempredInAlt((PredAST)$SEMPRED);}\n\t|   ^(ACTION elementOptions)\t{actionInAlt((ActionAST)$ACTION);}\n\t|   ^(SEMPRED elementOptions)\t{sempredInAlt((PredAST)$SEMPRED);}\n\t|\tEPSILON\n\t;\n\nlexerBlock\n@init {\n\tenterLexerBlock($start);\n}\n@after {\n\texitLexerBlock($start);\n}\n \t:\t^(BLOCK optionsSpec? lexerAlternative+)\n    ;\n\nlexerAtom\n@init {\n\tenterLexerAtom($start);\n}\n@after {\n\texitLexerAtom($start);\n}\n    :   terminal\n    |   ^(NOT blockSet)\n    |   blockSet\n    |   ^(WILDCARD elementOptions)\n    |   WILDCARD\n    |\tLEXER_CHAR_SET\n    |   range\n    |   ruleref\n    ;\n\nactionElement\n@init {\n\tenterActionElement($start);\n}\n@after {\n\texitActionElement($start);\n}\n\t:\tACTION\n\t|   ^(ACTION elementOptions)\n\t|   SEMPRED\n\t|   ^(SEMPRED elementOptions)\n\t;\n\nalternative\n@init {\n\tenterAlternative((AltAST)$start);\n\tdiscoverAlt((AltAST)$start);\n}\n@after {\n\tfinishAlt((AltAST)$start);\n\texitAlternative((AltAST)$start);\n}\n\t:\t^(ALT elementOptions? element+)\n\t|\t^(ALT elementOptions? EPSILON)\n    ;\n\nlexerCommand\n@init {\n\tenterLexerCommand($start);\n}\n@after {\n\texitLexerCommand($start);\n}\n\t:\t^(LEXER_ACTION_CALL ID lexerCommandExpr)\n        {lexerCallCommand(currentOuterAltNumber, $ID, $lexerCommandExpr.start);}\n\t|\tID\n        {lexerCommand(currentOuterAltNumber, $ID);}\n\t;\n\nlexerCommandExpr\n@init {\n\tenterLexerCommandExpr($start);\n}\n@after {\n\texitLexerCommandExpr($start);\n}\n\t:\tID\n\t|\tINT\n\t;\n\nelement\n@init {\n\tenterElement($start);\n}\n@after {\n\texitElement($start);\n}\n\t:\tlabeledElement\n\t|\tatom\n\t|\tsubrule\n\t|   ACTION\t\t\t\t\t\t{actionInAlt((ActionAST)$ACTION);}\n\t|   SEMPRED\t\t\t\t\t\t{sempredInAlt((PredAST)$SEMPRED);}\n\t|   ^(ACTION elementOptions)\t{actionInAlt((ActionAST)$ACTION);}\n\t|   ^(SEMPRED elementOptions)\t{sempredInAlt((PredAST)$SEMPRED);}\n\t|\trange\n\t|\t^(NOT blockSet)\n\t|\t^(NOT block)\n\t;\n\nastOperand\n@init {\n\tenterAstOperand($start);\n}\n@after {\n\texitAstOperand($start);\n}\n\t:\tatom\n\t|\t^(NOT blockSet)\n\t|\t^(NOT block)\n\t;\n\nlabeledElement\n@init {\n\tenterLabeledElement($start);\n}\n@after {\n\texitLabeledElement($start);\n}\n\t:\t^((ASSIGN|PLUS_ASSIGN) ID element) {label($start, $ID, $element.start);}\n\t;\n\nsubrule\n@init {\n\tenterSubrule($start);\n}\n@after {\n\texitSubrule($start);\n}\n\t:\t^(blockSuffix block)\n\t| \tblock\n    ;\n\nlexerSubrule\n@init {\n\tenterLexerSubrule($start);\n}\n@after {\n\texitLexerSubrule($start);\n}\n\t:\t^(blockSuffix lexerBlock)\n\t| \tlexerBlock\n    ;\n\nblockSuffix\n@init {\n\tenterBlockSuffix($start);\n}\n@after {\n\texitBlockSuffix($start);\n}\n    : ebnfSuffix\n    ;\n\nebnfSuffix\n@init {\n\tenterEbnfSuffix($start);\n}\n@after {\n\texitEbnfSuffix($start);\n}\n\t:\tOPTIONAL\n  \t|\tCLOSURE\n   \t|\tPOSITIVE_CLOSURE\n\t;\n\natom\n@init {\n\tenterAtom($start);\n}\n@after {\n\texitAtom($start);\n}\n\t:\t^(DOT ID terminal)\n\t|\t^(DOT ID ruleref)\n    |\t^(WILDCARD elementOptions)\t{wildcardRef($WILDCARD);}\n    |\tWILDCARD\t\t\t\t\t{wildcardRef($WILDCARD);}\n    |   terminal\n    |\tblockSet\n    |   ruleref\n    ;\n\nblockSet\n@init {\n\tenterBlockSet($start);\n}\n@after {\n\texitBlockSet($start);\n}\n\t:\t^(SET setElement+)\n\t;\n\nsetElement\n@init {\n\tenterSetElement($start);\n}\n@after {\n\texitSetElement($start);\n}\n\t:\t^(STRING_LITERAL elementOptions)    {stringRef((TerminalAST)$STRING_LITERAL);}\n\t|\t^(TOKEN_REF elementOptions) \t\t{tokenRef((TerminalAST)$TOKEN_REF);}\n\t|\tSTRING_LITERAL                  \t{stringRef((TerminalAST)$STRING_LITERAL);}\n\t|\tTOKEN_REF\t\t                    {tokenRef((TerminalAST)$TOKEN_REF);}\n\t|\t^(RANGE a=STRING_LITERAL b=STRING_LITERAL)\n\t\t{\n\t\tstringRef((TerminalAST)$a);\n\t\tstringRef((TerminalAST)$b);\n\t\t}\n        |       LEXER_CHAR_SET\n\t;\n\nblock\n@init {\n\tenterBlock($start);\n}\n@after {\n\texitBlock($start);\n}\n    :\t^(BLOCK optionsSpec? ruleAction* ACTION? alternative+)\n    ;\n\nruleref\n@init {\n\tenterRuleref($start);\n}\n@after {\n\texitRuleref($start);\n}\n    :\t^(RULE_REF arg=ARG_ACTION? elementOptions?)\n    \t{\n    \truleRef($RULE_REF, (ActionAST)$ARG_ACTION);\n    \tif ( $arg!=null ) actionInAlt((ActionAST)$arg);\n    \t}\n    ;\n\nrange\n@init {\n\tenterRange($start);\n}\n@after {\n\texitRange($start);\n}\n    : ^(RANGE STRING_LITERAL STRING_LITERAL)\n    ;\n\nterminal\n@init {\n\tenterTerminal($start);\n}\n@after {\n\texitTerminal($start);\n}\n    :  ^(STRING_LITERAL elementOptions)\n    \t\t\t\t\t\t\t\t{stringRef((TerminalAST)$STRING_LITERAL);}\n    |\tSTRING_LITERAL\t\t\t\t{stringRef((TerminalAST)$STRING_LITERAL);}\n    |\t^(TOKEN_REF elementOptions)\t{tokenRef((TerminalAST)$TOKEN_REF);}\n    |\tTOKEN_REF\t    \t\t\t{tokenRef((TerminalAST)$TOKEN_REF);}\n    ;\n\nelementOptions\n@init {\n\tenterElementOptions($start);\n}\n@after {\n\texitElementOptions($start);\n}\n    :\t^(ELEMENT_OPTIONS elementOption[(GrammarASTWithOptions)$start.getParent()]*)\n    ;\n\nelementOption[GrammarASTWithOptions t]\n@init {\n\tenterElementOption($start);\n}\n@after {\n\texitElementOption($start);\n}\n    :\tID\t\t\t\t\t\t\t\t{elementOption(t, $ID, null);}\n    |   ^(ASSIGN id=ID v=ID)\t\t\t{elementOption(t, $id, $v);}\n    |   ^(ASSIGN ID v=STRING_LITERAL)\t{elementOption(t, $ID, $v);}\n    |   ^(ASSIGN ID v=ACTION)\t\t\t{elementOption(t, $ID, $v);}\n    |   ^(ASSIGN ID v=INT)\t\t\t\t{elementOption(t, $ID, $v);}\n    ;\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/LeftRecursiveRuleWalker.g",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** Find left-recursive rules */\ntree grammar LeftRecursiveRuleWalker;\n\noptions {\n\ttokenVocab=ANTLRParser;\n    ASTLabelType=GrammarAST;\n}\n\n@header {\npackage org.antlr.v4.parse;\n\nimport org.antlr.v4.misc.*;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.*;\n}\n\n@members {\nprivate String ruleName;\nprivate int currentOuterAltNumber; // which outer alt of rule?\npublic int numAlts;  // how many alts for this rule total?\n\npublic void setAltAssoc(AltAST altTree, int alt) {}\npublic void binaryAlt(AltAST altTree, int alt) {}\npublic void prefixAlt(AltAST altTree, int alt) {}\npublic void suffixAlt(AltAST altTree, int alt) {}\npublic void otherAlt(AltAST altTree, int alt) {}\npublic void setReturnValues(GrammarAST t) {}\n}\n\n@rulecatch { }\n\n// TODO: can get parser errors for not matching pattern; make them go away\npublic\nrec_rule returns [boolean isLeftRec]\n@init\n{\n\tcurrentOuterAltNumber = 1;\n}\n\t:\t^(\tr=RULE id=RULE_REF {ruleName=$id.getText();}\n\t\t\truleModifier?\n//\t\t\t(ARG_ACTION)? shouldn't allow args, right?\n\t\t\t(^(RETURNS a=ARG_ACTION {setReturnValues($a);}))?\n//      \t\t( ^(THROWS .+) )? don't allow\n      \t\t( ^(LOCALS ARG_ACTION) )? // TODO: copy these to gen'd code\n      \t\t(\t^(OPTIONS .*)\n\t\t    |   ^(AT ID ACTION) // TODO: copy\n\t\t    )*\n\t\t\truleBlock {$isLeftRec = $ruleBlock.isLeftRec;}\n\t\t\texceptionGroup\n\t\t)\n\t;\n\nexceptionGroup\n    :\texceptionHandler* finallyClause?\n    ;\n\nexceptionHandler\n\t: ^(CATCH ARG_ACTION ACTION)\n\t;\n\nfinallyClause\n\t: ^(FINALLY ACTION)\n\t;\n\nruleModifier\n    : PUBLIC\n    | PRIVATE\n    | PROTECTED\n    ;\n\nruleBlock returns [boolean isLeftRec]\n@init{boolean lr=false; this.numAlts = $start.getChildCount();}\n\t:\t^(\tBLOCK\n\t\t\t(\n\t\t\t\to=outerAlternative\n\t\t\t\t{if ($o.isLeftRec) $isLeftRec = true;}\n\t\t\t\t{currentOuterAltNumber++;}\n\t\t\t)+\n\t\t)\n\t;\n\n/** An alt is either prefix, suffix, binary, or ternary operation or \"other\" */\nouterAlternative returns [boolean isLeftRec]\n    :   (binary)=>           binary\n                             {binaryAlt((AltAST)$start, currentOuterAltNumber); $isLeftRec=true;}\n    |   (prefix)=>           prefix\n                             {prefixAlt((AltAST)$start, currentOuterAltNumber);}\n    |   (suffix)=>           suffix\n                             {suffixAlt((AltAST)$start, currentOuterAltNumber); $isLeftRec=true;}\n    |   nonLeftRecur         {otherAlt((AltAST)$start,  currentOuterAltNumber);}\n    ;\n\nbinary\n\t:\t^( ALT elementOptions? recurse element* recurse epsilonElement* )\n        {setAltAssoc((AltAST)$ALT,currentOuterAltNumber);}\n\t;\n\nprefix\n\t:\t^(\tALT elementOptions?\n\t\t\telement+\n\t\t\trecurse epsilonElement*\n\t\t )\n         {setAltAssoc((AltAST)$ALT,currentOuterAltNumber);}\n\t;\n\nsuffix\n    :   ^( ALT elementOptions? recurse element+ )\n         {setAltAssoc((AltAST)$ALT,currentOuterAltNumber);}\n    ;\n\nnonLeftRecur\n    :   ^(ALT elementOptions? element+)\n    ;\n\nrecurse\n\t:\t^(ASSIGN ID recurseNoLabel)\n\t|\t^(PLUS_ASSIGN ID recurseNoLabel)\n\t|\trecurseNoLabel\n\t;\n\nrecurseNoLabel : {((CommonTree)input.LT(1)).getText().equals(ruleName)}? RULE_REF;\n\ntoken returns [GrammarAST t=null]\n\t:\t^(ASSIGN ID s=token {$t = $s.t;})\n\t|\t^(PLUS_ASSIGN ID s=token {$t = $s.t;})\n\t|\tb=STRING_LITERAL    \t\t\t\t\t{$t = $b;}\n    |\t^(b=STRING_LITERAL elementOptions)\t\t{$t = $b;}\n    |\t^(c=TOKEN_REF elementOptions)\t\t\t{$t = $c;}\n\t|\tc=TOKEN_REF        \t\t\t\t\t\t{$t = $c;}\n\t;\n\nelementOptions\n    :\t^(ELEMENT_OPTIONS elementOption*)\n    ;\n\nelementOption\n    :\tID\n    |   ^(ASSIGN ID ID)\n    |   ^(ASSIGN ID STRING_LITERAL)\n    |   ^(ASSIGN ID ACTION)\n    |   ^(ASSIGN ID INT)\n    ;\n\nelement\n\t:\tatom\n\t|\t^(NOT element)\n\t|\t^(RANGE atom atom)\n\t|\t^(ASSIGN ID element)\n\t|\t^(PLUS_ASSIGN ID element)\n    |\t^(SET setElement+)\n    |   RULE_REF\n\t|\tebnf\n\t|\tepsilonElement\n\t;\n\nepsilonElement\n\t:\tACTION\n\t|\tSEMPRED\n\t|\tEPSILON\n\t|\t^(ACTION elementOptions)\n\t|\t^(SEMPRED elementOptions)\n\t;\n\nsetElement\n\t:\t^(STRING_LITERAL elementOptions)\n\t|\t^(TOKEN_REF elementOptions)\n\t|\tSTRING_LITERAL\n\t|\tTOKEN_REF\n\t;\n\nebnf:   block\n    |   ^( OPTIONAL block )\n    |   ^( CLOSURE block )\n    |   ^( POSITIVE_CLOSURE block )\n    ;\n\nblock\n    :\t^(BLOCK ACTION? alternative+)\n    ;\n\nalternative\n\t:\t^(ALT elementOptions? element+)\n    ;\n\natom\n\t:\t^(RULE_REF ARG_ACTION? elementOptions?)\n    |  ^(STRING_LITERAL elementOptions)\n\t|\tSTRING_LITERAL\n    |\t^(TOKEN_REF elementOptions)\n\t|\tTOKEN_REF\n    |\t^(WILDCARD elementOptions)\n\t|\tWILDCARD\n\t|\t^(DOT ID element)\n\t;\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ResyncToEndOfRuleBlock.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\n/** Used to throw us out of deeply nested element back to end of a rule's\n *  alt list. Note it's not under RecognitionException.\n */\npublic class ResyncToEndOfRuleBlock extends RuntimeException {\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ScopeParser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.BaseRecognizer;\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.Attribute;\nimport org.antlr.v4.tool.AttributeDict;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.ast.ActionAST;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Parse args, return values, locals\n * <p>\n * rule[arg1, arg2, ..., argN] returns [ret1, ..., retN]\n * <p>\n * text is target language dependent.  Java/C#/C/C++ would\n * use \"int i\" but ruby/python would use \"i\". Languages with\n * postfix types like Go, Swift use \"x : T\" notation or \"T x\".\n */\npublic class ScopeParser {\n\t/**\n\t * Given an arg or retval scope definition list like\n\t * <p>\n\t * <code>\n\t * Map&lt;String, String&gt;, int[] j3, char *foo32[3]\n\t * </code>\n\t * <p>\n\t * or\n\t * <p>\n\t * <code>\n\t * int i=3, j=a[34]+20\n\t * </code>\n\t * <p>\n\t * convert to an attribute scope.\n\t */\n\tpublic static AttributeDict parseTypedArgList(ActionAST action, String s, Grammar g) {\n\t\treturn parse(action, s, ',', g);\n\t}\n\n\tpublic static AttributeDict parse(ActionAST action, String s, char separator, Grammar g) {\n\t\tAttributeDict dict = new AttributeDict();\n\t\tList<Pair<String, Integer>> decls = splitDecls(s, separator);\n\t\tfor (Pair<String, Integer> decl : decls) {\n\t\t\tif (decl.a.trim().length() > 0) {\n\t\t\t\tAttribute a = parseAttributeDef(action, decl, g);\n\t\t\t\tdict.add(a);\n\t\t\t}\n\t\t}\n\t\treturn dict;\n\t}\n\n\t/**\n\t * For decls like \"String foo\" or \"char *foo32[]\" compute the ID\n\t * and type declarations.  Also handle \"int x=3\" and 'T t = new T(\"foo\")'\n\t * but if the separator is ',' you cannot use ',' in the initvalue\n\t * unless you escape use \"\\,\" escape.\n\t */\n\tpublic static Attribute parseAttributeDef(ActionAST action, Pair<String, Integer> decl, Grammar g) {\n\t\tif (decl.a == null) return null;\n\n\t\tAttribute attr = new Attribute();\n\t\tint rightEdgeOfDeclarator = decl.a.length() - 1;\n\t\tint equalsIndex = decl.a.indexOf('=');\n\t\tif (equalsIndex > 0) {\n\t\t\t// everything after the '=' is the init value\n\t\t\tattr.initValue = decl.a.substring(equalsIndex + 1, decl.a.length()).trim();\n\t\t\trightEdgeOfDeclarator = equalsIndex - 1;\n\t\t}\n\n\t\tString declarator = decl.a.substring(0, rightEdgeOfDeclarator + 1);\n\t\tPair<Integer, Integer> p;\n\t\tString text = decl.a;\n\t\ttext = text.replaceAll(\"::\",\"\");\n\t\tif ( text.contains(\":\") ) {\n\t\t\t// declarator has type appearing after the name like \"x:T\"\n\t\t\tp = _parsePostfixDecl(attr, declarator, action, g);\n\t\t}\n\t\telse {\n\t\t\t// declarator has type appearing before the name like \"T x\"\n\t\t\tp = _parsePrefixDecl(attr, declarator, action, g);\n\t\t}\n\t\tint idStart = p.a;\n\t\tint idStop = p.b;\n\n\t\tattr.decl = decl.a;\n\n\t\tif (action != null) {\n\t\t\tString actionText = action.getText();\n\t\t\tint[] lines = new int[actionText.length()];\n\t\t\tint[] charPositionInLines = new int[actionText.length()];\n\t\t\tfor (int i = 0, line = 0, col = 0; i < actionText.length(); i++, col++) {\n\t\t\t\tlines[i] = line;\n\t\t\t\tcharPositionInLines[i] = col;\n\t\t\t\tif (actionText.charAt(i) == '\\n') {\n\t\t\t\t\tline++;\n\t\t\t\t\tcol = -1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint[] charIndexes = new int[actionText.length()];\n\t\t\tfor (int i = 0, j = 0; i < actionText.length(); i++, j++) {\n\t\t\t\tcharIndexes[j] = i;\n\t\t\t\t// skip comments\n\t\t\t\tif (i < actionText.length() - 1 && actionText.charAt(i) == '/' && actionText.charAt(i + 1) == '/') {\n\t\t\t\t\twhile (i < actionText.length() && actionText.charAt(i) != '\\n') {\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint declOffset = charIndexes[decl.b];\n\t\t\tint declLine = lines[declOffset + idStart];\n\n\t\t\tint line = action.getToken().getLine() + declLine;\n\t\t\tint charPositionInLine = charPositionInLines[declOffset + idStart];\n\t\t\tif (declLine == 0) {\n\t\t\t\t/* offset for the start position of the ARG_ACTION token, plus 1\n\t\t\t\t * since the ARG_ACTION text had the leading '[' stripped before\n\t\t\t\t * reaching the scope parser.\n\t\t\t\t */\n\t\t\t\tcharPositionInLine += action.getToken().getCharPositionInLine() + 1;\n\t\t\t}\n\n\t\t\tint offset = ((CommonToken) action.getToken()).getStartIndex();\n\t\t\tattr.token = new CommonToken(action.getToken().getInputStream(), ANTLRParser.ID, BaseRecognizer.DEFAULT_TOKEN_CHANNEL, offset + declOffset + idStart + 1, offset + declOffset + idStop);\n\t\t\tattr.token.setLine(line);\n\t\t\tattr.token.setCharPositionInLine(charPositionInLine);\n\t\t\tassert attr.name.equals(attr.token.getText()) : \"Attribute text should match the pseudo-token text at this point.\";\n\t\t}\n\n\t\treturn attr;\n\t}\n\n\tpublic static Pair<Integer, Integer> _parsePrefixDecl(Attribute attr, String decl, ActionAST a, Grammar g) {\n\t\t// walk backwards looking for start of an ID\n\t\tboolean inID = false;\n\t\tint start = -1;\n\t\tfor (int i = decl.length() - 1; i >= 0; i--) {\n\t\t\tchar ch = decl.charAt(i);\n\t\t\t// if we haven't found the end yet, keep going\n\t\t\tif (!inID && Character.isLetterOrDigit(ch)) {\n\t\t\t\tinID = true;\n\t\t\t}\n\t\t\telse if (inID && !(Character.isLetterOrDigit(ch) || ch == '_')) {\n\t\t\t\tstart = i + 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (start < 0 && inID) {\n\t\t\tstart = 0;\n\t\t}\n\t\tif (start < 0) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.CANNOT_FIND_ATTRIBUTE_NAME_IN_DECL, g.fileName, a.token, decl);\n\t\t}\n\n\t\t// walk forward looking for end of an ID\n\t\tint stop = -1;\n\t\tfor (int i = start; i < decl.length(); i++) {\n\t\t\tchar ch = decl.charAt(i);\n\t\t\t// if we haven't found the end yet, keep going\n\t\t\tif (!(Character.isLetterOrDigit(ch) || ch == '_')) {\n\t\t\t\tstop = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (i == decl.length() - 1) {\n\t\t\t\tstop = i + 1;\n\t\t\t}\n\t\t}\n\n\t\t// the name is the last ID\n\t\tattr.name = decl.substring(start, stop);\n\n\t\t// the type is the decl minus the ID (could be empty)\n\t\tattr.type = decl.substring(0, start);\n\t\tif (stop <= decl.length() - 1) {\n\t\t\tattr.type += decl.substring(stop, decl.length());\n\t\t}\n\n\t\tattr.type = attr.type.trim();\n\t\tif (attr.type.length() == 0) {\n\t\t\tattr.type = null;\n\t\t}\n\t\treturn new Pair<Integer, Integer>(start, stop);\n\t}\n\n\tpublic static Pair<Integer, Integer> _parsePostfixDecl(Attribute attr, String decl, ActionAST a, Grammar g) {\n\t\tint start = -1;\n\t\tint stop = -1;\n\t\tint colon = decl.indexOf(':');\n\t\tint namePartEnd = colon == -1 ? decl.length() : colon;\n\n\t\t// look for start of name\n\t\tfor (int i = 0; i < namePartEnd; ++i) {\n\t\t\tchar ch = decl.charAt(i);\n\t\t\tif (Character.isLetterOrDigit(ch) || ch == '_') {\n\t\t\t\tstart = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (start == -1) {\n\t\t\tstart = 0;\n\t\t\tg.tool.errMgr.grammarError(ErrorType.CANNOT_FIND_ATTRIBUTE_NAME_IN_DECL, g.fileName, a.token, decl);\n\t\t}\n\n\t\t// look for stop of name\n\t\tfor (int i = start; i < namePartEnd; ++i) {\n\t\t\tchar ch = decl.charAt(i);\n\t\t\tif (!(Character.isLetterOrDigit(ch) || ch == '_')) {\n\t\t\t\tstop = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (i == namePartEnd - 1) {\n\t\t\t\tstop = namePartEnd;\n\t\t\t}\n\t\t}\n\n\t\tif (stop == -1) {\n\t\t\tstop = start;\n\t\t}\n\n\t\t// extract name from decl\n\t\tattr.name =  decl.substring(start, stop);\n\n\t\t// extract type from decl (could be empty)\n\t\tif (colon == -1) {\n\t\t\tattr.type = \"\";\n\t\t}\n\t\telse {\n\t\t\tattr.type = decl.substring(colon + 1, decl.length());\n\t\t}\n\t\tattr.type = attr.type.trim();\n\n\t\tif (attr.type.length() == 0) {\n\t\t\tattr.type = null;\n\t\t}\n\t\treturn new Pair<Integer, Integer>(start, stop);\n\t}\n\n\t/**\n\t * Given an argument list like\n\t * <p>\n\t * x, (*a).foo(21,33), 3.2+1, '\\n',\n\t * \"a,oo\\nick\", {bl, \"fdkj\"eck}, [\"cat\\n,\", x, 43]\n\t * <p>\n\t * convert to a list of attributes.  Allow nested square brackets etc...\n\t * Set separatorChar to ';' or ',' or whatever you want.\n\t */\n\tpublic static List<Pair<String, Integer>> splitDecls(String s, int separatorChar) {\n\t\tList<Pair<String, Integer>> args = new ArrayList<Pair<String, Integer>>();\n\t\t_splitArgumentList(s, 0, -1, separatorChar, args);\n\t\treturn args;\n\t}\n\n\tpublic static int _splitArgumentList(String actionText,\n\t                                     int start,\n\t                                     int targetChar,\n\t                                     int separatorChar,\n\t                                     List<Pair<String, Integer>> args) {\n\t\tif (actionText == null) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tactionText = actionText.replaceAll(\"//[^\\\\n]*\", \"\");\n\t\tint n = actionText.length();\n\t\t//System.out.println(\"actionText@\"+start+\"->\"+(char)targetChar+\"=\"+actionText.substring(start,n));\n\t\tint p = start;\n\t\tint last = p;\n\t\twhile (p < n && actionText.charAt(p) != targetChar) {\n\t\t\tint c = actionText.charAt(p);\n\t\t\tswitch (c) {\n\t\t\t\tcase '\\'':\n\t\t\t\t\tp++;\n\t\t\t\t\twhile (p < n && actionText.charAt(p) != '\\'') {\n\t\t\t\t\t\tif (actionText.charAt(p) == '\\\\' && (p + 1) < n &&\n\t\t\t\t\t\t\t\tactionText.charAt(p + 1) == '\\'') {\n\t\t\t\t\t\t\tp++; // skip escaped quote\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp++;\n\t\t\t\t\t}\n\t\t\t\t\tp++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '\"':\n\t\t\t\t\tp++;\n\t\t\t\t\twhile (p < n && actionText.charAt(p) != '\\\"') {\n\t\t\t\t\t\tif (actionText.charAt(p) == '\\\\' && (p + 1) < n &&\n\t\t\t\t\t\t\t\tactionText.charAt(p + 1) == '\\\"') {\n\t\t\t\t\t\t\tp++; // skip escaped quote\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp++;\n\t\t\t\t\t}\n\t\t\t\t\tp++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase '(':\n\t\t\t\t\tp = _splitArgumentList(actionText, p + 1, ')', separatorChar, args);\n\t\t\t\t\tbreak;\n\t\t\t\tcase '{':\n\t\t\t\t\tp = _splitArgumentList(actionText, p + 1, '}', separatorChar, args);\n\t\t\t\t\tbreak;\n\t\t\t\tcase '<':\n\t\t\t\t\tif (actionText.indexOf('>', p + 1) >= p) {\n\t\t\t\t\t\t// do we see a matching '>' ahead?  if so, hope it's a generic\n\t\t\t\t\t\t// and not less followed by expr with greater than\n\t\t\t\t\t\tp = _splitArgumentList(actionText, p + 1, '>', separatorChar, args);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tp++; // treat as normal char\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase '[':\n\t\t\t\t\tp = _splitArgumentList(actionText, p + 1, ']', separatorChar, args);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif (c == separatorChar && targetChar == -1) {\n\t\t\t\t\t\tString arg = actionText.substring(last, p);\n\t\t\t\t\t\tint index = last;\n\t\t\t\t\t\twhile (index < p && Character.isWhitespace(actionText.charAt(index))) {\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//System.out.println(\"arg=\"+arg);\n\t\t\t\t\t\targs.add(new Pair<String, Integer>(arg.trim(), index));\n\t\t\t\t\t\tlast = p + 1;\n\t\t\t\t\t}\n\t\t\t\t\tp++;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (targetChar == -1 && p <= n) {\n\t\t\tString arg = actionText.substring(last, p).trim();\n\t\t\tint index = last;\n\t\t\twhile (index < p && Character.isWhitespace(actionText.charAt(index))) {\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\t//System.out.println(\"arg=\"+arg);\n\t\t\tif (arg.length() > 0) {\n\t\t\t\targs.add(new Pair<String, Integer>(arg.trim(), index));\n\t\t\t}\n\t\t}\n\t\tp++;\n\t\treturn p;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/TokenVocabParser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/** */\npublic class TokenVocabParser {\n\tprotected final Grammar g;\n\n\tpublic TokenVocabParser(Grammar g) {\n\t\tthis.g = g;\n\t}\n\n\t/** Load a vocab file {@code <vocabName>.tokens} and return mapping. */\n\tpublic Map<String,Integer> load() {\n\t\tMap<String,Integer> tokens = new LinkedHashMap<String,Integer>();\n\t\tint maxTokenType = -1;\n\t\tFile fullFile = getImportedVocabFile();\n\t\tFileInputStream fis = null;\n\t\tBufferedReader br = null;\n\t\tTool tool = g.tool;\n\t\tString vocabName = g.getOptionString(\"tokenVocab\");\n\t\ttry {\n\t\t\tPattern tokenDefPattern = Pattern.compile(\"([^\\n]+?)[ \\\\t]*?=[ \\\\t]*?([0-9]+)\");\n\t\t\tfis = new FileInputStream(fullFile);\n\t\t\tInputStreamReader isr;\n\t\t\tif (tool.grammarEncoding != null) {\n\t\t\t\tisr = new InputStreamReader(fis, tool.grammarEncoding);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tisr = new InputStreamReader(fis);\n\t\t\t}\n\n\t\t\tbr = new BufferedReader(isr);\n\t\t\tString tokenDef = br.readLine();\n\t\t\tint lineNum = 1;\n\t\t\twhile ( tokenDef!=null ) {\n\t\t\t\tMatcher matcher = tokenDefPattern.matcher(tokenDef);\n\t\t\t\tif ( matcher.find() ) {\n\t\t\t\t\tString tokenID = matcher.group(1);\n\t\t\t\t\tString tokenTypeS = matcher.group(2);\n\t\t\t\t\tint tokenType;\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttokenType = Integer.valueOf(tokenTypeS);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (NumberFormatException nfe) {\n\t\t\t\t\t\ttool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR,\n\t\t\t\t\t\t\t\t\t\t\t  vocabName + CodeGenerator.VOCAB_FILE_EXTENSION,\n\t\t\t\t\t\t\t\t\t\t\t  \" bad token type: \"+tokenTypeS,\n\t\t\t\t\t\t\t\t\t\t\t  lineNum);\n\t\t\t\t\t\ttokenType = Token.INVALID_TOKEN_TYPE;\n\t\t\t\t\t}\n\t\t\t\t\ttool.log(\"grammar\", \"import \"+tokenID+\"=\"+tokenType);\n\t\t\t\t\ttokens.put(tokenID, tokenType);\n\t\t\t\t\tmaxTokenType = Math.max(maxTokenType,tokenType);\n\t\t\t\t\tlineNum++;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif ( tokenDef.length()>0 ) { // ignore blank lines\n\t\t\t\t\t\ttool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR,\n\t\t\t\t\t\t\t\t\t\t\t  vocabName + CodeGenerator.VOCAB_FILE_EXTENSION,\n\t\t\t\t\t\t\t\t\t\t\t  \" bad token def: \" + tokenDef,\n\t\t\t\t\t\t\t\t\t\t\t  lineNum);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttokenDef = br.readLine();\n\t\t\t}\n\t\t}\n\t\tcatch (FileNotFoundException fnfe) {\n\t\t\tGrammarAST inTree = g.ast.getOptionAST(\"tokenVocab\");\n\t\t\tString inTreeValue = inTree.getToken().getText();\n\t\t\tif ( vocabName.equals(inTreeValue) ) {\n\t\t\t\ttool.errMgr.grammarError(ErrorType.CANNOT_FIND_TOKENS_FILE_REFD_IN_GRAMMAR,\n\t\t\t\t\t\t\t\t\t\t g.fileName,\n\t\t\t\t\t\t\t\t\t\t inTree.getToken(),\n\t\t\t\t\t\t\t\t\t\t fullFile);\n\t\t\t}\n\t\t\telse { // must be from -D option on cmd-line not token in tree\n\t\t\t\ttool.errMgr.toolError(ErrorType.CANNOT_FIND_TOKENS_FILE_GIVEN_ON_CMDLINE,\n\t\t\t\t\t\t\t\t\t  fullFile,\n\t\t\t\t\t\t\t\t\t  g.name);\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\ttool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE,\n\t\t\t\t\t\t\t\t  e,\n\t\t\t\t\t\t\t\t  fullFile,\n\t\t\t\t\t\t\t\t  e.getMessage());\n\t\t}\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tif ( br!=null ) br.close();\n\t\t\t}\n\t\t\tcatch (IOException ioe) {\n\t\t\t\ttool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE,\n\t\t\t\t\t\t\t\t\t  ioe,\n\t\t\t\t\t\t\t\t\t  fullFile,\n\t\t\t\t\t\t\t\t\t  ioe.getMessage());\n\t\t\t}\n\t\t}\n\t\treturn tokens;\n\t}\n\n\t/** Return a File descriptor for vocab file.  Look in library or\n\t *  in -o output path.  antlr -o foo T.g4 U.g4 where U needs T.tokens\n\t *  won't work unless we look in foo too. If we do not find the\n\t *  file in the lib directory then must assume that the .tokens file\n\t *  is going to be generated as part of this build and we have defined\n\t *  .tokens files so that they ALWAYS are generated in the base output\n\t *  directory, which means the current directory for the command line tool if there\n\t *  was no output directory specified.\n\t */\n\tpublic File getImportedVocabFile() {\n\t\tString vocabName = g.getOptionString(\"tokenVocab\");\n\t\tFile f = new File(g.tool.libDirectory,\n\t\t\t\t\t\t  File.separator +\n\t\t\t\t\t\t  vocabName +\n\t\t\t\t\t\t  CodeGenerator.VOCAB_FILE_EXTENSION);\n\t\tif (f.exists()) {\n\t\t\treturn f;\n\t\t}\n\n\t\t// We did not find the vocab file in the lib directory, so we need\n\t\t// to look for it in the output directory which is where .tokens\n\t\t// files are generated (in the base, not relative to the input\n\t\t// location.)\n\t\tf = new File(g.tool.outputDirectory, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION);\n\t\tif ( f.exists() ) {\n\t\t\treturn f;\n\t\t}\n\t\t\n\t\t// Still not found? Use the grammar's subfolder then.\n\t\tString fileDirectory;\n\n\t\tif (g.fileName.lastIndexOf(File.separatorChar) == -1) {\n\t\t\t// No path is included in the file name, so make the file\n\t\t\t// directory the same as the parent grammar (which might still be just \"\"\n\t\t\t// but when it is not, we will write the file in the correct place.\n\t\t\tfileDirectory = \".\";\n\t\t}\n\t\telse {\n\t\t\tfileDirectory = g.fileName.substring(0, g.fileName.lastIndexOf(File.separatorChar));\n\t\t}\n\t\treturn new File(fileDirectory, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ToolANTLRLexer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.CharStream;\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.tool.ErrorType;\n\npublic class ToolANTLRLexer extends ANTLRLexer {\n\tpublic Tool tool;\n\n\tpublic ToolANTLRLexer(CharStream input, Tool tool) {\n\t\tsuper(input);\n\t\tthis.tool = tool;\n\t}\n\n\t@Override\n\tpublic void displayRecognitionError(String[] tokenNames, RecognitionException e) {\n\t\tString msg = getErrorMessage(e, tokenNames);\n\t\ttool.errMgr.syntaxError(ErrorType.SYNTAX_ERROR, getSourceName(), e.token, e, msg);\n\t}\n\n\t@Override\n\tpublic void grammarError(ErrorType etype, Token token, Object... args) {\n\t\ttool.errMgr.grammarError(etype, getSourceName(), token, args);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/ToolANTLRParser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.NoViableAltException;\nimport org.antlr.runtime.Parser;\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.runtime.TokenStream;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.tool.ErrorType;\n\n/** Override error handling for use with ANTLR tool itself; leaves\n *  nothing in grammar associated with Tool so others can use in IDEs, ...\n */\npublic class ToolANTLRParser extends ANTLRParser {\n\tpublic Tool tool;\n\n\tpublic ToolANTLRParser(TokenStream input, Tool tool) {\n\t\tsuper(input);\n\t\tthis.tool = tool;\n\t}\n\n\t@Override\n\tpublic void displayRecognitionError(String[] tokenNames,\n\t\t\t\t\t\t\t\t\t\tRecognitionException e)\n\t{\n\t\tString msg = getParserErrorMessage(this, e);\n\t\tif ( !paraphrases.isEmpty() ) {\n\t\t\tString paraphrase = paraphrases.peek();\n\t\t\tmsg = msg+\" while \"+paraphrase;\n\t\t}\n\t//\tList stack = getRuleInvocationStack(e, this.getClass().getName());\n\t//\tmsg += \", rule stack = \"+stack;\n\t\ttool.errMgr.syntaxError(ErrorType.SYNTAX_ERROR, getSourceName(), e.token, e, msg);\n\t}\n\n\tpublic String getParserErrorMessage(Parser parser, RecognitionException e) {\n\t\tString msg;\n\t\tif ( e instanceof NoViableAltException) {\n\t\t\tString name = parser.getTokenErrorDisplay(e.token);\n\t\t\tmsg = name+\" came as a complete surprise to me\";\n\t\t}\n\t\telse if ( e instanceof v4ParserException) {\n\t\t\tmsg = ((v4ParserException)e).msg;\n\t\t}\n\t\telse {\n\t\t\tmsg = parser.getErrorMessage(e, parser.getTokenNames());\n\t\t}\n\t\treturn msg;\n\t}\n\n\t@Override\n\tpublic void grammarError(ErrorType etype, org.antlr.runtime.Token token, Object... args) {\n\t\ttool.errMgr.grammarError(etype, getSourceName(), token, args);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/parse/v4ParserException.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.parse;\n\nimport org.antlr.runtime.IntStream;\nimport org.antlr.runtime.RecognitionException;\n\n/** */\npublic class v4ParserException extends RecognitionException {\n\tpublic String msg;\n\t/** Used for remote debugger deserialization */\n\tpublic v4ParserException() {}\n\n\tpublic v4ParserException(String msg, IntStream input) {\n\t\tsuper(input);\n\t\tthis.msg = msg;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/ActionSniffer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.parse.ActionSplitter;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.List;\n\n/** Find token and rule refs plus refs to them in actions;\n *  side-effect: update Alternatives\n */\npublic class ActionSniffer extends BlankActionSplitterListener {\n\tpublic Grammar g;\n\tpublic Rule r;          // null if action outside of rule\n\tpublic Alternative alt; // null if action outside of alt; could be in rule\n\tpublic ActionAST node;\n\tpublic Token actionToken; // token within action\n\tpublic ErrorManager errMgr;\n\n\tpublic ActionSniffer(Grammar g, Rule r, Alternative alt, ActionAST node, Token actionToken) {\n\t\tthis.g = g;\n\t\tthis.r = r;\n\t\tthis.alt = alt;\n\t\tthis.node = node;\n\t\tthis.actionToken = actionToken;\n\t\tthis.errMgr = g.tool.errMgr;\n\t}\n\n\tpublic void examineAction() {\n\t\t//System.out.println(\"examine \"+actionToken);\n\t\tANTLRStringStream in = new ANTLRStringStream(actionToken.getText());\n\t\tin.setLine(actionToken.getLine());\n\t\tin.setCharPositionInLine(actionToken.getCharPositionInLine());\n\t\tActionSplitter splitter = new ActionSplitter(in, this);\n\t\t// forces eval, triggers listener methods\n\t\tnode.chunks = splitter.getActionTokens();\n\t}\n\n\tpublic void processNested(Token actionToken) {\n\t\tANTLRStringStream in = new ANTLRStringStream(actionToken.getText());\n\t\tin.setLine(actionToken.getLine());\n\t\tin.setCharPositionInLine(actionToken.getCharPositionInLine());\n\t\tActionSplitter splitter = new ActionSplitter(in, this);\n\t\t// forces eval, triggers listener methods\n\t\tsplitter.getActionTokens();\n\t}\n\n\n\t@Override\n\tpublic void attr(String expr, Token x) { trackRef(x); }\n\n\t@Override\n\tpublic void qualifiedAttr(String expr, Token x, Token y) { trackRef(x); }\n\n\t@Override\n\tpublic void setAttr(String expr, Token x, Token rhs) {\n\t\ttrackRef(x);\n\t\tprocessNested(rhs);\n\t}\n\n\t@Override\n\tpublic void setNonLocalAttr(String expr, Token x, Token y, Token rhs) {\n\t\tprocessNested(rhs);\n\t}\n\n\tpublic void trackRef(Token x) {\n\t\tList<TerminalAST> xRefs = alt.tokenRefs.get(x.getText());\n\t\tif ( xRefs!=null ) {\n\t\t\talt.tokenRefsInActions.map(x.getText(), node);\n\t\t}\n\t\tList<GrammarAST> rRefs = alt.ruleRefs.get(x.getText());\n\t\tif ( rRefs!=null ) {\n\t\t\talt.ruleRefsInActions.map(x.getText(), node);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/AttributeChecks.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.parse.ActionSplitter;\nimport org.antlr.v4.parse.ActionSplitterListener;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LabelElementPair;\nimport org.antlr.v4.tool.LabelType;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.List;\n\n/** Trigger checks for various kinds of attribute expressions.\n *  no side-effects.\n */\npublic class AttributeChecks implements ActionSplitterListener {\n    public Grammar g;\n    public Rule r;          // null if action outside of rule\n    public Alternative alt; // null if action outside of alt; could be in rule\n    public ActionAST node;\n\tpublic Token actionToken; // token within action\n\tpublic ErrorManager errMgr;\n\n    public AttributeChecks(Grammar g, Rule r, Alternative alt, ActionAST node, Token actionToken) {\n        this.g = g;\n        this.r = r;\n        this.alt = alt;\n        this.node = node;\n        this.actionToken = actionToken;\n\t\tthis.errMgr = g.tool.errMgr;\n    }\n\n    public static void checkAllAttributeExpressions(Grammar g) {\n        for (ActionAST act : g.namedActions.values()) {\n            AttributeChecks checker = new AttributeChecks(g, null, null, act, act.token);\n            checker.examineAction();\n        }\n\n        for (Rule r : g.rules.values()) {\n            for (ActionAST a : r.namedActions.values()) {\n                AttributeChecks checker = new AttributeChecks(g, r, null, a, a.token);\n                checker.examineAction();\n            }\n            for (int i=1; i<=r.numberOfAlts; i++) {\n                Alternative alt = r.alt[i];\n                for (ActionAST a : alt.actions) {\n                    AttributeChecks checker =\n                        new AttributeChecks(g, r, alt, a, a.token);\n                    checker.examineAction();\n                }\n            }\n            for (GrammarAST e : r.exceptions) {\n\t\t\t\tActionAST a = (ActionAST)e.getChild(1);\n                AttributeChecks checker = new AttributeChecks(g, r, null, a, a.token);\n                checker.examineAction();\n\t\t\t}\n\t\t\tif ( r.finallyAction!=null ) {\n\t\t\t\tAttributeChecks checker =\n\t\t\t\t\tnew AttributeChecks(g, r, null, r.finallyAction, r.finallyAction.token);\n\t\t\t\tchecker.examineAction();\n\t\t\t}\n        }\n    }\n\n    public void examineAction() {\n\t\t//System.out.println(\"examine \"+actionToken);\n        ANTLRStringStream in = new ANTLRStringStream(actionToken.getText());\n        in.setLine(actionToken.getLine());\n        in.setCharPositionInLine(actionToken.getCharPositionInLine());\n        ActionSplitter splitter = new ActionSplitter(in, this);\n\t\t// forces eval, triggers listener methods\n        node.chunks = splitter.getActionTokens();\n    }\n\n    // LISTENER METHODS\n\n\t// $x.y\n\t@Override\n\tpublic void qualifiedAttr(String expr, Token x, Token y) {\n\t\tif ( g.isLexer() ) {\n\t\t\terrMgr.grammarError(ErrorType.ATTRIBUTE_IN_LEXER_ACTION,\n\t\t\t\t\t\t\t\tg.fileName, x, x.getText()+\".\"+y.getText(), expr);\n\t\t\treturn;\n\t\t}\n\t\tif ( node.resolver.resolveToAttribute(x.getText(), node)!=null ) {\n\t\t\t// must be a member access to a predefined attribute like $ctx.foo\n\t\t\tattr(expr, x);\n\t\t\treturn;\n\t\t}\n\n\t\tif ( node.resolver.resolveToAttribute(x.getText(), y.getText(), node)==null ) {\n\t\t\tRule rref = isolatedRuleRef(x.getText());\n\t\t\tif ( rref!=null ) {\n\t\t\t\tif ( rref.args!=null && rref.args.get(y.getText())!=null ) {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_RULE_PARAMETER_REF,\n\t\t\t\t\t\t\t\t\t\t\t  g.fileName, y, y.getText(), rref.name, expr);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\terrMgr.grammarError(ErrorType.UNKNOWN_RULE_ATTRIBUTE,\n\t\t\t\t\t\t\t\t\t\t\t  g.fileName, y, y.getText(), rref.name, expr);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( !node.resolver.resolvesToAttributeDict(x.getText(), node) ) {\n\t\t\t\terrMgr.grammarError(ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE,\n\t\t\t\t\t\t\t\t\t\t  g.fileName, x, x.getText(), expr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\terrMgr.grammarError(ErrorType.UNKNOWN_ATTRIBUTE_IN_SCOPE,\n\t\t\t\t\t\t\t\t\t\t  g.fileName, y, y.getText(), expr);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setAttr(String expr, Token x, Token rhs) {\n\t\tif ( g.isLexer() ) {\n\t\t\terrMgr.grammarError(ErrorType.ATTRIBUTE_IN_LEXER_ACTION,\n\t\t\t\t\t\t\t\tg.fileName, x, x.getText(), expr);\n\t\t\treturn;\n\t\t}\n\t\tif ( node.resolver.resolveToAttribute(x.getText(), node)==null ) {\n\t\t\tErrorType errorType = ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE;\n\t\t\tif ( node.resolver.resolvesToListLabel(x.getText(), node) ) {\n\t\t\t\t// $ids for ids+=ID etc...\n\t\t\t\terrorType = ErrorType.ASSIGNMENT_TO_LIST_LABEL;\n\t\t\t}\n\n\t\t\terrMgr.grammarError(errorType,\n\t\t\t\t\t\t\t\tg.fileName, x, x.getText(), expr);\n\t\t}\n\t\tnew AttributeChecks(g, r, alt, node, rhs).examineAction();\n\t}\n\n\t@Override\n    public void attr(String expr, Token x) {\n\t\tif ( g.isLexer() ) {\n\t\t\terrMgr.grammarError(ErrorType.ATTRIBUTE_IN_LEXER_ACTION,\n\t\t\t\t\t\t\t\tg.fileName, x, x.getText(), expr);\n\t\t\treturn;\n\t\t}\n\t\tif ( node.resolver.resolveToAttribute(x.getText(), node)==null ) {\n\t\t\tif ( node.resolver.resolvesToToken(x.getText(), node) ) {\n\t\t\t\treturn; // $ID for token ref or label of token\n\t\t\t}\n\t\t\tif ( node.resolver.resolvesToListLabel(x.getText(), node) ) {\n\t\t\t\treturn; // $ids for ids+=ID etc...\n\t\t\t}\n\t\t\tif ( isolatedRuleRef(x.getText())!=null ) {\n\t\t\t\terrMgr.grammarError(ErrorType.ISOLATED_RULE_REF,\n\t\t\t\t\t\t\t\t\tg.fileName, x, x.getText(), expr);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\terrMgr.grammarError(ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE,\n\t\t\t\t\t\t\t\tg.fileName, x, x.getText(), expr);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void nonLocalAttr(String expr, Token x, Token y) {\n\t\tRule r = g.getRule(x.getText());\n\t\tif ( r==null ) {\n\t\t\terrMgr.grammarError(ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF,\n\t\t\t\t\t\t\t\tg.fileName, x, x.getText(), y.getText(), expr);\n\t\t}\n\t\telse if ( r.resolveToAttribute(y.getText(), null)==null ) {\n\t\t\terrMgr.grammarError(ErrorType.UNKNOWN_RULE_ATTRIBUTE,\n\t\t\t\t\t\t\t\tg.fileName, y, y.getText(), x.getText(), expr);\n\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setNonLocalAttr(String expr, Token x, Token y, Token rhs) {\n\t\tRule r = g.getRule(x.getText());\n\t\tif ( r==null ) {\n\t\t\terrMgr.grammarError(ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF,\n\t\t\t\t\t\t\t\tg.fileName, x, x.getText(), y.getText(), expr);\n\t\t}\n\t\telse if ( r.resolveToAttribute(y.getText(), null)==null ) {\n\t\t\terrMgr.grammarError(ErrorType.UNKNOWN_RULE_ATTRIBUTE,\n\t\t\t\t\t\t\t\tg.fileName, y, y.getText(), x.getText(), expr);\n\n\t\t}\n\t}\n\n\t@Override\n\tpublic void text(String text) { }\n\n\t// don't care\n\tpublic void templateInstance(String expr) {   }\n\tpublic void indirectTemplateInstance(String expr) {   }\n\tpublic void setExprAttribute(String expr) {   }\n\tpublic void setSTAttribute(String expr) {  }\n\tpublic void templateExpr(String expr) {  }\n\n\t// SUPPORT\n\n\tpublic Rule isolatedRuleRef(String x) {\n\t\tif ( node.resolver instanceof Grammar ) return null;\n\n\t\tif ( x.equals(r.name) ) return r;\n\t\tList<LabelElementPair> labels = null;\n\t\tif ( node.resolver instanceof Rule ) {\n\t\t\tlabels = r.getElementLabelDefs().get(x);\n\t\t}\n\t\telse if ( node.resolver instanceof Alternative ) {\n\t\t\tlabels = ((Alternative)node.resolver).labelDefs.get(x);\n\t\t}\n\t\tif ( labels!=null ) {  // it's a label ref. is it a rule label?\n\t\t\tLabelElementPair anyLabelDef = labels.get(0);\n\t\t\tif ( anyLabelDef.type==LabelType.RULE_LABEL ) {\n\t\t\t\treturn g.getRule(anyLabelDef.element.getText());\n\t\t\t}\n\t\t}\n\t\tif ( node.resolver instanceof Alternative ) {\n\t\t\tif ( ((Alternative)node.resolver).ruleRefs.get(x)!=null ) {\n\t\t\t\treturn g.getRule(x);\n\t\t\t}\n\t\t}\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/BasicSemanticChecks.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.tree.CommonTree;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.GrammarTreeVisitor;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTWithOptions;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.antlr.v4.tool.ast.RuleRefAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\nimport org.stringtemplate.v4.misc.MultiMap;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\n/** No side-effects except for setting options into the appropriate node.\n *  TODO:  make the side effects into a separate pass this\n *\n * Invokes check rules for these:\n *\n * FILE_AND_GRAMMAR_NAME_DIFFER\n * LEXER_RULES_NOT_ALLOWED\n * PARSER_RULES_NOT_ALLOWED\n * CANNOT_ALIAS_TOKENS\n * ARGS_ON_TOKEN_REF\n * ILLEGAL_OPTION\n * REWRITE_OR_OP_WITH_NO_OUTPUT_OPTION\n * NO_RULES\n * REWRITE_FOR_MULTI_ELEMENT_ALT\n * HETERO_ILLEGAL_IN_REWRITE_ALT\n * AST_OP_WITH_NON_AST_OUTPUT_OPTION\n * AST_OP_IN_ALT_WITH_REWRITE\n * CONFLICTING_OPTION_IN_TREE_FILTER\n * WILDCARD_AS_ROOT\n * INVALID_IMPORT\n * TOKEN_VOCAB_IN_DELEGATE\n * IMPORT_NAME_CLASH\n * REPEATED_PREQUEL\n * TOKEN_NAMES_MUST_START_UPPER\n */\npublic class BasicSemanticChecks extends GrammarTreeVisitor {\n\t/** Set of valid imports.  Maps delegate to set of delegator grammar types.\n\t *  validDelegations.get(LEXER) gives list of the kinds of delegators\n\t *  that can import lexers.\n\t */\n\tpublic final static MultiMap<Integer,Integer> validImportTypes =\n\t\tnew MultiMap<Integer,Integer>() {\n\t\t\t{\n\t\t\t\tmap(ANTLRParser.LEXER, ANTLRParser.LEXER);\n\t\t\t\tmap(ANTLRParser.LEXER, ANTLRParser.COMBINED);\n\n\t\t\t\tmap(ANTLRParser.PARSER, ANTLRParser.PARSER);\n\t\t\t\tmap(ANTLRParser.PARSER, ANTLRParser.COMBINED);\n\n\t\t\t\tmap(ANTLRParser.COMBINED, ANTLRParser.COMBINED);\n\t\t\t}\n\t\t};\n\n\tpublic Grammar g;\n\tpublic RuleCollector ruleCollector;\n\tpublic ErrorManager errMgr;\n\n\t/**\n\t * When this is {@code true}, the semantic checks will report\n\t * {@link ErrorType#UNRECOGNIZED_ASSOC_OPTION} where appropriate. This may\n\t * be set to {@code false} to disable this specific check.\n\t *\n\t * <p>The default value is {@code true}.</p>\n\t */\n\tpublic boolean checkAssocElementOption = true;\n\n\t/**\n\t * This field is used for reporting the {@link ErrorType#MODE_WITHOUT_RULES}\n\t * error when necessary.\n\t */\n\tprotected int nonFragmentRuleCount;\n\n\t/**\n\t * This is {@code true} from the time {@link #discoverLexerRule} is called\n\t * for a lexer rule with the {@code fragment} modifier until\n\t * {@link #exitLexerRule} is called.\n\t */\n\tprivate boolean inFragmentRule;\n\n\t/**\n\t * Value of caseInsensitive option (false if not defined)\n\t */\n\tprivate boolean grammarCaseInsensitive = false;\n\n\tpublic BasicSemanticChecks(Grammar g, RuleCollector ruleCollector) {\n\t\tthis.g = g;\n\t\tthis.ruleCollector = ruleCollector;\n\t\tthis.errMgr = g.tool.errMgr;\n\t}\n\n\t@Override\n\tpublic ErrorManager getErrorManager() { return errMgr; }\n\n\tpublic void process() {\tvisitGrammar(g.ast); }\n\n\t// Routines to route visitor traffic to the checking routines\n\n\t@Override\n\tpublic void discoverGrammar(GrammarRootAST root, GrammarAST ID) {\n\t\tcheckGrammarName(ID.token);\n\t}\n\n\t@Override\n\tpublic void finishPrequels(GrammarAST firstPrequel) {\n\t\tif ( firstPrequel==null ) return;\n\t\tGrammarAST parent = (GrammarAST)firstPrequel.parent;\n\t\tList<GrammarAST> options = parent.getAllChildrenWithType(OPTIONS);\n\t\tList<GrammarAST> imports = parent.getAllChildrenWithType(IMPORT);\n\t\tList<GrammarAST> tokens = parent.getAllChildrenWithType(TOKENS_SPEC);\n\t\tcheckNumPrequels(options, imports, tokens);\n\t}\n\n\t@Override\n\tpublic void importGrammar(GrammarAST label, GrammarAST ID) {\n\t\tcheckImport(ID.token);\n\t}\n\n\t@Override\n\tpublic void discoverRules(GrammarAST rules) {\n\t\tcheckNumRules(rules);\n\t}\n\n\t@Override\n\tprotected void enterMode(GrammarAST tree) {\n\t\tnonFragmentRuleCount = 0;\n\t}\n\n\t@Override\n\tprotected void exitMode(GrammarAST tree) {\n\t\tif (nonFragmentRuleCount == 0) {\n\t\t\tToken token = tree.getToken();\n\t\t\tString name = \"?\";\n\t\t\tif (tree.getChildCount() > 0) {\n\t\t\t\tname = tree.getChild(0).getText();\n\t\t\t\tif (name == null || name.isEmpty()) {\n\t\t\t\t\tname = \"?\";\n\t\t\t\t}\n\n\t\t\t\ttoken = ((GrammarAST)tree.getChild(0)).getToken();\n\t\t\t}\n\n\t\t\tg.tool.errMgr.grammarError(ErrorType.MODE_WITHOUT_RULES, g.fileName, token, name, g);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void modeDef(GrammarAST m, GrammarAST ID) {\n\t\tif ( !g.isLexer() ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.MODE_NOT_IN_LEXER, g.fileName,\n\t\t\t\t\t\t\t\t\t   ID.token, ID.token.getText(), g);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void discoverRule(RuleAST rule, GrammarAST ID,\n\t\t\t\t\t\t\t List<GrammarAST> modifiers,\n\t\t\t\t\t\t\t ActionAST arg, ActionAST returns,\n\t\t\t\t\t\t\t GrammarAST thrws, GrammarAST options,\n\t\t\t\t\t\t\t ActionAST locals,\n\t\t\t\t\t\t\t List<GrammarAST> actions, GrammarAST block)\n\t{\n\t\t// TODO: chk that all or no alts have \"# label\"\n\t\tcheckInvalidRuleDef(ID.token);\n\t}\n\n\t@Override\n\tpublic void discoverLexerRule(RuleAST rule, GrammarAST ID, List<GrammarAST> modifiers, GrammarAST options,\n\t\t\t\t\t\t\t\t  GrammarAST block)\n\t{\n\t\tcheckInvalidRuleDef(ID.token);\n\n\t\tif (modifiers != null) {\n\t\t\tfor (GrammarAST tree : modifiers) {\n\t\t\t\tif (tree.getType() == ANTLRParser.FRAGMENT) {\n\t\t\t\t\tinFragmentRule = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!inFragmentRule) {\n\t\t\tnonFragmentRuleCount++;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void exitLexerRule(GrammarAST tree) {\n\t\tinFragmentRule = false;\n\t}\n\n\t@Override\n\tpublic void ruleRef(GrammarAST ref, ActionAST arg) {\n\t\tcheckInvalidRuleRef(ref.token);\n\t}\n\n\t@Override\n\tpublic void grammarOption(GrammarAST ID, GrammarAST valueAST) {\n\t\tcheckOptions(g.ast, ID.token, valueAST);\n\t}\n\n\t@Override\n\tpublic void ruleOption(GrammarAST ID, GrammarAST valueAST) {\n\t\tcheckOptions((GrammarAST)ID.getAncestor(RULE), ID.token, valueAST);\n\t}\n\n\t@Override\n\tpublic void blockOption(GrammarAST ID, GrammarAST valueAST) {\n\t\tcheckOptions((GrammarAST)ID.getAncestor(BLOCK), ID.token, valueAST);\n\t}\n\n\t@Override\n\tpublic void defineToken(GrammarAST ID) {\n\t\tcheckTokenDefinition(ID.token);\n\t}\n\n\t@Override\n\tprotected void enterChannelsSpec(GrammarAST tree) {\n\t\tErrorType errorType = g.isParser()\n\t\t\t\t? ErrorType.CHANNELS_BLOCK_IN_PARSER_GRAMMAR\n\t\t\t\t: g.isCombined()\n\t\t\t\t? ErrorType.CHANNELS_BLOCK_IN_COMBINED_GRAMMAR\n\t\t\t\t: null;\n\t\tif (errorType != null) {\n\t\t\tg.tool.errMgr.grammarError(errorType, g.fileName, tree.token);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void defineChannel(GrammarAST ID) {\n\t\tcheckChannelDefinition(ID.token);\n\t}\n\n\t@Override\n\tpublic void elementOption(GrammarASTWithOptions elem, GrammarAST ID, GrammarAST valueAST) {\n\t\tcheckElementOptions(elem, ID, valueAST);\n\t}\n\n\t@Override\n\tpublic void finishRule(RuleAST rule, GrammarAST ID, GrammarAST block) {\n\t\tif ( rule.isLexerRule() ) return;\n\t\tBlockAST blk = (BlockAST)rule.getFirstChildWithType(BLOCK);\n\t\tint nalts = blk.getChildCount();\n\t\tGrammarAST idAST = (GrammarAST)rule.getChild(0);\n\t\tfor (int i=0; i< nalts; i++) {\n\t\t\tAltAST altAST = (AltAST)blk.getChild(i);\n\t\t\tif ( altAST.altLabel!=null ) {\n\t\t\t\tString altLabel = altAST.altLabel.getText();\n\t\t\t\t// first check that label doesn't conflict with a rule\n\t\t\t\t// label X or x can't be rule x.\n\t\t\t\tRule r = ruleCollector.rules.get(Utils.decapitalize(altLabel));\n\t\t\t\tif ( r!=null ) {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.ALT_LABEL_CONFLICTS_WITH_RULE,\n\t\t\t\t\t\t\t\t\t\t\t   g.fileName, altAST.altLabel.token,\n\t\t\t\t\t\t\t\t\t\t\t   altLabel,\n\t\t\t\t\t\t\t\t\t\t\t   r.name);\n\t\t\t\t}\n\t\t\t\t// Now verify that label X or x doesn't conflict with label\n\t\t\t\t// in another rule. altLabelToRuleName has both X and x mapped.\n\t\t\t\tString prevRuleForLabel = ruleCollector.altLabelToRuleName.get(altLabel);\n\t\t\t\tif ( prevRuleForLabel!=null && !prevRuleForLabel.equals(rule.getRuleName()) ) {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.ALT_LABEL_REDEF,\n\t\t\t\t\t\t\t\t\t\t\t   g.fileName, altAST.altLabel.token,\n\t\t\t\t\t\t\t\t\t\t\t   altLabel,\n\t\t\t\t\t\t\t\t\t\t\t   rule.getRuleName(),\n\t\t\t\t\t\t\t\t\t\t\t   prevRuleForLabel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tList<GrammarAST> altLabels = ruleCollector.ruleToAltLabels.get(rule.getRuleName());\n\t\tint numAltLabels = 0;\n\t\tif ( altLabels!=null ) numAltLabels = altLabels.size();\n\t\tif ( numAltLabels>0 && nalts != numAltLabels ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.RULE_WITH_TOO_FEW_ALT_LABELS,\n\t\t\t\t\t\t\t\t\t   g.fileName, idAST.token, rule.getRuleName());\n\t\t}\n\t}\n\n\t// Routines to do the actual work of checking issues with a grammar.\n\t// They are triggered by the visitor methods above.\n\n\tvoid checkGrammarName(Token nameToken) {\n\t\tString fullyQualifiedName = nameToken.getInputStream().getSourceName();\n\t\tif (fullyQualifiedName == null) {\n\t\t\t// This wasn't read from a file.\n\t\t\treturn;\n\t\t}\n\n\t\tFile f = new File(fullyQualifiedName);\n\t\tString fileName = f.getName();\n\t\tif ( g.originalGrammar!=null ) return; // don't warn about diff if this is implicit lexer\n\t\tif ( !Utils.stripFileExtension(fileName).equals(nameToken.getText()) &&\n\t\t     !fileName.equals(Grammar.GRAMMAR_FROM_STRING_NAME)) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.FILE_AND_GRAMMAR_NAME_DIFFER,\n\t\t\t\t\t\t\t\t\t   fileName, nameToken, nameToken.getText(), fileName);\n\t\t}\n\t}\n\n\tvoid checkNumRules(GrammarAST rulesNode) {\n\t\tif ( rulesNode.getChildCount()==0 ) {\n\t\t\tGrammarAST root = (GrammarAST)rulesNode.getParent();\n\t\t\tGrammarAST IDNode = (GrammarAST)root.getChild(0);\n\t\t\tg.tool.errMgr.grammarError(ErrorType.NO_RULES, g.fileName,\n\t\t\t\t\tnull, IDNode.getText(), g);\n\t\t}\n\t}\n\n\tvoid checkNumPrequels(List<GrammarAST> options,\n\t\t\t\t\t\t  List<GrammarAST> imports,\n\t\t\t\t\t\t  List<GrammarAST> tokens)\n\t{\n\t\tList<Token> secondOptionTokens = new ArrayList<Token>();\n\t\tif ( options!=null && options.size()>1 ) {\n\t\t\tsecondOptionTokens.add(options.get(1).token);\n\t\t}\n\t\tif ( imports!=null && imports.size()>1 ) {\n\t\t\tsecondOptionTokens.add(imports.get(1).token);\n\t\t}\n\t\tif ( tokens!=null && tokens.size()>1 ) {\n\t\t\tsecondOptionTokens.add(tokens.get(1).token);\n\t\t}\n\t\tfor (Token t : secondOptionTokens) {\n\t\t\tString fileName = t.getInputStream().getSourceName();\n\t\t\tg.tool.errMgr.grammarError(ErrorType.REPEATED_PREQUEL,\n\t\t\t\t\t\t\t\t\t   fileName, t);\n\t\t}\n\t}\n\n\tvoid checkInvalidRuleDef(Token ruleID) {\n\t\tString fileName = null;\n\t\tif ( ruleID.getInputStream()!=null ) {\n\t\t\tfileName = ruleID.getInputStream().getSourceName();\n\t\t}\n\t\tif ( g.isLexer() && Character.isLowerCase(ruleID.getText().charAt(0)) ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.PARSER_RULES_NOT_ALLOWED,\n\t\t\t\t\t\t\t\t\t   fileName, ruleID, ruleID.getText());\n\t\t}\n\t\tif ( g.isParser() &&\n\t\t\tGrammar.isTokenName(ruleID.getText()) )\n\t\t{\n\t\t\tg.tool.errMgr.grammarError(ErrorType.LEXER_RULES_NOT_ALLOWED,\n\t\t\t\t\t\t\t\t\t   fileName, ruleID, ruleID.getText());\n\t\t}\n\t}\n\n\tvoid checkInvalidRuleRef(Token ruleID) {\n\t\tString fileName = ruleID.getInputStream().getSourceName();\n\t\tif ( g.isLexer() && Character.isLowerCase(ruleID.getText().charAt(0)) ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.PARSER_RULE_REF_IN_LEXER_RULE,\n\t\t\t\t\t\t\t\t\t   fileName, ruleID, ruleID.getText(), currentRuleName);\n\t\t}\n\t}\n\n\tvoid checkTokenDefinition(Token tokenID) {\n\t\tString fileName = tokenID.getInputStream().getSourceName();\n\t\tif ( !Grammar.isTokenName(tokenID.getText()) ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.TOKEN_NAMES_MUST_START_UPPER,\n\t\t\t\t\t\t\t\t\t   fileName,\n\t\t\t\t\t\t\t\t\t   tokenID,\n\t\t\t\t\t\t\t\t\t   tokenID.getText());\n\t\t}\n\t}\n\n\tvoid checkChannelDefinition(Token tokenID) {\n\t}\n\n\t@Override\n\tprotected void enterLexerElement(GrammarAST tree) {\n\t}\n\n\t@Override\n\tprotected void enterLexerCommand(GrammarAST tree) {\n\t\tcheckElementIsOuterMostInSingleAlt(tree);\n\n\t\tif (inFragmentRule) {\n\t\t\tString fileName = tree.token.getInputStream().getSourceName();\n\t\t\tString ruleName = currentRuleName;\n\t\t\tg.tool.errMgr.grammarError(ErrorType.FRAGMENT_ACTION_IGNORED, fileName, tree.token, ruleName);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void actionInAlt(ActionAST action) {\n\t\tif (inFragmentRule) {\n\t\t\tString fileName = action.token.getInputStream().getSourceName();\n\t\t\tString ruleName = currentRuleName;\n\t\t\tg.tool.errMgr.grammarError(ErrorType.FRAGMENT_ACTION_IGNORED, fileName, action.token, ruleName);\n\t\t}\n\t}\n\n\t/**\n\t Make sure that action is last element in outer alt; here action,\n\t a2, z, and zz are bad, but a3 is ok:\n\t (RULE A (BLOCK (ALT {action} 'a')))\n\t (RULE B (BLOCK (ALT (BLOCK (ALT {a2} 'x') (ALT 'y')) {a3})))\n\t (RULE C (BLOCK (ALT 'd' {z}) (ALT 'e' {zz})))\n\t */\n\tprotected void checkElementIsOuterMostInSingleAlt(GrammarAST tree) {\n\t\tCommonTree alt = tree.parent;\n\t\tCommonTree blk = alt.parent;\n\t\tboolean outerMostAlt = blk.parent.getType() == RULE;\n\t\tTree rule = tree.getAncestor(RULE);\n\t\tString fileName = tree.getToken().getInputStream().getSourceName();\n\t\tif ( !outerMostAlt || blk.getChildCount()>1 )\n\t\t{\n\t\t\tErrorType e = ErrorType.LEXER_COMMAND_PLACEMENT_ISSUE;\n\t\t\tg.tool.errMgr.grammarError(e,\n\t\t\t\t\t\t\t\t\t   fileName,\n\t\t\t\t\t\t\t\t\t   tree.getToken(),\n\t\t\t\t\t\t\t\t\t   rule.getChild(0).getText());\n\n\t\t}\n\t}\n\n\t@Override\n\tpublic void label(GrammarAST op, GrammarAST ID, GrammarAST element) {\n\t\tswitch (element.getType()) {\n\t\t// token atoms\n\t\tcase TOKEN_REF:\n\t\tcase STRING_LITERAL:\n\t\tcase RANGE:\n\t\t// token sets\n\t\tcase SET:\n\t\tcase NOT:\n\t\t// rule atoms\n\t\tcase RULE_REF:\n\t\tcase WILDCARD:\n\t\t\treturn;\n\n\t\tdefault:\n\t\t\tString fileName = ID.token.getInputStream().getSourceName();\n\t\t\tg.tool.errMgr.grammarError(ErrorType.LABEL_BLOCK_NOT_A_SET, fileName, ID.token, ID.getText());\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void enterTerminal(GrammarAST tree) {\n\t\tString text = tree.getText();\n\t\tif (text.equals(\"''\")) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED, g.fileName, tree.token, \"''\");\n\t\t}\n\t}\n\n\t/** Check option is appropriate for grammar, rule, subrule */\n\tvoid checkOptions(GrammarAST parent, Token optionID, GrammarAST valueAST) {\n\t\tSet<String> optionsToCheck = null;\n\t\tint parentType = parent.getType();\n\t\tswitch (parentType) {\n\t\t\tcase ANTLRParser.BLOCK:\n\t\t\t\toptionsToCheck = g.isLexer() ? Grammar.lexerBlockOptions : Grammar.parserBlockOptions;\n\t\t\t\tbreak;\n\t\t\tcase ANTLRParser.RULE:\n\t\t\t\toptionsToCheck = g.isLexer() ? Grammar.lexerRuleOptions : Grammar.parseRuleOptions;\n\t\t\t\tbreak;\n\t\t\tcase ANTLRParser.GRAMMAR:\n\t\t\t\toptionsToCheck = g.getType() == ANTLRParser.LEXER\n\t\t\t\t\t\t? Grammar.lexerOptions\n\t\t\t\t\t\t: Grammar.parserOptions;\n\t\t\t\tbreak;\n\t\t}\n\t\tString optionName = optionID.getText();\n\t\tif (optionsToCheck != null && !optionsToCheck.contains(optionName)) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION, g.fileName, optionID, optionName);\n\t\t}\n\t\telse {\n\t\t\tcheckCaseInsensitiveOption(optionID, valueAST, parentType);\n\t\t}\n\t}\n\n\tprivate void checkCaseInsensitiveOption(Token optionID, GrammarAST valueAST, int parentType) {\n\t\tString optionName = optionID.getText();\n\t\tif (optionName.equals(Grammar.caseInsensitiveOptionName)) {\n\t\t\tString valueText = valueAST.getText();\n\t\t\tif (valueText.equals(\"true\") || valueText.equals(\"false\")) {\n\t\t\t\tboolean currentValue = Boolean.parseBoolean(valueText);\n\t\t\t\tif (parentType == ANTLRParser.GRAMMAR) {\n\t\t\t\t\tgrammarCaseInsensitive = currentValue;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (grammarCaseInsensitive == currentValue) {\n\t\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.REDUNDANT_CASE_INSENSITIVE_LEXER_RULE_OPTION,\n\t\t\t\t\t\t\t\tg.fileName, optionID, currentValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION_VALUE, g.fileName, valueAST.getToken(),\n\t\t\t\t\t\toptionName, valueText);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Check option is appropriate for elem; parent of ID is ELEMENT_OPTIONS */\n\tboolean checkElementOptions(GrammarASTWithOptions elem,\n\t\t\t\t\t\t\t\tGrammarAST ID,\n\t\t\t\t\t\t\t\tGrammarAST valueAST)\n\t{\n\t\tif (checkAssocElementOption && ID != null && \"assoc\".equals(ID.getText())) {\n\t\t\tif (elem.getType() != ANTLRParser.ALT) {\n\t\t\t\tToken optionID = ID.token;\n\t\t\t\tString fileName = optionID.getInputStream().getSourceName();\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.UNRECOGNIZED_ASSOC_OPTION,\n\t\t\t\t\t\t\t\t\t\t   fileName,\n\t\t\t\t\t\t\t\t\t\t   optionID,\n\t\t\t\t\t\t\t\t\t\t   currentRuleName);\n\t\t\t}\n\t\t}\n\n\t\tif ( elem instanceof RuleRefAST ) {\n\t\t\treturn checkRuleRefOptions((RuleRefAST)elem, ID, valueAST);\n\t\t}\n\t\tif ( elem instanceof TerminalAST ) {\n\t\t\treturn checkTokenOptions((TerminalAST)elem, ID, valueAST);\n\t\t}\n\t\tif ( elem.getType()==ANTLRParser.ACTION ) {\n\t\t\treturn false;\n\t\t}\n\t\tif ( elem.getType()==ANTLRParser.SEMPRED ) {\n\t\t\tToken optionID = ID.token;\n\t\t\tString fileName = optionID.getInputStream().getSourceName();\n\t\t\tif ( valueAST!=null && !Grammar.semPredOptions.contains(optionID.getText()) ) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION,\n\t\t\t\t\t\t\t\t\t\t   fileName,\n\t\t\t\t\t\t\t\t\t\t   optionID,\n\t\t\t\t\t\t\t\t\t\t   optionID.getText());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tboolean checkRuleRefOptions(RuleRefAST elem, GrammarAST ID, GrammarAST valueAST) {\n\t\tToken optionID = ID.token;\n\t\tString fileName = optionID.getInputStream().getSourceName();\n\t\t// don't care about id<SimpleValue> options\n\t\tif ( valueAST!=null && !Grammar.ruleRefOptions.contains(optionID.getText()) ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION,\n\t\t\t\t\t\t\t\t\t   fileName,\n\t\t\t\t\t\t\t\t\t   optionID,\n\t\t\t\t\t\t\t\t\t   optionID.getText());\n\t\t\treturn false;\n\t\t}\n\t\t// TODO: extra checks depending on rule kind?\n\t\treturn true;\n\t}\n\n\tboolean checkTokenOptions(TerminalAST elem, GrammarAST ID, GrammarAST valueAST) {\n\t\tToken optionID = ID.token;\n\t\tString fileName = optionID.getInputStream().getSourceName();\n\t\t// don't care about ID<ASTNodeName> options\n\t\tif ( valueAST!=null && !Grammar.tokenOptions.contains(optionID.getText()) ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.ILLEGAL_OPTION,\n\t\t\t\t\t\t\t\t\t   fileName,\n\t\t\t\t\t\t\t\t\t   optionID,\n\t\t\t\t\t\t\t\t\t   optionID.getText());\n\t\t\treturn false;\n\t\t}\n\t\t// TODO: extra checks depending on terminal kind?\n\t\treturn true;\n\t}\n\n\tvoid checkImport(Token importID) {\n\t\tGrammar delegate = g.getImportedGrammar(importID.getText());\n\t\tif ( delegate==null ) return;\n\t\tList<Integer> validDelegators = validImportTypes.get(delegate.getType());\n\t\tif ( validDelegators!=null && !validDelegators.contains(g.getType()) ) {\n\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_IMPORT,\n\t\t\t\t\t\t\t\t\t   g.fileName,\n\t\t\t\t\t\t\t\t\t   importID,\n\t\t\t\t\t\t\t\t\t   g, delegate);\n\t\t}\n\t\tif ( g.isCombined() &&\n\t\t\t (delegate.name.equals(g.name+Grammar.getGrammarTypeToFileNameSuffix(ANTLRParser.LEXER))||\n\t\t\t  delegate.name.equals(g.name+Grammar.getGrammarTypeToFileNameSuffix(ANTLRParser.PARSER))) )\n\t\t{\n\t\t\tg.tool.errMgr.grammarError(ErrorType.IMPORT_NAME_CLASH,\n\t\t\t\t\t\t\t\t\t   g.fileName,\n\t\t\t\t\t\t\t\t\t   importID,\n\t\t\t\t\t\t\t\t\t   g, delegate);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/BlankActionSplitterListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.parse.ActionSplitterListener;\n\npublic class BlankActionSplitterListener implements ActionSplitterListener {\n\t@Override\n\tpublic void qualifiedAttr(String expr, Token x, Token y) {\n\t}\n\n\t@Override\n\tpublic void setAttr(String expr, Token x, Token rhs) {\n\t}\n\n\t@Override\n\tpublic void attr(String expr, Token x) {\n\t}\n\n\tpublic void templateInstance(String expr) {\n\t}\n\n\t@Override\n\tpublic void nonLocalAttr(String expr, Token x, Token y) {\n\t}\n\n\t@Override\n\tpublic void setNonLocalAttr(String expr, Token x, Token y, Token rhs) {\n\t}\n\n\tpublic void indirectTemplateInstance(String expr) {\n\t}\n\n\tpublic void setExprAttribute(String expr) {\n\t}\n\n\tpublic void setSTAttribute(String expr) {\n\t}\n\n\tpublic void templateExpr(String expr) {\n\t}\n\n\t@Override\n\tpublic void text(String text) {\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/RuleCollector.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.v4.analysis.LeftRecursiveRuleAnalyzer;\nimport org.antlr.v4.misc.OrderedHashMap;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.GrammarTreeVisitor;\nimport org.antlr.v4.parse.ScopeParser;\nimport org.antlr.v4.tool.*;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.stringtemplate.v4.misc.MultiMap;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class RuleCollector extends GrammarTreeVisitor {\n\tprivate boolean grammarCaseInsensitive = false;\n\n\t/** which grammar are we checking */\n\tpublic Grammar g;\n\tpublic ErrorManager errMgr;\n\n\t// stuff to collect. this is the output\n\tpublic OrderedHashMap<String, Rule> rules = new OrderedHashMap<String, Rule>();\n\tpublic MultiMap<String,GrammarAST> ruleToAltLabels = new MultiMap<String, GrammarAST>();\n\tpublic Map<String,String> altLabelToRuleName = new HashMap<String, String>();\n\n\tpublic RuleCollector(Grammar g) {\n\t\tthis.g = g;\n\t\tthis.errMgr = g.tool.errMgr;\n\t}\n\n\t@Override\n\tpublic ErrorManager getErrorManager() { return errMgr; }\n\n\tpublic void process(GrammarAST ast) { visitGrammar(ast); }\n\n\t@Override\n\tpublic void discoverRule(RuleAST rule, GrammarAST ID,\n\t\t\t\t\t\t\t List<GrammarAST> modifiers, ActionAST arg,\n\t\t\t\t\t\t\t ActionAST returns, GrammarAST thrws,\n\t\t\t\t\t\t\t GrammarAST options, ActionAST locals,\n\t\t\t\t\t\t\t List<GrammarAST> actions,\n\t\t\t\t\t\t\t GrammarAST block)\n\t{\n\t\tint numAlts = block.getChildCount();\n\t\tRule r;\n\t\tif ( LeftRecursiveRuleAnalyzer.hasImmediateRecursiveRuleRefs(rule, ID.getText()) ) {\n\t\t\tr = new LeftRecursiveRule(g, ID.getText(), rule);\n\t\t}\n\t\telse {\n\t\t\tr = new Rule(g, ID.getText(), rule, numAlts);\n\t\t}\n\t\trules.put(r.name, r);\n\n\t\tif ( arg!=null ) {\n\t\t\tr.args = ScopeParser.parseTypedArgList(arg, arg.getText(), g);\n\t\t\tr.args.type = AttributeDict.DictType.ARG;\n\t\t\tr.args.ast = arg;\n\t\t\targ.resolver = r.alt[currentOuterAltNumber];\n\t\t}\n\n\t\tif ( returns!=null ) {\n\t\t\tr.retvals = ScopeParser.parseTypedArgList(returns, returns.getText(), g);\n\t\t\tr.retvals.type = AttributeDict.DictType.RET;\n\t\t\tr.retvals.ast = returns;\n\t\t}\n\n\t\tif ( locals!=null ) {\n\t\t\tr.locals = ScopeParser.parseTypedArgList(locals, locals.getText(), g);\n\t\t\tr.locals.type = AttributeDict.DictType.LOCAL;\n\t\t\tr.locals.ast = locals;\n\t\t}\n\n\t\tfor (GrammarAST a : actions) {\n\t\t\t// a = ^(AT ID ACTION)\n\t\t\tActionAST action = (ActionAST) a.getChild(1);\n\t\t\tr.namedActions.put(a.getChild(0).getText(), action);\n\t\t\taction.resolver = r;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void discoverOuterAlt(AltAST alt) {\n\t\tif ( alt.altLabel!=null ) {\n\t\t\truleToAltLabels.map(currentRuleName, alt.altLabel);\n\t\t\tString altLabel = alt.altLabel.getText();\n\t\t\taltLabelToRuleName.put(Utils.capitalize(altLabel), currentRuleName);\n\t\t\taltLabelToRuleName.put(Utils.decapitalize(altLabel), currentRuleName);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void grammarOption(GrammarAST ID, GrammarAST valueAST) {\n\t\tBoolean caseInsensitive = getCaseInsensitiveValue(ID, valueAST);\n\t\tif (caseInsensitive != null) {\n\t\t\tgrammarCaseInsensitive = caseInsensitive;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void discoverLexerRule(RuleAST rule, GrammarAST ID, List<GrammarAST> modifiers,\n\t\t\t\t\t\t\t\t  GrammarAST options, GrammarAST block)\n\t{\n\t\tboolean currentCaseInsensitive = grammarCaseInsensitive;\n\t\tif (options != null) {\n\t\t\tfor (Object child : options.getChildren()) {\n\t\t\t\tGrammarAST childAST = (GrammarAST) child;\n\t\t\t\tBoolean caseInsensitive = getCaseInsensitiveValue((GrammarAST)childAST.getChild(0), (GrammarAST)childAST.getChild(1));\n\t\t\t\tif (caseInsensitive != null) {\n\t\t\t\t\tcurrentCaseInsensitive = caseInsensitive;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint numAlts = block.getChildCount();\n\t\tRule r = new Rule(g, ID.getText(), rule, numAlts, currentModeName, currentCaseInsensitive);\n\t\tif ( !modifiers.isEmpty() ) r.modifiers = modifiers;\n\t\trules.put(r.name, r);\n\t}\n\n\tprivate Boolean getCaseInsensitiveValue(GrammarAST optionID, GrammarAST valueAST) {\n\t\tString optionName = optionID.getText();\n\t\tif (optionName.equals(Grammar.caseInsensitiveOptionName)) {\n\t\t\tString valueText = valueAST.getText();\n\t\t\tif (valueText.equals(\"true\") || valueText.equals(\"false\")) {\n\t\t\t\treturn Boolean.parseBoolean(valueText);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/SemanticPipeline.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.v4.analysis.LeftRecursiveRuleTransformer;\nimport org.antlr.v4.automata.LexerATNFactory;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n/** Do as much semantic checking as we can and fill in grammar\n *  with rules, actions, and token definitions.\n *  The only side effects are in the grammar passed to process().\n *  We consume a bunch of memory here while we build up data structures\n *  to perform checking, but all of it goes away after this pipeline object\n *  gets garbage collected.\n *\n *  After this pipeline finishes, we can be sure that the grammar\n *  is syntactically correct and that it's semantically correct enough for us\n *  to attempt grammar analysis. We have assigned all token types.\n *  Note that imported grammars bring in token and rule definitions\n *  but only the root grammar and any implicitly created lexer grammar\n *  get their token definitions filled up. We are treating the\n *  imported grammars like includes.\n *\n *  The semantic pipeline works on root grammars (those that do the importing,\n *  if any). Upon entry to the semantic pipeline, all imported grammars\n *  should have been loaded into delegate grammar objects with their\n *  ASTs created.  The pipeline does the BasicSemanticChecks on the\n *  imported grammar before collecting symbols. We cannot perform the\n *  simple checks such as undefined rule until we have collected all\n *  tokens and rules from the imported grammars into a single collection.\n */\npublic class SemanticPipeline {\n\tpublic Grammar g;\n\n\tpublic SemanticPipeline(Grammar g) {\n\t\tthis.g = g;\n\t}\n\n\tpublic void process() {\n\t\tif ( g.ast==null ) return;\n\n\t\t// COLLECT RULE OBJECTS\n\t\tRuleCollector ruleCollector = new RuleCollector(g);\n\t\truleCollector.process(g.ast);\n\n\t\t// DO BASIC / EASY SEMANTIC CHECKS\n\t\tint prevErrors = g.tool.errMgr.getNumErrors();\n\t\tBasicSemanticChecks basics = new BasicSemanticChecks(g, ruleCollector);\n\t\tbasics.process();\n\t\tif ( g.tool.errMgr.getNumErrors()>prevErrors ) return;\n\n\t\t// TRANSFORM LEFT-RECURSIVE RULES\n\t\tprevErrors = g.tool.errMgr.getNumErrors();\n\t\tLeftRecursiveRuleTransformer lrtrans =\n\t\t\tnew LeftRecursiveRuleTransformer(g.ast, ruleCollector.rules.values(), g);\n\t\tlrtrans.translateLeftRecursiveRules();\n\n\t\t// don't continue if we got errors during left-recursion elimination\n\t\tif ( g.tool.errMgr.getNumErrors()>prevErrors ) return;\n\n\t\t// STORE RULES IN GRAMMAR\n\t\tfor (Rule r : ruleCollector.rules.values()) {\n\t\t\tg.defineRule(r);\n\t\t}\n\n\t\t// COLLECT SYMBOLS: RULES, ACTIONS, TERMINALS, ...\n\t\tSymbolCollector collector = new SymbolCollector(g);\n\t\tcollector.process(g.ast);\n\n\t\t// CHECK FOR SYMBOL COLLISIONS\n\t\tSymbolChecks symcheck = new SymbolChecks(g, collector);\n\t\tsymcheck.process(); // side-effect: strip away redef'd rules.\n\n\t\tfor (GrammarAST a : collector.namedActions) {\n\t\t\tg.defineAction(a);\n\t\t}\n\n\t\t// LINK (outermost) ALT NODES WITH Alternatives\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tfor (int i=1; i<=r.numberOfAlts; i++) {\n\t\t\t\tr.alt[i].ast.alt = r.alt[i];\n\t\t\t}\n\t\t}\n\n\t\t// ASSIGN TOKEN TYPES\n\t\tg.importTokensFromTokensFile();\n\t\tif ( g.isLexer() ) {\n\t\t\tassignLexerTokenTypes(g, collector.tokensDefs);\n\t\t}\n\t\telse {\n\t\t\tassignTokenTypes(g, collector.tokensDefs,\n\t\t\t\t\t\t\t collector.tokenIDRefs, collector.terminals);\n\t\t}\n\n\t\tsymcheck.checkForModeConflicts(g);\n\t\tsymcheck.checkForUnreachableTokens(g);\n\n\t\tassignChannelTypes(g, collector.channelDefs);\n\n\t\t// CHECK RULE REFS NOW (that we've defined rules in grammar)\n\t\tsymcheck.checkRuleArgs(g, collector.rulerefs);\n\t\tidentifyStartRules(collector);\n\t\tsymcheck.checkForQualifiedRuleIssues(g, collector.qualifiedRulerefs);\n\n\t\t// don't continue if we got symbol errors\n\t\tif ( g.tool.getNumErrors()>0 ) return;\n\n\t\t// CHECK ATTRIBUTE EXPRESSIONS FOR SEMANTIC VALIDITY\n\t\tAttributeChecks.checkAllAttributeExpressions(g);\n\n\t\tUseDefAnalyzer.trackTokenRuleRefsInActions(g);\n\t}\n\n\tvoid identifyStartRules(SymbolCollector collector) {\n\t\tfor (GrammarAST ref : collector.rulerefs) {\n\t\t\tString ruleName = ref.getText();\n\t\t\tRule r = g.getRule(ruleName);\n\t\t\tif ( r!=null ) r.isStartRule = false;\n\t\t}\n\t}\n\n\tvoid assignLexerTokenTypes(Grammar g, List<GrammarAST> tokensDefs) {\n\t\tGrammar G = g.getOutermostGrammar(); // put in root, even if imported\n\t\tfor (GrammarAST def : tokensDefs) {\n\t\t\t// tokens { id (',' id)* } so must check IDs not TOKEN_REF\n\t\t\tif ( Grammar.isTokenName(def.getText()) ) {\n\t\t\t\tG.defineTokenName(def.getText());\n\t\t\t}\n\t\t}\n\n\t\t/* Define token types for nonfragment rules which do not include a 'type(...)'\n\t\t * or 'more' lexer command.\n\t\t */\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tif ( !r.isFragment() && !hasTypeOrMoreCommand(r) ) {\n\t\t\t\tG.defineTokenName(r.name);\n\t\t\t}\n\t\t}\n\n\t\t// FOR ALL X : 'xxx'; RULES, DEFINE 'xxx' AS TYPE X\n\t\tList<Pair<GrammarAST,GrammarAST>> litAliases =\n\t\t\tGrammar.getStringLiteralAliasesFromLexerRules(g.ast);\n\t\tSet<String> conflictingLiterals = new HashSet<String>();\n\t\tif ( litAliases!=null ) {\n\t\t\tfor (Pair<GrammarAST,GrammarAST> pair : litAliases) {\n\t\t\t\tGrammarAST nameAST = pair.a;\n\t\t\t\tGrammarAST litAST = pair.b;\n\t\t\t\tif ( !G.stringLiteralToTypeMap.containsKey(litAST.getText()) ) {\n\t\t\t\t\tG.defineTokenAlias(nameAST.getText(), litAST.getText());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// oops two literal defs in two rules (within or across modes).\n\t\t\t\t\tconflictingLiterals.add(litAST.getText());\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (String lit : conflictingLiterals) {\n\t\t\t\t// Remove literal if repeated across rules so it's not\n\t\t\t\t// found by parser grammar.\n\t\t\t\tInteger value = G.stringLiteralToTypeMap.remove(lit);\n\t\t\t\tif (value != null && value > 0 && value < G.typeToStringLiteralList.size() && lit.equals(G.typeToStringLiteralList.get(value))) {\n\t\t\t\t\tG.typeToStringLiteralList.set(value, null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tboolean hasTypeOrMoreCommand(Rule r) {\n\t\tGrammarAST ast = r.ast;\n\t\tif (ast == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tGrammarAST altActionAst = (GrammarAST)ast.getFirstDescendantWithType(ANTLRParser.LEXER_ALT_ACTION);\n\t\tif (altActionAst == null) {\n\t\t\t// the rule isn't followed by any commands\n\t\t\treturn false;\n\t\t}\n\n\t\t// first child is the alt itself, subsequent are the actions\n\t\tfor (int i = 1; i < altActionAst.getChildCount(); i++) {\n\t\t\tGrammarAST node = (GrammarAST)altActionAst.getChild(i);\n\t\t\tif (node.getType() == ANTLRParser.LEXER_ACTION_CALL) {\n\t\t\t\tif (\"type\".equals(node.getChild(0).getText())) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (\"more\".equals(node.getText())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tvoid assignTokenTypes(Grammar g, List<GrammarAST> tokensDefs,\n\t\t\t\t\t\t  List<GrammarAST> tokenIDs, List<GrammarAST> terminals)\n\t{\n\t\t//Grammar G = g.getOutermostGrammar(); // put in root, even if imported\n\n\t\t// create token types for tokens { A, B, C } ALIASES\n\t\tfor (GrammarAST alias : tokensDefs) {\n\t\t\tif (g.getTokenType(alias.getText()) != Token.INVALID_TYPE) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.TOKEN_NAME_REASSIGNMENT, g.fileName, alias.token, alias.getText());\n\t\t\t}\n\n\t\t\tg.defineTokenName(alias.getText());\n\t\t}\n\n\t\t// DEFINE TOKEN TYPES FOR TOKEN REFS LIKE ID, INT\n\t\tfor (GrammarAST idAST : tokenIDs) {\n\t\t\tif (g.getTokenType(idAST.getText()) == Token.INVALID_TYPE) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.IMPLICIT_TOKEN_DEFINITION, g.fileName, idAST.token, idAST.getText());\n\t\t\t}\n\n\t\t\tg.defineTokenName(idAST.getText());\n\t\t}\n\n\t\t// VERIFY TOKEN TYPES FOR STRING LITERAL REFS LIKE 'while', ';'\n\t\tfor (GrammarAST termAST : terminals) {\n\t\t\tif (termAST.getType() != ANTLRParser.STRING_LITERAL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (g.getTokenType(termAST.getText()) == Token.INVALID_TYPE) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.IMPLICIT_STRING_DEFINITION, g.fileName, termAST.token, termAST.getText());\n\t\t\t}\n\t\t}\n\n\t\tg.tool.log(\"semantics\", \"tokens=\"+g.tokenNameToTypeMap);\n        g.tool.log(\"semantics\", \"strings=\"+g.stringLiteralToTypeMap);\n\t}\n\n\t/**\n\t * Assign constant values to custom channels defined in a grammar.\n\t *\n\t * @param g The grammar.\n\t * @param channelDefs A collection of AST nodes defining individual channels\n\t * within a {@code channels{}} block in the grammar.\n\t */\n\tvoid assignChannelTypes(Grammar g, List<GrammarAST> channelDefs) {\n\t\tGrammar outermost = g.getOutermostGrammar();\n\t\tfor (GrammarAST channel : channelDefs) {\n\t\t\tString channelName = channel.getText();\n\n\t\t\t// Channel names can't alias tokens or modes, because constant\n\t\t\t// values are also assigned to them and the ->channel(NAME) lexer\n\t\t\t// command does not distinguish between the various ways a constant\n\t\t\t// can be declared. This method does not verify that channels do not\n\t\t\t// alias rules, because rule names are not associated with constant\n\t\t\t// values in ANTLR grammar semantics.\n\n\t\t\tif (g.getTokenType(channelName) != Token.INVALID_TYPE) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.CHANNEL_CONFLICTS_WITH_TOKEN, g.fileName, channel.token, channelName);\n\t\t\t}\n\n\t\t\tif (LexerATNFactory.COMMON_CONSTANTS.containsKey(channelName)) {\n\t\t\t\tg.tool.errMgr.grammarError(ErrorType.CHANNEL_CONFLICTS_WITH_COMMON_CONSTANTS, g.fileName, channel.token, channelName);\n\t\t\t}\n\n\t\t\tif (outermost instanceof LexerGrammar) {\n\t\t\t\tLexerGrammar lexerGrammar = (LexerGrammar)outermost;\n\t\t\t\tif (lexerGrammar.modes.containsKey(channelName)) {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.CHANNEL_CONFLICTS_WITH_MODE, g.fileName, channel.token, channelName);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutermost.defineChannelName(channel.getText());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/SymbolChecks.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.runtime.tree.CommonTree;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.v4.automata.LexerATNFactory;\nimport org.antlr.v4.parse.ANTLRLexer;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.Attribute;\nimport org.antlr.v4.tool.AttributeDict;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LabelElementPair;\nimport org.antlr.v4.tool.LabelType;\nimport org.antlr.v4.tool.LeftRecursiveRule;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n/** Check for symbol problems; no side-effects.  Inefficient to walk rules\n *  and such multiple times, but I like isolating all error checking outside\n *  of code that actually defines symbols etc...\n *\n *  Side-effect: strip away redef'd rules.\n */\npublic class SymbolChecks {\n\tGrammar g;\n\tSymbolCollector collector;\n\tMap<String, Rule> nameToRuleMap = new HashMap<String, Rule>();\n\tSet<String> tokenIDs = new HashSet<String>();\n\tMap<String, Set<String>> actionScopeToActionNames = new HashMap<String, Set<String>>();\n\n\tpublic ErrorManager errMgr;\n\n\tprotected final Set<String> reservedNames = new HashSet<String>();\n\n\t{\n\t\treservedNames.addAll(LexerATNFactory.getCommonConstants());\n\t}\n\n\tpublic SymbolChecks(Grammar g, SymbolCollector collector) {\n\t\tthis.g = g;\n\t\tthis.collector = collector;\n\t\tthis.errMgr = g.tool.errMgr;\n\n\t\tfor (GrammarAST tokenId : collector.tokenIDRefs) {\n\t\t\ttokenIDs.add(tokenId.getText());\n\t\t}\n\t}\n\n\tpublic void process() {\n\t\t// methods affect fields, but no side-effects outside this object\n\t\t// So, call order sensitive\n\t\t// First collect all rules for later use in checkForLabelConflict()\n\t\tif (g.rules != null) {\n\t\t\tfor (Rule r : g.rules.values()) nameToRuleMap.put(r.name, r);\n\t\t}\n\t\tcheckReservedNames(g.rules.values());\n\t\tcheckActionRedefinitions(collector.namedActions);\n\t\tcheckForLabelConflicts(g.rules.values());\n\t}\n\n\tpublic void checkActionRedefinitions(List<GrammarAST> actions) {\n\t\tif (actions == null) return;\n\t\tString scope = g.getDefaultActionScope();\n\t\tString name;\n\t\tGrammarAST nameNode;\n\t\tfor (GrammarAST ampersandAST : actions) {\n\t\t\tnameNode = (GrammarAST) ampersandAST.getChild(0);\n\t\t\tif (ampersandAST.getChildCount() == 2) {\n\t\t\t\tname = nameNode.getText();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tscope = nameNode.getText();\n\t\t\t\tname = ampersandAST.getChild(1).getText();\n\t\t\t}\n\t\t\tSet<String> scopeActions = actionScopeToActionNames.get(scope);\n\t\t\tif (scopeActions == null) { // init scope\n\t\t\t\tscopeActions = new HashSet<String>();\n\t\t\t\tactionScopeToActionNames.put(scope, scopeActions);\n\t\t\t}\n\t\t\tif (!scopeActions.contains(name)) {\n\t\t\t\tscopeActions.add(name);\n\t\t\t}\n\t\t\telse {\n\t\t\t\terrMgr.grammarError(ErrorType.ACTION_REDEFINITION,\n\t\t\t\t\t\tg.fileName, nameNode.token, name);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Make sure a label doesn't conflict with another symbol.\n\t * Labels must not conflict with: rules, tokens, scope names,\n\t * return values, parameters, and rule-scope dynamic attributes\n\t * defined in surrounding rule.  Also they must have same type\n\t * for repeated defs.\n\t */\n\tpublic void checkForLabelConflicts(Collection<Rule> rules) {\n\t\tfor (Rule r : rules) {\n\t\t\tcheckForAttributeConflicts(r);\n\n\t\t\tMap<String, LabelElementPair> labelNameSpace = new HashMap<>();\n\t\t\tfor (int i = 1; i <= r.numberOfAlts; i++) {\n\t\t\t\tAlternative a = r.alt[i];\n\t\t\t\tfor (List<LabelElementPair> pairs : a.labelDefs.values()) {\n\t\t\t\t\tif (r.hasAltSpecificContexts()) {\n\t\t\t\t\t\t// Collect labelName-labeledRules map for rule with alternative labels.\n\t\t\t\t\t\tMap<String, List<LabelElementPair>> labelPairs = new HashMap<>();\n\t\t\t\t\t\tfor (LabelElementPair p : pairs) {\n\t\t\t\t\t\t\tString labelName = findAltLabelName(p.label);\n\t\t\t\t\t\t\tif (labelName != null) {\n\t\t\t\t\t\t\t\tList<LabelElementPair> list;\n\t\t\t\t\t\t\t\tif (labelPairs.containsKey(labelName)) {\n\t\t\t\t\t\t\t\t\tlist = labelPairs.get(labelName);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tlist = new ArrayList<>();\n\t\t\t\t\t\t\t\t\tlabelPairs.put(labelName, list);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlist.add(p);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (List<LabelElementPair> internalPairs : labelPairs.values()) {\n\t\t\t\t\t\t\tlabelNameSpace.clear();\n\t\t\t\t\t\t\tcheckLabelPairs(r, labelNameSpace, internalPairs);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcheckLabelPairs(r, labelNameSpace, pairs);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void checkLabelPairs(Rule r, Map<String, LabelElementPair> labelNameSpace, List<LabelElementPair> pairs) {\n\t\tfor (LabelElementPair p : pairs) {\n\t\t\tcheckForLabelConflict(r, p.label);\n\t\t\tString name = p.label.getText();\n\t\t\tLabelElementPair prev = labelNameSpace.get(name);\n\t\t\tif (prev == null) {\n\t\t\t\tlabelNameSpace.put(name, p);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcheckForTypeMismatch(r, prev, p);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate String findAltLabelName(CommonTree label) {\n\t\tif (label == null) {\n\t\t\treturn null;\n\t\t}\n\t\telse if (label instanceof AltAST) {\n\t\t\tAltAST altAST = (AltAST) label;\n\t\t\tif (altAST.altLabel != null) {\n\t\t\t\treturn altAST.altLabel.toString();\n\t\t\t}\n\t\t\telse if (altAST.leftRecursiveAltInfo != null) {\n\t\t\t\treturn altAST.leftRecursiveAltInfo.altLabel.toString();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn findAltLabelName(label.parent);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treturn findAltLabelName(label.parent);\n\t\t}\n\t}\n\n\tprivate void checkForTypeMismatch(Rule r, LabelElementPair prevLabelPair, LabelElementPair labelPair) {\n\t\t// label already defined; if same type, no problem\n\t\tif (prevLabelPair.type != labelPair.type) {\n\t\t\t// Current behavior: take a token of rule declaration in case of left-recursive rule\n\t\t\t// Desired behavior: take a token of proper label declaration in case of left-recursive rule\n\t\t\t// See https://github.com/antlr/antlr4/pull/1585\n\t\t\t// Such behavior is referring to the fact that the warning is typically reported on the actual label redefinition,\n\t\t\t//   but for left-recursive rules the warning is reported on the enclosing rule.\n\t\t\torg.antlr.runtime.Token token = r instanceof LeftRecursiveRule\n\t\t\t\t\t? ((GrammarAST) r.ast.getChild(0)).getToken()\n\t\t\t\t\t: labelPair.label.token;\n\t\t\terrMgr.grammarError(\n\t\t\t\t\tErrorType.LABEL_TYPE_CONFLICT,\n\t\t\t\t\tg.fileName,\n\t\t\t\t\ttoken,\n\t\t\t\t\tlabelPair.label.getText(),\n\t\t\t\t\tlabelPair.type + \"!=\" + prevLabelPair.type);\n\t\t}\n\t\tif (!prevLabelPair.element.getText().equals(labelPair.element.getText()) &&\n\t\t\t(prevLabelPair.type.equals(LabelType.RULE_LABEL) || prevLabelPair.type.equals(LabelType.RULE_LIST_LABEL)) &&\n\t\t\t(labelPair.type.equals(LabelType.RULE_LABEL) || labelPair.type.equals(LabelType.RULE_LIST_LABEL))) {\n\n\t\t\torg.antlr.runtime.Token token = r instanceof LeftRecursiveRule\n\t\t\t\t\t? ((GrammarAST) r.ast.getChild(0)).getToken()\n\t\t\t\t\t: labelPair.label.token;\n\t\t\tString prevLabelOp = prevLabelPair.type.equals(LabelType.RULE_LIST_LABEL) ? \"+=\" : \"=\";\n\t\t\tString labelOp = labelPair.type.equals(LabelType.RULE_LIST_LABEL) ? \"+=\" : \"=\";\n\t\t\terrMgr.grammarError(\n\t\t\t\t\tErrorType.LABEL_TYPE_CONFLICT,\n\t\t\t\t\tg.fileName,\n\t\t\t\t\ttoken,\n\t\t\t\t\tlabelPair.label.getText() + labelOp + labelPair.element.getText(),\n\t\t\t\t\tprevLabelPair.label.getText() + prevLabelOp + prevLabelPair.element.getText());\n\t\t}\n\t}\n\n\tpublic void checkForLabelConflict(Rule r, GrammarAST labelID) {\n\t\tString name = labelID.getText();\n\t\tif (nameToRuleMap.containsKey(name)) {\n\t\t\tErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_RULE;\n\t\t\terrMgr.grammarError(etype, g.fileName, labelID.token, name, r.name);\n\t\t}\n\n\t\tif (tokenIDs.contains(name)) {\n\t\t\tErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_TOKEN;\n\t\t\terrMgr.grammarError(etype, g.fileName, labelID.token, name, r.name);\n\t\t}\n\n\t\tif (r.args != null && r.args.get(name) != null) {\n\t\t\tErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_ARG;\n\t\t\terrMgr.grammarError(etype, g.fileName, labelID.token, name, r.name);\n\t\t}\n\n\t\tif (r.retvals != null && r.retvals.get(name) != null) {\n\t\t\tErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_RETVAL;\n\t\t\terrMgr.grammarError(etype, g.fileName, labelID.token, name, r.name);\n\t\t}\n\n\t\tif (r.locals != null && r.locals.get(name) != null) {\n\t\t\tErrorType etype = ErrorType.LABEL_CONFLICTS_WITH_LOCAL;\n\t\t\terrMgr.grammarError(etype, g.fileName, labelID.token, name, r.name);\n\t\t}\n\t}\n\n\tpublic void checkForAttributeConflicts(Rule r) {\n\t\tcheckDeclarationRuleConflicts(r, r.args, nameToRuleMap.keySet(), ErrorType.ARG_CONFLICTS_WITH_RULE);\n\t\tcheckDeclarationRuleConflicts(r, r.args, tokenIDs, ErrorType.ARG_CONFLICTS_WITH_TOKEN);\n\n\t\tcheckDeclarationRuleConflicts(r, r.retvals, nameToRuleMap.keySet(), ErrorType.RETVAL_CONFLICTS_WITH_RULE);\n\t\tcheckDeclarationRuleConflicts(r, r.retvals, tokenIDs, ErrorType.RETVAL_CONFLICTS_WITH_TOKEN);\n\n\t\tcheckDeclarationRuleConflicts(r, r.locals, nameToRuleMap.keySet(), ErrorType.LOCAL_CONFLICTS_WITH_RULE);\n\t\tcheckDeclarationRuleConflicts(r, r.locals, tokenIDs, ErrorType.LOCAL_CONFLICTS_WITH_TOKEN);\n\n\t\tcheckLocalConflictingDeclarations(r, r.retvals, r.args, ErrorType.RETVAL_CONFLICTS_WITH_ARG);\n\t\tcheckLocalConflictingDeclarations(r, r.locals, r.args, ErrorType.LOCAL_CONFLICTS_WITH_ARG);\n\t\tcheckLocalConflictingDeclarations(r, r.locals, r.retvals, ErrorType.LOCAL_CONFLICTS_WITH_RETVAL);\n\t}\n\n\tprotected void checkDeclarationRuleConflicts(Rule r, AttributeDict attributes, Set<String> ruleNames, ErrorType errorType) {\n\t\tif (attributes == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (Attribute attribute : attributes.attributes.values()) {\n\t\t\tif (ruleNames.contains(attribute.name)) {\n\t\t\t\terrMgr.grammarError(\n\t\t\t\t\t\terrorType,\n\t\t\t\t\t\tg.fileName,\n\t\t\t\t\t\tattribute.token != null ? attribute.token : ((GrammarAST) r.ast.getChild(0)).token,\n\t\t\t\t\t\tattribute.name,\n\t\t\t\t\t\tr.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void checkLocalConflictingDeclarations(Rule r, AttributeDict attributes, AttributeDict referenceAttributes, ErrorType errorType) {\n\t\tif (attributes == null || referenceAttributes == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tSet<String> conflictingKeys = attributes.intersection(referenceAttributes);\n\t\tfor (String key : conflictingKeys) {\n\t\t\terrMgr.grammarError(\n\t\t\t\t\terrorType,\n\t\t\t\t\tg.fileName,\n\t\t\t\t\tattributes.get(key).token != null ? attributes.get(key).token : ((GrammarAST)r.ast.getChild(0)).token,\n\t\t\t\t\tkey,\n\t\t\t\t\tr.name);\n\t\t}\n\t}\n\n\tprotected void checkReservedNames(Collection<Rule> rules) {\n\t\tfor (Rule rule : rules) {\n\t\t\tif (reservedNames.contains(rule.name)) {\n\t\t\t\terrMgr.grammarError(ErrorType.RESERVED_RULE_NAME, g.fileName, ((GrammarAST)rule.ast.getChild(0)).getToken(), rule.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void checkForModeConflicts(Grammar g) {\n\t\tif (g.isLexer()) {\n\t\t\tLexerGrammar lexerGrammar = (LexerGrammar)g;\n\t\t\tfor (String modeName : lexerGrammar.modes.keySet()) {\n\t\t\t\tif (!modeName.equals(\"DEFAULT_MODE\") && reservedNames.contains(modeName)) {\n\t\t\t\t\tRule rule = lexerGrammar.modes.get(modeName).iterator().next();\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.MODE_CONFLICTS_WITH_COMMON_CONSTANTS, g.fileName, rule.ast.parent.getToken(), modeName);\n\t\t\t\t}\n\n\t\t\t\tif (g.getTokenType(modeName) != Token.INVALID_TYPE) {\n\t\t\t\t\tRule rule = lexerGrammar.modes.get(modeName).iterator().next();\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.MODE_CONFLICTS_WITH_TOKEN, g.fileName, rule.ast.parent.getToken(), modeName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Algorithm steps:\n\t * 1. Collect all simple string literals (i.e. 'asdf', 'as' 'df', but not [a-z]+, 'a'..'z')\n\t *    for all lexer rules in each mode except of autogenerated tokens ({@link #getSingleTokenValues(Rule) getSingleTokenValues})\n\t * 2. Compare every string literal with each other ({@link #checkForOverlap(Grammar, Rule, Rule, List<String>, List<String>) checkForOverlap})\n\t *    and throw TOKEN_UNREACHABLE warning if the same string found.\n\t * Complexity: O(m * n^2 / 2), approximately equals to O(n^2)\n\t * where m - number of modes, n - average number of lexer rules per mode.\n\t * See also testUnreachableTokens unit test for details.\n\t */\n\tpublic void checkForUnreachableTokens(Grammar g) {\n\t\tif (g.isLexer()) {\n\t\t\tLexerGrammar lexerGrammar = (LexerGrammar)g;\n\t\t\tfor (List<Rule> rules : lexerGrammar.modes.values()) {\n\t\t\t\t// Collect string literal lexer rules for each mode\n\t\t\t\tList<Rule> stringLiteralRules = new ArrayList<>();\n\t\t\t\tList<List<String>> stringLiteralValues = new ArrayList<>();\n\t\t\t\tfor (int i = 0; i < rules.size(); i++) {\n\t\t\t\t\tRule rule = rules.get(i);\n\n\t\t\t\t\tList<String> ruleStringAlts = getSingleTokenValues(rule);\n\t\t\t\t\tif (ruleStringAlts != null && ruleStringAlts.size() > 0) {\n\t\t\t\t\t\tstringLiteralRules.add(rule);\n\t\t\t\t\t\tstringLiteralValues.add(ruleStringAlts);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Check string sets intersection\n\t\t\t\tfor (int i = 0; i < stringLiteralRules.size(); i++) {\n\t\t\t\t\tList<String> firstTokenStringValues = stringLiteralValues.get(i);\n\t\t\t\t\tRule rule1 =  stringLiteralRules.get(i);\n\t\t\t\t\tcheckForOverlap(g, rule1, rule1, firstTokenStringValues, stringLiteralValues.get(i));\n\n\t\t\t\t\t// Check fragment rules only with themself\n\t\t\t\t\tif (!rule1.isFragment()) {\n\t\t\t\t\t\tfor (int j = i + 1; j < stringLiteralRules.size(); j++) {\n\t\t\t\t\t\t\tRule rule2 = stringLiteralRules.get(j);\n\t\t\t\t\t\t\tif (!rule2.isFragment()) {\n\t\t\t\t\t\t\t\tcheckForOverlap(g, rule1, stringLiteralRules.get(j), firstTokenStringValues, stringLiteralValues.get(j));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * {@return} list of simple string literals for rule {@param rule}\n\t */\n\tprivate List<String> getSingleTokenValues(Rule rule)\n\t{\n\t\tList<String> values = new ArrayList<>();\n\t\tfor (Alternative alt : rule.alt) {\n\t\t\tif (alt != null) {\n\t\t\t\t// select first alt if token has a command\n\t\t\t\tTree rootNode = alt.ast.getChildCount() == 2 &&\n\t\t\t\t\t\talt.ast.getChild(0) instanceof AltAST && alt.ast.getChild(1) instanceof GrammarAST\n\t\t\t\t\t\t? alt.ast.getChild(0)\n\t\t\t\t\t\t: alt.ast;\n\n\t\t\t\tif (rootNode.getTokenStartIndex() == -1) {\n\t\t\t\t\tcontinue; // ignore autogenerated tokens from combined grammars that start with T__\n\t\t\t\t}\n\n\t\t\t\t// Ignore alt if contains not only string literals (repetition, optional)\n\t\t\t\tboolean ignore = false;\n\t\t\t\tStringBuilder currentValue = new StringBuilder();\n\t\t\t\tfor (int i = 0; i < rootNode.getChildCount(); i++) {\n\t\t\t\t\tTree child = rootNode.getChild(i);\n\t\t\t\t\tif (!(child instanceof TerminalAST)) {\n\t\t\t\t\t\tignore = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tTerminalAST terminalAST = (TerminalAST)child;\n\t\t\t\t\tif (terminalAST.token.getType() != ANTLRLexer.STRING_LITERAL) {\n\t\t\t\t\t\tignore = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tString text = terminalAST.token.getText();\n\t\t\t\t\t\tcurrentValue.append(text.substring(1, text.length() - 1));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!ignore) {\n\t\t\t\t\tvalues.add(currentValue.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}\n\n\t/**\n\t * For same rule compare values from next index:\n\t * TOKEN_WITH_SAME_VALUES: 'asdf' | 'asdf';\n\t * For different rules compare from start value:\n\t * TOKEN1: 'asdf';\n\t * TOKEN2: 'asdf';\n\t */\n\tprivate void checkForOverlap(Grammar g, Rule rule1, Rule rule2, List<String> firstTokenStringValues, List<String> secondTokenStringValues) {\n\t\tfor (int i = 0; i < firstTokenStringValues.size(); i++) {\n\t\t\tint secondTokenInd = rule1 == rule2 ? i + 1 : 0;\n\t\t\tString str1 = firstTokenStringValues.get(i);\n\t\t\tfor (int j = secondTokenInd; j < secondTokenStringValues.size(); j++) {\n\t\t\t\tString str2 = secondTokenStringValues.get(j);\n\t\t\t\tif (str1.equals(str2)) {\n\t\t\t\t\terrMgr.grammarError(ErrorType.TOKEN_UNREACHABLE, g.fileName,\n\t\t\t\t\t\t\t((GrammarAST) rule2.ast.getChild(0)).token, rule2.name, str2, rule1.name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// CAN ONLY CALL THE TWO NEXT METHODS AFTER GRAMMAR HAS RULE DEFS (see semanticpipeline)\n\tpublic void checkRuleArgs(Grammar g, List<GrammarAST> rulerefs) {\n\t\tif ( rulerefs==null ) return;\n\t\tfor (GrammarAST ref : rulerefs) {\n\t\t\tString ruleName = ref.getText();\n\t\t\tRule r = g.getRule(ruleName);\n\t\t\tGrammarAST arg = (GrammarAST)ref.getFirstChildWithType(ANTLRParser.ARG_ACTION);\n\t\t\tif ( arg!=null && (r==null || r.args==null) ) {\n\t\t\t\terrMgr.grammarError(ErrorType.RULE_HAS_NO_ARGS,\n\t\t\t\t\t\tg.fileName, ref.token, ruleName);\n\n\t\t\t}\n\t\t\telse if ( arg==null && (r!=null && r.args!=null) ) {\n\t\t\t\terrMgr.grammarError(ErrorType.MISSING_RULE_ARGS,\n\t\t\t\t\t\tg.fileName, ref.token, ruleName);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void checkForQualifiedRuleIssues(Grammar g, List<GrammarAST> qualifiedRuleRefs) {\n\t\tfor (GrammarAST dot : qualifiedRuleRefs) {\n\t\t\tGrammarAST grammar = (GrammarAST)dot.getChild(0);\n\t\t\tGrammarAST rule = (GrammarAST)dot.getChild(1);\n\t\t\tg.tool.log(\"semantics\", grammar.getText()+\".\"+rule.getText());\n\t\t\tGrammar delegate = g.getImportedGrammar(grammar.getText());\n\t\t\tif ( delegate==null ) {\n\t\t\t\terrMgr.grammarError(ErrorType.NO_SUCH_GRAMMAR_SCOPE,\n\t\t\t\t\t\tg.fileName, grammar.token, grammar.getText(),\n\t\t\t\t\t\trule.getText());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ( g.getRule(grammar.getText(), rule.getText())==null ) {\n\t\t\t\t\terrMgr.grammarError(ErrorType.NO_SUCH_RULE_IN_SCOPE,\n\t\t\t\t\t\t\tg.fileName, rule.token, grammar.getText(),\n\t\t\t\t\t\t\trule.getText());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/SymbolCollector.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.v4.parse.GrammarTreeVisitor;\nimport org.antlr.v4.tool.ErrorManager;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LabelElementPair;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTWithOptions;\nimport org.antlr.v4.tool.ast.PredAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n/** Collects (create) rules, terminals, strings, actions, scopes etc... from AST\n *  side-effects: sets resolver field of asts for actions and\n *  defines predicates via definePredicateInAlt(), collects actions and stores\n *  in alts.\n *  TODO: remove side-effects!\n */\npublic class SymbolCollector extends GrammarTreeVisitor {\n\t/** which grammar are we checking */\n\tpublic Grammar g;\n\n\t// stuff to collect\n\tpublic List<GrammarAST> rulerefs = new ArrayList<GrammarAST>();\n\tpublic List<GrammarAST> qualifiedRulerefs = new ArrayList<GrammarAST>();\n\tpublic List<GrammarAST> terminals = new ArrayList<GrammarAST>();\n\tpublic List<GrammarAST> tokenIDRefs = new ArrayList<GrammarAST>();\n\tpublic Set<String> strings = new HashSet<String>();\n\tpublic List<GrammarAST> tokensDefs = new ArrayList<GrammarAST>();\n\tpublic List<GrammarAST> channelDefs = new ArrayList<GrammarAST>();\n\n\t/** Track action name node in @parser::members {...} or @members {...} */\n\tList<GrammarAST> namedActions = new ArrayList<GrammarAST>();\n\n\tpublic ErrorManager errMgr;\n\n\t// context\n\tpublic Rule currentRule;\n\n\tpublic SymbolCollector(Grammar g) {\n\t\tthis.g = g;\n\t\tthis.errMgr = g.tool.errMgr;\n\t}\n\n\t@Override\n\tpublic ErrorManager getErrorManager() { return errMgr; }\n\n\tpublic void process(GrammarAST ast) { visitGrammar(ast); }\n\n\t@Override\n\tpublic void globalNamedAction(GrammarAST scope, GrammarAST ID, ActionAST action) {\n\t\taction.setScope(scope);\n\t\tnamedActions.add((GrammarAST)ID.getParent());\n\t\taction.resolver = g;\n\t}\n\n\t@Override\n\tpublic void defineToken(GrammarAST ID) {\n\t\tterminals.add(ID);\n\t\ttokenIDRefs.add(ID);\n\t\ttokensDefs.add(ID);\n\t}\n\n\t@Override\n\tpublic void defineChannel(GrammarAST ID) {\n\t\tchannelDefs.add(ID);\n\t}\n\n\t@Override\n\tpublic void discoverRule(RuleAST rule, GrammarAST ID,\n\t\t\t\t\t\t\t List<GrammarAST> modifiers, ActionAST arg,\n\t\t\t\t\t\t\t ActionAST returns, GrammarAST thrws,\n\t\t\t\t\t\t\t GrammarAST options, ActionAST locals,\n\t\t\t\t\t\t\t List<GrammarAST> actions,\n\t\t\t\t\t\t\t GrammarAST block)\n\t{\n\t\tcurrentRule = g.getRule(ID.getText());\n\t}\n\n\t@Override\n\tpublic void discoverLexerRule(RuleAST rule, GrammarAST ID, List<GrammarAST> modifiers, GrammarAST options,\n\t\t\t\t\t\t\t\t  GrammarAST block)\n\t{\n\t\tcurrentRule = g.getRule(ID.getText());\n\t}\n\n\t@Override\n\tpublic void discoverOuterAlt(AltAST alt) {\n\t\tcurrentRule.alt[currentOuterAltNumber].ast = alt;\n\t}\n\n\t@Override\n\tpublic void actionInAlt(ActionAST action) {\n\t\tcurrentRule.defineActionInAlt(currentOuterAltNumber, action);\n\t\taction.resolver = currentRule.alt[currentOuterAltNumber];\n\t}\n\n\t@Override\n\tpublic void sempredInAlt(PredAST pred) {\n\t\tcurrentRule.definePredicateInAlt(currentOuterAltNumber, pred);\n\t\tpred.resolver = currentRule.alt[currentOuterAltNumber];\n\t}\n\n\t@Override\n\tpublic void ruleCatch(GrammarAST arg, ActionAST action) {\n\t\tGrammarAST catchme = (GrammarAST)action.getParent();\n\t\tcurrentRule.exceptions.add(catchme);\n\t\taction.resolver = currentRule;\n\t}\n\n\t@Override\n\tpublic void finallyAction(ActionAST action) {\n\t\tcurrentRule.finallyAction = action;\n\t\taction.resolver = currentRule;\n\t}\n\n\t@Override\n\tpublic void label(GrammarAST op, GrammarAST ID, GrammarAST element) {\n\t\tLabelElementPair lp = new LabelElementPair(g, ID, element, op.getType());\n\t\tcurrentRule.alt[currentOuterAltNumber].labelDefs.map(ID.getText(), lp);\n\t}\n\n\t@Override\n\tpublic void stringRef(TerminalAST ref) {\n\t\tterminals.add(ref);\n\t\tstrings.add(ref.getText());\n\t\tif ( currentRule!=null ) {\n\t\t\tcurrentRule.alt[currentOuterAltNumber].tokenRefs.map(ref.getText(), ref);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void tokenRef(TerminalAST ref) {\n\t\tterminals.add(ref);\n\t\ttokenIDRefs.add(ref);\n\t\tif ( currentRule!=null ) {\n\t\t\tcurrentRule.alt[currentOuterAltNumber].tokenRefs.map(ref.getText(), ref);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void ruleRef(GrammarAST ref, ActionAST arg) {\n//\t\tif ( inContext(\"DOT ...\") ) qualifiedRulerefs.add((GrammarAST)ref.getParent());\n\t\trulerefs.add(ref);\n    \tif ( currentRule!=null ) {\n    \t\tcurrentRule.alt[currentOuterAltNumber].ruleRefs.map(ref.getText(), ref);\n    \t}\n\t}\n\n\t@Override\n\tpublic void grammarOption(GrammarAST ID, GrammarAST valueAST) {\n\t\tsetActionResolver(valueAST);\n\t}\n\n\t@Override\n\tpublic void ruleOption(GrammarAST ID, GrammarAST valueAST) {\n\t\tsetActionResolver(valueAST);\n\t}\n\n\t@Override\n\tpublic void blockOption(GrammarAST ID, GrammarAST valueAST) {\n\t\tsetActionResolver(valueAST);\n\t}\n\n\t@Override\n\tpublic void elementOption(GrammarASTWithOptions t, GrammarAST ID, GrammarAST valueAST) {\n\t\tsetActionResolver(valueAST);\n\t}\n\n\t/** In case of option id={...}, set resolve in case they use $foo */\n\tprivate void setActionResolver(GrammarAST valueAST) {\n\t\tif ( valueAST instanceof ActionAST) {\n\t\t\t((ActionAST)valueAST).resolver = currentRule.alt[currentOuterAltNumber];\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/semantics/UseDefAnalyzer.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.semantics;\n\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.ActionSplitter;\nimport org.antlr.v4.parse.ActionSplitterListener;\nimport org.antlr.v4.tool.Alternative;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n/** Look for errors and deadcode stuff */\npublic class UseDefAnalyzer {\n\t// side-effect: updates Alternative with refs in actions\n\tpublic static void trackTokenRuleRefsInActions(Grammar g) {\n\t\tfor (Rule r : g.rules.values()) {\n\t\t\tfor (int i=1; i<=r.numberOfAlts; i++) {\n\t\t\t\tAlternative alt = r.alt[i];\n\t\t\t\tfor (ActionAST a : alt.actions) {\n\t\t\t\t\tActionSniffer sniffer =\tnew ActionSniffer(g, r, alt, a, a.token);\n\t\t\t\t\tsniffer.examineAction();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static boolean actionIsContextDependent(ActionAST actionAST) {\n\t\tANTLRStringStream in = new ANTLRStringStream(actionAST.token.getText());\n\t\tin.setLine(actionAST.token.getLine());\n\t\tin.setCharPositionInLine(actionAST.token.getCharPositionInLine());\n\t\tfinal boolean[] dependent = new boolean[] {false}; // can't be simple bool with anon class\n\t\tActionSplitterListener listener = new BlankActionSplitterListener() {\n\t\t\t@Override\n\t\t\tpublic void nonLocalAttr(String expr, Token x, Token y) { dependent[0] = true; }\n\t\t\t@Override\n\t\t\tpublic void qualifiedAttr(String expr, Token x, Token y) { dependent[0] = true; }\n\t\t\t@Override\n\t\t\tpublic void setAttr(String expr, Token x, Token rhs) { dependent[0] = true; }\n\t\t\t@Override\n\t\t\tpublic void setExprAttribute(String expr) { dependent[0] = true; }\n\t\t\t@Override\n\t\t\tpublic void setNonLocalAttr(String expr, Token x, Token y, Token rhs) { dependent[0] = true; }\n\t\t\t@Override\n\t\t\tpublic void attr(String expr, Token x) {  dependent[0] = true; }\n\t\t};\n\t\tActionSplitter splitter = new ActionSplitter(in, listener);\n\t\t// forces eval, triggers listener methods\n\t\tsplitter.getActionTokens();\n\t\treturn dependent[0];\n\t}\n\n\t/** Find all rules reachable from r directly or indirectly for all r in g */\n\tpublic static Map<Rule, Set<Rule>> getRuleDependencies(Grammar g) {\n\t\treturn getRuleDependencies(g, g.rules.values());\n\t}\n\n\tpublic static Map<Rule, Set<Rule>> getRuleDependencies(LexerGrammar g, String modeName) {\n\t\treturn getRuleDependencies(g, g.modes.get(modeName));\n\t}\n\n\tpublic static Map<Rule, Set<Rule>> getRuleDependencies(Grammar g, Collection<Rule> rules) {\n\t\tMap<Rule, Set<Rule>> dependencies = new HashMap<Rule, Set<Rule>>();\n\n\t\tfor (Rule r : rules) {\n\t\t\tList<GrammarAST> tokenRefs = r.ast.getNodesWithType(ANTLRParser.TOKEN_REF);\n\t\t\tfor (GrammarAST tref : tokenRefs) {\n\t\t\t\tSet<Rule> calls = dependencies.get(r);\n\t\t\t\tif ( calls==null ) {\n\t\t\t\t\tcalls = new HashSet<Rule>();\n\t\t\t\t\tdependencies.put(r, calls);\n\t\t\t\t}\n\t\t\t\tcalls.add(g.getRule(tref.getText()));\n\t\t\t}\n\t\t}\n\n\t\treturn dependencies;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ANTLRMessage.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.Token;\nimport org.stringtemplate.v4.ST;\n\nimport java.util.Arrays;\n\npublic class ANTLRMessage {\n\tprivate static final Object[] EMPTY_ARGS = new Object[0];\n\n\n    private final ErrorType errorType;\n\n    private final Object[] args;\n\n    private final Throwable e;\n\n    // used for location template\n    public String fileName;\n    public int line = -1;\n    public int charPosition = -1;\n\n\tpublic Grammar g;\n\t/** Most of the time, we'll have a token such as an undefined rule ref\n     *  and so this will be set.\n     */\n    public Token offendingToken;\n\n\tpublic ANTLRMessage(ErrorType errorType) {\n        this(errorType, (Throwable)null, Token.INVALID_TOKEN);\n    }\n\n    public ANTLRMessage(ErrorType errorType, Token offendingToken, Object... args) {\n        this(errorType, null, offendingToken, args);\n\t}\n\n    public ANTLRMessage(ErrorType errorType, Throwable e, Token offendingToken, Object... args) {\n        this.errorType = errorType;\n        this.e = e;\n        this.args = args;\n\t\tthis.offendingToken = offendingToken;\n    }\n\n\n    public ErrorType getErrorType() {\n        return errorType;\n    }\n\n\n    public Object[] getArgs() {\n\t\tif (args == null) {\n\t\t\treturn EMPTY_ARGS;\n\t\t}\n\n\t\treturn args;\n    }\n\n\tpublic ST getMessageTemplate(boolean verbose) {\n\t\tST messageST = new ST(getErrorType().msg);\n\t\tmessageST.impl.name = errorType.name();\n\n\t\tmessageST.add(\"verbose\", verbose);\n\t\tObject[] args = getArgs();\n\t\tfor (int i=0; i<args.length; i++) {\n\t\t\tString attr = \"arg\";\n\t\t\tif ( i>0 ) attr += i + 1;\n\t\t\tmessageST.add(attr, args[i]);\n\t\t}\n\t\tif ( args.length<2 ) messageST.add(\"arg2\", null); // some messages ref arg2\n\n\t\tThrowable cause = getCause();\n\t\tif ( cause!=null ) {\n\t\t\tmessageST.add(\"exception\", cause);\n\t\t\tmessageST.add(\"stackTrace\", cause.getStackTrace());\n\t\t}\n\t\telse {\n\t\t\tmessageST.add(\"exception\", null); // avoid ST error msg\n\t\t\tmessageST.add(\"stackTrace\", null);\n\t\t}\n\n\t\treturn messageST;\n\t}\n\n\n    public Throwable getCause() {\n        return e;\n    }\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Message{\" +\n\t\t\t   \"errorType=\" + getErrorType() +\n\t\t\t   \", args=\" + Arrays.asList(getArgs()) +\n\t\t\t   \", e=\" + getCause() +\n\t\t\t   \", fileName='\" + fileName + '\\'' +\n\t\t\t   \", line=\" + line +\n\t\t\t   \", charPosition=\" + charPosition +\n\t\t\t   '}';\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ANTLRToolListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\n/** Defines behavior of object able to handle error messages from ANTLR including\n *  both tool errors like \"can't write file\" and grammar ambiguity warnings.\n *  To avoid having to change tools that use ANTLR (like GUIs), I am\n *  wrapping error data in Message objects and passing them to the listener.\n *  In this way, users of this interface are less sensitive to changes in\n *  the info I need for error messages.\n */\npublic interface ANTLRToolListener {\n\tpublic void info(String msg);\n\tpublic void error(ANTLRMessage msg);\n\tpublic void warning(ANTLRMessage msg);\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/Alternative.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\n\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\nimport org.stringtemplate.v4.misc.MultiMap;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** An outermost alternative for a rule.  We don't track inner alternatives. */\npublic class Alternative implements AttributeResolver {\n    public Rule rule;\n\n\tpublic AltAST ast;\n\n\t/** What alternative number is this outermost alt? 1..n */\n\tpublic int altNum;\n\n    // token IDs, string literals in this alt\n    public MultiMap<String, TerminalAST> tokenRefs = new MultiMap<String, TerminalAST>();\n\n\t// does not include labels\n\tpublic MultiMap<String, GrammarAST> tokenRefsInActions = new MultiMap<String, GrammarAST>();\n\n    // all rule refs in this alt\n    public MultiMap<String, GrammarAST> ruleRefs = new MultiMap<String, GrammarAST>();\n\n\t// does not include labels\n\tpublic MultiMap<String, GrammarAST> ruleRefsInActions = new MultiMap<String, GrammarAST>();\n\n    /** A list of all LabelElementPair attached to tokens like id=ID, ids+=ID */\n    public MultiMap<String, LabelElementPair> labelDefs = new MultiMap<String, LabelElementPair>();\n\n    // track all token, rule, label refs in rewrite (right of ->)\n    //public List<GrammarAST> rewriteElements = new ArrayList<GrammarAST>();\n\n    /** Track all executable actions other than named actions like @init\n     *  and catch/finally (not in an alt). Also tracks predicates, rewrite actions.\n     *  We need to examine these actions before code generation so\n     *  that we can detect refs to $rule.attr etc...\n\t *\n\t *  This tracks per alt\n     */\n    public List<ActionAST> actions = new ArrayList<ActionAST>();\n\n    public Alternative(Rule r, int altNum) { this.rule = r; this.altNum = altNum; }\n\n\t@Override\n\tpublic boolean resolvesToToken(String x, ActionAST node) {\n\t\tif ( tokenRefs.get(x)!=null ) return true;\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\tif ( anyLabelDef!=null && anyLabelDef.type==LabelType.TOKEN_LABEL ) return true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean resolvesToAttributeDict(String x, ActionAST node) {\n\t\tif ( resolvesToToken(x, node) ) return true;\n        if ( ruleRefs.get(x)!=null ) return true; // rule ref in this alt?\n        LabelElementPair anyLabelDef = getAnyLabelDef(x);\n        if ( anyLabelDef!=null && anyLabelDef.type==LabelType.RULE_LABEL ) return true;\n\t\treturn false;\n\t}\n\n\t/**  $x\t\tAttribute: rule arguments, return values, predefined rule prop.\n\t */\n\t@Override\n\tpublic Attribute resolveToAttribute(String x, ActionAST node) {\n\t\treturn rule.resolveToAttribute(x, node); // reuse that code\n\t}\n\n\t/** $x.y, x can be surrounding rule, token/rule/label ref. y is visible\n\t *  attr in that dictionary.  Can't see args on rule refs.\n\t */\n\t@Override\n\tpublic Attribute resolveToAttribute(String x, String y, ActionAST node) {\n        if ( tokenRefs.get(x)!=null ) { // token ref in this alt?\n            return rule.getPredefinedScope(LabelType.TOKEN_LABEL).get(y);\n        }\n        if ( ruleRefs.get(x)!=null ) {  // rule ref in this alt?\n            // look up rule, ask it to resolve y (must be retval or predefined)\n\t\t\treturn rule.g.getRule(x).resolveRetvalOrProperty(y);\n\t\t}\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\tif ( anyLabelDef!=null && anyLabelDef.type==LabelType.RULE_LABEL ) {\n\t\t\treturn rule.g.getRule(anyLabelDef.element.getText()).resolveRetvalOrProperty(y);\n\t\t}\n\t\telse if ( anyLabelDef!=null ) {\n\t\t\tAttributeDict scope = rule.getPredefinedScope(anyLabelDef.type);\n\t\t\tif (scope == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn scope.get(y);\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean resolvesToLabel(String x, ActionAST node) {\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\treturn anyLabelDef!=null &&\n\t\t\t   (anyLabelDef.type==LabelType.TOKEN_LABEL ||\n\t\t\t\tanyLabelDef.type==LabelType.RULE_LABEL);\n\t}\n\n\t@Override\n\tpublic boolean resolvesToListLabel(String x, ActionAST node) {\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\treturn anyLabelDef!=null &&\n\t\t\t   (anyLabelDef.type==LabelType.RULE_LIST_LABEL ||\n\t\t\t\tanyLabelDef.type==LabelType.TOKEN_LIST_LABEL);\n\t}\n\n\tpublic LabelElementPair getAnyLabelDef(String x) {\n\t\tList<LabelElementPair> labels = labelDefs.get(x);\n\t\tif ( labels!=null ) return labels.get(0);\n\t\treturn null;\n\t}\n\n\t/** x can be ruleref or rule label. */\n\tpublic Rule resolveToRule(String x) {\n        if ( ruleRefs.get(x)!=null ) return rule.g.getRule(x);\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\tif ( anyLabelDef!=null && anyLabelDef.type==LabelType.RULE_LABEL ) {\n            return rule.g.getRule(anyLabelDef.element.getText());\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/Attribute.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.Token;\n\n/** Track the names of attributes defined in arg lists, return values,\n *  scope blocks etc...\n */\npublic class Attribute {\n    /** The entire declaration such as \"String foo\" or \"x:int\" */\n    public String decl;\n\n    /** The type; might be empty such as for Python which has no static typing */\n    public String type;\n\n    /** The name of the attribute \"foo\" */\n    public String name;\n\n\t/** A {@link Token} giving the position of the name of this attribute in the grammar. */\n\tpublic Token token;\n\n    /** The optional attribute initialization expression */\n    public String initValue;\n\n\t/** Who contains us? */\n\tpublic AttributeDict dict;\n\n    public Attribute() {}\n\n    public Attribute(String name) { this(name,null); }\n\n    public Attribute(String name, String decl) {\n        this.name = name;\n        this.decl = decl;\n    }\n\n    @Override\n    public String toString() {\n        if ( initValue!=null ) {\n\t        return name+\":\"+type+\"=\"+initValue;\n        }\n        if ( type!=null ) {\n\t        return name+\":\"+type;\n        }\n        return name;\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/AttributeDict.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.Set;\n\n/** Track the attributes within retval, arg lists etc...\n *  <p>\n *  Each rule has potentially 3 scopes: return values,\n *  parameters, and an implicitly-named scope (i.e., a scope defined in a rule).\n *  Implicitly-defined scopes are named after the rule; rules and scopes then\n *  must live in the same name space--no collisions allowed.\n */\npublic class AttributeDict {\n    public String name;\n    public GrammarAST ast;\n\tpublic DictType type;\n\n    /** All {@link Token} scopes (token labels) share the same fixed scope of\n     *  of predefined attributes.  I keep this out of the {@link Token}\n     *  interface to avoid a runtime type leakage.\n     */\n    public static final AttributeDict predefinedTokenDict = new AttributeDict(DictType.TOKEN);\n    static {\n        predefinedTokenDict.add(new Attribute(\"text\"));\n        predefinedTokenDict.add(new Attribute(\"type\"));\n        predefinedTokenDict.add(new Attribute(\"line\"));\n        predefinedTokenDict.add(new Attribute(\"index\"));\n        predefinedTokenDict.add(new Attribute(\"pos\"));\n        predefinedTokenDict.add(new Attribute(\"channel\"));\n        predefinedTokenDict.add(new Attribute(\"int\"));\n    }\n\n    public enum DictType {\n        ARG, RET, LOCAL, TOKEN,\n\t\tPREDEFINED_RULE, PREDEFINED_LEXER_RULE,\n    }\n\n    /** The list of {@link Attribute} objects. */\n\n    public final LinkedHashMap<String, Attribute> attributes =\n        new LinkedHashMap<String, Attribute>();\n\n\tpublic AttributeDict() {}\n\tpublic AttributeDict(DictType type) { this.type = type; }\n\n\tpublic Attribute add(Attribute a) { a.dict = this; return attributes.put(a.name, a); }\n    public Attribute get(String name) { return attributes.get(name); }\n\n    public String getName() {\n        return name;\n    }\n\n    public int size() { return attributes.size(); }\n\n    /** Return the set of keys that collide from\n     *  {@code this} and {@code other}.\n     */\n\n    public Set<String> intersection(AttributeDict other) {\n        if ( other==null || other.size()==0 || size()==0 ) {\n            return Collections.emptySet();\n        }\n\n\t\tSet<String> result = new HashSet<String>(attributes.keySet());\n\t\tresult.retainAll(other.attributes.keySet());\n\t\treturn result;\n    }\n\n    @Override\n    public String toString() {\n        return getName()+\":\"+attributes;\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/AttributeResolver.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.tool.ast.ActionAST;\n\n/** Grammars, rules, and alternatives all have symbols visible to\n *  actions.  To evaluate attr exprs, ask action for its resolver\n *  then ask resolver to look up various symbols. Depending on the context,\n *  some symbols are available at some aren't.\n *\n *  Alternative level:\n *\n *  $x\t\tAttribute: rule arguments, return values, predefined rule prop.\n * \t\t\tAttributeDict: references to tokens and token labels in the\n * \t\t\tcurrent alt (including any elements within subrules contained\n * \t\t\tin that outermost alt). x can be rule with scope or a global scope.\n * \t\t\tList label: x is a token/rule list label.\n *  $x.y\tAttribute: x is surrounding rule, rule/token/label ref\n *  $s::y\tAttribute: s is any rule with scope or global scope; y is prop within\n *\n *  Rule level:\n *\n *  $x\t\tAttribute: rule arguments, return values, predefined rule prop.\n * \t\t\tAttributeDict: references to token labels in *any* alt. x can\n * \t\t\tbe any rule with scope or global scope.\n * \t\t\tList label: x is a token/rule list label.\n *  $x.y\tAttribute: x is surrounding rule, label ref (in any alts)\n *  $s::y\tAttribute: s is any rule with scope or global scope; y is prop within\n *\n *  Grammar level:\n *\n *  $s\t\tAttributeDict: s is a global scope\n *  $s::y\tAttribute: s is a global scope; y is prop within\n */\npublic interface AttributeResolver {\n\tpublic boolean resolvesToListLabel(String x, ActionAST node);\n\tpublic boolean resolvesToLabel(String x, ActionAST node);\n\tpublic boolean resolvesToAttributeDict(String x, ActionAST node);\n\tpublic boolean resolvesToToken(String x, ActionAST node);\n\tpublic Attribute resolveToAttribute(String x, ActionAST node);\n\tpublic Attribute resolveToAttribute(String x, String y, ActionAST node);\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/BuildDependencyGenerator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.SourceType;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STGroupFile;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** Given a grammar file, show the dependencies on .tokens etc...\n *  Using ST, emit a simple \"make compatible\" list of dependencies.\n *  For example, combined grammar T.g (no token import) generates:\n *\n *  \tTParser.java : T.g\n *  \tT.tokens : T.g\n *  \tTLexer.java : T.g\n *\n *  If we are using the listener pattern (-listener on the command line)\n *  then we add:\n *\n *      TListener.java : T.g\n *      TBaseListener.java : T.g\n *\n *  If we are using the visitor pattern (-visitor on the command line)\n *  then we add:\n *\n *      TVisitor.java : T.g\n *      TBaseVisitor.java : T.g\n *\n *  If \"-lib libdir\" is used on command-line with -depend and option\n *  tokenVocab=A in grammar, then include the path like this:\n *\n * \t\tT.g: libdir/A.tokens\n *\n *  Pay attention to -o as well:\n *\n * \t\toutputdir/TParser.java : T.g\n *\n *  So this output shows what the grammar depends on *and* what it generates.\n *\n *  Operate on one grammar file at a time.  If given a list of .g on the\n *  command-line with -depend, just emit the dependencies.  The grammars\n *  may depend on each other, but the order doesn't matter.  Build tools,\n *  reading in this output, will know how to organize it.\n *\n *  This code was obvious until I removed redundant \"./\" on front of files\n *  and had to escape spaces in filenames :(\n *\n *  I literally copied from v3 so might be slightly inconsistent with the\n *  v4 code base.\n */\npublic class BuildDependencyGenerator {\n    protected Tool tool;\n    protected Grammar g;\n    protected CodeGenerator generator;\n    protected STGroup templates;\n\n    public BuildDependencyGenerator(Tool tool, Grammar g) {\n        this.tool = tool;\n\t\tthis.g = g;\n\t\tgenerator = CodeGenerator.create(g);\n    }\n\n    /** From T.g return a list of File objects that\n     *  name files ANTLR will emit from T.g.\n     */\n    public List<File> getGeneratedFileList() {\n        List<File> files = new ArrayList<File>();\n\n        // add generated recognizer; e.g., TParser.java\n        if (generator.getTarget().needsHeader()) {\n          files.add(getOutputFile(generator.getRecognizerFileName(SourceType.HEADER)));\n        }\n\t\tif (generator.getTarget().supportsSplitParser()) {\n\t\t\tfiles.add(getOutputFile(generator.getRecognizerFileName(SourceType.SOURCE_LEAN)));\n\t\t\tfiles.add(getOutputFile(generator.getRecognizerFileName(SourceType.SOURCE_CONTEXTS)));\n\t\t\tfiles.add(getOutputFile(generator.getRecognizerFileName(SourceType.SOURCE_DFA)));\n\t\t} else {\n\t\t\tfiles.add(getOutputFile(generator.getRecognizerFileName(SourceType.SOURCE)));\n\t\t}\n\t\t// add output vocab file; e.g., T.tokens. This is always generated to\n        // the base output directory, which will be just . if there is no -o option\n        //\n\t\tfiles.add(getOutputFile(generator.getVocabFileName()));\n        // are we generating a .h file?\n        ST headerExtST = null;\n        ST extST = generator.getTemplates().getInstanceOf(\"codeFileExtension\");\n        if (generator.getTemplates().isDefined(\"headerFile\")) {\n            headerExtST = generator.getTemplates().getInstanceOf(\"headerFileExtension\");\n            String suffix = Grammar.getGrammarTypeToFileNameSuffix(g.getType());\n            String fileName = g.name + suffix + headerExtST.render();\n            files.add(getOutputFile(fileName));\n        }\n        if ( g.isCombined() ) {\n            // add autogenerated lexer; e.g., TLexer.java TLexer.h TLexer.tokens\n\n            String suffix = Grammar.getGrammarTypeToFileNameSuffix(ANTLRParser.LEXER);\n            String lexer = g.name + suffix + extST.render();\n            files.add(getOutputFile(lexer));\n            String lexerTokens = g.name + suffix + CodeGenerator.VOCAB_FILE_EXTENSION;\n            files.add(getOutputFile(lexerTokens));\n\n            // TLexer.h\n            if (headerExtST != null) {\n                String header = g.name + suffix + headerExtST.render();\n                files.add(getOutputFile(header));\n            }\n        }\n\n        if ( g.tool.gen_listener ) {\n          // add generated listener; e.g., TListener.java\n          if (generator.getTarget().needsHeader()) {\n            files.add(getOutputFile(generator.getListenerFileName(SourceType.HEADER)));\n          }\n          files.add(getOutputFile(generator.getListenerFileName(SourceType.SOURCE)));\n\n          // add generated base listener; e.g., TBaseListener.java\n          if (generator.getTarget().needsHeader()) {\n            files.add(getOutputFile(generator.getBaseListenerFileName(SourceType.HEADER)));\n          }\n          files.add(getOutputFile(generator.getBaseListenerFileName(SourceType.SOURCE)));\n        }\n\n        if ( g.tool.gen_visitor ) {\n          // add generated visitor; e.g., TVisitor.java\n          if (generator.getTarget().needsHeader()) {\n            files.add(getOutputFile(generator.getVisitorFileName(SourceType.HEADER)));\n          }\n          files.add(getOutputFile(generator.getVisitorFileName(SourceType.SOURCE)));\n\n          // add generated base visitor; e.g., TBaseVisitor.java\n          if (generator.getTarget().needsHeader()) {\n            files.add(getOutputFile(generator.getBaseVisitorFileName(SourceType.HEADER)));\n          }\n          files.add(getOutputFile(generator.getBaseVisitorFileName(SourceType.SOURCE)));\n        }\n\n\n\t\t// handle generated files for imported grammars\n\t\tList<Grammar> imports = g.getAllImportedGrammars();\n\t\tif ( imports!=null ) {\n\t\t\tfor (Grammar g : imports) {\n//\t\t\t\tFile outputDir = tool.getOutputDirectory(g.fileName);\n//\t\t\t\tString fname = groomQualifiedFileName(outputDir.toString(), g.getRecognizerName() + extST.render());\n//\t\t\t\tfiles.add(new File(outputDir, fname));\n\t\t\t\tfiles.add(getOutputFile(g.fileName));\n\t\t\t}\n\t\t}\n\n\t\tif (files.isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\treturn files;\n\t}\n\n\tpublic File getOutputFile(String fileName) {\n\t\tFile outputDir = tool.getOutputDirectory(g.fileName);\n\t\tif ( outputDir.toString().equals(\".\") ) {\n\t\t\t// pay attention to -o then\n\t\t\toutputDir = tool.getOutputDirectory(fileName);\n\t\t}\n\t\tif ( outputDir.toString().equals(\".\") ) {\n\t\t\treturn new File(fileName);\n\t\t}\n\t\tif (outputDir.getName().equals(\".\")) {\n\t\t\tString fname = outputDir.toString();\n\t\t\tint dot = fname.lastIndexOf('.');\n\t\t\toutputDir = new File(outputDir.toString().substring(0,dot));\n\t\t}\n\n\t\tif (outputDir.getName().indexOf(' ') >= 0) { // has spaces?\n\t\t\tString escSpaces = outputDir.toString().replace(\" \", \"\\\\ \");\n\t\t\toutputDir = new File(escSpaces);\n\t\t}\n\t\treturn new File(outputDir, fileName);\n\t}\n\n    /**\n     * Return a list of File objects that name files ANTLR will read\n     * to process T.g; This can be .tokens files if the grammar uses the tokenVocab option\n     * as well as any imported grammar files.\n     */\n    public List<File> getDependenciesFileList() {\n        // Find all the things other than imported grammars\n        List<File> files = getNonImportDependenciesFileList();\n\n        // Handle imported grammars\n        List<Grammar> imports = g.getAllImportedGrammars();\n        if ( imports!=null ) {\n\t\t\tfor (Grammar g : imports) {\n\t\t\t\tString libdir = tool.libDirectory;\n\t\t\t\tString fileName = groomQualifiedFileName(libdir, g.fileName);\n\t\t\t\tfiles.add(new File(fileName));\n\t\t\t}\n\t\t}\n\n        if (files.isEmpty()) {\n            return null;\n        }\n        return files;\n    }\n\n    /**\n     * Return a list of File objects that name files ANTLR will read\n     * to process T.g; This can only be .tokens files and only\n     * if they use the tokenVocab option.\n     *\n     * @return List of dependencies other than imported grammars\n     */\n    public List<File> getNonImportDependenciesFileList() {\n        List<File> files = new ArrayList<File>();\n\n        // handle token vocabulary loads\n        String tokenVocab = g.getOptionString(\"tokenVocab\");\n        if (tokenVocab != null) {\n\t\t\tString fileName =\n\t\t\t\ttokenVocab + CodeGenerator.VOCAB_FILE_EXTENSION;\n\t\t\tFile vocabFile;\n\t\t\tif ( tool.libDirectory.equals(\".\") ) {\n\t\t\t\tvocabFile = new File(fileName);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvocabFile = new File(tool.libDirectory, fileName);\n\t\t\t}\n\t\t\tfiles.add(vocabFile);\n\t\t}\n\n        return files;\n    }\n\n    public ST getDependencies() {\n        loadDependencyTemplates();\n        ST dependenciesST = templates.getInstanceOf(\"dependencies\");\n        dependenciesST.add(\"in\", getDependenciesFileList());\n        dependenciesST.add(\"out\", getGeneratedFileList());\n        dependenciesST.add(\"grammarFileName\", g.fileName);\n        return dependenciesST;\n    }\n\n    public void loadDependencyTemplates() {\n        if (templates != null) return;\n        String fileName = \"org/antlr/v4/tool/templates/depend.stg\";\n        templates = new STGroupFile(fileName, \"UTF-8\");\n    }\n\n    public CodeGenerator getGenerator() {\n        return generator;\n    }\n\n    public String groomQualifiedFileName(String outputDir, String fileName) {\n        if (outputDir.equals(\".\")) {\n            return fileName;\n        }\n\t\telse if (outputDir.indexOf(' ') >= 0) { // has spaces?\n            String escSpaces = outputDir.replace(\" \", \"\\\\ \");\n            return escSpaces + File.separator + fileName;\n        }\n\t\telse {\n            return outputDir + File.separator + fileName;\n        }\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/DOTGenerator.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.runtime.atn.ATNConfig;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.AbstractPredicateTransition;\nimport org.antlr.v4.runtime.atn.ActionTransition;\nimport org.antlr.v4.runtime.atn.AtomTransition;\nimport org.antlr.v4.runtime.atn.BlockEndState;\nimport org.antlr.v4.runtime.atn.BlockStartState;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.NotSetTransition;\nimport org.antlr.v4.runtime.atn.PlusBlockStartState;\nimport org.antlr.v4.runtime.atn.PlusLoopbackState;\nimport org.antlr.v4.runtime.atn.RangeTransition;\nimport org.antlr.v4.runtime.atn.RuleStartState;\nimport org.antlr.v4.runtime.atn.RuleStopState;\nimport org.antlr.v4.runtime.atn.RuleTransition;\nimport org.antlr.v4.runtime.atn.SetTransition;\nimport org.antlr.v4.runtime.atn.StarBlockStartState;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.runtime.atn.StarLoopbackState;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.dfa.DFAState;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STGroupFile;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Set;\n\n/** The DOT (part of graphviz) generation aspect. */\npublic class DOTGenerator {\n\tpublic static final boolean STRIP_NONREDUCED_STATES = false;\n\n\tprotected String arrowhead=\"normal\";\n\tprotected String rankdir=\"LR\";\n\n\t/** Library of output templates; use {@code <attrname>} format. */\n    public final static STGroup stlib = new STGroupFile(\"org/antlr/v4/tool/templates/dot/graphs.stg\");\n\n    protected Grammar grammar;\n\n    /** This aspect is associated with a grammar */\n\tpublic DOTGenerator(Grammar grammar) {\n\t\tthis.grammar = grammar;\n\t}\n\n\tpublic String getDOT(DFA dfa, boolean isLexer) {\n\t\tif ( dfa.s0==null )\treturn null;\n\n\t\tST dot = stlib.getInstanceOf(\"dfa\");\n\t\tdot.add(\"name\", \"DFA\"+dfa.decision);\n\t\tdot.add(\"startState\", dfa.s0.stateNumber);\n//\t\tdot.add(\"useBox\", Tool.internalOption_ShowATNConfigsInDFA);\n\t\tdot.add(\"rankdir\", rankdir);\n\n\t\t// define stop states first; seems to be a bug in DOT where doublecircle\n\t\tfor (DFAState d : dfa.states.keySet()) {\n\t\t\tif ( !d.isAcceptState ) continue;\n\t\t\tST st = stlib.getInstanceOf(\"stopstate\");\n\t\t\tst.add(\"name\", \"s\"+d.stateNumber);\n\t\t\tst.add(\"label\", getStateLabel(d));\n\t\t\tdot.add(\"states\", st);\n\t\t}\n\n\t\tfor (DFAState d : dfa.states.keySet()) {\n\t\t\tif ( d.isAcceptState ) continue;\n\t\t\tif ( d.stateNumber == Integer.MAX_VALUE ) continue;\n\t\t\tST st = stlib.getInstanceOf(\"state\");\n\t\t\tst.add(\"name\", \"s\"+d.stateNumber);\n\t\t\tst.add(\"label\", getStateLabel(d));\n\t\t\tdot.add(\"states\", st);\n\t\t}\n\n\t\tfor (DFAState d : dfa.states.keySet()) {\n\t\t\tif ( d.edges!=null ) {\n\t\t\t\tfor (int i = 0; i < d.edges.length; i++) {\n\t\t\t\t\tDFAState target = d.edges[i];\n\t\t\t\t\tif ( target==null) continue;\n\t\t\t\t\tif ( target.stateNumber == Integer.MAX_VALUE ) continue;\n\t\t\t\t\tint ttype = i-1; // we shift up for EOF as -1 for parser\n\t\t\t\t\tString label = String.valueOf(ttype);\n\t\t\t\t\tif ( isLexer ) label = \"'\"+getEdgeLabel(new StringBuilder().appendCodePoint(i).toString())+\"'\";\n\t\t\t\t\telse if ( grammar!=null ) label = grammar.getTokenDisplayName(ttype);\n\t\t\t\t\tST st = stlib.getInstanceOf(\"edge\");\n\t\t\t\t\tst.add(\"label\", label);\n\t\t\t\t\tst.add(\"src\", \"s\"+d.stateNumber);\n\t\t\t\t\tst.add(\"target\", \"s\"+target.stateNumber);\n\t\t\t\t\tst.add(\"arrowhead\", arrowhead);\n\t\t\t\t\tdot.add(\"edges\", st);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tString output = dot.render();\n\t\treturn Utils.sortLinesInString(output);\n\t}\n\n\tprotected String getStateLabel(DFAState s) {\n\t\tif ( s==null ) return \"null\";\n\t\tStringBuilder buf = new StringBuilder(250);\n\t\tbuf.append('s');\n\t\tbuf.append(s.stateNumber);\n\t\tif ( s.isAcceptState ) {\n\t\t\tbuf.append(\"=>\").append(s.prediction);\n\t\t}\n\t\tif ( s.requiresFullContext) {\n\t\t\tbuf.append(\"^\");\n\t\t}\n\t\tif ( grammar!=null ) {\n\t\t\tSet<Integer> alts = s.getAltSet();\n\t\t\tif ( alts!=null ) {\n\t\t\t\tbuf.append(\"\\\\n\");\n\t\t\t\t// separate alts\n\t\t\t\tIntegerList altList = new IntegerList();\n\t\t\t\taltList.addAll(alts);\n\t\t\t\taltList.sort();\n\t\t\t\tSet<ATNConfig> configurations = s.configs;\n\t\t\t\tfor (int altIndex = 0; altIndex < altList.size(); altIndex++) {\n\t\t\t\t\tint alt = altList.get(altIndex);\n\t\t\t\t\tif ( altIndex>0 ) {\n\t\t\t\t\t\tbuf.append(\"\\\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tbuf.append(\"alt\");\n\t\t\t\t\tbuf.append(alt);\n\t\t\t\t\tbuf.append(':');\n\t\t\t\t\t// get a list of configs for just this alt\n\t\t\t\t\t// it will help us print better later\n\t\t\t\t\tList<ATNConfig> configsInAlt = new ArrayList<ATNConfig>();\n\t\t\t\t\tfor (ATNConfig c : configurations) {\n\t\t\t\t\t\tif (c.alt != alt) continue;\n\t\t\t\t\t\tconfigsInAlt.add(c);\n\t\t\t\t\t}\n\t\t\t\t\tint n = 0;\n\t\t\t\t\tfor (int cIndex = 0; cIndex < configsInAlt.size(); cIndex++) {\n\t\t\t\t\t\tATNConfig c = configsInAlt.get(cIndex);\n\t\t\t\t\t\tn++;\n\t\t\t\t\t\tbuf.append(c.toString(null, false));\n\t\t\t\t\t\tif ( (cIndex+1)<configsInAlt.size() ) {\n\t\t\t\t\t\t\tbuf.append(\", \");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ( n%5==0 && (configsInAlt.size()-cIndex)>3 ) {\n\t\t\t\t\t\t\tbuf.append(\"\\\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tString stateLabel = buf.toString();\n        return stateLabel;\n    }\n\n\tpublic String getDOT(ATNState startState) {\n\t\treturn getDOT(startState, false);\n\t}\n\n\tpublic String getDOT(ATNState startState, boolean isLexer) {\n\t\tSet<String> ruleNames = grammar.rules.keySet();\n\t\tString[] names = new String[ruleNames.size()+1];\n\t\tint i = 0;\n\t\tfor (String s : ruleNames) names[i++] = s;\n\t\treturn getDOT(startState, names, isLexer);\n\t}\n\n    /** Return a String containing a DOT description that, when displayed,\n     *  will show the incoming state machine visually.  All nodes reachable\n     *  from startState will be included.\n     */\n\tpublic String getDOT(ATNState startState, String[] ruleNames, boolean isLexer) {\n\t\tif ( startState==null )\treturn null;\n\n\t\t// The output DOT graph for visualization\n\t\tSet<ATNState> markedStates = new HashSet<ATNState>();\n\t\tST dot = stlib.getInstanceOf(\"atn\");\n\t\tdot.add(\"startState\", startState.stateNumber);\n\t\tdot.add(\"rankdir\", rankdir);\n\n\t\tList<ATNState> work = new LinkedList<ATNState>();\n\n\t\twork.add(startState);\n\t\twhile ( !work.isEmpty() ) {\n\t\t\tATNState s = work.get(0);\n\t\t\tif ( markedStates.contains(s) ) { work.remove(0); continue; }\n\t\t\tmarkedStates.add(s);\n\n\t\t\t// don't go past end of rule node to the follow states\n\t\t\tif ( s instanceof RuleStopState) continue;\n\n\t\t\t// special case: if decision point, then line up the alt start states\n\t\t\t// unless it's an end of block\n//\t\t\tif ( s instanceof BlockStartState ) {\n//\t\t\t\tST rankST = stlib.getInstanceOf(\"decision-rank\");\n//\t\t\t\tDecisionState alt = (DecisionState)s;\n//\t\t\t\tfor (int i=0; i<alt.getNumberOfTransitions(); i++) {\n//\t\t\t\t\tATNState target = alt.transition(i).target;\n//\t\t\t\t\tif ( target!=null ) {\n//\t\t\t\t\t\trankST.add(\"states\", target.stateNumber);\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t\tdot.add(\"decisionRanks\", rankST);\n//\t\t\t}\n\n\t\t\t// make a DOT edge for each transition\n\t\t\tST edgeST;\n\t\t\tfor (int i = 0; i < s.getNumberOfTransitions(); i++) {\n\t\t\t\tTransition edge = s.transition(i);\n\t\t\t\tif ( edge instanceof RuleTransition ) {\n\t\t\t\t\tRuleTransition rr = ((RuleTransition)edge);\n\t\t\t\t\t// don't jump to other rules, but display edge to follow node\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n\n\t\t\t\t\tString label = \"<\" + ruleNames[rr.ruleIndex];\n\t\t\t\t\tif (((RuleStartState)rr.target).isLeftRecursiveRule) {\n\t\t\t\t\t\tlabel += \"[\" + rr.precedence + \"]\";\n\t\t\t\t\t}\n\t\t\t\t\tlabel += \">\";\n\n\t\t\t\t\tedgeST.add(\"label\", label);\n\t\t\t\t\tedgeST.add(\"src\", \"s\"+s.stateNumber);\n\t\t\t\t\tedgeST.add(\"target\", \"s\"+rr.followState.stateNumber);\n\t\t\t\t\tedgeST.add(\"arrowhead\", arrowhead);\n\t\t\t\t\tdot.add(\"edges\", edgeST);\n\t\t\t\t\twork.add(rr.followState);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif ( edge instanceof ActionTransition) {\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"action-edge\");\n\t\t\t\t\tedgeST.add(\"label\", getEdgeLabel(edge.toString()));\n\t\t\t\t}\n\t\t\t\telse if ( edge instanceof AbstractPredicateTransition ) {\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n\t\t\t\t\tedgeST.add(\"label\", getEdgeLabel(edge.toString()));\n\t\t\t\t}\n\t\t\t\telse if ( edge.isEpsilon() ) {\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"epsilon-edge\");\n\t\t\t\t\tedgeST.add(\"label\", getEdgeLabel(edge.toString()));\n\t\t\t\t\tboolean loopback = false;\n\t\t\t\t\tif (edge.target instanceof PlusBlockStartState) {\n\t\t\t\t\t\tloopback = s.equals(((PlusBlockStartState)edge.target).loopBackState);\n\t\t\t\t\t}\n\t\t\t\t\telse if (edge.target instanceof StarLoopEntryState) {\n\t\t\t\t\t\tloopback = s.equals(((StarLoopEntryState)edge.target).loopBackState);\n\t\t\t\t\t}\n\t\t\t\t\tedgeST.add(\"loopback\", loopback);\n\t\t\t\t}\n\t\t\t\telse if ( edge instanceof AtomTransition ) {\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n\t\t\t\t\tAtomTransition atom = (AtomTransition)edge;\n\t\t\t\t\tString label = String.valueOf(atom.label);\n\t\t\t\t\tif ( isLexer ) label = \"'\"+getEdgeLabel(new StringBuilder().appendCodePoint(atom.label).toString())+\"'\";\n\t\t\t\t\telse if ( grammar!=null ) label = grammar.getTokenDisplayName(atom.label);\n\t\t\t\t\tedgeST.add(\"label\", getEdgeLabel(label));\n\t\t\t\t}\n\t\t\t\telse if ( edge instanceof SetTransition ) {\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n\t\t\t\t\tSetTransition set = (SetTransition)edge;\n\t\t\t\t\tString label = set.label().toString();\n\t\t\t\t\tif ( isLexer ) label = set.label().toString(true);\n\t\t\t\t\telse if ( grammar!=null ) label = set.label().toString(grammar.getVocabulary());\n\t\t\t\t\tif ( edge instanceof NotSetTransition ) label = \"~\"+label;\n\t\t\t\t\tedgeST.add(\"label\", getEdgeLabel(label));\n\t\t\t\t}\n\t\t\t\telse if ( edge instanceof RangeTransition ) {\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n\t\t\t\t\tRangeTransition range = (RangeTransition)edge;\n\t\t\t\t\tString label = range.label().toString();\n\t\t\t\t\tif ( isLexer ) label = range.toString();\n\t\t\t\t\telse if ( grammar!=null ) label = range.label().toString(grammar.getVocabulary());\n\t\t\t\t\tedgeST.add(\"label\", getEdgeLabel(label));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n\t\t\t\t\tedgeST.add(\"label\", getEdgeLabel(edge.toString()));\n\t\t\t\t}\n\t\t\t\tedgeST.add(\"src\", \"s\"+s.stateNumber);\n\t\t\t\tedgeST.add(\"target\", \"s\"+edge.target.stateNumber);\n\t\t\t\tedgeST.add(\"arrowhead\", arrowhead);\n\t\t\t\tif (s.getNumberOfTransitions() > 1) {\n\t\t\t\t\tedgeST.add(\"transitionIndex\", i);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tedgeST.add(\"transitionIndex\", false);\n\t\t\t\t}\n\t\t\t\tdot.add(\"edges\", edgeST);\n\t\t\t\twork.add(edge.target);\n\t\t\t}\n\t\t}\n\n\t\t// define nodes we visited (they will appear first in DOT output)\n\t\t// this is an example of ST's lazy eval :)\n\t\t// define stop state first; seems to be a bug in DOT where doublecircle\n\t\t// shape only works if we define them first. weird.\n//\t\tATNState stopState = startState.atn.ruleToStopState.get(startState.rule);\n//\t\tif ( stopState!=null ) {\n//\t\t\tST st = stlib.getInstanceOf(\"stopstate\");\n//\t\t\tst.add(\"name\", \"s\"+stopState.stateNumber);\n//\t\t\tst.add(\"label\", getStateLabel(stopState));\n//\t\t\tdot.add(\"states\", st);\n//\t\t}\n\t\tfor (ATNState s : markedStates) {\n\t\t\tif ( !(s instanceof RuleStopState) ) continue;\n\t\t\tST st = stlib.getInstanceOf(\"stopstate\");\n\t\t\tst.add(\"name\", \"s\"+s.stateNumber);\n\t\t\tst.add(\"label\", getStateLabel(s));\n\t\t\tdot.add(\"states\", st);\n\t\t}\n\n\t\tfor (ATNState s : markedStates) {\n\t\t\tif ( s instanceof RuleStopState ) continue;\n\t\t\tST st = stlib.getInstanceOf(\"state\");\n\t\t\tst.add(\"name\", \"s\"+s.stateNumber);\n\t\t\tst.add(\"label\", getStateLabel(s));\n\t\t\tst.add(\"transitions\", s.getTransitions());\n\t\t\tdot.add(\"states\", st);\n\t\t}\n\n\t\treturn dot.render();\n\t}\n\n\n    /** Do a depth-first walk of the state machine graph and\n     *  fill a DOT description template.  Keep filling the\n     *  states and edges attributes.  We know this is an ATN\n     *  for a rule so don't traverse edges to other rules and\n     *  don't go past rule end state.\n     */\n//    protected void walkRuleATNCreatingDOT(ST dot,\n//                                          ATNState s)\n//    {\n//        if ( markedStates.contains(s) ) {\n//            return; // already visited this node\n//        }\n//\n//        markedStates.add(s.stateNumber); // mark this node as completed.\n//\n//        // first add this node\n//        ST stateST;\n//        if ( s instanceof RuleStopState ) {\n//            stateST = stlib.getInstanceOf(\"stopstate\");\n//        }\n//        else {\n//            stateST = stlib.getInstanceOf(\"state\");\n//        }\n//        stateST.add(\"name\", getStateLabel(s));\n//        dot.add(\"states\", stateST);\n//\n//        if ( s instanceof RuleStopState )  {\n//            return; // don't go past end of rule node to the follow states\n//        }\n//\n//        // special case: if decision point, then line up the alt start states\n//        // unless it's an end of block\n//\t\tif ( s instanceof DecisionState ) {\n//\t\t\tGrammarAST n = ((ATNState)s).ast;\n//\t\t\tif ( n!=null && s instanceof BlockEndState ) {\n//\t\t\t\tST rankST = stlib.getInstanceOf(\"decision-rank\");\n//\t\t\t\tATNState alt = (ATNState)s;\n//\t\t\t\twhile ( alt!=null ) {\n//\t\t\t\t\trankST.add(\"states\", getStateLabel(alt));\n//\t\t\t\t\tif ( alt.transition(1) !=null ) {\n//\t\t\t\t\t\talt = (ATNState)alt.transition(1).target;\n//\t\t\t\t\t}\n//\t\t\t\t\telse {\n//\t\t\t\t\t\talt=null;\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t\tdot.add(\"decisionRanks\", rankST);\n//\t\t\t}\n//\t\t}\n//\n//        // make a DOT edge for each transition\n//\t\tST edgeST = null;\n//\t\tfor (int i = 0; i < s.getNumberOfTransitions(); i++) {\n//            Transition edge = (Transition) s.transition(i);\n//            if ( edge instanceof RuleTransition ) {\n//                RuleTransition rr = ((RuleTransition)edge);\n//                // don't jump to other rules, but display edge to follow node\n//                edgeST = stlib.getInstanceOf(\"edge\");\n//\t\t\t\tif ( rr.rule.g != grammar ) {\n//\t\t\t\t\tedgeST.add(\"label\", \"<\"+rr.rule.g.name+\".\"+rr.rule.name+\">\");\n//\t\t\t\t}\n//\t\t\t\telse {\n//\t\t\t\t\tedgeST.add(\"label\", \"<\"+rr.rule.name+\">\");\n//\t\t\t\t}\n//\t\t\t\tedgeST.add(\"src\", getStateLabel(s));\n//\t\t\t\tedgeST.add(\"target\", getStateLabel(rr.followState));\n//\t\t\t\tedgeST.add(\"arrowhead\", arrowhead);\n//                dot.add(\"edges\", edgeST);\n//\t\t\t\twalkRuleATNCreatingDOT(dot, rr.followState);\n//                continue;\n//            }\n//\t\t\tif ( edge instanceof ActionTransition ) {\n//\t\t\t\tedgeST = stlib.getInstanceOf(\"action-edge\");\n//\t\t\t}\n//\t\t\telse if ( edge instanceof PredicateTransition ) {\n//\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n//\t\t\t}\n//\t\t\telse if ( edge.isEpsilon() ) {\n//\t\t\t\tedgeST = stlib.getInstanceOf(\"epsilon-edge\");\n//\t\t\t}\n//\t\t\telse {\n//\t\t\t\tedgeST = stlib.getInstanceOf(\"edge\");\n//\t\t\t}\n//\t\t\tedgeST.add(\"label\", getEdgeLabel(edge.toString(grammar)));\n//            edgeST.add(\"src\", getStateLabel(s));\n//\t\t\tedgeST.add(\"target\", getStateLabel(edge.target));\n//\t\t\tedgeST.add(\"arrowhead\", arrowhead);\n//            dot.add(\"edges\", edgeST);\n//            walkRuleATNCreatingDOT(dot, edge.target); // keep walkin'\n//        }\n//    }\n\n    /** Fix edge strings so they print out in DOT properly;\n\t *  generate any gated predicates on edge too.\n\t */\n    protected String getEdgeLabel(String label) {\n\t\tlabel = label.replace(\"\\\\\", \"\\\\\\\\\");\n\t\tlabel = label.replace(\"\\\"\", \"\\\\\\\"\");\n\t\tlabel = label.replace(\"\\n\", \"\\\\\\\\n\");\n\t\tlabel = label.replace(\"\\r\", \"\");\n        return label;\n    }\n\n\tprotected String getStateLabel(ATNState s) {\n\t\tif ( s==null ) return \"null\";\n\t\tString stateLabel = \"\";\n\n\t\tif (s instanceof BlockStartState) {\n\t\t\tstateLabel += \"&rarr;\\\\n\";\n\t\t}\n\t\telse if (s instanceof BlockEndState) {\n\t\t\tstateLabel += \"&larr;\\\\n\";\n\t\t}\n\n\t\tstateLabel += String.valueOf(s.stateNumber);\n\n\t\tif (s instanceof PlusBlockStartState || s instanceof PlusLoopbackState) {\n\t\t\tstateLabel += \"+\";\n\t\t}\n\t\telse if (s instanceof StarBlockStartState || s instanceof StarLoopEntryState || s instanceof StarLoopbackState) {\n\t\t\tstateLabel += \"*\";\n\t\t}\n\n\t\tif ( s instanceof DecisionState && ((DecisionState)s).decision>=0 ) {\n\t\t\tstateLabel = stateLabel+\"\\\\nd=\"+((DecisionState)s).decision;\n\t\t}\n\n\t\treturn stateLabel;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/DefaultToolListener.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.Tool;\nimport org.stringtemplate.v4.ST;\n\n/** */\npublic class DefaultToolListener implements ANTLRToolListener {\n\tpublic Tool tool;\n\n\tpublic DefaultToolListener(Tool tool) { this.tool = tool; }\n\n\t@Override\n\tpublic void info(String msg) {\n\t\tif (tool.errMgr.formatWantsSingleLineMessage()) {\n\t\t\tmsg = msg.replace('\\n', ' ');\n\t\t}\n\t\tSystem.out.println(msg);\n\t}\n\n\t@Override\n\tpublic void error(ANTLRMessage msg) {\n\t\tST msgST = tool.errMgr.getMessageTemplate(msg);\n\t\tString outputMsg = msgST.render();\n\t\tif (tool.errMgr.formatWantsSingleLineMessage()) {\n\t\t\toutputMsg = outputMsg.replace('\\n', ' ');\n\t\t}\n\t\tSystem.err.println(outputMsg);\n\t}\n\n\t@Override\n\tpublic void warning(ANTLRMessage msg) {\n\t\tST msgST = tool.errMgr.getMessageTemplate(msg);\n\t\tString outputMsg = msgST.render();\n\t\tif (tool.errMgr.formatWantsSingleLineMessage()) {\n\t\t\toutputMsg = outputMsg.replace('\\n', ' ');\n\t\t}\n\t\tSystem.err.println(outputMsg);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ErrorManager.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.Tool;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STGroupFile;\nimport org.stringtemplate.v4.misc.ErrorBuffer;\n\nimport java.io.File;\nimport java.net.URL;\nimport java.util.*;\n\npublic class ErrorManager {\n\tprivate final static Map<String, STGroupFile> loadedFormats = new HashMap<>();\n\n\tpublic static final String FORMATS_DIR = \"org/antlr/v4/tool/templates/messages/formats/\";\n\n\tpublic Tool tool;\n\tpublic int errors;\n\tpublic int warnings;\n\n\t/** All errors that have been generated */\n\tpublic Set<ErrorType> errorTypes = EnumSet.noneOf(ErrorType.class);\n\n    /** The group of templates that represent the current message format. */\n    STGroup format;\n\n    String formatName;\n\n    ErrorBuffer initSTListener = new ErrorBuffer();\n\n\tpublic ErrorManager(Tool tool) {\n\t\tthis.tool = tool;\n\t}\n\n\tpublic void resetErrorState() {\n\t\terrors = 0;\n\t\twarnings = 0;\n\t}\n\n\tpublic ST getMessageTemplate(ANTLRMessage msg) {\n\t\tST messageST = msg.getMessageTemplate(tool.longMessages);\n\t\tST locationST = getLocationFormat();\n\t\tST reportST = getReportFormat(msg.getErrorType().severity);\n\t\tST messageFormatST = getMessageFormat();\n\n\t\tboolean locationValid = false;\n\t\tif (msg.line != -1) {\n\t\t\tlocationST.add(\"line\", msg.line);\n\t\t\tlocationValid = true;\n\t\t}\n\t\tif (msg.charPosition != -1) {\n\t\t\tlocationST.add(\"column\", msg.charPosition);\n\t\t\tlocationValid = true;\n\t\t}\n\t\tif (msg.fileName != null) {\n\t\t\tString displayFileName = msg.fileName;\n\t\t\tif (formatName.equals(\"antlr\")) {\n\t\t\t\t// Don't show path to file in messages in ANTLR format;\n\t\t\t\t// they're too long.\n\t\t\t\tFile f = new File(msg.fileName);\n\t\t\t\tif ( f.exists() ) {\n\t\t\t\t\tdisplayFileName = f.getName();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// For other message formats, use the full filename in the\n\t\t\t\t// message.  This assumes that these formats are intended to\n\t\t\t\t// be parsed by IDEs, and so they need the full path to\n\t\t\t\t// resolve correctly.\n\t\t\t}\n\t\t\tlocationST.add(\"file\", displayFileName);\n\t\t\tlocationValid = true;\n\t\t}\n\n\t\tmessageFormatST.add(\"id\", msg.getErrorType().code);\n\t\tmessageFormatST.add(\"text\", messageST);\n\n\t\tif (locationValid) reportST.add(\"location\", locationST);\n\t\treportST.add(\"message\", messageFormatST);\n\t\t//((DebugST)reportST).inspect();\n//\t\treportST.impl.dump();\n\t\treturn reportST;\n\t}\n\n    /** Return a StringTemplate that refers to the current format used for\n     * emitting messages.\n     */\n    public ST getLocationFormat() {\n        return format.getInstanceOf(\"location\");\n    }\n\n    public ST getReportFormat(ErrorSeverity severity) {\n        ST st = format.getInstanceOf(\"report\");\n        st.add(\"type\", severity.getText());\n        return st;\n    }\n\n    public ST getMessageFormat() {\n        return format.getInstanceOf(\"message\");\n    }\n    public boolean formatWantsSingleLineMessage() {\n        return format.getInstanceOf(\"wantsSingleLineMessage\").render().equals(\"true\");\n    }\n\n\tpublic void info(String msg) { tool.info(msg); }\n\n\tpublic void syntaxError(ErrorType etype,\n\t\t\t\t\t\t\t\t   String fileName,\n\t\t\t\t\t\t\t\t   org.antlr.runtime.Token token,\n\t\t\t\t\t\t\t\t   org.antlr.runtime.RecognitionException antlrException,\n\t\t\t\t\t\t\t\t   Object... args)\n\t{\n\t\tANTLRMessage msg = new GrammarSyntaxMessage(etype,fileName,token,antlrException,args);\n\t\temit(etype, msg);\n\t}\n\n\tpublic static void fatalInternalError(String error, Throwable e) {\n\t\tinternalError(error, e);\n\t\tthrow new RuntimeException(error, e);\n\t}\n\n\tpublic static void internalError(String error, Throwable e) {\n        StackTraceElement location = getLastNonErrorManagerCodeLocation(e);\n\t\tinternalError(\"Exception \"+e+\"@\"+location+\": \"+error);\n    }\n\n    public static void internalError(String error) {\n        StackTraceElement location =\n            getLastNonErrorManagerCodeLocation(new Exception());\n        String msg = location+\": \"+error;\n        System.err.println(\"internal error: \"+msg);\n    }\n\n    /**\n     * Raise a predefined message with some number of parameters for the StringTemplate but for which there\n     * is no location information possible.\n     * @param errorType The Message Descriptor\n     * @param args The arguments to pass to the StringTemplate\n     */\n\tpublic void toolError(ErrorType errorType, Object... args) {\n\t\ttoolError(errorType, null, args);\n\t}\n\n\tpublic void toolError(ErrorType errorType, Throwable e, Object... args) {\n\t\tToolMessage msg = new ToolMessage(errorType, e, args);\n\t\temit(errorType, msg);\n\t}\n\n    public void grammarError(ErrorType etype,\n\t\t\t\t\t\t\t String fileName,\n\t\t\t\t\t\t\t org.antlr.runtime.Token token,\n\t\t\t\t\t\t\t Object... args)\n\t{\n        ANTLRMessage msg = new GrammarSemanticsMessage(etype,fileName,token,args);\n\t\temit(etype, msg);\n\n\t}\n\n\tpublic void leftRecursionCycles(String fileName, Collection<? extends Collection<Rule>> cycles) {\n\t\terrors++;\n\t\tANTLRMessage msg = new LeftRecursionCyclesMessage(fileName, cycles);\n\t\ttool.error(msg);\n\t}\n\n    public int getNumErrors() {\n        return errors;\n    }\n\n    /** Return first non ErrorManager code location for generating messages */\n    private static StackTraceElement getLastNonErrorManagerCodeLocation(Throwable e) {\n        StackTraceElement[] stack = e.getStackTrace();\n        int i = 0;\n        for (; i < stack.length; i++) {\n            StackTraceElement t = stack[i];\n            if (!t.toString().contains(\"ErrorManager\")) {\n                break;\n            }\n        }\n        StackTraceElement location = stack[i];\n        return location;\n    }\n\n    // S U P P O R T  C O D E\n\n\t@SuppressWarnings(\"fallthrough\")\n\tpublic void emit(ErrorType etype, ANTLRMessage msg) {\n\t\tswitch ( etype.severity ) {\n\t\t\tcase WARNING_ONE_OFF:\n\t\t\t\tif ( errorTypes.contains(etype) ) break;\n\t\t\t\t// fall thru\n\t\t\tcase WARNING:\n\t\t\t\twarnings++;\n\t\t\t\ttool.warning(msg);\n\t\t\t\tbreak;\n\t\t\tcase ERROR_ONE_OFF:\n\t\t\t\tif ( errorTypes.contains(etype) ) break;\n\t\t\t\t// fall thru\n\t\t\tcase ERROR:\n\t\t\t\terrors++;\n\t\t\t\ttool.error(msg);\n\t\t\t\tbreak;\n      default:\n        break;\n\t\t}\n\t\terrorTypes.add(etype);\n\t}\n\n    /** The format gets reset either from the Tool if the user supplied a command line option to that effect\n     *  Otherwise we just use the default \"antlr\".\n     */\n    public void setFormat(String formatName) {\n\t\tSTGroupFile loadedFormat;\n\n\t\tsynchronized (loadedFormats) {\n\t\t\tloadedFormat = loadedFormats.get(formatName);\n\t\t\tif (loadedFormat == null) {\n\t\t\t\tString fileName = FORMATS_DIR + formatName + STGroup.GROUP_FILE_EXTENSION;\n\t\t\t\tClassLoader cl = Thread.currentThread().getContextClassLoader();\n\t\t\t\tURL url = cl.getResource(fileName);\n\t\t\t\tif (url == null) {\n\t\t\t\t\tcl = ErrorManager.class.getClassLoader();\n\t\t\t\t\turl = cl.getResource(fileName);\n\t\t\t\t}\n\t\t\t\tif (url == null && formatName.equals(\"antlr\")) {\n\t\t\t\t\trawError(\"ANTLR installation corrupted; cannot find ANTLR messages format file \" + fileName);\n\t\t\t\t\tpanic();\n\t\t\t\t}\n\t\t\t\telse if (url == null) {\n\t\t\t\t\trawError(\"no such message format file \" + fileName + \" retrying with default ANTLR format\");\n\t\t\t\t\tsetFormat(\"antlr\"); // recurse on this rule, trying the default message format\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tloadedFormat = new STGroupFile(url, \"UTF-8\", '<', '>');\n\t\t\t\tloadedFormat.load();\n\n\t\t\t\tloadedFormats.put(formatName, loadedFormat);\n\t\t\t}\n\t\t}\n\n\t\tthis.formatName = formatName;\n\t\tthis.format = loadedFormat;\n\n\t\tif (!initSTListener.errors.isEmpty()) {\n\t\t\trawError(\"ANTLR installation corrupted; can't load messages format file:\\n\" +\n\t\t\t\t\tinitSTListener.toString());\n\t\t\tpanic();\n\t\t}\n\n\t\tboolean formatOK = verifyFormat();\n\t\tif (!formatOK && formatName.equals(\"antlr\")) {\n\t\t\trawError(\"ANTLR installation corrupted; ANTLR messages format file \" + formatName + \".stg incomplete\");\n\t\t\tpanic();\n\t\t}\n\t\telse if (!formatOK) {\n\t\t\tsetFormat(\"antlr\"); // recurse on this rule, trying the default message format\n\t\t}\n\t}\n\n    /** Verify the message format template group */\n    protected boolean verifyFormat() {\n        boolean ok = true;\n        if (!format.isDefined(\"location\")) {\n            System.err.println(\"Format template 'location' not found in \" + formatName);\n            ok = false;\n        }\n        if (!format.isDefined(\"message\")) {\n            System.err.println(\"Format template 'message' not found in \" + formatName);\n            ok = false;\n        }\n        if (!format.isDefined(\"report\")) {\n            System.err.println(\"Format template 'report' not found in \" + formatName);\n            ok = false;\n        }\n        return ok;\n    }\n\n    /** If there are errors during ErrorManager init, we have no choice\n     *  but to go to System.err.\n     */\n    static void rawError(String msg) {\n        System.err.println(msg);\n    }\n\n    static void rawError(String msg, Throwable e) {\n        rawError(msg);\n        e.printStackTrace(System.err);\n    }\n\n\tpublic void panic(ErrorType errorType, Object... args) {\n\t\tToolMessage msg = new ToolMessage(errorType, args);\n\t\tST msgST = getMessageTemplate(msg);\n\t\tString outputMsg = msgST.render();\n\t\tif ( formatWantsSingleLineMessage() ) {\n\t\t\toutputMsg = outputMsg.replace('\\n', ' ');\n\t\t}\n\t\tpanic(outputMsg);\n\t}\n\n\tpublic static void panic(String msg) {\n\t\trawError(msg);\n\t\tpanic();\n\t}\n\n    public static void panic() {\n        // can't call tool.panic since there may be multiple tools; just\n        // one error manager\n        throw new Error(\"ANTLR ErrorManager panic\");\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ErrorSeverity.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.tool;\n\n/**\n * Abstracts away the definition of Message severity and the text that should\n * display to represent that severity if there is no StringTemplate available\n * to do it.\n *\n * @author Jim Idle - Temporal Wave LLC (jimi@temporal-wave.com)\n */\npublic enum ErrorSeverity {\n    INFO    (\"info\"),\n\tWARNING (\"warning\"),\n\tWARNING_ONE_OFF (\"warning\"),\n\tERROR   (\"error\"),\n\tERROR_ONE_OFF   (\"error\"),\n    FATAL   (\"fatal\"),  // TODO: add fatal for which phase? sync with ErrorManager\n    ;\n\n    /**\n     * The text version of the ENUM value, used for display purposes\n     */\n    private final String text;\n\n    /**\n     * Standard getter method for the text that should be displayed in order to\n     * represent the severity to humans and product modelers.\n     *\n     * @return The human readable string representing the severity level\n     */\n    public String getText() { return text; }\n\n    /**\n     * Standard constructor to build an instance of the Enum entries\n     *\n     * @param text The human readable string representing the severity level\n     */\n    private ErrorSeverity(String text) { this.text = text; }\n}\n\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ErrorType.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.runtime.Lexer;\n\n/**\n * A complex enumeration of all the error messages that the tool can issue.\n * <p>\n * When adding error messages, also add a description of the message to the\n * Wiki with a location under the Wiki page\n * <a href=\"http://www.antlr.org/wiki/display/ANTLR4/Errors+Reported+by+the+ANTLR+Tool\">Errors Reported by the ANTLR Tool</a>.\n *\n * @author Jim Idle &lt;jimi@temporal-wave.com&gt;, Terence Parr\n * @since 4.0\n */\npublic enum ErrorType {\n\t/*\n\t * Tool errors\n\t */\n\n\t/**\n\t * Compiler Error 1.\n\t *\n\t * <p>cannot write file <em>filename</em>: <em>reason</em></p>\n\t */\n\tCANNOT_WRITE_FILE(1, \"cannot write file <arg>: <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 2.\n\t *\n\t * <p>unknown command-line option <em>option</em></p>\n\t */\n\tINVALID_CMDLINE_ARG(2, \"unknown command-line option <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 3.\n\t *\n\t * <p>cannot find tokens file <em>filename</em></p>\n\t */\n\tCANNOT_FIND_TOKENS_FILE_GIVEN_ON_CMDLINE(3, \"cannot find tokens file <arg> given for <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 4.\n\t *\n\t * <p>cannot find tokens file <em>filename</em>: <em>reason</em></p>\n\t */\n\tERROR_READING_TOKENS_FILE(4, \"error reading tokens file <arg>: <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 5.\n\t *\n\t * <p>directory not found: <em>directory</em></p>\n\t */\n\tDIR_NOT_FOUND(5, \"directory not found: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 6.\n\t *\n\t * <p>output directory is a file: <em>filename</em></p>\n\t */\n\tOUTPUT_DIR_IS_FILE(6, \"output directory is a file: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 7.\n\t *\n\t * <p>cannot find or open file: <em>filename</em></p>\n\t */\n\tCANNOT_OPEN_FILE(7, \"cannot find or open file: <arg><if(exception&&verbose)>; reason: <exception><endif>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 8.\n\t *\n\t * <p>\n\t * grammar name <em>name</em> and file name <em>filename</em> differ</p>\n\t */\n\tFILE_AND_GRAMMAR_NAME_DIFFER(8, \"grammar name <arg> and file name <arg2> differ\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 9.\n\t *\n\t * <p>invalid {@code -Dname=value} syntax: <em>syntax</em></p>\n\t */\n\tBAD_OPTION_SET_SYNTAX(9, \"invalid -Dname=value syntax: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 10.\n\t *\n\t * <p>warning treated as error</p>\n\t */\n\tWARNING_TREATED_AS_ERROR(10, \"warning treated as error\", ErrorSeverity.ERROR_ONE_OFF),\n\t/**\n\t * Compiler Error 11.\n\t *\n\t * <p>cannot find tokens file <em>filename</em>: <em>reason</em></p>\n\t */\n\tERROR_READING_IMPORTED_GRAMMAR(11, \"error reading imported grammar <arg> referenced in <arg2>\", ErrorSeverity.ERROR),\n\n\t/**\n\t * Compiler Error 20.\n\t *\n\t * <p>internal error: <em>message</em></p>\n\t */\n\tINTERNAL_ERROR(20, \"internal error: <arg> <arg2><if(exception&&verbose)>: <exception>\" +\n\t\t\t\t   \"<stackTrace; separator=\\\"\\\\n\\\"><endif>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 21.\n\t *\n\t * <p>.tokens file syntax error <em>filename</em>: <em>message</em></p>\n\t */\n\tTOKENS_FILE_SYNTAX_ERROR(21, \".tokens file syntax error <arg>:<arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 22.\n\t *\n\t * <p>template error: <em>message</em></p>\n\t */\n\tSTRING_TEMPLATE_WARNING(22, \"template error: <arg> <arg2><if(exception&&verbose)>: <exception>\" +\n\t\t\t\t   \"<stackTrace; separator=\\\"\\\\n\\\"><endif>\", ErrorSeverity.WARNING),\n\n\t/*\n\t * Code generation errors\n\t */\n\n\t/**\n\t * Compiler Error 30.\n\t *\n\t * <p>can't find code generation templates: <em>group</em></p>\n\t */\n\tMISSING_CODE_GEN_TEMPLATES(30, \"can't find code generation templates: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 31.\n\t *\n\t * <p>\n\t * ANTLR cannot generate <em>language</em> code as of version\n\t * <em>version</em></p>\n\t */\n\tCANNOT_CREATE_TARGET_GENERATOR(31, \"ANTLR cannot generate <arg> code as of version \"+ Tool.VERSION, ErrorSeverity.ERROR_ONE_OFF),\n\t/**\n\t * Compiler Error 32.\n\t *\n\t * <p>\n\t * code generation template <em>template</em> has missing, misnamed, or\n\t * incomplete arg list; missing <em>field</em></p>\n\t */\n\tCODE_TEMPLATE_ARG_ISSUE(32, \"code generation template <arg> has missing, misnamed, or incomplete arg list; missing <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 33.\n\t *\n\t * <p>missing code generation template <em>template</em></p>\n\t */\n\tCODE_GEN_TEMPLATES_INCOMPLETE(33, \"missing code generation template <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 34.\n\t *\n\t * <p>\n\t * no mapping to template name for output model class <em>class</em></p>\n\t */\n\tNO_MODEL_TO_TEMPLATE_MAPPING(34, \"no mapping to template name for output model class <arg>\", ErrorSeverity.ERROR),\n    /**\n   \t * Compiler Error 35.\n   \t *\n   \t * <p>templates/target and tool aren't compatible</p>\n   \t */\n   \tINCOMPATIBLE_TOOL_AND_TEMPLATES(35, \"<arg3> code generation target requires ANTLR <arg2>; it can't be loaded by the current ANTLR <arg>\", ErrorSeverity.ERROR),\n\n\t/*\n\t * Grammar errors\n\t */\n\n\t/**\n\t * Compiler Error 50.\n\t *\n\t * <p>syntax error: <em>message</em></p>\n\t */\n\tSYNTAX_ERROR(50, \"syntax error: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 51.\n\t *\n\t * <p>rule <em>rule</em> redefinition; previous at line <em>line</em></p>\n\t */\n\tRULE_REDEFINITION(51, \"rule <arg> redefinition; previous at line <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 52.\n\t *\n\t * <p>lexer rule <em>rule</em> not allowed in parser</p>\n\t */\n\tLEXER_RULES_NOT_ALLOWED(52, \"lexer rule <arg> not allowed in parser\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 53.\n\t *\n\t * <p>parser rule <em>rule</em> not allowed in lexer</p>\n\t */\n\tPARSER_RULES_NOT_ALLOWED(53, \"parser rule <arg> not allowed in lexer\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 54.\n\t *\n\t * <p>\n\t * repeated grammar prequel spec ({@code options}, {@code tokens}, or\n\t * {@code import}); please merge</p>\n\t */\n    REPEATED_PREQUEL(54, \"repeated grammar prequel spec (options, tokens, or import); please merge\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 56.\n\t *\n\t * <p>reference to undefined rule: <em>rule</em></p>\n\t *\n\t * @see #PARSER_RULE_REF_IN_LEXER_RULE\n\t */\n\tUNDEFINED_RULE_REF(56, \"reference to undefined rule: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 57.\n\t *\n\t * <p>\n\t * reference to undefined rule <em>rule</em> in non-local ref\n\t * <em>reference</em></p>\n\t */\n\tUNDEFINED_RULE_IN_NONLOCAL_REF(57, \"reference to undefined rule <arg> in non-local ref <arg3>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 60.\n\t *\n\t * <p>token names must start with an uppercase letter: <em>name</em></p>\n\t */\n    TOKEN_NAMES_MUST_START_UPPER(60, \"token names must start with an uppercase letter: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 63.\n\t *\n\t * <p>\n\t * unknown attribute reference <em>attribute</em> in\n\t * <em>expression</em></p>\n\t */\n\tUNKNOWN_SIMPLE_ATTRIBUTE(63, \"unknown attribute reference <arg> in <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 64.\n\t *\n\t * <p>\n\t * parameter <em>parameter</em> of rule <em>rule</em> is not accessible\n\t * in this scope: <em>expression</em></p>\n\t */\n\tINVALID_RULE_PARAMETER_REF(64, \"parameter <arg> of rule <arg2> is not accessible in this scope: <arg3>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 65.\n\t *\n\t * <p>\n\t * unknown attribute <em>attribute</em> for rule <em>rule</em> in\n\t * <em>expression</em></p>\n\t */\n\tUNKNOWN_RULE_ATTRIBUTE(65, \"unknown attribute <arg> for rule <arg2> in <arg3>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 66.\n\t *\n\t * <p>\n\t * attribute <em>attribute</em> isn't a valid property in\n\t * <em>expression</em></p>\n\t */\n    UNKNOWN_ATTRIBUTE_IN_SCOPE(66, \"attribute <arg> isn't a valid property in <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 67.\n\t *\n\t * <p>\n\t * missing attribute access on rule reference <em>rule</em> in\n\t * <em>expression</em></p>\n\t */\n\tISOLATED_RULE_REF(67, \"missing attribute access on rule reference <arg> in <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 69.\n\t *\n\t * <p>label <em>label</em> conflicts with rule with same name</p>\n\t */\n\tLABEL_CONFLICTS_WITH_RULE(69, \"label <arg> conflicts with rule with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 70.\n\t *\n\t * <p>label <em>label</em> conflicts with token with same name</p>\n\t */\n\tLABEL_CONFLICTS_WITH_TOKEN(70, \"label <arg> conflicts with token with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 72.\n\t *\n\t * <p>label <em>label</em> conflicts with parameter with same name</p>\n\t */\n\tLABEL_CONFLICTS_WITH_ARG(72, \"label <arg> conflicts with parameter with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 73.\n\t *\n\t * <p>label <em>label</em> conflicts with return value with same name</p>\n\t */\n\tLABEL_CONFLICTS_WITH_RETVAL(73, \"label <arg> conflicts with return value with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 74.\n\t *\n\t * <p>label <em>label</em> conflicts with local with same name</p>\n\t */\n\tLABEL_CONFLICTS_WITH_LOCAL(74, \"label <arg> conflicts with local with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 75.\n\t *\n\t * <p>\n\t * label <em>label</em> type mismatch with previous definition:\n\t * <em>message</em></p>\n\t */\n\tLABEL_TYPE_CONFLICT(75, \"label <arg> type mismatch with previous definition: <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 76.\n\t *\n\t * <p>\n\t * return value <em>name</em> conflicts with parameter with same name</p>\n\t */\n\tRETVAL_CONFLICTS_WITH_ARG(76, \"return value <arg> conflicts with parameter with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 79.\n\t *\n\t * <p>missing argument(s) on rule reference: <em>rule</em></p>\n\t */\n\tMISSING_RULE_ARGS(79, \"missing argument(s) on rule reference: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 80.\n\t *\n\t * <p>rule <em>rule</em> has no defined parameters</p>\n\t */\n\tRULE_HAS_NO_ARGS(80, \"rule <arg> has no defined parameters\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 83.\n\t *\n\t * <p>unsupported option <em>option</em></p>\n\t */\n\tILLEGAL_OPTION(83, \"unsupported option <arg>\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Warning 84.\n\t *\n\t * <p>unsupported option value <em>name</em>=<em>value</em></p>\n\t */\n\tILLEGAL_OPTION_VALUE(84, \"unsupported option value <arg>=<arg2>\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 94.\n\t *\n\t * <p>redefinition of <em>action</em> action</p>\n\t */\n    ACTION_REDEFINITION(94, \"redefinition of <arg> action\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 99.\n\t *\n\t * <p>This error may take any of the following forms.</p>\n\t *\n\t * <ul>\n\t * <li>grammar <em>grammar</em> has no rules</li>\n\t * <li>implicitly generated grammar <em>grammar</em> has no rules</li>\n\t * </ul>\n\t */\n\tNO_RULES(99, \"<if(arg2.implicitLexerOwner)>implicitly generated <endif>grammar <arg> has no rules\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 105.\n\t *\n\t * <p>\n\t * reference to undefined grammar in rule reference:\n\t * <em>grammar</em>.<em>rule</em></p>\n\t */\n\tNO_SUCH_GRAMMAR_SCOPE(105, \"reference to undefined grammar in rule reference: <arg>.<arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 106.\n\t *\n\t * <p>rule <em>rule</em> is not defined in grammar <em>grammar</em></p>\n\t */\n\tNO_SUCH_RULE_IN_SCOPE(106, \"rule <arg2> is not defined in grammar <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 108.\n\t *\n\t * <p>token name <em>Token</em> is already defined</p>\n\t */\n\tTOKEN_NAME_REASSIGNMENT(108, \"token name <arg> is already defined\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Warning 109.\n\t *\n\t * <p>options ignored in imported grammar <em>grammar</em></p>\n\t */\n\tOPTIONS_IN_DELEGATE(109, \"options ignored in imported grammar <arg>\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 110.\n\t *\n\t * <p>\n\t * can't find or load grammar <em>grammar</em> from\n\t * <em>filename</em></p>\n\t */\n\tCANNOT_FIND_IMPORTED_GRAMMAR(110, \"can't find or load grammar <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 111.\n\t *\n\t * <p>\n\t * <em>grammartype</em> grammar <em>grammar1</em> cannot import\n\t * <em>grammartype</em> grammar <em>grammar2</em></p>\n\t */\n\tINVALID_IMPORT(111, \"<arg.typeString> grammar <arg.name> cannot import <arg2.typeString> grammar <arg2.name>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 113.\n\t *\n\t * <p>\n\t * <em>grammartype</em> grammar <em>grammar1</em> and imported\n\t * <em>grammartype</em> grammar <em>grammar2</em> both generate\n\t * <em>recognizer</em></p>\n\t */\n\tIMPORT_NAME_CLASH(113, \"<arg.typeString> grammar <arg.name> and imported <arg2.typeString> grammar <arg2.name> both generate <arg2.recognizerName>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 114.\n\t *\n\t * <p>cannot find tokens file <em>filename</em></p>\n\t */\n\tCANNOT_FIND_TOKENS_FILE_REFD_IN_GRAMMAR(114, \"cannot find tokens file <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 118.\n\t *\n\t * <p>\n\t * all operators of alt <em>alt</em> of left-recursive rule must have same\n\t * associativity</p>\n\t *\n\t * @deprecated This warning is no longer applicable with the current syntax for specifying associativity.\n\t */\n\t@Deprecated\n\tALL_OPS_NEED_SAME_ASSOC(118, \"all operators of alt <arg> of left-recursive rule must have same associativity\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 119.\n\t *\n\t * <p>\n\t * The following sets of rules are mutually left-recursive\n\t * <em>[rules]</em></p>\n\t */\n\tLEFT_RECURSION_CYCLES(119, \"The following sets of rules are mutually left-recursive <arg:{c| [<c:{r|<r.name>}; separator=\\\", \\\">]}; separator=\\\" and \\\">\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 120.\n\t *\n\t * <p>lexical modes are only allowed in lexer grammars</p>\n\t */\n\tMODE_NOT_IN_LEXER(120, \"lexical modes are only allowed in lexer grammars\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 121.\n\t *\n\t * <p>cannot find an attribute name in attribute declaration</p>\n\t */\n\tCANNOT_FIND_ATTRIBUTE_NAME_IN_DECL(121, \"cannot find an attribute name in attribute declaration\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 122.\n\t *\n\t * <p>rule <em>rule</em>: must label all alternatives or none</p>\n\t */\n\tRULE_WITH_TOO_FEW_ALT_LABELS(122, \"rule <arg>: must label all alternatives or none\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 123.\n\t *\n\t * <p>\n\t * rule alt label <em>label</em> redefined in rule <em>rule1</em>,\n\t * originally in rule <em>rule2</em></p>\n\t */\n\tALT_LABEL_REDEF(123, \"rule alt label <arg> redefined in rule <arg2>, originally in rule <arg3>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 124.\n\t *\n\t * <p>\n\t * rule alt label <em>label</em> conflicts with rule <em>rule</em></p>\n\t */\n\tALT_LABEL_CONFLICTS_WITH_RULE(124, \"rule alt label <arg> conflicts with rule <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 125.\n\t *\n\t * <p>implicit definition of token <em>Token</em> in parser</p>\n\t */\n\tIMPLICIT_TOKEN_DEFINITION(125, \"implicit definition of token <arg> in parser\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 126.\n\t *\n\t * <p>\n\t * cannot create implicit token for string literal in non-combined grammar:\n\t * <em>literal</em></p>\n\t */\n\tIMPLICIT_STRING_DEFINITION(126, \"cannot create implicit token for string literal in non-combined grammar: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 128.\n\t *\n\t * <p>\n\t * attribute references not allowed in lexer actions:\n\t * <em>expression</em></p>\n\t */\n\tATTRIBUTE_IN_LEXER_ACTION(128, \"attribute references not allowed in lexer actions: $<arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 130.\n\t *\n\t * <p>label <em>label</em> assigned to a block which is not a set</p>\n\t */\n\tLABEL_BLOCK_NOT_A_SET(130, \"label <arg> assigned to a block which is not a set\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 131.\n\t *\n\t * <p>This warning may take any of the following forms.</p>\n\t *\n\t * <ul>\n\t * <li>greedy block {@code ()*} contains wildcard; the non-greedy syntax {@code ()*?} may be preferred</li>\n\t * <li>greedy block {@code ()+} contains wildcard; the non-greedy syntax {@code ()+?} may be preferred</li>\n\t * </ul>\n\t */\n\tEXPECTED_NON_GREEDY_WILDCARD_BLOCK(131, \"greedy block ()<arg> contains wildcard; the non-greedy syntax ()<arg>? may be preferred\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 132.\n\t *\n\t * <p>\n\t * action in lexer rule <em>rule</em> must be last element of single\n\t * outermost alt</p>\n\t *\n\t * @deprecated This error is no longer issued by ANTLR 4.2.\n\t */\n\t@Deprecated\n\tLEXER_ACTION_PLACEMENT_ISSUE(132, \"action in lexer rule <arg> must be last element of single outermost alt\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 133.\n\t *\n\t * <p>\n\t * {@code ->command} in lexer rule <em>rule</em> must be last element of\n\t * single outermost alt</p>\n\t */\n\tLEXER_COMMAND_PLACEMENT_ISSUE(133, \"->command in lexer rule <arg> must be last element of single outermost alt\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 134.\n\t *\n\t * <p>\n\t * symbol <em>symbol</em> conflicts with generated code in target language\n\t * or runtime</p>\n\t */\n\t@Deprecated\n\tUSE_OF_BAD_WORD(134, \"symbol <arg> conflicts with generated code in target language or runtime\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 183.\n\t *\n\t * <p>rule reference <em>rule</em> is not currently supported in a set</p>\n\t */\n\tUNSUPPORTED_REFERENCE_IN_LEXER_SET(183, \"rule reference <arg> is not currently supported in a set\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 135.\n\t *\n\t * <p>cannot assign a value to list label <em>label</em></p>\n\t */\n\tASSIGNMENT_TO_LIST_LABEL(135, \"cannot assign a value to list label <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 136.\n\t *\n\t * <p>return value <em>name</em> conflicts with rule with same name</p>\n\t */\n\tRETVAL_CONFLICTS_WITH_RULE(136, \"return value <arg> conflicts with rule with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 137.\n\t *\n\t * <p>return value <em>name</em> conflicts with token with same name</p>\n\t */\n\tRETVAL_CONFLICTS_WITH_TOKEN(137, \"return value <arg> conflicts with token with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 138.\n\t *\n\t * <p>parameter <em>parameter</em> conflicts with rule with same name</p>\n\t */\n\tARG_CONFLICTS_WITH_RULE(138, \"parameter <arg> conflicts with rule with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 139.\n\t *\n\t * <p>parameter <em>parameter</em> conflicts with token with same name</p>\n\t */\n\tARG_CONFLICTS_WITH_TOKEN(139, \"parameter <arg> conflicts with token with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 140.\n\t *\n\t * <p>local <em>local</em> conflicts with rule with same name</p>\n\t */\n\tLOCAL_CONFLICTS_WITH_RULE(140, \"local <arg> conflicts with rule with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 141.\n\t *\n\t * <p>local <em>local</em> conflicts with rule token same name</p>\n\t */\n\tLOCAL_CONFLICTS_WITH_TOKEN(141, \"local <arg> conflicts with rule token same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 142.\n\t *\n\t * <p>local <em>local</em> conflicts with parameter with same name</p>\n\t */\n\tLOCAL_CONFLICTS_WITH_ARG(142, \"local <arg> conflicts with parameter with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 143.\n\t *\n\t * <p>local <em>local</em> conflicts with return value with same name</p>\n\t */\n\tLOCAL_CONFLICTS_WITH_RETVAL(143, \"local <arg> conflicts with return value with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 144.\n\t *\n\t * <p>\n\t * multi-character literals are not allowed in lexer sets:\n\t * <em>literal</em></p>\n\t */\n\tINVALID_LITERAL_IN_LEXER_SET(144, \"multi-character literals are not allowed in lexer sets: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 145.\n\t *\n\t * <p>\n\t * lexer mode <em>mode</em> must contain at least one non-fragment\n\t * rule</p>\n\t *\n\t * <p>\n\t * Every lexer mode must contain at least one rule which is not declared\n\t * with the {@code fragment} modifier.</p>\n\t */\n\tMODE_WITHOUT_RULES(145, \"lexer mode <arg> must contain at least one non-fragment rule\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 146.\n\t *\n\t * <p>non-fragment lexer rule <em>rule</em> can match the empty string</p>\n\t *\n\t * <p>All non-fragment lexer rules must match at least one character.</p>\n\t *\n\t * <p>The following example shows this error.</p>\n\t *\n\t * <pre>\n\t * Whitespace : [ \\t]+;  // ok\n\t * Whitespace : [ \\t];   // ok\n\t *\n\t * fragment WS : [ \\t]*; // ok\n\t *\n\t * Whitespace : [ \\t]*;  // error 146\n\t * </pre>\n\t */\n\tEPSILON_TOKEN(146, \"non-fragment lexer rule <arg> can match the empty string\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 147.\n\t *\n\t * <p>\n\t * left recursive rule <em>rule</em> must contain an alternative which is\n\t * not left recursive</p>\n\t *\n\t * <p>Left-recursive rules must contain at least one alternative which is not\n\t * left recursive.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * // error 147:\n\t * a : a ID\n\t *   | a INT\n\t *   ;\n\t * </pre>\n\t */\n\tNO_NON_LR_ALTS(147, \"left recursive rule <arg> must contain an alternative which is not left recursive\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 148.\n\t *\n\t * <p>\n\t * left recursive rule <em>rule</em> contains a left recursive alternative\n\t * which can be followed by the empty string</p>\n\t *\n\t * <p>In left-recursive rules, all left-recursive alternatives must match at\n\t * least one symbol following the recursive rule invocation.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * a : ID    // ok        (alternative is not left recursive)\n\t *   | a INT // ok        (a must be follow by INT)\n\t *   | a ID? // error 148 (the ID following a is optional)\n\t *   ;\n\t * </pre>\n\t */\n\tEPSILON_LR_FOLLOW(148, \"left recursive rule <arg> contains a left recursive alternative which can be followed by the empty string\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 149.\n\t *\n\t * <p>\n\t * lexer command <em>command</em> does not exist or is not supported by\n\t * the current target</p>\n\t *\n\t * <p>Each lexer command requires an explicit implementation in the target\n\t * templates. This error indicates that the command was incorrectly written\n\t * or is not supported by the current target.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * X : 'foo' -&gt; type(Foo);  // ok\n\t * Y : 'foo' -&gt; token(Foo); // error 149 (token is not a supported lexer command)\n\t * </pre>\n\t *\n\t * @since 4.1\n\t */\n\tINVALID_LEXER_COMMAND(149, \"lexer command <arg> does not exist or is not supported by the current target\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 150.\n\t *\n\t * <p>missing argument for lexer command <em>command</em></p>\n\t *\n\t * <p>Some lexer commands require an argument.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * X : 'foo' -&gt; type(Foo); // ok\n\t * Y : 'foo' -&gt; type;      // error 150 (the type command requires an argument)\n\t * </pre>\n\t *\n\t * @since 4.1\n\t */\n\tMISSING_LEXER_COMMAND_ARGUMENT(150, \"missing argument for lexer command <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 151.\n\t *\n\t * <p>lexer command <em>command</em> does not take any arguments</p>\n\t *\n\t * <p>A lexer command which does not take parameters was invoked with an\n\t * argument.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * X : 'foo' -&gt; popMode;    // ok\n\t * Y : 'foo' -&gt; popMode(A); // error 151 (the popMode command does not take an argument)\n\t * </pre>\n\t *\n\t * @since 4.1\n\t */\n\tUNWANTED_LEXER_COMMAND_ARGUMENT(151, \"lexer command <arg> does not take any arguments\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 152.\n\t *\n\t * <p>unterminated string literal</p>\n\t *\n\t * <p>The grammar contains an unterminated string literal.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * x : 'x'; // ok\n\t * y : 'y';  // error 152\n\t * </pre>\n\t *\n\t * @since 4.1\n\t */\n\tUNTERMINATED_STRING_LITERAL(152, \"unterminated string literal\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 153.\n\t *\n\t * <p>\n\t * rule <em>rule</em> contains a closure with at least one alternative\n\t * that can match an empty string</p>\n\t *\n\t * <p>A rule contains a closure ({@code (...)*}) or positive closure\n\t * ({@code (...)+}) around an empty alternative.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * x  : ;\n\t * y  : x+;                                // error 153\n\t * z1 : ('foo' | 'bar'? 'bar2'?)*;         // error 153\n\t * z2 : ('foo' | 'bar' 'bar2'? | 'bar2')*; // ok\n\t * </pre>\n\t *\n\t * @since 4.1\n\t */\n\tEPSILON_CLOSURE(153, \"rule <arg> contains a closure with at least one alternative that can match an empty string\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 154.\n\t *\n\t * <p>\n\t * rule <em>rule</em> contains an optional block with at least one\n\t * alternative that can match an empty string</p>\n\t *\n\t * <p>A rule contains an optional block ({@code (...)?}) around an empty\n\t * alternative.</p>\n\t *\n\t * <p>The following rule produces this warning.</p>\n\t *\n\t * <pre>\n\t * x  : ;\n\t * y  : x?;                                // warning 154\n\t * z1 : ('foo' | 'bar'? 'bar2'?)?;         // warning 154\n\t * z2 : ('foo' | 'bar' 'bar2'? | 'bar2')?; // ok\n\t * </pre>\n\t *\n\t * @since 4.1\n\t */\n\tEPSILON_OPTIONAL(154, \"rule <arg> contains an optional block with at least one alternative that can match an empty string\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Warning 155.\n\t *\n\t * <p>\n\t * rule <em>rule</em> contains a lexer command with an unrecognized\n\t * constant value; lexer interpreters may produce incorrect output</p>\n\t *\n\t * <p>A lexer rule contains a standard lexer command, but the constant value\n\t * argument for the command is an unrecognized string. As a result, the\n\t * lexer command will be translated as a custom lexer action, preventing the\n\t * command from executing in some interpreted modes. The output of the lexer\n\t * interpreter may not match the output of the generated lexer.</p>\n\t *\n\t * <p>The following rule produces this warning.</p>\n\t *\n\t * <pre>\n\t * &#064;members {\n\t * public static final int CUSTOM = HIDDEN + 1;\n\t * }\n\t *\n\t * X : 'foo' -&gt; channel(HIDDEN);           // ok\n\t * Y : 'bar' -&gt; channel(CUSTOM);           // warning 155\n\t * </pre>\n\t *\n\t * @since 4.2\n\t */\n\tUNKNOWN_LEXER_CONSTANT(155, \"rule <arg> contains a lexer command with an unrecognized constant value; lexer interpreters may produce incorrect output\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 156.\n\t *\n\t * <p>invalid escape sequence</p>\n\t *\n\t * <p>The grammar contains a string literal with an invalid escape sequence.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * x : 'x';  // ok\n\t * y : '\\u005Cu'; // error 156\n\t * </pre>\n\t *\n\t * @since 4.2.1\n\t */\n\tINVALID_ESCAPE_SEQUENCE(156, \"invalid escape sequence <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 157.\n\t *\n\t * <p>rule <em>rule</em> contains an assoc element option in an\n\t * unrecognized location</p>\n\t *\n\t * <p>\n\t * In ANTLR 4.2, the position of the {@code assoc} element option was moved\n\t * from the operator terminal(s) to the alternative itself. This warning is\n\t * reported when an {@code assoc} element option is specified on a grammar\n\t * element that is not recognized by the current version of ANTLR, and as a\n\t * result will simply be ignored.\n\t * </p>\n\t *\n\t * <p>The following rule produces this warning.</p>\n\t *\n\t * <pre>\n\t * x : 'x'\n\t *   | x '+'&lt;assoc=right&gt; x   // warning 157\n\t *   |&lt;assoc=right&gt; x * x   // ok\n\t *   ;\n\t * </pre>\n\t *\n\t * @since 4.2.1\n\t */\n\tUNRECOGNIZED_ASSOC_OPTION(157, \"rule <arg> contains an assoc terminal option in an unrecognized location\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Warning 158.\n\t *\n\t * <p>fragment rule <em>rule</em> contains an action or command which can\n\t * never be executed</p>\n\t *\n\t * <p>A lexer rule which is marked with the {@code fragment} modifier\n\t * contains an embedded action or lexer command. ANTLR lexers only execute\n\t * commands and embedded actions located in the top-level matched rule.\n\t * Since fragment rules can never be the top-level rule matched by a lexer,\n\t * actions or commands placed in these rules can never be executed during\n\t * the lexing process.</p>\n\t *\n\t * <p>The following rule produces this warning.</p>\n\t *\n\t * <pre>\n\t * X1 : 'x' -&gt; more    // ok\n\t *    ;\n\t * Y1 : 'x' {more();}  // ok\n\t *    ;\n\t * fragment\n\t * X2 : 'x' -&gt; more    // warning 158\n\t *    ;\n\t * fragment\n\t * Y2 : 'x' {more();}  // warning 158\n\t *    ;\n\t * </pre>\n\t *\n\t * @since 4.2.1\n\t */\n\tFRAGMENT_ACTION_IGNORED(158, \"fragment rule <arg> contains an action or command which can never be executed\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 159.\n\t *\n\t * <p>cannot declare a rule with reserved name <em>rule</em></p>\n\t *\n\t * <p>A rule was declared with a reserved name.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * EOF :  ' '   // error 159 (EOF is a reserved name)\n\t *     ;\n\t * </pre>\n\t *\n\t * @since 4.2.1\n\t */\n\tRESERVED_RULE_NAME(159, \"cannot declare a rule with reserved name <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 160.\n\t *\n\t * <p>reference to parser rule <em>rule</em> in lexer rule <em>name</em></p>\n\t *\n\t * @see #UNDEFINED_RULE_REF\n\t */\n\tPARSER_RULE_REF_IN_LEXER_RULE(160, \"reference to parser rule <arg> in lexer rule <arg2>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 161.\n\t *\n\t * <p>channel <em>name</em> conflicts with token with same name</p>\n\t */\n\tCHANNEL_CONFLICTS_WITH_TOKEN(161, \"channel <arg> conflicts with token with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 162.\n\t *\n\t * <p>channel <em>name</em> conflicts with mode with same name</p>\n\t */\n\tCHANNEL_CONFLICTS_WITH_MODE(162, \"channel <arg> conflicts with mode with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 163.\n\t *\n\t * <p>custom channels are not supported in parser grammars</p>\n\t */\n\tCHANNELS_BLOCK_IN_PARSER_GRAMMAR(163, \"custom channels are not supported in parser grammars\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 164.\n\t *\n\t * <p>custom channels are not supported in combined grammars</p>\n\t */\n\tCHANNELS_BLOCK_IN_COMBINED_GRAMMAR(164, \"custom channels are not supported in combined grammars\", ErrorSeverity.ERROR),\n\n\tNONCONFORMING_LR_RULE(169, \"rule <arg> is left recursive but doesn't conform to a pattern ANTLR can handle\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 170.\n\t *\n\t * <pre>\n\t * mode M1;\n\t * A1: 'a'; // ok\n\t * mode M2;\n\t * A2: 'a'; // ok\n\t * M1: 'b'; // error 170\n\t * </pre>\n\t *\n\t * <p>mode <em>name</em> conflicts with token with same name</p>\n\t */\n\tMODE_CONFLICTS_WITH_TOKEN(170, \"mode <arg> conflicts with token with same name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 171.\n\t *\n\t * <p>can not use or declare token with reserved name</p>\n\t *\n\t * <p>Reserved names: HIDDEN, DEFAULT_TOKEN_CHANNEL, SKIP, MORE, MAX_CHAR_VALUE, MIN_CHAR_VALUE.\n\t *\n\t * <p>Can be used but cannot be declared: EOF</p>\n\t */\n\tTOKEN_CONFLICTS_WITH_COMMON_CONSTANTS(171, \"cannot use or declare token with reserved name <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 172.\n\t *\n\t * <p>can not use or declare channel with reserved name</p>\n\t *\n\t * <p>Reserved names: DEFAULT_MODE, SKIP, MORE, EOF, MAX_CHAR_VALUE, MIN_CHAR_VALUE.\n\t *\n\t * <p>Can be used but cannot be declared: HIDDEN, DEFAULT_TOKEN_CHANNEL</p>\n\t */\n\tCHANNEL_CONFLICTS_WITH_COMMON_CONSTANTS(172, \"cannot use or declare channel with reserved name <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 173.\n\t *\n\t * <p>can not use or declare mode with reserved name</p>\n\t *\n\t * <p>Reserved names: HIDDEN, DEFAULT_TOKEN_CHANNEL, SKIP, MORE, MAX_CHAR_VALUE, MIN_CHAR_VALUE.\n\t *\n\t * <p>Can be used and cannot declared: DEFAULT_MODE</p>\n\t */\n\tMODE_CONFLICTS_WITH_COMMON_CONSTANTS(173, \"cannot use or declare mode with reserved name <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 174.\n\t *\n\t * <p>empty strings and sets not allowed</p>\n\t *\n\t * <pre>\n\t * A: '''test''';\n\t * B: '';\n\t * C: 'test' '';\n\t * D: [];\n\t * E: [f-a];\n\t * </pre>\n\t */\n\tEMPTY_STRINGS_AND_SETS_NOT_ALLOWED(174, \"string literals and sets cannot be empty: <arg>\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 175.\n\t *\n\t * <p><em>name</em> is not a recognized token name</p>\n\t *\n\t * <pre>TOKEN: 'a' -> type(CHANNEL1); // error 175</pre>\n\t */\n\tCONSTANT_VALUE_IS_NOT_A_RECOGNIZED_TOKEN_NAME(175, \"<arg> is not a recognized token name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 176.\n\t *\n\t * <p><em>name</em>is not a recognized mode name</p>\n\t *\n\t * <pre>TOKEN: 'a' -> mode(MODE1); // error 176</pre>\n\t */\n\tCONSTANT_VALUE_IS_NOT_A_RECOGNIZED_MODE_NAME(176, \"<arg> is not a recognized mode name\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Error 177.\n\t *\n\t * <p><em>name</em> is not a recognized channel name</p>\n\t *\n\t * <pre>TOKEN: 'a' -> channel(TOKEN1); // error 177</pre>\n\t */\n\tCONSTANT_VALUE_IS_NOT_A_RECOGNIZED_CHANNEL_NAME(177, \"<arg> is not a recognized channel name\", ErrorSeverity.ERROR),\n\t/*\n\t* Compiler Warning 178.\n\t*\n\t* <p>lexer rule has a duplicated commands</p>\n\t*\n\t* <p>TOKEN: 'asdf' -> mode(MODE1), mode(MODE2);</p>\n\t* */\n\tDUPLICATED_COMMAND(178, \"duplicated command <arg>\", ErrorSeverity.WARNING),\n\t/*\n\t* Compiler Waring 179.\n\t*\n\t* <p>incompatible commands <em>command1</em> and <em>command2</em></p>\n\t*\n\t* <p>T00: 'a00' -> skip, more;</p>\n\t */\n\tINCOMPATIBLE_COMMANDS(179, \"incompatible commands <arg> and <arg2>\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Warning 180.\n\t *\n\t * <p>chars \"a-f\" used multiple times in set [a-fc-m]</p>\n\t *\n\t * <pre>\n\t * A:    [aa-z];   // warning\n\t * B:    [a-fc-m]; // warning\n\t * </pre>\n\t *\n\t * TODO: Does not work with fragment rules.\n\t */\n\tCHARACTERS_COLLISION_IN_SET(180, \"chars <arg> used multiple times in set <arg2>\", ErrorSeverity.WARNING),\n\n\t/**\n\t * Compiler Warning 181\n\t *\n\t * <p>The token range operator makes no sense in the parser as token types\n\t * are not ordered (except in implementation).\n\t * </p>\n\t *\n\t * <pre>\n\t * grammar T;\n\t * a : 'A'..'Z' ;\n\t * </pre>\n\t *\n\t */\n\tTOKEN_RANGE_IN_PARSER(181, \"token ranges not allowed in parser: <arg>..<arg2>\", ErrorSeverity.ERROR),\n\n\t/**\n\t * Compiler Error 182.\n\t *\n\t * <p>Unicode properties cannot be part of a lexer charset range</p>\n\t *\n\t * <pre>\n\t * A: [\\\\p{Letter}-\\\\p{Number}];\n\t * </pre>\n\t */\n\tUNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE(\n\t\t\t182,\n\t\t\t\"unicode property escapes not allowed in lexer charset range: <arg>\",\n\t\t\tErrorSeverity.ERROR),\n\n\t/**\n\t * Compiler Warning 184.\n\t *\n\t * <p>The token value overlapped by another token or self</p>\n\t *\n\t * <pre>\n\t * TOKEN1: 'value';\n\t * TOKEN2: 'value'; // warning\n\t * </pre>\n\t */\n\tTOKEN_UNREACHABLE(\n\t\t\t184,\n\t\t\t\"One of the token <arg> values unreachable. <arg2> is always overlapped by token <arg3>\",\n\t\t\tErrorSeverity.WARNING),\n\n\t/**\n\t * <p>Range probably contains not implied characters. Both bounds should be defined in lower or UPPER case\n\t * For instance, the range [A-z] (ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxy)\n\t * probably contains not implied characters: [\\]^_`\n\t *\n\t * Use the following definition: [A-Za-z]\n\t * If the characters are implied, include them explicitly: [A-Za-z[\\\\\\]^_`]\n\t * </p>\n\t *\n\t * <pre>\n\t * TOKEN: [A-z]; // warning\n\t * </pre>\n\t */\n\tRANGE_PROBABLY_CONTAINS_NOT_IMPLIED_CHARACTERS(\n\t\t\t185,\n\t\t\t\"Range <arg>..<arg2> probably contains not implied characters <arg3>. Both bounds should be defined in lower or UPPER case\",\n\t\t\tErrorSeverity.WARNING\n\t),\n\n\t/**\n\t * <p>\n\t * rule <em>rule</em> contains a closure with at least one alternative\n\t * that can match EOF</p>\n\t *\n\t * <p>A rule contains a closure ({@code (...)*}) or positive closure\n\t * ({@code (...)+}) around EOF.</p>\n\t *\n\t * <p>The following rule produces this error.</p>\n\t *\n\t * <pre>\n\t * x : EOF*;         // error\n\t * y : EOF+;         // error\n\t * z : EOF;         // ok\n\t * </pre>\n\t */\n\tEOF_CLOSURE(\n\t\t\t186,\n\t\t\t\"rule <arg> contains a closure with at least one alternative that can match EOF\",\n\t\t\tErrorSeverity.ERROR\n\t),\n\n\t/**\n\t * <p>Redundant caseInsensitive lexer rule option</p>\n\t *\n\t * <pre>\n\t * options { caseInsensitive=true; }\n\t * TOKEN options { caseInsensitive=true; } : [a-z]+ -> caseInsensitive(true); // warning\n\t * </pre>\n\t */\n\tREDUNDANT_CASE_INSENSITIVE_LEXER_RULE_OPTION(\n\t\t\t187,\n\t\t\t\"caseInsensitive lexer rule option is redundant because its value equals to global value (<arg>)\",\n\t\t\tErrorSeverity.WARNING\n\t),\n\n\t/*\n\t * Backward incompatibility errors\n\t */\n\n\t/**\n\t * Compiler Error 200.\n\t *\n\t * <p>tree grammars are not supported in ANTLR 4</p>\n\t *\n\t * <p>\n\t * This error message is provided as a compatibility notice for users\n\t * migrating from ANTLR 3. ANTLR 4 does not support tree grammars, but\n\t * instead offers automatically generated parse tree listeners and visitors\n\t * as a more maintainable alternative.</p>\n\t */\n\t@Deprecated\n\tV3_TREE_GRAMMAR(200, \"tree grammars are not supported in ANTLR 4\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 201.\n\t *\n\t * <p>\n\t * labels in lexer rules are not supported in ANTLR 4; actions cannot\n\t * reference elements of lexical rules but you can use\n\t * {@link Lexer#getText()} to get the entire text matched for the rule</p>\n\t *\n\t * <p>\n\t * ANTLR 4 uses a DFA for recognition of entire tokens, resulting in faster\n\t * and smaller lexers than ANTLR 3 produced. As a result, sub-rules\n\t * referenced within lexer rules are not tracked independently, and cannot\n\t * be assigned to labels.</p>\n\t */\n\t@Deprecated\n\tV3_LEXER_LABEL(201, \"labels in lexer rules are not supported in ANTLR 4; \" +\n\t\t\"actions cannot reference elements of lexical rules but you can use \" +\n\t\t\"getText() to get the entire text matched for the rule\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Warning 202.\n\t *\n\t * <p>\n\t * {@code tokens {A; B;}} syntax is now {@code tokens {A, B}} in ANTLR\n\t * 4</p>\n\t *\n\t * <p>\n\t * ANTLR 4 uses comma-separated token declarations in the {@code tokens{}}\n\t * block. This warning appears when the tokens block is written using the\n\t * ANTLR 3 syntax of semicolon-terminated token declarations.</p>\n\t *\n\t * <p>\n\t * <strong>NOTE:</strong> ANTLR 4 does not allow a trailing comma to appear following the\n\t * last token declared in the {@code tokens{}} block.</p>\n\t */\n\t@Deprecated\n\tV3_TOKENS_SYNTAX(202, \"tokens {A; B;} syntax is now tokens {A, B} in ANTLR 4\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 203.\n\t *\n\t * <p>\n\t * assignments in {@code tokens{}} are not supported in ANTLR 4; use lexical\n\t * rule <em>TokenName</em> : <em>LiteralValue</em>; instead</p>\n\t *\n\t * <p>\n\t * ANTLR 3 allowed literal tokens to be declared and assigned a value within\n\t * the {@code tokens{}} block. ANTLR 4 no longer offers this syntax. When\n\t * migrating a grammar from ANTLR 3 to ANTLR 4, any tokens with a literal\n\t * value declared in the {@code tokens{}} block should be converted to\n\t * standard lexer rules.</p>\n\t */\n\t@Deprecated\n\tV3_ASSIGN_IN_TOKENS(203, \"assignments in tokens{} are not supported in ANTLR 4; use lexical rule <arg> : <arg2>; instead\", ErrorSeverity.ERROR),\n\t/**\n\t * Compiler Warning 204.\n\t *\n\t * <p>\n\t * {@code {...}?=>} explicitly gated semantic predicates are deprecated in\n\t * ANTLR 4; use {@code {...}?} instead</p>\n\t *\n\t * <p>\n\t * ANTLR 4 treats semantic predicates consistently in a manner similar to\n\t * gated semantic predicates in ANTLR 3. When migrating a grammar from ANTLR\n\t * 3 to ANTLR 4, all uses of the gated semantic predicate syntax can be\n\t * safely converted to the standard semantic predicated syntax, which is the\n\t * only form used by ANTLR 4.</p>\n\t */\n\t@Deprecated\n\tV3_GATED_SEMPRED(204, \"{...}?=> explicitly gated semantic predicates are deprecated in ANTLR 4; use {...}? instead\", ErrorSeverity.WARNING),\n\t/**\n\t * Compiler Error 205.\n\t *\n\t * <p>{@code (...)=>} syntactic predicates are not supported in ANTLR 4</p>\n\t *\n\t * <p>\n\t * ANTLR 4's improved lookahead algorithms do not require the use of\n\t * syntactic predicates to disambiguate long lookahead sequences. The\n\t * syntactic predicates should be removed when migrating a grammar from\n\t * ANTLR 3 to ANTLR 4.</p>\n\t */\n\t@Deprecated\n\tV3_SYNPRED(205, \"(...)=> syntactic predicates are not supported in ANTLR 4\", ErrorSeverity.ERROR),\n\n    // Dependency sorting errors\n\n    /* t1.g4 -> t2.g4 -> t3.g4 ->t1.g4 */\n    //CIRCULAR_DEPENDENCY(200, \"your grammars contain a circular dependency and cannot be sorted into a valid build order\", ErrorSeverity.ERROR),\n\t;\n\n\t/**\n\t * The error or warning message, in StringTemplate 4 format using {@code <}\n\t * and {@code >} as the delimiters. Arguments for the message may be\n\t * referenced using the following names:\n\t *\n\t * <ul>\n\t * <li>{@code arg}: The first template argument</li>\n\t * <li>{@code arg2}: The second template argument</li>\n\t * <li>{@code arg3}: The third template argument</li>\n\t * <li>{@code verbose}: {@code true} if verbose messages were requested; otherwise, {@code false}</li>\n\t * <li>{@code exception}: The exception which resulted in the error, if any.</li>\n\t * <li>{@code stackTrace}: The stack trace for the exception, when available.</li>\n\t * </ul>\n\t */\n\tpublic final String msg;\n\t/**\n\t * The error or warning number.\n\t *\n\t * <p>The code should be unique, and following its\n\t * use in a release should not be altered or reassigned.</p>\n\t */\n    public final int code;\n\t/**\n\t * The error severity.\n\t */\n    public final ErrorSeverity severity;\n\n\t/**\n\t * Constructs a new {@link ErrorType} with the specified code, message, and\n\t * severity.\n\t *\n\t * @param code The unique error number.\n\t * @param msg The error message template.\n\t * @param severity The error severity.\n\t */\n\tErrorType(int code, String msg, ErrorSeverity severity) {\n        this.code = code;\n\t\tthis.msg = msg;\n        this.severity = severity;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/Grammar.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.analysis.LeftRecursiveRuleTransformer;\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.misc.CharSupport;\nimport org.antlr.v4.misc.OrderedHashMap;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.parse.GrammarTreeVisitor;\nimport org.antlr.v4.parse.TokenVocabParser;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.runtime.atn.SemanticContext;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.*;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTWithOptions;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\nimport org.antlr.v4.tool.ast.PredAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Grammar implements AttributeResolver {\n\tpublic static final String GRAMMAR_FROM_STRING_NAME = \"<string>\";\n\t/**\n\t * This value is used in the following situations to indicate that a token\n\t * type does not have an associated name which can be directly referenced in\n\t * a grammar.\n\t *\n\t * <ul>\n\t * <li>This value is the name and display name for the token with type\n\t * {@link Token#INVALID_TYPE}.</li>\n\t * <li>This value is the name for tokens with a type not represented by a\n\t * named token. The display name for these tokens is simply the string\n\t * representation of the token type as an integer.</li>\n\t * </ul>\n\t */\n\tpublic static final String INVALID_TOKEN_NAME = \"<INVALID>\";\n\t/**\n\t * This value is used as the name for elements in the array returned by\n\t * {@link #getRuleNames} for indexes not associated with a rule.\n\t */\n\tpublic static final String INVALID_RULE_NAME = \"<invalid>\";\n\n\tpublic static final String caseInsensitiveOptionName = \"caseInsensitive\";\n\n\tpublic static final Set<String> parserOptions = new HashSet<String>();\n\tstatic {\n\t\tparserOptions.add(\"superClass\");\n\t\tparserOptions.add(\"contextSuperClass\");\n\t\tparserOptions.add(\"TokenLabelType\");\n\t\tparserOptions.add(\"tokenVocab\");\n\t\tparserOptions.add(\"language\");\n\t\tparserOptions.add(\"accessLevel\");\n\t\tparserOptions.add(\"exportMacro\");\n\t\tparserOptions.add(caseInsensitiveOptionName);\n\t}\n\n\tpublic static final Set<String> lexerOptions = parserOptions;\n\n\tpublic static final Set<String> lexerRuleOptions = new HashSet<>();\n\tstatic {\n\t\tlexerRuleOptions.add(caseInsensitiveOptionName);\n\t}\n\n\tpublic static final Set<String> parseRuleOptions = new HashSet<>();\n\n\tpublic static final Set<String> parserBlockOptions = new HashSet<String>();\n\n\tpublic static final Set<String> lexerBlockOptions = new HashSet<String>();\n\n\t/** Legal options for rule refs like id&lt;key=value&gt; */\n\tpublic static final Set<String> ruleRefOptions = new HashSet<String>();\n\tstatic {\n\t\truleRefOptions.add(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME);\n\t\truleRefOptions.add(LeftRecursiveRuleTransformer.TOKENINDEX_OPTION_NAME);\n\t}\n\n\t/** Legal options for terminal refs like ID&lt;assoc=right&gt; */\n\tpublic static final Set<String> tokenOptions = new HashSet<String>();\n\tstatic {\n\t\ttokenOptions.add(\"assoc\");\n\t\ttokenOptions.add(LeftRecursiveRuleTransformer.TOKENINDEX_OPTION_NAME);\n\t}\n\n\tpublic static final Set<String> actionOptions = new HashSet<String>();\n\n\tpublic static final Set<String> semPredOptions = new HashSet<String>();\n\tstatic {\n\t\tsemPredOptions.add(LeftRecursiveRuleTransformer.PRECEDENCE_OPTION_NAME);\n\t\tsemPredOptions.add(\"fail\");\n\t}\n\n\tpublic static final Set<String> doNotCopyOptionsToLexer = new HashSet<String>();\n\tstatic {\n\t\tdoNotCopyOptionsToLexer.add(\"superClass\");\n\t\tdoNotCopyOptionsToLexer.add(\"TokenLabelType\");\n\t\tdoNotCopyOptionsToLexer.add(\"tokenVocab\");\n\t}\n\n\tpublic static final Map<String, AttributeDict> grammarAndLabelRefTypeToScope =\n\t\tnew HashMap<String, AttributeDict>();\n\tstatic {\n\t\tgrammarAndLabelRefTypeToScope.put(\"parser:RULE_LABEL\", Rule.predefinedRulePropertiesDict);\n\t\tgrammarAndLabelRefTypeToScope.put(\"parser:TOKEN_LABEL\", AttributeDict.predefinedTokenDict);\n\t\tgrammarAndLabelRefTypeToScope.put(\"combined:RULE_LABEL\", Rule.predefinedRulePropertiesDict);\n\t\tgrammarAndLabelRefTypeToScope.put(\"combined:TOKEN_LABEL\", AttributeDict.predefinedTokenDict);\n\t}\n\n\tpublic String name;\n    public GrammarRootAST ast;\n\n\t/** Track token stream used to create this grammar */\n\n\tpublic final org.antlr.runtime.TokenStream tokenStream;\n\n\t/** If we transform grammar, track original unaltered token stream.\n\t *  This is set to the same value as tokenStream when tokenStream is\n\t *  initially set.\n\t *\n\t *  If this field differs from tokenStream, then we have transformed\n\t *  the grammar.\n\t */\n\n\tpublic org.antlr.runtime.TokenStream originalTokenStream;\n\n    public String text; // testing only\n    public String fileName;\n\n    /** Was this parser grammar created from a COMBINED grammar?  If so,\n\t *  this is what we extracted.\n\t */\n    public LexerGrammar implicitLexer;\n\n\t/** If this is an extracted/implicit lexer, we point at original grammar */\n\tpublic Grammar originalGrammar;\n\n    /** If we're imported, who imported us? If null, implies grammar is root */\n    public Grammar parent;\n    public List<Grammar> importedGrammars;\n\n\t/** All rules defined in this specific grammar, not imported. Also does\n\t *  not include lexical rules if combined.\n\t */\n    public OrderedHashMap<String, Rule> rules = new OrderedHashMap<String, Rule>();\n\tpublic List<Rule> indexToRule = new ArrayList<Rule>();\n\n\tint ruleNumber = 0; // used to get rule indexes (0..n-1)\n\tint stringLiteralRuleNumber = 0; // used to invent rule names for 'keyword', ';', ... (0..n-1)\n\n\t/** The ATN that represents the grammar with edges labelled with tokens\n\t *  or epsilon.  It is more suitable to analysis than an AST representation.\n\t */\n\tpublic ATN atn;\n\n\tpublic Map<Integer, Interval> stateToGrammarRegionMap;\n\n\tpublic Map<Integer, DFA> decisionDFAs = new HashMap<Integer, DFA>();\n\n\tpublic List<IntervalSet[]> decisionLOOK;\n\n\tpublic final Tool tool;\n\n\t/** Token names and literal tokens like \"void\" are uniquely indexed.\n\t *  with -1 implying EOF.  Characters are different; they go from\n\t *  -1 (EOF) to \\uFFFE.  For example, 0 could be a binary byte you\n\t *  want to lexer.  Labels of DFA/ATN transitions can be both tokens\n\t *  and characters.  I use negative numbers for bookkeeping labels\n\t *  like EPSILON. Char/String literals and token types overlap in the same\n\t *  space, however.\n\t */\n\tint maxTokenType = Token.MIN_USER_TOKEN_TYPE -1;\n\n\t/**\n\t * Map token like {@code ID} (but not literals like {@code 'while'}) to its\n\t * token type.\n\t */\n\tpublic final Map<String, Integer> tokenNameToTypeMap = new LinkedHashMap<String, Integer>();\n\n\t/**\n\t * Map token literals like {@code 'while'} to its token type. It may be that\n\t * {@code WHILE=\"while\"=35}, in which case both {@link #tokenNameToTypeMap}\n\t * and this field will have entries both mapped to 35.\n\t */\n\tpublic final Map<String, Integer> stringLiteralToTypeMap = new LinkedHashMap<String, Integer>();\n\n\t/**\n\t * Reverse index for {@link #stringLiteralToTypeMap}. Indexed with raw token\n\t * type. 0 is invalid.\n\t */\n\tpublic final List<String> typeToStringLiteralList = new ArrayList<String>();\n\n\t/**\n\t * Map a token type to its token name. Indexed with raw token type. 0 is\n\t * invalid.\n\t */\n\tpublic final List<String> typeToTokenList = new ArrayList<String>();\n\n\t/**\n\t * The maximum channel value which is assigned by this grammar. Values below\n\t * {@link Token#MIN_USER_CHANNEL_VALUE} are assumed to be predefined.\n\t */\n\tint maxChannelType = Token.MIN_USER_CHANNEL_VALUE - 1;\n\n\t/**\n\t * Map channel like {@code COMMENTS_CHANNEL} to its constant channel value.\n\t * Only user-defined channels are defined in this map.\n\t */\n\tpublic final Map<String, Integer> channelNameToValueMap = new LinkedHashMap<String, Integer>();\n\n\t/**\n\t * Map a constant channel value to its name. Indexed with raw channel value.\n\t * The predefined channels {@link Token#DEFAULT_CHANNEL} and\n\t * {@link Token#HIDDEN_CHANNEL} are not stored in this list, so the values\n\t * at the corresponding indexes is {@code null}.\n\t */\n\tpublic final List<String> channelValueToNameList = new ArrayList<String>();\n\n    /** Map a name to an action.\n     *  The code generator will use this to fill holes in the output files.\n     *  I track the AST node for the action in case I need the line number\n     *  for errors.\n     */\n\tpublic Map<String,ActionAST> namedActions = new HashMap<String,ActionAST>();\n\n\t/** Tracks all user lexer actions in all alternatives of all rules.\n\t *  Doesn't track sempreds.  maps tree node to action index (alt number 1..n).\n \t */\n\tpublic LinkedHashMap<ActionAST, Integer> lexerActions = new LinkedHashMap<ActionAST, Integer>();\n\n\t/** All sempreds found in grammar; maps tree node to sempred index;\n\t *  sempred index is 0..n-1\n\t */\n\tpublic LinkedHashMap<PredAST, Integer> sempreds = new LinkedHashMap<PredAST, Integer>();\n\t/** Map the other direction upon demand */\n\tpublic LinkedHashMap<Integer, PredAST> indexToPredMap;\n\n\tpublic static final String AUTO_GENERATED_TOKEN_NAME_PREFIX = \"T__\";\n\n\tpublic Grammar(Tool tool, GrammarRootAST ast) {\n\t\tif ( ast==null ) {\n\t\t\tthrow new NullPointerException(\"ast\");\n\t\t}\n\n\t\tif (ast.tokenStream == null) {\n\t\t\tthrow new IllegalArgumentException(\"ast must have a token stream\");\n\t\t}\n\n        this.tool = tool;\n        this.ast = ast;\n        this.name = (ast.getChild(0)).getText();\n\t\tthis.tokenStream = ast.tokenStream;\n\t\tthis.originalTokenStream = this.tokenStream;\n\n\t\tinitTokenSymbolTables();\n    }\n\n\t/** For testing */\n\tpublic Grammar(String grammarText) throws org.antlr.runtime.RecognitionException {\n\t\tthis(GRAMMAR_FROM_STRING_NAME, grammarText, null);\n\t}\n\n\tpublic Grammar(String grammarText, LexerGrammar tokenVocabSource) throws org.antlr.runtime.RecognitionException {\n\t\tthis(GRAMMAR_FROM_STRING_NAME, grammarText, tokenVocabSource, null);\n\t}\n\n\t/** For testing */\n\tpublic Grammar(String grammarText, ANTLRToolListener listener)\n\t\tthrows org.antlr.runtime.RecognitionException\n\t{\n\t\tthis(GRAMMAR_FROM_STRING_NAME, grammarText, listener);\n\t}\n\n\t/** For testing; builds trees, does sem anal */\n\tpublic Grammar(String fileName, String grammarText)\n\t\tthrows org.antlr.runtime.RecognitionException\n\t{\n\t\tthis(fileName, grammarText, null);\n\t}\n\n\t/** For testing; builds trees, does sem anal */\n\tpublic Grammar(String fileName, String grammarText, ANTLRToolListener listener)\n\t\tthrows org.antlr.runtime.RecognitionException\n\t{\n\t\tthis(fileName, grammarText, null, listener);\n\t}\n\n\t/** For testing; builds trees, does sem anal */\n\tpublic Grammar(String fileName, String grammarText, Grammar tokenVocabSource, ANTLRToolListener listener)\n\t\tthrows org.antlr.runtime.RecognitionException\n\t{\n        this.text = grammarText;\n\t\tthis.fileName = fileName;\n\t\tthis.tool = new Tool();\n\t\tANTLRToolListener hush = new ANTLRToolListener() {\n\t\t\t@Override\n\t\t\tpublic void info(String msg) { }\n\t\t\t@Override\n\t\t\tpublic void error(ANTLRMessage msg) { }\n\t\t\t@Override\n\t\t\tpublic void warning(ANTLRMessage msg) { }\n\t\t};\n\t\ttool.addListener(hush); // we want to hush errors/warnings\n\t\tthis.tool.addListener(listener);\n\t\torg.antlr.runtime.ANTLRStringStream in = new org.antlr.runtime.ANTLRStringStream(grammarText);\n\t\tin.name = fileName;\n\n\t\tthis.ast = tool.parse(fileName, in);\n\t\tif ( ast==null ) {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\n\t\tif (ast.tokenStream == null) {\n\t\t\tthrow new IllegalStateException(\"expected ast to have a token stream\");\n\t\t}\n\n\t\tthis.tokenStream = ast.tokenStream;\n\t\tthis.originalTokenStream = this.tokenStream;\n\n\t\t// ensure each node has pointer to surrounding grammar\n\t\tfinal Grammar thiz = this;\n\t\torg.antlr.runtime.tree.TreeVisitor v = new org.antlr.runtime.tree.TreeVisitor(new GrammarASTAdaptor());\n\t\tv.visit(ast, new org.antlr.runtime.tree.TreeVisitorAction() {\n\t\t\t@Override\n\t\t\tpublic Object pre(Object t) { ((GrammarAST)t).g = thiz; return t; }\n\t\t\t@Override\n\t\t\tpublic Object post(Object t) { return t; }\n\t\t});\n\t\tinitTokenSymbolTables();\n\n\t\tif (tokenVocabSource != null) {\n\t\t\timportVocab(tokenVocabSource);\n\t\t}\n\n\t\ttool.process(this, false);\n    }\n\n\tprotected void initTokenSymbolTables() {\n\t\ttokenNameToTypeMap.put(\"EOF\", Token.EOF);\n\n\t\t// reserve a spot for the INVALID token\n\t\ttypeToTokenList.add(null);\n\t}\n\n\n\tpublic void loadImportedGrammars() {\n\t\tthis.loadImportedGrammars(new HashSet<>());\n\t}\n\n    private void loadImportedGrammars(Set<String> visited) {\n\t\tif ( ast==null ) return;\n        GrammarAST i = (GrammarAST)ast.getFirstChildWithType(ANTLRParser.IMPORT);\n        if ( i==null ) return;\n\t    visited.add(this.name);\n        importedGrammars = new ArrayList<Grammar>();\n        for (Object c : i.getChildren()) {\n            GrammarAST t = (GrammarAST)c;\n            String importedGrammarName = null;\n            if ( t.getType()==ANTLRParser.ASSIGN ) {\n\t\t\t\tt = (GrammarAST)t.getChild(1);\n\t\t\t\timportedGrammarName = t.getText();\n            }\n            else if ( t.getType()==ANTLRParser.ID ) {\n                importedGrammarName = t.getText();\n\t\t\t}\n\t\t\tif ( visited.contains(importedGrammarName) ) { // ignore circular refs\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tGrammar g;\n\t\t\ttry {\n\t\t\t\tg = tool.loadImportedGrammar(this, t);\n\t\t\t}\n\t\t\tcatch (IOException ioe) {\n\t\t\t\ttool.errMgr.grammarError(ErrorType.ERROR_READING_IMPORTED_GRAMMAR,\n\t\t\t\t\t\t\t\t\t\t importedGrammarName,\n\t\t\t\t\t\t\t\t\t\t t.getToken(),\n\t\t\t\t\t\t\t\t\t\t importedGrammarName,\n\t\t\t\t\t\t\t\t\t\t name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// did it come back as error node or missing?\n\t\t\tif ( g == null ) continue;\n\t\t\tg.parent = this;\n\t\t\timportedGrammars.add(g);\n\t\t\tg.loadImportedGrammars(visited); // recursively pursue any imports in this import\n        }\n    }\n\n    public void defineAction(GrammarAST atAST) {\n        if ( atAST.getChildCount()==2 ) {\n            String name = atAST.getChild(0).getText();\n            namedActions.put(name, (ActionAST)atAST.getChild(1));\n        }\n        else {\n\t\t\tString scope = atAST.getChild(0).getText();\n            String gtype = getTypeString();\n            if ( scope.equals(gtype) || (scope.equals(\"parser\")&&gtype.equals(\"combined\")) ) {\n\t\t\t\tString name = atAST.getChild(1).getText();\n\t\t\t\tnamedActions.put(name, (ActionAST)atAST.getChild(2));\n\t\t\t}\n        }\n    }\n\n\t/**\n\t * Define the specified rule in the grammar. This method assigns the rule's\n\t * {@link Rule#index} according to the {@link #ruleNumber} field, and adds\n\t * the {@link Rule} instance to {@link #rules} and {@link #indexToRule}.\n\t *\n\t * @param r The rule to define in the grammar.\n\t * @return {@code true} if the rule was added to the {@link Grammar}\n\t * instance; otherwise, {@code false} if a rule with this name already\n\t * existed in the grammar instance.\n\t */\n\tpublic boolean defineRule(Rule r) {\n\t\tif ( rules.get(r.name)!=null ) {\n\t\t\treturn false;\n\t\t}\n\t\trules.put(r.name, r);\n\t\tr.index = ruleNumber++;\n\t\tindexToRule.add(r);\n\t\treturn true;\n\t}\n\n\t/**\n\t * Undefine the specified rule from this {@link Grammar} instance. The\n\t * instance {@code r} is removed from {@link #rules} and\n\t * {@link #indexToRule}. This method updates the {@link Rule#index} field\n\t * for all rules defined after {@code r}, and decrements {@link #ruleNumber}\n\t * in preparation for adding new rules.\n\t * <p>\n\t * This method does nothing if the current {@link Grammar} does not contain\n\t * the instance {@code r} at index {@code r.index} in {@link #indexToRule}.\n\t * </p>\n\t *\n\t * @param r\n\t * @return {@code true} if the rule was removed from the {@link Grammar}\n\t * instance; otherwise, {@code false} if the specified rule was not defined\n\t * in the grammar.\n\t */\n\tpublic boolean undefineRule(Rule r) {\n\t\tif (r.index < 0 || r.index >= indexToRule.size() || indexToRule.get(r.index) != r) {\n\t\t\treturn false;\n\t\t}\n\n\t\tassert rules.get(r.name) == r;\n\n\t\trules.remove(r.name);\n\t\tindexToRule.remove(r.index);\n\t\tfor (int i = r.index; i < indexToRule.size(); i++) {\n\t\t\tassert indexToRule.get(i).index == i + 1;\n\t\t\tindexToRule.get(i).index--;\n\t\t}\n\n\t\truleNumber--;\n\t\treturn true;\n\t}\n\n//\tpublic int getNumRules() {\n//\t\tint n = rules.size();\n//\t\tList<Grammar> imports = getAllImportedGrammars();\n//\t\tif ( imports!=null ) {\n//\t\t\tfor (Grammar g : imports) n += g.getNumRules();\n//\t\t}\n//\t\treturn n;\n//\t}\n\n    public Rule getRule(String name) {\n\t\tRule r = rules.get(name);\n\t\tif ( r!=null ) return r;\n\t\treturn null;\n\t\t/*\n\t\tList<Grammar> imports = getAllImportedGrammars();\n\t\tif ( imports==null ) return null;\n\t\tfor (Grammar g : imports) {\n\t\t\tr = g.getRule(name); // recursively walk up hierarchy\n\t\t\tif ( r!=null ) return r;\n\t\t}\n\t\treturn null;\n\t\t*/\n\t}\n\n\tpublic ATN getATN() {\n\t\tif ( atn==null ) {\n\t\t\tParserATNFactory factory = new ParserATNFactory(this);\n\t\t\tatn = factory.createATN();\n\t\t}\n\t\treturn atn;\n\t}\n\n\tpublic Rule getRule(int index) { return indexToRule.get(index); }\n\n\tpublic Rule getRule(String grammarName, String ruleName) {\n\t\tif ( grammarName!=null ) { // scope override\n\t\t\tGrammar g = getImportedGrammar(grammarName);\n\t\t\tif ( g ==null ) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn g.rules.get(ruleName);\n\t\t}\n\t\treturn getRule(ruleName);\n\t}\n\n    /** Get list of all imports from all grammars in the delegate subtree of g.\n     *  The grammars are in import tree preorder.  Don't include ourselves\n     *  in list as we're not a delegate of ourselves.\n     */\n\tpublic List<Grammar> getAllImportedGrammars() {\n\t\tif (importedGrammars == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tLinkedHashMap<String, Grammar> delegates = new LinkedHashMap<String, Grammar>();\n\t\tfor (Grammar d : importedGrammars) {\n\t\t\tdelegates.put(d.fileName, d);\n\t\t\tList<Grammar> ds = d.getAllImportedGrammars();\n\t\t\tif (ds != null) {\n\t\t\t\tfor (Grammar imported : ds) {\n\t\t\t\t\tdelegates.put(imported.fileName, imported);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn new ArrayList<Grammar>(delegates.values());\n\t}\n\n    public List<Grammar> getImportedGrammars() { return importedGrammars; }\n\n\tpublic LexerGrammar getImplicitLexer() {\n\t\treturn implicitLexer;\n\t}\n\n\t/** convenience method for Tool.loadGrammar() */\n\tpublic static Grammar load(String fileName) {\n\t\tTool antlr = new Tool();\n\t\treturn antlr.loadGrammar(fileName);\n\t}\n\n\t/** Return list of imported grammars from root down to our parent.\n     *  Order is [root, ..., this.parent].  (us not included).\n     */\n    public List<Grammar> getGrammarAncestors() {\n        Grammar root = getOutermostGrammar();\n        if ( this==root ) return null;\n        List<Grammar> grammars = new ArrayList<Grammar>();\n        // walk backwards to root, collecting grammars\n        Grammar p = this.parent;\n        while ( p!=null ) {\n            grammars.add(0, p); // add to head so in order later\n            p = p.parent;\n        }\n        return grammars;\n    }\n\n    /** Return the grammar that imported us and our parents. Return this\n     *  if we're root.\n     */\n    public Grammar getOutermostGrammar() {\n        if ( parent==null ) return this;\n        return parent.getOutermostGrammar();\n    }\n\n    /** Get the name of the generated recognizer; may or may not be same\n     *  as grammar name.\n     *  Recognizer is TParser and TLexer from T if combined, else\n     *  just use T regardless of grammar type.\n     */\n    public String getRecognizerName() {\n        String suffix = \"\";\n        List<Grammar> grammarsFromRootToMe = getOutermostGrammar().getGrammarAncestors();\n        String qualifiedName = name;\n        if ( grammarsFromRootToMe!=null ) {\n            StringBuilder buf = new StringBuilder();\n            for (Grammar g : grammarsFromRootToMe) {\n                buf.append(g.name);\n                buf.append('_');\n            }\n            buf.append(name);\n            qualifiedName = buf.toString();\n        }\n\n        if ( isCombined() || (isLexer() && implicitLexer!=null) )\n        {\n            suffix = Grammar.getGrammarTypeToFileNameSuffix(getType());\n        }\n        return qualifiedName+suffix;\n    }\n\n\tpublic String getStringLiteralLexerRuleName(String lit) {\n\t\treturn AUTO_GENERATED_TOKEN_NAME_PREFIX + stringLiteralRuleNumber++;\n\t}\n\n    /** Return grammar directly imported by this grammar */\n    public Grammar getImportedGrammar(String name) {\n\t\tfor (Grammar g : importedGrammars) {\n            if ( g.name.equals(name) ) return g;\n        }\n        return null;\n    }\n\n\tpublic int getTokenType(String token) {\n\t\tInteger I;\n\t\tif ( token.charAt(0)=='\\'') {\n\t\t\tI = stringLiteralToTypeMap.get(token);\n\t\t}\n\t\telse { // must be a label like ID\n\t\t\tI = tokenNameToTypeMap.get(token);\n\t\t}\n\t\tint i = (I!=null)? I : Token.INVALID_TYPE;\n\t\t//tool.log(\"grammar\", \"grammar type \"+type+\" \"+tokenName+\"->\"+i);\n\t\treturn i;\n\t}\n\n\tpublic String getTokenName(String literal) {\n\t\tGrammar grammar = this;\n\t\twhile (grammar != null) {\n\t\t\tif (grammar.stringLiteralToTypeMap.containsKey(literal))\n\t\t\t\treturn grammar.getTokenName(grammar.stringLiteralToTypeMap.get(literal));\n\t\t\tgrammar = grammar.parent;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Given a token type, get a meaningful name for it such as the ID\n\t *  or string literal.  If this is a lexer and the ttype is in the\n\t *  char vocabulary, compute an ANTLR-valid (possibly escaped) char literal.\n\t */\n\tpublic String getTokenDisplayName(int ttype) {\n\t\t// inside any target's char range and is lexer grammar?\n\t\tif ( isLexer() &&\n\t\t\t ttype >= Lexer.MIN_CHAR_VALUE && ttype <= Lexer.MAX_CHAR_VALUE )\n\t\t{\n\t\t\treturn CharSupport.getANTLRCharLiteralForChar(ttype);\n\t\t}\n\n\t\tif ( ttype==Token.EOF ) {\n\t\t\treturn \"EOF\";\n\t\t}\n\n\t\tif ( ttype==Token.INVALID_TYPE ) {\n\t\t\treturn INVALID_TOKEN_NAME;\n\t\t}\n\n\t\tif (ttype >= 0 && ttype < typeToStringLiteralList.size() && typeToStringLiteralList.get(ttype) != null) {\n\t\t\treturn typeToStringLiteralList.get(ttype);\n\t\t}\n\n\t\tif (ttype >= 0 && ttype < typeToTokenList.size() && typeToTokenList.get(ttype) != null) {\n\t\t\treturn typeToTokenList.get(ttype);\n\t\t}\n\n\t\treturn String.valueOf(ttype);\n\t}\n\n\t/**\n\t * Gets the name by which a token can be referenced in the generated code.\n\t * For tokens defined in a {@code tokens{}} block or via a lexer rule, this\n\t * is the declared name of the token. For token types generated by the use\n\t * of a string literal within a parser rule of a combined grammar, this is\n\t * the automatically generated token type which includes the\n\t * {@link #AUTO_GENERATED_TOKEN_NAME_PREFIX} prefix. For types which are not\n\t * associated with a defined token, this method returns\n\t * {@link #INVALID_TOKEN_NAME}.\n\t *\n\t * @param ttype The token type.\n\t * @return The name of the token with the specified type.\n\t */\n\n\tpublic String getTokenName(int ttype) {\n\t\t// inside any target's char range and is lexer grammar?\n\t\tif ( isLexer() &&\n\t\t\t ttype >= Lexer.MIN_CHAR_VALUE && ttype <= Lexer.MAX_CHAR_VALUE )\n\t\t{\n\t\t\treturn CharSupport.getANTLRCharLiteralForChar(ttype);\n\t\t}\n\n\t\tif ( ttype==Token.EOF ) {\n\t\t\treturn \"EOF\";\n\t\t}\n\n\t\tif (ttype >= 0 && ttype < typeToTokenList.size() && typeToTokenList.get(ttype) != null) {\n\t\t\treturn typeToTokenList.get(ttype);\n\t\t}\n\n\t\treturn INVALID_TOKEN_NAME;\n\t}\n\n\t/**\n\t * Gets the constant channel value for a user-defined channel.\n\t *\n\t * <p>\n\t * This method only returns channel values for user-defined channels. All\n\t * other channels, including the predefined channels\n\t * {@link Token#DEFAULT_CHANNEL} and {@link Token#HIDDEN_CHANNEL} along with\n\t * any channel defined in code (e.g. in a {@code @members{}} block), are\n\t * ignored.</p>\n\t *\n\t * @param channel The channel name.\n\t * @return The channel value, if {@code channel} is the name of a known\n\t * user-defined token channel; otherwise, -1.\n\t */\n\tpublic int getChannelValue(String channel) {\n\t\tInteger I = channelNameToValueMap.get(channel);\n\t\tint i = (I != null) ? I : -1;\n\t\treturn i;\n\t}\n\n\t/**\n\t * Gets an array of rule names for rules defined or imported by the\n\t * grammar. The array index is the rule index, and the value is the name of\n\t * the rule with the corresponding {@link Rule#index}.\n\t *\n\t * <p>If no rule is defined with an index for an element of the resulting\n\t * array, the value of that element is {@link #INVALID_RULE_NAME}.</p>\n\t *\n\t * @return The names of all rules defined in the grammar.\n\t */\n\tpublic String[] getRuleNames() {\n\t\tString[] result = new String[rules.size()];\n\t\tArrays.fill(result, INVALID_RULE_NAME);\n\t\tfor (Rule rule : rules.values()) {\n\t\t\tresult[rule.index] = rule.name;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Gets an array of token names for tokens defined or imported by the\n\t * grammar. The array index is the token type, and the value is the result\n\t * of {@link #getTokenName} for the corresponding token type.\n\t *\n\t * @see #getTokenName\n\t * @return The token names of all tokens defined in the grammar.\n\t */\n\tpublic String[] getTokenNames() {\n\t\tint numTokens = getMaxTokenType();\n\t\tString[] tokenNames = new String[numTokens+1];\n\t\tfor (int i = 0; i < tokenNames.length; i++) {\n\t\t\ttokenNames[i] = getTokenName(i);\n\t\t}\n\n\t\treturn tokenNames;\n\t}\n\n\t/**\n\t * Gets an array of display names for tokens defined or imported by the\n\t * grammar. The array index is the token type, and the value is the result\n\t * of {@link #getTokenDisplayName} for the corresponding token type.\n\t *\n\t * @see #getTokenDisplayName\n\t * @return The display names of all tokens defined in the grammar.\n\t */\n\tpublic String[] getTokenDisplayNames() {\n\t\tint numTokens = getMaxTokenType();\n\t\tString[] tokenNames = new String[numTokens+1];\n\t\tfor (int i = 0; i < tokenNames.length; i++) {\n\t\t\ttokenNames[i] = getTokenDisplayName(i);\n\t\t}\n\n\t\treturn tokenNames;\n\t}\n\n\t/**\n\t * Gets the literal names assigned to tokens in the grammar.\n\t */\n\n\tpublic String[] getTokenLiteralNames() {\n\t\tint numTokens = getMaxTokenType();\n\t\tString[] literalNames = new String[numTokens+1];\n\t\tfor (int i = 0; i < Math.min(literalNames.length, typeToStringLiteralList.size()); i++) {\n\t\t\tliteralNames[i] = typeToStringLiteralList.get(i);\n\t\t}\n\n\t\tfor (Map.Entry<String, Integer> entry : stringLiteralToTypeMap.entrySet()) {\n\t\t\tint value = entry.getValue();\n\t\t\tif (value >= 0 && value < literalNames.length && literalNames[value] == null) {\n\t\t\t\tliteralNames[value] = entry.getKey();\n\t\t\t}\n\t\t}\n\n\t\treturn literalNames;\n\t}\n\n\t/**\n\t * Gets the symbolic names assigned to tokens in the grammar.\n\t */\n\n\tpublic String[] getTokenSymbolicNames() {\n\t\tint numTokens = getMaxTokenType();\n\t\tString[] symbolicNames = new String[numTokens+1];\n\t\tfor (int i = 0; i < Math.min(symbolicNames.length, typeToTokenList.size()); i++) {\n\t\t\tif (typeToTokenList.get(i) == null || typeToTokenList.get(i).startsWith(AUTO_GENERATED_TOKEN_NAME_PREFIX)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsymbolicNames[i] = typeToTokenList.get(i);\n\t\t}\n\n\t\treturn symbolicNames;\n\t}\n\n\t/**\n\t * Gets a {@link Vocabulary} instance describing the vocabulary used by the\n\t * grammar.\n\t */\n\n\tpublic Vocabulary getVocabulary() {\n\t\treturn new VocabularyImpl(getTokenLiteralNames(), getTokenSymbolicNames());\n\t}\n\n\t/** Given an arbitrarily complex SemanticContext, walk the \"tree\" and get display string.\n\t *  Pull predicates from grammar text.\n\t */\n\tpublic String getSemanticContextDisplayString(SemanticContext semctx) {\n\t\tif ( semctx instanceof SemanticContext.Predicate ) {\n\t\t\treturn getPredicateDisplayString((SemanticContext.Predicate)semctx);\n\t\t}\n\t\tif ( semctx instanceof SemanticContext.AND ) {\n\t\t\tSemanticContext.AND and = (SemanticContext.AND)semctx;\n\t\t\treturn joinPredicateOperands(and, \" and \");\n\t\t}\n\t\tif ( semctx instanceof SemanticContext.OR ) {\n\t\t\tSemanticContext.OR or = (SemanticContext.OR)semctx;\n\t\t\treturn joinPredicateOperands(or, \" or \");\n\t\t}\n\t\treturn semctx.toString();\n\t}\n\n\tpublic String joinPredicateOperands(SemanticContext.Operator op, String separator) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (SemanticContext operand : op.getOperands()) {\n\t\t\tif (buf.length() > 0) {\n\t\t\t\tbuf.append(separator);\n\t\t\t}\n\n\t\t\tbuf.append(getSemanticContextDisplayString(operand));\n\t\t}\n\n\t\treturn buf.toString();\n\t}\n\n\tpublic LinkedHashMap<Integer, PredAST> getIndexToPredicateMap() {\n\t\tLinkedHashMap<Integer, PredAST> indexToPredMap = new LinkedHashMap<Integer, PredAST>();\n\t\tfor (Rule r : rules.values()) {\n\t\t\tfor (ActionAST a : r.actions) {\n\t\t\t\tif (a instanceof PredAST) {\n\t\t\t\t\tPredAST p = (PredAST) a;\n\t\t\t\t\tindexToPredMap.put(sempreds.get(p), p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn indexToPredMap;\n\t}\n\n\tpublic String getPredicateDisplayString(SemanticContext.Predicate pred) {\n\t\tif ( indexToPredMap==null ) {\n\t\t\tindexToPredMap = getIndexToPredicateMap();\n\t\t}\n\t\tActionAST actionAST = indexToPredMap.get(pred.predIndex);\n\t\treturn actionAST.getText();\n\t}\n\n\t/** What is the max char value possible for this grammar's target?  Use\n\t *  unicode max if no target defined.\n\t */\n\tpublic int getMaxCharValue() {\n\t\treturn org.antlr.v4.runtime.Lexer.MAX_CHAR_VALUE;\n//\t\tif ( generator!=null ) {\n//\t\t\treturn generator.getTarget().getMaxCharValue(generator);\n//\t\t}\n//\t\telse {\n//\t\t\treturn Label.MAX_CHAR_VALUE;\n//\t\t}\n\t}\n\n\t/** Return a set of all possible token or char types for this grammar */\n\tpublic IntSet getTokenTypes() {\n\t\tif ( isLexer() ) {\n\t\t\treturn getAllCharValues();\n\t\t}\n\t\treturn IntervalSet.of(Token.MIN_USER_TOKEN_TYPE, getMaxTokenType());\n\t}\n\n\t/** Return min to max char as defined by the target.\n\t *  If no target, use max unicode char value.\n\t */\n\tpublic IntSet getAllCharValues() {\n\t\treturn IntervalSet.of(Lexer.MIN_CHAR_VALUE, getMaxCharValue());\n\t}\n\n\t/** How many token types have been allocated so far? */\n\tpublic int getMaxTokenType() {\n\t\treturn typeToTokenList.size() - 1; // don't count 0 (invalid)\n\t}\n\n\t/** Return a new unique integer in the token type space */\n\tpublic int getNewTokenType() {\n\t\tmaxTokenType++;\n\t\treturn maxTokenType;\n\t}\n\n\t/** Return a new unique integer in the channel value space. */\n\tpublic int getNewChannelNumber() {\n\t\tmaxChannelType++;\n\t\treturn maxChannelType;\n\t}\n\n\tpublic void importTokensFromTokensFile() {\n\t\tString vocab = getOptionString(\"tokenVocab\");\n\t\tif ( vocab!=null ) {\n\t\t\tTokenVocabParser vparser = new TokenVocabParser(this);\n\t\t\tMap<String,Integer> tokens = vparser.load();\n\t\t\ttool.log(\"grammar\", \"tokens=\" + tokens);\n\t\t\tfor (String t : tokens.keySet()) {\n\t\t\t\tif ( t.charAt(0)=='\\'' ) defineStringLiteral(t, tokens.get(t));\n\t\t\t\telse defineTokenName(t, tokens.get(t));\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void importVocab(Grammar importG) {\n\t\tfor (String tokenName: importG.tokenNameToTypeMap.keySet()) {\n\t\t\tdefineTokenName(tokenName, importG.tokenNameToTypeMap.get(tokenName));\n\t\t}\n\t\tfor (String tokenName: importG.stringLiteralToTypeMap.keySet()) {\n\t\t\tdefineStringLiteral(tokenName, importG.stringLiteralToTypeMap.get(tokenName));\n\t\t}\n\t\tfor (Map.Entry<String, Integer> channel : importG.channelNameToValueMap.entrySet()) {\n\t\t\tdefineChannelName(channel.getKey(), channel.getValue());\n\t\t}\n//\t\tthis.tokenNameToTypeMap.putAll( importG.tokenNameToTypeMap );\n//\t\tthis.stringLiteralToTypeMap.putAll( importG.stringLiteralToTypeMap );\n\t\tint max = Math.max(this.typeToTokenList.size(), importG.typeToTokenList.size());\n\t\tUtils.setSize(typeToTokenList, max);\n\t\tfor (int ttype=0; ttype<importG.typeToTokenList.size(); ttype++) {\n\t\t\tmaxTokenType = Math.max(maxTokenType, ttype);\n\t\t\tthis.typeToTokenList.set(ttype, importG.typeToTokenList.get(ttype));\n\t\t}\n\n\t\tmax = Math.max(this.channelValueToNameList.size(), importG.channelValueToNameList.size());\n\t\tUtils.setSize(channelValueToNameList, max);\n\t\tfor (int channelValue = 0; channelValue < importG.channelValueToNameList.size(); channelValue++) {\n\t\t\tmaxChannelType = Math.max(maxChannelType, channelValue);\n\t\t\tthis.channelValueToNameList.set(channelValue, importG.channelValueToNameList.get(channelValue));\n\t\t}\n\t}\n\n\tpublic int defineTokenName(String name) {\n\t\tInteger prev = tokenNameToTypeMap.get(name);\n\t\tif ( prev==null ) return defineTokenName(name, getNewTokenType());\n\t\treturn prev;\n\t}\n\n\tpublic int defineTokenName(String name, int ttype) {\n\t\tInteger prev = tokenNameToTypeMap.get(name);\n\t\tif ( prev!=null ) return prev;\n\t\ttokenNameToTypeMap.put(name, ttype);\n\t\tsetTokenForType(ttype, name);\n\t\tmaxTokenType = Math.max(maxTokenType, ttype);\n\t\treturn ttype;\n\t}\n\n\tpublic int defineStringLiteral(String lit) {\n\t\tif ( stringLiteralToTypeMap.containsKey(lit) ) {\n\t\t\treturn stringLiteralToTypeMap.get(lit);\n\t\t}\n\t\treturn defineStringLiteral(lit, getNewTokenType());\n\n\t}\n\n\tpublic int defineStringLiteral(String lit, int ttype) {\n\t\tif ( !stringLiteralToTypeMap.containsKey(lit) ) {\n\t\t\tstringLiteralToTypeMap.put(lit, ttype);\n\t\t\t// track in reverse index too\n\t\t\tif ( ttype>=typeToStringLiteralList.size() ) {\n\t\t\t\tUtils.setSize(typeToStringLiteralList, ttype+1);\n\t\t\t}\n\t\t\ttypeToStringLiteralList.set(ttype, lit);\n\n\t\t\tsetTokenForType(ttype, lit);\n\t\t\treturn ttype;\n\t\t}\n\t\treturn Token.INVALID_TYPE;\n\t}\n\n\tpublic int defineTokenAlias(String name, String lit) {\n\t\tint ttype = defineTokenName(name);\n\t\tstringLiteralToTypeMap.put(lit, ttype);\n\t\tsetTokenForType(ttype, name);\n\t\treturn ttype;\n\t}\n\n\tpublic void setTokenForType(int ttype, String text) {\n\t\tif (ttype == Token.EOF) {\n\t\t\t// ignore EOF, it will be reported as an error separately\n\t\t\treturn;\n\t\t}\n\n\t\tif ( ttype>=typeToTokenList.size() ) {\n\t\t\tUtils.setSize(typeToTokenList, ttype+1);\n\t\t}\n\t\tString prevToken = typeToTokenList.get(ttype);\n\t\tif ( prevToken==null || prevToken.charAt(0)=='\\'' ) {\n\t\t\t// only record if nothing there before or if thing before was a literal\n\t\t\ttypeToTokenList.set(ttype, text);\n\t\t}\n\t}\n\n\t/**\n\t * Define a token channel with a specified name.\n\t *\n\t * <p>\n\t * If a channel with the specified name already exists, the previously\n\t * assigned channel value is returned.</p>\n\t *\n\t * @param name The channel name.\n\t * @return The constant channel value assigned to the channel.\n\t */\n\tpublic int defineChannelName(String name) {\n\t\tInteger prev = channelNameToValueMap.get(name);\n\t\tif (prev == null) {\n\t\t\treturn defineChannelName(name, getNewChannelNumber());\n\t\t}\n\n\t\treturn prev;\n\t}\n\n\t/**\n\t * Define a token channel with a specified name.\n\t *\n\t * <p>\n\t * If a channel with the specified name already exists, the previously\n\t * assigned channel value is not altered.</p>\n\t *\n\t * @param name The channel name.\n\t * @return The constant channel value assigned to the channel.\n\t */\n\tpublic int defineChannelName(String name, int value) {\n\t\tInteger prev = channelNameToValueMap.get(name);\n\t\tif (prev != null) {\n\t\t\treturn prev;\n\t\t}\n\n\t\tchannelNameToValueMap.put(name, value);\n\t\tsetChannelNameForValue(value, name);\n\t\tmaxChannelType = Math.max(maxChannelType, value);\n\t\treturn value;\n\t}\n\n\t/**\n\t * Sets the channel name associated with a particular channel value.\n\t *\n\t * <p>\n\t * If a name has already been assigned to the channel with constant value\n\t * {@code channelValue}, this method does nothing.</p>\n\t *\n\t * @param channelValue The constant value for the channel.\n\t * @param name The channel name.\n\t */\n\tpublic void setChannelNameForValue(int channelValue, String name) {\n\t\tif (channelValue >= channelValueToNameList.size()) {\n\t\t\tUtils.setSize(channelValueToNameList, channelValue + 1);\n\t\t}\n\n\t\tString prevChannel = channelValueToNameList.get(channelValue);\n\t\tif (prevChannel == null) {\n\t\t\tchannelValueToNameList.set(channelValue, name);\n\t\t}\n\t}\n\n\t// no isolated attr at grammar action level\n\t@Override\n\tpublic Attribute resolveToAttribute(String x, ActionAST node) {\n\t\treturn null;\n\t}\n\n\t// no $x.y makes sense here\n\t@Override\n\tpublic Attribute resolveToAttribute(String x, String y, ActionAST node) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean resolvesToLabel(String x, ActionAST node) { return false; }\n\n\t@Override\n\tpublic boolean resolvesToListLabel(String x, ActionAST node) { return false; }\n\n\t@Override\n\tpublic boolean resolvesToToken(String x, ActionAST node) { return false; }\n\n\t@Override\n\tpublic boolean resolvesToAttributeDict(String x, ActionAST node) {\n\t\treturn false;\n\t}\n\n\t/** Given a grammar type, what should be the default action scope?\n     *  If I say @members in a COMBINED grammar, for example, the\n     *  default scope should be \"parser\".\n     */\n    public String getDefaultActionScope() {\n        switch ( getType() ) {\n            case ANTLRParser.LEXER :\n                return \"lexer\";\n            case ANTLRParser.PARSER :\n            case ANTLRParser.COMBINED :\n                return \"parser\";\n        }\n        return null;\n    }\n\n    public int getType() {\n        if ( ast!=null ) return ast.grammarType;\n        return 0;\n    }\n\n\tpublic org.antlr.runtime.TokenStream getTokenStream() {\n\t\tif ( ast!=null ) return ast.tokenStream;\n\t\treturn null;\n\t}\n\n\tpublic boolean isLexer() { return getType()==ANTLRParser.LEXER; }\n\tpublic boolean isParser() { return getType()==ANTLRParser.PARSER; }\n\tpublic boolean isCombined() { return getType()==ANTLRParser.COMBINED; }\n\n\t/** Is id a valid token name? Does id start with an uppercase letter? */\n\tpublic static boolean isTokenName(String id) {\n\t\treturn Character.isUpperCase(id.charAt(0));\n\t}\n\n    public String getTypeString() {\n        if ( ast==null ) return null;\n        return ANTLRParser.tokenNames[getType()].toLowerCase();\n    }\n\n    public static String getGrammarTypeToFileNameSuffix(int type) {\n        switch ( type ) {\n            case ANTLRParser.LEXER : return \"Lexer\";\n            case ANTLRParser.PARSER : return \"Parser\";\n            // if combined grammar, gen Parser and Lexer will be done later\n            // TODO: we are separate now right?\n            case ANTLRParser.COMBINED : return \"Parser\";\n            default :\n                return \"<invalid>\";\n        }\n\t}\n\n\tpublic String getLanguage() {\n\t\treturn getOptionString(\"language\");\n\t}\n\n\tpublic String getOptionString(String key) { return ast.getOptionString(key); }\n\n\t/** Given ^(TOKEN_REF ^(OPTIONS ^(ELEMENT_OPTIONS (= assoc right))))\n\t *  set option assoc=right in TOKEN_REF.\n\t */\n\tpublic static void setNodeOptions(GrammarAST node, GrammarAST options) {\n\t\tif ( options==null ) return;\n\t\tGrammarASTWithOptions t = (GrammarASTWithOptions)node;\n\t\tif ( t.getChildCount()==0 || options.getChildCount()==0 ) return;\n\t\tfor (Object o : options.getChildren()) {\n\t\t\tGrammarAST c = (GrammarAST)o;\n\t\t\tif ( c.getType()==ANTLRParser.ASSIGN ) {\n\t\t\t\tt.setOption(c.getChild(0).getText(), (GrammarAST)c.getChild(1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tt.setOption(c.getText(), null); // no arg such as ID<VarNodeType>\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Return list of (TOKEN_NAME node, 'literal' node) pairs */\n\tpublic static List<Pair<GrammarAST,GrammarAST>> getStringLiteralAliasesFromLexerRules(GrammarRootAST ast) {\n\t\tString[] patterns = {\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (ALT %lit:STRING_LITERAL)))\",\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (ALT %lit:STRING_LITERAL ACTION)))\",\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (ALT %lit:STRING_LITERAL SEMPRED)))\",\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (LEXER_ALT_ACTION (ALT %lit:STRING_LITERAL) .)))\",\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (LEXER_ALT_ACTION (ALT %lit:STRING_LITERAL) . .)))\",\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (LEXER_ALT_ACTION (ALT %lit:STRING_LITERAL) (LEXER_ACTION_CALL . .))))\",\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (LEXER_ALT_ACTION (ALT %lit:STRING_LITERAL) . (LEXER_ACTION_CALL . .))))\",\n\t\t\t\"(RULE %name:TOKEN_REF (BLOCK (LEXER_ALT_ACTION (ALT %lit:STRING_LITERAL) (LEXER_ACTION_CALL . .) .)))\",\n\t\t\t// TODO: allow doc comment in there\n\t\t};\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(ast.token.getInputStream());\n\t\torg.antlr.runtime.tree.TreeWizard wiz = new org.antlr.runtime.tree.TreeWizard(adaptor,ANTLRParser.tokenNames);\n\t\tList<Pair<GrammarAST,GrammarAST>> lexerRuleToStringLiteral =\n\t\t\tnew ArrayList<Pair<GrammarAST,GrammarAST>>();\n\n\t\tList<GrammarAST> ruleNodes = ast.getNodesWithType(ANTLRParser.RULE);\n\t\tif ( ruleNodes==null || ruleNodes.isEmpty() ) return null;\n\n\t\tfor (GrammarAST r : ruleNodes) {\n\t\t\t//tool.log(\"grammar\", r.toStringTree());\n//\t\t\tSystem.out.println(\"chk: \"+r.toStringTree());\n\t\t\torg.antlr.runtime.tree.Tree name = r.getChild(0);\n\t\t\tif ( name.getType()==ANTLRParser.TOKEN_REF ) {\n\t\t\t\t// check rule against patterns\n\t\t\t\tboolean isLitRule;\n\t\t\t\tfor (String pattern : patterns) {\n\t\t\t\t\tisLitRule =\n\t\t\t\t\t\tdefAlias(r, pattern, wiz, lexerRuleToStringLiteral);\n\t\t\t\t\tif ( isLitRule ) break;\n\t\t\t\t}\n//\t\t\t\tif ( !isLitRule ) System.out.println(\"no pattern matched\");\n\t\t\t}\n\t\t}\n\t\treturn lexerRuleToStringLiteral;\n\t}\n\n\tprotected static boolean defAlias(GrammarAST r, String pattern,\n\t\t\t\t\t\t\t\t\t  org.antlr.runtime.tree.TreeWizard wiz,\n\t\t\t\t\t\t\t\t\t  List<Pair<GrammarAST,GrammarAST>> lexerRuleToStringLiteral)\n\t{\n\t\tHashMap<String, Object> nodes = new HashMap<String, Object>();\n\t\tif ( wiz.parse(r, pattern, nodes) ) {\n\t\t\tGrammarAST litNode = (GrammarAST)nodes.get(\"lit\");\n\t\t\tGrammarAST nameNode = (GrammarAST)nodes.get(\"name\");\n\t\t\tPair<GrammarAST, GrammarAST> pair =\n\t\t\t\tnew Pair<GrammarAST, GrammarAST>(nameNode, litNode);\n\t\t\tlexerRuleToStringLiteral.add(pair);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Set<String> getStringLiterals() {\n\t\tfinal Set<String> strings = new LinkedHashSet<String>();\n\t\tGrammarTreeVisitor collector = new GrammarTreeVisitor() {\n\t\t\t@Override\n\t\t\tpublic void stringRef(TerminalAST ref) {\n\t\t\t\tstrings.add(ref.getText());\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic ErrorManager getErrorManager() { return tool.errMgr; }\n\t\t};\n\t\tcollector.visitGrammar(ast);\n\t\treturn strings;\n\t}\n\n\tpublic void setLookaheadDFA(int decision, DFA lookaheadDFA) {\n\t\tdecisionDFAs.put(decision, lookaheadDFA);\n\t}\n\n\tpublic static Map<Integer, Interval> getStateToGrammarRegionMap(GrammarRootAST ast, IntervalSet grammarTokenTypes) {\n\t\tMap<Integer, Interval> stateToGrammarRegionMap = new HashMap<Integer, Interval>();\n\t\tif ( ast==null ) return stateToGrammarRegionMap;\n\n\t\tList<GrammarAST> nodes = ast.getNodesWithType(grammarTokenTypes);\n\t\tfor (GrammarAST n : nodes) {\n\t\t\tif (n.atnState != null) {\n\t\t\t\tInterval tokenRegion = Interval.of(n.getTokenStartIndex(), n.getTokenStopIndex());\n\t\t\t\torg.antlr.runtime.tree.Tree ruleNode = null;\n\t\t\t\t// RULEs, BLOCKs of transformed recursive rules point to original token interval\n\t\t\t\tswitch ( n.getType() ) {\n\t\t\t\t\tcase ANTLRParser.RULE :\n\t\t\t\t\t\truleNode = n;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase ANTLRParser.BLOCK :\n\t\t\t\t\tcase ANTLRParser.CLOSURE :\n\t\t\t\t\t\truleNode = n.getAncestor(ANTLRParser.RULE);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( ruleNode instanceof RuleAST ) {\n\t\t\t\t\tString ruleName = ((RuleAST) ruleNode).getRuleName();\n\t\t\t\t\tRule r = ast.g.getRule(ruleName);\n\t\t\t\t\tif ( r instanceof LeftRecursiveRule ) {\n\t\t\t\t\t\tRuleAST originalAST = ((LeftRecursiveRule) r).getOriginalAST();\n\t\t\t\t\t\ttokenRegion = Interval.of(originalAST.getTokenStartIndex(), originalAST.getTokenStopIndex());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstateToGrammarRegionMap.put(n.atnState.stateNumber, tokenRegion);\n\t\t\t}\n\t\t}\n\t\treturn stateToGrammarRegionMap;\n\t}\n\n\t/** Given an ATN state number, return the token index range within the grammar from which that ATN state was derived. */\n\tpublic Interval getStateToGrammarRegion(int atnStateNumber) {\n\t\tif ( stateToGrammarRegionMap==null ) {\n\t\t\tstateToGrammarRegionMap = getStateToGrammarRegionMap(ast, null); // map all nodes with non-null atn state ptr\n\t\t}\n\t\tif ( stateToGrammarRegionMap==null ) return Interval.INVALID;\n\n\t\treturn stateToGrammarRegionMap.get(atnStateNumber);\n\t}\n\n\tpublic LexerInterpreter createLexerInterpreter(CharStream input) {\n\t\tif (this.isParser()) {\n\t\t\tthrow new IllegalStateException(\"A lexer interpreter can only be created for a lexer or combined grammar.\");\n\t\t}\n\n\t\tif (this.isCombined()) {\n\t\t\treturn implicitLexer.createLexerInterpreter(input);\n\t\t}\n\n\t\tList<String> allChannels = new ArrayList<String>();\n\t\tallChannels.add(\"DEFAULT_TOKEN_CHANNEL\");\n\t\tallChannels.add(\"HIDDEN\");\n\t\tallChannels.addAll(channelValueToNameList);\n\n\t\t// must run ATN through serializer to set some state flags\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tATN deserializedATN = new ATNDeserializer().deserialize(serialized.toArray());\n\t\treturn new LexerInterpreter(\n\t\t\t\tfileName,\n\t\t\t\tgetVocabulary(),\n\t\t\t\tArrays.asList(getRuleNames()),\n\t\t\t\tallChannels,\n\t\t\t\t((LexerGrammar)this).modes.keySet(),\n\t\t\t\tdeserializedATN,\n\t\t\t\tinput);\n\t}\n\n\t/** @since 4.5.1 */\n\tpublic GrammarParserInterpreter createGrammarParserInterpreter(TokenStream tokenStream) {\n\t\tif (this.isLexer()) {\n\t\t\tthrow new IllegalStateException(\"A parser interpreter can only be created for a parser or combined grammar.\");\n\t\t}\n\t\t// must run ATN through serializer to set some state flags\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tATN deserializedATN = new ATNDeserializer().deserialize(serialized.toArray());\n\n\t\treturn new GrammarParserInterpreter(this, deserializedATN, tokenStream);\n\t}\n\n\tpublic ParserInterpreter createParserInterpreter(TokenStream tokenStream) {\n\t\tif (this.isLexer()) {\n\t\t\tthrow new IllegalStateException(\"A parser interpreter can only be created for a parser or combined grammar.\");\n\t\t}\n\n\t\t// must run ATN through serializer to set some state flags\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tATN deserializedATN = new ATNDeserializer().deserialize(serialized.toArray());\n\n\t\treturn new ParserInterpreter(fileName, getVocabulary(), Arrays.asList(getRuleNames()), deserializedATN, tokenStream);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/GrammarInterpreterRuleContext.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.runtime.InterpreterRuleContext;\nimport org.antlr.v4.runtime.ParserRuleContext;\n\n/** An {@link InterpreterRuleContext} that knows which alternative\n *  for a rule was matched.\n *\n *  @see GrammarParserInterpreter\n *  @since 4.5.1\n */\npublic class GrammarInterpreterRuleContext extends InterpreterRuleContext {\n\tprotected int outerAltNum = 1;\n\n\tpublic GrammarInterpreterRuleContext(ParserRuleContext parent, int invokingStateNumber, int ruleIndex) {\n\t\tsuper(parent, invokingStateNumber, ruleIndex);\n\t}\n\n\t/** The predicted outermost alternative for the rule associated\n\t *  with this context object.  If this node left recursive, the true original\n\t *  outermost alternative is returned.\n\t */\n\tpublic int getOuterAltNum() { return outerAltNum; }\n\n\tpublic void setOuterAltNum(int outerAltNum) {\n\t\tthis.outerAltNum = outerAltNum;\n\t}\n\n\t@Override\n\tpublic int getAltNumber() {\n\t\t// override here and called old functionality; makes it backward compatible vs changing names\n\t\treturn getOuterAltNum();\n\t}\n\n\t@Override\n\tpublic void setAltNumber(int altNumber) {\n\t\tsetOuterAltNum(altNumber);\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/GrammarParserInterpreter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.runtime.BailErrorStrategy;\nimport org.antlr.v4.runtime.DefaultErrorStrategy;\nimport org.antlr.v4.runtime.InputMismatchException;\nimport org.antlr.v4.runtime.InterpreterRuleContext;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.RecognitionException;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.atn.RuleStartState;\nimport org.antlr.v4.runtime.atn.StarLoopEntryState;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.lang.reflect.Constructor;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.BitSet;\nimport java.util.Collection;\nimport java.util.List;\n\n/** A heavier weight {@link ParserInterpreter} that creates parse trees\n *  that track alternative numbers for subtree roots.\n *\n * @since 4.5.1\n *\n */\npublic class GrammarParserInterpreter extends ParserInterpreter {\n\t/** The grammar associated with this interpreter. Unlike the\n\t *  {@link ParserInterpreter} from the standard distribution,\n\t *  this can reference Grammar, which is in the tools area not\n\t *  purely runtime.\n\t */\n\tprotected final Grammar g;\n\n\tprotected BitSet decisionStatesThatSetOuterAltNumInContext;\n\n\t/** Cache {@link LeftRecursiveRule#getPrimaryAlts()} and\n\t *  {@link LeftRecursiveRule#getRecursiveOpAlts()} for states in\n\t *  {@link #decisionStatesThatSetOuterAltNumInContext}. It only\n\t *  caches decisions in left-recursive rules.\n\t */\n\tprotected int[][] stateToAltsMap;\n\n\tpublic GrammarParserInterpreter(Grammar g,\n\t\t\t\t\t\t\t\t\tString grammarFileName,\n\t\t\t\t\t\t\t\t\tVocabulary vocabulary,\n\t\t\t\t\t\t\t\t\tCollection<String> ruleNames,\n\t\t\t\t\t\t\t\t\tATN atn,\n\t\t\t\t\t\t\t\t\tTokenStream input) {\n\t\tsuper(grammarFileName, vocabulary, ruleNames, atn, input);\n\t\tthis.g = g;\n\t}\n\n\tpublic GrammarParserInterpreter(Grammar g, ATN atn, TokenStream input) {\n\t\tsuper(g.fileName, g.getVocabulary(),\n\t\t\t  Arrays.asList(g.getRuleNames()),\n\t\t\t  atn, // must run ATN through serializer to set some state flags\n\t\t\t  input);\n\t\tthis.g = g;\n\t\tdecisionStatesThatSetOuterAltNumInContext = findOuterMostDecisionStates();\n\t\tstateToAltsMap = new int[g.atn.states.size()][];\n\t}\n\n\t@Override\n\tprotected InterpreterRuleContext createInterpreterRuleContext(ParserRuleContext parent,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int invokingStateNumber,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int ruleIndex)\n\t{\n\t\treturn new GrammarInterpreterRuleContext(parent, invokingStateNumber, ruleIndex);\n\t}\n\n\t@Override\n\tpublic void reset() {\n\t\tsuper.reset();\n\t\toverrideDecisionRoot = null;\n\t}\n\n\t/** identify the ATN states where we need to set the outer alt number.\n\t *  For regular rules, that's the block at the target to rule start state.\n\t *  For left-recursive rules, we track the primary block, which looks just\n\t *  like a regular rule's outer block, and the star loop block (always\n\t *  there even if 1 alt).\n\t */\n\tpublic BitSet findOuterMostDecisionStates() {\n\t\tBitSet track = new BitSet(atn.states.size());\n\t\tint numberOfDecisions = atn.getNumberOfDecisions();\n\t\tfor (int i = 0; i < numberOfDecisions; i++) {\n\t\t\tDecisionState decisionState = atn.getDecisionState(i);\n\t\t\tRuleStartState startState = atn.ruleToStartState[decisionState.ruleIndex];\n\t\t\t// Look for StarLoopEntryState that is in any left recursive rule\n\t\t\tif ( decisionState instanceof StarLoopEntryState) {\n\t\t\t\tStarLoopEntryState loopEntry = (StarLoopEntryState)decisionState;\n\t\t\t\tif ( loopEntry.isPrecedenceDecision ) {\n\t\t\t\t\t// Recursive alts always result in a (...)* in the transformed\n\t\t\t\t\t// left recursive rule and that always has a BasicBlockStartState\n\t\t\t\t\t// even if just 1 recursive alt exists.\n\t\t\t\t\tATNState blockStart = loopEntry.transition(0).target;\n\t\t\t\t\t// track the StarBlockStartState associated with the recursive alternatives\n\t\t\t\t\ttrack.set(blockStart.stateNumber);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ( startState.transition(0).target == decisionState ) {\n\t\t\t\t// always track outermost block for any rule if it exists\n\t\t\t\ttrack.set(decisionState.stateNumber);\n\t\t\t}\n\t\t}\n\t\treturn track;\n\t}\n\n\t/** Override this method so that we can record which alternative\n\t *  was taken at each decision point. For non-left recursive rules,\n\t *  it's simple. Set decisionStatesThatSetOuterAltNumInContext\n\t *  indicates which decision states should set the outer alternative number.\n\t *\n\t *  <p>Left recursive rules are much more complicated to deal with:\n\t *  there is typically a decision for the primary alternatives and a\n\t *  decision to choose between the recursive operator alternatives.\n\t *  For example, the following left recursive rule has two primary and 2\n\t *  recursive alternatives.</p>\n\t *\n\t\t e : e '*' e\n\t\t   | '-' INT\n\t\t   | e '+' e\n\t\t   | ID\n\t\t   ;\n\n\t *  <p>ANTLR rewrites that rule to be</p>\n\n\t\t e[int precedence]\n\t\t\t : ('-' INT | ID)\n\t\t\t ( {...}? '*' e[5]\n\t\t\t | {...}? '+' e[3]\n\t\t\t )*\n\t\t\t;\n\n\t *\n\t *  <p>So, there are two decisions associated with picking the outermost alt.\n\t *  This complicates our tracking significantly. The outermost alternative number\n\t *  is a function of the decision (ATN state) within a left recursive rule and the\n\t *  predicted alternative coming back from adaptivePredict().\n\t *\n\t *  We use stateToAltsMap as a cache to avoid expensive calls to\n\t *  getRecursiveOpAlts().\n\t */\n\t@Override\n\tprotected int visitDecisionState(DecisionState p) {\n\t\tint predictedAlt = super.visitDecisionState(p);\n\t\tif( p.getNumberOfTransitions() > 1) {\n//\t\t\tSystem.out.println(\"decision \"+p.decision+\": \"+predictedAlt);\n\t\t\tif( p.decision == this.overrideDecision &&\n\t\t\t\tthis._input.index() == this.overrideDecisionInputIndex )\n\t\t\t{\n\t\t\t\toverrideDecisionRoot = (GrammarInterpreterRuleContext)getContext();\n\t\t\t}\n\t\t}\n\n\t\tGrammarInterpreterRuleContext ctx = (GrammarInterpreterRuleContext)_ctx;\n\t\tif ( decisionStatesThatSetOuterAltNumInContext.get(p.stateNumber) ) {\n\t\t\tctx.outerAltNum = predictedAlt;\n\t\t\tRule r = g.getRule(p.ruleIndex);\n\t\t\tif ( atn.ruleToStartState[r.index].isLeftRecursiveRule ) {\n\t\t\t\tint[] alts = stateToAltsMap[p.stateNumber];\n\t\t\t\tLeftRecursiveRule lr = (LeftRecursiveRule) g.getRule(p.ruleIndex);\n\t\t\t\tif (p.getStateType() == ATNState.BLOCK_START) {\n\t\t\t\t\tif ( alts==null ) {\n\t\t\t\t\t\talts = lr.getPrimaryAlts();\n\t\t\t\t\t\tstateToAltsMap[p.stateNumber] = alts; // cache it\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( p.getStateType() == ATNState.STAR_BLOCK_START ) {\n\t\t\t\t\tif ( alts==null ) {\n\t\t\t\t\t\talts = lr.getRecursiveOpAlts();\n\t\t\t\t\t\tstateToAltsMap[p.stateNumber] = alts; // cache it\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tctx.outerAltNum = alts[predictedAlt];\n\t\t\t}\n\t\t}\n\n\t\treturn predictedAlt;\n\t}\n\n\t/** Given an ambiguous parse information, return the list of ambiguous parse trees.\n\t *  An ambiguity occurs when a specific token sequence can be recognized\n\t *  in more than one way by the grammar. These ambiguities are detected only\n\t *  at decision points.\n\t *\n\t *  The list of trees includes the actual interpretation (that for\n\t *  the minimum alternative number) and all ambiguous alternatives.\n\t *  The actual interpretation is always first.\n\t *\n\t *  This method reuses the same physical input token stream used to\n\t *  detect the ambiguity by the original parser in the first place.\n\t *  This method resets/seeks within but does not alter originalParser.\n\t *\n\t *  The trees are rooted at the node whose start..stop token indices\n\t *  include the start and stop indices of this ambiguity event. That is,\n\t *  the trees returned will always include the complete ambiguous subphrase\n\t *  identified by the ambiguity event.  The subtrees returned will\n\t *  also always contain the node associated with the overridden decision.\n\t *\n\t *  Be aware that this method does NOT notify error or parse listeners as\n\t *  it would trigger duplicate or otherwise unwanted events.\n\t *\n\t *  This uses a temporary ParserATNSimulator and a ParserInterpreter\n\t *  so we don't mess up any statistics, event lists, etc...\n\t *  The parse tree constructed while identifying/making ambiguityInfo is\n\t *  not affected by this method as it creates a new parser interp to\n\t *  get the ambiguous interpretations.\n\t *\n\t *  Nodes in the returned ambig trees are independent of the original parse\n\t *  tree (constructed while identifying/creating ambiguityInfo).\n\t *\n\t *  @since 4.5.1\n\t *\n\t *  @param g              From which grammar should we drive alternative\n\t *                        numbers and alternative labels.\n\t *\n\t *  @param originalParser The parser used to create ambiguityInfo; it\n\t *                        is not modified by this routine and can be either\n\t *                        a generated or interpreted parser. It's token\n\t *                        stream *is* reset/seek()'d.\n\t *  @param tokens\t\t  A stream of tokens to use with the temporary parser.\n\t *                        This will often be just the token stream within the\n\t *                        original parser but here it is for flexibility.\n\t *\n\t *  @param decision       Which decision to try different alternatives for.\n\t *\n\t *  @param alts           The set of alternatives to try while re-parsing.\n\t *\n\t *  @param startIndex\t  The index of the first token of the ambiguous\n\t *                        input or other input of interest.\n\t *\n\t *  @param stopIndex      The index of the last token of the ambiguous input.\n\t *                        The start and stop indexes are used primarily to\n\t *                        identify how much of the resulting parse tree\n\t *                        to return.\n\t *\n\t *  @param startRuleIndex The start rule for the entire grammar, not\n\t *                        the ambiguous decision. We re-parse the entire input\n\t *                        and so we need the original start rule.\n\t *\n\t *  @return               The list of all possible interpretations of\n\t *                        the input for the decision in ambiguityInfo.\n\t *                        The actual interpretation chosen by the parser\n\t *                        is always given first because this method\n\t *                        retests the input in alternative order and\n\t *                        ANTLR always resolves ambiguities by choosing\n\t *                        the first alternative that matches the input.\n\t *                        The subtree returned\n\t *\n\t *  @throws RecognitionException Throws upon syntax error while matching\n\t *                               ambig input.\n\t */\n\tpublic static List<ParserRuleContext> getAllPossibleParseTrees(Grammar g,\n\t                                                               Parser originalParser,\n\t                                                               TokenStream tokens,\n\t                                                               int decision,\n\t                                                               BitSet alts,\n\t                                                               int startIndex,\n\t                                                               int stopIndex,\n\t                                                               int startRuleIndex)\n\t\tthrows RecognitionException {\n\t\tList<ParserRuleContext> trees = new ArrayList<ParserRuleContext>();\n\t\t// Create a new parser interpreter to parse the ambiguous subphrase\n\t\tParserInterpreter parser = deriveTempParserInterpreter(g, originalParser, tokens);\n\n\t\tif ( stopIndex>=(tokens.size()-1) ) { // if we are pointing at EOF token\n\t\t\t// EOF is not in tree, so must be 1 less than last non-EOF token\n\t\t\tstopIndex = tokens.size()-2;\n\t\t}\n\n\t\t// get ambig trees\n\t\tint alt = alts.nextSetBit(0);\n\t\twhile ( alt>=0 ) {\n\t\t\t// re-parse entire input for all ambiguous alternatives\n\t\t\t// (don't have to do first as it's been parsed, but do again for simplicity\n\t\t\t//  using this temp parser.)\n\t\t\tparser.reset();\n\t\t\tparser.addDecisionOverride(decision, startIndex, alt);\n\t\t\tParserRuleContext t = parser.parse(startRuleIndex);\n\t\t\tGrammarInterpreterRuleContext ambigSubTree =\n\t\t\t\t(GrammarInterpreterRuleContext) Trees.getRootOfSubtreeEnclosingRegion(t, startIndex, stopIndex);\n\t\t\t// Use higher of overridden decision tree or tree enclosing all tokens\n\t\t\tif ( Trees.isAncestorOf(parser.getOverrideDecisionRoot(), ambigSubTree) ) {\n\t\t\t\tambigSubTree = (GrammarInterpreterRuleContext) parser.getOverrideDecisionRoot();\n\t\t\t}\n\t\t\ttrees.add(ambigSubTree);\n\t\t\talt = alts.nextSetBit(alt+1);\n\t\t}\n\n\t\treturn trees;\n\t}\n\n\t/** Return a list of parse trees, one for each alternative in a decision\n\t *  given the same input.\n\t *\n\t *  Very similar to {@link #getAllPossibleParseTrees} except\n\t *  that it re-parses the input for every alternative in a decision,\n\t *  not just the ambiguous ones (there is no alts parameter here).\n\t *  This method also tries to reduce the size of the parse trees\n\t *  by stripping away children of the tree that are completely out of range\n\t *  of startIndex..stopIndex. Also, because errors are expected, we\n\t *  use a specialized error handler that more or less bails out\n\t *  but that also consumes the first erroneous token at least. This\n\t *  ensures that an error node will be in the parse tree for display.\n\t *\n\t *  NOTES:\n    // we must parse the entire input now with decision overrides\n\t// we cannot parse a subset because it could be that a decision\n\t// above our decision of interest needs to read way past\n\t// lookaheadInfo.stopIndex. It seems like there is no escaping\n\t// the use of a full and complete token stream if we are\n\t// resetting to token index 0 and re-parsing from the start symbol.\n\t// It's not easy to restart parsing somewhere in the middle like a\n\t// continuation because our call stack does not match the\n\t// tree stack because of left recursive rule rewriting. grrrr!\n\t *\n\t * @since 4.5.1\n\t */\n\tpublic static List<ParserRuleContext> getLookaheadParseTrees(Grammar g,\n\t                                                             ParserInterpreter originalParser,\n\t                                                             TokenStream tokens,\n\t                                                             int startRuleIndex,\n\t                                                             int decision,\n\t                                                             int startIndex,\n\t                                                             int stopIndex) {\n\t\tList<ParserRuleContext> trees = new ArrayList<ParserRuleContext>();\n\t\t// Create a new parser interpreter to parse the ambiguous subphrase\n\t\tParserInterpreter parser = deriveTempParserInterpreter(g, originalParser, tokens);\n\n\t\tDecisionState decisionState = originalParser.getATN().decisionToState.get(decision);\n\n\t\tfor (int alt = 1; alt<=decisionState.getTransitions().length; alt++) {\n\t\t\t// re-parse entire input for all ambiguous alternatives\n\t\t\t// (don't have to do first as it's been parsed, but do again for simplicity\n\t\t\t//  using this temp parser.)\n\t\t\tGrammarParserInterpreter.BailButConsumeErrorStrategy errorHandler =\n\t\t\t\tnew GrammarParserInterpreter.BailButConsumeErrorStrategy();\n\t\t\tparser.setErrorHandler(errorHandler);\n\t\t\tparser.reset();\n\t\t\tparser.addDecisionOverride(decision, startIndex, alt);\n\t\t\tParserRuleContext tt = parser.parse(startRuleIndex);\n\t\t\tint stopTreeAt = stopIndex;\n\t\t\tif ( errorHandler.firstErrorTokenIndex>=0 ) {\n\t\t\t\tstopTreeAt = errorHandler.firstErrorTokenIndex; // cut off rest at first error\n\t\t\t}\n\t\t\tInterval overallRange = tt.getSourceInterval();\n\t\t\tif ( stopTreeAt>overallRange.b ) {\n\t\t\t\t// If we try to look beyond range of tree, stopTreeAt must be EOF\n\t\t\t\t// for which there is no EOF ref in grammar. That means tree\n\t\t\t\t// will not have node for stopTreeAt; limit to overallRange.b\n\t\t\t\tstopTreeAt = overallRange.b;\n\t\t\t}\n\t\t\tParserRuleContext subtree =\n\t\t\t\tTrees.getRootOfSubtreeEnclosingRegion(tt,\n\t\t\t\t                                      startIndex,\n\t\t\t\t                                      stopTreeAt);\n\t\t\t// Use higher of overridden decision tree or tree enclosing all tokens\n\t\t\tif ( Trees.isAncestorOf(parser.getOverrideDecisionRoot(), subtree) ) {\n\t\t\t\tsubtree = parser.getOverrideDecisionRoot();\n\t\t\t}\n\t\t\tTrees.stripChildrenOutOfRange(subtree, parser.getOverrideDecisionRoot(), startIndex, stopTreeAt);\n\t\t\ttrees.add(subtree);\n\t\t}\n\n\t\treturn trees;\n\t}\n\n\t/** Derive a new parser from an old one that has knowledge of the grammar.\n\t *  The Grammar object is used to correctly compute outer alternative\n\t *  numbers for parse tree nodes. A parser of the same type is created\n\t *  for subclasses of {@link ParserInterpreter}.\n\t */\n\tpublic static ParserInterpreter deriveTempParserInterpreter(Grammar g, Parser originalParser, TokenStream tokens) {\n\t\tParserInterpreter parser;\n\t\tif (originalParser instanceof ParserInterpreter) {\n\t\t\tClass<? extends ParserInterpreter> c = originalParser.getClass().asSubclass(ParserInterpreter.class);\n\t\t\ttry {\n\t\t\t\tConstructor<? extends ParserInterpreter> ctor = c.getConstructor(Grammar.class, ATN.class, TokenStream.class);\n\t\t\t\tparser = ctor.newInstance(g, originalParser.getATN(), originalParser.getTokenStream());\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tthrow new IllegalArgumentException(\"can't create parser to match incoming \"+originalParser.getClass().getSimpleName(), e);\n\t\t\t}\n\t\t}\n\t\telse { // must've been a generated parser\n//\t\t\tIntegerList serialized = ATNSerializer.getSerialized(originalParser.getATN(), g.getLanguage());\n//\t\t\tATN deserialized = new ATNDeserializer().deserialize(serialized.toArray());\n\t\t\tparser = new ParserInterpreter(originalParser.getGrammarFileName(),\n\t\t\t\t\t\t\t\t\t\t   originalParser.getVocabulary(),\n\t\t\t\t\t\t\t\t\t\t   Arrays.asList(originalParser.getRuleNames()),\n\t\t\t\t\t                       originalParser.getATN(),\n\t\t\t\t\t\t\t\t\t\t   tokens);\n\t\t}\n\n\t\tparser.setInputStream(tokens);\n\n\t\t// Make sure that we don't get any error messages from using this temporary parser\n\t\tparser.setErrorHandler(new BailErrorStrategy());\n\t\tparser.removeErrorListeners();\n\t\tparser.removeParseListeners();\n\t\tparser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);\n\t\treturn parser;\n\t}\n\n\t/** We want to stop and track the first error but we cannot bail out like\n\t *  {@link BailErrorStrategy} as consume() constructs trees. We make sure\n\t *  to create an error node during recovery with this strategy. We\n\t *  consume() 1 token during the \"bail out of rule\" mechanism in recover()\n\t *  and let it fall out of the rule to finish constructing trees. For\n\t *  recovery in line, we throw InputMismatchException to engage recover().\n\t */\n\tpublic static class BailButConsumeErrorStrategy extends DefaultErrorStrategy {\n\t\tpublic int firstErrorTokenIndex = -1;\n\t\t@Override\n\t\tpublic void recover(Parser recognizer, RecognitionException e) {\n\t\t\tint errIndex = recognizer.getInputStream().index();\n\t\t\tif ( firstErrorTokenIndex == -1 ) {\n\t\t\t\tfirstErrorTokenIndex = errIndex; // latch\n\t\t\t}\n//\t\t\tSystem.err.println(\"recover: error at \" + errIndex);\n\t\t\tTokenStream input = recognizer.getInputStream();\n\t\t\tif ( input.index()<input.size()-1 ) { // don't consume() eof\n\t\t\t\trecognizer.consume(); // just kill this bad token and let it continue.\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic Token recoverInline(Parser recognizer) throws RecognitionException {\n\t\t\tint errIndex = recognizer.getInputStream().index();\n\t\t\tif ( firstErrorTokenIndex == -1 ) {\n\t\t\t\tfirstErrorTokenIndex = errIndex; // latch\n\t\t\t}\n//\t\t\tSystem.err.println(\"recoverInline: error at \" + errIndex);\n\t\t\tInputMismatchException e = new InputMismatchException(recognizer);\n//\t\t\tTokenStream input = recognizer.getInputStream(); // seek EOF\n//\t\t\tinput.seek(input.size() - 1);\n\t\t\tthrow e;\n\t\t}\n\n\t\t@Override\n\t\tpublic void sync(Parser recognizer) { } // don't consume anything; let it fail later\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/GrammarSemanticsMessage.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.Token;\n\n/** A problem with the symbols and/or meaning of a grammar such as rule\n *  redefinition. Any msg where we can point to a location in the grammar.\n */\npublic class GrammarSemanticsMessage extends ANTLRMessage {\n    public GrammarSemanticsMessage(ErrorType etype,\n                                   String fileName,\n                                   Token offendingToken,\n                                   Object... args)\n    {\n        super(etype,offendingToken,args);\n        this.fileName = fileName;\n\t\tif ( offendingToken!=null ) {\n            line = offendingToken.getLine();\n            charPosition = offendingToken.getCharPositionInLine();\n        }\n    }\n}\n\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/GrammarSyntaxMessage.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.runtime.Token;\n\n/** A problem with the syntax of your antlr grammar such as\n *  \"The '{' came as a complete surprise to me at this point in your program\"\n */\npublic class GrammarSyntaxMessage extends ANTLRMessage {\n\tpublic GrammarSyntaxMessage(ErrorType etype,\n\t\t\t\t\t\t\t\tString fileName,\n\t\t\t\t\t\t\t\tToken offendingToken,\n\t\t\t\t\t\t\t\tRecognitionException antlrException,\n\t\t\t\t\t\t\t\tObject... args)\n\t{\n\t\tsuper(etype, antlrException, offendingToken, args);\n\t\tthis.fileName = fileName;\n\t\tthis.offendingToken = offendingToken;\n\t\tif ( offendingToken!=null ) {\n\t\t\tline = offendingToken.getLine();\n\t\t\tcharPosition = offendingToken.getCharPositionInLine();\n\t\t}\n\t}\n\n    @SuppressWarnings({\"ThrowableResultOfMethodCallIgnored\"})\n    @Override\n    public RecognitionException getCause() {\n        return (RecognitionException)super.getCause();\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/GrammarTransformPipeline.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.runtime.tree.CommonTree;\nimport org.antlr.runtime.tree.CommonTreeNodeStream;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.runtime.tree.TreeVisitor;\nimport org.antlr.runtime.tree.TreeVisitorAction;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.analysis.LeftRecursiveRuleTransformer;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.BlockSetTransformer;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.parse.GrammarToken;\nimport org.antlr.v4.runtime.misc.DoubleKeyMap;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.BlockAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarASTWithOptions;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.antlr.v4.tool.ast.TerminalAST;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\n/** Handle left-recursion and block-set transforms */\npublic class GrammarTransformPipeline {\n\tpublic Grammar g;\n\tpublic Tool tool;\n\n\tpublic GrammarTransformPipeline(Grammar g, Tool tool) {\n\t\tthis.g = g;\n\t\tthis.tool = tool;\n\t}\n\n\tpublic void process() {\n\t\tGrammarRootAST root = g.ast;\n\t\tif ( root==null ) return;\n        tool.log(\"grammar\", \"before: \"+root.toStringTree());\n\n        integrateImportedGrammars(g);\n\t\treduceBlocksToSets(root);\n        expandParameterizedLoops(root);\n\n        tool.log(\"grammar\", \"after: \"+root.toStringTree());\n\t}\n\n\tpublic void reduceBlocksToSets(GrammarAST root) {\n\t\tCommonTreeNodeStream nodes = new CommonTreeNodeStream(new GrammarASTAdaptor(), root);\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor();\n\t\tBlockSetTransformer transformer = new BlockSetTransformer(nodes, g);\n\t\ttransformer.setTreeAdaptor(adaptor);\n\t\ttransformer.downup(root);\n\t}\n\n    /** Find and replace\n     *      ID*[','] with ID (',' ID)*\n     *      ID+[','] with ID (',' ID)+\n     *      (x {action} y)+[','] with x {action} y (',' x {action} y)+\n     *\n     *  Parameter must be a token.\n     *  todo: do we want?\n     */\n    public void expandParameterizedLoops(GrammarAST root) {\n        TreeVisitor v = new TreeVisitor(new GrammarASTAdaptor());\n        v.visit(root, new TreeVisitorAction() {\n            @Override\n            public Object pre(Object t) {\n                if ( ((GrammarAST)t).getType() == 3 ) {\n                    return expandParameterizedLoop((GrammarAST)t);\n                }\n                return t;\n            }\n            @Override\n            public Object post(Object t) { return t; }\n        });\n    }\n\n    public GrammarAST expandParameterizedLoop(GrammarAST t) {\n        // todo: update grammar, alter AST\n        return t;\n    }\n\n    /** Utility visitor that sets grammar ptr in each node */\n\tpublic static void setGrammarPtr(final Grammar g, GrammarAST tree) {\n\t\tif ( tree==null ) return;\n\t\t// ensure each node has pointer to surrounding grammar\n\t\tTreeVisitor v = new TreeVisitor(new GrammarASTAdaptor());\n\t\tv.visit(tree, new TreeVisitorAction() {\n\t\t\t@Override\n\t\t\tpublic Object pre(Object t) { ((GrammarAST)t).g = g; return t; }\n\t\t\t@Override\n\t\t\tpublic Object post(Object t) { return t; }\n\t\t});\n\t}\n\n\tpublic static void augmentTokensWithOriginalPosition(final Grammar g, GrammarAST tree) {\n\t\tif ( tree==null ) return;\n\n\t\tList<GrammarAST> optionsSubTrees = tree.getNodesWithType(ANTLRParser.ELEMENT_OPTIONS);\n\t\tfor (int i = 0; i < optionsSubTrees.size(); i++) {\n\t\t\tGrammarAST t = optionsSubTrees.get(i);\n\t\t\tCommonTree elWithOpt = t.parent;\n\t\t\tif ( elWithOpt instanceof GrammarASTWithOptions ) {\n\t\t\t\tMap<String, GrammarAST> options = ((GrammarASTWithOptions) elWithOpt).getOptions();\n\t\t\t\tif ( options.containsKey(LeftRecursiveRuleTransformer.TOKENINDEX_OPTION_NAME) ) {\n\t\t\t\t\tGrammarToken newTok = new GrammarToken(g, elWithOpt.getToken());\n\t\t\t\t\tnewTok.originalTokenIndex = Integer.valueOf(options.get(LeftRecursiveRuleTransformer.TOKENINDEX_OPTION_NAME).getText());\n\t\t\t\t\telWithOpt.token = newTok;\n\n\t\t\t\t\tGrammarAST originalNode = g.ast.getNodeWithTokenIndex(newTok.getTokenIndex());\n\t\t\t\t\tif (originalNode != null) {\n\t\t\t\t\t\t// update the AST node start/stop index to match the values\n\t\t\t\t\t\t// of the corresponding node in the original parse tree.\n\t\t\t\t\t\telWithOpt.setTokenStartIndex(originalNode.getTokenStartIndex());\n\t\t\t\t\t\telWithOpt.setTokenStopIndex(originalNode.getTokenStopIndex());\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// the original AST node could not be located by index;\n\t\t\t\t\t\t// make sure to assign valid values for the start/stop\n\t\t\t\t\t\t// index so toTokenString will not throw exceptions.\n\t\t\t\t\t\telWithOpt.setTokenStartIndex(newTok.getTokenIndex());\n\t\t\t\t\t\telWithOpt.setTokenStopIndex(newTok.getTokenIndex());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Merge all the rules, token definitions, and named actions from\n\t\timported grammars into the root grammar tree.  Perform:\n\n\t \t(tokens { X (= Y 'y')) + (tokens { Z )\t-&gt;\t(tokens { X (= Y 'y') Z)\n\n\t \t(@ members {foo}) + (@ members {bar})\t-&gt;\t(@ members {foobar})\n\n\t \t(RULES (RULE x y)) + (RULES (RULE z))\t-&gt;\t(RULES (RULE x y z))\n\n\t \tRules in root prevent same rule from being appended to RULES node.\n\n\t \tThe goal is a complete combined grammar so we can ignore subordinate\n\t \tgrammars.\n\t */\n\tpublic void integrateImportedGrammars(Grammar rootGrammar) {\n\t\tList<Grammar> imports = rootGrammar.getAllImportedGrammars();\n\t\tif ( imports==null ) return;\n\n\t\tGrammarAST root = rootGrammar.ast;\n\t\tGrammarAST id = (GrammarAST) root.getChild(0);\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(id.token.getInputStream());\n\n\t\tGrammarAST channelsRoot = (GrammarAST)root.getFirstChildWithType(ANTLRParser.CHANNELS);\n\t \tGrammarAST tokensRoot = (GrammarAST)root.getFirstChildWithType(ANTLRParser.TOKENS_SPEC);\n\n\t\tList<GrammarAST> actionRoots = root.getNodesWithType(ANTLRParser.AT);\n\n\t\t// Compute list of rules in root grammar and ensure we have a RULES node\n\t\tGrammarAST RULES = (GrammarAST)root.getFirstChildWithType(ANTLRParser.RULES);\n\t\tSet<String> rootRuleNames = new HashSet<String>();\n\t\t// make list of rules we have in root grammar\n\t\tList<GrammarAST> rootRules = RULES.getNodesWithType(ANTLRParser.RULE);\n\t\tfor (GrammarAST r : rootRules) rootRuleNames.add(r.getChild(0).getText());\n\n\t\t// make list of modes we have in root grammar\n\t\tList<GrammarAST> rootModes = root.getNodesWithType(ANTLRParser.MODE);\n\t\tSet<String> rootModeNames = new HashSet<String>();\n\t\tfor (GrammarAST m : rootModes) rootModeNames.add(m.getChild(0).getText());\n\t\tList<GrammarAST> addedModes = new ArrayList<GrammarAST>();\n\n\t\tfor (Grammar imp : imports) {\n\t\t\t// COPY CHANNELS\n\t\t\tGrammarAST imp_channelRoot = (GrammarAST)imp.ast.getFirstChildWithType(ANTLRParser.CHANNELS);\n\t\t\tif ( imp_channelRoot != null) {\n\t\t\t\trootGrammar.tool.log(\"grammar\", \"imported channels: \"+imp_channelRoot.getChildren());\n\t\t\t\tif (channelsRoot==null) {\n\t\t\t\t\tchannelsRoot = imp_channelRoot.dupTree();\n\t\t\t\t\tchannelsRoot.g = rootGrammar;\n\t\t\t\t\troot.insertChild(1, channelsRoot); // ^(GRAMMAR ID TOKENS...)\n\t\t\t\t} else {\n\t\t\t\t\tfor (int c = 0; c < imp_channelRoot.getChildCount(); ++c) {\n\t\t\t\t\t\tString channel = imp_channelRoot.getChild(c).getText();\n\t\t\t\t\t\tboolean channelIsInRootGrammar = false;\n\t\t\t\t\t\tfor (int rc = 0; rc < channelsRoot.getChildCount(); ++rc) {\n\t\t\t\t\t\t\tString rootChannel = channelsRoot.getChild(rc).getText();\n\t\t\t\t\t\t\tif (rootChannel.equals(channel)) {\n\t\t\t\t\t\t\t\tchannelIsInRootGrammar = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!channelIsInRootGrammar) {\n                            channelsRoot.addChild(imp_channelRoot.getChild(c).dupNode());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// COPY TOKENS\n\t\t\tGrammarAST imp_tokensRoot = (GrammarAST)imp.ast.getFirstChildWithType(ANTLRParser.TOKENS_SPEC);\n\t\t\tif ( imp_tokensRoot!=null ) {\n\t\t\t\trootGrammar.tool.log(\"grammar\", \"imported tokens: \"+imp_tokensRoot.getChildren());\n\t\t\t\tif ( tokensRoot==null ) {\n\t\t\t\t\ttokensRoot = (GrammarAST)adaptor.create(ANTLRParser.TOKENS_SPEC, \"TOKENS\");\n\t\t\t\t\ttokensRoot.g = rootGrammar;\n\t\t\t\t\troot.insertChild(1, tokensRoot); // ^(GRAMMAR ID TOKENS...)\n\t\t\t\t}\n\t\t\t\ttokensRoot.addChildren(Arrays.asList(imp_tokensRoot.getChildren().toArray(new Tree[0])));\n\t\t\t}\n\n\t\t\tList<GrammarAST> all_actionRoots = new ArrayList<GrammarAST>();\n\t\t\tList<GrammarAST> imp_actionRoots = imp.ast.getAllChildrenWithType(ANTLRParser.AT);\n\t\t\tif ( actionRoots!=null ) all_actionRoots.addAll(actionRoots);\n\t\t\tall_actionRoots.addAll(imp_actionRoots);\n\n\t\t\t// COPY ACTIONS\n\t\t\tif ( imp_actionRoots!=null ) {\n\t\t\t\tDoubleKeyMap<String, String, GrammarAST> namedActions =\n\t\t\t\t\tnew DoubleKeyMap<String, String, GrammarAST>();\n\n\t\t\t\trootGrammar.tool.log(\"grammar\", \"imported actions: \"+imp_actionRoots);\n\t\t\t\tfor (GrammarAST at : all_actionRoots) {\n\t\t\t\t\tString scopeName = rootGrammar.getDefaultActionScope();\n\t\t\t\t\tGrammarAST scope, name, action;\n\t\t\t\t\tif ( at.getChildCount()>2 ) { // must have a scope\n\t\t\t\t\t\tscope = (GrammarAST)at.getChild(0);\n\t\t\t\t\t\tscopeName = scope.getText();\n\t\t\t\t\t\tname = (GrammarAST)at.getChild(1);\n\t\t\t\t\t\taction = (GrammarAST)at.getChild(2);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tname = (GrammarAST)at.getChild(0);\n\t\t\t\t\t\taction = (GrammarAST)at.getChild(1);\n\t\t\t\t\t}\n\t\t\t\t\tGrammarAST prevAction = namedActions.get(scopeName, name.getText());\n\t\t\t\t\tif ( prevAction==null ) {\n\t\t\t\t\t\tnamedActions.put(scopeName, name.getText(), action);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif ( prevAction.g == at.g ) {\n\t\t\t\t\t\t\trootGrammar.tool.errMgr.grammarError(ErrorType.ACTION_REDEFINITION,\n\t\t\t\t\t\t\t\t\t\t\t\tat.g.fileName, name.token, name.getText());\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tString s1 = prevAction.getText();\n\t\t\t\t\t\t\ts1 = s1.substring(1, s1.length()-1);\n\t\t\t\t\t\t\tString s2 = action.getText();\n\t\t\t\t\t\t\ts2 = s2.substring(1, s2.length()-1);\n\t\t\t\t\t\t\tString combinedAction = \"{\"+s1 + '\\n'+ s2+\"}\";\n\t\t\t\t\t\t\tprevAction.token.setText(combinedAction);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// at this point, we have complete list of combined actions,\n\t\t\t\t// some of which are already living in root grammar.\n\t\t\t\t// Merge in any actions not in root grammar into root's tree.\n\t\t\t\tfor (String scopeName : namedActions.keySet()) {\n\t\t\t\t\tfor (String name : namedActions.keySet(scopeName)) {\n\t\t\t\t\t\tGrammarAST action = namedActions.get(scopeName, name);\n\t\t\t\t\t\trootGrammar.tool.log(\"grammar\", action.g.name+\" \"+scopeName+\":\"+name+\"=\"+action.getText());\n\t\t\t\t\t\tif ( action.g != rootGrammar ) {\n\t\t\t\t\t\t\troot.insertChild(1, action.getParent());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// COPY MODES\n\t\t\t// The strategy is to copy all the mode sections rules across to any\n\t\t\t// mode section in the new grammar with the same name or a new\n\t\t\t// mode section if no matching mode is resolved. Rules which are\n\t\t\t// already in the new grammar are ignored for copy. If the mode\n\t\t\t// section being added ends up empty it is not added to the merged\n\t\t\t// grammar.\n            List<GrammarAST> modes = imp.ast.getNodesWithType(ANTLRParser.MODE);\n\t\t\tif (modes != null) {\n\t\t\t\tfor (GrammarAST m : modes) {\n\t\t\t\t\trootGrammar.tool.log(\"grammar\", \"imported mode: \" + m.toStringTree());\n\t\t\t\t\tString name = m.getChild(0).getText();\n\t\t\t\t\tboolean rootAlreadyHasMode = rootModeNames.contains(name);\n\t\t\t\t\tGrammarAST destinationAST = null;\n\t\t\t\t\tif (rootAlreadyHasMode) {\n\t\t                for (GrammarAST m2 : rootModes) {\n\t\t\t\t\t\t\tif (m2.getChild(0).getText().equals(name)) {\n                                destinationAST = m2;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdestinationAST = m.dupNode();\n\t\t\t\t\t\tdestinationAST.addChild(m.getChild(0).dupNode());\n\t\t\t\t\t}\n\n\t\t\t\t\tint addedRules = 0;\n\t\t\t\t\tList<GrammarAST> modeRules = m.getAllChildrenWithType(ANTLRParser.RULE);\n\t\t\t\t\tfor (GrammarAST r : modeRules) {\n\t\t\t\t\t    rootGrammar.tool.log(\"grammar\", \"imported rule: \"+r.toStringTree());\n\t\t\t\t\t\tString ruleName = r.getChild(0).getText();\n\t\t\t\t\t    boolean rootAlreadyHasRule = rootRuleNames.contains(ruleName);\n\t\t\t\t\t    if (!rootAlreadyHasRule) {\n\t\t\t\t\t\t    destinationAST.addChild(r);\n\t\t\t\t\t\t\taddedRules++;\n\t\t\t\t\t\t    rootRuleNames.add(ruleName);\n\t\t\t\t\t    }\n\t\t\t\t\t}\n\t\t\t\t\tif (!rootAlreadyHasMode && addedRules > 0) {\n\t\t\t\t\t\trootGrammar.ast.addChild(destinationAST);\n\t\t\t\t\t\trootModeNames.add(name);\n\t\t\t\t\t\trootModes.add(destinationAST);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// COPY RULES\n\t\t\t// Rules copied in the mode copy phase are not copied again.\n\t\t\tList<GrammarAST> rules = imp.ast.getNodesWithType(ANTLRParser.RULE);\n\t\t\tif ( rules!=null ) {\n\t\t\t\tfor (GrammarAST r : rules) {\n\t\t\t\t\trootGrammar.tool.log(\"grammar\", \"imported rule: \"+r.toStringTree());\n\t\t\t\t\tString name = r.getChild(0).getText();\n\t\t\t\t\tboolean rootAlreadyHasRule = rootRuleNames.contains(name);\n\t\t\t\t\tif ( !rootAlreadyHasRule ) {\n\t\t\t\t\t\tRULES.addChild(r); // merge in if not overridden\n\t\t\t\t\t\trootRuleNames.add(name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tGrammarAST optionsRoot = (GrammarAST)imp.ast.getFirstChildWithType(ANTLRParser.OPTIONS);\n\t\t\tif ( optionsRoot!=null ) {\n\t\t\t\t// suppress the warning if the options match the options specified\n\t\t\t\t// in the root grammar\n\t\t\t\t// https://github.com/antlr/antlr4/issues/707\n\n\t\t\t\tboolean hasNewOption = false;\n\t\t\t\tfor (Map.Entry<String, GrammarAST> option : imp.ast.getOptions().entrySet()) {\n\t\t\t\t\tString importOption = imp.ast.getOptionString(option.getKey());\n\t\t\t\t\tif (importOption == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tString rootOption = rootGrammar.ast.getOptionString(option.getKey());\n\t\t\t\t\tif (!importOption.equals(rootOption)) {\n\t\t\t\t\t\thasNewOption = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (hasNewOption) {\n\t\t\t\t\trootGrammar.tool.errMgr.grammarError(ErrorType.OPTIONS_IN_DELEGATE,\n\t\t\t\t\t\t\t\t\t\toptionsRoot.g.fileName, optionsRoot.token, imp.name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trootGrammar.tool.log(\"grammar\", \"Grammar: \"+rootGrammar.ast.toStringTree());\n\t}\n\n\t/** Build lexer grammar from combined grammar that looks like:\n\t *\n\t *  (COMBINED_GRAMMAR A\n\t *      (tokens { X (= Y 'y'))\n\t *      (OPTIONS (= x 'y'))\n\t *      (@ members {foo})\n\t *      (@ lexer header {package jj;})\n\t *      (RULES (RULE .+)))\n\t *\n\t *  Move rules and actions to new tree, don't dup. Split AST apart.\n\t *  We'll have this Grammar share token symbols later; don't generate\n\t *  tokenVocab or tokens{} section.  Copy over named actions.\n\t *\n\t *  Side-effects: it removes children from GRAMMAR &amp; RULES nodes\n\t *                in combined AST.  Anything cut out is dup'd before\n\t *                adding to lexer to avoid \"who's ur daddy\" issues\n\t */\n\tpublic GrammarRootAST extractImplicitLexer(Grammar combinedGrammar) {\n\t\tGrammarRootAST combinedAST = combinedGrammar.ast;\n\t\t//tool.log(\"grammar\", \"before=\"+combinedAST.toStringTree());\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(combinedAST.token.getInputStream());\n\t\tGrammarAST[] elements = combinedAST.getChildren().toArray(new GrammarAST[0]);\n\n\t\t// MAKE A GRAMMAR ROOT and ID\n\t\tString lexerName = combinedAST.getChild(0).getText()+\"Lexer\";\n\t\tGrammarRootAST lexerAST =\n\t\t    new GrammarRootAST(new CommonToken(ANTLRParser.GRAMMAR, \"LEXER_GRAMMAR\"), combinedGrammar.ast.tokenStream);\n\t\tlexerAST.grammarType = ANTLRParser.LEXER;\n\t\tlexerAST.token.setInputStream(combinedAST.token.getInputStream());\n\t\tlexerAST.addChild((GrammarAST)adaptor.create(ANTLRParser.ID, lexerName));\n\n\t\t// COPY OPTIONS\n\t\tGrammarAST optionsRoot =\n\t\t\t(GrammarAST)combinedAST.getFirstChildWithType(ANTLRParser.OPTIONS);\n\t\tif ( optionsRoot!=null && optionsRoot.getChildCount()!=0 ) {\n\t\t\tGrammarAST lexerOptionsRoot = (GrammarAST)adaptor.dupNode(optionsRoot);\n\t\t\tlexerAST.addChild(lexerOptionsRoot);\n\t\t\tGrammarAST[] options = optionsRoot.getChildren().toArray(new GrammarAST[0]);\n\t\t\tfor (GrammarAST o : options) {\n\t\t\t\tString optionName = o.getChild(0).getText();\n\t\t\t\tif ( Grammar.lexerOptions.contains(optionName) &&\n\t\t\t\t\t !Grammar.doNotCopyOptionsToLexer.contains(optionName) )\n\t\t\t\t{\n\t\t\t\t\tGrammarAST optionTree = (GrammarAST)adaptor.dupTree(o);\n\t\t\t\t\tlexerOptionsRoot.addChild(optionTree);\n\t\t\t\t\tlexerAST.setOption(optionName, (GrammarAST)optionTree.getChild(1));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// COPY all named actions, but only move those with lexer:: scope\n\t\tList<GrammarAST> actionsWeMoved = new ArrayList<GrammarAST>();\n\t\tfor (GrammarAST e : elements) {\n\t\t\tif ( e.getType()==ANTLRParser.AT ) {\n\t\t\t\tlexerAST.addChild((Tree)adaptor.dupTree(e));\n\t\t\t\tif ( e.getChild(0).getText().equals(\"lexer\") ) {\n\t\t\t\t\tactionsWeMoved.add(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (GrammarAST r : actionsWeMoved) {\n\t\t\tcombinedAST.deleteChild( r );\n\t\t}\n\n\t\tGrammarAST combinedRulesRoot =\n\t\t\t(GrammarAST)combinedAST.getFirstChildWithType(ANTLRParser.RULES);\n\t\tif ( combinedRulesRoot==null ) return lexerAST;\n\n\t\t// MOVE lexer rules\n\n\t\tGrammarAST lexerRulesRoot =\n\t\t\t(GrammarAST)adaptor.create(ANTLRParser.RULES, \"RULES\");\n\t\tlexerAST.addChild(lexerRulesRoot);\n\t\tList<GrammarAST> rulesWeMoved = new ArrayList<GrammarAST>();\n\t\tGrammarASTWithOptions[] rules;\n\t\tif (combinedRulesRoot.getChildCount() > 0) {\n\t\t\trules = combinedRulesRoot.getChildren().toArray(new GrammarASTWithOptions[0]);\n\t\t}\n\t\telse {\n\t\t\trules = new GrammarASTWithOptions[0];\n\t\t}\n\n\t\tfor (GrammarASTWithOptions r : rules) {\n\t\t\tString ruleName = r.getChild(0).getText();\n\t\t\tif (Grammar.isTokenName(ruleName)) {\n\t\t\t\tlexerRulesRoot.addChild((Tree)adaptor.dupTree(r));\n\t\t\t\trulesWeMoved.add(r);\n\t\t\t}\n\t\t}\n\t\tfor (GrammarAST r : rulesWeMoved) {\n\t\t\tcombinedRulesRoot.deleteChild( r );\n\t\t}\n\n\t\t// Will track 'if' from IF : 'if' ; rules to avoid defining new token for 'if'\n\t\tList<Pair<GrammarAST,GrammarAST>> litAliases =\n\t\t\tGrammar.getStringLiteralAliasesFromLexerRules(lexerAST);\n\n\t\tSet<String> stringLiterals = combinedGrammar.getStringLiterals();\n\t\t// add strings from combined grammar (and imported grammars) into lexer\n\t\t// put them first as they are keywords; must resolve ambigs to these rules\n//\t\ttool.log(\"grammar\", \"strings from parser: \"+stringLiterals);\n\t\tint insertIndex = 0;\n\t\tnextLit:\n\t\tfor (String lit : stringLiterals) {\n\t\t\t// if lexer already has a rule for literal, continue\n\t\t\tif ( litAliases!=null ) {\n\t\t\t\tfor (Pair<GrammarAST,GrammarAST> pair : litAliases) {\n\t\t\t\t\tGrammarAST litAST = pair.b;\n\t\t\t\t\tif ( lit.equals(litAST.getText()) ) continue nextLit;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// create for each literal: (RULE <uniquename> (BLOCK (ALT <lit>))\n\t\t\tString rname = combinedGrammar.getStringLiteralLexerRuleName(lit);\n\t\t\t// can't use wizard; need special node types\n\t\t\tGrammarAST litRule = new RuleAST(ANTLRParser.RULE);\n\t\t\tBlockAST blk = new BlockAST(ANTLRParser.BLOCK);\n\t\t\tAltAST alt = new AltAST(ANTLRParser.ALT);\n\t\t\tTerminalAST slit = new TerminalAST(new CommonToken(ANTLRParser.STRING_LITERAL, lit));\n\t\t\talt.addChild(slit);\n\t\t\tblk.addChild(alt);\n\t\t\tCommonToken idToken = new CommonToken(ANTLRParser.TOKEN_REF, rname);\n\t\t\tlitRule.addChild(new TerminalAST(idToken));\n\t\t\tlitRule.addChild(blk);\n\t\t\tlexerRulesRoot.insertChild(insertIndex, litRule);\n//\t\t\tlexerRulesRoot.getChildren().add(0, litRule);\n\t\t\tlexerRulesRoot.freshenParentAndChildIndexes(); // reset indexes and set litRule parent\n\n\t\t\t// next literal will be added after the one just added\n\t\t\tinsertIndex++;\n\t\t}\n\n\t\t// TODO: take out after stable if slow\n\t\tlexerAST.sanityCheckParentAndChildIndexes();\n\t\tcombinedAST.sanityCheckParentAndChildIndexes();\n//\t\ttool.log(\"grammar\", combinedAST.toTokenString());\n\n        combinedGrammar.tool.log(\"grammar\", \"after extract implicit lexer =\"+combinedAST.toStringTree());\n        combinedGrammar.tool.log(\"grammar\", \"lexer =\"+lexerAST.toStringTree());\n\n\t\tif ( lexerRulesRoot.getChildCount()==0 )\treturn null;\n\t\treturn lexerAST;\n\t}\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/LabelElementPair.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.BitSet;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.tool.ast.GrammarAST;\n\npublic class LabelElementPair {\n    public static final BitSet tokenTypeForTokens = new BitSet();\n    static {\n        tokenTypeForTokens.add(ANTLRParser.TOKEN_REF);\n        tokenTypeForTokens.add(ANTLRParser.STRING_LITERAL);\n        tokenTypeForTokens.add(ANTLRParser.WILDCARD);\n    }\n\n    public GrammarAST label;\n    public GrammarAST element;\n    public LabelType type;\n\n    public LabelElementPair(Grammar g, GrammarAST label, GrammarAST element, int labelOp) {\n        this.label = label;\n        this.element = element;\n        // compute general case for label type\n        if ( element.getFirstDescendantWithType(tokenTypeForTokens)!=null ) {\n            if ( labelOp==ANTLRParser.ASSIGN ) type = LabelType.TOKEN_LABEL;\n            else type = LabelType.TOKEN_LIST_LABEL;\n        }\n        else if ( element.getFirstDescendantWithType(ANTLRParser.RULE_REF)!=null ) {\n            if ( labelOp==ANTLRParser.ASSIGN ) type = LabelType.RULE_LABEL;\n            else type = LabelType.RULE_LIST_LABEL;\n        }\n\n        // now reset if lexer and string\n        if ( g.isLexer() ) {\n            if ( element.getFirstDescendantWithType(ANTLRParser.STRING_LITERAL)!=null ) {\n                if ( labelOp==ANTLRParser.ASSIGN ) type = LabelType.LEXER_STRING_LABEL;\n            }\n        }\n    }\n\n    @Override\n    public String toString() {\n        return label.getText()+\" \"+type+\" \"+element.toString();\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/LabelType.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\n/** the various kinds of labels. t=type, id=ID, types+=type ids+=ID */\npublic enum LabelType {\n    RULE_LABEL,\n    TOKEN_LABEL,\n    RULE_LIST_LABEL,\n    TOKEN_LIST_LABEL,\n    LEXER_STRING_LABEL;         // used in lexer for x='a'\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/LeftRecursionCyclesMessage.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.Token;\n\nimport java.util.Collection;\n\npublic class LeftRecursionCyclesMessage extends ANTLRMessage {\n\tpublic LeftRecursionCyclesMessage(String fileName, Collection<? extends Collection<Rule>> cycles) {\n\t\tsuper(ErrorType.LEFT_RECURSION_CYCLES, getStartTokenOfFirstRule(cycles), cycles);\n\t\tthis.fileName = fileName;\n\t}\n\n\tprotected static Token getStartTokenOfFirstRule(Collection<? extends Collection<Rule>> cycles) {\n\t    if (cycles == null) {\n\t        return null;\n\t    }\n\n\t    for (Collection<Rule> collection : cycles) {\n\t        if (collection == null) {\n\t            return null;\n\t        }\n\n\t        for (Rule rule : collection) {\n\t            if (rule.ast != null) {\n\t                return rule.ast.getToken();\n\t            }\n\t        }\n\t    }\n\t\treturn null;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/LeftRecursiveRule.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.analysis.LeftRecursiveRuleAltInfo;\nimport org.antlr.v4.misc.OrderedHashMap;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.RuleAST;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class LeftRecursiveRule extends Rule {\n\tpublic List<LeftRecursiveRuleAltInfo> recPrimaryAlts;\n\tpublic OrderedHashMap<Integer, LeftRecursiveRuleAltInfo> recOpAlts;\n\tpublic RuleAST originalAST;\n\n\t/** Did we delete any labels on direct left-recur refs? Points at ID of ^(= ID el) */\n\tpublic List<Pair<GrammarAST,String>> leftRecursiveRuleRefLabels =\n\t\tnew ArrayList<Pair<GrammarAST,String>>();\n\n\tpublic LeftRecursiveRule(Grammar g, String name, RuleAST ast) {\n\t\tsuper(g, name, ast, 1);\n\t\toriginalAST = ast;\n\t\talt = new Alternative[numberOfAlts+1]; // always just one\n\t\tfor (int i=1; i<=numberOfAlts; i++) alt[i] = new Alternative(this, i);\n\t}\n\n\t@Override\n\tpublic boolean hasAltSpecificContexts() {\n\t\treturn super.hasAltSpecificContexts() || getAltLabels()!=null;\n\t}\n\n\t@Override\n\tpublic int getOriginalNumberOfAlts() {\n\t\tint n = 0;\n\t\tif ( recPrimaryAlts!=null ) n += recPrimaryAlts.size();\n\t\tif ( recOpAlts!=null ) n += recOpAlts.size();\n\t\treturn n;\n\t}\n\n\tpublic RuleAST getOriginalAST() {\n\t\treturn originalAST;\n\t}\n\n\t@Override\n\tpublic List<AltAST> getUnlabeledAltASTs() {\n\t\tList<AltAST> alts = new ArrayList<AltAST>();\n\t\tfor (LeftRecursiveRuleAltInfo altInfo : recPrimaryAlts) {\n\t\t\tif (altInfo.altLabel == null) alts.add(altInfo.originalAltAST);\n\t\t}\n\t\tfor (int i = 0; i < recOpAlts.size(); i++) {\n\t\t\tLeftRecursiveRuleAltInfo altInfo = recOpAlts.getElement(i);\n\t\t\tif ( altInfo.altLabel==null ) alts.add(altInfo.originalAltAST);\n\t\t}\n\t\tif ( alts.isEmpty() ) return null;\n\t\treturn alts;\n\t}\n\n\t/** Return an array that maps predicted alt from primary decision\n\t *  to original alt of rule. For following rule, return [0, 2, 4]\n\t *\n\t\te : e '*' e\n\t\t  | INT\n\t\t  | e '+' e\n\t\t  | ID\n\t\t  ;\n\n\t *  That maps predicted alt 1 to original alt 2 and predicted 2 to alt 4.\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic int[] getPrimaryAlts() {\n\t\tif ( recPrimaryAlts.size()==0 ) return null;\n\t\tint[] alts = new int[recPrimaryAlts.size()+1];\n\t\tfor (int i = 0; i < recPrimaryAlts.size(); i++) { // recPrimaryAlts is a List not Map like recOpAlts\n\t\t\tLeftRecursiveRuleAltInfo altInfo = recPrimaryAlts.get(i);\n\t\t\talts[i+1] = altInfo.altNum;\n\t\t}\n\t\treturn alts;\n\t}\n\n\t/** Return an array that maps predicted alt from recursive op decision\n\t *  to original alt of rule. For following rule, return [0, 1, 3]\n\t *\n\t\te : e '*' e\n\t\t  | INT\n\t\t  | e '+' e\n\t\t  | ID\n\t\t  ;\n\n\t *  That maps predicted alt 1 to original alt 1 and predicted 2 to alt 3.\n\t *\n\t *  @since 4.5.1\n\t */\n\tpublic int[] getRecursiveOpAlts() {\n\t\tif ( recOpAlts.size()==0 ) return null;\n\t\tint[] alts = new int[recOpAlts.size()+1];\n\t\tint alt = 1;\n\t\tfor (LeftRecursiveRuleAltInfo altInfo : recOpAlts.values()) {\n\t\t\talts[alt] = altInfo.altNum;\n\t\t\talt++; // recOpAlts has alts possibly with gaps\n\t\t}\n\t\treturn alts;\n\t}\n\n\t/** Get -&gt; labels from those alts we deleted for left-recursive rules. */\n\t@Override\n\tpublic Map<String, List<Pair<Integer, AltAST>>> getAltLabels() {\n\t\tMap<String, List<Pair<Integer, AltAST>>> labels = new HashMap<String, List<Pair<Integer, AltAST>>>();\n\t\tMap<String, List<Pair<Integer, AltAST>>> normalAltLabels = super.getAltLabels();\n\t\tif ( normalAltLabels!=null ) labels.putAll(normalAltLabels);\n\t\tif ( recPrimaryAlts!=null ) {\n\t\t\tfor (LeftRecursiveRuleAltInfo altInfo : recPrimaryAlts) {\n\t\t\t\tif (altInfo.altLabel != null) {\n\t\t\t\t\tList<Pair<Integer, AltAST>> pairs = labels.get(altInfo.altLabel);\n\t\t\t\t\tif (pairs == null) {\n\t\t\t\t\t\tpairs = new ArrayList<Pair<Integer, AltAST>>();\n\t\t\t\t\t\tlabels.put(altInfo.altLabel, pairs);\n\t\t\t\t\t}\n\n\t\t\t\t\tpairs.add(new Pair<Integer, AltAST>(altInfo.altNum, altInfo.originalAltAST));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( recOpAlts!=null ) {\n\t\t\tfor (int i = 0; i < recOpAlts.size(); i++) {\n\t\t\t\tLeftRecursiveRuleAltInfo altInfo = recOpAlts.getElement(i);\n\t\t\t\tif ( altInfo.altLabel!=null ) {\n\t\t\t\t\tList<Pair<Integer, AltAST>> pairs = labels.get(altInfo.altLabel);\n\t\t\t\t\tif (pairs == null) {\n\t\t\t\t\t\tpairs = new ArrayList<Pair<Integer, AltAST>>();\n\t\t\t\t\t\tlabels.put(altInfo.altLabel, pairs);\n\t\t\t\t\t}\n\n\t\t\t\t\tpairs.add(new Pair<Integer, AltAST>(altInfo.altNum, altInfo.originalAltAST));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( labels.isEmpty() ) return null;\n\t\treturn labels;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/LexerGrammar.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.runtime.misc.MultiMap;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\n\n/** */\npublic class LexerGrammar extends Grammar {\n\tpublic static final String DEFAULT_MODE_NAME = \"DEFAULT_MODE\";\n\n\t/** The grammar from which this lexer grammar was derived (if implicit) */\n    public Grammar implicitLexerOwner;\n\n\t/** DEFAULT_MODE rules are added first due to grammar syntax order */\n\tpublic MultiMap<String, Rule> modes;\n\n\tpublic LexerGrammar(Tool tool, GrammarRootAST ast) {\n\t\tsuper(tool, ast);\n\t}\n\n\tpublic LexerGrammar(String grammarText) throws RecognitionException {\n\t\tsuper(grammarText);\n\t}\n\n\tpublic LexerGrammar(String grammarText, ANTLRToolListener listener) throws RecognitionException {\n\t\tsuper(grammarText, listener);\n\t}\n\n\tpublic LexerGrammar(String fileName, String grammarText, ANTLRToolListener listener) throws RecognitionException {\n\t\tsuper(fileName, grammarText, listener);\n\t}\n\n\t@Override\n\tpublic boolean defineRule(Rule r) {\n\t\tif (!super.defineRule(r)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( modes==null ) modes = new MultiMap<String, Rule>();\n\t\tmodes.map(r.mode, r);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean undefineRule(Rule r) {\n\t\tif (!super.undefineRule(r)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tboolean removed = modes.get(r.mode).remove(r);\n\t\tassert removed;\n\t\treturn true;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/Rule.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.tool.ast.ActionAST;\nimport org.antlr.v4.tool.ast.AltAST;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.PredAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.stringtemplate.v4.misc.MultiMap;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Rule implements AttributeResolver {\n\t/** Rule refs have a predefined set of attributes as well as\n     *  the return values and args.\n     *\n     *  These must be consistent with ActionTranslator.rulePropToModelMap, ...\n     */\n\tpublic static final AttributeDict predefinedRulePropertiesDict =\n\t\tnew AttributeDict(AttributeDict.DictType.PREDEFINED_RULE);\n\tstatic {\n\t\tpredefinedRulePropertiesDict.add(new Attribute(\"parser\"));\n\t\tpredefinedRulePropertiesDict.add(new Attribute(\"text\"));\n\t\tpredefinedRulePropertiesDict.add(new Attribute(\"start\"));\n\t\tpredefinedRulePropertiesDict.add(new Attribute(\"stop\"));\n\t\tpredefinedRulePropertiesDict.add(new Attribute(\"ctx\"));\n\t}\n\n\tpublic static final Set<String> validLexerCommands = new HashSet<String>();\n\tstatic {\n\t\t// CALLS\n\t\tvalidLexerCommands.add(\"mode\");\n\t\tvalidLexerCommands.add(\"pushMode\");\n\t\tvalidLexerCommands.add(\"type\");\n\t\tvalidLexerCommands.add(\"channel\");\n\n\t\t// ACTIONS\n\t\tvalidLexerCommands.add(\"popMode\");\n\t\tvalidLexerCommands.add(\"skip\");\n\t\tvalidLexerCommands.add(\"more\");\n\t}\n\n\tpublic final String name;\n\tpublic List<GrammarAST> modifiers;\n\n\tpublic RuleAST ast;\n\tpublic AttributeDict args;\n\tpublic AttributeDict retvals;\n\tpublic AttributeDict locals;\n\n\t/** In which grammar does this rule live? */\n\tpublic final Grammar g;\n\n\t/** If we're in a lexer grammar, we might be in a mode */\n\tpublic final String mode;\n\n\t/** If null then use value from global option that is false by default */\n\tpublic final boolean caseInsensitive;\n\n    /** Map a name to an action for this rule like @init {...}.\n     *  The code generator will use this to fill holes in the rule template.\n     *  I track the AST node for the action in case I need the line number\n     *  for errors.\n     */\n    public Map<String, ActionAST> namedActions =\n        new HashMap<String, ActionAST>();\n\n    /** Track exception handlers; points at \"catch\" node of (catch exception action)\n\t *  don't track finally action\n\t */\n    public List<GrammarAST> exceptions = new ArrayList<GrammarAST>();\n\n\t/** Track all executable actions other than named actions like @init\n\t *  and catch/finally (not in an alt). Also tracks predicates, rewrite actions.\n\t *  We need to examine these actions before code generation so\n\t *  that we can detect refs to $rule.attr etc...\n\t *\n\t *  This tracks per rule; Alternative objs also track per alt.\n\t */\n\tpublic List<ActionAST> actions = new ArrayList<ActionAST>();\n\n\tpublic ActionAST finallyAction;\n\n\tpublic final int numberOfAlts;\n\n\tpublic boolean isStartRule = true; // nobody calls us\n\n\t/** 1..n alts */\n\tpublic Alternative[] alt;\n\n\t/** All rules have unique index 0..n-1 */\n\tpublic int index;\n\n\tpublic int actionIndex = -1; // if lexer; 0..n-1 for n actions in a rule\n\n\tpublic Rule(Grammar g, String name, RuleAST ast, int numberOfAlts) {\n\t\tthis(g, name, ast, numberOfAlts, null, false);\n\t}\n\n\tpublic Rule(Grammar g, String name, RuleAST ast, int numberOfAlts, String lexerMode, boolean caseInsensitive) {\n\t\tthis.g = g;\n\t\tthis.name = name;\n\t\tthis.ast = ast;\n\t\tthis.numberOfAlts = numberOfAlts;\n\t\talt = new Alternative[numberOfAlts+1]; // 1..n\n\t\tfor (int i=1; i<=numberOfAlts; i++) alt[i] = new Alternative(this, i);\n\t\tthis.mode = lexerMode;\n\t\tthis.caseInsensitive = caseInsensitive;\n\t}\n\n\tpublic void defineActionInAlt(int currentAlt, ActionAST actionAST) {\n\t\tactions.add(actionAST);\n\t\talt[currentAlt].actions.add(actionAST);\n\t\tif ( g.isLexer() ) {\n\t\t\tdefineLexerAction(actionAST);\n\t\t}\n\t}\n\n\t/** Lexer actions are numbered across rules 0..n-1 */\n\tpublic void defineLexerAction(ActionAST actionAST) {\n\t\tactionIndex = g.lexerActions.size();\n\t\tif ( g.lexerActions.get(actionAST)==null ) {\n\t\t\tg.lexerActions.put(actionAST, actionIndex);\n\t\t}\n\t}\n\n\tpublic void definePredicateInAlt(int currentAlt, PredAST predAST) {\n\t\tactions.add(predAST);\n\t\talt[currentAlt].actions.add(predAST);\n\t\tif ( g.sempreds.get(predAST)==null ) {\n\t\t\tg.sempreds.put(predAST, g.sempreds.size());\n\t\t}\n\t}\n\n\tpublic Attribute resolveRetvalOrProperty(String y) {\n\t\tif ( retvals!=null ) {\n\t\t\tAttribute a = retvals.get(y);\n\t\t\tif ( a!=null ) return a;\n\t\t}\n\t\tAttributeDict d = getPredefinedScope(LabelType.RULE_LABEL);\n\t\treturn d.get(y);\n\t}\n\n\tpublic Set<String> getTokenRefs() {\n        Set<String> refs = new HashSet<String>();\n\t\tfor (int i=1; i<=numberOfAlts; i++) {\n\t\t\trefs.addAll(alt[i].tokenRefs.keySet());\n\t\t}\n\t\treturn refs;\n    }\n\n    public Set<String> getElementLabelNames() {\n        Set<String> refs = new HashSet<String>();\n        for (int i=1; i<=numberOfAlts; i++) {\n            refs.addAll(alt[i].labelDefs.keySet());\n        }\n\t\tif ( refs.isEmpty() ) return null;\n        return refs;\n    }\n\n    public MultiMap<String, LabelElementPair> getElementLabelDefs() {\n        MultiMap<String, LabelElementPair> defs =\n            new MultiMap<String, LabelElementPair>();\n        for (int i=1; i<=numberOfAlts; i++) {\n            for (List<LabelElementPair> pairs : alt[i].labelDefs.values()) {\n                for (LabelElementPair p : pairs) {\n                    defs.map(p.label.getText(), p);\n                }\n            }\n        }\n        return defs;\n    }\n\n\tpublic boolean hasAltSpecificContexts() {\n\t\treturn getAltLabels()!=null;\n\t}\n\n\t/** Used for recursive rules (subclass), which have 1 alt, but many original alts */\n\tpublic int getOriginalNumberOfAlts() {\n\t\treturn numberOfAlts;\n\t}\n\n\t/**\n\t * Get {@code #} labels. The keys of the map are the labels applied to outer\n\t * alternatives of a lexer rule, and the values are collections of pairs\n\t * (alternative number and {@link AltAST}) identifying the alternatives with\n\t * this label. Unlabeled alternatives are not included in the result.\n\t */\n\tpublic Map<String, List<Pair<Integer, AltAST>>> getAltLabels() {\n\t\tMap<String, List<Pair<Integer, AltAST>>> labels = new LinkedHashMap<String, List<Pair<Integer, AltAST>>>();\n\t\tfor (int i=1; i<=numberOfAlts; i++) {\n\t\t\tGrammarAST altLabel = alt[i].ast.altLabel;\n\t\t\tif ( altLabel!=null ) {\n\t\t\t\tList<Pair<Integer, AltAST>> list = labels.get(altLabel.getText());\n\t\t\t\tif (list == null) {\n\t\t\t\t\tlist = new ArrayList<Pair<Integer, AltAST>>();\n\t\t\t\t\tlabels.put(altLabel.getText(), list);\n\t\t\t\t}\n\n\t\t\t\tlist.add(new Pair<Integer, AltAST>(i, alt[i].ast));\n\t\t\t}\n\t\t}\n\t\tif ( labels.isEmpty() ) return null;\n\t\treturn labels;\n\t}\n\n\tpublic List<AltAST> getUnlabeledAltASTs() {\n\t\tList<AltAST> alts = new ArrayList<AltAST>();\n\t\tfor (int i=1; i<=numberOfAlts; i++) {\n\t\t\tGrammarAST altLabel = alt[i].ast.altLabel;\n\t\t\tif ( altLabel==null ) alts.add(alt[i].ast);\n\t\t}\n\t\tif ( alts.isEmpty() ) return null;\n\t\treturn alts;\n\t}\n\n\t/**  $x\t\tAttribute: rule arguments, return values, predefined rule prop.\n\t */\n\t@Override\n\tpublic Attribute resolveToAttribute(String x, ActionAST node) {\n\t\tif ( args!=null ) {\n\t\t\tAttribute a = args.get(x);   \tif ( a!=null ) return a;\n\t\t}\n\t\tif ( retvals!=null ) {\n\t\t\tAttribute a = retvals.get(x);\tif ( a!=null ) return a;\n\t\t}\n\t\tif ( locals!=null ) {\n\t\t\tAttribute a = locals.get(x);\tif ( a!=null ) return a;\n\t\t}\n\t\tAttributeDict properties = getPredefinedScope(LabelType.RULE_LABEL);\n\t\treturn properties.get(x);\n\t}\n\n\t/** $x.y\tAttribute: x is surrounding rule, label ref (in any alts) */\n\t@Override\n\tpublic Attribute resolveToAttribute(String x, String y, ActionAST node) {\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\tif ( anyLabelDef!=null ) {\n\t\t\tif ( anyLabelDef.type==LabelType.RULE_LABEL ) {\n\t\t\t\treturn g.getRule(anyLabelDef.element.getText()).resolveRetvalOrProperty(y);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tAttributeDict scope = getPredefinedScope(anyLabelDef.type);\n\t\t\t\tif (scope == null) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn scope.get(y);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\n\t}\n\n\t@Override\n\tpublic boolean resolvesToLabel(String x, ActionAST node) {\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\treturn anyLabelDef!=null &&\n\t\t\t   (anyLabelDef.type==LabelType.RULE_LABEL ||\n\t\t\t\tanyLabelDef.type==LabelType.TOKEN_LABEL);\n\t}\n\n\t@Override\n\tpublic boolean resolvesToListLabel(String x, ActionAST node) {\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\treturn anyLabelDef!=null &&\n\t\t\t   (anyLabelDef.type==LabelType.RULE_LIST_LABEL ||\n\t\t\t\tanyLabelDef.type==LabelType.TOKEN_LIST_LABEL);\n\t}\n\n\t@Override\n\tpublic boolean resolvesToToken(String x, ActionAST node) {\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\tif ( anyLabelDef!=null && anyLabelDef.type==LabelType.TOKEN_LABEL ) return true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean resolvesToAttributeDict(String x, ActionAST node) {\n\t\tif ( resolvesToToken(x, node) ) return true;\n\t\treturn false;\n\t}\n\n\tpublic Rule resolveToRule(String x) {\n\t\tif ( x.equals(this.name) ) return this;\n\t\tLabelElementPair anyLabelDef = getAnyLabelDef(x);\n\t\tif ( anyLabelDef!=null && anyLabelDef.type==LabelType.RULE_LABEL ) {\n\t\t\treturn g.getRule(anyLabelDef.element.getText());\n\t\t}\n\t\treturn g.getRule(x);\n\t}\n\n\tpublic LabelElementPair getAnyLabelDef(String x) {\n\t\tList<LabelElementPair> labels = getElementLabelDefs().get(x);\n\t\tif ( labels!=null ) return labels.get(0);\n\t\treturn null;\n\t}\n\n    public AttributeDict getPredefinedScope(LabelType ltype) {\n        String grammarLabelKey = g.getTypeString() + \":\" + ltype;\n        return Grammar.grammarAndLabelRefTypeToScope.get(grammarLabelKey);\n    }\n\n\tpublic boolean isFragment() {\n\t\tif ( modifiers==null ) return false;\n\t\tfor (GrammarAST a : modifiers) {\n\t\t\tif ( a.getText().equals(\"fragment\") ) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int hashCode() { return name.hashCode(); }\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!(obj instanceof Rule)) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn name.equals(((Rule)obj).name);\n\t}\n\n\t@Override\n    public String toString() {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append(\"Rule{name=\").append(name);\n\t\tif ( args!=null ) buf.append(\", args=\").append(args);\n\t\tif ( retvals!=null ) buf.append(\", retvals=\").append(retvals);\n\t\tbuf.append(\"}\");\n\t\treturn buf.toString();\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ToolMessage.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool;\n\nimport org.antlr.runtime.Token;\n\n/** A generic message from the tool such as \"file not found\" type errors; there\n *  is no reason to create a special object for each error unlike the grammar\n *  errors, which may be rather complex.\n *\n *  Sometimes you need to pass in a filename or something to say it is \"bad\".\n *  Allow a generic object to be passed in and the string template can deal\n *  with just printing it or pulling a property out of it.\n */\npublic class ToolMessage extends ANTLRMessage {\n\tpublic ToolMessage(ErrorType errorType) {\n\t\tsuper(errorType);\n\t}\n    public ToolMessage(ErrorType errorType, Object... args) {\n        super(errorType, null, Token.INVALID_TOKEN, args);\n    }\n    public ToolMessage(ErrorType errorType, Throwable e, Object... args) {\n        super(errorType, e, Token.INVALID_TOKEN, args);\n    }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/ActionAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.tool.AttributeResolver;\n\nimport java.util.List;\n\npublic class ActionAST extends GrammarASTWithOptions implements RuleElementAST {\n    // Alt, rule, grammar space\n\tGrammarAST scope = null;\n\tpublic AttributeResolver resolver;\n\tpublic List<Token> chunks; // useful for ANTLR IDE developers\n\n\tpublic ActionAST(ActionAST node) {\n\t\tsuper(node);\n\t\tthis.resolver = node.resolver;\n\t\tthis.chunks = node.chunks;\n\t}\n\n\tpublic ActionAST(Token t) { super(t); }\n    public ActionAST(int type) { super(type); }\n    public ActionAST(int type, Token t) { super(type, t); }\n\n\t@Override\n\tpublic ActionAST dupNode() { return new ActionAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n\n\tpublic void setScope(GrammarAST scope) {\n\t\tthis.scope = scope;\n\t}\n\n\tpublic GrammarAST getScope() {\n\t\treturn scope;\n\t}\n\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/AltAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.analysis.LeftRecursiveRuleAltInfo;\nimport org.antlr.v4.tool.Alternative;\n\n/** Any ALT (which can be child of ALT_REWRITE node) */\npublic class AltAST extends GrammarASTWithOptions {\n\tpublic Alternative alt;\n\n\t/** If we transformed this alt from a left-recursive one, need info on it */\n\tpublic LeftRecursiveRuleAltInfo leftRecursiveAltInfo;\n\n\t/** If someone specified an outermost alternative label with #foo.\n\t *  Token type will be ID.\n\t */\n\tpublic GrammarAST altLabel;\n\n\tpublic AltAST(AltAST node) {\n\t\tsuper(node);\n\t\tthis.alt = node.alt;\n\t\tthis.altLabel = node.altLabel;\n\t\tthis.leftRecursiveAltInfo = node.leftRecursiveAltInfo;\n\t}\n\n\tpublic AltAST(Token t) { super(t); }\n\tpublic AltAST(int type) { super(type); }\n\tpublic AltAST(int type, Token t) { super(type, t); }\n\tpublic AltAST(int type, Token t, String text) { super(type,t,text); }\n\n\t@Override\n\tpublic AltAST dupNode() { return new AltAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/BlockAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class BlockAST extends GrammarASTWithOptions implements RuleElementAST {\n    // TODO: maybe I need a Subrule object like Rule so these options mov to that?\n    /** What are the default options for a subrule? */\n    public static final Map<String, String> defaultBlockOptions =\n            new HashMap<String, String>();\n\n    public static final Map<String, String> defaultLexerBlockOptions =\n            new HashMap<String, String>();\n\n\tpublic BlockAST(BlockAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic BlockAST(Token t) { super(t); }\n    public BlockAST(int type) { super(type); }\n    public BlockAST(int type, Token t) { super(type, t); }\n\tpublic BlockAST(int type, Token t, String text) { super(type,t,text); }\n\n\t@Override\n\tpublic BlockAST dupNode() { return new BlockAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/GrammarAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.CharStream;\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.tree.CommonTree;\nimport org.antlr.runtime.tree.CommonTreeNodeStream;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.parse.GrammarASTAdaptor;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.Grammar;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class GrammarAST extends CommonTree {\n\t/** For error msgs, nice to know which grammar this AST lives in */\n\t// TODO: try to remove\n\tpublic Grammar g;\n\n\t/** If we build an ATN, we make AST node point at left edge of ATN construct */\n\tpublic ATNState atnState;\n\n\tpublic String textOverride;\n\n    public GrammarAST() {}\n    public GrammarAST(Token t) { super(t); }\n    public GrammarAST(GrammarAST node) {\n\t\tsuper(node);\n\t\tthis.g = node.g;\n\t\tthis.atnState = node.atnState;\n\t\tthis.textOverride = node.textOverride;\n\t}\n    public GrammarAST(int type) { super(new CommonToken(type, ANTLRParser.tokenNames[type])); }\n    public GrammarAST(int type, Token t) {\n\t\tthis(new CommonToken(t));\n\t\ttoken.setType(type);\n\t}\n    public GrammarAST(int type, Token t, String text) {\n\t\tthis(new CommonToken(t));\n\t\ttoken.setType(type);\n\t\ttoken.setText(text);\n    }\n\n\tpublic GrammarAST[] getChildrenAsArray() {\n\t\treturn children.toArray(new GrammarAST[0]);\n\t}\n\n\tpublic List<GrammarAST> getNodesWithType(int ttype) {\n\t\treturn getNodesWithType(IntervalSet.of(ttype));\n\t}\n\n\tpublic List<GrammarAST> getAllChildrenWithType(int type) {\n\t\tList<GrammarAST> nodes = new ArrayList<GrammarAST>();\n\t\tfor (int i = 0; children!=null && i < children.size(); i++) {\n\t\t\tTree t = (Tree) children.get(i);\n\t\t\tif ( t.getType()==type ) {\n\t\t\t\tnodes.add((GrammarAST)t);\n\t\t\t}\n\t\t}\n\t\treturn nodes;\n\t}\n\n\tpublic List<GrammarAST> getNodesWithType(IntervalSet types) {\n\t\tList<GrammarAST> nodes = new ArrayList<GrammarAST>();\n\t\tList<GrammarAST> work = new LinkedList<GrammarAST>();\n\t\twork.add(this);\n\t\tGrammarAST t;\n\t\twhile ( !work.isEmpty() ) {\n\t\t\tt = work.remove(0);\n\t\t\tif ( types==null || types.contains(t.getType()) ) nodes.add(t);\n\t\t\tif ( t.children!=null ) {\n\t\t\t\twork.addAll(Arrays.asList(t.getChildrenAsArray()));\n\t\t\t}\n\t\t}\n\t\treturn nodes;\n\t}\n\n\tpublic List<GrammarAST> getNodesWithTypePreorderDFS(IntervalSet types) {\n\t\tArrayList<GrammarAST> nodes = new ArrayList<GrammarAST>();\n\t\tgetNodesWithTypePreorderDFS_(nodes, types);\n\t\treturn nodes;\n\t}\n\n\tpublic void getNodesWithTypePreorderDFS_(List<GrammarAST> nodes, IntervalSet types) {\n\t\tif ( types.contains(this.getType()) ) nodes.add(this);\n\t\t// walk all children of root.\n\t\tfor (int i= 0; i < getChildCount(); i++) {\n\t\t\tGrammarAST child = (GrammarAST)getChild(i);\n\t\t\tchild.getNodesWithTypePreorderDFS_(nodes, types);\n\t\t}\n\t}\n\n\tpublic GrammarAST getNodeWithTokenIndex(int index) {\n\t\tif ( this.getToken()!=null && this.getToken().getTokenIndex()==index ) {\n\t\t\treturn this;\n\t\t}\n\t\t// walk all children of root.\n\t\tfor (int i= 0; i < getChildCount(); i++) {\n\t\t\tGrammarAST child = (GrammarAST)getChild(i);\n\t\t\tGrammarAST result = child.getNodeWithTokenIndex(index);\n\t\t\tif ( result!=null ) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic AltAST getOutermostAltNode() {\n\t\tif ( this instanceof AltAST && parent.parent instanceof RuleAST ) {\n\t\t\treturn (AltAST)this;\n\t\t}\n\t\tif ( parent!=null ) return ((GrammarAST)parent).getOutermostAltNode();\n\t\treturn null;\n\t}\n\n\t/** Walk ancestors of this node until we find ALT with\n\t *  alt!=null or leftRecursiveAltInfo!=null. Then grab label if any.\n\t *  If not a rule element, just returns null.\n\t */\n\tpublic String getAltLabel() {\n\t\tList<? extends Tree> ancestors = this.getAncestors();\n\t\tif ( ancestors==null ) return null;\n\t\tfor (int i=ancestors.size()-1; i>=0; i--) {\n\t\t\tGrammarAST p = (GrammarAST)ancestors.get(i);\n\t\t\tif ( p.getType()== ANTLRParser.ALT ) {\n\t\t\t\tAltAST a = (AltAST)p;\n\t\t\t\tif ( a.altLabel!=null ) return a.altLabel.getText();\n\t\t\t\tif ( a.leftRecursiveAltInfo!=null ) {\n\t\t\t\t\treturn a.leftRecursiveAltInfo.altLabel;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean deleteChild(org.antlr.runtime.tree.Tree t) {\n\t\tfor (int i=0; i<children.size(); i++) {\n\t\t\tObject c = children.get(i);\n\t\t\tif ( c == t ) {\n\t\t\t\tdeleteChild(t.getChildIndex());\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n    // TODO: move to basetree when i settle on how runtime works\n    // TODO: don't include this node!!\n\t// TODO: reuse other method\n    public CommonTree getFirstDescendantWithType(int type) {\n        if ( getType()==type ) return this;\n        if ( children==null ) return null;\n        for (Object c : children) {\n            GrammarAST t = (GrammarAST)c;\n            if ( t.getType()==type ) return t;\n            CommonTree d = t.getFirstDescendantWithType(type);\n            if ( d!=null ) return d;\n        }\n        return null;\n    }\n\n\t// TODO: don't include this node!!\n\tpublic CommonTree getFirstDescendantWithType(org.antlr.runtime.BitSet types) {\n\t\tif ( types.member(getType()) ) return this;\n\t\tif ( children==null ) return null;\n\t\tfor (Object c : children) {\n\t\t\tGrammarAST t = (GrammarAST)c;\n\t\t\tif ( types.member(t.getType()) ) return t;\n\t\t\tCommonTree d = t.getFirstDescendantWithType(types);\n\t\t\tif ( d!=null ) return d;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void setType(int type) {\n\t\ttoken.setType(type);\n\t}\n//\n//\t@Override\n//\tpublic String getText() {\n//\t\tif ( textOverride!=null ) return textOverride;\n//        if ( token!=null ) {\n//            return token.getText();\n//        }\n//        return \"\";\n//\t}\n\n\tpublic void setText(String text) {\n//\t\ttextOverride = text; // don't alt tokens as others might see\n\t\ttoken.setText(text); // we delete surrounding tree, so ok to alter\n\t}\n\n//\t@Override\n//\tpublic boolean equals(Object obj) {\n//\t\treturn super.equals(obj);\n//\t}\n\n\t@Override\n    public GrammarAST dupNode() {\n        return new GrammarAST(this);\n    }\n\n\tpublic GrammarAST dupTree() {\n\t\tGrammarAST t = this;\n\t\tCharStream input = this.token.getInputStream();\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(input);\n\t\treturn (GrammarAST)adaptor.dupTree(t);\n\t}\n\n\tpublic String toTokenString() {\n\t\tCharStream input = this.token.getInputStream();\n\t\tGrammarASTAdaptor adaptor = new GrammarASTAdaptor(input);\n\t\tCommonTreeNodeStream nodes =\n\t\t\tnew CommonTreeNodeStream(adaptor, this);\n\t\tStringBuilder buf = new StringBuilder();\n\t\tGrammarAST o = (GrammarAST)nodes.LT(1);\n\t\tint type = adaptor.getType(o);\n\t\twhile ( type!=Token.EOF ) {\n\t\t\tbuf.append(\" \");\n\t\t\tbuf.append(o.getText());\n\t\t\tnodes.consume();\n\t\t\to = (GrammarAST)nodes.LT(1);\n\t\t\ttype = adaptor.getType(o);\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/GrammarASTErrorNode.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.TokenStream;\nimport org.antlr.runtime.tree.CommonErrorNode;\n\n/** A node representing erroneous token range in token stream */\npublic class GrammarASTErrorNode extends GrammarAST {\n    CommonErrorNode delegate;\n    public GrammarASTErrorNode(TokenStream input, Token start, Token stop,\n                               org.antlr.runtime.RecognitionException e)\n    {\n        delegate = new CommonErrorNode(input,start,stop,e);\n    }\n\n    @Override\n    public boolean isNil() { return delegate.isNil(); }\n\n    @Override\n    public int getType() { return delegate.getType(); }\n\n    @Override\n    public String getText() { return delegate.getText(); }\n    @Override\n    public String toString() { return delegate.toString(); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/GrammarASTVisitor.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\n/** A simple visitor, based upon the classic double dispatch method,\n *  for walking GrammarAST trees resulting from parsing ANTLR grammars.\n *  There is also the GrammarTreeVisitor.g tree grammar that looks for\n *  subtree patterns and fires off high-level events as opposed to\n *  \"found node\" events like this visitor does. Also, like all\n *  visitors, the users of this interface are required to implement\n *  the node visitation of the children. The GrammarTreeVisitor mechanism\n *  fires events and the user is not required to do any walking code.\n *\n *  GrammarAST t = ...;\n *  GrammarASTVisitor v = new ...;\n *  t.visit(v);\n */\npublic interface GrammarASTVisitor {\n\t/** This is the generic visitor method that will be invoked\n\t *  for any other kind of AST node not covered by the other visit methods.\n\t */\n\tObject visit(GrammarAST node);\n\n\tObject visit(GrammarRootAST node);\n\tObject visit(RuleAST node);\n\n\tObject visit(BlockAST node);\n\tObject visit(OptionalBlockAST node);\n\tObject visit(PlusBlockAST node);\n\tObject visit(StarBlockAST node);\n\n\tObject visit(AltAST node);\n\n\tObject visit(NotAST node);\n\tObject visit(PredAST node);\n\tObject visit(RangeAST node);\n\tObject visit(SetAST node);\n\tObject visit(RuleRefAST node);\n\tObject visit(TerminalAST node);\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/GrammarASTWithOptions.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.misc.CharSupport;\nimport org.antlr.v4.tool.ErrorType;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic abstract class GrammarASTWithOptions extends GrammarAST {\n    protected Map<String, GrammarAST> options;\n\n\tpublic GrammarASTWithOptions(GrammarASTWithOptions node) {\n\t\tsuper(node);\n\t\tthis.options = node.options;\n\t}\n\n\tpublic GrammarASTWithOptions(Token t) { super(t); }\n    public GrammarASTWithOptions(int type) { super(type); }\n    public GrammarASTWithOptions(int type, Token t) { super(type, t); }\n    public GrammarASTWithOptions(int type, Token t, String text) { super(type,t,text); }\n\n    public void setOption(String key, GrammarAST node) {\n        if ( options==null ) options = new HashMap<String, GrammarAST>();\n        options.put(key, node);\n    }\n\n\tpublic String getOptionString(String key) {\n\t\tGrammarAST value = getOptionAST(key);\n\t\tif ( value == null ) return null;\n\t\tif ( value instanceof ActionAST ) {\n\t\t\treturn value.getText();\n\t\t}\n\t\telse {\n\t\t\tString v = value.getText();\n\t\t\tif ( v.startsWith(\"'\") || v.startsWith(\"\\\"\") ) {\n\t\t\t\tv = CharSupport.getStringFromGrammarStringLiteral(v);\n\t\t\t\tif (v == null) {\n\t\t\t\t\tg.tool.errMgr.grammarError(ErrorType.INVALID_ESCAPE_SEQUENCE, g.fileName, value.getToken(), value.getText());\n\t\t\t\t\tv = \"\";\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn v;\n\t\t}\n\t}\n\n\t/** Gets AST node holding value for option key; ignores default options\n\t *  and command-line forced options.\n\t */\n    public GrammarAST getOptionAST(String key) {\n        if ( options==null ) return null;\n        return options.get(key);\n    }\n\n\tpublic int getNumberOfOptions() {\n\t\treturn options==null ? 0 : options.size();\n\t}\n\n\t@Override\n\tpublic abstract GrammarASTWithOptions dupNode();\n\n\n\tpublic Map<String, GrammarAST> getOptions() {\n\t\tif (options == null) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\n\t\treturn options;\n\t}\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/GrammarRootAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.TokenStream;\nimport org.antlr.runtime.tree.Tree;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class GrammarRootAST extends GrammarASTWithOptions {\n\tpublic static final Map<String, String> defaultOptions = new HashMap<String, String>();\n\tstatic {\n\t\tdefaultOptions.put(\"language\",\"Java\");\n\t}\n\n    public int grammarType; // LEXER, PARSER, GRAMMAR (combined)\n\tpublic boolean hasErrors;\n\t/** Track stream used to create this tree */\n\n\tpublic final TokenStream tokenStream;\n\tpublic Map<String, String> cmdLineOptions; // -DsuperClass=T on command line\n\tpublic String fileName;\n\n\tpublic GrammarRootAST(GrammarRootAST node) {\n\t\tsuper(node);\n\t\tthis.grammarType = node.grammarType;\n\t\tthis.hasErrors = node.hasErrors;\n\t\tthis.tokenStream = node.tokenStream;\n\t}\n\n\tpublic GrammarRootAST(Token t, TokenStream tokenStream) {\n\t\tsuper(t);\n\t\tif (tokenStream == null) {\n\t\t\tthrow new NullPointerException(\"tokenStream\");\n\t\t}\n\n\t\tthis.tokenStream = tokenStream;\n\t}\n\n\tpublic GrammarRootAST(int type, Token t, TokenStream tokenStream) {\n\t\tsuper(type, t);\n\t\tif (tokenStream == null) {\n\t\t\tthrow new NullPointerException(\"tokenStream\");\n\t\t}\n\n\t\tthis.tokenStream = tokenStream;\n\t}\n\n\tpublic GrammarRootAST(int type, Token t, String text, TokenStream tokenStream) {\n\t\tsuper(type,t,text);\n\t\tif (tokenStream == null) {\n\t\t\tthrow new NullPointerException(\"tokenStream\");\n\t\t}\n\n\t\tthis.tokenStream = tokenStream;\n    }\n\n\tpublic String getGrammarName() {\n\t\tTree t = getChild(0);\n\t\tif ( t!=null ) return t.getText();\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getOptionString(String key) {\n\t\tif ( cmdLineOptions!=null && cmdLineOptions.containsKey(key) ) {\n\t\t\treturn cmdLineOptions.get(key);\n\t\t}\n\t\tString value = super.getOptionString(key);\n\t\tif ( value==null ) {\n\t\t\tvalue = defaultOptions.get(key);\n\t\t}\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n\n\t@Override\n\tpublic GrammarRootAST dupNode() { return new GrammarRootAST(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/NotAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class NotAST extends GrammarAST implements RuleElementAST {\n\n\tpublic NotAST(NotAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic NotAST(int type, Token t) { super(type, t); }\n\n\t@Override\n\tpublic NotAST dupNode() {\n\t\treturn new NotAST(this);\n\t}\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/OptionalBlockAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class OptionalBlockAST extends GrammarAST implements RuleElementAST, QuantifierAST {\n\tprivate final boolean _greedy;\n\n\tpublic OptionalBlockAST(OptionalBlockAST node) {\n\t\tsuper(node);\n\t\t_greedy = node._greedy;\n\t}\n\n\tpublic OptionalBlockAST(int type, Token t, Token nongreedy) {\n\t\tsuper(type, t);\n\t\t_greedy = nongreedy == null;\n\t}\n\n\t@Override\n\tpublic boolean isGreedy() {\n\t\treturn _greedy;\n\t}\n\n\t@Override\n\tpublic OptionalBlockAST dupNode() { return new OptionalBlockAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/PlusBlockAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class PlusBlockAST extends GrammarAST implements RuleElementAST, QuantifierAST {\n\tprivate final boolean _greedy;\n\n\tpublic PlusBlockAST(PlusBlockAST node) {\n\t\tsuper(node);\n\t\t_greedy = node._greedy;\n\t}\n\n\tpublic PlusBlockAST(int type, Token t, Token nongreedy) {\n\t\tsuper(type, t);\n\t\t_greedy = nongreedy == null;\n\t}\n\n\t@Override\n\tpublic boolean isGreedy() {\n\t\treturn _greedy;\n\t}\n\n\t@Override\n\tpublic PlusBlockAST dupNode() { return new PlusBlockAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/PredAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class PredAST extends ActionAST {\n\tpublic PredAST(PredAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic PredAST(Token t) { super(t); }\n    public PredAST(int type) { super(type); }\n    public PredAST(int type, Token t) { super(type, t); }\n\n\t@Override\n\tpublic PredAST dupNode() { return new PredAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/QuantifierAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\n/**\n *\n * @author Sam Harwell\n */\npublic interface QuantifierAST {\n\n\tboolean isGreedy();\n\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/RangeAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class RangeAST extends GrammarAST implements RuleElementAST {\n\n\tpublic RangeAST(RangeAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic RangeAST(Token t) { super(t); }\n\n\t@Override\n\tpublic RangeAST dupNode() {\n\t\treturn new RangeAST(this);\n\t}\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/RuleAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.tool.Grammar;\n\npublic class RuleAST extends GrammarASTWithOptions {\n\tpublic RuleAST(RuleAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic RuleAST(Token t) { super(t); }\n    public RuleAST(int type) { super(type); }\n\n\tpublic boolean isLexerRule() {\n\t\tString name = getRuleName();\n\t\treturn name!=null && Grammar.isTokenName(name);\n\t}\n\n\tpublic String getRuleName() {\n\t\tGrammarAST nameNode = (GrammarAST)getChild(0);\n\t\tif ( nameNode!=null ) return nameNode.getText();\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic RuleAST dupNode() { return new RuleAST(this); }\n\n\tpublic ActionAST getLexerAction() {\n\t\tTree blk = getFirstChildWithType(ANTLRParser.BLOCK);\n\t\tif ( blk.getChildCount()==1 ) {\n\t\t\tTree onlyAlt = blk.getChild(0);\n\t\t\tTree lastChild = onlyAlt.getChild(onlyAlt.getChildCount()-1);\n\t\t\tif ( lastChild.getType()==ANTLRParser.ACTION ) {\n\t\t\t\treturn (ActionAST)lastChild;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/RuleElementAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\n/** Tag indicated AST node is a rule element like token or rule ref. */\npublic interface RuleElementAST {\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/RuleRefAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.CommonToken;\nimport org.antlr.runtime.Token;\n\npublic class RuleRefAST extends GrammarASTWithOptions implements RuleElementAST {\n\tpublic RuleRefAST(RuleRefAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic RuleRefAST(Token t) { super(t); }\n    public RuleRefAST(int type) { super(type); }\n    public RuleRefAST(int type, Token t) { super(type, t); }\n\n\t/** Dup token too since we overwrite during LR rule transform */\n\t@Override\n\tpublic RuleRefAST dupNode() {\n\t\tRuleRefAST r = new RuleRefAST(this);\n\t\t// In LR transform, we alter original token stream to make e -> e[n]\n\t\t// Since we will be altering the dup, we need dup to have the\n\t\t// original token.  We can set this tree (the original) to have\n\t\t// a new token.\n\t\tr.token = this.token;\n\t\tthis.token = new CommonToken(r.token);\n\t\treturn r;\n\t}\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/SetAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class SetAST extends GrammarAST implements RuleElementAST {\n\n\tpublic SetAST(SetAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic SetAST(int type, Token t, String text) { super(type,t,text); }\n\n\t@Override\n\tpublic SetAST dupNode() {\n\t\treturn new SetAST(this);\n\t}\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/StarBlockAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class StarBlockAST extends GrammarAST implements RuleElementAST, QuantifierAST {\n\tprivate final boolean _greedy;\n\n\tpublic StarBlockAST(StarBlockAST node) {\n\t\tsuper(node);\n\t\t_greedy = node._greedy;\n\t}\n\n\tpublic StarBlockAST(int type, Token t, Token nongreedy) {\n\t\tsuper(type, t);\n\t\t_greedy = nongreedy == null;\n\t}\n\n\t@Override\n\tpublic boolean isGreedy() {\n\t\treturn _greedy;\n\t}\n\n\t@Override\n\tpublic StarBlockAST dupNode() { return new StarBlockAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/tool/ast/TerminalAST.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.tool.ast;\n\nimport org.antlr.runtime.Token;\n\npublic class TerminalAST extends GrammarASTWithOptions implements RuleElementAST {\n\n\tpublic TerminalAST(TerminalAST node) {\n\t\tsuper(node);\n\t}\n\n\tpublic TerminalAST(Token t) { super(t); }\n    public TerminalAST(int type) { super(type); }\n    public TerminalAST(int type, Token t) { super(type, t); }\n\n\t@Override\n\tpublic TerminalAST dupNode() { return new TerminalAST(this); }\n\n\t@Override\n\tpublic Object visit(GrammarASTVisitor v) { return v.visit(this); }\n}\n"
  },
  {
    "path": "tool/src/org/antlr/v4/unicode/UnicodeDataTemplateController.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.unicode;\n\nimport com.ibm.icu.lang.UCharacter;\nimport com.ibm.icu.lang.UProperty;\nimport com.ibm.icu.text.UnicodeSet;\nimport com.ibm.icu.util.RangeValueIterator;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.IntervalSet;\n\nimport java.util.*;\n\n/**\n * StringTemplate controller used to generate parameters to feed\n * to {@code unicodedata.st} to code-generate {@code UnicodeData.java},\n * used by the tool for Unicode property escapes like {@code \\\\p\\{Lu\\}}.\n *\n * Uses ICU to iterate over Unicode character categories, properties,\n * and script codes, as well as aliases for those codes.\n *\n * This class exists in its own Maven module to avoid adding a\n * dependency from the tool onto the (large) ICU runtime.\n */\npublic abstract class UnicodeDataTemplateController {\n\tprivate static void addIntervalForCategory(\n\t\t\tMap<String, IntervalSet> categoryMap,\n\t\t\tString categoryName,\n\t\t\tint start,\n\t\t\tint finish) {\n\t\tIntervalSet intervalSet = categoryMap.get(categoryName);\n\t\tif (intervalSet == null) {\n\t\t\tintervalSet = new IntervalSet();\n\t\t\tcategoryMap.put(categoryName, intervalSet);\n\t\t}\n\t\tintervalSet.add(start, finish);\n\t}\n\n\tprivate static void addPropertyAliases(\n\t\t\tMap<String, String> propertyAliases,\n\t\t\tString propertyName,\n\t\t\tint property) {\n\t\tint nameChoice = UProperty.NameChoice.LONG;\n\t\twhile (true) {\n\t\t\tString alias;\n\t\t\ttry {\n\t\t\t\talias = UCharacter.getPropertyName(property, nameChoice);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t// No more aliases.\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tassert alias != null;\n\t\t\taddPropertyAlias(propertyAliases, alias, propertyName);\n\t\t\tnameChoice++;\n\t\t}\n\t}\n\n\tprivate static void addPropertyAlias(\n\t\t\tMap<String, String> propertyAliases,\n\t\t\tString alias,\n\t\t\tString propertyName) {\n\t\tpropertyAliases.put(alias, propertyName);\n\t}\n\n\tpublic static Map<String, Object> getProperties() {\n\t\tMap<String, IntervalSet> propertyCodePointRanges = new LinkedHashMap<>();\n\t\taddUnicodeCategoryCodesToCodePointRanges(propertyCodePointRanges);\n\t\taddUnicodeBinaryPropertyCodesToCodePointRanges(propertyCodePointRanges);\n\t\taddUnicodeIntPropertyCodesToCodePointRanges(propertyCodePointRanges);\n\t\taddTR35ExtendedPictographicPropertyCodesToCodePointRanges(propertyCodePointRanges);\n\t\taddEmojiPresentationPropertyCodesToCodePointRanges(propertyCodePointRanges);\n\n\t\tMap<String, String> propertyAliases = new LinkedHashMap<>();\n\t\taddUnicodeCategoryCodesToNames(propertyAliases);\n\t\taddUnicodeBinaryPropertyCodesToNames(propertyAliases);\n\t\taddUnicodeScriptCodesToNames(propertyAliases);\n\t\taddUnicodeBlocksToNames(propertyAliases);\n\t\taddUnicodeIntPropertyCodesToNames(propertyAliases);\n\t\tpropertyAliases.put(\"EP\", \"Extended_Pictographic\");\n\n\t\tMap<String, List<Integer>> rawPropertyCodePointRanges = new LinkedHashMap<>();\n\t\tfor (Map.Entry<String, IntervalSet> entry : propertyCodePointRanges.entrySet()) {\n\t\t\trawPropertyCodePointRanges.put(entry.getKey().toLowerCase(Locale.US), convertToRawArray(entry.getValue()));\n\t\t}\n\t\tList<String> rawPropertyAliases = new ArrayList<>(propertyAliases.size() * 2);\n\t\tfor (Map.Entry<String, String> entry : propertyAliases.entrySet()) {\n\t\t\trawPropertyAliases.add(entry.getKey().toLowerCase(Locale.US));\n\t\t\trawPropertyAliases.add(entry.getValue().toLowerCase(Locale.US));\n\t\t}\n\n\t\tMap<String, Object> properties = new LinkedHashMap<>();\n\t\tproperties.put(\"rawPropertyCodePointRanges\", rawPropertyCodePointRanges);\n\t\tproperties.put(\"rawPropertyAliases\", rawPropertyAliases);\n\t\treturn properties;\n\t}\n\n\tprivate static List<Integer> convertToRawArray(IntervalSet intervalSet) {\n\t\tList<Interval> intervals = intervalSet.getIntervals();\n\t\tint intervalSetSize = intervals.size();\n\t\tList<Integer> rawArray = new ArrayList<>(intervalSetSize * 2);\n\t\tfor (Interval interval : intervals) {\n\t\t\trawArray.add(interval.a);\n\t\t\trawArray.add(interval.b);\n\t\t}\n\t\treturn rawArray;\n\t}\n\n\tprivate static String getShortPropertyName(int property) {\n\t\tString propertyName = UCharacter.getPropertyName(property, UProperty.NameChoice.SHORT);\n\t\t// For some reason, a few properties only have long names.\n\t\tif (propertyName == null) {\n\t\t\tpropertyName = UCharacter.getPropertyName(property, UProperty.NameChoice.LONG);\n\t\t}\n\t\treturn propertyName;\n\t}\n\n\tprivate static void addUnicodeCategoryCodesToCodePointRanges(Map<String, IntervalSet> propertyCodePointRanges) {\n\t\tRangeValueIterator iter = UCharacter.getTypeIterator();\n\t\tRangeValueIterator.Element element = new RangeValueIterator.Element();\n\t\twhile (iter.next(element)) {\n\t\t\tString categoryName = UCharacter.getPropertyValueName(\n\t\t\t\t\tUProperty.GENERAL_CATEGORY_MASK,\n\t\t\t\t\t1 << element.value,\n\t\t\t\t\tUProperty.NameChoice.SHORT);\n\t\t\taddIntervalForCategory(propertyCodePointRanges, categoryName, element.start, element.limit - 1);\n\t\t\t// Add short category so Ll, Lu, Lo, etc. all show up under L\n\t\t\tString shortCategoryName = categoryName.substring(0, 1);\n\t\t\taddIntervalForCategory(propertyCodePointRanges, shortCategoryName, element.start, element.limit - 1);\n\t\t}\n\t}\n\n\tprivate static void addUnicodeCategoryCodesToNames(Map<String, String> propertyAliases) {\n\t\tRangeValueIterator iter = UCharacter.getTypeIterator();\n\t\tRangeValueIterator.Element element = new RangeValueIterator.Element();\n\t\twhile (iter.next(element)) {\n\t\t\tint generalCategoryMask = 1 << element.value;\n\t\t\tString categoryName = UCharacter.getPropertyValueName(\n\t\t\t\t\tUProperty.GENERAL_CATEGORY_MASK,\n\t\t\t\t\tgeneralCategoryMask,\n\t\t\t\t\tUProperty.NameChoice.SHORT);\n\t\t\tint nameChoice = UProperty.NameChoice.LONG;\n\t\t\twhile (true) {\n\t\t\t\tString alias;\n\t\t\t\ttry {\n\t\t\t\t\talias = UCharacter.getPropertyValueName(\n\t\t\t\t\t\t\tUProperty.GENERAL_CATEGORY_MASK,\n\t\t\t\t\t\t\tgeneralCategoryMask,\n\t\t\t\t\t\t\tnameChoice);\n\t\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t\t// No more aliases.\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tassert alias != null;\n\t\t\t\taddPropertyAlias(propertyAliases, alias, categoryName);\n\t\t\t\tnameChoice++;\n\t\t\t}\n\t\t}\n\t\t// Add short categories\n\t\taddPropertyAlias(propertyAliases, \"Control\", \"C\");\n\t\taddPropertyAlias(propertyAliases, \"Letter\", \"L\");\n\t\taddPropertyAlias(propertyAliases, \"Number\", \"N\");\n\t\taddPropertyAlias(propertyAliases, \"Mark\", \"M\");\n\t\taddPropertyAlias(propertyAliases, \"Punctuation\", \"P\");\n\t\taddPropertyAlias(propertyAliases, \"Symbol\", \"S\");\n\t\taddPropertyAlias(propertyAliases, \"Space\", \"Z\");\n\t}\n\n\tprivate static void addUnicodeBinaryPropertyCodesToCodePointRanges(Map<String, IntervalSet> propertyCodePointRanges) {\n\t\tfor (int property = UProperty.BINARY_START;\n\t\t     property < UProperty.BINARY_LIMIT;\n\t\t     property++) {\n\t\t\tString propertyName = getShortPropertyName(property);\n\t\t\tIntervalSet intervalSet = new IntervalSet();\n\t\t\tUnicodeSet unicodeSet = new UnicodeSet();\n\t\t\tunicodeSet.applyIntPropertyValue(property, 1);\n\t\t\tfor (UnicodeSet.EntryRange range : unicodeSet.ranges()) {\n\t\t\t\tintervalSet.add(range.codepoint, range.codepointEnd);\n\t\t\t}\n\t\t\tpropertyCodePointRanges.put(propertyName, intervalSet);\n\t\t}\n\t}\n\n\tprivate static void addUnicodeBinaryPropertyCodesToNames(Map<String, String> propertyAliases) {\n\t\tfor (int property = UProperty.BINARY_START;\n\t\t     property < UProperty.BINARY_LIMIT;\n\t\t     property++) {\n\t\t\tString propertyName = getShortPropertyName(property);\n\t\t\taddPropertyAliases(propertyAliases, propertyName, property);\n\t\t}\n\t}\n\n\tprivate static void addIntPropertyRanges(int property, String namePrefix, Map<String, IntervalSet> propertyCodePointRanges) {\n\t\tfor (int propertyValue = UCharacter.getIntPropertyMinValue(property);\n\t\t     propertyValue <= UCharacter.getIntPropertyMaxValue(property);\n\t\t     propertyValue++) {\n\t\t\tUnicodeSet set = new UnicodeSet();\n\t\t\tset.applyIntPropertyValue(property, propertyValue);\n\t\t\tString propertyName = namePrefix + UCharacter.getPropertyValueName(property, propertyValue, UProperty.NameChoice.SHORT);\n\t\t\tIntervalSet intervalSet = propertyCodePointRanges.get(propertyName);\n\t\t\tif (intervalSet == null) {\n\t\t\t\tintervalSet = new IntervalSet();\n\t\t\t\tpropertyCodePointRanges.put(propertyName, intervalSet);\n\t\t\t}\n\t\t\taddUnicodeSetToIntervalSet(set, intervalSet);\n\t\t}\n\t}\n\n\tprivate static void addUnicodeSetToIntervalSet(UnicodeSet unicodeSet, IntervalSet intervalSet) {\n\t\tfor (UnicodeSet.EntryRange range : unicodeSet.ranges()) {\n\t\t\tintervalSet.add(range.codepoint, range.codepointEnd);\n\t\t}\n\t}\n\n\tprivate static void addUnicodeIntPropertyCodesToCodePointRanges(Map<String, IntervalSet> propertyCodePointRanges) {\n\t\tfor (int property = UProperty.INT_START;\n\t\t     property < UProperty.INT_LIMIT;\n\t\t     property++) {\n\t\t\tString propertyName = getShortPropertyName(property);\n\t\t\taddIntPropertyRanges(property, propertyName + \"=\", propertyCodePointRanges);\n\t\t}\n\t}\n\n\tprivate static void addTR35ExtendedPictographicPropertyCodesToCodePointRanges(Map<String, IntervalSet> propertyCodePointRanges) {\n\t\tIntervalSet set = new IntervalSet();\n\t\t// Generated using scripts/parse-extended-pictographic/parse.py\n\t\tset.add(0x1F774, 0x1F77F);\n\t\tset.add(0x2700, 0x2701);\n\t\tset.add(0x2703, 0x2704);\n\t\tset.add(0x270E);\n\t\tset.add(0x2710, 0x2711);\n\t\tset.add(0x2765, 0x2767);\n\t\tset.add(0x1F030, 0x1F093);\n\t\tset.add(0x1F094, 0x1F09F);\n\t\tset.add(0x1F10D, 0x1F10F);\n\t\tset.add(0x1F12F);\n\t\tset.add(0x1F16C, 0x1F16F);\n\t\tset.add(0x1F1AD, 0x1F1E5);\n\t\tset.add(0x1F260, 0x1F265);\n\t\tset.add(0x1F203, 0x1F20F);\n\t\tset.add(0x1F23C, 0x1F23F);\n\t\tset.add(0x1F249, 0x1F24F);\n\t\tset.add(0x1F252, 0x1F25F);\n\t\tset.add(0x1F266, 0x1F2FF);\n\t\tset.add(0x1F7D5, 0x1F7FF);\n\t\tset.add(0x1F000, 0x1F003);\n\t\tset.add(0x1F005, 0x1F02B);\n\t\tset.add(0x1F02C, 0x1F02F);\n\t\tset.add(0x1F322, 0x1F323);\n\t\tset.add(0x1F394, 0x1F395);\n\t\tset.add(0x1F398);\n\t\tset.add(0x1F39C, 0x1F39D);\n\t\tset.add(0x1F3F1, 0x1F3F2);\n\t\tset.add(0x1F3F6);\n\t\tset.add(0x1F4FE);\n\t\tset.add(0x1F53E, 0x1F548);\n\t\tset.add(0x1F54F);\n\t\tset.add(0x1F568, 0x1F56E);\n\t\tset.add(0x1F571, 0x1F572);\n\t\tset.add(0x1F57B, 0x1F586);\n\t\tset.add(0x1F588, 0x1F589);\n\t\tset.add(0x1F58E, 0x1F58F);\n\t\tset.add(0x1F591, 0x1F594);\n\t\tset.add(0x1F597, 0x1F5A3);\n\t\tset.add(0x1F5A6, 0x1F5A7);\n\t\tset.add(0x1F5A9, 0x1F5B0);\n\t\tset.add(0x1F5B3, 0x1F5BB);\n\t\tset.add(0x1F5BD, 0x1F5C1);\n\t\tset.add(0x1F5C5, 0x1F5D0);\n\t\tset.add(0x1F5D4, 0x1F5DB);\n\t\tset.add(0x1F5DF, 0x1F5E0);\n\t\tset.add(0x1F5E2);\n\t\tset.add(0x1F5E4, 0x1F5E7);\n\t\tset.add(0x1F5E9, 0x1F5EE);\n\t\tset.add(0x1F5F0, 0x1F5F2);\n\t\tset.add(0x1F5F4, 0x1F5F9);\n\t\tset.add(0x2605);\n\t\tset.add(0x2607, 0x260D);\n\t\tset.add(0x260F, 0x2610);\n\t\tset.add(0x2612);\n\t\tset.add(0x2616, 0x2617);\n\t\tset.add(0x2619, 0x261C);\n\t\tset.add(0x261E, 0x261F);\n\t\tset.add(0x2621);\n\t\tset.add(0x2624, 0x2625);\n\t\tset.add(0x2627, 0x2629);\n\t\tset.add(0x262B, 0x262D);\n\t\tset.add(0x2630, 0x2637);\n\t\tset.add(0x263B, 0x2647);\n\t\tset.add(0x2654, 0x265F);\n\t\tset.add(0x2661, 0x2662);\n\t\tset.add(0x2664);\n\t\tset.add(0x2667);\n\t\tset.add(0x2669, 0x267A);\n\t\tset.add(0x267C, 0x267E);\n\t\tset.add(0x2680, 0x2691);\n\t\tset.add(0x2695);\n\t\tset.add(0x2698);\n\t\tset.add(0x269A);\n\t\tset.add(0x269D, 0x269F);\n\t\tset.add(0x26A2, 0x26A9);\n\t\tset.add(0x26AC, 0x26AF);\n\t\tset.add(0x26B2, 0x26BC);\n\t\tset.add(0x26BF, 0x26C3);\n\t\tset.add(0x26C6, 0x26C7);\n\t\tset.add(0x26C9, 0x26CD);\n\t\tset.add(0x26D0);\n\t\tset.add(0x26D2);\n\t\tset.add(0x26D5, 0x26E8);\n\t\tset.add(0x26EB, 0x26EF);\n\t\tset.add(0x26F6);\n\t\tset.add(0x26FB, 0x26FC);\n\t\tset.add(0x26FE, 0x26FF);\n\t\tset.add(0x2388);\n\t\tset.add(0x1FA00, 0x1FFFD);\n\t\tset.add(0x1F0A0, 0x1F0AE);\n\t\tset.add(0x1F0B1, 0x1F0BF);\n\t\tset.add(0x1F0C1, 0x1F0CF);\n\t\tset.add(0x1F0D1, 0x1F0F5);\n\t\tset.add(0x1F0AF, 0x1F0B0);\n\t\tset.add(0x1F0C0);\n\t\tset.add(0x1F0D0);\n\t\tset.add(0x1F0F6, 0x1F0FF);\n\t\tset.add(0x1F80C, 0x1F80F);\n\t\tset.add(0x1F848, 0x1F84F);\n\t\tset.add(0x1F85A, 0x1F85F);\n\t\tset.add(0x1F888, 0x1F88F);\n\t\tset.add(0x1F8AE, 0x1F8FF);\n\t\tset.add(0x1F900, 0x1F90B);\n\t\tset.add(0x1F91F);\n\t\tset.add(0x1F928, 0x1F92F);\n\t\tset.add(0x1F931, 0x1F932);\n\t\tset.add(0x1F94C);\n\t\tset.add(0x1F95F, 0x1F96B);\n\t\tset.add(0x1F992, 0x1F997);\n\t\tset.add(0x1F9D0, 0x1F9E6);\n\t\tset.add(0x1F90C, 0x1F90F);\n\t\tset.add(0x1F93F);\n\t\tset.add(0x1F94D, 0x1F94F);\n\t\tset.add(0x1F96C, 0x1F97F);\n\t\tset.add(0x1F998, 0x1F9BF);\n\t\tset.add(0x1F9C1, 0x1F9CF);\n\t\tset.add(0x1F9E7, 0x1F9FF);\n\t\tset.add(0x1F6C6, 0x1F6CA);\n\t\tset.add(0x1F6D3, 0x1F6D4);\n\t\tset.add(0x1F6E6, 0x1F6E8);\n\t\tset.add(0x1F6EA);\n\t\tset.add(0x1F6F1, 0x1F6F2);\n\t\tset.add(0x1F6F7, 0x1F6F8);\n\t\tset.add(0x1F6D5, 0x1F6DF);\n\t\tset.add(0x1F6ED, 0x1F6EF);\n\t\tset.add(0x1F6F9, 0x1F6FF);\n\t\tpropertyCodePointRanges.put(\"Extended_Pictographic\", set);\n\n\t\tUnicodeSet emojiRKUnicodeSet = new UnicodeSet(\"[\\\\p{GCB=Regional_Indicator}\\\\*#0-9\\\\u00a9\\\\u00ae\\\\u2122\\\\u3030\\\\u303d]\");\n\t\tIntervalSet emojiRKIntervalSet = new IntervalSet();\n\t\taddUnicodeSetToIntervalSet(emojiRKUnicodeSet, emojiRKIntervalSet);\n\t\tpropertyCodePointRanges.put(\"EmojiRK\", emojiRKIntervalSet);\n\n\t\tUnicodeSet emojiNRKUnicodeSet = new UnicodeSet(\"[\\\\p{Emoji=Yes}]\");\n\t\temojiNRKUnicodeSet.removeAll(emojiRKUnicodeSet);\n\t\tIntervalSet emojiNRKIntervalSet = new IntervalSet();\n\t\taddUnicodeSetToIntervalSet(emojiNRKUnicodeSet, emojiNRKIntervalSet);\n\t\tpropertyCodePointRanges.put(\"EmojiNRK\", emojiNRKIntervalSet);\n\t}\n\n\tprivate static void addEmojiPresentationPropertyCodesToCodePointRanges(Map<String, IntervalSet> propertyCodePointRanges) {\n\t\tUnicodeSet emojiDefaultUnicodeSet = new UnicodeSet(\"[[\\\\p{Emoji=Yes}]&[\\\\p{Emoji_Presentation=Yes}]]\");\n\t\tIntervalSet emojiDefaultIntervalSet = new IntervalSet();\n\t\taddUnicodeSetToIntervalSet(emojiDefaultUnicodeSet, emojiDefaultIntervalSet);\n\t\tpropertyCodePointRanges.put(\"EmojiPresentation=EmojiDefault\", emojiDefaultIntervalSet);\n\n\t\tUnicodeSet textDefaultUnicodeSet = new UnicodeSet(\"[[\\\\p{Emoji=Yes}]&[\\\\p{Emoji_Presentation=No}]]\");\n\t\tIntervalSet textDefaultIntervalSet = new IntervalSet();\n\t\taddUnicodeSetToIntervalSet(textDefaultUnicodeSet, textDefaultIntervalSet);\n\t\tpropertyCodePointRanges.put(\"EmojiPresentation=TextDefault\", textDefaultIntervalSet);\n\n\t\tUnicodeSet textUnicodeSet = new UnicodeSet(\"[\\\\p{Emoji=No}]\");\n\t\tIntervalSet textIntervalSet = new IntervalSet();\n\t\taddUnicodeSetToIntervalSet(textUnicodeSet, textIntervalSet);\n\t\tpropertyCodePointRanges.put(\"EmojiPresentation=Text\", textIntervalSet);\n        }\n\n\tprivate static void addIntPropertyAliases(int property, String namePrefix, Map<String, String> propertyAliases) {\n\t\tString propertyName = getShortPropertyName(property);\n\t\tfor (int propertyValue = UCharacter.getIntPropertyMinValue(property);\n\t\t     propertyValue <= UCharacter.getIntPropertyMaxValue(property);\n\t\t     propertyValue++) {\n\t\t\tString aliasTarget = propertyName + \"=\" + UCharacter.getPropertyValueName(property, propertyValue, UProperty.NameChoice.SHORT);\n\t\t\tint nameChoice = UProperty.NameChoice.SHORT;\n\t\t\tString alias;\n\t\t\twhile (true) {\n\t\t\t\ttry {\n\t\t\t\t\talias = namePrefix + UCharacter.getPropertyValueName(property, propertyValue, nameChoice);\n\t\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t\t// No more aliases.\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tassert alias != null;\n\t\t\t\taddPropertyAlias(propertyAliases, alias, aliasTarget);\n\t\t\t\tnameChoice++;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void addUnicodeScriptCodesToNames(Map<String, String> propertyAliases) {\n\t\taddIntPropertyAliases(UProperty.SCRIPT, \"\", propertyAliases);\n\t}\n\n\tprivate static void addUnicodeBlocksToNames(Map<String, String> propertyAliases) {\n\t\taddIntPropertyAliases(UProperty.BLOCK, \"In\", propertyAliases);\n\t}\n\n\tprivate static void addUnicodeIntPropertyCodesToNames(Map<String, String> propertyAliases) {\n\t\tfor (int property = UProperty.INT_START;\n\t\t     property < UProperty.INT_LIMIT;\n\t\t     property++) {\n\t\t\tint nameChoice = UProperty.NameChoice.SHORT + 1;\n\t\t\twhile (true) {\n\t\t\t\tString propertyNameAlias;\n\t\t\t\ttry {\n\t\t\t\t\tpropertyNameAlias = UCharacter.getPropertyName(property, nameChoice);\n\t\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t\t// No more aliases.\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\taddIntPropertyAliases(property, propertyNameAlias + \"=\", propertyAliases);\n\t\t\t\tnameChoice++;\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/pom.xml",
    "content": "<!--\n  ~ Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n  ~ Use of this file is governed by the BSD 3-clause license that\n  ~ can be found in the LICENSE.txt file in the project root.\n  -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.antlr</groupId>\n    <artifactId>antlr4-master</artifactId>\n    <version>4.13.3-SNAPSHOT</version>\n  </parent>\n  <artifactId>antlr4-tool-testsuite</artifactId>\n  <name>ANTLR 4 Tool Tests</name>\n  <description>A collection of tests for ANTLR 4 Runtime libraries.</description>\n\n    <prerequisites>\n        <maven>3.8</maven>\n    </prerequisites>\n\n  <inceptionYear>2009</inceptionYear>\n\n  <properties>\n    <jUnitVersion>5.9.0</jUnitVersion>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.antlr</groupId>\n      <artifactId>ST4</artifactId>\n      <version>4.3.4</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.antlr</groupId>\n      <artifactId>antlr4-runtime-testsuite</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n      <type>test-jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.antlr</groupId>\n      <artifactId>antlr4</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n        <groupId>org.junit.jupiter</groupId>\n        <artifactId>junit-jupiter-api</artifactId>\n        <version>${jUnitVersion}</version>\n        <scope>test</scope>\n    </dependency>\n    <dependency>\n        <groupId>org.junit.jupiter</groupId>\n        <artifactId>junit-jupiter-engine</artifactId>\n        <version>${jUnitVersion}</version>\n        <scope>test</scope>\n    </dependency>\n    <dependency>\n        <groupId>org.junit.jupiter</groupId>\n        <artifactId>junit-jupiter-params</artifactId>\n        <version>${jUnitVersion}</version>\n        <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <build>\n    <testSourceDirectory>test</testSourceDirectory>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-surefire-plugin</artifactId>\n        <version>2.22.2</version>\n        <configuration>\n          <!-- SUREFIRE-951: file.encoding cannot be set via systemPropertyVariables -->\n          <argLine>-Dfile.encoding=UTF-8</argLine>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "tool-testsuite/resources/junit-platform.properties",
    "content": "junit.jupiter.execution.parallel.enabled = true\njunit.jupiter.execution.parallel.mode.default = concurrent\njunit.jupiter.execution.parallel.mode.classes.default = concurrent"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/ATNDescriber.java",
    "content": "package org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.atn.*;\n\nimport java.io.InvalidClassException;\nimport java.util.List;\n\n/** Make human readable set of ints from serialized ATN like this (for debugging / testing):\n *\n * max type 1\n * 0:TOKEN_START -1\n * 1:RULE_START 0\n * 2:RULE_STOP 0\n * 3:BASIC 0\n * 4:BASIC 0\n * rule 0:1 1\n * mode 0:0\n * 0:'a'..128169\n * 0->1 EPSILON 0,0,0\n * 1->3 EPSILON 0,0,0\n * 3->4 SET 0,0,0\n * 4->2 EPSILON 0,0,0\n * 0:0\n */\npublic class ATNDescriber {\n\tpublic ATN atn;\n\tprivate List<String> tokenNames;\n\n\tpublic ATNDescriber(ATN atn, List<String> tokenNames) {\n\t\tassert atn.grammarType != null;\n\t\tthis.atn = atn;\n\t\tthis.tokenNames = tokenNames;\n\t}\n\n\t/** For testing really; gives a human readable version of the ATN */\n\tpublic String decode(int[] data) {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tint p = 0;\n\t\tint version = data[p++];\n\t\tif (version != ATNDeserializer.SERIALIZED_VERSION) {\n\t\t\tString reason = String.format(\"Could not deserialize ATN with version %d (expected %d).\", version, ATNDeserializer.SERIALIZED_VERSION);\n\t\t\tthrow new UnsupportedOperationException(new InvalidClassException(ATN.class.getName(), reason));\n\t\t}\n\n\t\tp++; // skip grammarType\n\t\tint maxType = data[p++];\n\t\tbuf.append(\"max type \").append(maxType).append(\"\\n\");\n\t\tint nstates = data[p++];\n\t\tfor (int i=0; i<nstates; i++) {\n\t\t\tint stype = data[p++];\n\t\t\tif ( stype== ATNState.INVALID_TYPE ) continue; // ignore bad type of states\n\t\t\tint ruleIndex = data[p++];\n\t\t\tif (ruleIndex == Character.MAX_VALUE) {\n\t\t\t\truleIndex = -1;\n\t\t\t}\n\n\t\t\tString arg = \"\";\n\t\t\tif ( stype == ATNState.LOOP_END ) {\n\t\t\t\tint loopBackStateNumber = data[p++];\n\t\t\t\targ = \" \"+loopBackStateNumber;\n\t\t\t}\n\t\t\telse if ( stype == ATNState.PLUS_BLOCK_START || stype == ATNState.STAR_BLOCK_START || stype == ATNState.BLOCK_START ) {\n\t\t\t\tint endStateNumber = data[p++];\n\t\t\t\targ = \" \"+endStateNumber;\n\t\t\t}\n\t\t\tbuf.append(i).append(\":\")\n\t\t\t\t\t.append(ATNState.serializationNames.get(stype)).append(\" \")\n\t\t\t\t\t.append(ruleIndex).append(arg).append(\"\\n\");\n\t\t}\n\t\t// this code is meant to model the form of ATNDeserializer.deserialize,\n\t\t// since both need to be updated together whenever a change is made to\n\t\t// the serialization format. The \"dead\" code is only used in debugging\n\t\t// and testing scenarios, so the form you see here was kept for\n\t\t// improved maintainability.\n\t\t// start\n\t\tint numNonGreedyStates = data[p++];\n\t\tfor (int i = 0; i < numNonGreedyStates; i++) {\n\t\t\tint stateNumber = data[p++];\n\t\t}\n\t\tint numPrecedenceStates = data[p++];\n\t\tfor (int i = 0; i < numPrecedenceStates; i++) {\n\t\t\tint stateNumber = data[p++];\n\t\t}\n\t\t// finish\n\t\tint nrules = data[p++];\n\t\tfor (int i=0; i<nrules; i++) {\n\t\t\tint s = data[p++];\n\t\t\tif (atn.grammarType == ATNType.LEXER) {\n\t\t\t\tint arg1 = data[p++];\n\t\t\t\tbuf.append(\"rule \").append(i).append(\":\").append(s).append(\" \").append(arg1).append('\\n');\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbuf.append(\"rule \").append(i).append(\":\").append(s).append('\\n');\n\t\t\t}\n\t\t}\n\t\tint nmodes = data[p++];\n\t\tfor (int i=0; i<nmodes; i++) {\n\t\t\tint s = data[p++];\n\t\t\tbuf.append(\"mode \").append(i).append(\":\").append(s).append('\\n');\n\t\t}\n\t\tint numBMPSets = data[p++];\n\t\tp = appendSets(buf, data, p, numBMPSets);\n\t\tint nedges = data[p++];\n\t\tfor (int i=0; i<nedges; i++) {\n\t\t\tint src = data[p];\n\t\t\tint trg = data[p + 1];\n\t\t\tint ttype = data[p + 2];\n\t\t\tint arg1 = data[p + 3];\n\t\t\tint arg2 = data[p + 4];\n\t\t\tint arg3 = data[p + 5];\n\t\t\tbuf.append(src).append(\"->\").append(trg)\n\t\t\t\t\t.append(\" \").append(Transition.serializationNames.get(ttype))\n\t\t\t\t\t.append(\" \").append(arg1).append(\",\").append(arg2).append(\",\").append(arg3)\n\t\t\t\t\t.append(\"\\n\");\n\t\t\tp += 6;\n\t\t}\n\t\tint ndecisions = data[p++];\n\t\tfor (int i=0; i<ndecisions; i++) {\n\t\t\tint s = data[p++];\n\t\t\tbuf.append(i).append(\":\").append(s).append(\"\\n\");\n\t\t}\n\t\tif (atn.grammarType == ATNType.LEXER) {\n\t\t\t// this code is meant to model the form of ATNDeserializer.deserialize,\n\t\t\t// since both need to be updated together whenever a change is made to\n\t\t\t// the serialization format. The \"dead\" code is only used in debugging\n\t\t\t// and testing scenarios, so the form you see here was kept for\n\t\t\t// improved maintainability.\n\t\t\tint lexerActionCount = data[p++];\n\t\t\tfor (int i = 0; i < lexerActionCount; i++) {\n\t\t\t\tLexerActionType actionType = LexerActionType.values()[data[p++]];\n\t\t\t\tint data1 = data[p++];\n\t\t\t\tint data2 = data[p++];\n\t\t\t}\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tprivate int appendSets(StringBuilder buf, int[] data, int p, int nsets) {\n\t\tfor (int i=0; i<nsets; i++) {\n\t\t\tint nintervals = data[p++];\n\t\t\tbuf.append(i).append(\":\");\n\t\t\tboolean containsEof = data[p++] != 0;\n\t\t\tif (containsEof) {\n\t\t\t\tbuf.append(getTokenName(Token.EOF));\n\t\t\t}\n\n\t\t\tfor (int j=0; j<nintervals; j++) {\n\t\t\t\tif ( containsEof || j>0 ) {\n\t\t\t\t\tbuf.append(\", \");\n\t\t\t\t}\n\n\t\t\t\tint a = data[p++];\n\t\t\t\tint b = data[p++];\n\t\t\t\tbuf.append(getTokenName(a)).append(\"..\").append(getTokenName(b));\n\t\t\t}\n\t\t\tbuf.append(\"\\n\");\n\t\t}\n\t\treturn p;\n\t}\n\n\tpublic String getTokenName(int t) {\n\t\tif ( t==-1 ) return \"EOF\";\n\n\t\tif ( atn.grammarType == ATNType.LEXER &&\n\t\t\t\tt >= Character.MIN_VALUE && t <= Character.MAX_VALUE )\n\t\t{\n\t\t\tswitch (t) {\n\t\t\t\tcase '\\n':\n\t\t\t\t\treturn \"'\\\\n'\";\n\t\t\t\tcase '\\r':\n\t\t\t\t\treturn \"'\\\\r'\";\n\t\t\t\tcase '\\t':\n\t\t\t\t\treturn \"'\\\\t'\";\n\t\t\t\tcase '\\b':\n\t\t\t\t\treturn \"'\\\\b'\";\n\t\t\t\tcase '\\f':\n\t\t\t\t\treturn \"'\\\\f'\";\n\t\t\t\tcase '\\\\':\n\t\t\t\t\treturn \"'\\\\\\\\'\";\n\t\t\t\tcase '\\'':\n\t\t\t\t\treturn \"'\\\\''\";\n\t\t\t\tdefault:\n\t\t\t\t\tif ( Character.UnicodeBlock.of((char)t)==Character.UnicodeBlock.BASIC_LATIN &&\n\t\t\t\t\t\t\t!Character.isISOControl((char)t) ) {\n\t\t\t\t\t\treturn '\\''+Character.toString((char)t)+'\\'';\n\t\t\t\t\t}\n\t\t\t\t\t// turn on the bit above max \"\\uFFFF\" value so that we pad with zeros\n\t\t\t\t\t// then only take last 4 digits\n\t\t\t\t\tString hex = Integer.toHexString(t|0x10000).toUpperCase().substring(1,5);\n\t\t\t\t\tString unicodeStr = \"'\\\\u\"+hex+\"'\";\n\t\t\t\t\treturn unicodeStr;\n\t\t\t}\n\t\t}\n\n\t\tif (tokenNames != null && t >= 0 && t < tokenNames.size()) {\n\t\t\treturn tokenNames.get(t);\n\t\t}\n\n\t\treturn String.valueOf(t);\n\t}\n\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/InterpreterTreeTextProvider.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.gui.TreeTextProvider;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.Tree;\nimport org.antlr.v4.runtime.tree.Trees;\n\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class InterpreterTreeTextProvider implements TreeTextProvider {\n\tpublic List<String> ruleNames;\n\tpublic InterpreterTreeTextProvider(String[] ruleNames) {this.ruleNames = Arrays.asList(ruleNames);}\n\n\t@Override\n\tpublic String getText(Tree node) {\n\t\tif ( node==null ) return \"null\";\n\t\tString nodeText = Trees.getNodeText(node, ruleNames);\n\t\tif ( node instanceof ErrorNode) {\n\t\t\treturn \"<error \"+nodeText+\">\";\n\t\t}\n\t\treturn nodeText;\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/Java.g4",
    "content": "/*\n [The \"BSD licence\"]\n Copyright (c) 2007-2008 Terence Parr\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/** A Java 1.5 grammar for ANTLR v3 derived from the spec\n *\n *  This is a very close representation of the spec; the changes\n *  are comestic (remove left recursion) and also fixes (the spec\n *  isn't exactly perfect).  I have run this on the 1.4.2 source\n *  and some nasty looking enums from 1.5, but have not really\n *  tested for 1.5 compatibility.\n *\n *  I built this with: java -Xmx100M org.antlr.Tool java.g \n *  and got two errors that are ok (for now):\n *  java.g:691:9: Decision can match input such as\n *    \"'0'..'9'{'E', 'e'}{'+', '-'}'0'..'9'{'D', 'F', 'd', 'f'}\"\n *    using multiple alternatives: 3, 4\n *  As a result, alternative(s) 4 were disabled for that input\n *  java.g:734:35: Decision can match input such as \"{'$', 'A'..'Z',\n *    '_', 'a'..'z', '\\u00C0'..'\\u00D6', '\\u00D8'..'\\u00F6',\n *    '\\u00F8'..'\\u1FFF', '\\u3040'..'\\u318F', '\\u3300'..'\\u337F',\n *    '\\u3400'..'\\u3D2D', '\\u4E00'..'\\u9FFF', '\\uF900'..'\\uFAFF'}\"\n *    using multiple alternatives: 1, 2\n *  As a result, alternative(s) 2 were disabled for that input\n *\n *  You can turn enum on/off as a keyword :)\n *\n *  Version 1.0 -- initial release July 5, 2006 (requires 3.0b2 or higher)\n *\n *  Primary author: Terence Parr, July 2006\n *\n *  Version 1.0.1 -- corrections by Koen Vanderkimpen & Marko van Dooren,\n *      October 25, 2006;\n *      fixed normalInterfaceDeclaration: now uses typeParameters instead\n *          of typeParameter (according to JLS, 3rd edition)\n *      fixed castExpression: no longer allows expression next to type\n *          (according to semantics in JLS, in contrast with syntax in JLS)\n *\n *  Version 1.0.2 -- Terence Parr, Nov 27, 2006\n *      java spec I built this from had some bizarre for-loop control.\n *          Looked weird and so I looked elsewhere...Yep, it's messed up.\n *          simplified.\n *\n *  Version 1.0.3 -- Chris Hogue, Feb 26, 2007\n *      Factored out an annotationName rule and used it in the annotation rule.\n *          Not sure why, but typeName wasn't recognizing references to inner\n *          annotations (e.g. @InterfaceName.InnerAnnotation())\n *      Factored out the elementValue section of an annotation reference.  Created \n *          elementValuePair and elementValuePairs rules, then used them in the \n *          annotation rule.  Allows it to recognize annotation references with \n *          multiple, comma separated attributes.\n *      Updated elementValueArrayInitializer so that it allows multiple elements.\n *          (It was only allowing 0 or 1 element).\n *      Updated localVariableDeclaration to allow annotations.  Interestingly the JLS\n *          doesn't appear to indicate this is legal, but it does work as of at least\n *          JDK 1.5.0_06.\n *      Moved the Identifier portion of annotationTypeElementRest to annotationMethodRest.\n *          Because annotationConstantRest already references variableDeclarator which \n *          has the Identifier portion in it, the parser would fail on constants in \n *          annotation definitions because it expected two identifiers.  \n *      Added optional trailing ';' to the alternatives in annotationTypeElementRest.\n *          Wouldn't handle an inner interface that has a trailing ';'.\n *      Swapped the expression and type rule reference order in castExpression to \n *          make it check for genericized casts first.  It was failing to recognize a\n *          statement like  \"Class<Byte> TYPE = (Class<Byte>)...;\" because it was seeing\n *          'Class<Byte' in the cast expression as a less than expression, then failing \n *          on the '>'.\n *      Changed createdName to use typeArguments instead of nonWildcardTypeArguments.\n *      Changed the 'this' alternative in primary to allow 'identifierSuffix' rather than\n *          just 'arguments'.  The case it couldn't handle was a call to an explicit\n *          generic method invocation (e.g. this.<E>doSomething()).  Using identifierSuffix\n *          may be overly aggressive--perhaps should create a more constrained thisSuffix rule?\n *      \n *  Version 1.0.4 -- Hiroaki Nakamura, May 3, 2007\n *\n *  Fixed formalParameterDecls, localVariableDeclaration, forInit,\n *  and forVarControl to use variableModifier* not 'final'? (annotation)?\n *\n *  Version 1.0.5 -- Terence, June 21, 2007\n *  --a[i].foo didn't work. Fixed unaryExpression\n *\n *  Version 1.0.6 -- John Ridgway, March 17, 2008\n *      Made \"assert\" a switchable keyword like \"enum\".\n *      Fixed compilationUnit to disallow \"annotation importDeclaration ...\".\n *      Changed \"Identifier ('.' Identifier)*\" to \"qualifiedName\" in more \n *          places.\n *      Changed modifier* and/or variableModifier* to classOrInterfaceModifiers,\n *          modifiers or variableModifiers, as appropriate.\n *      Renamed \"bound\" to \"typeBound\" to better match language in the JLS.\n *      Added \"memberDeclaration\" which rewrites to methodDeclaration or \n *      fieldDeclaration and pulled type into memberDeclaration.  So we parse \n *          type and then move on to decide whether we're dealing with a field\n *          or a method.\n *      Modified \"constructorDeclaration\" to use \"constructorBody\" instead of\n *          \"methodBody\".  constructorBody starts with explicitConstructorInvocation,\n *          then goes on to blockStatement*.  Pulling explicitConstructorInvocation\n *          out of expressions allowed me to simplify \"primary\".\n *      Changed variableDeclarator to simplify it.\n *      Changed type to use classOrInterfaceType, thus simplifying it; of course\n *          I then had to add classOrInterfaceType, but it is used in several \n *          places.\n *      Fixed annotations, old version allowed \"@X(y,z)\", which is illegal.\n *      Added optional comma to end of \"elementValueArrayInitializer\"; as per JLS.\n *      Changed annotationTypeElementRest to use normalClassDeclaration and \n *          normalInterfaceDeclaration rather than classDeclaration and \n *          interfaceDeclaration, thus getting rid of a couple of grammar ambiguities.\n *      Split localVariableDeclaration into localVariableDeclarationStatement\n *          (includes the terminating semi-colon) and localVariableDeclaration.  \n *          This allowed me to use localVariableDeclaration in \"forInit\" clauses,\n *           simplifying them.\n *      Changed switchBlockStatementGroup to use multiple labels.  This adds an\n *          ambiguity, but if one uses appropriately greedy parsing it yields the\n *           parse that is closest to the meaning of the switch statement.\n *      Renamed \"forVarControl\" to \"enhancedForControl\" -- JLS language.\n *      Added semantic predicates to test for shift operations rather than other\n *          things.  Thus, for instance, the string \"< <\" will never be treated\n *          as a left-shift operator.\n *      In \"creator\" we rule out \"nonWildcardTypeArguments\" on arrayCreation, \n *          which are illegal.\n *      Moved \"nonWildcardTypeArguments into innerCreator.\n *      Removed 'super' superSuffix from explicitGenericInvocation, since that\n *          is only used in explicitConstructorInvocation at the beginning of a\n *           constructorBody.  (This is part of the simplification of expressions\n *           mentioned earlier.)\n *      Simplified primary (got rid of those things that are only used in\n *          explicitConstructorInvocation).\n *      Lexer -- removed \"Exponent?\" from FloatingPointLiteral choice 4, since it\n *          led to an ambiguity.\n *\n *      This grammar successfully parses every .java file in the JDK 1.5 source \n *          tree (excluding those whose file names include '-', which are not\n *          valid Java compilation units).\n *\n *  June 26, 2008\n *\n *\tconditionalExpression had wrong precedence x?y:z.\n *\n *  Known remaining problems:\n *      \"Letter\" and \"JavaIDDigit\" are wrong.  The actual specification of\n *      \"Letter\" should be \"a character for which the method\n *      Character.isJavaIdentifierStart(int) returns true.\"  A \"Java \n *      letter-or-digit is a character for which the method \n *      Character.isJavaIdentifierPart(int) returns true.\"\n */\ngrammar Java;\n\n// starting point for parsing a java file\n/* The annotations are separated out to make parsing faster, but must be associated with\n   a packageDeclaration or a typeDeclaration (and not an empty one). */\ncompilationUnit\n    :   annotations\n        (   packageDeclaration importDeclaration* typeDeclaration*\n        |   classOrInterfaceDeclaration typeDeclaration*\n        )\n        EOF\n    |   packageDeclaration? importDeclaration* typeDeclaration*\n        EOF\n    ;\n\npackageDeclaration\n    :   'package' qualifiedName ';'\n    ;\n    \nimportDeclaration\n    :   'import' 'static'? qualifiedName ('.' '*')? ';'\n    ;\n    \ntypeDeclaration\n    :   classOrInterfaceDeclaration\n    |   ';'\n    ;\n    \nclassOrInterfaceDeclaration\n    :   classOrInterfaceModifiers (classDeclaration | interfaceDeclaration)\n    ;\n    \nclassOrInterfaceModifiers\n    :   classOrInterfaceModifier*\n    ;\n\nclassOrInterfaceModifier\n    :   annotation       // class or interface\n    |   (   'public'     // class or interface\n        |   'protected'  // class or interface\n        |   'private'    // class or interface\n        |   'abstract'   // class or interface\n        |   'static'     // class or interface\n        |   'final'      // class only -- does not apply to interfaces\n        |   'strictfp'   // class or interface\n        )\n    ;\n\nmodifiers\n    :   modifier*\n    ;\n\nclassDeclaration\n    :   normalClassDeclaration\n    |   enumDeclaration\n    ;\n    \nnormalClassDeclaration\n    :   'class' Identifier typeParameters?\n        ('extends' type)?\n        ('implements' typeList)?\n        classBody\n    ;\n    \ntypeParameters\n    :   '<' typeParameter (',' typeParameter)* '>'\n    ;\n\ntypeParameter\n    :   Identifier ('extends' typeBound)?\n    ;\n        \ntypeBound\n    :   type ('&' type)*\n    ;\n\nenumDeclaration\n    :   ENUM Identifier ('implements' typeList)? enumBody\n    ;\n\nenumBody\n    :   '{' enumConstants? ','? enumBodyDeclarations? '}'\n    ;\n\nenumConstants\n    :   enumConstant (',' enumConstant)*\n    ;\n    \nenumConstant\n    :   annotations? Identifier arguments? classBody?\n    ;\n    \nenumBodyDeclarations\n    :   ';' (classBodyDeclaration)*\n    ;\n    \ninterfaceDeclaration\n    :   normalInterfaceDeclaration\n    |   annotationTypeDeclaration\n    ;\n    \nnormalInterfaceDeclaration\n    :   'interface' Identifier typeParameters? ('extends' typeList)? interfaceBody\n    ;\n    \ntypeList\n    :   type (',' type)*\n    ;\n    \nclassBody\n    :   '{' classBodyDeclaration* '}'\n    ;\n    \ninterfaceBody\n    :   '{' interfaceBodyDeclaration* '}'\n    ;\n\nclassBodyDeclaration\n    :   ';'\n    |   'static'? block\n    |   modifiers memberDecl\n    ;\n    \nmemberDecl\n    :   genericMethodOrConstructorDecl\n    |   memberDeclaration\n    |   'void' Identifier voidMethodDeclaratorRest\n    |   Identifier constructorDeclaratorRest\n    |   interfaceDeclaration\n    |   classDeclaration\n    ;\n    \nmemberDeclaration\n    :   type (methodDeclaration | fieldDeclaration)\n    ;\n\ngenericMethodOrConstructorDecl\n    :   typeParameters genericMethodOrConstructorRest\n    ;\n    \ngenericMethodOrConstructorRest\n    :   (type | 'void') Identifier methodDeclaratorRest\n    |   Identifier constructorDeclaratorRest\n    ;\n\nmethodDeclaration\n    :   Identifier methodDeclaratorRest\n    ;\n\nfieldDeclaration\n    :   variableDeclarators ';'\n    ;\n        \ninterfaceBodyDeclaration\n    :   modifiers interfaceMemberDecl\n    |   ';'\n    ;\n\ninterfaceMemberDecl\n    :   interfaceMethodOrFieldDecl\n    |   interfaceGenericMethodDecl\n    |   'void' Identifier voidInterfaceMethodDeclaratorRest\n    |   interfaceDeclaration\n    |   classDeclaration\n    ;\n    \ninterfaceMethodOrFieldDecl\n    :   type Identifier interfaceMethodOrFieldRest\n    ;\n    \ninterfaceMethodOrFieldRest\n    :   constantDeclaratorsRest ';'\n    |   interfaceMethodDeclaratorRest\n    ;\n    \nmethodDeclaratorRest\n    :   formalParameters ('[' ']')*\n        ('throws' qualifiedNameList)?\n        (   methodBody\n        |   ';'\n        )\n    ;\n    \nvoidMethodDeclaratorRest\n    :   formalParameters ('throws' qualifiedNameList)?\n        (   methodBody\n        |   ';'\n        )\n    ;\n    \ninterfaceMethodDeclaratorRest\n    :   formalParameters ('[' ']')* ('throws' qualifiedNameList)? ';'\n    ;\n    \ninterfaceGenericMethodDecl\n    :   typeParameters (type | 'void') Identifier\n        interfaceMethodDeclaratorRest\n    ;\n    \nvoidInterfaceMethodDeclaratorRest\n    :   formalParameters ('throws' qualifiedNameList)? ';'\n    ;\n    \nconstructorDeclaratorRest\n    :   formalParameters ('throws' qualifiedNameList)? constructorBody\n    ;\n\nconstantDeclarator\n    :   Identifier constantDeclaratorRest\n    ;\n    \nvariableDeclarators\n    :   variableDeclarator (',' variableDeclarator)*\n    ;\n\nvariableDeclarator\n    :   variableDeclaratorId ('=' variableInitializer)?\n    ;\n    \nconstantDeclaratorsRest\n    :   constantDeclaratorRest (',' constantDeclarator)*\n    ;\n\nconstantDeclaratorRest\n    :   ('[' ']')* '=' variableInitializer\n    ;\n    \nvariableDeclaratorId\n    :   Identifier ('[' ']')*\n    ;\n\nvariableInitializer\n    :   arrayInitializer\n    |   expression\n    ;\n        \narrayInitializer\n    :   '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'\n    ;\n\nmodifier\n    :   annotation\n    |   (   'public'\n        |   'protected'\n        |   'private'\n        |   'static'\n        |   'abstract'\n        |   'final'\n        |   'native'\n        |   'synchronized'\n        |   'transient'\n        |   'volatile'\n        |   'strictfp'\n        )\n    ;\n\npackageOrTypeName\n    :   qualifiedName\n    ;\n\nenumConstantName\n    :   Identifier\n    ;\n\ntypeName\n    :   qualifiedName\n    ;\n\ntype\n\t:\tclassOrInterfaceType ('[' ']')*\n\t|\tprimitiveType ('[' ']')*\n\t;\n\nclassOrInterfaceType\n\t:\tIdentifier typeArguments? ('.' Identifier typeArguments? )*\n\t;\n\nprimitiveType\n    :   'boolean'\n    |   'char'\n    |   'byte'\n    |   'short'\n    |   'int'\n    |   'long'\n    |   'float'\n    |   'double'\n    ;\n\nvariableModifier\n    :   'final'\n    |   annotation\n    ;\n\ntypeArguments\n    :   '<' typeArgument (',' typeArgument)* '>'\n    ;\n    \ntypeArgument\n    :   type\n    |   '?' (('extends' | 'super') type)?\n    ;\n    \nqualifiedNameList\n    :   qualifiedName (',' qualifiedName)*\n    ;\n\nformalParameters\n    :   '(' formalParameterDecls? ')'\n    ;\n    \nformalParameterDecls\n    :   variableModifiers type formalParameterDeclsRest\n    ;\n    \nformalParameterDeclsRest\n    :   variableDeclaratorId (',' formalParameterDecls)?\n    |   '...' variableDeclaratorId\n    ;\n    \nmethodBody\n    :   block\n    ;\n\nconstructorBody\n    :   block\n    ;\n\nqualifiedName\n    :   Identifier ('.' Identifier)*\n    ;\n    \nliteral \n    :   IntegerLiteral\n    |   FloatingPointLiteral\n    |   CharacterLiteral\n    |   StringLiteral\n    |   BooleanLiteral\n    |   'null'\n    ;\n\n// ANNOTATIONS\n\nannotations\n    :   annotation+\n    ;\n\nannotation\n    :   '@' annotationName ( '(' ( elementValuePairs | elementValue )? ')' )?\n    ;\n    \nannotationName\n    : Identifier ('.' Identifier)*\n    ;\n\nelementValuePairs\n    :   elementValuePair (',' elementValuePair)*\n    ;\n\nelementValuePair\n    :   Identifier '=' elementValue\n    ;\n    \nelementValue\n    :   conditionalExpression\n    |   annotation\n    |   elementValueArrayInitializer\n    ;\n    \nelementValueArrayInitializer\n    :   '{' (elementValue (',' elementValue)*)? (',')? '}'\n    ;\n    \nannotationTypeDeclaration\n    :   '@' 'interface' Identifier annotationTypeBody\n    ;\n    \nannotationTypeBody\n    :   '{' (annotationTypeElementDeclaration)* '}'\n    ;\n    \nannotationTypeElementDeclaration\n    :   modifiers annotationTypeElementRest\n\t|\t';' // this is not allowed by the grammar, but apparently allowed by the actual compiler\n    ;\n    \nannotationTypeElementRest\n    :   type annotationMethodOrConstantRest ';'\n    |   normalClassDeclaration ';'?\n    |   normalInterfaceDeclaration ';'?\n    |   enumDeclaration ';'?\n    |   annotationTypeDeclaration ';'?\n    ;\n    \nannotationMethodOrConstantRest\n    :   annotationMethodRest\n    |   annotationConstantRest\n    ;\n    \nannotationMethodRest\n    :   Identifier '(' ')' defaultValue?\n    ;\n    \nannotationConstantRest\n    :   variableDeclarators\n    ;\n    \ndefaultValue\n    :   'default' elementValue\n    ;\n\n// STATEMENTS / BLOCKS\n\nblock\n    :   '{' blockStatement* '}'\n    ;\n    \nblockStatement\n    :   localVariableDeclarationStatement\n    |   classOrInterfaceDeclaration\n    |   statement\n    ;\n    \nlocalVariableDeclarationStatement\n    :    localVariableDeclaration ';'\n    ;\n\nlocalVariableDeclaration\n    :   variableModifiers type variableDeclarators\n    ;\n    \nvariableModifiers\n    :   variableModifier*\n    ;\n\nstatement\n    :\tblock\n    |   ASSERT expression (':' expression)? ';'\n    |   'if' parExpression statement ('else' statement)?\n    |   'for' '(' forControl ')' statement\n    |   'while' parExpression statement\n    |   'do' statement 'while' parExpression ';'\n    |   'try' block (catches finallyBlock? | finallyBlock)\n\t|\t'try' resourceSpecification block catches? finallyBlock?\n    |   'switch' parExpression '{' switchBlockStatementGroups '}'\n    |   'synchronized' parExpression block\n    |   'return' expression? ';'\n    |   'throw' expression ';'\n    |   'break' Identifier? ';'\n    |   'continue' Identifier? ';'\n    |   ';' \n    |   statementExpression ';'\n    |   Identifier ':' statement\n    ;\n\ncatches\n    :   catchClause+\n    ;\n    \ncatchClause\n    :   'catch' '(' variableModifiers catchType Identifier ')' block\n    ;\n\ncatchType\n\t:\tqualifiedName ('|' qualifiedName)*\n\t;\n\nfinallyBlock\n\t:\t'finally' block\n\t;\n\nresourceSpecification\n\t:\t'(' resources ';'? ')'\n\t;\n\nresources\n\t:\tresource (';' resource)*\n\t;\n\nresource\n\t:\tvariableModifiers classOrInterfaceType variableDeclaratorId '=' expression\n\t;\n\nformalParameter\n    :   variableModifiers type variableDeclaratorId\n    ;\n        \nswitchBlockStatementGroups\n    :   (switchBlockStatementGroup)*\n    ;\n    \n/* The change here (switchLabel -> switchLabel+) technically makes this grammar\n   ambiguous; but with appropriately greedy parsing it yields the most\n   appropriate AST, one in which each group, except possibly the last one, has\n   labels and statements. */\nswitchBlockStatementGroup\n    :   switchLabel+ blockStatement*\n    ;\n    \nswitchLabel\n    :   'case' constantExpression ':'\n    |   'case' enumConstantName ':'\n    |   'default' ':'\n    ;\n    \nforControl\n    :   enhancedForControl\n    |   forInit? ';' expression? ';' forUpdate?\n    ;\n\nforInit\n    :   localVariableDeclaration\n    |   expressionList\n    ;\n    \nenhancedForControl\n    :   variableModifiers type Identifier ':' expression\n    ;\n\nforUpdate\n    :   expressionList\n    ;\n\n// EXPRESSIONS\n\nparExpression\n    :   '(' expression ')'\n    ;\n    \nexpressionList\n    :   expression (',' expression)*\n    ;\n\nstatementExpression\n    :   expression\n    ;\n    \nconstantExpression\n    :   expression\n    ;\n    \nexpression\n    :   conditionalExpression (assignmentOperator expression)?\n    ;\n    \nassignmentOperator\n    :   '='\n    |   '+='\n    |   '-='\n    |   '*='\n    |   '/='\n    |   '&='\n    |   '|='\n    |   '^='\n    |   '%='\n    |   '<<='\n    |   '>>='\n    |   '>>>='\n    ;\n\nconditionalExpression\n    :   conditionalOrExpression ( '?' expression ':' conditionalExpression )?\n    ;\n\nconditionalOrExpression\n    :   conditionalAndExpression ( '||' conditionalAndExpression )*\n    ;\n\nconditionalAndExpression\n    :   inclusiveOrExpression ( '&&' inclusiveOrExpression )*\n    ;\n\ninclusiveOrExpression\n    :   exclusiveOrExpression ( '|' exclusiveOrExpression )*\n    ;\n\nexclusiveOrExpression\n    :   andExpression ( '^' andExpression )*\n    ;\n\nandExpression\n    :   equalityExpression ( '&' equalityExpression )*\n    ;\n\nequalityExpression\n    :   instanceOfExpression ( ('==' | '!=') instanceOfExpression )*\n    ;\n\ninstanceOfExpression\n    :   relationalExpression ('instanceof' type)?\n    ;\n\nrelationalExpression\n    :   shiftExpression ( relationalOp shiftExpression )*\n    ;\n    \nrelationalOp\n    :   '<='\n    |   '>='\n    |   '<'\n    |   '>'\n    ;\n\nshiftExpression\n    :   additiveExpression ( shiftOp additiveExpression )*\n    ;\n\nshiftOp\n    :   t1='<' t2='<'\n//        { $t1.getLine() == $t2.getLine() &&\n//          $t1.getCharPositionInLine() + 1 == $t2.getCharPositionInLine() }?\n    |   t1='>' t2='>' t3='>'\n//        { $t1.getLine() == $t2.getLine() &&\n//          $t1.getCharPositionInLine() + 1 == $t2.getCharPositionInLine() &&\n//          $t2.getLine() == $t3.getLine() &&\n//          $t2.getCharPositionInLine() + 1 == $t3.getCharPositionInLine() }?\n    |   t1='>' t2='>'\n//        { $t1.getLine() == $t2.getLine() &&\n//          $t1.getCharPositionInLine() + 1 == $t2.getCharPositionInLine() }?\n    ;\n\n\nadditiveExpression\n    :   multiplicativeExpression ( ('+' | '-') multiplicativeExpression )*\n    ;\n\nmultiplicativeExpression\n    :   unaryExpression ( ( '*' | '/' | '%' ) unaryExpression )*\n    ;\n    \nunaryExpression\n    :   '+' unaryExpression\n    |   '-' unaryExpression\n    |   '++' unaryExpression\n    |   '--' unaryExpression\n    |   unaryExpressionNotPlusMinus\n    ;\n\nunaryExpressionNotPlusMinus\n    :   '~' unaryExpression\n    |   '!' unaryExpression\n    |   castExpression\n    |   primary selector* ('++'|'--')?\n    ;\n\ncastExpression\n    :  '(' primitiveType ')' unaryExpression\n    |  '(' (type | expression) ')' unaryExpressionNotPlusMinus\n    ;\n\nprimary\n    :   parExpression\n    |   'this' arguments?\n    |   'super' superSuffix\n    |   literal\n    |   'new' creator\n\t|\tnonWildcardTypeArguments (explicitGenericInvocationSuffix | 'this' arguments)\n    |   Identifier ('.' Identifier)* identifierSuffix?\n    |   primitiveType ('[' ']')* '.' 'class'\n    |   'void' '.' 'class'\n    ;\n\nidentifierSuffix\n    :   ('[' ']')+ '.' 'class'\n    |   '[' expression ']'\n    |   arguments\n    |   '.' 'class'\n    |   '.' explicitGenericInvocation\n    |   '.' 'this'\n    |   '.' 'super' arguments\n    |   '.' 'new' nonWildcardTypeArguments? innerCreator\n    ;\n\ncreator\n    :   nonWildcardTypeArguments createdName classCreatorRest\n    |   createdName (arrayCreatorRest | classCreatorRest)\n    ;\n\ncreatedName\n    :   Identifier typeArgumentsOrDiamond? ('.' Identifier typeArgumentsOrDiamond?)*\n\t|\tprimitiveType\n    ;\n    \ninnerCreator\n    :   Identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest\n    ;\n\narrayCreatorRest\n    :   '['\n        (   ']' ('[' ']')* arrayInitializer\n        |   expression ']' ('[' expression ']')* ('[' ']')*\n        )\n    ;\n\nclassCreatorRest\n    :   arguments classBody?\n    ;\n    \nexplicitGenericInvocation\n    :   nonWildcardTypeArguments explicitGenericInvocationSuffix\n    ;\n    \nnonWildcardTypeArguments\n    :   '<' typeList '>'\n    ;\n\ntypeArgumentsOrDiamond\n\t:\t'<' '>'\n\t|\ttypeArguments\n\t;\n\nnonWildcardTypeArgumentsOrDiamond\n\t:\t'<' '>'\n\t|\tnonWildcardTypeArguments\n\t;\n\nselector\n    :   '.' Identifier arguments?\n\t|\t'.' explicitGenericInvocation\n    |   '.' 'this'\n    |   '.' 'super' superSuffix\n    |   '.' 'new' nonWildcardTypeArguments? innerCreator\n    |   '[' expression ']'\n    ;\n    \nsuperSuffix\n    :   arguments\n    |   '.' Identifier arguments?\n    ;\n\nexplicitGenericInvocationSuffix\n\t:\t'super' superSuffix\n\t|\tIdentifier arguments\n\t;\n\narguments\n    :   '(' expressionList? ')'\n    ;\n\n// LEXER\n\n// §3.9 Keywords\n\nABSTRACT : 'abstract';\nASSERT : 'assert';\nBOOLEAN : 'boolean';\nBREAK : 'break';\nBYTE : 'byte';\nCASE : 'case';\nCATCH : 'catch';\nCHAR : 'char';\nCLASS : 'class';\nCONST : 'const';\nCONTINUE : 'continue';\nDEFAULT : 'default';\nDO : 'do';\nDOUBLE : 'double';\nELSE : 'else';\nENUM : 'enum';\nEXTENDS : 'extends';\nFINAL : 'final';\nFINALLY : 'finally';\nFLOAT : 'float';\nFOR : 'for';\nIF : 'if';\nGOTO : 'goto';\nIMPLEMENTS : 'implements';\nIMPORT : 'import';\nINSTANCEOF : 'instanceof';\nINT : 'int';\nINTERFACE : 'interface';\nLONG : 'long';\nNATIVE : 'native';\nNEW : 'new';\nPACKAGE : 'package';\nPRIVATE : 'private';\nPROTECTED : 'protected';\nPUBLIC : 'public';\nRETURN : 'return';\nSHORT : 'short';\nSTATIC : 'static';\nSTRICTFP : 'strictfp';\nSUPER : 'super';\nSWITCH : 'switch';\nSYNCHRONIZED : 'synchronized';\nTHIS : 'this';\nTHROW : 'throw';\nTHROWS : 'throws';\nTRANSIENT : 'transient';\nTRY : 'try';\nVOID : 'void';\nVOLATILE : 'volatile';\nWHILE : 'while';\n\n// §3.10.1 Integer Literals\n\nIntegerLiteral\n\t:\tDecimalIntegerLiteral\n\t|\tHexIntegerLiteral\n\t|\tOctalIntegerLiteral\n\t|\tBinaryIntegerLiteral\n\t;\n\nfragment\nDecimalIntegerLiteral\n\t:\tDecimalNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nHexIntegerLiteral\n\t:\tHexNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nOctalIntegerLiteral\n\t:\tOctalNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nBinaryIntegerLiteral\n\t:\tBinaryNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nIntegerTypeSuffix\n\t:\t[lL]\n\t;\n\nfragment\nDecimalNumeral\n\t:\t'0'\n\t|\tNonZeroDigit (Digits? | Underscores Digits)\n\t;\n\nfragment\nDigits\n\t:\tDigit (DigitsAndUnderscores? Digit)?\n\t;\n\nfragment\nDigit\n\t:\t'0'\n\t|\tNonZeroDigit\n\t;\n\nfragment\nNonZeroDigit\n\t:\t[1-9]\n\t;\n\nfragment\nDigitsAndUnderscores\n\t:\tDigitOrUnderscore+\n\t;\n\nfragment\nDigitOrUnderscore\n\t:\tDigit\n\t|\t'_'\n\t;\n\nfragment\nUnderscores\n\t:\t'_'+\n\t;\n\nfragment\nHexNumeral\n\t:\t'0' [xX] HexDigits\n\t;\n\nfragment\nHexDigits\n\t:\tHexDigit (HexDigitsAndUnderscores? HexDigit)?\n\t;\n\nfragment\nHexDigit\n\t:\t[0-9a-fA-F]\n\t;\n\nfragment\nHexDigitsAndUnderscores\n\t:\tHexDigitOrUnderscore+\n\t;\n\nfragment\nHexDigitOrUnderscore\n\t:\tHexDigit\n\t|\t'_'\n\t;\n\nfragment\nOctalNumeral\n\t:\t'0' Underscores? OctalDigits\n\t;\n\nfragment\nOctalDigits\n\t:\tOctalDigit (OctalDigitsAndUnderscores? OctalDigit)?\n\t;\n\nfragment\nOctalDigit\n\t:\t[0-7]\n\t;\n\nfragment\nOctalDigitsAndUnderscores\n\t:\tOctalDigitOrUnderscore+\n\t;\n\nfragment\nOctalDigitOrUnderscore\n\t:\tOctalDigit\n\t|\t'_'\n\t;\n\nfragment\nBinaryNumeral\n\t:\t'0' [bB] BinaryDigits\n\t;\n\nfragment\nBinaryDigits\n\t:\tBinaryDigit (BinaryDigitsAndUnderscores? BinaryDigit)?\n\t;\n\nfragment\nBinaryDigit\n\t:\t[01]\n\t;\n\nfragment\nBinaryDigitsAndUnderscores\n\t:\tBinaryDigitOrUnderscore+\n\t;\n\nfragment\nBinaryDigitOrUnderscore\n\t:\tBinaryDigit\n\t|\t'_'\n\t;\n\n// §3.10.2 Floating-Point Literals\n\nFloatingPointLiteral\n\t:\tDecimalFloatingPointLiteral\n\t|\tHexadecimalFloatingPointLiteral\n\t;\n\nfragment\nDecimalFloatingPointLiteral\n\t:\tDigits '.' Digits? ExponentPart? FloatTypeSuffix?\n\t|\t'.' Digits ExponentPart? FloatTypeSuffix?\n\t|\tDigits ExponentPart FloatTypeSuffix?\n\t|\tDigits FloatTypeSuffix\n\t;\n\nfragment\nExponentPart\n\t:\tExponentIndicator SignedInteger\n\t;\n\nfragment\nExponentIndicator\n\t:\t[eE]\n\t;\n\nfragment\nSignedInteger\n\t:\tSign? Digits\n\t;\n\nfragment\nSign\n\t:\t[+\\-]\n\t;\n\nfragment\nFloatTypeSuffix\n\t:\t[fFdD]\n\t;\n\nfragment\nHexadecimalFloatingPointLiteral\n\t:\tHexSignificand BinaryExponent FloatTypeSuffix?\n\t;\n\nfragment\nHexSignificand\n\t:\tHexNumeral '.'?\n\t|\t'0' [xX] HexDigits? '.' HexDigits\n\t;\n\nfragment\nBinaryExponent\n\t:\tBinaryExponentIndicator SignedInteger\n\t;\n\nfragment\nBinaryExponentIndicator\n\t:\t[pP]\n\t;\n\n// §3.10.3 Boolean Literals\n\nBooleanLiteral\n\t:\t'true'\n\t|\t'false'\n\t;\n\n// §3.10.4 Character Literals\n\nCharacterLiteral\n\t:\t'\\'' SingleCharacter '\\''\n\t|\t'\\'' EscapeSequence '\\''\n\t;\n\nfragment\nSingleCharacter\n\t:\t~['\\\\]\n\t;\n\n// §3.10.5 String Literals\n\nStringLiteral\n\t:\t'\"' StringCharacters? '\"'\n\t;\n\nfragment\nStringCharacters\n\t:\tStringCharacter+\n\t;\n\nfragment\nStringCharacter\n\t:\t~[\"\\\\]\n\t|\tEscapeSequence\n\t;\n\n// §3.10.6 Escape Sequences for Character and String Literals\n\nfragment\nEscapeSequence\n\t:\t'\\\\' [btnfr\"'\\\\]\n\t|\tOctalEscape\n\t;\n\nfragment\nOctalEscape\n\t:\t'\\\\' OctalDigit\n\t|\t'\\\\' OctalDigit OctalDigit\n\t|\t'\\\\' ZeroToThree OctalDigit OctalDigit\n\t;\n\nfragment\nZeroToThree\n\t:\t[0-3]\n\t;\n\n// §3.10.7 The Null Literal\n\nNullLiteral\n\t:\t'null'\n\t;\n\n// §3.11 Separators\n\nLPAREN : '(';\nRPAREN : ')';\nLBRACE : '{';\nRBRACE : '}';\nLBRACK : '[';\nRBRACK : ']';\nSEMI : ';';\nCOMMA : ',';\nDOT : '.';\n\n// §3.12 Operators\n\nASSIGN : '=';\nGT : '>';\nLT : '<';\nBANG : '!';\nTILDE : '~';\nQUESTION : '?';\nCOLON : ':';\nEQUAL : '==';\nLE : '<=';\nGE : '>=';\nNOTEQUAL : '!=';\nAND : '&&';\nOR : '||';\nINC : '++';\nDEC : '--';\nADD : '+';\nSUB : '-';\nMUL : '*';\nDIV : '/';\nBITAND : '&';\nBITOR : '|';\nCARET : '^';\nMOD : '%';\n\nADD_ASSIGN : '+=';\nSUB_ASSIGN : '-=';\nMUL_ASSIGN : '*=';\nDIV_ASSIGN : '/=';\nAND_ASSIGN : '&=';\nOR_ASSIGN : '|=';\nXOR_ASSIGN : '^=';\nMOD_ASSIGN : '%=';\nLSHIFT_ASSIGN : '<<=';\nRSHIFT_ASSIGN : '>>=';\nURSHIFT_ASSIGN : '>>>=';\n\n// §3.8 Identifiers (must appear after all keywords in the grammar)\n\nIdentifier\n\t:\tJavaLetter JavaLetterOrDigit*\n\t;\n\nfragment\nJavaLetter\n\t:\t[a-zA-Z$_] // these are the \"java letters\" below 0xFF\n\t|\t// covers all characters above 0xFF which are not a surrogate\n\t\t~[\\u0000-\\u00FF\\uD800-\\uDBFF]\n\t\t{Character.isJavaIdentifierStart(_input.LA(-1))}?\n\t|\t// covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF\n\t\t[\\uD800-\\uDBFF] [\\uDC00-\\uDFFF]\n\t\t{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?\n\t;\n\nfragment\nJavaLetterOrDigit\n\t:\t[a-zA-Z0-9$_] // these are the \"java letters or digits\" below 0xFF\n\t|\t// covers all characters above 0xFF which are not a surrogate\n\t\t~[\\u0000-\\u00FF\\uD800-\\uDBFF]\n\t\t{Character.isJavaIdentifierPart(_input.LA(-1))}?\n\t|\t// covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF\n\t\t[\\uD800-\\uDBFF] [\\uDC00-\\uDFFF]\n\t\t{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?\n\t;\n\n//\n// Additional symbols not defined in the lexical specification\n//\n\nAT : '@';\nELLIPSIS : '...';\n\n//\n// Whitespace and comments\n//\n\nWS  :  [ \\t\\r\\n\\u000C]+ -> skip\n    ;\n\nCOMMENT\n    :   '/*' .*? '*/' -> skip\n    ;\n\nLINE_COMMENT\n    :   '//' ~[\\r\\n]* -> skip\n    ;\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/JavaLR.g4",
    "content": "/*\n [The \"BSD licence\"]\n Copyright (c) 2007-2008 Terence Parr\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n 3. The name of the author may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/** A Java 1.5 grammar for ANTLR v3 derived from the spec\n *\n *  This is a very close representation of the spec; the changes\n *  are comestic (remove left recursion) and also fixes (the spec\n *  isn't exactly perfect).  I have run this on the 1.4.2 source\n *  and some nasty looking enums from 1.5, but have not really\n *  tested for 1.5 compatibility.\n *\n *  I built this with: java -Xmx100M org.antlr.Tool java.g \n *  and got two errors that are ok (for now):\n *  java.g:691:9: Decision can match input such as\n *    \"'0'..'9'{'E', 'e'}{'+', '-'}'0'..'9'{'D', 'F', 'd', 'f'}\"\n *    using multiple alternatives: 3, 4\n *  As a result, alternative(s) 4 were disabled for that input\n *  java.g:734:35: Decision can match input such as \"{'$', 'A'..'Z',\n *    '_', 'a'..'z', '\\u00C0'..'\\u00D6', '\\u00D8'..'\\u00F6',\n *    '\\u00F8'..'\\u1FFF', '\\u3040'..'\\u318F', '\\u3300'..'\\u337F',\n *    '\\u3400'..'\\u3D2D', '\\u4E00'..'\\u9FFF', '\\uF900'..'\\uFAFF'}\"\n *    using multiple alternatives: 1, 2\n *  As a result, alternative(s) 2 were disabled for that input\n *\n *  You can turn enum on/off as a keyword :)\n *\n *  Version 1.0 -- initial release July 5, 2006 (requires 3.0b2 or higher)\n *\n *  Primary author: Terence Parr, July 2006\n *\n *  Version 1.0.1 -- corrections by Koen Vanderkimpen & Marko van Dooren,\n *      October 25, 2006;\n *      fixed normalInterfaceDeclaration: now uses typeParameters instead\n *          of typeParameter (according to JLS, 3rd edition)\n *      fixed castExpression: no longer allows expression next to type\n *          (according to semantics in JLS, in contrast with syntax in JLS)\n *\n *  Version 1.0.2 -- Terence Parr, Nov 27, 2006\n *      java spec I built this from had some bizarre for-loop control.\n *          Looked weird and so I looked elsewhere...Yep, it's messed up.\n *          simplified.\n *\n *  Version 1.0.3 -- Chris Hogue, Feb 26, 2007\n *      Factored out an annotationName rule and used it in the annotation rule.\n *          Not sure why, but typeName wasn't recognizing references to inner\n *          annotations (e.g. @InterfaceName.InnerAnnotation())\n *      Factored out the elementValue section of an annotation reference.  Created \n *          elementValuePair and elementValuePairs rules, then used them in the \n *          annotation rule.  Allows it to recognize annotation references with \n *          multiple, comma separated attributes.\n *      Updated elementValueArrayInitializer so that it allows multiple elements.\n *          (It was only allowing 0 or 1 element).\n *      Updated localVariableDeclaration to allow annotations.  Interestingly the JLS\n *          doesn't appear to indicate this is legal, but it does work as of at least\n *          JDK 1.5.0_06.\n *      Moved the Identifier portion of annotationTypeElementRest to annotationMethodRest.\n *          Because annotationConstantRest already references variableDeclarator which \n *          has the Identifier portion in it, the parser would fail on constants in \n *          annotation definitions because it expected two identifiers.  \n *      Added optional trailing ';' to the alternatives in annotationTypeElementRest.\n *          Wouldn't handle an inner interface that has a trailing ';'.\n *      Swapped the expression and type rule reference order in castExpression to \n *          make it check for genericized casts first.  It was failing to recognize a\n *          statement like  \"Class<Byte> TYPE = (Class<Byte>)...;\" because it was seeing\n *          'Class<Byte' in the cast expression as a less than expression, then failing \n *          on the '>'.\n *      Changed createdName to use typeArguments instead of nonWildcardTypeArguments.\n *      Changed the 'this' alternative in primary to allow 'identifierSuffix' rather than\n *          just 'arguments'.  The case it couldn't handle was a call to an explicit\n *          generic method invocation (e.g. this.<E>doSomething()).  Using identifierSuffix\n *          may be overly aggressive--perhaps should create a more constrained thisSuffix rule?\n *      \n *  Version 1.0.4 -- Hiroaki Nakamura, May 3, 2007\n *\n *  Fixed formalParameterDecls, localVariableDeclaration, forInit,\n *  and forVarControl to use variableModifier* not 'final'? (annotation)?\n *\n *  Version 1.0.5 -- Terence, June 21, 2007\n *  --a[i].foo didn't work. Fixed unaryExpression\n *\n *  Version 1.0.6 -- John Ridgway, March 17, 2008\n *      Made \"assert\" a switchable keyword like \"enum\".\n *      Fixed compilationUnit to disallow \"annotation importDeclaration ...\".\n *      Changed \"Identifier ('.' Identifier)*\" to \"qualifiedName\" in more \n *          places.\n *      Changed modifier* and/or variableModifier* to classOrInterfaceModifiers,\n *          modifiers or variableModifiers, as appropriate.\n *      Renamed \"bound\" to \"typeBound\" to better match language in the JLS.\n *      Added \"memberDeclaration\" which rewrites to methodDeclaration or \n *      fieldDeclaration and pulled type into memberDeclaration.  So we parse \n *          type and then move on to decide whether we're dealing with a field\n *          or a method.\n *      Modified \"constructorDeclaration\" to use \"constructorBody\" instead of\n *          \"methodBody\".  constructorBody starts with explicitConstructorInvocation,\n *          then goes on to blockStatement*.  Pulling explicitConstructorInvocation\n *          out of expressions allowed me to simplify \"primary\".\n *      Changed variableDeclarator to simplify it.\n *      Changed type to use classOrInterfaceType, thus simplifying it; of course\n *          I then had to add classOrInterfaceType, but it is used in several \n *          places.\n *      Fixed annotations, old version allowed \"@X(y,z)\", which is illegal.\n *      Added optional comma to end of \"elementValueArrayInitializer\"; as per JLS.\n *      Changed annotationTypeElementRest to use normalClassDeclaration and \n *          normalInterfaceDeclaration rather than classDeclaration and \n *          interfaceDeclaration, thus getting rid of a couple of grammar ambiguities.\n *      Split localVariableDeclaration into localVariableDeclarationStatement\n *          (includes the terminating semi-colon) and localVariableDeclaration.  \n *          This allowed me to use localVariableDeclaration in \"forInit\" clauses,\n *           simplifying them.\n *      Changed switchBlockStatementGroup to use multiple labels.  This adds an\n *          ambiguity, but if one uses appropriately greedy parsing it yields the\n *           parse that is closest to the meaning of the switch statement.\n *      Renamed \"forVarControl\" to \"enhancedForControl\" -- JLS language.\n *      Added semantic predicates to test for shift operations rather than other\n *          things.  Thus, for instance, the string \"< <\" will never be treated\n *          as a left-shift operator.\n *      In \"creator\" we rule out \"nonWildcardTypeArguments\" on arrayCreation, \n *          which are illegal.\n *      Moved \"nonWildcardTypeArguments into innerCreator.\n *      Removed 'super' superSuffix from explicitGenericInvocation, since that\n *          is only used in explicitConstructorInvocation at the beginning of a\n *           constructorBody.  (This is part of the simplification of expressions\n *           mentioned earlier.)\n *      Simplified primary (got rid of those things that are only used in\n *          explicitConstructorInvocation).\n *      Lexer -- removed \"Exponent?\" from FloatingPointLiteral choice 4, since it\n *          led to an ambiguity.\n *\n *      This grammar successfully parses every .java file in the JDK 1.5 source \n *          tree (excluding those whose file names include '-', which are not\n *          valid Java compilation units).\n *\n *  June 26, 2008\n *\n *\tconditionalExpression had wrong precedence x?y:z.\n *\n *  February 26, 2011\n *\tadded left-recursive expression rule\n *\n *  Known remaining problems:\n *      \"Letter\" and \"JavaIDDigit\" are wrong.  The actual specification of\n *      \"Letter\" should be \"a character for which the method\n *      Character.isJavaIdentifierStart(int) returns true.\"  A \"Java \n *      letter-or-digit is a character for which the method \n *      Character.isJavaIdentifierPart(int) returns true.\"\n */\ngrammar JavaLR;\n\n// starting point for parsing a java file\n/* The annotations are separated out to make parsing faster, but must be associated with\n   a packageDeclaration or a typeDeclaration (and not an empty one). */\ncompilationUnit\n    :   annotations\n        (   packageDeclaration importDeclaration* typeDeclaration*\n        |   classOrInterfaceDeclaration typeDeclaration*\n        )\n        EOF\n    |   packageDeclaration? importDeclaration* typeDeclaration*\n        EOF\n    ;\n\npackageDeclaration\n    :   'package' qualifiedName ';'\n    ;\n    \nimportDeclaration\n    :   'import' 'static'? qualifiedName ('.' '*')? ';'\n    ;\n    \ntypeDeclaration\n    :   classOrInterfaceDeclaration\n    |   ';'\n    ;\n    \nclassOrInterfaceDeclaration\n    :   classOrInterfaceModifiers (classDeclaration | interfaceDeclaration)\n    ;\n    \nclassOrInterfaceModifiers\n    :   classOrInterfaceModifier*\n    ;\n\nclassOrInterfaceModifier\n    :   annotation       // class or interface\n    |   (   'public'     // class or interface\n        |   'protected'  // class or interface\n        |   'private'    // class or interface\n        |   'abstract'   // class or interface\n        |   'static'     // class or interface\n        |   'final'      // class only -- does not apply to interfaces\n        |   'strictfp'   // class or interface\n        )\n    ;\n\nmodifiers\n    :   modifier*\n    ;\n\nclassDeclaration\n    :   normalClassDeclaration\n    |   enumDeclaration\n    ;\n    \nnormalClassDeclaration\n    :   'class' Identifier typeParameters?\n        ('extends' type)?\n        ('implements' typeList)?\n        classBody\n    ;\n    \ntypeParameters\n    :   '<' typeParameter (',' typeParameter)* '>'\n    ;\n\ntypeParameter\n    :   Identifier ('extends' typeBound)?\n    ;\n        \ntypeBound\n    :   type ('&' type)*\n    ;\n\nenumDeclaration\n    :   ENUM Identifier ('implements' typeList)? enumBody\n    ;\n\nenumBody\n    :   '{' enumConstants? ','? enumBodyDeclarations? '}'\n    ;\n\nenumConstants\n    :   enumConstant (',' enumConstant)*\n    ;\n    \nenumConstant\n    :   annotations? Identifier arguments? classBody?\n    ;\n    \nenumBodyDeclarations\n    :   ';' (classBodyDeclaration)*\n    ;\n    \ninterfaceDeclaration\n    :   normalInterfaceDeclaration\n    |   annotationTypeDeclaration\n    ;\n    \nnormalInterfaceDeclaration\n    :   'interface' Identifier typeParameters? ('extends' typeList)? interfaceBody\n    ;\n    \ntypeList\n    :   type (',' type)*\n    ;\n    \nclassBody\n    :   '{' classBodyDeclaration* '}'\n    ;\n    \ninterfaceBody\n    :   '{' interfaceBodyDeclaration* '}'\n    ;\n\nclassBodyDeclaration\n    :   ';'\n    |   'static'? block\n    |   modifiers memberDecl\n    ;\n    \nmemberDecl\n    :   genericMethodOrConstructorDecl\n    |   memberDeclaration\n    |   'void' Identifier voidMethodDeclaratorRest\n    |   Identifier constructorDeclaratorRest\n    |   interfaceDeclaration\n    |   classDeclaration\n    ;\n    \nmemberDeclaration\n    :   type (methodDeclaration | fieldDeclaration)\n    ;\n\ngenericMethodOrConstructorDecl\n    :   typeParameters genericMethodOrConstructorRest\n    ;\n    \ngenericMethodOrConstructorRest\n    :   (type | 'void') Identifier methodDeclaratorRest\n    |   Identifier constructorDeclaratorRest\n    ;\n\nmethodDeclaration\n    :   Identifier methodDeclaratorRest\n    ;\n\nfieldDeclaration\n    :   variableDeclarators ';'\n    ;\n        \ninterfaceBodyDeclaration\n    :   modifiers interfaceMemberDecl\n    |   ';'\n    ;\n\ninterfaceMemberDecl\n    :   interfaceMethodOrFieldDecl\n    |   interfaceGenericMethodDecl\n    |   'void' Identifier voidInterfaceMethodDeclaratorRest\n    |   interfaceDeclaration\n    |   classDeclaration\n    ;\n    \ninterfaceMethodOrFieldDecl\n    :   type Identifier interfaceMethodOrFieldRest\n    ;\n    \ninterfaceMethodOrFieldRest\n    :   constantDeclaratorsRest ';'\n    |   interfaceMethodDeclaratorRest\n    ;\n    \nmethodDeclaratorRest\n    :   formalParameters ('[' ']')*\n        ('throws' qualifiedNameList)?\n        (   methodBody\n        |   ';'\n        )\n    ;\n    \nvoidMethodDeclaratorRest\n    :   formalParameters ('throws' qualifiedNameList)?\n        (   methodBody\n        |   ';'\n        )\n    ;\n    \ninterfaceMethodDeclaratorRest\n    :   formalParameters ('[' ']')* ('throws' qualifiedNameList)? ';'\n    ;\n    \ninterfaceGenericMethodDecl\n    :   typeParameters (type | 'void') Identifier\n        interfaceMethodDeclaratorRest\n    ;\n    \nvoidInterfaceMethodDeclaratorRest\n    :   formalParameters ('throws' qualifiedNameList)? ';'\n    ;\n    \nconstructorDeclaratorRest\n    :   formalParameters ('throws' qualifiedNameList)? constructorBody\n    ;\n\nconstantDeclarator\n    :   Identifier constantDeclaratorRest\n    ;\n    \nvariableDeclarators\n    :   variableDeclarator (',' variableDeclarator)*\n    ;\n\nvariableDeclarator\n    :   variableDeclaratorId ('=' variableInitializer)?\n    ;\n    \nconstantDeclaratorsRest\n    :   constantDeclaratorRest (',' constantDeclarator)*\n    ;\n\nconstantDeclaratorRest\n    :   ('[' ']')* '=' variableInitializer\n    ;\n    \nvariableDeclaratorId\n    :   Identifier ('[' ']')*\n    ;\n\nvariableInitializer\n    :   arrayInitializer\n    |   expression\n    ;\n        \narrayInitializer\n    :   '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'\n    ;\n\nmodifier\n    :   annotation\n    |   (   'public'\n        |   'protected'\n        |   'private'\n        |   'static'\n        |   'abstract'\n        |   'final'\n        |   'native'\n        |   'synchronized'\n        |   'transient'\n        |   'volatile'\n        |   'strictfp'\n        )\n    ;\n\npackageOrTypeName\n    :   qualifiedName\n    ;\n\nenumConstantName\n    :   Identifier\n    ;\n\ntypeName\n    :   qualifiedName\n    ;\n\ntype\n\t:\tclassOrInterfaceType ('[' ']')*\n\t|\tprimitiveType ('[' ']')*\n\t;\n\nclassOrInterfaceType\n\t:\tIdentifier typeArguments? ('.' Identifier typeArguments? )*\n\t;\n\nprimitiveType\n    :   'boolean'\n    |   'char'\n    |   'byte'\n    |   'short'\n    |   'int'\n    |   'long'\n    |   'float'\n    |   'double'\n    ;\n\nvariableModifier\n    :   'final'\n    |   annotation\n    ;\n\ntypeArguments\n    :   '<' typeArgument (',' typeArgument)* '>'\n    ;\n    \ntypeArgument\n    :   type\n    |   '?' (('extends' | 'super') type)?\n    ;\n    \nqualifiedNameList\n    :   qualifiedName (',' qualifiedName)*\n    ;\n\nformalParameters\n    :   '(' formalParameterDecls? ')'\n    ;\n    \nformalParameterDecls\n    :   variableModifiers type formalParameterDeclsRest\n    ;\n    \nformalParameterDeclsRest\n    :   variableDeclaratorId (',' formalParameterDecls)?\n    |   '...' variableDeclaratorId\n    ;\n    \nmethodBody\n    :   block\n    ;\n\nconstructorBody\n    :   block\n    ;\n\nqualifiedName\n    :   Identifier ('.' Identifier)*\n    ;\n    \nliteral \n    :   IntegerLiteral\n    |   FloatingPointLiteral\n    |   CharacterLiteral\n    |   StringLiteral\n    |   BooleanLiteral\n    |   'null'\n    ;\n\n// ANNOTATIONS\n\nannotations\n    :   annotation+\n    ;\n\nannotation\n    :   '@' annotationName ( '(' ( elementValuePairs | elementValue )? ')' )?\n    ;\n    \nannotationName\n    : Identifier ('.' Identifier)*\n    ;\n\nelementValuePairs\n    :   elementValuePair (',' elementValuePair)*\n    ;\n\nelementValuePair\n    :   Identifier '=' elementValue\n    ;\n    \nelementValue\n    :   expression\n    |   annotation\n    |   elementValueArrayInitializer\n    ;\n    \nelementValueArrayInitializer\n    :   '{' (elementValue (',' elementValue)*)? (',')? '}'\n    ;\n    \nannotationTypeDeclaration\n    :   '@' 'interface' Identifier annotationTypeBody\n    ;\n    \nannotationTypeBody\n    :   '{' (annotationTypeElementDeclaration)* '}'\n    ;\n    \nannotationTypeElementDeclaration\n    :   modifiers annotationTypeElementRest\n\t|\t';' // this is not allowed by the grammar, but apparently allowed by the actual compiler\n    ;\n    \nannotationTypeElementRest\n    :   type annotationMethodOrConstantRest ';'\n    |   normalClassDeclaration ';'?\n    |   normalInterfaceDeclaration ';'?\n    |   enumDeclaration ';'?\n    |   annotationTypeDeclaration ';'?\n    ;\n    \nannotationMethodOrConstantRest\n    :   annotationMethodRest\n    |   annotationConstantRest\n    ;\n    \nannotationMethodRest\n    :   Identifier '(' ')' defaultValue?\n    ;\n    \nannotationConstantRest\n    :   variableDeclarators\n    ;\n    \ndefaultValue\n    :   'default' elementValue\n    ;\n\n// STATEMENTS / BLOCKS\n\nblock\n    :   '{' blockStatement* '}'\n    ;\n    \nblockStatement\n    :   localVariableDeclarationStatement\n    |   classOrInterfaceDeclaration\n    |   statement\n    ;\n    \nlocalVariableDeclarationStatement\n    :    localVariableDeclaration ';'\n    ;\n\nlocalVariableDeclaration\n    :   variableModifiers type variableDeclarators\n    ;\n    \nvariableModifiers\n    :   variableModifier*\n    ;\n\nstatement\n    : block\n    |   ASSERT expression (':' expression)? ';'\n    |   'if' parExpression statement ('else' statement)?\n    |   'for' '(' forControl ')' statement\n    |   'while' parExpression statement\n    |   'do' statement 'while' parExpression ';'\n    |   'try' block (catches finallyBlock? | finallyBlock)\n\t|\t'try' resourceSpecification block catches? finallyBlock?\n    |   'switch' parExpression '{' switchBlockStatementGroups '}'\n    |   'synchronized' parExpression block\n    |   'return' expression? ';'\n    |   'throw' expression ';'\n    |   'break' Identifier? ';'\n    |   'continue' Identifier? ';'\n    |   ';' \n    |   statementExpression ';'\n    |   Identifier ':' statement\n    ;\n\ncatches\n    :   catchClause+\n    ;\n\ncatchClause\n    :   'catch' '(' variableModifiers catchType Identifier ')' block\n    ;\n\ncatchType\n\t:\tqualifiedName ('|' qualifiedName)*\n\t;\n\nfinallyBlock\n\t:\t'finally' block\n\t;\n\nresourceSpecification\n\t:\t'(' resources ';'? ')'\n\t;\n\nresources\n\t:\tresource (';' resource)*\n\t;\n\nresource\n\t:\tvariableModifiers classOrInterfaceType variableDeclaratorId '=' expression\n\t;\n\nformalParameter\n    :   variableModifiers type variableDeclaratorId\n    ;\n        \nswitchBlockStatementGroups\n    :   (switchBlockStatementGroup)*\n    ;\n    \n/* The change here (switchLabel -> switchLabel+) technically makes this grammar\n   ambiguous; but with appropriately greedy parsing it yields the most\n   appropriate AST, one in which each group, except possibly the last one, has\n   labels and statements. */\nswitchBlockStatementGroup\n    :   switchLabel+ blockStatement*\n    ;\n    \nswitchLabel\n    :   'case' constantExpression ':'\n    |   'case' enumConstantName ':'\n    |   'default' ':'\n    ;\n    \nforControl\n    :   enhancedForControl\n    |   forInit? ';' expression? ';' forUpdate?\n    ;\n\nforInit\n    :   localVariableDeclaration\n    |   expressionList\n    ;\n    \nenhancedForControl\n    :   variableModifiers type Identifier ':' expression\n    ;\n\nforUpdate\n    :   expressionList\n    ;\n\n// EXPRESSIONS\n\nparExpression\n    :   '(' expression ')'\n    ;\n    \nexpressionList\n    :   expression (',' expression)*\n    ;\n\nstatementExpression\n    :   expression\n    ;\n    \nconstantExpression\n    :   expression\n    ;\n    \nexpression\n\t:   primary\n    |   expression '.' Identifier\n    |   expression '.' 'this'\n    |   expression '.' 'new' nonWildcardTypeArguments? innerCreator\n    |   expression '.' 'super' superSuffix\n    |\texpression '.' explicitGenericInvocation\n    |   'new' creator\n    |   expression '[' expression ']'\n    |   '(' type ')' expression\n    |   expression ('++' | '--')\n    |   expression '(' expressionList? ')'\n    |   ('+'|'-'|'++'|'--') expression\n    |   ('~'|'!') expression\n    |   expression ('*'|'/'|'%') expression\n    |   expression ('+'|'-') expression\n    |   expression ('<' '<' | '>' '>' '>' | '>' '>') expression\n    |   expression ('<=' | '>=' | '>' | '<') expression\n\t|   expression 'instanceof' type\n\t|   expression ('==' | '!=') expression\n\t|   expression '&' expression\n\t|   expression '^' expression\n\t|   expression '|' expression\n\t|   expression '&&' expression\n\t|   expression '||' expression\n\t|   expression '?' expression ':' expression\n\t|<assoc=right> expression\n        (\t'='\n        |\t'+='\n        |\t'-='\n        |\t'*='\n        |\t'/='\n        |\t'&='\n        |\t'|='\n        |\t'^='\n        |\t'>>='\n        |\t'>>>='\n        |\t'<<='\n        |\t'%='\n        )\n        expression\n    ;\n\nprimary\n\t:\t'(' expression ')'\n    |   'this'\n    |   'super'\n    |   literal\n    |   Identifier\n    |   type '.' 'class'\n    |   'void' '.' 'class'\n\t|\tnonWildcardTypeArguments (explicitGenericInvocationSuffix | 'this' arguments)\n    ;\n\ncreator\n    :   nonWildcardTypeArguments createdName classCreatorRest\n    |   createdName (arrayCreatorRest | classCreatorRest)\n    ;\n\ncreatedName\n    :   Identifier typeArgumentsOrDiamond? ('.' Identifier typeArgumentsOrDiamond?)*\n    |   primitiveType\n    ;\n    \ninnerCreator\n    :   Identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest\n    ;\n\narrayCreatorRest\n    :   '['\n        (   ']' ('[' ']')* arrayInitializer\n        |   expression ']' ('[' expression ']')* ('[' ']')*\n        )\n    ;\n\nclassCreatorRest\n    :   arguments classBody?\n    ;\n    \nexplicitGenericInvocation\n    :\tnonWildcardTypeArguments explicitGenericInvocationSuffix\n    ;\n    \nnonWildcardTypeArguments\n    :   '<' typeList '>'\n    ;\n\ntypeArgumentsOrDiamond\n\t:\t'<' '>'\n\t|\ttypeArguments\n\t;\n\nnonWildcardTypeArgumentsOrDiamond\n\t:\t'<' '>'\n\t|\tnonWildcardTypeArguments\n\t;\n\nsuperSuffix\n    :   arguments\n    |   '.' Identifier arguments?\n    ;\n\nexplicitGenericInvocationSuffix\n\t:\t'super' superSuffix\n\t|\tIdentifier arguments\n\t;\n\narguments\n    :   '(' expressionList? ')'\n    ;\n\n// LEXER\n\n// §3.9 Keywords\n\nABSTRACT : 'abstract';\nASSERT : 'assert';\nBOOLEAN : 'boolean';\nBREAK : 'break';\nBYTE : 'byte';\nCASE : 'case';\nCATCH : 'catch';\nCHAR : 'char';\nCLASS : 'class';\nCONST : 'const';\nCONTINUE : 'continue';\nDEFAULT : 'default';\nDO : 'do';\nDOUBLE : 'double';\nELSE : 'else';\nENUM : 'enum';\nEXTENDS : 'extends';\nFINAL : 'final';\nFINALLY : 'finally';\nFLOAT : 'float';\nFOR : 'for';\nIF : 'if';\nGOTO : 'goto';\nIMPLEMENTS : 'implements';\nIMPORT : 'import';\nINSTANCEOF : 'instanceof';\nINT : 'int';\nINTERFACE : 'interface';\nLONG : 'long';\nNATIVE : 'native';\nNEW : 'new';\nPACKAGE : 'package';\nPRIVATE : 'private';\nPROTECTED : 'protected';\nPUBLIC : 'public';\nRETURN : 'return';\nSHORT : 'short';\nSTATIC : 'static';\nSTRICTFP : 'strictfp';\nSUPER : 'super';\nSWITCH : 'switch';\nSYNCHRONIZED : 'synchronized';\nTHIS : 'this';\nTHROW : 'throw';\nTHROWS : 'throws';\nTRANSIENT : 'transient';\nTRY : 'try';\nVOID : 'void';\nVOLATILE : 'volatile';\nWHILE : 'while';\n\n// §3.10.1 Integer Literals\n\nIntegerLiteral\n\t:\tDecimalIntegerLiteral\n\t|\tHexIntegerLiteral\n\t|\tOctalIntegerLiteral\n\t|\tBinaryIntegerLiteral\n\t;\n\nfragment\nDecimalIntegerLiteral\n\t:\tDecimalNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nHexIntegerLiteral\n\t:\tHexNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nOctalIntegerLiteral\n\t:\tOctalNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nBinaryIntegerLiteral\n\t:\tBinaryNumeral IntegerTypeSuffix?\n\t;\n\nfragment\nIntegerTypeSuffix\n\t:\t[lL]\n\t;\n\nfragment\nDecimalNumeral\n\t:\t'0'\n\t|\tNonZeroDigit (Digits? | Underscores Digits)\n\t;\n\nfragment\nDigits\n\t:\tDigit (DigitsAndUnderscores? Digit)?\n\t;\n\nfragment\nDigit\n\t:\t'0'\n\t|\tNonZeroDigit\n\t;\n\nfragment\nNonZeroDigit\n\t:\t[1-9]\n\t;\n\nfragment\nDigitsAndUnderscores\n\t:\tDigitOrUnderscore+\n\t;\n\nfragment\nDigitOrUnderscore\n\t:\tDigit\n\t|\t'_'\n\t;\n\nfragment\nUnderscores\n\t:\t'_'+\n\t;\n\nfragment\nHexNumeral\n\t:\t'0' [xX] HexDigits\n\t;\n\nfragment\nHexDigits\n\t:\tHexDigit (HexDigitsAndUnderscores? HexDigit)?\n\t;\n\nfragment\nHexDigit\n\t:\t[0-9a-fA-F]\n\t;\n\nfragment\nHexDigitsAndUnderscores\n\t:\tHexDigitOrUnderscore+\n\t;\n\nfragment\nHexDigitOrUnderscore\n\t:\tHexDigit\n\t|\t'_'\n\t;\n\nfragment\nOctalNumeral\n\t:\t'0' Underscores? OctalDigits\n\t;\n\nfragment\nOctalDigits\n\t:\tOctalDigit (OctalDigitsAndUnderscores? OctalDigit)?\n\t;\n\nfragment\nOctalDigit\n\t:\t[0-7]\n\t;\n\nfragment\nOctalDigitsAndUnderscores\n\t:\tOctalDigitOrUnderscore+\n\t;\n\nfragment\nOctalDigitOrUnderscore\n\t:\tOctalDigit\n\t|\t'_'\n\t;\n\nfragment\nBinaryNumeral\n\t:\t'0' [bB] BinaryDigits\n\t;\n\nfragment\nBinaryDigits\n\t:\tBinaryDigit (BinaryDigitsAndUnderscores? BinaryDigit)?\n\t;\n\nfragment\nBinaryDigit\n\t:\t[01]\n\t;\n\nfragment\nBinaryDigitsAndUnderscores\n\t:\tBinaryDigitOrUnderscore+\n\t;\n\nfragment\nBinaryDigitOrUnderscore\n\t:\tBinaryDigit\n\t|\t'_'\n\t;\n\n// §3.10.2 Floating-Point Literals\n\nFloatingPointLiteral\n\t:\tDecimalFloatingPointLiteral\n\t|\tHexadecimalFloatingPointLiteral\n\t;\n\nfragment\nDecimalFloatingPointLiteral\n\t:\tDigits '.' Digits? ExponentPart? FloatTypeSuffix?\n\t|\t'.' Digits ExponentPart? FloatTypeSuffix?\n\t|\tDigits ExponentPart FloatTypeSuffix?\n\t|\tDigits FloatTypeSuffix\n\t;\n\nfragment\nExponentPart\n\t:\tExponentIndicator SignedInteger\n\t;\n\nfragment\nExponentIndicator\n\t:\t[eE]\n\t;\n\nfragment\nSignedInteger\n\t:\tSign? Digits\n\t;\n\nfragment\nSign\n\t:\t[+-]\n\t;\n\nfragment\nFloatTypeSuffix\n\t:\t[fFdD]\n\t;\n\nfragment\nHexadecimalFloatingPointLiteral\n\t:\tHexSignificand BinaryExponent FloatTypeSuffix?\n\t;\n\nfragment\nHexSignificand\n\t:\tHexNumeral '.'?\n\t|\t'0' [xX] HexDigits? '.' HexDigits\n\t;\n\nfragment\nBinaryExponent\n\t:\tBinaryExponentIndicator SignedInteger\n\t;\n\nfragment\nBinaryExponentIndicator\n\t:\t[pP]\n\t;\n\n// §3.10.3 Boolean Literals\n\nBooleanLiteral\n\t:\t'true'\n\t|\t'false'\n\t;\n\n// §3.10.4 Character Literals\n\nCharacterLiteral\n\t:\t'\\'' SingleCharacter '\\''\n\t|\t'\\'' EscapeSequence '\\''\n\t;\n\nfragment\nSingleCharacter\n\t:\t~['\\\\]\n\t;\n\n// §3.10.5 String Literals\n\nStringLiteral\n\t:\t'\"' StringCharacters? '\"'\n\t;\n\nfragment\nStringCharacters\n\t:\tStringCharacter+\n\t;\n\nfragment\nStringCharacter\n\t:\t~[\"\\\\]\n\t|\tEscapeSequence\n\t;\n\n// §3.10.6 Escape Sequences for Character and String Literals\n\nfragment\nEscapeSequence\n\t:\t'\\\\' [btnfr\"'\\\\]\n\t|\tOctalEscape\n\t;\n\nfragment\nOctalEscape\n\t:\t'\\\\' OctalDigit\n\t|\t'\\\\' OctalDigit OctalDigit\n\t|\t'\\\\' ZeroToThree OctalDigit OctalDigit\n\t;\n\nfragment\nZeroToThree\n\t:\t[0-3]\n\t;\n\n// §3.10.7 The Null Literal\n\nNullLiteral\n\t:\t'null'\n\t;\n\n// §3.11 Separators\n\nLPAREN : '(';\nRPAREN : ')';\nLBRACE : '{';\nRBRACE : '}';\nLBRACK : '[';\nRBRACK : ']';\nSEMI : ';';\nCOMMA : ',';\nDOT : '.';\n\n// §3.12 Operators\n\nASSIGN : '=';\nGT : '>';\nLT : '<';\nBANG : '!';\nTILDE : '~';\nQUESTION : '?';\nCOLON : ':';\nEQUAL : '==';\nLE : '<=';\nGE : '>=';\nNOTEQUAL : '!=';\nAND : '&&';\nOR : '||';\nINC : '++';\nDEC : '--';\nADD : '+';\nSUB : '-';\nMUL : '*';\nDIV : '/';\nBITAND : '&';\nBITOR : '|';\nCARET : '^';\nMOD : '%';\n\nADD_ASSIGN : '+=';\nSUB_ASSIGN : '-=';\nMUL_ASSIGN : '*=';\nDIV_ASSIGN : '/=';\nAND_ASSIGN : '&=';\nOR_ASSIGN : '|=';\nXOR_ASSIGN : '^=';\nMOD_ASSIGN : '%=';\nLSHIFT_ASSIGN : '<<=';\nRSHIFT_ASSIGN : '>>=';\nURSHIFT_ASSIGN : '>>>=';\n\n// §3.8 Identifiers (must appear after all keywords in the grammar)\n\nIdentifier\n\t:\tJavaLetter JavaLetterOrDigit*\n\t;\n\nfragment\nJavaLetter\n\t:\t[a-zA-Z$_] // these are the \"java letters\" below 0xFF\n\t|\t// covers all characters above 0xFF which are not a surrogate\n\t\t~[\\u0000-\\u00FF\\uD800-\\uDBFF]\n\t\t{Character.isJavaIdentifierStart(_input.LA(-1))}?\n\t|\t// covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF\n\t\t[\\uD800-\\uDBFF] [\\uDC00-\\uDFFF]\n\t\t{Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?\n\t;\n\nfragment\nJavaLetterOrDigit\n\t:\t[a-zA-Z0-9$_] // these are the \"java letters or digits\" below 0xFF\n\t|\t// covers all characters above 0xFF which are not a surrogate\n\t\t~[\\u0000-\\u00FF\\uD800-\\uDBFF]\n\t\t{Character.isJavaIdentifierPart(_input.LA(-1))}?\n\t|\t// covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF\n\t\t[\\uD800-\\uDBFF] [\\uDC00-\\uDFFF]\n\t\t{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?\n\t;\n\n//\n// Additional symbols not defined in the lexical specification\n//\n\nAT : '@';\nELLIPSIS : '...';\n\n//\n// Whitespace and comments\n//\n\nWS  :  [ \\t\\r\\n\\u000C]+ -> skip\n    ;\n\nCOMMENT\n    :   '/*' .*? '*/' -> skip\n    ;\n\nLINE_COMMENT\n    :   '//' ~[\\r\\n]* -> skip\n    ;\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/JavaUnicodeInputStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.misc.Interval;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class JavaUnicodeInputStream implements CharStream {\n\n\tprivate final CharStream source;\n\tprivate final IntegerList escapeIndexes = new IntegerList();\n\tprivate final IntegerList escapeCharacters = new IntegerList();\n\tprivate final IntegerList escapeIndirectionLevels = new IntegerList();\n\n\tprivate int escapeListIndex;\n\tprivate int range;\n\tprivate int slashCount;\n\n\tprivate int la1;\n\n\tpublic JavaUnicodeInputStream(CharStream source) {\n\t\tif (source == null) {\n\t\t\tthrow new NullPointerException(\"source\");\n\t\t}\n\n\t\tthis.source = source;\n\t\tthis.la1 = source.LA(1);\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn source.size();\n\t}\n\n\t@Override\n\tpublic int index() {\n\t\treturn source.index();\n\t}\n\n\t@Override\n\tpublic String getSourceName() {\n\t\treturn source.getSourceName();\n\t}\n\n\t@Override\n\tpublic String getText(Interval interval) {\n\t\treturn source.getText(interval);\n\t}\n\n\t@Override\n\tpublic void consume() {\n\t\tif (la1 != '\\\\') {\n\t\t\tsource.consume();\n\t\t\tla1 = source.LA(1);\n\t\t\trange = Math.max(range, source.index());\n\t\t\tslashCount = 0;\n\t\t\treturn;\n\t\t}\n\n\t\t// make sure the next character has been processed\n\t\tthis.LA(1);\n\n\t\tif (escapeListIndex >= escapeIndexes.size() || escapeIndexes.get(escapeListIndex) != index()) {\n\t\t\tsource.consume();\n\t\t\tslashCount++;\n\t\t}\n\t\telse {\n\t\t\tint indirectionLevel = escapeIndirectionLevels.get(escapeListIndex);\n\t\t\tfor (int i = 0; i < 6 + indirectionLevel; i++) {\n\t\t\t\tsource.consume();\n\t\t\t}\n\n\t\t\tescapeListIndex++;\n\t\t\tslashCount = 0;\n\t\t}\n\n\t\tla1 = source.LA(1);\n\t\tassert range >= index();\n\t}\n\n\t@Override\n\tpublic int LA(int i) {\n\t\tif (i == 1 && la1 != '\\\\') {\n\t\t\treturn la1;\n\t\t}\n\n\t\tif (i <= 0) {\n\t\t\tint desiredIndex = index() + i;\n\t\t\tfor (int j = escapeListIndex - 1; j >= 0; j--) {\n\t\t\t\tif (escapeIndexes.get(j) + 6 + escapeIndirectionLevels.get(j) > desiredIndex) {\n\t\t\t\t\tdesiredIndex -= 5 + escapeIndirectionLevels.get(j);\n\t\t\t\t}\n\n\t\t\t\tif (escapeIndexes.get(j) == desiredIndex) {\n\t\t\t\t\treturn escapeCharacters.get(j);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn source.LA(desiredIndex - index());\n\t\t}\n\t\telse {\n\t\t\tint desiredIndex = index() + i - 1;\n\t\t\tfor (int j = escapeListIndex; j < escapeIndexes.size(); j++) {\n\t\t\t\tif (escapeIndexes.get(j) == desiredIndex) {\n\t\t\t\t\treturn escapeCharacters.get(j);\n\t\t\t\t}\n\t\t\t\telse if (escapeIndexes.get(j) < desiredIndex) {\n\t\t\t\t\tdesiredIndex += 5 + escapeIndirectionLevels.get(j);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn source.LA(desiredIndex - index() + 1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint[] currentIndex = { index() };\n\t\t\tint[] slashCountPtr = { slashCount };\n\t\t\tint[] indirectionLevelPtr = { 0 };\n\t\t\tfor (int j = 0; j < i; j++) {\n\t\t\t\tint previousIndex = currentIndex[0];\n\t\t\t\tint c = readCharAt(currentIndex, slashCountPtr, indirectionLevelPtr);\n\t\t\t\tif (currentIndex[0] > range) {\n\t\t\t\t\tif (currentIndex[0] - previousIndex > 1) {\n\t\t\t\t\t\tescapeIndexes.add(previousIndex);\n\t\t\t\t\t\tescapeCharacters.add(c);\n\t\t\t\t\t\tescapeIndirectionLevels.add(indirectionLevelPtr[0]);\n\t\t\t\t\t}\n\n\t\t\t\t\trange = currentIndex[0];\n\t\t\t\t}\n\n\t\t\t\tif (j == i - 1) {\n\t\t\t\t\treturn c;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new IllegalStateException(\"shouldn't be reachable\");\n\t\t}\n\t}\n\n\t@Override\n\tpublic int mark() {\n\t\treturn source.mark();\n\t}\n\n\t@Override\n\tpublic void release(int marker) {\n\t\tsource.release(marker);\n\t}\n\n\t@Override\n\tpublic void seek(int index) {\n\t\tif (index > range) {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\n\t\tsource.seek(index);\n\t\tla1 = source.LA(1);\n\n\t\tslashCount = 0;\n\t\twhile (source.LA(-slashCount - 1) == '\\\\') {\n\t\t\tslashCount++;\n\t\t}\n\n\t\tescapeListIndex = escapeIndexes.binarySearch(source.index());\n\t\tif (escapeListIndex < 0) {\n\t\t\tescapeListIndex = -escapeListIndex - 1;\n\t\t}\n\t}\n\n\tprivate static boolean isHexDigit(int c) {\n\t\treturn c >= '0' && c <= '9'\n\t\t\t|| c >= 'a' && c <= 'f'\n\t\t\t|| c >= 'A' && c <= 'F';\n\t}\n\n\tprivate static int hexValue(int c) {\n\t\tif (c >= '0' && c <= '9') {\n\t\t\treturn c - '0';\n\t\t}\n\n\t\tif (c >= 'a' && c <= 'f') {\n\t\t\treturn c - 'a' + 10;\n\t\t}\n\n\t\tif (c >= 'A' && c <= 'F') {\n\t\t\treturn c - 'A' + 10;\n\t\t}\n\n\t\tthrow new IllegalArgumentException(\"c\");\n\t}\n\n\tprivate int readCharAt(int[] nextIndexPtr, int[] slashCountPtr, int[] indirectionLevelPtr) {\n\t\tassert nextIndexPtr != null && nextIndexPtr.length == 1;\n\t\tassert slashCountPtr != null && slashCountPtr.length == 1;\n\t\tassert indirectionLevelPtr != null && indirectionLevelPtr.length == 1;\n\n\t\tboolean blockUnicodeEscape = (slashCountPtr[0] % 2) != 0;\n\n\t\tint c0 = source.LA(nextIndexPtr[0] - index() + 1);\n\t\tif (c0 == '\\\\') {\n\t\t\tslashCountPtr[0]++;\n\n\t\t\tif (!blockUnicodeEscape) {\n\t\t\t\tint c1 = source.LA(nextIndexPtr[0] - index() + 2);\n\t\t\t\tif (c1 == 'u') {\n\t\t\t\t\tint c2 = source.LA(nextIndexPtr[0] - index() + 3);\n\t\t\t\t\tindirectionLevelPtr[0] = 0;\n\t\t\t\t\twhile (c2 == 'u') {\n\t\t\t\t\t\tindirectionLevelPtr[0]++;\n\t\t\t\t\t\tc2 = source.LA(nextIndexPtr[0] - index() + 3 + indirectionLevelPtr[0]);\n\t\t\t\t\t}\n\n\t\t\t\t\tint c3 = source.LA(nextIndexPtr[0] - index() + 4 + indirectionLevelPtr[0]);\n\t\t\t\t\tint c4 = source.LA(nextIndexPtr[0] - index() + 5 + indirectionLevelPtr[0]);\n\t\t\t\t\tint c5 = source.LA(nextIndexPtr[0] - index() + 6 + indirectionLevelPtr[0]);\n\t\t\t\t\tif (isHexDigit(c2) && isHexDigit(c3) && isHexDigit(c4) && isHexDigit(c5)) {\n\t\t\t\t\t\tint value = hexValue(c2);\n\t\t\t\t\t\tvalue = (value << 4) + hexValue(c3);\n\t\t\t\t\t\tvalue = (value << 4) + hexValue(c4);\n\t\t\t\t\t\tvalue = (value << 4) + hexValue(c5);\n\n\t\t\t\t\t\tnextIndexPtr[0] += 6 + indirectionLevelPtr[0];\n\t\t\t\t\t\tslashCountPtr[0] = 0;\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnextIndexPtr[0]++;\n\t\treturn c0;\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/MockIntTokenStream.java",
    "content": "package org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.runtime.misc.Interval;\n\npublic class MockIntTokenStream implements TokenStream {\n\n\tpublic IntegerList types;\n\tint p=0;\n\n\tpublic MockIntTokenStream(IntegerList types) { this.types = types; }\n\n\t@Override\n\tpublic void consume() { p++; }\n\n\t@Override\n\tpublic int LA(int i) { return LT(i).getType(); }\n\n\t@Override\n\tpublic int mark() {\n\t\treturn index();\n\t}\n\n\t@Override\n\tpublic int index() { return p; }\n\n\t@Override\n\tpublic void release(int marker) {\n\t\tseek(marker);\n\t}\n\n\t@Override\n\tpublic void seek(int index) {\n\t\tp = index;\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn types.size();\n\t}\n\n\t@Override\n\tpublic String getSourceName() {\n\t\treturn UNKNOWN_SOURCE_NAME;\n\t}\n\n\t@Override\n\tpublic Token LT(int i) {\n\t\tCommonToken t;\n\t\tint rawIndex = p + i - 1;\n\t\tif ( rawIndex>=types.size() ) t = new CommonToken(Token.EOF);\n\t\telse t = new CommonToken(types.get(rawIndex));\n\t\tt.setTokenIndex(rawIndex);\n\t\treturn t;\n\t}\n\n\t@Override\n\tpublic Token get(int i) {\n\t\treturn new org.antlr.v4.runtime.CommonToken(types.get(i));\n\t}\n\n\t@Override\n\tpublic TokenSource getTokenSource() {\n\t\treturn null;\n\t}\n\n\n\t@Override\n\tpublic String getText() {\n\t\tthrow new UnsupportedOperationException(\"can't give strings\");\n\t}\n\n\n\t@Override\n\tpublic String getText(Interval interval) {\n\t\tthrow new UnsupportedOperationException(\"can't give strings\");\n\t}\n\n\n\t@Override\n\tpublic String getText(RuleContext ctx) {\n\t\tthrow new UnsupportedOperationException(\"can't give strings\");\n\t}\n\n\n\t@Override\n\tpublic String getText(Token start, Token stop) {\n\t\tthrow new UnsupportedOperationException(\"can't give strings\");\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/ParserInterpreterForTesting.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.ParserATNSimulator;\nimport org.antlr.v4.runtime.atn.PredictionContextCache;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.tool.Grammar;\n\npublic class ParserInterpreterForTesting {\n\tpublic static class DummyParser extends Parser {\n\t\tpublic final ATN atn;\n\t\tpublic final DFA[] decisionToDFA; // not shared for interp\n\t\tpublic final PredictionContextCache sharedContextCache =\n\t\t\tnew PredictionContextCache();\n\n\t\tpublic Grammar g;\n\t\tpublic DummyParser(Grammar g, ATN atn, TokenStream input) {\n\t\t\tsuper(input);\n\t\t\tthis.g = g;\n\t\t\tthis.atn = atn;\n\t\t\tthis.decisionToDFA = new DFA[atn.getNumberOfDecisions()];\n\t\t\tfor (int i = 0; i < decisionToDFA.length; i++) {\n\t\t\t\tdecisionToDFA[i] = new DFA(atn.getDecisionState(i), i);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic String getGrammarFileName() {\n\t\t\tthrow new UnsupportedOperationException(\"not implemented\");\n\t\t}\n\n\t\t@Override\n\t\tpublic String[] getRuleNames() {\n\t\t\treturn g.rules.keySet().toArray(new String[0]);\n\t\t}\n\n\t\t@Override\n\t\t@Deprecated\n\t\tpublic String[] getTokenNames() {\n\t\t\treturn g.getTokenNames();\n\t\t}\n\n\t\t@Override\n\t\tpublic ATN getATN() {\n\t\t\treturn atn;\n\t\t}\n\t}\n\n\tprotected Grammar g;\n\tpublic DummyParser parser;\n\tprotected ParserATNSimulator atnSimulator;\n\tprotected TokenStream input;\n\n\tpublic ParserInterpreterForTesting(Grammar g) {\n\t\tthis.g = g;\n\t}\n\n\tpublic ParserInterpreterForTesting(Grammar g, TokenStream input) {\n\t\tTool antlr = new Tool();\n\t\tantlr.process(g,false);\n\t\tparser = new DummyParser(g, g.atn, input);\n\t\tatnSimulator =\n\t\t\tnew ParserATNSimulator(parser, g.atn, parser.decisionToDFA,\n\t\t\t\t\t\t\t\t\t\t  parser.sharedContextCache);\n\t}\n\n\tpublic int adaptivePredict(TokenStream input, int decision,\n\t\t\t\t\t\t\t   ParserRuleContext outerContext)\n\t{\n\t\treturn atnSimulator.adaptivePredict(input, decision, outerContext);\n\t}\n\n\tpublic int matchATN(TokenStream input,\n\t\t\t\t\t\tATNState startState)\n\t{\n\t\tif (startState.getNumberOfTransitions() == 1) {\n\t\t\treturn 1;\n\t\t}\n\t\telse if (startState instanceof DecisionState) {\n\t\t\treturn atnSimulator.adaptivePredict(input, ((DecisionState)startState).decision, null);\n\t\t}\n\t\telse if (startState.getNumberOfTransitions() > 0) {\n\t\t\treturn 1;\n\t\t}\n\t\telse {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic ParserATNSimulator getATNSimulator() {\n\t\treturn atnSimulator;\n\t}\n\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/PositionAdjustingLexer.g4",
    "content": "/*\n * [The \"BSD license\"]\n *  Copyright (c) 2012-2016 Terence Parr\n *  Copyright (c) 2012-2016 Sam Harwell\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *  1. Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *  2. Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *  3. The name of the author may not be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlexer grammar PositionAdjustingLexer;\n\n@members {\n\t@Override\n\tpublic Token nextToken() {\n\t\tif (!(_interp instanceof PositionAdjustingLexerATNSimulator)) {\n\t\t\t_interp = new PositionAdjustingLexerATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache);\n\t\t}\n\n\t\treturn super.nextToken();\n\t}\n\n\t@Override\n\tpublic Token emit() {\n\t\tswitch (_type) {\n\t\tcase TOKENS:\n\t\t\thandleAcceptPositionForKeyword(\"tokens\");\n\t\t\tbreak;\n\n\t\tcase LABEL:\n\t\t\thandleAcceptPositionForIdentifier();\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\treturn super.emit();\n\t}\n\n\tprivate boolean handleAcceptPositionForIdentifier() {\n\t\tString tokenText = getText();\n\t\tint identifierLength = 0;\n\t\twhile (identifierLength < tokenText.length() && isIdentifierChar(tokenText.charAt(identifierLength))) {\n\t\t\tidentifierLength++;\n\t\t}\n\n\t\tif (getInputStream().index() > _tokenStartCharIndex + identifierLength) {\n\t\t\tint offset = identifierLength - 1;\n\t\t\tgetInterpreter().resetAcceptPosition(getInputStream(), _tokenStartCharIndex + offset, _tokenStartLine, _tokenStartCharPositionInLine + offset);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate boolean handleAcceptPositionForKeyword(String keyword) {\n\t\tif (getInputStream().index() > _tokenStartCharIndex + keyword.length()) {\n\t\t\tint offset = keyword.length() - 1;\n\t\t\tgetInterpreter().resetAcceptPosition(getInputStream(), _tokenStartCharIndex + offset, _tokenStartLine, _tokenStartCharPositionInLine + offset);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic PositionAdjustingLexerATNSimulator getInterpreter() {\n\t\treturn (PositionAdjustingLexerATNSimulator)super.getInterpreter();\n\t}\n\n\tprivate static boolean isIdentifierChar(char c) {\n\t\treturn Character.isLetterOrDigit(c) || c == '_';\n\t}\n\n\tprotected static class PositionAdjustingLexerATNSimulator extends LexerATNSimulator {\n\n\t\tpublic PositionAdjustingLexerATNSimulator(Lexer recog, ATN atn,\n\t\t\t\t\t\t\t\t\t\t\t\t  DFA[] decisionToDFA,\n\t\t\t\t\t\t\t\t\t\t\t\t  PredictionContextCache sharedContextCache)\n\t\t{\n\t\t\tsuper(recog, atn, decisionToDFA, sharedContextCache);\n\t\t}\n\n\t\tprotected void resetAcceptPosition(CharStream input, int index, int line, int charPositionInLine) {\n\t\t\tinput.seek(index);\n\t\t\tthis.line = line;\n\t\t\tthis.charPositionInLine = charPositionInLine;\n\t\t\tconsume(input);\n\t\t}\n\n\t}\n}\n\nASSIGN : '=' ;\nPLUS_ASSIGN : '+=' ;\nLCURLY:\t'{';\n\n// 'tokens' followed by '{'\nTOKENS : 'tokens' IGNORED '{';\n\n// IDENTIFIER followed by '+=' or '='\nLABEL\n\t:\tIDENTIFIER IGNORED '+'? '='\n\t;\n\nIDENTIFIER\n\t:\t[a-zA-Z_] [a-zA-Z0-9_]*\n\t;\n\nfragment\nIGNORED\n\t:\t[ \\t\\r\\n]*\n\t;\n\nNEWLINE\n\t:\t[\\r\\n]+ -> skip\n\t;\n\nWS\n\t:\t[ \\t]+ -> skip\n\t;\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/Psl.g4",
    "content": "grammar Psl;\n\n@parser::members\n{\n\tpublic void printPosition(String name, Token tok)\n\t{\n\t\tSystem.out.printf(\"%s: pos %d, len %d%n\",\n\t\t\t\tname, tok.getCharPositionInLine(), tok.getText().length());\n\t}\n\n\n\t/**\n\t * Checks whether a set of digit groups and commas construct\n\t * a valid command-number.\n\t *\n\t * @param digits\n\t *\t\tThe groups of digits, each group in a separate item.\n\t * @param commas\n\t *\t\tThe commas found separating the digit groups.\n\t *\n\t * There should be one more digit group than commas.\n\t * There should be no internal white space.\n\t *\n\t * @returns true (valid), false (invalid)\n\t */\n\n\tpublic boolean isValidCommaNumber(List<Token> digits, List<Token> commas)\n\t{\n\t\tToken[]\taDigits = new Token[0];\n\t\tToken[]\taCommas = new Token[0];\n\t\tint\t\tj;\n\n\t\taDigits = digits.toArray(aDigits);\n\t\taCommas = commas.toArray(aCommas);\n\t\tif (aDigits.length != aCommas.length + 1)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tfor (j = 0; j < aCommas.length; ++j)\n\t\t{\n\t\t\tint\tp1, p2, p3;\n\t\t\tp1 = aDigits[j].getCharPositionInLine()\n\t\t\t\t\t+ aDigits[j].getText().length();\n\t\t\tp2 = aCommas[j].getCharPositionInLine();\n\t\t\tp3 = aDigits[j + 1].getCharPositionInLine();\n\t\t\tif (p1 != p2 || (p2 + 1) != p3)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\n\t/**\n\t * Checks whether a the pieces of a floating-point number\n\t * construct a valid number.\n\t *\n\t * @param whole\n\t *\t\tThe whole part of the number.  Can be null.\n\t * @param period\n\t *\t\tThe decimal point.\n\t * @param fraction\n\t *\t\tThe fraction part of the number.  Can be null.\n\t *\n\t * At least one of the whole or fraction must be present.\n\t * The decimal point is required.\n\t *\n\t * @returns true (valid), false (invalid)\n\t */\n\n\tpublic boolean isValidFloatingConstant(\n\t\tToken whole,\n\t\tToken period,\n\t\tToken fraction\n\t)\n\t{\n\t\tboolean\t\tfoundDigits = false;\n\t\tint\t\t\tcolumn;\n\n\t\tif (whole != null)\n\t\t{\n\t\t\tfoundDigits = true;\n\t\t\tcolumn = whole.getCharPositionInLine()\n\t\t\t\t\t+ whole.getText().length();\n\t\t\tif (column != period.getCharPositionInLine())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (fraction != null)\n\t\t{\n\t\t\tfoundDigits = true;\n\t\t\tcolumn = period.getCharPositionInLine() + 1;\n\t\t\tif (column != fraction.getCharPositionInLine())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn foundDigits;\n\t}\n}\n\ntranslation_unit\n\t:\tnumeric_range\n\t\tEOF\n\t;\n\npattern\n\t:\tnumeric_range\n\t;\n\nnumeric_range\n\t:\tEURO_NUMBER\n\t\tPAREN_LEFT\n\t\tnumeric_endpoint\n\t\tTILDE\n\t\tnumeric_endpoint\n\t\tPAREN_RIGHT\n\t|\tNUMBER\n\t\tPAREN_LEFT\n\t\tnumeric_endpoint\n\t\tTILDE\n\t\tnumeric_endpoint\n\t\tPAREN_RIGHT\n\t;\n\nnumeric_endpoint\n\t:\t( PLUS | MINUS )? integer_constant\n\t|\t( PLUS | MINUS )? floating_constant\n\t|\t( PLUS | MINUS )? comma_number\n\t;\n\n\t/* Floating-point numbers and comma numbers are valid only\n\t * as numeric endpoints in number() or euro_number().  Otherwise,\n\t * the pieces should be parsed as separate lexical tokens, such as\n\t *\n\t *\tinteger_constant '.' integer_constant\n\t *\n\t * Because of parser lookahead and the subtle interactions between\n\t * the parser and the lexer, changing lexical modes from the parser\n\t * is not safe.  The code below checks the constraints for floating\n\t * numbers, forbidding internal white space.\n\t */\n\nfloating_constant\n\t:\tcomma_number PERIOD fraction=DIGIT_SEQUENCE?\n\t\t{\n\t\t\tisValidFloatingConstant($comma_number.stop, $PERIOD, $fraction)\n\t\t}?<fail = {\n\t\t\t\"COMMA:A floating-point constant cannot have internal white space\"\n\t\t}>\n\n\t/*|\twhole=DIGIT_SEQUENCE PERIOD fraction=DIGIT_SEQUENCE?\n\t\t{\n\t\t\tisValidFloatingConstant($whole, $PERIOD, $fraction)\n\t\t}?/* <fail = {\n\t\t\t\"DIG:A floating-point constant cannot have internal white space\"\n\t\t}>*/\n\n\t|\tPERIOD fraction=DIGIT_SEQUENCE\n\t\t{\n\t\t\tisValidFloatingConstant(null, $PERIOD, $fraction)\n\t\t}?<fail = {\n\t\t\t\"DEC:A floating-point constant cannot have internal white space\"\n\t\t}>\n\t;\n\ncomma_number\n\t:\tdigits+=DIGIT_SEQUENCE ( commas+=COMMA digits+=DIGIT_SEQUENCE )+\n\t\t{\n\t\t\tisValidCommaNumber($digits, $commas)\n\t\t}?<fail = {\n\t\t\t\"A comma-number cannot have internal white space\"\n\t\t}>\n\t;\n\nterm_expression\n\t:\tterm\n\t|\tRETURN\n\t\t(\n\t\t\tPAREN_LEFT\n\t\t\t( integer_constant | ALL )\n\t\t\tPAREN_RIGHT\n\t\t)?\n\t\tterm\n\t;\n\nterm\n\t:\tpattern\n\t|\tPAREN_LEFT term_expression PAREN_RIGHT\n\t;\n\ninteger_constant\n\t:\tDIGIT_SEQUENCE\n\t|\tINTEGER_CONSTANT\n\t|\tBINARY_CONSTANT\n\t|\tDECIMAL_CONSTANT\n\t|\tHEXADECIMAL_CONSTANT\n\t|\tOCTAL_CONSTANT\n\t;\n\n// LEXER\n\n/* Letter fragments\n */\n\nfragment A: [Aa] ;\nfragment B: [BB] ;\nfragment C: [Cc] ;\nfragment D: [Dd] ;\nfragment E: [Ee] ;\nfragment F: [Ff] ;\nfragment G: [Gg] ;\nfragment H: [Hh] ;\nfragment I: [Ii] ;\nfragment J: [Jj] ;\nfragment K: [Kk] ;\nfragment L: [Ll] ;\nfragment M: [Mm] ;\nfragment N: [Nn] ;\nfragment O: [Oo] ;\nfragment P: [Pp] ;\nfragment Q: [Qq] ;\nfragment R: [Rr] ;\nfragment S: [Ss] ;\nfragment T: [Tt] ;\nfragment U: [Uu] ;\nfragment V: [Vv] ;\nfragment W: [Ww] ;\nfragment X: [Xx] ;\nfragment Y: [Yy] ;\nfragment Z: [Zz] ;\n\n\nWHITESPACE_IN_LINE\n\t:\t[ \\t]+\n\t\t-> skip\n\t;\n\nNEWLINE\n\t:\t'\\r'? '\\n'\n\t\t-> skip\n\t;\n\nWHITESPACE_ALL\n\t:\t[ \\n\\r\\t]+\n\t\t-> skip\n\t;\n\n\n\t/* A sequence of decimal digits is useful on its own,\n\t * to avoid the base-prefixes (0b, 0x, ...) that an\n\t * INTEGER_CONTANT would allow.\n\t * Need to define before INTEGER_CONSTANT to make sure\n\t * DIGIT_SEQUENCE is recognized before INTEGER_CONSTANT.\n\t */\n\nDIGIT_SEQUENCE\n\t:\t[0-9]+\n\t;\n\nINTEGER_CONSTANT\n\t:\tBINARY_CONSTANT\n\t|\tDECIMAL_CONSTANT\n\t|\tHEXADECIMAL_CONSTANT\n\t|\tOCTAL_CONSTANT\n\t;\n\nBINARY_CONSTANT\n\t:\t'0' [Bb] [0-1]+\n\t;\n\nDECIMAL_CONSTANT\n\t:\t( '0' [Dd] )? [0-9]+\n\t;\n\nHEXADECIMAL_CONSTANT\n\t:\t'0' [HhXx] [0-9a-fA-F]+\n\t;\n\nOCTAL_CONSTANT\n\t:\t'0' [Oo] [0-7]+\n\t;\n\n/*\tkeywords\n */\n\nALL\n\t:\tA L L\n\t;\n\nEURO_NUMBER\n\t:\tE U R O '_' N U M B E R\n\t;\n\n\nNUMBER\n\t:\tN U M B E R\n\t;\n\nRETURN\n\t:\tR E T U R N\n\t;\n\nIDENTIFIER\n\t:\t[A-Za-z][A-Za-z0-9_]*\n\t;\n\n\n/* The single-character tokens.\n */\n\nCOMMA\n\t:\t','\n\t;\n\nMINUS\n\t:\t'-'\n\t;\n\nPAREN_LEFT\n\t:\t'('\n\t;\n\nPAREN_RIGHT\n\t:\t')'\n\t;\n\nPERIOD\n\t:\t'.'\n\t;\n\nPLUS\n\t:\t'+'\n\t;\n\nTILDE\n\t:\t'~'\n\t;\n\n\t/* This rule must be last (or nearly last) to avoid\n\t * matching individual characters for other rules.\n\t */\n\nANY_CHAR_BUT_NEWLINE\n\t:\t~[\\n\\r]\n\t;\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestASTStructure.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.CharStream;\nimport org.antlr.runtime.CommonTokenStream;\nimport org.antlr.runtime.Parser;\nimport org.antlr.runtime.RuleReturnScope;\nimport org.antlr.runtime.TokenSource;\nimport org.antlr.runtime.TokenStream;\nimport org.antlr.runtime.tree.Tree;\nimport org.antlr.runtime.tree.TreeAdaptor;\nimport org.junit.jupiter.api.Test;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestASTStructure {\n\tString lexerClassName = \"org.antlr.v4.parse.ANTLRLexer\";\n\tString parserClassName = \"org.antlr.v4.parse.ANTLRParser\";\n\tString  adaptorClassName = \"org.antlr.v4.parse.GrammarASTAdaptor\";\n\n\tpublic Object execParser(\n\tString ruleName,\n\tString input,\n\tint scriptLine)\n\tthrows Exception\n\t{\n\t\tANTLRStringStream is = new ANTLRStringStream(input);\n\t\tClass<? extends TokenSource> lexerClass = Class.forName(lexerClassName).asSubclass(TokenSource.class);\n\t\tConstructor<? extends TokenSource> lexConstructor = lexerClass.getConstructor(CharStream.class);\n\t\tTokenSource lexer = lexConstructor.newInstance(is);\n\t\tis.setLine(scriptLine);\n\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\n\t\tClass<? extends Parser> parserClass = Class.forName(parserClassName).asSubclass(Parser.class);\n\t\tConstructor<? extends Parser> parConstructor = parserClass.getConstructor(TokenStream.class);\n\t\tParser parser = parConstructor.newInstance(tokens);\n\n\t\t// set up customized tree adaptor if necessary\n\t\tif ( adaptorClassName!=null ) {\n\t\t\tMethod m = parserClass.getMethod(\"setTreeAdaptor\", TreeAdaptor.class);\n\t\t\tClass<? extends TreeAdaptor> adaptorClass = Class.forName(adaptorClassName).asSubclass(TreeAdaptor.class);\n\t\t\tm.invoke(parser, adaptorClass.newInstance());\n\t\t}\n\n\t\tMethod ruleMethod = parserClass.getMethod(ruleName);\n\n\t\t// INVOKE RULE\n\t\treturn ruleMethod.invoke(parser);\n\t}\n\n\t@Test public void test_grammarSpec1() throws Exception {\n\t\t// gunit test on line 15\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"grammarSpec\", \"parser grammar P; a : A;\", 15);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(PARSER_GRAMMAR P (RULES (RULE a (BLOCK (ALT A)))))\";\n\t\tassertEquals(expecting, actual, \"testing rule grammarSpec\");\n\t}\n\n\t@Test public void test_grammarSpec2() throws Exception {\n\t\t// gunit test on line 18\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"grammarSpec\", \"\\n    parser grammar P;\\n    tokens { A, B }\\n    @header {foo}\\n    a : A;\\n    \", 18);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(PARSER_GRAMMAR P (tokens { A B) (@ header {foo}) (RULES (RULE a (BLOCK (ALT A)))))\";\n\t\tassertEquals(expecting, actual, \"testing rule grammarSpec\");\n\t}\n\n\t@Test public void test_grammarSpec3() throws Exception {\n\t\t// gunit test on line 30\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"grammarSpec\", \"\\n    parser grammar P;\\n    @header {foo}\\n    tokens { A,B }\\n    a : A;\\n    \", 30);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(PARSER_GRAMMAR P (@ header {foo}) (tokens { A B) (RULES (RULE a (BLOCK (ALT A)))))\";\n\t\tassertEquals(expecting, actual, \"testing rule grammarSpec\");\n\t}\n\n\t@Test public void test_grammarSpec4() throws Exception {\n\t\t// gunit test on line 42\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"grammarSpec\", \"\\n    parser grammar P;\\n    import A=B, C;\\n    a : A;\\n    \", 42);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(PARSER_GRAMMAR P (import (= A B) C) (RULES (RULE a (BLOCK (ALT A)))))\";\n\t\tassertEquals(expecting, actual, \"testing rule grammarSpec\");\n\t} @Test public void test_delegateGrammars1() throws Exception {\n\t\t// gunit test on line 53\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"delegateGrammars\", \"import A;\", 53);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(import A)\";\n\t\tassertEquals(expecting, actual, \"testing rule delegateGrammars\");\n\t} @Test public void test_rule1() throws Exception {\n\t\t// gunit test on line 56\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"a : A<X,Y=a.b.c>;\", 56);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE a (BLOCK (ALT (A (ELEMENT_OPTIONS X (= Y a.b.c))))))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t}\n\n\t@Test public void test_rule2() throws Exception {\n\t\t// gunit test on line 58\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"A : B+;\", 58);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE A (BLOCK (ALT (+ (BLOCK (ALT B))))))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t}\n\n\t@Test public void test_rule3() throws Exception {\n\t\t// gunit test on line 60\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"\\n    a[int i] returns [int y]\\n    @init {blort}\\n      : ID ;\\n    \", 60);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE a int i (returns int y) (@ init {blort}) (BLOCK (ALT ID)))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t}\n\n\t@Test public void test_rule4() throws Exception {\n\t\t// gunit test on line 75\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"\\n    a[int i] returns [int y]\\n    @init {blort}\\n    options {backtrack=true;}\\n      : ID;\\n    \", 75);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE a int i (returns int y) (@ init {blort}) (OPTIONS (= backtrack true)) (BLOCK (ALT ID)))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t}\n\n\t@Test public void test_rule5() throws Exception {\n\t\t// gunit test on line 88\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"\\n    a : ID ;\\n      catch[A b] {foo}\\n      finally {bar}\\n    \", 88);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE a (BLOCK (ALT ID)) (catch A b {foo}) (finally {bar}))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t}\n\n\t@Test public void test_rule6() throws Exception {\n\t\t// gunit test on line 97\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"\\n    a : ID ;\\n      catch[A a] {foo}\\n      catch[B b] {fu}\\n      finally {bar}\\n    \", 97);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE a (BLOCK (ALT ID)) (catch A a {foo}) (catch B b {fu}) (finally {bar}))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t}\n\n\t@Test public void test_rule7() throws Exception {\n\t\t// gunit test on line 107\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"\\n\\ta[int i]\\n\\tlocals [int a, float b]\\n\\t\\t:\\tA\\n\\t\\t;\\n\\t\", 107);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE a int i (locals int a, float b) (BLOCK (ALT A)))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t}\n\n\t@Test public void test_rule8() throws Exception {\n\t\t// gunit test on line 115\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"rule\", \"\\n\\ta[int i] throws a.b.c\\n\\t\\t:\\tA\\n\\t\\t;\\n\\t\", 115);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(RULE a int i (throws a.b.c) (BLOCK (ALT A)))\";\n\t\tassertEquals(expecting, actual, \"testing rule rule\");\n\t} @Test public void test_ebnf1() throws Exception {\n\t\t// gunit test on line 123\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"ebnf\", \"(A|B)\", 123);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(BLOCK (ALT A) (ALT B))\";\n\t\tassertEquals(expecting, actual, \"testing rule ebnf\");\n\t}\n\n\t@Test public void test_ebnf2() throws Exception {\n\t\t// gunit test on line 124\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"ebnf\", \"(A|B)?\", 124);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(? (BLOCK (ALT A) (ALT B)))\";\n\t\tassertEquals(expecting, actual, \"testing rule ebnf\");\n\t}\n\n\t@Test public void test_ebnf3() throws Exception {\n\t\t// gunit test on line 125\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"ebnf\", \"(A|B)*\", 125);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT A) (ALT B)))\";\n\t\tassertEquals(expecting, actual, \"testing rule ebnf\");\n\t}\n\n\t@Test public void test_ebnf4() throws Exception {\n\t\t// gunit test on line 126\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"ebnf\", \"(A|B)+\", 126);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT A) (ALT B)))\";\n\t\tassertEquals(expecting, actual, \"testing rule ebnf\");\n\t} @Test public void test_element1() throws Exception {\n\t\t// gunit test on line 129\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"~A\", 129);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(~ (SET A))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element2() throws Exception {\n\t\t// gunit test on line 130\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"b+\", 130);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT b)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element3() throws Exception {\n\t\t// gunit test on line 131\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"(b)+\", 131);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT b)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element4() throws Exception {\n\t\t// gunit test on line 132\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"b?\", 132);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(? (BLOCK (ALT b)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element5() throws Exception {\n\t\t// gunit test on line 133\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"(b)?\", 133);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(? (BLOCK (ALT b)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element6() throws Exception {\n\t\t// gunit test on line 134\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"(b)*\", 134);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT b)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element7() throws Exception {\n\t\t// gunit test on line 135\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"b*\", 135);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT b)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element8() throws Exception {\n\t\t// gunit test on line 136\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"'while'*\", 136);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT 'while')))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element9() throws Exception {\n\t\t// gunit test on line 137\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"'a'+\", 137);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT 'a')))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element10() throws Exception {\n\t\t// gunit test on line 138\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"a[3]\", 138);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(a 3)\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element11() throws Exception {\n\t\t// gunit test on line 139\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"'a'..'z'+\", 139);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT (.. 'a' 'z'))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element12() throws Exception {\n\t\t// gunit test on line 140\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x=ID\", 140);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(= x ID)\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element13() throws Exception {\n\t\t// gunit test on line 141\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x=ID?\", 141);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(? (BLOCK (ALT (= x ID))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element14() throws Exception {\n\t\t// gunit test on line 142\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x=ID*\", 142);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT (= x ID))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element15() throws Exception {\n\t\t// gunit test on line 143\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x=b\", 143);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(= x b)\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element16() throws Exception {\n\t\t// gunit test on line 144\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x=(A|B)\", 144);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(= x (BLOCK (ALT A) (ALT B)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element17() throws Exception {\n\t\t// gunit test on line 145\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x=~(A|B)\", 145);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(= x (~ (SET A B)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element18() throws Exception {\n\t\t// gunit test on line 146\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x+=~(A|B)\", 146);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+= x (~ (SET A B)))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element19() throws Exception {\n\t\t// gunit test on line 147\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x+=~(A|B)+\", 147);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT (+= x (~ (SET A B))))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element20() throws Exception {\n\t\t// gunit test on line 148\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x=b+\", 148);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT (= x b))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element21() throws Exception {\n\t\t// gunit test on line 149\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x+=ID*\", 149);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT (+= x ID))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element22() throws Exception {\n\t\t// gunit test on line 150\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x+='int'*\", 150);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT (+= x 'int'))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element23() throws Exception {\n\t\t// gunit test on line 151\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"x+=b+\", 151);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(+ (BLOCK (ALT (+= x b))))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n\n\t@Test public void test_element24() throws Exception {\n\t\t// gunit test on line 152\n\t\tRuleReturnScope rstruct = (RuleReturnScope)execParser(\"element\", \"({blort} 'x')*\", 152);\n\t\tObject actual = ((Tree)rstruct.getTree()).toStringTree();\n\t\tObject expecting = \"(* (BLOCK (ALT {blort} 'x')))\";\n\t\tassertEquals(expecting, actual, \"testing rule element\");\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestATNConstruction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.automata.ATNPrinter;\nimport org.antlr.v4.automata.LexerATNFactory;\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.test.runtime.ErrorQueue;\nimport org.antlr.v4.test.runtime.RuntimeTestUtils;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.antlr.v4.tool.ast.GrammarRootAST;\nimport org.antlr.v4.tool.ast.RuleAST;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.Arrays;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\npublic class TestATNConstruction {\n\t@Test public void testA() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->s2\\n\" +\n\t\t\t\"s2-A->s3\\n\" +\n\t\t\t\"s3->RuleStop_a_1\\n\" +\n\t\t\t\"RuleStop_a_1-EOF->s4\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAB() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A B ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->s2\\n\" +\n\t\t\t\t\"s2-A->s3\\n\" +\n\t\t\t\t\"s3-B->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAorB() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A | B {;} ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_5\\n\" +\n\t\t\t\t\"BlockStart_5->s2\\n\" +\n\t\t\t\t\"BlockStart_5->s3\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_6\\n\" +\n\t\t\t\t\"s3-B->s4\\n\" +\n\t\t\t\t\"BlockEnd_6->RuleStop_a_1\\n\" +\n\t\t\t\t\"s4-action_0:-1->BlockEnd_6\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s7\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testSetAorB() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A | B ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->s2\\n\" +\n\t\t\t\t\"s2-{A, B}->s3\\n\" +\n\t\t\t\t\"s3->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s4\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testLexerIsntSetMultiCharString() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : ('0x' | '0X') ;\");\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->BlockStart_7\\n\" +\n\t\t\t\t\"BlockStart_7->s3\\n\" +\n\t\t\t\t\"BlockStart_7->s5\\n\" +\n\t\t\t\t\"s3-'0'->s4\\n\" +\n\t\t\t\t\"s5-'0'->s6\\n\" +\n\t\t\t\t\"s4-'x'->BlockEnd_8\\n\" +\n\t\t\t\t\"s6-'X'->BlockEnd_8\\n\" +\n\t\t\t\t\"BlockEnd_8->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testRange() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : 'a'..'c' ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-'a'..'c'->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSet() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [abc] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{97..99}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetRange() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [a-c] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{97..99}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodeBMPEscape() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [\\\\uABCD] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-43981->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodeBMPEscapeRange() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [a-c\\\\uABCD-\\\\uABFF] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{97..99, 43981..44031}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodeSMPEscape() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [\\\\u{10ABCD}] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-1092557->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodeSMPEscapeRange() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [a-c\\\\u{10ABCD}-\\\\u{10ABFF}] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{97..99, 1092557..1092607}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodePropertyEscape() throws Exception {\n\t\t// The Gothic script is long dead and unlikely to change (which would\n\t\t// cause this test to fail)\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [\\\\p{Gothic}] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{66352..66378}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodePropertyInvertEscape() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [\\\\P{Gothic}] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{0..66351, 66379..1114111}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodeMultiplePropertyEscape() throws Exception {\n\t\t// Ditto the Mahajani script. Not going to change soon. I hope.\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [\\\\p{Gothic}\\\\p{Mahajani}] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{66352..66378, 69968..70006}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testCharSetUnicodePropertyOverlap() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : [\\\\p{ASCII_Hex_Digit}\\\\p{Hex_Digit}] ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->s3\\n\" +\n\t\t\t\t\"s3-{48..57, 65..70, 97..102, 65296..65305, 65313..65318, 65345..65350}->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testRangeOrRange() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : ('a'..'c' 'h' | 'q' 'j'..'l') ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_1\\n\" +\n\t\t\t\t\"RuleStart_A_1->BlockStart_7\\n\" +\n\t\t\t\t\"BlockStart_7->s3\\n\" +\n\t\t\t\t\"BlockStart_7->s5\\n\" +\n\t\t\t\t\"s3-'a'..'c'->s4\\n\" +\n\t\t\t\t\"s5-'q'->s6\\n\" +\n\t\t\t\t\"s4-'h'->BlockEnd_8\\n\" +\n\t\t\t\t\"s6-'j'..'l'->BlockEnd_8\\n\" +\n\t\t\t\t\"BlockEnd_8->RuleStop_A_2\\n\";\n\t\tcheckTokensRule(g, null, expecting);\n\t}\n\t@Test public void testStringLiteralInParser() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"grammar P;\\n\"+\n\t\t\t\"a : A|'b' ;\"\n\t\t);\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->s2\\n\" +\n\t\t\t\t\"s2-{'b', A}->s3\\n\" +\n\t\t\t\t\"s3->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s4\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testABorCD() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A B | C D;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_6\\n\" +\n\t\t\t\t\"BlockStart_6->s2\\n\" +\n\t\t\t\t\"BlockStart_6->s4\\n\" +\n\t\t\t\t\"s2-A->s3\\n\" +\n\t\t\t\t\"s4-C->s5\\n\" +\n\t\t\t\t\"s3-B->BlockEnd_7\\n\" +\n\t\t\t\t\"s5-D->BlockEnd_7\\n\" +\n\t\t\t\t\"BlockEnd_7->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s8\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testbA() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : b A ;\\n\"+\n\t\t\t\"b : B ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->s4\\n\" +\n\t\t\t\t\"s4-b->RuleStart_b_2\\n\" +\n\t\t\t\t\"s5-A->s6\\n\" +\n\t\t\t\t\"s6->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s9\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t\texpecting =\n\t\t\t\"RuleStart_b_2->s7\\n\" +\n\t\t\t\t\"s7-B->s8\\n\" +\n\t\t\t\t\"s8->RuleStop_b_3\\n\" +\n\t\t\t\t\"RuleStop_b_3->s5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"b\", expecting);\n\t}\n\t@Test public void testFollow() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : b A ;\\n\"+\n\t\t\t\"b : B ;\\n\"+\n\t\t\t\"c : b C;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_b_2->s9\\n\" +\n\t\t\t\t\"s9-B->s10\\n\" +\n\t\t\t\t\"s10->RuleStop_b_3\\n\" +\n\t\t\t\t\"RuleStop_b_3->s7\\n\" +\n\t\t\t\t\"RuleStop_b_3->s12\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"b\", expecting);\n\t}\n\t@Test public void testAorEpsilon() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A | ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_4\\n\" +\n\t\t\t\t\"BlockStart_4->s2\\n\" +\n\t\t\t\t\"BlockStart_4->s3\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_5\\n\" +\n\t\t\t\t\"s3->BlockEnd_5\\n\" +\n\t\t\t\t\"BlockEnd_5->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s6\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAOptional() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A?;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_3\\n\" +\n\t\t\t\t\"BlockStart_3->s2\\n\" +\n\t\t\t\t\"BlockStart_3->BlockEnd_4\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_4\\n\" +\n\t\t\t\t\"BlockEnd_4->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAorBoptional() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : (A{;}|B)?;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_5\\n\" +\n\t\t\t\t\"BlockStart_5->s2\\n\" +\n\t\t\t\t\"BlockStart_5->s4\\n\" +\n\t\t\t\t\"BlockStart_5->BlockEnd_6\\n\" +\n\t\t\t\t\"s2-A->s3\\n\" +\n\t\t\t\t\"s4-B->BlockEnd_6\\n\" +\n\t\t\t\t\"BlockEnd_6->RuleStop_a_1\\n\" +\n\t\t\t\t\"s3-action_0:-1->BlockEnd_6\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s7\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testSetAorBoptional() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : (A|B)?;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_3\\n\" +\n\t\t\t\t\"BlockStart_3->s2\\n\" +\n\t\t\t\t\"BlockStart_3->BlockEnd_4\\n\" +\n\t\t\t\t\"s2-{A, B}->BlockEnd_4\\n\" +\n\t\t\t\t\"BlockEnd_4->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAorBthenC() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : (A | B) C;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->s2\\n\" +\n\t\t\t\t\"s2-{A, B}->s3\\n\" +\n\t\t\t\t\"s3-C->s4\\n\" +\n\t\t\t\t\"s4->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAplus() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A+;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->PlusBlockStart_3\\n\" +\n\t\t\t\t\"PlusBlockStart_3->s2\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_4\\n\" +\n\t\t\t\t\"BlockEnd_4->PlusLoopBack_5\\n\" +\n\t\t\t\t\"PlusLoopBack_5->PlusBlockStart_3\\n\" +\n\t\t\t\t\"PlusLoopBack_5->s6\\n\" +\n\t\t\t\t\"s6->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s7\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAplusSingleAltHasPlusASTPointingAtLoopBackState() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"s : a B ;\\n\" +\t\t\t// (RULE a (BLOCK (ALT (+ (BLOCK (ALT A))))))\n\t\t\t\"a : A+;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_2->PlusBlockStart_8\\n\" +\n\t\t\t\"PlusBlockStart_8->s7\\n\" +\n\t\t\t\"s7-A->BlockEnd_9\\n\" +\n\t\t\t\"BlockEnd_9->PlusLoopBack_10\\n\" +\n\t\t\t\"PlusLoopBack_10->PlusBlockStart_8\\n\" +\n\t\t\t\"PlusLoopBack_10->s11\\n\" +\n\t\t\t\"s11->RuleStop_a_3\\n\" +\n\t\t\t\"RuleStop_a_3->s5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t\t// Get all AST -> ATNState relationships. Make sure loopback is covered when no loop entry decision\n\t\tList<GrammarAST> ruleNodes = g.ast.getNodesWithType(ANTLRParser.RULE);\n\t\tRuleAST a = (RuleAST)ruleNodes.get(1);\n\t\tList<GrammarAST> nodesInRule = a.getNodesWithType(null);\n\t\tMap<GrammarAST, ATNState> covered = new LinkedHashMap<GrammarAST, ATNState>();\n\t\tfor (GrammarAST node : nodesInRule) {\n\t\t\tif ( node.atnState != null ) {\n\t\t\t\tcovered.put(node, node.atnState);\n\t\t\t}\n\t\t}\n\t\tassertEquals(\"{RULE=2, BLOCK=8, +=10, BLOCK=8, A=7}\", covered.toString());\n\t}\n\t@Test public void testAorBplus() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : (A|B{;})+;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->PlusBlockStart_5\\n\" +\n\t\t\t\t\"PlusBlockStart_5->s2\\n\" +\n\t\t\t\t\"PlusBlockStart_5->s3\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_6\\n\" +\n\t\t\t\t\"s3-B->s4\\n\" +\n\t\t\t\t\"BlockEnd_6->PlusLoopBack_7\\n\" +\n\t\t\t\t\"s4-action_0:-1->BlockEnd_6\\n\" +\n\t\t\t\t\"PlusLoopBack_7->PlusBlockStart_5\\n\" +\n\t\t\t\t\"PlusLoopBack_7->s8\\n\" +\n\t\t\t\t\"s8->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s9\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAorBorEmptyPlus() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : (A | B | )+ ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->PlusBlockStart_5\\n\" +\n\t\t\t\t\"PlusBlockStart_5->s2\\n\" +\n\t\t\t\t\"PlusBlockStart_5->s3\\n\" +\n\t\t\t\t\"PlusBlockStart_5->s4\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_6\\n\" +\n\t\t\t\t\"s3-B->BlockEnd_6\\n\" +\n\t\t\t\t\"s4->BlockEnd_6\\n\" +\n\t\t\t\t\"BlockEnd_6->PlusLoopBack_7\\n\" +\n\t\t\t\t\"PlusLoopBack_7->PlusBlockStart_5\\n\" +\n\t\t\t\t\"PlusLoopBack_7->s8\\n\" +\n\t\t\t\t\"s8->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s9\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testEmptyOrEmpty() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : | ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_4\\n\"+\n\t\t\t\"BlockStart_4->s2\\n\"+\n\t\t\t\"BlockStart_4->s3\\n\"+\n\t\t\t\"s2->BlockEnd_5\\n\"+\n\t\t\t\"s3->BlockEnd_5\\n\"+\n\t\t\t\"BlockEnd_5->RuleStop_a_1\\n\"+\n\t\t\t\"RuleStop_a_1-EOF->s6\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAStar() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : A*;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->StarLoopEntry_5\\n\" +\n\t\t\t\t\"StarLoopEntry_5->StarBlockStart_3\\n\" +\n\t\t\t\t\"StarLoopEntry_5->s6\\n\" +\n\t\t\t\t\"StarBlockStart_3->s2\\n\" +\n\t\t\t\t\"s6->RuleStop_a_1\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_4\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s8\\n\" +\n\t\t\t\t\"BlockEnd_4->StarLoopBack_7\\n\" +\n\t\t\t\t\"StarLoopBack_7->StarLoopEntry_5\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testNestedAstar() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : (COMMA ID*)*;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->StarLoopEntry_11\\n\" +\n\t\t\t\t\"StarLoopEntry_11->StarBlockStart_9\\n\" +\n\t\t\t\t\"StarLoopEntry_11->s12\\n\" +\n\t\t\t\t\"StarBlockStart_9->s2\\n\" +\n\t\t\t\t\"s12->RuleStop_a_1\\n\" +\n\t\t\t\t\"s2-COMMA->StarLoopEntry_6\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s14\\n\" +\n\t\t\t\t\"StarLoopEntry_6->StarBlockStart_4\\n\" +\n\t\t\t\t\"StarLoopEntry_6->s7\\n\" +\n\t\t\t\t\"StarBlockStart_4->s3\\n\" +\n\t\t\t\t\"s7->BlockEnd_10\\n\" +\n\t\t\t\t\"s3-ID->BlockEnd_5\\n\" +\n\t\t\t\t\"BlockEnd_10->StarLoopBack_13\\n\" +\n\t\t\t\t\"BlockEnd_5->StarLoopBack_8\\n\" +\n\t\t\t\t\"StarLoopBack_13->StarLoopEntry_11\\n\" +\n\t\t\t\t\"StarLoopBack_8->StarLoopEntry_6\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testAorBstar() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : (A | B{;})* ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->StarLoopEntry_7\\n\" +\n\t\t\t\t\"StarLoopEntry_7->StarBlockStart_5\\n\" +\n\t\t\t\t\"StarLoopEntry_7->s8\\n\" +\n\t\t\t\t\"StarBlockStart_5->s2\\n\" +\n\t\t\t\t\"StarBlockStart_5->s3\\n\" +\n\t\t\t\t\"s8->RuleStop_a_1\\n\" +\n\t\t\t\t\"s2-A->BlockEnd_6\\n\" +\n\t\t\t\t\"s3-B->s4\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s10\\n\" +\n\t\t\t\t\"BlockEnd_6->StarLoopBack_9\\n\" +\n\t\t\t\t\"s4-action_0:-1->BlockEnd_6\\n\" +\n\t\t\t\t\"StarLoopBack_9->StarLoopEntry_7\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\t@Test public void testPredicatedAorB() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : {p1}? A | {p2}? B ;\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->BlockStart_6\\n\" +\n\t\t\t\t\"BlockStart_6->s2\\n\" +\n\t\t\t\t\"BlockStart_6->s4\\n\" +\n\t\t\t\t\"s2-pred_0:0->s3\\n\" +\n\t\t\t\t\"s4-pred_0:1->s5\\n\" +\n\t\t\t\t\"s3-A->BlockEnd_7\\n\" +\n\t\t\t\t\"s5-B->BlockEnd_7\\n\" +\n\t\t\t\t\"BlockEnd_7->RuleStop_a_1\\n\" +\n\t\t\t\t\"RuleStop_a_1-EOF->s8\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"a\", expecting);\n\t}\n\n\t@Test public void testParserRuleRefInLexerRule() throws Exception {\n\t\tboolean threwException = false;\n\t\tErrorQueue errorQueue = new ErrorQueue();\n\t\ttry {\n\t\t\tString gstr =\n\t\t\t\t\"grammar U;\\n\"+\n\t\t\t\t\"a : A;\\n\"+\n\t\t\t\t\"A : a;\\n\";\n\n\t\t\tTool tool = new Tool();\n\t\t\ttool.removeListeners();\n\t\t\ttool.addListener(errorQueue);\n\t\t\tassertEquals(0, errorQueue.size());\n\t\t\tGrammarRootAST grammarRootAST = tool.parseGrammarFromString(gstr);\n\t\t\tassertEquals(0, errorQueue.size());\n\t\t\tGrammar g = tool.createGrammar(grammarRootAST);\n\t\t\tassertEquals(0, errorQueue.size());\n\t\t\tg.fileName = \"<string>\";\n\t\t\ttool.process(g, false);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrewException = true;\n\t\t\te.printStackTrace();\n\t\t}\n\t\tSystem.out.println(errorQueue);\n\t\tassertEquals(1, errorQueue.errors.size());\n\t\tassertEquals(ErrorType.PARSER_RULE_REF_IN_LEXER_RULE, errorQueue.errors.get(0).getErrorType());\n\t\tassertEquals(\"[a, A]\", Arrays.toString(errorQueue.errors.get(0).getArgs()));\n\t\tassertTrue(!threwException);\n\t}\n\n\t/** Test for https://github.com/antlr/antlr4/issues/1369\n\t *  Repeated edges:\n\n\t RuleStop_e_3->BlockEnd_26\n\t RuleStop_e_3->BlockEnd_26\n\t RuleStop_e_3->BlockEnd_26\n\n\t * @throws Exception\n\t */\n\t@Test public void testForRepeatedTransitionsToStopState() throws Exception {\n\t\tString gstr =\n\t\t\t\"grammar T;\\n\"+\n\t\t\t\"\\t s : e EOF;\\n\"+\n\t\t\t\"\\t e :<assoc=right> e '*' e\\n\"+\n\t\t\t\"\\t   |<assoc=right> e '+' e\\n\"+\n\t\t\t\"\\t   |<assoc=right> e '?' e ':' e\\n\"+\n\t\t\t\"\\t   |<assoc=right> e '=' e\\n\"+\n\t\t\t\"\\t   | ID\\n\"+\n\t\t\t\"\\t   ;\\n\"+\n\t\t\t\"\\t ID : 'a'..'z'+ ;\\n\"+\n\t\t\t\"\\t WS : (' '|'\\\\n') -> skip ;\";\n\t\tGrammar g = new Grammar(gstr);\n\t\tString expecting =\n\t\t\t\"RuleStart_e_2->s7\\n\"+\n\t\t\t\"s7-action_1:-1->s8\\n\"+\n\t\t\t\"s8-ID->s9\\n\"+\n\t\t\t\"s9->StarLoopEntry_27\\n\"+\n\t\t\t\"StarLoopEntry_27->StarBlockStart_25\\n\"+\n\t\t\t\"StarLoopEntry_27->s28\\n\"+\n\t\t\t\"StarBlockStart_25->s10\\n\"+\n\t\t\t\"StarBlockStart_25->s13\\n\"+\n\t\t\t\"StarBlockStart_25->s16\\n\"+\n\t\t\t\"StarBlockStart_25->s22\\n\"+\n\t\t\t\"s28->RuleStop_e_3\\n\"+\n\t\t\t\"s10-5 >= _p->s11\\n\"+\n\t\t\t\"s13-4 >= _p->s14\\n\"+\n\t\t\t\"s16-3 >= _p->s17\\n\"+\n\t\t\t\"s22-2 >= _p->s23\\n\"+\n\t\t\t\"RuleStop_e_3->s5\\n\"+\n\t\t\t\"RuleStop_e_3->BlockEnd_26\\n\"+\n\t\t\t\"RuleStop_e_3->s19\\n\"+\n\t\t\t\"RuleStop_e_3->s21\\n\"+\n\t\t\t\"s11-'*'->s12\\n\"+\n\t\t\t\"s14-'+'->s15\\n\"+\n\t\t\t\"s17-'?'->s18\\n\"+\n\t\t\t\"s23-'='->s24\\n\"+\n\t\t\t\"s12-e->RuleStart_e_2\\n\"+\n\t\t\t\"s15-e->RuleStart_e_2\\n\"+\n\t\t\t\"s18-e->RuleStart_e_2\\n\"+\n\t\t\t\"s24-e->RuleStart_e_2\\n\"+\n\t\t\t\"BlockEnd_26->StarLoopBack_29\\n\"+\n\t\t\t\"s19-':'->s20\\n\"+\n\t\t\t\"StarLoopBack_29->StarLoopEntry_27\\n\"+\n\t\t\t\"s20-e->RuleStart_e_2\\n\"+\n\t\t\t\"s21->BlockEnd_26\\n\";\n\t\tRuntimeTestUtils.checkRuleATN(g, \"e\", expecting);\n\t}\n\n\n/*\n\t@Test public void testMultiplePredicates() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : {p1}? {p1a}? A | {p2}? B | {p3} b;\\n\" +\n\t\t\t\"b : {p4}? B ;\");\n\t\tString expecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"a\", expecting);\n\t}\n\t@Test public void testSets() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"a : ( A | B )+ ;\\n\" +\n\t\t\t\"b : ( A | B{;} )+ ;\\n\" +\n\t\t\t\"c : (A|B) (A|B) ;\\n\" +\n\t\t\t\"d : ( A | B )* ;\\n\" +\n\t\t\t\"e : ( A | B )? ;\");\n\t\tString expecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"a\", expecting);\n\t\texpecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"b\", expecting);\n\t\texpecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"c\", expecting);\n\t\texpecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"d\", expecting);\n\t\texpecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"e\", expecting);\n\t}\n\t@Test public void testNotSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"tokens { A; B; C; }\\n\"+\n\t\t\t\"a : ~A ;\\n\");\n\t\tString expecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"a\", expecting);\n\t}\n\t@Test public void testNotSingletonBlockSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"tokens { A; B; C; }\\n\"+\n\t\t\t\"a : ~(A) ;\\n\");\n\t\tString expecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"a\", expecting);\n\t}\n\t@Test public void testNotCharSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : ~'3' ;\\n\");\n\t\tString expecting =\n\t\t\t\"RuleStart_A_1->s5\\n\" +\n\t\t\t\"s5-{'\\\\u0000'..'2', '4'..'\\\\uFFFE'}->s6\\n\" +\n\t\t\t\"s6->RuleStop_A_2\\n\";\n\t\tcheckRule(g, \"A\", expecting);\n\t}\n\t@Test public void testNotBlockSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : ~('3'|'b') ;\\n\");\n\t\tString expecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"A\", expecting);\n\t}\n\t@Test public void testNotSetLoop() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : ~('3')* ;\\n\");\n\t\tString expecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"A\", expecting);\n\t}\n\t@Test public void testNotBlockSetLoop() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : ~('3'|'b')* ;\\n\");\n\t\tString expecting =\n\t\t\t\"\\n\";\n\t\tcheckRule(g, \"A\", expecting);\n\t}\n\t@Test public void testLabeledNotSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar P;\\n\"+\n\t\t\t\"tokens { A; B; C; }\\n\"+\n\t\t\t\"a : t=~A ;\\n\");\n\t\tString expecting =\n\t\t\t\".s0->.s1\\n\" +\n\t\t\t\".s1->.s2\\n\" +\n\t\t\t\".s2-B..C->.s3\\n\" +\n\t\t\t\".s3->:s4\\n\" +\n\t\t\t\":s4-EOF->.s5\\n\";\n\t\tcheckRule(g, \"a\", expecting);\n\t}\n\t@Test public void testLabeledNotCharSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : t=~'3' ;\\n\");\n\t\tString expecting =\n\t\t\t\".s0->.s1\\n\" +\n\t\t\t\".s1->.s2\\n\" +\n\t\t\t\".s2-{'\\\\u0000'..'2', '4'..'\\\\uFFFF'}->.s3\\n\" +\n\t\t\t\".s3->:s4\\n\" +\n\t\t\t\":s4-<EOT>->.s5\\n\";\n\t\tcheckRule(g, \"A\", expecting);\n\t}\n\t@Test public void testLabeledNotBlockSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"lexer grammar P;\\n\"+\n\t\t\t\"A : t=~('3'|'b') ;\\n\");\n\t\tString expecting =\n\t\t\t\".s0->.s1\\n\" +\n\t\t\t\".s1->.s2\\n\" +\n\t\t\t\".s2-{'\\\\u0000'..'2', '4'..'a', 'c'..'\\\\uFFFF'}->.s3\\n\" +\n\t\t\t\".s3->:s4\\n\" +\n\t\t\t\":s4-<EOT>->.s5\\n\";\n\t\tcheckRule(g, \"A\", expecting);\n\t}\n\t@Test public void testEscapedCharLiteral() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"grammar P;\\n\"+\n\t\t\t\"a : '\\\\n';\");\n\t\tString expecting =\n\t\t\t\".s0->.s1\\n\" +\n\t\t\t\".s1->.s2\\n\" +\n\t\t\t\".s2-'\\\\n'->.s3\\n\" +\n\t\t\t\".s3->:s4\\n\" +\n\t\t\t\":s4-EOF->.s5\\n\";\n\t\tcheckRule(g, \"a\", expecting);\n\t}\n\t@Test public void testEscapedStringLiteral() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"grammar P;\\n\"+\n\t\t\t\"a : 'a\\\\nb\\\\u0030c\\\\'';\");\n\t\tString expecting =\n\t\t\t\"RuleStart_a_0->s2\\n\" +\n\t\t\t\"s2-'a\\\\nb\\\\u0030c\\\\''->s3\\n\" +\n\t\t\t\"s3->RuleStop_a_1\\n\" +\n\t\t\t\"RuleStop_a_1-EOF->s4\\n\";\n\t\tcheckRule(g, \"a\", expecting);\n\t}\n\t*/\n\n\t@Test public void testDefaultMode() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"X : 'x' ;\\n\" +\n\t\t\t\"mode FOO;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tString expecting =\n\t\t\t\"s0->RuleStart_A_2\\n\" +\n\t\t\t\t\"s0->RuleStart_X_4\\n\" +\n\t\t\t\t\"RuleStart_A_2->s10\\n\" +\n\t\t\t\t\"RuleStart_X_4->s12\\n\" +\n\t\t\t\t\"s10-'a'->s11\\n\" +\n\t\t\t\t\"s12-'x'->s13\\n\" +\n\t\t\t\t\"s11->RuleStop_A_3\\n\" +\n\t\t\t\t\"s13->RuleStop_X_5\\n\";\n\t\tcheckTokensRule(g, \"DEFAULT_MODE\", expecting);\n\t}\n\n\t@Test public void testMode() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"X : 'x' ;\\n\" +\n\t\t\t\"mode FOO;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tString expecting =\n\t\t\t\"s1->RuleStart_B_6\\n\" +\n\t\t\t\t\"s1->RuleStart_C_8\\n\" +\n\t\t\t\t\"RuleStart_B_6->s14\\n\" +\n\t\t\t\t\"RuleStart_C_8->s16\\n\" +\n\t\t\t\t\"s14-'b'->s15\\n\" +\n\t\t\t\t\"s16-'c'->s17\\n\" +\n\t\t\t\t\"s15->RuleStop_B_7\\n\" +\n\t\t\t\t\"s17->RuleStop_C_9\\n\";\n\t\tcheckTokensRule(g, \"FOO\", expecting);\n\t}\n\tvoid checkTokensRule(LexerGrammar g, String modeName, String expecting) {\n//\t\tif ( g.ast!=null && !g.ast.hasErrors ) {\n//\t\t\tSystem.out.println(g.ast.toStringTree());\n//\t\t\tTool antlr = new Tool();\n//\t\t\tSemanticPipeline sem = new SemanticPipeline(g);\n//\t\t\tsem.process();\n//\t\t\tif ( g.getImportedGrammars()!=null ) { // process imported grammars (if any)\n//\t\t\t\tfor (Grammar imp : g.getImportedGrammars()) {\n//\t\t\t\t\tantlr.processNonCombinedGrammar(imp);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n\t\tif ( modeName==null ) modeName = \"DEFAULT_MODE\";\n\t\tif ( g.modes.get(modeName)==null ) {\n\t\t\tSystem.err.println(\"no such mode \"+modeName);\n\t\t\treturn;\n\t\t}\n\t\tParserATNFactory f = new LexerATNFactory(g);\n\t\tATN nfa = f.createATN();\n\t\tATNState startState = nfa.modeNameToStartState.get(modeName);\n\t\tATNPrinter serializer = new ATNPrinter(g, startState);\n\t\tString result = serializer.asString();\n\t\t//System.out.print(result);\n\t\tassertEquals(expecting, result);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestATNDeserialization.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNDeserializer;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.Arrays;\n\nimport static org.antlr.v4.runtime.atn.ATNDeserializer.encodeIntsWith16BitWords;\nimport static org.antlr.v4.runtime.atn.ATNDeserializer.decodeIntsEncodedAs16BitWords;\nimport static org.antlr.v4.test.tool.ToolTestUtils.createATN;\nimport static org.junit.jupiter.api.Assertions.assertArrayEquals;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n\npublic class TestATNDeserialization {\n\t@Test public void testSimpleNoBlock() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A B ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testEOF() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : EOF ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testEOFInSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (EOF|A) ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testNot() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"tokens {A, B, C}\\n\" +\n\t\t\t\"a : ~A ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testWildcard() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"tokens {A, B, C}\\n\" +\n\t\t\t\"a : . ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testPEGAchillesHeel() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A | A B ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void test3Alts() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A | A B | A B C ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testSimpleLoop() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A+ B ;\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testRuleRef() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : e ;\\n\" +\n\t\t\t\"e : E ;\\n\");\n\t\tcheckDeserializationIsStable(g);\n\t}\n\n\t@Test public void testLexerTwoRules() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLexerEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' EOF ;\\n\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLexerEOFInSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' (EOF|'\\\\n') ;\\n\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLexerRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : '0'..'9' ;\\n\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLexerLoops() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : '0'..'9'+ ;\\n\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLexerNotSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b')\\n ;\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLexerNotSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b'|'e'|'p'..'t')\\n ;\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLexerNotSetWithRange2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b') ~('e'|'p'..'t')\\n ;\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void test2ModesInLexer() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\t\t\t\"A : 'a'\\n ;\\n\" +\n\t\t\t\t\t\t\"mode M;\\n\" +\n\t\t\t\t\t\t\"B : 'b';\\n\" +\n\t\t\t\t\t\t\"mode M2;\\n\" +\n\t\t\t\t\t\t\"C : 'c';\\n\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\t@Test public void testLastValidBMPCharInSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\t\t\"ID : 'Ā'..'\\\\uFFFC'; // FFFD+ are not valid char\\n\");\n\t\tcheckDeserializationIsStable(lg);\n\t}\n\n\tprotected void checkDeserializationIsStable(Grammar g) {\n\t\tATN atn = createATN(g, false);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString atnData = new ATNDescriber(atn, Arrays.asList(g.getTokenNames())).decode(serialized.toArray());\n\n\t\tIntegerList serialized16 = encodeIntsWith16BitWords(serialized);\n\t\tint[] ints16 = serialized16.toArray();\n\t\tchar[] chars = new char[ints16.length];\n\t\tfor (int i = 0; i < ints16.length; i++) {\n\t\t\tchars[i] = (char)ints16[i];\n\t\t}\n\t\tint[] serialized32 = decodeIntsEncodedAs16BitWords(chars, true);\n\n\t\tassertArrayEquals(serialized.toArray(), serialized32);\n\n\t\tATN atn2 = new ATNDeserializer().deserialize(serialized.toArray());\n\t\tIntegerList serialized1 = ATNSerializer.getSerialized(atn2);\n\t\tString atn2Data = new ATNDescriber(atn2, Arrays.asList(g.getTokenNames())).decode(serialized1.toArray());\n\n\t\tassertEquals(atnData, atn2Data);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestATNInterpreter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.NoViableAltException;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.BlockStartState;\nimport org.antlr.v4.runtime.atn.LexerATNSimulator;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.tool.DOTGenerator;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.createATN;\nimport static org.antlr.v4.test.tool.ToolTestUtils.getTokenTypesViaATN;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.fail;\n\n\t// NOTICE: TOKENS IN LEXER, PARSER MUST BE SAME OR TOKEN TYPE MISMATCH\n\t// NOTICE: TOKENS IN LEXER, PARSER MUST BE SAME OR TOKEN TYPE MISMATCH\n\t// NOTICE: TOKENS IN LEXER, PARSER MUST BE SAME OR TOKEN TYPE MISMATCH\n\npublic class TestATNInterpreter {\n\t@Test public void testSimpleNoBlock() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A B ;\");\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t}\n\n\t@Test public void testSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"tokens {A,B,C}\\n\" +\n\t\t\t\"a : ~A ;\");\n\t\tcheckMatchedAlt(lg, g, \"b\", 1);\n\t}\n\n\t@Test public void testPEGAchillesHeel() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A | A B ;\");\n\t\tcheckMatchedAlt(lg, g, \"a\", 1);\n\t\tcheckMatchedAlt(lg, g, \"ab\", 2);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 2);\n\t}\n\n\t@Test public void testMustTrackPreviousGoodAlt() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A | A B ;\");\n\n\t\tcheckMatchedAlt(lg, g, \"a\", 1);\n\t\tcheckMatchedAlt(lg, g, \"ab\", 2);\n\n\t\tcheckMatchedAlt(lg, g, \"ac\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 2);\n\t}\n\n\t@Test\n\tpublic void testMustTrackPreviousGoodAltWithEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (A | A B) EOF;\");\n\n\t\tcheckMatchedAlt(lg, g, \"a\", 1);\n\t\tcheckMatchedAlt(lg, g, \"ab\", 2);\n\n\t\ttry {\n\t\t\tcheckMatchedAlt(lg, g, \"ac\", 1);\n\t\t\tfail();\n\t\t}\n\t\tcatch (NoViableAltException re) {\n\t\t\tassertEquals(1, re.getOffendingToken().getTokenIndex());\n\t\t\tassertEquals(3, re.getOffendingToken().getType());\n\t\t}\n\t}\n\n\t@Test public void testMustTrackPreviousGoodAlt2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A | A B | A B C ;\");\n\n\t\tcheckMatchedAlt(lg, g, \"a\", 1);\n\t\tcheckMatchedAlt(lg, g, \"ab\", 2);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 3);\n\n\t\tcheckMatchedAlt(lg, g, \"ad\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abd\", 2);\n\t\tcheckMatchedAlt(lg, g, \"abcd\", 3);\n\t}\n\n\t@Test\n\tpublic void testMustTrackPreviousGoodAlt2WithEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (A | A B | A B C) EOF;\");\n\n\t\tcheckMatchedAlt(lg, g, \"a\", 1);\n\t\tcheckMatchedAlt(lg, g, \"ab\", 2);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 3);\n\n\t\ttry {\n\t\t\tcheckMatchedAlt(lg, g, \"abd\", 1);\n\t\t\tfail();\n\t\t}\n\t\tcatch (NoViableAltException re) {\n\t\t\tassertEquals(2, re.getOffendingToken().getTokenIndex());\n\t\t\tassertEquals(4, re.getOffendingToken().getType());\n\t\t}\n\t}\n\n\t@Test public void testMustTrackPreviousGoodAlt3() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A B | A | A B C ;\");\n\n\t\tcheckMatchedAlt(lg, g, \"a\", 2);\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 3);\n\n\t\tcheckMatchedAlt(lg, g, \"ad\", 2);\n\t\tcheckMatchedAlt(lg, g, \"abd\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abcd\", 3);\n\t}\n\n\t@Test\n\tpublic void testMustTrackPreviousGoodAlt3WithEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (A B | A | A B C) EOF;\");\n\n\t\tcheckMatchedAlt(lg, g, \"a\", 2);\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 3);\n\n\t\ttry {\n\t\t\tcheckMatchedAlt(lg, g, \"abd\", 1);\n\t\t\tfail();\n\t\t}\n\t\tcatch (NoViableAltException re) {\n\t\t\tassertEquals(2, re.getOffendingToken().getTokenIndex());\n\t\t\tassertEquals(4, re.getOffendingToken().getType());\n\t\t}\n\t}\n\n\t@Test public void testAmbigAltChooseFirst() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A B | A B ;\"); // first alt\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 1);\n\t}\n\n\t@Test public void testAmbigAltChooseFirstWithFollowingToken() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (A B | A B) C ;\"); // first alt\n\t\tcheckMatchedAlt(lg, g, \"abc\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abcd\", 1);\n\t}\n\n\t@Test public void testAmbigAltChooseFirstWithFollowingToken2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (A B | A B | C) D ;\");\n\t\tcheckMatchedAlt(lg, g, \"abd\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abdc\", 1);\n\t\tcheckMatchedAlt(lg, g, \"cd\", 3);\n\t}\n\n\t@Test public void testAmbigAltChooseFirst2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A B | A B | A B C ;\");\n\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 3);\n\n\t\tcheckMatchedAlt(lg, g, \"abd\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abcd\", 3);\n\t}\n\n\t@Test\n\tpublic void testAmbigAltChooseFirst2WithEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (A B | A B | A B C) EOF;\");\n\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"abc\", 3);\n\n\t\ttry {\n\t\t\tcheckMatchedAlt(lg, g, \"abd\", 1);\n\t\t\tfail();\n\t\t}\n\t\tcatch (NoViableAltException re) {\n\t\t\tassertEquals(2, re.getOffendingToken().getTokenIndex());\n\t\t\tassertEquals(4, re.getOffendingToken().getType());\n\t\t}\n\t}\n\n\t@Test public void testSimpleLoop() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"D : 'd' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A+ B ;\");\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"aab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"aaaaaab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"aabd\", 1);\n\t}\n\n\t@Test public void testCommonLeftPrefix() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A B | A C ;\");\n\t\tcheckMatchedAlt(lg, g, \"ab\", 1);\n\t\tcheckMatchedAlt(lg, g, \"ac\", 2);\n\t}\n\n\t@Test public void testArbitraryLeftPrefix() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A+ B | A+ C ;\");\n\t\tcheckMatchedAlt(lg, g, \"aac\", 2);\n\t}\n\n\t@Test public void testRecursiveLeftPrefix() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"LP : '(' ;\\n\" +\n\t\t\t\"RP : ')' ;\\n\" +\n\t\t\t\"INT : '0'..'9'+ ;\\n\"\n\t\t);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"tokens {A,B,C,LP,RP,INT}\\n\" +\n\t\t\t\"a : e B | e C ;\\n\" +\n\t\t\t\"e : LP e RP\\n\" +\n\t\t\t\"  | INT\\n\" +\n\t\t\t\"  ;\");\n\t\tcheckMatchedAlt(lg, g, \"34b\", 1);\n\t\tcheckMatchedAlt(lg, g, \"34c\", 2);\n\t\tcheckMatchedAlt(lg, g, \"(34)b\", 1);\n\t\tcheckMatchedAlt(lg, g, \"(34)c\", 2);\n\t\tcheckMatchedAlt(lg, g, \"((34))b\", 1);\n\t\tcheckMatchedAlt(lg, g, \"((34))c\", 2);\n\t}\n\n\tpublic void checkMatchedAlt(LexerGrammar lg, final Grammar g,\n\t\t\t\t\t\t\t\tString inputString,\n\t\t\t\t\t\t\t\tint expected)\n\t{\n\t\tATN lexatn = createATN(lg, true);\n\t\tLexerATNSimulator lexInterp = new LexerATNSimulator(lexatn,new DFA[] { new DFA(lexatn.modeToStartState.get(Lexer.DEFAULT_MODE)) },null);\n\t\tIntegerList types = getTokenTypesViaATN(inputString, lexInterp);\n//\t\tSystem.out.println(types);\n\n\t\tg.importVocab(lg);\n\n\t\tParserATNFactory f = new ParserATNFactory(g);\n\t\tATN atn = f.createATN();\n\n\t\tTokenStream input = new MockIntTokenStream(types);\n//\t\tSystem.out.println(\"input=\"+input.types);\n\t\tParserInterpreterForTesting interp = new ParserInterpreterForTesting(g, input);\n\t\tATNState startState = atn.ruleToStartState[g.getRule(\"a\").index];\n\t\tif ( startState.transition(0).target instanceof BlockStartState ) {\n\t\t\tstartState = startState.transition(0).target;\n\t\t}\n\n\t\tDOTGenerator dot = new DOTGenerator(g);\n//\t\tSystem.out.println(dot.getDOT(atn.ruleToStartState[g.getRule(\"a\").index]));\n\t\tRule r = g.getRule(\"e\");\n//\t\tif ( r!=null ) System.out.println(dot.getDOT(atn.ruleToStartState[r.index]));\n\n\t\tint result = interp.matchATN(input, startState);\n\t\tassertEquals(expected, result);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestATNLexerInterpreter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.LexerATNSimulator;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.Utils;\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.antlr.v4.tool.DOTGenerator;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.*;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/**\n * Lexer rules are little quirky when it comes to wildcards. Problem\n * stems from the fact that we want the longest match to win among\n * several rules and even within a rule. However, that conflicts\n * with the notion of non-greedy, which by definition tries to match\n * the fewest possible. During ATN construction, non-greedy loops\n * have their entry and exit branches reversed so that the ATN\n * simulator will see the exit branch 1st, giving it a priority. The\n * 1st path to the stop state kills any other paths for that rule\n * that begin with the wildcard. In general, this does everything we\n * want, but occasionally there are some quirks as you'll see from\n * the tests below.\n */\npublic class TestATNLexerInterpreter {\n\t@Test public void testLexerTwoRules() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\");\n\t\tString expecting = \"A, B, A, B, EOF\";\n\t\tcheckLexerMatches(lg, \"abab\", expecting);\n\t}\n\n\t@Test public void testShortLongRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'xy'\\n\" +\n\t\t\t\"  | 'xyz'\\n\" + // this alt is preferred since there are no non-greedy configs\n\t\t\t\"  ;\\n\" +\n\t\t\t\"Z : 'z'\\n\" +\n\t\t\t\"  ;\\n\");\n\t\tcheckLexerMatches(lg, \"xy\", \"A, EOF\");\n\t\tcheckLexerMatches(lg, \"xyz\", \"A, EOF\");\n\t}\n\n\t@Test public void testShortLongRule2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'xyz'\\n\" +  // make sure nongreedy mech cut off doesn't kill this alt\n\t\t\t\"  | 'xy'\\n\" +\n\t\t\t\"  ;\\n\");\n\t\tcheckLexerMatches(lg, \"xy\", \"A, EOF\");\n\t\tcheckLexerMatches(lg, \"xyz\", \"A, EOF\");\n\t}\n\n\t@Test public void testWildOnEndFirstAlt() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'xy' .\\n\" + // should pursue '.' since xyz hits stop first, before 2nd alt\n\t\t\t\"  | 'xy'\\n\" +\n\t\t\t\"  ;\\n\" +\n\t\t\t\"Z : 'z'\\n\" +\n\t\t\t\"  ;\\n\");\n\t\tcheckLexerMatches(lg, \"xy\", \"A, EOF\");\n\t\tcheckLexerMatches(lg, \"xyz\", \"A, EOF\");\n\t}\n\n\t@Test public void testWildOnEndLastAlt() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'xy'\\n\" +\n\t\t\t\"  | 'xy' .\\n\" +  // this alt is preferred since there are no non-greedy configs\n\t\t\t\"  ;\\n\" +\n\t\t\t\"Z : 'z'\\n\" +\n\t\t\t\"  ;\\n\");\n\t\tcheckLexerMatches(lg, \"xy\", \"A, EOF\");\n\t\tcheckLexerMatches(lg, \"xyz\", \"A, EOF\");\n\t}\n\n\t@Test public void testWildcardNonQuirkWhenSplitBetweenTwoRules() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'xy' ;\\n\" +\n\t\t\t\"B : 'xy' . 'z' ;\\n\");\n\t\tcheckLexerMatches(lg, \"xy\", \"A, EOF\");\n\t\tcheckLexerMatches(lg, \"xyqz\", \"B, EOF\");\n\t}\n\n\t@Test public void testLexerLoops() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : '0'..'9'+ ;\\n\" +\n\t\t\t\"ID : 'a'..'z'+ ;\\n\");\n\t\tString expecting = \"ID, INT, ID, INT, EOF\";\n\t\tcheckLexerMatches(lg, \"a34bde3\", expecting);\n\t}\n\n\t@Test public void testLexerNotSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, \"c\", expecting);\n\t}\n\n\t@Test public void testLexerSetUnicodeBMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('\\u611B'|'\\u611C')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, \"\\u611B\", expecting);\n\t}\n\n\t@Test public void testLexerNotSetUnicodeBMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\u611B'|'\\u611C')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, \"\\u611D\", expecting);\n\t}\n\n\t\t@Test public void testLexerNotSetUnicodeBMPMatchesSMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\u611B'|'\\u611C')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, new StringBuilder().appendCodePoint(0x1F4A9).toString(), expecting);\n\t}\n\n\t@Test public void testLexerSetUnicodeSMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('\\\\u{1F4A9}'|'\\\\u{1F4AA}')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, new StringBuilder().appendCodePoint(0x1F4A9).toString(), expecting);\n\t}\n\n\t@Test public void testLexerNotBMPSetMatchesUnicodeSMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, new StringBuilder().appendCodePoint(0x1F4A9).toString(), expecting);\n\t}\n\n\t@Test public void testLexerNotBMPSetMatchesBMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, \"\\u611B\", expecting);\n\t}\n\n\t@Test public void testLexerNotBMPSetMatchesSMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, new StringBuilder().appendCodePoint(0x1F4A9).toString(), expecting);\n\t}\n\n\t@Test public void testLexerNotSMPSetMatchesBMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\\\u{1F4A9}'|'\\\\u{1F4AA}')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, \"\\u611B\", expecting);\n\t}\n\n\t@Test public void testLexerNotSMPSetMatchesSMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\\\u{1F4A9}'|'\\\\u{1F4AA}')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, new StringBuilder().appendCodePoint(0x1D7C0).toString(), expecting);\n\t}\n\n\t@Test public void testLexerRangeUnicodeSMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('\\\\u{1F4A9}'..'\\\\u{1F4B0}')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, new StringBuilder().appendCodePoint(0x1F4AF).toString(), expecting);\n\t}\n\n\t@Test public void testLexerRangeUnicodeBMPToSMP() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('\\\\u611B'..'\\\\u{1F4B0}')\\n ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, new StringBuilder().appendCodePoint(0x12001).toString(), expecting);\n\t}\n\n\t@Test public void testLexerKeywordIDAmbiguity() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"KEND : 'end' ;\\n\" +\n\t\t\t\"ID : 'a'..'z'+ ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n')+ ;\");\n\t\tString expecting = \"ID, EOF\";\n\t\t//checkLexerMatches(lg, \"e\", expecting);\n\t\texpecting = \"KEND, EOF\";\n\t\tcheckLexerMatches(lg, \"end\", expecting);\n\t\texpecting = \"ID, EOF\";\n\t\tcheckLexerMatches(lg, \"ending\", expecting);\n\t\texpecting = \"ID, WS, KEND, WS, ID, EOF\";\n\t\tcheckLexerMatches(lg, \"a end bcd\", expecting);\n\t}\n\n\t@Test public void testLexerRuleRef() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : DIGIT+ ;\\n\" +\n\t\t\t\"fragment DIGIT : '0'..'9' ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n')+ ;\");\n\t\tString expecting = \"INT, WS, INT, EOF\";\n\t\tcheckLexerMatches(lg, \"32 99\", expecting);\n\t}\n\n\t@Test public void testRecursiveLexerRuleRef() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '/*' (CMT | ~'*')+ '*/' ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n')+ ;\");\n\t\tString expecting = \"CMT, WS, CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"/* ick */\\n/* /*nested*/ */\", expecting);\n\t}\n\n\t@Test public void testRecursiveLexerRuleRefWithWildcard() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '/*' (CMT | .)*? '*/' ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n')+ ;\");\n\n\t\tString expecting = \"CMT, WS, CMT, WS, EOF\";\n\t\tcheckLexerMatches(lg,\n\t\t\t\t\t\t  \"/* ick */\\n\" +\n\t\t\t\t\t\t  \"/* /* */\\n\" +\n\t\t\t\t\t\t  \"/* /*nested*/ */\\n\",\n\t\t\t\t\t\t  expecting);\n\t}\n\n\t@Test public void testLexerWildcardGreedyLoopByDefault() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '//' .* '\\\\n' ;\\n\");\n\t\tString expecting = \"CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"//x\\n//y\\n\", expecting);\n\t}\n\n\t@Test public void testLexerWildcardLoopExplicitNonGreedy() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '//' .*? '\\\\n' ;\\n\");\n\t\tString expecting = \"CMT, CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"//x\\n//y\\n\", expecting);\n\t}\n\n\t@Test public void testLexerEscapeInString() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"STR : '[' ('~' ']' | .)* ']' ;\\n\");\n\t\tcheckLexerMatches(lg, \"[a~]b]\", \"STR, EOF\");\n\t\tcheckLexerMatches(lg, \"[a]\", \"STR, EOF\");\n\t}\n\n\t@Test public void testLexerWildcardGreedyPlusLoopByDefault() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '//' .+ '\\\\n' ;\\n\");\n\t\tString expecting = \"CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"//x\\n//y\\n\", expecting);\n\t}\n\n\t@Test public void testLexerWildcardExplicitNonGreedyPlusLoop() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '//' .+? '\\\\n' ;\\n\");\n\t\tString expecting = \"CMT, CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"//x\\n//y\\n\", expecting);\n\t}\n\n\t// does not fail since ('*/')? can't match and have rule succeed\n\t@Test public void testLexerGreedyOptionalShouldWorkAsWeExpect() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '/*' ('*/')? '*/' ;\\n\");\n\t\tString expecting = \"CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"/**/\", expecting);\n\t}\n\n\t@Test public void testGreedyBetweenRules() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : '<a>' ;\\n\" +\n\t\t\t\"B : '<' .+ '>' ;\\n\");\n\t\tString expecting = \"B, EOF\";\n\t\tcheckLexerMatches(lg, \"<a><x>\", expecting);\n\t}\n\n\t@Test public void testNonGreedyBetweenRules() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : '<a>' ;\\n\" +\n\t\t\t\"B : '<' .+? '>' ;\\n\");\n\t\tString expecting = \"A, B, EOF\";\n\t\tcheckLexerMatches(lg, \"<a><x>\", expecting);\n\t}\n\n\t@Test public void testEOFAtEndOfLineComment() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '//' ~('\\\\n')* ;\\n\");\n\t\tString expecting = \"CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"//x\", expecting);\n\t}\n\n\t@Test public void testEOFAtEndOfLineComment2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '//' ~('\\\\n'|'\\\\r')* ;\\n\");\n\t\tString expecting = \"CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"//x\", expecting);\n\t}\n\n\t/** only positive sets like (EOF|'\\n') can match EOF and not in wildcard or ~foo sets\n\t *  EOF matches but does not advance cursor.\n\t */\n\t@Test public void testEOFInSetAtEndOfLineComment() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"CMT : '//' .* (EOF|'\\\\n') ;\\n\");\n\t\tString expecting = \"CMT, EOF\";\n\t\tcheckLexerMatches(lg, \"//\", expecting);\n\t}\n\n\t@Test public void testEOFSuffixInSecondRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' ;\\n\"+ // shorter than 'a' EOF, despite EOF being 0 width\n\t\t\t\"B : 'a' EOF ;\\n\");\n\t\tString expecting = \"B, EOF\";\n\t\tcheckLexerMatches(lg, \"a\", expecting);\n\t}\n\n\t@Test public void testEOFSuffixInFirstRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' EOF ;\\n\"+\n\t\t\t\"B : 'a';\\n\");\n\t\tString expecting = \"A, EOF\";\n\t\tcheckLexerMatches(lg, \"a\", expecting);\n\t}\n\n\t@Test public void testEOFByItself() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"DONE : EOF ;\\n\"+\n\t\t\t\"A : 'a';\\n\");\n\t\tString expecting = \"A, DONE, EOF\";\n\t\tcheckLexerMatches(lg, \"a\", expecting);\n\t}\n\n\t@Test public void testLexerCaseInsensitive() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"WS:             [ \\\\t\\\\r\\\\n] -> skip;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"SIMPLE_TOKEN:           'and';\\n\" +\n\t\t\t\"TOKEN_WITH_SPACES:      'as' 'd' 'f';\\n\" +\n\t\t\t\"TOKEN_WITH_DIGITS:      'INT64';\\n\" +\n\t\t\t\"TOKEN_WITH_UNDERSCORE:  'TOKEN_WITH_UNDERSCORE';\\n\" +\n\t\t\t\"BOOL:                   'true' | 'FALSE';\\n\" +\n\t\t\t\"SPECIAL:                '==';\\n\" +\n\t\t\t\"SET:                    [a-z0-9]+;\\n\" +   // [a-zA-Z0-9]\n\t\t\t\"RANGE:                  ('а'..'я')+;\"\n\t\t\t);\n\n\t\tString inputString =\n\t\t\t\"and AND aND\\n\" +\n\t\t\t\"asdf ASDF\\n\" +\n\t\t\t\"int64\\n\" +\n\t\t\t\"token_WITH_underscore\\n\" +\n\t\t\t\"TRUE FALSE\\n\" +\n\t\t\t\"==\\n\" +\n\t\t\t\"A0bcDE93\\n\" +\n\t\t\t\"АБВабв\\n\";\n\n\t\tString expecting = Utils.join(new String[] {\n\t\t\t\"SIMPLE_TOKEN\", \"SIMPLE_TOKEN\", \"SIMPLE_TOKEN\",\n\t\t\t\"TOKEN_WITH_SPACES\", \"TOKEN_WITH_SPACES\",\n\t\t\t\"TOKEN_WITH_DIGITS\",\n\t\t\t\"TOKEN_WITH_UNDERSCORE\",\n\t\t\t\"BOOL\", \"BOOL\",\n\t\t\t\"SPECIAL\",\n\t\t\t\"SET\",\n\t\t\t\"RANGE\",\n\t\t\t\"EOF\"\n\t\t},\n\t\t\", WS, \");\n\n\t\tcheckLexerMatches(lg, inputString, expecting);\n\t}\n\n\t@Test public void testLexerCaseInsensitiveLiteralWithNegation() {\n\t\tString grammar =\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"LITERAL_WITH_NOT:   ~'f';\\n\";     // ~('f' | 'F)\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"F\");\n\n\t\tassertEquals(\"line 1:0 token recognition error at: 'F'\\n\", executedState.errors);\n\t}\n\n\t@Test public void testLexerCaseInsensitiveSetWithNegation() {\n\t\tString grammar =\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"SET_WITH_NOT: ~[a-c];\\n\";        // ~[a-cA-C]\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"B\");\n\n\t\tassertEquals(\"line 1:0 token recognition error at: 'B'\\n\", executedState.errors);\n\t}\n\n\t@Test public void testLexerCaseInsensitiveFragments() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"TOKEN_0:         FRAGMENT 'd'+;\\n\" +\n\t\t\t\t\"TOKEN_1:         FRAGMENT 'e'+;\\n\" +\n\t\t\t\t\"FRAGMENT:        'abc';\\n\");\n\n\t\tString inputString =\n\t\t\t\t\"ABCDDD\";\n\n\t\tString expecting = \"TOKEN_0, EOF\";\n\n\t\tcheckLexerMatches(lg, inputString, expecting);\n\t}\n\n\t@Test public void testLexerCaseInsensitiveWithDifferentCultures() throws Exception {\n\t\t// From http://www.periodni.com/unicode_utf-8_encoding.html\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"ENGLISH_TOKEN:   [a-z]+;\\n\" +\n\t\t\t\t\"GERMAN_TOKEN:    [äéöüß]+;\\n\" +\n\t\t\t\t\"FRENCH_TOKEN:    [àâæ-ëîïôœùûüÿ]+;\\n\" +\n\t\t\t\t\"CROATIAN_TOKEN:  [ćčđšž]+;\\n\" +\n\t\t\t\t\"ITALIAN_TOKEN:   [àèéìòù]+;\\n\" +\n\t\t\t\t\"SPANISH_TOKEN:   [áéíñóúü¡¿]+;\\n\" +\n\t\t\t\t\"GREEK_TOKEN:     [α-ω]+;\\n\" +\n\t\t\t\t\"RUSSIAN_TOKEN:   [а-я]+;\\n\" +\n\t\t\t\t\"WS:              [ ]+ -> skip;\"\n\t\t\t\t);\n\n\t\tString inputString = \"abcXYZ äéöüßÄÉÖÜß àâæçÙÛÜŸ ćčđĐŠŽ àèéÌÒÙ áéÚÜ¡¿ αβγΧΨΩ абвЭЮЯ \";\n\n\t\tString expecting = Utils.join(new String[] {\n\t\t\t\t\"ENGLISH_TOKEN\",\n\t\t\t\t\"GERMAN_TOKEN\",\n\t\t\t\t\"FRENCH_TOKEN\",\n\t\t\t\t\"CROATIAN_TOKEN\",\n\t\t\t\t\"ITALIAN_TOKEN\",\n\t\t\t\t\"SPANISH_TOKEN\",\n\t\t\t\t\"GREEK_TOKEN\",\n\t\t\t\t\"RUSSIAN_TOKEN\",\n\t\t\t\t\"EOF\" },\n\t\t\t\t\", WS, \");\n\n\t\tcheckLexerMatches(lg, inputString, expecting);\n\t}\n\n\t@Test public void testNotImpliedCharactersWithEnabledCaseInsensitiveOption() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"TOKEN: ('A'..'z')+;\\n\"\n\t\t);\n\n\t\t// No range transformation because of mixed character case in range borders\n\t\tString inputString = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz\";\n\t\tcheckLexerMatches(lg, inputString, \"TOKEN, EOF\");\n\t}\n\n\t@Test public void testCaseInsensitiveInLexerRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"TOKEN1 options { caseInsensitive=true; } : [a-f]+;\\n\" +\n\t\t\t\t\"WS: [ ]+ -> skip;\"\n\t\t);\n\n\t\tcheckLexerMatches(lg, \"ABCDEF\", \"TOKEN1, EOF\");\n\t}\n\n\t@Test public void testCaseInsensitiveInLexerRuleOverridesGlobalValue() {\n\t\tString grammar =\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive=true; }\\n\" +\n\t\t\t\t\"STRING options { caseInsensitive=false; } : 'N'? '\\\\'' (~'\\\\'' | '\\\\'\\\\'')* '\\\\'';\\n\";\n\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"n'sample'\");\n\t\tassertEquals(\"line 1:0 token recognition error at: 'n'\\n\", executedState.errors);\n\t}\n\n\tprivate void checkLexerMatches(LexerGrammar lg, String inputString, String expecting) {\n\t\tATN atn = createATN(lg, true);\n\t\tCharStream input = CharStreams.fromString(inputString);\n\t\tATNState startState = atn.modeNameToStartState.get(\"DEFAULT_MODE\");\n\t\tDOTGenerator dot = new DOTGenerator(lg);\n//\t\tSystem.out.println(dot.getDOT(startState, true));\n\n\t\tList<String> tokenTypes = getTokenTypes(lg, atn, input);\n\n\t\tString result = Utils.join(tokenTypes.iterator(), \", \");\n//\t\tSystem.out.println(tokenTypes);\n\t\tassertEquals(expecting, result);\n\t}\n\n\tprivate static List<String> getTokenTypes(LexerGrammar lg, ATN atn, CharStream input) {\n\t\tLexerATNSimulator interp = new LexerATNSimulator(atn, new DFA[]{new DFA(atn.modeToStartState.get(Lexer.DEFAULT_MODE))}, null);\n\t\tList<String> tokenTypes = new ArrayList<>();\n\t\tint ttype;\n\t\tboolean hitEOF = false;\n\t\tdo {\n\t\t\tif ( hitEOF ) {\n\t\t\t\ttokenTypes.add(\"EOF\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint t = input.LA(1);\n\t\t\tttype = interp.match(input, Lexer.DEFAULT_MODE);\n\t\t\tif ( ttype== Token.EOF ) {\n\t\t\t\ttokenTypes.add(\"EOF\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttokenTypes.add(lg.typeToTokenList.get(ttype));\n\t\t\t}\n\n\t\t\tif ( t== IntStream.EOF ) {\n\t\t\t\thitEOF = true;\n\t\t\t}\n\t\t} while ( ttype!=Token.EOF );\n\t\treturn tokenTypes;\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestATNParserPrediction.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.NoViableAltException;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.LexerATNSimulator;\nimport org.antlr.v4.runtime.atn.PredictionContextCache;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.tool.DOTGenerator;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LeftRecursiveRule;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.Arrays;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.*;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\n// NOTICE: TOKENS IN LEXER, PARSER MUST BE SAME OR TOKEN TYPE MISMATCH\n// NOTICE: TOKENS IN LEXER, PARSER MUST BE SAME OR TOKEN TYPE MISMATCH\n// NOTICE: TOKENS IN LEXER, PARSER MUST BE SAME OR TOKEN TYPE MISMATCH\n\npublic class TestATNParserPrediction {\n\t@Test public void testAorB() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"a : A{;} | B ;\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"b\", 2);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"a\",\n\t\t\"b\",\n\t\t\"a\"\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-'a'->:s1=>1\\n\",\n\n\t\t\"s0-'a'->:s1=>1\\n\" +\n\t\t\"s0-'b'->:s2=>2\\n\",\n\n\t\t\"s0-'a'->:s1=>1\\n\" + // don't change after it works\n\t\t\"s0-'b'->:s2=>2\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testEmptyInput() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"a : A | ;\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"\", 2);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"a\",\n\t\t\"\",\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-'a'->:s1=>1\\n\",\n\n\t\t\"s0-EOF->:s2=>2\\n\" +\n\t\t\"s0-'a'->:s1=>1\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testPEGAchillesHeel() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"a : A | A B ;\");\n\t\tcheckPredictedAlt(lg, g, 0, \"a\", 1);\n\t\tcheckPredictedAlt(lg, g, 0, \"ab\", 2);\n\t\tcheckPredictedAlt(lg, g, 0, \"abc\", 2);\n\n\t\tString[] inputs = {\n\t\t\"a\",\n\t\t\"ab\",\n\t\t\"abc\"\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-EOF->:s2=>1\\n\",\n\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-EOF->:s2=>1\\n\" +\n\t\t\"s1-'b'->:s3=>2\\n\",\n\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-EOF->:s2=>1\\n\" +\n\t\t\"s1-'b'->:s3=>2\\n\"\n\t\t};\n\t\tcheckDFAConstruction(lg, g, 0, inputs, dfa);\n\t}\n\n\t@Test public void testRuleRefxory() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"a : x | y ;\\n\" +\n\t\t\"x : A ;\\n\" +\n\t\t\"y : B ;\\n\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"b\", 2);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"a\",\n\t\t\"b\",\n\t\t\"a\"\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-'a'->:s1=>1\\n\",\n\n\t\t\"s0-'a'->:s1=>1\\n\" +\n\t\t\"s0-'b'->:s2=>2\\n\",\n\n\t\t\"s0-'a'->:s1=>1\\n\" + // don't change after it works\n\t\t\"s0-'b'->:s2=>2\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testOptionalRuleChasesGlobalFollow() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"tokens {A,B,C}\\n\" +\n\t\t\"a : x B ;\\n\" +\n\t\t\"b : x C ;\\n\" +\n\t\t\"x : A | ;\\n\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"b\", 2);\n\t\tcheckPredictedAlt(lg, g, decision, \"c\", 2);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"a\",\n\t\t\"b\",\n\t\t\"c\",\n\t\t\"c\",\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-'a'->:s1=>1\\n\",\n\n\t\t\"s0-'a'->:s1=>1\\n\" +\n\t\t\"s0-'b'->:s2=>2\\n\",\n\n\t\t\"s0-'a'->:s1=>1\\n\" +\n\t\t\"s0-'b'->:s2=>2\\n\" +\n\t\t\"s0-'c'->:s3=>2\\n\",\n\n\t\t\"s0-'a'->:s1=>1\\n\" +\n\t\t\"s0-'b'->:s2=>2\\n\" +\n\t\t\"s0-'c'->:s3=>2\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testLL1Ambig() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"a : A | A | A B ;\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"ab\", 3);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"a\",\n\t\t\"ab\",\n\t\t\"ab\"\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-EOF->:s2^=>1\\n\",\n\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-EOF->:s2^=>1\\n\" +\n\t\t\"s1-'b'->:s3=>3\\n\",\n\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-EOF->:s2^=>1\\n\" +\n\t\t\"s1-'b'->:s3=>3\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testLL2Ambig() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"a : A B | A B | A B C ;\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"ab\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"abc\", 3);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"ab\",\n\t\t\"abc\",\n\t\t\"ab\"\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-'b'->s2\\n\" +\n\t\t\"s2-EOF->:s3^=>1\\n\",\n\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-'b'->s2\\n\" +\n\t\t\"s2-EOF->:s3^=>1\\n\" +\n\t\t\"s2-'c'->:s4=>3\\n\",\n\n\t\t\"s0-'a'->s1\\n\" +\n\t\t\"s1-'b'->s2\\n\" +\n\t\t\"s2-EOF->:s3^=>1\\n\" +\n\t\t\"s2-'c'->:s4=>3\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testRecursiveLeftPrefix() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\" +\n\t\t\"LP : '(' ;\\n\" +\n\t\t\"RP : ')' ;\\n\" +\n\t\t\"INT : '0'..'9'+ ;\\n\"\n\t\t);\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"tokens {A,B,C,LP,RP,INT}\\n\" +\n\t\t\"a : e B | e C ;\\n\" +\n\t\t\"e : LP e RP\\n\" +\n\t\t\"  | INT\\n\" +\n\t\t\"  ;\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"34b\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"34c\", 2);\n\t\tcheckPredictedAlt(lg, g, decision, \"((34))b\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"((34))c\", 2);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"34b\",\n\t\t\"34c\",\n\t\t\"((34))b\",\n\t\t\"((34))c\"\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'b'->:s2=>1\\n\",\n\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'b'->:s2=>1\\n\" +\n\t\t\"s1-'c'->:s3=>2\\n\",\n\n\t\t\"s0-'('->s4\\n\" +\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'b'->:s2=>1\\n\" +\n\t\t\"s1-'c'->:s3=>2\\n\" +\n\t\t\"s4-'('->s5\\n\" +\n\t\t\"s5-INT->s6\\n\" +\n\t\t\"s6-')'->s7\\n\" +\n\t\t\"s7-')'->s1\\n\",\n\n\t\t\"s0-'('->s4\\n\" +\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'b'->:s2=>1\\n\" +\n\t\t\"s1-'c'->:s3=>2\\n\" +\n\t\t\"s4-'('->s5\\n\" +\n\t\t\"s5-INT->s6\\n\" +\n\t\t\"s6-')'->s7\\n\" +\n\t\t\"s7-')'->s1\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testRecursiveLeftPrefixWithAorABIssue() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"A : 'a' ;\\n\" +\n\t\t\"B : 'b' ;\\n\" +\n\t\t\"C : 'c' ;\\n\" +\n\t\t\"LP : '(' ;\\n\" +\n\t\t\"RP : ')' ;\\n\" +\n\t\t\"INT : '0'..'9'+ ;\\n\"\n\t\t);\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"tokens {A,B,C,LP,RP,INT}\\n\" +\n\t\t\"a : e A | e A B ;\\n\" +\n\t\t\"e : LP e RP\\n\" +\n\t\t\"  | INT\\n\" +\n\t\t\"  ;\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"34a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"34ab\", 2); // PEG would miss this one!\n\t\tcheckPredictedAlt(lg, g, decision, \"((34))a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"((34))ab\", 2);\n\n\t\t// After matching these inputs for decision, what is DFA after each prediction?\n\t\tString[] inputs = {\n\t\t\"34a\",\n\t\t\"34ab\",\n\t\t\"((34))a\",\n\t\t\"((34))ab\",\n\t\t};\n\t\tString[] dfa = {\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'a'->s2\\n\" +\n\t\t\"s2-EOF->:s3=>1\\n\",\n\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'a'->s2\\n\" +\n\t\t\"s2-EOF->:s3=>1\\n\" +\n\t\t\"s2-'b'->:s4=>2\\n\",\n\n\t\t\"s0-'('->s5\\n\" +\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'a'->s2\\n\" +\n\t\t\"s2-EOF->:s3=>1\\n\" +\n\t\t\"s2-'b'->:s4=>2\\n\" +\n\t\t\"s5-'('->s6\\n\" +\n\t\t\"s6-INT->s7\\n\" +\n\t\t\"s7-')'->s8\\n\" +\n\t\t\"s8-')'->s1\\n\",\n\n\t\t\"s0-'('->s5\\n\" +\n\t\t\"s0-INT->s1\\n\" +\n\t\t\"s1-'a'->s2\\n\" +\n\t\t\"s2-EOF->:s3=>1\\n\" +\n\t\t\"s2-'b'->:s4=>2\\n\" +\n\t\t\"s5-'('->s6\\n\" +\n\t\t\"s6-INT->s7\\n\" +\n\t\t\"s7-')'->s8\\n\" +\n\t\t\"s8-')'->s1\\n\",\n\t\t};\n\t\tcheckDFAConstruction(lg, g, decision, inputs, dfa);\n\t}\n\n\t@Test public void testContinuePrediction() throws Exception {\n\t\t// Sam found prev def of ambiguity was too restrictive.\n\t\t// E.g., (13, 1, []), (13, 2, []), (12, 2, []) should not\n\t\t// be declared ambig since (12, 2, []) can take us to\n\t\t// unambig state maybe. keep going.\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"ID : 'a'..'z' ;\\n\" + // one char\n\t\t\"SEMI : ';' ;\\n\"+\n\t\t\"INT : '0'..'9'+ ;\\n\"\n\t\t);\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"tokens {ID,SEMI,INT}\\n\" +\n\t\t\"a : (ID | ID ID?) SEMI ;\");\n\t\tint decision = 1;\n\t\tcheckPredictedAlt(lg, g, decision, \"a;\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"ab;\", 2);\n\t}\n\n\t@Test public void testContinuePrediction2() throws Exception {\n\t\t// ID is ambig for first two alts, but ID SEMI lets us move forward with alt 3\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"ID : 'a'..'z' ;\\n\" + // one char\n\t\t\"SEMI : ';' ;\\n\"+\n\t\t\"INT : '0'..'9'+ ;\\n\"\n\t\t);\n\t\tGrammar g = new Grammar(\n\t\t\"parser grammar T;\\n\"+\n\t\t\"tokens {ID,SEMI,INT}\\n\" +\n\t\t\"a : ID | ID | ID SEMI ;\\n\");\n\t\tint decision = 0;\n\t\tcheckPredictedAlt(lg, g, decision, \"a\", 1);\n\t\tcheckPredictedAlt(lg, g, decision, \"a;\", 3);\n\t}\n\n\t@Test public void testAltsForLRRuleComputation() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\"grammar T;\\n\" +\n\t\t\"e : e '*' e\\n\" +\n\t\t\"  | INT\\n\" +\n\t\t\"  | e '+' e\\n\" +\n\t\t\"  | ID\\n\" +\n\t\t\"  ;\\n\" +\n\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\"WS : [ \\\\r\\\\t\\\\n]+ ;\");\n\t\tRule e = g.getRule(\"e\");\n\t\tassertTrue(e instanceof LeftRecursiveRule);\n\t\tLeftRecursiveRule lr = (LeftRecursiveRule)e;\n\t\tassertEquals(\"[0, 2, 4]\", Arrays.toString(lr.getPrimaryAlts()));\n\t\tassertEquals(\"[0, 1, 3]\", Arrays.toString(lr.getRecursiveOpAlts()));\n\t}\n\n\t@Test public void testAltsForLRRuleComputation2() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\"grammar T;\\n\" +\n\t\t\"e : INT\\n\" +\n\t\t\"  | e '*' e\\n\" +\n\t\t\"  | ID\\n\" +\n\t\t\"  ;\\n\" +\n\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\"WS : [ \\\\r\\\\t\\\\n]+ ;\");\n\t\tRule e = g.getRule(\"e\");\n\t\tassertTrue(e instanceof LeftRecursiveRule);\n\t\tLeftRecursiveRule lr = (LeftRecursiveRule)e;\n\t\tassertEquals(\"[0, 1, 3]\", Arrays.toString(lr.getPrimaryAlts()));\n\t\tassertEquals(\"[0, 2]\", Arrays.toString(lr.getRecursiveOpAlts()));\n\t}\n\n\t@Test public void testAltsForLRRuleComputation3() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\"grammar T;\\n\" +\n\t\t\"random : 'blort';\\n\" + // should have no effect\n\t\t\"e : '--' e\\n\" +\n\t\t\"  | e '*' e\\n\" +\n\t\t\"  | e '+' e\\n\" +\n\t\t\"  | e '--'\\n\" +\n\t\t\"  | ID\\n\" +\n\t\t\"  ;\\n\" +\n\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\"WS : [ \\\\r\\\\t\\\\n]+ ;\");\n\t\tRule e = g.getRule(\"e\");\n\t\tassertTrue(e instanceof LeftRecursiveRule);\n\t\tLeftRecursiveRule lr = (LeftRecursiveRule)e;\n\t\tassertEquals(\"[0, 1, 5]\", Arrays.toString(lr.getPrimaryAlts()));\n\t\tassertEquals(\"[0, 2, 3, 4]\", Arrays.toString(lr.getRecursiveOpAlts()));\n\t}\n\n\t/** first check that the ATN predicts right alt.\n\t *  Then check adaptive prediction.\n\t */\n\tpublic void checkPredictedAlt(LexerGrammar lg, Grammar g, int decision,\n\t                              String inputString, int expectedAlt)\n\t{\n\t\tATN lexatn = createATN(lg, true);\n\t\tLexerATNSimulator lexInterp =\n\t\tnew LexerATNSimulator(lexatn,new DFA[] { new DFA(lexatn.modeToStartState.get(Lexer.DEFAULT_MODE)) },new PredictionContextCache());\n\t\tIntegerList types = getTokenTypesViaATN(inputString, lexInterp);\n//\t\tSystem.out.println(types);\n\n\t\tsemanticProcess(lg);\n\t\tg.importVocab(lg);\n\t\tsemanticProcess(g);\n\n\t\tParserATNFactory f = new ParserATNFactory(g);\n\t\tATN atn = f.createATN();\n\n\t\tDOTGenerator dot = new DOTGenerator(g);\n\n\t\tRule r = g.getRule(\"a\");\n//\t\tif ( r!=null) System.out.println(dot.getDOT(atn.ruleToStartState[r.index]));\n\t\tr = g.getRule(\"b\");\n//\t\tif ( r!=null) System.out.println(dot.getDOT(atn.ruleToStartState[r.index]));\n\t\tr = g.getRule(\"e\");\n//\t\tif ( r!=null) System.out.println(dot.getDOT(atn.ruleToStartState[r.index]));\n\t\tr = g.getRule(\"ifstat\");\n//\t\tif ( r!=null) System.out.println(dot.getDOT(atn.ruleToStartState[r.index]));\n\t\tr = g.getRule(\"block\");\n//\t\tif ( r!=null) System.out.println(dot.getDOT(atn.ruleToStartState[r.index]));\n\n\t\t// Check ATN prediction\n//\t\tParserATNSimulator interp = new ParserATNSimulator(atn);\n\t\tTokenStream input = new MockIntTokenStream(types);\n\t\tParserInterpreterForTesting interp = new ParserInterpreterForTesting(g, input);\n\t\tint alt = interp.adaptivePredict(input, decision, ParserRuleContext.EMPTY);\n\n\t\tassertEquals(expectedAlt, alt);\n\n\t\t// Check adaptive prediction\n\t\tinput.seek(0);\n\t\talt = interp.adaptivePredict(input, decision, null);\n\t\tassertEquals(expectedAlt, alt);\n\t\t// run 2x; first time creates DFA in atn\n\t\tinput.seek(0);\n\t\talt = interp.adaptivePredict(input, decision, null);\n\t\tassertEquals(expectedAlt, alt);\n\t}\n\n\tpublic void checkDFAConstruction(LexerGrammar lg, Grammar g, int decision,\n\t                                 String[] inputString, String[] dfaString)\n\t{\n//\t\tTool.internalOption_ShowATNConfigsInDFA = true;\n\t\tATN lexatn = createATN(lg, true);\n\t\tLexerATNSimulator lexInterp =\n\t\tnew LexerATNSimulator(lexatn,new DFA[] { new DFA(lexatn.getDecisionState(Lexer.DEFAULT_MODE)) }, new PredictionContextCache());\n\n\t\tsemanticProcess(lg);\n\t\tg.importVocab(lg);\n\t\tsemanticProcess(g);\n\n\t\tParserInterpreterForTesting interp = new ParserInterpreterForTesting(g, null);\n\t\tfor (int i=0; i<inputString.length; i++) {\n\t\t\t// Check DFA\n\t\t\tIntegerList types = getTokenTypesViaATN(inputString[i], lexInterp);\n//\t\t\tSystem.out.println(types);\n\t\t\tTokenStream input = new MockIntTokenStream(types);\n\t\t\ttry {\n\t\t\t\tinterp.adaptivePredict(input, decision, ParserRuleContext.EMPTY);\n\t\t\t}\n\t\t\tcatch (NoViableAltException nvae) {\n\t\t\t\tnvae.printStackTrace(System.err);\n\t\t\t}\n\t\t\tDFA dfa = interp.parser.decisionToDFA[decision];\n\t\t\tassertEquals(dfaString[i], dfa.toString(g.getVocabulary()));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestATNSerialization.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNSerializer;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.Arrays;\n\nimport static org.antlr.v4.runtime.atn.ATNDeserializer.encodeIntsWith16BitWords;\nimport static org.antlr.v4.runtime.atn.ATNDeserializer.decodeIntsEncodedAs16BitWords;\nimport static org.antlr.v4.test.tool.ToolTestUtils.createATN;\nimport static org.junit.jupiter.api.Assertions.assertArrayEquals;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestATNSerialization {\n\t@Test public void testSimpleNoBlock() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A B ;\");\n\t\tString expecting =\n\t\t\t\"max type 2\\n\" +\n\t\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\t\"rule 0:0\\n\" +\n\t\t\t\t\"0->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"2->3 ATOM 1,0,0\\n\" +\n\t\t\t\t\"3->4 ATOM 2,0,0\\n\" +\n\t\t\t\t\"4->1 EPSILON 0,0,0\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void testEOF() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\t\t\t\"a : A EOF ;\");\n\t\tString expecting =\n\t\t\t\t\"max type 1\\n\" +\n\t\t\t\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\t\t\t\"rule 0:0\\n\" +\n\t\t\t\t\t\t\"0->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\t\t\"2->3 ATOM 1,0,0\\n\" +\n\t\t\t\t\t\t\"3->4 ATOM 0,0,1\\n\" +\n\t\t\t\t\t\t\"4->1 EPSILON 0,0,0\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void testEOFInSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : (A|EOF) ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"rule 0:0\\n\" +\n\t\t\t\t\"0:EOF, A..A\\n\" +\n\t\t\t\t\"0->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"2->3 SET 0,0,0\\n\" +\n\t\t\t\t\"3->1 EPSILON 0,0,0\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void testNot() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"tokens {A, B, C}\\n\" +\n\t\t\t\"a : ~A ;\");\n\t\tString expecting =\n\t\t\t\"max type 3\\n\" +\n\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:0\\n\" +\n\t\t\t\"0:A..A\\n\" +\n\t\t\t\"0->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"2->3 NOT_SET 0,0,0\\n\" +\n\t\t\t\"3->1 EPSILON 0,0,0\\n\";\n\t\tATN atn = createATN(g, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(g.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testWildcard() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"tokens {A, B, C}\\n\" +\n\t\t\t\"a : . ;\");\n\t\tString expecting =\n\t\t\t\"max type 3\\n\" +\n\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:0\\n\" +\n\t\t\t\"0->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"2->3 WILDCARD 0,0,0\\n\" +\n\t\t\t\"3->1 EPSILON 0,0,0\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void testPEGAchillesHeel() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A | A B ;\");\n\t\tString expecting =\n\t\t\t\"max type 2\\n\" +\n\t\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"5:BLOCK_START 0 6\\n\" +\n\t\t\t\t\"6:BLOCK_END 0\\n\" +\n\t\t\t\t\"7:BASIC 0\\n\" +\n\t\t\t\t\"rule 0:0\\n\" +\n\t\t\t\t\"0->5 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"2->6 ATOM 1,0,0\\n\" +\n\t\t\t\t\"3->4 ATOM 1,0,0\\n\" +\n\t\t\t\t\"4->6 ATOM 2,0,0\\n\" +\n\t\t\t\t\"5->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"5->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:5\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void test3Alts() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A | A B | A B C ;\");\n\t\tString expecting =\n\t\t\t\"max type 3\\n\" +\n\t\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\t\"6:BASIC 0\\n\" +\n\t\t\t\t\"7:BASIC 0\\n\" +\n\t\t\t\t\"8:BLOCK_START 0 9\\n\" +\n\t\t\t\t\"9:BLOCK_END 0\\n\" +\n\t\t\t\t\"10:BASIC 0\\n\" +\n\t\t\t\t\"rule 0:0\\n\" +\n\t\t\t\t\"0->8 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"2->9 ATOM 1,0,0\\n\" +\n\t\t\t\t\"3->4 ATOM 1,0,0\\n\" +\n\t\t\t\t\"4->9 ATOM 2,0,0\\n\" +\n\t\t\t\t\"5->6 ATOM 1,0,0\\n\" +\n\t\t\t\t\"6->7 ATOM 2,0,0\\n\" +\n\t\t\t\t\"7->9 ATOM 3,0,0\\n\" +\n\t\t\t\t\"8->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"8->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"8->5 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"9->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:8\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void testSimpleLoop() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : A+ B ;\");\n\t\tString expecting =\n\t\t\t\"max type 2\\n\" +\n\t\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\t\"2:BASIC 0\\n\" +\n\t\t\t\t\"3:PLUS_BLOCK_START 0 4\\n\" +\n\t\t\t\t\"4:BLOCK_END 0\\n\" +\n\t\t\t\t\"5:PLUS_LOOP_BACK 0\\n\" +\n\t\t\t\t\"6:LOOP_END 0 5\\n\" +\n\t\t\t\t\"7:BASIC 0\\n\" +\n\t\t\t\t\"8:BASIC 0\\n\" +\n\t\t\t\t\"9:BASIC 0\\n\" +\n\t\t\t\t\"rule 0:0\\n\" +\n\t\t\t\t\"0->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"2->4 ATOM 1,0,0\\n\" +\n\t\t\t\t\"3->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"4->5 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"5->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"5->6 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->7 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"7->8 ATOM 2,0,0\\n\" +\n\t\t\t\t\"8->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:5\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void testRuleRef() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : e ;\\n\" +\n\t\t\t\"e : E ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\t\"0:RULE_START 0\\n\" +\n\t\t\t\t\"1:RULE_STOP 0\\n\" +\n\t\t\t\t\"2:RULE_START 1\\n\" +\n\t\t\t\t\"3:RULE_STOP 1\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\t\"6:BASIC 1\\n\" +\n\t\t\t\t\"7:BASIC 1\\n\" +\n\t\t\t\t\"8:BASIC 1\\n\" +\n\t\t\t\t\"rule 0:0\\n\" +\n\t\t\t\t\"rule 1:2\\n\" +\n\t\t\t\t\"0->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"2->6 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"4->5 RULE 2,1,0\\n\" +\n\t\t\t\t\"5->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->7 ATOM 1,0,0\\n\" +\n\t\t\t\t\"7->3 EPSILON 0,0,0\\n\";\n\t\tcheckResults(g, expecting);\n\t}\n\n\t@Test public void testLexerTwoRules() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 2\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:RULE_START 1\\n\" +\n\t\t\t\"4:RULE_STOP 1\\n\" +\n\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\"6:BASIC 0\\n\" +\n\t\t\t\"7:BASIC 1\\n\" +\n\t\t\t\"8:BASIC 1\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"rule 1:3 2\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"0->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->5 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->7 EPSILON 0,0,0\\n\" +\n\t\t\t\"5->6 ATOM 97,0,0\\n\" +\n\t\t\t\"6->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"7->8 ATOM 98,0,0\\n\" +\n\t\t\t\"8->4 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeSMPLiteralSerializedToSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : '\\\\u{1F4A9}' ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 ATOM 128169,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeSMPRangeSerializedToSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : ('a'..'\\\\u{1F4A9}') ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 RANGE 97,128169,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeSMPAndBMPSetSerialized() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\t\t\t\"SMP : ('\\\\u{1F4A9}' | '\\\\u{1F4AF}') ;\\n\"+\n\t\t\t\t\t\t\"BMP : ('a' | 'x') ;\");\n\t\tString expecting =\n\t\t\t\t\"max type 2\\n\" +\n\t\t\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\t\t\t\"3:RULE_START 1\\n\" +\n\t\t\t\t\t\t\"4:RULE_STOP 1\\n\" +\n\t\t\t\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\t\t\t\"6:BASIC 0\\n\" +\n\t\t\t\t\t\t\"7:BASIC 1\\n\" +\n\t\t\t\t\t\t\"8:BASIC 1\\n\" +\n\t\t\t\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\t\t\t\"rule 1:3 2\\n\" +\n\t\t\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\t\t\"0:128169..128169, 128175..128175\\n\" +\n\t\t\t\t\t\t\"1:'a'..'a', 'x'..'x'\\n\" +\n\t\t\t\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\t\t\"0->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\t\t\"1->5 EPSILON 0,0,0\\n\" +\n\t\t\t\t\t\t\"3->7 EPSILON 0,0,0\\n\" +\n\t\t\t\t\t\t\"5->6 SET 0,0,0\\n\" +\n\t\t\t\t\t\t\"6->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\t\t\"7->8 SET 1,0,0\\n\" +\n\t\t\t\t\t\t\"8->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerWith0xFFFCInSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\t\t\"ID : ([A-Z_]|'Ā'..'\\\\uFFFC') ([A-Z_0-9]|'Ā'..'\\\\uFFFC')*; // FFFD+ are not valid char\\n\");\n\t\tString expecting =\n\t\t\t\t\"max type 1\\n\" +\n\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BLOCK_START 0 5\\n\" +\n\t\t\t\t\"5:BLOCK_END 0\\n\" +\n\t\t\t\t\"6:BASIC 0\\n\" +\n\t\t\t\t\"7:STAR_BLOCK_START 0 8\\n\" +\n\t\t\t\t\"8:BLOCK_END 0\\n\" +\n\t\t\t\t\"9:STAR_LOOP_ENTRY 0\\n\" +\n\t\t\t\t\"10:LOOP_END 0 11\\n\" +\n\t\t\t\t\"11:STAR_LOOP_BACK 0\\n\" +\n\t\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\"0:'A'..'Z', '_'..'_', '\\\\u0100'..'\\\\uFFFC'\\n\" +\n\t\t\t\t\"1:'0'..'9', 'A'..'Z', '_'..'_', '\\\\u0100'..'\\\\uFFFC'\\n\" +\n\t\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"3->5 SET 0,0,0\\n\" +\n\t\t\t\t\"4->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"5->9 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->8 SET 1,0,0\\n\" +\n\t\t\t\t\"7->6 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"8->11 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"9->7 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"9->10 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"10->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"11->9 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:0\\n\" +\n\t\t\t\t\"1:4\\n\" +\n\t\t\t\t\"2:7\\n\" +\n\t\t\t\t\"3:9\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerNotLiteral() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : ~'a' ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'a'..'a'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : '0'..'9' ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 RANGE 48,57,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : 'a' EOF ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"3->4 ATOM 97,0,0\\n\" +\n\t\t\t\t\"4->5 ATOM 0,0,1\\n\" +\n\t\t\t\t\"5->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerEOFInSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : 'a' (EOF|'\\\\n') ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"5:BLOCK_START 0 6\\n\" +\n\t\t\t\t\"6:BLOCK_END 0\\n\" +\n\t\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\"0:EOF, '\\\\n'..'\\\\n'\\n\" +\n\t\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"3->5 ATOM 97,0,0\\n\" +\n\t\t\t\t\"4->6 SET 0,0,0\\n\" +\n\t\t\t\t\"5->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:0\\n\" +\n\t\t\t\t\"1:5\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerLoops() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"INT : '0'..'9'+ ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:PLUS_BLOCK_START 0 5\\n\" +\n\t\t\t\t\"5:BLOCK_END 0\\n\" +\n\t\t\t\t\"6:PLUS_LOOP_BACK 0\\n\" +\n\t\t\t\t\"7:LOOP_END 0 6\\n\" +\n\t\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"3->5 RANGE 48,57,0\\n\" +\n\t\t\t\t\"4->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"5->6 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->7 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"7->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:0\\n\" +\n\t\t\t\t\"1:6\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerAction() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a' {a} ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' {c} ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 3\\n\" +\n\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\t\"3:RULE_START 1\\n\" +\n\t\t\t\t\"4:RULE_STOP 1\\n\" +\n\t\t\t\t\"5:RULE_START 2\\n\" +\n\t\t\t\t\"6:RULE_STOP 2\\n\" +\n\t\t\t\t\"7:BASIC 0\\n\" +\n\t\t\t\t\"8:BASIC 0\\n\" +\n\t\t\t\t\"9:BASIC 0\\n\" +\n\t\t\t\t\"10:BASIC 1\\n\" +\n\t\t\t\t\"11:BASIC 1\\n\" +\n\t\t\t\t\"12:BASIC 2\\n\" +\n\t\t\t\t\"13:BASIC 2\\n\" +\n\t\t\t\t\"14:BASIC 2\\n\" +\n\t\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\t\"rule 1:3 2\\n\" +\n\t\t\t\t\"rule 2:5 3\\n\" +\n\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0->5 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->7 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"3->10 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"5->12 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"7->8 ATOM 97,0,0\\n\" +\n\t\t\t\t\"8->9 ACTION 0,0,0\\n\" +\n\t\t\t\t\"9->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"10->11 ATOM 98,0,0\\n\" +\n\t\t\t\t\"11->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"12->13 ATOM 99,0,0\\n\" +\n\t\t\t\t\"13->14 ACTION 2,1,0\\n\" +\n\t\t\t\t\"14->6 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerNotSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'a'..'b'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tcheckResults(lg, expecting);\n\t}\n\n\t@Test public void testLexerSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('a'|'b'|'e'|'p'..'t')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'a'..'b', 'e'..'e', 'p'..'t'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerNotSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b'|'e'|'p'..'t')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'a'..'b', 'e'..'e', 'p'..'t'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeUnescapedBMPNotSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\u4E9C'|'\\u4E9D')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'\\\\u4E9C'..'\\\\u4E9D'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeUnescapedBMPSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('\\u4E9C'|'\\u4E9D'|'\\u6C5F'|'\\u305F'..'\\u307B')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'\\\\u305F'..'\\\\u307B', '\\\\u4E9C'..'\\\\u4E9D', '\\\\u6C5F'..'\\\\u6C5F'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeUnescapedBMPNotSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\u4E9C'|'\\u4E9D'|'\\u6C5F'|'\\u305F'..'\\u307B')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'\\\\u305F'..'\\\\u307B', '\\\\u4E9C'..'\\\\u4E9D', '\\\\u6C5F'..'\\\\u6C5F'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeEscapedBMPNotSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\\\u4E9C'|'\\\\u4E9D')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'\\\\u4E9C'..'\\\\u4E9D'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeEscapedBMPSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('\\\\u4E9C'|'\\\\u4E9D'|'\\\\u6C5F'|'\\\\u305F'..'\\\\u307B')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'\\\\u305F'..'\\\\u307B', '\\\\u4E9C'..'\\\\u4E9D', '\\\\u6C5F'..'\\\\u6C5F'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeEscapedBMPNotSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\\\u4E9C'|'\\\\u4E9D'|'\\\\u6C5F'|'\\\\u305F'..'\\\\u307B')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:'\\\\u305F'..'\\\\u307B', '\\\\u4E9C'..'\\\\u4E9D', '\\\\u6C5F'..'\\\\u6C5F'\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeEscapedSMPNotSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\\\u{1F4A9}'|'\\\\u{1F4AA}')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:128169..128170\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeEscapedSMPSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ('\\\\u{1F4A9}'|'\\\\u{1F4AA}'|'\\\\u{1F441}'|'\\\\u{1D40F}'..'\\\\u{1D413}')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:119823..119827, 128065..128065, 128169..128170\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerUnicodeEscapedSMPNotSetWithRange() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('\\\\u{1F4A9}'|'\\\\u{1F4AA}'|'\\\\u{1F441}'|'\\\\u{1D40F}'..'\\\\u{1D413}')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"0:119823..119827, 128065..128065, 128169..128170\\n\" +\n\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\"4->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerWildcardWithMode() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : 'a'..'z'+ ;\\n\"+\n\t\t\t\"mode CMT;\" +\n\t\t\t\"COMMENT : '*/' {skip(); popMode();} ;\\n\" +\n\t\t\t\"JUNK : . {more();} ;\\n\");\n\t\tString expecting =\n\t\t\t\"max type 3\\n\" +\n\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\"1:TOKEN_START -1\\n\" +\n\t\t\t\t\"2:RULE_START 0\\n\" +\n\t\t\t\t\"3:RULE_STOP 0\\n\" +\n\t\t\t\t\"4:RULE_START 1\\n\" +\n\t\t\t\t\"5:RULE_STOP 1\\n\" +\n\t\t\t\t\"6:RULE_START 2\\n\" +\n\t\t\t\t\"7:RULE_STOP 2\\n\" +\n\t\t\t\t\"8:BASIC 0\\n\" +\n\t\t\t\t\"9:PLUS_BLOCK_START 0 10\\n\" +\n\t\t\t\t\"10:BLOCK_END 0\\n\" +\n\t\t\t\t\"11:PLUS_LOOP_BACK 0\\n\" +\n\t\t\t\t\"12:LOOP_END 0 11\\n\" +\n\t\t\t\t\"13:BASIC 1\\n\" +\n\t\t\t\t\"14:BASIC 1\\n\" +\n\t\t\t\t\"15:BASIC 1\\n\" +\n\t\t\t\t\"16:BASIC 1\\n\" +\n\t\t\t\t\"17:BASIC 1\\n\" +\n\t\t\t\t\"18:BASIC 2\\n\" +\n\t\t\t\t\"19:BASIC 2\\n\" +\n\t\t\t\t\"20:BASIC 2\\n\" +\n\t\t\t\t\"rule 0:2 1\\n\" +\n\t\t\t\t\"rule 1:4 2\\n\" +\n\t\t\t\t\"rule 2:6 3\\n\" +\n\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\"mode 1:1\\n\" +\n\t\t\t\t\"0->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->4 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->6 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"2->9 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"4->13 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"6->18 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"8->10 RANGE 97,122,0\\n\" +\n\t\t\t\t\"9->8 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"10->11 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"11->9 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"11->12 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"12->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"13->14 ATOM 42,0,0\\n\" +\n\t\t\t\t\"14->15 ATOM 47,0,0\\n\" +\n\t\t\t\t\"15->16 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"16->17 ACTION 1,0,0\\n\" +\n\t\t\t\t\"17->5 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"18->19 WILDCARD 0,0,0\\n\" +\n\t\t\t\t\"19->20 ACTION 2,1,0\\n\" +\n\t\t\t\t\"20->7 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:0\\n\" +\n\t\t\t\t\"1:1\\n\" +\n\t\t\t\t\"2:11\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testLexerNotSetWithRange2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"ID : ~('a'|'b') ~('e'|'p'..'t')\\n ;\");\n\t\tString expecting =\n\t\t\t\"max type 1\\n\" +\n\t\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\t\"1:RULE_START 0\\n\" +\n\t\t\t\t\"2:RULE_STOP 0\\n\" +\n\t\t\t\t\"3:BASIC 0\\n\" +\n\t\t\t\t\"4:BASIC 0\\n\" +\n\t\t\t\t\"5:BASIC 0\\n\" +\n\t\t\t\t\"rule 0:1 1\\n\" +\n\t\t\t\t\"mode 0:0\\n\" +\n\t\t\t\t\"0:'a'..'b'\\n\" +\n\t\t\t\t\"1:'e'..'e', 'p'..'t'\\n\" +\n\t\t\t\t\"0->1 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"1->3 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"3->4 NOT_SET 0,0,0\\n\" +\n\t\t\t\t\"4->5 NOT_SET 1,0,0\\n\" +\n\t\t\t\t\"5->2 EPSILON 0,0,0\\n\" +\n\t\t\t\t\"0:0\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testModeInLexer() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a'\\n ;\\n\" +\n\t\t\t\"B : 'b';\\n\" +\n\t\t\t\"mode M;\\n\" +\n\t\t\t\"C : 'c';\\n\"+\n\t\t\t\"D : 'd';\\n\");\n\t\tString expecting =\n\t\t\t\"max type 4\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:TOKEN_START -1\\n\" +\n\t\t\t\"2:RULE_START 0\\n\" +\n\t\t\t\"3:RULE_STOP 0\\n\" +\n\t\t\t\"4:RULE_START 1\\n\" +\n\t\t\t\"5:RULE_STOP 1\\n\" +\n\t\t\t\"6:RULE_START 2\\n\" +\n\t\t\t\"7:RULE_STOP 2\\n\" +\n\t\t\t\"8:RULE_START 3\\n\" +\n\t\t\t\"9:RULE_STOP 3\\n\" +\n\t\t\t\"10:BASIC 0\\n\" +\n\t\t\t\"11:BASIC 0\\n\" +\n\t\t\t\"12:BASIC 1\\n\" +\n\t\t\t\"13:BASIC 1\\n\" +\n\t\t\t\"14:BASIC 2\\n\" +\n\t\t\t\"15:BASIC 2\\n\" +\n\t\t\t\"16:BASIC 3\\n\" +\n\t\t\t\"17:BASIC 3\\n\" +\n\t\t\t\"rule 0:2 1\\n\" +\n\t\t\t\"rule 1:4 2\\n\" +\n\t\t\t\"rule 2:6 3\\n\" +\n\t\t\t\"rule 3:8 4\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"mode 1:1\\n\" +\n\t\t\t\"0->2 EPSILON 0,0,0\\n\" +\n\t\t\t\"0->4 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->6 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->8 EPSILON 0,0,0\\n\" +\n\t\t\t\"2->10 EPSILON 0,0,0\\n\" +\n\t\t\t\"4->12 EPSILON 0,0,0\\n\" +\n\t\t\t\"6->14 EPSILON 0,0,0\\n\" +\n\t\t\t\"8->16 EPSILON 0,0,0\\n\" +\n\t\t\t\"10->11 ATOM 97,0,0\\n\" +\n\t\t\t\"11->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"12->13 ATOM 98,0,0\\n\" +\n\t\t\t\"13->5 EPSILON 0,0,0\\n\" +\n\t\t\t\"14->15 ATOM 99,0,0\\n\" +\n\t\t\t\"15->7 EPSILON 0,0,0\\n\" +\n\t\t\t\"16->17 ATOM 100,0,0\\n\" +\n\t\t\t\"17->9 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\" +\n\t\t\t\"1:1\\n\";\n\t\tATN atn = createATN(lg, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(lg.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void test2ModesInLexer() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"A : 'a'\\n ;\\n\" +\n\t\t\t\"mode M;\\n\" +\n\t\t\t\"B : 'b';\\n\" +\n\t\t\t\"mode M2;\\n\" +\n\t\t\t\"C : 'c';\\n\");\n\t\tString expecting =\n\t\t\t\"max type 3\\n\" +\n\t\t\t\"0:TOKEN_START -1\\n\" +\n\t\t\t\"1:TOKEN_START -1\\n\" +\n\t\t\t\"2:TOKEN_START -1\\n\" +\n\t\t\t\"3:RULE_START 0\\n\" +\n\t\t\t\"4:RULE_STOP 0\\n\" +\n\t\t\t\"5:RULE_START 1\\n\" +\n\t\t\t\"6:RULE_STOP 1\\n\" +\n\t\t\t\"7:RULE_START 2\\n\" +\n\t\t\t\"8:RULE_STOP 2\\n\" +\n\t\t\t\"9:BASIC 0\\n\" +\n\t\t\t\"10:BASIC 0\\n\" +\n\t\t\t\"11:BASIC 1\\n\" +\n\t\t\t\"12:BASIC 1\\n\" +\n\t\t\t\"13:BASIC 2\\n\" +\n\t\t\t\"14:BASIC 2\\n\" +\n\t\t\t\"rule 0:3 1\\n\" +\n\t\t\t\"rule 1:5 2\\n\" +\n\t\t\t\"rule 2:7 3\\n\" +\n\t\t\t\"mode 0:0\\n\" +\n\t\t\t\"mode 1:1\\n\" +\n\t\t\t\"mode 2:2\\n\" +\n\t\t\t\"0->3 EPSILON 0,0,0\\n\" +\n\t\t\t\"1->5 EPSILON 0,0,0\\n\" +\n\t\t\t\"2->7 EPSILON 0,0,0\\n\" +\n\t\t\t\"3->9 EPSILON 0,0,0\\n\" +\n\t\t\t\"5->11 EPSILON 0,0,0\\n\" +\n\t\t\t\"7->13 EPSILON 0,0,0\\n\" +\n\t\t\t\"9->10 ATOM 97,0,0\\n\" +\n\t\t\t\"10->4 EPSILON 0,0,0\\n\" +\n\t\t\t\"11->12 ATOM 98,0,0\\n\" +\n\t\t\t\"12->6 EPSILON 0,0,0\\n\" +\n\t\t\t\"13->14 ATOM 99,0,0\\n\" +\n\t\t\t\"14->8 EPSILON 0,0,0\\n\" +\n\t\t\t\"0:0\\n\" +\n\t\t\t\"1:1\\n\" +\n\t\t\t\"2:2\\n\";\n\t\tcheckResults(lg, expecting);\n\t}\n\n\tprivate void checkResults(Grammar g, String expecting) {\n\t\tATN atn = createATN(g, true);\n\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\tString result = new ATNDescriber(atn, Arrays.asList(g.getTokenNames())).decode(serialized.toArray());\n\t\tassertEquals(expecting, result);\n\n\t\tIntegerList serialized16 = encodeIntsWith16BitWords(serialized);\n\t\tint[] ints16 = serialized16.toArray();\n\t\tchar[] chars = new char[ints16.length];\n\t\tfor (int i = 0; i < ints16.length; i++) {\n\t\t\tchars[i] = (char)ints16[i];\n\t\t}\n\t\tint[] serialized32 = decodeIntsEncodedAs16BitWords(chars, true);\n\n\t\tassertArrayEquals(serialized.toArray(), serialized32);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestActionSplitter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.ANTLRStringStream;\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.parse.ActionSplitter;\nimport org.antlr.v4.semantics.BlankActionSplitterListener;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestActionSplitter {\n    final static String[] exprs = {\n        \"foo\",\t\t\"['foo'<\" + ActionSplitter.TEXT + \">]\",\n        \"$x\",\t\t\"['$x'<\" + ActionSplitter.ATTR + \">]\",\n        \"\\\\$x\",\t\t\"['\\\\$x'<\" + ActionSplitter.TEXT + \">]\",\n        \"$x.y\",\t\t\"['$x.y'<\" + ActionSplitter.QUALIFIED_ATTR + \">]\",\n        \"$ID.text\",\t\t\"['$ID.text'<\" + ActionSplitter.QUALIFIED_ATTR + \">]\",\n        \"$ID\",\t\t\"['$ID'<\" + ActionSplitter.ATTR + \">]\",\n        \"$ID.getText()\",\t\t\"['$ID'<\" + ActionSplitter.ATTR + \">, '.getText()'<\" + ActionSplitter.TEXT + \">]\",\n        \"$ID.text = \\\"test\\\";\",\t\t\"['$ID.text'<\" + ActionSplitter.QUALIFIED_ATTR + \">, ' = \\\"test\\\";'<\" + ActionSplitter.TEXT + \">]\",\n        \"$a.line == $b.line\",\t\t\"['$a.line'<\" + ActionSplitter.QUALIFIED_ATTR + \">, ' == '<\" + ActionSplitter.TEXT + \">, '$b.line'<\" + ActionSplitter.QUALIFIED_ATTR + \">]\",\n        \"$r.tree\",\t\t\"['$r.tree'<\" + ActionSplitter.QUALIFIED_ATTR + \">]\",\n        \"foo $a::n bar\",\t\t\"['foo '<\" + ActionSplitter.TEXT + \">, '$a::n'<\" + ActionSplitter.NONLOCAL_ATTR + \">, ' bar'<\" + ActionSplitter.TEXT + \">]\",\n        \"$rule::x;\",\t\t\"['$rule::x'<\" + ActionSplitter.NONLOCAL_ATTR + \">, ';'<\" + ActionSplitter.TEXT + \">]\",\n        \"$field::x = $field.st;\",\t\t\"['$field::x = $field.st;'<\" + ActionSplitter.SET_NONLOCAL_ATTR + \">]\",\n        \"$foo.get(\\\"ick\\\");\",\t\t\"['$foo'<\" + ActionSplitter.ATTR + \">, '.get(\\\"ick\\\");'<\" + ActionSplitter.TEXT + \">]\",\n    };\n\n    @Test\n\tpublic void testExprs() {\n\t\tfor (int i = 0; i < exprs.length; i += 2) {\n\t\t\tString input = exprs[i];\n\t\t\tString expect = exprs[i + 1];\n\t\t\tList<String> chunks = getActionChunks(input);\n\t\t\tassertEquals(expect, chunks.toString(), \"input: \" + input);\n\t\t}\n\t}\n\n\tprivate static List<String> getActionChunks(String a) {\n        List<String> chunks = new ArrayList<String>();\n        ActionSplitter splitter = new ActionSplitter(new ANTLRStringStream(a),\n\t\t\t\t\t\t\t\t\t\t\t\t\t new BlankActionSplitterListener());\n        Token t = splitter.nextToken();\n        while ( t.getType()!=Token.EOF ) {\n            chunks.add(\"'\"+t.getText()+\"'<\"+t.getType()+\">\");\n            t = splitter.nextToken();\n        }\n        return chunks;\n    }\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestActionTranslation.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.analysis.AnalysisPipeline;\nimport org.antlr.v4.automata.ATNFactory;\nimport org.antlr.v4.automata.LexerATNFactory;\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.codegen.SourceType;\nimport org.antlr.v4.semantics.SemanticPipeline;\nimport org.antlr.v4.test.runtime.ErrorQueue;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STGroupString;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/** */\n@SuppressWarnings(\"unused\")\npublic class TestActionTranslation {\n\tString attributeTemplate =\n\t\t\"attributeTemplate(members,init,inline,finally,inline2) ::= <<\\n\" +\n\t\t\"parser grammar A;\\n\"+\n\t\t\"@members {#members#<members>#end-members#}\\n\" +\n\t\t\"a[int x, int x1] returns [int y]\\n\" +\n\t\t\"@init {#init#<init>#end-init#}\\n\" +\n\t\t\"    :   id=ID ids+=ID lab=b[34] c d {\\n\" +\n\t\t\"\t\t #inline#<inline>#end-inline#\\n\" +\n\t\t\"\t\t }\\n\" +\n\t\t\"\t\t c\\n\" +\n\t\t\"    ;\\n\" +\n\t\t\"    finally {#finally#<finally>#end-finally#}\\n\" +\n\t\t\"b[int d] returns [int e]\\n\" +\n\t\t\"    :   {#inline2#<inline2>#end-inline2#}\\n\" +\n\t\t\"    ;\\n\" +\n\t\t\"c returns [int x, int y] : ;\\n\" +\n\t\t\"d\t :   ;\\n\" +\n\t\t\">>\";\n\n    @Test public void testEscapedLessThanInAction() throws Exception {\n        String action = \"i<3; '<xmltag>'\";\n\t\tString expected = \"i<3; '<xmltag>'\";\n\t\ttestActions(attributeTemplate, \"members\", action, expected);\n\t\ttestActions(attributeTemplate, \"init\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t\ttestActions(attributeTemplate, \"finally\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline2\", action, expected);\n    }\n\n    @Test public void testEscaped$InAction() throws Exception {\n\t\tString action = \"int \\\\$n; \\\"\\\\$in string\\\\$\\\"\";\n\t\tString expected = \"int $n; \\\"$in string$\\\"\";\n\t\ttestActions(attributeTemplate, \"members\", action, expected);\n\t\ttestActions(attributeTemplate, \"init\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t\ttestActions(attributeTemplate, \"finally\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline2\", action, expected);\n    }\n\n\t/**\n\t * Regression test for \"in antlr v4 lexer, $ translation issue in action\".\n\t * https://github.com/antlr/antlr4/issues/176\n\t */\n\t@Test public void testUnescaped$InAction() throws Exception {\n\t\tString action = \"\\\\$string$\";\n\t\tString expected = \"$string$\";\n\t\ttestActions(attributeTemplate, \"members\", action, expected);\n\t\ttestActions(attributeTemplate, \"init\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t\ttestActions(attributeTemplate, \"finally\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline2\", action, expected);\n\t}\n\n\t@Test public void testEscapedSlash() throws Exception {\n\t\tString action   = \"x = '\\\\n';\";  // x = '\\n'; -> x = '\\n';\n\t\tString expected = \"x = '\\\\n';\";\n\t\ttestActions(attributeTemplate, \"members\", action, expected);\n\t\ttestActions(attributeTemplate, \"init\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t\ttestActions(attributeTemplate, \"finally\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline2\", action, expected);\n\t}\n\n\t@Test public void testComplicatedArgParsing() throws Exception {\n\t\tString action = \"x, (*a).foo(21,33), 3.2+1, '\\\\n', \"+\n\t\t\t\t\t\t\"\\\"a,oo\\\\nick\\\", {bl, \\\"fdkj\\\"eck}\";\n\t\tString expected = \"x, (*a).foo(21,33), 3.2+1, '\\\\n', \"+\n\t\t\t\t\t\t\"\\\"a,oo\\\\nick\\\", {bl, \\\"fdkj\\\"eck}\";\n\t\ttestActions(attributeTemplate, \"members\", action, expected);\n\t\ttestActions(attributeTemplate, \"init\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t\ttestActions(attributeTemplate, \"finally\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline2\", action, expected);\n\t}\n\n\t@Test public void testComplicatedArgParsingWithTranslation() throws Exception {\n\t\tString action = \"x, $ID.text+\\\"3242\\\", (*$ID).foo(21,33), 3.2+1, '\\\\n', \"+\n\t\t\t\t\t\t\"\\\"a,oo\\\\nick\\\", {bl, \\\"fdkj\\\"eck}\";\n\t\tString expected =\n\t\t\t\"x, (((AContext)_localctx).ID!=null?((AContext)_localctx).ID.getText():null)+\\\"3242\\\", \" +\n\t\t\t\"(*((AContext)_localctx).ID).foo(21,33), 3.2+1, '\\\\n', \\\"a,oo\\\\nick\\\", {bl, \\\"fdkj\\\"eck}\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t}\n\n\t@Test public void testArguments() throws Exception {\n\t\tString action = \"$x; $ctx.x\";\n\t\tString expected = \"_localctx.x; _localctx.x\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t}\n\n\t@Test public void testReturnValue() throws Exception {\n\t\tString action = \"$y; $ctx.y\";\n\t\tString expected = \"_localctx.y; _localctx.y\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t}\n\n\t@Test public void testReturnValueWithNumber() throws Exception {\n\t\tString action = \"$ctx.x1\";\n\t\tString expected = \"_localctx.x1\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t}\n\n\t@Test public void testReturnValuesCurrentRule() throws Exception {\n\t\tString action = \"$y; $ctx.y;\";\n\t\tString expected = \"_localctx.y; _localctx.y;\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t}\n\n\t@Test public void testReturnValues() throws Exception {\n\t\tString action = \"$lab.e; $b.e; $y.e = \\\"\\\";\";\n\t\tString expected = \"((AContext)_localctx).lab.e; ((AContext)_localctx).b.e; _localctx.y.e = \\\"\\\";\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t}\n\n    @Test public void testReturnWithMultipleRuleRefs() throws Exception {\n\t\tString action = \"$c.x; $c.y;\";\n\t\tString expected = \"((AContext)_localctx).c.x; ((AContext)_localctx).c.y;\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n    }\n\n    @Test public void testTokenRefs() throws Exception {\n\t\tString action = \"$id; $ID; $id.text; $id.getText(); $id.line;\";\n\t\tString expected = \"((AContext)_localctx).id; ((AContext)_localctx).ID; (((AContext)_localctx).id!=null?((AContext)_localctx).id.getText():null); ((AContext)_localctx).id.getText(); (((AContext)_localctx).id!=null?((AContext)_localctx).id.getLine():0);\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n    }\n\n    @Test public void testRuleRefs() throws Exception {\n        String action = \"$lab.start; $c.text;\";\n\t\tString expected = \"(((AContext)_localctx).lab!=null?(((AContext)_localctx).lab.start):null); (((AContext)_localctx).c!=null?_input.getText(((AContext)_localctx).c.start,((AContext)_localctx).c.stop):null);\";\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n    }\n\n    /** Added in response to https://github.com/antlr/antlr4/issues/1211 */\n\t@Test public void testUnknownAttr() throws Exception {\n\t\tString action = \"$qqq.text\";\n\t\tString expected = \"\"; // was causing an exception\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t}\n\n\t/**\n\t * Regression test for issue #1295\n     * $e.v yields incorrect value 0 in \"e returns [int v] : '1' {$v = 1;} | '(' e ')' {$v = $e.v;} ;\"\n\t * https://github.com/antlr/antlr4/issues/1295\n\t */\n\t@Test public void testRuleRefsRecursive() throws Exception {\n        String recursiveTemplate =\n            \"recursiveTemplate(inline) ::= <<\\n\" +\n            \"parser grammar A;\\n\"+\n            \"e returns [int v]\\n\" +\n            \"    :   INT {$v = $INT.int;}\\n\" +\n            \"    |   '(' e ')' {\\n\" +\n            \"\t\t #inline#<inline>#end-inline#\\n\" +\n            \"\t\t }\\n\" +\n            \"    ;\\n\" +\n            \">>\";\n        String leftRecursiveTemplate =\n            \"recursiveTemplate(inline) ::= <<\\n\" +\n            \"parser grammar A;\\n\"+\n            \"e returns [int v]\\n\" +\n            \"    :   a=e op=('*'|'/') b=e  {$v = eval($a.v, $op.type, $b.v);}\\n\" +\n            \"    |   INT {$v = $INT.int;}\\n\" +\n            \"    |   '(' e ')' {\\n\" +\n            \"\t\t #inline#<inline>#end-inline#\\n\" +\n            \"\t\t }\\n\" +\n            \"    ;\\n\" +\n            \">>\";\n        // ref to value returned from recursive call to rule\n        String action = \"$v = $e.v;\";\n\t\tString expected = \"((EContext)_localctx).v =  ((EContext)_localctx).e.v;\";\n\t\ttestActions(recursiveTemplate, \"inline\", action, expected);\n\t\ttestActions(leftRecursiveTemplate, \"inline\", action, expected);\n        // ref to predefined attribute obtained from recursive call to rule\n        action = \"$v = $e.text.length();\";\n        expected = \"((EContext)_localctx).v =  (((EContext)_localctx).e!=null?_input.getText(((EContext)_localctx).e.start,((EContext)_localctx).e.stop):null).length();\";\n\t\ttestActions(recursiveTemplate, \"inline\", action, expected);\n\t\ttestActions(leftRecursiveTemplate, \"inline\", action, expected);\n\t}\n\n\t@Test public void testRefToTextAttributeForCurrentRule() throws Exception {\n        String action = \"$ctx.text; $text\";\n\n\t\t// this is the expected translation for all cases\n\t\tString expected =\n\t\t\t\"_localctx.text; _input.getText(_localctx.start, _input.LT(-1))\";\n\n\t\ttestActions(attributeTemplate, \"init\", action, expected);\n\t\ttestActions(attributeTemplate, \"inline\", action, expected);\n\t\ttestActions(attributeTemplate, \"finally\", action, expected);\n    }\n\n    @Test public void testEmptyActions() throws Exception {\n\t    String gS =\n\t   \t\t\"grammar A;\\n\"+\n\t   \t\t\"a[] : 'a' ;\\n\" +\n\t   \t\t\"c : a[] c[] ;\\n\";\n\t    Grammar g = new Grammar(gS);\n    }\n\n\tprivate static void testActions(String templates, String actionName, String action, String expected) throws org.antlr.runtime.RecognitionException {\n\t\tint lp = templates.indexOf('(');\n\t\tString name = templates.substring(0, lp);\n\t\tSTGroup group = new STGroupString(templates);\n\t\tST st = group.getInstanceOf(name);\n\t\tst.add(actionName, action);\n\t\tString grammar = st.render();\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tGrammar g = new Grammar(grammar, equeue);\n\t\tif ( g.ast!=null && !g.ast.hasErrors ) {\n\t\t\tSemanticPipeline sem = new SemanticPipeline(g);\n\t\t\tsem.process();\n\n\t\t\tATNFactory factory = new ParserATNFactory(g);\n\t\t\tif ( g.isLexer() ) factory = new LexerATNFactory((LexerGrammar)g);\n\t\t\tg.atn = factory.createATN();\n\n\t\t\tAnalysisPipeline anal = new AnalysisPipeline(g);\n\t\t\tanal.process();\n\n\t\t\tCodeGenerator gen = CodeGenerator.create(g);\n\t\t\tST outputFileST = gen.generateParser(SourceType.SOURCE);\n\t\t\tString output = outputFileST.render();\n\t\t\t//System.out.println(output);\n\t\t\tString b = \"#\" + actionName + \"#\";\n\t\t\tint start = output.indexOf(b);\n\t\t\tString e = \"#end-\" + actionName + \"#\";\n\t\t\tint end = output.indexOf(e);\n\t\t\tString snippet = output.substring(start+b.length(),end);\n\t\t\tassertEquals(expected, snippet);\n\t\t}\n\t\tif ( equeue.size()>0 ) {\n//\t\t\tSystem.err.println(equeue.toString());\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestAmbigParseTrees.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.gui.Trees;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.atn.ATNState;\nimport org.antlr.v4.runtime.atn.AmbiguityInfo;\nimport org.antlr.v4.runtime.atn.BasicBlockStartState;\nimport org.antlr.v4.runtime.atn.DecisionInfo;\nimport org.antlr.v4.runtime.atn.DecisionState;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.atn.RuleStartState;\nimport org.antlr.v4.runtime.atn.Transition;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.GrammarParserInterpreter;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n\npublic class TestAmbigParseTrees {\n\t@Test public void testParseDecisionWithinAmbiguousStartRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : A x C\" +\n\t\t\t\"  | A B C\" +\n\t\t\t\"  ;\" +\n\t\t\t\"x : B ; \\n\",\n\t\t\tlg);\n\n\t\ttestInterpAtSpecificAlt(lg, g, \"s\", 1, \"abc\", \"(s:1 a (x:1 b) c)\");\n\t\ttestInterpAtSpecificAlt(lg, g, \"s\", 2, \"abc\", \"(s:2 a b c)\");\n\t}\n\n\t@Test public void testAmbigAltsAtRoot() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : A x C\" +\n\t\t\t\"  | A B C\" +\n\t\t\t\"  ;\" +\n\t\t\t\"x : B ; \\n\",\n\t\t\tlg);\n\n\t\tString startRule = \"s\";\n\t\tString input = \"abc\";\n\t\tString expectedAmbigAlts = \"{1, 2}\";\n\t\tint decision = 0;\n\t\tString expectedOverallTree = \"(s:1 a (x:1 b) c)\";\n\t\tString[] expectedParseTrees = {\"(s:1 a (x:1 b) c)\",\n\t\t\t\t\t\t\t\t\t   \"(s:2 a b c)\"};\n\n\t\ttestAmbiguousTrees(lg, g, startRule, input, decision,\n\t\t\t\t\t\t   expectedAmbigAlts,\n\t\t\t\t\t\t   expectedOverallTree, expectedParseTrees);\n\t}\n\n\t@Test public void testAmbigAltsNotAtRoot() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : x ;\" +\n\t\t\t\"x : y ;\" +\n\t\t\t\"y : A z C\" +\n\t\t\t\"  | A B C\" +\n\t\t\t\"  ;\" +\n\t\t\t\"z : B ; \\n\",\n\t\t\tlg);\n\n\t\tString startRule = \"s\";\n\t\tString input = \"abc\";\n\t\tString expectedAmbigAlts = \"{1, 2}\";\n\t\tint decision = 0;\n\t\tString expectedOverallTree = \"(s:1 (x:1 (y:1 a (z:1 b) c)))\";\n\t\tString[] expectedParseTrees = {\"(y:1 a (z:1 b) c)\",\n\t\t\t\t\t\t\t\t\t   \"(y:2 a b c)\"};\n\n\t\ttestAmbiguousTrees(lg, g, startRule, input, decision,\n\t\t\t\t\t\t   expectedAmbigAlts,\n\t\t\t\t\t\t   expectedOverallTree, expectedParseTrees);\n\t}\n\n\t@Test public void testAmbigAltDipsIntoOuterContextToRoot() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"SELF : 'self' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"DOT : '.' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"e : p (DOT ID)* ;\\n\"+\n\t\t\t\"p : SELF\" +\n\t\t\t\"  | SELF DOT ID\" +\n\t\t\t\"  ;\",\n\t\t\tlg);\n\n\t\tString startRule = \"e\";\n\t\tString input = \"self.x\";\n\t\tString expectedAmbigAlts = \"{1, 2}\";\n\t\tint decision = 1; // decision in p\n\t\tString expectedOverallTree = \"(e:1 (p:1 self) . x)\";\n\t\tString[] expectedParseTrees = {\"(e:1 (p:1 self) . x)\",\n\t\t\t\t\t\t\t\t\t   \"(p:2 self . x)\"};\n\n\t\ttestAmbiguousTrees(lg, g, startRule, input, decision,\n\t\t\t\t\t\t   expectedAmbigAlts,\n\t\t\t\t\t\t   expectedOverallTree, expectedParseTrees);\n\t}\n\n\t@Test public void testAmbigAltDipsIntoOuterContextBelowRoot() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"SELF : 'self' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"DOT : '.' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e ;\\n\"+\n\t\t\t\"e : p (DOT ID)* ;\\n\"+\n\t\t\t\"p : SELF\" +\n\t\t\t\"  | SELF DOT ID\" +\n\t\t\t\"  ;\",\n\t\t\tlg);\n\n\t\tString startRule = \"s\";\n\t\tString input = \"self.x\";\n\t\tString expectedAmbigAlts = \"{1, 2}\";\n\t\tint decision = 1; // decision in p\n\t\tString expectedOverallTree = \"(s:1 (e:1 (p:1 self) . x))\";\n\t\tString[] expectedParseTrees = {\"(e:1 (p:1 self) . x)\", // shouldn't include s\n\t\t\t\t\t\t\t\t\t   \"(p:2 self . x)\"};      // shouldn't include e\n\n\t\ttestAmbiguousTrees(lg, g, startRule, input, decision,\n\t\t\t\t\t\t   expectedAmbigAlts,\n\t\t\t\t\t\t   expectedOverallTree, expectedParseTrees);\n\t}\n\n\t@Test public void testAmbigAltInLeftRecursiveBelowStartRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"SELF : 'self' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"DOT : '.' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e ;\\n\" +\n\t\t\t\"e : p | e DOT ID ;\\n\"+\n\t\t\t\"p : SELF\" +\n\t\t\t\"  | SELF DOT ID\" +\n\t\t\t\"  ;\",\n\t\t\tlg);\n\n\t\tString startRule = \"s\";\n\t\tString input = \"self.x\";\n\t\tString expectedAmbigAlts = \"{1, 2}\";\n\t\tint decision = 1; // decision in p\n\t\tString expectedOverallTree = \"(s:1 (e:2 (e:1 (p:1 self)) . x))\";\n\t\tString[] expectedParseTrees = {\"(e:2 (e:1 (p:1 self)) . x)\",\n\t\t\t\t\t\t\t\t\t   \"(p:2 self . x)\"};\n\n\t\ttestAmbiguousTrees(lg, g, startRule, input, decision,\n\t\t\t\t\t\t   expectedAmbigAlts,\n\t\t\t\t\t\t   expectedOverallTree, expectedParseTrees);\n\t}\n\n\t@Test public void testAmbigAltInLeftRecursiveStartRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"SELF : 'self' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"DOT : '.' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"e : p | e DOT ID ;\\n\"+\n\t\t\t\"p : SELF\" +\n\t\t\t\"  | SELF DOT ID\" +\n\t\t\t\"  ;\",\n\t\t\tlg);\n\n\t\tString startRule = \"e\";\n\t\tString input = \"self.x\";\n\t\tString expectedAmbigAlts = \"{1, 2}\";\n\t\tint decision = 1; // decision in p\n\t\tString expectedOverallTree = \"(e:2 (e:1 (p:1 self)) . x)\";\n\t\tString[] expectedParseTrees = {\"(e:2 (e:1 (p:1 self)) . x)\",\n\t\t\t\t\t\t\t\t\t   \"(p:2 self . x)\"}; // shows just enough for self.x\n\n\t\ttestAmbiguousTrees(lg, g, startRule, input, decision,\n\t\t\t\t\t\t   expectedAmbigAlts,\n\t\t\t\t\t\t   expectedOverallTree, expectedParseTrees);\n\t}\n\n\tpublic void testAmbiguousTrees(LexerGrammar lg, Grammar g,\n\t\t\t\t\t\t\t\t   String startRule, String input, int decision,\n\t\t\t\t\t\t\t\t   String expectedAmbigAlts,\n\t\t\t\t\t\t\t\t   String overallTree,\n\t\t\t\t\t\t\t\t   String[] expectedParseTrees)\n\t{\n\t\tInterpreterTreeTextProvider nodeTextProvider = new InterpreterTreeTextProvider(g.getRuleNames());\n\n\t\tLexerInterpreter lexEngine = lg.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\tfinal GrammarParserInterpreter parser = g.createGrammarParserInterpreter(tokens);\n\t\tparser.setProfile(true);\n\t\tparser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);\n\n\t\t// PARSE\n\t\tint ruleIndex = g.rules.get(startRule).index;\n\t\tParserRuleContext parseTree = parser.parse(ruleIndex);\n\t\tassertEquals(overallTree, Trees.toStringTree(parseTree, nodeTextProvider));\n\t\tSystem.out.println();\n\n\t\tDecisionInfo[] decisionInfo = parser.getParseInfo().getDecisionInfo();\n\t\tList<AmbiguityInfo> ambiguities = decisionInfo[decision].ambiguities;\n\t\tassertEquals(1, ambiguities.size());\n\t\tAmbiguityInfo ambiguityInfo = ambiguities.get(0);\n\n\t\tList<ParserRuleContext> ambiguousParseTrees =\n\t\t\tGrammarParserInterpreter.getAllPossibleParseTrees(g,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  parser,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  tokens,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  decision,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  ambiguityInfo.ambigAlts,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  ambiguityInfo.startIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  ambiguityInfo.stopIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  ruleIndex);\n\t\tassertEquals(expectedAmbigAlts, ambiguityInfo.ambigAlts.toString());\n\t\tassertEquals(ambiguityInfo.ambigAlts.cardinality(), ambiguousParseTrees.size());\n\n\t\tfor (int i = 0; i<ambiguousParseTrees.size(); i++) {\n\t\t\tParserRuleContext t = ambiguousParseTrees.get(i);\n\t\t\tassertEquals(expectedParseTrees[i], Trees.toStringTree(t, nodeTextProvider));\n\t\t}\n\t}\n\n\tvoid testInterpAtSpecificAlt(LexerGrammar lg, Grammar g,\n\t\t\t\t\t\t\t\t String startRule, int startAlt,\n\t\t\t\t\t\t\t\t String input,\n\t\t\t\t\t\t\t\t String expectedParseTree)\n\t{\n\t\tLexerInterpreter lexEngine = lg.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\tParserInterpreter parser = g.createGrammarParserInterpreter(tokens);\n\t\tRuleStartState ruleStartState = g.atn.ruleToStartState[g.getRule(startRule).index];\n\t\tTransition tr = ruleStartState.transition(0);\n\t\tATNState t2 = tr.target;\n\t\tif ( !(t2 instanceof BasicBlockStartState) ) {\n\t\t\tthrow new IllegalArgumentException(\"rule has no decision: \"+startRule);\n\t\t}\n\t\tparser.addDecisionOverride(((DecisionState)t2).decision, 0, startAlt);\n\t\tParseTree t = parser.parse(g.rules.get(startRule).index);\n\t\tInterpreterTreeTextProvider nodeTextProvider = new InterpreterTreeTextProvider(g.getRuleNames());\n\t\tassertEquals(expectedParseTree, Trees.toStringTree(t, nodeTextProvider));\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestAttributeChecks.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.tool.ErrorType;\nimport org.junit.jupiter.api.Test;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.misc.ErrorBuffer;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.testErrors;\n\n/** */\npublic class TestAttributeChecks {\n    String attributeTemplate =\n        \"parser grammar A;\\n\"+\n        \"@members {<members>}\\n\" +\n\t\t\"tokens{ID}\\n\" +\n        \"a[int x] returns [int y]\\n\" +\n        \"@init {<init>}\\n\" +\n        \"    :   id=ID ids+=ID lab=b[34] labs+=b[34] {\\n\" +\n\t\t\"\t\t <inline>\\n\" +\n\t\t\"\t\t }\\n\" +\n\t\t\"\t\t c\\n\" +\n        \"    ;\\n\" +\n        \"    finally {<finally>}\\n\" +\n        \"b[int d] returns [int e]\\n\" +\n        \"    :   {<inline2>}\\n\" +\n        \"    ;\\n\" +\n        \"c   :   ;\\n\";\n\n    String[] membersChecks = {\n\t    \"$a\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:2:11: unknown attribute reference a in $a\\n\",\n        \"$a.y\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:2:11: unknown attribute reference a in $a.y\\n\",\n    };\n\n    String[] initChecks = {\n\t\t\"$text\",\t\t\"\",\n\t\t\"$start\",\t\t\"\",\n\t\t\"$x = $y\",\t\t\"\",\n\t\t\"$y = $x\",\t\t\"\",\n\t\t\"$lab.e\",\t\t\"\",\n\t\t\"$ids\",\t\t\t\"\",\n\t\t\"$labs\",\t\t\"\",\n\n\t\t\"$c\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:5:8: unknown attribute reference c in $c\\n\",\n\t\t\"$a.q\",\t\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:5:10: unknown attribute q for rule a in $a.q\\n\",\n    };\n\n\tString[] inlineChecks = {\n\t\t\"$text\",\t\t\"\",\n\t\t\"$start\",\t\t\"\",\n\t\t\"$x = $y\",\t\t\"\",\n\t\t\"$y = $x\",\t\t\"\",\n\t\t\"$y.b = 3;\",\t\"\",\n\t\t\"$ctx.x = $ctx.y\",\t\"\",\n\t\t\"$lab.e\",\t\t\"\",\n\t\t\"$lab.text\",\t\"\",\n\t\t\"$b.e\",\t\t\t\"\",\n\t\t\"$c.text\",      \"\",\n\t\t\"$ID\",\t\t\t\"\",\n\t\t\"$ID.text\",\t\t\"\",\n\t\t\"$id\",\t\t\t\"\",\n\t\t\"$id.text\",\t\t\"\",\n\t\t\"$ids\",\t\t\t\"\",\n\t\t\"$labs\",\t\t\"\",\n\t};\n\n\tString[] bad_inlineChecks = {\n\t\t\"$lab\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:7:4: missing attribute access on rule reference lab in $lab\\n\",\n\t\t\"$q\",           \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference q in $q\\n\",\n\t\t\"$q.y\",         \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference q in $q.y\\n\",\n\t\t\"$q = 3\",       \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference q in $q\\n\",\n\t\t\"$q = 3;\",      \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference q in $q = 3;\\n\",\n\t\t\"$q.y = 3;\",    \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference q in $q.y\\n\",\n\t\t\"$q = $blort;\", \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference q in $q = $blort;\\n\" +\n\t\t\t\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:9: unknown attribute reference blort in $blort\\n\",\n\t\t\"$a.ick\",       \"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:7:6: unknown attribute ick for rule a in $a.ick\\n\",\n\t\t\"$a.ick = 3;\",  \"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:7:6: unknown attribute ick for rule a in $a.ick\\n\",\n\t\t\"$b.d\",         \"error(\" + ErrorType.INVALID_RULE_PARAMETER_REF.code + \"): A.g4:7:6: parameter d of rule b is not accessible in this scope: $b.d\\n\",  // cant see rule refs arg\n\t\t\"$d.text\",      \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference d in $d.text\\n\", // valid rule, but no ref\n\t\t\"$lab.d\",\t\t\"error(\" + ErrorType.INVALID_RULE_PARAMETER_REF.code + \"): A.g4:7:8: parameter d of rule b is not accessible in this scope: $lab.d\\n\",\n\t\t\"$ids = null;\",\t\"error(\" + ErrorType.ASSIGNMENT_TO_LIST_LABEL.code + \"): A.g4:7:4: cannot assign a value to list label ids\\n\",\n\t\t\"$labs = null;\",\"error(\" + ErrorType.ASSIGNMENT_TO_LIST_LABEL.code + \"): A.g4:7:4: cannot assign a value to list label labs\\n\",\n\t};\n\n\tString[] finallyChecks = {\n\t\t\"$text\",\t\t\"\",\n\t\t\"$start\",\t\t\"\",\n\t\t\"$x = $y\",\t\t\"\",\n\t\t\"$y = $x\",\t\t\"\",\n\t\t\"$lab.e\",\t\t\"\",\n\t\t\"$lab.text\",\t\"\",\n\t\t\"$id\",\t\t\t\"\",\n\t\t\"$id.text\",\t\t\"\",\n\t\t\"$ids\",\t\t\t\"\",\n\t\t\"$labs\",\t\t\"\",\n\n\t\t\"$lab\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:10:14: missing attribute access on rule reference lab in $lab\\n\",\n\t\t\"$q\",           \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference q in $q\\n\",\n\t\t\"$q.y\",         \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference q in $q.y\\n\",\n\t\t\"$q = 3\",       \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference q in $q\\n\",\n\t\t\"$q = 3;\",      \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference q in $q = 3;\\n\",\n\t\t\"$q.y = 3;\",    \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference q in $q.y\\n\",\n\t\t\"$q = $blort;\", \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference q in $q = $blort;\\n\" +\n\t\t\t\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:19: unknown attribute reference blort in $blort\\n\",\n\t\t\"$a.ick\",       \"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:10:16: unknown attribute ick for rule a in $a.ick\\n\",\n\t\t\"$a.ick = 3;\",  \"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:10:16: unknown attribute ick for rule a in $a.ick\\n\",\n\t\t\"$b.e\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference b in $b.e\\n\", // cant see rule refs outside alts\n\t\t\"$b.d\",         \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference b in $b.d\\n\",\n\t\t\"$c.text\",      \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference c in $c.text\\n\",\n\t\t\"$lab.d\",\t\t\"error(\" + ErrorType.INVALID_RULE_PARAMETER_REF.code + \"): A.g4:10:18: parameter d of rule b is not accessible in this scope: $lab.d\\n\",\n\t};\n\n\tString[] dynMembersChecks = {\n\t\t\"$S\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:2:11: unknown attribute reference S in $S\\n\",\n\t\t\"$S::i\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:2:11: reference to undefined rule S in non-local ref $S::i\\n\",\n\t\t\"$S::i=$S::i\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:2:11: reference to undefined rule S in non-local ref $S::i\\n\" +\n\t\t\t\t\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:2:17: reference to undefined rule S in non-local ref $S::i\\n\",\n\n\t\t\"$b::f\",\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:2:14: unknown attribute f for rule b in $b::f\\n\",\n\t\t\"$S::j\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:2:11: reference to undefined rule S in non-local ref $S::j\\n\",\n\t\t\"$S::j = 3;\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:2:11: reference to undefined rule S in non-local ref $S::j = 3;\\n\",\n\t\t\"$S::j = $S::k;\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:2:11: reference to undefined rule S in non-local ref $S::j = $S::k;\\n\",\n\t};\n\n\tString[] dynInitChecks = {\n\t\t\"$a\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:5:8: missing attribute access on rule reference a in $a\\n\",\n\t\t\"$b\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:5:8: unknown attribute reference b in $b\\n\",\n\t\t\"$lab\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:5:8: missing attribute access on rule reference lab in $lab\\n\",\n\t\t\"$b::f\",\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:5:11: unknown attribute f for rule b in $b::f\\n\",\n\t\t\"$S::i\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:5:8: reference to undefined rule S in non-local ref $S::i\\n\",\n\t\t\"$S::i=$S::i\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:5:8: reference to undefined rule S in non-local ref $S::i\\n\" +\n\t\t\t\t\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:5:14: reference to undefined rule S in non-local ref $S::i\\n\",\n\t\t\"$a::z\",\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:5:11: unknown attribute z for rule a in $a::z\\n\",\n\t\t\"$S\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:5:8: unknown attribute reference S in $S\\n\",\n\n\t\t\"$S::j\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:5:8: reference to undefined rule S in non-local ref $S::j\\n\",\n\t\t\"$S::j = 3;\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:5:8: reference to undefined rule S in non-local ref $S::j = 3;\\n\",\n\t\t\"$S::j = $S::k;\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:5:8: reference to undefined rule S in non-local ref $S::j = $S::k;\\n\",\n\t};\n\n\tString[] dynInlineChecks = {\n\t\t\"$a\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:7:4: missing attribute access on rule reference a in $a\\n\",\n\t\t\"$b\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:7:4: missing attribute access on rule reference b in $b\\n\",\n\t\t\"$lab\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:7:4: missing attribute access on rule reference lab in $lab\\n\",\n\t\t\"$b::f\",\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:7:7: unknown attribute f for rule b in $b::f\\n\",\n\t\t\"$S::i\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:7:4: reference to undefined rule S in non-local ref $S::i\\n\",\n\t\t\"$S::i=$S::i\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:7:4: reference to undefined rule S in non-local ref $S::i\\n\" +\n\t\t\t\t\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:7:10: reference to undefined rule S in non-local ref $S::i\\n\",\n\t\t\"$a::z\",\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:7:7: unknown attribute z for rule a in $a::z\\n\",\n\n\t\t\"$S::j\",\t\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:7:4: reference to undefined rule S in non-local ref $S::j\\n\",\n\t\t\"$S::j = 3;\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:7:4: reference to undefined rule S in non-local ref $S::j = 3;\\n\",\n\t\t\"$S::j = $S::k;\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:7:4: reference to undefined rule S in non-local ref $S::j = $S::k;\\n\",\n\t\t\"$Q[-1]::y\",        \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$Q[-i]::y\",        \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$Q[i]::y\",    \t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$Q[0]::y\",    \t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$Q[-1]::y = 23;\",  \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$Q[-i]::y = 23;\",  \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$Q[i]::y = 23;\",   \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$Q[0]::y = 23;\",   \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference Q in $Q\\n\",\n\t\t\"$S[-1]::y\",        \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[-i]::y\",        \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[i]::y\",     \t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[0]::y\",     \t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[-1]::y = 23;\",  \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[-i]::y = 23;\",  \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[i]::y = 23;\",   \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[0]::y = 23;\",   \"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\",\n\t\t\"$S[$S::y]::i\",\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:7:4: unknown attribute reference S in $S\\n\" +\n\t\t\t\t\t\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:7:7: reference to undefined rule S in non-local ref $S::y\\n\"\n\t};\n\n\tString[] dynFinallyChecks = {\n\t\t\"$a\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:10:14: missing attribute access on rule reference a in $a\\n\",\n\t\t\"$b\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference b in $b\\n\",\n\t\t\"$lab\",\t\t\t\"error(\" + ErrorType.ISOLATED_RULE_REF.code + \"): A.g4:10:14: missing attribute access on rule reference lab in $lab\\n\",\n\t\t\"$b::f\",\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:10:17: unknown attribute f for rule b in $b::f\\n\",\n\t\t\"$S\",\t\t\t\"error(\" + ErrorType.UNKNOWN_SIMPLE_ATTRIBUTE.code + \"): A.g4:10:14: unknown attribute reference S in $S\\n\",\n\t\t\"$S::i\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:10:14: reference to undefined rule S in non-local ref $S::i\\n\",\n\t\t\"$S::i=$S::i\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:10:14: reference to undefined rule S in non-local ref $S::i\\n\" +\n\t\t\t\t\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:10:20: reference to undefined rule S in non-local ref $S::i\\n\",\n\t\t\"$a::z\",\t\t\"error(\" + ErrorType.UNKNOWN_RULE_ATTRIBUTE.code + \"): A.g4:10:17: unknown attribute z for rule a in $a::z\\n\",\n\n\t\t\"$S::j\",\t\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:10:14: reference to undefined rule S in non-local ref $S::j\\n\",\n\t\t\"$S::j = 3;\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:10:14: reference to undefined rule S in non-local ref $S::j = 3;\\n\",\n\t\t\"$S::j = $S::k;\",\t\"error(\" + ErrorType.UNDEFINED_RULE_IN_NONLOCAL_REF.code + \"): A.g4:10:14: reference to undefined rule S in non-local ref $S::j = $S::k;\\n\",\n\t};\n\n    @Test public void testMembersActions() throws RecognitionException {\n        testActions(\"members\", membersChecks, attributeTemplate);\n    }\n\n    @Test public void testDynamicMembersActions() throws RecognitionException {\n        testActions(\"members\", dynMembersChecks, attributeTemplate);\n    }\n\n    @Test public void testInitActions() throws RecognitionException {\n        testActions(\"init\", initChecks, attributeTemplate);\n    }\n\n    @Test public void testDynamicInitActions() throws RecognitionException {\n        testActions(\"init\", dynInitChecks, attributeTemplate);\n    }\n\n\t@Test public void testInlineActions() throws RecognitionException {\n\t\ttestActions(\"inline\", inlineChecks, attributeTemplate);\n\t}\n\n\t@Test public void testDynamicInlineActions() throws RecognitionException {\n\t\ttestActions(\"inline\", dynInlineChecks, attributeTemplate);\n\t}\n\n\t@Test public void testBadInlineActions() throws RecognitionException {\n\t\ttestActions(\"inline\", bad_inlineChecks, attributeTemplate);\n\t}\n\n\t@Test public void testFinallyActions() throws RecognitionException {\n\t\ttestActions(\"finally\", finallyChecks, attributeTemplate);\n\t}\n\n\t@Test public void testDynamicFinallyActions() throws RecognitionException {\n\t\ttestActions(\"finally\", dynFinallyChecks, attributeTemplate);\n\t}\n\n\t@Test public void testTokenRef() throws RecognitionException {\n\t\tString grammar =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"tokens{ID}\\n\" +\n\t\t\t\"a : x=ID {Token t = $x; t = $ID;} ;\\n\";\n\t\tString expected =\n\t\t\t\"\";\n\t\ttestErrors(new String[] {grammar, expected}, false);\n\t}\n\n\tprivate static void testActions(String location, String[] pairs, String template) {\n\t\tfor (int i = 0; i < pairs.length; i += 2) {\n\t\t\tString action = pairs[i];\n\t\t\tString expected = pairs[i + 1];\n\t\t\tSTGroup g = new STGroup('<', '>');\n\t\t\tg.setListener(new ErrorBuffer()); // hush warnings\n\t\t\tST st = new ST(g, template);\n\t\t\tst.add(location, action);\n\t\t\tString grammar = st.render();\n\t\t\ttestErrors(new String[]{grammar, expected}, false);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestBasicSemanticErrors.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.tool.ErrorType;\nimport org.junit.jupiter.api.Test;\nimport org.stringtemplate.v4.ST;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.testErrors;\n\npublic class TestBasicSemanticErrors {\n    final static String[] U = {\n        // INPUT\n        \"parser grammar U;\\n\" +\n        \"options { foo=bar; k=3;}\\n\" +\n        \"tokens {\\n\" +\n\t\t\"        ID,\\n\" +\n        \"        f,\\n\" +\n        \"        S\\n\" +\n        \"}\\n\" +\n        \"tokens { A }\\n\" +\n        \"options { x=y; }\\n\" +\n        \"\\n\" +\n        \"a\\n\" +\n        \"options { blech=bar; greedy=true; }\\n\" +\n        \"        :       ID\\n\" +\n        \"        ;\\n\" +\n        \"b : ( options { ick=bar; greedy=true; } : ID )+ ;\\n\" +\n        \"c : ID<blue> ID<x=y> ;\",\n        // YIELDS\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:2:10: unsupported option foo\\n\" +\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:2:19: unsupported option k\\n\" +\n\t\t\"error(\" + ErrorType.TOKEN_NAMES_MUST_START_UPPER.code + \"): U.g4:5:8: token names must start with an uppercase letter: f\\n\" +\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:9:10: unsupported option x\\n\" +\n\t\t\"error(\" + ErrorType.REPEATED_PREQUEL.code + \"): U.g4:9:0: repeated grammar prequel spec (options, tokens, or import); please merge\\n\" +\n\t\t\"error(\" + ErrorType.REPEATED_PREQUEL.code + \"): U.g4:8:0: repeated grammar prequel spec (options, tokens, or import); please merge\\n\" +\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:12:10: unsupported option blech\\n\" +\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:12:21: unsupported option greedy\\n\" +\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:15:16: unsupported option ick\\n\" +\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:15:25: unsupported option greedy\\n\" +\n\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): U.g4:16:16: unsupported option x\\n\",\n    };\n\n\t@Test public void testU() { testErrors(U, false); }\n\n\t/**\n\t * Regression test for #25 \"Don't allow labels on not token set subrules\".\n\t * https://github.com/antlr/antlr4/issues/25\n\t */\n\t@Test\n\tpublic void testIllegalNonSetLabel() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"ss : op=('=' | '+=' | expr) EOF;\\n\" +\n\t\t\t\"expr : '=' '=';\\n\" +\n\t\t\t\"\";\n\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.LABEL_BLOCK_NOT_A_SET.code + \"): T.g4:2:5: label op assigned to a block which is not a set\\n\";\n\n\t\ttestErrors(new String[] { grammar, expected }, false);\n\t}\n\n\t@Test\n\tpublic void testArgumentRetvalLocalConflicts() throws Exception {\n\t\tString grammarTemplate =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"ss<if(args)>[<args>]<endif> <if(retvals)>returns [<retvals>]<endif>\\n\" +\n\t\t\t\"<if(locals)>locals [<locals>]<endif>\\n\" +\n\t\t\t\"  : <body> EOF;\\n\" +\n\t\t\t\"expr : '=';\\n\";\n\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.ARG_CONFLICTS_WITH_RULE.code + \"): T.g4:2:7: parameter expr conflicts with rule with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.RETVAL_CONFLICTS_WITH_RULE.code + \"): T.g4:2:26: return value expr conflicts with rule with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.LOCAL_CONFLICTS_WITH_RULE.code + \"): T.g4:3:12: local expr conflicts with rule with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.RETVAL_CONFLICTS_WITH_ARG.code + \"): T.g4:2:26: return value expr conflicts with parameter with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.LOCAL_CONFLICTS_WITH_ARG.code + \"): T.g4:3:12: local expr conflicts with parameter with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.LOCAL_CONFLICTS_WITH_RETVAL.code + \"): T.g4:3:12: local expr conflicts with return value with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.LABEL_CONFLICTS_WITH_RULE.code + \"): T.g4:4:4: label expr conflicts with rule with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.LABEL_CONFLICTS_WITH_ARG.code + \"): T.g4:4:4: label expr conflicts with parameter with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.LABEL_CONFLICTS_WITH_RETVAL.code + \"): T.g4:4:4: label expr conflicts with return value with same name\\n\" +\n\t\t\t\"error(\" + ErrorType.LABEL_CONFLICTS_WITH_LOCAL.code + \"): T.g4:4:4: label expr conflicts with local with same name\\n\";\n\t\tST grammarST = new ST(grammarTemplate);\n\t\tgrammarST.add(\"args\", \"int expr\");\n\t\tgrammarST.add(\"retvals\", \"int expr\");\n\t\tgrammarST.add(\"locals\", \"int expr\");\n\t\tgrammarST.add(\"body\", \"expr=expr\");\n\t\ttestErrors(new String[] { grammarST.render(), expected }, false);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestBufferedTokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.BufferedTokenStream;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenSource;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestBufferedTokenStream {\n\tprotected TokenStream createTokenStream(TokenSource src) {\n\t\treturn new BufferedTokenStream(src);\n\t}\n\n\t@Test public void testFirstToken() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 3 * 0 + 2 * 0;\n        CharStream input = new ANTLRInputStream(\"x = 3 * 0 + 2 * 0;\");\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n        TokenStream tokens = createTokenStream(lexEngine);\n\n        String result = tokens.LT(1).getText();\n        String expecting = \"x\";\n        assertEquals(expecting, result);\n    }\n\n    @Test public void test2ndToken() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 3 * 0 + 2 * 0;\n        CharStream input = new ANTLRInputStream(\"x = 3 * 0 + 2 * 0;\");\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n        TokenStream tokens = createTokenStream(lexEngine);\n\n        String result = tokens.LT(2).getText();\n        String expecting = \" \";\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testCompleteBuffer() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 3 * 0 + 2 * 0;\n        CharStream input = new ANTLRInputStream(\"x = 3 * 0 + 2 * 0;\");\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n        TokenStream tokens = createTokenStream(lexEngine);\n\n        int i = 1;\n        Token t = tokens.LT(i);\n        while ( t.getType()!=Token.EOF ) {\n            i++;\n            t = tokens.LT(i);\n        }\n        tokens.LT(i++); // push it past end\n        tokens.LT(i++);\n\n        String result = tokens.getText();\n        String expecting = \"x = 3 * 0 + 2 * 0;\";\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testCompleteBufferAfterConsuming() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 3 * 0 + 2 * 0;\n        CharStream input = new ANTLRInputStream(\"x = 3 * 0 + 2 * 0;\");\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n        TokenStream tokens = createTokenStream(lexEngine);\n\n        Token t = tokens.LT(1);\n        while ( t.getType()!=Token.EOF ) {\n            tokens.consume();\n            t = tokens.LT(1);\n        }\n\n        String result = tokens.getText();\n        String expecting = \"x = 3 * 0 + 2 * 0;\";\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testLookback() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 3 * 0 + 2 * 0;\n        CharStream input = new ANTLRInputStream(\"x = 3 * 0 + 2 * 0;\");\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n        TokenStream tokens = createTokenStream(lexEngine);\n\n        tokens.consume(); // get x into buffer\n        Token t = tokens.LT(-1);\n        assertEquals(\"x\", t.getText());\n\n        tokens.consume();\n        tokens.consume(); // consume '='\n        t = tokens.LT(-3);\n        assertEquals(\"x\", t.getText());\n        t = tokens.LT(-2);\n        assertEquals(\" \", t.getText());\n        t = tokens.LT(-1);\n        assertEquals(\"=\", t.getText());\n    }\n\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestCharSupport.java",
    "content": "/*\n * Copyright (c) 2012-2019 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.misc.CharSupport;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertNull;\n\npublic class TestCharSupport {\n\t@Test\n\tpublic void testGetANTLRCharLiteralForChar() {\n\t\tassertEquals(\"'<INVALID>'\",\n\t\t\tCharSupport.getANTLRCharLiteralForChar(-1));\n\t\tassertEquals(\"'\\\\n'\",\n\t\t\tCharSupport.getANTLRCharLiteralForChar('\\n'));\n\t\tassertEquals(\"'\\\\\\\\'\",\n\t\t\tCharSupport.getANTLRCharLiteralForChar('\\\\'));\n\t\tassertEquals(\"'\\\\''\",\n\t\t\tCharSupport.getANTLRCharLiteralForChar('\\''));\n\t\tassertEquals(\"'b'\",\n\t\t\tCharSupport.getANTLRCharLiteralForChar('b'));\n\t\tassertEquals(\"'\\\\uFFFF'\",\n\t\t\tCharSupport.getANTLRCharLiteralForChar(0xFFFF));\n\t\tassertEquals(\"'\\\\u{10FFFF}'\",\n\t\t\tCharSupport.getANTLRCharLiteralForChar(0x10FFFF));\n\t}\n\n\t@Test\n\tpublic void testGetCharValueFromGrammarCharLiteral() {\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromGrammarCharLiteral(null));\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromGrammarCharLiteral(\"\"));\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromGrammarCharLiteral(\"b\"));\n\t\tassertEquals(111,\n\t\t\tCharSupport.getCharValueFromGrammarCharLiteral(\"foo\"));\n\t}\n\n\t@Test\n\tpublic void testGetStringFromGrammarStringLiteral() {\n\t\tassertNull(CharSupport\n\t\t\t.getStringFromGrammarStringLiteral(\"foo\\\\u{bbb\"));\n\t\tassertNull(CharSupport\n\t\t\t.getStringFromGrammarStringLiteral(\"foo\\\\u{[]bb\"));\n\t\tassertNull(CharSupport\n\t\t\t.getStringFromGrammarStringLiteral(\"foo\\\\u[]bb\"));\n\t\tassertNull(CharSupport\n\t\t\t.getStringFromGrammarStringLiteral(\"foo\\\\ubb\"));\n\n\t\tassertEquals(\"oo»b\", CharSupport\n\t\t\t.getStringFromGrammarStringLiteral(\"foo\\\\u{bb}bb\"));\n\t}\n\n\t@Test\n\tpublic void testGetCharValueFromCharInGrammarLiteral() {\n\t\tassertEquals(102,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"f\"));\n\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"\\' \"));\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"\\\\ \"));\n\t\tassertEquals(39,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"\\\\\\'\"));\n\t\tassertEquals(10,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"\\\\n\"));\n\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"foobar\"));\n\t\tassertEquals(4660,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"\\\\u1234\"));\n\t\tassertEquals(18,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"\\\\u{12}\"));\n\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"\\\\u{\"));\n\t\tassertEquals(-1,\n\t\t\tCharSupport.getCharValueFromCharInGrammarLiteral(\"foo\"));\n\t}\n\n\t@Test\n\tpublic void testParseHexValue() {\n\t\tassertEquals(-1, CharSupport.parseHexValue(\"foobar\", -1, 3));\n\t\tassertEquals(-1, CharSupport.parseHexValue(\"foobar\", 1, -1));\n\t\tassertEquals(-1, CharSupport.parseHexValue(\"foobar\", 1, 3));\n\t\tassertEquals(35, CharSupport.parseHexValue(\"123456\", 1, 3));\n\t}\n\n\t@Test\n\tpublic void testCapitalize() {\n\t\tassertEquals(\"Foo\", CharSupport.capitalize(\"foo\"));\n\t}\n\n\t@Test\n\tpublic void testGetIntervalSetEscapedString() {\n\t\tassertEquals(\"\",\n\t\t\tCharSupport.getIntervalSetEscapedString(new IntervalSet()));\n\t\tassertEquals(\"'\\\\u0000'\",\n\t\t\tCharSupport.getIntervalSetEscapedString(new IntervalSet(0)));\n\t\tassertEquals(\"'\\\\u0001'..'\\\\u0003'\",\n\t\t\tCharSupport.getIntervalSetEscapedString(new IntervalSet(3, 1, 2)));\n\t}\n\n\t@Test\n\tpublic void testGetRangeEscapedString() {\n\t\tassertEquals(\"'\\\\u0002'..'\\\\u0004'\",\n\t\t\tCharSupport.getRangeEscapedString(2, 4));\n\t\tassertEquals(\"'\\\\u0002'\",\n\t\t\tCharSupport.getRangeEscapedString(2, 2));\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestCodeGeneration.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.automata.ATNFactory;\nimport org.antlr.v4.automata.LexerATNFactory;\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.codegen.CodeGenerator;\nimport org.antlr.v4.semantics.SemanticPipeline;\nimport org.antlr.v4.test.runtime.ErrorQueue;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\nimport org.stringtemplate.v4.AutoIndentWriter;\nimport org.stringtemplate.v4.InstanceScope;\nimport org.stringtemplate.v4.Interpreter;\nimport org.stringtemplate.v4.ST;\nimport org.stringtemplate.v4.STGroup;\nimport org.stringtemplate.v4.STWriter;\nimport org.stringtemplate.v4.misc.ErrorManager;\nimport org.stringtemplate.v4.misc.ErrorType;\n\nimport java.io.IOException;\nimport java.io.StringWriter;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertFalse;\nimport static org.junit.jupiter.api.Assertions.assertNotEquals;\n\npublic class TestCodeGeneration {\n\t@Test public void testArgDecl() throws Exception { // should use template not string\n\t\t/*ErrorQueue equeue = */new ErrorQueue();\n\t\tString g =\n\t\t\t\t\"grammar T;\\n\" +\n\t\t\t\t\"a[int xyz] : 'a' ;\\n\";\n\t\tList<String> evals = getEvalInfoForString(g, \"int xyz\");\n\t\tSystem.out.println(evals);\n\t\tfor (int i = 0; i < evals.size(); i++) {\n\t\t\tString eval = evals.get(i);\n\t\t\tassertFalse(eval.startsWith(\"<pojo:\"), \"eval should not be POJO: \"+eval);\n\t\t}\n\t}\n\n\t@Test public void AssignTokenNamesToStringLiteralsInGeneratedParserRuleContexts() throws Exception {\n\t\tString g =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"root: 't1';\\n\" +\n\t\t\t\"Token: 't1';\";\n\t\tList<String> evals = getEvalInfoForString(g, \"() { return getToken(\");\n\t\tassertNotEquals(0, evals.size());\n\t}\n\n\t@Test public void AssignTokenNamesToStringLiteralArraysInGeneratedParserRuleContexts() throws Exception {\n\t\tString g =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\t\"root: 't1' 't1';\\n\" +\n\t\t\t\t\"Token: 't1';\";\n\t\tList<String> evals = getEvalInfoForString(g, \"() { return getTokens(\");\n\t\tassertNotEquals(0, evals.size());\n\t}\n\n\t/** Add tags around each attribute/template/value write */\n\tpublic static class DebugInterpreter extends Interpreter {\n\t\tList<String> evals = new ArrayList<String>();\n\t\tErrorManager myErrMgrCopy;\n\t\tint tab = 0;\n\t\tpublic DebugInterpreter(STGroup group, ErrorManager errMgr, boolean debug) {\n\t\t\tsuper(group, errMgr, debug);\n\t\t\tmyErrMgrCopy = errMgr;\n\t\t}\n\n\t\t@Override\n\t\tprotected int writeObject(STWriter out, InstanceScope scope, Object o, String[] options) {\n\t\t\tif ( o instanceof ST ) {\n\t\t\t\tString name = ((ST)o).getName();\n\t\t\t\tname = name.substring(1);\n\t\t\t\tif ( !name.startsWith(\"_sub\") ) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tout.write(\"<ST:\" + name + \">\");\n\t\t\t\t\t\tevals.add(\"<ST:\" + name + \">\");\n\t\t\t\t\t\tint r = super.writeObject(out, scope, o, options);\n\t\t\t\t\t\tout.write(\"</ST:\" + name + \">\");\n\t\t\t\t\t\tevals.add(\"</ST:\" + name + \">\");\n\t\t\t\t\t\treturn r;\n\t\t\t\t\t} catch (IOException ioe) {\n\t\t\t\t\t\tmyErrMgrCopy.IOError(scope.st, ErrorType.WRITE_IO_ERROR, ioe);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn super.writeObject(out, scope, o, options);\n\t\t}\n\n\t\t@Override\n\t\tprotected int writePOJO(STWriter out, InstanceScope scope, Object o, String[] options) throws IOException {\n\t\t\tClass<?> type = o.getClass();\n\t\t\tString name = type.getSimpleName();\n\t\t\tout.write(\"<pojo:\"+name+\">\"+o.toString()+\"</pojo:\"+name+\">\");\n\t\t\tevals.add(\"<pojo:\" + name + \">\" + o.toString() + \"</pojo:\" + name + \">\");\n\t\t\treturn super.writePOJO(out, scope, o, options);\n\t\t}\n\n\t\tpublic void indent(STWriter out) throws IOException {\n\t\t\tfor (int i=1; i<=tab; i++) {\n\t\t\t\tout.write(\"\\t\");\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List<String> getEvalInfoForString(String grammarString, String pattern) throws RecognitionException {\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tGrammar g = new Grammar(grammarString);\n\t\tList<String> evals = new ArrayList<String>();\n\t\tif ( g.ast!=null && !g.ast.hasErrors ) {\n\t\t\tSemanticPipeline sem = new SemanticPipeline(g);\n\t\t\tsem.process();\n\n\t\t\tATNFactory factory = new ParserATNFactory(g);\n\t\t\tif (g.isLexer()) factory = new LexerATNFactory((LexerGrammar) g);\n\t\t\tg.atn = factory.createATN();\n\n\t\t\tCodeGenerator gen = CodeGenerator.create(g);\n\t\t\tST outputFileST = gen.generateParser();\n\n//\t\t\tSTViz viz = outputFileST.inspect();\n//\t\t\ttry {\n//\t\t\t\tviz.waitForClose();\n//\t\t\t}\n//\t\t\tcatch (Exception e) {\n//\t\t\t\te.printStackTrace();\n//\t\t\t}\n\n\t\t\tboolean debug = false;\n\t\t\tDebugInterpreter interp =\n\t\t\t\t\tnew DebugInterpreter(outputFileST.groupThatCreatedThisInstance,\n\t\t\t\t\t\t\toutputFileST.impl.nativeGroup.errMgr,\n\t\t\t\t\t\t\tdebug);\n\t\t\tInstanceScope scope = new InstanceScope(null, outputFileST);\n\t\t\tStringWriter sw = new StringWriter();\n\t\t\tAutoIndentWriter out = new AutoIndentWriter(sw);\n\t\t\tinterp.exec(out, scope);\n\n\t\t\tfor (String e : interp.evals) {\n\t\t\t\tif (e.contains(pattern)) {\n\t\t\t\t\tevals.add(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( equeue.size()>0 ) {\n\t\t\tSystem.err.println(equeue.toString());\n\t\t}\n\t\treturn evals;\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestCommonTokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CommonToken;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.IntStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenFactory;\nimport org.antlr.v4.runtime.TokenSource;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.WritableToken;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\n\npublic class TestCommonTokenStream extends TestBufferedTokenStream {\n\t@Override\n\tprotected TokenStream createTokenStream(TokenSource src) {\n\t\treturn new CommonTokenStream(src);\n\t}\n\n\t@Test public void testOffChannel() throws Exception {\n        TokenSource lexer = // simulate input \" x =34  ;\\n\"\n            new TokenSource() {\n                int i = 0;\n                @SuppressWarnings(\"serial\")\n\t\t\t\tWritableToken[] tokens = {\n                    new CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}},\n                    new CommonToken(1,\"x\"),\n                    new CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}},\n                    new CommonToken(1,\"=\"),\n                    new CommonToken(1,\"34\"),\n                    new CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}},\n                    new CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}},\n                    new CommonToken(1,\";\"),\n                    new CommonToken(1,\"\\n\") {{channel = Lexer.HIDDEN;}},\n                    new CommonToken(Token.EOF,\"\")\n                };\n                @Override\n                public Token nextToken() {\n                    return tokens[i++];\n                }\n                @Override\n                public String getSourceName() { return \"test\"; }\n\t\t\t\t@Override\n\t\t\t\tpublic int getCharPositionInLine() {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic int getLine() {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic CharStream getInputStream() {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void setTokenFactory(TokenFactory<?> factory) {\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic TokenFactory<?> getTokenFactory() {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t};\n\n        CommonTokenStream tokens = new CommonTokenStream(lexer);\n\n        assertEquals(\"x\", tokens.LT(1).getText()); // must skip first off channel token\n        tokens.consume();\n        assertEquals(\"=\", tokens.LT(1).getText());\n        assertEquals(\"x\", tokens.LT(-1).getText());\n\n        tokens.consume();\n        assertEquals(\"34\", tokens.LT(1).getText());\n        assertEquals(\"=\", tokens.LT(-1).getText());\n\n        tokens.consume();\n        assertEquals(\";\", tokens.LT(1).getText());\n        assertEquals(\"34\", tokens.LT(-1).getText());\n\n        tokens.consume();\n        assertEquals(Token.EOF, tokens.LA(1));\n        assertEquals(\";\", tokens.LT(-1).getText());\n\n        assertEquals(\"34\", tokens.LT(-2).getText());\n        assertEquals(\"=\", tokens.LT(-3).getText());\n        assertEquals(\"x\", tokens.LT(-4).getText());\n    }\n\n\t@Test public void testFetchOffChannel() throws Exception {\n\t\tTokenSource lexer = // simulate input \" x =34  ; \\n\"\n\t\t                    // token indexes   01234 56789\n\t\t\tnew TokenSource() {\n\t\t\t\tint i = 0;\n\t\t\t\t@SuppressWarnings(\"serial\")\n\t\t\t\tWritableToken[] tokens = {\n\t\t\t\tnew CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}}, // 0\n\t\t\t\tnew CommonToken(1,\"x\"),\t\t\t\t\t\t\t\t// 1\n\t\t\t\tnew CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}},\t// 2\n\t\t\t\tnew CommonToken(1,\"=\"),\t\t\t\t\t\t\t\t// 3\n\t\t\t\tnew CommonToken(1,\"34\"),\t\t\t\t\t\t\t// 4\n\t\t\t\tnew CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}},\t// 5\n\t\t\t\tnew CommonToken(1,\" \") {{channel = Lexer.HIDDEN;}}, // 6\n\t\t\t\tnew CommonToken(1,\";\"),\t\t\t\t\t\t\t\t// 7\n\t\t\t\tnew CommonToken(1,\" \")  {{channel = Lexer.HIDDEN;}},// 8\n\t\t\t\tnew CommonToken(1,\"\\n\") {{channel = Lexer.HIDDEN;}},// 9\n\t\t\t\tnew CommonToken(Token.EOF,\"\")\t\t\t\t\t\t// 10\n\t\t\t\t};\n\t\t\t\t@Override\n\t\t\t\tpublic Token nextToken() {\n\t\t\t\t\treturn tokens[i++];\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic String getSourceName() { return \"test\"; }\n\t\t\t\t@Override\n\t\t\t\tpublic int getCharPositionInLine() {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic int getLine() {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic CharStream getInputStream() {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic void setTokenFactory(TokenFactory<?> factory) {\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic TokenFactory<?> getTokenFactory() {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t};\n\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\t\ttokens.fill();\n\t\tassertEquals(null, tokens.getHiddenTokensToLeft(0));\n\t\tassertEquals(null, tokens.getHiddenTokensToRight(0));\n\n\t\tassertEquals(\"[[@0,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToLeft(1).toString());\n\t\tassertEquals(\"[[@2,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToRight(1).toString());\n\n\t\tassertEquals(null, tokens.getHiddenTokensToLeft(2));\n\t\tassertEquals(null, tokens.getHiddenTokensToRight(2));\n\n\t\tassertEquals(\"[[@2,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToLeft(3).toString());\n\t\tassertEquals(null, tokens.getHiddenTokensToRight(3));\n\n\t\tassertEquals(null, tokens.getHiddenTokensToLeft(4));\n\t\tassertEquals(\"[[@5,0:0=' ',<1>,channel=1,0:-1], [@6,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToRight(4).toString());\n\n\t\tassertEquals(null, tokens.getHiddenTokensToLeft(5));\n\t\tassertEquals(\"[[@6,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToRight(5).toString());\n\n\t\tassertEquals(\"[[@5,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToLeft(6).toString());\n\t\tassertEquals(null, tokens.getHiddenTokensToRight(6));\n\n\t\tassertEquals(\"[[@5,0:0=' ',<1>,channel=1,0:-1], [@6,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToLeft(7).toString());\n\t\tassertEquals(\"[[@8,0:0=' ',<1>,channel=1,0:-1], [@9,0:0='\\\\n',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToRight(7).toString());\n\n\t\tassertEquals(null, tokens.getHiddenTokensToLeft(8));\n\t\tassertEquals(\"[[@9,0:0='\\\\n',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToRight(8).toString());\n\n\t\tassertEquals(\"[[@8,0:0=' ',<1>,channel=1,0:-1]]\",\n\t\t\t\t\t tokens.getHiddenTokensToLeft(9).toString());\n\t\tassertEquals(null, tokens.getHiddenTokensToRight(9));\n\t}\n\n\t@Test\n\tpublic void testSingleEOF() throws Exception {\n\t\tTokenSource lexer = new TokenSource() {\n\n\t\t\t@Override\n\t\t\tpublic Token nextToken() {\n\t\t\t\treturn new CommonToken(Token.EOF);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getLine() {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getCharPositionInLine() {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic CharStream getInputStream() {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String getSourceName() {\n\t\t\t\treturn IntStream.UNKNOWN_SOURCE_NAME;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic TokenFactory<?> getTokenFactory() {\n\t\t\t\tthrow new UnsupportedOperationException(\"Not supported yet.\");\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void setTokenFactory(TokenFactory<?> factory) {\n\t\t\t\tthrow new UnsupportedOperationException(\"Not supported yet.\");\n\t\t\t}\n\t\t};\n\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\t\ttokens.fill();\n\n\t\tassertEquals(Token.EOF, tokens.LA(1));\n\t\tassertEquals(0, tokens.index());\n\t\tassertEquals(1, tokens.size());\n\t}\n\n\t@Test\n\tpublic void testCannotConsumeEOF() {\n\t\tTokenSource lexer = new TokenSource() {\n\n\t\t\t@Override\n\t\t\tpublic Token nextToken() {\n\t\t\t\treturn new CommonToken(Token.EOF);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getLine() {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getCharPositionInLine() {\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic CharStream getInputStream() {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String getSourceName() {\n\t\t\t\treturn IntStream.UNKNOWN_SOURCE_NAME;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic TokenFactory<?> getTokenFactory() {\n\t\t\t\tthrow new UnsupportedOperationException(\"Not supported yet.\");\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void setTokenFactory(TokenFactory<?> factory) {\n\t\t\t\tthrow new UnsupportedOperationException(\"Not supported yet.\");\n\t\t\t}\n\t\t};\n\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexer);\n\t\ttokens.fill();\n\n\t\tassertEquals(Token.EOF, tokens.LA(1));\n\t\tassertEquals(0, tokens.index());\n\t\tassertEquals(1, tokens.size());\n\t\tassertThrows(IllegalStateException.class, tokens::consume);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestCompositeGrammars.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.antlr.v4.test.runtime.states.JavaCompiledState;\nimport org.antlr.v4.tool.ANTLRMessage;\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.GrammarSemanticsMessage;\n\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.io.TempDir;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Path;\nimport java.util.*;\n\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.PathSeparator;\nimport static org.antlr.v4.test.tool.ToolTestUtils.*;\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class TestCompositeGrammars {\n\tprotected boolean debug = false;\n\n\t@Test public void testImportFileLocationInSubdir(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"a : B {System.out.println(\\\"S.a\\\");} ;\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\tString subdir = tempDirPath + PathSeparator + \"sub\";\n\t\tFileUtils.mkdir(subdir);\n\t\twriteFile(subdir, \"S.g4\", slave);\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"s : a ;\\n\" +\n\t\t\t\"B : 'b' ;\" + // defines B from inherited token space\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\" ;\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", subdir);\n\t\tassertEquals(0, equeue.size());\n\t}\n\n\t// Test for https://github.com/antlr/antlr4/issues/1317\n\t@Test public void testImportSelfLoop(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import M;\\n\" +\n\t\t\t\"s : 'a' ;\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.size());\n\t}\n\n\t@Test public void testImportIntoLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"lexer grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"A : 'a';\\n\" +\n\t\t\t\"B : 'b';\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t    \"lexer grammar S;\\n\" +\n\t\t\t\"C : 'c';\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.errors.size());\n\t}\n\n\t@Test public void testImportModesIntoLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"lexer grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"A : 'a' -> pushMode(X);\\n\" +\n\t\t\t\"B : 'b';\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t\t\"lexer grammar S;\\n\" +\n\t\t\t\"D : 'd';\\n\" +\n\t\t\t\"mode X;\\n\" +\n\t\t\t\"C : 'c' -> popMode;\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.errors.size());\n\t}\n\n\t@Test public void testImportChannelsIntoLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"lexer grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"channels {CH_A, CH_B}\\n\" +\n\t\t\t\"A : 'a' -> channel(CH_A);\\n\" +\n\t\t\t\"B : 'b' -> channel(CH_B);\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t\t\"lexer grammar S;\\n\" +\n\t\t\t\"C : 'c';\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.errors.size());\n\t}\n\n\t@Test public void testImportMixedChannelsIntoLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"lexer grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"channels {CH_A, CH_B}\\n\" +\n\t\t\t\"A : 'a' -> channel(CH_A);\\n\" +\n\t\t\t\"B : 'b' -> channel(CH_B);\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t\t\"lexer grammar S;\\n\" +\n\t\t\t\"channels {CH_C}\\n\" +\n\t\t\t\"C : 'c' -> channel(CH_C);\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.errors.size());\n\t}\n\n\t@Test public void testImportClashingChannelsIntoLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"lexer grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"channels {CH_A, CH_B, CH_C}\\n\" +\n\t\t\t\"A : 'a' -> channel(CH_A);\\n\" +\n\t\t\t\"B : 'b' -> channel(CH_B);\\n\" +\n\t\t\t\"C : 'C' -> channel(CH_C);\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t\t\"lexer grammar S;\\n\" +\n\t\t\t\"channels {CH_C}\\n\" +\n\t\t\t\"C : 'c' -> channel(CH_C);\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.errors.size());\n\t}\n\n\t@Test public void testMergeModesIntoLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"lexer grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"A : 'a' -> pushMode(X);\\n\" +\n\t\t\t\"mode X;\\n\" +\n\t\t\t\"B : 'b';\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t\t\"lexer grammar S;\\n\" +\n\t\t\t\"D : 'd';\\n\" +\n\t\t\t\"mode X;\\n\" +\n\t\t\t\"C : 'c' -> popMode;\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.errors.size());\n\t}\n\n\t@Test public void testEmptyModesInLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"lexer grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"A : 'a';\\n\" +\n\t\t\t\"C : 'e';\\n\" +\n\t\t\t\"B : 'b';\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t\t\"lexer grammar S;\\n\" +\n\t\t\t\"D : 'd';\\n\" +\n\t\t\t\"mode X;\\n\" +\n\t\t\t\"C : 'c' -> popMode;\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(0, equeue.errors.size());\n\t}\n\n\t@Test public void testCombinedGrammarImportsModalLexerGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"A : 'a';\\n\" +\n\t\t\t\"B : 'b';\\n\" +\n\t\t\t\"r : A B;\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\n\t\tString slave =\n\t\t\t\"lexer grammar S;\\n\" +\n\t\t\t\"D : 'd';\\n\" +\n\t\t\t\"mode X;\\n\" +\n\t\t\t\"C : 'c' -> popMode;\\n\";\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tassertEquals(1, equeue.errors.size());\n\t\tANTLRMessage msg = equeue.errors.get(0);\n\t\tassertEquals(ErrorType.MODE_NOT_IN_LEXER, msg.getErrorType());\n\t\tassertEquals(\"X\", msg.getArgs()[0]);\n\t\tassertEquals(3, msg.line);\n\t\tassertEquals(5, msg.charPosition);\n\t\tassertEquals(\"M.g4\", new File(msg.fileName).getName());\n\t}\n\n\t@Test public void testDelegatesSeeSameTokenType(@TempDir Path tempDir) throws RecognitionException {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slaveS =\n\t\t\t\"parser grammar S;\\n\"+\n\t\t\t\"tokens { A, B, C }\\n\"+\n\t\t\t\"x : A ;\\n\";\n\t\tString slaveT =\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"tokens { C, B, A } // reverse order\\n\"+\n\t\t\t\"y : A ;\\n\";\n\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slaveS);\n\t\twriteFile(tempDirPath, \"T.g4\", slaveT);\n\n\t\tString master =\n\t\t\t\"// The lexer will create rules to match letters a, b, c.\\n\"+\n\t\t\t\"// The associated token types A, B, C must have the same value\\n\"+\n\t\t\t\"// and all import'd parsers.  Since ANTLR regenerates all imports\\n\"+\n\t\t\t\"// for use with the delegator M, it can generate the same token type\\n\"+\n\t\t\t\"// mapping in each parser:\\n\"+\n\t\t\t\"// public static final int C=6;\\n\"+\n\t\t\t\"// public static final int EOF=-1;\\n\"+\n\t\t\t\"// public static final int B=5;\\n\"+\n\t\t\t\"// public static final int WS=7;\\n\"+\n\t\t\t\"// public static final int A=4;\\n\"+\n\t\t\t\"grammar M;\\n\"+\n\t\t\t\"import S,T;\\n\"+\n\t\t\t\"s : x y ; // matches AA, which should be 'aa'\\n\"+\n\t\t\t\"B : 'b' ; // another order: B, A, C\\n\"+\n\t\t\t\"A : 'a' ;\\n\"+\n\t\t\t\"C : 'c' ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tGrammar g = new Grammar(tempDirPath+\"/M.g4\", master, equeue);\n\t\tString expectedTokenIDToTypeMap = \"{EOF=-1, B=1, A=2, C=3, WS=4}\";\n\t\tString expectedStringLiteralToTypeMap = \"{'a'=2, 'b'=1, 'c'=3}\";\n\t\tString expectedTypeToTokenList = \"[B, A, C, WS]\";\n\t\tassertEquals(expectedTokenIDToTypeMap, g.tokenNameToTypeMap.toString());\n\t\tassertEquals(expectedStringLiteralToTypeMap, sort(g.stringLiteralToTypeMap).toString());\n\t\tassertEquals(expectedTypeToTokenList, realElements(g.typeToTokenList).toString());\n\t\tassertEquals(0, equeue.errors.size(), \"unexpected errors: \"+equeue);\n\t}\n\n\t@Test public void testErrorInImportedGetsRightFilename(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"a : 'a' | c;\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\";\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-lib\", tempDirPath);\n\t\tANTLRMessage msg = equeue.errors.get(0);\n\t\tassertEquals(ErrorType.UNDEFINED_RULE_REF, msg.getErrorType());\n\t\tassertEquals(\"c\", msg.getArgs()[0]);\n\t\tassertEquals(2, msg.line);\n\t\tassertEquals(10, msg.charPosition);\n\t\tassertEquals(\"S.g4\", new File(msg.fileName).getName());\n\t}\n\n\t@Test public void testImportFileNotSearchedForInOutputDir(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"a : B {System.out.println(\\\"S.a\\\");} ;\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\tString outdir = tempDirPath + \"/out\";\n\t\tFileUtils.mkdir(outdir);\n\t\twriteFile(outdir, \"S.g4\", slave);\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"s : a ;\\n\" +\n\t\t\t\"B : 'b' ;\" + // defines B from inherited token space\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\" ;\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-o\", outdir);\n\t\tassertEquals(ErrorType.CANNOT_FIND_IMPORTED_GRAMMAR, equeue.errors.get(0).getErrorType());\n\t}\n\n\t@Test public void testOutputDirShouldNotEffectImports(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"a : B {System.out.println(\\\"S.a\\\");} ;\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\tString subdir = tempDirPath + \"/sub\";\n\t\tFileUtils.mkdir(subdir);\n\t\twriteFile(subdir, \"S.g4\", slave);\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"s : a ;\\n\" +\n\t\t\t\"B : 'b' ;\" + // defines B from inherited token space\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\" ;\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tString outdir = tempDirPath + \"/out\";\n\t\tFileUtils.mkdir(outdir);\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", false, \"-o\", outdir, \"-lib\", subdir);\n\t\tassertEquals(0, equeue.size());\n\t}\n\n\t@Test public void testTokensFileInOutputDirAndImportFileInSubdir(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"a : B {System.out.println(\\\"S.a\\\");} ;\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\tString subdir = tempDirPath + \"/sub\";\n\t\tFileUtils.mkdir(subdir);\n\t\twriteFile(subdir, \"S.g4\", slave);\n\t\tString parser =\n\t\t\t\"parser grammar MParser;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"options {tokenVocab=MLexer;}\\n\" +\n\t\t\t\"s : a ;\\n\";\n\t\twriteFile(tempDirPath, \"MParser.g4\", parser);\n\t\tString lexer =\n\t\t\t\"lexer grammar MLexer;\\n\" +\n\t\t\t\"B : 'b' ;\" + // defines B from inherited token space\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\" ;\n\t\twriteFile(tempDirPath, \"MLexer.g4\", lexer);\n\t\tString outdir = tempDirPath + \"/out\";\n\t\tFileUtils.mkdir(outdir);\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"MLexer.g4\", false, \"-o\", outdir);\n\t\tassertEquals(0, equeue.size());\n\t\tequeue = Generator.antlrOnString(tempDirPath, \"Java\", \"MParser.g4\", false, \"-o\", outdir, \"-lib\", subdir);\n\t\tassertEquals(0, equeue.size());\n\t}\n\n\t@Test public void testImportedTokenVocabIgnoredWithWarning(@TempDir Path tempDir) throws RecognitionException {\n\t\tString tempDirPath = tempDir.toString();\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"options {tokenVocab=whatever;}\\n\" +\n\t\t\t\"tokens { A }\\n\" +\n\t\t\t\"x : A {System.out.println(\\\"S.x\\\");} ;\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"s : x ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\" ;\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tGrammar g = new Grammar(tempDirPath+\"/M.g4\", master, equeue);\n\n\t\tObject expectedArg = \"S\";\n\t\tErrorType expectedMsgID = ErrorType.OPTIONS_IN_DELEGATE;\n\t\tGrammarSemanticsMessage expectedMessage =\n\t\t\tnew GrammarSemanticsMessage(expectedMsgID, g.fileName, null, expectedArg);\n\t\tcheckGrammarSemanticsWarning(equeue, expectedMessage);\n\n\t\tassertEquals(0, equeue.errors.size(), \"unexpected errors: \"+equeue);\n\t\tassertEquals(1, equeue.warnings.size(), \"unexpected warnings: \"+equeue);\n\t}\n\n\t@Test public void testSyntaxErrorsInImportsNotThrownOut(@TempDir Path tempDir) throws RecognitionException {\n\t\tString tempDirPath = tempDir.toString();\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"options {toke\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"s : x ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\" ;\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\t/*Grammar g =*/ new Grammar(tempDirPath+\"/M.g4\", master, equeue);\n\n\t\tassertEquals(ErrorType.SYNTAX_ERROR, equeue.errors.get(0).getErrorType());\n\t}\n\n\t// Make sure that M can import S that imports T.\n\t@Test public void test3LevelImport(@TempDir Path tempDir) throws RecognitionException {\n\t\tString tempDirPath = tempDir.toString();\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tString slave =\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"a : T ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"T.g4\", slave);\n\t\tString slave2 =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"import T;\\n\" +\n\t\t\t\"a : S ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slave2);\n\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"a : M ;\\n\" ;\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tGrammar g = new Grammar(tempDirPath+\"/M.g4\", master, equeue);\n\n\t\tString expectedTokenIDToTypeMap = \"{EOF=-1, M=1}\"; // S and T aren't imported; overridden\n\t\tString expectedStringLiteralToTypeMap = \"{}\";\n\t\tString expectedTypeToTokenList = \"[M]\";\n\n\t\tassertEquals(expectedTokenIDToTypeMap,\n\t\t\t\t\t g.tokenNameToTypeMap.toString());\n\t\tassertEquals(expectedStringLiteralToTypeMap, g.stringLiteralToTypeMap.toString());\n\t\tassertEquals(expectedTypeToTokenList,\n\t\t\t\t\t realElements(g.typeToTokenList).toString());\n\n\t\tassertEquals(0, equeue.errors.size(), \"unexpected errors: \"+equeue);\n\t\tassertTrue(compile(\"M.g4\", master, \"MParser\", \"a\", tempDir));\n\t}\n\n\t@Test public void testBigTreeOfImports(@TempDir Path tempDir) throws RecognitionException {\n\t\tString tempDirPath = tempDir.toString();\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tString slave =\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"tokens{T}\\n\" +\n\t\t\t\"x : T ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"T.g4\", slave);\n\t\tslave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"import T;\\n\" +\n\t\t\t\"tokens{S}\\n\" +\n\t\t\t\"y : S ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\n\t\tslave =\n\t\t\t\"parser grammar C;\\n\" +\n\t\t\t\"tokens{C}\\n\" +\n\t\t\t\"i : C ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"C.g4\", slave);\n\t\tslave =\n\t\t\t\"parser grammar B;\\n\" +\n\t\t\t\"tokens{B}\\n\" +\n\t\t\t\"j : B ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"B.g4\", slave);\n\t\tslave =\n\t\t\t\"parser grammar A;\\n\" +\n\t\t\t\"import B,C;\\n\" +\n\t\t\t\"tokens{A}\\n\" +\n\t\t\t\"k : A ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"A.g4\", slave);\n\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S,A;\\n\" +\n\t\t\t\"tokens{M}\\n\" +\n\t\t\t\"a : M ;\\n\" ;\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tGrammar g = new Grammar(tempDirPath+\"/M.g4\", master, equeue);\n\n\t\tassertEquals(\"[]\", equeue.errors.toString());\n\t\tassertEquals(\"[]\", equeue.warnings.toString());\n\t\tString expectedTokenIDToTypeMap = \"{EOF=-1, M=1, S=2, T=3, A=4, B=5, C=6}\";\n\t\tString expectedStringLiteralToTypeMap = \"{}\";\n\t\tString expectedTypeToTokenList = \"[M, S, T, A, B, C]\";\n\n\t\tassertEquals(expectedTokenIDToTypeMap,\n\t\t\t\t\t g.tokenNameToTypeMap.toString());\n\t\tassertEquals(expectedStringLiteralToTypeMap, g.stringLiteralToTypeMap.toString());\n\t\tassertEquals(expectedTypeToTokenList,\n\t\t\t\t\t realElements(g.typeToTokenList).toString());\n\t\tassertTrue(compile(\"M.g4\", master, \"MParser\", \"a\", tempDir));\n\t}\n\n\t@Test public void testRulesVisibleThroughMultilevelImport(@TempDir Path tempDir) throws RecognitionException {\n\t\tString tempDirPath = tempDir.toString();\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tString slave =\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"x : T ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"T.g4\", slave);\n\t\tString slave2 =\n\t\t\t\"parser grammar S;\\n\" + // A, B, C token type order\n\t\t\t\"import T;\\n\" +\n\t\t\t\"a : S ;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slave2);\n\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"a : M x ;\\n\" ; // x MUST BE VISIBLE TO M\n\t\twriteFile(tempDirPath, \"M.g4\", master);\n\t\tGrammar g = new Grammar(tempDirPath+\"/M.g4\", master, equeue);\n\n\t\tString expectedTokenIDToTypeMap = \"{EOF=-1, M=1, T=2}\";\n\t\tString expectedStringLiteralToTypeMap = \"{}\";\n\t\tString expectedTypeToTokenList = \"[M, T]\";\n\n\t\tassertEquals(expectedTokenIDToTypeMap,\n\t\t\t\t\t g.tokenNameToTypeMap.toString());\n\t\tassertEquals(expectedStringLiteralToTypeMap, g.stringLiteralToTypeMap.toString());\n\t\tassertEquals(expectedTypeToTokenList,\n\t\t\t\t\t realElements(g.typeToTokenList).toString());\n\n\t\tassertEquals(0, equeue.errors.size(), \"unexpected errors: \"+equeue);\n\t}\n\n\t@Test public void testNestedComposite(@TempDir Path tempDir) throws RecognitionException {\n\t\tString tempDirPath = tempDir.toString();\n\t\t// Wasn't compiling. http://www.antlr.org/jira/browse/ANTLR-438\n\t\tErrorQueue equeue = new ErrorQueue();\n\t\tString gstr =\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"T1: '1';\\n\" +\n\t\t\t\"T2: '2';\\n\" +\n\t\t\t\"T3: '3';\\n\" +\n\t\t\t\"T4: '4';\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"L.g4\", gstr);\n\t\tgstr =\n\t\t\t\"parser grammar G1;\\n\" +\n\t\t\t\"s: a | b;\\n\" +\n\t\t\t\"a: T1;\\n\" +\n\t\t\t\"b: T2;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"G1.g4\", gstr);\n\n\t\tgstr =\n\t\t\t\"parser grammar G2;\\n\" +\n\t\t\t\"import G1;\\n\" +\n\t\t\t\"a: T3;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"G2.g4\", gstr);\n\t\tString G3str =\n\t\t\t\"grammar G3;\\n\" +\n\t\t\t\"import G2;\\n\" +\n\t\t\t\"b: T4;\\n\" ;\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"G3.g4\", G3str);\n\n\t\tGrammar g = new Grammar(tempDirPath+\"/G3.g4\", G3str, equeue);\n\n\t\tString expectedTokenIDToTypeMap = \"{EOF=-1, T4=1, T3=2}\";\n\t\tString expectedStringLiteralToTypeMap = \"{}\";\n\t\tString expectedTypeToTokenList = \"[T4, T3]\";\n\n\t\tassertEquals(expectedTokenIDToTypeMap,\n\t\t\t\t\t g.tokenNameToTypeMap.toString());\n\t\tassertEquals(expectedStringLiteralToTypeMap, g.stringLiteralToTypeMap.toString());\n\t\tassertEquals(expectedTypeToTokenList,\n\t\t\t\t\t realElements(g.typeToTokenList).toString());\n\n\t\tassertEquals(0, equeue.errors.size(), \"unexpected errors: \"+equeue);\n\n\t\tassertTrue(compile(\"G3.g4\", G3str, \"G3Parser\", \"b\", tempDir));\n\t}\n\n\t@Test public void testHeadersPropogatedCorrectlyToImportedGrammars(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave =\n\t\t\t\"parser grammar S;\\n\" +\n\t\t\t\"a : B {System.out.print(\\\"S.a\\\");} ;\\n\";\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"S.g4\", slave);\n\t\tString master =\n\t\t\t\"grammar M;\\n\" +\n\t\t\t\"import S;\\n\" +\n\t\t\t\"@header{package mypackage;}\\n\" +\n\t\t\t\"s : a ;\\n\" +\n\t\t\t\"B : 'b' ;\" + // defines B from inherited token space\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\" ;\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"M.g4\", master, false);\n\t\tint expecting = 0; // should be ok\n\t\tassertEquals(expecting, equeue.errors.size());\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#670 \"exception when importing\n\t * grammar\".  I think this one always worked but I found that a different\n\t * Java grammar caused an error and so I made the testImportLeftRecursiveGrammar() test below.\n\t * https://github.com/antlr/antlr4/issues/670\n\t */\n\t// TODO: migrate to test framework\n\t@Test\n\tpublic void testImportLargeGrammar(@TempDir Path tempDir) throws IOException {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave = load(\"Java.g4\");\n\t\tString master =\n\t\t\t\"grammar NewJava;\\n\" +\n\t\t\t\"import Java;\\n\";\n\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"Java.g4\", slave);\n\t\tExecutedState executedState = execParser(\"NewJava.g4\", master,\n\t\t\t\t\"NewJavaParser\", \"NewJavaLexer\", \"compilationUnit\", \"package Foo;\",\n\t\t\t\tdebug, tempDir);\n\t\tassertEquals(\"\", executedState.output);\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#670 \"exception when importing\n\t * grammar\".\n\t * https://github.com/antlr/antlr4/issues/670\n\t */\n\t// TODO: migrate to test framework\n\t@Test\n\tpublic void testImportLeftRecursiveGrammar(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString slave =\n\t\t\t\"grammar Java;\\n\" +\n\t\t\t\"e : '(' e ')'\\n\" +\n\t\t\t\"  | e '=' e\\n\" +\n\t\t\t\"  | ID\\n\" +\n\t\t\t\"  ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\";\n\t\tString master =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"import Java;\\n\" +\n\t\t\t\"s : e ;\\n\";\n\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"Java.g4\", slave);\n\t\tExecutedState executedState = execParser(\n\t\t\t\t\"T.g4\", master, \"TParser\", \"TLexer\", \"s\", \"a=b\", debug,\n\t\t\t\ttempDir);\n\t\tassertEquals(\"\", executedState.output);\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n\n\t// ISSUE: https://github.com/antlr/antlr4/issues/2296\n\t@Test\n\tpublic void testCircularGrammarInclusion(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString g1 =\n\t\t\t\t\"grammar G1;\\n\" +\n\t\t\t\t\"import  G2;\\n\" +\n\t\t\t\t\"r : 'R1';\";\n\n\t\tString g2 =\n\t\t\t\t\"grammar G2;\\n\" +\n\t\t\t\t\"import  G1;\\n\" +\n\t\t\t\t\"r : 'R2';\";\n\n\t\tFileUtils.mkdir(tempDirPath);\n\t\twriteFile(tempDirPath, \"G1.g4\", g1);\n\t\tExecutedState executedState = execParser(\"G2.g4\", g2, \"G2Parser\", \"G2Lexer\", \"r\", \"R2\", debug, tempDir);\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n\n\tprivate static void checkGrammarSemanticsWarning(ErrorQueue equeue, GrammarSemanticsMessage expectedMessage) {\n\t\tANTLRMessage foundMsg = null;\n\t\tfor (int i = 0; i < equeue.warnings.size(); i++) {\n\t\t\tANTLRMessage m = equeue.warnings.get(i);\n\t\t\tif (m.getErrorType()==expectedMessage.getErrorType() ) {\n\t\t\t\tfoundMsg = m;\n\t\t\t}\n\t\t}\n\t\tassertNotNull(foundMsg, \"no error; \"+expectedMessage.getErrorType()+\" expected\");\n\t\tassertTrue(foundMsg instanceof GrammarSemanticsMessage, \"error is not a GrammarSemanticsMessage\");\n\t\tassertEquals(Arrays.toString(expectedMessage.getArgs()), Arrays.toString(foundMsg.getArgs()));\n\t\tif ( equeue.size()!=1 ) {\n\t\t\tSystem.err.println(equeue);\n\t\t}\n\t}\n\n\tprivate static boolean compile(String grammarFileName, String grammarStr, String parserName, String startRuleName,\n\t\t\t\t\t\t\tPath tempDirPath\n\t) {\n\t\tRunOptions runOptions = createOptionsForJavaToolTests(grammarFileName, grammarStr, parserName, null,\n\t\t\t\tfalse, false, startRuleName, null,\n\t\t\t\tfalse, false, Stage.Compile);\n\t\ttry (JavaRunner runner = new JavaRunner(tempDirPath, false)) {\n\t\t\tJavaCompiledState compiledState = (JavaCompiledState) runner.run(runOptions);\n\t\t\treturn !compiledState.containsErrors();\n\t\t}\n\t}\n\n\tpublic static <K extends Comparable<? super K>,V> LinkedHashMap<K,V> sort(Map<K,V> data) {\n\t\tLinkedHashMap<K,V> dup = new LinkedHashMap<K, V>();\n\t\tList<K> keys = new ArrayList<K>(data.keySet());\n\t\tCollections.sort(keys);\n\t\tfor (K k : keys) {\n\t\t\tdup.put(k, data.get(k));\n\t\t}\n\t\treturn dup;\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestDollarParser.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.execParser;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\npublic class TestDollarParser {\n\t@Test\n\tpublic void testSimpleCall() {\n\t\tString grammar = \"grammar T;\\n\" +\n                      \"a : ID  { outStream.println(new java.io.File($parser.getSourceName()).getAbsolutePath()); }\\n\" +\n                      \"  ;\\n\" +\n                      \"ID : 'a'..'z'+ ;\\n\";\n\t\tExecutedState executedState = execParser(\"T.g4\", grammar, \"TParser\", \"TLexer\", \"a\", \"x\", true);\n\t\tassertTrue(executedState.output.contains(\"input\"));\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestErrorSets.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.tool.ErrorType;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.testErrors;\n\n/** Test errors with the set stuff in lexer and parser */\npublic class TestErrorSets {\n\tprotected boolean debug = false;\n\n\t@Test public void testNotCharSetWithRuleRef() throws Exception {\n\t\t// might be a useful feature to add someday\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"a : A {System.out.println($A.text);} ;\\n\" +\n\t\t\t\"A : ~('a'|B) ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\",\n\t\t\t\"error(\" + ErrorType.UNSUPPORTED_REFERENCE_IN_LEXER_SET.code + \"): T.g4:3:10: rule reference B is not currently supported in a set\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testNotCharSetWithString() throws Exception {\n\t\t// might be a useful feature to add someday\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"a : A {System.out.println($A.text);} ;\\n\" +\n\t\t\t\"A : ~('a'|'aa') ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\",\n\t\t\t\"error(\" + ErrorType.INVALID_LITERAL_IN_LEXER_SET.code + \"): T.g4:3:10: multi-character literals are not allowed in lexer sets: 'aa'\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestEscapeSequenceParsing.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.misc.EscapeSequenceParsing;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.misc.EscapeSequenceParsing.Result;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestEscapeSequenceParsing {\n\t@Test\n\tpublic void testParseEmpty() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseJustBackslash() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseInvalidEscape() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\z\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseNewline() {\n\t\tassertEquals(\n\t\t\t\tnew Result(Result.Type.CODE_POINT, '\\n', IntervalSet.EMPTY_SET, 0,2),\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\n\", 0));\n\t}\n\n\t@Test\n\tpublic void testParseTab() {\n\t\tassertEquals(\n\t\t\t\tnew Result(Result.Type.CODE_POINT, '\\t', IntervalSet.EMPTY_SET, 0,2),\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\t\", 0));\n\t}\n\n\t@Test\n\tpublic void testParseUnicodeTooShort() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\uABC\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodeBMP() {\n\t\tassertEquals(\n\t\t\t\tnew Result(Result.Type.CODE_POINT, 0xABCD, IntervalSet.EMPTY_SET, 0,6),\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\uABCD\", 0));\n\t}\n\n\t@Test\n\tpublic void testParseUnicodeSMPTooShort() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\u{}\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodeSMPMissingCloseBrace() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\u{12345\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodeTooBig() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\u{110000}\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodeSMP() {\n\t\tassertEquals(\n\t\t\t\tnew Result(Result.Type.CODE_POINT, 0x10ABCD, IntervalSet.EMPTY_SET, 0,10),\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\u{10ABCD}\", 0));\n\t}\n\n\t@Test\n\tpublic void testParseUnicodePropertyTooShort() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\p{}\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodePropertyMissingCloseBrace() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\p{1234\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodeProperty() {\n\t\tassertEquals(\n\t\t\t\tnew Result(Result.Type.PROPERTY, -1, IntervalSet.of(66560, 66639), 0,11),\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\p{Deseret}\", 0));\n\t}\n\n\t@Test\n\tpublic void testParseUnicodePropertyInvertedTooShort() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\P{}\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodePropertyInvertedMissingCloseBrace() {\n\t\tassertEquals(\n\t\t\t\tEscapeSequenceParsing.Result.Type.INVALID,\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\P{Deseret\", 0).type);\n\t}\n\n\t@Test\n\tpublic void testParseUnicodePropertyInverted() {\n\t\tIntervalSet expected = IntervalSet.of(0, 66559);\n\t\texpected.add(66640, Character.MAX_CODE_POINT);\n\t\tassertEquals(\n\t\t\t\tnew Result(Result.Type.PROPERTY, -1, expected, 0, 11),\n\t\t\t\tEscapeSequenceParsing.parseEscape(\"\\\\P{Deseret}\", 0));\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestFastQueue.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.misc.FastQueue;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.NoSuchElementException;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestFastQueue {\n    @Test public void testQueueNoRemove() throws Exception {\n        FastQueue<String> q = new FastQueue<String>();\n        q.add(\"a\");\n        q.add(\"b\");\n        q.add(\"c\");\n        q.add(\"d\");\n        q.add(\"e\");\n        String expecting = \"a b c d e\";\n        String found = q.toString();\n        assertEquals(expecting, found);\n    }\n\n    @Test public void testQueueThenRemoveAll() throws Exception {\n        FastQueue<String> q = new FastQueue<String>();\n        q.add(\"a\");\n        q.add(\"b\");\n        q.add(\"c\");\n        q.add(\"d\");\n        q.add(\"e\");\n        StringBuilder buf = new StringBuilder();\n        while ( q.size()>0 ) {\n            String o = q.remove();\n            buf.append(o);\n            if ( q.size()>0 ) buf.append(\" \");\n        }\n        assertEquals(0, q.size(), \"queue should be empty\");\n        String expecting = \"a b c d e\";\n        String found = buf.toString();\n        assertEquals(expecting, found);\n    }\n\n    @Test public void testQueueThenRemoveOneByOne() throws Exception {\n        StringBuilder buf = new StringBuilder();\n        FastQueue<String> q = new FastQueue<String>();\n        q.add(\"a\");\n        buf.append(q.remove());\n        q.add(\"b\");\n        buf.append(q.remove());\n        q.add(\"c\");\n        buf.append(q.remove());\n        q.add(\"d\");\n        buf.append(q.remove());\n        q.add(\"e\");\n        buf.append(q.remove());\n        assertEquals(0, q.size(), \"queue should be empty\");\n        String expecting = \"abcde\";\n        String found = buf.toString();\n        assertEquals(expecting, found);\n    }\n\n    // E r r o r s\n\n    @Test public void testGetFromEmptyQueue() throws Exception {\n        FastQueue<String> q = new FastQueue<String>();\n        String msg = null;\n        try { q.remove(); }\n        catch (NoSuchElementException nsee) {\n            msg = nsee.getMessage();\n        }\n        String expecting = \"queue index 0 > last index -1\";\n        String found = msg;\n        assertEquals(expecting, found);\n    }\n\n    @Test public void testGetFromEmptyQueueAfterSomeAdds() throws Exception {\n        FastQueue<String> q = new FastQueue<String>();\n        q.add(\"a\");\n        q.add(\"b\");\n        q.remove();\n        q.remove();\n        String msg = null;\n        try { q.remove(); }\n        catch (NoSuchElementException nsee) {\n            msg = nsee.getMessage();\n        }\n        String expecting = \"queue index 0 > last index -1\";\n        String found = msg;\n        assertEquals(expecting, found);\n    }\n\n    @Test public void testGetFromEmptyQueueAfterClear() throws Exception {\n        FastQueue<String> q = new FastQueue<String>();\n        q.add(\"a\");\n        q.add(\"b\");\n        q.clear();\n        String msg = null;\n        try { q.remove(); }\n        catch (NoSuchElementException nsee) {\n            msg = nsee.getMessage();\n        }\n        String expecting = \"queue index 0 > last index -1\";\n        String found = msg;\n        assertEquals(expecting, found);\n    }\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestGrammarParserInterpreter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.gui.Trees;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.InterpreterRuleContext;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.GrammarParserInterpreter;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/** Tests to ensure GrammarParserInterpreter subclass of ParserInterpreter\n *  hasn't messed anything up.\n */\npublic class TestGrammarParserInterpreter {\n\tpublic static final String lexerText = \"lexer grammar L;\\n\" +\n\t\t\t\t\t\t\t\t\t\t   \"PLUS : '+' ;\\n\" +\n\t\t\t\t\t\t\t\t\t\t   \"MULT : '*' ;\\n\" +\n\t\t\t\t\t\t\t\t\t\t   \"ID : [a-z]+ ;\\n\" +\n\t\t\t\t\t\t\t\t\t\t   \"INT : [0-9]+ ;\\n\" +\n\t\t\t\t\t\t\t\t\t\t   \"WS : [ \\\\r\\\\t\\\\n]+ ;\\n\";\n\n\t@Test\n\tpublic void testAlts() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : ID\\n\"+\n\t\t\t\"  | INT{;}\\n\"+\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\t\ttestInterp(lg, g, \"s\", \"a\",\t\t\"(s:1 a)\");\n\t\ttestInterp(lg, g, \"s\", \"3\", \t\"(s:2 3)\");\n\t}\n\n\t@Test\n\tpublic void testAltsAsSet() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : ID\\n\"+\n\t\t\t\"  | INT\\n\"+\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\t\ttestInterp(lg, g, \"s\", \"a\",\t\t\"(s:1 a)\");\n\t\ttestInterp(lg, g, \"s\", \"3\", \t\"(s:1 3)\");\n\t}\n\n\t@Test\n\tpublic void testAltsWithLabels() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : ID  # foo\\n\" +\n\t\t\t\"  | INT # bar\\n\" +\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\t\t// it won't show the labels here because my simple node text provider above just shows the alternative\n\t\ttestInterp(lg, g, \"s\", \"a\",\t\t\"(s:1 a)\");\n\t\ttestInterp(lg, g, \"s\", \"3\", \t\"(s:2 3)\");\n\t}\n\n\t@Test\n\tpublic void testOneAlt() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : ID\\n\"+\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\t\ttestInterp(lg, g, \"s\", \"a\",\t\t\"(s:1 a)\");\n\t}\n\n\n\t@Test\n\tpublic void testLeftRecursionWithMultiplePrimaryAndRecursiveOps() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e EOF ;\\n\" +\n\t\t\t\"e : e MULT e\\n\" +\n\t\t\t\"  | e PLUS e\\n\" +\n\t\t\t\"  | INT\\n\" +\n\t\t\t\"  | ID\\n\" +\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"a\",\t\t\"(s:1 (e:4 a) <EOF>)\");\n\t\ttestInterp(lg, g, \"e\", \"a\",\t\t\"(e:4 a)\");\n\t\ttestInterp(lg, g, \"e\", \"34\",\t\"(e:3 34)\");\n\t\ttestInterp(lg, g, \"e\", \"a+1\",\t\"(e:2 (e:4 a) + (e:3 1))\");\n\t\ttestInterp(lg, g, \"e\", \"1+2*a\",\t\"(e:2 (e:3 1) + (e:1 (e:3 2) * (e:4 a)))\");\n\t}\n\n\tInterpreterRuleContext testInterp(LexerGrammar lg, Grammar g,\n\t                                  String startRule, String input,\n\t                                  String expectedParseTree)\n\t{\n\t\tLexerInterpreter lexEngine = lg.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\tGrammarParserInterpreter parser = g.createGrammarParserInterpreter(tokens);\n\t\tParseTree t = parser.parse(g.rules.get(startRule).index);\n\t\tInterpreterTreeTextProvider nodeTextProvider = new InterpreterTreeTextProvider(g.getRuleNames());\n\t\tString treeStr = Trees.toStringTree(t, nodeTextProvider);\n//\t\tSystem.out.println(\"parse tree: \"+treeStr);\n\t\tassertEquals(expectedParseTree, treeStr);\n\t\treturn (InterpreterRuleContext)t;\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestGraphNodes.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.atn.ArrayPredictionContext;\nimport org.antlr.v4.runtime.atn.EmptyPredictionContext;\nimport org.antlr.v4.runtime.atn.PredictionContext;\nimport org.antlr.v4.runtime.atn.SingletonPredictionContext;\nimport org.junit.jupiter.api.Disabled;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.ArrayDeque;\nimport java.util.Deque;\nimport java.util.IdentityHashMap;\nimport java.util.Map;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestGraphNodes {\n\tpublic boolean rootIsWildcard() { return true; }\n\tpublic boolean fullCtx() { return false; }\n\n\t@Test public void test_$_$() {\n\t\tPredictionContext r = PredictionContext.merge(\n\t\t\t\tEmptyPredictionContext.Instance, EmptyPredictionContext.Instance, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"*\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_$_$_fullctx() {\n\t\tPredictionContext r = PredictionContext.merge(\n\t\t\t\tEmptyPredictionContext.Instance, EmptyPredictionContext.Instance, fullCtx(), null);\n//\t\tSystem.out.println(toDOTString(r, fullCtx()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"$\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, fullCtx()));\n\t}\n\n\t@Test public void test_x_$() {\n\t\tPredictionContext r = PredictionContext.merge(x(), EmptyPredictionContext.Instance, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"*\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_x_$_fullctx() {\n\t\tPredictionContext r = PredictionContext.merge(x(), EmptyPredictionContext.Instance, fullCtx(), null);\n//\t\tSystem.out.println(toDOTString(r, fullCtx()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>$\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"$\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, fullCtx()));\n\t}\n\n\t@Test public void test_$_x() {\n\t\tPredictionContext r = PredictionContext.merge(EmptyPredictionContext.Instance, x(), rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"*\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_$_x_fullctx() {\n\t\tPredictionContext r = PredictionContext.merge(EmptyPredictionContext.Instance, x(), fullCtx(), null);\n//\t\tSystem.out.println(toDOTString(r, fullCtx()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>$\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"$\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, fullCtx()));\n\t}\n\n\t@Test public void test_a_a() {\n\t\tPredictionContext r = PredictionContext.merge(a(), a(), rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_a$_ax() {\n\t\tPredictionContext a1 = a();\n\t\tPredictionContext x = x();\n\t\tPredictionContext a2 = createSingleton(x, 1);\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_a$_ax_fullctx() {\n\t\tPredictionContext a1 = a();\n\t\tPredictionContext x = x();\n\t\tPredictionContext a2 = createSingleton(x, 1);\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, fullCtx(), null);\n//\t\tSystem.out.println(toDOTString(r, fullCtx()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[shape=record, label=\\\"<p0>|<p1>$\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"$\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s1:p0->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, fullCtx()));\n\t}\n\n\t@Test public void test_ax$_a$() {\n\t\tPredictionContext x = x();\n\t\tPredictionContext a1 = createSingleton(x, 1);\n\t\tPredictionContext a2 = a();\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_aa$_a$_$_fullCtx() {\n\t\tPredictionContext empty = EmptyPredictionContext.Instance;\n\t\tPredictionContext child1 = createSingleton(empty, 8);\n\t\tPredictionContext right = PredictionContext.merge(empty, child1, false, null);\n\t\tPredictionContext left = createSingleton(right, 8);\n\t\tPredictionContext merged = PredictionContext.merge(left, right, false, null);\n\t\tString actual = toDOTString(merged, false);\n//\t\tSystem.out.println(actual);\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>$\\\"];\\n\" +\n\t\t\t\"  s1[shape=record, label=\\\"<p0>|<p1>$\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"$\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"8\\\"];\\n\" +\n\t\t\t\"  s1:p0->s2[label=\\\"8\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, actual);\n\t}\n\n\t@Test public void test_ax$_a$_fullctx() {\n\t\tPredictionContext x = x();\n\t\tPredictionContext a1 = createSingleton(x, 1);\n\t\tPredictionContext a2 = a();\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, fullCtx(), null);\n//\t\tSystem.out.println(toDOTString(r, fullCtx()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[shape=record, label=\\\"<p0>|<p1>$\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"$\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s1:p0->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, fullCtx()));\n\t}\n\n\t@Test public void test_a_b() {\n\t\tPredictionContext r = PredictionContext.merge(a(), b(), rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_ax_ax_same() {\n\t\tPredictionContext x = x();\n\t\tPredictionContext a1 = createSingleton(x, 1);\n\t\tPredictionContext a2 = createSingleton(x, 1);\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s1->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_ax_ax() {\n\t\tPredictionContext x1 = x();\n\t\tPredictionContext x2 = x();\n\t\tPredictionContext a1 = createSingleton(x1, 1);\n\t\tPredictionContext a2 = createSingleton(x2, 1);\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s1->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_abx_abx() {\n\t\tPredictionContext x1 = x();\n\t\tPredictionContext x2 = x();\n\t\tPredictionContext b1 = createSingleton(x1, 2);\n\t\tPredictionContext b2 = createSingleton(x2, 2);\n\t\tPredictionContext a1 = createSingleton(b1, 1);\n\t\tPredictionContext a2 = createSingleton(b2, 1);\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s2->s3[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_abx_acx() {\n\t\tPredictionContext x1 = x();\n\t\tPredictionContext x2 = x();\n\t\tPredictionContext b = createSingleton(x1, 2);\n\t\tPredictionContext c = createSingleton(x2, 3);\n\t\tPredictionContext a1 = createSingleton(b, 1);\n\t\tPredictionContext a2 = createSingleton(c, 1);\n\t\tPredictionContext r = PredictionContext.merge(a1, a2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s1:p0->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s1:p1->s2[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s2->s3[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_ax_bx_same() {\n\t\tPredictionContext x = x();\n\t\tPredictionContext a = createSingleton(x, 1);\n\t\tPredictionContext b = createSingleton(x, 2);\n\t\tPredictionContext r = PredictionContext.merge(a, b, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s1->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_ax_bx() {\n\t\tPredictionContext x1 = x();\n\t\tPredictionContext x2 = x();\n\t\tPredictionContext a = createSingleton(x1, 1);\n\t\tPredictionContext b = createSingleton(x2, 2);\n\t\tPredictionContext r = PredictionContext.merge(a, b, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s1->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_ax_by() {\n\t\tPredictionContext a = createSingleton(x(), 1);\n\t\tPredictionContext b = createSingleton(y(), 2);\n\t\tPredictionContext r = PredictionContext.merge(a, b, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s2->s3[label=\\\"10\\\"];\\n\" +\n\t\t\t\"  s1->s3[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_a$_bx() {\n\t\tPredictionContext x2 = x();\n\t\tPredictionContext a = a();\n\t\tPredictionContext b = createSingleton(x2, 2);\n\t\tPredictionContext r = PredictionContext.merge(a, b, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s2->s1[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_a$_bx_fullctx() {\n\t\tPredictionContext x2 = x();\n\t\tPredictionContext a = a();\n\t\tPredictionContext b = createSingleton(x2, 2);\n\t\tPredictionContext r = PredictionContext.merge(a, b, fullCtx(), null);\n//\t\tSystem.out.println(toDOTString(r, fullCtx()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"$\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s2->s1[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, fullCtx()));\n\t}\n\n\t@Disabled(\"Known inefficiency but deferring resolving the issue for now\")\n\t@Test public void test_aex_bfx() {\n\t\t// TJP: this is inefficient as it leaves the top x nodes unmerged.\n\t\tPredictionContext x1 = x();\n\t\tPredictionContext x2 = x();\n\t\tPredictionContext e = createSingleton(x1, 5);\n\t\tPredictionContext f = createSingleton(x2, 6);\n\t\tPredictionContext a = createSingleton(e, 1);\n\t\tPredictionContext b = createSingleton(f, 2);\n\t\tPredictionContext r = PredictionContext.merge(a, b, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s4[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s2->s3[label=\\\"6\\\"];\\n\" +\n\t\t\t\"  s3->s4[label=\\\"9\\\"];\\n\" +\n\t\t\t\"  s1->s3[label=\\\"5\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t// Array merges\n\n\t@Test public void test_A$_A$_fullctx() {\n\t\tArrayPredictionContext A1 = array(EmptyPredictionContext.Instance);\n\t\tArrayPredictionContext A2 = array(EmptyPredictionContext.Instance);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, fullCtx(), null);\n//\t\tSystem.out.println(toDOTString(r, fullCtx()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"$\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, fullCtx()));\n\t}\n\n\t@Test public void test_Aab_Ac() { // a,b + c\n\t\tSingletonPredictionContext a = a();\n\t\tSingletonPredictionContext b = b();\n\t\tSingletonPredictionContext c = c();\n\t\tArrayPredictionContext A1 = array(a, b);\n\t\tArrayPredictionContext A2 = array(c);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s1[label=\\\"3\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aa_Aa() {\n\t\tSingletonPredictionContext a1 = a();\n\t\tSingletonPredictionContext a2 = a();\n\t\tArrayPredictionContext A1 = array(a1);\n\t\tArrayPredictionContext A2 = array(a2);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aa_Abc() { // a + b,c\n\t\tSingletonPredictionContext a = a();\n\t\tSingletonPredictionContext b = b();\n\t\tSingletonPredictionContext c = c();\n\t\tArrayPredictionContext A1 = array(a);\n\t\tArrayPredictionContext A2 = array(b, c);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s1[label=\\\"3\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aac_Ab() { // a,c + b\n\t\tSingletonPredictionContext a = a();\n\t\tSingletonPredictionContext b = b();\n\t\tSingletonPredictionContext c = c();\n\t\tArrayPredictionContext A1 = array(a, c);\n\t\tArrayPredictionContext A2 = array(b);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s1[label=\\\"3\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aab_Aa() { // a,b + a\n\t\tArrayPredictionContext A1 = array(a(), b());\n\t\tArrayPredictionContext A2 = array(a());\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aab_Ab() { // a,b + b\n\t\tArrayPredictionContext A1 = array(a(), b());\n\t\tArrayPredictionContext A2 = array(b());\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aax_Aby() { // ax + by but in arrays\n\t\tSingletonPredictionContext a = createSingleton(x(), 1);\n\t\tSingletonPredictionContext b = createSingleton(y(), 2);\n\t\tArrayPredictionContext A1 = array(a);\n\t\tArrayPredictionContext A2 = array(b);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s2->s3[label=\\\"10\\\"];\\n\" +\n\t\t\t\"  s1->s3[label=\\\"9\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aax_Aay() { // ax + ay -> merged singleton a, array parent\n\t\tSingletonPredictionContext a1 = createSingleton(x(), 1);\n\t\tSingletonPredictionContext a2 = createSingleton(y(), 1);\n\t\tArrayPredictionContext A1 = array(a1);\n\t\tArrayPredictionContext A2 = array(a2);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[label=\\\"0\\\"];\\n\" +\n\t\t\t\"  s1[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s1:p0->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"  s1:p1->s2[label=\\\"10\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aaxc_Aayd() { // ax,c + ay,d -> merged a, array parent\n\t\tSingletonPredictionContext a1 = createSingleton(x(), 1);\n\t\tSingletonPredictionContext a2 = createSingleton(y(), 1);\n\t\tArrayPredictionContext A1 = array(a1, c());\n\t\tArrayPredictionContext A2 = array(a2, d());\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s1[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s0:p2->s2[label=\\\"4\\\"];\\n\" +\n\t\t\t\"  s1:p0->s2[label=\\\"9\\\"];\\n\" +\n\t\t\t\"  s1:p1->s2[label=\\\"10\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aaubv_Acwdx() { // au,bv + cw,dx -> [a,b,c,d]->[u,v,w,x]\n\t\tSingletonPredictionContext a = createSingleton(u(), 1);\n\t\tSingletonPredictionContext b = createSingleton(v(), 2);\n\t\tSingletonPredictionContext c = createSingleton(w(), 3);\n\t\tSingletonPredictionContext d = createSingleton(x(), 4);\n\t\tArrayPredictionContext A1 = array(a, b);\n\t\tArrayPredictionContext A2 = array(c, d);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>|<p3>\\\"];\\n\" +\n\t\t\t\"  s4[label=\\\"4\\\"];\\n\" +\n\t\t\t\"  s5[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s3[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s0:p3->s4[label=\\\"4\\\"];\\n\" +\n\t\t\t\"  s4->s5[label=\\\"9\\\"];\\n\" +\n\t\t\t\"  s3->s5[label=\\\"8\\\"];\\n\" +\n\t\t\t\"  s2->s5[label=\\\"7\\\"];\\n\" +\n\t\t\t\"  s1->s5[label=\\\"6\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aaubv_Abvdx() { // au,bv + bv,dx -> [a,b,d]->[u,v,x]\n\t\tSingletonPredictionContext a = createSingleton(u(), 1);\n\t\tSingletonPredictionContext b1 = createSingleton(v(), 2);\n\t\tSingletonPredictionContext b2 = createSingleton(v(), 2);\n\t\tSingletonPredictionContext d = createSingleton(x(), 4);\n\t\tArrayPredictionContext A1 = array(a, b1);\n\t\tArrayPredictionContext A2 = array(b2, d);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s4[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s3[label=\\\"4\\\"];\\n\" +\n\t\t\t\"  s3->s4[label=\\\"9\\\"];\\n\" +\n\t\t\t\"  s2->s4[label=\\\"7\\\"];\\n\" +\n\t\t\t\"  s1->s4[label=\\\"6\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aaubv_Abwdx() { // au,bv + bw,dx -> [a,b,d]->[u,[v,w],x]\n\t\tSingletonPredictionContext a = createSingleton(u(), 1);\n\t\tSingletonPredictionContext b1 = createSingleton(v(), 2);\n\t\tSingletonPredictionContext b2 = createSingleton(w(), 2);\n\t\tSingletonPredictionContext d = createSingleton(x(), 4);\n\t\tArrayPredictionContext A1 = array(a, b1);\n\t\tArrayPredictionContext A2 = array(b2, d);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s4[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s2[shape=record, label=\\\"<p0>|<p1>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s3[label=\\\"4\\\"];\\n\" +\n\t\t\t\"  s3->s4[label=\\\"9\\\"];\\n\" +\n\t\t\t\"  s2:p0->s4[label=\\\"7\\\"];\\n\" +\n\t\t\t\"  s2:p1->s4[label=\\\"8\\\"];\\n\" +\n\t\t\t\"  s1->s4[label=\\\"6\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aaubv_Abvdu() { // au,bv + bv,du -> [a,b,d]->[u,v,u]; u,v shared\n\t\tSingletonPredictionContext a = createSingleton(u(), 1);\n\t\tSingletonPredictionContext b1 = createSingleton(v(), 2);\n\t\tSingletonPredictionContext b2 = createSingleton(v(), 2);\n\t\tSingletonPredictionContext d = createSingleton(u(), 4);\n\t\tArrayPredictionContext A1 = array(a, b1);\n\t\tArrayPredictionContext A2 = array(b2, d);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s3[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s2[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s1[label=\\\"4\\\"];\\n\" +\n\t\t\t\"  s2->s3[label=\\\"7\\\"];\\n\" +\n\t\t\t\"  s1->s3[label=\\\"6\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\t@Test public void test_Aaubu_Acudu() { // au,bu + cu,du -> [a,b,c,d]->[u,u,u,u]\n\t\tSingletonPredictionContext a = createSingleton(u(), 1);\n\t\tSingletonPredictionContext b = createSingleton(u(), 2);\n\t\tSingletonPredictionContext c = createSingleton(u(), 3);\n\t\tSingletonPredictionContext d = createSingleton(u(), 4);\n\t\tArrayPredictionContext A1 = array(a, b);\n\t\tArrayPredictionContext A2 = array(c, d);\n\t\tPredictionContext r = PredictionContext.merge(A1, A2, rootIsWildcard(), null);\n//\t\tSystem.out.println(toDOTString(r, rootIsWildcard()));\n\t\tString expecting =\n\t\t\t\"digraph G {\\n\" +\n\t\t\t\"rankdir=LR;\\n\" +\n\t\t\t\"  s0[shape=record, label=\\\"<p0>|<p1>|<p2>|<p3>\\\"];\\n\" +\n\t\t\t\"  s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s2[label=\\\"*\\\"];\\n\" +\n\t\t\t\"  s0:p0->s1[label=\\\"1\\\"];\\n\" +\n\t\t\t\"  s0:p1->s1[label=\\\"2\\\"];\\n\" +\n\t\t\t\"  s0:p2->s1[label=\\\"3\\\"];\\n\" +\n\t\t\t\"  s0:p3->s1[label=\\\"4\\\"];\\n\" +\n\t\t\t\"  s1->s2[label=\\\"6\\\"];\\n\" +\n\t\t\t\"}\\n\";\n\t\tassertEquals(expecting, toDOTString(r, rootIsWildcard()));\n\t}\n\n\n\t// ------------ SUPPORT -------------------------\n\n\tprotected SingletonPredictionContext a() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 1);\n\t}\n\n\tprivate SingletonPredictionContext b() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 2);\n\t}\n\n\tprivate SingletonPredictionContext c() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 3);\n\t}\n\n\tprivate SingletonPredictionContext d() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 4);\n\t}\n\n\tprivate SingletonPredictionContext u() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 6);\n\t}\n\n\tprivate SingletonPredictionContext v() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 7);\n\t}\n\n\tprivate SingletonPredictionContext w() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 8);\n\t}\n\n\tprivate SingletonPredictionContext x() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 9);\n\t}\n\n\tprivate SingletonPredictionContext y() {\n\t\treturn createSingleton(EmptyPredictionContext.Instance, 10);\n\t}\n\n\tpublic SingletonPredictionContext createSingleton(PredictionContext parent, int payload) {\n\t\tSingletonPredictionContext a = SingletonPredictionContext.create(parent, payload);\n\t\treturn a;\n\t}\n\n\tpublic ArrayPredictionContext array(SingletonPredictionContext... nodes) {\n\t\tPredictionContext[] parents = new PredictionContext[nodes.length];\n\t\tint[] invokingStates = new int[nodes.length];\n\t\tfor (int i=0; i<nodes.length; i++) {\n\t\t\tparents[i] = nodes[i].parent;\n\t\t\tinvokingStates[i] = nodes[i].returnState;\n\t\t}\n\t\treturn new ArrayPredictionContext(parents, invokingStates);\n\t}\n\n\tprivate static String toDOTString(PredictionContext context, boolean rootIsWildcard) {\n\t\tStringBuilder nodes = new StringBuilder();\n\t\tStringBuilder edges = new StringBuilder();\n\t\tMap<PredictionContext, PredictionContext> visited = new IdentityHashMap<PredictionContext, PredictionContext>();\n\t\tMap<PredictionContext, Integer> contextIds = new IdentityHashMap<PredictionContext, Integer>();\n\t\tDeque<PredictionContext> workList = new ArrayDeque<PredictionContext>();\n\t\tvisited.put(context, context);\n\t\tcontextIds.put(context, contextIds.size());\n\t\tworkList.add(context);\n\t\twhile (!workList.isEmpty()) {\n\t\t\tPredictionContext current = workList.pop();\n\t\t\tnodes.append(\"  s\").append(contextIds.get(current)).append('[');\n\n\t\t\tif (current.size() > 1) {\n\t\t\t\tnodes.append(\"shape=record, \");\n\t\t\t}\n\n\t\t\tnodes.append(\"label=\\\"\");\n\n\t\t\tif (current.isEmpty()) {\n\t\t\t\tnodes.append(rootIsWildcard ? '*' : '$');\n\t\t\t} else if (current.size() > 1) {\n\t\t\t\tfor (int i = 0; i < current.size(); i++) {\n\t\t\t\t\tif (i > 0) {\n\t\t\t\t\t\tnodes.append('|');\n\t\t\t\t\t}\n\n\t\t\t\t\tnodes.append(\"<p\").append(i).append('>');\n\t\t\t\t\tif (current.getReturnState(i) == PredictionContext.EMPTY_RETURN_STATE) {\n\t\t\t\t\t\tnodes.append(rootIsWildcard ? '*' : '$');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnodes.append(contextIds.get(current));\n\t\t\t}\n\n\t\t\tnodes.append(\"\\\"];\\n\");\n\n\t\t\tif (current.isEmpty()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < current.size(); i++) {\n\t\t\t\tif (current.getReturnState(i) == PredictionContext.EMPTY_RETURN_STATE) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (visited.put(current.getParent(i), current.getParent(i)) == null) {\n\t\t\t\t\tcontextIds.put(current.getParent(i), contextIds.size());\n\t\t\t\t\tworkList.push(current.getParent(i));\n\t\t\t\t}\n\n\t\t\t\tedges.append(\"  s\").append(contextIds.get(current));\n\t\t\t\tif (current.size() > 1) {\n\t\t\t\t\tedges.append(\":p\").append(i);\n\t\t\t\t}\n\n\t\t\t\tedges.append(\"->\");\n\t\t\t\tedges.append('s').append(contextIds.get(current.getParent(i)));\n\t\t\t\tedges.append(\"[label=\\\"\").append(current.getReturnState(i)).append(\"\\\"]\");\n\t\t\t\tedges.append(\";\\n\");\n\t\t\t}\n\t\t}\n\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"digraph G {\\n\");\n\t\tbuilder.append(\"rankdir=LR;\\n\");\n\t\tbuilder.append(nodes);\n\t\tbuilder.append(edges);\n\t\tbuilder.append(\"}\\n\");\n\t\treturn builder.toString();\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestIntervalSet.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class TestIntervalSet {\n\n    /** Public default constructor used by TestRig */\n    public TestIntervalSet() {\n\t}\n\n\t@Test public void testSingleElement() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(99);\n\t\tString expecting = \"99\";\n\t\tassertEquals(s.toString(), expecting);\n\t}\n\n\t@Test public void testMin() throws Exception {\n\t\tassertEquals(0, IntervalSet.COMPLETE_CHAR_SET.getMinElement());\n\t\tassertEquals(Token.EPSILON, IntervalSet.COMPLETE_CHAR_SET.or(IntervalSet.of(Token.EPSILON)).getMinElement());\n\t\tassertEquals(Token.EOF, IntervalSet.COMPLETE_CHAR_SET.or(IntervalSet.of(Token.EOF)).getMinElement());\n\t}\n\n\t@Test public void testIsolatedElements() throws Exception {\n\t\tIntervalSet s = new IntervalSet();\n\t\ts.add(1);\n\t\ts.add('z');\n\t\ts.add('\\uFFF0');\n\t\tString expecting = \"{1, 122, 65520}\";\n        assertEquals(s.toString(), expecting);\n    }\n\n    @Test public void testMixedRangesAndElements() throws Exception {\n        IntervalSet s = new IntervalSet();\n        s.add(1);\n        s.add('a','z');\n        s.add('0','9');\n        String expecting = \"{1, 48..57, 97..122}\";\n        assertEquals(s.toString(), expecting);\n    }\n\n    @Test public void testSimpleAnd() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        IntervalSet s2 = IntervalSet.of(13,15);\n        String expecting = \"{13..15}\";\n        String result = (s.and(s2)).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testRangeAndIsolatedElement() throws Exception {\n        IntervalSet s = IntervalSet.of('a','z');\n        IntervalSet s2 = IntervalSet.of('d');\n        String expecting = \"100\";\n        String result = (s.and(s2)).toString();\n        assertEquals(expecting, result);\n    }\n\n\t@Test public void testEmptyIntersection() throws Exception {\n\t\tIntervalSet s = IntervalSet.of('a','z');\n\t\tIntervalSet s2 = IntervalSet.of('0','9');\n\t\tString expecting = \"{}\";\n\t\tString result = (s.and(s2)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testEmptyIntersectionSingleElements() throws Exception {\n\t\tIntervalSet s = IntervalSet.of('a');\n\t\tIntervalSet s2 = IntervalSet.of('d');\n\t\tString expecting = \"{}\";\n\t\tString result = (s.and(s2)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n    @Test public void testNotSingleElement() throws Exception {\n        IntervalSet vocabulary = IntervalSet.of(1,1000);\n        vocabulary.add(2000,3000);\n        IntervalSet s = IntervalSet.of(50,50);\n        String expecting = \"{1..49, 51..1000, 2000..3000}\";\n        String result = (s.complement(vocabulary)).toString();\n        assertEquals(expecting, result);\n    }\n\n\t@Test public void testNotSet() throws Exception {\n\t\tIntervalSet vocabulary = IntervalSet.of(1,1000);\n\t\tIntervalSet s = IntervalSet.of(50,60);\n\t\ts.add(5);\n\t\ts.add(250,300);\n\t\tString expecting = \"{1..4, 6..49, 61..249, 301..1000}\";\n\t\tString result = (s.complement(vocabulary)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testNotEqualSet() throws Exception {\n\t\tIntervalSet vocabulary = IntervalSet.of(1,1000);\n\t\tIntervalSet s = IntervalSet.of(1,1000);\n\t\tString expecting = \"{}\";\n\t\tString result = (s.complement(vocabulary)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testNotSetEdgeElement() throws Exception {\n\t\tIntervalSet vocabulary = IntervalSet.of(1,2);\n\t\tIntervalSet s = IntervalSet.of(1);\n\t\tString expecting = \"2\";\n\t\tString result = (s.complement(vocabulary)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n    @Test public void testNotSetFragmentedVocabulary() throws Exception {\n        IntervalSet vocabulary = IntervalSet.of(1,255);\n        vocabulary.add(1000,2000);\n        vocabulary.add(9999);\n        IntervalSet s = IntervalSet.of(50, 60);\n        s.add(3);\n        s.add(250,300);\n        s.add(10000); // this is outside range of vocab and should be ignored\n        String expecting = \"{1..2, 4..49, 61..249, 1000..2000, 9999}\";\n        String result = (s.complement(vocabulary)).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testSubtractOfCompletelyContainedRange() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        IntervalSet s2 = IntervalSet.of(12,15);\n        String expecting = \"{10..11, 16..20}\";\n        String result = (s.subtract(s2)).toString();\n        assertEquals(expecting, result);\n    }\n\n\t@Test public void testSubtractFromSetWithEOF() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(10,20);\n\t\ts.add(Token.EOF);\n\t\tIntervalSet s2 = IntervalSet.of(12,15);\n\t\tString expecting = \"{<EOF>, 10..11, 16..20}\";\n\t\tString result = (s.subtract(s2)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testSubtractOfOverlappingRangeFromLeft() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(10,20);\n\t\tIntervalSet s2 = IntervalSet.of(5,11);\n\t\tString expecting = \"{12..20}\";\n        String result = (s.subtract(s2)).toString();\n        assertEquals(expecting, result);\n\n        IntervalSet s3 = IntervalSet.of(5,10);\n        expecting = \"{11..20}\";\n        result = (s.subtract(s3)).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testSubtractOfOverlappingRangeFromRight() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        IntervalSet s2 = IntervalSet.of(15,25);\n        String expecting = \"{10..14}\";\n        String result = (s.subtract(s2)).toString();\n        assertEquals(expecting, result);\n\n        IntervalSet s3 = IntervalSet.of(20,25);\n        expecting = \"{10..19}\";\n        result = (s.subtract(s3)).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testSubtractOfCompletelyCoveredRange() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        IntervalSet s2 = IntervalSet.of(1,25);\n        String expecting = \"{}\";\n        String result = (s.subtract(s2)).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testSubtractOfRangeSpanningMultipleRanges() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        s.add(30,40);\n        s.add(50,60); // s has 3 ranges now: 10..20, 30..40, 50..60\n        IntervalSet s2 = IntervalSet.of(5,55); // covers one and touches 2nd range\n        String expecting = \"{56..60}\";\n        String result = (s.subtract(s2)).toString();\n        assertEquals(expecting, result);\n\n        IntervalSet s3 = IntervalSet.of(15,55); // touches both\n        expecting = \"{10..14, 56..60}\";\n        result = (s.subtract(s3)).toString();\n        assertEquals(expecting, result);\n    }\n\n\t/** The following was broken:\n\t \t{0..113, 115..65534}-{0..115, 117..65534}=116..65534\n\t */\n\t@Test public void testSubtractOfWackyRange() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(0,113);\n\t\ts.add(115,200);\n\t\tIntervalSet s2 = IntervalSet.of(0,115);\n\t\ts2.add(117,200);\n\t\tString expecting = \"116\";\n\t\tString result = (s.subtract(s2)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n    @Test public void testSimpleEquals() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        IntervalSet s2 = IntervalSet.of(10,20);\n        assertEquals(s, s2);\n\n        IntervalSet s3 = IntervalSet.of(15,55);\n        assertFalse(s.equals(s3));\n    }\n\n    @Test public void testEquals() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        s.add(2);\n        s.add(499,501);\n        IntervalSet s2 = IntervalSet.of(10,20);\n        s2.add(2);\n        s2.add(499,501);\n        assertEquals(s, s2);\n\n        IntervalSet s3 = IntervalSet.of(10,20);\n        s3.add(2);\n\t\tassertFalse(s.equals(s3));\n    }\n\n    @Test public void testSingleElementMinusDisjointSet() throws Exception {\n        IntervalSet s = IntervalSet.of(15,15);\n        IntervalSet s2 = IntervalSet.of(1,5);\n        s2.add(10,20);\n        String expecting = \"{}\"; // 15 - {1..5, 10..20} = {}\n        String result = s.subtract(s2).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testMembership() throws Exception {\n        IntervalSet s = IntervalSet.of(15,15);\n        s.add(50,60);\n        assertTrue(!s.contains(0));\n        assertTrue(!s.contains(20));\n        assertTrue(!s.contains(100));\n        assertTrue(s.contains(15));\n        assertTrue(s.contains(55));\n        assertTrue(s.contains(50));\n        assertTrue(s.contains(60));\n    }\n\n    // {2,15,18} & 10..20\n    @Test public void testIntersectionWithTwoContainedElements() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        IntervalSet s2 = IntervalSet.of(2,2);\n        s2.add(15);\n        s2.add(18);\n        String expecting = \"{15, 18}\";\n        String result = (s.and(s2)).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testIntersectionWithTwoContainedElementsReversed() throws Exception {\n        IntervalSet s = IntervalSet.of(10,20);\n        IntervalSet s2 = IntervalSet.of(2,2);\n        s2.add(15);\n        s2.add(18);\n        String expecting = \"{15, 18}\";\n        String result = (s2.and(s)).toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testComplement() throws Exception {\n        IntervalSet s = IntervalSet.of(100,100);\n        s.add(101,101);\n        IntervalSet s2 = IntervalSet.of(100,102);\n        String expecting = \"102\";\n        String result = (s.complement(s2)).toString();\n        assertEquals(expecting, result);\n    }\n\n\t@Test public void testComplement2() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(100,101);\n\t\tIntervalSet s2 = IntervalSet.of(100,102);\n\t\tString expecting = \"102\";\n\t\tString result = (s.complement(s2)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testComplement3() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(1,96);\n\t\ts.add(99, Lexer.MAX_CHAR_VALUE);\n\t\tString expecting = \"{97..98}\";\n\t\tString result = (s.complement(1, Lexer.MAX_CHAR_VALUE)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n    @Test public void testMergeOfRangesAndSingleValues() throws Exception {\n        // {0..41, 42, 43..65534}\n        IntervalSet s = IntervalSet.of(0,41);\n        s.add(42);\n        s.add(43,65534);\n        String expecting = \"{0..65534}\";\n        String result = s.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testMergeOfRangesAndSingleValuesReverse() throws Exception {\n        IntervalSet s = IntervalSet.of(43,65534);\n        s.add(42);\n        s.add(0,41);\n        String expecting = \"{0..65534}\";\n        String result = s.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testMergeWhereAdditionMergesTwoExistingIntervals() throws Exception {\n        // 42, 10, {0..9, 11..41, 43..65534}\n        IntervalSet s = IntervalSet.of(42);\n        s.add(10);\n        s.add(0,9);\n        s.add(43,65534);\n        s.add(11,41);\n        String expecting = \"{0..65534}\";\n        String result = s.toString();\n        assertEquals(expecting, result);\n    }\n\n\t/**\n\t * This case is responsible for antlr/antlr4#153.\n\t * https://github.com/antlr/antlr4/issues/153\n\t */\n\t@Test public void testMergeWhereAdditionMergesThreeExistingIntervals() throws Exception {\n\t\tIntervalSet s = new IntervalSet();\n\t\ts.add(0);\n\t\ts.add(3);\n\t\ts.add(5);\n\t\ts.add(0, 7);\n\t\tString expecting = \"{0..7}\";\n\t\tString result = s.toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testMergeWithDoubleOverlap() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(1,10);\n\t\ts.add(20,30);\n\t\ts.add(5,25); // overlaps two!\n\t\tString expecting = \"{1..30}\";\n\t\tString result = s.toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testSize() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(20,30);\n\t\ts.add(50,55);\n\t\ts.add(5,19);\n\t\tString expecting = \"32\";\n\t\tString result = String.valueOf(s.size());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t@Test public void testToList() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(20,25);\n\t\ts.add(50,55);\n\t\ts.add(5,5);\n\t\tString expecting = \"[5, 20, 21, 22, 23, 24, 25, 50, 51, 52, 53, 54, 55]\";\n\t\tString result = String.valueOf(s.toList());\n\t\tassertEquals(expecting, result);\n\t}\n\n\t/** The following was broken:\n\t    {'\\u0000'..'s', 'u'..'\\uFFFE'} & {'\\u0000'..'q', 's'..'\\uFFFE'}=\n\t    {'\\u0000'..'q', 's'}!!!! broken...\n\t \t'q' is 113 ascii\n\t \t'u' is 117\n\t*/\n\t@Test public void testNotRIntersectionNotT() throws Exception {\n\t\tIntervalSet s = IntervalSet.of(0,'s');\n\t\ts.add('u',200);\n\t\tIntervalSet s2 = IntervalSet.of(0,'q');\n\t\ts2.add('s',200);\n\t\tString expecting = \"{0..113, 115, 117..200}\";\n\t\tString result = (s.and(s2)).toString();\n\t\tassertEquals(expecting, result);\n\t}\n\n    @Test public void testRmSingleElement() throws Exception {\n        IntervalSet s = IntervalSet.of(1,10);\n        s.add(-3,-3);\n        s.remove(-3);\n        String expecting = \"{1..10}\";\n        String result = s.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testRmLeftSide() throws Exception {\n        IntervalSet s = IntervalSet.of(1,10);\n        s.add(-3,-3);\n        s.remove(1);\n        String expecting = \"{-3, 2..10}\";\n        String result = s.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testRmRightSide() throws Exception {\n        IntervalSet s = IntervalSet.of(1,10);\n        s.add(-3,-3);\n        s.remove(10);\n        String expecting = \"{-3, 1..9}\";\n        String result = s.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test public void testRmMiddleRange() throws Exception {\n        IntervalSet s = IntervalSet.of(1,10);\n        s.add(-3,-3);\n        s.remove(5);\n        String expecting = \"{-3, 1..4, 6..10}\";\n        String result = s.toString();\n        assertEquals(expecting, result);\n    }\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestLeftRecursionToolIssues.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.tool.ErrorType;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.testErrors;\n\n/** */\npublic class TestLeftRecursionToolIssues {\n\tprotected boolean debug = false;\n\n\t@Test public void testCheckForNonLeftRecursiveRule() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"s @after {System.out.println($ctx.toStringTree(this));} : a ;\\n\" +\n\t\t\t\"a : a ID\\n\" +\n\t\t\t\"  ;\\n\" +\n\t\t\t\"ID : 'a'..'z'+ ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.NO_NON_LR_ALTS.code + \"): T.g4:3:0: left recursive rule a must contain an alternative which is not left recursive\\n\";\n\t\ttestErrors(new String[] { grammar, expected }, false);\n\t}\n\n\t@Test public void testCheckForLeftRecursiveEmptyFollow() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"s @after {System.out.println($ctx.toStringTree(this));} : a ;\\n\" +\n\t\t\t\"a : a ID?\\n\" +\n\t\t\t\"  | ID\\n\" +\n\t\t\t\"  ;\\n\" +\n\t\t\t\"ID : 'a'..'z'+ ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.EPSILON_LR_FOLLOW.code + \"): T.g4:3:0: left recursive rule a contains a left recursive alternative which can be followed by the empty string\\n\";\n\t\ttestErrors(new String[] { grammar, expected }, false);\n\t}\n\n\t/** Reproduces https://github.com/antlr/antlr4/issues/855 */\n\t@Test public void testLeftRecursiveRuleRefWithArg() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"statement\\n\" +\n\t\t\t\"locals[Scope scope]\\n\" +\n\t\t\t\"    : expressionA[$scope] ';'\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"expressionA[Scope scope]\\n\" +\n\t\t\t\"    : atom[$scope]\\n\" +\n\t\t\t\"    | expressionA[$scope] '[' expressionA[$scope] ']'\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"atom[Scope scope]\\n\" +\n\t\t\t\"    : 'dummy'\\n\" +\n\t\t\t\"    ;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.NONCONFORMING_LR_RULE.code + \"): T.g4:6:0: rule expressionA is left recursive but doesn't conform to a pattern ANTLR can handle\\n\";\n\t\ttestErrors(new String[]{grammar, expected}, false);\n\t}\n\n\t/** Reproduces https://github.com/antlr/antlr4/issues/855 */\n\t@Test public void testLeftRecursiveRuleRefWithArg2() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"a[int i] : 'x'\\n\" +\n\t\t\t\"  | a[3] 'y'\\n\" +\n\t\t\t\"  ;\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.NONCONFORMING_LR_RULE.code + \"): T.g4:2:0: rule a is left recursive but doesn't conform to a pattern ANTLR can handle\\n\";\n\t\ttestErrors(new String[]{grammar, expected}, false);\n\t}\n\n\t/** Reproduces https://github.com/antlr/antlr4/issues/855 */\n\t@Test public void testLeftRecursiveRuleRefWithArg3() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"a : 'x'\\n\" +\n\t\t\t\"  | a[3] 'y'\\n\" +\n\t\t\t\"  ;\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.NONCONFORMING_LR_RULE.code + \"): T.g4:2:0: rule a is left recursive but doesn't conform to a pattern ANTLR can handle\\n\";\n\t\ttestErrors(new String[]{grammar, expected}, false);\n\t}\n\n\t/** Reproduces https://github.com/antlr/antlr4/issues/822 */\n\t@Test public void testIsolatedLeftRecursiveRuleRef() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"a : a | b ;\\n\" +\n\t\t\t\"b : 'B' ;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.NONCONFORMING_LR_RULE.code + \"): T.g4:2:0: rule a is left recursive but doesn't conform to a pattern ANTLR can handle\\n\";\n\t\ttestErrors(new String[]{grammar, expected}, false);\n\t}\n\n\t/** Reproduces https://github.com/antlr/antlr4/issues/773 */\n\t@Test public void testArgOnPrimaryRuleInLeftRecursiveRule() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"val: dval[1]\\n\" +\n\t\t\t\"   | val '*' val\\n\" +\n\t\t\t\"   ;\\n\" +\n\t\t\t\"dval[int  x]: '.';\\n\";\n\t\tString expected = \"\"; // dval[1] should not be error\n\t\ttestErrors(new String[]{grammar, expected}, false);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestLexerActions.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.execLexer;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestLexerActions {\n\t// ----- ACTIONS --------------------------------------------------------\n\n\t@Test public void testActionExecutedInDFA() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : '0'..'9'+ {outStream.println(\\\"I\\\");} ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"34 34\");\n\t\tString expecting =\n\t\t\t\"I\\n\" +\n\t\t\t\"I\\n\" +\n\t\t\t\"[@0,0:1='34',<1>,1:0]\\n\" +\n\t\t\t\"[@1,3:4='34',<1>,1:3]\\n\" +\n\t\t\t\"[@2,5:4='<EOF>',<-1>,1:5]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testActionEvalsAtCorrectIndex() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : [0-9] {outStream.println(\\\"2nd char: \\\"+(char)_input.LA(1));} [0-9]+ ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"123 45\");\n\t\tString expecting =\n\t\t\t\"2nd char: 2\\n\" +\n\t\t\t\"2nd char: 5\\n\" +\n\t\t\t\"[@0,0:2='123',<1>,1:0]\\n\" +\n\t\t\t\"[@1,4:5='45',<1>,1:4]\\n\" +\n\t\t\t\"[@2,6:5='<EOF>',<-1>,1:6]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t/**\n\t * This is a regressing test for antlr/antlr4#469 \"Not all internal lexer\n\t * rule actions are executed\".\n\t * https://github.com/antlr/antlr4/issues/469\n\t */\n\t@Test public void testEvalMultipleActions() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"@lexer::members\\n\" +\n\t\t\t\"{\\n\" +\n\t\t\t\"class Marker\\n\" +\n\t\t\t\"{\\n\" +\n\t\t\t\"   Marker (Lexer lexer) { this.lexer = lexer; }\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"   public String getText ()\\n\" +\n\t\t\t\"   {\\n\" +\n\t\t\t\"      return lexer._input.getText (new Interval (start_index, stop_index));\\n\" +\n\t\t\t\"   }\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"   public void start ()  { start_index = lexer._input.index (); outStream.println (\\\"Start:\\\" + start_index);}\\n\" +\n\t\t\t\"   public void stop () { stop_index = lexer._input.index (); outStream.println (\\\"Stop:\\\" + stop_index);}\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"   private int start_index = 0;\\n\" +\n\t\t\t\"   private int stop_index = 0;\\n\" +\n\t\t\t\"   private Lexer lexer;\\n\" +\n\t\t\t\"}\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"Marker m_name = new Marker (this);\\n\" +\n\t\t\t\"}\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"HELLO: 'hello' WS { m_name.start (); } NAME { m_name.stop (); } '\\\\n' { outStream.println (\\\"Hello: \\\" + m_name.getText ()); };\\n\" +\n\t\t\t\"NAME: ('a'..'z' | 'A'..'Z')+ ('\\\\n')?;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"fragment WS: [ \\\\r\\\\t\\\\n]+ ;\\n\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"hello Steve\\n\");\n\t\tString expecting =\n\t\t\t\"Start:6\\n\" +\n\t\t\t\"Stop:11\\n\" +\n\t\t\t\"Hello: Steve\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"[@0,0:11='hello Steve\\\\n',<1>,1:0]\\n\" +\n\t\t\t\"[@1,12:11='<EOF>',<-1>,2:0]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void test2ActionsIn1Rule() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : [0-9] {outStream.println(\\\"x\\\");} [0-9]+ {outStream.println(\\\"y\\\");} ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"123 45\");\n\t\tString expecting =\n\t\t\t\"x\\n\" +\n\t\t\t\"y\\n\" +\n\t\t\t\"x\\n\" +\n\t\t\t\"y\\n\" +\n\t\t\t\"[@0,0:2='123',<1>,1:0]\\n\" +\n\t\t\t\"[@1,4:5='45',<1>,1:4]\\n\" +\n\t\t\t\"[@2,6:5='<EOF>',<-1>,1:6]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testAltActionsIn1Rule() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : ( [0-9]+ {outStream.print(\\\"int\\\");}\\n\" +\n\t\t\t\"    | [a-z]+ {outStream.print(\\\"id\\\");}\\n\" +\n\t\t\t\"    )\\n\" +\n\t\t\t\"    {outStream.println(\\\" last\\\");}\\n\" +\n\t\t\t\"    ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"123 ab\");\n\t\tString expecting =\n\t\t\t\"int last\\n\" +\n\t\t\t\"id last\\n\" +\n\t\t\t\"[@0,0:2='123',<1>,1:0]\\n\" +\n\t\t\t\"[@1,4:5='ab',<1>,1:4]\\n\" +\n\t\t\t\"[@2,6:5='<EOF>',<-1>,1:6]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testActionPlusCommand() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : '0'..'9'+ {outStream.println(\\\"I\\\");} -> skip ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"34 34\");\n\t\tString expecting =\n\t\t\t\"I\\n\" +\n\t\t\t\"I\\n\" +\n\t\t\t\"[@0,5:4='<EOF>',<-1>,1:5]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t// ----- COMMANDS --------------------------------------------------------\n\n\t@Test public void testSkipCommand() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : '0'..'9'+ {outStream.println(\\\"I\\\");} ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"34 34\");\n\t\tString expecting =\n\t\t\t\"I\\n\" +\n\t\t\t\"I\\n\" +\n\t\t\t\"[@0,0:1='34',<1>,1:0]\\n\" +\n\t\t\t\"[@1,3:4='34',<1>,1:3]\\n\" +\n\t\t\t\"[@2,5:4='<EOF>',<-1>,1:5]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testMoreCommand() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : '0'..'9'+ {outStream.println(\\\"I\\\");} ;\\n\"+\n\t\t\t\"WS : '#' -> more ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"34#10\");\n\t\tString expecting =\n\t\t\t\"I\\n\" +\n\t\t\t\"I\\n\" +\n\t\t\t\"[@0,0:1='34',<1>,1:0]\\n\" +\n\t\t\t\"[@1,2:4='#10',<1>,1:2]\\n\" +\n\t\t\t\"[@2,5:4='<EOF>',<-1>,1:5]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testTypeCommand() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\"+\n\t\t\t\"I : '0'..'9'+ {outStream.println(\\\"I\\\");} ;\\n\"+\n\t\t\t\"HASH : '#' -> type(HASH) ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"34#\");\n\t\tString expecting =\n\t\t\t\"I\\n\" +\n\t\t\t\"[@0,0:1='34',<1>,1:0]\\n\" +\n\t\t\t\"[@1,2:2='#',<2>,1:2]\\n\" +\n\t\t\t\"[@2,3:2='<EOF>',<-1>,1:3]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testCombinedCommand() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"I : '0'..'9'+ {outStream.println(\\\"I\\\");} ;\\n\"+\n\t\t\t\"HASH : '#' -> type(100), skip, more  ;\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"34#11\");\n\t\tString expecting =\n\t\t\t\"I\\n\" +\n\t\t\t\"I\\n\" +\n\t\t\t\"[@0,0:1='34',<1>,1:0]\\n\" +\n\t\t\t\"[@1,2:4='#11',<1>,1:2]\\n\" +\n\t\t\t\"[@2,5:4='<EOF>',<-1>,1:5]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testLexerMode() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"STRING_START : '\\\"' -> pushMode(STRING_MODE), more;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\"+\n\t\t\t\"mode STRING_MODE;\\n\"+\n\t\t\t\"STRING : '\\\"' -> popMode;\\n\"+\n\t\t\t\"ANY : . -> more;\\n\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"\\\"abc\\\" \\\"ab\\\"\");\n\t\tString expecting =\n\t\t\t\"[@0,0:4='\\\"abc\\\"',<2>,1:0]\\n\" +\n\t\t\t\"[@1,6:9='\\\"ab\\\"',<2>,1:6]\\n\" +\n\t\t\t\"[@2,10:9='<EOF>',<-1>,1:10]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testLexerPushPopModeAction() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"STRING_START : '\\\"' -> pushMode(STRING_MODE), more ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\"+\n\t\t\t\"mode STRING_MODE;\\n\"+\n\t\t\t\"STRING : '\\\"' -> popMode ;\\n\"+  // token type 2\n\t\t\t\"ANY : . -> more ;\\n\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"\\\"abc\\\" \\\"ab\\\"\");\n\t\tString expecting =\n\t\t\t\"[@0,0:4='\\\"abc\\\"',<2>,1:0]\\n\" +\n\t\t\t\"[@1,6:9='\\\"ab\\\"',<2>,1:6]\\n\" +\n\t\t\t\"[@2,10:9='<EOF>',<-1>,1:10]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t@Test public void testLexerModeAction() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"STRING_START : '\\\"' -> mode(STRING_MODE), more ;\\n\" +\n\t\t\t\"WS : (' '|'\\\\n') -> skip ;\\n\"+\n\t\t\t\"mode STRING_MODE;\\n\"+\n\t\t\t\"STRING : '\\\"' -> mode(DEFAULT_MODE) ;\\n\"+ // ttype 2 since '\"' ambiguity\n\t\t\t\"ANY : . -> more ;\\n\";\n\t\tExecutedState executedState = execLexer(\"L.g4\", grammar, \"L\", \"\\\"abc\\\" \\\"ab\\\"\");\n\t\tString expecting =\n\t\t\t\"[@0,0:4='\\\"abc\\\"',<2>,1:0]\\n\" +\n\t\t\t\"[@1,6:9='\\\"ab\\\"',<2>,1:6]\\n\" +\n\t\t\t\"[@2,10:9='<EOF>',<-1>,1:10]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n\t// ----- PREDICATES --------------------------------------------------------\n\n\t/**\n\t * This is a regression test for antlr/antlr4#398 \"Lexer: literal matches\n\t * while negated char set fail to match\"\n\t * https://github.com/antlr/antlr4/issues/398\n\t */\n\t@Test\n\tpublic void testFailingPredicateEvalIsNotCached() {\n\t\tString grammar =\n\t\t\t\"lexer grammar TestLexer;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"fragment WS: [ \\\\t]+;\\n\" +\n\t\t\t\"fragment EOL: '\\\\r'? '\\\\n';\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"LINE: WS? ~[\\\\r\\\\n]* EOL { !getText().trim().startsWith(\\\"Item:\\\") }?;\\n\" +\n\t\t\t\"ITEM: WS? 'Item:' -> pushMode(ITEM_HEADING_MODE);\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"mode ITEM_HEADING_MODE;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"NAME: ~[\\\\r\\\\n]+;\\n\" +\n\t\t\t\"SECTION_HEADING_END: EOL -> popMode;\\n\";\n\t\tString input =\n\t\t\t\"A line here.\\n\" +\n\t\t\t\"Item: name of item\\n\" +\n\t\t\t\"Another line.\\n\" +\n\t\t\t\"More line.\\n\";\n\t\tExecutedState executedState = execLexer(\"TestLexer.g4\", grammar, \"TestLexer\", input);\n\t\tString expecting =\n\t\t\t\"[@0,0:12='A line here.\\\\n',<1>,1:0]\\n\" +\n\t\t\t\"[@1,13:17='Item:',<2>,2:0]\\n\" +\n\t\t\t\"[@2,18:30=' name of item',<3>,2:5]\\n\" +\n\t\t\t\"[@3,31:31='\\\\n',<4>,2:18]\\n\" +\n\t\t\t\"[@4,32:45='Another line.\\\\n',<1>,3:0]\\n\" +\n\t\t\t\"[@5,46:56='More line.\\\\n',<1>,4:0]\\n\" +\n\t\t\t\"[@6,57:56='<EOF>',<-1>,5:0]\\n\";\n\t\tassertEquals(expecting, executedState.output);\n\t}\n\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestLookaheadTrees.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.gui.Trees;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.atn.DecisionInfo;\nimport org.antlr.v4.runtime.atn.LookaheadEventInfo;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.GrammarParserInterpreter;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestLookaheadTrees {\n\tpublic static final String lexerText =\n\t\t\"lexer grammar L;\\n\" +\n\t\t\"DOT  : '.' ;\\n\" +\n\t\t\"SEMI : ';' ;\\n\" +\n\t\t\"BANG : '!' ;\\n\" +\n\t\t\"PLUS : '+' ;\\n\" +\n\t\t\"LPAREN : '(' ;\\n\" +\n\t\t\"RPAREN : ')' ;\\n\" +\n\t\t\"MULT : '*' ;\\n\" +\n\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\"WS : [ \\\\r\\\\t\\\\n]+ ;\\n\";\n\n\t@Test\n\tpublic void testAlts() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e SEMI EOF ;\\n\" +\n\t\t\t\"e : ID DOT ID\\n\"+\n\t\t\t\"  | ID LPAREN RPAREN\\n\"+\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\n\t\tString startRuleName = \"s\";\n\t\tint decision = 0;\n\n\t\ttestLookaheadTrees(lg, g, \"a.b;\", startRuleName, decision,\n\t\t\t\t\t\t   new String[] {\"(e:1 a . b)\", \"(e:2 a <error .>)\"});\n\t}\n\n\t@Test\n\tpublic void testAlts2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e? SEMI EOF ;\\n\" +\n\t\t\t\"e : ID\\n\" +\n\t\t\t\"  | e BANG\" +\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\n\t\tString startRuleName = \"s\";\n\t\tint decision = 1; // (...)* in e.\n\n\t\ttestLookaheadTrees(lg, g, \"a;\", startRuleName, decision,\n\t\t\t\t\t\t   new String[] {\"(e:2 (e:1 a) <error ;>)\", // Decision for alt 1 is error as no ! char, but alt 2 (exit) is good.\n\t\t\t\t\t\t\t\t\t\t \"(s:1 (e:1 a) ; <EOF>)\"}); // root s:1 is included to show ';' node\n\t}\n\n\t@Test\n\tpublic void testIncludeEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e ;\\n\" +\n\t\t\t\"e : ID DOT ID EOF\\n\"+\n\t\t\t\"  | ID DOT ID EOF\\n\"+\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\n\t\tint decision = 0;\n\t\ttestLookaheadTrees(lg, g, \"a.b\", \"s\", decision,\n\t\t\t\t\t\t   new String[] {\"(e:1 a . b <EOF>)\", \"(e:2 a . b <EOF>)\"});\n\t}\n\n\t@Test\n\tpublic void testCallLeftRecursiveRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(lexerText);\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : a BANG EOF;\\n\" +\n\t\t\t\"a : e SEMI \\n\" +\n\t\t\t\"  | ID SEMI \\n\" +\n\t\t\t\"  ;\" +\n\t\t\t\"e : e MULT e\\n\" +\n\t\t\t\"  | e PLUS e\\n\" +\n\t\t\t\"  | e DOT e\\n\" +\n\t\t\t\"  | ID\\n\" +\n\t\t\t\"  | INT\\n\" +\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\n\t\tint decision = 0;\n\t\ttestLookaheadTrees(lg, g, \"x;!\", \"s\", decision,\n\t\t\t\t\t\t   new String[] {\"(a:1 (e:4 x) ;)\",\n\t\t\t\t\t\t\t\t\t\t \"(a:2 x ;)\"}); // shouldn't include BANG, EOF\n\t\tdecision = 2; // (...)* in e\n\t\ttestLookaheadTrees(lg, g, \"x+1;!\", \"s\", decision,\n\t\t\t\t\t\t   new String[] {\"(e:1 (e:4 x) <error +>)\",\n\t\t\t\t\t\t\t\t\t\t \"(e:2 (e:4 x) + (e:5 1))\",\n\t\t\t\t\t\t\t\t\t\t \"(e:3 (e:4 x) <error +>)\"});\n\t}\n\n\tpublic void testLookaheadTrees(LexerGrammar lg, Grammar g,\n\t\t\t\t\t\t\t\t   String input,\n\t\t\t\t\t\t\t\t   String startRuleName,\n\t\t\t\t\t\t\t\t   int decision,\n\t\t\t\t\t\t\t\t   String[] expectedTrees)\n\t{\n\t\tint startRuleIndex = g.getRule(startRuleName).index;\n\t\tInterpreterTreeTextProvider nodeTextProvider =\n\t\t\t\t\tnew InterpreterTreeTextProvider(g.getRuleNames());\n\n\t\tLexerInterpreter lexEngine = lg.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\tGrammarParserInterpreter parser = g.createGrammarParserInterpreter(tokens);\n\t\tparser.setProfile(true);\n\t\tParseTree t = parser.parse(startRuleIndex);\n\n\t\tDecisionInfo decisionInfo = parser.getParseInfo().getDecisionInfo()[decision];\n\t\tLookaheadEventInfo lookaheadEventInfo = decisionInfo.SLL_MaxLookEvent;\n\n\t\tList<ParserRuleContext> lookaheadParseTrees =\n\t\t\tGrammarParserInterpreter.getLookaheadParseTrees(g, parser, tokens, startRuleIndex, lookaheadEventInfo.decision,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlookaheadEventInfo.startIndex, lookaheadEventInfo.stopIndex);\n\n\t\tassertEquals(expectedTrees.length, lookaheadParseTrees.size());\n\t\tfor (int i = 0; i < lookaheadParseTrees.size(); i++) {\n\t\t\tParserRuleContext lt = lookaheadParseTrees.get(i);\n\t\t\tassertEquals(expectedTrees[i], Trees.toStringTree(lt, nodeTextProvider));\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestParseTreeMatcher.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.InputMismatchException;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.NoViableAltException;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.runtime.tree.pattern.ParseTreeMatch;\nimport org.antlr.v4.runtime.tree.pattern.ParseTreePattern;\nimport org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher;\nimport org.antlr.v4.test.runtime.RunOptions;\nimport org.antlr.v4.test.runtime.Stage;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.states.JavaCompiledState;\nimport org.antlr.v4.test.runtime.states.JavaExecutedState;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.List;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.createOptionsForJavaToolTests;\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class TestParseTreeMatcher {\n\t@Test public void testChunking() {\n\t\tParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null);\n\t\tassertEquals(\"[ID, ' = ', expr, ' ;']\", m.split(\"<ID> = <expr> ;\").toString());\n\t\tassertEquals(\"[' ', ID, ' = ', expr]\", m.split(\" <ID> = <expr>\").toString());\n\t\tassertEquals(\"[ID, ' = ', expr]\", m.split(\"<ID> = <expr>\").toString());\n\t\tassertEquals(\"[expr]\", m.split(\"<expr>\").toString());\n\t\tassertEquals(\"['<x> foo']\", m.split(\"\\\\<x\\\\> foo\").toString());\n\t\tassertEquals(\"['foo <x> bar ', tag]\", m.split(\"foo \\\\<x\\\\> bar <tag>\").toString());\n\t}\n\n\t@Test public void testDelimiters() {\n\t\tParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null);\n\t\tm.setDelimiters(\"<<\", \">>\", \"$\");\n\t\tString result = m.split(\"<<ID>> = <<expr>> ;$<< ick $>>\").toString();\n\t\tassertEquals(\"[ID, ' = ', expr, ' ;<< ick >>']\", result);\n\t}\n\n\t@Test public void testInvertedTags() throws Exception {\n\t\tParseTreePatternMatcher m= new ParseTreePatternMatcher(null, null);\n\t\tString result = null;\n\t\ttry {\n\t\t\tm.split(\">expr<\");\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\tresult = iae.getMessage();\n\t\t}\n\t\tString expected = \"tag delimiters out of order in pattern: >expr<\";\n\t\tassertEquals(expected, result);\n\t}\n\n\t@Test public void testUnclosedTag() throws Exception {\n\t\tParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null);\n\t\tString result = null;\n\t\ttry {\n\t\t\tm.split(\"<expr hi mom\");\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\tresult = iae.getMessage();\n\t\t}\n\t\tString expected = \"unterminated tag in pattern: <expr hi mom\";\n\t\tassertEquals(expected, result);\n\t}\n\n\t@Test public void testExtraClose() throws Exception {\n\t\tParseTreePatternMatcher m = new ParseTreePatternMatcher(null, null);\n\t\tString result = null;\n\t\ttry {\n\t\t\tm.split(\"<expr> >\");\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\tresult = iae.getMessage();\n\t\t}\n\t\tString expected = \"missing start tag in pattern: <expr> >\";\n\t\tassertEquals(expected, result);\n\t}\n\n\t@Test public void testTokenizingPattern() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X1;\\n\" +\n\t\t\t\"s : ID '=' expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\t\tParseTreePatternMatcher m = getPatternMatcher(\"X1.g4\", grammar, \"X1Parser\", \"X1Lexer\", \"s\");\n\n\t\tList<? extends Token> tokens = m.tokenize(\"<ID> = <expr> ;\");\n\t\tassertEquals(\"[ID:3, [@-1,1:1='=',<1>,1:1], expr:7, [@-1,1:1=';',<2>,1:1]]\", tokens.toString());\n\t}\n\n\t@Test\n\tpublic void testCompilingPattern() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X2;\\n\" +\n\t\t\t\"s : ID '=' expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\t\tParseTreePatternMatcher m = getPatternMatcher(\"X2.g4\", grammar, \"X2Parser\", \"X2Lexer\", \"s\");\n\n\t\tParseTreePattern t = m.compile(\"<ID> = <expr> ;\", m.getParser().getRuleIndex(\"s\"));\n\t\tassertEquals(\"(s <ID> = (expr <expr>) ;)\", t.getPatternTree().toStringTree(m.getParser()));\n\t}\n\n\t@Test\n\tpublic void testCompilingPatternConsumesAllTokens() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X2;\\n\" +\n\t\t\t\"s : ID '=' expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\t\tParseTreePatternMatcher m = getPatternMatcher(\"X2.g4\", grammar, \"X2Parser\", \"X2Lexer\", \"s\");\n\n\t\tboolean failed = false;\n\t\ttry {\n\t\t\tm.compile(\"<ID> = <expr> ; extra\", m.getParser().getRuleIndex(\"s\"));\n\t\t}\n\t\tcatch (ParseTreePatternMatcher.StartRuleDoesNotConsumeFullPattern e) {\n\t\t\tfailed = true;\n\t\t}\n\t\tassertTrue(failed);\n\t}\n\n\t@Test\n\tpublic void testPatternMatchesStartRule() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X2;\\n\" +\n\t\t\t\"s : ID '=' expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\t\tParseTreePatternMatcher m = getPatternMatcher(\"X2.g4\", grammar, \"X2Parser\", \"X2Lexer\", \"s\");\n\n\t\tboolean failed = false;\n\t\ttry {\n\t\t\tm.compile(\"<ID> ;\", m.getParser().getRuleIndex(\"s\"));\n\t\t}\n\t\tcatch (InputMismatchException e) {\n\t\t\tfailed = true;\n\t\t}\n\t\tassertTrue(failed);\n\t}\n\n\t@Test\n\tpublic void testPatternMatchesStartRule2() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X2;\\n\" +\n\t\t\t\"s : ID '=' expr ';' | expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\t\tParseTreePatternMatcher m = getPatternMatcher(\"X2.g4\", grammar, \"X2Parser\", \"X2Lexer\", \"s\");\n\n\t\tboolean failed = false;\n\t\ttry {\n\t\t\tm.compile(\"<ID> <ID> ;\", m.getParser().getRuleIndex(\"s\"));\n\t\t}\n\t\tcatch (NoViableAltException e) {\n\t\t\tfailed = true;\n\t\t}\n\t\tassertTrue(failed);\n\t}\n\n\t@Test\n\tpublic void testHiddenTokensNotSeenByTreePatternParser() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X2;\\n\" +\n\t\t\t\"s : ID '=' expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> channel(HIDDEN) ;\\n\";\n\t\tParseTreePatternMatcher m = getPatternMatcher(\"X2.g4\", grammar, \"X2Parser\", \"X2Lexer\", \"s\");\n\n\t\tParseTreePattern t = m.compile(\"<ID> = <expr> ;\", m.getParser().getRuleIndex(\"s\"));\n\t\tassertEquals(\"(s <ID> = (expr <expr>) ;)\", t.getPatternTree().toStringTree(m.getParser()));\n\t}\n\n\t@Test\n\tpublic void testCompilingMultipleTokens() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X2;\\n\" +\n\t\t\t\"s : ID '=' ID ';' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\t\tParseTreePatternMatcher m =\tgetPatternMatcher(\"X2.g4\", grammar, \"X2Parser\", \"X2Lexer\", \"s\");\n\n\t\tParseTreePattern t = m.compile(\"<ID> = <ID> ;\", m.getParser().getRuleIndex(\"s\"));\n\t\tString results = t.getPatternTree().toStringTree(m.getParser());\n\t\tString expected = \"(s <ID> = <ID> ;)\";\n\t\tassertEquals(expected, results);\n\t}\n\n\t@Test public void testIDNodeMatches() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X3;\\n\" +\n\t\t\t\"s : ID ';' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"x ;\";\n\t\tString pattern = \"<ID>;\";\n\t\tcheckPatternMatch(grammar, \"s\", input, pattern, \"X3\");\n\t}\n\n\t@Test public void testIDNodeWithLabelMatches() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X8;\\n\" +\n\t\t\t\"s : ID ';' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"x ;\";\n\t\tString pattern = \"<id:ID>;\";\n\t\tParseTreeMatch m = checkPatternMatch(grammar, \"s\", input, pattern, \"X8\");\n\t\tassertEquals(\"{ID=[x], id=[x]}\", m.getLabels().toString());\n\t\tassertNotNull(m.get(\"id\"));\n\t\tassertNotNull(m.get(\"ID\"));\n\t\tassertEquals(\"x\", m.get(\"id\").getText());\n\t\tassertEquals(\"x\", m.get(\"ID\").getText());\n\t\tassertEquals(\"[x]\", m.getAll(\"id\").toString());\n\t\tassertEquals(\"[x]\", m.getAll(\"ID\").toString());\n\n\t\tassertNull(m.get(\"undefined\"));\n\t\tassertEquals(\"[]\", m.getAll(\"undefined\").toString());\n\t}\n\n\t@Test public void testLabelGetsLastIDNode() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X9;\\n\" +\n\t\t\t\"s : ID ID ';' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"x y;\";\n\t\tString pattern = \"<id:ID> <id:ID>;\";\n\t\tParseTreeMatch m = checkPatternMatch(grammar, \"s\", input, pattern, \"X9\");\n\t\tassertEquals(\"{ID=[x, y], id=[x, y]}\", m.getLabels().toString());\n\t\tassertNotNull(m.get(\"id\"));\n\t\tassertNotNull(m.get(\"ID\"));\n\t\tassertEquals(\"y\", m.get(\"id\").getText());\n\t\tassertEquals(\"y\", m.get(\"ID\").getText());\n\t\tassertEquals(\"[x, y]\", m.getAll(\"id\").toString());\n\t\tassertEquals(\"[x, y]\", m.getAll(\"ID\").toString());\n\n\t\tassertNull(m.get(\"undefined\"));\n\t\tassertEquals(\"[]\", m.getAll(\"undefined\").toString());\n\t}\n\n\t@Test public void testIDNodeWithMultipleLabelMatches() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X7;\\n\" +\n\t\t\t\"s : ID ID ID ';' ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"x y z;\";\n\t\tString pattern = \"<a:ID> <b:ID> <a:ID>;\";\n\t\tParseTreeMatch m = checkPatternMatch(grammar, \"s\", input, pattern, \"X7\");\n\t\tassertEquals(\"{ID=[x, y, z], a=[x, z], b=[y]}\", m.getLabels().toString());\n\t\tassertNotNull(m.get(\"a\")); // get first\n\t\tassertNotNull(m.get(\"b\"));\n\t\tassertNotNull(m.get(\"ID\"));\n\t\tassertEquals(\"z\", m.get(\"a\").getText());\n\t\tassertEquals(\"y\", m.get(\"b\").getText());\n\t\tassertEquals(\"z\", m.get(\"ID\").getText()); // get last\n\t\tassertEquals(\"[x, z]\", m.getAll(\"a\").toString());\n\t\tassertEquals(\"[y]\", m.getAll(\"b\").toString());\n\t\tassertEquals(\"[x, y, z]\", m.getAll(\"ID\").toString()); // ordered\n\n\t\tassertEquals(\"xyz;\", m.getTree().getText()); // whitespace stripped by lexer\n\n\t\tassertNull(m.get(\"undefined\"));\n\t\tassertEquals(\"[]\", m.getAll(\"undefined\").toString());\n\t}\n\n\t@Test public void testTokenAndRuleMatch() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X4;\\n\" +\n\t\t\t\"s : ID '=' expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"x = 99;\";\n\t\tString pattern = \"<ID> = <expr> ;\";\n\t\tcheckPatternMatch(grammar, \"s\", input, pattern, \"X4\");\n\t}\n\n\t@Test public void testTokenTextMatch() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X4;\\n\" +\n\t\t\t\"s : ID '=' expr ';' ;\\n\" +\n\t\t\t\"expr : ID | INT ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"x = 0;\";\n\t\tString pattern = \"<ID> = 1;\";\n\t\tboolean invertMatch = true; // 0!=1\n\t\tcheckPatternMatch(grammar, \"s\", input, pattern, \"X4\", invertMatch);\n\n\t\tinput = \"x = 0;\";\n\t\tpattern = \"<ID> = 0;\";\n\t\tinvertMatch = false;\n\t\tcheckPatternMatch(grammar, \"s\", input, pattern, \"X4\", invertMatch);\n\n\t\tinput = \"x = 0;\";\n\t\tpattern = \"x = 0;\";\n\t\tinvertMatch = false;\n\t\tcheckPatternMatch(grammar, \"s\", input, pattern, \"X4\", invertMatch);\n\n\t\tinput = \"x = 0;\";\n\t\tpattern = \"y = 0;\";\n\t\tinvertMatch = true;\n\t\tcheckPatternMatch(grammar, \"s\", input, pattern, \"X4\", invertMatch);\n\t}\n\n\t@Test public void testAssign() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X5;\\n\" +\n\t\t\t\"s   : expr ';'\\n\" +\n\t\t\t//\"    | 'return' expr ';'\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"expr: expr '.' ID\\n\" +\n\t\t\t\"    | expr '*' expr\\n\" +\n\t\t\t\"    | expr '=' expr\\n\" +\n\t\t\t\"    | ID\\n\" +\n\t\t\t\"    | INT\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"x = 99;\";\n\t\tString pattern = \"<ID> = <expr>;\";\n\t\tcheckPatternMatch(grammar, \"s\", input, pattern, \"X5\");\n\t}\n\n\t@Test public void testLRecursiveExpr() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar X6;\\n\" +\n\t\t\t\"s   : expr ';'\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"expr: expr '.' ID\\n\" +\n\t\t\t\"    | expr '*' expr\\n\" +\n\t\t\t\"    | expr '=' expr\\n\" +\n\t\t\t\"    | ID\\n\" +\n\t\t\t\"    | INT\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"ID : [a-z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"WS : [ \\\\r\\\\n\\\\t]+ -> skip ;\\n\";\n\n\t\tString input = \"3*4*5\";\n\t\tString pattern = \"<expr> * <expr> * <expr>\";\n\t\tcheckPatternMatch(grammar, \"expr\", input, pattern, \"X6\");\n\t}\n\n\tprivate static ParseTreeMatch checkPatternMatch(String grammar, String startRule,\n\t\t\t\t\t\t\t\t\t\t\tString input, String pattern,\n\t\t\t\t\t\t\t\t\t\t\tString grammarName)\n\t\tthrows Exception\n\t{\n\t\treturn checkPatternMatch(grammar, startRule, input, pattern, grammarName, false);\n\t}\n\n\tprivate static ParseTreeMatch checkPatternMatch(String grammar, String startRule,\n\t\t\t\t\t\t\t\t\t\t\tString input, String pattern,\n\t\t\t\t\t\t\t\t\t\t\tString grammarName, boolean invertMatch)\n\t\tthrows Exception\n\t{\n\t\tString grammarFileName = grammarName+\".g4\";\n\t\tString parserName = grammarName+\"Parser\";\n\t\tString lexerName = grammarName+\"Lexer\";\n\t\tRunOptions runOptions = createOptionsForJavaToolTests(grammarFileName, grammar, parserName, lexerName,\n\t\t\t\tfalse, false, startRule, input,\n\t\t\t\tfalse, false, Stage.Execute);\n\t\ttry (JavaRunner runner = new JavaRunner()) {\n\t\t\tJavaExecutedState executedState = (JavaExecutedState)runner.run(runOptions);\n\t\t\tJavaCompiledState compiledState = (JavaCompiledState)executedState.previousState;\n\t\t\tParser parser = compiledState.initializeDummyLexerAndParser().b;\n\n\t\t\tParseTreePattern p = parser.compileParseTreePattern(pattern, parser.getRuleIndex(startRule));\n\n\t\t\tParseTreeMatch match = p.match(executedState.parseTree);\n\t\t\tboolean matched = match.succeeded();\n\t\t\tif ( invertMatch ) assertFalse(matched);\n\t\t\telse assertTrue(matched);\n\t\t\treturn match;\n\t\t}\n\t}\n\n\tprivate static ParseTreePatternMatcher getPatternMatcher(\n\t\t\tString grammarFileName, String grammar, String parserName, String lexerName, String startRule\n\t) throws Exception {\n\t\tRunOptions runOptions = createOptionsForJavaToolTests(grammarFileName, grammar, parserName, lexerName,\n\t\t\t\tfalse, false, startRule, null,\n\t\t\t\tfalse, false, Stage.Compile);\n\t\ttry (JavaRunner runner = new JavaRunner()) {\n\t\t\tJavaCompiledState compiledState = (JavaCompiledState) runner.run(runOptions);\n\n\t\t\tPair<Lexer, Parser> lexerParserPair = compiledState.initializeDummyLexerAndParser();\n\n\t\t\treturn new ParseTreePatternMatcher(lexerParserPair.a, lexerParserPair.b);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestParserExec.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.junit.jupiter.api.Disabled;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.io.TempDir;\n\nimport java.nio.file.Path;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.*;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/** Test parser execution.\n *\n *  For the non-greedy stuff, the rule is that .* or any other non-greedy loop\n *  (any + or * loop that has an alternative with '.' in it is automatically\n *  non-greedy) never sees past the end of the rule containing that loop.\n *  There is no automatic way to detect when the exit branch of a non-greedy\n *  loop has seen enough input to determine how much the loop should consume\n *  yet still allow matching the entire input. Of course, this is extremely\n *  inefficient, particularly for things like\n *\n *     block : '{' (block|.)* '}' ;\n *\n *  that need only see one symbol to know when it hits a '}'. So, I\n *  came up with a practical solution.  During prediction, the ATN\n *  simulator never fall off the end of a rule to compute the global\n *  FOLLOW. Instead, we terminate the loop, choosing the exit branch.\n *  Otherwise, we predict to reenter the loop.  For example, input\n *  \"{ foo }\" will allow the loop to match foo, but that's it. During\n *  prediction, the ATN simulator will see that '}' reaches the end of a\n *  rule that contains a non-greedy loop and stop prediction. It will choose\n *  the exit branch of the inner loop. So, the way in which you construct\n *  the rule containing a non-greedy loop dictates how far it will scan ahead.\n *  Include everything after the non-greedy loop that you know it must scan\n *  in order to properly make a prediction decision. these beasts are tricky,\n *  so be careful. don't liberally sprinkle them around your code.\n *\n *  To simulate filter mode, use ( .* (pattern1|pattern2|...) )*\n *\n *  Nongreedy loops match as much input as possible while still allowing\n *  the remaining input to match.\n */\npublic class TestParserExec {\n\t/**\n\t * This is a regression test for antlr/antlr4#118.\n\t * https://github.com/antlr/antlr4/issues/118\n\t */\n\t@Disabled(\"Performance impact of passing this test may not be worthwhile\")\n\t// TODO: port to test framework (not ported because test currently fails)\n\t@Test public void testStartRuleWithoutEOF() {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\"+\n\t\t\t\"s @after {dumpDFA();}\\n\" +\n\t\t\t\"  : ID | ID INT ID ;\\n\" +\n\t\t\t\"ID : 'a'..'z'+ ;\\n\"+\n\t\t\t\"INT : '0'..'9'+ ;\\n\"+\n\t\t\t\"WS : (' '|'\\\\t'|'\\\\n')+ -> skip ;\\n\";\n\t\tExecutedState executedState = execParser(\"T.g4\", grammar, \"TParser\", \"TLexer\",\n\t\t\t\t\"s\", \"abc 34\", true);\n\t\tString expecting =\n\t\t\t\"Decision 0:\\n\" +\n\t\t\t\"s0-ID->s1\\n\" +\n\t\t\t\"s1-INT->s2\\n\" +\n\t\t\t\"s2-EOF->:s3=>1\\n\"; // Must point at accept state\n\t\tassertEquals(expecting, executedState.output);\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#588 \"ClassCastException during\n\t * semantic predicate handling\".\n\t * https://github.com/antlr/antlr4/issues/588\n\t */\n\t// TODO: port to test framework (can we simplify the Psl grammar?)\n\t@Test public void testFailedPredicateExceptionState() throws Exception {\n\t\tString grammar = load(\"Psl.g4\");\n\t\tExecutedState executedState = execParser(\"Psl.g4\", grammar,\n\t\t\t\t\"PslParser\", \"PslLexer\", \"floating_constant\", \" . 234\", false);\n\t\tassertEquals(\"\", executedState.output);\n\t\tassertEquals(\"line 1:6 rule floating_constant DEC:A floating-point constant cannot have internal white space\\n\", executedState.errors);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#563 \"Inconsistent token\n\t * handling in ANTLR4\".\n\t * https://github.com/antlr/antlr4/issues/563\n\t */\n\t// TODO: port to test framework (missing templates)\n\t@Test public void testAlternateQuotes(@TempDir Path tempDir) {\n\t\tString lexerGrammar =\n\t\t\t\"lexer grammar ModeTagsLexer;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"// Default mode rules (the SEA)\\n\" +\n\t\t\t\"OPEN  : '«'     -> mode(ISLAND) ;       // switch to ISLAND mode\\n\" +\n\t\t\t\"TEXT  : ~'«'+ ;                         // clump all text together\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"mode ISLAND;\\n\" +\n\t\t\t\"CLOSE : '»'     -> mode(DEFAULT_MODE) ; // back to SEA mode \\n\" +\n\t\t\t\"SLASH : '/' ;\\n\" +\n\t\t\t\"ID    : [a-zA-Z]+ ;                     // match/send ID in tag to parser\\n\";\n\t\tString parserGrammar =\n\t\t\t\"parser grammar ModeTagsParser;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"options { tokenVocab=ModeTagsLexer; } // use tokens from ModeTagsLexer.g4\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"file: (tag | TEXT)* ;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"tag : '«' ID '»'\\n\" +\n\t\t\t\"    | '«' '/' ID '»'\\n\" +\n\t\t\t\"    ;\";\n\n\t\texecLexer(\"ModeTagsLexer.g4\", lexerGrammar, \"ModeTagsLexer\", \"\",\n\t\t\t\ttempDir, true);\n\t\tExecutedState executedState = execParser(\"ModeTagsParser.g4\", parserGrammar,\n\t\t\t\t\"ModeTagsParser\", \"ModeTagsLexer\",\n\t\t\t\t\"file\", \"\", false,\n\t\t\t\ttempDir);\n\t\tassertEquals(\"\", executedState.output);\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#672 \"Initialization failed in\n\t * locals\".\n\t * https://github.com/antlr/antlr4/issues/672\n\t */\n\t// TODO: port to test framework (missing templates)\n\t@Test public void testAttributeValueInitialization() {\n\t\tString grammar =\n\t\t\t\"grammar Data; \\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"file : group+ EOF; \\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"group: INT sequence {outStream.println($sequence.values.size());} ; \\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"sequence returns [List<Integer> values = new ArrayList<Integer>()] \\n\" +\n\t\t\t\"  locals[List<Integer> localValues = new ArrayList<Integer>()]\\n\" +\n\t\t\t\"         : (INT {$localValues.add($INT.int);})* {$values.addAll($localValues);}\\n\" +\n\t\t\t\"; \\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"INT : [0-9]+ ; // match integers \\n\" +\n\t\t\t\"WS : [ \\\\t\\\\n\\\\r]+ -> skip ; // toss out all whitespace\\n\";\n\n\t\tString input = \"2 9 10 3 1 2 3\";\n\t\tExecutedState executedState = execParser(\"Data.g4\", grammar,\n\t\t\t\t\"DataParser\", \"DataLexer\", \"file\", input, false);\n\t\tassertEquals(\"6\\n\", executedState.output);\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n\n\t@Test public void testCaseInsensitiveInCombinedGrammar() throws Exception {\n\t\tString grammar =\n\t\t\t\t\"grammar CaseInsensitiveGrammar;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"e\\n\" +\n\t\t\t\t\"    : ID\\n\" +\n\t\t\t\t\"    | 'not' e\\n\" +\n\t\t\t\t\"    | e 'and' e\\n\" +\n\t\t\t\t\"    | 'new' ID '(' e ')'\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"ID: [a-z_][a-z_0-9]*;\\n\" +\n\t\t\t\t\"WS: [ \\\\t\\\\n\\\\r]+ -> skip;\";\n\n\t\tString input = \"NEW Abc (Not a AND not B)\";\n\t\tExecutedState executedState = execParser(\n\t\t\t\t\"CaseInsensitiveGrammar.g4\", grammar,\n\t\t\t\t\"CaseInsensitiveGrammarParser\", \"CaseInsensitiveGrammarLexer\",\n\t\t\t\t\"e\", input, false);\n\t\tassertEquals(\"\", executedState.output);\n\t\tassertEquals(\"\", executedState.errors);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestParserInterpreter.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n\npublic class TestParserInterpreter {\n\t@Test public void testEmptyStartRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s :  ;\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"\", \"s\");\n\t\ttestInterp(lg, g, \"s\", \"a\", \"s\");\n\t}\n\n\t@Test public void testA() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : A ;\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"a\", \"(s a)\");\n\t\tassertEquals(\"0..0\", t.getSourceInterval().toString());\n\t}\n\n\t@Test public void testEOF() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : A EOF ;\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"a\", \"(s a <EOF>)\");\n\t\tassertEquals(\"0..1\", t.getSourceInterval().toString());\n\t}\n\n\t@Test public void testEOFInChild() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : x ;\\n\" +\n\t\t\t\"x : A EOF ;\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"a\", \"(s (x a <EOF>))\");\n\t\tassertEquals(\"0..1\", t.getSourceInterval().toString());\n\t\tassertEquals(\"0..1\", t.getChild(0).getSourceInterval().toString());\n\t}\n\n\t@Test public void testEmptyRuleAfterEOFInChild() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : x y;\\n\" +\n\t\t\t\"x : A EOF ;\\n\" +\n\t\t\t\"y : ;\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"a\", \"(s (x a <EOF>) y)\");\n\t\tassertEquals(\"0..1\", t.getSourceInterval().toString()); // s\n\t\tassertEquals(\"0..1\", t.getChild(0).getSourceInterval().toString()); // x\n// unspecified\t\tassertEquals(\"1..0\", t.getChild(1).getSourceInterval().toString()); // y\n\t}\n\n\t@Test public void testEmptyRuleAfterJustEOFInChild() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : x y;\\n\" +\n\t\t\t\"x : EOF ;\\n\" +\n\t\t\t\"y : ;\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"\", \"(s (x <EOF>) y)\");\n\t\tassertEquals(\"0..0\", t.getSourceInterval().toString()); // s\n\t\tassertEquals(\"0..0\", t.getChild(0).getSourceInterval().toString()); // x\n\t\t// this next one is a weird special case where somebody tries to match beyond in the file\n// unspecified\t\tassertEquals(\"0..-1\", t.getChild(1).getSourceInterval().toString()); // y\n\t}\n\n\t@Test public void testEmptyInput() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : x EOF ;\\n\" +\n\t\t\t\"x : ;\\n\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"\", \"(s x <EOF>)\");\n\t\tassertEquals(\"0..0\", t.getSourceInterval().toString()); // s\n\t\tassertEquals(\"0..-1\", t.getChild(0).getSourceInterval().toString()); // x\n\t}\n\n\t@Test public void testEmptyInputWithCallsAfter() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : x y ;\\n\" +\n\t\t\t\"x : EOF ;\\n\" +\n\t\t\t\"y : z ;\\n\" +\n\t\t\t\"z : ;\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"\", \"(s (x <EOF>) (y z))\");\n\t\tassertEquals(\"0..0\", t.getSourceInterval().toString()); // s\n\t\tassertEquals(\"0..0\", t.getChild(0).getSourceInterval().toString()); // x\n// unspecified\t\tassertEquals(\"0..-1\", t.getChild(1).getSourceInterval().toString()); // x\n\t}\n\n\t@Test public void testEmptyFirstRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : x A ;\\n\" +\n\t\t\t\"x : ;\\n\",\n\t\t\tlg);\n\n\t\tParseTree t = testInterp(lg, g, \"s\", \"a\", \"(s x a)\");\n\t\tassertEquals(\"0..0\", t.getSourceInterval().toString()); // s\n\t\t// This gets an empty interval because the stop token is null for x\n\t\tassertEquals(\"0..-1\", t.getChild(0).getSourceInterval().toString()); // x\n\t}\n\n\t@Test public void testAorB() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"s : A{;} | B ;\",\n\t\t\tlg);\n\t\ttestInterp(lg, g, \"s\", \"a\", \"(s a)\");\n\t\ttestInterp(lg, g, \"s\", \"b\", \"(s b)\");\n\t}\n\n\t@Test public void testCall() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"s : t C ;\\n\" +\n\t\t\t\"t : A{;} | B ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"ac\", \"(s (t a) c)\");\n\t\ttestInterp(lg, g, \"s\", \"bc\", \"(s (t b) c)\");\n\t}\n\n\t@Test public void testCall2() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"s : t C ;\\n\" +\n\t\t\t\"t : u ;\\n\" +\n\t\t\t\"u : A{;} | B ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"ac\", \"(s (t (u a)) c)\");\n\t\ttestInterp(lg, g, \"s\", \"bc\", \"(s (t (u b)) c)\");\n\t}\n\n\t@Test public void testOptionalA() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : A? B ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"b\", \"(s b)\");\n\t\ttestInterp(lg, g, \"s\", \"ab\", \"(s a b)\");\n\t}\n\n\t@Test public void testOptionalAorB() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : (A{;}|B)? C ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"c\", \"(s c)\");\n\t\ttestInterp(lg, g, \"s\", \"ac\", \"(s a c)\");\n\t\ttestInterp(lg, g, \"s\", \"bc\", \"(s b c)\");\n\t}\n\n\t@Test public void testStarA() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : A* B ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"b\", \"(s b)\");\n\t\ttestInterp(lg, g, \"s\", \"ab\", \"(s a b)\");\n\t\ttestInterp(lg, g, \"s\", \"aaaaaab\", \"(s a a a a a a b)\");\n\t}\n\n\t@Test public void testStarAorB() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : (A{;}|B)* C ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"c\", \"(s c)\");\n\t\ttestInterp(lg, g, \"s\", \"ac\", \"(s a c)\");\n\t\ttestInterp(lg, g, \"s\", \"bc\", \"(s b c)\");\n\t\ttestInterp(lg, g, \"s\", \"abaaabc\", \"(s a b a a a b c)\");\n\t\ttestInterp(lg, g, \"s\", \"babac\", \"(s b a b a c)\");\n\t}\n\n\t@Test public void testLeftRecursion() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"PLUS : '+' ;\\n\" +\n\t\t\t\"MULT : '*' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e ;\\n\" +\n\t\t\t\"e : e MULT e\\n\" +\n\t\t\t\"  | e PLUS e\\n\" +\n\t\t\t\"  | A\\n\" +\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"s\", \"a\", \t\"(s (e a))\");\n\t\ttestInterp(lg, g, \"s\", \"a+a\", \t\"(s (e (e a) + (e a)))\");\n\t\ttestInterp(lg, g, \"s\", \"a*a\", \t\"(s (e (e a) * (e a)))\");\n\t\ttestInterp(lg, g, \"s\", \"a+a+a\", \"(s (e (e (e a) + (e a)) + (e a)))\");\n\t\ttestInterp(lg, g, \"s\", \"a*a+a\", \"(s (e (e (e a) * (e a)) + (e a)))\");\n\t\ttestInterp(lg, g, \"s\", \"a+a*a\", \"(s (e (e a) + (e (e a) * (e a))))\");\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#461.\n\t * https://github.com/antlr/antlr4/issues/461\n\t */\n\t@Test public void testLeftRecursiveStartRule() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\" +\n\t\t\t\"C : 'c' ;\\n\" +\n\t\t\t\"PLUS : '+' ;\\n\" +\n\t\t\t\"MULT : '*' ;\\n\");\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"s : e ;\\n\" +\n\t\t\t\"e : e MULT e\\n\" +\n\t\t\t\"  | e PLUS e\\n\" +\n\t\t\t\"  | A\\n\" +\n\t\t\t\"  ;\\n\",\n\t\t\tlg);\n\n\t\ttestInterp(lg, g, \"e\", \"a\", \t\"(e a)\");\n\t\ttestInterp(lg, g, \"e\", \"a+a\", \t\"(e (e a) + (e a))\");\n\t\ttestInterp(lg, g, \"e\", \"a*a\", \t\"(e (e a) * (e a))\");\n\t\ttestInterp(lg, g, \"e\", \"a+a+a\", \"(e (e (e a) + (e a)) + (e a))\");\n\t\ttestInterp(lg, g, \"e\", \"a*a+a\", \"(e (e (e a) * (e a)) + (e a))\");\n\t\ttestInterp(lg, g, \"e\", \"a+a*a\", \"(e (e a) + (e (e a) * (e a)))\");\n\t}\n\n\t@Test public void testCaseInsensitiveTokensInParser() throws Exception {\n\t\tLexerGrammar lg = new LexerGrammar(\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"NOT: 'not';\\n\" +\n\t\t\t\t\"AND: 'and';\\n\" +\n\t\t\t\t\"NEW: 'new';\\n\" +\n\t\t\t\t\"LB:  '(';\\n\" +\n\t\t\t\t\"RB:  ')';\\n\" +\n\t\t\t\t\"ID: [a-z_][a-z_0-9]*;\\n\" +\n\t\t\t\t\"WS: [ \\\\t\\\\n\\\\r]+ -> skip;\");\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"e\\n\" +\n\t\t\t\t\"    : ID\\n\" +\n\t\t\t\t\"    | 'not' e\\n\" +\n\t\t\t\t\"    | e 'and' e\\n\" +\n\t\t\t\t\"    | 'new' ID '(' e ')'\\n\" +\n\t\t\t\t\"    ;\", lg);\n\n\t\ttestInterp(lg, g, \"e\", \"NEW Abc (Not a AND not B)\", \"(e NEW Abc ( (e (e Not (e a)) AND (e not (e B))) ))\");\n\t}\n\n\tParseTree testInterp(LexerGrammar lg, Grammar g,\n\t\t\t\t\tString startRule, String input,\n\t\t\t\t\tString expectedParseTree)\n\t{\n\t\tLexerInterpreter lexEngine = lg.createLexerInterpreter(new ANTLRInputStream(input));\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\tParserInterpreter parser = g.createParserInterpreter(tokens);\n\t\tParseTree t = parser.parse(g.rules.get(startRule).index);\n\t\tassertEquals(expectedParseTree, t.toStringTree(parser));\n\t\treturn t;\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestParserProfiler.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.RecognitionException;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.atn.DecisionInfo;\nimport org.antlr.v4.test.runtime.RunOptions;\nimport org.antlr.v4.test.runtime.Stage;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.antlr.v4.tool.Rule;\nimport org.junit.jupiter.api.Disabled;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.Arrays;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.createOptionsForJavaToolTests;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n@SuppressWarnings(\"unused\")\npublic class TestParserProfiler {\n\tfinal static LexerGrammar lg;\n\n\tstatic {\n\t\ttry {\n\t\t\tlg = new LexerGrammar(\n\t\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\t\t\t\"WS : [ \\\\r\\\\t\\\\n]+ -> channel(HIDDEN) ;\\n\" +\n\t\t\t\t\t\t\t\"SEMI : ';' ;\\n\" +\n\t\t\t\t\t\t\t\"DOT : '.' ;\\n\" +\n\t\t\t\t\t\t\t\"ID : [a-zA-Z]+ ;\\n\" +\n\t\t\t\t\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\t\t\t\t\"PLUS : '+' ;\\n\" +\n\t\t\t\t\t\t\t\"MULT : '*' ;\\n\");\n\t\t} catch (RecognitionException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t@Test public void testLL1() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"s : ';'{}\\n\" +\n\t\t\t\t\"  | '.'\\n\" +\n\t\t\t\t\"  ;\\n\",\n\t\t\t\tlg);\n\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"s\", \";\");\n\t\tassertEquals(1, info.length);\n\t\tString expecting =\n\t\t\t\t\"{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=1, \" +\n\t\t\t\t\"SLL_ATNTransitions=1, SLL_DFATransitions=0, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}\";\n\t\tassertEquals(expecting, info[0].toString());\n\t}\n\n\t@Test public void testLL2() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"s : ID ';'{}\\n\" +\n\t\t\t\t\"  | ID '.'\\n\" +\n\t\t\t\t\"  ;\\n\",\n\t\t\t\tlg);\n\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"s\", \"xyz;\");\n\t\tassertEquals(1, info.length);\n\t\tString expecting =\n\t\t\t\t\"{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=2, \" +\n\t\t\t\t\"SLL_ATNTransitions=2, SLL_DFATransitions=0, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}\";\n\t\tassertEquals(expecting, info[0].toString());\n\t}\n\n\t@Test public void testRepeatedLL2() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"s : ID ';'{}\\n\" +\n\t\t\t\t\"  | ID '.'\\n\" +\n\t\t\t\t\"  ;\\n\",\n\t\t\t\tlg);\n\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"s\", \"xyz;\", \"abc;\");\n\t\tassertEquals(1, info.length);\n\t\tString expecting =\n\t\t\t\t\"{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=4, \" +\n\t\t\t\t\"SLL_ATNTransitions=2, SLL_DFATransitions=2, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}\";\n\t\tassertEquals(expecting, info[0].toString());\n\t}\n\n\t@Test public void test3xLL2() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"s : ID ';'{}\\n\" +\n\t\t\t\t\"  | ID '.'\\n\" +\n\t\t\t\t\"  ;\\n\",\n\t\t\t\tlg);\n\n\t\t// The '.' vs ';' causes another ATN transition\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"s\", \"xyz;\", \"abc;\", \"z.\");\n\t\tassertEquals(1, info.length);\n\t\tString expecting =\n\t\t\t\t\"{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=6, \" +\n\t\t\t\t\"SLL_ATNTransitions=3, SLL_DFATransitions=3, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}\";\n\t\tassertEquals(expecting, info[0].toString());\n\t}\n\n\t@Test public void testOptional() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"s : ID ('.' ID)? ';'\\n\" +\n\t\t\t\t\"  | ID INT \\n\" +\n\t\t\t\t\"  ;\\n\",\n\t\t\t\tlg);\n\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"s\", \"a.b;\");\n\t\tassertEquals(2, info.length);\n\t\tString expecting =\n\t\t\t\"[{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=1, \" +\n\t\t\t  \"SLL_ATNTransitions=1, SLL_DFATransitions=0, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}, \" +\n\t\t\t \"{decision=1, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=2, \" +\n\t\t\t  \"SLL_ATNTransitions=2, SLL_DFATransitions=0, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}]\";\n\t\tassertEquals(expecting, Arrays.toString(info));\n\t}\n\n\t@Test public void test2xOptional() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"s : ID ('.' ID)? ';'\\n\" +\n\t\t\t\t\"  | ID INT \\n\" +\n\t\t\t\t\"  ;\\n\",\n\t\t\t\tlg);\n\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"s\", \"a.b;\", \"a.b;\");\n\t\tassertEquals(2, info.length);\n\t\tString expecting =\n\t\t\t\"[{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=2, \" +\n\t\t\t  \"SLL_ATNTransitions=1, SLL_DFATransitions=1, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}, \" +\n\t\t\t \"{decision=1, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=4, \" +\n\t\t\t  \"SLL_ATNTransitions=2, SLL_DFATransitions=2, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}]\";\n\t\tassertEquals(expecting, Arrays.toString(info));\n\t}\n\n\t@Test public void testContextSensitivity() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\"parser grammar T;\\n\"+\n\t\t\t\"a : '.' e ID \\n\" +\n\t\t\t\"  | ';' e INT ID ;\\n\" +\n\t\t\t\"e : INT | ;\\n\",\n\t\t\tlg);\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"a\", \"; 1 x\");\n\t\tassertEquals(2, info.length);\n\t\tString expecting =\n\t\t\t\"{decision=1, contextSensitivities=1, errors=0, ambiguities=0, SLL_lookahead=3, SLL_ATNTransitions=2, SLL_DFATransitions=0, LL_Fallback=1, LL_lookahead=3, LL_ATNTransitions=2}\";\n\t\tassertEquals(expecting, info[1].toString());\n\t}\n\n\t@Disabled\n\t@Test public void testSimpleLanguage() throws Exception {\n\t\tGrammar g = new Grammar(TestXPath.grammar);\n\t\tString input =\n\t\t\t\"def f(x,y) { x = 3+4*1*1/5*1*1+1*1+1; y; ; }\\n\" +\n\t\t\t\"def g(x,a,b,c,d,e) { return 1+2*x; }\\n\"+\n\t\t\t\"def h(x) { a=3; x=0+1; return a*x; }\\n\";\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(g.getImplicitLexer(), g, \"prog\", input);\n\t\tString expecting =\n\t\t\t\"[{decision=0, contextSensitivities=1, errors=0, ambiguities=0, SLL_lookahead=3, \" +\n\t\t\t\"SLL_ATNTransitions=2, SLL_DFATransitions=0, LL_Fallback=1, LL_ATNTransitions=1}]\";\n\n\n\t\tassertEquals(expecting, Arrays.toString(info));\n\t\tassertEquals(1, info.length);\n\t}\n\n\t@Disabled\n\t@Test public void testDeepLookahead() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\t\"s : e ';'\\n\" +\n\t\t\t\t\"  | e '.' \\n\" +\n\t\t\t\t\"  ;\\n\" +\n\t\t\t\t\"e : (ID|INT) ({true}? '+' e)*\\n\" +       // d=1 entry, d=2 bypass\n\t\t\t\t\"  ;\\n\",\n\t\t\t\tlg);\n\n\t\t// pred forces to\n\t\t// ambig and ('+' e)* tail recursion forces lookahead to fall out of e\n\t\t// any non-precedence predicates are always evaluated as true by the interpreter\n\t\tDecisionInfo[] info = interpAndGetDecisionInfo(lg, g, \"s\", \"a+b+c;\");\n\t\t// at \"+b\" it uses k=1 and enters loop then calls e for b...\n\t\t// e matches and d=2 uses \"+c;\" for k=3\n\t\tassertEquals(2, info.length);\n\t\tString expecting =\n\t\t\t\"[{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=6, \" +\n\t\t\t  \"SLL_ATNTransitions=6, SLL_DFATransitions=0, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}, \" +\n\t\t\t \"{decision=1, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=4, \" +\n\t\t\t  \"SLL_ATNTransitions=2, SLL_DFATransitions=2, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}]\";\n\t\tassertEquals(expecting, Arrays.toString(info));\n\t}\n\n\t@Test public void testProfilerGeneratedCode() {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"s : a+ ID EOF ;\\n\" +\n\t\t\t\"a : ID ';'{}\\n\" +\n\t\t\t\"  | ID '.'\\n\" +\n\t\t\t\"  ;\\n\"+\n\t\t\t\"WS : [ \\\\r\\\\t\\\\n]+ -> channel(HIDDEN) ;\\n\" +\n\t\t\t\"SEMI : ';' ;\\n\" +\n\t\t\t\"DOT : '.' ;\\n\" +\n\t\t\t\"ID : [a-zA-Z]+ ;\\n\" +\n\t\t\t\"INT : [0-9]+ ;\\n\" +\n\t\t\t\"PLUS : '+' ;\\n\" +\n\t\t\t\"MULT : '*' ;\\n\";\n\n\t\tRunOptions runOptions = createOptionsForJavaToolTests(\"T.g4\", grammar, \"TParser\", \"TLexer\",\n\t\t\t\tfalse, false, \"s\", \"xyz;abc;z.q\",\n\t\t\t\ttrue, false, Stage.Execute);\n\t\ttry (JavaRunner runner = new JavaRunner()) {\n\t\t\tExecutedState state = (ExecutedState) runner.run(runOptions);\n\t\t\tString expecting =\n\t\t\t\t\t\"[{decision=0, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=6, SLL_ATNTransitions=4, \" +\n\t\t\t\t\t\t\t\"SLL_DFATransitions=2, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0},\" +\n\t\t\t\t\t\t\t\" {decision=1, contextSensitivities=0, errors=0, ambiguities=0, SLL_lookahead=6, \" +\n\t\t\t\t\t\t\t\"SLL_ATNTransitions=3, SLL_DFATransitions=3, LL_Fallback=0, LL_lookahead=0, LL_ATNTransitions=0}]\\n\";\n\t\t\tassertEquals(expecting, state.output);\n\t\t\tassertEquals(\"\", state.errors);\n\t\t}\n\t}\n\n\tpublic DecisionInfo[] interpAndGetDecisionInfo(\n\t\t\tLexerGrammar lg, Grammar g,\n\t\t\tString startRule, String... input)\n\t{\n\n\t\tLexerInterpreter lexEngine = lg.createLexerInterpreter(null);\n\t\tParserInterpreter parser = g.createParserInterpreter(null);\n\t\tparser.setProfile(true);\n\t\tfor (String s : input) {\n\t\t\tlexEngine.reset();\n\t\t\tparser.reset();\n\t\t\tlexEngine.setInputStream(new ANTLRInputStream(s));\n\t\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\t\tparser.setInputStream(tokens);\n\t\t\tRule r = g.rules.get(startRule);\n\t\t\tif ( r==null ) {\n\t\t\t\treturn parser.getParseInfo().getDecisionInfo();\n\t\t\t}\n\t\t\tParserRuleContext t = parser.parse(r.index);\n//\t\t\ttry {\n//\t\t\t\tUtils.waitForClose(t.inspect(parser).get());\n//\t\t\t}\n//\t\t\tcatch (Exception e) {\n//\t\t\t\te.printStackTrace();\n//\t\t\t}\n//\n//\t\t\tSystem.out.println(t.toStringTree(parser));\n\t\t}\n\t\treturn parser.getParseInfo().getDecisionInfo();\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestPerformance.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.ANTLRFileStream;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.BailErrorStrategy;\nimport org.antlr.v4.runtime.BaseErrorListener;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.DefaultErrorStrategy;\nimport org.antlr.v4.runtime.DiagnosticErrorListener;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.ParserInterpreter;\nimport org.antlr.v4.runtime.ParserRuleContext;\nimport org.antlr.v4.runtime.RecognitionException;\nimport org.antlr.v4.runtime.Recognizer;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.atn.ATN;\nimport org.antlr.v4.runtime.atn.ATNConfig;\nimport org.antlr.v4.runtime.atn.ATNConfigSet;\nimport org.antlr.v4.runtime.atn.LexerATNSimulator;\nimport org.antlr.v4.runtime.atn.ParserATNSimulator;\nimport org.antlr.v4.runtime.atn.PredictionContextCache;\nimport org.antlr.v4.runtime.atn.PredictionMode;\nimport org.antlr.v4.runtime.dfa.DFA;\nimport org.antlr.v4.runtime.dfa.DFAState;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.runtime.misc.MurmurHash;\nimport org.antlr.v4.runtime.misc.ParseCancellationException;\nimport org.antlr.v4.runtime.tree.ErrorNode;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.ParseTreeListener;\nimport org.antlr.v4.runtime.tree.ParseTreeWalker;\nimport org.antlr.v4.runtime.tree.TerminalNode;\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.states.JavaCompiledState;\nimport org.junit.jupiter.api.Disabled;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.Timeout;\nimport org.junit.jupiter.api.io.TempDir;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.io.IOException;\nimport java.lang.ref.Reference;\nimport java.lang.ref.SoftReference;\nimport java.lang.ref.WeakReference;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.BitSet;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicIntegerArray;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport static org.antlr.v4.test.runtime.FileUtils.writeFile;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.NewLine;\nimport static org.antlr.v4.test.tool.ToolTestUtils.createOptionsForJavaToolTests;\nimport static org.antlr.v4.test.tool.ToolTestUtils.load;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\nimport static org.junit.jupiter.api.Assertions.fail;\n\n@SuppressWarnings(\"unused\")\npublic class TestPerformance {\n    /**\n     * Parse all java files under this package within the JDK_SOURCE_ROOT\n     * (environment variable or property defined on the Java command line).\n     */\n    private static final String TOP_PACKAGE = \"java.lang\";\n    /**\n     * {@code true} to load java files from sub-packages of\n     * {@link #TOP_PACKAGE}.\n     */\n    private static final boolean RECURSIVE = true;\n\t/**\n\t * {@code true} to read all source files from disk into memory before\n\t * starting the parse. The default value is {@code true} to help prevent\n\t * drive speed from affecting the performance results. This value may be set\n\t * to {@code false} to support parsing large input sets which would not\n\t * otherwise fit into memory.\n\t */\n\tprivate static final boolean PRELOAD_SOURCES = true;\n\t/**\n\t * The encoding to use when reading source files.\n\t */\n\tprivate static final String ENCODING = \"UTF-8\";\n\t/**\n\t * The maximum number of files to parse in a single iteration.\n\t */\n\tprivate static final int MAX_FILES_PER_PARSE_ITERATION = Integer.MAX_VALUE;\n\n\t/**\n\t * {@code true} to call {@link Collections#shuffle} on the list of input\n\t * files before the first parse iteration.\n\t */\n\tprivate static final boolean SHUFFLE_FILES_AT_START = false;\n\t/**\n\t * {@code true} to call {@link Collections#shuffle} before each parse\n\t * iteration <em>after</em> the first.\n\t */\n\tprivate static final boolean SHUFFLE_FILES_AFTER_ITERATIONS = false;\n\t/**\n\t * The instance of {@link Random} passed when calling\n\t * {@link Collections#shuffle}.\n\t */\n\tprivate static final Random RANDOM = new Random();\n\n    /**\n     * {@code true} to use the Java grammar with expressions in the v4\n     * left-recursive syntax (JavaLR.g4). {@code false} to use the standard\n     * grammar (Java.g4). In either case, the grammar is renamed in the\n     * temporary directory to Java.g4 before compiling.\n     */\n    private static final boolean USE_LR_GRAMMAR = true;\n    /**\n     * {@code true} to specify the {@code -Xforce-atn} option when generating\n     * the grammar, forcing all decisions in {@code JavaParser} to be handled by\n     * {@link ParserATNSimulator#adaptivePredict}.\n     */\n    private static final boolean FORCE_ATN = false;\n    /**\n     * {@code true} to specify the {@code -atn} option when generating the\n     * grammar. This will cause ANTLR to export the ATN for each decision as a\n     * DOT (GraphViz) file.\n     */\n    private static final boolean EXPORT_ATN_GRAPHS = true;\n\t/**\n\t * {@code true} to specify the {@code -XdbgST} option when generating the\n\t * grammar.\n\t */\n\tprivate static final boolean DEBUG_TEMPLATES = false;\n\t/**\n\t * {@code true} to specify the {@code -XdbgSTWait} option when generating the\n\t * grammar.\n\t */\n\tprivate static final boolean DEBUG_TEMPLATES_WAIT = DEBUG_TEMPLATES;\n    /**\n     * {@code true} to delete temporary (generated and compiled) files when the\n     * test completes.\n     */\n    private static final boolean DELETE_TEMP_FILES = true;\n\t/**\n\t * {@code true} to use a {@link ParserInterpreter} for parsing instead of\n\t * generated parser.\n\t */\n\tprivate static final boolean USE_PARSER_INTERPRETER = false;\n\n\t/**\n\t * {@code true} to call {@link System#gc} and then wait for 5 seconds at the\n\t * end of the test to make it easier for a profiler to grab a heap dump at\n\t * the end of the test run.\n\t */\n    private static final boolean PAUSE_FOR_HEAP_DUMP = false;\n\n    /**\n     * Parse each file with {@code JavaParser.compilationUnit}.\n     */\n    private static final boolean RUN_PARSER = true;\n    /**\n     * {@code true} to use {@link BailErrorStrategy}, {@code false} to use\n     * {@link DefaultErrorStrategy}.\n     */\n    private static final boolean BAIL_ON_ERROR = false;\n\t/**\n\t * {@code true} to compute a checksum for verifying consistency across\n\t * optimizations and multiple passes.\n\t */\n\tprivate static final boolean COMPUTE_CHECKSUM = true;\n    /**\n     * This value is passed to {@link Parser#setBuildParseTree}.\n     */\n    private static final boolean BUILD_PARSE_TREES = false;\n    /**\n     * Use\n     * {@link ParseTreeWalker#DEFAULT}{@code .}{@link ParseTreeWalker#walk walk}\n     * with the {@code JavaParserBaseListener} to show parse tree walking\n     * overhead. If {@link #BUILD_PARSE_TREES} is {@code false}, the listener\n     * will instead be called during the parsing process via\n     * {@link Parser#addParseListener}.\n     */\n    private static final boolean BLANK_LISTENER = false;\n\n\t/**\n\t * Shows the number of {@link DFAState} and {@link ATNConfig} instances in\n\t * the DFA cache at the end of each pass. If {@link #REUSE_LEXER_DFA} and/or\n\t * {@link #REUSE_PARSER_DFA} are false, the corresponding instance numbers\n\t * will only apply to one file (the last file if {@link #NUMBER_OF_THREADS}\n\t * is 0, otherwise the last file which was parsed on the first thread).\n\t */\n    private static final boolean SHOW_DFA_STATE_STATS = true;\n\t/**\n\t * If {@code true}, the DFA state statistics report includes a breakdown of\n\t * the number of DFA states contained in each decision (with rule names).\n\t */\n\tprivate static final boolean DETAILED_DFA_STATE_STATS = true;\n\n\t/**\n\t * Specify the {@link PredictionMode} used by the\n\t * {@link ParserATNSimulator}. If {@link #TWO_STAGE_PARSING} is\n\t * {@code true}, this value only applies to the second stage, as the first\n\t * stage will always use {@link PredictionMode#SLL}.\n\t */\n\tprivate static final PredictionMode PREDICTION_MODE = PredictionMode.LL;\n\n\tprivate static final boolean TWO_STAGE_PARSING = true;\n\n    private static final boolean SHOW_CONFIG_STATS = false;\n\n\t/**\n\t * If {@code true}, detailed statistics for the number of DFA edges were\n\t * taken while parsing each file, as well as the number of DFA edges which\n\t * required on-the-fly computation.\n\t */\n\tprivate static final boolean COMPUTE_TRANSITION_STATS = false;\n\tprivate static final boolean SHOW_TRANSITION_STATS_PER_FILE = false;\n\t/**\n\t * If {@code true}, the transition statistics will be adjusted to a running\n\t * total before reporting the final results.\n\t */\n\tprivate static final boolean TRANSITION_RUNNING_AVERAGE = false;\n\t/**\n\t * If {@code true}, transition statistics will be weighted according to the\n\t * total number of transitions taken during the parsing of each file.\n\t */\n\tprivate static final boolean TRANSITION_WEIGHTED_AVERAGE = false;\n\n\t/**\n\t * If {@code true}, after each pass a summary of the time required to parse\n\t * each file will be printed.\n\t */\n\tprivate static final boolean COMPUTE_TIMING_STATS = false;\n\t/**\n\t * If {@code true}, the timing statistics for {@link #COMPUTE_TIMING_STATS}\n\t * will be cumulative (i.e. the time reported for the <em>n</em>th file will\n\t * be the total time required to parse the first <em>n</em> files).\n\t */\n\tprivate static final boolean TIMING_CUMULATIVE = false;\n\t/**\n\t * If {@code true}, the timing statistics will include the parser only. This\n\t * flag allows for targeted measurements, and helps eliminate variance when\n\t * {@link #PRELOAD_SOURCES} is {@code false}.\n\t * <p/>\n\t * This flag has no impact when {@link #RUN_PARSER} is {@code false}.\n\t */\n\tprivate static final boolean TIME_PARSE_ONLY = false;\n\n\t/**\n\t * When {@code true}, messages will be printed to {@link System#err} when\n\t * the first stage (SLL) parsing resulted in a syntax error. This option is\n\t * ignored when {@link #TWO_STAGE_PARSING} is {@code false}.\n\t */\n\tprivate static final boolean REPORT_SECOND_STAGE_RETRY = true;\n\tprivate static final boolean REPORT_SYNTAX_ERRORS = true;\n\tprivate static final boolean REPORT_AMBIGUITIES = false;\n\tprivate static final boolean REPORT_FULL_CONTEXT = false;\n\tprivate static final boolean REPORT_CONTEXT_SENSITIVITY = REPORT_FULL_CONTEXT;\n\n    /**\n     * If {@code true}, a single {@code JavaLexer} will be used, and\n     * {@link Lexer#setInputStream} will be called to initialize it for each\n     * source file. Otherwise, a new instance will be created for each file.\n     */\n    private static final boolean REUSE_LEXER = false;\n\t/**\n\t * If {@code true}, a single DFA will be used for lexing which is shared\n\t * across all threads and files. Otherwise, each file will be lexed with its\n\t * own DFA which is accomplished by creating one ATN instance per thread and\n\t * clearing its DFA cache before lexing each file.\n\t */\n\tprivate static final boolean REUSE_LEXER_DFA = true;\n    /**\n     * If {@code true}, a single {@code JavaParser} will be used, and\n     * {@link Parser#setInputStream} will be called to initialize it for each\n     * source file. Otherwise, a new instance will be created for each file.\n     */\n    private static final boolean REUSE_PARSER = false;\n\t/**\n\t * If {@code true}, a single DFA will be used for parsing which is shared\n\t * across all threads and files. Otherwise, each file will be parsed with\n\t * its own DFA which is accomplished by creating one ATN instance per thread\n\t * and clearing its DFA cache before parsing each file.\n\t */\n\tprivate static final boolean REUSE_PARSER_DFA = true;\n    /**\n     * If {@code true}, the shared lexer and parser are reset after each pass.\n     * If {@code false}, all passes after the first will be fully \"warmed up\",\n     * which makes them faster and can compare them to the first warm-up pass,\n     * but it will not distinguish bytecode load/JIT time from warm-up time\n     * during the first pass.\n     */\n    private static final boolean CLEAR_DFA = false;\n    /**\n     * Total number of passes to make over the source.\n     */\n    private static final int PASSES = 4;\n\n\t/**\n\t * This option controls the granularity of multi-threaded parse operations.\n\t * If {@code true}, the parsing operation will be parallelized across files;\n\t * otherwise the parsing will be parallelized across multiple iterations.\n\t */\n\tprivate static final boolean FILE_GRANULARITY = true;\n\n\t/**\n\t * Number of parser threads to use.\n\t */\n\tprivate static final int NUMBER_OF_THREADS = 1;\n\n    private static final Lexer[] sharedLexers = new Lexer[NUMBER_OF_THREADS];\n\n    private static final Parser[] sharedParsers = new Parser[NUMBER_OF_THREADS];\n\n    private static final ParseTreeListener[] sharedListeners = new ParseTreeListener[NUMBER_OF_THREADS];\n\n\tprivate static final long[][] totalTransitionsPerFile;\n\tprivate static final long[][] computedTransitionsPerFile;\n\tstatic {\n\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\ttotalTransitionsPerFile = new long[PASSES][];\n\t\t\tcomputedTransitionsPerFile = new long[PASSES][];\n\t\t} else {\n\t\t\ttotalTransitionsPerFile = null;\n\t\t\tcomputedTransitionsPerFile = null;\n\t\t}\n\t}\n\n\tprivate static final long[][][] decisionInvocationsPerFile;\n\tprivate static final long[][][] fullContextFallbackPerFile;\n\tprivate static final long[][][] nonSllPerFile;\n\tprivate static final long[][][] totalTransitionsPerDecisionPerFile;\n\tprivate static final long[][][] computedTransitionsPerDecisionPerFile;\n\tprivate static final long[][][] fullContextTransitionsPerDecisionPerFile;\n\tstatic {\n\t\tif (COMPUTE_TRANSITION_STATS && DETAILED_DFA_STATE_STATS) {\n\t\t\tdecisionInvocationsPerFile = new long[PASSES][][];\n\t\t\tfullContextFallbackPerFile = new long[PASSES][][];\n\t\t\tnonSllPerFile = new long[PASSES][][];\n\t\t\ttotalTransitionsPerDecisionPerFile = new long[PASSES][][];\n\t\t\tcomputedTransitionsPerDecisionPerFile = new long[PASSES][][];\n\t\t\tfullContextTransitionsPerDecisionPerFile = new long[PASSES][][];\n\t\t} else {\n\t\t\tdecisionInvocationsPerFile = null;\n\t\t\tfullContextFallbackPerFile = null;\n\t\t\tnonSllPerFile = null;\n\t\t\ttotalTransitionsPerDecisionPerFile = null;\n\t\t\tcomputedTransitionsPerDecisionPerFile = null;\n\t\t\tfullContextTransitionsPerDecisionPerFile = null;\n\t\t}\n\t}\n\n\tprivate static final long[][] timePerFile;\n\tprivate static final int[][] tokensPerFile;\n\tstatic {\n\t\tif (COMPUTE_TIMING_STATS) {\n\t\t\ttimePerFile = new long[PASSES][];\n\t\t\ttokensPerFile = new int[PASSES][];\n\t\t} else {\n\t\t\ttimePerFile = null;\n\t\t\ttokensPerFile = null;\n\t\t}\n\t}\n\n    private final AtomicIntegerArray tokenCount = new AtomicIntegerArray(PASSES);\n\n    @Test\n    @Disabled\n    public void compileJdk() throws IOException, InterruptedException, ExecutionException {\n        String jdkSourceRoot = getSourceRoot(\"JDK\");\n\t\tassertTrue(jdkSourceRoot != null && !jdkSourceRoot.isEmpty(),\n\t\t\t\t\"The JDK_SOURCE_ROOT environment variable must be set for performance testing.\");\n\n        JavaCompiledState javaCompiledState = compileJavaParser(USE_LR_GRAMMAR);\n        final String lexerName    = USE_LR_GRAMMAR ? \"JavaLRLexer\"        : \"JavaLexer\";\n        final String parserName   = USE_LR_GRAMMAR ? \"JavaLRParser\"       : \"JavaParser\";\n        final String listenerName = USE_LR_GRAMMAR ? \"JavaLRBaseListener\" : \"JavaBaseListener\";\n        final String entryPoint = \"compilationUnit\";\n        final ParserFactory factory = getParserFactory(javaCompiledState, listenerName, entryPoint);\n\n\t\tif (!TOP_PACKAGE.isEmpty()) {\n            jdkSourceRoot = jdkSourceRoot + '/' + TOP_PACKAGE.replace('.', '/');\n        }\n\n        File directory = new File(jdkSourceRoot);\n        assertTrue(directory.isDirectory());\n\n\t\tFilenameFilter filesFilter = FilenameFilters.extension(\".java\", false);\n\t\tFilenameFilter directoriesFilter = FilenameFilters.ALL_FILES;\n\t\tfinal List<InputDescriptor> sources = loadSources(directory, filesFilter, directoriesFilter, RECURSIVE);\n\n\t\tfor (int i = 0; i < PASSES; i++) {\n\t\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\t\ttotalTransitionsPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)];\n\t\t\t\tcomputedTransitionsPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)];\n\n\t\t\t\tif (DETAILED_DFA_STATE_STATS) {\n\t\t\t\t\tdecisionInvocationsPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)][];\n\t\t\t\t\tfullContextFallbackPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)][];\n\t\t\t\t\tnonSllPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)][];\n\t\t\t\t\ttotalTransitionsPerDecisionPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)][];\n\t\t\t\t\tcomputedTransitionsPerDecisionPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)][];\n\t\t\t\t\tfullContextTransitionsPerDecisionPerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)][];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (COMPUTE_TIMING_STATS) {\n\t\t\t\ttimePerFile[i] = new long[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)];\n\t\t\t\ttokensPerFile[i] = new int[Math.min(sources.size(), MAX_FILES_PER_PARSE_ITERATION)];\n\t\t\t}\n\t\t}\n\n\t\tSystem.out.format(\"Located %d source files.%n\", sources.size());\n\t\tSystem.out.print(getOptionsDescription(TOP_PACKAGE));\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(FILE_GRANULARITY ? 1 : NUMBER_OF_THREADS, new NumberedThreadFactory());\n\n\t\tList<Future<?>> passResults = new ArrayList<Future<?>>();\n\t\tpassResults.add(executorService.submit(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tparse1(0, factory, sources, SHUFFLE_FILES_AT_START);\n\t\t\t\t} catch (InterruptedException ex) {\n\t\t\t\t\tLogger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}));\n        for (int i = 0; i < PASSES - 1; i++) {\n            final int currentPass = i + 1;\n\t\t\tpassResults.add(executorService.submit(new Runnable() {\n\t\t\t\t@Override\n\t\t\t\tpublic void run() {\n\t\t\t\t\tif (CLEAR_DFA) {\n\t\t\t\t\t\tint index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber();\n\t\t\t\t\t\tif (sharedLexers.length > 0 && sharedLexers[index] != null) {\n\t\t\t\t\t\t\tATN atn = sharedLexers[index].getATN();\n\t\t\t\t\t\t\tfor (int j = 0; j < sharedLexers[index].getInterpreter().decisionToDFA.length; j++) {\n\t\t\t\t\t\t\t\tsharedLexers[index].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (sharedParsers.length > 0 && sharedParsers[index] != null) {\n\t\t\t\t\t\t\tATN atn = sharedParsers[index].getATN();\n\t\t\t\t\t\t\tfor (int j = 0; j < sharedParsers[index].getInterpreter().decisionToDFA.length; j++) {\n\t\t\t\t\t\t\t\tsharedParsers[index].getInterpreter().decisionToDFA[j] = new DFA(atn.getDecisionState(j), j);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (FILE_GRANULARITY) {\n\t\t\t\t\t\t\tArrays.fill(sharedLexers, null);\n\t\t\t\t\t\t\tArrays.fill(sharedParsers, null);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparse2(currentPass, factory, sources, SHUFFLE_FILES_AFTER_ITERATIONS);\n\t\t\t\t\t} catch (InterruptedException ex) {\n\t\t\t\t\t\tLogger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n        }\n\n\t\tfor (Future<?> passResult : passResults) {\n\t\t\tpassResult.get();\n\t\t}\n\n\t\texecutorService.shutdown();\n\t\texecutorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);\n\n\t\tif (COMPUTE_TRANSITION_STATS && SHOW_TRANSITION_STATS_PER_FILE) {\n\t\t\tcomputeTransitionStatistics();\n\t\t}\n\n\t\tif (COMPUTE_TIMING_STATS) {\n\t\t\tcomputeTimingStatistics();\n\t\t}\n\n\t\tsources.clear();\n\t\tif (PAUSE_FOR_HEAP_DUMP) {\n\t\t\tSystem.gc();\n\t\t\tSystem.out.println(\"Pausing before application exit.\");\n\t\t\ttry {\n\t\t\t\tThread.sleep(4000);\n\t\t\t} catch (InterruptedException ex) {\n\t\t\t\tLogger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);\n\t\t\t}\n\t\t}\n    }\n\n\t/**\n\t * Compute and print ATN/DFA transition statistics.\n\t */\n\tprivate void computeTransitionStatistics() {\n\t\tif (TRANSITION_RUNNING_AVERAGE) {\n\t\t\tfor (int i = 0; i < PASSES; i++) {\n\t\t\t\tlong[] data = computedTransitionsPerFile[i];\n\t\t\t\tfor (int j = 0; j < data.length - 1; j++) {\n\t\t\t\t\tdata[j + 1] += data[j];\n\t\t\t\t}\n\n\t\t\t\tdata = totalTransitionsPerFile[i];\n\t\t\t\tfor (int j = 0; j < data.length - 1; j++) {\n\t\t\t\t\tdata[j + 1] += data[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlong[] sumNum = new long[totalTransitionsPerFile[0].length];\n\t\tlong[] sumDen = new long[totalTransitionsPerFile[0].length];\n\t\tdouble[] sumNormalized = new double[totalTransitionsPerFile[0].length];\n\t\tfor (int i = 0; i < PASSES; i++) {\n\t\t\tlong[] num = computedTransitionsPerFile[i];\n\t\t\tlong[] den = totalTransitionsPerFile[i];\n\t\t\tfor (int j = 0; j < den.length; j++) {\n\t\t\t\tsumNum[j] += num[j];\n\t\t\t\tsumDen[j] += den[j];\n\t\t\t\tif (den[j] > 0) {\n\t\t\t\t\tsumNormalized[j] += (double)num[j] / (double)den[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdouble[] weightedAverage = new double[totalTransitionsPerFile[0].length];\n\t\tdouble[] average = new double[totalTransitionsPerFile[0].length];\n\t\tfor (int i = 0; i < average.length; i++) {\n\t\t\tif (sumDen[i] > 0) {\n\t\t\t\tweightedAverage[i] = (double)sumNum[i] / (double)sumDen[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tweightedAverage[i] = 0;\n\t\t\t}\n\n\t\t\taverage[i] = sumNormalized[i] / PASSES;\n\t\t}\n\n\t\tdouble[] low95 = new double[totalTransitionsPerFile[0].length];\n\t\tdouble[] high95 = new double[totalTransitionsPerFile[0].length];\n\t\tdouble[] low67 = new double[totalTransitionsPerFile[0].length];\n\t\tdouble[] high67 = new double[totalTransitionsPerFile[0].length];\n\t\tdouble[] stddev = new double[totalTransitionsPerFile[0].length];\n\t\tfor (int i = 0; i < stddev.length; i++) {\n\t\t\tdouble[] points = new double[PASSES];\n\t\t\tfor (int j = 0; j < PASSES; j++) {\n\t\t\t\tlong totalTransitions = totalTransitionsPerFile[j][i];\n\t\t\t\tif (totalTransitions > 0) {\n\t\t\t\t\tpoints[j] = ((double)computedTransitionsPerFile[j][i] / (double)totalTransitionsPerFile[j][i]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpoints[j] = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tArrays.sort(points);\n\n\t\t\tfinal double averageValue = TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i];\n\t\t\tdouble value = 0;\n\t\t\tfor (int j = 0; j < PASSES; j++) {\n\t\t\t\tdouble diff = points[j] - averageValue;\n\t\t\t\tvalue += diff * diff;\n\t\t\t}\n\n\t\t\tint ignoreCount95 = (int)Math.round(PASSES * (1 - 0.95) / 2.0);\n\t\t\tint ignoreCount67 = (int)Math.round(PASSES * (1 - 0.667) / 2.0);\n\t\t\tlow95[i] = points[ignoreCount95];\n\t\t\thigh95[i] = points[points.length - 1 - ignoreCount95];\n\t\t\tlow67[i] = points[ignoreCount67];\n\t\t\thigh67[i] = points[points.length - 1 - ignoreCount67];\n\t\t\tstddev[i] = Math.sqrt(value / PASSES);\n\t\t}\n\n\t\tSystem.out.format(\"File\\tAverage\\tStd. Dev.\\t95%% Low\\t95%% High\\t66.7%% Low\\t66.7%% High%n\");\n\t\tfor (int i = 0; i < stddev.length; i++) {\n\t\t\tfinal double averageValue = TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i];\n\t\t\tSystem.out.format(\"%d\\t%e\\t%e\\t%e\\t%e\\t%e\\t%e%n\", i + 1, averageValue, stddev[i], averageValue - low95[i], high95[i] - averageValue, averageValue - low67[i], high67[i] - averageValue);\n\t\t}\n\t}\n\n\t/**\n\t * Compute and print timing statistics.\n\t */\n\tprivate void computeTimingStatistics() {\n\t\tif (TIMING_CUMULATIVE) {\n\t\t\tfor (int i = 0; i < PASSES; i++) {\n\t\t\t\tlong[] data = timePerFile[i];\n\t\t\t\tfor (int j = 0; j < data.length - 1; j++) {\n\t\t\t\t\tdata[j + 1] += data[j];\n\t\t\t\t}\n\n\t\t\t\tint[] data2 = tokensPerFile[i];\n\t\t\t\tfor (int j = 0; j < data2.length - 1; j++) {\n\t\t\t\t\tdata2[j + 1] += data2[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfinal int fileCount = timePerFile[0].length;\n\t\tdouble[] sum = new double[fileCount];\n\t\tfor (int i = 0; i < PASSES; i++) {\n\t\t\tlong[] data = timePerFile[i];\n\t\t\tint[] tokenData = tokensPerFile[i];\n\t\t\tfor (int j = 0; j < data.length; j++) {\n\t\t\t\tsum[j] += (double)data[j] / (double)tokenData[j];\n\t\t\t}\n\t\t}\n\n\t\tdouble[] average = new double[fileCount];\n\t\tfor (int i = 0; i < average.length; i++) {\n\t\t\taverage[i] = sum[i] / PASSES;\n\t\t}\n\n\t\tdouble[] low95 = new double[fileCount];\n\t\tdouble[] high95 = new double[fileCount];\n\t\tdouble[] low67 = new double[fileCount];\n\t\tdouble[] high67 = new double[fileCount];\n\t\tdouble[] stddev = new double[fileCount];\n\t\tfor (int i = 0; i < stddev.length; i++) {\n\t\t\tdouble[] points = new double[PASSES];\n\t\t\tfor (int j = 0; j < PASSES; j++) {\n\t\t\t\tpoints[j] = (double)timePerFile[j][i] / (double)tokensPerFile[j][i];\n\t\t\t}\n\n\t\t\tArrays.sort(points);\n\n\t\t\tfinal double averageValue = average[i];\n\t\t\tdouble value = 0;\n\t\t\tfor (int j = 0; j < PASSES; j++) {\n\t\t\t\tdouble diff = points[j] - averageValue;\n\t\t\t\tvalue += diff * diff;\n\t\t\t}\n\n\t\t\tint ignoreCount95 = (int)Math.round(PASSES * (1 - 0.95) / 2.0);\n\t\t\tint ignoreCount67 = (int)Math.round(PASSES * (1 - 0.667) / 2.0);\n\t\t\tlow95[i] = points[ignoreCount95];\n\t\t\thigh95[i] = points[points.length - 1 - ignoreCount95];\n\t\t\tlow67[i] = points[ignoreCount67];\n\t\t\thigh67[i] = points[points.length - 1 - ignoreCount67];\n\t\t\tstddev[i] = Math.sqrt(value / PASSES);\n\t\t}\n\n\t\tSystem.out.format(\"File\\tAverage\\tStd. Dev.\\t95%% Low\\t95%% High\\t66.7%% Low\\t66.7%% High%n\");\n\t\tfor (int i = 0; i < stddev.length; i++) {\n\t\t\tfinal double averageValue = average[i];\n\t\t\tSystem.out.format(\"%d\\t%e\\t%e\\t%e\\t%e\\t%e\\t%e%n\", i + 1, averageValue, stddev[i], averageValue - low95[i], high95[i] - averageValue, averageValue - low67[i], high67[i] - averageValue);\n\t\t}\n\t}\n\n\tprivate String getSourceRoot(String prefix) {\n\t\tString sourceRoot = System.getenv(prefix+\"_SOURCE_ROOT\");\n\t\tif (sourceRoot == null) {\n\t\t\tsourceRoot = System.getProperty(prefix+\"_SOURCE_ROOT\");\n\t\t}\n\n\t\treturn sourceRoot;\n\t}\n\n    public static String getOptionsDescription(String topPackage) {\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"Input=\");\n        if (topPackage.isEmpty()) {\n            builder.append(\"*\");\n        }\n        else {\n            builder.append(topPackage).append(\".*\");\n        }\n\n        builder.append(\", Grammar=\").append(USE_LR_GRAMMAR ? \"LR\" : \"Standard\");\n        builder.append(\", ForceAtn=\").append(FORCE_ATN);\n\n        builder.append(NewLine);\n\n        builder.append(\"Op=Lex\").append(RUN_PARSER ? \"+Parse\" : \" only\");\n        builder.append(\", Strategy=\").append(BAIL_ON_ERROR ? BailErrorStrategy.class.getSimpleName() : DefaultErrorStrategy.class.getSimpleName());\n        builder.append(\", BuildParseTree=\").append(BUILD_PARSE_TREES);\n        builder.append(\", WalkBlankListener=\").append(BLANK_LISTENER);\n\n        builder.append(NewLine);\n\n        builder.append(\"Lexer=\").append(REUSE_LEXER ? \"setInputStream\" : \"newInstance\");\n        builder.append(\", Parser=\").append(REUSE_PARSER ? \"setInputStream\" : \"newInstance\");\n        builder.append(\", AfterPass=\").append(CLEAR_DFA ? \"newInstance\" : \"setInputStream\");\n\n        builder.append(NewLine);\n\n        return builder.toString();\n    }\n\n    /**\n     *  This method is separate from {@link #parse2} so the first pass can be distinguished when analyzing\n     *  profiler results.\n     */\n    protected void parse1(int currentPass, ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException {\n\t\tif (FILE_GRANULARITY) {\n\t\t\tSystem.gc();\n\t\t}\n\n        parseSources(currentPass, factory, sources, shuffleSources);\n    }\n\n    /**\n     *  This method is separate from {@link #parse1} so the first pass can be distinguished when analyzing\n     *  profiler results.\n     */\n    protected void parse2(int currentPass, ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException {\n\t\tif (FILE_GRANULARITY) {\n\t\t\tSystem.gc();\n\t\t}\n\n        parseSources(currentPass, factory, sources, shuffleSources);\n    }\n\n    protected List<InputDescriptor> loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive) {\n        List<InputDescriptor> result = new ArrayList<InputDescriptor>();\n        loadSources(directory, filesFilter, directoriesFilter, recursive, result);\n        return result;\n    }\n\n    protected void loadSources(File directory, FilenameFilter filesFilter, FilenameFilter directoriesFilter, boolean recursive, Collection<InputDescriptor> result) {\n        assert directory.isDirectory();\n\n        File[] sources = directory.listFiles(filesFilter);\n        for (File file : sources) {\n\t\t\tif (!file.isFile()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tresult.add(new InputDescriptor(file.getAbsolutePath()));\n        }\n\n        if (recursive) {\n            File[] children = directory.listFiles(directoriesFilter);\n            for (File child : children) {\n                if (child.isDirectory()) {\n                    loadSources(child, filesFilter, directoriesFilter, true, result);\n                }\n            }\n        }\n    }\n\n    int configOutputSize = 0;\n\n\tprotected void parseSources(final int currentPass, final ParserFactory factory, Collection<InputDescriptor> sources, boolean shuffleSources) throws InterruptedException {\n\t\tif (shuffleSources) {\n\t\t\tList<InputDescriptor> sourcesList = new ArrayList<InputDescriptor>(sources);\n\t\t\tsynchronized (RANDOM) {\n\t\t\t\tCollections.shuffle(sourcesList, RANDOM);\n\t\t\t}\n\n\t\t\tsources = sourcesList;\n\t\t}\n\n\t\tlong startTime = System.nanoTime();\n        tokenCount.set(currentPass, 0);\n        int inputSize = 0;\n\t\tint inputCount = 0;\n\n\t\tCollection<Future<FileParseResult>> results = new ArrayList<Future<FileParseResult>>();\n\t\tExecutorService executorService;\n\t\tif (FILE_GRANULARITY) {\n\t\t\texecutorService = Executors.newFixedThreadPool(FILE_GRANULARITY ? NUMBER_OF_THREADS : 1, new NumberedThreadFactory());\n\t\t} else {\n\t\t\texecutorService = Executors.newSingleThreadExecutor(new FixedThreadNumberFactory(((NumberedThread)Thread.currentThread()).getThreadNumber()));\n\t\t}\n\n\t\tfor (InputDescriptor inputDescriptor : sources) {\n\t\t\tif (inputCount >= MAX_FILES_PER_PARSE_ITERATION) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfinal CharStream input = inputDescriptor.getInputStream();\n            input.seek(0);\n            inputSize += input.size();\n\t\t\tinputCount++;\n\t\t\tFuture<FileParseResult> futureChecksum = executorService.submit(new Callable<FileParseResult>() {\n\t\t\t\t@Override\n\t\t\t\tpublic FileParseResult call() {\n\t\t\t\t\t// this incurred a great deal of overhead and was causing significant variations in performance results.\n\t\t\t\t\t//System.out.format(\"Parsing file %s\\n\", input.getSourceName());\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn factory.parseFile(input, currentPass, ((NumberedThread)Thread.currentThread()).getThreadNumber());\n\t\t\t\t\t} catch (IllegalStateException ex) {\n\t\t\t\t\t\tex.printStackTrace(System.err);\n\t\t\t\t\t} catch (Throwable t) {\n\t\t\t\t\t\tt.printStackTrace(System.err);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tresults.add(futureChecksum);\n        }\n\n\t\tMurmurHashChecksum checksum = new MurmurHashChecksum();\n\t\tint currentIndex = -1;\n\t\tfor (Future<FileParseResult> future : results) {\n\t\t\tcurrentIndex++;\n\t\t\tint fileChecksum = 0;\n\t\t\ttry {\n\t\t\t\tFileParseResult fileResult = future.get();\n\t\t\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\t\t\ttotalTransitionsPerFile[currentPass][currentIndex] = sum(fileResult.parserTotalTransitions);\n\t\t\t\t\tcomputedTransitionsPerFile[currentPass][currentIndex] = sum(fileResult.parserComputedTransitions);\n\n\t\t\t\t\tif (DETAILED_DFA_STATE_STATS) {\n\t\t\t\t\t\tdecisionInvocationsPerFile[currentPass][currentIndex] = fileResult.decisionInvocations;\n\t\t\t\t\t\tfullContextFallbackPerFile[currentPass][currentIndex] = fileResult.fullContextFallback;\n\t\t\t\t\t\tnonSllPerFile[currentPass][currentIndex] = fileResult.nonSll;\n\t\t\t\t\t\ttotalTransitionsPerDecisionPerFile[currentPass][currentIndex] = fileResult.parserTotalTransitions;\n\t\t\t\t\t\tcomputedTransitionsPerDecisionPerFile[currentPass][currentIndex] = fileResult.parserComputedTransitions;\n\t\t\t\t\t\tfullContextTransitionsPerDecisionPerFile[currentPass][currentIndex] = fileResult.parserFullContextTransitions;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (COMPUTE_TIMING_STATS) {\n\t\t\t\t\ttimePerFile[currentPass][currentIndex] = fileResult.endTime - fileResult.startTime;\n\t\t\t\t\ttokensPerFile[currentPass][currentIndex] = fileResult.tokenCount;\n\t\t\t\t}\n\n\t\t\t\tfileChecksum = fileResult.checksum;\n\t\t\t} catch (ExecutionException ex) {\n\t\t\t\tLogger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex);\n\t\t\t}\n\n\t\t\tif (COMPUTE_CHECKSUM) {\n\t\t\t\tupdateChecksum(checksum, fileChecksum);\n\t\t\t}\n\t\t}\n\n\t\texecutorService.shutdown();\n\t\texecutorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);\n\n        System.out.format(\"%d. Total parse time for %d files (%d KB, %d tokens%s): %.0fms%n\",\n\t\t\t\t\t\t  currentPass + 1,\n                          inputCount,\n                          inputSize / 1024,\n                          tokenCount.get(currentPass),\n\t\t\t\t\t\t  COMPUTE_CHECKSUM ? String.format(\", checksum 0x%8X\", checksum.getValue()) : \"\",\n                          (double)(System.nanoTime() - startTime) / 1000000.0);\n\n\t\tif (sharedLexers.length > 0) {\n\t\t\tint index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber();\n\t\t\tLexer lexer = sharedLexers[index];\n\t\t\tfinal LexerATNSimulator lexerInterpreter = lexer.getInterpreter();\n\t\t\tfinal DFA[] modeToDFA = lexerInterpreter.decisionToDFA;\n\t\t\tif (SHOW_DFA_STATE_STATS) {\n\t\t\t\tint states = 0;\n\t\t\t\tint configs = 0;\n\t\t\t\tSet<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();\n\n\t\t\t\tfor (int i = 0; i < modeToDFA.length; i++) {\n\t\t\t\t\tDFA dfa = modeToDFA[i];\n\t\t\t\t\tif (dfa == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tstates += dfa.states.size();\n\t\t\t\t\tfor (DFAState state : dfa.states.values()) {\n\t\t\t\t\t\tconfigs += state.configs.size();\n\t\t\t\t\t\tuniqueConfigs.addAll(state.configs);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tSystem.out.format(\"There are %d lexer DFAState instances, %d configs (%d unique).%n\", states, configs, uniqueConfigs.size());\n\n\t\t\t\tif (DETAILED_DFA_STATE_STATS) {\n\t\t\t\t\tSystem.out.format(\"\\tMode\\tStates\\tConfigs\\tMode%n\");\n\t\t\t\t\tfor (int i = 0; i < modeToDFA.length; i++) {\n\t\t\t\t\t\tDFA dfa = modeToDFA[i];\n\t\t\t\t\t\tif (dfa == null || dfa.states.isEmpty()) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint modeConfigs = 0;\n\t\t\t\t\t\tfor (DFAState state : dfa.states.values()) {\n\t\t\t\t\t\t\tmodeConfigs += state.configs.size();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString modeName = lexer.getModeNames()[i];\n\t\t\t\t\t\tSystem.out.format(\"\\t%d\\t%d\\t%d\\t%s%n\", dfa.decision, dfa.states.size(), modeConfigs, modeName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (RUN_PARSER && sharedParsers.length > 0) {\n\t\t\tint index = FILE_GRANULARITY ? 0 : ((NumberedThread)Thread.currentThread()).getThreadNumber();\n\t\t\tParser parser = sharedParsers[index];\n            // make sure the individual DFAState objects actually have unique ATNConfig arrays\n            final ParserATNSimulator interpreter = parser.getInterpreter();\n            final DFA[] decisionToDFA = interpreter.decisionToDFA;\n\n            if (SHOW_DFA_STATE_STATS) {\n                int states = 0;\n\t\t\t\tint configs = 0;\n\t\t\t\tSet<ATNConfig> uniqueConfigs = new HashSet<ATNConfig>();\n\n                for (int i = 0; i < decisionToDFA.length; i++) {\n                    DFA dfa = decisionToDFA[i];\n                    if (dfa == null) {\n                        continue;\n                    }\n\n                    states += dfa.states.size();\n\t\t\t\t\tfor (DFAState state : dfa.states.values()) {\n\t\t\t\t\t\tconfigs += state.configs.size();\n\t\t\t\t\t\tuniqueConfigs.addAll(state.configs);\n\t\t\t\t\t}\n                }\n\n                System.out.format(\"There are %d parser DFAState instances, %d configs (%d unique).%n\", states, configs, uniqueConfigs.size());\n\n\t\t\t\tif (DETAILED_DFA_STATE_STATS) {\n\t\t\t\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\t\t\t\tSystem.out.format(\"\\tDecision\\tStates\\tConfigs\\tPredict (ALL)\\tPredict (LL)\\tNon-SLL\\tTransitions\\tTransitions (ATN)\\tTransitions (LL)\\tLA (SLL)\\tLA (LL)\\tRule%n\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tSystem.out.format(\"\\tDecision\\tStates\\tConfigs\\tRule%n\");\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (int i = 0; i < decisionToDFA.length; i++) {\n\t\t\t\t\t\tDFA dfa = decisionToDFA[i];\n\t\t\t\t\t\tif (dfa == null || dfa.states.isEmpty()) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint decisionConfigs = 0;\n\t\t\t\t\t\tfor (DFAState state : dfa.states.values()) {\n\t\t\t\t\t\t\tdecisionConfigs += state.configs.size();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString ruleName = parser.getRuleNames()[parser.getATN().decisionToState.get(dfa.decision).ruleIndex];\n\n\t\t\t\t\t\tlong calls = 0;\n\t\t\t\t\t\tlong fullContextCalls = 0;\n\t\t\t\t\t\tlong nonSllCalls = 0;\n\t\t\t\t\t\tlong transitions = 0;\n\t\t\t\t\t\tlong computedTransitions = 0;\n\t\t\t\t\t\tlong fullContextTransitions = 0;\n\t\t\t\t\t\tdouble lookahead = 0;\n\t\t\t\t\t\tdouble fullContextLookahead = 0;\n\t\t\t\t\t\tString formatString;\n\t\t\t\t\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\t\t\t\t\tfor (long[] data : decisionInvocationsPerFile[currentPass]) {\n\t\t\t\t\t\t\t\tcalls += data[i];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (long[] data : fullContextFallbackPerFile[currentPass]) {\n\t\t\t\t\t\t\t\tfullContextCalls += data[i];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (long[] data : nonSllPerFile[currentPass]) {\n\t\t\t\t\t\t\t\tnonSllCalls += data[i];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (long[] data : totalTransitionsPerDecisionPerFile[currentPass]) {\n\t\t\t\t\t\t\t\ttransitions += data[i];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (long[] data : computedTransitionsPerDecisionPerFile[currentPass]) {\n\t\t\t\t\t\t\t\tcomputedTransitions += data[i];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (long[] data : fullContextTransitionsPerDecisionPerFile[currentPass]) {\n\t\t\t\t\t\t\t\tfullContextTransitions += data[i];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (calls > 0) {\n\t\t\t\t\t\t\t\tlookahead = (double)(transitions - fullContextTransitions) / (double)calls;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (fullContextCalls > 0) {\n\t\t\t\t\t\t\t\tfullContextLookahead = (double)fullContextTransitions / (double)fullContextCalls;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tformatString = \"\\t%1$d\\t%2$d\\t%3$d\\t%4$d\\t%5$d\\t%6$d\\t%7$d\\t%8$d\\t%9$d\\t%10$f\\t%11$f\\t%12$s%n\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcalls = 0;\n\t\t\t\t\t\t\tformatString = \"\\t%1$d\\t%2$d\\t%3$d\\t%12$s%n\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tSystem.out.format(formatString, dfa.decision, dfa.states.size(), decisionConfigs, calls, fullContextCalls, nonSllCalls, transitions, computedTransitions, fullContextTransitions, lookahead, fullContextLookahead, ruleName);\n\t\t\t\t\t}\n\t\t\t\t}\n            }\n\n            int localDfaCount = 0;\n            int globalDfaCount = 0;\n            int localConfigCount = 0;\n            int globalConfigCount = 0;\n            int[] contextsInDFAState = new int[0];\n\n            for (int i = 0; i < decisionToDFA.length; i++) {\n                DFA dfa = decisionToDFA[i];\n                if (dfa == null) {\n                    continue;\n                }\n\n                if (SHOW_CONFIG_STATS) {\n                    for (DFAState state : dfa.states.keySet()) {\n                        if (state.configs.size() >= contextsInDFAState.length) {\n                            contextsInDFAState = Arrays.copyOf(contextsInDFAState, state.configs.size() + 1);\n                        }\n\n                        if (state.isAcceptState) {\n                            boolean hasGlobal = false;\n                            for (ATNConfig config : state.configs) {\n                                if (config.reachesIntoOuterContext > 0) {\n                                    globalConfigCount++;\n                                    hasGlobal = true;\n                                } else {\n                                    localConfigCount++;\n                                }\n                            }\n\n                            if (hasGlobal) {\n                                globalDfaCount++;\n                            } else {\n                                localDfaCount++;\n                            }\n                        }\n\n                        contextsInDFAState[state.configs.size()]++;\n                    }\n                }\n            }\n\n            if (SHOW_CONFIG_STATS && currentPass == 0) {\n                System.out.format(\"  DFA accept states: %d total, %d with only local context, %d with a global context%n\", localDfaCount + globalDfaCount, localDfaCount, globalDfaCount);\n                System.out.format(\"  Config stats: %d total, %d local, %d global%n\", localConfigCount + globalConfigCount, localConfigCount, globalConfigCount);\n                if (SHOW_DFA_STATE_STATS) {\n                    for (int i = 0; i < contextsInDFAState.length; i++) {\n                        if (contextsInDFAState[i] != 0) {\n                            System.out.format(\"  %d configs = %d%n\", i, contextsInDFAState[i]);\n                        }\n                    }\n                }\n            }\n        }\n\n\t\tif (COMPUTE_TIMING_STATS) {\n\t\t\tSystem.out.format(\"File\\tTokens\\tTime%n\");\n\t\t\tfor (int i = 0; i< timePerFile[currentPass].length; i++) {\n\t\t\t\tSystem.out.format(\"%d\\t%d\\t%d%n\", i + 1, tokensPerFile[currentPass][i], timePerFile[currentPass][i]);\n\t\t\t}\n\t\t}\n    }\n\n\tprivate static long sum(long[] array) {\n\t\tlong result = 0;\n\t\tfor (int i = 0; i < array.length; i++) {\n\t\t\tresult += array[i];\n\t\t}\n\n\t\treturn result;\n\t}\n\n    protected JavaCompiledState compileJavaParser(boolean leftRecursive) throws IOException {\n        String grammarFileName = leftRecursive ? \"JavaLR.g4\"    : \"Java.g4\";\n        String parserName      = leftRecursive ? \"JavaLRParser\" : \"JavaParser\";\n        String lexerName       = leftRecursive ? \"JavaLRLexer\"  : \"JavaLexer\";\n        String body = load(grammarFileName);\n        List<String> extraOptions = new ArrayList<String>();\n\t\textraOptions.add(\"-Werror\");\n        if (FORCE_ATN) {\n            extraOptions.add(\"-Xforce-atn\");\n        }\n        if (EXPORT_ATN_GRAPHS) {\n            extraOptions.add(\"-atn\");\n        }\n\t\tif (DEBUG_TEMPLATES) {\n\t\t\textraOptions.add(\"-XdbgST\");\n\t\t\tif (DEBUG_TEMPLATES_WAIT) {\n\t\t\t\textraOptions.add(\"-XdbgSTWait\");\n\t\t\t}\n\t\t}\n        String[] extraOptionsArray = extraOptions.toArray(new String[0]);\n\n\t\tRunOptions runOptions = createOptionsForJavaToolTests(grammarFileName, body, parserName, lexerName,\n\t\t\t\tfalse, true, null, null,\n\t\t\t\tfalse, false, Stage.Compile);\n\t\ttry (RuntimeRunner runner = new JavaRunner()) {\n\t\t\treturn (JavaCompiledState) runner.run(runOptions);\n\t\t}\n    }\n\n\tprivate static void updateChecksum(MurmurHashChecksum checksum, int value) {\n\t\tchecksum.update(value);\n\t}\n\n\tprivate static void updateChecksum(MurmurHashChecksum checksum, Token token) {\n\t\tif (token == null) {\n\t\t\tchecksum.update(0);\n\t\t\treturn;\n\t\t}\n\n\t\tupdateChecksum(checksum, token.getStartIndex());\n\t\tupdateChecksum(checksum, token.getStopIndex());\n\t\tupdateChecksum(checksum, token.getLine());\n\t\tupdateChecksum(checksum, token.getCharPositionInLine());\n\t\tupdateChecksum(checksum, token.getType());\n\t\tupdateChecksum(checksum, token.getChannel());\n\t}\n\n    protected ParserFactory getParserFactory(JavaCompiledState javaCompiledState, String listenerName, final String entryPoint) {\n        try {\n            ClassLoader loader = javaCompiledState.loader;\n\t\t\tfinal Class<? extends ParseTreeListener> listenerClass = loader.loadClass(listenerName).asSubclass(ParseTreeListener.class);\n\n            final Constructor<? extends Lexer> lexerCtor = javaCompiledState.lexer.getConstructor(CharStream.class);\n            final Constructor<? extends Parser> parserCtor = javaCompiledState.parser.getConstructor(TokenStream.class);\n\n            // construct initial instances of the lexer and parser to deserialize their ATNs\n\t\t\tjavaCompiledState.initializeDummyLexerAndParser();\n\n            return new ParserFactory() {\n\n\t\t\t\t@Override\n                public FileParseResult parseFile(CharStream input, int currentPass, int thread) {\n\t\t\t\t\tfinal MurmurHashChecksum checksum = new MurmurHashChecksum();\n\n\t\t\t\t\tfinal long startTime = System.nanoTime();\n\t\t\t\t\tassert thread >= 0 && thread < NUMBER_OF_THREADS;\n\n                    try {\n\t\t\t\t\t\tParseTreeListener listener = sharedListeners[thread];\n\t\t\t\t\t\tif (listener == null) {\n\t\t\t\t\t\t\tlistener = listenerClass.newInstance();\n\t\t\t\t\t\t\tsharedListeners[thread] = listener;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tLexer lexer = sharedLexers[thread];\n                        if (REUSE_LEXER && lexer != null) {\n                            lexer.setInputStream(input);\n                        } else {\n\t\t\t\t\t\t\tLexer previousLexer = lexer;\n                            lexer = lexerCtor.newInstance(input);\n\t\t\t\t\t\t\tDFA[] decisionToDFA = (FILE_GRANULARITY || previousLexer == null ? lexer : previousLexer).getInterpreter().decisionToDFA;\n\t\t\t\t\t\t\tif (!REUSE_LEXER_DFA || (!FILE_GRANULARITY && previousLexer == null)) {\n\t\t\t\t\t\t\t\tdecisionToDFA = new DFA[decisionToDFA.length];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\t\t\t\t\t\tlexer.setInterpreter(new StatisticsLexerATNSimulator(lexer, lexer.getATN(), decisionToDFA, lexer.getInterpreter().getSharedContextCache()));\n\t\t\t\t\t\t\t} else if (!REUSE_LEXER_DFA) {\n\t\t\t\t\t\t\t\tlexer.setInterpreter(new LexerATNSimulator(lexer, lexer.getATN(), decisionToDFA, lexer.getInterpreter().getSharedContextCache()));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tsharedLexers[thread] = lexer;\n                        }\n\n\t\t\t\t\t\tlexer.removeErrorListeners();\n\t\t\t\t\t\tlexer.addErrorListener(DescriptiveErrorListener.INSTANCE);\n\n\t\t\t\t\t\tif (lexer.getInterpreter().decisionToDFA[0] == null) {\n\t\t\t\t\t\t\tATN atn = lexer.getATN();\n\t\t\t\t\t\t\tfor (int i = 0; i < lexer.getInterpreter().decisionToDFA.length; i++) {\n\t\t\t\t\t\t\t\tlexer.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n                        CommonTokenStream tokens = new CommonTokenStream(lexer);\n                        tokens.fill();\n                        tokenCount.addAndGet(currentPass, tokens.size());\n\n\t\t\t\t\t\tif (COMPUTE_CHECKSUM) {\n\t\t\t\t\t\t\tfor (Token token : tokens.getTokens()) {\n\t\t\t\t\t\t\t\tupdateChecksum(checksum, token);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n                        if (!RUN_PARSER) {\n                            return new FileParseResult(input.getSourceName(), (int)checksum.getValue(), null, tokens.size(), startTime, lexer, null);\n                        }\n\n\t\t\t\t\t\tfinal long parseStartTime = System.nanoTime();\n\t\t\t\t\t\tParser parser = sharedParsers[thread];\n                        if (REUSE_PARSER && parser != null) {\n                            parser.setInputStream(tokens);\n                        } else {\n\t\t\t\t\t\t\tParser previousParser = parser;\n\n\t\t\t\t\t\t\tif (USE_PARSER_INTERPRETER) {\n\t\t\t\t\t\t\t\tParser referenceParser = parserCtor.newInstance(tokens);\n\t\t\t\t\t\t\t\tparser = new ParserInterpreter(referenceParser.getGrammarFileName(), referenceParser.getVocabulary(), Arrays.asList(referenceParser.getRuleNames()), referenceParser.getATN(), tokens);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tparser = parserCtor.newInstance(tokens);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tDFA[] decisionToDFA = (FILE_GRANULARITY || previousParser == null ? parser : previousParser).getInterpreter().decisionToDFA;\n\t\t\t\t\t\t\tif (!REUSE_PARSER_DFA || (!FILE_GRANULARITY && previousParser == null)) {\n\t\t\t\t\t\t\t\tdecisionToDFA = new DFA[decisionToDFA.length];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\t\t\t\t\t\tparser.setInterpreter(new StatisticsParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache()));\n\t\t\t\t\t\t\t} else if (!REUSE_PARSER_DFA) {\n\t\t\t\t\t\t\t\tparser.setInterpreter(new ParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache()));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tsharedParsers[thread] = parser;\n                        }\n\n\t\t\t\t\t\tparser.removeParseListeners();\n\t\t\t\t\t\tparser.removeErrorListeners();\n\t\t\t\t\t\tif (!TWO_STAGE_PARSING) {\n\t\t\t\t\t\t\tparser.addErrorListener(DescriptiveErrorListener.INSTANCE);\n\t\t\t\t\t\t\tparser.addErrorListener(new SummarizingDiagnosticErrorListener());\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (parser.getInterpreter().decisionToDFA[0] == null) {\n\t\t\t\t\t\t\tATN atn = parser.getATN();\n\t\t\t\t\t\t\tfor (int i = 0; i < parser.getInterpreter().decisionToDFA.length; i++) {\n\t\t\t\t\t\t\t\tparser.getInterpreter().decisionToDFA[i] = new DFA(atn.getDecisionState(i), i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tparser.getInterpreter().setPredictionMode(TWO_STAGE_PARSING ? PredictionMode.SLL : PREDICTION_MODE);\n\t\t\t\t\t\tparser.setBuildParseTree(BUILD_PARSE_TREES);\n\t\t\t\t\t\tif (!BUILD_PARSE_TREES && BLANK_LISTENER) {\n\t\t\t\t\t\t\tparser.addParseListener(listener);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (BAIL_ON_ERROR || TWO_STAGE_PARSING) {\n\t\t\t\t\t\t\tparser.setErrorHandler(new BailErrorStrategy());\n\t\t\t\t\t\t}\n\n                        Method parseMethod = javaCompiledState.parser.getMethod(entryPoint);\n                        Object parseResult;\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (COMPUTE_CHECKSUM && !BUILD_PARSE_TREES) {\n\t\t\t\t\t\t\t\tparser.addParseListener(new ChecksumParseTreeListener(checksum));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (USE_PARSER_INTERPRETER) {\n\t\t\t\t\t\t\t\tParserInterpreter parserInterpreter = (ParserInterpreter)parser;\n\t\t\t\t\t\t\t\tparseResult = parserInterpreter.parse(Collections.lastIndexOfSubList(Arrays.asList(parser.getRuleNames()), Collections.singletonList(entryPoint)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tparseResult = parseMethod.invoke(parser);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (InvocationTargetException ex) {\n\t\t\t\t\t\t\tif (!TWO_STAGE_PARSING) {\n\t\t\t\t\t\t\t\tthrow ex;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tString sourceName = tokens.getSourceName();\n\t\t\t\t\t\t\tsourceName = sourceName != null && !sourceName.isEmpty() ? sourceName+\": \" : \"\";\n\t\t\t\t\t\t\tif (REPORT_SECOND_STAGE_RETRY) {\n\t\t\t\t\t\t\t\tSystem.err.println(sourceName+\"Forced to retry with full context.\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (!(ex.getCause() instanceof ParseCancellationException)) {\n\t\t\t\t\t\t\t\tthrow ex;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\ttokens.seek(0);\n\t\t\t\t\t\t\tif (REUSE_PARSER && parser != null) {\n\t\t\t\t\t\t\t\tparser.setInputStream(tokens);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tParser previousParser = parser;\n\n\t\t\t\t\t\t\t\tif (USE_PARSER_INTERPRETER) {\n\t\t\t\t\t\t\t\t\tParser referenceParser = parserCtor.newInstance(tokens);\n\t\t\t\t\t\t\t\t\tparser = new ParserInterpreter(referenceParser.getGrammarFileName(), referenceParser.getVocabulary(), Arrays.asList(referenceParser.getRuleNames()), referenceParser.getATN(), tokens);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tparser = parserCtor.newInstance(tokens);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tDFA[] decisionToDFA = previousParser.getInterpreter().decisionToDFA;\n\t\t\t\t\t\t\t\tif (COMPUTE_TRANSITION_STATS) {\n\t\t\t\t\t\t\t\t\tparser.setInterpreter(new StatisticsParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache()));\n\t\t\t\t\t\t\t\t} else if (!REUSE_PARSER_DFA) {\n\t\t\t\t\t\t\t\t\tparser.setInterpreter(new ParserATNSimulator(parser, parser.getATN(), decisionToDFA, parser.getInterpreter().getSharedContextCache()));\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tsharedParsers[thread] = parser;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tparser.removeParseListeners();\n\t\t\t\t\t\t\tparser.removeErrorListeners();\n\t\t\t\t\t\t\tparser.addErrorListener(DescriptiveErrorListener.INSTANCE);\n\t\t\t\t\t\t\tparser.addErrorListener(new SummarizingDiagnosticErrorListener());\n\t\t\t\t\t\t\tparser.getInterpreter().setPredictionMode(PredictionMode.LL);\n\t\t\t\t\t\t\tparser.setBuildParseTree(BUILD_PARSE_TREES);\n\t\t\t\t\t\t\tif (COMPUTE_CHECKSUM && !BUILD_PARSE_TREES) {\n\t\t\t\t\t\t\t\tparser.addParseListener(new ChecksumParseTreeListener(checksum));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!BUILD_PARSE_TREES && BLANK_LISTENER) {\n\t\t\t\t\t\t\t\tparser.addParseListener(listener);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (BAIL_ON_ERROR) {\n\t\t\t\t\t\t\t\tparser.setErrorHandler(new BailErrorStrategy());\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tparseResult = parseMethod.invoke(parser);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tassertTrue(parseResult instanceof ParseTree);\n\t\t\t\t\t\tif (COMPUTE_CHECKSUM && BUILD_PARSE_TREES) {\n\t\t\t\t\t\t\tParseTreeWalker.DEFAULT.walk(new ChecksumParseTreeListener(checksum), (ParseTree)parseResult);\n\t\t\t\t\t\t}\n                        if (BUILD_PARSE_TREES && BLANK_LISTENER) {\n                            ParseTreeWalker.DEFAULT.walk(listener, (ParseTree)parseResult);\n                        }\n\n\t\t\t\t\t\treturn new FileParseResult(input.getSourceName(), (int)checksum.getValue(), (ParseTree)parseResult, tokens.size(), TIME_PARSE_ONLY ? parseStartTime : startTime, lexer, parser);\n                    } catch (Exception e) {\n\t\t\t\t\t\tif (!REPORT_SYNTAX_ERRORS && e instanceof ParseCancellationException) {\n\t\t\t\t\t\t\treturn new FileParseResult(\"unknown\", (int)checksum.getValue(), null, 0, startTime, null, null);\n\t\t\t\t\t\t}\n\n                        e.printStackTrace(System.out);\n                        throw new IllegalStateException(e);\n                    }\n                }\n            };\n        } catch (Exception e) {\n            e.printStackTrace(System.out);\n            fail(e.getMessage());\n            throw new IllegalStateException(e);\n        }\n    }\n\n    protected interface ParserFactory {\n        FileParseResult parseFile(CharStream input, int currentPass, int thread);\n    }\n\n\tprotected static class FileParseResult {\n\t\tpublic final String sourceName;\n\t\tpublic final int checksum;\n\t\tpublic final ParseTree parseTree;\n\t\tpublic final int tokenCount;\n\t\tpublic final long startTime;\n\t\tpublic final long endTime;\n\n\t\tpublic final int lexerDFASize;\n\t\tpublic final long lexerTotalTransitions;\n\t\tpublic final long lexerComputedTransitions;\n\n\t\tpublic final int parserDFASize;\n\t\tpublic final long[] decisionInvocations;\n\t\tpublic final long[] fullContextFallback;\n\t\tpublic final long[] nonSll;\n\t\tpublic final long[] parserTotalTransitions;\n\t\tpublic final long[] parserComputedTransitions;\n\t\tpublic final long[] parserFullContextTransitions;\n\n\t\tpublic FileParseResult(String sourceName, int checksum, ParseTree parseTree, int tokenCount, long startTime, Lexer lexer, Parser parser) {\n\t\t\tthis.sourceName = sourceName;\n\t\t\tthis.checksum = checksum;\n\t\t\tthis.parseTree = parseTree;\n\t\t\tthis.tokenCount = tokenCount;\n\t\t\tthis.startTime = startTime;\n\t\t\tthis.endTime = System.nanoTime();\n\n\t\t\tif (lexer != null) {\n\t\t\t\tLexerATNSimulator interpreter = lexer.getInterpreter();\n\t\t\t\tif (interpreter instanceof StatisticsLexerATNSimulator) {\n\t\t\t\t\tlexerTotalTransitions = ((StatisticsLexerATNSimulator)interpreter).totalTransitions;\n\t\t\t\t\tlexerComputedTransitions = ((StatisticsLexerATNSimulator)interpreter).computedTransitions;\n\t\t\t\t} else {\n\t\t\t\t\tlexerTotalTransitions = 0;\n\t\t\t\t\tlexerComputedTransitions = 0;\n\t\t\t\t}\n\n\t\t\t\tint dfaSize = 0;\n\t\t\t\tfor (DFA dfa : interpreter.decisionToDFA) {\n\t\t\t\t\tif (dfa != null) {\n\t\t\t\t\t\tdfaSize += dfa.states.size();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlexerDFASize = dfaSize;\n\t\t\t} else {\n\t\t\t\tlexerDFASize = 0;\n\t\t\t\tlexerTotalTransitions = 0;\n\t\t\t\tlexerComputedTransitions = 0;\n\t\t\t}\n\n\t\t\tif (parser != null) {\n\t\t\t\tParserATNSimulator interpreter = parser.getInterpreter();\n\t\t\t\tif (interpreter instanceof StatisticsParserATNSimulator) {\n\t\t\t\t\tdecisionInvocations = ((StatisticsParserATNSimulator)interpreter).decisionInvocations;\n\t\t\t\t\tfullContextFallback = ((StatisticsParserATNSimulator)interpreter).fullContextFallback;\n\t\t\t\t\tnonSll = ((StatisticsParserATNSimulator)interpreter).nonSll;\n\t\t\t\t\tparserTotalTransitions = ((StatisticsParserATNSimulator)interpreter).totalTransitions;\n\t\t\t\t\tparserComputedTransitions = ((StatisticsParserATNSimulator)interpreter).computedTransitions;\n\t\t\t\t\tparserFullContextTransitions = ((StatisticsParserATNSimulator)interpreter).fullContextTransitions;\n\t\t\t\t} else {\n\t\t\t\t\tdecisionInvocations = new long[0];\n\t\t\t\t\tfullContextFallback = new long[0];\n\t\t\t\t\tnonSll = new long[0];\n\t\t\t\t\tparserTotalTransitions = new long[0];\n\t\t\t\t\tparserComputedTransitions = new long[0];\n\t\t\t\t\tparserFullContextTransitions = new long[0];\n\t\t\t\t}\n\n\t\t\t\tint dfaSize = 0;\n\t\t\t\tfor (DFA dfa : interpreter.decisionToDFA) {\n\t\t\t\t\tif (dfa != null) {\n\t\t\t\t\t\tdfaSize += dfa.states.size();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tparserDFASize = dfaSize;\n\t\t\t} else {\n\t\t\t\tparserDFASize = 0;\n\t\t\t\tdecisionInvocations = new long[0];\n\t\t\t\tfullContextFallback = new long[0];\n\t\t\t\tnonSll = new long[0];\n\t\t\t\tparserTotalTransitions = new long[0];\n\t\t\t\tparserComputedTransitions = new long[0];\n\t\t\t\tparserFullContextTransitions = new long[0];\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static class StatisticsLexerATNSimulator extends LexerATNSimulator {\n\n\t\tpublic long totalTransitions;\n\t\tpublic long computedTransitions;\n\n\t\tpublic StatisticsLexerATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) {\n\t\t\tsuper(atn, decisionToDFA, sharedContextCache);\n\t\t}\n\n\t\tpublic StatisticsLexerATNSimulator(Lexer recog, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) {\n\t\t\tsuper(recog, atn, decisionToDFA, sharedContextCache);\n\t\t}\n\n\t\t@Override\n\t\tprotected DFAState getExistingTargetState(DFAState s, int t) {\n\t\t\ttotalTransitions++;\n\t\t\treturn super.getExistingTargetState(s, t);\n\t\t}\n\n\t\t@Override\n\t\tprotected DFAState computeTargetState(CharStream input, DFAState s, int t) {\n\t\t\tcomputedTransitions++;\n\t\t\treturn super.computeTargetState(input, s, t);\n\t\t}\n\t}\n\n\tprivate static class StatisticsParserATNSimulator extends ParserATNSimulator {\n\n\t\tpublic final long[] decisionInvocations;\n\t\tpublic final long[] fullContextFallback;\n\t\tpublic final long[] nonSll;\n\t\tpublic final long[] totalTransitions;\n\t\tpublic final long[] computedTransitions;\n\t\tpublic final long[] fullContextTransitions;\n\n\t\tprivate int decision;\n\n\t\tpublic StatisticsParserATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) {\n\t\t\tsuper(atn, decisionToDFA, sharedContextCache);\n\t\t\tdecisionInvocations = new long[atn.decisionToState.size()];\n\t\t\tfullContextFallback = new long[atn.decisionToState.size()];\n\t\t\tnonSll = new long[atn.decisionToState.size()];\n\t\t\ttotalTransitions = new long[atn.decisionToState.size()];\n\t\t\tcomputedTransitions = new long[atn.decisionToState.size()];\n\t\t\tfullContextTransitions = new long[atn.decisionToState.size()];\n\t\t}\n\n\t\tpublic StatisticsParserATNSimulator(Parser parser, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) {\n\t\t\tsuper(parser, atn, decisionToDFA, sharedContextCache);\n\t\t\tdecisionInvocations = new long[atn.decisionToState.size()];\n\t\t\tfullContextFallback = new long[atn.decisionToState.size()];\n\t\t\tnonSll = new long[atn.decisionToState.size()];\n\t\t\ttotalTransitions = new long[atn.decisionToState.size()];\n\t\t\tcomputedTransitions = new long[atn.decisionToState.size()];\n\t\t\tfullContextTransitions = new long[atn.decisionToState.size()];\n\t\t}\n\n\t\t@Override\n\t\tpublic int adaptivePredict(TokenStream input, int decision, ParserRuleContext outerContext) {\n\t\t\ttry {\n\t\t\t\tthis.decision = decision;\n\t\t\t\tdecisionInvocations[decision]++;\n\t\t\t\treturn super.adaptivePredict(input, decision, outerContext);\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tthis.decision = -1;\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tprotected int execATNWithFullContext(DFA dfa, DFAState D, ATNConfigSet s0, TokenStream input, int startIndex, ParserRuleContext outerContext) {\n\t\t\tfullContextFallback[decision]++;\n\t\t\treturn super.execATNWithFullContext(dfa, D, s0, input, startIndex, outerContext);\n\t\t}\n\n\t\t@Override\n\t\tprotected DFAState getExistingTargetState(DFAState previousD, int t) {\n\t\t\ttotalTransitions[decision]++;\n\t\t\treturn super.getExistingTargetState(previousD, t);\n\t\t}\n\n\t\t@Override\n\t\tprotected DFAState computeTargetState(DFA dfa, DFAState previousD, int t) {\n\t\t\tcomputedTransitions[decision]++;\n\t\t\treturn super.computeTargetState(dfa, previousD, t);\n\t\t}\n\n\t\t@Override\n\t\tprotected ATNConfigSet computeReachSet(ATNConfigSet closure, int t, boolean fullCtx) {\n\t\t\tif (fullCtx) {\n\t\t\t\ttotalTransitions[decision]++;\n\t\t\t\tcomputedTransitions[decision]++;\n\t\t\t\tfullContextTransitions[decision]++;\n\t\t\t}\n\n\t\t\treturn super.computeReachSet(closure, t, fullCtx);\n\t\t}\n\t}\n\n\tprivate static class DescriptiveErrorListener extends BaseErrorListener {\n\t\tpublic final static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener();\n\n\t\t@Override\n\t\tpublic void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,\n\t\t\t\t\t\t\t\tint line, int charPositionInLine,\n\t\t\t\t\t\t\t\tString msg, RecognitionException e)\n\t\t{\n\t\t\tif (!REPORT_SYNTAX_ERRORS) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tString sourceName = recognizer.getInputStream().getSourceName();\n\t\t\tif (!sourceName.isEmpty()) {\n\t\t\t\tsourceName = String.format(\"%s:%d:%d: \", sourceName, line, charPositionInLine);\n\t\t\t}\n\n\t\t\tSystem.err.println(sourceName+\"line \"+line+\":\"+charPositionInLine+\" \"+msg);\n\t\t}\n\n\t}\n\n\tprivate static class SummarizingDiagnosticErrorListener extends DiagnosticErrorListener {\n\t\tprivate BitSet _sllConflict;\n\t\tprivate ATNConfigSet _sllConfigs;\n\n\t\t@Override\n\t\tpublic void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, ATNConfigSet configs) {\n\t\t\tif (COMPUTE_TRANSITION_STATS && DETAILED_DFA_STATE_STATS) {\n\t\t\t\tBitSet sllPredictions = getConflictingAlts(_sllConflict, _sllConfigs);\n\t\t\t\tint sllPrediction = sllPredictions.nextSetBit(0);\n\t\t\t\tBitSet llPredictions = getConflictingAlts(ambigAlts, configs);\n\t\t\t\tint llPrediction = llPredictions.cardinality() == 0 ? ATN.INVALID_ALT_NUMBER : llPredictions.nextSetBit(0);\n\t\t\t\tif (sllPrediction != llPrediction) {\n\t\t\t\t\t((StatisticsParserATNSimulator)recognizer.getInterpreter()).nonSll[dfa.decision]++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!REPORT_AMBIGUITIES) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// show the rule name along with the decision\n\t\t\tString format = \"reportAmbiguity d=%d (%s): ambigAlts=%s, input='%s'\";\n\t\t\tint decision = dfa.decision;\n\t\t\tString rule = recognizer.getRuleNames()[dfa.atnStartState.ruleIndex];\n\t\t\tString input = recognizer.getTokenStream().getText(Interval.of(startIndex, stopIndex));\n\t\t\trecognizer.notifyErrorListeners(String.format(format, decision, rule, ambigAlts, input));\n\t\t}\n\n\t\t@Override\n\t\tpublic void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs) {\n\t\t\t_sllConflict = conflictingAlts;\n\t\t\t_sllConfigs = configs;\n\t\t\tif (!REPORT_FULL_CONTEXT) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// show the rule name and viable configs along with the base info\n\t\t\tString format = \"reportAttemptingFullContext d=%d (%s), input='%s', viable=%s\";\n\t\t\tint decision = dfa.decision;\n\t\t\tString rule = recognizer.getRuleNames()[dfa.atnStartState.ruleIndex];\n\t\t\tString input = recognizer.getTokenStream().getText(Interval.of(startIndex, stopIndex));\n\t\t\tBitSet representedAlts = getConflictingAlts(conflictingAlts, configs);\n\t\t\trecognizer.notifyErrorListeners(String.format(format, decision, rule, input, representedAlts));\n\t\t}\n\n\t\t@Override\n\t\tpublic void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs) {\n\t\t\tif (COMPUTE_TRANSITION_STATS && DETAILED_DFA_STATE_STATS) {\n\t\t\t\tBitSet sllPredictions = getConflictingAlts(_sllConflict, _sllConfigs);\n\t\t\t\tint sllPrediction = sllPredictions.nextSetBit(0);\n\t\t\t\tif (sllPrediction != prediction) {\n\t\t\t\t\t((StatisticsParserATNSimulator)recognizer.getInterpreter()).nonSll[dfa.decision]++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!REPORT_CONTEXT_SENSITIVITY) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// show the rule name and viable configs along with the base info\n\t\t\tString format = \"reportContextSensitivity d=%d (%s), input='%s', viable={%d}\";\n\t\t\tint decision = dfa.decision;\n\t\t\tString rule = recognizer.getRuleNames()[dfa.atnStartState.ruleIndex];\n\t\t\tString input = recognizer.getTokenStream().getText(Interval.of(startIndex, stopIndex));\n\t\t\trecognizer.notifyErrorListeners(String.format(format, decision, rule, input, prediction));\n\t\t}\n\n\t}\n\n\tprotected static final class FilenameFilters {\n\t\tpublic static final FilenameFilter ALL_FILES = new FilenameFilter() {\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t};\n\n\t\tpublic static FilenameFilter extension(String extension) {\n\t\t\treturn extension(extension, true);\n\t\t}\n\n\t\tpublic static FilenameFilter extension(String extension, boolean caseSensitive) {\n\t\t\treturn new FileExtensionFilenameFilter(extension, caseSensitive);\n\t\t}\n\n\t\tpublic static FilenameFilter name(String filename) {\n\t\t\treturn name(filename, true);\n\t\t}\n\n\t\tpublic static FilenameFilter name(String filename, boolean caseSensitive) {\n\t\t\treturn new FileNameFilenameFilter(filename, caseSensitive);\n\t\t}\n\n\t\tpublic static FilenameFilter all(FilenameFilter... filters) {\n\t\t\treturn new AllFilenameFilter(filters);\n\t\t}\n\n\t\tpublic static FilenameFilter any(FilenameFilter... filters) {\n\t\t\treturn new AnyFilenameFilter(filters);\n\t\t}\n\n\t\tpublic static FilenameFilter none(FilenameFilter... filters) {\n\t\t\treturn not(any(filters));\n\t\t}\n\n\t\tpublic static FilenameFilter not(FilenameFilter filter) {\n\t\t\treturn new NotFilenameFilter(filter);\n\t\t}\n\n\t\tprivate FilenameFilters() {\n\t\t}\n\n\t\tprotected static class FileExtensionFilenameFilter implements FilenameFilter {\n\n\t\t\tprivate final String extension;\n\t\t\tprivate final boolean caseSensitive;\n\n\t\t\tpublic FileExtensionFilenameFilter(String extension, boolean caseSensitive) {\n\t\t\t\tif (!extension.startsWith(\".\")) {\n\t\t\t\t\textension = '.' + extension;\n\t\t\t\t}\n\n\t\t\t\tthis.extension = extension;\n\t\t\t\tthis.caseSensitive = caseSensitive;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\tif (caseSensitive) {\n\t\t\t\t\treturn name.endsWith(extension);\n\t\t\t\t} else {\n\t\t\t\t\treturn name.toLowerCase().endsWith(extension);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprotected static class FileNameFilenameFilter implements FilenameFilter {\n\n\t\t\tprivate final String filename;\n\t\t\tprivate final boolean caseSensitive;\n\n\t\t\tpublic FileNameFilenameFilter(String filename, boolean caseSensitive) {\n\t\t\t\tthis.filename = filename;\n\t\t\t\tthis.caseSensitive = caseSensitive;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\tif (caseSensitive) {\n\t\t\t\t\treturn name.equals(filename);\n\t\t\t\t} else {\n\t\t\t\t\treturn name.toLowerCase().equals(filename);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprotected static class AllFilenameFilter implements FilenameFilter {\n\n\t\t\tprivate final FilenameFilter[] filters;\n\n\t\t\tpublic AllFilenameFilter(FilenameFilter[] filters) {\n\t\t\t\tthis.filters = filters;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\tfor (FilenameFilter filter : filters) {\n\t\t\t\t\tif (!filter.accept(dir, name)) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tprotected static class AnyFilenameFilter implements FilenameFilter {\n\n\t\t\tprivate final FilenameFilter[] filters;\n\n\t\t\tpublic AnyFilenameFilter(FilenameFilter[] filters) {\n\t\t\t\tthis.filters = filters;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\tfor (FilenameFilter filter : filters) {\n\t\t\t\t\tif (filter.accept(dir, name)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tprotected static class NotFilenameFilter implements FilenameFilter {\n\n\t\t\tprivate final FilenameFilter filter;\n\n\t\t\tpublic NotFilenameFilter(FilenameFilter filter) {\n\t\t\t\tthis.filter = filter;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\treturn !filter.accept(dir, name);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected static class NumberedThread extends Thread {\n\t\tprivate final int threadNumber;\n\n\t\tpublic NumberedThread(Runnable target, int threadNumber) {\n\t\t\tsuper(target);\n\t\t\tthis.threadNumber = threadNumber;\n\t\t}\n\n\t\tpublic final int getThreadNumber() {\n\t\t\treturn threadNumber;\n\t\t}\n\n\t}\n\n\tprotected static class NumberedThreadFactory implements ThreadFactory {\n\t\tprivate final AtomicInteger nextThread = new AtomicInteger();\n\n\t\t@Override\n\t\tpublic Thread newThread(Runnable r) {\n\t\t\tint threadNumber = nextThread.getAndIncrement();\n\t\t\tassert threadNumber < NUMBER_OF_THREADS;\n\t\t\treturn new NumberedThread(r, threadNumber);\n\t\t}\n\n\t}\n\n\tprotected static class FixedThreadNumberFactory implements ThreadFactory {\n\t\tprivate final int threadNumber;\n\n\t\tpublic FixedThreadNumberFactory(int threadNumber) {\n\t\t\tthis.threadNumber = threadNumber;\n\t\t}\n\n\t\t@Override\n\t\tpublic Thread newThread(Runnable r) {\n\t\t\tassert threadNumber < NUMBER_OF_THREADS;\n\t\t\treturn new NumberedThread(r, threadNumber);\n\t\t}\n\t}\n\n\tprotected static class ChecksumParseTreeListener implements ParseTreeListener {\n\t\tprivate static final int VISIT_TERMINAL = 1;\n\t\tprivate static final int VISIT_ERROR_NODE = 2;\n\t\tprivate static final int ENTER_RULE = 3;\n\t\tprivate static final int EXIT_RULE = 4;\n\n\t\tprivate final MurmurHashChecksum checksum;\n\n\t\tpublic ChecksumParseTreeListener(MurmurHashChecksum checksum) {\n\t\t\tthis.checksum = checksum;\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitTerminal(TerminalNode node) {\n\t\t\tchecksum.update(VISIT_TERMINAL);\n\t\t\tupdateChecksum(checksum, node.getSymbol());\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitErrorNode(ErrorNode node) {\n\t\t\tchecksum.update(VISIT_ERROR_NODE);\n\t\t\tupdateChecksum(checksum, node.getSymbol());\n\t\t}\n\n\t\t@Override\n\t\tpublic void enterEveryRule(ParserRuleContext ctx) {\n\t\t\tchecksum.update(ENTER_RULE);\n\t\t\tupdateChecksum(checksum, ctx.getRuleIndex());\n\t\t\tupdateChecksum(checksum, ctx.getStart());\n\t\t}\n\n\t\t@Override\n\t\tpublic void exitEveryRule(ParserRuleContext ctx) {\n\t\t\tchecksum.update(EXIT_RULE);\n\t\t\tupdateChecksum(checksum, ctx.getRuleIndex());\n\t\t\tupdateChecksum(checksum, ctx.getStop());\n\t\t}\n\n\t}\n\n\tprotected static final class InputDescriptor {\n\t\tprivate final String source;\n\t\tprivate Reference<CloneableANTLRFileStream> inputStream;\n\n\t\tpublic InputDescriptor(String source) {\n\t\t\tthis.source = source;\n\t\t\tif (PRELOAD_SOURCES) {\n\t\t\t\tgetInputStream();\n\t\t\t}\n\t\t}\n\n\n\t\tpublic synchronized CharStream getInputStream() {\n\t\t\tCloneableANTLRFileStream stream = inputStream != null ? inputStream.get() : null;\n\t\t\tif (stream == null) {\n\t\t\t\ttry {\n\t\t\t\t\tstream = new CloneableANTLRFileStream(source, ENCODING);\n\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t\t}\n\n\t\t\t\tif (PRELOAD_SOURCES) {\n\t\t\t\t\tinputStream = new StrongReference<CloneableANTLRFileStream>(stream);\n\t\t\t\t} else {\n\t\t\t\t\tinputStream = new SoftReference<CloneableANTLRFileStream>(stream);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new JavaUnicodeInputStream(stream.createCopy());\n\t\t}\n\t}\n\n\tprotected static class CloneableANTLRFileStream extends ANTLRFileStream {\n\n\t\tpublic CloneableANTLRFileStream(String fileName, String encoding) throws IOException {\n\t\t\tsuper(fileName, encoding);\n\t\t}\n\n\t\tpublic ANTLRInputStream createCopy() {\n\t\t\tANTLRInputStream stream = new ANTLRInputStream(this.data, this.n);\n\t\t\tstream.name = this.getSourceName();\n\t\t\treturn stream;\n\t\t}\n\t}\n\n\tpublic static class StrongReference<T> extends WeakReference<T> {\n\t\tpublic final T referent;\n\n\t\tpublic StrongReference(T referent) {\n\t\t\tsuper(referent);\n\t\t\tthis.referent = referent;\n\t\t}\n\n\t\t@Override\n\t\tpublic T get() {\n\t\t\treturn referent;\n\t\t}\n\t}\n\n\tprivate static class MurmurHashChecksum {\n\t\tprivate int value;\n\t\tprivate int count;\n\n\t\tpublic MurmurHashChecksum() {\n\t\t\tthis.value = MurmurHash.initialize();\n\t\t}\n\n\t\tpublic void update(int value) {\n\t\t\tthis.value = MurmurHash.update(this.value, value);\n\t\t\tthis.count++;\n\t\t}\n\n\t\tpublic int getValue() {\n\t\t\treturn MurmurHash.finish(value, count);\n\t\t}\n\t}\n\n\t@Test\n\t@Timeout(20)\n\tpublic void testExponentialInclude(@TempDir Path tempDir) {\n\t\tString tempDirPath = tempDir.toString();\n\t\tString grammarFormat =\n\t\t\t\"parser grammar Level_%d_%d;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"%s import Level_%d_1, Level_%d_2;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"rule_%d_%d : EOF;\\n\";\n\n\t\tFileUtils.mkdir(tempDirPath);\n\n\t\tlong startTime = System.nanoTime();\n\n\t\tint levels = 20;\n\t\tfor (int level = 0; level < levels; level++) {\n\t\t\tString leafPrefix = level == levels - 1 ? \"//\" : \"\";\n\t\t\tString grammar1 = String.format(grammarFormat, level, 1, leafPrefix, level + 1, level + 1, level, 1);\n\t\t\twriteFile(tempDirPath, \"Level_\" + level + \"_1.g4\", grammar1);\n\t\t\tif (level > 0) {\n\t\t\t\tString grammar2 = String.format(grammarFormat, level, 2, leafPrefix, level + 1, level + 1, level, 1);\n\t\t\t\twriteFile(tempDirPath, \"Level_\" + level + \"_2.g4\", grammar2);\n\t\t\t}\n\t\t}\n\n\t\tErrorQueue equeue = Generator.antlrOnString(tempDirPath, \"Java\", \"Level_0_1.g4\", false);\n\t\tassertTrue(equeue.errors.isEmpty());\n\n\t\tlong endTime = System.nanoTime();\n\t\tSystem.out.format(\"%s milliseconds.%n\", (endTime - startTime) / 1000000.0);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestScopeParsing.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.ScopeParser;\nimport org.antlr.v4.tool.Attribute;\nimport org.antlr.v4.tool.Grammar;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.MethodSource;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestScopeParsing {\n    final static String[] argPairs = {\n\t\t\t\"\", \"\",\n\t\t\t\" \", \"\",\n\t\t\t\"int i\", \"i:int\",\n\t\t\t\"int[] i, int j[]\", \"i:int[], j:int []\",\n\t\t\t\"Map<A,B>[] i, int j[]\", \"i:Map<A,B>[], j:int []\",\n\t\t\t\"Map<A,List<B>>[] i\", \"i:Map<A,List<B>>[]\",\n\t\t\t\"int i = 34+a[3], int j[] = new int[34]\",\n\t\t\t\"i:int=34+a[3], j:int []=new int[34]\",\n\t\t\t\"char *[3] foo = {1,2,3}\", \"foo:char *[3]={1,2,3}\", // not valid C really, C is \"type name\" however so this is cool (this was broken in 4.5 anyway)\n\t\t\t\"String[] headers\", \"headers:String[]\",\n\n\t\t\t// C++\n\t\t\t\"std::vector<std::string> x\", \"x:std::vector<std::string>\", // yuck. Don't choose :: as the : of a declaration\n\n\t\t\t// python/ruby style\n\t\t\t\"i\", \"i\",\n\t\t\t\"i,j\", \"i, j\",\n\t\t\t\"i\\t,j, k\", \"i, j, k\",\n\n\t\t\t// swift style\n\t\t\t\"x: int\", \"x:int\",\n\t\t\t\"x :int\", \"x:int\",\n\t\t\t\"x:int\", \"x:int\",\n\t\t\t\"x:int=3\", \"x:int=3\",\n\t\t\t\"r:Rectangle=Rectangle(fromLength: 6, fromBreadth: 12)\", \"r:Rectangle=Rectangle(fromLength: 6, fromBreadth: 12)\",\n\t\t\t\"p:pointer to int\", \"p:pointer to int\",\n\t\t\t\"a: array[3] of int\", \"a:array[3] of int\",\n\t\t\t\"a \\t:\\tfunc(array[3] of int)\", \"a:func(array[3] of int)\",\n\t\t\t\"x:int, y:float\", \"x:int, y:float\",\n\t\t\t\"x:T?, f:func(array[3] of int), y:int\", \"x:T?, f:func(array[3] of int), y:int\",\n\n\t\t\t// go is postfix type notation like \"x int\" but must use either \"int x\" or \"x:int\" in [...] actions\n\t\t\t\"float64 x = 3\", \"x:float64=3\",\n\t\t\t\"map[string]int x\", \"x:map[string]int\",\n\t};\n\n    @ParameterizedTest\n\t@MethodSource(\"getAllTestDescriptors\")\n    public void testArgs(Parameter parameter) throws Exception {\n\t\tGrammar dummy = new Grammar(\"grammar T; a:'a';\");\n\n\t\tLinkedHashMap<String, Attribute> attributes = ScopeParser.parseTypedArgList(null, parameter.input, dummy).attributes;\n\t\tList<String> out = new ArrayList<>();\n\t\tfor (String arg : attributes.keySet()) {\n\t\t\tAttribute attr = attributes.get(arg);\n\t\t\tout.add(attr.toString());\n\t\t}\n\t\tString actual = Utils.join(out.toArray(), \", \");\n\t\tassertEquals(parameter.output, actual);\n\t}\n\n\tprivate static Collection<Parameter> getAllTestDescriptors() {\n\t\tList<Parameter> tests = new ArrayList<>();\n\t\tfor (int i = 0; i < argPairs.length; i+=2) {\n\t\t\tString arg = argPairs[i];\n\t\t\tString output = argPairs[i+1];\n\t\t\ttests.add(new Parameter(arg, output));\n\t\t}\n\t\treturn tests;\n\t}\n\n\tstatic class Parameter {\n\t\tpublic final String input;\n\t\tpublic final String output;\n\n\t\tpublic Parameter(String input, String output) {\n\t\t\tthis.input = input;\n\t\t\tthis.output = output;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn input;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestSplitParser.java",
    "content": "package org.antlr.v4.test.tool;\n\nimport org.antlr.v4.Tool;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\n\nimport javax.tools.JavaCompiler;\nimport javax.tools.JavaFileObject;\nimport javax.tools.StandardJavaFileManager;\nimport javax.tools.ToolProvider;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.PathSeparator;\n\n\npublic class TestSplitParser {\n\n\tJavaCompiler compiler = ToolProvider.getSystemJavaCompiler();\n\tPath outDir = null;\n\n\t@BeforeEach\n\tpublic void beforeEach() throws IOException {\n\t\toutDir = Files.createTempDirectory(\"antlr4-tool-test-\").toAbsolutePath();\n\t}\n\n\t@Test\n\tpublic void testGeneratesDefaultFiles() throws Exception {\n\t\tSet<String> created = generate();\n\t\tassert created.size() == 4;\n\t\tassert created.contains(\"JavaLRLexer.java\");\n\t\tassert created.contains(\"JavaLRParser.java\");\n\t\tassert created.contains(\"JavaLRBaseListener.java\");\n\t\tassert created.contains(\"JavaLRListener.java\");\n\t\tcheckCompiles(created);\n\t}\n\n\t@Test\n\tpublic void testGeneratesNoListenerFiles() throws Exception {\n\t\tSet<String> created = generate(\"-no-listener\");\n\t\tassert created.size() == 2;\n\t\tassert created.contains(\"JavaLRLexer.java\");\n\t\tassert created.contains(\"JavaLRParser.java\");\n\t\tcheckCompiles(created);\n\t}\n\n\t@Test\n\tpublic void testGeneratesVisitorFiles() throws Exception {\n\t\tSet<String> created = generate(\"-visitor\");\n\t\tassert created.size() == 6;\n\t\tassert created.contains(\"JavaLRLexer.java\");\n\t\tassert created.contains(\"JavaLRParser.java\");\n\t\tassert created.contains(\"JavaLRBaseListener.java\");\n\t\tassert created.contains(\"JavaLRListener.java\");\n\t\tassert created.contains(\"JavaLRBaseVisitor.java\");\n\t\tassert created.contains(\"JavaLRVisitor.java\");\n\t\tcheckCompiles(created);\n\t}\n\n\t@Test\n\tpublic void testGeneratesSplitFiles() throws Exception {\n\t\tSet<String> created = generate(\"-split-parser\", \"-visitor\");\n\t\tassert created.size() == 8;\n\t\tassert created.contains(\"JavaLRLexer.java\");\n\t\tassert created.contains(\"JavaLRParser.java\");\n\t\tassert created.contains(\"JavaLRParserContexts.java\");\n\t\tassert created.contains(\"JavaLRParserDFA.java\");\n\t\tassert created.contains(\"JavaLRBaseListener.java\");\n\t\tassert created.contains(\"JavaLRListener.java\");\n\t\tassert created.contains(\"JavaLRBaseVisitor.java\");\n\t\tassert created.contains(\"JavaLRVisitor.java\");\n\t\tString content = Files.readString(Path.of(outDir.toString(), \"JavaLRParser.java\"));\n\t\tassert !content.contains(\"ATNDeserializer()\");\n\t\tassert !content.contains(\"extends ParserRuleContext\");\n\t\tcontent = Files.readString(Path.of(outDir.toString(), \"JavaLRParserContexts.java\"));\n\t\tassert !content.contains(\"ATNDeserializer()\");\n\t\tassert content.contains(\"extends ParserRuleContext\");\n\t\tcontent = Files.readString(Path.of(outDir.toString(), \"JavaLRParserDFA.java\"));\n\t\tassert content.contains(\"ATNDeserializer()\");\n\t\tassert !content.contains(\"extends ParserRuleContext\");\n\t\tcheckCompiles(created);\n\t}\n\n\tSet<String> generate(String ... args) throws IOException {\n\t\tList<String> options = new ArrayList<>(Arrays.asList(args));\n\t\tString grammar = getClass().getPackageName().replace(\".\", \"/\") + \"/JavaLR.g4\";\n\t\tURL url = Thread.currentThread().getContextClassLoader().getResource(grammar);\n\t\tassert url!=null;\n\t\tString path = url.getPath();\n\t\toptions.add(\"-o\");\n\t\toptions.add(outDir.toString());\n\t\toptions.add(\"-package\");\n\t\toptions.add(\"antlr4.split\");\n\t\toptions.add(path);\n\t\tTool antlr = new Tool(options.toArray(new String[] {}));\n\t\tantlr.processGrammarsOnCommandLine();\n\t\treturn Files.list(outDir)\n\t\t\t.map(Path::getFileName)\n\t\t\t.map(Object::toString)\n\t\t\t.filter(name -> name.endsWith(\".java\"))\n\t\t\t.collect(Collectors.toSet());\n\n\t}\n\n\tvoid checkCompiles(Set<String> generated) throws Exception, ClassNotFoundException {\n\t\tStandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);\n\t\tList<File> files = generated.stream()\n\t\t\t.map(name -> Path.of(outDir.toString(), name))\n\t\t\t.map(Path::toFile)\n\t\t\t.collect(Collectors.toList());\n\t\tIterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);\n\t\tIterable<String> compileOptions =\n\t\t\tArrays.asList(\"-g\", \"-source\", \"1.8\", \"-target\", \"1.8\", \"-implicit:class\", \"-Xlint:-options\", \"-d\",\n\t\t\t\toutDir.toString(), \"-cp\", outDir + PathSeparator + System.getProperty(\"java.class.path\"));\n\t\tJavaCompiler.CompilationTask task =\n\t\t\tcompiler.getTask(null, fileManager, null, compileOptions, null,\n\t\t\t\tcompilationUnits);\n\t\ttask.call();\n\t\tClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();\n\t\tClassLoader loader = new URLClassLoader(new URL[]{outDir.toUri().toURL()}, systemClassLoader);\n\t\tfor (String name : generated) {\n\t\t\tname = \"antlr4.split.\" + name.substring(0, name.indexOf(\".java\"));\n\t\t\tClass<?> klass = loader.loadClass(name);\n\t\t\tassert klass != null;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestSymbolIssues.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.tool.ErrorType;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.realElements;\nimport static org.antlr.v4.test.tool.ToolTestUtils.testErrors;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/** */\npublic class TestSymbolIssues {\n    final static String[] A = {\n        // INPUT\n        \"grammar A;\\n\" +\n        \"options { opt='sss'; k=3; }\\n\" +\n        \"\\n\" +\n        \"@members {foo}\\n\" +\n        \"@members {bar}\\n\" +\n        \"@lexer::header {package jj;}\\n\" +\n        \"@lexer::header {package kk;}\\n\" +\n        \"\\n\" +\n        \"a[int i] returns [foo f] : X ID a[3] b[34] c ;\\n\" +\n        \"b returns [int g] : Y 'y' 'if' a ;\\n\" +\n        \"c : FJKD ;\\n\" +\n        \"\\n\" +\n        \"ID : 'a'..'z'+ ID ;\",\n        // YIELDS\n\t\t\t\"error(\" + ErrorType.ACTION_REDEFINITION.code + \"): A.g4:5:1: redefinition of members action\\n\" +\n\t\t\t\"error(\" + ErrorType.ACTION_REDEFINITION.code + \"): A.g4:7:1: redefinition of header action\\n\" +\n\t\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): A.g4:2:10: unsupported option opt\\n\" +\n\t\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): A.g4:2:21: unsupported option k\\n\" +\n\t\t\t\"error(\" + ErrorType.ACTION_REDEFINITION.code + \"): A.g4:5:1: redefinition of members action\\n\" +\n\t\t\t\"warning(\" + ErrorType.IMPLICIT_TOKEN_DEFINITION.code + \"): A.g4:9:27: implicit definition of token X in parser\\n\" +\n\t\t\t\"warning(\" + ErrorType.IMPLICIT_TOKEN_DEFINITION.code + \"): A.g4:10:20: implicit definition of token Y in parser\\n\" +\n\t\t\t\"warning(\" + ErrorType.IMPLICIT_TOKEN_DEFINITION.code + \"): A.g4:11:4: implicit definition of token FJKD in parser\\n\" +\n\t\t\t\"error(\" + ErrorType.RULE_HAS_NO_ARGS.code + \"): A.g4:9:37: rule b has no defined parameters\\n\" +\n\t\t\t\"error(\" + ErrorType.MISSING_RULE_ARGS.code + \"): A.g4:10:31: missing argument(s) on rule reference: a\\n\"\n    };\n\n\tfinal static String[] B = {\n        // INPUT\n        \"parser grammar B;\\n\" +\n        \"tokens { ID, FOO, X, Y }\\n\" +\n        \"\\n\" +\n        \"a : s=ID b+=ID X=ID '.' ;\\n\" +\n        \"\\n\" +\n        \"b : x=ID x+=ID ;\\n\" +\n        \"\\n\" +\n        \"s : FOO ;\",\n        // YIELDS\n\t\t\"error(\" + ErrorType.LABEL_CONFLICTS_WITH_RULE.code + \"): B.g4:4:4: label s conflicts with rule with same name\\n\" +\n\t\t\"error(\" + ErrorType.LABEL_CONFLICTS_WITH_RULE.code + \"): B.g4:4:9: label b conflicts with rule with same name\\n\" +\n\t\t\"error(\" + ErrorType.LABEL_CONFLICTS_WITH_TOKEN.code + \"): B.g4:4:15: label X conflicts with token with same name\\n\" +\n\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): B.g4:6:9: label x type mismatch with previous definition: TOKEN_LIST_LABEL!=TOKEN_LABEL\\n\" +\n\t\t\"error(\" + ErrorType.IMPLICIT_STRING_DEFINITION.code + \"): B.g4:4:20: cannot create implicit token for string literal in non-combined grammar: '.'\\n\"\n    };\n\n\tfinal static String[] D = {\n        // INPUT\n        \"parser grammar D;\\n\" +\n\t\t\"tokens{ID}\\n\" +\n        \"a[int j] \\n\" +\n        \"        :       i=ID j=ID ;\\n\" +\n        \"\\n\" +\n        \"b[int i] returns [int i] : ID ;\\n\" +\n        \"\\n\" +\n        \"c[int i] returns [String k]\\n\" +\n        \"        :       ID ;\",\n\n        // YIELDS\n        \"error(\" + ErrorType.LABEL_CONFLICTS_WITH_ARG.code + \"): D.g4:4:21: label j conflicts with parameter with same name\\n\" +\n\t\t\"error(\" + ErrorType.RETVAL_CONFLICTS_WITH_ARG.code + \"): D.g4:6:22: return value i conflicts with parameter with same name\\n\"\n    };\n\n\tfinal static String[] E = {\n\t\t// INPUT\n\t\t\"grammar E;\\n\" +\n\t\t\"tokens {\\n\" +\n\t\t\"\tA, A,\\n\" +\n\t\t\"\tB,\\n\" +\n\t\t\"\tC\\n\" +\n\t\t\"}\\n\" +\n\t\t\"a : A ;\\n\",\n\n\t\t// YIELDS\n\t\t\"warning(\" + ErrorType.TOKEN_NAME_REASSIGNMENT.code + \"): E.g4:3:4: token name A is already defined\\n\"\n\t};\n\n\tfinal static String[] F = {\n\t\t// INPUT\n\t\t\"lexer grammar F;\\n\" +\n\t\t\"A: 'a';\\n\" +\n\t\t\"mode M1;\\n\" +\n\t\t\"A1: 'a';\\n\" +\n\t\t\"mode M2;\\n\" +\n\t\t\"A2: 'a';\\n\" +\n\t\t\"M1: 'b';\\n\",\n\n\t\t// YIELDS\n\t\t\"error(\" + ErrorType.MODE_CONFLICTS_WITH_TOKEN.code + \"): F.g4:3:0: mode M1 conflicts with token with same name\\n\"\n\t};\n\n    @Test public void testA() { testErrors(A, false); }\n    @Test public void testB() { testErrors(B, false); }\n\t@Test public void testD() { testErrors(D, false); }\n\t@Test public void testE() { testErrors(E, false); }\n\t@Test public void testF() { testErrors(F, false); }\n\n\t@Test public void testStringLiteralRedefs() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"mode X;\\n\"+\n\t\t\t\"B : 'a' ;\\n\"+\n\t\t\t\"mode Y;\\n\"+\n\t\t\t\"C : 'a' ;\\n\";\n\n\t\tLexerGrammar g = new LexerGrammar(grammar);\n\n\t\tString expectedTokenIDToTypeMap = \"{EOF=-1, A=1, B=2, C=3}\";\n\t\tString expectedStringLiteralToTypeMap = \"{}\";\n\t\tString expectedTypeToTokenList = \"[A, B, C]\";\n\n\t\tassertEquals(expectedTokenIDToTypeMap, g.tokenNameToTypeMap.toString());\n\t\tassertEquals(expectedStringLiteralToTypeMap, g.stringLiteralToTypeMap.toString());\n\t\tassertEquals(expectedTypeToTokenList, realElements(g.typeToTokenList).toString());\n\t}\n\n\t@Test public void testEmptyLexerModeDetection() throws Exception {\n\t\tString[] test = {\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a';\\n\" +\n\t\t\t\"mode X;\\n\" +\n\t\t\t\"fragment B : 'b';\",\n\n\t\t\t\"error(\" + ErrorType.MODE_WITHOUT_RULES.code + \"): L.g4:3:5: lexer mode X must contain at least one non-fragment rule\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testEmptyLexerRuleDetection() throws Exception {\n\t\tString[] test = {\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A : 'a';\\n\" +\n\t\t\t\"WS : [ \\t]* -> skip;\\n\" +\n\t\t\t\"mode X;\\n\" +\n\t\t\t\"  B : C;\\n\" +\n\t\t\t\"  fragment C : A | (A C)?;\",\n\n\t\t\t\"warning(\" + ErrorType.EPSILON_TOKEN.code + \"): L.g4:3:0: non-fragment lexer rule WS can match the empty string\\n\" +\n\t\t\t\"warning(\" + ErrorType.EPSILON_TOKEN.code + \"): L.g4:5:2: non-fragment lexer rule B can match the empty string\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testTokensModesChannelsDeclarationConflictsWithReserved() throws Exception {\n\t\tString[] test = {\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"channels { SKIP, HIDDEN, channel0 }\\n\" +\n\t\t\t\"A: 'a';\\n\" +\n\t\t\t\"mode MAX_CHAR_VALUE;\\n\" +\n\t\t\t\"MIN_CHAR_VALUE: 'a';\\n\" +\n\t\t\t\"mode DEFAULT_MODE;\\n\" +\n\t\t\t\"B: 'b';\\n\" +\n\t\t\t\"mode M;\\n\" +\n\t\t\t\"C: 'c';\",\n\n\t\t\t\"error(\" + ErrorType.RESERVED_RULE_NAME.code + \"): L.g4:5:0: cannot declare a rule with reserved name MIN_CHAR_VALUE\\n\" +\n\t\t\t\"error(\" + ErrorType.MODE_CONFLICTS_WITH_COMMON_CONSTANTS.code + \"): L.g4:4:0: cannot use or declare mode with reserved name MAX_CHAR_VALUE\\n\" +\n\t\t\t\"error(\" + ErrorType.CHANNEL_CONFLICTS_WITH_COMMON_CONSTANTS.code + \"): L.g4:2:11: cannot use or declare channel with reserved name SKIP\\n\" +\n\t\t\t\"error(\" + ErrorType.CHANNEL_CONFLICTS_WITH_COMMON_CONSTANTS.code + \"): L.g4:2:17: cannot use or declare channel with reserved name HIDDEN\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testTokensModesChannelsUsingConflictsWithReserved() throws Exception {\n\t\tString[] test = {\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"A: 'a' -> channel(SKIP);\\n\" +\n\t\t\t\"B: 'b' -> type(MORE);\\n\" +\n\t\t\t\"C: 'c' -> mode(SKIP);\\n\" +\n\t\t\t\"D: 'd' -> channel(HIDDEN);\\n\" +\n\t\t\t\"E: 'e' -> type(EOF);\\n\" +\n\t\t\t\"F: 'f' -> pushMode(DEFAULT_MODE);\",\n\n\t\t\t\"error(\" + ErrorType.CHANNEL_CONFLICTS_WITH_COMMON_CONSTANTS.code + \"): L.g4:2:18: cannot use or declare channel with reserved name SKIP\\n\" +\n\t\t\t\"error(\" + ErrorType.TOKEN_CONFLICTS_WITH_COMMON_CONSTANTS.code + \"): L.g4:3:15: cannot use or declare token with reserved name MORE\\n\" +\n\t\t\t\"error(\" + ErrorType.MODE_CONFLICTS_WITH_COMMON_CONSTANTS.code + \"): L.g4:4:15: cannot use or declare mode with reserved name SKIP\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t// https://github.com/antlr/antlr4/issues/1411\n\t@Test public void testWrongIdForTypeChannelModeCommand() throws Exception {\n\t\tString[] test = {\n\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\"tokens { TOKEN1 }\\n\" +\n\t\t\t\"channels { CHANNEL1 }\\n\" +\n\t\t\t\"TOKEN: 'asdf' -> type(CHANNEL1), channel(MODE1), mode(TOKEN1);\\n\" +\n\t\t\t\"mode MODE1;\\n\" +\n\t\t\t\"MODE1_TOKEN: 'qwer';\",\n\n\t\t\t\"error(\" + ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_TOKEN_NAME.code + \"): L.g4:4:22: CHANNEL1 is not a recognized token name\\n\" +\n\t\t\t\"error(\" + ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_CHANNEL_NAME.code + \"): L.g4:4:41: MODE1 is not a recognized channel name\\n\" +\n\t\t\t\"error(\" + ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_MODE_NAME.code + \"): L.g4:4:54: TOKEN1 is not a recognized mode name\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t// https://github.com/antlr/antlr4/issues/1388\n\t@Test public void testDuplicatedCommands() throws Exception {\n\t\tString[] test = {\n\t\t\t\"lexer grammar Lexer;\\n\" +\n\t\t\t\"channels { CHANNEL1, CHANNEL2 }\\n\" +\n\t\t\t\"tokens { TEST1, TEST2 }\\n\" +\n\t\t\t\"TOKEN: 'a' -> mode(MODE1), mode(MODE2);\\n\" +\n\t\t\t\"TOKEN1: 'b' -> pushMode(MODE1), mode(MODE2);\\n\" +\n\t\t\t\"TOKEN2: 'c' -> pushMode(MODE1), pushMode(MODE2); // pushMode is not duplicate\\n\" +\n\t\t\t\"TOKEN3: 'd' -> popMode, popMode;                 // popMode is not duplicate\\n\" +\n\t\t\t\"mode MODE1;\\n\" +\n\t\t\t\"MODE1_TOKEN: 'e';\\n\" +\n\t\t\t\"mode MODE2;\\n\" +\n\t\t\t\"MODE2_TOKEN: 'f';\\n\" +\n\t\t\t\"MODE2_TOKEN1: 'g' -> type(TEST1), type(TEST2);\\n\" +\n\t\t\t\"MODE2_TOKEN2: 'h' -> channel(CHANNEL1), channel(CHANNEL2), channel(DEFAULT_TOKEN_CHANNEL);\",\n\n\t\t\t\"warning(\" + ErrorType.DUPLICATED_COMMAND.code + \"): Lexer.g4:4:27: duplicated command mode\\n\" +\n\t\t\t\"warning(\" + ErrorType.DUPLICATED_COMMAND.code + \"): Lexer.g4:12:34: duplicated command type\\n\" +\n\t\t\t\"warning(\" + ErrorType.DUPLICATED_COMMAND.code + \"): Lexer.g4:13:40: duplicated command channel\\n\" +\n\t\t\t\"warning(\" + ErrorType.DUPLICATED_COMMAND.code + \"): Lexer.g4:13:59: duplicated command channel\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t// https://github.com/antlr/antlr4/issues/1388\n\t@Test public void testIncompatibleCommands() throws Exception {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"channels { CHANNEL1 }\\n\" +\n\t\t\t\t\"tokens { TYPE1 }\\n\" +\n\t\t\t\t\"// Incompatible\\n\" +\n\t\t\t\t\"T00: 'a00' -> skip, more;\\n\" +\n\t\t\t\t\"T01: 'a01' -> skip, type(TYPE1);\\n\" +\n\t\t\t\t\"T02: 'a02' -> skip, channel(CHANNEL1);\\n\" +\n\t\t\t\t\"T03: 'a03' -> more, type(TYPE1);\\n\" +\n\t\t\t\t\"T04: 'a04' -> more, channel(CHANNEL1);\\n\" +\n\t\t\t\t\"T05: 'a05' -> more, skip;\\n\" +\n\t\t\t\t\"T06: 'a06' -> type(TYPE1), skip;\\n\" +\n\t\t\t\t\"T07: 'a07' -> type(TYPE1), more;\\n\" +\n\t\t\t\t\"T08: 'a08' -> channel(CHANNEL1), skip;\\n\" +\n\t\t\t\t\"T09: 'a09' -> channel(CHANNEL1), more;\\n\" +\n\t\t\t\t\"// Allowed\\n\" +\n\t\t\t\t\"T10: 'a10' -> type(TYPE1), channel(CHANNEL1);\\n\" +\n\t\t\t\t\"T11: 'a11' -> channel(CHANNEL1), type(TYPE1);\",\n\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:5:20: incompatible commands skip and more\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:6:20: incompatible commands skip and type\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:7:20: incompatible commands skip and channel\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:8:20: incompatible commands more and type\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:9:20: incompatible commands more and channel\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:10:20: incompatible commands more and skip\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:11:27: incompatible commands type and skip\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:12:27: incompatible commands type and more\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:13:33: incompatible commands channel and skip\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.INCOMPATIBLE_COMMANDS.code + \"): L.g4:14:33: incompatible commands channel and more\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t// https://github.com/antlr/antlr4/issues/1409\n\t@Test public void testLabelsForTokensWithMixedTypes() {\n\t\tString[] test = {\n\t\t\t\t\"grammar L;\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"rule1                                      // Correct (Alternatives)\\n\" +\n\t\t\t\t\"    : t1=a  #aLabel\\n\" +\n\t\t\t\t\"    | t1=b  #bLabel\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"rule2                         //Incorrect type casting in generated code (RULE_LABEL)\\n\" +\n\t\t\t\t\"    : t2=a | t2=b\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"rule3\\n\" +\n\t\t\t\t\"    : t3+=a+ b t3+=c+     //Incorrect type casting in generated code (RULE_LIST_LABEL)\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"rule4\\n\" +\n\t\t\t\t\"    : a t4=A b t4=B c                  // Correct (TOKEN_LABEL)\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"rule5\\n\" +\n\t\t\t\t\"    : a t5+=A b t5+=B c                // Correct (TOKEN_LIST_LABEL)\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"rule6                     // Correct (https://github.com/antlr/antlr4/issues/1543)\\n\" +\n\t\t\t\t\"    : t6=a                          #t6_1_Label\\n\" +\n\t\t\t\t\"    | t6=rule6 b (t61=c)? t62=rule6 #t6_2_Label\\n\" +\n\t\t\t\t\"    | t6=A     a (t61=B)? t62=A     #t6_3_Label\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"rule7                     // Incorrect (https://github.com/antlr/antlr4/issues/1543)\\n\" +\n\t\t\t\t\"    : a\\n\" +\n\t\t\t\t\"    | t7=rule7 b (t71=c)? t72=rule7 \\n\" +\n\t\t\t\t\"    | t7=A     a (t71=B)? t72=A     \\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"rule8                     // Correct (https://github.com/antlr/antlr4/issues/1543)\\n\" +\n\t\t\t\t\"    : a\\n\" +\n\t\t\t\t\"    | t8=rule8 a t8=rule8\\n\" +\n\t\t\t\t\"    | t8=rule8 b t8=rule8\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"a: A;\\n\" +\n\t\t\t\t\"b: B;\\n\" +\n\t\t\t\t\"c: C;\\n\" +\n\t\t\t\t\"A: 'a';\\n\" +\n\t\t\t\t\"B: 'b';\\n\" +\n\t\t\t\t\"C: 'c';\\n\",\n\n\t\t\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): L.g4:8:13: label t2=b type mismatch with previous definition: t2=a\\n\" +\n\t\t\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): L.g4:11:15: label t3+=c type mismatch with previous definition: t3+=a\\n\" +\n\n\t\t\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): L.g4:24:0: label t7 type mismatch with previous definition: TOKEN_LABEL!=RULE_LABEL\\n\" +\n\t\t\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): L.g4:24:0: label t71 type mismatch with previous definition: RULE_LABEL!=TOKEN_LABEL\\n\" +\n\t\t\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): L.g4:24:0: label t72 type mismatch with previous definition: RULE_LABEL!=TOKEN_LABEL\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t// https://github.com/antlr/antlr4/issues/1543\n\t@Test public void testLabelsForTokensWithMixedTypesLRWithLabels() {\n\t\tString[] test = {\n\t\t\t\t\"grammar L;\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"expr\\n\" +\n\t\t\t\t\"    : left=A '+' right=A        #primary\\n\" +\n\t\t\t\t\"    | left=expr '-' right=expr  #sub\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"A: 'a';\\n\" +\n\t\t\t\t\"B: 'b';\\n\" +\n\t\t\t\t\"C: 'c';\\n\",\n\n\t\t\t\t\"\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t// https://github.com/antlr/antlr4/issues/1543\n\t@Test\n\tpublic void testLabelsForTokensWithMixedTypesLRWithoutLabels() {\n\t\tString[] test = {\n\t\t\t\t\"grammar L;\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"expr\\n\" +\n\t\t\t\t\"    : left=A '+' right=A\\n\" +\n\t\t\t\t\"    | left=expr '-' right=expr\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"A: 'a';\\n\" +\n\t\t\t\t\"B: 'b';\\n\" +\n\t\t\t\t\"C: 'c';\\n\",\n\n\t\t\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): L.g4:3:0: label left type mismatch with previous definition: TOKEN_LABEL!=RULE_LABEL\\n\" +\n\t\t\t\t\"error(\" + ErrorType.LABEL_TYPE_CONFLICT.code + \"): L.g4:3:0: label right type mismatch with previous definition: RULE_LABEL!=TOKEN_LABEL\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testCharsCollision() throws  Exception {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"TOKEN_RANGE:      [aa-f];\\n\" +\n\t\t\t\t\"TOKEN_RANGE_2:    [A-FD-J];\\n\" +\n\t\t\t\t\"TOKEN_RANGE_3:    'Z' | 'K'..'R' | 'O'..'V';\\n\" +\n\t\t\t\t\"TOKEN_RANGE_4:    'g'..'l' | [g-l];\\n\" +\n\t\t\t\t\"TOKEN_RANGE_WITHOUT_COLLISION: '_' | [a-zA-Z];\\n\" +\n\t\t\t\t\"TOKEN_RANGE_WITH_ESCAPED_CHARS: [\\\\n-\\\\r] | '\\\\n'..'\\\\r';\",\n\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4:2:18: chars a-f used multiple times in set [aa-f]\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4:3:18: chars D-J used multiple times in set [A-FD-J]\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4:4:38: chars O-V used multiple times in set 'Z' | 'K'..'R' | 'O'..'V'\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4::: chars 'g' used multiple times in set 'g'..'l'\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4::: chars '\\\\n' used multiple times in set '\\\\n'..'\\\\r'\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testCaseInsensitiveCharsCollision() {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"TOKEN_RANGE:      [a-fA-F0-9];\\n\" +\n\t\t\t\t\"TOKEN_RANGE_2:    'g'..'l' | 'G'..'L';\\n\" +\n\t\t\t\t\"TOKEN_RANGE_3:    'm'..'q' | [M-Q];\\n\",\n\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4:3:18: chars a-f used multiple times in set [a-fA-F0-9]\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4:4:32: chars g-l used multiple times in set 'g'..'l' | 'G'..'L'\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4::: chars 'M' used multiple times in set 'M'..'Q' | 'm'..'q'\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.CHARACTERS_COLLISION_IN_SET.code + \"): L.g4::: chars 'm' used multiple times in set 'M'..'Q' | 'm'..'q'\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testCaseInsensitiveWithUnicodeRanges() {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive=true; }\\n\" +\n\t\t\t\t\"FullWidthLetter\\n\" +\n\t\t\t\t\"    : '\\\\u00c0'..'\\\\u00d6' // ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ\\n\" +\n\t\t\t\t\"    | '\\\\u00f8'..'\\\\u00ff' // øùúûüýþÿ\\n\" +\n\t\t\t\t\"    ;\",\n\n\t\t\t\t\"\"\n\t\t};\n\n\t\t// Don't transform øùúûüýþÿ to uppercase\n\t\t// ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂăĄąĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸ\n\t\t// because of different length of lower and UPPER range\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testUnreachableTokens() {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar Test;\\n\" +\n\t\t\t\t\"TOKEN1: 'as' 'df' | 'qwer';\\n\" +\n\t\t\t\t\"TOKEN2: [0-9];\\n\" +\n\t\t\t\t\"TOKEN3: 'asdf';\\n\" +\n\t\t\t\t\"TOKEN4: 'q' 'w' 'e' 'r' | A;\\n\" +\n\t\t\t\t\"TOKEN5: 'aaaa';\\n\" +\n\t\t\t\t\"TOKEN6: 'asdf';\\n\" +\n\t\t\t\t\"TOKEN7: 'qwer'+;\\n\" +\n\t\t\t\t\"TOKEN8: 'a' 'b' | 'b' | 'a' 'b';\\n\" +\n\t\t\t\t\"fragment\\n\" +\n\t\t\t\t\"TOKEN9: 'asdf' | 'qwer' | 'qwer';\\n\" +\n\t\t\t\t\"TOKEN10: '\\\\r\\\\n' | '\\\\r\\\\n';\\n\" +\n\t\t\t\t\"TOKEN11: '\\\\r\\\\n';\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"mode MODE1;\\n\" +\n\t\t\t\t\"TOKEN12: 'asdf';\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"fragment A: 'A';\",\n\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:4:0: One of the token TOKEN3 values unreachable. asdf is always overlapped by token TOKEN1\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:5:0: One of the token TOKEN4 values unreachable. qwer is always overlapped by token TOKEN1\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:7:0: One of the token TOKEN6 values unreachable. asdf is always overlapped by token TOKEN1\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:7:0: One of the token TOKEN6 values unreachable. asdf is always overlapped by token TOKEN3\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:9:0: One of the token TOKEN8 values unreachable. ab is always overlapped by token TOKEN8\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:11:0: One of the token TOKEN9 values unreachable. qwer is always overlapped by token TOKEN9\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:12:0: One of the token TOKEN10 values unreachable. \\\\r\\\\n is always overlapped by token TOKEN10\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:13:0: One of the token TOKEN11 values unreachable. \\\\r\\\\n is always overlapped by token TOKEN10\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.TOKEN_UNREACHABLE.code + \"): Test.g4:13:0: One of the token TOKEN11 values unreachable. \\\\r\\\\n is always overlapped by token TOKEN10\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testIllegalCaseInsensitiveOptionValue() {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = badValue; }\\n\" +\n\t\t\t\t\"TOKEN_1 options { caseInsensitive = badValue; } : [A-F]+;\\n\",\n\n\t\t\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION_VALUE.code + \"): L.g4:2:28: unsupported option value caseInsensitive=badValue\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION_VALUE.code + \"): L.g4:3:36: unsupported option value caseInsensitive=badValue\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testRedundantCaseInsensitiveLexerRuleOption() {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = true; }\\n\" +\n\t\t\t\t\"TOKEN options { caseInsensitive = true; } : [A-F]+;\\n\",\n\n\t\t\t\t\"warning(\" + ErrorType.REDUNDANT_CASE_INSENSITIVE_LEXER_RULE_OPTION.code + \"): L.g4:3:16: caseInsensitive lexer rule option is redundant because its value equals to global value (true)\\n\"\n\t\t};\n\t\ttestErrors(test, false);\n\n\t\tString[] test2 = {\n\t\t\t\t\"lexer grammar L;\\n\" +\n\t\t\t\t\"options { caseInsensitive = false; }\\n\" +\n\t\t\t\t\"TOKEN options { caseInsensitive = false; } : [A-F]+;\\n\",\n\n\t\t\t\t\"warning(\" + ErrorType.REDUNDANT_CASE_INSENSITIVE_LEXER_RULE_OPTION.code + \"): L.g4:3:16: caseInsensitive lexer rule option is redundant because its value equals to global value (false)\\n\"\n\t\t};\n\t\ttestErrors(test2, false);\n\t}\n\n\t@Test public void testCaseInsensitiveOptionInParseRule() {\n\t\tString[] test = {\n\t\t\t\t\"grammar G;\\n\" +\n\t\t\t\t\"root options { caseInsensitive=true; } : 'token';\",\n\n\t\t\t\t\"warning(\" + ErrorType.ILLEGAL_OPTION.code + \"): G.g4:2:15: unsupported option caseInsensitive\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testNotImpliedCharacters() {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar Test;\\n\" +\n\t\t\t\t\"TOKEN1: 'A'..'g';\\n\" +\n\t\t\t\t\"TOKEN2: [C-m];\\n\" +\n\t\t\t\t\"TOKEN3: [А-я]; // OK since range does not contain intermediate characters\\n\" +\n\t\t\t\t\"TOKEN4: '\\\\u0100'..'\\\\u1fff'; // OK since range borders are unicode characters\",\n\n\t\t\t\t\"warning(\" + ErrorType.RANGE_PROBABLY_CONTAINS_NOT_IMPLIED_CHARACTERS.code + \"): Test.g4:2:8: Range A..g probably contains not implied characters [\\\\]^_`. Both bounds should be defined in lower or UPPER case\\n\" +\n\t\t\t\t\"warning(\" + ErrorType.RANGE_PROBABLY_CONTAINS_NOT_IMPLIED_CHARACTERS.code + \"): Test.g4:3:8: Range C..m probably contains not implied characters [\\\\]^_`. Both bounds should be defined in lower or UPPER case\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t@Test public void testNotImpliedCharactersWithCaseInsensitiveOption() {\n\t\tString[] test = {\n\t\t\t\t\"lexer grammar Test;\\n\" +\n\t\t\t\t\"options { caseInsensitive=true; }\\n\" +\n\t\t\t\t\"TOKEN: [A-z];\",\n\n\t\t\t\t\"warning(\" + ErrorType.RANGE_PROBABLY_CONTAINS_NOT_IMPLIED_CHARACTERS.code + \"): Test.g4:3:7: Range A..z probably contains not implied characters [\\\\]^_`. Both bounds should be defined in lower or UPPER case\\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n\n\t// ISSUE: https://github.com/antlr/antlr4/issues/2788\n\t@Test public void testUndefinedLabel() {\n\t\tString[] test = {\n\t\t\t\t\"grammar Test;\" +\n\t\t\t\t\"root\\n\" +\n\t\t\t\t\"    : root a\\n\" +\n\t\t\t\t\"    | b [error]\\n\" +\n\t\t\t\t\"    ;\\n\" +\n\t\t\t\t\"\\n\" +\n\t\t\t\t\"a: 'a';\\n\" +\n\t\t\t\t\"b: 'b';\",\n\n\t\t\t\t\"error(\" + ErrorType.INTERNAL_ERROR.code + \"): Test.g4:2:30: internal error: Rule error undefined \\n\"\n\t\t};\n\n\t\ttestErrors(test, false);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestTokenPositionOptions.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.parse.ANTLRParser;\nimport org.antlr.v4.runtime.misc.IntervalSet;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestTokenPositionOptions {\n\t@Test public void testLeftRecursionRewrite() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar T;\\n\" +\n\t\t\t\t\"s : e ';' ;\\n\" +\n\t\t\t\t\"e : e '*' e\\n\" +\n\t\t\t\t\"  | e '+' e\\n\" +\n\t\t\t\t\"  | e '.' ID\\n\" +\n\t\t\t\t\"  | '-' e\\n\" +\n\t\t\t\t\"  | ID\\n\" +\n\t\t\t\t\"  ;\\n\" +\n\t\t\t\t\"ID : [a-z]+ ;\\n\"\n\t\t);\n\n\t\tString expectedTree =\n\t\t\t\t\"(COMBINED_GRAMMAR T (RULES (RULE s (BLOCK (ALT e ';'))) (RULE e (BLOCK (ALT (BLOCK (ALT {} ('-' (ELEMENT_OPTIONS (= tokenIndex 43))) (e (ELEMENT_OPTIONS (= tokenIndex 45) (= p 2)))) (ALT (ID (ELEMENT_OPTIONS (= tokenIndex 49))))) (* (BLOCK (ALT ({precpred(_ctx, 5)}? (ELEMENT_OPTIONS (= p 5))) ('*' (ELEMENT_OPTIONS (= tokenIndex 21))) (e (ELEMENT_OPTIONS (= tokenIndex 23) (= p 6)))) (ALT ({precpred(_ctx, 4)}? (ELEMENT_OPTIONS (= p 4))) ('+' (ELEMENT_OPTIONS (= tokenIndex 29))) (e (ELEMENT_OPTIONS (= tokenIndex 31) (= p 5)))) (ALT ({precpred(_ctx, 3)}? (ELEMENT_OPTIONS (= p 3))) ('.' (ELEMENT_OPTIONS (= tokenIndex 37))) (ID (ELEMENT_OPTIONS (= tokenIndex 39)))))))))))\";\n\t\tassertEquals(expectedTree, g.ast.toStringTree());\n\n\t\tString expectedElementTokens =\n\t\t\t\t\"[@5,11:11='s',<54>,2:0]\\n\" +\n\t\t\t\t\"[@9,15:15='e',<54>,2:4]\\n\" +\n\t\t\t\t\"[@11,17:19='';'',<59>,2:6]\\n\" +\n\t\t\t\t\"[@15,23:23='e',<54>,3:0]\\n\" +\n\t\t\t\t\"[@43,64:66=''-'',<59>,6:4]\\n\" +\n\t\t\t\t\"[@45,68:68='e',<54>,6:8]\\n\" +\n\t\t\t\t\"[@49,74:75='ID',<62>,7:4]\\n\" +\n\t\t\t\t\"[@21,29:31=''*'',<59>,3:6]\\n\" +\n\t\t\t\t\"[@23,33:33='e',<54>,3:10]\\n\" +\n\t\t\t\t\"[@29,41:43=''+'',<59>,4:6]\\n\" +\n\t\t\t\t\"[@31,45:45='e',<54>,4:10]\\n\" +\n\t\t\t\t\"[@37,53:55=''.'',<59>,5:6]\\n\" +\n\t\t\t\t\"[@39,57:58='ID',<62>,5:10]\";\n\n\t\tIntervalSet types =\n\t\t\t\tnew IntervalSet(ANTLRParser.TOKEN_REF,\n\t\t\t\tANTLRParser.STRING_LITERAL,\n\t\t\t\tANTLRParser.RULE_REF);\n\t\tList<GrammarAST> nodes = g.ast.getNodesWithTypePreorderDFS(types);\n\t\tList<Token> tokens = new ArrayList<Token>();\n\t\tfor (GrammarAST node : nodes) {\n\t\t\ttokens.add(node.getToken());\n\t\t}\n\t\tassertEquals(expectedElementTokens, Utils.join(tokens.toArray(), \"\\n\"));\n\t}\n\n\t@Test public void testLeftRecursionWithLabels() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar T;\\n\" +\n\t\t\t\t\"s : e ';' ;\\n\" +\n\t\t\t\t\"e : e '*' x=e\\n\" +\n\t\t\t\t\"  | e '+' e\\n\" +\n\t\t\t\t\"  | e '.' y=ID\\n\" +\n\t\t\t\t\"  | '-' e\\n\" +\n\t\t\t\t\"  | ID\\n\" +\n\t\t\t\t\"  ;\\n\" +\n\t\t\t\t\"ID : [a-z]+ ;\\n\"\n\t\t);\n\n\t\tString expectedTree =\n\t\t\t\t\"(COMBINED_GRAMMAR T (RULES (RULE s (BLOCK (ALT e ';'))) (RULE e (BLOCK (ALT (BLOCK (ALT {} ('-' (ELEMENT_OPTIONS (= tokenIndex 47))) (e (ELEMENT_OPTIONS (= tokenIndex 49) (= p 2)))) (ALT (ID (ELEMENT_OPTIONS (= tokenIndex 53))))) (* (BLOCK (ALT ({precpred(_ctx, 5)}? (ELEMENT_OPTIONS (= p 5))) ('*' (ELEMENT_OPTIONS (= tokenIndex 21))) (= x (e (ELEMENT_OPTIONS (= tokenIndex 25) (= p 6))))) (ALT ({precpred(_ctx, 4)}? (ELEMENT_OPTIONS (= p 4))) ('+' (ELEMENT_OPTIONS (= tokenIndex 31))) (e (ELEMENT_OPTIONS (= tokenIndex 33) (= p 5)))) (ALT ({precpred(_ctx, 3)}? (ELEMENT_OPTIONS (= p 3))) ('.' (ELEMENT_OPTIONS (= tokenIndex 39))) (= y (ID (ELEMENT_OPTIONS (= tokenIndex 43))))))))))))\";\n\t\tassertEquals(expectedTree, g.ast.toStringTree());\n\n\t\tString expectedElementTokens =\n\t\t\t\t\"[@5,11:11='s',<54>,2:0]\\n\" +\n\t\t\t\t\"[@9,15:15='e',<54>,2:4]\\n\" +\n\t\t\t\t\"[@11,17:19='';'',<59>,2:6]\\n\" +\n\t\t\t\t\"[@15,23:23='e',<54>,3:0]\\n\" +\n\t\t\t\t\"[@47,68:70=''-'',<59>,6:4]\\n\" +\n\t\t\t\t\"[@49,72:72='e',<54>,6:8]\\n\" +\n\t\t\t\t\"[@53,78:79='ID',<62>,7:4]\\n\" +\n\t\t\t\t\"[@21,29:31=''*'',<59>,3:6]\\n\" +\n\t\t\t\t\"[@25,35:35='e',<54>,3:12]\\n\" +\n\t\t\t\t\"[@31,43:45=''+'',<59>,4:6]\\n\" +\n\t\t\t\t\"[@33,47:47='e',<54>,4:10]\\n\" +\n\t\t\t\t\"[@39,55:57=''.'',<59>,5:6]\\n\" +\n\t\t\t\t\"[@43,61:62='ID',<62>,5:12]\";\n\n\t\tIntervalSet types =\n\t\t\t\tnew IntervalSet(ANTLRParser.TOKEN_REF,\n\t\t\t\tANTLRParser.STRING_LITERAL,\n\t\t\t\tANTLRParser.RULE_REF);\n\t\tList<GrammarAST> nodes = g.ast.getNodesWithTypePreorderDFS(types);\n\t\tList<Token> tokens = new ArrayList<Token>();\n\t\tfor (GrammarAST node : nodes) {\n\t\t\ttokens.add(node.getToken());\n\t\t}\n\t\tassertEquals(expectedElementTokens, Utils.join(tokens.toArray(), \"\\n\"));\n\t}\n\n\t@Test public void testLeftRecursionWithSet() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar T;\\n\" +\n\t\t\t\t\"s : e ';' ;\\n\" +\n\t\t\t\t\"e : e op=('*'|'/') e\\n\" +\n\t\t\t\t\"  | e '+' e\\n\" +\n\t\t\t\t\"  | e '.' ID\\n\" +\n\t\t\t\t\"  | '-' e\\n\" +\n\t\t\t\t\"  | ID\\n\" +\n\t\t\t\t\"  ;\\n\" +\n\t\t\t\t\"ID : [a-z]+ ;\\n\"\n\t\t);\n\n\t\tString expectedTree =\n\t\t\t\t\"(COMBINED_GRAMMAR T (RULES (RULE s (BLOCK (ALT e ';'))) (RULE e (BLOCK (ALT (BLOCK (ALT {} ('-' (ELEMENT_OPTIONS (= tokenIndex 49))) (e (ELEMENT_OPTIONS (= tokenIndex 51) (= p 2)))) (ALT (ID (ELEMENT_OPTIONS (= tokenIndex 55))))) (* (BLOCK (ALT ({precpred(_ctx, 5)}? (ELEMENT_OPTIONS (= p 5))) (= op (SET ('*' (ELEMENT_OPTIONS (= tokenIndex 24))) ('/' (ELEMENT_OPTIONS (= tokenIndex 26))))) (e (ELEMENT_OPTIONS (= tokenIndex 29) (= p 6)))) (ALT ({precpred(_ctx, 4)}? (ELEMENT_OPTIONS (= p 4))) ('+' (ELEMENT_OPTIONS (= tokenIndex 35))) (e (ELEMENT_OPTIONS (= tokenIndex 37) (= p 5)))) (ALT ({precpred(_ctx, 3)}? (ELEMENT_OPTIONS (= p 3))) ('.' (ELEMENT_OPTIONS (= tokenIndex 43))) (ID (ELEMENT_OPTIONS (= tokenIndex 45)))))))))))\";\n\t\tassertEquals(expectedTree, g.ast.toStringTree());\n\n\t\tString expectedElementTokens =\n\t\t\t\t\"[@5,11:11='s',<54>,2:0]\\n\" +\n\t\t\t\t\"[@9,15:15='e',<54>,2:4]\\n\" +\n\t\t\t\t\"[@11,17:19='';'',<59>,2:6]\\n\" +\n\t\t\t\t\"[@15,23:23='e',<54>,3:0]\\n\" +\n\t\t\t\t\"[@49,73:75=''-'',<59>,6:4]\\n\" +\n\t\t\t\t\"[@51,77:77='e',<54>,6:8]\\n\" +\n\t\t\t\t\"[@55,83:84='ID',<62>,7:4]\\n\" +\n\t\t\t\t\"[@24,33:35=''*'',<59>,3:10]\\n\" +\n\t\t\t\t\"[@26,37:39=''/'',<59>,3:14]\\n\" +\n\t\t\t\t\"[@29,42:42='e',<54>,3:19]\\n\" +\n\t\t\t\t\"[@35,50:52=''+'',<59>,4:6]\\n\" +\n\t\t\t\t\"[@37,54:54='e',<54>,4:10]\\n\" +\n\t\t\t\t\"[@43,62:64=''.'',<59>,5:6]\\n\" +\n\t\t\t\t\"[@45,66:67='ID',<62>,5:10]\";\n\n\t\tIntervalSet types =\n\t\t\t\tnew IntervalSet(ANTLRParser.TOKEN_REF,\n\t\t\t\tANTLRParser.STRING_LITERAL,\n\t\t\t\tANTLRParser.RULE_REF);\n\t\tList<GrammarAST> nodes = g.ast.getNodesWithTypePreorderDFS(types);\n\t\tList<Token> tokens = new ArrayList<Token>();\n\t\tfor (GrammarAST node : nodes) {\n\t\t\ttokens.add(node.getToken());\n\t\t}\n\t\tassertEquals(expectedElementTokens, Utils.join(tokens.toArray(), \"\\n\"));\n\t}\n\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestTokenTypeAssignment.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport java.util.StringTokenizer;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class TestTokenTypeAssignment {\n\t@Test public void testParserSimpleTokens() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar t;\\n\"+\n\t\t\t\t\"a : A | B;\\n\" +\n\t\t\t\t\"b : C ;\");\n\t\tString rules = \"a, b\";\n\t\tString tokenNames = \"A, B, C\";\n\t\tcheckSymbols(g, rules, tokenNames);\n\t}\n\n\t@Test public void testParserTokensSection() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"parser grammar t;\\n\" +\n\t\t\t\t\"tokens {\\n\" +\n\t\t\t\t\"  C,\\n\" +\n\t\t\t\t\"  D\" +\n\t\t\t\t\"}\\n\"+\n\t\t\t\t\"a : A | B;\\n\" +\n\t\t\t\t\"b : C ;\");\n\t\tString rules = \"a, b\";\n\t\tString tokenNames = \"A, B, C, D\";\n\t\tcheckSymbols(g, rules, tokenNames);\n\t}\n\n\t@Test public void testLexerTokensSection() throws Exception {\n\t\tLexerGrammar g = new LexerGrammar(\n\t\t\t\t\"lexer grammar t;\\n\" +\n\t\t\t\t\"tokens {\\n\" +\n\t\t\t\t\"  C,\\n\" +\n\t\t\t\t\"  D\" +\n\t\t\t\t\"}\\n\"+\n\t\t\t\t\"A : 'a';\\n\" +\n\t\t\t\t\"C : 'c' ;\");\n\t\tString rules = \"A, C\";\n\t\tString tokenNames = \"A, C, D\";\n\t\tcheckSymbols(g, rules, tokenNames);\n\t}\n\n\t@Test public void testCombinedGrammarLiterals() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\"+\n\t\t\t\t\"a : 'begin' b 'end';\\n\" +\n\t\t\t\t\"b : C ';' ;\\n\" +\n\t\t\t\t\"ID : 'a' ;\\n\" +\n\t\t\t\t\"FOO : 'foo' ;\\n\" +  // \"foo\" is not a token name\n\t\t\t\t\"C : 'c' ;\\n\");        // nor is 'c'\n\t\tString rules = \"a, b\";\n\t\tString tokenNames = \"C, FOO, ID, 'begin', 'end', ';'\";\n\t\tcheckSymbols(g, rules, tokenNames);\n\t}\n\n\t@Test public void testLiteralInParserAndLexer() throws Exception {\n\t\t// 'x' is token and char in lexer rule\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\" +\n\t\t\t\t\"a : 'x' E ; \\n\" +\n\t\t\t\t\"E: 'x' '0' ;\\n\");\n\n\t\tString literals = \"['x']\";\n\t\tString foundLiterals = g.stringLiteralToTypeMap.keySet().toString();\n\t\tassertEquals(literals, foundLiterals);\n\n\t\tfoundLiterals = g.implicitLexer.stringLiteralToTypeMap.keySet().toString();\n\t\tassertEquals(\"['x']\", foundLiterals); // pushed in lexer from parser\n\n\t\tString[] typeToTokenName = g.getTokenDisplayNames();\n\t\tSet<String> tokens = new LinkedHashSet<String>();\n\t\tfor (String t : typeToTokenName) if ( t!=null ) tokens.add(t);\n\t\tassertEquals(\"[<INVALID>, 'x', E]\", tokens.toString());\n\t}\n\n\t@Test public void testPredDoesNotHideNameToLiteralMapInLexer() throws Exception {\n\t\t// 'x' is token and char in lexer rule\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\" +\n\t\t\t\t\"a : 'x' X ; \\n\" +\n\t\t\t\t\"X: 'x' {true}?;\\n\"); // must match as alias even with pred\n\n\t\tassertEquals(\"{'x'=1}\", g.stringLiteralToTypeMap.toString());\n\t\tassertEquals(\"{EOF=-1, X=1}\", g.tokenNameToTypeMap.toString());\n\n\t\t// pushed in lexer from parser\n\t\tassertEquals(\"{'x'=1}\", g.implicitLexer.stringLiteralToTypeMap.toString());\n\t\tassertEquals(\"{EOF=-1, X=1}\", g.implicitLexer.tokenNameToTypeMap.toString());\n\t}\n\n\t@Test public void testCombinedGrammarWithRefToLiteralButNoTokenIDRef() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\"+\n\t\t\t\t\"a : 'a' ;\\n\" +\n\t\t\t\t\"A : 'a' ;\\n\");\n\t\tString rules = \"a\";\n\t\tString tokenNames = \"A, 'a'\";\n\t\tcheckSymbols(g, rules, tokenNames);\n\t}\n\n\t@Test public void testSetDoesNotMissTokenAliases() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\"+\n\t\t\t\t\"a : 'a'|'b' ;\\n\" +\n\t\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\t\"B : 'b' ;\\n\");\n\t\tString rules = \"a\";\n\t\tString tokenNames = \"A, 'a', B, 'b'\";\n\t\tcheckSymbols(g, rules, tokenNames);\n\t}\n\n\t// T E S T  L I T E R A L  E S C A P E S\n\n\t@Test public void testParserCharLiteralWithEscape() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\"+\n\t\t\t\t\"a : '\\\\n';\\n\");\n\t\tSet<?> literals = g.stringLiteralToTypeMap.keySet();\n\t\t// must store literals how they appear in the antlr grammar\n\t\tassertEquals(\"'\\\\n'\", literals.toArray()[0]);\n\t}\n\n\t@Test public void testParserCharLiteralWithBasicUnicodeEscape() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\"+\n\t\t\t\t\"a : '\\\\uABCD';\\n\");\n\t\tSet<?> literals = g.stringLiteralToTypeMap.keySet();\n\t\t// must store literals how they appear in the antlr grammar\n\t\tassertEquals(\"'\\\\uABCD'\", literals.toArray()[0]);\n\t}\n\n\t@Test public void testParserCharLiteralWithExtendedUnicodeEscape() throws Exception {\n\t\tGrammar g = new Grammar(\n\t\t\t\t\"grammar t;\\n\"+\n\t\t\t\t\"a : '\\\\u{1ABCD}';\\n\");\n\t\tSet<?> literals = g.stringLiteralToTypeMap.keySet();\n\t\t// must store literals how they appear in the antlr grammar\n\t\tassertEquals(\"'\\\\u{1ABCD}'\", literals.toArray()[0]);\n\t}\n\n\tprotected void checkSymbols(Grammar g,\n\t\t\t\t\t\t\t\tString rulesStr,\n\t\t\t\t\t\t\t\tString allValidTokensStr)\n\t\tthrows Exception\n\t{\n\t\tString[] typeToTokenName = g.getTokenNames();\n\t\tSet<String> tokens = new HashSet<String>();\n\t\tfor (int i = 0; i < typeToTokenName.length; i++) {\n\t\t\tString t = typeToTokenName[i];\n\t\t\tif ( t!=null ) {\n\t\t\t\tif (t.startsWith(Grammar.AUTO_GENERATED_TOKEN_NAME_PREFIX)) {\n\t\t\t\t\ttokens.add(g.getTokenDisplayName(i));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttokens.add(t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// make sure expected tokens are there\n\t\tStringTokenizer st = new StringTokenizer(allValidTokensStr, \", \");\n\t\twhile ( st.hasMoreTokens() ) {\n\t\t\tString tokenName = st.nextToken();\n\t\t\tassertTrue(g.getTokenType(tokenName) != Token.INVALID_TYPE, \"token \"+tokenName+\" expected, but was undefined\");\n\t\t\ttokens.remove(tokenName);\n\t\t}\n\t\t// make sure there are not any others (other than <EOF> etc...)\n\t\tfor (String tokenName : tokens) {\n\t\t\tassertTrue(g.getTokenType(tokenName) < Token.MIN_USER_TOKEN_TYPE, \"unexpected token name \"+tokenName);\n\t\t}\n\n\t\t// make sure all expected rules are there\n\t\tst = new StringTokenizer(rulesStr, \", \");\n\t\tint n = 0;\n\t\twhile ( st.hasMoreTokens() ) {\n\t\t\tString ruleName = st.nextToken();\n\t\t\tassertNotNull(g.getRule(ruleName), \"rule \"+ruleName+\" expected\");\n\t\t\tn++;\n\t\t}\n\t\t//System.out.println(\"rules=\"+rules);\n\t\t// make sure there are no extra rules\n\t\tassertEquals(n, g.rules.size(), \"number of rules mismatch; expecting \"+n+\"; found \"+g.rules.size());\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestToolSyntaxErrors.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.tool.ErrorType;\nimport org.junit.jupiter.api.Test;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.testErrors;\nimport static org.junit.jupiter.api.Assertions.assertNotEquals;\n\npublic class TestToolSyntaxErrors {\n\tfinal static String[] A = {\n\t    // INPUT\n\t\t\"grammar A;\\n\" +\n\t\t\"\",\n\t\t// YIELDS\n\t\t\"error(\" + ErrorType.NO_RULES.code + \"): A.g4::: grammar A has no rules\\n\",\n\n\t\t\"lexer grammar A;\\n\" +\n\t\t\"\",\n\t\t\"error(\" + ErrorType.NO_RULES.code + \"): A.g4::: grammar A has no rules\\n\",\n\n\t\t\"A;\",\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:1:0: syntax error: 'A' came as a complete surprise to me\\n\",\n\n\t\t\"grammar ;\",\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:1:8: syntax error: ';' came as a complete surprise to me while looking for an identifier\\n\",\n\n\t\t\"grammar A\\n\" +\n\t\t\"a : ID ;\\n\",\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:0: syntax error: missing SEMI at 'a'\\n\",\n\n\t\t\"grammar A;\\n\" +\n\t\t\"a : ID ;;\\n\"+\n\t\t\"b : B ;\",\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:8: syntax error: ';' came as a complete surprise to me\\n\",\n\n\t\t\"grammar A;;\\n\" +\n\t\t\"a : ID ;\\n\",\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A;.g4:1:10: syntax error: ';' came as a complete surprise to me\\n\",\n\n\t\t\"grammar A;\\n\" +\n\t\t\"a @init : ID ;\\n\",\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:8: syntax error: mismatched input ':' expecting ACTION while matching rule preamble\\n\",\n\n\t\t\"grammar A;\\n\" +\n\t\t\"a  ( A | B ) D ;\\n\" +\n\t\t\"b : B ;\",\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:3: syntax error: '(' came as a complete surprise to me while matching rule preamble\\n\" +\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:11: syntax error: mismatched input ')' expecting SEMI while matching a rule\\n\" +\n\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:15: syntax error: mismatched input ';' expecting COLON while matching a lexer rule\\n\",\n    };\n\n\t@Test\n\tpublic void AllErrorCodesDistinct() {\n\t\tErrorType[] errorTypes = ErrorType.class.getEnumConstants();\n\t\tfor (int i = 0; i < errorTypes.length; i++) {\n\t\t\tfor (int j = i + 1; j < errorTypes.length; j++) {\n\t\t\t\tassertNotEquals(errorTypes[i].code, errorTypes[j].code);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Test public void testA() { testErrors(A, true); }\n\n\t@Test public void testExtraColon() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : : A ;\\n\" +\n\t\t\t\"b : B ;\",\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:4: syntax error: ':' came as a complete surprise to me while matching alternative\\n\",\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testMissingRuleSemi() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : A \\n\" +\n\t\t\t\"b : B ;\",\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:3:0: syntax error: unterminated rule (missing ';') detected at 'b :' while looking for rule element\\n\",\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testMissingRuleSemi2() {\n\t\tString[] pair = new String[] {\n\t\t\t\"lexer grammar A;\\n\" +\n\t\t\t\"A : 'a' \\n\" +\n\t\t\t\"B : 'b' ;\",\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:3:2: syntax error: unterminated rule (missing ';') detected at ': 'b'' while looking for lexer rule element\\n\",\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testMissingRuleSemi3() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : A \\n\" +\n\t\t\t\"b[int i] returns [int y] : B ;\",\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:3:9: syntax error: unterminated rule (missing ';') detected at 'returns int y' while looking for rule element\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testMissingRuleSemi4() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : b \\n\" +\n\t\t\t\"  catch [Exception e] {...}\\n\" +\n\t\t\t\"b : B ;\\n\",\n\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:4: syntax error: unterminated rule (missing ';') detected at 'b catch' while looking for rule element\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testMissingRuleSemi5() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : A \\n\" +\n\t\t\t\"  catch [Exception e] {...}\\n\",\n\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:4: syntax error: unterminated rule (missing ';') detected at 'A catch' while looking for rule element\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testBadRulePrequelStart() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a @ options {k=1;} : A ;\\n\" +\n\t\t\t\"b : B ;\",\n\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:4: syntax error: 'options {' came as a complete surprise to me while looking for an identifier\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testBadRulePrequelStart2() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a } : A ;\\n\" +\n\t\t\t\"b : B ;\",\n\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:2: syntax error: '}' came as a complete surprise to me while matching rule preamble\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testModeInParser() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : A ;\\n\" +\n\t\t\t\"mode foo;\\n\" +\n\t\t\t\"b : B ;\",\n\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:4:0: syntax error: 'b' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:4:6: syntax error: mismatched input ';' expecting COLON while matching a lexer rule\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#243\n\t * \"Generate a good message for unterminated strings\"\n\t * https://github.com/antlr/antlr4/issues/243\n\t */\n\t@Test public void testUnterminatedStringLiteral() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : 'x\\n\" +\n\t\t\t\"  ;\\n\",\n\n\t\t\t\"error(\" + ErrorType.UNTERMINATED_STRING_LITERAL.code + \"): A.g4:2:4: unterminated string literal\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#262\n\t * \"Parser Rule Name Starting With an Underscore\"\n\t * https://github.com/antlr/antlr4/issues/262\n\t */\n\t@Test public void testParserRuleNameStartingWithUnderscore() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"_a : 'x' ;\\n\",\n\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:0: syntax error: '_' came as a complete surprise to me\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#194\n\t * \"NullPointerException on 'options{}' in grammar file\"\n\t * https://github.com/antlr/antlr4/issues/194\n\t */\n\t@Test public void testEmptyGrammarOptions() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"options {}\\n\" +\n\t\t\t\"a : 'x' ;\\n\",\n\n\t\t\t\"\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a \"related\" regression test for antlr/antlr4#194\n\t * \"NullPointerException on 'options{}' in grammar file\"\n\t * https://github.com/antlr/antlr4/issues/194\n\t */\n\t@Test public void testEmptyRuleOptions() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a options{} : 'x' ;\\n\",\n\n\t\t\t\"\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a \"related\" regression test for antlr/antlr4#194\n\t * \"NullPointerException on 'options{}' in grammar file\"\n\t * https://github.com/antlr/antlr4/issues/194\n\t */\n\t@Test public void testEmptyBlockOptions() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"a : (options{} : 'x') ;\\n\",\n\n\t\t\t\"\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testEmptyTokensBlock() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"tokens {}\\n\" +\n\t\t\t\"a : 'x' ;\\n\",\n\n\t\t\t\"\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#190\n\t * \"NullPointerException building lexer grammar using bogus 'token' action\"\n\t * https://github.com/antlr/antlr4/issues/190\n\t */\n\t@Test public void testInvalidLexerCommand() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"tokens{Foo}\\n\" +\n\t\t\t\"b : Foo ;\\n\" +\n\t\t\t\"X : 'foo1' -> popmode;\\n\" + // \"meant\" to use -> popMode\n\t\t\t\"Y : 'foo2' -> token(Foo);\", // \"meant\" to use -> type(Foo)\n\n\t\t\t\"error(\" + ErrorType.INVALID_LEXER_COMMAND.code + \"): A.g4:4:14: lexer command popmode does not exist or is not supported by the current target\\n\" +\n\t\t\t\"error(\" + ErrorType.INVALID_LEXER_COMMAND.code + \"): A.g4:5:14: lexer command token does not exist or is not supported by the current target\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testLexerCommandArgumentValidation() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"tokens{Foo}\\n\" +\n\t\t\t\"b : Foo ;\\n\" +\n\t\t\t\"X : 'foo1' -> popMode(Foo);\\n\" + // \"meant\" to use -> popMode\n\t\t\t\"Y : 'foo2' -> type;\", // \"meant\" to use -> type(Foo)\n\n\t\t\t\"error(\" + ErrorType.UNWANTED_LEXER_COMMAND_ARGUMENT.code + \"): A.g4:4:14: lexer command popMode does not take any arguments\\n\" +\n\t\t\t\"error(\" + ErrorType.MISSING_LEXER_COMMAND_ARGUMENT.code + \"): A.g4:5:14: missing argument for lexer command type\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testRuleRedefinition() {\n\t\tString[] pair = new String[] {\n\t\t\t\"grammar Oops;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"ret_ty : A ;\\n\" +\n\t\t\t\"ret_ty : B ;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"A : 'a' ;\\n\" +\n\t\t\t\"B : 'b' ;\\n\",\n\n\t\t\t\"error(\" + ErrorType.RULE_REDEFINITION.code + \"): Oops.g4:4:0: rule ret_ty redefinition; previous at line 3\\n\"\n\t\t};\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testEpsilonClosureAnalysis() {\n\t\tString grammar =\n\t\t\t\"grammar A;\\n\"\n\t\t\t+ \"x : ;\\n\"\n\t\t\t+ \"y1 : x+;\\n\"\n\t\t\t+ \"y2 : x*;\\n\"\n\t\t\t+ \"z1 : ('foo' | 'bar'? 'bar2'?)*;\\n\"\n\t\t\t+ \"z2 : ('foo' | 'bar' 'bar2'? | 'bar2')*;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.EPSILON_CLOSURE.code + \"): A.g4:3:0: rule y1 contains a closure with at least one alternative that can match an empty string\\n\" +\n\t\t\t\"error(\" + ErrorType.EPSILON_CLOSURE.code + \"): A.g4:4:0: rule y2 contains a closure with at least one alternative that can match an empty string\\n\" +\n\t\t\t\"error(\" + ErrorType.EPSILON_CLOSURE.code + \"): A.g4:5:0: rule z1 contains a closure with at least one alternative that can match an empty string\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t// Test for https://github.com/antlr/antlr4/issues/1203\n\t@Test public void testEpsilonNestedClosureAnalysis() {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\"+\n\t\t\t\"s : (a a)* ;\\n\"+\n\t\t\t\"a : 'foo'* ;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.EPSILON_CLOSURE.code + \"): T.g4:2:0: rule s contains a closure with at least one alternative that can match an empty string\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t// Test for https://github.com/antlr/antlr4/issues/2860, https://github.com/antlr/antlr4/issues/1105\n\t@Test public void testEpsilonClosureInLexer() {\n\t\tString grammar =\n\t\t\t\t\"lexer grammar T;\\n\" +\n\t\t\t\t\"TOKEN: '\\\\'' FRAGMENT '\\\\'';\\n\" +\n\t\t\t\t\"fragment FRAGMENT: ('x'|)+;\";\n\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.EPSILON_CLOSURE.code + \"): T.g4:3:9: rule FRAGMENT contains a closure with at least one alternative that can match an empty string\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\t\tgrammar,\n\t\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t// Test for https://github.com/antlr/antlr4/issues/3359\n\t@Test public void testEofClosure() {\n\t\tString grammar =\n\t\t\t\t\"lexer grammar EofClosure;\\n\" +\n\t\t\t\t\"EofClosure: 'x' EOF*;\\n\" +\n\t\t\t\t\"EofInAlternative: 'y' ('z' | EOF);\";\n\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.EOF_CLOSURE.code + \"): EofClosure.g4:2:0: rule EofClosure contains a closure with at least one alternative that can match EOF\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\t\tgrammar,\n\t\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t// Test for https://github.com/antlr/antlr4/issues/1203\n\t@Test public void testEpsilonOptionalAndClosureAnalysis() {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\"+\n\t\t\t\"s : (a a)? ;\\n\"+\n\t\t\t\"a : 'foo'* ;\\n\";\n\t\tString expected =\n\t\t\t\"warning(\" + ErrorType.EPSILON_OPTIONAL.code + \"): T.g4:2:0: rule s contains an optional block with at least one alternative that can match an empty string\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testEpsilonOptionalAnalysis() {\n\t\tString grammar =\n\t\t\t\"grammar A;\\n\"\n\t\t\t+ \"x : ;\\n\"\n\t\t\t+ \"y  : x?;\\n\"\n\t\t\t+ \"z1 : ('foo' | 'bar'? 'bar2'?)?;\\n\"\n\t\t\t+ \"z2 : ('foo' | 'bar' 'bar2'? | 'bar2')?;\\n\";\n\t\tString expected =\n\t\t\t\"warning(\" + ErrorType.EPSILON_OPTIONAL.code + \"): A.g4:3:0: rule y contains an optional block with at least one alternative that can match an empty string\\n\" +\n\t\t\t\"warning(\" + ErrorType.EPSILON_OPTIONAL.code + \"): A.g4:4:0: rule z1 contains an optional block with at least one alternative that can match an empty string\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#315\n\t * \"Inconsistent lexer error msg for actions\"\n\t * https://github.com/antlr/antlr4/issues/315\n\t */\n\t@Test public void testActionAtEndOfOneLexerAlternative() {\n\t\tString grammar =\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"stat : 'start' CharacterLiteral 'end' EOF;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"// Lexer\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"CharacterLiteral\\n\" +\n\t\t\t\"    :   '\\\\'' SingleCharacter '\\\\''\\n\" +\n\t\t\t\"    |   '\\\\'' ~[\\\\r\\\\n] {notifyErrorListeners(\\\"unclosed character literal\\\");}\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"fragment\\n\" +\n\t\t\t\"SingleCharacter\\n\" +\n\t\t\t\"    :   ~['\\\\\\\\\\\\r\\\\n]\\n\" +\n\t\t\t\"    ;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"WS   : [ \\\\r\\\\t\\\\n]+ -> skip ;\\n\";\n\t\tString expected =\n\t\t\t\"\";\n\n\t\tString[] pair = new String[] { grammar, expected };\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#308 \"NullPointer exception\"\n\t * https://github.com/antlr/antlr4/issues/308\n\t */\n\t@Test public void testDoubleQuotedStringLiteral() {\n\t\tString grammar =\n\t\t\t\"lexer grammar A;\\n\"\n\t\t\t+ \"WHITESPACE : (\\\" \\\" | \\\"\\\\t\\\" | \\\"\\\\n\\\" | \\\"\\\\r\\\" | \\\"\\\\f\\\");\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:14: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:16: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:20: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:21: syntax error: '\\\\' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:23: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:27: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:28: syntax error: '\\\\' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:30: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:34: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:35: syntax error: '\\\\' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:37: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:41: syntax error: '\\\"' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:42: syntax error: '\\\\' came as a complete surprise to me\\n\" +\n\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): A.g4:2:44: syntax error: '\\\"' came as a complete surprise to me\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for https://github.com/antlr/antlr4/issues/1815\n\t * \"Null ptr exception in SqlBase.g4\"\n\t */\n\t@Test public void testDoubleQuoteInTwoStringLiterals() {\n\t\tString grammar =\n\t\t\t\"lexer grammar A;\\n\" +\n\t\t\t\"STRING : '\\\\\\\"' '\\\\\\\"' 'x' ;\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): A.g4:2:10: invalid escape sequence \\\\\\\"\\n\"+\n\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): A.g4:2:15: invalid escape sequence \\\\\\\"\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This test ensures that the {@link ErrorType#INVALID_ESCAPE_SEQUENCE}\n\t * error is not reported for escape sequences that are known to be valid.\n\t */\n\t@Test public void testValidEscapeSequences() {\n\t\tString grammar =\n\t\t\t\"lexer grammar A;\\n\" +\n\t\t\t\"NORMAL_ESCAPE : '\\\\b \\\\t \\\\n \\\\f \\\\r \\\\' \\\\\\\\';\\n\" +\n\t\t\t\"UNICODE_ESCAPE : '\\\\u0001 \\\\u00A1 \\\\u00a1 \\\\uaaaa \\\\uAAAA';\\n\";\n\t\tString expected =\n\t\t\t\"\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#507 \"NullPointerException When\n\t * Generating Code from Grammar\".\n\t * https://github.com/antlr/antlr4/issues/507\n\t */\n\t@Test public void testInvalidEscapeSequences() {\n\t\tString grammar =\n\t\t\t\"lexer grammar A;\\n\" +\n\t\t\t\"RULE : 'Foo \\\\uAABG \\\\x \\\\u';\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): A.g4:2:12: invalid escape sequence \\\\uAABG\\n\" +\n\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): A.g4:2:19: invalid escape sequence \\\\x\\n\" +\n\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): A.g4:2:22: invalid escape sequence \\\\u\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#959 \"NullPointerException\".\n\t * https://github.com/antlr/antlr4/issues/959\n\t */\n\t@Test public void testNotAllowedEmptyStrings() {\n\t\tString grammar =\n\t\t\t\"lexer grammar T;\\n\" +\n\t\t\t\"Error0: '''test''';\\n\" +\n\t\t\t\"Error1: '' 'test';\\n\" +\n\t\t\t\"Error2: 'test' '';\\n\" +\n\t\t\t\"Error3: '';\\n\" +\n\t\t\t\"NotError: ' ';\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): T.g4:2:8: string literals and sets cannot be empty: ''\\n\" +\n\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): T.g4:2:16: string literals and sets cannot be empty: ''\\n\" +\n\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): T.g4:3:8: string literals and sets cannot be empty: ''\\n\" +\n\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): T.g4:4:15: string literals and sets cannot be empty: ''\\n\" +\n\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): T.g4:5:8: string literals and sets cannot be empty: ''\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\t\tgrammar,\n\t\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testInvalidCharSetsAndStringLiterals() {\n\t\tString grammar =\n\t\t\t\t\"lexer grammar Test;\\n\" +\n\t\t\t\t\"INVALID_STRING_LITERAL_RANGE: 'GH'..'LM';\\n\" +\n\t\t\t\t\"INVALID_CHAR_SET:             [\\\\u24\\\\uA2][\\\\{];\\n\" +  //https://github.com/antlr/antlr4/issues/1077\n\t\t\t\t\"EMPTY_STRING_LITERAL_RANGE:   'F'..'A' | 'Z';\\n\" +\n\t\t\t\t\"EMPTY_CHAR_SET:               [f-az][];\\n\" +\n\t\t\t\t\"START_HYPHEN_IN_CHAR_SET:     [-z];\\n\" +\n\t\t\t\t\"END_HYPHEN_IN_CHAR_SET:       [a-];\\n\" +\n\t\t\t\t\"SINGLE_HYPHEN_IN_CHAR_SET:    [-];\\n\" +\n\t\t\t\t\"VALID_STRING_LITERALS:        '\\\\u1234' | '\\\\t' | '\\\\'';\\n\" +\n\t\t\t\t\"VALID_CHAR_SET:               [`\\\\-=\\\\]];\" +\n\t\t\t\t\"EMPTY_CHAR_SET_WITH_INVALID_ESCAPE_SEQUENCE: [\\\\'];\";  // https://github.com/antlr/antlr4/issues/1556\n\n\t\tString expected =\n\t\t\t\t\"error(\" + ErrorType.INVALID_LITERAL_IN_LEXER_SET.code + \"): Test.g4:2:30: multi-character literals are not allowed in lexer sets: 'GH'\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_LITERAL_IN_LEXER_SET.code + \"): Test.g4:2:36: multi-character literals are not allowed in lexer sets: 'LM'\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:3:30: invalid escape sequence \\\\u24\\\\u\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:3:40: invalid escape sequence \\\\{\\n\" +\n\t\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): Test.g4:4:33: string literals and sets cannot be empty: 'F'..'A'\\n\" +\n\t\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): Test.g4:5:30: string literals and sets cannot be empty: 'f'..'a'\\n\" +\n\t\t\t\t\"error(\" + ErrorType.EMPTY_STRINGS_AND_SETS_NOT_ALLOWED.code + \"): Test.g4:5:36: string literals and sets cannot be empty: []\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:10:84: invalid escape sequence \\\\'\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\t\tgrammar,\n\t\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testInvalidUnicodeEscapesInCharSet() {\n\t\tString grammar =\n\t\t\t\t\"lexer grammar Test;\\n\" +\n\t\t\t\t\"INVALID_EXTENDED_UNICODE_EMPTY: [\\\\u{}];\\n\" +\n\t\t\t\t\"INVALID_EXTENDED_UNICODE_NOT_TERMINATED: [\\\\u{];\\n\" +\n\t\t\t\t\"INVALID_EXTENDED_UNICODE_TOO_LONG: [\\\\u{110000}];\\n\" +\n\t\t\t\t\"INVALID_UNICODE_PROPERTY_EMPTY: [\\\\p{}];\\n\" +\n\t\t\t\t\"INVALID_UNICODE_PROPERTY_NOT_TERMINATED: [\\\\p{];\\n\" +\n\t\t\t\t\"INVALID_INVERTED_UNICODE_PROPERTY_EMPTY: [\\\\P{}];\\n\" +\n\t\t\t\t\"INVALID_UNICODE_PROPERTY_UNKNOWN: [\\\\p{NotAProperty}];\\n\" +\n\t\t\t\t\"INVALID_INVERTED_UNICODE_PROPERTY_UNKNOWN: [\\\\P{NotAProperty}];\\n\" +\n\t\t\t\t\"UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE: [\\\\p{Uppercase_Letter}-\\\\p{Lowercase_Letter}];\\n\" +\n\t\t\t\t\"UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE_2: [\\\\p{Letter}-Z];\\n\" +\n\t\t\t\t\"UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE_3: [A-\\\\p{Number}];\\n\" +\n\t\t\t\t\"INVERTED_UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE: [\\\\P{Uppercase_Letter}-\\\\P{Number}];\\n\" +\n\t\t\t\t\"EMOJI_MODIFIER: [\\\\p{Grapheme_Cluster_Break=E_Base}];\\n\";\n\n\t\tString expected =\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:2:32: invalid escape sequence \\\\u{}\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:3:41: invalid escape sequence \\\\u{\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:4:35: invalid escape sequence \\\\u{110\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:5:32: invalid escape sequence \\\\p{}\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:6:41: invalid escape sequence \\\\p{\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:7:41: invalid escape sequence \\\\P{}\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:8:34: invalid escape sequence \\\\p{NotAProperty}\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:9:43: invalid escape sequence \\\\P{NotAProperty}\\n\" +\n\t\t\t\t\"error(\" + ErrorType.UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE.code + \"): Test.g4:10:39: unicode property escapes not allowed in lexer charset range: [\\\\p{Uppercase_Letter}-\\\\p{Lowercase_Letter}]\\n\" +\n\t\t\t\t\"error(\" + ErrorType.UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE.code + \"): Test.g4:11:41: unicode property escapes not allowed in lexer charset range: [\\\\p{Letter}-Z]\\n\" +\n\t\t\t\t\"error(\" + ErrorType.UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE.code + \"): Test.g4:12:41: unicode property escapes not allowed in lexer charset range: [A-\\\\p{Number}]\\n\" +\n\t\t\t\t\"error(\" + ErrorType.UNICODE_PROPERTY_NOT_ALLOWED_IN_RANGE.code + \"): Test.g4:13:48: unicode property escapes not allowed in lexer charset range: [\\\\P{Uppercase_Letter}-\\\\P{Number}]\\n\" +\n\t\t\t\t\"error(\" + ErrorType.INVALID_ESCAPE_SEQUENCE.code + \"): Test.g4:14:16: invalid escape sequence \\\\p{Grapheme_Cluster_Break=E_Base}\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\t\tgrammar,\n\t\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This test ensures the {@link ErrorType#UNRECOGNIZED_ASSOC_OPTION} warning\n\t * is produced as described in the documentation.\n\t */\n\t@Test public void testUnrecognizedAssocOption() {\n\t\tString grammar =\n\t\t\t\"grammar A;\\n\" +\n\t\t\t\"x : 'x'\\n\" +\n\t\t\t\"  | x '+'<assoc=right> x   // warning 157\\n\" +\n\t\t\t\"  |<assoc=right> x '*' x   // ok\\n\" +\n\t\t\t\"  ;\\n\";\n\t\tString expected =\n\t\t\t\"warning(\" + ErrorType.UNRECOGNIZED_ASSOC_OPTION.code + \"): A.g4:3:10: rule x contains an assoc terminal option in an unrecognized location\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This test ensures the {@link ErrorType#FRAGMENT_ACTION_IGNORED} warning\n\t * is produced as described in the documentation.\n\t */\n\t@Test public void testFragmentActionIgnored() {\n\t\tString grammar =\n\t\t\t\"lexer grammar A;\\n\" +\n\t\t\t\"X1 : 'x' -> more    // ok\\n\" +\n\t\t\t\"   ;\\n\" +\n\t\t\t\"Y1 : 'x' {more();}  // ok\\n\" +\n\t\t\t\"   ;\\n\" +\n\t\t\t\"fragment\\n\" +\n\t\t\t\"X2 : 'x' -> more    // warning 158\\n\" +\n\t\t\t\"   ;\\n\" +\n\t\t\t\"fragment\\n\" +\n\t\t\t\"Y2 : 'x' {more();}  // warning 158\\n\" +\n\t\t\t\"   ;\\n\";\n\t\tString expected =\n\t\t\t\"warning(\" + ErrorType.FRAGMENT_ACTION_IGNORED.code + \"): A.g4:7:12: fragment rule X2 contains an action or command which can never be executed\\n\" +\n\t\t\t\"warning(\" + ErrorType.FRAGMENT_ACTION_IGNORED.code + \"): A.g4:10:9: fragment rule Y2 contains an action or command which can never be executed\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#500 \"Array Index Out Of\n\t * Bounds\".\n\t * https://github.com/antlr/antlr4/issues/500\n\t */\n\t@Test public void testTokenNamedEOF() {\n\t\tString grammar =\n\t\t\t\"lexer grammar A;\\n\" +\n\t\t\t\"WS : ' ';\\n\" +\n\t\t\t\" EOF : 'a';\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.RESERVED_RULE_NAME.code + \"): A.g4:3:1: cannot declare a rule with reserved name EOF\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#649 \"unknown target causes\n\t * null ptr exception.\".\n\t * https://github.com/antlr/antlr4/issues/649\n\t * Stops before processing the lexer\n\t */\n\t@Test public void testInvalidLanguageInGrammarWithLexerCommand() {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"options { language=Foo; }\\n\" +\n\t\t\t\"start : 'T' EOF;\\n\" +\n\t\t\t\"Something : 'something' -> channel(CUSTOM);\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.CANNOT_CREATE_TARGET_GENERATOR.code + \"):  ANTLR cannot generate Foo code as of version \" + Tool.VERSION + \"\\n\";\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#649 \"unknown target causes\n\t * null ptr exception.\".\n\t * https://github.com/antlr/antlr4/issues/649\n\t */\n\t@Test public void testInvalidLanguageInGrammar() {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"options { language=Foo; }\\n\" +\n\t\t\t\"start : 'T' EOF;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.CANNOT_CREATE_TARGET_GENERATOR.code + \"):  ANTLR cannot generate Foo code as of version \" + Tool.VERSION + \"\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testChannelDefinitionInLexer() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar T;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"channels {\\n\" +\n\t\t\t\"\tWHITESPACE_CHANNEL,\\n\" +\n\t\t\t\"\tCOMMENT_CHANNEL\\n\" +\n\t\t\t\"}\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"COMMENT:    '//' ~[\\\\n]+ -> channel(COMMENT_CHANNEL);\\n\" +\n\t\t\t\"WHITESPACE: [ \\\\t]+      -> channel(WHITESPACE_CHANNEL);\\n\";\n\n\t\tString expected = \"\";\n\n\t\tString[] pair = { grammar, expected };\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testChannelDefinitionInParser() throws Exception {\n\t\tString grammar =\n\t\t\t\"parser grammar T;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"channels {\\n\" +\n\t\t\t\"\tWHITESPACE_CHANNEL,\\n\" +\n\t\t\t\"\tCOMMENT_CHANNEL\\n\" +\n\t\t\t\"}\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"start : EOF;\\n\";\n\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.CHANNELS_BLOCK_IN_PARSER_GRAMMAR.code + \"): T.g4:3:0: custom channels are not supported in parser grammars\\n\";\n\n\t\tString[] pair = { grammar, expected };\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testChannelDefinitionInCombined() throws Exception {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"channels {\\n\" +\n\t\t\t\"\tWHITESPACE_CHANNEL,\\n\" +\n\t\t\t\"\tCOMMENT_CHANNEL\\n\" +\n\t\t\t\"}\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"start : EOF;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"COMMENT:    '//' ~[\\\\n]+ -> channel(COMMENT_CHANNEL);\\n\" +\n\t\t\t\"WHITESPACE: [ \\\\t]+      -> channel(WHITESPACE_CHANNEL);\\n\";\n\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_CHANNEL_NAME.code + \"): T.g4:10:35: COMMENT_CHANNEL is not a recognized channel name\\n\" +\n\t\t\t\"error(\" + ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_CHANNEL_NAME.code + \"): T.g4:11:35: WHITESPACE_CHANNEL is not a recognized channel name\\n\" +\n\t\t\t\"error(\" + ErrorType.CHANNELS_BLOCK_IN_COMBINED_GRAMMAR.code + \"): T.g4:3:0: custom channels are not supported in combined grammars\\n\";\n\n\t\tString[] pair = { grammar, expected };\n\t\ttestErrors(pair, true);\n\t}\n\n\t/**\n\t * This is a regression test for antlr/antlr4#497 now that antlr/antlr4#309\n\t * is resolved.\n\t * https://github.com/antlr/antlr4/issues/497\n\t * https://github.com/antlr/antlr4/issues/309\n\t */\n\t@Test public void testChannelDefinitions() throws Exception {\n\t\tString grammar =\n\t\t\t\"lexer grammar T;\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"channels {\\n\" +\n\t\t\t\"\tWHITESPACE_CHANNEL,\\n\" +\n\t\t\t\"\tCOMMENT_CHANNEL\\n\" +\n\t\t\t\"}\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"COMMENT:    '//' ~[\\\\n]+ -> channel(COMMENT_CHANNEL);\\n\" +\n\t\t\t\"WHITESPACE: [ \\\\t]+      -> channel(WHITESPACE_CHANNEL);\\n\" +\n\t\t\t\"NEWLINE:    '\\\\r'? '\\\\n' -> channel(NEWLINE_CHANNEL);\";\n\n\t\t// WHITESPACE_CHANNEL and COMMENT_CHANNEL are defined, but NEWLINE_CHANNEL is not\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.CONSTANT_VALUE_IS_NOT_A_RECOGNIZED_CHANNEL_NAME.code + \"): T.g4:10:34: NEWLINE_CHANNEL is not a recognized channel name\\n\";\n\n\t\tString[] pair = { grammar, expected };\n\t\ttestErrors(pair, true);\n\t}\n\n\t// Test for https://github.com/antlr/antlr4/issues/1556\n\t@Test public void testRangeInParserGrammar() {\n\t\tString grammar =\n\t\t\t\"grammar T;\\n\"+\n\t\t\t\"a:  'A'..'Z' ;\\n\";\n\t\tString expected =\n\t\t\t\"error(\" + ErrorType.TOKEN_RANGE_IN_PARSER.code + \"): T.g4:2:4: token ranges not allowed in parser: 'A'..'Z'\\n\";\n\n\t\tString[] pair = new String[] {\n\t\t\tgrammar,\n\t\t\texpected\n\t\t};\n\n\t\ttestErrors(pair, true);\n\t}\n\n\t@Test public void testRuleNamesAsTree() {\n\t\tString grammar =\n\t\t\t\t\"grammar T;\\n\" +\n\t\t\t\t\"tree : 'X';\";\n\t\ttestErrors(new String[] { grammar, \"\" }, true);\n\t}\n\n\t@Test public void testLexerRuleLabel() {\n\t\tString grammar =\n\t\t\t\t\"grammar T;\\n\" +\n\t\t\t\t\"a : A;\\n\" +\n\t\t\t\t\"A : h=~('b'|'c') ;\";\n\t\ttestErrors(new String[] {\n\t\t\t\tgrammar,\n\t\t\t\t\"error(\" + ErrorType.SYNTAX_ERROR.code + \"): T.g4:3:5: syntax error: '=' came as a complete surprise to me while looking for lexer rule element\\n\" }, false);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestTopologicalSort.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.misc.Graph;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n/** Test topo sort in GraphNode. */\npublic class TestTopologicalSort {\n    @Test\n    public void testFairlyLargeGraph() throws Exception {\n        Graph<String> g = new Graph<String>();\n        g.addEdge(\"C\", \"F\");\n        g.addEdge(\"C\", \"G\");\n        g.addEdge(\"C\", \"A\");\n        g.addEdge(\"C\", \"B\");\n        g.addEdge(\"A\", \"D\");\n        g.addEdge(\"A\", \"E\");\n        g.addEdge(\"B\", \"E\");\n        g.addEdge(\"D\", \"E\");\n        g.addEdge(\"D\", \"F\");\n        g.addEdge(\"F\", \"H\");\n        g.addEdge(\"E\", \"F\");\n\n        String expecting = \"[H, F, G, E, D, A, B, C]\";\n        List<String> nodes = g.sort();\n        String result = nodes.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test\n    public void testCyclicGraph() throws Exception {\n        Graph<String> g = new Graph<String>();\n        g.addEdge(\"A\", \"B\");\n        g.addEdge(\"B\", \"C\");\n        g.addEdge(\"C\", \"A\");\n        g.addEdge(\"C\", \"D\");\n\n        String expecting = \"[D, C, B, A]\";\n        List<String> nodes = g.sort();\n        String result = nodes.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test\n    public void testRepeatedEdges() throws Exception {\n        Graph<String> g = new Graph<String>();\n        g.addEdge(\"A\", \"B\");\n        g.addEdge(\"B\", \"C\");\n        g.addEdge(\"A\", \"B\"); // dup\n        g.addEdge(\"C\", \"D\");\n\n        String expecting = \"[D, C, B, A]\";\n        List<String> nodes = g.sort();\n        String result = nodes.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test\n    public void testSimpleTokenDependence() throws Exception {\n        Graph<String> g = new Graph<String>();\n        g.addEdge(\"Java.g4\", \"MyJava.tokens\"); // Java feeds off manual token file\n        g.addEdge(\"Java.tokens\", \"Java.g4\");\n        g.addEdge(\"Def.g4\", \"Java.tokens\");    // walkers feed off generated tokens\n        g.addEdge(\"Ref.g4\", \"Java.tokens\");\n\n        String expecting = \"[MyJava.tokens, Java.g4, Java.tokens, Def.g4, Ref.g4]\";\n        List<String> nodes = g.sort();\n        String result = nodes.toString();\n        assertEquals(expecting, result);\n    }\n\n    @Test\n    public void testParserLexerCombo() throws Exception {\n        Graph<String> g = new Graph<String>();\n        g.addEdge(\"JavaLexer.tokens\", \"JavaLexer.g4\");\n        g.addEdge(\"JavaParser.g4\", \"JavaLexer.tokens\");\n        g.addEdge(\"Def.g4\", \"JavaLexer.tokens\");\n        g.addEdge(\"Ref.g4\", \"JavaLexer.tokens\");\n\n        String expecting = \"[JavaLexer.g4, JavaLexer.tokens, JavaParser.g4, Def.g4, Ref.g4]\";\n        List<String> nodes = g.sort();\n        String result = nodes.toString();\n        assertEquals(expecting, result);\n    }\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestUnbufferedCharStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CommonTokenFactory;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.IntStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.UnbufferedCharStream;\nimport org.antlr.v4.runtime.misc.Interval;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.io.Reader;\nimport java.io.StringReader;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\n\n@SuppressWarnings(\"unused\")\npublic class TestUnbufferedCharStream {\n\t@Test public void testNoChar() {\n\t\tCharStream input = createStream(\"\");\n\t\tassertEquals(IntStream.EOF, input.LA(1));\n\t\tassertEquals(IntStream.EOF, input.LA(2));\n\t}\n\n\t/**\n\t * The {@link IntStream} interface does not specify the behavior when the\n\t * EOF symbol is consumed, but {@link UnbufferedCharStream} handles this\n\t * particular case by throwing an {@link IllegalStateException}.\n\t */\n\t@Test\n\tpublic void testConsumeEOF() {\n\t\tCharStream input = createStream(\"\");\n\t\tassertEquals(IntStream.EOF, input.LA(1));\n\t\tassertThrows(IllegalStateException.class, input::consume);\n\t}\n\n\t@Test\n\tpublic void testNegativeSeek() {\n\t\tCharStream input = createStream(\"\");\n\t\tassertThrows(IllegalArgumentException.class, () -> input.seek(-1));\n\t}\n\n\t@Test\n\tpublic void testSeekPastEOF() {\n\t\tCharStream input = createStream(\"\");\n\t\tassertEquals(0, input.index());\n\t\tinput.seek(1);\n\t\tassertEquals(0, input.index());\n\t}\n\n\t/**\n\t * The {@link IntStream} interface does not specify the behavior when marks\n\t * are not released in the reversed order they were created, but\n\t * {@link UnbufferedCharStream} handles this case by throwing an\n\t * {@link IllegalStateException}.\n\t */\n\t@Test\n\tpublic void testMarkReleaseOutOfOrder() {\n\t\tCharStream input = createStream(\"\");\n\t\tint m1 = input.mark();\n\t\tint m2 = input.mark();\n\t\tassertThrows(IllegalStateException.class, () -> input.release(m1));\n\t}\n\n\t/**\n\t * The {@link IntStream} interface does not specify the behavior when a mark\n\t * is released twice, but {@link UnbufferedCharStream} handles this case by\n\t * throwing an {@link IllegalStateException}.\n\t */\n\t@Test\n\tpublic void testMarkReleasedTwice() {\n\t\tCharStream input = createStream(\"\");\n\t\tint m1 = input.mark();\n\t\tinput.release(m1);\n\t\tassertThrows(IllegalStateException.class, () -> input.release(m1));\n\t}\n\n\t/**\n\t * The {@link IntStream} interface does not specify the behavior when a mark\n\t * is released twice, but {@link UnbufferedCharStream} handles this case by\n\t * throwing an {@link IllegalStateException}.\n\t */\n\t@Test\n\tpublic void testNestedMarkReleasedTwice() {\n\t\tCharStream input = createStream(\"\");\n\t\tint m1 = input.mark();\n\t\tint m2 = input.mark();\n\t\tinput.release(m2);\n\t\tassertThrows(IllegalStateException.class, () -> input.release(m2));\n\t}\n\n\t/**\n\t * It is not valid to pass a mark to {@link IntStream#seek}, but\n\t * {@link UnbufferedCharStream} creates marks in such a way that this\n\t * invalid usage results in an {@link IllegalArgumentException}.\n\t */\n\t@Test\n\tpublic void testMarkPassedToSeek() {\n\t\tCharStream input = createStream(\"\");\n\t\tint m1 = input.mark();\n\t\tassertThrows(IllegalArgumentException.class, () -> input.seek(m1));\n\t}\n\n\t@Test\n\tpublic void testSeekBeforeBufferStart() {\n\t\tCharStream input = createStream(\"xyz\");\n\t\tinput.consume();\n\t\tint m1 = input.mark();\n\t\tassertEquals(1, input.index());\n\t\tinput.consume();\n\t\tassertThrows(IllegalArgumentException.class, () -> input.seek(0));\n\t}\n\n\t@Test\n\tpublic void testGetTextBeforeBufferStart() {\n\t\tCharStream input = createStream(\"xyz\");\n\t\tinput.consume();\n\t\tint m1 = input.mark();\n\t\tassertEquals(1, input.index());\n\t\tassertThrows(UnsupportedOperationException.class, () -> input.getText(new Interval(0, 1)));\n\t}\n\n\t@Test\n\tpublic void testGetTextInMarkedRange() {\n\t\tCharStream input = createStream(\"xyz\");\n\t\tinput.consume();\n\t\tint m1 = input.mark();\n\t\tassertEquals(1, input.index());\n\t\tinput.consume();\n\t\tinput.consume();\n\t\tassertEquals(\"yz\", input.getText(new Interval(1, 2)));\n\t}\n\n\t@Test\n\tpublic void testLastChar() {\n\t\tCharStream input = createStream(\"abcdef\");\n\n\t\tinput.consume();\n\t\tassertEquals('a', input.LA(-1));\n\n\t\tint m1 = input.mark();\n\t\tinput.consume();\n\t\tinput.consume();\n\t\tinput.consume();\n\t\tassertEquals('d', input.LA(-1));\n\n\t\tinput.seek(2);\n\t\tassertEquals('b', input.LA(-1));\n\n\t\tinput.release(m1);\n\t\tinput.seek(3);\n\t\tassertEquals('c', input.LA(-1));\n\t\t// this special case is not required by the IntStream interface, but\n\t\t// UnbufferedCharStream allows it so we have to make sure the resulting\n\t\t// state is consistent\n\t\tinput.seek(2);\n\t\tassertEquals('b', input.LA(-1));\n\t}\n\n\t@Test public void test1Char() throws Exception {\n\t\tTestingUnbufferedCharStream input = createStream(\"x\");\n\t\tassertEquals('x', input.LA(1));\n\t\tinput.consume();\n\t\tassertEquals(IntStream.EOF, input.LA(1));\n\t\tString r = input.getRemainingBuffer();\n\t\tassertEquals(\"\\uFFFF\", r); // shouldn't include x\n\t\tassertEquals(\"\\uFFFF\", input.getBuffer()); // whole buffer\n\t}\n\n\t@Test public void test2Char() throws Exception {\n\t\tTestingUnbufferedCharStream input = createStream(\"xy\");\n\t\tassertEquals('x', input.LA(1));\n\t\tinput.consume();\n\t\tassertEquals('y', input.LA(1));\n\t\tassertEquals(\"y\", input.getRemainingBuffer()); // shouldn't include x\n\t\tassertEquals(\"y\", input.getBuffer());\n\t\tinput.consume();\n\t\tassertEquals(IntStream.EOF, input.LA(1));\n\t\tassertEquals(\"\\uFFFF\", input.getBuffer());\n\t}\n\n    @Test public void test2CharAhead() throws Exception {\n   \t\tCharStream input = createStream(\"xy\");\n   \t\tassertEquals('x', input.LA(1));\n   \t\tassertEquals('y', input.LA(2));\n   \t\tassertEquals(IntStream.EOF, input.LA(3));\n   \t}\n\n    @Test public void testBufferExpand() throws Exception {\n\t\tTestingUnbufferedCharStream input = createStream(\"01234\", 2);\n   \t\tassertEquals('0', input.LA(1));\n        assertEquals('1', input.LA(2));\n        assertEquals('2', input.LA(3));\n        assertEquals('3', input.LA(4));\n        assertEquals('4', input.LA(5));\n\t\tassertEquals(\"01234\", input.getBuffer());\n   \t\tassertEquals(IntStream.EOF, input.LA(6));\n   \t}\n\n    @Test public void testBufferWrapSize1() throws Exception {\n   \t\tCharStream input = createStream(\"01234\", 1);\n        assertEquals('0', input.LA(1));\n        input.consume();\n        assertEquals('1', input.LA(1));\n        input.consume();\n        assertEquals('2', input.LA(1));\n        input.consume();\n        assertEquals('3', input.LA(1));\n        input.consume();\n        assertEquals('4', input.LA(1));\n        input.consume();\n   \t\tassertEquals(IntStream.EOF, input.LA(1));\n   \t}\n\n    @Test public void testBufferWrapSize2() throws Exception {\n   \t\tCharStream input = createStream(\"01234\", 2);\n        assertEquals('0', input.LA(1));\n        input.consume();\n        assertEquals('1', input.LA(1));\n        input.consume();\n        assertEquals('2', input.LA(1));\n        input.consume();\n        assertEquals('3', input.LA(1));\n        input.consume();\n        assertEquals('4', input.LA(1));\n        input.consume();\n   \t\tassertEquals(IntStream.EOF, input.LA(1));\n   \t}\n\n\t@Test public void test1Mark() throws Exception {\n\t\tTestingUnbufferedCharStream input = createStream(\"xyz\");\n\t\tint m = input.mark();\n\t\tassertEquals('x', input.LA(1));\n\t\tassertEquals('y', input.LA(2));\n\t\tassertEquals('z', input.LA(3));\n\t\tinput.release(m);\n\t\tassertEquals(IntStream.EOF, input.LA(4));\n\t\tassertEquals(\"xyz\\uFFFF\", input.getBuffer());\n\t}\n\n\t@Test public void test1MarkWithConsumesInSequence() throws Exception {\n\t\tTestingUnbufferedCharStream input = createStream(\"xyz\");\n\t\tint m = input.mark();\n\t\tinput.consume(); // x, moves to y\n\t\tinput.consume(); // y\n\t\tinput.consume(); // z, moves to EOF\n\t\tassertEquals(IntStream.EOF, input.LA(1));\n\t\tassertEquals(\"xyz\\uFFFF\", input.getBuffer());\n\t\tinput.release(m); // wipes buffer\n\t\tassertEquals(\"\\uFFFF\", input.getBuffer());\n\t}\n\n    @Test public void test2Mark() throws Exception {\n\t\tTestingUnbufferedCharStream input = createStream(\"xyz\", 100);\n   \t\tassertEquals('x', input.LA(1));\n        input.consume(); // reset buffer index (p) to 0\n        int m1 = input.mark();\n   \t\tassertEquals('y', input.LA(1));\n        input.consume();\n        int m2 = input.mark();\n\t\tassertEquals(\"yz\", input.getBuffer());\n        input.release(m2); // drop to 1 marker\n        input.consume();\n        input.release(m1); // shifts remaining char to beginning\n   \t\tassertEquals(IntStream.EOF, input.LA(1));\n\t\tassertEquals(\"\\uFFFF\", input.getBuffer());\n   \t}\n\n    @Test public void testAFewTokens() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n                \"lexer grammar t;\\n\"+\n\t\t\t\t\"ID : 'a'..'z'+;\\n\" +\n\t\t\t\t\"INT : '0'..'9'+;\\n\" +\n\t\t\t\t\"SEMI : ';';\\n\" +\n\t\t\t\t\"ASSIGN : '=';\\n\" +\n\t\t\t\t\"PLUS : '+';\\n\" +\n\t\t\t\t\"MULT : '*';\\n\" +\n\t\t\t\t\"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 3 * 0 + 2 * 0;\n\t\tTestingUnbufferedCharStream input = createStream(\"x = 302 * 91 + 20234234 * 0;\");\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n\t\t// copy text into tokens from char stream\n\t\tlexEngine.setTokenFactory(new CommonTokenFactory(true));\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n        String result = tokens.LT(1).getText();\n        String expecting = \"x\";\n        assertEquals(expecting, result);\n\t\ttokens.fill();\n\t\texpecting =\n\t\t\t\"[[@0,0:0='x',<1>,1:0], [@1,1:1=' ',<7>,1:1], [@2,2:2='=',<4>,1:2],\" +\n\t\t\t\" [@3,3:3=' ',<7>,1:3], [@4,4:6='302',<2>,1:4], [@5,7:7=' ',<7>,1:7],\" +\n\t\t\t\" [@6,8:8='*',<6>,1:8], [@7,9:9=' ',<7>,1:9], [@8,10:11='91',<2>,1:10],\" +\n\t\t\t\" [@9,12:12=' ',<7>,1:12], [@10,13:13='+',<5>,1:13], [@11,14:14=' ',<7>,1:14],\" +\n\t\t\t\" [@12,15:22='20234234',<2>,1:15], [@13,23:23=' ',<7>,1:23],\" +\n\t\t\t\" [@14,24:24='*',<6>,1:24], [@15,25:25=' ',<7>,1:25], [@16,26:26='0',<2>,1:26],\" +\n\t\t\t\" [@17,27:27=';',<3>,1:27], [@18,28:27='',<-1>,1:28]]\";\n\t\tassertEquals(expecting, tokens.getTokens().toString());\n    }\n\n\t@Test public void testUnicodeSMP() throws Exception {\n\t\tTestingUnbufferedCharStream input = createStream(\"\\uD83C\\uDF0E\");\n\t\tassertEquals(0x1F30E, input.LA(1));\n\t\tassertEquals(\"\\uD83C\\uDF0E\", input.getBuffer());\n\t\tinput.consume();\n\t\tassertEquals(IntStream.EOF, input.LA(1));\n\t\tassertEquals(\"\\uFFFF\", input.getBuffer());\n\t}\n\n\t@Test\n\tpublic void testDanglingHighSurrogateAtEOFThrows() {\n\t\tassertThrows(RuntimeException.class, () -> createStream(\"\\uD83C\"));\n\t}\n\n\t@Test\n\tpublic void testDanglingHighSurrogateThrows() {\n\t\tassertThrows(RuntimeException.class, () -> createStream(\"\\uD83C\\u0123\"));\n\t}\n\n\t@Test\n\tpublic void testDanglingLowSurrogateThrows() {\n\t\tassertThrows(RuntimeException.class, () -> createStream(\"\\uDF0E\"));\n\t}\n\n\tprotected static TestingUnbufferedCharStream createStream(String text) {\n\t\treturn new TestingUnbufferedCharStream(new StringReader(text));\n\t}\n\n\tprotected static TestingUnbufferedCharStream createStream(String text, int bufferSize) {\n\t\treturn new TestingUnbufferedCharStream(new StringReader(text), bufferSize);\n\t}\n\n\tprotected static class TestingUnbufferedCharStream extends UnbufferedCharStream {\n\n\t\tpublic TestingUnbufferedCharStream(Reader input) {\n\t\t\tsuper(input);\n\t\t}\n\n\t\tpublic TestingUnbufferedCharStream(Reader input, int bufferSize) {\n\t\t\tsuper(input, bufferSize);\n\t\t}\n\n\t\t/** For testing.  What's in moving window into data stream from\n\t\t *  current index, LA(1) or data[p], to end of buffer?\n\t\t */\n\t\tpublic String getRemainingBuffer() {\n\t\t\tif ( n==0 ) return \"\";\n\t\t\tint len = n;\n\t\t\tif (data[len-1] == IntStream.EOF) {\n\t\t\t\t// Don't pass -1 to new String().\n\t\t\t\treturn new String(data,p,len-p-1) + \"\\uFFFF\";\n\t\t\t} else {\n\t\t\t\treturn new String(data,p,len-p);\n\t\t\t}\n\t\t}\n\n\t\t/** For testing.  What's in moving window buffer into data stream.\n\t\t *  From 0..p-1 have been consume.\n\t\t */\n\t\tpublic String getBuffer() {\n\t\t\tif ( n==0 ) return \"\";\n\t\t\tint len = n;\n\t\t\t// Don't pass -1 to new String().\n\t\t\tif (data[len-1] == IntStream.EOF) {\n\t\t\t\t// Don't pass -1 to new String().\n\t\t\t\treturn new String(data,0,len-1) + \"\\uFFFF\";\n\t\t\t} else {\n\t\t\t\treturn new String(data,0,len);\n\t\t\t}\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestUnbufferedTokenStream.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.TokenSource;\nimport org.antlr.v4.runtime.TokenStream;\nimport org.antlr.v4.runtime.UnbufferedTokenStream;\nimport org.antlr.v4.tool.LexerGrammar;\nimport org.junit.jupiter.api.Test;\n\nimport java.io.StringReader;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\n@SuppressWarnings(\"unused\")\npublic class TestUnbufferedTokenStream {\n\t@Test\n\tpublic void testLookahead() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 302;\n        CharStream input = new ANTLRInputStream(\n\t\t\tnew StringReader(\"x = 302;\")\n\t\t);\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n        TokenStream tokens = new UnbufferedTokenStream<Token>(lexEngine);\n\n\t\tassertEquals(\"x\", tokens.LT(1).getText());\n\t\tassertEquals(\" \", tokens.LT(2).getText());\n\t\tassertEquals(\"=\", tokens.LT(3).getText());\n\t\tassertEquals(\" \", tokens.LT(4).getText());\n\t\tassertEquals(\"302\", tokens.LT(5).getText());\n\t\tassertEquals(\";\", tokens.LT(6).getText());\n    }\n\n\t@Test public void testNoBuffering() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 302;\n        CharStream input = new ANTLRInputStream(\n\t\t\tnew StringReader(\"x = 302;\")\n\t\t);\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n\t\tTestingUnbufferedTokenStream<Token> tokens = new TestingUnbufferedTokenStream<Token>(lexEngine);\n\n\t\tassertEquals(\"[[@0,0:0='x',<1>,1:0]]\", tokens.getBuffer().toString());\n\t\tassertEquals(\"x\", tokens.LT(1).getText());\n\t\ttokens.consume(); // move to WS\n\t\tassertEquals(\" \", tokens.LT(1).getText());\n\t\tassertEquals(\"[[@1,1:1=' ',<7>,1:1]]\", tokens.getRemainingBuffer().toString());\n\t\ttokens.consume();\n\t\tassertEquals(\"=\", tokens.LT(1).getText());\n\t\tassertEquals(\"[[@2,2:2='=',<4>,1:2]]\", tokens.getRemainingBuffer().toString());\n\t\ttokens.consume();\n\t\tassertEquals(\" \", tokens.LT(1).getText());\n\t\tassertEquals(\"[[@3,3:3=' ',<7>,1:3]]\", tokens.getRemainingBuffer().toString());\n\t\ttokens.consume();\n\t\tassertEquals(\"302\", tokens.LT(1).getText());\n\t\tassertEquals(\"[[@4,4:6='302',<2>,1:4]]\", tokens.getRemainingBuffer().toString());\n\t\ttokens.consume();\n\t\tassertEquals(\";\", tokens.LT(1).getText());\n\t\tassertEquals(\"[[@5,7:7=';',<3>,1:7]]\", tokens.getRemainingBuffer().toString());\n    }\n\n\t@Test public void testMarkStart() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 302;\n        CharStream input = new ANTLRInputStream(\n\t\t\tnew StringReader(\"x = 302;\")\n\t\t);\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n\t\tTestingUnbufferedTokenStream<Token> tokens = new TestingUnbufferedTokenStream<Token>(lexEngine);\n\n\t\tint m = tokens.mark();\n\t\tassertEquals(\"[[@0,0:0='x',<1>,1:0]]\", tokens.getBuffer().toString());\n\t\tassertEquals(\"x\", tokens.LT(1).getText());\n\t\ttokens.consume(); // consume x\n\t\tassertEquals(\"[[@0,0:0='x',<1>,1:0], [@1,1:1=' ',<7>,1:1]]\", tokens.getBuffer().toString());\n\t\ttokens.consume(); // ' '\n\t\ttokens.consume(); // =\n\t\ttokens.consume(); // ' '\n\t\ttokens.consume(); // 302\n\t\ttokens.consume(); // ;\n\t\tassertEquals(\"[[@0,0:0='x',<1>,1:0], [@1,1:1=' ',<7>,1:1],\" +\n\t\t\t\t\t \" [@2,2:2='=',<4>,1:2], [@3,3:3=' ',<7>,1:3],\" +\n\t\t\t\t\t \" [@4,4:6='302',<2>,1:4], [@5,7:7=';',<3>,1:7],\" +\n\t\t\t\t\t \" [@6,8:7='<EOF>',<-1>,1:8]]\",\n\t\t\t\t\t tokens.getBuffer().toString());\n    }\n\n\t@Test public void testMarkThenRelease() throws Exception {\n        LexerGrammar g = new LexerGrammar(\n            \"lexer grammar t;\\n\"+\n            \"ID : 'a'..'z'+;\\n\" +\n            \"INT : '0'..'9'+;\\n\" +\n            \"SEMI : ';';\\n\" +\n            \"ASSIGN : '=';\\n\" +\n            \"PLUS : '+';\\n\" +\n            \"MULT : '*';\\n\" +\n            \"WS : ' '+;\\n\");\n        // Tokens: 012345678901234567\n        // Input:  x = 302;\n        CharStream input = new ANTLRInputStream(\n\t\t\tnew StringReader(\"x = 302 + 1;\")\n\t\t);\n        LexerInterpreter lexEngine = g.createLexerInterpreter(input);\n\t\tTestingUnbufferedTokenStream<Token> tokens = new TestingUnbufferedTokenStream<Token>(lexEngine);\n\n\t\tint m = tokens.mark();\n\t\tassertEquals(\"[[@0,0:0='x',<1>,1:0]]\", tokens.getBuffer().toString());\n\t\tassertEquals(\"x\", tokens.LT(1).getText());\n\t\ttokens.consume(); // consume x\n\t\tassertEquals(\"[[@0,0:0='x',<1>,1:0], [@1,1:1=' ',<7>,1:1]]\", tokens.getBuffer().toString());\n\t\ttokens.consume(); // ' '\n\t\ttokens.consume(); // =\n\t\ttokens.consume(); // ' '\n\t\tassertEquals(\"302\", tokens.LT(1).getText());\n\t\ttokens.release(m); // \"x = 302\" is in buffer. will kill buffer\n\t\ttokens.consume(); // 302\n\t\ttokens.consume(); // ' '\n\t\tm = tokens.mark(); // mark at the +\n\t\tassertEquals(\"+\", tokens.LT(1).getText());\n\t\ttokens.consume(); // '+'\n\t\ttokens.consume(); // ' '\n\t\ttokens.consume(); // 1\n\t\ttokens.consume(); // ;\n\t\tassertEquals(\"<EOF>\", tokens.LT(1).getText());\n\t\t// we marked at the +, so that should be the start of the buffer\n\t\tassertEquals(\"[[@6,8:8='+',<5>,1:8], [@7,9:9=' ',<7>,1:9],\" +\n\t\t\t\t\t \" [@8,10:10='1',<2>,1:10], [@9,11:11=';',<3>,1:11],\" +\n\t\t\t\t\t \" [@10,12:11='<EOF>',<-1>,1:12]]\",\n\t\t\t\t\t tokens.getBuffer().toString());\n\t\ttokens.release(m);\n    }\n\n\tprotected static class TestingUnbufferedTokenStream<T extends Token> extends UnbufferedTokenStream<T> {\n\n\t\tpublic TestingUnbufferedTokenStream(TokenSource tokenSource) {\n\t\t\tsuper(tokenSource);\n\t\t}\n\n\t\t/** For testing.  What's in moving window into token stream from\n\t\t *  current index, LT(1) or tokens[p], to end of buffer?\n\t\t */\n\t\tprotected List<? extends Token> getRemainingBuffer() {\n\t\t\tif ( n==0 ) {\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\n\t\t\treturn Arrays.asList(tokens).subList(p, n);\n\t\t}\n\n\t\t/** For testing.  What's in moving window buffer into data stream.\n\t\t *  From 0..p-1 have been consume.\n\t\t */\n\t\tprotected List<? extends Token> getBuffer() {\n\t\t\tif ( n==0 ) {\n\t\t\t\treturn Collections.emptyList();\n\t\t\t}\n\n\t\t\treturn Arrays.asList(tokens).subList(0, n);\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestUnicodeData.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\nimport org.antlr.v4.unicode.UnicodeData;\n\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class TestUnicodeData {\n\t@Test\n\tpublic void testUnicodeGeneralCategoriesLatin() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Lu\").contains('X'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Lu\").contains('x'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Ll\").contains('x'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Ll\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"L\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"L\").contains('x'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"N\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Z\").contains(' '));\n\t}\n\n\t@Test\n\tpublic void testUnicodeGeneralCategoriesBMP() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Lu\").contains('\\u1E3A'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Lu\").contains('\\u1E3B'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Ll\").contains('\\u1E3B'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Ll\").contains('\\u1E3A'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"L\").contains('\\u1E3A'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"L\").contains('\\u1E3B'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"N\").contains('\\u1BB0'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"N\").contains('\\u1E3A'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Z\").contains('\\u2028'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Z\").contains('\\u1E3A'));\n\t}\n\n\t@Test\n\tpublic void testUnicodeGeneralCategoriesSMP() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Lu\").contains(0x1D5D4));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Lu\").contains(0x1D770));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Ll\").contains(0x1D770));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Ll\").contains(0x1D5D4));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"L\").contains(0x1D5D4));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"L\").contains(0x1D770));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"N\").contains(0x11C50));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"N\").contains(0x1D5D4));\n\t}\n\n\t@Test\n\tpublic void testUnicodeCategoryAliases() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Lowercase_Letter\").contains('x'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Lowercase_Letter\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Letter\").contains('x'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Letter\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Enclosing_Mark\").contains(0x20E2));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Enclosing_Mark\").contains('x'));\n\t}\n\n\t@Test\n\tpublic void testUnicodeBinaryProperties() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Emoji\").contains(0x1F4A9));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Emoji\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"alnum\").contains('9'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"alnum\").contains(0x1F4A9));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Dash\").contains('-'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Hex\").contains('D'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Hex\").contains('Q'));\n\t}\n\n\t@Test\n\tpublic void testUnicodeBinaryPropertyAliases() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Ideo\").contains('\\u611B'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Ideo\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Soft_Dotted\").contains('\\u0456'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Soft_Dotted\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Noncharacter_Code_Point\").contains('\\uFFFF'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"Noncharacter_Code_Point\").contains('X'));\n\t}\n\n\t@Test\n\tpublic void testUnicodeScripts() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Zyyy\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Latn\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Hani\").contains(0x4E04));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Cyrl\").contains(0x0404));\n\t}\n\n\t@Test\n\tpublic void testUnicodeScriptEquals() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Script=Zyyy\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Script=Latn\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Script=Hani\").contains(0x4E04));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Script=Cyrl\").contains(0x0404));\n\t}\n\n\t@Test\n\tpublic void testUnicodeScriptAliases() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Common\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Latin\").contains('X'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Han\").contains(0x4E04));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Cyrillic\").contains(0x0404));\n\t}\n\n\t@Test\n\tpublic void testUnicodeBlocks() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"InASCII\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"InCJK\").contains(0x4E04));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"InCyrillic\").contains(0x0404));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"InMisc_Pictographs\").contains(0x1F4A9));\n\t}\n\n\t@Test\n\tpublic void testUnicodeBlockEquals() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Block=ASCII\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Block=CJK\").contains(0x4E04));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Block=Cyrillic\").contains(0x0404));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Block=Misc_Pictographs\").contains(0x1F4A9));\n\t}\n\n\t@Test\n\tpublic void testUnicodeBlockAliases() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"InBasic_Latin\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"InMiscellaneous_Mathematical_Symbols_B\").contains(0x29BE));\n\t}\n\n\t@Test\n\tpublic void testEnumeratedPropertyEquals() {\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"Grapheme_Cluster_Break=E_Base\").contains(0x1F47E),\n\t\t\t\t\"U+1F47E ALIEN MONSTER is not an emoji modifier\");\n\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"Grapheme_Cluster_Break=E_Base\").contains(0x1038),\n\t\t\t\t\"U+1038 MYANMAR SIGN VISARGA is not a spacing mark\");\n\n\t\tassertTrue(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"East_Asian_Width=Ambiguous\").contains(0x00A1),\n\t\t\t\t\"U+00A1 INVERTED EXCLAMATION MARK has ambiguous East Asian Width\");\n\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"East_Asian_Width=Ambiguous\").contains(0x00A2),\n\t\t\t\t\"U+00A2 CENT SIGN does not have ambiguous East Asian Width\");\n\t}\n\n        @Test\n        public void extendedPictographic() {\n\t\tassertTrue(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"Extended_Pictographic\").contains(0x1F588),\n\t\t\t\t\"U+1F588 BLACK PUSHPIN is in Extended Pictographic\");\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"Extended_Pictographic\").contains('0'),\n\t\t\t\t\"0 is not in Extended Pictographic\");\n        }\n\n        @Test\n        public void emojiPresentation() {\n\t\tassertTrue(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"EmojiPresentation=EmojiDefault\").contains(0x1F4A9),\n\t\t\t\t\"U+1F4A9 PILE OF POO is in EmojiPresentation=EmojiDefault\");\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"EmojiPresentation=EmojiDefault\").contains('0'),\n\t\t\t\t\"0 is not in EmojiPresentation=EmojiDefault\");\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"EmojiPresentation=EmojiDefault\").contains('A'),\n\t\t\t\t\"A is not in EmojiPresentation=EmojiDefault\");\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"EmojiPresentation=TextDefault\").contains(0x1F4A9),\n\t\t\t\t\"U+1F4A9 PILE OF POO is not in EmojiPresentation=TextDefault\");\n\t\tassertTrue(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"EmojiPresentation=TextDefault\").contains('0'),\n\t\t\t\t\"0 is in EmojiPresentation=TextDefault\");\n\t\tassertFalse(\n\t\t\t\tUnicodeData.getPropertyCodePoints(\"EmojiPresentation=TextDefault\").contains('A'),\n\t\t\t\t\"A is not in EmojiPresentation=TextDefault\");\n        }\n\n\t@Test\n\tpublic void testPropertyCaseInsensitivity() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"l\").contains('x'));\n\t\tassertFalse(UnicodeData.getPropertyCodePoints(\"l\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"common\").contains('0'));\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"Alnum\").contains('0'));\n\t}\n\n\t@Test\n\tpublic void testPropertyDashSameAsUnderscore() {\n\t\tassertTrue(UnicodeData.getPropertyCodePoints(\"InLatin-1\").contains('\\u00F0'));\n\t}\n\n\t@Test\n\tpublic void modifyingUnicodeDataShouldThrow() {\n\t\tIllegalStateException exception = assertThrows(IllegalStateException.class, () -> UnicodeData.getPropertyCodePoints(\"L\").add(0x12345));\n\t\tassertEquals(\"can't alter readonly IntervalSet\", exception.getMessage());\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestUnicodeEscapes.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.codegen.UnicodeEscapes;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestUnicodeEscapes {\n\t@Test\n\tpublic void latinJavaEscape() {\n\t\tcheckUnicodeEscape(\"\\\\u0061\", 0x0061, \"Java\");\n\t}\n\n\t@Test\n\tpublic void latinPythonEscape() {\n\t\tcheckUnicodeEscape(\"\\\\u0061\", 0x0061, \"Python3\");\n\t}\n\n\t@Test\n\tpublic void latinSwiftEscape() {\n\t\tcheckUnicodeEscape(\"\\\\u{0061}\", 0x0061, \"Swift\");\n\t}\n\n\t@Test\n\tpublic void bmpJavaEscape() {\n\t\tcheckUnicodeEscape(\"\\\\uABCD\", 0xABCD, \"Java\");\n\t}\n\n\t@Test\n\tpublic void bmpPythonEscape() {\n\t\tcheckUnicodeEscape(\"\\\\uABCD\", 0xABCD, \"Python3\");\n\t}\n\n\t@Test\n\tpublic void bmpSwiftEscape() {\n\t\tcheckUnicodeEscape(\"\\\\u{ABCD}\", 0xABCD, \"Swift\");\n\t}\n\n\t@Test\n\tpublic void smpJavaEscape() {\n\t\tcheckUnicodeEscape(\"\\\\uD83D\\\\uDCA9\", 0x1F4A9, \"Java\");\n\t}\n\n\t@Test\n\tpublic void smpPythonEscape() {\n\t\tcheckUnicodeEscape(\"\\\\U0001F4A9\", 0x1F4A9, \"Python3\");\n\t}\n\n\t@Test\n\tpublic void smpSwiftEscape() {\n\t\tcheckUnicodeEscape(\"\\\\u{1F4A9}\", 0x1F4A9, \"Swift\");\n\t}\n\n\tprivate void checkUnicodeEscape(String expected, int input, String language) {\n\t\tassertEquals(expected, UnicodeEscapes.escapeCodePoint(input, language));\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestUnicodeGrammar.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.gui.Trees;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.CharStream;\nimport org.antlr.v4.runtime.CharStreams;\nimport org.antlr.v4.runtime.CommonTokenStream;\nimport org.antlr.v4.runtime.LexerInterpreter;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.GrammarParserInterpreter;\nimport org.junit.jupiter.api.Test;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\npublic class TestUnicodeGrammar {\n\t@Test\n\tpublic void unicodeBMPLiteralInGrammar() throws Exception {\n\t\tString grammarText =\n\t\t\t\"grammar Unicode;\\n\" +\n\t\t\t\"r : 'hello' WORLD;\\n\" +\n\t\t\t\"WORLD : ('world' | '\\\\u4E16\\\\u754C' | '\\\\u1000\\\\u1019\\\\u1039\\\\u1018\\\\u102C' );\\n\" +\n\t\t\t\"WS : [ \\\\t\\\\r\\\\n]+ -> skip;\\n\";\n\t\tString inputText = \"hello \\u4E16\\u754C\";\n\t\tassertEquals(\n\t\t\t\t\"(r:1 \" + inputText + \")\",\n\t\t\t\tparseTreeForGrammarWithInput(\n\t\t\t\t\t\tgrammarText,\n\t\t\t\t\t\t\"r\",\n\t\t\t\t\t\tinputText));\n\t}\n\n\t// TODO: This test cannot pass unless we change either the grammar\n\t// parser to decode surrogate pair literals to code points (which\n\t// would break existing clients) or to treat them as an\n\t// alternative:\n\t//\n\t// '\\\\uD83C\\\\uDF0D' -> ('\\\\u{1F30E}' | '\\\\uD83C\\\\uDF0D')\n\t//\n\t// but I worry that might cause parse ambiguity if we're not careful.\n\t//@Test\n\tpublic void unicodeSurrogatePairLiteralInGrammar() throws Exception {\n\t\tString grammarText =\n\t\t\t\"grammar Unicode;\\n\" +\n\t\t\t\"r : 'hello' WORLD;\\n\" +\n\t\t\t\"WORLD : ('\\\\uD83C\\\\uDF0D' | '\\\\uD83C\\\\uDF0E' | '\\\\uD83C\\\\uDF0F' );\\n\" +\n\t\t\t\"WS : [ \\\\t\\\\r\\\\n]+ -> skip;\\n\";\n\t\tString inputText = new StringBuilder(\"hello \")\n\t\t\t\t.appendCodePoint(0x1F30E)\n\t\t\t\t.toString();\n\t\tassertEquals(\n\t\t\t\t\"(r:1 \" + inputText + \")\",\n\t\t\t\tparseTreeForGrammarWithInput(\n\t\t\t\t\t\tgrammarText,\n\t\t\t\t\t\t\"r\",\n\t\t\t\t\t\tinputText));\n\t}\n\n\t@Test\n\tpublic void unicodeSMPLiteralInGrammar() throws Exception {\n\t\tString grammarText =\n\t\t\t\"grammar Unicode;\\n\" +\n\t\t\t\"r : 'hello' WORLD;\\n\" +\n\t\t\t\"WORLD : ('\\\\u{1F30D}' | '\\\\u{1F30E}' | '\\\\u{1F30F}' );\\n\" +\n\t\t\t\"WS : [ \\\\t\\\\r\\\\n]+ -> skip;\\n\";\n\t\tString inputText = new StringBuilder(\"hello \")\n\t\t\t\t.appendCodePoint(0x1F30E)\n\t\t\t\t.toString();\n\t\tassertEquals(\n\t\t\t\t\"(r:1 \" + inputText + \")\",\n\t\t\t\tparseTreeForGrammarWithInput(\n\t\t\t\t\t\tgrammarText,\n\t\t\t\t\t\t\"r\",\n\t\t\t\t\t\tinputText));\n\t}\n\n\t@Test\n\tpublic void unicodeSMPRangeInGrammar() throws Exception {\n\t\tString grammarText =\n\t\t\t\"grammar Unicode;\\n\" +\n\t\t\t\"r : 'hello' WORLD;\\n\" +\n\t\t\t\"WORLD : ('\\\\u{1F30D}'..'\\\\u{1F30F}' );\\n\" +\n\t\t\t\"WS : [ \\\\t\\\\r\\\\n]+ -> skip;\\n\";\n\t\tString inputText = new StringBuilder(\"hello \")\n\t\t\t\t.appendCodePoint(0x1F30E)\n\t\t\t\t.toString();\n\t\tassertEquals(\n\t\t\t\t\"(r:1 \" + inputText + \")\",\n\t\t\t\tparseTreeForGrammarWithInput(\n\t\t\t\t\t\tgrammarText,\n\t\t\t\t\t\t\"r\",\n\t\t\t\t\t\tinputText));\n\t}\n\n\t@Test\n\tpublic void matchingDanglingSurrogateInInput() throws Exception {\n\t\tString grammarText =\n\t\t\t\"grammar Unicode;\\n\" +\n\t\t\t\"r : 'hello' WORLD;\\n\" +\n\t\t\t\"WORLD : ('\\\\uD83C' | '\\\\uD83D' | '\\\\uD83E' );\\n\" +\n\t\t\t\"WS : [ \\\\t\\\\r\\\\n]+ -> skip;\\n\";\n\t\tString inputText = \"hello \\uD83C\";\n\t\tassertEquals(\n\t\t\t\t\"(r:1 \" + inputText + \")\",\n\t\t\t\tparseTreeForGrammarWithInput(\n\t\t\t\t\t\tgrammarText,\n\t\t\t\t\t\t\"r\",\n\t\t\t\t\t\tinputText));\n\t}\n\n\t@Test\n\tpublic void binaryGrammar() throws Exception {\n\t\tString grammarText =\n\t\t\t\"grammar Binary;\\n\" +\n\t\t\t\"r : HEADER PACKET+ FOOTER;\\n\" +\n\t\t\t\"HEADER : '\\\\u0002\\\\u0000\\\\u0001\\\\u0007';\\n\" +\n\t\t\t\"PACKET : '\\\\u00D0' ('\\\\u00D1' | '\\\\u00D2' | '\\\\u00D3') +;\\n\" +\n\t\t\t\"FOOTER : '\\\\u00FF';\\n\";\n\t\tbyte[] toParse = new byte[] {\n\t\t\t\t(byte)0x02, (byte)0x00, (byte)0x01, (byte)0x07,\n\t\t\t\t(byte)0xD0, (byte)0xD2, (byte)0xD2, (byte)0xD3, (byte)0xD3, (byte)0xD3,\n\t\t\t\t(byte)0xD0, (byte)0xD3, (byte)0xD3, (byte)0xD1,\n\t\t\t\t(byte)0xFF\n\t\t};\n\t\tCharStream charStream;\n\t\ttry (ByteArrayInputStream is = new ByteArrayInputStream(toParse);\n\t\t     // Note we use ISO_8859_1 to treat all byte values as Unicode \"characters\" from\n\t\t     // U+0000 to U+00FF.\n\t\t     InputStreamReader isr = new InputStreamReader(is, StandardCharsets.ISO_8859_1)) {\n\t\t\tcharStream = new ANTLRInputStream(isr);\n\t\t}\n\t\tGrammar grammar = new Grammar(grammarText);\n\t\tLexerInterpreter lexEngine = grammar.createLexerInterpreter(charStream);\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\tGrammarParserInterpreter parser = grammar.createGrammarParserInterpreter(tokens);\n\t\tParseTree parseTree = parser.parse(grammar.rules.get(\"r\").index);\n\t\tInterpreterTreeTextProvider nodeTextProvider =\n\t\t\t\tnew InterpreterTreeTextProvider(grammar.getRuleNames());\n\t\tString result = Trees.toStringTree(parseTree, nodeTextProvider);\n\n\t\tassertEquals(\n\t\t\t\t\"(r:1 \\u0002\\u0000\\u0001\\u0007 \\u00D0\\u00D2\\u00D2\\u00D3\\u00D3\\u00D3 \\u00D0\\u00D3\\u00D3\\u00D1 \\u00FF)\",\n\t\t\t\tresult);\n\t}\n\n\tprivate static String parseTreeForGrammarWithInput(\n\t\t\tString grammarText,\n\t\t\tString rootRule,\n\t\t\tString inputText) throws Exception {\n\t\tGrammar grammar = new Grammar(grammarText);\n\t\tLexerInterpreter lexEngine = grammar.createLexerInterpreter(\n\t\t\t\tCharStreams.fromString(inputText));\n\t\tCommonTokenStream tokens = new CommonTokenStream(lexEngine);\n\t\tGrammarParserInterpreter parser = grammar.createGrammarParserInterpreter(tokens);\n\t\tParseTree parseTree = parser.parse(grammar.rules.get(rootRule).index);\n\t\tInterpreterTreeTextProvider nodeTextProvider =\n\t\t\t\tnew InterpreterTreeTextProvider(grammar.getRuleNames());\n\t\treturn Trees.toStringTree(parseTree, nodeTextProvider);\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestUtils.java",
    "content": "package org.antlr.v4.test.tool;\n\nimport org.antlr.runtime.Token;\nimport org.antlr.v4.misc.Utils;\nimport org.antlr.v4.tool.ast.GrammarAST;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\npublic class TestUtils {\n\t@Test\n\tpublic void testStripFileExtension() {\n\t\tassertNull(Utils.stripFileExtension(null));\n\t\tassertEquals(\"foo\", Utils.stripFileExtension(\"foo\"));\n\t\tassertEquals(\"foo\", Utils.stripFileExtension(\"foo.txt\"));\n\t}\n\n\t@Test\n\tpublic void testJoin() {\n\t\tassertEquals(\"foobbar\",\n\t\t\tUtils.join(new String[]{\"foo\", \"bar\"}, \"b\"));\n\t\tassertEquals(\"foo,bar\",\n\t\t\tUtils.join(new String[]{\"foo\", \"bar\"}, \",\"));\n\t}\n\n\t@Test\n\tpublic void testSortLinesInString() {\n\t\tassertEquals(\"bar\\nbaz\\nfoo\\n\",\n\t\t\tUtils.sortLinesInString(\"foo\\nbar\\nbaz\"));\n\t}\n\n\t@Test\n\tpublic void testNodesToStrings() {\n\t\tArrayList<GrammarAST> values = new ArrayList<>();\n\t\tvalues.add(new GrammarAST(Token.EOR_TOKEN_TYPE));\n\t\tvalues.add(new GrammarAST(Token.DOWN));\n\t\tvalues.add(new GrammarAST(Token.UP));\n\n\t\tassertNull(Utils.nodesToStrings(null));\n\t\tassertNotNull(Utils.nodesToStrings(values));\n\t}\n\n\t@Test\n\tpublic void testCapitalize() {\n\t\tassertEquals(\"Foo\", Utils.capitalize(\"foo\"));\n\t}\n\n\t@Test\n\tpublic void testDecapitalize() {\n\t\tassertEquals(\"fOO\", Utils.decapitalize(\"FOO\"));\n\t}\n\n\t@Test\n\tpublic void testSelect() {\n\t\tArrayList<String> strings = new ArrayList<>();\n\t\tstrings.add(\"foo\");\n\t\tstrings.add(\"bar\");\n\n\t\tUtils.Func1<String, String> func1 = new Utils.Func1() {\n\t\t\t@Override\n\t\t\tpublic Object exec(Object arg1) {\n\t\t\t\treturn \"baz\";\n\t\t\t}\n\t\t};\n\n\t\tArrayList<String> retval = new ArrayList<>();\n\t\tretval.add(\"baz\");\n\t\tretval.add(\"baz\");\n\n\t\tassertEquals(retval, Utils.select(strings, func1));\n\t\tassertNull(Utils.select(null, null));\n\t}\n\n\t@Test\n\tpublic void testFind() {\n\t\tArrayList<String> strings = new ArrayList<>();\n\t\tstrings.add(\"foo\");\n\t\tstrings.add(\"bar\");\n\t\tassertEquals(\"foo\", Utils.find(strings, String.class));\n\n\t\tassertNull(Utils.find(new ArrayList<>(), String.class));\n\t}\n\n\t@Test\n\tpublic void testIndexOf() {\n\t\tArrayList<String> strings = new ArrayList<>();\n\t\tstrings.add(\"foo\");\n\t\tstrings.add(\"bar\");\n\t\tUtils.Filter filter = new Utils.Filter() {\n\t\t\t@Override\n\t\t\tpublic boolean select(Object o) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\t\tassertEquals(0, Utils.indexOf(strings, filter));\n\t\tassertEquals(-1, Utils.indexOf(new ArrayList<>(), null));\n\t}\n\n\t@Test\n\tpublic void testLastIndexOf() {\n\t\tArrayList<String> strings = new ArrayList<>();\n\t\tstrings.add(\"foo\");\n\t\tstrings.add(\"bar\");\n\t\tUtils.Filter filter = new Utils.Filter() {\n\t\t\t@Override\n\t\t\tpublic boolean select(Object o) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\t\tassertEquals(1, Utils.lastIndexOf(strings, filter));\n\t\tassertEquals(-1, Utils.lastIndexOf(new ArrayList<>(), null));\n\t}\n\n\t@Test\n\tpublic void testSetSize() {\n\t\tArrayList<String> strings = new ArrayList<>();\n\t\tstrings.add(\"foo\");\n\t\tstrings.add(\"bar\");\n\t\tstrings.add(\"baz\");\n\t\tassertEquals(3, strings.size());\n\n\t\tUtils.setSize(strings, 2);\n\t\tassertEquals(2, strings.size());\n\n\t\tUtils.setSize(strings, 4);\n\t\tassertEquals(4, strings.size());\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestVocabulary.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.Vocabulary;\nimport org.antlr.v4.runtime.VocabularyImpl;\nimport org.junit.jupiter.api.Test;\n\nimport static org.junit.jupiter.api.Assertions.*;\n\n/**\n *\n * @author Sam Harwell\n */\npublic class TestVocabulary {\n\t@Test\n\tpublic void testEmptyVocabulary() {\n\t\tassertNotNull(VocabularyImpl.EMPTY_VOCABULARY);\n\t\tassertEquals(\"EOF\", VocabularyImpl.EMPTY_VOCABULARY.getSymbolicName(Token.EOF));\n\t\tassertEquals(\"0\", VocabularyImpl.EMPTY_VOCABULARY.getDisplayName(Token.INVALID_TYPE));\n\t}\n\n\t@Test\n\tpublic void testVocabularyFromTokenNames() {\n\t\tString[] tokenNames = {\n\t\t\t\"<INVALID>\",\n\t\t\t\"TOKEN_REF\", \"RULE_REF\", \"'//'\", \"'/'\", \"'*'\", \"'!'\", \"ID\", \"STRING\"\n\t\t};\n\n\t\tVocabulary vocabulary = VocabularyImpl.fromTokenNames(tokenNames);\n\t\tassertNotNull(vocabulary);\n\t\tassertEquals(\"EOF\", vocabulary.getSymbolicName(Token.EOF));\n\t\tfor (int i = 0; i < tokenNames.length; i++) {\n\t\t\tassertEquals(tokenNames[i], vocabulary.getDisplayName(i));\n\n\t\t\tif (tokenNames[i].startsWith(\"'\")) {\n\t\t\t\tassertEquals(tokenNames[i], vocabulary.getLiteralName(i));\n\t\t\t\tassertNull(vocabulary.getSymbolicName(i));\n\t\t\t}\n\t\t\telse if (Character.isUpperCase(tokenNames[i].charAt(0))) {\n\t\t\t\tassertNull(vocabulary.getLiteralName(i));\n\t\t\t\tassertEquals(tokenNames[i], vocabulary.getSymbolicName(i));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tassertNull(vocabulary.getLiteralName(i));\n\t\t\t\tassertNull(vocabulary.getSymbolicName(i));\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/TestXPath.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.runtime.Parser;\nimport org.antlr.v4.runtime.RuleContext;\nimport org.antlr.v4.runtime.misc.Pair;\nimport org.antlr.v4.runtime.tree.ParseTree;\nimport org.antlr.v4.runtime.tree.TerminalNode;\nimport org.antlr.v4.runtime.tree.xpath.XPath;\nimport org.antlr.v4.test.runtime.RunOptions;\nimport org.antlr.v4.test.runtime.Stage;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.states.JavaCompiledState;\nimport org.antlr.v4.test.runtime.states.JavaExecutedState;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport static org.antlr.v4.test.tool.ToolTestUtils.createOptionsForJavaToolTests;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\n\npublic class TestXPath {\n\tpublic static final String grammar =\n\t\t\"grammar Expr;\\n\" +\n\t\t\"prog:   func+ ;\\n\" +\n\t\t\"func:  'def' ID '(' arg (',' arg)* ')' body ;\\n\" +\n\t\t\"body:  '{' stat+ '}' ;\\n\" +\n\t\t\"arg :  ID ;\\n\" +\n\t\t\"stat:   expr ';'                 # printExpr\\n\" +\n\t\t\"    |   ID '=' expr ';'          # assign\\n\" +\n\t\t\"    |   'return' expr ';'        # ret\\n\" +\n\t\t\"    |   ';'                      # blank\\n\" +\n\t\t\"    ;\\n\" +\n\t\t\"expr:   expr ('*'|'/') expr      # MulDiv\\n\" +\n\t\t\"    |   expr ('+'|'-') expr      # AddSub\\n\" +\n\t\t\"    |   primary                  # prim\\n\" +\n\t\t\"    ;\\n\" +\n\t\t\"primary\" +\n\t\t\"    :   INT                      # int\\n\" +\n\t\t\"    |   ID                       # id\\n\" +\n\t\t\"    |   '(' expr ')'             # parens\\n\" +\n\t\t\"\t ;\" +\n\t\t\"\\n\" +\n\t\t\"MUL :   '*' ; // assigns token name to '*' used above in grammar\\n\" +\n\t\t\"DIV :   '/' ;\\n\" +\n\t\t\"ADD :   '+' ;\\n\" +\n\t\t\"SUB :   '-' ;\\n\" +\n\t\t\"RETURN : 'return' ;\\n\" +\n\t\t\"ID  :   [a-zA-Z]+ ;      // match identifiers\\n\" +\n\t\t\"INT :   [0-9]+ ;         // match integers\\n\" +\n\t\t\"NEWLINE:'\\\\r'? '\\\\n' -> skip;     // return newlines to parser (is end-statement signal)\\n\" +\n\t\t\"WS  :   [ \\\\t]+ -> skip ; // toss out whitespace\\n\";\n\tpublic static final String SAMPLE_PROGRAM =\n\t\t\t\"def f(x,y) { x = 3+4; y; ; }\\n\" +\n\t\t\t\"def g(x) { return 1+2*x; }\\n\";\n\n\t@Test public void testValidPaths() throws Exception {\n\t\tString xpath[] = {\n\t\t\t\"/prog/func\",\t\t// all funcs under prog at root\n\t\t\t\"/prog/*\",\t\t\t// all children of prog at root\n\t\t\t\"/*/func\",\t\t\t// all func kids of any root node\n\t\t\t\"prog\",\t\t\t\t// prog must be root node\n\t\t\t\"/prog\",\t\t\t// prog must be root node\n\t\t\t\"/*\",\t\t\t\t// any root\n\t\t\t\"*\",\t\t\t\t// any root\n\t\t\t\"//ID\",\t\t\t\t// any ID in tree\n\t\t\t\"//expr/primary/ID\",// any ID child of a primary under any expr\n\t\t\t\"//body//ID\",\t\t// any ID under a body\n\t\t\t\"//'return'\",\t\t// any 'return' literal in tree, matched by literal name\n\t\t\t\"//RETURN\",\t\t\t// any 'return' literal in tree, matched by symbolic name\n\t\t\t\"//primary/*\",\t\t// all kids of any primary\n\t\t\t\"//func/*/stat\",\t// all stat nodes grandkids of any func node\n\t\t\t\"/prog/func/'def'\",\t// all def literal kids of func kid of prog\n\t\t\t\"//stat/';'\",\t\t// all ';' under any stat node\n\t\t\t\"//expr/primary/!ID\",\t// anything but ID under primary under any expr node\n\t\t\t\"//expr/!primary\",\t// anything but primary under any expr node\n\t\t\t\"//!*\",\t\t\t\t// nothing anywhere\n\t\t\t\"/!*\",\t\t\t\t// nothing at root\n\t\t\t\"//expr//ID\",\t\t// any ID under any expression (tests antlr/antlr4#370)\n\t\t};\n\t\tString expected[] = {\n\t\t\t\"[func, func]\",\n\t\t\t\"[func, func]\",\n\t\t\t\"[func, func]\",\n\t\t\t\"[prog]\",\n\t\t\t\"[prog]\",\n\t\t\t\"[prog]\",\n\t\t\t\"[prog]\",\n\t\t\t\"[f, x, y, x, y, g, x, x]\",\n\t\t\t\"[y, x]\",\n\t\t\t\"[x, y, x]\",\n\t\t\t\"[return]\",\n\t\t\t\"[return]\",\n\t\t\t\"[3, 4, y, 1, 2, x]\",\n\t\t\t\"[stat, stat, stat, stat]\",\n\t\t\t\"[def, def]\",\n\t\t\t\"[;, ;, ;, ;]\",\n\t\t\t\"[3, 4, 1, 2]\",\n\t\t\t\"[expr, expr, expr, expr, expr, expr]\",\n\t\t\t\"[]\",\n\t\t\t\"[]\",\n\t\t\t\"[y, x]\",\n\t\t};\n\n\t\tfor (int i=0; i<xpath.length; i++) {\n\t\t\tList<String> nodes = getNodeStrings(\"Expr.g4\", grammar, SAMPLE_PROGRAM, xpath[i], \"prog\", \"ExprParser\", \"ExprLexer\");\n\t\t\tString result = nodes.toString();\n\t\t\tassertEquals(expected[i], result, \"path \"+xpath[i]+\" failed\");\n\t\t}\n\t}\n\n\t@Test public void testWeirdChar() throws Exception {\n\t\tString path = \"&\";\n\t\tString expected = \"Invalid tokens or characters at index 0 in path '&'\";\n\n\t\ttestError(\"Expr.g4\", grammar, SAMPLE_PROGRAM, path, expected, \"prog\", \"ExprParser\", \"ExprLexer\");\n\t}\n\n\t@Test public void testWeirdChar2() throws Exception {\n\t\tString path = \"//w&e/\";\n\t\tString expected = \"Invalid tokens or characters at index 3 in path '//w&e/'\";\n\n\t\ttestError(\"Expr.g4\", grammar, SAMPLE_PROGRAM, path, expected, \"prog\", \"ExprParser\", \"ExprLexer\");\n\t}\n\n\t@Test public void testBadSyntax() throws Exception {\n\t\tString path = \"///\";\n\t\tString expected = \"/ at index 2 isn't a valid rule name\";\n\n\t\ttestError(\"Expr.g4\", grammar, SAMPLE_PROGRAM, path, expected, \"prog\", \"ExprParser\", \"ExprLexer\");\n\t}\n\n\t@Test public void testMissingWordAtEnd() throws Exception {\n\t\tString path = \"//\";\n\t\tString expected = \"Missing path element at end of path\";\n\n\t\ttestError(\"Expr.g4\", grammar, SAMPLE_PROGRAM, path, expected, \"prog\", \"ExprParser\", \"ExprLexer\");\n\t}\n\n\t@Test public void testBadTokenName() throws Exception {\n\t\tString path = \"//Ick\";\n\t\tString expected = \"Ick at index 2 isn't a valid token name\";\n\n\t\ttestError(\"Expr.g4\", grammar, SAMPLE_PROGRAM, path, expected, \"prog\", \"ExprParser\", \"ExprLexer\");\n\t}\n\n\t@Test public void testBadRuleName() throws Exception {\n\t\tString path = \"/prog/ick\";\n\t\tString expected = \"ick at index 6 isn't a valid rule name\";\n\n\t\ttestError(\"Expr.g4\", grammar, SAMPLE_PROGRAM, path, expected, \"prog\", \"ExprParser\", \"ExprLexer\");\n\t}\n\n\tprivate void testError(String grammarFileName, String grammar, String input, String xpath, String expected,\n\t\t\t\t\t\t\t String startRuleName, String parserName, String lexerName)\n\t\tthrows Exception\n\t{\n\t\tIllegalArgumentException e = null;\n\t\ttry {\n\t\t\tcompileAndExtract(grammarFileName, grammar, input, xpath, startRuleName, parserName, lexerName);\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\te = iae;\n\t\t}\n\t\tassertNotNull(e);\n\t\tassertEquals(expected, e.getMessage());\n\t}\n\n\tprivate List<String> getNodeStrings(String grammarFileName, String grammar, String input, String xpath,\n\t\t\t\t\t\t\t\t\t   String startRuleName, String parserName, String lexerName)\n\t\tthrows Exception\n\t{\n\t\tPair<String[], Collection<ParseTree>> result = compileAndExtract(\n\t\t\t\tgrammarFileName, grammar, input, xpath, startRuleName, parserName, lexerName);\n\n\t\tList<String> nodes = new ArrayList<>();\n\t\tfor (ParseTree t : result.b) {\n\t\t\tif ( t instanceof RuleContext) {\n\t\t\t\tRuleContext r = (RuleContext)t;\n\t\t\t\tnodes.add(result.a[r.getRuleIndex()]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tTerminalNode token = (TerminalNode)t;\n\t\t\t\tnodes.add(token.getText());\n\t\t\t}\n\t\t}\n\t\treturn nodes;\n\t}\n\n\tprivate Pair<String[], Collection<ParseTree>> compileAndExtract(String grammarFileName, String grammar,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tString input, String xpath, String startRuleName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tString parserName, String lexerName\n\t) throws Exception {\n\t\tRunOptions runOptions = createOptionsForJavaToolTests(grammarFileName, grammar, parserName, lexerName,\n\t\t\t\tfalse, false, startRuleName, input,\n\t\t\t\tfalse, false, Stage.Execute);\n\t\ttry (JavaRunner runner = new JavaRunner()) {\n\t\t\tJavaExecutedState executedState = (JavaExecutedState)runner.run(runOptions);\n\t\t\tJavaCompiledState compiledState = (JavaCompiledState)executedState.previousState;\n\t\t\tParser parser = compiledState.initializeLexerAndParser(input).b;\n\t\t\tCollection<ParseTree> found = XPath.findAll(executedState.parseTree, xpath, parser);\n\n\t\t\treturn new Pair<>(parser.getRuleNames(), found);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tool-testsuite/test/org/antlr/v4/test/tool/ToolTestUtils.java",
    "content": "/*\n * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.\n * Use of this file is governed by the BSD 3-clause license that\n * can be found in the LICENSE.txt file in the project root.\n */\n\npackage org.antlr.v4.test.tool;\n\nimport org.antlr.v4.Tool;\nimport org.antlr.v4.automata.LexerATNFactory;\nimport org.antlr.v4.automata.ParserATNFactory;\nimport org.antlr.v4.runtime.ANTLRInputStream;\nimport org.antlr.v4.runtime.Lexer;\nimport org.antlr.v4.runtime.Token;\nimport org.antlr.v4.runtime.atn.*;\nimport org.antlr.v4.runtime.misc.IntegerList;\nimport org.antlr.v4.semantics.SemanticPipeline;\nimport org.antlr.v4.test.runtime.*;\nimport org.antlr.v4.test.runtime.java.JavaRunner;\nimport org.antlr.v4.test.runtime.states.ExecutedState;\nimport org.antlr.v4.test.runtime.states.State;\nimport org.antlr.v4.tool.Grammar;\nimport org.antlr.v4.tool.LexerGrammar;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.List;\n\nimport static org.antlr.v4.test.runtime.FileUtils.deleteDirectory;\nimport static org.antlr.v4.test.runtime.Generator.antlrOnString;\nimport static org.antlr.v4.test.runtime.RuntimeTestUtils.TempDirectory;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.fail;\n\npublic class ToolTestUtils {\n\tpublic static ExecutedState execLexer(String grammarFileName, String grammarStr, String lexerName, String input) {\n\t\treturn execLexer(grammarFileName, grammarStr, lexerName, input, null, false);\n\t}\n\n\tpublic static ExecutedState execLexer(String grammarFileName, String grammarStr, String lexerName, String input,\n\t\t\t\t\t\t\t\t\t  Path tempDir, boolean saveTestDir) {\n\t\treturn execRecognizer(grammarFileName, grammarStr, null, lexerName,\n\t\t\t\tnull, input, false, tempDir, saveTestDir);\n\t}\n\n\tpublic static ExecutedState execParser(String grammarFileName, String grammarStr,\n\t\t\t\t\t\t\t\t\t   String parserName, String lexerName, String startRuleName,\n\t\t\t\t\t\t\t\t\t   String input, boolean showDiagnosticErrors\n\t) {\n\t\treturn execParser(grammarFileName, grammarStr, parserName, lexerName, startRuleName,\n\t\t\t\tinput, showDiagnosticErrors, null);\n\t}\n\n\tpublic static ExecutedState execParser(String grammarFileName, String grammarStr,\n\t\t\t\t\t\t\t\t\tString parserName, String lexerName, String startRuleName,\n\t\t\t\t\t\t\t\t\tString input, boolean showDiagnosticErrors, Path workingDir\n\t) {\n\t\treturn execRecognizer(grammarFileName, grammarStr, parserName, lexerName,\n\t\t\t\tstartRuleName, input, showDiagnosticErrors, workingDir, false);\n\t}\n\n\tprivate static ExecutedState execRecognizer(String grammarFileName, String grammarStr,\n\t\t\t\t\t\t\t\t\t\t String parserName, String lexerName, String startRuleName,\n\t\t\t\t\t\t\t\t\t\t String input, boolean showDiagnosticErrors,\n\t\t\t\t\t\t\t\t\t\t Path workingDir, boolean saveTestDir) {\n\t\tRunOptions runOptions = createOptionsForJavaToolTests(grammarFileName, grammarStr, parserName, lexerName,\n\t\t\t\tfalse, true, startRuleName, input,\n\t\t\t\tfalse, showDiagnosticErrors, Stage.Execute);\n\t\ttry (JavaRunner runner = new JavaRunner(workingDir, saveTestDir)) {\n\t\t\tState result = runner.run(runOptions);\n\t\t\tif (!(result instanceof ExecutedState)) {\n\t\t\t\tfail(result.getErrorMessage());\n\t\t\t}\n\t\t\treturn  (ExecutedState) result;\n\t\t}\n\t}\n\n\tpublic static RunOptions createOptionsForJavaToolTests(\n\t\t\tString grammarFileName, String grammarStr, String parserName, String lexerName,\n\t\t\tboolean useListener, boolean useVisitor, String startRuleName,\n\t\t\tString input, boolean profile, boolean showDiagnosticErrors,\n\t\t\tStage endStage\n\t) {\n\t\treturn new RunOptions(grammarFileName, grammarStr, parserName, lexerName, useListener, useVisitor, startRuleName,\n\t\t\t\tinput, profile, showDiagnosticErrors, false, false, endStage, \"Java\",\n\t\t\t\tJavaRunner.runtimeTestParserName, PredictionMode.LL, true);\n\t}\n\n\tpublic static void testErrors(String[] pairs, boolean printTree) {\n\t\tfor (int i = 0; i < pairs.length; i += 2) {\n\t\t\tString grammarStr = pairs[i];\n\t\t\tString expect = pairs[i + 1];\n\n\t\t\tString[] lines = grammarStr.split(\"\\n\");\n\t\t\tString fileName = getFilenameFromFirstLineOfGrammar(lines[0]);\n\n\t\t\tString tempDirName = \"AntlrTestErrors-\" + Thread.currentThread().getName() + \"-\" + System.currentTimeMillis();\n\t\t\tString tempTestDir = Paths.get(TempDirectory, tempDirName).toString();\n\n\t\t\ttry {\n\t\t\t\tErrorQueue equeue = antlrOnString(tempTestDir, null, fileName, grammarStr, false);\n\n\t\t\t\tString actual = equeue.toString(true);\n\t\t\t\tactual = actual.replace(tempTestDir + File.separator, \"\");\n\t\t\t\tString msg = grammarStr;\n\t\t\t\tmsg = msg.replace(\"\\n\", \"\\\\n\");\n\t\t\t\tmsg = msg.replace(\"\\r\", \"\\\\r\");\n\t\t\t\tmsg = msg.replace(\"\\t\", \"\\\\t\");\n\n\t\t\t\tassertEquals(expect, actual, \"error in: \" + msg);\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\ttry {\n\t\t\t\t\tdeleteDirectory(new File(tempTestDir));\n\t\t\t\t} catch (IOException ignored) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static String getFilenameFromFirstLineOfGrammar(String line) {\n\t\tString fileName = \"A\" + Tool.GRAMMAR_EXTENSION;\n\t\tint grIndex = line.lastIndexOf(\"grammar\");\n\t\tint semi = line.lastIndexOf(';');\n\t\tif ( grIndex>=0 && semi>=0 ) {\n\t\t\tint space = line.indexOf(' ', grIndex);\n\t\t\tfileName = line.substring(space+1, semi)+Tool.GRAMMAR_EXTENSION;\n\t\t}\n\t\tif ( fileName.length()==Tool.GRAMMAR_EXTENSION.length() ) fileName = \"A\" + Tool.GRAMMAR_EXTENSION;\n\t\treturn fileName;\n\t}\n\n\tpublic static List<String> realElements(List<String> elements) {\n\t\treturn elements.subList(Token.MIN_USER_TOKEN_TYPE, elements.size());\n\t}\n\n\tpublic static String load(String fileName)\n\t\t\tthrows IOException {\n\t\tif ( fileName==null ) {\n\t\t\treturn null;\n\t\t}\n\n\t\tString fullFileName = ToolTestUtils.class.getPackage().getName().replace('.', '/')+'/'+fileName;\n\t\tint size = 65000;\n\t\tInputStream fis = ToolTestUtils.class.getClassLoader().getResourceAsStream(fullFileName);\n\t\ttry (InputStreamReader isr = new InputStreamReader(fis)) {\n\t\t\tchar[] data = new char[size];\n\t\t\tint n = isr.read(data);\n\t\t\treturn new String(data, 0, n);\n\t\t}\n\t}\n\n\tpublic static ATN createATN(Grammar g, boolean useSerializer) {\n\t\tif ( g.atn==null ) {\n\t\t\tsemanticProcess(g);\n\t\t\tassertEquals(0, g.tool.getNumErrors());\n\n\t\t\tParserATNFactory f = g.isLexer() ? new LexerATNFactory((LexerGrammar) g) : new ParserATNFactory(g);\n\n\t\t\tg.atn = f.createATN();\n\t\t\tassertEquals(0, g.tool.getNumErrors());\n\t\t}\n\n\t\tATN atn = g.atn;\n\t\tif ( useSerializer ) {\n\t\t\t// sets some flags in ATN\n\t\t\tIntegerList serialized = ATNSerializer.getSerialized(atn);\n\t\t\treturn new ATNDeserializer().deserialize(serialized.toArray());\n\t\t}\n\n\t\treturn atn;\n\t}\n\n\tpublic static void semanticProcess(Grammar g) {\n\t\tif ( g.ast!=null && !g.ast.hasErrors ) {\n//\t\t\tSystem.out.println(g.ast.toStringTree());\n\t\t\tTool antlr = new Tool();\n\t\t\tSemanticPipeline sem = new SemanticPipeline(g);\n\t\t\tsem.process();\n\t\t\tif ( g.getImportedGrammars()!=null ) { // process imported grammars (if any)\n\t\t\t\tfor (Grammar imp : g.getImportedGrammars()) {\n\t\t\t\t\tantlr.processNonCombinedGrammar(imp, false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static IntegerList getTokenTypesViaATN(String input, LexerATNSimulator lexerATN) {\n\t\tANTLRInputStream in = new ANTLRInputStream(input);\n\t\tIntegerList tokenTypes = new IntegerList();\n\t\tint ttype;\n\t\tdo {\n\t\t\tttype = lexerATN.match(in, Lexer.DEFAULT_MODE);\n\t\t\ttokenTypes.add(ttype);\n\t\t} while ( ttype!= Token.EOF );\n\t\treturn tokenTypes;\n\t}\n}\n"
  }
]